Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Document typed plugin routes; add the plan

Damian Legawiec19a21cb601f0
diff --git a/CLAUDE.md b/CLAUDE.md
index 4d3d823bc7..a90b083a89 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -40,6 +40,7 @@ Multi-version plans (some phases shipped, some pending):
- `6.0-channels-catalogs-b2b.md` — Channel + ProductPublication (replaces StoreProduct) + single-owner Product (`belongs_to :store`) + Publishing card (legacy admin + SPA) + `Channel#default` boolean shipped in 5.5. Channel-level gated storefront access (`storefront_access` enum + channel-owned `guest_checkout`, both with store fallback, enforced in the v3 Store API) targeted for 5.6. Catalog, Company/CompanyLocation/CompanyContact for B2B pending in 6.0. Multi-store catalogs (historic `Product has_many :stores`) move to the `spree_multi_store` extension.
- `5.6-6.0-single-store-promotions-payment-methods.md` — Migrate `Spree::Promotion` + `Spree::PaymentMethod` from multi-store (`has_many :stores` via `spree_promotions_stores` / `spree_payment_methods_stores` join tables) to single-owner `belongs_to :store`, mirroring the 5.5 single-owner Product migration. 5.6 (implemented): `store_id` FK + required-store presence via `Spree::SingleStoreResource`, backfill rake task (loud per-record deprecation on shared records), shared `LegacyMultiStoreSupport` deprecation bridge, deletes the `ResourceController` `store_ids=` seam, deprecates `StoreScopedResource`; multi-store sharing moves to the `spree_multi_store` extension (join tables left intact). 6.0 cleanup: enforce `null: false`, drop join tables + bridges. Paired with `6.0-channels-catalogs-b2b.md`.
- `5.6-project-layout-and-dashboard.md` — React Dashboard Developer Preview packaging + `backend/` → `api/` project layout. Implemented: `<Dashboard />` shell export from `@spree/dashboard` (source-only, relative imports only), monorepo-canonical `packages/dashboard-starter` thin host (synced to the `spree/dashboard-starter` template repo on release), `spree add dashboard` (env carries only `VITE_SPREE_API_URL` — never secret keys). Pending: layout rename + `detectApiDir` dual-layout CLI, create-spree-app dashboard phase, `spree upgrade layout`, template sync job.
+- `5.6-dashboard-typed-plugin-routes.md` — Plugin file routes compiled into the host's TanStack route tree: `spree.dashboard.routes` marker + virtual-route-config composition in `@spree/dashboard/vite`, `createDashboardRouter` + `<Dashboard router>` ownership inversion, typed cast-free links. Runtime route registry stays for dynamic/in-app cases (catch-all is lowest priority). Implemented; published-tarball spike pending.
Pending design work (drafts, no implementation yet):
- `5.6-admin-spa-csv-import.md` — Universal dashboard CSV import over the existing `Spree::Import` pipeline (implemented). Admin API v3 surface (create via direct-upload signed blob, `complete_mapping`, `retry_failed_rows`, nested failed-rows index, write-scope gating), `client.imports` SDK resource, dashboard-core `ImportButton` (per-context `<Can>` gating, upload Sheet) + full-window wizard dialog driven by an `?import=` search param, with history under `/settings/imports` (new `audit` settings-nav group). Status via API polling — explicitly no ActionCable/Turbo Streams in the SPA; legacy per-row live feed replaced by polled counters + paginated failed-rows table.
diff --git a/docs/developer/dashboard/customization/routes.mdx b/docs/developer/dashboard/customization/routes.mdx
index ec4b97ad7f..083d7dc280 100644
--- a/docs/developer/dashboard/customization/routes.mdx
+++ b/docs/developer/dashboard/customization/routes.mdx
@@ -4,9 +4,55 @@ sidebarTitle: Routes
description: Mount custom pages under your dashboard's `/$storeId/...` path. Supports path params, permission gating, and works alongside the dashboard's built-in routes.
---
-The dashboard's first-party routes (`customers/`, `orders/`, `products/`, …) are file-based via TanStack Router and live in `@spree/dashboard/src/routes/`. Custom routes from host customizations or plugins go through a **route registry** in `@spree/dashboard-core`. A catch-all dispatcher mounted at `/_authenticated/$storeId/$` reads the registry on every navigation and renders the matched component.
+The dashboard's first-party routes (`customers/`, `orders/`, `products/`, …) are file-based via TanStack Router and live in `@spree/dashboard/src/routes/`. Custom pages have two mechanisms:
-## Add a route
+1. **File routes** (packaged plugins — preferred): the plugin ships ordinary TanStack route files, and the host build compiles them into its typed route tree. Typed `<Link>`s with no casts, route-level code splitting, `validateSearch`, loaders — full router citizenship.
+2. **Route registry** (in-app & dynamic): `defineDashboardPlugin({ routes })` entries matched at navigation time by a catch-all dispatcher at `/_authenticated/$storeId/$`. Use for host-app customizations (`plugins.ts`) and anything registered conditionally at runtime. File routes always win over the registry — the catch-all is the lowest-priority match.
+
+## File routes (packaged plugins)
+
+Declare a routes directory in your plugin's marker and put TanStack route files in it:
+
+```jsonc
+// package.json
+"spree": { "dashboard": { "plugin": true, "routes": "./src/routes" } }
+```
+
+```
+src/
+├── pages/ # page components
+└── routes/
+ ├── brands.index.tsx # → /$storeId/brands
+ └── brands.$brandId.tsx # → /$storeId/brands/br_123
+```
+
+```tsx
+// src/routes/brands.index.tsx
+import { resourceSearchSchema } from '@spree/dashboard-core'
+import { createFileRoute } from '@tanstack/react-router'
+import { BrandsListPage } from '../pages/brands-list'
+
+export const Route = createFileRoute('/_authenticated/$storeId/brands/')({
+ validateSearch: resourceSearchSchema,
+ component: () => <BrandsListPage searchParams={Route.useSearch()} />,
+})
+```
+
+Rules that make this work:
+
+- **Commit the final composed path literal.** Plugin routes mount under the dashboard's `_authenticated/$storeId` layout; the route generator verifies the literal (and would rewrite a wrong one).
+- **The host regenerates its `routeTree.gen.ts` on every dev start and build** from installed package versions — updating your plugin picks up new routes automatically (dev servers need a restart, same as installing a plugin).
+- **Exclude `src/routes` from your package's standalone `tsc`** — `createFileRoute` paths only type-check against a generated tree, which exists in host programs. Develop against a dashboard host (the scaffold's tsconfig ships this exclusion).
+
+Links to file routes are fully typed — no casts:
+
+```tsx
+<Link to="/$storeId/brands/$brandId" params={{ brandId: brand.id }}>view</Link>
+```
+
+## Runtime route registry (in-app & dynamic)
+
+Register from your host app's `plugins.ts` (or a plugin that genuinely needs runtime registration):
```tsx
import { defineDashboardPlugin } from '@spree/dashboard-core'
@@ -97,9 +143,9 @@ function ReportsPage() {
}
```
-## Linking to a custom route
+## Linking to a registry route
-Use TanStack Router's `<Link>`. The dashboard's link API expects a path template + params object:
+Registry routes aren't in the generated route tree, so links to them bypass static checking:
```tsx
import { Link } from '@tanstack/react-router'
diff --git a/docs/developer/dashboard/plugins/publishing.mdx b/docs/developer/dashboard/plugins/publishing.mdx
index b5b6c378b7..35c071b5ea 100644
--- a/docs/developer/dashboard/plugins/publishing.mdx
+++ b/docs/developer/dashboard/plugins/publishing.mdx
@@ -88,12 +88,15 @@ Declare your package as a dashboard plugin in its own `package.json`:
{
"spree": {
"dashboard": {
- "plugin": true
+ "plugin": true,
+ "routes": "./src/routes"
}
}
}
```
+`routes` (optional) points at your TanStack file-routes directory; the host build compiles it into its typed route tree — see the [routes guide](/developer/dashboard/customization/routes).
+
This marker is what powers **auto-discovery**: when a host calls `spreeDashboardPlugin()` without an explicit `plugins` array (the default), the Vite plugin walks the host's `package.json` deps + devDeps, reads each one's manifest, and picks up anything with `spree.dashboard.plugin: true`. The host doesn't have to know your plugin's name — `pnpm add @your-scope/your-plugin` is the entire installation step.
The CLI scaffold (`spree plugin new`) writes this field for you. If you're hand-rolling a plugin, add it before publishing — without it, hosts that rely on auto-discovery won't find your plugin and Tailwind won't pick up your class names.
diff --git a/docs/developer/dashboard/plugins/scaffolding.mdx b/docs/developer/dashboard/plugins/scaffolding.mdx
index 019437820c..c0dd545622 100644
--- a/docs/developer/dashboard/plugins/scaffolding.mdx
+++ b/docs/developer/dashboard/plugins/scaffolding.mdx
@@ -22,8 +22,10 @@ your-plugin/
├── index.tsx # defineDashboardPlugin entry
├── client.ts # adminClient request wrappers
├── types.ts # plugin-specific TS types
- ├── routes/
+ ├── pages/
│ └── <name>-list.tsx
+ ├── routes/ # TanStack file routes, compiled into the host's typed route tree
+ │ └── <name>.index.tsx
├── slots/
│ └── product-<name>-card.tsx
└── locales/
@@ -87,11 +89,13 @@ import { defineDashboardPlugin } from '@spree/dashboard-core'
import { PackageIcon } from 'lucide-react'
import i18n from 'i18next'
import en from './locales/en.json'
-import { MyPluginList } from './routes/my-plugin-list'
import { MyPluginCard } from './slots/product-my-plugin-card'
i18n.addResourceBundle('en', 'admin', en, true, false)
+// Routes are NOT registered here — they ship as file routes in src/routes/
+// (declared via the package.json marker) and compile into the host's typed
+// route tree. See the routes guide.
defineDashboardPlugin({
nav: [{
key: 'my-plugin',
@@ -100,11 +104,6 @@ defineDashboardPlugin({
icon: PackageIcon,
position: 250,
}],
- routes: [{
- key: 'my-plugin-list',
- path: '/my-plugin',
- component: MyPluginList,
- }],
slots: {
'product.form_sidebar': [{
id: 'my-plugin-card',
diff --git a/docs/plans/5.6-dashboard-typed-plugin-routes.md b/docs/plans/5.6-dashboard-typed-plugin-routes.md
new file mode 100644
index 0000000000..57ccb56cc5
--- /dev/null
+++ b/docs/plans/5.6-dashboard-typed-plugin-routes.md
@@ -0,0 +1,105 @@
+# Dashboard Typed Plugin Routes (Build-Time Route Composition)
+
+**Status:** In Progress (core implemented; published-tarball spike pending)
+**Target:** Spree 5.6 (React Dashboard Developer Preview)
+**Depends on:** `5.6-project-layout-and-dashboard.md` (shell export, `packages/dashboard-starter`), `6.0-admin-spa.md`
+**Author:** Damian + Claude
+**Last updated:** 2026-07-06
+
+## Summary
+
+Plugin routes originally went only through a runtime registry: `defineDashboardPlugin({ routes })` entries matched by a catch-all `$` route at navigation time. That works, but plugin pages were second-class — `<Link>`s to them needed `as never` casts, they got no route-level code splitting, and no router features (loaders, search-schema validation, per-route error boundaries). This plan makes packaged plugins ship ordinary TanStack **file routes** that the **host build compiles into its route tree**, giving plugin pages full typed-router citizenship, while the runtime registry remains the API for dynamic, host-app cases.
+
+The enabling insight: TanStack Router's generator **parses route files statically — it never executes them** — so plugin route files can be composed at build time without running plugin code in Node (the fragility we deliberately avoid; compare Vendure executing the server config inside Vite).
+
+## Key Decisions (do not deviate without discussion)
+
+- **Plugin routes are plain TanStack route files** in a directory the plugin declares via its existing marker: `"spree": { "dashboard": { "plugin": true, "routes": "./src/routes" } }`. Route files may import anything (they compile in the browser build); the plugin's *entry module* no longer registers routes.
+- **Route files commit the FINAL composed path literal** (e.g. `createFileRoute('/_authenticated/$storeId/brands/')`). Plugin routes mount under the shell's authenticated store scope. The generator verifies literals and rewrites mismatches — committing them correctly means it never writes into the package (verified: files pass through untouched).
+- **The host generates the route tree** (`src/routeTree.gen.ts`, committed). `@spree/dashboard/vite`'s `spreeDashboardPlugin()` wraps `@tanstack/router-plugin` with a `@tanstack/virtual-file-routes` config: a hand-maintained skeleton of the shell's top-level layout (`__root` → `login`/`accept-invitation` → `_authenticated` → `$storeId`) that `physical()`-mounts the shell's `$storeId` pages plus each discovered plugin's routes directory. Regeneration happens on every dev start and build, from installed package versions — no publish-time snapshot exists to go stale, and upgrades that add/rename pages show up as a reviewable gen-file diff and as type errors on stale links.
+- **Router ownership is inverted.** `@spree/dashboard` exports `createDashboardRouter(routeTree)` and `<Dashboard router={...} />`; the `Register`/`FileRoutesByPath` augmentations live in host code only (the shell's own live in its `main.tsx` dev harness, which hosts never import). Two augmentations of the same interface in one program conflict — this split is load-bearing.
+- **The registry + catch-all stay** for dynamic and in-app registration (`plugins.ts`, conditional routes). File routes always win: the catch-all `$` is by definition the lowest-priority match.
+- **Composition lives in `@spree/dashboard/vite`, not `dashboard-core/vite`.** Custom dashboards built on core + ui have no shell routes to compose; they keep using `@spree/dashboard-core/vite`.
+- **Plugin route files are excluded from the plugin's standalone `tsc`** (`"exclude": ["src/routes"]`). `createFileRoute` paths only type-check against a generated tree, which only exists in a host program. In this monorepo the starter compiles them (it is the standing consumer test); out-of-repo authors develop against a host app.
+
+## Design Details
+
+### The convention (plugin side)
+
+```
+my-plugin/packages/dashboard/
+├── package.json # "spree": { "dashboard": { "plugin": true, "routes": "./src/routes" } }
+└── src/
+ ├── index.tsx # entry: slots, nav, tables, translations — NO route registration
+ ├── pages/ # page components
+ └── routes/ # TanStack route files, full final path literals
+ ├── brands.index.tsx → /$storeId/brands
+ └── brands.$brandId.tsx → /$storeId/brands/br_123
+```
+
+Route files use everything the router offers — `validateSearch` (e.g. `resourceSearchSchema` from dashboard-core for `<ResourceTable>` pages), loaders, error components. Links to plugin routes are fully typed in the host program: no `as string` / `as never` casts.
+
+### The composition (host side)
+
+`spreeDashboardPlugin()` from `@spree/dashboard/vite`:
+
+1. Resolves the shell's `routes/` directory from the host's installed `@spree/dashboard`.
+2. Resolves each plugin's declared routes dir via `discoverDashboardPluginManifests` (same discovery/whitelist as activation and Tailwind scanning — one plugin list drives all three).
+3. Configures `TanStackRouterVite` with the virtual skeleton + `physical('')` mounts and `generatedRouteTree: src/routeTree.gen.ts` (host-relative; option to override).
+
+Host `main.tsx` (the starter ships this):
+
+```tsx
+import { createDashboardRouter, Dashboard } from '@spree/dashboard'
+import 'virtual:spree-dashboard-plugins'
+import './plugins'
+import './styles.css'
+import { routeTree } from './routeTree.gen'
+
+const router = createDashboardRouter(routeTree)
+
+declare module '@tanstack/react-router' {
+ interface Register {
+ router: typeof router
+ }
+}
+
+createRoot(document.getElementById('root')!).render(<Dashboard router={router} />)
+```
+
+### Verified in-repo
+
+- Flag-off regeneration of the shell's own tree via the virtual skeleton produces the **identical route set** (44 routes) as the previous file-scan config; the shell's Vite config uses the same composition (dogfooding — a skeleton omission breaks shell dev/e2e in-repo, not silently in hosts).
+- The starter's composed tree contains the example plugin's routes (46 = 44 + 2) with correct IDs and full paths; plugin route files pass through generation unmodified.
+- Starter typecheck passes with the example plugin's **cast-free** `<Link to="/$storeId/brands/$brandId" params={{ brandId }}>` — typed plugin links proven end-to-end.
+- The starter must declare `@tanstack/react-router` as a direct dependency: its gen file augments the router module, and augmentation only lands on the copy the host resolves.
+
+## Migration Path
+
+1. *(shipped)* Shell: `@/` → relative imports, `createDashboardRouter` + `<Dashboard router>` exports, `Register` moved to `main.tsx`.
+2. *(shipped)* `@spree/dashboard/vite` route composition; the dashboard app itself and `packages/dashboard-starter` build through it.
+3. *(shipped)* `spree.dashboard.routes` marker; example plugin and CLI scaffold template migrated to file routes.
+4. Docs: routes guide teaches file routes as the packaged-plugin path, registry for dynamic cases.
+5. **Pending:** packed-tarball spike (generator parsing route files under real `node_modules`), then this pattern is cleared for published plugins.
+6. Registry `routes:` stays indefinitely for in-app use; revisit whether to deprecate it for *packaged* plugins after the preview feedback round.
+
+## Constraints on Current Work
+
+- **New shell top-level routes must be added to the virtual skeleton** in `packages/dashboard/src/vite/index.ts` (files under `_authenticated/$storeId/` need nothing — they're physically mounted).
+- **Never declare `Register`/route-tree augmentations in shell code hosts compile** — host `main.tsx` only.
+- **Plugin scaffolds/examples put pages in `src/pages/`, route files in `src/routes/`**, and exclude `src/routes` from standalone tsc.
+- **Don't hand-edit `routeTree.gen.ts`** anywhere; it regenerates on every build.
+
+## Open Questions
+
+1. **Published-tarball behavior** — the generator must parse (and never write to) route files inside real `node_modules`. Expected fine (parse-only, literals committed correct); needs the spike before plugins publish.
+2. **Route path collisions between plugins** — currently surfaces as a generator error naming files, not packages. Wrap with a friendlier message?
+3. **Version coupling** — `@spree/dashboard` now depends on `@tanstack/router-plugin` + `@tanstack/virtual-file-routes`; pin policy relative to `@tanstack/react-router` majors/minors.
+
+## References
+
+- `docs/plans/5.6-project-layout-and-dashboard.md` — shell export, starter, packaging decisions (open question 5 there is resolved by this plan)
+- `docs/plans/6.0-admin-spa.md` — SPA architecture and extension points
+- `packages/dashboard/src/vite/index.ts` — the composition
+- `packages/dashboard-core/src/lib/route-registry.ts` — the runtime registry this coexists with
+- TanStack virtual file routes: https://tanstack.com/router/latest/docs/framework/react/routing/virtual-file-routes
diff --git a/docs/plans/5.6-project-layout-and-dashboard.md b/docs/plans/5.6-project-layout-and-dashboard.md
index 7522c8a81f..c73799549a 100644
--- a/docs/plans/5.6-project-layout-and-dashboard.md
+++ b/docs/plans/5.6-project-layout-and-dashboard.md
@@ -552,7 +552,7 @@ Manual QA checklist:
4. **When exactly does `backend/` support get dropped?** The plan says "by 6.0 GA". Open: do we want a 5.7 deprecation warning step in between, or jump straight from "silent dual-support in 5.6" to "warning in 6.0 RC" to "removed in 6.0 GA"? The 5.6/6.0 cycle is short enough that one warning step at 6.0 RC is probably enough.
-5. **Build-time typed route composition (future).** Plugin routes currently go through the runtime route registry + catch-all dispatcher — simple, works for in-app customization, but plugin-route `<Link>`s need `as never` casts and get no route-level code splitting. Since the shell is source-only and the Vite plugin already knows the discovered plugin list at build time, a later phase could additionally compile statically-declared plugin routes into the host's route tree (typed links, per-route chunks) while keeping the runtime registry for dynamic cases. Requires route declarations to be importable without executing the full plugin module — likely a conventional `dashboard/routes` entry. Not preview-blocking; design when the first big plugin needs it.
+5. **Build-time typed route composition** — resolved and implemented; see `5.6-dashboard-typed-plugin-routes.md`.
## References