Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

feat(cli): build admin dashboard extensions and let a package ship its own entry (#1424)

Viktor Holik1e105aa1b209
diff --git a/packages/cli/src/commands/dashboard-build.ts b/packages/cli/src/commands/dashboard-build.ts
new file mode 100644
index 000000000..fb86c27ae
--- /dev/null
+++ b/packages/cli/src/commands/dashboard-build.ts
@@ -0,0 +1,55 @@
+import path from "path";
+import { handleError } from "@/src/utils/handle-error";
+import {
+ buildDashboardExtensions,
+ type DashboardApp,
+} from "@/src/utils/build-dashboard-extensions";
+import { logger } from "@/src/utils/logger";
+import { spinner } from "@/src/utils/spinner";
+import { Command } from "commander";
+
+const APPS: DashboardApp[] = ["admin", "vendor"];
+
+export const dashboardBuild = new Command()
+ .name("dashboard:build")
+ .description(
+ "build a dashboard extensions entry (routes, widgets, custom fields, i18n) from a source directory"
+ )
+ .option(
+ "-c, --cwd <cwd>",
+ "the working directory. defaults to the current directory.",
+ process.cwd()
+ )
+ .option("-a, --app <app>", "which panel the entry targets (admin|vendor)", "admin")
+ .option("-s, --src <src>", "source directory to crawl", "src")
+ .option("-o, --out <out>", "output file", "dist/admin-extensions.mjs")
+ .option("-w, --watch", "rebuild on change", false)
+ .action(async (opts) => {
+ try {
+ const cwd = path.resolve(opts.cwd);
+
+ if (!APPS.includes(opts.app)) {
+ logger.error(`--app must be one of: ${APPS.join(", ")}`);
+ process.exit(1);
+ }
+
+ const buildSpinner = spinner(`Building ${opts.app} extensions...`);
+
+ const ok = await buildDashboardExtensions({
+ root: cwd,
+ srcDir: opts.src,
+ outFile: opts.out,
+ watch: opts.watch,
+ });
+
+ if (ok) {
+ buildSpinner.succeed(`Built ${opts.app} extensions.`);
+ } else {
+ buildSpinner.fail(`Failed to build ${opts.app} extensions.`);
+ process.exit(1);
+ }
+ } catch (error) {
+ logger.break();
+ handleError(error);
+ }
+ });
diff --git a/packages/cli/src/commands/plugin-build.ts b/packages/cli/src/commands/plugin-build.ts
index cfc6d6488..f4f66b90b 100644
--- a/packages/cli/src/commands/plugin-build.ts
+++ b/packages/cli/src/commands/plugin-build.ts
@@ -1,6 +1,6 @@
import path from "path";
import { handleError } from "@/src/utils/handle-error";
-import { buildVendorExtensions } from "@/src/utils/build-vendor-extensions";
+import { buildDashboardExtensions } from "@/src/utils/build-dashboard-extensions";
import { logger } from "@/src/utils/logger";
import { spinner } from "@/src/utils/spinner";
import { Command } from "commander";
@@ -35,7 +35,13 @@ export const pluginBuild = new Command()
const responses = await Promise.all([
compiler.buildPluginBackend(tsConfig),
compiler.buildPluginAdminExtensions(bundler),
- buildVendorExtensions({ root: cwd, outDir: pluginsDistFolder }),
+ ...(["admin", "vendor"] as const).map((app) =>
+ buildDashboardExtensions({
+ root: cwd,
+ srcDir: `src/${app}`,
+ outFile: path.join(pluginsDistFolder, "src", app, "index.mjs"),
+ })
+ ),
]);
if (responses.every((response) => response === true)) {
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 08f06683e..2345e1ce0 100755
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -12,6 +12,7 @@ import { search } from "./commands/search";
import { telemetry } from "./commands/telemetry";
import { view } from "./commands/view";
import { pluginBuild } from "./commands/plugin-build";
+import { dashboardBuild } from "./commands/dashboard-build";
process.on("SIGINT", () => process.exit(0));
process.on("SIGTERM", () => process.exit(0));
@@ -37,7 +38,8 @@ async function main() {
.addCommand(search)
.addCommand(telemetry)
.addCommand(view)
- .addCommand(pluginBuild);
+ .addCommand(pluginBuild)
+ .addCommand(dashboardBuild);
program.parse();
}
diff --git a/packages/cli/src/utils/build-dashboard-extensions.ts b/packages/cli/src/utils/build-dashboard-extensions.ts
new file mode 100644
index 000000000..5fda6f1ae
--- /dev/null
+++ b/packages/cli/src/utils/build-dashboard-extensions.ts
@@ -0,0 +1,174 @@
+import { readFileSync } from "fs";
+import { builtinModules } from "node:module";
+import { rm, writeFile } from "node:fs/promises";
+import path from "path";
+import fs from "fs";
+import { generatePluginEntryModule } from "@mercurjs/dashboard-sdk/vite";
+
+const VALID_FILE_EXTENSIONS = [".tsx", ".ts", ".jsx", ".js"];
+
+export type DashboardApp = "admin" | "vendor";
+
+export interface BuildDashboardExtensionsOptions {
+ /** Package root — its `package.json` seeds the external list. */
+ root: string;
+ /** Directory holding `routes/`, `widgets/`, `custom-fields/`, `i18n/`. */
+ srcDir: string;
+ /** Where to write the bundled ESM entry. */
+ outFile: string;
+ /** Extra bare specifiers to keep external (e.g. host-provided peers). */
+ extraExternal?: string[];
+ watch?: boolean;
+}
+
+/**
+ * An authored `index.*` in `srcDir` replaces the crawled entry, so a package can
+ * hand-write what it contributes — including re-exporting an entry another
+ * package already built — instead of having it derived from its folder tree.
+ */
+function findAuthoredEntry(srcDir: string): string | null {
+ for (const ext of VALID_FILE_EXTENSIONS) {
+ const candidate = path.join(srcDir, `index${ext}`);
+ if (fs.existsSync(candidate)) return candidate;
+ }
+ return null;
+}
+
+function readExternalNames(root: string, extra: string[]): Set<string> {
+ let pkg: Record<string, Record<string, string> | undefined> = {};
+ try {
+ pkg = JSON.parse(readFileSync(path.resolve(root, "package.json"), "utf-8"));
+ } catch {
+ // A package.json is not required — the defaults below still apply.
+ }
+
+ return new Set([
+ ...Object.keys(pkg.dependencies || {}),
+ ...Object.keys(pkg.peerDependencies || {}),
+ ...Object.keys(pkg.devDependencies || {}),
+ "react",
+ "react/jsx-runtime",
+ "react-dom",
+ "react-router-dom",
+ "react-i18next",
+ "i18next",
+ "@medusajs/js-sdk",
+ "@medusajs/admin-sdk",
+ "@medusajs/ui",
+ "@medusajs/icons",
+ "@mercurjs/client",
+ "@mercurjs/dashboard-shared",
+ "@tanstack/react-query",
+ ...extra,
+ ]);
+}
+
+/**
+ * Bundle a dashboard surface (`src/admin` or `src/vendor`) into the single ESM
+ * entry the Vite plugin loads. Works for a Medusa plugin and for a standalone
+ * package that ships its own prebuilt entry.
+ *
+ * Returns `true` when there is nothing to build, so callers can run it
+ * unconditionally for both surfaces.
+ */
+export async function buildDashboardExtensions(
+ options: BuildDashboardExtensionsOptions
+): Promise<boolean> {
+ const srcDir = path.resolve(options.root, options.srcDir);
+
+ if (!fs.existsSync(srcDir)) {
+ return true;
+ }
+
+ const vite = await import("vite");
+ const react = (await import("@vitejs/plugin-react")).default;
+
+ const external = readExternalNames(options.root, options.extraExternal ?? []);
+
+ const outFile = path.resolve(options.root, options.outFile);
+ const outDir = path.dirname(outFile);
+ const fileName = path.basename(outFile, path.extname(outFile));
+
+ const authoredEntry = findAuthoredEntry(srcDir);
+ const generatedEntry = path.join(srcDir, "__dashboard-extensions__.js");
+ const entryFile = authoredEntry ?? generatedEntry;
+
+ try {
+ if (!authoredEntry) {
+ await writeFile(
+ generatedEntry,
+ generatePluginEntryModule(srcDir),
+ "utf-8"
+ );
+ }
+
+ const originalNodeEnv = process.env.NODE_ENV;
+ process.env.NODE_ENV = "production";
+
+ await vite.build({
+ build: {
+ lib: {
+ entry: entryFile,
+ formats: ["es", "cjs"],
+ fileName,
+ },
+ emptyOutDir: false,
+ minify: false,
+ outDir,
+ watch: options.watch ? {} : undefined,
+ rollupOptions: {
+ external: (id, importer) => {
+ const idParts = id.split("/");
+ const name = idParts[0]?.startsWith("@")
+ ? `${idParts[0]}/${idParts[1]}`
+ : idParts[0];
+
+ const builtinModulesWithNodePrefix = [
+ ...builtinModules,
+ ...builtinModules.map((modName) => `node:${modName}`),
+ ];
+
+ if (!importer) {
+ return Boolean(
+ (name && external.has(name)) ||
+ (name && builtinModulesWithNodePrefix.includes(name))
+ );
+ }
+
+ return Boolean(name && external.has(name));
+ },
+ output: {
+ preserveModules: false,
+ chunkFileNames: () => `_chunks/[name]-[hash]`,
+ },
+ },
+ },
+ plugins: [react()],
+ logLevel: "silent",
+ clearScreen: false,
+ });
+
+ process.env.NODE_ENV = originalNodeEnv;
+
+ // The Vite plugin resolves this entry as ESM by extension, so `.es.js` has
+ // to become `.mjs` regardless of what the caller named the output.
+ const esFile = path.join(outDir, `${fileName}.es.js`);
+ const mjsFile = path.join(outDir, `${fileName}.mjs`);
+ if (fs.existsSync(esFile)) {
+ fs.renameSync(esFile, mjsFile);
+ }
+
+ return true;
+ } catch (error) {
+ console.error(error);
+ return false;
+ } finally {
+ if (!authoredEntry) {
+ try {
+ await rm(generatedEntry, { force: true });
+ } catch {
+ // ignore
+ }
+ }
+ }
+}
diff --git a/packages/cli/src/utils/build-vendor-extensions.ts b/packages/cli/src/utils/build-vendor-extensions.ts
deleted file mode 100644
index d91b69af9..000000000
--- a/packages/cli/src/utils/build-vendor-extensions.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { readFileSync } from "fs";
-import { builtinModules } from "node:module";
-import { rm, writeFile } from "node:fs/promises";
-import path from "path";
-import fs from "fs";
-import { generatePluginEntryModule } from "@mercurjs/dashboard-sdk/vite";
-
-interface BuildVendorExtensionsOptions {
- root: string;
- outDir: string;
-}
-
-export async function buildVendorExtensions(
- options: BuildVendorExtensionsOptions
-): Promise<boolean> {
- const vendorDir = path.resolve(options.root, "src/vendor");
-
- if (!fs.existsSync(vendorDir)) {
- return true;
- }
-
- const vite = await import("vite");
- const react = (await import("@vitejs/plugin-react")).default;
-
- const pkg = JSON.parse(
- readFileSync(path.resolve(options.root, "package.json"), "utf-8")
- );
- const external = new Set([
- ...Object.keys(pkg.dependencies || {}),
- ...Object.keys(pkg.peerDependencies || {}),
- ...Object.keys(pkg.devDependencies || {}),
- "react",
- "react/jsx-runtime",
- "react-router-dom",
- "react-i18next",
- "@medusajs/js-sdk",
- "@medusajs/admin-sdk",
- "@mercurjs/client",
- "@tanstack/react-query",
- ]);
-
- const outDir = path.resolve(options.outDir, "src/vendor");
- const entryFile = path.resolve(
- options.root,
- "src/vendor/__vendor-extensions__.js"
- );
-
- try {
- const entryCode = generatePluginEntryModule(vendorDir);
- await writeFile(entryFile, entryCode, "utf-8");
-
- const originalNodeEnv = process.env.NODE_ENV;
- process.env.NODE_ENV = "production";
-
- await vite.build({
- build: {
- lib: {
- entry: entryFile,
- formats: ["es", "cjs"],
- fileName: "index",
- },
- emptyOutDir: false,
- minify: false,
- outDir,
- rollupOptions: {
- external: (id, importer) => {
- const idParts = id.split("/");
- const name = idParts[0]?.startsWith("@")
- ? `${idParts[0]}/${idParts[1]}`
- : idParts[0];
-
- const builtinModulesWithNodePrefix = [
- ...builtinModules,
- ...builtinModules.map((modName) => `node:${modName}`),
- ];
-
- if (!importer) {
- return Boolean(
- (name && external.has(name)) ||
- (name && builtinModulesWithNodePrefix.includes(name))
- );
- }
-
- return Boolean(name && external.has(name));
- },
- output: {
- preserveModules: false,
- interop: "auto",
- chunkFileNames: () => `_chunks/[name]-[hash]`,
- },
- },
- },
- plugins: [react()],
- logLevel: "silent",
- clearScreen: false,
- });
-
- process.env.NODE_ENV = originalNodeEnv;
-
- // Rename index.es.js to index.mjs for ESM consumption
- const esFile = path.join(outDir, "index.es.js");
- const mjsFile = path.join(outDir, "index.mjs");
- if (fs.existsSync(esFile)) {
- fs.renameSync(esFile, mjsFile);
- }
-
- return true;
- } catch (error) {
- console.error(error);
- return false;
- } finally {
- try {
- await rm(entryFile, { force: true });
- } catch {
- // ignore
- }
- }
-}