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.

Automatically include Spree documentation for Agents during `create-s… (#13808)

Damian Legawiecad3a74571ed7
diff --git a/.github/workflows/docs-package.yml b/.github/workflows/docs-package.yml
new file mode 100644
index 0000000000..d9b077b3bf
--- /dev/null
+++ b/.github/workflows/docs-package.yml
@@ -0,0 +1,93 @@
+name: Docs Package
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - "docs/developer/**"
+ - "docs/api-reference/**"
+ - "docs/integrations/**"
+ - "packages/docs/**"
+ pull_request:
+ paths:
+ - "docs/developer/**"
+ - "docs/api-reference/**"
+ - "docs/integrations/**"
+ - "packages/docs/**"
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: true
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ name: "Build"
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: pnpm/action-setup@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ cache: pnpm
+
+ - run: pnpm install --frozen-lockfile
+
+ - run: pnpm --filter @spree/docs build
+
+ - name: Verify output
+ run: |
+ FILE_COUNT=$(find packages/docs/dist -name "*.md" | wc -l)
+ echo "Built $FILE_COUNT markdown files"
+ if [ "$FILE_COUNT" -lt 100 ]; then
+ echo "Expected at least 100 files, got $FILE_COUNT"
+ exit 1
+ fi
+
+ release:
+ name: "Release"
+ needs: build
+ if: github.ref == 'refs/heads/main' && github.event_name == 'push'
+ runs-on: ubuntu-latest
+ permissions:
+ contents: write
+ id-token: write
+ defaults:
+ run:
+ working-directory: packages/docs
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: pnpm/action-setup@v4
+
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 20
+ cache: pnpm
+ registry-url: https://registry.npmjs.org
+
+ - run: pnpm install --frozen-lockfile
+ working-directory: .
+
+ - name: Upgrade npm for Trusted Publishing support
+ run: npm install -g npm@latest
+ working-directory: .
+
+ - name: Auto-bump patch version
+ run: |
+ CURRENT=$(node -p "require('./package.json').version")
+ PUBLISHED=$(npm view @spree/docs version 2>/dev/null || echo "0.0.0")
+ if [ "$CURRENT" = "$PUBLISHED" ]; then
+ npm version patch --no-git-tag-version
+ echo "Bumped from $CURRENT to $(node -p "require('./package.json').version")"
+ else
+ echo "Current version $CURRENT not yet published, using as-is"
+ fi
+
+ - name: Build and Publish
+ run: node scripts/build.js && npm publish --provenance --access public
diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml
index 4b03e8fbf1..71d0e4f302 100644
--- a/.github/workflows/packages.yml
+++ b/.github/workflows/packages.yml
@@ -5,12 +5,18 @@ on:
branches: [main]
paths:
- "packages/**"
+ - "docs/developer/**"
+ - "docs/api-reference/**"
+ - "docs/integrations/**"
- "pnpm-lock.yaml"
- "turbo.json"
- ".github/workflows/packages.yml"
pull_request:
paths:
- "packages/**"
+ - "docs/developer/**"
+ - "docs/api-reference/**"
+ - "docs/integrations/**"
- "pnpm-lock.yaml"
- "turbo.json"
- ".github/workflows/packages.yml"
diff --git a/docs/developer/storefront/blocks.mdx b/docs/developer/storefront/rails/blocks.mdx
similarity index 96%
rename from docs/developer/storefront/blocks.mdx
rename to docs/developer/storefront/rails/blocks.mdx
index 8a7b17de0c..5f4e5f248b 100644
--- a/docs/developer/storefront/blocks.mdx
+++ b/docs/developer/storefront/rails/blocks.mdx
@@ -3,7 +3,7 @@ title: "Blocks"
description: "Learn how to utilize blocks to build your Spree Storefront"
---
-Blocks are the lowest level of components in Spree Storefront. They are nested inside [sections](/developer/storefront/sections) and represent individual content elements like headings, text, buttons, and images.
+Blocks are the lowest level of components in Spree Storefront. They are nested inside [sections](/developer/storefront/rails/sections) and represent individual content elements like headings, text, buttons, and images.
## How Blocks Work
@@ -280,6 +280,6 @@ block.asset.attached?
## Related Documentation
-- [Sections](/developer/storefront/sections) - Parent containers for blocks
-- [Links](/developer/storefront/links) - Adding links to blocks
+- [Sections](/developer/storefront/rails/sections) - Parent containers for blocks
+- [Links](/developer/storefront/rails/links) - Adding links to blocks
- [Media](/developer/core-concepts/media) - Working with images
diff --git a/docs/developer/storefront/custom-css.mdx b/docs/developer/storefront/rails/custom-css.mdx
similarity index 97%
rename from docs/developer/storefront/custom-css.mdx
rename to docs/developer/storefront/rails/custom-css.mdx
index 640feaef22..dbc825a768 100644
--- a/docs/developer/storefront/custom-css.mdx
+++ b/docs/developer/storefront/rails/custom-css.mdx
@@ -257,6 +257,6 @@ Use them in your templates:
## Related Documentation
-- [Themes](/developer/storefront/themes) - Theme settings and colors
-- [Custom JavaScript](/developer/storefront/custom-javascript) - Adding interactivity
+- [Themes](/developer/storefront/rails/themes) - Theme settings and colors
+- [Custom JavaScript](/developer/storefront/rails/custom-javascript) - Adding interactivity
- [Tailwind CSS 4 Documentation](https://tailwindcss.com/docs) - Official Tailwind docs
diff --git a/docs/developer/storefront/custom-javascript.mdx b/docs/developer/storefront/rails/custom-javascript.mdx
similarity index 96%
rename from docs/developer/storefront/custom-javascript.mdx
rename to docs/developer/storefront/rails/custom-javascript.mdx
index a5118f1f5d..f733d3efd2 100644
--- a/docs/developer/storefront/custom-javascript.mdx
+++ b/docs/developer/storefront/rails/custom-javascript.mdx
@@ -166,6 +166,6 @@ document.addEventListener('turbo:frame-load', (event) => {
## Related Documentation
-- [Custom CSS](/developer/storefront/custom-css) - Styling your storefront
-- [Sections](/developer/storefront/sections) - Creating custom sections
-- [Blocks](/developer/storefront/blocks) - Creating custom blocks
\ No newline at end of file
+- [Custom CSS](/developer/storefront/rails/custom-css) - Styling your storefront
+- [Sections](/developer/storefront/rails/sections) - Creating custom sections
+- [Blocks](/developer/storefront/rails/blocks) - Creating custom blocks
\ No newline at end of file
diff --git a/docs/developer/storefront/helper-methods.mdx b/docs/developer/storefront/rails/helper-methods.mdx
similarity index 98%
rename from docs/developer/storefront/helper-methods.mdx
rename to docs/developer/storefront/rails/helper-methods.mdx
index 9cc6180993..ef02567a83 100644
--- a/docs/developer/storefront/helper-methods.mdx
+++ b/docs/developer/storefront/rails/helper-methods.mdx
@@ -330,6 +330,6 @@ These helpers are used for Page Builder preview functionality:
## Related Documentation
-- [Sections](/developer/storefront/sections) - Section rendering and customization
-- [Blocks](/developer/storefront/blocks) - Block rendering
+- [Sections](/developer/storefront/rails/sections) - Section rendering and customization
+- [Blocks](/developer/storefront/rails/blocks) - Block rendering
- [Media](/developer/core-concepts/media) - Image helper methods
diff --git a/docs/developer/storefront/links.mdx b/docs/developer/storefront/rails/links.mdx
similarity index 94%
rename from docs/developer/storefront/links.mdx
rename to docs/developer/storefront/rails/links.mdx
index c2bb8e7c88..6fda64dfbd 100644
--- a/docs/developer/storefront/links.mdx
+++ b/docs/developer/storefront/rails/links.mdx
@@ -4,7 +4,7 @@ sidebarTitle: "Links"
description: "Learn how to use links for navigation in your Spree Storefront"
---
-Links are used to create navigation throughout the storefront. They can be assigned to [sections](/developer/storefront/sections) and [blocks](/developer/storefront/blocks), enabling users to navigate to different pages, products, categories, or external URLs.
+Links are used to create navigation throughout the storefront. They can be assigned to [sections](/developer/storefront/rails/sections) and [blocks](/developer/storefront/rails/blocks), enabling users to navigate to different pages, products, categories, or external URLs.
## How Links Work
@@ -293,6 +293,6 @@ The label is derived from (in order):
## Related Documentation
-- [Sections](/developer/storefront/sections) - Adding links to sections
-- [Blocks](/developer/storefront/blocks) - Adding links to blocks
-- [Pages](/developer/storefront/pages) - Understanding internal page linking
+- [Sections](/developer/storefront/rails/sections) - Adding links to sections
+- [Blocks](/developer/storefront/rails/blocks) - Adding links to blocks
+- [Pages](/developer/storefront/rails/pages) - Understanding internal page linking
diff --git a/docs/developer/storefront/pages.mdx b/docs/developer/storefront/rails/pages.mdx
similarity index 96%
rename from docs/developer/storefront/pages.mdx
rename to docs/developer/storefront/rails/pages.mdx
index 272874be32..a290e4e7c8 100644
--- a/docs/developer/storefront/pages.mdx
+++ b/docs/developer/storefront/rails/pages.mdx
@@ -1,7 +1,7 @@
---
title: "Storefront Pages"
sidebarTitle: "Pages"
-description: "Learn how to create and use pages in your Spree storefront"
+description: "Learn how to create and use pages in your Spree Rails storefront"
---
## Built-in Pages
@@ -29,7 +29,7 @@ We're planning to add page builder support for the following pages in the next S
## Sections
-Each page is made of [sections](/developer/storefront/sections). Sections are the building blocks of a page. They are used to create the page content.
+Each page is made of [sections](/developer/storefront/rails/sections). Sections are the building blocks of a page. They are used to create the page content.
You can fetch page sections using:
diff --git a/docs/developer/storefront/sections.mdx b/docs/developer/storefront/rails/sections.mdx
similarity index 100%
rename from docs/developer/storefront/sections.mdx
rename to docs/developer/storefront/rails/sections.mdx
diff --git a/docs/developer/storefront/storefront.mdx b/docs/developer/storefront/rails/storefront.mdx
similarity index 87%
rename from docs/developer/storefront/storefront.mdx
rename to docs/developer/storefront/rails/storefront.mdx
index 40fc53de7a..1a91f9e3fa 100644
--- a/docs/developer/storefront/storefront.mdx
+++ b/docs/developer/storefront/rails/storefront.mdx
@@ -40,19 +40,19 @@ You will also need to create your first theme:
Rails Storefront consists of:
<CardGroup>
- <Card title="Themes" href="/developer/storefront/themes">
+ <Card title="Themes" href="/developer/storefront/rails/themes">
Themes are a collection of styles, scripts and templates that are used to style and layout the storefront.
</Card>
- <Card title="Pages" href="/developer/storefront/pages">
+ <Card title="Pages" href="/developer/storefront/rails/pages">
Pages are the main building blocks of the storefront. They are used to create the structure of the storefront. Each Theme comes with a set of default pages such as Home Page, Product Listing Page, Product Page, etc, but you can create your own custom landing pages as well.
</Card>
- <Card title="Sections" href="/developer/storefront/sections">
+ <Card title="Sections" href="/developer/storefront/rails/sections">
Sections are the building blocks of the pages. They are used to create the structure of the pages. Each Section is a collection of Blocks.
</Card>
- <Card title="Blocks" href="/developer/storefront/blocks">
+ <Card title="Blocks" href="/developer/storefront/rails/blocks">
Blocks are the smallest building blocks of the storefront. They are used to create the content of the pages.
</Card>
- <Card title="Links" href="/developer/storefront/links">
+ <Card title="Links" href="/developer/storefront/rails/links">
Links are used to create the navigation of the storefront. They can be assigned to Sections and Blocks.
</Card>
</CardGroup>
diff --git a/docs/developer/storefront/themes.mdx b/docs/developer/storefront/rails/themes.mdx
similarity index 100%
rename from docs/developer/storefront/themes.mdx
rename to docs/developer/storefront/rails/themes.mdx
diff --git a/docs/developer/tutorial/extending-models.mdx b/docs/developer/tutorial/extending-models.mdx
index 53d282c308..7257d0a5a2 100644
--- a/docs/developer/tutorial/extending-models.mdx
+++ b/docs/developer/tutorial/extending-models.mdx
@@ -362,7 +362,7 @@ end
```
<Info>
- SEO features like slugs, meta titles, and FriendlyId are covered in the [SEO](/developer/tutorial/seo) tutorial.
+ SEO features like slugs, meta titles, and FriendlyId are covered in the [Slugs](/developer/core-concepts/slugs) documentation.
</Info>
### Spree Initializer Additions
diff --git a/docs/developer/tutorial/page-builder.mdx b/docs/developer/tutorial/page-builder.mdx
deleted file mode 100644
index 77869b73e6..0000000000
--- a/docs/developer/tutorial/page-builder.mdx
+++ /dev/null
@@ -1,489 +0,0 @@
----
-title: Page Builder Integration
-description: Learn how to connect your Brands feature to Page Builder for admin-manageable pages
----
-
-In this tutorial, we'll enhance our brand pages by integrating them with Spree's Page Builder. This allows store administrators to customize page layouts, add sections, and modify designs without touching code.
-
-<Info>
- This guide assumes you've completed the [Storefront](/developer/tutorial/storefront) tutorial and have working brand pages.
-</Info>
-
-## What We're Building
-
-By the end of this tutorial, you'll have:
-
-- A **Brand List** page type manageable via Page Builder
-- A **Brand** page type for individual brand pages
-- Custom sections: `BrandGrid` and `BrandBanner`
-- Full admin customization support
-
-## Understanding Page Builder Architecture
-
-Page Builder uses three main components:
-
-| Component | Purpose |
-|-----------|---------|
-| **Page** | Defines the page type (e.g., Homepage, Product Details, Brand List) |
-| **Section** | Reusable content blocks within a page (e.g., Hero Banner, Product Grid) |
-| **Block** | Smallest units within sections (e.g., Heading, Text, Button) |
-
-## Step 1: Create Page Types
-
-### Brand List Page
-
-Create a page type for the brands listing:
-
-```ruby app/models/spree/pages/brand_list.rb
-module Spree
- module Pages
- class BrandList < Spree::Page
- def icon_name
- 'building-store'
- end
-
- def customizable?
- true
- end
-
- def page_builder_url
- return unless page_builder_url_exists?(:brands_path)
-
- Spree::Core::Engine.routes.url_helpers.brands_path
- end
-
- def default_sections
- [
- Spree::PageSections::PageTitle.new(
- preferred_heading: Spree.t(:brands)
- ),
- Spree::PageSections::BrandGrid.new
- ]
- end
- end
- end
-end
-```
-
-### Brand Page
-
-Create a page type for individual brand pages:
-
-```ruby app/models/spree/pages/brand.rb
-module Spree
- module Pages
- class Brand < Spree::Page
- def icon_name
- 'tag'
- end
-
- def customizable?
- true
- end
-
- def page_builder_url
- return unless page_builder_url_exists?(:brands_path)
-
- brand = Spree::Brand.first
- return unless brand
-
- Spree::Core::Engine.routes.url_helpers.brand_path(brand)
- end
-
- def default_sections
- [
- Spree::PageSections::BrandBanner.new,
- Spree::PageSections::ProductGrid.new(
- preferred_heading: Spree.t(:products)
- )
- ]
- end
- end
- end
-end
-```
-
-## Step 2: Register Pages
-
-Add your pages to the Spree configuration:
-
-```ruby config/initializers/spree.rb
-Rails.application.config.after_initialize do
- # Register custom pages
- Spree.page_builder.pages += [
- Spree::Pages::BrandList,
- Spree::Pages::Brand
- ]
-end
-```
-
-## Step 3: Create Custom Sections
-
-### Brand Grid Section
-
-This section displays a grid of all brands:
-
-```ruby app/models/spree/page_sections/brand_grid.rb
-module Spree
- module PageSections
- class BrandGrid < Spree::PageSection
- TOP_PADDING_DEFAULT = 40
- BOTTOM_PADDING_DEFAULT = 40
-
- preference :show_description, :boolean, default: false
-
- def icon_name
- 'layout-grid'
- end
-
- # Content sections can be added/removed in Page Builder
- def self.role
- 'content'
- end
-
- def brands
- Spree::Brand.order(:name)
- end
- end
- end
-end
-```
-
-### Brand Banner Section
-
-This section displays the brand header with logo and description:
-
-```ruby app/models/spree/page_sections/brand_banner.rb
-module Spree
- module PageSections
- class BrandBanner < Spree::PageSection
- TOP_PADDING_DEFAULT = 60
- BOTTOM_PADDING_DEFAULT = 40
-
- preference :show_logo, :boolean, default: true
- preference :show_description, :boolean, default: true
- preference :layout, :string, default: 'horizontal'
-
- before_validation :ensure_valid_layout
-
- def icon_name
- 'id-badge'
- end
-
- # System sections are part of the core page functionality
- def self.role
- 'system'
- end
-
- def can_be_deleted?
- false
- end
-
- private
-
- def ensure_valid_layout
- self.preferred_layout = 'horizontal' unless %w[horizontal vertical].include?(preferred_layout)
- end
- end
- end
-end
-```
-
-## Step 4: Register Sections
-
-Add your sections to the configuration:
-
-```ruby config/initializers/spree.rb
-Rails.application.config.after_initialize do
- # Register custom pages
- Spree.page_builder.pages += [
- Spree::Pages::BrandList,
- Spree::Pages::Brand
- ]
-
- # Register custom sections
- Spree.page_builder.page_sections += [
- Spree::PageSections::BrandGrid,
- Spree::PageSections::BrandBanner
- ]
-end
-```
-
-## Step 5: Create Admin Forms
-
-Admin section forms use Spree's Admin Form Builder, which provides helper methods like `spree_select` and `spree_check_box` for consistent styling and functionality.
-
-### Brand Grid Admin Form
-
-```erb app/views/spree/admin/page_sections/forms/_brand_grid.html.erb
-<%= f.spree_check_box :preferred_show_description,
- label: Spree.t(:show_description),
- data: { action: 'auto-submit#submit' } %>
-```
-
-### Brand Banner Admin Form
-
-```erb app/views/spree/admin/page_sections/forms/_brand_banner.html.erb
-<%= f.spree_check_box :preferred_show_logo,
- label: Spree.t(:show_logo),
- data: { action: 'auto-submit#submit' } %>
-
-<%= f.spree_check_box :preferred_show_description,
- label: Spree.t(:show_description),
- data: { action: 'auto-submit#submit' } %>
-
-<% content_for(:design_tab) do %>
- <%= f.spree_select :preferred_layout,
- options_for_select([
- [Spree.t(:horizontal), 'horizontal'],
- [Spree.t(:vertical), 'vertical']
- ], @page_section.preferred_layout),
- { label: Spree.t(:layout) },
- { data: { action: 'auto-submit#submit' } } %>
- <hr />
-<% end %>
-```
-
-## Step 6: Create Storefront Views
-
-### Brand Grid Section View
-
-```erb app/views/themes/default/spree/page_sections/_brand_grid.html.erb
-<% cache_unless page_builder_enabled?, spree_storefront_base_cache_scope.call(section) do %>
- <div style="<%= section_styles(section) %>">
- <div class="page-container">
- <% brands = section.brands %>
- <% if brands.any? %>
- <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
- <% brands.each do |brand| %>
- <%= link_to spree.brand_path(brand),
- class: 'block group',
- data: { turbo_frame: '_top' } do %>
- <div class="aspect-square bg-accent rounded-lg overflow-hidden mb-3">
- <% if brand.logo.attached? %>
- <%= spree_image_tag brand.logo,
- width: 300,
- height: 300,
- class: 'w-full h-full object-contain p-6 group-hover:scale-105 transition-transform',
- alt: brand.name %>
- <% else %>
- <div class="w-full h-full flex items-center justify-center">
- <span class="text-4xl font-medium text-neutral-400">
- <%= brand.name.first.upcase %>
- </span>
- </div>
- <% end %>
- </div>
- <h3 class="font-medium group-hover:text-primary transition-colors">
- <%= brand.name %>
- </h3>
- <% if section.preferred_show_description && brand.description.present? %>
- <p class="mt-1 text-sm text-neutral-600 line-clamp-2">
- <%= brand.description.to_plain_text.truncate(100) %>
- </p>
- <% end %>
- <% end %>
- <% end %>
- </div>
- <% else %>
- <p class="text-neutral-600"><%= Spree.t(:no_brands_found) %></p>
- <% end %>
- </div>
- </div>
-<% end %>
-```
-
-### Brand Banner Section View
-
-```erb app/views/themes/default/spree/page_sections/_brand_banner.html.erb
-<% cache_unless page_builder_enabled?, spree_storefront_base_cache_scope.call(section) do %>
- <div style="<%= section_styles(section) %>">
- <div class="page-container">
- <% if brand.present? %>
- <div class="<%= section.preferred_layout == 'horizontal' ? 'flex flex-col md:flex-row gap-8 items-start' : 'text-center' %>">
- <% if section.preferred_show_logo && brand.logo.attached? %>
- <div class="<%= section.preferred_layout == 'horizontal' ? 'w-32 h-32 flex-shrink-0' : 'w-40 h-40 mx-auto mb-6' %> bg-accent rounded-lg">
- <%= spree_image_tag brand.logo,
- width: 160,
- height: 160,
- class: 'w-full h-full object-contain p-4',
- alt: brand.name %>
- </div>
- <% end %>
-
- <div>
- <h1 class="text-2xl lg:text-3xl font-medium mb-4">
- <%= brand.name %>
- </h1>
-
- <% if section.preferred_show_description && brand.description.present? %>
- <div class="prose max-w-none text-neutral-600">
- <%= brand.description %>
- </div>
- <% end %>
- </div>
- </div>
- <% end %>
- </div>
- </div>
-<% end %>
-```
-
-## Step 7: Update the Controller
-
-Update your controller to use Page Builder pages:
-
-```ruby app/controllers/spree/brands_controller.rb
-module Spree
- class BrandsController < StoreController
- before_action :load_brand, only: [:show]
-
- def index
- # Load the Page Builder page
- @current_page = current_theme.pages.find_by(type: 'Spree::Pages::BrandList')
-
- # Fallback data if sections need it
- @brands = Spree::Brand.order(:name)
- end
-
- def show
- # Load the Page Builder page
- @current_page = current_theme.pages.find_by(type: 'Spree::Pages::Brand')
-
- # Load products for the ProductGrid section
- @products = @brand.products
- .active(current_currency)
- .includes(storefront_products_includes)
- .page(params[:page])
- .per(12)
- end
-
- private
-
- def load_brand
- @brand = Spree::Brand.find(params[:id])
- end
-
- def accurate_title
- if @brand
- @brand.meta_title.presence || @brand.name
- else
- Spree.t(:brands)
- end
- end
- end
-end
-```
-
-## Step 8: Update Views to Use Page Builder
-
-### Brand List Index View
-
-```erb app/views/themes/default/spree/brands/index.html.erb
-<%= render_page(@current_page, brands: @brands) %>
-```
-
-### Brand Show View
-
-```erb app/views/themes/default/spree/brands/show.html.erb
-<%= render_page(@current_page, brand: @brand, products: @products) %>
-```
-
-The `render_page` helper automatically renders all sections in the order defined in Page Builder.
-
-## Step 9: Passing Variables to Sections
-
-Section views receive variables passed to `render_page`. Update your section views to use them:
-
-```erb app/views/themes/default/spree/page_sections/_brand_banner.html.erb
-<% # 'brand' variable is passed from the controller via render_page %>
-<% cache_unless page_builder_enabled?, [spree_storefront_base_cache_scope.call(section), brand] do %>
- <div style="<%= section_styles(section) %>">
- <%# ... use 'brand' variable ... %>
- </div>
-<% end %>
-```
-
-## Step 10: Add Translations
-
-```yaml config/locales/en.yml
-en:
- spree:
- brands: Brands
- no_brands_found: No brands found.
- products_by_brand: "Products by %{brand}"
- show_description: Show description
- show_logo: Show logo
- layout: Layout
- horizontal: Horizontal
- vertical: Vertical
-```
-
-## Testing Page Builder Integration
-
-1. Start your Rails server
-2. Go to **Admin → Storefront → Pages**
-3. You should see "Brand List" and "Brand" pages
-4. Click on a page to customize it in Page Builder
-5. Add, remove, or reorder sections
-6. Customize section settings
-7. Preview changes in real-time
-
-## Section Roles Explained
-
-| Role | Description | Can Delete? | Example |
-|------|-------------|-------------|---------|
-| `content` | General content sections | Yes | BrandGrid, ImageBanner |
-| `system` | Core page functionality | No | BrandBanner, ProductDetails |
-| `header` | Layout header sections | No | Header, AnnouncementBar |
-| `footer` | Layout footer sections | No | Footer, Newsletter |
-
-## Complete File Structure
-
-After completing this tutorial, you should have:
-
-```
-app/
-├── controllers/spree/
-│ └── brands_controller.rb
-├── models/spree/
-│ ├── pages/
-│ │ ├── brand.rb
-│ │ └── brand_list.rb
-│ └── page_sections/
-│ ├── brand_banner.rb
-│ └── brand_grid.rb
-└── views/
- ├── spree/admin/page_sections/forms/
- │ ├── _brand_banner.html.erb
- │ └── _brand_grid.html.erb
- └── themes/default/spree/
- ├── brands/
- │ ├── index.html.erb
- │ └── show.html.erb
- └── page_sections/
- ├── _brand_banner.html.erb
- └── _brand_grid.html.erb
-
-config/
-├── initializers/
-│ └── spree.rb (updated)
-└── locales/
- └── en.yml (updated)
-```
-
-## Benefits of Page Builder Integration
-
-| Without Page Builder | With Page Builder |
-|---------------------|-------------------|
-| Developers edit views for layout changes | Admins customize layouts in browser |
-| Code deployment required for design changes | Real-time preview and publish |
-| Fixed page structure | Drag-and-drop section ordering |
-| Hardcoded settings | Admin-configurable preferences |
-
-## Related Documentation
-
-- [Sections](/developer/storefront/sections) - Creating custom sections
-- [Blocks](/developer/storefront/blocks) - Adding blocks to sections
-- [Pages](/developer/storefront/pages) - Page types and routing
-- [Themes](/developer/storefront/themes) - Theme customization
diff --git a/docs/developer/tutorial/seo.mdx b/docs/developer/tutorial/seo.mdx
deleted file mode 100644
index e4ca47c6cf..0000000000
--- a/docs/developer/tutorial/seo.mdx
+++ /dev/null
@@ -1,344 +0,0 @@
----
-title: SEO
-description: Learn how to optimize your Brands feature for search engines
----
-
-<Info>
- This guide assumes you've completed the [Storefront](/developer/tutorial/storefront) tutorial. You should have working brand pages.
-</Info>
-
-This guide covers SEO best practices for your custom Spree features, including friendly URLs, meta tags, and Open Graph data.
-
-## SEO-Friendly URLs
-
-Rather than using database IDs in URLs:
-
-```
-https://example.com/brands/1
-```
-
-Create human-readable URLs that help with SEO:
-
-```
-https://example.com/brands/nike-sportswear
-```
-
-### Step 1: Add SEO Columns
-
-Add columns for slug and meta fields:
-
-```bash
-bin/rails g migration AddSeoFieldsToSpreeBrands slug:string:uniq meta_title:string meta_description:text
-```
-
-```bash
-bin/rails db:migrate
-```
-
-This adds:
-- `slug` - SEO-friendly URL with unique index
-- `meta_title` - Custom page title for search engines
-- `meta_description` - Description shown in search results
-
-### Step 2: Add FriendlyId to the Model
-
-Add FriendlyId to generate SEO-friendly URLs automatically:
-
-```ruby app/models/spree/brand.rb {3-4,9}
-module Spree
- class Brand < Spree::Base
- extend FriendlyId
- friendly_id :slug_candidates, use: %i[slugged]
-
- # ... other code ...
-
- validates :name, presence: true
- validates :slug, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }
- end
-end
-```
-
-The `slug_candidates` method is already defined in `Spree::Base`:
-
-```ruby
-def slug_candidates
- [
- :name,
- [:name, :uuid_for_friendly_id]
- ]
-end
-```
-
-This generates the slug from the name. If the name is taken, it appends a UUID.
-
-### Step 3: Add SEO Fields to Admin
-
-Spree provides a reusable SEO partial that handles slug, meta title, and meta description with a live search preview. Update your admin form:
-
-```erb app/views/spree/admin/brands/_form.html.erb {1-2,5-12,15,25-32}
-<div class="row" data-controller="slug-form seo-form">
- <div class="col-lg-8">
- <div class="card mb-6">
- <div class="card-body">
- <%= f.spree_text_field :name,
- required: true,
- data: {
- seo_form_target: 'sourceTitleInput',
- slug_form_target: 'name',
- action: 'slug-form#updateUrlFromName'
- } %>
- <%= f.spree_rich_text_area :description,
- data: { seo_form_target: 'sourceDescriptionInput' } %>
- </div>
- </div>
- </div>
-
- <div class="col-lg-4">
- <div class="card mb-6">
- <div class="card-header">
- <h5 class="card-title"><%= Spree.t(:logo) %></h5>
- </div>
- <div class="card-body">
- <%= f.spree_file_field :logo, width: 300, height: 300, crop: true %>
- </div>
- </div>
-
- <%= render 'spree/admin/shared/seo',
- f: f,
- title: @brand.name,
- meta_title: @brand.meta_title,
- description: @brand.description,
- slug: @brand.slug,
- slug_path: 'brands',
- placeholder: 'Add a name and description to see how this brand might appear in a search engine listing' %>
- </div>
-</div>
-```
-
-The SEO partial provides:
-- **Live preview** of how the page will appear in search results
-- **Meta title** field with character count
-- **Meta description** field
-- **Slug** field with auto-generation from name
-
-The `seo-form` Stimulus controller syncs the preview with your form inputs in real-time.
-
-Don't forget to permit the SEO attributes in your controller:
-
-```ruby app/controllers/spree/admin/brands_controller.rb {6-8}
-def permitted_resource_params
- params.require(:brand).permit(
- :name,
- :description,
- :logo,
- :slug,
- :meta_title,
- :meta_description)
-end
-```
-
-### Step 4: Use Slugs in Storefront
-
-Update your controller to use `friendly.find`:
-
-```ruby app/controllers/spree/brands_controller.rb
-def load_brand
- @brand = Spree::Brand.friendly.find(params[:id])
-end
-```
-
-The `friendly.find` method:
-- Finds by slug first (e.g., `/brands/nike-sportswear`)
-- Falls back to ID if no slug matches
-- Raises `ActiveRecord::RecordNotFound` if neither is found
-
-### URL Helpers
-
-Always pass the model object to path helpers:
-
-```erb
-<%= link_to brand.name, spree.brand_path(brand) %>
-<%# => /brands/nike-sportswear %>
-```
-
-FriendlyId overrides `to_param` to return the slug automatically.
-
-### Handling Slug Changes
-
-To redirect old URLs when slugs change, enable slug history:
-
-```ruby app/models/spree/brand.rb
-extend FriendlyId
-friendly_id :slug_candidates, use: %i[slugged history]
-```
-
-Old slugs will automatically resolve to the current slug.
-
-## Meta Tags & Open Graph
-
-Spree automatically generates meta tags and Open Graph data. The system uses a helper called `object` that finds the main instance variable based on your controller name.
-
-For `BrandsController`, Spree looks for `@brand` and generates:
-- Meta description
-- Open Graph tags (og:title, og:description, og:image)
-- Twitter Card tags
-
-### Page Title
-
-Override `accurate_title` in your controller to set the page `<title>`:
-
-```ruby app/controllers/spree/brands_controller.rb
-private
-
-def accurate_title
- if @brand
- @brand.meta_title.presence || @brand.name
- else
- Spree.t(:brands)
- end
-end
-```
-
-### Meta Description
-
-Spree checks these sources in order:
-
-1. `@page_description` instance variable (if set)
-2. `@brand.meta_description` (if the model has this attribute)
-3. `current_store.meta_description` (fallback)
-
-#### Using the SEO Partial
-
-If you followed [Step 1](#step-1-add-seo-columns) and [Step 3](#step-3-add-seo-fields-to-admin), your model already has `meta_description` and the admin form uses the SEO partial. Spree will automatically use `@brand.meta_description` for the page description.
-
-#### Manual Override
-
-For custom logic, set `@page_description` directly:
-
-```ruby
-def show
- @page_description = "Shop #{@brand.name} - #{@brand.products.count} products available"
-end
-```
-
-### Social Sharing Image
-
-For Open Graph images, Spree checks:
-
-1. `@page_image` instance variable (if set)
-2. `@brand.image` (if the model responds to `image`)
-3. `current_store.social_image` (fallback)
-
-If your Brand model has `logo` but not `image`, add an alias:
-
-```ruby app/models/spree/brand.rb
-def image
- logo
-end
-```
-
-Or set it manually:
-
-```ruby
-def show
- @page_image = @brand.logo if @brand.logo.attached?
-end
-```
-
-## Complete SEO-Optimized Model
-
-Here's a complete Brand model with full SEO support:
-
-```ruby app/models/spree/brand.rb
-module Spree
- class Brand < Spree::Base
- extend FriendlyId
- friendly_id :slug_candidates, use: %i[slugged]
-
- has_many :products, class_name: 'Spree::Product', dependent: :nullify
-
- has_one_attached :logo
- has_rich_text :description
-
- # Database columns: slug, meta_title, meta_description
-
- validates :name, presence: true
- validates :slug, presence: true, uniqueness: { scope: spree_base_uniqueness_scope }
-
- # SEO: Use logo as Open Graph image
- def image
- logo
- end
- end
-end
-```
-
-## Complete SEO-Optimized Controller
-
-```ruby app/controllers/spree/brands_controller.rb
-module Spree
- class BrandsController < StoreController
- before_action :load_brand, only: [:show]
-
- def index
- @brands = Spree::Brand.order(:name)
- end
-
- def show
- @products = @brand.products
- .active(current_currency)
- .includes(storefront_products_includes)
- .page(params[:page])
- .per(12)
-
- # Optional: Custom page description
- # @page_description = "Shop #{@brand.name} products"
-
- # Optional: Custom social image
- # @page_image = @brand.logo if @brand.logo.attached?
- end
-
- private
-
- def load_brand
- @brand = Spree::Brand.friendly.find(params[:id])
- end
-
- def accurate_title
- if @brand
- @brand.meta_title.presence || @brand.name
- else
- Spree.t(:brands)
- end
- end
- end
-end
-```
-
-## SEO Checklist
-
-<Check>
- **Friendly URLs** - Use slugs instead of IDs (`/brands/nike` not `/brands/1`)
-</Check>
-
-<Check>
- **Page Titles** - Override `accurate_title` for descriptive titles
-</Check>
-
-<Check>
- **Meta Descriptions** - Add `meta_description` field or set `@page_description`
-</Check>
-
-<Check>
- **Social Images** - Provide `image` method or set `@page_image` for Open Graph
-</Check>
-
-<Check>
- **Slug History** - Enable FriendlyId history to handle URL changes gracefully
-</Check>
-
-## Related Documentation
-
-- [Storefront Tutorial](/developer/tutorial/storefront) - Building storefront pages
-- [Model Tutorial](/developer/tutorial/model) - Creating the Brand model
-- [Admin Tutorial](/developer/tutorial/admin) - Building the admin interface
diff --git a/docs/developer/tutorial/storefront.mdx b/docs/developer/tutorial/storefront.mdx
deleted file mode 100644
index 160f582502..0000000000
--- a/docs/developer/tutorial/storefront.mdx
+++ /dev/null
@@ -1,366 +0,0 @@
----
-title: Storefront
-description: Learn how to create storefront pages for your Brands feature
----
-
-In this tutorial, we'll create storefront pages to display brands to your customers. We'll start with a simple Rails approach using controllers and views, then in the next guide we'll connect it to Page Builder.
-
-<Info>
- This guide assumes you've completed the [Model](/developer/tutorial/model), [Admin](/developer/tutorial/admin), [Rich Text](/developer/tutorial/rich-text), [File Uploads](/developer/tutorial/file-uploads), and [Extending Core Models](/developer/tutorial/extending-models) tutorials. You should have a working `Spree::Brand` model with products associated to brands.
-</Info>
-
-## What We're Building
-
-By the end of this tutorial, you'll have:
-
-- A custom theme for your store
-- A brands listing page at `/brands`
-- Individual brand pages at `/brands/:id`
-- Styled views using Tailwind CSS
-
-## Step 1: Create a Custom Theme
-
-Before adding custom views, create your own theme. This is important because:
-
-- **Upgrade safety** - Your customizations won't be overwritten when updating Spree
-- **Clean separation** - Your code stays separate from Spree's default theme
-- **Full control** - You get a complete copy of all templates to customize
-
-Run the theme generator:
-
-```bash
-bin/rails g spree:storefront:theme MyStore
-```
-
-This creates:
-- `app/views/themes/my_store/` - Copy of all storefront templates
-- `app/models/spree/themes/my_store.rb` - Theme configuration class
-
-The generator also updates your `config/initializers/spree.rb`:
-
-```ruby config/initializers/spree.rb
-Spree.page_builder.themes << Spree::Themes::MyStore
-```
-
-### Activate Your Theme
-
-1. Go to **Admin → Storefront → Themes**
-2. Find your new theme in the "Add new theme" section
-3. Click **Add** to activate it
-
-<Warning>
- Always create a custom theme for production stores. Never modify the default theme directly - your changes will be lost during Spree upgrades.
-</Warning>
-
-## Step 2: Add Routes
-
-Now let's add routes for our brand pages. Create or update your routes file:
-
-```ruby config/routes.rb
-Spree::Core::Engine.add_routes do
- scope '(:locale)', locale: /#{Spree.available_locales.join('|')}/, defaults: { locale: nil } do
- resources :brands, only: [:index, :show]
- end
-end
-```
-
-<Info>
- The `scope '(:locale)'` wrapper enables internationalization - URLs like `/fr/brands` will work automatically if you have French locale enabled.
-</Info>
-
-## Step 3: Create the Controller
-
-Create a controller that inherits from `Spree::StoreController`. This base controller provides:
-
-- Access to `current_store`, `current_theme`, `current_currency`
-- User authentication helpers
-- Storefront layout and helpers
-- SEO and meta tag support
-
-```ruby app/controllers/spree/brands_controller.rb
-module Spree
- class BrandsController < StoreController
- before_action :load_brand, only: [:show]
-
- def index
- @brands = Spree::Brand.order(:name)
- end
-
- def show
- @products = @brand.products.active(current_currency).includes(storefront_products_includes)
- end
-
- private
-
- def load_brand
- @brand = Spree::Brand.find(params[:id])
- end
-
- # Override to set page title for SEO
- def accurate_title
- if @brand
- @brand.name
- else
- Spree.t(:brands)
- end
- end
- end
-end
-```
-
-### Key Points
-
-- **Inherit from `Spree::StoreController`** - Not `ApplicationController`. This gives you access to all storefront functionality.
-- **Use `current_store`** - Always scope queries to the current store for multi-store support.
-- **Override `accurate_title`** - This sets the page `<title>` tag.
-
-<Tip>
- Want SEO-friendly URLs like `/brands/nike` instead of `/brands/123`? See the [SEO](/developer/tutorial/seo) tutorial to add slug support.
-</Tip>
-
-## Step 4: Create the Views
-
-Storefront views live in your theme directory. Create the brands views in your custom theme:
-
-```bash
-mkdir -p app/views/themes/my_store/spree/brands
-```
-
-Your theme's view structure:
-
-```
-app/views/themes/my_store/spree/brands/
-├── index.html.erb
-├── show.html.erb
-└── _brand_card.html.erb
-```
-
-### Brands Listing Page
-
-```erb app/views/themes/my_store/spree/brands/index.html.erb
-<div class="page-container py-8">
- <h1 class="text-2xl lg:text-3xl font-medium mb-8">
- <%= Spree.t(:brands) %>
- </h1>
-
- <% if @brands.any? %>
- <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
- <% @brands.each do |brand| %>
- <%= render 'brand_card', brand: brand %>
- <% end %>
- </div>
- <% else %>
- <p class="text-neutral-600">
- <%= Spree.t(:no_brands_found) %>
- </p>
- <% end %>
-</div>
-```
-
-### Brand Card Partial
-
-```erb app/views/themes/my_store/spree/brands/_brand_card.html.erb
-<%= link_to spree.brand_path(brand),
- class: 'block group',
- data: { turbo_frame: '_top' } do %>
- <div class="aspect-square bg-accent rounded-lg overflow-hidden mb-3">
- <% if brand.logo.attached? %>
- <%= spree_image_tag brand.logo,
- width: 300,
- height: 300,
- class: 'w-full h-full object-contain p-6 group-hover:scale-105 transition-transform',
- alt: brand.name %>
- <% else %>
- <div class="w-full h-full flex items-center justify-center">
- <span class="text-4xl font-medium text-neutral-400">
- <%= brand.name.first.upcase %>
- </span>
- </div>
- <% end %>
- </div>
- <h2 class="font-medium group-hover:text-primary transition-colors">
- <%= brand.name %>
- </h2>
-<% end %>
-```
-
-### Single Brand Page
-
-```erb app/views/themes/my_store/spree/brands/show.html.erb
-<div class="page-container py-8">
- <%# Brand Header %>
- <div class="flex flex-col md:flex-row gap-8 mb-12">
- <% if @brand.logo.attached? %>
- <div class="w-32 h-32 bg-accent rounded-lg flex-shrink-0">
- <%= spree_image_tag @brand.logo,
- width: 128,
- height: 128,
- class: 'w-full h-full object-contain p-4',
- alt: @brand.name %>
- </div>
- <% end %>
-
- <div>
- <h1 class="text-2xl lg:text-3xl font-medium mb-4">
- <%= @brand.name %>
- </h1>
-
- <% if @brand.description.present? %>
- <div class="prose max-w-none text-neutral-600">
- <%= @brand.description %>
- </div>
- <% end %>
- </div>
- </div>
-
- <%# Products Grid %>
- <% if @products.any? %>
- <h2 class="text-xl font-medium mb-6">
- <%= Spree.t(:products_by_brand, brand: @brand.name) %>
- </h2>
-
- <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
- <%= render 'spree/shared/products', products: @products %>
- </div>
- <% else %>
- <p class="text-neutral-600">
- <%= Spree.t(:no_products_found) %>
- </p>
- <% end %>
-</div>
-```
-
-## Step 5: Add Translations
-
-Add the necessary translations:
-
-```yaml config/locales/en.yml
-en:
- spree:
- brands: Brands
- no_brands_found: No brands found.
- products_by_brand: "Products by %{brand}"
-```
-
-## Step 6: Add Navigation Link (Optional)
-
-To add a link to brands in your header navigation, you can use the Admin Dashboard:
-
-1. Go to **Storefront → Theme Editor**
-2. Click on **Header** section
-3. Add a new navigation link pointing to `/brands`
-
-Or programmatically in your header partial:
-
-```erb
-<%= link_to Spree.t(:brands), spree.brands_path, class: 'nav-link' %>
-```
-
-## Understanding the View Structure
-
-### Theme Directory
-
-Views are organized by theme in `app/views/themes/{theme_name}/spree/`:
-
-```
-app/views/themes/my_store/spree/
-├── brands/ # Your brand views
-├── products/ # Product views
-├── shared/ # Shared partials
-└── page_sections/ # Page Builder sections
-```
-
-<Info>
- Spree looks for views in your active theme first. If a view isn't found, it falls back to the default theme. This means you only need to copy and customize the files you want to change.
-</Info>
-
-### Key CSS Classes
-
-Spree's default theme uses these common patterns:
-
-| Class | Purpose |
-|-------|---------|
-| `page-container` | Centered container with max-width and padding |
-| `bg-accent` | Uses theme's accent background color |
-| `text-primary` | Uses theme's primary text color |
-| `btn-primary` | Primary button style |
-| `btn-secondary` | Secondary button style |
-
-### Using Spree Helpers
-
-```erb
-<%# Image helper with automatic optimization %>
-<%= spree_image_tag image, width: 400, height: 400 %>
-
-<%# URL helpers %>
-<%= spree.brands_path %>
-<%= spree.brand_path(brand) %>
-
-<%# Translation helper %>
-<%= Spree.t(:brands) %>
-
-<%# Price display %>
-<%= display_price(product.price_in(current_currency)) %>
-```
-
-## Testing Your Pages
-
-Start your Rails server and visit:
-
-- `http://localhost:3000/brands` - Brand listing
-- `http://localhost:3000/brands/1` - Single brand (using the brand's ID)
-
-<Tip>
- Want SEO-friendly URLs like `/brands/nike` instead of `/brands/1`? See the [SEO](/developer/tutorial/seo) tutorial to add slug support, meta tags, and Open Graph data.
-</Tip>
-
-## What's Next?
-
-You now have working brand pages using standard Rails MVC patterns. In the next guide, [Testing](/developer/tutorial/testing), we'll write automated tests for your feature to make sure it works as expected, also in the future when you make changes to your code.
-
-## Complete Controller Example
-
-Here's the complete controller with all features:
-
-```ruby app/controllers/spree/brands_controller.rb
-module Spree
- class BrandsController < StoreController
- before_action :load_brand, only: [:show]
-
- def index
- @brands = Spree::Brand.order(:name)
- .page(params[:page])
- .per(24)
- end
-
- def show
- @products = @brand.products.active(current_currency).includes(storefront_products_includes)
- @page_description = @brand.description&.to_plain_text&.truncate(160)
- end
-
- private
-
- def load_brand
- @brand = Spree::Brand.find(params[:id])
- end
-
- def accurate_title
- if @brand
- @brand.name
- else
- Spree.t(:brands)
- end
- end
- end
-end
-```
-
-<Info>
- To use SEO-friendly slugs like `/brands/nike` instead of `/brands/1`, follow the [SEO](/developer/tutorial/seo) tutorial.
-</Info>
-
-## Related Documentation
-
-- [Storefront Overview](/developer/storefront/storefront) - Storefront architecture
-- [Custom CSS](/developer/storefront/custom-css) - Styling with Tailwind
-- [Helper Methods](/developer/storefront/helper-methods) - Available helpers
diff --git a/docs/developer/tutorial/testing.mdx b/docs/developer/tutorial/testing.mdx
index f3da9f1453..536e7a8c01 100644
--- a/docs/developer/tutorial/testing.mdx
+++ b/docs/developer/tutorial/testing.mdx
@@ -5,7 +5,7 @@ Spree uses [RSpec](https://rspec.info), [Factory Bot](https://github.com/thought
We also provide the `spree_dev_tools` gem that helps you write Spree-specific tests.
<Info>
- This guide assumes you've completed all previous tutorials through [Page Builder](/developer/tutorial/page-builder). You should have a complete `Spree::Brand` model with admin, storefront, and SEO features.
+ This guide assumes you've completed all previous tutorials through [Extending Models](/developer/tutorial/extending-models). You should have a complete `Spree::Brand` model with admin features.
</Info>
## Setup
@@ -320,61 +320,6 @@ RSpec.describe Spree::Admin::BrandsController, type: :controller do
end
```
-### Storefront Controller Tests
-
-```ruby spec/controllers/spree/brands_controller_spec.rb
-require 'rails_helper'
-
-RSpec.describe Spree::Brand, type: :model do
- describe 'associations' do
- it 'has many products' do
- association = described_class.reflect_on_association(:products)
- expect(association.macro).to eq(:has_many)
- expect(association.class_name).to eq('Spree::Product')
- end
- end
-
- describe 'validations' do
- it 'validates presence of name' do
- brand = build(:brand, name: nil)
- expect(brand).not_to be_valid
- expect(brand.errors[:name]).to include("can't be blank")
- end
-
- describe 'slug uniqueness' do
- let!(:existing_brand) { create(:brand, slug: 'nike') }
-
- it 'validates uniqueness of slug' do
- brand = build(:brand, slug: 'nike')
- expect(brand).not_to be_valid
- expect(brand.errors[:slug]).to include('has already been taken')
- end
- end
- end
-
- describe 'FriendlyId' do
- it 'generates slug from name' do
- brand = create(:brand, name: 'Nike Sportswear', slug: nil)
- expect(brand.slug).to eq('nike-sportswear')
- end
-
- it 'handles duplicate names by appending UUID' do
- create(:brand, name: 'Nike', slug: 'nike')
- brand = create(:brand, name: 'Nike', slug: nil)
- expect(brand.slug).to match(/nike-[a-f0-9-]+/)
- end
- end
-
- describe '#image' do
- let(:brand) { create(:brand, :with_logo) }
-
- it 'returns logo as image for Open Graph' do
- expect(brand.image).to eq(brand.logo)
- end
- end
-end
-```
-
## Writing Feature Tests
Feature tests (also called system tests) simulate real user interactions using Capybara.
@@ -560,9 +505,8 @@ spec/
* [Model Tutorial](/developer/tutorial/model) - Creating the Brand model
* [Admin Tutorial](/developer/tutorial/admin) - Building the admin interface
* [Extending Core Models](/developer/tutorial/extending-models) - Connecting Brands to Products
-* [Storefront Tutorial](/developer/tutorial/storefront) - Creating storefront pages
* [RSpec Documentation](https://rspec.info/documentation/) - Official RSpec docs
* [Factory Bot Documentation](https://github.com/thoughtbot/factory_bot/blob/main/GETTING_STARTED.md) - Factory Bot guide
----
\ No newline at end of file
+---
diff --git a/docs/docs.json b/docs/docs.json
index 44cfbc4c97..7458b9086f 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -66,6 +66,54 @@
{
"source": "/developer/extending-spree/promotions",
"destination": "/developer/how-to/custom-promotion"
+ },
+ {
+ "source": "/developer/tutorial/seo",
+ "destination": "/developer/core-concepts/slugs"
+ },
+ {
+ "source": "/developer/tutorial/storefront",
+ "destination": "/developer/storefront/rails/storefront"
+ },
+ {
+ "source": "/developer/tutorial/page-builder",
+ "destination": "/developer/storefront/rails/sections"
+ },
+ {
+ "source": "/developer/storefront/storefront",
+ "destination": "/developer/storefront/rails/storefront"
+ },
+ {
+ "source": "/developer/storefront/themes",
+ "destination": "/developer/storefront/rails/themes"
+ },
+ {
+ "source": "/developer/storefront/sections",
+ "destination": "/developer/storefront/rails/sections"
+ },
+ {
+ "source": "/developer/storefront/blocks",
+ "destination": "/developer/storefront/rails/blocks"
+ },
+ {
+ "source": "/developer/storefront/pages",
+ "destination": "/developer/storefront/rails/pages"
+ },
+ {
+ "source": "/developer/storefront/links",
+ "destination": "/developer/storefront/rails/links"
+ },
+ {
+ "source": "/developer/storefront/helper-methods",
+ "destination": "/developer/storefront/rails/helper-methods"
+ },
+ {
+ "source": "/developer/storefront/custom-css",
+ "destination": "/developer/storefront/rails/custom-css"
+ },
+ {
+ "source": "/developer/storefront/custom-javascript",
+ "destination": "/developer/storefront/rails/custom-javascript"
}
],
"contextual": {
diff --git a/packages/create-spree-app/src/scaffold.ts b/packages/create-spree-app/src/scaffold.ts
index 310181ae9c..23627cb351 100644
--- a/packages/create-spree-app/src/scaffold.ts
+++ b/packages/create-spree-app/src/scaffold.ts
@@ -10,6 +10,7 @@ import { envContent } from './templates/env.js'
import { rootPackageJsonContent } from './templates/package-json.js'
import { readmeContent } from './templates/readme.js'
import { gitignoreContent } from './templates/gitignore.js'
+import { rootClaudeMdContent, agentsMdContent } from './templates/claude-md.js'
import { downloadStorefront, installRootDeps, installStorefrontDeps, writeStorefrontEnv } from './storefront.js'
import { downloadBackend } from './backend.js'
@@ -63,6 +64,8 @@ export async function scaffold(options: ScaffoldOptions): Promise<void> {
fs.writeFileSync(path.join(projectDir, 'package.json'), rootPackageJsonContent(projectName))
fs.writeFileSync(path.join(projectDir, 'README.md'), readmeContent(projectName, storefront, port))
fs.writeFileSync(path.join(projectDir, '.gitignore'), gitignoreContent())
+ fs.writeFileSync(path.join(projectDir, 'CLAUDE.md'), rootClaudeMdContent(storefront))
+ fs.writeFileSync(path.join(projectDir, 'AGENTS.md'), agentsMdContent())
s.stop('Project structure created.')
diff --git a/packages/create-spree-app/src/templates/claude-md.ts b/packages/create-spree-app/src/templates/claude-md.ts
new file mode 100644
index 0000000000..ccd8ce0bab
--- /dev/null
+++ b/packages/create-spree-app/src/templates/claude-md.ts
@@ -0,0 +1,72 @@
+export function agentsMdContent(): string {
+ return `# Agent Instructions
+
+See [CLAUDE.md](./CLAUDE.md) for full project instructions and conventions.
+`
+}
+
+export function rootClaudeMdContent(hasStorefront: boolean): string {
+ const lines = [
+ '# Spree Commerce Application',
+ '',
+ '## Project Structure',
+ '',
+ '| Directory | Description |',
+ '|-----------|-------------|',
+ '| `backend/` | Rails API application (Spree Commerce) |',
+ ]
+
+ if (hasStorefront) {
+ lines.push('| `apps/storefront/` | Next.js storefront |')
+ }
+
+ lines.push(
+ '',
+ '## Agent Instructions',
+ '',
+ '- **Backend work** (Ruby/Rails, Spree models, API, database): See `backend/CLAUDE.md`',
+ )
+
+ if (hasStorefront) {
+ lines.push(
+ '- **Storefront work** (Next.js, React, TypeScript): See `apps/storefront/CLAUDE.md`',
+ )
+ }
+
+ lines.push(
+ '',
+ '## Spree Documentation',
+ '',
+ 'Full developer docs are installed locally:',
+ '',
+ '```',
+ 'node_modules/@spree/docs/dist/',
+ '├── developer/',
+ '│ ├── core-concepts/ # Products, orders, payments, inventory, etc.',
+ '│ ├── customization/ # Decorators, extensions, configuration, dependencies',
+ '│ ├── admin/ # Admin panel customization',
+ '│ ├── storefront/ # Storefront building guides',
+ '│ ├── sdk/ # TypeScript SDK documentation',
+ '│ └── tutorial/ # Step-by-step tutorials',
+ '├── api-reference/',
+ '│ ├── store-api/ # Store API v3 guides',
+ '│ └── store.yaml # OpenAPI 3.0 spec (all endpoints, params, schemas)',
+ '└── integrations/ # Stripe, Meilisearch, etc.',
+ '```',
+ '',
+ 'Read these files when you need Spree-specific guidance.',
+ '',
+ '## Common Commands',
+ '',
+ '```bash',
+ 'npm run dev # Start backend (Docker)',
+ 'npm run stop # Stop services',
+ 'npm run console # Rails console',
+ 'npm run logs # Backend logs',
+ 'npx spree eject # Switch to local backend builds',
+ '```',
+ '',
+ )
+
+ return lines.join('\n')
+}
diff --git a/packages/create-spree-app/src/templates/package-json.ts b/packages/create-spree-app/src/templates/package-json.ts
index ccf1296503..0b4e06fc45 100644
--- a/packages/create-spree-app/src/templates/package-json.ts
+++ b/packages/create-spree-app/src/templates/package-json.ts
@@ -16,6 +16,7 @@ export function rootPackageJsonContent(name: string): string {
},
dependencies: {
'@spree/cli': '2.0.0-beta.7',
+ '@spree/docs': 'latest',
},
}
diff --git a/packages/docs/.gitignore b/packages/docs/.gitignore
new file mode 100644
index 0000000000..849ddff3b7
--- /dev/null
+++ b/packages/docs/.gitignore
@@ -0,0 +1 @@
+dist/
diff --git a/packages/docs/README.md b/packages/docs/README.md
new file mode 100644
index 0000000000..cbd7a85f41
--- /dev/null
+++ b/packages/docs/README.md
@@ -0,0 +1,54 @@
+# @spree/docs
+
+Spree Commerce developer documentation packaged for local access by AI agents and development tools.
+
+## Installation
+
+```bash
+npm install @spree/docs
+# or
+pnpm add @spree/docs
+```
+
+## Usage
+
+Documentation files are plain Markdown, accessible at:
+
+```
+node_modules/@spree/docs/dist/
+├── developer/
+│ ├── core-concepts/ # Products, orders, payments, inventory, etc.
+│ ├── customization/ # Decorators, extensions, configuration
+│ ├── admin/ # Admin panel customization
+│ ├── storefront/ # Storefront building guides
+│ ├── sdk/ # TypeScript SDK documentation
+│ ├── deployment/ # Deployment guides
+│ └── tutorial/ # Step-by-step tutorials
+├── api-reference/
+│ └── store-api/ # Store API reference
+└── integrations/ # Third-party integration guides
+```
+
+### For AI Agents
+
+Point your `CLAUDE.md` or agent configuration to the docs:
+
+```markdown
+## Spree Documentation
+Full developer docs: `node_modules/@spree/docs/dist/`
+```
+
+### Programmatic Access (Node.js)
+
+```javascript
+import { readFileSync } from 'fs'
+import { createRequire } from 'module'
+
+const require = createRequire(import.meta.url)
+const docsPath = require.resolve('@spree/docs/dist/developer/core-concepts/products.md')
+const content = readFileSync(docsPath, 'utf-8')
+```
+
+## License
+
+CC-BY-4.0 — same as the Spree Commerce documentation.
diff --git a/packages/docs/package.json b/packages/docs/package.json
new file mode 100644
index 0000000000..8f4f7735c7
--- /dev/null
+++ b/packages/docs/package.json
@@ -0,0 +1,32 @@
+{
+ "name": "@spree/docs",
+ "version": "0.1.0",
+ "description": "Spree Commerce developer documentation for AI agents and local reference",
+ "type": "module",
+ "license": "CC-BY-4.0",
+ "author": "Vendo Connect Inc.",
+ "homepage": "https://spreecommerce.org",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/spree/spree.git",
+ "directory": "packages/docs"
+ },
+ "bugs": {
+ "url": "https://github.com/spree/spree/issues"
+ },
+ "files": [
+ "dist/**/*.md",
+ "dist/**/*.yaml"
+ ],
+ "scripts": {
+ "build": "node scripts/build.js",
+ "test": "vitest run",
+ "clean": "rm -rf dist"
+ },
+ "devDependencies": {
+ "vitest": "^4.0.18"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+}
diff --git a/packages/docs/scripts/build.js b/packages/docs/scripts/build.js
new file mode 100644
index 0000000000..061dab5364
--- /dev/null
+++ b/packages/docs/scripts/build.js
@@ -0,0 +1,136 @@
+/**
+ * Converts Mintlify MDX docs to plain Markdown for AI agent consumption.
+ *
+ * - Strips Mintlify-specific JSX components (Info, Warning, Tabs, etc.)
+ * - Inlines imported snippets
+ * - Preserves frontmatter, code blocks, mermaid diagrams
+ * - Outputs clean .md files to dist/
+ */
+
+import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, statSync } from 'fs'
+import { join, dirname, relative, resolve } from 'path'
+import { convertContent, resolveImports, extractFrontmatter, rewriteLinks } from './convert.js'
+
+const ROOT = resolve(import.meta.dirname, '..', '..', '..')
+const DOCS_DIR = join(ROOT, 'docs')
+const DIST_DIR = resolve(import.meta.dirname, '..', 'dist')
+
+// Directories to include in the output
+const INCLUDE_DIRS = [
+ 'developer',
+ 'api-reference',
+ 'integrations',
+]
+
+// Paths to exclude (relative to DOCS_DIR)
+const EXCLUDE_PATHS = [
+ 'developer/storefront/rails',
+]
+
+// ---------------------------------------------------------------------------
+// Snippet resolution (uses filesystem — not in convert.js)
+// ---------------------------------------------------------------------------
+
+const snippetCache = new Map()
+
+function resolveSnippet(importPath) {
+ const absPath = join(DOCS_DIR, importPath.replace(/^\//, ''))
+ if (snippetCache.has(absPath)) return snippetCache.get(absPath)
+
+ if (!existsSync(absPath)) {
+ snippetCache.set(absPath, '')
+ return ''
+ }
+
+ let content = readFileSync(absPath, 'utf-8')
+ content = resolveImports(content, resolveSnippet)
+ content = convertContent(content)
+ snippetCache.set(absPath, content)
+ return content
+}
+
+// ---------------------------------------------------------------------------
+// File processing
+// ---------------------------------------------------------------------------
+
+function processFile(filePath) {
+ let content = readFileSync(filePath, 'utf-8')
+
+ const { frontmatter, body } = extractFrontmatter(content)
+ const fileRelDir = dirname(relative(DOCS_DIR, filePath))
+
+ let processed = body
+ processed = resolveImports(processed, resolveSnippet)
+ processed = convertContent(processed)
+ processed = rewriteLinks(processed, fileRelDir)
+
+ if (frontmatter) {
+ processed = frontmatter + '\n' + processed.trim() + '\n'
+ } else {
+ processed = processed.trim() + '\n'
+ }
+
+ return processed
+}
+
+function walkDir(dir, fileList = []) {
+ for (const entry of readdirSync(dir)) {
+ const full = join(dir, entry)
+ if (statSync(full).isDirectory()) {
+ walkDir(full, fileList)
+ } else if (entry.endsWith('.mdx') || entry.endsWith('.md')) {
+ fileList.push(full)
+ }
+ }
+ return fileList
+}
+
+// ---------------------------------------------------------------------------
+// Main
+// ---------------------------------------------------------------------------
+
+let totalFiles = 0
+
+for (const dir of INCLUDE_DIRS) {
+ const sourceDir = join(DOCS_DIR, dir)
+ if (!existsSync(sourceDir)) {
+ console.warn(`Skipping ${dir}: directory not found`)
+ continue
+ }
+
+ const files = walkDir(sourceDir)
+
+ for (const file of files) {
+ const rel = relative(DOCS_DIR, file)
+ if (EXCLUDE_PATHS.some((ex) => rel.startsWith(ex))) continue
+ const outPath = join(DIST_DIR, rel.replace(/\.mdx$/, '.md'))
+
+ mkdirSync(dirname(outPath), { recursive: true })
+
+ const converted = processFile(file)
+ writeFileSync(outPath, converted)
+ totalFiles++
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Copy OpenAPI specs
+// ---------------------------------------------------------------------------
+
+const OPENAPI_FILES = [
+ 'api-reference/store.yaml',
+]
+
+for (const file of OPENAPI_FILES) {
+ const src = join(DOCS_DIR, file)
+ if (!existsSync(src)) {
+ console.warn(`Skipping OpenAPI spec: ${file} not found`)
+ continue
+ }
+ const dest = join(DIST_DIR, file)
+ mkdirSync(dirname(dest), { recursive: true })
+ writeFileSync(dest, readFileSync(src, 'utf-8'))
+ totalFiles++
+}
+
+console.log(`@spree/docs: converted ${totalFiles} files to ${DIST_DIR}`)
diff --git a/packages/docs/scripts/convert.js b/packages/docs/scripts/convert.js
new file mode 100644
index 0000000000..b12ec3dd37
--- /dev/null
+++ b/packages/docs/scripts/convert.js
@@ -0,0 +1,238 @@
+/**
+ * Pure conversion functions for MDX → Markdown transformation.
+ * Separated from build.js for testability.
+ */
+
+import { relative } from "path";
+
+// ---------------------------------------------------------------------------
+// Callout mapping
+// ---------------------------------------------------------------------------
+
+const CALLOUT_MAP = {
+ Info: "INFO",
+ Warning: "WARNING",
+ Tip: "TIP",
+ Note: "NOTE",
+ Hint: "HINT",
+};
+
+// ---------------------------------------------------------------------------
+// Import resolution
+// ---------------------------------------------------------------------------
+
+export function resolveImports(content, snippetResolver = () => "") {
+ // Collect import mappings: import Name from '/snippets/...'
+ const importMap = new Map();
+ const importRegex = /^import\s+(\w+)\s+from\s+['"]([^'"]+)['"]\s*;?\s*$/gm;
+ let match;
+
+ while ((match = importRegex.exec(content)) !== null) {
+ const [, componentName, importPath] = match;
+ // Only resolve snippet imports (from /snippets/ or relative .mdx)
+ if (importPath.includes("/snippets/") || importPath.endsWith(".mdx")) {
+ importMap.set(componentName, importPath);
+ }
+ }
+
+ // Remove all import lines
+ content = content.replace(
+ /^import\s+\w+\s+from\s+['"][^'"]+['"]\s*;?\s*$/gm,
+ "",
+ );
+
+ // Replace <ComponentName /> self-closing tags with inlined snippet content
+ for (const [name, path] of importMap) {
+ const selfClosingRegex = new RegExp(`<${name}\\s*/>`, "g");
+ const snippetContent = snippetResolver(path);
+ content = content.replace(selfClosingRegex, snippetContent);
+ }
+
+ return content;
+}
+
+// ---------------------------------------------------------------------------
+// Component conversion
+// ---------------------------------------------------------------------------
+
+export function convertContent(content) {
+ // Protect code blocks from conversion
+ const codeBlocks = [];
+ content = content.replace(/(```[\s\S]*?```|`[^`\n]+`)/g, (match) => {
+ const index = codeBlocks.length;
+ codeBlocks.push(match);
+ return `__CODE_BLOCK_${index}__`;
+ });
+
+ // --- Callout components → GitHub-style blockquote alerts ---
+ for (const [component, label] of Object.entries(CALLOUT_MAP)) {
+ const regex = new RegExp(
+ `<${component}>\\s*([\\s\\S]*?)\\s*</${component}>`,
+ "gi",
+ );
+ content = content.replace(regex, (_, inner) => {
+ const lines = inner.trim().split("\n");
+ return `> **${label}:** ${lines.join("\n> ")}`;
+ });
+ }
+
+ // --- Tabs → Sections with headers ---
+ content = content.replace(/<Tabs>\s*([\s\S]*?)\s*<\/Tabs>/gi, (_, inner) => {
+ return inner.replace(
+ /<Tab\s+title="([^"]*)">\s*([\s\S]*?)\s*<\/Tab>/gi,
+ (_, title, tabContent) => {
+ return `**${title}:**\n\n${tabContent.trim()}\n`;
+ },
+ );
+ });
+
+ // --- Steps → Numbered list ---
+ let stepCounter = 0;
+ content = content.replace(
+ /<Steps>\s*([\s\S]*?)\s*<\/Steps>/gi,
+ (_, inner) => {
+ stepCounter = 0;
+ return inner.replace(
+ /<Step\s+title="([^"]*)">\s*([\s\S]*?)\s*<\/Step>/gi,
+ (_, title, stepContent) => {
+ stepCounter++;
+ return `**Step ${stepCounter}: ${title}**\n\n${stepContent.trim()}\n`;
+ },
+ );
+ },
+ );
+
+ // --- CodeGroup → Just keep the code blocks inside ---
+ content = content.replace(/<\/?CodeGroup>/gi, "");
+
+ // --- Accordion/AccordionGroup → Details/summary ---
+ content = content.replace(
+ /<AccordionGroup>\s*([\s\S]*?)\s*<\/AccordionGroup>/gi,
+ (_, inner) => inner,
+ );
+ content = content.replace(
+ /<Accordion\s+title="([^"]*)">\s*([\s\S]*?)\s*<\/Accordion>/gi,
+ (_, title, inner) => {
+ return `<details>\n<summary>${title}</summary>\n\n${inner.trim()}\n\n</details>\n`;
+ },
+ );
+
+ // --- Card/CardGroup → Bold title + description ---
+ content = content.replace(/<\/?CardGroup[^>]*>/gi, "");
+ content = content.replace(
+ /<Card\s+([^>]*)>([\s\S]*?)<\/Card>/gi,
+ (_, attrs, inner) => {
+ const titleMatch = attrs.match(/title="([^"]*)"/);
+ const hrefMatch = attrs.match(/href="([^"]*)"/);
+ const title = titleMatch ? titleMatch[1] : "";
+ const href = hrefMatch ? hrefMatch[1] : "";
+ const titleText = href ? `[${title}](${href})` : `**${title}**`;
+ const body = inner.trim();
+ return body ? `- ${titleText} — ${body}` : `- ${titleText}`;
+ },
+ );
+ // Self-closing cards
+ content = content.replace(/<Card\s+([\s\S]*?)\/>/gi, (_, attrs) => {
+ const titleMatch = attrs.match(/title="([^"]*)"/);
+ const hrefMatch = attrs.match(/href="([^"]*)"/);
+ const title = titleMatch ? titleMatch[1] : "";
+ const href = hrefMatch ? hrefMatch[1] : "";
+ return href ? `- [${title}](${href})` : `- **${title}**`;
+ });
+
+ // --- Frame → Just keep the content (strip the wrapper) ---
+ content = content.replace(
+ /<Frame[^>]*>\s*([\s\S]*?)\s*<\/Frame>/gi,
+ (_, inner) => inner.trim(),
+ );
+
+ // --- Expandable → Details/summary ---
+ content = content.replace(
+ /<Expandable\s+title="([^"]*)">\s*([\s\S]*?)\s*<\/Expandable>/gi,
+ (_, title, inner) => {
+ return `<details>\n<summary>${title}</summary>\n\n${inner.trim()}\n\n</details>\n`;
+ },
+ );
+
+ // --- ResponseField → Bold field name with type ---
+ content = content.replace(
+ /<ResponseField\s+name="([^"]*)"\s+type="([^"]*)">\s*([\s\S]*?)\s*<\/ResponseField>/gi,
+ (_, name, type, desc) => {
+ return `- **\`${name}\`** (\`${type}\`) — ${desc.trim()}`;
+ },
+ );
+
+ // --- ParamField → Bold param name with type ---
+ content = content.replace(
+ /<ParamField\s+([^>]*)>\s*([\s\S]*?)\s*<\/ParamField>/gi,
+ (_, attrs, desc) => {
+ const nameMatch = attrs.match(/(?:name|path|query|body)="([^"]*)"/);
+ const typeMatch = attrs.match(/type="([^"]*)"/);
+ const name = nameMatch ? nameMatch[1] : "";
+ const type = typeMatch ? ` (\`${typeMatch[1]}\`)` : "";
+ return `- **\`${name}\`**${type} — ${desc.trim()}`;
+ },
+ );
+
+ // --- Icon → just remove ---
+ content = content.replace(/<Icon\s[^>]*\/>/gi, "");
+ content = content.replace(/<Icon\s[^>]*>[^<]*<\/Icon>/gi, "");
+
+ // --- CopyCommand → code block ---
+ content = content.replace(
+ /<CopyCommand\s+command="([^"]*)"[^>]*\/>/gi,
+ (_, cmd) => {
+ return "```bash\n" + cmd + "\n```";
+ },
+ );
+
+ // --- Columns → just keep content ---
+ content = content.replace(/<\/?Columns[^>]*>/gi, "");
+
+ // --- Any remaining self-closing custom components → remove ---
+ content = content.replace(/<[A-Z]\w*\s[^>]*\/>/g, "");
+
+ // --- Any remaining paired custom components → keep inner content ---
+ content = content.replace(
+ /<([A-Z]\w*)(?:\s[^>]*)?>[\s]*([\s\S]*?)[\s]*<\/\1>/g,
+ (_, _tag, inner) => inner.trim(),
+ );
+
+ // --- Clean up: remove excessive blank lines ---
+ content = content.replace(/\n{4,}/g, "\n\n\n");
+
+ // --- Restore code blocks ---
+ content = content.replace(
+ /__CODE_BLOCK_(\d+)__/g,
+ (_, index) => codeBlocks[parseInt(index)],
+ );
+
+ return content;
+}
+
+// ---------------------------------------------------------------------------
+// Frontmatter handling
+// ---------------------------------------------------------------------------
+
+export function extractFrontmatter(content) {
+ const match = content.match(/^---\n([\s\S]*?)\n---\n/);
+ if (!match) return { frontmatter: null, body: content };
+ return { frontmatter: match[0], body: content.slice(match[0].length) };
+}
+
+// ---------------------------------------------------------------------------
+// Link rewriting
+// ---------------------------------------------------------------------------
+
+export function rewriteLinks(content, fileRelDir) {
+ return content.replace(
+ /\[([^\]]*)\]\(\/(developer|api-reference|integrations)(\/[^)]*)\)/g,
+ (match, text, prefix, rest) => {
+ const [pathPart, anchor] = rest.split("#", 2);
+ const targetPath = prefix + pathPart;
+ const relPath = relative(fileRelDir, targetPath) || ".";
+ const suffix = anchor ? `#${anchor}` : "";
+ return `[${text}](${relPath}.md${suffix})`;
+ },
+ );
+}
diff --git a/packages/docs/tests/convert.test.js b/packages/docs/tests/convert.test.js
new file mode 100644
index 0000000000..4a90ba13d3
--- /dev/null
+++ b/packages/docs/tests/convert.test.js
@@ -0,0 +1,383 @@
+import { describe, it, expect } from 'vitest'
+import { convertContent, resolveImports, extractFrontmatter, rewriteLinks } from '../scripts/convert.js'
+
+// ---------------------------------------------------------------------------
+// extractFrontmatter
+// ---------------------------------------------------------------------------
+
+describe('extractFrontmatter', () => {
+ it('extracts YAML frontmatter', () => {
+ const input = '---\ntitle: Hello\n---\nBody content'
+ const { frontmatter, body } = extractFrontmatter(input)
+ expect(frontmatter).toBe('---\ntitle: Hello\n---\n')
+ expect(body).toBe('Body content')
+ })
+
+ it('returns null frontmatter when none present', () => {
+ const input = 'Just body content'
+ const { frontmatter, body } = extractFrontmatter(input)
+ expect(frontmatter).toBeNull()
+ expect(body).toBe('Just body content')
+ })
+
+ it('handles multi-field frontmatter', () => {
+ const input = '---\ntitle: Test\ndescription: A test page\n---\nBody'
+ const { frontmatter, body } = extractFrontmatter(input)
+ expect(frontmatter).toContain('title: Test')
+ expect(frontmatter).toContain('description: A test page')
+ expect(body).toBe('Body')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertContent — Callouts
+// ---------------------------------------------------------------------------
+
+describe('convertContent — callouts', () => {
+ it('converts <Info> to blockquote', () => {
+ const input = '<Info>\nThis is important.\n</Info>'
+ expect(convertContent(input)).toContain('> **INFO:** This is important.')
+ })
+
+ it('converts <Warning> to blockquote', () => {
+ const input = '<Warning>\nBe careful!\n</Warning>'
+ expect(convertContent(input)).toContain('> **WARNING:** Be careful!')
+ })
+
+ it('converts <Tip> to blockquote', () => {
+ const input = '<Tip>\nA helpful tip.\n</Tip>'
+ expect(convertContent(input)).toContain('> **TIP:** A helpful tip.')
+ })
+
+ it('converts <Note> to blockquote', () => {
+ const input = '<Note>\nTake note.\n</Note>'
+ expect(convertContent(input)).toContain('> **NOTE:** Take note.')
+ })
+
+ it('handles multiline callout content', () => {
+ const input = '<Info>\nLine one.\nLine two.\n</Info>'
+ const result = convertContent(input)
+ expect(result).toContain('> **INFO:** Line one.\n> Line two.')
+ })
+
+ it('is case-insensitive', () => {
+ const input = '<info>\nLowercase tag.\n</info>'
+ expect(convertContent(input)).toContain('> **INFO:** Lowercase tag.')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertContent — Tabs
+// ---------------------------------------------------------------------------
+
+describe('convertContent — tabs', () => {
+ it('converts tabs to labeled sections', () => {
+ const input = `<Tabs>
+ <Tab title="Ruby">
+ Ruby content here.
+ </Tab>
+ <Tab title="JavaScript">
+ JS content here.
+ </Tab>
+</Tabs>`
+ const result = convertContent(input)
+ expect(result).toContain('**Ruby:**')
+ expect(result).toContain('Ruby content here.')
+ expect(result).toContain('**JavaScript:**')
+ expect(result).toContain('JS content here.')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertContent — Steps
+// ---------------------------------------------------------------------------
+
+describe('convertContent — steps', () => {
+ it('converts steps to numbered sections', () => {
+ const input = `<Steps>
+ <Step title="Install">
+ Run npm install.
+ </Step>
+ <Step title="Configure">
+ Edit config file.
+ </Step>
+</Steps>`
+ const result = convertContent(input)
+ expect(result).toContain('**Step 1: Install**')
+ expect(result).toContain('Run npm install.')
+ expect(result).toContain('**Step 2: Configure**')
+ expect(result).toContain('Edit config file.')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertContent — CodeGroup
+// ---------------------------------------------------------------------------
+
+describe('convertContent — CodeGroup', () => {
+ it('strips CodeGroup tags, keeps code blocks', () => {
+ const input = `<CodeGroup>
+
+\`\`\`ruby
+puts "hello"
+\`\`\`
+
+\`\`\`javascript
+console.log("hello")
+\`\`\`
+
+</CodeGroup>`
+ const result = convertContent(input)
+ expect(result).not.toContain('CodeGroup')
+ expect(result).toContain('puts "hello"')
+ expect(result).toContain('console.log("hello")')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertContent — Accordion
+// ---------------------------------------------------------------------------
+
+describe('convertContent — accordion', () => {
+ it('converts Accordion to details/summary', () => {
+ const input = `<Accordion title="Click to expand">
+ Hidden content here.
+</Accordion>`
+ const result = convertContent(input)
+ expect(result).toContain('<details>')
+ expect(result).toContain('<summary>Click to expand</summary>')
+ expect(result).toContain('Hidden content here.')
+ expect(result).toContain('</details>')
+ })
+
+ it('strips AccordionGroup wrapper', () => {
+ const input = `<AccordionGroup>
+ <Accordion title="Item 1">Content 1</Accordion>
+ <Accordion title="Item 2">Content 2</Accordion>
+</AccordionGroup>`
+ const result = convertContent(input)
+ expect(result).not.toContain('AccordionGroup')
+ expect(result).toContain('<summary>Item 1</summary>')
+ expect(result).toContain('<summary>Item 2</summary>')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertContent — Cards
+// ---------------------------------------------------------------------------
+
+describe('convertContent — cards', () => {
+ it('converts Card with title and href to link', () => {
+ const input = '<Card title="Products" href="/developer/core-concepts/products">Product docs</Card>'
+ const result = convertContent(input)
+ expect(result).toContain('- [Products](/developer/core-concepts/products) — Product docs')
+ })
+
+ it('converts Card with title only to bold', () => {
+ const input = '<Card title="Products">Product docs</Card>'
+ const result = convertContent(input)
+ expect(result).toContain('- **Products** — Product docs')
+ })
+
+ it('strips CardGroup wrapper', () => {
+ const input = '<CardGroup cols={2}>\n<Card title="A">a</Card>\n</CardGroup>'
+ const result = convertContent(input)
+ expect(result).not.toContain('CardGroup')
+ expect(result).toContain('- **A** — a')
+ })
+
+ it('converts self-closing Card', () => {
+ const input = '<Card title="Link" href="/page" />'
+ const result = convertContent(input)
+ expect(result).toContain('- [Link](/page)')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertContent — Frame
+// ---------------------------------------------------------------------------
+
+describe('convertContent — Frame', () => {
+ it('strips Frame wrapper, keeps content', () => {
+ const input = '<Frame caption="Dashboard">\n <img src="/images/dash.png" />\n</Frame>'
+ const result = convertContent(input)
+ expect(result).not.toContain('Frame')
+ expect(result).toContain('<img src="/images/dash.png" />')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertContent — ResponseField / ParamField
+// ---------------------------------------------------------------------------
+
+describe('convertContent — API field components', () => {
+ it('converts ResponseField', () => {
+ const input = '<ResponseField name="email" type="string">\n The user email\n</ResponseField>'
+ const result = convertContent(input)
+ expect(result).toContain('- **`email`** (`string`) — The user email')
+ })
+
+ it('converts ParamField with body attr', () => {
+ const input = '<ParamField body="name" type="string">\n Product name\n</ParamField>'
+ const result = convertContent(input)
+ expect(result).toContain('- **`name`** (`string`) — Product name')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertContent — misc components
+// ---------------------------------------------------------------------------
+
+describe('convertContent — misc', () => {
+ it('removes Icon components', () => {
+ const input = 'Before <Icon name="check" /> after'
+ expect(convertContent(input)).toBe('Before after')
+ })
+
+ it('converts CopyCommand to code block', () => {
+ const input = '<CopyCommand command="npm install spree" />'
+ const result = convertContent(input)
+ expect(result).toContain('```bash\nnpm install spree\n```')
+ })
+
+ it('strips Columns wrapper', () => {
+ const input = '<Columns>\nContent\n</Columns>'
+ const result = convertContent(input)
+ expect(result).not.toContain('Columns')
+ expect(result).toContain('Content')
+ })
+
+ it('strips unknown paired components, keeps content', () => {
+ const input = '<SectionHeading size="lg">\nMy Section\n</SectionHeading>'
+ const result = convertContent(input)
+ expect(result).not.toContain('SectionHeading')
+ expect(result).toContain('My Section')
+ })
+
+ it('removes unknown self-closing components', () => {
+ const input = 'Text <CustomWidget prop="val" /> more text'
+ expect(convertContent(input)).toBe('Text more text')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// convertContent — code block protection
+// ---------------------------------------------------------------------------
+
+describe('convertContent — code block protection', () => {
+ it('does not convert components inside code blocks', () => {
+ const input = '```html\n<Info>This should stay</Info>\n```'
+ const result = convertContent(input)
+ expect(result).toContain('<Info>This should stay</Info>')
+ expect(result).not.toContain('**INFO:**')
+ })
+
+ it('does not convert components inside inline code', () => {
+ const input = 'Use `<Info>` for callouts'
+ const result = convertContent(input)
+ expect(result).toContain('`<Info>`')
+ })
+
+ it('collapses excessive blank lines', () => {
+ const input = 'Line 1\n\n\n\n\n\nLine 2'
+ const result = convertContent(input)
+ expect(result).toBe('Line 1\n\n\nLine 2')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// resolveImports
+// ---------------------------------------------------------------------------
+
+describe('resolveImports', () => {
+ it('removes import lines', () => {
+ const input = `import Foo from '/snippets/foo.mdx'\n\nBody content`
+ const result = resolveImports(input)
+ expect(result).not.toContain('import')
+ expect(result).toContain('Body content')
+ })
+
+ it('replaces self-closing component with snippet content', () => {
+ const input = `import MySnippet from '/snippets/my.mdx'\n\n<MySnippet />`
+ const resolver = (path) => {
+ if (path === '/snippets/my.mdx') return 'Inlined content'
+ return ''
+ }
+ const result = resolveImports(input, resolver)
+ expect(result).toContain('Inlined content')
+ expect(result).not.toContain('MySnippet')
+ })
+
+ it('ignores non-snippet imports', () => {
+ const input = `import { createClient } from '@spree/sdk'\n\nBody`
+ const result = resolveImports(input)
+ // Non-snippet imports are still removed (they're JS imports, not useful in MD)
+ expect(result).toContain('Body')
+ })
+
+ it('handles multiple snippet imports', () => {
+ const input = `import A from '/snippets/a.mdx'\nimport B from '/snippets/b.mdx'\n\n<A />\n<B />`
+ const resolver = (path) => {
+ if (path === '/snippets/a.mdx') return 'Content A'
+ if (path === '/snippets/b.mdx') return 'Content B'
+ return ''
+ }
+ const result = resolveImports(input, resolver)
+ expect(result).toContain('Content A')
+ expect(result).toContain('Content B')
+ })
+})
+
+// ---------------------------------------------------------------------------
+// rewriteLinks
+// ---------------------------------------------------------------------------
+
+describe('rewriteLinks', () => {
+ it('converts absolute links to relative .md paths', () => {
+ const input = '[Products](/developer/core-concepts/products)'
+ const result = rewriteLinks(input, 'developer/core-concepts')
+ expect(result).toBe('[Products](products.md)')
+ })
+
+ it('handles cross-directory links', () => {
+ const input = '[Store API](/api-reference/store-api/introduction)'
+ const result = rewriteLinks(input, 'developer/core-concepts')
+ expect(result).toBe('[Store API](../../api-reference/store-api/introduction.md)')
+ })
+
+ it('preserves anchors', () => {
+ const input = '[Translations](/developer/core-concepts/translations#resource-translations)'
+ const result = rewriteLinks(input, 'developer/core-concepts')
+ expect(result).toBe('[Translations](translations.md#resource-translations)')
+ })
+
+ it('handles links from nested directory to sibling', () => {
+ const input = '[Admin](/developer/admin/navigation)'
+ const result = rewriteLinks(input, 'developer/customization')
+ expect(result).toBe('[Admin](../admin/navigation.md)')
+ })
+
+ it('does not rewrite external links', () => {
+ const input = '[GitHub](https://github.com/spree/spree)'
+ const result = rewriteLinks(input, 'developer/core-concepts')
+ expect(result).toBe('[GitHub](https://github.com/spree/spree)')
+ })
+
+ it('does not rewrite links to non-doc paths', () => {
+ const input = '[Home](/)'
+ const result = rewriteLinks(input, 'developer/core-concepts')
+ expect(result).toBe('[Home](/)')
+ })
+
+ it('handles links from root-level files', () => {
+ const input = '[Products](/developer/core-concepts/products)'
+ const result = rewriteLinks(input, 'developer')
+ expect(result).toBe('[Products](core-concepts/products.md)')
+ })
+
+ it('handles integrations links', () => {
+ const input = '[Stripe](/integrations/payments/stripe)'
+ const result = rewriteLinks(input, 'developer/core-concepts')
+ expect(result).toBe('[Stripe](../../integrations/payments/stripe.md)')
+ })
+})
diff --git a/packages/docs/vitest.config.js b/packages/docs/vitest.config.js
new file mode 100644
index 0000000000..d91102ff79
--- /dev/null
+++ b/packages/docs/vitest.config.js
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({
+ test: {
+ include: ['tests/**/*.test.js'],
+ },
+})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e0f5c2c429..2028b2ff42 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -120,6 +120,12 @@ importers:
specifier: ^4.0.18
+ packages/docs:
+ devDependencies:
+ vitest:
+ specifier: ^4.0.18
+
packages/next:
devDependencies:
'@changesets/changelog-github':