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
Added the @spree/core package for code every Spree client shares (#14938)
Damian Legawiec7c295c4d40c8
diff --git a/.changeset/dashboard-uses-spree-core.md b/.changeset/dashboard-uses-spree-core.mdnew file mode 100644index 0000000000..b911d84264--- /dev/null+++ b/.changeset/dashboard-uses-spree-core.md@@ -0,0 +1,10 @@+---+"@spree/dashboard-core": patch+"@spree/seller-dashboard": patch+---++Moved the money, percentage, typed-amount, display-name and code-shape helpers and the list of currencies still in use into `@spree/core`, which the dashboard packages and the seller panel now depend on. `@spree/dashboard-core` still exports them under the same names.++- A customer's average order value is now worked out exactly.+- Calculator summaries show money with each currency's own number of decimals.+- The bulk variant editor now reads `1,500` as fifteen hundred and `1,234.5` correctly when you type or paste a weight or dimension.diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.ymlindex 5b3b57d5c8..e2269b1a81 100644--- a/.github/workflows/packages.yml+++ b/.github/workflows/packages.yml@@ -105,8 +105,8 @@ jobs:- name: Check SDK code lists are up to daterun: |pnpm generate:code-lists- if [ -n "$(git status --porcelain -- packages/sdk-core/src/code-lists.generated.ts)" ]; then- git diff -- packages/sdk-core/src/code-lists.generated.ts+ if [ -n "$(git status --porcelain -- packages/core/src/code-lists.generated.ts)" ]; then+ git diff -- packages/core/src/code-lists.generated.tsecho "::error::SDK code lists are out of date. Run 'pnpm generate:code-lists' and commit the result."exit 1fi@@ -153,7 +153,7 @@ jobs:# `pnpm publish` does in the release jobs below.- name: Pack packagesrun: |- for pkg in admin-sdk seller-sdk dashboard-ui dashboard-core dashboard seller-dashboard cli; do+ for pkg in core admin-sdk seller-sdk dashboard-ui dashboard-core dashboard seller-dashboard cli; dopnpm --dir "packages/$pkg" pack --pack-destination "$RUNNER_TEMP/tarballs"done@@ -444,6 +444,66 @@ jobs:if: steps.check.outputs.published == 'false'run: pnpm turbo build --filter=@spree/sdk && npm publish --provenance --access public --tag ${{ steps.tag.outputs.tag }}+ release-core:+ name: "Core - Release"+ needs: [check, scaffolded-app]+ if: github.ref == 'refs/heads/main' && github.event_name == 'push'+ runs-on: ubuntu-latest+ permissions:+ contents: write+ pull-requests: write+ id-token: write+ defaults:+ run:+ working-directory: packages/core+ steps:+ - uses: actions/checkout@v7++ - uses: pnpm/action-setup@v6++ - uses: actions/[email protected]+ with:+ node-version: 22+ cache: pnpm+ registry-url: https://registry.npmjs.org++ - run: pnpm install --frozen-lockfile+ working-directory: .++ # See release-sdk: Trusted Publishing needs a newer npm than Node 22 ships.+ - name: Upgrade npm for Trusted Publishing support+ run: |+ npm install -g npm@latest --prefix="$HOME/.npm-global"+ echo "$HOME/.npm-global/bin" >> "$GITHUB_PATH"+ working-directory: .++ - name: Check if version is published+ id: check+ run: |+ PACKAGE_VERSION=$(node -p "require('./package.json').version")+ if npm view @spree/core@$PACKAGE_VERSION version 2>/dev/null; then+ echo "published=true" >> $GITHUB_OUTPUT+ else+ echo "published=false" >> $GITHUB_OUTPUT+ fi++ # Unlike @spree/sdk, there is no older stable line to protect, so 0.x+ # releases go to `latest`: that is what the npm page shows and what a+ # plain `npm install @spree/core` resolves.+ - name: Determine npm tag+ id: tag+ run: |+ PACKAGE_VERSION=$(node -p "require('./package.json').version")+ if echo "$PACKAGE_VERSION" | grep -qE '[-]'; then+ echo "tag=beta" >> $GITHUB_OUTPUT+ else+ echo "tag=latest" >> $GITHUB_OUTPUT+ fi++ - name: Build and Publish+ if: steps.check.outputs.published == 'false'+ run: pnpm turbo build --filter=@spree/core && npm publish --provenance --access public --tag ${{ steps.tag.outputs.tag }}+release-admin-sdk:name: "Admin SDK - Release"needs: [check, scaffolded-app]@@ -603,7 +663,9 @@ jobs:# same-push admin-sdk version bump must land on npm first, or installs of# the just-published dashboard packages fail until it does. (release-cli# waits on this job, completing the admin-sdk → dashboard → cli chain.)- needs: [check, scaffolded-app, release-admin-sdk]+ # The same holds for @spree/core, which dashboard-core, dashboard-ui and+ # dashboard depend on.+ needs: [check, scaffolded-app, release-admin-sdk, release-core]if: github.ref == 'refs/heads/main' && github.event_name == 'push'runs-on: ubuntu-latestpermissions:@@ -665,7 +727,8 @@ jobs:# starter with ranges floored at these versions.release-seller:name: "Seller packages - Release"- needs: [check, scaffolded-app]+ # Gated on release-core for the same reason as release-dashboard.+ needs: [check, scaffolded-app, release-core]if: github.ref == 'refs/heads/main' && github.event_name == 'push'runs-on: ubuntu-latestpermissions:diff --git a/CLAUDE.md b/CLAUDE.mdindex 672d849612..84ff557a13 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -31,6 +31,7 @@ Use `/project:create-plan` and `/project:update-plan` for plan management, and `| `packages/sdk` | `@spree/sdk` — TypeScript Store API client || `packages/admin-sdk` | `@spree/admin-sdk` — TypeScript Admin API client || `packages/seller-sdk` | `@spree/seller-sdk` — TypeScript Seller API client |+| `packages/core` | `@spree/core` — universal code with no HTTP: code lists, money helpers, filter vocabulary (published; the base for shared TypeScript code) || `packages/sdk-core` | `@spree/sdk-core` — shared HTTP/retry/error layer (private internal) || `packages/cli` | `@spree/cli` — Docker-based project management CLI || `packages/create-spree-app` | `create-spree-app` — project scaffolding |@@ -716,6 +717,10 @@ When displaying amount or percentage fields please always use `<InputGroup>` wit`Currency` should be always rendered as a dropdown using `currency-select.tsx` component, this also applies to Preferences fields representing currency`Country` and `Countries` fields should always use `copuntry-combobox.tsx` component, this also applies to preferences fields representing a single country or multiple choices+### @spree/core — Universal code++Published package for code that is not tied to HTTP or a framework: the code lists (`pnpm generate:code-lists`) and code-shape checks, unit systems, display names, money helpers (arithmetic, percentages, reading typed amounts) and the filter vocabulary. The dashboard packages and the seller panel import it directly — never through `@spree/admin-sdk` / `@spree/seller-sdk`, which re-export the same code; `@spree/dashboard-core` still re-exports its money helpers for plugin authors. Code any client could use — a conversion, a format, a validation rule shared with the server — goes here, never into an SDK or a dashboard package. No runtime dependencies. `@spree/sdk-core` re-exports it and the SDKs bundle it, offering its code lists and money helpers under the same names as before. The code generators read it from source (the `@spree/source` export condition), so they run before anything is built.+### @spree/sdk-core — Shared HTTP LayerPrivate package providing `createRequestFn()`, `SpreeError`, retry logic, and Ransack param transformation. Used internally by both SDKs.diff --git a/lefthook.yml b/lefthook.ymlindex ca5c8f1658..cfbc05f6cb 100644--- a/lefthook.yml+++ b/lefthook.yml@@ -55,10 +55,10 @@ pre-commit:# needs fresh lists.glob:- "docs/api-reference/{store,admin}.yaml"- - "packages/sdk-core/scripts/generate-code-lists.ts"+ - "packages/core/scripts/generate-code-lists.ts"run: |pnpm generate:code-lists- git add packages/sdk-core/src/code-lists.generated.ts+ git add packages/core/src/code-lists.generated.tspre-push:commands:diff --git a/package.json b/package.jsonindex ffede294a2..b4fa2b2344 100644--- a/package.json+++ b/package.json@@ -9,7 +9,7 @@"generate:zod": "pnpm --recursive --filter \"./packages/*\" run generate:zod","generate:filters": "pnpm --recursive --filter \"./packages/*\" run generate:filters","generate:params": "pnpm --recursive --filter \"./packages/*\" run generate:params",- "generate:code-lists": "pnpm --filter @spree/sdk run generate:code-lists",+ "generate:code-lists": "pnpm --filter @spree/core run generate:code-lists","lint": "turbo lint","lint:fix": "turbo lint:fix","format": "turbo format",diff --git a/packages/README.md b/packages/README.mdindex 50d915ed1c..7f360e9e5f 100644--- a/packages/README.md+++ b/packages/README.md@@ -1,6 +1,6 @@# Spree TypeScript Packages-This directory contains the TypeScript side of the Spree monorepo: SDKs, the React admin SPA, the CLI, project scaffolding, and the docs bundle. Everything here is managed with **pnpm workspaces** + **Turbo**, built with **tsup** (or Vite for the admin SPA), tested with **Vitest**, and linted with **Biome**. Versioning for published packages is handled by **Changesets**.+This directory contains the TypeScript side of the Spree monorepo: the shared core library, the SDKs, the admin dashboard and seller panel, the CLI, project scaffolding, and the docs bundle. Everything here is managed with **pnpm workspaces** + **Turbo**, built with **tsup** (or Vite for the admin SPA), tested with **Vitest**, and linted with **Biome**. Versioning for published packages is handled by **Changesets**.For monorepo-wide conventions (type generation pipeline, code style, testing) see the root [`CLAUDE.md`](../CLAUDE.md). For backend conventions see [`spree/`](../spree/).@@ -8,23 +8,29 @@ For monorepo-wide conventions (type generation pipeline, code style, testing) se| Badge | Meaning || --- | --- |-| **Stable** | Published to npm, follows semver, safe for production. |-| **Developer Preview** | Published to npm but API may change between minor versions. Pin exact versions. |-| **In Development** | Active work for an upcoming Spree release. Not yet published or only published behind a `next` dist-tag. |+| **Stable** | Published to npm under `latest`, follows semver, safe for production. |+| **Release Candidate** | The Spree 6.0 line, published under the `beta` dist-tag. The API is settling; pin exact versions. |+| **Developer Preview** | Published to npm on the 0.x line; the API may change between minor versions. Pin exact versions. || **Internal** | Private to the workspace (`"private": true`), not published. |## Packages| 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 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. |-| [`sdk-core`](./sdk-core) | — | **Internal** | Shared HTTP/retry/error layer used by `@spree/sdk` and `@spree/admin-sdk`. Not published. |-| [`cli`](./cli) | [`@spree/cli`](https://www.npmjs.com/package/@spree/cli) | **Stable** (2.x) | Docker-based CLI for managing Spree projects scaffolded with `create-spree-app`. |-| [`create-spree-app`](./create-spree-app) | [`create-spree-app`](https://www.npmjs.com/package/create-spree-app) | **Stable** (1.x) | One-shot scaffolder: `npx create-spree-app my-store`. Sets up backend (Docker) + optional Next.js storefront. |+| [`sdk`](./sdk) | [`@spree/sdk`](https://www.npmjs.com/package/@spree/sdk) | **Stable** (1.x) · **Release Candidate** (2.0) | TypeScript client for the customer-facing **Store API v3**. 1.x targets Spree 5.x; 2.0 targets Spree 6.0. |+| [`admin-sdk`](./admin-sdk) | [`@spree/admin-sdk`](https://www.npmjs.com/package/@spree/admin-sdk) | **Release Candidate** (1.0) | TypeScript client for the **Admin API v3**. |+| [`seller-sdk`](./seller-sdk) | [`@spree/seller-sdk`](https://www.npmjs.com/package/@spree/seller-sdk) | **Release Candidate** (1.0) | TypeScript client for the **Seller API**, used by marketplace seller panels. |+| [`core`](./core) | [`@spree/core`](https://www.npmjs.com/package/@spree/core) | **Developer Preview** (0.x) | Universal code with no HTTP: country, currency, locale and unit code lists, unit systems, display names, exact money arithmetic and input parsing, the filter vocabulary. |+| [`sdk-core`](./sdk-core) | — | **Internal** | Shared HTTP, retry and error layer the SDKs bundle. |+| [`dashboard`](./dashboard) | [`@spree/dashboard`](https://www.npmjs.com/package/@spree/dashboard) | **Release Candidate** (1.0) | The Spree 6.0 admin dashboard, a React single-page app. Replaces the legacy Rails `spree/admin` engine. |+| [`dashboard-core`](./dashboard-core) | [`@spree/dashboard-core`](https://www.npmjs.com/package/@spree/dashboard-core) | **Release Candidate** (1.0) | Dashboard framework: registries (table, nav, slot, settings-nav), providers, shared hooks, `defineDashboardPlugin`. The extension API. |+| [`dashboard-ui`](./dashboard-ui) | [`@spree/dashboard-ui`](https://www.npmjs.com/package/@spree/dashboard-ui) | **Release Candidate** (1.0) | Design system: shadcn primitives, headless composed components, design tokens. Source-only. |+| [`seller-dashboard`](./seller-dashboard) | [`@spree/seller-dashboard`](https://www.npmjs.com/package/@spree/seller-dashboard) | **Release Candidate** (1.0) | The marketplace seller panel, the seller-facing counterpart to the admin dashboard. |+| [`dashboard-starter`](./dashboard-starter) | — | **Internal** | Host app for the admin dashboard; the source of the [`spree/dashboard-starter`](https://github.com/spree/dashboard-starter) template. |+| [`seller-dashboard-starter`](./seller-dashboard-starter) | — | **Internal** | Host app for the seller panel; the source of the [`spree/seller-dashboard-starter`](https://github.com/spree/seller-dashboard-starter) template. |+| [`dashboard-plugin-example`](./dashboard-plugin-example) | — | **Internal** | Example dashboard plugin (a Brands feature); the reference for the plugin authoring docs. |+| [`cli`](./cli) | [`@spree/cli`](https://www.npmjs.com/package/@spree/cli) | **Stable** (3.x) | CLI for managing Spree projects scaffolded with `create-spree-app`. |+| [`create-spree-app`](./create-spree-app) | [`create-spree-app`](https://www.npmjs.com/package/create-spree-app) | **Stable** (2.x) | One-shot scaffolder: `npx create-spree-app my-store`. Sets up the backend and, optionally, the Next.js storefront. || [`docs`](./docs) | [`@spree/docs`](https://www.npmjs.com/package/@spree/docs) | **Developer Preview** (0.x) | Spree developer documentation packaged for local access by AI agents and dev tools. |### `@spree/sdk` — Store API client@@ -35,9 +41,11 @@ Includes auto-generated TypeScript types and Zod schemas derived from the Rails### `@spree/admin-sdk` — Admin API client-The 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.+The 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 by the `@spree/dashboard` app and by integrations and admin tooling.-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/seller-sdk` — Seller API client++The client for the Seller API, which marketplace sellers use to manage their own products, orders and fulfillment. Used by `@spree/seller-dashboard`.### `@spree/dashboard`, `@spree/dashboard-core`, `@spree/dashboard-ui` — the admin dashboard stack@@ -47,23 +55,27 @@ The Spree 6.0 admin is a three-package stack:- **`@spree/dashboard-core`** — the framework. The four registries (table, nav, slot, settings-nav), the four providers (auth, permission, store, theme), generic infra hooks (`use-auth`, `use-permissions`, `use-resource-mutation`, `use-direct-upload`, `use-global-search`, …), the admin SDK client singleton, and the `defineDashboardPlugin` extension facade. **This is what plugin authors import** to register navigation, slots, table columns, and routes.- **`@spree/dashboard`** — the deployable SPA. Routes, resource hooks (`use-orders`, `use-products`, `use-customers`, …), Zod schemas, locale strings, the app shell. Composes the other two. Built with Vite + TanStack Router (file-based) + TanStack Query + React Hook Form + Tailwind.-Plugin authors install `@spree/dashboard-ui` + `@spree/dashboard-core` as peer dependencies. Seller panels, white-label admins, and other custom variants compose the same packages with their own routes/shell.+Plugin authors install `@spree/dashboard-ui` + `@spree/dashboard-core` as peer dependencies. The seller panel (`@spree/seller-dashboard`), white-label admins, and other custom variants compose the same packages with their own routes and shell. Merchants run the dashboards from the `dashboard-starter` and `seller-dashboard-starter` templates.Architecture, extension points (table registry, navigation registry, component injection), the package boundary rules, and the phased migration are documented in [`docs/plans/6.0-admin-spa.md`](../docs/plans/6.0-admin-spa.md). Local setup for the SPA is in [`packages/dashboard/README.md`](./dashboard/README.md).-All three packages are currently private in the workspace and ship together with the Spree 6.0 release.+The three packages always release together under one version, and ship with Spree 6.0.++### `@spree/core` — Universal code++The code every Spree client shares, whatever it runs on: code lists generated from the API references, unit systems, display names, money helpers that work on decimal strings without floating point (arithmetic, percentages, reading typed amounts), and the filter types. The dashboard packages depend on it directly. No dependencies and no network calls. The SDKs bundle it and re-export its code lists and money helpers, so SDK users never install it separately. It is the home for any code a client could use — a conversion, a format, a rule shared with the server — and the base for moving more of Spree to TypeScript.### `@spree/sdk-core` — Shared internals-Private package. Provides `createRequestFn()`, `SpreeError`, retry logic, and Ransack query-param transformation (`transformListParams()`). Consumed by both SDKs; not intended for direct use.+Private package. Provides `createRequestFn()`, `SpreeError`, retry logic, and Ransack query-param transformation (`transformListParams()`), and re-exports `@spree/core`. Consumed by the SDKs; not intended for direct use.### `@spree/cli` — Project management CLI-Docker-based commands for projects scaffolded via `create-spree-app`: starting/stopping services, running migrations, opening Rails consoles, loading sample data, etc. Bundled automatically into new projects.+Commands for projects scaffolded via `create-spree-app`: starting/stopping services, running migrations, opening Rails consoles, loading sample data, etc. Bundled automatically into new projects.### `create-spree-app` — Project scaffolder-The recommended entry point for new Spree projects. Clones [`spree/spree-starter`](https://github.com/spree/spree-starter), wires up Docker Compose, optionally adds the Next.js storefront, and runs first-time setup. Replaces the legacy in-repo `server/` directory.+The recommended entry point for new Spree projects. Clones [`spree/spree-starter`](https://github.com/spree/spree-starter), optionally adds the Next.js storefront, and runs first-time setup.### `@spree/docs` — Documentation bundle@@ -83,4 +95,4 @@ pnpm lint:fix # Biome lint + auto-fixpnpm format # Biome format-write```-Per-package commands are documented in each package's `README.md`. Changesets for versioning go in the package's `.changeset/` directory.+Per-package commands are documented in each package's `README.md`. Changesets for versioning go in the root [`.changeset/`](../.changeset/) directory (`pnpm changeset`), never in a package's own directory.diff --git a/packages/admin-sdk/package.json b/packages/admin-sdk/package.jsonindex df8ed605a3..8cd061ed29 100644--- a/packages/admin-sdk/package.json+++ b/packages/admin-sdk/package.json@@ -46,7 +46,7 @@"scripts": {"generate:admin-client": "tsx scripts/generate-admin-client.ts","generate:zod": "tsx ../sdk-core/scripts/generate-zod.ts",- "generate:filters": "tsx ../sdk-core/scripts/generate-filters.ts admin",+ "generate:filters": "tsx --conditions=@spree/source ../sdk-core/scripts/generate-filters.ts admin","generate:params": "tsx ../sdk-core/scripts/generate-params.ts admin","build": "tsup","dev": "tsup --watch",diff --git a/packages/admin-sdk/tests/core-exports.test.ts b/packages/admin-sdk/tests/core-exports.test.tsnew file mode 100644index 0000000000..99f314c76c--- /dev/null+++ b/packages/admin-sdk/tests/core-exports.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from 'vitest'+import * as sdk from '../src'++// The code lists and money helpers live in @spree/core; clients import them+// from the SDK, so the SDK has to keep offering every one of them.+describe('@spree/core exports', () => {+ it.each([+ 'CountryCode',+ 'CurrencyCode',+ 'DimensionUnit',+ 'LocaleCode',+ 'WeightUnit',+ 'compareMoney',+ 'decimalPlaces',+ 'formatMoney',+ 'isDecimalString',+ 'isZeroMoney',+ 'multiplyMoney',+ 'negateMoney',+ 'subtractMoney',+ 'sumMoney',+ ])('offers %s', (name) => {+ expect(sdk).toHaveProperty(name)+ })+})diff --git a/packages/core/README.md b/packages/core/README.mdnew file mode 100644index 0000000000..74ca03d19b--- /dev/null+++ b/packages/core/README.md@@ -0,0 +1,246 @@+# @spree/core++The shared foundation of [Spree Commerce](https://spreecommerce.org) for TypeScript and JavaScript: the code lists the Spree API speaks, exact money arithmetic, and the filter vocabulary of its list endpoints.++It has no dependencies and makes no network calls, so it runs anywhere JavaScript does: browsers, Node.js, edge runtimes, React Native and build scripts. The [Store](https://www.npmjs.com/package/@spree/sdk), [Admin](https://www.npmjs.com/package/@spree/admin-sdk) and [Seller](https://www.npmjs.com/package/@spree/seller-sdk) SDKs are built on it and re-export its code lists and money helpers. Install it on its own when you need those without an API client — in a checkout widget, a feed generator, a test suite or your own backend.++```bash+npm install @spree/core+```++> **Developer Preview.** `@spree/core` is on the 0.x line, and its API may change between minor versions until 1.0, so pin an exact version.++## Contents++- [Code lists](#code-lists) — countries, currencies, locales, weight and dimension units, and checking a code you received+- [Unit systems](#unit-systems) — which weight units belong to metric and imperial+- [Display names](#display-names) — country, currency and language names in any language+- [Money](#money) — exact arithmetic, percentages and formatting for decimal-string amounts+- [Reading typed amounts](#reading-typed-amounts) — turning "1.234,56" into "1234.56"+- [Filters](#filters) — types for the queries Spree list endpoints accept+- [Compatibility](#compatibility)++## Code lists++Every country, currency, locale and unit Spree accepts, as closed lists generated from the Spree API reference. Each list is both a value you can iterate and a type, and every code is documented with its English name, so your editor shows "US Dollar" when you hover `USD`.++| List | Contains | Example |+| --- | --- | --- |+| `CountryCode` | 240 ISO 3166-1 alpha-2 country codes | `CountryCode.US` → `'US'` |+| `CurrencyCode` | 178 ISO 4217 currency codes | `CurrencyCode.EUR` → `'EUR'` |+| `LocaleCode` | 202 locale codes | `LocaleCode.pt_BR` → `'pt-BR'` |+| `WeightUnit` | `g`, `kg`, `lb`, `oz` | `WeightUnit.kg` → `'kg'` |+| `DimensionUnit` | `mm`, `cm`, `in`, `ft` | `DimensionUnit.cm` → `'cm'` |++```typescript+import { CurrencyCode, WeightUnit } from '@spree/core';++// As a type: only codes Spree accepts compile.+function setCurrency(currency: CurrencyCode) {}+setCurrency('EUR');+setCurrency('EURO'); // Type error++// As a value: build a picker from the full list.+const options = Object.values(WeightUnit); // ['g', 'kg', 'lb', 'oz']+```++A locale with a region uses a hyphen in its value and an underscore in its key, so `LocaleCode.pt_BR` is `'pt-BR'`.++### Checking a code you received++`isCountryCode`, `isCurrencyCode` and `isLocaleCode` check a value's shape and narrow its type, so a plain string from a form, a URL or a file becomes a typed code:++```typescript+import { isCountryCode } from '@spree/core';++const country = new URLSearchParams(location.search).get('country');+if (isCountryCode(country)) {+ // country is a CountryCode here+}+```++They check the shape only, `US` but not `us` or `USA`, and accept a code missing from the lists above. The Spree server holds the authoritative list and rejects a code it does not know, so a client built with an older or newer version of this package still accepts what its server does.++### Currencies still in use++`CurrencyCode` includes replaced currencies, such as the Croatian kuna, so that amounts recorded in them stay valid. `ACTIVE_CURRENCY_CODES` leaves them out, for a picker offering any currency for new prices, and `RETIRED_CURRENCY_CODES` lists the ones it leaves out.++## Unit systems++A Spree store uses either the metric or the imperial system. `UNIT_SYSTEM_WEIGHT_UNITS` lists the weight units each one offers, the usual one first, so a settings screen can offer only the units that fit:++```typescript+import { UNIT_SYSTEMS, UNIT_SYSTEM_WEIGHT_UNITS, type UnitSystem } from '@spree/core';++UNIT_SYSTEMS; // ['metric', 'imperial']+UNIT_SYSTEM_WEIGHT_UNITS.metric; // ['kg', 'g']+UNIT_SYSTEM_WEIGHT_UNITS.imperial; // ['lb', 'oz']+```++## Display names++`intlDisplayName` names a country, currency, language or other code in the reader's language, falling back to English:++```typescript+import { intlDisplayName } from '@spree/core';++intlDisplayName('region', 'de', 'US'); // 'Vereinigte Staaten'+intlDisplayName('currency', 'fr', 'JPY'); // 'yen japonais'+intlDisplayName('language', 'en', 'pt-BR'); // 'Brazilian Portuguese'+```++It answers `undefined` when the runtime has no name for a code or the code is malformed, so you choose the fallback, usually the code itself: `intlDisplayName('region', locale, code) ?? code`.++`localeEndonym` names a language in that language itself, for a language picker where every reader finds their own language:++```typescript+import { localeEndonym } from '@spree/core';++localeEndonym('de'); // 'Deutsch'+localeEndonym('fr'); // 'Français'+```++## Money++Spree sends and accepts every amount as a decimal string such as `"1234.56"`, never as a JavaScript number. A number cannot hold most decimal amounts exactly (`0.1 + 0.2` is `0.30000000000000004`), and those errors grow into lost cents on totals, refunds and payouts.++These helpers work on the strings directly, without converting them to numbers, so every result is exact:++```typescript+import { sumMoney, subtractMoney, multiplyMoney, compareMoney, formatMoney } from '@spree/core';++const subtotal = sumMoney(['19.99', '5.01'], 'USD'); // '25.00'+const lineTotal = multiplyMoney('9.99', 3, 'USD'); // '29.97'+const balance = subtractMoney('10.00', '0.01'); // '9.99'++if (compareMoney(subtotal, '25.00') >= 0) {+ // free shipping+}++formatMoney(subtotal, 'USD', 'en-US'); // '$25.00'+```++| Function | What it does |+| --- | --- |+| `sumMoney(values, currency?)` | Adds amounts. Blank values (`null`, `undefined`, `''`) count as zero. |+| `subtractMoney(a, b, currency?)` | `a` minus `b`. |+| `multiplyMoney(value, quantity, currency?)` | An amount times a whole number. A fractional quantity throws an error. |+| `negateMoney(value)` | Flips the sign: `'5.00'` → `'-5.00'`. |+| `compareMoney(a, b)` | `-1`, `0` or `1`. Decimals don't matter: `'10.0'` equals `'10.00'`. |+| `isZeroMoney(value)` | Whether an amount is zero. Blank values count as zero. |+| `isDecimalString(value)` | Whether a value is a plain decimal string. `'19.99'` is; `'19,99'` and the number `19.99` are not. |+| `decimalPlaces(currency)` | How many decimals a currency uses: 2 for USD, 0 for JPY, 3 for KWD. An unknown code answers 2. |+| `formatMoney(amount, currency, locale?, options?)` | Formats an amount for display in a language. |+| `isPositiveMoney(value)` | Whether an amount is above zero. Blank or malformed values are not. |++### Percentages and shares++Rates travel as decimal strings too. These helpers convert and apply them without floating point, rounding the result once, half away from zero, to the currency's decimals:++```typescript+import { percentOf, prorateMoney, fractionToPercent, percentToFraction } from '@spree/core';++percentOf('19.99', '10', 'USD'); // '2.00' — 10% of $19.99+prorateMoney('10.00', 1, 3, 'USD'); // '3.33' — the share 1 of 3 units carries+fractionToPercent('0.23'); // '23' — a stored rate as a merchant reads it+percentToFraction('7.25'); // '0.0725' — a typed percentage as the API stores it+```++`shiftDecimalPoint(value, places)` moves the decimal point by whole places, exactly: `shiftDecimalPoint('0.077', 2)` is `'7.7'`.++### Nothing is rounded away++Arithmetic never rounds. A result keeps the most decimals any input has and, when you pass a currency, at least that currency's decimals:++```typescript+sumMoney(['1.5', '2.5'], 'USD'); // '4.00' — padded to the currency's 2 decimals+sumMoney(['1000'], 'JPY'); // '1000' — the yen has no decimals+multiplyMoney('19.9990', 3); // '59.9970' — a unit price keeps its 4 decimals+```++Rounding happens once, when you display the amount.++### Formatting++`formatMoney` shows an amount in a currency and language, using the currency's own number of decimals:++```typescript+formatMoney('1234.5', 'USD', 'en-US'); // '$1,234.50'+formatMoney('1234.5', 'EUR', 'de-DE'); // '1.234,50 €'+formatMoney('1500', 'JPY', 'ja-JP'); // '¥1,500'+formatMoney('0.0125', 'USD', 'en-US', { unitPrice: true }); // '$0.0125'+```++- Leave out the locale to use the reader's own language.+- `unitPrice: true` keeps up to 4 decimals, for prices per gram or per unit.+- A missing or malformed amount formats as an empty string, so a page never shows `NaN`.+- An amount that rounds to zero shows no minus sign: `'-0.001'` formats as `'$0.00'`.++`CURRENCY_EXPONENTS` exposes the full currency decimals table. The Spree server reads the same table, so the server and your client always agree on a currency's decimals.++## Reading typed amounts++People type amounts in their own number format: a German writes `1.234,56`, a French person `1 234,56`. Spree accepts only `1234.56`, and never guesses on the server. Convert input in the same language the field is displayed in:++```typescript+import { normalizeMoneyInput, currencyParts } from '@spree/core';++normalizeMoneyInput('1.234,56', 'de'); // '1234.56'+normalizeMoneyInput('1 234,56', 'fr'); // '1234.56'+normalizeMoneyInput('19.50', 'de'); // '19.50' — a period before two digits is a decimal point+normalizeMoneyInput(' ', 'en'); // ''++currencyParts('EUR', 'de'); // { symbol: '€', decimal: ',' } — to label the input+```++The result is always a plain decimal string or `''`, never a number, so nothing is lost on the way to the API.++## Filters++Spree list endpoints accept filters named after an attribute and a condition: `name_cont` (name contains), `price_gteq` (price at least), `status_in` (status is one of), `deleted_at_null` (not deleted). These types build exact TypeScript types for those queries, so a misspelled filter or a value of the wrong kind fails to compile.++The SDKs already type every list method this way. Use these types to describe queries of your own, such as a saved search or a URL you build by hand:++```typescript+import type { RangeFilters, SortKey, TextFilters } from '@spree/core';++type ProductQuery = TextFilters<'name' | 'sku'> &+ RangeFilters<'price'> & {+ sort?: SortKey<'name' | 'price' | 'created_at'>;+ };++const query: ProductQuery = {+ name_cont: 'shirt',+ price_gteq: '10.00',+ sort: '-price',+};+```++| Type | For | Conditions |+| --- | --- | --- |+| `TextFilters<Attribute>` | Text | `eq`, `not_eq`, `cont`, `i_cont`, `not_cont`, `start`, `end`, `in`, `not_in`, `null`, `not_null`, `present`, `blank` |+| `RangeFilters<Attribute, Value?>` | Amounts, counts, dates and times | `eq`, `not_eq`, `lt`, `lteq`, `gt`, `gteq`, `in`, `not_in`, `null`, `not_null` |+| `EnumFilters<Attribute, Value>` | A known set of values that extensions may add to, such as statuses | `eq`, `not_eq`, `in`, `not_in`, `null`, `not_null` |+| `CodeFilters<Attribute, Code>` | A closed code list, such as `CurrencyCode` | `eq`, `not_eq`, `in`, `not_in`, `null`, `not_null` |+| `IdFilters<Attribute>` | Record IDs, such as `prod_86Rf07xd4z` | `eq`, `not_eq`, `in`, `not_in`, `null`, `not_null` |+| `BooleanFilters<Attribute>` | True or false | `eq`, `not_eq`, `in`, `not_in`, `true`, `false`, `null` |+| `Prefixed<Prefix, Filters>` | Filters on an associated record, such as `variants_sku_eq` | — |+| `SortKey<Attribute>` | Sorting: `'name'`, descending `'-name'`, or two fields `'name,-price'` | — |++Amounts in `RangeFilters` are decimal strings, like everywhere else in Spree. `FILTER_PREDICATES` lists the conditions for each kind of value, if you need them at runtime, for example to build a filter editor, and `FilterPredicate` is the type of any one of them.++## Compatibility++- ES modules and CommonJS, with TypeScript types included.+- Node.js 18 or later, and every current browser.+- `formatMoney` uses the built-in `Intl.NumberFormat`.++## Links++- [Spree documentation](https://spreecommerce.org/docs)+- [Source code](https://github.com/spree/spree/tree/main/packages/core)+- [Report an issue](https://github.com/spree/spree/issues)++## License++MITdiff --git a/packages/core/biome.json b/packages/core/biome.jsonnew file mode 100644index 0000000000..807e9850f0--- /dev/null+++ b/packages/core/biome.json@@ -0,0 +1,8 @@+{+ "$schema": "https://biomejs.dev/schemas/2.5.15/schema.json",+ "root": false,+ "extends": ["../../biome.json"],+ "files": {+ "includes": ["src/**", "tests/**"]+ }+}diff --git a/packages/core/package.json b/packages/core/package.jsonnew file mode 100644index 0000000000..0dff248c34--- /dev/null+++ b/packages/core/package.json@@ -0,0 +1,70 @@+{+ "name": "@spree/core",+ "version": "0.1.0",+ "description": "Universal Spree Commerce code: country, currency, locale and unit code lists, exact money arithmetic and the filter vocabulary",+ "type": "module",+ "sideEffects": false,+ "main": "./dist/index.cjs",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "@spree/source": "./src/index.ts",+ "import": {+ "types": "./dist/index.d.ts",+ "default": "./dist/index.js"+ },+ "require": {+ "types": "./dist/index.d.cts",+ "default": "./dist/index.cjs"+ }+ }+ },+ "files": [+ "dist",+ "src",+ "README.md"+ ],+ "scripts": {+ "build": "tsup",+ "dev": "tsup --watch",+ "test": "vitest run",+ "typecheck": "tsc --noEmit",+ "lint": "biome check src tests",+ "lint:fix": "biome check --fix src tests",+ "format": "biome format --write src tests",+ "clean": "rm -rf dist",+ "generate:code-lists": "tsx scripts/generate-code-lists.ts",+ "prepublishOnly": "npm run build"+ },+ "keywords": [+ "spree",+ "ecommerce",+ "money",+ "currency",+ "iso-4217",+ "typescript"+ ],+ "author": "Vendo Connect Inc.",+ "license": "MIT",+ "repository": {+ "type": "git",+ "url": "git+https://github.com/spree/spree.git",+ "directory": "packages/core"+ },+ "homepage": "https://spreecommerce.org",+ "bugs": {+ "url": "https://github.com/spree/spree/issues"+ },+ "devDependencies": {+ "@types/node": "^26.6.5",+ "tsup": "^9.0.0",+ "tsx": "^4.21.0",+ "typescript": "^7.0.2",+ "vitest": "^5.0.5",+ "yaml": "^2.9.1"+ },+ "engines": {+ "node": ">=18.0.0"+ }+}diff --git a/packages/sdk-core/scripts/generate-code-lists.ts b/packages/core/scripts/generate-code-lists.tssimilarity index 100%rename from packages/sdk-core/scripts/generate-code-lists.tsrename to packages/core/scripts/generate-code-lists.tsdiff --git a/packages/sdk-core/src/code-lists.generated.ts b/packages/core/src/code-lists.generated.tssimilarity index 100%rename from packages/sdk-core/src/code-lists.generated.tsrename to packages/core/src/code-lists.generated.tsdiff --git a/packages/core/src/codes.ts b/packages/core/src/codes.tsnew file mode 100644index 0000000000..bd87759b3e--- /dev/null+++ b/packages/core/src/codes.ts@@ -0,0 +1,56 @@+import { type CountryCode, CurrencyCode, type LocaleCode } from './code-lists.generated'++/**+ * Whether a value has the shape of an ISO 3166-1 alpha-2 country code.+ *+ * Shape only: the connected server holds the authoritative list and rejects a+ * code it does not know, while `CountryCode` is fixed when this package is+ * built. Checking against that copy would hide or reject a code an older or+ * newer server accepts.+ */+export function isCountryCode(value: unknown): value is CountryCode {+ return typeof value === 'string' && /^[A-Z]{2}$/.test(value)+}++/** Whether a value has the shape of an ISO 4217 currency code. See `isCountryCode`. */+export function isCurrencyCode(value: unknown): value is CurrencyCode {+ return typeof value === 'string' && /^[A-Z]{3}$/.test(value)+}++/**+ * Whether a value has the shape of a locale code: an ISO 639-1 language,+ * optionally with a region (`en`, `pt-BR`, `es-419`). See `isCountryCode`.+ */+export function isLocaleCode(value: unknown): value is LocaleCode {+ return typeof value === 'string' && /^[a-z]{2,3}(-[A-Z0-9]{2,3})?$/.test(value)+}++/**+ * Replaced currencies Spree still accepts, so amounts recorded in them stay+ * valid, but which nobody should pick for new prices.+ */+export const RETIRED_CURRENCY_CODES: ReadonlySet<CurrencyCode> = new Set<CurrencyCode>([+ 'BYR',+ 'CUC',+ 'EEK',+ 'HRK',+ 'LTL',+ 'LVL',+ 'MRO',+ 'MTL',+ 'SKK',+ 'SLL',+ 'STD',+ 'TMM',+ 'VEF',+ 'ZMK',+ 'ZWD',+ 'ZWL',+ 'ZWN',+ 'ZWR',+])++/** Every currency Spree accepts that is still in use, for a picker offering any currency. */+export const ACTIVE_CURRENCY_CODES: readonly CurrencyCode[] = Object.values(CurrencyCode).filter(+ (code) => !RETIRED_CURRENCY_CODES.has(code),+)diff --git a/packages/sdk-core/src/currency-exponents.ts b/packages/core/src/currency-exponents.tssimilarity index 100%rename from packages/sdk-core/src/currency-exponents.tsrename to packages/core/src/currency-exponents.tsdiff --git a/packages/core/src/display-names.ts b/packages/core/src/display-names.tsnew file mode 100644index 0000000000..60d0f7c2d2--- /dev/null+++ b/packages/core/src/display-names.ts@@ -0,0 +1,34 @@+/**+ * The name of a country, currency, language or other code in a reader's+ * language, through `Intl.DisplayNames`, falling back to English. Answers+ * `undefined` when the runtime has no name for it or the code is malformed,+ * so the caller chooses its own fallback (usually the code itself).+ *+ * @example intlDisplayName('region', 'de', 'US') // "Vereinigte Staaten"+ */+export function intlDisplayName(+ type: Intl.DisplayNamesType,+ locale: string,+ code: string,+): string | undefined {+ try {+ return new Intl.DisplayNames([locale, 'en'], { type }).of(code)+ } catch {+ return undefined+ }+}++/**+ * A language's name in that language itself (`Deutsch`, `Français`, `中文`),+ * for a language picker every reader can find their own language in. Some+ * languages write their names in lowercase, so the first letter is+ * capitalized by that language's own rules. An unknown code answers itself.+ *+ * @example localeEndonym('fr') // "Français"+ */+export function localeEndonym(code: string): string {+ const name = intlDisplayName('language', code, code)+ if (!name) return code++ return name.charAt(0).toLocaleUpperCase(code) + name.slice(1)+}diff --git a/packages/sdk-core/src/filters.ts b/packages/core/src/filters.tssimilarity index 94%rename from packages/sdk-core/src/filters.tsrename to packages/core/src/filters.tsindex 499cbedac3..01177f19e3 100644--- a/packages/sdk-core/src/filters.ts+++ b/packages/core/src/filters.ts@@ -31,6 +31,11 @@ export const FILTER_PREDICATES = {type Predicates = typeof FILTER_PREDICATEStype Kind = keyof Predicates+/** Every predicate a list endpoint accepts on some kind of value: `eq`, `i_cont`, `not_in`, … */+export type FilterPredicate = {+ [K in Kind]: Predicates[K]['value' | 'list' | 'flag'][number]+}[Kind]+type Keyed<K extends string, P extends string, V> = { [Key in K as `${Key}_${P}`]?: V }type KindFilters<K extends string, Of extends Kind, V> = Keyed<diff --git a/packages/core/src/index.ts b/packages/core/src/index.tsnew file mode 100644index 0000000000..6ca01bd843--- /dev/null+++ b/packages/core/src/index.ts@@ -0,0 +1,55 @@+// Code lists+export {+ CountryCode,+ CurrencyCode,+ DimensionUnit,+ LocaleCode,+ WeightUnit,+} from './code-lists.generated'+export {+ ACTIVE_CURRENCY_CODES,+ isCountryCode,+ isCurrencyCode,+ isLocaleCode,+ RETIRED_CURRENCY_CODES,+} from './codes'+// Money+export { CURRENCY_EXPONENTS } from './currency-exponents'+// Display names+export { intlDisplayName, localeEndonym } from './display-names'+// Filters+export type {+ BooleanFilters,+ CodeFilters,+ CustomFieldValueFilters,+ EnumFilters,+ FilterPredicate,+ IdFilters,+ OrFilters,+ Prefixed,+ RangeFilters,+ SortKey,+ TextFilters,+} from './filters'+export { FILTER_PREDICATES } from './filters'+export {+ compareMoney,+ decimalPlaces,+ formatMoney,+ fractionToPercent,+ isDecimalString,+ isPositiveMoney,+ isZeroMoney,+ multiplyMoney,+ negateMoney,+ percentOf,+ percentToFraction,+ prorateMoney,+ shiftDecimalPoint,+ subtractMoney,+ sumMoney,+} from './money'+export { currencyParts, normalizeMoneyInput } from './money-input'+// Units+export type { UnitSystem } from './unit-systems'+export { UNIT_SYSTEM_WEIGHT_UNITS, UNIT_SYSTEMS } from './unit-systems'diff --git a/packages/core/src/money-input.ts b/packages/core/src/money-input.tsnew file mode 100644index 0000000000..57f7ec1d65--- /dev/null+++ b/packages/core/src/money-input.ts@@ -0,0 +1,106 @@+// Reading amounts people type. Spree accepts amounts only as canonical decimal+// strings ("1234.56": a period decimal, no grouping), and never parses a+// comma or a period on the server, because how a number is written is a+// presentation concern. A client converts what was typed in the reader's own+// format, in the same locale the field is displayed in, so a value reads back+// exactly as it was shown.++/**+ * Derives a locale's decimal and group separators via `Intl`. `fr` groups with+ * a narrow no-break space (U+202F), so we read the real characters rather than+ * assuming `,`/`.`/`" "`.+ */+function separatorsFor(locale: string): { decimal: string; group: string } {+ try {+ const parts = new Intl.NumberFormat(locale, { useGrouping: true }).formatToParts(11111.1)+ return {+ decimal: parts.find((p) => p.type === 'decimal')?.value ?? '.',+ group: parts.find((p) => p.type === 'group')?.value ?? '',+ }+ } catch {+ return { decimal: '.', group: '' }+ }+}++/**+ * Converts a locale-formatted amount string to a canonical decimal string.+ *+ * - `"1.234,56"` under `de` → `"1234.56"`+ * - `"1 234,56"` under `fr` → `"1234.56"` (narrow-space grouping)+ * - `"19.99"` under `en` → `"19.99"`+ * - `"19.50"` under `de` → `"19.50"` (a period can't be grouping before two digits)+ * - `""` / whitespace → `""`+ *+ * Strips the locale's group separator and any whitespace, standardizes the+ * decimal separator to `.`, and drops stray characters. Keeps the value as a+ * string throughout — never `Number()`-coerces — to preserve precision.+ *+ * @param raw the merchant's typed value+ * @param locale the display locale the value was entered in (e.g. `de`)+ * @returns canonical `"1234.56"`-form string, or `''` for blank input+ */+export function normalizeMoneyInput(raw: string | null | undefined, locale: string): string {+ if (raw == null) return ''+ const trimmed = raw.trim()+ if (trimmed === '') return ''++ const { decimal, group } = separatorsFor(locale)++ let out = trimmed+ // A group separator is always followed by exactly three digits, so a lone+ // one that is not (`19.50` under `de`) is the merchant typing the other+ // decimal mark. `1.500` stays ambiguous and is read the locale's way.+ const groupParts = group.trim() === '' ? [] : out.split(group)+ if (+ groupParts.length === 2 &&+ !out.includes(decimal) &&+ groupParts[1].replace(/\D/g, '').length !== 3+ ) {+ out = groupParts.join(decimal)+ }+ // Remove the locale's grouping separator (explicit char) plus any whitespace+ // (covers narrow/no-break spaces used by some locales as the group char).+ if (group) out = out.split(group).join('')+ out = out.replace(/\s/g, '')+ // Standardize the decimal separator to `.`.+ if (decimal !== '.') out = out.split(decimal).join('.')+ // Drop anything that isn't a digit, dot, or minus.+ out = out.replace(/[^0-9.-]/g, '')++ // Enforce the canonical shape: a single optional leading minus, then digits+ // with at most one decimal point. Stray separators (`1.2.3`) or interior+ // minus signs (`12-3.4`) would otherwise reach the API as malformed values.+ const negative = out.startsWith('-')+ const digitsAndDots = out.replace(/-/g, '')+ const firstDot = digitsAndDots.indexOf('.')+ const canonical =+ firstDot === -1+ ? digitsAndDots+ : `${digitsAndDots.slice(0, firstDot)}.${digitsAndDots.slice(firstDot + 1).replace(/\./g, '')}`++ if (canonical === '' || canonical === '.') return ''+ return negative ? `-${canonical}` : canonical+}++/**+ * A currency's symbol and decimal separator in a locale, for labelling an+ * amount input ("€" and "," for EUR in `de`). An unknown currency falls back+ * to its code and a period.+ */+export function currencyParts(+ currencyCode: string,+ locale: string,+): { symbol: string; decimal: string } {+ try {+ const parts = new Intl.NumberFormat(locale, {+ style: 'currency',+ currency: currencyCode,+ }).formatToParts(1234.56)+ return {+ symbol: parts.find((p) => p.type === 'currency')?.value ?? currencyCode,+ decimal: parts.find((p) => p.type === 'decimal')?.value ?? '.',+ }+ } catch {+ return { symbol: currencyCode, decimal: '.' }+ }+}diff --git a/packages/sdk-core/src/money.ts b/packages/core/src/money.tssimilarity index 62%rename from packages/sdk-core/src/money.tsrename to packages/core/src/money.tsindex aa2bfc2bf0..b8670374e0 100644--- a/packages/sdk-core/src/money.ts+++ b/packages/core/src/money.ts@@ -155,3 +155,94 @@ export function formatMoney(function roundsToZero(amount: string, places: number): boolean {return compareMoney(amount, `0.${'0'.repeat(places)}5`) < 0}++/** Whether an amount is a decimal string above zero. Blank or malformed is not. */+export function isPositiveMoney(value: string | null | undefined): value is string {+ return isDecimalString(value) && compareMoney(value, '0') > 0+}++/**+ * Moves the decimal point of a decimal string by whole places, exactly, and+ * writes the result without trailing zeros ("0.077" shifted by 2 is "7.7").+ * Anything that is not a decimal string comes back unchanged.+ */+export function shiftDecimalPoint(value: string, places: number): string {+ if (!isDecimalString(value)) return value++ const negative = value.startsWith('-')+ const [whole, fraction = ''] = (negative ? value.slice(1) : value).split('.')+ let digits = whole + fraction+ let point = whole.length + places+ if (point < 0) {+ digits = '0'.repeat(-point) + digits+ point = 0+ }+ digits = digits.padEnd(point, '0')++ const integer = digits.slice(0, point).replace(/^0+(?=\d)/, '') || '0'+ const decimals = digits.slice(point).replace(/0+$/, '')+ const text = decimals ? `${integer}.${decimals}` : integer+ return negative && /[1-9]/.test(text) ? `-${text}` : text+}++/** A fraction rate ("0.23") as the percentage a merchant reads ("23"). Blank stays blank. */+export function fractionToPercent(fraction: string | null | undefined): string {+ return fraction == null || fraction === '' ? '' : shiftDecimalPoint(fraction, 2)+}++/** A typed percentage ("23") as the fraction rate the API stores ("0.23"). Blank stays blank. */+export function percentToFraction(percent: string | null | undefined): string {+ return percent == null || percent === '' ? '' : shiftDecimalPoint(percent.trim(), -2)+}++/**+ * numerator / denominator, where the numerator carries `scale` decimals,+ * rounded half away from zero to the currency's decimals.+ */+function roundToCurrency(+ numerator: bigint,+ scale: number,+ denominator: bigint,+ currency: string,+): string {+ const places = decimalPlaces(currency)+ const negative = numerator < 0n !== denominator < 0n+ let dividend = numerator < 0n ? -numerator : numerator+ let divisor = denominator < 0n ? -denominator : denominator+ if (scale > places) divisor *= 10n ** BigInt(scale - places)+ else dividend *= 10n ** BigInt(places - scale)++ let units = dividend / divisor+ if ((dividend % divisor) * 2n >= divisor) units += 1n++ const text = shiftDecimalPoint((negative ? -units : units).toString(), -places)+ return sumMoney([text], currency)+}++/**+ * A percentage of an amount, exactly, rounded half away from zero to the+ * currency's decimals ("10" percent of "19.99" USD is "2.00").+ */+export function percentOf(amount: string, percent: string, currency: string): string {+ const left = parse(amount)+ const right = parse(percent)+ // The percentage is a hundredth, so the product carries two more places.+ return roundToCurrency(left.units * right.units, left.scale + right.scale + 2, 1n, currency)+}++/**+ * The share of an amount that `part` of `whole` units carries ("10.00" for 1+ * of 3 is "3.33"), rounded half away from zero to the currency's decimals.+ */+export function prorateMoney(+ amount: string,+ part: number,+ whole: number,+ currency: string,+): string {+ if (!Number.isInteger(part) || !Number.isInteger(whole) || whole === 0) {+ throw new Error(`Cannot prorate ${part} of ${whole}`)+ }+ const { units, scale } = parse(amount)+ return roundToCurrency(units * BigInt(part), scale, BigInt(whole), currency)+}diff --git a/packages/core/src/unit-systems.ts b/packages/core/src/unit-systems.tsnew file mode 100644index 0000000000..d5e77c4ea9--- /dev/null+++ b/packages/core/src/unit-systems.ts@@ -0,0 +1,12 @@+import type { WeightUnit } from './code-lists.generated'++/** The measurement systems a store can use. */+export type UnitSystem = 'metric' | 'imperial'++export const UNIT_SYSTEMS: readonly UnitSystem[] = ['metric', 'imperial']++/** The weight units each system offers, the usual one first. */+export const UNIT_SYSTEM_WEIGHT_UNITS: Readonly<Record<UnitSystem, readonly WeightUnit[]>> = {+ metric: ['kg', 'g'],+ imperial: ['lb', 'oz'],+}diff --git a/packages/sdk/tests/iso-codes.test.ts b/packages/core/tests/code-lists.test.tssimilarity index 53%rename from packages/sdk/tests/iso-codes.test.tsrename to packages/core/tests/code-lists.test.tsindex bc9b4a9be3..83bd0ea525 100644--- a/packages/sdk/tests/iso-codes.test.ts+++ b/packages/core/tests/code-lists.test.ts@@ -1,10 +1,12 @@import { describe, expect, it } from 'vitest'-import { CountryCode, CurrencyCode, LocaleCode } from '../src'+import { CountryCode, CurrencyCode, DimensionUnit, LocaleCode, WeightUnit } from '../src'-describe('ISO code lists', () => {+describe('code lists', () => {it('name each code by its standard value', () => {expect(CountryCode.US).toBe('US')expect(CurrencyCode.EUR).toBe('EUR')expect(LocaleCode.pt_BR).toBe('pt-BR')+ expect(WeightUnit.kg).toBe('kg')+ expect(DimensionUnit.ft).toBe('ft')})})diff --git a/packages/core/tests/codes.test.ts b/packages/core/tests/codes.test.tsnew file mode 100644index 0000000000..c416a4f1f6--- /dev/null+++ b/packages/core/tests/codes.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest'+import {+ ACTIVE_CURRENCY_CODES,+ CurrencyCode,+ isCountryCode,+ isCurrencyCode,+ isLocaleCode,+ RETIRED_CURRENCY_CODES,+} from '../src'++describe('code shapes', () => {+ it('accepts a code by its shape, including one this package does not list', () => {+ expect([+ isCountryCode('US'),+ isCountryCode('XK'),+ isCountryCode('us'),+ isCountryCode(1),+ ]).toEqual([true, true, false, false])+ expect([isCurrencyCode('EUR'), isCurrencyCode('EU'), isCurrencyCode(null)]).toEqual([+ true,+ false,+ false,+ ])+ expect([+ isLocaleCode('en'),+ isLocaleCode('pt-BR'),+ isLocaleCode('es-419'),+ isLocaleCode('pt_BR'),+ ]).toEqual([true, true, true, false])+ })+})++describe('active currencies', () => {+ it('lists every accepted currency except the retired ones', () => {+ for (const code of RETIRED_CURRENCY_CODES) expect(Object.values(CurrencyCode)).toContain(code)+ expect(ACTIVE_CURRENCY_CODES).toContain('EUR')+ expect(ACTIVE_CURRENCY_CODES).not.toContain('HRK')+ expect(ACTIVE_CURRENCY_CODES.length + RETIRED_CURRENCY_CODES.size).toBe(+ Object.values(CurrencyCode).length,+ )+ })+})diff --git a/packages/core/tests/display-names.test.ts b/packages/core/tests/display-names.test.tsnew file mode 100644index 0000000000..5fdbf46fc1--- /dev/null+++ b/packages/core/tests/display-names.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest'+import { intlDisplayName, localeEndonym } from '../src'++describe('intlDisplayName', () => {+ it('names a code in the reader’s language', () => {+ expect(intlDisplayName('region', 'en', 'US')).toBe('United States')+ expect(intlDisplayName('currency', 'en', 'EUR')).toBe('Euro')+ })++ it('answers undefined for a malformed code', () => {+ expect(intlDisplayName('language', 'en', 'not a code')).toBeUndefined()+ })+})++describe('localeEndonym', () => {+ it('names a language in itself, capitalized', () => {+ expect(localeEndonym('de')).toBe('Deutsch')+ expect(localeEndonym('fr')).toBe('Français')+ })++ it('answers an unknown code back', () => {+ expect(localeEndonym('not a code')).toBe('not a code')+ })+})diff --git a/packages/dashboard-core/src/lib/normalize-money.test.ts b/packages/core/tests/money-input.test.tssimilarity index 84%rename from packages/dashboard-core/src/lib/normalize-money.test.tsrename to packages/core/tests/money-input.test.tsindex ee53f5a6e3..fdbbe7a8d7 100644--- a/packages/dashboard-core/src/lib/normalize-money.test.ts+++ b/packages/core/tests/money-input.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { normalizeMoneyInput } from './normalize-money'+import { currencyParts, normalizeMoneyInput } from '../src'describe('normalizeMoneyInput', () => {it('passes through canonical en input', () => {@@ -65,3 +65,14 @@ describe('normalizeMoneyInput', () => {expect(normalizeMoneyInput('abc', 'en')).toBe('')})})++describe('currencyParts', () => {+ it('gives a currency’s symbol and decimal separator in a locale', () => {+ expect(currencyParts('EUR', 'de')).toEqual({ symbol: '€', decimal: ',' })+ expect(currencyParts('USD', 'en')).toEqual({ symbol: '$', decimal: '.' })+ })++ it('falls back to the code and a period for an unknown currency', () => {+ expect(currencyParts('XYZ1', 'en')).toEqual({ symbol: 'XYZ1', decimal: '.' })+ })+})diff --git a/packages/admin-sdk/tests/money.test.ts b/packages/core/tests/money.test.tssimilarity index 61%rename from packages/admin-sdk/tests/money.test.tsrename to packages/core/tests/money.test.tsindex 0f9935326a..940c8c6bcf 100644--- a/packages/admin-sdk/tests/money.test.ts+++ b/packages/core/tests/money.test.ts@@ -1,15 +1,21 @@import { readFileSync } from 'node:fs'import { resolve } from 'node:path'import { describe, expect, it } from 'vitest'-import { CURRENCY_EXPONENTS } from '../../sdk-core/src/currency-exponents'import {+ CURRENCY_EXPONENTS,compareMoney,decimalPlaces,formatMoney,+ fractionToPercent,isDecimalString,+ isPositiveMoney,isZeroMoney,multiplyMoney,negateMoney,+ percentOf,+ percentToFraction,+ prorateMoney,+ shiftDecimalPoint,subtractMoney,sumMoney,} from '../src'@@ -96,3 +102,57 @@ describe('money helpers', () => {expect(formatMoney('-0.005', 'USD', 'en')).toBe('-$0.01')})})++describe('shiftDecimalPoint', () => {+ it('moves the point exactly, without float noise', () => {+ expect(shiftDecimalPoint('0.077', 2)).toBe('7.7')+ expect(shiftDecimalPoint('7.7', -2)).toBe('0.077')+ expect(shiftDecimalPoint('0.07', 2)).toBe('7')+ expect(shiftDecimalPoint('1', 2)).toBe('100')+ expect(shiftDecimalPoint('100', -2)).toBe('1')+ expect(shiftDecimalPoint('-0.5', 2)).toBe('-50')+ expect(shiftDecimalPoint('0', -2)).toBe('0')+ })++ it('leaves a value that is not a decimal string alone', () => {+ expect(shiftDecimalPoint('abc', 2)).toBe('abc')+ })+})++describe('fractionToPercent / percentToFraction', () => {+ it('round-trips and keeps blanks blank', () => {+ expect(fractionToPercent('0.23')).toBe('23')+ expect(percentToFraction('23')).toBe('0.23')+ expect(percentToFraction('7.25')).toBe('0.0725')+ expect(fractionToPercent(null)).toBe('')+ expect(percentToFraction('')).toBe('')+ })+})++describe('percentOf', () => {+ it('rounds to the currency decimals', () => {+ expect(percentOf('19.99', '10', 'USD')).toBe('2.00')+ expect(percentOf('100', '12.5', 'USD')).toBe('12.50')+ expect(percentOf('1000', '0.05', 'JPY')).toBe('1')+ expect(percentOf('1.005', '50', 'KWD')).toBe('0.503')+ })+})++describe('isPositiveMoney', () => {+ it('is true only for an amount above zero', () => {+ expect(isPositiveMoney('0.01')).toBe(true)+ expect(isPositiveMoney('0.00')).toBe(false)+ expect(isPositiveMoney('-1')).toBe(false)+ expect(isPositiveMoney(null)).toBe(false)+ expect(isPositiveMoney('abc')).toBe(false)+ })+})++describe('prorateMoney', () => {+ it('shares an amount across units, rounded to the currency', () => {+ expect(prorateMoney('10.00', 1, 3, 'USD')).toBe('3.33')+ expect(prorateMoney('10.00', 2, 3, 'USD')).toBe('6.67')+ expect(prorateMoney('10.00', 3, 3, 'USD')).toBe('10.00')+ expect(prorateMoney('1000', 1, 3, 'JPY')).toBe('333')+ })+})diff --git a/packages/core/tests/unit-systems.test.ts b/packages/core/tests/unit-systems.test.tsnew file mode 100644index 0000000000..25ffb3587b--- /dev/null+++ b/packages/core/tests/unit-systems.test.ts@@ -0,0 +1,36 @@+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'+import { describe, expect, it } from 'vitest'+import { parse } from 'yaml'+import { UNIT_SYSTEM_WEIGHT_UNITS, UNIT_SYSTEMS, WeightUnit } from '../src'++// Every `unit_system` the Admin API reference declares, wherever it appears.+function publishedUnitSystems(node: unknown, found = new Set<string>()): Set<string> {+ if (Array.isArray(node)) {+ for (const item of node) publishedUnitSystems(item, found)+ } else if (node && typeof node === 'object') {+ for (const [key, value] of Object.entries(node)) {+ const values = (value as { enum?: unknown })?.enum+ if (key === 'unit_system' && Array.isArray(values)) {+ for (const system of values) found.add(String(system))+ }+ publishedUnitSystems(value, found)+ }+ }+ return found+}++describe('unit systems', () => {+ it('match the unit systems the Admin API accepts', () => {+ const reference = parse(+ readFileSync(resolve(__dirname, '../../../docs/api-reference/admin.yaml'), 'utf-8'),+ )+ expect([...publishedUnitSystems(reference)].sort()).toEqual([...UNIT_SYSTEMS].sort())+ })++ it('offer every weight unit in exactly one system', () => {+ expect(Object.values(UNIT_SYSTEM_WEIGHT_UNITS).flat().sort()).toEqual(+ Object.values(WeightUnit).sort(),+ )+ })+})diff --git a/packages/core/tsconfig.json b/packages/core/tsconfig.jsonnew file mode 100644index 0000000000..ca4102418d--- /dev/null+++ b/packages/core/tsconfig.json@@ -0,0 +1,24 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "lib": ["ES2022", "DOM"],+ "ignoreDeprecations": "6.0",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": true,+ "declarationMap": true,+ "sourceMap": true,+ "outDir": "./dist",+ "rootDir": "./src",+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules", "dist"]+}diff --git a/packages/core/tsup.config.ts b/packages/core/tsup.config.tsnew file mode 100644index 0000000000..3b22e6dbc1--- /dev/null+++ b/packages/core/tsup.config.ts@@ -0,0 +1,14 @@+import { defineConfig } from 'tsup'++export default defineConfig({+ entry: {+ index: 'src/index.ts',+ },+ format: ['cjs', 'esm'],+ dts: true,+ splitting: false,+ sourcemap: true,+ clean: true,+ treeshake: true,+ minify: false,+})diff --git a/packages/core/vitest.config.ts b/packages/core/vitest.config.tsnew file mode 100644index 0000000000..2b1c323fe2--- /dev/null+++ b/packages/core/vitest.config.ts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config'++export default defineConfig({+ test: {+ environment: 'node',+ },+})diff --git a/packages/dashboard-core/package.json b/packages/dashboard-core/package.jsonindex d6920ffd01..b74bf7f3cc 100644--- a/packages/dashboard-core/package.json+++ b/packages/dashboard-core/package.json@@ -73,6 +73,7 @@"@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2","@hookform/resolvers": "^5.2.2",+ "@spree/core": "workspace:^","@tailwindcss/vite": "^4.2.4","@tanstack/react-hotkeys": "^0.14.3","date-fns": "^4.4.0",diff --git a/packages/dashboard-core/src/api-client.ts b/packages/dashboard-core/src/api-client.tsindex 903f21c03f..a489eac4f0 100644--- a/packages/dashboard-core/src/api-client.ts+++ b/packages/dashboard-core/src/api-client.ts@@ -14,13 +14,8 @@* promise the seller panel methods its API does not have.*/-import type {- CountryCode,- DimensionUnit,- PermissionRule,- UploadFileOptions,- WeightUnit,-} from '@spree/admin-sdk'+import type { PermissionRule, UploadFileOptions } from '@spree/admin-sdk'+import type { CountryCode, DimensionUnit, WeightUnit } from '@spree/core'/** What a panel may change on the signed-in person's own account. */export interface PanelAccountParams {@@ -393,9 +388,9 @@ export interface PanelPackageTypeWrites extends PanelPackageTypeReads {}export type PanelPackageTypeKind = 'box' | 'envelope' | 'carton' | 'pallet' | 'container'-/** @deprecated Use `DimensionUnit` from `@spree/admin-sdk`. */+/** @deprecated Use `DimensionUnit` from `@spree/core`. */export type PanelPackageDimensionUnit = DimensionUnit-/** @deprecated Use `WeightUnit` from `@spree/admin-sdk`. */+/** @deprecated Use `WeightUnit` from `@spree/core`. */export type PanelPackageWeightUnit = WeightUnit/**diff --git a/packages/dashboard-core/src/components/address-form-dialog.tsx b/packages/dashboard-core/src/components/address-form-dialog.tsxindex 6386f2a6b6..1f0bae69a3 100644--- a/packages/dashboard-core/src/components/address-form-dialog.tsx+++ b/packages/dashboard-core/src/components/address-form-dialog.tsx@@ -1,5 +1,5 @@import { zodResolver } from '@hookform/resolvers/zod'-import type { CountryCode } from '@spree/admin-sdk'+import { type CountryCode, isCountryCode } from '@spree/core'import {Button,Checkbox,@@ -22,7 +22,7 @@ import { Controller, type DefaultValues, useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { z } from 'zod/v4'import { mapSpreeErrorsToForm } from '../lib/form-errors'-import { countryCodeSchema, isCountryCode } from '../lib/iso-codes'+import { countryCodeSchema } from '../lib/iso-codes'import { useOptionalStore } from '../providers/store-provider'import { CountryCombobox } from './country-combobox'import { StateCombobox, useCountryStates } from './country-state-fields'diff --git a/packages/dashboard-core/src/components/country-combobox.tsx b/packages/dashboard-core/src/components/country-combobox.tsxindex 55c03464fa..db8cf3f9f0 100644--- a/packages/dashboard-core/src/components/country-combobox.tsx+++ b/packages/dashboard-core/src/components/country-combobox.tsx@@ -1,4 +1,4 @@-import type { CountryCode } from '@spree/admin-sdk'+import { type CountryCode, isCountryCode } from '@spree/core'import {Combobox,ComboboxButtonTrigger,@@ -19,7 +19,6 @@ import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { useCountries } from '../hooks/use-countries'import { useDisplayName } from '../hooks/use-display-name'-import { isCountryCode } from '../lib/iso-codes'export type CountryOption = { iso: CountryCode; iso3: string }diff --git a/packages/dashboard-core/src/components/currency-select.tsx b/packages/dashboard-core/src/components/currency-select.tsxindex e54cbb2e0f..57d90bf177 100644--- a/packages/dashboard-core/src/components/currency-select.tsx+++ b/packages/dashboard-core/src/components/currency-select.tsx@@ -1,4 +1,4 @@-import type { CurrencyCode } from '@spree/admin-sdk'+import { type CurrencyCode, isCurrencyCode } from '@spree/core'import {Combobox,ComboboxButtonTrigger,@@ -12,10 +12,9 @@ import {import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { useDisplayName } from '../hooks/use-display-name'-import { isCurrencyCode } from '../lib/iso-codes'import { useOptionalStore } from '../providers/store-provider'-export { ALL_CURRENCY_CODES } from '../lib/currencies'+export { ACTIVE_CURRENCY_CODES as ALL_CURRENCY_CODES } from '@spree/core'interface CurrencySelectProps {/** Classes for the trigger — used to match a neighbouring control's height. */diff --git a/packages/dashboard-core/src/components/preferences-form.tsx b/packages/dashboard-core/src/components/preferences-form.tsxindex 296f92acd0..46a95eee52 100644--- a/packages/dashboard-core/src/components/preferences-form.tsx+++ b/packages/dashboard-core/src/components/preferences-form.tsx@@ -1,10 +1,5 @@-import type { CurrencyCode } from '@spree/admin-sdk'-import {- compareMoney,- isDecimalString,- type PreferencePropertySchema,- type PreferenceSchema,-} from '@spree/admin-sdk'+import type { PreferencePropertySchema, PreferenceSchema } from '@spree/admin-sdk'+import { type CurrencyCode, compareMoney, currencyParts, isDecimalString } from '@spree/core'import {Button,Field,@@ -29,7 +24,6 @@ import { PlusIcon, TrashIcon } from '@spree/dashboard-ui/icons'import { useId, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { useMoneyLocale } from '../hooks/use-money-locale'-import { currencyParts } from '../lib/currency-parts'import { CountryCombobox, CountryMultiCombobox } from './country-combobox'import { CurrencySelect } from './currency-select'import { StoreDatePicker } from './store-date-picker'diff --git a/packages/dashboard-core/src/components/table-toolbar.tsx b/packages/dashboard-core/src/components/table-toolbar.tsxindex 645aa5420e..a049e15845 100644--- a/packages/dashboard-core/src/components/table-toolbar.tsx+++ b/packages/dashboard-core/src/components/table-toolbar.tsx@@ -1,3 +1,4 @@+import type { FilterPredicate } from '@spree/core'import {Button,Checkbox,@@ -82,14 +83,16 @@ interface TableToolbarProps {// Operator labels are stored as i18n keys (`admin.components.table_toolbar.operators.*`)// and resolved with `t()` at render time so they follow the active language.-const storeCodeOperators = [+type OperatorOption = { value: FilterPredicate; labelKey: string }++const storeCodeOperators: OperatorOption[] = [{ value: 'eq', labelKey: 'admin.components.table_toolbar.operators.is' },{ value: 'not_eq', labelKey: 'admin.components.table_toolbar.operators.is_not' },{ value: 'in', labelKey: 'admin.components.table_toolbar.operators.is_any_of' },{ value: 'not_in', labelKey: 'admin.components.table_toolbar.operators.is_none_of' },]-const operatorsByType: Record<string, { value: string; labelKey: string }[]> = {+const operatorsByType: Record<string, OperatorOption[]> = {string: [// `i_cont` (case-insensitive) rather than `cont` — an admin typing// "2 years" expects to match "2 Years".diff --git a/packages/dashboard-core/src/hooks/use-display-name.ts b/packages/dashboard-core/src/hooks/use-display-name.tsindex 8f05c459a0..765e63ce73 100644--- a/packages/dashboard-core/src/hooks/use-display-name.ts+++ b/packages/dashboard-core/src/hooks/use-display-name.ts@@ -1,24 +1,7 @@import { useMemo } from 'react'import { useTranslation } from 'react-i18next'-/**- * Resolves a code to its display name via `Intl.DisplayNames`, localized to a- * given UI language. Returns `undefined` when the runtime lacks coverage so- * callers can apply their own fallback (usually the raw code).- *- * Standalone (non-hook) variant for module-level use outside React.- */-export function intlDisplayName(- type: Intl.DisplayNamesType,- locale: string,- code: string,-): string | undefined {- try {- return new Intl.DisplayNames([locale, 'en'], { type }).of(code)- } catch {- return undefined- }-}+export { intlDisplayName } from '@spree/core'/*** Hook returning a memoized `code -> name` resolver for one `Intl.DisplayNames`diff --git a/packages/dashboard-core/src/index.ts b/packages/dashboard-core/src/index.tsindex f00a2d4984..221e166e0b 100644--- a/packages/dashboard-core/src/index.ts+++ b/packages/dashboard-core/src/index.ts@@ -11,6 +11,17 @@// import { AuthProvider } from '@spree/dashboard-core/providers/auth-provider'// import { useResourceMutation } from '@spree/dashboard-core/hooks/use-resource-mutation'+// Money helpers from @spree/core, offered here as before for plugin authors+export {+ currencyParts,+ fractionToPercent,+ isPositiveMoney,+ normalizeMoneyInput,+ percentOf,+ percentToFraction,+ prorateMoney,+ shiftDecimalPoint,+} from '@spree/core'export * from './api-client'// ---------------------------------------------------------------------------// Admin SDK client (Vite-aware singleton; reads VITE_SPREE_API_URL at build)@@ -81,7 +92,6 @@ export * from './lib/create-action-registry'// Registries — pluggable extension points (nav, route, slot, table,// settings-nav, form fields, custom field components)// ----------------------------------------------------------------------------export * from './lib/currency-parts'export * from './lib/custom-field-components'export * from './lib/date-presets'export * from './lib/delivery-form'@@ -103,9 +113,7 @@ export * from './lib/i18n'export * from './lib/import-types'export * from './lib/iso-codes'export * from './lib/label-upload-form'-export * from './lib/money'export * from './lib/nav-registry'-export * from './lib/normalize-money'export * from './lib/permissions'export * from './lib/progress'export * from './lib/query-client'diff --git a/packages/dashboard-core/src/lib/currencies.ts b/packages/dashboard-core/src/lib/currencies.tsindex d4ce88debc..21a9d0d885 100644--- a/packages/dashboard-core/src/lib/currencies.ts+++ b/packages/dashboard-core/src/lib/currencies.ts@@ -1,34 +1,2 @@-import { CurrencyCode } from '@spree/admin-sdk'--// Replaced currencies Spree still accepts so orders priced in them stay-// valid, but which no merchant should pick for new pricing.-const RETIRED_CURRENCY_CODES: ReadonlySet<string> = new Set([- 'BYR',- 'CUC',- 'EEK',- 'HRK',- 'LTL',- 'LVL',- 'MRO',- 'MTL',- 'SKK',- 'SLL',- 'STD',- 'TMM',- 'VEF',- 'ZMK',- 'ZWD',- 'ZWL',- 'ZWN',- 'ZWR',-])--/**- * Every currency Spree accepts that is still in use. Used for contexts where- * the merchant can pick *any* currency (a market's currency) rather than one- * the store already supports. The list ships with the SDK, so a currency a- * newer server adds appears once the dashboard is upgraded with it.- */-export const ALL_CURRENCY_CODES: readonly CurrencyCode[] = Object.values(CurrencyCode).filter(- (code) => !RETIRED_CURRENCY_CODES.has(code),-)+/** @deprecated Import `ACTIVE_CURRENCY_CODES` from `@spree/core`. Removed in 6.1. */+export { ACTIVE_CURRENCY_CODES as ALL_CURRENCY_CODES } from '@spree/core'diff --git a/packages/dashboard-core/src/lib/currency-parts.ts b/packages/dashboard-core/src/lib/currency-parts.tsindex 9efe468729..8004c08fee 100644--- a/packages/dashboard-core/src/lib/currency-parts.ts+++ b/packages/dashboard-core/src/lib/currency-parts.ts@@ -1,21 +1,2 @@-// Resolve a currency code into its symbol + decimal separator under the-// current locale, with a safe fallback for unknown/invalid currencies.-// Shared between the server-backed BulkPriceEditor and the form-backed-// ProductBulkPriceEditor.-export function currencyParts(- currencyCode: string,- locale: string,-): { symbol: string; decimal: string } {- try {- const parts = new Intl.NumberFormat(locale, {- style: 'currency',- currency: currencyCode,- }).formatToParts(1234.56)- return {- symbol: parts.find((p) => p.type === 'currency')?.value ?? currencyCode,- decimal: parts.find((p) => p.type === 'decimal')?.value ?? '.',- }- } catch {- return { symbol: currencyCode, decimal: '.' }- }-}+/** @deprecated Import from `@spree/core`. Removed in 6.1. */+export { currencyParts } from '@spree/core'diff --git a/packages/dashboard-core/src/lib/filters-to-ransack.ts b/packages/dashboard-core/src/lib/filters-to-ransack.tsindex 0b87766add..74c03656a3 100644--- a/packages/dashboard-core/src/lib/filters-to-ransack.ts+++ b/packages/dashboard-core/src/lib/filters-to-ransack.ts@@ -1,3 +1,4 @@+import { FILTER_PREDICATES } from '@spree/core'import { type ColumnDef, type FilterRule, parseFilterIds } from './table-registry'/**@@ -20,7 +21,9 @@ import { type ColumnDef, type FilterRule, parseFilterIds } from './table-registr// `q[xxx_in][]=...` for each item. The chip stores the IDs as a CSV string// in `FilterRule.value` so the URL serializer (which already JSON-stringifies// FilterRule[]) stays simple.-const ARRAY_OPERATORS = new Set(['in', 'not_in'])+const ARRAY_OPERATORS = new Set<string>(+ Object.values(FILTER_PREDICATES).flatMap((predicates) => predicates.list),+)const NEGATING_OPERATORS = new Set(['not_in', 'not_eq'])diff --git a/packages/dashboard-core/src/lib/form-mappers.ts b/packages/dashboard-core/src/lib/form-mappers.tsindex 0968ba37df..d7cc31997b 100644--- a/packages/dashboard-core/src/lib/form-mappers.ts+++ b/packages/dashboard-core/src/lib/form-mappers.ts@@ -1,4 +1,4 @@-import type { CountryCode } from '@spree/admin-sdk'+import type { CountryCode } from '@spree/core'import type { PanelAccountParams } from '../api-client'/**diff --git a/packages/dashboard-core/src/lib/formatters.ts b/packages/dashboard-core/src/lib/formatters.tsindex d92871669f..1f878c1b11 100644--- a/packages/dashboard-core/src/lib/formatters.ts+++ b/packages/dashboard-core/src/lib/formatters.ts@@ -1,4 +1,5 @@-import { formatMoney, type Price } from '@spree/admin-sdk'+import type { Price } from '@spree/admin-sdk'+import { formatMoney } from '@spree/core'import { parseISO } from 'date-fns'import { formatInTimeZone } from 'date-fns-tz'import i18n from 'i18next'@@ -19,9 +20,8 @@ export function formatPrice(}/**- * Formats an API amount (a decimal string) in its currency, falling back to- * the bare number for a currency `Intl` does not know, and to `fallback` when- * either is missing.+ * Formats an API amount (a decimal string) in its currency, or answers+ * `fallback` when either is missing or `Intl` cannot format the pair.*/export function formatAmount(amount: string | null | undefined,@@ -29,12 +29,8 @@ export function formatAmount(locale?: string,fallback = '—',): string {- if (amount === null || amount === undefined || amount === '' || !currency) return fallback- try {- return formatMoney(amount, currency, locale) || fallback- } catch {- return `${amount} ${currency}`- }+ if (!currency) return fallback+ return formatMoney(amount, currency, locale) || fallback}export function formatStoreDateTime(iso: string, timezone: string) {diff --git a/packages/dashboard-core/src/lib/i18n.ts b/packages/dashboard-core/src/lib/i18n.tsindex cca20f347d..4c017d55d8 100644--- a/packages/dashboard-core/src/lib/i18n.ts+++ b/packages/dashboard-core/src/lib/i18n.ts@@ -1,6 +1,6 @@+import { localeEndonym } from '@spree/core'import i18n from 'i18next'import { initReactI18next } from 'react-i18next'-import { intlDisplayName } from '../hooks/use-display-name'// Relative path, not `@/...`: dashboard-core ships source; the consuming// project's `@/*` alias is theirs alone (see Phase 1's rationale).import en from '../locales/en.json'@@ -153,17 +153,6 @@ function localeCodesFromBundlePaths(paths: string[]): string[] {return ['en', ...paths.map((path) => path.replace(/^.*\/locales\//, '').replace('.json', ''))]}-// Each language's endonym (its own name: `Deutsch`, `中文`). `Intl.DisplayNames`-// answers in the language's own convention, so some come back lowercase-// (`français`, `polski`); capitalize the first letter by THAT language's casing-// rules rather than the current locale's. Scripts without case are unaffected,-// and an unknown code falls back to itself.-function localeEndonym(code: string): string {- const name = intlDisplayName('language', code, code) ?? code-- return name.charAt(0).toLocaleUpperCase(code) + name.slice(1)-}-// The languages the running panel can display, as it declared them. `null`// until a panel does, which accepts every code — the behaviour before panels// declared anything.diff --git a/packages/dashboard-core/src/lib/iso-codes.ts b/packages/dashboard-core/src/lib/iso-codes.tsindex 31f7e630f1..a626625902 100644--- a/packages/dashboard-core/src/lib/iso-codes.ts+++ b/packages/dashboard-core/src/lib/iso-codes.ts@@ -1,32 +1,15 @@-import type { CountryCode, CurrencyCode, LocaleCode } from '@spree/admin-sdk'+import {+ type CountryCode,+ type CurrencyCode,+ isCountryCode,+ isCurrencyCode,+ isLocaleCode,+ type LocaleCode,+} from '@spree/core'import i18n from 'i18next'import { z } from 'zod/v4'-/**- * Whether a value has the shape of an ISO 3166-1 alpha-2 country code.- *- * Shape only: the connected server holds the authoritative list and rejects- * a code it does not know, while the SDK's `CountryCode` list is fixed when it- * is built. Checking against that copy would hide or reject a code an older or- * newer server accepts. This is the one place a plain string becomes a- * `CountryCode`.- */-export function isCountryCode(value: unknown): value is CountryCode {- return typeof value === 'string' && /^[A-Z]{2}$/.test(value)-}--/** Whether a value has the shape of an ISO 4217 currency code. See `isCountryCode`. */-export function isCurrencyCode(value: unknown): value is CurrencyCode {- return typeof value === 'string' && /^[A-Z]{3}$/.test(value)-}--/**- * Whether a value has the shape of a locale code: an ISO 639-1 language,- * optionally with a region (`en`, `pt-BR`, `es-419`). See `isCountryCode`.- */-export function isLocaleCode(value: unknown): value is LocaleCode {- return typeof value === 'string' && /^[a-z]{2,3}(-[A-Z0-9]{2,3})?$/.test(value)-}+export { isCountryCode, isCurrencyCode, isLocaleCode }/*** A required country field. A form that allows leaving it blank widens itdiff --git a/packages/dashboard-core/src/lib/money.test.ts b/packages/dashboard-core/src/lib/money.test.tsdeleted file mode 100644index b3b956d1ad..0000000000--- a/packages/dashboard-core/src/lib/money.test.ts+++ /dev/null@@ -1,63 +0,0 @@-import { describe, expect, it } from 'vitest'-import {- fractionToPercent,- isPositiveMoney,- percentOf,- percentToFraction,- prorateMoney,- shiftDecimalPoint,-} from './money'--describe('shiftDecimalPoint', () => {- it('moves the point exactly, without float noise', () => {- expect(shiftDecimalPoint('0.077', 2)).toBe('7.7')- expect(shiftDecimalPoint('7.7', -2)).toBe('0.077')- expect(shiftDecimalPoint('0.07', 2)).toBe('7')- expect(shiftDecimalPoint('1', 2)).toBe('100')- expect(shiftDecimalPoint('100', -2)).toBe('1')- expect(shiftDecimalPoint('-0.5', 2)).toBe('-50')- expect(shiftDecimalPoint('0', -2)).toBe('0')- })-- it('leaves a value that is not a decimal string alone', () => {- expect(shiftDecimalPoint('abc', 2)).toBe('abc')- })-})--describe('fractionToPercent / percentToFraction', () => {- it('round-trips and keeps blanks blank', () => {- expect(fractionToPercent('0.23')).toBe('23')- expect(percentToFraction('23')).toBe('0.23')- expect(percentToFraction('7.25')).toBe('0.0725')- expect(fractionToPercent(null)).toBe('')- expect(percentToFraction('')).toBe('')- })-})--describe('percentOf', () => {- it('rounds to the currency decimals', () => {- expect(percentOf('19.99', '10', 'USD')).toBe('2.00')- expect(percentOf('100', '12.5', 'USD')).toBe('12.50')- expect(percentOf('1000', '0.05', 'JPY')).toBe('1')- expect(percentOf('1.005', '50', 'KWD')).toBe('0.503')- })-})--describe('isPositiveMoney', () => {- it('is true only for an amount above zero', () => {- expect(isPositiveMoney('0.01')).toBe(true)- expect(isPositiveMoney('0.00')).toBe(false)- expect(isPositiveMoney('-1')).toBe(false)- expect(isPositiveMoney(null)).toBe(false)- expect(isPositiveMoney('abc')).toBe(false)- })-})--describe('prorateMoney', () => {- it('shares an amount across units, rounded to the currency', () => {- expect(prorateMoney('10.00', 1, 3, 'USD')).toBe('3.33')- expect(prorateMoney('10.00', 2, 3, 'USD')).toBe('6.67')- expect(prorateMoney('10.00', 3, 3, 'USD')).toBe('10.00')- expect(prorateMoney('1000', 1, 3, 'JPY')).toBe('333')- })-})diff --git a/packages/dashboard-core/src/lib/money.ts b/packages/dashboard-core/src/lib/money.tsindex 14ba144b79..3821dce177 100644--- a/packages/dashboard-core/src/lib/money.ts+++ b/packages/dashboard-core/src/lib/money.ts@@ -1,99 +1,9 @@-import { compareMoney, decimalPlaces, isDecimalString, sumMoney } from '@spree/admin-sdk'--/** Whether an amount is a decimal string above zero. Blank or malformed is not. */-export function isPositiveMoney(value: string | null | undefined): boolean {- return isDecimalString(value) && compareMoney(value, '0') > 0-}--/**- * Moves the decimal point of a decimal string by whole places, exactly, and- * writes the result without trailing zeros ("0.077" shifted by 2 is "7.7").- * Anything that is not a decimal string comes back unchanged.- */-export function shiftDecimalPoint(value: string, places: number): string {- if (!isDecimalString(value)) return value-- const negative = value.startsWith('-')- const [whole, fraction = ''] = (negative ? value.slice(1) : value).split('.')- let digits = whole + fraction- let point = whole.length + places- if (point < 0) {- digits = '0'.repeat(-point) + digits- point = 0- }- digits = digits.padEnd(point, '0')-- const integer = digits.slice(0, point).replace(/^0+(?=\d)/, '') || '0'- const decimals = digits.slice(point).replace(/0+$/, '')- const text = decimals ? `${integer}.${decimals}` : integer- return negative && /[1-9]/.test(text) ? `-${text}` : text-}--/** A fraction rate ("0.23") as the percentage a merchant reads ("23"). Blank stays blank. */-export function fractionToPercent(fraction: string | null | undefined): string {- return fraction == null || fraction === '' ? '' : shiftDecimalPoint(fraction, 2)-}--/** A typed percentage ("23") as the fraction rate the API stores ("0.23"). Blank stays blank. */-export function percentToFraction(percent: string | null | undefined): string {- return percent == null || percent === '' ? '' : shiftDecimalPoint(percent.trim(), -2)-}--function scaled(value: string): { units: bigint; scale: number } {- const negative = value.startsWith('-')- const [whole, fraction = ''] = (negative ? value.slice(1) : value).split('.')- const units = BigInt(whole + fraction)- return { units: negative ? -units : units, scale: fraction.length }-}--/**- * numerator / denominator, where the numerator carries `scale` decimals,- * rounded half away from zero to the currency's decimals.- */-function roundToCurrency(- numerator: bigint,- scale: number,- denominator: bigint,- currency: string,-): string {- const places = decimalPlaces(currency)- const negative = numerator < 0n !== denominator < 0n- let dividend = numerator < 0n ? -numerator : numerator- let divisor = denominator < 0n ? -denominator : denominator- if (scale > places) divisor *= 10n ** BigInt(scale - places)- else dividend *= 10n ** BigInt(places - scale)-- let units = dividend / divisor- if ((dividend % divisor) * 2n >= divisor) units += 1n-- const text = shiftDecimalPoint((negative ? -units : units).toString(), -places)- return sumMoney([text], currency)-}--/**- * A percentage of an amount, exactly, rounded half away from zero to the- * currency's decimals ("10" percent of "19.99" USD is "2.00").- */-export function percentOf(amount: string, percent: string, currency: string): string {- const left = scaled(amount)- const right = scaled(percent)- // The percentage is a hundredth, so the product carries two more places.- return roundToCurrency(left.units * right.units, left.scale + right.scale + 2, 1n, currency)-}--/**- * The share of an amount that `part` of `whole` units carries ("10.00" for 1- * of 3 is "3.33"), rounded half away from zero to the currency's decimals.- */-export function prorateMoney(- amount: string,- part: number,- whole: number,- currency: string,-): string {- if (!Number.isInteger(part) || !Number.isInteger(whole) || whole === 0) {- throw new Error(`Cannot prorate ${part} of ${whole}`)- }- const { units, scale } = scaled(amount)- return roundToCurrency(units * BigInt(part), scale, BigInt(whole), currency)-}+/** @deprecated Import these from `@spree/core`. Removed in 6.1. */+export {+ fractionToPercent,+ isPositiveMoney,+ percentOf,+ percentToFraction,+ prorateMoney,+ shiftDecimalPoint,+} from '@spree/core'diff --git a/packages/dashboard-core/src/lib/normalize-money.ts b/packages/dashboard-core/src/lib/normalize-money.tsindex 6f984291ad..02e0b71bea 100644--- a/packages/dashboard-core/src/lib/normalize-money.ts+++ b/packages/dashboard-core/src/lib/normalize-money.ts@@ -1,85 +1,2 @@-// Normalize a merchant's locale-formatted money input into the canonical-// decimal string the Admin API expects (`"1234.56"` — period decimal, no-// grouping). Industry-standard: localization is a presentation concern, so the-// dashboard converts here, in the browser, and never relies on the server to-// parse comma-vs-period. See docs/plans/5.5-client-side-money-normalization.md.-//-// The locale is the admin's own (`useMoneyLocale`), the same one the field is-// displayed in, so a value reads back exactly as it was shown.--/**- * Derives a locale's decimal and group separators via `Intl`. `fr` groups with- * a narrow no-break space (U+202F), so we read the real characters rather than- * assuming `,`/`.`/`" "`.- */-function separatorsFor(locale: string): { decimal: string; group: string } {- try {- const parts = new Intl.NumberFormat(locale, { useGrouping: true }).formatToParts(11111.1)- return {- decimal: parts.find((p) => p.type === 'decimal')?.value ?? '.',- group: parts.find((p) => p.type === 'group')?.value ?? '',- }- } catch {- return { decimal: '.', group: '' }- }-}--/**- * Converts a locale-formatted amount string to a canonical decimal string.- *- * - `"1.234,56"` under `de` → `"1234.56"`- * - `"1 234,56"` under `fr` → `"1234.56"` (narrow-space grouping)- * - `"19.99"` under `en` → `"19.99"`- * - `"19.50"` under `de` → `"19.50"` (a period can't be grouping before two digits)- * - `""` / whitespace → `""`- *- * Strips the locale's group separator and any whitespace, standardizes the- * decimal separator to `.`, and drops stray characters. Keeps the value as a- * string throughout — never `Number()`-coerces — to preserve precision.- *- * @param raw the merchant's typed value- * @param locale the display locale the value was entered in (e.g. `de`)- * @returns canonical `"1234.56"`-form string, or `''` for blank input- */-export function normalizeMoneyInput(raw: string | null | undefined, locale: string): string {- if (raw == null) return ''- const trimmed = raw.trim()- if (trimmed === '') return ''-- const { decimal, group } = separatorsFor(locale)-- let out = trimmed- // A group separator is always followed by exactly three digits, so a lone- // one that is not (`19.50` under `de`) is the merchant typing the other- // decimal mark. `1.500` stays ambiguous and is read the locale's way.- const groupParts = group.trim() === '' ? [] : out.split(group)- if (- groupParts.length === 2 &&- !out.includes(decimal) &&- groupParts[1].replace(/\D/g, '').length !== 3- ) {- out = groupParts.join(decimal)- }- // Remove the locale's grouping separator (explicit char) plus any whitespace- // (covers narrow/no-break spaces used by some locales as the group char).- if (group) out = out.split(group).join('')- out = out.replace(/\s/g, '')- // Standardize the decimal separator to `.`.- if (decimal !== '.') out = out.split(decimal).join('.')- // Drop anything that isn't a digit, dot, or minus.- out = out.replace(/[^0-9.-]/g, '')-- // Enforce the canonical shape: a single optional leading minus, then digits- // with at most one decimal point. Stray separators (`1.2.3`) or interior- // minus signs (`12-3.4`) would otherwise reach the API as malformed values.- const negative = out.startsWith('-')- const digitsAndDots = out.replace(/-/g, '')- const firstDot = digitsAndDots.indexOf('.')- const canonical =- firstDot === -1- ? digitsAndDots- : `${digitsAndDots.slice(0, firstDot)}.${digitsAndDots.slice(firstDot + 1).replace(/\./g, '')}`-- if (canonical === '' || canonical === '.') return ''- return negative ? `-${canonical}` : canonical-}+/** @deprecated Import from `@spree/core`. Removed in 6.1. */+export { normalizeMoneyInput } from '@spree/core'diff --git a/packages/dashboard-core/src/lib/return-refunds.ts b/packages/dashboard-core/src/lib/return-refunds.tsindex a2aa0d9fec..72eeaf5b0a 100644--- a/packages/dashboard-core/src/lib/return-refunds.ts+++ b/packages/dashboard-core/src/lib/return-refunds.ts@@ -1,6 +1,5 @@-import { compareMoney, isDecimalString, isZeroMoney, sumMoney } from '@spree/admin-sdk'+import { compareMoney, isDecimalString, isZeroMoney, prorateMoney, sumMoney } from '@spree/core'import { formatMoney } from './formatters'-import { prorateMoney } from './money'/** True when a received return is owed nothing, so completing it moves no money. */export function returnOwesNothing(refundableTotal: string): boolean {diff --git a/packages/dashboard-core/src/lib/store-config.ts b/packages/dashboard-core/src/lib/store-config.tsindex 63b2bafb61..81c1e5936d 100644--- a/packages/dashboard-core/src/lib/store-config.ts+++ b/packages/dashboard-core/src/lib/store-config.ts@@ -1,4 +1,5 @@-import type { CurrencyCode, LocaleCode, Market, PaginatedResponse } from '@spree/admin-sdk'+import type { Market, PaginatedResponse } from '@spree/admin-sdk'+import type { CurrencyCode, LocaleCode } from '@spree/core'import { adminClient } from '../client'/**diff --git a/packages/dashboard-core/src/pages/package-types.tsx b/packages/dashboard-core/src/pages/package-types.tsxindex f6922e6f59..e5e14e38cf 100644--- a/packages/dashboard-core/src/pages/package-types.tsx+++ b/packages/dashboard-core/src/pages/package-types.tsx@@ -1,5 +1,5 @@import { zodResolver } from '@hookform/resolvers/zod'-import { DimensionUnit, WeightUnit } from '@spree/admin-sdk'+import { DimensionUnit, WeightUnit } from '@spree/core'import {Button,Field,diff --git a/packages/dashboard-core/src/products/bulk-variants-dialog.tsx b/packages/dashboard-core/src/products/bulk-variants-dialog.tsxindex f46176a698..99af0c0dc0 100644--- a/packages/dashboard-core/src/products/bulk-variants-dialog.tsx+++ b/packages/dashboard-core/src/products/bulk-variants-dialog.tsx@@ -1,4 +1,4 @@-import { DimensionUnit, WeightUnit } from '@spree/admin-sdk'+import { DimensionUnit, normalizeMoneyInput, WeightUnit } from '@spree/core'import type { ProductFormValues, VariantFormValues } from '@spree/dashboard-core'import { useCountries, useCountryDisplayName } from '@spree/dashboard-core'import {@@ -169,39 +169,24 @@ export function BulkVariantsDialog({ form, open, onOpenChange }: Props) {set(`variants.${idx}.cartons_per_pallet`, change.value)breakcase 'cartonWeight': {- if (change.value == null || change.value.trim() === '') {- set(`variants.${idx}.carton_weight`, null)- break- }- const parsed = Number(change.value.trim().replace(',', '.'))- if (!Number.isFinite(parsed) || parsed < 0) break- set(`variants.${idx}.carton_weight`, parsed)+ const parsed = readMeasure(change.value)+ if (parsed !== undefined) set(`variants.${idx}.carton_weight`, parsed)break}case 'preorderable':set(`variants.${idx}.preorderable`, change.value)breakcase 'backorderLimit': {- if (change.value == null || change.value.trim() === '') {- set(`variants.${idx}.backorder_limit`, null)- break+ const parsed = readMeasure(change.value)+ if (parsed !== undefined) {+ set(`variants.${idx}.backorder_limit`, parsed === null ? null : Math.trunc(parsed))}- const parsed = Number(change.value.trim().replace(',', '.'))- if (!Number.isFinite(parsed) || parsed < 0) break- set(`variants.${idx}.backorder_limit`, Math.trunc(parsed))break}default: {- // weight / height / width / depth — decimals. Accept a comma- // decimal (the cell ships raw input); ignore anything that doesn't- // parse to a non-negative number rather than mangling it.- if (change.value == null || change.value.trim() === '') {- set(`variants.${idx}.${change.field}`, null)- break- }- const parsed = Number(change.value.trim().replace(',', '.'))- if (!Number.isFinite(parsed) || parsed < 0) break- set(`variants.${idx}.${change.field}`, parsed)+ // weight / height / width / depth+ const parsed = readMeasure(change.value)+ if (parsed !== undefined) set(`variants.${idx}.${change.field}`, parsed)break}}@@ -291,3 +276,19 @@ export function BulkVariantsDialog({ form, open, onOpenChange }: Props) {</Dialog>)}++// Cells show numbers with a period, so they read back the same way, with+// comma grouping (`1,500`) or a lone decimal comma (`2,5`) also accepted.+const MEASURE_INPUT = /^(?:(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?|\d+,\d+)$/++/**+ * A measurement typed or pasted into a cell: `null` when cleared, `undefined`+ * when it is not a non-negative number, so the cell keeps its value rather+ * than being mangled.+ */+function readMeasure(value: string | null | undefined): number | null | undefined {+ const typed = value?.trim() ?? ''+ if (typed === '') return null+ if (!MEASURE_INPUT.test(typed)) return undefined+ return Number(normalizeMoneyInput(typed, 'en'))+}diff --git a/packages/dashboard-core/src/products/product-bulk-price-editor.tsx b/packages/dashboard-core/src/products/product-bulk-price-editor.tsxindex 32dbe3bc17..e365519589 100644--- a/packages/dashboard-core/src/products/product-bulk-price-editor.tsx+++ b/packages/dashboard-core/src/products/product-bulk-price-editor.tsx@@ -1,12 +1,10 @@-import type { CurrencyCode } from '@spree/admin-sdk'+import { type CurrencyCode, currencyParts, normalizeMoneyInput } from '@spree/core'import type { ProductFormValues, VariantPriceFormValues } from '@spree/dashboard-core'import { type BulkPriceRow, BulkPriceTable } from '@spree/dashboard-ui'import { useCallback, useMemo } from 'react'import { type UseFormReturn, useWatch } from 'react-hook-form'import { useTranslation } from 'react-i18next'import { useMoneyLocale } from '../hooks/use-money-locale'-import { currencyParts } from '../lib/currency-parts'-import { normalizeMoneyInput } from '../lib/normalize-money'import { composeOptionsText } from '../products/variants-matrix'import { useFormOptionTypes as useOptionTypes } from './use-product-form-data'diff --git a/packages/dashboard-core/src/products/product-form-cards.tsx b/packages/dashboard-core/src/products/product-form-cards.tsxindex d1c5041b06..a26df6a974 100644--- a/packages/dashboard-core/src/products/product-form-cards.tsx+++ b/packages/dashboard-core/src/products/product-form-cards.tsx@@ -13,7 +13,7 @@ import {useSortable,} from '@dnd-kit/sortable'import { CSS } from '@dnd-kit/utilities'-import type { CurrencyCode } from '@spree/admin-sdk'+import type { CurrencyCode } from '@spree/core'import type { MediaType, ProductFormValues } from '@spree/dashboard-core'import {getApiClient,diff --git a/packages/dashboard-core/src/products/product-types.ts b/packages/dashboard-core/src/products/product-types.tsindex 3a204f9fe7..6dca6f7484 100644--- a/packages/dashboard-core/src/products/product-types.ts+++ b/packages/dashboard-core/src/products/product-types.ts@@ -1,4 +1,4 @@-import type { CountryCode, CurrencyCode } from '@spree/admin-sdk'+import type { CountryCode, CurrencyCode } from '@spree/core'/*** What the shared product form reads off a product, its variants and itsdiff --git a/packages/dashboard-core/src/products/variant-edit-sheet.tsx b/packages/dashboard-core/src/products/variant-edit-sheet.tsxindex 6cdb62cedc..326a78ada9 100644--- a/packages/dashboard-core/src/products/variant-edit-sheet.tsx+++ b/packages/dashboard-core/src/products/variant-edit-sheet.tsx@@ -1,4 +1,4 @@-import { DimensionUnit, WeightUnit } from '@spree/admin-sdk'+import { DimensionUnit, WeightUnit } from '@spree/core'import type { ProductFormValues, VariantFormValues } from '@spree/dashboard-core'import { CountryCombobox, StoreDatePicker } from '@spree/dashboard-core'import {diff --git a/packages/dashboard-core/src/providers/store-provider.tsx b/packages/dashboard-core/src/providers/store-provider.tsxindex c2c3375699..e4e2d96f3f 100644--- a/packages/dashboard-core/src/providers/store-provider.tsx+++ b/packages/dashboard-core/src/providers/store-provider.tsx@@ -1,4 +1,5 @@-import type { CurrencyCode, LocaleCode, Store } from '@spree/admin-sdk'+import type { Store } from '@spree/admin-sdk'+import type { CurrencyCode, LocaleCode } from '@spree/core'import { useQuery } from '@tanstack/react-query'import { createContext, type ReactNode, useContext, useEffect, useMemo, useRef } from 'react'import { adminClient } from '../client'diff --git a/packages/dashboard-core/src/schemas/package-type.ts b/packages/dashboard-core/src/schemas/package-type.tsindex aa11de536e..9849e78e9c 100644--- a/packages/dashboard-core/src/schemas/package-type.ts+++ b/packages/dashboard-core/src/schemas/package-type.ts@@ -1,4 +1,4 @@-import { DimensionUnit, WeightUnit } from '@spree/admin-sdk'+import { DimensionUnit, WeightUnit } from '@spree/core'import { requiredMessage } from '@spree/dashboard-ui'import i18n from 'i18next'import { z } from 'zod/v4'diff --git a/packages/dashboard-ui/package.json b/packages/dashboard-ui/package.jsonindex 01b647cbdf..d14a15d971 100644--- a/packages/dashboard-ui/package.json+++ b/packages/dashboard-ui/package.json@@ -67,6 +67,7 @@"@dnd-kit/utilities": "3.2.2","@fontsource-variable/geist": "5.3.0","@fontsource-variable/geist-mono": "5.3.0",+ "@spree/core": "workspace:^","@tanstack/react-hotkeys": "^0.14.3","@tanstack/react-table": "9.3.1","@tiptap/core": "3.32.0",diff --git a/packages/dashboard-ui/src/spree/address-block.tsx b/packages/dashboard-ui/src/spree/address-block.tsxindex 4c75e16ed5..d847f370d5 100644--- a/packages/dashboard-ui/src/spree/address-block.tsx+++ b/packages/dashboard-ui/src/spree/address-block.tsx@@ -1,3 +1,4 @@+import { intlDisplayName } from '@spree/core'import { useTranslation } from 'react-i18next'/**@@ -28,15 +29,8 @@ function localizedCountryName(iso?: string | null,name?: string | null,): string | null {- if (iso) {- try {- const localized = new Intl.DisplayNames([locale, 'en'], { type: 'region' }).of(iso)- if (localized) return localized- } catch {- // Runtime without Intl.DisplayNames coverage — fall back below.- }- }- return name ?? iso ?? null+ const localized = iso ? intlDisplayName('region', locale, iso) : undefined+ return localized || (name ?? iso ?? null)}export function AddressBlock({diff --git a/packages/dashboard-ui/src/spree/calculator-summary.tsx b/packages/dashboard-ui/src/spree/calculator-summary.tsxindex 904a646b93..4c6d7ed68b 100644--- a/packages/dashboard-ui/src/spree/calculator-summary.tsx+++ b/packages/dashboard-ui/src/spree/calculator-summary.tsx@@ -13,6 +13,9 @@* Lives on the frontend (rather than as a server-rendered string) so* draft edits update the row immediately, before any save.*/++import { formatMoney, isDecimalString } from '@spree/core'+export interface CalculatorPayload {/*** Display name for the calculator, already localized by the caller — this@@ -101,7 +104,12 @@ function formatField(): string | null {if (value === null || value === undefined || value === '') return nullif (property.format === 'currency') return null- if (property.format === 'money') return formatMoney(value, currency)+ if (property.format === 'money') {+ const amount = String(value)+ return (+ formatMoney(amount, currency) || (isDecimalString(amount) ? `${amount} ${currency}` : amount)+ )+ }if (/(?:^|_)percent$/.test(key)) return `${value}%`const type = (Array.isArray(property.type) ? property.type : [property.type]).find(@@ -115,19 +123,6 @@ function formatField(return `${humanize(key)}: ${value}`}-function formatMoney(value: unknown, currency: string): string {- const amount = String(value)- if (!/^-?\d+(\.\d+)?$/.test(amount)) return amount- try {- // `Intl` reads a numeric string exactly; its ES2022 typings only list numbers.- return new Intl.NumberFormat(undefined, { style: 'currency', currency }).format(- amount as unknown as number,- )- } catch {- return `${amount} ${currency}`- }-}-function humanize(key: string): string {const spaced = key.replace(/_/g, ' ').trim()return spaced.charAt(0).toUpperCase() + spaced.slice(1)diff --git a/packages/dashboard-ui/src/spree/claim-resolve-dialog.tsx b/packages/dashboard-ui/src/spree/claim-resolve-dialog.tsxindex 17817b01b3..fed59c781d 100644--- a/packages/dashboard-ui/src/spree/claim-resolve-dialog.tsx+++ b/packages/dashboard-ui/src/spree/claim-resolve-dialog.tsx@@ -1,3 +1,4 @@+import { isPositiveMoney } from '@spree/core'import { useState } from 'react'import { useTranslation } from 'react-i18next'import { Button } from '../ui/button'@@ -92,11 +93,11 @@ export function ClaimResolveDialog({},]+ // A number input keeps `.5` as typed; the API reads only `0.5`.+ const refundAmount = amount.startsWith('.') ? `0${amount}` : amount// Refunding nothing, or replacing nothing, is what the server rejects —// say so here instead of letting the request fail.- // The amount is the canonical decimal string a number input yields, so- // "above zero" is unsigned digits with a non-zero digit among them.- const positiveAmount = /^(\d+(\.\d+)?|\.\d+)$/.test(amount) && /[1-9]/.test(amount)+ const positiveAmount = isPositiveMoney(refundAmount)const ready =(!refunding || positiveAmount) && (!sendingReplacement || chosenReplacements.length > 0)@@ -211,7 +212,7 @@ export function ClaimResolveDialog({onSubmit({resolution,refundMethod,- amount: refunding ? amount : undefined,+ amount: refunding ? refundAmount : undefined,replacementLineItemIds: chosenReplacements,})}diff --git a/packages/dashboard/e2e/post-sale.spec.ts b/packages/dashboard/e2e/post-sale.spec.tsindex dff7754372..84209e8ae2 100644--- a/packages/dashboard/e2e/post-sale.spec.ts+++ b/packages/dashboard/e2e/post-sale.spec.ts@@ -104,6 +104,39 @@ test.describe('post-sale', () => {})})+ test('resolves a claim with a refund once the amount is above zero', async ({ page }) => {+ const creds = await login(page)+ const order = await createShippedOrder(page, creds.accessToken, 1)+ await page.goto(`/${creds.store_id}/orders/${order.id}`)++ const claims = card(page, /^claims/i)+ await claims.getByRole('button', { name: /new claim/i }).click({ timeout: 15_000 })+ const dialog = page.getByRole('dialog')+ await dialog.getByRole('spinbutton', { name: new RegExp(FIXTURE_PROMO_PRODUCT) }).fill('1')+ await dialog.locator('#reason-claim-reasons').click()+ await page.getByRole('option', { name: 'Never arrived' }).click()+ await dialog.getByRole('button', { name: /new claim/i }).click()+ await expect(claims.getByText(/^open$/i)).toBeVisible({ timeout: 15_000 })++ await recordAction(page, /^claims/i, /^approve$/i)+ await expect(claims.getByText(/^approved$/i)).toBeVisible({ timeout: 15_000 })++ await recordAction(page, /^claims/i, /^resolve$/i)+ const resolve = page.getByRole('dialog')+ await expect(resolve.getByRole('heading', { name: /^resolve claim$/i })).toBeVisible()+ const amount = resolve.getByLabel(/^refund amount$/i)+ const submit = resolve.getByRole('button', { name: /^resolve$/i })++ await amount.fill('0')+ await expect(submit).toBeDisabled()+ // Typed without the leading zero, as a number field allows.+ await amount.fill('.5')+ await expect(submit).toBeEnabled()+ await submit.click()++ await expect(claims.getByText(/^resolved$/i)).toBeVisible({ timeout: 15_000 })+ })+test('lists exchanges store-wide', async ({ page }) => {const creds = await login(page)await page.goto(`/${creds.store_id}/exchanges`)diff --git a/packages/dashboard/e2e/products-variants.spec.ts b/packages/dashboard/e2e/products-variants.spec.tsindex 6224c262c6..b8e1c060b2 100644--- a/packages/dashboard/e2e/products-variants.spec.ts+++ b/packages/dashboard/e2e/products-variants.spec.ts@@ -121,4 +121,62 @@ test.describe('product variants', () => {await expect(reopened.getByLabel(/^weight$/i)).toHaveValue('1.5')await expect(reopened.locator('[id$="-dim-unit"]')).toHaveText('ft')})++ test('reads weights typed into the bulk editor with grouping and a decimal comma', async ({+ page,+ }) => {+ const creds = await login(page)++ const colorLabel = await seedOptionType(page, creds.store_id, 'color', ['red', 'blue'])++ const productName = `E2E Bulk Weights ${Date.now()}`+ await createProduct(page, creds.store_id, productName)+ await addOptionToVariants(page, colorLabel, ['Red', 'Blue'])++ const variantsCard = variantsCardLocator(page)+ await variantsCard.getByRole('button', { name: /^bulk edit$/i }).click()+ const grid = page.getByRole('dialog')++ // A spreadsheet cell is read-only until double-clicked.+ for (const [variant, typed] of [+ ['Red', '1,500'],+ ['Blue', '2,5'],+ ]) {+ const cell = grid.getByLabel(new RegExp(`^weight — .*\\b${variant}$`, 'i'))+ await cell.dblclick()+ await cell.fill(typed)+ await cell.press('Enter')+ }+ await expect(grid.getByLabel(/^weight — .*\bred$/i)).toHaveValue('1500')+ await expect(grid.getByLabel(/^weight — .*\bblue$/i)).toHaveValue('2.5')++ // A value that is not a number in either format leaves the cell as it was.+ const red = grid.getByLabel(/^weight — .*\bred$/i)+ await red.dblclick()+ await red.fill('1.234,5')+ await red.press('Enter')+ await expect(red).toHaveValue('1500')++ await grid.getByRole('button', { name: /^done$/i }).click()+ await expect(grid).toBeHidden()++ await page.getByRole('button', { name: /save product/i }).click()+ await expect(page.getByRole('button', { name: /save product/i })).toBeDisabled({+ timeout: 30_000,+ })++ await page.reload()+ for (const [variant, weight] of [+ ['red', '1500'],+ ['blue', '2.5'],+ ]) {+ await variantsCard+ .getByRole('button', { name: new RegExp(`^edit .*\\b${variant}$`, 'i') })+ .click()+ const sheet = page.getByRole('dialog')+ await expect(sheet.getByLabel(/^weight$/i)).toHaveValue(weight)+ await sheet.getByRole('button', { name: /^done$/i }).click()+ await expect(sheet).toBeHidden()+ }+ })})diff --git a/packages/dashboard/e2e/tax-rates.spec.ts b/packages/dashboard/e2e/tax-rates.spec.tsindex 0058d2ab9d..69bf185884 100644--- a/packages/dashboard/e2e/tax-rates.spec.ts+++ b/packages/dashboard/e2e/tax-rates.spec.ts@@ -84,7 +84,7 @@ test.describe('tax rates', () => {await expect(page.locator('#rate_percent')).toHaveValue('7.125', { timeout: 15_000 })})- test('refuses a fourth decimal and a blank rate without saving', async ({ page }) => {+ test('refuses a fourth decimal, a negative and a blank rate without saving', async ({ page }) => {const creds = await login(page)await gotoIndex(page, TAX_RATES_PATH(creds.store_id), CTA)@@ -95,6 +95,10 @@ test.describe('tax rates', () => {await expect(rateField).toHaveAttribute('aria-invalid', 'true')await expect(page.getByText(/at most 3 decimal places/i)).toBeVisible()+ await rateField.fill('-5')+ await page.getByRole('button', { name: /create tax rate/i }).click()+ await expect(rateField).toHaveAttribute('aria-invalid', 'true')+await rateField.fill('')await page.getByRole('button', { name: /create tax rate/i }).click()await expect(rateField).toHaveAttribute('aria-invalid', 'true')diff --git a/packages/dashboard/package.json b/packages/dashboard/package.jsonindex 11524f5d25..21274b65db 100644--- a/packages/dashboard/package.json+++ b/packages/dashboard/package.json@@ -65,6 +65,7 @@"@fontsource-variable/geist": "^5.3.0","@fontsource-variable/geist-mono": "^5.3.0","@hookform/resolvers": "^5.2.2",+ "@spree/core": "workspace:^","@tanstack/react-hotkeys": "^0.14.3","@tanstack/react-table": "^9.3.1","@tanstack/router-plugin": "^1.168.46",diff --git a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsxindex a647ff1747..d556cd89dc 100644--- a/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx+++ b/packages/dashboard/src/components/spree/bulk-price-editor/bulk-price-editor.tsx@@ -1,4 +1,5 @@-import type { CurrencyCode, PriceBulkUpsertRowParams } from '@spree/admin-sdk'+import type { PriceBulkUpsertRowParams } from '@spree/admin-sdk'+import type { CurrencyCode } from '@spree/core'import {adminClient,currencyParts,diff --git a/packages/dashboard/src/components/spree/customers/customer-lifetime-stats-card.tsx b/packages/dashboard/src/components/spree/customers/customer-lifetime-stats-card.tsxindex 29713ef391..af75cdb4fb 100644--- a/packages/dashboard/src/components/spree/customers/customer-lifetime-stats-card.tsx+++ b/packages/dashboard/src/components/spree/customers/customer-lifetime-stats-card.tsx@@ -1,4 +1,5 @@-import { type Customer, decimalPlaces } from '@spree/admin-sdk'+import type { Customer } from '@spree/admin-sdk'+import { prorateMoney } from '@spree/core'import { formatAmount, isPositiveMoney, useMoneyLocale, useStore } from '@spree/dashboard-core'import { Item, ItemContent, ItemDescription, ItemTitle, RelativeTime } from '@spree/dashboard-ui'import type { ReactNode } from 'react'@@ -10,13 +11,14 @@ export function CustomerLifetimeStatsCard({ customer }: { customer: Customer })const { defaultCurrency } = useStore()const orders = customer.orders_count ?? 0const totalSpent = customer.total_spent- // Dividing needs a number; the average is only displayed, never sent or compared.- const averageForDisplay =- orders > 0 && isPositiveMoney(totalSpent)- ? (Number(totalSpent) / orders).toFixed(decimalPlaces(defaultCurrency))- : nullconst aovDisplay =- averageForDisplay === null ? '—' : formatAmount(averageForDisplay, defaultCurrency, moneyLocale)+ orders > 0 && isPositiveMoney(totalSpent)+ ? formatAmount(+ prorateMoney(totalSpent, 1, orders, defaultCurrency),+ defaultCurrency,+ moneyLocale,+ )+ : '—'return (<div className="grid grid-cols-2 gap-3 lg:grid-cols-5">diff --git a/packages/dashboard/src/components/spree/orders/fulfillment-edit-dialog.tsx b/packages/dashboard/src/components/spree/orders/fulfillment-edit-dialog.tsxindex 7b73cdaaa4..e3f3959f9a 100644--- a/packages/dashboard/src/components/spree/orders/fulfillment-edit-dialog.tsx+++ b/packages/dashboard/src/components/spree/orders/fulfillment-edit-dialog.tsx@@ -1,4 +1,5 @@-import { type Fulfillment, isZeroMoney, type Order, SpreeError } from '@spree/admin-sdk'+import { type Fulfillment, type Order, SpreeError } from '@spree/admin-sdk'+import { isZeroMoney } from '@spree/core'import { formatAmount, useMoneyLocale, useStockLocations } from '@spree/dashboard-core'import { FulfillmentEditDialog as SharedFulfillmentEditDialog } from '@spree/dashboard-ui'import { useState } from 'react'diff --git a/packages/dashboard/src/components/spree/orders/fulfillment-label-upload-dialog.tsx b/packages/dashboard/src/components/spree/orders/fulfillment-label-upload-dialog.tsxindex d799792968..57e1eca772 100644--- a/packages/dashboard/src/components/spree/orders/fulfillment-label-upload-dialog.tsx+++ b/packages/dashboard/src/components/spree/orders/fulfillment-label-upload-dialog.tsx@@ -1,5 +1,5 @@import { zodResolver } from '@hookform/resolvers/zod'-import type { CurrencyCode } from '@spree/admin-sdk'+import type { CurrencyCode } from '@spree/core'import {EMPTY_FILE_UPLOAD_VALUE,FileUploadField,diff --git a/packages/dashboard/src/components/spree/orders/order-adjustments-cards.tsx b/packages/dashboard/src/components/spree/orders/order-adjustments-cards.tsxindex f8515bd373..704dc0a7f8 100644--- a/packages/dashboard/src/components/spree/orders/order-adjustments-cards.tsx+++ b/packages/dashboard/src/components/spree/orders/order-adjustments-cards.tsx@@ -1,13 +1,5 @@-import {- compareMoney,- type Discount,- type Fee,- type FeeCreateParams,- isDecimalString,- isZeroMoney,- type Order,- sumMoney,-} from '@spree/admin-sdk'+import type { Discount, Fee, FeeCreateParams, Order } from '@spree/admin-sdk'+import { compareMoney, isDecimalString, isZeroMoney, sumMoney } from '@spree/core'import { adminClient, currencyParts, formatMoney, Money, percentOf } from '@spree/dashboard-core'import {Badge,diff --git a/packages/dashboard/src/components/spree/orders/order-discounts-sidebar-card.tsx b/packages/dashboard/src/components/spree/orders/order-discounts-sidebar-card.tsxindex 0119485d43..d7808e6987 100644--- a/packages/dashboard/src/components/spree/orders/order-discounts-sidebar-card.tsx+++ b/packages/dashboard/src/components/spree/orders/order-discounts-sidebar-card.tsx@@ -1,5 +1,5 @@import type { Order } from '@spree/admin-sdk'-import { isZeroMoney } from '@spree/admin-sdk'+import { isZeroMoney } from '@spree/core'import { adminClient, Money, useResourceKey } from '@spree/dashboard-core'import {Button,diff --git a/packages/dashboard/src/components/spree/orders/order-edit-items-table.tsx b/packages/dashboard/src/components/spree/orders/order-edit-items-table.tsxindex 7b3b6da593..80f71e3105 100644--- a/packages/dashboard/src/components/spree/orders/order-edit-items-table.tsx+++ b/packages/dashboard/src/components/spree/orders/order-edit-items-table.tsx@@ -1,4 +1,4 @@-import { compareMoney, isDecimalString, multiplyMoney } from '@spree/admin-sdk'+import { compareMoney, isDecimalString, multiplyMoney } from '@spree/core'import { Money } from '@spree/dashboard-core'import {Badge,diff --git a/packages/dashboard/src/components/spree/orders/order-summary-card.tsx b/packages/dashboard/src/components/spree/orders/order-summary-card.tsxindex 2bebffffb8..e42d635f8a 100644--- a/packages/dashboard/src/components/spree/orders/order-summary-card.tsx+++ b/packages/dashboard/src/components/spree/orders/order-summary-card.tsx@@ -1,5 +1,5 @@import type { Order } from '@spree/admin-sdk'-import { isZeroMoney } from '@spree/admin-sdk'+import { isZeroMoney } from '@spree/core'import { isPositiveMoney, LocaleLabel, Money, useStore } from '@spree/dashboard-core'import { Card, CardHeader, CardTitle, cn, Separator } from '@spree/dashboard-ui'import { Link } from '@tanstack/react-router'diff --git a/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsx b/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsxindex 9fd626e421..a93d83c140 100644--- a/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsx+++ b/packages/dashboard/src/components/spree/post-sale-create-dialogs.tsx@@ -1,5 +1,5 @@import type { Claim, Order, Variant } from '@spree/admin-sdk'-import { sumMoney } from '@spree/admin-sdk'+import { sumMoney } from '@spree/core'import {adminClient,currencyParts,diff --git a/packages/dashboard/src/components/spree/purchase-order-form.tsx b/packages/dashboard/src/components/spree/purchase-order-form.tsxindex 790aa38b6f..d07ebd5727 100644--- a/packages/dashboard/src/components/spree/purchase-order-form.tsx+++ b/packages/dashboard/src/components/spree/purchase-order-form.tsx@@ -1,5 +1,5 @@-import type { CurrencyCode, Supplier } from '@spree/admin-sdk'-import { isDecimalString } from '@spree/admin-sdk'+import type { Supplier } from '@spree/admin-sdk'+import { type CurrencyCode, isDecimalString } from '@spree/core'import {CurrencySelect,PageHeader,diff --git a/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx b/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsxindex 88b2844627..c57ad4ee15 100644--- a/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx+++ b/packages/dashboard/src/components/spree/shipping/delivery-method-sheet.tsx@@ -1,6 +1,6 @@import { zodResolver } from '@hookform/resolvers/zod'import type { DeliveryProfile, DeliveryZone } from '@spree/admin-sdk'-import { isDecimalString, isZeroMoney } from '@spree/admin-sdk'+import { isDecimalString, isZeroMoney } from '@spree/core'import { mapSpreeErrorsToForm } from '@spree/dashboard-core'import {Button,diff --git a/packages/dashboard/src/components/spree/shipping/delivery-zone-region-picker.tsx b/packages/dashboard/src/components/spree/shipping/delivery-zone-region-picker.tsxindex dadab479d7..6356bbe0e1 100644--- a/packages/dashboard/src/components/spree/shipping/delivery-zone-region-picker.tsx+++ b/packages/dashboard/src/components/spree/shipping/delivery-zone-region-picker.tsx@@ -1,4 +1,5 @@-import type { CountryCode, DeliveryZone } from '@spree/admin-sdk'+import type { DeliveryZone } from '@spree/admin-sdk'+import type { CountryCode } from '@spree/core'import { useCountryDisplayName, useSortByCountryName, useStore } from '@spree/dashboard-core'import {Button,diff --git a/packages/dashboard/src/components/spree/shipping/delivery-zone-selection.ts b/packages/dashboard/src/components/spree/shipping/delivery-zone-selection.tsindex 255664eff8..d90c4b9230 100644--- a/packages/dashboard/src/components/spree/shipping/delivery-zone-selection.ts+++ b/packages/dashboard/src/components/spree/shipping/delivery-zone-selection.ts@@ -1,4 +1,5 @@-import type { CountryCode, DeliveryZone } from '@spree/admin-sdk'+import type { DeliveryZone } from '@spree/admin-sdk'+import type { CountryCode } from '@spree/core'import type { DeliveryZoneMemberValues } from '../../../schemas/delivery-zone'/**diff --git a/packages/dashboard/src/lib/commission-line-rate-label.ts b/packages/dashboard/src/lib/commission-line-rate-label.tsindex 6a43bc8979..ba5b80cde2 100644--- a/packages/dashboard/src/lib/commission-line-rate-label.ts+++ b/packages/dashboard/src/lib/commission-line-rate-label.ts@@ -1,4 +1,5 @@-import { type CommissionLine, isDecimalString, type Order } from '@spree/admin-sdk'+import type { CommissionLine, Order } from '@spree/admin-sdk'+import { isDecimalString } from '@spree/core'import { formatAmount, prorateMoney } from '@spree/dashboard-core'import i18n, { type TFunction } from 'i18next'diff --git a/packages/dashboard/src/lib/delivery-method-summary.ts b/packages/dashboard/src/lib/delivery-method-summary.tsindex c3673ac382..e266007b62 100644--- a/packages/dashboard/src/lib/delivery-method-summary.ts+++ b/packages/dashboard/src/lib/delivery-method-summary.ts@@ -1,4 +1,5 @@-import { type DeliveryMethodRule, isDecimalString, isZeroMoney } from '@spree/admin-sdk'+import type { DeliveryMethodRule } from '@spree/admin-sdk'+import { isDecimalString, isZeroMoney } from '@spree/core'import { formatAmount } from '@spree/dashboard-core'import type { TFunction } from 'i18next'diff --git a/packages/dashboard/src/lib/packing-slip.ts b/packages/dashboard/src/lib/packing-slip.tsindex 001889d439..b65a122441 100644--- a/packages/dashboard/src/lib/packing-slip.ts+++ b/packages/dashboard/src/lib/packing-slip.ts@@ -1,12 +1,5 @@-import {- type Fulfillment,- isDecimalString,- isZeroMoney,- type LineItem,- multiplyMoney,- type Order,- sumMoney,-} from '@spree/admin-sdk'+import type { Fulfillment, LineItem, Order } from '@spree/admin-sdk'+import { isDecimalString, isZeroMoney, multiplyMoney, sumMoney } from '@spree/core'import { formatAmount, fulfillmentItemRows } from '@spree/dashboard-core'import type { TFunction } from 'i18next'import i18n from 'i18next'diff --git a/packages/dashboard/src/lib/tax-line-groups.ts b/packages/dashboard/src/lib/tax-line-groups.tsindex 47c5af3109..dfea015325 100644--- a/packages/dashboard/src/lib/tax-line-groups.ts+++ b/packages/dashboard/src/lib/tax-line-groups.ts@@ -1,4 +1,4 @@-import { isDecimalString, sumMoney } from '@spree/admin-sdk'+import { isDecimalString, sumMoney } from '@spree/core'/*** How tax rows are shown on an order: one rate charged on many linesdiff --git a/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsxindex cc2be68ace..4ec9e31a92 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/loyalty/store-credits.tsx@@ -1,5 +1,5 @@import type { StoreCredit, StoreCreditCurrencyTotal } from '@spree/admin-sdk'-import { isZeroMoney } from '@spree/admin-sdk'+import { isZeroMoney } from '@spree/core'import {Can,formatAmount,diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsxindex 9f5e6acb7d..2ccdec4a0d 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/orders/$orderId/edit.tsx@@ -1,5 +1,6 @@import { zodResolver } from '@hookform/resolvers/zod'-import { compareMoney, isZeroMoney, type Order, SpreeError, type Variant } from '@spree/admin-sdk'+import { type Order, SpreeError, type Variant } from '@spree/admin-sdk'+import { compareMoney, isZeroMoney } from '@spree/core'import {adminClient,GONE_STATUSES,diff --git a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsxindex bf4831ae3d..e6a6a80eab 100644--- a/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx+++ b/packages/dashboard/src/routes/_authenticated/$storeId/settings/store.tsx@@ -1,5 +1,6 @@import { zodResolver } from '@hookform/resolvers/zod'import { SpreeError, type Store, type StoreDataSourceProvider } from '@spree/admin-sdk'+import { UNIT_SYSTEM_WEIGHT_UNITS, UNIT_SYSTEMS } from '@spree/core'import {extensionFormValues,extensionSubmitValues,@@ -67,8 +68,6 @@ import {STOREFRONT_ACCESS_LEVELS,type StoreSettingsFormValues,storeSettingsFormSchema,- UNIT_SYSTEMS,- WEIGHT_UNITS,} from '../../../../schemas/store'export const Route = createFileRoute('/_authenticated/$storeId/settings/store')({@@ -210,7 +209,7 @@ function StoreSettingsForm({ store }: { store: Store }) {// that system so the form never holds an inconsistent pair.const unitSystem = form.watch('unit_system')useEffect(() => {- const validUnits = WEIGHT_UNITS[unitSystem] ?? []+ const validUnits = UNIT_SYSTEM_WEIGHT_UNITS[unitSystem] ?? []const current = form.getValues('weight_unit')if (current && !validUnits.includes(current)) {form.setValue('weight_unit', validUnits[0] ?? '', { shouldDirty: true })@@ -305,7 +304,7 @@ function StoreSettingsForm({ store }: { store: Store }) {)const weightOptions = useMemo(() =>- (WEIGHT_UNITS[unitSystem] ?? WEIGHT_UNITS.metric).map((value) => ({+ (UNIT_SYSTEM_WEIGHT_UNITS[unitSystem] ?? UNIT_SYSTEM_WEIGHT_UNITS.metric).map((value) => ({value,label: t(`admin.store.weight_units.${value}`),})),diff --git a/packages/dashboard/src/schemas/catalog.ts b/packages/dashboard/src/schemas/catalog.tsindex 0f647c8fac..93557210ff 100644--- a/packages/dashboard/src/schemas/catalog.ts+++ b/packages/dashboard/src/schemas/catalog.ts@@ -1,5 +1,5 @@-import type { CatalogCreateParams, CurrencyCode, PriceList } from '@spree/admin-sdk'-import { compareMoney, negateMoney } from '@spree/admin-sdk'+import type { CatalogCreateParams, PriceList } from '@spree/admin-sdk'+import { type CurrencyCode, compareMoney, negateMoney } from '@spree/core'import {blankToNull,isPositiveMoney,diff --git a/packages/dashboard/src/schemas/commission-rate.ts b/packages/dashboard/src/schemas/commission-rate.tsindex 9afaab1e1e..eef37f38b4 100644--- a/packages/dashboard/src/schemas/commission-rate.ts+++ b/packages/dashboard/src/schemas/commission-rate.ts@@ -3,7 +3,7 @@ import type {CommissionRateCreateParams,CommissionRateUpdateParams,} from '@spree/admin-sdk'-import { compareMoney, isDecimalString } from '@spree/admin-sdk'+import { compareMoney, isDecimalString } from '@spree/core'import { blankToNull, fractionToPercent, i18n, percentToFraction } from '@spree/dashboard-core'import { requiredMessage } from '@spree/dashboard-ui'import { z } from 'zod/v4'diff --git a/packages/dashboard/src/schemas/market.ts b/packages/dashboard/src/schemas/market.tsindex 5d2fb53ee7..0fa712e809 100644--- a/packages/dashboard/src/schemas/market.ts+++ b/packages/dashboard/src/schemas/market.ts@@ -1,4 +1,5 @@-import type { LocaleCode, MarketCreateParams, MarketUpdateParams } from '@spree/admin-sdk'+import type { MarketCreateParams, MarketUpdateParams } from '@spree/admin-sdk'+import type { LocaleCode } from '@spree/core'import { countryCodeSchema, currencyCodeSchema } from '@spree/dashboard-core'import { requiredMessage } from '@spree/dashboard-ui'import type { DefaultValues } from 'react-hook-form'diff --git a/packages/dashboard/src/schemas/marketplace.ts b/packages/dashboard/src/schemas/marketplace.tsindex b82dee626c..c498a2490f 100644--- a/packages/dashboard/src/schemas/marketplace.ts+++ b/packages/dashboard/src/schemas/marketplace.ts@@ -1,4 +1,4 @@-import { compareMoney, isDecimalString } from '@spree/admin-sdk'+import { compareMoney, isDecimalString } from '@spree/core'import { z } from 'zod'const nonNegativeDecimal = zdiff --git a/packages/dashboard/src/schemas/order.ts b/packages/dashboard/src/schemas/order.tsindex 5c724b1d5c..8db7e82028 100644--- a/packages/dashboard/src/schemas/order.ts+++ b/packages/dashboard/src/schemas/order.ts@@ -1,10 +1,5 @@-import {- isDecimalString,- type LineItem,- multiplyMoney,- type OrderUpdateParams,- sumMoney,-} from '@spree/admin-sdk'+import type { LineItem, OrderUpdateParams } from '@spree/admin-sdk'+import { isDecimalString, multiplyMoney, sumMoney } from '@spree/core'import { fulfilledQuantities, type GroupableFulfillment, i18n } from '@spree/dashboard-core'import { z } from 'zod/v4'@@ -108,7 +103,11 @@ export const orderEditItemSchema = z.superRefine((item, ctx) => {// Neither case sends a price, so refusing the form over one would block a// legitimate removal.- if (!item.removed && !item.revert_price && !/^\d+(\.\d+)?$/.test(item.price)) {+ if (+ !item.removed &&+ !item.revert_price &&+ !(isDecimalString(item.price) && !item.price.startsWith('-'))+ ) {ctx.addIssue({code: 'custom',path: ['price'],diff --git a/packages/dashboard/src/schemas/price-list.ts b/packages/dashboard/src/schemas/price-list.tsindex bec04e1aad..0862b48299 100644--- a/packages/dashboard/src/schemas/price-list.ts+++ b/packages/dashboard/src/schemas/price-list.ts@@ -4,7 +4,7 @@ import type {PriceListUpdateParams,PriceRule,} from '@spree/admin-sdk'-import { isDecimalString, isZeroMoney } from '@spree/admin-sdk'+import { isDecimalString, isZeroMoney } from '@spree/core'import {blankToNull,defaultPreferences,diff --git a/packages/dashboard/src/schemas/store.ts b/packages/dashboard/src/schemas/store.tsindex 0333f40051..6f2bfaf61d 100644--- a/packages/dashboard/src/schemas/store.ts+++ b/packages/dashboard/src/schemas/store.ts@@ -1,16 +1,7 @@-import { WeightUnit } from '@spree/admin-sdk'+import { WeightUnit } from '@spree/core'import { requiredMessage } from '@spree/dashboard-ui'import { z } from 'zod/v4'-// Labels live in `en.json` under `admin.store.unit_systems.*` and-// `admin.store.weight_units.*`. Consumers translate at render time.-export type UnitSystem = 'metric' | 'imperial'-export const UNIT_SYSTEMS: readonly UnitSystem[] = ['metric', 'imperial']-export const WEIGHT_UNITS: Record<UnitSystem, readonly WeightUnit[]> = {- metric: ['kg', 'g'],- imperial: ['lb', 'oz'],-}-// Store-wide storefront posture. Unlike the channel field there is no blank// "inherit" option — the store is the terminal fallback in the resolution// chain, so it always holds a concrete value. Labels live in `en.json` underdiff --git a/packages/dashboard/src/schemas/tax-rate.ts b/packages/dashboard/src/schemas/tax-rate.tsindex 5cc7c7d450..f00e56c16d 100644--- a/packages/dashboard/src/schemas/tax-rate.ts+++ b/packages/dashboard/src/schemas/tax-rate.ts@@ -1,4 +1,5 @@-import { compareMoney, isDecimalString, type TaxRateCreateParams } from '@spree/admin-sdk'+import type { TaxRateCreateParams } from '@spree/admin-sdk'+import { compareMoney, isDecimalString } from '@spree/core'import { blankToNull, countryCodeSchema } from '@spree/dashboard-core'import { decimalPlacesMessage, requiredMessage } from '@spree/dashboard-ui'import { z } from 'zod/v4'@@ -8,7 +9,9 @@ export const taxRateFormSchema = z.object({// The merchant types a percentage (20); the API converts it to the fraction it stores.rate_percent: z.string()- .regex(/^\d+(\.\d+)?$/, { error: requiredMessage('tax_rate.amount') })+ .refine((value) => isDecimalString(value) && !value.startsWith('-'), {+ error: requiredMessage('tax_rate.amount'),+ })// Stored as a fraction to five decimals, so a percentage keeps three..refine((value) => (value.split('.')[1] ?? '').length <= 3, {error: decimalPlacesMessage('tax_rate.amount', 3),diff --git a/packages/sdk-core/package.json b/packages/sdk-core/package.jsonindex ace37b5ee1..b7729a658c 100644--- a/packages/sdk-core/package.json+++ b/packages/sdk-core/package.json@@ -33,6 +33,7 @@"clean": "rm -rf dist"},"devDependencies": {+ "@spree/core": "workspace:*","@types/spark-md5": "^3.0.5","spark-md5": "^3.0.2","tsup": "^9.0.0",diff --git a/packages/sdk-core/src/filter-types.ts b/packages/sdk-core/src/filter-types.tsindex 76eda182ba..8222d56fcd 100644--- a/packages/sdk-core/src/filter-types.ts+++ b/packages/sdk-core/src/filter-types.ts@@ -4,7 +4,7 @@// tables the Ransack allowlists produce, so the types say exactly what the API// accepts.-import { FILTER_PREDICATES } from './filters'+import { FILTER_PREDICATES } from '@spree/core'const PACKAGE_HEADER ='// This file is auto-generated from the filter tables in docs/api-reference by `pnpm generate:filters`. Do not edit directly.\n'diff --git a/packages/sdk-core/src/index.ts b/packages/sdk-core/src/index.tsindex 90c90e5a27..3574990fdd 100644--- a/packages/sdk-core/src/index.ts+++ b/packages/sdk-core/src/index.ts@@ -1,42 +1,10 @@-// Request infrastructure--// Code lists-export {- CountryCode,- CurrencyCode,- DimensionUnit,- LocaleCode,- WeightUnit,-} from './code-lists.generated'+// Universal code, re-exported so every SDK can offer it+export * from '@spree/core'export type { FilterSpec } from './filter-types'export { renderAppFilterTypes, renderFilterTypes } from './filter-types'-export type {- BooleanFilters,- CodeFilters,- CustomFieldValueFilters,- EnumFilters,- IdFilters,- OrFilters,- Prefixed,- RangeFilters,- SortKey,- TextFilters,-} from './filters'export type { ResolvedRetryConfig } from './helpers'// Helpersexport { getParams, resolveRetryConfig } from './helpers'-// Money-export {- compareMoney,- decimalPlaces,- formatMoney,- isDecimalString,- isZeroMoney,- multiplyMoney,- negateMoney,- subtractMoney,- sumMoney,-} from './money'// Paramsexport { transformListParams } from './params'export type {diff --git a/packages/sdk-core/tsconfig.json b/packages/sdk-core/tsconfig.jsonindex ca4102418d..b723ec5365 100644--- a/packages/sdk-core/tsconfig.json+++ b/packages/sdk-core/tsconfig.json@@ -3,6 +3,7 @@"target": "ES2022","module": "ESNext","moduleResolution": "bundler",+ "customConditions": ["@spree/source"],"lib": ["ES2022", "DOM"],"ignoreDeprecations": "6.0","strict": true,diff --git a/packages/sdk-core/tsup.config.ts b/packages/sdk-core/tsup.config.tsindex 9a9454400c..753063576e 100644--- a/packages/sdk-core/tsup.config.ts+++ b/packages/sdk-core/tsup.config.ts@@ -5,7 +5,9 @@ export default defineConfig({index: 'src/index.ts',},format: ['cjs', 'esm'],- dts: true,+ // Inlined, so the SDKs that bundle this package stay self-contained.+ dts: { resolve: ['@spree/core'] },+ noExternal: ['@spree/core'],splitting: false,sourcemap: true,clean: true,diff --git a/packages/sdk/package.json b/packages/sdk/package.jsonindex 2e95720d14..eafa84645a 100644--- a/packages/sdk/package.json+++ b/packages/sdk/package.json@@ -55,9 +55,8 @@],"scripts": {"generate:zod": "tsx ../sdk-core/scripts/generate-zod.ts",- "generate:filters": "tsx ../sdk-core/scripts/generate-filters.ts store",+ "generate:filters": "tsx --conditions=@spree/source ../sdk-core/scripts/generate-filters.ts store","generate:params": "tsx ../sdk-core/scripts/generate-params.ts store",- "generate:code-lists": "tsx ../sdk-core/scripts/generate-code-lists.ts","build": "tsup","dev": "tsup --watch","console": "tsx console.ts",diff --git a/packages/sdk/tests/core-exports.test.ts b/packages/sdk/tests/core-exports.test.tsnew file mode 100644index 0000000000..99f314c76c--- /dev/null+++ b/packages/sdk/tests/core-exports.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from 'vitest'+import * as sdk from '../src'++// The code lists and money helpers live in @spree/core; clients import them+// from the SDK, so the SDK has to keep offering every one of them.+describe('@spree/core exports', () => {+ it.each([+ 'CountryCode',+ 'CurrencyCode',+ 'DimensionUnit',+ 'LocaleCode',+ 'WeightUnit',+ 'compareMoney',+ 'decimalPlaces',+ 'formatMoney',+ 'isDecimalString',+ 'isZeroMoney',+ 'multiplyMoney',+ 'negateMoney',+ 'subtractMoney',+ 'sumMoney',+ ])('offers %s', (name) => {+ expect(sdk).toHaveProperty(name)+ })+})diff --git a/packages/seller-dashboard/package.json b/packages/seller-dashboard/package.jsonindex af5ef8238f..9c3310d49c 100644--- a/packages/seller-dashboard/package.json+++ b/packages/seller-dashboard/package.json@@ -48,6 +48,7 @@"@dnd-kit/core": "^6.3.1","@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2",+ "@spree/core": "workspace:^","@spree/seller-sdk": "workspace:*","@tanstack/router-plugin": "^1.168.46","@tanstack/virtual-file-routes": "^1.162.0",diff --git a/packages/seller-dashboard/src/components/orders/fulfillment-edit-dialog.tsx b/packages/seller-dashboard/src/components/orders/fulfillment-edit-dialog.tsxindex c1e1b18864..f9437e5eeb 100644--- a/packages/seller-dashboard/src/components/orders/fulfillment-edit-dialog.tsx+++ b/packages/seller-dashboard/src/components/orders/fulfillment-edit-dialog.tsx@@ -1,6 +1,7 @@+import { isZeroMoney } from '@spree/core'import { formatMoney, useMoneyLocale } from '@spree/dashboard-core'import { FulfillmentEditDialog as SharedFulfillmentEditDialog } from '@spree/dashboard-ui'-import { type Fulfillment, isZeroMoney, SpreeError } from '@spree/seller-sdk'+import { type Fulfillment, SpreeError } from '@spree/seller-sdk'import { useState } from 'react'import { useTranslation } from 'react-i18next'import { useFulfillmentActions } from '../../hooks/use-fulfillments'diff --git a/packages/seller-dashboard/src/components/orders/fulfillment-label-upload-dialog.tsx b/packages/seller-dashboard/src/components/orders/fulfillment-label-upload-dialog.tsxindex 173a8944f0..0f91f4f192 100644--- a/packages/seller-dashboard/src/components/orders/fulfillment-label-upload-dialog.tsx+++ b/packages/seller-dashboard/src/components/orders/fulfillment-label-upload-dialog.tsx@@ -1,4 +1,5 @@import { zodResolver } from '@hookform/resolvers/zod'+import type { CurrencyCode } from '@spree/core'import {EMPTY_FILE_UPLOAD_VALUE,FileUploadField,@@ -9,7 +10,6 @@ import {mapSpreeErrorsToForm,} from '@spree/dashboard-core'import { LabelUploadDialog } from '@spree/dashboard-ui'-import type { CurrencyCode } from '@spree/seller-sdk'import { useState } from 'react'import { useForm } from 'react-hook-form'import { useTranslation } from 'react-i18next'diff --git a/packages/seller-dashboard/src/components/orders/order-cards.tsx b/packages/seller-dashboard/src/components/orders/order-cards.tsxindex ff2b4b7863..fc63c4b2c8 100644--- a/packages/seller-dashboard/src/components/orders/order-cards.tsx+++ b/packages/seller-dashboard/src/components/orders/order-cards.tsx@@ -1,3 +1,4 @@+import { isZeroMoney } from '@spree/core'import {AddressFormDialog,formatMoney,@@ -21,7 +22,6 @@ import {} from '@spree/dashboard-ui'import { EllipsisVerticalIcon, PencilIcon } from '@spree/dashboard-ui/icons'import type { Order, OrderAddressParams } from '@spree/seller-sdk'-import { isZeroMoney } from '@spree/seller-sdk'import { type ReactNode, useState } from 'react'import { useTranslation } from 'react-i18next'import { sellerClient } from '../../api-client'diff --git a/packages/seller-dashboard/src/components/orders/post-sale-cards.tsx b/packages/seller-dashboard/src/components/orders/post-sale-cards.tsxindex 52a641ead0..c5870202cd 100644--- a/packages/seller-dashboard/src/components/orders/post-sale-cards.tsx+++ b/packages/seller-dashboard/src/components/orders/post-sale-cards.tsx@@ -1,3 +1,4 @@+import { sumMoney } from '@spree/core'import { currencyParts, formatMoney, isPositiveMoney, useMoneyLocale } from '@spree/dashboard-core'import {Button,@@ -23,7 +24,6 @@ import {ShieldAlertIcon,} from '@spree/dashboard-ui/icons'import type { Claim, Order } from '@spree/seller-sdk'-import { sumMoney } from '@spree/seller-sdk'import i18n from 'i18next'import { useState } from 'react'import { useTranslation } from 'react-i18next'diff --git a/packages/seller-dashboard/src/hooks/use-fulfillments.ts b/packages/seller-dashboard/src/hooks/use-fulfillments.tsindex d291f14a30..b02399bef0 100644--- a/packages/seller-dashboard/src/hooks/use-fulfillments.ts+++ b/packages/seller-dashboard/src/hooks/use-fulfillments.ts@@ -1,6 +1,6 @@+import type { CurrencyCode } from '@spree/core'import { useResourceKeyBuilder } from '@spree/dashboard-core'import { toastManager } from '@spree/dashboard-ui'-import type { CurrencyCode } from '@spree/seller-sdk'import { useMutation, useQueryClient } from '@tanstack/react-query'import { sellerClient } from '../api-client'diff --git a/packages/seller-sdk/package.json b/packages/seller-sdk/package.jsonindex f4d5c1dbaa..53c4017994 100644--- a/packages/seller-sdk/package.json+++ b/packages/seller-sdk/package.json@@ -45,7 +45,7 @@],"scripts": {"generate:zod": "tsx ../sdk-core/scripts/generate-zod.ts",- "generate:filters": "tsx ../sdk-core/scripts/generate-filters.ts seller",+ "generate:filters": "tsx --conditions=@spree/source ../sdk-core/scripts/generate-filters.ts seller","generate:params": "tsx ../sdk-core/scripts/generate-params.ts seller","build": "tsup","dev": "tsup --watch",diff --git a/packages/seller-sdk/tests/core-exports.test.ts b/packages/seller-sdk/tests/core-exports.test.tsnew file mode 100644index 0000000000..99f314c76c--- /dev/null+++ b/packages/seller-sdk/tests/core-exports.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from 'vitest'+import * as sdk from '../src'++// The code lists and money helpers live in @spree/core; clients import them+// from the SDK, so the SDK has to keep offering every one of them.+describe('@spree/core exports', () => {+ it.each([+ 'CountryCode',+ 'CurrencyCode',+ 'DimensionUnit',+ 'LocaleCode',+ 'WeightUnit',+ 'compareMoney',+ 'decimalPlaces',+ 'formatMoney',+ 'isDecimalString',+ 'isZeroMoney',+ 'multiplyMoney',+ 'negateMoney',+ 'subtractMoney',+ 'sumMoney',+ ])('offers %s', (name) => {+ expect(sdk).toHaveProperty(name)+ })+})diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 1be131b111..8ac9c708f8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -131,6 +131,27 @@ importers:specifier: ^2.8.4version: 2.9.1+ packages/core:+ devDependencies:+ '@types/node':+ specifier: ^26.6.5+ version: 26.6.5+ tsup:+ specifier: ^9.0.0+ tsx:+ specifier: ^4.21.0+ version: 4.23.15+ typescript:+ specifier: ^7.0.2+ version: 7.0.2+ vitest:+ specifier: ^5.0.5+ version: 5.0.5(@types/[email protected])(@vitest/[email protected])([email protected](@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))+ yaml:+ specifier: ^2.9.1+ version: 2.9.1+packages/create-spree-app:dependencies:'@clack/prompts':@@ -185,6 +206,9 @@ importers:'@hookform/resolvers':specifier: ^5.2.2version: 5.9.1(@standard-schema/[email protected])([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected]))([email protected])+ '@spree/core':+ specifier: workspace:^+ version: link:../core'@tanstack/react-hotkeys':specifier: ^0.14.3@@ -339,6 +363,9 @@ importers:'@hookform/resolvers':specifier: ^5.2.2version: 5.9.1(@standard-schema/[email protected])([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected]))([email protected])+ '@spree/core':+ specifier: workspace:^+ version: link:../core'@tailwindcss/vite':specifier: ^4.2.4version: 4.3.3([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected]))@@ -561,6 +588,9 @@ importers:'@fontsource-variable/geist-mono':specifier: 5.3.0version: 5.3.0+ '@spree/core':+ specifier: workspace:^+ version: link:../core'@tanstack/react-hotkeys':specifier: ^0.14.3@@ -712,6 +742,9 @@ importers:packages/sdk-core:devDependencies:+ '@spree/core':+ specifier: workspace:*+ version: link:../core'@types/spark-md5':specifier: ^3.0.5version: 3.0.5@@ -742,6 +775,9 @@ importers:'@hookform/resolvers':specifier: ^5.2.2version: 5.9.1(@standard-schema/[email protected])([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected]))([email protected])+ '@spree/core':+ specifier: workspace:^+ version: link:../core'@spree/seller-sdk':specifier: workspace:*version: link:../seller-sdk