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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Shrink package READMEs to identity + quick start + docs links (#14324)
Damian Legawiec63f4a1eb1b08
diff --git a/packages/admin-sdk/README.md b/packages/admin-sdk/README.mdindex 71e6c4f735..dcccd61984 100644--- a/packages/admin-sdk/README.md+++ b/packages/admin-sdk/README.md@@ -8,10 +8,6 @@ Official TypeScript SDK for the **Spree Commerce Admin API** — manage products```bashnpm install @spree/admin-sdk-# or-yarn add @spree/admin-sdk-# or-pnpm add @spree/admin-sdk```## Quick start@@ -21,290 +17,37 @@ import { createAdminClient } from '@spree/admin-sdk'const client = createAdminClient({baseUrl: 'https://store.example.com',- secretKey: 'sk_xxx',+ secretKey: 'sk_xxx', // server-to-server; JWT auth for admin UIs also supported})-// List orders-const { data: orders, meta } = await client.orders.list({+const { data: orders } = await client.orders.list({status_eq: 'complete',sort: '-completed_at',limit: 25,})-// Create an order in one shot-const order = await client.orders.create({- email: '[email protected]',- currency: 'USD',- items: [{ variant_id: 'variant_xxx', quantity: 1 }],- shipping_address: {- first_name: 'Jane',- last_name: 'Doe',- address1: '350 Fifth Avenue',- city: 'New York',- postal_code: '10118',- country_iso: 'US',- state_abbr: 'NY',- phone: '+1 212 555 1234',- },-})--// Manage a customerconst customer = await client.customers.create({email: '[email protected]',first_name: 'Jane',last_name: 'Doe',tags: ['wholesale'],})--await client.customers.addresses.create(customer.id, {- first_name: 'Jane',- last_name: 'Doe',- address1: '350 Fifth Avenue',- city: 'New York',- postal_code: '10118',- country_iso: 'US',- state_abbr: 'NY',- phone: '+1 212 555 1234',- is_default_shipping: true,-})-```--## Authentication--The Admin API supports two authentication methods.--### Secret API key (server-to-server)--Use a **secret API key** (`sk_…`) for backend integrations. Each key carries a list of [scopes](https://spreecommerce.org/docs/api-reference/admin-api/authentication#permissions) granted at creation time. Never embed secret keys in client-side code, mobile apps, or public repositories.--```typescript-const client = createAdminClient({- baseUrl: 'https://store.example.com',- secretKey: 'sk_xxx',-})-```--### JWT bearer token (admin SPA)--Authenticate as an admin user and use the returned JWT for subsequent requests. JWT-authenticated requests use [CanCanCan abilities](https://github.com/CanCanCommunity/cancancan) instead of scopes.--The refresh token never appears in JSON — the server sets it as an `HttpOnly` cookie scoped to `/api/v3/admin/auth`, and the SDK sends requests with `credentials: 'include'` by default so the cookie flows automatically. The access token is the only credential your code holds.--```typescript-// A cookie-auth SPA can start with no credentials at all and bootstrap-// from the refresh cookie:-const client = createAdminClient({ baseUrl: 'https://store.example.com' })--// Login returns { token, user } — the refresh token lands in the cookie-const { token, user } = await client.auth.login({- email: '[email protected]',- password: 'password123',-})-client.setToken(token)--// Refresh takes no arguments — it's driven entirely by the cookie-client.onUnauthorized(async () => {- const { token: fresh } = await client.auth.refresh()- client.setToken(fresh)- return true-})--// Logout destroys the refresh token server-side and clears the cookie-await client.auth.logout()-```--`auth.login()` also accepts third-party identity-provider payloads (`{ provider: 'auth0', token: '<jwt>' }`) when the server has a matching strategy registered in `Spree.store_authentication_strategies`.--## Resource clients--| Client | Endpoints |-|---|---|-| `client.orders` | List, get, create, update, delete, complete, cancel, approve, resume, resend confirmation. Nested: `items`, `payments` (incl. capture/void), `fulfillments` (incl. fulfill/cancel/resume/split), `refunds`, `giftCards`, `storeCredits`, `adjustments`. |-| `client.customers` | CRUD plus bulk group/tag operations. Nested: `addresses`, `creditCards`, `storeCredits`. |-| `client.customerGroups` | CRUD on customer groups. |-| `client.products` | CRUD, clone, and bulk operations (status, categories, channels, tags, destroy). Nested: `media`, `variants` (with their own `media`). |-| `client.variants` | Top-level variant search across products. |-| `client.optionTypes` | CRUD on option types and values. |-| `client.categories` | List categories. |-| `client.tags` | Autocomplete tag names per taggable type. |-| `client.prices` | CRUD plus `bulkUpsert` / `bulkDestroy` for variant prices. |-| `client.priceLists` | CRUD, activate/deactivate, and price-list rule types. |-| `client.promotions` | CRUD. Nested: `actions`, `rules`, `couponCodes`. Companion lookups: `client.promotionActions.types/calculators`, `client.promotionRules.types`. |-| `client.giftCards` / `client.giftCardBatches` | Gift card CRUD and batch creation. |-| `client.storeCreditCategories` | List/read store credit categories. |-| `client.paymentMethods` | CRUD plus `types` (available gateway types). |-| `client.taxCategories` | CRUD on tax categories. |-| `client.stockLocations` | CRUD on stock locations. |-| `client.stockItems` | List, get, update, delete stock items. |-| `client.stockTransfers` | List, get, create, delete stock transfers. |-| `client.channels` | CRUD plus `addProducts` / `removeProducts`. |-| `client.markets` | CRUD on markets. |-| `client.countries` | List and read countries (for address dropdowns). |-| `client.customFieldDefinitions` | CRUD on custom field definitions. |-| `client.exports` | Create and track CSV exports (products, orders, customers, …). |-| `client.adminUsers` | List, get, update, delete admin users. |-| `client.invitations` | Staff invitations — list, get, create, delete, resend. |-| `client.roles` | List and read roles. |-| `client.apiKeys` | CRUD plus revoke for API keys. |-| `client.allowedOrigins` | CRUD on CORS allowed origins. |-| `client.webhookEndpoints` | CRUD, send test, enable/disable. Nested: `deliveries` (list, get, redeliver). |-| `client.dashboard` | Sales analytics. |-| `client.store` | Store profile (get, update). |-| `client.me` | Current admin user + permissions. |-| `client.auth` | Login (email/password or identity provider), cookie-driven refresh, logout, invitation lookup/acceptance. |-| `client.directUploads` | Pre-signed Active Storage uploads (used by media flows). |--### Custom fields--Resources that support custom fields expose a `customFields` accessor taking the parent ID first — `client.products.customFields.list('prod_xxx')` — and the generic escape hatch covers everything else:--```typescript-await client.customFields('Spree::Product', 'prod_xxx').list()-```--## Querying--Collection endpoints support [Ransack](https://activerecord-hackery.github.io/ransack/) filters via flat parameters:--```typescript-const orders = await client.orders.list({- status_eq: 'complete',- total_gteq: 100,- email_cont: '@example.com',- user_id_eq: 'cus_xxx', // resource IDs work directly- sort: '-completed_at',- page: 2,- limit: 50,- expand: ['items', 'customer'],-})-```--The SDK wraps filter keys in `q[…]` automatically.--## Error handling--Every non-2xx response throws a `SpreeError`:--```typescript-import { SpreeError } from '@spree/admin-sdk'--try {- await client.orders.update(orderId, { email })-} catch (err) {- if (err instanceof SpreeError) {- console.log(err.code) // e.g. 'cart_already_updated'- console.log(err.status) // e.g. 409- console.log(err.details) // optional structured context- }-}-```--When a request fails because the API key lacks the required scope, the error has `code: 'access_denied'` and `details.required_scope` carries the missing scope name.--## TypeScript support--Full TypeScript support with generated types from the API serializers:--```typescript-import type {- AdminOrder,- AdminProduct,- AdminCustomer,- AdminFulfillment,- AdminPayment,- PaginatedResponse,-} from '@spree/admin-sdk'--const orders: PaginatedResponse<AdminOrder> = await client.orders.list()-const product: AdminProduct = await client.products.get('prod_xxx')-```--Admin types are exported with the `Admin` prefix to distinguish them from the customer-facing `@spree/sdk` types (which use `Store` prefixes for the same domain entities). Admin types include fields and relationships hidden from the Store API.--## Custom fetch--You can provide a custom fetch implementation:--```typescript-const client = createAdminClient({- baseUrl: 'https://store.example.com',- secretKey: 'sk_xxx',- fetch: customFetchImplementation,-})```## Documentation-- **SDK guides:** [spreecommerce.org/docs/developer/sdk/admin/quickstart](https://spreecommerce.org/docs/developer/sdk/admin/quickstart)-- **Full API reference:** [spreecommerce.org/docs/api-reference/admin-api](https://spreecommerce.org/docs/api-reference/admin-api/introduction)-- **Authentication & scopes:** [spreecommerce.org/docs/api-reference/admin-api/authentication](https://spreecommerce.org/docs/api-reference/admin-api/authentication)-- **Errors:** [spreecommerce.org/docs/api-reference/admin-api/errors](https://spreecommerce.org/docs/api-reference/admin-api/errors)-- **Querying:** [spreecommerce.org/docs/api-reference/admin-api/querying](https://spreecommerce.org/docs/api-reference/admin-api/querying)--## Development+The full guides live on the docs site — this README intentionally stays short:-### Setup+- [Admin SDK quickstart](https://spreecommerce.org/docs/developer/sdk/admin/quickstart)+- [Authentication](https://spreecommerce.org/docs/developer/sdk/admin/authentication) — scoped secret keys vs. admin JWT+- [Resources](https://spreecommerce.org/docs/developer/sdk/admin/resources) — every resource client and its methods+- [Querying & errors](https://spreecommerce.org/docs/developer/sdk/admin/querying-and-errors) — filtering, sorting, pagination, `SpreeError`+- [Extending the client](https://spreecommerce.org/docs/developer/sdk/admin/extending) — custom endpoints+- [Admin API reference](https://spreecommerce.org/docs/api-reference/admin-api/introduction)-```bash-cd packages/admin-sdk-pnpm install-```+## Contributing-### Scripts--| Command | Description |-|---|---|-| `pnpm test` | Run tests once |-| `pnpm test:watch` | Run tests in watch mode |-| `pnpm typecheck` | Type-check with `tsc --noEmit` |-| `pnpm lint` | Lint with Biome |-| `pnpm lint:fix` | Lint and auto-fix with Biome |-| `pnpm format` | Format source with Biome |-| `pnpm build` | Build CJS + ESM bundles with `tsup` |-| `pnpm dev` | Build in watch mode |-| `pnpm generate:admin-client` | Regenerate the resource client from the OpenAPI spec |--### Type generation pipeline--When the upstream Admin API serializers in `spree/api` change, regenerate types from the monorepo root:--```bash-# 1. Regenerate TypeScript types from Alba serializers-cd spree/api && bundle exec rake typelizer:generate--# 2. Rebuild the SDK (consumes the generated types)-cd packages/admin-sdk && pnpm build--# 3. Run tests to confirm nothing broke-pnpm test-```--Generated TypeScript types land in `src/types/generated/`; do not edit by hand.--### Releasing--This package uses [Changesets](https://github.com/changesets/changesets) for version management and publishing.--**After making changes:**--```bash-pnpm changeset-```--This prompts you to select a semver bump type (patch/minor/major) and write a summary. A changeset file is created in `.changeset/`.--**How releases work:**--1. Changeset files are committed with your PR-2. When merged to `main`, a GitHub Action creates a "Version Packages" PR that bumps the version and updates the CHANGELOG-3. When that PR is merged, the package is automatically published to npm under the `next` dist-tag (Developer Preview), so `npm install @spree/admin-sdk` does not pick it up as `latest`--**Manual release (if needed):**--```bash-pnpm version # Apply changesets and bump version-pnpm release # Build and publish to npm-```+The SDK lives in the [spree/spree monorepo](https://github.com/spree/spree) under `packages/admin-sdk` — see the repository docs for the development setup and the serializer → types → Zod generation pipeline.## Licensediff --git a/packages/cli/README.md b/packages/cli/README.mdindex 0f5ce04635..31e2f87c57 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -1,24 +1,8 @@# @spree/cli-CLI for managing [Spree Commerce](https://spreecommerce.org) projects.+CLI for managing [Spree Commerce](https://spreecommerce.org) projects — Docker-based dev stack, generators, API keys, and a gh-style Admin API client.-Automatically included in projects created with [`create-spree-app`](https://www.npmjs.com/package/create-spree-app). Can also be installed standalone.--## Installation--Already included when you scaffold a project with `create-spree-app`. To install separately:--```bash-npm install @spree/cli-```--Or run directly with npx:--```bash-npx @spree/cli <command>-```--Or install globally:+Automatically included in projects created with [`create-spree-app`](https://spreecommerce.org/docs/developer/create-spree-app/quickstart). Can also be installed standalone:```bashnpm install -g @spree/cli@@ -27,220 +11,31 @@ spree <command>## Commands-Run these from your Spree project directory.--### `spree dev`--Run the app in the foreground — prints connection info, then streams web + worker logs (like `vite dev`).--```bash-spree dev-```--Press `Ctrl+C` to stop web + worker. The databases (postgres, redis, meilisearch) keep running for a fast next boot — `spree stop` shuts everything down.--### `spree stop`--Stop all running services.--```bash-spree stop-```--### `spree update`--Pull the latest Spree Docker image and recreate containers. Database migrations run automatically on startup via `db:prepare`.--```bash-spree update-```--To pin a specific version, edit `SPREE_VERSION_TAG` in your `.env` file:--```-SPREE_VERSION_TAG=5.4-```--### `spree eject`--Switch from the prebuilt Docker image to building from your local `backend/` directory. This lets you customize the Rails app — add gems, override models, add migrations, etc.--```bash-spree eject-```--After ejecting, edit files in `backend/` and run `spree dev` to rebuild and restart.--### `spree logs [service]`--Stream logs from a service. Defaults to `web`.--```bash-spree logs # web server logs-spree logs worker # background job logs-```--### `spree console`--Open an interactive Rails console inside the running container.--```bash-spree console-```--### `spree shell`--Open an interactive bash shell inside the web container. If the container is down, a one-off container is started against the same volumes instead.--```bash-spree shell-spree bash # alias-```--### `spree rspec`--Run the RSpec test suite inside the web container with `RAILS_ENV=test`. Everything after `rspec` is passed through to RSpec.--```bash-spree rspec # full suite-spree rspec spec/models/product_spec.rb # one file-spree rspec spec/models/product_spec.rb:15 # one example-spree rspec --format documentation-```--Before the first run, create the test database with `spree rails db:test:prepare`.--### `spree user create`--Create an admin user. Prompts interactively for email and password, or accepts flags for scripting.--```bash-# Interactive-spree user create--# Non-interactive-spree user create --email [email protected] --password secret123-```--The user is automatically assigned the `admin` role on the default store.--### `spree api-key create`--Create a Store API (publishable) or Admin API (secret) key. Prompts interactively for name and type, or accepts flags.--```bash-# Interactive-spree api-key create--# Non-interactive-spree api-key create --name "My Storefront" --type publishable-spree api-key create --name "Admin Integration" --type secret --scopes read_orders,write_products-```--Secret keys require at least one scope (`read_all` for a read-only key, `write_all` for full access, or granular `read_*`/`write_*` pairs).--**Important:** Secret key tokens are displayed only once at creation time and cannot be retrieved later. Save them immediately.--### `spree api-key list`--List all API keys for the default store with their name, type, token/prefix, creation date, and status.--```bash-spree api-key list-```--### `spree api-key revoke`--Revoke an API key by its token (publishable) or token prefix (secret).--```bash-spree api-key revoke pk_abc123def456...-```--### `spree api`--Call the Admin API directly with generic `get`/`post`/`patch`/`delete` commands. Works against any Spree 5.5+ instance — inside a project it self-provisions a **read-only** key via the dev stack on first use (saved to `.spree/credentials.json`, gitignored). For other servers set `SPREE_API_KEY` (the host defaults to `http://localhost:3000`; add `SPREE_BASE_URL` for a remote store) or save a profile with `spree auth login`.--```bash-spree api get /products -q status_eq=active --sort -created_at --limit 10-spree api get /orders/ord_x8k2J9aQ --expand items,payments-spree api post /products -d '{"name":"Classic Tee","prices":[{"currency":"USD","amount":"29.99"}]}'-spree api patch /orders/ord_x8k2J9aQ/cancel-spree api delete /products/prod_86Rf07xd--spree api endpoints --resource orders # endpoints + required scopes (offline)-spree api schema "POST /orders" # request/response schema (offline)-spree api status # resolved credentials + server check-```--Output is JSON on stdout — indented and colored in a terminal, compact and uncolored when piped (so it feeds cleanly into `jq`). `--format table` renders collections for humans. `--fields name,price` trims the response (the `id` is always included). API errors exit `1` with the error envelope on stderr — scope denials include the exact `--scopes` remediation.--### `spree completion`--Output a shell completion script (`bash`, `zsh`, or `fish`). Tab-completion suggests resource paths, Ransack predicate stems, and scope names — offline from the bundled spec.--```bash-eval "$(spree completion zsh)" # add to ~/.zshrc (bash/fish also supported)-```--### `spree auth`--Manage saved Admin API credentials for remote stores (profiles in `~/.config/spree/config.json`).--```bash-spree auth login --profile prod --base-url https://store.example.com # key read from a prompt-spree api get /orders --profile prod-spree auth status-spree auth list-spree auth logout --profile prod-```--### `spree seed`--Run database seeds.--```bash-spree seed-```--### `spree sample-data`--Load sample products, categories, customers, and images.--```bash-spree sample-data-```--## How It Works--The CLI detects your project by looking for `docker-compose.yml` in the current directory. All commands execute via `docker compose` against the running Spree containers.--- **Port** is read from `SPREE_PORT` in your `.env` file (default: `3000`)-- **User and API key commands** run Ruby scripts via `docker compose exec web bin/rails runner`-- **Service commands** (`dev`, `stop`, `update`) are thin wrappers around `docker compose`--## Using with npm scripts--Projects created with `create-spree-app` include convenience scripts in `package.json`:--```bash-npm run dev # spree dev-npm run stop # spree stop-npm run update # spree update-npm run eject # spree eject-npm run logs # spree logs-npm run logs:worker # spree logs worker-npm run console # spree console-npm run seed # spree seed-npm run load-sample-data # spree sample-data-```--## Learn More--- [Spree Documentation](https://spreecommerce.org/docs)-- [Store API Reference](https://spreecommerce.org/docs/api-reference/introduction)-- [create-spree-app](https://www.npmjs.com/package/create-spree-app)-- [Spree GitHub](https://github.com/spree/spree)+Run from your Spree project directory:++| Command | Description |+|---------|-------------|+| `spree dev` | Run the app in the foreground — streams logs, Ctrl+C stops it. First run completes setup automatically; co-runs the React Dashboard dev server when `apps/dashboard` exists |+| `spree stop` | Stop backend services |+| `spree update` | Pull the latest Spree image and restart (runs migrations automatically) |+| `spree eject` | Switch from the prebuilt image to building from `backend/` |+| `spree add dashboard` | Add the React Dashboard (Developer Preview) to an existing project |+| `spree build --production` | Build the production image — the Spree API plus your dashboard, in one |+| `spree console` / `spree shell` / `spree logs` | Rails console, container shell, log tailing |+| `spree migrate` / `spree seed` / `spree sample-data` | Database tasks |+| `spree generate …` | Spree generators (models, API resources, subscribers, migrations) |+| `spree user create` / `spree api-key …` | Admin users and scoped API keys |+| `spree api get/post/patch/delete <path>` | Call the Admin API directly (`spree api endpoints` lists routes + scopes) |+| `spree rspec` | Run the backend test suite inside the container |++## Documentation++The full command reference lives on the docs site — this README intentionally stays short:++- [CLI quickstart](https://spreecommerce.org/docs/developer/cli/quickstart)+- [Admin API from the CLI](https://spreecommerce.org/docs/developer/cli/admin-api) — credentials, scopes, profiles+- [create-spree-app](https://spreecommerce.org/docs/developer/create-spree-app/quickstart)+- [Deployment](https://spreecommerce.org/docs/developer/deployment/docker)## Licensediff --git a/packages/create-spree-app/README.md b/packages/create-spree-app/README.mdindex f74e0f1472..08d95fd926 100644--- a/packages/create-spree-app/README.md+++ b/packages/create-spree-app/README.md@@ -1,6 +1,6 @@# create-spree-app-Scaffold a new [Spree Commerce](https://spreecommerce.org) project with a single command. Backend runs via Docker using pre-built images, with a full Rails app included for customization.+Scaffold a new [Spree Commerce](https://spreecommerce.org) project with a single command — a full Rails backend (the Spree API) running via Docker, an optional Next.js storefront, the React Dashboard behind `--react-dashboard`, and the `spree` CLI for day-to-day work. Setup completes automatically: image pulled, database seeded, API keys configured.## Quick Start@@ -8,117 +8,24 @@ Scaffold a new [Spree Commerce](https://spreecommerce.org) project with a singlenpx create-spree-app my-store```-This will walk you through an interactive setup:--1. Include **Next.js Storefront** (default: yes)-2. Optionally load sample data (products, categories, images)-3. Optionally start Docker services immediately--## CLI Flags--For non-interactive usage:--```bash-npx create-spree-app my-store --no-storefront --no-sample-data --no-start-```-| Flag | Description ||------|-------------|+| `--react-dashboard` | Include the React Dashboard (Developer Preview — also available later via `spree add dashboard`) || `--no-storefront` | Skip Next.js storefront setup || `--no-sample-data` | Skip loading sample products |-| `--no-start` | Don't start Docker services |+| `--no-start` | Don't start Docker services (the first `dev` run completes setup instead) || `--port <number>` | Port for the Spree backend (default: `3000`) |-| `--use-npm` | Use npm as package manager |-| `--use-yarn` | Use yarn as package manager |-| `--use-pnpm` | Use pnpm as package manager |--## What You Get--```-my-store/-├── docker-compose.yml # Spree backend (prebuilt image) + Postgres + Redis-├── docker-compose.dev.yml # Alternative: build from local backend/-├── .env # SECRET_KEY_BASE, SPREE_PORT-├── .gitignore-├── package.json # @spree/cli + convenience scripts-├── README.md-├── backend/ # Full Rails app (from spree/spree-starter)-│ ├── Gemfile-│ ├── Dockerfile-│ ├── config/-│ ├── app/-│ └── ...-└── apps/- └── storefront/ # Next.js app (unless --no-storefront)-```--## Prerequisites--- [Node.js](https://nodejs.org/) >= 20-- [Docker](https://docs.docker.com/get-docker/) (for running the backend)--## After Setup--### Admin Dashboard--Open http://localhost:3000/admin--- Email: `[email protected]`-- Password: `spree123`--### Store API+| `--use-npm` / `--use-yarn` / `--use-pnpm` | Package manager (auto-detected from how you run the command) |-http://localhost:3000/api/v3/store+## Documentation-### Storefront--```bash-cd my-store/apps/storefront-npm run dev-```--Open http://localhost:3001--## Customizing the Backend--The `backend/` directory contains a full Rails application with Spree installed. By default, the project uses a prebuilt Docker image. To switch to building from your local backend:--```bash-npx spree eject-```--This rebuilds the Docker image from `backend/` and restarts services. You can then:--- **Add gems** to `backend/Gemfile`-- **Override models** with decorators in `backend/app/models/`-- **Add controllers** in `backend/app/controllers/`-- **Configure Spree** in `backend/config/initializers/spree.rb`-- **Add migrations** with `cd backend && bin/rails generate migration`--## Useful Commands--Run these from your project directory (powered by [`@spree/cli`](https://www.npmjs.com/package/@spree/cli)):--| Command | Description |-|---------|-------------|-| `npm run dev` | Start backend services and stream logs |-| `npm run stop` | Stop backend services |-| `npm run eject` | Switch from prebuilt image to local backend builds |-| `npm run update` | Pull latest Spree image and restart |-| `npm run logs` | View backend logs |-| `npm run console` | Rails console |--You can also use the CLI directly for additional commands:--```bash-npx spree user create # Create an admin user-npx spree api-key create # Create an API key-npx spree api-key list # List API keys-```+The full guide — generated project structure, customization, deployment — lives on the docs site:-## Learn More+- [create-spree-app quickstart](https://spreecommerce.org/docs/developer/create-spree-app/quickstart)+- [Spree CLI](https://spreecommerce.org/docs/developer/cli/quickstart)+- [Deployment](https://spreecommerce.org/docs/developer/deployment/docker)-- [Spree Documentation](https://spreecommerce.org/docs)+Just evaluating Spree? Skip self-hosting and use a [hosted sandbox](https://spreecommerce.org).## Licensediff --git a/packages/dashboard-core/README.md b/packages/dashboard-core/README.mdindex b2ff532926..eb0d0bd294 100644--- a/packages/dashboard-core/README.md+++ b/packages/dashboard-core/README.md@@ -1,8 +1,8 @@# @spree/dashboard-core-Spree Dashboard framework. Registries, providers, infra hooks, the admin SDK client, and the `defineDashboardPlugin` extension API.+Spree Dashboard framework — registries, providers, infra hooks, the admin SDK client singleton, and the `defineDashboardPlugin` extension API.-This is the package plugin authors install. Use it to register nav entries, slot widgets, table column extensions, and settings pages from a separate npm package that gets imported into `@spree/dashboard` at boot.+This is the package plugin authors install. Use it to register nav entries, slot widgets, table column extensions, form fields, and settings pages from a separate npm package that `@spree/dashboard` activates at boot.## Install@@ -10,409 +10,42 @@ This is the package plugin authors install. Use it to register nav entries, slotpnpm add @spree/dashboard-core @spree/dashboard-ui```-Peer dependencies that the consuming app provides: `react`, `react-dom`, `@spree/admin-sdk`, `@spree/dashboard-ui`, `@tanstack/react-query`, `@tanstack/react-router`, `@tanstack/react-hotkeys`, `react-hook-form`, `react-i18next`, `i18next`, `sonner`.+**List `@spree/dashboard-core` (and React, the TanStack packages, i18next, …) as peer dependencies in your plugin.** The registries are module singletons — a bundled second copy would write to Maps the app never reads, a silent no-op. The [plugin distribution guide](https://spreecommerce.org/docs/developer/dashboard/plugins/distributing) covers the full peer list.-**Why peer deps:** the registries (nav, slot, table, settings-nav, form fields, custom field components) are module singletons. If your plugin bundles its own copy of `@spree/dashboard-core`, `registerSlot` writes to a different Map than the app's `<Slot>` reads — silent no-op. Same applies to React, the query client, the router instance, and the i18n singleton. pnpm dedupes these to a single instance as long as they're peers.--## What's in the box--```-@spree/dashboard-core-├── adminClient # @spree/admin-sdk instance, baseUrl wired to VITE_SPREE_API_URL-│-├── Providers (mount in your app shell, in this order)-│ ├── AuthProvider # JWT + refresh token, /auth/refresh on cold load-│ ├── PermissionProvider # /api/v3/admin/me → CanCanCan rules-│ └── StoreProvider # current store context (multi-store)-│-├── Registries (the four extension points)-│ ├── nav # sidebar items-│ ├── settingsNav # settings sub-shell groups + items-│ ├── slot # named injection points (`product.form_sidebar`, ...)-│ └── tables # column add/remove/update per list view-│-├── Infra hooks-│ ├── useAuth # { token, user, login(), logout() }-│ ├── usePermissions # CanCanCan rules + <Can> helper-│ ├── useStore # current store-│ ├── useResourceMutation # useMutation + toast + form-error mapping-│ ├── useDirectUpload # Active Storage direct-upload-│ ├── useGlobalSearch # cross-resource search-│ ├── useCommandPalette # ⌘K palette state-│ ├── useCopyToClipboard-│ ├── useScrolled-│ ├── useCountries # admin/countries (geo data, cached)-│ ├── useExport # CSV export jobs (polled)-│ └── useCustomFields # metafield definitions + values-│-├── i18n (i18next + react-i18next)-│ ├── Base translation namespace (`admin.actions.*`, `admin.common.*`, `admin.validation.*`, …)-│ ├── Trans, useTranslation # re-exported from react-i18next-│ └── i18n # the i18next singleton (call addResourceBundle to extend)-│-├── Helpers-│ ├── filtersToRansack # UI filter shape → Ransack params-│ ├── mapSpreeErrorsToForm # 422 → RHF setError-│ ├── formatPrice / getInitials-│ ├── Subject, Action # CanCanCan subject/action constants-│ └── queryClient # TanStack Query client singleton-│-└── defineDashboardPlugin # the one-call extension facade-```--Additional entry point:--- `@spree/dashboard-core/vite` — Vite plugin that wires Tailwind v4. See [Vite integration](#vite-integration).--## Vite integration--The dashboard relies on Tailwind v4, which doesn't scan `node_modules` by default and only accepts filesystem paths in `@source` directives (not bare package specifiers). The `spreeDashboardPlugin` from `@spree/dashboard-core/vite` resolves each Spree dashboard package and each host-named plugin through Node module resolution and injects matching `@source` directives into your CSS entry at build time. It also bundles `@tailwindcss/vite` itself so plugin ordering is guaranteed — hosts must NOT register `@tailwindcss/vite` separately.--### Using the full `@spree/dashboard` app shell--```ts-// host vite.config.ts-import { spreeDashboardPlugin } from '@spree/dashboard-core/vite'-import { TanStackRouterVite } from '@tanstack/router-plugin/vite'-import react from '@vitejs/plugin-react'-import { defineConfig } from 'vite'--export default defineConfig({- plugins: [- spreeDashboardPlugin({- plugins: [- '@my-store/orders-dashboard-plugin',- '@my-store/wishlists-dashboard-plugin',- ],- }),- TanStackRouterVite(),- react(),- ],-})-```--```css-/* host src/styles.css */-@import "@spree/dashboard/styles.css";-```--### Building a custom dashboard on `@spree/dashboard-core` + `@spree/dashboard-ui`--If you're not using `@spree/dashboard`'s app shell — e.g. a vendor portal or B2B buyer admin built directly on the registries and primitives — point `cssEntry` at your own CSS file:--```ts-// custom-dashboard vite.config.ts-import { spreeDashboardPlugin } from '@spree/dashboard-core/vite'--export default defineConfig({- plugins: [- spreeDashboardPlugin({- cssEntry: './src/admin.css',- plugins: ['@my-store/vendor-portal-plugin'],- }),- // host owns react, router, etc.- ],-})-```--```css-/* custom-dashboard src/admin.css */-@import "@spree/dashboard-ui/styles.css";-/* Tailwind auto-scans the host's own src/, so host-authored classes- work without configuration. The Vite plugin injects @source for- @spree/dashboard-core, @spree/dashboard-ui, and any named plugins. */-```--### `@spree/dashboard-ui` only (no `@spree/dashboard-core`)--If you only need design-system primitives and tokens, no registries, no providers — you don't need this Vite plugin at all. Install `@spree/dashboard-ui`, set up `@tailwindcss/vite` yourself, and import its stylesheet:--```css-@import "@spree/dashboard-ui/styles.css";-```--`dashboard-ui/styles.css` carries its own `@source` directives covering its components.--### Options+## Quick start```ts-spreeDashboardPlugin({- /**- * Path to the host's CSS entry file, relative to the host's project root.- * The plugin injects @source directives into this file. Defaults to- * `./src/styles.css`.- */- cssEntry: './src/styles.css',-- /**- * Names of installed dashboard plugin packages. Each must be a resolvable- * npm specifier. The plugin resolves each via Node module resolution and- * tells Tailwind to scan its source files.- */- plugins: ['@my-store/orders-plugin'],-})-```--### What plugin authors must do--Ship `src/` in their published package so Tailwind has source files to scan:--```json-// plugin's package.json-{- "name": "@my-store/orders-dashboard-plugin",- "main": "./src/index.ts",- "types": "./src/index.ts",- "files": ["src", "README.md"]-}-```--Plugin authors do NOT need to ship pre-built CSS, configure Tailwind, or care about the host's package manager — adding the plugin name to the host's `plugins: [...]` is enough.--## Plugin authoring — the basics--Your plugin is an npm package. Its entry module calls `defineDashboardPlugin({...})` at import time. The dashboard app imports your entry module before first render — every registry handles late registration via `useSyncExternalStore`, so even if your plugin loads asynchronously the sidebar/slots re-render.--```tsx-// my-spree-plugin/src/index.ts-import { defineDashboardPlugin, usePermissions } from '@spree/dashboard-core'-import { Card, CardHeader, CardTitle, CardContent } from '@spree/dashboard-ui'-import { BarChartIcon } from 'lucide-react'--function WishlistsWidget({ product }: { product: { id: string; wishlist_count: number } }) {- return (- <Card>- <CardHeader><CardTitle>Wishlists</CardTitle></CardHeader>- <CardContent>{product.wishlist_count} customers</CardContent>- </Card>- )-}+import { defineDashboardPlugin } from '@spree/dashboard-core/plugin'+import { PackageIcon } from 'lucide-react'+import { WishlistCard } from './wishlist-card'defineDashboardPlugin({- nav: [- { key: 'wishlists', label: 'Wishlists', path: '/wishlists', icon: BarChartIcon, position: 50 },- ],+ nav: [{ key: 'wishlists', label: 'Wishlists', path: '/wishlists', icon: PackageIcon }],slots: {- 'product.form_sidebar': [- { id: 'wishlist-count', component: WishlistsWidget, position: 50 },- ],+ 'product.form_sidebar': [{ id: 'wishlist-count', component: WishlistCard }],},tables: {products: {- add: [{ key: 'wishlist_count', label: 'Wishlists', sortable: true }],- },- },-})-```--Then in the consuming app's entry point:--```ts-// my-spree-app/src/main.tsx-import '@spree/dashboard-core/lib/i18n' // base translations-import 'my-spree-plugin' // your plugin registers extensions-// ...rest of normal dashboard bootstrap-```--## Translations — extending the base namespace--Plugin authors **inherit the framework's base translation namespace** (`admin.actions.save`, `admin.common.no_results`, `admin.validation.required`, `admin.fields.<simple>.label`, …) for free. To add your own keys, call `i18n.addResourceBundle` after the side-effect import.--```ts-// my-spree-plugin/src/index.ts-import { i18n } from '@spree/dashboard-core'-import en from './locales/en.json'-//-// {-// "admin": {-// "wishlists": {-// "title": "Wishlists",-// "empty_state": "No wishlists yet"-// }-// }-// }--i18n.addResourceBundle('en', 'translation', en, true, true)-// `deep: true` + `overwrite: true` merge nested keys into the base namespace-// without dropping anything the framework provided.-```--Now anywhere in your plugin you can mix base keys and your own:--```tsx-import { useTranslation } from '@spree/dashboard-core'--function WishlistsHeader() {- const { t } = useTranslation()- return (- <header>- <h1>{t('admin.wishlists.title')}</h1>- <button>{t('admin.actions.create')}</button>{/* base */}- </header>- )-}-```--### When plugins should pick their own sub-namespace--`addResourceBundle` deep-merges into `admin.*`, so `admin.actions.save` from a plugin would **overwrite** the framework's `admin.actions.save`. To avoid collisions, put plugin-specific text under a vendor-prefixed key:--```jsonc-{- "admin": {- "wishlists": { ... } // ok — fresh namespace under admin- }-}-```--Not:--```jsonc-{- "admin": {- "actions": {- "share": "Share" // collides if the framework ever adds `admin.actions.share`- }- }-}-```--Prefer `admin.<plugin>.*` for everything you own. Use base keys (`admin.actions.*`, `admin.common.*`, `admin.fields.<simple>.*`) by *reading* them, not by extending them.--### Multi-locale plugins--Same pattern, once per locale:--```ts-import { i18n } from '@spree/dashboard-core'-import en from './locales/en.json'-import fr from './locales/fr.json'--i18n.addResourceBundle('en', 'translation', en, true, true)-i18n.addResourceBundle('fr', 'translation', fr, true, true)-```--The framework currently ships English only; once Spree's locale list grows the same `addResourceBundle` pattern applies.--## Extension surface — the registries--### `nav` — main sidebar items--```ts-import { nav } from '@spree/dashboard-core'-import { PackageIcon } from 'lucide-react'--nav.add({- key: 'wishlists',- label: 'Wishlists',- path: '/wishlists', // prefixed with /$storeId at render time- icon: PackageIcon,- position: 50, // built-ins use 100/200/300 — slot in between- subject: 'Spree::Wishlist', // CanCanCan subject — hides item without permission-})--// Or: insert relative to an existing entry-nav.insertAfter('orders', { key: 'wishlists', label: 'Wishlists', path: '/wishlists' })-nav.update('orders', { label: 'All Orders' })-nav.remove('legacy-thing')-```--### `settingsNav` — settings sub-shell--Settings entries cluster under groups:--```ts-import { settingsNav } from '@spree/dashboard-core'--settingsNav.addGroup({ key: 'integrations', label: 'Integrations', position: 500 })-settingsNav.add({- key: 'wishlist-settings',- label: 'Wishlists',- path: '/wishlists', // prefixed with /$storeId/settings at render time- group: 'integrations',- position: 100,-})-```--### `registerSlot` — named injection points--Slots are typed by their context. A `product.form_sidebar` slot receives the product, ambient permissions, store, and user:--```tsx-import { registerSlot } from '@spree/dashboard-core'-import { Card } from '@spree/dashboard-ui'--registerSlot<{ product: { id: string; wishlist_count: number } }>('product.form_sidebar', {- id: 'wishlist-count',- component: ({ product, permissions }) => {- if (!permissions?.can('manage', 'Spree::Wishlist')) return null- return <Card>Wishlists: {product.wishlist_count}</Card>- },- position: 50,- // Optional visibility predicate — receives the merged context- if: (ctx) => ctx.product.wishlist_count > 0,-})-```--Built-in slot names follow a `resource.location` convention (e.g. `product.form_sidebar`, `order.page_body`, `product.actions`). The full list lives in the [slots catalog](https://spreecommerce.org/docs/developer/dashboard/slots-catalog).--### `tables` — list-view column extensions--```ts-import { tables } from '@spree/dashboard-core'--tables.products.addColumn({- key: 'wishlist_count',- label: 'Wishlists',- sortable: true,- render: (product) => product.wishlist_count,-})-tables.products.removeColumn('legacy_column')-tables.products.updateColumn('total', { label: 'Net total' })-```--**Ordering:** built-in tables register lazily via side-effect imports in route files (`import '@/tables/products'` inside the products route), so calling `tables.products.addColumn(...)` from your plugin's entry module — which loads before any route mounts — would otherwise race the registration. The mutator handles this transparently: mutations on a not-yet-registered table are queued and replayed when `defineTable('products', ...)` runs. Mutations on tables that never register stay pending and never fire, which is the right behavior when your plugin extends an optional feature.--## `defineDashboardPlugin` — one-call facade--Every registry in a single declarative config:--```ts-import { defineDashboardPlugin } from '@spree/dashboard-core/plugin'--defineDashboardPlugin({- nav: [...],- settingsNavGroups: [...],- settingsNav: [...],- slots: { 'product.form_sidebar': [...] },- tables: {- products: {- add: [...],+ add: [{ key: 'wishlist_count', label: 'Wishlists', render: (p) => p.wishlist_count }],remove: ['legacy_column'],- update: { total: { label: 'Net total' } },},},- // Extension fields on built-in forms — hydrate from the fetched resource,- // persist through the form's own Save. Render the input from a slot widget- // bound via useHostForm().- formFields: {- product: [{ name: 'tech_specs', from: (product) => product?.tech_specs ?? '' }],- },- // Replace the input widget for a specific custom field definition.- customFieldComponents: { 'specs.color': ColorPicker },+ formFields: { product: [{ name: 'tech_specs', from: (p) => p?.tech_specs ?? '' }] },})```-Equivalent to calling the underlying registry methods directly. Use whichever feels right — the facade is purely ergonomic.+A second entry point, `@spree/dashboard-core/vite`, provides the Vite plugin that wires Tailwind v4 and plugin auto-discovery for custom hosts.-## What's NOT here+## Documentation-Resource-specific hooks (`use-orders`, `use-products`, `use-customers`, …), Zod schemas, feature pages, route definitions, and per-feature locale strings live in `@spree/dashboard` (the app). We do not publish feature internals. Plugin authors compose new pages out of `@spree/dashboard-ui` primitives + `@spree/dashboard-core` infra, not out of forked feature internals.+The full guides live on the docs site — this README intentionally stays short:-Theme and toast UI live in `@spree/dashboard-ui` (they're rendering concerns, no Spree backend coupling): `ThemeProvider`, `useTheme`, `Toaster`.+- [Dashboard overview](https://spreecommerce.org/docs/developer/dashboard/overview) & [concepts](https://spreecommerce.org/docs/developer/dashboard/concepts)+- [Customization quickstart](https://spreecommerce.org/docs/developer/dashboard/customization/quickstart) — nav, routes, slots, tables, translations, permissions+- [Slots catalog](https://spreecommerce.org/docs/developer/dashboard/slots-catalog) — every named injection point+- [Plugin authoring](https://spreecommerce.org/docs/developer/dashboard/plugins/overview) — scaffolding, publishing, distributing+- [Public API](https://spreecommerce.org/docs/developer/dashboard/public-api) — everything this package exports, with stability guarantees-## Architectural notes+## License-- **Client injection**: `adminClient` reads `import.meta.env.VITE_SPREE_API_URL` at build time. Three deployment topologies (dev proxy, prod single-origin, prod cross-origin) all share one code path. See `src/client.ts` for details.-- **i18n bootstrap**: `import '@spree/dashboard-core/lib/i18n'` initializes i18next with the base namespace. Must run before any component calls `useTranslation`. The dashboard's `i18n-setup.ts` does this + adds the app's resources via `addResourceBundle`. Plugins follow the same pattern.-- **Registries are module singletons**: see "Peer dependencies" above. Build your plugin with `@spree/dashboard-core` listed as a peer dep, not a regular dep.+MITdiff --git a/packages/dashboard/README.md b/packages/dashboard/README.mdindex eaee85f870..00273d2309 100644--- a/packages/dashboard/README.md+++ b/packages/dashboard/README.md@@ -1,276 +1,39 @@# @spree/dashboard-The Spree Commerce admin dashboard (the "React Dashboard") — a React single-page application that replaces the Classic Admin (the server-rendered Rails engine). Built on the [Admin API](https://spreecommerce.org/docs/api-reference/admin-api/introduction) via `@spree/admin-sdk`, with an extension model (table registry, navigation registry, slots, typed plugin routes) for plugin authors.+The Spree Commerce admin dashboard (the "React Dashboard") — a React single-page application that replaces the Classic Admin (the server-rendered Rails engine). Built on the [Admin API](https://spreecommerce.org/docs/api-reference/admin-api/introduction) via `@spree/admin-sdk`, with an extension model (nav, slots, tables, typed plugin routes) for plugin authors.Part of the three-package dashboard stack with [`@spree/dashboard-core`](https://github.com/spree/spree/tree/main/packages/dashboard-core) (the framework and extension API) and [`@spree/dashboard-ui`](https://github.com/spree/spree/tree/main/packages/dashboard-ui) (the design system).-> **Developer Preview.** APIs may change between 0.x releases; in Spree 6 the React Dashboard becomes the default admin. Docs: [React Dashboard](https://spreecommerce.org/docs/developer/dashboard/overview).+> **Developer Preview.** APIs may change between 0.x releases; in Spree 6 the React Dashboard becomes the default admin.## Tech stack-| Layer | Choice |-|---|---|-| Build & dev | [Vite](https://vitejs.dev/) |-| Routing | [TanStack Router](https://tanstack.com/router) (file-based, type-safe) |-| Data fetching | [TanStack Query](https://tanstack.com/query) |-| Forms | [React Hook Form](https://react-hook-form.com/) + [Zod](https://zod.dev/) |-| UI primitives | [shadcn/ui](https://ui.shadcn.com/) + [Base UI](https://base-ui.com/) + [Tailwind CSS](https://tailwindcss.com/) |-| Icons | [lucide-react](https://lucide.dev/) |-| Charts | [Recharts](https://recharts.org/) |-| Rich text | [Tiptap](https://tiptap.dev/) |-| Notifications | [Sonner](https://sonner.emilkowal.ski/) |-| Lint & format | [Biome](https://biomejs.dev/) |+Vite · TanStack Router (file-based, type-safe) · TanStack Query · React Hook Form + Zod · shadcn/ui + Base UI + Tailwind CSS · lucide-react · Recharts · Tiptap · Sonner · Biome.-## Host integration+## Using it-Host apps consume the dashboard by installing all three packages and wiring our Vite plugin into their build:--```ts-// host vite.config.ts-import { spreeDashboardPlugin } from '@spree/dashboard/vite'-import { TanStackRouterVite } from '@tanstack/router-plugin/vite'-import react from '@vitejs/plugin-react'-import { defineConfig } from 'vite'--export default defineConfig({- plugins: [- spreeDashboardPlugin({- plugins: [- '@my-store/orders-dashboard-plugin',- '@my-store/wishlists-dashboard-plugin',- ],- }),- TanStackRouterVite(),- react(),- ],-})-```--```css-/* host src/styles.css */-@import "@spree/dashboard/styles.css";-```--```ts-// host src/main.tsx-import '@my-store/orders-dashboard-plugin' // side-effect: defineDashboardPlugin()-import '@my-store/wishlists-dashboard-plugin'-import './styles.css'-// … mount the app-```--The Vite plugin bundles `@tailwindcss/vite` and injects `@source` directives for every Spree dashboard package and every host-named plugin, so hosts don't configure Tailwind directly. `@spree/dashboard/vite` is a thin re-export of [`@spree/dashboard-core/vite`](../dashboard-core/README.md#vite-integration) — that's where the plugin lives and where the full options reference (custom dashboards, plugin authoring, `cssEntry`, etc.) is documented.--## Getting started--The admin needs a running Spree backend exposing the Admin API. The simplest setup:--```bash-# 1. Boot a Spree server (from the monorepo root)-pnpm server:setup # one-time bootstrap: clones spree-starter into ./server, boots the stack, prepares the DB-pnpm server:dev # foreground; streams logs — Rails on http://localhost:3000 (Ctrl+C stops it)--# 2. In a separate terminal, run the admin dev server-cd packages/dashboard-pnpm dev # http://localhost:5173-```--Vite proxies `/api/*` to `http://localhost:3000`. The first time you load the admin, sign in with the seed admin user (default: `[email protected]` / `spree123` — override at seed time with `ADMIN_EMAIL` / `ADMIN_PASSWORD`; see `spree/core/app/services/spree/seeds/admin_user.rb`). If you need to reset an admin password, run `pnpm server:console` and update the user from the Rails console.--### Configuration--The dev server reads its API base URL from `VITE_SPREE_API_URL` (defaults to `http://localhost:3000`). For a custom backend:--```bash-VITE_SPREE_API_URL=https://my-spree.example.com pnpm dev-```--For production builds, set the same env var at build time:+Don't wire this package by hand — scaffold a host app, which pins the stack and configures the Vite integration (`@spree/dashboard/vite`) for you:```bash-VITE_SPREE_API_URL=https://api.mystore.com pnpm build+# in a create-spree-app project (or pass --react-dashboard at create time)+spree add dashboard```-## Scripts--| Command | Description |-|---|---|-| `pnpm dev` | Start Vite dev server with HMR on port 5173 |-| `pnpm build` | Type-check and build the SPA into `dist/` |-| `pnpm preview` | Serve the production build locally |-| `pnpm lint` | Lint with Biome |-| `pnpm lint:fix` | Lint and auto-fix with Biome |-| `pnpm format` | Format source with Biome |-| `pnpm test:e2e` | Run the Playwright E2E suite against a real Rails backend |-| `pnpm test:e2e:ui` | Run the E2E suite in Playwright's interactive UI for debugging |-| `pnpm test:e2e:install` | One-time: install the Chromium build Playwright drives |--## Project structure--```-src/-├── client.ts # adminClient instance (configures @spree/admin-sdk)-├── main.tsx # app entry, providers-├── router.tsx # TanStack Router configuration-├── routeTree.gen.ts # generated by @tanstack/router-plugin (do not edit)-├── routes/ # file-based routes-│ ├── __root.tsx # router context (auth, permissions)-│ ├── login.tsx # public login page-│ └── _authenticated/ # auth-guarded routes-│ └── $storeId/ # multi-store routes (orders, products, customers, ...)-├── components/ # app-level components-│ └── ui/ # shadcn/ui primitives-├── hooks/ # data hooks built on @spree/admin-sdk-├── providers/ # AuthProvider, PermissionProvider, StoreProvider-├── tables/ # table definitions for the registry-├── schemas/ # Zod form schemas-└── lib/ # utilities, query client, table registry-```--## Architecture notes--### Authentication--JWT access token in memory + refresh token in an HttpOnly signed cookie.--- Login → `POST /api/v3/admin/auth/login` returns `{ token, user }`. The server also sets `spree_admin_refresh_token` — an HttpOnly signed cookie scoped to `/api/v3/admin/auth`, invisible to JS.-- Access token stays in React state only — **no `localStorage`**, no `sessionStorage`.-- On cold load, the SPA calls `POST /api/v3/admin/auth/refresh` (cookie-driven) to bootstrap. Routes wait for `auth.isInitializing === false` before redirecting.-- Background refresh every 58 minutes (the JWT defaults to a 1-hour TTL).-- 401 responses trigger an automatic refresh via the SDK's `onUnauthorized` hook, then retry the original request.-- Logout → `POST /api/v3/admin/auth/logout` destroys the refresh-token row server-side and clears the cookie. The in-memory state is cleared regardless of whether the network call succeeds.-- Concurrent refresh attempts are serialized to prevent double-rotation under StrictMode/HMR.--CSRF defense comes from the cookie's `SameSite` attribute combined with the `Spree::AllowedOrigin` allowlist enforced via `Rack::Cors`. There is no double-submit CSRF token.--Public routes (login) sit at the root; everything else is gated by `routes/_authenticated.tsx`.--In dev, `vite.config.ts` proxies `/api/*` → `http://localhost:3000` so the SPA is same-origin with the Rails API and `SameSite=Lax` cookies work without HTTPS. In production, set `VITE_SPREE_API_URL` to the absolute API origin — the backend issues `SameSite=None; Secure` automatically when `Rails.env.production?`.--### Permissions--Permissions are **server-driven**. On login, `GET /api/v3/admin/me` returns the user's CanCanCan abilities serialized as JSON. The SPA mirrors them via:--```tsx-import { Can, usePermissions } from '@spree/dashboard-core'--// Declarative-<Can I="update" a="Order"><EditButton /></Can>--// Imperative-const { can } = usePermissions()-if (can('destroy', 'Product')) { /* ... */ }-```--The server still enforces `authorize!` on every request — the SPA is UX only.--### Multi-store+The host consumes the exported `<Dashboard />` shell and `createDashboardRouter`, activates any installed dashboard plugins through auto-discovery, and composes their file routes into one typed route tree.-All authenticated routes include a `$storeId` segment (e.g. `/store_abc/orders`). The `StoreProvider` configures the SDK with the active store and exposes `useStore()` to read the current store's currency, locale, and metadata. The root authenticated route redirects to the user's default store.+## Documentation-### Extension points+The full guides live on the docs site — this README intentionally stays short:-Extension points for plugin authors (see the [customization docs](https://spreecommerce.org/docs/developer/dashboard/customization/quickstart)):--1. **Table registry** — register columns/filters/actions for any list view-2. **Navigation registry** — inject sidebar menu items, including under built-in menus-3. **Slots** — inject components into core pages (e.g., extra cards on the order detail)-4. **Typed file routes** — plugin pages compiled into the host's route tree with type-checked links--The shadcn copy-paste model means UI components in `src/components/ui/` are owned by this project, not a component library. Extensions can copy-and-modify rather than fighting library abstractions.--## Adding a shadcn/ui component--```bash-pnpm dlx shadcn@latest add <component-name>-```--Components land in `src/components/ui/`. Customize freely.--## Working with @spree/admin-sdk--All API calls go through the `adminClient` singleton from `@spree/dashboard-core`. Wrap calls in custom hooks under `src/hooks/`:--```ts-// src/hooks/use-orders.ts-import { adminClient, useResourceKey } from '@spree/dashboard-core'-import { useQuery } from '@tanstack/react-query'--export function useOrders(params: ListOrdersParams) {- return useQuery({- queryKey: useResourceKey('orders', params),- queryFn: () => adminClient.orders.list(params),- })-}-```--Mutations follow the same pattern with `useMutation` and `queryClient.invalidateQueries(...)` to refresh affected views.--## End-to-end tests--The `e2e/` folder holds [Playwright](https://playwright.dev/) specs that drive the SPA against a real Rails backend — no API mocks. CI runs the same suite via the `dashboard-e2e` job in `.github/workflows/packages.yml`; locally, `pnpm test:e2e` mirrors what CI does.--What the suite boots:--- **Rails** on `:3010` — the dummy app at `spree/api/spec/dummy`, with a fresh SQLite DB seeded via `Spree::Seeds::All` on every run.-- **Vite dev server** on `:5174` — proxies `/api/*` to the test Rails so the SPA stays same-origin (matches dev's cookie posture exactly).-- **Playwright** drives Chromium and tears both down at the end.--Currently covered:--- `e2e/auth.spec.ts` — login form happy path + invalid-credentials error-- `e2e/invitation-acceptance.spec.ts` — full staff-onboarding lifecycle: admin signs in → opens Settings → Staff → invites a teammate → logs out → invitee opens the link in a fresh browser context → completes signup → lands authenticated--### Running locally--One-time prerequisites: a built dummy Rails app and the Chromium browser bundle.--```bash-# From the repo root, build the dummy Rails app once.-cd spree/api-bundle install-bundle exec rake test_app--# From this package, install Playwright's Chromium once per machine.-cd ../../packages/dashboard-pnpm test:e2e:install-```--Then run the suite:--```bash-pnpm test:e2e # full suite-pnpm test:e2e e2e/auth.spec.ts # one file-pnpm test:e2e -g "invites a teammate" # filter by test name-pnpm test:e2e:ui # interactive debugger (time-travel, DOM inspector)-```--`pnpm test:e2e` is safe to re-run: each run resets the SQLite DB before seeding, so tests start from a known state.--### Debugging failures--On failure, Playwright drops three artifacts in `test-results/<spec>/`:--- `test-failed-1.png` — screenshot at the moment of failure-- `video.webm` — the full run-- `error-context.md` — DOM snapshot + the failing locator (usually enough to fix selector issues without re-running)--CI uploads these as a `playwright-report` artifact (14-day retention) on failed runs.--### Adding a spec--Specs live next to the existing ones in `e2e/`. Use `getCredentials()` from `e2e/fixtures.ts` for the seeded admin email/password and store ID — anything else, drive through the UI like a user would. Avoid hitting the Admin API directly from a spec unless the flow you're testing requires backend setup that has no UI path; the value of these tests is exercising the full layer cake.+- [Overview](https://spreecommerce.org/docs/developer/dashboard/overview) & [concepts](https://spreecommerce.org/docs/developer/dashboard/concepts) — architecture, auth, permissions, multi-store+- [Customization](https://spreecommerce.org/docs/developer/dashboard/customization/quickstart) — your pages, nav, slots, tables, translations+- [Plugins](https://spreecommerce.org/docs/developer/dashboard/plugins/overview) — build and distribute dashboard extensions+- [Deployment](https://spreecommerce.org/docs/developer/dashboard/deployment) — served by the Spree server at `/dashboard` (default) or a CDN+- [Public API](https://spreecommerce.org/docs/developer/dashboard/public-api)## Contributing-Development happens in the [spree/spree](https://github.com/spree/spree) monorepo under `packages/dashboard`. Architecture decisions live in `docs/plans/6.0-admin-spa.md` there — please read that before proposing significant changes.--When changing API contracts, also update the upstream serializers in `spree/api` and regenerate types:--```bash-cd spree/api && bundle exec rake typelizer:generate-cd packages/admin-sdk && pnpm build-```+The dashboard lives in the [spree/spree monorepo](https://github.com/spree/spree) under `packages/dashboard` — see the repository docs (`CLAUDE.md`) for local development against a Spree backend and the Playwright E2E suite.## Licensediff --git a/packages/sdk/README.md b/packages/sdk/README.mdindex da7ab3ad84..afc5c09693 100644--- a/packages/sdk/README.md+++ b/packages/sdk/README.md@@ -1,15 +1,11 @@# @spree/sdk-Official TypeScript SDK for Spree Commerce API v3.+Official TypeScript SDK for the [Spree Commerce](https://spreecommerce.org) Store API v3 — fully typed resource clients, guest and customer authentication, carts and checkout, with runtime Zod schemas generated from the API's serializers.## Installation```bashnpm install @spree/sdk-# or-yarn add @spree/sdk-# or-pnpm add @spree/sdk```## Quick Start@@ -17,849 +13,33 @@ pnpm add @spree/sdk```typescriptimport { createClient } from '@spree/sdk';-// Initialize the clientconst client = createClient({baseUrl: 'https://api.mystore.com',publishableKey: 'spree_pk_xxx',});-// Browse products (Store API)-const products = await client.products.list({- limit: 10,- expand: ['variants', 'media'],-});--// Get a single product-const product = await client.products.get('spree-tote');+// Browse the catalog+const products = await client.products.list({ limit: 10, expand: ['variants', 'media'] });-// Authentication-const { token, user } = await client.auth.login({- email: '[email protected]',- password: 'password123',-});--// Create a cart and add items+// Cart + checkoutconst cart = await client.carts.create();-await client.carts.items.create(cart.id, {- variant_id: 'var_abc123',- quantity: 2,-}, { spreeToken: cart.token });--// Update cart and complete-await client.carts.update(cart.id, {- email: '[email protected]',-}, { spreeToken: cart.token });-await client.carts.complete(cart.id, { spreeToken: cart.token });-```--## Client Architecture--All Store API resources are available directly on the client:+await client.carts.items.create(cart.id, { variant_id: 'var_abc123', quantity: 2 }, { spreeToken: cart.token });-```typescript-client.products.list() // Products-client.carts.create() // Create a cart-client.carts.get(cartId) // Get a cart by ID-client.carts.items.create(cartId, params) // Cart line items-client.carts.complete(cartId, opt) // Complete cart-client.carts.list(opt) // List active carts-client.customers.create(params) // Registration-client.customer.get(opt) // Account-client.customer.orders.list() // Order history-```--## Authentication--The SDK supports multiple authentication modes:--### 1. Publishable Key Only (Guest/Public Access)--```typescript-const client = createClient({- baseUrl: 'https://api.mystore.com',- publishableKey: 'spree_pk_xxx',-});--// Public endpoints work without user authentication-const products = await client.products.list();-```--### 2. Publishable Key + JWT (Authenticated Customer)--```typescript-// Login to get tokens-const { token, user } = await client.auth.login({- email: '[email protected]',- password: 'password123',-});--// Use token for authenticated requests+// Customer authentication (JWT)+const { token } = await client.auth.login({ email: '[email protected]', password: 'password123' });const orders = await client.customer.orders.list({}, { token });--// Refresh when the access token expires — pass the refresh token, get a rotated pair back-const newTokens = await client.auth.refresh({ refresh_token: refreshToken });--// Logout — revokes the refresh token server-side-await client.auth.logout({ refresh_token: refreshToken });-```--### 3. Register New Customer--```typescript-const { token, user } = await client.customers.create({- email: '[email protected]',- password: 'password123',- password_confirmation: 'password123',- first_name: 'John',- last_name: 'Doe',-});-```--## Guest Checkout--For guest checkout, use the `token` returned when creating a cart:--```typescript-// Create a cart (guest)-const cart = await client.carts.create();--// Use spreeToken for all cart operations-const options = { spreeToken: cart.token };--// Add items-await client.carts.items.create(cart.id, {- variant_id: 'var_abc123',- quantity: 1,-}, options);--// Update cart with email and addresses-await client.carts.update(cart.id, {- email: '[email protected]',-}, options);--// Complete the order-await client.carts.complete(cart.id, options);-```--## API Reference--### Products--```typescript-// List products with filtering-const products = await client.products.list({- page: 1,- limit: 25,- name_cont: 'shirt',- sort: 'price asc',- expand: ['variants', 'media', 'categories'],-});--// Get single product by ID or slug-const product = await client.products.get('spree-tote', {- expand: ['variants', 'media'],-});--// Get product with prior price (EU Omnibus Directive compliance)-const product = await client.products.get('spree-tote', {- expand: ['prior_price'],-});-console.log(product.prior_price); // { amount: "9.99", currency: "USD", display_amount: "$9.99", ... }--// Get available filters (price range, availability, options, categories)-const filters = await client.products.filters({- category_id: 'ctg_abc123', // Optional: scope filters to a category-});-```--### Categories--```typescript-// List categories with filtering-const categories = await client.categories.list({- depth_eq: 1, // Top-level categories only-});--// Get single category by ID or permalink-const category = await client.categories.get('clothing/shirts', {- expand: ['ancestors', 'children'], // For breadcrumbs and subcategories-});--// List products in a category-const categoryProducts = await client.categories.products.list('clothing/shirts', {- page: 1,- limit: 12,- expand: ['media', 'default_variant'],-});-```--### Carts--All cart operations use explicit cart IDs (`cart_xxx`). The cart is authorized-via `spreeToken` header (guest) or JWT token (authenticated user).--```typescript-// Create a new cart-const cart = await client.carts.create();--// Get a cart by ID-const cart = await client.carts.get('cart_xxx', { spreeToken: cart.token });--// Delete / abandon a cart-await client.carts.delete('cart_xxx', { spreeToken: cart.token });--// Associate guest cart with authenticated user-await client.carts.associate('cart_xxx', {- token: jwtToken, // User's JWT token-});--// List all active carts for authenticated user-const { data: carts } = await client.carts.list({ token: jwtToken });--// Update cart (email, addresses, customer note)-await client.carts.update('cart_xxx', {- email: '[email protected]',- shipping_address: {- first_name: 'John',- last_name: 'Doe',- address1: '123 Main St',- city: 'New York',- postal_code: '10001',- phone: '+1 555 123 4567',- country_iso: 'US',- state_abbr: 'NY',- },-}, options);--// Complete the order-await client.carts.complete('cart_xxx', options);-```--### Cart Items (Line Items)--```typescript-const options = { spreeToken: cart.token };--// Add item-await client.carts.items.create('cart_xxx', {- variant_id: 'var_123',- quantity: 2,-}, options);--// Update item quantity-await client.carts.items.update('cart_xxx', lineItemId, {- quantity: 3,-}, options);--// Remove item-await client.carts.items.delete('cart_xxx', lineItemId, options);-```--### Discount Codes--```typescript-const options = { spreeToken: cart.token };--// Apply a discount code-await client.carts.discountCodes.apply('cart_xxx', 'SAVE20', options);--// Remove a discount code-await client.carts.discountCodes.remove('cart_xxx', 'SAVE20', options);-```--### Gift Cards--```typescript-const options = { spreeToken: cart.token };--// Apply a gift card-const cart = await client.carts.giftCards.apply('cart_xxx', 'GC-ABCD-1234', options);--// Remove a gift card (ID from cart.gift_card.id)-await client.carts.giftCards.remove('cart_xxx', 'gc_abc123', options);--// Check cart warnings (e.g. items removed due to stock changes)-if (cart.warnings.length > 0) {- cart.warnings.forEach(w => console.log(w.code, w.message));-}-```--### Fulfillments--```typescript-const options = { spreeToken: cart.token };--// Fulfillments are included in the cart response.-// Select a delivery rate-await client.carts.fulfillments.update('cart_xxx', fulfillmentId, {- selected_delivery_rate_id: 'rate_xxx',-}, options);-```--### Store Credits--```typescript-const options = { spreeToken: cart.token };--// Apply store credit (applies maximum available by default)-await client.carts.storeCredits.apply('cart_xxx', undefined, options);--// Apply specific amount of store credit-await client.carts.storeCredits.apply('cart_xxx', 25.00, options);--// Remove store credit-await client.carts.storeCredits.remove('cart_xxx', options);-```--### Payments--```typescript-const options = { spreeToken: cart.token };--// Payment methods and payments are included in the cart response.-// Each payment method includes `session_required` flag:-// - true -> use paymentSessions (Stripe, Adyen, PayPal, etc.)-// - false -> use payments.create (Check, Cash on Delivery, Bank Transfer, etc.)--// Create a payment for a non-session payment method-// (e.g. Check, Cash on Delivery, Bank Transfer, Purchase Order)-const payment = await client.carts.payments.create('cart_xxx', {- payment_method_id: 'pm_xxx',- amount: '99.99', // Optional, defaults to order total minus store credits- metadata: { // Optional, write-only metadata- purchase_order_number: 'PO-12345',- },-}, options);-```--### Payment Sessions--Payment sessions provide a unified, provider-agnostic interface for payment processing. They work with any payment gateway (Stripe, Adyen, PayPal, etc.) through a single API.--```typescript-const options = { spreeToken: cart.token };--// Create a payment session (initializes a session with the payment gateway)-const session = await client.carts.paymentSessions.create('cart_xxx', {- payment_method_id: 'pm_xxx',- amount: '99.99', // Optional, defaults to order total- external_data: { // Optional, provider-specific data- return_url: 'https://mystore.com/checkout/complete',- },-}, options);--// The session contains provider-specific data (e.g., Stripe client_secret)-console.log(session.external_data.client_secret);--// Get a payment session-const existing = await client.carts.paymentSessions.get(- 'cart_xxx', session.id, options-);--// Update a payment session (e.g., after order total changes)-await client.carts.paymentSessions.update('cart_xxx', session.id, {- amount: '149.99',-}, options);--// Complete the payment session (after customer confirms payment on the frontend)-const completed = await client.carts.paymentSessions.complete(- 'cart_xxx',- session.id,- { session_result: 'success' },- options-);-console.log(completed.status); // 'completed'-```--### Orders--Completed orders can be looked up by ID or number:--```typescript-// Get a completed order by ID or number-const order = await client.orders.get('R123456789', {- expand: ['items', 'fulfillments'],-}, { spreeToken: orderToken });-```--For order history, use the customer orders resource:--```typescript-const options = { token: jwtToken };--// List order history for authenticated customer-const orders = await client.customer.orders.list({}, options);--// Get a specific order from history-const order = await client.customer.orders.get('or_xxx', {- expand: ['items', 'fulfillments'],-}, options);-```--### Markets--```typescript-// List all markets-const { data: markets } = await client.markets.list();-// [{ id: "mkt_xxx", name: "North America", currency: "USD", default_locale: "en", ... }]--// Get a single market-const market = await client.markets.get('mkt_xxx');--// Resolve which market applies for a country-const market = await client.markets.resolve('DE');-// => { id: "mkt_xxx", name: "Europe", currency: "EUR", default_locale: "de", ... }--// List countries in a market-const { data: countries } = await client.markets.countries.list('mkt_xxx');--// Get a country in a market (with states for address forms)-const country = await client.markets.countries.get('mkt_xxx', 'DE', {- expand: ['states'],-});-```--### Geography--```typescript-// List countries available for checkout-const { data: countries } = await client.countries.list();--// Get country by ISO code (with states)-const usa = await client.countries.get('US', { expand: ['states'] });-console.log(usa.states); // Array of states-```--### Customer Account--```typescript-const options = { token: jwtToken };--// Get profile-const profile = await client.customer.get(options);--// Update profile-await client.customer.update({- first_name: 'John',- last_name: 'Doe',-}, options);-```--### Customer Addresses--```typescript-const options = { token: jwtToken };--// List addresses-const { data: addresses } = await client.customer.addresses.list({}, options);--// Get address by ID-const address = await client.customer.addresses.get('addr_xxx', options);--// Create address-await client.customer.addresses.create({- first_name: 'John',- last_name: 'Doe',- address1: '123 Main St',- city: 'New York',- postal_code: '10001',- country_iso: 'US',- state_abbr: 'NY',-}, options);--// Update address-await client.customer.addresses.update('addr_xxx', { city: 'Brooklyn' }, options);--// Delete address-await client.customer.addresses.delete('addr_xxx', options);--// Set as default billing or shipping address-await client.customer.addresses.update('addr_xxx', { is_default_billing: true }, options);-await client.customer.addresses.update('addr_xxx', { is_default_shipping: true }, options);-```--### Password Resets--```typescript-// Request a password reset email-// Always returns { message: string } (202 status) — prevents email enumeration-await client.passwordResets.create({- email: '[email protected]',- redirect_url: 'https://myshop.com/reset-password', // optional, validated against store's allowed origins-});--// Reset password with token from email-// Returns AuthTokens (JWT + user) — auto-login on success-// Token expires in 15 minutes-const { token, user } = await client.passwordResets.update('reset_token_xxx', {- password: 'newPassword123',- password_confirmation: 'newPassword123',-});-```--### Customer Credit Cards--```typescript-const options = { token: jwtToken };--// List saved credit cards-const { data: cards } = await client.customer.creditCards.list({}, options);--// Get credit card by ID-const card = await client.customer.creditCards.get('cc_xxx', options);--// Delete credit card-await client.customer.creditCards.delete('cc_xxx', options);-```--### Wishlists--```typescript-const options = { token: jwtToken };--// List wishlists-const { data: wishlists } = await client.wishlists.list({}, options);--// Get wishlist by ID-const wishlist = await client.wishlists.get('wl_xxx', {- expand: ['wishlist_items'],-}, options);--// Create wishlist-const newWishlist = await client.wishlists.create({- name: 'Birthday Ideas',- is_private: true,-}, options);--// Update wishlist-await client.wishlists.update('wl_xxx', {- name: 'Updated Name',-}, options);--// Delete wishlist-await client.wishlists.delete('wl_xxx', options);-```--### Wishlist Items--```typescript-const options = { token: jwtToken };--// Add item to wishlist-await client.wishlists.items.create('wl_xxx', {- variant_id: 'var_123',- quantity: 1,-}, options);--// Update item quantity-await client.wishlists.items.update('wl_xxx', 'wi_xxx', {- quantity: 2,-}, options);--// Remove item from wishlist-await client.wishlists.items.delete('wl_xxx', 'wi_xxx', options);-```--## Nested Resources--The SDK uses a resource builder pattern for nested resources:--| Parent Resource | Nested Resource | Available Methods |-|-----------------|-----------------|-------------------|-| `carts` | `items` | `create`, `update`, `delete` |-| `carts` | `discountCodes` | `apply`, `remove` |-| `carts` | `giftCards` | `apply`, `remove` |-| `carts` | `fulfillments` | `update` |-| `carts` | `payments` | `create` |-| `carts` | `paymentSessions` | `create`, `get`, `update`, `complete` |-| `carts` | `storeCredits` | `apply`, `remove` |-| `policies` | — | `list`, `get` |-| `passwordResets` | — | `create`, `update` |-| `customer` | `addresses` | `list`, `get`, `create`, `update`, `delete` |-| `customer` | `creditCards` | `list`, `get`, `delete` |-| `customer` | `giftCards` | `list`, `get` |-| `customer` | `storeCredits` | `list`, `get` |-| `customer` | `orders` | `list`, `get` |-| `customer` | `paymentSetupSessions` | `create`, `get`, `complete` |-| `newsletterSubscribers` | — | `create`, `verify` |-| `markets` | `countries` | `list`, `get` |-| `wishlists` | `items` | `create`, `update`, `delete` |--Example:-```typescript-// Cart resources take cartId as first argument-await client.carts.items.create(cartId, params, options);-await client.carts.discountCodes.apply(cartId, code, options);-await client.carts.fulfillments.update(cartId, fulfillmentId, params, options);-await client.carts.payments.create(cartId, params, options);-await client.carts.paymentSessions.create(cartId, params, options);-await client.carts.storeCredits.apply(cartId, amount, options);--// Other nested resources follow the same pattern-await client.customer.addresses.list({}, options);-await client.customer.orders.list({}, options);-await client.markets.countries.list(marketId);-await client.wishlists.items.create(wishlistId, params, options);-```--## Localization, Currency & Sales Channels--### Client-level defaults--Set locale, currency, country, and sales channel when creating the client:--```typescript-const client = createClient({- baseUrl: 'https://api.mystore.com',- publishableKey: 'spree_pk_xxx',- locale: 'fr',- currency: 'EUR',- country: 'FR',- channel: 'pos',-});--// All requests use fr/EUR/FR and the 'pos' channel automatically-const products = await client.products.list();-```--Update defaults at any time:--```typescript-client.setLocale('de');-client.setCurrency('EUR');-client.setCountry('DE');-client.setChannel('wholesale');-```--The `channel` value can be either a channel `code` (e.g. `online`, `pos`, `wholesale`) or the prefixed ID (`ch_…`). `code` is preferred — it's merchant-meaningful and stable across environments. The SDK maps it to the `X-Spree-Channel` request header, which selects which [sales channel](https://spreecommerce.org/docs/developer/core-concepts/channels) scopes the request. When omitted, the store's default channel is used.--### Per-request overrides--Pass headers with any request to override the defaults:--```typescript-const products = await client.products.list({}, {- locale: 'fr',- currency: 'EUR',- country: 'FR',- channel: 'pos',-});```-## Error Handling--```typescript-import { SpreeError } from '@spree/sdk';--try {- await client.products.get('non-existent');-} catch (error) {- if (error instanceof SpreeError) {- console.log(error.code); // 'record_not_found'- console.log(error.message); // 'Product not found'- console.log(error.status); // 404- console.log(error.details); // Validation errors (if any)- }-}-```--## TypeScript Support--The SDK includes full TypeScript support with generated types from the API serializers:--```typescript-import type {- Product,- Cart,- Order,- Variant,- Category,- LineItem,- Address,- Customer,- PaginatedResponse,-} from '@spree/sdk';--// All responses are fully typed-const products: PaginatedResponse<Product> = await client.products.list();-const category: Category = await client.categories.get('clothing');-const cart: Cart = await client.carts.get('cart_xxx');-```--## Available Types--All types are exported as unprefixed names (e.g., `Product`, `Order`). Legacy `Store*` prefixed aliases (e.g., `StoreProduct`) are still available for backward compatibility.--### Core Types-- `Product` - Product data-- `Variant` - Variant data-- `Cart` - Cart data (uses `cart_` prefixed IDs)-- `Order` - Completed order data (uses `or_` prefixed IDs)-- `LineItem` - Line item in cart-- `Category` - Category-- `Country` - Country with states-- `State` - State/province-- `Address` - Customer address-- `Customer` - Customer profile-- `Market` - Market configuration (currency, locales, countries)+## Documentation-### Commerce Types-- `Payment` - Payment record-- `PaymentMethod` - Payment method-- `PaymentSession` - Provider-agnostic payment session-- `Fulfillment` - Fulfillment record-- `DeliveryRate` - Delivery rate option-- `DeliveryMethod` - Delivery method-- `CreditCard` - Saved credit card-- `GiftCard` - Gift card-- `Discount` - Discount applied to a cart or order+The full guides live on the docs site — this README intentionally stays short:-### Product Types-- `Media` - Product media (images, videos)-- `Price` - Price data-- `PriceHistory` - Prior price data (for EU Omnibus Directive compliance)-- `OptionType` - Option type (e.g., Size, Color)-- `OptionValue` - Option value (e.g., Small, Red)-- `DigitalLink` - Digital download link-- `CustomField` - Custom field data--### Wishlist Types-- `Wishlist` - Wishlist-- `WishlistItem` - Wishlist item--### Client Types-- `Client` - Main client interface-- `StoreClient` - Store API client class-- `ClientConfig` - Client configuration-- `RequestOptions` - Per-request options-- `RetryConfig` - Retry behavior configuration--### Utility Types-- `PaginatedResponse<T>` - Paginated API response-- `ListResponse<T>` - List API response-- `AuthTokens` - JWT tokens from login-- `AddressParams` - Address input parameters-- `UpdateCartParams` - Cart update parameters (email, addresses, etc.)-- `CreatePaymentParams` - Direct payment creation parameters (for non-session payment methods)-- `CreatePaymentSessionParams` - Payment session creation parameters-- `UpdatePaymentSessionParams` - Payment session update parameters-- `CompletePaymentSessionParams` - Payment session completion parameters-- `ProductFiltersResponse` - Product filters response-- `CheckoutRequirement` - Checkout requirement (`{ step, field, message }`)--## Custom Fetch--You can provide a custom fetch implementation:--```typescript-import { createClient } from '@spree/sdk';--const client = createClient({- baseUrl: 'https://api.mystore.com',- publishableKey: 'spree_pk_xxx',- fetch: customFetchImplementation,-});-```--## Webhooks--The SDK includes webhook signature verification and types via the `@spree/sdk/webhooks` subpath:--```typescript-import { verifyWebhookSignature, type WebhookEvent } from '@spree/sdk/webhooks';-import type { Order } from '@spree/sdk';--// Verify a webhook signature (works with any framework)-const isValid = verifyWebhookSignature(- rawBody, // raw request body string- request.headers.get('x-spree-webhook-signature')!, // HMAC signature- request.headers.get('x-spree-webhook-timestamp')!, // unix timestamp- process.env.SPREE_WEBHOOK_SECRET! // endpoint secret key-);--// Type your webhook handlers using SDK types-type OrderEvent = WebhookEvent<Order>;--function handleOrderCompleted(event: OrderEvent) {- const order = event.data; // fully typed Order- console.log(order.number, order.email, order.display_total);-}-```--Webhook payloads use the same V3 serializers as the REST API, so all SDK types (`Order`, `Cart`, `Payment`, `Fulfillment`, etc.) work directly as the `data` field type.--For **Next.js** projects, the [Spree Storefront](https://github.com/spree/storefront) includes a ready-made webhook route handler with signature verification and event routing.--## Development--### Setup--```bash-cd sdk-npm install-```--### Scripts--| Command | Description |-|---------|-------------|-| `npm test` | Run tests once |-| `npm run test:watch` | Run tests in watch mode |-| `npm run test:coverage` | Run tests with coverage report |-| `npm run typecheck` | Type-check with `tsc --noEmit` |-| `npm run build` | Build CJS + ESM bundles with `tsup` |-| `npm run dev` | Build in watch mode |-| `npm run console` | Interactive REPL for testing the SDK |--### Testing--Tests use [Vitest](https://vitest.dev/) with [MSW](https://mswjs.io/) (Mock Service Worker) for API mocking at the network level.--```bash-# Run all tests-npm test--# Run in watch mode during development-npm run test:watch--# Run with coverage-npm run test:coverage-```--Test files live in `tests/` and follow the structure:--- `tests/mocks/handlers.ts` - MSW request handlers with fixture data-- `tests/mocks/server.ts` - MSW server instance-- `tests/setup.ts` - Server lifecycle (listen/reset/close)-- `tests/helpers.ts` - `createTestClient()` and constants-- `tests/*.test.ts` - Test suites per resource (auth, products, orders, etc.)--To add tests for a new endpoint, add an MSW handler in `handlers.ts` and create a corresponding test file.--### Releasing--This package uses [Changesets](https://github.com/changesets/changesets) for version management and publishing.--**After making changes:**--```bash-npx changeset-```--This prompts you to select a semver bump type (patch/minor/major) and write a summary. A changeset file is created in `.changeset/`.--**How releases work:**--1. Changeset files are committed with your PR-2. When merged to `main`, a GitHub Action creates a "Version Packages" PR that bumps the version and updates the CHANGELOG-3. When that PR is merged, the package is automatically published to npm--**Manual release (if needed):**--```bash-npm run version # Apply changesets and bump version-npm run release # Build and publish to npm-```+- [SDK quickstart](https://spreecommerce.org/docs/developer/sdk/quickstart)+- [Authentication](https://spreecommerce.org/docs/developer/sdk/authentication) — publishable key, customer JWT + refresh, guest cart tokens+- [Configuration](https://spreecommerce.org/docs/developer/sdk/configuration) — retries, custom fetch, error handling+- [Store resources](https://spreecommerce.org/docs/developer/sdk/store/products) — products, cart & checkout, payments, account, wishlists, markets+- [Extending the client](https://spreecommerce.org/docs/developer/sdk/extending) — custom endpoints+- [Store API reference](https://spreecommerce.org/docs/api-reference/store-api/introduction)## License