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
Release SDK 1.1 and Admin SDK 0.2.0 (#14152)
Damian Legawieceda0f9858c5a
diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.mdindex aa055860e7..d8b75549a1 100644--- a/.github/CONTRIBUTING.md+++ b/.github/CONTRIBUTING.md@@ -371,7 +371,9 @@ cd packages/sdk # or packages/admin-sdk, packages/cli, packages/create-spree-pnpm changeset```-This creates a changeset file describing your changes. Commit it with your PR. When merged to `main`, a GitHub Action creates a "Version Packages" PR that bumps the version and publishes to npm.+This creates a changeset file describing your changes. Commit it with your PR.++Releasing is a two-step flow: a maintainer consumes the pending changesets (`changeset version` — writes the CHANGELOG and bumps `package.json`) and merges that bump to `main`; the release jobs in `.github/workflows/packages.yml` then detect the unpublished version and publish with npm provenance via Trusted Publishing. `@spree/admin-sdk` publishes under the `next` dist-tag while on the 0.x Developer Preview line; the others ship as `latest` (prereleases go to `beta`).Private packages (`@spree/dashboard`, `@spree/dashboard-core`, `@spree/dashboard-ui`, `@spree/sdk-core`) don't need changesets.diff --git a/docs/developer/contributing/developing-spree.mdx b/docs/developer/contributing/developing-spree.mdxindex c2bcdfe04a..b481f48234 100644--- a/docs/developer/contributing/developing-spree.mdx+++ b/docs/developer/contributing/developing-spree.mdx@@ -337,7 +337,9 @@ cd packages/sdk # or packages/admin-sdk, packages/cli, packages/create-spree-pnpm changeset```-This creates a changeset file describing your changes. Commit it with your PR. When merged to `main`, a GitHub Action creates a "Version Packages" PR that bumps the version and publishes to npm.+This creates a changeset file describing your changes. Commit it with your PR.++Releasing is a two-step flow: a maintainer consumes the pending changesets (`changeset version` — writes the CHANGELOG and bumps `package.json`) and merges that bump to `main`; the release jobs in `.github/workflows/packages.yml` then detect the unpublished version and publish with npm provenance via Trusted Publishing. `@spree/admin-sdk` publishes under the `next` dist-tag while on the 0.x Developer Preview line; the others ship as `latest` (prereleases go to `beta`).Private packages (`@spree/dashboard`, `@spree/dashboard-core`, `@spree/dashboard-ui`, `@spree/sdk-core`) don't need changesets.diff --git a/docs/developer/sdk/admin/authentication.mdx b/docs/developer/sdk/admin/authentication.mdxnew file mode 100644index 0000000000..c49285c830--- /dev/null+++ b/docs/developer/sdk/admin/authentication.mdx@@ -0,0 +1,110 @@+---+title: "Authentication"+description: "Authenticate the Admin SDK with a secret API key (server-to-server, scope-based) or JWT cookie auth (browser admin apps, role-based)."+---++The Admin API supports two authentication methods. Both reach the same endpoints — they differ in **where the credential lives** and **how authorization is decided**:++| | Secret API key | JWT + cookie |+|---|---|---|+| **For** | Backend integrations, automations, cron jobs | Browser-based admin apps where a human signs in |+| **Credential** | `sk_…` key, created in the admin | Short-lived access token + httpOnly refresh cookie |+| **Authorization** | [Scopes](/api-reference/admin-api/authentication) attached to the key (`read_products`, `write_orders`, …) | The admin user's roles and permissions |+| **Where it runs** | Server-side only — never in a browser | Browser (the refresh token never touches your JS) |++## Secret API key (server-to-server)++Create a secret key in the admin under **Settings → API Keys**, grant it the scopes your integration needs, and pass it to the client:++```typescript+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: process.env.SPREE_SECRET_KEY, // sk_xxx+})+```++Each key carries the list of scopes granted at creation time. A request to an endpoint the key isn't scoped for fails with `code: 'access_denied'` — the error's `details.required_scope` names the missing scope (see [Querying & Errors](/developer/sdk/admin/querying-and-errors#scope-errors)).++<Warning>+ Secret keys grant back-office access to your store. Never embed them in client-side code, mobile apps, or public repositories — keep them in server-side environment variables or a secrets manager.+</Warning>++## JWT + cookie authentication (browser apps)++For browser-based admin tooling, authenticate as an admin user. The flow is designed so that **no long-lived credential is ever exposed to JavaScript**:++- `auth.login()` returns `{ token, user }` — a short-lived access token you hold in memory.+- 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.+- `auth.refresh()` takes **no arguments** — it's driven entirely by the cookie, and rotates it on every call.+- `auth.logout()` revokes the refresh token server-side and clears the cookie.++```typescript+import { createAdminClient } from '@spree/admin-sdk'++// A cookie-auth app can start with no credentials at all+const client = createAdminClient({ baseUrl: 'https://your-store.com' })++// Sign in — the refresh token lands in the httpOnly cookie+const { token, user } = await client.auth.login({+ email: '[email protected]',+ password: 'password123',+})+client.setToken(token)++// Auto-recover from expired access tokens+client.onUnauthorized(async () => {+ const { token: fresh } = await client.auth.refresh()+ client.setToken(fresh)+ return true // retry the failed request+})++// Sign out — revokes the refresh token server-side+await client.auth.logout()+```++### Bootstrapping a returning session++Because the refresh cookie outlives the in-memory access token, a returning user can be signed back in without re-entering credentials — call `refresh()` on app load and treat failure as "not signed in":++```typescript+try {+ const { token } = await client.auth.refresh()+ client.setToken(token)+} catch {+ // No valid session — show the login form+}+```++### Identity providers++`auth.login()` also accepts third-party identity-provider payloads when the server has a matching strategy registered in `Spree.store_authentication_strategies`:++```typescript+const { token } = await client.auth.login({ provider: 'auth0', token: idpJwt })+```++### Current user and permissions++After signing in, `client.me.get()` returns the admin user's profile together with their serialized permissions — use it to drive what your UI shows:++```typescript+const { user, permissions } = await client.me.get()+```++## Staff invitations++The `auth` resource also exposes the unauthenticated invitation-acceptance flow used when onboarding new staff: `auth.lookupInvitation(id, token)` returns the safe-to-render invitation context (store, role, inviter), and `auth.acceptInvitation(id, token, params)` accepts it — issuing a JWT and refresh cookie identical to `login`. Sending invitations is an authenticated operation on [`client.invitations`](/developer/sdk/admin/resources).++## Custom fetch++Pass a custom `fetch` implementation when you need request interception, proxying, or a non-standard runtime:++```typescript+const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: process.env.SPREE_SECRET_KEY,+ fetch: customFetchImplementation,+})+```diff --git a/docs/developer/sdk/admin/querying-and-errors.mdx b/docs/developer/sdk/admin/querying-and-errors.mdxnew file mode 100644index 0000000000..e5d36c5b7c--- /dev/null+++ b/docs/developer/sdk/admin/querying-and-errors.mdx@@ -0,0 +1,131 @@+---+title: "Querying & Errors"+description: "Filter, sort, paginate, and expand Admin API collections with flat Ransack parameters — and handle structured SpreeError responses."+---++## Filtering++Collection endpoints support [Ransack](https://activerecord-hackery.github.io/ransack/) filters passed as **flat parameters** — append a predicate suffix to any filterable attribute. The SDK wraps filter keys in `q[…]` automatically:++```typescript+const { data: orders } = await client.orders.list({+ status_eq: 'complete', // exact match+ total_gteq: 100, // greater than or equal+ email_cont: '@example.com', // substring match+ user_id_eq: 'cus_xxx', // prefixed IDs work directly+ sort: '-completed_at',+ page: 2,+ limit: 50,+})+```++Common predicates: `_eq`, `_not_eq`, `_cont` (contains), `_start`, `_end`, `_gteq` / `_lteq`, `_gt` / `_lt`, `_in` (array), `_null`. The filterable attributes per resource are listed in the [Admin API reference](/api-reference/admin-api/introduction); each model declares an explicit allowlist, so unknown filter keys are ignored rather than executed.++<Note>+ Foreign-key predicates accept **prefixed IDs** (`user_id_eq: 'cus_xxx'`, `variant_id_in: ['variant_a', 'variant_b']`) — the API translates them; you never handle raw database IDs.+</Note>++## Sorting++Pass `sort` with an attribute name; prefix with `-` for descending. Comma-separate multiple fields:++```typescript+await client.products.list({ sort: '-updated_at,name' })+```++## Pagination++List responses return `{ data, meta }`. Drive pagination with `page` and `limit`:++```typescript+const { data, meta } = await client.products.list({ page: 1, limit: 50 })++meta.count // total records+meta.pages // total pages+meta.next // next page number, or null on the last page+meta.previous // previous page number, or null on the first+```++A simple fetch-all loop:++```typescript+let page: number | null = 1+while (page) {+ const { data, meta } = await client.products.list({ page, limit: 100 })+ process(data)+ page = meta.next+}+```++## Expanding associations++Pass `expand` to embed related records in the response, instead of making follow-up requests. Dot notation reaches nested associations (up to 4 levels):++```typescript+const order = await client.orders.get('order_xxx', {+ expand: ['items', 'customer', 'fulfillments.items'],+})++const products = await client.products.list({+ expand: ['variants', 'variants.media'],+})+```++`fields` does the opposite — trims the response to just the attributes you name (`id` is always included):++```typescript+await client.products.list({ fields: ['name', 'slug', 'status'] })+```++## Error handling++Every non-2xx response throws a `SpreeError` with a stable machine-readable `code`, the HTTP `status`, and optional structured `details`:++```typescript+import { SpreeError } from '@spree/admin-sdk'++try {+ await client.orders.update(orderId, { email })+} catch (err) {+ if (err instanceof SpreeError) {+ err.code // e.g. 'validation_error', 'record_not_found', 'access_denied'+ err.status // e.g. 422+ err.message // human-readable summary+ err.details // optional structured context+ }+}+```++### Validation errors++On `422` responses, `details` maps attribute names to arrays of messages — ready to project onto form fields:++```typescript+try {+ await client.products.create({ name: '' })+} catch (err) {+ if (err instanceof SpreeError && err.status === 422) {+ err.details // { name: ["can't be blank"] }+ }+}+```++### Scope errors++When a request fails because the secret API key lacks the required [scope](/developer/sdk/admin/authentication), the error has `code: 'access_denied'` and `details.required_scope` names the missing scope:++```typescript+catch (err) {+ if (err instanceof SpreeError && err.code === 'access_denied') {+ console.error(`API key is missing scope: ${err.details?.required_scope}`)+ }+}+```++### Expired JWT sessions++For cookie-authenticated apps, register an `onUnauthorized` handler to transparently refresh and retry on `401` — see [Authentication](/developer/sdk/admin/authentication#jwt--cookie-authentication-browser-apps).++## Retries++The SDK retries failed idempotent requests (GET/HEAD, plus requests carrying an idempotency key) with exponential backoff and jitter — transient network errors and retryable statuses recover without any code on your side.diff --git a/docs/developer/sdk/admin/quickstart.mdx b/docs/developer/sdk/admin/quickstart.mdxindex 07d9eab696..2e011d2b7b 100644--- a/docs/developer/sdk/admin/quickstart.mdx+++ b/docs/developer/sdk/admin/quickstart.mdx@@ -1,24 +1,83 @@----title: Admin API-description: Manage your store programmatically with the Spree Admin SDK+title: "Admin SDK"+sidebarTitle: Quickstart+description: "Manage your store programmatically with @spree/admin-sdk — the official TypeScript client for the Spree Admin API v3."----<Info>- The Admin API SDK is coming soon. The `client.admin` namespace is ready and will provide full access to administrative endpoints for managing products, orders, customers, and store settings.-</Info>+[`@spree/admin-sdk`](https://www.npmjs.com/package/@spree/admin-sdk) is the official TypeScript SDK for the [Admin API v3](/api-reference/admin-api/introduction) — the back-office counterpart to [`@spree/sdk`](/developer/sdk/quickstart). Use it to build integrations, automations, internal tools, and custom admin UIs: manage products, orders, customers, stock, promotions, webhooks, and more.-## Preview+<Warning>+ The Admin SDK is in **Developer Preview** on the `0.x` line and published under the `next` dist-tag. The API surface may change between minor versions — check the [changelog](https://github.com/spree/spree/blob/main/packages/admin-sdk/CHANGELOG.md) when updating. It requires Spree 5.5 or newer.+</Warning>++## Installation++```bash+npm install @spree/admin-sdk@next+```++## Quick start++Create a client with a [secret API key](/developer/sdk/admin/authentication) (server-to-server) and start calling resources:```typescript-import { createClient } from '@spree/sdk';+import { createAdminClient } from '@spree/admin-sdk'++const client = createAdminClient({+ baseUrl: 'https://your-store.com',+ secretKey: process.env.SPREE_SECRET_KEY, // sk_xxx — server-side only+})-const client = createClient({- baseUrl: 'https://api.mystore.com',- secretKey: 'sk_xxx', // Admin API requires a secret key-});+// List recent completed orders+const { data: orders, meta } = await client.orders.list({+ status_eq: 'complete',+ sort: '-completed_at',+ limit: 25,+})-// Admin endpoints will be available under client.admin.*-// client.admin.products.list()-// client.admin.orders.list()-// client.admin.customers.list()+// Create a purchasable product — pricing lives on variants+const product = await client.products.create({+ name: 'Aero Hoodie',+ status: 'active',+ tags: ['new-arrivals'],+ variants: [+ {+ sku: 'AERO-HOODIE',+ prices: [{ currency: 'USD', amount: '59.00' }],+ },+ ],+})```++Every method is fully typed — responses use `Admin`-prefixed types generated from the API serializers:++```typescript+import type { AdminOrder, PaginatedResponse } from '@spree/admin-sdk'++const page: PaginatedResponse<AdminOrder> = await client.orders.list()+```++<Note>+ Secret keys grant back-office access — never ship them in browser code. For browser-based admin apps, use [JWT cookie authentication](/developer/sdk/admin/authentication#jwt--cookie-authentication-browser-apps) instead.+</Note>++## Learn more++<CardGroup cols={2}>+ <Card title="Authentication" icon="key" href="/developer/sdk/admin/authentication">+ Secret keys with scopes for servers, JWT + httpOnly refresh cookie for browser apps.+ </Card>+ <Card title="Resources" icon="boxes" href="/developer/sdk/admin/resources">+ The full resource map — products, orders, customers, stock, promotions, webhooks, and more.+ </Card>+ <Card title="Querying & Errors" icon="filter" href="/developer/sdk/admin/querying-and-errors">+ Filtering, sorting, pagination, prefixed IDs, and structured error handling.+ </Card>+ <Card title="Admin API Reference" icon="book" href="/api-reference/admin-api/introduction">+ The underlying REST API the SDK wraps — every endpoint, parameter, and response shape.+ </Card>+</CardGroup>++<Tip>+ Adding your own resources? The [`spree generate api_resource`](/developer/tutorial/api) generator scaffolds Admin API endpoints (model, serializers, controllers, specs) in one command, and the [extending guide](/developer/sdk/extending) shows how to call custom endpoints from the SDK.+</Tip>diff --git a/docs/developer/sdk/admin/resources.mdx b/docs/developer/sdk/admin/resources.mdxnew file mode 100644index 0000000000..16fbe16049--- /dev/null+++ b/docs/developer/sdk/admin/resources.mdx@@ -0,0 +1,126 @@+---+title: "Resources"+description: "The full @spree/admin-sdk resource map — products, orders, customers, inventory, pricing, promotions, store configuration, and platform resources."+---++Every Admin API resource is exposed as a property on the client (`client.orders`, `client.products`, …). Collection resources follow a consistent CRUD shape — `list`, `get`, `create`, `update`, `delete` — plus resource-specific actions. Nested resources take the **parent ID as the first argument**:++```typescript+// Top-level+const order = await client.orders.get('order_xxx')++// Nested — parent ID first+const payments = await client.orders.payments.list('order_xxx')+await client.orders.payments.capture('order_xxx', 'payment_xxx')++// Nested create+await client.customers.addresses.create('cus_xxx', {+ first_name: 'Jane',+ last_name: 'Doe',+ address1: '350 Fifth Avenue',+ city: 'New York',+ postal_code: '10118',+ country_iso: 'US',+ state_abbr: 'NY',+ is_default_shipping: true,+})+```++## Catalog++| Client | Endpoints |+|---|---|+| `client.products` | CRUD, `clone`, and bulk operations (`bulkStatusUpdate`, `bulkAddToCategories` / `bulkRemoveFromCategories`, `bulkAddToChannels` / `bulkRemoveFromChannels`, `bulkAddTags` / `bulkRemoveTags`, `bulkDestroy`). Nested: `media`, `variants` (with their own `media`). |+| `client.variants` | Top-level variant search across products (`list`, `get`). |+| `client.optionTypes` | CRUD on option types and their values. |+| `client.categories` | List categories. |+| `client.tags` | Autocomplete tag names per taggable type. |+| `client.taxCategories` | CRUD on tax categories. |++## Orders & fulfillment++| Client | Endpoints |+|---|---|+| `client.orders` | List, get, create, update, delete, `complete`, `cancel`, `approve`, `resume`, `resendConfirmation`. Nested: `items`, `payments` (incl. `capture` / `void`), `fulfillments` (incl. `fulfill` / `cancel` / `resume` / `split`), `refunds`, `giftCards`, `storeCredits`, `adjustments`. |++## Customers++| Client | Endpoints |+|---|---|+| `client.customers` | CRUD plus bulk group operations (`bulkAddToGroups` / `bulkRemoveFromGroups`) and bulk tags. Nested: `addresses`, `creditCards`, `storeCredits`. |+| `client.customerGroups` | CRUD on customer groups. |++## Pricing & promotions++| Client | Endpoints |+|---|---|+| `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`. |+| `client.promotionActions` | Lookup of available action `types` and `calculators`. |+| `client.promotionRules` | Lookup of available rule `types`. |+| `client.giftCards` | CRUD on gift cards. |+| `client.giftCardBatches` | List, get, and create gift card batches. |+| `client.storeCreditCategories` | List and read store credit categories. |++## Inventory++| Client | Endpoints |+|---|---|+| `client.stockLocations` | CRUD on stock locations. |+| `client.stockItems` | List, get, update, delete stock items. |+| `client.stockTransfers` | List, get, create, delete stock transfers. |++## Sales channels++| Client | Endpoints |+|---|---|+| `client.channels` | CRUD plus `addProducts` / `removeProducts`. |+| `client.markets` | CRUD on markets. |++## Store configuration++| Client | Endpoints |+|---|---|+| `client.store` | Store profile (`get`, `update`). |+| `client.paymentMethods` | CRUD plus `types` (available gateway types). |+| `client.countries` | List and read countries (for address dropdowns). |+| `client.customFieldDefinitions` | CRUD on [custom field](/developer/core-concepts/metafields) definitions. |+| `client.exports` | Create and track CSV exports (products, orders, customers, …). |+| `client.directUploads` | Pre-signed Active Storage uploads (used by media flows). |++## Platform & access++| Client | Endpoints |+|---|---|+| `client.auth` | Login (email/password or identity provider), cookie-driven refresh, logout, invitation lookup/acceptance — see [Authentication](/developer/sdk/admin/authentication). |+| `client.me` | Current admin user + permissions. |+| `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, `sendTest`, `enable` / `disable`. Nested: `deliveries` (list, get, `redeliver`). |+| `client.dashboard` | Sales analytics. |++## Custom fields++Resources that support [custom fields](/developer/core-concepts/metafields) (products, variants, orders, customers, categories, option types) expose a `customFields` accessor taking the parent ID first:++```typescript+await client.products.customFields.list('prod_xxx')+await client.products.customFields.create('prod_xxx', {+ custom_field_definition_id: 'cfd_xxx',+ value: 'limited-edition',+})+```++The generic escape hatch covers any owner type:++```typescript+await client.customFields('Spree::Product', 'prod_xxx').list()+```++## Adding your own resources++The resource map grows with your store. The [`spree generate api_resource`](/developer/tutorial/api) generator scaffolds new Admin API endpoints (model, serializers, controllers, routes, specs) in one command — then call them from the SDK with a [custom fetch or raw request](/developer/sdk/extending), or generate a typed client for them.diff --git a/docs/developer/sdk/quickstart.mdx b/docs/developer/sdk/quickstart.mdxindex 548c232d56..e58c60f8de 100644--- a/docs/developer/sdk/quickstart.mdx+++ b/docs/developer/sdk/quickstart.mdx@@ -3,6 +3,8 @@ title: Quickstartdescription: Install the Spree TypeScript SDK, configure your Store API client, and make your first calls to products, carts, checkout, and customer endpoints.---+`@spree/sdk` is the customer-facing SDK — products, carts, checkout, and account flows against the Store API. For back-office integrations (managing products, orders, customers, stock), use the [Admin SDK](/developer/sdk/admin/quickstart).+## Installation```bash@@ -70,7 +72,6 @@ The SDK uses a resource builder pattern for nested resources:| `customer` | `orders` | `list` || `customer` | `paymentSetupSessions` | `create`, `get`, `complete` || `policies` | — | `list`, `get` |-| `categories` | `products` | `list` || `wishlists` | `items` | `create`, `update`, `delete` |```typescript@@ -79,7 +80,6 @@ await client.carts.items.create(cartId, params, options);await client.carts.payments.list(cartId, options);await client.carts.fulfillments.update(cartId, fulfillmentId, params, options);await client.customer.addresses.list({}, options);-await client.categories.products.list(categoryId, params, options);await client.wishlists.items.create(wishlistId, params, options);```diff --git a/docs/developer/tutorial/api.mdx b/docs/developer/tutorial/api.mdxindex b1025310f9..9264e0de82 100644--- a/docs/developer/tutorial/api.mdx+++ b/docs/developer/tutorial/api.mdx@@ -373,7 +373,7 @@ curl -X POST -H "X-Spree-API-Key: sk_YOUR_KEY" \```<Info>- Secret keys carry scopes (`read_brands`, `write_brands` style) and JWT admin users go through CanCanCan abilities — see [API authentication](/developer/customization/api) for the full model.+ Secret keys carry scopes (`read_brands`, `write_brands` style) and JWT admin users go through CanCanCan abilities — see [API authentication](/developer/customization/api) for the full model. From TypeScript, the [Admin SDK](/developer/sdk/admin/quickstart) wraps the Admin API with typed clients for all built-in resources.</Info>## Step 6: Add Brand to Product Responsesdiff --git a/docs/docs.json b/docs/docs.jsonindex 82bff6537b..88d3f1ccf3 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -472,9 +472,9 @@"tab": "SDK & Tools","menu": [{- "item": "SDK",+ "item": "Store SDK","icon": "code",- "description": "JavaScript/TypeScript SDK for Spree API",+ "description": "TypeScript SDK for the Store API","groups": [{"group": "Getting Started",@@ -495,11 +495,21 @@"developer/sdk/store/account","developer/sdk/store/wishlists"]- },+ }+ ]+ },+ {+ "item": "Admin SDK",+ "icon": "shield-check",+ "description": "TypeScript SDK for the Admin API",+ "groups": [{- "group": "Admin API",+ "group": "Admin SDK","pages": [- "developer/sdk/admin/quickstart"+ "developer/sdk/admin/quickstart",+ "developer/sdk/admin/authentication",+ "developer/sdk/admin/resources",+ "developer/sdk/admin/querying-and-errors"]}]diff --git a/packages/README.md b/packages/README.mdindex b6cbb780c7..cdc0ab7849 100644--- a/packages/README.md+++ b/packages/README.md@@ -18,7 +18,7 @@ For monorepo-wide conventions (type generation pipeline, code style, testing) se| Package | npm | Status | Description ||---|---|---|---|| [`sdk`](./sdk) | [`@spree/sdk`](https://www.npmjs.com/package/@spree/sdk) | **Stable** (1.x) | TypeScript client for the customer-facing **Store API v3**. |-| [`admin-sdk`](./admin-sdk) | [`@spree/admin-sdk`](https://www.npmjs.com/package/@spree/admin-sdk) | **Developer Preview** (0.x) | TypeScript client for the **Admin API**. Tracks Spree 6.0 development. |+| [`admin-sdk`](./admin-sdk) | [`@spree/admin-sdk`](https://www.npmjs.com/package/@spree/admin-sdk) | **Developer Preview** (0.x) | TypeScript client for the **Admin API v3** (Spree 5.5+). Published under the `next` dist-tag. || [`dashboard`](./dashboard) | `@spree/dashboard` (not yet published) | **In Development** | React SPA admin dashboard for Spree 6.0. Will replace the legacy Rails `spree/admin` engine. Currently private in the workspace; will be published as `@spree/dashboard` once ready. || [`dashboard-ui`](./dashboard-ui) | `@spree/dashboard-ui` (not yet published) | **In Development** | Design system for the dashboard — shadcn primitives, headless composed components, design tokens. Source-only; consumed by `@spree/dashboard` and downstream plugin authors. || [`dashboard-core`](./dashboard-core) | `@spree/dashboard-core` (not yet published) | **In Development** | Dashboard framework — registries (table, nav, slot, settings-nav), providers, generic infra hooks, `defineDashboardPlugin`. The extension API surface. |@@ -37,7 +37,7 @@ Includes auto-generated TypeScript types and Zod schemas derived from the RailsThe back-office counterpart to `@spree/sdk`. Same patterns, but targets the Admin API and supports both **secret API key** (server-to-server, scope-based authorization) and **JWT** (admin user, CanCanCan-based authorization) auth modes. Used internally by the `@spree/dashboard` SPA and externally by integrations and admin tooling.-This package is in **Developer Preview** alongside the Spree 6.0 Admin API. Expect breaking changes between minor versions until 1.0.+The Admin API v3 ships with Spree 5.5; the SDK is in **Developer Preview** on the 0.x line (published under the `next` dist-tag). Expect breaking changes between minor versions until 1.0.### `@spree/dashboard`, `@spree/dashboard-core`, `@spree/dashboard-ui` — the admin dashboard stackdiff --git a/packages/admin-sdk/.changeset/admin-cookie-auth.md b/packages/admin-sdk/.changeset/admin-cookie-auth.mddeleted file mode 100644index 32905c605b..0000000000--- a/packages/admin-sdk/.changeset/admin-cookie-auth.md+++ /dev/null@@ -1,19 +0,0 @@-----'@spree/admin-sdk': minor------Cookie-backed admin authentication. The refresh token now lives in an `HttpOnly` signed cookie scoped to `/api/v3/admin/auth` instead of being returned in JSON; the access token is the only thing the SPA holds in memory. This eliminates the most attractive XSS target on the admin SPA and adds a real server-side logout that destroys the refresh-token row.--CSRF protection is provided by the combination of the cookie's `SameSite` attribute and the existing `Spree::AllowedOrigin` allowlist enforced via `Rack::Cors` — no separate CSRF token is issued or required by the SDK.--**Note on bump type:** `@spree/admin-sdk` is on a 0.x version line (`next` dist-tag, Developer Preview). Per semver §4 and Changesets convention, breaking changes on 0.x packages bump the minor — moving to `major` would mean 1.0.0 and signal API stability we do not yet guarantee. The changes below are breaking; coordinated with the server-side change shipping in Spree 5.5.--**Breaking changes:**--- `AuthTokens` no longer contains `refresh_token`. The shape is `{ token, user }`.-- `client.auth.refresh()` takes no arguments — it reads the refresh-token cookie. Previously it required `{ refresh_token }` in the body.-- New `client.auth.logout()` — POSTs to `/api/v3/admin/auth/logout`, which destroys the refresh-token row server-side and clears the auth cookie. Idempotent.-- `createAdminClient()` now defaults to `credentials: 'include'` so cookies flow on cross-origin requests. Override via `createAdminClient({ credentials: 'omit' })` if needed.-- The `secretKey || jwtToken` constructor guard has been relaxed: a cookie-auth SPA may start with neither and bootstrap by calling `auth.refresh()` immediately. Server-to-server callers should still pass `secretKey`.--When using `baseUrl: ''` (e.g. with a Vite dev proxy), the SDK now resolves the relative path against `window.location.origin` so `new URL` doesn't throw.diff --git a/packages/admin-sdk/.changeset/admin-csv-exports.md b/packages/admin-sdk/.changeset/admin-csv-exports.mddeleted file mode 100644index 31a26bd02a..0000000000--- a/packages/admin-sdk/.changeset/admin-csv-exports.md+++ /dev/null@@ -1,11 +0,0 @@-----'@spree/admin-sdk': minor------Admin CSV exports — bring back filtered CSV downloads of products, orders, customers, etc. that the legacy Rails admin supported.--- New `client.exports` resource with `list / get / create / delete`.-- New `ExportCreateParams` / `ExportType` request types and `Export` entity type.-- `Export.download_url` is the path to a server-side download endpoint (`GET /api/v3/admin/exports/:id/download`) that 303s to a freshly-signed ActiveStorage URL — assign it to `window.location.href` to trigger the download.-- `Export.done` flips to `true` once the background job finishes generating and attaching the CSV; clients should poll `get(id)` until then.-- `search_params` accepts the same Ransack predicate shape (`{ name_cont, price_gt, … }`) used on list endpoints, so toolbar filter state can be forwarded as-is.diff --git a/packages/admin-sdk/.changeset/admin-custom-fields-crud.md b/packages/admin-sdk/.changeset/admin-custom-fields-crud.mddeleted file mode 100644index 4aa9eee316..0000000000--- a/packages/admin-sdk/.changeset/admin-custom-fields-crud.md+++ /dev/null@@ -1,13 +0,0 @@-----'@spree/admin-sdk': minor------Custom Fields CRUD API + token-based `field_type`.--- New `client.{products,variants,orders,customers,categories,optionTypes}.customFields` accessors with `list / get / create / update / delete`.-- New top-level `client.customFieldDefinitions` accessor with full CRUD.-- New generic escape hatch `client.customFields(ownerType, ownerId)` for plugin-defined parents that don't have a first-class accessor.-- `CustomField.field_type` and `CustomFieldDefinition.field_type` are now string-literal unions (`'short_text' | 'long_text' | 'rich_text' | 'number' | 'boolean' | 'json' | (string & {})`) instead of plain `string`. Built-ins narrow + autocomplete; plugin tokens still type-check.-- `CustomField` retains the legacy `type` field (Ruby STI class name) alongside the new `field_type` token. The TypeScript type is annotated with `@deprecated` so editors surface the migration tip on hover; eslint with `no-deprecated` will flag references. Migrate to `field_type`; `type` will be removed in a future minor.-- New `CustomFieldDefinition` type exported from the package.-- Includes the `Spree::CustomField` / `Spree::CustomFieldDefinition` constant aliases on the server side; no naming changes to existing models or table layout.diff --git a/packages/admin-sdk/.changeset/admin-sprint-3-writes.md b/packages/admin-sdk/.changeset/admin-sprint-3-writes.mddeleted file mode 100644index 73c5cc0a21..0000000000--- a/packages/admin-sdk/.changeset/admin-sprint-3-writes.md+++ /dev/null@@ -1,12 +0,0 @@-----'@spree/admin-sdk': minor------Sprint 3: utility CRUD writes for tax categories, stock items, stock transfers, and payment methods.--- `client.taxCategories` gains `get / create / update / delete`. Backed by `/api/v3/admin/tax_categories`. The serializer now exposes `description` alongside `name`, `tax_code`, and `is_default`. Setting `is_default: true` on create or update auto-demotes the previous default.-- `client.stockItems` is new with `list / get / update / delete`. Adjust `count_on_hand` and `backorderable` on existing variant/location pairings. Stock items are auto-created when a variant lands at a stock location, so there's no `create` here — use the variants and stock-locations endpoints for that flow. Filterable via Ransack on `count_on_hand`, `stock_location_id`, and `variant_id`.-- `client.stockTransfers` is new with `list / get / create / delete`. Backed by `/api/v3/admin/stock_transfers`. The create body takes a `variants: [{ variant_id, quantity }]` array; pass `source_location_id` for a transfer between two locations or omit it to record an external vendor receive at the destination. The model fans the payload out across `stock_movements` and adjusts source/destination `count_on_hand` atomically.-- `client.paymentMethods` gains `create / update / delete / types`. The create body requires `type` (the fully-qualified STI subclass, e.g. `'Spree::PaymentMethod::Check'`); unknown types return a 422 with `unknown_payment_method_type`. New payment methods are scoped to the current store automatically. The serializer now exposes `display_on` and `position` on top of the existing `name`, `description`, `type`, `active`, and `auto_capture`. `client.paymentMethods.types()` returns the registered subclasses as `[{ type, label, description }]` so admin UIs can render a provider dropdown without hard-coding class names.--Provider-specific configuration (Stripe API keys, PayPal credentials, etc.) is **not** part of this release — that lands with the universal preferences form in the next sprint.diff --git a/packages/admin-sdk/.changeset/admin-sprint-4-promotions.md b/packages/admin-sdk/.changeset/admin-sprint-4-promotions.mddeleted file mode 100644index b3f0f4e3b2..0000000000--- a/packages/admin-sdk/.changeset/admin-sprint-4-promotions.md+++ /dev/null@@ -1,19 +0,0 @@-----'@spree/admin-sdk': minor------Sprint 4: full admin promotion stack — promotions, actions, rules, and coupon codes.--- `client.promotions` is new with `list / get / create / update / delete`. Mirrors `Spree::Promotion`: `name`, `description`, `code`, `starts_at`, `expires_at`, `usage_limit`, `match_policy`, `kind` (`'coupon_code' | 'automatic'`), `multi_codes` + `number_of_codes` + `code_prefix` for batch coupon generation, `path`, `advertise`, `promotion_category_id`, and `store_ids`.--- `client.promotions.actions` (nested) handles the STI subclass pattern: `list / get / create / update / delete` on `/promotions/:id/promotion_actions`. The create body takes a `type` (the fully-qualified subclass like `'Spree::Promotion::Actions::FreeShipping'`) plus a `preferences: { ... }` hash that round-trips through the typed setters declared on the subclass.--- `client.promotions.rules` (nested) is the same shape for `Spree::PromotionRule` subclasses (Currency, Country, ItemTotal, Product, Taxon, etc.).--- `client.promotions.couponCodes` (nested) is read-only — `list / get`. Coupon codes are server-generated based on the promotion's `multi_codes` settings.--- `client.promotionActions.types()` and `client.promotionRules.types()` are top-level discovery endpoints. Each returns `{ data: ResourceTypeDefinition[] }` where each entry is `{ type, label, description, preference_schema }`. The `preference_schema` describes the configurable knobs for a given subclass — `[{ key, type, default }]` — so admin UIs can render generic configuration forms without hard-coding per-subclass field lists.--- `client.paymentMethods.create / update` now accept an optional `preferences` hash, matching the same round-trip pattern. The serializer payload also gains `preferences` (current values) and `preference_schema` (shape).--- New shared types: `PreferenceField`, `ResourceTypeDefinition`. The previously-shipped `PaymentMethodType` is now an alias of `ResourceTypeDefinition`.diff --git a/packages/admin-sdk/.changeset/admin-staff-and-api-keys.md b/packages/admin-sdk/.changeset/admin-staff-and-api-keys.mddeleted file mode 100644index 67d8ad16c4..0000000000--- a/packages/admin-sdk/.changeset/admin-staff-and-api-keys.md+++ /dev/null@@ -1,14 +0,0 @@-----'@spree/admin-sdk': minor------Staff and API key management.--- New `client.adminUsers` accessor with `list / get / update / delete`. Listing is scoped to admin users with at least one role assignment on the current store. `delete` removes the per-store role assignment rather than deleting the global account, so the user keeps access to any other stores.-- New `client.invitations` accessor with `list / get / create / delete / resend`. Invitations carry an `email` + prefixed `role_id`; on accept, a per-store `RoleUser` is created. `resend` issues a fresh token and re-dispatches the invitation email.-- New `client.apiKeys` accessor with `list / get / create / update / delete / revoke`. Supports both `publishable` (storefront) and `secret` (server-to-server) keys. The plaintext token for secret keys is delivered exactly once on the create response — store it client-side immediately because subsequent reads expose only `token_prefix`. `revoke` marks the key revoked while preserving the row for audit.-- New `client.roles` accessor with `list / get`. Read-only — used to populate the role picker on the staff invite/edit forms.-- New `client.auth.lookupInvitation(id, token)` and `client.auth.acceptInvitation(id, token, params)`. Public (unauthenticated) endpoints that drive the SPA invitation acceptance screen — `lookup` returns the safe-to-render context (store, role, inviter, `invitee_exists`) so the page can pick between sign-in (existing account) and signup (new account); `accept` creates the user if needed, marks the invitation accepted, and issues a JWT + refresh-token cookie identical to `auth.login`.-- `Invitation` now carries `acceptance_url` — the shareable link the SPA's "Copy invitation link" action and the invitation email both use.-- New types: `ApiKey`, `Invitation`, `Role`, `InvitationLookup`. `AdminUser` now includes a `roles` field with the role assignments scoped to the current store.-- New params types: `ApiKeyCreateParams`, `ApiKeyUpdateParams`, `InvitationCreateParams`, `InvitationAcceptParams`, `AdminUserUpdateParams`.diff --git a/packages/admin-sdk/.changeset/admin-stock-locations.md b/packages/admin-sdk/.changeset/admin-stock-locations.mddeleted file mode 100644index a8cdb59890..0000000000--- a/packages/admin-sdk/.changeset/admin-stock-locations.md+++ /dev/null@@ -1,10 +0,0 @@-----'@spree/admin-sdk': minor------Stock location management.--- New `client.stockLocations` accessor with `list / get / create / update / delete`. Backed by `/api/v3/admin/stock_locations`. Listing supports the standard Ransack filters (`name_cont`, `active_eq`, `kind_eq`, `pickup_enabled_eq`, etc.) plus default ordering by `default desc, name asc` so the default location surfaces first.-- New params types: `StockLocationCreateParams`, `StockLocationUpdateParams`. Address fields use `country_iso` (ISO-3166 alpha-2 country code, e.g. `'US'`) and `state_abbr` (state/province abbreviation, e.g. `'NY'`) — the same opaque handles used everywhere else in the API for countries and states.-- The `StockLocation` entity gains the 6.0 fulfillment-and-delivery columns: `kind` (`'warehouse' | 'store' | 'fulfillment_center'`, open string — plugins can register custom kinds), `pickup_enabled`, `pickup_stock_policy` (`'local'` keeps stock at the location only; `'any'` allows transfer-in / ship-to-store), `pickup_ready_in_minutes`, and `pickup_instructions`. These are the storefront-facing fields the upcoming pickup-fulfillment flow surfaces at checkout. See `docs/plans/6.0-fulfillment-and-delivery.md` for the wider context.-- Admin serializer now also exposes `admin_name`, `address2`, `state_name`, `phone`, `company`, plus `created_at` / `updated_at`.diff --git a/packages/admin-sdk/.changeset/admin-store-credit-categories.md b/packages/admin-sdk/.changeset/admin-store-credit-categories.mddeleted file mode 100644index da64194f9c..0000000000--- a/packages/admin-sdk/.changeset/admin-store-credit-categories.md+++ /dev/null@@ -1,10 +0,0 @@-----'@spree/admin-sdk': minor------Store credit category lookups + richer store credit payloads.--- New `client.storeCreditCategories` accessor with `list / get`. Backed by `/api/v3/admin/store_credit_categories`. Read-only — categories are configured at the store level and used to classify issued store credits ("Goodwill", "Refund", "Gift Card", etc.). Ransack filtering supported (e.g. `q[name_cont]`).-- New `StoreCreditCategory` type exported from the package: `{ id, name, non_expiring, created_at, updated_at }`. `non_expiring` reflects whether the category name appears in `Spree::Config[:non_expiring_credit_types]`.-- The admin `StoreCredit` shape now includes `category_id`, `category_name`, and `memo`. `category_id` round-trips with the categories endpoint above; `category_name` is delegated from the associated category for display without an extra fetch; `memo` is the merchant-visible note set when the credit was issued.-- The existing `client.customers.storeCredits.{create,update}` endpoints have not changed shape — `category_id` and `memo` were already accepted on write; this release only surfaces them on read.diff --git a/packages/admin-sdk/.changeset/login-provider-dispatch.md b/packages/admin-sdk/.changeset/login-provider-dispatch.mddeleted file mode 100644index 8e08967e7d..0000000000--- a/packages/admin-sdk/.changeset/login-provider-dispatch.md+++ /dev/null@@ -1,5 +0,0 @@-----'@spree/admin-sdk': minor------Add provider-dispatched login. `client.auth.login()` now accepts third-party identity-provider payloads (e.g. `{ provider: 'okta', token: '<jwt>' }`) in addition to the existing `{ email, password }` shape — `LoginCredentials` is now a discriminated union of `EmailPasswordLogin | ProviderLogin`, both newly exported. Pairs with the server-side strategy registry at `Spree.admin_authentication_strategies`. Existing email/password calls are unchanged.diff --git a/packages/admin-sdk/.changeset/product-option-values.md b/packages/admin-sdk/.changeset/product-option-values.mddeleted file mode 100644index 1a5f2ed9d8..0000000000--- a/packages/admin-sdk/.changeset/product-option-values.md+++ /dev/null@@ -1,7 +0,0 @@-----'@spree/admin-sdk': patch------Expose `Product.option_values` in the Admin API.--The `Product` type now includes an optional `option_values: Array<OptionValue>` field, listing the option values that are actually in use across the product's variants — useful for rendering option pickers and variant matrices in the admin without iterating over every variant.diff --git a/packages/admin-sdk/CHANGELOG.md b/packages/admin-sdk/CHANGELOG.mdnew file mode 100644index 0000000000..7c5a097970--- /dev/null+++ b/packages/admin-sdk/CHANGELOG.md@@ -0,0 +1,97 @@+# @spree/admin-sdk++## 0.2.0++### Minor Changes++- Cookie-backed admin authentication. The refresh token now lives in an `HttpOnly` signed cookie scoped to `/api/v3/admin/auth` instead of being returned in JSON; the access token is the only thing the SPA holds in memory. This eliminates the most attractive XSS target on the admin SPA and adds a real server-side logout that destroys the refresh-token row.++ CSRF protection is provided by the combination of the cookie's `SameSite` attribute and the existing `Spree::AllowedOrigin` allowlist enforced via `Rack::Cors` — no separate CSRF token is issued or required by the SDK.++ **Note on bump type:** `@spree/admin-sdk` is on a 0.x version line (`next` dist-tag, Developer Preview). Per semver §4 and Changesets convention, breaking changes on 0.x packages bump the minor — moving to `major` would mean 1.0.0 and signal API stability we do not yet guarantee. The changes below are breaking; coordinated with the server-side change shipping in Spree 5.5.++ **Breaking changes:**++ - `AuthTokens` no longer contains `refresh_token`. The shape is `{ token, user }`.+ - `client.auth.refresh()` takes no arguments — it reads the refresh-token cookie. Previously it required `{ refresh_token }` in the body.+ - New `client.auth.logout()` — POSTs to `/api/v3/admin/auth/logout`, which destroys the refresh-token row server-side and clears the auth cookie. Idempotent.+ - `createAdminClient()` now defaults to `credentials: 'include'` so cookies flow on cross-origin requests. Override via `createAdminClient({ credentials: 'omit' })` if needed.+ - The `secretKey || jwtToken` constructor guard has been relaxed: a cookie-auth SPA may start with neither and bootstrap by calling `auth.refresh()` immediately. Server-to-server callers should still pass `secretKey`.++ When using `baseUrl: ''` (e.g. with a Vite dev proxy), the SDK now resolves the relative path against `window.location.origin` so `new URL` doesn't throw.++- Admin CSV exports — bring back filtered CSV downloads of products, orders, customers, etc. that the legacy Rails admin supported.++ - New `client.exports` resource with `list / get / create / delete`.+ - New `ExportCreateParams` / `ExportType` request types and `Export` entity type.+ - `Export.download_url` is the path to a server-side download endpoint (`GET /api/v3/admin/exports/:id/download`) that 303s to a freshly-signed ActiveStorage URL — assign it to `window.location.href` to trigger the download.+ - `Export.done` flips to `true` once the background job finishes generating and attaching the CSV; clients should poll `get(id)` until then.+ - `search_params` accepts the same Ransack predicate shape (`{ name_cont, price_gt, … }`) used on list endpoints, so toolbar filter state can be forwarded as-is.++- Custom Fields CRUD API + token-based `field_type`.++ - New `client.{products,variants,orders,customers,categories,optionTypes}.customFields` accessors with `list / get / create / update / delete`.+ - New top-level `client.customFieldDefinitions` accessor with full CRUD.+ - New generic escape hatch `client.customFields(ownerType, ownerId)` for plugin-defined parents that don't have a first-class accessor.+ - `CustomField.field_type` and `CustomFieldDefinition.field_type` are now string-literal unions (`'short_text' | 'long_text' | 'rich_text' | 'number' | 'boolean' | 'json' | (string & {})`) instead of plain `string`. Built-ins narrow + autocomplete; plugin tokens still type-check.+ - `CustomField` retains the legacy `type` field (Ruby STI class name) alongside the new `field_type` token. The TypeScript type is annotated with `@deprecated` so editors surface the migration tip on hover; eslint with `no-deprecated` will flag references. Migrate to `field_type`; `type` will be removed in a future minor.+ - New `CustomFieldDefinition` type exported from the package.+ - Includes the `Spree::CustomField` / `Spree::CustomFieldDefinition` constant aliases on the server side; no naming changes to existing models or table layout.++- Sprint 3: utility CRUD writes for tax categories, stock items, stock transfers, and payment methods.++ - `client.taxCategories` gains `get / create / update / delete`. Backed by `/api/v3/admin/tax_categories`. The serializer now exposes `description` alongside `name`, `tax_code`, and `is_default`. Setting `is_default: true` on create or update auto-demotes the previous default.+ - `client.stockItems` is new with `list / get / update / delete`. Adjust `count_on_hand` and `backorderable` on existing variant/location pairings. Stock items are auto-created when a variant lands at a stock location, so there's no `create` here — use the variants and stock-locations endpoints for that flow. Filterable via Ransack on `count_on_hand`, `stock_location_id`, and `variant_id`.+ - `client.stockTransfers` is new with `list / get / create / delete`. Backed by `/api/v3/admin/stock_transfers`. The create body takes a `variants: [{ variant_id, quantity }]` array; pass `source_location_id` for a transfer between two locations or omit it to record an external vendor receive at the destination. The model fans the payload out across `stock_movements` and adjusts source/destination `count_on_hand` atomically.+ - `client.paymentMethods` gains `create / update / delete / types`. The create body requires `type` (the fully-qualified STI subclass, e.g. `'Spree::PaymentMethod::Check'`); unknown types return a 422 with `unknown_payment_method_type`. New payment methods are scoped to the current store automatically. The serializer now exposes `display_on` and `position` on top of the existing `name`, `description`, `type`, `active`, and `auto_capture`. `client.paymentMethods.types()` returns the registered subclasses as `[{ type, label, description }]` so admin UIs can render a provider dropdown without hard-coding class names.++ Provider-specific configuration (Stripe API keys, PayPal credentials, etc.) is **not** part of this release — that lands with the universal preferences form in the next sprint.++- Sprint 4: full admin promotion stack — promotions, actions, rules, and coupon codes.++ - `client.promotions` is new with `list / get / create / update / delete`. Mirrors `Spree::Promotion`: `name`, `description`, `code`, `starts_at`, `expires_at`, `usage_limit`, `match_policy`, `kind` (`'coupon_code' | 'automatic'`), `multi_codes` + `number_of_codes` + `code_prefix` for batch coupon generation, `path`, `advertise`, `promotion_category_id`, and `store_ids`.++ - `client.promotions.actions` (nested) handles the STI subclass pattern: `list / get / create / update / delete` on `/promotions/:id/promotion_actions`. The create body takes a `type` (the fully-qualified subclass like `'Spree::Promotion::Actions::FreeShipping'`) plus a `preferences: { ... }` hash that round-trips through the typed setters declared on the subclass.++ - `client.promotions.rules` (nested) is the same shape for `Spree::PromotionRule` subclasses (Currency, Country, ItemTotal, Product, Taxon, etc.).++ - `client.promotions.couponCodes` (nested) is read-only — `list / get`. Coupon codes are server-generated based on the promotion's `multi_codes` settings.++ - `client.promotionActions.types()` and `client.promotionRules.types()` are top-level discovery endpoints. Each returns `{ data: ResourceTypeDefinition[] }` where each entry is `{ type, label, description, preference_schema }`. The `preference_schema` describes the configurable knobs for a given subclass — `[{ key, type, default }]` — so admin UIs can render generic configuration forms without hard-coding per-subclass field lists.++ - `client.paymentMethods.create / update` now accept an optional `preferences` hash, matching the same round-trip pattern. The serializer payload also gains `preferences` (current values) and `preference_schema` (shape).++ - New shared types: `PreferenceField`, `ResourceTypeDefinition`. The previously-shipped `PaymentMethodType` is now an alias of `ResourceTypeDefinition`.++- Staff and API key management.++ - New `client.adminUsers` accessor with `list / get / update / delete`. Listing is scoped to admin users with at least one role assignment on the current store. `delete` removes the per-store role assignment rather than deleting the global account, so the user keeps access to any other stores.+ - New `client.invitations` accessor with `list / get / create / delete / resend`. Invitations carry an `email` + prefixed `role_id`; on accept, a per-store `RoleUser` is created. `resend` issues a fresh token and re-dispatches the invitation email.+ - New `client.apiKeys` accessor with `list / get / create / update / delete / revoke`. Supports both `publishable` (storefront) and `secret` (server-to-server) keys. The plaintext token for secret keys is delivered exactly once on the create response — store it client-side immediately because subsequent reads expose only `token_prefix`. `revoke` marks the key revoked while preserving the row for audit.+ - New `client.roles` accessor with `list / get`. Read-only — used to populate the role picker on the staff invite/edit forms.+ - New `client.auth.lookupInvitation(id, token)` and `client.auth.acceptInvitation(id, token, params)`. Public (unauthenticated) endpoints that drive the SPA invitation acceptance screen — `lookup` returns the safe-to-render context (store, role, inviter, `invitee_exists`) so the page can pick between sign-in (existing account) and signup (new account); `accept` creates the user if needed, marks the invitation accepted, and issues a JWT + refresh-token cookie identical to `auth.login`.+ - `Invitation` now carries `acceptance_url` — the shareable link the SPA's "Copy invitation link" action and the invitation email both use.+ - New types: `ApiKey`, `Invitation`, `Role`, `InvitationLookup`. `AdminUser` now includes a `roles` field with the role assignments scoped to the current store.+ - New params types: `ApiKeyCreateParams`, `ApiKeyUpdateParams`, `InvitationCreateParams`, `InvitationAcceptParams`, `AdminUserUpdateParams`.++- Stock location management.++ - New `client.stockLocations` accessor with `list / get / create / update / delete`. Backed by `/api/v3/admin/stock_locations`. Listing supports the standard Ransack filters (`name_cont`, `active_eq`, `kind_eq`, `pickup_enabled_eq`, etc.) plus default ordering by `default desc, name asc` so the default location surfaces first.+ - New params types: `StockLocationCreateParams`, `StockLocationUpdateParams`. Address fields use `country_iso` (ISO-3166 alpha-2 country code, e.g. `'US'`) and `state_abbr` (state/province abbreviation, e.g. `'NY'`) — the same opaque handles used everywhere else in the API for countries and states.+ - The `StockLocation` entity gains the 6.0 fulfillment-and-delivery columns: `kind` (`'warehouse' | 'store' | 'fulfillment_center'`, open string — plugins can register custom kinds), `pickup_enabled`, `pickup_stock_policy` (`'local'` keeps stock at the location only; `'any'` allows transfer-in / ship-to-store), `pickup_ready_in_minutes`, and `pickup_instructions`. These are the storefront-facing fields the upcoming pickup-fulfillment flow surfaces at checkout. See `docs/plans/6.0-fulfillment-and-delivery.md` for the wider context.+ - Admin serializer now also exposes `admin_name`, `address2`, `state_name`, `phone`, `company`, plus `created_at` / `updated_at`.++- Store credit category lookups + richer store credit payloads.++ - New `client.storeCreditCategories` accessor with `list / get`. Backed by `/api/v3/admin/store_credit_categories`. Read-only — categories are configured at the store level and used to classify issued store credits ("Goodwill", "Refund", "Gift Card", etc.). Ransack filtering supported (e.g. `q[name_cont]`).+ - New `StoreCreditCategory` type exported from the package: `{ id, name, non_expiring, created_at, updated_at }`. `non_expiring` reflects whether the category name appears in `Spree::Config[:non_expiring_credit_types]`.+ - The admin `StoreCredit` shape now includes `category_id`, `category_name`, and `memo`. `category_id` round-trips with the categories endpoint above; `category_name` is delegated from the associated category for display without an extra fetch; `memo` is the merchant-visible note set when the credit was issued.+ - The existing `client.customers.storeCredits.{create,update}` endpoints have not changed shape — `category_id` and `memo` were already accepted on write; this release only surfaces them on read.++- Add provider-dispatched login. `client.auth.login()` now accepts third-party identity-provider payloads (e.g. `{ provider: 'okta', token: '<jwt>' }`) in addition to the existing `{ email, password }` shape — `LoginCredentials` is now a discriminated union of `EmailPasswordLogin | ProviderLogin`, both newly exported. Pairs with the server-side strategy registry at `Spree.admin_authentication_strategies`. Existing email/password calls are unchanged.++### Patch Changes++- Expose `Product.option_values` in the Admin API.++ The `Product` type now includes an optional `option_values: Array<OptionValue>` field, listing the option values that are actually in use across the product's variants — useful for rendering option pickers and variant matrices in the admin without iterating over every variant.diff --git a/packages/admin-sdk/README.md b/packages/admin-sdk/README.mdindex 44781c3b0d..71e6c4f735 100644--- a/packages/admin-sdk/README.md+++ b/packages/admin-sdk/README.md@@ -88,49 +88,80 @@ const client = createAdminClient({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-const client = createAdminClient({- baseUrl: 'https://store.example.com',- jwtToken: '<jwt>',-})+// 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' })-// Or login interactively:-const tempClient = createAdminClient({ baseUrl, secretKey })-const { token, refresh_token, user } = await tempClient.auth.login({+// 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)-const adminClient = createAdminClient({ baseUrl, jwtToken: token })-adminClient.onUnauthorized(async () => {- const { token: fresh } = await tempClient.auth.refresh({ token: refresh_token })- adminClient.setToken(fresh)+// 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()```-## Resource clients+`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`.-Top-level resources:+## Resource clients| Client | Endpoints ||---|---|-| `client.orders` | List, get, create, update, delete, complete, cancel, approve, resume, resend confirmation. Nested: `items`, `payments`, `fulfillments`, `refunds`, `giftCards`, `storeCredits`, `adjustments`. |-| `client.customers` | List, get, create, update, delete. Nested: `addresses`, `creditCards`, `storeCredits`. |-| `client.products` | List, get, create, update, delete. Nested: `media`, `variants` (which also has `media`). |+| `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 and read categories. |-| `client.paymentMethods` | List and read configured payment methods. |-| `client.taxCategories` | List and read tax categories. |-| `client.countries` | List and read countries (for address dropdowns). |+| `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. |+| `client.store` | Store profile (get, update). || `client.me` | Current admin user + permissions. |-| `client.auth` | Login, refresh. |+| `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()+```+## QueryingCollection endpoints support [Ransack](https://activerecord-hackery.github.io/ransack/) filters via flat parameters:@@ -204,6 +235,7 @@ const client = createAdminClient({## 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)diff --git a/packages/admin-sdk/package.json b/packages/admin-sdk/package.jsonindex 9d87e4eacd..32a78037a2 100644--- a/packages/admin-sdk/package.json+++ b/packages/admin-sdk/package.json@@ -1,6 +1,6 @@{"name": "@spree/admin-sdk",- "version": "0.1.0",+ "version": "0.2.0","description": "Official TypeScript SDK for Spree Commerce Admin API","type": "module","main": "./dist/index.cjs",diff --git a/packages/sdk/.changeset/login-provider-dispatch.md b/packages/sdk/.changeset/login-provider-dispatch.mddeleted file mode 100644index 96a38803c8..0000000000--- a/packages/sdk/.changeset/login-provider-dispatch.md+++ /dev/null@@ -1,5 +0,0 @@-----'@spree/sdk': minor------Add provider-dispatched login. `client.auth.login()` now accepts third-party identity-provider payloads (e.g. `{ provider: 'auth0', token: '<jwt>' }`) in addition to the existing `{ email, password }` shape — `LoginCredentials` is now a discriminated union of `EmailPasswordLogin | ProviderLogin`, both newly exported. Pairs with the server-side strategy registry at `Spree.store_authentication_strategies`. Existing email/password calls are unchanged.diff --git a/packages/sdk/.changeset/product-meta-title.md b/packages/sdk/.changeset/product-meta-title.mddeleted file mode 100644index bbe69c4a2c..0000000000--- a/packages/sdk/.changeset/product-meta-title.md+++ /dev/null@@ -1,7 +0,0 @@-----'@spree/sdk': patch------Expose `Product.meta_title` in the Store API.--`meta_title` is a storefront SEO field (used in `<title>` tags) — previously it was only on the Admin product serializer. Now serialized on the Store `Product` type as `meta_title: string | null` so storefronts can render it without a second admin call.diff --git a/packages/sdk/.changeset/product-option-values.md b/packages/sdk/.changeset/product-option-values.mddeleted file mode 100644index 02f2e8e046..0000000000--- a/packages/sdk/.changeset/product-option-values.md+++ /dev/null@@ -1,7 +0,0 @@-----'@spree/sdk': patch------Expose `Product.option_values` in the Store API.--The `Product` type now includes an optional `option_values: Array<OptionValue>` field, listing the option values that are actually in use across the product's variants. This lets storefronts render option pickers (size, color, etc.) without iterating over every variant to collect them.diff --git a/packages/sdk/.changeset/store-channel-header.md b/packages/sdk/.changeset/store-channel-header.mddeleted file mode 100644index 526afe51ff..0000000000--- a/packages/sdk/.changeset/store-channel-header.md+++ /dev/null@@ -1,11 +0,0 @@-----'@spree/sdk': patch------Add sales-channel selection to the Store SDK via the `X-Spree-Channel` header.--- `createClient({ channel: 'pos' })` — set a client-level default-- `client.setChannel('wholesale')` — sticky setter, mirrors `setLocale` / `setCurrency` / `setCountry`-- `await client.products.list({}, { channel: 'pos' })` — per-request override--The value can be either a channel `code` (e.g. `online`, `pos`, `wholesale`) or the prefixed ID (`ch_…`); `code` is preferred. Backend resolution stays at `Spree::Api::V3::ChannelResolution`: a matching header picks the channel for the request, otherwise the store's default channel applies.diff --git a/packages/sdk/.changeset/store-newsletter-subscribers.md b/packages/sdk/.changeset/store-newsletter-subscribers.mddeleted file mode 100644index d257b6ed2c..0000000000--- a/packages/sdk/.changeset/store-newsletter-subscribers.md+++ /dev/null@@ -1,9 +0,0 @@-----'@spree/sdk': minor------Add `client.newsletterSubscribers.create()` and `client.newsletterSubscribers.verify()` for the new Store API newsletter subscription endpoints.--Lets headless storefronts subscribe guests to the newsletter before account creation and confirm the double opt-in via the verification token from the confirmation email. Pass `redirect_url` on `create()` and the storefront receives a `newsletter_subscriber.subscription_requested` webhook with the token + validated redirect URL so it can send the confirmation email itself — same pattern as `customer.password_reset_requested`. When called with a JWT and the customer's own email, the subscription is auto-verified.--Consent is now preserved across registration: when `client.customers.create()` is called with an email that already has a newsletter subscription on the current store, that subscriber is linked to the new user. If the subscription was verified, `accepts_email_marketing` is set to `true` on the returned customer even when the registration body sent `false` — so guests who opted in before signing up don't lose their consent.diff --git a/packages/sdk/.changeset/storefront-custom-field-tokens.md b/packages/sdk/.changeset/storefront-custom-field-tokens.mddeleted file mode 100644index 499fda4e9c..0000000000--- a/packages/sdk/.changeset/storefront-custom-field-tokens.md+++ /dev/null@@ -1,8 +0,0 @@-----'@spree/sdk': minor------Custom field `field_type` token.--- `CustomField` now exposes `field_type` as a string-literal union (`'short_text' | 'long_text' | 'rich_text' | 'number' | 'boolean' | 'json' | (string & {})`) — abstract token instead of the Ruby STI class name. Aligns with how Shopify, Saleor, Vendure, and commercetools expose typed custom fields.-- The legacy `type` field (e.g. `'Spree::Metafields::ShortText'`) is unchanged and still emitted alongside the new `field_type` for back-compat. The TypeScript type is annotated with `@deprecated` so editors surface the migration tip on hover; eslint with `no-deprecated` will flag references. Storefronts should switch to `field_type`; `type` will be removed in a future minor.diff --git a/packages/sdk/.changeset/zod-schema-customer-payment-method-fields.md b/packages/sdk/.changeset/zod-schema-customer-payment-method-fields.mddeleted file mode 100644index 5c9f83436b..0000000000--- a/packages/sdk/.changeset/zod-schema-customer-payment-method-fields.md+++ /dev/null@@ -1,10 +0,0 @@-----'@spree/sdk': minor------Sync Zod schemas with TypeScript types for `Customer` and `PaymentMethod`.--- `CustomerSchema` now includes `full_name: string` (already present in the `Customer` type since the Admin Customers API landed; the runtime schema was stale).-- `PaymentMethodSchema` now includes `source_required: boolean` (already present in the `PaymentMethod` type).--No source-API change — this only affects callers using `CustomerSchema` / `PaymentMethodSchema` for runtime validation (e.g., `CustomerSchema.parse(response)`). Validation no longer rejects these fields and parsed values are correctly typed.diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.mdindex 38ad01e31b..e2eb90f935 100644--- a/packages/sdk/CHANGELOG.md+++ b/packages/sdk/CHANGELOG.md@@ -1,5 +1,47 @@# @spree/sdk+## 1.1.0++### Minor Changes++- Add provider-dispatched login. `client.auth.login()` now accepts third-party identity-provider payloads (e.g. `{ provider: 'auth0', token: '<jwt>' }`) in addition to the existing `{ email, password }` shape — `LoginCredentials` is now a discriminated union of `EmailPasswordLogin | ProviderLogin`, both newly exported. Pairs with the server-side strategy registry at `Spree.store_authentication_strategies`. Existing email/password calls are unchanged.++- Add `client.newsletterSubscribers.create()` and `client.newsletterSubscribers.verify()` for the new Store API newsletter subscription endpoints.++ Lets headless storefronts subscribe guests to the newsletter before account creation and confirm the double opt-in via the verification token from the confirmation email. Pass `redirect_url` on `create()` and the storefront receives a `newsletter_subscriber.subscription_requested` webhook with the token + validated redirect URL so it can send the confirmation email itself — same pattern as `customer.password_reset_requested`. When called with a JWT and the customer's own email, the subscription is auto-verified.++ Consent is now preserved across registration: when `client.customers.create()` is called with an email that already has a newsletter subscription on the current store, that subscriber is linked to the new user. If the subscription was verified, `accepts_email_marketing` is set to `true` on the returned customer even when the registration body sent `false` — so guests who opted in before signing up don't lose their consent.++- Custom field `field_type` token.++ - `CustomField` now exposes `field_type` as a string-literal union (`'short_text' | 'long_text' | 'rich_text' | 'number' | 'boolean' | 'json' | (string & {})`) — abstract token instead of the Ruby STI class name. Aligns with how Shopify, Saleor, Vendure, and commercetools expose typed custom fields.+ - The legacy `type` field (e.g. `'Spree::Metafields::ShortText'`) is unchanged and still emitted alongside the new `field_type` for back-compat. The TypeScript type is annotated with `@deprecated` so editors surface the migration tip on hover; eslint with `no-deprecated` will flag references. Storefronts should switch to `field_type`; `type` will be removed in a future minor.++- Sync Zod schemas with TypeScript types for `Customer` and `PaymentMethod`.++ - `CustomerSchema` now includes `full_name: string` (already present in the `Customer` type since the Admin Customers API landed; the runtime schema was stale).+ - `PaymentMethodSchema` now includes `source_required: boolean` (already present in the `PaymentMethod` type).++ No source-API change — this only affects callers using `CustomerSchema` / `PaymentMethodSchema` for runtime validation (e.g., `CustomerSchema.parse(response)`). Validation no longer rejects these fields and parsed values are correctly typed.++### Patch Changes++- Expose `Product.meta_title` in the Store API.++ `meta_title` is a storefront SEO field (used in `<title>` tags) — previously it was only on the Admin product serializer. Now serialized on the Store `Product` type as `meta_title: string | null` so storefronts can render it without a second admin call.++- Expose `Product.option_values` in the Store API.++ The `Product` type now includes an optional `option_values: Array<OptionValue>` field, listing the option values that are actually in use across the product's variants. This lets storefronts render option pickers (size, color, etc.) without iterating over every variant to collect them.++- Add sales-channel selection to the Store SDK via the `X-Spree-Channel` header.++ - `createClient({ channel: 'pos' })` — set a client-level default+ - `client.setChannel('wholesale')` — sticky setter, mirrors `setLocale` / `setCurrency` / `setCountry`+ - `await client.products.list({}, { channel: 'pos' })` — per-request override++ The value can be either a channel `code` (e.g. `online`, `pos`, `wholesale`) or the prefixed ID (`ch_…`); `code` is preferred. Backend resolution stays at `Spree::Api::V3::ChannelResolution`: a matching header picks the channel for the request, otherwise the store's default channel applies.+## 1.0.1### Patch Changesdiff --git a/packages/sdk/README.md b/packages/sdk/README.mdindex 378ff57862..da7ab3ad84 100644--- a/packages/sdk/README.md+++ b/packages/sdk/README.md@@ -96,8 +96,11 @@ const { token, user } = await client.auth.login({// Use token for authenticated requestsconst orders = await client.customer.orders.list({}, { token });-// Refresh token when needed-const newTokens = await client.auth.refresh({ 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@@ -140,13 +143,6 @@ await client.carts.complete(cart.id, options);## API Reference-### Store--```typescript-// Get current store information-const store = await client.store.get();-```-### Products```typescript@@ -584,8 +580,9 @@ The SDK uses a resource builder pattern for nested resources:| `customer` | `giftCards` | `list`, `get` || `customer` | `storeCredits` | `list`, `get` || `customer` | `orders` | `list`, `get` |+| `customer` | `paymentSetupSessions` | `create`, `get`, `complete` |+| `newsletterSubscribers` | — | `create`, `verify` || `markets` | `countries` | `list`, `get` |-| `categories` | `products` | `list` || `wishlists` | `items` | `create`, `update`, `delete` |Example:@@ -602,7 +599,6 @@ await client.carts.storeCredits.apply(cartId, amount, options);await client.customer.addresses.list({}, options);await client.customer.orders.list({}, options);await client.markets.countries.list(marketId);-await client.categories.products.list(categoryId, params, options);await client.wishlists.items.create(wishlistId, params, options);```diff --git a/packages/sdk/package.json b/packages/sdk/package.jsonindex 996c1c2d39..392998f603 100644--- a/packages/sdk/package.json+++ b/packages/sdk/package.json@@ -1,6 +1,6 @@{"name": "@spree/sdk",- "version": "1.0.1",+ "version": "1.1.0","description": "Official TypeScript SDK for Spree Commerce Store API","type": "module","main": "./dist/index.cjs",