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.

fix(dashboard-sdk): emit only the layer keys each virtual module reads (#1744)

Viktor Holik98524215a46d
diff --git a/packages/dashboard-sdk/src/__tests__/i18n.spec.ts b/packages/dashboard-sdk/src/__tests__/i18n.spec.ts
index 4a882c2bc..61111ac8c 100644
--- a/packages/dashboard-sdk/src/__tests__/i18n.spec.ts
+++ b/packages/dashboard-sdk/src/__tests__/i18n.spec.ts
@@ -16,14 +16,22 @@ const makeDir = () => {
const setup = async ({
app,
plugins = [],
+ routes = {},
}: {
app?: Record<string, unknown>
plugins?: Record<string, unknown>[]
+ routes?: Record<string, string>
}) => {
const root = makeDir()
const srcDir = path.join(root, "src")
fs.mkdirSync(srcDir)
+ for (const [file, source] of Object.entries(routes)) {
+ const target = path.join(srcDir, "routes", file)
+ fs.mkdirSync(path.dirname(target), { recursive: true })
+ fs.writeFileSync(target, source)
+ }
+
if (app) {
fs.mkdirSync(path.join(srcDir, "i18n"))
fs.writeFileSync(
@@ -42,7 +50,7 @@ const setup = async ({
const out = path.join(root, "virtual-i18n.ts")
fs.writeFileSync(out, code)
- return (await import(out)).default
+ return { code, resources: (await import(out)).default }
}
afterEach(() => {
@@ -53,21 +61,21 @@ afterEach(() => {
describe("generateI18n", () => {
test("no app file and no plugins yields empty resources", async () => {
- expect(await setup({})).toEqual({})
+ expect((await setup({})).resources).toEqual({})
})
test("app file only is returned verbatim", async () => {
const app = { en: { translation: { a: "1" } } }
- expect(await setup({ app })).toEqual(app)
+ expect((await setup({ app })).resources).toEqual(app)
})
test("plugin resources are included", async () => {
const plugin = { en: { translation: { a: 1 } } }
- expect(await setup({ plugins: [plugin] })).toEqual(plugin)
+ expect((await setup({ plugins: [plugin] })).resources).toEqual(plugin)
})
test("plugin and app deep-merge, app wins on conflicts", async () => {
- const result = await setup({
+ const { resources: result } = await setup({
plugins: [{ en: { translation: { x: { a: 1, c: "plugin" } } } }],
app: { en: { translation: { x: { b: 2, c: "app" } } } },
})
@@ -75,7 +83,7 @@ describe("generateI18n", () => {
})
test("languages from plugin and app are both kept", async () => {
- const result = await setup({
+ const { resources: result } = await setup({
plugins: [{ pl: { translation: { a: "pl" } } }],
app: { en: { translation: { a: "en" } } },
})
@@ -86,9 +94,21 @@ describe("generateI18n", () => {
})
test("later plugins win over earlier ones", async () => {
- const result = await setup({
+ const { resources: result } = await setup({
plugins: [{ en: { translation: { a: 1 } } }, { en: { translation: { a: 2 } } }],
})
expect(result).toEqual({ en: { translation: { a: 2 } } })
})
+
+ test("route files are not imported", async () => {
+ const app = { en: { translation: { a: "1" } } }
+ const { code, resources } = await setup({
+ app,
+ routes: {
+ "products/create/page.tsx": `throw new Error("route evaluated")\nexport default () => null`,
+ },
+ })
+ expect(code).not.toContain("/routes/")
+ expect(resources).toEqual(app)
+ })
})
diff --git a/packages/dashboard-sdk/src/custom-fields.ts b/packages/dashboard-sdk/src/custom-fields.ts
index 0cf3fd519..bc78fe335 100644
--- a/packages/dashboard-sdk/src/custom-fields.ts
+++ b/packages/dashboard-sdk/src/custom-fields.ts
@@ -8,7 +8,7 @@ import type { BuiltMercurConfig } from "./types"
* `ExtensionRegistry` keys them so a later config replaces an earlier one.
*/
export function generateCustomFields(config: BuiltMercurConfig): string {
- const { header, names } = emitLayers(config)
+ const { header, names } = emitLayers(config, ["customFieldsModule"])
return `${header}
diff --git a/packages/dashboard-sdk/src/i18n.ts b/packages/dashboard-sdk/src/i18n.ts
index 5b6cc02bf..ea60891de 100644
--- a/packages/dashboard-sdk/src/i18n.ts
+++ b/packages/dashboard-sdk/src/i18n.ts
@@ -3,7 +3,7 @@ import type { BuiltMercurConfig } from "./types"
/** Deep-merged in layer order, so a later layer overrides a plugin's copy. */
export function generateI18n(config: BuiltMercurConfig): string {
- const { header, names } = emitLayers(config)
+ const { header, names } = emitLayers(config, ["i18nModule"])
// deepMerge is inlined because the virtual module has no runtime dependency on @mercurjs/admin.
return `${header}
diff --git a/packages/dashboard-sdk/src/layers.ts b/packages/dashboard-sdk/src/layers.ts
index 4b7a49ab3..50c596c7b 100644
--- a/packages/dashboard-sdk/src/layers.ts
+++ b/packages/dashboard-sdk/src/layers.ts
@@ -34,6 +34,19 @@ function findFile(dir: string, stem: string): string | null {
return null
}
+export const LAYER_KEYS = [
+ "routeModule",
+ "menuItemModule",
+ "widgetModule",
+ "customFieldsModule",
+ "layoutModule",
+ "i18nModule",
+ "navigationModule",
+ "preferenceModule",
+] as const
+
+export type LayerKey = (typeof LAYER_KEYS)[number]
+
export type CollectedLayer = {
imports: string[]
/** Declares `const <name> = { routeModule, menuItemModule, ... }`. */
@@ -47,87 +60,99 @@ export type CollectedLayer = {
* so every layer merges the same way. Identifiers carry the layer index so
* several crawled layers can share one module.
*/
-export function collectLayer(srcDir: string, layer: number, startIndex = 0): CollectedLayer {
+export function collectLayer(
+ srcDir: string,
+ layer: number,
+ startIndex = 0,
+ keys: readonly LayerKey[] = LAYER_KEYS
+): CollectedLayer {
const name = `__layer${layer}`
const routesDir = path.join(srcDir, "routes")
+ const wants = (key: LayerKey) => keys.includes(key)
let index = startIndex
- const routeResults: NonNullable<ReturnType<typeof parseFile>>[] = []
- const menuItemResults: NonNullable<ReturnType<typeof parseMenuItemFile>>[] = []
+ const imports: string[] = []
+ const fields: string[] = []
+
+ if (wants("routeModule") || wants("menuItemModule")) {
+ const routeResults: NonNullable<ReturnType<typeof parseFile>>[] = []
+ const menuItemResults: NonNullable<ReturnType<typeof parseMenuItemFile>>[] = []
+
+ for (const file of crawlRoutes(routesDir)) {
+ if (wants("routeModule")) {
+ const route = parseFile(file, routesDir, index)
+ if (route) routeResults.push(route)
+ }
+
+ if (wants("menuItemModule")) {
+ const menuItem = parseMenuItemFile(file, routesDir, index)
+ if (menuItem) menuItemResults.push(menuItem)
+ }
+
+ index++
+ }
- for (const file of crawlRoutes(routesDir)) {
- const route = parseFile(file, routesDir, index)
- if (route) routeResults.push(route)
+ if (wants("routeModule")) {
+ const routeTree = buildRouteTree(routeResults)
+ imports.push(...routeTree.flatMap((r) => r.imports))
+ fields.push(`routeModule: { routes: [
+${routeTree.map((r) => formatRoute(r.route)).join(",\n")}
+ ] }`)
+ }
- const menuItem = parseMenuItemFile(file, routesDir, index)
- if (menuItem) menuItemResults.push(menuItem)
+ if (wants("menuItemModule")) {
+ imports.push(...menuItemResults.map((r) => r.import))
+ fields.push(`menuItemModule: { menuItems: [
+${menuItemResults.map((r) => formatMenuItem(r.menuItem)).join(",\n")}
+ ] }`)
+ }
+ }
- index++
+ if (wants("widgetModule")) {
+ const widgets = collectWidgets(srcDir, index)
+ index += widgets.entries.length
+ imports.push(...widgets.imports)
+ fields.push(`widgetModule: { widgets: [
+${widgets.entries.join(",\n")}
+ ] }`)
}
- const routeTree = buildRouteTree(routeResults)
- const routeImports = routeTree.flatMap((r) => r.imports)
- const routes = routeTree.map((r) => formatRoute(r.route))
-
- const menuItemImports = menuItemResults.map((r) => r.import)
- const menuItems = menuItemResults.map((r) => formatMenuItem(r.menuItem))
-
- const widgets = collectWidgets(srcDir, index)
- index += widgets.entries.length
-
- const cfFiles = crawlModuleFiles(path.join(srcDir, "custom-fields"))
- const cfImports = cfFiles.map(
- (file, i) => `import __cf${layer}_${i} from "${normalizePath(file)}"`
- )
- const cfRefs = cfFiles.map((_, i) => ` __cf${layer}_${i}`)
-
- const layoutFiles = crawlModuleFiles(path.join(srcDir, "layouts"))
- const layoutImports = layoutFiles.map(
- (file, i) => `import __layout${layer}_${i} from "${normalizePath(file)}"`
- )
- const layoutRefs = layoutFiles.map((_, i) => ` __layout${layer}_${i}`)
-
- const i18nFile = findFile(path.join(srcDir, "i18n"), "index")
- const i18nName = `__i18n${layer}`
- const navigationFile = findFile(srcDir, NAVIGATION_FILE)
- const navigationName = `__navigation${layer}`
- const preferencesFile = findFile(srcDir, LAYOUT_PREFERENCES_FILE)
- const preferencesName = `__preferences${layer}`
-
- const imports = [
- ...routeImports,
- ...menuItemImports,
- ...widgets.imports,
- ...cfImports,
- ...layoutImports,
- ...(i18nFile ? [`import ${i18nName} from "${normalizePath(i18nFile)}"`] : []),
- ...(navigationFile
- ? [`import ${navigationName} from "${normalizePath(navigationFile)}"`]
- : []),
- ...(preferencesFile
- ? [`import ${preferencesName} from "${normalizePath(preferencesFile)}"`]
- : []),
+ if (wants("customFieldsModule")) {
+ const cfFiles = crawlModuleFiles(path.join(srcDir, "custom-fields"))
+ imports.push(
+ ...cfFiles.map((file, i) => `import __cf${layer}_${i} from "${normalizePath(file)}"`)
+ )
+ fields.push(`customFieldsModule: { configs: [
+${cfFiles.map((_, i) => ` __cf${layer}_${i}`).join(",\n")}
+ ] }`)
+ }
+
+ if (wants("layoutModule")) {
+ const layoutFiles = crawlModuleFiles(path.join(srcDir, "layouts"))
+ imports.push(
+ ...layoutFiles.map(
+ (file, i) => `import __layout${layer}_${i} from "${normalizePath(file)}"`
+ )
+ )
+ fields.push(`layoutModule: { layouts: [
+${layoutFiles.map((_, i) => ` __layout${layer}_${i}`).join(",\n")}
+ ] }`)
+ }
+
+ const singleFiles: [LayerKey, string | null, string][] = [
+ ["i18nModule", findFile(path.join(srcDir, "i18n"), "index"), `__i18n${layer}`],
+ ["navigationModule", findFile(srcDir, NAVIGATION_FILE), `__navigation${layer}`],
+ ["preferenceModule", findFile(srcDir, LAYOUT_PREFERENCES_FILE), `__preferences${layer}`],
]
+ for (const [key, file, ident] of singleFiles) {
+ if (!wants(key)) continue
+ if (file) imports.push(`import ${ident} from "${normalizePath(file)}"`)
+ fields.push(`${key}: ${file ? ident : "{}"}`)
+ }
+
const declaration = `const ${name} = {
- routeModule: { routes: [
-${routes.join(",\n")}
- ] },
- menuItemModule: { menuItems: [
-${menuItems.join(",\n")}
- ] },
- widgetModule: { widgets: [
-${widgets.entries.join(",\n")}
- ] },
- customFieldsModule: { configs: [
-${cfRefs.join(",\n")}
- ] },
- layoutModule: { layouts: [
-${layoutRefs.join(",\n")}
- ] },
- i18nModule: ${i18nFile ? i18nName : "{}"},
- navigationModule: ${navigationFile ? navigationName : "{}"},
- preferenceModule: ${preferencesFile ? preferencesName : "{}"},
+${fields.map((field) => ` ${field},`).join("\n")}
}`
return { imports, declaration, name, nextIndex: index }
@@ -140,7 +165,15 @@ export type EmittedLayers = {
names: string[]
}
-export function emitLayers(config: Pick<BuiltMercurConfig, "pluginExtensions" | "projectDir" | "srcDir">): EmittedLayers {
+/**
+ * Crawled layers only import what `keys` names. A module that reads, say, only
+ * `i18nModule` must not import route files: a route that imports the host
+ * package would close an import cycle back into that module.
+ */
+export function emitLayers(
+ config: Pick<BuiltMercurConfig, "pluginExtensions" | "projectDir" | "srcDir">,
+ keys: readonly LayerKey[]
+): EmittedLayers {
const lines: string[] = []
const declarations: string[] = []
const names: string[] = []
@@ -154,7 +187,7 @@ export function emitLayers(config: Pick<BuiltMercurConfig, "pluginExtensions" |
return
}
- const collected = collectLayer(source.srcDir, layer, index)
+ const collected = collectLayer(source.srcDir, layer, index, keys)
index = collected.nextIndex
lines.push(...collected.imports)
declarations.push(collected.declaration)
diff --git a/packages/dashboard-sdk/src/layouts-module.ts b/packages/dashboard-sdk/src/layouts-module.ts
index 45c6ca643..9d1b39597 100644
--- a/packages/dashboard-sdk/src/layouts-module.ts
+++ b/packages/dashboard-sdk/src/layouts-module.ts
@@ -3,7 +3,7 @@ import type { BuiltMercurConfig } from "./types"
/** A later layout with the same id replaces the earlier one; `core:` ids are reserved. */
export function generateLayouts(config: BuiltMercurConfig): string {
- const { header, names } = emitLayers(config)
+ const { header, names } = emitLayers(config, ["layoutModule"])
return `${header}
diff --git a/packages/dashboard-sdk/src/menu-items.ts b/packages/dashboard-sdk/src/menu-items.ts
index e22a494d0..a5a2f8579 100644
--- a/packages/dashboard-sdk/src/menu-items.ts
+++ b/packages/dashboard-sdk/src/menu-items.ts
@@ -276,7 +276,7 @@ export function parseMenuItemFile(
/** Later layers win: a menu item at a path already declared replaces it. */
export function generateMenuItems(config: BuiltMercurConfig): string {
- const { header, names } = emitLayers(config)
+ const { header, names } = emitLayers(config, ["menuItemModule"])
return `${header}
diff --git a/packages/dashboard-sdk/src/navigation.ts b/packages/dashboard-sdk/src/navigation.ts
index 15ef4d6ab..aff063b60 100644
--- a/packages/dashboard-sdk/src/navigation.ts
+++ b/packages/dashboard-sdk/src/navigation.ts
@@ -6,7 +6,7 @@ import type { BuiltMercurConfig } from "./types"
* items with the same id are combined field by field, later layers winning.
*/
export function generateNavigation(config: BuiltMercurConfig): string {
- const { header, names } = emitLayers(config)
+ const { header, names } = emitLayers(config, ["navigationModule"])
return `${header}
diff --git a/packages/dashboard-sdk/src/preferences-module.ts b/packages/dashboard-sdk/src/preferences-module.ts
index 0ec2be589..614a99a52 100644
--- a/packages/dashboard-sdk/src/preferences-module.ts
+++ b/packages/dashboard-sdk/src/preferences-module.ts
@@ -6,7 +6,7 @@ import type { BuiltMercurConfig } from "./types"
* the runtime registry, field by field per zone entry, later layers winning.
*/
export function generatePreferences(config: BuiltMercurConfig): string {
- const { header, names } = emitLayers(config)
+ const { header, names } = emitLayers(config, ["preferenceModule"])
return `${header}
diff --git a/packages/dashboard-sdk/src/routes.ts b/packages/dashboard-sdk/src/routes.ts
index c778bcb1d..66f2580e2 100644
--- a/packages/dashboard-sdk/src/routes.ts
+++ b/packages/dashboard-sdk/src/routes.ts
@@ -284,7 +284,7 @@ export function buildRouteTree(results: RouteResult[]): RouteResult[] {
* the override and hands the overridden page to the new one as `renderDefault`.
*/
export function generateRoutes(config: BuiltMercurConfig): string {
- const { header, names } = emitLayers(config)
+ const { header, names } = emitLayers(config, ["routeModule"])
return `${header}
diff --git a/packages/dashboard-sdk/src/widgets.ts b/packages/dashboard-sdk/src/widgets.ts
index 6efa2dd18..2226d722d 100644
--- a/packages/dashboard-sdk/src/widgets.ts
+++ b/packages/dashboard-sdk/src/widgets.ts
@@ -216,7 +216,7 @@ export function collectWidgets(
* the earlier one so a project can swap a plugin's widget without a new id.
*/
export function generateWidgets(config: BuiltMercurConfig): string {
- const { header, names } = emitLayers(config)
+ const { header, names } = emitLayers(config, ["widgetModule"])
return `${header}