Skip to content

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

Data Apps Beta (#74840)

Timofey Kachalov806e4b756c35
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 4f1b8b31c52..02e7083f8bc 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -1303,7 +1303,8 @@
metabase.metabot.core
metabase.metabot.init
metabase.metabot.self
- metabase.metabot.settings}
+ metabase.metabot.settings
+ metabase.metabot.tools.entity-details}
:friends #{agent-api
enterprise/metabot
enterprise/metabot-analytics
@@ -2505,6 +2506,28 @@
:model/TransformRun
:model/TransformTag}}
+ typed-schemas
+ {:team "Embedding"
+ :api #{metabase.typed-schemas.api}
+ :uses #{actions
+ api
+ collections
+ lib
+ lib-be
+ metabot
+ metrics
+ models
+ system
+ types
+ util}
+ :model-imports #{:model/Action
+ :model/Card
+ :model/Collection
+ :model/Database
+ :model/Field
+ :model/Measure
+ :model/Table}}
+
types
{:team "Querying Platform"
:api #{metabase.types.core
@@ -3072,6 +3095,17 @@
:api #{}
:uses #{premium-features}}
+ enterprise/data-apps
+ {:team "Gadget"
+ :api #{metabase-enterprise.data-apps.api
+ metabase-enterprise.data-apps.init
+ metabase-enterprise.data-apps.sync}
+ :uses #{api
+ models
+ premium-features
+ settings
+ util}}
+
enterprise/data-complexity-score
{:team "Metabot"
:api #{metabase-enterprise.data-complexity-score.api
@@ -3420,6 +3454,7 @@
task
task-history
util
+ enterprise/data-apps
enterprise/serialization
enterprise/transforms-python}
:model-exports #{:model/RemoteSyncTask}
diff --git a/.gitignore b/.gitignore
index 5ca874c6bbd..a61caada9ec 100644
--- a/.gitignore
+++ b/.gitignore
@@ -89,6 +89,7 @@ cypress.env.json
/resources/frontend_client/app/embedding-sdk.js.map
/resources/frontend_client/app/embedding-sdk/
/resources/frontend_client/tmp-*/
+/resources/frontend_client/data-app.html
/resources/frontend_client/embed.html
/resources/frontend_client/embed-sdk.html
/resources/frontend_client/embed-mcp.html
diff --git a/.typedoc/typedoc-plugin-not-exported.js b/.typedoc/typedoc-plugin-not-exported.js
new file mode 100644
index 00000000000..381784a360a
--- /dev/null
+++ b/.typedoc/typedoc-plugin-not-exported.js
@@ -0,0 +1,27 @@
+import { Comment, Converter } from "typedoc";
+
+const TAG = "@notExported";
+
+export function load(app) {
+ app.options.getDeclaration("blockTags").defaultValue?.push?.(TAG);
+
+ app.converter.on(Converter.EVENT_RESOLVE_END, (context) => {
+ const project = context.project;
+ const intentional = new Set(app.options.getValue("intentionallyNotExported"));
+
+ for (const id in project.reflections) {
+ const ref = project.reflections[id];
+ const tags = ref.comment?.blockTags ?? [];
+ for (const tag of tags) {
+ if (tag.tag === TAG) {
+ const name = Comment.combineDisplayParts(tag.content).trim();
+ if (name) {
+ intentional.add(name);
+ }
+ }
+ }
+ }
+
+ app.options.setValue("intentionallyNotExported", [...intentional]);
+ });
+}
diff --git a/.typedoc/typedoc.common.config.js b/.typedoc/typedoc.common.config.js
index 836818f502f..a828880c48c 100644
--- a/.typedoc/typedoc.common.config.js
+++ b/.typedoc/typedoc.common.config.js
@@ -10,6 +10,7 @@ const config = {
"typedoc-plugin-dt-links",
"typedoc-plugin-redirect",
"./typedoc-plugin-replace-text.js",
+ "./typedoc-plugin-not-exported.js",
],
entryPoints: ["../resources/embedding-sdk/dist/index.d.ts"],
router: "structure",
diff --git a/bin/embedding-sdk/fixup-types-after-compilation.js b/bin/embedding-sdk/fixup-types-after-compilation.js
index 367b8b24e91..9b428614074 100644
--- a/bin/embedding-sdk/fixup-types-after-compilation.js
+++ b/bin/embedding-sdk/fixup-types-after-compilation.js
@@ -1,12 +1,15 @@
#!/usr/bin/env node
/* eslint-env node */
-/* eslint-disable import/no-commonjs, import/order, no-console */
+/* eslint-disable import/order */
const fs = require("fs");
const path = require("path");
+const { spawn } = require("child_process");
const glob = require("glob");
-const { Extractor, ExtractorConfig } = require("@microsoft/api-extractor");
const SDK_DIST_DIR_PATH = path.resolve("./resources/embedding-sdk/dist");
+const API_EXTRACTOR_BIN_PATH = path.resolve(
+ "./node_modules/@microsoft/api-extractor/bin/api-extractor",
+);
/*
* This script replaces all custom aliases in Embedding SDK generated ".d.ts" files so that this imports could be resolved
@@ -26,10 +29,52 @@ const REPLACES_MAP = {
cljs: "target/cljs_release",
};
-const API_EXTRACTOR_CONFIG_PATH = path.join(
- __dirname,
- "../../enterprise/frontend/src/embedding-sdk-package/embedding-sdk-api-extractor.json",
-);
+const DTS_ROLLUPS = [
+ {
+ name: "main",
+ configPath: path.join(
+ __dirname,
+ "../../enterprise/frontend/src/embedding-sdk-package/embedding-sdk-api-extractor.json",
+ ),
+ entryPointPath: path.join(
+ __dirname,
+ "../../resources/embedding-sdk/dist/enterprise/frontend/src/embedding-sdk-package/index.d.ts",
+ ),
+ },
+ {
+ name: "data-app",
+ configPath: path.join(
+ __dirname,
+ "../../enterprise/frontend/src/embedding-sdk-package/embedding-sdk-data-app-api-extractor.json",
+ ),
+ entryPointPath: path.join(
+ __dirname,
+ "../../resources/embedding-sdk/dist/enterprise/frontend/src/embedding-sdk-package/data-app.d.ts",
+ ),
+ },
+ {
+ name: "data-app-dev",
+ configPath: path.join(
+ __dirname,
+ "../../enterprise/frontend/src/embedding-sdk-package/embedding-sdk-data-app-dev-api-extractor.json",
+ ),
+ entryPointPath: path.join(
+ __dirname,
+ "../../resources/embedding-sdk/dist/enterprise/frontend/src/embedding-sdk-package/data-app-dev.d.ts",
+ ),
+ },
+ {
+ name: "data-app-dev-config",
+ configPath: path.join(
+ __dirname,
+ "../../enterprise/frontend/src/embedding-sdk-package/embedding-sdk-data-app-dev-config-api-extractor.json",
+ ),
+ entryPointPath: path.join(
+ __dirname,
+ "../../resources/embedding-sdk/dist/enterprise/frontend/src/embedding-sdk-package/data-app-dev.config.d.ts",
+ ),
+ },
+];
const getLogger = (prefix) => {
const verbose = process.env.SDK_FIXUP_VERBOSE_LOGS === "true";
@@ -110,7 +155,7 @@ const removeUnresolvedReexports = (filePath) => {
}
};
-const fixupTypesAfterCompilation = ({ isWatchMode }) => {
+const fixupTypesAfterCompilation = async ({ isWatchMode }) => {
log("Fixing SDK d.ts files...");
const dtsFilePaths = glob.sync(`${SDK_DIST_DIR_PATH}/**/*.d.ts`);
@@ -123,45 +168,97 @@ const fixupTypesAfterCompilation = ({ isWatchMode }) => {
console.log("[dts fixup] Done!");
if (!isWatchMode) {
- generateDtsRollup();
+ await generateDtsRollup();
}
};
-const generateDtsRollup = () => {
+const generateDtsRollup = async () => {
// Dts rollup logger
const { log, error } = getLogger("dts rollup");
log("Generate dts rollup...");
- const dtsRollupEntryPointPath = path.resolve(
- path.join(
- __dirname,
- "../../resources/embedding-sdk/dist/enterprise/frontend/src/embedding-sdk-package/index.d.ts",
- ),
- );
- const dtsRollupEntryPointPathExist = fs.existsSync(dtsRollupEntryPointPath);
+ const existingEntryPointCount = DTS_ROLLUPS.filter(({ entryPointPath }) =>
+ fs.existsSync(path.resolve(entryPointPath)),
+ ).length;
- if (!dtsRollupEntryPointPathExist) {
+ if (existingEntryPointCount === 0) {
log("It looks like dts rollup is already generated, skipping...");
return;
}
- const apiExtractorConfig = ExtractorConfig.loadFileAndPrepare(
- API_EXTRACTOR_CONFIG_PATH,
+ if (existingEntryPointCount !== DTS_ROLLUPS.length) {
+ DTS_ROLLUPS.forEach(({ entryPointPath, name }) => {
+ const resolvedEntryPointPath = path.resolve(entryPointPath);
+ if (!fs.existsSync(resolvedEntryPointPath)) {
+ error(
+ `Dts rollup entry point for ${name} does not exist: ${resolvedEntryPointPath}`,
+ );
+ }
+ });
+ process.exitCode = 1;
+ return;
+ }
+
+ let hasExtractorFailure = false;
+
+ // The extractors are independent (each reads the shared compiled d.ts tree
+ // and writes its own rollup), so run them concurrently. Output is buffered
+ // per extractor and printed on completion so parallel runs don't interleave.
+ const runApiExtractor = ({ configPath, name }) =>
+ new Promise((resolve) => {
+ const child = spawn(
+ process.execPath,
+ [
+ API_EXTRACTOR_BIN_PATH,
+ "run",
+ "--local",
+ "--verbose",
+ "--config",
+ path.resolve(configPath),
+ ],
+ { stdio: ["ignore", "pipe", "pipe"] },
+ );
+
+ let output = "";
+ child.stdout.on("data", (chunk) => (output += chunk));
+ child.stderr.on("data", (chunk) => (output += chunk));
+ child.on("close", (status, signal) =>
+ resolve({ name, status, signal, output }),
+ );
+ });
+
+ const results = await Promise.all(
+ DTS_ROLLUPS.filter(({ entryPointPath, name }) => {
+ if (fs.existsSync(path.resolve(entryPointPath))) {
+ return true;
+ }
+
+ error(
+ `Dts rollup entry point for ${name} does not exist: ${path.resolve(entryPointPath)}`,
+ );
+ hasExtractorFailure = true;
+ return false;
+ }).map(runApiExtractor),
);
- const extractorResult = Extractor.invoke(apiExtractorConfig, {
- localBuild: true,
- showVerboseMessages: true,
- });
+ for (const { name, status, signal, output } of results) {
+ log(`--- api-extractor: ${name} ---`);
+ process.stdout.write(output);
- if (!extractorResult.succeeded) {
- error(
- `API Extractor completed with ${extractorResult.errorCount} errors` +
- ` and ${extractorResult.warningCount} warnings`,
- );
+ if (status !== 0 || signal) {
+ error(
+ `API Extractor failed for ${name}` +
+ (signal ? ` with signal ${signal}` : ""),
+ );
+ hasExtractorFailure = true;
+ }
+ }
+
+ if (hasExtractorFailure) {
process.exitCode = 1;
+ return;
}
log("API Extractor completed successfully");
@@ -220,7 +317,7 @@ const isWatchMode = process.argv.includes("--watch");
const run = async () => {
// when running on a clean state and with --watch, the folder might not exist yet
await waitForFolder(SDK_DIST_DIR_PATH);
- fixupTypesAfterCompilation({ isWatchMode });
+ await fixupTypesAfterCompilation({ isWatchMode });
if (isWatchMode) {
console.log("\n\n\n");
diff --git a/bun.lock b/bun.lock
index 456b35e1692..c1c0ceec52f 100644
--- a/bun.lock
+++ b/bun.lock
@@ -277,6 +277,7 @@
"@types/tether": "^1.4.6",
"@types/underscore": "^1.13.0",
"@types/use-sync-external-store": "^1.5.0",
+ "@vitejs/plugin-react": "^6.0.2",
"ajv": "^8.5.0",
"babel-loader": "^9.1.2",
"babel-plugin-ttag": "^1.8.16",
@@ -402,6 +403,9 @@
"typedoc-plugin-redirect": "^1.2.0",
"typescript-eslint": "8.60.0",
"typescript-plugin-css-modules": "^5.1.0",
+ "vite": "^8.0.16",
+ "vite-plugin-css-injected-by-js": "^3.5.2",
+ "vite-plugin-svgr": "^5.2.0",
"web-streams-polyfill": "^4.1.0",
"webpack": "5.105.0",
"webpack-bundle-analyzer": "^4.10.1",
@@ -1275,6 +1279,8 @@
"@opentelemetry/semantic-conventions": ["@opentelemetry/[email protected]", "", {}, "sha512-aKcOkyrorBGlajjRdVoJWHTxfxO1vCNHLJVlSDaRHDIdjU+pX8IYQPvPDkYiujKLbRnWU+1TBwEt0QRgSm4SGA=="],
+ "@oxc-project/types": ["@oxc-project/[email protected]", "", {}, "sha512-r9gHphtCs+1M7J0pw6Sn/hh/Wpa/iQrOOkrNAlVLF/gHq+/CJmHIWKKUUhdWjcD6CIa8idarspCsASiXCXvFUw=="],
+
"@oxfmt/binding-android-arm-eabi": ["@oxfmt/[email protected]", "", { "os": "android", "cpu": "arm" }, "sha512-lTN4//sgYywK8ulQo7a/EZVzOTGomGQv2IG/7tMYdqTV3xN3QTqWpXcZBGUzaicC4B882N+5zJLYZ37IWfUMcg=="],
"@oxfmt/binding-android-arm64": ["@oxfmt/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-XbVgqR1WsIcCkfxwh2tdg3M1MWgR23YOboW2nbB8ab0gInNNLGy7cIAdr78XaoG/bGdaF4488XRhuGWq67xrzA=="],
@@ -1439,6 +1445,40 @@
"@remirror/core-constants": ["@remirror/[email protected]", "", {}, "sha512-42aWfPrimMfDKDi4YegyS7x+/0tlzaqwPQCULLanv3DMIlu96KTJR0fM5isWX2UViOqlGnX6YFgqWepcX+XMNg=="],
+ "@rolldown/binding-android-arm64": ["@rolldown/[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ=="],
+
+ "@rolldown/binding-darwin-arm64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-51Bnx9pNiMRKSUNtBfySkNJ9vMU9Hh3I1ozDd6gyPPYzaXCfnptUcEZxXGYFn+ul2dtcMUiqGR1Yai2K10uoTw=="],
+
+ "@rolldown/binding-darwin-x64": ["@rolldown/[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-Tm+gbfC0aHu1tBA/JvKQh32S0K6YgCHkiAF4/W6xX0K0RmNuc94VeK419dJoE65R5aRxmo+noZQSWrAMF6yb6g=="],
+
+ "@rolldown/binding-freebsd-x64": ["@rolldown/[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JMzDKCCXq93YccG5gz3hvOs1oXRKAf0XYpfOS88e+wZrC8Iugj6j68867vrYZkvpDDpKn/KoKORThmchMpF6TA=="],
+
+ "@rolldown/binding-linux-arm-gnueabihf": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-uML21j2K5TfPGutKxub+M+nLjZIrWjXQ5Grx4lCe/nimTj9B4L63zHpjXLl4y0L3mcm2htEQIb06oCG/szerNw=="],
+
+ "@rolldown/binding-linux-arm64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-navSiuTMogvnQoZoM/v+l3ZWo50/NTwSHSzheABx/RCnmUPaKwq9qSo4Br2OYRs21+Fz8uFqITZM3H4opOB0/Q=="],
+
+ "@rolldown/binding-linux-arm64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-lAryqH7IteztmCXQXk0etKj4wBQ7Gx5S6LjKhsgp9zb8I5bsuvU/2llH1hDQcjsFeqIsovMVN339/8pUDDBXxA=="],
+
+ "@rolldown/binding-linux-ppc64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "ppc64" }, "sha512-fsK/sNBnxzBlL4O1JNrZakVQxPspqpED5dLtNsZS9oOKmtSpdNIzxH2kkol5HYTWJN47sE20ztMJPxfZ89qGOg=="],
+
+ "@rolldown/binding-linux-s390x-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "s390x" }, "sha512-gLYb4BIadlfTOYT5gO503n8zQjXflgzpD0FcyKh0Mzx3rqCZKnHoJWV9xe1KXUJ5lx2JfcSHr/mhzS0PC/McAA=="],
+
+ "@rolldown/binding-linux-x64-gnu": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-FjcpEKUyJygHgs1o50VYNvkt5+7Le/VEdYt0AkRpkL33MnyQfwr8l5mXwMmfmTbyMPr5vJLC+8/Gd9gXnwU1QQ=="],
+
+ "@rolldown/binding-linux-x64-musl": ["@rolldown/[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-Me+PfPI2TMeOQk0gYWfLQZtTktrmzbr8cDboqX83XKc7UrgAi55gF+2dUkWdxd19n55Essp2yeca+O9N5rBxHg=="],
+
+ "@rolldown/binding-openharmony-arm64": ["@rolldown/[email protected]", "", { "os": "none", "cpu": "arm64" }, "sha512-yc5WrLzXks6zCQfn9Oxr8pORKyl/pF+QjHmW/Qx3qu0oyrrNC+y2JLTU1E2rcWYAmzlnqngWXHQjy51VzW70Vw=="],
+
+ "@rolldown/binding-wasm32-wasi": ["@rolldown/[email protected]", "", { "dependencies": { "@emnapi/core": "1.11.1", "@emnapi/runtime": "1.11.1", "@napi-rs/wasm-runtime": "^1.1.6" }, "cpu": "none" }, "sha512-VbQGPX2b4r48TAMIM2cjgluIM1HYutm4pcTEJsle7iEP7sB1dFqtPLBVbdLAZCxy1txCcPxf4QFf4v8uvltPqA=="],
+
+ "@rolldown/binding-win32-arm64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-gHv82k63z4qpV5+Q1y/12KrK0ltWBukVDI8nZcbT7Tt/ZlOIVwppazneq0F93oDxTo3IgAMEDIoQh3E2n6mVsw=="],
+
+ "@rolldown/binding-win32-x64-msvc": ["@rolldown/[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-tTZuDBPw85tEN5PQi1pnEBzDy0Z49HtScLAbD5t6hyeU92A95pRWaSMw1GZZi/RwgSgUIl0xrSlXIT/9QzvYSA=="],
+
+ "@rolldown/pluginutils": ["@rolldown/[email protected]", "", {}, "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw=="],
+
+ "@rollup/pluginutils": ["@rollup/[email protected]", "", { "dependencies": { "@types/estree": "^1.0.0", "estree-walker": "^2.0.2", "picomatch": "^4.0.2" }, "peerDependencies": { "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0" }, "optionalPeers": ["rollup"] }, "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg=="],
+
"@rspack/binding": ["@rspack/[email protected]", "", { "optionalDependencies": { "@rspack/binding-darwin-arm64": "2.0.3", "@rspack/binding-darwin-x64": "2.0.3", "@rspack/binding-linux-arm64-gnu": "2.0.3", "@rspack/binding-linux-arm64-musl": "2.0.3", "@rspack/binding-linux-x64-gnu": "2.0.3", "@rspack/binding-linux-x64-musl": "2.0.3", "@rspack/binding-wasm32-wasi": "2.0.3", "@rspack/binding-win32-arm64-msvc": "2.0.3", "@rspack/binding-win32-ia32-msvc": "2.0.3", "@rspack/binding-win32-x64-msvc": "2.0.3" } }, "sha512-4exVNhGhW5RFHjK87XeTKbkA/qAgI5NHJlT1jNqiJv0gcUXLqTOEU3w7f8+f9zUo4JMFvPc0c9veOi4M19YYTg=="],
"@rspack/binding-darwin-arm64": ["@rspack/[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-4UyCjLJwU/WxR6K1/gG4u3+jUsoaRHJ5rNu9fto/UbvrItwdlVNULChAApqZFw6mcSetMddSjSICeuj5pSB6sA=="],
@@ -2157,6 +2197,8 @@
"@visx/vendor": ["@visx/[email protected]", "", { "dependencies": { "@types/d3-array": "3.0.3", "@types/d3-color": "3.1.0", "@types/d3-delaunay": "6.0.1", "@types/d3-format": "3.0.1", "@types/d3-geo": "3.1.0", "@types/d3-interpolate": "3.0.1", "@types/d3-scale": "4.0.2", "@types/d3-time": "3.0.0", "@types/d3-time-format": "2.1.0", "d3-array": "3.2.1", "d3-color": "3.1.0", "d3-delaunay": "6.0.2", "d3-format": "3.1.0", "d3-geo": "3.1.0", "d3-interpolate": "3.0.1", "d3-scale": "4.0.2", "d3-time": "3.1.0", "d3-time-format": "4.1.0", "internmap": "2.0.3" } }, "sha512-yt3SEZRVmt36+APsCISSO9eSOtzQkBjt+QRxNRzcTWuzwMAaF3PHCCSe31++kkpgY9yFoF+Gfes1TBe5NlETiQ=="],
+ "@vitejs/plugin-react": ["@vitejs/[email protected]", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-vmFvco5/QuC2f9Oj+wTk0+9XeDFkHxSamwZKYc7MxYwKICfvUvlMhqKI0VuICPltGqh1neqBKDvO4kes1ya8vg=="],
+
"@vitest/expect": ["@vitest/[email protected]", "", { "dependencies": { "@vitest/spy": "2.0.5", "@vitest/utils": "2.0.5", "chai": "^5.1.1", "tinyrainbow": "^1.2.0" } }, "sha512-yHZtwuP7JZivj65Gxoi8upUN2OzHTi3zVfjwdpu2WrvCZPLwsJ2Ey5ILIPccoW23dd/zQBlJ4/dhi7DWNyXCpA=="],
"@vitest/pretty-format": ["@vitest/[email protected]", "", { "dependencies": { "tinyrainbow": "^1.2.0" } }, "sha512-9HiSZ9zpqNLKlbIDRWOnAWqgcA7xu+8YxXSekhr0Ykab7PAYFkhkwoqVArPOtJhPmYeE2YHgKZlj3CP36z2AJQ=="],
@@ -2905,7 +2947,7 @@
"destroy": ["[email protected]", "", {}, "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg=="],
- "detect-libc": ["[email protected]", "", { "bin": { "detect-libc": "./bin/detect-libc.js" } }, "sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg=="],
+ "detect-libc": ["[email protected]", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"detect-newline": ["[email protected]", "", {}, "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA=="],
@@ -3119,7 +3161,7 @@
"estree-util-is-identifier-name": ["[email protected]", "", {}, "sha512-hFtqIDZTIUZ9BXLb8y4pYGyk6+wekIivNVTcmvk8NoOh+VeRn5y6cEHzbURrWbfp1fIqdVipilzj+lfaadNZmg=="],
- "estree-walker": ["[email protected]", "", {}, "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w=="],
+ "estree-walker": ["[email protected]", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="],
"esutils": ["[email protected]", "", {}, "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g=="],
@@ -3853,6 +3895,30 @@
"lighthouse-logger": ["[email protected]", "", { "dependencies": { "debug": "^2.6.9", "marky": "^1.2.2" } }, "sha512-gPWxznF6TKmUHrOQjlVo2UbaL2EJ71mb2CCeRs/2qBpi4L/g4LUVc9+3lKQ6DTUZwJswfM7ainGrLO1+fOqa2g=="],
+ "lightningcss": ["[email protected]", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],
+
+ "lightningcss-android-arm64": ["[email protected]", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="],
+
+ "lightningcss-darwin-arm64": ["[email protected]", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ=="],
+
+ "lightningcss-darwin-x64": ["[email protected]", "", { "os": "darwin", "cpu": "x64" }, "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w=="],
+
+ "lightningcss-freebsd-x64": ["[email protected]", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig=="],
+
+ "lightningcss-linux-arm-gnueabihf": ["[email protected]", "", { "os": "linux", "cpu": "arm" }, "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw=="],
+
+ "lightningcss-linux-arm64-gnu": ["[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ=="],
+
+ "lightningcss-linux-arm64-musl": ["[email protected]", "", { "os": "linux", "cpu": "arm64" }, "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg=="],
+
+ "lightningcss-linux-x64-gnu": ["[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA=="],
+
+ "lightningcss-linux-x64-musl": ["[email protected]", "", { "os": "linux", "cpu": "x64" }, "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg=="],
+
+ "lightningcss-win32-arm64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "arm64" }, "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw=="],
+
+ "lightningcss-win32-x64-msvc": ["[email protected]", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],
+
"lilconfig": ["[email protected]", "", {}, "sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ=="],
"lines-and-columns": ["[email protected]", "", {}, "sha1-HADHQ7QzzQpOgHWPe2SldEDZ/wA="],
@@ -4869,6 +4935,8 @@
"robust-predicates": ["[email protected]", "", {}, "sha512-IXgzBWvWQwE6PrDI05OvmXUIruQTcoMDzRsOd5CDvHCVLcLHMTSYvOK5Cm46kWqlV3yAbuSpBZdJ5oP5OUoStg=="],
+ "rolldown": ["[email protected]", "", { "dependencies": { "@oxc-project/types": "=0.139.0", "@rolldown/pluginutils": "^1.0.0" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.1.5", "@rolldown/binding-darwin-arm64": "1.1.5", "@rolldown/binding-darwin-x64": "1.1.5", "@rolldown/binding-freebsd-x64": "1.1.5", "@rolldown/binding-linux-arm-gnueabihf": "1.1.5", "@rolldown/binding-linux-arm64-gnu": "1.1.5", "@rolldown/binding-linux-arm64-musl": "1.1.5", "@rolldown/binding-linux-ppc64-gnu": "1.1.5", "@rolldown/binding-linux-s390x-gnu": "1.1.5", "@rolldown/binding-linux-x64-gnu": "1.1.5", "@rolldown/binding-linux-x64-musl": "1.1.5", "@rolldown/binding-openharmony-arm64": "1.1.5", "@rolldown/binding-wasm32-wasi": "1.1.5", "@rolldown/binding-win32-arm64-msvc": "1.1.5", "@rolldown/binding-win32-x64-msvc": "1.1.5" }, "bin": { "rolldown": "./bin/cli.mjs" } }, "sha512-t9z29cJjXf/vxQ8dyhCSpt6H6aSwHTk8cT5I3iy6SMXuFpk5mB6PL6XfC8PCwrPTx93udwKUm9HRteAlTGBLiA=="],
+
"rollup-plugin-inject": ["[email protected]", "", { "dependencies": { "estree-walker": "^0.6.1", "magic-string": "^0.25.3", "rollup-pluginutils": "^2.8.1" } }, "sha512-ptg9PQwzs3orn4jkgXJ74bfs5vYz1NCZlSQMBUA0wKcGp5i5pA1AO3fOUEte8enhGUC+iapTCzEWw2jEFFUO/w=="],
"rollup-plugin-node-polyfills": ["[email protected]", "", { "dependencies": { "rollup-plugin-inject": "^3.0.0" } }, "sha512-4kCrKPTJ6sK4/gLL/U5QzVT8cxJcofO0OU74tnB19F40cmuAKSzH5/siithxlofFEjwvw1YAhPmbvGNA6jEroA=="],
@@ -5461,6 +5529,12 @@
"vfile-message": ["[email protected]", "", { "dependencies": { "@types/unist": "^3.0.0", "unist-util-stringify-position": "^4.0.0" } }, "sha512-jRDZ1IMLttGj41KcZvlrYAaI3CfqpLpfpf+Mfig13viT6NKvRzWZ+lXz0Y5D60w6uJIBAOGq9mSHf0gktF0duw=="],
+ "vite": ["[email protected]", "", { "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.5", "postcss": "^8.5.16", "rolldown": "~1.1.4", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.3.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-bTT9PsdWO+MQMNG9ZXIP/qM9wGh37DFxTV/sPq9cFpHr3w4jkgef032PkAL9jAqhk3Nz8NQw3O8n6/xFkqO4QQ=="],
+
+ "vite-plugin-css-injected-by-js": ["[email protected]", "", { "peerDependencies": { "vite": ">2.0.0-0" } }, "sha512-2MpU/Y+SCZyWUB6ua3HbJCrgnF0KACAsmzOQt1UvRVJCGF6S8xdA3ZUhWcWdM9ivG4I5az8PnQmwwrkC2CAQrQ=="],
+
+ "vite-plugin-svgr": ["[email protected]", "", { "dependencies": { "@rollup/pluginutils": "^5.3.0", "@svgr/core": "^8.1.0", "@svgr/plugin-jsx": "^8.1.0" }, "peerDependencies": { "vite": ">=3.0.0" } }, "sha512-qj2eAKF8C6PZWemVTvQA0xgQIcP1hHU6Buh7fl6BhvayWwnuxE+z417miKxeDvRWbDrupQ1oK99hfxElopJ3sQ=="],
+
"vitest-axe": ["[email protected]", "", { "dependencies": { "aria-query": "^5.0.0", "axe-core": "^4.4.2", "chalk": "^5.0.1", "dom-accessibility-api": "^0.5.14", "lodash-es": "^4.17.21", "redent": "^3.0.0" } }, "sha512-jvtXxeQPg8R/2ANTY8QicA5pvvdRP4F0FsVUAHANJ46YCDASie/cuhlSzu0DGcLmZvGBSBNsNuK3HqfaeknyvA=="],
"vm-browserify": ["[email protected]", "", {}, "sha512-2ham8XPWTONajOR0ohOKOHXkm3+gaBmGut3SRuu75xLd/RRaY6vqgh8NBYYk7+RW3u5AtzPQZG8F10LHkl0lAQ=="],
@@ -5815,6 +5889,8 @@
"@nicolo-ribaudo/eslint-scope-5-internals/eslint-scope": ["[email protected]", "", { "dependencies": { "esrecurse": "^4.3.0", "estraverse": "^4.1.1" } }, "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw=="],
+ "@parcel/watcher/detect-libc": ["[email protected]", "", { "bin": { "detect-libc": "./bin/detect-libc.js" } }, "sha512-pGjwhsmsp4kL2RTz08wcOlGN83otlqHeD/Z5T8GXZB+/YcpQ/dgo+lbU8ZsGxV0HIvqqxo9l7mqYwyYMD9bKDg=="],
+
"@pmmmwh/react-refresh-webpack-plugin/source-map": ["[email protected]", "", {}, "sha512-CkCj6giN3S+n9qrYiBTX5gystlENnRW5jZeNLHpe6aue+SrHcG5VYwujhW9s4dY31mEGsxBDrHR6oI69fTXsaQ=="],
"@redocly/cli/ajv": ["@redocly/[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-BieiCML/IgP6x99HZByJSt7fJE4ipgzO7KAFss92Bs+PEI35BhY7vGIysFXLT+YmS7nHtQjZjhOQyPPEf7xGHA=="],
@@ -5835,6 +5911,16 @@
"@redocly/respect-core/colorette": ["[email protected]", "", {}, "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w=="],
+ "@rolldown/binding-wasm32-wasi/@emnapi/core": ["@emnapi/[email protected]", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.2", "tslib": "^2.4.0" } }, "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ=="],
+
+ "@rolldown/binding-wasm32-wasi/@emnapi/runtime": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw=="],
+
+ "@rolldown/binding-wasm32-wasi/@napi-rs/wasm-runtime": ["@napi-rs/[email protected]", "", { "dependencies": { "@tybys/wasm-util": "^0.10.3" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-ZLv/JdUfkvOy9eCnnBaGfiO+XimbjebAeO+MRQqD/B+FR1tnRN0tpKSJHRbE8sFfS6aqsXZ67TQjfwfsxULVbg=="],
+
+ "@rollup/pluginutils/@types/estree": ["@types/[email protected]", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="],
+
+ "@rollup/pluginutils/picomatch": ["[email protected]", "", {}, "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A=="],
+
"@rushstack/node-core-library/ajv": ["[email protected]", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-PlXPeEWMXMZ7sPYOHqmDyCJzcfNrUr3fGNKtezX14ykXOEIvyK81d+qydx89KY5O71FKMPaQ2vBfBFI5NHR63A=="],
"@rushstack/node-core-library/fs-extra": ["[email protected]", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^6.0.1", "universalify": "^2.0.0" } }, "sha512-Z4XaCL6dUDHfP/jT25jJKMmtxvuwbkrD1vNSMFlo9lNLY2c5FHYSQgHPRZUjAB26TpDEoW9HCOgplrdbaPV/ew=="],
@@ -6055,12 +6141,8 @@
"@vue/compiler-core/entities": ["[email protected]", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="],
- "@vue/compiler-core/estree-walker": ["[email protected]", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="],
-
"@vue/compiler-sfc/@babel/parser": ["@babel/[email protected]", "", { "dependencies": { "@babel/types": "^7.29.0" }, "bin": "./bin/babel-parser.js" }, "sha512-4GgRzy/+fsBa72/RZVJmGKPmZu9Byn8o4MoLpmNe1m8ZfYnz5emHLQz3U4gLud6Zwl0RZIcgiLD7Uq7ySFuDLA=="],
- "@vue/compiler-sfc/estree-walker": ["[email protected]", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="],
-
"@vue/compiler-sfc/magic-string": ["[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
"@vue/compiler-sfc/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.11", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ=="],
@@ -7007,8 +7089,12 @@
"ripemd160/hash-base": ["[email protected]", "", { "dependencies": { "inherits": "^2.0.4", "readable-stream": "^3.6.0", "safe-buffer": "^5.2.0" } }, "sha512-1nmYp/rhMDiE7AYkDw+lLwlAzz0AntGIe51F3RfFfEqyQ3feY2eI/NcwC6umIQVOASPMsWJLJScWKSSvzL9IVA=="],
+ "rollup-plugin-inject/estree-walker": ["[email protected]", "", {}, "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w=="],
+
"rollup-plugin-inject/magic-string": ["[email protected]", "", { "dependencies": { "sourcemap-codec": "^1.4.8" } }, "sha512-RmF0AsMzgt25qzqqLc1+MbHmhdx0ojF2Fvs4XnOqz2ZOBXzzkEwc/dJQZCYHAn7v1jbVOjAZfK8msRn4BxO4VQ=="],
+ "rollup-pluginutils/estree-walker": ["[email protected]", "", {}, "sha512-SqmZANLWS0mnatqbSfRP5g8OXZC12Fgg1IwNtLsyHDzJizORW4khDfjPqJZsemPWBB2uqykUah5YpQ6epsqC/w=="],
+
"router/path-to-regexp": ["[email protected]", "", {}, "sha512-PuseHIvAnz3bjrM2rGJtSgo1zjgxapTLZ7x2pjhzWwlp4SJQgK3f3iZIQwkpEnBaKz6seKBADpM4B4ySkuYypg=="],
"rxjs/tslib": ["[email protected]", "", {}, "sha512-AEYxH93jGFPn/a2iVAwW87VuUIkR1FVUKB77NwMF7nBTDkDrrT/Hpt/IrCJ0QXhW27jTBDcf5ZY7w6RiqTMw2Q=="],
@@ -7197,6 +7283,12 @@
"vfile-message/@types/unist": ["@types/[email protected]", "", {}, "sha512-dqId9J8K/vGi5Zr7oo212BGii5m3q5Hxlkwy3WpYuKPklmBEvsbMYYyLxAQpSffdLl/gdW0XUpKWFvYmyoWCoQ=="],
+ "vite/picomatch": ["[email protected]", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="],
+
+ "vite/postcss": ["[email protected]", "", { "dependencies": { "nanoid": "^3.3.12", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg=="],
+
+ "vite/tinyglobby": ["[email protected]", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g=="],
+
"vitest-axe/aria-query": ["[email protected]", "", {}, "sha512-V+SM7AbUwJ+EBnB8+DXs0hPZHO0W6pqBcc0dW90OwtVG02PswOu/teuARoLQjdDOH+t9pJgGnW5/Qmouf3gPJg=="],
"vitest-axe/chalk": ["[email protected]", "", {}, "sha512-zgVZuo2WcZgfUEmsn6eO3kINexW8RAE4maiQ8QNs8CtpPCSyMiYsULR3HQYkm3w8FIA3SberyMJMSldGsW+U3w=="],
@@ -7463,6 +7555,14 @@
"@redocly/cli/react-dom/scheduler": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.1.0" } }, "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ=="],
+ "@rolldown/binding-wasm32-wasi/@emnapi/core/@emnapi/wasi-threads": ["@emnapi/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="],
+
+ "@rolldown/binding-wasm32-wasi/@emnapi/core/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
+ "@rolldown/binding-wasm32-wasi/@emnapi/runtime/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
+ "@rolldown/binding-wasm32-wasi/@napi-rs/wasm-runtime/@tybys/wasm-util": ["@tybys/[email protected]", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="],
+
"@storybook/addon-docs/react-dom/scheduler": ["[email protected]", "", { "dependencies": { "loose-envify": "^1.1.0" } }, "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ=="],
"@storybook/addon-webpack5-compiler-babel/babel-loader/find-cache-dir": ["[email protected]", "", { "dependencies": { "common-path-prefix": "^3.0.0", "pkg-dir": "^7.0.0" } }, "sha512-9ZonPT4ZAK4a+1pUPVPZJapbi7O5qbbJPdYw/NOQWZZbVLdDTYM3A4R9z/DpAM08IDaFGsvPgiGZ82WEwUDWjg=="],
@@ -8331,6 +8431,8 @@
"unbox-primitive/which-boxed-primitive/is-number-object": ["[email protected]", "", { "dependencies": { "call-bound": "^1.0.3", "has-tostringtag": "^1.0.2" } }, "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw=="],
+ "vite/postcss/nanoid": ["[email protected]", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA=="],
+
"webpack-dev-middleware/mime-types/mime-db": ["[email protected]", "", {}, "sha512-5y8A56jg7XVQx2mbv1lu49NR4dokRnhZYTtL+KGfaa27uq4pSTXkwQkFJl4pkRMyNFz/EtYDSkiiEHx3F7UN6g=="],
"webpack-dev-middleware/schema-utils/@types/json-schema": ["@types/[email protected]", "", {}, "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ=="],
@@ -8517,6 +8619,8 @@
"@redocly/cli/glob/minimatch/brace-expansion": ["[email protected]", "", { "dependencies": { "balanced-match": "^4.0.2" } }, "sha512-Pdk8c9poy+YhOgVWw1JNN22/HcivgKWwpxKq04M/jTmHyCZn12WPJebZxdjSa5TmBqISrUSgNYU3eRORljfCCw=="],
+ "@rolldown/binding-wasm32-wasi/@napi-rs/wasm-runtime/@tybys/wasm-util/tslib": ["[email protected]", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
+
"@storybook/addon-webpack5-compiler-babel/babel-loader/find-cache-dir/pkg-dir": ["[email protected]", "", { "dependencies": { "find-up": "^6.3.0" } }, "sha512-Ie9z/WINcxxLp27BKOCHGde4ITq9UklYKDzVo1nhk5sqGEXU3FpkwP5GM2voTGJkGd9B3Otl+Q4uwSOeSUtOBA=="],
"@storybook/addon-webpack5-compiler-babel/babel-loader/schema-utils/@types/json-schema": ["@types/[email protected]", "", {}, "sha512-qcUXuemtEu+E5wZSJHNxUXeCZhAfXKQ41D+duX+VYPde7xyEVZci+/oXKJL13tnRs9lR2pr4fod59GT6/X1/yQ=="],
diff --git a/e2e/support/assets/data-apps/.gitignore b/e2e/support/assets/data-apps/.gitignore
new file mode 100644
index 00000000000..875a192f532
--- /dev/null
+++ b/e2e/support/assets/data-apps/.gitignore
@@ -0,0 +1,6 @@
+# Each test app under this directory commits its `src/` and its `data_app.yaml`
+# manifest. Everything else — the SDK/template base pulled in at test setup and
+# the built `dist/` bundle (Vite API) — is generated, so it's ignored here.
+/*/*
+!/*/src
+!/*/data_app.yaml
diff --git a/e2e/support/assets/data-apps/custom-error-component/data_app.yaml b/e2e/support/assets/data-apps/custom-error-component/data_app.yaml
new file mode 100644
index 00000000000..040a3afbd80
--- /dev/null
+++ b/e2e/support/assets/data-apps/custom-error-component/data_app.yaml
@@ -0,0 +1,2 @@
+name: Custom Error Component
+path: ./dist/index.js
diff --git a/e2e/support/assets/data-apps/custom-error-component/src/index.tsx b/e2e/support/assets/data-apps/custom-error-component/src/index.tsx
new file mode 100644
index 00000000000..db5ed23c0a3
--- /dev/null
+++ b/e2e/support/assets/data-apps/custom-error-component/src/index.tsx
@@ -0,0 +1,34 @@
+import {
+ type SdkErrorComponentProps,
+ StaticQuestion,
+} from "@metabase/embedding-sdk-react";
+import type { DataAppFactory } from "@metabase/embedding-sdk-react/data-app";
+
+// A question id that does not exist, so the SDK takes its error path — which this
+// app overrides with its own `errorComponent`, asserting an app-supplied component
+// wins over the host's default neutral error state.
+const MISSING_QUESTION_ID = 999999999;
+
+function CustomError({ message }: SdkErrorComponentProps) {
+ return (
+ <div data-testid="custom-error-component">Custom app error: {message}</div>
+ );
+}
+
+function App() {
+ return (
+ <div data-testid="custom-error-app" style={{ padding: 24 }}>
+ <h1>Custom error app</h1>
+ <div style={{ height: 300 }}>
+ <StaticQuestion questionId={MISSING_QUESTION_ID} />
+ </div>
+ </div>
+ );
+}
+
+const factory: DataAppFactory = () => ({
+ component: App,
+ providerProps: { errorComponent: CustomError },
+});
+
+export default factory;
diff --git a/e2e/support/assets/data-apps/kitchen-sink/data_app.yaml b/e2e/support/assets/data-apps/kitchen-sink/data_app.yaml
new file mode 100644
index 00000000000..64aebc33050
--- /dev/null
+++ b/e2e/support/assets/data-apps/kitchen-sink/data_app.yaml
@@ -0,0 +1,2 @@
+name: Kitchen Sink
+path: ./dist/index.js
diff --git a/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx b/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx
new file mode 100644
index 00000000000..c7747d9569a
--- /dev/null
+++ b/e2e/support/assets/data-apps/kitchen-sink/src/App.tsx
@@ -0,0 +1,436 @@
+import {
+ InteractiveQuestion,
+ StaticQuestion,
+ useAction,
+} from "@metabase/embedding-sdk-react";
+import {
+ aggregations,
+ breakout,
+ copy,
+ DataAppLink,
+ DataAppRouter,
+ filter,
+ orderBy,
+ useDataAppLocation,
+ useMetabaseQuery,
+ useMetabaseQueryObject,
+} from "@metabase/embedding-sdk-react/data-app";
+import { type ComponentType, useEffect, useState } from "react";
+
+import { getTestEnv } from "./test-env";
+
+// The sandbox throws host-realm errors, whose `instanceof Error` can be false in
+// the guest; read `.message` defensively.
+const describeError = (err: unknown): string =>
+ (err as { message?: string })?.message ?? String(err);
+
+const PROBE_COLOR = "rgb(0, 128, 0)";
+
+function Overview() {
+ const { scalarQuery, questionQuery } = getTestEnv();
+ const ordersCount = useMetabaseQuery(scalarQuery);
+ const totalOrders = ordersCount.data?.rawRows?.[0]?.[0];
+ const ordersQuery = useMetabaseQueryObject(questionQuery);
+
+ return (
+ <div data-testid="data-app-content" style={{ padding: 24 }}>
+ <h1 style={{ margin: "0 0 16px" }}>Orders overview</h1>
+
+ <section
+ style={{
+ padding: 16,
+ border: "1px solid #e0e0e0",
+ borderRadius: 8,
+ marginBottom: 24,
+ maxWidth: 240,
+ }}
+ >
+ <div
+ style={{
+ color: "#6b7280",
+ fontSize: 12,
+ textTransform: "uppercase",
+ letterSpacing: 0.5,
+ }}
+ >
+ Total orders
+ </div>
+ <div
+ data-testid="orders-count"
+ style={{ fontSize: 32, fontWeight: 700 }}
+ >
+ {ordersCount.isLoading ? "…" : String(totalOrders ?? "—")}
+ </div>
+ </section>
+
+ <h2 style={{ margin: "0 0 8px" }}>All orders</h2>
+ <div style={{ height: 400 }}>
+ {ordersQuery.query ? (
+ <InteractiveQuestion card={{ query: ordersQuery.query }} />
+ ) : (
+ <div>…</div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function Details() {
+ return (
+ <div data-testid="data-app-details" style={{ padding: 24 }}>
+ <h1 style={{ margin: "0 0 16px" }}>Order details</h1>
+ <p>A nested page reached through the data-app router.</p>
+ </div>
+ );
+}
+
+function QueryStates() {
+ const { scalarQuery, errorQuery } = getTestEnv();
+ const broken = useMetabaseQuery(errorQuery!);
+ const working = useMetabaseQuery(scalarQuery);
+ const count = working.data?.rawRows?.[0]?.[0];
+
+ return (
+ <div data-testid="data-app-query-states" style={{ padding: 24 }}>
+ <h1>Query states</h1>
+ <div data-testid="query-error">{broken.error ? "error" : "no-error"}</div>
+ <div data-testid="query-loading">
+ {working.isLoading ? "loading" : "done"}
+ </div>
+ <div data-testid="query-value">
+ {working.isLoading ? "…" : String(count ?? "—")}
+ </div>
+ <button
+ type="button"
+ data-testid="query-refetch"
+ onClick={() => {
+ working.refetch();
+ }}
+ >
+ refetch
+ </button>
+ </div>
+ );
+}
+
+function StaticQuestionPage() {
+ const { questionQuery } = getTestEnv();
+ const q = useMetabaseQueryObject(questionQuery);
+
+ return (
+ <div data-testid="data-app-static-question" style={{ padding: 24 }}>
+ <h1>Static question</h1>
+ <div style={{ height: 360 }}>
+ {q.query ? (
+ <StaticQuestion card={{ query: q.query }} />
+ ) : (
+ <div data-testid="static-question-loading">…</div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function Combinators() {
+ const combinators = getTestEnv().combinators!;
+ const countAgg = aggregations.count();
+
+ const q = useMetabaseQuery({
+ source: combinators.source,
+ filters: [filter(combinators.filterField, ">", combinators.filterValue)],
+ aggregations: [countAgg],
+ breakouts: [breakout(combinators.breakoutField)],
+ orderBys: [orderBy(countAgg, "desc")],
+ });
+
+ return (
+ <div data-testid="data-app-combinators" style={{ padding: 24 }}>
+ <h1>Combinators</h1>
+ <div data-testid="combinators-loading">
+ {q.isLoading ? "loading" : "done"}
+ </div>
+ <div data-testid="combinators-error">
+ {q.error ? "error" : "no-error"}
+ </div>
+ <div data-testid="combinators-rowcount">
+ {String(q.data?.rows?.length ?? 0)}
+ </div>
+ </div>
+ );
+}
+
+function Actions() {
+ const { actionId, actionParams } = getTestEnv();
+ const action = useAction(actionId ?? null);
+ const [output, setOutput] = useState("idle");
+
+ const onExecute = async () => {
+ try {
+ const res = await action.execute(actionParams ?? {});
+ setOutput(res ? "returned-result" : "returned-null");
+ } catch {
+ setOutput("threw");
+ }
+ };
+
+ return (
+ <div data-testid="data-app-actions" style={{ padding: 24 }}>
+ <h1>Actions</h1>
+ <button type="button" data-testid="action-execute" onClick={onExecute}>
+ execute
+ </button>
+ <button
+ type="button"
+ data-testid="action-reset"
+ onClick={() => action.reset()}
+ >
+ reset
+ </button>
+ <div data-testid="action-executing">
+ {action.isExecuting ? "executing" : "idle"}
+ </div>
+ <div data-testid="action-result">
+ {action.result ? "has-result" : "no-result"}
+ </div>
+ <div data-testid="action-error">
+ {action.error ? "has-error" : "no-error"}
+ </div>
+ <div data-testid="action-output">{output}</div>
+ </div>
+ );
+}
+
+function Clipboard() {
+ const [status, setStatus] = useState("idle");
+
+ const onCopy = async () => {
+ try {
+ await copy("data-app-clipboard-payload");
+ setStatus("copied");
+ } catch (err) {
+ setStatus(`failed: ${describeError(err)}`);
+ }
+ };
+
+ return (
+ <div data-testid="data-app-clipboard" style={{ padding: 24 }}>
+ <h1>Clipboard</h1>
+ <button type="button" data-testid="clipboard-copy" onClick={onCopy}>
+ copy
+ </button>
+ <div data-testid="clipboard-status">{status}</div>
+ </div>
+ );
+}
+
+// With no app-supplied `errorComponent`, the host's default neutral error state
+// renders here.
+function MissingQuestion() {
+ return (
+ <div
+ data-testid="data-app-missing-question"
+ style={{ padding: 24, height: 300 }}
+ >
+ <StaticQuestion questionId={999999999} />
+ </div>
+ );
+}
+
+// Throws during render so the host's BundleErrorBoundary reports the failure to
+// the parent, which renders its themed error screen.
+function ThrowingPage(): JSX.Element {
+ throw new Error("intentional data-app bundle render error");
+}
+
+type Probe = { id: string; run: () => void };
+
+const BLOCKED_PROBES: Probe[] = [
+ { id: "script", run: () => document.createElement("script") },
+ { id: "window-open", run: () => window.open("https://blocked.test") },
+ { id: "alert", run: () => window.alert("x") },
+ { id: "history", run: () => window.history.pushState({}, "", "/x") },
+ {
+ id: "keydown-listener",
+ run: () => document.addEventListener("keydown", () => {}),
+ },
+ { id: "websocket", run: () => new WebSocket("wss://blocked.test") },
+ {
+ id: "sendbeacon",
+ run: () => navigator.sendBeacon("https://blocked.test"),
+ },
+];
+
+function Sandbox() {
+ const { sandbox } = getTestEnv();
+ const [probeResults, setProbeResults] = useState<Record<string, string>>({});
+ const [innerHtml, setInnerHtml] = useState("pending");
+ const [blockedFetch, setBlockedFetch] = useState("pending");
+ const [allowedFetch, setAllowedFetch] = useState("pending");
+ const [blockedXhr, setBlockedXhr] = useState("pending");
+ const [allowedXhr, setAllowedXhr] = useState("pending");
+
+ useEffect(() => {
+ const results: Record<string, string> = {};
+ for (const probe of BLOCKED_PROBES) {
+ try {
+ probe.run();
+ results[probe.id] = "not blocked";
+ } catch {
+ results[probe.id] = "blocked";
+ }
+ }
+ setProbeResults(results);
+
+ // `innerHTML` is distorted through DOMPurify, which strips <script>.
+ try {
+ const el = document.createElement("div");
+ el.innerHTML = "<script>window.x=1</script><b>ok</b>";
+ setInnerHtml(el.querySelector("script") ? "not stripped" : "stripped");
+ } catch (err) {
+ setInnerHtml(`threw: ${describeError(err)}`);
+ }
+
+ if (sandbox) {
+ fetch(sandbox.blockedUrl)
+ .then((res) => setBlockedFetch(`ok: ${res.status}`))
+ .catch((err) => setBlockedFetch(`blocked: ${describeError(err)}`));
+
+ fetch(sandbox.allowedUrl)
+ .then((res) => setAllowedFetch(`ok: ${res.status}`))
+ .catch((err) => setAllowedFetch(`blocked: ${describeError(err)}`));
+
+ if (sandbox.xhrBlockedUrl) {
+ try {
+ const xhr = new XMLHttpRequest();
+ xhr.open("GET", sandbox.xhrBlockedUrl);
+ setBlockedXhr("not blocked");
+ } catch (err) {
+ setBlockedXhr(`blocked: ${describeError(err)}`);
+ }
+ }
+
+ if (sandbox.xhrAllowedUrl) {
+ const xhr = new XMLHttpRequest();
+ xhr.addEventListener("load", () => setAllowedXhr(`ok: ${xhr.status}`));
+ xhr.addEventListener("error", () => setAllowedXhr("blocked: error"));
+ try {
+ xhr.open("GET", sandbox.xhrAllowedUrl);
+ xhr.send();
+ } catch (err) {
+ setAllowedXhr(`blocked: ${describeError(err)}`);
+ }
+ }
+ }
+ }, [sandbox]);
+
+ return (
+ <div data-testid="data-app-sandbox" style={{ padding: 24 }}>
+ <h1 style={{ margin: "0 0 16px" }}>Sandbox</h1>
+ {BLOCKED_PROBES.map((probe) => (
+ <div key={probe.id} data-testid={`probe-${probe.id}`}>
+ {probeResults[probe.id] ?? "pending"}
+ </div>
+ ))}
+ <div data-testid="probe-innerhtml">{innerHtml}</div>
+ <div data-testid="blocked-fetch-result">{blockedFetch}</div>
+ <div data-testid="allowed-fetch-result">{allowedFetch}</div>
+ <div data-testid="blocked-xhr-result">{blockedXhr}</div>
+ <div data-testid="allowed-xhr-result">{allowedXhr}</div>
+ </div>
+ );
+}
+
+function Isolation() {
+ const [cssInjected, setCssInjected] = useState("pending");
+ const [jsMarker, setJsMarker] = useState("pending");
+
+ useEffect(() => {
+ // `createElement("style")` is the one tag the data-app sandbox permits, so
+ // apps can style their own sandboxed document.
+ try {
+ const style = document.createElement("style");
+ style.textContent = `.isolation-css-probe { color: ${PROBE_COLOR}; } body { background-color: ${PROBE_COLOR}; }`;
+ document.head.appendChild(style);
+ setCssInjected("ok");
+ } catch (err) {
+ setCssInjected(`failed: ${describeError(err)}`);
+ }
+
+ try {
+ const globals = globalThis as Record<string, unknown>;
+ globals.__DATA_APP_ISOLATION_MARKER__ = "in-app";
+ setJsMarker(String(globals.__DATA_APP_ISOLATION_MARKER__));
+ } catch (err) {
+ setJsMarker(`failed: ${describeError(err)}`);
+ }
+ }, []);
+
+ return (
+ <div data-testid="data-app-isolation" style={{ padding: 24 }}>
+ <h1 style={{ margin: "0 0 16px" }}>Isolation</h1>
+ <div data-testid="css-injected">{cssInjected}</div>
+ <div data-testid="isolation-css-probe" className="isolation-css-probe">
+ css probe
+ </div>
+ <div data-testid="js-marker">{jsMarker}</div>
+ </div>
+ );
+}
+
+const ROUTES: Record<string, ComponentType> = {
+ "/details": Details,
+ "/sandboxing": Sandbox,
+ "/isolation": Isolation,
+ "/query-states": QueryStates,
+ "/static-question": StaticQuestionPage,
+ "/combinators": Combinators,
+ "/actions": Actions,
+ "/clipboard": Clipboard,
+ "/missing-question": MissingQuestion,
+ "/throw": ThrowingPage,
+};
+
+function Shell() {
+ const { pathname, navigate } = useDataAppLocation();
+ const Page = ROUTES[pathname] ?? Overview;
+
+ return (
+ <div style={{ fontFamily: "sans-serif" }}>
+ <nav
+ style={{
+ padding: 16,
+ borderBottom: "1px solid #e0e0e0",
+ display: "flex",
+ gap: 16,
+ flexWrap: "wrap",
+ }}
+ >
+ <DataAppLink to="/">Overview</DataAppLink>
+ <DataAppLink to="/details">Details</DataAppLink>
+ <DataAppLink to="/sandboxing">Sandbox</DataAppLink>
+ <DataAppLink to="/isolation">Isolation</DataAppLink>
+ <button
+ type="button"
+ data-testid="navigate-to-details"
+ onClick={() => navigate("/details")}
+ >
+ navigate to details
+ </button>
+ </nav>
+
+ <div data-testid="current-pathname" style={{ padding: "0 16px" }}>
+ {pathname}
+ </div>
+
+ <Page />
+ </div>
+ );
+}
+
+export default function App() {
+ return (
+ <DataAppRouter>
+ <Shell />
+ </DataAppRouter>
+ );
+}
diff --git a/e2e/support/assets/data-apps/kitchen-sink/src/index.tsx b/e2e/support/assets/data-apps/kitchen-sink/src/index.tsx
new file mode 100644
index 00000000000..97a94779d6c
--- /dev/null
+++ b/e2e/support/assets/data-apps/kitchen-sink/src/index.tsx
@@ -0,0 +1,7 @@
+import type { DataAppFactory } from "@metabase/embedding-sdk-react/data-app";
+
+import App from "./App";
+
+const factory: DataAppFactory = () => ({ component: App });
+
+export default factory;
diff --git a/e2e/support/assets/data-apps/kitchen-sink/src/test-env.ts b/e2e/support/assets/data-apps/kitchen-sink/src/test-env.ts
new file mode 100644
index 00000000000..c0004477b30
--- /dev/null
+++ b/e2e/support/assets/data-apps/kitchen-sink/src/test-env.ts
@@ -0,0 +1,20 @@
+// The type is the tests' contract and lives with them; this file is only how the
+// app reads it back inside the sandbox realm.
+import type { DataAppTestEnv } from "../../../../helpers/data-app-test-env";
+
+declare global {
+ // eslint-disable-next-line no-var -- `var` (not `const`) so `globalThis.x` typechecks
+ var __METABASE_DATA_APP_TEST_ENV__: DataAppTestEnv | undefined;
+}
+
+export function getTestEnv(): DataAppTestEnv {
+ const env = globalThis.__METABASE_DATA_APP_TEST_ENV__;
+
+ if (!env) {
+ throw new Error(
+ "data-app test env was not injected — pass `testEnv` to H.mockDataApp",
+ );
+ }
+
+ return env;
+}
diff --git a/e2e/support/assets/data-apps/tsconfig.json b/e2e/support/assets/data-apps/tsconfig.json
new file mode 100644
index 00000000000..5775a3ca625
--- /dev/null
+++ b/e2e/support/assets/data-apps/tsconfig.json
@@ -0,0 +1,16 @@
+{
+ "extends": "../../../../tsconfig.json",
+ "compilerOptions": {
+ "noEmit": true,
+ "incremental": false,
+ "rootDir": "../../../.."
+ },
+ "include": [
+ "../../../../frontend/src/types/**/*.d.ts",
+ "../../../../frontend/src/embedding-sdk-shared/types/*.d.ts",
+ "../../../../frontend/src/metabase/utils/dayjs.ts",
+ "*/src/**/*.ts",
+ "*/src/**/*.tsx"
+ ],
+ "exclude": [".build"]
+}
diff --git a/e2e/support/assets/example_synced_data_apps/data_apps/bad-config/data_app.yaml b/e2e/support/assets/example_synced_data_apps/data_apps/bad-config/data_app.yaml
new file mode 100644
index 00000000000..89a1e6b0e9d
--- /dev/null
+++ b/e2e/support/assets/example_synced_data_apps/data_apps/bad-config/data_app.yaml
@@ -0,0 +1 @@
+name: [unterminated
diff --git a/e2e/support/assets/example_synced_data_apps/data_apps/bad-config/index.js b/e2e/support/assets/example_synced_data_apps/data_apps/bad-config/index.js
new file mode 100644
index 00000000000..2d569610c95
--- /dev/null
+++ b/e2e/support/assets/example_synced_data_apps/data_apps/bad-config/index.js
@@ -0,0 +1,2 @@
+// Present, but unreachable: its data_app.yaml can't be parsed, so the app is skipped.
+export default () => ({ component: null });
diff --git a/e2e/support/assets/example_synced_data_apps/data_apps/broken-bundle/data_app.yaml b/e2e/support/assets/example_synced_data_apps/data_apps/broken-bundle/data_app.yaml
new file mode 100644
index 00000000000..400b85650c3
--- /dev/null
+++ b/e2e/support/assets/example_synced_data_apps/data_apps/broken-bundle/data_app.yaml
@@ -0,0 +1,3 @@
+name: Broken Bundle
+# Points at a file that isn't in the repo — a valid config, an un-loadable app.
+path: ./missing.js
diff --git a/e2e/support/assets/example_synced_data_apps/data_apps/good/data_app.yaml b/e2e/support/assets/example_synced_data_apps/data_apps/good/data_app.yaml
new file mode 100644
index 00000000000..800e24a54e0
--- /dev/null
+++ b/e2e/support/assets/example_synced_data_apps/data_apps/good/data_app.yaml
@@ -0,0 +1,2 @@
+name: Good App
+path: ./index.js
diff --git a/e2e/support/assets/example_synced_data_apps/data_apps/good/index.js b/e2e/support/assets/example_synced_data_apps/data_apps/good/index.js
new file mode 100644
index 00000000000..e68ee3ca4c4
--- /dev/null
+++ b/e2e/support/assets/example_synced_data_apps/data_apps/good/index.js
@@ -0,0 +1,3 @@
+// A placeholder bundle — this fixture exercises sync/materialization + the admin
+// listing + the bundle endpoint, not rendering, so the bytes are served opaquely.
+export default () => ({ component: null });
diff --git a/e2e/support/assets/example_synced_data_apps/data_apps/no-config/index.js b/e2e/support/assets/example_synced_data_apps/data_apps/no-config/index.js
new file mode 100644
index 00000000000..9c1c2183649
--- /dev/null
+++ b/e2e/support/assets/example_synced_data_apps/data_apps/no-config/index.js
@@ -0,0 +1,3 @@
+// A bundle with no data_app.yaml beside it — nothing declares this directory an
+// app, so sync doesn't discover it.
+export default () => ({ component: null });
diff --git a/e2e/support/config.js b/e2e/support/config.js
index 58326eac612..aaadc62990c 100644
--- a/e2e/support/config.js
+++ b/e2e/support/config.js
@@ -26,6 +26,7 @@ import {
startCustomVizDevServer,
stopCustomVizDevServer,
} from "./helpers/e2e-custom-viz-dev-server-tasks";
+import { buildDataApp } from "./helpers/e2e-data-app-tasks";
import { signJwt } from "./helpers/e2e-jwt-tasks";
import {
startMockLlmServer,
@@ -215,6 +216,7 @@ const defaultConfig = {
stopMockLlmServer,
startCustomVizDevServer,
stopCustomVizDevServer,
+ buildDataApp,
});
/********************************************************************
diff --git a/e2e/support/helpers/build-data-app-fixture.mjs b/e2e/support/helpers/build-data-app-fixture.mjs
new file mode 100644
index 00000000000..abc41f12ed2
--- /dev/null
+++ b/e2e/support/helpers/build-data-app-fixture.mjs
@@ -0,0 +1,51 @@
+import fs from "node:fs";
+import path from "node:path";
+import { pathToFileURL } from "node:url";
+
+import { build as bundle } from "esbuild";
+import { build } from "vite";
+
+import {
+ BUILD_CONFIGS_DIR,
+ DATA_APP_FIXTURES_DIR,
+ SDK_DATA_APP_DEV_CONFIG_SOURCE,
+} from "./data-app-fixture-paths.mjs";
+
+const appName = process.argv[2];
+if (!appName) {
+ console.error("usage: build-data-app-fixture.mjs <appName>");
+ process.exit(2);
+}
+
+const appDir = path.join(DATA_APP_FIXTURES_DIR, appName);
+
+if (!fs.existsSync(path.join(appDir, "src"))) {
+ console.error(`data-app fixture "${appName}" has no src/ at ${appDir}`);
+ process.exit(2);
+}
+
+const scratchDir = path.join(DATA_APP_FIXTURES_DIR, ".build");
+fs.mkdirSync(scratchDir, { recursive: true });
+const dataAppDevEntry = path.join(scratchDir, `${appName}.data-app-dev.mjs`);
+
+await bundle({
+ entryPoints: [SDK_DATA_APP_DEV_CONFIG_SOURCE],
+ outfile: dataAppDevEntry,
+ bundle: true,
+ platform: "node",
+ format: "esm",
+ packages: "external",
+ alias: { "build-configs": BUILD_CONFIGS_DIR },
+ logLevel: "warning",
+});
+
+const { dataAppConfig } = await import(pathToFileURL(dataAppDevEntry).href);
+
+process.chdir(appDir);
+
+await build({
+ root: appDir,
+ configFile: false,
+ logLevel: "warn",
+ plugins: dataAppConfig().plugins,
+});
diff --git a/e2e/support/helpers/data-app-fixture-paths.mjs b/e2e/support/helpers/data-app-fixture-paths.mjs
new file mode 100644
index 00000000000..fcdf0fd950c
--- /dev/null
+++ b/e2e/support/helpers/data-app-fixture-paths.mjs
@@ -0,0 +1,23 @@
+import { execFileSync } from "node:child_process";
+import path from "node:path";
+
+export const REPO_ROOT = execFileSync("git", ["rev-parse", "--show-toplevel"], {
+ encoding: "utf8",
+}).trim();
+
+export const DATA_APP_FIXTURES_DIR = path.join(
+ REPO_ROOT,
+ "e2e/support/assets/data-apps",
+);
+
+export const DATA_APP_BUILD_SCRIPT = path.join(
+ REPO_ROOT,
+ "e2e/support/helpers/build-data-app-fixture.mjs",
+);
+
+export const SDK_DATA_APP_DEV_CONFIG_SOURCE = path.join(
+ REPO_ROOT,
+ "enterprise/frontend/src/embedding-sdk-package/data-app-dev.config.ts",
+);
+
+export const BUILD_CONFIGS_DIR = path.join(REPO_ROOT, "frontend/build");
diff --git a/e2e/support/helpers/data-app-test-env.ts b/e2e/support/helpers/data-app-test-env.ts
new file mode 100644
index 00000000000..8e177e682a8
--- /dev/null
+++ b/e2e/support/helpers/data-app-test-env.ts
@@ -0,0 +1,56 @@
+import type { LocalFieldReference } from "@metabase/embedding-sdk-react/data-app";
+
+/**
+ * The config a spec injects into a data-app fixture (via `H.mockDataApp`'s
+ * `testEnv`), so a fixture doesn't hard-code values that track the Cypress
+ * snapshot — sample-DB ids, URLs, the id of an action the spec created.
+ *
+ * It lives with the tests rather than inside a fixture because it's the contract
+ * between the two, and the fixtures are standalone SDK apps outside this TS
+ * program (see `exclude` in `e2e/tsconfig.json`). A fixture reads it back at
+ * runtime through its own `getTestEnv()`.
+ */
+export type DataAppTestEnv = {
+ scalarQuery: { source: TableSource; aggregations: CountAggregation[] };
+ questionQuery: { source: TableSource };
+ /**
+ * `/sandboxing` page: URLs it fetches to probe the sandbox's `allowed_hosts`
+ * gate. `allowedUrl` is expected to be in `allowed_hosts`, `blockedUrl` is not.
+ * `xhr*Url` drive the same gate through `XMLHttpRequest`.
+ */
+ sandbox?: {
+ allowedUrl: string;
+ blockedUrl: string;
+ xhrAllowedUrl?: string;
+ xhrBlockedUrl?: string;
+ };
+ /**
+ * `/query-states` page: a deliberately invalid query (bad table id), so the hook
+ * resolves to an `error` state; the page also exercises `refetch`.
+ */
+ errorQuery?: { source: TableSource };
+ /**
+ * `/combinators` page: exercises `filter`/`breakout`/`orderBy`/`aggregations`.
+ * The page hardcodes a `>` filter and a count aggregation ordered desc, so
+ * `filterField` must be numeric; `breakoutField` groups the rows.
+ */
+ combinators?: {
+ source: TableSource;
+ filterField: LocalFieldReference;
+ filterValue: number;
+ breakoutField: LocalFieldReference;
+ };
+ /**
+ * `/actions` page: the id of the action the spec creates and `useAction`
+ * executes, so it can't be hard-coded in the app. Left out to exercise the "no
+ * action id" path, where the hook must not request anything.
+ */
+ actionId?: number;
+ /** `/actions` page: the parameters the page passes to `execute()`. */
+ actionParams?: Record<string, string | number>;
+};
+
+// The queries use the SDK's `source` API (`{ type: "table", id }`); the database
+// is resolved from the SDK's metadata store, so no databaseId is passed.
+type TableSource = { type: "table"; id: number };
+type CountAggregation = { type: "operator"; operator: "count"; args: [] };
diff --git a/e2e/support/helpers/e2e-data-app-helpers.ts b/e2e/support/helpers/e2e-data-app-helpers.ts
new file mode 100644
index 00000000000..981d108f00a
--- /dev/null
+++ b/e2e/support/helpers/e2e-data-app-helpers.ts
@@ -0,0 +1,130 @@
+import * as Urls from "metabase/urls/data-apps";
+import type { DataApp } from "metabase-types/api";
+
+import type { DataAppTestEnv } from "./data-app-test-env";
+import { getIframeBody } from "./e2e-embedding-helpers";
+import { LOCAL_GIT_PATH } from "./e2e-remote-sync-helpers";
+
+export const SYNCED_DATA_APPS_FIXTURE_PATH =
+ Cypress.config("projectRoot") +
+ "/e2e/support/assets/example_synced_data_apps";
+
+/**
+ * Copy the example data-app repo into the working directory of the local git repo
+ * `setupGitSync` created, so a `commitToRepo` + a real pull materialize its apps.
+ * The repo holds one directory per materialization outcome (a good app, an app
+ * whose bundle is missing, a malformed config, and a directory with no config) —
+ * see the fixture and the sync spec that drives it.
+ */
+export const copySyncedDataAppsFixture = () =>
+ cy.task("copyDirectory", {
+ source: SYNCED_DATA_APPS_FIXTURE_PATH,
+ destination: LOCAL_GIT_PATH,
+ });
+
+/**
+ * The e2e data-app fixture that `mockDataApp` builds and serves — its directory
+ * name and its `/apps/<slug>` URL segment. One bundle with a page per surface it
+ * exercises (questions, query hooks, actions, clipboard, sandbox, isolation), so
+ * the specs share a single build.
+ */
+export const DATA_APP_NAME = "kitchen-sink";
+export const DATA_APP_DISPLAY_NAME = "Kitchen Sink";
+
+/**
+ * Visit a nested route inside the fixture data app. `openDataApp` encodes the
+ * slug, so it can't carry a sub-path — deep-links go through a raw `cy.visit`.
+ */
+export const visitDataAppRoute = (route: string) =>
+ cy.visit(`/apps/${DATA_APP_NAME}/${route}`);
+
+/**
+ * A minimal `DataApp`-shaped row. Admin-list state tests use it directly (they
+ * only assert how the management UI renders the list, no real bundle needed);
+ * `mockDataApp` uses it for the intercepted metadata of the built fixture.
+ */
+export const fakeDataApp = (overrides: Partial<DataApp> = {}): DataApp => ({
+ id: 1,
+ name: DATA_APP_NAME,
+ display_name: DATA_APP_DISPLAY_NAME,
+ bundle_path: `data_apps/${DATA_APP_NAME}/dist/index.js`,
+ enabled: true,
+ allowed_hosts: [],
+ bundle_hash: "e2e-bundle-hash",
+ last_synced_sha: "e2e0000",
+ last_synced_at: "2024-01-01T00:00:00Z",
+ sync_error: null,
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:00Z",
+ ...overrides,
+});
+
+type MockDataAppOptions<TestEnv> = {
+ /** Display name (iframe title + admin list); defaults to the fixture dir name. */
+ displayName?: string;
+ /** `allowed_hosts` served in the bundle response header. */
+ allowedHosts?: string[];
+ /**
+ * Config a fixture reads at runtime, so it doesn't hard-code values that track
+ * the Cypress snapshot (e.g. sample-DB ids). It's JSON-serialized and prepended
+ * to the served bundle as `globalThis.__METABASE_DATA_APP_TEST_ENV__`; since the
+ * bundle is evaluated as one script in the sandbox realm, the app reads it as a
+ * plain global. Typed by `DataAppTestEnv` by default; pass another fixture's
+ * type as `TestEnv` if it differs.
+ */
+ testEnv?: TestEnv;
+};
+
+/**
+ * Set up a data app for the current test
+ */
+export const mockDataApp = <TestEnv = DataAppTestEnv>(
+ appName: string,
+ options: MockDataAppOptions<TestEnv> = {},
+) => {
+ const slug = appName;
+ const displayName = options.displayName ?? appName;
+ const allowedHosts = options.allowedHosts ?? [];
+
+ // Prelude runs in the sandbox realm before the bundle's factory, so the app
+ // can read the injected config as a global (see MockDataAppOptions.testEnv).
+ const prelude =
+ options.testEnv !== undefined
+ ? `globalThis.__METABASE_DATA_APP_TEST_ENV__ = ${JSON.stringify(options.testEnv)};\n`
+ : "";
+
+ return cy.task<string>("buildDataApp", { appName }).then((bundleCode) => {
+ const app = fakeDataApp({
+ name: slug,
+ display_name: displayName,
+ allowed_hosts: allowedHosts,
+ });
+
+ cy.intercept("GET", "/api/apps/repo-status", {
+ configured: true,
+ });
+ cy.intercept("GET", "/api/apps", [app]);
+ cy.intercept({ method: "GET", pathname: `/api/apps/${slug}` }, app);
+ cy.intercept(
+ { method: "GET", pathname: `/api/apps/${slug}/bundle` },
+ {
+ statusCode: 200,
+ headers: {
+ "content-type": "text/javascript",
+ "X-Metabase-Data-App-Allowed-Hosts": JSON.stringify(allowedHosts),
+ },
+ body: prelude + bundleCode,
+ },
+ );
+
+ return cy.wrap({ slug, displayName }, { log: false });
+ });
+};
+
+export function openDataApp(slug: string) {
+ return cy.visit(Urls.dataApp(slug));
+}
+
+export function dataAppIframe(displayName: string) {
+ return getIframeBody(`iframe[title="${displayName}"]`);
+}
diff --git a/e2e/support/helpers/e2e-data-app-tasks.ts b/e2e/support/helpers/e2e-data-app-tasks.ts
new file mode 100644
index 00000000000..724e9e0f6e9
--- /dev/null
+++ b/e2e/support/helpers/e2e-data-app-tasks.ts
@@ -0,0 +1,52 @@
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+
+import {
+ DATA_APP_BUILD_SCRIPT,
+ DATA_APP_FIXTURES_DIR,
+ REPO_ROOT,
+} from "./data-app-fixture-paths.mjs";
+
+/**
+ * Cypress task: build a data-app fixture and return its bundle code.
+ */
+export async function buildDataApp({
+ appName,
+}: {
+ appName: string;
+}): Promise<string> {
+ const appDir = path.join(DATA_APP_FIXTURES_DIR, appName);
+
+ if (!fs.existsSync(path.join(appDir, "src"))) {
+ throw new Error(`data-app fixture "${appName}" has no src/ at ${appDir}`);
+ }
+
+ await new Promise<void>((resolve, reject) => {
+ const child = spawn(process.execPath, [DATA_APP_BUILD_SCRIPT, appName], {
+ cwd: REPO_ROOT,
+ stdio: ["ignore", "inherit", "inherit"],
+ });
+
+ child.on("error", reject);
+ child.on("exit", (code) =>
+ code === 0
+ ? resolve()
+ : reject(
+ new Error(
+ `data-app build for "${appName}" exited with code ${code}`,
+ ),
+ ),
+ );
+ });
+
+ const bundlePath = path.join(DATA_APP_FIXTURES_DIR, appName, "dist/index.js");
+
+ if (!fs.existsSync(bundlePath)) {
+ throw new Error(
+ `data-app build for "${appName}" produced no bundle at ${bundlePath}`,
+ );
+ }
+
+ return fs.readFileSync(bundlePath, "utf8");
+}
diff --git a/e2e/support/helpers/index.ts b/e2e/support/helpers/index.ts
index f0ec0ffb3f1..1d4ffd84e7a 100644
--- a/e2e/support/helpers/index.ts
+++ b/e2e/support/helpers/index.ts
@@ -13,6 +13,8 @@ export * from "./e2e-command-palette-helpers";
export * from "./e2e-comment-helpers";
export * from "./e2e-custom-column-helpers";
export * from "./e2e-custom-viz-helpers";
+export * from "./data-app-test-env";
+export * from "./e2e-data-app-helpers";
export * from "./e2e-dashboard-helpers";
export * from "./e2e-dashboard-visualizer-helpers";
export * from "./e2e-data-studio-helpers";
diff --git a/e2e/test-component/scenarios/embedding-sdk/sdk-question-card-prop.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/sdk-question-card-prop.cy.spec.tsx
new file mode 100644
index 00000000000..44dc7023f74
--- /dev/null
+++ b/e2e/test-component/scenarios/embedding-sdk/sdk-question-card-prop.cy.spec.tsx
@@ -0,0 +1,75 @@
+import {
+ InteractiveQuestion,
+ type MetabaseCard,
+ StaticQuestion,
+} from "@metabase/embedding-sdk-react";
+
+import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";
+import { mountSdkContent } from "e2e/support/helpers/embedding-sdk-component-testing";
+import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";
+import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";
+
+const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;
+
+// What a data app actually passes: a `card` object built from a query (e.g. the
+// output of `createMetabaseQuery` / `useMetabaseQueryObject`) plus the chosen
+// `visualization` and its `visualizationSettings`. The serialized-string form is
+// an edge case covered by the unit tests; here we verify the data-app path
+// renders the chosen chart end-to-end.
+const card: MetabaseCard = {
+ query: {
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["max", ["field", ORDERS.QUANTITY, null]]],
+ breakout: [["field", ORDERS.PRODUCT_ID, null]],
+ limit: 2,
+ },
+ },
+ visualization: "bar",
+ visualizationSettings: {
+ "graph.y_axis.title_text": "Max quantity",
+ },
+};
+
+describe("scenarios > embedding-sdk > sdk-question card prop", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+
+ cy.signOut();
+ mockAuthProviderAndJwtSignIn();
+
+ cy.intercept("POST", "/api/dataset").as("dataset");
+ });
+
+ it("InteractiveQuestion should render the chosen visualization from the `card` prop", () => {
+ mountSdkContent(<InteractiveQuestion card={card} />);
+
+ cy.wait("@dataset").then(({ response }) => {
+ expect(response?.statusCode).to.equal(202);
+ });
+
+ getSdkRoot().within(() => {
+ cy.log("renders the chart, honoring the chosen `bar` visualization");
+ cy.findByTestId("visualization-root").should("be.visible");
+ cy.findByTestId("table-root").should("not.exist");
+ });
+ });
+
+ it("StaticQuestion should render the chosen visualization from the `card` prop", () => {
+ mountSdkContent(<StaticQuestion card={card} />);
+
+ cy.wait("@dataset").then(({ response }) => {
+ expect(response?.statusCode).to.equal(202);
+ });
+
+ getSdkRoot().within(() => {
+ cy.log("renders the chart, honoring the chosen `bar` visualization");
+ cy.findByTestId("visualization-root").should("be.visible");
+ cy.findByTestId("table-root").should("not.exist");
+ });
+ });
+});
diff --git a/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx
index 79c824a2507..f84ae2e785d 100644
--- a/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx
+++ b/e2e/test-component/scenarios/embedding-sdk/static-question.cy.spec.tsx
@@ -6,6 +6,7 @@ import {
type StaticQuestionProps,
} from "@metabase/embedding-sdk-react";
+import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import { createQuestion, modal, popover } from "e2e/support/helpers";
import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";
@@ -281,4 +282,43 @@ describe("scenarios > embedding-sdk > static-question", () => {
getSdkRoot().button("Alerts").should("be.visible");
});
});
+
+ it("should not request /api/card/undefined when clicking a data point on a query-only ad-hoc card", () => {
+ // A query-only ad-hoc card has no saved card id. A static question must not
+ // navigate on a chart click — previously it did, fetching
+ // `GET /api/card/undefined` (the new card's id was `undefined`).
+ cy.intercept("GET", "/api/card/undefined").as("getUndefinedCard");
+
+ mountSdkContent(
+ <StaticQuestion
+ card={{
+ query: {
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [
+ ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
+ ],
+ limit: 5,
+ },
+ },
+ }}
+ />,
+ );
+
+ getSdkRoot().within(() => {
+ cy.log("the aggregated query renders a cartesian chart");
+ H.cartesianChartCircle().should("have.length.greaterThan", 0);
+
+ cy.log("clicking a data point must not navigate to a new card");
+ H.cartesianChartCircle().first().click();
+
+ // The chart stays put (retry gives any erroneous navigation time to fire).
+ H.cartesianChartCircle().should("have.length.greaterThan", 0);
+ });
+
+ cy.get("@getUndefinedCard.all").should("have.length", 0);
+ });
});
diff --git a/e2e/test/scenarios/data-apps/actions.cy.spec.ts b/e2e/test/scenarios/data-apps/actions.cy.spec.ts
new file mode 100644
index 00000000000..d7af613db87
--- /dev/null
+++ b/e2e/test/scenarios/data-apps/actions.cy.spec.ts
@@ -0,0 +1,103 @@
+import { WRITABLE_DB_ID } from "e2e/support/cypress_data";
+import {
+ DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,
+ DATA_APP_NAME as APP_NAME,
+ visitDataAppRoute as visitAppRoute,
+} from "e2e/support/helpers";
+
+import { DATA_APP_TEST_ENV as TEST_ENV } from "./helpers";
+
+const { H } = cy;
+
+const TEST_TABLE = "scoreboard_actions";
+const MODEL_NAME = "Scoreboard model";
+const EXISTING_TEAM = "Amorous Aardvarks";
+
+describe(
+ "scenarios > data apps > actions (useAction)",
+ { tags: ["@external", "@actions"] },
+ () => {
+ beforeEach(() => {
+ H.restore("postgres-writable");
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+
+ H.resetTestTable({ type: "postgres", table: TEST_TABLE });
+ H.resyncDatabase({ dbId: WRITABLE_DB_ID, tableName: TEST_TABLE });
+ H.setActionsEnabledForDB(WRITABLE_DB_ID);
+ H.createModelFromTableName({
+ tableName: TEST_TABLE,
+ modelName: MODEL_NAME,
+ });
+ });
+
+ const setupActionsApp = (actionParams: Record<string, string | number>) =>
+ cy.get("@modelId").then((modelId) => {
+ H.createImplicitAction({
+ model_id: modelId,
+ kind: "create",
+ }).then(({ body: action }) => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: { ...TEST_ENV, actionId: action.id, actionParams },
+ });
+ });
+ });
+
+ it("executes the action, exposing isExecuting and result, and resets", () => {
+ cy.intercept("POST", "/api/action/*/execute", (req) => {
+ req.on("response", (res) => res.setDelay(300));
+ });
+
+ setupActionsApp({ team_name: "Data App FC", score: 7 });
+
+ visitAppRoute("actions");
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByTestId("action-execute").click();
+ cy.findByTestId("action-executing").should("have.text", "executing");
+
+ cy.findByTestId("action-result", { timeout: 30000 }).should(
+ "have.text",
+ "has-result",
+ );
+ cy.findByTestId("action-output").should("have.text", "returned-result");
+ cy.findByTestId("action-error").should("have.text", "no-error");
+
+ cy.findByTestId("action-reset").click();
+ cy.findByTestId("action-result").should("have.text", "no-result");
+ });
+
+ H.queryWritableDB(
+ `SELECT team_name, score FROM ${TEST_TABLE} WHERE team_name = 'Data App FC'`,
+ ).then(({ rows }) => {
+ expect(rows).to.have.length(1);
+ expect(rows[0].score).to.eq(7);
+ });
+ });
+
+ it("surfaces an error when the action fails", () => {
+ // `team_name` is unique, so creating a team that already exists fails in the
+ // database — a real rejection, not a stubbed one.
+ setupActionsApp({ team_name: EXISTING_TEAM, score: 1 });
+
+ visitAppRoute("actions");
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByTestId("action-execute").click();
+
+ cy.findByTestId("action-error", { timeout: 30000 }).should(
+ "have.text",
+ "has-error",
+ );
+ cy.findByTestId("action-result").should("have.text", "no-result");
+ cy.findByTestId("action-executing").should("have.text", "idle");
+ });
+
+ H.queryWritableDB(
+ `SELECT team_name FROM ${TEST_TABLE} WHERE team_name = '${EXISTING_TEAM}'`,
+ ).then(({ rows }) => {
+ // Nothing was written - the existing team is still the only one.
+ expect(rows).to.have.length(1);
+ });
+ });
+ },
+);
diff --git a/e2e/test/scenarios/data-apps/admin.cy.spec.ts b/e2e/test/scenarios/data-apps/admin.cy.spec.ts
new file mode 100644
index 00000000000..454c30ea212
--- /dev/null
+++ b/e2e/test/scenarios/data-apps/admin.cy.spec.ts
@@ -0,0 +1,106 @@
+import {
+ DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,
+ DATA_APP_NAME as APP_NAME,
+} from "e2e/support/helpers";
+
+import { DATA_APP_TEST_ENV as TEST_ENV } from "./helpers";
+
+const { H } = cy;
+
+describe("scenarios > data apps > admin management", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ // `bleeding-edge` grants the `data-apps` premium feature; requires the EE build.
+ H.activateToken("bleeding-edge");
+ });
+
+ it("Happy Path: lists a data app and renders it in its sandboxed iframe with real SDK data", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: TEST_ENV,
+ });
+
+ cy.visit("/admin/settings/apps");
+ cy.findByRole("link", { name: APP_DISPLAY_NAME })
+ .scrollIntoView()
+ .should("be.visible");
+
+ cy.intercept("POST", "/api/dataset").as("dataAppQuery");
+
+ H.openDataApp(APP_NAME);
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByRole("heading", { name: "Orders overview" }).should(
+ "be.visible",
+ );
+
+ cy.findByTestId("orders-count", { timeout: 30000 })
+ .invoke("text")
+ .should("match", /^\d+$/);
+
+ cy.findByText("Subtotal", { timeout: 30000 }).should("be.visible");
+ });
+
+ // The iframe's query requests must be attributed to the data app, so
+ // query_execution analytics record which app ran them (EMB-2088).
+ cy.wait("@dataAppQuery").then(({ request }) => {
+ expect(request.headers["x-metabase-client"]).to.equal("data-app");
+ expect(request.headers["x-metabase-client-identifier"]).to.equal(
+ APP_NAME,
+ );
+ });
+ });
+
+ it("dismisses the promo banner and keeps it hidden across a reload", () => {
+ cy.intercept("GET", "/api/apps/repo-status", { configured: true });
+ cy.intercept("GET", "/api/apps", []);
+ cy.intercept(
+ "PUT",
+ "/api/user-key-value/namespace/user_acknowledgement/key/data-apps-admin-settings-banner",
+ ).as("ackBanner");
+
+ cy.visit("/admin/settings/apps");
+
+ H.main()
+ .findByText(/AI-generated React apps/)
+ .should("be.visible");
+ cy.findByRole("button", { name: "Dismiss" }).click();
+ cy.wait("@ackBanner");
+ H.main()
+ .findByText(/AI-generated React apps/)
+ .should("not.exist");
+
+ // The dismissal persists (a real user-key-value write), so a reload keeps it hidden.
+ cy.reload();
+ cy.findByRole("heading", { name: "Data apps" }).should("be.visible");
+ H.main()
+ .findByText(/AI-generated React apps/)
+ .should("not.exist");
+ });
+});
+
+describe("scenarios > data apps > upsell (OSS)", { tags: "@OSS" }, () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ // No token: on the OSS build the `data-apps` feature is unavailable, so the
+ // settings page shows the upsell instead of the management UI.
+ });
+
+ it("shows the data-apps upsell instead of the management UI", () => {
+ cy.visit("/admin/settings/apps");
+
+ H.main().within(() => {
+ cy.findByText("Build apps on your data").should("be.visible");
+ cy.findByText("Try for free").should("be.visible");
+ });
+ });
+
+ it("marks the Data apps settings nav item with an upsell gem", () => {
+ cy.visit("/admin/settings/apps");
+
+ cy.findByRole("link", { name: /Data apps/ }).within(() => {
+ cy.findByTestId("upsell-gem").should("exist");
+ });
+ });
+});
diff --git a/e2e/test/scenarios/data-apps/helpers/index.ts b/e2e/test/scenarios/data-apps/helpers/index.ts
new file mode 100644
index 00000000000..95fc15b7ea1
--- /dev/null
+++ b/e2e/test/scenarios/data-apps/helpers/index.ts
@@ -0,0 +1,38 @@
+import type { LocalFieldReference } from "@metabase/embedding-sdk-react/data-app";
+
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import type { DataAppTestEnv } from "e2e/support/helpers";
+
+// These live here (co-located with the specs) rather than in
+// `e2e/support/helpers/e2e-data-app-helpers.ts`: that file is part of the
+// Cypress support bundle, and importing `cypress_sample_database` there would
+// pull the git-ignored `cypress_sample_database.json` into the snapshot-creation
+// build — before that file is generated. Specs are bundled only after it exists.
+
+const { ORDERS_ID } = SAMPLE_DATABASE;
+
+/**
+ * A numeric field dimension for the query-builder combinators, hand-built the way
+ * an app without a generated `metabase.data.ts` schema would build one.
+ */
+export const dataAppNumericField = (
+ fieldId: number,
+ name: string,
+): LocalFieldReference => ({
+ type: "column",
+ fieldId,
+ tableId: ORDERS_ID,
+ name,
+ jsType: "number",
+});
+
+const source = { type: "table" as const, id: ORDERS_ID };
+
+/** The `testEnv` the fixture's Overview page reads (Orders count + question). */
+export const DATA_APP_TEST_ENV: DataAppTestEnv = {
+ scalarQuery: {
+ source,
+ aggregations: [{ type: "operator", operator: "count", args: [] }],
+ },
+ questionQuery: { source },
+};
diff --git a/e2e/test/scenarios/data-apps/sandbox.cy.spec.ts b/e2e/test/scenarios/data-apps/sandbox.cy.spec.ts
new file mode 100644
index 00000000000..c3f956e8cfa
--- /dev/null
+++ b/e2e/test/scenarios/data-apps/sandbox.cy.spec.ts
@@ -0,0 +1,210 @@
+import {
+ DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,
+ DATA_APP_NAME as APP_NAME,
+ visitDataAppRoute as visitAppRoute,
+} from "e2e/support/helpers";
+
+import { DATA_APP_TEST_ENV as TEST_ENV } from "./helpers";
+
+const { H } = cy;
+
+describe("scenarios > data apps > sandbox & isolation", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ // `bleeding-edge` grants the `data-apps` premium feature; requires the EE build.
+ H.activateToken("bleeding-edge");
+ });
+
+ describe("sandboxing", () => {
+ const ALLOWED_ORIGIN = "https://allowed.data-app.test";
+ const ALLOWED_URL = `${ALLOWED_ORIGIN}/ping`;
+ const BLOCKED_URL = "https://blocked.data-app.test/ping";
+
+ it("blocks disallowed APIs and cross-origin fetch, but permits allowed_hosts", () => {
+ // The allowed host is stubbed with a CORS header so the sandbox's real
+ // network call resolves; the blocked host is never intercepted because the
+ // sandbox rejects it before it reaches the network.
+ cy.intercept("GET", ALLOWED_URL, {
+ statusCode: 200,
+ headers: { "access-control-allow-origin": "*" },
+ body: "pong",
+ });
+
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ allowedHosts: [ALLOWED_ORIGIN],
+ testEnv: {
+ ...TEST_ENV,
+ sandbox: { allowedUrl: ALLOWED_URL, blockedUrl: BLOCKED_URL },
+ },
+ });
+
+ H.openDataApp(APP_NAME);
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByRole("heading", { name: "Orders overview" }).should(
+ "be.visible",
+ );
+ cy.findByRole("link", { name: "Sandbox" }).click();
+
+ // A blocked DOM API throws synchronously inside the sandbox.
+ cy.findByTestId("probe-script", { timeout: 30000 }).should(
+ "have.text",
+ "blocked",
+ );
+
+ // A fetch to a host not in allowed_hosts is rejected by the sandbox.
+ cy.findByTestId("blocked-fetch-result", { timeout: 30000 }).should(
+ "contain",
+ "not in allowed_hosts",
+ );
+
+ // A fetch to a host in allowed_hosts reaches the (stubbed) network.
+ cy.findByTestId("allowed-fetch-result", { timeout: 30000 }).should(
+ "have.text",
+ "ok: 200",
+ );
+ });
+ });
+ });
+
+ describe("sandbox breadth", () => {
+ const ALLOWED_ORIGIN = "https://allowed.data-app.test";
+ const ALLOWED_URL = `${ALLOWED_ORIGIN}/ping`;
+ const BLOCKED_URL = "https://blocked.data-app.test/ping";
+
+ // Method/constructor calls the sandbox distortion replaces with a throwing
+ // shim. (Getter-only reads like `localStorage` aren't intercepted, so they
+ // aren't asserted here.)
+ const BLOCKED_PROBE_IDS = [
+ "script",
+ "window-open",
+ "alert",
+ "history",
+ "keydown-listener",
+ "websocket",
+ "sendbeacon",
+ ];
+
+ it("blocks a broad set of dangerous globals, strips innerHTML, and gates XHR", () => {
+ cy.intercept("GET", ALLOWED_URL, {
+ statusCode: 200,
+ headers: { "access-control-allow-origin": "*" },
+ body: "pong",
+ });
+
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ allowedHosts: [ALLOWED_ORIGIN],
+ testEnv: {
+ ...TEST_ENV,
+ sandbox: {
+ allowedUrl: ALLOWED_URL,
+ blockedUrl: BLOCKED_URL,
+ xhrAllowedUrl: ALLOWED_URL,
+ xhrBlockedUrl: BLOCKED_URL,
+ },
+ },
+ });
+
+ visitAppRoute("sandboxing");
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ BLOCKED_PROBE_IDS.forEach((id) => {
+ cy.findByTestId(`probe-${id}`, { timeout: 30000 }).should(
+ "have.text",
+ "blocked",
+ );
+ });
+
+ cy.findByTestId("probe-innerhtml").should("have.text", "stripped");
+
+ // XHR obeys the same allowlist as fetch.
+ cy.findByTestId("blocked-xhr-result").should("contain", "blocked");
+ cy.findByTestId("allowed-xhr-result", { timeout: 30000 }).should(
+ "have.text",
+ "ok: 200",
+ );
+ });
+ });
+ });
+
+ describe("isolation", () => {
+ const openIsolationPage = () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: TEST_ENV,
+ });
+ H.openDataApp(APP_NAME);
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByRole("heading", { name: "Orders overview" }).should(
+ "be.visible",
+ );
+ cy.findByRole("link", { name: "Isolation" }).click();
+ });
+ };
+
+ it("keeps the app's CSS inside the iframe", () => {
+ openIsolationPage();
+
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ // The injected <style> applies to the app's own document.
+ cy.findByTestId("css-injected").should("have.text", "ok");
+ cy.findByTestId("isolation-css-probe").should(
+ "have.css",
+ "color",
+ "rgb(0, 128, 0)",
+ );
+ });
+
+ // The aggressive `body` rule injected in the iframe does not reach the
+ // parent document.
+ cy.get("body").should(
+ "not.have.css",
+ "background-color",
+ "rgb(0, 128, 0)",
+ );
+ });
+
+ it("keeps the app's JS globals out of the parent realm (near-membrane)", () => {
+ openIsolationPage();
+
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ // The app set the global in its own realm and read it back.
+ cy.findByTestId("js-marker").should("have.text", "in-app");
+ });
+
+ // The parent window never sees the app's global.
+ cy.window().should("not.have.property", "__DATA_APP_ISOLATION_MARKER__");
+ });
+ });
+
+ describe("iframe security headers", () => {
+ it("serves the embed document with the expected CSP + framing headers", () => {
+ cy.request({
+ url: `/embed/apps/${APP_NAME}`,
+ failOnStatusCode: false,
+ }).then((res) => {
+ const csp = String(res.headers["content-security-policy"] ?? "");
+ expect(csp).to.contain("frame-ancestors 'self'");
+ expect(csp).to.contain("default-src 'none'");
+ expect(csp).to.contain("form-action 'none'");
+ expect(csp).to.contain("'unsafe-eval'");
+ expect(String(res.headers["x-frame-options"] ?? "")).to.match(
+ /sameorigin/i,
+ );
+ });
+ });
+
+ it("renders the app in a locked-down sandboxed iframe", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: TEST_ENV,
+ });
+
+ H.openDataApp(APP_NAME);
+ cy.get(`iframe[title="${APP_DISPLAY_NAME}"]`)
+ .should("have.attr", "sandbox")
+ .and("contain", "allow-scripts");
+ });
+ });
+});
diff --git a/e2e/test/scenarios/data-apps/sdk.cy.spec.ts b/e2e/test/scenarios/data-apps/sdk.cy.spec.ts
new file mode 100644
index 00000000000..522eabdffe9
--- /dev/null
+++ b/e2e/test/scenarios/data-apps/sdk.cy.spec.ts
@@ -0,0 +1,203 @@
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import {
+ DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,
+ DATA_APP_NAME as APP_NAME,
+ visitDataAppRoute as visitAppRoute,
+} from "e2e/support/helpers";
+
+import {
+ DATA_APP_TEST_ENV as TEST_ENV,
+ dataAppNumericField as numericField,
+} from "./helpers";
+
+const { ORDERS_ID, ORDERS } = SAMPLE_DATABASE;
+
+const { H } = cy;
+
+describe("scenarios > data apps > SDK runtime", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ // `bleeding-edge` grants the `data-apps` premium feature; requires the EE build.
+ H.activateToken("bleeding-edge");
+ });
+
+ describe("query hooks & question components", () => {
+ const setupQueryStatesApp = () =>
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: {
+ ...TEST_ENV,
+ // A table id that doesn't exist → the query resolves to an error.
+ errorQuery: { source: { type: "table", id: 999999 } },
+ },
+ });
+
+ it("surfaces the useMetabaseQuery error state", () => {
+ setupQueryStatesApp();
+
+ visitAppRoute("query-states");
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByTestId("query-error", { timeout: 30000 }).should(
+ "have.text",
+ "error",
+ );
+ });
+ });
+
+ it("re-runs the query when the app calls refetch", () => {
+ cy.intercept("POST", "/api/dataset").as("datasetQuery");
+ setupQueryStatesApp();
+
+ visitAppRoute("query-states");
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ // The query has to have resolved before refetching means anything.
+ cy.findByTestId("query-value", { timeout: 30000 })
+ .invoke("text")
+ .should("match", /^\d+$/);
+ });
+
+ // A refetch of a query that already succeeded renders the same value, so the
+ // request going out again is the only thing that proves refetch did anything.
+ cy.get("@datasetQuery.all").then((queriesBefore) => {
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByTestId("query-refetch").click();
+ });
+
+ cy.get("@datasetQuery.all").should(
+ "have.length",
+ queriesBefore.length + 1,
+ );
+ });
+ });
+
+ it("renders a StaticQuestion from useMetabaseQueryObject", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: TEST_ENV,
+ });
+
+ visitAppRoute("static-question");
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ // A rendered value, not just the header: the hook's query object has to
+ // have actually run.
+ cy.findAllByTestId("header-cell", { timeout: 30000 }).then(
+ ($headers) => {
+ const subtotalIndex = [...$headers].findIndex(
+ (header) => header.textContent?.trim() === "Subtotal",
+ );
+ expect(subtotalIndex, "Subtotal column").to.be.at.least(0);
+
+ // Cells are row-major, so the first row's Subtotal sits at the
+ // column's own index.
+ cy.findByTestId("table-body")
+ .findAllByTestId("cell-data")
+ .should("have.length.greaterThan", subtotalIndex)
+ .then(($cells) => {
+ const subtotal = $cells.eq(subtotalIndex).text();
+ expect(parseFloat(subtotal.replace(/[^\d.]/g, ""))).to.be.above(
+ 0,
+ );
+ });
+ },
+ );
+ });
+ });
+
+ it("builds a query with filter/breakout/orderBy/aggregations helpers", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: {
+ ...TEST_ENV,
+ combinators: {
+ source: { type: "table", id: ORDERS_ID },
+ filterField: numericField(ORDERS.TOTAL, "TOTAL"),
+ filterValue: 50,
+ breakoutField: numericField(ORDERS.PRODUCT_ID, "PRODUCT_ID"),
+ },
+ },
+ });
+
+ visitAppRoute("combinators");
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByTestId("combinators-loading", { timeout: 30000 }).should(
+ "have.text",
+ "done",
+ );
+ cy.findByTestId("combinators-error").should("have.text", "no-error");
+ // `.should(callback)` retries until the query resolves with rows.
+ cy.findByTestId("combinators-rowcount", { timeout: 30000 }).should(
+ ($el) => {
+ expect(Number($el.text())).to.be.greaterThan(0);
+ },
+ );
+ });
+ });
+ });
+
+ describe("clipboard (copy)", () => {
+ it("writes text to the clipboard from a user click", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: TEST_ENV,
+ });
+
+ visitAppRoute("clipboard");
+
+ // Headless Chrome reports the iframe document as unfocused, so the real
+ // `navigator.clipboard.writeText` rejects ("Document is not focused").
+ // Stub it: the test still verifies the app reaches the sanctioned `copy`
+ // (not blocked by the sandbox) with the right text — the OS write itself
+ // is browser behavior, not ours.
+ H.dataAppIframe(APP_DISPLAY_NAME).then(($body) => {
+ const win = $body[0].ownerDocument.defaultView;
+ if (win) {
+ const writeText = cy.stub(win.navigator.clipboard, "writeText");
+ writeText.resolves();
+ writeText.as("writeText");
+ }
+ });
+
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByTestId("clipboard-copy").click();
+ cy.findByTestId("clipboard-status", { timeout: 30000 }).should(
+ "have.text",
+ "copied",
+ );
+ });
+
+ cy.get("@writeText").should(
+ "have.been.calledOnceWith",
+ "data-app-clipboard-payload",
+ );
+ });
+ });
+
+ describe("error component", () => {
+ it("shows the default neutral error state for a missing question", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: TEST_ENV,
+ });
+
+ visitAppRoute("missing-question");
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByText(/not found/i, { timeout: 30000 }).should("be.visible");
+ });
+ });
+
+ it("lets an app override the default with its own errorComponent", () => {
+ const CUSTOM_APP = "custom-error-component";
+ const CUSTOM_DISPLAY = "Custom Error App";
+
+ H.mockDataApp(CUSTOM_APP, { displayName: CUSTOM_DISPLAY });
+
+ H.openDataApp(CUSTOM_APP);
+ H.dataAppIframe(CUSTOM_DISPLAY).within(() => {
+ cy.findByTestId("custom-error-component", { timeout: 30000 })
+ .should("be.visible")
+ .and("contain", "Custom app error");
+ });
+ });
+ });
+});
diff --git a/e2e/test/scenarios/data-apps/sync.cy.spec.ts b/e2e/test/scenarios/data-apps/sync.cy.spec.ts
new file mode 100644
index 00000000000..81c06129f34
--- /dev/null
+++ b/e2e/test/scenarios/data-apps/sync.cy.spec.ts
@@ -0,0 +1,95 @@
+const { H } = cy;
+
+/**
+ * Drives a real remote-sync pull of a repo whose `data_apps/` covers every
+ * materialization outcome, and asserts each is handled the way the backend
+ * intends (see `data-apps.sync` / `data-apps.config`):
+ *
+ * good/ valid config + bundle -> materialized, served
+ * broken-bundle/ valid config, missing bundle -> row with "Sync failed", not served
+ * bad-config/ malformed data_app.yaml -> skipped, no row
+ * no-config/ a bundle but no data_app.yaml -> not discovered, no row
+ *
+ * A bad app never blocks a good one, and neither a bad config nor a missing
+ * bundle removes an app that isn't theirs.
+ */
+describe("scenarios > data apps > repo sync", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ H.setupGitSync();
+ });
+
+ it("materializes each app per its config/bundle, isolating the broken ones", () => {
+ H.copySyncedCollectionFixture();
+ H.copySyncedDataAppsFixture();
+ H.commitToRepo("Add data apps with mixed config/bundle states");
+
+ H.configureGitAndPullChanges("read-write");
+
+ cy.visit("/admin/settings/apps");
+ cy.findByTestId("admin-layout-content").within(() => {
+ // The good app is materialized and shown as synced. Scope to its own row so
+ // its status can't be satisfied by another app's — a "Sync failed" leaking
+ // onto the good app (or "Synced" onto the broken one) must fail the test.
+ cy.findByTestId("data-app-list-item-good")
+ .scrollIntoView()
+ .within(() => {
+ cy.findByRole("link", { name: "Good App" }).should("be.visible");
+ cy.findByText(/^Synced/).should("be.visible");
+ });
+
+ // The app whose bundle is missing still appears — with its failure, not hidden.
+ // Its name is plain text, not a link: a sync-failed app can't be opened.
+ cy.findByTestId("data-app-list-item-broken-bundle")
+ .scrollIntoView()
+ .within(() => {
+ cy.findByText("Broken Bundle").should("be.visible");
+ cy.findByRole("link", { name: "Broken Bundle" }).should("not.exist");
+ cy.findByText("Sync failed").should("be.visible");
+ });
+
+ // The malformed config and the config-less directory produced no app at all.
+ cy.findByText("/apps/bad-config").should("not.exist");
+ cy.findByText("/apps/no-config").should("not.exist");
+ });
+
+ // The API tells the same story: exactly the two apps, and only the good one serves a bundle.
+ cy.request("GET", "/api/apps").then(({ body: apps }) => {
+ expect(apps.map((app: { name: string }) => app.name).sort()).to.deep.eq([
+ "broken-bundle",
+ "good",
+ ]);
+ });
+
+ cy.request("/api/apps/good/bundle").its("status").should("eq", 200);
+
+ cy.request({
+ url: "/api/apps/broken-bundle/bundle",
+ failOnStatusCode: false,
+ }).then(({ status, body }) => {
+ expect(status).to.eq(404);
+ expect(body).to.deep.eq({ error: "Bundle not synced yet" });
+ });
+
+ for (const slug of ["bad-config", "no-config"]) {
+ cy.request({
+ url: `/api/apps/${slug}/bundle`,
+ failOnStatusCode: false,
+ }).then(({ status, body }) => {
+ expect(status).to.eq(404);
+ expect(body).to.eq("Not found.");
+ });
+ }
+
+ // And what a user opening the broken app sees: its metadata loads (the app
+ // exists), the host frames it, and the bundle 404 surfaces from inside the
+ // iframe as the "isn't ready yet" screen — driven by the real pull, no mocks.
+ // (The not-found screen for a missing app is covered in viewing.cy.spec.ts.)
+ cy.visit("/apps/broken-bundle");
+ H.main()
+ .findByText(/isn.t ready yet/i, { timeout: 30000 })
+ .should("be.visible");
+ });
+});
diff --git a/e2e/test/scenarios/data-apps/viewing.cy.spec.ts b/e2e/test/scenarios/data-apps/viewing.cy.spec.ts
new file mode 100644
index 00000000000..7dce3a756c3
--- /dev/null
+++ b/e2e/test/scenarios/data-apps/viewing.cy.spec.ts
@@ -0,0 +1,147 @@
+import {
+ DATA_APP_DISPLAY_NAME as APP_DISPLAY_NAME,
+ DATA_APP_NAME as APP_NAME,
+ visitDataAppRoute as visitAppRoute,
+} from "e2e/support/helpers";
+
+import { DATA_APP_TEST_ENV as TEST_ENV } from "./helpers";
+
+const { H } = cy;
+
+describe("scenarios > data apps > viewing & routing", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ // `bleeding-edge` grants the `data-apps` premium feature; requires the EE build.
+ H.activateToken("bleeding-edge");
+ });
+
+ describe("viewing permissions", () => {
+ it("lets a non-admin open a data app by direct URL", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: TEST_ENV,
+ });
+
+ // A normal (non-admin) user has data access, so the app opens and renders
+ // its data — the admin gate is only on *managing* apps, not viewing them.
+ cy.signInAsNormalUser();
+ H.openDataApp(APP_NAME);
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByRole("heading", { name: "Orders overview" }).should(
+ "be.visible",
+ );
+ cy.findByTestId("orders-count", { timeout: 30000 })
+ .invoke("text")
+ .should("match", /^\d+$/);
+ });
+ });
+
+ it("opens the app shell for a user without data access, but shows no data", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: TEST_ENV,
+ });
+
+ // The `nodata` user can open the app (viewing isn't gated), but the query
+ // the app runs goes through the QP with the user's own permissions — with
+ // no data access it resolves to no data (the fixture renders "—").
+ cy.signIn("nodata");
+ H.openDataApp(APP_NAME);
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByRole("heading", { name: "Orders overview" }).should(
+ "be.visible",
+ );
+ cy.findByTestId("orders-count", { timeout: 30000 }).should(
+ "have.text",
+ "—",
+ );
+ });
+ });
+
+ it("shows a not-found state for a disabled or missing app", () => {
+ // No app with this slug exists, so the metadata endpoint really 404s and the
+ // host renders a not-found state rather than a broken iframe — no mock needed.
+ H.openDataApp("does-not-exist");
+ H.main().findByText("Data app not found").should("be.visible");
+ });
+ });
+
+ describe("internal routing", () => {
+ it("mirrors internal route changes into the parent URL", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: TEST_ENV,
+ });
+
+ H.openDataApp(APP_NAME);
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByRole("heading", { name: "Orders overview" }).should(
+ "be.visible",
+ );
+ // Navigate to a nested page using the exposed `DataAppLink`.
+ cy.findByRole("link", { name: "Details" }).click();
+ cy.findByRole("heading", { name: "Order details" }).should(
+ "be.visible",
+ );
+ // The app's own router moved, too — not just the page that rendered.
+ cy.findByTestId("current-pathname").should("have.text", "/details");
+ });
+
+ // The iframe's client-side navigation is mirrored to the parent's URL bar
+ // (via replaceState), so the top-level path reflects the nested route.
+ cy.location("pathname").should("eq", `/apps/${APP_NAME}/details`);
+ });
+
+ it("starts on the target page when deep-linked directly to a sub-route", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: TEST_ENV,
+ });
+
+ visitAppRoute("details");
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByRole("heading", { name: "Order details" }).should(
+ "be.visible",
+ );
+ cy.findByTestId("current-pathname").should("have.text", "/details");
+ });
+ });
+
+ it("navigates imperatively via useDataAppLocation().navigate", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: TEST_ENV,
+ });
+
+ H.openDataApp(APP_NAME);
+ H.dataAppIframe(APP_DISPLAY_NAME).within(() => {
+ cy.findByRole("heading", { name: "Orders overview" }).should(
+ "be.visible",
+ );
+ cy.findByTestId("navigate-to-details").click();
+ cy.findByRole("heading", { name: "Order details" }).should(
+ "be.visible",
+ );
+ cy.findByTestId("current-pathname").should("have.text", "/details");
+ });
+ cy.location("pathname").should("eq", `/apps/${APP_NAME}/details`);
+ });
+ });
+
+ describe("host error / not-ready screens", () => {
+ it("shows a themed host error screen when the bundle throws while rendering", () => {
+ H.mockDataApp(APP_NAME, {
+ displayName: APP_DISPLAY_NAME,
+ testEnv: TEST_ENV,
+ });
+
+ visitAppRoute("throw");
+ // The throw is caught in the iframe and reported to the parent, which
+ // renders its themed failure screen in the host realm.
+ H.main()
+ .findByText(/couldn.t be loaded/i, { timeout: 30000 })
+ .should("be.visible");
+ });
+ });
+});
diff --git a/e2e/tsconfig.json b/e2e/tsconfig.json
index 3ddbdeba95d..292a141d433 100644
--- a/e2e/tsconfig.json
+++ b/e2e/tsconfig.json
@@ -15,8 +15,15 @@
"@metabase/embedding-sdk-react": [
"../enterprise/frontend/src/embedding-sdk-package/index.ts"
],
+ "@metabase/embedding-sdk-react/data-app": [
+ "../enterprise/frontend/src/embedding-sdk-package/data-app.ts"
+ ],
"*": ["../frontend/src/*"]
}
},
- "include": ["**/*"]
+ "include": ["**/*"],
+ // Data-app fixtures are standalone SDK apps (built by Vite, typechecked by
+ // their own tsconfig) — not part of the e2e TS program. Including them pulls
+ // SDK source outside this project's rootDir.
+ "exclude": ["support/assets/data-apps"]
}
diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
index cc29f573dd2..f3cea35500d 100644
--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
@@ -17,6 +17,7 @@
[metabase-enterprise.content-translation.routes]
[metabase-enterprise.content-verification.api.routes]
[metabase-enterprise.custom-viz-plugin.api]
+ [metabase-enterprise.data-apps.api]
[metabase-enterprise.data-complexity-score.api]
[metabase-enterprise.data-studio.api]
[metabase-enterprise.database-replication.api :as database-replication.api]
@@ -48,6 +49,7 @@
[metabase-enterprise.workspaces.api]
[metabase.api.macros :as api.macros]
[metabase.api.util.handlers :as handlers]
+ [metabase.request.core :as request]
[metabase.util.i18n :refer [deferred-tru]]))
(comment metabase-enterprise.advanced-config.api.logs/keep-me)
@@ -60,6 +62,7 @@
:collection-cleanup (deferred-tru "Collection Cleanup")
:content-translation (deferred-tru "Content translation")
:custom-viz (deferred-tru "Custom Visualizations")
+ :data-apps (deferred-tru "Data Apps")
:library (deferred-tru "Library")
:dependencies (deferred-tru "Dependency Tracking")
:schema-viewer (deferred-tru "Schema Viewer")
@@ -93,6 +96,10 @@
TODO -- Please fix them! See #22687"
{"/moderation-review" metabase-enterprise.content-verification.api.routes/routes
+ ;; Data-app bundle hosting. Naughty because the FE route lives at `/apps/:slug`
+ ;; (and `/api/apps/...`), NOT `/api/ee/...` — `/app/*` is reserved for static
+ ;; assets, so we keep the public path stable here. Superuser-only inside the handler.
+ (str "/" request/data-app-url-segment) (premium-handler metabase-enterprise.data-apps.api/routes :data-apps)
"/mt" metabase-enterprise.sandbox.api.routes/sandbox-routes
"/table" metabase-enterprise.sandbox.api.routes/sandbox-table-routes})
diff --git a/enterprise/backend/src/metabase_enterprise/core/init.clj b/enterprise/backend/src/metabase_enterprise/core/init.clj
index e0aef1c4c4c..22575758139 100644
--- a/enterprise/backend/src/metabase_enterprise/core/init.clj
+++ b/enterprise/backend/src/metabase_enterprise/core/init.clj
@@ -11,6 +11,7 @@
[metabase-enterprise.audit-app.init]
[metabase-enterprise.cache.init]
[metabase-enterprise.custom-viz-plugin.init]
+ [metabase-enterprise.data-apps.init]
[metabase-enterprise.data-complexity-score.init]
[metabase-enterprise.database-replication.init]
[metabase-enterprise.dependencies.init]
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/api.clj b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj
new file mode 100644
index 00000000000..54020bb15b3
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/api.clj
@@ -0,0 +1,183 @@
+(ns metabase-enterprise.data-apps.api
+ "Data-app endpoints, mounted at `/api/apps`.
+
+ Data apps come from the repository connected via the remote-sync feature. The
+ repo's `data_apps/<dir>/data_app.yaml` files are discovered on sync and each is
+ materialized as one `data_app` row, caching the app's bundle. Users navigate to
+ `/apps/:slug`, which fetches `/api/apps/:slug/bundle` and evaluates the
+ bytes inside a Near Membrane sandbox.
+
+ Note: we can't use `/app/...` for the frontend or `/api/app/...` for the API
+ because Metabase's server reserves `/app/*` for serving static assets (see
+ `metabase.server.routes/static-files-handler`)."
+ (:require
+ [clojure.string :as str]
+ [metabase-enterprise.data-apps.models.data-app :as data-app]
+ [metabase-enterprise.data-apps.sync :as data-app.sync]
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.api.routes.common :refer [+auth]]
+ [metabase.util.json :as json]
+ [metabase.util.malli.schema :as ms]
+ [toucan2.core :as t2])
+ (:import
+ (java.io ByteArrayInputStream)))
+
+(set! *warn-on-reflection* true)
+
+;;; ------------------------------------------------ Constants ------------------------------------------------
+
+;; Slug must not collide with the literal `repo-status` sub-route.
+(def ^:private slug-regex #"(?!repo-status$)[^/]+")
+
+(def ^:private bundle-response-headers
+ ;; `no-cache` so the browser may cache but must revalidate via
+ ;; the content-hash ETag — we answer If-None-Match with 304 below.
+ {"Content-Type" "application/javascript"
+ "X-Content-Type-Options" "nosniff"
+ "Cross-Origin-Resource-Policy" "same-origin"
+ "Referrer-Policy" "no-referrer"
+ "Cache-Control" "no-cache"})
+
+;;; ------------------------------------------------ Helpers ------------------------------------------------
+
+(defn- repo-status []
+ (let [url (data-app.sync/repo-url)]
+ {:configured (some? url)
+ :url url}))
+
+(defn- if-none-match-hashes
+ "Parse an `If-None-Match` header into the set of bare hashes it lists, dropping
+ any `W/` weak prefix and surrounding quotes (handles a comma-separated list)."
+ [header]
+ (->> (some-> header (str/split #"\s*,\s*"))
+ (map #(-> % (str/replace-first #"^W/" "") (str/replace #"^\"|\"$" "")))
+ set))
+
+;;; ------------------------------------------------ Schemas ------------------------------------------------
+
+(def ^:private DataAppResponse
+ [:map
+ [:id ms/PositiveInt]
+ [:name ms/NonBlankString]
+ [:display_name ms/NonBlankString]
+ [:bundle_path ms/NonBlankString]
+ [:enabled :boolean]
+ [:allowed_hosts [:sequential :string]]
+ [:bundle_hash [:maybe :string]]
+ [:last_synced_sha [:maybe :string]]
+ [:last_synced_at [:maybe :any]]
+ [:sync_error [:maybe :string]]
+ [:created_at :any]
+ [:updated_at :any]])
+
+(def ^:private PublicDataAppResponse
+ [:map {:closed true}
+ [:name ms/NonBlankString]
+ [:display_name ms/NonBlankString]])
+
+(def ^:private RepoStatusResponse
+ [:map
+ [:configured :boolean]
+ [:url [:maybe :string]]])
+
+;;; --------------------------------------------- Repo status ---------------------------------------------
+
+(api.macros/defendpoint :get "/repo-status" :- RepoStatusResponse
+ "Status of the connected repository as it relates to data apps. Data apps are
+ pulled by the remote-sync import (manual \"Pull changes\", auto-import, or
+ startup); the connection is configured on the remote-sync settings page."
+ []
+ (api/check-superuser)
+ (repo-status))
+
+;;; ------------------------------------------------ Apps ------------------------------------------------
+
+(defn- data-app-response
+ "Return full data-app metadata to superusers and only navigational fields to other users."
+ [app]
+ (if api/*is-superuser?*
+ app
+ (select-keys app [:name :display_name])))
+
+(api.macros/defendpoint :get "/" :- [:sequential [:or DataAppResponse PublicDataAppResponse]]
+ "List the data apps provided by the connected repository. Pass `available=true`
+ to return only enabled apps without sync errors."
+ [_route-params
+ {:keys [available]} :- [:map [:available {:optional true} [:maybe :boolean]]]]
+ (->> (data-app/select-non-blob (cond-> {:order-by [[:display_name :asc]]}
+ available (assoc :where [:and
+ [:= :enabled true]
+ [:= :sync_error nil]])))
+ (map api/read-check)
+ (mapv data-app-response)))
+
+;; NOTE on the `slug-regex` constraint: the default path-param matcher allows
+;; slashes inside a segment, so `/:slug` would otherwise swallow `/x/bundle`.
+;; The regex also excludes the literal `repo-status` sub-route above.
+(api.macros/defendpoint :put ["/:slug" :slug slug-regex] :- DataAppResponse
+ "Enable or disable a single data app. Disabled apps are not served."
+ [{:keys [slug]} :- [:map [:slug ms/NonBlankString]]
+ _query-params
+ {:keys [enabled]} :- [:map [:enabled :boolean]]]
+ (api/check-superuser)
+ (let [app (api/check-404 (data-app/select-one-non-blob :name slug))]
+ (t2/update! :model/DataApp :id (:id app) {:enabled enabled})
+ (data-app/select-one-non-blob :id (:id app))))
+
+(api.macros/defendpoint :delete ["/:slug" :slug slug-regex] :- :nil
+ "Remove a single data app (its row and cached bundle). Intended for clearing
+ out apps once their repository is no longer connected — a sync never deletes,
+ and while a repo is connected it would just re-materialize the app."
+ [{:keys [slug]} :- [:map [:slug ms/NonBlankString]]]
+ (api/check-superuser)
+ ;; `t2/delete!` returns the row count; a 0 means the slug wasn't there → 404.
+ (api/check-404 (pos? (t2/delete! :model/DataApp :name slug)))
+ ;; a `nil` body is rendered as a 204; matches the `:- :nil` response schema
+ ;; above (returning `generic-204-no-content` would fail that validation).
+ nil)
+
+(api.macros/defendpoint :get ["/:slug" :slug slug-regex] :- [:or DataAppResponse PublicDataAppResponse]
+ "Fetch metadata for a single enabled data app by its slug."
+ [{:keys [slug]} :- [:map [:slug ms/NonBlankString]]]
+ (data-app-response (api/read-check (data-app/select-one-non-blob :name slug :enabled true))))
+
+(api.macros/defendpoint :get ["/:slug/bundle" :slug slug-regex] :- :any
+ "Serve the cached JS bundle for a single enabled data app by slug. Honors
+ `If-None-Match` against the content-hash ETag with a 304."
+ [{:keys [slug]} :- [:map [:slug ms/NonBlankString]]
+ _query-params
+ _body
+ request
+ respond
+ raise]
+ (try
+ (let [row (api/read-check (data-app/select-one-non-blob :name slug :enabled true))
+ hash (:bundle_hash row)
+ etag (some->> hash (format "\"%s\""))]
+ (cond
+ (and hash (contains? (if-none-match-hashes (get-in request [:headers "if-none-match"])) hash))
+ ;; 304 carries only the cacheable headers (Cache-Control) + ETag — never
+ ;; Content-Type or a body, per RFC 9110 §15.4.5.
+ (respond {:status 304, :headers {"Cache-Control" "no-cache", "ETag" etag}})
+
+ :else
+ (let [^bytes bundle (t2/select-one-fn :bundle :model/DataApp :id (:id row))]
+ (if (and bundle (pos? (alength bundle)))
+ (respond {:status 200
+ :headers (-> bundle-response-headers
+ ;; JSON array of origins the sandboxed bundle may fetch/XHR; the
+ ;; iframe reads this to configure its Near-Membrane fetch allowlist.
+ (assoc "X-Metabase-Data-App-Allowed-Hosts"
+ (json/encode (:allowed_hosts row)))
+ (cond-> etag (assoc "ETag" etag)))
+ :body (ByteArrayInputStream. bundle)})
+ (respond {:status 404
+ :headers {"Content-Type" "application/json"}
+ :body "{\"error\":\"Bundle not synced yet\"}"})))))
+ (catch Throwable e
+ (raise e))))
+
+(def routes
+ "`/api/apps` routes."
+ (api.macros/ns-handler *ns* +auth))
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/config.clj b/enterprise/backend/src/metabase_enterprise/data_apps/config.clj
new file mode 100644
index 00000000000..ffb249c2d04
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/config.clj
@@ -0,0 +1,140 @@
+(ns metabase-enterprise.data-apps.config
+ "Parsing + validation of a per-app `data_app.yaml`. Each data app lives in its
+ own directory under `data_apps/` at the repo root, alongside its built bundle:
+
+ data_apps/
+ sales/ # the directory name is the slug: /apps/sales
+ data_app.yaml
+ dist/index.js
+
+ where `data_app.yaml` is:
+
+ name: Sales dashboard # display name
+ path: dist/index.js # bundle path, relative to this app's directory
+ allowed_hosts: # optional — origins the sandboxed bundle may fetch/XHR
+ - https://api.example.com
+ - https://*.internal.acme.com"
+ (:require
+ [clojure.java.io :as io]
+ [clojure.string :as str]
+ [metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.yaml :as yaml])
+ (:import
+ (java.io ByteArrayInputStream)))
+
+(set! *warn-on-reflection* true)
+
+(def config-file-name
+ "Name of the per-app config file (used in error messages)."
+ "data_app.yaml")
+
+(def apps-dir
+ "Directory at the repo root that holds one subdirectory per data app."
+ "data_apps")
+
+(def ^:private slug-pattern
+ "Lowercase letters/numbers separated by single dashes. An app *directory* must
+ match this: the name is used verbatim as the slug, never normalized. Folding
+ case here would reintroduce the collisions the directory naming rules out —
+ git happily holds both `data_apps/Sales` and `data_apps/sales`."
+ #"[a-z0-9]+(?:-[a-z0-9]+)*")
+
+(def ^:private reserved-slugs
+ "Slugs that collide with literal `/api/apps/*` sub-routes (see the API's
+ `slug-regex`). An app with one of these would sync but be unreachable, so we
+ reject it during parsing."
+ #{"repo-status"})
+
+(defn- normalize-path
+ "Trim and drop a leading `./` so the path is relative to the app directory."
+ [p]
+ (-> (str p) str/trim (str/replace #"^\./" "")))
+
+(def ^:private allowed-host-re
+ "A single `allowed_hosts` entry: an origin the app's sandboxed bundle may
+ `fetch`/XHR — scheme + host, an optional `*.` subdomain wildcard, and an
+ optional port. No path/query/`*`/non-http(s) scheme: it names an
+ origin, e.g. `https://api.example.com` or `https://*.internal.acme.com`."
+ #"(?i)https?://(\*\.)?[a-z0-9-]+(\.[a-z0-9-]+)*(:\d+)?")
+
+(defn- normalized-allowed-host
+ "Trim, lowercase, and drop trailing slashes from one `allowed_hosts` entry."
+ [entry]
+ (some-> entry str str/trim u/lower-case-en (str/replace #"/+$" "")))
+
+(defn- parse-allowed-host
+ "Normalize + validate a single `allowed_hosts` entry (see [[allowed-host-re]]).
+ Throws an `ex-info` with `:status-code` 400 when it isn't an origin-only value."
+ [entry ^String dir]
+ (let [s (normalized-allowed-host entry)]
+ (when-not (and (seq s) (re-matches allowed-host-re s))
+ (throw (ex-info (tru "{0}/{1}: \"{2}\" is not a valid allowed_hosts entry — use an origin like https://api.example.com or https://*.example.com."
+ dir config-file-name (str entry))
+ {:status-code 400})))
+ s))
+
+(defn- parse-allowed-hosts
+ "Validate + normalize the optional `allowed_hosts` list from a parsed config.
+ Each entry must be an origin-only value (see [[allowed-host-re]]); returns a
+ lowercased, de-duplicated vector, or `[]` when the key is absent. Throws an
+ `ex-info` with `:status-code` 400 on a non-list value or an invalid entry."
+ [parsed ^String dir]
+ (let [raw (:allowed_hosts parsed)]
+ (cond
+ (nil? raw) []
+ (not (sequential? raw))
+ (throw (ex-info (tru "{0}/{1}: \"allowed_hosts\" must be a list." dir config-file-name)
+ {:status-code 400}))
+ :else
+ (->> raw
+ (map #(parse-allowed-host % dir))
+ distinct
+ vec))))
+
+(defn- path-traversal? [path]
+ (some #(= ".." %) (str/split path #"/")))
+
+(defn- parse-yaml [^bytes bytes ^String dir]
+ (try
+ (with-open [r (io/reader (ByteArrayInputStream. bytes) :encoding "UTF-8")]
+ (yaml/parse-stream r))
+ (catch Exception e
+ (throw (ex-info (tru "Could not parse {0}/{1}: {2}" dir config-file-name (ex-message e))
+ {:status-code 400})))))
+
+(defn- dir-slug
+ "The app's slug: the name of its directory (`data_apps/sales` -> `sales`)."
+ [^String dir]
+ (subs dir (inc (str/last-index-of dir "/"))))
+
+(defn parse-app-config
+ "Parse the bytes of one `data_app.yaml` from the app directory `dir` (e.g.
+ `data_apps/sales`) into `{:slug ..., :display_name ..., :path ...,
+ :allowed_hosts [...]}`. The slug is the directory's name; `path` is relative to
+ the directory; `:allowed_hosts` is a (possibly empty) vector of origins the
+ sandboxed bundle may reach. Throws an `ex-info` with `:status-code` 400 on
+ malformed or incomplete content — including a directory whose name isn't a
+ usable slug, since that app has no URL to be served at."
+ [^bytes bytes ^String dir]
+ (let [parsed (parse-yaml bytes dir)
+ slug (dir-slug dir)
+ name (some-> (:name parsed) str str/trim not-empty)
+ path (some-> (:path parsed) normalize-path not-empty)
+ allowed-hosts (parse-allowed-hosts parsed dir)]
+ (when-not (re-matches slug-pattern slug)
+ (throw (ex-info (tru "{0}: the app directory''s name is its slug, so it must be lowercase letters, numbers, and dashes." dir)
+ {:status-code 400})))
+ (when (contains? reserved-slugs slug)
+ (throw (ex-info (tru "{0}: \"{1}\" is a reserved slug — rename the directory." dir slug)
+ {:status-code 400})))
+ (when-not name
+ (throw (ex-info (tru "{0}/{1}: \"name\" is required." dir config-file-name)
+ {:status-code 400})))
+ (when-not path
+ (throw (ex-info (tru "{0}/{1}: \"path\" is required." dir config-file-name)
+ {:status-code 400})))
+ (when (path-traversal? path)
+ (throw (ex-info (tru "{0}/{1}: \"path\" must not contain \"..\"." dir config-file-name)
+ {:status-code 400})))
+ {:slug slug, :display_name name, :path path, :allowed_hosts allowed-hosts}))
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/csp.clj b/enterprise/backend/src/metabase_enterprise/data_apps/csp.clj
new file mode 100644
index 00000000000..8abd25f4f04
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/csp.clj
@@ -0,0 +1,16 @@
+(ns metabase-enterprise.data-apps.csp
+ "EE implementation of the data-app CSP `connect-src` host lookup declared in
+ [[metabase.server.middleware.security]]. Kept separate from the HTTP API so
+ the core security middleware's lookup doesn't pull in route code."
+ (:require
+ [metabase-enterprise.data-apps.models.data-app :as data-app]
+ [metabase.premium-features.core :refer [defenterprise]]))
+
+(defenterprise data-app-connect-src-hosts
+ "Origins the enabled data app with `slug` may reach (its `allowed_hosts`), or
+ `[]` when there is no such enabled app. Drives the data-app iframe document's
+ CSP `connect-src` so the sandboxed bundle can fetch/XHR those origins."
+ :feature :data-apps
+ [slug]
+ (or (:allowed_hosts (data-app/select-one-non-blob :name slug :enabled true))
+ []))
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/init.clj b/enterprise/backend/src/metabase_enterprise/data_apps/init.clj
new file mode 100644
index 00000000000..53251438552
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/init.clj
@@ -0,0 +1,7 @@
+(ns metabase-enterprise.data-apps.init
+ (:require
+ [metabase-enterprise.data-apps.api]
+ [metabase-enterprise.data-apps.config]
+ [metabase-enterprise.data-apps.csp]
+ [metabase-enterprise.data-apps.models.data-app]
+ [metabase-enterprise.data-apps.sync]))
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj b/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj
new file mode 100644
index 00000000000..82d7371da52
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/models/data_app.clj
@@ -0,0 +1,78 @@
+(ns metabase-enterprise.data-apps.models.data-app
+ (:require
+ [metabase.api.common :as api]
+ [metabase.models.interface :as mi]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2])
+ (:import
+ (java.sql Blob)))
+
+(set! *warn-on-reflection* true)
+
+(methodical/defmethod t2/table-name :model/DataApp [_model] :data_app)
+
+(defn- blob->bytes ^bytes [v]
+ (cond
+ (nil? v) nil
+ (instance? Blob v) (let [^Blob b v] (.getBytes b 1 (int (.length b))))
+ :else v))
+
+(def ^:private transform-bundle
+ "Coerce JDBC `Blob` values into plain byte arrays on read."
+ {:in identity
+ :out blob->bytes})
+
+(t2/deftransforms :model/DataApp
+ {:bundle transform-bundle
+ ;; JSON array of origins the sandboxed bundle may fetch/XHR (see config.clj).
+ :allowed_hosts mi/transform-json})
+
+(doto :model/DataApp
+ (derive :metabase/model)
+ (derive :hook/timestamped?))
+
+;; Reads always see `allowed_hosts` as a vector, never nil — a row synced before
+;; the column existed has NULL until it's re-synced. Guard on `contains?` so
+;; selects that don't fetch the column (e.g. `select-one-fn :bundle`) are left
+;; untouched rather than gaining a spurious `:allowed_hosts` key.
+(t2/define-after-select :model/DataApp
+ [app]
+ (cond-> app
+ (contains? app :allowed_hosts) (update :allowed_hosts #(or % []))))
+
+(def non-blob-columns
+ "Columns to select for normal data-app metadata reads, excluding the raw bundle blob."
+ [:id :name :display_name :bundle_path :enabled :allowed_hosts
+ :bundle_hash :last_synced_sha :last_synced_at :sync_error
+ :created_at :updated_at])
+
+(defn select-one-non-blob
+ "Like `t2/select-one` on `:model/DataApp`, but excludes the bundle blob."
+ [& conditions]
+ (apply t2/select-one (into [:model/DataApp] non-blob-columns) conditions))
+
+(defn select-non-blob
+ "Like `t2/select` on `:model/DataApp`, but excludes the bundle blob."
+ [& conditions]
+ (apply t2/select (into [:model/DataApp] non-blob-columns) conditions))
+
+;; Any signed-in user may view (open) a data app. The `/api/apps` endpoints
+;; are `+auth`, so reaching a read-check already means the user is authenticated.
+;; Data the app queries still runs through the QP with the user's own
+;; permissions, so a viewer without data access simply sees no data.
+(defmethod mi/can-read? :model/DataApp
+ ([_instance] true)
+ ([_model _pk] true))
+
+(defmethod mi/can-write? :model/DataApp
+ ([_instance] api/*is-superuser?*)
+ ([_model _pk] api/*is-superuser?*))
+
+(defmethod mi/can-create? :model/DataApp
+ [_model _instance]
+ api/*is-superuser?*)
+
+(methodical/defmethod mi/to-json :model/DataApp
+ "Never include the raw bundle bytes in JSON."
+ [data-app json-generator]
+ (next-method (dissoc data-app :bundle) json-generator))
diff --git a/enterprise/backend/src/metabase_enterprise/data_apps/sync.clj b/enterprise/backend/src/metabase_enterprise/data_apps/sync.clj
new file mode 100644
index 00000000000..eadf59539e3
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/data_apps/sync.clj
@@ -0,0 +1,201 @@
+(ns metabase-enterprise.data-apps.sync
+ "Materialize data apps from a synced repository snapshot.
+
+ Data apps ride the remote-sync import pipeline: whenever remote-sync pulls the
+ connected repository (manual \"Pull changes\", auto-import poll, or startup),
+ it calls [[sync-from-snapshot!]] with the just-imported snapshot. We discover
+ every `data_apps/<dir>/data_app.yaml` and materialize one `data_app` row per app
+ (caching the built bundle). A sync only upserts — it never deletes, so an app
+ whose directory is gone from the repo is kept until an admin removes it.
+
+ This namespace does no Git access of its own — the snapshot's `read-file` /
+ `list-files` come from remote-sync. The cached `bundle` blob is what serving
+ reads, so a failed sync never takes a working app offline, and the admin
+ `enabled` toggle is preserved across syncs."
+ (:require
+ [clojure.string :as str]
+ [metabase-enterprise.data-apps.config :as data-app.config]
+ [metabase.settings.core :as setting]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.log :as log]
+ [toucan2.core :as t2])
+ (:import
+ (java.security MessageDigest)
+ (java.util.regex Pattern)
+ (org.apache.commons.codec.binary Hex)))
+
+(set! *warn-on-reflection* true)
+
+(def ^:const max-bundle-bytes
+ "Cap on a synced bundle's size (10 MiB)."
+ (* 10 1024 1024))
+
+(defn- bytes-hash ^String [^bytes b]
+ (let [^MessageDigest md (MessageDigest/getInstance "SHA-256")]
+ (Hex/encodeHexString ^bytes (.digest md b))))
+
+(defn- ->bytes ^bytes [^String s]
+ (.getBytes s "UTF-8"))
+
+(defn repo-url
+ "The connected remote-sync repository URL, or nil when none is configured. Read
+ by keyword so this OSS namespace has no compile-time dependency on the
+ enterprise remote-sync module; returns nil when that module (and its setting)
+ isn't loaded."
+ []
+ (let [url (try (setting/get :remote-sync-url) (catch Throwable _ nil))]
+ (when-not (str/blank? url)
+ url)))
+
+;;; ----------------------------------------------------- Discovery -----------------------------------------------------
+
+(def ^:private app-dir-regex
+ ;; the data_apps/<dir> folder a repo path sits in (dir = a single path segment)
+ (re-pattern (format "(%s/[^/]+)/.*" (Pattern/quote data-app.config/apps-dir))))
+
+(defn- discover-app-configs
+ "Given the snapshot's `list-files` and `read-file` fns (where `read-file`
+ returns file text or nil), iterate the folders under `data_apps/` and return one
+ entry per folder that is an app — it holds a `data_app.yaml`; a folder without
+ one is skipped. Each entry is a parsed app
+ `{:slug :display_name :bundle :allowed_hosts}` (with `:bundle` the repo-root
+ relative bundle path) or `{:config-error <message>}`. Parse/read failures are
+ isolated per app so one bad config can't abort the sync."
+ [list-files read-file]
+ (let [files (set (list-files))
+ app-dirs (distinct (keep #(second (re-matches app-dir-regex %)) files))]
+ (for [dir app-dirs
+ :let [config-path (files (str dir "/data_app.yaml"))]
+ :when config-path]
+ (try
+ (if-let [content (read-file config-path)]
+ (let [{:keys [slug display_name path allowed_hosts]} (data-app.config/parse-app-config (->bytes content) dir)]
+ {:slug slug, :display_name display_name, :bundle (str dir "/" path), :allowed_hosts allowed_hosts})
+ {:config-error (tru "Could not read {0}." config-path)})
+ (catch Throwable e
+ {:config-error (ex-message e)})))))
+
+;;; ----------------------------------------------------- Materialize -----------------------------------------------------
+
+(defn- upsert-by-name!
+ "Insert or update by slug. Never writes `:enabled`, so the admin toggle (and the
+ DB default of true for new rows) is preserved across syncs."
+ [slug row]
+ (if (t2/exists? :model/DataApp :name slug)
+ (t2/update! :model/DataApp :name slug row)
+ (t2/insert! :model/DataApp (assoc row :name slug))))
+
+(defn- app-content-changed?
+ "Whether the just-synced content differs from the `existing` row (nil = a new
+ app). Compares only content-bearing fields — a `last_synced_sha` /
+ `last_synced_at` bump on an otherwise-identical app is NOT a change, so callers
+ can count real changes (e.g. for the remote-sync pull summary)."
+ [existing {:keys [display_name bundle_path bundle_hash allowed_hosts]}]
+ (or (nil? existing)
+ (some? (:sync_error existing))
+ (not= (:display_name existing) display_name)
+ (not= (:bundle_path existing) bundle_path)
+ (not= (:bundle_hash existing) bundle_hash)
+ (not= (vec (or (:allowed_hosts existing) []))
+ (vec (or allowed_hosts [])))))
+
+(defn- sync-app!
+ "Materialize one app. On bundle failure, the row's metadata is still upserted
+ with `sync_error` set so the app appears in the list with its failure; the
+ previously cached bundle (if any) is kept. `existing` is the app's pre-sync row
+ (or nil); returns true when this sync actually changed the app's content (a new
+ app, differing bundle/metadata, or a new failure) so callers can count changes."
+ [existing {:keys [slug display_name bundle sha read-file allowed_hosts]}]
+ (try
+ (let [content (read-file bundle)
+ _ (when-not content
+ (throw (ex-info (tru "Bundle file \"{0}\" not found in the repository." bundle)
+ {:status-code 400})))
+ ^bytes bytes (->bytes content)]
+ (when (> (alength bytes) max-bundle-bytes)
+ (throw (ex-info (tru "Bundle for \"{0}\" must be less than {1} MiB."
+ slug (quot max-bundle-bytes (* 1024 1024)))
+ {:status-code 413})))
+ (let [fields {:display_name display_name
+ :allowed_hosts allowed_hosts
+ :bundle_path bundle
+ :bundle_hash (bytes-hash bytes)}]
+ (upsert-by-name! slug (assoc fields
+ :bundle bytes
+ :last_synced_sha sha
+ :last_synced_at :%now
+ :sync_error nil))
+ (app-content-changed? existing fields)))
+ (catch Throwable e
+ (upsert-by-name! slug {:display_name display_name
+ :allowed_hosts allowed_hosts
+ :bundle_path bundle
+ :sync_error (ex-message e)})
+ (log/warnf e "[data-app] failed to sync app %s" slug)
+ ;; a failing app counts as a change unless it was already failing identically
+ (or (nil? existing) (not= (:sync_error existing) (ex-message e))))))
+
+(defn import-from-snapshot!
+ "Materialize data apps from a synced repo `snapshot`:
+
+ {:read-file (fn [path] -> <file-text-string> | nil)
+ :list-files (fn [] -> [<path-string> ...])
+ :sha <commit-sha-string>}
+
+ Discovers every `data_apps/<dir>/data_app.yaml` and upserts a row per app in a
+ single transaction. Apps not present in the snapshot are left untouched (a
+ sync never deletes — removal is an explicit admin action). Returns
+ `{:synced <n>, :changed <n>, :sha <sha>, :config-errors [<message> ...]}`,
+ where `:changed` is how many apps this sync actually created/updated
+ (a `last_synced_sha` bump on an unchanged app does not count). A malformed
+ `data_app.yaml` is isolated (collected into `:config-errors`, that app skipped)
+ rather than aborting the others; per-app bundle failures are recorded on the
+ row.
+
+ Two apps can't collide on a slug here: a slug *is* an app's directory name (see
+ the config namespace), a repo can't hold two `data_apps/<slug>` directories, and
+ discovery takes one config per directory (see [[discover-app-configs]])."
+ [{:keys [read-file list-files sha]}]
+ ;; realize discovery once (it calls read-file/parse per config); `results` is
+ ;; then walked several times below
+ (let [results (vec (discover-app-configs list-files read-file))
+ good (filter :slug results)
+ errors (vec (keep :config-error results))
+ ;; pre-sync rows, so we can tell a real change from a sha/timestamp bump
+ existing (into {} (map (juxt :name identity))
+ (t2/select [:model/DataApp :name :display_name :allowed_hosts
+ :bundle_path :bundle_hash :sync_error]))
+ changed
+ ;; Upsert-only: a sync never deletes. Apps materialized from a previous
+ ;; repo are kept (they survive unlinking, and switching repos), and an
+ ;; app whose directory name matches an existing app's is overridden in
+ ;; place by `upsert-by-name!`. Rows are removed only by an explicit admin
+ ;; action (see the API's DELETE).
+ (t2/with-transaction [_conn]
+ (reduce (fn [n cfg]
+ (cond-> n
+ (sync-app! (get existing (:slug cfg))
+ (assoc cfg :sha sha :read-file read-file))
+ inc))
+ 0 good))]
+ (log/infof "[data-app] synced sha=%s apps=%d changed=%d errors=%d"
+ sha (count good) changed (count errors))
+ {:synced (count good), :changed changed, :sha sha, :config-errors errors}))
+
+(defn sync-from-snapshot!
+ "Entry point for the remote-sync import pipeline. Materializes data apps from
+ the just-imported `snapshot` (see [[import-from-snapshot!]] for its shape).
+ Never throws, so it can't break the surrounding remote-sync import: a thrown
+ failure is logged and swallowed, and a malformed `data_app.yaml` is logged and
+ its app simply doesn't appear. Returns the [[import-from-snapshot!]] result, or
+ nil if the sync threw."
+ [snapshot]
+ (try
+ (let [{:keys [config-errors] :as result} (import-from-snapshot! snapshot)]
+ (when (seq config-errors)
+ (log/warnf "[data-app] %d data_app.yaml config(s) skipped: %s"
+ (count config-errors) (str/join "; " config-errors)))
+ result)
+ (catch Throwable e
+ (log/warn e "[data-app] sync from remote-sync snapshot failed")
+ nil)))
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj
index 6d39394071e..c692254024b 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/impl.clj
@@ -3,6 +3,7 @@
[clojure.string :as str]
[diehard.core :as dh]
[java-time.api :as t]
+ [metabase-enterprise.data-apps.sync :as data-apps.sync]
[metabase-enterprise.remote-sync.guards :as guards]
[metabase-enterprise.remote-sync.merge :as remote-sync.merge]
[metabase-enterprise.remote-sync.models.remote-sync-object :as remote-sync.object]
@@ -311,6 +312,19 @@
(and (some? pre-task-branch)
(not= pre-task-branch (settings/remote-sync-branch))))
+(defn- materialize-data-apps!
+ "After a successful content import, materialize data apps from the same
+ snapshot. Data apps live under `data_apps/` in the repo (outside the serdes
+ paths), so they ride this import rather than having their own sync. Adapts the
+ snapshot to plain reader fns; `data-apps.sync/sync-from-snapshot!` never throws."
+ [^SourceSnapshot snapshot]
+ ;; `read-file` returns file text (a string) or nil; data-apps.sync converts to
+ ;; bytes on its side, keeping all Java interop out of this namespace.
+ (data-apps.sync/sync-from-snapshot!
+ {:read-file (fn [path] (source.p/read-file snapshot path))
+ :list-files (fn [] (source.p/list-files snapshot))
+ :sha (source.p/version snapshot)}))
+
(defn load-snapshot!
"Loads a snapshot's serialized entities into the app DB and reconciles local state to match it:
runs `load-metabase!`, toggles the `remote-sync-transforms` setting based on the snapshot's contents,
@@ -383,6 +397,19 @@
(transduce (map count) + 0 (concat (vals (:by-entity-id imported-data))
(vals (:by-path imported-data)))))
+(defn- fold-data-app-changes
+ "Fold the count of data apps changed by a pull into its `:outcome`. Data apps
+ live under `data_apps/` — outside serdes — and are materialized separately (see
+ [[materialize-data-apps!]]), so they're invisible to [[pulled-change-count]].
+ Without this, a pull whose only changes are data apps reports `pull-skipped` /
+ `count 0`. Caller guarantees `da-changed` is positive."
+ [outcome da-changed]
+ (case (:kind outcome)
+ "pull-skipped" {:kind "pulled" :count da-changed :branch (settings/remote-sync-branch)}
+ "pulled" (update outcome :count (fnil + 0) da-changed)
+ "merged" (update outcome :pulled (fnil + 0) da-changed)
+ outcome))
+
(defn- incremental-import-plan
"What an incremental load would touch, or [[incremental-not-possible]] if the change must fall back to a full
import. On success returns `{:ingestable <ingestable-or-nil> :deleted-rsos <RemoteSyncObject rows>}`. Falls back
@@ -566,90 +593,101 @@
(not force-deletion?)
(into (:deletion-conflicts @conflicts)))))
incremental-plan (delay (incremental-import-plan snapshot last-imported-version))
- dirty? (delay (remote-sync.object/dirty?))]
- (cond
- ;; --- Merge mode: fold remote changes into local, keeping un-pushed local changes. ---
- merge?
- (cond
- ;; No safe merge base (no prior sync, or base orphaned by a force-push/rebase) — can't 3-way merge.
- (nil? base-snapshot)
- {:status :conflict
- :version snapshot-version
- :conflicts ["Remote history was rewritten (force-push or rebase); cannot merge automatically."]
- :message "Cannot merge: the remote branch history was rewritten. Discard local changes and pull, or push to a new branch."}
-
- ;; Remote hasn't advanced past the merge base — nothing to fold in; keep local changes dirty.
- (= (source.p/version base-snapshot) snapshot-version)
- (do
- (log/info "Pull merge: remote has not advanced; keeping local changes unchanged")
- {:status :success
- :version snapshot-version
- :merge-summary {:added 0 :updated 0 :removed 0}
- :outcome {:kind "pull-skipped"}})
-
- :else
- (import-merged! snapshot base-snapshot task-id sync-timestamp))
-
- ;; --- Forced reload: bypasses the no-op/incremental guards. Deletion conflicts (when
- ;; force-deletion? is false) still block; otherwise a full reload. ---
- force?
- (cond
- (seq @blocking-conflicts)
- (let [message (format "Skipping import: snapshot version %s contains conflicts use force to override" snapshot-version)]
- (log/info message)
- {:status :conflict
- :version snapshot-version
- :conflicts (into #{} (map :category) @blocking-conflicts)
- :conflict-details @blocking-conflicts
- :message message})
-
- :else
- (let [_ (log/info "Remote sync full import: forced")
- imported-data (load-snapshot! snapshot task-id sync-timestamp :finalize! finalize!)]
- (log/info "Successfully reloaded entities from git repository")
- {:status :success
- :version snapshot-version
- :outcome {:kind "pulled"
- :count (pulled-change-count imported-data)
- :branch (settings/remote-sync-branch)}}))
-
- ;; --- Normal pull ---
- ;; Cheap no-op pull: nothing changed remotely, so nothing is loaded or deleted.
- (= last-imported-version snapshot-version)
- (do
- (log/infof "Skipping import: snapshot version %s matches last imported version" snapshot-version)
- {:status :success
- :version snapshot-version
- :outcome {:kind "pull-skipped"}})
-
- ;; Incremental fast-path: no local drift and the change is incrementally loadable. Tested before the
- ;; conflict. It touches only changed files, so it can't wholesale-delete unsynced transforms.
- (and (not @dirty?)
- (not= :remote-sync/incremental-not-possible @incremental-plan))
- (incremental-load-snapshot! @incremental-plan snapshot-version task-id sync-timestamp :finalize! finalize!)
-
- (seq @blocking-conflicts)
- (let [message (format "Skipping import: snapshot version %s contains conflicts use force to override" snapshot-version)]
- (log/info message)
- {:status :conflict
- :version snapshot-version
- :conflicts (into #{} (map :category) @blocking-conflicts) ; Backward compat: set of category names
- :conflict-details @blocking-conflicts
- :message message})
-
- :else ;; fall back to full import
- (let [reason (cond
- @dirty? "local changes pending"
- first-import? "first import"
- :else "changes not incrementally loadable")
- _ (log/infof "Remote sync full import: %s" reason)
- imported-data (load-snapshot! snapshot task-id sync-timestamp :finalize! finalize!)]
- (log/info "Successfully reloaded entities from git repository")
- {:status :success
- :version snapshot-version
- :outcome {:kind "pulled"
- :count (pulled-change-count imported-data)
- :branch (settings/remote-sync-branch)}})))
+ dirty? (delay (remote-sync.object/dirty?))
+ result
+ (cond
+ ;; --- Merge mode: fold remote changes into local, keeping un-pushed local changes. ---
+ merge?
+ (cond
+ ;; No safe merge base (no prior sync, or base orphaned by a force-push/rebase) — can't 3-way merge.
+ (nil? base-snapshot)
+ {:status :conflict
+ :version snapshot-version
+ :conflicts ["Remote history was rewritten (force-push or rebase); cannot merge automatically."]
+ :message "Cannot merge: the remote branch history was rewritten. Discard local changes and pull, or push to a new branch."}
+
+ ;; Remote hasn't advanced past the merge base — nothing to fold in; keep local changes dirty.
+ (= (source.p/version base-snapshot) snapshot-version)
+ (do
+ (log/info "Pull merge: remote has not advanced; keeping local changes unchanged")
+ {:status :success
+ :version snapshot-version
+ :merge-summary {:added 0 :updated 0 :removed 0}
+ :outcome {:kind "pull-skipped"}})
+
+ :else
+ (import-merged! snapshot base-snapshot task-id sync-timestamp))
+
+ ;; --- Forced reload: bypasses the no-op/incremental guards. Deletion conflicts (when
+ ;; force-deletion? is false) still block; otherwise a full reload. ---
+ force?
+ (cond
+ (seq @blocking-conflicts)
+ (let [message (format "Skipping import: snapshot version %s contains conflicts use force to override" snapshot-version)]
+ (log/info message)
+ {:status :conflict
+ :version snapshot-version
+ :conflicts (into #{} (map :category) @blocking-conflicts)
+ :conflict-details @blocking-conflicts
+ :message message})
+
+ :else
+ (let [_ (log/info "Remote sync full import: forced")
+ imported-data (load-snapshot! snapshot task-id sync-timestamp :finalize! finalize!)]
+ (log/info "Successfully reloaded entities from git repository")
+ {:status :success
+ :version snapshot-version
+ :outcome {:kind "pulled"
+ :count (pulled-change-count imported-data)
+ :branch (settings/remote-sync-branch)}}))
+
+ ;; --- Normal pull ---
+ ;; Cheap no-op pull: nothing changed remotely, so nothing is loaded or deleted.
+ (= last-imported-version snapshot-version)
+ (do
+ (log/infof "Skipping import: snapshot version %s matches last imported version" snapshot-version)
+ {:status :success
+ :version snapshot-version
+ :outcome {:kind "pull-skipped"}})
+
+ ;; Incremental fast-path: no local drift and the change is incrementally loadable. Tested before the
+ ;; conflict. It touches only changed files, so it can't wholesale-delete unsynced transforms.
+ (and (not @dirty?)
+ (not= :remote-sync/incremental-not-possible @incremental-plan))
+ (incremental-load-snapshot! @incremental-plan snapshot-version task-id sync-timestamp :finalize! finalize!)
+
+ (seq @blocking-conflicts)
+ (let [message (format "Skipping import: snapshot version %s contains conflicts use force to override" snapshot-version)]
+ (log/info message)
+ {:status :conflict
+ :version snapshot-version
+ :conflicts (into #{} (map :category) @blocking-conflicts) ; Backward compat: set of category names
+ :conflict-details @blocking-conflicts
+ :message message})
+
+ :else ;; fall back to full import
+ (let [reason (cond
+ @dirty? "local changes pending"
+ first-import? "first import"
+ :else "changes not incrementally loadable")
+ _ (log/infof "Remote sync full import: %s" reason)
+ imported-data (load-snapshot! snapshot task-id sync-timestamp :finalize! finalize!)]
+ (log/info "Successfully reloaded entities from git repository")
+ {:status :success
+ :version snapshot-version
+ :outcome {:kind "pulled"
+ :count (pulled-change-count imported-data)
+ :branch (settings/remote-sync-branch)}}))]
+ ;; Data apps ride the pull: re-materialize from the real source snapshot
+ ;; (the repo file tree under `data_apps/`), not the synthetic merged
+ ;; snapshot `load-snapshot!` sees. They're counted outside serdes, so fold
+ ;; their change count into the outcome — otherwise a data-app-only pull
+ ;; would report `pull-skipped` / `count 0`.
+ (if (= :success (:status result))
+ (let [da-changed (:changed (materialize-data-apps! snapshot) 0)]
+ (cond-> result
+ (pos? da-changed) (update :outcome fold-data-app-changes da-changed)))
+ result))
(catch Exception e
;; A cancellation isn't a failure: log it and return nil. Otherwise log the error, count it, and
;; return a user-friendly :error result.
@@ -658,7 +696,7 @@
(do
(log/errorf e "Failed to reload from git repository: %s" (ex-message e))
(analytics/inc! :metabase-remote-sync/imports-failed)
- {:status :error
+ {:status :error
:message (source-error-message e)
:version (source.p/version snapshot)
:details {:error-type (type e)}})))
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
index 7057f79086c..b941d926289 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
@@ -80,6 +80,7 @@
"ConnectionImpersonation"
"ContentTranslation"
"DashboardBookmark"
+ "DataApp"
"DataComplexityScore"
"DataPermissions"
"DatabaseRouter"
diff --git a/enterprise/backend/test/metabase_enterprise/api/session_test.clj b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
index 8a290330b7b..a6ecf40f043 100644
--- a/enterprise/backend/test/metabase_enterprise/api/session_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
@@ -25,6 +25,7 @@
:config-text-file
:content-translation
:content-verification
+ :data-apps
:data-complexity-score
:dashboard-subscription-filters
:disable-password-login
@@ -79,6 +80,7 @@
:config_text_file true
:content_translation true
:content_verification true
+ :data-apps true
:data-complexity-score true
:dashboard_subscription_filters true
:disable_password_login true
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj
new file mode 100644
index 00000000000..a619d0f3b11
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/api_test.clj
@@ -0,0 +1,298 @@
+(ns metabase-enterprise.data-apps.api-test
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase-enterprise.data-apps.sync :as data-app.sync]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+;;; ---------------------------------------------- Helpers ----------------------------------------------
+
+(defn- create-app! []
+ (t2/insert! :model/DataApp
+ :name "demo"
+ :display_name "Demo"
+ :bundle_path "data_apps/demo/index.js"
+ :bundle (.getBytes "BUNDLE" "UTF-8")
+ :bundle_hash "abc123"))
+
+(def ^:private fake-sha "0123456789abcdef0123456789abcdef01234567")
+
+(defn- snapshot
+ "Build a snapshot (as the remote-sync import passes one) from a path->content
+ map. `read-file` returns file text (a string) or nil."
+ [path->content & {:keys [sha] :or {sha fake-sha}}]
+ {:sha sha
+ :list-files (fn [] (vec (keys path->content)))
+ :read-file (fn [p] (get path->content p))})
+
+(defn- app-config
+ "Render a per-app data_app.yaml from `{:name :path :allowed_hosts}`. No slug: an
+ app's slug is the name of the directory the config sits in."
+ [{:keys [name path allowed_hosts]}]
+ (str (format "name: %s\npath: %s\n" name path)
+ (when (seq allowed_hosts)
+ (apply str "allowed_hosts:\n"
+ (map #(format " - %s\n" %) allowed_hosts)))))
+
+(defn- app-files
+ "Repo files for one data app under `data_apps/<dir>/`: its data_app.yaml plus a
+ bundle at `path` with `bundle` content."
+ [dir {:keys [path bundle] :as cfg}]
+ {(format "data_apps/%s/data_app.yaml" dir) (app-config cfg)
+ (format "data_apps/%s/%s" dir path) bundle})
+
+;;; ---------------------------------------------- Permissions ----------------------------------------------
+
+(deftest non-superuser-can-view-and-list-but-not-manage-test
+ ;; global mode so the `:data-apps` premium feature is visible to the real-HTTP
+ ;; `user-real-request` calls below (which run on Jetty threads that don't inherit
+ ;; a thread-local `binding`).
+ (mt/test-helpers-set-global-values!
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-model-cleanup [:model/DataApp]
+ (create-app!)
+ (testing "a non-superuser can view (open) a data app"
+ (is (= [{:name "demo" :display_name "Demo"}]
+ (mt/user-http-request :rasta :get 200 "apps")))
+ (is (= {:name "demo" :display_name "Demo"}
+ (mt/user-http-request :rasta :get 200 "apps/demo")))
+ (is (str/includes?
+ (str (mt/user-real-request :rasta :get 200 "apps/demo/bundle"))
+ "BUNDLE")))
+ (testing "but is still forbidden from managing data apps"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "apps/repo-status")))
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 "apps/demo" {:enabled false}))))))))
+
+(deftest superuser-can-manage-and-view-test
+ (mt/test-helpers-set-global-values!
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-model-cleanup [:model/DataApp]
+ (create-app!)
+ (testing "a superuser can list, read metadata, and serve the bundle"
+ (is (=? [{:name "demo" :display_name "Demo"}]
+ (mt/user-http-request :crowberto :get 200 "apps")))
+ (is (=? {:name "demo"}
+ (mt/user-http-request :crowberto :get 200 "apps/demo")))
+ (is (str/includes?
+ (str (mt/user-real-request :crowberto :get 200 "apps/demo/bundle"))
+ "BUNDLE")))))))
+
+(deftest list-available-apps-test
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-model-cleanup [:model/DataApp]
+ (t2/insert! :model/DataApp :name "ready" :display_name "Ready" :bundle_path "data_apps/ready/index.js")
+ (t2/insert! :model/DataApp :name "disabled" :display_name "Disabled" :bundle_path "data_apps/disabled/index.js"
+ :enabled false)
+ (t2/insert! :model/DataApp :name "failed" :display_name "Failed" :bundle_path "data_apps/failed/index.js"
+ :sync_error "Could not read bundle")
+ (is (=? [{:name "ready" :display_name "Ready"}]
+ (mt/user-http-request :rasta :get 200 "apps?available=true"))))))
+
+(deftest bundle-includes-allowed-hosts-header-test
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-model-cleanup [:model/DataApp]
+ (t2/insert! :model/DataApp
+ :name "demo"
+ :display_name "Demo"
+ :bundle_path "data_apps/demo/index.js"
+ :bundle (.getBytes "BUNDLE" "UTF-8")
+ :bundle_hash "abc123"
+ :allowed_hosts ["https://api.example.com"])
+ (testing "the bundle response carries the app's allowed_hosts as a JSON header"
+ (let [resp (mt/user-http-request-full-response :crowberto :get 200 "apps/demo/bundle")]
+ (is (= "[\"https://api.example.com\"]"
+ (get-in resp [:headers "X-Metabase-Data-App-Allowed-Hosts"])))))
+ (testing "an app with no allowed_hosts still sends the header as an empty JSON array"
+ (t2/update! :model/DataApp :name "demo" {:allowed_hosts []})
+ (let [resp (mt/user-http-request-full-response :crowberto :get 200 "apps/demo/bundle")]
+ (is (= "[]"
+ (get-in resp [:headers "X-Metabase-Data-App-Allowed-Hosts"]))))))))
+
+(deftest list-includes-allowed-hosts-test
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-model-cleanup [:model/DataApp]
+ (t2/insert! :model/DataApp
+ :name "withhosts" :display_name "With"
+ :bundle_path "data_apps/withhosts/index.js"
+ :allowed_hosts ["https://api.example.com"])
+ ;; inserted without the column → stored NULL, exercising the read coercion
+ (t2/insert! :model/DataApp
+ :name "nohosts" :display_name "No"
+ :bundle_path "data_apps/nohosts/index.js")
+ (testing "the list endpoint returns allowed_hosts, always a list (NULL → [])"
+ (let [by-name (->> (mt/user-http-request :crowberto :get 200 "apps")
+ (into {} (map (juxt :name identity))))]
+ (is (= ["https://api.example.com"]
+ (get-in by-name ["withhosts" :allowed_hosts])))
+ (is (= [] (get-in by-name ["nohosts" :allowed_hosts]))))))))
+
+;;; ----------------------------------------------------- Sync -----------------------------------------------------
+
+(deftest import-materializes-apps-test
+ (mt/with-model-cleanup [:model/DataApp]
+ (let [result (data-app.sync/import-from-snapshot!
+ (snapshot (merge (app-files "sales" {:name "Sales" :path "dist/index.js" :bundle "SALES-BUNDLE"})
+ (app-files "ops" {:name "Ops" :path "dist/app.js" :bundle "OPS-BUNDLE"}))))]
+ (is (=? {:synced 2} result))
+ (is (= #{"sales" "ops"} (t2/select-fn-set :name :model/DataApp)))
+ (let [sales (t2/select-one :model/DataApp :name "sales")]
+ (is (= "SALES-BUNDLE" (String. ^bytes (:bundle sales) "UTF-8")))
+ (is (= "Sales" (:display_name sales)))
+ (is (= "data_apps/sales/dist/index.js" (:bundle_path sales)))
+ (is (true? (:enabled sales)))
+ (is (= fake-sha (:last_synced_sha sales)))
+ (is (nil? (:sync_error sales)))))))
+
+(deftest import-stores-allowed-hosts-test
+ (mt/with-model-cleanup [:model/DataApp]
+ (testing "allowed_hosts from data_app.yaml are persisted on the row"
+ (data-app.sync/import-from-snapshot!
+ (snapshot (app-files "sales" {:name "Sales" :path "dist/index.js" :bundle "B"
+ :allowed_hosts ["https://api.example.com" "https://*.acme.com"]})))
+ (is (= ["https://api.example.com" "https://*.acme.com"]
+ (:allowed_hosts (t2/select-one :model/DataApp :name "sales")))))
+ (testing "re-syncing without allowed_hosts clears them to an empty list"
+ (data-app.sync/import-from-snapshot!
+ (snapshot (app-files "sales" {:name "Sales" :path "dist/index.js" :bundle "B"})))
+ (is (= [] (:allowed_hosts (t2/select-one :model/DataApp :name "sales")))))))
+
+(deftest import-keeps-apps-absent-from-snapshot-test
+ (mt/with-model-cleanup [:model/DataApp]
+ (data-app.sync/import-from-snapshot!
+ (snapshot (merge (app-files "keep" {:name "Keep" :path "index.js" :bundle "KEEP"})
+ (app-files "gone" {:name "Gone" :path "index.js" :bundle "GONE"}))))
+ (is (= #{"keep" "gone"} (t2/select-fn-set :name :model/DataApp)))
+ ;; A sync never deletes: an app missing from a later snapshot is kept, not
+ ;; pruned. Removal is an explicit admin action (DELETE /api/apps/:slug).
+ (data-app.sync/import-from-snapshot!
+ (snapshot (app-files "keep" {:name "Keep" :path "index.js" :bundle "KEEP"})))
+ (is (= #{"keep" "gone"} (t2/select-fn-set :name :model/DataApp))
+ "the app absent from the later snapshot is kept")))
+
+(deftest delete-endpoint-test
+ (mt/test-helpers-set-global-values!
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-model-cleanup [:model/DataApp]
+ (create-app!)
+ (testing "a non-superuser cannot remove an app"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :delete 403 "apps/demo")))
+ (is (t2/exists? :model/DataApp :name "demo")))
+ (testing "a superuser removes the app"
+ (is (nil? (mt/user-http-request :crowberto :delete 204 "apps/demo")))
+ (is (not (t2/exists? :model/DataApp :name "demo"))))
+ (testing "removing a non-existent app 404s"
+ (mt/user-http-request :crowberto :delete 404 "apps/missing"))))))
+
+(deftest import-preserves-enabled-across-syncs-test
+ (mt/with-model-cleanup [:model/DataApp]
+ (data-app.sync/import-from-snapshot!
+ (snapshot (app-files "a" {:name "A" :path "index.js" :bundle "V1"})))
+ (t2/update! :model/DataApp :name "a" {:enabled false})
+ ;; a new bundle must not flip the admin's enabled toggle back on
+ (data-app.sync/import-from-snapshot!
+ (snapshot (app-files "a" {:name "A" :path "index.js" :bundle "V2"})))
+ (let [a (t2/select-one :model/DataApp :name "a")]
+ (is (false? (:enabled a)) "the disabled toggle is preserved")
+ (is (= "V2" (String. ^bytes (:bundle a) "UTF-8")) "the bundle is still updated"))))
+
+(deftest import-per-app-error-test
+ (testing "a missing bundle file fails just that app, not the whole import"
+ (mt/with-model-cleanup [:model/DataApp]
+ (data-app.sync/import-from-snapshot!
+ (snapshot (merge (app-files "good" {:name "Good" :path "index.js" :bundle "GOOD"})
+ ;; "bad" declares a path that doesn't exist
+ {"data_apps/bad/data_app.yaml" (app-config {:name "Bad" :path "missing.js"})})))
+ (is (= #{"good" "bad"} (t2/select-fn-set :name :model/DataApp)))
+ (let [good (t2/select-one :model/DataApp :name "good")
+ bad (t2/select-one :model/DataApp :name "bad")]
+ (is (= "GOOD" (String. ^bytes (:bundle good) "UTF-8")))
+ (is (nil? (:sync_error good)))
+ (is (nil? (:bundle bad)))
+ (is (str/includes? (:sync_error bad) "missing.js"))))))
+
+(deftest import-serves-each-app-from-its-directory-test
+ (testing "the directory an app lives in is the slug it's served at — two apps can't collide on one"
+ (mt/with-model-cleanup [:model/DataApp]
+ (data-app.sync/import-from-snapshot!
+ (snapshot (merge (app-files "one" {:name "One" :path "a.js" :bundle "A"})
+ (app-files "two" {:name "Two" :path "b.js" :bundle "B"}))))
+ (is (= #{"one" "two"} (t2/select-fn-set :name :model/DataApp))))))
+
+(deftest import-isolates-bad-config-test
+ (testing "a malformed data_app.yaml is isolated: other apps still sync, the bad one is reported, nothing is pruned"
+ (mt/with-model-cleanup [:model/DataApp]
+ ;; pre-existing app that must survive a sync where another config is broken
+ (data-app.sync/import-from-snapshot!
+ (snapshot (app-files "existing" {:name "Existing" :path "i.js" :bundle "E"})))
+ (let [result (data-app.sync/import-from-snapshot!
+ (snapshot (merge (app-files "good" {:name "Good" :path "i.js" :bundle "GOOD"})
+ {"data_apps/bad/data_app.yaml" "name: [unterminated"})))]
+ (is (=? {:synced 1} result))
+ (is (= 1 (count (:config-errors result))))
+ (is (= #{"existing" "good"} (t2/select-fn-set :name :model/DataApp))
+ "the good app is added and the pre-existing app is NOT pruned despite the bad config")))))
+
+(deftest sync-from-snapshot!-never-throws-test
+ (testing "a malformed data_app.yaml is isolated into :config-errors; the app just doesn't appear, the sync doesn't throw"
+ (mt/with-model-cleanup [:model/DataApp]
+ (let [result (data-app.sync/sync-from-snapshot!
+ (snapshot {"data_apps/x/data_app.yaml" "name: [unterminated"}))]
+ (is (seq (:config-errors result)))
+ (is (empty? (t2/select-fn-set :name :model/DataApp))))))
+ (testing "a clean sync materializes the app with no config errors"
+ (mt/with-model-cleanup [:model/DataApp]
+ (let [result (data-app.sync/sync-from-snapshot!
+ (snapshot (app-files "a" {:name "A" :path "index.js" :bundle "A"})))]
+ (is (empty? (:config-errors result)))
+ (is (= #{"a"} (t2/select-fn-set :name :model/DataApp)))))))
+
+;;; ----------------------------------------------------- API -----------------------------------------------------
+
+(deftest list-and-bundle-endpoints-test
+ (mt/test-helpers-set-global-values!
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-model-cleanup [:model/DataApp]
+ (data-app.sync/import-from-snapshot!
+ (snapshot (app-files "demo" {:name "Demo app" :path "dist/index.js" :bundle "DEMOBUNDLE"})))
+ (testing "GET / lists the synced apps"
+ (is (=? [{:name "demo" :display_name "Demo app"
+ :bundle_path "data_apps/demo/dist/index.js" :enabled true}]
+ (mt/user-http-request :crowberto :get 200 "apps"))))
+ (testing "GET /:slug/bundle serves the cached bytes"
+ (is (str/includes?
+ (str (mt/user-real-request :crowberto :get 200 "apps/demo/bundle"))
+ "DEMOBUNDLE")))))))
+
+(deftest repo-status-endpoint-test
+ (mt/with-premium-features #{:data-apps}
+ (testing "reports no repository when none is connected"
+ (mt/with-dynamic-fn-redefs [data-app.sync/repo-url (constantly nil)]
+ (is (=? {:configured false :url nil}
+ (mt/user-http-request :crowberto :get 200 "apps/repo-status")))))
+ (testing "reports the connected repository URL"
+ (mt/with-dynamic-fn-redefs [data-app.sync/repo-url (constantly "https://github.com/metabase/stats-remote-sync")]
+ (is (=? {:configured true :url "https://github.com/metabase/stats-remote-sync"}
+ (mt/user-http-request :crowberto :get 200 "apps/repo-status")))))))
+
+(deftest enable-disable-endpoint-test
+ (mt/test-helpers-set-global-values!
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-model-cleanup [:model/DataApp]
+ (data-app.sync/import-from-snapshot!
+ (snapshot (app-files "demo" {:name "Demo" :path "index.js" :bundle "BUNDLE"})))
+ (testing "PUT /:slug can disable an app"
+ (is (=? {:name "demo" :enabled false}
+ (mt/user-http-request :crowberto :put 200 "apps/demo" {:enabled false}))))
+ (testing "a disabled app is not served"
+ (is (= "Not found." (mt/user-http-request :crowberto :get 404 "apps/demo")))
+ (mt/user-real-request :crowberto :get 404 "apps/demo/bundle"))
+ (testing "re-enabling restores serving"
+ (is (=? {:enabled true}
+ (mt/user-http-request :crowberto :put 200 "apps/demo" {:enabled true})))
+ (is (=? {:name "demo"} (mt/user-http-request :crowberto :get 200 "apps/demo"))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/config_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/config_test.clj
new file mode 100644
index 00000000000..9d3c4769db1
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/config_test.clj
@@ -0,0 +1,80 @@
+(ns metabase-enterprise.data-apps.config-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.data-apps.config :as data-app.config]))
+
+(set! *warn-on-reflection* true)
+
+(defn- ->bytes ^bytes [^String s]
+ (.getBytes s "UTF-8"))
+
+(defn- parse
+ "Parse a `data_app.yaml` as if it sat in `dir` (default `data_apps/sales`, so the
+ parsed slug is `sales` — the slug is the directory's name, never a config key)."
+ ([s] (parse s "data_apps/sales"))
+ ([s dir] (data-app.config/parse-app-config (->bytes s) dir)))
+
+(deftest parse-valid-config-test
+ (is (= {:slug "sales" :display_name "Sales dashboard" :path "dist/index.js" :allowed_hosts []}
+ (parse "name: Sales dashboard
+path: ./dist/index.js"))))
+
+(deftest slug-comes-from-the-directory-test
+ (testing "the app's slug is the name of the directory it lives in"
+ (is (= "inventory" (:slug (parse "name: X\npath: dist/index.js" "data_apps/inventory")))))
+ (testing "a directory name that isn't a usable slug is rejected — the app would have no URL to be served at"
+ (doseq [bad ["Sales" "my_app" "sales app" "-sales" "sales-"]]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"lowercase letters, numbers, and dashes"
+ (parse "name: X\npath: dist/index.js" (str "data_apps/" bad)))
+ (str "should reject the directory: " bad)))))
+
+(deftest parse-allowed-hosts-test
+ (testing "valid entries are lowercased, trailing-slash-stripped, and de-duplicated"
+ (is (= ["https://api.example.com" "https://*.internal.acme.com"]
+ (:allowed_hosts
+ (parse "name: X\npath: dist/index.js\nallowed_hosts:\n - https://API.example.com/\n - https://*.internal.acme.com\n - https://api.example.com")))))
+ (testing "absent → empty vector"
+ (is (= [] (:allowed_hosts (parse "name: X\npath: dist/index.js")))))
+ (testing "a non-list value is rejected"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"allowed_hosts.*must be a list"
+ (parse "name: X\npath: dist/index.js\nallowed_hosts: https://api.example.com"))))
+ (testing "invalid entries (bare *, path, non-http scheme, no scheme) are rejected"
+ (doseq [bad ["*" "https://example.com/path" "ftp://example.com" "example.com"]]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"not a valid allowed_hosts entry"
+ (parse (str "name: X\npath: dist/index.js\nallowed_hosts:\n - \"" bad "\"")))
+ (str "should reject: " bad)))))
+
+(deftest parse-strips-leading-dot-slash-test
+ (is (= "dist/app.js"
+ (:path (parse "name: X\npath: ./dist/app.js")))))
+
+(deftest unknown-fields-are-ignored-test
+ (testing "unknown keys don't fail the parse — including a stray `slug`, which the directory name overrides"
+ (is (= {:slug "sales" :display_name "X" :path "dist/index.js" :allowed_hosts []}
+ (parse "name: X\nslug: elsewhere\nfuture_option: 1\npath: dist/index.js")))))
+
+(deftest parse-errors-test
+ (testing "missing name"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"name"
+ (parse "path: dist/index.js"))))
+ (testing "missing path"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"path"
+ (parse "name: X"))))
+ (testing "malformed yaml"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Could not parse"
+ (parse "name: [unterminated"))))
+ (testing "path traversal is rejected"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must not contain"
+ (parse "name: X\npath: ../other/dist/index.js")))
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"must not contain"
+ (parse "name: X\npath: dist/../../escape.js"))))
+ (testing "a directory whose name collides with an API sub-route is rejected"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"reserved slug"
+ (parse "name: X\npath: dist/index.js" "data_apps/repo-status")))))
+
+(deftest parse-errors-carry-400-test
+ (try
+ (parse "name: X")
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= 400 (:status-code (ex-data e)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/csp_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/csp_test.clj
new file mode 100644
index 00000000000..4427c7abc09
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/csp_test.clj
@@ -0,0 +1,64 @@
+(ns metabase-enterprise.data-apps.csp-test
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase.config.core :as config]
+ [metabase.server.middleware.security :as mw.security]
+ [metabase.test :as mt]))
+
+(set! *warn-on-reflection* true)
+
+(defn- connect-src-for!
+ "The `connect-src` directive of the CSP that the security middleware emits for
+ a request to `uri`."
+ [uri]
+ (with-redefs [config/is-dev? false]
+ (let [handler (mw.security/add-security-headers
+ (fn [_req respond _raise] (respond {:status 200 :headers {} :body "ok"})))
+ response (handler {:uri uri :headers {}} identity identity)
+ csp (get-in response [:headers "Content-Security-Policy"])]
+ (->> (str/split csp #";\s*")
+ (filter #(str/starts-with? % "connect-src "))
+ first))))
+
+(deftest data-app-connect-src-allowed-hosts-test
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-temp [:model/DataApp _ {:name "boba"
+ :display_name "Boba"
+ :bundle_path "data_apps/boba/dist/index.js"
+ :enabled true
+ :allowed_hosts ["https://api.example.com" "https://*.acme.com"]}]
+ (testing "the data-app iframe document's connect-src includes the app's allowed_hosts (and keeps 'self')"
+ (let [cs (connect-src-for! "/embed/apps/boba")]
+ (is (str/includes? cs "https://api.example.com"))
+ (is (str/includes? cs "https://*.acme.com"))
+ (is (str/includes? cs "'self'"))))
+ (testing "a deeper sub-route of the same app gets them too"
+ (is (str/includes? (connect-src-for! "/embed/apps/boba/sub/route")
+ "https://api.example.com")))
+ (testing "the main app's connect-src does NOT include them"
+ (is (not (str/includes? (connect-src-for! "/") "https://api.example.com"))))
+ (testing "an unknown app contributes no hosts"
+ (is (not (str/includes? (connect-src-for! "/embed/apps/nope")
+ "api.example.com")))))))
+
+(deftest data-app-connect-src-hosts-fn-test
+ (mt/with-temp [:model/DataApp _ {:name "boba"
+ :display_name "Boba"
+ :bundle_path "x"
+ :enabled true
+ :allowed_hosts ["https://api.example.com"]}]
+ (testing "with the :data-apps feature the EE impl returns the app's allowed_hosts"
+ (mt/with-premium-features #{:data-apps}
+ (is (= ["https://api.example.com"] (mw.security/data-app-connect-src-hosts "boba")))))
+ (testing "without the feature it falls back to []"
+ (mt/with-premium-features #{}
+ (is (= [] (mw.security/data-app-connect-src-hosts "boba")))))
+ (testing "a disabled app contributes nothing"
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-temp [:model/DataApp _ {:name "off"
+ :display_name "Off"
+ :bundle_path "x"
+ :enabled false
+ :allowed_hosts ["https://nope.example.com"]}]
+ (is (= [] (mw.security/data-app-connect-src-hosts "off"))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.clj
new file mode 100644
index 00000000000..207ded48fb7
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/models/data_app_test.clj
@@ -0,0 +1,69 @@
+(ns metabase-enterprise.data-apps.models.data-app-test
+ "Unit coverage for the DataApp model: the blob-excluding reads, JSON that never
+ leaks the bundle bytes, the `allowed_hosts` NULL→[] read coercion, and the
+ superuser-only permission gating."
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.data-apps.models.data-app :as data-app]
+ [metabase.api.common :as api]
+ [metabase.models.interface :as mi]
+ [metabase.test :as mt]
+ [metabase.util.json :as json]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(defn- insert-app! [& {:as extra}]
+ (t2/insert-returning-pk!
+ :model/DataApp
+ (merge {:name "m"
+ :display_name "M"
+ :bundle_path "data_apps/m/index.js"
+ :bundle (.getBytes "BUNDLEBYTES" "UTF-8")
+ :bundle_hash "hash"}
+ extra)))
+
+(deftest to-json-never-includes-the-bundle-bytes-test
+ (mt/with-model-cleanup [:model/DataApp]
+ (insert-app!)
+ (let [app (t2/select-one :model/DataApp :name "m")
+ decoded (json/decode (json/encode app))]
+ (is (contains? app :bundle) "the selected instance still carries the raw bundle")
+ (is (not (contains? decoded "bundle"))
+ "but the JSON representation omits it")
+ (is (= "M" (get decoded "display_name"))))))
+
+(deftest non-blob-selects-exclude-the-bundle-test
+ (mt/with-model-cleanup [:model/DataApp]
+ (insert-app! :allowed_hosts ["https://api.example.com"])
+ (testing "select-one-non-blob returns metadata without the bundle blob"
+ (let [app (data-app/select-one-non-blob :name "m")]
+ (is (not (contains? app :bundle)))
+ (is (= "M" (:display_name app)))
+ (is (= ["https://api.example.com"] (:allowed_hosts app)))))
+ (testing "select-non-blob returns a seq of blob-free rows"
+ (let [apps (data-app/select-non-blob :name "m")]
+ (is (= 1 (count apps)))
+ (is (not (contains? (first apps) :bundle)))))))
+
+(deftest allowed-hosts-reads-as-a-vector-never-nil-test
+ (mt/with-model-cleanup [:model/DataApp]
+ (testing "a row stored with NULL allowed_hosts reads back as []"
+ (insert-app!)
+ (is (= [] (:allowed_hosts (t2/select-one :model/DataApp :name "m")))))
+ (testing "a stored list round-trips through the JSON transform"
+ (insert-app! :name "n" :allowed_hosts ["https://a.com" "https://b.com"])
+ (is (= ["https://a.com" "https://b.com"]
+ (:allowed_hosts (t2/select-one :model/DataApp :name "n")))))))
+
+(deftest permissions-test
+ (testing "a superuser can read, write, and create"
+ (binding [api/*is-superuser?* true]
+ (is (mi/can-read? :model/DataApp 1))
+ (is (mi/can-write? :model/DataApp 1))
+ (is (mi/can-create? :model/DataApp {}))))
+ (testing "any signed-in user can read (view), but write/create stay superuser-only"
+ (binding [api/*is-superuser?* false]
+ (is (mi/can-read? :model/DataApp 1))
+ (is (not (mi/can-write? :model/DataApp 1)))
+ (is (not (mi/can-create? :model/DataApp {}))))))
diff --git a/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.clj b/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.clj
new file mode 100644
index 00000000000..9ebc61fa078
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/data_apps/sync_test.clj
@@ -0,0 +1,117 @@
+(ns metabase-enterprise.data-apps.sync-test
+ "Unit coverage for the materialization edge cases not exercised through the API
+ suite: the `:changed` accounting (content vs. sha/timestamp bumps) and the
+ oversized-bundle guard (rejected with a sync_error, previously cached bundle
+ retained)."
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase-enterprise.data-apps.sync :as data-app.sync]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private fake-sha "0123456789abcdef0123456789abcdef01234567")
+
+(defn- snapshot
+ [path->content & {:keys [sha] :or {sha fake-sha}}]
+ {:sha sha
+ :list-files (fn [] (vec (keys path->content)))
+ :read-file (fn [p] (get path->content p))})
+
+(defn- app-files
+ "The repo files for one app in `data_apps/<dir>`. `dir` is the app's slug — the
+ config declares no slug, it is the directory's name."
+ [dir {:keys [name path bundle]}]
+ {(format "data_apps/%s/data_app.yaml" dir)
+ (format "name: %s\npath: %s\n" name path)
+ (format "data_apps/%s/%s" dir path) bundle})
+
+(deftest changed-count-tracks-content-not-sha-bumps-test
+ (mt/with-model-cleanup [:model/DataApp]
+ (let [files (app-files "a" {:name "A" :path "index.js" :bundle "V1"})]
+ (testing "the first sync counts the new app"
+ (is (=? {:synced 1 :changed 1}
+ (data-app.sync/import-from-snapshot! (snapshot files)))))
+ (testing "re-syncing identical content at a new sha is not a change"
+ (is (=? {:synced 1 :changed 0}
+ (data-app.sync/import-from-snapshot!
+ (snapshot files :sha "ffffffffffffffffffffffffffffffffffffffff")))))
+ (testing "a metadata-only change counts"
+ (is (=? {:changed 1}
+ (data-app.sync/import-from-snapshot!
+ (snapshot (app-files "a" {:name "A renamed" :path "index.js" :bundle "V1"}))))))
+ (testing "a bundle content change counts"
+ (is (=? {:changed 1}
+ (data-app.sync/import-from-snapshot!
+ (snapshot (app-files "a" {:name "A renamed" :path "index.js" :bundle "V2"})))))))))
+
+(deftest sync-across-repos-keeps-overrides-and-adds-test
+ (testing "linking repo A, unlinking, then linking repo B: keep A-only apps, override shared slugs with B, add B-only apps"
+ (mt/with-model-cleanup [:model/DataApp]
+ ;; Repo A: Foo + Bar
+ (data-app.sync/import-from-snapshot!
+ (snapshot (merge (app-files "foo" {:name "Foo" :path "index.js" :bundle "FOO"})
+ (app-files "bar" {:name "Bar A" :path "index.js" :bundle "BAR-A"}))))
+ (is (= #{"foo" "bar"} (t2/select-fn-set :name :model/DataApp)))
+ ;; Unlinking A doesn't sync (nothing prunes). Linking repo B (Bar + Baz)
+ ;; and importing it keeps Foo, overrides Bar by slug, and adds Baz.
+ (data-app.sync/import-from-snapshot!
+ (snapshot (merge (app-files "bar" {:name "Bar B" :path "index.js" :bundle "BAR-B"})
+ (app-files "baz" {:name "Baz" :path "index.js" :bundle "BAZ"}))))
+ (is (= #{"foo" "bar" "baz"} (t2/select-fn-set :name :model/DataApp))
+ "Foo (from repo A) is kept and Baz (from repo B) is added")
+ (is (= "Foo" (:display_name (t2/select-one :model/DataApp :name "foo")))
+ "Foo is untouched by repo B")
+ (let [bar (t2/select-one :model/DataApp :name "bar")]
+ (is (= "Bar B" (:display_name bar))
+ "Bar is overridden in place by repo B (slug conflict)")
+ (is (= "BAR-B" (String. ^bytes (:bundle bar) "UTF-8"))
+ "Bar's cached bundle is repo B's")))))
+
+(defn- oversized-bundle ^String []
+ (.repeat "a" (int (inc data-app.sync/max-bundle-bytes))))
+
+(deftest oversized-bundle-is-rejected-test
+ (testing "a bundle over the size cap is rejected with a sync_error, no bundle cached"
+ (mt/with-model-cleanup [:model/DataApp]
+ (data-app.sync/import-from-snapshot!
+ (snapshot (app-files "big" {:name "Big" :path "index.js"
+ :bundle (oversized-bundle)})))
+ (let [app (t2/select-one :model/DataApp :name "big")]
+ (is (some? app) "the app still appears in the list")
+ (is (nil? (:bundle app)) "no oversized bundle was cached")
+ (is (str/includes? (:sync_error app) "MiB"))))))
+
+(deftest oversized-resync-keeps-the-previous-bundle-test
+ (testing "an oversized re-sync sets sync_error but keeps the last good bundle"
+ (mt/with-model-cleanup [:model/DataApp]
+ (data-app.sync/import-from-snapshot!
+ (snapshot (app-files "app" {:name "App" :path "index.js" :bundle "GOOD"})))
+ (data-app.sync/import-from-snapshot!
+ (snapshot (app-files "app" {:name "App" :path "index.js"
+ :bundle (oversized-bundle)})))
+ (let [app (t2/select-one :model/DataApp :name "app")]
+ (is (= "GOOD" (String. ^bytes (:bundle app) "UTF-8"))
+ "the previously cached bundle is retained")
+ (is (str/includes? (:sync_error app) "MiB"))))))
+
+(deftest a-directory-without-a-config-is-not-an-app-test
+ (testing "a data_apps/<dir> that ships a bundle but no data_app.yaml is not discovered — no app, no error"
+ (mt/with-model-cleanup [:model/DataApp]
+ (let [result (data-app.sync/import-from-snapshot!
+ (snapshot {"data_apps/orphan/index.js" "BUNDLE"}))]
+ (is (=? {:synced 0 :changed 0 :config-errors []} result))
+ (is (empty? (t2/select-fn-set :name :model/DataApp)))))))
+
+(deftest an-unreadable-config-is-a-config-error-test
+ (testing "a data_app.yaml the snapshot lists but can't read is isolated as a config-error, not a crash"
+ (mt/with-model-cleanup [:model/DataApp]
+ (let [result (data-app.sync/import-from-snapshot!
+ {:sha fake-sha
+ :list-files (fn [] ["data_apps/ghost/data_app.yaml"])
+ :read-file (fn [_] nil)})]
+ (is (= 1 (count (:config-errors result))))
+ (is (str/includes? (first (:config-errors result)) "data_apps/ghost/data_app.yaml"))
+ (is (empty? (t2/select-fn-set :name :model/DataApp)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/data_app_pull_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/data_app_pull_test.clj
new file mode 100644
index 00000000000..5073ef3d727
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/data_app_pull_test.clj
@@ -0,0 +1,89 @@
+(ns metabase-enterprise.remote-sync.data-app-pull-test
+ "A remote-sync pull's outcome (the \"N changes\" summary the admin sees) must
+ count data-app changes. Data apps live under `data_apps/` — outside serdes — and
+ are materialized separately (`metabase-enterprise.data-apps.sync`), so without
+ `impl/fold-data-app-changes` a pull whose only changes are data apps reports
+ `pull-skipped` / `count 0`. These cover the three pull shapes: data-app-only,
+ mixed (serdes + data apps), and serdes-only."
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.remote-sync.impl :as impl]
+ [metabase-enterprise.remote-sync.source.protocol :as source.p]
+ [metabase-enterprise.remote-sync.test-helpers :as rs.test]
+ [metabase.search.test-util :as search.tu]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once (fixtures/initialize :db))
+(use-fixtures :each rs.test/clean-remote-sync-state rs.test/commit-with-temp)
+
+(defn- import-at!
+ "Run `import!` against the source's snapshot at `version`, complete the task (so
+ `last-version` advances for the next pull), and return the result."
+ [src version & {:keys [force?] :or {force? false}}]
+ (let [task (t2/insert-returning-pk! :model/RemoteSyncTask
+ {:sync_task_type "import" :initiated_by (mt/user->id :rasta)})
+ result (impl/import! (source.p/snapshot-at src version) task :force? force?)]
+ (impl/handle-task-result! result task)
+ result))
+
+(defn- app-tree
+ "Repo files for one data app: its `data_app.yaml` + a bundle at `dist/index.js`."
+ [slug bundle]
+ {(str "data_apps/" slug "/data_app.yaml") (str "name: " slug "\npath: dist/index.js\n")
+ (str "data_apps/" slug "/dist/index.js") bundle})
+
+;; One self-contained serdes entity (a bare collection — no DB deps), used as the
+;; "data" change. Reuses the path/content shape the mock harness imports cleanly.
+(def ^:private coll-path
+ "collections/M-Q4pcV0qkiyJ0kiSWECl_some_collection/M-Q4pcV0qkiyJ0kiSWECl_some_collection.yaml")
+(def ^:private coll-file
+ {coll-path (rs.test/generate-collection-yaml "M-Q4pcV0qkiyJ0kiSWECl" "Some Collection")})
+
+(defn- pull-outcome!
+ "Establish `v0` as the baseline, then pull `v1` (a normal, non-forced pull) and
+ return its `:outcome`."
+ [v0 v1]
+ (let [src (rs.test/versioned-source :trees {"v0" v0 "v1" v1} :current "v0")]
+ (is (= :success (:status (import-at! src "v0" :force? true))) "baseline import succeeds")
+ (let [result (import-at! src "v1")]
+ (is (= :success (:status result)) "pull succeeds")
+ (:outcome result))))
+
+(deftest data-app-only-pull-counts-app-changes-test
+ (testing "a pull whose only change is a data app is reported as a real pull, not pull-skipped / 0 changes"
+ (search.tu/with-index-disabled
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-temporary-setting-values [remote-sync-type :read-write remote-sync-transforms false]
+ (mt/with-model-cleanup [:model/DataApp]
+ (let [outcome (pull-outcome! (app-tree "sales" "BUNDLE-V1")
+ (app-tree "sales" "BUNDLE-V2"))]
+ (is (= "pulled" (:kind outcome)) "not reported as skipped")
+ (is (= 1 (:count outcome)) "the one changed data app is counted"))))))))
+
+(deftest data-only-pull-excludes-unchanged-apps-test
+ (testing "a serdes-only pull counts serdes content; unchanged data apps add nothing"
+ (search.tu/with-index-disabled
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-temporary-setting-values [remote-sync-type :read-write remote-sync-transforms false]
+ (mt/with-model-cleanup [:model/DataApp :model/Collection]
+ ;; v1 adds a collection; the data app is byte-for-byte the same as v0.
+ (let [app (app-tree "sales" "BUNDLE")
+ outcome (pull-outcome! app (merge coll-file app))]
+ (is (= "pulled" (:kind outcome)))
+ (is (= 1 (:count outcome)) "the collection counts; the unchanged app adds 0"))))))))
+
+(deftest mixed-pull-counts-serdes-and-apps-test
+ (testing "a mixed pull counts serdes content AND the changed data apps"
+ (search.tu/with-index-disabled
+ (mt/with-premium-features #{:data-apps}
+ (mt/with-temporary-setting-values [remote-sync-type :read-write remote-sync-transforms false]
+ (mt/with-model-cleanup [:model/DataApp :model/Collection]
+ ;; v1 adds a collection AND changes the data app's bundle.
+ (let [outcome (pull-outcome! (app-tree "ops" "BUNDLE")
+ (merge coll-file (app-tree "ops" "BUNDLE-V2")))]
+ (is (= "pulled" (:kind outcome)))
+ (is (= 2 (:count outcome)) "the collection (1) plus the changed data app (1)"))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.clj
new file mode 100644
index 00000000000..f3d5a55bae7
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/data_apps_test.clj
@@ -0,0 +1,60 @@
+(ns metabase-enterprise.remote-sync.data-apps-test
+ "Integration coverage for the data-apps hook in the remote-sync import pipeline:
+ importing a repo materializes data apps from its `data_apps/` directory."
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.data-apps.models.data-app]
+ [metabase-enterprise.remote-sync.impl :as impl]
+ [metabase-enterprise.remote-sync.source.protocol :as source.p]
+ [metabase-enterprise.remote-sync.test-helpers :as test-helpers]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [toucan2.core :as t2]))
+
+(use-fixtures :once (fixtures/initialize :db))
+(use-fixtures :each (fn [f] (test-helpers/clean-remote-sync-state f)))
+
+(comment metabase-enterprise.data-apps.models.data-app/keep-me)
+
+(defn- import! [files]
+ (let [source (test-helpers/create-mock-source :initial-files files)
+ task-id (t2/insert-returning-pk! :model/RemoteSyncTask
+ {:sync_task_type "import" :initiated_by (mt/user->id :rasta)})
+ ;; force: the mock source reports a constant version, so without this the
+ ;; second import in a test would hit the "version unchanged" skip branch
+ result (impl/import! (source.p/snapshot source) task-id :force? true)]
+ ;; calling import! directly leaves the task "running"; mark it ended so a
+ ;; subsequent import in the same test isn't blocked by the running-task guard
+ (t2/update! :model/RemoteSyncTask task-id {:ended_at :%now})
+ result))
+
+(deftest import-materializes-data-apps-test
+ (testing "a remote-sync import materializes data apps from data_apps/ alongside serdes content"
+ (mt/with-model-cleanup [:model/DataApp]
+ (let [files {"main" {"collections/c/c.yaml"
+ (test-helpers/generate-collection-yaml "data-apps-test-collx" "DA Coll")
+ "data_apps/sales/data_app.yaml" "name: Sales\npath: ./dist/index.js\n"
+ "data_apps/sales/dist/index.js" "SALESBUNDLE"}}
+ result (import! files)]
+ (is (= :success (:status result)))
+ (let [app (t2/select-one :model/DataApp :name "sales")]
+ (is (some? app) "the data app from the repo was materialized by the import")
+ (is (= "Sales" (:display_name app)))
+ (is (= "data_apps/sales/dist/index.js" (:bundle_path app)))
+ (is (true? (:enabled app)))
+ (is (= "SALESBUNDLE" (String. ^bytes (:bundle app) "UTF-8"))))))))
+
+(deftest import-keeps-data-apps-absent-from-repo-test
+ (testing "an import whose repo no longer has an app dir keeps that app (a sync never deletes)"
+ (mt/with-model-cleanup [:model/DataApp]
+ (import! {"main" {"data_apps/gone/data_app.yaml" "name: Gone\npath: ./i.js\n"
+ "data_apps/gone/i.js" "X"
+ "data_apps/kept/data_app.yaml" "name: Kept\npath: ./i.js\n"
+ "data_apps/kept/i.js" "K"}})
+ (is (= #{"gone" "kept"} (t2/select-fn-set :name :model/DataApp)))
+ (import! {"main" {"data_apps/kept/data_app.yaml" "name: Kept\npath: ./i.js\n"
+ "data_apps/kept/i.js" "K"}})
+ (is (some? (t2/select-one :model/DataApp :name "gone"))
+ "the app absent from the later import is kept, not pruned")
+ (is (some? (t2/select-one :model/DataApp :name "kept"))
+ "the still-present app is kept"))))
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
index 4f2f91a7480..38bb58f3360 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/models/entity_id_test.clj
@@ -54,6 +54,7 @@
:model/CollectionBookmark
:model/ContentTranslation
:model/DashboardBookmark
+ :model/DataApp
:model/DataComplexityScore
:model/DataPermissions
:model/DatabaseRouter
diff --git a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts
index 0c0008068cc..17e55384bdb 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts
+++ b/enterprise/frontend/src/embedding-sdk-ee/auth/auth.ts
@@ -29,10 +29,8 @@ import type { MetabaseAuthConfig } from "embedding-sdk-shared/types/auth-config"
import type { SdkAuthState } from "embedding-sdk-shared/types/auth-state";
import { SDK_AUTH_STATE_KEY } from "embedding-sdk-shared/types/auth-state";
import { requestSessionTokenFromEmbedJs } from "metabase/embedding/embedding-iframe-sdk/utils";
-import {
- sessionTokenHeaders,
- setApiKeyHeader,
-} from "metabase/embedding/lib/embedding-request-auth";
+import { getSessionTokenHeaders } from "metabase/embedding/lib/auth/get-session-token-headers";
+import { setApiKeyHeader } from "metabase/embedding/lib/auth/set-api-key-header";
import {
EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG,
isEmbeddingEajs,
@@ -74,7 +72,7 @@ PLUGIN_EMBEDDING_SDK_AUTH.initAuth = async (
// applies to the very request that triggered the refresh.
const sessionTokenHandler = async () => {
const session = await dispatch(getOrRefreshSession(authConfig)).unwrap();
- return session?.id ? sessionTokenHeaders(session.id) : undefined;
+ return session?.id ? getSessionTokenHeaders(session.id) : undefined;
};
// Check if we can use the auth pre-fetched by the bootstrap chunk
diff --git a/enterprise/frontend/src/embedding-sdk-package/bin/generate-package-support-files.ts b/enterprise/frontend/src/embedding-sdk-package/bin/generate-package-support-files.ts
index 1fb1e1d148a..78e96ecee1e 100644
--- a/enterprise/frontend/src/embedding-sdk-package/bin/generate-package-support-files.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/bin/generate-package-support-files.ts
@@ -34,6 +34,24 @@ export * from "./main.bundle.js";
writeToFile("nextjs.cjs", nextjs_cjs);
writeToFile("nextjs.js", nextjs_js);
+// Data-app specific imports
+const dataApp_cjs = `
+const DataApp = require("./data-app.bundle");
+
+module.exports = DataApp;
+`.trim();
+
+const dataApp_js = `
+export * from "./data-app.esm.js";
+`.trim();
+
+writeToFile("data-app.cjs", dataApp_cjs);
+writeToFile("data-app.js", dataApp_js);
+
+// The data-app dev preset (`data-app-dev.js`, ESM-only) and the dev entry
+// (`data-app-dev-entry.js`) are emitted directly by the rspack builds, so they
+// need no wrappers here.
+
// Development mode entry point.
// When the host app bundler resolves the "development" exports condition,
// this file sets a window global so the SDK bundle can detect dev mode.
@@ -46,7 +64,7 @@ try {
console.warn("Metabase SDK: Failed to set dev mode flag", e);
}
-module.exports = require("./main.bundle");
+export * from "./main.esm.js";
`.trim();
writeToFile("main.development.js", devMode_js);
diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/DataAppLink.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/DataAppLink.tsx
new file mode 100644
index 00000000000..e9c9ff2eeb2
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/DataAppLink.tsx
@@ -0,0 +1,21 @@
+import type { DataAppLinkProps } from "embedding-sdk-bundle/lib/data-app/router";
+import { getWindow } from "embedding-sdk-shared/lib/get-window";
+
+export const DataAppLink = ({ to, children, ...rest }: DataAppLinkProps) => {
+ const BundleDataAppLink =
+ getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.DataAppLink;
+
+ if (!BundleDataAppLink) {
+ return (
+ <a href={to} {...rest}>
+ {children}
+ </a>
+ );
+ }
+
+ return (
+ <BundleDataAppLink to={to} {...rest}>
+ {children}
+ </BundleDataAppLink>
+ );
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/index.ts b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/index.ts
new file mode 100644
index 00000000000..b1cd7e1db26
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/index.ts
@@ -0,0 +1 @@
+export { DataAppLink } from "./DataAppLink";
diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/DataAppRouter.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/DataAppRouter.tsx
new file mode 100644
index 00000000000..0774fdb73c5
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/DataAppRouter.tsx
@@ -0,0 +1,14 @@
+import type { ReactNode } from "react";
+
+import { getWindow } from "embedding-sdk-shared/lib/get-window";
+
+export const DataAppRouter = ({ children }: { children?: ReactNode }) => {
+ const BundleDataAppRouter =
+ getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.DataAppRouter;
+
+ if (!BundleDataAppRouter) {
+ return <>{children}</>;
+ }
+
+ return <BundleDataAppRouter>{children}</BundleDataAppRouter>;
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/index.ts b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/index.ts
new file mode 100644
index 00000000000..a4931dd7dcb
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/index.ts
@@ -0,0 +1 @@
+export { DataAppRouter } from "./DataAppRouter";
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx
new file mode 100644
index 00000000000..6c276693f62
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx
@@ -0,0 +1,107 @@
+import * as React from "react";
+import * as ReactDOM from "react-dom";
+import * as ReactDOMClient from "react-dom/client";
+import * as ReactDOMServer from "react-dom/server";
+import * as ReactJsxDevRuntime from "react/jsx-dev-runtime";
+import * as ReactJsxRuntime from "react/jsx-runtime";
+import * as sdkExports from "@metabase/embedding-sdk-react";
+import * as dataAppExports from "@metabase/embedding-sdk-react/data-app";
+import {
+ DataAppDevProvider,
+ DevToolbar,
+ createDataAppSandbox,
+ installDevDiagnostics,
+} from "@metabase/embedding-sdk-react/data-app-dev";
+import {
+ allowedHosts,
+ appSlug,
+ bundleUrl,
+ rebuiltEvent,
+} from "virtual:metabase-data-app-dev-config";
+import { createRoot } from "react-dom/client";
+
+// The same baseline reset the production iframe loads (`iframe-vendors.ts`), so the
+// dev preview matches production. style-loader injects it at runtime.
+import "metabase-enterprise/data_apps/sandbox/iframe-baseline.css";
+
+// The data-app dev entry. rspack bundles this file into the SDK dist as
+// `data-app-dev-entry.js` (see `rspack.embedding-sdk-package.config.js`),
+// inlining the sandbox + dev toolbar so they aren't part of the package's public
+// API. `react`, `react-dom`, `@metabase/embedding-sdk-react/*`, and the dev
+// plugin's `virtual:metabase-data-app-dev-config` are left EXTERNAL, so the
+// consumer's Vite resolves them — the bundle runs against the consumer's single
+// React/SDK instance (the same ones the app bundle is endowed with), and the dev
+// plugin provides the config (the app's `allowed_hosts` + the bundle URL/event).
+//
+// It mounts the diagnostics toolbar, builds the Near-Membrane sandbox, then
+// fetches + evaluates the app's IIFE bundle and renders it under
+// `DataAppDevProvider`. Load failures go through `console.error`, so the toolbar
+// surfaces them.
+
+const authConfig = {
+ metabaseInstanceUrl: import.meta.env.DATA_APP_MB_URL,
+ apiKey: import.meta.env.DATA_APP_MB_API_KEY,
+};
+
+installDevDiagnostics();
+
+const toolbarRoot = document.createElement("div");
+document.body.appendChild(toolbarRoot);
+createRoot(toolbarRoot).render(<DevToolbar />);
+
+const root = document.getElementById("root");
+if (!root) {
+ throw new Error("#root not found");
+}
+const appRoot = createRoot(root);
+
+const sandbox = createDataAppSandbox({
+ label: "dev",
+ targetWindow: window,
+ allowedHosts,
+ endowments: {
+ React,
+ reactDom: ReactDOM,
+ reactDomClient: ReactDOMClient,
+ reactDomServer: ReactDOMServer,
+ reactJsxRuntime: ReactJsxRuntime,
+ reactJsxDevRuntime: ReactJsxDevRuntime,
+ sdkExports,
+ dataAppExports,
+ },
+});
+
+async function loadAndRender() {
+ const res = await fetch(bundleUrl, { cache: "no-store" });
+
+ if (!res.ok) {
+ throw new Error(
+ `Failed to load the data-app bundle: ${res.status} ${res.statusText}.`,
+ );
+ }
+
+ const code = await res.text();
+ const { component: Component, providerProps } = sandbox.evaluate(code)();
+
+ appRoot.render(
+ <DataAppDevProvider
+ appSlug={appSlug}
+ authConfig={authConfig}
+ {...providerProps}
+ >
+ <Component />
+ </DataAppDevProvider>,
+ );
+}
+
+loadAndRender().catch((error) => {
+ console.error(error);
+});
+
+if (import.meta.hot) {
+ import.meta.hot.on(rebuiltEvent, () => {
+ loadAndRender().catch((error) => {
+ console.error(error);
+ });
+ });
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev.config.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev.config.ts
new file mode 100644
index 00000000000..f0add641747
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev.config.ts
@@ -0,0 +1,5 @@
+// Node subpath `@metabase/embedding-sdk-react/data-app-dev/config` with the Vite app config
+export {
+ dataAppConfig,
+ type DataAppConfigOverrides,
+} from "./data-app-dev/index";
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev.ts
new file mode 100644
index 00000000000..35c6a43e144
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev.ts
@@ -0,0 +1,6 @@
+// Browser subpath `@metabase/embedding-sdk-react/data-app-dev` with dev app client exports.
+// The Node Vite config preset lives at `/data-app-dev/config` (data-app-dev.config.ts).
+export { DataAppDevProvider } from "./data-app-dev/components/DataAppDevProvider/DataAppDevProvider";
+export { DevToolbar } from "./data-app-dev/components/DevToolbar/DevToolbar";
+export { installDevDiagnostics } from "./data-app-dev/components/DevToolbar/diagnostics";
+export { createDataAppSandbox } from "metabase-enterprise/data_apps/sandbox/sandbox";
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/bundle.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/bundle.ts
new file mode 100644
index 00000000000..8a6678438a3
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/bundle.ts
@@ -0,0 +1,22 @@
+/**
+ * Build/runtime constants shared by the data-app dev server preset and its dev
+ * plugin. The sandbox globals contract itself lives with the sandbox
+ * (`metabase-enterprise/data_apps/sandbox/globals.ts`); it's re-exported here
+ * so the dev preset keeps a single import site.
+ */
+
+export {
+ DATA_APP_EXTERNALS,
+ DATA_APP_FACTORY_GLOBAL,
+ DATA_APP_GLOBALS,
+ DATA_APP_GLOBAL_NAMES,
+} from "metabase-enterprise/data_apps/sandbox/globals";
+
+/** The app entry the IIFE is built from. */
+export const DATA_APP_ENTRY = "src/index.tsx";
+
+/** Dev-only URL the dev entry fetches the freshly-built IIFE bundle from. */
+export const DATA_APP_BUNDLE_URL = "/@data-app-bundle.js";
+
+/** Custom HMR event the dev plugin emits on rebuild so the dev entry soft-reloads. */
+export const DATA_APP_REBUILT_EVENT = "data-app:rebuilt";
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/bundle.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/bundle.unit.spec.ts
new file mode 100644
index 00000000000..b7e6ad0ed2c
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/bundle.unit.spec.ts
@@ -0,0 +1,20 @@
+import { DATA_APP_EXTERNALS, DATA_APP_GLOBALS } from "./bundle";
+
+describe("data-app bundle externals", () => {
+ it("externalizes React DOM imports to endowed globals", () => {
+ expect(DATA_APP_GLOBALS).toEqual(
+ expect.objectContaining({
+ "react-dom": "__react_dom__",
+ "react-dom/client": "__react_dom_client__",
+ "react-dom/server": "__react_dom_server__",
+ }),
+ );
+ expect(DATA_APP_EXTERNALS).toEqual(
+ expect.arrayContaining([
+ "react-dom",
+ "react-dom/client",
+ "react-dom/server",
+ ]),
+ );
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DataAppDevProvider/DataAppDevProvider.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DataAppDevProvider/DataAppDevProvider.tsx
new file mode 100644
index 00000000000..c5257a857c9
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DataAppDevProvider/DataAppDevProvider.tsx
@@ -0,0 +1,33 @@
+import { once } from "underscore";
+
+import type { MetabaseProviderProps } from "embedding-sdk-bundle/types/metabase-provider";
+import { MetabaseProvider } from "embedding-sdk-package/components/public/MetabaseProvider/MetabaseProvider";
+import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";
+
+const registerDataAppDevContext = once((appSlug: string) => {
+ ensureMetabaseProviderPropsStore().updateInternalProps({
+ dataApp: { name: appSlug, isDev: true },
+ });
+});
+
+export type DataAppDevProviderProps = MetabaseProviderProps & {
+ appSlug: string;
+};
+
+/**
+ * Provider for the data-app local dev preview (`npm run dev`). Wraps
+ * `MetabaseProvider` and reports the page's traffic as the data app, so query
+ * executions are attributed to the app (as "data-app-preview") instead of the
+ * React SDK.
+ *
+ * Intended only for the local Vite dev server.
+ */
+export const DataAppDevProvider = ({
+ appSlug,
+ children,
+ ...props
+}: DataAppDevProviderProps) => {
+ registerDataAppDevContext(appSlug);
+
+ return <MetabaseProvider {...props}>{children}</MetabaseProvider>;
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DataAppDevProvider/DataAppDevProvider.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DataAppDevProvider/DataAppDevProvider.unit.spec.tsx
new file mode 100644
index 00000000000..9d6faec4293
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DataAppDevProvider/DataAppDevProvider.unit.spec.tsx
@@ -0,0 +1,32 @@
+import { render, screen } from "@testing-library/react";
+
+import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";
+
+import { DataAppDevProvider } from "./DataAppDevProvider";
+
+jest.mock(
+ "embedding-sdk-package/components/public/MetabaseProvider/MetabaseProvider",
+ () => ({
+ MetabaseProvider: ({ children }: { children: React.ReactNode }) => (
+ <>{children}</>
+ ),
+ }),
+);
+
+describe("DataAppDevProvider", () => {
+ it("registers the data-app dev context for the bundle realm and renders children", () => {
+ render(
+ <DataAppDevProvider
+ appSlug="sales"
+ authConfig={{ metabaseInstanceUrl: "http://localhost:3000" }}
+ >
+ <div>app content</div>
+ </DataAppDevProvider>,
+ );
+
+ expect(screen.getByText("app content")).toBeInTheDocument();
+ expect(
+ ensureMetabaseProviderPropsStore().getState().internalProps.dataApp,
+ ).toEqual({ name: "sales", isDev: true });
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.module.css b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.module.css
new file mode 100644
index 00000000000..6c6dc5ff5a1
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.module.css
@@ -0,0 +1,103 @@
+/* The dev toolbar renders in the host page, potentially before the SDK bundle
+ and its theme variables load, so every color falls back to a literal. */
+
+.DevToolbar {
+ position: fixed;
+ right: 16px;
+ bottom: 16px;
+ /* Stay above any host-app content. */
+ z-index: 2147483647;
+ font-family:
+ system-ui,
+ -apple-system,
+ "Segoe UI",
+ sans-serif;
+ font-size: 13px;
+}
+
+.Toggle {
+ display: block;
+ margin-left: auto;
+ padding: 8px 14px;
+ border: none;
+ border-radius: 8px;
+ cursor: pointer;
+ color: #fff;
+ background: var(--mb-color-brand, #509ee3);
+ box-shadow: 0 2px 8px var(--mb-color-shadow, rgba(0, 0, 0, 0.13));
+ font-weight: 700;
+}
+
+.ToggleHasErrors {
+ background: var(--mb-color-error, #e35050);
+}
+
+.Panel {
+ width: 380px;
+ max-height: 60vh;
+ margin-bottom: 8px;
+ display: flex;
+ flex-direction: column;
+ background: var(--mb-color-background-primary, #fff);
+ color: var(--mb-color-text-primary, #4c5773);
+ border: 1px solid var(--mb-color-border, #eeecec);
+ border-radius: 8px;
+ overflow: hidden;
+ box-shadow: 0 8px 24px var(--mb-color-shadow, rgba(0, 0, 0, 0.13));
+}
+
+.Header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 10px 12px;
+ background: var(--mb-color-background-secondary, #f9fbfc);
+ border-bottom: 1px solid var(--mb-color-border, #eeecec);
+}
+
+.Title {
+ font-weight: 700;
+}
+
+.Spacer {
+ flex: 1;
+}
+
+.Action {
+ border: none;
+ background: none;
+ color: var(--mb-color-brand, #509ee3);
+ cursor: pointer;
+ padding: 0;
+ font-size: 13px;
+ font-weight: 600;
+}
+
+.Body {
+ overflow-y: auto;
+ padding: 4px;
+}
+
+.Empty {
+ padding: 12px;
+ color: var(--mb-color-text-secondary, #696e7b);
+}
+
+.Entry {
+ padding: 8px 10px;
+ border-bottom: 1px solid var(--mb-color-border, #eeecec);
+}
+
+.EntryTime {
+ color: var(--mb-color-text-tertiary, #949aab);
+ font-size: 11px;
+ margin-bottom: 2px;
+}
+
+.EntryMessage {
+ white-space: pre-wrap;
+ word-break: break-word;
+ font-family: Monaco, ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 12px;
+ color: var(--mb-color-text-primary, #4c5773);
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.tsx
new file mode 100644
index 00000000000..87898249519
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.tsx
@@ -0,0 +1,72 @@
+/* eslint-disable i18next/no-literal-string */
+import cx from "classnames";
+import { useState, useSyncExternalStore } from "react";
+
+import S from "./DevToolbar.module.css";
+import {
+ clearDevDiagnostics,
+ getDevDiagnostics,
+ subscribeDevDiagnostics,
+} from "./diagnostics";
+
+export function DevToolbar() {
+ const entries = useSyncExternalStore(
+ subscribeDevDiagnostics,
+ getDevDiagnostics,
+ );
+ const [open, setOpen] = useState(false);
+ const count = entries.length;
+
+ return (
+ <div className={S.DevToolbar}>
+ {open && (
+ <div className={S.Panel}>
+ <div className={S.Header}>
+ <span className={S.Title}>Data app diagnostics</span>
+ <span className={S.Spacer} />
+ <button
+ type="button"
+ className={S.Action}
+ onClick={clearDevDiagnostics}
+ >
+ Clear
+ </button>
+ <button
+ type="button"
+ className={S.Action}
+ onClick={() => setOpen(false)}
+ >
+ Close
+ </button>
+ </div>
+ <div className={S.Body}>
+ {count === 0 ? (
+ <div className={S.Empty}>No errors captured.</div>
+ ) : (
+ entries
+ .slice()
+ .reverse()
+ .map((entry) => (
+ <div key={entry.id} className={S.Entry}>
+ <div className={S.EntryTime}>
+ {new Date(entry.time).toLocaleTimeString()}
+ </div>
+ <div className={S.EntryMessage}>{entry.message}</div>
+ </div>
+ ))
+ )}
+ </div>
+ </div>
+ )}
+
+ <button
+ type="button"
+ className={cx(S.Toggle, { [S.ToggleHasErrors]: count > 0 })}
+ onClick={() => setOpen((value) => !value)}
+ title="Data app diagnostics"
+ >
+ ⚠ Diagnostics{count > 0 ? ` (${count})` : ""}
+ </button>
+ </div>
+ );
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.unit.spec.tsx
new file mode 100644
index 00000000000..86a335a5675
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/DevToolbar.unit.spec.tsx
@@ -0,0 +1,86 @@
+import userEvent from "@testing-library/user-event";
+
+import { act, render, screen } from "__support__/ui";
+
+import { DevToolbar } from "./DevToolbar";
+import { clearDevDiagnostics, installDevDiagnostics } from "./diagnostics";
+
+const recordError = (message: string) => {
+ act(() => {
+ console.error(message);
+ });
+};
+
+let originalConsoleError: typeof console.error;
+
+beforeAll(() => {
+ originalConsoleError = console.error;
+ console.error = () => {};
+ installDevDiagnostics();
+});
+
+afterAll(() => {
+ console.error = originalConsoleError;
+});
+
+beforeEach(() => {
+ clearDevDiagnostics();
+});
+
+const getToggle = () => screen.getByRole("button", { name: /Diagnostics/ });
+
+describe("DevToolbar", () => {
+ it("renders a collapsed diagnostics toggle with no count when there are no errors", () => {
+ render(<DevToolbar />);
+
+ expect(getToggle()).toHaveTextContent(/^⚠ Diagnostics$/);
+ expect(screen.queryByText("Data app diagnostics")).not.toBeInTheDocument();
+ });
+
+ it("opens the panel showing the empty state, then closes via the toggle", async () => {
+ render(<DevToolbar />);
+
+ await userEvent.click(getToggle());
+ expect(screen.getByText("Data app diagnostics")).toBeInTheDocument();
+ expect(screen.getByText("No errors captured.")).toBeInTheDocument();
+
+ await userEvent.click(getToggle());
+ expect(screen.queryByText("Data app diagnostics")).not.toBeInTheDocument();
+ });
+
+ it("shows the captured count and lists entries newest first", async () => {
+ render(<DevToolbar />);
+
+ recordError("first error");
+ recordError("second error");
+
+ expect(getToggle()).toHaveTextContent("⚠ Diagnostics (2)");
+
+ await userEvent.click(getToggle());
+
+ const messages = screen.getAllByText(/error$/);
+ expect(messages[0]).toHaveTextContent("second error");
+ expect(messages[1]).toHaveTextContent("first error");
+ });
+
+ it("clears entries when Clear is clicked, leaving the panel open", async () => {
+ render(<DevToolbar />);
+ recordError("boom");
+
+ await userEvent.click(getToggle());
+ await userEvent.click(screen.getByRole("button", { name: "Clear" }));
+
+ expect(screen.getByText("No errors captured.")).toBeInTheDocument();
+ expect(getToggle()).toHaveTextContent(/^⚠ Diagnostics$/);
+ });
+
+ it("closes the panel when Close is clicked", async () => {
+ render(<DevToolbar />);
+
+ await userEvent.click(getToggle());
+ expect(screen.getByText("Data app diagnostics")).toBeInTheDocument();
+
+ await userEvent.click(screen.getByRole("button", { name: "Close" }));
+ expect(screen.queryByText("Data app diagnostics")).not.toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/diagnostics.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/diagnostics.ts
new file mode 100644
index 00000000000..e5f0fde1f3d
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/diagnostics.ts
@@ -0,0 +1,114 @@
+// Dev diagnostics store for the data-app dev toolbar. Captures errors —
+// including the sandbox's `[data-app …] blocked API call: …` logs, which surface
+// through `console.error` — so the toolbar can show what went wrong (the sandbox
+// otherwise reports blocked APIs only as an opaque `#<Object>`).
+//
+// Capture is opt-in: it only patches `console.error` / listens for uncaught
+// errors once `installDevDiagnostics()` is called. Nothing here runs on import,
+// so a host that imports `createDataAppSandbox` from the same entry doesn't pull
+// any of this in unless it's actually used.
+
+export type DevDiagnosticLevel = "error";
+
+export interface DevDiagnosticEntry {
+ id: number;
+ time: number;
+ level: DevDiagnosticLevel;
+ message: string;
+}
+
+const MAX_ENTRIES = 200;
+
+let entries: DevDiagnosticEntry[] = [];
+let nextId = 1;
+let installed = false;
+const listeners = new Set<() => void>();
+
+const emit = () => {
+ for (const listener of listeners) {
+ listener();
+ }
+};
+
+const formatArg = (arg: unknown): string => {
+ if (typeof arg === "string") {
+ return arg;
+ }
+ if (arg instanceof Error) {
+ return arg.stack ?? `${arg.name}: ${arg.message}`;
+ }
+ try {
+ return JSON.stringify(arg);
+ } catch {
+ return String(arg);
+ }
+};
+
+/**
+ * Format a CSP violation for the toolbar. The dev server mirrors Metabase's
+ * production CSP, so a violation here means the app would be blocked once
+ * sandboxed in Metabase too — e.g. a native `<form action="…">` hitting
+ * `form-action 'none'`, or a `fetch` to a host outside `allowed_hosts`. These
+ * never reach `console.error`, so the toolbar wouldn't see them otherwise.
+ */
+const formatCspViolation = (event: SecurityPolicyViolationEvent): string => {
+ const directive = event.effectiveDirective || event.violatedDirective;
+ const target = event.blockedURI || "inline content";
+
+ return `Content Security Policy (${directive}) blocked ${target}`;
+};
+
+const record = (level: DevDiagnosticLevel, message: string) => {
+ // New array reference each time so `useSyncExternalStore` re-renders.
+ entries = [...entries, { id: nextId++, time: Date.now(), level, message }];
+ if (entries.length > MAX_ENTRIES) {
+ entries = entries.slice(-MAX_ENTRIES);
+ }
+ emit();
+};
+
+export const getDevDiagnostics = (): readonly DevDiagnosticEntry[] => entries;
+
+export const subscribeDevDiagnostics = (listener: () => void): (() => void) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+};
+
+export const clearDevDiagnostics = (): void => {
+ entries = [];
+ emit();
+};
+
+/**
+ * Start capturing errors into the diagnostics store: wraps `console.error` and
+ * listens for uncaught errors / unhandled rejections. Idempotent. Call it before
+ * the sandbox runs so nothing is missed.
+ */
+export const installDevDiagnostics = (): void => {
+ if (installed || typeof window === "undefined") {
+ return;
+ }
+ installed = true;
+
+ const originalError = console.error.bind(console);
+ console.error = (...args: unknown[]) => {
+ record("error", args.map(formatArg).join(" "));
+ originalError(...args);
+ };
+
+ window.addEventListener("error", (event) => {
+ if (event.error != null || event.message) {
+ record("error", formatArg(event.error ?? event.message));
+ }
+ });
+
+ window.addEventListener("unhandledrejection", (event) => {
+ record("error", `Unhandled rejection: ${formatArg(event.reason)}`);
+ });
+
+ window.addEventListener("securitypolicyviolation", (event) => {
+ record("error", formatCspViolation(event));
+ });
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/diagnostics.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/diagnostics.unit.spec.ts
new file mode 100644
index 00000000000..2b43636276f
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/components/DevToolbar/diagnostics.unit.spec.ts
@@ -0,0 +1,147 @@
+import {
+ type DevDiagnosticEntry,
+ clearDevDiagnostics,
+ getDevDiagnostics,
+ installDevDiagnostics,
+ subscribeDevDiagnostics,
+} from "./diagnostics";
+
+const last = (entries: readonly DevDiagnosticEntry[]) =>
+ entries[entries.length - 1];
+
+let forwarded: unknown[][] = [];
+let originalConsoleError: typeof console.error;
+
+beforeAll(() => {
+ originalConsoleError = console.error;
+ console.error = (...args: unknown[]) => {
+ forwarded.push(args);
+ };
+ installDevDiagnostics();
+});
+
+afterAll(() => {
+ console.error = originalConsoleError;
+});
+
+beforeEach(() => {
+ clearDevDiagnostics();
+ forwarded = [];
+});
+
+describe("dev diagnostics store", () => {
+ it("starts empty", () => {
+ expect(getDevDiagnostics()).toEqual([]);
+ });
+
+ it("records console.error calls as error entries with id/time/message", () => {
+ console.error("boom", { code: 1 });
+
+ const entries = getDevDiagnostics();
+ expect(entries).toHaveLength(1);
+ expect(entries[0]).toMatchObject({
+ level: "error",
+ message: 'boom {"code":1}',
+ });
+ expect(typeof entries[0].id).toBe("number");
+ expect(typeof entries[0].time).toBe("number");
+ });
+
+ it("still forwards to the original console.error", () => {
+ console.error("passed through");
+
+ expect(forwarded).toContainEqual(["passed through"]);
+ });
+
+ it("formats Error arguments using their message", () => {
+ console.error(new Error("kaboom"));
+
+ expect(last(getDevDiagnostics()).message).toContain("kaboom");
+ });
+
+ it("captures uncaught window errors", () => {
+ const event = Object.assign(new Event("error"), {
+ message: "window blew up",
+ });
+ window.dispatchEvent(event);
+
+ expect(last(getDevDiagnostics()).message).toContain("window blew up");
+ });
+
+ it("captures unhandled promise rejections", () => {
+ const event = Object.assign(new Event("unhandledrejection"), {
+ reason: "nope",
+ });
+ window.dispatchEvent(event);
+
+ expect(last(getDevDiagnostics()).message).toBe("Unhandled rejection: nope");
+ });
+
+ it("captures CSP form-action violations (e.g. a blocked native form submit)", () => {
+ const event = Object.assign(new Event("securitypolicyviolation"), {
+ effectiveDirective: "form-action",
+ violatedDirective: "form-action",
+ blockedURI: "https://example.com/",
+ originalPolicy: "connect-src 'self'; form-action 'none'",
+ } satisfies Partial<SecurityPolicyViolationEvent>);
+ window.dispatchEvent(event);
+
+ expect(last(getDevDiagnostics()).message).toBe(
+ "Content Security Policy (form-action) blocked https://example.com/",
+ );
+ });
+
+ it("formats other CSP violations generically (e.g. connect-src)", () => {
+ const event = Object.assign(new Event("securitypolicyviolation"), {
+ effectiveDirective: "connect-src",
+ violatedDirective: "connect-src",
+ blockedURI: "https://evil.test/",
+ originalPolicy: "connect-src 'self'; form-action 'none'",
+ } satisfies Partial<SecurityPolicyViolationEvent>);
+ window.dispatchEvent(event);
+
+ expect(last(getDevDiagnostics()).message).toBe(
+ "Content Security Policy (connect-src) blocked https://evil.test/",
+ );
+ });
+
+ it("notifies subscribers on record and clear, and stops after unsubscribe", () => {
+ const listener = jest.fn();
+ const unsubscribe = subscribeDevDiagnostics(listener);
+
+ console.error("one");
+ expect(listener).toHaveBeenCalledTimes(1);
+
+ clearDevDiagnostics();
+ expect(listener).toHaveBeenCalledTimes(2);
+
+ unsubscribe();
+ console.error("two");
+ expect(listener).toHaveBeenCalledTimes(2);
+ });
+
+ it("returns a fresh array reference per record (so useSyncExternalStore re-renders)", () => {
+ const before = getDevDiagnostics();
+ console.error("change");
+
+ expect(getDevDiagnostics()).not.toBe(before);
+ });
+
+ it("is idempotent — installing again does not double-record", () => {
+ installDevDiagnostics();
+ console.error("once");
+
+ expect(getDevDiagnostics()).toHaveLength(1);
+ });
+
+ it("caps stored entries at 200, keeping the most recent", () => {
+ for (let i = 0; i < 205; i++) {
+ console.error(`error ${i}`);
+ }
+
+ const entries = getDevDiagnostics();
+ expect(entries).toHaveLength(200);
+ expect(entries[0].message).toBe("error 5");
+ expect(last(entries).message).toBe("error 204");
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/build-config.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/build-config.ts
new file mode 100644
index 00000000000..45d149d2754
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/build-config.ts
@@ -0,0 +1,46 @@
+import type { LibraryFormats } from "vite";
+import cssInjectedByJsPlugin from "vite-plugin-css-injected-by-js";
+import svgr from "vite-plugin-svgr";
+
+import {
+ DATA_APP_ENTRY,
+ DATA_APP_EXTERNALS,
+ DATA_APP_FACTORY_GLOBAL,
+ DATA_APP_GLOBALS,
+} from "../bundle";
+
+/**
+ * The data-app bundle contract, shared by `vite build` (production) and the dev
+ * server's in-memory membrane build so both emit the same shape: one IIFE that
+ * assigns the app factory to `__dataAppFactory__`, with React + the SDK left
+ * external and mapped to the globals the sandbox endows. `fileName` is the only
+ * difference — the shipped `index.js` vs the dev `data-app-bundle.js`.
+ *
+ * `assetsInlineLimit: () => true` forces every imported asset (images, fonts, …)
+ * to be base64-inlined: the backend serves one bundle file, so the build must
+ * emit a single self-contained `.js` with no sidecar assets.
+ */
+export function dataAppLibBuild(fileName: string) {
+ return {
+ assetsInlineLimit: () => true,
+ lib: {
+ entry: DATA_APP_ENTRY,
+ formats: ["iife"] satisfies LibraryFormats[],
+ name: DATA_APP_FACTORY_GLOBAL,
+ fileName: () => fileName,
+ },
+ rollupOptions: {
+ external: DATA_APP_EXTERNALS,
+ output: { globals: DATA_APP_GLOBALS },
+ },
+ };
+}
+
+/**
+ * Plugins every data-app build needs: inline imported CSS into the JS (the IIFE
+ * has no HTML to link a stylesheet), and let SVGs be imported as React
+ * components via `vite-plugin-svgr`.
+ */
+export function dataAppBuildPlugins() {
+ return [cssInjectedByJsPlugin(), svgr()];
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/define.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/define.ts
new file mode 100644
index 00000000000..a05a0411753
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/define.ts
@@ -0,0 +1,8 @@
+// Libraries such as react-datepicker require a process.NODE_ENV define.
+export function getDataAppDefine(mode: string): Record<string, string> {
+ return {
+ "process.env.NODE_ENV": JSON.stringify(
+ mode === "production" ? "production" : "development",
+ ),
+ };
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/define.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/define.unit.spec.ts
new file mode 100644
index 00000000000..aae40be3965
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/define.unit.spec.ts
@@ -0,0 +1,15 @@
+import { getDataAppDefine } from "./define";
+
+describe("getDataAppDefine", () => {
+ it("defines process.env.NODE_ENV for production builds", () => {
+ expect(getDataAppDefine("production")).toEqual({
+ "process.env.NODE_ENV": '"production"',
+ });
+ });
+
+ it("defines process.env.NODE_ENV for development builds", () => {
+ expect(getDataAppDefine("development")).toEqual({
+ "process.env.NODE_ENV": '"development"',
+ });
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/dev-connect-src.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/dev-connect-src.ts
new file mode 100644
index 00000000000..bfbb41ca742
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/dev-connect-src.ts
@@ -0,0 +1,44 @@
+const toOrigin = (url: string | undefined): string | undefined => {
+ try {
+ return url ? new URL(url).origin : undefined;
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * Dev-server CSP mirroring what Metabase emits for a data app in production:
+ *
+ * - `connect-src`: the app may reach its `allowed_hosts` (plus the Metabase
+ * instance, for the SDK's own calls) and the Vite dev server / HMR websocket
+ * — nothing else. So a `fetch`/XHR a production data app couldn't make is
+ * blocked in `npm run dev` too, instead of silently working locally.
+ * - `form-action`: restricts native `<form action="…">` submits to the app's
+ * `allowed_hosts` (mirroring `connect-src`); with none declared it is
+ * `'none'`, blocking every native submit. Client-side `onSubmit` handlers
+ * still work — they preventDefault, so no submission is ever checked.
+ * - `frame-src`: the app may embed / navigate to `'self'` and its
+ * `allowed_hosts` (mirroring production, where declared hosts are added to
+ * `frame-src`), so an `<iframe>`/navigation a production app couldn't make
+ * is blocked in `npm run dev` too.
+ */
+export const buildDevCsp = (
+ allowedHosts: string[],
+ metabaseUrl: string | undefined,
+): string => {
+ const instanceOrigin = toOrigin(metabaseUrl);
+ const sources = [
+ "'self'",
+ "ws://localhost:*",
+ "wss://localhost:*",
+ "ws://127.0.0.1:*",
+ "wss://127.0.0.1:*",
+ ...(instanceOrigin ? [instanceOrigin] : []),
+ ...allowedHosts,
+ ];
+ const formAction =
+ allowedHosts.length > 0 ? allowedHosts.join(" ") : "'none'";
+ const frameSrc = ["'self'", ...allowedHosts].join(" ");
+
+ return `connect-src ${sources.join(" ")}; form-action ${formAction}; frame-src ${frameSrc}`;
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/dev-connect-src.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/dev-connect-src.unit.spec.ts
new file mode 100644
index 00000000000..9534dee3e33
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/dev-connect-src.unit.spec.ts
@@ -0,0 +1,52 @@
+import { buildDevCsp } from "./dev-connect-src";
+
+/** Extract a single directive's value from a CSP header string. */
+function directive(csp: string, name: string): string | undefined {
+ return csp
+ .split(";")
+ .map((part) => part.trim())
+ .find((part) => part === name || part.startsWith(`${name} `))
+ ?.slice(name.length)
+ .trim();
+}
+
+describe("buildDevCsp", () => {
+ it("blocks native submits and limits framing to 'self' when no allowed_hosts", () => {
+ const csp = buildDevCsp([], undefined);
+
+ expect(directive(csp, "connect-src")).toBe(
+ "'self' ws://localhost:* wss://localhost:* ws://127.0.0.1:* wss://127.0.0.1:*",
+ );
+ expect(directive(csp, "form-action")).toBe("'none'");
+ expect(directive(csp, "frame-src")).toBe("'self'");
+ });
+
+ it("adds allowed_hosts to connect-src, form-action and frame-src", () => {
+ const hosts = ["https://api.example.com", "https://*.trusted.test"];
+ const csp = buildDevCsp(hosts, undefined);
+
+ for (const host of hosts) {
+ expect(directive(csp, "connect-src")).toContain(host);
+ }
+ expect(directive(csp, "form-action")).toBe(hosts.join(" "));
+ expect(directive(csp, "frame-src")).toBe(`'self' ${hosts.join(" ")}`);
+ });
+
+ it("adds the Metabase instance origin to connect-src only, normalized to an origin", () => {
+ const csp = buildDevCsp([], "http://localhost:3000/app?token=secret#x");
+
+ expect(directive(csp, "connect-src")).toContain("http://localhost:3000");
+ // Only the origin — never the path/query/fragment.
+ expect(csp).not.toContain("/app");
+ expect(csp).not.toContain("secret");
+ // The instance origin is for fetch, not for submitting/framing.
+ expect(directive(csp, "form-action")).toBe("'none'");
+ expect(directive(csp, "frame-src")).toBe("'self'");
+ });
+
+ it("ignores an unparseable Metabase URL", () => {
+ const csp = buildDevCsp([], "not a url");
+
+ expect(directive(csp, "connect-src")).not.toContain("not a url");
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/env-prefix.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/env-prefix.ts
new file mode 100644
index 00000000000..cd32af4b663
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/env-prefix.ts
@@ -0,0 +1,16 @@
+import type { ConfigEnv } from "vite";
+
+/**
+ * The env-var prefix Vite exposes to `import.meta.env` for a data app.
+ *
+ * The app's `DATA_APP_*` vars (including the dev `DATA_APP_MB_API_KEY` kept in
+ * `.env.local`) are exposed to the bundle in the dev preview ONLY. A production
+ * `vite build` gets `undefined` (Vite's default `VITE_` prefix), so those dev
+ * secrets can never be statically inlined into the shipped `dist/index.js` that
+ * Metabase serves to users — even if app code reads `import.meta.env.DATA_APP_*`.
+ */
+export function dataAppEnvPrefix(
+ command: ConfigEnv["command"],
+): string[] | undefined {
+ return command === "serve" ? ["DATA_APP_"] : undefined;
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/env-prefix.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/env-prefix.unit.spec.ts
new file mode 100644
index 00000000000..d58fad16c40
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/env-prefix.unit.spec.ts
@@ -0,0 +1,11 @@
+import { dataAppEnvPrefix } from "./env-prefix";
+
+describe("dataAppEnvPrefix", () => {
+ it("exposes the app's DATA_APP_ env vars in the dev preview (serve)", () => {
+ expect(dataAppEnvPrefix("serve")).toEqual(["DATA_APP_"]);
+ });
+
+ it("exposes no DATA_APP_ env vars in a production build", () => {
+ expect(dataAppEnvPrefix("build")).toBeUndefined();
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/find-env-root.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/find-env-root.ts
new file mode 100644
index 00000000000..f76f11facc6
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/find-env-root.ts
@@ -0,0 +1,25 @@
+import fs from "node:fs";
+import path from "node:path";
+
+// How many parent dirs above the app to search for `.env.local`. Covers the
+// deepest supported layout where the app is synced into a parent repo as
+// `<repo>/data_apps/<app>` (2 levels deep). `.git` is a hard stop — `.env.local`
+// lives at the repo root, so we never search above it.
+const MAX_ENV_SEARCH_DEPTH = 2;
+
+/** Walk up from `start` to the dir holding `.env.local` (or the git root). */
+export function findEnvRoot(start: string): string {
+ let dir = start;
+
+ for (let i = 0; i <= MAX_ENV_SEARCH_DEPTH; i++) {
+ if (
+ fs.existsSync(path.join(dir, ".env.local")) ||
+ fs.existsSync(path.join(dir, ".git"))
+ ) {
+ return dir;
+ }
+ dir = path.dirname(dir);
+ }
+
+ return start;
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/find-env-root.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/find-env-root.unit.spec.ts
new file mode 100644
index 00000000000..88e551fd2f2
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/find-env-root.unit.spec.ts
@@ -0,0 +1,61 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import { findEnvRoot } from "./find-env-root";
+
+jest.mock("node:fs");
+
+const mockedFs = jest.mocked(fs);
+
+type SetupOpts = {
+ existing?: string[];
+ start: string;
+};
+
+const setup = ({ existing = [], start }: SetupOpts) => {
+ const set = new Set(existing);
+
+ mockedFs.existsSync.mockImplementation((p) => set.has(p.toString()));
+
+ return { root: findEnvRoot(start) };
+};
+
+describe("findEnvRoot", () => {
+ afterEach(() => jest.resetAllMocks());
+
+ it("returns the start dir when it holds .env.local", () => {
+ const start = "/repo/data_apps/sales";
+ expect(
+ setup({ existing: [path.join(start, ".env.local")], start }).root,
+ ).toBe(start);
+ });
+
+ it("walks up to the dir holding .env.local", () => {
+ const { root } = setup({
+ existing: [path.join("/repo", ".env.local")],
+ start: "/repo/data_apps/sales",
+ });
+ expect(root).toBe("/repo");
+ });
+
+ it("stops at the git root even without an .env.local", () => {
+ const { root } = setup({
+ existing: [path.join("/repo", ".git")],
+ start: "/repo/data_apps/sales",
+ });
+ expect(root).toBe("/repo");
+ });
+
+ it("returns the start dir when nothing is found within the search depth", () => {
+ expect(setup({ start: "/a/b/c" }).root).toBe("/a/b/c");
+ });
+
+ it("does not search above the max depth (2 parents)", () => {
+ // .env.local sits 3 levels up — beyond MAX_ENV_SEARCH_DEPTH.
+ const { root } = setup({
+ existing: [path.join("/root", ".env.local")],
+ start: "/root/one/two/three",
+ });
+ expect(root).toBe("/root/one/two/three");
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.ts
new file mode 100644
index 00000000000..484da2510ad
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.ts
@@ -0,0 +1,77 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import { load as parseYaml } from "js-yaml";
+
+/**
+ * The app's parsed `data_app.yaml` manifest, validated and normalized:
+ * `allowed_hosts` is guaranteed to be a list of strings.
+ */
+export type DataAppManifest = {
+ allowed_hosts?: string[];
+};
+
+const isString = (value: unknown): value is string => typeof value === "string";
+
+const parseAllowedHosts = (
+ value: unknown,
+ manifestPath: string,
+): string[] | undefined => {
+ if (value == null) {
+ return undefined;
+ }
+
+ if (!Array.isArray(value)) {
+ throw new Error(`${manifestPath}: "allowed_hosts" must be a list.`);
+ }
+
+ if (!value.every(isString)) {
+ const nonString = value.find((host) => !isString(host));
+
+ throw new Error(
+ `${manifestPath}: every "allowed_hosts" entry must be a string, got ${JSON.stringify(
+ nonString,
+ )}.`,
+ );
+ }
+
+ return value;
+};
+
+/**
+ * Read, parse, and normalize the app's `data_app.yaml` manifest.
+ * Returns null when the app has no manifest.
+ */
+export const readManifest = (
+ appRoot: string,
+): { manifestPath: string; manifest: DataAppManifest } | null => {
+ const manifestPath = [path.join(appRoot, "data_app.yaml")].find((candidate) =>
+ fs.existsSync(candidate),
+ );
+
+ if (!manifestPath) {
+ return null;
+ }
+
+ let parsed: unknown;
+
+ try {
+ parsed = parseYaml(fs.readFileSync(manifestPath, "utf8"));
+ } catch (error) {
+ throw new Error(
+ `Could not parse ${manifestPath}: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+ }
+
+ const raw: { allowed_hosts?: unknown } =
+ typeof parsed === "object" && parsed !== null ? parsed : {};
+
+ return {
+ manifestPath,
+ manifest: {
+ allowed_hosts: parseAllowedHosts(raw.allowed_hosts, manifestPath),
+ },
+ };
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.unit.spec.ts
new file mode 100644
index 00000000000..a71b090e99d
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/config/read-manifest.unit.spec.ts
@@ -0,0 +1,80 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import { readManifest } from "./read-manifest";
+
+jest.mock("node:fs");
+
+const mockedFs = jest.mocked(fs);
+
+const APP_ROOT = "/app";
+const YAML_PATH = path.join(APP_ROOT, "data_app.yaml");
+
+const setup = (files: Record<string, string>) => {
+ mockedFs.existsSync.mockImplementation((p) => p.toString() in files);
+ mockedFs.readFileSync.mockImplementation((p) => {
+ const content = files[p.toString()];
+
+ if (content == null) {
+ throw new Error(`unexpected read: ${p}`);
+ }
+
+ return content;
+ });
+};
+
+afterEach(() => jest.resetAllMocks());
+
+describe("readManifest", () => {
+ it("returns null when no manifest exists", () => {
+ setup({});
+
+ expect(readManifest(APP_ROOT)).toBeNull();
+ });
+
+ it("returns an empty manifest for non-object yaml", () => {
+ setup({ [YAML_PATH]: "just a string\n" });
+
+ expect(readManifest(APP_ROOT)?.manifest).toEqual({});
+ });
+
+ it("throws on unparseable yaml", () => {
+ setup({ [YAML_PATH]: "allowed_hosts: [unclosed\n" });
+
+ expect(() => readManifest(APP_ROOT)).toThrow(/Could not parse/);
+ });
+
+ describe("allowed_hosts", () => {
+ it("reads allowed_hosts as a list of strings", () => {
+ setup({
+ [YAML_PATH]:
+ "allowed_hosts:\n - https://api.example.com\n - https://*.acme.com\n",
+ });
+
+ expect(readManifest(APP_ROOT)?.manifest.allowed_hosts).toEqual([
+ "https://api.example.com",
+ "https://*.acme.com",
+ ]);
+ });
+
+ it("is undefined when the manifest has no allowed_hosts key", () => {
+ setup({ [YAML_PATH]: "name: My App\n" });
+
+ expect(readManifest(APP_ROOT)?.manifest.allowed_hosts).toBeUndefined();
+ });
+
+ it("throws when allowed_hosts is not a list", () => {
+ setup({ [YAML_PATH]: "allowed_hosts: nope\n" });
+
+ expect(() => readManifest(APP_ROOT)).toThrow(
+ /"allowed_hosts" must be a list/,
+ );
+ });
+
+ it("throws on a non-string entry", () => {
+ setup({ [YAML_PATH]: "allowed_hosts:\n - https://ok.com\n - 42\n" });
+
+ expect(() => readManifest(APP_ROOT)).toThrow(/must be a string/);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.ts
new file mode 100644
index 00000000000..63139d8486d
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.ts
@@ -0,0 +1,244 @@
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { type Plugin, type Rollup, build } from "vite";
+
+// Build-time string constants shared with the rspack config; bundled as values,
+// so this references no app runtime code (cf. `use-load-sdk-bundle.ts`). A
+// namespace import stays single-line so the disable covers the reported line.
+// eslint-disable-next-line metabase/no-external-references-for-sdk-package-code
+import * as dataAppVirtualModules from "build-configs/embedding-sdk/constants/data-app-virtual-modules";
+
+import { DATA_APP_BUNDLE_URL, DATA_APP_REBUILT_EVENT } from "../bundle";
+import { dataAppBuildPlugins, dataAppLibBuild } from "../config/build-config";
+import { getDataAppDefine } from "../config/define";
+
+// Virtual modules the dev server provides. The dev server serves a synthetic
+// `index.html` (below) that imports the dev entry; the dev entry imports the
+// config (the app's allowed hosts + the bundle URL/event). The dev entry is the
+// prebuilt `data-app-dev-entry.js` (bundled by the SDK's browser build, shipped
+// next to this bundle in `dist`); it keeps React + `@metabase/embedding-sdk-react`
+// external so the consumer's Vite resolves them to its single instance.
+const { DATA_APP_DEV_CONFIG_VIRTUAL_ID, DATA_APP_DEV_ENTRY_VIRTUAL_ID } =
+ dataAppVirtualModules;
+
+const DEV_ENTRY_SOURCE_PATH = fileURLToPath(
+ new URL("data-app-dev-entry.js", import.meta.url),
+);
+
+// The dev server's HTML shell, served synthetically so the app scaffold needs no
+// `index.html`. It just boots the dev entry (resolved + served as a virtual
+// module below), which injects the baseline reset CSS itself (the same file the
+// production iframe loads).
+const INDEX_HTML = `<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Data App Dev Preview</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module">
+ import ${JSON.stringify(DATA_APP_DEV_ENTRY_VIRTUAL_ID)};
+ </script>
+ </body>
+</html>
+`;
+
+// Rollup/Vite's virtual-module marker: a leading NUL byte tells Rollup core and
+// other plugins that an id is synthetic, so they don't try to resolve/load it
+// from disk. It's a convention (not a public export), so we spell it out; Vite
+// encodes it as `__x00__` in dev URLs.
+const RESOLVED_PREFIX = "\0";
+
+/**
+ * Makes `npm run dev` run the app through the real Near-Membrane sandbox instead
+ * of mounting it un-sandboxed, so dev behaves like production — including for
+ * third-party libraries the app bundles.
+ *
+ * The membrane evaluates a code string, not Vite's module graph, so the app is
+ * built in-memory as the production IIFE on server start and on every `src/`
+ * change, served at `DATA_APP_BUNDLE_URL`. Instead of a full page reload it emits
+ * `DATA_APP_REBUILT_EVENT`, and the dev entry re-evaluates the new bundle in the
+ * live sandbox and re-renders in place — preserving the loaded SDK + auth (a
+ * soft reload; component state still resets, since the app is an opaque bundle).
+ */
+export function dataAppSandboxDevPlugin(
+ appSlug: string,
+ allowedHosts: string[],
+): Plugin {
+ let bundleCode = "";
+
+ const rebuild = async (root: string, mode: string) => {
+ const result = await build({
+ root,
+ mode,
+ configFile: false,
+ define: getDataAppDefine(mode),
+ logLevel: "warn",
+ plugins: dataAppBuildPlugins(),
+ build: {
+ write: false,
+ minify: mode === "production",
+ ...dataAppLibBuild("data-app-bundle.js"),
+ },
+ });
+
+ const outputs = Array.isArray(result) ? result : [result];
+
+ bundleCode =
+ outputs
+ .flatMap((output) => ("output" in output ? output.output : []))
+ .find((chunk): chunk is Rollup.OutputChunk => chunk.type === "chunk")
+ ?.code ?? "";
+ };
+
+ return {
+ name: "metabase-data-app-dev",
+ apply: "serve",
+
+ resolveId(id) {
+ if (
+ id === DATA_APP_DEV_ENTRY_VIRTUAL_ID ||
+ id === DATA_APP_DEV_CONFIG_VIRTUAL_ID
+ ) {
+ return RESOLVED_PREFIX + id;
+ }
+ },
+
+ load(id) {
+ if (id === RESOLVED_PREFIX + DATA_APP_DEV_ENTRY_VIRTUAL_ID) {
+ return fs.readFileSync(DEV_ENTRY_SOURCE_PATH, "utf8");
+ }
+
+ if (id === RESOLVED_PREFIX + DATA_APP_DEV_CONFIG_VIRTUAL_ID) {
+ return [
+ `export const allowedHosts = ${JSON.stringify(allowedHosts)};`,
+ `export const appSlug = ${JSON.stringify(appSlug)};`,
+ `export const bundleUrl = ${JSON.stringify(DATA_APP_BUNDLE_URL)};`,
+ `export const rebuiltEvent = ${JSON.stringify(DATA_APP_REBUILT_EVENT)};`,
+ ].join("\n");
+ }
+ },
+
+ async configureServer(server) {
+ const { root, mode } = server.config;
+
+ const safeRebuild = async (): Promise<boolean> => {
+ try {
+ await rebuild(root, mode);
+
+ return true;
+ } catch (error) {
+ server.config.logger.error(
+ `[data-app-dev] failed to build the app bundle: ${
+ error instanceof Error ? error.message : String(error)
+ }`,
+ );
+
+ return false;
+ }
+ };
+
+ // Coalesce rebuilds: at most one Vite build runs at a time, and changes
+ // that arrive mid-build collapse into a single follow-up — so a burst of
+ // saves can't back up a queue of full rebuilds (or fire a soft reload each).
+ let building = false;
+ let pending = false;
+ const rebuildAndNotify = async () => {
+ if (building) {
+ pending = true;
+ return;
+ }
+
+ building = true;
+ try {
+ let built = false;
+ do {
+ pending = false;
+ built = await safeRebuild();
+ } while (pending);
+
+ if (built) {
+ server.ws.send({ type: "custom", event: DATA_APP_REBUILT_EVENT });
+ }
+ } finally {
+ building = false;
+ }
+ };
+
+ // Initial build; no client is connected yet, so nothing to notify.
+ await safeRebuild();
+
+ server.middlewares.use((req, res, next) => {
+ if (req.url?.split("?")[0] !== DATA_APP_BUNDLE_URL) {
+ next();
+
+ return;
+ }
+
+ if (!bundleCode) {
+ res.statusCode = 503;
+ res.setHeader("Content-Type", "text/plain");
+ res.end("data-app bundle is not built — see the dev server logs.");
+
+ return;
+ }
+
+ res.setHeader("Content-Type", "text/javascript");
+ res.end(bundleCode);
+ });
+
+ const srcDir = `${path.sep}src${path.sep}`;
+
+ server.watcher.on("change", async (file) => {
+ if (file.includes(srcDir)) {
+ await rebuildAndNotify();
+ }
+ });
+
+ // Serve the synthetic index.html as a POST middleware (after Vite's
+ // transform/asset middlewares) so it only catches navigation requests —
+ // the initial load and any deep link / SPA route, not module/asset fetches.
+ // `transformIndexHtml` injects the HMR client + resolves the entry import.
+ return () => {
+ server.middlewares.use(async (req, res, next) => {
+ if (
+ req.method !== "GET" ||
+ !req.headers.accept?.includes("text/html")
+ ) {
+ next();
+
+ return;
+ }
+
+ try {
+ const html = await server.transformIndexHtml(
+ req.url ?? "/",
+ INDEX_HTML,
+ );
+
+ res.statusCode = 200;
+
+ // Apply the configured `server.headers` (our CSP) to this document.
+ const configuredHeaders = server.config.server.headers;
+ if (configuredHeaders) {
+ for (const [name, value] of Object.entries(configuredHeaders)) {
+ if (value != null) {
+ res.setHeader(name, value);
+ }
+ }
+ }
+
+ res.setHeader("Content-Type", "text/html");
+ res.end(html);
+ } catch (error) {
+ next(error);
+ }
+ });
+ };
+ },
+ };
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.unit.spec.ts
new file mode 100644
index 00000000000..7119b0f6eb4
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/dev-plugin/plugin.unit.spec.ts
@@ -0,0 +1,290 @@
+import fs from "node:fs";
+import path from "node:path";
+
+import { build } from "vite";
+
+import {
+ DATA_APP_DEV_CONFIG_VIRTUAL_ID,
+ DATA_APP_DEV_ENTRY_VIRTUAL_ID,
+} from "build-configs/embedding-sdk/constants/data-app-virtual-modules";
+
+import { DATA_APP_BUNDLE_URL, DATA_APP_REBUILT_EVENT } from "../bundle";
+
+import { dataAppSandboxDevPlugin } from "./plugin";
+
+jest.mock("vite", () => ({ build: jest.fn() }));
+// Mock at the app's own config boundary rather than the individual Vite plugins
+// it pulls in (`vite-plugin-css-injected-by-js`, `vite-plugin-svgr`): `build`
+// is stubbed out anyway, so the plugin never uses these values — the test only
+// needs `build-config` not to import those ESM-only packages at load time.
+jest.mock("../config/build-config", () => ({
+ dataAppBuildPlugins: () => [],
+ dataAppLibBuild: () => ({}),
+}));
+jest.mock("node:fs");
+
+const mockedBuild = jest.mocked(build);
+const mockedFs = jest.mocked(fs);
+
+const RESOLVED = (id: string) => `\0${id}`;
+
+type FakeServer = {
+ config: {
+ root: string;
+ mode: string;
+ logger: { error: jest.Mock };
+ server: { headers: Record<string, string | null> };
+ };
+ ws: { send: jest.Mock };
+ middlewares: { use: jest.Mock };
+ watcher: { on: jest.Mock };
+ transformIndexHtml: jest.Mock;
+};
+type TestPlugin = {
+ name: string;
+ apply: string;
+ resolveId: (id: string) => string | undefined;
+ load: (id: string) => string | undefined;
+ configureServer: (server: FakeServer) => Promise<() => void>;
+};
+
+const APP_SLUG = "test-app";
+
+function makePlugin(appSlug: string, allowedHosts: string[] = []): TestPlugin {
+ // Vite declares every hook on `Plugin` as an `ObjectHook` union (a function or
+ // a `{ handler }` object) bound to Rollup's plugin context. The tests call the
+ // hooks we return as plain functions, which no assignable type expresses.
+ return dataAppSandboxDevPlugin(
+ appSlug,
+ allowedHosts,
+ ) as unknown as TestPlugin;
+}
+
+describe("dataAppSandboxDevPlugin", () => {
+ afterEach(() => jest.clearAllMocks());
+
+ it("only applies to the dev server", () => {
+ const plugin = makePlugin(APP_SLUG);
+
+ expect(plugin.name).toBe("metabase-data-app-dev");
+ expect(plugin.apply).toBe("serve");
+ });
+
+ describe("virtual modules", () => {
+ const setup = (allowedHosts: string[] = []) => {
+ return { plugin: makePlugin(APP_SLUG, allowedHosts) };
+ };
+
+ it("resolves the dev-entry and config virtual ids to synthetic ids", () => {
+ const { plugin } = setup();
+
+ expect(plugin.resolveId(DATA_APP_DEV_ENTRY_VIRTUAL_ID)).toBe(
+ RESOLVED(DATA_APP_DEV_ENTRY_VIRTUAL_ID),
+ );
+ expect(plugin.resolveId(DATA_APP_DEV_CONFIG_VIRTUAL_ID)).toBe(
+ RESOLVED(DATA_APP_DEV_CONFIG_VIRTUAL_ID),
+ );
+ });
+
+ it("ignores unrelated ids", () => {
+ expect(setup().plugin.resolveId("react")).toBeUndefined();
+ });
+
+ it("serves the prebuilt dev entry source for the entry virtual id", () => {
+ mockedFs.readFileSync.mockReturnValue("DEV_ENTRY_SOURCE");
+ const { plugin } = setup();
+
+ expect(plugin.load(RESOLVED(DATA_APP_DEV_ENTRY_VIRTUAL_ID))).toBe(
+ "DEV_ENTRY_SOURCE",
+ );
+ expect(mockedFs.readFileSync).toHaveBeenCalledWith(
+ expect.stringContaining("data-app-dev-entry.js"),
+ "utf8",
+ );
+ });
+
+ it("generates the config module with the app's allowed hosts and bundle constants", () => {
+ const { plugin } = setup(["https://api.example.com"]);
+ const source = plugin.load(RESOLVED(DATA_APP_DEV_CONFIG_VIRTUAL_ID));
+
+ expect(source).toContain(
+ `export const allowedHosts = ${JSON.stringify(["https://api.example.com"])};`,
+ );
+ expect(source).toContain(`export const appSlug = "test-app";`);
+ expect(source).toContain(
+ `export const bundleUrl = ${JSON.stringify(DATA_APP_BUNDLE_URL)};`,
+ );
+ expect(source).toContain(
+ `export const rebuiltEvent = ${JSON.stringify(DATA_APP_REBUILT_EVENT)};`,
+ );
+ });
+
+ it("does not load unrelated ids", () => {
+ expect(setup().plugin.load("\0other")).toBeUndefined();
+ });
+ });
+
+ describe("dev server wiring", () => {
+ const DEV_CSP = "connect-src 'self'; form-action 'none'; frame-src 'self'";
+
+ function makeServer(): FakeServer {
+ return {
+ config: {
+ root: "/app",
+ mode: "development",
+ logger: { error: jest.fn() },
+ server: { headers: { "Content-Security-Policy": DEV_CSP } },
+ },
+ ws: { send: jest.fn() },
+ middlewares: { use: jest.fn() },
+ watcher: { on: jest.fn() },
+ transformIndexHtml: jest.fn(async (_url: string, html: string) => html),
+ };
+ }
+
+ async function setup(bundleCode = "BUNDLE_CODE") {
+ // Rollup's `OutputChunk` declares ~20 required fields; the plugin only
+ // reads `type` and `code`, so the stub deliberately omits the rest.
+ mockedBuild.mockResolvedValue({
+ output: [{ type: "chunk", code: bundleCode }],
+ } as unknown as Awaited<ReturnType<typeof build>>);
+
+ const server = makeServer();
+
+ // `configureServer` returns a hook Vite runs after its own middlewares;
+ // call it so the document (index.html) middleware is registered too.
+ const registerLateMiddleware =
+ await makePlugin(APP_SLUG).configureServer(server);
+ registerLateMiddleware();
+
+ return { server };
+ }
+
+ it("builds the bundle on startup and serves it at the bundle URL", async () => {
+ const { server } = await setup("BUNDLE_CODE");
+
+ expect(mockedBuild).toHaveBeenCalledTimes(1);
+
+ const bundleMiddleware = server.middlewares.use.mock.calls[0][0];
+ const res = { statusCode: 0, setHeader: jest.fn(), end: jest.fn() };
+ const next = jest.fn();
+ bundleMiddleware({ url: DATA_APP_BUNDLE_URL }, res, next);
+
+ expect(res.setHeader).toHaveBeenCalledWith(
+ "Content-Type",
+ "text/javascript",
+ );
+ expect(res.end).toHaveBeenCalledWith("BUNDLE_CODE");
+ expect(next).not.toHaveBeenCalled();
+ });
+
+ it("passes non-bundle requests through to the next middleware", async () => {
+ const { server } = await setup();
+
+ const bundleMiddleware = server.middlewares.use.mock.calls[0][0];
+ const next = jest.fn();
+ bundleMiddleware(
+ { url: "/some/asset.js" },
+ { setHeader: jest.fn(), end: jest.fn() },
+ next,
+ );
+
+ expect(next).toHaveBeenCalledTimes(1);
+ });
+
+ it("rebuilds and notifies the client when a src file changes", async () => {
+ const { server } = await setup();
+ expect(mockedBuild).toHaveBeenCalledTimes(1);
+
+ const [event, onChange] = server.watcher.on.mock.calls[0];
+ expect(event).toBe("change");
+
+ await onChange(`/app${path.sep}src${path.sep}index.tsx`);
+
+ expect(mockedBuild).toHaveBeenCalledTimes(2);
+ expect(server.ws.send).toHaveBeenCalledWith({
+ type: "custom",
+ event: DATA_APP_REBUILT_EVENT,
+ });
+ });
+
+ it("ignores changes outside src/", async () => {
+ const { server } = await setup();
+
+ const onChange = server.watcher.on.mock.calls[0][1];
+ await onChange("/app/README.md");
+
+ expect(mockedBuild).toHaveBeenCalledTimes(1);
+ expect(server.ws.send).not.toHaveBeenCalled();
+ });
+
+ describe("synthetic index.html document", () => {
+ // The document middleware is the second one registered: the bundle
+ // middleware from `configureServer` (index 0), then this one from the
+ // returned late hook (index 1).
+ const getDocumentMiddleware = (server: FakeServer) =>
+ server.middlewares.use.mock.calls[1][0];
+
+ it("serves the transformed shell with the configured CSP for navigations", async () => {
+ const { server } = await setup();
+ const res = { statusCode: 0, setHeader: jest.fn(), end: jest.fn() };
+ const next = jest.fn();
+
+ await getDocumentMiddleware(server)(
+ { method: "GET", headers: { accept: "text/html" }, url: "/" },
+ res,
+ next,
+ );
+
+ // The shell HTML goes through Vite's transform (HMR client, etc.).
+ expect(server.transformIndexHtml).toHaveBeenCalledWith(
+ "/",
+ expect.stringContaining('<div id="root">'),
+ );
+ // The dev CSP configured on the server is copied onto the document.
+ expect(res.setHeader).toHaveBeenCalledWith(
+ "Content-Security-Policy",
+ DEV_CSP,
+ );
+ expect(res.setHeader).toHaveBeenCalledWith("Content-Type", "text/html");
+ expect(res.end).toHaveBeenCalledWith(
+ expect.stringContaining("<!doctype html>"),
+ );
+ expect(next).not.toHaveBeenCalled();
+ });
+
+ it("leaves non-HTML requests for the next middleware", async () => {
+ const { server } = await setup();
+ const next = jest.fn();
+
+ await getDocumentMiddleware(server)(
+ {
+ method: "GET",
+ headers: { accept: "application/javascript" },
+ url: "/some/asset.js",
+ },
+ { setHeader: jest.fn(), end: jest.fn() },
+ next,
+ );
+
+ expect(server.transformIndexHtml).not.toHaveBeenCalled();
+ expect(next).toHaveBeenCalledTimes(1);
+ });
+
+ it("forwards transformIndexHtml errors to the next middleware", async () => {
+ const { server } = await setup();
+ const error = new Error("transform failed");
+ server.transformIndexHtml.mockRejectedValueOnce(error);
+ const next = jest.fn();
+
+ await getDocumentMiddleware(server)(
+ { method: "GET", headers: { accept: "text/html" }, url: "/" },
+ { statusCode: 0, setHeader: jest.fn(), end: jest.fn() },
+ next,
+ );
+
+ expect(next).toHaveBeenCalledWith(error);
+ });
+ });
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts
new file mode 100644
index 00000000000..65e1984867c
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.ts
@@ -0,0 +1,112 @@
+import path from "node:path";
+
+import react from "@vitejs/plugin-react";
+import {
+ type ConfigEnv,
+ type PluginOption,
+ type UserConfig,
+ loadEnv,
+} from "vite";
+
+import { dataAppBuildPlugins, dataAppLibBuild } from "./config/build-config";
+import { getDataAppDefine } from "./config/define";
+import { buildDevCsp } from "./config/dev-connect-src";
+import { dataAppEnvPrefix } from "./config/env-prefix";
+import { findEnvRoot } from "./config/find-env-root";
+import { readManifest } from "./config/read-manifest";
+import { dataAppSandboxDevPlugin } from "./dev-plugin/plugin";
+
+/**
+ * The contract plugin array used by {@link dataAppConfig}. It bundles the React
+ * plugin, inlines imported CSS, adds SVG-as-component support, runs `npm run dev`
+ * through the real Near-Membrane sandbox (so dev behaves like production), serves
+ * the dev entry, and applies the bundle contract — the IIFE entry/format + the
+ * React/SDK externals/globals — through a `config` hook that Vite merges *over*
+ * the user's config, so it can't be accidentally overridden.
+ *
+ * Internal: apps configure through {@link dataAppConfig}, not this directly.
+ */
+function dataAppVitePlugin(): PluginOption[] {
+ const appRoot = process.cwd();
+ const envDir = findEnvRoot(appRoot);
+
+ const manifestResult = readManifest(appRoot);
+
+ if (!manifestResult) {
+ throw new Error(
+ `No data_app.yaml found in ${appRoot}. Run vite from the data app's own ` +
+ `directory (data_apps/<slug>/).`,
+ );
+ }
+
+ const appSlug = path.basename(appRoot);
+ const allowedHosts = manifestResult.manifest.allowed_hosts ?? [];
+
+ return [
+ react(),
+ ...dataAppBuildPlugins(),
+ dataAppSandboxDevPlugin(appSlug, allowedHosts),
+ {
+ name: "metabase-data-app",
+ // Merged over the user's config (`mergeConfig(userConfig, this)`), so these
+ // win — the bundle Metabase loads always matches what dev runs. `loadEnv`
+ // needs the mode, which is only known here in the `config` hook.
+ config: (_config: UserConfig, env: ConfigEnv): UserConfig => ({
+ define: getDataAppDefine(env.mode),
+ envDir,
+ // Dev preview only — keeps `.env.local` secrets out of prod builds. See
+ // `dataAppEnvPrefix`.
+ envPrefix: dataAppEnvPrefix(env.command),
+ // The dev plugin serves a synthetic index.html, so there's no file on
+ // disk for Vite's default HTML/SPA middleware to find.
+ appType: "custom",
+ build: {
+ outDir: "dist",
+ emptyOutDir: true,
+ ...dataAppLibBuild("index.js"),
+ },
+ server: {
+ host: "localhost",
+ headers: {
+ "Content-Security-Policy": buildDevCsp(
+ allowedHosts,
+ loadEnv(env.mode, envDir, "").DATA_APP_MB_URL,
+ ),
+ },
+ },
+ }),
+ },
+ ];
+}
+
+/** Default dev server port; override via `dataAppConfig({ port })`. */
+const DEFAULT_DEV_PORT = 5174;
+
+export interface DataAppConfigOverrides {
+ /** Dev server port. Defaults to 5174. */
+ port?: number;
+}
+
+/**
+ * The complete Vite config for a Metabase data app — the only thing a template
+ * `vite.config.ts` needs:
+ *
+ * ```ts
+ * import { dataAppConfig } from "@metabase/embedding-sdk-react/data-app-dev/config";
+ *
+ * export default dataAppConfig();
+ * ```
+ *
+ * `overrides` exposes only a curated set of knobs (currently just `port`, which
+ * defaults to 5174). The contract plugin that enforces the bundle format +
+ * sandbox is always applied and is intentionally NOT overridable, so a data app
+ * can't drift from what Metabase loads.
+ */
+export function dataAppConfig({
+ port = DEFAULT_DEV_PORT,
+}: DataAppConfigOverrides = {}): UserConfig {
+ return {
+ plugins: [dataAppVitePlugin()],
+ server: { port },
+ };
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.unit.spec.ts
new file mode 100644
index 00000000000..59f9de99f43
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/index.unit.spec.ts
@@ -0,0 +1,53 @@
+import { readManifest } from "./config/read-manifest";
+
+import { dataAppConfig } from "./index";
+
+jest.mock("vite", () => ({ loadEnv: jest.fn(() => ({})) }));
+jest.mock("@vitejs/plugin-react", () => ({
+ __esModule: true,
+ default: () => ({ name: "mock-react" }),
+}));
+jest.mock("./config/build-config", () => ({
+ dataAppBuildPlugins: () => [],
+ dataAppLibBuild: () => ({}),
+}));
+jest.mock("./config/find-env-root", () => ({
+ findEnvRoot: (appRoot: string) => appRoot,
+}));
+jest.mock("./dev-plugin/plugin", () => ({
+ dataAppSandboxDevPlugin: () => ({ name: "mock-sandbox-dev" }),
+}));
+jest.mock("./config/read-manifest");
+
+const mockedReadManifest = jest.mocked(readManifest);
+
+afterEach(() => jest.resetAllMocks());
+
+describe("dataAppConfig", () => {
+ it("throws when the cwd has no data_app.yaml (run from the wrong directory)", () => {
+ mockedReadManifest.mockReturnValue(null);
+
+ expect(() => dataAppConfig()).toThrow(/No data_app\.yaml found/);
+ });
+
+ it("builds the config when a manifest is present", () => {
+ mockedReadManifest.mockReturnValue({
+ manifestPath: "/app/data_app.yaml",
+ manifest: { allowed_hosts: [] },
+ });
+
+ const config = dataAppConfig();
+
+ expect(config.server?.port).toBe(5174);
+ expect(config.plugins).toBeDefined();
+ });
+
+ it("uses the port override", () => {
+ mockedReadManifest.mockReturnValue({
+ manifestPath: "/app/data_app.yaml",
+ manifest: {},
+ });
+
+ expect(dataAppConfig({ port: 4000 }).server?.port).toBe(4000);
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app-dev/vite-env.d.ts b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/vite-env.d.ts
new file mode 100644
index 00000000000..2dee926c97a
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app-dev/vite-env.d.ts
@@ -0,0 +1,24 @@
+// Ambient types for `dev-entry.tsx` (bundled by rspack, but type-checked by the
+// main program). The dev app's env vars + Vite's `import.meta.env`/`.hot` and the
+// dev plugin's config virtual module are declared here so `dev-entry.tsx` checks
+// against real shapes. No other code declares `ImportMeta`, so this is the sole
+// (global) declaration; the interfaces merge with the built-in `ImportMeta.url`.
+
+interface ImportMetaEnv {
+ readonly DATA_APP_MB_URL: string;
+ readonly DATA_APP_MB_API_KEY: string;
+}
+
+interface ImportMeta {
+ readonly env: ImportMetaEnv;
+ readonly hot?: {
+ on(event: string, cb: (...args: unknown[]) => void): void;
+ };
+}
+
+declare module "virtual:metabase-data-app-dev-config" {
+ export const allowedHosts: string[];
+ export const appSlug: string;
+ export const bundleUrl: string;
+ export const rebuiltEvent: string;
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app.ts b/enterprise/frontend/src/embedding-sdk-package/data-app.ts
new file mode 100644
index 00000000000..6885a2fc1ec
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/data-app.ts
@@ -0,0 +1,42 @@
+// eslint-disable-next-line metabase/no-external-references-for-sdk-package-code
+import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
+// eslint-disable-next-line metabase/no-external-references-for-sdk-package-code
+import { defineBuildInfo } from "metabase/embedding-sdk/lib/define-build-info";
+// eslint-disable-next-line metabase/no-external-references-for-sdk-package-code
+import { defineGlobalDependencies } from "metabase/embedding-sdk/lib/define-global-dependencies";
+
+EMBEDDING_SDK_CONFIG.isEmbeddingSdk = true;
+
+defineBuildInfo("METABASE_EMBEDDING_SDK_PACKAGE_BUILD_INFO");
+defineGlobalDependencies();
+
+export { DataAppRouter } from "./components/public/DataAppRouter";
+export { DataAppLink } from "./components/public/DataAppLink";
+export { copy } from "./lib/public/copy";
+export { useDataAppLocation } from "./hooks/public/use-data-app-location";
+export {
+ aggregations,
+ breakout,
+ filter,
+ orderBy,
+ useMetabaseQuery,
+ useMetabaseQueryObject,
+} from "./hooks/public/use-metabase-query";
+export type {
+ LocalFieldReference,
+ MetabaseBreakout,
+ MetabaseOrderBy,
+ MetabaseQueryOptions,
+ MetabaseQueryObject,
+ OrderByDirection,
+ UseMetabaseQueryObjectResult,
+ UseMetabaseQueryResult,
+} from "./hooks/public/use-metabase-query";
+export type {
+ ActionKindFromDataAppSchema,
+ ActionParametersFromDataAppSchema,
+} from "./hooks/public/use-action";
+export type {
+ DataAppFactory,
+ DataAppMetabaseProviderProps,
+} from "metabase-enterprise/data_apps/sandbox/types";
diff --git a/enterprise/frontend/src/embedding-sdk-package/embedding-sdk-data-app-api-extractor.json b/enterprise/frontend/src/embedding-sdk-package/embedding-sdk-data-app-api-extractor.json
new file mode 100644
index 00000000000..ee265f812d9
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/embedding-sdk-data-app-api-extractor.json
@@ -0,0 +1,25 @@
+{
+ "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
+ "mainEntryPointFilePath": "<projectFolder>/resources/embedding-sdk/dist/enterprise/frontend/src/embedding-sdk-package/data-app.d.ts",
+ "bundledPackages": [],
+ "apiReport": {
+ "enabled": false
+ },
+ "docModel": {
+ "enabled": false
+ },
+ "dtsRollup": {
+ "enabled": true,
+ "untrimmedFilePath": "<projectFolder>/resources/embedding-sdk/dist/data-app.d.ts"
+ },
+ "tsdocMetadata": {
+ "enabled": false
+ },
+ "messages": {
+ "extractorMessageReporting": {
+ "ae-wrong-input-file-type": {
+ "logLevel": "none"
+ }
+ }
+ }
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/embedding-sdk-data-app-dev-api-extractor.json b/enterprise/frontend/src/embedding-sdk-package/embedding-sdk-data-app-dev-api-extractor.json
new file mode 100644
index 00000000000..22ed08b0058
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/embedding-sdk-data-app-dev-api-extractor.json
@@ -0,0 +1,25 @@
+{
+ "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
+ "mainEntryPointFilePath": "<projectFolder>/resources/embedding-sdk/dist/enterprise/frontend/src/embedding-sdk-package/data-app-dev.d.ts",
+ "bundledPackages": [],
+ "apiReport": {
+ "enabled": false
+ },
+ "docModel": {
+ "enabled": false
+ },
+ "dtsRollup": {
+ "enabled": true,
+ "untrimmedFilePath": "<projectFolder>/resources/embedding-sdk/dist/data-app-dev.d.ts"
+ },
+ "tsdocMetadata": {
+ "enabled": false
+ },
+ "messages": {
+ "extractorMessageReporting": {
+ "ae-wrong-input-file-type": {
+ "logLevel": "none"
+ }
+ }
+ }
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/embedding-sdk-data-app-dev-config-api-extractor.json b/enterprise/frontend/src/embedding-sdk-package/embedding-sdk-data-app-dev-config-api-extractor.json
new file mode 100644
index 00000000000..cc1d208187e
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/embedding-sdk-data-app-dev-config-api-extractor.json
@@ -0,0 +1,25 @@
+{
+ "$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json",
+ "mainEntryPointFilePath": "<projectFolder>/resources/embedding-sdk/dist/enterprise/frontend/src/embedding-sdk-package/data-app-dev.config.d.ts",
+ "bundledPackages": [],
+ "apiReport": {
+ "enabled": false
+ },
+ "docModel": {
+ "enabled": false
+ },
+ "dtsRollup": {
+ "enabled": true,
+ "untrimmedFilePath": "<projectFolder>/resources/embedding-sdk/dist/data-app-dev.config.d.ts"
+ },
+ "tsdocMetadata": {
+ "enabled": false
+ },
+ "messages": {
+ "extractorMessageReporting": {
+ "ae-wrong-input-file-type": {
+ "logLevel": "none"
+ }
+ }
+ }
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/private/use-load-sdk-bundle.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/private/use-load-sdk-bundle.ts
index d1e8f23e970..50131263084 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/private/use-load-sdk-bundle.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/private/use-load-sdk-bundle.ts
@@ -4,6 +4,10 @@ import { useEffect } from "react";
import { SDK_BUNDLE_FULL_PATH } from "build-configs/embedding-sdk/constants/sdk-bundle";
import { SDK_BUNDLE_SCRIPT_DATA_ATTRIBUTE_PASCAL_CASED } from "embedding-sdk-package/constants/sdk-bundle-script-data-attribute-name";
import { getSdkBundleScriptElement } from "embedding-sdk-package/lib/private/get-sdk-bundle-script-element";
+import {
+ SDK_BUNDLE_ERROR,
+ SDK_BUNDLE_LOADED,
+} from "embedding-sdk-shared/constants/event-names";
import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";
import {
SdkLoadingError,
@@ -21,7 +25,7 @@ const SDK_PACKAGE_VERSION = process.env.VERSION || "unknown";
*
* - On script `load`: if `window.METABASE_EMBEDDING_SDK_BUNDLE` is already
* set, the monolithic bundle ran synchronously → resolve.
- * - On `"metabase-sdk-bundle-loaded"` CustomEvent: the bootstrap loaded all
+ * - On `SDK_BUNDLE_LOADED` CustomEvent: the bootstrap loaded all
* chunks and `index.ts` executed → resolve.
* - First signal wins; all listeners are cleaned up after settling.
*/
@@ -62,14 +66,14 @@ const waitForScriptLoading = (script: HTMLScriptElement) => {
};
const cleanup = () => {
- document.removeEventListener("metabase-sdk-bundle-loaded", onBundleEvent);
- document.removeEventListener("metabase-sdk-bundle-error", onBundleError);
+ document.removeEventListener(SDK_BUNDLE_LOADED, onBundleEvent);
+ document.removeEventListener(SDK_BUNDLE_ERROR, onBundleError);
script.removeEventListener("load", onScriptLoad);
script.removeEventListener("error", onScriptError);
};
- document.addEventListener("metabase-sdk-bundle-loaded", onBundleEvent);
- document.addEventListener("metabase-sdk-bundle-error", onBundleError);
+ document.addEventListener(SDK_BUNDLE_LOADED, onBundleEvent);
+ document.addEventListener(SDK_BUNDLE_ERROR, onBundleError);
script.addEventListener("load", onScriptLoad);
script.addEventListener("error", onScriptError);
});
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/data-schema.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/data-schema.ts
new file mode 100644
index 00000000000..afe4e49b926
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/data-schema.ts
@@ -0,0 +1,99 @@
+import type { QueryQuestionResult } from "embedding-sdk-bundle/lib/query-question";
+import type {
+ FieldSchema,
+ MeasureSchema,
+ MetricSchema,
+ QuestionSchema,
+ SchemaColumn,
+ SchemaJavaScriptType,
+ SegmentSchema,
+ TableSchema,
+} from "embedding-sdk-shared/lib/create-metabase-query/schema";
+import type { DatasetColumn, RowValues } from "metabase-types/api";
+
+export type {
+ FieldSchema,
+ MeasureSchema,
+ MetricSchema,
+ QuestionSchema,
+ SchemaColumn,
+ SchemaJavaScriptType,
+ SegmentSchema,
+ TableSchema,
+};
+
+/**
+ * A single value returned by Metabase query results or action responses.
+ */
+export type RowValue = string | number | null | boolean | object;
+
+export type SchemaValue<TColumn extends SchemaColumn> =
+ TColumn["jsType"] extends "string"
+ ? string | null
+ : TColumn["jsType"] extends "number"
+ ? number | null
+ : TColumn["jsType"] extends "boolean"
+ ? boolean | null
+ : TColumn["jsType"] extends "Date"
+ ? string | Date | null
+ : RowValue | null;
+
+/** @notExported SchemaValue */
+export type SchemaRow<TSchema extends { columns: readonly SchemaColumn[] }> = {
+ [TColumn in TSchema["columns"][number] as TColumn["name"]]: SchemaValue<TColumn>;
+};
+
+/**
+ * @notExported DatasetColumn
+ * @notExported RowValues
+ */
+export type QueryData<TRow> = {
+ id?: QueryQuestionResult["id"] | null;
+ name?: QueryQuestionResult["name"] | null;
+ description?: QueryQuestionResult["description"];
+ entityId?: QueryQuestionResult["entityId"] | null;
+ rowCount: number | null;
+ runningTime: number | null;
+ columns: DatasetColumn[];
+ rows: TRow[];
+ rawRows: RowValues[];
+};
+
+export type InferSchema<TSchema, TFallback> = TSchema extends {
+ columns: readonly SchemaColumn[];
+}
+ ? SchemaRow<TSchema>
+ : TFallback;
+
+export function getSchemaId<TEntity extends { id: unknown }>(
+ entity: TEntity | TEntity["id"] | null,
+): TEntity["id"] | null {
+ if (entity == null) {
+ return null;
+ }
+
+ if (typeof entity === "object" && "id" in entity) {
+ // `TEntity["id"]` is unconstrained, so it may itself be an object with an
+ // `id`: the guard cannot narrow the `TEntity | TEntity["id"]` union for TS.
+ return entity.id as TEntity["id"];
+ }
+
+ // Not an entity object, so it is already the id — but TS still cannot rule
+ // `TEntity` out of the union at the type level.
+ return entity as TEntity["id"];
+}
+
+export function mapRowsToObjects<TRow>(
+ columns: DatasetColumn[],
+ rows: RowValues[],
+): TRow[] {
+ return rows.map((row) => {
+ // Rows are keyed by column names known only at runtime; `TRow` is the
+ // schema-derived shape the caller expects, so the two can't be tied in TS.
+ return columns.reduce<Record<string, RowValue>>((acc, column, index) => {
+ const key = column.name || column.display_name || `column_${index}`;
+ acc[key] = row[index];
+ return acc;
+ }, {}) as TRow;
+ });
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/index.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/index.ts
index 5e5a2be3628..3f8e3d0033b 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/index.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/index.ts
@@ -2,12 +2,17 @@ export { useAction } from "./use-action";
export type { UseActionResult } from "./use-action";
export type {
ActionExecuteError,
+ ActionImplicitKind,
ActionKind,
+ ActionKindFromDataAppSchema,
+ ActionParameterSchema,
+ ActionParametersFromDataAppSchema,
ActionResultForBulk,
ActionResultForCreate,
ActionResultForDelete,
ActionResultForKind,
ActionResultForSql,
ActionResultForUpdate,
+ ActionSchema,
AnyActionResult,
} from "./types";
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/types.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/types.ts
index b420d570f47..825803d7d21 100644
--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/types.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-action/types.ts
@@ -1,14 +1,19 @@
/**
* Public types for the `useAction` hook surface.
*
- * The hook is schema-agnostic — these types describe just the action kind
- * union and the discriminated `result` shape it drives. A future Data App
- * integration will layer schema-derived helpers (`ActionParametersFromDataAppSchema`,
- * `ActionKindFromDataAppSchema`) on top; they are NOT shipped from this
- * branch.
+ * The hook itself is schema-agnostic — the `ActionKind` union and the
+ * discriminated `ActionResultForKind` shape it drives describe just the
+ * kind / response surface. The `…FromDataAppSchema` helpers below layer on
+ * top, deriving the hook's `TParameters` / `TKind` generics from a
+ * generated `metabase.data.ts` schema entry; the hook never sees the
+ * schema directly.
*/
-import type { RowValue } from "metabase-types/api";
+import type {
+ RowValue,
+ SchemaColumn,
+ SchemaJavaScriptType,
+} from "../data-schema";
/**
* Flat public kind union. Maps onto the backend's namespaced
@@ -128,3 +133,128 @@ export type ActionResultForKind<TKind extends ActionKind | undefined> =
: TKind extends "sql"
? ActionResultForSql
: AnyActionResult;
+
+// ============================================================================
+// Data App schema-derived helpers
+// ----------------------------------------------------------------------------
+// These layer on top of the schema-agnostic types above. They read the shape
+// of a single action entry in a generated `metabase.data.ts` schema and
+// derive the hook's `TParameters` / `TKind` generics, so a Data App author
+// writes `useAction<ActionParametersFromDataAppSchema<typeof action>,
+// ActionKindFromDataAppSchema<typeof action>>(action.id)` and gets
+// compile-time parameter checking plus a typed `result` with no casts.
+// Mode-1 (raw SDK) callers don't import these — they declare `TParameters`
+// by hand and pass `TKind` as a literal.
+// ============================================================================
+
+/**
+ * Backend-namespaced `implicitKind` values for basic actions. Mapped onto
+ * the flat `ActionKind` union by `ActionKindFromDataAppSchema`.
+ *
+ * @category useAction
+ */
+export type ActionImplicitKind =
+ | "row/create"
+ | "row/update"
+ | "row/delete"
+ | "bulk/create"
+ | "bulk/update"
+ | "bulk/delete";
+
+/**
+ * Shape of a single action parameter as it appears in a generated
+ * `metabase.data.ts` schema entry.
+ *
+ * @category useAction
+ */
+export type ActionParameterSchema = SchemaColumn & {
+ slug: string;
+ required?: boolean;
+};
+
+/**
+ * Shape of a single action entry in a generated `metabase.data.ts` schema.
+ * The `id` is the numeric action id passed to `useAction`; `parameters`
+ * drives `ActionParametersFromDataAppSchema`; `implicitKind` / `type` drive
+ * `ActionKindFromDataAppSchema`.
+ *
+ * @category useAction
+ */
+export type ActionSchema = {
+ kind?: "action";
+ id: number;
+ name?: string;
+ type?: "query" | "implicit";
+ implicitKind?: ActionImplicitKind;
+ parameters: readonly ActionParameterSchema[];
+ description?: string;
+ entityId?: string;
+};
+
+/** TS value type for a single action parameter, derived from its `jsType`. */
+type ActionParamValue<TParam extends { jsType?: SchemaJavaScriptType }> =
+ TParam["jsType"] extends "string"
+ ? string | null
+ : TParam["jsType"] extends "number"
+ ? number | null
+ : TParam["jsType"] extends "boolean"
+ ? boolean | null
+ : TParam["jsType"] extends "Date"
+ ? string | Date | null
+ : RowValue | null;
+
+/**
+ * Walks a schema entry's `parameters` tuple and produces an object keyed by
+ * slug. Parameters with `required: true` become required keys; everything
+ * else is optional. Feeds the hook's `TParameters` generic so a Data App
+ * author gets compile-time errors on missing required keys, wrong value
+ * types, and unknown slugs. Falls back to `Record<string, unknown>` if
+ * `TAction` is not a schema entry (e.g. a bare numeric id).
+ *
+ * @category useAction
+ * @notExported ActionParamValue
+ */
+export type ActionParametersFromDataAppSchema<TAction> = TAction extends {
+ parameters: readonly ActionParameterSchema[];
+}
+ ? {
+ [P in TAction["parameters"][number] as P extends { required: true }
+ ? P["slug"]
+ : never]: ActionParamValue<P>;
+ } & {
+ [P in TAction["parameters"][number] as P extends { required: true }
+ ? never
+ : P["slug"]]?: ActionParamValue<P>;
+ }
+ : Record<string, unknown>;
+
+/**
+ * Maps a schema entry's `implicitKind` (or `type === "query"`) to the flat
+ * `ActionKind` union. Feeds the hook's `TKind` generic so `result` is
+ * typed via `ActionResultForKind<TKind>` with no cast — schema-derived,
+ * but the value the hook sees is just a string literal.
+ *
+ * row/create → "create"
+ * row/update → "update"
+ * row/delete → "delete"
+ * bulk/* → "bulk"
+ * type=query → "sql"
+ *
+ * Falls back to the full `ActionKind` union if `TAction` is not a schema
+ * entry (e.g. a bare numeric id).
+ *
+ * @category useAction
+ */
+export type ActionKindFromDataAppSchema<TAction> = TAction extends {
+ implicitKind: "row/create";
+}
+ ? "create"
+ : TAction extends { implicitKind: "row/update" }
+ ? "update"
+ : TAction extends { implicitKind: "row/delete" }
+ ? "delete"
+ : TAction extends { implicitKind: `bulk/${string}` }
+ ? "bulk"
+ : TAction extends { type: "query" }
+ ? "sql"
+ : ActionKind;
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-data-app-location/index.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-data-app-location/index.ts
new file mode 100644
index 00000000000..969308222c4
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-data-app-location/index.ts
@@ -0,0 +1,4 @@
+export {
+ useDataAppLocation,
+ type UseDataAppLocationResult,
+} from "./use-data-app-location";
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-data-app-location/use-data-app-location.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-data-app-location/use-data-app-location.ts
new file mode 100644
index 00000000000..0ce18d5a65d
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-data-app-location/use-data-app-location.ts
@@ -0,0 +1,75 @@
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+ useSyncExternalStore,
+} from "react";
+
+import { SDK_BUNDLE_LOADED } from "embedding-sdk-shared/constants/event-names";
+import { getWindow } from "embedding-sdk-shared/lib/get-window";
+
+export type UseDataAppLocationResult = {
+ pathname: string;
+ navigate: (to: string) => void;
+};
+
+const computeSubPath = (basename: string): string => {
+ if (typeof window === "undefined") {
+ return "/";
+ }
+
+ const pathname = window.location.pathname;
+ const subPath =
+ basename && pathname.startsWith(basename)
+ ? pathname.slice(basename.length)
+ : pathname;
+
+ return subPath || "/";
+};
+
+const useDataAppRouting = () =>
+ useSyncExternalStore(
+ (notify) => {
+ const target = typeof document !== "undefined" ? document : null;
+ const handler = () => notify();
+ target?.addEventListener(SDK_BUNDLE_LOADED, handler);
+ return () => {
+ target?.removeEventListener(SDK_BUNDLE_LOADED, handler);
+ };
+ },
+ () => getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.dataAppRouting,
+ () => undefined,
+ );
+
+export const useDataAppLocation = (): UseDataAppLocationResult => {
+ const dataAppRouting = useDataAppRouting();
+
+ const basename = useMemo(
+ () => dataAppRouting?.getBasename() ?? "",
+ [dataAppRouting],
+ );
+
+ const [pathname, setPathname] = useState(() => computeSubPath(basename));
+
+ useEffect(() => {
+ if (!dataAppRouting) {
+ return;
+ }
+
+ setPathname(computeSubPath(dataAppRouting.getBasename()));
+
+ return dataAppRouting.subscribe(() => {
+ setPathname(computeSubPath(dataAppRouting.getBasename()));
+ });
+ }, [dataAppRouting]);
+
+ const navigate = useCallback(
+ (to: string) => {
+ dataAppRouting?.navigate(to);
+ },
+ [dataAppRouting],
+ );
+
+ return { pathname, navigate };
+};
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/aggregation-helpers.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/aggregation-helpers.ts
new file mode 100644
index 00000000000..55c33e48f44
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/aggregation-helpers.ts
@@ -0,0 +1,117 @@
+import type { SchemaJavaScriptType } from "../data-schema";
+
+import type {
+ CountAggregationSchema,
+ FieldAggregationOperator,
+ FieldAggregationSchema,
+ NumericAggregationDimension,
+ OrderableAggregationDimension,
+} from "./types";
+
+export const count = (): CountAggregationSchema => ({
+ type: "operator",
+ operator: "count",
+ args: [],
+ columns: [{ name: "count", displayName: "Count", jsType: "number" }],
+});
+
+export const sum = <TDimension>(
+ dimension: NumericAggregationDimension<TDimension>,
+): FieldAggregationSchema<"sum", NumericAggregationDimension<TDimension>> =>
+ fieldAggregation("sum", "Sum", dimension);
+
+export const avg = <TDimension>(
+ dimension: NumericAggregationDimension<TDimension>,
+): FieldAggregationSchema<"avg", NumericAggregationDimension<TDimension>> =>
+ fieldAggregation("avg", "Average", dimension);
+
+export const median = <TDimension>(
+ dimension: NumericAggregationDimension<TDimension>,
+): FieldAggregationSchema<"median", NumericAggregationDimension<TDimension>> =>
+ fieldAggregation("median", "Median", dimension);
+
+export const distinct = <TDimension>(
+ dimension: TDimension,
+): FieldAggregationSchema<"distinct", TDimension> =>
+ fieldAggregation("distinct", "Distinct values", dimension);
+
+export const min = <TDimension>(
+ dimension: OrderableAggregationDimension<TDimension>,
+): FieldAggregationSchema<"min", OrderableAggregationDimension<TDimension>> =>
+ fieldAggregation("min", "Minimum", dimension);
+
+export const max = <TDimension>(
+ dimension: OrderableAggregationDimension<TDimension>,
+): FieldAggregationSchema<"max", OrderableAggregationDimension<TDimension>> =>
+ fieldAggregation("max", "Maximum", dimension);
+
+const fieldAggregation = <
+ TOperator extends FieldAggregationOperator,
+ TDimension,
+>(
+ type: TOperator,
+ displayName: string,
+ dimension: TDimension,
+): FieldAggregationSchema<TOperator, TDimension> =>
+ // The column's `name`/`jsType` are computed at runtime (`string` /
+ // `SchemaJavaScriptType`), while the schema type states them as the conditional
+ // literals derived from `TOperator` — TS can't connect the two.
+ ({
+ type: "operator",
+ operator: type,
+ args: [dimension],
+ columns: [
+ {
+ name: getFieldAggregationColumnName(type),
+ displayName,
+ jsType: getFieldAggregationColumnJavaScriptType(type, dimension),
+ },
+ ],
+ }) as unknown as FieldAggregationSchema<TOperator, TDimension>;
+
+const getFieldAggregationColumnName = (
+ type: FieldAggregationOperator,
+): string => (type === "distinct" ? "count" : type);
+
+function getFieldAggregationColumnJavaScriptType(
+ type: FieldAggregationOperator,
+ dimension: unknown,
+): SchemaJavaScriptType {
+ if (type !== "min" && type !== "max") {
+ return "number";
+ }
+
+ if (
+ dimension == null ||
+ typeof dimension !== "object" ||
+ !("jsType" in dimension)
+ ) {
+ return "number";
+ }
+
+ const { jsType } = dimension;
+
+ if (isOrderableJavaScriptType(jsType)) {
+ return jsType;
+ }
+
+ return "number";
+}
+
+const isOrderableJavaScriptType = (
+ value: unknown,
+): value is Exclude<SchemaJavaScriptType, "unknown"> =>
+ value === "string" ||
+ value === "number" ||
+ value === "boolean" ||
+ value === "Date";
+
+export const aggregations = {
+ avg,
+ count,
+ distinct,
+ max,
+ median,
+ min,
+ sum,
+} as const;
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/bundle.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/bundle.ts
new file mode 100644
index 00000000000..7e98cacbb0a
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/bundle.ts
@@ -0,0 +1,7 @@
+import { getWindow } from "embedding-sdk-shared/lib/get-window";
+
+export const getEmbeddingSdkBundle = () =>
+ getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE;
+
+export const getResolveDatasetQueryFromBundle = () =>
+ getEmbeddingSdkBundle()?.resolveDatasetQuery;
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/index.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/index.ts
new file mode 100644
index 00000000000..c34886984aa
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/index.ts
@@ -0,0 +1,23 @@
+export {
+ aggregations,
+ avg,
+ count,
+ distinct,
+ max,
+ median,
+ min,
+ sum,
+} from "./aggregation-helpers";
+export { breakout, filter, orderBy } from "./query-helpers";
+export { useMetabaseQuery } from "./use-metabase-query";
+export { useMetabaseQueryObject } from "./use-metabase-query-object";
+export type {
+ LocalFieldReference,
+ MetabaseBreakout,
+ MetabaseOrderBy,
+ MetabaseQueryOptions,
+ OrderByDirection,
+ UseMetabaseQueryResult,
+} from "./types";
+export type { UseMetabaseQueryObjectResult } from "./use-metabase-query-object";
+export type { MetabaseQueryObject } from "metabase/embedding-sdk/types/question";
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/map-dataset-query-data.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/map-dataset-query-data.ts
new file mode 100644
index 00000000000..ed1d75138d3
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/map-dataset-query-data.ts
@@ -0,0 +1,13 @@
+import type { QueryDatasetResult } from "embedding-sdk-bundle/lib/query-dataset";
+import type { QueryQuestionResult } from "embedding-sdk-bundle/lib/query-question";
+
+import type { QueryData } from "../data-schema";
+import { mapRowsToObjects } from "../data-schema";
+
+export const mapDatasetQueryData = <TRow>(
+ result: QueryQuestionResult | QueryDatasetResult,
+): QueryData<TRow> => ({
+ ...result,
+ rows: mapRowsToObjects<TRow>(result.columns, result.rows),
+ rawRows: result.rows,
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/query-helpers.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/query-helpers.ts
new file mode 100644
index 00000000000..0de3db37e74
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/query-helpers.ts
@@ -0,0 +1,211 @@
+import { isUnaryOperator } from "embedding-sdk-shared/lib/create-metabase-query/input-guards";
+
+import type { SchemaColumn } from "../data-schema";
+
+import type {
+ BetweenFilterOperatorForDimension,
+ BinningOptions,
+ BreakoutOptionsArgument,
+ FilterLiteralValue,
+ FilterOperator,
+ MetabaseDimensionFilterForOperator,
+ OrderByDirection,
+ UnaryFilterOperatorForDimension,
+ ValueFilterOperatorForDimension,
+} from "./types";
+
+export function filter<
+ TDimension,
+ TOperator extends ValueFilterOperatorForDimension<TDimension>,
+>(
+ dimension: TDimension,
+ operator: TOperator,
+ value: unknown,
+): MetabaseDimensionFilterForOperator<TDimension, TOperator>;
+
+export function filter<
+ TDimension,
+ TOperator extends BetweenFilterOperatorForDimension<TDimension>,
+>(
+ dimension: TDimension,
+ operator: TOperator,
+ values: readonly [unknown, unknown],
+): MetabaseDimensionFilterForOperator<TDimension, TOperator>;
+
+export function filter<
+ TDimension,
+ TOperator extends UnaryFilterOperatorForDimension<TDimension>,
+>(
+ dimension: TDimension,
+ operator: TOperator,
+): MetabaseDimensionFilterForOperator<TDimension, TOperator>;
+
+export function filter(
+ dimension: unknown,
+ operator: FilterOperator,
+ value?: unknown,
+): MetabaseDimensionFilterForOperator<unknown, FilterOperator> {
+ if (operator === "between") {
+ // The `between` overload takes a `[min, max]` tuple, but the implementation
+ // signature shared by all overloads widens `value` to `unknown`.
+ const [min, max] = value as readonly [unknown, unknown];
+
+ return {
+ type: "operator",
+ operator,
+ args: [dimension, toFilterLiteral(min), toFilterLiteral(max)],
+ };
+ }
+
+ if (isUnaryOperator(operator)) {
+ return { type: "operator", operator, args: [dimension] };
+ }
+
+ return {
+ type: "operator",
+ operator,
+ args: [dimension, toFilterLiteral(value)],
+ };
+}
+
+export function breakout<TDimension extends object>(
+ dimension: TDimension,
+): TDimension;
+
+export function breakout<TDimension extends object>(
+ dimension: TDimension,
+ options: BreakoutOptionsArgument<TDimension>,
+): TDimension & BreakoutOptionsArgument<TDimension>;
+
+export function breakout<TDimension extends object>(
+ dimension: TDimension,
+ options?: BreakoutOptionsArgument<TDimension>,
+) {
+ return {
+ ...dimension,
+ unit: options && "unit" in options ? options.unit : undefined,
+ ...getBinningOptions(options),
+ };
+}
+
+export function orderBy<
+ TAggregation extends { columns?: readonly SchemaColumn[] },
+>(
+ aggregation: TAggregation,
+ direction?: OrderByDirection,
+): SchemaColumn & { type: "column"; direction?: OrderByDirection };
+
+export function orderBy<TDimension>(
+ dimension: TDimension,
+ direction?: OrderByDirection,
+): TDimension & { direction?: OrderByDirection };
+
+export function orderBy<TDimension>(
+ dimension: TDimension,
+ direction: OrderByDirection | undefined,
+ options: BreakoutOptionsArgument<TDimension>,
+): TDimension & {
+ direction?: OrderByDirection;
+} & BreakoutOptionsArgument<TDimension>;
+
+export function orderBy<TDimension>(
+ dimension: TDimension,
+ direction?: OrderByDirection,
+ options?: BreakoutOptionsArgument<TDimension>,
+) {
+ const aggregationColumn = getAggregationResultColumn(dimension);
+
+ if (aggregationColumn) {
+ return {
+ type: "column",
+ name: aggregationColumn.name,
+ ...(direction ? { direction } : undefined),
+ };
+ }
+
+ // Do not pass the display name. It narrows the lookup and causes "No column found" errors.
+ // The orderable column’s display name can be different from the schema field’s display name.
+ const { displayName: _displayName, ...orderableDimension } = dimension as {
+ displayName?: unknown;
+ } & object;
+
+ return {
+ ...orderableDimension,
+ ...(direction ? { direction } : undefined),
+ unit: options && "unit" in options ? options.unit : undefined,
+ ...getBinningOptions(options),
+ };
+}
+
+function getAggregationResultColumn(value: unknown): SchemaColumn | undefined {
+ if (value == null || typeof value !== "object" || !("columns" in value)) {
+ return undefined;
+ }
+
+ const { columns } = value;
+
+ if (!Array.isArray(columns)) {
+ return undefined;
+ }
+
+ const [column] = columns;
+
+ return isSchemaColumn(column) ? column : undefined;
+}
+
+function isSchemaColumn(value: unknown): value is SchemaColumn {
+ return (
+ value != null &&
+ typeof value === "object" &&
+ "name" in value &&
+ typeof value.name === "string"
+ );
+}
+
+function getBinningOptions(
+ options:
+ | {
+ binning?: BinningOptions;
+ bins?: number | "auto";
+ binWidth?: number | "auto";
+ }
+ | undefined,
+) {
+ if (!options) {
+ return undefined;
+ }
+
+ if ("bins" in options && options.bins != null) {
+ return { bins: options.bins };
+ }
+
+ if ("binWidth" in options && options.binWidth != null) {
+ return { binWidth: options.binWidth };
+ }
+
+ if (options.binning?.strategy === "num-bins") {
+ return { bins: options.binning["num-bins"] };
+ }
+
+ if (options.binning?.strategy === "bin-width") {
+ return { binWidth: options.binning["bin-width"] };
+ }
+
+ if (options.binning?.strategy === "default") {
+ return { bins: "auto" as const };
+ }
+
+ return undefined;
+}
+
+function toFilterLiteral(value: unknown): {
+ type: "literal";
+ value: FilterLiteralValue;
+} {
+ return {
+ type: "literal",
+ // The overloads accept the filter value as `unknown` (it is only constrained
+ // by the operator), while the emitted filter types it as a literal value.
+ value: value as FilterLiteralValue,
+ };
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/stable-query-key.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/stable-query-key.ts
new file mode 100644
index 00000000000..53ef60c450d
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/stable-query-key.ts
@@ -0,0 +1,18 @@
+export const stableStringifyQuery = (query: unknown) =>
+ JSON.stringify(sortQueryObject(query));
+
+function sortQueryObject(value: unknown): unknown {
+ if (value === null || typeof value !== "object") {
+ return value;
+ }
+
+ if (Array.isArray(value)) {
+ return value.map(sortQueryObject);
+ }
+
+ return Object.fromEntries(
+ Object.entries(value)
+ .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
+ .map(([key, value]) => [key, sortQueryObject(value)]),
+ );
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts
new file mode 100644
index 00000000000..15c386adf82
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/types.ts
@@ -0,0 +1,498 @@
+import type {
+ BooleanFilterOperator,
+ DefaultFilterOperator,
+ ExcludeDateFilterOperator,
+ FilterOperator as LibFilterOperator,
+ StringFilterOperator as LibStringFilterOperator,
+ NumberFilterOperator,
+ SpecificDateFilterOperator,
+ TimeFilterOperator,
+} from "metabase-lib/common";
+import type { TemporalUnit } from "metabase-types/api";
+
+import type {
+ FieldSchema,
+ InferSchema,
+ MetricSchema,
+ QueryData,
+ QuestionSchema,
+ SchemaColumn,
+ SchemaJavaScriptType,
+ SchemaValue,
+ TableSchema,
+} from "../data-schema";
+
+type Values<T> = T[keyof T];
+type UnionToIntersection<TUnion> = (
+ TUnion extends unknown ? (value: TUnion) => void : never
+) extends (value: infer TIntersection) => void
+ ? TIntersection
+ : never;
+
+type FieldValues<TEntity> = TEntity extends {
+ fields?: infer TFields;
+}
+ ? Values<NonNullable<TFields>>
+ : never;
+
+type FieldNames<TEntity> =
+ FieldValues<TEntity> extends { name: infer TName } ? TName : string;
+
+type SegmentIds<TEntity> = TEntity extends { segments?: infer TSegments }
+ ? Values<NonNullable<TSegments>> extends { id: infer TId }
+ ? TId
+ : never
+ : never;
+
+type MeasureIds<TEntity> = TEntity extends { measures?: infer TMeasures }
+ ? Values<NonNullable<TMeasures>> extends { id: infer TId }
+ ? TId
+ : never
+ : never;
+
+type SourceQuerySpec<TTable> = {
+ type: "table";
+ id: TTable extends { id: infer TId extends number } ? TId : number;
+};
+
+type TableId<TTable> = TTable extends { id: infer TId extends number }
+ ? TId
+ : number;
+
+export type SegmentReference<TTable = unknown> = {
+ type: "segment";
+ id: [SegmentIds<TTable>] extends [never] ? number : SegmentIds<TTable>;
+ tableId?: TableId<TTable>;
+};
+
+export type MeasureReference<TTable = unknown> = {
+ type: "measure";
+ id: [MeasureIds<TTable>] extends [never] ? number : MeasureIds<TTable>;
+ tableId?: TableId<TTable>;
+ columns?: readonly SchemaColumn[];
+};
+
+/**
+ * Metrics with table source emits `sourceTableId`. Its `mappedTableIds` can include
+ * joined tables exposed by generated dimensions, so once `sourceTableId` matches the
+ * source table, `mappedTableIds` must stay wider than the source table id.
+ *
+ * The second branch is a fallback for Metric metadata without `sourceTableId`.
+ * In that shape, `mappedTableIds` is the only available compile-time proof,
+ * so each mapped id must match the query source table.
+ */
+export type MetricReference<TTable = unknown> = Omit<
+ MetricSchema,
+ "mappedTableIds" | "sourceCardId" | "sourceTableId"
+> & {
+ type: "metric";
+
+ // Metrics based on saved questions are not yet supported
+ // TODO(EMB-2045): add support for saved questions as metric sources
+ sourceCardId?: never;
+} & (
+ | {
+ sourceTableId: TableId<TTable>;
+ mappedTableIds?: readonly number[];
+ }
+ | {
+ sourceTableId?: TableId<TTable>;
+ mappedTableIds: readonly TableId<TTable>[];
+ }
+ );
+
+/**
+ * A dimension on the query's own source table — what `filter`, `breakout`, and
+ * `orderBy` take. Apps with a generated `metabase.data.ts` schema get these from
+ * it; an app building one by hand (from a field id and table id) names this type.
+ * `FieldReference` is deliberately not the type to reach for: it also admits
+ * FK-joined dimensions, which a local source table can't accept.
+ */
+export type LocalFieldReference<TTable = unknown> = Omit<
+ FieldSchema,
+ "sourceFieldId" | "tableId"
+> & {
+ type: "column";
+ name: [FieldNames<TTable>] extends [never] ? string : FieldNames<TTable>;
+ tableId: TableId<TTable>;
+
+ // Fields with `sourceFieldId` are FK-joined dimensions; keep them out of the
+ // "local source table" branch so table ownership checks stay strict.
+ sourceFieldId?: never;
+};
+
+type JoinedFieldReference = Omit<FieldSchema, "sourceFieldId" | "tableId"> & {
+ type: "column";
+ sourceFieldId: number;
+
+ // Joined fields are scoped through the source FK field, not by declaring
+ // themselves as fields on the query's source table.
+ tableId?: never;
+};
+
+export type FieldReference<TTable = unknown> =
+ | LocalFieldReference<TTable>
+ | JoinedFieldReference;
+
+export type CountAggregation = {
+ type: "operator";
+ operator: "count";
+ args: [];
+};
+
+export type CountAggregationSchema = CountAggregation & {
+ columns: readonly [
+ {
+ name: "count";
+ displayName: "Count";
+ jsType: "number";
+ },
+ ];
+};
+
+type CountAggregationColumn = CountAggregationSchema["columns"][number];
+
+export type FieldAggregationOperator =
+ | "sum"
+ | "avg"
+ | "median"
+ | "distinct"
+ | "min"
+ | "max";
+
+export type FieldAggregation<
+ TOperator extends FieldAggregationOperator = FieldAggregationOperator,
+ TDimension = unknown,
+> = {
+ type: "operator";
+ operator: TOperator;
+ args: readonly [TDimension];
+};
+
+export type FieldAggregationSchema<
+ TOperator extends FieldAggregationOperator = FieldAggregationOperator,
+ TDimension = unknown,
+ TJavaScriptType extends SchemaJavaScriptType = "number",
+> = FieldAggregation<TOperator, TDimension> & {
+ columns: readonly [
+ {
+ name: TOperator extends "distinct" ? "count" : TOperator;
+ displayName: string;
+ jsType: TJavaScriptType;
+ },
+ ];
+};
+
+type AnyAggregation<TTable = unknown> =
+ | CountAggregation
+ | CountAggregationSchema
+ | FieldAggregation<FieldAggregationOperator, FieldReference<TTable>>
+ | FieldAggregationSchema<FieldAggregationOperator, FieldReference<TTable>>
+ | MeasureReference<TTable>
+ | MetricReference<TTable>;
+
+type AggregationDimensionWithJavaScriptType<
+ TDimension,
+ TJavaScriptType extends SchemaJavaScriptType,
+> = TDimension extends unknown
+ ? TDimension extends { jsType?: infer TDimensionJavaScriptType }
+ ? Extract<
+ NonNullable<TDimensionJavaScriptType>,
+ TJavaScriptType
+ > extends never
+ ? never
+ : TDimension
+ : TDimension
+ : never;
+
+export type NumericAggregationDimension<TDimension> =
+ AggregationDimensionWithJavaScriptType<TDimension, "number">;
+
+export type OrderableAggregationDimension<TDimension> =
+ AggregationDimensionWithJavaScriptType<
+ TDimension,
+ "string" | "number" | "boolean" | "Date"
+ >;
+
+export type FilterOperator =
+ | Exclude<LibFilterOperator, "inside">
+ | "time-interval";
+
+type UnaryFilterOperator = "is-empty" | "not-empty" | "is-null" | "not-null";
+type BetweenFilterOperator = "between";
+type StringFilterOperator = LibStringFilterOperator | DefaultFilterOperator;
+type DateFilterOperator =
+ | SpecificDateFilterOperator
+ | ExcludeDateFilterOperator
+ | TimeFilterOperator
+ | ">="
+ | "<="
+ | "time-interval";
+
+type FilterOperatorForDimension<TDimension> = TDimension extends {
+ jsType?: infer TJavaScriptType;
+}
+ ? NonNullable<TJavaScriptType> extends "string"
+ ? StringFilterOperator
+ : NonNullable<TJavaScriptType> extends "number"
+ ? NumberFilterOperator
+ : NonNullable<TJavaScriptType> extends "boolean"
+ ? BooleanFilterOperator
+ : NonNullable<TJavaScriptType> extends "Date"
+ ? DateFilterOperator
+ : FilterOperator
+ : FilterOperator;
+
+export type UnaryFilterOperatorForDimension<TDimension> = Extract<
+ FilterOperatorForDimension<TDimension>,
+ UnaryFilterOperator
+>;
+
+export type BetweenFilterOperatorForDimension<TDimension> = Extract<
+ FilterOperatorForDimension<TDimension>,
+ BetweenFilterOperator
+>;
+
+export type ValueFilterOperatorForDimension<TDimension> = Exclude<
+ FilterOperatorForDimension<TDimension>,
+ UnaryFilterOperator | BetweenFilterOperator
+>;
+
+export type MetabaseDimensionFilterForOperator<
+ TDimension,
+ TOperator extends FilterOperatorForDimension<TDimension>,
+> = {
+ type: "operator";
+ operator: TOperator;
+ args: readonly [
+ TDimension,
+ ...{
+ type: "literal";
+ value: FilterLiteralValue;
+ }[],
+ ];
+};
+
+type MetabaseDimensionFilterForDimension<TDimension> =
+ TDimension extends unknown
+ ? {
+ type: "operator";
+ operator: FilterOperatorForDimension<TDimension>;
+ args: readonly [
+ TDimension,
+ ...{
+ type: "literal";
+ value: FilterLiteralValue;
+ }[],
+ ];
+ }
+ : never;
+
+export type MetabaseDimensionFilter<TEntity = unknown> =
+ MetabaseDimensionFilterForDimension<FieldReference<TEntity>>;
+
+export type FilterLiteralValue = string | number | bigint | boolean;
+
+type DateBucketDimension<TDimension> = TDimension extends unknown
+ ? TDimension extends { jsType?: infer TJavaScriptType }
+ ? "Date" extends NonNullable<TJavaScriptType>
+ ? TDimension
+ : never
+ : TDimension
+ : never;
+
+type NonDateBucketDimension<TDimension> = TDimension extends unknown
+ ? TDimension extends { jsType?: infer TJavaScriptType }
+ ? "Date" extends NonNullable<TJavaScriptType>
+ ? never
+ : TDimension
+ : never
+ : never;
+
+export type BreakoutOptionsArgument<TDimension> = [
+ DateBucketDimension<TDimension>,
+] extends [never]
+ ? { binning?: BinningOptions } & BinningOptionsInput
+ : { unit?: TemporalUnit; binning?: BinningOptions } & BinningOptionsInput;
+
+export type MetabaseBreakoutObjectForDimension<TDimension> =
+ | ([DateBucketDimension<TDimension>] extends [never]
+ ? never
+ : DateBucketDimension<TDimension> & {
+ unit?: TemporalUnit;
+ binning?: BinningOptions;
+ } & BinningOptionsInput)
+ | ([NonDateBucketDimension<TDimension>] extends [never]
+ ? never
+ : NonDateBucketDimension<TDimension> & {
+ binning?: BinningOptions;
+ } & BinningOptionsInput);
+
+export type MetabaseBreakout<TTable = unknown> =
+ | FieldReference<TTable>
+ | MetabaseBreakoutObjectForDimension<FieldReference<TTable>>;
+
+export type OrderByDirection = "asc" | "desc";
+
+type MetabaseOrderByObjectForDimension<TDimension> =
+ MetabaseBreakoutObjectForDimension<TDimension> & {
+ direction?: OrderByDirection;
+ };
+
+export type MetabaseOrderBy<TTable = unknown> =
+ | (FieldReference<TTable> & { direction?: OrderByDirection })
+ | MetabaseOrderByObjectForDimension<FieldReference<TTable>>
+ | AggregationResultOrderBy;
+
+type AggregationResultOrderBy = {
+ type: "column";
+ name: string;
+ direction?: OrderByDirection;
+};
+
+type BinningOptionsInput =
+ | { bins?: number | "auto"; binWidth?: never }
+ | { binWidth?: number | "auto"; bins?: never };
+
+export type BinningOptions =
+ | { strategy: "default" }
+ | { strategy: "num-bins"; "num-bins": number }
+ | { strategy: "bin-width"; "bin-width": number };
+
+type TableQueryBase<TTable> = {
+ source: TTable extends TableSchema ? SourceQuerySpec<TTable> : TableSchema;
+ fields?: readonly FieldReference<TTable>[];
+ filters?: readonly (
+ | SegmentReference<TTable>
+ | MetabaseDimensionFilterForDimension<FieldReference<TTable>>
+ )[];
+ orderBys?: readonly MetabaseOrderBy<TTable>[];
+ limit?: number;
+ enabled?: boolean;
+} & (
+ | {
+ breakouts?: undefined;
+ aggregations?: readonly AnyAggregation<TTable>[];
+ }
+ | {
+ breakouts: readonly MetabaseBreakout<TTable>[];
+ aggregations: readonly [
+ AnyAggregation<TTable>,
+ ...AnyAggregation<TTable>[],
+ ];
+ }
+);
+
+export type QuestionQuery<TQuestion = unknown> = {
+ source: TQuestion extends QuestionSchema ? TQuestion : QuestionSchema;
+ fields?: never;
+ filters?: never;
+ aggregations?: never;
+ breakouts?: never;
+ orderBys?: never;
+ limit?: never;
+ enabled?: boolean;
+};
+
+type RequireAggregationsForBreakouts<TQuery> = TQuery extends {
+ breakouts: readonly [unknown, ...unknown[]];
+}
+ ? TQuery extends { aggregations: readonly [unknown, ...unknown[]] }
+ ? unknown
+ : { aggregations: readonly [unknown, ...unknown[]] }
+ : unknown;
+
+export type TableQuery<TTable, TQuery = unknown> = TableQueryBase<TTable> &
+ RequireAggregationsForBreakouts<TQuery>;
+
+export type MetabaseQueryOptions<TEntity = unknown, _TSchema = unknown> = [
+ TEntity,
+] extends [undefined]
+ ? TableQuery<TEntity> | QuestionQuery<TEntity>
+ : TEntity extends QuestionSchema
+ ? QuestionQuery<TEntity>
+ : TableQuery<TEntity>;
+
+type EmptyRow = Record<never, never>;
+
+type ColumnRow<TColumn> = TColumn extends SchemaColumn
+ ? string extends TColumn["name"]
+ ? EmptyRow
+ : { [TName in TColumn["name"]]: SchemaValue<TColumn> }
+ : EmptyRow;
+
+type RowsFromColumns<TColumn> = [TColumn] extends [never]
+ ? EmptyRow
+ : UnionToIntersection<TColumn extends unknown ? ColumnRow<TColumn> : never>;
+
+type TupleElement<TValue> = TValue extends readonly unknown[]
+ ? TValue[number]
+ : never;
+
+type QueryFieldColumns<TQuery> = TQuery extends { fields?: infer TFields }
+ ? TupleElement<NonNullable<TFields>>
+ : never;
+
+type QueryBreakoutColumns<TQuery> = TQuery extends {
+ breakouts?: infer TBreakouts;
+}
+ ? TupleElement<NonNullable<TBreakouts>>
+ : never;
+
+type QueryAggregationColumns<TQuery> = TQuery extends {
+ aggregations?: infer TAggregations;
+}
+ ? TupleElement<NonNullable<TAggregations>> extends infer TAggregation
+ ? TAggregation extends { columns: infer TColumns }
+ ? TupleElement<NonNullable<TColumns>>
+ : TAggregation extends CountAggregation
+ ? CountAggregationColumn
+ : never
+ : never
+ : never;
+
+type DefaultTableColumns<TEntity, TQuery> = TQuery extends { fields: unknown }
+ ? never
+ : TQuery extends { aggregations: unknown }
+ ? never
+ : TQuery extends { breakouts: unknown }
+ ? never
+ : TEntity extends { fields?: infer TFields }
+ ? Values<NonNullable<TFields>>
+ : never;
+
+type InferQuerySchema<TEntity, TQuery> = InferSchema<TEntity, EmptyRow> &
+ RowsFromColumns<
+ | DefaultTableColumns<TEntity, TQuery>
+ | QueryFieldColumns<TQuery>
+ | QueryBreakoutColumns<TQuery>
+ | QueryAggregationColumns<TQuery>
+ >;
+
+type InferQueryEntity<TQuery> = TQuery extends { source: infer TTable }
+ ? TTable
+ : undefined;
+
+type QueryEntity<TEntity, TQuery> = [TEntity] extends [undefined]
+ ? InferQueryEntity<TQuery>
+ : TEntity;
+
+export type UseMetabaseQueryResult<TEntity = unknown, TQuery = unknown> = {
+ data: QueryData<InferQuerySchema<TEntity, TQuery>> | null;
+ isLoading: boolean;
+ error: unknown;
+ refetch: () => Promise<void>;
+};
+
+export type UseMetabaseQuery = <
+ TEntity extends TableSchema | QuestionSchema | undefined = undefined,
+ TSchema = unknown,
+ const TQuery = MetabaseQueryOptions<TEntity, TSchema>,
+>(
+ query: TQuery &
+ (TQuery extends MetabaseQueryOptions<TEntity, TSchema>
+ ? TQuery extends { source: unknown }
+ ? RequireAggregationsForBreakouts<TQuery>
+ : unknown
+ : MetabaseQueryOptions<TEntity, TSchema>),
+) => UseMetabaseQueryResult<QueryEntity<TEntity, TQuery>, TQuery>;
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query-object.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query-object.ts
new file mode 100644
index 00000000000..44be08d5560
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query-object.ts
@@ -0,0 +1,99 @@
+import { useEffect, useMemo, useRef } from "react";
+import { useAsyncFn } from "react-use";
+
+import { useLazySelector } from "embedding-sdk-package/hooks/private/use-lazy-selector";
+import { useMetabaseProviderPropsStore } from "embedding-sdk-shared/hooks/use-metabase-provider-props-store";
+import { useSdkLoadingState } from "embedding-sdk-shared/hooks/use-sdk-loading-state";
+import type { MetabaseQueryObject } from "metabase/embedding-sdk/types/question";
+
+import {
+ getEmbeddingSdkBundle,
+ getResolveDatasetQueryFromBundle,
+} from "./bundle";
+import { stableStringifyQuery } from "./stable-query-key";
+import type { MetabaseQueryOptions } from "./types";
+
+export type UseMetabaseQueryObjectResult = {
+ query: MetabaseQueryObject | null;
+ error: unknown;
+ isLoading: boolean;
+};
+
+type QueryObjectState = {
+ query: MetabaseQueryObject;
+ queryKey: string;
+};
+
+/**
+ * Resolves a data app query into a query object that can be passed to SDK question components.
+ */
+export function useMetabaseQueryObject(
+ query: MetabaseQueryOptions,
+): UseMetabaseQueryObjectResult {
+ const { loadingState } = useSdkLoadingState();
+
+ const loginStatus = useLazySelector(getEmbeddingSdkBundle()?.getLoginStatus);
+
+ const {
+ state: {
+ internalProps: { reduxStore },
+ },
+ } = useMetabaseProviderPropsStore();
+
+ const queryKey = useMemo(() => stableStringifyQuery(query), [query]);
+ const queryRef = useRef(query);
+ const pendingQueryKeyRef = useRef<string | null>(null);
+
+ queryRef.current = query;
+
+ const [{ value, error, loading }, resolveQueryObject] =
+ useAsyncFn(async (): Promise<QueryObjectState | null> => {
+ const resolveDatasetQuery = getResolveDatasetQueryFromBundle();
+
+ if (!reduxStore || !resolveDatasetQuery) {
+ return null;
+ }
+
+ const result = await resolveDatasetQuery(reduxStore)(queryRef.current);
+
+ return {
+ // The bundle returns the opaque `DatasetQuery`; the public API publishes
+ // the structural `MetabaseQueryObject` instead (see its own docs for why).
+ query: result as MetabaseQueryObject,
+ queryKey,
+ };
+ }, [queryKey, reduxStore]);
+
+ useEffect(() => {
+ if (
+ !reduxStore ||
+ !getResolveDatasetQueryFromBundle() ||
+ loginStatus?.status !== "success"
+ ) {
+ return;
+ }
+
+ pendingQueryKeyRef.current = queryKey;
+ resolveQueryObject();
+ }, [
+ loadingState,
+ loginStatus?.status,
+ queryKey,
+ reduxStore,
+ resolveQueryObject,
+ ]);
+
+ if (error && !loading && pendingQueryKeyRef.current === queryKey) {
+ return { query: null, error, isLoading: false };
+ }
+
+ if (loginStatus?.status !== "success" || value?.queryKey !== queryKey) {
+ return { query: null, error: null, isLoading: true };
+ }
+
+ return {
+ query: value.query,
+ error: error ?? null,
+ isLoading: loading,
+ };
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query.ts
new file mode 100644
index 00000000000..a91c4626885
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query.ts
@@ -0,0 +1,99 @@
+import { useCallback, useEffect, useMemo, useRef } from "react";
+import { useAsyncFn } from "react-use";
+
+import { useLazySelector } from "embedding-sdk-package/hooks/private/use-lazy-selector";
+import { useMetabaseProviderPropsStore } from "embedding-sdk-shared/hooks/use-metabase-provider-props-store";
+import { isQueryInput } from "embedding-sdk-shared/lib/create-metabase-query/input-guards";
+
+import type { QuestionSchema, TableSchema } from "../data-schema";
+
+import {
+ getEmbeddingSdkBundle,
+ getResolveDatasetQueryFromBundle,
+} from "./bundle";
+import { mapDatasetQueryData } from "./map-dataset-query-data";
+import { stableStringifyQuery } from "./stable-query-key";
+import type {
+ MetabaseQueryOptions,
+ UseMetabaseQuery,
+ UseMetabaseQueryResult,
+} from "./types";
+
+const useMetabaseQueryImpl = <
+ TEntity extends TableSchema | QuestionSchema | undefined = undefined,
+ TSchema = unknown,
+ TQuery extends MetabaseQueryOptions<TEntity, TSchema> = MetabaseQueryOptions<
+ TEntity,
+ TSchema
+ >,
+>(
+ query: TQuery,
+): UseMetabaseQueryResult<TEntity, TQuery> => {
+ const {
+ state: {
+ internalProps: { reduxStore },
+ },
+ } = useMetabaseProviderPropsStore();
+
+ const loginStatus = useLazySelector(getEmbeddingSdkBundle()?.getLoginStatus);
+
+ const queryDataset = getEmbeddingSdkBundle()?.queryDataset;
+ const resolveDatasetQuery = getResolveDatasetQueryFromBundle();
+
+ const queryKey = useMemo(() => stableStringifyQuery(query), [query]);
+ const queryRef = useRef(query);
+
+ useEffect(() => {
+ queryRef.current = query;
+ }, [query, queryKey]);
+
+ const [{ value: data = null, loading: isLoading, error }, fetchQuery] =
+ useAsyncFn(async (): Promise<
+ UseMetabaseQueryResult<TEntity, TQuery>["data"]
+ > => {
+ const currentQuery = queryRef.current;
+
+ if (currentQuery.enabled === false) {
+ return null;
+ }
+
+ if (!reduxStore) {
+ return null;
+ }
+
+ if (isQueryInput(currentQuery)) {
+ if (!queryDataset || !resolveDatasetQuery) {
+ return null;
+ }
+
+ const datasetQuery =
+ await resolveDatasetQuery(reduxStore)(currentQuery);
+ const result = await queryDataset(reduxStore)({ datasetQuery });
+
+ return mapDatasetQueryData(result);
+ }
+
+ return null;
+ }, [queryDataset, reduxStore, resolveDatasetQuery]);
+
+ // Type signature of refetch requires returning Promise<void>
+ const refetch = useCallback(async () => {
+ await fetchQuery();
+ }, [fetchQuery]);
+
+ useEffect(() => {
+ if (loginStatus?.status === "success") {
+ refetch();
+ }
+ }, [loginStatus?.status, queryKey, refetch]);
+
+ return {
+ data,
+ isLoading,
+ error: isLoading ? null : (error ?? null),
+ refetch,
+ };
+};
+
+/** @notExported useMetabaseQuery */
+export const useMetabaseQuery = useMetabaseQueryImpl as UseMetabaseQuery;
diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query.unit.spec.tsx
new file mode 100644
index 00000000000..95ec13dcd07
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-metabase-query/use-metabase-query.unit.spec.tsx
@@ -0,0 +1,1651 @@
+import { act, renderHook, waitFor } from "@testing-library/react";
+
+import { resolveDatasetQuery as resolveDatasetQueryInBundle } from "embedding-sdk-bundle/lib/create-metabase-query";
+import type { QueryDatasetResult } from "embedding-sdk-bundle/lib/query-dataset";
+import type { SdkStore } from "embedding-sdk-bundle/store/types";
+import type { MetabaseEmbeddingSdkBundleExports } from "embedding-sdk-bundle/types/sdk-bundle";
+import { useLazySelector } from "embedding-sdk-package/hooks/private/use-lazy-selector";
+import { useMetabaseProviderPropsStore } from "embedding-sdk-shared/hooks/use-metabase-provider-props-store";
+import { useSdkLoadingState } from "embedding-sdk-shared/hooks/use-sdk-loading-state";
+import type { QueryInput } from "embedding-sdk-shared/lib/create-metabase-query/input-guards";
+import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";
+import { SdkLoadingState } from "embedding-sdk-shared/types/sdk-loading";
+import { cardApi } from "metabase/api";
+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";
+import type { MetabaseCard } from "metabase/embedding-sdk/types/question";
+import { fetchTableMetadata } from "metabase/redux/tables";
+import { getMetadataUnfiltered } from "metabase/selectors/metadata";
+import type { DatasetQuery } from "metabase-types/api";
+import { createMockCard } from "metabase-types/api/mocks";
+
+import * as DataApp from "../../../data-app";
+import type { RowValue } from "../data-schema";
+
+import type { MetabaseQueryOptions, UseMetabaseQueryObjectResult } from ".";
+import {
+ avg,
+ breakout,
+ count,
+ filter,
+ orderBy,
+ sum,
+ useMetabaseQuery,
+ useMetabaseQueryObject,
+} from ".";
+
+jest.mock("embedding-sdk-package/hooks/private/use-lazy-selector", () => ({
+ useLazySelector: jest.fn(() => ({ status: "success" })),
+}));
+
+jest.mock(
+ "embedding-sdk-shared/hooks/use-metabase-provider-props-store",
+ () => ({
+ useMetabaseProviderPropsStore: jest.fn(),
+ }),
+);
+
+jest.mock("embedding-sdk-shared/hooks/use-sdk-loading-state", () => ({
+ useSdkLoadingState: jest.fn(() => ({ loadingState: "loaded" })),
+}));
+
+jest.mock("metabase/api", () => ({
+ cardApi: {
+ endpoints: {
+ getCard: { name: "getCard" },
+ getCardQueryMetadata: { name: "getCardQueryMetadata" },
+ },
+ },
+}));
+
+jest.mock("metabase/api/utils/run-rtk-endpoint", () => ({
+ runRtkEndpoint: jest.fn(() => Promise.resolve(undefined)),
+}));
+
+jest.mock("metabase/redux/tables", () => ({
+ fetchTableMetadata: jest.fn(({ id }) => ({
+ type: "fetchTableMetadata",
+ payload: id,
+ })),
+}));
+
+jest.mock("metabase/selectors/metadata", () => ({
+ getMetadataUnfiltered: jest.fn(),
+}));
+
+const mockFetchTableMetadata = jest.mocked(fetchTableMetadata);
+const mockGetMetadataUnfiltered = jest.mocked(getMetadataUnfiltered);
+const mockRunRtkEndpoint = jest.mocked(runRtkEndpoint);
+const mockUseLazySelector = jest.mocked(useLazySelector);
+const mockUseMetabaseProviderPropsStore = jest.mocked(
+ useMetabaseProviderPropsStore,
+);
+const mockUseSdkLoadingState = jest.mocked(useSdkLoadingState);
+
+const TEST_SCHEMA = {
+ tables: {
+ orders: {
+ type: "table",
+ id: 1,
+ fields: {
+ id: {
+ type: "column",
+ fieldId: 100,
+ tableId: 1,
+ name: "ID",
+ "source-name": "orders",
+ displayName: "ID",
+ jsType: "number",
+ },
+ createdAt: {
+ type: "column",
+ fieldId: 103,
+ tableId: 1,
+ name: "CREATED_AT",
+ "source-name": "orders",
+ displayName: "Created At",
+ jsType: "Date",
+ baseType: "type/DateTime",
+ },
+ amount: {
+ type: "column",
+ fieldId: 102,
+ tableId: 1,
+ name: "AMOUNT",
+ "source-name": "orders",
+ displayName: "Amount",
+ jsType: "number",
+ },
+ status: {
+ type: "column",
+ fieldId: 101,
+ tableId: 1,
+ name: "STATUS",
+ "source-name": "orders",
+ displayName: "Status",
+ jsType: "string",
+ },
+ productId: {
+ type: "column",
+ fieldId: 104,
+ tableId: 1,
+ name: "PRODUCT_ID",
+ displayName: "Product ID",
+ jsType: "number",
+ },
+ replacementProductId: {
+ type: "column",
+ fieldId: 105,
+ tableId: 1,
+ name: "REPLACEMENT_PRODUCT_ID",
+ displayName: "Replacement Product ID",
+ jsType: "number",
+ },
+ },
+ segments: {
+ completed: { type: "segment", id: 11, tableId: 1 },
+ },
+ measures: {
+ revenue: {
+ type: "measure",
+ id: 21,
+ tableId: 1,
+ columns: [{ name: "sum", displayName: "Sum", jsType: "number" }],
+ },
+ },
+ },
+ products: {
+ type: "table",
+ id: 2,
+ fields: {
+ price: {
+ type: "column",
+ fieldId: 201,
+ tableId: 2,
+ name: "PRICE",
+ "source-name": "products",
+ displayName: "Price",
+ jsType: "number",
+ },
+ name: {
+ type: "column",
+ fieldId: 202,
+ tableId: 2,
+ name: "NAME",
+ displayName: "Name",
+ jsType: "string",
+ },
+ },
+ segments: {
+ active: { type: "segment", id: 12, tableId: 2 },
+ },
+ measures: {
+ price: {
+ type: "measure",
+ id: 22,
+ tableId: 2,
+ columns: [{ name: "price", displayName: "Price", jsType: "number" }],
+ },
+ },
+ },
+ },
+ metrics: {
+ revenue: {
+ type: "metric",
+ id: 31,
+ name: "Revenue",
+ databaseId: 1,
+ sourceTableId: 1,
+ mappedTableIds: [1, 2],
+ columns: [{ name: "sum", displayName: "Revenue", jsType: "number" }],
+ dimensions: {
+ orders: {
+ amount: {
+ type: "column",
+ fieldId: 102,
+ tableId: 1,
+ name: "AMOUNT",
+ "source-name": "orders",
+ displayName: "Amount",
+ jsType: "number",
+ },
+ createdAt: {
+ type: "column",
+ fieldId: 103,
+ tableId: 1,
+ name: "CREATED_AT",
+ "source-name": "orders",
+ displayName: "Created At",
+ jsType: "Date",
+ baseType: "type/DateTime",
+ },
+ status: {
+ type: "column",
+ fieldId: 101,
+ tableId: 1,
+ name: "STATUS",
+ "source-name": "orders",
+ displayName: "Status",
+ jsType: "string",
+ },
+ product: {
+ type: "column",
+ fieldId: 202,
+ sourceFieldId: 104,
+ name: "NAME",
+ displayName: "Name",
+ jsType: "string",
+ },
+ },
+ },
+ },
+ sourceCardMetric: {
+ type: "metric",
+ id: 32,
+ name: "Stores with over 5 employees",
+ databaseId: 1,
+ sourceCardId: 1,
+ mappedTableIds: [1],
+ columns: [{ name: "count", displayName: "Count", jsType: "number" }],
+ dimensions: {
+ fields: {
+ count: {
+ type: "column",
+ name: "count",
+ displayName: "Count",
+ jsType: "number",
+ },
+ },
+ orders: {
+ status: {
+ type: "column",
+ fieldId: 101,
+ tableId: 1,
+ name: "STATUS",
+ "source-name": "orders",
+ displayName: "Status",
+ jsType: "string",
+ },
+ product: {
+ type: "column",
+ fieldId: 202,
+ sourceFieldId: 104,
+ name: "NAME",
+ displayName: "Name",
+ jsType: "string",
+ },
+ },
+ },
+ },
+ productRevenue: {
+ type: "metric",
+ id: 32,
+ name: "Product Revenue",
+ databaseId: 1,
+ sourceTableId: 2,
+ mappedTableIds: [2],
+ columns: [
+ {
+ name: "Product Revenue",
+ displayName: "Product Revenue",
+ jsType: "number",
+ },
+ ],
+ dimensions: {
+ products: {
+ price: {
+ type: "column",
+ fieldId: 201,
+ tableId: 2,
+ name: "PRICE",
+ displayName: "Price",
+ jsType: "number",
+ },
+ },
+ },
+ },
+ questionRevenue: {
+ type: "metric",
+ id: 33,
+ name: "Question Revenue",
+ databaseId: 1,
+ sourceCardId: 41,
+ mappedTableIds: [1],
+ columns: [
+ {
+ name: "Question Revenue",
+ displayName: "Question Revenue",
+ jsType: "number",
+ },
+ ],
+ dimensions: {
+ orders: {
+ createdAt: {
+ type: "column",
+ fieldId: 103,
+ tableId: 1,
+ name: "CREATED_AT",
+ displayName: "Created At",
+ jsType: "Date",
+ baseType: "type/DateTime",
+ },
+ },
+ },
+ },
+ },
+ questions: {
+ ordersQuestion: {
+ type: "card",
+ id: 41,
+ name: "Orders question",
+ columns: [
+ {
+ type: "column",
+ name: "STATUS",
+ displayName: "Status",
+ jsType: "string",
+ },
+ {
+ type: "column",
+ name: "AMOUNT",
+ displayName: "Amount",
+ jsType: "number",
+ },
+ {
+ type: "column",
+ name: "CREATED_AT",
+ displayName: "Created At",
+ jsType: "Date",
+ },
+ ],
+ },
+ },
+} as const;
+
+type OrdersTable = (typeof TEST_SCHEMA)["tables"]["orders"];
+type OrdersQuestion = (typeof TEST_SCHEMA)["questions"]["ordersQuestion"];
+
+const TEST_METADATA = {
+ databases: {
+ 1: {
+ id: 1,
+ name: "Test Database",
+ features: ["basic-aggregations", "binning", "expressions"],
+ },
+ },
+ tables: {
+ 1: { id: 1, db_id: 1, name: "orders", display_name: "Orders" },
+ 2: { id: 2, db_id: 1, name: "products", display_name: "Products" },
+ },
+ fields: {
+ 100: {
+ id: 100,
+ table_id: 1,
+ name: "ID",
+ display_name: "ID",
+ base_type: "type/Integer",
+ effective_type: "type/Integer",
+ },
+ 101: {
+ id: 101,
+ table_id: 1,
+ name: "STATUS",
+ display_name: "Status",
+ base_type: "type/Text",
+ effective_type: "type/Text",
+ },
+ 102: {
+ id: 102,
+ table_id: 1,
+ name: "AMOUNT",
+ display_name: "Amount",
+ base_type: "type/Float",
+ effective_type: "type/Float",
+ },
+ 103: {
+ id: 103,
+ table_id: 1,
+ name: "CREATED_AT",
+ display_name: "Created At",
+ base_type: "type/DateTime",
+ effective_type: "type/DateTime",
+ },
+ 104: {
+ id: 104,
+ table_id: 1,
+ name: "PRODUCT_ID",
+ display_name: "Product ID",
+ base_type: "type/Integer",
+ effective_type: "type/Integer",
+ semantic_type: "type/FK",
+ fk_target_field_id: 200,
+ },
+ 105: {
+ id: 105,
+ table_id: 1,
+ name: "REPLACEMENT_PRODUCT_ID",
+ display_name: "Replacement Product ID",
+ base_type: "type/Integer",
+ effective_type: "type/Integer",
+ semantic_type: "type/FK",
+ fk_target_field_id: 200,
+ },
+ 200: {
+ id: 200,
+ table_id: 2,
+ name: "ID",
+ display_name: "ID",
+ base_type: "type/Integer",
+ effective_type: "type/Integer",
+ semantic_type: "type/PK",
+ },
+ 201: {
+ id: 201,
+ table_id: 2,
+ name: "PRICE",
+ display_name: "Price",
+ base_type: "type/Float",
+ effective_type: "type/Float",
+ },
+ 202: {
+ id: 202,
+ table_id: 2,
+ name: "NAME",
+ display_name: "Name",
+ base_type: "type/Text",
+ effective_type: "type/Text",
+ },
+ },
+ segments: {
+ 11: { id: 11, table_id: 1, name: "Completed" },
+ 12: { id: 12, table_id: 2, name: "Active" },
+ },
+ measures: {
+ 21: {
+ id: 21,
+ name: "Revenue",
+ table_id: 1,
+ definition: {
+ type: "query",
+ database: 1,
+ query: {
+ "source-table": 1,
+ aggregation: [["count"]],
+ },
+ },
+ },
+ 22: {
+ id: 22,
+ name: "Price",
+ table_id: 2,
+ definition: {
+ type: "query",
+ database: 1,
+ query: {
+ "source-table": 2,
+ aggregation: [["count"]],
+ },
+ },
+ },
+ },
+ questions: {
+ 41: createMockCard({
+ id: 41,
+ name: "Orders question",
+ dataset_query: {
+ type: "query",
+ database: 1,
+ query: {
+ "source-table": 1,
+ },
+ },
+ }),
+ 31: createMockCard({
+ id: 31,
+ name: "Revenue",
+ type: "metric",
+ dataset_query: {
+ type: "query",
+ database: 1,
+ query: {
+ "source-table": 1,
+ aggregation: [["sum", ["field", 102, null]]],
+ },
+ },
+ }),
+ 32: createMockCard({
+ id: 32,
+ name: "Product Revenue",
+ type: "metric",
+ dataset_query: {
+ type: "query",
+ database: 1,
+ query: {
+ "source-table": 2,
+ aggregation: [["sum", ["field", 201, null]]],
+ },
+ },
+ }),
+ },
+};
+
+const createMockStore = (): SdkStore =>
+ // A real `getSdkStore()` pulls in reducers this spec's `metabase/api` mock can't
+ // satisfy; only `dispatch` and `getState` are reached, and both land in mocks.
+ ({
+ dispatch: jest.fn((action) => Promise.resolve(action)),
+ getState: jest.fn(() => ({})),
+ }) as unknown as SdkStore;
+
+type MbqlStage = Record<string, unknown>;
+
+const mbqlQuery = (stages: MbqlStage[]): DatasetQuery =>
+ // `DatasetQuery` is opaque, so one can't be written as a literal.
+ ({
+ "lib/type": "mbql/query",
+ database: 1,
+ stages,
+ }) as unknown as DatasetQuery;
+
+const stagesOf = (query: DatasetQuery): MbqlStage[] =>
+ // ...nor its stages read.
+ (query as unknown as { stages: MbqlStage[] }).stages;
+
+const TEST_DATASET_QUERY = mbqlQuery([{ "source-table": 1 }]);
+
+const mockPropsStore = (reduxStore: SdkStore) =>
+ mockUseMetabaseProviderPropsStore.mockReturnValue({
+ state: { internalProps: { reduxStore }, props: null },
+ store: ensureMetabaseProviderPropsStore(),
+ });
+
+const stubSdkBundle = (
+ exports: Partial<MetabaseEmbeddingSdkBundleExports>,
+): void => {
+ window.METABASE_EMBEDDING_SDK_BUNDLE =
+ // The global is typed as the whole bundle; a test needs one or two functions.
+ exports as MetabaseEmbeddingSdkBundleExports;
+};
+
+const LOADED_SDK_STATE: ReturnType<typeof useSdkLoadingState> = {
+ loadingState: SdkLoadingState.Loaded,
+ loadingError: null,
+ isInitial: false,
+ isLoading: false,
+ isLoaded: true,
+ isInitialized: false,
+ isError: false,
+ isNotStartedLoading: false,
+};
+
+function createDeferred<TValue>() {
+ let resolve!: (value: TValue) => void;
+ let reject!: (error: unknown) => void;
+ const promise = new Promise<TValue>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+
+ return { promise, resolve, reject };
+}
+
+const _validTableQuery = {
+ source: TEST_SCHEMA.tables.orders,
+ fields: [
+ TEST_SCHEMA.tables.orders.fields.id,
+ TEST_SCHEMA.tables.orders.fields.status,
+ ],
+ filters: [
+ TEST_SCHEMA.tables.orders.segments.completed,
+ filter(TEST_SCHEMA.tables.orders.fields.status, "=", "paid"),
+ ],
+ aggregations: [
+ TEST_SCHEMA.tables.orders.measures.revenue,
+ sum(TEST_SCHEMA.tables.orders.fields.amount),
+ ],
+ breakouts: [
+ breakout(TEST_SCHEMA.tables.orders.fields.createdAt, { unit: "month" }),
+ ],
+ orderBys: [
+ orderBy(TEST_SCHEMA.tables.orders.fields.createdAt, "desc", {
+ unit: "month",
+ }),
+ ],
+ limit: 100,
+} satisfies MetabaseQueryOptions<OrdersTable>;
+
+const _invalidCrossTableSegmentQuery = {
+ source: TEST_SCHEMA.tables.orders,
+ filters: [
+ // @ts-expect-error segments must belong to the source table
+ TEST_SCHEMA.tables.products.segments.active,
+ ],
+} satisfies MetabaseQueryOptions<OrdersTable>;
+
+const _invalidCrossTableMeasureQuery = {
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [
+ // @ts-expect-error measures must belong to the source table
+ TEST_SCHEMA.tables.products.measures.price,
+ ],
+} satisfies MetabaseQueryOptions<OrdersTable>;
+
+const _invalidCrossTableFieldQuery = {
+ source: TEST_SCHEMA.tables.orders,
+ fields: [
+ // @ts-expect-error fields must belong to the source table
+ TEST_SCHEMA.tables.products.fields.price,
+ ],
+} satisfies MetabaseQueryOptions<OrdersTable>;
+
+const _validTableQueryWithMetricAggregation = {
+ source: TEST_SCHEMA.tables.orders,
+ filters: [
+ TEST_SCHEMA.tables.orders.segments.completed,
+ filter(TEST_SCHEMA.metrics.revenue.dimensions.orders.status, "=", "paid"),
+ ],
+ aggregations: [
+ TEST_SCHEMA.metrics.revenue,
+ TEST_SCHEMA.tables.orders.measures.revenue,
+ sum(TEST_SCHEMA.metrics.revenue.dimensions.orders.amount),
+ ],
+ breakouts: [
+ breakout(TEST_SCHEMA.metrics.revenue.dimensions.orders.createdAt, {
+ unit: "month",
+ }),
+ ],
+ orderBys: [
+ orderBy(TEST_SCHEMA.metrics.revenue.dimensions.orders.createdAt, "desc", {
+ unit: "month",
+ }),
+ ],
+ limit: 100,
+} satisfies MetabaseQueryOptions<OrdersTable>;
+
+const _validTableQueryWithJoinedMetricBreakout = {
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [TEST_SCHEMA.metrics.revenue],
+ breakouts: [breakout(TEST_SCHEMA.metrics.revenue.dimensions.orders.product)],
+} satisfies MetabaseQueryOptions<OrdersTable>;
+
+const _validSavedQuestionQuery = {
+ source: TEST_SCHEMA.questions.ordersQuestion,
+} satisfies MetabaseQueryOptions<OrdersQuestion>;
+
+const _invalidSavedQuestionClauseQuery = {
+ source: TEST_SCHEMA.questions.ordersQuestion,
+
+ // @ts-expect-error saved question queries only support source and enabled
+ fields: [TEST_SCHEMA.questions.ordersQuestion.columns[0]],
+} satisfies MetabaseQueryOptions<OrdersQuestion>;
+
+const _validCardQuery = {
+ query: {
+ "lib/type": "mbql/query",
+ database: 1,
+ stages: [],
+ },
+} satisfies MetabaseCard;
+
+// Only this value's *type* is used: the fixtures below typecheck, they never run.
+const hookResult = {} as UseMetabaseQueryObjectResult;
+const _validHookResultCard = {
+ query: hookResult.query,
+} satisfies MetabaseCard;
+
+const _invalidHookResultCard = {
+ // @ts-expect-error pass useMetabaseQueryObject(...).query, not the whole hook result
+ query: hookResult,
+} satisfies MetabaseCard;
+
+const _invalidCrossTableMetricAggregationQuery = {
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [
+ // @ts-expect-error metric aggregations must belong to the source table
+ TEST_SCHEMA.metrics.productRevenue,
+ ],
+} satisfies MetabaseQueryOptions<OrdersTable>;
+
+const _invalidIdOnlyMetricAggregationQuery = {
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [
+ // @ts-expect-error metric aggregations must include source table metadata
+ { type: "metric", id: 31 },
+ ],
+} satisfies MetabaseQueryOptions<OrdersTable>;
+
+const _invalidSourceCardMetricAggregationQuery = {
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [
+ // @ts-expect-error source-card metric aggregations need a saved question source
+ TEST_SCHEMA.metrics.questionRevenue,
+ ],
+} satisfies MetabaseQueryOptions<OrdersTable>;
+
+const _invalidMetricSourceQuery = {
+ // @ts-expect-error Metrics must be used in aggregations, not as query sources
+ source: TEST_SCHEMA.metrics.revenue,
+} satisfies MetabaseQueryOptions;
+
+function TypeFixtures() {
+ const selectedFieldsResult = useMetabaseQuery({
+ source: TEST_SCHEMA.tables.orders,
+ fields: [TEST_SCHEMA.tables.orders.fields.id],
+ });
+
+ const selectedFieldValue: number | null | undefined =
+ selectedFieldsResult.data?.rows[0]?.ID;
+
+ void selectedFieldValue;
+
+ const selectedFieldsQuery = {
+ source: TEST_SCHEMA.tables.orders,
+ fields: [
+ TEST_SCHEMA.tables.orders.fields.id,
+ TEST_SCHEMA.tables.orders.fields.status,
+ ],
+ } satisfies MetabaseQueryOptions<OrdersTable>;
+
+ const selectedFieldsQueryResult = useMetabaseQuery(selectedFieldsQuery);
+
+ const selectedQueryFieldValue: string | null | undefined =
+ selectedFieldsQueryResult.data?.rows[0]?.STATUS;
+
+ void selectedQueryFieldValue;
+
+ const scalarAggregationResult = useMetabaseQuery({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [sum(TEST_SCHEMA.tables.orders.fields.amount)],
+ });
+
+ const scalarAggregationValue: RowValue | undefined =
+ scalarAggregationResult.data?.rows[0]?.sum;
+
+ void scalarAggregationValue;
+
+ // @ts-expect-error aggregation result rows should not include source fields
+ void scalarAggregationResult.data?.rows[0]?.amount;
+
+ const metricResult = useMetabaseQuery({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [TEST_SCHEMA.metrics.revenue],
+ });
+
+ const metricAggregationValue = metricResult.data?.rows[0];
+
+ void metricAggregationValue;
+
+ // @ts-expect-error aggregation result rows should not include source fields
+ void metricResult.data?.rows[0]?.status;
+
+ const groupedMetricResult = useMetabaseQuery<OrdersTable>({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [TEST_SCHEMA.metrics.revenue],
+ breakouts: [
+ breakout(TEST_SCHEMA.metrics.revenue.dimensions.orders.createdAt, {
+ unit: "month",
+ }),
+ ],
+ });
+
+ const groupedMetricBreakoutValue: string | Date | null | undefined =
+ groupedMetricResult.data?.rows[0]?.CREATED_AT;
+
+ void groupedMetricBreakoutValue;
+
+ // @ts-expect-error result row keys use returned column names, not schema object keys
+ void groupedMetricResult.data?.rows[0]?.createdAt;
+
+ const sortKey: "amount" | "createdAt" = "createdAt";
+
+ type OrdersField =
+ (typeof TEST_SCHEMA.tables.orders.fields)[keyof typeof TEST_SCHEMA.tables.orders.fields];
+
+ const sortFields = {
+ amount: TEST_SCHEMA.tables.orders.fields.amount,
+ createdAt: TEST_SCHEMA.tables.orders.fields.createdAt,
+ } satisfies Record<string, OrdersField>;
+
+ useMetabaseQuery({
+ source: TEST_SCHEMA.tables.orders,
+ orderBys: [orderBy(sortFields[sortKey], "desc")],
+ });
+
+ // @ts-expect-error grouped queries must include an explicit aggregation
+ useMetabaseQuery<OrdersTable>({
+ source: TEST_SCHEMA.tables.orders,
+ breakouts: [
+ breakout(TEST_SCHEMA.tables.orders.fields.createdAt, { unit: "month" }),
+ ],
+ });
+
+ return null;
+}
+
+void TypeFixtures;
+
+describe("resolveDatasetQuery", () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockRunRtkEndpoint.mockResolvedValue(undefined);
+ mockGetMetadataUnfiltered.mockReturnValue(
+ // `Metadata` is a class; the fixture is the plain shape read out of it.
+ TEST_METADATA as unknown as ReturnType<typeof getMetadataUnfiltered>,
+ );
+ mockUseLazySelector.mockReturnValue({ status: "success" });
+ mockUseSdkLoadingState.mockReturnValue(LOADED_SDK_STATE);
+ mockPropsStore(createMockStore());
+ window.METABASE_EMBEDDING_SDK_BUNDLE = undefined;
+ });
+
+ it("exports the table query DSL from the data-app entrypoint", () => {
+ expect(DataApp).toMatchObject({
+ aggregations: {
+ avg: expect.any(Function),
+ count: expect.any(Function),
+ distinct: expect.any(Function),
+ max: expect.any(Function),
+ median: expect.any(Function),
+ min: expect.any(Function),
+ sum: expect.any(Function),
+ },
+ breakout: expect.any(Function),
+ filter: expect.any(Function),
+ orderBy: expect.any(Function),
+ useMetabaseQuery: expect.any(Function),
+ useMetabaseQueryObject: expect.any(Function),
+ });
+ expect(DataApp).not.toHaveProperty("count");
+ expect(DataApp).not.toHaveProperty("sum");
+ expect(DataApp).not.toHaveProperty("resolveDatasetQuery");
+ });
+
+ it("loads table metadata and passes the public source DSL through Lib.createTestQuery", async () => {
+ const store = createMockStore();
+
+ const datasetQuery = await resolveDatasetQueryInBundle(store)({
+ source: TEST_SCHEMA.tables.orders,
+ fields: [
+ TEST_SCHEMA.tables.orders.fields.id,
+ TEST_SCHEMA.tables.orders.fields.status,
+ ],
+ filters: [
+ TEST_SCHEMA.tables.orders.segments.completed,
+ filter(TEST_SCHEMA.tables.orders.fields.status, "=", "paid"),
+ ],
+ aggregations: [count(), sum(TEST_SCHEMA.tables.orders.fields.amount)],
+ breakouts: [
+ breakout(TEST_SCHEMA.tables.orders.fields.createdAt, { unit: "month" }),
+ ],
+ orderBys: [
+ orderBy(TEST_SCHEMA.tables.orders.fields.createdAt, "desc", {
+ unit: "month",
+ }),
+ ],
+ limit: 100,
+ });
+
+ expect(mockFetchTableMetadata).toHaveBeenCalledWith({ id: 1 });
+
+ expect(store.dispatch).toHaveBeenCalledWith({
+ type: "fetchTableMetadata",
+ payload: 1,
+ });
+
+ expect(mockGetMetadataUnfiltered).toHaveBeenCalledWith({});
+
+ expect(datasetQuery).toMatchObject({
+ "lib/type": "mbql/query",
+ database: 1,
+ stages: [
+ {
+ "lib/type": "mbql.stage/mbql",
+ "source-table": 1,
+ fields: [
+ ["field", expect.anything(), 100],
+ ["field", expect.anything(), 101],
+ ],
+ filters: [
+ ["segment", expect.anything(), 11],
+ ["=", expect.anything(), ["field", expect.anything(), 101], "paid"],
+ ],
+ aggregation: [
+ ["count", expect.anything()],
+ ["sum", expect.anything(), ["field", expect.anything(), 102]],
+ ],
+ breakout: [
+ [
+ "field",
+ expect.objectContaining({ "temporal-unit": "month" }),
+ 103,
+ ],
+ ],
+ "order-by": [
+ [
+ "desc",
+ expect.anything(),
+ [
+ "field",
+ expect.objectContaining({ "temporal-unit": "month" }),
+ 103,
+ ],
+ ],
+ ],
+ limit: 100,
+ },
+ ],
+ });
+ });
+
+ it("passes generated table Measures to Lib.createTestQuery measure aggregations", async () => {
+ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [TEST_SCHEMA.tables.orders.measures.revenue],
+ });
+
+ expect(stagesOf(datasetQuery)[0].aggregation).toEqual([
+ ["measure", expect.anything(), 21],
+ ]);
+ });
+
+ it("accepts id-only table source references", async () => {
+ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())({
+ source: { type: "table", id: 1 },
+ fields: [TEST_SCHEMA.tables.orders.fields.id],
+ });
+
+ expect(datasetQuery).toMatchObject({
+ database: 1,
+ stages: [
+ {
+ "source-table": 1,
+ fields: [["field", expect.anything(), 100]],
+ },
+ ],
+ });
+ });
+
+ it("loads metric aggregation metadata and passes the public table source DSL through Lib.createTestQuery", async () => {
+ const store = createMockStore();
+
+ const datasetQuery = await resolveDatasetQueryInBundle(store)({
+ source: TEST_SCHEMA.tables.orders,
+ filters: [
+ TEST_SCHEMA.tables.orders.segments.completed,
+ filter(
+ TEST_SCHEMA.metrics.revenue.dimensions.orders.status,
+ "=",
+ "paid",
+ ),
+ ],
+ aggregations: [
+ TEST_SCHEMA.metrics.revenue,
+ count(),
+ sum(TEST_SCHEMA.metrics.revenue.dimensions.orders.amount),
+ TEST_SCHEMA.tables.orders.measures.revenue,
+ ],
+ breakouts: [
+ breakout(TEST_SCHEMA.metrics.revenue.dimensions.orders.createdAt, {
+ unit: "month",
+ }),
+ ],
+ limit: 100,
+ });
+
+ expect(mockFetchTableMetadata).toHaveBeenCalledWith({ id: 1 });
+
+ expect(mockRunRtkEndpoint).toHaveBeenNthCalledWith(
+ 1,
+ { id: 31 },
+ store.dispatch,
+ cardApi.endpoints.getCard,
+ { forceRefetch: false },
+ );
+
+ expect(mockRunRtkEndpoint).toHaveBeenNthCalledWith(
+ 2,
+ 31,
+ store.dispatch,
+ cardApi.endpoints.getCardQueryMetadata,
+ { forceRefetch: false },
+ );
+
+ expect(datasetQuery).toMatchObject({
+ "lib/type": "mbql/query",
+ database: 1,
+ stages: [
+ {
+ "lib/type": "mbql.stage/mbql",
+ "source-table": 1,
+ filters: [
+ ["segment", expect.anything(), 11],
+ ["=", expect.anything(), ["field", expect.anything(), 101], "paid"],
+ ],
+ aggregation: [
+ ["metric", expect.anything(), 31],
+ ["count", expect.anything()],
+ ["sum", expect.anything(), ["field", expect.anything(), 102]],
+ ["measure", expect.anything(), 21],
+ ],
+ breakout: [
+ [
+ "field",
+ expect.objectContaining({ "temporal-unit": "month" }),
+ 103,
+ ],
+ ],
+ limit: 100,
+ },
+ ],
+ });
+ });
+
+ it("builds metric queries with FK-joined dimension breakouts", async () => {
+ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [TEST_SCHEMA.metrics.revenue],
+ breakouts: [
+ breakout(TEST_SCHEMA.metrics.revenue.dimensions.orders.product),
+ ],
+ });
+
+ expect(datasetQuery).toMatchObject({
+ database: 1,
+ stages: [
+ {
+ "source-table": 1,
+ aggregation: [["metric", expect.anything(), 31]],
+ breakout: [
+ ["field", expect.objectContaining({ "source-field": 104 }), 202],
+ ],
+ },
+ ],
+ });
+ });
+
+ it("passes generated metric dimension orderBys through Lib.createTestQuery", async () => {
+ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [TEST_SCHEMA.metrics.revenue],
+ breakouts: [
+ breakout(TEST_SCHEMA.metrics.revenue.dimensions.orders.createdAt, {
+ unit: "month",
+ }),
+ ],
+ orderBys: [
+ orderBy(
+ TEST_SCHEMA.metrics.revenue.dimensions.orders.createdAt,
+ "desc",
+ { unit: "month" },
+ ),
+ ],
+ limit: 12,
+ });
+
+ expect(datasetQuery).toMatchObject({
+ stages: [
+ {
+ "source-table": 1,
+ aggregation: [["metric", expect.anything(), 31]],
+ breakout: [
+ [
+ "field",
+ expect.objectContaining({ "temporal-unit": "month" }),
+ 103,
+ ],
+ ],
+ "order-by": [
+ [
+ "desc",
+ expect.anything(),
+ [
+ "field",
+ expect.objectContaining({ "temporal-unit": "month" }),
+ 103,
+ ],
+ ],
+ ],
+ limit: 12,
+ },
+ ],
+ });
+ });
+
+ it("loads saved question metadata and passes the question source through Lib.createTestQuery", async () => {
+ const store = createMockStore();
+
+ const datasetQuery = await resolveDatasetQueryInBundle(store)({
+ source: TEST_SCHEMA.questions.ordersQuestion,
+ });
+
+ expect(mockFetchTableMetadata).not.toHaveBeenCalled();
+
+ expect(mockRunRtkEndpoint).toHaveBeenNthCalledWith(
+ 1,
+ { id: 41 },
+ store.dispatch,
+ cardApi.endpoints.getCard,
+ { forceRefetch: false },
+ );
+
+ expect(mockRunRtkEndpoint).toHaveBeenNthCalledWith(
+ 2,
+ 41,
+ store.dispatch,
+ cardApi.endpoints.getCardQueryMetadata,
+ { forceRefetch: false },
+ );
+
+ expect(datasetQuery).toMatchObject({
+ "lib/type": "mbql/query",
+ database: 1,
+ stages: [
+ {
+ "lib/type": "mbql.stage/mbql",
+ "source-card": 41,
+ },
+ ],
+ });
+ });
+
+ it("passes aggregation result orderBys through Lib.createTestQuery", async () => {
+ const avgAmount = avg(TEST_SCHEMA.tables.orders.fields.amount);
+
+ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [avgAmount],
+ breakouts: [breakout(TEST_SCHEMA.tables.orders.fields.status)],
+ orderBys: [orderBy(avgAmount, "desc")],
+ limit: 15,
+ });
+
+ expect(datasetQuery).toMatchObject({
+ stages: [
+ {
+ aggregation: [
+ ["avg", expect.anything(), ["field", expect.anything(), 102]],
+ ],
+ breakout: [["field", expect.anything(), 101]],
+ "order-by": [
+ [
+ "desc",
+ expect.anything(),
+ ["aggregation", expect.anything(), expect.anything()],
+ ],
+ ],
+ limit: 15,
+ },
+ ],
+ });
+ });
+
+ it("passes metric aggregation result orderBys through Lib.createTestQuery", async () => {
+ const avgAmount = avg(TEST_SCHEMA.metrics.revenue.dimensions.orders.amount);
+
+ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [TEST_SCHEMA.metrics.revenue, avgAmount],
+ breakouts: [
+ breakout(TEST_SCHEMA.metrics.revenue.dimensions.orders.status),
+ ],
+ orderBys: [orderBy(avgAmount, "desc")],
+ limit: 15,
+ });
+
+ expect(datasetQuery).toMatchObject({
+ stages: [
+ {
+ aggregation: [
+ ["metric", expect.anything(), 31],
+ ["avg", expect.anything(), ["field", expect.anything(), 102]],
+ ],
+ breakout: [["field", expect.anything(), 101]],
+ "order-by": [
+ [
+ "desc",
+ expect.anything(),
+ ["aggregation", expect.anything(), expect.anything()],
+ ],
+ ],
+ limit: 15,
+ },
+ ],
+ });
+ });
+
+ it("passes metric aggregation orderBys through Lib.createTestQuery", async () => {
+ const datasetQuery = await resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [TEST_SCHEMA.metrics.revenue],
+ breakouts: [
+ breakout(TEST_SCHEMA.metrics.revenue.dimensions.orders.status),
+ ],
+ orderBys: [orderBy(TEST_SCHEMA.metrics.revenue, "desc")],
+ limit: 15,
+ });
+
+ expect(datasetQuery).toMatchObject({
+ stages: [
+ {
+ aggregation: [["metric", expect.anything(), 31]],
+ breakout: [["field", expect.anything(), 101]],
+ "order-by": [
+ [
+ "desc",
+ expect.anything(),
+ ["aggregation", expect.anything(), expect.anything()],
+ ],
+ ],
+ limit: 15,
+ },
+ ],
+ });
+ });
+
+ it("rejects invalid limits with a clear error message", async () => {
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ limit: 0,
+ }),
+ ).rejects.toThrow("Table query limit must be a positive integer.");
+ });
+
+ it("rejects cross-table query clauses with clear error messages", async () => {
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ fields: [TEST_SCHEMA.tables.products.fields.price],
+ }),
+ ).rejects.toThrow(
+ "Table query fields must belong to source table 1, but received table id 2.",
+ );
+
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ filters: [filter(TEST_SCHEMA.tables.products.fields.price, "=", 10)],
+ }),
+ ).rejects.toThrow(
+ "Table query filters must belong to source table 1, but received table id 2.",
+ );
+
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [sum(TEST_SCHEMA.tables.products.fields.price)],
+ }),
+ ).rejects.toThrow(
+ "Table query aggregations must belong to source table 1, but received table id 2.",
+ );
+
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ breakouts: [TEST_SCHEMA.tables.products.fields.price],
+ }),
+ ).rejects.toThrow(
+ "Table query breakouts must belong to source table 1, but received table id 2.",
+ );
+
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ orderBys: [orderBy(TEST_SCHEMA.tables.products.fields.price, "desc")],
+ }),
+ ).rejects.toThrow(
+ "Table query orderBys must belong to source table 1, but received table id 2.",
+ );
+
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [avg(TEST_SCHEMA.tables.orders.fields.amount)],
+ breakouts: [breakout(TEST_SCHEMA.tables.orders.fields.status)],
+ orderBys: [orderBy(TEST_SCHEMA.tables.orders.fields.amount, "desc")],
+ }),
+ ).rejects.toThrow(
+ "Table query orderBys for grouped queries must use query breakouts or aggregations included in the query.",
+ );
+
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ breakouts: [
+ breakout(TEST_SCHEMA.tables.orders.fields.createdAt, {
+ unit: "month",
+ }),
+ ],
+ orderBys: [
+ orderBy(TEST_SCHEMA.tables.orders.fields.createdAt, "desc", {
+ unit: "year",
+ }),
+ ],
+ }),
+ ).rejects.toThrow(
+ "Table query orderBys for grouped queries must use query breakouts or aggregations included in the query.",
+ );
+ });
+
+ it("rejects cross-table metric aggregations with clear error messages", async () => {
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [TEST_SCHEMA.metrics.productRevenue],
+ }),
+ ).rejects.toThrow(
+ "Table query metric aggregations must belong to source table 1, but received mapped table ids 2.",
+ );
+ });
+
+ it("rejects metric aggregations without source table metadata", async () => {
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [{ type: "metric", id: 31 }],
+ }),
+ ).rejects.toThrow(
+ "Table query metric aggregations must include source table metadata.",
+ );
+ });
+
+ it("rejects source-card metric aggregations under table sources", async () => {
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.tables.orders,
+ aggregations: [TEST_SCHEMA.metrics.questionRevenue],
+ }),
+ ).rejects.toThrow(
+ "Table query metric aggregations cannot use source-card Metrics. Use a saved question source for source-card Metrics.",
+ );
+ });
+
+ it("rejects unsupported saved question query clauses with a clear error message", async () => {
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.questions.ordersQuestion,
+ fields: [TEST_SCHEMA.questions.ordersQuestion.columns[0]],
+ }),
+ ).rejects.toThrow(
+ "Saved question queries only support source and enabled, but received fields.",
+ );
+
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.questions.ordersQuestion,
+ limit: 10,
+ }),
+ ).rejects.toThrow(
+ "Saved question queries only support source and enabled, but received limit.",
+ );
+
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ source: TEST_SCHEMA.questions.ordersQuestion,
+ aggregations: [avg(TEST_SCHEMA.questions.ordersQuestion.columns[1])],
+ }),
+ ).rejects.toThrow(
+ "Saved question queries only support source and enabled, but received aggregations.",
+ );
+ });
+
+ it("rejects metric sources with a clear error message", async () => {
+ await expect(
+ resolveDatasetQueryInBundle(createMockStore())({
+ // @ts-expect-error a metric is not a valid query source
+ source: TEST_SCHEMA.metrics.revenue,
+ }),
+ ).rejects.toThrow(
+ 'Query object creation requires a source reference like `{ type: "table", id }` or `{ type: "card", id }`.',
+ );
+ });
+});
+
+describe("useMetabaseQueryObject", () => {
+ const query = {
+ source: TEST_SCHEMA.tables.orders,
+ limit: 10,
+ };
+
+ it("returns a loading state until async query creation resolves", async () => {
+ const deferred = createDeferred<DatasetQuery>();
+ const resolveDatasetQuery = jest.fn(() => jest.fn(() => deferred.promise));
+ stubSdkBundle({ resolveDatasetQuery });
+
+ const { result } = renderHook(() => useMetabaseQueryObject(query));
+
+ expect(result.current).toEqual({
+ query: null,
+ error: null,
+ isLoading: true,
+ });
+
+ deferred.resolve(TEST_DATASET_QUERY);
+
+ await waitFor(() =>
+ expect(result.current).toEqual({
+ query: TEST_DATASET_QUERY,
+ error: null,
+ isLoading: false,
+ }),
+ );
+ });
+
+ it("returns query creation errors instead of swallowing them", async () => {
+ const error = new Error("No column found");
+ const resolveDatasetQuery = jest.fn(() =>
+ jest.fn(() => Promise.reject(error)),
+ );
+ stubSdkBundle({ resolveDatasetQuery });
+
+ const { result } = renderHook(() => useMetabaseQueryObject(query));
+
+ await waitFor(() =>
+ expect(result.current).toEqual({
+ query: null,
+ error,
+ isLoading: false,
+ }),
+ );
+ });
+
+ it("waits for login before resolving the query", async () => {
+ const resolveDatasetQuery = jest.fn(() =>
+ jest.fn(() => Promise.resolve(TEST_DATASET_QUERY)),
+ );
+ stubSdkBundle({ resolveDatasetQuery });
+ mockUseLazySelector.mockReturnValue({ status: "loading" });
+
+ const { result, rerender } = renderHook(() =>
+ useMetabaseQueryObject(query),
+ );
+
+ expect(result.current).toEqual({
+ query: null,
+ error: null,
+ isLoading: true,
+ });
+ expect(resolveDatasetQuery).not.toHaveBeenCalled();
+
+ mockUseLazySelector.mockReturnValue({ status: "success" });
+ rerender();
+
+ await waitFor(() => {
+ expect(resolveDatasetQuery).toHaveBeenCalled();
+ expect(result.current).toEqual({
+ query: TEST_DATASET_QUERY,
+ error: null,
+ isLoading: false,
+ });
+ });
+ });
+
+ it("does not expose stale query results after the input changes", async () => {
+ const firstDeferred = createDeferred<DatasetQuery>();
+ const secondDeferred = createDeferred<DatasetQuery>();
+
+ const firstQuery = {
+ source: TEST_SCHEMA.tables.orders,
+ limit: 10,
+ };
+
+ const secondQuery = {
+ source: TEST_SCHEMA.tables.orders,
+ limit: 20,
+ };
+
+ const secondDatasetQuery = mbqlQuery([{ "source-table": 1, limit: 20 }]);
+
+ // Which deferred a call gets is decided by the only field that differs.
+ const resolveDatasetQuery = jest.fn(
+ () => (input: QueryInput) =>
+ "limit" in input && input.limit === 10
+ ? firstDeferred.promise
+ : secondDeferred.promise,
+ );
+
+ stubSdkBundle({ resolveDatasetQuery });
+
+ const { result, rerender } = renderHook(
+ ({ currentQuery }) => useMetabaseQueryObject(currentQuery),
+ { initialProps: { currentQuery: firstQuery } },
+ );
+
+ rerender({ currentQuery: secondQuery });
+ firstDeferred.resolve(TEST_DATASET_QUERY);
+
+ expect(result.current).toEqual({
+ query: null,
+ error: null,
+ isLoading: true,
+ });
+
+ secondDeferred.resolve(secondDatasetQuery);
+
+ await waitFor(() =>
+ expect(result.current).toEqual({
+ query: secondDatasetQuery,
+ error: null,
+ isLoading: false,
+ }),
+ );
+ });
+});
+
+describe("useMetabaseQuery", () => {
+ it("ignores a stale response after the query changes", async () => {
+ const firstQuery = {
+ source: TEST_SCHEMA.tables.orders,
+ limit: 10,
+ };
+
+ const secondQuery = {
+ source: TEST_SCHEMA.tables.orders,
+ limit: 20,
+ };
+
+ const firstDatasetQuery = mbqlQuery([{ "source-table": 1, limit: 10 }]);
+ const secondDatasetQuery = mbqlQuery([{ "source-table": 1, limit: 20 }]);
+
+ const firstResponse = createDeferred<QueryDatasetResult>();
+ const secondResponse = createDeferred<QueryDatasetResult>();
+
+ const runDatasetQuery = jest.fn(
+ ({ datasetQuery }: { datasetQuery: DatasetQuery }) =>
+ datasetQuery === firstDatasetQuery
+ ? firstResponse.promise
+ : secondResponse.promise,
+ );
+
+ const resolveDatasetQuery = jest.fn(
+ () => (input: QueryInput) =>
+ Promise.resolve(
+ "limit" in input && input.limit === 10
+ ? firstDatasetQuery
+ : secondDatasetQuery,
+ ),
+ );
+
+ stubSdkBundle({
+ resolveDatasetQuery,
+ queryDataset: jest.fn(() => runDatasetQuery),
+ });
+
+ const { result, rerender } = renderHook(
+ ({ currentQuery }) => useMetabaseQuery(currentQuery),
+ { initialProps: { currentQuery: firstQuery } },
+ );
+
+ await waitFor(() => expect(runDatasetQuery).toHaveBeenCalledTimes(1));
+ rerender({ currentQuery: secondQuery });
+
+ await waitFor(() => expect(runDatasetQuery).toHaveBeenCalledTimes(2));
+
+ await act(async () => {
+ firstResponse.resolve({
+ rowCount: 1,
+ runningTime: 1,
+ columns: [],
+ rows: [],
+ });
+ await firstResponse.promise;
+ });
+
+ expect(result.current).toMatchObject({
+ data: null,
+ error: null,
+ isLoading: true,
+ });
+
+ await act(async () => {
+ secondResponse.resolve({
+ rowCount: 2,
+ runningTime: 2,
+ columns: [],
+ rows: [],
+ });
+
+ await secondResponse.promise;
+ });
+
+ await waitFor(() =>
+ expect(result.current).toMatchObject({
+ data: expect.objectContaining({ rowCount: 2 }),
+ error: null,
+ isLoading: false,
+ }),
+ );
+ });
+
+ it("waits for async query creation before querying the dataset", async () => {
+ const deferred = createDeferred<DatasetQuery>();
+ const queryDataset = jest.fn(() =>
+ Promise.resolve({
+ rowCount: 1,
+ runningTime: 1,
+ columns: [],
+ rows: [],
+ }),
+ );
+ stubSdkBundle({
+ resolveDatasetQuery: jest.fn(() => jest.fn(() => deferred.promise)),
+ queryDataset: jest.fn(() => queryDataset),
+ });
+
+ renderHook(() =>
+ useMetabaseQuery({
+ source: TEST_SCHEMA.tables.orders,
+ limit: 10,
+ }),
+ );
+
+ expect(queryDataset).not.toHaveBeenCalled();
+
+ deferred.resolve(TEST_DATASET_QUERY);
+
+ await waitFor(() =>
+ expect(queryDataset).toHaveBeenCalledWith({
+ datasetQuery: TEST_DATASET_QUERY,
+ }),
+ );
+ });
+});
diff --git a/enterprise/frontend/src/embedding-sdk-package/index.ts b/enterprise/frontend/src/embedding-sdk-package/index.ts
index fc159305ca2..a8d9e9aea81 100644
--- a/enterprise/frontend/src/embedding-sdk-package/index.ts
+++ b/enterprise/frontend/src/embedding-sdk-package/index.ts
@@ -42,10 +42,13 @@ export type {
AnyActionResult,
UseActionResult,
} from "./hooks/public/use-action";
-
export { defineMetabaseAuthConfig } from "./lib/public/define-metabase-auth-config";
export { defineMetabaseTheme } from "./lib/public/define-metabase-theme";
+export { DataAppRouter } from "./components/public/DataAppRouter";
+export { DataAppLink } from "./components/public/DataAppLink";
+export { useDataAppLocation } from "./hooks/public/use-data-app-location";
+
export {
type CollectionBrowserProps,
type CollectionBrowserListColumns,
@@ -119,6 +122,7 @@ export type {
MetabaseCollection,
MetabaseCollectionItem,
MetabaseDataPointObject,
+ MetabaseQueryObject,
MetabaseDashboard,
MetabaseDashboardPluginsConfig,
MetabaseEmbeddingColorKeyV2,
@@ -127,6 +131,7 @@ export type {
MetabaseFontFamily,
MetabaseGlobalPluginsConfig,
ProtectedColorKey,
+ MetabaseCard,
MetabasePluginsConfig,
MetabaseQuestion,
MetabaseTheme,
@@ -160,6 +165,15 @@ export type {
SqlParameterValues,
SdkActionId,
} from "embedding-sdk-bundle/types";
+export type {
+ FieldSchema,
+ QueryData,
+ RowValue,
+ SchemaColumn,
+ SchemaJavaScriptType,
+ SchemaRow,
+} from "./hooks/public/data-schema";
+export type { QueryQuestionResult } from "embedding-sdk-bundle/lib/query-question";
export type {
EmbeddingEntityType,
diff --git a/enterprise/frontend/src/embedding-sdk-package/lib/public/copy.ts b/enterprise/frontend/src/embedding-sdk-package/lib/public/copy.ts
new file mode 100644
index 00000000000..fcecdad4e91
--- /dev/null
+++ b/enterprise/frontend/src/embedding-sdk-package/lib/public/copy.ts
@@ -0,0 +1,25 @@
+/**
+ * Write text to the system clipboard from a data app.
+ *
+ * Data apps run in a Near-Membrane sandbox that blocks the raw clipboard APIs
+ * (`document.execCommand`, `navigator.clipboard`) — the full surface, and
+ * *reading* the clipboard in particular, is unsafe. This is the sanctioned,
+ * write-only replacement: it runs in the host realm (endowed into the sandbox),
+ * coerces the input to a string, and writes it through the host clipboard. It
+ * exposes no read access and no other clipboard surface, so the only capability
+ * granted back to the bundle is "write a string".
+ *
+ * Browsers gate clipboard writes on user activation, so call it from a user
+ * event (e.g. a click handler).
+ */
+export async function copy(text: string): Promise<void> {
+ const value = String(text);
+
+ if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) {
+ throw new Error(
+ "Clipboard write is unavailable here — it requires a secure context (HTTPS) and user activation.",
+ );
+ }
+
+ await navigator.clipboard.writeText(value);
+}
diff --git a/enterprise/frontend/src/embedding-sdk-package/package.template.json b/enterprise/frontend/src/embedding-sdk-package/package.template.json
index 3c57ffb2ab8..4984d488a95 100644
--- a/enterprise/frontend/src/embedding-sdk-package/package.template.json
+++ b/enterprise/frontend/src/embedding-sdk-package/package.template.json
@@ -19,6 +19,19 @@
"require": "./dist/nextjs.cjs",
"import": "./dist/nextjs.js"
},
+ "./data-app": {
+ "types": "./dist/data-app.d.ts",
+ "require": "./dist/data-app.cjs",
+ "import": "./dist/data-app.js"
+ },
+ "./data-app-dev": {
+ "types": "./dist/data-app-dev.d.ts",
+ "import": "./dist/data-app-dev.js"
+ },
+ "./data-app-dev/config": {
+ "types": "./dist/data-app-dev.config.d.ts",
+ "import": "./dist/data-app-dev.config.js"
+ },
"./package.json": "./package.json"
},
"typesVersions": {
diff --git a/enterprise/frontend/src/metabase-enterprise/api/data-app.ts b/enterprise/frontend/src/metabase-enterprise/api/data-app.ts
new file mode 100644
index 00000000000..2cb5792b528
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/api/data-app.ts
@@ -0,0 +1,69 @@
+import type {
+ DataApp,
+ DataAppRepoStatus,
+ SetDataAppEnabledRequest,
+} from "metabase-types/api";
+
+import { EnterpriseApi } from "./api";
+import { idTag, invalidateTags, listTag } from "./tags";
+
+// Repo status is a single resource; tag it so it and the app list both refresh
+// when a sync changes things.
+const REPO_STATUS_TAG = idTag("data-app", "REPO-STATUS");
+
+type ListDataAppsOptions = { available?: boolean };
+
+export const dataAppApi = EnterpriseApi.injectEndpoints({
+ endpoints: (builder) => ({
+ listDataApps: builder.query<DataApp[], ListDataAppsOptions | void>({
+ query: (options) => ({
+ method: "GET",
+ url: "/api/apps",
+ params: options,
+ }),
+ providesTags: (apps = []) => [
+ listTag("data-app"),
+ ...apps.map((app) => idTag("data-app", app.name)),
+ ],
+ }),
+ getDataApp: builder.query<DataApp, string>({
+ query: (name) => ({
+ method: "GET",
+ url: `/api/apps/${encodeURIComponent(name)}`,
+ }),
+ providesTags: (_, __, name) => [idTag("data-app", name)],
+ }),
+ getDataAppRepoStatus: builder.query<DataAppRepoStatus, void>({
+ query: () => ({
+ method: "GET",
+ url: "/api/apps/repo-status",
+ }),
+ providesTags: () => [REPO_STATUS_TAG],
+ }),
+ setDataAppEnabled: builder.mutation<DataApp, SetDataAppEnabledRequest>({
+ query: ({ name, enabled }) => ({
+ method: "PUT",
+ url: `/api/apps/${encodeURIComponent(name)}`,
+ body: { enabled },
+ }),
+ invalidatesTags: (_, error, { name }) =>
+ invalidateTags(error, [listTag("data-app"), idTag("data-app", name)]),
+ }),
+ deleteDataApp: builder.mutation<void, string>({
+ query: (name) => ({
+ method: "DELETE",
+ url: `/api/apps/${encodeURIComponent(name)}`,
+ }),
+ invalidatesTags: (_, error, name) =>
+ invalidateTags(error, [listTag("data-app"), idTag("data-app", name)]),
+ }),
+ }),
+});
+
+export const {
+ useListDataAppsQuery,
+ useGetDataAppQuery,
+ useGetDataAppRepoStatusQuery,
+ useSetDataAppEnabledMutation,
+ useDeleteDataAppMutation,
+} = dataAppApi;
diff --git a/enterprise/frontend/src/metabase-enterprise/api/index.ts b/enterprise/frontend/src/metabase-enterprise/api/index.ts
index 6639c50a7dd..141a5c307fb 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/index.ts
@@ -8,6 +8,7 @@ export * from "./billing-info";
export * from "./cloud-add-ons";
export * from "./content-translation";
export * from "./custom-viz-plugin";
+export * from "./data-app";
export * from "./db-routing";
export * from "./dependencies";
export * from "./erd";
diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-dom-read.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-dom-read.ts
index 03bf56154be..7445aa3d0bf 100644
--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-dom-read.ts
+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-dom-read.ts
@@ -1,9 +1,11 @@
import type { CustomVizPluginId } from "metabase-types/api";
-// DOM scoping: every Node crossing the membrane is filtered. Nodes inside
-// the plugin's mount subtree (marked with data-plugin-sandbox=<id>) pass
-// through real; nodes outside are replaced with a detached decoy of the
-// same kind so the plugin can't read or mutate host UI.
+// DOM scoping is custom-viz-specific: each custom-viz plugin renders inside
+// its own `<div data-plugin-sandbox="<id>">…</div>` container, and every Node
+// crossing the membrane is filtered against that selector. Nodes inside the
+// plugin's container pass through real; nodes outside (sibling cards, the
+// dashboard's chrome, anywhere in the host DOM) are replaced with detached
+// decoys of the same kind so the plugin can't read or mutate host UI.
//
// Why this filters on Node, not just Element:
//
@@ -12,13 +14,9 @@ import type { CustomVizPluginId } from "metabase-types/api";
// `MutationObserver.observe(document, …)`, and `Range.setStart(document, 0)`.
// An Element-only filter would leave those APIs walking the entire host
// DOM and surfacing real host Text/Comment nodes.
-//
-// Filtering on Node also catches:
-// - `getSelection().anchorNode` / `focusNode` if the user has selected
-// host text.
-// - `Range.startContainer` / `endContainer` returning Text nodes.
const PLUGIN_SANDBOX_ATTR = "data-plugin-sandbox";
+
export const ACTIVE_ELEMENT_GETTER = Object.getOwnPropertyDescriptor(
Document.prototype,
"activeElement",
@@ -60,11 +58,12 @@ function getOwnerElement(node: Node): Element | null {
return null;
}
-// document.activeElement crosses the membrane and would otherwise be replaced
-// with a decoy when focus is on host UI — noisy and confusing for libraries
-// (notably React) that probe activeElement during rendering. Return null when
-// the focused element is outside the plugin's subtree, so the plugin sees
-// "nothing focused inside my React tree" rather than a fake element.
+// `document.activeElement` crosses the membrane and would otherwise be
+// replaced with a decoy when focus is on host UI — noisy and confusing for
+// libraries (notably React) that probe activeElement during rendering.
+// Return null when the focused element is outside the plugin's subtree, so
+// the plugin sees "nothing focused inside my React tree" rather than a fake
+// element.
export function activeElementDistortion(pluginId: CustomVizPluginId) {
return function activeElement(this: Document): Element | null {
// Unjustified type cast. FIXME
diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions.ts b/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions.ts
index b7da6116c5d..023531301b5 100644
--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions.ts
+++ b/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions.ts
@@ -1,115 +1,35 @@
+import { makeSandboxDistortionCallback } from "metabase/utils/scripts-sandbox";
import type { CustomVizPluginId } from "metabase-types/api";
-import { BLOCKED_NATIVE_REFS } from "./distortions-blocked-apis";
-import {
- CREATE_ELEMENT,
- CREATE_ELEMENT_NS,
- INSERT_ADJACENT_HTML,
- SANITIZED_SETTERS,
- SET_ATTRIBUTE,
- SET_ATTRIBUTE_NODE,
- SET_ATTRIBUTE_NODE_NS,
- SET_ATTRIBUTE_NS,
- SET_ATTR_VALUE_DESCRIPTOR,
- SET_NAMED_ITEM,
- SET_NAMED_ITEM_NS,
- attrValueSetterDistortion,
- createElementDistortion,
- createElementNSDistortion,
- insertAdjacentHTMLDistortion,
- sanitizedSetterDistortion,
- setAttributeDistortion,
- setAttributeNSDistortion,
- setAttributeNodeDistortion,
- setAttributeNodeNSDistortion,
- setNamedItemDistortion,
- setNamedItemNSDistortion,
-} from "./distortions-dom-mutate";
import {
ACTIVE_ELEMENT_GETTER,
activeElementDistortion,
getSafeSandboxDomNode,
isDomNode,
} from "./distortions-dom-read";
-import {
- ADD_EVENT_LISTENER,
- addEventListenerDistortion,
-} from "./distortions-event";
+/**
+ * Custom-viz Near Membrane distortion callback.
+ *
+ * Composes:
+ * 1. Custom-viz-only DOM scoping (`getSafeSandboxDomNode`,
+ * `activeElementDistortion`) keyed on `data-plugin-sandbox=<pluginId>`.
+ * 2. The shared sandbox callback from `utils/scripts-sandbox`, which blocks
+ * network egress, sanitizes DOM mutations, and blocks dangerous element
+ * creates and event listeners.
+ */
export function makeDistortionCallback(pluginId: CustomVizPluginId) {
+ const sharedDistortion = makeSandboxDistortionCallback(`plugin ${pluginId}`);
+
return function distortionCallback(value: object): object {
if (isDomNode(value)) {
return getSafeSandboxDomNode(value, pluginId);
}
- if (typeof value !== "function") {
- return value;
- }
-
- if (SANITIZED_SETTERS.has(value)) {
- const info = SANITIZED_SETTERS.get(value);
- if (info) {
- return sanitizedSetterDistortion(pluginId, info.name, info.originalSet);
- }
- }
-
if (value === ACTIVE_ELEMENT_GETTER) {
return activeElementDistortion(pluginId);
}
- if (value === ADD_EVENT_LISTENER) {
- return addEventListenerDistortion(pluginId);
- }
-
- if (value === CREATE_ELEMENT) {
- return createElementDistortion(pluginId);
- }
-
- if (value === CREATE_ELEMENT_NS) {
- return createElementNSDistortion(pluginId);
- }
-
- if (value === INSERT_ADJACENT_HTML) {
- return insertAdjacentHTMLDistortion(pluginId);
- }
-
- if (value === SET_ATTRIBUTE) {
- return setAttributeDistortion(pluginId);
- }
-
- if (value === SET_ATTRIBUTE_NS) {
- return setAttributeNSDistortion(pluginId);
- }
-
- if (value === SET_ATTRIBUTE_NODE) {
- return setAttributeNodeDistortion(pluginId);
- }
-
- if (value === SET_ATTRIBUTE_NODE_NS) {
- return setAttributeNodeNSDistortion(pluginId);
- }
-
- if (value === SET_NAMED_ITEM) {
- return setNamedItemDistortion(pluginId);
- }
-
- if (value === SET_NAMED_ITEM_NS) {
- return setNamedItemNSDistortion(pluginId);
- }
-
- if (value === SET_ATTR_VALUE_DESCRIPTOR) {
- return attrValueSetterDistortion(pluginId);
- }
-
- const blockedLabel = BLOCKED_NATIVE_REFS.get(value);
- if (blockedLabel) {
- return function blocked() {
- throw new Error(
- `[plugin ${pluginId}] blocked API call: ${blockedLabel}`,
- );
- };
- }
-
- return value;
+ return sharedDistortion(value);
};
}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.module.css b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.module.css
new file mode 100644
index 00000000000..0357d580166
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.module.css
@@ -0,0 +1,3 @@
+.appList > *:not(:last-child) {
+ border-bottom: 1px solid var(--mb-color-border);
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.tsx
new file mode 100644
index 00000000000..fe7f04a5c1a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.tsx
@@ -0,0 +1,104 @@
+import { t } from "ttag";
+
+import {
+ SettingsPageWrapper,
+ SettingsSection,
+} from "metabase/admin/components/SettingsSection";
+import { Badge, Box, Flex, Group, Loader, Stack, Title } from "metabase/ui";
+import {
+ useGetDataAppRepoStatusQuery,
+ useListDataAppsQuery,
+} from "metabase-enterprise/api";
+
+import S from "./ManageDataAppsPage.module.css";
+import { DataAppListItem } from "./components/DataAppListItem/DataAppListItem";
+import { DataAppRepoSection } from "./components/DataAppRepoSection/DataAppRepoSection";
+import { DataAppSkillsSection } from "./components/DataAppSkillsSection/DataAppSkillsSection";
+import { DataAppsEmptyState } from "./components/DataAppsEmptyState/DataAppsEmptyState";
+import { DataAppsBanner } from "./components/DataAppsPromoBanner/DataAppsBanner";
+
+const DATA_APP_REPO_QUERY_OPTS = {
+ // Keep the sync status fresh while the page is open: the backend polls the repo
+ // on its own schedule, so re-fetch the list periodically to reflect those syncs.
+ // Skipped automatically when the tab is unfocused.
+ pollingInterval: 10_000,
+ skipPollingIfUnfocused: true,
+ // Repo connection is managed on a different tab (Remote Sync) through another
+ // API slice, so it can't invalidate this cache. Refetch on mount so navigating
+ // (back) to the Data apps tab always reflects the current connection instead
+ // of a stale cached value.
+ refetchOnMountOrArgChange: true,
+} as const;
+
+export const ManageDataAppsPage = () => {
+ const { data: status, isLoading: isStatusLoading } =
+ useGetDataAppRepoStatusQuery(undefined, DATA_APP_REPO_QUERY_OPTS);
+ const { data: apps, isLoading: isAppsLoading } = useListDataAppsQuery(
+ undefined,
+ DATA_APP_REPO_QUERY_OPTS,
+ );
+
+ const isConfigured = status?.configured ?? false;
+
+ return (
+ <SettingsPageWrapper>
+ <Group gap="sm" align="center">
+ <Title order={1}>{t`Data apps`}</Title>
+
+ <Badge>{t`Beta`}</Badge>
+ </Group>
+
+ <DataAppsBanner />
+
+ <Stack gap="md">
+ <Title order={2}>{t`Setup`}</Title>
+
+ <SettingsSection
+ stackProps={{
+ gap: "lg",
+ }}
+ >
+ <DataAppRepoSection isConfigured={isConfigured} url={status?.url} />
+
+ <DataAppSkillsSection />
+ </SettingsSection>
+ </Stack>
+
+ {isStatusLoading ? (
+ <Flex justify="center" p="xl">
+ <Loader />
+ </Flex>
+ ) : (
+ <Stack gap="md">
+ <Title order={2}>{t`Apps`}</Title>
+
+ {isAppsLoading && (
+ <Flex justify="center" p="xl">
+ <Loader />
+ </Flex>
+ )}
+
+ {apps?.length === 0 && !isAppsLoading && <DataAppsEmptyState />}
+
+ {apps && apps.length > 0 && (
+ <Box
+ bd="1px solid var(--mb-color-border)"
+ bdrs="md"
+ bg="background-primary"
+ className={S.appList}
+ style={{ overflow: "hidden" }}
+ >
+ {apps.map((app) => (
+ <DataAppListItem
+ key={app.id}
+ app={app}
+ canRemove={!isConfigured}
+ />
+ ))}
+ </Box>
+ )}
+ </Stack>
+ )}
+ </SettingsPageWrapper>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsx
new file mode 100644
index 00000000000..38a1aec5fec
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/ManageDataAppsPage.unit.spec.tsx
@@ -0,0 +1,251 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { setupUserAcknowledgementEndpoints } from "__support__/server-mocks";
+import { renderWithProviders, screen, within } from "__support__/ui";
+import { UndoListing } from "metabase/common/components/UndoListing";
+import { Route } from "metabase/router";
+import type { DataApp } from "metabase-types/api";
+import { createMockDataApp } from "metabase-types/api/mocks";
+
+import { ManageDataAppsPage } from "./ManageDataAppsPage";
+
+type SetupOpts = {
+ configured?: boolean;
+ url?: string | null;
+ apps?: DataApp[];
+};
+
+const setup = ({
+ configured = true,
+ url = null,
+ apps = [],
+}: SetupOpts = {}) => {
+ fetchMock.get("path:/api/apps/repo-status", { configured, url });
+ fetchMock.get("path:/api/apps", apps);
+
+ setupUserAcknowledgementEndpoints({
+ key: "data-apps-admin-settings-banner",
+ value: true,
+ });
+
+ const Page = () => (
+ <>
+ <ManageDataAppsPage />
+ <UndoListing />
+ </>
+ );
+
+ renderWithProviders(<Route path="/" component={Page} />, {
+ withRouter: true,
+ });
+};
+
+const openActionsMenu = async (displayName: string) =>
+ userEvent.click(
+ await screen.findByRole("button", { name: `Actions for ${displayName}` }),
+ );
+
+describe("ManageDataAppsPage", () => {
+ describe("empty states", () => {
+ it("shows the generic empty state, and no duplicate 'no repository' message, when no repo is connected", async () => {
+ setup({ configured: false });
+
+ expect(
+ await screen.findByText("Your data apps will appear here"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText(/No repository is connected yet/),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows the empty state when a connected repository has no apps", async () => {
+ const url = "https://github.com/metabase/stats-remote-sync";
+ setup({ configured: true, url });
+
+ expect(await screen.findByText(url)).toBeInTheDocument();
+ expect(
+ await screen.findByText("Your data apps will appear here"),
+ ).toBeInTheDocument();
+ });
+
+ it("shows the setup section: repo status, the Git sync link, and the install command", async () => {
+ setup({ configured: false });
+
+ expect(
+ await screen.findByText("No repository connected"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("link", { name: "Go to Git sync settings" }),
+ ).toHaveAttribute("href", "/admin/settings/remote-sync");
+ expect(
+ screen.getByText(/npx skills add metabase\/metabase/),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(/--skill metabase-data-app-setup/),
+ ).toBeInTheDocument();
+ });
+ });
+
+ describe("the app list", () => {
+ it("links an enabled app to its route and shows its path", async () => {
+ setup({ apps: [createMockDataApp({ name: "sales" })] });
+
+ expect(
+ await screen.findByRole("link", { name: "Sales" }),
+ ).toHaveAttribute("href", "/apps/sales");
+ expect(screen.getByText("/apps/sales")).toBeInTheDocument();
+ });
+
+ it("shows a disabled app as plain text with a Disabled badge", async () => {
+ setup({ apps: [createMockDataApp({ name: "sales", enabled: false })] });
+
+ expect(await screen.findByText("Sales")).toBeInTheDocument();
+ // A disabled app isn't reachable, so its name isn't a link.
+ expect(
+ screen.queryByRole("link", { name: "Sales" }),
+ ).not.toBeInTheDocument();
+ expect(screen.getByText("Disabled")).toBeInTheDocument();
+ });
+
+ it("gives every app its own actions menu", async () => {
+ setup({
+ apps: [
+ createMockDataApp({
+ id: 1,
+ name: "alpha",
+ display_name: "Alpha App",
+ }),
+ createMockDataApp({ id: 2, name: "beta", display_name: "Beta App" }),
+ ],
+ });
+
+ expect(
+ await screen.findByRole("link", { name: "Alpha App" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("link", { name: "Beta App" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Actions for Alpha App" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Actions for Beta App" }),
+ ).toBeInTheDocument();
+ });
+
+ it("renders each sync status: a synced sha, a failure with its reason, and never-synced", async () => {
+ setup({
+ apps: [
+ createMockDataApp({
+ id: 1,
+ display_name: "Synced App",
+ last_synced_sha: "abcdef0",
+ }),
+ createMockDataApp({
+ id: 2,
+ display_name: "Failed App",
+ sync_error: "boom: bad manifest",
+ }),
+ createMockDataApp({
+ id: 3,
+ display_name: "New App",
+ last_synced_sha: null,
+ sync_error: null,
+ }),
+ ],
+ });
+
+ expect(await screen.findByText("Synced abcdef0")).toBeInTheDocument();
+ expect(screen.getByText("Sync failed")).toHaveAttribute(
+ "title",
+ "boom: bad manifest",
+ );
+ expect(screen.getByText("Not synced yet")).toBeInTheDocument();
+ });
+
+ it("shows how many hosts an app is allowed to reach", async () => {
+ setup({
+ apps: [
+ createMockDataApp({
+ allowed_hosts: ["https://api.example.com", "https://*.acme.com"],
+ }),
+ ],
+ });
+
+ expect(await screen.findByText("2 allowed hosts")).toBeInTheDocument();
+ });
+ });
+
+ describe("actions", () => {
+ it("disables an app", async () => {
+ setup({ apps: [createMockDataApp({ name: "sales" })] });
+ fetchMock.put(
+ "path:/api/apps/sales",
+ createMockDataApp({ enabled: false }),
+ );
+
+ await openActionsMenu("Sales");
+ await userEvent.click(
+ await screen.findByRole("menuitem", { name: "Disable" }),
+ );
+
+ const request = fetchMock.callHistory.lastCall("path:/api/apps/sales");
+ expect(await request?.request?.json()).toEqual({ enabled: false });
+ });
+
+ it("re-enables a disabled app", async () => {
+ setup({ apps: [createMockDataApp({ name: "sales", enabled: false })] });
+ fetchMock.put("path:/api/apps/sales", createMockDataApp());
+
+ await openActionsMenu("Sales");
+ await userEvent.click(
+ await screen.findByRole("menuitem", { name: "Re-enable" }),
+ );
+
+ const request = fetchMock.callHistory.lastCall("path:/api/apps/sales");
+ expect(await request?.request?.json()).toEqual({ enabled: true });
+ });
+
+ it("offers no Remove while a repository is connected", async () => {
+ // A removed app would just come back on the next sync, so Remove is only
+ // offered once the repo is unlinked.
+ setup({ configured: true, apps: [createMockDataApp({ name: "sales" })] });
+
+ await openActionsMenu("Sales");
+
+ expect(
+ await screen.findByRole("menuitem", { name: "Disable" }),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("menuitem", { name: "Remove" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("removes an app once the repository is unlinked", async () => {
+ // A sync never deletes, so an app synced while a repo was connected stays
+ // listed after unlinking — with a Remove action to clear it out.
+ setup({
+ configured: false,
+ apps: [createMockDataApp({ name: "sales" })],
+ });
+ fetchMock.delete("path:/api/apps/sales", 204);
+
+ await openActionsMenu("Sales");
+ await userEvent.click(
+ await screen.findByRole("menuitem", { name: "Remove" }),
+ );
+ await userEvent.click(
+ within(await screen.findByRole("dialog")).getByRole("button", {
+ name: "Remove",
+ }),
+ );
+
+ expect(
+ fetchMock.callHistory.called("path:/api/apps/sales", {
+ method: "DELETE",
+ }),
+ ).toBe(true);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.tsx
new file mode 100644
index 00000000000..8235ab0abd7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.tsx
@@ -0,0 +1,78 @@
+import { useCallback } from "react";
+import { t } from "ttag";
+
+import { useConfirmation, useToast } from "metabase/common/hooks";
+import { ActionIcon, Icon, Menu } from "metabase/ui";
+import {
+ useDeleteDataAppMutation,
+ useSetDataAppEnabledMutation,
+} from "metabase-enterprise/api";
+import type { DataApp } from "metabase-types/api";
+
+type Props = {
+ app: DataApp;
+ canRemove?: boolean;
+};
+
+export const DataAppActionsMenu = ({ app, canRemove = false }: Props) => {
+ const [setEnabled] = useSetDataAppEnabledMutation();
+ const [deleteDataApp, { isLoading: isDeleting }] = useDeleteDataAppMutation();
+ const [sendToast] = useToast();
+ const { show: showConfirmation, modalContent: confirmationModal } =
+ useConfirmation();
+
+ const handleToggleEnabled = useCallback(async () => {
+ try {
+ await setEnabled({ name: app.name, enabled: !app.enabled }).unwrap();
+ } catch {
+ sendToast({ message: t`Failed to update this app`, icon: "warning" });
+ }
+ }, [app.name, app.enabled, setEnabled, sendToast]);
+
+ const handleRemove = useCallback(() => {
+ showConfirmation({
+ title: t`Remove ${app.display_name} app?`,
+ message: t`This removes the data app, which won't be reachable until it's synced again from a connected repository.`,
+ confirmButtonText: t`Remove`,
+ onConfirm: async () => {
+ try {
+ await deleteDataApp(app.name).unwrap();
+ } catch {
+ sendToast({
+ message: t`Failed to remove this data app`,
+ icon: "warning",
+ });
+ }
+ },
+ });
+ }, [app.display_name, app.name, deleteDataApp, sendToast, showConfirmation]);
+
+ return (
+ <>
+ <Menu position="bottom-end">
+ <Menu.Target>
+ <ActionIcon
+ aria-label={t`Actions for ${app.display_name}`}
+ variant="subtle"
+ c="text-secondary"
+ loading={isDeleting}
+ >
+ <Icon name="ellipsis" />
+ </ActionIcon>
+ </Menu.Target>
+
+ <Menu.Dropdown>
+ <Menu.Item onClick={handleToggleEnabled}>
+ {app.enabled ? t`Disable` : t`Re-enable`}
+ </Menu.Item>
+
+ {canRemove && (
+ <Menu.Item onClick={handleRemove}>{t`Remove`}</Menu.Item>
+ )}
+ </Menu.Dropdown>
+ </Menu>
+
+ {confirmationModal}
+ </>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.unit.spec.tsx
new file mode 100644
index 00000000000..3069531f97c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppActionsMenu/DataAppActionsMenu.unit.spec.tsx
@@ -0,0 +1,95 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+import { UndoListing } from "metabase/common/components/UndoListing";
+import { createMockDataApp } from "metabase-types/api/mocks";
+
+import { DataAppActionsMenu } from "./DataAppActionsMenu";
+
+const setup = ({ enabled = true, canRemove = false } = {}) => {
+ const app = createMockDataApp({
+ name: "sales",
+ display_name: "Sales",
+ enabled,
+ });
+ renderWithProviders(
+ <>
+ <DataAppActionsMenu app={app} canRemove={canRemove} />
+ {/* Mounts the toaster so failure toasts are assertable in the DOM. */}
+ <UndoListing />
+ </>,
+ );
+};
+
+const openMenu = () =>
+ userEvent.click(screen.getByRole("button", { name: "Actions for Sales" }));
+
+const confirmRemove = async () =>
+ userEvent.click(
+ within(await screen.findByRole("dialog")).getByRole("button", {
+ name: "Remove",
+ }),
+ );
+
+describe("DataAppActionsMenu", () => {
+ it("should show a toast when toggling enabled fails", async () => {
+ fetchMock.put("path:/api/apps/sales", 500);
+ setup({ enabled: true });
+
+ await openMenu();
+ await userEvent.click(
+ await screen.findByRole("menuitem", { name: "Disable" }),
+ );
+
+ expect(
+ await screen.findByText("Failed to update this app"),
+ ).toBeInTheDocument();
+ });
+
+ it("should show a toast when removal fails", async () => {
+ fetchMock.delete("path:/api/apps/sales", 500);
+ setup({ canRemove: true });
+
+ await openMenu();
+ await userEvent.click(
+ await screen.findByRole("menuitem", { name: "Remove" }),
+ );
+ await confirmRemove();
+
+ expect(
+ await screen.findByText("Failed to remove this data app"),
+ ).toBeInTheDocument();
+ });
+
+ it("should show a loading state on the trigger while a delete is in flight", async () => {
+ let finishDelete = () => {};
+ fetchMock.delete(
+ "path:/api/apps/sales",
+ () =>
+ new Promise(
+ (resolve) => (finishDelete = () => resolve({ status: 204 })),
+ ),
+ );
+ setup({ canRemove: true });
+
+ await openMenu();
+ await userEvent.click(
+ await screen.findByRole("menuitem", { name: "Remove" }),
+ );
+ await confirmRemove();
+
+ const trigger = () =>
+ screen.getByRole("button", { name: "Actions for Sales" });
+
+ // Mantine marks a loading ActionIcon with `data-loading`.
+ await waitFor(() =>
+ expect(trigger()).toHaveAttribute("data-loading", "true"),
+ );
+
+ finishDelete();
+ await waitFor(() =>
+ expect(trigger()).not.toHaveAttribute("data-loading", "true"),
+ );
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppAllowedHosts/DataAppAllowedHosts.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppAllowedHosts/DataAppAllowedHosts.tsx
new file mode 100644
index 00000000000..a4173a4078b
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppAllowedHosts/DataAppAllowedHosts.tsx
@@ -0,0 +1,49 @@
+import { msgid, ngettext } from "ttag";
+
+import { HoverCard, Stack, Text } from "metabase/ui";
+
+type Props = {
+ /** External origins the app may fetch/XHR (from `data_app.yaml`). */
+ hosts: string[];
+};
+
+/**
+ * The app's network allowlist, shown inline in the admin list as an underlined
+ * "N allowed hosts" that reveals the origins in a hover card. Renders nothing
+ * when the app declares no allowed hosts.
+ */
+export function DataAppAllowedHosts({ hosts }: Props) {
+ if (hosts.length === 0) {
+ return null;
+ }
+
+ const label = ngettext(
+ msgid`${hosts.length} allowed host`,
+ `${hosts.length} allowed hosts`,
+ hosts.length,
+ );
+
+ return (
+ <HoverCard position="bottom-start">
+ <HoverCard.Target>
+ <Text
+ size="sm"
+ c="text-secondary"
+ lh="1.4"
+ style={{ textDecoration: "underline dotted", cursor: "help" }}
+ >
+ {label}
+ </Text>
+ </HoverCard.Target>
+ <HoverCard.Dropdown p="sm">
+ <Stack gap="xs">
+ {hosts.map((host, index) => (
+ <Text key={`${index}-${host}`} ff="monospace" size="sm">
+ {host}
+ </Text>
+ ))}
+ </Stack>
+ </HoverCard.Dropdown>
+ </HoverCard>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppAllowedHosts/DataAppAllowedHosts.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppAllowedHosts/DataAppAllowedHosts.unit.spec.tsx
new file mode 100644
index 00000000000..01348902746
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppAllowedHosts/DataAppAllowedHosts.unit.spec.tsx
@@ -0,0 +1,40 @@
+import userEvent from "@testing-library/user-event";
+
+import { renderWithProviders, screen } from "__support__/ui";
+
+import { DataAppAllowedHosts } from "./DataAppAllowedHosts";
+
+describe("DataAppAllowedHosts", () => {
+ it("renders nothing when there are no allowed hosts", () => {
+ renderWithProviders(<DataAppAllowedHosts hosts={[]} />);
+
+ expect(screen.queryByText(/allowed host/)).not.toBeInTheDocument();
+ });
+
+ it("shows a singular label for a single host", () => {
+ renderWithProviders(
+ <DataAppAllowedHosts hosts={["https://api.example.com"]} />,
+ );
+
+ expect(screen.getByText("1 allowed host")).toBeInTheDocument();
+ });
+
+ it("shows a pluralized count and reveals the hosts on hover", async () => {
+ renderWithProviders(
+ <DataAppAllowedHosts
+ hosts={["https://api.example.com", "https://*.acme.com"]}
+ />,
+ );
+
+ const label = screen.getByText("2 allowed hosts");
+ expect(label).toBeInTheDocument();
+
+ // The origins live in a hover card that opens on pointer hover.
+ await userEvent.hover(label);
+
+ expect(
+ await screen.findByText("https://api.example.com"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("https://*.acme.com")).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppIcon/DataAppIcon.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppIcon/DataAppIcon.tsx
new file mode 100644
index 00000000000..bf0f999e0db
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppIcon/DataAppIcon.tsx
@@ -0,0 +1,20 @@
+import { Flex, Icon } from "metabase/ui";
+
+const ICON_SIZE = 20;
+
+export function DataAppIcon() {
+ return (
+ <Flex
+ align="center"
+ justify="center"
+ w="2.75rem"
+ h="2.75rem"
+ bd="1px solid var(--mb-color-border)"
+ bg="background-secondary"
+ visibleFrom="sm"
+ style={{ borderRadius: "50%", flexShrink: 0 }}
+ >
+ <Icon name="app" size={ICON_SIZE} c="text-secondary" />
+ </Flex>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppListItem/DataAppListItem.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppListItem/DataAppListItem.tsx
new file mode 100644
index 00000000000..84e545be82c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppListItem/DataAppListItem.tsx
@@ -0,0 +1,29 @@
+import { Flex, Group } from "metabase/ui";
+import type { DataApp } from "metabase-types/api";
+
+import { DataAppActionsMenu } from "../DataAppActionsMenu/DataAppActionsMenu";
+import { DataAppStatusBadge } from "../DataAppStatusBadge/DataAppStatusBadge";
+import { DataAppSummary } from "../DataAppSummary/DataAppSummary";
+
+type Props = {
+ app: DataApp;
+ canRemove?: boolean;
+};
+
+export const DataAppListItem = ({ app, canRemove = false }: Props) => (
+ <Flex
+ data-testid={`data-app-list-item-${app.name}`}
+ justify="space-between"
+ align="center"
+ gap="md"
+ p="md"
+ >
+ <DataAppSummary app={app} />
+
+ <Group flex="0 0 auto" gap="md" wrap="nowrap" align="center">
+ <DataAppStatusBadge app={app} />
+
+ <DataAppActionsMenu app={app} canRemove={canRemove} />
+ </Group>
+ </Flex>
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppRepoSection/DataAppRepoSection.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppRepoSection/DataAppRepoSection.tsx
new file mode 100644
index 00000000000..6958afb3ce0
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppRepoSection/DataAppRepoSection.tsx
@@ -0,0 +1,51 @@
+import { t } from "ttag";
+
+import { Link } from "metabase/common/components/Link";
+import { Button, Group, Icon, Stack, Text, Title } from "metabase/ui";
+
+const REMOTE_SYNC_SETTINGS_PATH = "/admin/settings/remote-sync";
+
+type Props = {
+ /** Whether a repository is connected via remote-sync. */
+ isConfigured: boolean;
+ /** The connected repository URL (shown when configured). */
+ url?: string | null;
+};
+
+export const DataAppRepoSection = ({ isConfigured, url }: Props) => (
+ <Stack gap="sm">
+ <Title order={3}>{t`Remote sync repo`}</Title>
+
+ <Text>
+ {t`Data apps live in the repository connected via Git sync. Each app's built bundle is served at /apps/:name.`}
+ </Text>
+
+ <Group gap="md" wrap="nowrap" align="center">
+ <Group
+ gap="sm"
+ wrap="nowrap"
+ flex={1}
+ miw={0}
+ px="md"
+ py="sm"
+ bg="background-secondary"
+ bd="1px solid var(--mb-color-border)"
+ bdrs="md"
+ visibleFrom="sm"
+ >
+ <Icon name="git_branch" c="text-secondary" size={16} flex="0 0 auto" />
+ <Text
+ ff="monospace"
+ c={isConfigured ? "text-primary" : "text-secondary"}
+ truncate
+ >
+ {isConfigured ? url : t`No repository connected`}
+ </Text>
+ </Group>
+
+ <Button component={Link} to={REMOTE_SYNC_SETTINGS_PATH} variant="default">
+ {t`Go to Git sync settings`}
+ </Button>
+ </Group>
+ </Stack>
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsx
new file mode 100644
index 00000000000..09daebf0543
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.tsx
@@ -0,0 +1,60 @@
+import { t } from "ttag";
+
+import { CopyTextArea } from "metabase/common/components/CopyTextArea";
+import { useSetting } from "metabase/common/hooks";
+import { Stack, Text, Title } from "metabase/ui";
+import {
+ isLocalOrSnapshotVersion,
+ versionToNumericComponents,
+} from "metabase/utils/version";
+
+const REPOSITORY_NAME = "metabase/metabase";
+const MAIN_BRANCH_NAME = "master";
+const RELEASE_BRANCH_PREFIX = "release";
+const PUBLIC_SKILLS_PATH = "/skills";
+
+// The data-app skills to install. `skills add metabase/metabase` alone would
+// discover *every* skill in the repo, so each is selected explicitly.
+const DATA_APP_SKILLS = [
+ "metabase-data-app-setup",
+ "metabase-data-app-routing",
+ "metabase-data-app-actions",
+ "metabase-data-app-semantic-layer",
+];
+
+export const DataAppSkillsSection = () => {
+ // Pin the data-app skills (and the template bundled inside `metabase-data-app-setup`)
+ // to the branch matching this instance: `release-x.<major>.x`, or `master` for
+ // local/dev builds that have no release branch.
+ const { tag } = useSetting("version");
+ const majorVersion = tag ? versionToNumericComponents(tag)?.[1] : undefined;
+ const skillBranch =
+ tag && !isLocalOrSnapshotVersion(tag) && majorVersion != null
+ ? `${RELEASE_BRANCH_PREFIX}-x.${majorVersion}.x`
+ : MAIN_BRANCH_NAME;
+
+ const skillCommandBase = `npx skills add ${REPOSITORY_NAME}${PUBLIC_SKILLS_PATH}#${skillBranch}`;
+ const skillSelectors = DATA_APP_SKILLS.map((skill) => `--skill ${skill}`);
+ // Joined with shell line-continuations (` \` + newline) so each `--skill` is on
+ // its own line for readability, while the copied text is still one runnable
+ // command when pasted.
+ const installSkillCommand = [skillCommandBase, ...skillSelectors].join(
+ " \\\n",
+ );
+
+ return (
+ <Stack gap="sm">
+ <Title order={3}>{t`AI skills`}</Title>
+
+ {/* eslint-disable-next-line metabase/no-literal-metabase-strings -- Admin UI string */}
+ <Text>{t`Install Metabase Data App skills in your project, then ask your AI agent to create a data app.`}</Text>
+
+ <CopyTextArea
+ value={installSkillCommand}
+ aria-label={t`Install command`}
+ autosize
+ ff="monospace"
+ />
+ </Stack>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsx
new file mode 100644
index 00000000000..fd2b95eff0f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSkillsSection/DataAppSkillsSection.unit.spec.tsx
@@ -0,0 +1,75 @@
+import userEvent from "@testing-library/user-event";
+
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import {
+ createMockSettingsState,
+ createMockState,
+} from "metabase/redux/store/mocks";
+import { createMockVersion } from "metabase-types/api/mocks";
+
+import { DataAppSkillsSection } from "./DataAppSkillsSection";
+
+const setup = (tag?: string) => {
+ renderWithProviders(<DataAppSkillsSection />, {
+ storeInitialState: createMockState({
+ settings: createMockSettingsState({
+ version: createMockVersion({ tag }),
+ }),
+ }),
+ });
+};
+
+const copyCommand = async () => {
+ const writeText = jest.fn((_text: string) => Promise.resolve());
+ Object.assign(navigator, { clipboard: { writeText } });
+
+ await userEvent.click(screen.getByTestId("copy-button"));
+
+ await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1));
+ return writeText.mock.calls[0][0];
+};
+
+const DATA_APP_SKILLS = [
+ "metabase-data-app-setup",
+ "metabase-data-app-routing",
+ "metabase-data-app-actions",
+ "metabase-data-app-semantic-layer",
+];
+
+describe("DataAppSkillsSection", () => {
+ it("shows the command in a copy field, split across lines with shell continuations", async () => {
+ setup("v0.64.0");
+
+ const command = await copyCommand();
+
+ // The command is shown in a copy field (textarea) exactly as it is copied.
+ expect(screen.getByRole("textbox")).toHaveValue(command);
+
+ // Each --skill sits on its own line, joined by ` \` line-continuations, so
+ // the pasted command is still one runnable invocation.
+ expect(command).toContain("npx skills add metabase/metabase/skills#");
+ expect(command).toContain(" \\\n--skill metabase-data-app-setup");
+ });
+
+ it.each(DATA_APP_SKILLS)(
+ "includes the %s skill in the copied command",
+ async (skill) => {
+ setup("v0.64.0");
+
+ expect(await copyCommand()).toContain(`--skill ${skill}`);
+ },
+ );
+
+ // Release builds pin to their `release-x.<major>.x` branch; local, snapshot,
+ // and unknown builds fall back to `master`.
+ it.each<[tag: string | undefined, branch: string]>([
+ ["v0.64.0", "release-x.64.x"],
+ ["vLOCAL_DEV", "master"],
+ ["v0.53.0-SNAPSHOT", "master"],
+ [undefined, "master"],
+ ])("pins the skills for version '%s' to #%s", async (tag, branch) => {
+ setup(tag);
+
+ expect(await copyCommand()).toContain(`/skills#${branch}`);
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppStatusBadge/DataAppStatusBadge.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppStatusBadge/DataAppStatusBadge.tsx
new file mode 100644
index 00000000000..1225eb0b97a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppStatusBadge/DataAppStatusBadge.tsx
@@ -0,0 +1,26 @@
+import { t } from "ttag";
+
+import { Badge } from "metabase/ui";
+import type { DataApp } from "metabase-types/api";
+
+type Props = {
+ app: DataApp;
+};
+
+export const DataAppStatusBadge = ({ app }: Props) => {
+ if (app.enabled) {
+ return null;
+ }
+
+ return (
+ <Badge
+ size="md"
+ c="text-secondary"
+ bg="background-secondary"
+ bdrs="sm"
+ tt="none"
+ >
+ {t`Disabled`}
+ </Badge>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.tsx
new file mode 100644
index 00000000000..6b19033c7f4
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.tsx
@@ -0,0 +1,104 @@
+import { t } from "ttag";
+
+import { Group, Stack, Text } from "metabase/ui";
+import type { MetabaseColorKey } from "metabase/ui/colors/types";
+import * as Urls from "metabase/urls";
+import type { DataApp } from "metabase-types/api";
+
+import { DataAppAllowedHosts } from "../DataAppAllowedHosts/DataAppAllowedHosts";
+import { DataAppIcon } from "../DataAppIcon/DataAppIcon";
+
+type Props = {
+ app: DataApp;
+};
+
+const Bullet = () => (
+ <Text size="sm" c="text-secondary" aria-hidden>
+ &bull;
+ </Text>
+);
+
+function getSyncStatus({ sync_error, last_synced_sha }: DataApp): {
+ label: string;
+ color: MetabaseColorKey;
+ title?: string;
+} {
+ if (sync_error) {
+ return { label: t`Sync failed`, color: "error", title: sync_error };
+ }
+
+ if (last_synced_sha) {
+ return {
+ label: t`Synced ${last_synced_sha.slice(0, 7)}`,
+ color: "text-secondary",
+ };
+ }
+
+ return { label: t`Not synced yet`, color: "text-tertiary" };
+}
+
+const SyncStatus = ({ app }: Props) => {
+ const { label, color, title } = getSyncStatus(app);
+
+ return (
+ <Text size="sm" c={color} title={title} lh="1.4">
+ {label}
+ </Text>
+ );
+};
+
+export const DataAppSummary = ({ app }: Props) => {
+ const isOpenable = app.enabled && !app.sync_error;
+
+ return (
+ <Group align="center" flex="1" wrap="nowrap" miw={0}>
+ <DataAppIcon />
+
+ <Stack flex="1" gap={2} miw={0}>
+ {isOpenable ? (
+ <Text
+ component="a"
+ href={Urls.getSubpathSafeUrl(Urls.dataApp(app.name))}
+ target="_blank"
+ rel="noreferrer"
+ fw={700}
+ lh="1.4"
+ c="brand"
+ truncate
+ >
+ {app.display_name}
+ </Text>
+ ) : (
+ <Text fw={700} lh="1.4" c="text-secondary" truncate>
+ {app.display_name}
+ </Text>
+ )}
+
+ <Group gap="xs" align="center" wrap="wrap">
+ <Text
+ size="sm"
+ c="text-secondary"
+ ff="monospace"
+ lh="1.4"
+ truncate
+ maw="100%"
+ >
+ {Urls.dataApp(app.name)}
+ </Text>
+
+ <Bullet />
+
+ <SyncStatus app={app} />
+
+ {app.allowed_hosts.length > 0 && (
+ <>
+ <Bullet />
+
+ <DataAppAllowedHosts hosts={app.allowed_hosts} />
+ </>
+ )}
+ </Group>
+ </Stack>
+ </Group>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.unit.spec.tsx
new file mode 100644
index 00000000000..672c319dee7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppSummary/DataAppSummary.unit.spec.tsx
@@ -0,0 +1,101 @@
+import { renderWithProviders, screen } from "__support__/ui";
+import { createMockDataApp } from "metabase-types/api/mocks";
+
+import { DataAppSummary } from "./DataAppSummary";
+
+describe("DataAppSummary", () => {
+ it("renders an enabled app's name as a link to the app", () => {
+ renderWithProviders(
+ <DataAppSummary
+ app={createMockDataApp({ name: "sales", display_name: "Sales" })}
+ />,
+ );
+
+ const link = screen.getByRole("link", { name: "Sales" });
+ expect(link).toHaveAttribute(
+ "href",
+ expect.stringContaining("/apps/sales"),
+ );
+ });
+
+ it("renders a disabled app's name as plain text (no link)", () => {
+ renderWithProviders(
+ <DataAppSummary
+ app={createMockDataApp({ display_name: "Sales", enabled: false })}
+ />,
+ );
+
+ expect(screen.getByText("Sales")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("link", { name: "Sales" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("renders a sync-failed app's name as plain text (the link would lead to a dead end)", () => {
+ renderWithProviders(
+ <DataAppSummary
+ app={createMockDataApp({
+ display_name: "Sales",
+ enabled: true,
+ sync_error: "Bundle file not found",
+ })}
+ />,
+ );
+
+ expect(screen.getByText("Sales")).toBeInTheDocument();
+ expect(
+ screen.queryByRole("link", { name: "Sales" }),
+ ).not.toBeInTheDocument();
+ });
+
+ describe("sync status", () => {
+ it("shows the short synced SHA when the app has synced", () => {
+ renderWithProviders(
+ <DataAppSummary
+ app={createMockDataApp({
+ last_synced_sha: "0123456789abcdef",
+ sync_error: null,
+ })}
+ />,
+ );
+
+ expect(screen.getByText("Synced 0123456")).toBeInTheDocument();
+ });
+
+ it("shows a failure label with the error as a tooltip when the sync failed", () => {
+ renderWithProviders(
+ <DataAppSummary
+ app={createMockDataApp({ sync_error: "boom: bad manifest" })}
+ />,
+ );
+
+ const status = screen.getByText("Sync failed");
+ expect(status).toBeInTheDocument();
+ expect(status).toHaveAttribute("title", "boom: bad manifest");
+ });
+
+ it("prefers the failure label over the SHA when both are present", () => {
+ renderWithProviders(
+ <DataAppSummary
+ app={createMockDataApp({
+ last_synced_sha: "0123456789abcdef",
+ sync_error: "boom",
+ })}
+ />,
+ );
+
+ expect(screen.getByText("Sync failed")).toBeInTheDocument();
+ expect(screen.queryByText(/^Synced/)).not.toBeInTheDocument();
+ });
+
+ it("shows 'Not synced yet' when the app has never synced", () => {
+ renderWithProviders(
+ <DataAppSummary
+ app={createMockDataApp({ last_synced_sha: null, sync_error: null })}
+ />,
+ );
+
+ expect(screen.getByText("Not synced yet")).toBeInTheDocument();
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppsEmptyState/DataAppsEmptyState.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppsEmptyState/DataAppsEmptyState.tsx
new file mode 100644
index 00000000000..4959a139757
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppsEmptyState/DataAppsEmptyState.tsx
@@ -0,0 +1,29 @@
+import { t } from "ttag";
+
+import { Flex, Icon, Text } from "metabase/ui";
+
+export const DataAppsEmptyState = () => (
+ <Flex
+ direction="column"
+ align="center"
+ justify="center"
+ gap="md"
+ bd="1px solid var(--mb-color-border)"
+ bdrs="md"
+ bg="background-primary"
+ mih="16rem"
+ p="xl"
+ >
+ <Flex
+ align="center"
+ justify="center"
+ w="6rem"
+ h="6rem"
+ bg="background-secondary"
+ style={{ borderRadius: "50%" }}
+ >
+ <Icon name="app" size={48} c="border" />
+ </Flex>
+ <Text c="text-disabled">{t`Your data apps will appear here`}</Text>
+ </Flex>
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppsPromoBanner/DataAppsBanner.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppsPromoBanner/DataAppsBanner.tsx
new file mode 100644
index 00000000000..12d71565ab3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/admin/components/DataAppsPromoBanner/DataAppsBanner.tsx
@@ -0,0 +1,46 @@
+import { t } from "ttag";
+
+import { UserHasSeen } from "metabase/common/components/UserHasSeen/UserHasSeen";
+import { ActionIcon, Box, Group, Icon, Stack, Text } from "metabase/ui";
+
+const BANNER_ID = "data-apps-admin-settings-banner";
+
+export const DataAppsBanner = () => (
+ <UserHasSeen id={BANNER_ID}>
+ {({ hasSeen, ack }) =>
+ hasSeen ? null : (
+ <Box
+ pos="relative"
+ p="lg"
+ bg="background-brand"
+ bd="1px solid var(--mb-color-border)"
+ bdrs="md"
+ >
+ <ActionIcon
+ pos="absolute"
+ top="1rem"
+ right="1rem"
+ variant="subtle"
+ c="text-primary"
+ aria-label={t`Dismiss`}
+ onClick={ack}
+ >
+ <Icon name="close" />
+ </ActionIcon>
+
+ <Stack gap="sm">
+ <Group gap="sm" wrap="nowrap" pr="xl">
+ <Icon name="app" c="brand" flex="0 0 auto" />
+ <Text fw={700} c="brand">
+ {t`AI-generated React apps on top of your semantic layer`}
+ </Text>
+ </Group>
+
+ {/* eslint-disable-next-line metabase/no-literal-metabase-strings -- Admin UI string */}
+ <Text>{t`Have your AI agent of choice use Metabase's Data App skills to build a custom app backed by git, using the vetted metrics and data you've defined within Metabase.`}</Text>
+ </Stack>
+ </Box>
+ )
+ }
+ </UserHasSeen>
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.module.css b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.module.css
new file mode 100644
index 00000000000..48461b1d2dd
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.module.css
@@ -0,0 +1,10 @@
+.root {
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+}
+
+.content {
+ width: 100%;
+ height: 100%;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.tsx
new file mode 100644
index 00000000000..28fda6e7baa
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.tsx
@@ -0,0 +1,25 @@
+import type { ReactNode } from "react";
+
+import { Box } from "metabase/ui";
+
+import S from "./DataAppLayout.module.css";
+
+interface DataAppLayoutProps {
+ params: { name: string };
+ children: ReactNode;
+}
+
+export function DataAppLayout({ params, children }: DataAppLayoutProps) {
+ const { name } = params;
+
+ return (
+ <Box className={S.root}>
+ {/* Key on the app slug so navigating between apps remounts the host (and
+ its iframe) with the new app. Sub-path mirroring keeps the same
+ `:name`, so internal navigation never triggers a reload. */}
+ <Box key={name} className={S.content}>
+ {children}
+ </Box>
+ </Box>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.unit.spec.tsx
new file mode 100644
index 00000000000..2825331b6ef
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppLayout/DataAppLayout.unit.spec.tsx
@@ -0,0 +1,15 @@
+import { renderWithProviders, screen } from "__support__/ui";
+
+import { DataAppLayout } from "./DataAppLayout";
+
+describe("DataAppLayout", () => {
+ it("renders the data-app content", () => {
+ renderWithProviders(
+ <DataAppLayout params={{ name: "sales" }}>
+ <div>app content</div>
+ </DataAppLayout>,
+ );
+
+ expect(screen.getByText("app content")).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.module.css b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.module.css
new file mode 100644
index 00000000000..ed117c49b65
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.module.css
@@ -0,0 +1,10 @@
+/*
+ * Cap the width of the stack-trace box (`ErrorBox`), applied via
+ * `ErrorDetails`' `errorBoxClassName` — a long trace otherwise stretches the
+ * box to the full content width.
+ */
+.stackTrace {
+ max-width: 40rem;
+ overflow-x: auto;
+ overflow-wrap: anywhere;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx
new file mode 100644
index 00000000000..2a8f9bf9109
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.tsx
@@ -0,0 +1,279 @@
+import cx from "classnames";
+import { useEffect, useMemo, useState } from "react";
+import { t } from "ttag";
+
+import { EmptyState } from "metabase/common/components/EmptyState";
+import { ErrorDetails } from "metabase/common/components/ErrorDetails/ErrorDetails";
+import { GenericError, NotFound } from "metabase/common/components/ErrorPages";
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import CS from "metabase/css/core/index.css";
+import QueryBuilderS from "metabase/css/query_builder.module.css";
+import { Box, Flex } from "metabase/ui";
+import { useGetDataAppQuery } from "metabase-enterprise/api";
+
+import {
+ DATA_APP_ERROR_MESSAGE_TYPE,
+ type DataAppBundleErrorMessage,
+} from "../../constants";
+import { attachIframeUrlMirror } from "../../lib/attach-iframe-url-mirror";
+import { deriveIframeSrc } from "../../lib/derive-iframe-src";
+import { isCrossOriginError } from "../../lib/is-cross-origin-error";
+
+import S from "./DataAppView.module.css";
+
+interface AppViewProps {
+ params: { name: string };
+}
+
+/** The iframe can post anything; only trust objects tagged with our error type. */
+function isBundleErrorMessage(
+ data: unknown,
+): data is Partial<DataAppBundleErrorMessage> {
+ return (
+ typeof data === "object" &&
+ data !== null &&
+ "type" in data &&
+ data.type === DATA_APP_ERROR_MESSAGE_TYPE
+ );
+}
+
+/**
+ * /apps/:name(/*) — renders the requested data-app inside an isolated
+ * iframe, mirroring the iframe's internal route into the parent's URL.
+ *
+ * Sync semantics:
+ * - Parent → iframe: only on initial mount. The parent's current
+ * sub-path is read once and appended to the iframe's `src`. Later
+ * parent navigations are ignored (re-mounting the iframe is what
+ * would happen, and that's both expensive and against the design).
+ * - Iframe → parent: continuous. Every `pushState` / `replaceState` /
+ * `popstate` inside the iframe updates the parent's URL via
+ * `replaceState` (no parent reload, no extra history entry).
+ *
+ * The data-app bundle itself knows nothing about either direction —
+ * it just uses React Router as if it were the top-level app.
+ */
+export function DataAppView({ params }: AppViewProps) {
+ const name = params.name;
+ const validName = typeof name === "string" && name.length > 0;
+ // Callback ref (vs `useRef`) — fires when the iframe element actually
+ // mounts. The iframe is conditionally rendered (only after `meta`
+ // resolves), so a `useEffect` keyed on `[name, validName]` alone would
+ // run before the iframe exists and silently skip.
+ const [iframeEl, setIframeEl] = useState<HTMLIFrameElement | null>(null);
+
+ // The iframe is blank until its document + bundles finish downloading (the
+ // in-iframe `BundleHost` loader only appears once its React app mounts), so we
+ // cover it with a loader here until its `load` event fires.
+ const [iframeLoaded, setIframeLoaded] = useState(false);
+
+ // Errors that happen *inside* the iframe (bundle fetch failed, or the bundle
+ // crashed at runtime) are reported up to here via `postMessage` so we can
+ // render the failure screen in the host realm — where it matches the rest of
+ // the app's theme exactly, instead of fighting the SDK theme inside the frame.
+ const [bundleError, setBundleError] =
+ useState<DataAppBundleErrorMessage | null>(null);
+
+ // Reset whenever we navigate to a different app so a stale error doesn't stick.
+ // Note: this currently is not possible, but may happen if we show apps in the left nav menu
+ useEffect(() => setBundleError(null), [name]);
+
+ // Read parent path → iframe src ONCE; never re-derive on later renders.
+ const src = useMemo(
+ () => (validName ? deriveIframeSrc(name) : ""),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [],
+ );
+
+ const {
+ data: meta,
+ isLoading: metaLoading,
+ error: metaError,
+ } = useGetDataAppQuery(name, { skip: !validName });
+
+ useEffect(() => {
+ if (!iframeEl || !validName) {
+ return undefined;
+ }
+
+ let detach: (() => void) | null = null;
+
+ const onLoad = () => {
+ setIframeLoaded(true);
+
+ // The iframe can navigate cross-origin — a form submitting to an allowed
+ // external host, or the chrome-error page from a blocked navigation — and a
+ // cross-origin `contentWindow` throws on access. Mirroring only works
+ // same-origin, so tear down the old mirror and skip re-attaching if so.
+ try {
+ detach?.();
+ detach = null;
+
+ const win = iframeEl.contentWindow;
+
+ if (win) {
+ detach = attachIframeUrlMirror(win, name);
+ }
+ } catch (error) {
+ detach = null;
+ // Expected only for a cross-origin frame; rethrow anything else so mirror
+ // bugs surface.
+ if (!isCrossOriginError(error)) {
+ throw error;
+ }
+ }
+ };
+
+ iframeEl.addEventListener("load", onLoad);
+
+ // If the iframe already loaded before the effect ran, attach now.
+ if (iframeEl.contentWindow?.document.readyState === "complete") {
+ onLoad();
+ }
+
+ return () => {
+ iframeEl.removeEventListener("load", onLoad);
+ detach?.();
+ };
+ }, [iframeEl, name, validName]);
+
+ useEffect(() => {
+ if (!iframeEl) {
+ return undefined;
+ }
+
+ const onMessage = (event: MessageEvent) => {
+ // Only trust messages from our own iframe
+ if (event.source !== iframeEl.contentWindow) {
+ return;
+ }
+
+ const data: unknown = event.data;
+
+ if (isBundleErrorMessage(data)) {
+ setBundleError({
+ type: DATA_APP_ERROR_MESSAGE_TYPE,
+ notReady: Boolean(data.notReady),
+ message: typeof data.message === "string" ? data.message : undefined,
+ stack: typeof data.stack === "string" ? data.stack : undefined,
+ });
+ }
+ };
+
+ window.addEventListener("message", onMessage);
+
+ return () => window.removeEventListener("message", onMessage);
+ }, [iframeEl]);
+
+ if (!validName) {
+ return (
+ <NotFound
+ title={t`Data app not found`}
+ message={t`This data app doesn’t exist or has been disabled.`}
+ />
+ );
+ }
+
+ if (metaLoading || (!meta && !metaError)) {
+ return <LoadingAndErrorWrapper loading />;
+ }
+
+ if (metaError || !meta) {
+ // A disabled or non-existent app 404s from the metadata endpoint; anything
+ // else is an unexpected failure.
+ const status =
+ metaError && typeof metaError === "object" && "status" in metaError
+ ? metaError.status
+ : undefined;
+
+ if (!metaError || status === 404) {
+ return (
+ <NotFound
+ title={t`Data app not found`}
+ message={t`This data app doesn’t exist or has been disabled.`}
+ />
+ );
+ }
+
+ return (
+ <GenericError
+ title={t`Couldn’t load this data app`}
+ message={t`We ran into an error loading this data app. Try refreshing the page, or go back.`}
+ details={metaError}
+ />
+ );
+ }
+
+ if (bundleError) {
+ if (bundleError.notReady) {
+ return (
+ <NotFound
+ title={t`This data app isn’t ready yet`}
+ message={t`Its bundle hasn’t finished syncing from the connected repository. Try again in a moment.`}
+ />
+ );
+ }
+
+ return (
+ <Flex
+ direction="column"
+ w="100%"
+ h="100%"
+ justify="center"
+ align="center"
+ >
+ <EmptyState
+ title={t`This data app couldn’t be loaded`}
+ message={
+ bundleError.message ||
+ t`Something went wrong while loading this app. Try refreshing the page.`
+ }
+ illustrationElement={
+ <div
+ className={cx(
+ QueryBuilderS.QueryErrorImage,
+ QueryBuilderS.QueryErrorImageServerError,
+ )}
+ />
+ }
+ />
+
+ <ErrorDetails
+ className={CS.pt2}
+ errorBoxClassName={S.stackTrace}
+ details={bundleError.stack}
+ />
+ </Flex>
+ );
+ }
+
+ return (
+ <Box pos="relative" h="100%">
+ {!iframeLoaded && (
+ <Box pos="absolute" style={{ inset: 0, zIndex: 1 }}>
+ <LoadingAndErrorWrapper loading />
+ </Box>
+ )}
+
+ {/*
+ `allow-forms` is enabled so native form submissions can reach the app's
+ declared `allowed_hosts`. The CSP `form-action` directive (see the data-app
+ CSP in `security.clj` / the dev server) restricts submissions to exactly
+ those hosts — with no `allowed_hosts` it is `'none'` — blocking any other
+ target. Client-side `<form onSubmit>` (preventDefault) is unaffected.
+ */}
+ <iframe
+ ref={setIframeEl}
+ title={meta.display_name}
+ src={src}
+ sandbox="allow-scripts allow-same-origin allow-downloads allow-forms allow-modals allow-popups"
+ style={{
+ display: "block",
+ width: "100%",
+ height: "100%",
+ border: 0,
+ }}
+ />
+ </Box>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx
new file mode 100644
index 00000000000..a2281566a92
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/components/DataAppView/DataAppView.unit.spec.tsx
@@ -0,0 +1,122 @@
+import { act } from "@testing-library/react";
+
+import { renderWithProviders, screen } from "__support__/ui";
+import { useGetDataAppQuery } from "metabase-enterprise/api";
+import { createMockDataApp } from "metabase-types/api/mocks";
+
+import { DATA_APP_ERROR_MESSAGE_TYPE } from "../../constants";
+
+import { DataAppView } from "./DataAppView";
+
+jest.mock("metabase-enterprise/api", () => ({
+ ...jest.requireActual("metabase-enterprise/api"),
+ useGetDataAppQuery: jest.fn(),
+}));
+
+const mockedGetApp = jest.mocked(useGetDataAppQuery);
+
+type SetupOpts = {
+ name?: string;
+ data?: ReturnType<typeof createMockDataApp>;
+ isLoading?: boolean;
+ error?: unknown;
+};
+
+function setup({
+ name = "sales",
+ data,
+ isLoading = false,
+ error,
+}: SetupOpts = {}) {
+ // RTK Query's hook result is a wide discriminated union (refetch, status,
+ // isFetching, …); the component reads only these three fields.
+ mockedGetApp.mockReturnValue({
+ data,
+ isLoading,
+ error,
+ } as unknown as ReturnType<typeof useGetDataAppQuery>);
+
+ renderWithProviders(<DataAppView params={{ name }} />);
+}
+
+describe("DataAppView", () => {
+ afterEach(() => jest.clearAllMocks());
+
+ it("shows a not-found screen when the name is empty", () => {
+ setup({ name: "" });
+
+ expect(screen.getByText("Data app not found")).toBeInTheDocument();
+ });
+
+ it("shows a not-found screen when the app 404s (disabled or missing)", () => {
+ setup({ error: { status: 404 } });
+
+ expect(screen.getByText("Data app not found")).toBeInTheDocument();
+ });
+
+ it("shows a generic error screen for an unexpected failure", () => {
+ setup({ error: { status: 500 } });
+
+ expect(screen.getByText("Couldn’t load this data app")).toBeInTheDocument();
+ });
+
+ it("renders the app inside an iframe once metadata resolves", () => {
+ setup({ data: createMockDataApp({ display_name: "Sales" }) });
+
+ const iframe = screen.getByTitle("Sales");
+ expect(iframe).toBeInTheDocument();
+ expect(iframe).toHaveAttribute("src", "/embed/apps/sales");
+ });
+
+ /** Post a `message` event as if it came from `source`. */
+ function postMessage(source: MessageEventSource | null, data: unknown) {
+ act(() => {
+ window.dispatchEvent(new MessageEvent("message", { data, source }));
+ });
+ }
+
+ function setupIframe() {
+ setup({ data: createMockDataApp({ display_name: "Sales" }) });
+ return screen.getByTitle<HTMLIFrameElement>("Sales");
+ }
+
+ it("shows the not-ready screen when the iframe reports its bundle hasn't synced", () => {
+ const iframe = setupIframe();
+
+ postMessage(iframe.contentWindow, {
+ type: DATA_APP_ERROR_MESSAGE_TYPE,
+ notReady: true,
+ });
+
+ expect(
+ screen.getByText("This data app isn’t ready yet"),
+ ).toBeInTheDocument();
+ });
+
+ it("shows the themed error screen with the reported message when the iframe's bundle crashes", () => {
+ const iframe = setupIframe();
+
+ postMessage(iframe.contentWindow, {
+ type: DATA_APP_ERROR_MESSAGE_TYPE,
+ notReady: false,
+ message: "kaboom",
+ });
+
+ expect(
+ screen.getByText("This data app couldn’t be loaded"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("kaboom")).toBeInTheDocument();
+ });
+
+ it("ignores error messages that aren't from its own iframe", () => {
+ setupIframe();
+
+ // A look-alike message from a different window must not trigger the error UI.
+ postMessage(window, { type: DATA_APP_ERROR_MESSAGE_TYPE, notReady: true });
+
+ expect(
+ screen.queryByText("This data app isn’t ready yet"),
+ ).not.toBeInTheDocument();
+ expect(screen.getByTitle("Sales")).toBeInTheDocument();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/constants.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/constants.ts
new file mode 100644
index 00000000000..0552f852cbf
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/constants.ts
@@ -0,0 +1,16 @@
+/**
+ * `postMessage` type the iframe-top app (`DataAppIframeApp`) sends to the host
+ * (`AppView`) when the bundle can't be loaded or crashes at runtime, so the host
+ * can render the failure screen in its own (correctly themed) realm.
+ */
+export const DATA_APP_ERROR_MESSAGE_TYPE = "metabase.data-app.error" as const;
+
+export type DataAppBundleErrorMessage = {
+ type: typeof DATA_APP_ERROR_MESSAGE_TYPE;
+ /** True when the app is enabled but its bundle hasn't synced yet (a 404). */
+ notReady: boolean;
+ /** The real error message, pulled out of the (possibly opaque) thrown value. */
+ message?: string;
+ /** The error's stack, when one could be read. */
+ stack?: string;
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsx
new file mode 100644
index 00000000000..271a6892375
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/index.tsx
@@ -0,0 +1,22 @@
+import { PLUGIN_DATA_APPS } from "metabase/plugins";
+import { hasPremiumFeature } from "metabase-enterprise/settings";
+
+import { ManageDataAppsPage } from "./admin/ManageDataAppsPage";
+import { DataAppsNavbarSection } from "./navbar/DataAppsNavbarSection";
+import { getRoutes } from "./routes";
+
+/**
+ * Initialize data-apps plugin features.
+ *
+ * The admin nav item + the upsell live in OSS (so they show on every edition);
+ * the EE plugin only provides the real management UI, gated on the `data-apps`
+ * token feature.
+ */
+export function initializePlugin() {
+ if (hasPremiumFeature("data-apps")) {
+ PLUGIN_DATA_APPS.isEnabled = true;
+ PLUGIN_DATA_APPS.getRoutes = getRoutes;
+ PLUGIN_DATA_APPS.ManageDataAppsPage = ManageDataAppsPage;
+ PLUGIN_DATA_APPS.MainNavbarSection = DataAppsNavbarSection;
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/attach-iframe-url-mirror.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/attach-iframe-url-mirror.ts
new file mode 100644
index 00000000000..8cc42095690
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/attach-iframe-url-mirror.ts
@@ -0,0 +1,80 @@
+import * as Urls from "metabase/urls";
+
+import { isCrossOriginError } from "./is-cross-origin-error";
+
+/**
+ * The `Window` members the URL mirror touches. Narrower than `Window` so a test
+ * can pass a small typed fake without an unsafe cast — a real `Window` satisfies
+ * it.
+ */
+export interface UrlMirrorWindow {
+ readonly location: Pick<Location, "pathname">;
+ history: Pick<History, "pushState" | "replaceState">;
+ addEventListener: (type: "popstate", listener: () => void) => void;
+ removeEventListener: (type: "popstate", listener: () => void) => void;
+}
+
+/**
+ * Mirrors the iframe's URL into the parent's URL bar (no page reload).
+ *
+ * Same-origin frame, so we monkey-patch the iframe's `History` methods
+ * directly — no `postMessage` bridge. Wrapping `pushState`/`replaceState`
+ * catches programmatic nav; `popstate` catches browser back/forward
+ * inside the iframe. Each change is mirrored via the parent's
+ * `replaceState` (not `pushState`) so iframe-internal navigations don't
+ * clutter the parent's back-history with one entry each.
+ *
+ * Returns a cleanup that restores the originals.
+ */
+export function attachIframeUrlMirror(
+ iframeWindow: UrlMirrorWindow,
+ parentName: string,
+): () => void {
+ const iframePrefix = Urls.getSubpathSafeUrl(
+ `${Urls.DATA_APP_EMBED_PREFIX}/${encodeURIComponent(parentName)}`,
+ );
+ const parentPrefix = Urls.getSubpathSafeUrl(Urls.dataApp(parentName));
+
+ const mirror = () => {
+ const iframePath = iframeWindow.location.pathname;
+ const tail = iframePath.startsWith(iframePrefix)
+ ? iframePath.slice(iframePrefix.length)
+ : "";
+ const parentTarget =
+ parentPrefix + tail + window.location.search + window.location.hash;
+ const parentCurrent =
+ window.location.pathname + window.location.search + window.location.hash;
+ if (parentCurrent !== parentTarget) {
+ window.history.replaceState(window.history.state, "", parentTarget);
+ }
+ };
+
+ const history = iframeWindow.history;
+ const origPush = history.pushState;
+ const origReplace = history.replaceState;
+
+ history.pushState = function (...args) {
+ origPush.apply(this, args);
+ mirror();
+ };
+ history.replaceState = function (...args) {
+ origReplace.apply(this, args);
+ mirror();
+ };
+ iframeWindow.addEventListener("popstate", mirror);
+
+ return () => {
+ try {
+ history.pushState = origPush;
+ history.replaceState = origReplace;
+ iframeWindow.removeEventListener("popstate", mirror);
+ } catch (error) {
+ // Expected only when the frame navigated cross-origin: its window can no
+ // longer be touched, and the patched history/listeners are gone with the old
+ // document anyway. Rethrow anything else so real bugs surface.
+ if (!isCrossOriginError(error)) {
+ throw error;
+ }
+ }
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/attach-iframe-url-mirror.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/attach-iframe-url-mirror.unit.spec.ts
new file mode 100644
index 00000000000..93da68f0671
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/attach-iframe-url-mirror.unit.spec.ts
@@ -0,0 +1,127 @@
+import { setBasename } from "metabase/utils/basename";
+
+import {
+ type UrlMirrorWindow,
+ attachIframeUrlMirror,
+} from "./attach-iframe-url-mirror";
+
+type PopstateArgs = [type: "popstate", listener: () => void];
+
+interface FakeIframeWindow {
+ location: { pathname: string };
+ history: {
+ pushState: jest.Mock<void, unknown[]>;
+ replaceState: jest.Mock<void, unknown[]>;
+ };
+ addEventListener: jest.Mock<void, PopstateArgs>;
+ removeEventListener: jest.Mock<void, PopstateArgs>;
+}
+
+function fakeIframeWindow(pathname: string): FakeIframeWindow {
+ return {
+ location: { pathname },
+ history: {
+ pushState: jest.fn<void, unknown[]>(),
+ replaceState: jest.fn<void, unknown[]>(),
+ },
+ addEventListener: jest.fn<void, PopstateArgs>(),
+ removeEventListener: jest.fn<void, PopstateArgs>(),
+ };
+}
+
+// `FakeIframeWindow` structurally satisfies `UrlMirrorWindow`, so no cast is
+// needed at the call sites below.
+const asMirrorWindow = (iframe: FakeIframeWindow): UrlMirrorWindow => iframe;
+
+describe("attachIframeUrlMirror", () => {
+ // The basename is module-level global state; keep the root-path default clean
+ // for every test regardless of what a subpath case set.
+ afterEach(() => setBasename(""));
+
+ it("patches the iframe history + popstate on attach and restores them on cleanup", () => {
+ const iframe = fakeIframeWindow("/embed/apps/sales");
+ const origPush = iframe.history.pushState;
+ const origReplace = iframe.history.replaceState;
+
+ const detach = attachIframeUrlMirror(asMirrorWindow(iframe), "sales");
+
+ expect(iframe.history.pushState).not.toBe(origPush);
+ expect(iframe.history.replaceState).not.toBe(origReplace);
+ expect(iframe.addEventListener).toHaveBeenCalledWith(
+ "popstate",
+ expect.any(Function),
+ );
+
+ detach();
+
+ expect(iframe.history.pushState).toBe(origPush);
+ expect(iframe.history.replaceState).toBe(origReplace);
+ expect(iframe.removeEventListener).toHaveBeenCalledWith(
+ "popstate",
+ expect.any(Function),
+ );
+ });
+
+ it("mirrors the iframe's sub-path into the parent URL on a patched navigation", () => {
+ const iframe = fakeIframeWindow("/embed/apps/sales");
+ const replaceSpy = jest.spyOn(window.history, "replaceState");
+
+ attachIframeUrlMirror(asMirrorWindow(iframe), "sales");
+
+ // Simulate an in-iframe navigation to a sub-route.
+ iframe.location.pathname = "/embed/apps/sales/orders";
+ iframe.history.pushState({}, "", "/embed/apps/sales/orders");
+
+ // The parent URL is replaced (not pushed) with the mirrored sub-path.
+ const lastCall = replaceSpy.mock.calls.at(-1);
+ expect(lastCall?.[2]).toContain("/apps/sales/orders");
+
+ replaceSpy.mockRestore();
+ });
+
+ it("preserves the Metabase basename on a subpath install", () => {
+ // Subpath install at `/mb`: the iframe `src` is built subpath-safe, so its
+ // pathname carries the basename (`/mb/embed/apps/:name/…`).
+ setBasename("/mb");
+ const iframe = fakeIframeWindow("/mb/embed/apps/sales");
+ const replaceSpy = jest.spyOn(window.history, "replaceState");
+
+ attachIframeUrlMirror(asMirrorWindow(iframe), "sales");
+
+ // Navigate to a sub-route inside the iframe.
+ iframe.location.pathname = "/mb/embed/apps/sales/orders";
+ iframe.history.pushState({}, "", "/mb/embed/apps/sales/orders");
+
+ // The mirrored parent URL keeps both the `/mb` basename and the `/orders`
+ // app sub-route — it must not collapse to a bare `/apps/sales`.
+ const target = replaceSpy.mock.calls.at(-1)?.[2];
+ expect(target).toContain("/mb/apps/sales/orders");
+ expect(target).not.toBe("/apps/sales");
+
+ replaceSpy.mockRestore();
+ });
+
+ it("does not throw on cleanup when the frame has gone cross-origin", () => {
+ const iframe = fakeIframeWindow("/embed/apps/sales");
+ const detach = attachIframeUrlMirror(asMirrorWindow(iframe), "sales");
+
+ // A cross-origin frame throws on any window access (like the chrome-error
+ // page after a blocked navigation, or a real external host).
+ iframe.removeEventListener = jest.fn<void, PopstateArgs>(() => {
+ throw new DOMException("Blocked a frame with origin …", "SecurityError");
+ });
+
+ expect(() => detach()).not.toThrow();
+ });
+
+ it("rethrows unexpected (non-cross-origin) cleanup errors so real bugs surface", () => {
+ const iframe = fakeIframeWindow("/embed/apps/sales");
+ const detach = attachIframeUrlMirror(asMirrorWindow(iframe), "sales");
+
+ iframe.removeEventListener = jest.fn<void, PopstateArgs>(() => {
+ throw new TypeError("boom");
+ });
+
+ expect(() => detach()).toThrow("boom");
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/derive-iframe-src.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/derive-iframe-src.ts
new file mode 100644
index 00000000000..6bbbb645309
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/derive-iframe-src.ts
@@ -0,0 +1,22 @@
+import * as Urls from "metabase/urls";
+
+/**
+ * Maps the parent's `/apps/:name(/sub/route)` path to the iframe's
+ * `/embed/apps/:name(/sub/route)` path.
+ *
+ * The sub-path is read from `window.location.pathname` at component init
+ * (it is later changed *from inside the iframe*, never from the parent's
+ * own URL — we intentionally don't re-sync the parent → iframe direction
+ * after initial mount). Trailing characters after the name segment are
+ * preserved verbatim.
+ */
+export function deriveIframeSrc(name: string): string {
+ const prefix = Urls.dataApp(name);
+ const path = window.location.pathname;
+ const index = path.indexOf(prefix);
+ const tail = index >= 0 ? path.slice(index + prefix.length) : "";
+
+ return Urls.getSubpathSafeUrl(
+ `${Urls.DATA_APP_EMBED_PREFIX}/${encodeURIComponent(name)}${tail}`,
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/derive-iframe-src.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/derive-iframe-src.unit.spec.ts
new file mode 100644
index 00000000000..4bded600e4a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/derive-iframe-src.unit.spec.ts
@@ -0,0 +1,23 @@
+import { deriveIframeSrc } from "./derive-iframe-src";
+
+const setup = (parentPath: string, name: string) => {
+ window.history.replaceState({}, "", parentPath);
+
+ return { src: deriveIframeSrc(name) };
+};
+
+describe("deriveIframeSrc", () => {
+ afterEach(() => window.history.replaceState({}, "", "/"));
+
+ it.each<[string, string, string]>([
+ ["/apps/sales", "sales", "/embed/apps/sales"],
+ ["/apps/sales/orders/42", "sales", "/embed/apps/sales/orders/42"],
+ ["/somewhere/else", "sales", "/embed/apps/sales"],
+ ["/apps/my%20app/page", "my app", "/embed/apps/my%20app/page"],
+ ])(
+ "maps parent %p (name %p) to iframe src %p",
+ (parentPath, name, expected) => {
+ expect(setup(parentPath, name).src).toBe(expected);
+ },
+ );
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-cross-origin-error.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-cross-origin-error.ts
new file mode 100644
index 00000000000..48b7f353717
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/lib/is-cross-origin-error.ts
@@ -0,0 +1,10 @@
+/**
+ * A cross-origin frame throws a `SecurityError` (`DOMException`) on any window
+ * access — reading `contentWindow`, patching its `history`, removing a listener,
+ * etc. That happens expectedly when the data-app iframe navigates to an external
+ * host, or lands on a blocked navigation's `chrome-error` page. Use this to
+ * tolerate that case while letting real bugs surface.
+ */
+export function isCrossOriginError(error: unknown): boolean {
+ return error instanceof DOMException && error.name === "SecurityError";
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/navbar/DataAppsNavbarSection.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/navbar/DataAppsNavbarSection.tsx
new file mode 100644
index 00000000000..11f842e4047
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/navbar/DataAppsNavbarSection.tsx
@@ -0,0 +1,48 @@
+import { t } from "ttag";
+
+import { CollapseSection } from "metabase/common/components/CollapseSection";
+import {
+ PaddedSidebarLink,
+ SidebarHeading,
+ SidebarSection,
+} from "metabase/nav/containers/MainNavbar/MainNavbar.styled";
+import * as Urls from "metabase/urls";
+import { useListDataAppsQuery } from "metabase-enterprise/api";
+
+export function DataAppsNavbarSection({
+ onItemSelect,
+}: {
+ onItemSelect: () => void;
+}) {
+ const { data: dataApps = [] } = useListDataAppsQuery({ available: true });
+
+ if (dataApps.length === 0) {
+ return null;
+ }
+
+ return (
+ <SidebarSection>
+ <CollapseSection
+ header={<SidebarHeading>{t`Data apps`}</SidebarHeading>}
+ initialState="expanded"
+ iconPosition="right"
+ iconSize={8}
+ aria-label={t`Data apps`}
+ >
+ {dataApps.map((dataApp) => (
+ <PaddedSidebarLink
+ // Data-app names are globally unique slugs, enforced by the database.
+ key={dataApp.name}
+ icon="app"
+ onClick={onItemSelect}
+ rel="noopener noreferrer"
+ target="_blank"
+ url={Urls.dataApp(dataApp.name)}
+ >
+ {dataApp.display_name}
+ </PaddedSidebarLink>
+ ))}
+ </CollapseSection>
+ </SidebarSection>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/navbar/DataAppsNavbarSection.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/navbar/DataAppsNavbarSection.unit.spec.tsx
new file mode 100644
index 00000000000..22762d25976
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/navbar/DataAppsNavbarSection.unit.spec.tsx
@@ -0,0 +1,52 @@
+import fetchMock from "fetch-mock";
+
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+import { Route } from "metabase/router";
+
+import { DataAppsNavbarSection } from "./DataAppsNavbarSection";
+
+describe("DataAppsNavbarSection", () => {
+ it("does not show apps section when there are no data apps", async () => {
+ fetchMock.get("path:/api/apps?available=true", []);
+
+ renderWithProviders(<DataAppsNavbarSection onItemSelect={jest.fn()} />);
+
+ await waitFor(() =>
+ expect(
+ screen.queryByRole("heading", { name: "Data apps" }),
+ ).not.toBeInTheDocument(),
+ );
+ });
+
+ it("shows every data app as a link", async () => {
+ fetchMock.get("path:/api/apps?available=true", [
+ { name: "gizmo", display_name: "Gizmo" },
+ { name: "gadget", display_name: "Gadget" },
+ ]);
+
+ renderWithProviders(
+ <Route
+ path="/"
+ component={() => <DataAppsNavbarSection onItemSelect={jest.fn()} />}
+ />,
+ { withRouter: true },
+ );
+
+ expect(
+ await screen.findByRole("heading", { name: "Data apps" }),
+ ).toBeInTheDocument();
+
+ const gizmoLink = await screen.findByRole("link", { name: /Gizmo/ });
+ expect(gizmoLink).toHaveAttribute("href", "/apps/gizmo");
+ expect(gizmoLink).toHaveAttribute("target", "_blank");
+
+ expect(
+ within(gizmoLink).getByRole("img", { name: "app icon" }),
+ ).toBeInTheDocument();
+
+ expect(screen.getByRole("link", { name: /Gadget/ })).toHaveAttribute(
+ "href",
+ "/apps/gadget",
+ );
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/routes.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/routes.tsx
new file mode 100644
index 00000000000..1b31d14640f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/routes.tsx
@@ -0,0 +1,27 @@
+import { Route } from "metabase/router";
+import * as Urls from "metabase/urls";
+
+import { DataAppLayout } from "./components/DataAppLayout/DataAppLayout";
+import { DataAppView } from "./components/DataAppView/DataAppView";
+
+/**
+ * Data-app host routes. Open to any signed-in user.
+ *
+ * Path can't be `/app/:name` because the server reserves `/app/*` for static
+ * asset serving.
+ */
+export function getRoutes() {
+ return (
+ <Route
+ path={`${Urls.DATA_APP_URL_SEGMENT}/:name`}
+ component={DataAppLayout}
+ >
+ <Route index component={DataAppView} />
+ {/* Sub-paths under /apps/:name are owned by the iframe's router.
+ Same component — `DataAppView` just keeps the iframe mounted; the URL
+ change is mirrored back from inside the iframe via
+ `history.replaceState`. */}
+ <Route path="*" component={DataAppView} />
+ </Route>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/app-data-app.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/app-data-app.tsx
new file mode 100644
index 00000000000..447bd2d29ce
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/app-data-app.tsx
@@ -0,0 +1,39 @@
+import { createRoot } from "react-dom/client";
+
+import { sdkBundleExports } from "embedding-sdk-bundle/sdk-bundle-exports";
+
+import { DataAppIframeApp } from "./components/DataAppIframeApp/DataAppIframeApp";
+
+/**
+ * Entry point loaded by `data-app.html` and served from `/embed/apps/:name`.
+ *
+ * This script boots inside the iframe — separate from the host Metabase
+ * app's React tree. It reads the data-app `:name` from the URL, fetches the
+ * bundle, instantiates it inside a Near Membrane sandbox bound to *this*
+ * window, and renders the resulting component.
+ */
+
+// Register the full SDK bundle surface in-process (no separately-loaded
+// `main.bundle.js` request) so everything the data-app sandbox endows resolves
+// against it — the query primitives the package hooks dereference and the
+// implementations the package component facades look up at render time.
+window.METABASE_EMBEDDING_SDK_BUNDLE = sdkBundleExports;
+
+const init = () => {
+ document.body.style.margin = "0";
+
+ const rootElement = document.getElementById("root");
+
+ if (!rootElement) {
+ console.error("no #root element on data-app iframe entry");
+ return;
+ }
+
+ createRoot(rootElement).render(<DataAppIframeApp />);
+};
+
+if (document.readyState !== "loading") {
+ init();
+} else {
+ document.addEventListener("DOMContentLoaded", init);
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppErrorState/DataAppErrorState.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppErrorState/DataAppErrorState.tsx
new file mode 100644
index 00000000000..83d335d92a0
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppErrorState/DataAppErrorState.tsx
@@ -0,0 +1,9 @@
+import type { SdkErrorComponentProps } from "embedding-sdk-bundle/types";
+import { Icon, Stack, Text } from "metabase/ui";
+
+export const DataAppErrorState = ({ message }: SdkErrorComponentProps) => (
+ <Stack align="center" justify="center" gap="sm" p="lg" ta="center">
+ <Icon name="warning" size={28} c="text-tertiary" />
+ <Text c="text-secondary">{message}</Text>
+ </Stack>
+);
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsx
new file mode 100644
index 00000000000..fe2cc446371
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.tsx
@@ -0,0 +1,113 @@
+import { Component, type ErrorInfo, type ReactNode, useMemo } from "react";
+import { t } from "ttag";
+
+import { Center, Loader } from "metabase/ui";
+import { color } from "metabase/ui/colors";
+
+import { type ErrorDetail, describeError } from "../../lib/describe-error";
+import { readNameFromUrl } from "../../lib/read-name-from-url";
+import { reportErrorToParent } from "../../lib/report-error-to-parent";
+import { useDataAppBundle } from "../../lib/use-data-app-bundle";
+import { DataAppProvider } from "../DataAppProvider/DataAppProvider";
+
+/**
+ * Catches errors thrown while *rendering* the bundle's React tree (the async
+ * fetch/instantiate failures are handled separately in `useDataAppBundle`).
+ * Without this, a throw inside the bundle — e.g. an opaque `#<Object>` from the
+ * Near-Membrane sandbox — unmounts the whole tree and leaves a blank iframe.
+ */
+class BundleErrorBoundary extends Component<
+ { children: ReactNode },
+ { detail: ErrorDetail | null }
+> {
+ state: { detail: ErrorDetail | null } = { detail: null };
+
+ static getDerivedStateFromError(error: unknown): { detail: ErrorDetail } {
+ return { detail: describeError(error) };
+ }
+
+ componentDidCatch(error: unknown, info: ErrorInfo) {
+ const detail = describeError(error);
+ console.error(
+ "[data-app] error rendering the bundle:",
+ detail.message,
+ detail.stack ?? "",
+ info,
+ );
+ reportErrorToParent(false, detail);
+ }
+
+ render() {
+ if (this.state.detail) {
+ // `componentDidCatch` already reported the error to the host, which shows
+ // the themed failure screen; a neutral loader covers the handoff.
+ return (
+ <Center h="100vh">
+ <Loader />
+ </Center>
+ );
+ }
+ return this.props.children;
+ }
+}
+
+/**
+ * Fetches + sandboxes the bundle (via `useDataAppBundle`), then wraps the
+ * resulting component with `DataAppProvider` (host-realm Redux store, SDK
+ * theme, portal container, Emotion cache).
+ *
+ * `DataAppProvider` lives here in host code (not inside the bundle), so the
+ * SDK's `setState`-via-listener paths (drill popups, plugin init, etc.) run in
+ * host realm and don't hit the React-18-batching-through-Near-Membrane bug. The
+ * bundle's `App.tsx` returns pure content; the factory passes the theme through
+ * as `{ component, theme }`.
+ */
+function BundleHost({ name }: { name: string }) {
+ const { data, failed } = useDataAppBundle(name);
+
+ // On failure we report the error up to the host `AppView` (see
+ // `reportErrorToParent`), which renders the themed failure screen in its own
+ // realm and unmounts this iframe. Until that handoff lands we show a neutral
+ // loader — never an in-frame error screen, which would flash mis-themed.
+ let content: ReactNode;
+ if (data && !failed) {
+ const AppComponent = data.component;
+ content = (
+ <BundleErrorBoundary>
+ <AppComponent />
+ </BundleErrorBoundary>
+ );
+ } else {
+ content = (
+ <Center h="100vh">
+ <Loader />
+ </Center>
+ );
+ }
+
+ return (
+ <DataAppProvider appName={name} providerProps={data?.providerProps}>
+ {content}
+ </DataAppProvider>
+ );
+}
+
+/**
+ * Iframe-top React app. Reads the data-app name from the URL, mounts the
+ * bundle, and gets out of the way. Any sub-routes the bundle navigates to
+ * (via `history.pushState`, `react-router`, etc.) are mirrored back to the
+ * parent URL by `attachIframeUrlMirror` — the bundle doesn't need to know.
+ */
+export const DataAppIframeApp = () => {
+ const name = useMemo(() => readNameFromUrl(), []);
+
+ if (!name) {
+ return (
+ <div style={{ padding: 16, color: color("error") }}>
+ {t`Missing data-app name in URL`}
+ </div>
+ );
+ }
+
+ return <BundleHost name={name} />;
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.unit.spec.tsx
new file mode 100644
index 00000000000..c55295a2d2c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppIframeApp/DataAppIframeApp.unit.spec.tsx
@@ -0,0 +1,94 @@
+import type { ReactNode } from "react";
+
+import { renderWithProviders, screen } from "__support__/ui";
+
+import { readNameFromUrl } from "../../lib/read-name-from-url";
+import { reportErrorToParent } from "../../lib/report-error-to-parent";
+import { useDataAppBundle } from "../../lib/use-data-app-bundle";
+
+import { DataAppIframeApp } from "./DataAppIframeApp";
+
+jest.mock("../../lib/read-name-from-url", () => ({
+ readNameFromUrl: jest.fn(),
+}));
+jest.mock("../../lib/use-data-app-bundle", () => ({
+ useDataAppBundle: jest.fn(),
+}));
+jest.mock("../../lib/report-error-to-parent", () => ({
+ reportErrorToParent: jest.fn(),
+}));
+jest.mock("../DataAppProvider/DataAppProvider", () => ({
+ DataAppProvider: ({ children }: { children: ReactNode }) => (
+ <div data-testid="data-app-provider">{children}</div>
+ ),
+}));
+
+const mockedReadName = jest.mocked(readNameFromUrl);
+const mockedUseBundle = jest.mocked(useDataAppBundle);
+const mockedReport = jest.mocked(reportErrorToParent);
+
+type SetupOpts = {
+ name?: string | null;
+ bundle?: ReturnType<typeof useDataAppBundle>;
+};
+
+const setup = ({
+ name = "sales",
+ bundle = { data: null, failed: false },
+}: SetupOpts = {}) => {
+ mockedReadName.mockReturnValue(name);
+ mockedUseBundle.mockReturnValue(bundle);
+ renderWithProviders(<DataAppIframeApp />);
+
+ return { report: mockedReport };
+};
+
+describe("DataAppIframeApp", () => {
+ afterEach(() => jest.clearAllMocks());
+
+ it("shows an error when the URL has no data-app name", () => {
+ setup({ name: null });
+
+ expect(
+ screen.getByText("Missing data-app name in URL"),
+ ).toBeInTheDocument();
+ });
+
+ it("renders the loaded bundle component inside DataAppProvider", () => {
+ setup({
+ bundle: {
+ data: { component: () => <div>bundle content</div>, providerProps: {} },
+ failed: false,
+ },
+ });
+
+ expect(screen.getByTestId("data-app-provider")).toBeInTheDocument();
+ expect(screen.getByText("bundle content")).toBeInTheDocument();
+ });
+
+ it("renders a neutral loader (no bundle content) until the bundle resolves", () => {
+ setup({ bundle: { data: null, failed: false } });
+
+ expect(screen.getByTestId("data-app-provider")).toBeInTheDocument();
+ expect(screen.queryByText("bundle content")).not.toBeInTheDocument();
+ });
+
+ it("reports a render-time bundle crash up to the host and shows a loader", () => {
+ const consoleError = jest
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+ const Boom = () => {
+ throw new Error("render boom");
+ };
+
+ const { report } = setup({
+ bundle: { data: { component: Boom, providerProps: {} }, failed: false },
+ });
+
+ expect(report).toHaveBeenCalledWith(
+ false,
+ expect.objectContaining({ message: "render boom" }),
+ );
+ consoleError.mockRestore();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppProvider/DataAppProvider.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppProvider/DataAppProvider.tsx
new file mode 100644
index 00000000000..7904e9aa389
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppProvider/DataAppProvider.tsx
@@ -0,0 +1,77 @@
+import createCache from "@emotion/cache";
+import { CacheProvider, Global } from "@emotion/react";
+import { type ReactNode, useMemo, useState } from "react";
+
+import { SCOPED_CSS_RESET } from "embedding-sdk-bundle/components/private/PublicComponentStylesWrapper";
+import { PortalContainer } from "embedding-sdk-bundle/components/private/SdkPortalContainer";
+import { SdkThemeProvider } from "embedding-sdk-bundle/components/private/SdkThemeProvider";
+import { setDataApp } from "metabase/embedding/config";
+import { MetabaseReduxProvider } from "metabase/redux";
+import { getCspNonce } from "metabase/utils/csp";
+import type { DataAppMetabaseProviderProps } from "metabase-enterprise/data_apps/sandbox/types";
+
+import { useHostSdkStore } from "../../lib/use-host-sdk-store";
+import { DataAppErrorState } from "../DataAppErrorState/DataAppErrorState";
+
+// Note: Mantine + SDK CSS is loaded into the iframe via the `data-app-vendors`
+// Rspack entry (`<link rel="stylesheet">` in the iframe srcdoc). Don't side-
+// effect-import CSS here — those imports run at parent-bundle eval and land
+// in the host document, not the iframe.
+
+interface DataAppProviderProps {
+ appName: string;
+ isDevApp?: boolean;
+ providerProps?: DataAppMetabaseProviderProps;
+ children?: ReactNode;
+}
+
+/**
+ * In-host equivalent of the SDK's `MetabaseProvider` / `ComponentProvider`:
+ * provides the SDK Redux store (pre-initialized, no auth handshake), the
+ * SDK theme provider, and the portal container the SDK's Mantine
+ * components (drill popups, dropdowns, modals) target via
+ * `#metabase-sdk-portal-root`. Without `PortalContainer` rendered, those
+ * overlays mount to `document.body` or silently fail.
+ *
+ * Takes the data app `providerProps`. The data-app surface inherits the host's
+ * session cookie; auth is already established.
+ */
+export const DataAppProvider = (props: DataAppProviderProps) => {
+ const { children, providerProps, appName, isDevApp } = props;
+ const { theme } = providerProps ?? {};
+
+ // Configure the data-app request headers before any child renders. This must happen during the first render
+ useState(() => setDataApp(appName, { isDev: isDevApp }));
+
+ // Swap the SDK's default red error alert for a calm, neutral empty state,
+ // unless the app ships its own `errorComponent`.
+ const hostProviderProps = useMemo(
+ () => ({
+ ...providerProps,
+ errorComponent: providerProps?.errorComponent ?? DataAppErrorState,
+ }),
+ [providerProps],
+ );
+ const sdkStore = useHostSdkStore(hostProviderProps);
+
+ // Iframe-side Emotion cache: keyed + CSP-nonced so SDK/Mantine styles inject
+ // into this document's head (not the parent's).
+ const emotionCache = useMemo(
+ () => createCache({ key: "data-app", nonce: getCspNonce() ?? undefined }),
+ [],
+ );
+
+ return (
+ <CacheProvider value={emotionCache}>
+ <MetabaseReduxProvider store={sdkStore}>
+ <SdkThemeProvider theme={theme}>
+ <Global styles={SCOPED_CSS_RESET} />
+
+ {children}
+
+ <PortalContainer />
+ </SdkThemeProvider>
+ </MetabaseReduxProvider>
+ </CacheProvider>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppProvider/DataAppProvider.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppProvider/DataAppProvider.unit.spec.tsx
new file mode 100644
index 00000000000..177df63389a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/components/DataAppProvider/DataAppProvider.unit.spec.tsx
@@ -0,0 +1,117 @@
+import { render, screen } from "@testing-library/react";
+
+import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
+import { PLUGIN_API } from "metabase/plugins";
+
+import { useHostSdkStore } from "../../lib/use-host-sdk-store";
+import { DataAppErrorState } from "../DataAppErrorState/DataAppErrorState";
+
+import { DataAppProvider } from "./DataAppProvider";
+
+// The SDK theme/portal wrappers read from the SDK redux store; stub them so the
+// test can use a bare fake store and stay focused on DataAppProvider's own wiring.
+jest.mock("embedding-sdk-bundle/components/private/SdkThemeProvider", () => ({
+ SdkThemeProvider: ({ children }: { children: React.ReactNode }) => (
+ <>{children}</>
+ ),
+}));
+jest.mock("embedding-sdk-bundle/components/private/SdkPortalContainer", () => ({
+ PortalContainer: () => null,
+}));
+jest.mock("../../lib/use-host-sdk-store", () => ({
+ useHostSdkStore: jest.fn(),
+}));
+
+const mockedUseHostSdkStore = jest.mocked(useHostSdkStore);
+
+const setup = (providerProps?: Record<string, unknown>) => {
+ // Minimal store: react-redux's Provider only needs these three; the SDK
+ // wrappers that would call selectors are mocked out above.
+ mockedUseHostSdkStore.mockReturnValue({
+ getState: () => ({}),
+ subscribe: () => () => {},
+ dispatch: () => {},
+ } as unknown as ReturnType<typeof useHostSdkStore>);
+
+ render(
+ <DataAppProvider appName="test-app" providerProps={providerProps}>
+ <div>app content</div>
+ </DataAppProvider>,
+ );
+};
+
+describe("DataAppProvider", () => {
+ const originalConfig = { ...EMBEDDING_SDK_CONFIG };
+ const originalHandlers = { ...PLUGIN_API.onBeforeRequestHandlers };
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ Object.assign(EMBEDDING_SDK_CONFIG, originalConfig);
+ Object.assign(PLUGIN_API.onBeforeRequestHandlers, originalHandlers);
+ });
+
+ it("renders its children", () => {
+ setup();
+ expect(screen.getByText("app content")).toBeInTheDocument();
+ });
+
+ it("configures the data-app request headers with the app name", async () => {
+ setup();
+
+ expect(EMBEDDING_SDK_CONFIG.isDataApp).toBe(true);
+ expect(EMBEDDING_SDK_CONFIG.metabaseClientRequestIdentifier).toBe(
+ "test-app",
+ );
+ expect(
+ await PLUGIN_API.onBeforeRequestHandlers.setRequestClientHeaders({
+ method: "GET",
+ url: "/api/health",
+ data: {},
+ }),
+ ).toEqual({
+ headers: {
+ "X-Metabase-Client": "data-app",
+ "X-Metabase-Client-Identifier": "test-app",
+ },
+ });
+ });
+
+ // Regression guard: the neutral error component must be registered in the
+ // shared MetabaseProvider props store (via useHostSdkStore -> setProps), not
+ // only dispatched to redux. Every SDK component the app renders remounts a
+ // ComponentProvider that runs `setErrorComponent(props.errorComponent ?? null)`,
+ // so a redux-only override gets reset back to `null` on a cold page load.
+ it("registers the data-app error component through the props store", () => {
+ setup();
+
+ expect(mockedUseHostSdkStore).toHaveBeenCalledWith(
+ expect.objectContaining({ errorComponent: DataAppErrorState }),
+ );
+ });
+
+ it("forwards the data app's provider props alongside the error component", () => {
+ const theme = { colors: { brand: "#123456" } };
+ setup({ theme });
+
+ expect(mockedUseHostSdkStore).toHaveBeenCalledWith(
+ expect.objectContaining({ theme, errorComponent: DataAppErrorState }),
+ );
+ });
+
+ it("still registers the error component when no provider props are given", () => {
+ setup(undefined);
+
+ expect(mockedUseHostSdkStore).toHaveBeenCalledWith(
+ expect.objectContaining({ errorComponent: DataAppErrorState }),
+ );
+ });
+
+ it("lets an app override the default error component with its own", () => {
+ const AppErrorComponent = () => <div>app error</div>;
+ setup({ errorComponent: AppErrorComponent });
+
+ expect(mockedUseHostSdkStore).toHaveBeenCalledWith(
+ expect.objectContaining({ errorComponent: AppErrorComponent }),
+ );
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.ts
new file mode 100644
index 00000000000..30f190933b9
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/iframe-vendors.ts
@@ -0,0 +1,7 @@
+import "@mantine/core/styles.css";
+import "@mantine/dates/styles.css";
+
+import "metabase-enterprise/data_apps/sandbox/iframe-baseline.css";
+
+import "metabase/utils/csp";
+import "metabase/utils/dayjs";
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/describe-error.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/describe-error.ts
new file mode 100644
index 00000000000..335fdd9d02e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/describe-error.ts
@@ -0,0 +1,37 @@
+import { t } from "ttag";
+
+/** The actual error message + stack pulled out of a thrown value. */
+export type ErrorDetail = { message: string; stack?: string };
+
+/**
+ * Pull a human-readable message + stack out of a thrown value.
+ *
+ * Errors thrown *inside* the bundle come from the Near-Membrane sandbox's guest
+ * realm, so they arrive as opaque proxies: they log as `#<Object>` and fail
+ * `instanceof Error` against the host realm. Reading their *string* properties
+ * across the membrane still returns real primitives, so we read `message` /
+ * `stack` defensively (the membrane could also throw, hence the try/catch).
+ */
+export function describeError(
+ value: unknown,
+ fallbackMessage?: string,
+): ErrorDetail {
+ const fallback = fallbackMessage || t`An unexpected error occurred.`;
+
+ try {
+ const errorLike =
+ typeof value === "object" && value !== null ? value : null;
+ const rawMessage =
+ errorLike && "message" in errorLike ? errorLike.message : undefined;
+ const rawStack =
+ errorLike && "stack" in errorLike ? errorLike.stack : undefined;
+
+ const message =
+ typeof rawMessage === "string" && rawMessage ? rawMessage : fallback;
+ const stack = typeof rawStack === "string" ? rawStack : undefined;
+
+ return { message, stack };
+ } catch {
+ return { message: fallback };
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/describe-error.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/describe-error.unit.spec.ts
new file mode 100644
index 00000000000..9df02a31211
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/describe-error.unit.spec.ts
@@ -0,0 +1,60 @@
+import { describeError } from "./describe-error";
+
+const setup = (value: unknown, fallbackMessage?: string) => {
+ return { result: describeError(value, fallbackMessage) };
+};
+
+describe("describeError", () => {
+ it("pulls message and stack out of a real Error", () => {
+ const error = new Error("boom");
+ error.stack = "boom\n at foo";
+
+ const { result } = setup(error);
+
+ expect(result).toEqual({ message: "boom", stack: "boom\n at foo" });
+ });
+
+ it("reads message/stack off a plain error-shaped object", () => {
+ const { result } = setup({ message: "nope", stack: "trace" });
+
+ expect(result).toEqual({ message: "nope", stack: "trace" });
+ });
+
+ it("falls back when the message is missing or not a string", () => {
+ expect(setup({ message: 42 }).result).toEqual({
+ message: "An unexpected error occurred.",
+ stack: undefined,
+ });
+ expect(setup(null).result).toEqual({
+ message: "An unexpected error occurred.",
+ stack: undefined,
+ });
+ });
+
+ it("uses the caller-provided fallback message", () => {
+ const { result } = setup(undefined, "could not load");
+
+ expect(result).toEqual({ message: "could not load", stack: undefined });
+ });
+
+ it("omits stack when it isn't a string", () => {
+ const { result } = setup({ message: "m", stack: { not: "a string" } });
+
+ expect(result).toEqual({ message: "m", stack: undefined });
+ });
+
+ it("returns the fallback when reading across a membrane-opaque proxy throws", () => {
+ // Mimics a Near-Membrane guest-realm value: touching any property throws in
+ // the host realm. `describeError` must swallow that and return the fallback.
+ const opaque = new Proxy(
+ {},
+ {
+ get() {
+ throw new Error("membrane access denied");
+ },
+ },
+ );
+
+ expect(setup(opaque, "opaque").result).toEqual({ message: "opaque" });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/read-name-from-url.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/read-name-from-url.ts
new file mode 100644
index 00000000000..00aef2a7710
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/read-name-from-url.ts
@@ -0,0 +1,19 @@
+import * as Urls from "metabase/urls";
+
+/**
+ * Reads the requested data-app name from the iframe URL.
+ *
+ * The BE serves this iframe at `/embed/apps/:name(/sub/route)`. Anything
+ * after the `:name` segment is owned by the bundle's own router and mirrored
+ * back to the parent by `attachIframeUrlMirror` in `AppView`.
+ */
+export function readNameFromUrl(): string | null {
+ const segments = window.location.pathname.split("/").filter(Boolean);
+ const index = segments.indexOf(Urls.DATA_APP_URL_SEGMENT);
+
+ if (index < 0 || index === segments.length - 1) {
+ return null;
+ }
+
+ return decodeURIComponent(segments[index + 1] ?? "");
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/read-name-from-url.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/read-name-from-url.unit.spec.ts
new file mode 100644
index 00000000000..b21b4b98ebd
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/read-name-from-url.unit.spec.ts
@@ -0,0 +1,21 @@
+import { readNameFromUrl } from "./read-name-from-url";
+
+const setup = (path: string) => {
+ window.history.replaceState({}, "", path);
+
+ return { name: readNameFromUrl() };
+};
+
+describe("readNameFromUrl", () => {
+ afterEach(() => window.history.replaceState({}, "", "/"));
+
+ it.each<[string, string | null]>([
+ ["/embed/apps/sales", "sales"],
+ ["/embed/apps/sales/orders/42", "sales"],
+ ["/embed/apps/my%20app", "my app"],
+ ["/embed/something/else", null],
+ ["/embed/apps", null],
+ ])("reads the name from %p as %p", (path, expected) => {
+ expect(setup(path).name).toBe(expected);
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-error-to-parent.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-error-to-parent.ts
new file mode 100644
index 00000000000..db4ac959457
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/report-error-to-parent.ts
@@ -0,0 +1,25 @@
+import { DATA_APP_ERROR_MESSAGE_TYPE } from "../../constants";
+
+import type { ErrorDetail } from "./describe-error";
+
+/**
+ * Report a bundle failure up to the host `AppView` (the parent window) so it can
+ * render the failure screen in its own realm, where it's themed exactly like the
+ * rest of the app — instead of trying (and failing) to match the host's theme
+ * from inside the SDK-themed iframe.
+ */
+export function reportErrorToParent(notReady: boolean, detail?: ErrorDetail) {
+ if (window.parent === window) {
+ return;
+ }
+
+ window.parent.postMessage(
+ {
+ type: DATA_APP_ERROR_MESSAGE_TYPE,
+ notReady,
+ message: detail?.message,
+ stack: detail?.stack,
+ },
+ "*",
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.ts
new file mode 100644
index 00000000000..32925360779
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.ts
@@ -0,0 +1,102 @@
+import { type ComponentType, useEffect, useState } from "react";
+
+import type { DataAppMetabaseProviderProps } from "metabase-enterprise/data_apps/sandbox/types";
+
+import {
+ DataAppBundleError,
+ fetchDataAppBundleCode,
+ instantiateDataAppBundle,
+} from "../loader";
+
+import { describeError } from "./describe-error";
+import { reportErrorToParent } from "./report-error-to-parent";
+
+export interface LoadedApp {
+ component: ComponentType<Record<string, unknown>>;
+ providerProps: DataAppMetabaseProviderProps;
+}
+
+/**
+ * Loads a data-app bundle by name and supervises it: fetches the bundle code,
+ * instantiates it inside the Near-Membrane sandbox, and watches for uncaught
+ * crashes. Any failure is reported up to the host `AppView` (which owns the
+ * themed failure screen); the returned `failed` flag only gates what the iframe
+ * renders in the meantime (the bundle vs. a neutral loader).
+ */
+export const useDataAppBundle = (
+ name: string,
+): {
+ data: LoadedApp | null;
+ failed: boolean;
+} => {
+ const [data, setData] = useState<LoadedApp | null>(null);
+ const [failed, setFailed] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+
+ setData(null);
+ setFailed(false);
+
+ const load = async () => {
+ const { code, allowedHosts } = await fetchDataAppBundleCode(name);
+
+ if (cancelled) {
+ return;
+ }
+
+ const { component, providerProps } = instantiateDataAppBundle(
+ code,
+ name,
+ window,
+ allowedHosts,
+ );
+
+ setData({ component, providerProps });
+ };
+
+ load().catch((error: unknown) => {
+ if (!cancelled) {
+ const notReady =
+ error instanceof DataAppBundleError && error.status === 404;
+ // A 404 (not-yet-synced) is expected, so we keep the friendly message;
+ // any other failure carries the real error so it can be shown.
+ const detail = notReady ? undefined : describeError(error);
+ setFailed(true);
+ reportErrorToParent(notReady, detail);
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [name]);
+
+ useEffect(() => {
+ // The bundle runs in a Near-Membrane sandbox that can throw errors which
+ // escape React's render cycle (e.g. an opaque `#<Object>` from the membrane)
+ // and so slip past `BundleErrorBoundary`, leaving a blank frame. Catch
+ // genuine uncaught JS errors at the window level and show the error screen.
+ // `event.error == null` for resource-load errors, which we ignore.
+ const onError = (event: ErrorEvent) => {
+ if (event.error != null) {
+ const detail = describeError(event.error, event.message);
+ // Log the unpacked message/stack so devtools shows the real error
+ // instead of the membrane's opaque `#<Object>`.
+ console.error(
+ "[data-app] uncaught error in the bundle:",
+ detail.message,
+ detail.stack ?? "",
+ );
+ setFailed(true);
+ reportErrorToParent(false, detail);
+ }
+ };
+
+ window.addEventListener("error", onError);
+
+ return () => window.removeEventListener("error", onError);
+ }, []);
+
+ return { data, failed };
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.unit.spec.ts
new file mode 100644
index 00000000000..d60136027fc
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-data-app-bundle.unit.spec.ts
@@ -0,0 +1,118 @@
+import { renderHook, waitFor } from "@testing-library/react";
+
+import {
+ DataAppBundleError,
+ fetchDataAppBundleCode,
+ instantiateDataAppBundle,
+} from "../loader";
+
+import { reportErrorToParent } from "./report-error-to-parent";
+import { type LoadedApp, useDataAppBundle } from "./use-data-app-bundle";
+
+jest.mock("../loader", () => ({
+ ...jest.requireActual("../loader"),
+ fetchDataAppBundleCode: jest.fn(),
+ instantiateDataAppBundle: jest.fn(),
+}));
+jest.mock("./report-error-to-parent", () => ({
+ reportErrorToParent: jest.fn(),
+}));
+
+const mockedFetch = jest.mocked(fetchDataAppBundleCode);
+const mockedInstantiate = jest.mocked(instantiateDataAppBundle);
+const mockedReport = jest.mocked(reportErrorToParent);
+
+const LOADED_APP: LoadedApp = { component: () => null, providerProps: {} };
+
+type SetupOpts = {
+ code?: string;
+ allowedHosts?: string[];
+ error?: Error;
+ app?: LoadedApp;
+};
+
+function setup({
+ code = "CODE",
+ allowedHosts = [],
+ error,
+ app,
+}: SetupOpts = {}) {
+ if (error) {
+ mockedFetch.mockRejectedValue(error);
+ } else {
+ mockedFetch.mockResolvedValue({ code, allowedHosts });
+ }
+ if (app) {
+ mockedInstantiate.mockReturnValue(app);
+ }
+ return renderHook(() => useDataAppBundle("sales"));
+}
+
+describe("useDataAppBundle", () => {
+ afterEach(() => jest.clearAllMocks());
+
+ it("fetches, instantiates, and exposes the loaded app", async () => {
+ const { result } = setup({
+ code: "CODE",
+ allowedHosts: ["https://x"],
+ app: LOADED_APP,
+ });
+
+ await waitFor(() => expect(result.current.data).toEqual(LOADED_APP));
+ expect(result.current.failed).toBe(false);
+ expect(mockedInstantiate).toHaveBeenCalledWith("CODE", "sales", window, [
+ "https://x",
+ ]);
+ expect(mockedReport).not.toHaveBeenCalled();
+ });
+
+ it("treats a 404 as the friendly not-ready state (no error detail)", async () => {
+ const { result } = setup({ error: new DataAppBundleError("nope", 404) });
+
+ await waitFor(() => expect(result.current.failed).toBe(true));
+ expect(result.current.data).toBeNull();
+ expect(mockedReport).toHaveBeenCalledWith(true, undefined);
+ });
+
+ it("reports the real error detail for any non-404 failure", async () => {
+ const { result } = setup({ error: new Error("boom") });
+
+ await waitFor(() => expect(result.current.failed).toBe(true));
+ expect(mockedReport).toHaveBeenCalledWith(
+ false,
+ expect.objectContaining({ message: "boom" }),
+ );
+ });
+
+ it("catches an uncaught window error that escapes the render cycle", async () => {
+ const consoleError = jest
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+ const { result } = setup({ app: LOADED_APP });
+ await waitFor(() => expect(result.current.data).toEqual(LOADED_APP));
+
+ window.dispatchEvent(
+ new ErrorEvent("error", {
+ error: new Error("kaboom"),
+ message: "kaboom",
+ }),
+ );
+
+ await waitFor(() => expect(result.current.failed).toBe(true));
+ expect(mockedReport).toHaveBeenCalledWith(
+ false,
+ expect.objectContaining({ message: "kaboom" }),
+ );
+ consoleError.mockRestore();
+ });
+
+ it("ignores window error events with no error object (resource loads)", async () => {
+ const { result } = setup({ app: LOADED_APP });
+ await waitFor(() => expect(result.current.data).toEqual(LOADED_APP));
+
+ window.dispatchEvent(new ErrorEvent("error", { error: null }));
+
+ expect(result.current.failed).toBe(false);
+ expect(mockedReport).not.toHaveBeenCalled();
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-host-sdk-store.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-host-sdk-store.ts
new file mode 100644
index 00000000000..c267ea05c17
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-host-sdk-store.ts
@@ -0,0 +1,73 @@
+import { useEffect, useRef } from "react";
+import useDeepCompareEffect from "react-use/lib/useDeepCompareEffect";
+
+import { getSdkStore } from "embedding-sdk-bundle/store";
+import { initAuth } from "embedding-sdk-bundle/store/auth/auth";
+import { setPluginsReady } from "embedding-sdk-bundle/store/reducer";
+import type { MetabaseProviderProps } from "embedding-sdk-bundle/types/metabase-provider";
+import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";
+import { SdkLoadingState } from "embedding-sdk-shared/types/sdk-loading";
+
+type SdkStore = ReturnType<typeof getSdkStore>;
+
+/**
+ * Same-origin, subpath-aware instance URL (e.g. `https://host/metabase`). The
+ * SDK assigns this straight to `api.basename`, so it must keep the Metabase
+ * subpath — `window.location.origin` alone would send `/api/...` instead of
+ * `/<subpath>/api/...` and break subpath deployments. `MetabaseRoot` is set by
+ * the iframe's `index_bootstrap` inline JS; it falls back to `/` if absent.
+ */
+function getMetabaseInstanceUrl(): string {
+ const basename = (window.MetabaseRoot ?? "/").replace(/\/+$/, "");
+
+ return `${window.location.origin}${basename}`;
+}
+
+/**
+ * Provides the host-backed SDK Redux store the data-app surface runs on.
+ *
+ * Forwards the caller's provider props (auth config, theme) into the SDK props
+ * store the same way the SDK's own `MetabaseProvider` does, with two
+ * differences that matter for correctness:
+ * - `children` is stripped — it's an unstable `ReactNode` with no meaning in
+ * the props store, and forwarding it would re-run the effect every render.
+ * - a deep-compare effect re-runs `setProps` only when prop *content* changes
+ * (e.g. `theme` arriving once the bundle loads), not on every render.
+ */
+export function useHostSdkStore(
+ props: Partial<Omit<MetabaseProviderProps, "children">> = {},
+): SdkStore {
+ const storeRef = useRef<SdkStore | null>(null);
+
+ if (!storeRef.current) {
+ storeRef.current = getSdkStore();
+ }
+
+ const store = storeRef.current;
+
+ // Forward auth config + theme into the SDK props store. Deep-compare so it
+ // only re-runs when the content changes, mirroring the SDK's MetabaseProvider.
+ useDeepCompareEffect(() => {
+ ensureMetabaseProviderPropsStore().setProps({
+ authConfig: {
+ isGuest: false,
+ metabaseInstanceUrl: getMetabaseInstanceUrl(),
+ },
+ ...props,
+ });
+ }, [props]);
+
+ // One-time init: mark the store ready and resolve auth. This must NOT re-run
+ // on prop changes — re-dispatching `initAuth`/`setPluginsReady` is incorrect.
+ useEffect(() => {
+ ensureMetabaseProviderPropsStore().updateInternalProps({
+ reduxStore: store,
+ loadingState: SdkLoadingState.Loaded,
+ });
+
+ store.dispatch({ type: initAuth.fulfilled.type });
+ store.dispatch(setPluginsReady(true));
+ }, [store]);
+
+ return store;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-host-sdk-store.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-host-sdk-store.unit.spec.ts
new file mode 100644
index 00000000000..a0c161eed0c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/lib/use-host-sdk-store.unit.spec.ts
@@ -0,0 +1,94 @@
+import { renderHook } from "@testing-library/react";
+
+import { getSdkStore } from "embedding-sdk-bundle/store";
+import { initAuth } from "embedding-sdk-bundle/store/auth/auth";
+import { setPluginsReady } from "embedding-sdk-bundle/store/reducer";
+import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";
+import { SdkLoadingState } from "embedding-sdk-shared/types/sdk-loading";
+
+import { useHostSdkStore } from "./use-host-sdk-store";
+
+jest.mock("embedding-sdk-bundle/store", () => ({ getSdkStore: jest.fn() }));
+jest.mock("embedding-sdk-bundle/store/auth/auth", () => ({
+ initAuth: { fulfilled: { type: "sdk/initAuth/fulfilled" } },
+}));
+jest.mock("embedding-sdk-bundle/store/reducer", () => ({
+ setPluginsReady: jest.fn((ready: boolean) => ({
+ type: "sdk/setPluginsReady",
+ payload: ready,
+ })),
+}));
+jest.mock(
+ "embedding-sdk-shared/lib/ensure-metabase-provider-props-store",
+ () => ({
+ ensureMetabaseProviderPropsStore: jest.fn(),
+ }),
+);
+
+const mockedGetSdkStore = jest.mocked(getSdkStore);
+const mockedEnsurePropsStore = jest.mocked(ensureMetabaseProviderPropsStore);
+
+const setup = (initialProps: Record<string, unknown> = {}) => {
+ const dispatch = jest.fn();
+ // The hook only ever dispatches; faking the rest of the Redux store contract
+ // (getState over the whole SDK state tree, subscribe, replaceReducer) is dead weight.
+ const store = { dispatch } as unknown as ReturnType<typeof getSdkStore>;
+ mockedGetSdkStore.mockReturnValue(store);
+
+ const setProps = jest.fn();
+ const updateInternalProps = jest.fn();
+ mockedEnsurePropsStore.mockReturnValue({
+ setProps,
+ updateInternalProps,
+ getState: () => ({ props: null, internalProps: {} }),
+ subscribe: () => () => undefined,
+ cleanup: () => undefined,
+ });
+
+ const utils = renderHook(({ props }) => useHostSdkStore(props), {
+ initialProps: { props: initialProps },
+ });
+
+ return { store, dispatch, setProps, updateInternalProps, ...utils };
+};
+
+describe("useHostSdkStore", () => {
+ afterEach(() => jest.clearAllMocks());
+
+ it("returns a single SDK store that stays stable across renders", () => {
+ const { result, rerender, store } = setup();
+
+ // Re-render with a changed prop: the store must stay the same instance.
+ rerender({ props: { theme: { colors: {} } } });
+
+ expect(result.current).toBe(store);
+ expect(mockedGetSdkStore).toHaveBeenCalledTimes(1);
+ });
+
+ it("marks the SDK store loaded and resolves auth exactly once", () => {
+ const { rerender, store, dispatch, updateInternalProps } = setup();
+
+ rerender({ props: {} });
+
+ expect(updateInternalProps).toHaveBeenCalledTimes(1);
+ expect(updateInternalProps).toHaveBeenCalledWith({
+ reduxStore: store,
+ loadingState: SdkLoadingState.Loaded,
+ });
+ expect(dispatch).toHaveBeenCalledWith({ type: initAuth.fulfilled.type });
+ expect(dispatch).toHaveBeenCalledWith(setPluginsReady(true));
+ });
+
+ it("forwards the host auth config and the caller's props into the props store", () => {
+ const theme = { colors: {} };
+ const { setProps } = setup({ theme });
+
+ expect(setProps).toHaveBeenCalledWith({
+ authConfig: {
+ isGuest: false,
+ metabaseInstanceUrl: "http://localhost",
+ },
+ theme,
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.ts
new file mode 100644
index 00000000000..cfcc0cac019
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.ts
@@ -0,0 +1,146 @@
+import * as React from "react";
+import * as ReactJsxRuntime from "react/jsx-runtime";
+import * as ReactDOM from "react-dom";
+import * as ReactDOMClient from "react-dom/client";
+import * as ReactDOMServer from "react-dom/server";
+import { pick } from "underscore";
+
+import * as sdkExports from "embedding-sdk-package";
+import * as dataAppExports from "embedding-sdk-package/data-app";
+import { getSubpathSafeUrl } from "metabase/urls";
+import { createDataAppSandbox } from "metabase-enterprise/data_apps/sandbox/sandbox";
+import {
+ DATA_APP_PROVIDER_PROP_KEYS,
+ type DataAppMetabaseProviderProps,
+} from "metabase-enterprise/data_apps/sandbox/types";
+
+export interface LoadedDataApp {
+ component: React.ComponentType<Record<string, unknown>>;
+ providerProps: DataAppMetabaseProviderProps;
+}
+
+/** Response carrying the bundle source plus the app's fetch/XHR allowlist. */
+export interface FetchedDataAppBundle {
+ code: string;
+ /** Origins the sandboxed bundle may fetch/XHR (from `data_app.yaml`). */
+ allowedHosts: string[];
+}
+
+/**
+ * Header the bundle endpoint sets with the app's `allowed_hosts` (JSON array).
+ * Drives the sandbox's fetch/XHR allowlist — see `sandbox/allowed-hosts.ts`.
+ */
+// eslint-disable-next-line metabase/no-literal-metabase-strings -- HTTP response header name, not user-facing
+const ALLOWED_HOSTS_HEADER = "X-Metabase-Data-App-Allowed-Hosts";
+
+const parseAllowedHostsHeader = (res: Response): string[] => {
+ const raw = res.headers.get(ALLOWED_HOSTS_HEADER);
+
+ if (!raw) {
+ return [];
+ }
+
+ try {
+ const parsed: unknown = JSON.parse(raw);
+
+ return Array.isArray(parsed)
+ ? parsed.filter((h): h is string => typeof h === "string")
+ : [];
+ } catch {
+ return [];
+ }
+};
+
+/**
+ * Error thrown when a data-app bundle can't be fetched. `status` carries the
+ * HTTP status (when the request reached the server) so the UI can tell a
+ * not-yet-synced app (404) apart from a genuine failure.
+ */
+export class DataAppBundleError extends Error {
+ status?: number;
+
+ constructor(message: string, status?: number) {
+ super(message);
+
+ this.name = "DataAppBundleError";
+ this.status = status;
+ }
+}
+
+/**
+ * Fetch a data-app bundle's raw JS source plus its fetch/XHR allowlist. Called
+ * from the iframe-top `DataAppIframeApp` after it reads the `:name` from the
+ * URL. Throws a [[DataAppBundleError]] on a transport failure or non-2xx
+ * response.
+ */
+export const fetchDataAppBundleCode = async (
+ name: string,
+): Promise<FetchedDataAppBundle> => {
+ const url = getSubpathSafeUrl(
+ `/api/apps/${encodeURIComponent(name)}/bundle?t=${Date.now()}`,
+ );
+
+ let res: Response;
+ try {
+ res = await fetch(url, { cache: "no-store" });
+ } catch (e) {
+ throw new DataAppBundleError(
+ `Failed to reach the server for data-app bundle: ${
+ e instanceof Error ? e.message : String(e)
+ }`,
+ );
+ }
+
+ if (!res.ok) {
+ throw new DataAppBundleError(
+ `Failed to fetch data-app bundle: HTTP ${res.status}`,
+ res.status,
+ );
+ }
+
+ return { code: await res.text(), allowedHosts: parseAllowedHostsHeader(res) };
+};
+
+/**
+ * Build a Near Membrane sandbox bound to `targetWindow` and evaluate the
+ * bundle inside it. With the iframe-top app architecture, `targetWindow` is
+ * the iframe's own `window` — same realm as the React tree rendering the
+ * factory's component, so no cross-document mounting.
+ */
+export const instantiateDataAppBundle = (
+ code: string,
+ label: string,
+ targetWindow: Window & typeof globalThis,
+ allowedHosts: string[] = [],
+): LoadedDataApp => {
+ const sandbox = createDataAppSandbox({
+ label,
+ targetWindow,
+ allowedHosts,
+ endowments: {
+ React,
+ reactDom: ReactDOM,
+ reactDomClient: ReactDOMClient,
+ reactDomServer: ReactDOMServer,
+ reactJsxRuntime: ReactJsxRuntime,
+ sdkExports,
+ dataAppExports,
+ },
+ });
+ const factory = sandbox.evaluate(code);
+
+ const def = factory();
+
+ if (!def || typeof def.component !== "function") {
+ throw new Error(
+ "Factory return value is missing a `component` function (expected { component, providerProps? })",
+ );
+ }
+
+ const providerProps = pick(
+ def.providerProps ?? {},
+ ...DATA_APP_PROVIDER_PROP_KEYS,
+ );
+
+ return { component: def.component, providerProps };
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.unit.spec.ts
new file mode 100644
index 00000000000..b6f9bbb82ce
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/runtime/loader.unit.spec.ts
@@ -0,0 +1,146 @@
+import { createDataAppSandbox } from "metabase-enterprise/data_apps/sandbox/sandbox";
+
+import {
+ DataAppBundleError,
+ fetchDataAppBundleCode,
+ instantiateDataAppBundle,
+} from "./loader";
+
+jest.mock("metabase-enterprise/data_apps/sandbox/sandbox", () => ({
+ ...jest.requireActual("metabase-enterprise/data_apps/sandbox/sandbox"),
+ createDataAppSandbox: jest.fn(),
+}));
+
+const ALLOWED_HOSTS_HEADER = "X-Metabase-Data-App-Allowed-Hosts";
+
+const mockedCreateSandbox = jest.mocked(createDataAppSandbox);
+
+describe("fetchDataAppBundleCode", () => {
+ const originalFetch = global.fetch;
+
+ const setup = (response: Response | Error) => {
+ const fetchMock = jest.fn(
+ (_input: RequestInfo | URL, _init?: RequestInit) =>
+ response instanceof Error
+ ? Promise.reject(response)
+ : Promise.resolve(response),
+ );
+
+ global.fetch = fetchMock;
+
+ return { fetchMock };
+ };
+
+ afterEach(() => {
+ global.fetch = originalFetch;
+ jest.clearAllMocks();
+ });
+
+ it("requests the bundle endpoint with cache disabled and the name encoded", async () => {
+ const { fetchMock } = setup(new Response("CODE"));
+
+ await fetchDataAppBundleCode("my app");
+
+ const [url, init] = fetchMock.mock.calls[0];
+
+ expect(url).toContain("/api/apps/my%20app/bundle");
+ expect(init).toEqual({ cache: "no-store" });
+ });
+
+ it.each<[string, string | undefined, string[]]>([
+ [
+ "a JSON array",
+ JSON.stringify(["https://api.example.com", "https://*.acme.com"]),
+ ["https://api.example.com", "https://*.acme.com"],
+ ],
+ ["absent", undefined, []],
+ ["invalid JSON", "{", []],
+ ["a non-array value", JSON.stringify({ nope: true }), []],
+ [
+ "mixed entries (non-strings dropped)",
+ JSON.stringify(["https://ok.com", 42, null]),
+ ["https://ok.com"],
+ ],
+ ])(
+ "returns the code and parses allowed_hosts when the header is %s",
+ async (_desc, header, expected) => {
+ setup(
+ new Response(
+ "CODE",
+ header === undefined
+ ? undefined
+ : { headers: { [ALLOWED_HOSTS_HEADER]: header } },
+ ),
+ );
+
+ await expect(fetchDataAppBundleCode("demo")).resolves.toEqual({
+ code: "CODE",
+ allowedHosts: expected,
+ });
+ },
+ );
+
+ it("throws a DataAppBundleError carrying the HTTP status on a non-2xx response", async () => {
+ setup(new Response("nope", { status: 404 }));
+
+ await expect(fetchDataAppBundleCode("demo")).rejects.toMatchObject({
+ name: "DataAppBundleError",
+ status: 404,
+ });
+ });
+
+ it("throws a DataAppBundleError with no status when the request never reaches the server", async () => {
+ setup(new Error("offline"));
+
+ const error = await fetchDataAppBundleCode("demo").catch((e) => e);
+ expect(error).toBeInstanceOf(DataAppBundleError);
+ expect(error.status).toBeUndefined();
+ expect(error.message).toMatch(/Failed to reach the server/);
+ });
+});
+
+describe("instantiateDataAppBundle", () => {
+ const setup = (factoryResult: unknown) => {
+ mockedCreateSandbox.mockReturnValue({
+ // @ts-expect-error - the factory result is deliberately untyped: these tests
+ // feed the loader malformed values (`null`, a non-function `component`).
+ evaluate: () => () => factoryResult,
+ });
+
+ return {
+ instantiate: () => instantiateDataAppBundle("code", "demo", window, []),
+ };
+ };
+
+ afterEach(() => jest.clearAllMocks());
+
+ it("returns the component and narrows providerProps to the allowed keys", () => {
+ const component = () => null;
+ const { instantiate } = setup({
+ component,
+ providerProps: {
+ theme: { colors: {} },
+ allowedCustomVisualizations: ["funnel"],
+ // Not an allowed key — must be dropped.
+ authConfig: { metabaseInstanceUrl: "https://evil" },
+ },
+ });
+
+ const loaded = instantiate();
+
+ expect(loaded.component).toBe(component);
+ expect(loaded.providerProps).toEqual({
+ theme: { colors: {} },
+ allowedCustomVisualizations: ["funnel"],
+ });
+ });
+
+ it.each<unknown>([{ component: "not a function" }, null])(
+ "throws when the factory returns %p",
+ (factoryResult) => {
+ const { instantiate } = setup(factoryResult);
+
+ expect(instantiate).toThrow(/missing a `component` function/);
+ },
+ );
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.ts
new file mode 100644
index 00000000000..e7244407ae6
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.ts
@@ -0,0 +1,206 @@
+/**
+ * Per-app fetch/XHR allowlist for the data-app Near-Membrane sandbox.
+ *
+ * By default the sandbox hard-blocks all network egress (see
+ * `metabase/utils/scripts-sandbox/distortions-blocked-apis`). When an app
+ * declares `allowed_hosts` in its `data_app.yaml`, those origins — and ONLY
+ * those, never the Metabase origin, which stays reachable only via sanctioned
+ * SDK calls — become reachable through `fetch`/`XMLHttpRequest`. Host matching
+ * mirrors the CSP `connect-src` the backend emits for the same hosts, so the JS
+ * layer and the browser CSP layer agree.
+ *
+ * The wildcard semantics (`*.example.com` matches subdomains, not the apex)
+ * intentionally match the backend's `approved-domain?`
+ * (`metabase.server.middleware.security`, used for embedding-origin allowlists).
+ * There's no shared implementation — that one is Clojure, this runs in the
+ * sandboxed browser realm — so keep the two in sync if either changes.
+ */
+
+/**
+ * The slice of the sandbox's realm the network wrappers touch: the native
+ * `fetch`/`XMLHttpRequest` they wrap, and the location a relative request URL
+ * resolves against. A real `Window & typeof globalThis` satisfies it.
+ */
+export interface SandboxRealm {
+ fetch: typeof fetch;
+ XMLHttpRequest: typeof XMLHttpRequest;
+ location: { href: string; origin: string };
+}
+
+interface AllowedOrigin {
+ protocol: string; // "https:" | "http:"
+ wildcard: boolean; // entry was "*.host"
+ host: string; // "example.com" (without the leading "*." when wildcard)
+ port: string; // "" means "any port" (the entry omitted one)
+}
+
+/**
+ * A valid `allowed_hosts` entry is *origin-only*: an http(s) scheme + host (+ an
+ * optional port), with no path, query, fragment, or credentials.
+ */
+function isRawHttpOrigin(url: URL): boolean {
+ return (
+ (url.protocol === "https:" || url.protocol === "http:") &&
+ url.pathname === "/" &&
+ url.search === "" &&
+ url.hash === "" &&
+ url.username === "" &&
+ url.password === ""
+ );
+}
+
+function parseAllowedOrigin(entry: string): AllowedOrigin | null {
+ let url: URL;
+ try {
+ // The standard URL parser lowercases the host, normalizes away the default
+ // port (`:443`/`:80` → ""), and accepts a leading `*.` wildcard. The request
+ // side (`toUrl`) parses the same way, so both stay consistent.
+ url = new URL(entry.trim());
+ } catch {
+ return null;
+ }
+
+ if (!isRawHttpOrigin(url)) {
+ return null;
+ }
+ const wildcard = url.hostname.startsWith("*.");
+ return {
+ protocol: url.protocol,
+ wildcard,
+ host: wildcard ? url.hostname.slice(2) : url.hostname,
+ port: url.port,
+ };
+}
+
+function originMatches(url: URL, origin: AllowedOrigin): boolean {
+ if (url.protocol !== origin.protocol) {
+ return false;
+ }
+ // An entry without a port matches any port; with one, it must match exactly.
+ if (origin.port && url.port !== origin.port) {
+ return false;
+ }
+ const host = url.hostname.toLowerCase();
+ // `*.example.com` matches any subdomain but not the apex (same as CSP).
+ return origin.wildcard
+ ? host.endsWith(`.${origin.host}`)
+ : host === origin.host;
+}
+
+export function isHostAllowed(url: URL, allowedHosts: string[]): boolean {
+ return allowedHosts.some((entry) => {
+ const origin = parseAllowedOrigin(entry);
+ return origin ? originMatches(url, origin) : false;
+ });
+}
+
+function toUrl(input: unknown, base: string): URL | null {
+ try {
+ if (typeof input === "string") {
+ return new URL(input, base);
+ }
+ if (input instanceof URL) {
+ return new URL(input.href, base);
+ }
+ if (typeof Request !== "undefined" && input instanceof Request) {
+ return new URL(input.url, base);
+ }
+ } catch {
+ // unparseable → treated as not-allowed by the callers below
+ }
+ return null;
+}
+
+/**
+ * The single decision the `fetch` and `XMLHttpRequest` wrappers share: resolve
+ * the request URL and decide whether the sandbox may make it. Returns `null`
+ * when the request is allowed, or a human-readable reason when it is blocked.
+ *
+ * A request is allowed only when its origin is in `allowedHosts` AND is not the
+ * Metabase origin — raw access to Metabase is *always* denied (the SDK is the
+ * sanctioned channel), even if an admin mistakenly lists it in `allowed_hosts`.
+ */
+function blockedReason(
+ input: unknown,
+ base: string,
+ allowedHosts: string[],
+ metabaseOrigin: string,
+): string | null {
+ const url = toUrl(input, base);
+ if (!url) {
+ return "an unparseable URL";
+ }
+ if (url.origin === metabaseOrigin) {
+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- developer-facing sandbox diagnostic, not localized UI
+ return `${url.origin} (the Metabase origin is reachable only via the SDK)`;
+ }
+ if (!isHostAllowed(url, allowedHosts)) {
+ return `${url.host} (not in allowed_hosts)`;
+ }
+ return null;
+}
+
+/**
+ * A `fetch` that only reaches `allowedHosts` (rejecting everything else,
+ * including the Metabase origin). Returns `null` when the allowlist is empty so
+ * the caller keeps the sandbox's default hard block.
+ */
+export function makeSandboxFetch(
+ targetWindow: SandboxRealm,
+ allowedHosts: string[],
+ label: string,
+): typeof fetch | null {
+ if (allowedHosts.length === 0) {
+ return null;
+ }
+ const realFetch = targetWindow.fetch.bind(targetWindow);
+ const base = targetWindow.location.href;
+ const metabaseOrigin = targetWindow.location.origin;
+ return function dataAppFetch(input: RequestInfo | URL, init?: RequestInit) {
+ const reason = blockedReason(input, base, allowedHosts, metabaseOrigin);
+ if (reason) {
+ return Promise.reject(
+ new Error(`[data-app ${label}] blocked fetch to ${reason}`),
+ );
+ }
+ return realFetch(input, init);
+ };
+}
+
+/**
+ * An `XMLHttpRequest` subclass that gates `open()` against `allowedHosts` (and
+ * always denies the Metabase origin). Returns `null` when the allowlist is empty
+ * (keeps the default hard block).
+ */
+export function makeSandboxXhr(
+ targetWindow: SandboxRealm,
+ allowedHosts: string[],
+ label: string,
+): typeof XMLHttpRequest | null {
+ if (allowedHosts.length === 0) {
+ return null;
+ }
+ const NativeXhr = targetWindow.XMLHttpRequest;
+ const base = targetWindow.location.href;
+ const metabaseOrigin = targetWindow.location.origin;
+ const SandboxXhr = class extends NativeXhr {
+ open(
+ method: string,
+ url: string | URL,
+ async: boolean = true,
+ username?: string | null,
+ password?: string | null,
+ ): void {
+ const reason = blockedReason(url, base, allowedHosts, metabaseOrigin);
+ if (reason) {
+ throw new Error(
+ `[data-app ${label}] blocked XMLHttpRequest to ${reason}`,
+ );
+ }
+ super.open(method, url, async, username, password);
+ }
+ };
+ // The subclass inherits the static UNSENT/OPENED/… constants at runtime;
+ // cast so the type matches the native constructor the membrane expects.
+ return SandboxXhr as typeof XMLHttpRequest;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.unit.spec.ts
new file mode 100644
index 00000000000..68ab1da3391
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/allowed-hosts.unit.spec.ts
@@ -0,0 +1,171 @@
+import {
+ type SandboxRealm,
+ isHostAllowed,
+ makeSandboxFetch,
+ makeSandboxXhr,
+} from "./allowed-hosts";
+
+const u = (href: string) => new URL(href);
+
+describe("isHostAllowed", () => {
+ it("matches an exact host (ignoring path)", () => {
+ expect(
+ isHostAllowed(u("https://api.example.com/v1/x"), [
+ "https://api.example.com",
+ ]),
+ ).toBe(true);
+ });
+
+ it("rejects a different host", () => {
+ expect(
+ isHostAllowed(u("https://evil.example.org/"), [
+ "https://api.example.com",
+ ]),
+ ).toBe(false);
+ });
+
+ it("rejects a protocol mismatch", () => {
+ expect(
+ isHostAllowed(u("http://api.example.com/"), ["https://api.example.com"]),
+ ).toBe(false);
+ });
+
+ it("matches subdomains for a wildcard but not the apex", () => {
+ const allow = ["https://*.example.com"];
+ expect(isHostAllowed(u("https://a.example.com/"), allow)).toBe(true);
+ expect(isHostAllowed(u("https://a.b.example.com/"), allow)).toBe(true);
+ expect(isHostAllowed(u("https://example.com/"), allow)).toBe(false);
+ expect(isHostAllowed(u("https://notexample.com/"), allow)).toBe(false);
+ });
+
+ it("matches an explicit port exactly; an entry without a port matches any", () => {
+ expect(
+ isHostAllowed(u("https://api.example.com:8443/"), [
+ "https://api.example.com:8443",
+ ]),
+ ).toBe(true);
+ expect(
+ isHostAllowed(u("https://api.example.com:9999/"), [
+ "https://api.example.com:8443",
+ ]),
+ ).toBe(false);
+ // an entry without a port matches any port
+ expect(
+ isHostAllowed(u("https://api.example.com:8443/"), [
+ "https://api.example.com",
+ ]),
+ ).toBe(true);
+ });
+
+ it("treats an explicit default port the same as none (agrees with CSP)", () => {
+ // `URL` strips the default port (`:443`/`:80` → ""), so an entry that spells
+ // it out must still match a default-port request — otherwise the JS allowlist
+ // would disagree with the browser's CSP matching.
+ expect(
+ isHostAllowed(u("https://api.example.com/"), [
+ "https://api.example.com:443",
+ ]),
+ ).toBe(true);
+ expect(
+ isHostAllowed(u("http://api.example.com/"), [
+ "http://api.example.com:80",
+ ]),
+ ).toBe(true);
+ });
+
+ it("denies everything for an empty allowlist", () => {
+ expect(isHostAllowed(u("https://api.example.com/"), [])).toBe(false);
+ });
+});
+
+describe("makeSandboxFetch", () => {
+ const base = "https://mb.example.com/embed/apps/sales";
+ const origin = "https://mb.example.com";
+
+ const fakeWindow = (fetch: typeof global.fetch): SandboxRealm => ({
+ fetch,
+ XMLHttpRequest,
+ location: { href: base, origin },
+ });
+
+ it("returns null for an empty allowlist (keeps the sandbox hard block)", () => {
+ expect(makeSandboxFetch(window, [], "sales")).toBeNull();
+ });
+
+ it("allows listed hosts and blocks others", async () => {
+ const realFetch = jest.fn(() => Promise.resolve(new Response("ok")));
+ const sandboxFetch = makeSandboxFetch(
+ fakeWindow(realFetch),
+ ["https://api.example.com"],
+ "sales",
+ );
+ expect(sandboxFetch).not.toBeNull();
+
+ await sandboxFetch!("https://api.example.com/data");
+ expect(realFetch).toHaveBeenCalledTimes(1);
+
+ await expect(sandboxFetch!("https://evil.example.org/")).rejects.toThrow(
+ /blocked fetch/,
+ );
+ expect(realFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it("always blocks the Metabase origin, even if it's in allowed_hosts", async () => {
+ const realFetch = jest.fn(() => Promise.resolve(new Response("ok")));
+ // The Metabase origin is mistakenly allowlisted — it must still be denied.
+ const sandboxFetch = makeSandboxFetch(
+ fakeWindow(realFetch),
+ [origin, "https://api.example.com"],
+ "sales",
+ )!;
+
+ await expect(sandboxFetch(`${origin}/api/user/current`)).rejects.toThrow(
+ /Metabase origin/,
+ );
+ // A relative URL resolves to the Metabase origin too.
+ await expect(sandboxFetch("/api/user/current")).rejects.toThrow(
+ /Metabase origin/,
+ );
+ expect(realFetch).not.toHaveBeenCalled();
+ });
+});
+
+describe("makeSandboxXhr", () => {
+ // jsdom's window origin is http://localhost — treat that as the Metabase origin.
+ const mbOrigin = window.location.origin;
+
+ it("returns null for an empty allowlist", () => {
+ expect(makeSandboxXhr(window, [], "sales")).toBeNull();
+ });
+
+ it("gates open() against the allowlist", () => {
+ const SandboxXhr = makeSandboxXhr(
+ window,
+ ["https://api.example.com"],
+ "sales",
+ );
+ expect(SandboxXhr).not.toBeNull();
+
+ const xhr = new SandboxXhr!();
+ expect(() => xhr.open("GET", "https://evil.example.org/")).toThrow(
+ /blocked XMLHttpRequest/,
+ );
+ // Allowed host: open() should not throw.
+ expect(() => xhr.open("GET", "https://api.example.com/data")).not.toThrow();
+ });
+
+ it("always blocks the Metabase origin, even if it's in allowed_hosts", () => {
+ const SandboxXhr = makeSandboxXhr(
+ window,
+ [mbOrigin, "https://api.example.com"],
+ "sales",
+ )!;
+ const xhr = new SandboxXhr();
+ expect(() => xhr.open("GET", `${mbOrigin}/api/user/current`)).toThrow(
+ /Metabase origin/,
+ );
+ expect(() => xhr.open("GET", "/api/user/current")).toThrow(
+ /Metabase origin/,
+ );
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.ts
new file mode 100644
index 00000000000..057ab52e82f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.ts
@@ -0,0 +1,89 @@
+import {
+ CREATE_ELEMENT,
+ CREATE_ELEMENT_NS,
+} from "metabase/utils/scripts-sandbox/distortions-dom-mutate";
+
+const isStyleTag = (tag: string) => tag.toLowerCase() === "style";
+
+function isStyleQualifiedName(qualifiedName: string) {
+ const localName = qualifiedName.includes(":")
+ ? qualifiedName.slice(qualifiedName.indexOf(":") + 1)
+ : qualifiedName;
+
+ return isStyleTag(localName);
+}
+
+/** The shared sandbox distortion callback, as the membrane types it. */
+type SharedDistortion = (value: object) => object;
+
+export function makeCreateElementDistortion(
+ value: typeof CREATE_ELEMENT,
+ shared: SharedDistortion,
+): typeof CREATE_ELEMENT;
+export function makeCreateElementDistortion(
+ value: typeof CREATE_ELEMENT_NS,
+ shared: SharedDistortion,
+): typeof CREATE_ELEMENT_NS;
+export function makeCreateElementDistortion(
+ value: object,
+ shared: SharedDistortion,
+): object | null;
+export function makeCreateElementDistortion(
+ value: object,
+ shared: SharedDistortion,
+): object | null {
+ if (value === CREATE_ELEMENT) {
+ // A distortion callback is typed `object -> object` (the membrane erases the
+ // call signature), so restore the signature of the ref it stands in for.
+ const sharedCreateElement = shared(value) as typeof CREATE_ELEMENT;
+
+ return function createElement(
+ this: Document,
+ tag: string,
+ options?: ElementCreationOptions,
+ ) {
+ // Data-app bundles inline imported CSS with
+ // `vite-plugin-css-injected-by-js`, which creates a `<style>` tag at
+ // runtime. Allow only that tag while keeping the shared dangerous-tag
+ // blocklist for `script` and other DOM creation.
+ if (isStyleTag(tag)) {
+ return CREATE_ELEMENT.call(this, tag, options);
+ }
+
+ return sharedCreateElement.call(this, tag, options);
+ };
+ }
+
+ if (value === CREATE_ELEMENT_NS) {
+ // Same signature restoration as above: `shared` hands back a drop-in
+ // replacement for `createElementNS`, typed only as `object`.
+ const sharedCreateElementNS = shared(value) as typeof CREATE_ELEMENT_NS;
+
+ return function createElementNS(
+ this: Document,
+ namespaceURI: string | null,
+ qualifiedName: string,
+ options?: ElementCreationOptions,
+ ) {
+ if (isStyleQualifiedName(qualifiedName)) {
+ // Same exception as `createElement("style")`, but for namespaced
+ // creation paths.
+ return CREATE_ELEMENT_NS.call(
+ this,
+ namespaceURI,
+ qualifiedName,
+ options,
+ );
+ }
+
+ return sharedCreateElementNS.call(
+ this,
+ namespaceURI,
+ qualifiedName,
+ options,
+ );
+ };
+ }
+
+ return null;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.unit.spec.ts
new file mode 100644
index 00000000000..f4b1620b233
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/create-element.unit.spec.ts
@@ -0,0 +1,92 @@
+import {
+ CREATE_ELEMENT,
+ CREATE_ELEMENT_NS,
+} from "metabase/utils/scripts-sandbox/distortions-dom-mutate";
+
+import { makeCreateElementDistortion } from "./create-element";
+
+// In production `shared` is the custom-viz sandbox distortion callback
+// (`makeSandboxDistortionCallback` from `metabase/utils/scripts-sandbox`) — the
+// same dangerous-tag blocklist custom-viz uses. Here it's stubbed so these tests
+// assert the delegation contract (non-<style> tags fall back to `shared`, with
+// the tag/options forwarded and its result returned); the blocklist behaviour
+// itself is covered by scripts-sandbox's own tests.
+const setup = (sentinel?: unknown) => {
+ const sharedImpl = jest.fn(() => sentinel);
+ const shared = jest.fn(() => sharedImpl);
+
+ return { shared, sharedImpl };
+};
+
+describe("makeCreateElementDistortion", () => {
+ it("returns null for values that aren't createElement / createElementNS", () => {
+ const { shared } = setup();
+
+ expect(makeCreateElementDistortion({}, shared)).toBeNull();
+ expect(shared).not.toHaveBeenCalled();
+ });
+
+ describe("createElement", () => {
+ it("allows <style> through the native creator (bundled CSS injection)", () => {
+ const { shared, sharedImpl } = setup();
+ const create = makeCreateElementDistortion(CREATE_ELEMENT, shared);
+
+ const el = create.call(document, "style");
+
+ expect(el).toBeInstanceOf(HTMLStyleElement);
+ expect(sharedImpl).not.toHaveBeenCalled();
+ });
+
+ it("delegates non-style tags to the shared (blocklisted) creator", () => {
+ const sentinel = document.createElement("div");
+ const { shared, sharedImpl } = setup(sentinel);
+ const create = makeCreateElementDistortion(CREATE_ELEMENT, shared);
+
+ const options = { is: "custom-el" };
+ const el = create.call(document, "script", options);
+
+ expect(shared).toHaveBeenCalledWith(CREATE_ELEMENT);
+ expect(sharedImpl).toHaveBeenCalledWith("script", options);
+ expect(el).toBe(sentinel);
+ });
+ });
+
+ describe("createElementNS", () => {
+ it("allows namespaced <style> through the native creator", () => {
+ const { shared, sharedImpl } = setup();
+ const create = makeCreateElementDistortion(CREATE_ELEMENT_NS, shared);
+
+ const el = create.call(
+ document,
+ "http://www.w3.org/1999/xhtml",
+ "html:style",
+ );
+
+ expect(el).toBeInstanceOf(HTMLStyleElement);
+ expect(sharedImpl).not.toHaveBeenCalled();
+ });
+
+ it("delegates non-style qualified names to the shared creator", () => {
+ const sentinel = document.createElementNS(
+ "http://www.w3.org/2000/svg",
+ "svg",
+ );
+ const { shared, sharedImpl } = setup(sentinel);
+ const create = makeCreateElementDistortion(CREATE_ELEMENT_NS, shared);
+
+ const el = create.call(
+ document,
+ "http://www.w3.org/2000/svg",
+ "svg:script",
+ );
+
+ expect(shared).toHaveBeenCalledWith(CREATE_ELEMENT_NS);
+ expect(sharedImpl).toHaveBeenCalledWith(
+ "http://www.w3.org/2000/svg",
+ "svg:script",
+ undefined,
+ );
+ expect(el).toBe(sentinel);
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.ts
new file mode 100644
index 00000000000..f0ddc0c7aca
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.ts
@@ -0,0 +1,59 @@
+import { makeSandboxDistortionCallback } from "metabase/utils/scripts-sandbox";
+
+import {
+ type SandboxRealm,
+ makeSandboxFetch,
+ makeSandboxXhr,
+} from "./allowed-hosts";
+import { makeCreateElementDistortion } from "./create-element";
+
+/**
+ * Data-app Near Membrane distortion callback.
+ *
+ * Reuses the shared callback from `utils/scripts-sandbox` — same blocking of
+ * fetch/XHR/etc., same DOM-mutation sanitization, same dangerous-tag /
+ * inline-handler / `javascript:`-URL filters as custom-viz — but, unlike
+ * custom-viz, replaces the hard `fetch`/`XMLHttpRequest` block with an
+ * allowlist when the app declares `allowed_hosts`. With no `allowed_hosts`
+ * the wrappers are null and we fall through to the shared hard block, so the
+ * default posture stays "no network".
+ *
+ * Data-app intentionally omits the per-plugin DOM scoping (decoy nodes
+ * outside a `data-plugin-sandbox` subtree) that custom-viz uses: a data app
+ * is a full-page route owned by a single admin-uploaded bundle, so there's
+ * no sibling DOM to protect from.
+ */
+export function makeDistortionCallback(
+ label: string,
+ targetWindow: SandboxRealm,
+ allowedHosts: string[],
+) {
+ const shared = makeSandboxDistortionCallback(
+ `data-app ${label}`,
+ (message) => {
+ // The thrown error usually reaches the developer only as an opaque
+ // cross-realm `#<Object>` (an unhandled async rejection), so log the real
+ // reason here — at the block point, where the console stack still points at
+ // the data-app code that called the blocked API.
+ console.error(message);
+ },
+ );
+ const sandboxFetch = makeSandboxFetch(targetWindow, allowedHosts, label);
+ const sandboxXhr = makeSandboxXhr(targetWindow, allowedHosts, label);
+
+ return function distortionCallback(value: object): object {
+ const createElementDistortion = makeCreateElementDistortion(value, shared);
+
+ if (createElementDistortion) {
+ return createElementDistortion;
+ }
+
+ if (sandboxFetch && value === targetWindow.fetch) {
+ return sandboxFetch;
+ }
+ if (sandboxXhr && value === targetWindow.XMLHttpRequest) {
+ return sandboxXhr;
+ }
+ return shared(value);
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.unit.spec.ts
new file mode 100644
index 00000000000..dcbbe60e4c2
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/distortions.unit.spec.ts
@@ -0,0 +1,100 @@
+import type { SandboxRealm } from "./allowed-hosts";
+import { makeDistortionCallback } from "./distortions";
+
+// A minimal stand-in for the iframe window the data-app sandbox is built on.
+// `fetch`/`XMLHttpRequest` are the native refs the membrane passes to the
+// distortion callback; `makeDistortionCallback` should route those to the
+// allowlist wrappers and delegate everything else to the shared callback.
+const fakeWindow = (): SandboxRealm => ({
+ fetch: async () => new Response("native"),
+ XMLHttpRequest: class NativeXHR extends XMLHttpRequest {},
+ location: {
+ href: "https://mb.example.com/embed/apps/sales",
+ origin: "https://mb.example.com",
+ },
+});
+
+describe("makeDistortionCallback", () => {
+ it("allows style elements for bundled CSS injection", () => {
+ const win = fakeWindow();
+ const callback = makeDistortionCallback("sales", win, []);
+ // The membrane types a distortion as `object -> object`, erasing the call
+ // signature of the native ref it replaces — restore it to invoke it.
+ const createElement = callback(
+ Document.prototype.createElement,
+ ) as typeof Document.prototype.createElement;
+
+ expect(() => createElement.call(document, "style")).not.toThrow();
+ });
+
+ it("keeps the shared dangerous-tag blocklist for non-style elements", () => {
+ const consoleErrorSpy = jest
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+ const win = fakeWindow();
+ const callback = makeDistortionCallback("sales", win, []);
+ // Same signature erasure as above.
+ const createElement = callback(
+ Document.prototype.createElement,
+ ) as typeof Document.prototype.createElement;
+
+ expect(() => createElement.call(document, "script")).toThrow(
+ "[data-app sales] blocked createElement: script",
+ );
+ consoleErrorSpy.mockRestore();
+ });
+
+ it("routes window.fetch to the allowlisted wrapper when allowed_hosts is set", async () => {
+ const win = fakeWindow();
+ const realFetch = jest.fn(() => Promise.resolve(new Response("ok")));
+ win.fetch = realFetch;
+
+ const callback = makeDistortionCallback("sales", win, [
+ "https://api.example.com",
+ ]);
+ // Same signature erasure as above.
+ const distorted = callback(win.fetch) as typeof fetch;
+
+ // Not the native fetch — a wrapper that enforces the allowlist.
+ expect(distorted).not.toBe(win.fetch);
+ await expect(distorted("https://evil.example.org/")).rejects.toThrow(
+ /blocked fetch/,
+ );
+ await distorted("https://api.example.com/data");
+ expect(realFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it("routes window.XMLHttpRequest to the allowlisted subclass when allowed_hosts is set", () => {
+ const win = fakeWindow();
+ const callback = makeDistortionCallback("sales", win, [
+ "https://api.example.com",
+ ]);
+ // Same signature erasure as above: the membrane hands the constructor back
+ // as a bare `object`.
+ const Distorted = callback(win.XMLHttpRequest) as typeof XMLHttpRequest;
+
+ expect(Distorted).not.toBe(win.XMLHttpRequest);
+ const xhr = new Distorted();
+ expect(() => xhr.open("GET", "https://evil.example.org/")).toThrow(
+ /blocked XMLHttpRequest/,
+ );
+ });
+
+ it("does not wrap fetch/XHR when allowed_hosts is empty (shared hard block stands)", () => {
+ const win = fakeWindow();
+ const callback = makeDistortionCallback("sales", win, []);
+ // No wrapper is installed; the value passes through to the shared callback,
+ // whose default-deny block of fetch/XHR is covered by the shared module.
+ expect(callback(win.fetch)).toBe(win.fetch);
+ expect(callback(win.XMLHttpRequest)).toBe(win.XMLHttpRequest);
+ });
+
+ it("delegates non-network values to the shared callback", () => {
+ const win = fakeWindow();
+ const callback = makeDistortionCallback("sales", win, [
+ "https://api.example.com",
+ ]);
+ const other = { some: "object" };
+ expect(callback(other)).toBe(other);
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/globals.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/globals.ts
new file mode 100644
index 00000000000..d528b7cd3c2
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/globals.ts
@@ -0,0 +1,36 @@
+/**
+ * The single source of truth for the globals the data-app bundle is built
+ * against. The app is built as one IIFE that assigns its factory to
+ * `DATA_APP_FACTORY_GLOBAL`, with React + the SDK left external and mapped to
+ * these names; the host's `createDataAppSandbox` (`./sandbox.ts`) endows
+ * exactly these names — both sides import this map so the build-time and
+ * runtime contracts can't drift.
+ */
+export const DATA_APP_GLOBAL_NAMES = {
+ react: "React",
+ reactDom: "__react_dom__",
+ reactDomClient: "__react_dom_client__",
+ reactDomServer: "__react_dom_server__",
+ reactJsxRuntime: "__react_jsx_runtime__",
+ reactJsxDevRuntime: "__react_jsx_dev_runtime__",
+ sdk: "__metabase_sdk__",
+ dataApp: "__metabase_data_app__",
+ factory: "__dataAppFactory__",
+} as const;
+
+export const DATA_APP_FACTORY_GLOBAL = DATA_APP_GLOBAL_NAMES.factory;
+
+/** Each externalized import mapped to the global the sandbox endows it as. */
+export const DATA_APP_GLOBALS: Record<string, string> = {
+ react: DATA_APP_GLOBAL_NAMES.react,
+ "react-dom": DATA_APP_GLOBAL_NAMES.reactDom,
+ "react-dom/client": DATA_APP_GLOBAL_NAMES.reactDomClient,
+ "react-dom/server": DATA_APP_GLOBAL_NAMES.reactDomServer,
+ "react/jsx-runtime": DATA_APP_GLOBAL_NAMES.reactJsxRuntime,
+ "react/jsx-dev-runtime": DATA_APP_GLOBAL_NAMES.reactJsxDevRuntime,
+ "@metabase/embedding-sdk-react": DATA_APP_GLOBAL_NAMES.sdk,
+ "@metabase/embedding-sdk-react/data-app": DATA_APP_GLOBAL_NAMES.dataApp,
+};
+
+/** The imports kept external, derived from `DATA_APP_GLOBALS` so the two can't drift. */
+export const DATA_APP_EXTERNALS: string[] = Object.keys(DATA_APP_GLOBALS);
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/iframe-baseline.css b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/iframe-baseline.css
new file mode 100644
index 00000000000..ecf0c3922da
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/iframe-baseline.css
@@ -0,0 +1,14 @@
+html,
+body,
+#root {
+ height: 100%;
+ margin: 0;
+}
+
+body {
+ font-family:
+ system-ui,
+ -apple-system,
+ "Segoe UI",
+ sans-serif;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.ts
new file mode 100644
index 00000000000..dbb5385a3b0
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.ts
@@ -0,0 +1,134 @@
+import createVirtualEnvironment from "@locker/near-membrane-dom";
+
+import { makeDistortionCallback } from "./distortions";
+import { DATA_APP_GLOBAL_NAMES } from "./globals";
+import type { DataAppFactory } from "./types";
+
+/**
+ * The realm objects the sandbox exposes to the bundle as globals.
+ *
+ * These are injected by the caller rather than imported here so the sandbox
+ * stays decoupled from any single SDK instance: the host passes its own realm's
+ * React/SDK, and the data-app template's dev entry passes the React/SDK from
+ * its installed `@metabase/embedding-sdk-react` — in both cases the bundle runs
+ * against exactly one SDK instance. (Importing them here would bundle a second
+ * SDK copy into the published `data-app-dev` entry.)
+ */
+export interface DataAppSandboxEndowments {
+ /** Endowed as the `React` global the bundle externalizes `react` to. */
+ React: unknown;
+ /** Endowed as `__react_dom__` (the `react-dom` external). */
+ reactDom: unknown;
+ /** Endowed as `__react_dom_client__` (the `react-dom/client` external). */
+ reactDomClient: unknown;
+ /** Endowed as `__react_dom_server__` (the `react-dom/server` external). */
+ reactDomServer: unknown;
+ /** Endowed as `__react_jsx_runtime__` (the `react/jsx-runtime` external). */
+ reactJsxRuntime: unknown;
+ /**
+ * Endowed as `__react_jsx_dev_runtime__` (the `react/jsx-dev-runtime`
+ * external). Only a development-mode bundle references it (jsxDEV), so the
+ * production host can omit it.
+ */
+ reactJsxDevRuntime?: unknown;
+ /** Endowed as `__metabase_sdk__` (the `@metabase/embedding-sdk-react` external). */
+ sdkExports: object;
+ /** Endowed as `__metabase_data_app__` (the `.../data-app` external). */
+ dataAppExports: object;
+}
+
+export interface CreateDataAppSandboxOptions {
+ /** Human-readable label used in sandbox diagnostics, e.g. the app slug. */
+ label?: string;
+ /** Realm the membrane binds to. Defaults to the current `window`. */
+ targetWindow?: Window & typeof globalThis;
+ /** Origins the bundle may fetch/XHR; empty keeps the default hard block. */
+ allowedHosts?: string[];
+ /** The realm's React/SDK exposed to the bundle. See [[DataAppSandboxEndowments]]. */
+ endowments: DataAppSandboxEndowments;
+}
+
+function isLiveTarget(target: object): boolean {
+ return target instanceof CSSStyleDeclaration;
+}
+
+function isDataAppFactory(value: unknown): value is DataAppFactory {
+ return typeof value === "function";
+}
+
+export function createDataAppSandbox({
+ label = "",
+ targetWindow = window,
+ allowedHosts = [],
+ endowments,
+}: CreateDataAppSandboxOptions) {
+ let captured: unknown;
+
+ const env = createVirtualEnvironment(targetWindow, {
+ distortionCallback: makeDistortionCallback(
+ label,
+ targetWindow,
+ allowedHosts,
+ ),
+ liveTargetCallback: isLiveTarget,
+ // Global names come from the shared `DATA_APP_GLOBAL_NAMES`, so the bundle's
+ // externals (defined by the SDK build) and these endowments can't drift.
+ endowments: Object.getOwnPropertyDescriptors({
+ [DATA_APP_GLOBAL_NAMES.react]: endowments.React,
+ [DATA_APP_GLOBAL_NAMES.reactDom]: endowments.reactDom,
+ [DATA_APP_GLOBAL_NAMES.reactDomClient]: endowments.reactDomClient,
+ [DATA_APP_GLOBAL_NAMES.reactDomServer]: endowments.reactDomServer,
+ [DATA_APP_GLOBAL_NAMES.reactJsxRuntime]: endowments.reactJsxRuntime,
+ ...(!!endowments.reactJsxDevRuntime && {
+ [DATA_APP_GLOBAL_NAMES.reactJsxDevRuntime]:
+ endowments.reactJsxDevRuntime,
+ }),
+ [DATA_APP_GLOBAL_NAMES.sdk]: {
+ ...endowments.sdkExports,
+ // Below we can set fallbacks to `sdkExports` exports that were renamed/removed to prevent breaking changes
+ },
+ [DATA_APP_GLOBAL_NAMES.dataApp]: {
+ ...endowments.dataAppExports,
+ // Below we can set fallbacks to `dataAppExports` exports that were renamed/removed to prevent breaking changes
+ },
+ get [DATA_APP_GLOBAL_NAMES.factory]() {
+ return captured;
+ },
+ set [DATA_APP_GLOBAL_NAMES.factory](value: unknown) {
+ captured = value;
+ },
+ }),
+ });
+
+ return {
+ evaluate(code: string): DataAppFactory {
+ try {
+ env.evaluate(code);
+ } catch (error) {
+ let message: string;
+
+ try {
+ // Reading `message` off a membrane-opaque throw can itself throw, so
+ // the read stays inside this try.
+ message = String(
+ typeof error === "object" && error !== null && "message" in error
+ ? (error.message ?? error)
+ : error,
+ );
+ } catch {
+ message = "Unknown error inside data-app sandbox";
+ }
+
+ throw new Error(message);
+ }
+
+ if (!isDataAppFactory(captured)) {
+ throw new Error(
+ "Bundle did not assign a function to __dataAppFactory__",
+ );
+ }
+
+ return captured;
+ },
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.unit.spec.ts
new file mode 100644
index 00000000000..e9015f4a14e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/sandbox.unit.spec.ts
@@ -0,0 +1,134 @@
+import createVirtualEnvironment from "@locker/near-membrane-dom";
+
+import { DATA_APP_GLOBAL_NAMES } from "./globals";
+import { createDataAppSandbox } from "./sandbox";
+
+jest.mock("@locker/near-membrane-dom");
+
+const mockedCreateEnv = jest.mocked(createVirtualEnvironment);
+
+type Endowments = Parameters<typeof createDataAppSandbox>[0]["endowments"];
+type EnvEndowments = Record<string, PropertyDescriptor>;
+
+function baseEndowments(overrides: Partial<Endowments> = {}): Endowments {
+ return {
+ React: { marker: "REACT" },
+ reactDom: {},
+ reactDomClient: {},
+ reactDomServer: {},
+ reactJsxRuntime: {},
+ sdkExports: { marker: "SDK" },
+ dataAppExports: { marker: "DATA_APP" },
+ ...overrides,
+ };
+}
+
+type SetupOpts = {
+ overrides?: Partial<Endowments>;
+ runBundle?: () => void;
+};
+
+function setup({ overrides, runBundle = () => {} }: SetupOpts = {}) {
+ let endowments: EnvEndowments | undefined;
+
+ mockedCreateEnv.mockReset();
+ mockedCreateEnv.mockImplementation((_targetWindow, options) => {
+ endowments = options?.endowments;
+ // `VirtualEnvironment` is a class with a large internal surface (link,
+ // remap, lazyRemapProperties, …); the sandbox only ever calls `evaluate`.
+ return {
+ evaluate: () => runBundle(),
+ } as unknown as ReturnType<typeof createVirtualEnvironment>;
+ });
+
+ const sandbox = createDataAppSandbox({
+ endowments: baseEndowments(overrides),
+ });
+
+ if (!endowments) {
+ throw new Error("createVirtualEnvironment was called without endowments");
+ }
+
+ const endowed = Object.fromEntries(
+ Object.entries(endowments).map(([name, descriptor]) => [
+ name,
+ descriptor.value,
+ ]),
+ );
+
+ return { sandbox, endowed };
+}
+
+describe("createDataAppSandbox", () => {
+ describe("endowment injection", () => {
+ it("endows the React externals under their global names and the SDK/data-app as spread copies", () => {
+ const original = baseEndowments();
+ const { endowed } = setup({ overrides: original });
+
+ expect(endowed).toMatchObject({
+ [DATA_APP_GLOBAL_NAMES.react]: original.React,
+ [DATA_APP_GLOBAL_NAMES.reactDom]: original.reactDom,
+ [DATA_APP_GLOBAL_NAMES.reactDomClient]: original.reactDomClient,
+ [DATA_APP_GLOBAL_NAMES.reactDomServer]: original.reactDomServer,
+ [DATA_APP_GLOBAL_NAMES.reactJsxRuntime]: original.reactJsxRuntime,
+ [DATA_APP_GLOBAL_NAMES.sdk]: original.sdkExports,
+ [DATA_APP_GLOBAL_NAMES.dataApp]: original.dataAppExports,
+ });
+ });
+
+ it("omits the dev jsx-runtime endowment unless one is provided", () => {
+ const withoutDev = setup();
+
+ expect(
+ DATA_APP_GLOBAL_NAMES.reactJsxDevRuntime in withoutDev.endowed,
+ ).toBe(false);
+
+ const reactJsxDevRuntime = { marker: "DEV" };
+ const withDev = setup({ overrides: { reactJsxDevRuntime } });
+
+ expect(withDev.endowed[DATA_APP_GLOBAL_NAMES.reactJsxDevRuntime]).toBe(
+ reactJsxDevRuntime,
+ );
+ });
+ });
+
+ describe("evaluate", () => {
+ it("throws when the bundle never assigns a factory", () => {
+ const { sandbox } = setup();
+
+ expect(() => sandbox.evaluate("code")).toThrow(
+ /did not assign a function/,
+ );
+ });
+
+ it("re-throws an error thrown during evaluation as a host-realm Error", () => {
+ const { sandbox } = setup({
+ runBundle: () => {
+ throw new Error("bundle blew up");
+ },
+ });
+
+ expect(() => sandbox.evaluate("code")).toThrow("bundle blew up");
+ });
+
+ it("falls back to a generic message when the thrown value is unreadable", () => {
+ const { sandbox } = setup({
+ runBundle: () => {
+ // A membrane-opaque throw whose `message` can't be read from the host.
+ throw new Proxy(
+ {},
+ {
+ get() {
+ throw new Error("no access");
+ },
+ },
+ );
+ },
+ });
+
+ expect(() => sandbox.evaluate("code")).toThrow(
+ "Unknown error inside data-app sandbox",
+ );
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/types.ts b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/types.ts
new file mode 100644
index 00000000000..491d82d354f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/types.ts
@@ -0,0 +1,37 @@
+import type * as React from "react";
+
+import type { MetabaseEmbeddingTheme } from "metabase/embedding-sdk/theme";
+import type { SdkErrorComponent } from "metabase/embedding-sdk/types/error-component";
+
+// The MetabaseProvider props a data app may customize.
+export const DATA_APP_PROVIDER_PROP_KEYS = [
+ "theme",
+ "allowedCustomVisualizations",
+ "errorComponent",
+] as const satisfies readonly (keyof DataAppMetabaseProviderProps)[];
+
+/**
+ * Structural mirror of the `MetabaseProviderProps` subset a data app may
+ * customize. Declared here (not as a `Pick` of the bundle type) so this
+ * contract has no app-tier dependency; keep it in sync with
+ * `MetabaseProviderProps` by hand until the props move to a shared tier.
+ */
+export type DataAppMetabaseProviderProps = {
+ theme?: MetabaseEmbeddingTheme;
+ allowedCustomVisualizations?: `custom:${string}`[];
+ errorComponent?: SdkErrorComponent;
+};
+
+/**
+ * The bundle's factory returns:
+ * - `component` — the React tree the host will mount inside its
+ * `DataAppProvider`. Should be pure content; no `<MetabaseProvider>`
+ * inside — the host owns the provider wrap so the SDK store/theme/
+ * portal context live in host realm.
+ * - `providerProps` — the `MetabaseProvider` props the data app wants to
+ * customize (theme, allowedCustomVisualizations, errorComponent).
+ */
+export type DataAppFactory = () => {
+ component: React.ComponentType<Record<string, unknown>>;
+ providerProps?: DataAppMetabaseProviderProps;
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/plugins.ts b/enterprise/frontend/src/metabase-enterprise/plugins.ts
index 9ee0c7b54f6..9c21bc4e651 100644
--- a/enterprise/frontend/src/metabase-enterprise/plugins.ts
+++ b/enterprise/frontend/src/metabase-enterprise/plugins.ts
@@ -21,6 +21,7 @@ import { initializePlugin as initializeContentTranslation } from "./content_tran
import { initializePlugin as initializeContentVerification } from "./content_verification";
import { initializePlugin as initializeCustomViz } from "./custom_viz";
import { initializePlugin as initializeLibrary } from "./data-studio/library";
+import { initializePlugin as initializeDataApps } from "./data_apps";
import { initializePlugin as initializeDatabaseReplication } from "./database_replication";
import { initializePlugin as initializeDatabaseRouting } from "./database_routing";
import { initializePlugin as initializeDependencies } from "./dependencies";
@@ -70,6 +71,7 @@ export function initializePlugins() {
initializeContentTranslation();
initializeContentVerification();
initializeCustomViz();
+ initializeDataApps();
initializeDatabaseRouting();
initializeRemoteSync();
initializeReplacement();
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.ts
index ed80cd53bed..62959252763 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.ts
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/middleware/remote-sync-listener-middleware.ts
@@ -41,6 +41,8 @@ const ALL_INVALIDATION_TAGS = [
tag("collection"),
tag("collection-tree"),
tag("content-translation"),
+ // data apps are materialized as part of the import, so refresh their list too
+ tag("data-app"),
tag("dashboard"),
tag("dashboard-question-candidates"),
tag("document"),
diff --git a/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/ScimInputs.tsx b/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/ScimInputs.tsx
index 4a6bc207bbb..150fc66837f 100644
--- a/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/ScimInputs.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/user_provisioning/components/ScimInputs.tsx
@@ -1,7 +1,7 @@
import { match } from "ts-pattern";
+import type { CopyTextInputProps } from "metabase/common/components/CopyTextInput";
import { CopyTextInput } from "metabase/common/components/CopyTextInput";
-import type { TextInputProps } from "metabase/ui";
import { getThemeOverrides } from "metabase/ui/theme";
// Unjustified type cast. FIXME
@@ -30,7 +30,7 @@ export const getTextInputStyles = (params: {
export const CopyScimInput = ({
disabled = true,
...props
-}: TextInputProps & {
+}: CopyTextInputProps & {
label: string;
value: string;
disabled?: boolean;
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 8693114d85d..b80ede697f7 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -87,6 +87,10 @@ const configs = [
"e2e/tmp/**",
"frontend/test/__support__/custom-viz-fixtures/**/*.js",
"**/custom-viz/fixtures/example_custom_viz_plugin/**",
+ // The data-app dev entry is served verbatim to the consumer's Vite (it
+ // imports `@metabase/embedding-sdk-react/*` + a virtual config module), so
+ // it can't be resolved/linted in this repo.
+ "enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx",
"node_modules/**",
"**/dist/**",
"**/target/**",
diff --git a/frontend/build/embedding-sdk/constants/data-app-virtual-modules.js b/frontend/build/embedding-sdk/constants/data-app-virtual-modules.js
new file mode 100644
index 00000000000..715a563b8ad
--- /dev/null
+++ b/frontend/build/embedding-sdk/constants/data-app-virtual-modules.js
@@ -0,0 +1,27 @@
+/**
+ * Virtual module IDs the data-app dev toolchain exposes. Shared so the SDK's Vite
+ * dev plugin (which resolves + serves them) and the rspack build (which
+ * externalizes the config module and builds the dev entry) can't drift.
+ *
+ * NOTE: import specifiers and `declare module` names must be string literals, so a
+ * couple of places repeat these by hand (`dev-entry.tsx`'s config import and
+ * `vite-env.d.ts`'s `declare module`) — keep them in sync with the values here.
+ */
+
+/**
+ * The dev entry the template's `index.html` imports; the dev plugin serves the
+ * prebuilt bundle for it.
+ *
+ * @type {"virtual:metabase-data-app-dev-entry"}
+ */
+module.exports.DATA_APP_DEV_ENTRY_VIRTUAL_ID =
+ "virtual:metabase-data-app-dev-entry";
+
+/**
+ * The config module the dev plugin generates (the app's allowed hosts + the bundle
+ * URL/event); the dev entry imports it and the rspack build externalizes it.
+ *
+ * @type {"virtual:metabase-data-app-dev-config"}
+ */
+module.exports.DATA_APP_DEV_CONFIG_VIRTUAL_ID =
+ "virtual:metabase-data-app-dev-config";
diff --git a/frontend/lint/module-boundaries.mjs b/frontend/lint/module-boundaries.mjs
index 0829d0f0161..0344fd06eff 100644
--- a/frontend/lint/module-boundaries.mjs
+++ b/frontend/lint/module-boundaries.mjs
@@ -229,6 +229,22 @@ const elements = [
mode: "full",
}),
),
+ // The Near-Membrane sandbox + its ABI (globals map, factory/provider-props
+ // contract). Feature tier on purpose: it's a library consumed by the app-tier
+ // entries (runtime + SDK package dev preset), and the tier guarantees it only
+ // reaches shared/lib — keep the sandbox's dependency surface auditable.
+ createElement({
+ type: "feature",
+ name: "data-app-sandbox",
+ pattern: "enterprise/frontend/src/metabase-enterprise/data_apps/sandbox/**",
+ mode: "full",
+ }),
+ createElement({
+ type: "app",
+ name: "data-app-runtime",
+ pattern: "enterprise/frontend/src/metabase-enterprise/data_apps/runtime/**",
+ mode: "full",
+ }),
createElement({
type: "feature",
name: "enterprise",
diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx
index 11c162f2b54..8c202747747 100644
--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/context/SdkQuestionProvider.tsx
@@ -6,6 +6,7 @@ import {
useMemo,
useState,
} from "react";
+import { match } from "ts-pattern";
import { t } from "ttag";
import { SdkError } from "embedding-sdk-bundle/components/private/PublicComponentWrapper";
@@ -293,6 +294,19 @@ export const SdkQuestionProvider = ({
[updateQuestion],
);
+ // How the user's `navigateToNewCard` prop maps to the context value:
+ // - null → navigation disabled (e.g. StaticQuestion / ad-hoc questions).
+ // Passed through as null; `Visualization` turns it into
+ // `undefined`, so the chart never wires `onChangeCardAndRun`
+ // (which would load a card by its undefined id → `/card/undefined`).
+ // - undefined → the SDK's internal navigation (the default).
+ // - a handler → run through the drill-through wrapper.
+ const contextNavigateToNewCard: SdkQuestionContextType["navigateToNewCard"] =
+ match(userNavigateToNewCard)
+ .with(null, () => null)
+ .with(undefined, () => navigateToNewCardWithSdkInternalNavigation)
+ .otherwise(() => navigateToNewCardWithDrillThrough);
+
const questionContext: SdkQuestionContextType = {
originalId: questionId,
lastVisibleStageIndex,
@@ -307,10 +321,7 @@ export const SdkQuestionProvider = ({
updateQuestion,
updateAndNormalizeQuestion,
updateParameterValues,
- navigateToNewCard:
- userNavigateToNewCard !== undefined
- ? navigateToNewCardWithDrillThrough
- : navigateToNewCardWithSdkInternalNavigation,
+ navigateToNewCard: contextNavigateToNewCard,
plugins,
question,
originalQuestion,
diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts
index 70f6251750a..0c49323ba4d 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts
+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.schema.ts
@@ -4,9 +4,18 @@ import type { FunctionSchema } from "embedding-sdk-bundle/types/schema";
import type { InteractiveQuestionInternalProps } from "./InteractiveQuestion";
-// Typed against the internal shape so runtime validation still accepts the
-// `query` prop used by the `useMetabot` hook. The public API (see
-// `InteractiveQuestionProps`) intentionally doesn't expose `query` to users.
+const hasEntityProp = (
+ props: InteractiveQuestionInternalProps | null | undefined,
+) =>
+ props != null &&
+ (props.questionId !== undefined ||
+ props.token !== undefined ||
+ props.card !== undefined ||
+ props.query !== undefined);
+
+// Typed against the internal shape so runtime validation accepts both the
+// public object `query` prop and the internal string `query` prop used by the
+// `useMetabot` hook.
const propsSchema: Yup.SchemaOf<InteractiveQuestionInternalProps> = Yup.object({
children: Yup.mixed().optional(),
className: Yup.mixed().optional(),
@@ -36,13 +45,9 @@ const propsSchema: Yup.SchemaOf<InteractiveQuestionInternalProps> = Yup.object({
})
.optional()
.noUnknown(),
- questionId: Yup.mixed().when(["token", "query"], {
- is: (token: unknown, query: unknown) =>
- token !== undefined || query !== undefined,
- then: (schema) => schema.optional(),
- otherwise: (schema) => schema.required(),
- }),
+ questionId: Yup.mixed().optional(),
token: Yup.mixed().optional(),
+ card: Yup.mixed().optional(),
query: Yup.mixed().optional(),
style: Yup.mixed().optional(),
targetCollection: Yup.mixed().optional(),
@@ -56,7 +61,13 @@ const propsSchema: Yup.SchemaOf<InteractiveQuestionInternalProps> = Yup.object({
withAlerts: Yup.mixed().optional(),
onDrillThrough: Yup.mixed().optional(),
onVisualizationChange: Yup.mixed().optional(),
-}).noUnknown();
+})
+ .test(
+ "has-entity-prop",
+ "questionId, token, card, or query is required",
+ hasEntityProp,
+ )
+ .noUnknown();
export const interactiveQuestionSchema: FunctionSchema = {
input: [propsSchema],
diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx
index b8bdb5ab985..7a0400eedba 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx
@@ -33,11 +33,11 @@ import {
SdkQuestion,
type SdkQuestionProps,
} from "embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion";
+import { resolveDeserializedCard } from "embedding-sdk-bundle/lib/sdk-question/resolve-deserialized-card";
import type {
SdkQuestionEntityInternalProps,
SdkQuestionEntityPublicProps,
} from "embedding-sdk-bundle/types/question";
-import { deserializeCardFromQuery } from "metabase/common/utils/card";
import { QuestionAlertsButton } from "../notifications/QuestionAlertsButton";
@@ -106,7 +106,9 @@ export type InteractiveQuestionComponents = {
function InteractiveQuestionInner(props: InteractiveQuestionInternalProps) {
const {
query,
+ card,
questionId,
+ token,
title,
withDownloads,
isSaveEnabled,
@@ -115,8 +117,8 @@ function InteractiveQuestionInner(props: InteractiveQuestionInternalProps) {
} = props;
const deserializedCard = useMemo(
- () => (query ? deserializeCardFromQuery(query) : undefined),
- [query],
+ () => resolveDeserializedCard({ card, query }),
+ [card, query],
);
// When rendered via the `query` prop (Metabot `navigate_to`), no questionId is
@@ -159,6 +161,7 @@ function InteractiveQuestionInner(props: InteractiveQuestionInternalProps) {
<SdkQuestion
{...rest}
questionId={resolvedQuestionId}
+ token={token}
title={title}
withDownloads={withDownloads}
isSaveEnabled={isSaveEnabled}
diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx
index abd902f4f7e..bda8245d6d0 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.unit.spec.tsx
@@ -7,6 +7,7 @@ import {
import {
setupAdhocQueryMetadataEndpoint,
setupAlertsEndpoints,
+ setupCardDataset,
setupCardEndpoints,
setupCardQueryEndpoints,
setupCardQueryMetadataEndpoint,
@@ -33,6 +34,7 @@ import {
} from "__support__/ui";
import { addAlertModalTests } from "embedding-sdk-bundle/components/public/question/shared-tests/alert-modal.spec";
import { addAlertsButtonTests } from "embedding-sdk-bundle/components/public/question/shared-tests/alerts-button.spec";
+import { addCardPropTests } from "embedding-sdk-bundle/components/public/question/shared-tests/card-prop.spec";
import type { SetupOpts } from "embedding-sdk-bundle/components/public/question/shared-tests/constants.spec";
import {
TEST_COLUMN,
@@ -51,6 +53,8 @@ import {
createMockCard,
createMockCardQueryMetadata,
createMockCollection,
+ createMockDataset,
+ createMockDatasetData,
createMockModelResult,
createMockTokenFeatures,
createMockUser,
@@ -180,6 +184,7 @@ const setup = async ({
};
addQueryPropTests({ Component: InteractiveQuestionInternal });
+addCardPropTests({ Component: InteractiveQuestion });
describe("InteractiveQuestion", () => {
addAlertsButtonTests(setup, {
@@ -205,6 +210,57 @@ describe("InteractiveQuestion", () => {
).toBeVisible();
});
+ it("should render an ad hoc question from a query-only card object", async () => {
+ const { state } = setupSdkState();
+
+ setupNotificationChannelsEndpoints({ email: { configured: false } });
+ setupAdhocQueryMetadataEndpoint(
+ createMockCardQueryMetadata({ databases: [TEST_DB] }),
+ );
+ setupCardDataset({
+ dataset: createMockDataset({
+ data: createMockDatasetData({
+ cols: [TEST_COLUMN],
+ rows: [["Test Row"], ["Test Row 2"]],
+ }),
+ }),
+ });
+ setupCollectionByIdEndpoint({
+ collections: [createMockCollection({ id: 1 })],
+ });
+
+ renderWithSDKProviders(
+ <InteractiveQuestion
+ card={{
+ query: {
+ type: "query",
+ database: TEST_DB.id,
+ query: { "source-table": TEST_TABLE.id },
+ parameters: [],
+ },
+ }}
+ />,
+ {
+ componentProviderProps: {
+ authConfig: createMockSdkConfig(),
+ },
+ storeInitialState: state,
+ },
+ );
+
+ await waitForLoaderToBeRemoved();
+
+ expect(screen.getByTestId("query-visualization-root")).toBeVisible();
+ expect(
+ within(screen.getByTestId("table-root")).getByText(
+ TEST_COLUMN.display_name,
+ ),
+ ).toBeVisible();
+ expect(
+ within(screen.getAllByRole("gridcell")[0]).getByText("Test Row"),
+ ).toBeVisible();
+ });
+
describe("toolbar visibility", () => {
it("should hide the chart type selector when it is disabled", async () => {
await setup({
diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts
index e3fc80f8a0e..449d08ab06e 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts
+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.schema.ts
@@ -4,9 +4,16 @@ import type { FunctionSchema } from "embedding-sdk-bundle/types/schema";
import type { StaticQuestionInternalProps } from "./StaticQuestion";
-// Typed against the internal shape so runtime validation still accepts the
-// `query` prop used by the `useMetabot` hook. The public API (see
-// `StaticQuestionProps`) intentionally doesn't expose `query` to users.
+const hasEntityProp = (props: StaticQuestionInternalProps | null | undefined) =>
+ props != null &&
+ (props.questionId !== undefined ||
+ props.token !== undefined ||
+ props.card !== undefined ||
+ props.query !== undefined);
+
+// Typed against the internal shape so runtime validation accepts both the
+// public object `query` prop and the internal string `query` prop used by the
+// `useMetabot` hook.
const propsSchema: Yup.SchemaOf<StaticQuestionInternalProps> = Yup.object({
children: Yup.mixed().optional(),
className: Yup.mixed().optional(),
@@ -15,13 +22,9 @@ const propsSchema: Yup.SchemaOf<StaticQuestionInternalProps> = Yup.object({
sqlParameters: Yup.mixed().optional(),
onSqlParametersChange: Yup.mixed().optional(),
hiddenParameters: Yup.mixed().optional(),
- questionId: Yup.mixed().when(["token", "query"], {
- is: (token: unknown, query: unknown) =>
- token !== undefined || query !== undefined,
- then: (schema) => schema.optional(),
- otherwise: (schema) => schema.required(),
- }),
+ questionId: Yup.mixed().optional(),
token: Yup.mixed().optional(),
+ card: Yup.mixed().optional(),
query: Yup.mixed().optional(),
style: Yup.mixed().optional(),
title: Yup.mixed().optional(),
@@ -29,7 +32,13 @@ const propsSchema: Yup.SchemaOf<StaticQuestionInternalProps> = Yup.object({
withChartTypeSelector: Yup.mixed().optional(),
withDownloads: Yup.mixed().optional(),
withAlerts: Yup.mixed().optional(),
-}).noUnknown();
+})
+ .test(
+ "has-entity-prop",
+ "questionId, token, card, or query is required",
+ hasEntityProp,
+ )
+ .noUnknown();
export const staticQuestionSchema: FunctionSchema = {
input: [propsSchema],
diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx
index 3aa4a8b7980..a97271c2eec 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx
@@ -32,13 +32,13 @@ import {
import { QuestionAlertsButton } from "embedding-sdk-bundle/components/public/notifications/QuestionAlertsButton";
import { useMobileLayout } from "embedding-sdk-bundle/hooks/private/use-mobile-layout";
import { useNormalizeGuestEmbedQuestionOrDashboardComponentProps } from "embedding-sdk-bundle/hooks/private/use-normalize-guest-embed-question-or-dashboard-component-props";
+import { resolveDeserializedCard } from "embedding-sdk-bundle/lib/sdk-question/resolve-deserialized-card";
import { useSdkSelector } from "embedding-sdk-bundle/store";
import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";
import type {
SdkQuestionEntityInternalProps,
SdkQuestionEntityPublicProps,
} from "embedding-sdk-bundle/types/question";
-import { deserializeCardFromQuery } from "metabase/common/utils/card";
import { Box, Group, Stack } from "metabase/ui";
import { getEmbeddingMode } from "metabase/visualizations/click-actions/lib/modes";
import { EmbeddingSdkStaticMode } from "metabase/visualizations/click-actions/modes/EmbeddingSdkStaticMode";
@@ -107,6 +107,7 @@ const StaticQuestionInner = (
props: StaticQuestionInternalProps,
): JSX.Element | null => {
const query = props.query;
+ const card = props.card;
// Normalize props for Guest Embed usage (e.g. enforce withDownloads in OSS).
const normalizedProps =
@@ -155,8 +156,8 @@ const StaticQuestionInner = (
);
const deserializedCard = useMemo(
- () => (query ? deserializeCardFromQuery(query) : undefined),
- [query],
+ () => resolveDeserializedCard({ card, query }),
+ [card, query],
);
const isGuestEmbed = useSdkSelector(getIsGuestEmbed);
diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx
index 51b3324381d..08a574c9b54 100644
--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx
+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.unit.spec.tsx
@@ -23,6 +23,7 @@ import {
} from "__support__/ui";
import { addAlertModalTests } from "embedding-sdk-bundle/components/public/question/shared-tests/alert-modal.spec";
import { addAlertsButtonTests } from "embedding-sdk-bundle/components/public/question/shared-tests/alerts-button.spec";
+import { addCardPropTests } from "embedding-sdk-bundle/components/public/question/shared-tests/card-prop.spec";
import type { SetupOpts } from "embedding-sdk-bundle/components/public/question/shared-tests/constants.spec";
import {
TEST_COLUMN,
@@ -154,6 +155,7 @@ const setup = async ({
};
addQueryPropTests({ Component: StaticQuestionInternal });
+addCardPropTests({ Component: StaticQuestion });
describe("StaticQuestion", () => {
addAlertsButtonTests(setup, { customComponent: StaticQuestion.AlertsButton });
diff --git a/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/card-prop.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/card-prop.spec.tsx
new file mode 100644
index 00000000000..759ba889aac
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/components/public/question/shared-tests/card-prop.spec.tsx
@@ -0,0 +1,158 @@
+import {
+ setupAdhocQueryMetadataEndpoint,
+ setupCardDataset,
+ setupCollectionByIdEndpoint,
+ setupNotificationChannelsEndpoints,
+} from "__support__/server-mocks";
+import {
+ mockGetBoundingClientRect,
+ screen,
+ waitForLoaderToBeRemoved,
+ within,
+} from "__support__/ui";
+import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";
+import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";
+import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";
+import type { MetabaseCard } from "embedding-sdk-bundle/types/question";
+import { utf8_to_b64url } from "metabase/utils/encoding";
+import {
+ createMockCardQueryMetadata,
+ createMockCollection,
+ createMockColumn,
+ createMockDataset,
+ createMockDatasetData,
+} from "metabase-types/api/mocks";
+
+import { TEST_COLUMN, TEST_DB, TEST_TABLE } from "./constants.spec";
+
+export function addCardPropTests({
+ Component,
+}: {
+ Component: (props: { card: string | MetabaseCard }) => React.ReactNode;
+}) {
+ describe("card prop", () => {
+ const DATASET_QUERY = {
+ database: TEST_DB.id,
+ type: "query" as const,
+ query: { "source-table": TEST_TABLE.id },
+ };
+
+ const CARD_STRING = utf8_to_b64url(
+ JSON.stringify({ dataset_query: DATASET_QUERY }),
+ );
+
+ const CARD_OBJECT: MetabaseCard = {
+ query: DATASET_QUERY,
+ visualization: "table",
+ visualizationSettings: {},
+ };
+
+ const QUERY_ONLY_CARD_OBJECT: MetabaseCard = {
+ query: DATASET_QUERY,
+ };
+
+ // A category + numeric dataset so a bar chart has something to render.
+ const BAR_CATEGORY_COLUMN = createMockColumn({
+ name: "CATEGORY",
+ display_name: "Category",
+ base_type: "type/Text",
+ });
+ const BAR_VALUE_COLUMN = createMockColumn({
+ name: "COUNT",
+ display_name: "Count",
+ base_type: "type/Integer",
+ });
+ const BAR_DATASET = createMockDataset({
+ data: createMockDatasetData({
+ cols: [BAR_CATEGORY_COLUMN, BAR_VALUE_COLUMN],
+ rows: [
+ ["a", 10],
+ ["b", 20],
+ ["c", 30],
+ ],
+ }),
+ });
+
+ const BAR_CARD: MetabaseCard = {
+ query: DATASET_QUERY,
+ visualization: "bar",
+ visualizationSettings: {
+ "graph.dimensions": ["CATEGORY"],
+ "graph.metrics": ["COUNT"],
+ },
+ };
+
+ const TABLE_DATASET = createMockDataset({
+ data: createMockDatasetData({
+ cols: [TEST_COLUMN],
+ rows: [["Test Row"], ["Test Row 2"]],
+ }),
+ });
+
+ async function setup(card: string | MetabaseCard, dataset = TABLE_DATASET) {
+ const { state } = setupSdkState();
+
+ setupNotificationChannelsEndpoints({ email: { configured: false } });
+ setupAdhocQueryMetadataEndpoint(
+ createMockCardQueryMetadata({ databases: [TEST_DB] }),
+ );
+ setupCardDataset({ dataset });
+ setupCollectionByIdEndpoint({
+ collections: [createMockCollection({ id: 1 })],
+ });
+
+ renderWithSDKProviders(<Component card={card} />, {
+ componentProviderProps: { authConfig: createMockSdkConfig() },
+ storeInitialState: state,
+ });
+
+ await waitForLoaderToBeRemoved();
+ }
+
+ beforeAll(() => {
+ mockGetBoundingClientRect();
+ });
+
+ it("should render a visualization when given a serialized card string", async () => {
+ await setup(CARD_STRING);
+
+ expect(screen.getByTestId("query-visualization-root")).toBeVisible();
+ expect(
+ within(screen.getByTestId("table-root")).getByText(
+ TEST_COLUMN.display_name,
+ ),
+ ).toBeVisible();
+ });
+
+ it("should render a visualization when given a card object", async () => {
+ await setup(CARD_OBJECT);
+
+ expect(screen.getByTestId("query-visualization-root")).toBeVisible();
+ expect(
+ within(screen.getByTestId("table-root")).getByText(
+ TEST_COLUMN.display_name,
+ ),
+ ).toBeVisible();
+ });
+
+ it("should render a visualization when given a card object without a chosen visualization", async () => {
+ await setup(QUERY_ONLY_CARD_OBJECT);
+
+ expect(screen.getByTestId("query-visualization-root")).toBeVisible();
+ expect(
+ within(screen.getByTestId("table-root")).getByText(
+ TEST_COLUMN.display_name,
+ ),
+ ).toBeVisible();
+ });
+
+ it("should honor the chosen `visualization` instead of defaulting to a table", async () => {
+ await setup(BAR_CARD, BAR_DATASET);
+
+ expect(screen.getByTestId("query-visualization-root")).toBeVisible();
+ // The `bar` visualization is honored (and locked), so a chart renders...
+ expect(screen.getByTestId("chart-container")).toBeInTheDocument();
+ expect(screen.queryByTestId("table-root")).not.toBeInTheDocument();
+ });
+ });
+}
diff --git a/frontend/src/embedding-sdk-bundle/embedding-sdk-bootstrap.ts b/frontend/src/embedding-sdk-bundle/embedding-sdk-bootstrap.ts
index 9fb88915ce3..89dbc2d92db 100644
--- a/frontend/src/embedding-sdk-bundle/embedding-sdk-bootstrap.ts
+++ b/frontend/src/embedding-sdk-bundle/embedding-sdk-bootstrap.ts
@@ -1,3 +1,5 @@
+import { SDK_BUNDLE_ERROR } from "embedding-sdk-shared/constants/event-names";
+
import { waitForAuthConfigAndStartEarlyAuthFlow } from "./bootstrap-auth";
// Bootstrap entry point for the SDK bundle.
@@ -51,6 +53,6 @@ function loadScript(filename: string): Promise<string> {
void Promise.all(manifest.chunks.map((filename) => loadScript(filename))).catch(
(error) => {
console.error("SDK Bootstrap: Failed to load bundle chunks:", error);
- document.dispatchEvent(new CustomEvent("metabase-sdk-bundle-error"));
+ document.dispatchEvent(new CustomEvent(SDK_BUNDLE_ERROR));
},
);
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.ts
index b90acf03d3c..9fe4c62f0e0 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
@@ -15,16 +15,12 @@ import type { MetabaseAuthConfig } from "embedding-sdk-bundle/types";
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 { getSdkPackageVersion } from "embedding-sdk-shared/lib/get-build-info";
-import {
- type OnBeforeRequestHandler,
- type RequestClientInfo,
- api,
-} from "metabase/api/client";
+import { type RequestClientInfo, api } from "metabase/api/client";
import registerDashboardVisualizations from "metabase/dashboard/visualizations/register";
-import {
- setEmbedPreviewHeader,
- setRequestClientHeaders,
-} from "metabase/embedding/lib/embedding-request-auth";
+import { setDataApp } from "metabase/embedding/config";
+import { setEmbedPreviewHeader } from "metabase/embedding/lib/auth/set-embed-preview-header";
+import { setReactSdkEmbedReferrerHeader } from "metabase/embedding/lib/auth/set-react-sdk-embed-referrer-header";
+import { setRequestClientHeaders } from "metabase/embedding/lib/auth/set-request-client-headers";
import {
EMBEDDING_SDK_CONFIG,
isEmbeddingEajs,
@@ -33,17 +29,6 @@ import { PLUGIN_API, PLUGIN_EMBEDDING_SDK } from "metabase/plugins";
import { setBasename } from "metabase/utils/basename";
import { registerVisualizations } from "metabase/visualizations/register";
-const reactSdkEmbedReferrerHandler: OnBeforeRequestHandler = async (
- config,
-) => ({
- ...config,
- headers: {
- ...config.headers,
- // eslint-disable-next-line metabase/no-literal-metabase-strings -- header name
- "X-Metabase-Embed-Referrer": window.location.href,
- },
-});
-
const sdkResponseErrorHandler = ({
metabaseVersion,
}: {
@@ -99,6 +84,15 @@ export const useInitData = () => {
const isGuestEmbed = !!props.authConfig.isGuest;
+ // `DataAppDevProvider` puts the app on the props store before rendering
+ // `MetabaseProvider`. Applied here, ahead of `useInitDataInternal`, so no request
+ // goes out unattributed.
+ if (internalProps.dataApp) {
+ setDataApp(internalProps.dataApp.name, {
+ isDev: internalProps.dataApp.isDev,
+ });
+ }
+
useInitDataInternal({
reduxStore,
isGuestEmbed,
@@ -129,6 +123,7 @@ export const useInitDataInternal = ({
setSdkRequestClientHeadersOnce({
name: EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader,
+ identifier: EMBEDDING_SDK_CONFIG.metabaseClientRequestIdentifier,
// Note: this is *package* version, it's undefined in EAJS
version: sdkPackageVersion,
});
@@ -138,7 +133,7 @@ export const useInitDataInternal = ({
// SdkIframeEmbedRoute.tsx using the value received via postMessage.
if (!isEmbeddingEajs()) {
PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.reactSdkEmbedReferrer =
- reactSdkEmbedReferrerHandler;
+ setReactSdkEmbedReferrerHeader;
}
// Dedupe by handler identity rather than total listener count — other code
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.unit.spec.tsx
new file mode 100644
index 00000000000..8e7fdb13288
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-init-data/use-init-data-internal.unit.spec.tsx
@@ -0,0 +1,77 @@
+import { renderHook } from "@testing-library/react";
+
+import type { SdkStore } from "embedding-sdk-bundle/store/types";
+import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";
+import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
+import { PLUGIN_API } from "metabase/plugins";
+
+import { useInitData } from "./use-init-data-internal";
+
+// Keep the test scoped to the header wiring; the viz registry is irrelevant.
+// `registerVisualizations` is a named export, so the mock must expose it under
+// that name — a bare `jest.fn()` module leaves it `undefined`, and the
+// `_.once(registerVisualizations)` call then throws on `undefined.apply`.
+jest.mock("metabase/visualizations/register", () => ({
+ registerVisualizations: jest.fn(),
+}));
+jest.mock("metabase/dashboard/visualizations/register", () => jest.fn());
+
+const fakeReduxStore = () =>
+ // A stub store: the test only reads `initStatus` and calls `dispatch`/`subscribe`,
+ // so it stubs those three members rather than the full `SdkStore` surface.
+ ({
+ getState: () => ({ sdk: { initStatus: { status: "success" } } }),
+ dispatch: jest.fn(),
+ subscribe: () => () => {},
+ }) as unknown as SdkStore;
+
+const setup = ({
+ dataApp,
+}: { dataApp?: { name: string; isDev?: boolean } } = {}) => {
+ const store = ensureMetabaseProviderPropsStore();
+
+ store.setProps({
+ authConfig: { metabaseInstanceUrl: "http://localhost:3000" },
+ });
+ store.updateInternalProps({ reduxStore: fakeReduxStore(), dataApp });
+
+ return renderHook(() => useInitData());
+};
+
+describe("useInitData » data-app context", () => {
+ const originalConfig = { ...EMBEDDING_SDK_CONFIG };
+ const originalHandlers = { ...PLUGIN_API.onBeforeRequestHandlers };
+
+ afterEach(() => {
+ Object.assign(EMBEDDING_SDK_CONFIG, originalConfig);
+ Object.assign(PLUGIN_API.onBeforeRequestHandlers, originalHandlers);
+ });
+
+ it("configures the data-app headers from internalProps.dataApp (dev Vite flow)", () => {
+ // Unmount before the test ends: the sdk project's global afterEach resets
+ // the props store, which re-renders a still-mounted subscriber against the
+ // empty state and makes useInitData throw.
+ const { unmount } = setup({ dataApp: { name: "sales", isDev: true } });
+
+ expect(EMBEDDING_SDK_CONFIG.isDataApp).toBe(true);
+ expect(EMBEDDING_SDK_CONFIG.isDataAppDev).toBe(true);
+ expect(EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader).toBe("data-app");
+ expect(EMBEDDING_SDK_CONFIG.metabaseClientRequestIdentifier).toBe("sales");
+
+ unmount();
+ });
+
+ it("leaves the SDK client config untouched without a data-app context", () => {
+ const { unmount } = setup();
+
+ expect(EMBEDDING_SDK_CONFIG.isDataApp).toBe(false);
+ expect(EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader).toBe(
+ "embedding-sdk-react",
+ );
+ expect(
+ EMBEDDING_SDK_CONFIG.metabaseClientRequestIdentifier,
+ ).toBeUndefined();
+
+ unmount();
+ });
+});
diff --git a/frontend/src/embedding-sdk-bundle/index.ts b/frontend/src/embedding-sdk-bundle/index.ts
index 37cf9de2b0e..58bfd47db56 100644
--- a/frontend/src/embedding-sdk-bundle/index.ts
+++ b/frontend/src/embedding-sdk-bundle/index.ts
@@ -21,72 +21,17 @@ initializePlugins();
// Imports which are only applicable to the embedding sdk, and not the new iframe embedding.
import "sdk-specific-imports";
-import type { MetabaseEmbeddingSdkBundleExports } from "./types/sdk-bundle";
+import { sdkBundleExports } from "./sdk-bundle-exports";
-import { MetabotSubscriber } from "./components/private/MetabotSubscriber/MetabotSubscriber";
-import { CollectionBrowser } from "./components/public/CollectionBrowser";
-import { CreateDashboardModal } from "./components/public/CreateDashboardModal";
-import { CreateQuestion } from "./components/public/CreateQuestion";
-import { InteractiveQuestion } from "./components/public/InteractiveQuestion";
-import { ComponentProvider } from "./components/public/ComponentProvider";
-import { MetabotQuestion } from "./components/public/MetabotQuestion";
-import { StaticQuestion } from "./components/public/StaticQuestion";
-import {
- EditableDashboard,
- InteractiveDashboard,
- StaticDashboard,
-} from "./components/public/dashboard";
-import { SdkDebugInfo } from "./components/public/SdkDebugInfo";
-import { getApplicationName } from "metabase/selectors/whitelabel";
-import { getSdkStore } from "./store/index";
-import {
- getAvailableFonts,
- getLoginStatus,
-} from "embedding-sdk-bundle/store/selectors";
-import { getUser } from "metabase/selectors/user";
-import { useInitData } from "./hooks/private/use-init-data";
-import { useLogVersionInfo } from "embedding-sdk-bundle/hooks/private/use-log-version-info";
-import { createDashboard } from "embedding-sdk-bundle/lib/create-dashboard";
-import { executeAction } from "embedding-sdk-bundle/lib/execute-action";
import { defineBuildInfo } from "metabase/embedding-sdk/lib/define-build-info";
-import { validateFunctionSchema } from "embedding-sdk-bundle/lib/validate-function-schema";
+import { SDK_BUNDLE_LOADED } from "embedding-sdk-shared/constants/event-names";
defineBuildInfo("METABASE_EMBEDDING_SDK_BUNDLE_BUILD_INFO");
-/**
- * IMPORTANT!
- * Any rename/removal change for object is a breaking change between the SDK Bundle and the SDK NPM package,
- * and should be done via the deprecation of the field first.
- */
-const sdkBundleExports: MetabaseEmbeddingSdkBundleExports = {
- CollectionBrowser,
- CreateDashboardModal,
- CreateQuestion,
- EditableDashboard,
- InteractiveDashboard,
- InteractiveQuestion,
- ComponentProvider,
- MetabotQuestion,
- SdkDebugInfo,
- StaticDashboard,
- StaticQuestion,
- getSdkStore,
- createDashboard,
- getApplicationName,
- getAvailableFonts,
- getLoginStatus,
- getUser,
- useInitData,
- useLogVersionInfo,
- validateFunctionSchema,
- MetabotSubscriber,
- executeAction,
-};
-
// Define a global export METABASE_EMBEDDING_SDK_BUNDLE for SDK package
window.METABASE_EMBEDDING_SDK_BUNDLE = sdkBundleExports;
// Signal that the bundle is ready. In the bootstrap flow (chunked loading),
// rspack defers entry execution until all chunks are registered, so this event
// fires only after everything is ready.
-document.dispatchEvent(new CustomEvent("metabase-sdk-bundle-loaded"));
+document.dispatchEvent(new CustomEvent(SDK_BUNDLE_LOADED));
diff --git a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts
new file mode 100644
index 00000000000..20ffb2cb70a
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/index.ts
@@ -0,0 +1,129 @@
+import type { SdkStore } from "embedding-sdk-bundle/store/types";
+import {
+ type QueryInput,
+ isQueryInput,
+ isQuestionInput,
+ isTableInput,
+} from "embedding-sdk-shared/lib/create-metabase-query/input-guards";
+import { cardApi } from "metabase/api";
+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";
+import { fetchTableMetadata } from "metabase/redux/tables";
+import { getMetadataUnfiltered } from "metabase/selectors/metadata";
+import * as Lib from "metabase-lib";
+import type { DatasetQuery, TestQuerySpec } from "metabase-types/api";
+import { isObject } from "metabase-types/guards";
+
+import { loadReferencedMetricMetadata } from "./metric-metadata";
+import { validateQueryInput } from "./validation";
+
+export type ResolveDatasetQuery = (
+ store: SdkStore,
+) => (input: QueryInput) => Promise<DatasetQuery>;
+
+export const resolveDatasetQuery: ResolveDatasetQuery =
+ (store) => async (input: QueryInput) => {
+ if (!isQueryInput(input)) {
+ throw new Error(
+ 'Query object creation requires a source reference like `{ type: "table", id }` or `{ type: "card", id }`.',
+ );
+ }
+
+ validateQueryInput(input);
+
+ await loadSourceMetadata(store, input);
+
+ return resolveQueryFromLoadedMetadata(
+ input,
+ getMetadataUnfiltered(store.getState()),
+ );
+ };
+
+function resolveQueryFromLoadedMetadata(
+ input: QueryInput,
+ metadata: Lib.Metadata,
+) {
+ if (!isQueryInput(input)) {
+ throw new Error(
+ 'Query object creation requires a source reference like `{ type: "table", id }` or `{ type: "card", id }`.',
+ );
+ }
+
+ const databaseId = getSourceDatabaseId(input, metadata);
+ const provider = Lib.metadataProvider(databaseId, metadata);
+
+ return Lib.toJsQuery(
+ Lib.createTestQuery(provider, { stages: [input] } satisfies TestQuerySpec),
+ );
+}
+
+async function loadSourceMetadata(store: SdkStore, input: QueryInput) {
+ if (input.source.type === "card") {
+ await loadCardMetadata(store, input.source.id);
+ return;
+ }
+
+ if (isTableInput(input)) {
+ await store.dispatch(fetchTableMetadata({ id: input.source.id }));
+ await loadReferencedMetricMetadata(store, input);
+ }
+}
+
+async function loadCardMetadata(store: SdkStore, id: number) {
+ await Promise.all([
+ runRtkEndpoint({ id }, store.dispatch, cardApi.endpoints.getCard, {
+ forceRefetch: false,
+ }),
+ runRtkEndpoint(id, store.dispatch, cardApi.endpoints.getCardQueryMetadata, {
+ forceRefetch: false,
+ }),
+ ]);
+}
+
+function getSourceDatabaseId(input: QueryInput, metadata: Lib.Metadata) {
+ if (isTableInput(input)) {
+ return getTableDatabaseId(input.source.id, metadata);
+ }
+
+ if (isQuestionInput(input)) {
+ return getCardDatabaseId(input.source.id, metadata);
+ }
+
+ throw new Error("Unable to find database for query source.");
+}
+
+function getTableDatabaseId(tableId: number, metadata: Lib.Metadata) {
+ const table = metadata.tables?.[tableId];
+
+ if (isObject(table) && typeof table.db_id === "number") {
+ return table.db_id;
+ }
+
+ throw new Error(`Unable to find database for table ${tableId}.`);
+}
+
+function getCardDatabaseId(cardId: number, metadata: Lib.Metadata) {
+ const card = metadata.questions?.[cardId];
+ const datasetQuery = getCardDatasetQuery(card);
+
+ if (isObject(datasetQuery) && typeof datasetQuery.database === "number") {
+ return datasetQuery.database;
+ }
+
+ throw new Error(`Unable to find database for saved question ${cardId}.`);
+}
+
+function getCardDatasetQuery(card: unknown) {
+ if (!isObject(card)) {
+ return null;
+ }
+
+ if (isObject(card.dataset_query)) {
+ return card.dataset_query;
+ }
+
+ if (typeof card.datasetQuery === "function") {
+ return card.datasetQuery();
+ }
+
+ return null;
+}
diff --git a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/metric-metadata.ts b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/metric-metadata.ts
new file mode 100644
index 00000000000..c35c3de26fc
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/metric-metadata.ts
@@ -0,0 +1,37 @@
+import type { SdkStore } from "embedding-sdk-bundle/store/types";
+import type { TableQueryInput } from "embedding-sdk-shared/lib/create-metabase-query/input-guards";
+import { isMetricReference } from "embedding-sdk-shared/lib/create-metabase-query/input-guards";
+import { cardApi } from "metabase/api";
+import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";
+
+export const loadReferencedMetricMetadata = (
+ store: SdkStore,
+ input: TableQueryInput,
+) =>
+ Promise.all(
+ collectMetricIdsToLoadMetadata(input).map((metricId) =>
+ loadMetricMetadata(store, metricId),
+ ),
+ );
+
+const collectMetricIdsToLoadMetadata = (query: TableQueryInput): number[] => [
+ ...new Set(
+ query.aggregations?.filter(isMetricReference).map((metric) => metric.id),
+ ),
+];
+
+const loadMetricMetadata = (store: SdkStore, metricId: number) =>
+ Promise.all([
+ runRtkEndpoint(
+ { id: metricId },
+ store.dispatch,
+ cardApi.endpoints.getCard,
+ { forceRefetch: false },
+ ),
+ runRtkEndpoint(
+ metricId,
+ store.dispatch,
+ cardApi.endpoints.getCardQueryMetadata,
+ { forceRefetch: false },
+ ),
+ ]);
diff --git a/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/validation.ts b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/validation.ts
new file mode 100644
index 00000000000..a4b1131663f
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/create-metabase-query/validation.ts
@@ -0,0 +1,323 @@
+import {
+ type QueryInput,
+ type QuestionQueryInput,
+ type TableQueryInput,
+ isMetricReference,
+} from "embedding-sdk-shared/lib/create-metabase-query/input-guards";
+import type { MetricSchema } from "embedding-sdk-shared/lib/create-metabase-query/schema";
+import { isObject } from "metabase-types/guards";
+
+export function validateQueryInput(input: QueryInput) {
+ if (isQuestionQueryInput(input)) {
+ validateQuestionInput(input);
+ return;
+ }
+
+ validateLimit(input.limit);
+ validateTableScopedInputs(input);
+}
+
+function validateLimit(limit: number | undefined) {
+ if (limit == null) {
+ return;
+ }
+
+ if (!Number.isInteger(limit) || limit <= 0) {
+ throw new Error("Table query limit must be a positive integer.");
+ }
+}
+
+function isQuestionQueryInput(input: QueryInput): input is QuestionQueryInput {
+ return input.source.type === "card";
+}
+
+function validateQuestionInput(input: QuestionQueryInput) {
+ const extraKeys = Object.keys(input).filter(
+ (key) => key !== "source" && key !== "enabled",
+ );
+
+ if (extraKeys.length > 0) {
+ throw new Error(
+ `Saved question queries only support source and enabled, but received ${extraKeys.join(
+ ", ",
+ )}.`,
+ );
+ }
+}
+
+function validateTableScopedInputs(input: TableQueryInput) {
+ const tableId = input.source.id;
+
+ input.fields?.forEach((field) => {
+ validateGeneratedTableReference(field, tableId, "Table query fields");
+ });
+
+ input.filters?.forEach((filter) => {
+ if (isTableScopedReference(filter)) {
+ validateGeneratedTableReference(filter, tableId, "Table query filters");
+ return;
+ }
+
+ validateGeneratedTableReference(
+ getFirstOperatorArg(filter),
+ tableId,
+ "Table query filters",
+ );
+ });
+
+ input.aggregations?.forEach((aggregation) => {
+ if (isMetricReference(aggregation)) {
+ validateMetricAggregation(aggregation, tableId);
+ return;
+ }
+
+ if (isTableScopedReference(aggregation)) {
+ validateGeneratedTableReference(
+ aggregation,
+ tableId,
+ "Table query aggregations",
+ );
+ return;
+ }
+
+ validateGeneratedTableReference(
+ getFirstOperatorArg(aggregation),
+ tableId,
+ "Table query aggregations",
+ );
+ });
+
+ input.breakouts?.forEach((breakout) => {
+ validateGeneratedTableReference(breakout, tableId, "Table query breakouts");
+ });
+
+ input.orderBys?.forEach((orderBy) => {
+ if (isAggregationResultReference(input.aggregations, orderBy)) {
+ return;
+ }
+
+ if (
+ isGroupedQuery(input) &&
+ !isBreakoutReference(input.breakouts, orderBy)
+ ) {
+ throw new Error(
+ "Table query orderBys for grouped queries must use query breakouts or aggregations included in the query.",
+ );
+ }
+
+ validateGeneratedTableReference(orderBy, tableId, "Table query orderBys");
+ });
+}
+
+function validateGeneratedTableReference(
+ reference: unknown,
+ expectedTableId: number,
+ context: string,
+) {
+ const actualTableId = getTableId(reference);
+
+ if (actualTableId == null || actualTableId === expectedTableId) {
+ return;
+ }
+
+ if (getSourceFieldId(reference) != null) {
+ return;
+ }
+
+ throw new Error(
+ `${context} must belong to source table ${expectedTableId}, but received table id ${actualTableId}.`,
+ );
+}
+
+function isTableScopedReference(value: unknown): value is { tableId?: number } {
+ return isObject(value) && "tableId" in value;
+}
+
+function getFirstOperatorArg(value: unknown) {
+ if (
+ !isObject(value) ||
+ value.type !== "operator" ||
+ !Array.isArray(value.args)
+ ) {
+ return undefined;
+ }
+
+ return value.args[0];
+}
+
+function isCountAggregation(value: unknown) {
+ return (
+ isObject(value) &&
+ value.type === "operator" &&
+ value.operator === "count" &&
+ Array.isArray(value.args) &&
+ value.args.length === 0
+ );
+}
+
+function isGroupedQuery(input: TableQueryInput) {
+ return Boolean(input.aggregations?.length || input.breakouts?.length);
+}
+
+function isAggregationResultReference(
+ aggregations: readonly unknown[] | undefined,
+ value: unknown,
+) {
+ if (
+ !isObject(value) ||
+ value.type !== "column" ||
+ typeof value.name !== "string"
+ ) {
+ return false;
+ }
+
+ return getAggregationResultColumnNames(aggregations).includes(value.name);
+}
+
+function getAggregationResultColumnNames(
+ aggregations: readonly unknown[] | undefined,
+) {
+ return (aggregations ?? []).flatMap((aggregation) => {
+ if (isCountAggregation(aggregation)) {
+ return ["count"];
+ }
+
+ const columns = getColumns(aggregation);
+
+ if (!columns) {
+ return [];
+ }
+
+ return columns.flatMap((column) =>
+ isObject(column) && typeof column.name === "string" ? [column.name] : [],
+ );
+ });
+}
+
+function getColumns(value: unknown) {
+ if (!isObject(value) || !("columns" in value)) {
+ return null;
+ }
+
+ return Array.isArray(value.columns) ? value.columns : null;
+}
+
+function isBreakoutReference(
+ breakouts: TableQueryInput["breakouts"] | undefined,
+ value: unknown,
+) {
+ if (!isObject(value)) {
+ return false;
+ }
+
+ return (breakouts ?? []).some(
+ (breakout) =>
+ fieldsMatch(breakout, value) && bucketOptionsMatch(breakout, value),
+ );
+}
+
+function getTableId(value: unknown): number | undefined {
+ if (!isTableScopedReference(value) || typeof value.tableId !== "number") {
+ return undefined;
+ }
+
+ return value.tableId;
+}
+
+function getSourceFieldId(value: unknown): number | undefined {
+ if (!isObject(value) || typeof value.sourceFieldId !== "number") {
+ return undefined;
+ }
+
+ return value.sourceFieldId;
+}
+
+function validateMetricAggregation(metric: MetricSchema, tableId: number) {
+ // Source-card Metrics need query composition over saved-question sources so
+ // Lib can scope metric dimensions to the card stage. Saved-question sources
+ // currently support source-only shortcuts, so reject source-card Metrics here.
+ if (metric.sourceCardId != null) {
+ throw new Error(
+ "Table query metric aggregations cannot use source-card Metrics. Use a saved question source for source-card Metrics.",
+ );
+ }
+
+ const allowedTableIds = getMetricAllowedTableIds(metric);
+
+ if (allowedTableIds === null) {
+ throw new Error(
+ "Table query metric aggregations must include source table metadata.",
+ );
+ }
+
+ if (allowedTableIds.includes(tableId)) {
+ return;
+ }
+
+ throw new Error(
+ `Table query metric aggregations must belong to source table ${tableId}, but received mapped table ids ${allowedTableIds.join(
+ ", ",
+ )}.`,
+ );
+}
+
+function getMetricAllowedTableIds(metric: MetricSchema) {
+ if (metric.mappedTableIds?.length) {
+ return metric.mappedTableIds;
+ }
+
+ if (metric.sourceTableId != null) {
+ return [metric.sourceTableId];
+ }
+
+ return null;
+}
+
+function fieldsMatch(left: unknown, right: Record<string, unknown>) {
+ if (!isObject(left)) {
+ return false;
+ }
+
+ const leftTableId = getTableId(left);
+ const rightTableId = getTableId(right);
+ const leftFieldId = typeof left.fieldId === "number" ? left.fieldId : null;
+ const rightFieldId = typeof right.fieldId === "number" ? right.fieldId : null;
+ const leftSourceFieldId = getSourceFieldId(left);
+ const rightSourceFieldId = getSourceFieldId(right);
+
+ return (
+ leftTableId === rightTableId &&
+ leftSourceFieldId === rightSourceFieldId &&
+ ((leftFieldId != null && leftFieldId === rightFieldId) ||
+ left.name === right.name)
+ );
+}
+
+function bucketOptionsMatch(left: unknown, right: Record<string, unknown>) {
+ if (!isObject(left)) {
+ return false;
+ }
+
+ return (
+ left.unit === right.unit &&
+ binningOptionsMatch(left.binning, right.binning) &&
+ left.bins === right.bins &&
+ left.binWidth === right.binWidth
+ );
+}
+
+function binningOptionsMatch(left: unknown, right: unknown) {
+ if (left == null || right == null) {
+ return left == null && right == null;
+ }
+
+ if (!isObject(left) || !isObject(right)) {
+ return false;
+ }
+
+ return (
+ left.strategy === right.strategy &&
+ left["num-bins"] === right["num-bins"] &&
+ left["bin-width"] === right["bin-width"]
+ );
+}
diff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppLink.tsx b/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppLink.tsx
new file mode 100644
index 00000000000..2d799f770d2
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppLink.tsx
@@ -0,0 +1,75 @@
+import type { AnchorHTMLAttributes, MouseEvent, ReactNode } from "react";
+
+import { browserHistory } from "metabase/router";
+
+import { getBasename } from "./DataAppRouter";
+
+export interface DataAppLinkProps extends Omit<
+ AnchorHTMLAttributes<HTMLAnchorElement>,
+ "href"
+> {
+ to: string;
+ children?: ReactNode;
+}
+
+/**
+ * Internal-only navigation link inside a data app.
+ *
+ * Deliberately does NOT delegate to react-router 3's `<Link>` —
+ * v3 components use deprecated React APIs (`getDefaultProps`,
+ * `childContextTypes`) that emit dev-mode warnings and will be removed
+ * in React 19.
+ */
+export const DataAppLink = ({
+ to,
+ children,
+ onClick,
+ target,
+ rel,
+ ...rest
+}: DataAppLinkProps) => {
+ const href = getBasename() + to;
+
+ const isExternalTarget = target != null && target !== "_self";
+ const resolvedRel = rel ?? (isExternalTarget ? "noopener noreferrer" : rel);
+
+ const handleClick = (event: MouseEvent<HTMLAnchorElement>) => {
+ onClick?.(event);
+
+ if (event.defaultPrevented) {
+ return;
+ }
+
+ if (isExternalTarget) {
+ // Explicit `target="_blank"` etc. — let the browser handle it.
+ return;
+ }
+
+ if (
+ event.button !== 0 ||
+ event.metaKey ||
+ event.ctrlKey ||
+ event.shiftKey ||
+ event.altKey
+ ) {
+ // Modifier keys / middle / right click → browser handles it (new tab,
+ // download, etc.). Don't preventDefault — we want the native action.
+ return;
+ }
+
+ event.preventDefault();
+ browserHistory.push(href);
+ };
+
+ return (
+ <a
+ href={href}
+ target={target}
+ rel={resolvedRel}
+ onClick={handleClick}
+ {...rest}
+ >
+ {children}
+ </a>
+ );
+};
diff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppRouter.tsx b/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppRouter.tsx
new file mode 100644
index 00000000000..c35505ece29
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppRouter.tsx
@@ -0,0 +1,54 @@
+import type { ReactNode } from "react";
+
+// Deep import (not the `metabase/urls` barrel) to keep the SDK bundle lean —
+// `data-apps.ts` is a leaf with no transitive deps.
+import { DATA_APP_EMBED_PREFIX } from "metabase/urls/data-apps";
+
+/**
+ * Escape a string for safe use as a literal inside a `RegExp`. The
+ * embed-prefix constant doesn't currently contain regex metacharacters,
+ * but escaping makes the regex robust against future changes to the
+ * constant.
+ */
+const escapeRegExp = (str: string): string =>
+ str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+// Captures everything from the start of `pathname` up to and including the
+// data-app `:name` segment. Tolerates a Metabase subpath install
+// (`/mb/embed/apps/sales/…`) by allowing arbitrary characters before
+// the `DATA_APP_EMBED_PREFIX` literal. In root installs (no subpath) the
+// pre-segment is empty and the match becomes `${DATA_APP_EMBED_PREFIX}/<name>`.
+const DATA_APP_BASENAME_RE = new RegExp(
+ `^(.*?${escapeRegExp(DATA_APP_EMBED_PREFIX)}/[^/]+)`,
+);
+
+/**
+ * Returns the iframe URL's data-app prefix — including any Metabase
+ * subpath install root — so consumers can strip it before exposing the
+ * sub-path to the bundle. Returns `""` for non-iframe contexts (the dev
+ * preview).
+ *
+ * Examples:
+ * `/embed/apps/sales/customers/42` → `/embed/apps/sales`
+ * `/mb/embed/apps/sales/customers/42` → `/mb/embed/apps/sales`
+ * `/customers/42` → `""`
+ */
+export const getBasename = (): string =>
+ window.location.pathname.match(DATA_APP_BASENAME_RE)?.[1] ?? "";
+
+interface DataAppRouterProps {
+ children?: ReactNode;
+}
+
+/**
+ * Wrap your data-app tree once. Inside, use `<DataAppLink to="…">` for
+ * navigation and `useDataAppLocation()` to read the current path.
+ *
+ * No `basename` prop: the basename is auto-detected from the iframe URL
+ * (`/embed/apps/<name>`). In the dev preview where there's no prefix,
+ * the same code works — `basename` resolves to `""` and the sub-path is
+ * just the raw pathname.
+ */
+export const DataAppRouter = ({ children }: DataAppRouterProps) => (
+ <>{children}</>
+);
diff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/index.ts b/frontend/src/embedding-sdk-bundle/lib/data-app/router/index.ts
new file mode 100644
index 00000000000..fcc1d6d06ff
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/data-app/router/index.ts
@@ -0,0 +1,19 @@
+import { browserHistory } from "metabase/router";
+
+import { DataAppRouter, getBasename } from "./DataAppRouter";
+
+export { DataAppRouter, getBasename };
+export { DataAppLink, type DataAppLinkProps } from "./DataAppLink";
+export { useDataAppLocation } from "./useDataAppLocation";
+
+/**
+ * Imperative routing surface exposed to the SDK bundle's public API.
+ * The bundle never depends on a router library directly — it only relies
+ * on this `{ getBasename, navigate, subscribe }` shape, backed by the
+ * `browserHistory` singleton's function-based API.
+ */
+export const dataAppRouting = {
+ getBasename,
+ navigate: (to: string) => browserHistory.push(getBasename() + to),
+ subscribe: (callback: () => void) => browserHistory.listen(callback),
+};
diff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.ts b/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.ts
new file mode 100644
index 00000000000..7ce38764b85
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.ts
@@ -0,0 +1,52 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+
+import { browserHistory } from "metabase/router";
+
+import { getBasename } from "./DataAppRouter";
+
+const computeSubPath = (basename: string): string => {
+ const pathname = window.location.pathname;
+ const subPath =
+ basename && pathname.startsWith(basename)
+ ? pathname.slice(basename.length)
+ : pathname;
+
+ return subPath || "/";
+};
+
+/**
+ * Returns the current data-app sub-path and a `navigate` function.
+ *
+ * Path is relative to the data-app root: `/`, `/customers/42`, etc.
+ * `navigate(to)` switches to a new sub-path without a full reload.
+ */
+export const useDataAppLocation = (): {
+ pathname: string;
+ navigate: (to: string) => void;
+} => {
+ // Basename never changes after mount: the iframe doesn't navigate to a
+ // different `<name>`; that'd be a parent-level route change which
+ // re-mounts the iframe entirely.
+ const basename = useMemo(() => getBasename(), []);
+ const [pathname, setPathname] = useState(() => computeSubPath(basename));
+
+ useEffect(() => {
+ // `browserHistory.listen` fires for every navigation — `<Link>` clicks,
+ // imperative `push` calls, and browser back/forward. One subscription
+ // covers all of them.
+ return browserHistory.listen(() => {
+ setPathname(computeSubPath(basename));
+ });
+ }, [basename]);
+
+ const navigate = useCallback(
+ (to: string) => {
+ // `to` is bundle-relative (e.g. "/customers/42"). The real URL is
+ // `basename + to`.
+ browserHistory.push(basename + to);
+ },
+ [basename],
+ );
+
+ return { pathname, navigate };
+};
diff --git a/frontend/src/embedding-sdk-bundle/lib/execute-action.ts b/frontend/src/embedding-sdk-bundle/lib/execute-action.ts
index bc8e663a528..68b19cd36d1 100644
--- a/frontend/src/embedding-sdk-bundle/lib/execute-action.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/execute-action.ts
@@ -16,8 +16,8 @@ export type ExecuteActionParams = {
};
/**
- * Loose response shape from the execute-action endpoint. The body varies by
- * action kind (created-row / rows-updated / rows-deleted / rows-affected /
+ * Loose response shape from the execute-action endpoint. The body varies
+ * by action kind (created-row / rows-updated / rows-deleted / rows-affected
* success+counts). Per-kind discrimination happens in the package hook via the
* generated `ActionResult<TAction>` type — this lib stays loose.
*
@@ -41,9 +41,10 @@ const parseActionId = (
/**
* Triggers a pre-existing Metabase action. The curried `(store) => fn` shape
- * mirrors `createDashboard` / `queryQuestion` / `queryMetric` so the package
+ * mirrors `createDashboard` / `queryQuestion` so the package
* hook can read `executeAction(reduxStore)({...})` off
- * `window.METABASE_EMBEDDING_SDK_BUNDLE`.
+ * `window.METABASE_EMBEDDING_SDK_BUNDLE`. The action runs by dispatching the
+ * `metabase/api` execute-action mutation on the passed store.
*/
export const executeAction =
(reduxStore: SdkStore) =>
diff --git a/frontend/src/embedding-sdk-bundle/lib/execute-action.unit.spec.ts b/frontend/src/embedding-sdk-bundle/lib/execute-action.unit.spec.ts
new file mode 100644
index 00000000000..71142932e47
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/execute-action.unit.spec.ts
@@ -0,0 +1,108 @@
+import fetchMock from "fetch-mock";
+
+import { getStore } from "__support__/entities-store";
+import type { SdkStore } from "embedding-sdk-bundle/store/types";
+import { Api } from "metabase/api";
+
+import { executeAction } from "./execute-action";
+
+const NUMERIC_ID = 42;
+const ENTITY_ID = "abc123def456abc123def";
+
+let activeStore: ReturnType<typeof getStore> | undefined;
+
+// `executeAction` dispatches the `metabase/api` execute-action mutation, so it
+// needs a real store wired with the RTK Query `Api` reducer + middleware.
+function setup() {
+ const store = getStore({ [Api.reducerPath]: Api.reducer }, {}, [
+ Api.middleware,
+ ]);
+ activeStore = store;
+ // The test store is built from the main-app `State`, so it does not carry the
+ // SDK-only slices of `SdkStoreState`. `executeAction` only ever touches
+ // `dispatch`, which is compatible.
+ return store as unknown as SdkStore;
+}
+
+describe("executeAction", () => {
+ afterEach(() => {
+ activeStore?.dispatch(Api.util.resetApiState());
+ activeStore = undefined;
+ fetchMock.removeRoutes().clearHistory();
+ });
+
+ it("POSTs to /api/action/:id/execute with the given parameters", async () => {
+ fetchMock.post(`path:/api/action/${NUMERIC_ID}/execute`, {
+ status: 200,
+ body: { "rows-affected": 7 },
+ });
+
+ const result = await executeAction(setup())({
+ actionId: NUMERIC_ID,
+ parameters: { id: 1, name: "European" },
+ });
+
+ expect(result).toEqual({ "rows-affected": 7 });
+ const calls = fetchMock.callHistory.calls(
+ `path:/api/action/${NUMERIC_ID}/execute`,
+ );
+ expect(calls).toHaveLength(1);
+ const body = JSON.parse(String(calls[0].options.body));
+ expect(body).toEqual({ parameters: { id: 1, name: "European" } });
+ });
+
+ it("defaults `parameters` to `{}` when omitted", async () => {
+ fetchMock.post(`path:/api/action/${NUMERIC_ID}/execute`, {
+ status: 200,
+ body: { "rows-affected": 0 },
+ });
+
+ await executeAction(setup())({ actionId: NUMERIC_ID });
+
+ const calls = fetchMock.callHistory.calls(
+ `path:/api/action/${NUMERIC_ID}/execute`,
+ );
+ expect(calls).toHaveLength(1);
+ expect(JSON.parse(String(calls[0].options.body))).toEqual({
+ parameters: {},
+ });
+ });
+
+ it("routes the request to /api/action/:eid/execute when given an entity_id string", async () => {
+ fetchMock.post(`path:/api/action/${ENTITY_ID}/execute`, {
+ status: 200,
+ body: { "created-row": { id: 1 } },
+ });
+
+ const result = await executeAction(setup())({
+ actionId: ENTITY_ID,
+ parameters: { name: "Jane" },
+ });
+
+ expect(result).toEqual({ "created-row": { id: 1 } });
+ expect(
+ fetchMock.callHistory.calls(`path:/api/action/${ENTITY_ID}/execute`),
+ ).toHaveLength(1);
+ // and not to the numeric-id path
+ expect(
+ fetchMock.callHistory.calls(`path:/api/action/${NUMERIC_ID}/execute`),
+ ).toHaveLength(0);
+ });
+
+ it("rejects with the client error shape on a non-2xx response", async () => {
+ fetchMock.post(`path:/api/action/${NUMERIC_ID}/execute`, {
+ status: 403,
+ body: { message: "denied" },
+ });
+
+ await expect(
+ executeAction(setup())({
+ actionId: NUMERIC_ID,
+ parameters: { id: 1 },
+ }),
+ ).rejects.toMatchObject({
+ status: 403,
+ data: { message: "denied" },
+ });
+ });
+});
diff --git a/frontend/src/embedding-sdk-bundle/lib/query-dataset.ts b/frontend/src/embedding-sdk-bundle/lib/query-dataset.ts
new file mode 100644
index 00000000000..da6b9af4397
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/query-dataset.ts
@@ -0,0 +1,37 @@
+import { api } from "metabase/api/client";
+import type {
+ Dataset,
+ DatasetColumn,
+ DatasetQuery,
+ RowValues,
+} from "metabase-types/api";
+
+export type QueryDatasetParams = {
+ datasetQuery: DatasetQuery;
+};
+
+export type QueryDatasetResult = {
+ rowCount: number | null;
+ runningTime: number | null;
+ columns: DatasetColumn[];
+ rows: RowValues[];
+};
+
+export const queryDataset =
+ () =>
+ async ({ datasetQuery }: QueryDatasetParams): Promise<QueryDatasetResult> => {
+ // `api.request` resolves to `unknown` (it does not take a response type
+ // parameter), so the /api/dataset body has to be named here.
+ const response = (await api.request({
+ method: "POST",
+ url: "/api/dataset",
+ body: datasetQuery,
+ })) as Dataset;
+
+ return {
+ rowCount: response.row_count ?? null,
+ runningTime: response.running_time ?? null,
+ columns: response.data?.cols ?? [],
+ rows: response.data?.rows ?? [],
+ };
+ };
diff --git a/frontend/src/embedding-sdk-bundle/lib/query-question.ts b/frontend/src/embedding-sdk-bundle/lib/query-question.ts
new file mode 100644
index 00000000000..fbb0d38bb72
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/query-question.ts
@@ -0,0 +1,79 @@
+import {
+ loadQuestionSdk,
+ runQuestionQuerySdk,
+} from "embedding-sdk-bundle/lib/sdk-question";
+import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";
+import type { SdkStore } from "embedding-sdk-bundle/store/types";
+import type {
+ MetabaseQuestion,
+ SdkQuestionId,
+ SqlParameterValues,
+} from "embedding-sdk-bundle/types/question";
+import { transformSdkQuestion } from "metabase/embedding-sdk/lib/transform-question";
+import { createRawSeries } from "metabase/visualizations/lib/series";
+import type { DatasetColumn, RowValues } from "metabase-types/api";
+
+export type QueryQuestionParams = {
+ questionId: SdkQuestionId;
+ initialSqlParameters?: SqlParameterValues;
+};
+
+export type QueryQuestionResult = {
+ id: MetabaseQuestion["id"];
+ name: MetabaseQuestion["name"];
+ description: MetabaseQuestion["description"];
+ entityId: MetabaseQuestion["entityId"];
+ rowCount: number | null;
+ runningTime: number | null;
+ columns: DatasetColumn[];
+ rows: RowValues[];
+};
+
+export const queryQuestion =
+ (reduxStore: SdkStore) =>
+ async ({
+ questionId,
+ initialSqlParameters,
+ }: QueryQuestionParams): Promise<QueryQuestionResult> => {
+ const dispatch = reduxStore.dispatch;
+ const getState = reduxStore.getState;
+ const isGuestEmbed = getIsGuestEmbed(getState());
+
+ const questionState = await dispatch(
+ loadQuestionSdk({
+ questionId,
+ token: undefined,
+ initialSqlParameters,
+ }),
+ );
+
+ const resultState = await runQuestionQuerySdk({
+ question: questionState.question,
+ isGuestEmbed,
+ token: undefined,
+ originalQuestion: questionState.originalQuestion,
+ parameterValues: questionState.parameterValues,
+ signal: new AbortController().signal,
+ dispatch,
+ });
+
+ const question = resultState.question ?? questionState.question;
+ const transformedQuestion = transformSdkQuestion(question);
+ const data = resultState.queryResults?.[0] ?? null;
+ const rawSeries =
+ createRawSeries({
+ card: question.card(),
+ queryResult: data,
+ }) ?? null;
+
+ return {
+ id: transformedQuestion.id,
+ name: transformedQuestion.name,
+ description: transformedQuestion.description,
+ entityId: transformedQuestion.entityId,
+ rowCount: data?.row_count ?? null,
+ runningTime: data?.running_time ?? null,
+ columns: data?.data.cols ?? [],
+ rows: rawSeries?.[0]?.data.rows ?? [],
+ };
+ };
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question-query.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question-query.ts
new file mode 100644
index 00000000000..cbc9b653c62
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question-query.ts
@@ -0,0 +1,24 @@
+import type { MetabaseQueryObject } from "embedding-sdk-bundle/types/question";
+import { deserializeCardFromQuery } from "metabase/common/utils/card";
+import type { DatasetQuery, UnsavedCard } from "metabase-types/api";
+
+export function getCardFromSdkQuestionQuery(
+ query: string | MetabaseQueryObject | null | undefined,
+): UnsavedCard | undefined {
+ if (query == null) {
+ return undefined;
+ }
+
+ if (typeof query === "string") {
+ return deserializeCardFromQuery(query);
+ }
+
+ return {
+ // `MetabaseQueryObject` is the public structural mirror of `DatasetQuery`
+ // and deliberately omits its opaque marker, so it cannot be assigned to the
+ // internal type without an assertion.
+ dataset_query: query as DatasetQuery,
+ display: "table",
+ visualization_settings: {},
+ };
+}
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/resolve-card-prop.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/resolve-card-prop.ts
new file mode 100644
index 00000000000..a1c29c915fa
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/resolve-card-prop.ts
@@ -0,0 +1,45 @@
+import type { MetabaseCard } from "embedding-sdk-bundle/types/question";
+import { deserializeCardFromQuery } from "metabase/common/utils/card";
+import type { DatasetQuery, UnsavedCard } from "metabase-types/api";
+
+export function resolveCardProp(
+ input: string | MetabaseCard,
+): UnsavedCard | null {
+ if (typeof input === "string") {
+ // A card copied from a question URL hash (`/question#<base64>` or bare base64).
+ try {
+ return deserializeCardFromQuery(input);
+ } catch {
+ console.warn(
+ // eslint-disable-next-line metabase/no-literal-metabase-strings
+ "InteractiveQuestion/StaticQuestion: the `card` string could not be parsed as a serialized question. Pass a value copied from a question URL hash, or a MetabaseCard object.",
+ );
+ return null;
+ }
+ }
+
+ if (input.query == null) {
+ return null;
+ }
+
+ const shouldSetDisplayLock =
+ input.visualization != null || input.displayIsLocked != null;
+
+ return {
+ // `MetabaseQueryObject` is the public structural mirror of `DatasetQuery`
+ // and deliberately omits its opaque marker, so it cannot be assigned to the
+ // internal type without an assertion.
+ dataset_query: input.query as DatasetQuery,
+ // Public-facing `visualization` maps to the internal card `display`. When
+ // omitted, let query results pick a better unlocked display later.
+ display: input.visualization ?? "table",
+ ...(shouldSetDisplayLock
+ ? {
+ // Default to locking an explicitly chosen display so the query builder
+ // doesn't reset it to a "sensible default" after results load.
+ displayIsLocked: input.displayIsLocked ?? true,
+ }
+ : {}),
+ visualization_settings: input.visualizationSettings ?? {},
+ };
+}
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/resolve-card-prop.unit.spec.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/resolve-card-prop.unit.spec.ts
new file mode 100644
index 00000000000..5b401f90ffe
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/resolve-card-prop.unit.spec.ts
@@ -0,0 +1,86 @@
+import type { MetabaseCard } from "embedding-sdk-bundle/types/question";
+import { utf8_to_b64url } from "metabase/utils/encoding";
+import type { DatasetQuery } from "metabase-types/api";
+
+import { resolveCardProp } from "./resolve-card-prop";
+
+const DATASET_QUERY: DatasetQuery = {
+ database: 1,
+ type: "query",
+ query: { "source-table": 2 },
+};
+
+const serialize = (card: object) => utf8_to_b64url(JSON.stringify(card));
+
+describe("resolveCardProp", () => {
+ it("parses a bare base64 string", () => {
+ const card = resolveCardProp(serialize({ dataset_query: DATASET_QUERY }));
+
+ expect(card?.dataset_query).toEqual(DATASET_QUERY);
+ });
+
+ it("parses a `/question#<base64>` prefixed string", () => {
+ const card = resolveCardProp(
+ "/question#" + serialize({ dataset_query: DATASET_QUERY }),
+ );
+
+ expect(card?.dataset_query).toEqual(DATASET_QUERY);
+ });
+
+ it("returns null and warns for an unparseable string", () => {
+ const warn = jest.spyOn(console, "warn").mockImplementation(() => {});
+
+ expect(resolveCardProp("not-a-real-card")).toBeNull();
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining("could not be parsed"),
+ );
+
+ warn.mockRestore();
+ });
+
+ it("maps a camelCase MetabaseCard object to a snake_case Card", () => {
+ const input: MetabaseCard = {
+ query: DATASET_QUERY,
+ visualization: "bar",
+ visualizationSettings: { "graph.dimensions": ["x"] },
+ };
+
+ const card = resolveCardProp(input);
+
+ expect(card).toEqual({
+ dataset_query: DATASET_QUERY,
+ display: "bar",
+ displayIsLocked: true,
+ visualization_settings: { "graph.dimensions": ["x"] },
+ });
+ });
+
+ it("returns null when a MetabaseCard object has a null query", () => {
+ expect(resolveCardProp({ query: null })).toBeNull();
+ });
+
+ it("uses an unlocked table display when `visualization` is omitted", () => {
+ const input: MetabaseCard = {
+ query: DATASET_QUERY,
+ };
+
+ const card = resolveCardProp(input);
+
+ expect(card).toEqual({
+ dataset_query: DATASET_QUERY,
+ display: "table",
+ visualization_settings: {},
+ });
+ });
+
+ it("respects an explicit `displayIsLocked: false`", () => {
+ const card = resolveCardProp({
+ query: DATASET_QUERY,
+ visualization: "bar",
+ visualizationSettings: {},
+ displayIsLocked: false,
+ });
+
+ expect(card?.displayIsLocked).toBe(false);
+ });
+});
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/resolve-deserialized-card.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/resolve-deserialized-card.ts
new file mode 100644
index 00000000000..61b10a3141f
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/resolve-deserialized-card.ts
@@ -0,0 +1,16 @@
+import { resolveCardProp } from "embedding-sdk-bundle/lib/sdk-question/resolve-card-prop";
+import { getCardFromSdkQuestionQuery } from "embedding-sdk-bundle/lib/sdk-question-query";
+import type { UnsavedCard } from "metabase-types/api";
+
+export function resolveDeserializedCard({
+ card,
+ query,
+}: {
+ card?: Parameters<typeof resolveCardProp>[0];
+ query?: Parameters<typeof getCardFromSdkQuestionQuery>[0];
+}): UnsavedCard | undefined {
+ if (card != null) {
+ return resolveCardProp(card) ?? undefined;
+ }
+ return getCardFromSdkQuestionQuery(query);
+}
diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-on-navigate.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-on-navigate.ts
index 07db7d9d04b..9e18cfe3422 100644
--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-on-navigate.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-on-navigate.ts
@@ -47,10 +47,15 @@ export const runQuestionOnNavigateSdk =
// Fallback when a visualization legend is clicked
if (cardIsEquivalent(previousCard, nextCard)) {
- nextCard = await loadCard(
- { cardId: nextCard.id },
- { dispatch, getState },
- );
+ // Reload the canonical card only for saved questions. Ad-hoc questions
+ // have no id, so keep the card as-is rather than firing
+ // `GET /api/card/undefined`.
+ if (nextCard.id !== null && nextCard.id !== undefined) {
+ nextCard = await loadCard(
+ { cardId: nextCard.id },
+ { dispatch, getState },
+ );
+ }
} else {
nextCard = getCardAfterVisualizationClick(nextCard, previousCard);
onClearQueryResults();
diff --git a/frontend/src/embedding-sdk-bundle/lib/validate-function-schema.ts b/frontend/src/embedding-sdk-bundle/lib/validate-function-schema.ts
index 7ec645d4554..df7749f31d7 100644
--- a/frontend/src/embedding-sdk-bundle/lib/validate-function-schema.ts
+++ b/frontend/src/embedding-sdk-bundle/lib/validate-function-schema.ts
@@ -1,43 +1,44 @@
-import type * as Yup from "yup";
+import { ValidationError } from "yup";
import type { FunctionSchema } from "embedding-sdk-bundle/types/schema";
import type {
- FunctionParametersSchemaValidationErrorMetadata,
FunctionSchemaValidationResult,
SchemaValidationErrorMetadata,
} from "embedding-sdk-shared/types/validation";
-const getErrorMetadata = <
- TMetadata extends
- | SchemaValidationErrorMetadata
- | FunctionParametersSchemaValidationErrorMetadata,
->({
- error,
- parameterIndex,
-}: {
- error: Yup.ValidationError;
- parameterIndex?: number;
-}): TMetadata | null => {
+const getErrorMetadata = (
+ error: ValidationError,
+): SchemaValidationErrorMetadata | null => {
switch (error.type) {
case "required":
- // Unjustified type cast. FIXME
return {
errorCode: "missing_required_property",
- data: error.params?.path ?? "",
- parameterIndex,
- } as TMetadata;
+ data: String(error.params?.path ?? ""),
+ };
+ case "has-entity-prop":
+ return {
+ errorCode: "missing_required_property",
+ data: "questionId, token, or query",
+ };
case "noUnknown":
- // Unjustified type cast. FIXME
return {
errorCode: "unrecognized_keys",
- data: error.params?.unknown ?? "",
- parameterIndex,
- } as TMetadata;
+ data: String(error.params?.unknown ?? ""),
+ };
}
return null;
};
+/**
+ * Schema violations surface as `ValidationError`; anything else thrown by
+ * `validateSync` is not a schema problem and carries no metadata.
+ */
+const getThrownErrorMetadata = (
+ error: unknown,
+): SchemaValidationErrorMetadata | null =>
+ ValidationError.isError(error) ? getErrorMetadata(error) : null;
+
export const validateFunctionSchema = <
TSchema extends FunctionSchema,
TParameters extends unknown[],
@@ -59,19 +60,13 @@ export const validateFunctionSchema = <
});
return { success: true };
- } catch (_error: unknown) {
- // Unjustified type cast. FIXME
- const error = _error as Yup.ValidationError;
- const errorMetadata =
- getErrorMetadata<FunctionParametersSchemaValidationErrorMetadata>({
- error,
- parameterIndex: i,
- });
+ } catch (error: unknown) {
+ const errorMetadata = getThrownErrorMetadata(error);
if (errorMetadata) {
return {
success: false,
- errorMetadata,
+ errorMetadata: { ...errorMetadata, parameterIndex: i },
};
}
}
@@ -90,12 +85,8 @@ export const validateFunctionSchema = <
});
return { success: true };
- } catch (_error: unknown) {
- // Unjustified type cast. FIXME
- const error = _error as Yup.ValidationError;
- const errorMetadata = getErrorMetadata<SchemaValidationErrorMetadata>({
- error,
- });
+ } catch (error: unknown) {
+ const errorMetadata = getThrownErrorMetadata(error);
if (errorMetadata) {
return {
diff --git a/frontend/src/embedding-sdk-bundle/lib/validate-function-schema.unit.spec.ts b/frontend/src/embedding-sdk-bundle/lib/validate-function-schema.unit.spec.ts
new file mode 100644
index 00000000000..bc0054ad487
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/lib/validate-function-schema.unit.spec.ts
@@ -0,0 +1,38 @@
+import * as Yup from "yup";
+
+import type { FunctionSchema } from "embedding-sdk-bundle/types/schema";
+
+import { validateFunctionSchema } from "./validate-function-schema";
+
+describe("validateFunctionSchema", () => {
+ it("reports an entity prop custom validation failure as a missing required property", () => {
+ const schema: FunctionSchema = {
+ input: [
+ Yup.object({
+ questionId: Yup.mixed().optional(),
+ token: Yup.mixed().optional(),
+ query: Yup.mixed().optional(),
+ }).test(
+ "has-entity-prop",
+ "questionId, token, or query is required",
+ (props) =>
+ props != null &&
+ (props.questionId !== undefined ||
+ props.token !== undefined ||
+ props.query !== undefined),
+ ),
+ ],
+ };
+
+ const { validateParameters } = validateFunctionSchema(schema);
+
+ expect(validateParameters([{}])).toEqual({
+ success: false,
+ errorMetadata: {
+ errorCode: "missing_required_property",
+ data: "questionId, token, or query",
+ parameterIndex: 0,
+ },
+ });
+ });
+});
diff --git a/frontend/src/embedding-sdk-bundle/sdk-bundle-exports.ts b/frontend/src/embedding-sdk-bundle/sdk-bundle-exports.ts
new file mode 100644
index 00000000000..ae31edc6eb0
--- /dev/null
+++ b/frontend/src/embedding-sdk-bundle/sdk-bundle-exports.ts
@@ -0,0 +1,74 @@
+/* eslint-disable import/order */
+
+import type { MetabaseEmbeddingSdkBundleExports } from "./types/sdk-bundle";
+
+import { MetabotSubscriber } from "./components/private/MetabotSubscriber/MetabotSubscriber";
+import { CollectionBrowser } from "./components/public/CollectionBrowser";
+import { CreateDashboardModal } from "./components/public/CreateDashboardModal";
+import { CreateQuestion } from "./components/public/CreateQuestion";
+import { InteractiveQuestion } from "./components/public/InteractiveQuestion";
+import { ComponentProvider } from "./components/public/ComponentProvider";
+import { MetabotQuestion } from "./components/public/MetabotQuestion";
+import { StaticQuestion } from "./components/public/StaticQuestion";
+import {
+ EditableDashboard,
+ InteractiveDashboard,
+ StaticDashboard,
+} from "./components/public/dashboard";
+import { SdkDebugInfo } from "./components/public/SdkDebugInfo";
+import { getApplicationName } from "metabase/selectors/whitelabel";
+import { getSdkStore } from "./store/index";
+import {
+ getAvailableFonts,
+ getLoginStatus,
+} from "embedding-sdk-bundle/store/selectors";
+import { getUser } from "metabase/selectors/user";
+import { useInitData } from "./hooks/private/use-init-data";
+import { useLogVersionInfo } from "embedding-sdk-bundle/hooks/private/use-log-version-info";
+import { createDashboard } from "embedding-sdk-bundle/lib/create-dashboard";
+import { executeAction } from "embedding-sdk-bundle/lib/execute-action";
+import { resolveDatasetQuery } from "embedding-sdk-bundle/lib/create-metabase-query";
+import { queryDataset } from "embedding-sdk-bundle/lib/query-dataset";
+import { queryQuestion } from "embedding-sdk-bundle/lib/query-question";
+import { validateFunctionSchema } from "embedding-sdk-bundle/lib/validate-function-schema";
+import {
+ DataAppLink,
+ DataAppRouter,
+ dataAppRouting,
+} from "embedding-sdk-bundle/lib/data-app/router";
+
+/**
+ * IMPORTANT!
+ * Any rename/removal change for object is a breaking change between the SDK Bundle and the SDK NPM package,
+ * and should be done via the deprecation of the field first.
+ */
+export const sdkBundleExports: MetabaseEmbeddingSdkBundleExports = {
+ CollectionBrowser,
+ CreateDashboardModal,
+ CreateQuestion,
+ DataAppLink,
+ DataAppRouter,
+ EditableDashboard,
+ InteractiveDashboard,
+ InteractiveQuestion,
+ ComponentProvider,
+ MetabotQuestion,
+ SdkDebugInfo,
+ StaticDashboard,
+ StaticQuestion,
+ getSdkStore,
+ resolveDatasetQuery,
+ createDashboard,
+ getApplicationName,
+ getAvailableFonts,
+ getLoginStatus,
+ getUser,
+ useInitData,
+ useLogVersionInfo,
+ validateFunctionSchema,
+ MetabotSubscriber,
+ queryDataset,
+ queryQuestion,
+ dataAppRouting,
+ executeAction,
+};
diff --git a/frontend/src/embedding-sdk-bundle/types/metabot.ts b/frontend/src/embedding-sdk-bundle/types/metabot.ts
index f0e48f6dbc4..b05a092b35b 100644
--- a/frontend/src/embedding-sdk-bundle/types/metabot.ts
+++ b/frontend/src/embedding-sdk-bundle/types/metabot.ts
@@ -48,10 +48,13 @@ export type MetabotMessage = MetabotUserTextMessage | MetabotAgentMessage;
/** @category useMetabot */
export type MetabotChartProps =
- | (Omit<StaticQuestionProps, "questionId" | "token" | "query"> & {
+ | (Omit<StaticQuestionProps, "questionId" | "token" | "query" | "card"> & {
drills?: false;
})
- | (Omit<InteractiveQuestionProps, "questionId" | "token" | "query"> & {
+ | (Omit<
+ InteractiveQuestionProps,
+ "questionId" | "token" | "query" | "card"
+ > & {
drills: true;
});
diff --git a/frontend/src/embedding-sdk-bundle/types/question.ts b/frontend/src/embedding-sdk-bundle/types/question.ts
index d9a3dea8743..cd3a19a2534 100644
--- a/frontend/src/embedding-sdk-bundle/types/question.ts
+++ b/frontend/src/embedding-sdk-bundle/types/question.ts
@@ -1,15 +1,23 @@
import type { ReactNode } from "react";
import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";
+import type {
+ MetabaseCard,
+ MetabaseQueryObject,
+} from "metabase/embedding-sdk/types/question";
import type { QueryParams } from "metabase/query_builder/actions";
import type { ObjectId } from "metabase/visualizations/components/ObjectDetail/types";
import type InternalQuestion from "metabase-lib/v1/Question";
-import type { Card, ParameterValuesMap } from "metabase-types/api";
+import type { Card, ParameterValuesMap, UnsavedCard } from "metabase-types/api";
import type { SdkDashboardId } from "./dashboard";
import type { SdkEntityId, SdkEntityToken } from "./entity";
-export type { MetabaseQuestion } from "metabase/embedding-sdk/types/question";
+export type {
+ MetabaseCard,
+ MetabaseQueryObject,
+ MetabaseQuestion,
+} from "metabase/embedding-sdk/types/question";
/**
* Represents the identifier for a question in the Metabase SDK.
@@ -52,6 +60,7 @@ export type SdkQuestionEntityPublicProps =
*/
questionId: SdkQuestionId | null;
token?: never;
+ card?: never;
query?: never;
}
| {
@@ -60,18 +69,40 @@ export type SdkQuestionEntityPublicProps =
* A valid JWT token for the guest embed.
*/
token: SdkEntityToken | null;
+ card?: never;
query?: never;
+ }
+ | {
+ questionId?: never;
+ token?: never;
+ /**
+ * An ad-hoc question to render without saving it first. Either a
+ * {@link MetabaseCard} object, or a serialized card string copied from a
+ * question URL hash (`/question#<base64>` or the bare base64).
+ */
+ card: string | MetabaseCard;
+ query?: never;
+ }
+ | {
+ questionId?: never;
+ token?: never;
+ card?: never;
+ /**
+ * A table-backed ad hoc query created with `useMetabaseQueryObject`.
+ */
+ query: MetabaseQueryObject | null;
};
/**
- * Internal type that adds the `query` prop used by the `useMetabot` hook. Not
- * re-exported from the public SDK package entry point.
+ * Internal type that adds the string `query` prop used by the `useMetabot`
+ * hook. Not re-exported from the public SDK package entry point.
*/
export type SdkQuestionEntityInternalProps =
| SdkQuestionEntityPublicProps
| {
questionId?: never;
token?: never;
+ card?: never;
query: string;
};
@@ -97,7 +128,7 @@ export type LoadSdkQuestionParams = {
/**
* @internal
*/
- deserializedCard?: Card;
+ deserializedCard?: UnsavedCard;
/**
* @internal
diff --git a/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts b/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts
index 976d9561959..a68b68a844b 100644
--- a/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts
+++ b/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts
@@ -12,10 +12,23 @@ import type { StaticQuestion } from "embedding-sdk-bundle/components/public/Stat
import type { EditableDashboard } from "embedding-sdk-bundle/components/public/dashboard/EditableDashboard";
import type { InteractiveDashboard } from "embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard";
import type { StaticDashboard } from "embedding-sdk-bundle/components/public/dashboard/StaticDashboard";
+import type { ResolveDatasetQuery } from "embedding-sdk-bundle/lib/create-metabase-query";
+import type {
+ DataAppLink,
+ DataAppRouter,
+} from "embedding-sdk-bundle/lib/data-app/router";
import type {
ExecuteActionParams,
ExecuteActionResult,
} from "embedding-sdk-bundle/lib/execute-action";
+import type {
+ QueryDatasetParams,
+ QueryDatasetResult,
+} from "embedding-sdk-bundle/lib/query-dataset";
+import type {
+ QueryQuestionParams,
+ QueryQuestionResult,
+} from "embedding-sdk-bundle/lib/query-question";
import type { SdkStore, SdkStoreState } from "embedding-sdk-bundle/store/types";
import type {
CreateDashboardValues,
@@ -45,12 +58,15 @@ export type MetabaseEmbeddingSdkBundleExports = PublicExports &
ReduxStoreSelectorsExports &
InternalHooksExports &
SchemaValidationUtils &
- InternalComponentExports;
+ InternalComponentExports &
+ DataAppRoutingExports;
type PublicExports = {
CollectionBrowser: InternalComponent<typeof CollectionBrowser>;
CreateDashboardModal: InternalComponent<typeof CreateDashboardModal>;
CreateQuestion: InternalComponent<typeof CreateQuestion>;
+ DataAppLink: typeof DataAppLink;
+ DataAppRouter: typeof DataAppRouter;
EditableDashboard: InternalComponent<typeof EditableDashboard>;
InteractiveDashboard: InternalComponent<typeof InteractiveDashboard>;
InteractiveQuestion: InternalComponent<typeof InteractiveQuestion>;
@@ -61,14 +77,31 @@ type PublicExports = {
StaticQuestion: InternalComponent<typeof StaticQuestion>;
};
+type DataAppRoutingExports = {
+ dataAppRouting: {
+ getBasename: () => string;
+ navigate: (to: string) => void;
+ subscribe: (callback: () => void) => () => void;
+ };
+};
+
type ReduxStoreExports = {
getSdkStore: ReduxStoreFactory;
};
type ReduxStoreUtilityFunctionExports = {
+ resolveDatasetQuery: ReduxStoreUtilityFunction<
+ ReturnType<ResolveDatasetQuery>
+ >;
createDashboard: ReduxStoreUtilityFunction<
(params: CreateDashboardValues) => Promise<MetabaseDashboard>
>;
+ queryQuestion: ReduxStoreUtilityFunction<
+ (params: QueryQuestionParams) => Promise<QueryQuestionResult>
+ >;
+ queryDataset: ReduxStoreUtilityFunction<
+ (params: QueryDatasetParams) => Promise<QueryDatasetResult>
+ >;
executeAction: ReduxStoreUtilityFunction<
(params: ExecuteActionParams) => Promise<ExecuteActionResult>
>;
diff --git a/frontend/src/embedding-sdk-bundle/types/ui.ts b/frontend/src/embedding-sdk-bundle/types/ui.ts
index cc3c5ac59c6..f5acb41a160 100644
--- a/frontend/src/embedding-sdk-bundle/types/ui.ts
+++ b/frontend/src/embedding-sdk-bundle/types/ui.ts
@@ -1,4 +1,7 @@
-import type { JSX, ReactNode } from "react";
+export type {
+ SdkErrorComponent,
+ SdkErrorComponentProps,
+} from "metabase/embedding-sdk/types/error-component";
/**
* @inline
@@ -45,20 +48,6 @@ export type {
MetabaseComponentTheme,
} from "metabase/embedding-sdk/theme";
-export type SdkErrorComponentProps = {
- type?: "relative" | "fixed";
- message: ReactNode;
- error?: Error;
- withCloseButton?: boolean;
- onClose?: () => void;
-};
-
-export type SdkErrorComponent = ({
- type,
- message,
- error,
-}: SdkErrorComponentProps) => JSX.Element;
-
export type SdkLoadingError = {
status: number;
message: string;
diff --git a/frontend/src/embedding-sdk-shared/constants/event-names.ts b/frontend/src/embedding-sdk-shared/constants/event-names.ts
new file mode 100644
index 00000000000..bd88c1e253c
--- /dev/null
+++ b/frontend/src/embedding-sdk-shared/constants/event-names.ts
@@ -0,0 +1,2 @@
+export const SDK_BUNDLE_LOADED = "metabase-sdk-bundle-loaded";
+export const SDK_BUNDLE_ERROR = "metabase-sdk-bundle-error";
diff --git a/frontend/src/embedding-sdk-shared/lib/create-metabase-query/input-guards.ts b/frontend/src/embedding-sdk-shared/lib/create-metabase-query/input-guards.ts
new file mode 100644
index 00000000000..6c723b70fc8
--- /dev/null
+++ b/frontend/src/embedding-sdk-shared/lib/create-metabase-query/input-guards.ts
@@ -0,0 +1,41 @@
+import type { TestStageWithSourceSpec } from "metabase-types/api";
+import { isObject } from "metabase-types/guards";
+
+import type { MetricSchema, QuestionSchema, TableSchema } from "./schema";
+
+export type TableQueryInput = Omit<TestStageWithSourceSpec, "source"> & {
+ source: TableSchema;
+ limit?: number;
+ enabled?: boolean;
+};
+
+export type QuestionQueryInput = {
+ source: QuestionSchema;
+ enabled?: boolean;
+};
+
+export type QueryInput = TableQueryInput | QuestionQueryInput;
+
+export const isTableInput = (input: unknown): input is TableQueryInput =>
+ isObject(input) && "source" in input && isTableReference(input.source);
+
+export const isTableReference = (value: unknown): value is TableSchema =>
+ isObject(value) && typeof value.id === "number" && value.type === "table";
+
+export const isMetricReference = (value: unknown): value is MetricSchema =>
+ isObject(value) && typeof value.id === "number" && value.type === "metric";
+
+export const isQuestionInput = (input: unknown): input is QuestionQueryInput =>
+ isObject(input) && "source" in input && isQuestionReference(input.source);
+
+export const isQuestionReference = (value: unknown): value is QuestionSchema =>
+ isObject(value) && typeof value.id === "number" && value.type === "card";
+
+export const isQueryInput = (input: unknown): input is QueryInput =>
+ isTableInput(input) || isQuestionInput(input);
+
+export const isUnaryOperator = (operator: string) =>
+ operator === "is-empty" ||
+ operator === "not-empty" ||
+ operator === "is-null" ||
+ operator === "not-null";
diff --git a/frontend/src/embedding-sdk-shared/lib/create-metabase-query/schema.ts b/frontend/src/embedding-sdk-shared/lib/create-metabase-query/schema.ts
new file mode 100644
index 00000000000..9e2c26d9ebb
--- /dev/null
+++ b/frontend/src/embedding-sdk-shared/lib/create-metabase-query/schema.ts
@@ -0,0 +1,69 @@
+export type SchemaJavaScriptType =
+ | "string"
+ | "number"
+ | "boolean"
+ | "Date"
+ | "unknown";
+
+export type SchemaColumn = {
+ type?: "column";
+ name: string;
+ description?: string;
+ displayName?: string;
+ jsType?: SchemaJavaScriptType;
+ baseType?: string;
+ effectiveType?: string;
+};
+
+/**
+ * Metadata for a generated table field.
+ */
+export type FieldSchema = SchemaColumn & {
+ type: "column";
+ id?: string | number;
+ sourceName?: string;
+ fieldId?: number;
+ tableId?: number;
+ sourceFieldId?: number;
+};
+
+export type SegmentSchema<TTableId extends number = number> = {
+ type: "segment";
+ id: number;
+ tableId: TTableId;
+};
+
+export type MeasureSchema<TTableId extends number = number> = {
+ type: "measure";
+ id: number;
+ tableId: TTableId;
+ columns: readonly SchemaColumn[];
+};
+
+export type TableSchema = {
+ type: "table";
+ id: number;
+ columns?: readonly SchemaColumn[];
+ fields?: Record<string, FieldSchema>;
+ segments?: Record<string, SegmentSchema>;
+ measures?: Record<string, MeasureSchema>;
+};
+
+export type MetricSchema = {
+ type: "metric";
+ id: number;
+ databaseId?: number;
+ sourceTableId?: number;
+ sourceCardId?: number;
+ mappedTableIds?: readonly number[];
+ columns?: readonly SchemaColumn[];
+ dimensions?: Record<string, Record<string, FieldSchema>>;
+};
+
+export type QuestionSchema = {
+ type: "card";
+ id: number;
+ name?: string;
+ display?: string;
+ columns?: readonly SchemaColumn[];
+};
diff --git a/frontend/src/embedding-sdk-shared/lib/ensure-metabase-provider-props-store.ts b/frontend/src/embedding-sdk-shared/lib/ensure-metabase-provider-props-store.ts
index 1b4266f3b5c..5b1cd172517 100644
--- a/frontend/src/embedding-sdk-shared/lib/ensure-metabase-provider-props-store.ts
+++ b/frontend/src/embedding-sdk-shared/lib/ensure-metabase-provider-props-store.ts
@@ -20,6 +20,7 @@ export type MetabaseProviderPropsStoreInternalProps = {
loadingError?: SdkLoadingError | null;
reduxStore?: ComponentProviderProps["reduxStore"] | null;
singleInstanceIdsMap?: Record<string, string[]>;
+ dataApp?: { name: string; isDev?: boolean } | null;
};
/**
diff --git a/frontend/src/embedding-sdk-shared/lib/version-utils.ts b/frontend/src/embedding-sdk-shared/lib/version-utils.ts
index b0ada051233..82e87731709 100644
--- a/frontend/src/embedding-sdk-shared/lib/version-utils.ts
+++ b/frontend/src/embedding-sdk-shared/lib/version-utils.ts
@@ -1,14 +1,16 @@
// SKIPPED eslint-disable-next-line no-external-references-for-sdk-package-code
import { EMBEDDING_SDK_BUNDLE_UNKNOWN_VERSION } from "build-configs/embedding-sdk/constants/versions";
// SKIPPED eslint-disable-next-line no-external-references-for-sdk-package-code
-import { versionToNumericComponents } from "metabase/utils/version";
+import {
+ isLocalOrSnapshotVersion,
+ versionToNumericComponents,
+} from "metabase/utils/version";
// They are mostly used for local development
export const isInvalidMetabaseVersion = (mbVersion: string) => {
return (
- mbVersion === "vLOCAL_DEV" ||
- mbVersion === EMBEDDING_SDK_BUNDLE_UNKNOWN_VERSION ||
- mbVersion.endsWith("-SNAPSHOT")
+ isLocalOrSnapshotVersion(mbVersion) ||
+ mbVersion === EMBEDDING_SDK_BUNDLE_UNKNOWN_VERSION
);
};
diff --git a/frontend/src/metabase-lib/query/query.unit.spec.ts b/frontend/src/metabase-lib/query/query.unit.spec.ts
index 59018fd5cbf..88155c009ff 100644
--- a/frontend/src/metabase-lib/query/query.unit.spec.ts
+++ b/frontend/src/metabase-lib/query/query.unit.spec.ts
@@ -1,5 +1,12 @@
+import { createMockMetadata } from "__support__/metadata";
import * as Lib from "metabase-lib";
import type { DatasetQuery } from "metabase-types/api";
+import {
+ createMockCard,
+ createMockMeasure,
+ createMockSegment,
+ createMockStructuredDatasetQuery,
+} from "metabase-types/api/mocks";
import {
ORDERS_ID,
PEOPLE_ID,
@@ -14,6 +21,9 @@ import {
SAMPLE_PROVIDER,
} from "./test-helpers";
+const METRIC_ID = 42;
+const QUESTION_ID = 43;
+
const DEFAULT_QUERY: DatasetQuery = {
database: SAMPLE_DATABASE.id,
type: "query",
@@ -87,6 +97,88 @@ describe("createTestQuery", () => {
});
expect(Lib.sourceTableOrCardId(query)).toBe(PRODUCTS_ID);
});
+
+ it("should create a query with a card source", () => {
+ const provider = Lib.metadataProvider(
+ SAMPLE_DATABASE.id,
+ createMockMetadata({
+ databases: [SAMPLE_DATABASE],
+ questions: [
+ createMockCard({
+ id: QUESTION_ID,
+ name: "Orders question",
+ dataset_query: createMockStructuredDatasetQuery({
+ database: SAMPLE_DATABASE.id,
+ query: {
+ "source-table": ORDERS_ID,
+ },
+ }),
+ }),
+ ],
+ }),
+ );
+
+ const query = Lib.createTestQuery(provider, {
+ stages: [
+ {
+ source: {
+ type: "card",
+ id: QUESTION_ID,
+ },
+ },
+ ],
+ });
+
+ expect(Lib.toJsQuery(query)).toMatchObject({
+ stages: [
+ {
+ "source-card": QUESTION_ID,
+ },
+ ],
+ });
+ });
+
+ it("should create a query with a metric aggregation", () => {
+ const provider = Lib.metadataProvider(
+ SAMPLE_DATABASE.id,
+ createMockMetadata({
+ databases: [SAMPLE_DATABASE],
+ questions: [
+ createMockCard({
+ id: METRIC_ID,
+ name: "Revenue",
+ type: "metric",
+ dataset_query: createMockStructuredDatasetQuery({
+ database: SAMPLE_DATABASE.id,
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ },
+ }),
+ }),
+ ],
+ }),
+ );
+
+ const query = Lib.createTestQuery(provider, {
+ stages: [
+ {
+ source: {
+ type: "table",
+ id: ORDERS_ID,
+ },
+ aggregations: [{ type: "metric", id: METRIC_ID }],
+ },
+ ],
+ });
+
+ expect(Lib.sourceTableOrCardId(query)).toBe(ORDERS_ID);
+ expect(
+ Lib.displayInfo(query, 0, Lib.aggregations(query, 0)[0]),
+ ).toMatchObject({
+ displayName: "Revenue",
+ });
+ });
});
describe("fields", () => {
@@ -391,6 +483,43 @@ describe("createTestQuery", () => {
});
describe("filters", () => {
+ it("should create a query with a segment filter", () => {
+ const SEGMENT_ID = 12;
+ const provider = Lib.metadataProvider(
+ SAMPLE_DATABASE.id,
+ createMockMetadata({
+ databases: [SAMPLE_DATABASE],
+ segments: [
+ createMockSegment({
+ id: SEGMENT_ID,
+ table_id: PRODUCTS_ID,
+ definition: createMockStructuredDatasetQuery({
+ query: {
+ "source-table": PRODUCTS_ID,
+ filter: ["=", ["field", PRODUCTS.CATEGORY, null], "Widget"],
+ },
+ }),
+ }),
+ ],
+ }),
+ );
+ const query = Lib.createTestQuery(provider, {
+ stages: [
+ {
+ source: {
+ type: "table",
+ id: PRODUCTS_ID,
+ },
+ filters: [{ type: "segment", id: SEGMENT_ID }],
+ },
+ ],
+ });
+
+ expect(Lib.toLegacyQuery(query)).toMatchObject({
+ query: { filter: ["segment", SEGMENT_ID] },
+ });
+ });
+
it("should create a query with filters", () => {
const query = Lib.createTestQuery(SAMPLE_PROVIDER, {
stages: [
@@ -423,6 +552,55 @@ describe("createTestQuery", () => {
});
describe("aggregations", () => {
+ it("should create a query with a measure aggregation", () => {
+ const MEASURE_ID = 34;
+
+ const provider = Lib.metadataProvider(
+ SAMPLE_DATABASE.id,
+ createMockMetadata({
+ databases: [SAMPLE_DATABASE],
+ measures: [
+ createMockMeasure({
+ id: MEASURE_ID,
+ table_id: PRODUCTS_ID,
+ definition: Lib.createTestJsQuery(SAMPLE_PROVIDER, {
+ stages: [
+ {
+ source: { type: "table", id: PRODUCTS_ID },
+ aggregations: [{ type: "operator", operator: "count" }],
+ },
+ ],
+ }),
+ }),
+ ],
+ }),
+ );
+
+ const query = Lib.createTestQuery(provider, {
+ stages: [
+ {
+ source: {
+ type: "table",
+ id: PRODUCTS_ID,
+ },
+ aggregations: [{ type: "measure", id: MEASURE_ID }],
+ },
+ ],
+ });
+
+ expect(Lib.toLegacyQuery(query)).toMatchObject({
+ query: {
+ aggregation: [
+ [
+ "aggregation-options",
+ expect.anything(),
+ { "display-name": "Measure" },
+ ],
+ ],
+ },
+ });
+ });
+
it("should create a query with aggregations", () => {
const query = Lib.createTestQuery(SAMPLE_PROVIDER, {
stages: [
diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.ts
index 4f10e9dc127..86c759401ab 100644
--- a/frontend/src/metabase-types/api/card.ts
+++ b/frontend/src/metabase-types/api/card.ts
@@ -295,12 +295,28 @@ export type ColumnSettings = TimeOnlyOptions & {
[key: string]: any;
};
+/**
+ * Visualization-specific display options. Prefer Metabase defaults unless the
+ * user asks for an explicit presentation change; many settings depend on exact
+ * result column names.
+ */
export type VisualizationSettings = {
+ /** Show value labels directly on supported chart marks. */
"graph.show_values"?: boolean;
+
+ /** Stack compatible series as `stacked` or `normalized`; `null` disables stacking. */
"stackable.stack_type"?: StackType;
+
+ /** Show aggregate labels for stacked chart segments. */
"graph.show_stack_values"?: StackValuesDisplay;
+
+ /** Limit the number of categories before grouping the rest into an "Other" bucket. */
"graph.max_categories_enabled"?: boolean;
+
+ /** Maximum number of categories to show before using the "Other" bucket. */
"graph.max_categories"?: number;
+
+ /** Aggregation used for values that are grouped into the "Other" bucket. */
"graph.other_category_aggregation_fn"?:
| "sum"
| "avg"
@@ -309,15 +325,22 @@ export type VisualizationSettings = {
| "stddev"
| "median";
- // Table
+ /** Visible table columns and order, as `{ name, enabled }` entries. */
"table.columns"?: TableColumnOrderSetting[];
- // Keys here can be modern (returned by `getColumnKey`) or legacy (`getLegacyColumnKey`).
- // Use `getColumnSettings` which checks for both keys.
+
+ /**
+ * Per-column titles, number or currency formatting, and click behavior.
+ * Keys can be modern (`getColumnKey`) or legacy (`getLegacyColumnKey`).
+ */
column_settings?: Record<string, ColumnSettings>;
- // X-axis
+ /** Override the x-axis label. */
"graph.x_axis.title_text"?: string;
+
+ /** X-axis scale, such as ordinal, timeseries, histogram, linear, pow, or log. */
"graph.x_axis.scale"?: XAxisScale;
+
+ /** Hide, compact, or rotate x-axis labels where the visualization supports it. */
"graph.x_axis.axis_enabled"?:
| true
| false
@@ -325,82 +348,157 @@ export type VisualizationSettings = {
| "rotate-45"
| "rotate-90";
- // Y-axis
+ /** Let Metabase choose the y-axis bounds automatically. */
"graph.y_axis.auto_range"?: boolean;
+
+ /** Override the y-axis label. */
"graph.y_axis.title_text"?: string;
+
+ /** Y-axis numeric scale, such as linear, pow, or log. */
"graph.y_axis.scale"?: YAxisScale;
+
+ /** Show or hide the y-axis where the visualization supports it. */
"graph.y_axis.axis_enabled"?: boolean;
+ /** Fixed y-axis minimum when auto range is disabled. */
"graph.y_axis.min"?: number;
+
+ /** Fixed y-axis maximum when auto range is disabled. */
"graph.y_axis.max"?: number;
- // Goal
+ /** Numeric value for the goal line. */
"graph.goal_value"?: number;
+
+ /** Draw a goal line on supported cartesian charts. */
"graph.show_goal"?: boolean;
+
+ /** Label for the goal line. */
"graph.goal_label"?: string;
- // Trend
+ /** Add a trend line, best for time-based trends without extra groupings. */
"graph.show_trendline"?: boolean;
- // Split panels
+ /** Render compatible series in separate panels instead of one chart. */
"graph.split_panels"?: boolean;
- // Series
+ /**
+ * Result column names used for the x-axis, category, or grouping dimension.
+ * Prefer Metabase defaults unless the query needs a specific split.
+ */
"graph.dimensions"?: string[];
+
+ /**
+ * Result metric column names to plot. Useful when the query returns multiple
+ * numeric columns and Metabase should not infer the metrics.
+ */
"graph.metrics"?: string[];
- // Series settings
+ /** Per-series labels, colors, and display tweaks. Keys are data-dependent. */
series_settings?: Record<string, SeriesSettings | undefined>;
+ /** Explicit order, labels, colors, and enabled state for breakout series. */
"graph.series_order"?: SeriesOrderSetting[];
- // Scatter plot settings
- "scatter.bubble"?: string; // col name
+ /** Result numeric column name used to size scatter plot bubbles. */
+ "scatter.bubble"?: string;
- // Waterfall settings
+ /** Color used for increasing waterfall bars. */
"waterfall.increase_color"?: string;
+
+ /** Color used for decreasing waterfall bars. */
"waterfall.decrease_color"?: string;
+
+ /** Color used for the total waterfall bar. */
"waterfall.total_color"?: string;
+
+ /** Add a final total bar to a waterfall chart. */
"waterfall.show_total"?: boolean;
- // Funnel settings
+ /** Explicit order, labels, colors, and enabled state for funnel steps. */
"funnel.rows"?: SeriesOrderSetting[];
+ /** Conditional formatting rules for table cells. */
"table.column_formatting"?: ColumnFormattingSetting[];
+
+ /** Pivot column selection. */
"pivot_table.column_split"?: PivotTableColumnSplitSetting;
+
+ /** Initially collapsed pivot rows. */
"pivot_table.collapsed_rows"?: PivotTableCollapsedRowsSetting;
- // Scalar Settings
+ /** Smart-scalar comparison configuration. */
"scalar.comparisons"?: SmartScalarComparison[];
+
+ /** Result column name to display as the main scalar value. */
"scalar.field"?: string;
+
+ /** Reverse good/bad direction for scalar comparisons. */
"scalar.switch_positive_negative"?: boolean;
+
+ /** Use compact formatting for the primary scalar number. */
"scalar.compact_primary_number"?: boolean;
+
+ /** Segment configuration for scalar visualizations. */
"scalar.segments"?: ScalarSegment[];
- // Pie Settings
+ /** Result column name, or names, used as pie slice dimensions. */
"pie.dimension"?: string | string[];
+
+ /** Result column name used as the middle ring dimension. */
"pie.middle_dimension"?: string;
+
+ /** Result column name used as the outer ring dimension. */
"pie.outer_dimension"?: string;
+
+ /** Explicit pie slice order, labels, colors, and enabled state. */
"pie.rows"?: PieRow[];
+
+ /** Result numeric column name used as the pie slice value. */
"pie.metric"?: string;
+
+ /** Sort pie slices by metric value. */
"pie.sort_rows"?: boolean;
+
+ /** Show the pie legend. */
"pie.show_legend"?: boolean;
+
+ /** Show the total value in the center of the pie. */
"pie.show_total"?: boolean;
+
+ /** Show labels on pie slices. */
"pie.show_labels"?: boolean;
+
+ /** Place percentages in the legend, inside slices, both, or neither. */
"pie.percent_visibility"?: "off" | "legend" | "inside" | "both";
+
+ /** Percentage decimal precision for pie labels. */
"pie.decimal_places"?: number;
+
+ /** Group small slices below this threshold into "Other". */
"pie.slice_threshold"?: number;
+
+ /** Legacy slice color map. Prefer defaults unless exact colors matter. */
"pie.colors"?: Record<string, string>;
- // Sankey settings
+ /** Result column name for the source node. */
"sankey.source"?: string;
+
+ /** Result column name for the target node. */
"sankey.target"?: string;
+
+ /** Result numeric column name for the flow value. */
"sankey.value"?: string;
+
+ /** Sankey node alignment. */
"sankey.node_align"?: "left" | "right" | "justify";
+
+ /** Show labels on Sankey flow edges. */
"sankey.show_edge_labels"?: boolean;
+
+ /** Formatting for Sankey edge labels. */
"sankey.label_value_formatting"?: "auto" | "full" | "compact";
- // Treemap settings
+ /** Treemap settings */
"treemap.grouping"?: string;
"treemap.sub_grouping"?: string | null;
"treemap.value"?: string;
@@ -410,17 +508,31 @@ export type VisualizationSettings = {
"treemap.show_leaf_labels"?: boolean;
"treemap.show_leaf_values"?: boolean;
- // BoxPlot settings
+ /** Box plot whisker calculation, such as Tukey or min/max. */
"boxplot.whisker_type"?: BoxPlotWhiskerType;
+
+ /** Show no points, outliers only, or all points. */
"boxplot.points_mode"?: BoxPlotPointsMode;
+
+ /** Show the mean marker. */
"boxplot.show_mean"?: boolean;
+
+ /** Show median values, all values, or no value labels. */
"boxplot.show_values_mode"?: BoxPlotShowValuesMode;
- // List view settings
- "list.columns"?: ListViewColumns; // set of columns selected for custom list view
- "list.entity_icon_enabled"?: boolean; // display/hide first list item column rendering image/icon
- "list.use_image_column"?: boolean; // render image from image/avatar url column instead of icon
+ /** Columns selected for custom list view. */
+ "list.columns"?: ListViewColumns;
+
+ /** Show or hide the first list item column that renders an image or icon. */
+ "list.entity_icon_enabled"?: boolean;
+
+ /** Render an image from an image/avatar URL column instead of the default icon. */
+ "list.use_image_column"?: boolean;
+
+ /** Icon used for list entities when an image column is not used. */
"list.entity_icon"?: IconName | null;
+
+ /** Color used for the list entity icon. */
"list.entity_icon_color"?: string;
[key: string]: any;
diff --git a/frontend/src/metabase-types/api/data-app.ts b/frontend/src/metabase-types/api/data-app.ts
new file mode 100644
index 00000000000..852c40a73fd
--- /dev/null
+++ b/frontend/src/metabase-types/api/data-app.ts
@@ -0,0 +1,51 @@
+export type DataAppId = number;
+
+/**
+ * A data app materialized from the connected repository. The repo's
+ * `data_apps/<dir>/data_app.yaml` files are discovered on sync; one row exists
+ * per app and the bundle is cached in the app DB and served at `/apps/:name`.
+ * The repository itself is configured via the remote-sync settings.
+ */
+export interface DataApp {
+ id: DataAppId;
+ /** The app's slug. */
+ name: string;
+ display_name: string;
+ /** Path within the repo to the built bundle. */
+ bundle_path: string;
+ /** Admin toggle. When false the app is not served. */
+ enabled: boolean;
+ /**
+ * External origins the app's sandboxed bundle may `fetch`/XHR, from its
+ * `data_app.yaml`. Empty means none (Metabase data still flows through the
+ * SDK). Each entry is an origin, optionally with a `*.` wildcard.
+ */
+ allowed_hosts: string[];
+ /** SHA-256 of the cached bundle; `null` until the first successful sync. */
+ bundle_hash: string | null;
+ /** Git commit the cached bundle was synced from; `null` until first sync. */
+ last_synced_sha: string | null;
+ /** ISO timestamp of the last successful sync; `null` if never synced. */
+ last_synced_at: string | null;
+ /** Message from this app's most recent failed sync; `null` when it succeeded. */
+ sync_error: string | null;
+ created_at: string;
+ updated_at: string;
+}
+
+/**
+ * Status of the connected repository as it relates to data apps. The connection
+ * itself (URL / branch / token) is configured on the remote-sync settings page.
+ */
+export interface DataAppRepoStatus {
+ /** Whether a repository is connected via remote-sync. */
+ configured: boolean;
+ /** The connected repository URL, or `null` when none is connected. */
+ url: string | null;
+}
+
+export interface SetDataAppEnabledRequest {
+ /** The app's slug. */
+ name: string;
+ enabled: boolean;
+}
diff --git a/frontend/src/metabase-types/api/icon.ts b/frontend/src/metabase-types/api/icon.ts
index 5b16eba4277..a23d4eba2af 100644
--- a/frontend/src/metabase-types/api/icon.ts
+++ b/frontend/src/metabase-types/api/icon.ts
@@ -15,6 +15,7 @@ export type IconName =
| "alert"
| "alert_filled"
| "alert_confirm"
+ | "app"
| "archive"
| "area"
| "attachment"
diff --git a/frontend/src/metabase-types/api/index.ts b/frontend/src/metabase-types/api/index.ts
index 00fd4a90955..35bfd36b158 100644
--- a/frontend/src/metabase-types/api/index.ts
+++ b/frontend/src/metabase-types/api/index.ts
@@ -17,6 +17,7 @@ export * from "./comments";
export * from "./content-translation";
export * from "./custom-viz-plugin";
export * from "./dashboard";
+export * from "./data-app";
export * from "./database";
export * from "./dataset";
export * from "./dependencies";
diff --git a/frontend/src/metabase-types/api/mocks/data-app.ts b/frontend/src/metabase-types/api/mocks/data-app.ts
new file mode 100644
index 00000000000..25020192c6c
--- /dev/null
+++ b/frontend/src/metabase-types/api/mocks/data-app.ts
@@ -0,0 +1,17 @@
+import type { DataApp } from "metabase-types/api";
+
+export const createMockDataApp = (opts?: Partial<DataApp>): DataApp => ({
+ id: 1,
+ name: "sales",
+ display_name: "Sales",
+ bundle_path: "data_apps/sales/dist/index.js",
+ enabled: true,
+ allowed_hosts: [],
+ bundle_hash: "abc123",
+ last_synced_sha: "0123456789abcdef",
+ last_synced_at: "2024-01-01T00:00:00Z",
+ sync_error: null,
+ created_at: "2024-01-01T00:00:00Z",
+ updated_at: "2024-01-01T00:00:00Z",
+ ...opts,
+});
diff --git a/frontend/src/metabase-types/api/mocks/index.ts b/frontend/src/metabase-types/api/mocks/index.ts
index 24d6842dcb8..36b1399e657 100644
--- a/frontend/src/metabase-types/api/mocks/index.ts
+++ b/frontend/src/metabase-types/api/mocks/index.ts
@@ -6,6 +6,7 @@ export * from "./bookmark";
export * from "./card";
export * from "./collection";
export * from "./dashboard";
+export * from "./data-app";
export * from "./database";
export * from "./dataset";
export * from "./dependencies";
diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.ts
index c7cac017a44..20f0065d036 100644
--- a/frontend/src/metabase-types/api/mocks/settings.ts
+++ b/frontend/src/metabase-types/api/mocks/settings.ts
@@ -144,6 +144,7 @@ export const createMockTokenFeatures = (
table_data_editing: false,
semantic_search: false,
remote_sync: false,
+ "data-apps": false,
"transforms-basic": false,
"transforms-python": false,
library: false,
diff --git a/frontend/src/metabase-types/api/query.ts b/frontend/src/metabase-types/api/query.ts
index cdcfe264d35..4bbc3d936d3 100644
--- a/frontend/src/metabase-types/api/query.ts
+++ b/frontend/src/metabase-types/api/query.ts
@@ -4,6 +4,8 @@ import type { CardId } from "./card";
import type { DatabaseId } from "./database";
import type { TemplateTag, TemplateTags, TemporalUnit } from "./dataset";
import type { FieldId } from "./field";
+import type { MeasureId } from "./measure";
+import type { MetricId } from "./metric";
import type { Parameter } from "./parameters";
import type { SegmentId } from "./segment";
import type { TableId } from "./table";
@@ -457,7 +459,9 @@ export type TestSourceSpec = TestTableSourceSpec | TestCardSourceSpec;
export type TestColumnSpec = {
type: "column";
name: string;
+ tableId?: TableId;
sourceName?: string;
+ sourceFieldId?: FieldId;
displayName?: string;
// When the columns cannot be disambiguated with name, sourceName and displayName
@@ -470,9 +474,28 @@ export type TestExpressionSpec =
| TestOperatorSpec
| TestColumnSpec;
-export type TestFilterSpec = TestExpressionSpec;
+export type TestSegmentSpec = {
+ type: "segment";
+ id: SegmentId;
+};
+
+export type TestMeasureSpec = {
+ type: "measure";
+ id: MeasureId;
+};
-export type TestAggregationSpec = TestExpressionSpec | TestNamedExpressionSpec;
+export type TestMetricSpec = {
+ type: "metric";
+ id: MetricId;
+};
+
+export type TestFilterSpec = TestExpressionSpec | TestSegmentSpec;
+
+export type TestAggregationSpec =
+ | TestExpressionSpec
+ | TestNamedExpressionSpec
+ | TestMeasureSpec
+ | TestMetricSpec;
export type TestNamedExpressionSpec = {
name: string;
@@ -487,7 +510,7 @@ export type TestLiteralSpec = {
export type TestOperatorSpec = {
type: "operator";
operator: string;
- args?: TestExpressionSpec[];
+ args?: readonly TestExpressionSpec[];
};
export type TestTemporalBucketSpec = {
@@ -527,16 +550,16 @@ type TestJoinConditionSpec = {
export type TestOrderBySpec = TestColumnSpec & {
direction?: "asc" | "desc";
-};
+} & TestBinningSpec;
export type TestStageSpec = {
- fields?: TestColumnSpec[];
- expressions?: TestNamedExpressionSpec[];
- joins?: TestJoinSpec[];
- filters?: TestFilterSpec[];
- aggregations?: TestAggregationSpec[];
- breakouts?: TestBreakoutSpec[];
- orderBys?: TestOrderBySpec[];
+ fields?: readonly TestColumnSpec[];
+ expressions?: readonly TestNamedExpressionSpec[];
+ joins?: readonly TestJoinSpec[];
+ filters?: readonly TestFilterSpec[];
+ aggregations?: readonly TestAggregationSpec[];
+ breakouts?: readonly TestBreakoutSpec[];
+ orderBys?: readonly TestOrderBySpec[];
limit?: number;
};
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index b494e4b49dd..bf4bb9aac15 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -371,6 +371,7 @@ export const tokenFeatures = [
"etl_connections_pg",
"table_data_editing",
"remote_sync",
+ "data-apps",
"dependencies",
"schema-viewer",
"semantic_search",
diff --git a/frontend/src/metabase/AppComponent.tsx b/frontend/src/metabase/AppComponent.tsx
index cbbc3e60785..538a681cd90 100644
--- a/frontend/src/metabase/AppComponent.tsx
+++ b/frontend/src/metabase/AppComponent.tsx
@@ -7,6 +7,7 @@ import { Navbar } from "metabase/app/nav/Navbar";
import {
getIsAdminApp,
getIsAppBarVisible,
+ getIsDataApp,
getIsDataStudioApp,
getIsNavBarEnabled,
} from "metabase/app/selectors";
@@ -61,6 +62,7 @@ interface AppStateProps {
errorPage: AppErrorDescriptor | null;
isAdminApp: boolean;
isDataStudioApp: boolean;
+ isDataApp: boolean;
bannerMessageDescriptor?: string;
isAppBarVisible: boolean;
isNavBarEnabled: boolean;
@@ -84,6 +86,7 @@ const mapStateToProps = (
errorPage: getErrorPage(state),
isAdminApp: getIsAdminApp(state, props),
isDataStudioApp: getIsDataStudioApp(state, props),
+ isDataApp: getIsDataApp(state, props),
isAppBarVisible: getIsAppBarVisible(state, props),
isNavBarEnabled: getIsNavBarEnabled(state, props),
});
@@ -96,6 +99,7 @@ function App({
errorPage,
isAdminApp,
isDataStudioApp,
+ isDataApp,
isAppBarVisible,
isNavBarEnabled,
children,
@@ -136,7 +140,7 @@ function App({
<UndoListing />
<StatusListing />
<NewModals />
- <Metabot hide={isAdminApp || isDataStudioApp} />
+ <Metabot hide={isAdminApp || isDataStudioApp || isDataApp} />
</AppContentContainer>
</AppContainer>
<Palette />
diff --git a/frontend/src/metabase/admin/settings/components/SettingsNav/DataAppsNav.tsx b/frontend/src/metabase/admin/settings/components/SettingsNav/DataAppsNav.tsx
new file mode 100644
index 00000000000..e5db9277483
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/components/SettingsNav/DataAppsNav.tsx
@@ -0,0 +1,25 @@
+import { t } from "ttag";
+
+import { UpsellGem } from "metabase/common/components/upsells/components";
+import { useHasTokenFeature } from "metabase/common/hooks";
+import { Flex } from "metabase/ui";
+import * as Urls from "metabase/urls";
+
+import { SettingsNavItem } from "./SettingsNavItem";
+
+export const DataAppsNav = () => {
+ const hasDataApps = useHasTokenFeature("data-apps");
+
+ return (
+ <SettingsNavItem
+ path={Urls.DATA_APP_URL_SEGMENT}
+ icon="app"
+ label={
+ <Flex gap="sm" align="center">
+ <span>{t`Data apps`}</span>
+ {!hasDataApps && <UpsellGem />}
+ </Flex>
+ }
+ />
+ );
+};
diff --git a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx
index 0648d6430a5..e3d3c16f770 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx
@@ -10,6 +10,7 @@ import { getUserIsAdmin } from "metabase/selectors/user";
import { Box, Divider, Flex } from "metabase/ui";
import { CustomVisualizationsNav } from "./CustomVisualizationsNav";
+import { DataAppsNav } from "./DataAppsNav";
import { SettingsNavItem } from "./SettingsNavItem";
import { UpdatesNavItem } from "./UpdatesNavItem";
@@ -79,6 +80,7 @@ export function SettingsNav() {
/>
{/* do not allow users with "Settings access" permissions to access custom viz pages */}
{isAdmin && <CustomVisualizationsNav />}
+ {isAdmin && <DataAppsNav />}
<SettingsNavItem path="maps" label={t`Maps`} icon="pinmap" />
<SettingsNavItem
path={!hasWhitelabel ? "whitelabel" : undefined}
diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsx
new file mode 100644
index 00000000000..5b8446de8c3
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/DataAppsSettingsPage.tsx
@@ -0,0 +1,26 @@
+import { t } from "ttag";
+
+import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";
+import { UpsellDataApps } from "metabase/admin/upsells";
+import { useHasTokenFeature } from "metabase/common/hooks";
+import { PLUGIN_DATA_APPS } from "metabase/plugins";
+
+/**
+ * Admin page at /admin/settings/apps. Lives in OSS so the nav item + upsell
+ * show on every edition; the real management UI is provided by the enterprise
+ * plugin (`PLUGIN_DATA_APPS.ManageDataAppsPage`) and only rendered once the
+ * `data-apps` token feature is present.
+ */
+export function DataAppsManagePage() {
+ const hasDataApps = useHasTokenFeature("data-apps");
+
+ if (!hasDataApps) {
+ return (
+ <SettingsPageWrapper title={t`Data apps`}>
+ <UpsellDataApps location="settings-data-apps" />
+ </SettingsPageWrapper>
+ );
+ }
+
+ return <PLUGIN_DATA_APPS.ManageDataAppsPage />;
+}
diff --git a/frontend/src/metabase/admin/settingsRoutes.tsx b/frontend/src/metabase/admin/settingsRoutes.tsx
index 2330a4ca45a..45a3f2d5d24 100644
--- a/frontend/src/metabase/admin/settingsRoutes.tsx
+++ b/frontend/src/metabase/admin/settingsRoutes.tsx
@@ -9,6 +9,7 @@ import {
import type { State } from "metabase/redux/store";
import { Route, type RouteComponent, redirect } from "metabase/router";
import { getSetting } from "metabase/selectors/settings";
+import * as Urls from "metabase/urls";
import { GoogleAuthForm } from "./settings/auth/components/GoogleAuthForm";
import { SettingsLdapForm } from "./settings/components/SettingsLdapForm";
@@ -21,6 +22,7 @@ import {
CustomVisualizationsFormPage,
CustomVisualizationsManagePage,
} from "./settings/components/SettingsPages/CustomVisualizationsSettingsPage";
+import { DataAppsManagePage } from "./settings/components/SettingsPages/DataAppsSettingsPage";
import { EmailSettingsPage } from "./settings/components/SettingsPages/EmailSettingsPage";
import { GeneralSettingsPage } from "./settings/components/SettingsPages/GeneralSettingsPage";
import { LicenseSettingsPage } from "./settings/components/SettingsPages/LicenseSettingsPage";
@@ -100,6 +102,14 @@ export const getSettingsRoutes = (
/>
)}
</Route>
+ <Route
+ path={
+ Urls.DATA_APP_URL_SEGMENT
+ } /* do not allow users with "Settings access" permissions to access data apps pages */
+ element={<IsAdmin />}
+ >
+ <Route index component={DataAppsManagePage} />
+ </Route>
<Route path="uploads" component={UploadSettingsPage} />
<Route
path="python-runner"
diff --git a/frontend/src/metabase/admin/upsells/UpsellDataApps.tsx b/frontend/src/metabase/admin/upsells/UpsellDataApps.tsx
new file mode 100644
index 00000000000..696d3034fef
--- /dev/null
+++ b/frontend/src/metabase/admin/upsells/UpsellDataApps.tsx
@@ -0,0 +1,32 @@
+import { t } from "ttag";
+
+import { UpsellBanner } from "metabase/common/components/upsells/components";
+import { UPGRADE_URL } from "metabase/common/components/upsells/constants";
+import { useHasTokenFeature } from "metabase/common/hooks";
+import { PLUGIN_ADMIN_SETTINGS } from "metabase/plugins";
+
+export const UpsellDataApps = ({ location }: { location: string }) => {
+ const hasDataApps = useHasTokenFeature("data-apps");
+ const campaign = "data-apps";
+ const { triggerUpsellFlow } = PLUGIN_ADMIN_SETTINGS.useUpsellFlow({
+ campaign,
+ location,
+ });
+
+ if (hasDataApps) {
+ return null;
+ }
+
+ return (
+ <UpsellBanner
+ title={t`Build apps on your data`}
+ campaign={campaign}
+ buttonText={t`Try for free`}
+ buttonLink={UPGRADE_URL}
+ location={location}
+ onClick={triggerUpsellFlow}
+ >
+ {t`Ship interactive apps powered by your data, served right inside Metabase.`}
+ </UpsellBanner>
+ );
+};
diff --git a/frontend/src/metabase/admin/upsells/index.ts b/frontend/src/metabase/admin/upsells/index.ts
index 316c7e846fd..f4dfac0a57e 100644
--- a/frontend/src/metabase/admin/upsells/index.ts
+++ b/frontend/src/metabase/admin/upsells/index.ts
@@ -2,6 +2,7 @@ export * from "./UpsellBetterSupport";
export * from "./UpsellCacheConfig";
export * from "./UpsellCloud";
export * from "./UpsellCustomViz";
+export * from "./UpsellDataApps";
export * from "./UpsellEmailWhitelabel";
export * from "./UpsellEmbeddingTheme";
export * from "./UpsellHosting";
diff --git a/frontend/src/metabase/api/client/types.ts b/frontend/src/metabase/api/client/types.ts
index a8781fe2b66..9cdb51e2953 100644
--- a/frontend/src/metabase/api/client/types.ts
+++ b/frontend/src/metabase/api/client/types.ts
@@ -22,7 +22,20 @@ export type ResponseFor<Raw extends boolean> = Raw extends true
? Response
: unknown;
-export type RequestClientInfo = { name: string; version?: string | null };
+export type RequestClientInfo = {
+ /**
+ * Client environment name
+ */
+ name: string;
+ /**
+ * Client identifier (if any), e.g. a data app name
+ */
+ identifier?: string;
+ /**
+ * SDK package version
+ */
+ version?: string | null;
+};
export type ResponseErrorInfo = {
metabaseVersion: string | null;
diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.ts
index 9e96d0d4838..76fd799818f 100644
--- a/frontend/src/metabase/api/tags/constants.ts
+++ b/frontend/src/metabase/api/tags/constants.ts
@@ -15,6 +15,7 @@ export const TAG_TYPES = [
"content-translation",
"dashboard",
"dashboard-question-candidates",
+ "data-app",
"database",
"dataset",
"document",
diff --git a/frontend/src/metabase/app-embed-mcp.tsx b/frontend/src/metabase/app-embed-mcp.tsx
index 73e3647c985..969b099d7d3 100644
--- a/frontend/src/metabase/app-embed-mcp.tsx
+++ b/frontend/src/metabase/app-embed-mcp.tsx
@@ -7,7 +7,6 @@ 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 { setSessionTokenHeader } from "metabase/embedding/lib/embedding-request-auth";
import { McpUiAppRoute } from "metabase/embedding/mcp/McpUiAppRoute";
import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
import { PLUGIN_API } from "metabase/plugins";
@@ -15,6 +14,7 @@ import { setBasename } from "metabase/utils/basename";
// Load EE plugins (whitelabeling, etc.) - no-op in OSS
import "sdk-iframe-embedding-ee-plugins";
+import { setSessionTokenHeader } from "./embedding/lib/auth/set-session-token-header";
EMBEDDING_SDK_CONFIG.isEmbeddingSdk = true;
EMBEDDING_SDK_CONFIG.isMcpApp = true;
diff --git a/frontend/src/metabase/app-main.js b/frontend/src/metabase/app-main.js
index 296cbe20ee0..a192ae630ab 100644
--- a/frontend/src/metabase/app-main.js
+++ b/frontend/src/metabase/app-main.js
@@ -6,7 +6,7 @@ import _ from "underscore";
import { api } from "metabase/api/client";
import { init } from "metabase/app";
-import { setRequestClientHeaders } from "metabase/embedding/lib/embedding-request-auth";
+import { setRequestClientHeaders } from "metabase/embedding/lib/auth/set-request-client-headers";
import { PLUGIN_API } from "metabase/plugins";
import { mainReducers } from "metabase/reducers-main";
import { setErrorPage } from "metabase/redux/app";
diff --git a/frontend/src/metabase/app/selectors.ts b/frontend/src/metabase/app/selectors.ts
index 478ac41dc86..23f9118fda4 100644
--- a/frontend/src/metabase/app/selectors.ts
+++ b/frontend/src/metabase/app/selectors.ts
@@ -35,6 +35,10 @@ export const getIsDataStudioApp = createSelector([getRouterPath], (path) => {
return path.startsWith("/data-studio");
});
+export const getIsDataApp = createSelector([getRouterPath], (path) => {
+ return path.startsWith(`${Urls.DATA_APP_ROOT_URL}/`);
+});
+
export const getIsMetricsViewer = createSelector([getRouterPath], (path) => {
return path.startsWith("/explore");
});
@@ -69,6 +73,9 @@ const PATHS_WITHOUT_NAVBAR = [
/^\/setup/,
/^\/auth/,
/^\/data-studio/,
+ // Data apps run full-page with their own custom chrome (a hover-down panel),
+ // so neither the left navbar nor the top app bar should be shown.
+ new RegExp(`^${Urls.DATA_APP_ROOT_URL}/`),
/\/model\/.*\/query/,
/\/model\/.*\/columns/,
/\/model\/.*\/metadata/,
diff --git a/frontend/src/metabase/common/components/CopyTextArea/CopyTextArea.module.css b/frontend/src/metabase/common/components/CopyTextArea/CopyTextArea.module.css
new file mode 100644
index 00000000000..c927792b0c8
--- /dev/null
+++ b/frontend/src/metabase/common/components/CopyTextArea/CopyTextArea.module.css
@@ -0,0 +1,14 @@
+.input {
+ /* 8px block, 16px inline-start; extra inline-end leaves room for the copy button */
+ padding: var(--mantine-spacing-sm) 2.5rem var(--mantine-spacing-sm)
+ var(--mantine-spacing-md);
+ border: none;
+ border-radius: var(--mantine-radius-md);
+ background-color: var(--mb-color-background_page-secondary);
+}
+
+/* Pin the copy button to the top-right rather than centering it over a tall field. */
+.section {
+ align-items: flex-start;
+ padding-top: var(--mantine-spacing-xs);
+}
diff --git a/frontend/src/metabase/common/components/CopyTextArea/CopyTextArea.tsx b/frontend/src/metabase/common/components/CopyTextArea/CopyTextArea.tsx
new file mode 100644
index 00000000000..998dcff2d58
--- /dev/null
+++ b/frontend/src/metabase/common/components/CopyTextArea/CopyTextArea.tsx
@@ -0,0 +1,45 @@
+import cx from "classnames";
+import type { Ref } from "react";
+import { forwardRef } from "react";
+
+import type { TextareaProps } from "metabase/ui";
+import { Textarea } from "metabase/ui";
+
+import type { CopyTextFieldClassNames } from "../CopyTextField/copy-text-field-props";
+import { getCopyTextFieldProps } from "../CopyTextField/copy-text-field-props";
+
+import S from "./CopyTextArea.module.css";
+
+type CopyTextAreaProps = Omit<TextareaProps, "classNames"> & {
+ value: string;
+ onCopied?: () => void;
+ classNames?: CopyTextFieldClassNames<TextareaProps>;
+};
+
+/**
+ * The multi-line sibling of `CopyTextInput`: a read-only `Textarea` with the same
+ * copy button. Long single-line values soft-wrap for readability while the copied
+ * value stays exactly what was passed.
+ */
+export const CopyTextArea = forwardRef(function CopyTextArea(
+ { classNames, onClick, onCopied, readOnly, ...props }: CopyTextAreaProps,
+ ref: Ref<HTMLTextAreaElement>,
+) {
+ return (
+ <Textarea
+ {...props}
+ ref={ref}
+ {...getCopyTextFieldProps<HTMLTextAreaElement>({
+ value: props.value,
+ readOnly,
+ onClick,
+ onCopied,
+ })}
+ classNames={{
+ ...classNames,
+ input: cx(S.input, classNames?.input),
+ section: cx(S.section, classNames?.section),
+ }}
+ />
+ );
+});
diff --git a/frontend/src/metabase/common/components/CopyTextArea/CopyTextArea.unit.spec.tsx b/frontend/src/metabase/common/components/CopyTextArea/CopyTextArea.unit.spec.tsx
new file mode 100644
index 00000000000..348cf91869d
--- /dev/null
+++ b/frontend/src/metabase/common/components/CopyTextArea/CopyTextArea.unit.spec.tsx
@@ -0,0 +1,29 @@
+import userEvent from "@testing-library/user-event";
+
+import { renderWithProviders, screen } from "__support__/ui";
+
+import { CopyTextArea } from "./CopyTextArea";
+
+describe("CopyTextArea", () => {
+ it("copies the value and calls onCopied when clicking the copy button", async () => {
+ jest.mocked(navigator.clipboard.writeText).mockClear();
+ const onCopied = jest.fn();
+ renderWithProviders(
+ <CopyTextArea value="npx run --a --b" onCopied={onCopied} />,
+ );
+
+ await userEvent.click(screen.getByTestId("copy-button"));
+
+ expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
+ "npx run --a --b",
+ );
+ expect(onCopied).toHaveBeenCalled();
+ });
+
+ it("does not render the copy button when there is nothing to copy", () => {
+ renderWithProviders(<CopyTextArea value="" placeholder="Loading…" />);
+
+ expect(screen.getByPlaceholderText("Loading…")).toBeInTheDocument();
+ expect(screen.queryByTestId("copy-button")).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/common/components/CopyTextArea/index.ts b/frontend/src/metabase/common/components/CopyTextArea/index.ts
new file mode 100644
index 00000000000..6e06a5b4d40
--- /dev/null
+++ b/frontend/src/metabase/common/components/CopyTextArea/index.ts
@@ -0,0 +1 @@
+export * from "./CopyTextArea";
diff --git a/frontend/src/metabase/common/components/CopyTextField/copy-text-field-props.tsx b/frontend/src/metabase/common/components/CopyTextField/copy-text-field-props.tsx
new file mode 100644
index 00000000000..fc74da555af
--- /dev/null
+++ b/frontend/src/metabase/common/components/CopyTextField/copy-text-field-props.tsx
@@ -0,0 +1,65 @@
+import type { MouseEvent } from "react";
+import { t } from "ttag";
+
+import { ActionIcon, CopyButton, Icon, Tooltip } from "metabase/ui";
+
+type CopyableElement = HTMLInputElement | HTMLTextAreaElement;
+
+/**
+ * The record form of a Mantine field's `classNames`. `CopyText*` fields merge
+ * their own module classes into the caller's, which the function form (the
+ * other half of Mantine's union) cannot express.
+ */
+export type CopyTextFieldClassNames<Props extends { classNames?: unknown }> =
+ Exclude<Props["classNames"], (...args: never[]) => unknown>;
+
+export type CopyTextFieldOptions<E extends CopyableElement> = {
+ value: string;
+ readOnly?: boolean;
+ onClick?: (event: MouseEvent<E>) => void;
+ onCopied?: () => void;
+};
+
+const DEFAULT_READ_ONLY = true;
+
+export function getCopyTextFieldProps<E extends CopyableElement>({
+ value,
+ readOnly,
+ onClick,
+ onCopied,
+}: CopyTextFieldOptions<E>) {
+ const isReadOnly = readOnly ?? DEFAULT_READ_ONLY;
+
+ return {
+ readOnly: isReadOnly,
+ onClick: (event: MouseEvent<E>) => {
+ if (isReadOnly) {
+ event.currentTarget.setSelectionRange(
+ 0,
+ event.currentTarget.value.length,
+ );
+ }
+ onClick?.(event);
+ },
+ rightSectionPointerEvents: "all" as const,
+ rightSection: value ? (
+ <CopyButton value={value} timeout={2000}>
+ {({ copied, copy }) => (
+ <Tooltip label={t`Copied!`} opened={copied}>
+ <ActionIcon
+ variant="subtle"
+ aria-label={t`Copy`}
+ data-testid="copy-button"
+ onClick={() => {
+ copy();
+ onCopied?.();
+ }}
+ >
+ <Icon name="copy" />
+ </ActionIcon>
+ </Tooltip>
+ )}
+ </CopyButton>
+ ) : undefined,
+ };
+}
diff --git a/frontend/src/metabase/common/components/CopyTextInput/CopyTextInput.tsx b/frontend/src/metabase/common/components/CopyTextInput/CopyTextInput.tsx
index 964389df97c..c45b7cfc621 100644
--- a/frontend/src/metabase/common/components/CopyTextInput/CopyTextInput.tsx
+++ b/frontend/src/metabase/common/components/CopyTextInput/CopyTextInput.tsx
@@ -1,69 +1,39 @@
import cx from "classnames";
import type { Ref } from "react";
import { forwardRef } from "react";
-import { t } from "ttag";
import type { TextInputProps } from "metabase/ui";
-import { ActionIcon, CopyButton, Icon, TextInput, Tooltip } from "metabase/ui";
+import { TextInput } from "metabase/ui";
+
+import type { CopyTextFieldClassNames } from "../CopyTextField/copy-text-field-props";
+import { getCopyTextFieldProps } from "../CopyTextField/copy-text-field-props";
import S from "./CopyTextInput.module.css";
-const defaultProps = {
- readOnly: true,
- value: "copy me",
+export type CopyTextInputProps = Omit<TextInputProps, "classNames"> & {
+ value: string;
+ onCopied?: () => void;
+ classNames?: CopyTextFieldClassNames<TextInputProps>;
};
export const CopyTextInput = forwardRef(function CopyTextInput(
- {
- classNames,
- onClick,
- onCopied,
- readOnly,
- ...props
- }: TextInputProps & { value: string; onCopied?: () => void },
+ { classNames, onClick, onCopied, readOnly, ...props }: CopyTextInputProps,
ref: Ref<HTMLInputElement>,
) {
- const isReadOnly = readOnly ?? defaultProps.readOnly;
-
return (
<TextInput
- {...defaultProps}
{...props}
ref={ref}
- readOnly={isReadOnly}
- onClick={(e) => {
- if (isReadOnly) {
- e.currentTarget.setSelectionRange(0, e.currentTarget.value.length);
- }
- onClick?.(e);
- }}
+ {...getCopyTextFieldProps<HTMLInputElement>({
+ value: props.value,
+ readOnly,
+ onClick,
+ onCopied,
+ })}
classNames={{
...classNames,
- // Unjustified type cast. FIXME
- input: cx(S.input, (classNames as Record<string, string>)?.input),
+ input: cx(S.input, classNames?.input),
}}
- rightSectionPointerEvents="all"
- rightSection={
- props.value ? (
- <CopyButton value={props.value} timeout={2000}>
- {({ copied, copy }) => (
- <Tooltip label={t`Copied!`} opened={copied}>
- <ActionIcon
- variant="subtle"
- aria-label={t`Copy`}
- data-testid="copy-button"
- onClick={() => {
- copy();
- onCopied?.();
- }}
- >
- <Icon name="copy" />
- </ActionIcon>
- </Tooltip>
- )}
- </CopyButton>
- ) : undefined
- }
/>
);
});
diff --git a/frontend/src/metabase/common/components/ErrorDetails/ErrorBox.tsx b/frontend/src/metabase/common/components/ErrorDetails/ErrorBox.tsx
index ce068232e6f..edf059e1fcc 100644
--- a/frontend/src/metabase/common/components/ErrorDetails/ErrorBox.tsx
+++ b/frontend/src/metabase/common/components/ErrorDetails/ErrorBox.tsx
@@ -1,11 +1,19 @@
+import cx from "classnames";
+
import { Box } from "metabase/ui";
import S from "./ErrorDetails.module.css";
import type { ErrorDetails } from "./types";
-export const ErrorBox = ({ children }: { children: ErrorDetails }) => (
+export const ErrorBox = ({
+ children,
+ className,
+}: {
+ children: ErrorDetails;
+ className?: string;
+}) => (
<Box
- className={S.monospace}
+ className={cx(S.monospace, className)}
p="md"
mt="sm"
fw="bold"
diff --git a/frontend/src/metabase/common/components/ErrorDetails/ErrorDetails.tsx b/frontend/src/metabase/common/components/ErrorDetails/ErrorDetails.tsx
index 06fb885b64f..e83df450d83 100644
--- a/frontend/src/metabase/common/components/ErrorDetails/ErrorDetails.tsx
+++ b/frontend/src/metabase/common/components/ErrorDetails/ErrorDetails.tsx
@@ -11,6 +11,7 @@ export function ErrorDetails({
details,
centered,
className,
+ errorBoxClassName,
}: ErrorDetailsProps) {
const [showError, setShowError] = useState(false);
@@ -34,7 +35,7 @@ export function ErrorDetails({
className={cx(CS.pt3, centered ? CS.textCentered : CS.textLeft)}
>
<h2>{t`Here's the full error message`}</h2>
- <ErrorBox>{details}</ErrorBox>
+ <ErrorBox className={errorBoxClassName}>{details}</ErrorBox>
</div>
</div>
);
diff --git a/frontend/src/metabase/common/components/ErrorDetails/types.ts b/frontend/src/metabase/common/components/ErrorDetails/types.ts
index 639ce5d3491..d9f5bdc5c85 100644
--- a/frontend/src/metabase/common/components/ErrorDetails/types.ts
+++ b/frontend/src/metabase/common/components/ErrorDetails/types.ts
@@ -4,4 +4,6 @@ export interface ErrorDetailsProps {
details?: ErrorDetails;
centered?: boolean;
className?: string;
+ /** Class applied to the inner error/stack-trace box (`ErrorBox`). */
+ errorBoxClassName?: string;
}
diff --git a/frontend/src/metabase/embedding-sdk/config.ts b/frontend/src/metabase/embedding-sdk/config.ts
index a49ad5c912a..3aa6562f27e 100644
--- a/frontend/src/metabase/embedding-sdk/config.ts
+++ b/frontend/src/metabase/embedding-sdk/config.ts
@@ -5,10 +5,14 @@ export const EMBEDDING_SDK_PORTAL_ROOT_ELEMENT_ID = "metabase-sdk-portal-root";
type InternalSdkConfig = {
isEmbeddingSdk: boolean;
isMcpApp: boolean;
+ isDataApp: boolean;
+ isDataAppDev: boolean;
metabaseClientRequestHeader:
| "embedding-sdk-react"
| "embedding-simple"
- | "mcp-apps";
+ | "mcp-apps"
+ | "data-app";
+ metabaseClientRequestIdentifier: string | undefined;
enableEmbeddingSettingKey: "enable-embedding-sdk" | "enable-embedding-simple";
tokenFeatureKey: "embedding_sdk" | "embedding_simple";
};
@@ -25,11 +29,29 @@ export const EMBEDDING_SDK_CONFIG: InternalSdkConfig = {
**/
isMcpApp: false,
+ /**
+ * Whether we are in the Data App context.
+ **/
+ isDataApp: false,
+
+ /**
+ * Whether the data app runs in the local development flow. Reported to the
+ * backend via the X-Metabase-Embedded-Preview header, so its traffic is
+ * recorded as the "data-app-preview" embedding client.
+ **/
+ isDataAppDev: false,
+
/**
* Which X-Metabase-Client header to use for requests to the Metabase instance?
*/
metabaseClientRequestHeader: "embedding-sdk-react",
+ /**
+ * Which X-Metabase-Client-Identifier header to use for requests to the
+ * Metabase instance? Identifies the concrete client, e.g. a data app name.
+ */
+ metabaseClientRequestIdentifier: undefined,
+
/**
* Which setting indicates whether the embedding is enabled?
*/
@@ -61,7 +83,17 @@ export const isEmbeddingSdk = () => EMBEDDING_SDK_CONFIG.isEmbeddingSdk;
export const isEmbeddingMcpApp = () => EMBEDDING_SDK_CONFIG.isMcpApp;
/**
- * Whether we are in the Embedded Analytics JS
+ * Whether we are in the Embedded Analytics JS.
*/
export const isEmbeddingEajs = () =>
EMBEDDING_SDK_IFRAME_EMBEDDING_CONFIG.isSimpleEmbedding;
+
+/**
+ * Whether we are in the Data App context.
+ */
+export const isDataApp = () => EMBEDDING_SDK_CONFIG.isDataApp;
+
+/**
+ * Whether we are in the Data App context.
+ */
+export const isDataAppDev = () => EMBEDDING_SDK_CONFIG.isDataAppDev;
diff --git a/frontend/src/metabase/embedding-sdk/types/error-component.ts b/frontend/src/metabase/embedding-sdk/types/error-component.ts
new file mode 100644
index 00000000000..c04b5614bd8
--- /dev/null
+++ b/frontend/src/metabase/embedding-sdk/types/error-component.ts
@@ -0,0 +1,15 @@
+import type { JSX, ReactNode } from "react";
+
+export type SdkErrorComponentProps = {
+ type?: "relative" | "fixed";
+ message: ReactNode;
+ error?: Error;
+ withCloseButton?: boolean;
+ onClose?: () => void;
+};
+
+export type SdkErrorComponent = ({
+ type,
+ message,
+ error,
+}: SdkErrorComponentProps) => JSX.Element;
diff --git a/frontend/src/metabase/embedding-sdk/types/question.ts b/frontend/src/metabase/embedding-sdk/types/question.ts
index b59360685c4..c561b37f2a0 100644
--- a/frontend/src/metabase/embedding-sdk/types/question.ts
+++ b/frontend/src/metabase/embedding-sdk/types/question.ts
@@ -1,3 +1,6 @@
+import type { VisualizationSettings } from "metabase-types/api/card";
+import type { CustomVizDisplayType } from "metabase-types/api/visualization";
+
export interface MetabaseQuestion {
id: number;
name: string;
@@ -6,3 +9,269 @@ export interface MetabaseQuestion {
isSavedQuestion: boolean;
}
+
+/**
+ * Each visualization below exposes a curated subset of {@link VisualizationSettings}
+ * via `Pick`. Only these keys are allowed, so `visualizationSettings` autocompletes
+ * and typechecks against the chosen `visualization`. To surface another setting,
+ * add its key to the relevant family. Custom visualizations (`custom:...`) are the
+ * exception and accept any settings.
+ *
+ * Omit `visualization` when Metabase should infer a display from the query.
+ * Set `visualization` when the user or design asks for a specific chart type.
+ * Only set `visualizationSettings` when a user or design asks for a specific
+ * presentation detail, such as hiding an axis label, showing value labels,
+ * stacking bars, adding a goal line, ordering table columns, or showing pie
+ * totals.
+ */
+
+/**
+ * Settings for bar, line, area, combo, and row charts. Use these to pin result
+ * columns, labels, scales, stacking, goal lines, trend lines, series order, or
+ * per-column formatting.
+ */
+export type CartesianVisualizationSettings = Pick<
+ VisualizationSettings,
+ | "graph.dimensions"
+ | "graph.metrics"
+ | "graph.series_order"
+ | "graph.show_values"
+ | "graph.show_trendline"
+ | "graph.show_goal"
+ | "graph.goal_value"
+ | "graph.goal_label"
+ | "graph.x_axis.title_text"
+ | "graph.x_axis.scale"
+ | "graph.x_axis.axis_enabled"
+ | "graph.y_axis.title_text"
+ | "graph.y_axis.scale"
+ | "graph.y_axis.auto_range"
+ | "graph.y_axis.min"
+ | "graph.y_axis.max"
+ | "stackable.stack_type"
+ | "series_settings"
+ | "column_settings"
+>;
+
+/**
+ * Settings for scatter plots. `graph.dimensions` selects the x-axis result
+ * column, `graph.metrics` selects the y-axis result column, and
+ * `scatter.bubble` optionally selects a numeric bubble-size column.
+ */
+export type ScatterVisualizationSettings = Pick<
+ VisualizationSettings,
+ | "graph.dimensions"
+ | "graph.metrics"
+ | "graph.x_axis.scale"
+ | "graph.y_axis.scale"
+ | "scatter.bubble"
+ | "series_settings"
+ | "column_settings"
+>;
+
+/**
+ * Settings for waterfall charts. Use these to choose step/value result
+ * columns, show step labels, override waterfall colors, add a total bar, or
+ * format columns.
+ */
+export type WaterfallVisualizationSettings = Pick<
+ VisualizationSettings,
+ | "graph.dimensions"
+ | "graph.metrics"
+ | "graph.show_values"
+ | "waterfall.increase_color"
+ | "waterfall.decrease_color"
+ | "waterfall.total_color"
+ | "waterfall.show_total"
+ | "column_settings"
+>;
+
+/**
+ * Settings for table, pivot, object detail, and list displays. Use these for
+ * visible column order, conditional formatting, pivot state, and per-column
+ * titles or number/currency formatting.
+ */
+export type TableVisualizationSettings = Pick<
+ VisualizationSettings,
+ | "table.columns"
+ | "table.column_formatting"
+ | "pivot_table.column_split"
+ | "pivot_table.collapsed_rows"
+ | "column_settings"
+>;
+
+/**
+ * Settings for pie and donut charts. Use these to pin slice/value result
+ * columns, sort slices, show legends, labels, totals, percentages, thresholds,
+ * colors, or column formatting.
+ */
+export type PieVisualizationSettings = Pick<
+ VisualizationSettings,
+ | "pie.dimension"
+ | "pie.metric"
+ | "pie.sort_rows"
+ | "pie.show_legend"
+ | "pie.show_total"
+ | "pie.show_labels"
+ | "pie.percent_visibility"
+ | "pie.decimal_places"
+ | "pie.slice_threshold"
+ | "pie.colors"
+ | "column_settings"
+>;
+
+/**
+ * Settings for scalar, smart scalar, gauge, and progress displays. Use these to
+ * select the main value column, compact the number, reverse comparison meaning,
+ * configure smart-scalar comparisons, or format columns.
+ */
+export type ScalarVisualizationSettings = Pick<
+ VisualizationSettings,
+ | "scalar.field"
+ | "scalar.switch_positive_negative"
+ | "scalar.compact_primary_number"
+ | "scalar.comparisons"
+ | "column_settings"
+>;
+
+/**
+ * Settings for funnel charts. Use `funnel.rows` only when you know the exact
+ * row keys and need explicit step order, labels, colors, or enabled state.
+ */
+export type FunnelVisualizationSettings = Pick<
+ VisualizationSettings,
+ "funnel.rows" | "column_settings"
+>;
+
+/**
+ * Settings for Sankey charts. Use these to select source, target, and flow
+ * value result columns, control node alignment, show edge labels, or format
+ * columns.
+ */
+export type SankeyVisualizationSettings = Pick<
+ VisualizationSettings,
+ | "sankey.source"
+ | "sankey.target"
+ | "sankey.value"
+ | "sankey.node_align"
+ | "sankey.show_edge_labels"
+ | "column_settings"
+>;
+
+/**
+ * Settings for box plots. Use these to choose whisker calculation, point
+ * visibility, mean marker visibility, value label mode, or column formatting.
+ */
+export type BoxplotVisualizationSettings = Pick<
+ VisualizationSettings,
+ | "boxplot.whisker_type"
+ | "boxplot.points_mode"
+ | "boxplot.show_mean"
+ | "boxplot.show_values_mode"
+ | "column_settings"
+>;
+
+/**
+ * Settings for pin and region maps. No map-specific settings are surfaced yet;
+ * use `column_settings` for stable column formatting only.
+ */
+export type MapVisualizationSettings = Pick<
+ VisualizationSettings,
+ "column_settings"
+>;
+
+/**
+ * Public structural type for ad-hoc SDK queries created by
+ * `useMetabaseQueryObject`.
+ *
+ * @public
+ */
+export type MetabaseQueryObject =
+ // Do not use the internal `DatasetQuery` type here. It carries an opaque marker
+ // that can be emitted separately from the main SDK and data-app declaration
+ // rollups, making otherwise identical query values fail across package entry
+ // points. This structural type keeps those entry points compatible while still
+ // being narrow enough to reject passing the whole hook result as `card.query`.
+ | { type: "query"; database?: unknown; query?: unknown; parameters?: unknown }
+ | {
+ type: "native";
+ database?: unknown;
+ native?: unknown;
+ parameters?: unknown;
+ }
+ | {
+ "lib/type": "mbql/query";
+ database?: unknown;
+ stages?: unknown;
+ parameters?: unknown;
+ };
+
+interface MetabaseCardBase {
+ query: MetabaseQueryObject | null;
+ displayIsLocked?: boolean;
+}
+
+/**
+ * Ad-hoc card definition for SDK-rendered questions. Pass only `query` when
+ * Metabase should infer a display from the query result. Add `visualization`
+ * when the user or design asks for a specific chart type. Add
+ * `visualizationSettings` only for explicit setting-level presentation changes.
+ *
+ * @notExported MetabaseCardBase
+ * @notExported TableVisualizationSettings
+ * @notExported CartesianVisualizationSettings
+ * @notExported ScatterVisualizationSettings
+ * @notExported WaterfallVisualizationSettings
+ * @notExported PieVisualizationSettings
+ * @notExported ScalarVisualizationSettings
+ * @notExported FunnelVisualizationSettings
+ * @notExported MapVisualizationSettings
+ * @notExported SankeyVisualizationSettings
+ * @notExported BoxplotVisualizationSettings
+ * @notExported CustomVizDisplayType
+ */
+export type MetabaseCard = MetabaseCardBase &
+ (
+ | {
+ visualization?: never;
+ visualizationSettings?: never;
+ }
+ | {
+ visualization: "table" | "pivot" | "object" | "list";
+ visualizationSettings?: TableVisualizationSettings;
+ }
+ | {
+ visualization: "bar" | "line" | "area" | "combo" | "row";
+ visualizationSettings?: CartesianVisualizationSettings;
+ }
+ | {
+ visualization: "scatter";
+ visualizationSettings?: ScatterVisualizationSettings;
+ }
+ | {
+ visualization: "waterfall";
+ visualizationSettings?: WaterfallVisualizationSettings;
+ }
+ | { visualization: "pie"; visualizationSettings?: PieVisualizationSettings }
+ | {
+ visualization: "scalar" | "smartscalar" | "gauge" | "progress";
+ visualizationSettings?: ScalarVisualizationSettings;
+ }
+ | {
+ visualization: "funnel";
+ visualizationSettings?: FunnelVisualizationSettings;
+ }
+ | { visualization: "map"; visualizationSettings?: MapVisualizationSettings }
+ | {
+ visualization: "sankey";
+ visualizationSettings?: SankeyVisualizationSettings;
+ }
+ | {
+ visualization: "boxplot";
+ visualizationSettings?: BoxplotVisualizationSettings;
+ }
+ | {
+ visualization: CustomVizDisplayType;
+ visualizationSettings?: Record<string, unknown>;
+ }
+ );
diff --git a/frontend/src/metabase/embedding/config.ts b/frontend/src/metabase/embedding/config.ts
index a12a9803cb8..1ed05e1fa46 100644
--- a/frontend/src/metabase/embedding/config.ts
+++ b/frontend/src/metabase/embedding/config.ts
@@ -1,11 +1,16 @@
+import { getSdkPackageVersion } from "embedding-sdk-shared/lib/get-build-info";
import {
- setEmbedPreviewHeader,
- setRequestClientHeaders,
-} from "metabase/embedding/lib/embedding-request-auth";
-import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
-import { PLUGIN_API } from "metabase/plugins";
+ EMBEDDING_SDK_CONFIG,
+ isDataApp,
+ isEmbeddingSdk,
+} from "metabase/embedding-sdk/config";
+import { PLUGIN_API, PLUGIN_EMBEDDING_SDK } from "metabase/plugins";
import { IFRAMED_IN_SELF, isWithinIframe } from "metabase/utils/iframe";
+import { setEmbedPreviewHeader } from "./lib/auth/set-embed-preview-header";
+import { setReactSdkEmbedReferrerHeader } from "./lib/auth/set-react-sdk-embed-referrer-header";
+import { setRequestClientHeaders } from "./lib/auth/set-request-client-headers";
+
type InternalEmbeddingConfig = {
isPublicEmbedding: boolean;
isStaticEmbedding: boolean;
@@ -35,9 +40,36 @@ export function setIsStaticEmbedding() {
PLUGIN_API.onBeforeRequestHandlers.setRequestClientHeaders =
setRequestClientHeaders({ name: "embedding-iframe-static" });
}
+
EMBEDDING_CONFIG.isStaticEmbedding = true;
}
+export function setDataApp(
+ dataAppName: string,
+ { isDev = false }: { isDev?: boolean } = {},
+) {
+ const sdkPackageVersion = getSdkPackageVersion();
+
+ EMBEDDING_SDK_CONFIG.isEmbeddingSdk = true;
+ EMBEDDING_SDK_CONFIG.isDataApp = true;
+ EMBEDDING_SDK_CONFIG.isDataAppDev = isDev;
+ EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader = "data-app";
+ EMBEDDING_SDK_CONFIG.metabaseClientRequestIdentifier = dataAppName;
+
+ PLUGIN_API.onBeforeRequestHandlers.setRequestClientHeaders =
+ setRequestClientHeaders({
+ name: EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader,
+ version: sdkPackageVersion,
+ identifier: EMBEDDING_SDK_CONFIG.metabaseClientRequestIdentifier,
+ });
+
+ PLUGIN_API.onBeforeRequestHandlers.setEmbedPreviewHeader =
+ setEmbedPreviewHeader;
+
+ PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.reactSdkEmbedReferrer =
+ setReactSdkEmbedReferrerHeader;
+}
+
export function isPublicEmbedding() {
return EMBEDDING_CONFIG.isPublicEmbedding;
}
@@ -51,9 +83,9 @@ export function isEmbedding() {
}
/**
- * Detect if this page is embedded in itself, i.e. it's an embed preview.
- * It will need to do something different if we ever embed Metabase in itself for another reason.
+ * Detect if this page is self embed within Metabase (embed preview).
+ * As data apps are also rendered inside metabase, we check that it's not the data app environment
*/
export function isEmbedPreview() {
- return IFRAMED_IN_SELF;
+ return IFRAMED_IN_SELF && !isDataApp();
}
diff --git a/frontend/src/metabase/embedding/config.unit.spec.ts b/frontend/src/metabase/embedding/config.unit.spec.ts
new file mode 100644
index 00000000000..ad2c15896f7
--- /dev/null
+++ b/frontend/src/metabase/embedding/config.unit.spec.ts
@@ -0,0 +1,142 @@
+import type {
+ OnBeforeRequestHandler,
+ OnBeforeRequestHandlerConfig,
+} from "metabase/api/client";
+import {
+ EMBEDDING_SDK_CONFIG,
+ isDataAppDev,
+} from "metabase/embedding-sdk/config";
+import { PLUGIN_API } from "metabase/plugins";
+
+import { isEmbedPreview, setDataApp } from "./config";
+import { setRequestClientHeaders } from "./lib/auth/set-request-client-headers";
+
+const iframeState = { iframedInSelf: false };
+
+jest.mock("metabase/utils/iframe", () => ({
+ get IFRAMED_IN_SELF() {
+ return iframeState.iframedInSelf;
+ },
+ isWithinIframe: () => false,
+}));
+
+const REQUEST: OnBeforeRequestHandlerConfig = {
+ method: "GET",
+ url: "/api/health",
+ data: {},
+};
+
+const runHandler = (handler: OnBeforeRequestHandler) => handler(REQUEST);
+
+describe("setDataApp", () => {
+ const originalConfig = { ...EMBEDDING_SDK_CONFIG };
+ const originalHandlers = { ...PLUGIN_API.onBeforeRequestHandlers };
+
+ afterEach(() => {
+ Object.assign(EMBEDDING_SDK_CONFIG, originalConfig);
+ Object.assign(PLUGIN_API.onBeforeRequestHandlers, originalHandlers);
+ iframeState.iframedInSelf = false;
+ });
+
+ it("configures the data-app context on the shared config", () => {
+ setDataApp("sales");
+
+ expect(EMBEDDING_SDK_CONFIG.isEmbeddingSdk).toBe(true);
+ expect(EMBEDDING_SDK_CONFIG.isDataApp).toBe(true);
+ expect(EMBEDDING_SDK_CONFIG.isDataAppDev).toBe(false);
+ expect(EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader).toBe("data-app");
+ expect(EMBEDDING_SDK_CONFIG.metabaseClientRequestIdentifier).toBe("sales");
+ });
+
+ it("installs a handler that sends the data-app client and identifier headers", async () => {
+ setDataApp("sales");
+
+ expect(
+ await runHandler(
+ PLUGIN_API.onBeforeRequestHandlers.setRequestClientHeaders,
+ ),
+ ).toEqual({
+ headers: {
+ "X-Metabase-Client": "data-app",
+ "X-Metabase-Client-Identifier": "sales",
+ },
+ });
+ });
+
+ it("omits the identifier header when the app name is unknown", async () => {
+ setDataApp("");
+
+ expect(
+ await runHandler(
+ PLUGIN_API.onBeforeRequestHandlers.setRequestClientHeaders,
+ ),
+ ).toEqual({ headers: { "X-Metabase-Client": "data-app" } });
+ });
+
+ it("does not send the embed-preview header for a non-dev data app", async () => {
+ setDataApp("sales");
+
+ expect(
+ await runHandler(
+ PLUGIN_API.onBeforeRequestHandlers.setEmbedPreviewHeader,
+ ),
+ ).toBeUndefined();
+ });
+
+ it("sends the embed-preview header for a dev data app, so it is recorded as data-app-preview", async () => {
+ setDataApp("sales", { isDev: true });
+
+ expect(isDataAppDev()).toBe(true);
+ expect(
+ await runHandler(
+ PLUGIN_API.onBeforeRequestHandlers.setEmbedPreviewHeader,
+ ),
+ ).toEqual({ headers: { "X-Metabase-Embedded-Preview": "true" } });
+ });
+
+ it("keeps the same headers when the SDK re-installs the handler from the config", async () => {
+ // `useInitData` (run by every SDK component's ComponentProvider) replaces
+ // the handler slot with one built from EMBEDDING_SDK_CONFIG. It must
+ // produce the same headers, or mounting an SDK component silently drops
+ // the data-app attribution.
+ setDataApp("sales");
+
+ const installed = await runHandler(
+ PLUGIN_API.onBeforeRequestHandlers.setRequestClientHeaders,
+ );
+ const reinstalled = await runHandler(
+ setRequestClientHeaders({
+ name: EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader,
+ identifier: EMBEDDING_SDK_CONFIG.metabaseClientRequestIdentifier,
+ }),
+ );
+
+ expect(reinstalled).toEqual(installed);
+ });
+});
+
+describe("isEmbedPreview", () => {
+ const originalConfig = { ...EMBEDDING_SDK_CONFIG };
+
+ afterEach(() => {
+ Object.assign(EMBEDDING_SDK_CONFIG, originalConfig);
+ iframeState.iframedInSelf = false;
+ });
+
+ it("is true when the page is iframed into itself", () => {
+ iframeState.iframedInSelf = true;
+
+ expect(isEmbedPreview()).toBe(true);
+ });
+
+ it("is false for a data app, which is always iframed into Metabase", () => {
+ iframeState.iframedInSelf = true;
+ EMBEDDING_SDK_CONFIG.isDataApp = true;
+
+ expect(isEmbedPreview()).toBe(false);
+ });
+
+ it("is false outside an iframe", () => {
+ expect(isEmbedPreview()).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-get-guest-embed-signed-token.ts b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-get-guest-embed-signed-token.ts
index 4540f418d94..9b86343bc67 100644
--- a/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-get-guest-embed-signed-token.ts
+++ b/frontend/src/metabase/embedding/embedding-iframe-sdk-setup/hooks/use-get-guest-embed-signed-token.ts
@@ -5,7 +5,8 @@ import { useSetting } from "metabase/common/hooks";
import type { SdkIframeEmbedSetupContextType } from "metabase/embedding/embedding-iframe-sdk-setup/context";
import { getResourceTypeFromExperience } from "metabase/embedding/embedding-iframe-sdk-setup/utils/get-resource-type-from-experience";
import { isQuestionOrDashboardSettings } from "metabase/embedding/embedding-iframe-sdk-setup/utils/is-question-or-dashboard-settings";
-import { getSignedToken } from "metabase/embedding/lib/embed";
+
+import { getSignedToken } from "../../lib/auth/get-signed-token";
const SIGNED_TOKEN_FOR_SNIPPET_EXPIRATION_MINUTES = 10;
const SIGNED_TOKEN_FOR_PREVIEW_EXPIRATION_MINUTES = 60;
diff --git a/frontend/src/metabase/embedding/lib/auth/get-session-token-headers.ts b/frontend/src/metabase/embedding/lib/auth/get-session-token-headers.ts
new file mode 100644
index 00000000000..0f1f7142024
--- /dev/null
+++ b/frontend/src/metabase/embedding/lib/auth/get-session-token-headers.ts
@@ -0,0 +1,8 @@
+/* eslint-disable metabase/no-literal-metabase-strings -- request header names */
+import type { OnBeforeRequestHandlerConfig } from "metabase/api/client";
+
+export const getSessionTokenHeaders = (
+ sessionToken: string,
+): Partial<OnBeforeRequestHandlerConfig> => ({
+ headers: { "X-Metabase-Session": sessionToken },
+});
diff --git a/frontend/src/metabase/embedding/lib/auth/get-signed-token.ts b/frontend/src/metabase/embedding/lib/auth/get-signed-token.ts
new file mode 100644
index 00000000000..33bf609e2c4
--- /dev/null
+++ b/frontend/src/metabase/embedding/lib/auth/get-signed-token.ts
@@ -0,0 +1,42 @@
+import { CompactSign } from "jose";
+
+import type {
+ EmbedResource,
+ EmbedResourceType,
+ EmbeddingParametersValues,
+} from "../../types";
+
+const DEFAULT_SIGNED_TOKEN_EXPIRATION_MINUTES = 10;
+
+export async function getSignedToken(
+ resourceType: EmbedResourceType,
+ rawResourceId: EmbedResource["id"],
+ params: EmbeddingParametersValues = {},
+ secretKey: string,
+ previewEmbeddingParams: EmbeddingParametersValues,
+ expirationMinutes: number = DEFAULT_SIGNED_TOKEN_EXPIRATION_MINUTES,
+) {
+ // rawResourceId is force converted to number
+ const normalizedResourceId = parseInt(rawResourceId as string, 10);
+
+ const iat = Math.round(new Date().getTime() / 1000);
+ const exp = iat + 60 * expirationMinutes;
+
+ const unsignedToken: Record<string, any> = {
+ resource: { [resourceType]: normalizedResourceId },
+ params: params,
+ iat,
+ exp,
+ };
+ // include the `embedding_params` settings inline in the token for previews
+ if (previewEmbeddingParams) {
+ unsignedToken._embedding_params = previewEmbeddingParams;
+ }
+
+ const encoder = new TextEncoder();
+ const key = encoder.encode(secretKey);
+
+ return new CompactSign(encoder.encode(JSON.stringify(unsignedToken)))
+ .setProtectedHeader({ alg: "HS256" })
+ .sign(key);
+}
diff --git a/frontend/src/metabase/embedding/lib/auth/set-api-key-header.ts b/frontend/src/metabase/embedding/lib/auth/set-api-key-header.ts
new file mode 100644
index 00000000000..d3cbb78f349
--- /dev/null
+++ b/frontend/src/metabase/embedding/lib/auth/set-api-key-header.ts
@@ -0,0 +1,21 @@
+import type { OnBeforeRequestHandler } from "metabase/api/client";
+
+/**
+ * Factories for the embedding-only request-header plugin handlers. Each closes
+ * over its value, so there's no shared mutable state — the embedding setup flow
+ * installs the handlers it needs onto the plugin slots:
+ *
+ * - `setApiKeyHeader` / `setSessionTokenHeader` onto `setEmbeddingRequestAuthHeaders`
+ * for static auth (an API key, or a session token that never refreshes — e.g.
+ * MCP). A refreshing SSO session instead emits its header from
+ * `getOrRefreshSessionHandler` via `getSessionTokenHeaders`, so the refreshed
+ * token applies to the request that triggered the refresh.
+ * - `setRequestClientHeaders` onto its own slot
+ * - `setEmbedPreviewHeader` onto its own slot (public + SDK flows only)
+ *
+ * In the normal app none are installed, so no embedding headers are emitted —
+ * keeping these embedding concerns out of the generic api client.
+ */
+export const setApiKeyHeader =
+ (apiKey: string): OnBeforeRequestHandler =>
+ async () => ({ headers: { "X-Api-Key": apiKey } });
diff --git a/frontend/src/metabase/embedding/lib/auth/set-embed-preview-header.ts b/frontend/src/metabase/embedding/lib/auth/set-embed-preview-header.ts
new file mode 100644
index 00000000000..611221d60c3
--- /dev/null
+++ b/frontend/src/metabase/embedding/lib/auth/set-embed-preview-header.ts
@@ -0,0 +1,16 @@
+/* eslint-disable metabase/no-literal-metabase-strings -- request header names */
+import type { OnBeforeRequestHandler } from "metabase/api/client";
+import { isEmbedPreview } from "metabase/embedding/config";
+import { isDataAppDev } from "metabase/embedding-sdk/config";
+
+/**
+ * Tag requests coming from an embed preview (the page is iframed into itself).
+ * Kept separate from `setRequestClientHeaders` because preview mode is
+ * orthogonal to which client is embedding. Installed by the public, SDK embed flows, and Data App Dev
+ * — static and full-app deliberately don't tag preview requests (see EMB-930 in `metabase/embedding/config`).
+ */
+export const setEmbedPreviewHeader: OnBeforeRequestHandler = async () => {
+ if (isEmbedPreview() || isDataAppDev()) {
+ return { headers: { "X-Metabase-Embedded-Preview": "true" } };
+ }
+};
diff --git a/frontend/src/metabase/embedding/lib/auth/set-react-sdk-embed-referrer-header.ts b/frontend/src/metabase/embedding/lib/auth/set-react-sdk-embed-referrer-header.ts
new file mode 100644
index 00000000000..5290c3abb67
--- /dev/null
+++ b/frontend/src/metabase/embedding/lib/auth/set-react-sdk-embed-referrer-header.ts
@@ -0,0 +1,7 @@
+/* eslint-disable metabase/no-literal-metabase-strings -- request header names */
+import type { OnBeforeRequestHandler } from "metabase/api/client";
+
+export const setReactSdkEmbedReferrerHeader: OnBeforeRequestHandler =
+ async () => {
+ return { headers: { "X-Metabase-Embed-Referrer": window.location.href } };
+ };
diff --git a/frontend/src/metabase/embedding/lib/auth/set-request-client-headers.ts b/frontend/src/metabase/embedding/lib/auth/set-request-client-headers.ts
new file mode 100644
index 00000000000..d3e3df08e61
--- /dev/null
+++ b/frontend/src/metabase/embedding/lib/auth/set-request-client-headers.ts
@@ -0,0 +1,28 @@
+/* eslint-disable metabase/no-literal-metabase-strings -- request header names */
+import type {
+ OnBeforeRequestHandler,
+ RequestClientInfo,
+} from "metabase/api/client";
+
+/**
+ * This helper sets a client-related headers that help identify a client
+ */
+export const setRequestClientHeaders =
+ (requestClient: RequestClientInfo): OnBeforeRequestHandler =>
+ async () => {
+ const headers: Record<string, string> = {};
+
+ if (requestClient.name) {
+ headers["X-Metabase-Client"] = requestClient.name;
+ }
+
+ if (requestClient.version) {
+ headers["X-Metabase-Client-Version"] = requestClient.version;
+ }
+
+ if (requestClient.identifier) {
+ headers["X-Metabase-Client-Identifier"] = requestClient.identifier;
+ }
+
+ return { headers };
+ };
diff --git a/frontend/src/metabase/embedding/lib/auth/set-request-client-headers.unit.spec.ts b/frontend/src/metabase/embedding/lib/auth/set-request-client-headers.unit.spec.ts
new file mode 100644
index 00000000000..bdadb245369
--- /dev/null
+++ b/frontend/src/metabase/embedding/lib/auth/set-request-client-headers.unit.spec.ts
@@ -0,0 +1,52 @@
+import type { OnBeforeRequestHandlerConfig } from "metabase/api/client";
+
+import { setRequestClientHeaders } from "./set-request-client-headers";
+
+const REQUEST: OnBeforeRequestHandlerConfig = {
+ method: "GET",
+ url: "/api/health",
+ data: {},
+};
+
+describe("setRequestClientHeaders", () => {
+ it("emits the client, version, and identifier headers when all are set", async () => {
+ const handler = setRequestClientHeaders({
+ name: "data-app",
+ version: "1.2.3",
+ identifier: "sales",
+ });
+
+ expect(await handler(REQUEST)).toEqual({
+ headers: {
+ "X-Metabase-Client": "data-app",
+ "X-Metabase-Client-Version": "1.2.3",
+ "X-Metabase-Client-Identifier": "sales",
+ },
+ });
+ });
+
+ it("omits the identifier header when the identifier is undefined", async () => {
+ const handler = setRequestClientHeaders({ name: "data-app" });
+
+ expect(await handler(REQUEST)).toEqual({
+ headers: { "X-Metabase-Client": "data-app" },
+ });
+ });
+
+ it("omits the identifier header when the identifier is empty", async () => {
+ const handler = setRequestClientHeaders({
+ name: "data-app",
+ identifier: "",
+ });
+
+ expect(await handler(REQUEST)).toEqual({
+ headers: { "X-Metabase-Client": "data-app" },
+ });
+ });
+
+ it("emits no headers when nothing is set", async () => {
+ const handler = setRequestClientHeaders({ name: "" });
+
+ expect(await handler(REQUEST)).toEqual({ headers: {} });
+ });
+});
diff --git a/frontend/src/metabase/embedding/lib/auth/set-session-token-header.ts b/frontend/src/metabase/embedding/lib/auth/set-session-token-header.ts
new file mode 100644
index 00000000000..0abb88e4ea7
--- /dev/null
+++ b/frontend/src/metabase/embedding/lib/auth/set-session-token-header.ts
@@ -0,0 +1,8 @@
+import type { OnBeforeRequestHandler } from "metabase/api/client";
+
+import { getSessionTokenHeaders } from "./get-session-token-headers";
+
+export const setSessionTokenHeader =
+ (sessionToken: string): OnBeforeRequestHandler =>
+ async () =>
+ getSessionTokenHeaders(sessionToken);
diff --git a/frontend/src/metabase/embedding/lib/embed.ts b/frontend/src/metabase/embedding/lib/embed.ts
index f149f2e085e..49b5aea4085 100644
--- a/frontend/src/metabase/embedding/lib/embed.ts
+++ b/frontend/src/metabase/embedding/lib/embed.ts
@@ -1,47 +1,12 @@
import querystring from "querystring";
-import { CompactSign } from "jose"; // using jose because jsonwebtoken doesn't work on the web :-/
-
import type {
EmbedResource,
EmbedResourceType,
EmbeddingParametersValues,
} from "../types";
-const DEFAULT_SIGNED_TOKEN_EXPIRATION_MINUTES = 10;
-
-export async function getSignedToken(
- resourceType: EmbedResourceType,
- rawResourceId: EmbedResource["id"],
- params: EmbeddingParametersValues = {},
- secretKey: string,
- previewEmbeddingParams: EmbeddingParametersValues,
- expirationMinutes: number = DEFAULT_SIGNED_TOKEN_EXPIRATION_MINUTES,
-) {
- // Unjustified type cast. FIXME
- const normalizedResourceId = parseInt(rawResourceId as string, 10);
-
- const iat = Math.round(new Date().getTime() / 1000);
- const exp = iat + 60 * expirationMinutes;
-
- const unsignedToken: Record<string, any> = {
- resource: { [resourceType]: normalizedResourceId },
- params: params,
- iat,
- exp,
- };
- // include the `embedding_params` settings inline in the token for previews
- if (previewEmbeddingParams) {
- unsignedToken._embedding_params = previewEmbeddingParams;
- }
-
- const encoder = new TextEncoder();
- const key = encoder.encode(secretKey);
-
- return new CompactSign(encoder.encode(JSON.stringify(unsignedToken)))
- .setProtectedHeader({ alg: "HS256" })
- .sign(key);
-}
+import { getSignedToken } from "./auth/get-signed-token";
export async function getSignedPreviewUrlWithoutHash(
siteUrl: string,
diff --git a/frontend/src/metabase/embedding/lib/embedding-request-auth.ts b/frontend/src/metabase/embedding/lib/embedding-request-auth.ts
deleted file mode 100644
index b0f7313715f..00000000000
--- a/frontend/src/metabase/embedding/lib/embedding-request-auth.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-/* eslint-disable metabase/no-literal-metabase-strings -- request header names */
-import type {
- OnBeforeRequestHandler,
- OnBeforeRequestHandlerConfig,
- RequestClientInfo,
-} from "metabase/api/client";
-import { IFRAMED_IN_SELF } from "metabase/utils/iframe";
-
-/**
- * Factories for the embedding-only request-header plugin handlers. Each closes
- * over its value, so there's no shared mutable state — the embedding setup flow
- * installs the handlers it needs onto the plugin slots:
- *
- * - `setApiKeyHeader` / `setSessionTokenHeader` onto `setEmbeddingRequestAuthHeaders`
- * for static auth (an API key, or a session token that never refreshes — e.g.
- * MCP). A refreshing SSO session instead emits its header from
- * `getOrRefreshSessionHandler` via `sessionTokenHeaders`, so the refreshed
- * token applies to the request that triggered the refresh.
- * - `setRequestClientHeaders` onto its own slot
- * - `setEmbedPreviewHeader` onto its own slot (public + SDK flows only)
- *
- * In the normal app none are installed, so no embedding headers are emitted —
- * keeping these embedding concerns out of the generic api client.
- */
-export const setApiKeyHeader =
- (apiKey: string): OnBeforeRequestHandler =>
- async () => ({ headers: { "X-Api-Key": apiKey } });
-
-export const sessionTokenHeaders = (
- sessionToken: string,
-): Partial<OnBeforeRequestHandlerConfig> => ({
- headers: { "X-Metabase-Session": sessionToken },
-});
-
-export const setSessionTokenHeader =
- (sessionToken: string): OnBeforeRequestHandler =>
- async () =>
- sessionTokenHeaders(sessionToken);
-
-export const setRequestClientHeaders =
- (requestClient: RequestClientInfo): OnBeforeRequestHandler =>
- async () => {
- const headers: Record<string, string> = {};
-
- if (requestClient.name) {
- headers["X-Metabase-Client"] = requestClient.name;
- }
- if (requestClient.version) {
- headers["X-Metabase-Client-Version"] = requestClient.version;
- }
-
- return { headers };
- };
-
-/**
- * Tag requests coming from an embed preview (the page is iframed into itself).
- * Kept separate from `setRequestClientHeaders` because preview mode is
- * orthogonal to which client is embedding. Installed only by the public and SDK
- * embed flows — static and full-app deliberately don't tag preview requests
- * (see EMB-930 in `metabase/embedding/config`).
- */
-export const setEmbedPreviewHeader: OnBeforeRequestHandler = async () => {
- if (IFRAMED_IN_SELF) {
- return { headers: { "X-Metabase-Embedded-Preview": "true" } };
- }
-};
diff --git a/frontend/src/metabase/embedding/mcp/api.ts b/frontend/src/metabase/embedding/mcp/api.ts
index 99dd4546774..1b06392f018 100644
--- a/frontend/src/metabase/embedding/mcp/api.ts
+++ b/frontend/src/metabase/embedding/mcp/api.ts
@@ -1,5 +1,6 @@
/* eslint-disable metabase/no-literal-metabase-strings */
+import { EMBEDDING_SDK_CONFIG } from "metabase/embedding-sdk/config";
import type { SubmitMcpAppsFeedbackRequest } from "metabase-types/api";
type StoreDrillQueryRequest = {
@@ -35,7 +36,7 @@ export async function storeDrillQuery({
method: "POST",
headers: {
"Content-Type": "application/json",
- "X-Metabase-Client": "mcp-apps",
+ "X-Metabase-Client": EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader,
"X-Metabase-Session": sessionToken,
"Mcp-Session-Id": mcpSessionId,
},
@@ -61,7 +62,7 @@ export async function submitMcpFeedback({
method: "POST",
headers: {
"Content-Type": "application/json",
- "X-Metabase-Client": "mcp-apps",
+ "X-Metabase-Client": EMBEDDING_SDK_CONFIG.metabaseClientRequestHeader,
"X-Metabase-Session": sessionToken,
"Mcp-Session-Id": mcpSessionId,
},
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx
index cf97d69f017..05325631088 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/MainNavbarContainer/MainNavbarView.tsx
@@ -17,7 +17,11 @@ import { useSetting, useUserSetting } from "metabase/common/hooks";
import { useIsAtHomepageDashboard } from "metabase/common/hooks/use-is-at-homepage-dashboard";
import { useShowOtherUsersCollections } from "metabase/common/hooks/use-show-other-users-collections";
import { NavbarLibrarySection } from "metabase/nav/containers/MainNavbar/NavbarLibrarySection";
-import { PLUGIN_REMOTE_SYNC, PLUGIN_TENANTS } from "metabase/plugins";
+import {
+ PLUGIN_DATA_APPS,
+ PLUGIN_REMOTE_SYNC,
+ PLUGIN_TENANTS,
+} from "metabase/plugins";
import { useSelector } from "metabase/redux";
import {
getCanAccessOnboardingPage,
@@ -303,6 +307,10 @@ export function MainNavbarView({
</ErrorBoundary>
</SidebarSection>
+ {PLUGIN_DATA_APPS.isEnabled && (
+ <PLUGIN_DATA_APPS.MainNavbarSection onItemSelect={onItemSelect} />
+ )}
+
<SidebarSection>
<ErrorBoundary>
<BrowseNavSection
diff --git a/frontend/src/metabase/nav/containers/MainNavbar/SidebarItems/SidebarLink.tsx b/frontend/src/metabase/nav/containers/MainNavbar/SidebarItems/SidebarLink.tsx
index 2e108c4a584..0db9b70fb25 100644
--- a/frontend/src/metabase/nav/containers/MainNavbar/SidebarItems/SidebarLink.tsx
+++ b/frontend/src/metabase/nav/containers/MainNavbar/SidebarItems/SidebarLink.tsx
@@ -28,6 +28,8 @@ interface SidebarLinkProps {
left?: ReactNode;
right?: ReactNode;
onClick?: (event: MouseEvent) => void;
+ target?: string;
+ rel?: string;
}
type ContentProps = {
@@ -57,6 +59,8 @@ function SidebarLink({
left = null,
right = null,
onClick,
+ target,
+ rel,
...props
}: SidebarLinkProps) {
const renderIcon = useCallback(() => {
@@ -88,7 +92,13 @@ function SidebarLink({
const Content = useMemo(() => {
return url
? (props: ContentProps) => (
- <FullWidthLink {...props} to={url} onClick={onClick} />
+ <FullWidthLink
+ {...props}
+ to={url}
+ target={target}
+ rel={rel}
+ onClick={onClick}
+ />
)
: (props: ContentProps) => (
<FullWidthButton
@@ -97,7 +107,7 @@ function SidebarLink({
onClick={onClick}
/>
);
- }, [url, isSelected, onClick]);
+ }, [url, isSelected, onClick, target, rel]);
return (
<NodeRoot
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index a5b53abf8f8..5175dc732c6 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -72,6 +72,7 @@ export {
PLUGIN_DATABASE_REPLICATION,
PLUGIN_TABLE_EDITING,
} from "./oss/database";
+export { PLUGIN_DATA_APPS } from "./oss/data-apps";
export { PLUGIN_EMBEDDING, type SimpleDataPickerProps } from "./oss/embedding";
export { PLUGIN_EMBEDDING_IFRAME_SDK } from "./oss/embedding-iframe-sdk";
export {
@@ -203,6 +204,7 @@ import { reinitialize as reinitializeContentTranslation } from "./oss/content-tr
import { reinitialize as reinitializeContentVerification } from "./oss/content-verification";
import { reinitialize as reinitializeCore } from "./oss/core";
import { reinitialize as reinitializeCustomViz } from "./oss/custom-viz";
+import { reinitialize as reinitializeDataApps } from "./oss/data-apps";
import { reinitialize as reinitializeDatabase } from "./oss/database";
import { reinitialize as reinitializeDependencies } from "./oss/dependencies";
import { reinitialize as reinitializeEmbedding } from "./oss/embedding";
@@ -250,6 +252,7 @@ export function reinitialize() {
reinitializeContentVerification();
reinitializeCore();
reinitializeCustomViz();
+ reinitializeDataApps();
reinitializeDatabase();
reinitializeEmbedding();
reinitializeEmbeddingIframeSdk();
diff --git a/frontend/src/metabase/plugins/oss/data-apps.ts b/frontend/src/metabase/plugins/oss/data-apps.ts
new file mode 100644
index 00000000000..e2b6ae3dddd
--- /dev/null
+++ b/frontend/src/metabase/plugins/oss/data-apps.ts
@@ -0,0 +1,26 @@
+import type { ComponentType, ReactNode } from "react";
+
+import { PluginPlaceholder } from "metabase/plugins/components/PluginPlaceholder";
+
+export type DataAppsPlugin = {
+ isEnabled: boolean;
+ getRoutes: () => ReactNode | null;
+ ManageDataAppsPage: ComponentType;
+ MainNavbarSection: ComponentType<{ onItemSelect: () => void }>;
+};
+
+const getDefaultPluginDataApps = (): DataAppsPlugin => ({
+ isEnabled: false,
+ getRoutes: () => null,
+ ManageDataAppsPage: PluginPlaceholder,
+ MainNavbarSection: PluginPlaceholder,
+});
+
+export const PLUGIN_DATA_APPS: DataAppsPlugin = getDefaultPluginDataApps();
+
+/**
+ * @internal Do not call directly. Use the main reinitialize function from metabase/plugins instead.
+ */
+export function reinitialize() {
+ Object.assign(PLUGIN_DATA_APPS, getDefaultPluginDataApps());
+}
diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
index d08beb77c1f..4d56b664052 100644
--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.ts
@@ -33,7 +33,7 @@ import Question from "metabase-lib/v1/Question";
import type Metadata from "metabase-lib/v1/metadata/Metadata";
import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";
import { updateCardTemplateTagNames } from "metabase-lib/v1/queries/NativeQuery";
-import type { Card, SegmentId } from "metabase-types/api";
+import type { Card, SegmentId, UnsavedCard } from "metabase-types/api";
import type { EntityToken } from "metabase-types/api/entity";
import { isSavedCard } from "metabase-types/guards";
@@ -197,7 +197,7 @@ export async function resolveCards({
}: {
cardId?: string | number;
token?: EntityToken | null;
- deserializedCard?: Card;
+ deserializedCard?: UnsavedCard;
options: BlankQueryOptions;
dispatch: Dispatch;
getState: GetState;
diff --git a/frontend/src/metabase/query_builder/reducers.ts b/frontend/src/metabase/query_builder/reducers.ts
index 9deff2c4795..56060511022 100644
--- a/frontend/src/metabase/query_builder/reducers.ts
+++ b/frontend/src/metabase/query_builder/reducers.ts
@@ -640,79 +640,84 @@ type NestedCardPayloadAction = {
};
// the card that is actively being worked on
+//
+// NOTE: the `.addCase` / `.addMatcher` calls below are written as separate
+// statements rather than a single fluent chain on purpose. The chained form
+// accumulates generic instantiation depth across every link, and the RTK
+// Query `matchFulfilled` matchers at the end push that past TypeScript's
+// "excessively deep" limit (TS2589) whenever the global API type graph grows.
+// Splitting into per-statement calls keeps each call's inference shallow.
export const card = createReducer<Card | null>(null, (builder) => {
- builder
- .addCase(RESET_QB, () => null)
- .addCase(CLOSE_QB, () => null)
- .addCase<string, NestedCardPayloadAction>(INITIALIZE_QB, (state, action) =>
- action.payload ? action.payload.card : null,
- )
- .addCase<string, CardPayloadAction>(
- SOFT_RELOAD_CARD,
- (state, action) => action.payload,
- )
- .addCase<string, CardPayloadAction>(
- RELOAD_CARD,
- (state, action) => action.payload,
- )
- .addCase<string, NestedCardPayloadAction>(
- SET_CARD_AND_RUN,
- (state, action) => action.payload.card,
- )
- .addCase<string, CardPayloadAction>(
- API_CREATE_QUESTION,
- (state, action) => action.payload,
- )
- .addCase<string, CardPayloadAction>(
- API_UPDATE_QUESTION,
- (state, action) => action.payload,
- )
- .addCase<string, NestedCardPayloadAction>(
- CANCEL_QUESTION_CHANGES,
- (state, action) => action.payload.card,
- )
- .addCase<string, NestedCardPayloadAction>(
- UPDATE_QUESTION,
- (state, action) => action.payload.card,
- )
- .addCase<string, NestedCardPayloadAction>(
- QUERY_COMPLETED,
- (state, action) => {
- if (!state) {
- return state;
- }
- return {
- ...state,
- display: action.payload.card.display,
- result_metadata: action.payload.card.result_metadata,
- visualization_settings: action.payload.card.visualization_settings,
- };
- },
- );
-
- // a separate builder statement keeps the expression shallow enough for
- // TypeScript's instantiation-depth limit (TS2589)
- builder
- .addMatcher(createCardPublicLink.matchFulfilled, (state, action) => {
+ builder.addCase(RESET_QB, () => null);
+ builder.addCase(CLOSE_QB, () => null);
+ builder.addCase<string, NestedCardPayloadAction>(
+ INITIALIZE_QB,
+ (state, action) => (action.payload ? action.payload.card : null),
+ );
+ builder.addCase<string, CardPayloadAction>(
+ SOFT_RELOAD_CARD,
+ (state, action) => action.payload,
+ );
+ builder.addCase<string, CardPayloadAction>(
+ RELOAD_CARD,
+ (state, action) => action.payload,
+ );
+ builder.addCase<string, NestedCardPayloadAction>(
+ SET_CARD_AND_RUN,
+ (state, action) => action.payload.card,
+ );
+ builder.addCase<string, CardPayloadAction>(
+ API_CREATE_QUESTION,
+ (state, action) => action.payload,
+ );
+ builder.addCase<string, CardPayloadAction>(
+ API_UPDATE_QUESTION,
+ (state, action) => action.payload,
+ );
+ builder.addCase<string, NestedCardPayloadAction>(
+ CANCEL_QUESTION_CHANGES,
+ (state, action) => action.payload.card,
+ );
+ builder.addCase<string, NestedCardPayloadAction>(
+ UPDATE_QUESTION,
+ (state, action) => action.payload.card,
+ );
+ builder.addCase<string, NestedCardPayloadAction>(
+ QUERY_COMPLETED,
+ (state, action) => {
if (!state) {
return state;
}
return {
...state,
- public_uuid: action.payload.uuid,
+ display: action.payload.card.display,
+ result_metadata: action.payload.card.result_metadata,
+ visualization_settings: action.payload.card.visualization_settings,
};
- })
- .addMatcher(deleteCardPublicLink.matchFulfilled, (state) => {
- if (!state) {
- return state;
- }
+ },
+ );
+ builder.addMatcher(createCardPublicLink.matchFulfilled, (state, action) => {
+ if (!state) {
+ return state;
+ }
+ return {
+ ...state,
+ public_uuid: action.payload.uuid,
+ };
+ });
+ builder.addMatcher(deleteCardPublicLink.matchFulfilled, (state) => {
+ if (!state) {
+ return state;
+ }
- return {
- ...state,
- public_uuid: null,
- };
- })
- .addMatcher(updateCardEnableEmbedding.matchFulfilled, (state, action) => {
+ return {
+ ...state,
+ public_uuid: null,
+ };
+ });
+ builder.addMatcher(
+ updateCardEnableEmbedding.matchFulfilled,
+ (state, action) => {
if (!state) {
return state;
}
@@ -720,8 +725,11 @@ export const card = createReducer<Card | null>(null, (builder) => {
...state,
enable_embedding: action.payload.enable_embedding,
};
- })
- .addMatcher(updateCardEmbeddingParams.matchFulfilled, (state, action) => {
+ },
+ );
+ builder.addMatcher(
+ updateCardEmbeddingParams.matchFulfilled,
+ (state, action) => {
if (!state) {
return state;
}
@@ -731,5 +739,6 @@ export const card = createReducer<Card | null>(null, (builder) => {
embedding_params: action.payload.embedding_params,
initially_published_at: action.payload.initially_published_at,
};
- });
+ },
+ );
});
diff --git a/frontend/src/metabase/router/react-router.ts b/frontend/src/metabase/router/react-router.ts
index 29168bf5b46..192a167725e 100644
--- a/frontend/src/metabase/router/react-router.ts
+++ b/frontend/src/metabase/router/react-router.ts
@@ -16,6 +16,7 @@ export {
// a `<Route index>` element without recursing back into the shim's own builder.
Route as ReactRouterRoute,
Router,
+ browserHistory,
createMemoryHistory,
createRoutes,
formatPattern,
diff --git a/frontend/src/metabase/routes.tsx b/frontend/src/metabase/routes.tsx
index 39c73f5a330..1c7081f5034 100644
--- a/frontend/src/metabase/routes.tsx
+++ b/frontend/src/metabase/routes.tsx
@@ -44,6 +44,7 @@ import NewModelOptions from "metabase/models/containers/NewModelOptions";
import { getRoutes as getModelRoutes } from "metabase/models/routes";
import {
PLUGIN_COLLECTIONS,
+ PLUGIN_DATA_APPS,
PLUGIN_TABLE_EDITING,
PLUGIN_TENANTS,
} from "metabase/plugins";
@@ -124,6 +125,8 @@ export const getRoutes = (store: AppStore) => {
<Route element={<IsAuthenticated />}>
{getMetabotRoutes()}
+ {PLUGIN_DATA_APPS.isEnabled && PLUGIN_DATA_APPS.getRoutes()}
+
{/* The global all hands routes, things in here are for all the folks */}
<Route path="/" component={LandingPageRedirect} />
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/app.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/app.svg
new file mode 100644
index 00000000000..50cc7b1718c
--- /dev/null
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/app.svg
@@ -0,0 +1 @@
+<svg width="16" height="16" viewBox="0 0 16 16" fill="currentcolor" xmlns="http://www.w3.org/2000/svg"><path d="M12.999 2.25a2 2 0 0 1 1.999 2v7.497a2 2 0 0 1-1.999 2H3.003a2 2 0 0 1-2-2V4.25a2 2 0 0 1 2-2h9.996zM2.503 11.747a.5.5 0 0 0 .5.5h9.996a.5.5 0 0 0 .499-.5V6.692H2.503v5.055zm3.044-6.555h1.7V3.75h-1.7v1.442zm3.2 0h4.751V4.25a.5.5 0 0 0-.499-.5H8.747v1.442zM3.003 3.75a.5.5 0 0 0-.5.5v.942h1.544V3.75H3.003z" /></svg>
diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
index ee020668bb2..19fc22abc14 100644
--- a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts
@@ -30,6 +30,8 @@ import alert_confirm_component from "./alert_confirm.svg?component";
import alert_confirm_source from "./alert_confirm.svg?source";
import alert_filled_component from "./alert_filled.svg?component";
import alert_filled_source from "./alert_filled.svg?source";
+import app_component from "./app.svg?component";
+import app_source from "./app.svg?source";
import archive_component from "./archive.svg?component";
import archive_source from "./archive.svg?source";
import area_component from "./area.svg?component";
@@ -657,6 +659,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =
component: alert_confirm_component,
source: alert_confirm_source,
},
+ app: {
+ component: app_component,
+ source: app_source,
+ },
archive: {
component: archive_component,
source: archive_source,
diff --git a/frontend/src/metabase/urls/data-apps.ts b/frontend/src/metabase/urls/data-apps.ts
new file mode 100644
index 00000000000..6d496089818
--- /dev/null
+++ b/frontend/src/metabase/urls/data-apps.ts
@@ -0,0 +1,22 @@
+/**
+ * Canonical data-app URLs. `DATA_APP_URL_SEGMENT` is the single source of
+ * truth for the `apps` path segment; the page, admin, and iframe-embed URLs
+ * all derive from it, so renaming the route is a one-line change here. (REST
+ * API paths deliberately live as bare strings in the API layer so they stay
+ * greppable — see `metabase-enterprise/api/data-app.ts`.)
+ */
+export const DATA_APP_URL_SEGMENT = "apps";
+
+/** User-facing page route: `/apps/:name`. */
+export const DATA_APP_ROOT_URL = `/${DATA_APP_URL_SEGMENT}`;
+
+/**
+ * Prefix the BE serves the internal data-app iframe entrypoint at:
+ * `/embed/apps`. The host builds the iframe `src` and mirrors its URL from
+ * this; the SDK bundle's router reads it to auto-detect its basename.
+ */
+export const DATA_APP_EMBED_PREFIX = `/embed/${DATA_APP_URL_SEGMENT}`;
+
+export function dataApp(name: string) {
+ return `${DATA_APP_ROOT_URL}/${encodeURIComponent(name)}`;
+}
diff --git a/frontend/src/metabase/urls/index.ts b/frontend/src/metabase/urls/index.ts
index b2f04bcc573..44f3c63d020 100644
--- a/frontend/src/metabase/urls/index.ts
+++ b/frontend/src/metabase/urls/index.ts
@@ -6,6 +6,7 @@ export * from "./browse";
export * from "./cards";
export * from "./collections";
export * from "./dashboards";
+export * from "./data-apps";
export * from "./data-studio";
export * from "./dependencies";
export * from "./documents";
diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-blocked-apis.ts b/frontend/src/metabase/utils/scripts-sandbox/distortions-blocked-apis.ts
similarity index 93%
rename from enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-blocked-apis.ts
rename to frontend/src/metabase/utils/scripts-sandbox/distortions-blocked-apis.ts
index 95ca5c26854..b262473dc5a 100644
--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-blocked-apis.ts
+++ b/frontend/src/metabase/utils/scripts-sandbox/distortions-blocked-apis.ts
@@ -104,8 +104,8 @@ if (window.CookieStore) {
}
// Referrer — URL of the page that linked here, which can leak internal
-// admin URLs or embed-link query params. Unlike `location.href`, the plugin
-// has no other way to read this.
+// admin URLs or embed-link query params. Unlike `location.href`, the
+// sandboxed script has no other way to read this.
block(getter(Document.prototype, "referrer"), "Document.get referrer");
// Host URL — `document.URL` / `documentURI` / `baseURI` resolve through the
@@ -137,8 +137,8 @@ block(window.close, "window.close");
block(method(Window.prototype, "open"), "window.open");
block(method(Window.prototype, "close"), "window.close");
-// UI dialogs — block modal/blocking dialogs initiated by the plugin so it
-// can't freeze the host UI or phish via the browser chrome.
+// UI dialogs — block modal/blocking dialogs initiated by the sandboxed
+// script so it can't freeze the host UI or phish via the browser chrome.
block(window.alert, "window.alert");
block(window.confirm, "window.confirm");
block(window.prompt, "window.prompt");
@@ -208,9 +208,9 @@ block(window.PerformanceObserver, "PerformanceObserver");
// Coordinate-based caret APIs return a raw host Text/Element Node at the
// given (x, y) position, which bypasses the Element-level DOM decoy in
// distortions-dom-read.ts (those decoys gate on Element entry points;
-// caret-from-point hands the plugin a Node directly). The plugin could
-// systematically probe host coordinates to read text content. No legit
-// viz needs caret-from-point queries.
+// caret-from-point hands the sandboxed script a Node directly). The script
+// could systematically probe host coordinates to read text content. No
+// legit viz needs caret-from-point queries.
block(
method(Document.prototype, "caretRangeFromPoint"),
"Document.caretRangeFromPoint",
@@ -274,13 +274,13 @@ block(
* Location — `window.location` itself is `[LegacyUnforgeable]`,
* the Location attributes (`href`, `pathname`) are
* also `[LegacyUnforgeable]` so they live on every Location instance rather
- * than on `Location.prototype`, AND `near-membrane-dom` runs the plugin in a
- * sandbox iframe with its own `Location` instance — so neither
+ * than on `Location.prototype`, AND `near-membrane-dom` runs the sandboxed
+ * script in a sandbox iframe with its own `Location` instance — so neither
* `Location.prototype` distortions nor host instance descriptors match the
- * references the plugin sees. We rely on the iframe sandbox to keep Location
- * operations contained: the plugin can read/navigate its own iframe's
- * Location, but the host page stays put. The
- * `plugin location operations do not navigate the host` e2e test verifies
+ * references the script sees. We rely on the iframe sandbox to keep
+ * Location operations contained: the script can read/navigate its own
+ * iframe's Location, but the host page stays put. The
+ * `sandboxed location operations do not navigate the host` e2e test verifies
* that boundary.
*
* `OffscreenCanvas`. The main "escape hatch" is `transferControlToOffscreen()`
diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-dom-mutate.ts b/frontend/src/metabase/utils/scripts-sandbox/distortions-dom-mutate.ts
similarity index 57%
rename from enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-dom-mutate.ts
rename to frontend/src/metabase/utils/scripts-sandbox/distortions-dom-mutate.ts
index ad3bfb47e9b..f5f1f287a26 100644
--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-dom-mutate.ts
+++ b/frontend/src/metabase/utils/scripts-sandbox/distortions-dom-mutate.ts
@@ -1,7 +1,5 @@
import DOMPurify from "dompurify";
-import type { CustomVizPluginId } from "metabase-types/api";
-
export const CREATE_ELEMENT = Document.prototype.createElement;
export const CREATE_ELEMENT_NS = Document.prototype.createElementNS;
export const INSERT_ADJACENT_HTML = Element.prototype.insertAdjacentHTML;
@@ -46,45 +44,33 @@ if (shadowInnerHTMLDescriptor?.set) {
}
const PURIFY_CONFIG = {
- // `<area>` is a hidden anchor (href/target/download), and `<map>` only
- // exists to host `<area>` — both same threat class as `<a>`.
FORBID_TAGS: ["form", "a", "style", "frame", "map", "area"],
FORBID_ATTR: ["target", "formaction", "action"],
ALLOWED_URI_REGEXP:
/^(?:#|\/|https?:|data:image\/(?:png|jpeg|gif|svg\+xml|webp);)/i,
};
-// DOMPurify exposes the list of nodes/attributes it stripped from the most
-// recent sanitize call as `DOMPurify.removed`. Reading it immediately after
-// sanitize lets us log only when something dangerous was actually removed,
-// not on harmless normalization (case, whitespace, missing close tags). The
-// distortion runs in the host realm, so console output goes to the host.
-function logSanitizationIfStripped(
- pluginId: CustomVizPluginId,
- source: string,
-) {
+function logSanitizationIfStripped(errorPrefix: string, source: string) {
if (DOMPurify.removed.length > 0) {
console.error(
- `[plugin ${pluginId}] DOMPurify stripped content from ${source}:`,
+ `[${errorPrefix}] DOMPurify stripped content from ${source}:`,
DOMPurify.removed,
);
}
}
export function sanitizedSetterDistortion(
- pluginId: CustomVizPluginId,
+ errorPrefix: string,
name: string,
originalSet: (this: Element | ShadowRoot, value: string) => void,
) {
return function (this: Element | ShadowRoot, value: string) {
const sanitized = DOMPurify.sanitize(value, PURIFY_CONFIG);
- logSanitizationIfStripped(pluginId, name);
+ logSanitizationIfStripped(errorPrefix, name);
originalSet.call(this, sanitized);
};
}
-// Tags that must never be created — they can load or execute arbitrary
-// code, or are tags we don't want plugins rendering at all.
const BLOCKED_TAGS = new Set([
"script",
"iframe",
@@ -96,46 +82,34 @@ const BLOCKED_TAGS = new Set([
"frame",
"form",
"a",
- // `<area>` is a hidden anchor (href/target/download navigation) and
- // `<map>` only exists as its container — same threat class as `<a>`.
"map",
"area",
- // CSS-based exfiltration (`@font-face { src: url(...) }`,
- // `background-image: url(...)`) until CSP font-src/img-src is tightened
- // (GDGT-2373). DOMPurify already strips `<style>` from sanitized HTML, but
- // the createElement path skips DOMPurify entirely.
"style",
- // Media elements load URLs via `src`/`srcset`
"video",
"audio",
"source",
"track",
- // `<input type="image">` fires a GET to `src` on render. `<input type=image src="…">` is a vector for exfiltration.
"input",
- // SVG external-resource / mutation-XSS vectors
"use",
"image",
"feimage",
"foreignobject",
]);
-export function createElementDistortion(pluginId: CustomVizPluginId) {
+export function createElementDistortion(errorPrefix: string) {
return function createElement(
this: Document,
tag: string,
options?: ElementCreationOptions,
) {
if (BLOCKED_TAGS.has(tag.toLowerCase())) {
- throw new Error(`[plugin ${pluginId}] blocked createElement: ${tag}`);
+ throw new Error(`[${errorPrefix}] blocked createElement: ${tag}`);
}
return CREATE_ELEMENT.call(this, tag, options);
};
}
-// Same blocklist applied to namespaced creates (SVG/MathML). React reaches
-// for createElementNS to build SVG trees — common for visualization plugins —
-// but the dangerous-tag filter (script, iframe, etc.) still applies.
-export function createElementNSDistortion(pluginId: CustomVizPluginId) {
+export function createElementNSDistortion(errorPrefix: string) {
return function createElementNS(
this: Document,
namespaceURI: string | null,
@@ -147,7 +121,7 @@ export function createElementNSDistortion(pluginId: CustomVizPluginId) {
: qualifiedName;
if (BLOCKED_TAGS.has(localName.toLowerCase())) {
throw new Error(
- `[plugin ${pluginId}] blocked createElementNS: ${qualifiedName}`,
+ `[${errorPrefix}] blocked createElementNS: ${qualifiedName}`,
);
}
return CREATE_ELEMENT_NS.call(
@@ -160,16 +134,10 @@ export function createElementNSDistortion(pluginId: CustomVizPluginId) {
};
}
-// Inline `on*` handler attributes execute as JavaScript when the element is
-// wired up — equivalent to `eval` on a string. Block them at the setAttribute
-// boundary; legitimate event listeners use addEventListener instead.
function isInlineEventHandlerName(name: unknown): boolean {
return typeof name === "string" && /^on/i.test(name);
}
-// URL-valued attributes — setting `javascript:<code>` here makes the browser
-// run <code> in the host realm (outside the membrane) when the element is
-// followed/submitted/loaded.
const URL_VALUED_ATTRS = new Set([
"href",
"src",
@@ -186,54 +154,56 @@ function isUrlValuedAttr(name: unknown): boolean {
return typeof name === "string" && URL_VALUED_ATTRS.has(name.toLowerCase());
}
-// Browsers tolerate leading whitespace before the protocol (e.g.
-// " javascript:..." still navigates), so allow any leading whitespace
-// before testing the prefix.
function isJavascriptUrl(value: unknown): boolean {
return typeof value === "string" && /^\s*javascript:/i.test(value);
}
function assertSafeAttrAssignment(
- pluginId: CustomVizPluginId,
+ errorPrefix: string,
apiName: string,
name: unknown,
value: unknown,
): void {
if (isInlineEventHandlerName(name)) {
throw new Error(
- `[plugin ${pluginId}] blocked ${apiName} for inline event handler: ${String(name)}`,
+ `[${errorPrefix}] blocked ${apiName} for inline event handler: ${String(name)}`,
);
}
if (isUrlValuedAttr(name) && isJavascriptUrl(value)) {
throw new Error(
- `[plugin ${pluginId}] blocked ${apiName} with javascript: URL: ${String(name)}`,
+ `[${errorPrefix}] blocked ${apiName} with javascript: URL: ${String(name)}`,
);
}
}
-export function setAttributeDistortion(pluginId: CustomVizPluginId) {
+export function setAttributeDistortion(errorPrefix: string) {
return function setAttribute(this: Element, name: string, value: string) {
- assertSafeAttrAssignment(pluginId, "setAttribute", name, value);
+ assertSafeAttrAssignment(errorPrefix, "setAttribute", name, value);
return SET_ATTRIBUTE.call(this, name, value);
};
}
-export function setAttributeNSDistortion(pluginId: CustomVizPluginId) {
+export function setAttributeNSDistortion(errorPrefix: string) {
return function setAttributeNS(
this: Element,
namespace: string | null,
qualifiedName: string,
value: string,
) {
- assertSafeAttrAssignment(pluginId, "setAttributeNS", qualifiedName, value);
+ assertSafeAttrAssignment(
+ errorPrefix,
+ "setAttributeNS",
+ qualifiedName,
+ value,
+ );
return SET_ATTRIBUTE_NS.call(this, namespace, qualifiedName, value);
};
}
-export function setAttributeNodeDistortion(pluginId: CustomVizPluginId) {
+export function setAttributeNodeDistortion(errorPrefix: string) {
return function setAttributeNode(this: Element, attr: Attr) {
assertSafeAttrAssignment(
- pluginId,
+ errorPrefix,
"setAttributeNode",
attr.name,
attr.value,
@@ -242,10 +212,10 @@ export function setAttributeNodeDistortion(pluginId: CustomVizPluginId) {
};
}
-export function setAttributeNodeNSDistortion(pluginId: CustomVizPluginId) {
+export function setAttributeNodeNSDistortion(errorPrefix: string) {
return function setAttributeNodeNS(this: Element, attr: Attr) {
assertSafeAttrAssignment(
- pluginId,
+ errorPrefix,
"setAttributeNodeNS",
attr.name,
attr.value,
@@ -254,35 +224,45 @@ export function setAttributeNodeNSDistortion(pluginId: CustomVizPluginId) {
};
}
-export function setNamedItemDistortion(pluginId: CustomVizPluginId) {
+export function setNamedItemDistortion(errorPrefix: string) {
return function setNamedItem(this: NamedNodeMap, attr: Attr) {
- assertSafeAttrAssignment(pluginId, "setNamedItem", attr.name, attr.value);
+ assertSafeAttrAssignment(
+ errorPrefix,
+ "setNamedItem",
+ attr.name,
+ attr.value,
+ );
return SET_NAMED_ITEM.call(this, attr);
};
}
-export function setNamedItemNSDistortion(pluginId: CustomVizPluginId) {
+export function setNamedItemNSDistortion(errorPrefix: string) {
return function setNamedItemNS(this: NamedNodeMap, attr: Attr) {
- assertSafeAttrAssignment(pluginId, "setNamedItemNS", attr.name, attr.value);
+ assertSafeAttrAssignment(
+ errorPrefix,
+ "setNamedItemNS",
+ attr.name,
+ attr.value,
+ );
return SET_NAMED_ITEM_NS.call(this, attr);
};
}
-export function attrValueSetterDistortion(pluginId: CustomVizPluginId) {
+export function attrValueSetterDistortion(errorPrefix: string) {
return function (this: Attr, val: string) {
- assertSafeAttrAssignment(pluginId, "Attr.set value", this.name, val);
+ assertSafeAttrAssignment(errorPrefix, "Attr.set value", this.name, val);
SET_ATTR_VALUE_DESCRIPTOR?.call(this, val);
};
}
-export function insertAdjacentHTMLDistortion(pluginId: CustomVizPluginId) {
+export function insertAdjacentHTMLDistortion(errorPrefix: string) {
return function insertAdjacentHTML(
this: Element,
position: InsertPosition,
html: string,
) {
const sanitized = DOMPurify.sanitize(html, PURIFY_CONFIG);
- logSanitizationIfStripped(pluginId, "insertAdjacentHTML");
+ logSanitizationIfStripped(errorPrefix, "insertAdjacentHTML");
INSERT_ADJACENT_HTML.call(this, position, sanitized);
};
}
diff --git a/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-event.ts b/frontend/src/metabase/utils/scripts-sandbox/distortions-event.ts
similarity index 53%
rename from enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-event.ts
rename to frontend/src/metabase/utils/scripts-sandbox/distortions-event.ts
index b91f48b2b57..133d9cf9b03 100644
--- a/enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-event.ts
+++ b/frontend/src/metabase/utils/scripts-sandbox/distortions-event.ts
@@ -1,12 +1,10 @@
-import type { CustomVizPluginId } from "metabase-types/api";
-
export const ADD_EVENT_LISTENER = EventTarget.prototype.addEventListener;
// Event types that, when listened for on `document` or `window`, give the
-// plugin a global keylogger / clipboard sniffer. There's no legitimate
-// reason for a viz plugin to listen for typed text or clipboard activity
-// outside its own subtree — listening on plugin-owned elements still
-// works, and that's where the plugin's own UI events live.
+// sandboxed script a global keylogger / clipboard sniffer. There's no
+// legitimate reason for it to listen for typed text or clipboard activity
+// outside its own subtree — listening on script-owned elements still
+// works, and that's where the script's own UI events live.
const GLOBAL_BLOCKED_EVENT_TYPES = new Set([
"keydown",
"keyup",
@@ -23,18 +21,13 @@ const GLOBAL_BLOCKED_EVENT_TYPES = new Set([
"compositionupdate",
"compositionend",
"storage",
- // `selectionchange` is intentionally NOT blocked: legitimate viz code
- // (e.g. calendar heatmap) listens for it. The residual risk — pairing
- // it with `window.getSelection()` to track host text selection — is
- // gated on the user actively selecting text and is the same narrow
- // residual we accepted in `distortions-dom-read.ts`.
]);
function isGlobalEventTarget(target: unknown): boolean {
return target instanceof Document || target instanceof Window;
}
-export function addEventListenerDistortion(pluginId: CustomVizPluginId) {
+export function addEventListenerDistortion(errorPrefix: string) {
return function addEventListener(
this: EventTarget,
type: string,
@@ -46,7 +39,7 @@ export function addEventListenerDistortion(pluginId: CustomVizPluginId) {
GLOBAL_BLOCKED_EVENT_TYPES.has(String(type).toLowerCase())
) {
throw new Error(
- `[plugin ${pluginId}] blocked addEventListener for global event type: ${type}`,
+ `[${errorPrefix}] blocked addEventListener for global event type: ${type}`,
);
}
return ADD_EVENT_LISTENER.call(this, type, listener, options);
diff --git a/frontend/src/metabase/utils/scripts-sandbox/distortions.ts b/frontend/src/metabase/utils/scripts-sandbox/distortions.ts
new file mode 100644
index 00000000000..32c2f9217bc
--- /dev/null
+++ b/frontend/src/metabase/utils/scripts-sandbox/distortions.ts
@@ -0,0 +1,161 @@
+import { BLOCKED_NATIVE_REFS } from "./distortions-blocked-apis";
+import {
+ CREATE_ELEMENT,
+ CREATE_ELEMENT_NS,
+ INSERT_ADJACENT_HTML,
+ SANITIZED_SETTERS,
+ SET_ATTRIBUTE,
+ SET_ATTRIBUTE_NODE,
+ SET_ATTRIBUTE_NODE_NS,
+ SET_ATTRIBUTE_NS,
+ SET_ATTR_VALUE_DESCRIPTOR,
+ SET_NAMED_ITEM,
+ SET_NAMED_ITEM_NS,
+ attrValueSetterDistortion,
+ createElementDistortion,
+ createElementNSDistortion,
+ insertAdjacentHTMLDistortion,
+ sanitizedSetterDistortion,
+ setAttributeDistortion,
+ setAttributeNSDistortion,
+ setAttributeNodeDistortion,
+ setAttributeNodeNSDistortion,
+ setNamedItemDistortion,
+ setNamedItemNSDistortion,
+} from "./distortions-dom-mutate";
+import {
+ ADD_EVENT_LISTENER,
+ addEventListenerDistortion,
+} from "./distortions-event";
+
+/**
+ * Build the common subset of a Near Membrane `distortionCallback` shared by
+ * every Metabase sandbox.
+ *
+ * This callback enforces:
+ * - blocked network-egress APIs (fetch, XHR, WebSocket, …) — see
+ * `distortions-blocked-apis`;
+ * - sanitized innerHTML / outerHTML / insertAdjacentHTML mutations via
+ * DOMPurify;
+ * - blocked element creation for dangerous tags (script, iframe, link,
+ * form, …);
+ * - blocked inline-event-handler attributes (`onclick="…"`) and
+ * `javascript:` URLs at the setAttribute boundary;
+ * - blocked `addEventListener` on `document`/`window` for typing /
+ * clipboard / storage event types.
+ *
+ * It does NOT handle DOM-node scoping (decoy nodes outside a script's
+ * subtree, scope-aware `document.activeElement`). Scoping is consumer-
+ * specific — custom-viz needs it for per-card isolation; data-app does not
+ * — so each module composes that on top of this callback if it wants it.
+ *
+ * `errorPrefix` is the bracketed label that appears in thrown messages,
+ * e.g. `data-app 5` produces `[data-app 5] blocked createElement: script`.
+ */
+export function makeSandboxDistortionCallback(
+ errorPrefix: string,
+ onBlocked?: (message: string) => void,
+) {
+ // Every distortion throws `[errorPrefix] blocked …` when the sandboxed script
+ // hits a blocked operation. That throw frequently reaches the developer only
+ // as an opaque cross-realm `#<Object>` (e.g. an unhandled async rejection), so
+ // when a consumer provides `onBlocked` we wrap the distorted function to log
+ // the real message synchronously at the block point — before re-throwing —
+ // where the stack still points at the offending sandbox code.
+ const reportThrows = (distorted: object): object => {
+ if (!onBlocked || typeof distorted !== "function") {
+ return distorted;
+ }
+
+ const fn = distorted;
+
+ return function reportingDistortion(this: unknown, ...args: unknown[]) {
+ try {
+ return fn.apply(this, args);
+ } catch (error) {
+ if (error instanceof Error) {
+ onBlocked(error.message);
+ }
+ throw error;
+ }
+ };
+ };
+
+ const resolveDistortion = (value: object): object => {
+ if (SANITIZED_SETTERS.has(value)) {
+ const info = SANITIZED_SETTERS.get(value);
+ if (info) {
+ return sanitizedSetterDistortion(
+ errorPrefix,
+ info.name,
+ info.originalSet,
+ );
+ }
+ }
+
+ if (value === ADD_EVENT_LISTENER) {
+ return addEventListenerDistortion(errorPrefix);
+ }
+
+ if (value === CREATE_ELEMENT) {
+ return createElementDistortion(errorPrefix);
+ }
+
+ if (value === CREATE_ELEMENT_NS) {
+ return createElementNSDistortion(errorPrefix);
+ }
+
+ if (value === INSERT_ADJACENT_HTML) {
+ return insertAdjacentHTMLDistortion(errorPrefix);
+ }
+
+ if (value === SET_ATTRIBUTE) {
+ return setAttributeDistortion(errorPrefix);
+ }
+
+ if (value === SET_ATTRIBUTE_NS) {
+ return setAttributeNSDistortion(errorPrefix);
+ }
+
+ if (value === SET_ATTRIBUTE_NODE) {
+ return setAttributeNodeDistortion(errorPrefix);
+ }
+
+ if (value === SET_ATTRIBUTE_NODE_NS) {
+ return setAttributeNodeNSDistortion(errorPrefix);
+ }
+
+ if (value === SET_NAMED_ITEM) {
+ return setNamedItemDistortion(errorPrefix);
+ }
+
+ if (value === SET_NAMED_ITEM_NS) {
+ return setNamedItemNSDistortion(errorPrefix);
+ }
+
+ if (value === SET_ATTR_VALUE_DESCRIPTOR) {
+ return attrValueSetterDistortion(errorPrefix);
+ }
+
+ const blockedLabel = BLOCKED_NATIVE_REFS.get(value);
+ if (blockedLabel) {
+ return function blocked() {
+ throw new Error(`[${errorPrefix}] blocked API call: ${blockedLabel}`);
+ };
+ }
+
+ return value;
+ };
+
+ return function distortionCallback(value: object): object {
+ if (typeof value !== "function") {
+ return value;
+ }
+
+ const distorted = resolveDistortion(value);
+
+ // Only wrap when we actually distorted `value`; pass-through values are
+ // returned untouched so we never log on a non-blocked call.
+ return distorted === value ? value : reportThrows(distorted);
+ };
+}
diff --git a/frontend/src/metabase/utils/scripts-sandbox/index.ts b/frontend/src/metabase/utils/scripts-sandbox/index.ts
new file mode 100644
index 00000000000..6ab881019b2
--- /dev/null
+++ b/frontend/src/metabase/utils/scripts-sandbox/index.ts
@@ -0,0 +1,2 @@
+export { BLOCKED_NATIVE_REFS } from "./distortions-blocked-apis";
+export { makeSandboxDistortionCallback } from "./distortions";
diff --git a/frontend/src/metabase/utils/version.ts b/frontend/src/metabase/utils/version.ts
index ba1a1577ce3..5e7a078f305 100644
--- a/frontend/src/metabase/utils/version.ts
+++ b/frontend/src/metabase/utils/version.ts
@@ -42,6 +42,14 @@ export function getMajorVersion(version: string): number | null {
return versionToNumericComponents(version)?.[1] ?? null;
}
+/**
+ * Local-dev (`vLOCAL_DEV`) and `-SNAPSHOT` builds are not published releases, so
+ * they have no corresponding `release-x.NN.x` branch — callers fall back to
+ * `master` for these.
+ */
+export const isLocalOrSnapshotVersion = (version: string) =>
+ version === "vLOCAL_DEV" || version.endsWith("-SNAPSHOT");
+
/**
* this should correctly compare all version formats Metabase uses, e.g.
* 0.0.9, 0.0.10-snapshot, 0.0.10-alpha1, 0.0.10-rc1, 0.0.10-rc2, 0.0.10-rc10
diff --git a/package.json b/package.json
index ca15ce7ff17..ec0432dcb0a 100644
--- a/package.json
+++ b/package.json
@@ -286,6 +286,7 @@
"@types/tether": "^1.4.6",
"@types/underscore": "^1.13.0",
"@types/use-sync-external-store": "^1.5.0",
+ "@vitejs/plugin-react": "^6.0.2",
"ajv": "^8.5.0",
"babel-loader": "^9.1.2",
"babel-plugin-ttag": "^1.8.16",
@@ -411,6 +412,9 @@
"typedoc-plugin-redirect": "^1.2.0",
"typescript-eslint": "8.60.0",
"typescript-plugin-css-modules": "^5.1.0",
+ "vite": "^8.0.16",
+ "vite-plugin-css-injected-by-js": "^3.5.2",
+ "vite-plugin-svgr": "^5.2.0",
"web-streams-polyfill": "^4.1.0",
"webpack": "5.105.0",
"webpack-bundle-analyzer": "^4.10.1",
@@ -464,9 +468,9 @@
"scripts": {
"mage": "./bin/mage",
"build": "bun run build:cljs && bun run build:js",
- "build-embedding-sdk-package": "bun run embedding-sdk:clean:dist && bun install && bun run build-release:cljs && bun run embedding-sdk:generate-package && bun run embedding-sdk:generate-package-support-files && bun run build-release:embedding-sdk-package && bun run build-embedding-sdk-cli && bun run embedding-sdk:dts:generate",
- "build-embedding-sdk-cli": "rspack --config rspack.embedding-sdk-cli.config.js",
- "build-embedding-sdk-cli:watch": "bun run build-embedding-sdk-cli --watch",
+ "build-embedding-sdk-package": "bun run embedding-sdk:clean:dist && bun install && bun run build-release:cljs && bun run embedding-sdk:generate-package && bun run embedding-sdk:generate-package-support-files && bun run build-release:embedding-sdk-package && bun run build-embedding-sdk-node && bun run embedding-sdk:dts:generate",
+ "build-embedding-sdk-node": "rspack --config rspack.embedding-sdk-node.config.js",
+ "build-embedding-sdk-node:watch": "bun run build-embedding-sdk-node --watch",
"build-hot": "rm -f target/cljs_dev/cljs.core.js && bun run build:cljs && bun run concurrently -n 'js' -c 'green,cyan' 'bun run build-hot:js'",
"build-hot-be": "rm -f target/cljs_dev/cljs.core.js && bun run concurrently -n 'cljs,js' -c 'yellow,green,cyan' 'bun run build-hot:cljs' 'ENABLE_CLJS_HOT_RELOAD=true bun run build-hot:js-wait'",
"build-hot:cljs": "bun install && shadow-cljs watch app",
diff --git a/resources/frontend_client/data_app_template.html b/resources/frontend_client/data_app_template.html
new file mode 100644
index 00000000000..1c0a30addf3
--- /dev/null
+++ b/resources/frontend_client/data_app_template.html
@@ -0,0 +1,52 @@
+<!DOCTYPE html>
+<html lang="{{{language}}}" translate="no">
+ <head>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <meta name="robots" content="noindex" />
+ <meta name="base-href" content="{{{baseHref}}}" />
+ <meta name="uri" content="{{{uri}}}" />
+
+ {{{embedCode}}}
+
+ <title>{{{applicationName}}}</title>
+
+ <base href="{{{baseHref}}}" />
+
+ <script type="application/json" id="_metabaseBootstrap">
+ {{{bootstrapJSON}}}
+ </script>
+
+ <script type="application/json" id="_metabaseUserLocalization">
+ {{{userLocalizationJSON}}}
+ </script>
+
+ <script type="application/json" id="_metabaseSiteLocalization">
+ {{{siteLocalizationJSON}}}
+ </script>
+
+ <script type="application/json" id="_metabaseUserColorScheme">
+ {{{userColorScheme}}}
+ </script>
+
+ <script type="application/json" id="_metabaseNonce">
+ {{{nonceJSON}}}
+ </script>
+
+ <!-- If you modify this script, make sure you update the whitelisted Content-Security-Policy hash in metabase.server.middleware.security -->
+ <script type="text/javascript">{{{bootstrapJS}}}</script>
+ <script type="text/javascript">{{{assetOnErrorJS}}}</script>
+ </head>
+
+ <!--
+ No `mb-wrapper` class on body: SDK components add it to their own
+ wrappers via `PublicComponentStylesWrapper`. Setting it on the body
+ would put the entire iframe (including the bundle's own chrome) under
+ Metabase's `.mb-wrapper`-scoped resets, which is what we're trying to
+ avoid.
+ -->
+ <body dir="ltr">
+ <div id="root"></div>
+ </body>
+</html>
diff --git a/resources/instance_analytics/collections/main/usage_analytics/embedding_usage/most_viewed_authenticated_embeds.yaml b/resources/instance_analytics/collections/main/usage_analytics/embedding_usage/most_viewed_authenticated_embeds.yaml
index 618b1f426aa..82a5af0af3c 100644
--- a/resources/instance_analytics/collections/main/usage_analytics/embedding_usage/most_viewed_authenticated_embeds.yaml
+++ b/resources/instance_analytics/collections/main/usage_analytics/embedding_usage/most_viewed_authenticated_embeds.yaml
@@ -217,10 +217,10 @@ result_metadata:
lib/desired-column-alias: embedding_client
lib/from-model?: true
lib/internal-remap:
- human-readable-values: [Modular embedding SDK, Modular embedding SDK (Preview), Modular embedding, Modular embedding (Preview), Public sharing, Static embedding, Static embedding (Preview), Full app embedding, Full app embedding (Preview), Embedding (Unknown)]
+ human-readable-values: [Modular embedding SDK, Modular embedding SDK (Preview), Modular embedding, Modular embedding (Preview), Public sharing, Static embedding, Static embedding (Preview), Full app embedding, Full app embedding (Preview), Embedding (Unknown), Data app, Data app (Preview)]
id: 291
name: Embedding Client
- values: [embedding-sdk-react, embedding-sdk-react-preview, embedding-simple, embedding-simple-preview, embedding-public, embedding-iframe-static, embedding-iframe-static-preview, embedding-iframe-full-app, embedding-iframe-full-app-preview, embedding-iframe]
+ values: [embedding-sdk-react, embedding-sdk-react-preview, embedding-simple, embedding-simple-preview, embedding-public, embedding-iframe-static, embedding-iframe-static-preview, embedding-iframe-full-app, embedding-iframe-full-app-preview, embedding-iframe, data-app, data-app-preview]
lib/type: metadata.column.remapping/internal
lib/original-display-name: Embedding Client
lib/original-name: embedding_client
diff --git a/resources/instance_analytics/collections/main/usage_analytics/embedding_usage/most_viewed_guest_embeds.yaml b/resources/instance_analytics/collections/main/usage_analytics/embedding_usage/most_viewed_guest_embeds.yaml
index e52bf2c228b..fedd3197082 100644
--- a/resources/instance_analytics/collections/main/usage_analytics/embedding_usage/most_viewed_guest_embeds.yaml
+++ b/resources/instance_analytics/collections/main/usage_analytics/embedding_usage/most_viewed_guest_embeds.yaml
@@ -215,10 +215,10 @@ result_metadata:
lib/desired-column-alias: embedding_client
lib/from-model?: true
lib/internal-remap:
- human-readable-values: [Modular embedding SDK, Modular embedding SDK (Preview), Modular embedding, Modular embedding (Preview), Public sharing, Static embedding, Static embedding (Preview), Full app embedding, Full app embedding (Preview), Embedding (Unknown)]
+ human-readable-values: [Modular embedding SDK, Modular embedding SDK (Preview), Modular embedding, Modular embedding (Preview), Public sharing, Static embedding, Static embedding (Preview), Full app embedding, Full app embedding (Preview), Embedding (Unknown), Data app, Data app (Preview)]
id: 291
name: Embedding Client
- values: [embedding-sdk-react, embedding-sdk-react-preview, embedding-simple, embedding-simple-preview, embedding-public, embedding-iframe-static, embedding-iframe-static-preview, embedding-iframe-full-app, embedding-iframe-full-app-preview, embedding-iframe]
+ values: [embedding-sdk-react, embedding-sdk-react-preview, embedding-simple, embedding-simple-preview, embedding-public, embedding-iframe-static, embedding-iframe-static-preview, embedding-iframe-full-app, embedding-iframe-full-app-preview, embedding-iframe, data-app, data-app-preview]
lib/type: metadata.column.remapping/internal
lib/original-display-name: Embedding Client
lib/original-name: embedding_client
diff --git a/resources/instance_analytics/collections/main/usage_analytics/embedding_usage/views_by_embedding_client.yaml b/resources/instance_analytics/collections/main/usage_analytics/embedding_usage/views_by_embedding_client.yaml
index 2b97b57fc6f..fc0bd3fbbd6 100644
--- a/resources/instance_analytics/collections/main/usage_analytics/embedding_usage/views_by_embedding_client.yaml
+++ b/resources/instance_analytics/collections/main/usage_analytics/embedding_usage/views_by_embedding_client.yaml
@@ -126,10 +126,10 @@ result_metadata:
lib/desired-column-alias: embedding_client
lib/from-model?: true
lib/internal-remap:
- human-readable-values: [Modular embedding SDK, Modular embedding SDK (Preview), Modular embedding, Modular embedding (Preview), Public sharing, Static embedding, Static embedding (Preview), Full app embedding, Full app embedding (Preview), Embedding (Unknown)]
+ human-readable-values: [Modular embedding SDK, Modular embedding SDK (Preview), Modular embedding, Modular embedding (Preview), Public sharing, Static embedding, Static embedding (Preview), Full app embedding, Full app embedding (Preview), Embedding (Unknown), Data app, Data app (Preview)]
id: 291
name: Embedding Client
- values: [embedding-sdk-react, embedding-sdk-react-preview, embedding-simple, embedding-simple-preview, embedding-public, embedding-iframe-static, embedding-iframe-static-preview, embedding-iframe-full-app, embedding-iframe-full-app-preview, embedding-iframe]
+ values: [embedding-sdk-react, embedding-sdk-react-preview, embedding-simple, embedding-simple-preview, embedding-public, embedding-iframe-static, embedding-iframe-static-preview, embedding-iframe-full-app, embedding-iframe-full-app-preview, embedding-iframe, data-app, data-app-preview]
lib/type: metadata.column.remapping/internal
lib/original-display-name: Embedding Client
lib/original-name: embedding_client
diff --git a/resources/instance_analytics/collections/main/usage_analytics/query_log.yaml b/resources/instance_analytics/collections/main/usage_analytics/query_log.yaml
index 4d13ab219a5..683ba1cff69 100644
--- a/resources/instance_analytics/collections/main/usage_analytics/query_log.yaml
+++ b/resources/instance_analytics/collections/main/usage_analytics/query_log.yaml
@@ -75,6 +75,9 @@ dataset_query:
- - field
- {base-type: type/Text, effective-type: type/Text}
- [Internal Metabase Database, public, v_query_log, embedding_client]
+ - - field
+ - {base-type: type/Text, effective-type: type/Text}
+ - [Internal Metabase Database, public, v_query_log, embedding_client_identifier]
- - field
- {base-type: type/Boolean, effective-type: type/Boolean}
- [Internal Metabase Database, public, v_query_log, is_preview]
@@ -422,6 +425,21 @@ result_metadata:
semantic_type: type/Category
settings: null
visibility_type: normal
+- base_type: type/Text
+ coercion_strategy: null
+ description: null
+ display_name: Embedding Client Identifier
+ effective_type: type/Text
+ field_ref:
+ - field
+ - [Internal Metabase Database, public, v_query_log, embedding_client_identifier]
+ - null
+ fk_target_field_id: null
+ id: [Internal Metabase Database, public, v_query_log, embedding_client_identifier]
+ name: embedding_client_identifier
+ semantic_type: type/Category
+ settings: null
+ visibility_type: normal
- base_type: type/Boolean
coercion_strategy: null
description: null
@@ -656,6 +674,7 @@ visualization_settings:
- {enabled: true, name: action_qualified_id}
- {enabled: true, name: query}
- {enabled: true, name: embedding_client}
+ - {enabled: true, name: embedding_client_identifier}
- {enabled: true, name: is_preview}
- {enabled: true, name: embedding_sdk_version}
- {enabled: true, name: metabase_version}
diff --git a/resources/instance_analytics/collections/main/usage_analytics/view_log.yaml b/resources/instance_analytics/collections/main/usage_analytics/view_log.yaml
index 46734a196b2..29523f2380e 100644
--- a/resources/instance_analytics/collections/main/usage_analytics/view_log.yaml
+++ b/resources/instance_analytics/collections/main/usage_analytics/view_log.yaml
@@ -36,6 +36,9 @@ dataset_query:
- - field
- {base-type: type/Text, effective-type: type/Text}
- [Internal Metabase Database, public, v_view_log, embedding_client]
+ - - field
+ - {base-type: type/Text, effective-type: type/Text}
+ - [Internal Metabase Database, public, v_view_log, embedding_client_identifier]
- - field
- {base-type: type/Text, effective-type: type/Text}
- [Internal Metabase Database, public, v_view_log, auth_method]
@@ -185,6 +188,21 @@ result_metadata:
semantic_type: type/Category
settings: null
visibility_type: normal
+- base_type: type/Text
+ coercion_strategy: null
+ description: null
+ display_name: Embedding Client Identifier
+ effective_type: type/Text
+ field_ref:
+ - field
+ - [Internal Metabase Database, public, v_view_log, embedding_client_identifier]
+ - null
+ fk_target_field_id: null
+ id: [Internal Metabase Database, public, v_view_log, embedding_client_identifier]
+ name: embedding_client_identifier
+ semantic_type: type/Category
+ settings: null
+ visibility_type: normal
- base_type: type/Text
coercion_strategy: null
description: null
diff --git a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_query_log/fields/embedding_client___fieldvalues.yaml b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_query_log/fields/embedding_client___fieldvalues.yaml
index d2fa851bb5b..baed24a1252 100644
--- a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_query_log/fields/embedding_client___fieldvalues.yaml
+++ b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_query_log/fields/embedding_client___fieldvalues.yaml
@@ -1,8 +1,8 @@
created_at: '2026-04-22T14:46:17.273549Z'
-human_readable_values: [Modular embedding SDK, Modular embedding SDK (Preview), Modular embedding, Modular embedding (Preview), Public sharing, Static embedding, Static embedding (Preview), Full app embedding, Full app embedding (Preview), Embedding (Unknown)]
+human_readable_values: [Modular embedding SDK, Modular embedding SDK (Preview), Modular embedding, Modular embedding (Preview), Public sharing, Static embedding, Static embedding (Preview), Full app embedding, Full app embedding (Preview), Embedding (Unknown), Data app, Data app (Preview)]
last_used_at: '2026-04-22T14:46:17.273549Z'
type: full
-values: [embedding-sdk-react, embedding-sdk-react-preview, embedding-simple, embedding-simple-preview, embedding-public, embedding-iframe-static, embedding-iframe-static-preview, embedding-iframe-full-app, embedding-iframe-full-app-preview, embedding-iframe]
+values: [embedding-sdk-react, embedding-sdk-react-preview, embedding-simple, embedding-simple-preview, embedding-public, embedding-iframe-static, embedding-iframe-static-preview, embedding-iframe-full-app, embedding-iframe-full-app-preview, embedding-iframe, data-app, data-app-preview]
serdes/meta:
- {id: Internal Metabase Database, model: Database}
- {id: public, model: Schema}
diff --git a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_query_log/fields/embedding_client_identifier.yaml b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_query_log/fields/embedding_client_identifier.yaml
new file mode 100644
index 00000000000..62b4a43a52c
--- /dev/null
+++ b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_query_log/fields/embedding_client_identifier.yaml
@@ -0,0 +1,21 @@
+name: embedding_client_identifier
+display_name: Embedding Client Identifier
+created_at: '2026-07-13T00:00:00Z'
+visibility_type: normal
+table_id: [Internal Metabase Database, public, v_query_log]
+database_type: varchar
+base_type: type/Text
+effective_type: type/Text
+semantic_type: type/Category
+position: 39
+custom_position: 0
+database_position: 39
+has_field_values: auto-list
+serdes/meta:
+- {id: Internal Metabase Database, model: Database}
+- {id: public, model: Schema}
+- {id: v_query_log, model: Table}
+- {id: embedding_client_identifier, model: Field}
+database_is_generated: false
+database_is_nullable: true
+database_is_pk: false
diff --git a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_view_log/fields/embedding_client___fieldvalues.yaml b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_view_log/fields/embedding_client___fieldvalues.yaml
index 355eeb24c75..6cd537f62a2 100644
--- a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_view_log/fields/embedding_client___fieldvalues.yaml
+++ b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_view_log/fields/embedding_client___fieldvalues.yaml
@@ -1,8 +1,8 @@
created_at: '2026-04-22T14:46:16.631421Z'
-human_readable_values: [Modular embedding SDK, Modular embedding SDK (Preview), Modular embedding, Modular embedding (Preview), Public sharing, Static embedding, Static embedding (Preview), Full app embedding, Full app embedding (Preview), Embedding (Unknown)]
+human_readable_values: [Modular embedding SDK, Modular embedding SDK (Preview), Modular embedding, Modular embedding (Preview), Public sharing, Static embedding, Static embedding (Preview), Full app embedding, Full app embedding (Preview), Embedding (Unknown), Data app, Data app (Preview)]
last_used_at: '2026-04-22T16:08:52.003887Z'
type: full
-values: [embedding-sdk-react, embedding-sdk-react-preview, embedding-simple, embedding-simple-preview, embedding-public, embedding-iframe-static, embedding-iframe-static-preview, embedding-iframe-full-app, embedding-iframe-full-app-preview, embedding-iframe]
+values: [embedding-sdk-react, embedding-sdk-react-preview, embedding-simple, embedding-simple-preview, embedding-public, embedding-iframe-static, embedding-iframe-static-preview, embedding-iframe-full-app, embedding-iframe-full-app-preview, embedding-iframe, data-app, data-app-preview]
serdes/meta:
- {id: Internal Metabase Database, model: Database}
- {id: public, model: Schema}
diff --git a/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_view_log/fields/embedding_client_identifier.yaml b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_view_log/fields/embedding_client_identifier.yaml
new file mode 100644
index 00000000000..c6f189494c6
--- /dev/null
+++ b/resources/instance_analytics/databases/internal_metabase_database/schemas/public/tables/v_view_log/fields/embedding_client_identifier.yaml
@@ -0,0 +1,21 @@
+name: embedding_client_identifier
+display_name: Embedding Client Identifier
+created_at: '2026-07-13T00:00:00Z'
+visibility_type: normal
+table_id: [Internal Metabase Database, public, v_view_log]
+database_type: varchar
+base_type: type/Text
+effective_type: type/Text
+semantic_type: type/Category
+position: 20
+custom_position: 0
+database_position: 20
+has_field_values: auto-list
+serdes/meta:
+- {id: Internal Metabase Database, model: Database}
+- {id: public, model: Schema}
+- {id: v_view_log, model: Table}
+- {id: embedding_client_identifier, model: Field}
+database_is_generated: false
+database_is_nullable: true
+database_is_pk: false
diff --git a/resources/migrations/064/20260717_data_app.yaml b/resources/migrations/064/20260717_data_app.yaml
new file mode 100644
index 00000000000..ec7c9274c99
--- /dev/null
+++ b/resources/migrations/064/20260717_data_app.yaml
@@ -0,0 +1,214 @@
+## Create data_app table for the data-app PoC.
+##
+## Data apps come from the repository connected via the remote-sync feature. The
+## repo root has a `data_apps/` directory; each subdirectory is one app and
+## contains a `data_app.yaml` (name/path/allowed_hosts) plus its built bundle. Each app dir
+## is materialized as one row in this table on sync. The `bundle` / `bundle_hash`
+## columns cache the last successfully synced bytes (nullable until first sync).
+
+databaseChangeLog:
+ - changeSet:
+ id: v64.data-app1
+ author: timofei
+ comment: Create data_app table for Git-synced data-app bundles
+ changes:
+ - createTable:
+ tableName: data_app
+ remarks: Stores Git-synced data-app bundles, one row per data_apps/<dir> app.
+ columns:
+ - column:
+ name: id
+ type: int
+ autoIncrement: true
+ constraints:
+ primaryKey: true
+ nullable: false
+ - column:
+ name: name
+ type: varchar(254)
+ remarks: Slug, used in the URL /apps/:name
+ constraints:
+ nullable: false
+ unique: true
+ - column:
+ name: display_name
+ type: varchar(254)
+ remarks: Human-readable name from the manifest, shown in the admin UI
+ constraints:
+ nullable: false
+ - column:
+ name: allowed_hosts
+ type: ${text.type}
+ remarks: JSON array of origins the sandboxed bundle may fetch/XHR. NULL when none configured.
+ constraints:
+ nullable: true
+ - column:
+ name: bundle_path
+ type: varchar(1024)
+ remarks: Path within the repository to this app's built bundle file
+ constraints:
+ nullable: false
+ - column:
+ name: bundle
+ type: ${blob.type}
+ remarks: Cached raw bytes of the last successfully synced bundle. NULL until first sync.
+ constraints:
+ nullable: true
+ - column:
+ name: bundle_hash
+ type: varchar(64)
+ remarks: SHA-256 hex of the cached bytes, used as HTTP ETag. NULL until first sync.
+ constraints:
+ nullable: true
+ - column:
+ name: last_synced_sha
+ type: varchar(40)
+ remarks: Git commit SHA the cached bundle was synced from
+ constraints:
+ nullable: true
+ - column:
+ name: last_synced_at
+ type: ${timestamp_type}
+ remarks: Timestamp of the last successful sync for this app
+ constraints:
+ nullable: true
+ - column:
+ name: sync_error
+ type: ${text.type}
+ remarks: Error from the most recent failed sync of this app, NULL when the last sync succeeded
+ constraints:
+ nullable: true
+ - column:
+ name: enabled
+ type: ${boolean.type}
+ defaultValueBoolean: true
+ remarks: Admin toggle. When false the app is not served and is hidden from the data-app routes.
+ constraints:
+ nullable: false
+ - column:
+ name: created_at
+ type: ${timestamp_type}
+ remarks: Timestamp when the data app was first synced
+ constraints:
+ nullable: false
+ - column:
+ name: updated_at
+ type: ${timestamp_type}
+ remarks: Timestamp when the data app was last updated
+ constraints:
+ nullable: false
+
+ - changeSet:
+ id: v64.data-app2
+ author: timofei
+ comment: Use longblob for data_app.bundle on MySQL/MariaDB so it can hold multi-MB bundles
+ changes:
+ - modifyDataType:
+ tableName: data_app
+ columnName: bundle
+ newDataType: longblob
+ rollback:
+ - modifyDataType:
+ tableName: data_app
+ columnName: bundle
+ newDataType: ${blob.type}
+ preConditions:
+ - onFail: MARK_RAN
+ - dbms:
+ type: mysql,mariadb
+
+ # --- Embedding analytics: attribute query executions / views to a concrete
+ # embedding client (e.g. the data-app name) carried by the
+ # X-Metabase-Client-Identifier header, alongside the other embedding attributes. ---
+
+ - changeSet:
+ id: v64.data-app3
+ author: timofei
+ comment: Add embedding_client_identifier column to query_execution for embedding analytics
+ changes:
+ - addColumn:
+ tableName: query_execution
+ columns:
+ - column:
+ name: embedding_client_identifier
+ remarks: Identifier of the concrete embedding client (e.g. the data-app name) from the X-Metabase-Client-Identifier header
+ type: varchar(254)
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v64.data-app4
+ author: timofei
+ comment: Add embedding_client_identifier column to view_log for embedding analytics
+ changes:
+ - addColumn:
+ tableName: view_log
+ columns:
+ - column:
+ name: embedding_client_identifier
+ remarks: Identifier of the concrete embedding client (e.g. the data-app name) from the X-Metabase-Client-Identifier header
+ type: varchar(254)
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v64.data-app5
+ author: timofei
+ comment: Updated view v_query_log v6 - add embedding_client_identifier (EMB-2088)
+ changes:
+ - sqlFile:
+ dbms: postgresql
+ path: ../instance_analytics_views/query_log/v6/postgres-query_log.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: mysql,mariadb
+ path: ../instance_analytics_views/query_log/v6/mysql-query_log.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: h2
+ path: ../instance_analytics_views/query_log/v6/h2-query_log.sql
+ relativeToChangelogFile: true
+ rollback:
+ - sqlFile:
+ dbms: postgresql
+ path: ../instance_analytics_views/query_log/v5/postgres-query_log.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: mysql,mariadb
+ path: ../instance_analytics_views/query_log/v5/mysql-query_log.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: h2
+ path: ../instance_analytics_views/query_log/v5/h2-query_log.sql
+ relativeToChangelogFile: true
+
+ - changeSet:
+ id: v64.data-app6
+ author: timofei
+ comment: Updated view v_view_log v5 - add embedding_client_identifier (EMB-2088)
+ changes:
+ - sqlFile:
+ dbms: postgresql
+ path: ../instance_analytics_views/view_log/v5/postgres-view_log.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: mysql,mariadb
+ path: ../instance_analytics_views/view_log/v5/mysql-view_log.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: h2
+ path: ../instance_analytics_views/view_log/v5/h2-view_log.sql
+ relativeToChangelogFile: true
+ rollback:
+ - sqlFile:
+ dbms: postgresql
+ path: ../instance_analytics_views/view_log/v4/postgres-view_log.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: mysql,mariadb
+ path: ../instance_analytics_views/view_log/v4/mysql-view_log.sql
+ relativeToChangelogFile: true
+ - sqlFile:
+ dbms: h2
+ path: ../instance_analytics_views/view_log/v4/h2-view_log.sql
+ relativeToChangelogFile: true
diff --git a/resources/migrations/instance_analytics_views/query_log/v6/h2-query_log.sql b/resources/migrations/instance_analytics_views/query_log/v6/h2-query_log.sql
new file mode 100644
index 00000000000..349ae80a2b5
--- /dev/null
+++ b/resources/migrations/instance_analytics_views/query_log/v6/h2-query_log.sql
@@ -0,0 +1,46 @@
+DROP VIEW IF EXISTS v_query_log;
+
+
+CREATE OR REPLACE VIEW v_query_log AS
+SELECT id AS entity_id,
+ started_at,
+ cast(running_time AS DOUBLE) / 1000 AS running_time_seconds,
+ result_rows,
+ native AS is_native,
+ context AS query_source,
+ error,
+ coalesce(executor_id, 0) AS user_id,
+ card_id,
+ 'card_' || card_id AS card_qualified_id,
+ dashboard_id,
+ 'dashboard_' || dashboard_id AS dashboard_qualified_id,
+ pulse_id,
+ database_id,
+ 'database_' || database_id AS database_qualified_id,
+ cache_hit,
+ action_id,
+ 'action_' || action_id AS action_qualified_id,
+ transform_id,
+ 'transform_' || transform_id AS transform_qualified_id,
+ lens_id,
+ lens_params,
+ query,
+ embedding_client,
+ embedding_client_identifier,
+ embedding_route,
+ CASE WHEN embedding_client LIKE '%-preview' THEN TRUE ELSE FALSE END AS is_preview,
+ embedding_sdk_version,
+ metabase_version,
+ auth_method,
+ is_sandboxed,
+ is_impersonated,
+ is_db_routed,
+ parameters,
+ tenant_id,
+ embedding_hostname,
+ embedding_path,
+ user_agent,
+ sanitized_user_agent,
+ ip_address
+FROM query_execution
+ LEFT JOIN query ON query_execution.hash = query.query_hash;
diff --git a/resources/migrations/instance_analytics_views/query_log/v6/mysql-query_log.sql b/resources/migrations/instance_analytics_views/query_log/v6/mysql-query_log.sql
new file mode 100644
index 00000000000..214d2dde55d
--- /dev/null
+++ b/resources/migrations/instance_analytics_views/query_log/v6/mysql-query_log.sql
@@ -0,0 +1,48 @@
+DROP VIEW IF EXISTS v_query_log;
+
+
+CREATE OR REPLACE
+SQL SECURITY INVOKER
+VIEW v_query_log AS
+SELECT id AS entity_id,
+ started_at,
+ cast(running_time AS DOUBLE) / 1000 AS running_time_seconds,
+ result_rows,
+ native AS is_native,
+ context AS query_source,
+ error,
+ coalesce(executor_id, 0) AS user_id,
+ card_id,
+ concat('card_', card_id) AS card_qualified_id,
+ dashboard_id,
+ concat('dashboard_', dashboard_id) AS dashboard_qualified_id,
+ pulse_id,
+ database_id,
+ concat('database_', database_id) AS database_qualified_id,
+ cache_hit,
+ action_id,
+ concat('action_', action_id) AS action_qualified_id,
+ transform_id,
+ concat('transform_', transform_id) AS transform_qualified_id,
+ lens_id,
+ lens_params,
+ query,
+ embedding_client,
+ embedding_client_identifier,
+ embedding_route,
+ CASE WHEN embedding_client LIKE '%-preview' THEN TRUE ELSE FALSE END AS is_preview,
+ embedding_sdk_version,
+ metabase_version,
+ auth_method,
+ is_sandboxed,
+ is_impersonated,
+ is_db_routed,
+ parameters,
+ tenant_id,
+ embedding_hostname,
+ embedding_path,
+ user_agent,
+ sanitized_user_agent,
+ ip_address
+FROM query_execution
+ LEFT JOIN query ON query_execution.hash = query.query_hash;
diff --git a/resources/migrations/instance_analytics_views/query_log/v6/postgres-query_log.sql b/resources/migrations/instance_analytics_views/query_log/v6/postgres-query_log.sql
new file mode 100644
index 00000000000..00ea0e489b2
--- /dev/null
+++ b/resources/migrations/instance_analytics_views/query_log/v6/postgres-query_log.sql
@@ -0,0 +1,46 @@
+DROP VIEW IF EXISTS v_query_log;
+
+
+CREATE OR REPLACE VIEW v_query_log AS
+SELECT id AS entity_id,
+ started_at,
+ cast(running_time AS double precision) / 1000 AS running_time_seconds,
+ result_rows,
+ native AS is_native,
+ context AS query_source,
+ error,
+ coalesce(executor_id, 0) AS user_id,
+ card_id,
+ 'card_' || card_id AS card_qualified_id,
+ dashboard_id,
+ 'dashboard_' || dashboard_id AS dashboard_qualified_id,
+ pulse_id,
+ database_id,
+ 'database_' || database_id AS database_qualified_id,
+ cache_hit,
+ action_id,
+ 'action_' || action_id AS action_qualified_id,
+ transform_id,
+ 'transform_' || transform_id AS transform_qualified_id,
+ lens_id,
+ lens_params,
+ query,
+ embedding_client,
+ embedding_client_identifier,
+ embedding_route,
+ CASE WHEN embedding_client LIKE '%-preview' THEN TRUE ELSE FALSE END AS is_preview,
+ embedding_sdk_version,
+ metabase_version,
+ auth_method,
+ is_sandboxed,
+ is_impersonated,
+ is_db_routed,
+ parameters,
+ tenant_id,
+ embedding_hostname,
+ embedding_path,
+ user_agent,
+ sanitized_user_agent,
+ ip_address
+FROM query_execution
+ LEFT JOIN query ON query_execution.hash = query.query_hash;
diff --git a/resources/migrations/instance_analytics_views/view_log/v5/h2-view_log.sql b/resources/migrations/instance_analytics_views/view_log/v5/h2-view_log.sql
new file mode 100644
index 00000000000..82d0c48a840
--- /dev/null
+++ b/resources/migrations/instance_analytics_views/view_log/v5/h2-view_log.sql
@@ -0,0 +1,24 @@
+DROP VIEW IF EXISTS v_view_log;
+
+
+CREATE OR REPLACE VIEW v_view_log AS
+ (SELECT id, timestamp, coalesce(user_id, 0) as user_id,
+ model AS entity_type,
+ model_id AS entity_id,
+ model || '_' || model_id AS entity_qualified_id,
+ embedding_client,
+ embedding_client_identifier,
+ embedding_route,
+ CASE WHEN embedding_client LIKE '%-preview' THEN TRUE ELSE FALSE END AS is_preview,
+ has_access,
+ context,
+ embedding_sdk_version,
+ metabase_version,
+ auth_method,
+ tenant_id,
+ embedding_hostname,
+ embedding_path,
+ user_agent,
+ sanitized_user_agent,
+ ip_address
+ FROM view_log)
diff --git a/resources/migrations/instance_analytics_views/view_log/v5/mysql-view_log.sql b/resources/migrations/instance_analytics_views/view_log/v5/mysql-view_log.sql
new file mode 100644
index 00000000000..140173e8479
--- /dev/null
+++ b/resources/migrations/instance_analytics_views/view_log/v5/mysql-view_log.sql
@@ -0,0 +1,26 @@
+DROP VIEW IF EXISTS v_view_log;
+
+
+CREATE OR REPLACE
+SQL SECURITY INVOKER
+VIEW v_view_log AS
+ (SELECT id, timestamp, coalesce(user_id, 0) as user_id,
+ model AS entity_type,
+ model_id AS entity_id,
+ concat(model, '_', model_id) AS entity_qualified_id,
+ embedding_client,
+ embedding_client_identifier,
+ embedding_route,
+ CASE WHEN embedding_client LIKE '%-preview' THEN TRUE ELSE FALSE END AS is_preview,
+ has_access,
+ context,
+ embedding_sdk_version,
+ metabase_version,
+ auth_method,
+ tenant_id,
+ embedding_hostname,
+ embedding_path,
+ user_agent,
+ sanitized_user_agent,
+ ip_address
+ FROM view_log)
diff --git a/resources/migrations/instance_analytics_views/view_log/v5/postgres-view_log.sql b/resources/migrations/instance_analytics_views/view_log/v5/postgres-view_log.sql
new file mode 100644
index 00000000000..66e5c699cd7
--- /dev/null
+++ b/resources/migrations/instance_analytics_views/view_log/v5/postgres-view_log.sql
@@ -0,0 +1,24 @@
+DROP VIEW IF EXISTS v_view_log;
+
+
+CREATE OR REPLACE VIEW v_view_log AS
+ (SELECT id, timestamp, coalesce(user_id, 0) AS user_id,
+ model AS entity_type,
+ model_id AS entity_id,
+ model || '_' || model_id AS entity_qualified_id,
+ embedding_client,
+ embedding_client_identifier,
+ embedding_route,
+ CASE WHEN embedding_client LIKE '%-preview' THEN TRUE ELSE FALSE END AS is_preview,
+ has_access,
+ context,
+ embedding_sdk_version,
+ metabase_version,
+ auth_method,
+ tenant_id,
+ embedding_hostname,
+ embedding_path,
+ user_agent,
+ sanitized_user_agent,
+ ip_address
+ FROM view_log)
diff --git a/rspack.embedding-sdk-cli.config.js b/rspack.embedding-sdk-cli.config.js
deleted file mode 100644
index 2430fcbb484..00000000000
--- a/rspack.embedding-sdk-cli.config.js
+++ /dev/null
@@ -1,71 +0,0 @@
-// @ts-check
-/* eslint-disable no-undef */
-const path = require("path");
-
-const rspack = require("@rspack/core");
-
-const SDK_CLI_DIST_PATH = path.join(__dirname, "/resources/embedding-sdk/dist");
-const SDK_PACKAGE_SRC_PATH =
- __dirname + "/enterprise/frontend/src/embedding-sdk-package";
-const SDK_BUNDLE_SRC_PATH =
- __dirname + "/frontend/src/embedding-sdk-bundle";
-const SDK_CLI_PATH = path.join(
- __dirname,
- "/enterprise/frontend/src/embedding-sdk-package/cli",
-);
-
-const METABASE_SRC_PATH = path.join(__dirname, "/frontend/src/metabase");
-const TYPES_SRC_PATH = path.join(__dirname, "/frontend/src/metabase-types");
-
-const BABEL_CONFIG = {
- cacheDirectory: process.env.BABEL_DISABLE_CACHE ? false : ".babel_cache",
-};
-
-/** @type {import('@rspack/cli').Configuration} */
-const config = {
- mode: "production",
- entry: `${SDK_CLI_PATH}/cli.ts`,
- target: "node",
- context: SDK_CLI_PATH,
- output: {
- path: SDK_CLI_DIST_PATH,
- filename: "cli.js",
- library: { type: "commonjs2" },
- },
- resolve: {
- extensions: [".ts", ".js"],
- alias: {
- metabase: METABASE_SRC_PATH,
- "metabase-types": TYPES_SRC_PATH,
- "embedding-sdk-package": SDK_PACKAGE_SRC_PATH,
- "embedding-sdk-bundle": SDK_BUNDLE_SRC_PATH,
- },
- },
- module: {
- rules: [
- {
- test: /\.(ts|js)$/,
- exclude: /node_modules/,
- use: [{ loader: "babel-loader", options: BABEL_CONFIG }],
- },
- ],
- },
- plugins: [
- new rspack.BannerPlugin({ banner: "#!/usr/bin/env node", raw: true }),
- ],
- optimization: {
- minimize: true,
- minimizer: [
- new rspack.SwcJsMinimizerRspackPlugin({
- minimizerOptions: {
- format: {
- comments: false,
- },
- },
- extractComments: false,
- }),
- ],
- },
-};
-
-module.exports = config;
diff --git a/rspack.embedding-sdk-node.config.js b/rspack.embedding-sdk-node.config.js
new file mode 100644
index 00000000000..55ff7ad00cf
--- /dev/null
+++ b/rspack.embedding-sdk-node.config.js
@@ -0,0 +1,115 @@
+// @ts-check
+/* eslint-disable no-undef */
+// Node-targeted builds for the SDK package: the `npx` CLI and the data-app dev
+// preset (`@metabase/embedding-sdk-react/data-app-dev/config`). Both run
+// in Node (not the browser), so they can't go through the browser rspack bundle.
+const path = require("path");
+
+const rspack = require("@rspack/core");
+
+const SDK_DIST_PATH = path.join(__dirname, "/resources/embedding-sdk/dist");
+const SDK_PACKAGE_SRC_PATH =
+ __dirname + "/enterprise/frontend/src/embedding-sdk-package";
+const SDK_BUNDLE_SRC_PATH = __dirname + "/frontend/src/embedding-sdk-bundle";
+const SDK_CLI_PATH = path.join(SDK_PACKAGE_SRC_PATH, "cli");
+
+const METABASE_SRC_PATH = path.join(__dirname, "/frontend/src/metabase");
+const TYPES_SRC_PATH = path.join(__dirname, "/frontend/src/metabase-types");
+const ENTERPRISE_SRC_PATH =
+ __dirname + "/enterprise/frontend/src/metabase-enterprise";
+const BUILD_CONFIGS_PATH = path.join(__dirname, "/frontend/build");
+
+const BABEL_CONFIG = {
+ cacheDirectory: process.env.BABEL_DISABLE_CACHE ? false : ".babel_cache",
+};
+
+const sharedResolve = {
+ extensions: [".ts", ".js"],
+ alias: {
+ metabase: METABASE_SRC_PATH,
+ "metabase-types": TYPES_SRC_PATH,
+ "embedding-sdk-package": SDK_PACKAGE_SRC_PATH,
+ "embedding-sdk-bundle": SDK_BUNDLE_SRC_PATH,
+ "metabase-enterprise": ENTERPRISE_SRC_PATH,
+ "build-configs": BUILD_CONFIGS_PATH,
+ },
+};
+
+const sharedModule = {
+ rules: [
+ {
+ test: /\.(tsx?|js)$/,
+ exclude: /node_modules/,
+ use: [{ loader: "babel-loader", options: BABEL_CONFIG }],
+ },
+ ],
+};
+
+const minimizer = [
+ new rspack.SwcJsMinimizerRspackPlugin({
+ minimizerOptions: { format: { comments: false } },
+ extractComments: false,
+ }),
+];
+
+/** @type {import('@rspack/cli').Configuration} */
+const cliConfig = {
+ mode: "production",
+ entry: `${SDK_CLI_PATH}/cli.ts`,
+ target: "node",
+ context: SDK_CLI_PATH,
+ output: {
+ path: SDK_DIST_PATH,
+ filename: "cli.js",
+ library: { type: "commonjs2" },
+ },
+ resolve: sharedResolve,
+ module: sharedModule,
+ plugins: [
+ new rspack.BannerPlugin({ banner: "#!/usr/bin/env node", raw: true }),
+ ],
+ optimization: { minimize: true, minimizer },
+};
+
+// ESM-only: this entry is imported from a Vite config (`import { dataAppConfig }
+// from "@metabase/embedding-sdk-react/data-app-dev/config"`), which Vite loads
+// through the ESM `import` condition. ESM-only lets the dev plugin read its
+// sibling dev-entry bundle via `import.meta.url` natively (no `__dirname` shim
+// needed). The browser subpath (`/data-app-dev`) is built from `data-app-dev.ts`
+// by rspack.embedding-sdk-package.config.js.
+/** @type {import('@rspack/cli').Configuration} */
+const dataAppDevConfig = {
+ mode: "production",
+ entry: `${SDK_PACKAGE_SRC_PATH}/data-app-dev.config.ts`,
+ target: "node",
+ context: SDK_PACKAGE_SRC_PATH,
+ // The consumer's app provides the Vite toolchain (the same Vite instance runs
+ // the config), so leave it all external. Bundling the plugins — `vite-plugin-svgr`
+ // especially — would pull in @svgr/core + Babel + TypeScript + browserslist,
+ // which is heavy and floods the build with dynamic-`require` warnings.
+ externals: [
+ "vite",
+ "@vitejs/plugin-react",
+ "vite-plugin-svgr",
+ "vite-plugin-css-injected-by-js",
+ ],
+ externalsType: "module",
+ output: {
+ path: SDK_DIST_PATH,
+ filename: "data-app-dev.config.js",
+ library: { type: "module" },
+ },
+ experiments: { outputModule: true },
+ resolve: sharedResolve,
+ // Leave `new URL(..., import.meta.url)` fully as runtime code: `url: false` stops
+ // it being treated as a build-time asset, and `importMeta: false` stops rspack
+ // baking `import.meta.url` to the source path — so at runtime it's the emitted
+ // bundle's URL and the dev plugin resolves its sibling dev-entry in `dist`.
+ module: {
+ ...sharedModule,
+ parser: { javascript: { url: false, importMeta: false } },
+ },
+ optimization: { minimize: true, minimizer },
+};
+
+module.exports = [cliConfig, dataAppDevConfig];
diff --git a/rspack.embedding-sdk-package.config.js b/rspack.embedding-sdk-package.config.js
index bc32626d5de..7fc7b861e03 100644
--- a/rspack.embedding-sdk-package.config.js
+++ b/rspack.embedding-sdk-package.config.js
@@ -8,9 +8,13 @@ const {
OPTIMIZATION_CONFIG,
} = require("./frontend/build/embedding-sdk/rspack/shared");
const { BABEL_CONFIG } = require("./frontend/build/shared/rspack/babel-config");
+const { CSS_CONFIG } = require("./frontend/build/shared/rspack/css-config");
const {
EXTERNAL_DEPENDENCIES,
} = require("./frontend/build/embedding-sdk/constants/external-dependencies");
+const {
+ DATA_APP_DEV_CONFIG_VIRTUAL_ID,
+} = require("./frontend/build/embedding-sdk/constants/data-app-virtual-modules");
const {
SDK_PACKAGE_BANNER,
} = require("./frontend/build/embedding-sdk/constants/banner");
@@ -31,12 +35,15 @@ const BUILD_PATH = __dirname + "/resources/embedding-sdk";
const EMBEDDING_SDK_BUNDLE_HOST = process.env.EMBEDDING_SDK_BUNDLE_HOST || "";
-const config = {
+const baseConfig = {
context: SDK_PACKAGE_SRC_PATH,
devtool: false,
- entry: "./index.ts",
+ entry: {
+ main: "./index.ts",
+ "data-app": "./data-app.ts",
+ },
output: {
path: BUILD_PATH + "/dist",
@@ -65,6 +72,19 @@ const config = {
},
],
},
+ {
+ // The published package has no separate stylesheet for consumers to
+ // import, and components like the dev toolbar must render standalone
+ // before the SDK bundle (and its CSS) loads. style-loader injects the
+ // CSS modules at runtime so they ship inside the JS bundle itself.
+ test: /\.css$/,
+ use: [
+ { loader: "style-loader" },
+ { loader: "css-loader", options: CSS_CONFIG },
+ { loader: "postcss-loader" },
+ ],
+ type: "javascript/auto",
+ },
],
},
@@ -79,10 +99,63 @@ const config = {
...getBuildInfoValues({ version: getSdkPackageVersionFromPackageJson() }),
}),
new rspack.optimize.LimitChunkCountPlugin({
- maxChunks: 1,
+ maxChunks: 3,
}),
new rspack.BannerPlugin(getBannerOptions(SDK_PACKAGE_BANNER)),
].filter(Boolean),
};
-module.exports = config;
+const esmConfig = {
+ ...baseConfig,
+
+ entry: {
+ "main.esm": "./index.ts",
+ "data-app.esm": "./data-app.ts",
+ "data-app-dev": "./data-app-dev.ts",
+ },
+
+ output: {
+ ...baseConfig.output,
+ filename: "[name].js",
+ library: {
+ type: "module",
+ },
+ },
+
+ externalsType: "module",
+
+ experiments: {
+ outputModule: true,
+ },
+};
+
+// The data-app dev entry is its own ESM build. It keeps the consumer's React/SDK
+// and the dev plugin's virtual config external (so the bundle runs against the
+// consumer's single React/SDK instance), with those extra externals scoped HERE
+// so they can't affect the SDK (`main` / `data-app`) builds above.
+const dataAppDevEntryConfig = {
+ ...esmConfig,
+
+ entry: {
+ "data-app-dev-entry": "./data-app-dev-entry.tsx",
+ },
+
+ externals: [
+ ...Object.keys(EXTERNAL_DEPENDENCIES),
+ "react/jsx-dev-runtime",
+ "@metabase/embedding-sdk-react",
+ "@metabase/embedding-sdk-react/data-app",
+ "@metabase/embedding-sdk-react/data-app-dev",
+ DATA_APP_DEV_CONFIG_VIRTUAL_ID,
+ ],
+
+ // Leave `import.meta` untouched so the consumer's Vite (not rspack) resolves it
+ // at serve time — `import.meta.env.DATA_APP_MB_*` for auth and `import.meta.hot`
+ // for the soft reload. Without this, rspack evaluates them to `undefined`.
+ module: {
+ ...baseConfig.module,
+ parser: { javascript: { importMeta: false } },
+ },
+};
+
+module.exports = [baseConfig, esmConfig, dataAppDevEntryConfig];
diff --git a/rspack.main.config.js b/rspack.main.config.js
index 384218544dc..fc9328b1df8 100644
--- a/rspack.main.config.js
+++ b/rspack.main.config.js
@@ -33,8 +33,14 @@ const {
const { SVGO_CONFIG } = require("./frontend/build/shared/rspack/svgo-config");
const SRC_PATH = __dirname + "/frontend/src/metabase";
+const ENTERPRISE_SRC_PATH =
+ __dirname + "/enterprise/frontend/src/metabase-enterprise";
const BUILD_PATH = __dirname + "/resources/frontend_client";
+// Data apps are an enterprise plugin (the iframe entry + its template live in the
+// enterprise tree), so their build entries and HTML are only produced in EE builds.
+const isEEBuild = process.env.MB_EDITION === "ee";
+
// For sharing the embedding snippets in the docs with the embedding
// onboarding flow in the app to keep the snippets always in sync.
const SDK_DOCS_SNIPPETS_PATH = __dirname + "/docs/embedding/sdk/snippets";
@@ -123,6 +129,12 @@ const config = {
"app-embed-sdk": "./app-embed-sdk.tsx",
"app-embed-mcp": "./app-embed-mcp.tsx",
styles: "./css/index.module.css",
+ ...(isEEBuild && {
+ "app-data-app":
+ ENTERPRISE_SRC_PATH + "/data_apps/runtime/app-data-app.tsx",
+ "data-app-vendors":
+ ENTERPRISE_SRC_PATH + "/data_apps/runtime/iframe-vendors.ts",
+ }),
},
// we override it for dev mode below
@@ -241,7 +253,11 @@ const config = {
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
- chunks: "initial",
+ // The data-app iframe is isolated from main-app CSS/JS by design;
+ // sharing the vendor chunk would re-link them. Keep its
+ // node_modules in its own chunks.
+ chunks: (chunk) =>
+ chunk.name !== "data-app-vendors" && chunk.name !== "app-data-app",
name: "vendor",
priority: -10,
},
@@ -305,6 +321,19 @@ const config = {
chunks: ["vendor", "styles", "app-embed-sdk"],
template: __dirname + "/resources/frontend_client/index_template.html",
}),
+ // Enterprise-only: data apps are an enterprise plugin, so the iframe HTML is
+ // only emitted in EE builds (its chunks only exist there).
+ ...(isEEBuild
+ ? [
+ new HtmlWebpackPlugin({
+ filename: "../../data-app.html",
+ chunksSortMode: "manual",
+ chunks: ["data-app-vendors", "app-data-app"],
+ template:
+ __dirname + "/resources/frontend_client/data_app_template.html",
+ }),
+ ]
+ : []),
new HtmlWebpackPlugin({
filename: "../../embed-mcp.html",
chunksSortMode: "manual",
diff --git a/skills/metabase-data-app-actions/SKILL.md b/skills/metabase-data-app-actions/SKILL.md
new file mode 100644
index 00000000000..60be2de76b3
--- /dev/null
+++ b/skills/metabase-data-app-actions/SKILL.md
@@ -0,0 +1,222 @@
+---
+name: metabase-data-app-actions
+description: Use when a Metabase data app needs to trigger a write or mutation — submitting a form, updating a row, deleting an entry, running a saved action, or any "do something" interaction. Covers invoking an existing action via `useAction`, parameter typing, response handling, and the critical post-action refresh of any UI data the action may have changed.
+---
+
+# Triggering actions from a Metabase data app
+
+A Metabase **action** is a server-defined write operation against the data warehouse — either a basic CRUD operation (insert / update / delete) on a model, or a custom SQL command. Actions are configured ahead of time on the Metabase instance, with their parameters, model bindings, and permissions already set. A data app's job is to **invoke** an action with the right parameters when the user does something — clicking a button, submitting a form, confirming a destructive prompt.
+
+## The mental model
+
+Actions belong to a model. They mutate that model's rows. Concretely:
+
+- Every action has a parent model. In the schema it appears as `schema.models.<modelName>.actions.<actionName>`.
+- Model entries are included here only to catalog actions. Do not render models as questions, pass model ids to `InteractiveQuestion`, or fetch model rows; use semantic-layer queries/questions for read views.
+- An action's `type` is either `"implicit"` (CRUD on the model) or `"query"` (custom SQL the user authored).
+- Implicit actions have an `implicitKind` that says what they do: `"row/create"`, `"row/update"`, `"row/delete"`, or `"bulk/*"` variants.
+- Each action publishes a `parameters` list. Each parameter has a `slug` (the key the Data App sends), a `jsType` (`"string"` / `"number"` / `"Date"` / `"boolean"` / `"unknown"`), and an optional `required` flag.
+- Use `action.parameters` to know which fields to render and submit. A create result may include `result["created-row"]`, but that row is only typed as `Record<string, RowValue>`; use it for lightweight confirmation, then refresh the existing table/question/query data already used by the page. Do not fetch or render the parent model itself.
+
+## What's in the schema (and what isn't)
+
+Action entries are only generated when the typed schema includes models. Before writing action-invoking code, make sure the schema was generated with `include-models=true`; with `database=<name-or-id>&include-models=true`, Metabase includes models/actions for that database only. Do not rely on `question-collections` for actions; question collections only add saved questions.
+
+Before writing any action-invoking code, look at the schema and enumerate what's available under `schema.models.<m>.actions` across the models the app cares about. The schema is your **complete** catalog of actions for the instance, not a catalog of model data to display. If a model's `actions` entry has `create`, `update`, `delete`, those are the actions invokable. Anything not present doesn't exist as far as the Data App is concerned.
+
+## The hook
+
+```ts
+import { useAction } from "@metabase/embedding-sdk-react";
+import {
+ type ActionKindFromDataAppSchema,
+ type ActionParametersFromDataAppSchema,
+} from "@metabase/embedding-sdk-react/data-app";
+
+const { execute, isExecuting, result, error, reset } = useAction<
+ ActionParametersFromDataAppSchema<typeof schema.models.<model>.actions.<action>>,
+ ActionKindFromDataAppSchema<typeof schema.models.<model>.actions.<action>>
+>(schema.models.<model>.actions.<action>.id);
+```
+
+- **First argument** is the action's numeric **id** — read it off the schema entry as `schema.models.<model>.actions.<action>.id`. The hook also accepts an action's `entity_id` string, but in a Data App you always have the numeric id on hand from the schema, so pass that.
+- **`TParameters` generic** — the type of the parameters object you'll pass to `execute`. In a Data App, derive it from the schema with `ActionParametersFromDataAppSchema<typeof schema.models.<model>.actions.<action>>` imported from `@metabase/embedding-sdk-react/data-app`; the helper expands the schema's `parameters[]` into a keyed object, marks `required: true` entries as required keys, and types each value from its `jsType`. Skip the generic and `execute` accepts any `Record<string, unknown>`.
+- **`TKind` generic** — the action kind literal that drives the discriminated `result` shape. In a Data App, derive it from the same schema entry with `ActionKindFromDataAppSchema<typeof schema.models.<model>.actions.<action>>` imported from `@metabase/embedding-sdk-react/data-app`; the helper maps `implicitKind` (`"row/create"` → `"create"`, `"row/update"` → `"update"`, `"row/delete"` → `"delete"`, any `"bulk/*"` → `"bulk"`) and `type === "query"` → `"sql"`. Skip the generic and `result` defaults to the `AnyActionResult` union — TS-narrowable via `"<key>" in result`, but you lose the per-kind precision.
+- **`execute(parameters)`** — triggers the action. Parameters object is keyed by parameter `slug`; parameters declared `required: true` are required keys, everything else optional. Returns the response body on success AND throws on failure (the error is also written to `error` state for render-time consumers). Resolves to `null` (without making a request) when `actionId` is `null` or the SDK is not yet initialized — guard the call site if those cases are reachable.
+- **No `enabled` / `options` argument.** The hook only ever runs when `execute(...)` is called, so a gate option would be redundant. Skip the action by branching in the event handler:
+ ```ts
+ const onClick = async () => {
+ if (!user.canEdit) return;
+ await execute({ id: orderId, discount });
+ };
+ ```
+- **`isExecuting`** — `true` between the call and its resolution. Drive button `disabled` from this so the user can't double-click into duplicate requests.
+- **`result`** — the response body, discriminated by `TKind` (or the `AnyActionResult` union when `TKind` is omitted). `null` before the first call and after `reset()`. Use it for lightweight confirmation (`result?.["created-row"]` after an insert, `result?.["rows-affected"]` after a SQL action), but do not treat create rows as richly typed model rows; refresh surrounding data instead — see *After an action runs*.
+- **`error`** — the last thrown error, typed `ActionExecuteError | null`. Read fields directly with no cast: `error?.data?.message`, `error?.status`, `error?.isCancelled`.
+- **`reset()`** — clears `result` and `error` back to `null`. Useful after the user acknowledges success or dismisses an error.
+
+**The hook does NOT auto-fire on mount.** Actions only run when the Data App calls `execute(...)` explicitly.
+
+## Canonical usage — a form that creates a row
+
+```tsx
+import { useAction } from "@metabase/embedding-sdk-react";
+import {
+ type ActionKindFromDataAppSchema,
+ type ActionParametersFromDataAppSchema,
+} from "@metabase/embedding-sdk-react/data-app";
+
+import schema from "../metabase.data";
+
+function AddPersonForm({ onCreated }: { onCreated: () => void }) {
+ const { useState } = React;
+ const { execute, isExecuting, error, reset } = useAction<
+ ActionParametersFromDataAppSchema<typeof schema.models.people.actions.create>,
+ ActionKindFromDataAppSchema<typeof schema.models.people.actions.create>
+ >(schema.models.people.actions.create.id);
+
+ const [name, setName] = useState("");
+ const [email, setEmail] = useState("");
+
+ async function onSubmit(e: React.FormEvent) {
+ e.preventDefault();
+ try {
+ await execute({ name, email }); // typed: keys match parameter slugs
+ setName("");
+ setEmail("");
+ onCreated(); // ← let the parent refresh dependent data
+ } catch {
+ // error is captured into hook state for render-time display
+ }
+ }
+
+ return (
+ <form onSubmit={onSubmit}>
+ <input value={name} onChange={(e) => setName(e.target.value)} />
+ <input value={email} onChange={(e) => setEmail(e.target.value)} />
+ <button type="submit" disabled={isExecuting || !name || !email}>
+ {isExecuting ? "Saving…" : "Add"}
+ </button>
+ </form>
+ );
+}
+```
+
+## Showing the error message
+
+When `execute(...)` fails, surface both error layers. The hook's `error` is typed `ActionExecuteError | null` — shape `{ status?, data: { message?, errors? }, isCancelled }`. `error.data.message` is the whole-request failure. `error.data.errors` is a per-field validation map keyed by parameter slug (`{ <slug>: <message> }`), or `{}` for whole-request failures. Read both directly, no cast:
+
+```tsx
+const fieldErrors = error?.data.errors ?? {};
+
+{error ? (
+ <pre style={{ whiteSpace: "pre-wrap", margin: 0 }}>
+ {error.data.message ?? "Action failed."}
+ </pre>
+) : null}
+
+{action.parameters.map((parameter) => {
+ const fieldError = fieldErrors[parameter.slug];
+ return (
+ <label key={parameter.slug}>
+ {parameter.displayName}
+ <input
+ aria-invalid={Boolean(fieldError)}
+ style={{ borderColor: fieldError ? "#dc2626" : undefined }}
+ />
+ {fieldError ? <div role="alert">{fieldError}</div> : null}
+ </label>
+ );
+})}
+```
+
+Use `<pre>` (or any element with `white-space: pre-wrap`) — the messages contain newlines that matter (driver errors include the SQL on its own line). A `<span>` collapses them into one wall of text.
+
+Example: submitting a 9-character value into a `CHARACTER(2)` column produces
+
+```
+Value too long for column "STATE CHARACTER(2)": "'dadasdasd' (9)";
+SQL statement:
+UPDATE "PUBLIC"."PEOPLE" SET … WHERE "PUBLIC"."PEOPLE"."ID" = 1 [22001-214]
+```
+
+That whole string is `error.data.message`. Render it as-is.
+
+**Don't:**
+
+- Render `"Failed"` / `"Something went wrong"` / `String(error)` instead of `error.data.message` — the user loses the only fix-it info they have.
+- Render only `error.data.message` for validation failures — `error.data.errors[parameter.slug]` is often the actionable "which field and why" detail.
+- Paraphrase the message into a "friendlier" version. The raw H2/Postgres/SQL error is more actionable than any rewrite.
+
+## After an action runs — keeping the UI honest
+
+When an action succeeds, the data the user sees may be stale. Without an explicit refresh, the list still shows the old rows; the stat tile still shows the old count; the row the user just edited still shows its old values. The action worked, but the UI lies — and there is no warning.
+
+The rule is simple and absolute: **after an action resolves successfully, every piece of data on the screen that the action could have changed must be refreshed.**
+
+## Mapping parameters
+
+Each `parameters[]` entry on a schema action exposes `slug`, `displayName`, `jsType`, and optionally `required`. The Data App's job:
+
+- **Object keys in `execute({ … })` match the parameter `slug` strings.** Use them as literal string keys — the typed `ActionParametersFromDataAppSchema<TAction>` shape will reject typos at compile time, but only when the action arg is the schema entry (not a bare id).
+- **Pick the right input `type` from `jsType`** so the browser provides the correct UX and built-in coercion. The agent never invents the input type from the slug name (a slug called `"phone"` is still `jsType: "string"` → `type="text"`).
+
+ | `jsType` | Input element |
+ | --- | --- |
+ | `"string"` | `<input type="text" …>` |
+ | `"number"` | `<input type="number" …>` |
+ | `"boolean"` | `<input type="checkbox" …>` (or a Mantine `Switch`/`Checkbox`) |
+ | `"Date"` | `<input type="date" …>` (or `"datetime-local"` if a time component is expected) |
+ | `"unknown"` | `<input type="text" …>` — best effort, coerce at the call site |
+
+- **Value types in `execute({ … })` match `jsType`.** A `jsType: "number"` parameter wants a `number`, not a string. With `type="number"` the input emits a number for `.valueAsNumber`, but `<input>.value` is still a string — coerce at the call site (`Number(input)`) if you're reading the latter.
+- **`required: true` parameters cannot be omitted.** Reflected in the TS type: required keys are required.
+- **`displayName`** is for labels; never use it as a key.
+
+For implicit actions, the slugs match the model's column names (slugified). For custom SQL actions, slugs are whatever the action's author named the SQL parameters in Metabase. Either way, the schema is the source of truth.
+
+## Form-side validation — match the main app
+
+The schema exposes `parameter.required` (and `jsType` for type coercion). That's the full validation contract today, matching Metabase's built-in action-execute form. **No length checks, no min/max, no format checks** — anything more granular comes back as a BE error after submit (see *Showing the error message*).
+
+**Schema is the ONLY source of truth.** Read `parameter.required` and wire it — nothing else. Don't add `required` because a field is named `"email"`, don't cap a "name" at 100 chars on a hunch, don't set `type="email"` from the slug. If the schema is silent, the field is unconstrained.
+
+**Disable the submit button while the form is invalid.** Drive it from the browser's native verdict so `required` is the only rule in play:
+
+```tsx
+const [isFormValid, setIsFormValid] = useState(false);
+const onFormChange = (e: React.FormEvent<HTMLFormElement>) =>
+ setIsFormValid(e.currentTarget.checkValidity());
+
+<form onSubmit={...} onChange={onFormChange}>
+ <input required={parameter.required} />
+ <button type="submit" disabled={isExecuting || !isFormValid}>Create</button>
+</form>
+```
+
+No hand-rolled `!name || !email` checks.
+
+## Debugging Checklist
+
+When an action appears to succeed but the screen doesn't update, or a call fails with a 400:
+
+1. Log `result`, `error`, and `isExecuting` after `await execute(...)` to confirm the request actually went through and succeeded.
+2. Confirm `useAction` was called with `schema.models.<model>.actions.<action>.id` (the numeric id) AND the `ActionParametersFromDataAppSchema<typeof …>` generic — without the generic, `execute` won't type-check the parameters object and typos slip through.
+3. Log the object passed to `execute({ ... })`. Every key must match a parameter `slug` from `schema.models.<model>.actions.<action>.parameters`; every value must match its declared `jsType`.
+4. List every data view on the screen that reads from the mutated model. Confirm each one's data hook is mounted ABOVE the action trigger so its refresh callback can be passed down.
+5. Confirm the refresh callback is called AFTER `await execute(...)` AND that the refresh itself is awaited. When multiple refreshes apply, confirm they're awaited together (`Promise.all`).
+6. For implicit actions, confirm the right `implicitKind` matches what you intend (`row/create` vs `row/update` vs `row/delete`) — picking the wrong action publishes the wrong write.
+7. If the schema doesn't list an action you expect, the action isn't defined on the instance or the schema file is stale. Regenerate the schema.
+
+## Common Mistakes
+
+- Omitting the `ActionParametersFromDataAppSchema<typeof schema.models.<model>.actions.<action>>` generic on `useAction`. `execute` then accepts any `Record<string, unknown>` and typos like `{ wrongKey: 1 }` slip through.
+- Forgetting to refresh after a successful action. The UI keeps rendering stale data with no error or warning.
+- Rendering `"Failed"` / `"Something went wrong"` / `String(error)` instead of the real backend message. Always extract `error.data.message` / `error.data.errors` (the diagnostic the user needs is in there) and render it verbatim — see *Showing the error message*.
+- Calling the refresh callback without `await`ing it. The modal dismisses or the form clears before fresh data arrives, leaving the user staring at the stale view for a beat.
+- Loading data INSIDE the same component that triggers the action. The hook is below the trigger, so its refresh callback can't be wired up. Lift the data hook to a parent and hand its refresh callback down to the trigger.
+- Passing raw `<input>` strings as parameter values when the slug's `jsType` is `"number"` or `"boolean"`. Coerce at the call site.
+- Letting the trigger fire while a previous request is in flight. Drive `disabled={isExecuting}` from the hook.
+- Prepending the action's `result` directly to a local list to skip the refresh. Server-filled defaults (auto-IDs, timestamps, computed columns, derived join columns) diverge from any client-side guess.
+- Inventing an action because the user asked for behavior the instance doesn't expose. The schema is the catalog of what exists; surface the gap, don't fake the call.
+- Reaching for `fetch("/api/action/...")` directly. The sandbox blocks raw network calls to the Metabase origin (raw `fetch`/XHR work only for external `allowed_hosts` declared in `data_app.yaml`); the only path to actions is `useAction`.
diff --git a/skills/metabase-data-app-routing/SKILL.md b/skills/metabase-data-app-routing/SKILL.md
new file mode 100644
index 00000000000..9679a8e71a1
--- /dev/null
+++ b/skills/metabase-data-app-routing/SKILL.md
@@ -0,0 +1,186 @@
+---
+name: metabase-data-app-routing
+description: Add client-side routing (multiple pages) to an existing Metabase data-app project using the host-provided `DataAppRouter`, `DataAppLink`, and `useDataAppLocation` primitives. Use when the user has an existing data-app project and wants more than one page.
+---
+
+# Add routing to a data-app
+
+A Metabase data-app bundle doesn't bundle a router library — it imports three small primitives from `@metabase/embedding-sdk-react/data-app`:
+
+| API | Purpose |
+|---|---|
+| `<DataAppRouter>` | Wrap the app once. Tracks the current sub-path. Auto-detects the iframe's URL prefix; bundle author writes no basename. |
+| `<DataAppLink to="/customers/42">` | Internal navigation link. Renders a real `<a href>` so middle-click / cmd-click open in a new tab. |
+| `useDataAppLocation()` | Returns `{ pathname, navigate }`. Use `pathname` for match-by-equality / `startsWith` rendering; use `navigate(to)` for programmatic nav. |
+
+That's the entire surface. **No `react-router` of any version, no `<BrowserRouter>`, no `<HashRouter>`.** The API is deliberately decoupled from any router library so a future Metabase version can swap the underlying implementation without touching bundle code.
+
+## When to use this skill
+
+- The user has a working data-app project — scaffolded from the `data-app-template` repo, so a one-liner `vite.config.ts` (`dataAppConfig()`) and an `src/index.tsx` that exports a factory already exist. The dev preview has no in-project entry: the SDK's dev preset serves it.
+- The user wants the bundle to render different content at different URLs (`/overview`, `/customers/:id`).
+- **Do not use this skill** to scaffold a project from scratch — it only patches an existing data-app project. If there is no project yet, stop and tell the user to start with a new data-app scaffold before adding routing.
+
+The template already externalizes `@metabase/embedding-sdk-react/data-app` in `vite.config.ts`. You do NOT need to edit `vite.config.ts` to add routing — just edit `src/App.tsx` (and add more component files as needed) per the step below.
+
+## Step 1 — Wrap `App.tsx` with `<DataAppRouter>`
+
+Import the routing primitives normally. `<DataAppRouter>` does NOT take a `basename` prop — it auto-detects the iframe's URL prefix (`/embed/apps/<name>`) in production and resolves to no prefix in the Vite dev preview.
+
+`App.tsx` is pure content — no `<MetabaseProvider>` here. The SDK's dev preview entry (`DataAppDevProvider`) and the production host (`DataAppProvider`) each wrap the tree in their own realm.
+
+```tsx
+import { StaticQuestion } from "@metabase/embedding-sdk-react";
+import {
+ DataAppRouter,
+ DataAppLink,
+ useDataAppLocation,
+} from "@metabase/embedding-sdk-react/data-app";
+
+function Nav() {
+ return (
+ <nav style={{ padding: 16, borderBottom: "1px solid #e5e7eb" }}>
+ <DataAppLink to="/" style={{ marginRight: 16 }}>Overview</DataAppLink>
+ <DataAppLink to="/customers/42">Customer 42</DataAppLink>
+ </nav>
+ );
+}
+
+function Page() {
+ const { pathname } = useDataAppLocation();
+
+ if (pathname === "/") {
+ return (
+ <div style={{ padding: 24 }}>
+ <h1>Overview</h1>
+ <StaticQuestion questionId={1} height={360} />
+ </div>
+ );
+ }
+
+ const customerMatch = pathname.match(/^\/customers\/(\d+)$/);
+ if (customerMatch) {
+ const id = Number(customerMatch[1]);
+ return (
+ <div style={{ padding: 24 }}>
+ <h1>Customer #{id}</h1>
+ <StaticQuestion questionId={id} height={360} />
+ </div>
+ );
+ }
+
+ return <div style={{ padding: 24 }}>Not found: {pathname}</div>;
+}
+
+export default function App() {
+ return (
+ <DataAppRouter>
+ <Nav />
+ <Page />
+ </DataAppRouter>
+ );
+}
+```
+
+Run `yarn dev`, click the links, watch the URL bar change. Reload at `http://localhost:5174/customers/42` and the dev preview lands on the customer route directly.
+
+## Always preselect the default (leftmost) tab on load
+
+**If the app presents multiple tabs (or any top-level page switcher), the base path `/` MUST render the default — leftmost / first — tab's content, never a blank page, a "Not found", or an empty shell.** This is the single most common mistake: the app boots at `/`, no branch matches, and the user sees nothing until they click a tab. Don't rely on the user (or a later navigation) to select the first tab — the default tab is the initial state.
+
+Two equivalent ways to guarantee it, depending on whether tabs are route-backed:
+
+- **Route-backed tabs** — give `/` an explicit branch that renders the first tab, so an unmatched/base path resolves to it:
+
+ ```tsx
+ const TABS = [
+ { path: "/", label: "Overview", render: () => <Overview /> },
+ { path: "/customers", label: "Customers", render: () => <Customers /> },
+ { path: "/reports", label: "Reports", render: () => <Reports /> },
+ ];
+
+ function Page() {
+ const { pathname } = useDataAppLocation();
+ // Exact-or-prefix match; fall back to the FIRST tab so `/` (and any
+ // unknown sub-path) always shows the default tab, never a blank page.
+ const active =
+ TABS.find((t) => t.path !== "/" && pathname.startsWith(t.path)) ?? TABS[0];
+ return active.render();
+ }
+ ```
+
+- **Local-state tabs (no routing)** — initialize the active-tab state to the first tab, so the very first render shows it:
+
+ ```tsx
+ const [active, setActive] = useState(TABS[0].id); // default = leftmost tab
+ ```
+
+Verify by reloading the app at its base path (`/`) with a fresh load: the leftmost tab's content must be visible immediately, and that tab must read as selected in the tab bar.
+
+## How navigation translates to the parent URL
+
+You don't need to do anything for this. For context:
+
+- Bundle calls `<DataAppLink to="/customers/42">` → host's `navigate` runs `pushState` with `/embed/apps/<name>/customers/42`.
+- The parent's `AppView` observes the iframe URL change and mirrors it to the parent's URL bar as `/apps/<name>/customers/42` — the `/embed` prefix is stripped because the parent's React Router route is `/apps/:name/*`, not `/embed/...`.
+- Reload works because the BE serves the same `data-app.html` for every `/embed/apps/:name/*` sub-path; the iframe boots, `<DataAppRouter>` reads `window.location.pathname`, auto-detects the prefix, and starts at the right sub-path.
+
+## What NOT to do
+
+- **Don't add `react-router-dom`** (or any router library) to the project. The bundle doesn't need it.
+- **Don't use `<BrowserRouter>` or `<HashRouter>`** inside the bundle. They run their own `setState` flow that hits the Near Membrane batching bug.
+- **Don't call `window.history.pushState` directly** from inside the bundle. Use `<DataAppLink>` or `navigate` from `useDataAppLocation`.
+- **Don't try to read or write the parent's URL.** The iframe's sandbox attribute blocks it by design.
+
+## Common patterns
+
+### Conditional render based on path
+
+```tsx
+const { pathname } = useDataAppLocation();
+if (pathname === "/") return <Home />;
+if (pathname.startsWith("/customers/")) return <Customer />;
+return <NotFound />;
+```
+
+### Programmatic navigation (e.g. from a `<button>`)
+
+```tsx
+function OpenCustomerButton({ id }: { id: number }) {
+ const { navigate } = useDataAppLocation();
+ return <button onClick={() => navigate(`/customers/${id}`)}>Open #{id}</button>;
+}
+```
+
+### Parsing path params manually
+
+There's no built-in `useParams`. Match yourself:
+
+```tsx
+const { pathname } = useDataAppLocation();
+const match = pathname.match(/^\/customers\/(\d+)$/);
+if (match) {
+ const id = Number(match[1]);
+ // ...
+}
+```
+
+If you find yourself doing this often, factor it into your own helper inside the bundle:
+
+```tsx
+function useCustomerIdFromPath(): number | null {
+ const { pathname } = useDataAppLocation();
+ const m = pathname.match(/^\/customers\/(\d+)$/);
+ return m ? Number(m[1]) : null;
+}
+```
+
+## Troubleshooting
+
+| Symptom | Fix |
+|---|---|
+| `<DataAppLink>` renders as plain text (no clickable link) on initial load. | The bundle hasn't finished loading and the fallback path is showing. The provider wrap is supplied automatically (the SDK dev preview's `DataAppDevProvider`, or the host's `DataAppProvider`) — don't add `<MetabaseProvider>` inside the app. The fallback resolves to a real link once the bundle is up. |
+| URL changes in dev preview but the production iframe shows the bundle re-render itself on every navigation (or routes don't work in prod at all). | `vite.config.ts` got edited and lost `@metabase/embedding-sdk-react/data-app` from `external` / `output.globals`. Restore from the [template](https://github.com/metabase/data-app-template) — without it, Vite inlines the package's implementation into `dist/index.js`, which runs inside the Near Membrane sandbox and breaks React's state batching. |
+| URL changes but UI doesn't. | A `<BrowserRouter>`/`<HashRouter>` is still in the tree. Strip the router library out and use `<DataAppRouter>` / `<DataAppLink>` instead — the Near Membrane interaction with React-18 batching breaks every router that runs its own `setState` inside the bundle. |
+| Reload at a deep URL in dev (`localhost:5174/customers/42`) shows a blank page. | Vite's dev server is serving the route as a 404 instead of falling back to `index.html`. Set `appType: "spa"` in `vite.config.ts` (it's the default — only an issue if someone overrode it). |
+| Middle-click on a `<DataAppLink>` does nothing. | The link uses `event.button !== 0` to skip non-left clicks; check you haven't wrapped it in another component that swallows the event. |
diff --git a/skills/metabase-data-app-semantic-layer/SKILL.md b/skills/metabase-data-app-semantic-layer/SKILL.md
new file mode 100644
index 00000000000..ce14bae5a43
--- /dev/null
+++ b/skills/metabase-data-app-semantic-layer/SKILL.md
@@ -0,0 +1,687 @@
+---
+name: metabase-data-app-semantic-layer
+description: Use when building, creating, or editing data apps that should query Metabase tables and metrics through generated schema files like metabase.data.ts or *.metabase.data.ts.
+---
+
+# Metabase Data App Semantic Layer
+
+## Core Rules
+
+Keep the semantic layer and presentation layer separate.
+
+- All Metabase context must come from the generated schema file, usually `src/metabase.data.ts` or `src/*.metabase.data.ts`.
+- Do not discover data through MCP tools, create Metabase content, create tables, or edit the semantic layer while building the React UI.
+- Import data app query helpers from `@metabase/embedding-sdk-react/data-app`.
+- Prefer generated schema objects over raw IDs or strings. Extract local constants for top-level table objects.
+- Never hand-write `DatasetQuery`/MBQL objects in app code. Do not pass inline query objects like `{ type: "query", query: { "source-table": table.id } }`, raw `source-table` clauses, raw field IDs, bare table IDs, or metric IDs to SDK components, `useMetabaseQuery`, or `useMetabaseQueryObject`. Prefer generated table and metric schema objects; for simple table-source queries, an explicit source reference like `{ type: "table", id: table.id }` is also valid.
+- Build queries with `source: schema.tables.<name>` or `source: schema.questions.<name>`, generated `fields`, generated `segments`, generated `measures`, generated metrics in `aggregations`, generated metric `dimensions`, `filter(...)`, `breakout(...)`, `orderBy(...)`, and `aggregations` helpers such as `aggregations.count()` and `aggregations.sum(...)`. Do not use `source: schema.metrics.<name>`; metrics are aggregation expressions, not query sources.
+- Prefer semantically rich table queries over shallow table dumps. Use curated table measures, segments, filters, and breakouts when they make the generated app more useful.
+- Prefer semantic-layer definitions over React-side inference. If the schema has a segment or measure for a concept, use it instead of recreating the concept from raw rows.
+- Filter UI must default to showing data. Empty controls, "All" options, and incomplete custom ranges should produce no filter instead of blocking queries or showing a blank dashboard.
+- Do not hardcode categorical filter option values. A generated schema field only proves the field exists, not which values exist; query options from Metabase at runtime using the same generated schema field that the filter applies.
+- Dashboard-level filters should visibly affect every compatible card, table, KPI, and trend. If a filter can only apply to one query, make that scope obvious in the UI; do not show duplicate or no-op date controls.
+- Entity filters, where the stored value is an id/key and the UI shows a label, must use a single searchable combobox. Click/focus must open the option list immediately, before typing. Query options at runtime, search labels, and store the raw value. Never render entity filters as `<select>`; plain selects are only for short closed enums explicitly provided by the user.
+- Do not use native `<input type="date">` for data-app filter bars. Its placeholder and calendar popover are browser-controlled, often show `mm/dd/yyyy`, and cannot be reliably themed. If the repo already has a date picker component or component library, use that. Otherwise install `react-datepicker` for custom date selection.
+- Date bars must include Custom last by default: duration presets, All time, then Custom. Omit Custom only when the user explicitly asks for fixed presets only or no date range control. Date pickers must receive `Date | null`, never `new Date("")` or another invalid date for incomplete ranges; type strict callback parameters explicitly, such as `onChange={(date: Date | null) => ...}`.
+- Never invent aggregation or measure objects such as `{ name: "count" }` or `{ name: "sum", field: ... }`. Use generated table measures or exported aggregation helpers.
+- Only render values returned by Metabase or deterministic transforms of returned values. Do not invent KPI values, trends, labels, statuses, ratings, timestamps, rankings, insights, segments, or chart series.
+- Do not custom-render ambiguous business fields such as `margin`, `rate`, `score`, `percent`, `health`, `risk`, or `efficiency`. Do not add `%`, multiply by 100, color-code, or render stars unless semantic-layer units explicitly support it; use an SDK table/chart, omit the field, or ask for curation.
+- Visualization data must come from Metabase through `useMetabaseQuery` or `useMetabaseQueryObject` with `InteractiveQuestion`/`StaticQuestion`. Do not hardcode chart-ready arrays, sample data, demo values, or schema-shaped mock values.
+- When wrapping an SDK-rendered question in a card or section that already has its own title, pass `title={false}` to the SDK question component to avoid duplicate generated question titles.
+- `useMetabaseQueryObject(...)` returns `{ query, error, isLoading }`. Pass only the `query` property as `card={{ query }}` to `InteractiveQuestion` or `StaticQuestion`; never pass the whole hook result as `card.query`.
+- `useMetabaseQuery().rows` are keyed objects, not tuple arrays. Never read `row[0]` / `row[1]`, and never silence this with `as unknown as [string, number][]`, `DisplayRow`, or another tuple cast. If TypeScript says property `0` does not exist, it is catching a real bug. For typed `data.rows`, use literal keys such as `row.count` or generated field names such as `row[ordersTable.fields.createdAt.name]`. Use `data.columns` with `rawRows` or after explicitly narrowing a key; do not index typed rows with arbitrary `string` values from `data.columns`.
+- Do not cast query objects to `Parameters<typeof useMetabaseQuery>[0]`. That erases the generated table/metric validation. Use `useMetabaseQuery<typeof table>(...)`, or type a reusable query object with `satisfies MetabaseQueryOptions<typeof table>`.
+- Do not build shared filter arrays with `ReturnType<typeof filter>[]` or `push(...)`; this can collapse overload inference. Pass raw filter state between components and build each query's `filters: [...]` inline with spreads.
+- Do not include `fields` in queries with `aggregations` and `breakouts`; breakouts determine grouped result columns. Use `fields` only for row-selection queries.
+- Before rendering a field, verify it exists in the generated schema object and is returned by the query. Do not guess table keys, field keys, or column names from the Metabase API, business intuition, or old mock data; only use entries actually emitted in `src/metabase.data.ts`.
+- Avoid unsupported freshness or operational claims such as "real-time", "live", "understaffed", or "risk" unless the returned data or curated semantic-layer definition supports them.
+- Before claiming the work is done or preparing a final handoff, run a TypeScript type-only check and report the command/result. If the check fails, fix the type errors before any final summary.
+
+## Generate Schema
+
+If the schema file already exists, use it. If it is missing or stale, treat schema generation as semantic-layer curation for this data app, not a mechanical export.
+
+Before generating, make sure the user has explicitly chosen the library scope the app needs:
+
+- `include-data-library=true` for the whole `Library / Data` tree.
+- `include-metric-library=true` for the whole `Library / metrics` tree.
+- `library-collections=<id-or-entity-id>[,<id-or-entity-id>]` for specific Data or metrics library subcollections.
+- `question-collections=<id-or-entity-id>[,<id-or-entity-id>]` for specific normal collections that contain saved questions.
+- `include-models=true` for readable models that have actions. When combined with `database=<name-or-id>`, it includes models with actions for that database only.
+- `database=<name-or-id>` when the app should use tables from one database.
+
+Use `question-collections` when the app needs `schema.questions.*` to be generated. Use `include-models=true` when the app needs any saved action under `schema.models.<model>.actions`; models without executable actions are omitted to keep generated schemas compact. It can be combined with `library-collections`, `include-data-library`, `include-metric-library`, or `question-collections` so one schema can include selected tables/metrics/questions plus all relevant actions.
+
+If the user asks for any mutation-like flow, such as creating, updating, deleting, submitting, approving, executing an action, or running a write operation, include `include-models=true` in the typed-schema URL. Do this even when the user names one specific model/action, because actions are only discoverable through generated model entries.
+
+If the user did not already choose a library scope, stop and ask what they want. Warn before exporting the whole instance: including everything is noisy, bloats context, and makes agents more likely to pick irrelevant entities.
+
+The Metabase URL and API key live in the **repo-root** `.env.local` as
+`DATA_APP_MB_URL` and `DATA_APP_MB_API_KEY` (one file per repo, usually two levels up
+from the app dir, not in the app dir). The command below `source`s that file so
+the shell substitutes the values straight into `curl` — you never read, extract,
+or handle the credentials yourself.
+
+> **Never ask the user to paste the API key into the chat, and never `cat` /
+> `echo` `.env.local`** — it's git-ignored and may hold other secrets, so its
+> contents must stay out of the conversation. `source` it so the shell uses the
+> values without exposing them. If `$DATA_APP_MB_API_KEY` or `$DATA_APP_MB_URL` is empty
+> or still set to the default `mb_replace_me` placeholder after sourcing, ask
+> the user to add real values themselves, then continue.
+
+Source the credentials from the repo-root `.env.local` and generate the scoped
+schema:
+
+```bash
+ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"
+if [ -z "$ROOT" ]; then
+ echo "Not inside the connected git repo — cd into it first." >&2
+ exit 1
+fi
+
+(
+ source "$ROOT/.env.local" 2>/dev/null
+ # Fail early (before curl) if either var is missing or placeholder-only.
+ if [ -z "$DATA_APP_MB_URL" ] || [ "$DATA_APP_MB_URL" = "mb_replace_me" ] ||
+ [ -z "$DATA_APP_MB_API_KEY" ] || [ "$DATA_APP_MB_API_KEY" = "mb_replace_me" ]; then
+ echo "Set real DATA_APP_MB_URL / DATA_APP_MB_API_KEY in repo-root .env.local" >&2
+ exit 1
+ fi
+ curl \
+ -o src/metabase.data.ts \
+ -H "x-api-key: $DATA_APP_MB_API_KEY" \
+ -H "Accept: text/typescript" \
+ "$DATA_APP_MB_URL/api/typed-schemas/v1/typescript?include-data-library=true&include-metric-library=true"
+)
+```
+
+When the app needs saved questions, include `question-collections=<id-or-entity-id>[,<id-or-entity-id>]` in the typed-schema URL. When the app needs models or actions, include `include-models=true`.
+
+If schema generation fails while building a selected saved question, model, or model action, do not hide, paraphrase away, or retry past the error. Surface the typed-schema error to the user, including the failing `card-id` / `card-name` / `card-type`, `model-id` / `model-name`, dropped action ids, and message when present. This usually means a selected model/question/action was readable enough to select, but its details could not be built, often because its source table, source card, or action details are not published, accessible, valid, or resolvable in the fetch context. The schema would otherwise omit the entire `schema.models.<model>` or `schema.questions.<question>` entry, or return a model whose `actions` map silently omits an action, so the user needs to curate or publish the missing dependency before regenerating.
+
+## Standard pattern
+
+```ts
+import {
+ aggregations,
+ breakout,
+ filter,
+ orderBy,
+ useMetabaseQuery,
+ useMetabaseQueryObject,
+} from "@metabase/embedding-sdk-react/data-app";
+import schema from "../metabase.data";
+
+const ordersTable = schema.tables.orders;
+
+const { data, isLoading, error } = useMetabaseQuery({
+ source: ordersTable,
+ filters: [
+ ordersTable.segments.completed,
+ filter(ordersTable.fields.status, "=", "paid"),
+ ],
+ aggregations: [aggregations.sum(ordersTable.fields.amount)],
+ breakouts: [breakout(ordersTable.fields.createdAt, { unit: "month" })],
+ orderBys: [orderBy(ordersTable.fields.createdAt, "desc", { unit: "month" })],
+ limit: 100,
+});
+```
+
+For direct row access, prefer letting `useMetabaseQuery(...)` infer the query shape from the inline query object. If you need a reusable query object and table ownership checks, type the object with `satisfies MetabaseQueryOptions<OrdersTable>`, then pass it to `useMetabaseQuery(query)`. Avoid forcing the hook generic on selected-field queries when you need precise row keys from `data.rows`.
+
+Use keyed schema objects:
+
+- Tables: `source: schema.tables.<table>`
+- metrics: `schema.metrics.<metric>` inside `aggregations`
+- Saved questions: `source: schema.questions.<question>`
+- Fields: `schema.tables.<table>.fields.<field>`
+- Segments: `schema.tables.<table>.segments.<segment>`
+- Measures: `schema.tables.<table>.measures.<measure>`
+- metric dimensions: `schema.metrics.<metric>.dimensions.<group>.<dimension>`
+
+Do not pass raw dimension strings like `"created_at"` or `"segment"`.
+
+## Table query recipes
+
+For a table query, pass the generated table object as `source`:
+
+```ts
+const recordsTable = schema.tables.records;
+
+const { data } = useMetabaseQuery({
+ source: recordsTable,
+ fields: [recordsTable.fields.id, recordsTable.fields.status],
+});
+```
+
+For grouped table summaries, include at least one aggregation:
+
+```ts
+useMetabaseQuery({
+ source: recordsTable,
+ filters: [
+ recordsTable.segments.activeRecords,
+ filter(recordsTable.fields.amount, ">", 100),
+ ],
+ aggregations: [recordsTable.measures.totalAmount],
+ breakouts: [breakout(recordsTable.fields.createdAt, { unit: "month" })],
+ orderBys: [orderBy(recordsTable.fields.createdAt, "desc", { unit: "month" })],
+});
+```
+
+For basic aggregations without a curated measure, use the `aggregations` helpers:
+
+```ts
+useMetabaseQuery({
+ source: recordsTable,
+ aggregations: [
+ aggregations.count(),
+ aggregations.sum(recordsTable.fields.amount),
+ ],
+ breakouts: [breakout(recordsTable.fields.category)],
+});
+```
+
+When using the same helper more than once, Metabase may return numbered runtime keys such as `sum`, `sum_2`, and `sum_3`. TypeScript only models the base helper key today. For custom KPI code that intentionally uses repeated same-kind aggregations, read through `data.columns` or cast the row to `Record<string, unknown>` before accessing numbered keys. Prefer curated measures or separate queries when that is clearer.
+
+Table fields, segments, measures, filters, breakouts, and orderBys must come from the queried table. For reusable query objects, use `satisfies MetabaseQueryOptions<RecordsTable>` so TypeScript can validate the query while preserving precise row keys.
+
+## metric aggregation recipes
+
+For a metric-backed query, pass the generated table object as `source` and the generated metric object in `aggregations`:
+
+```ts
+const ordersTable = schema.tables.orders;
+const revenueMetric = schema.metrics.revenue;
+
+const { data } = useMetabaseQuery({
+ source: ordersTable,
+ aggregations: [revenueMetric],
+});
+```
+
+Use generated metric dimensions for filters and breakouts in queries that aggregate the owning metric. Dimensions from the metric's source table work directly. Dimensions from related tables also work when the generated field includes `sourceFieldId`; prefer those related-table dimensions for readable labels instead of grouping by raw foreign key IDs:
+
+```ts
+useMetabaseQuery({
+ source: ordersTable,
+ aggregations: [revenueMetric],
+ filters: [filter(revenueMetric.dimensions.orders.status, "=", "paid")],
+ breakouts: [
+ breakout(revenueMetric.dimensions.orders.createdAt, { unit: "month" }),
+ breakout(revenueMetric.dimensions.franchises.name),
+ ],
+ orderBys: [
+ orderBy(revenueMetric.dimensions.orders.createdAt, "desc", {
+ unit: "month",
+ }),
+ ],
+});
+
+// Prefer readable related-table dimensions when available.
+breakout(revenueMetric.dimensions.franchises.name);
+
+// Avoid raw FK IDs when the related-table dimension exists.
+breakout(revenueMetric.dimensions.orders.franchiseId);
+```
+
+Queries backed by metrics can include helper aggregations over generated metric dimensions. They can also use compatible saved Segments and Measures from the table source when the generated schema exposes them:
+
+```ts
+useMetabaseQuery({
+ source: ordersTable,
+ filters: [schema.tables.orders.segments.completed],
+ aggregations: [
+ revenueMetric,
+ schema.tables.orders.measures.totalRevenue,
+ aggregations.sum(revenueMetric.dimensions.orders.amount),
+ ],
+ breakouts: [breakout(revenueMetric.dimensions.orders.status)],
+});
+```
+
+A metric aggregation must belong to the table source. Do not use source-card metrics in table-source queries. Generated metric dimensions are scoped to their owning metric: if a query uses `revenueMetric.dimensions.*` in filters, helper aggregations, breakouts, or orderBys, it must also include `revenueMetric` in `aggregations`. Do not use metric dimensions as standalone table fields for unrelated `count()` or table-measure queries. Generated metric dimensions must also resolve to the table source. For reusable query objects, use `satisfies MetabaseQueryOptions<typeof ordersTable>` so TypeScript can validate the query while preserving precise row keys.
+
+## Saved question query recipes
+
+For a saved question query, pass the generated question object as `source`:
+
+```ts
+const ordersQuestion = schema.questions.ordersQuestion;
+
+const { data } = useMetabaseQuery({
+ source: ordersQuestion,
+});
+```
+
+Saved question queries only support `source` and `enabled` today. Do not add `fields`, `filters`, helper aggregations, breakouts, orderBys, or limits to `source: schema.questions.<question>` queries yet; use table-source queries, including metric aggregations, when the app needs post-source query clauses.
+
+SQL parameters stay on the existing `questionId` query path. Do not pass SQL parameter values through `source: schema.questions.<question>`.
+
+## SDK-rendered views
+
+Table fields, segments, measure aggregations, and metric aggregations must come from the queried table. Generated metric dimensions used in filters, helper aggregations, breakouts, and orderBys must resolve to the queried table and belong to a metric included in the same query's `aggregations`.
+When table queries use `fields`, `segments`, `aggregations`, `breakouts`, or `orderBys`, prefer inline inference or a reusable query object with `satisfies MetabaseQueryOptions<typeof recordsTable>` so TypeScript can validate the query without losing precise result-row keys.
+
+## Interactive Metabase Views
+
+Use Metabase's SDK `InteractiveQuestion` or `StaticQuestion` by default when the UI can be expressed as a normal Metabase question visualization. Build a semantic query with `useMetabaseQueryObject`, then pass it through the SDK question component's `card` prop.
+
+`useMetabaseQueryObject` supports generated table queries, including metric aggregations. Use `useMetabaseQuery` when custom React needs direct row data; use `useMetabaseQueryObject` when Metabase should render or manage the visualization. Do not pass generics to `useMetabaseQueryObject`; it returns `{ query, error, isLoading }`, not query result rows.
+
+The examples below use `return null` for minimal loading and error handling. In a real app, render the app's existing loading or error UI there. Passing `card={{ query }}` is safe while `query` is `null`; do not pass the full `{ query, error, isLoading }` hook result as `card.query`.
+
+When wrapping `useMetabaseQueryObject` in a reusable chart/card component, destructure and render `error`; do not read only `{ query }`, because query-construction failures otherwise look like endless loading. Calling the hook inside that child component is valid React. Do not call hooks directly inside loops, conditions, or callbacks in the parent component.
+
+Wrong/right pattern:
+
+```tsx
+const trendQuery = useMetabaseQueryObject(querySpec);
+<InteractiveQuestion card={{ query: trendQuery }} />; // wrong
+
+const { query: trendQuery } = useMetabaseQueryObject(querySpec);
+<InteractiveQuestion card={{ query: trendQuery }} />; // right
+```
+
+Hook typing:
+
+- `useMetabaseQuery(...)` infers typed row data from the generated `source` and query object. For reusable query objects, use `satisfies MetabaseQueryOptions<...>` on the object instead of forcing the hook generic.
+- `useMetabaseQueryObject(...)` accepts no generic and returns `{ query, error, isLoading }`. Pass the `query` property to `card={{ query }}`.
+- Do not use `as Parameters<typeof useMetabaseQuery>[0]` to quiet query typing errors. It hides invalid table fields, metric aggregations, and breakouts. Prefer `useMetabaseQuery<typeof table>(query)` or `const query = { ... } satisfies MetabaseQueryOptions<typeof table>`.
+
+The basic prop contract is:
+
+- Generated table query, including metric aggregations: `<StaticQuestion card={{ query }} />`
+- Full interactive question: `<InteractiveQuestion card={{ query }} />`
+
+When you need the set of SDK-supported question displays, do not copy a local list. In generated apps, search `node_modules/@metabase/embedding-sdk-react/dist/index.d.ts` for the exact declaration `declare const cardDisplayTypes: readonly [...]` and use that tuple as the source of truth. Do not read the whole declaration file into context.
+
+Always pass SDK-rendered ad hoc questions with a `card` object. Start with `card={{ query }}` when the user has not asked for a specific chart type and Metabase defaults can infer a reasonable display from the query. Use `card={{ query, visualization }}` when the user request or design calls for a specific chart type, such as a pie chart for a distribution, but does not ask for setting-level customization. Add `visualizationSettings` only when the user explicitly asks for a setting-level presentation change, such as hiding or renaming an axis label, showing value labels, stacking bars, adding a goal line, ordering table columns, showing pie totals/labels, or controlling series/slice order. Search `node_modules/@metabase/embedding-sdk-react/dist/index.d.ts` for `export declare type MetabaseCard`, the relevant `*VisualizationSettings` type, and any setting key you plan to use. Read the JSDoc comments attached to those declarations, then use the TypeScript declarations as the source of truth for legal `visualization` and `visualizationSettings` combinations. Build the query with `useMetabaseQueryObject`; do not call internal query resolution helpers, cast through `any`, or hardcode settings from memory.
+
+For lightweight descriptions of the exposed settings and when to use them, read [references/visualization-settings.md](references/visualization-settings.md). Treat that file as guidance only; the installed SDK declaration decides what is legal.
+
+Before writing a `card`, check `node_modules/@metabase/embedding-sdk-react/dist/data-app.d.ts` for the `useMetabaseQueryObject` return type. Destructure the returned `query` and use that value in `card.query`; for configured cards, type the object with `satisfies MetabaseCard`. If TypeScript reports duplicate opaque `DatasetQuery` symbols, do not force a cast; update the SDK package before using `card`.
+
+Do not invent alternate prop names for generated queries or visualization settings. If the SDK type says a prop does not exist, believe it and use the documented `card` prop shape.
+
+When `useMetabaseQuery` is needed, map typed rows into an explicit local view model using named properties before rendering:
+
+```ts
+const orderedAtKey = ordersTable.fields.orderedAt.name;
+
+const chartRows = (data?.rows ?? []).map((row) => ({
+ label: String(row[orderedAtKey] ?? "Unknown"),
+ value: row.count,
+}));
+```
+
+### SDK Chart Heights
+
+When an SDK-rendered chart lives in a card, panel, dashboard cell, or any other area that needs a specific height, pass that height to the SDK component that owns the visualization. Setting only the outer container or card height is not enough — the chart can render taller than the card and get cut off.
+
+- Chart only: pass `height` to `InteractiveQuestion.QuestionVisualization`.
+- Default question layout with query bar: pass `height` to `InteractiveQuestion`.
+- Static question: pass `height` to `StaticQuestion`.
+
+Use the actual body height available to the chart. For example, if a card is 560px tall and has a 60px header, pass `height="500px"` to the SDK component.
+
+Prefer `InteractiveQuestion` for:
+
+- standard charts, pivot tables, maps, object/list views, scalar/KPI values, and exploratory views
+- trends, category comparisons, grouped summaries, geographic views, scatter plots, funnels, gauges, progress, waterfall, boxplot, and sankey-shaped queries
+- bar, line, area, row, and trend charts whenever a semantic query with measures and breakouts can produce the needed result
+- tables where users benefit from Metabase interactions such as sorting, column inspection, drill-through, downloading, or changing visualization settings
+- cases where Metabase visualization settings can handle the presentation, such as axes, labels, stacking, goals, trendlines, split panels, series settings, table columns, formatting, pie settings, pivot settings, and list settings
+
+Generated dashboards should use Metabase charts as much as possible. Do not replace a normal bar, line, area, row, trend, pivot, map, or sortable table with a custom SVG/React visualization just to make it look more bespoke.
+
+Use custom React visualizations only when the user's requested presentation does not fit Metabase display types or visualization settings.
+
+Good custom visualization reasons:
+
+- bespoke scorecards, alert panels, narrative layouts, or mixed-content cards that cannot be represented as a normal Metabase chart/table
+- combining multiple Metabase queries into one visual unit
+- custom interactions or product-specific UI that Metabase's chart/table chrome cannot express
+- unusual chart forms such as calendar grids, timelines, heat strips, radial views, custom maps, or domain-specific diagrams
+
+For custom charts, use an existing charting dependency when the app already has one. Otherwise, SVG charts are fine. Keep single-value KPI cards and bespoke summaries on `useMetabaseQuery` when you need direct row data, but first consider whether an SDK scalar/smartscalar/gauge/progress view would be good enough.
+
+If you build a custom chart, map typed SDK rows into an explicit local view model before rendering. Read typed row values with known result keys, such as `schema.tables.orders.fields.orderedAt.name` (`ordered_at`) or aggregation names like `count`/`sum`; do not read generated schema object property names such as `row.orderedAt` unless the returned column name is actually `orderedAt`. If the key only comes from `data.columns` at runtime, use `rawRows` with the matching column position or narrow the key to a literal before indexing `data.rows`. Do not write generic chart components that assume positional rows.
+
+Chart only, without the toolbar:
+
+```tsx
+import {
+ InteractiveQuestion,
+ StaticQuestion,
+ type MetabaseCard,
+} from "@metabase/embedding-sdk-react";
+
+import {
+ aggregations,
+ breakout,
+ useMetabaseQueryObject,
+} from "@metabase/embedding-sdk-react/data-app";
+
+const eventsTable = schema.tables.events;
+
+const { query, isLoading, error } = useMetabaseQueryObject({
+ source: eventsTable,
+ aggregations: [aggregations.sum(eventsTable.fields.amount)],
+ breakouts: [breakout(eventsTable.fields.occurredAt, { unit: "month" })],
+});
+
+if (error) {
+ return null;
+}
+
+if (isLoading || !query) {
+ return null;
+}
+
+return (
+ <InteractiveQuestion card={{ query }}>
+ <InteractiveQuestion.QuestionVisualization height="500px" />
+ </InteractiveQuestion>
+);
+```
+
+Configured SDK visualization:
+
+```tsx
+const { query, isLoading, error } = useMetabaseQueryObject({
+ source: eventsTable,
+ aggregations: [eventsTable.measures.totalAmount],
+ breakouts: [breakout(eventsTable.fields.occurredAt, { unit: "month" })],
+});
+
+if (error) {
+ return null;
+}
+
+if (isLoading || !query) {
+ return null;
+}
+
+const trendCard = {
+ query,
+ visualization: "bar",
+ visualizationSettings: {
+ "graph.show_values": true,
+ "graph.y_axis.title_text": "Total amount",
+ },
+} satisfies MetabaseCard;
+
+return (
+ <InteractiveQuestion card={trendCard}>
+ <InteractiveQuestion.QuestionVisualization height="500px" />
+ </InteractiveQuestion>
+);
+```
+
+Do not invent alternate prop names for generated queries. If the SDK type says a prop does not exist, believe it and use the documented `card` prop shape.
+
+```tsx
+const { query, isLoading, error } = useMetabaseQueryObject({
+ source: eventsTable,
+ aggregations: [eventsTable.measures.totalAmount],
+ breakouts: [breakout(eventsTable.fields.occurredAt, { unit: "month" })],
+});
+
+if (error) {
+ return null;
+}
+
+if (isLoading || !query) {
+ return null;
+}
+
+return <InteractiveQuestion card={{ query }} height="500px" />;
+```
+
+Static question:
+
+```tsx
+const { query, isLoading, error } = useMetabaseQueryObject({
+ source: eventsTable,
+ aggregations: [eventsTable.measures.totalAmount],
+ breakouts: [breakout(eventsTable.fields.occurredAt, { unit: "month" })],
+});
+
+if (error) {
+ return null;
+}
+
+if (isLoading || !query) {
+ return null;
+}
+
+return <StaticQuestion card={{ query }} height="500px" />;
+```
+
+Do not wrap `InteractiveQuestion` or `StaticQuestion` in containers that clip or move on hover. Avoid `overflow: hidden`, hover transforms, and hover-driven layout shifts around embedded Metabase UI; popovers, menus, and chart tooltips need stable geometry and visible overflow. If a parent card has a fixed height, also pass the matching available height to `InteractiveQuestion`, `StaticQuestion`, or `InteractiveQuestion.QuestionVisualization`; never rely on the parent height alone.
+
+## Filters And Breakouts
+
+Use helpers because they give better autocomplete and shorter errors.
+
+```ts
+filter(ordersTable.fields.quantity, ">", 0);
+filter(ordersTable.fields.status, "contains", "paid");
+filter(ordersTable.fields.quantity, "between", [10, 20]);
+filter(ordersTable.fields.status, "not-empty");
+
+breakout(ordersTable.fields.createdAt, { unit: "month" });
+breakout(ordersTable.fields.amount, {
+ binning: { strategy: "num-bins", "num-bins": 10 },
+});
+breakout(ordersTable.fields.state);
+
+orderBy(ordersTable.fields.createdAt, "desc", { unit: "month" });
+```
+
+Do not hand-write `orderBys` object literals such as `{ field, direction }` or `{ fieldId, direction }`; use `orderBy(...)`. When ordering the same date field used by a date breakout, pass the same `unit` to both `breakout(...)` and `orderBy(...)`.
+
+For top-N grouped summaries, order by the aggregation result, not the raw source field. Store the aggregation helper in a local constant and pass that same constant to both `aggregations` and `orderBy(...)`:
+
+```ts
+const avgQuantity = aggregations.avg(inventoryTable.fields.quantityOnHand);
+
+const { query, error, isLoading } = useMetabaseQueryObject({
+ source: inventoryTable,
+ aggregations: [avgQuantity],
+ breakouts: [breakout(inventoryTable.fields.ingredient)],
+ orderBys: [orderBy(avgQuantity, "desc")],
+ limit: 15,
+});
+```
+
+For user-selectable sorting, build a typed map of allowed generated fields instead of indexing the whole `fields` object:
+
+```ts
+import type { MetabaseQueryOptions } from "@metabase/embedding-sdk-react/data-app";
+
+type SortKey = "revenue" | "orders";
+type ScorecardTable = typeof scorecardTable;
+
+type ScorecardField =
+ ScorecardTable["fields"][keyof ScorecardTable["fields"]];
+
+const sortFields = {
+ revenue: scorecardTable.fields.netRevenue,
+ orders: scorecardTable.fields.orders,
+} satisfies Record<SortKey, ScorecardField>;
+
+const query = {
+ source: scorecardTable,
+ orderBys: [orderBy(sortFields[sortKey], "desc")],
+} satisfies MetabaseQueryOptions<ScorecardTable>;
+```
+
+For metric queries, pass generated metric dimensions to `filter(...)` and `breakout(...)`:
+
+```ts
+filter(revenueMetric.dimensions.orders.status, "=", "paid");
+breakout(revenueMetric.dimensions.orders.createdAt, { unit: "month" });
+```
+
+Filter operator rules:
+
+- string: `=`, `!=`, `contains`, `does-not-contain`, `starts-with`, `ends-with`, `is-empty`, `not-empty`, `is-null`, `not-null`
+- number: `=`, `!=`, `>`, `>=`, `<`, `<=`, `between`, `is-null`, `not-null`
+- date: `=`, `!=`, `>`, `>=`, `<`, `<=`, `between`, `time-interval`, `is-null`, `not-null`
+- boolean: `=`, `is-null`, `not-null`
+
+Only date dimensions can use `unit`. Non-date dimensions can be used as breakouts without `unit`; numeric dimensions can use `binning`.
+
+Segments are already filters:
+
+```ts
+filters: [
+ schema.tables.records.segments.activeRecords,
+ filter(schema.tables.records.fields.amount, ">", 100),
+];
+```
+
+Use curated segments first when they exactly match the product intent. Use `filter(...)` when the UI needs a threshold, category, date range, text match, boolean condition, or other narrowing that is not already represented by a curated segment.
+
+## Filter UI Patterns
+
+When the user asks for custom filters, build normal React controls that feed semantic query filters.
+
+Before implementing filters, create a filter contract for the visible dashboard. At minimum, identify:
+
+- For each filter, name the runtime query that provides its options.
+- For each filter, name the raw value used in `filter(...)`.
+- For each card, table, KPI, and trend, name the generated table field or metric dimension that can receive that filter.
+- If a filter only applies to one section, keep it section-scoped or omit it from the global filter bar.
+- If a page needs a different date field such as `snapshotDate`, use one visible date control for that page.
+- KPI/detail pairs that describe the same concept should use the same relevant filters.
+
+Use the detailed checklist in `references/filter-ui-patterns.md` for filter state rules, runtime categorical options, stale option reset, searchable controls, and custom date-picker implementation.
+
+For the common memoized date/category filter shape:
+
+```tsx
+type DatePreset = "30d" | "90d" | "custom" | "all";
+
+const [datePreset, setDatePreset] = useState<DatePreset>("all");
+const [customStart, setCustomStart] = useState<Date | null>(null);
+const [customEnd, setCustomEnd] = useState<Date | null>(null);
+const [status, setStatus] = useState("all");
+
+const toLocalDateString = (date: Date) =>
+ `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
+
+const dateRange = useMemo((): readonly [string, string] | null => {
+ if (datePreset === "all") {
+ return null;
+ }
+
+ if (datePreset === "custom") {
+ return customStart && customEnd
+ ? [toLocalDateString(customStart), toLocalDateString(customEnd)]
+ : null;
+ }
+
+ return getPresetDateRange(datePreset);
+}, [datePreset, customStart, customEnd]);
+
+const orderFilters = useMemo(
+ () => [
+ ...(dateRange
+ ? [filter(ordersTable.fields.createdAt, "between", dateRange)]
+ : []),
+ ...(status === "all"
+ ? []
+ : [filter(ordersTable.fields.status, "=", status)]),
+ ],
+ [dateRange, status],
+);
+```
+
+When date picker state uses `Date | null`, convert selected dates with a local `YYYY-MM-DD` formatter before passing them to `filter(..., "between", range)`. Do not use `date.toISOString().split("T")[0]` for local date filters.
+
+## Result Shape And Charts
+
+- Prefer keyed `data.rows`.
+- Never treat `data.rows` as positional arrays. Do not use `row[0]`, `row[1]`, `DisplayRow`, or tuple casts for `useMetabaseQuery` row objects.
+- Inspect `data.columns` before mapping low-level `rawRows`, but do not use arbitrary `data.columns[].name` strings to index typed `data.rows`.
+- Runtime row objects are keyed by returned Metabase column names, usually `column.name` such as `total_amount` or `average_score`. Do not assume generated schema keys like `totalAmount` or `averageScore` are runtime row keys.
+- For generated field references, the React property path and runtime result key can differ: `schema.tables.orders.fields.orderedAt.name` might be `ordered_at`. Use `row[ordersTable.fields.orderedAt.name]`, `row.count`, or `data.columns` metadata instead of guessing `row.orderedAt`.
+- Treat row values as nullable. Guard before calling number/string methods such as `toFixed`, `toLocaleString`, or string transforms.
+- Use `rawRows` only for known positional shapes.
+- Aggregation columns may be named `count`, `sum`, or `avg`; match metadata when needed.
+- If a custom visualization needs several helper aggregations with the same output name, such as multiple `aggregations.sum(...)` calls, prefer separate single-aggregation queries so each typed row has the known `sum` key. If one multi-aggregation query is necessary, read `rawRows` by column position after checking `data.columns`; do not depend on generated names like `sum_2` unless they are explicitly typed or narrowed in the app code.
+- Grouped queries can include a `null` breakout bucket. Render it as `"Unknown"` or filter it out deliberately.
+- Time-series charts need multiple ordered buckets. Do not fake sparklines for scalar or one-point results.
+- Multi-series charts with different units or magnitudes need separate axes or normalization.
+- Format user-facing values: currency to at most 2 decimals, counts as whole numbers, dates as readable labels.
+- Do not render ambiguous derived business values unless the semantic layer description or inspected sample values make the meaning and units obvious.
+- Empty results are distinct from loading. After `isLoading` is false, render a clear empty state instead of leaving a skeleton or blank KPI.
+
+## Presentation Guidance
+
+Prefer Metabase-rendered panels for chart-shaped and table-shaped data. The React app may group, sort, format, and derive display-only values from `data.rows` when a custom panel is justified, but do not make custom panels the default.
+
+Good transforms:
+
+- Group rows for summaries.
+- Sort and slice rows for ranked lists only when a custom list is clearly better than a Metabase row/bar/table visualization.
+- Pick chart types from actual data shape, and prefer Metabase `bar`, `line`, `area`, `row`, `combo`, `pivot`, and `table` displays before writing custom chart code.
+- Show loading, error, and empty states.
+- Bound dense result displays. Tables, alert lists, logs, and ranked lists should use a top-N slice, grouping, pagination, or a fixed/max-height scroll area so a large result set cannot stretch the entire page.
+
+When a page feels like a raw table browser, look for schema-backed ways to enrich it:
+
+- Use segments for curated subsets like active, completed, overdue, high-priority, or needs-attention records.
+- Use measures for curated aggregations instead of recalculating everything ad hoc in React.
+- Use metrics when the schema exposes a curated metric aggregation for the page's core business question.
+- Use filters to focus the query on the UI's intent.
+- Use breakouts to create trends, category comparisons, and grouped summaries.
+- If the enriched result is still a sortable/drillable table, render it with SDK visualization components instead of rebuilding table behavior in React.
+
+Avoid manual classification when the semantic layer already has the concept. Prefer curated segments, fields, or measures over string matching, threshold heuristics, or category reconstruction in React.
+
+If no curated schema entry supports the intended UI, leave the section out or ask for semantic-layer curation. Do not keep mock data or placeholder analytics in the finished app.
+
+## Final Checks
+
+- Run `npm run typecheck`.
+- Keep TypeScript diagnostics compact in the chat or handoff. Use the full output locally to fix the app, but report grouped root causes and only a few representative diagnostics instead of pasting the entire `tsc` output.
+- Verify every rendered value can be traced to a returned row property, schema field, measure, or deterministic transform.
+- Search touched files for `row[0]`, `row[1]`, `row.orderedAt`, `row.orderDate`, `as unknown as`, `DisplayRow`, `<select`, `margin`, `rate`, `score`, `percent`, `%`, `* 100`, and `.toFixed`; fix positional rows, result-key guesses, entity `<select>` filters, and unsupported business-field interpretations.
+- Verify every date preset bar includes Custom last unless explicitly omitted, every visible date filter affects the current page, and no page shows duplicate date filters for one scope.
+- Verify `data_app.yaml` points at the built bundle path and that the bundle path is tracked by git.
+- For every visible filter, verify "All" maps to no filter, selected values come from runtime query results, and each non-All option changes every card it claims to affect.
+
+## Common Mistakes
+
+- Creating or searching for Metabase content during app building.
+- Importing older hooks instead of `useMetabaseQuery`.
+- Copying raw numeric IDs into constants instead of using generated schema objects.
+- Inventing ad hoc measure objects such as `{ name: "count" }` or `{ name: "sum", field: fieldId }`.
+- Passing raw strings for table fields.
+- Adding lookup helpers instead of using keyed generated schema objects.
+- Inventing SDK component prop names instead of using `query` for generated table queries.
+- Mixing fields, segments, or measures from unrelated tables.
+- Adding a filter UI that sends empty values instead of omitting the filter.
+- Hardcoding categorical filter values instead of querying the runtime values from Metabase.
+- Displaying entity names but filtering by those names when a stable ID is available.
+- Applying a dashboard-level filter to only one KPI while related charts and tables ignore it.
+- Showing a global Date Range plus a page-specific Snapshot Date where one date filter has no effect.
+- Letting a KPI and its detail table use different date or category filters without explaining the difference.
+- Rendering `Margin`/`Rate`/`Score`/`Health` with invented `%`, stars, colors, or thresholds.
+- Shipping a date preset bar with no Custom range option, or Custom before All time.
+- Charting opaque IDs such as `franchise_id` when a user-facing name is available.
+- Rendering an entity filter in a plain `<select>`, even if the current runtime option list is short.
+- Using native `<input type="date">` and shipping browser-controlled `mm/dd/yyyy` placeholders or unthemed calendar popovers.
+- Assuming `filter(...)` fully validates value types.
+- Letting a `null` bucket become the latest time-series point.
+- Hardcoding business values, labels, timestamps, or rankings.
+- Creating chart-ready arrays by hand instead of deriving them from queried `data.rows`.
+- Casting typed SDK rows to generic tuple rows such as `[string, number]`.
+- Reading generated object property names such as `row.orderedAt` when Metabase returns column names such as `ordered_at`.
+- Rendering fields that are not present in the schema or returned query result.
+- Rendering `No data` while the SDK is still authenticating or loading.
+- Creating nested `MetabaseProvider` instances instead of sharing one provider at the app boundary.
diff --git a/skills/metabase-data-app-semantic-layer/references/filter-ui-patterns.md b/skills/metabase-data-app-semantic-layer/references/filter-ui-patterns.md
new file mode 100644
index 00000000000..a8551596ec1
--- /dev/null
+++ b/skills/metabase-data-app-semantic-layer/references/filter-ui-patterns.md
@@ -0,0 +1,148 @@
+# Filter UI Checklist
+
+Use these patterns when building custom filter bars for data apps.
+
+## Filter Contract
+
+Before writing controls, map each filter to the dashboard. Keep this contract small and concrete:
+
+| Filter | Runtime options query | Raw value | Applies to | Unsupported sections |
+| --------- | ----------------------------- | ------------ | --------------------------------- | -------------------- |
+| Franchise | breakout on franchise id/name | franchise id | orders, revenue Metric, inventory | none |
+| Plan | breakout on plan | plan text | orders | revenue, inventory |
+
+If a filter has unsupported sections, either make it section-scoped or do not render it as a global dashboard filter. Do not show duplicate date controls for the same page unless both visibly affect different labeled sections.
+
+For every rendered card or table, build filters from that query source's generated table fields or compatible Metric dimensions. Do not reuse a filter array built for a different table.
+
+Before rendering a filter, answer:
+
+- What query provides runtime options?
+- What raw value is stored?
+- Which cards can accept that value?
+- Which cards cannot?
+- Does `All` produce no filter?
+
+## Runtime Categorical Options
+
+Query options from Metabase at runtime with a breakout on the same generated table field or compatible Metric dimension used by the filter.
+
+- Run a `useMetabaseQuery` breakout on the same table field or Metric dimension used by `filter(...)`, then derive a deduped option list from returned rows.
+- Prefer querying options from the same source used by the charts so the option list stays compatible with the filter.
+- Treat categorical labels as runtime values unless the user explicitly provides a closed enum. Field names in the generated schema are not value lists.
+- Use a searchable picker/combobox for entity filters and long runtime option lists.
+
+For Metric-backed cards, use the table source plus generated Metric aggregation. Use the generated Metric dimension in both the options query and the visible card query when the dimension belongs to that table source:
+
+```ts
+const ordersTable = schema.tables.orders;
+const revenueMetric = schema.metrics.revenue;
+const franchiseDimension = revenueMetric.dimensions.orders.franchiseId;
+
+const { data: optionData } = useMetabaseQuery<typeof ordersTable>({
+ source: ordersTable,
+ aggregations: [revenueMetric],
+ breakouts: [breakout(franchiseDimension)],
+});
+
+const revenueFilters =
+ selectedFranchise === "all"
+ ? []
+ : [filter(franchiseDimension, "=", selectedFranchise)];
+```
+
+Do not use source-card Metrics in table-source filter queries. Wait for saved-question source support, then pair those Metrics with `source: schema.questions.<question>` instead.
+
+For entity filters, keep display labels and raw values separate:
+
+```ts
+type Option = { label: string; value: string };
+
+const franchiseOptions = rows.map((row) => ({
+ label: row.franchise_name ?? row.franchise_id,
+ value: row.franchise_id,
+}));
+```
+
+Use the raw `value` in `filter(...)`. Never filter by display labels when a stable id is available.
+
+Do not render a free-text input that writes directly to an exact id filter. If the filter is searchable, search option labels and store the selected raw value.
+
+## Reset Missing Runtime Values
+
+Runtime option sets can change. If the selected value disappears, reset to `all` so the app does not stay filtered to no rows.
+
+```tsx
+useEffect(() => {
+ if (
+ selectedValue !== "all" &&
+ !options.some((option) => option.value === selectedValue)
+ ) {
+ setSelectedValue("all");
+ }
+}, [options, selectedValue]);
+```
+
+Keep the `All` option selectable even while options are loading, empty, or errored.
+
+## Filter State Rules
+
+- Default every filter to `all` or empty, and run the unfiltered query.
+- Convert `all`, `""`, `null`, and `undefined` to `[]`.
+- Keep `All` options selectable even while runtime option queries are loading, empty, or errored.
+- Do not disable the whole control while loading options; keep `All` enabled and show a loading/empty option for dynamic values.
+- If a selected runtime option disappears from the latest option query, reset that filter to `all` so stale values do not keep filtering the dashboard to no rows.
+- For custom date ranges, apply the filter only when both dates are valid.
+- Never fill half-selected ranges with sentinel dates like `2000-01-01` or `2100-01-01`.
+- Keep one filter array per queried table when charts use different date fields.
+- Memoize filter arrays so SDK query keys stay stable.
+- For boolean Yes/No/All filters, map both `true` and `false` explicitly; only All maps to no filter.
+
+## Searchable Runtime Filters
+
+Entity filters are filters where the selected value is an id/key but users need a label. They always use one searchable combobox, never a native `<select>` or a search input paired with `<select>`. Plain `<select>` is only for short closed enums explicitly provided by the user.
+
+If no component exists:
+
+- Prefer a small established combobox/listbox dependency for keyboard/focus behavior.
+- Hand-roll only a small picker: input, capped list, mouse selection, Escape/blur close, and clear button.
+
+Minimum behavior:
+
+- Click or focus opens the option list immediately, even before the user types.
+- Search filters labels, not raw ids.
+- The `All` option is always available.
+- Selecting an option stores the raw `value`.
+- The list is capped or scrollable so it cannot stretch the page.
+
+Do not close the list from an `onBlur` handler on the trigger button when the
+popover contains an auto-focused input. Moving focus from the button to the
+input blurs the button and immediately closes the list. If hand-rolling a
+combobox, keep focus inside one wrapper and close only when focus leaves the
+whole wrapper, or close from explicit selection, Escape, and outside clicks.
+
+Style this to match the app. If accessibility, keyboard behavior, or popover positioning becomes non-trivial, prefer a small established combobox component or the app's component library instead of hand-rolling more behavior.
+
+## Date Range Filters
+
+Date ranges should use ISO `YYYY-MM-DD` strings for query values. Never use `type="date"`.
+
+For custom date pickers:
+
+- Include a Custom range option in date preset bars by default. Omit it only when the user explicitly asks for fixed presets only or no date range control. Order presets as durations first, then All time, then Custom last.
+- First check whether the repo already has a date picker component or component library. If it does, use the existing component.
+- If the repo has no existing date picker, install `react-datepicker`. The default data-app template only includes React, React DOM, and the Metabase SDK.
+- Do not install a large UI suite just for one data-app date filter.
+- Import `react-datepicker/dist/react-datepicker.css`, then add small CSS overrides for the app's visual style if needed.
+- Type strict `react-datepicker` callbacks explicitly, for example `onChange={(date: Date | null) => ...}` for single-date pickers.
+- For custom date ranges, use `selectsRange` with local `Date | null` start/end state, but only commit the query range when both dates are selected.
+- If the custom range control should look like the other preset buttons, use `customInput` with a `forwardRef` button, spread react-datepicker's injected props, and call its injected `onClick` so the popover still opens.
+- Convert selected dates to ISO `YYYY-MM-DD` strings with local date getters (`getFullYear`, `getMonth`, `getDate`) rather than `toISOString()`.
+- For date-picker `selected` props, parse saved strings defensively and pass `null` for empty or invalid values. Never pass `new Date("")`.
+- Recent `react-datepicker` packages include their own TypeScript types; do not add `@types/react-datepicker` unless the installed version actually needs it.
+
+Install `react-datepicker` only when the repo does not already have a date picker:
+
+```bash
+npm install react-datepicker
+```
diff --git a/skills/metabase-data-app-semantic-layer/references/visualization-settings.md b/skills/metabase-data-app-semantic-layer/references/visualization-settings.md
new file mode 100644
index 00000000000..771b479ffaf
--- /dev/null
+++ b/skills/metabase-data-app-semantic-layer/references/visualization-settings.md
@@ -0,0 +1,46 @@
+# SDK Visualization Settings
+
+Use this as a quick orientation guide. The installed SDK types are always the source of truth: search `node_modules/@metabase/embedding-sdk-react/dist/index.d.ts` for `MetabaseCard`, the relevant `*VisualizationSettings` type, and any setting key before writing settings. The SDK declaration includes lightweight descriptions for the supported setting families and keys.
+
+## How To Choose Settings
+
+- Start with `card={{ query }}` when the user has not asked for a specific chart type and Metabase defaults can infer a reasonable display from the query.
+- Use `card={{ query, visualization }}` when the user request or design calls for a specific chart type, such as a pie chart for a distribution, but does not ask for setting-level customization.
+- Use `card={{ query, visualization, visualizationSettings }}` only when the user explicitly asks for a setting-level presentation change, such as hiding or renaming an axis label, showing value labels, stacking bars, adding a goal line, ordering table columns, showing pie totals/labels, or controlling series/slice order.
+- Use `useMetabaseQueryObject` to build the query. Do not call internal query resolution helpers directly.
+- Set only the few settings that express the requested setting-level change. Let Metabase choose defaults for dimensions, metrics, colors, and formatting when the query shape is obvious.
+- Use result column names in settings such as `graph.dimensions`, `graph.metrics`, `pie.dimension`, `pie.metric`, `scalar.field`, `sankey.source`, and `scatter.bubble`. If you are not sure what column names the query will produce, avoid those keys and use safer presentation settings instead.
+- Keep `column_settings`, `series_settings`, row ordering, and per-slice colors minimal. They depend on exact result keys and can break when the query changes.
+
+## Source Lookup
+
+Use targeted searches instead of reading the whole declaration file:
+
+```bash
+rg -n "export declare type MetabaseCard|declare interface MetabaseCardBase|declare type .*VisualizationSettings|declare type VisualizationSettings" node_modules/@metabase/embedding-sdk-react/dist/index.d.ts
+```
+
+When the app has an older SDK package, also check:
+
+```bash
+rg -n "useMetabaseQueryObject|UseMetabaseQueryObjectResult" node_modules/@metabase/embedding-sdk-react/dist/data-app.d.ts
+```
+
+If `useMetabaseQueryObject` and `MetabaseCard` expose incompatible opaque `DatasetQuery` symbols, do not cast through `any`; update the SDK package before using `card`.
+
+## Setting Families
+
+Read the setting-family docstrings from the installed SDK declaration:
+
+- `CartesianVisualizationSettings`: bar, line, area, combo, row
+- `ScatterVisualizationSettings`: scatter plots
+- `WaterfallVisualizationSettings`: waterfall charts
+- `TableVisualizationSettings`: table, pivot, object detail, list
+- `PieVisualizationSettings`: pie and donut charts
+- `ScalarVisualizationSettings`: scalar, smartscalar, gauge, progress
+- `FunnelVisualizationSettings`: funnel charts
+- `SankeyVisualizationSettings`: Sankey charts
+- `BoxplotVisualizationSettings`: box plots
+- `MapVisualizationSettings`: pin and region maps
+
+For individual setting behavior, search the same declaration for the key, such as `graph.dimensions`, `pie.dimension`, `sankey.source`, or `boxplot.whisker_type`. Do not invent settings that are not exposed by the installed SDK type. Custom `custom:*` visualizations accept `Record<string, unknown>` settings only when the app has a known custom visualization contract.
diff --git a/skills/metabase-data-app-setup/SKILL.md b/skills/metabase-data-app-setup/SKILL.md
new file mode 100644
index 00000000000..1917d2e34c5
--- /dev/null
+++ b/skills/metabase-data-app-setup/SKILL.md
@@ -0,0 +1,441 @@
+---
+name: metabase-data-app-setup
+description: Scaffold a new Metabase data-app into the connected remote-sync repository's `data_apps/<app>/` directory from the `data-app-template`. Use when the user asks to start, create, scaffold, or set up a data-app from scratch.
+---
+
+# Create a Metabase Data App
+
+A Metabase **data-app** is a single JS bundle that the host loads inside a Near Membrane sandbox and renders inside its own React tree. The scaffold is a Vite + React + TypeScript project: source under `src/`, a dev server that previews the app against a real Metabase **through the same Near Membrane sandbox + distortion rules Metabase uses in production** — so `npm run dev` behaves like production, including for third-party libraries the app bundles — and `npm run build` producing a single `dist/index.js`. (Because the sandbox runs a built bundle, a change rebuilds it and does a *soft reload* — re-evaluates the bundle in the sandbox and remounts the app, keeping auth/SDK loaded — rather than hot-swapping modules; component state resets, but there's no full browser refresh.) The dev preview also shows a corner **⚠ Diagnostics** toolbar that captures runtime errors — including the sandbox's otherwise-opaque blocked-API messages — so failures surface instead of being swallowed.
+
+**Data apps are served from Git, not uploaded.** A single repository is connected to Metabase via remote-sync (Admin → Settings → Remote sync). Each app lives in its own directory `data_apps/<app>/` inside that repo — its source, a `data_app.yaml` (name/path), and the committed built bundle at the `path` its `data_app.yaml` declares (`dist/index.js` by default). On each remote-sync import Metabase materializes one app per directory and serves it at `/apps/<slug>` url, where the slug **is** the directory's name. So this skill always scaffolds **into the connected repo's `data_apps/<app>/` directory**, never as a standalone project.
+
+**The scaffold ships inside this skill at `./template/`** — a Vite + React + TypeScript project that was installed alongside the skill. Step 3 just copies it into the app directory; the skill then guides you through the customization + first-app-content steps — it never generates project files from scratch. If you find yourself writing `package.json`, `vite.config.ts`, `tsconfig.json`, or `src/index.tsx` by hand, stop — copy the template instead.
+
+## When to invoke this skill
+
+- "scaffold a new data app" / "create a Metabase data app" / "set up a data-app project"
+- "I want to build a data app" / any vague intent to author a data app
+- Starting a fresh agent task that will produce a data-app bundle.
+- Do **not** use this skill for an existing data-app project when the task is to
+ build screens, use Metabase data, generate or refresh schema files, wire saved
+ questions / tables / metrics / actions, add filters, or author data hooks.
+ Treat those as existing-data-app editing tasks and use the agent's normal
+ skill-discovery flow from the user's wording.
+
+## Step 1 — Locate the remote-sync repository
+
+Data apps live inside the Git repository connected to Metabase via remote-sync. Find it before scaffolding:
+
+- Ask: **"Do you already have a Git repository connected to this Metabase via remote-sync?"**
+ - **Yes** → ask for its local path.
+ - **No** → ask the user to **create one** (a plain Git repo they will connect under Admin → Settings → Remote sync) and share its path. The skill does **not** create or connect the repo — the user owns that.
+- Verify the path exists and is a Git working tree (it has a `.git`). This repo is the working directory for every step below.
+
+## Step 2 — Name the app and create its directory
+
+1. Settle on the app's **directory name** before scaffolding — it is used verbatim as the slug (the `/apps/<slug>` URL), so it **must be dash-cased**: lowercase letters, numbers, and single dashes (`[a-z0-9]+(?:-[a-z0-9]+)*`), e.g. `sales-overview`. Anything else (uppercase, spaces, underscores) is rejected on sync. If the purpose isn't clear yet, ask a one-line "what's this app for?" and propose a name; confirm it.
+2. Ensure `<repo>/data_apps/` exists; create it if missing.
+3. Create `<repo>/data_apps/<slug>/`. **If it already exists**, treat it as an existing project (see below) — never overwrite without confirmation.
+
+### Detecting an existing app
+
+If `<repo>/data_apps/<slug>/` already holds a project, verify it matches the current `data-app-template`. Check **all** of:
+
+1. `vite.config.ts` is a one-liner: `export default dataAppConfig()`
+ (from `@metabase/embedding-sdk-react/data-app-dev/config`). There is **no**
+ local `config/` directory: the whole bundle contract (externals/globals, the
+ dev sandbox entry, CSS/SVG handling) lives inside that SDK config, not the
+ scaffold. `dataAppConfig` takes only a curated set of overrides (currently just
+ `port`); the contract plugin is always applied and can't be overridden.
+2. `src/index.tsx` default-exports a `DataAppFactory` (type from
+ `@metabase/embedding-sdk-react/data-app`) returning `{ component, providerProps? }`
+ (no args).
+
+**All checks pass** → template-shaped. Ask: "Extend this app, or scaffold a new one under a different slug?" If extend → skip the copy step, edit `src/`. If new → pick a different slug and restart at Step 2.
+
+**Any check fails** → not template-shaped (older scaffold or drift). **Stop.** Tell the user the structure differs from the current template, extending it risks breaking the bundle contract, and ask whether to (1) migrate it, (2) scaffold fresh under a new slug and port the code over, or (3) proceed anyway at their risk. Wait for the answer.
+
+Never overwrite existing files without explicit confirmation.
+
+## Step 3 — Copy the template into the app directory
+
+The template ships **inside this skill** at `./template/` (installed alongside the skill via `skills add metabase/metabase/skills#release-x.<major>.x`). Copy it into the app directory:
+
+```bash
+APP_DIR="<repo>/data_apps/<slug>"
+# `<skill-dir>` = the directory this SKILL.md was loaded from
+# (e.g. `.claude/skills/metabase-data-app-setup`); the template is its `template/` subfolder.
+cp -R "<skill-dir>/template/." "$APP_DIR/"
+```
+
+A data app is a *subdirectory* of the remote-sync repo, not its own repository — so this is a plain copy, never a nested `git clone` / `git init`. Everything below runs **inside `$APP_DIR`**.
+
+## Step 4 — Customize
+
+Once the template is in `<repo>/data_apps/<slug>/` (run everything below from that directory):
+
+1. Edit `package.json` `name` to match the slug.
+2. Pin `@metabase/embedding-sdk-react` to the published data-apps tag (the template ships with `*`):
+
+ ```bash
+ npm install @metabase/embedding-sdk-react@63-data-apps
+ ```
+
+ This resolves to the current internal-testing SDK build with the `@metabase/embedding-sdk-react/data-app` entrypoint (the app's APIs) and the `@metabase/embedding-sdk-react/data-app-dev/config` entrypoint `vite.config.ts` uses (the dev/build preset, which serves the sandbox entry). Do not use `latest`, `63-stable`, or a generic `^0.63.x` range for data apps until the data-app SDK surface is promoted out of the internal tag.
+3. **Ensure the repo-root `.gitignore` ignores `.env.local`** — do this *before* creating any credentials file so the secret can never be committed. Create the `.gitignore` if the repo doesn't have one, then add the entry if it's missing:
+
+ ```bash
+ ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"
+ if [ -z "$ROOT" ]; then
+ echo "MISSING (run this from inside the connected git repo)"
+ else
+ GITIGNORE="$ROOT/.gitignore"
+ # Create the repo-root .gitignore if absent, then ensure `.env.local` is
+ # ignored so the credentials file (next step) can never be committed.
+ [ -f "$GITIGNORE" ] || : > "$GITIGNORE"
+ grep -qxF ".env.local" "$GITIGNORE" || echo ".env.local" >> "$GITIGNORE"
+ fi
+ ```
+4. Set up the Metabase credentials at the **repository root** — `<repo>/.env.local` (usually two levels up from the app dir), **not** the app dir. One `.env.local` there serves every data app in the repo.
+
+ Create it from the example if absent, then verify the two vars are set **without printing the file** (it may hold other secrets) — `source` it and echo only a pass/fail signal, never the values:
+
+ ```bash
+ # Resolve the repo root first; an unguarded $(git ...) would expand to
+ # "/.env.local" outside a repo and touch a system-level file.
+ ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"
+ if [ -z "$ROOT" ]; then
+ echo "MISSING (run this from inside the connected git repo)"
+ else
+ ENV_FILE="$ROOT/.env.local"
+ [ -f "$ENV_FILE" ] || cp .env.local.example "$ENV_FILE"
+ # Source inside a subshell so the vars never leak into your environment.
+ ( source "$ENV_FILE" 2>/dev/null
+ [ -n "$DATA_APP_MB_URL" ] && [ "$DATA_APP_MB_URL" != "mb_replace_me" ] &&
+ [ -n "$DATA_APP_MB_API_KEY" ] && [ "$DATA_APP_MB_API_KEY" != "mb_replace_me" ]
+ ) && echo "creds present" || echo "MISSING"
+ fi
+ ```
+
+ If it prints `MISSING`, **ask the user to fill `DATA_APP_MB_URL` (the running Metabase instance) and `DATA_APP_MB_API_KEY` (Admin → Authentication → API keys) in `<repo>/.env.local` themselves** — up front, before anything needs the key.
+
+ > **Never ask the user to paste the API key into the chat, and never `cat` / `echo` / print `.env.local` or its variables.** It's git-ignored and may hold *other* secrets — the file's contents and the key must never enter the conversation or your context. Every command that needs the key `source`s the file (as above) so the shell uses the value directly; you only ever see the `creds present` / `MISSING` signal, never the secret itself. (`creds present` only means both vars are filled and not the default `mb_replace_me` placeholder — not that the URL or key are valid; a bad key surfaces later when a request fails.)
+5. `npm install` (or whichever package manager the user prefers — the template ships with no lockfile, so `npm` / `yarn` / `pnpm` / `bun` all work; use the project's existing lockfile if one appears post-clone).
+6. **Fix the app's `.gitignore` so the lockfile *and* the built bundle get committed.** Two things must end up tracked in the remote-sync repo:
+ - **Lockfile** — strip the lockfile-ignoring block (the chunk between `# Lockfiles —` and `bun.lockb`, covering `package-lock.json` / `yarn.lock` / `pnpm-lock.yaml` / `bun.lock` / `bun.lockb`) so the project commits its lockfile for reproducible installs.
+ - **The built bundle** — Metabase serves the file at the `path` declared in `data_app.yaml` (the template builds to `dist/index.js`, the default `path`) straight from the committed Git tree, so **that file must be committed**. If the template's `.gitignore` ignores `dist/` (or wherever your build outputs), remove that line.
+ **Verify with `git status`** — after `npm install` + a build, both the generated lockfile and the built bundle (the file `path` points at) must appear as untracked/committable files. If either doesn't, the relevant `.gitignore` line is still there; remove it and re-check. Do **not** skip this — agents have repeatedly shipped projects with no committed lockfile or an un-synced bundle.
+7. `npm run dev` and confirm the preview at http://localhost:5174 renders the starter "Hello, data app" message.
+8. If the preview hits CORS, add `http://localhost:5174` under Admin → Embedding → Embedded analytics SDK → CORS.
+9. **Edit `data_app.yaml`** (it ships with the template, in the app directory). This is the per-app config Metabase reads on sync — one file per app. Fill in its fields for this app:
+
+ ```yaml
+ name: Sales App # display name shown in the admin UI
+ path: ./dist/index.js # bundle path, relative to this app's directory — leave as-is unless you change the build output
+ # allowed_hosts: # optional — external origins the app may fetch/XHR (see below)
+ # - https://api.example.com
+ # - https://*.internal.acme.com
+ ```
+
+ Commit it alongside the built bundle (the file `path` points at).
+
+ **`allowed_hosts`** — only needed if the app calls an **external** API directly
+ with `fetch`/`XHR`. The sandbox blocks all network egress by default; listing an
+ origin here (exact or a `*.` subdomain wildcard) opens it in both `npm run dev`
+ (dev-server CSP) and Metabase (iframe CSP + sandbox). Do **not** list the
+ Metabase instance — Metabase data is read via the `useMetabaseQuery` data hooks
+ and written via `useAction` (the SDK handles auth), never raw `fetch`. Leave
+ `allowed_hosts` out entirely when the app only talks to Metabase.
+
+ Native `<form action="…">` submissions and `<iframe src="…">`/navigations obey
+ the **same** allowlist. Prefer a client-side `<form onSubmit>` that
+ `preventDefault`s and writes via `useAction`/`fetch`: a native submit
+ *navigates the sandboxed iframe away* from the app. If you do use one, the
+ target host must be in `allowed_hosts` or it's blocked (`form-action` for
+ submits, `frame-src` for embeds/navigations). A host you navigate to or embed
+ must also permit framing (`X-Frame-Options`/`frame-ancestors`) — many public
+ sites don't.
+
+## Step 5 — Verify the starter app
+
+At this point the data app exists. Keep this workflow focused on creating the
+project scaffold and proving the starter bundle works.
+
+1. Run `npm run typecheck`.
+2. Run `npm run build`.
+3. Confirm `git status` shows the app source, lockfile, `data_app.yaml`, and the
+ built bundle (`dist/index.js` by default) as committable files.
+4. If the user asked for a live preview, run `npm run dev` and confirm the
+ starter "Hello, data app" screen renders through the sandbox preview.
+
+Stop here if the user only asked to create, scaffold, or set up a data app.
+
+If the next task is to build or iterate on the actual app UI — especially if it
+mentions an existing data app, Metabase data, generated schema files, saved
+questions, tables, metrics, actions, filters, semantic-layer entities, or data
+hooks — treat it as a separate existing-data-app editing task. Use the agent's
+normal skill-discovery flow from those terms. Do not expand this scaffold skill
+with data-layer authoring rules.
+
+**Do not modify `src/index.tsx` or `tsconfig.json` unless the change is genuinely required.** The whole build/dev setup lives in the SDK behind `dataAppConfig()` (which also serves the dev HTML shell — there's no `index.html` to edit), so `vite.config.ts` is just:
+
+```ts
+import { dataAppConfig } from "@metabase/embedding-sdk-react/data-app-dev/config";
+
+export default dataAppConfig();
+```
+
+`dataAppConfig` exposes only a curated set of overrides (currently just `port`). The whole contract — factory shape, externals/globals, the dev sandbox entry, CSS inlining, and SVG-as-component support — is baked in and **can't** be overridden; that's deliberate, so a data app can't drift from what Metabase loads. There's no local build config to touch (and no `index.html` — the SDK's dev server serves the HTML shell), and tweaks to `src/index.tsx` still risk breaking the factory shape and silently break drill popups and routing.
+
+There is intentionally **no escape hatch** for extra Vite plugins, aliases, or `define`s — `port` is the only knob. If you think you need more, you almost certainly don't; solve it in `src/` instead.
+
+**After every meaningful round of edits, run `npm run typecheck`.** It runs `tsc --noEmit` over `src/` and `vite.config.ts` — catches wrong prop shapes against the SDK types, broken refactors, missing imports, etc. The Vite dev server does NOT typecheck (it only transpiles), so errors that would fail a production CI run can sit invisibly in a passing `npm run dev` session. Run it before declaring a task complete.
+
+**Before handoff, re-check package hygiene.** `@metabase/embedding-sdk-react` should use the expected data-app SDK source/tag for the target environment, and `@types/react-datepicker` should not be installed unless the chosen `react-datepicker` version actually needs it.
+
+## Source conventions
+
+### 1. Write TSX
+
+Plain ESM + TSX, normal package imports:
+
+```tsx
+// src/components/CustomerCard.tsx
+import { StaticQuestion } from "@metabase/embedding-sdk-react";
+
+type Customer = { name: string; questionId: number };
+
+export default function CustomerCard({ customer }: { customer: Customer }) {
+ return (
+ <article>
+ <h3>{customer.name}</h3>
+ <StaticQuestion questionId={customer.questionId} height={300} width="100%" />
+ </article>
+ );
+}
+```
+
+### 2. Structure from the start
+
+Default project layout once the starter app is extended:
+
+```
+src/
+├── index.tsx (template — the factory; don't edit)
+├── App.tsx (routing + composition only)
+├── theme.ts
+├── pages/ (one file per screen)
+│ ├── Overview.tsx
+│ └── CustomerDetail.tsx
+├── components/ (shared UI)
+│ └── Card.tsx
+├── hooks/ (data-fetching wrappers, custom hooks)
+│ └── useCustomers.ts
+├── lib/ (pure helpers / derivations)
+│ └── format.ts
+└── types/ (shared TS types)
+ └── customer.ts
+```
+
+Vite bundles everything reachable from `src/index.tsx` into a single `dist/index.js` IIFE — the folder layout is purely for your own readability.
+
+**If the app has multiple tabs (or any top-level screen switcher), the default — leftmost / first — tab MUST be selected on initial load.** The app should never boot to a blank page, an empty shell, or a "nothing selected" state that waits for the user to click. Agents repeatedly forget this. For local-state tabs, initialize the active tab to the first one so the very first render shows it:
+
+```tsx
+const [active, setActive] = useState(TABS[0].id); // default = leftmost tab
+```
+
+If the tabs are instead backed by URL routes (multiple pages), the same rule applies via the router — see the `metabase-data-app-routing` skill for making the base path `/` resolve to the default tab. Either way, verify by loading the app fresh: the leftmost tab's content is visible immediately and reads as selected.
+
+**The build output is one self-contained `.js` file — nothing else.** The backend serves a single bundle, so there are no sidecar files: CSS is inlined into the JS, and every imported asset (images, fonts, SVGs-as-URLs) is base64-inlined as a data URI. So `import logo from "./logo.png"` / `import iconUrl from "./icon.svg"` give you a ready-to-use data-URI string, and SVGs can also be imported as React components with the **`?react`** suffix (built-in `svgr`): `import Icon from "./icon.svg?react"`. Everything gets baked into `dist/index.js` — just keep large binaries out, since inlining inflates the bundle. (If your editor doesn't recognize a `?react` import, add `declare module "*.svg?react";` to a `.d.ts` in `src/`.)
+
+### 3. Import SDK values from the correct SDK entrypoint
+
+The build externalizes React, the JSX runtimes, `@metabase/embedding-sdk-react`, and `@metabase/embedding-sdk-react/data-app` to sandbox globals in **both** production and `npm run dev` — in dev the sandbox entry endows them from the npm package, so the bundle runs identically in both. Just import from the entrypoints normally:
+
+```tsx
+// ✅ correct
+import { StaticQuestion } from "@metabase/embedding-sdk-react";
+import {
+ DataAppRouter,
+ DataAppLink,
+ useMetabaseQuery,
+} from "@metabase/embedding-sdk-react/data-app";
+
+// ❌ wrong — no globalThis pattern; you'd be reading nothing
+const { MetabaseProvider, StaticQuestion } = globalThis;
+```
+
+**Do NOT render `<MetabaseProvider>` in `App.tsx`.** The dev entry (served by the SDK's dev preset) and the production host both wrap your tree in a provider that lives in their own realm — wrapping inside the bundle would route the SDK's `setState`-via-listener paths through the Near Membrane sandbox and silently break drill popups, plugin init, and similar.
+
+### 4. Import `react` normally too
+
+The build externalizes `react` and `react-dom`, so plain imports resolve the same way in both modes — the production host and the dev sandbox both endow them as sandbox globals:
+
+```tsx
+import { useState, useEffect, useMemo } from "react";
+```
+
+**No `import React from "react"` needed in TSX files** — the template uses the automatic JSX runtime (`jsx: "react-jsx"` in `tsconfig.json`; `dataAppConfig()` includes the React plugin). The compiler injects the JSX-runtime imports it needs (`react/jsx-runtime` in production, `react/jsx-dev-runtime` in dev — both externalized and endowed by the sandbox). Just write JSX and named imports — that's it.
+
+For React *types* (e.g. `ComponentType`, `ReactNode`, `RefObject`), use named type imports rather than the `React.` namespace:
+
+```ts
+import type { ComponentType, ReactNode } from "react";
+```
+
+## Theme rules
+
+`MetabaseProvider`'s `theme` (defined in `src/theme.ts`) is the only way SDK component appearance changes. It is NOT a stylesheet for the bundle's own chrome.
+
+| Field | Purpose | Notes |
+|---|---|---|
+| `colors.brand` | Accent for SDK widgets | Use the data app's primary color. |
+| `colors.brand-hover`, `colors.brand-hover-light` | Hover/accent backgrounds for SDK widgets | Use a subtle surface tint that contrasts with hover text. Do not use the same saturated color as `brand`. |
+| `colors.charts` | Chart palette | Array of strings. Use vivid brand-shade colors only; **never pale tints** — palette index 1+ may render labels and pale-on-white is invisible. |
+| `colors.positive` / `colors.negative` | Semantic indicators | |
+| `colors.background`, `colors.background-secondary` | SDK component surface | **MUST match the immediate parent container of the SDK component.** If the chart sits inside a white card, use `"white"`. If it sits on a tinted page, use that tint. |
+| `colors.text-primary`, `text-secondary`, `text-tertiary` | Text on SDK surfaces | **MUST contrast with `background`.** For white bg: use `#1f2937` or similar dark color. The SDK's default `text-primary` resolves to ~white, so leaving it unset on a white surface produces invisible white text. **Always pair `background` and `text-primary` when overriding.** |
+| `fontFamily` | SDK widget typography | |
+
+Hover colors are a contrast pair. If you set `colors.text-hover`, verify it
+contrasts with `colors.brand-hover` / `colors.brand-hover-light` in open menus,
+chart type selectors, and visualization settings dropdowns. For a blue `brand`,
+use a pale hover surface like `#EAF4FF`, not the brand blue itself.
+
+**The theme only styles SDK widgets — never your own UI.** For your page background, headers, card wrappers, etc., use inline `style={{ background: "#f5f5f7" }}` or CSS modules on your own elements.
+
+**Don't expect per-subtree theming.** Multiple `<MetabaseProvider>`s on the page fight for the single CSS-variable slot. If the look needs to change with state, recompute `sdkTheme` at the App level and re-render — the whole tree re-themes.
+
+## Custom error UI (optional)
+
+When an embedded question or dashboard can't load — its `questionId` was removed, the user lacks access, or a request fails — the host renders a **neutral built-in error state** in place of that component (a muted icon + the SDK's message). This needs no setup; leave it alone unless the app has a strong reason to restyle it.
+
+To match the app's look, return your own `errorComponent` in the factory's `providerProps` (the same object that carries `theme`). It's an ordinary `providerProps` key, not a change to the factory shape — safe to add:
+
+```tsx
+// src/components/AppError.tsx
+import type { SdkErrorComponentProps } from "@metabase/embedding-sdk-react";
+
+export default function AppError({ message }: SdkErrorComponentProps) {
+ return (
+ <div style={{ padding: 16, textAlign: "center", color: "#6b7280" }}>
+ {message}
+ </div>
+ );
+}
+```
+
+```tsx
+// src/index.tsx — add the key alongside `theme`
+import AppError from "./components/AppError";
+
+const factory: DataAppFactory = () => ({
+ component: App,
+ providerProps: { theme: sdkTheme, errorComponent: AppError },
+});
+```
+
+Rules:
+
+- **It replaces the error UI for *every* SDK component in the app**, not just not-found — so keep the copy generic. Render `message` (or your own wording), not an assumption about which error occurred.
+- `message` is a `ReactNode` — render it as-is; don't call `.toString()` or index into it.
+- Keep it a small **presentational** component. It renders inside the host's provider, but treat it as leaf UI — no data hooks, no `useMetabaseQuery`.
+- Omit `errorComponent` entirely to keep the neutral default. There's no need to re-implement it.
+
+## Available SDK surface
+
+The bundle imports React hooks/JSX, SDK components from `@metabase/embedding-sdk-react`, and data-app-specific routing/query APIs from `@metabase/embedding-sdk-react/data-app`. `dataAppConfig()` externalizes these packages at build time, so production references the host's copies at runtime (`globalThis.__metabase_sdk__` / `globalThis.__metabase_data_app__` for SDK packages), and the Vite dev sandbox endows the same globals from the installed npm package.
+
+`<MetabaseProvider>` is **not** rendered by the bundle's `App.tsx` — the dev entry and the host wrap it for their respective modes. Bundle author only renders the **content** below.
+
+| Import | Purpose |
+|---|---|
+| `React` (from `"react"`) | Hooks (`useState`, `useEffect`, etc.), JSX runtime. Externalized to the host's React via `react: "React"`. |
+| `StaticQuestion` | Non-drillable question. Props include `questionId`, `card`, `withChartTypeSelector`, `height`, `width`. |
+| `InteractiveQuestion` | Drillable question. Same props as StaticQuestion plus drill behaviors. Use `card={{ query }}` for ad hoc SDK-rendered questions. Add `visualization` when the request calls for a specific chart type, and add `visualizationSettings` only for explicit setting-level presentation changes; use skill discovery for schema-backed query and card type guardrails. |
+| `MetabaseCard` | Type-only import from `@metabase/embedding-sdk-react` for ad hoc SDK-rendered cards with `visualization` or `visualizationSettings`; use skill discovery for the full generated-query card contract before authoring data-layer code. |
+| `CreateQuestion`, `MetabotQuestion` | More question variants. |
+| `StaticDashboard`, `InteractiveDashboard`, `EditableDashboard` | Dashboard variants. |
+| `CreateDashboardModal` | Modal for new-dashboard flow. |
+| `CollectionBrowser` | Collection picker. |
+| `@metabase/embedding-sdk-react/data-app` exports | Data-app-only helpers for routing, schema-backed data reads, actions, clipboard, and sandbox-safe integration. Treat schema-backed queries, generated schema files, filters, metrics, actions, and other data-layer behavior as existing-data-app editing work; use skill discovery before authoring that code. |
+
+### Blocked APIs
+
+The Near Membrane sandbox throws at runtime on these globals. Use the endowed replacement instead:
+
+| Blocked | Use instead |
+|---|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| **Network** — `fetch`, `XMLHttpRequest`, `WebSocket` | Use the SDK/data-app APIs for Metabase reads and writes — never raw `fetch`. Raw `fetch`/`XHR` reach **only** the external origins listed in `data_app.yaml`'s `allowed_hosts` (Step 4); everything else (including the Metabase origin) throws. `WebSocket` is always blocked. |
+| **UI dialogs** — `alert`, `confirm`, `prompt` | Render a React modal in your own tree. |
+| **Storage** — `localStorage`, `sessionStorage`, `indexedDB`, `document.cookie` | Treat the data app as stateless across reloads; persist via a Metabase action. |
+| **Window / history navigation** — `window.open`, `history.pushState`, `history.replaceState` | `useDataAppLocation().navigate` for in-app; `<a target="_blank" rel="noopener">` for external. |
+| **Clipboard** — `document.execCommand("copy")`, `navigator.clipboard` | `copy` (write-only): `import { copy } from "@metabase/embedding-sdk-react/data-app"`, then `await copy(text)` from a user event. There is **no** read/paste API — that would let a bundle exfiltrate whatever the user copied. |
+| **Other `navigator.*` device APIs** — `geolocation`, etc. | Not available. |
+| **Global `document`/`window` listeners** for typing/clipboard events — `keydown`, `keyup`, `keypress`, `beforeinput`, `input`, `paste`, `copy`, `cut`, `before*paste/copy/cut`, `compositionstart/update/end`, `storage` | Attach the listener to your own element, or use the React handler (`onKeyDown`, `onPaste`, …) on the specific input/container. The same listener on a script-owned element still works. |
+
+**Rule of thumb:** if you're about to touch `window.X`, `document.X`, `navigator.X`, `history.X`, or any storage global, stop and pick the endowed replacement above. The endowed surface (React + React DOM + SDK components + data hooks + `useAction` + DataAppRouter + `copy`) covers every routine need; anything outside it is intentionally unreachable.
+
+### When to use SDK charts vs `useMetabaseQuery`
+
+This is a per-rendering decision, not a project-wide one:
+
+- **`useMetabaseQueryObject` + `StaticQuestion` / `InteractiveQuestion`** — default for ordinary dashboard charts: bar, line, area, row, pie, scalar/smartscalar, gauge, progress, pivot, map, sortable table, and other displays Metabase already renders well. Build the semantic query from generated schema objects, destructure the returned `query`, then pass only that value to the SDK component with a card object, for example `<StaticQuestion card={{ query }} ... />`. Never pass the whole `{ query, error, isLoading }` hook result as `card.query`.
+- **`useMetabaseQuery`** — use when React genuinely needs row values: extracting KPI numbers, powering custom controls, composing bespoke summary cards, combining multiple queries into one UI element, or rendering a visualization Metabase cannot express.
+
+Generated dashboards should prefer SDK-rendered charts. Do not rebuild normal bar/line/table charts in React just to match app chrome. If you choose `useMetabaseQuery`, keep the row handling typed.
+
+**Always render a spinner (or skeleton) while `isLoading` is `true`** — never an empty slot or stale value, which causes layout shift when the data arrives. Same rule for lifted / derived queries (pass `isLoading` down) and for `useAction`'s `isExecuting` (spinner in the button + `disabled={isExecuting}`).
+
+**Call each schema entry at most once per render tree.** Multiple `useMetabaseQuery` calls on the same `questionId` (or same `tableId` + identical filters/measures/breakouts) mount independent subscriptions, fire duplicate queries, and let consumers disagree mid-load. Lift the call to the highest component that needs the data; pass `data` / `isLoading` / `error` down as props. Different ids — or the same id with different filters / breakouts — are different data sources; call them separately.
+
+For the hook contract itself — generics, table sources, segments, measures, breakouts, sorting, and debugging — use skill discovery before authoring schema-backed data-layer code.
+
+## SDK component sizing
+
+SDK components do NOT auto-fit their parent. Always pass explicit dimensions:
+
+```tsx
+<div style={{ height: 360, overflow: "hidden" }}>
+ <StaticQuestion
+ questionId={1}
+ height="100%"
+ width="100%"
+ withChartTypeSelector={false}
+ />
+</div>
+```
+
+Without `height`/`width`, the SDK component renders at its intrinsic size and overflows.
+
+## Sync to Metabase
+
+Data apps are delivered by Git, not uploaded — you commit the app directory and Metabase pulls it on its next remote-sync import.
+
+1. `npm run build` → produces the bundle at your `data_app.yaml` `path` (the template builds to `dist/index.js`).
+2. From the **repo root**, commit the app directory — its `data_app.yaml`, the built bundle (the file `path` points at), the source, and the lockfile — and **push**:
+ ```bash
+ git add data_apps/<slug>
+ git commit -m "Add <slug> data app"
+ git push
+ ```
+3. The app appears in Metabase on the next remote-sync import — a manual **Pull changes** (Admin → Data apps / Remote sync), the auto-import poll, or a restart — reachable at `/apps/<slug>`.
+
+**To update:** commit a new build and pull again. **To remove:** a sync never deletes, so removing the app's directory from the repo does *not* remove the app — an admin removes it in Metabase (Admin → Data apps).
+
+## Common pitfalls
+
+| Symptom | Fix |
+|---|---|
+| "Failed to fetch the user, the session might be invalid." | Bad API key or CORS — check `( ROOT="$(git rev-parse --show-toplevel 2>/dev/null)"; [ -n "$ROOT" ] && source "$ROOT/.env.local" 2>/dev/null; [ -n "$DATA_APP_MB_URL" ] && [ "$DATA_APP_MB_URL" != "mb_replace_me" ] && [ -n "$DATA_APP_MB_API_KEY" ] && [ "$DATA_APP_MB_API_KEY" != "mb_replace_me" ] && curl -H "x-api-key: $DATA_APP_MB_API_KEY" "$DATA_APP_MB_URL/api/user/current" || echo "set real DATA_APP_MB_URL / DATA_APP_MB_API_KEY in the repo-root .env.local" )` (uses the repo-root `.env.local`), add `http://localhost:5174` to SDK CORS origins. |
+| Invisible chart labels. | Set `text-primary` in the theme (see *Theme rules*). |
+| Chart overflows its container. | Pass `height` / `width` to the SDK component (see *SDK component sizing*). |
+| "Invalid hook call" at runtime. | Two React copies. `dataAppConfig()` externalizes `react` — ensure `react`/`react-dom` are installed and you haven't added a second React or a mismatched version. |
+| Bundle is multi-MB. | React/the SDK should be externalized by the contract plugin — confirm `vite.config.ts` still uses `dataAppConfig()` and the pinned data-apps SDK tag is installed. (A large but not multi-MB bundle can also be inlined assets — see the single-file note above.) |
+| `dist/index.js` doesn't assign to `__dataAppFactory__`. | `src/index.tsx` must `export default` the `DataAppFactory` — the preset wires that into the IIFE global. |
+| `Cannot find module '@metabase/embedding-sdk-react'`. | Run `npm install` (or the equivalent for your package manager). Types come from the package directly. |
+| Drill popups don't open / SDK components show empty / "MetabaseProvider not found" at runtime in dev. | `App.tsx` is rendering its own `<MetabaseProvider>` — remove it. The dev entry (SDK) and the production host provide the provider; wrapping it inside the bundle routes the SDK's state paths through the sandbox and breaks them. |
+| Dev preview blank / `Bundle did not assign a function to __dataAppFactory__` / sandbox errors in dev. | `src/index.tsx` isn't default-exporting the factory, or your app code throws while the sandbox evaluates the bundle — open the dev toolbar's **Diagnostics** panel for the real error. |
+| Component state resets on every edit. | Expected: dev rebuilds the bundle and does a *soft reload* — re-evaluates it in the sandbox and remounts the app (auth/SDK stay loaded, no browser refresh). There's no module-level HMR / Fast Refresh because the app is an evaluated bundle in an isolated realm, so local component state resets. |
+| URL changes but UI doesn't update in production (works in dev). | Import the routing primitives from `@metabase/embedding-sdk-react/data-app` (not the main entry) and keep using `dataAppConfig()` — it externalizes `/data-app` so its routing isn't inlined (inlining triggers the React-state-batching-through-Near-Membrane bug). |
diff --git a/skills/metabase-data-app-setup/template/.env.local.example b/skills/metabase-data-app-setup/template/.env.local.example
new file mode 100644
index 00000000000..32cdccb3828
--- /dev/null
+++ b/skills/metabase-data-app-setup/template/.env.local.example
@@ -0,0 +1,2 @@
+DATA_APP_MB_URL=http://localhost:3000
+DATA_APP_MB_API_KEY=mb_replace_me
diff --git a/skills/metabase-data-app-setup/template/.gitignore b/skills/metabase-data-app-setup/template/.gitignore
new file mode 100644
index 00000000000..1da42fddcc3
--- /dev/null
+++ b/skills/metabase-data-app-setup/template/.gitignore
@@ -0,0 +1,16 @@
+node_modules
+.env.local
+.vite
+dist
+.idea
+
+# Lockfiles — the template is package-manager agnostic; don't commit any
+# generated lockfile from `npm install` / `yarn` / `pnpm install` / `bun install`.
+# Downstream projects scaffolded from this template should DELETE these lines
+# from their own .gitignore once they pick a package manager — they'll want
+# their lockfile committed for reproducible installs.
+package-lock.json
+yarn.lock
+pnpm-lock.yaml
+bun.lock
+bun.lockb
\ No newline at end of file
diff --git a/skills/metabase-data-app-setup/template/LICENSE b/skills/metabase-data-app-setup/template/LICENSE
new file mode 100644
index 00000000000..5f9c0a626d2
--- /dev/null
+++ b/skills/metabase-data-app-setup/template/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Metabase
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/skills/metabase-data-app-setup/template/README.md b/skills/metabase-data-app-setup/template/README.md
new file mode 100644
index 00000000000..8a601330a94
--- /dev/null
+++ b/skills/metabase-data-app-setup/template/README.md
@@ -0,0 +1,94 @@
+# data-app-template
+
+A Metabase **data app** — a single-bundle React app (built with the Embedding
+SDK) that Metabase renders inside an isolated, sandboxed iframe at
+`/apps/<slug>`.
+
+Data apps are delivered through **Git, not uploaded**: this directory lives at
+`data_apps/<slug>/` inside a repository connected to Metabase via remote sync.
+You commit the built bundle (`dist/index.js`), and on the next remote-sync
+import Metabase materializes the app and serves it. There is no upload step.
+
+## Develop
+
+```bash
+npm install # or yarn / pnpm / bun — no lockfile shipped
+cp .env.local.example .env.local # set DATA_APP_MB_URL + DATA_APP_MB_API_KEY
+npm run dev # preview at http://localhost:5174
+```
+
+`npm run dev` previews the app against a real Metabase **through the same
+Near-Membrane sandbox + CSP rules production uses**, so dev behaves like prod.
+Edit anything under `src/` — the preview soft-reloads.
+
+If the dev preview hits CORS, add `http://localhost:5174` under
+Admin → Embedding → Embedded analytics SDK → CORS.
+
+## Ship
+
+```bash
+npm run build # produces a single dist/index.js
+```
+
+Commit `dist/index.js` (the `path` declared in `data_app.yaml`) along with your
+source. The app appears at `/apps/<slug>` after Metabase's next remote-sync
+import (manual "Pull changes", auto-import, or startup).
+
+## What's in the box
+
+```
+.
+├── data_app.yaml ← manifest: name, bundle path, allowed_hosts
+├── package.json ← @metabase/embedding-sdk-react + react/react-dom + Vite toolchain
+├── vite.config.ts ← one-liner: `export default dataAppConfig()`
+├── tsconfig.json
+├── src/
+│ ├── index.tsx ← entry — default-exports a factory returning { component, providerProps }
+│ ├── App.tsx ← edit this; pure content, no <MetabaseProvider> wrap
+│ └── theme.ts ← the SDK theme, passed via providerProps
+├── .env.local.example
+└── .gitignore
+```
+
+The build, dev server, Near-Membrane sandbox, and bundle contract all live in
+the SDK behind `dataAppConfig()` — there's no `index.html` or separate dev entry
+to edit. Keep `<MetabaseProvider>` out of `App.tsx`: the production host and the
+dev preview each provide it in their own realm.
+
+The build output is a single self-contained `dist/index.js` — CSS and assets are
+inlined, and React + the SDK are externalized to the host's instances, so the
+bundle stays small.
+
+## Calling external APIs (`allowed_hosts`)
+
+A data app runs sandboxed: by default it **can't** `fetch`/XHR anything. To let
+it reach an external API, list the origins in `data_app.yaml` under
+`allowed_hosts` (supports a `*.` subdomain wildcard):
+
+```yaml
+allowed_hosts:
+ - https://api.example.com
+ - https://*.internal.acme.com
+```
+
+The same allowlist is enforced in both places: `npm run dev` applies it via the
+dev server's CSP, and Metabase applies it via the iframe CSP + the membrane
+sandbox. The Metabase instance itself is reached through the SDK (not listed
+here). A call to any other host fails in dev exactly as it will in production.
+
+### Forms and embeds
+
+`allowed_hosts` also governs native `<form action="…">` submissions and
+`<iframe src="…">` / navigations, not just `fetch`.
+
+Prefer a **client-side** form — `<form onSubmit={(e) => { e.preventDefault(); … }}>`
+that writes via the SDK (`useAction`) or `fetch` — over a native
+`<form action="…">`. A native submit **navigates the sandboxed iframe away** from
+your app.
+
+If you do use `<form action="https://…">` (or embed/navigate to a host via an
+`<iframe>`), the target host must be in `allowed_hosts`, or the browser blocks it
+(`form-action` for submits, `frame-src` for embeds). Note a host you embed or
+navigate to must also **allow being framed** (`X-Frame-Options` /
+`frame-ancestors`) — many public sites (e.g. `example.com`) don't, so they can't
+be shown in-frame regardless of `allowed_hosts`.
diff --git a/skills/metabase-data-app-setup/template/data_app.yaml b/skills/metabase-data-app-setup/template/data_app.yaml
new file mode 100644
index 00000000000..29be0051fd0
--- /dev/null
+++ b/skills/metabase-data-app-setup/template/data_app.yaml
@@ -0,0 +1,9 @@
+name: Data App Template
+path: ./dist/index.js
+
+# Origins this app may call with fetch/XHR. Everything else is blocked — both in
+# `npm run dev` (via the dev server's CSP) and inside Metabase (the sandbox).
+# The Metabase instance itself is reached through the SDK, not listed here.
+# allowed_hosts:
+# - https://api.example.com
+# - https://*.internal.acme.com
diff --git a/skills/metabase-data-app-setup/template/package.json b/skills/metabase-data-app-setup/template/package.json
new file mode 100644
index 00000000000..d5142d69049
--- /dev/null
+++ b/skills/metabase-data-app-setup/template/package.json
@@ -0,0 +1,25 @@
+{
+ "name": "data-app-template",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "dev": "vite --port 5174",
+ "build": "vite build",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "@metabase/embedding-sdk-react": "*",
+ "react": "^18.3.1",
+ "react-dom": "^18.3.1"
+ },
+ "devDependencies": {
+ "@types/react": "^18.3.12",
+ "@types/react-dom": "^18.3.1",
+ "@vitejs/plugin-react": "^6.0.2",
+ "typescript": "^6.0.3",
+ "vite": "^8.0.16",
+ "vite-plugin-css-injected-by-js": "^3.5.2",
+ "vite-plugin-svgr": "^5.2.0"
+ }
+}
diff --git a/skills/metabase-data-app-setup/template/src/App.tsx b/skills/metabase-data-app-setup/template/src/App.tsx
new file mode 100644
index 00000000000..d8e380d3f48
--- /dev/null
+++ b/skills/metabase-data-app-setup/template/src/App.tsx
@@ -0,0 +1,9 @@
+export default function App() {
+ return (
+ <div style={{ padding: 24 }}>
+ <h1 style={{ margin: 0 }}>Hello, data app</h1>
+
+ <p style={{ color: "#555" }}>Edit src/App.tsx to begin.</p>
+ </div>
+ );
+}
diff --git a/skills/metabase-data-app-setup/template/src/index.tsx b/skills/metabase-data-app-setup/template/src/index.tsx
new file mode 100644
index 00000000000..73299f764a7
--- /dev/null
+++ b/skills/metabase-data-app-setup/template/src/index.tsx
@@ -0,0 +1,14 @@
+import type { DataAppFactory } from "@metabase/embedding-sdk-react/data-app";
+
+import App from "./App";
+import { sdkTheme } from "./theme";
+
+// The data app's entry point. Return the root component plus any `providerProps`
+// the host should apply to `MetabaseProvider` (e.g. `theme`,
+// `allowedCustomVisualizations`).
+const factory: DataAppFactory = () => ({
+ component: App,
+ providerProps: { theme: sdkTheme },
+});
+
+export default factory;
diff --git a/skills/metabase-data-app-setup/template/src/theme.ts b/skills/metabase-data-app-setup/template/src/theme.ts
new file mode 100644
index 00000000000..2d9b6ee0b0b
--- /dev/null
+++ b/skills/metabase-data-app-setup/template/src/theme.ts
@@ -0,0 +1,16 @@
+import type { MetabaseTheme } from "@metabase/embedding-sdk-react";
+
+export const sdkTheme: MetabaseTheme = {
+ colors: {
+ brand: "#4D96FF",
+ "brand-hover": "#EAF4FF",
+ positive: "#4D96FF",
+ charts: ["#4D96FF"],
+ background: "white",
+ "background-secondary": "white",
+ "text-primary": "#1f2937",
+ "text-secondary": "#4b5563",
+ "text-tertiary": "#6b7280",
+ },
+ fontFamily: "system-ui, -apple-system, Segoe UI, sans-serif",
+};
diff --git a/skills/metabase-data-app-setup/template/tsconfig.json b/skills/metabase-data-app-setup/template/tsconfig.json
new file mode 100644
index 00000000000..ae9cdb14735
--- /dev/null
+++ b/skills/metabase-data-app-setup/template/tsconfig.json
@@ -0,0 +1,25 @@
+{
+ "compilerOptions": {
+ "target": "ES2020",
+ "lib": ["ES2020", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "jsx": "react-jsx",
+ "esModuleInterop": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "skipLibCheck": true,
+ "noEmit": true,
+ "strict": true,
+ "allowJs": false,
+ "checkJs": false,
+ "noImplicitAny": true,
+ "strictNullChecks": true,
+ "forceConsistentCasingInFileNames": true,
+ "noUnusedLocals": false,
+ "noUnusedParameters": false,
+ "noFallthroughCasesInSwitch": true,
+ "types": ["vite/client"]
+ },
+ "include": ["src", "vite.config.ts"]
+}
diff --git a/skills/metabase-data-app-setup/template/vite.config.ts b/skills/metabase-data-app-setup/template/vite.config.ts
new file mode 100644
index 00000000000..3e1520458f2
--- /dev/null
+++ b/skills/metabase-data-app-setup/template/vite.config.ts
@@ -0,0 +1,3 @@
+import { dataAppConfig } from "@metabase/embedding-sdk-react/data-app-dev/config";
+
+export default dataAppConfig();
diff --git a/src/metabase/analytics/sdk.clj b/src/metabase/analytics/sdk.clj
index bd1eb6cdb92..640fc4c07ce 100644
--- a/src/metabase/analytics/sdk.clj
+++ b/src/metabase/analytics/sdk.clj
@@ -40,6 +40,12 @@
(defn get-client "Returns [[*client*]] dynamic var" [] *client*)
+(def ^:dynamic *client-identifier*
+ "Used to track the identifier of the concrete embedding client, e.g. the data-app name."
+ nil)
+
+(defn get-client-identifier "Returns [[*client-identifier*]]." [] *client-identifier*)
+
(def ^:dynamic *route* "Used to track the API route for the current request (e.g. \"public\", \"guest-embed\")." nil)
(defn get-route "Returns [[*route*]]." [] *route*)
@@ -119,6 +125,7 @@
[m :- :map]
(-> m
(update :embedding_client (fn [client] (or *client* client)))
+ (update :embedding_client_identifier (fn [identifier] (or *client-identifier* identifier)))
(update :embedding_route (fn [route] (or *route* route)))
(update :embedding_sdk_version (fn [version] (or *version* version)))
(update :auth_method (fn [method] (or *auth-method* method)))
@@ -131,7 +138,8 @@
"embedding-iframe-full-app"
"embedding-iframe-static"
"embedding-public"
- "embedding-simple"})
+ "embedding-simple"
+ "data-app"})
(defn- track-sdk-response
"Tabulates the number of responses by status code made by clients of the SDK."
@@ -143,6 +151,8 @@
"embedding-iframe-static" (analytics/inc! :metabase-embedding-iframe-static/response {:status (str status)})
"embedding-public" (analytics/inc! :metabase-embedding-public/response {:status (str status)})
"embedding-simple" (analytics/inc! :metabase-embedding-simple/response {:status (str status)})
+ ;; Known client, but a response-code counter tells us nothing actionable about data apps - so no metric.
+ "data-app" nil
(log/infof "Unknown client. client: %s" sdk-client)))
(defn embedding-context?
@@ -173,14 +183,18 @@
[request respond raise]
(let [metabase-client-header (get-in request [:headers "x-metabase-client"])
version (get-in request [:headers "x-metabase-client-version"])
+ ;; column is varchar(254); truncate rather than fail the row insert on an oversized header
+ identifier (some-> (get-in request [:headers "x-metabase-client-identifier"])
+ (as-> s (subs s 0 (min (count s) 254))))
preview? (= (get-in request [:headers "x-metabase-embedded-preview"]) "true")
route (embedding-route (:uri request))
;; *client* is the SDK/client identity from the header, with -preview suffix if applicable
client (cond-> metabase-client-header
preview? (some-> (str "-preview")))]
- (binding [*client* client
- *route* route
- *version* version]
+ (binding [*client* client
+ *client-identifier* identifier
+ *route* route
+ *version* version]
(handler request
(fn responder [response]
;; Only track prometheus when NO route match AND header is an embedding context
diff --git a/src/metabase/api/macros.clj b/src/metabase/api/macros.clj
index 6048a67e64e..0ac2e79b814 100644
--- a/src/metabase/api/macros.clj
+++ b/src/metabase/api/macros.clj
@@ -397,7 +397,10 @@
:route "route parameters"
:query "query parameters"
:body "body"
- :request "request"))
+ :request "request"
+ ;; fall back to the keyword name for any other validated
+ ;; params-type so we never throw "No matching clause" here
+ (name params-type)))
(let [explanation (mr/explain schema decoded)
specific-errors (invalid-params-specific-errors explanation)
errors (invalid-params-errors explanation)]
diff --git a/src/metabase/api_routes/routes.clj b/src/metabase/api_routes/routes.clj
index 14790a4896b..3c80453c6f5 100644
--- a/src/metabase/api_routes/routes.clj
+++ b/src/metabase/api_routes/routes.clj
@@ -70,6 +70,7 @@
[metabase.transforms-rest.api.transform]
[metabase.transforms-rest.api.transform-job]
[metabase.transforms-rest.api.transform-tag]
+ [metabase.typed-schemas.api]
[metabase.upload.api]
[metabase.user-key-value.api]
[metabase.users-rest.api]
@@ -125,6 +126,7 @@
metabase.transforms-rest.api.transform/keep-me
metabase.transforms-rest.api.transform-job/keep-me
metabase.transforms-rest.api.transform-tag/keep-me
+ metabase.typed-schemas.api/keep-me
metabase.upload.api/keep-me
metabase.user-key-value.api/keep-me
metabase.users-rest.api/keep-me
@@ -243,6 +245,7 @@
"/transform" (+auth metabase.transforms-rest.api.transform/routes)
"/transform-job" (+auth metabase.transforms-rest.api.transform/transform-job-routes)
"/transform-tag" (+auth metabase.transforms-rest.api.transform/transform-tag-routes)
+ "/typed-schemas" (+auth metabase.typed-schemas.api/routes)
"/upload" (+auth 'metabase.upload.api)
"/user" (+auth 'metabase.users-rest.api)
"/user-key-value" (+auth 'metabase.user-key-value.api)
diff --git a/src/metabase/internal_stats/core.clj b/src/metabase/internal_stats/core.clj
index f7f9fe1124e..8c0d827165c 100644
--- a/src/metabase/internal_stats/core.clj
+++ b/src/metabase/internal_stats/core.clj
@@ -1,5 +1,6 @@
(ns metabase.internal-stats.core
(:require
+ [metabase.internal-stats.data-apps :as data-app-stats]
[metabase.internal-stats.embedding :as embedding-stats]
[metabase.internal-stats.metabot :as metabot-stats]
[metabase.internal-stats.query-executions :as query-execution-stats]
@@ -7,6 +8,10 @@
[metabase.internal-stats.users :as user-stats]
[potemkin :as p]))
+(p/import-vars
+ [data-app-stats
+ data-app-stats])
+
(p/import-vars
[embedding-stats
embedding-dashboard-count
diff --git a/src/metabase/internal_stats/data_apps.clj b/src/metabase/internal_stats/data_apps.clj
new file mode 100644
index 00000000000..36dd4328649
--- /dev/null
+++ b/src/metabase/internal_stats/data_apps.clj
@@ -0,0 +1,9 @@
+(ns metabase.internal-stats.data-apps
+ (:require
+ [toucan2.core :as t2]))
+
+(defn data-app-stats
+ "How many data apps this instance actually serves: enabled and synced without
+ error (`sync_error IS NULL`), matching what the UI treats as an openable app."
+ []
+ {:data-app-count (t2/count :data_app :enabled true :sync_error nil)})
diff --git a/src/metabase/lib/query/test_spec.cljc b/src/metabase/lib/query/test_spec.cljc
index 1d80cbe3373..84e29ff994d 100644
--- a/src/metabase/lib/query/test_spec.cljc
+++ b/src/metabase/lib/query/test_spec.cljc
@@ -44,10 +44,12 @@
(mu/defn- matches-column? :- :boolean
[query :- ::lib.schema/query
_stage-number :- :int
- {:keys [name source-name display-name]} :- ::lib.schema.test-spec/test-column-spec
+ {:keys [name table-id source-name source-field-id display-name]} :- ::lib.schema.test-spec/test-column-spec
column :- ::lib.schema.metadata/column]
(cond-> (= name (:name column))
+ (some? table-id) (and (= table-id (:table-id column)))
(some? source-name) (and (= source-name (some->> column :table-id (lib.metadata/table query) :name)))
+ (some? source-field-id) (and (= source-field-id ((some-fn :fk-field-id :lib/original-fk-field-id) column)))
(some? display-name) (and (= display-name (:display-name column)))))
(mu/defn- find-column :- ::lib.schema.metadata/column
@@ -259,26 +261,46 @@
(mu/defn- append-filter :- ::lib.schema/query
[query :- ::lib.schema/query
stage-number :- :int
- filter-spec :- ::lib.schema.test-spec/test-expression-spec]
- (->> (lib.filter/filterable-columns query stage-number)
- (expression-spec->expression-clause query stage-number filter-spec)
- (lib.filter/filter query stage-number)))
+ filter-spec :- [:or ::lib.schema.test-spec/test-expression-spec ::lib.schema.test-spec/test-segment-spec]]
+ (if (= (keyword (:type filter-spec)) :segment)
+ (if-let [segment (lib.metadata/segment query (:id filter-spec))]
+ (lib.filter/filter query stage-number segment)
+ (throw (ex-info "No segment found" {:segment-spec filter-spec})))
+ (->> (lib.filter/filterable-columns query stage-number)
+ (expression-spec->expression-clause query stage-number filter-spec)
+ (lib.filter/filter query stage-number))))
(mu/defn- append-filters :- ::lib.schema/query
[query :- ::lib.schema/query
stage-number :- :int
- filter-specs :- [:sequential ::lib.schema.test-spec/test-expression-spec]]
+ filter-specs :- [:sequential [:or ::lib.schema.test-spec/test-expression-spec
+ ::lib.schema.test-spec/test-segment-spec]]]
(reduce #(append-filter %1 stage-number %2)
query
filter-specs))
+(mu/defn- saved-aggregation-spec? :- :boolean
+ [aggregation-spec :- ::lib.schema.test-spec/test-aggregation-spec]
+ (boolean (#{:measure :metric} (keyword (:type aggregation-spec)))))
+
+(mu/defn- saved-aggregation :- [:maybe [:or ::lib.schema.metadata/measure ::lib.schema.metadata/metric]]
+ [query :- ::lib.schema/query
+ aggregation-spec :- ::lib.schema.test-spec/test-aggregation-spec]
+ (case (keyword (:type aggregation-spec))
+ :measure (lib.metadata/measure query (:id aggregation-spec))
+ :metric (lib.metadata/metric query (:id aggregation-spec))))
+
(mu/defn- append-aggregation :- ::lib.schema/query
[query :- ::lib.schema/query
stage-number :- :int
aggregation-spec :- ::lib.schema.test-spec/test-aggregation-spec]
- (->> (lib.aggregation/aggregable-columns query stage-number)
- (expression-spec->expression-clause query stage-number aggregation-spec)
- (lib.aggregation/aggregate query stage-number)))
+ (if (saved-aggregation-spec? aggregation-spec)
+ (if-let [aggregation (saved-aggregation query aggregation-spec)]
+ (lib.aggregation/aggregate query stage-number aggregation)
+ (throw (ex-info "No saved aggregation found" {:aggregation-spec aggregation-spec})))
+ (->> (lib.aggregation/aggregable-columns query stage-number)
+ (expression-spec->expression-clause query stage-number aggregation-spec)
+ (lib.aggregation/aggregate query stage-number))))
(mu/defn- append-aggregations :- ::lib.schema/query
[query :- ::lib.schema/query
diff --git a/src/metabase/lib/schema/test_spec.cljc b/src/metabase/lib/schema/test_spec.cljc
index 35101d55558..d0dffa622b9 100644
--- a/src/metabase/lib/schema/test_spec.cljc
+++ b/src/metabase/lib/schema/test_spec.cljc
@@ -31,7 +31,9 @@
[:map
[:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :column]]
[:name string?]
+ [:table-id {:optional true} [:maybe ::lib.schema.id/table]]
[:source-name {:optional true} [:maybe string?]]
+ [:source-field-id {:optional true} [:maybe ::lib.schema.id/field]]
[:display-name {:optional true} [:maybe string?]]
[:index {:optional true} [:maybe pos-int?]]])
@@ -87,11 +89,26 @@
[:literal [:ref ::test-literal-expression-spec]]
[:operator [:ref ::test-operator-expression-spec]]])
+(mr/def ::test-segment-spec
+ [:map
+ [:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :segment]]
+ [:id [:ref ::lib.schema.id/segment]]])
+
(mr/def ::test-named-expression-spec
[:map
[:name string?]
[:value [:ref ::test-expression-spec]]])
+(mr/def ::test-measure-spec
+ [:map
+ [:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :measure]]
+ [:id [:ref ::lib.schema.id/measure]]])
+
+(mr/def ::test-metric-spec
+ [:map
+ [:type [:= {:decode/normalize lib.schema.common/normalize-keyword} :metric]]
+ [:id [:ref ::lib.schema.id/metric]]])
+
(mr/def ::test-join-spec
[:map
[:source [:ref ::test-source-spec]]
@@ -113,7 +130,9 @@
(mr/def ::test-aggregation-spec
[:or
[:ref ::test-expression-spec]
- [:ref ::test-named-expression-spec]])
+ [:ref ::test-named-expression-spec]
+ [:ref ::test-measure-spec]
+ [:ref ::test-metric-spec]])
(mr/def ::test-stage-spec
[:map
@@ -121,7 +140,7 @@
[:fields {:optional true} [:maybe [:sequential ::test-column-spec]]]
[:expressions {:optional true} [:maybe [:sequential ::test-named-expression-spec]]]
[:joins {:optional true} [:maybe [:sequential ::test-join-spec]]]
- [:filters {:optional true} [:maybe [:sequential ::test-expression-spec]]]
+ [:filters {:optional true} [:maybe [:sequential [:or ::test-expression-spec ::test-segment-spec]]]]
[:aggregations {:optional true} [:maybe [:sequential ::test-aggregation-spec]]]
[:breakouts {:optional true} [:maybe [:sequential ::test-breakout-spec]]]
[:order-bys {:optional true} [:maybe [:sequential ::test-order-by-spec]]]
diff --git a/src/metabase/metabot/core.clj b/src/metabase/metabot/core.clj
index 307dd415acc..934ed459f3d 100644
--- a/src/metabase/metabot/core.clj
+++ b/src/metabase/metabot/core.clj
@@ -4,6 +4,8 @@
[metabase.metabot.provider-util]
[metabase.metabot.scope]
[metabase.metabot.search-models]
+ [metabase.metabot.tools.entity-details]
+ [metabase.metabot.tools.util]
[metabase.metabot.usage]
[potemkin :as p]))
@@ -32,6 +34,14 @@
entity-type->search-model
search-model->entity-type])
+(p/import-vars
+ [metabase.metabot.tools.entity-details
+ get-metric-details
+ get-report-details
+ get-table-details]
+ [metabase.metabot.tools.util
+ ->result-column])
+
(p/import-vars
[metabase.metabot.usage
check-usage-limits!
diff --git a/src/metabase/metabot/tools/entity_details.clj b/src/metabase/metabot/tools/entity_details.clj
index d08171c1a57..a9378c20fc3 100644
--- a/src/metabase/metabot/tools/entity_details.clj
+++ b/src/metabase/metabot/tools/entity_details.clj
@@ -477,13 +477,14 @@
(merge related)))))
(defn cards-details
- "Get the details of metrics or models as specified by `card-type` and `cards`
+ "Get the details of metrics, models, or questions as specified by `card-type` and `cards`
from the database with ID `database-id` respecting `options`."
[card-type database-id cards options]
(let [mp (lib-be/application-database-metadata-provider database-id)
detail-fn (case card-type
:metric metric-details
- :model card-details)]
+ :model card-details
+ :question card-details)]
(lib.metadata/bulk-metadata mp :metadata/card (map :id cards))
(map #(-> (detail-fn % mp (u/assoc-default options :field-values-fn identity))
(assoc :type card-type))
diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.clj
index 6e061488335..b76d315b464 100644
--- a/src/metabase/models/resolution.clj
+++ b/src/metabase/models/resolution.clj
@@ -34,6 +34,7 @@
:model/ConnectionImpersonation metabase-enterprise.impersonation.models
:model/ContentTranslation metabase.content-translation.models
:model/CustomVizPlugin metabase-enterprise.custom-viz-plugin.models.custom-viz-plugin
+ :model/DataApp metabase-enterprise.data-apps.models.data-app
:model/Dashboard metabase.dashboards.models.dashboard
:model/DashboardBookmark metabase.bookmarks.models.bookmark
:model/DashboardCard metabase.dashboards.models.dashboard-card
diff --git a/src/metabase/premium_features/core.clj b/src/metabase/premium_features/core.clj
index 8f7bfceda65..fce3a353eb0 100644
--- a/src/metabase/premium_features/core.clj
+++ b/src/metabase/premium_features/core.clj
@@ -59,6 +59,7 @@
enable-custom-viz?
enable-data-complexity-score?
enable-dashboard-subscription-filters?
+ enable-data-apps?
enable-database-auth-providers?
enable-database-routing?
enable-library?
diff --git a/src/metabase/premium_features/settings.clj b/src/metabase/premium_features/settings.clj
index 78de3dc67a5..8f6d0a6b370 100644
--- a/src/metabase/premium_features/settings.clj
+++ b/src/metabase/premium_features/settings.clj
@@ -293,6 +293,10 @@
"Does this instance support remote syncing collections."
:remote-sync)
+(define-premium-feature ^{:added "0.57.0"} enable-data-apps?
+ "Should we allow users to publish and run data apps?"
+ :data-apps)
+
(define-premium-feature ^{:added "0.59.0"} enable-basic-transforms?
"Should we allow users to use transforms? Replacement for transforms"
:transforms-basic)
@@ -394,6 +398,7 @@
:content_verification (enable-content-verification?)
:custom-viz (enable-custom-viz?)
:custom-viz-available (has-feature? :custom-viz)
+ :data-apps (enable-data-apps?)
:data-complexity-score (enable-data-complexity-score?)
:dashboard_subscription_filters (enable-dashboard-subscription-filters?)
:database_auth_providers (enable-database-auth-providers?)
diff --git a/src/metabase/premium_features/token_check.clj b/src/metabase/premium_features/token_check.clj
index e9b18c2ae54..3ebd9e2c624 100644
--- a/src/metabase/premium_features/token_check.clj
+++ b/src/metabase/premium_features/token_check.clj
@@ -148,6 +148,7 @@
stats (merge (internal-stats/query-execution-last-utc-day)
(embedding-settings embedding-dashboard-count embedding-question-count)
(internal-stats/metabot-stats)
+ (internal-stats/data-app-stats)
(transform-stats)
{:users users
:embedding-dashboard-count embedding-dashboard-count
diff --git a/src/metabase/request/core.clj b/src/metabase/request/core.clj
index a1dec666280..909d0a7edf1 100644
--- a/src/metabase/request/core.clj
+++ b/src/metabase/request/core.clj
@@ -55,6 +55,9 @@
api-call?
auth-call?
cacheable?
+ data-app-embed-prefix
+ data-app-url-segment
+ data-app?
device-info
embed?
embedded?
diff --git a/src/metabase/request/util.clj b/src/metabase/request/util.clj
index bfa0e3bbb0e..221790e63b4 100644
--- a/src/metabase/request/util.clj
+++ b/src/metabase/request/util.clj
@@ -39,6 +39,27 @@
[{:keys [uri]}]
(re-matches #"^/embed/.*$" uri))
+(def data-app-url-segment
+ "URL path segment identifying data-app routes. Single source of truth on the
+ BE: the `/apps` page route, the `/embed/apps` iframe prefix, and the
+ `/api/apps` API mount all derive from it (mirrors the FE
+ `DATA_APP_URL_SEGMENT`)."
+ "apps")
+
+(def data-app-embed-prefix
+ "URL prefix the BE serves the internal data-app iframe entrypoint at."
+ (str "/embed/" data-app-url-segment))
+
+(def ^:private data-app-uri-regex
+ (re-pattern (str "^" data-app-embed-prefix "/.*$")))
+
+(defn data-app?
+ "Is this ring request the internal data-app iframe entrypoint (`/embed/apps/...`)?
+ It is only ever framed by the same-origin Metabase app, so it gets
+ `frame-ancestors 'self'` rather than the open embedding `*`."
+ [{:keys [uri]}]
+ (re-matches data-app-uri-regex uri))
+
(defn cacheable?
"Can the ring request be permanently cached?"
[{:keys [request-method uri], :as _request}]
diff --git a/src/metabase/server/middleware/security.clj b/src/metabase/server/middleware/security.clj
index dc2b7369aa8..be42472913f 100644
--- a/src/metabase/server/middleware/security.clj
+++ b/src/metabase/server/middleware/security.clj
@@ -9,9 +9,11 @@
[metabase.config.core :as config]
[metabase.embedding.settings :as embedding.settings]
[metabase.mcp.core :as mcp]
+ [metabase.premium-features.core :refer [defenterprise]]
[metabase.request.core :as request]
[metabase.server.settings :as server.settings]
[metabase.settings.core :as setting]
+ [metabase.system.core :as system]
[metabase.util :as u]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
@@ -222,9 +224,19 @@
(def ^:private frontend-address (str "http://localhost:" frontend-dev-port))
(def ^:private cljs-dev-port (or (env/env :mb-cljs-dev-port) "9630"))
+(defenterprise data-app-connect-src-hosts
+ "Origins the data app identified by `slug` may reach (its `allowed_hosts`),
+ added to the data-app iframe document's CSP `connect-src` so the sandboxed
+ bundle can `fetch`/XHR them. Returns `[]` in OSS, when the `:data-apps`
+ feature is absent, or when there's no enabled app for `slug`. EE
+ implementation: [[metabase-enterprise.data-apps.csp]]."
+ metabase-enterprise.data-apps.csp
+ [_slug]
+ [])
+
(defn- content-security-policy-header
"`Content-Security-Policy` header. See https://content-security-policy.com for more details."
- [nonce]
+ [nonce data-app-iframe? data-app-connect-hosts]
{"Content-Security-Policy"
(str/join
(for [[k vs] {:default-src ["'none'"]
@@ -250,14 +262,26 @@
(when config/is-dev?
["'unsafe-eval'"
(str "http://localhost:" cljs-dev-port)])
+ ;; Custom data apps run their uploaded bundle inside a Near-Membrane
+ ;; sandbox, which executes the bundle source via `eval` (its sandbox
+ ;; lives in a same-origin child iframe that inherits this document's
+ ;; CSP). So the data-app entrypoint must allow 'unsafe-eval' — scoped
+ ;; to this route only; the main app CSP stays strict.
+ (when data-app-iframe?
+ ["'unsafe-eval'"])
(when-not config/is-dev?
(map (partial format "'sha256-%s'") inline-js-hashes)))
:child-src ["'self'"
"https://accounts.google.com"]
:style-src ["'self'"
- ;; See [[generate-nonce]]
- (when nonce
+ ;; See [[generate-nonce]].
+ (when (and nonce (not data-app-iframe?))
(format "'nonce-%s'" nonce))
+ ;; Custom data apps render into an isolated iframe whose outer document only owns
+ ;; the iframe boundary. Allowing inline styles here lets single-file uploaded apps
+ ;; style their own sandboxed document without relaxing the main app CSP.
+ (when data-app-iframe?
+ "'unsafe-inline'")
;; for webpack hot reloading
(when config/is-dev?
frontend-address)
@@ -266,44 +290,93 @@
(str "http://localhost:" cljs-dev-port))
"https://accounts.google.com"]
:style-src-attr ["'self'"]
- :frame-src (parse-allowed-iframe-hosts (server.settings/allowed-iframe-hosts))
+ :frame-src (if (some? data-app-connect-hosts)
+ ;; Data-app docs get a per-app framing allowlist:
+ ;; only `'self'` and the origins the app declared
+ ;; in `allowed_hosts` — NOT the instance-wide iframe
+ ;; hosts, so a data app can't frame those unless it
+ ;; lists them itself.
+ (into ["'self'"] data-app-connect-hosts)
+ (parse-allowed-iframe-hosts (server.settings/allowed-iframe-hosts)))
:font-src (into (cond-> always-allowed-resource-hosts
config/is-dev? (conj frontend-address))
(application-font-files->hosts))
- :img-src (if (server.settings/csp-img-enabled)
- (cond-> (into (parse-allowed-resource-hosts (server.settings/csp-img-allowed-hosts))
- (map-tile-server->hosts))
- config/is-dev? (conj frontend-address))
- (into ["*"] always-allowed-resource-hosts))
- :connect-src ["'self'"
- ;; Google Identity Services
- "https://accounts.google.com"
- ;; MailChimp. So people can sign up for the Metabase mailing list in the sign up process
- "metabase.us10.list-manage.com"
- ;; Snowplow analytics
- (when (analytics/anon-tracking-enabled)
- (setting/get-value-of-type :string :snowplow-url))
- (when (analytics/anon-tracking-enabled)
- (setting/get-value-of-type :string :metaplow-url))
- ;; Webpack dev server
- (when config/is-dev?
- (str "*:" frontend-dev-port " ws://*:" frontend-dev-port))
- ;; CLJS REPL
- (when config/is-dev?
- (str "ws://*:" cljs-dev-port))]
+ :img-src (cond-> (if (server.settings/csp-img-enabled)
+ (cond-> (into (parse-allowed-resource-hosts (server.settings/csp-img-allowed-hosts))
+ (map-tile-server->hosts))
+ config/is-dev? (conj frontend-address))
+ (into ["*"] always-allowed-resource-hosts))
+ ;; Data apps need blob: to load icons for custom viz
+ data-app-iframe? (conj "blob:"))
+ :connect-src (into
+ ["'self'"
+ ;; Google Identity Services
+ "https://accounts.google.com"
+ ;; MailChimp. So people can sign up for the Metabase mailing list in the sign up process
+ "metabase.us10.list-manage.com"
+ ;; Snowplow analytics
+ (when (analytics/anon-tracking-enabled)
+ (setting/get-value-of-type :string :snowplow-url))
+ (when (analytics/anon-tracking-enabled)
+ (setting/get-value-of-type :string :metaplow-url))
+ ;; Webpack dev server
+ (when config/is-dev?
+ (str "*:" frontend-dev-port " ws://*:" frontend-dev-port))
+ ;; CLJS REPL
+ (when config/is-dev?
+ (str "ws://*:" cljs-dev-port))]
+ ;; Per-app `allowed_hosts` for the data-app iframe document, so its
+ ;; sandboxed bundle can fetch/XHR the origins the app declared. Added
+ ;; separately from `'self'` (which stays for the host-side SDK calls).
+ (when data-app-iframe? data-app-connect-hosts))
:manifest-src ["'self'"]
:media-src ["www.metabase.com"]}]
(format "%s %s; " (name k) (str/join " " vs))))})
+(defn- interactive-embedding-origins
+ "The configured interactive-embedding app origins, when interactive embedding is
+ enabled; otherwise nil."
+ []
+ (and (setting/get-value-of-type :boolean :enable-embedding-interactive)
+ (setting/get-value-of-type :string :embedding-app-origins-interactive)))
+
+(defn- frame-ancestors-value
+ "The `frame-ancestors` CSP source-list for a given framing `mode`:
+ `:any` (open embedding), `:self` (same-origin only, e.g. the internal data-app
+ iframe), or `:none` (no framing, unless interactive embedding is configured)."
+ [mode]
+ (case mode
+ :any "*"
+ :self "'self'"
+ (or (interactive-embedding-origins) "'none'")))
+
(defn- content-security-policy-header-with-frame-ancestors
- [allow-iframes? nonce]
- (update (content-security-policy-header nonce)
- "Content-Security-Policy"
- #(format "%s frame-ancestors %s;" % (if allow-iframes? "*"
- (if-let [eao (and (setting/get-value-of-type :boolean :enable-embedding-interactive)
- (setting/get-value-of-type :string :embedding-app-origins-interactive))]
- eao
- "'none'")))))
+ [frame-ancestors-mode nonce data-app-iframe? data-app-connect-hosts]
+ (cond-> (update (content-security-policy-header nonce data-app-iframe? data-app-connect-hosts)
+ "Content-Security-Policy"
+ #(format "%s frame-ancestors %s;" % (frame-ancestors-value frame-ancestors-mode)))
+ ;; Restrict native `<form action="…">` submissions to the app's declared
+ ;; `allowed_hosts` (mirroring `connect-src`); with none declared this is
+ ;; `'none'`, blocking every native submit. `form-action` does not fall back to
+ ;; `default-src`, so it must be set explicitly. Client-side `onSubmit` handlers
+ ;; are unaffected — they `preventDefault`, so no submission is ever checked.
+ data-app-iframe? (update "Content-Security-Policy"
+ #(str % " form-action "
+ (if (seq data-app-connect-hosts)
+ (str/join " " data-app-connect-hosts)
+ "'none'")
+ ";"))))
+
+(defn- x-frame-options-header
+ "Legacy `X-Frame-Options` companion to the CSP `frame-ancestors` (for browsers
+ that don't honor the latter). Omitted for `:any` (open embedding)."
+ [mode]
+ (case mode
+ :any nil
+ :self {"X-Frame-Options" "SAMEORIGIN"}
+ {"X-Frame-Options" (if-let [eao (interactive-embedding-origins)]
+ (format "ALLOW-FROM %s" (-> eao (str/split #" ") first))
+ "DENY")}))
(defn approved-domain?
"Checks if the domain is compatible with the reference one"
@@ -389,20 +462,19 @@
"Access-Control-Max-Age" "60"}))))
(defn security-headers
- "Fetch a map of security headers that should be added to a response based on the passed options."
- [& {:keys [origin nonce allow-iframes? allow-cache?]
- :or {allow-iframes? false, allow-cache? false}}]
+ "Fetch a map of security headers that should be added to a response based on the passed options.
+ `:frame-ancestors` controls clickjacking protection: `:any` (open embedding),
+ `:self` (same-origin only), or `:none` (default — no framing unless interactive
+ embedding is configured)."
+ [& {:keys [origin nonce frame-ancestors allow-cache? data-app-iframe? data-app-connect-hosts]
+ :or {frame-ancestors :none, allow-cache? false, data-app-iframe? false}}]
(merge
(if allow-cache? cache-far-future-headers (cache-prevention-headers))
strict-transport-security-header
- (content-security-policy-header-with-frame-ancestors allow-iframes? nonce)
+ (content-security-policy-header-with-frame-ancestors frame-ancestors nonce data-app-iframe? data-app-connect-hosts)
(access-control-headers origin (embedding.settings/embedding-app-origins-sdk))
- (when-not allow-iframes?
- ;; Tell browsers not to render our site as an iframe (prevent clickjacking)
- {"X-Frame-Options" (if-let [eao (and (setting/get-value-of-type :boolean :enable-embedding-interactive)
- (setting/get-value-of-type :string :embedding-app-origins-interactive))]
- (format "ALLOW-FROM %s" (-> eao (str/split #" ") first))
- "DENY")})
+ ;; Tell browsers not to render our site as an iframe (prevent clickjacking)
+ (x-frame-options-header frame-ancestors)
{;; Prevent Flash / PDF files from including content from site.
"X-Permitted-Cross-Domain-Policies" "none"
;; Tell browser not to use MIME sniffing to guess types of files -- protect against MIME type confusion attacks
@@ -421,13 +493,67 @@
(or (= (:request-method request) :options)
(contains? #{400 402} (:status response)))))
+(defn- data-app-iframe-request?
+ [request]
+ (str/starts-with? (:uri request) (str request/data-app-embed-prefix "/")))
+
+(def ^:private data-app-slug-regex
+ (re-pattern (str "/(?:embed/)?" request/data-app-url-segment "/([^/]+).*")))
+
+(defn- data-app-slug
+ "Slug of the data-app document being served, parsed from the top-level
+ `/apps/<slug>` page or the internal `/embed/apps/<slug>` iframe (and
+ any deeper sub-route), or nil. The top page needs it too: its `frame-src`
+ governs what the iframe below it may navigate to."
+ [request]
+ (second (re-matches data-app-slug-regex (:uri request))))
+
+(defn- site-origin
+ "This Metabase instance's origin as `{:protocol :domain :port}` (parsed from
+ `site-url`), or nil. Matches the shape [[parse-url]] returns so origins compare
+ with `=`."
+ []
+ (when-let [url (not-empty (system/site-url))]
+ (try
+ (let [^URI uri (URI. ^String url)]
+ (when-let [host (.getHost uri)]
+ {:protocol (.getScheme uri)
+ :domain host
+ :port (let [p (.getPort uri)] (when-not (neg? p) (str p)))}))
+ (catch Exception _ nil))))
+
+(defn- drop-instance-origin
+ "Removes any `allowed_hosts` entry that resolves to this Metabase instance's own
+ origin. A native `<form>` submit or frame to the instance would carry the
+ user's session cookies, and the SDK is the only sanctioned way to reach
+ Metabase — so we keep the instance out of the app's `form-action`/`frame-src`/
+ `connect-src` even when an app mistakenly lists it (mirroring the JS fetch/XHR
+ sandbox, which blocks the instance origin regardless)."
+ [hosts]
+ (if-let [self (site-origin)]
+ (remove #(= self (parse-url %)) hosts)
+ hosts))
+
(defn- add-security-headers* [request response]
;; merge is other way around so that handler can override headers
(let [headers (security-headers
- :origin (get (:headers request) "origin")
- :nonce (:nonce request)
- :allow-iframes? ((some-fn request/public? request/embed?) request)
- :allow-cache? (request/cacheable? request))
+ :origin (get (:headers request) "origin")
+ :nonce (:nonce request)
+ ;; The internal data-app iframe is only ever framed by the
+ ;; same-origin Metabase app, so restrict it to `'self'` rather
+ ;; than the open embedding `*`. Check it before the broader
+ ;; `embed?`, which `/embed/apps/...` also matches.
+ :frame-ancestors (cond
+ (request/data-app? request) :self
+ ((some-fn request/public? request/embed?) request) :any
+ :else :none)
+ :allow-cache? (request/cacheable? request)
+ :data-app-iframe? (data-app-iframe-request? request)
+ ;; Per-app `allowed_hosts` → `connect-src`/`form-action` (iframe
+ ;; doc) and `frame-src` (both the iframe doc and the top page,
+ ;; whose `frame-src` gates the iframe's own navigations).
+ :data-app-connect-hosts (when-let [slug (data-app-slug request)]
+ (drop-instance-origin (data-app-connect-src-hosts slug))))
cors-headers (when (always-allow-cors? request response)
{"Access-Control-Allow-Origin" "*"
"Access-Control-Allow-Headers" "*"
diff --git a/src/metabase/server/routes.clj b/src/metabase/server/routes.clj
index 94f1715581b..9972562b51c 100644
--- a/src/metabase/server/routes.clj
+++ b/src/metabase/server/routes.clj
@@ -10,6 +10,7 @@
[metabase.initialization-status.core :as init-status]
[metabase.oauth-server.api :as oauth-server.api]
[metabase.query-processor.schema :as qp.schema]
+ [metabase.request.core :as request]
[metabase.server.auth-wrapper :as auth-wrapper]
[metabase.server.middleware.embedding-sdk-bundle :as mw.embedding-sdk-bundle]
[metabase.server.routes.index :as index]
@@ -41,6 +42,11 @@
#_{:clj-kondo/ignore [:discouraged-var]}
(defroutes ^:private ^{:arglists '([request respond raise])} embed-routes
(GET "/sdk/v1" [] index/embed-sdk)
+ ;; Same `data-app.html` for the bare path and any deeper sub-route — the
+ ;; iframe's React Router owns the sub-path; reloads at an inner URL still
+ ;; have to serve the SPA shell.
+ (GET [(str "/" request/data-app-url-segment "/:name"), :name #"[^/]+"] [] index/data-app)
+ (GET [(str "/" request/data-app-url-segment "/:name/*"), :name #"[^/]+"] [] index/data-app)
(GET ["/question/:token.:export-format", :export-format qp.schema/export-formats-regex]
[token export-format]
(redirect-including-query-string (format "%s/api/embed/card/%s/query/%s" (system/site-url) token export-format)))
diff --git a/src/metabase/server/routes/index.clj b/src/metabase/server/routes/index.clj
index a68f0c6c32b..0c811a0b629 100644
--- a/src/metabase/server/routes/index.clj
+++ b/src/metabase/server/routes/index.clj
@@ -127,3 +127,4 @@
(def public "/public index.html entrypoint." (partial entrypoint "public" :embeddable))
(def embed "/embed index.html entrypoint." (partial entrypoint "embed" :embeddable))
(def embed-sdk "/embed/sdk/v1 index.html entrypoint." (partial entrypoint "embed-sdk" :embeddable))
+(def data-app "/embed/apps/:name iframe entrypoint." (partial entrypoint "data-app" :embeddable))
diff --git a/src/metabase/typed_schemas/api.clj b/src/metabase/typed_schemas/api.clj
new file mode 100644
index 00000000000..5d13bfb828a
--- /dev/null
+++ b/src/metabase/typed_schemas/api.clj
@@ -0,0 +1,133 @@
+(ns metabase.typed-schemas.api
+ "/api/typed-schemas endpoints."
+ (:require
+ [clojure.set :as set]
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.typed-schemas.api.render :as render]
+ [metabase.typed-schemas.api.schema :as schema]
+ [metabase.typed-schemas.api.schema.metric :as schema.metric]
+ [metabase.typed-schemas.api.schema.model :as schema.model]
+ [metabase.typed-schemas.api.schema.question :as schema.question]
+ [metabase.typed-schemas.api.schema.table :as schema.table]
+ [metabase.typed-schemas.api.scope :as scope]
+ [metabase.util.malli.schema :as ms]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private typescript-response-headers
+ {"Content-Type" "text/typescript; charset=utf-8"
+ "X-Content-Type-Options" "nosniff"
+ "Cross-Origin-Resource-Policy" "same-origin"
+ "Referrer-Policy" "no-referrer"
+ "Cache-Control" "no-store"})
+
+(defn- validate-query-params!
+ [query-params]
+ (let [library-value (scope/query-library-value query-params)
+ library-collection-values (scope/query-library-collection-values query-params)
+ question-collection-values (scope/query-question-collection-values query-params)
+ include-library-root? (or (scope/query-include-data-library? query-params)
+ (scope/query-include-metric-library? query-params))
+ collection-scoped? (or library-value
+ library-collection-values
+ question-collection-values
+ include-library-root?)
+ database-value (scope/query-database-value query-params)
+ questions-only (scope/truthy-query-param? (:questions query-params))]
+ (api/check-400
+ (not (and library-value (or library-collection-values include-library-root?)))
+ "The library query parameter is mutually exclusive with library-collections, include-data-library, and include-metric-library.")
+ (api/check-400
+ (not (and collection-scoped? database-value))
+ "Collection-scoped query parameters and database query parameters are mutually exclusive.")
+ (api/check-400
+ (not (and collection-scoped? questions-only))
+ "Collection-scoped query parameters and the questions query parameter are mutually exclusive.")
+ (api/check-400
+ (not (and questions-only (nil? database-value)))
+ "The questions query parameter requires a database query parameter.")))
+
+(defn- typed-schema-for-library-scope
+ [library-scope models]
+ (let [{:keys [metric-collection-ids]} library-scope
+ metrics (schema.metric/metric-schemas nil metric-collection-ids)
+ mapped-table-ids (->> metrics (mapcat :mappedTableIds) set)
+ library-table-ids (->> (schema.table/select-library-tables library-scope) (map :id) set)
+ table-ids (set/union library-table-ids mapped-table-ids)
+ tables (schema.table/table-schemas (schema.table/select-tables nil table-ids))]
+ (schema/base-schema [] models tables metrics)))
+
+(defn- typed-schema
+ [query-params]
+ (validate-query-params! query-params)
+ (let [library-value (scope/query-library-value query-params)
+ library-collection-values (scope/query-library-collection-values query-params)
+ question-collection-values (scope/query-question-collection-values query-params)
+ library-scope (scope/library-scope query-params)
+ database-ids (scope/database-ids-for-value (scope/query-database-value query-params))
+ question-collection-ids (scope/collection-scope question-collection-values)
+ include-models? (scope/query-include-models? query-params)
+ models (cond
+ database-ids
+ (schema.model/model-schemas database-ids)
+
+ include-models?
+ (schema.model/model-schemas nil)
+
+ :else
+ [])
+ questions-only (scope/truthy-query-param? (:questions query-params))]
+ (cond
+ (or library-value
+ library-collection-values
+ library-scope
+ question-collection-values
+ (and include-models? (nil? database-ids)))
+ (let [questions (if question-collection-values
+ (schema.question/question-schemas nil question-collection-ids)
+ [])
+ library-schema (some-> library-scope
+ (typed-schema-for-library-scope models))]
+ (schema/base-schema questions
+ models
+ (-> library-schema :tables vals)
+ (-> library-schema :metrics vals)))
+
+ questions-only
+ (schema/base-schema (schema.question/question-schemas database-ids) models [] [])
+
+ :else
+ (let [questions (schema.question/question-schemas database-ids)
+ metrics (schema.metric/metric-schemas database-ids)
+ tables (schema.table/table-schemas (schema.table/select-tables database-ids))]
+ (schema/base-schema questions models tables metrics)))))
+
+(def ^:private TypedSchemaQueryParams
+ [:map
+ [:database {:optional true} [:maybe ms/NonBlankString]]
+ [:database-name {:optional true} [:maybe ms/NonBlankString]]
+ [:library {:optional true} [:maybe ms/NonBlankString]]
+ [:library-collections {:optional true} [:maybe ms/NonBlankString]]
+ [:collections {:optional true} [:maybe ms/NonBlankString]]
+ [:question-collections {:optional true} [:maybe ms/NonBlankString]]
+ [:include-data-library {:optional true} [:maybe :boolean]]
+ [:include-metric-library {:optional true} [:maybe :boolean]]
+ [:include-models {:optional true} [:maybe :boolean]]
+ [:questions {:optional true} [:maybe :boolean]]])
+
+(api.macros/defendpoint :get "/v1/typescript" :- :any
+ "Generate a TypeScript semantic schema module."
+ [_route-params
+ query-params :- TypedSchemaQueryParams
+ _body
+ _request
+ respond
+ _raise]
+ (respond {:status 200
+ :headers typescript-response-headers
+ :body (render/render-typescript (typed-schema query-params))}))
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/api/typed-schemas/` routes."
+ (api.macros/ns-handler *ns*))
diff --git a/src/metabase/typed_schemas/api/common.clj b/src/metabase/typed_schemas/api/common.clj
new file mode 100644
index 00000000000..1d43d59c006
--- /dev/null
+++ b/src/metabase/typed_schemas/api/common.clj
@@ -0,0 +1,113 @@
+(ns metabase.typed-schemas.api.common
+ "Shared helpers for typed-schema generation."
+ (:require
+ [clojure.string :as str]
+ [medley.core :as m]
+ [metabase.types.core]
+ [metabase.util :as u]))
+
+(set! *warn-on-reflection* true)
+
+(comment metabase.types.core/keep-me)
+
+;; Action parameters in generated schemas use these primitive types.
+(def ^:private primitive-type->js-type
+ {:number "number"
+ :boolean "boolean"
+ :string "string"
+ :date "Date"
+ :datetime "Date"
+ :time "Date"})
+
+(defn- type-keyword
+ [schema-type]
+ (cond
+ (keyword? schema-type) schema-type
+ (string? schema-type) (let [schema-type (str/replace schema-type #"^:" "")]
+ (if (str/includes? schema-type "/")
+ (keyword schema-type)
+ (keyword "type" schema-type)))))
+
+;; Result columns and fields use Metabase base/effective types. For example,
+;; `:type/Integer` maps to "number", and `:type/UUID` maps to "string".
+(defn- schema-type->js-type
+ [schema-type]
+ (let [schema-type (type-keyword schema-type)]
+ (cond
+ (nil? schema-type) "unknown"
+ (isa? schema-type :type/Boolean) "boolean"
+ (isa? schema-type :type/Number) "number"
+ (isa? schema-type :type/Temporal) "Date"
+ (isa? schema-type :type/Text) "string"
+ (isa? schema-type :type/TextLike) "string"
+ :else "unknown")))
+
+(defn- js-type
+ [{:keys [type base_type effective_type] :as _column}]
+ (or (get primitive-type->js-type type)
+ (schema-type->js-type (or effective_type base_type))))
+
+(defn column-schema
+ "Returns the typed-schema representation for a result column or field-like map."
+ [{:keys [name display_name base_type effective_type semantic_type description unit] :as column}]
+ (let [effective-type (or effective_type base_type)]
+ (m/assoc-some
+ {:type "column"
+ :name name
+ :displayName (or display_name name)
+ :jsType (js-type column)}
+ :baseType base_type
+ :effectiveType (when (not= effective-type base_type) effective-type)
+ :semanticType semantic_type
+ :description description
+ :unit unit)))
+
+(defn generated-key
+ "Returns a stable JavaScript object key for an entity name and id."
+ [entity-name id]
+ (let [generated-key (some-> entity-name u/->camelCaseEn)]
+ (if (str/blank? generated-key)
+ (str "entity" id)
+ generated-key)))
+
+(defn pascal-case
+ "Capitalizes the first character of string without changing the rest."
+ [string]
+ (when-not (str/blank? string)
+ (str (u/upper-case-en (subs string 0 1))
+ (subs string 1))))
+
+(defn- duplicate-key?
+ [key->count key]
+ (> (get key->count key 0) 1))
+
+(defn- keyed-map-candidate-key
+ [key->count {:keys [key id]
+ key-disambiguator :keyDisambiguator
+ table-id :tableId}]
+ (cond-> key
+ (duplicate-key? key->count key) (str (or key-disambiguator table-id id))))
+
+(defn keyed-map
+ "Returns a sorted map keyed by each entity key, disambiguating duplicate keys."
+ [entities]
+ (let [entities (vec entities)
+ base-key->count (frequencies (map :key entities))
+ candidate-keys (mapv (partial keyed-map-candidate-key base-key->count) entities)
+ candidate->count (frequencies candidate-keys)]
+ (into (sorted-map)
+ (map (fn [[entity candidate-key]]
+ (let [key (cond-> candidate-key
+ (duplicate-key? candidate->count candidate-key) (str (:id entity)))]
+ [key (-> entity
+ (dissoc :keyDisambiguator)
+ (assoc :key key))])))
+ (map vector entities candidate-keys))))
+
+(defn keyed-model-map
+ "Returns a sorted model map keyed by model key, exposing only action namespaces."
+ [models]
+ (reduce-kv (fn [model-map model-key model]
+ (assoc model-map model-key (select-keys model [:actions])))
+ (sorted-map)
+ (keyed-map models)))
diff --git a/src/metabase/typed_schemas/api/javascript.clj b/src/metabase/typed_schemas/api/javascript.clj
new file mode 100644
index 00000000000..7e6c5435867
--- /dev/null
+++ b/src/metabase/typed_schemas/api/javascript.clj
@@ -0,0 +1,172 @@
+(ns metabase.typed-schemas.api.javascript
+ "JavaScript syntax rendering helpers for typed schemas."
+ (:require
+ [clojure.string :as str]
+ [metabase.util :as u]
+ [metabase.util.json :as json]))
+
+(def ^:private js-identifier-pattern
+ #"[A-Za-z_$][A-Za-z0-9_$]*")
+
+(defn- spaces
+ [indent]
+ (apply str (repeat indent " ")))
+
+(defn line-block
+ "Returns `lines` joined as a JavaScript block followed by a blank line."
+ [& lines]
+ (str (str/join "\n" lines) "\n\n"))
+
+(defn reference
+ "Returns a marker for a raw JavaScript expression.
+
+ [[render-value]] normally renders maps as object literals. Some renderer code
+ needs to splice an existing JavaScript expression into that object instead,
+ such as `tables.orders.fields` or `pickFields(...)`."
+ [path]
+ {:javascriptReference path})
+
+(defn- entry-value
+ "Returns the requested entry without invoking map lookup.
+
+ Some rendered schemas can contain sorted maps with string keys; direct keyword
+ lookup can make those maps compare keywords to strings and throw."
+ [entries-map entry-key-to-find]
+ (some (fn [[entry-key entry-value]]
+ (when (= entry-key entry-key-to-find)
+ entry-value))
+ entries-map))
+
+(defn reference?
+ "Returns true when `value` is a raw JavaScript expression marker created by [[reference]]."
+ [value]
+ (and (map? value)
+ (string? (entry-value value :javascriptReference))))
+
+(defn- javascript-key
+ "Renders a value as a JavaScript object key.
+
+ Valid identifiers render bare e.g. orders; everything else renders as a quoted
+ property name e.g. \"orders-by-month\"."
+ [entry-key]
+ (let [key-name (u/qualified-name entry-key)]
+ (if (re-matches js-identifier-pattern key-name)
+ key-name
+ (json/encode key-name))))
+
+(defn- javascript-property-access
+ "Renders property access for a JavaScript reference path segment."
+ [path-segment]
+ (let [segment-name (u/qualified-name path-segment)]
+ (if (re-matches js-identifier-pattern segment-name)
+ (str "." segment-name)
+ (str "[" (json/encode segment-name) "]"))))
+
+(defn reference-path
+ "Returns a JavaScript property path for `path-segments`."
+ [& path-segments]
+ (str (u/qualified-name (first path-segments))
+ (apply str (map javascript-property-access (rest path-segments)))))
+
+(defn- primitive-value?
+ [value]
+ (or (nil? value)
+ (string? value)
+ (number? value)
+ (true? value)
+ (false? value)))
+
+(defn string-vector
+ "Renders `values` as a JavaScript string array literal."
+ [values]
+ (str "[ " (str/join ", " (map json/encode values)) " ]"))
+
+(declare render-value*)
+
+(defn- render-node
+ "Renders one nested value with its optional leading comments and object key.
+
+ The four-argument arity is for vector items, which have comments but no key.
+ The five-argument arity is for map entries, which render `key: value`."
+ ([options indent path value]
+ (let [{:keys [item-comments]} options
+ comments (item-comments indent path value)
+ prefix (spaces indent)]
+ (str (when (seq comments)
+ (str (str/join "\n" comments) "\n"))
+ prefix
+ (render-value* value indent path options))))
+ ([options indent path entry-key value]
+ (let [{:keys [entry-comments]} options
+ comments (entry-comments indent path entry-key value)
+ prefix (spaces indent)]
+ (str (when (seq comments)
+ (str (str/join "\n" comments) "\n"))
+ prefix
+ (javascript-key entry-key)
+ ": "
+ (render-value* value indent (conj path entry-key) options)))))
+
+(defn- render-entry
+ [options indent path entry-key value]
+ (render-node options indent path entry-key value))
+
+(defn- render-map
+ "Renders a map as a JavaScript object literal.
+
+ `:map-keys` controls both key ordering and which keys are emitted."
+ [{:keys [map-keys] :as options} value indent path]
+ (let [entries (->> (map-keys path value)
+ (map (fn [entry-key]
+ (render-entry options (+ indent 2) path entry-key (get value entry-key)))))]
+ (if (seq entries)
+ (str "{\n" (str/join ",\n" entries) "\n" (spaces indent) "}")
+ "{ }")))
+
+(defn- render-vector
+ "Renders a vector as a compact array for primitive values, or multiline array otherwise."
+ [options value indent path]
+ (cond
+ (empty? value)
+ "[ ]"
+
+ (every? primitive-value? value)
+ (str "[ " (str/join ", " (map json/encode value)) " ]")
+
+ :else
+ (let [entries (map-indexed (fn [index item]
+ (render-node options (+ indent 2) (conj path index) item))
+ value)]
+ (str "[\n" (str/join ",\n" entries) "\n" (spaces indent) "]"))))
+
+(defn- render-value*
+ "Recursive implementation for [[render-value]].
+
+ `path` tracks where the value lives so callers can choose keys and comments
+ based on surrounding schema context."
+ [value indent path options]
+ (cond
+ (reference? value) (entry-value value :javascriptReference)
+ (map? value) (render-map options value indent path)
+ (vector? value) (render-vector options value indent path)
+ (seq? value) (render-vector options (vec value) indent path)
+ :else (json/encode value)))
+
+(defn render-value
+ "Renders `value` into JavaScript syntax.
+
+ Options:
+ - `:path` is the current object path.
+ - `:map-keys` returns the keys to render for a map at `[path value]`.
+ - `:entry-comments` returns comment lines before a map entry.
+ - `:item-comments` returns comment lines before a vector item."
+ ([value]
+ (render-value value {}))
+ ([value {:keys [path map-keys entry-comments item-comments]
+ :or {path []
+ map-keys (fn [_path value] (keys value))
+ entry-comments (constantly nil)
+ item-comments (constantly nil)}}]
+ (render-value* value 0 path {:map-keys map-keys
+ :entry-comments entry-comments
+ :item-comments item-comments})))
diff --git a/src/metabase/typed_schemas/api/render.clj b/src/metabase/typed_schemas/api/render.clj
new file mode 100644
index 00000000000..8745821c564
--- /dev/null
+++ b/src/metabase/typed_schemas/api/render.clj
@@ -0,0 +1,352 @@
+(ns metabase.typed-schemas.api.render
+ "TypeScript rendering for typed schemas."
+ (:require
+ [clojure.string :as str]
+ [metabase.typed-schemas.api.javascript :as javascript]
+ [metabase.util :as u]))
+
+(def ^:private const-suffix
+ " as const")
+
+;; The rendered schema serves two audiences:
+;; - `:runtime` keys are executable data consumed by the Lib.createTestQuery DSL.
+;; - `:comment` keys are emitted as nearby JavaScript comments for coding agents
+;; and humans, preserving useful context without making the runtime object
+;; larger or more ambiguous than the DSL needs.
+(def ^:private schema-render-policy
+ {:question {:runtime [:type :id :name :display :columns :parameters]
+ :comment [:entityId :description :verified]}
+ :table {:runtime [:type :id :name :fields :segments :measures]
+ :comment [:entityId :description :databaseName :schemaName :tableName]}
+ :field {:runtime [:type :name :sourceName :jsType :fieldId :tableId
+ :baseType :effectiveType :defaultTemporalBucket]
+ :comment [:displayName :description :semanticType :unit]}
+ :segment {:runtime [:type :id :tableId :name]
+ :comment [:entityId :description]}
+ :measure {:runtime [:type :id :tableId :name :columns]
+ :comment [:entityId :description]}
+ :metric {:runtime [:type :id :name :databaseId :sourceTableId :sourceCardId
+ :mappedTableIds :columns :dimensions]
+ :comment [:entityId :description :verified :sourceTable]}
+ :metric-dimension {:runtime [:type :id :fieldId :metricId :tableId :sourceName :sourceFieldId
+ :name :jsType :baseType :effectiveType :defaultTemporalBucket]
+ :comment [:displayName :description :semanticType :unit]}
+ :column {:runtime [:type :name :jsType]
+ :comment [:displayName :description :baseType :effectiveType :semanticType :unit]}})
+
+(def ^:private comment-labels
+ {:baseType "Base type"
+ :databaseName "Database"
+ :description "Description"
+ :displayName "Display name"
+ :effectiveType "Effective type"
+ :entityId "Entity ID"
+ :schemaName "Schema"
+ :semanticType "Semantic type"
+ :sourceTable "Source table"
+ :tableName "Table"
+ :unit "Unit"
+ :verified "Verified"})
+
+(defn- spaces
+ [indent]
+ (apply str (repeat indent " ")))
+
+(defn- entry-value
+ "Returns the requested entry without invoking map lookup.
+
+ Some rendered schemas can contain sorted maps with string keys; direct keyword
+ lookup can make those maps compare keywords to strings and throw."
+ [entries-map entry-key-to-find]
+ (some (fn [[entry-key entry-value]]
+ (when (= entry-key entry-key-to-find)
+ entry-value))
+ entries-map))
+
+(defn- node-kind
+ "Returns the schema node kind at `path`.
+
+ Most nodes identify themselves with `:type`, but fields/columns are also
+ inferred from their position so the renderer can apply the right runtime and
+ comment policy."
+ [path value]
+ (when (map? value)
+ (let [kind (or (entry-value value :type)
+ (entry-value value :kind))]
+ (cond
+ (= kind "card") :question
+ (= kind "question") :question
+ (= kind "table") :table
+ (= kind "segment") :segment
+ (= kind "measure") :measure
+ (= kind "metric") :metric
+ (= (last (butlast path)) :fields) :field
+ (and (= kind "column")
+ (or (= (last (butlast path)) :dimensions)
+ (= (last (drop-last 2 path)) :dimensions))) :metric-dimension
+ (= (last (butlast path)) :columns) :column
+ :else nil))))
+
+(defn- policy-runtime-keys
+ "Returns the keys that should be emitted as runtime data for a schema node."
+ [kind value]
+ (let [runtime-keys (get-in schema-render-policy [kind :runtime])]
+ (if runtime-keys
+ (->> runtime-keys
+ (filter #(contains? value %)))
+ (keys value))))
+
+(defn- redundant-table-name-comment?
+ "Returns true when a table-name comment would duplicate the object key."
+ [entry-key table-name]
+ (and (some? entry-key)
+ (some? table-name)
+ (= (name entry-key) (str table-name))))
+
+(defn- policy-comment-keys
+ "Returns the keys that should be rendered as context comments for a schema node."
+ [kind value entry-key]
+ (->> (get-in schema-render-policy [kind :comment])
+ (remove #(and (= kind :table)
+ (= % :tableName)
+ (redundant-table-name-comment? entry-key (get value %))))
+ (filter #(contains? value %))))
+
+(defn- comment-value
+ "Formats a schema value for a single-line JavaScript comment."
+ [value]
+ (cond
+ (nil? value) nil
+ (map? value) (->> [(:databaseName value) (:schemaName value) (:tableName value)]
+ (keep identity)
+ (str/join "."))
+ :else (str value)))
+
+(defn- comment-lines
+ "Returns JavaScript comment lines for context-only schema fields.
+
+ Fields listed under `:comment` in [[schema-render-policy]] are useful context
+ for humans and coding agents, but are intentionally omitted from runtime
+ objects consumed by the Lib.createTestQuery DSL."
+ [indent kind value entry-key]
+ (let [prefix (spaces indent)]
+ (for [comment-key (policy-comment-keys kind value entry-key)
+ :let [comment-text (comment-value (get value comment-key))]
+ :when (not (str/blank? comment-text))]
+ (str prefix
+ "// "
+ (get comment-labels comment-key (name comment-key))
+ ": "
+ (str/replace comment-text #"\R+" " ")))))
+
+(defn- schema-render-options
+ "Returns callbacks that adapt typed-schema render policy to [[javascript/render-value]].
+
+ The JavaScript renderer knows how to print Clojure data as JavaScript syntax.
+ These callbacks teach it which schema keys are runtime fields and which fields
+ should be emitted as nearby context comments."
+ []
+ {:map-keys (fn [path value]
+ (policy-runtime-keys (node-kind path value) value))
+ :entry-comments (fn [indent path entry-key value]
+ (comment-lines indent (node-kind (conj path entry-key) value) value entry-key))
+ :item-comments (fn [indent path value]
+ (comment-lines indent (node-kind path value) value nil))})
+
+(defn- table-fields-reference-lookup
+ "Returns table-id -> JavaScript field-map reference for tables in `schema`."
+ [schema]
+ (into {}
+ (for [[table-key {:keys [id]}] (:tables schema)
+ :when (integer? id)]
+ [id {:key table-key
+ :reference (javascript/reference-path :tables table-key :fields)}])))
+
+(defn- field-lookup-keys
+ "Returns the table-scoped lookup keys that can identify a field."
+ [table-id {:keys [fieldId name]}]
+ (cond-> []
+ (integer? fieldId) (conj [table-id fieldId])
+ (string? name) (conj [table-id name])))
+
+(defn- table-field-key-entries
+ "Returns lookup entries that map table/field identity to rendered field keys."
+ [table-id table-key fields]
+ (for [[field-key field] fields
+ lookup-key (field-lookup-keys table-id field)]
+ [lookup-key {:table-key table-key
+ :field-key field-key}]))
+
+(defn- table-field-key-lookup
+ "Returns [table-id field-id-or-name] -> rendered table/field keys for `schema`."
+ [schema]
+ (into {}
+ (mapcat (fn [[table-key {:keys [id fields]}]]
+ (when (integer? id)
+ (table-field-key-entries id table-key fields))))
+ (:tables schema)))
+
+(defn- pick-fields-call
+ "Returns a TypeScript `pickFields(...)` call for compacted metric dimensions."
+ ([fields-reference field-keys]
+ (pick-fields-call fields-reference field-keys nil))
+ ([fields-reference field-keys source-field-id]
+ (str "pickFields(" fields-reference ", " (javascript/string-vector field-keys)
+ (when (integer? source-field-id)
+ (str ", { sourceFieldId: " source-field-id " }"))
+ ")")))
+
+(defn- dimension-group-output-key
+ "Returns the output key for a compacted dimension group.
+
+ Multiple joins to the same table need source-field suffixes to stay distinct."
+ [table-key source-field-id table-key-count]
+ (if (= 1 (get table-key-count table-key))
+ table-key
+ (str table-key "Via" source-field-id)))
+
+(defn- metric-dimension-table-field
+ "Returns table field metadata when a metric dimension can be represented by `pickFields(...)`."
+ [fields-reference-by-table field-key-by-table-and-field {:keys [tableId fieldId name sourceFieldId]}]
+ (when-let [{table-key :key, :keys [reference]} (get fields-reference-by-table tableId)]
+ (when-let [{:keys [field-key]} (or (get field-key-by-table-and-field [tableId fieldId])
+ (get field-key-by-table-and-field [tableId name]))]
+ {:field-key field-key
+ :reference reference
+ :source-field-id sourceFieldId
+ :table-key table-key})))
+
+(defn- add-compact-metric-dimension-field
+ "Adds one matched metric dimension to its table/source-field compaction group."
+ [groups {:keys [field-key reference source-field-id table-key]}]
+ (update groups
+ [table-key source-field-id]
+ (fnil (fn [group]
+ (update group :field-keys conj field-key))
+ {:field-keys []
+ :reference reference
+ :source-field-id source-field-id
+ :table-key table-key})))
+
+(defn- compact-metric-dimension-fields
+ "Compacts table-backed metric dimensions into grouped JavaScript references.
+
+ Returns both the rendered `:fields` map and the original dimension keys that
+ were compacted, so raw dimensions can be preserved without another lookup pass."
+ [fields-reference-by-table field-key-by-table-and-field dimensions]
+ (let [{:keys [fields-by-group dimension-keys]}
+ (reduce (fn [acc [dimension-key dimension]]
+ (if-let [field (metric-dimension-table-field fields-reference-by-table
+ field-key-by-table-and-field
+ dimension)]
+ (-> acc
+ (update :fields-by-group add-compact-metric-dimension-field field)
+ (update :dimension-keys conj dimension-key))
+ acc))
+ {:dimension-keys #{}
+ :fields-by-group (array-map)}
+ dimensions)
+ table-key-count (frequencies (map (comp :table-key val) fields-by-group))]
+ {:dimension-keys dimension-keys
+ :fields (not-empty
+ (reduce-kv (fn [acc _ {:keys [table-key reference field-keys source-field-id]}]
+ (assoc acc
+ (dimension-group-output-key table-key source-field-id table-key-count)
+ (javascript/reference (pick-fields-call reference
+ (distinct field-keys)
+ source-field-id))))
+ (array-map)
+ fields-by-group))}))
+
+(defn- compact-metric-dimension-keys
+ "Returns original metric dimension keys represented by compacted fields."
+ [compact-fields]
+ (:dimension-keys compact-fields))
+
+(defn- raw-metric-dimension-fields
+ "Returns non-compacted metric dimensions as raw runtime fields.
+
+ Raw dimensions are kept under `\"fields\"`, or `\"metricFields\"` if compacted
+ fields already use `\"fields\"` as their output key."
+ [dimensions compact-keys compact-fields]
+ (when-let [raw-fields (not-empty (update-vals (apply dissoc dimensions compact-keys)
+ #(dissoc % :metricId)))]
+ (let [group-key (if (contains? compact-fields "fields")
+ "metricFields"
+ "fields")]
+ {group-key raw-fields})))
+
+(defn- compact-metric-dimensions
+ "Rewrites metric dimensions into compact field references where possible."
+ [schema]
+ (let [fields-reference-by-table (table-fields-reference-lookup schema)
+ field-key-by-table-and-field (table-field-key-lookup schema)]
+ (update schema :metrics
+ (fn [metrics]
+ (update-vals metrics
+ (fn [metric]
+ (let [dimensions (:dimensions metric)
+ compact-fields (compact-metric-dimension-fields fields-reference-by-table
+ field-key-by-table-and-field
+ dimensions)
+ fields (:fields compact-fields)
+ compact-keys (compact-metric-dimension-keys compact-fields)
+ raw-fields (raw-metric-dimension-fields dimensions compact-keys fields)
+ compact-dimensions (not-empty (merge raw-fields fields))]
+ (cond-> (dissoc metric :dimensions)
+ compact-dimensions (assoc :dimensions compact-dimensions)))))))))
+
+(defn- render-top-level-const
+ "Renders one top-level schema section as a TypeScript `const ... as const`."
+ [section-key value]
+ (str "const " (u/qualified-name section-key) " = " (javascript/render-value value (assoc (schema-render-options) :path [section-key]))
+ const-suffix ";\n\n"))
+
+(defn- render-pick-fields-helper
+ "Renders the TypeScript helper used by compacted metric dimensions."
+ []
+ (javascript/line-block
+ "function pickFields<TFields extends object, TKey extends keyof TFields>("
+ " fields: TFields,"
+ " keys: readonly TKey[],"
+ " options?: { sourceFieldId?: number },"
+ "): Pick<TFields, TKey> {"
+ " return Object.fromEntries(keys.map((key) => {"
+ " const field = fields[key] as { tableId?: number };"
+ " if (options?.sourceFieldId == null) {"
+ " return [key, field];"
+ " }"
+ " const { tableId, ...joinedField } = field;"
+ ""
+ " return [key, { ...joinedField, sourceFieldId: options.sourceFieldId }];"
+ " })) as Pick<TFields, TKey>;"
+ "}"))
+
+(defn- uses-pick-fields-helper?
+ "Returns true when rendered metrics contain `pickFields(...)` references."
+ [schema]
+ (boolean
+ (some (fn [metric]
+ (some javascript/reference? (vals (:dimensions metric))))
+ (vals (:metrics schema)))))
+
+(defn render-typescript
+ "Render `schema` as an ES module containing `as const` TypeScript constants."
+ [schema]
+ (let [schema (compact-metric-dimensions schema)
+ top-level-keys [:questions :models :tables :metrics]
+ schema-metadata (apply dissoc schema top-level-keys)
+ schema-value (reduce (fn [schema-value section-key]
+ (if (contains? schema section-key)
+ (assoc schema-value section-key (javascript/reference (name section-key)))
+ schema-value))
+ schema-metadata
+ top-level-keys)]
+ (str (when (uses-pick-fields-helper? schema)
+ (render-pick-fields-helper))
+ (apply str
+ (for [section-key top-level-keys
+ :when (contains? schema section-key)]
+ (render-top-level-const section-key (get schema section-key))))
+ "const schema = " (javascript/render-value schema-value (schema-render-options)) const-suffix ";\n\n"
+ "export default schema;\n")))
diff --git a/src/metabase/typed_schemas/api/schema.clj b/src/metabase/typed_schemas/api/schema.clj
new file mode 100644
index 00000000000..1bd58780633
--- /dev/null
+++ b/src/metabase/typed_schemas/api/schema.clj
@@ -0,0 +1,21 @@
+(ns metabase.typed-schemas.api.schema
+ "Top-level typed schema helpers."
+ (:require
+ [metabase.system.core :as system]
+ [metabase.typed-schemas.api.common :as common])
+ (:import
+ (java.time Instant)))
+
+(set! *warn-on-reflection* true)
+
+(defn base-schema
+ "Returns the top-level typed schema map."
+ [questions models tables metrics]
+ (array-map
+ :schemaVersion 2
+ :generatedAt (str (Instant/now))
+ :metabase {:instanceUrl (system/site-url)}
+ :questions (common/keyed-map questions)
+ :models (common/keyed-model-map models)
+ :tables (common/keyed-map tables)
+ :metrics (common/keyed-map metrics)))
diff --git a/src/metabase/typed_schemas/api/schema/common.clj b/src/metabase/typed_schemas/api/schema/common.clj
new file mode 100644
index 00000000000..655c9aac8dc
--- /dev/null
+++ b/src/metabase/typed_schemas/api/schema/common.clj
@@ -0,0 +1,56 @@
+(ns metabase.typed-schemas.api.schema.common
+ "Shared typed-schema source helpers."
+ (:require
+ [medley.core :as m]
+ [metabase.collections.models.collection :as collection]
+ [metabase.lib-be.core :as lib-be]
+ [metabase.lib.core :as lib]
+ [metabase.metabot.core :as metabot]
+ [metabase.models.interface :as mi]
+ [metabase.typed-schemas.api.scope :as scope]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(defn select-schema-cards
+ "Returns readable, non-archived cards for schema generation.
+
+ Metrics, models and saved questions are backed by cards. They need
+ the same visibility, archived, database and collection filters."
+ ([card-type database-ids]
+ (select-schema-cards card-type database-ids nil))
+ ([card-type database-ids collection-ids]
+ (->> (t2/select :model/Card
+ {:where (cond-> [:and
+ [:= :type (name card-type)]
+ [:= :archived false]
+ (collection/visible-collection-filter-clause :collection_id)]
+ database-ids (conj (scope/database-id-filter-clause database-ids :database_id))
+ collection-ids (conj (scope/id-filter-clause collection-ids :collection_id)))
+ :order-by [[:name :asc] [:id :asc]]})
+ (filter mi/can-read?))))
+
+(defn aggregation-result-column-with-metadata-provider
+ "Returns an aggregation result column using an existing metadata provider."
+ [metadata-provider query-definition]
+ (try
+ (let [query (lib/query metadata-provider query-definition)
+ aggregation-column (m/find-first #(= (:lib/source %) :source/aggregations)
+ (lib/returned-columns query))]
+ (when aggregation-column
+ (metabot/->result-column query aggregation-column)))
+ ;; Result-column inference is best effort; callers fall back to an unknown column.
+ (catch Exception _
+ nil)))
+
+(defn aggregation-result-column
+ "Returns the first aggregation result column for a saved query
+ definition, for metrics and measures."
+ [database-id query-definition]
+ (try
+ (aggregation-result-column-with-metadata-provider
+ (lib-be/application-database-metadata-provider database-id)
+ query-definition)
+ ;; Result-column inference is best effort; callers fall back to an unknown column.
+ (catch Exception _
+ nil)))
diff --git a/src/metabase/typed_schemas/api/schema/metric.clj b/src/metabase/typed_schemas/api/schema/metric.clj
new file mode 100644
index 00000000000..8b1c503cdf1
--- /dev/null
+++ b/src/metabase/typed_schemas/api/schema/metric.clj
@@ -0,0 +1,280 @@
+(ns metabase.typed-schemas.api.schema.metric
+ "Typed schema generation for metrics and metric dimensions."
+ (:require
+ [medley.core :as m]
+ [metabase.metabot.core :as metabot]
+ [metabase.metrics.core :as metrics]
+ [metabase.models.interface :as mi]
+ [metabase.typed-schemas.api.common :as common]
+ [metabase.typed-schemas.api.schema.common :as schema.common]
+ [metabase.typed-schemas.api.schema.table :as schema.table]
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(defn- metric-result-column
+ "Returns the metric aggregation result column inferred by Lib."
+ [card]
+ (schema.common/aggregation-result-column (:database_id card) (:dataset_query card)))
+
+(defn- metric-details-error-message
+ [card error-message]
+ (format "Failed to build schema details for metric \"%s\" (card %s): %s"
+ (or (:name card) "Untitled")
+ (:id card)
+ (or error-message "unknown error")))
+
+(defn- metric-details-error-data
+ [card error-data]
+ (m/assoc-some
+ {:card-id (:id card)
+ :card-name (:name card)
+ :card-type (:type card)}
+ :status-code (:status-code error-data)))
+
+(defn- metric-details
+ "Returns metric details with queryable dimensions for schema generation."
+ [card]
+ (let [response (metabot/get-metric-details {:metric-id (:id card)
+ ;; The typed schema does not use the default temporal dimension.
+ :with-default-temporal-breakout? false
+ :with-field-values? false
+ :with-queryable-dimensions? true
+ :with-segments? false})]
+ (or (:structured-output response)
+ (let [error-message (:output response)]
+ (throw (ex-info (metric-details-error-message card error-message)
+ (assoc (metric-details-error-data card response)
+ :error-message error-message)))))))
+
+(defn- persisted-dimension->column
+ "Converts persisted metric dimensions to column-shaped maps.
+
+ Persisted metric dimensions use kebab-case field/type keys, while [[common/column-schema]] expects
+ result-column-style snake_case keys."
+ [dimension]
+ (let [field-id (some-> dimension :sources first :field-id)]
+ {:name (:name dimension)
+ :display_name (:display-name dimension)
+ :base_type (some-> (:effective-type dimension) u/qualified-name)
+ :effective_type (some-> (:effective-type dimension) u/qualified-name)
+ :semantic_type (some-> (:semantic-type dimension) u/qualified-name)
+ :field_id field-id}))
+
+(defn- dimension-field-id
+ "Returns the field id backing a metric dimension, including persisted dimension sources."
+ [{:keys [field_id] :as dimension}]
+ (or field_id (some-> dimension :sources first :field-id)))
+
+(defn- dimension-table-id
+ "Returns the table id that backs a metric dimension, when known."
+ ([dimension]
+ (dimension-table-id dimension nil))
+ ([dimension field-table-ids]
+ (or (:table_id dimension)
+ (:table-id dimension)
+ (if field-table-ids
+ (get field-table-ids (dimension-field-id dimension))
+ (schema.table/table-by-field-id (dimension-field-id dimension))))))
+
+(defn- field-table-ids
+ "Returns backing table ids for dimensions that need field-based resolution."
+ [dimensions]
+ (let [field-ids (into #{}
+ (comp (remove #(or (:table_id %) (:table-id %)))
+ (keep dimension-field-id))
+ dimensions)]
+ (when (seq field-ids)
+ (into {}
+ (map (juxt :id :table_id))
+ (t2/select [:model/Field :id :table_id] :id [:in field-ids])))))
+
+(defn- dimension-schema
+ "Returns the schema for a metric dimension."
+ ([dimension metric-id]
+ (dimension-schema dimension metric-id (dimension-table-id dimension) {} {}))
+ ([dimension
+ metric-id
+ table-id
+ table-key-by-id
+ table-source-name-by-id]
+ (let [field-id (dimension-field-id dimension)
+ dimension-id (or (:id dimension) field-id)
+ column (if (:sources dimension)
+ (persisted-dimension->column dimension)
+ dimension)]
+ (m/assoc-some
+ (assoc (common/column-schema column)
+ :type "column"
+ :key (common/generated-key (:name column) dimension-id)
+ :id (str dimension-id))
+ :sourceName (when (integer? table-id)
+ (get table-source-name-by-id table-id))
+ :fieldId (when (integer? field-id) field-id)
+ :tableId (when (integer? table-id) table-id)
+ :sourceFieldId (when (integer? (:source-field-id dimension))
+ (:source-field-id dimension))
+ :metricId metric-id
+ :keyDisambiguator (when (integer? table-id)
+ (get table-key-by-id table-id))))))
+
+(defn- mapping-source-field-id
+ "Returns the mapped source field id for a metric dimension mapping."
+ [{:keys [target]}]
+ (when (and (vector? target)
+ (= :field (first target))
+ (map? (second target)))
+ (let [source-field-id (:source-field (second target))]
+ (when (integer? source-field-id)
+ source-field-id))))
+
+(defn- enrich-dimensions-with-mappings
+ "Adds mapped source field ids to persisted metric dimensions."
+ [dimensions dimension-mappings]
+ (let [mapping-by-dimension-id (into {} (map (juxt :dimension-id identity)) dimension-mappings)]
+ (mapv (fn [{:keys [id] :as dimension}]
+ (m/assoc-some dimension
+ :source-field-id (some-> (get mapping-by-dimension-id id)
+ mapping-source-field-id)))
+ dimensions)))
+
+(defn- sync-and-fetch-metric-dimensions!
+ "Syncs and returns persisted metric dimensions with mapping metadata."
+ [{:keys [id]}]
+ (metrics/sync-dimensions! :metadata/metric id)
+ (let [{:keys [dimensions dimension_mappings]} (t2/select-one [:model/Card :dimensions :dimension_mappings] :id id)]
+ (enrich-dimensions-with-mappings dimensions dimension_mappings)))
+
+(defn- readable-table-source-rows
+ "Returns readable table rows for table-backed metric dimensions."
+ [table-ids]
+ (when (seq table-ids)
+ (->> (t2/select [:model/Table :id :name :display_name] :id [:in table-ids])
+ (filter mi/can-read?))))
+
+(defn- table-key-disambiguators
+ "Returns table display keys used to disambiguate compacted metric dimensions."
+ ([table-ids]
+ (table-key-disambiguators table-ids (readable-table-source-rows table-ids)))
+ ([_dimension-table-ids table-rows]
+ (when (seq table-rows)
+ (->> table-rows
+ (map (fn [{:keys [id name display_name]}]
+ [id (common/pascal-case (common/generated-key (or display_name name) id))]))
+ (into {})))))
+
+(defn- table-source-names
+ "Returns table names emitted as metric dimension source names."
+ ([table-ids]
+ (table-source-names table-ids (readable-table-source-rows table-ids)))
+ ([_dimension-table-ids table-rows]
+ (when (seq table-rows)
+ (->> table-rows
+ (map (juxt :id :name))
+ (into {})))))
+
+(defn- source-table-schema
+ "Returns the metric source table identity from portable table metadata."
+ [[database-name schema-name table-name]]
+ (when (and database-name table-name)
+ {:databaseName database-name
+ :schemaName schema-name
+ :tableName table-name}))
+
+(defn- source-table-reference
+ "Returns the metric query source-table reference from either query shape."
+ [card]
+ (or (get-in card [:dataset_query :query :source-table])
+ (get-in card [:dataset_query :stages 0 :source-table])))
+
+(defn- source-table-id
+ "Returns the source table id for table-backed metrics."
+ [card]
+ (let [source-table (source-table-reference card)]
+ (when (integer? source-table)
+ source-table)))
+
+(defn- source-card-id
+ "Returns the source card id for metrics that are based on saved questions."
+ [card]
+ (or (when-let [source-card (get-in card [:dataset_query :stages 0 :source-card])]
+ (when (integer? source-card)
+ source-card))
+ (let [source-table (source-table-reference card)]
+ (when (string? source-table)
+ (some->> (re-matches #"card__(\d+)" source-table)
+ second
+ parse-long)))))
+
+(defn- fallback-metric-column
+ "Returns a stable fallback column when metric result-column inference fails."
+ [{:keys [name]}]
+ {:type "column"
+ :name name
+ :displayName name
+ :jsType "unknown"})
+
+(defn- metric-dimensions-with-table-ids
+ "Returns metric dimensions paired with their backing table ids, filtering mapped dimensions for card metrics."
+ [details source-card-id-value]
+ (let [dimensions (or (seq (sync-and-fetch-metric-dimensions! details))
+ (:queryable-dimensions details))
+ field-table-ids (field-table-ids dimensions)]
+ (cond->> (mapv (fn [dimension]
+ [dimension (dimension-table-id dimension field-table-ids)])
+ dimensions)
+ source-card-id-value (remove (fn [[_dimension table-id]]
+ (integer? table-id))))))
+
+(defn- metric-dimension-schemas
+ "Returns dimension schemas and mapped table ids for a metric."
+ [metric-id details source-card-id-value]
+ (let [dimension-table-id-pairs (metric-dimensions-with-table-ids details source-card-id-value)
+ table-ids (->> dimension-table-id-pairs (keep second) (filter integer?) distinct)
+ table-rows (readable-table-source-rows table-ids)
+ table-key-by-id (table-key-disambiguators table-ids table-rows)
+ table-source-name-by-id (table-source-names table-ids table-rows)
+ dimension-schemas (mapv (fn [[dimension table-id]]
+ (dimension-schema dimension
+ metric-id
+ table-id
+ table-key-by-id
+ table-source-name-by-id))
+ dimension-table-id-pairs)]
+ {:dimension-schemas dimension-schemas
+ :mapped-table-ids (->> dimension-schemas (keep :tableId) distinct sort vec)}))
+
+(defn- metric-schema
+ "Returns the schema for a metric and its queryable dimensions."
+ [{:keys [id name description verified portable_entity_id base_table_portable_fk] :as details}
+ card]
+ (let [result-column (or (some-> (metric-result-column card) common/column-schema)
+ (fallback-metric-column details))
+ source-card-id-value (source-card-id card)
+ {:keys [dimension-schemas mapped-table-ids]} (metric-dimension-schemas id details source-card-id-value)]
+ (m/assoc-some
+ {:type "metric"
+ :key (common/generated-key name id)
+ :id id
+ :name name
+ :columns [result-column]}
+ :databaseId (:database_id card)
+ :sourceTableId (source-table-id card)
+ :sourceCardId source-card-id-value
+ :entityId portable_entity_id
+ :description description
+ :verified (when verified true)
+ :sourceTable (source-table-schema base_table_portable_fk)
+ :mappedTableIds (not-empty mapped-table-ids)
+ :dimensions (not-empty (common/keyed-map dimension-schemas)))))
+
+(defn metric-schemas
+ "Returns metric schemas, with optional database and collection scopes."
+ ([database-ids]
+ (metric-schemas database-ids nil))
+ ([database-ids collection-ids]
+ (for [card (schema.common/select-schema-cards :metric database-ids collection-ids)
+ :let [details (metric-details card)]
+ :when details]
+ (metric-schema details card))))
diff --git a/src/metabase/typed_schemas/api/schema/model.clj b/src/metabase/typed_schemas/api/schema/model.clj
new file mode 100644
index 00000000000..0c7691e3583
--- /dev/null
+++ b/src/metabase/typed_schemas/api/schema/model.clj
@@ -0,0 +1,269 @@
+(ns metabase.typed-schemas.api.schema.model
+ "Typed schema generation for models and actions."
+ (:require
+ [clojure.string :as str]
+ [medley.core :as m]
+ [metabase.actions.core :as actions]
+ [metabase.lib.schema.common :as lib.schema.common]
+ [metabase.typed-schemas.api.common :as common]
+ [metabase.typed-schemas.api.schema.common :as schema.common]
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(defn- keyword-or-string?
+ "Returns true for values that can be normalized to keywords."
+ [value]
+ ((some-fn keyword? string?) value))
+
+(defn- keyword-name
+ "Returns a display string for Toucan-normalized action type/kind keywords."
+ [value]
+ (when (keyword? value)
+ (u/qualified-name value)))
+
+(defn- action-type-name
+ "Returns a display-safe action type name."
+ [action]
+ (or (keyword-name (:type action)) "unknown"))
+
+(defn- model-action-error-data
+ "Returns structured error data for model action schema failures."
+ ([model error-data]
+ (m/assoc-some
+ {:model-id (:id model)
+ :model-name (:name model)}
+ :status-code (:status-code error-data)))
+ ([model action error-data]
+ (m/assoc-some
+ (assoc (model-action-error-data model error-data)
+ :action-id (:id action)
+ :action-name (:name action)
+ :action-type (:type action))
+ :status-code (:status-code error-data))))
+
+(defn- action-rows
+ "Returns raw rows so we can detect actions that cannot be resolved to action details."
+ [model-ids]
+ (t2/select [:model/Action :id :model_id :name :type]
+ :model_id [:in model-ids]
+ :archived false
+ :type [:not= "http"]))
+
+(defn- unresolved-action-rows
+ "Returns action rows missing from resolved action details."
+ [action-rows action-details]
+ (let [action-ids (set (map :id action-details))]
+ (not-empty
+ (remove #(contains? action-ids (:id %)) action-rows))))
+
+(defn- unresolved-action-rows-message
+ "Returns the error message for action rows that cannot be resolved."
+ [model unresolved-action-rows]
+ (format "Failed to build action schemas for model \"%s\" (card %s): action rows could not be resolved: %s"
+ (or (:name model) "Untitled")
+ (:id model)
+ (str/join ", "
+ (for [action unresolved-action-rows]
+ (format "%s (action %s, type %s)"
+ (or (:name action) "Untitled")
+ (:id action)
+ (action-type-name action))))))
+
+(defn- unresolved-action-rows-data
+ "Returns structured error data for action rows that cannot be resolved."
+ [model unresolved-action-rows]
+ (assoc (model-action-error-data model nil)
+ :unresolved-action-rows (mapv #(select-keys % [:id :name :type]) unresolved-action-rows)))
+
+(defn- throw-if-unresolved-action-rows!
+ "Surfaces action rows that cannot be resolved into action details."
+ [model action-rows action-details]
+ (when-let [unresolved-rows (unresolved-action-rows action-rows action-details)]
+ (throw (ex-info (unresolved-action-rows-message model unresolved-rows)
+ (unresolved-action-rows-data model unresolved-rows)))))
+
+(defn- param-type->js-type
+ "Returns the JS type for a Metabase action parameter type."
+ [param-type]
+ (when (keyword-or-string? param-type)
+ (let [param-type-keyword (lib.schema.common/normalize-keyword param-type)
+ prefix (or (namespace param-type-keyword) (name param-type-keyword))]
+ (case prefix
+ ("number" "numeric") "number"
+ ("text" "string") "string"
+ "date" "Date"
+ "boolean" "boolean"
+ nil))))
+
+(defn- template-tag-name-from-target
+ "Returns the template-tag name referenced by an action parameter target."
+ [target]
+ (when (sequential? target)
+ (let [[op inner] target]
+ (when (and (or (= op :variable) (= op "variable"))
+ (sequential? inner))
+ (let [[tag-op tag-name] inner]
+ (when (or (= tag-op :template-tag) (= tag-op "template-tag"))
+ (cond
+ (string? tag-name) tag-name
+ (keyword? tag-name) (clojure.core/name tag-name)
+ :else nil)))))))
+
+(defn- query-action-template-tag-types
+ "Returns template-tag types for query action parameters."
+ [{:keys [type dataset_query]}]
+ (when (and (= (lib.schema.common/normalize-keyword type) :query) dataset_query)
+ (let [stage-tags (some-> dataset_query :stages first :template-tags)
+ native-tags (some-> dataset_query :native :template-tags)
+ tags (or stage-tags native-tags)]
+ (into {}
+ (for [[tag-key tag] tags]
+ [(or (:name tag)
+ (cond
+ (string? tag-key) tag-key
+ (keyword? tag-key) (clojure.core/name tag-key)
+ :else nil))
+ (:type tag)])))))
+
+(defn- model-action-error-message
+ "Returns the error message for model action schema failures."
+ ([model error-message]
+ (format "Failed to build action schemas for model \"%s\" (card %s): %s"
+ (or (:name model) "Untitled")
+ (:id model)
+ (or error-message "unknown error")))
+ ([model action error-message]
+ (format "Failed to build action schema for action \"%s\" (action %s, type %s) on model \"%s\" (card %s): %s"
+ (or (:name action) "Untitled")
+ (:id action)
+ (action-type-name action)
+ (or (:name model) "Untitled")
+ (:id model)
+ (or error-message "unknown error"))))
+
+(defn- error-data-with-cause-message
+ "Adds the original exception message to structured error data."
+ [error-data exception]
+ (assoc error-data :cause-message (ex-message exception)))
+
+(defn- action-parameter-schema
+ "Returns the schema for an action execute parameter."
+ [tag-types
+ {:keys [id slug name display-name type target required]}]
+ (let [resolved-slug (or slug
+ (some-> id clojure.core/name)
+ (some-> name u/slugify))
+ resolved-type (or (param-type->js-type type)
+ (param-type->js-type
+ (get tag-types
+ (template-tag-name-from-target target)))
+ "unknown")]
+ (m/assoc-some
+ {:slug resolved-slug
+ :displayName (or display-name name resolved-slug)
+ :jsType resolved-type}
+ :required (when required true))))
+
+(defn- action-detail-schema
+ "Returns the typed schema entry for resolved action details."
+ [{:keys [id name description type kind parameters entity_id] :as action}]
+ (let [tag-types (query-action-template-tag-types action)
+ implicit? (= (lib.schema.common/normalize-keyword type) :implicit)]
+ (m/assoc-some
+ {:kind "action"
+ :key (common/generated-key name id)
+ :id id
+ :name name
+ :type (keyword-name type)
+ :parameters (mapv #(action-parameter-schema tag-types %) parameters)}
+ :description description
+ :entityId entity_id
+ :implicitKind (when implicit? (keyword-name kind)))))
+
+(defn- resolved-action-details
+ "Returns action details from the actions module, preserving lookup error context."
+ [model]
+ (try
+ (actions/select-actions
+ nil
+ :model_id (:id model)
+ :archived false
+ :type [:not= "http"])
+ (catch Exception exception
+ (throw (ex-info (model-action-error-message model (ex-message exception))
+ (error-data-with-cause-message
+ (model-action-error-data model (ex-data exception))
+ exception)
+ exception)))))
+
+(defn- resolved-action-details-for-models
+ "Returns resolved action details for selected models."
+ [models]
+ (let [model-ids (set (map :id models))]
+ (try
+ (actions/select-actions
+ models
+ :model_id [:in model-ids]
+ :archived false
+ :type [:not= "http"])
+ (catch Exception exception
+ (throw (ex-info (format "Failed to build action schemas for selected models: %s" (ex-message exception))
+ (error-data-with-cause-message
+ {:model-ids model-ids
+ :status-code (:status-code (ex-data exception))}
+ exception)
+ exception))))))
+
+(defn- model-action-schema
+ "Returns an action schema, preserving which model/action failed to render."
+ [model action]
+ (try
+ (action-detail-schema action)
+ (catch Exception exception
+ (throw (ex-info (model-action-error-message model action (ex-message exception))
+ (error-data-with-cause-message
+ (model-action-error-data model action (ex-data exception))
+ exception)
+ exception)))))
+
+(defn- model-action-schemas
+ "Returns action schemas for a model, preserving action lookup error context."
+ ([model]
+ (model-action-schemas model
+ (action-rows #{(:id model)})
+ (resolved-action-details model)))
+ ([model action-rows action-details]
+ (throw-if-unresolved-action-rows! model action-rows action-details)
+ (not-empty
+ (mapv #(model-action-schema model %) action-details))))
+
+(defn model-schema
+ "Returns the model schema with actions, or nil when the model has no executable actions."
+ ([model]
+ (model-schema model (model-action-schemas model)))
+ ([{:keys [id name]} action-schemas]
+ (when (seq action-schemas)
+ {:key (common/generated-key name id)
+ :keyDisambiguator id
+ :actions (common/keyed-map action-schemas)})))
+
+(defn model-schemas
+ "Returns model schemas, with optional database and collection scopes."
+ ([database-ids]
+ (model-schemas database-ids nil))
+ ([database-ids collection-ids]
+ (let [models (schema.common/select-schema-cards :model database-ids collection-ids)]
+ (if (seq models)
+ (let [model-ids (set (map :id models))
+ action-rows-by-model-id (group-by :model_id (action-rows model-ids))
+ action-details-by-model-id (group-by :model_id (resolved-action-details-for-models models))]
+ (for [model models
+ :let [action-schemas (model-action-schemas model
+ (get action-rows-by-model-id (:id model))
+ (get action-details-by-model-id (:id model)))
+ schema (model-schema model action-schemas)]
+ :when schema]
+ schema))
+ []))))
diff --git a/src/metabase/typed_schemas/api/schema/question.clj b/src/metabase/typed_schemas/api/schema/question.clj
new file mode 100644
index 00000000000..20064724cec
--- /dev/null
+++ b/src/metabase/typed_schemas/api/schema/question.clj
@@ -0,0 +1,73 @@
+(ns metabase.typed-schemas.api.schema.question
+ "Typed schema generation for saved questions."
+ (:require
+ [medley.core :as m]
+ [metabase.metabot.tools.entity-details :as entity-details]
+ [metabase.typed-schemas.api.common :as common]
+ [metabase.typed-schemas.api.schema.common :as schema.common]))
+
+(set! *warn-on-reflection* true)
+
+(defn- question-details-error-message
+ [card error-message]
+ (format "Failed to build schema details for question \"%s\" (card %s): %s"
+ (or (:name card) "Untitled")
+ (:id card)
+ (or error-message "unknown error")))
+
+(defn- question-details-error-data
+ [card error-data]
+ (m/assoc-some
+ {:card-id (:id card)
+ :card-name (:name card)
+ :card-type (:type card)}
+ :status-code (:status-code error-data)))
+
+(defn- question-details
+ "Returns saved-question details in the selected-card order."
+ [cards]
+ (let [details-by-card-id (into {}
+ (mapcat (fn [[database-id database-cards]]
+ (mapv (fn [card details]
+ (try
+ [(:id card)
+ (assoc details
+ :result-columns (:fields details)
+ :display (:display card))]
+ (catch Exception exception
+ (throw (ex-info (question-details-error-message card (ex-message exception))
+ (assoc (question-details-error-data card (ex-data exception))
+ :cause-message (ex-message exception))
+ exception)))))
+ database-cards
+ (entity-details/cards-details
+ :question database-id database-cards
+ {:with-field-values? false
+ :with-related-tables? false
+ :with-metrics? false
+ :with-measures? false
+ :with-segments? false})))
+ (group-by :database_id cards)))]
+ (mapv details-by-card-id (map :id cards))))
+
+(defn question-schema
+ "Returns the schema for a saved question."
+ [{:keys [id name description verified display result-columns portable_entity_id]}]
+ (m/assoc-some
+ {:type "card"
+ :key (common/generated-key name id)
+ :id id
+ :name name
+ :display display
+ :columns (mapv common/column-schema result-columns)}
+ :entityId portable_entity_id
+ :description description
+ :verified (when verified true)))
+
+(defn question-schemas
+ "Returns schemas for saved questions, with optional database and collection scopes."
+ ([database-ids]
+ (question-schemas database-ids nil))
+ ([database-ids collection-ids]
+ (let [cards (schema.common/select-schema-cards :question database-ids collection-ids)]
+ (mapv question-schema (question-details cards)))))
diff --git a/src/metabase/typed_schemas/api/schema/table.clj b/src/metabase/typed_schemas/api/schema/table.clj
new file mode 100644
index 00000000000..e22846875cd
--- /dev/null
+++ b/src/metabase/typed_schemas/api/schema/table.clj
@@ -0,0 +1,193 @@
+(ns metabase.typed-schemas.api.schema.table
+ "Typed schema generation for tables, fields, segments and measures."
+ (:require
+ [medley.core :as m]
+ [metabase.lib-be.core :as lib-be]
+ [metabase.metabot.core :as metabot]
+ [metabase.models.interface :as mi]
+ [metabase.typed-schemas.api.common :as common]
+ [metabase.typed-schemas.api.schema.common :as schema.common]
+ [metabase.typed-schemas.api.scope :as scope]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(defn table-by-field-id
+ "Returns the table for a given field id."
+ [field-id]
+ (when (integer? field-id)
+ (t2/select-one-fn :table_id :model/Field :id field-id)))
+
+(defn field-schema
+ "Returns the schema for a table field."
+ ([field]
+ (field-schema field nil nil))
+ ([field source-name]
+ (field-schema field source-name nil))
+ ([{:keys [id field_id] :as field} source-name table-id]
+ (let [field-id (or id field_id)
+ table-id (or table-id (:table_id field) (:table-id field) (table-by-field-id field-id))]
+ (m/assoc-some
+ (assoc (common/column-schema field)
+ :type "column"
+ :key (common/generated-key (:name field) field-id)
+ :id field-id)
+ :sourceName source-name
+ :fieldId (when (integer? field-id) field-id)
+ :tableId (when (integer? table-id) table-id)
+ :defaultTemporalBucket (:unit field)))))
+
+(defn select-tables
+ "Returns readable tables, with optional database and table-id scopes.
+
+ Library and database endpoint paths both need the same active/readable table
+ rules; only their id filters differ."
+ ([database-ids]
+ (select-tables database-ids nil))
+ ([database-ids table-ids]
+ (->> (t2/select :model/Table
+ {:where (cond-> [:and [:= :active true]]
+ database-ids (conj (scope/database-id-filter-clause database-ids :db_id))
+ table-ids (conj (scope/id-filter-clause table-ids :id)))
+ :order-by [[:name :asc] [:id :asc]]})
+ (filter mi/can-read?))))
+
+(defn select-library-tables
+ "Returns published tables from the library based on the given scope."
+ [{:keys [data-collection-ids]}]
+ (->> (t2/select :model/Table
+ {:where [:and
+ [:= :active true]
+ [:= :is_published true]
+ (scope/id-filter-clause data-collection-ids :collection_id)]
+ :order-by [[:name :asc] [:id :asc]]})
+ (filter mi/can-read?)))
+
+(defn segment-schema
+ "Returns the schema for a segment."
+ [table-id {:keys [id name description display-name portable-entity-id portable_entity_id]}]
+ (m/assoc-some
+ {:type "segment"
+ :key (common/generated-key (or display-name name) id)
+ :id id
+ :tableId table-id
+ :name name}
+ :entityId (or portable_entity_id portable-entity-id)
+ :description description))
+
+(defn- fallback-measure-column
+ [{:keys [name]}]
+ {:type "column"
+ :name name
+ :displayName name
+ :jsType "unknown"})
+
+(defn measure-result-column
+ "Returns the result column for a measure definition, or nil when it cannot be inferred.
+
+ Measures render as aggregate fields. When Lib can infer the
+ aggregation column, the schema exposes the real result type. Otherwise, the
+ measure remains usable with a fallback column."
+ [database-id measure-id]
+ (try
+ (when-let [definition (t2/select-one-fn :definition :model/Measure :id measure-id)]
+ (schema.common/aggregation-result-column database-id definition))
+ (catch Exception _
+ nil)))
+
+(defn- measure-result-columns
+ "Returns result columns for table measures with one definition query and metadata provider."
+ [database-id measures]
+ (let [measure-ids (into [] (keep :id) measures)]
+ (when (seq measure-ids)
+ (let [definition-by-measure-id (into {}
+ (map (juxt :id :definition))
+ (t2/select [:model/Measure :id :definition] :id [:in measure-ids]))]
+ (try
+ (let [metadata-provider (lib-be/application-database-metadata-provider database-id)]
+ (into {}
+ (keep (fn [{:keys [id]}]
+ (when-let [definition (get definition-by-measure-id id)]
+ [id (schema.common/aggregation-result-column-with-metadata-provider metadata-provider definition)])))
+ measures))
+ ;; Result-column inference is best effort; callers fall back to an unknown column.
+ (catch Exception _
+ {}))))))
+
+(defn measure-schema
+ "Returns the schema for a measure."
+ ([table-id database-id measure]
+ (measure-schema table-id database-id (measure-result-column database-id (:id measure)) measure))
+ ([table-id _database-id result-column {:keys [id name description display-name portable-entity-id portable_entity_id]}]
+ (m/assoc-some
+ {:type "measure"
+ :key (common/generated-key (or display-name name) id)
+ :id id
+ :tableId table-id
+ :name name
+ :columns [(or (some-> result-column common/column-schema)
+ (fallback-measure-column {:name (or display-name name)}))]}
+ :entityId (or portable_entity_id portable-entity-id)
+ :description description)))
+
+(defn table-schema
+ "Returns the schema for a table."
+ [{:keys [id name description display_name database_id database_name database_schema portable_entity_id fields segments measures]}]
+ (let [segments-map (common/keyed-map (map #(segment-schema id %) segments))
+ measure-result-column-by-id (measure-result-columns database_id measures)
+ measures-map (common/keyed-map (map #(measure-schema id database_id
+ (get measure-result-column-by-id (:id %))
+ %)
+ measures))]
+ (m/assoc-some
+ {:type "table"
+ :key (common/generated-key (or display_name name) id)
+ :id id
+ :name (or display_name name)
+ :databaseName database_name
+ :tableName name
+ :fields (common/keyed-map (map #(field-schema % name id) fields))}
+ :entityId portable_entity_id
+ :description description
+ :schemaName database_schema
+ :segments (not-empty segments-map)
+ :measures (not-empty measures-map))))
+
+(defn- table-details-error-message
+ [table error-message]
+ (format "Failed to build schema details for table \"%s\" (table %s): %s"
+ (or (:name table) "Untitled")
+ (:id table)
+ (or error-message "unknown error")))
+
+(defn- table-details-error-data
+ [table error-data]
+ (m/assoc-some
+ {:table-id (:id table)
+ :table-name (:name table)}
+ :status-code (:status-code error-data)))
+
+(defn- table-details
+ [table]
+ (let [response (metabot/get-table-details
+ {:entity-type :table
+ :entity-id (:id table)
+ :with-fields? true
+ :with-field-values? false
+ :with-related-tables? false
+ :with-metrics? false
+ :with-measures? true
+ :with-segments? true})]
+ (or (:structured-output response)
+ (let [error-message (:output response)]
+ (throw (ex-info (table-details-error-message table error-message)
+ (assoc (table-details-error-data table response)
+ :error-message error-message)))))))
+
+(defn table-schemas
+ "Returns table schemas for selected table rows."
+ [tables]
+ (for [table tables
+ :let [details (table-details table)]
+ :when details]
+ (table-schema details)))
diff --git a/src/metabase/typed_schemas/api/scope.clj b/src/metabase/typed_schemas/api/scope.clj
new file mode 100644
index 00000000000..be7814e8301
--- /dev/null
+++ b/src/metabase/typed_schemas/api/scope.clj
@@ -0,0 +1,218 @@
+(ns metabase.typed-schemas.api.scope
+ "Scope resolution for typed-schema endpoints."
+ (:require
+ [clojure.string :as str]
+ [metabase.api.common :as api]
+ [metabase.collections.models.collection :as collection]
+ [metabase.models.interface :as mi]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(defn truthy-query-param?
+ "Returns true when a query param value should be interpreted as enabled."
+ [v]
+ (contains? #{true "true" "1"} v))
+
+(def ^:private library-data-entity-id
+ "Entity id of the root Data library collection."
+ "librarylibrarydatadat")
+
+(def ^:private library-metrics-entity-id
+ "Entity id of the root metrics library collection."
+ "librarylibrarymetrics")
+
+(defn query-database-value
+ "Returns the requested database id/name query param."
+ [query-params]
+ (some-> (or (:database query-params)
+ (:database-name query-params))
+ str/trim
+ not-empty))
+
+(defn database-ids-for-value
+ "Returns readable database ids matching `database-value`."
+ [database-value]
+ (when database-value
+ (let [database-id (parse-long database-value)]
+ (->> (if database-id
+ (t2/select :model/Database :id database-id)
+ (t2/select :model/Database :name database-value))
+ (filter mi/can-read?)
+ (map :id)
+ set))))
+
+(defn database-id-filter-clause
+ "Returns a Honey SQL filter clause for optional database ids."
+ [database-ids column]
+ (when database-ids
+ (if (seq database-ids)
+ [:in column database-ids]
+ [:= column -1])))
+
+(defn id-filter-clause
+ "Returns a Honey SQL filter clause for optional ids."
+ [ids column]
+ (when ids
+ (if (seq ids)
+ [:in column ids]
+ [:= column -1])))
+
+(defn query-library-value
+ "Returns the `library` query param."
+ [query-params]
+ (some-> (:library query-params)
+ str/trim
+ not-empty))
+
+(defn- query-comma-separated-values
+ [query-params param-keys]
+ (when-let [value (some-> (->> param-keys
+ (keep query-params)
+ first)
+ str/trim
+ not-empty)]
+ (->> (str/split value #",")
+ (map str/trim)
+ (remove str/blank?)
+ seq)))
+
+(defn query-library-collection-values
+ "Returns requested library collection refs."
+ [query-params]
+ (query-comma-separated-values query-params [:library-collections
+ :collections]))
+
+(defn query-include-data-library?
+ "Returns true when the root Data library should be included."
+ [query-params]
+ (truthy-query-param? (:include-data-library query-params)))
+
+(defn query-include-metric-library?
+ "Returns true when the root metrics library should be included."
+ [query-params]
+ (truthy-query-param? (:include-metric-library query-params)))
+
+(defn query-include-models?
+ "Returns true when readable model action namespaces should be included."
+ [query-params]
+ (truthy-query-param? (:include-models query-params)))
+
+(defn query-question-collection-values
+ "Returns requested question collection refs."
+ [query-params]
+ (query-comma-separated-values query-params [:question-collections]))
+
+(defn- library-collection-for-value
+ [library-value]
+ (when library-value
+ (let [collection-id (parse-long library-value)]
+ (->> (if collection-id
+ (t2/select :model/Collection :id collection-id)
+ (t2/select :model/Collection :name library-value))
+ (filter #(contains? collection/library-collection-types (:type %)))
+ (filter mi/can-read?)
+ first))))
+
+(defn- library-collection-for-ref
+ [collection-value]
+ (let [collection-id (parse-long collection-value)]
+ (->> (if collection-id
+ (t2/select :model/Collection :id collection-id)
+ (t2/select :model/Collection :entity_id collection-value))
+ (filter #(contains? collection/library-collection-types (:type %)))
+ (filter mi/can-read?)
+ first)))
+
+(defn- library-collection-for-entity-id
+ [entity-id]
+ (->> (t2/select :model/Collection :entity_id entity-id)
+ (filter #(contains? collection/library-collection-types (:type %)))
+ (filter mi/can-read?)
+ first))
+
+(defn- collection-for-ref
+ [collection-value]
+ (let [collection-id (parse-long collection-value)]
+ (->> (if collection-id
+ (t2/select :model/Collection :id collection-id)
+ (t2/select :model/Collection :entity_id collection-value))
+ (filter mi/can-read?)
+ first)))
+
+(defn collection-scope
+ "Returns ids for requested normal collections and descendants."
+ [collection-values]
+ (when (seq collection-values)
+ (let [collections (for [collection-value collection-values]
+ (or (collection-for-ref collection-value)
+ (api/check-404 false)))]
+ (->> collections
+ (mapcat #(cons % (collection/descendants-flat %)))
+ (map :id)
+ set))))
+
+(defn- library-collection-scope*
+ [library-collections]
+ (let [ids (->> library-collections
+ (mapcat #(cons % (collection/descendants-flat %)))
+ (map :id)
+ set)
+ rows (t2/select [:model/Collection :id :type] :id [:in ids])
+ ids-for-type (fn [collection-type]
+ (->> rows
+ (filter #(= (:type %) collection-type))
+ (map :id)
+ set))]
+ {:library-collections library-collections
+ :collection-ids ids
+ :data-collection-ids (ids-for-type collection/library-data-collection-type)
+ :metric-collection-ids (ids-for-type collection/library-metrics-collection-type)}))
+
+(defn library-collection-scope
+ "Returns the library scope for one named or numeric library collection."
+ [library-value]
+ (when library-value
+ (let [library (or (library-collection-for-value library-value)
+ (api/check-404 false))]
+ (library-collection-scope* [library]))))
+
+(defn library-collections-scope
+ "Returns the library scope for requested library collection refs."
+ [collection-values]
+ (when (seq collection-values)
+ (let [collections (for [collection-value collection-values]
+ (or (library-collection-for-ref collection-value)
+ (api/check-404 false)))]
+ (library-collection-scope* collections))))
+
+(defn- included-library-root-collections
+ [query-params]
+ (keep (fn [[include? entity-id]]
+ (when include?
+ (or (library-collection-for-entity-id entity-id)
+ (api/check-404 false))))
+ [[(query-include-data-library? query-params) library-data-entity-id]
+ [(query-include-metric-library? query-params) library-metrics-entity-id]]))
+
+(defn library-scope
+ "Returns the requested library scope for data and metric library params."
+ [query-params]
+ (let [library-value (query-library-value query-params)
+ library-collection-values (query-library-collection-values query-params)
+ included-roots (included-library-root-collections query-params)
+ collection-scope (cond
+ library-value
+ (library-collection-scope library-value)
+
+ library-collection-values
+ (library-collections-scope library-collection-values))]
+ (cond
+ (and collection-scope (seq included-roots))
+ (library-collection-scope* (concat (:library-collections collection-scope) included-roots))
+
+ (seq included-roots)
+ (library-collection-scope* included-roots)
+
+ :else
+ collection-scope)))
diff --git a/test/metabase/actions_rest/api_test.clj b/test/metabase/actions_rest/api_test.clj
index d1ed7fb1511..46802c5bef5 100644
--- a/test/metabase/actions_rest/api_test.clj
+++ b/test/metabase/actions_rest/api_test.clj
@@ -395,6 +395,53 @@
:specific-errors {:model_id ["missing required key, received: nil"]}}
(mt/user-http-request :crowberto :post 400 "action" {:type "query" :name "test"}))))))))))
+(deftest remap-parameter-keys-test
+ (testing "remap-parameter-keys translates incoming parameter keys to the destination parameter's :id"
+ (let [action {:parameters [{:id "d800e41d-edde-49cb-b63b-2386aba34334"
+ :slug "id"
+ :name "ID"}
+ {:id "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b"
+ :slug "discount"
+ :name "Discount"}]}]
+ (testing "slug-keyed input is remapped to :id"
+ (is (= {"d800e41d-edde-49cb-b63b-2386aba34334" 1
+ "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b" 0.1}
+ (#'api.action/remap-parameter-keys action
+ {"id" 1 "discount" 0.1}))))
+ (testing "already-:id-keyed input is passed through unchanged"
+ (is (= {"d800e41d-edde-49cb-b63b-2386aba34334" 1
+ "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b" 0.1}
+ (#'api.action/remap-parameter-keys
+ action
+ {"d800e41d-edde-49cb-b63b-2386aba34334" 1
+ "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b" 0.1}))))
+ (testing "display-name keys (`:name`) are NOT accepted — they pass through unchanged"
+ (is (= {"ID" 1 "Discount" 0.1}
+ (#'api.action/remap-parameter-keys action
+ {"ID" 1 "Discount" 0.1}))))
+ (testing "unknown keys pass through unchanged so downstream validation still fires"
+ (is (= {"d800e41d-edde-49cb-b63b-2386aba34334" 1
+ "bogus" 42}
+ (#'api.action/remap-parameter-keys action
+ {"id" 1 "bogus" 42}))))
+ (testing "a mix of :id and :slug keys resolve together"
+ (is (= {"d800e41d-edde-49cb-b63b-2386aba34334" 1
+ "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b" 0.1}
+ (#'api.action/remap-parameter-keys
+ action
+ {"d800e41d-edde-49cb-b63b-2386aba34334" 1
+ "discount" 0.1}))))
+ (testing "empty parameters map → empty result"
+ (is (= {}
+ (#'api.action/remap-parameter-keys action {}))))
+ (testing "implicit-action style (no :slug) — :id-keyed input still passes through"
+ (let [implicit-action {:parameters [{:id "name" :name "Name"}
+ {:id "email" :name "Email"}]}]
+ (is (= {"name" "Foo" "email" "[email protected]"}
+ (#'api.action/remap-parameter-keys
+ implicit-action
+ {"name" "Foo" "email" "[email protected]"}))))))))
+
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | PUBLIC SHARING ENDPOINTS |
;;; +----------------------------------------------------------------------------------------------------------------+
@@ -493,53 +540,6 @@
(is (= "Not found."
(mt/user-http-request :crowberto :delete 404 (format "action/%d/public_link" Integer/MAX_VALUE)))))))))
-(deftest remap-parameter-keys-test
- (testing "remap-parameter-keys translates incoming parameter keys to the destination parameter's :id"
- (let [action {:parameters [{:id "d800e41d-edde-49cb-b63b-2386aba34334"
- :slug "id"
- :name "ID"}
- {:id "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b"
- :slug "discount"
- :name "Discount"}]}]
- (testing "slug-keyed input is remapped to :id"
- (is (= {"d800e41d-edde-49cb-b63b-2386aba34334" 1
- "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b" 0.1}
- (#'api.action/remap-parameter-keys action
- {"id" 1 "discount" 0.1}))))
- (testing "already-:id-keyed input is passed through unchanged"
- (is (= {"d800e41d-edde-49cb-b63b-2386aba34334" 1
- "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b" 0.1}
- (#'api.action/remap-parameter-keys
- action
- {"d800e41d-edde-49cb-b63b-2386aba34334" 1
- "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b" 0.1}))))
- (testing "display-name keys (`:name`) are NOT accepted — they pass through unchanged"
- (is (= {"ID" 1 "Discount" 0.1}
- (#'api.action/remap-parameter-keys action
- {"ID" 1 "Discount" 0.1}))))
- (testing "unknown keys pass through unchanged so downstream validation still fires"
- (is (= {"d800e41d-edde-49cb-b63b-2386aba34334" 1
- "bogus" 42}
- (#'api.action/remap-parameter-keys action
- {"id" 1 "bogus" 42}))))
- (testing "a mix of :id and :slug keys resolve together"
- (is (= {"d800e41d-edde-49cb-b63b-2386aba34334" 1
- "58c9e1ca-2f3a-4e57-96d9-2507c21a9a4b" 0.1}
- (#'api.action/remap-parameter-keys
- action
- {"d800e41d-edde-49cb-b63b-2386aba34334" 1
- "discount" 0.1}))))
- (testing "empty parameters map → empty result"
- (is (= {}
- (#'api.action/remap-parameter-keys action {}))))
- (testing "implicit-action style (no :slug) — :id-keyed input still passes through"
- (let [implicit-action {:parameters [{:id "name" :name "Name"}
- {:id "email" :name "Email"}]}]
- (is (= {"name" "Foo" "email" "[email protected]"}
- (#'api.action/remap-parameter-keys
- implicit-action
- {"name" "Foo" "email" "[email protected]"}))))))))
-
(deftest execute-action-test
(mt/with-actions-test-data-and-actions-enabled
(mt/with-actions [{:keys [action-id]} unshared-action-opts]
diff --git a/test/metabase/analytics/sdk_persistence_test.clj b/test/metabase/analytics/sdk_persistence_test.clj
new file mode 100644
index 00000000000..2660575f30d
--- /dev/null
+++ b/test/metabase/analytics/sdk_persistence_test.clj
@@ -0,0 +1,44 @@
+(ns metabase.analytics.sdk-persistence-test
+ "End-to-end coverage for the embedding client headers: a request carrying
+ X-Metabase-Client / -Identifier / -Embedded-Preview must have its context
+ persisted onto the analytics rows written during that request. The
+ header-parsing details are covered in [[metabase.server.middleware.sdk-test]];
+ this namespace covers the request -> `query_execution` row contract."
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(defn- venues-query [limit]
+ (let [mp (mt/metadata-provider)]
+ (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/limit limit))))
+
+(defn- latest-query-execution [embedding-client]
+ (t2/select-one :model/QueryExecution
+ :embedding_client embedding-client
+ {:order-by [[:id :desc]]}))
+
+(deftest query-execution-embedding-client-test
+ (mt/with-temporary-setting-values [synchronous-batch-updates true]
+ (testing "the embedding client and identifier of the request are persisted on the QueryExecution row"
+ (mt/user-http-request :crowberto :post 202 "dataset"
+ {:request-options
+ {:headers {"x-metabase-client" "data-app"
+ "x-metabase-client-identifier" "sales"}}}
+ (venues-query 1))
+ (is (=? {:embedding_client "data-app"
+ :embedding_client_identifier "sales"}
+ (latest-query-execution "data-app"))))
+ (testing "a dev data app (preview header) is persisted as the data-app-preview client"
+ (mt/user-http-request :crowberto :post 202 "dataset"
+ {:request-options
+ {:headers {"x-metabase-client" "data-app"
+ "x-metabase-client-identifier" "sales"
+ "x-metabase-embedded-preview" "true"}}}
+ (venues-query 2))
+ (is (=? {:embedding_client "data-app-preview"
+ :embedding_client_identifier "sales"}
+ (latest-query-execution "data-app-preview"))))))
diff --git a/test/metabase/analytics/stats_test.clj b/test/metabase/analytics/stats_test.clj
index cffe786e70a..5335c9e5c14 100644
--- a/test/metabase/analytics/stats_test.clj
+++ b/test/metabase/analytics/stats_test.clj
@@ -546,6 +546,7 @@
or to this set, so that [[every-feature-is-accounted-for-test]] passes."
#{:audit-app ;; tracked under :mb-analytics
:collection-cleanup
+ :data-apps
:data-complexity-score
:development-mode
:library
diff --git a/test/metabase/api/common_test.clj b/test/metabase/api/common_test.clj
index 2303280eab7..3c82d852c4b 100644
--- a/test/metabase/api/common_test.clj
+++ b/test/metabase/api/common_test.clj
@@ -21,7 +21,7 @@
{:status 404
:body "Not found."
:headers {"Cache-Control" "max-age=0, no-cache, must-revalidate, proxy-revalidate"
- "Content-Security-Policy" (str (-> (@#'mw.security/content-security-policy-header nil) vals first)
+ "Content-Security-Policy" (str (-> (@#'mw.security/content-security-policy-header nil false nil) vals first)
" frame-ancestors 'none';")
"Content-Type" "text/plain"
"Expires" "Tue, 03 Jul 2001 06:00:00 GMT"
diff --git a/test/metabase/app_db/general_schema_tests.clj b/test/metabase/app_db/general_schema_tests.clj
index d2b7c190fe9..dbe4c00f246 100644
--- a/test/metabase/app_db/general_schema_tests.clj
+++ b/test/metabase/app_db/general_schema_tests.clj
@@ -17,7 +17,8 @@
(deftest ^:parallel fks-are-indexed-test
(when (= (mdb/db-type) :postgres)
- (let [excluded-fks #{}
+ (let [excluded-fks #{{:table_name "data_app"
+ :column_name "creator_id"}}
indexed-fks (t2/query
"SELECT
conrelid::regclass::text AS table_name,
diff --git a/test/metabase/cmd/copy_test.clj b/test/metabase/cmd/copy_test.clj
index 9fa960f0b95..64fe7e1e734 100644
--- a/test/metabase/cmd/copy_test.clj
+++ b/test/metabase/cmd/copy_test.clj
@@ -34,6 +34,7 @@
:model/CloudMigration
:model/ContentTranslation
:model/DashboardFavorite
+ :model/DataApp
:model/DataComplexityScore
:model/DatabaseRouter
:model/Dependency
diff --git a/test/metabase/internal_stats/data_apps_test.clj b/test/metabase/internal_stats/data_apps_test.clj
new file mode 100644
index 00000000000..e0e9505bf3e
--- /dev/null
+++ b/test/metabase/internal_stats/data_apps_test.clj
@@ -0,0 +1,38 @@
+(ns metabase.internal-stats.data-apps-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.internal-stats.data-apps :as sut]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(defn- data-app!
+ "Inserts straight into the table, the way [[sut/data-app-stats]] reads it — `:model/DataApp` is EE-only and
+ this namespace is OSS."
+ [& {:as extra}]
+ (let [app-name (mt/random-name)]
+ (t2/insert! :data_app (merge {:name app-name
+ :display_name "App"
+ :bundle_path "data_apps/app/index.js"
+ :created_at :%now
+ :updated_at :%now}
+ extra))
+ app-name))
+
+(deftest data-app-stats-counts-enabled-apps-test
+ (mt/initialize-if-needed! :db)
+ (let [app-names (atom [])
+ create! (fn [& {:as extra}] (swap! app-names conj (data-app! extra)))]
+ (try
+ (let [before (:data-app-count (sut/data-app-stats))]
+ (create!)
+ (create!)
+ (testing "a synced app is enabled by default, and counts"
+ (is (= 2 (- (:data-app-count (sut/data-app-stats)) before))))
+ (testing "an app the admin disabled is out of service, so it doesn't count"
+ (create! :enabled false)
+ (is (= 2 (- (:data-app-count (sut/data-app-stats)) before))))
+ (testing "an app that failed to sync is not served, so it doesn't count even when enabled"
+ (create! :sync_error "boom")
+ (is (= 2 (- (:data-app-count (sut/data-app-stats)) before)))))
+ (finally
+ (t2/delete! :data_app :name [:in @app-names])))))
diff --git a/test/metabase/lib/query/test_spec_test.cljc b/test/metabase/lib/query/test_spec_test.cljc
index 1dad67447ca..a5efe2da68b 100644
--- a/test/metabase/lib/query/test_spec_test.cljc
+++ b/test/metabase/lib/query/test_spec_test.cljc
@@ -113,6 +113,17 @@
(is (=? [[:count {}]]
(lib/aggregations query))))))
+(deftest ^:parallel test-query-with-metric-aggregation-test
+ (testing "test-query adds Metrics as aggregations"
+ (let [query (lib.query.test-spec/test-query
+ lib.tu/metadata-provider-with-metric
+ {:stages [{:source {:type :table
+ :id (meta/id :checkins)}
+ :aggregations [{:type :metric
+ :id 1}]}]})]
+ (is (=? [[:metric {} 1]]
+ (lib/aggregations query))))))
+
(deftest ^:parallel test-query-with-breakouts-test
(testing "test-query adds breakouts to the query"
(let [query (lib.query.test-spec/test-query
@@ -633,6 +644,17 @@
{:source-field (meta/id :orders :product-id)}
(meta/id :products :created-at)]]
(lib/breakouts query)))
+ (let [query (lib.query.test-spec/test-query
+ meta/metadata-provider
+ {:stages [{:source {:type :table
+ :id (meta/id :orders)}
+ :breakouts [{:type :column
+ :name "CATEGORY"
+ :source-field-id (meta/id :orders :product-id)}]}]})]
+ (is (=? [[:field
+ {:source-field (meta/id :orders :product-id)}
+ (meta/id :products :category)]]
+ (lib/breakouts query))))
(let [query (lib.query.test-spec/test-query
meta/metadata-provider
{:stages [{:source {:type :table
diff --git a/test/metabase/query_processor/api_test.clj b/test/metabase/query_processor/api_test.clj
index 17832919b71..d9cefb7a97b 100644
--- a/test/metabase/query_processor/api_test.clj
+++ b/test/metabase/query_processor/api_test.clj
@@ -133,6 +133,7 @@
:started_at true
:running_time true
:embedding_client nil
+ :embedding_client_identifier nil
:embedding_hostname nil
:embedding_path nil
:embedding_route nil
diff --git a/test/metabase/server/middleware/sdk_test.clj b/test/metabase/server/middleware/sdk_test.clj
index 53106d4f2a5..ae73797f707 100644
--- a/test/metabase/server/middleware/sdk_test.clj
+++ b/test/metabase/server/middleware/sdk_test.clj
@@ -16,10 +16,11 @@
(f char)))))
(defn- mock-request
- [{:keys [client version]}]
+ [{:keys [client version identifier]}]
(cond-> (ring.mock/request :get "api/health")
- client (ring.mock/header (keyword (wonk-case "x-metabase-client")) client)
- version (ring.mock/header (keyword (wonk-case "x-metabase-client-version")) version)))
+ client (ring.mock/header (keyword (wonk-case "x-metabase-client")) client)
+ version (ring.mock/header (keyword (wonk-case "x-metabase-client-version")) version)
+ identifier (ring.mock/header (keyword (wonk-case "x-metabase-client-identifier")) identifier)))
(deftest bind-client-test
(are [client]
@@ -43,6 +44,30 @@
nil
"1.1.1"))
+(deftest bind-client-identifier-test
+ (are [identifier]
+ (let [request (mock-request {:client "data-app" :identifier identifier})
+ handler (analytics.core/embedding-mw
+ (fn [_ respond _] (respond {:status 200 :body (sdk/get-client-identifier)})))
+ response (handler request identity identity)]
+ (is (= identifier (:body response))))
+ nil
+ "my-data-app")
+ (testing "oversized identifiers are truncated to fit the varchar(254) column"
+ (let [request (mock-request {:client "data-app" :identifier (apply str (repeat 300 "a"))})
+ handler (analytics.core/embedding-mw
+ (fn [_ respond _] (respond {:status 200 :body (sdk/get-client-identifier)})))
+ response (handler request identity identity)]
+ (is (= 254 (count (:body response)))))))
+
+(deftest include-sdk-info-client-identifier-test
+ (binding [sdk/*client-identifier* "my-data-app"]
+ (is (=? {:embedding_client_identifier "my-data-app"}
+ (analytics.core/include-sdk-info {}))))
+ (testing "an existing value is kept when the var is unset"
+ (is (=? {:embedding_client_identifier "my-data-app"}
+ (analytics.core/include-sdk-info {:embedding_client_identifier "my-data-app"})))))
+
(deftest embeding-mw-bumps-metrics-with-react-sdk-client-header
(mt/with-prometheus-system! [_ system]
;; X-Metabase-Client header == "embedding-sdk-react" => SDK context
@@ -141,6 +166,22 @@
(is (= 1.0 (mt/metric-value system :metabase-embedding-simple/response {:status "400"})))
(is (= 1.0 (mt/metric-value system :metabase-embedding-simple/response {:status "500"}))))))
+(deftest embedding-mw-does-not-bump-metrics-with-data-app-client-header
+ (let [prometheus-standin (atom {})]
+ (mt/with-dynamic-fn-redefs [analytics/inc! (fn [k _] (swap! prometheus-standin update k (fnil inc 0)))]
+ ;; data-app is a known SDK client, but a response-code counter tells us nothing
+ ;; actionable about data apps, so the middleware intentionally emits no metric.
+ (let [request (mock-request {:client "data-app"})
+ good (analytics.core/embedding-mw (fn [_ respond _] (respond {:status 200})))
+ bad (analytics.core/embedding-mw (fn [_ respond _] (respond {:status 400})))
+ exception (analytics.core/embedding-mw (fn [_ _respond raise] (raise {})))]
+ (good request identity identity)
+ (is (= {} @prometheus-standin))
+ (bad request identity identity)
+ (is (= {} @prometheus-standin))
+ (exception request identity identity)
+ (is (= {} @prometheus-standin))))))
+
(deftest embeding-mw-does-not-bump-metrics-with-random-sdk-header
(let [prometheus-standin (atom {})]
(mt/with-dynamic-fn-redefs [analytics/inc! (fn [k _] (swap! prometheus-standin update k (fnil inc 0)))]
@@ -281,7 +322,18 @@
(let [request (-> (ring.mock/request :get "/api/embed/dashboard/42")
(assoc :uri "/api/embed/dashboard/42")
(ring.mock/header "x-metabase-client" "embedding-sdk-react"))]
- (is (= "embedding-sdk-react" (client-from-mw request))))))
+ (is (= "embedding-sdk-react" (client-from-mw request)))))
+ (testing "a dev data app (preview header) is recorded as data-app-preview"
+ (let [request (-> (ring.mock/request :get "/api/card/1")
+ (ring.mock/header "x-metabase-client" "data-app")
+ (ring.mock/header "x-metabase-embedded-preview" "true"))]
+ (is (= "data-app-preview" (client-from-mw request))))))
+
+(deftest embedding-context?-test
+ (testing "data-app requests are an embedding context (comments gating + response tracking apply)"
+ (is (analytics.core/embedding-context? "data-app")))
+ (testing "arbitrary client values are not"
+ (is (not (analytics.core/embedding-context? "my-app")))))
(deftest include-analytics-is-idempotent
(let [m (atom {})]
diff --git a/test/metabase/server/middleware/security_test.clj b/test/metabase/server/middleware/security_test.clj
index 3c41fef867d..2c3ec6f1583 100644
--- a/test/metabase/server/middleware/security_test.clj
+++ b/test/metabase/server/middleware/security_test.clj
@@ -20,6 +20,13 @@
(as-> xs (filter #(str/starts-with? % (str directive " ")) xs))
first))
+(defn- csp-directive-from-response
+ [response directive]
+ (-> (get-in response [:headers "Content-Security-Policy"])
+ (str/split #"; *")
+ (as-> xs (filter #(str/starts-with? % (str directive " ")) xs))
+ first))
+
(defn- x-frame-options-header
[]
(get (mw.security/security-headers) "X-Frame-Options"))
@@ -79,6 +86,114 @@
(is (= (str "ALLOW-FROM " (first embedding-app-origins))
(x-frame-options-header))))))))
+(defn- headers-for-uri
+ "Run the security-headers middleware for a request to `uri` and return its headers."
+ [uri]
+ (let [handler (mw.security/add-security-headers
+ (fn [_request respond _raise] (respond {:status 200 :headers {} :body "ok"})))]
+ (:headers (handler {:uri uri :headers {}} identity identity))))
+
+(defn- frame-ancestors-for [uri]
+ (->> (str/split (get (headers-for-uri uri) "Content-Security-Policy") #"; *")
+ (filter #(str/starts-with? % "frame-ancestors "))
+ first))
+
+(deftest data-app-frame-ancestors-test
+ (testing "the internal data-app iframe is framable only by the same-origin host"
+ (is (= "frame-ancestors 'self'" (frame-ancestors-for "/embed/apps/sales")))
+ (is (= "frame-ancestors 'self'" (frame-ancestors-for "/embed/apps/sales/sub/route")))
+ (is (= "SAMEORIGIN" (get (headers-for-uri "/embed/apps/sales") "X-Frame-Options"))))
+ (testing "other /embed and /public pages keep open framing (unchanged)"
+ (doseq [uri ["/embed/dashboard/abc" "/public/question/abc"]]
+ (is (= "frame-ancestors *" (frame-ancestors-for uri)))
+ (is (nil? (get (headers-for-uri uri) "X-Frame-Options")))))
+ (testing "the top-level /apps page itself is not framable"
+ (mt/with-temporary-setting-values [enable-embedding-interactive false]
+ (is (= "frame-ancestors 'none'" (frame-ancestors-for "/apps/sales")))
+ (is (= "DENY" (get (headers-for-uri "/apps/sales") "X-Frame-Options"))))))
+
+(defn- csp-directive-for [uri directive]
+ (->> (str/split (get (headers-for-uri uri) "Content-Security-Policy") #"; *")
+ (filter #(str/starts-with? % (str directive " ")))
+ first))
+
+(deftest data-app-form-action-test
+ (testing "with no allowed_hosts, native <form action> submits are blocked (client-side onSubmit still works)"
+ (with-redefs [mw.security/data-app-connect-src-hosts (constantly [])]
+ (is (= "form-action 'none'" (csp-directive-for "/embed/apps/sales" "form-action")))
+ (is (= "form-action 'none'"
+ (csp-directive-for "/embed/apps/sales/sub/route" "form-action")))))
+ (testing "form-action mirrors the app's allowed_hosts (like connect-src)"
+ (with-redefs [mw.security/data-app-connect-src-hosts
+ (constantly ["https://api.example.com" "https://*.trusted.test"])]
+ (is (= "form-action https://api.example.com https://*.trusted.test"
+ (csp-directive-for "/embed/apps/sales" "form-action")))))
+ (testing "other documents leave form-action unset (falls through to no restriction)"
+ (doseq [uri ["/embed/dashboard/abc" "/public/question/abc" "/apps/sales"]]
+ (is (nil? (csp-directive-for uri "form-action"))))))
+
+(deftest data-app-frame-src-test
+ (testing "a data app's frame-src is a per-app allowlist: only 'self' + its allowed_hosts"
+ ;; A global iframe host (wikipedia) is configured but must NOT leak into a data
+ ;; app's frame-src — the app can only frame what it declares.
+ (mt/with-temporary-setting-values [allowed-iframe-hosts "https://www.wikipedia.org"]
+ (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://example.com"])]
+ ;; Both the top page and the iframe doc: the top page's `frame-src` gates
+ ;; what the iframe below it may navigate to.
+ (doseq [uri ["/apps/sales" "/embed/apps/sales"]]
+ (let [frame-src (csp-directive-for uri "frame-src")]
+ (is (str/includes? frame-src "'self'") uri)
+ (is (str/includes? frame-src "https://example.com") uri)
+ (is (not (str/includes? frame-src "wikipedia"))
+ (str uri " must not include the instance-wide iframe hosts")))))))
+ (testing "with no allowed_hosts, a data app can only frame 'self'"
+ (with-redefs [mw.security/data-app-connect-src-hosts (constantly [])]
+ (is (= "frame-src 'self'" (csp-directive-for "/embed/apps/sales" "frame-src")))))
+ (testing "non-data-app documents keep the instance-wide iframe hosts, not app hosts"
+ (mt/with-temporary-setting-values [allowed-iframe-hosts "https://www.wikipedia.org"]
+ (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://example.com"])]
+ (let [frame-src (csp-directive-for "/embed/dashboard/abc" "frame-src")]
+ (is (str/includes? frame-src "wikipedia"))
+ (is (not (str/includes? frame-src "https://example.com"))))))))
+
+(deftest data-app-instance-origin-excluded-test
+ (testing "the Metabase instance origin is dropped from a data app's allowlist even if listed"
+ (mt/with-temporary-setting-values [site-url "https://mymetabase.example"]
+ (with-redefs [mw.security/data-app-connect-src-hosts
+ (constantly ["https://mymetabase.example" "https://api.allowed.test"])]
+ (let [form-action (csp-directive-for "/embed/apps/sales" "form-action")
+ frame-src (csp-directive-for "/embed/apps/sales" "frame-src")
+ connect-src (csp-directive-for "/embed/apps/sales" "connect-src")]
+ (testing "the genuinely-external host survives"
+ (is (str/includes? form-action "https://api.allowed.test"))
+ (is (str/includes? frame-src "https://api.allowed.test"))
+ (is (str/includes? connect-src "https://api.allowed.test")))
+ (testing "the instance origin is filtered out (no native form/frame/fetch to Metabase)"
+ (is (not (str/includes? form-action "mymetabase.example")))
+ (is (not (str/includes? frame-src "https://mymetabase.example")))
+ (is (not (str/includes? connect-src "https://mymetabase.example")))))))))
+
+(deftest data-app-connect-src-test
+ (testing "a data app's allowed_hosts are added to the iframe document's connect-src"
+ (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://api.example.com"])]
+ (is (str/includes? (csp-directive-for "/embed/apps/sales" "connect-src")
+ "https://api.example.com"))))
+ (testing "with no allowed_hosts, the iframe connect-src has no app hosts (same as any doc)"
+ (with-redefs [mw.security/data-app-connect-src-hosts (constantly [])]
+ (is (= (csp-directive-for "/embed/apps/sales" "connect-src")
+ (csp-directive-for "/embed/dashboard/abc" "connect-src")))))
+ (testing "the top-level /data-app page keeps a tight connect-src — hosts go to the iframe doc, not here"
+ (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://api.example.com"])]
+ (is (not (str/includes? (csp-directive-for "/apps/sales" "connect-src")
+ "https://api.example.com")))
+ ;; ...but the top page still gets them in frame-src (it gates the iframe's nav).
+ (is (str/includes? (csp-directive-for "/apps/sales" "frame-src")
+ "https://api.example.com"))))
+ (testing "non-data-app documents don't get app hosts in connect-src"
+ (with-redefs [mw.security/data-app-connect-src-hosts (constantly ["https://api.example.com"])]
+ (is (not (str/includes? (csp-directive-for "/embed/dashboard/abc" "connect-src")
+ "https://api.example.com"))))))
+
(deftest nonce-test
(testing "The nonce in the CSP header should match the nonce in the HTML from a index.html request"
(let [nonceJSON (atom nil)
@@ -105,6 +220,61 @@
(testing "The same nonce is in the body of the rendered page"
(is (str/includes? (:body response) nonce))))))))
+(deftest data-app-inline-style-csp-test
+ (testing "Only data-app iframe responses allow inline styles"
+ (with-redefs [config/is-dev? false]
+ (let [wrapped-handler (mw.security/add-security-headers
+ (fn [_request respond _raise]
+ (respond {:status 200 :headers {} :body "ok"})))
+ app-response (wrapped-handler {:uri "/"
+ :headers {}}
+ identity
+ identity)
+ data-response (wrapped-handler {:uri "/embed/apps/boba"
+ :headers {}}
+ identity
+ identity)
+ app-style-src (csp-directive-from-response app-response "style-src")
+ data-style-src (csp-directive-from-response data-response "style-src")
+ data-script-src (csp-directive-from-response data-response "script-src")]
+ (is (str/includes? app-style-src "'nonce-"))
+ (is (not (str/includes? app-style-src "'unsafe-inline'")))
+ (is (str/includes? data-style-src "'unsafe-inline'"))
+ (is (not (str/includes? data-style-src "'nonce-")))
+ (is (str/includes? data-script-src "'nonce-"))
+ (is (not (str/includes? data-script-src "'unsafe-inline'")))))))
+
+(deftest data-app-unsafe-eval-csp-test
+ (testing "Only data-app iframe responses allow 'unsafe-eval' in script-src"
+ ;; Data apps run their uploaded bundle through a Near-Membrane sandbox whose
+ ;; same-origin child iframe inherits this document's CSP and evaluates the
+ ;; bundle source via `eval`, so the data-app entrypoint must permit
+ ;; 'unsafe-eval' while the main app CSP stays strict.
+ (with-redefs [config/is-dev? false]
+ (let [wrapped-handler (mw.security/add-security-headers
+ (fn [_request respond _raise]
+ (respond {:status 200 :headers {} :body "ok"})))
+ script-src-for (fn [uri]
+ (-> (wrapped-handler {:uri uri :headers {}} identity identity)
+ (csp-directive-from-response "script-src")))]
+ (is (not (str/includes? (script-src-for "/") "'unsafe-eval'")))
+ (is (str/includes? (script-src-for "/embed/apps/boba") "'unsafe-eval'"))
+ ;; sub-routes under the data-app entrypoint are the same SPA shell
+ (is (str/includes? (script-src-for "/embed/apps/boba/sub/route") "'unsafe-eval'"))))))
+
+(deftest data-app-blob-img-csp-test
+ (testing "Only data-app iframe responses allow the blob: scheme in img-src"
+ (with-redefs [config/is-dev? false]
+ (let [wrapped-handler (mw.security/add-security-headers
+ (fn [_request respond _raise]
+ (respond {:status 200 :headers {} :body "ok"})))
+ img-src-for (fn [uri]
+ (-> (wrapped-handler {:uri uri :headers {}} identity identity)
+ (csp-directive-from-response "img-src")))]
+ (is (not (str/includes? (img-src-for "/") "blob:")))
+ (is (str/includes? (img-src-for "/embed/apps/boba") "blob:"))
+ (is (str/includes? (img-src-for "/embed/apps/boba/sub/route") "blob:"))))))
+
(deftest ^:parallel test-parse-url
(testing "Should parse valid urls"
(are [url expected] (= expected
diff --git a/test/metabase/typed_schemas/api/common_test.clj b/test/metabase/typed_schemas/api/common_test.clj
new file mode 100644
index 00000000000..b97ce286bee
--- /dev/null
+++ b/test/metabase/typed_schemas/api/common_test.clj
@@ -0,0 +1,62 @@
+(ns metabase.typed-schemas.api.common-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.typed-schemas.api.common :as typed-schemas.api.common]))
+
+(deftest column-schema-includes-description-test
+ (is (= {:type "column"
+ :name "name"
+ :displayName "Name"
+ :baseType "type/Text"
+ :jsType "string"
+ :description "Name of the customer"}
+ (#'typed-schemas.api.common/column-schema {:name "name"
+ :display_name "Name"
+ :base_type "type/Text"
+ :description "Name of the customer"}))))
+
+(deftest column-schema-maps-metabase-types-test
+ (are [column js-type] (= js-type
+ (:jsType (#'typed-schemas.api.common/column-schema column)))
+ {:name "bool", :base_type :type/Boolean} "boolean"
+ {:name "int", :base_type :type/Integer} "number"
+ {:name "date", :base_type :type/DateTime} "Date"
+ {:name "uuid", :base_type :type/UUID} "string"
+ {:name "string", :base_type "type/Text"} "string"
+ {:name "decimal", :base_type "Decimal"} "number"
+ {:name "effective", :effective_type :type/Text} "string"
+ {:name "unknown", :base_type :type/Structured} "unknown"))
+
+(deftest keyed-map-disambiguates-duplicate-keys-with-readable-suffix-test
+ (is (= {"channelOrderItems" {:key "channelOrderItems"
+ :id "40f15584-bca0-4557-910d-e5e789757f23"
+ :tableId 261}
+ "channelOrders" {:key "channelOrders"
+ :id "ca9bef16-d484-4add-8245-ddbc78287e8f"
+ :tableId 167}}
+ (#'typed-schemas.api.common/keyed-map
+ [{:key "channel"
+ :id "ca9bef16-d484-4add-8245-ddbc78287e8f"
+ :tableId 167
+ :keyDisambiguator "Orders"}
+ {:key "channel"
+ :id "40f15584-bca0-4557-910d-e5e789757f23"
+ :tableId 261
+ :keyDisambiguator "OrderItems"}]))))
+
+(deftest keyed-map-falls-back-to-id-when-readable-suffix-does-not-disambiguate-test
+ (is (= {"channelOrders1" {:key "channelOrders1"
+ :id 1
+ :tableId 167}
+ "channelOrders2" {:key "channelOrders2"
+ :id 2
+ :tableId 168}}
+ (#'typed-schemas.api.common/keyed-map
+ [{:key "channel"
+ :id 1
+ :tableId 167
+ :keyDisambiguator "Orders"}
+ {:key "channel"
+ :id 2
+ :tableId 168
+ :keyDisambiguator "Orders"}]))))
diff --git a/test/metabase/typed_schemas/api/render_test.clj b/test/metabase/typed_schemas/api/render_test.clj
new file mode 100644
index 00000000000..46f6cc97814
--- /dev/null
+++ b/test/metabase/typed_schemas/api/render_test.clj
@@ -0,0 +1,109 @@
+(ns metabase.typed-schemas.api.render-test
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase.typed-schemas.api.render :as typed-schemas.api.render]))
+
+(def ^:private orders-question
+ {:type "card"
+ :description "Saved orders"})
+
+(def ^:private orders-table
+ {:type "table"
+ :id 10
+ :fields {"paymentMethod" {:type "column"
+ :name "payment_method"
+ :displayName "Payment Method"
+ :semanticType "type/Category"
+ :jsType "string"
+ :fieldId 3970
+ :tableId 10}}})
+
+(def ^:private franchises-table
+ {:type "table"
+ :id 20
+ :fields {"name" {:type "column"
+ :name "name"
+ :displayName "Name"
+ :jsType "string"
+ :fieldId 500
+ :tableId 20}}})
+
+(def ^:private payment-method-dimension
+ {:name "payment_method"
+ :displayName "Payment Method"
+ :semanticType "type/Category"
+ :fieldId 3970
+ :tableId 10
+ :metricId 5})
+
+(def ^:private franchise-name-dimension
+ {:name "name"
+ :fieldId 500
+ :tableId 20
+ :sourceFieldId 42
+ :metricId 5})
+
+(def ^:private revenue-metric
+ {:type "metric"
+ :databaseId 1
+ :sourceTableId 10
+ :description "Total order revenue"
+ :mappedTableIds [10 20]
+ :dimensions {"paymentMethod" payment-method-dimension
+ "franchiseName" franchise-name-dimension}})
+
+(def ^:private compacting-schema
+ {:schemaVersion 2
+ :questions {"ordersQuestion" orders-question}
+ :tables {"orders" orders-table
+ "franchises" franchises-table}
+ :metrics {"revenue" revenue-metric}})
+
+(def ^:private raw-dimensions-schema
+ {:schemaVersion 2
+ :metrics {"modelRevenue" {:type "metric"
+ :id 6
+ :name "Model Revenue"
+ :dimensions {"createdAt" {:type "column"
+ :name "created_at"
+ :baseType "type/DateTime"
+ :jsType "Date"}}}}})
+
+(deftest typescript-renderer-emits-comments-and-runtime-metadata-test
+ (let [body (typed-schemas.api.render/render-typescript compacting-schema)]
+ ;; Emit comments to provide context for agents
+ (is (str/includes? body "// Description: Saved orders"))
+ (is (str/includes? body "// Description: Total order revenue"))
+ (is (str/includes? body "// Display name: Payment Method"))
+ (is (str/includes? body "// Semantic type: type/Category"))
+ ;; Emit metadata needed for the Lib.createTestQuery DSL
+ (is (str/includes? body "ordersQuestion: {\n type: \"card\""))
+ (is (str/includes? body "paymentMethod: {\n type: \"column\""))
+ (is (str/includes? body "databaseId: 1"))
+ (is (str/includes? body "sourceTableId: 10"))
+ (is (str/includes? body "mappedTableIds: [ 10, 20 ]"))
+ ;; Comment-only metadata should not become runtime fields.
+ (is (not (str/includes? body "displayName: \"Payment Method\"")))))
+
+(deftest typescript-renderer-compacts-metric-dimensions-test
+ (let [body (typed-schemas.api.render/render-typescript compacting-schema)]
+ ;; Metric dimensions should compact into pickFields(...) references.
+ (is (str/includes? body "function pickFields"))
+ (is (str/includes? body "const field = fields[key] as { tableId?: number };"))
+ (is (str/includes? body "const { tableId, ...joinedField } = field;"))
+ (is (str/includes? body "orders: pickFields(tables.orders.fields, [ \"paymentMethod\" ])"))
+ (is (str/includes? body "franchises: pickFields(tables.franchises.fields, [ \"name\" ], { sourceFieldId: 42 })"))
+ ;; Source field id should be preserved.
+ (is (= 1 (count (re-seq #"sourceFieldId: 42" body))))
+ ;; `metricId` is only used to identify dimensions while compacting them.
+ ;; The generated TypeScript module should not contain metric id.
+ (is (not (str/includes? body "metricId: 5")))))
+
+(deftest typescript-renderer-omits-pick-fields-helper-for-raw-dimensions-test
+ (let [body (typed-schemas.api.render/render-typescript raw-dimensions-schema)]
+ ;; Dimensions that cannot be resolved to table fields stay as raw fields, so
+ ;; the rendered module should not include the pickFields helper.
+ (is (not (str/includes? body "function pickFields")))
+ (is (not (str/includes? body "pickFields(")))
+ (is (str/includes? body "fields: {\n createdAt: {"))))
diff --git a/test/metabase/typed_schemas/api/schema/metric_test.clj b/test/metabase/typed_schemas/api/schema/metric_test.clj
new file mode 100644
index 00000000000..71e8bbb5c5a
--- /dev/null
+++ b/test/metabase/typed_schemas/api/schema/metric_test.clj
@@ -0,0 +1,191 @@
+(ns metabase.typed-schemas.api.schema.metric-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.metabot.core :as metabot]
+ [metabase.models.interface :as mi]
+ [metabase.test :as mt]
+ [metabase.typed-schemas.api.schema.metric :as schema.metric]
+ [metabase.typed-schemas.api.schema.table :as schema.table]
+ [toucan2.core :as t2]))
+
+(deftest ^:parallel metric-dimension-schema-uses-dimension-id-test
+ (is (= {:type "column"
+ :name "category"
+ :displayName "Category"
+ :baseType "type/Text"
+ :jsType "string"
+ :key "category"
+ :id "550e8400-e29b-41d4-a716-446655440001"
+ :fieldId 3815
+ :tableId 12
+ :metricId 247}
+ (#'schema.metric/dimension-schema
+ {:id "550e8400-e29b-41d4-a716-446655440001"
+ :name "category"
+ :display-name "Category"
+ :effective-type :type/Text
+ :table-id 12
+ :sources [{:type :field, :field-id 3815}]}
+ 247))))
+
+(deftest ^:parallel metric-dimension-schema-preserves-source-field-id-test
+ (is (= 102
+ (:sourceFieldId
+ (#'schema.metric/dimension-schema
+ {:id "category-dimension"
+ :name "category"
+ :source-field-id 102}
+ 247)))))
+
+(deftest ^:parallel metric-source-id-test
+ (testing "integer source-table emits sourceTableId but not sourceCardId"
+ (let [card {:dataset_query {:query {:source-table 10}}}]
+ (is (= 10 (#'schema.metric/source-table-id card)))
+ (is (nil? (#'schema.metric/source-card-id card)))))
+ (testing "card source-table emits sourceCardId but not sourceTableId"
+ (let [card {:dataset_query {:query {:source-table "card__42"}}}]
+ (is (nil? (#'schema.metric/source-table-id card)))
+ (is (= 42 (#'schema.metric/source-card-id card)))))
+ (testing "stage source-card emits sourceCardId"
+ (is (= 42 (#'schema.metric/source-card-id
+ {:dataset_query {:stages [{:source-card 42}]}})))))
+
+(deftest metric-details-skips-default-temporal-breakout-test
+ (mt/with-dynamic-fn-redefs [metabot/get-metric-details
+ (fn [options]
+ (is (false? (:with-default-temporal-breakout? options)))
+ {:structured-output {:id 247}})]
+ (is (= {:id 247}
+ (#'schema.metric/metric-details {:id 247})))))
+
+(deftest metric-details-surfaces-error-responses-test
+ (mt/with-dynamic-fn-redefs [metabot/get-metric-details
+ (constantly {:output "Not found."
+ :status-code 404})]
+ (let [exception (try
+ (#'schema.metric/metric-details {:id 247
+ :name "Customer Lifetime Value"
+ :type :metric})
+ (catch clojure.lang.ExceptionInfo exception
+ exception))]
+ (is (instance? clojure.lang.ExceptionInfo exception))
+ (is (= {:card-id 247
+ :card-name "Customer Lifetime Value"
+ :card-type :metric
+ :status-code 404
+ :error-message "Not found."}
+ (ex-data exception))))))
+
+(deftest table-source-names-filters-unreadable-tables-test
+ (with-redefs [t2/select (constantly [{:id 10 :name "orders" :display_name "Orders"}
+ {:id 20 :name "franchises" :display_name "Franchises"}])
+ mi/can-read? (fn [{:keys [id]}] (= id 10))]
+ (is (= {10 "orders"}
+ (#'schema.metric/table-source-names [10 20])))
+ (is (= {10 "Orders"}
+ (#'schema.metric/table-key-disambiguators [10 20])))))
+
+(deftest metric-schema-keys-dimensions-test
+ (with-redefs [schema.metric/metric-result-column (constantly nil)
+ schema.metric/readable-table-source-rows
+ (constantly [{:id 10 :name "orders" :display_name "Orders"}])
+ schema.metric/sync-and-fetch-metric-dimensions!
+ (constantly [{:id "550e8400-e29b-41d4-a716-446655440001"
+ :name "orders"
+ :display-name "Orders"
+ :effective-type :type/Integer
+ :table-id 10
+ :sources [{:type :field, :field-id 42}]}])]
+ (is (= {:type "metric"
+ :key "customerLifetimeValue"
+ :id 247
+ :name "Customer Lifetime Value"
+ :columns [{:type "column"
+ :name "Customer Lifetime Value"
+ :displayName "Customer Lifetime Value"
+ :jsType "unknown"}]
+ :mappedTableIds [10]
+ :dimensions {"orders" {:type "column"
+ :name "orders"
+ :sourceName "orders"
+ :displayName "Orders"
+ :baseType "type/Integer"
+ :jsType "number"
+ :key "orders"
+ :id "550e8400-e29b-41d4-a716-446655440001"
+ :fieldId 42
+ :tableId 10
+ :metricId 247}}}
+ (#'schema.metric/metric-schema
+ {:id 247
+ :name "Customer Lifetime Value"}
+ {:id 247})))))
+
+(deftest metric-schema-reuses-table-source-rows-test
+ (let [table-select-count (atom 0)]
+ (with-redefs [schema.metric/metric-result-column (constantly nil)
+ schema.metric/sync-and-fetch-metric-dimensions!
+ (constantly [{:id "orders-dimension"
+ :name "orders"
+ :table-id 10}])
+ mi/can-read? (constantly true)
+ t2/select (fn [columns & _args]
+ (when (= columns [:model/Table :id :name :display_name])
+ (swap! table-select-count inc)
+ [{:id 10 :name "orders" :display_name "Orders"}]))]
+ (#'schema.metric/metric-schema
+ {:id 247
+ :name "Customer Lifetime Value"}
+ {:id 247})
+ (is (= 1 @table-select-count)))))
+
+(deftest metric-dimensions-bulk-load-table-ids-test
+ (let [field-select-count (atom 0)
+ field-lookup-attempts (atom [])
+ dimensions [{:id "orders-dimension"
+ :sources [{:type :field, :field-id 42}]}
+ {:id "people-dimension"
+ :sources [{:type :field, :field-id 84}]}]]
+ (mt/with-dynamic-fn-redefs [schema.metric/sync-and-fetch-metric-dimensions! (constantly dimensions)
+ schema.table/table-by-field-id (fn [field-id]
+ (swap! field-lookup-attempts conj field-id)
+ ({42 10, 84 20} field-id))
+ t2/select (fn [columns & _args]
+ (when (= columns [:model/Field :id :table_id])
+ (swap! field-select-count inc)
+ [{:id 42 :table_id 10}
+ {:id 84 :table_id 20}]))]
+ (is (= (mapv vector dimensions [10 20])
+ (#'schema.metric/metric-dimensions-with-table-ids {:id 247} nil)))
+ (is (= 1 @field-select-count))
+ (is (empty? @field-lookup-attempts)))))
+
+(deftest source-card-metric-schema-omits-mapped-table-dimensions-test
+ (with-redefs [schema.metric/metric-result-column (constantly nil)
+ schema.metric/sync-and-fetch-metric-dimensions!
+ (constantly [{:id "count-dimension-uuid"
+ :name "count"}
+ {:id "store-name-dimension-uuid"
+ :name "store_name"
+ :table-id 10}])]
+ (is (= {:type "metric"
+ :key "storesWithOver5Employees"
+ :id 259
+ :name "Stores with Over 5 Employees"
+ :columns [{:type "column"
+ :name "Stores with Over 5 Employees"
+ :displayName "Stores with Over 5 Employees"
+ :jsType "unknown"}]
+ :sourceCardId 258
+ :dimensions {"count" {:type "column"
+ :name "count"
+ :displayName "count"
+ :jsType "unknown"
+ :key "count"
+ :id "count-dimension-uuid"
+ :metricId 259}}}
+ (#'schema.metric/metric-schema
+ {:id 259
+ :name "Stores with Over 5 Employees"}
+ {:id 259
+ :dataset_query {:stages [{:source-card 258}]}})))))
diff --git a/test/metabase/typed_schemas/api/schema/model_test.clj b/test/metabase/typed_schemas/api/schema/model_test.clj
new file mode 100644
index 00000000000..856003c9903
--- /dev/null
+++ b/test/metabase/typed_schemas/api/schema/model_test.clj
@@ -0,0 +1,115 @@
+(ns metabase.typed-schemas.api.schema.model-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.actions.core :as actions]
+ [metabase.typed-schemas.api.schema.common :as schema.common]
+ [metabase.typed-schemas.api.schema.model :as schema.model]))
+
+(deftest model-schema-includes-actions-test
+ (with-redefs [schema.model/model-action-schemas
+ (fn [model]
+ (is (= 42 (:id model)))
+ [{:kind "action", :key "create", :id 5}])]
+ (is (= {:key "ordersModel"
+ :keyDisambiguator 42
+ :actions {"create" {:kind "action", :key "create", :id 5}}}
+ (schema.model/model-schema
+ {:id 42
+ :name "Orders model"})))))
+
+(deftest model-schemas-includes-actionable-models-test
+ (with-redefs [schema.common/select-schema-cards
+ (fn [card-type database-ids collection-ids]
+ (is (= :model card-type))
+ (is (= #{1} database-ids))
+ (is (nil? collection-ids))
+ [{:id 42 :name "Model 42"}
+ {:id 43 :name "Model 43"}])
+ schema.model/action-rows
+ (constantly [{:id 5 :model_id 42 :name "Create" :type :query}])
+ actions/select-actions
+ (constantly [{:id 5
+ :model_id 42
+ :name "Create"
+ :type :query
+ :parameters []}])]
+ (is (= #{"model42"}
+ (->> (schema.model/model-schemas #{1})
+ (map :key)
+ set)))))
+
+; Ensures we are not doing N+1 queries for action rows and details
+(deftest model-schemas-bulk-loads-actions-test
+ (let [models [{:id 42 :name "Model 42"}
+ {:id 43 :name "Model 43"}]
+ action-rows-calls (atom [])
+ action-details-calls (atom [])]
+ (with-redefs [schema.common/select-schema-cards (constantly models)
+ schema.model/action-rows (fn [model-ids]
+ (swap! action-rows-calls conj model-ids)
+ [])
+ actions/select-actions (fn [known-models & options]
+ (swap! action-details-calls conj [known-models options])
+ [])]
+ (is (= [] (vec (schema.model/model-schemas #{1}))))
+ (is (= [#{42 43}] @action-rows-calls))
+ (is (= [[models [:model_id [:in #{42 43}]
+ :archived false
+ :type [:not= "http"]]]]
+ @action-details-calls)))))
+
+(deftest model-schema-surfaces-action-selection-errors-test
+ (with-redefs [schema.model/action-rows (constantly [])
+ actions/select-actions (fn [& _]
+ (throw (ex-info "action lookup failed"
+ {:status-code 500})))]
+ (let [exception (is (thrown? clojure.lang.ExceptionInfo
+ (schema.model/model-schema {:id 100
+ :name "Broken model"})))]
+ (is (= "Failed to build action schemas for model \"Broken model\" (card 100): action lookup failed"
+ (ex-message exception)))
+ (is (= {:model-id 100
+ :model-name "Broken model"
+ :status-code 500
+ :cause-message "action lookup failed"}
+ (select-keys (ex-data exception) [:model-id :model-name :status-code :cause-message]))))))
+
+(deftest model-schema-surfaces-action-rendering-errors-test
+ (with-redefs [actions/select-actions (constantly [{:id 200
+ :name "Broken action"
+ :type :query}])
+ schema.model/action-rows (constantly [{:id 200
+ :name "Broken action"
+ :type :query}])
+ schema.model/action-detail-schema (fn [& _]
+ (throw (ex-info "action parameters are invalid"
+ {:status-code 500})))]
+ (let [exception (is (thrown? clojure.lang.ExceptionInfo
+ (schema.model/model-schema {:id 100
+ :name "Broken model"})))]
+ (is (= "Failed to build action schema for action \"Broken action\" (action 200, type query) on model \"Broken model\" (card 100): action parameters are invalid"
+ (ex-message exception)))
+ (is (= {:model-id 100
+ :model-name "Broken model"
+ :action-id 200
+ :action-name "Broken action"
+ :action-type :query
+ :status-code 500
+ :cause-message "action parameters are invalid"}
+ (select-keys (ex-data exception)
+ [:model-id :model-name :action-id :action-name :action-type :status-code :cause-message]))))))
+
+(deftest model-schema-surfaces-unresolved-action-row-errors-test
+ (with-redefs [schema.model/action-rows (constantly [{:id 200
+ :name "Broken action"
+ :type :broken}])
+ actions/select-actions (constantly [])]
+ (let [exception (is (thrown? clojure.lang.ExceptionInfo
+ (schema.model/model-schema {:id 100
+ :name "Broken model"})))]
+ (is (= "Failed to build action schemas for model \"Broken model\" (card 100): action rows could not be resolved: Broken action (action 200, type broken)"
+ (ex-message exception)))
+ (is (= {:model-id 100
+ :model-name "Broken model"
+ :unresolved-action-rows [{:id 200, :name "Broken action", :type :broken}]}
+ (select-keys (ex-data exception) [:model-id :model-name :unresolved-action-rows]))))))
diff --git a/test/metabase/typed_schemas/api/schema/question_test.clj b/test/metabase/typed_schemas/api/schema/question_test.clj
new file mode 100644
index 00000000000..6f6c744d046
--- /dev/null
+++ b/test/metabase/typed_schemas/api/schema/question_test.clj
@@ -0,0 +1,39 @@
+(ns metabase.typed-schemas.api.schema.question-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.metabot.tools.entity-details :as entity-details]
+ [metabase.test :as mt]
+ [metabase.typed-schemas.api.schema.common :as schema.common]
+ [metabase.typed-schemas.api.schema.question :as schema.question]))
+
+(deftest question-schema-uses-card-source-discriminator-test
+ (is (= {:type "card"
+ :key "ordersQuestion"
+ :id 41
+ :name "Orders question"
+ :display "table"
+ :columns [{:type "column", :name "count", :displayName "Count", :jsType "number"}]}
+ (schema.question/question-schema
+ {:id 41
+ :name "Orders question"
+ :display "table"
+ :result-columns [{:name "count", :display_name "Count", :type :number}]}))))
+
+(deftest question-schemas-bulk-loads-details-by-database-test
+ (let [cards [{:id 41 :name "Orders question" :type :question :database_id 1 :display "table"}
+ {:id 42 :name "People question" :type :question :database_id 1 :display "table"}]
+ bulk-details-calls (atom [])
+ report-details-calls (atom [])]
+ (mt/with-dynamic-fn-redefs [entity-details/get-report-details
+ (fn [{:keys [report-id] :as options}]
+ (swap! report-details-calls conj options)
+ {:structured-output {:id report-id :result-columns []}})]
+ (with-redefs [schema.common/select-schema-cards (constantly cards)
+ entity-details/cards-details (fn [card-type database-id selected-cards _options]
+ (swap! bulk-details-calls conj [card-type database-id selected-cards])
+ (map #(assoc % :fields []) selected-cards))]
+ (is (= [41 42]
+ (mapv :id (schema.question/question-schemas nil))))
+ (is (= [[:question 1 cards]]
+ @bulk-details-calls))
+ (is (empty? @report-details-calls))))))
diff --git a/test/metabase/typed_schemas/api/schema/table_test.clj b/test/metabase/typed_schemas/api/schema/table_test.clj
new file mode 100644
index 00000000000..6c322d41527
--- /dev/null
+++ b/test/metabase/typed_schemas/api/schema/table_test.clj
@@ -0,0 +1,143 @@
+(ns metabase.typed-schemas.api.schema.table-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.lib-be.core :as lib-be]
+ [metabase.metabot.core :as metabot]
+ [metabase.test :as mt]
+ [metabase.typed-schemas.api.schema.common :as schema.common]
+ [metabase.typed-schemas.api.schema.table :as schema.table]
+ [toucan2.core :as t2]))
+
+(def ^:private created-at-field
+ {:id 42
+ :table_id 10
+ :name "created_at"
+ :display_name "Created At"
+ :base_type "type/DateTime"})
+
+(def ^:private created-at-field-schema
+ {:type "column"
+ :name "created_at"
+ :displayName "Created At"
+ :baseType "type/DateTime"
+ :jsType "Date"
+ :key "createdAt"
+ :id 42
+ :fieldId 42
+ :tableId 10})
+
+(def ^:private orders-table
+ {:id 10
+ :name "orders"
+ :display_name "Orders"
+ :database_id 1
+ :database_name "Boba"
+ :fields [created-at-field]})
+
+(def ^:private total-revenue-measure
+ {:id 1
+ :name "Total Revenue"})
+
+(def ^:private total-revenue-schema
+ {:type "measure"
+ :key "totalRevenue"
+ :id 1
+ :tableId 10
+ :name "Total Revenue"})
+
+(deftest field-schema-uses-field-id-test
+ (is (= created-at-field-schema
+ (schema.table/field-schema created-at-field))))
+
+(deftest table-schema-keys-fields-test
+ (is (= {:type "table"
+ :key "orders"
+ :id 10
+ :name "Orders"
+ :databaseName "Boba"
+ :tableName "orders"
+ :fields {"createdAt" (assoc created-at-field-schema :sourceName "orders")}}
+ (schema.table/table-schema orders-table))))
+
+; Avoid N+1 on table fields by re-using the known table id
+(deftest table-schema-uses-known-table-id-for-detail-fields-test
+ (let [field-table-lookups (atom 0)
+ detail-fields [{:field_id 42
+ :name "created_at"
+ :display_name "Created At"
+ :base_type "type/DateTime"}
+ {:field_id 43
+ :name "total"
+ :display_name "Total"
+ :base_type "type/Decimal"}]]
+ (with-redefs [t2/select-one-fn (fn [& _]
+ (swap! field-table-lookups inc)
+ 999)]
+ (let [schema (schema.table/table-schema (assoc orders-table :fields detail-fields))]
+ (is (= #{10} (->> (:fields schema) vals (map :tableId) set)))
+ (is (zero? @field-table-lookups))))))
+
+(deftest segment-schema-uses-type-discriminator-test
+ (is (= {:type "segment"
+ :key "completedOrders"
+ :id 12
+ :tableId 10
+ :name "Completed Orders"}
+ (schema.table/segment-schema
+ 10
+ {:id 12
+ :name "Completed Orders"
+ :display-name "Completed Orders"}))))
+
+(deftest measure-schema-uses-result-column-test
+ (testing "measure result columns come from the measure definition when available"
+ (with-redefs [schema.table/measure-result-column
+ (constantly {:name "sum"
+ :display_name "Sum of Total"
+ :base_type "type/Decimal"})]
+ (is (= (assoc total-revenue-schema
+ :columns [{:type "column"
+ :name "sum"
+ :displayName "Sum of Total"
+ :baseType "type/Decimal"
+ :jsType "number"}])
+ (schema.table/measure-schema 10 2 total-revenue-measure)))))
+ (testing "measure result columns fall back to the measure name"
+ (with-redefs [schema.table/measure-result-column (constantly nil)]
+ (is (= (assoc total-revenue-schema
+ :columns [{:type "column", :name "Total Revenue", :displayName "Total Revenue", :jsType "unknown"}])
+ (schema.table/measure-schema 10 2 total-revenue-measure))))))
+
+(deftest table-schemas-surface-detail-error-responses-test
+ (mt/with-dynamic-fn-redefs [metabot/get-table-details
+ (constantly {:output "Not found."
+ :status-code 404})]
+ (let [exception (try
+ (doall (schema.table/table-schemas [{:id 10 :name "Orders"}]))
+ (catch clojure.lang.ExceptionInfo exception
+ exception))]
+ (is (instance? clojure.lang.ExceptionInfo exception))
+ (is (= {:table-id 10
+ :table-name "Orders"
+ :status-code 404
+ :error-message "Not found."}
+ (ex-data exception))))))
+
+;; Batch measure definitions to avoid N+1 queries.
+(deftest table-schema-bulk-loads-measure-definitions-test
+ (let [measure-select-count (atom 0)
+ metadata-provider-count (atom 0)
+ measures [{:id 1 :name "Total Revenue"}
+ {:id 2 :name "Average Revenue"}]]
+ (with-redefs [lib-be/application-database-metadata-provider (fn [_database-id]
+ (swap! metadata-provider-count inc)
+ :metadata-provider)
+ schema.common/aggregation-result-column-with-metadata-provider (constantly nil)
+ t2/select (fn [columns & _args]
+ (when (= columns [:model/Measure :id :definition])
+ (swap! measure-select-count inc)
+ [{:id 1 :definition [:aggregation 1]}
+ {:id 2 :definition [:aggregation 2]}]))]
+ (schema.table/table-schema (assoc orders-table :measures measures))
+ (is (= 1 @measure-select-count))
+ (is (= 1 @metadata-provider-count)))))
diff --git a/test/metabase/typed_schemas/api/scope_test.clj b/test/metabase/typed_schemas/api/scope_test.clj
new file mode 100644
index 00000000000..e22e32d3fbb
--- /dev/null
+++ b/test/metabase/typed_schemas/api/scope_test.clj
@@ -0,0 +1,147 @@
+(ns metabase.typed-schemas.api.scope-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase.collections.models.collection :as collection]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.typed-schemas.api.scope :as typed-schemas.api.scope]))
+
+(use-fixtures :once (fixtures/initialize :db :test-users))
+
+(deftest library-collection-scope-accepts-subcollection-id-test
+ (mt/with-temp [:model/Collection root {:name "Library"
+ :type "library"
+ :location "/"}
+ :model/Collection data {:name "Data"
+ :type "library-data"
+ :location (collection/children-location root)}
+ :model/Collection child {:name "Boba Data"
+ :type "library-data"
+ :location (collection/children-location data)}]
+ (mt/with-test-user :crowberto
+ (is (= {:collection-ids #{(:id child)}
+ :data-collection-ids #{(:id child)}
+ :metric-collection-ids #{}}
+ (select-keys (#'typed-schemas.api.scope/library-collection-scope (str (:id child)))
+ [:collection-ids :data-collection-ids :metric-collection-ids]))))))
+
+(deftest library-collections-scope-accepts-comma-separated-subcollection-ids-test
+ (mt/with-temp [:model/Collection root {:name "Library"
+ :type "library"
+ :location "/"}
+ :model/Collection data {:name "Data"
+ :type "library-data"
+ :location (collection/children-location root)}
+ :model/Collection metrics {:name "Metrics"
+ :type "library-metrics"
+ :location (collection/children-location root)}
+ :model/Collection data-child {:name "Boba Data"
+ :type "library-data"
+ :location (collection/children-location data)}
+ :model/Collection data-grandkid {:name "Boba Data Nested"
+ :type "library-data"
+ :location (collection/children-location data-child)}
+ :model/Collection metric-child {:name "Boba Metrics"
+ :type "library-metrics"
+ :location (collection/children-location metrics)}]
+ (mt/with-test-user :crowberto
+ (is (= {:collection-ids #{(:id data-child) (:id data-grandkid) (:id metric-child)}
+ :data-collection-ids #{(:id data-child) (:id data-grandkid)}
+ :metric-collection-ids #{(:id metric-child)}}
+ (select-keys (#'typed-schemas.api.scope/library-collections-scope
+ (#'typed-schemas.api.scope/query-library-collection-values
+ {:library-collections (format "%d, %d"
+ (:id data-child)
+ (:id metric-child))}))
+ [:collection-ids :data-collection-ids :metric-collection-ids]))))))
+
+(deftest library-collections-scope-accepts-representation-entity-ids-test
+ (mt/with-temp [:model/Collection root {:name "Library"
+ :type "library"
+ :location "/"}
+ :model/Collection data {:name "Data"
+ :type "library-data"
+ :location (collection/children-location root)}
+ :model/Collection website {:name "Website"
+ :type "library-data"
+ :entity_id "g-jLnamuHKdezZMthJ-z7"
+ :location (collection/children-location data)}
+ :model/Collection website-page {:name "Website Page"
+ :type "library-data"
+ :location (collection/children-location website)}]
+ (mt/with-test-user :crowberto
+ (is (= {:collection-ids #{(:id website) (:id website-page)}
+ :data-collection-ids #{(:id website) (:id website-page)}
+ :metric-collection-ids #{}}
+ (select-keys (#'typed-schemas.api.scope/library-collections-scope ["g-jLnamuHKdezZMthJ-z7"])
+ [:collection-ids :data-collection-ids :metric-collection-ids]))))))
+
+(deftest library-scope-includes-canonical-data-and-metrics-libraries-test
+ (with-redefs [typed-schemas.api.scope/library-data-entity-id "test-library-data"
+ typed-schemas.api.scope/library-metrics-entity-id "test-library-metrics"]
+ (mt/with-temp [:model/Collection root {:name "Library"
+ :type "library"
+ :location "/"}
+ :model/Collection data {:name "Data"
+ :type "library-data"
+ :entity_id "test-library-data"
+ :location (collection/children-location root)}
+ :model/Collection metrics {:name "Metrics"
+ :type "library-metrics"
+ :entity_id "test-library-metrics"
+ :location (collection/children-location root)}
+ :model/Collection data-child {:name "Boba Data"
+ :type "library-data"
+ :location (collection/children-location data)}
+ :model/Collection metric-child {:name "Boba Metrics"
+ :type "library-metrics"
+ :location (collection/children-location metrics)}]
+ (mt/with-test-user :crowberto
+ (is (= {:collection-ids #{(:id data) (:id data-child) (:id metrics) (:id metric-child)}
+ :data-collection-ids #{(:id data) (:id data-child)}
+ :metric-collection-ids #{(:id metrics) (:id metric-child)}}
+ (select-keys (#'typed-schemas.api.scope/library-scope
+ {:include-data-library "true"
+ :include-metric-library "true"})
+ [:collection-ids :data-collection-ids :metric-collection-ids])))))))
+
+(deftest ^:parallel query-collection-values-use-kebab-case-params-test
+ (is (= ["1" "2"]
+ (#'typed-schemas.api.scope/query-library-collection-values {:library-collections "1, 2"})))
+ (is (= ["3" "4"]
+ (#'typed-schemas.api.scope/query-question-collection-values {:question-collections "3, 4"})))
+ (is (true?
+ (#'typed-schemas.api.scope/query-include-models? {:include-models "true"})))
+ (is (nil?
+ (#'typed-schemas.api.scope/query-library-collection-values {:libraryCollections "1, 2"})))
+ (is (nil?
+ (#'typed-schemas.api.scope/query-question-collection-values {:questionCollections "3, 4"})))
+ (is (false?
+ (#'typed-schemas.api.scope/query-include-models? {:includeModels "true"}))))
+
+(deftest question-collection-scope-accepts-comma-separated-collection-ids-test
+ (mt/with-temp [:model/Collection parent {:name "Question Parent"
+ :location "/"}
+ :model/Collection child {:name "Question Child"
+ :location (collection/children-location parent)}]
+ (mt/with-test-user :crowberto
+ (is (= #{(:id parent) (:id child)}
+ (#'typed-schemas.api.scope/collection-scope
+ (#'typed-schemas.api.scope/query-question-collection-values
+ {:question-collections (str (:id parent))})))))))
+
+(deftest question-collection-scope-accepts-representation-entity-ids-test
+ (mt/with-temp [:model/Collection parent {:name "Question Parent"
+ :entity_id "question-entity-id-1"
+ :location "/"}
+ :model/Collection child {:name "Question Child"
+ :location (collection/children-location parent)}]
+ (mt/with-test-user :crowberto
+ (is (= #{(:id parent) (:id child)}
+ (#'typed-schemas.api.scope/collection-scope ["question-entity-id-1"]))))))
+
+(deftest question-collection-scope-rejects-missing-collection-ref-test
+ (mt/with-test-user :crowberto
+ (let [e (is (thrown? clojure.lang.ExceptionInfo
+ (#'typed-schemas.api.scope/collection-scope ["missing-entity-id-1"])))]
+ (is (= 404 (:status-code (ex-data e)))))))
diff --git a/test/metabase/typed_schemas/api_test.clj b/test/metabase/typed_schemas/api_test.clj
new file mode 100644
index 00000000000..54a7fb32c87
--- /dev/null
+++ b/test/metabase/typed_schemas/api_test.clj
@@ -0,0 +1,344 @@
+(ns metabase.typed-schemas.api-test
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.typed-schemas.api :as typed-schemas.api]
+ [metabase.typed-schemas.api.render :as typed-schemas.api.render]
+ [metabase.typed-schemas.api.schema.metric :as typed-schemas.api.schema.metric]
+ [metabase.typed-schemas.api.schema.model :as typed-schemas.api.schema.model]
+ [metabase.typed-schemas.api.schema.question :as typed-schemas.api.schema.question]
+ [metabase.typed-schemas.api.schema.table :as typed-schemas.api.schema.table]
+ [metabase.typed-schemas.api.scope :as typed-schemas.api.scope]))
+
+(use-fixtures :once (fixtures/initialize :db :web-server :test-users))
+
+(deftest typescript-endpoint-test
+ (let [response (mt/user-http-request-full-response :crowberto :get 200 "typed-schemas/v1/typescript")]
+ (is (= "text/typescript; charset=utf-8" (get-in response [:headers "Content-Type"])))
+ (is (str/starts-with? (:body response) "const questions = "))
+ (is (str/includes? (:body response) "\nconst schema = {"))
+ (is (str/includes? (:body response) "\n schemaVersion: 2"))
+ (is (str/includes? (:body response) "\n questions: questions"))
+ (is (str/includes? (:body response) "\n tables: tables"))
+ (is (str/includes? (:body response) "\n metrics: metrics"))
+ (is (str/ends-with? (:body response) "export default schema;\n"))
+ (is (not (str/includes? (:body response) "\"schemaVersion\"")))
+ (is (not (str/includes? (:body response) "operators: [ ]")))
+ (is (not (str/includes? (:body response) "parameters: [ ]")))
+ (is (not (str/includes? (:body response) "verified: false")))))
+
+(deftest query-params-are-coerced-at-endpoint-test
+ (with-redefs [typed-schemas.api/typed-schema identity
+ typed-schemas.api.render/render-typescript pr-str]
+ (let [response (-> (mt/user-http-request-full-response
+ :crowberto
+ :get
+ 200
+ "typed-schemas/v1/typescript?include-models=true&questions=false&library-collections=1,2")
+ :body
+ read-string)]
+ (is (true? (:include-models response)))
+ (is (false? (:questions response)))
+ (is (= "1,2" (:library-collections response))))))
+
+(deftest database-filter-test
+ (testing "a non-matching database name returns an empty semantic schema"
+ (let [response (mt/user-http-request-full-response
+ :crowberto
+ :get
+ 200
+ "typed-schemas/v1/typescript?database=__missing_database__")]
+ (is (str/includes? (:body response) "schemaVersion: 2"))
+ (is (str/includes? (:body response) "const questions = { }"))
+ (is (str/includes? (:body response) "const tables = { }"))
+ (is (str/includes? (:body response) "const metrics = { }"))))
+ (testing "questions=true returns only questions for a numeric database id"
+ (let [response (mt/user-http-request-full-response
+ :crowberto
+ :get
+ 200
+ (format "typed-schemas/v1/typescript?database=%s&questions=true" (mt/id)))]
+ (is (str/includes? (:body response) "schemaVersion: 2"))
+ (is (str/includes? (:body response) "const questions = {"))
+ (is (str/includes? (:body response) "const tables = { }"))
+ (is (str/includes? (:body response) "const metrics = { }")))))
+
+(deftest database-filter-scopes-models-test
+ (let [model-database-ids (atom [])]
+ (with-redefs [typed-schemas.api.scope/database-ids-for-value (constantly #{42})
+ typed-schemas.api.schema.model/model-schemas (fn [database-ids]
+ (swap! model-database-ids conj database-ids)
+ [])
+ typed-schemas.api.schema.question/question-schemas (fn
+ ([_database-ids] [])
+ ([_database-ids _collection-ids] []))
+ typed-schemas.api.schema.metric/metric-schemas (fn
+ ([_database-ids] [])
+ ([_database-ids _collection-ids] []))
+ typed-schemas.api.schema.table/select-tables (fn
+ ([_database-ids] [])
+ ([_database-ids _table-ids] []))
+ typed-schemas.api.schema.table/table-schemas (constantly [])]
+ (#'typed-schemas.api/typed-schema {:database "Boba"})
+ (#'typed-schemas.api/typed-schema {:database "Boba" :questions "true"})
+ (is (= [#{42} #{42}] @model-database-ids)))))
+
+(deftest library-and-database-are-mutually-exclusive-test
+ (mt/user-http-request-full-response
+ :crowberto
+ :get
+ 400
+ "typed-schemas/v1/typescript?library=1&database=1")
+ (mt/user-http-request-full-response
+ :crowberto
+ :get
+ 400
+ "typed-schemas/v1/typescript?library=1&questions=true")
+ (mt/user-http-request-full-response
+ :crowberto
+ :get
+ 400
+ "typed-schemas/v1/typescript?questions=true"))
+
+(deftest collection-query-params-are-mutually-exclusive-test
+ (mt/user-http-request-full-response
+ :crowberto
+ :get
+ 400
+ "typed-schemas/v1/typescript?library-collections=1,2&database=1")
+ (mt/user-http-request-full-response
+ :crowberto
+ :get
+ 400
+ "typed-schemas/v1/typescript?question-collections=1,2&questions=true")
+ (mt/user-http-request-full-response
+ :crowberto
+ :get
+ 400
+ "typed-schemas/v1/typescript?library=1&library-collections=2"))
+
+(deftest library-schema-includes-metric-mapped-tables-test
+ (let [selected-table-ids (atom nil)]
+ (with-redefs [typed-schemas.api.scope/library-collection-scope
+ (constantly {:metric-collection-ids #{20}
+ :data-collection-ids #{10}})
+ typed-schemas.api.schema.model/model-schemas
+ (fn
+ ([_database-ids]
+ (is false "library-only schemas should not load models"))
+ ([_database-ids _collection-ids]
+ (is false "library-only schemas should not load models")))
+ typed-schemas.api.schema.metric/metric-schemas
+ (fn [_database-ids collection-ids]
+ (is (= #{20} collection-ids))
+ [{:type "metric"
+ :key "revenue"
+ :id 1
+ :name "Revenue"
+ :columns [{:name "Revenue", :displayName "Revenue", :jsType "number"}]
+ :mappedTableIds [42]}])
+ typed-schemas.api.schema.table/select-library-tables
+ (constantly [{:id 10}])
+ typed-schemas.api.schema.table/select-tables
+ (fn [_database-ids table-ids]
+ (reset! selected-table-ids table-ids)
+ [{:id 10} {:id 42}])
+ typed-schemas.api.schema.table/table-schemas
+ (constantly [{:type "table", :key "publishedTable", :id 10}
+ {:type "table", :key "mappedTable", :id 42}])]
+ (let [schema (#'typed-schemas.api/typed-schema {:library "123"})]
+ (is (= #{10 42} @selected-table-ids))
+ (is (= {} (:questions schema)))
+ (is (= {} (:models schema)))
+ (is (= #{10 42} (->> (:tables schema) vals (map :id) set)))
+ (is (= #{1} (->> (:metrics schema) vals (map :id) set)))))))
+
+(deftest collections-schema-includes-selected-data-and-metric-collections-test
+ (let [selected-table-ids (atom nil)]
+ (with-redefs [typed-schemas.api.scope/library-collections-scope
+ (fn [collection-values]
+ (is (= ["10" "20"] collection-values))
+ {:metric-collection-ids #{20}
+ :data-collection-ids #{10}})
+ typed-schemas.api.schema.model/model-schemas
+ (fn
+ ([_database-ids]
+ (is false "library-only schemas should not load models"))
+ ([_database-ids _collection-ids]
+ (is false "library-only schemas should not load models")))
+ typed-schemas.api.schema.metric/metric-schemas
+ (fn [_database-ids collection-ids]
+ (is (= #{20} collection-ids))
+ [{:type "metric"
+ :key "revenue"
+ :id 1
+ :name "Revenue"
+ :columns [{:name "Revenue", :displayName "Revenue", :jsType "number"}]
+ :mappedTableIds [42]}])
+ typed-schemas.api.schema.table/select-library-tables
+ (fn [library-scope]
+ (is (= #{10} (:data-collection-ids library-scope)))
+ [{:id 10}])
+ typed-schemas.api.schema.table/select-tables
+ (fn [_database-ids table-ids]
+ (reset! selected-table-ids table-ids)
+ [{:id 10} {:id 42}])
+ typed-schemas.api.schema.table/table-schemas
+ (constantly [{:type "table", :key "publishedTable", :id 10}
+ {:type "table", :key "mappedTable", :id 42}])]
+ (let [schema (#'typed-schemas.api/typed-schema {:library-collections "10, 20"})]
+ (is (= #{10 42} @selected-table-ids))
+ (is (= {} (:questions schema)))
+ (is (= {} (:models schema)))
+ (is (= #{10 42} (->> (:tables schema) vals (map :id) set)))
+ (is (= #{1} (->> (:metrics schema) vals (map :id) set)))))))
+
+(deftest include-models-schema-includes-actionable-models-test
+ (with-redefs [typed-schemas.api.schema.model/model-schemas
+ (fn [database-ids]
+ (is (nil? database-ids))
+ [{:key "actionableModel"
+ :actions {"create" {:kind "action", :key "create", :id 1}}}])
+ typed-schemas.api.schema.question/question-schemas
+ (fn
+ ([_database-ids]
+ (is false "include-models-only schemas should not load questions"))
+ ([_database-ids _collection-ids]
+ (is false "include-models-only schemas should not load questions")))
+ typed-schemas.api.schema.metric/metric-schemas
+ (fn
+ ([_database-ids]
+ (is false "include-models-only schemas should not load metrics"))
+ ([_database-ids _collection-ids]
+ (is false "include-models-only schemas should not load metrics")))
+ typed-schemas.api.schema.table/select-tables
+ (fn
+ ([_database-ids]
+ (is false "include-models-only schemas should not load tables"))
+ ([_database-ids _table-ids]
+ (is false "include-models-only schemas should not load tables")))]
+ (let [schema (#'typed-schemas.api/typed-schema {:include-models "true"})]
+ (is (= {} (:questions schema)))
+ (is (= {"actionableModel" {:actions {"create" {:kind "action", :key "create", :id 1}}}}
+ (:models schema)))
+ (is (= {} (:tables schema)))
+ (is (= {} (:metrics schema))))))
+
+(deftest include-models-with-database-scopes-models-test
+ (let [model-database-ids (atom [])]
+ (with-redefs [typed-schemas.api.scope/database-ids-for-value (constantly #{42})
+ typed-schemas.api.schema.model/model-schemas (fn [database-ids]
+ (swap! model-database-ids conj database-ids)
+ [{:key "databaseModel"
+ :actions {"create" {:kind "action", :key "create", :id 1}}}])
+ typed-schemas.api.schema.question/question-schemas (fn
+ ([_database-ids] [])
+ ([_database-ids _collection-ids] []))
+ typed-schemas.api.schema.metric/metric-schemas (fn
+ ([_database-ids] [])
+ ([_database-ids _collection-ids] []))
+ typed-schemas.api.schema.table/select-tables (fn
+ ([_database-ids] [])
+ ([_database-ids _table-ids] []))
+ typed-schemas.api.schema.table/table-schemas (constantly [])]
+ (let [schema (#'typed-schemas.api/typed-schema {:database "Boba" :include-models "true"})]
+ (is (= [#{42}] @model-database-ids))
+ (is (= {"databaseModel" {:actions {"create" {:kind "action", :key "create", :id 1}}}}
+ (:models schema)))))))
+
+(deftest question-collections-schema-includes-selected-question-collections-test
+ (with-redefs [typed-schemas.api.scope/collection-scope
+ (fn [collection-values]
+ (is (= ["30" "40"] collection-values))
+ #{30 40})
+ typed-schemas.api.schema.question/question-schemas
+ (fn [database-ids collection-ids]
+ (is (nil? database-ids))
+ (is (= #{30 40} collection-ids))
+ [{:type "card", :key "ordersByMonth", :id 1}])
+ typed-schemas.api.schema.model/model-schemas
+ (fn
+ ([_database-ids]
+ (is false "question collection schemas should not load models"))
+ ([_database-ids _collection-ids]
+ (is false "question collection schemas should not load models")))]
+ (let [schema (#'typed-schemas.api/typed-schema {:question-collections "30, 40"})]
+ (is (= #{1} (->> (:questions schema) vals (map :id) set)))
+ (is (= {} (:models schema)))
+ (is (= {} (:tables schema)))
+ (is (= {} (:metrics schema))))))
+
+(deftest library-and-question-collections-can-be-combined-test
+ (with-redefs [typed-schemas.api.scope/library-collections-scope
+ (fn [collection-values]
+ (is (= ["10"] collection-values))
+ {:metric-collection-ids #{10}
+ :data-collection-ids #{10}})
+ typed-schemas.api.scope/collection-scope
+ (fn [collection-values]
+ (is (= ["30"] collection-values))
+ #{30})
+ typed-schemas.api.schema.question/question-schemas
+ (fn [database-ids collection-ids]
+ (is (nil? database-ids))
+ (is (= #{30} collection-ids))
+ [{:type "card", :key "ordersByMonth", :id 1}])
+ typed-schemas.api.schema.model/model-schemas
+ (fn
+ ([_database-ids]
+ (is false "question collection schemas should not load models"))
+ ([_database-ids _collection-ids]
+ (is false "question collection schemas should not load models")))
+ typed-schemas.api.schema.metric/metric-schemas
+ (constantly [{:type "metric", :key "revenue", :id 2}])
+ typed-schemas.api.schema.table/select-library-tables
+ (constantly [{:id 3}])
+ typed-schemas.api.schema.table/select-tables
+ (constantly [{:id 3}])
+ typed-schemas.api.schema.table/table-schemas
+ (constantly [{:type "table", :key "orders", :id 3}])]
+ (let [schema (#'typed-schemas.api/typed-schema {:library-collections "10"
+ :question-collections "30"})]
+ (is (= #{1} (->> (:questions schema) vals (map :id) set)))
+ (is (= {} (:models schema)))
+ (is (= #{3} (->> (:tables schema) vals (map :id) set)))
+ (is (= #{2} (->> (:metrics schema) vals (map :id) set))))))
+
+(deftest library-and-question-collections-can-be-combined-with-include-models-test
+ (with-redefs [typed-schemas.api.scope/library-collections-scope
+ (fn [collection-values]
+ (is (= ["10"] collection-values))
+ {:metric-collection-ids #{10}
+ :data-collection-ids #{10}})
+ typed-schemas.api.scope/collection-scope
+ (fn [collection-values]
+ (is (= ["30"] collection-values))
+ #{30})
+ typed-schemas.api.schema.question/question-schemas
+ (fn [database-ids collection-ids]
+ (is (nil? database-ids))
+ (is (= #{30} collection-ids))
+ [{:type "card", :key "ordersByMonth", :id 1}])
+ typed-schemas.api.schema.model/model-schemas
+ (fn [database-ids]
+ (is (nil? database-ids))
+ [{:key "selectedQuestionCollectionModel"
+ :actions {"create" {:kind "action", :key "create", :id 1}}}])
+ typed-schemas.api.schema.metric/metric-schemas
+ (constantly [{:type "metric", :key "revenue", :id 2}])
+ typed-schemas.api.schema.table/select-library-tables
+ (constantly [{:id 3}])
+ typed-schemas.api.schema.table/select-tables
+ (constantly [{:id 3}])
+ typed-schemas.api.schema.table/table-schemas
+ (constantly [{:type "table", :key "orders", :id 3}])]
+ (let [schema (#'typed-schemas.api/typed-schema {:library-collections "10"
+ :question-collections "30"
+ :include-models "true"})]
+ (is (= #{1} (->> (:questions schema) vals (map :id) set)))
+ (is (= {"selectedQuestionCollectionModel" {:actions {"create" {:kind "action", :key "create", :id 1}}}}
+ (:models schema)))
+ (is (= #{3} (->> (:tables schema) vals (map :id) set)))
+ (is (= #{2} (->> (:metrics schema) vals (map :id) set))))))
diff --git a/tsconfig.json b/tsconfig.json
index 8dab10165f3..e0256df710e 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -17,9 +17,25 @@
"zrender/lib/core/types": ["./node_modules/zrender/lib/core/types"],
"sdk-ee-plugins": ["./frontend/src/metabase/plugins/noop"],
"sdk-specific-imports": ["./frontend/src/metabase/utils/noop"],
- "sdk-iframe-embedding-ee-plugins": ["./frontend/src/metabase/plugins/noop"],
- "sdk-iframe-embedding-script-ee-plugins": ["./frontend/src/metabase/plugins/noop"],
- "custom-viz": ["./enterprise/frontend/src/custom-viz/src/index.ts"]
+ "sdk-iframe-embedding-ee-plugins": [
+ "./frontend/src/metabase/plugins/noop"
+ ],
+ "sdk-iframe-embedding-script-ee-plugins": [
+ "./frontend/src/metabase/plugins/noop"
+ ],
+ "custom-viz": ["./enterprise/frontend/src/custom-viz/src/index.ts"],
+ "@metabase/embedding-sdk-react": [
+ "./enterprise/frontend/src/embedding-sdk-package/index.ts"
+ ],
+ "@metabase/embedding-sdk-react/data-app": [
+ "./enterprise/frontend/src/embedding-sdk-package/data-app.ts"
+ ],
+ "@metabase/embedding-sdk-react/data-app-dev": [
+ "./enterprise/frontend/src/embedding-sdk-package/data-app-dev.ts"
+ ],
+ "@metabase/embedding-sdk-react/data-app-dev/config": [
+ "./enterprise/frontend/src/embedding-sdk-package/data-app-dev.config.ts"
+ ]
},
"plugins": [
{
diff --git a/tsconfig.sdk.json b/tsconfig.sdk.json
index ed3e19b8e5a..e191e81b16c 100644
--- a/tsconfig.sdk.json
+++ b/tsconfig.sdk.json
@@ -26,6 +26,8 @@
],
"exclude": [
"node_modules",
+ "enterprise/frontend/src/embedding-sdk-package/data-app-dev-entry.tsx",
+ "enterprise/frontend/src/embedding-sdk-package/data-app-dev/vite-env.d.ts",
"**/*.spec.*",
"**/mocks/*",
"**/tests/*",