The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.
TypeScript b2b-marketplacecomposable-commerceecommerceenterpriseheadless-commercemarketplacemedusamedusajsmulti-vendortypescript
docs: add v2 developer guide pages and rewrite canary docs
vholikf3bcb9928c14
diff --git a/apps/docs/canary/blocks.mdx b/apps/docs/canary/blocks.mdxdeleted file mode 100644index f22093a59..000000000--- a/apps/docs/canary/blocks.mdx+++ /dev/null@@ -1,57 +0,0 @@-----title: "Blocks"-description: "Reusable code pieces you can install into your marketplace project."------<Snippet file="canary-warning.mdx" />--Blocks are the building units of a Mercur 2.0 marketplace. Each block is a self-contained piece of functionality — a module, workflow, API route, link, or UI extension — that gets copied directly into your project.--## Block types--<CardGroup cols={3}>- <Card title="Modules" icon="database">- Data models and business logic. Define entities, services, and database schemas.- </Card>- <Card title="Workflows" icon="arrow-progress">- Multi-step business processes with compensation logic and extension hooks.- </Card>- <Card title="API Routes" icon="route">- HTTP endpoints for Admin, Vendor, and Store APIs.- </Card>- <Card title="Links" icon="link">- Relationships between modules that enable cross-domain queries.- </Card>- <Card title="Admin Extensions" icon="table-columns">- Widgets and pages for the admin dashboard.- </Card>- <Card title="Vendor Extensions" icon="store">- Widgets and pages for the vendor portal.- </Card>-</CardGroup>--## Installing blocks--```bash-# Search for blocks-npx @mercurjs/cli@canary search--# Add specific blocks-npx @mercurjs/cli@canary add reviews commission--# Check for upstream changes-npx @mercurjs/cli@canary diff reviews-```--## Available blocks--| Block | Type | Description |-|---|---|---|-| `reviews` | Module + Workflows + API | Product and seller review system |-| `commission` | Module + Workflows | Commission rules and calculations |-| `requests` | Module + Workflows + API | Product moderation and approval flows |-| `order-return-request` | Module + Workflows | Return request escalation handling |-| `wishlist` | Module + API | Customer wishlists |-| `payout` | Module + Workflows | Vendor payout processing |-| `attributes` | Module + Links | Custom product attributes |-| `secondary-categories` | Module + Links | Alternative category trees |diff --git a/apps/docs/canary/quick-start.mdx b/apps/docs/canary/quick-start.mdxdeleted file mode 100644index 898b2ff2a..000000000--- a/apps/docs/canary/quick-start.mdx+++ /dev/null@@ -1,46 +0,0 @@-----title: "Quick Start"-description: "Create a new Mercur 2.0 marketplace project using the CLI."------<Snippet file="canary-warning.mdx" />--## Create a new project--```bash-npx @mercurjs/cli@canary create my-marketplace-```--The CLI will guide you through template selection, database configuration, and dependency installation.--## Add blocks--Browse and install blocks — the building units of your marketplace:--```bash-# Search available blocks-npx @mercurjs/cli@canary search--# Add blocks to your project-npx @mercurjs/cli@canary add reviews commission requests-```--## Start developing--```bash-cd my-marketplace-yarn dev-```--Your marketplace backend will be running at `http://localhost:9000`.--## What's next?--<CardGroup cols={2}>- <Card title="Browse Blocks" icon="cubes" href="/canary/blocks">- Explore all available modules, workflows, and extensions.- </Card>- <Card title="CLI Reference" icon="terminal" href="/cli-installation">- Learn all CLI commands and options.- </Card>-</CardGroup>diff --git a/apps/docs/canary/welcome.mdx b/apps/docs/canary/welcome.mdxdeleted file mode 100644index 257d438ca..000000000--- a/apps/docs/canary/welcome.mdx+++ /dev/null@@ -1,48 +0,0 @@-----title: "Welcome to Mercur 2.0"-sidebarTitle: "Welcome"-description: "The open-source marketplace engine, rebuilt from the ground up. Modular blocks, CLI-first workflow, and full code ownership."------<Snippet file="canary-warning.mdx" />--Mercur 2.0 is a complete rethink of how marketplace platforms should work. Instead of installing monolithic plugins, you pick and install individual **blocks** — modules, workflows, API routes, and UI extensions — directly into your project. You own every line of code.--## Get Started--<CardGroup cols={3}>- <Card title="Quick Start" icon="rocket" href="/canary/quick-start">- Create a new marketplace project in minutes using the Mercur CLI.- </Card>- <Card title="CLI Installation" icon="terminal" href="/cli-installation">- Install and configure the @mercurjs/cli tool for your environment.- </Card>- <Card title="What's New in 2.0" icon="sparkles" href="/canary/whats-new">- See what changed from 1.x and why we rebuilt Mercur from scratch.- </Card>-</CardGroup>--## Explore the Platform--<CardGroup cols={2}>- <Card title="Blocks" icon="cubes" href="/canary/blocks">- Browse available modules, workflows, links, and extensions you can add to your project.- </Card>- <Card title="Core Concepts" icon="book" href="/core-concepts/seller">- Understand sellers, commissions, order splitting, payouts, and marketplace logic.- </Card>-</CardGroup>--## Developer Resources--<CardGroup cols={3}>- <Card title="API Reference" icon="code" href="/api-reference">- Explore Admin, Vendor, and Store API endpoints with examples.- </Card>- <Card title="Integrations" icon="plug" href="/integrations/stripe">- Connect Stripe, Algolia, Resend, and more to your marketplace.- </Card>- <Card title="Help & Support" icon="life-ring" href="/help/support">- Get help via Discord, GitHub Discussions, or LLM-assisted docs.- </Card>-</CardGroup>diff --git a/apps/docs/canary/whats-new.mdx b/apps/docs/canary/whats-new.mdxdeleted file mode 100644index 973bef58c..000000000--- a/apps/docs/canary/whats-new.mdx+++ /dev/null@@ -1,39 +0,0 @@-----title: "What's New in 2.0"-description: "Key changes and improvements from Mercur 1.x to 2.0."------<Snippet file="canary-warning.mdx" />--## Block-based architecture--Mercur 2.0 replaces monolithic plugin packages with **blocks** — individual pieces of code installed directly into your project via the CLI, similar to shadcn/ui.--| | 1.x | 2.0 |-|---|---|---|-| **Installation** | npm packages | CLI-installed blocks |-| **Code ownership** | node_modules | Your source tree |-| **Customization** | Override/extend | Edit directly |-| **Updates** | Package upgrades | `mercurjs diff` to review changes |--## CLI-first workflow--The new `@mercurjs/cli` provides commands for every step of the development lifecycle:--- `mercurjs create` — scaffold a new project-- `mercurjs add` — install blocks from the registry-- `mercurjs diff` — compare local changes against upstream-- `mercurjs search` — discover available blocks-- `mercurjs codegen` — generate TypeScript types from API routes--## New block types--In addition to modules and workflows, 2.0 introduces:--- **Links** — define relationships between modules-- **Admin Extensions** — customize the admin dashboard-- **Vendor Extensions** — customize the vendor portal--## Migration from 1.x--If you're upgrading from 1.x, start a fresh 2.0 project and selectively add the blocks you need. The underlying Medusa framework and data models remain compatible.diff --git a/apps/docs/docs.json b/apps/docs/docs.jsonindex 320032f14..ec6585412 100644--- a/apps/docs/docs.json+++ b/apps/docs/docs.json@@ -337,23 +337,9 @@"tab": "Welcome","groups": [{- "group": "Overview",+ "group": "Welcome","pages": [- "canary/welcome"- ]- },- {- "group": "Getting Started",- "pages": [- "canary/quick-start",- "cli-installation",- "canary/whats-new"- ]- },- {- "group": "Concepts",- "pages": [- "canary/blocks"+ "v2/welcome"]}]@@ -362,286 +348,34 @@"tab": "Docs","groups": [{- "group": "Core Concepts",- "pages": [- "core-concepts/seller",- "core-concepts/order-splitting",- "core-concepts/payouts",- "core-concepts/commission",- "core-concepts/marketplace-settings",- "core-concepts/requests",- "core-concepts/reviews",- "core-concepts/notifications"- ]- },- {- "group": "Components",- "pages": [- "components/backend",- "components/admin-panel",- "components/vendor-panel",- "components/storefront"- ]- },- {- "group": "Product",- "pages": [- "product/framework",- "product/core-commerce-modules",- "product/core-infrastructure-modules",- {- "group": "Mercur marketplace modules",- "pages": [- {- "group": "Core",- "pages": [- {- "group": "Attribute module",- "pages": [- "product/modules/b2c-core/attribute/attribute-concept",- "product/modules/b2c-core/attribute/attribute-links",- "product/modules/b2c-core/attribute/attributes-data-models-ref",- "product/modules/b2c-core/attribute/attributes-services"- ]- },- {- "group": "Configuration module",- "pages": [- "product/modules/b2c-core/configuration/configuration-concept",- "product/modules/b2c-core/configuration/configuration-data-models-ref",- "product/modules/b2c-core/configuration/configuration-services"- ]- },- {- "group": "Marketplace module",- "pages": [- "product/modules/b2c-core/marketplace/marketplace-concept",- "product/modules/b2c-core/marketplace/marketplace-links",- "product/modules/b2c-core/marketplace/marketplace-data-model-reference",- "product/modules/b2c-core/marketplace/marketplace-service"- ]- },- {- "group": "Payout module",- "pages": [- "product/modules/b2c-core/payout/payout-concept",- "product/modules/b2c-core/payout/payout-links",- "product/modules/b2c-core/payout/payout-data-model-reference",- "product/modules/b2c-core/payout/payout-services"- ]- },- {- "group": "Secondary Category Module",- "pages": [- "product/modules/b2c-core/secondary-categories/secondary-categories-concept",- "product/modules/b2c-core/secondary-categories/secondary-category-links",- "product/modules/b2c-core/secondary-categories/sec-cat-data-model-reference",- "product/modules/b2c-core/secondary-categories/secondary-category-services"- ]- },- {- "group": "Seller module",- "pages": [- "product/modules/b2c-core/seller/seller-concept",- "product/modules/b2c-core/seller/seller-module-options",- "product/modules/b2c-core/seller/seller-links",- "product/modules/b2c-core/seller/seller-data-model-reference",- "product/modules/b2c-core/seller/seller-services"- ]- },- {- "group": "Split Order Payment Module",- "pages": [- "product/modules/b2c-core/split-order-payment/split-order-payment-concept",- "product/modules/b2c-core/split-order-payment/split-order-links",- "product/modules/b2c-core/split-order-payment/split-order-data-model-reference",- "product/modules/b2c-core/split-order-payment/split-order-services"- ]- },- {- "group": "Taxcode module",- "pages": [- "product/modules/b2c-core/taxcode/taxcode-concept",- "product/modules/b2c-core/taxcode/taxcode-links",- "product/modules/b2c-core/taxcode/taxcode-data-model-reference",- "product/modules/b2c-core/taxcode/taxcode-services"- ]- },- {- "group": "Wishlist module",- "pages": [- "product/modules/b2c-core/wishlist/wishlist-concept",- "product/modules/b2c-core/wishlist/wishlist-links",- "product/modules/b2c-core/wishlist/wishlist-data-model-reference",- "product/modules/b2c-core/wishlist/wishlist-services"- ]- }- ]- },- {- "group": "Commission",- "pages": [- {- "group": "Commission module",- "pages": [- "product/modules/commission/commission/commission-concept",- "product/modules/commission/commission/commission-data-model-reference",- "product/modules/commission/commission/commission-services"- ]- }- ]- },- {- "group": "Requests",- "pages": [- {- "group": "Request module",- "pages": [- "product/modules/requests/requests/requests-concept",- "product/modules/requests/requests/requests-links",- "product/modules/requests/requests/request-data-model-reference",- "product/modules/requests/requests/requests-services"- ]- },- {- "group": "Order Return Request module",- "pages": [- "product/modules/requests/order-return-request/order-return-request",- "product/modules/requests/order-return-request/order-return-request-links",- "product/modules/requests/order-return-request/order-return-request-data-model-reference",- "product/modules/requests/order-return-request/order-return-request-services"- ]- }- ]- },- {- "group": "Reviews",- "pages": [- {- "group": "Reviews module",- "pages": [- "product/modules/reviews/reviews/reviews-concept",- "product/modules/reviews/reviews/review-links",- "product/modules/reviews/reviews/review-data-model-reference",- "product/modules/reviews/reviews/review-service"- ]- }- ]- }- ]- },- {- "group": "Workflows",- "pages": [- {- "group": "Core",- "pages": [- "docs/product/workflows/core/price-list-workflows",- "docs/product/workflows/core/attribute",- "docs/product/workflows/core/campaign-workflows",- "docs/product/workflows/core/cart-workflows",- "docs/product/workflows/core/configuration-workflows",- "docs/product/workflows/core/customer-groups-workflows",- "docs/product/workflows/core/fulfillment-set-workflows",- "docs/product/workflows/core/order-workflows",- "docs/product/workflows/core/order-set-workflows",- "docs/product/workflows/core/payout-workflows",- "docs/product/workflows/core/product-workflows",- "docs/product/workflows/core/promotions-workflows",- "docs/product/workflows/core/seller-workflows",- "docs/product/workflows/core/split-order-payment",- "docs/product/workflows/core/wishlist-workflows",- "docs/product/workflows/core/common-workflows",- "docs/product/workflows/core/hooks"- ]- },- {- "group": "Commission",- "pages": [- "docs/product/workflows/commission/commission-workflows"- ]- },- {- "group": "Requests",- "pages": [- "docs/product/workflows/requests/requests",- "docs/product/workflows/requests/order-return-request-workflows"- ]- },- {- "group": "Reviews",- "pages": [- "docs/product/workflows/reviews/review-workflows"- ]- }- ]- },- "docs/product/js-sdk",- "docs/product/api",- {- "group": "Events",- "pages": [- "docs/product/events/core-events",- "docs/product/events/request-events",- "docs/product/events/reviews-events"- ]- },- {- "group": "Scheduled Jobs",- "pages": [- "docs/product/scheduled-jobs/core-scheduled-jobs"- ]- },- {- "group": "Subscribers",- "pages": [- "docs/product/subscribers/core",- "docs/product/subscribers/commission",- "docs/product/subscribers/requests",- "docs/product/subscribers/reviews"- ]- }- ]- },- {- "group": "Integrations",- "pages": [- "integrations/algolia",- "integrations/resend",- "integrations/stripe"- ]- },- {- "group": "Deployment",+ "group": "Getting started","pages": [- "medusa-cloud"+ "v2/getting-started/introduction",+ "v2/getting-started/concepts",+ "v2/getting-started/installation"]},{- "group": "Development",+ "group": "Core Concepts","pages": [- "development/set-up"+ "v2/core-concepts/seller",+ "v2/core-concepts/payout",+ "v2/core-concepts/commission"]},{- "group": "Help",+ "group": "Developer Guide","pages": [- "help/llm",- "help/mcp",- "help/support"+ "v2/developer-guide/overview",+ "v2/developer-guide/blocks",+ "v2/developer-guide/registry",+ "v2/developer-guide/api-client",+ "v2/developer-guide/cli",+ "v2/developer-guide/extending-panels"]}]},- {- "tab": "API Reference",- "groups": [- {- "group": "API Documentation",- "openapi": "api-reference/combined.oas.json"- }- ]- },{"tab": "Changelog","groups": [diff --git a/apps/docs/v2/core-concepts/commission.mdx b/apps/docs/v2/core-concepts/commission.mdxnew file mode 100644index 000000000..9dc8ac001--- /dev/null+++ b/apps/docs/v2/core-concepts/commission.mdx@@ -0,0 +1,113 @@+---+title: "Commission"+description: "How marketplace commissions work in Mercur — rates, rules, calculation, and the commission pipeline."+---++<Snippet file="canary-warning.mdx" />++Commissions are how the marketplace earns revenue. Rather than storing a single commission percentage, Mercur uses a **rule-based system** where commission rates are matched to line items and shipping methods based on configurable conditions.++## Commission rates++A **CommissionRate** defines how much commission the marketplace takes. Each rate has a type, a target, and an optional set of rules that determine when it applies.++| Field | Description |+|-------|-------------|+| `name` | Human-readable name (e.g. "Default Product Commission") |+| `code` | Unique system identifier |+| `type` | `FIXED` (flat amount) or `PERCENTAGE` |+| `target` | `ITEM` (applies to line items) or `SHIPPING` (applies to shipping methods) |+| `value` | The rate value — either a fixed amount or a percentage |+| `min_amount` | Optional minimum commission (floor) |+| `include_tax` | Whether to include tax in the base amount for calculation |+| `priority` | Higher priority rates are evaluated first |+| `currency_code` | Optional — restricts the rate to a specific currency |++## Commission rules++Rules determine **when** a rate applies. A rate without rules acts as a **default** — it applies to all items or shipping methods of its target type. Rules narrow the scope.++Each rule has a `reference` (the type of condition) and a `reference_id` (the value to match):++| Reference | Matches against |+|-----------|----------------|+| `product` | A specific product ID |+| `product_type` | Products of a given type |+| `product_collection` | Products in a collection |+| `product_category` | Products in a category |+| `seller` | Products owned by a specific seller |+| `shipping_option_type` | Shipping options of a given type |++A single rate can have multiple rules. The rate applies if **any** of its rules match.++### Priority and matching++Rates are evaluated in **descending priority order**. The first matching rate wins — subsequent rates are not applied. This lets you set up specific overrides with high priority and catch-all defaults with low priority.++**Example configuration:**++| Rate | Priority | Rules | Type | Value |+|------|----------|-------|------|-------|+| Electronics Commission | 10 | `product_category: "electronics"` | Percentage | 12% |+| Premium Seller Rate | 5 | `seller: "slr_abc123"` | Percentage | 8% |+| Default Commission | 0 | _(none — matches all)_ | Percentage | 15% |++An electronics product from the premium seller would match the Electronics Commission rate (priority 10), not the seller-specific rate (priority 5).++## The calculation pipeline++The `getCommissionLines` method calculates commissions for a given cart or order context:++**1. Load rates**+- All enabled commission rates are loaded with their rules, ordered by priority (highest first)+- Rates are separated into `ITEM` and `SHIPPING` targets++**2. Match items**+- For each line item, the system iterates through item-target rates in priority order+- It checks each rate's rules against the item's product, type, collection, category, and seller+- Rates with no rules match everything (defaults)+- First match wins++**3. Calculate amount**+- Base amount is the item subtotal (optionally including tax if `include_tax` is true)+- For `PERCENTAGE` rates: `commission = (base_amount × value) / 100`+- For `FIXED` rates: `commission = value`+- If the result is below `min_amount`, the minimum is used instead++**4. Match and calculate shipping**+- Same process repeats for shipping methods using shipping-target rates+- Matches against `shipping_option_type` rules++**5. Output**+- Returns an array of `CommissionLine` records, one per item and shipping method++<Info>+ All commission calculations use `BigNumber` arithmetic for precision. This is critical for financial accuracy — standard floating-point math can introduce rounding errors.+</Info>++## Commission lines++A **CommissionLine** is the calculated commission for a single line item or shipping method. It stores:++| Field | Description |+|-------|-------------|+| `item_id` | References the order line item or shipping method |+| `commission_rate_id` | The rate that was applied |+| `code` | Code of the applied rate |+| `rate` | The actual rate value used |+| `amount` | The calculated commission amount |++Commission lines are linked to order line items via a **read-only link**. This means you can query an order's line items and include their commission data in a single request.++## How commission connects to payouts++Commission lines are the bridge between orders and seller earnings:++1. An order is completed → commission lines are calculated for each item+2. When the order is credited to the seller's payout account, the total commission is subtracted:+ ```+ seller_earnings = order.total - sum(commission_line.amount)+ ```+3. The marketplace retains the commission amount++This separation means commission rates can be changed at any time without affecting already-calculated orders — the `CommissionLine` records serve as a permanent audit trail.diff --git a/apps/docs/v2/core-concepts/payout.mdx b/apps/docs/v2/core-concepts/payout.mdxnew file mode 100644index 000000000..40b394570--- /dev/null+++ b/apps/docs/v2/core-concepts/payout.mdx@@ -0,0 +1,114 @@+---+title: "Payout"+description: "How seller payouts work in Mercur — accounts, balances, transactions, and the payout pipeline."+---++<Snippet file="canary-warning.mdx" />++The payout module handles the financial side of a marketplace — tracking how much each seller has earned, maintaining their balance, and processing transfers to their bank accounts or payment accounts.++## Payout account++Every seller that wants to receive funds needs a **PayoutAccount**. This account is the central entity that links a seller to their financial balance and to an external payment provider (e.g. Stripe Connect).++### Account lifecycle++```+PENDING → ACTIVE+ ↓+ RESTRICTED → ACTIVE (or REJECTED)+```++| Status | Description |+|--------|-------------|+| `PENDING` | Account created, awaiting provider onboarding |+| `ACTIVE` | Fully onboarded, can receive payouts |+| `RESTRICTED` | Provider has flagged the account (e.g. missing KYC) |+| `REJECTED` | Provider rejected the account |++### Onboarding++When a payout account is created, an **Onboarding** record is attached to it. This stores provider-specific data needed for identity verification or account setup (e.g. Stripe Connect onboarding links). The onboarding data is merged with the account data before being sent to the provider.++<Info>+ Payout account creation uses idempotency keys to prevent duplicate accounts if the request is retried.+</Info>++## Balance tracking++Each payout account maintains a **PayoutBalance** per currency. The balance is updated automatically when transactions are added or removed.++Balances are stored with dual precision:+- `balance` — Display value for UI+- `raw_balance` — High-precision value (string with 20-digit precision) for accurate financial calculations++All balance calculations use `BigNumber` arithmetic to avoid floating-point errors.++## Transactions++A **PayoutTransaction** represents a credit or debit against a seller's payout account. Transactions are the building blocks of the balance — every balance change is backed by a transaction record.++Each transaction stores:++| Field | Description |+|-------|-------------|+| `amount` | The transaction amount |+| `currency_code` | Currency of the transaction |+| `reference` | Type of source (e.g. `"order"`) |+| `reference_id` | ID of the source entity |++<Info>+ Balance updates use `SERIALIZABLE` transaction isolation to prevent race conditions when multiple orders are credited simultaneously.+</Info>++## The payout pipeline++### Crediting an order++When an order is completed, the `creditOrderToPayoutAccountWorkflow` calculates the seller's earnings and credits their account:++1. **Fetch order** — Loads the order with its items, commission lines, and seller's payout account+2. **Validate account** — Confirms the seller has a linked payout account+3. **Calculate net earnings** — Sums commission amounts across all items and subtracts from the order total:+ ```+ net_amount = order.total - total_commission+ ```+4. **Create transaction** — Records a `PayoutTransaction` with `reference: "order"` pointing to the order ID+5. **Update balance** — Adds the transaction amount to the seller's `PayoutBalance` for that currency++### Processing payouts++The `processPayoutWorkflow` handles webhook events from the external payment provider. It uses conditional branching to update the correct entity:++**Account events:**+- `account.activated` → Status set to `ACTIVE`+- `account.restricted` → Status set to `RESTRICTED`+- `account.rejected` → Status set to `REJECTED`++**Payout events:**+- `payout.processing` → Status set to `PROCESSING`+- `payout.paid` → Status set to `PAID`+- `payout.failed` → Status set to `FAILED`+- `payout.canceled` → Status set to `CANCELED`++### Payout validation++Before a payout is initiated, the system validates:+1. The account status is `ACTIVE`+2. The account has sufficient balance in the requested currency++## Data model overview++```+PayoutAccount+├── Onboarding (one-to-one)+├── PayoutBalance (one-to-many, per currency)+├── PayoutTransaction (one-to-many, credits/debits)+└── Payout (one-to-many, actual transfers)+```++## Provider abstraction++The payout module is **provider-agnostic**. A `PayoutProviderService` acts as a bridge to the external payment processor. It delegates all external operations — creating accounts, processing payouts, parsing webhooks — to a pluggable provider implementation.++The module expects exactly one payout provider to be registered. Provider-specific data is stored in the `data` JSON fields on accounts, payouts, and onboarding records.diff --git a/apps/docs/v2/core-concepts/seller.mdx b/apps/docs/v2/core-concepts/seller.mdxnew file mode 100644index 000000000..15f82e719--- /dev/null+++ b/apps/docs/v2/core-concepts/seller.mdx@@ -0,0 +1,110 @@+---+title: "Seller"+description: "How sellers work in Mercur — registration, lifecycle, product ownership, and order splitting."+---++<Snippet file="canary-warning.mdx" />++In a marketplace, the **Seller** is the central actor. Every product, order, shipment, and payout ultimately ties back to a seller. Mercur's seller module manages the full vendor lifecycle — from registration through order fulfillment.++## Seller lifecycle++A seller progresses through a defined set of statuses:++```+PENDING → ACTIVE → (optionally) SUSPENDED+```++1. **PENDING** — A new seller registers and starts in this state. They can set up their profile but cannot sell.+2. **ACTIVE** — An admin approves the seller. Only active sellers' products appear in the storefront and can be purchased.+3. **SUSPENDED** — An admin can suspend a seller at any time, removing their products from sale.++### Seller profile++Each seller has a profile with:++| Field | Description |+|-------|-------------|+| `name` | Display name (required) |+| `handle` | Unique, URL-safe identifier (auto-generated from name) |+| `email` | Contact email |+| `phone` | Contact phone |+| `logo` | Logo URL for storefront/portal |+| `cover_image` | Cover image URL |+| `address_1`, `city`, `country_code`, `province`, `postal_code` | Business address |++Handles are validated to be URL-safe (alphanumeric characters, hyphens, and underscores only).++## Product ownership++Products in Mercur are always owned by a seller. This relationship is established via a **link** between the `Product` entity (from Medusa core) and the `Seller` entity. When a seller creates a product, this link is automatically created.++This ownership is what drives the core marketplace behavior — it determines which seller receives an order, which shipping options apply, and how commissions are calculated.++## Order splitting++When a customer adds products from multiple sellers to their cart and checks out, Mercur does not create a single order. Instead, it splits the cart into **one order per seller**.++### The split order pipeline++The `completeCartWithSplitOrdersWorkflow` handles this process:++**1. Validation**+- Acquires a distributed lock on the cart to prevent concurrent completions+- Validates that every cart item has an assigned seller+- Validates that items requiring shipping have seller-specific shipping methods++**2. Grouping by seller**+- Cart items are grouped by their seller+- Shipping methods are matched to the corresponding seller's shipping options+- Addresses, tax lines, and promotion adjustments are copied per seller++**3. Order creation**+- A separate order is created for each seller, containing only that seller's items and shipping methods+- An **OrderGroup** is created to tie all seller orders back to the original cart transaction+- Inventory is reserved across all orders in parallel++**4. Payment splitting**+- The total payment is proportionally allocated across seller orders+- Formula: `(seller_order_total / payment_total) × capture_amount`+- Each seller order gets its own payment transaction record++**5. Post-creation**+- Commission lines are calculated for each order+- Seller–customer relationships are created (for first-purchase tracking)+- `order.placed` events are emitted for each seller order+- An `order_group.created` event is emitted for the group++### OrderGroup++The `OrderGroup` entity represents the customer's view of their purchase. It groups all seller orders from a single checkout and provides computed fields:++- `seller_count` — Number of distinct sellers in the order+- `total` — Combined total across all seller orders++<Info>+ The order splitting process uses distributed locking with a 30-second timeout and 2-minute TTL to ensure only one completion attempt can proceed at a time.+</Info>++## Relationships++A seller is linked to many entities across the system:++| Entity | Relationship | Purpose |+|--------|-------------|---------|+| Products | One-to-many | Products the seller owns |+| Orders | One-to-many | Orders placed for this seller's items |+| Customers | Many-to-many | Customers who have purchased from this seller |+| Shipping Options | One-to-many | Seller-specific shipping methods |+| Stock Locations | One-to-many | Warehouses and fulfillment locations |+| Payout Account | One-to-one | Financial account for receiving payouts |+| Promotions | One-to-many | Seller-created promotions and discounts |+| Price Lists | One-to-many | Custom pricing rules |++## Extension points++The order completion workflow provides hooks for custom logic:++- **`validate`** — Add custom pre-completion validation+- **`beforePaymentAuthorization`** — Run logic before payment is captured+- **`orderGroupCreated`** — React to the completed order groupdiff --git a/apps/docs/v2/developer-guide/api-client.mdx b/apps/docs/v2/developer-guide/api-client.mdxnew file mode 100644index 000000000..3f89c55c0--- /dev/null+++ b/apps/docs/v2/developer-guide/api-client.mdx@@ -0,0 +1,132 @@+---+title: "API Client"+description: "Type-safe client for consuming Mercur APIs."+---++<Snippet file="canary-warning.mdx" />++`@mercurjs/client` provides a type-safe way to interact with your Mercur backend. Every endpoint, request input, and response is fully typed — inferred directly from your backend routes.++## Installation++```bash+npm install @mercurjs/client+```++## Create a client++```typescript+import { createClient } from "@mercurjs/client";+import type { Routes } from "./.mercur/_generated";++export const client = createClient<Routes>({+ baseUrl: "http://localhost:9000",+});+```++<Info>+ The `Routes` type is generated from your backend using `@mercurjs/cli+ codegen`. This gives the client full type safety with zero manual type+ definitions.+</Info>++You can pass default fetch options for authentication or other headers:++```typescript+export const client = createClient<Routes>({+ baseUrl: "http://localhost:9000",+ fetchOptions: {+ credentials: "include",+ headers: {+ Authorization: `Bearer ${token}`,+ },+ },+});+```++## Calling APIs++The client exposes three methods:++```typescript+// GET — fetch data+const { reviews } = await client.vendor.reviews.query({ limit: 10 });++// POST — create or update+const { product } = await client.vendor.products.mutate({+ title: "New Product",+ status: "draft",+});++// DELETE — remove a resource+await client.vendor.reviews.$id.delete({ $id: "rev_123" });+```++Use `$`-prefixed keys for path parameters:++```typescript+const { review } = await client.vendor.reviews.$id.query({+ $id: "rev_123",+});+```++Override fetch options per request when needed:++```typescript+const { reviews } = await client.vendor.reviews.query({+ fetchOptions: {+ signal: abortController.signal,+ },+});+```++## Inferring types++Extract input and output types from any client method using `InferClientInput` and `InferClientOutput`:++```typescript+import type { InferClientInput, InferClientOutput } from "@mercurjs/client";++type ListInput = InferClientInput<typeof client.vendor.reviews.query>;+type ReviewDTO = InferClientOutput<+ typeof client.vendor.reviews.$id.query+>["review"];+```++## React Query++The client returns plain Promises, so it works with any data-fetching library. Here's a typical pattern with TanStack React Query:++```typescript+import { useQuery } from "@tanstack/react-query";+import { client } from "../lib/client";++export function useReviews(+ query?: InferClientInput<typeof client.vendor.reviews.query>,+) {+ const { data, ...rest } = useQuery({+ queryKey: ["reviews", query],+ queryFn: () => client.vendor.reviews.query(query),+ });++ return { ...data, ...rest };+}+```++## Error handling++Failed requests throw a `ClientError`:++```typescript+import { ClientError } from "@mercurjs/client";++try {+ await client.vendor.reviews.$id.query({ $id: "invalid" });+} catch (error) {+ if (error instanceof ClientError) {+ error.message; // "Review not found"+ error.status; // 404+ error.statusText; // "Not Found"+ }+}+```diff --git a/apps/docs/v2/developer-guide/blocks.mdx b/apps/docs/v2/developer-guide/blocks.mdxnew file mode 100644index 000000000..9e739ee04--- /dev/null+++ b/apps/docs/v2/developer-guide/blocks.mdx@@ -0,0 +1,104 @@+---+title: "Blocks"+description: "Self-contained pieces of marketplace functionality that get copied into your project as source code."+---++<Snippet file="canary-warning.mdx" />++Blocks are the unit of distribution in Mercur. Each block is a self-contained feature — a reviews system, a wishlist, product import/export — that you install directly into your project. Unlike packages, blocks are copied as source code. You own every file and can modify anything.++## Installing blocks++```bash+npx @mercurjs/cli add reviews+npx @mercurjs/cli add wishlist product-import-export+```++The CLI fetches the block from the [registry](/v2/developer-guide/registry), resolves dependencies, transforms imports to match your project's path aliases, and copies the files into the right directories.++## What's inside a block++A block can contain any combination of:++| Type | What it is | Example |+|------|-----------|---------|+| **Modules** | Data models and business logic | Review model, wishlist service |+| **Workflows** | Multi-step business processes | Create review, export products |+| **API Routes** | HTTP endpoints | `GET /store/reviews`, `POST /vendor/products/import` |+| **Links** | Relationships between modules | Product-review link, customer-wishlist link |+| **Vendor extensions** | Vendor portal pages and components | Reviews list page, import drawer |+| **Admin extensions** | Admin panel pages and components | Reviews moderation page |++For example, the `reviews` block includes a module (data model + service), workflows (create/update/delete), API routes (store, vendor, admin), links (product-review, seller-review), and UI pages for both the vendor portal and admin panel.++## Block structure++Blocks follow a consistent directory convention:++```+reviews/+├── modules/reviews/ # Data model, service, types+├── workflows/review/ # Steps and workflow definitions+├── links/ # product-review, seller-review, etc.+├── api/+│ ├── admin/reviews/ # Admin API routes+│ ├── vendor/reviews/ # Vendor API routes+│ └── store/reviews/ # Store API routes+├── vendor/pages/reviews/ # Vendor portal UI+└── admin/pages/reviews/ # Admin panel UI+```++Files are placed into your project based on the aliases in your `blocks.json`:++```json blocks.json+{+ "aliases": {+ "modules": "packages/api/src/modules",+ "workflows": "packages/api/src/workflows",+ "api": "packages/api/src/api",+ "links": "packages/api/src/links",+ "vendor": "apps/vendor/src",+ "admin": "apps/admin/src"+ }+}+```++## Post-installation++After adding a block, the CLI shows setup instructions. Typically you need to:++1. **Register the module** in `medusa-config.ts`+2. **Add middlewares** to your `api/middlewares.ts`+3. **Run migrations** with `npx medusa db:generate` and `npx medusa db:migrate`+4. **Regenerate types** with `npx @mercurjs/cli codegen`++## Updating blocks++Check for changes against the registry:++```bash+npx @mercurjs/cli diff reviews+```++If there are updates you want, re-install with the overwrite flag:++```bash+npx @mercurjs/cli add reviews --overwrite+```++Since blocks are source code in your project, you control when and how updates are applied.++## Available blocks++Search the registry to see what's available:++```bash+npx @mercurjs/cli search+npx @mercurjs/cli search --query wishlist+```++View details about a specific block:++```bash+npx @mercurjs/cli view reviews+```diff --git a/apps/docs/v2/developer-guide/cli.mdx b/apps/docs/v2/developer-guide/cli.mdxnew file mode 100644index 000000000..6dcf85743--- /dev/null+++ b/apps/docs/v2/developer-guide/cli.mdx@@ -0,0 +1,174 @@+---+title: "CLI"+description: "Install blocks, scaffold projects, and generate types from the command line."+---++<Snippet file="canary-warning.mdx" />++The Mercur CLI (`@mercurjs/cli`) manages your marketplace project — creating projects, installing blocks, generating types, and checking for updates.++## Installation++```bash+npm install -g @mercurjs/cli+```++## Commands++### create++Scaffold a new Mercur project from a template.++```bash+npx @mercurjs/cli create my-marketplace+```++The CLI will prompt you for database credentials and install dependencies automatically.++| Option | Description |+|--------|-------------|+| `-t, --template <template>` | Template to use (default: `basic`) |+| `--no-deps` | Skip dependency installation |+| `--skip-db` | Skip database configuration |+| `--db-connection-string <string>` | PostgreSQL connection string |++### init++Initialize an existing project by creating a `blocks.json` configuration file.++```bash+npx @mercurjs/cli init+```++This sets up path aliases so the CLI knows where to place blocks in your project:++```json+{+ "aliases": {+ "modules": "packages/api/src/modules",+ "workflows": "packages/api/src/workflows",+ "api": "packages/api/src/api",+ "links": "packages/api/src/links",+ "vendor": "apps/vendor/src",+ "admin": "apps/admin/src"+ }+}+```++| Option | Description |+|--------|-------------|+| `-d, --defaults` | Use default paths without prompting |+| `-s, --silent` | Suppress output |++### add++Install blocks from the registry into your project.++```bash+npx @mercurjs/cli add wishlist+npx @mercurjs/cli add product-review order-tracking+```++Blocks are copied directly into your project as source code. The CLI resolves dependencies, transforms imports to match your path aliases, and installs required packages.++| Option | Description |+|--------|-------------|+| `-o, --overwrite` | Overwrite existing files |+| `-y, --yes` | Skip confirmation |+| `-s, --silent` | Suppress output |++### search++Find available blocks in the registry.++```bash+npx @mercurjs/cli search --query wishlist+```++| Option | Description |+|--------|-------------|+| `-q, --query <query>` | Search by name or description |+| `-r, --registry <registry>` | Registry to search (default: `@mercurjs`) |++### view++Display detailed information about a block.++```bash+npx @mercurjs/cli view wishlist+```++### diff++Compare local blocks against registry versions to check for updates.++```bash+npx @mercurjs/cli diff wishlist+```++If there are changes you want, update with:++```bash+npx @mercurjs/cli add wishlist --overwrite+```++### codegen++Generate TypeScript types from your API routes. Used by the [API Client](/v2/developer-guide/api-client) for type-safe requests.++```bash+npx @mercurjs/cli codegen+```++| Option | Description |+|--------|-------------|+| `-w, --watch` | Watch for changes and regenerate automatically |++### registry:build++Build a custom registry from a `registry.json` file.++```bash+npx @mercurjs/cli build+```++| Option | Description |+|--------|-------------|+| `-o, --output <path>` | Output directory (default: `./r`) |+| `-v, --verbose` | Show detailed output |++### info++Display project configuration and diagnostics.++```bash+npx @mercurjs/cli info+```++### telemetry++Control anonymous usage data collection.++```bash+npx @mercurjs/cli telemetry --disable+npx @mercurjs/cli telemetry --enable+```++## Custom registries++Add custom block registries to your `blocks.json`:++```json+{+ "registries": {+ "@mercurjs": "https://registry.mercurjs.com/{name}",+ "@my-registry": "https://my-registry.com/blocks/{name}.json"+ }+}+```++Use `{name}` as a placeholder for block names. Reference custom registries with the `-r` flag:++```bash+npx @mercurjs/cli search --query review --registry @my-registry+```diff --git a/apps/docs/v2/developer-guide/extending-panels.mdx b/apps/docs/v2/developer-guide/extending-panels.mdxnew file mode 100644index 000000000..da7d5d55c--- /dev/null+++ b/apps/docs/v2/developer-guide/extending-panels.mdx@@ -0,0 +1,225 @@+---+title: "Extending Panels"+description: "Add pages, customize navigation, branding, and replace components in the admin and vendor panels."+---++<Snippet file="canary-warning.mdx" />++Both the admin panel and vendor portal use the same SDK (`@mercurjs/dashboard-sdk`). Customization is file-based and convention-driven — you add pages by creating files, configure navigation through exports, and override components through config.++## Setup++Every panel project needs two files at its root:++### Vite config++```typescript vite.config.ts+import { defineConfig } from 'vite'+import react from '@vitejs/plugin-react'+import { dashboardPlugin } from '@mercurjs/dashboard-sdk'++export default defineConfig({+ plugins: [react(), dashboardPlugin()],+})+```++### Mercur config++```typescript mercur.config.ts+import { defineConfig } from '@mercurjs/dashboard-sdk'++export default defineConfig({+ name: 'My Marketplace',+ logo: 'https://example.com/logo.svg',+})+```++Available options:++| Option | Type | Description |+|--------|------|-------------|+| `name` | `string` | Application name shown in the sidebar |+| `logo` | `string` | URL to a logo image |+| `components` | `object` | Component overrides (see [Replacing components](#replacing-components)) |+| `i18n` | `object` | Internationalization settings |+| `backendUrl` | `string` | Medusa backend URL (default: `http://localhost:9000`) |++## Adding pages++Create a `page.tsx` file inside `src/pages/` and export a default React component. The route is determined by the file path.++```tsx src/pages/reviews/page.tsx+import { Star } from "@medusajs/icons"+import type { RouteConfig } from "@mercurjs/dashboard-sdk"++export const config: RouteConfig = {+ label: "Reviews",+ icon: Star,+ rank: 10,+}++export default function ReviewsPage() {+ return <div>Reviews</div>+}+```++This creates a `/reviews` route and adds a "Reviews" item to the sidebar.++### The `config` export++The `config` export controls how the page appears in navigation:++| Property | Type | Description |+|----------|------|-------------|+| `label` | `string` | **Required.** Text shown in the sidebar menu |+| `icon` | `ComponentType` | Icon component (e.g. from `@medusajs/icons`) |+| `rank` | `number` | Sort order — lower numbers appear first |+| `nested` | `string` | Parent path for nested menu items |+| `translationNs` | `string` | i18n namespace for the label |+| `public` | `boolean` | If `true`, the route is accessible without authentication |++Pages without a `config` export are still routed but won't appear in the sidebar.++## Routing conventions++File paths map to URL routes automatically:++| File path | Route | Description |+|-----------|-------|-------------|+| `src/pages/page.tsx` | `/` | Root page |+| `src/pages/reviews/page.tsx` | `/reviews` | Static segment |+| `src/pages/reviews/[id]/page.tsx` | `/reviews/:id` | Dynamic segment |+| `src/pages/reviews/[[id]]/page.tsx` | `/reviews/:id?` | Optional dynamic segment |+| `src/pages/search/[*].tsx` | `/search/*` | Catch-all |+| `src/pages/(settings)/page.tsx` | Route grouping | Groups routes without adding a URL segment |+| `src/pages/dashboard/@sidebar/page.tsx` | Parallel route | Renders alongside parent |++## Navigation++Sidebar items are generated from pages that export a `config` with a `label`.++### Ordering++Use `rank` to control the order. Lower values appear higher:++```tsx+// src/pages/orders/page.tsx+export const config: RouteConfig = {+ label: "Orders",+ icon: ShoppingCart,+ rank: 1,+}++// src/pages/products/page.tsx+export const config: RouteConfig = {+ label: "Products",+ icon: Tag,+ rank: 2,+}+```++### Nested menus++Use `nested` to group pages under a parent:++```tsx src/pages/settings/shipping/page.tsx+export const config: RouteConfig = {+ label: "Shipping",+ nested: "/settings",+}+```++This places "Shipping" as a child item under `/settings` in the sidebar.++## Branding++Set `name` and `logo` in `mercur.config.ts` to customize the sidebar header:++```typescript mercur.config.ts+import { defineConfig } from '@mercurjs/dashboard-sdk'++export default defineConfig({+ name: 'WeTest',+ logo: 'https://ui-avatars.com/api/?name=WeTest&background=18181B&color=fff&size=200&bold=true&format=svg',+})+```++## Replacing components++Override built-in layout components in `mercur.config.ts`:++```typescript mercur.config.ts+import { defineConfig } from '@mercurjs/dashboard-sdk'++export default defineConfig({+ name: 'My Marketplace',+ components: {+ MainSidebar: 'components/custom-sidebar',+ SettingsSidebar: 'components/custom-settings-sidebar',+ TopbarActions: 'components/custom-topbar-actions',+ },+})+```++Paths are relative to `src/`. Each file must have a default export:++```tsx src/components/custom-topbar-actions.tsx+export default function CustomTopbarActions() {+ return (+ <div>+ <button>Help</button>+ <button>Notifications</button>+ </div>+ )+}+```++| Component | Description |+|-----------|-------------|+| `MainSidebar` | Primary navigation sidebar |+| `SettingsSidebar` | Settings section sidebar |+| `TopbarActions` | Action buttons in the top bar |++## Internationalization++**1. Create translation resources**++```typescript src/i18n/index.ts+export default {+ en: {+ reviews: {+ title: "Reviews",+ description: "Manage product reviews",+ },+ },+ de: {+ reviews: {+ title: "Bewertungen",+ description: "Produktbewertungen verwalten",+ },+ },+}+```++**2. Reference the namespace in your page config**++```tsx src/pages/reviews/page.tsx+export const config: RouteConfig = {+ label: "reviews.title",+ icon: Star,+ translationNs: "reviews",+}+```++**3. Set the default language**++```typescript mercur.config.ts+import { defineConfig } from '@mercurjs/dashboard-sdk'++export default defineConfig({+ name: 'My Marketplace',+ i18n: {+ defaultLanguage: 'en',+ },+})+```diff --git a/apps/docs/v2/developer-guide/overview.mdx b/apps/docs/v2/developer-guide/overview.mdxnew file mode 100644index 000000000..915f5f9c8--- /dev/null+++ b/apps/docs/v2/developer-guide/overview.mdx@@ -0,0 +1,173 @@+---+title: "Overview"+description: "How Mercur is built — architecture, technology stack, and how the pieces fit together."+---++<Snippet file="canary-warning.mdx" />++Mercur is a marketplace platform built on top of [MedusaJS](https://medusajs.com), an open-source headless commerce framework. Rather than being a standalone application, Mercur extends Medusa with marketplace-specific logic — sellers, commissions, order splitting, payouts — while Medusa handles the foundational commerce layer.++This page explains how the system is structured and how its components interact.++## Architecture++Mercur follows a layered architecture where each layer has a distinct responsibility:++```mermaid+graph TD+ subgraph Frontend Layer+ A[Admin Panel]+ B[Vendor Portal]+ C[Storefront]+ end++ subgraph API Layer+ D["/admin/*"]+ E["/vendor/*"]+ F["/store/*"]+ end++ subgraph Marketplace Layer - Mercur+ G[Modules · Workflows · Links · Subscribers · Events]+ end++ subgraph Commerce Layer - Medusa+ H[Products · Orders · Carts · Payments · Fulfillment]+ end++ I[(PostgreSQL)]++ A --> D+ B --> E+ C --> F+ D --> G+ E --> G+ F --> G+ G --> H+ H --> I+```++### Commerce layer++Medusa provides the core commerce engine — products, pricing, carts, orders, payments, fulfillment, promotions, and inventory. Mercur does not replace any of this. Instead, it builds on top using Medusa's extension model: custom modules, links, workflows, and API routes.++### Marketplace layer++This is where Mercur's code lives. It introduces three custom modules — **Seller**, **Commission**, and **Payout** — along with workflows that coordinate marketplace-specific operations like order splitting and commission calculation. Links connect these modules to Medusa's core entities (products, orders, customers) without modifying the original models.++### API layer++Mercur exposes three sets of HTTP endpoints:++| API | Path | Purpose |+|-----|------|---------|+| **Admin** | `/admin/*` | Platform administration — manage sellers, configure commission rates, view payouts |+| **Vendor** | `/vendor/*` | Seller operations — manage products, orders, fulfillment, shipping, inventory, payouts |+| **Store** | `/store/*` | Storefront — browse sellers, manage carts, checkout with order splitting |++Each API route is composed of a request handler, middleware, query configuration, and Zod validators.++### Frontend layer++Three interfaces consume the APIs:++- **Admin Panel** — Built with React and Medusa UI components. Operators use it to manage the marketplace: approve sellers, set commission rates, handle disputes.+- **Vendor Portal** — A React application for sellers to manage their products, orders, fulfillment, and payouts. Uses file-based routing via the Dashboard SDK.+- **Storefront** — Customer-facing application. Can be built with any frontend technology that consumes the Store API.++## Technology stack++| Layer | Technology |+|-------|-----------|+| Runtime | Node.js 20+, TypeScript |+| Framework | MedusaJS v2 |+| Database | PostgreSQL |+| Frontend | React 18, React Router, Vite |+| Data fetching | TanStack React Query |+| UI components | Medusa UI, Radix UI |+| Form handling | React Hook Form, Zod |+| Tables | TanStack React Table |+| Build | Turborepo (monorepo), Bun (package manager), tsup |+| Internationalization | i18next |++## Core plugin++The core plugin (`@mercurjs/core-plugin`) is the main package that contains all marketplace logic. It's structured as a standard MedusaJS plugin:++```+core-plugin/src/+├── modules/ # Data models and services+│ ├── seller/ # Seller registration, profiles, order groups+│ ├── commission/ # Commission rates, rules, calculation+│ └── payout/ # Payout accounts, balances, transactions+├── links/ # Relationships between modules+├── workflows/ # Multi-step business processes+│ ├── seller/ # Seller CRUD workflows+│ ├── cart/ # Cart completion with order splitting+│ ├── commission/ # Commission rate and line management+│ ├── payout/ # Payout processing and crediting+│ ├── order-group/ # Order group operations+│ ├── promotion/ # Seller promotion workflows+│ ├── price-list/ # Price list operations+│ └── ... # Shipping, inventory, campaigns, etc.+├── api/ # HTTP route handlers+│ ├── admin/ # Admin API routes+│ ├── vendor/ # Vendor API routes+│ ├── store/ # Store API routes+│ └── hooks/ # Webhook handlers+├── subscribers/ # Event listeners+├── providers/ # Third-party provider integrations+└── jobs/ # Scheduled background tasks+```++### Modules++Modules encapsulate data models and business logic for a specific domain. Each module is self-contained with its own models, service, migrations, and repositories. Modules don't reference each other directly — they communicate through links and workflows.++### Links++Links define relationships between Mercur modules and Medusa core entities. For example, the `product-seller-link` connects a Medusa `Product` to a Mercur `Seller` without modifying either model. There are 17 links that wire the marketplace layer into the commerce layer — connecting sellers to products, orders, customers, shipping options, inventory, promotions, and more.++### Workflows++Workflows orchestrate multi-step operations that span multiple modules. They support compensation (automatic rollback on failure) and hooks (extension points for custom logic). The most significant workflow is `completeCartWithSplitOrdersWorkflow`, which handles the entire checkout process — validating items, splitting by seller, creating orders, allocating payments, and calculating commissions.++### Subscribers and events++Subscribers listen for events emitted by workflows and trigger asynchronous side effects — sending notifications, updating external systems, or processing webhooks. This keeps the core workflows focused on their primary job while allowing the system to react to changes.++## How data flows++A typical customer purchase flows through the system like this:++1. **Customer adds items** from multiple sellers to their cart (Store API)+2. **Cart completion** triggers the split order workflow (Marketplace Layer)+3. Items are **grouped by seller**, and a separate order is created for each (Commerce + Marketplace Layer)+4. **Commission lines** are calculated for each order based on matching rates (Commission Module)+5. **Payment is split** proportionally across seller orders (Commerce Layer)+6. Each seller's order is **credited to their payout account** after commission deduction (Payout Module)+7. **Events are emitted** — triggering notifications, webhook calls, and other side effects (Subscribers)+8. Sellers **manage their orders** through the Vendor Portal (Vendor API)+9. The admin **monitors everything** through the Admin Panel (Admin API)++## Block-based distribution++Mercur uses a **block-based architecture** for distribution. Instead of installing an opaque package, the CLI copies source code directly into your project. Each block is a self-contained piece of functionality — a module, a workflow, an API route, or a UI extension.++This means:+- You own every line of code in your project+- You can modify any block to fit your business requirements+- There are no hidden abstractions or version conflicts+- Updates are explicit — you diff and apply changes from the registry++The CLI (`@mercurjs/cli`) manages this process: scaffolding projects, installing blocks, searching the registry, and comparing local changes against upstream versions.++## Design principles++**Modular over monolithic** — Each marketplace feature is a separate module that can be installed, modified, or replaced independently. You don't need to use all of Mercur to benefit from it.++**Explicit over implicit** — Relationships between modules are defined through links, not hidden in service code. Workflows make multi-step operations visible and debuggable. API routes are file-based and predictable.++**Extensible over configurable** — Rather than exposing hundreds of configuration options, Mercur provides extension points. Workflows have hooks. Providers are pluggable. Models can be extended through Medusa's framework. When configuration isn't enough, you modify the source code directly.++**Commerce-aware** — Mercur doesn't reinvent commerce. It delegates products, pricing, orders, payments, and fulfillment to Medusa, and focuses exclusively on the marketplace logic that multi-vendor systems need.diff --git a/apps/docs/v2/developer-guide/registry.mdx b/apps/docs/v2/developer-guide/registry.mdxnew file mode 100644index 000000000..6829017bf--- /dev/null+++ b/apps/docs/v2/developer-guide/registry.mdx@@ -0,0 +1,167 @@+---+title: "Registry"+description: "Create, build, and host your own block registry."+---++<Snippet file="canary-warning.mdx" />++A registry is a collection of blocks that can be installed into any Mercur project using the CLI. The official Mercur registry (`@mercurjs`) provides all the built-in marketplace blocks. You can also create and host your own.++## How it works++A registry is a set of JSON files — one per block — served over HTTP. When you run `npx @mercurjs/cli add`, the CLI fetches the block's JSON, resolves its dependencies, and copies the source files into your project.++```+registry/+├── registry.json # Registry definition with all blocks+├── src/+│ └── my-block/ # Block source files+│ ├── modules/+│ ├── workflows/+│ └── api/+└── r/ # Built output (generated)+ ├── registry.json+ └── my-block.json # Block JSON with embedded file contents+```++## Creating a registry++Scaffold a new registry project:++```bash+npx @mercurjs/cli create my-registry --template registry+```++This creates a project with a `registry.json`, a `blocks.json` for path aliases, and a `src/` directory for your block source code.++## registry.json++The `registry.json` file defines your registry and all its blocks:++```json registry.json+{+ "$schema": "https://registry.mercurjs.com/registry.json",+ "name": "@my-org",+ "homepage": "https://my-org.com",+ "items": [+ {+ "name": "reviews",+ "description": "Product and seller reviews with ratings.",+ "dependencies": [],+ "registryDependencies": [],+ "docs": "## Configuration\n\nAdd the review module to your `medusa-config.ts`...",+ "files": [+ {+ "path": "reviews/modules/reviews/index.ts",+ "type": "registry:module"+ },+ {+ "path": "reviews/workflows/review/workflows/create-review.ts",+ "type": "registry:workflow"+ },+ {+ "path": "reviews/api/store/reviews/route.ts",+ "type": "registry:api"+ }+ ],+ "categories": ["module", "workflow", "api"]+ }+ ]+}+```++### Block properties++| Property | Description |+|----------|-------------|+| `name` | Block identifier used in `npx @mercurjs/cli add` |+| `description` | Short description shown in search results |+| `dependencies` | NPM packages to install |+| `registryDependencies` | Other blocks this block depends on (e.g. `@mercurjs/wishlist`) |+| `docs` | Markdown shown to the user after installation |+| `files` | List of source files with their paths and types |+| `categories` | Tags for search and filtering |++### File types++Each file in a block has a `type` that determines where it gets placed in the target project:++| Type | Target alias |+|------|-------------|+| `registry:module` | `modules` |+| `registry:workflow` | `workflows` |+| `registry:api` | `api` |+| `registry:link` | `links` |+| `registry:vendor` | `vendor` |+| `registry:admin` | `admin` |+| `registry:lib` | `lib` |++These map to the aliases defined in the consumer's `blocks.json`.++## Building++Build your registry into distributable JSON files:++```bash+npx @mercurjs/cli build+```++This reads `registry.json`, resolves all imports for each block, embeds the file contents, and outputs one JSON file per block to the `r/` directory.++| Option | Description |+|--------|-------------|+| `-o, --output <path>` | Output directory (default: `./r`) |+| `-v, --verbose` | Show detailed output |++The build step also automatically resolves NPM dependencies from your source imports — you don't need to list every transitive dependency manually.++## Hosting++Serve the built `r/` directory over HTTP. Any static hosting works — GitHub Pages, Vercel, Netlify, S3, or your own server. The only requirement is that `{name}.json` files are accessible at a public URL.++## Using custom registries++Add your registry to `blocks.json` in any Mercur project:++```json blocks.json+{+ "registries": {+ "@my-org": "https://my-registry.com/r/{name}.json"+ }+}+```++Use `{name}` as a placeholder for block names. Then install blocks from it:++```bash+npx @mercurjs/cli add @my-org/reviews+```++### Authentication++For private registries, you can use headers with environment variables:++```json blocks.json+{+ "registries": {+ "@my-org": {+ "url": "https://api.my-org.com/r/{name}.json",+ "headers": {+ "Authorization": "Bearer ${REGISTRY_TOKEN}"+ }+ }+ }+}+```++## Dependencies between blocks++Blocks can depend on other blocks using `registryDependencies`. When a user installs your block, the CLI automatically resolves and installs all dependencies in the correct order.++```json+{+ "name": "order-tracking",+ "registryDependencies": ["@mercurjs/wishlist"],+ "files": [...]+}+```diff --git a/apps/docs/v2/getting-started/concepts.mdx b/apps/docs/v2/getting-started/concepts.mdxnew file mode 100644index 000000000..3e34bb5d5--- /dev/null+++ b/apps/docs/v2/getting-started/concepts.mdx@@ -0,0 +1,66 @@+---+title: "Concepts"+description: "Core concepts behind Mercur — from the Medusa foundation to blocks, panels, and the registry."+---++<Snippet file="canary-warning.mdx" />++Mercur is built on a small set of concepts. Familiarity with these establishes a common language when working with the platform.++## Medusa++[MedusaJS](https://medusajs.com) is the open-source commerce framework that powers Mercur's foundation. It handles products, pricing, carts, orders, payments, fulfillment, and promotions. Mercur does not replace any of this — it extends Medusa with marketplace-specific logic using Medusa's own extension model.++## Admin Panel++The admin panel is a React application for **marketplace operators**. It provides a dashboard to manage sellers, configure commission rates, moderate product requests, handle disputes, and monitor the overall marketplace. It is built with [Medusa UI](https://docs.medusajs.com/ui) components and can be extended with custom pages and components through the [Dashboard SDK](#dashboard-sdk).++## Vendor Portal++The vendor portal is a React application for **sellers**. Sellers use it to manage their products, process orders, configure shipping, track payouts, and handle returns. Like the admin panel, it is built on the Dashboard SDK and can be fully customized.++## Storefront++The storefront is the **customer-facing** application. It can be built with any frontend technology that consumes the Store API — Next.js, Remix, or any other framework. Mercur provides a ready-made storefront template to start from.++## API Routes++Mercur exposes three sets of HTTP endpoints:++- **Admin API** (`/admin/*`) — Platform administration+- **Vendor API** (`/vendor/*`) — Seller operations+- **Store API** (`/store/*`) — Customer-facing storefront++Each route is composed of a handler, middleware, query configuration, and validators.++## Modules++Modules encapsulate data models and business logic for a specific domain. Each module is self-contained with its own models, service, and migrations. Mercur's marketplace modules include Seller, Commission, Payout, Marketplace, Requests, Reviews, and others. They communicate through [Links](#links) and [Workflows](#workflows), never directly.++## Links++Links define relationships between Mercur modules and Medusa core entities without modifying either side. For example, a link connects a Medusa Product to a Mercur Seller — this is how the system knows which seller owns which product.++## Workflows++Workflows coordinate multi-step operations across modules. They support compensation (automatic rollback on failure) and hooks (extension points for custom logic). For example, the checkout workflow splits a cart by seller, creates separate orders, allocates payments, and calculates commissions — all as a single atomic operation.++## Blocks++Blocks are the unit of distribution in Mercur. Each block is a self-contained piece of functionality — a module, a workflow, an API route, a link, or a UI extension. When you install a block, the CLI copies its source code directly into your project. You own every line and can modify anything.++## Registry++A registry is a collection of blocks available for installation. The official Mercur registry (`@mercurjs`) provides all marketplace blocks. You can also create and host [custom registries](/v2/developer-guide/cli#custom-registries) for your own blocks.++## CLI++The [Mercur CLI](/v2/developer-guide/cli) (`@mercurjs/cli`) manages your project — scaffolding from templates, installing blocks, searching registries, generating types, and diffing local changes against upstream versions.++## Dashboard SDK++The [Dashboard SDK](/v2/developer-guide/extending-panels) (`@mercurjs/dashboard-sdk`) is a Vite plugin shared by the admin panel and vendor portal. It provides file-based routing, automatic navigation generation, component overrides, and i18n support.++## API Client++The [API Client](/v2/developer-guide/api-client) (`@mercurjs/client`) provides type-safe access to all Mercur API endpoints. Types are generated from your actual API routes using `npx @mercurjs/cli codegen`, so requests and responses are always in sync with your backend.diff --git a/apps/docs/v2/getting-started/installation.mdx b/apps/docs/v2/getting-started/installation.mdxnew file mode 100644index 000000000..d82002f44--- /dev/null+++ b/apps/docs/v2/getting-started/installation.mdx@@ -0,0 +1,72 @@+---+title: "Installation"+description: "Install Mercur and set up your marketplace project."+---++<Snippet file="canary-warning.mdx" />++## Requirements++- [Node.js v20+](https://nodejs.org/en/download) (LTS version)+- [Git](https://git-scm.com/downloads)+- [PostgreSQL](https://www.postgresql.org/download/) installed and running++## Create a new project++Use the Mercur CLI to scaffold a new project:++```bash+npx @mercurjs/cli create my-marketplace+```++The CLI will guide you through template selection and database configuration.++## Initialize an existing project++If you have an existing Medusa project, initialize Mercur in it:++```bash+npx @mercurjs/cli init+```++This creates a `blocks.json` configuration file in your project.++## Add blocks++Install blocks from the registry:++```bash+npx @mercurjs/cli add <block-name>+```++Browse available blocks:++```bash+npx @mercurjs/cli search+```++## Run database migrations++After adding blocks that include modules:++```bash+npx medusa db:generate <module1> <module2> ...+npx medusa db:migrate+```++## Start the development server++```bash+npx medusa develop+```++## Default credentials++If you used the CLI to create a new project with seed data:++**Vendor:**++```+email: [email protected]+password: supersecret+```diff --git a/apps/docs/v2/getting-started/introduction.mdx b/apps/docs/v2/getting-started/introduction.mdxnew file mode 100644index 000000000..1f84f83ef--- /dev/null+++ b/apps/docs/v2/getting-started/introduction.mdx@@ -0,0 +1,34 @@+---+title: "Introduction"+description: "Mercur is an open-source marketplace platform built on MedusaJS with a block-based architecture."+---++<Snippet file="canary-warning.mdx" />++Mercur is an open-core **marketplace platform** built on top of the [Medusa Framework](https://medusajs.com). It follows a block-based architecture — install only the modules, workflows, API routes, and UI extensions you need directly into your project. No black-box dependencies, full code ownership.++## What is Mercur++Medusa provides the underlying commerce engine — products, pricing, carts, orders, fulfillment, and events — while Mercur builds the marketplace domain layer on top of it.++On top of Medusa's core, Mercur introduces marketplace entities and workflows such as sellers, onboarding, product requests, commissions, reviews, return escalations, order splitting, vendor payouts, and dedicated Admin, Vendor, and Storefront APIs.++It comes with three optional interfaces:++- an **Admin Panel** for marketplace operators+- a **Vendor Portal** for seller teams+- a **Storefront** ready for marketplace scenarios++## Why Mercur++### Built on a modern stack++Mercur runs on a modern TypeScript backend powered by the Medusa framework, giving you a proven foundation for products, carts, orders, promotions, and payments. It integrates with technologies like Resend (notifications), Algolia (search), and Stripe Connect (payouts) — all replaceable when needed.++### Block-based architecture++Unlike traditional plugins, Mercur uses a **block-based** approach. Blocks are copied directly into your project via the CLI, giving you full ownership and the ability to modify any piece of code without forking.++### Full extensibility and ownership++Mercur is fully open-core and MIT-licensed. There are no transaction fees, no commercial lock-in, and no constraints on how your marketplace must behave. You own the entire codebase and can host it anywhere.diff --git a/apps/docs/v2/welcome.mdx b/apps/docs/v2/welcome.mdxnew file mode 100644index 000000000..3ef1cf2ec--- /dev/null+++ b/apps/docs/v2/welcome.mdx@@ -0,0 +1,52 @@+---+title: "Build with Mercur"+sidebarTitle: "Introduction"+description: "Open source marketplace platform with full code ownership."+mode: "custom"+---++<div className="max-w-5xl mx-auto px-6 py-16">+ <Snippet file="canary-warning.mdx" />++ <div className="text-center mt-12 mb-16">+ <h1 className="text-5xl font-bold tracking-tight mb-4">Build with Mercur</h1>+ <p className="text-xl text-gray-500 dark:text-gray-400 max-w-2xl mx-auto">+ Open source marketplace platform with a modular, block-based architecture. Install only the pieces you need — full code ownership, no black-box dependencies.+ </p>+ <div className="mt-8 flex gap-4 justify-center">+ <a href="/v2/getting-started/introduction" className="inline-flex items-center px-5 py-2.5 rounded-lg bg-black dark:bg-white text-white dark:text-black font-medium text-sm hover:opacity-90 transition-opacity no-underline">+ Get Started+ </a>+ <a href="/v2/getting-started/introduction" className="inline-flex items-center px-5 py-2.5 rounded-lg border border-gray-200 dark:border-gray-700 font-medium text-sm hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors no-underline">+ Documentation+ </a>+ </div>+ </div>++ <div className="mb-16">+ <h2 className="text-2xl font-semibold mb-6">Resources</h2>+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">+ <a href="/v2/getting-started/introduction" className="block p-5 rounded-xl border border-gray-200 dark:border-gray-800 hover:border-gray-300 dark:hover:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-900 transition-all no-underline">+ <div className="flex items-center gap-3 mb-2">+ <span className="text-lg">📖</span>+ <h3 className="font-semibold text-base m-0">Documentation</h3>+ </div>+ <p className="text-sm text-gray-500 dark:text-gray-400 m-0">Guides on setup, configuration, and extending your marketplace.</p>+ </a>+ <a href="https://github.com/mercurjs/mercur" className="block p-5 rounded-xl border border-gray-200 dark:border-gray-800 hover:border-gray-300 dark:hover:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-900 transition-all no-underline">+ <div className="flex items-center gap-3 mb-2">+ <span className="text-lg">🧩</span>+ <h3 className="font-semibold text-base m-0">GitHub</h3>+ </div>+ <p className="text-sm text-gray-500 dark:text-gray-400 m-0">Source code, examples, and community contributions.</p>+ </a>+ <a href="https://discord.gg/hnZBzc4NJU" className="block p-5 rounded-xl border border-gray-200 dark:border-gray-800 hover:border-gray-300 dark:hover:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-900 transition-all no-underline">+ <div className="flex items-center gap-3 mb-2">+ <span className="text-lg">💬</span>+ <h3 className="font-semibold text-base m-0">Discord</h3>+ </div>+ <p className="text-sm text-gray-500 dark:text-gray-400 m-0">Join the community for help, discussions, and updates.</p>+ </a>+ </div>+ </div>+</div>