Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Add dual namespace architecture to SDK (store/admin) (#13591)

Damian Legawiec4ab2917ada9d
diff --git a/packages/next/package.json b/packages/next/package.json
index 4e30bb8076..cdb4a345e2 100644
--- a/packages/next/package.json
+++ b/packages/next/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/next",
- "version": "0.1.2",
+ "version": "0.2.0",
"description": "Next.js integration for Spree Commerce — server actions, caching, and cookie-based auth",
"type": "module",
"main": "./dist/index.js",
@@ -55,7 +55,7 @@
"url": "https://github.com/spree/spree/issues"
},
"peerDependencies": {
- "@spree/sdk": ">=0.1.8",
+ "@spree/sdk": ">=0.2.0",
"next": ">=15.0.0",
"react": ">=19.0.0"
},
diff --git a/packages/next/src/actions/addresses.ts b/packages/next/src/actions/addresses.ts
index 1901a53b2d..a05be589e4 100644
--- a/packages/next/src/actions/addresses.ts
+++ b/packages/next/src/actions/addresses.ts
@@ -10,7 +10,7 @@ import { getClient } from '../config';
*/
export async function listAddresses(): Promise<{ data: StoreAddress[] }> {
return withAuthRefresh(async (options) => {
- return getClient().customer.addresses.list(undefined, options);
+ return getClient().store.customer.addresses.list(undefined, options);
});
}
@@ -19,7 +19,7 @@ export async function listAddresses(): Promise<{ data: StoreAddress[] }> {
*/
export async function getAddress(id: string): Promise<StoreAddress> {
return withAuthRefresh(async (options) => {
- return getClient().customer.addresses.get(id, options);
+ return getClient().store.customer.addresses.get(id, options);
});
}
@@ -28,7 +28,7 @@ export async function getAddress(id: string): Promise<StoreAddress> {
*/
export async function createAddress(params: AddressParams): Promise<StoreAddress> {
const result = await withAuthRefresh(async (options) => {
- return getClient().customer.addresses.create(params, options);
+ return getClient().store.customer.addresses.create(params, options);
});
revalidateTag('addresses');
return result;
@@ -42,7 +42,7 @@ export async function updateAddress(
params: Partial<AddressParams>
): Promise<StoreAddress> {
const result = await withAuthRefresh(async (options) => {
- return getClient().customer.addresses.update(id, params, options);
+ return getClient().store.customer.addresses.update(id, params, options);
});
revalidateTag('addresses');
return result;
@@ -53,7 +53,7 @@ export async function updateAddress(
*/
export async function deleteAddress(id: string): Promise<void> {
await withAuthRefresh(async (options) => {
- return getClient().customer.addresses.delete(id, options);
+ return getClient().store.customer.addresses.delete(id, options);
});
revalidateTag('addresses');
}
diff --git a/packages/next/src/actions/auth.ts b/packages/next/src/actions/auth.ts
index 9e55427336..ce22e85416 100644
--- a/packages/next/src/actions/auth.ts
+++ b/packages/next/src/actions/auth.ts
@@ -15,14 +15,14 @@ export async function login(
password: string
): Promise<{ success: boolean; user?: { id: string; email: string; first_name?: string | null; last_name?: string | null }; error?: string }> {
try {
- const result = await getClient().auth.login({ email, password });
+ const result = await getClient().store.auth.login({ email, password });
await setAccessToken(result.token);
// Associate guest cart if one exists
const cartToken = await getCartToken();
if (cartToken) {
try {
- await getClient().cart.associate({
+ await getClient().store.cart.associate({
token: result.token,
orderToken: cartToken,
});
@@ -52,7 +52,7 @@ export async function register(
passwordConfirmation: string
): Promise<{ success: boolean; user?: { id: string; email: string; first_name?: string | null; last_name?: string | null }; error?: string }> {
try {
- const result = await getClient().auth.register({
+ const result = await getClient().store.auth.register({
email,
password,
password_confirmation: passwordConfirmation,
@@ -63,7 +63,7 @@ export async function register(
const cartToken = await getCartToken();
if (cartToken) {
try {
- await getClient().cart.associate({
+ await getClient().store.cart.associate({
token: result.token,
orderToken: cartToken,
});
@@ -103,7 +103,7 @@ export async function getCustomer(): Promise<StoreCustomer | null> {
try {
return await withAuthRefresh(async (options) => {
- return getClient().customer.get(options);
+ return getClient().store.customer.get(options);
});
} catch {
await clearAccessToken();
@@ -118,7 +118,7 @@ export async function updateCustomer(
data: { first_name?: string; last_name?: string; email?: string }
): Promise<StoreCustomer> {
const result = await withAuthRefresh(async (options) => {
- return getClient().customer.update(data, options);
+ return getClient().store.customer.update(data, options);
});
revalidateTag('customer');
return result;
diff --git a/packages/next/src/actions/cart.ts b/packages/next/src/actions/cart.ts
index c082048d43..2d7769126e 100644
--- a/packages/next/src/actions/cart.ts
+++ b/packages/next/src/actions/cart.ts
@@ -14,7 +14,7 @@ export async function getCart(): Promise<(StoreOrder & { token: string }) | null
if (!orderToken && !token) return null;
try {
- return await getClient().cart.get({ orderToken, token });
+ return await getClient().store.cart.get({ orderToken, token });
} catch {
return null;
}
@@ -28,7 +28,7 @@ export async function getOrCreateCart(): Promise<StoreOrder & { token: string }>
if (existing) return existing;
const token = await getAccessToken();
- const cart = await getClient().cart.create(token ? { token } : undefined);
+ const cart = await getClient().store.cart.create(token ? { token } : undefined);
if (cart.token) {
await setCartToken(cart.token);
@@ -49,7 +49,7 @@ export async function addItem(
const orderToken = cart.token;
const token = await getAccessToken();
- const lineItem = await getClient().orders.lineItems.create(
+ const lineItem = await getClient().store.orders.lineItems.create(
cart.id,
{ variant_id: variantId, quantity },
{ orderToken, token }
@@ -70,9 +70,9 @@ export async function updateItem(
const token = await getAccessToken();
if (!orderToken && !token) throw new Error('No cart found');
- const cart = await getClient().cart.get({ orderToken, token });
+ const cart = await getClient().store.cart.get({ orderToken, token });
- const lineItem = await getClient().orders.lineItems.update(
+ const lineItem = await getClient().store.orders.lineItems.update(
cart.id,
lineItemId,
{ quantity },
@@ -91,9 +91,9 @@ export async function removeItem(lineItemId: string): Promise<void> {
const token = await getAccessToken();
if (!orderToken && !token) throw new Error('No cart found');
- const cart = await getClient().cart.get({ orderToken, token });
+ const cart = await getClient().store.cart.get({ orderToken, token });
- await getClient().orders.lineItems.delete(cart.id, lineItemId, {
+ await getClient().store.orders.lineItems.delete(cart.id, lineItemId, {
orderToken,
token,
});
@@ -119,7 +119,7 @@ export async function associateCart(): Promise<(StoreOrder & { token: string })
if (!orderToken || !token) return null;
try {
- const result = await getClient().cart.associate({ orderToken, token });
+ const result = await getClient().store.cart.associate({ orderToken, token });
revalidateTag('cart');
return result;
} catch {
diff --git a/packages/next/src/actions/checkout.ts b/packages/next/src/actions/checkout.ts
index e65824c804..9828d1000d 100644
--- a/packages/next/src/actions/checkout.ts
+++ b/packages/next/src/actions/checkout.ts
@@ -19,7 +19,7 @@ export async function getCheckout(
orderId: string
): Promise<StoreOrder> {
const options = await getCheckoutOptions();
- return getClient().orders.get(
+ return getClient().store.orders.get(
orderId,
{ includes: 'line_items,shipments,ship_address,bill_address' },
options
@@ -40,7 +40,7 @@ export async function updateAddresses(
}
): Promise<StoreOrder> {
const options = await getCheckoutOptions();
- const result = await getClient().orders.update(orderId, params, options);
+ const result = await getClient().store.orders.update(orderId, params, options);
revalidateTag('checkout');
return result;
}
@@ -50,7 +50,7 @@ export async function updateAddresses(
*/
export async function advance(orderId: string): Promise<StoreOrder> {
const options = await getCheckoutOptions();
- const result = await getClient().orders.advance(orderId, options);
+ const result = await getClient().store.orders.advance(orderId, options);
revalidateTag('checkout');
return result;
}
@@ -60,7 +60,7 @@ export async function advance(orderId: string): Promise<StoreOrder> {
*/
export async function next(orderId: string): Promise<StoreOrder> {
const options = await getCheckoutOptions();
- const result = await getClient().orders.next(orderId, options);
+ const result = await getClient().store.orders.next(orderId, options);
revalidateTag('checkout');
return result;
}
@@ -72,7 +72,7 @@ export async function getShipments(
orderId: string
): Promise<{ data: StoreShipment[] }> {
const options = await getCheckoutOptions();
- return getClient().orders.shipments.list(orderId, options);
+ return getClient().store.orders.shipments.list(orderId, options);
}
/**
@@ -84,7 +84,7 @@ export async function selectShippingRate(
shippingRateId: string
): Promise<StoreShipment> {
const options = await getCheckoutOptions();
- const result = await getClient().orders.shipments.update(
+ const result = await getClient().store.orders.shipments.update(
orderId,
shipmentId,
{ selected_shipping_rate_id: shippingRateId },
@@ -102,7 +102,7 @@ export async function applyCoupon(
code: string
): Promise<StoreOrder> {
const options = await getCheckoutOptions();
- const result = await getClient().orders.couponCodes.apply(orderId, code, options);
+ const result = await getClient().store.orders.couponCodes.apply(orderId, code, options);
revalidateTag('checkout');
revalidateTag('cart');
return result;
@@ -116,7 +116,7 @@ export async function removeCoupon(
promotionId: string
): Promise<StoreOrder> {
const options = await getCheckoutOptions();
- const result = await getClient().orders.couponCodes.remove(orderId, promotionId, options);
+ const result = await getClient().store.orders.couponCodes.remove(orderId, promotionId, options);
revalidateTag('checkout');
revalidateTag('cart');
return result;
@@ -127,7 +127,7 @@ export async function removeCoupon(
*/
export async function complete(orderId: string): Promise<StoreOrder> {
const options = await getCheckoutOptions();
- const result = await getClient().orders.complete(orderId, options);
+ const result = await getClient().store.orders.complete(orderId, options);
revalidateTag('checkout');
revalidateTag('cart');
return result;
diff --git a/packages/next/src/actions/credit-cards.ts b/packages/next/src/actions/credit-cards.ts
index 96452c5f9c..90eebdbc75 100644
--- a/packages/next/src/actions/credit-cards.ts
+++ b/packages/next/src/actions/credit-cards.ts
@@ -10,7 +10,7 @@ import { getClient } from '../config';
*/
export async function listCreditCards(): Promise<{ data: StoreCreditCard[] }> {
return withAuthRefresh(async (options) => {
- return getClient().customer.creditCards.list(undefined, options);
+ return getClient().store.customer.creditCards.list(undefined, options);
});
}
@@ -19,7 +19,7 @@ export async function listCreditCards(): Promise<{ data: StoreCreditCard[] }> {
*/
export async function deleteCreditCard(id: string): Promise<void> {
await withAuthRefresh(async (options) => {
- return getClient().customer.creditCards.delete(id, options);
+ return getClient().store.customer.creditCards.delete(id, options);
});
revalidateTag('credit-cards');
}
diff --git a/packages/next/src/actions/gift-cards.ts b/packages/next/src/actions/gift-cards.ts
index 6e8c7f842a..069d2ee1ed 100644
--- a/packages/next/src/actions/gift-cards.ts
+++ b/packages/next/src/actions/gift-cards.ts
@@ -9,7 +9,7 @@ import { getClient } from '../config';
*/
export async function listGiftCards(): Promise<{ data: StoreGiftCard[] }> {
return withAuthRefresh(async (options) => {
- return getClient().customer.giftCards.list(undefined, options);
+ return getClient().store.customer.giftCards.list(undefined, options);
});
}
@@ -18,6 +18,6 @@ export async function listGiftCards(): Promise<{ data: StoreGiftCard[] }> {
*/
export async function getGiftCard(id: string): Promise<StoreGiftCard> {
return withAuthRefresh(async (options) => {
- return getClient().customer.giftCards.get(id, options);
+ return getClient().store.customer.giftCards.get(id, options);
});
}
diff --git a/packages/next/src/actions/orders.ts b/packages/next/src/actions/orders.ts
index 659db94c5b..0f50134cb7 100644
--- a/packages/next/src/actions/orders.ts
+++ b/packages/next/src/actions/orders.ts
@@ -11,7 +11,7 @@ export async function listOrders(
params?: Record<string, unknown>
): Promise<PaginatedResponse<StoreOrder>> {
return withAuthRefresh(async (options) => {
- return getClient().orders.list(params, options);
+ return getClient().store.orders.list(params, options);
});
}
@@ -23,6 +23,6 @@ export async function getOrder(
params?: Record<string, unknown>
): Promise<StoreOrder> {
return withAuthRefresh(async (options) => {
- return getClient().orders.get(idOrNumber, params, options);
+ return getClient().store.orders.get(idOrNumber, params, options);
});
}
diff --git a/packages/next/src/auth-helpers.ts b/packages/next/src/auth-helpers.ts
index 43491ffa84..de091b7d0a 100644
--- a/packages/next/src/auth-helpers.ts
+++ b/packages/next/src/auth-helpers.ts
@@ -22,7 +22,7 @@ export async function getAuthOptions(): Promise<RequestOptions> {
// Refresh if token expires in less than 1 hour
if (exp && exp - now < 3600) {
try {
- const refreshed = await getClient().auth.refresh({ token });
+ const refreshed = await getClient().store.auth.refresh({ token });
await setAccessToken(refreshed.token);
return { token: refreshed.token };
} catch {
@@ -57,7 +57,7 @@ export async function withAuthRefresh<T>(
// If 401, try refreshing the token once
if (error instanceof SpreeError && error.status === 401) {
try {
- const refreshed = await getClient().auth.refresh({ token: options.token });
+ const refreshed = await getClient().store.auth.refresh({ token: options.token });
await setAccessToken(refreshed.token);
return await fn({ token: refreshed.token });
} catch {
diff --git a/packages/next/src/config.ts b/packages/next/src/config.ts
index 9a397d61ab..2128c11f69 100644
--- a/packages/next/src/config.ts
+++ b/packages/next/src/config.ts
@@ -7,13 +7,13 @@ let _config: SpreeNextConfig | null = null;
/**
* Initialize the Spree Next.js integration.
* Call this once in your app (e.g., in `lib/storefront.ts`).
- * If not called, the client will auto-initialize from SPREE_API_URL and SPREE_API_KEY env vars.
+ * If not called, the client will auto-initialize from SPREE_API_URL and SPREE_PUBLISHABLE_KEY env vars.
*/
export function initSpreeNext(config: SpreeNextConfig): void {
_config = config;
_client = createSpreeClient({
baseUrl: config.baseUrl,
- apiKey: config.apiKey,
+ publishableKey: config.publishableKey,
});
}
@@ -24,12 +24,12 @@ export function initSpreeNext(config: SpreeNextConfig): void {
export function getClient(): SpreeClient {
if (!_client) {
const baseUrl = process.env.SPREE_API_URL;
- const apiKey = process.env.SPREE_API_KEY;
- if (baseUrl && apiKey) {
- initSpreeNext({ baseUrl, apiKey });
+ const publishableKey = process.env.SPREE_PUBLISHABLE_KEY;
+ if (baseUrl && publishableKey) {
+ initSpreeNext({ baseUrl, publishableKey });
} else {
throw new Error(
- '@spree/next is not configured. Either call initSpreeNext() or set SPREE_API_URL and SPREE_API_KEY environment variables.'
+ '@spree/next is not configured. Either call initSpreeNext() or set SPREE_API_URL and SPREE_PUBLISHABLE_KEY environment variables.'
);
}
}
diff --git a/packages/next/src/data/countries.ts b/packages/next/src/data/countries.ts
index 2a9c632672..4d68e38ab2 100644
--- a/packages/next/src/data/countries.ts
+++ b/packages/next/src/data/countries.ts
@@ -8,7 +8,7 @@ import type { SpreeNextOptions } from '../types';
export async function listCountries(
options?: SpreeNextOptions
): Promise<{ data: StoreCountry[] }> {
- return getClient().countries.list({
+ return getClient().store.countries.list({
locale: options?.locale,
currency: options?.currency,
});
@@ -21,7 +21,7 @@ export async function getCountry(
iso: string,
options?: SpreeNextOptions
): Promise<StoreCountry> {
- return getClient().countries.get(iso, {
+ return getClient().store.countries.get(iso, {
locale: options?.locale,
currency: options?.currency,
});
diff --git a/packages/next/src/data/products.ts b/packages/next/src/data/products.ts
index 258763a635..ab1ebfc57d 100644
--- a/packages/next/src/data/products.ts
+++ b/packages/next/src/data/products.ts
@@ -9,7 +9,7 @@ export async function listProducts(
params?: Record<string, unknown>,
options?: SpreeNextOptions
): Promise<PaginatedResponse<StoreProduct>> {
- return getClient().products.list(params, {
+ return getClient().store.products.list(params, {
locale: options?.locale,
currency: options?.currency,
});
@@ -23,7 +23,7 @@ export async function getProduct(
params?: { includes?: string },
options?: SpreeNextOptions
): Promise<StoreProduct> {
- return getClient().products.get(slugOrId, params, {
+ return getClient().store.products.get(slugOrId, params, {
locale: options?.locale,
currency: options?.currency,
});
@@ -36,7 +36,7 @@ export async function getProductFilters(
params?: Record<string, unknown>,
options?: SpreeNextOptions
): Promise<ProductFiltersResponse> {
- return getClient().products.filters(params, {
+ return getClient().store.products.filters(params, {
locale: options?.locale,
currency: options?.currency,
});
diff --git a/packages/next/src/data/store.ts b/packages/next/src/data/store.ts
index 92bfdc1b8e..a34b29f1c4 100644
--- a/packages/next/src/data/store.ts
+++ b/packages/next/src/data/store.ts
@@ -6,7 +6,7 @@ import type { SpreeNextOptions } from '../types';
* Get the current store configuration.
*/
export async function getStore(options?: SpreeNextOptions): Promise<StoreStore> {
- return getClient().store.get({
+ return getClient().store.store.get({
locale: options?.locale,
currency: options?.currency,
});
diff --git a/packages/next/src/data/taxonomies.ts b/packages/next/src/data/taxonomies.ts
index df70ff7d29..bdac7600ba 100644
--- a/packages/next/src/data/taxonomies.ts
+++ b/packages/next/src/data/taxonomies.ts
@@ -9,7 +9,7 @@ export async function listTaxonomies(
params?: Record<string, unknown>,
options?: SpreeNextOptions
): Promise<PaginatedResponse<StoreTaxonomy>> {
- return getClient().taxonomies.list(params, {
+ return getClient().store.taxonomies.list(params, {
locale: options?.locale,
currency: options?.currency,
});
@@ -23,7 +23,7 @@ export async function getTaxonomy(
params?: Record<string, unknown>,
options?: SpreeNextOptions
): Promise<StoreTaxonomy> {
- return getClient().taxonomies.get(id, params, {
+ return getClient().store.taxonomies.get(id, params, {
locale: options?.locale,
currency: options?.currency,
});
diff --git a/packages/next/src/data/taxons.ts b/packages/next/src/data/taxons.ts
index 3eee6f4fc0..6e23a6d7ce 100644
--- a/packages/next/src/data/taxons.ts
+++ b/packages/next/src/data/taxons.ts
@@ -9,7 +9,7 @@ export async function listTaxons(
params?: Record<string, unknown>,
options?: SpreeNextOptions
): Promise<PaginatedResponse<StoreTaxon>> {
- return getClient().taxons.list(params, {
+ return getClient().store.taxons.list(params, {
locale: options?.locale,
currency: options?.currency,
});
@@ -23,7 +23,7 @@ export async function getTaxon(
params?: Record<string, unknown>,
options?: SpreeNextOptions
): Promise<StoreTaxon> {
- return getClient().taxons.get(idOrPermalink, params, {
+ return getClient().store.taxons.get(idOrPermalink, params, {
locale: options?.locale,
currency: options?.currency,
});
@@ -37,7 +37,7 @@ export async function listTaxonProducts(
params?: Record<string, unknown>,
options?: SpreeNextOptions
): Promise<PaginatedResponse<StoreProduct>> {
- return getClient().taxons.products.list(taxonId, params, {
+ return getClient().store.taxons.products.list(taxonId, params, {
locale: options?.locale,
currency: options?.currency,
});
diff --git a/packages/next/src/types.ts b/packages/next/src/types.ts
index 475bd7e683..d21dd98e80 100644
--- a/packages/next/src/types.ts
+++ b/packages/next/src/types.ts
@@ -1,8 +1,8 @@
export interface SpreeNextConfig {
/** Base URL of the Spree API (e.g., 'https://api.mystore.com') */
baseUrl: string;
- /** Publishable API key for store access */
- apiKey: string;
+ /** Publishable API key for Store API access */
+ publishableKey: string;
/** Cookie name for the cart order token (default: '_spree_cart_token') */
cartCookieName?: string;
/** Cookie name for the JWT access token (default: '_spree_jwt') */
diff --git a/packages/next/tests/actions/addresses.test.ts b/packages/next/tests/actions/addresses.test.ts
index 7fb05694d7..7765af19a0 100644
--- a/packages/next/tests/actions/addresses.test.ts
+++ b/packages/next/tests/actions/addresses.test.ts
@@ -3,17 +3,19 @@ import { mockCookieStore } from '../setup';
import { initSpreeNext, resetClient } from '../../src/config';
const mockClient = {
- customer: {
- addresses: {
- list: vi.fn(),
- get: vi.fn(),
- create: vi.fn(),
- update: vi.fn(),
- delete: vi.fn(),
+ store: {
+ customer: {
+ addresses: {
+ list: vi.fn(),
+ get: vi.fn(),
+ create: vi.fn(),
+ update: vi.fn(),
+ delete: vi.fn(),
+ },
+ },
+ auth: {
+ refresh: vi.fn(),
},
- },
- auth: {
- refresh: vi.fn(),
},
};
@@ -47,7 +49,7 @@ describe('address actions', () => {
beforeEach(() => {
vi.clearAllMocks();
resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });
+ initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
// Authenticated user with valid JWT
mockCookieStore.get.mockReturnValue({ value: makeFutureJwt() });
});
@@ -55,11 +57,11 @@ describe('address actions', () => {
describe('listAddresses', () => {
it('returns addresses list', async () => {
const mockAddresses = { data: [{ id: '1', firstname: 'John' }] };
- mockClient.customer.addresses.list.mockResolvedValue(mockAddresses);
+ mockClient.store.customer.addresses.list.mockResolvedValue(mockAddresses);
const result = await listAddresses();
expect(result).toEqual(mockAddresses);
- expect(mockClient.customer.addresses.list).toHaveBeenCalledWith(
+ expect(mockClient.store.customer.addresses.list).toHaveBeenCalledWith(
undefined,
expect.objectContaining({ token: expect.any(String) })
);
@@ -69,11 +71,11 @@ describe('address actions', () => {
describe('getAddress', () => {
it('returns a single address', async () => {
const mockAddress = { id: '1', firstname: 'John', lastname: 'Doe' };
- mockClient.customer.addresses.get.mockResolvedValue(mockAddress);
+ mockClient.store.customer.addresses.get.mockResolvedValue(mockAddress);
const result = await getAddress('1');
expect(result).toEqual(mockAddress);
- expect(mockClient.customer.addresses.get).toHaveBeenCalledWith(
+ expect(mockClient.store.customer.addresses.get).toHaveBeenCalledWith(
'1',
expect.objectContaining({ token: expect.any(String) })
);
@@ -91,11 +93,11 @@ describe('address actions', () => {
country_iso: 'US',
};
const mockAddress = { id: '2', ...params };
- mockClient.customer.addresses.create.mockResolvedValue(mockAddress);
+ mockClient.store.customer.addresses.create.mockResolvedValue(mockAddress);
const result = await createAddress(params);
expect(result).toEqual(mockAddress);
- expect(mockClient.customer.addresses.create).toHaveBeenCalledWith(
+ expect(mockClient.store.customer.addresses.create).toHaveBeenCalledWith(
params,
expect.objectContaining({ token: expect.any(String) })
);
@@ -107,11 +109,11 @@ describe('address actions', () => {
it('updates address and revalidates', async () => {
const params = { firstname: 'Updated' };
const mockAddress = { id: '1', firstname: 'Updated', lastname: 'Doe' };
- mockClient.customer.addresses.update.mockResolvedValue(mockAddress);
+ mockClient.store.customer.addresses.update.mockResolvedValue(mockAddress);
const result = await updateAddress('1', params);
expect(result).toEqual(mockAddress);
- expect(mockClient.customer.addresses.update).toHaveBeenCalledWith(
+ expect(mockClient.store.customer.addresses.update).toHaveBeenCalledWith(
'1',
params,
expect.objectContaining({ token: expect.any(String) })
@@ -122,10 +124,10 @@ describe('address actions', () => {
describe('deleteAddress', () => {
it('deletes address and revalidates', async () => {
- mockClient.customer.addresses.delete.mockResolvedValue(undefined);
+ mockClient.store.customer.addresses.delete.mockResolvedValue(undefined);
await deleteAddress('1');
- expect(mockClient.customer.addresses.delete).toHaveBeenCalledWith(
+ expect(mockClient.store.customer.addresses.delete).toHaveBeenCalledWith(
'1',
expect.objectContaining({ token: expect.any(String) })
);
diff --git a/packages/next/tests/actions/auth.test.ts b/packages/next/tests/actions/auth.test.ts
index 228c600b8e..5a8586dff2 100644
--- a/packages/next/tests/actions/auth.test.ts
+++ b/packages/next/tests/actions/auth.test.ts
@@ -3,17 +3,19 @@ import { mockCookieStore } from '../setup';
import { initSpreeNext, resetClient } from '../../src/config';
const mockClient = {
- auth: {
- login: vi.fn(),
- register: vi.fn(),
- refresh: vi.fn(),
- },
- customer: {
- get: vi.fn(),
- update: vi.fn(),
- },
- cart: {
- associate: vi.fn(),
+ store: {
+ auth: {
+ login: vi.fn(),
+ register: vi.fn(),
+ refresh: vi.fn(),
+ },
+ customer: {
+ get: vi.fn(),
+ update: vi.fn(),
+ },
+ cart: {
+ associate: vi.fn(),
+ },
},
};
@@ -37,7 +39,7 @@ describe('auth actions', () => {
beforeEach(() => {
vi.clearAllMocks();
resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });
+ initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
});
describe('login', () => {
@@ -47,7 +49,7 @@ describe('auth actions', () => {
user: { id: '1', email: '[email protected]', first_name: 'Test', last_name: 'User' },
};
mockCookieStore.get.mockReturnValue(undefined); // no cart token
- mockClient.auth.login.mockResolvedValue(authResult);
+ mockClient.store.auth.login.mockResolvedValue(authResult);
const result = await login('[email protected]', 'password123');
expect(result.success).toBe(true);
@@ -64,18 +66,18 @@ describe('auth actions', () => {
const authResult = { token: 'jwt_new', user: { id: '1', email: '[email protected]' } };
mockCookieStore.get
.mockReturnValueOnce({ value: 'guest_cart_token' }); // getCartToken
- mockClient.auth.login.mockResolvedValue(authResult);
- mockClient.cart.associate.mockResolvedValue({});
+ mockClient.store.auth.login.mockResolvedValue(authResult);
+ mockClient.store.cart.associate.mockResolvedValue({});
await login('[email protected]', 'pass');
- expect(mockClient.cart.associate).toHaveBeenCalledWith({
+ expect(mockClient.store.cart.associate).toHaveBeenCalledWith({
token: 'jwt_new',
orderToken: 'guest_cart_token',
});
});
it('returns error on failure', async () => {
- mockClient.auth.login.mockRejectedValue(new Error('Invalid credentials'));
+ mockClient.store.auth.login.mockRejectedValue(new Error('Invalid credentials'));
const result = await login('[email protected]', 'wrong');
expect(result.success).toBe(false);
@@ -108,7 +110,7 @@ describe('auth actions', () => {
it('returns customer when authenticated', async () => {
const mockUser = { id: '1', email: '[email protected]' };
mockCookieStore.get.mockReturnValue({ value: 'valid_jwt' });
- mockClient.customer.get.mockResolvedValue(mockUser);
+ mockClient.store.customer.get.mockResolvedValue(mockUser);
const customer = await getCustomer();
expect(customer).toEqual(mockUser);
diff --git a/packages/next/tests/actions/cart.test.ts b/packages/next/tests/actions/cart.test.ts
index 508b477e09..5bbe0a68df 100644
--- a/packages/next/tests/actions/cart.test.ts
+++ b/packages/next/tests/actions/cart.test.ts
@@ -4,16 +4,18 @@ import { initSpreeNext, resetClient } from '../../src/config';
// Mock the SDK client
const mockClient = {
- cart: {
- get: vi.fn(),
- create: vi.fn(),
- associate: vi.fn(),
- },
- orders: {
- lineItems: {
+ store: {
+ cart: {
+ get: vi.fn(),
create: vi.fn(),
- update: vi.fn(),
- delete: vi.fn(),
+ associate: vi.fn(),
+ },
+ orders: {
+ lineItems: {
+ create: vi.fn(),
+ update: vi.fn(),
+ delete: vi.fn(),
+ },
},
},
};
@@ -29,7 +31,7 @@ describe('cart actions', () => {
beforeEach(() => {
vi.clearAllMocks();
resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });
+ initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
});
describe('getCart', () => {
@@ -42,18 +44,18 @@ describe('cart actions', () => {
it('returns cart when order token exists', async () => {
const mockCart = { id: '1', token: 'order_abc', line_items: [] };
mockCookieStore.get.mockReturnValue({ value: 'order_abc' });
- mockClient.cart.get.mockResolvedValue(mockCart);
+ mockClient.store.cart.get.mockResolvedValue(mockCart);
const cart = await getCart();
expect(cart).toEqual(mockCart);
- expect(mockClient.cart.get).toHaveBeenCalledWith(
+ expect(mockClient.store.cart.get).toHaveBeenCalledWith(
expect.objectContaining({ orderToken: 'order_abc' })
);
});
it('returns null when cart fetch fails', async () => {
mockCookieStore.get.mockReturnValue({ value: 'bad_token' });
- mockClient.cart.get.mockRejectedValue(new Error('Not found'));
+ mockClient.store.cart.get.mockRejectedValue(new Error('Not found'));
const cart = await getCart();
expect(cart).toBeNull();
@@ -64,21 +66,21 @@ describe('cart actions', () => {
it('returns existing cart if available', async () => {
const mockCart = { id: '1', token: 'existing', line_items: [] };
mockCookieStore.get.mockReturnValue({ value: 'existing' });
- mockClient.cart.get.mockResolvedValue(mockCart);
+ mockClient.store.cart.get.mockResolvedValue(mockCart);
const cart = await getOrCreateCart();
expect(cart).toEqual(mockCart);
- expect(mockClient.cart.create).not.toHaveBeenCalled();
+ expect(mockClient.store.cart.create).not.toHaveBeenCalled();
});
it('creates new cart when none exists', async () => {
const newCart = { id: '2', token: 'new_token', line_items: [] };
mockCookieStore.get.mockReturnValue(undefined);
- mockClient.cart.create.mockResolvedValue(newCart);
+ mockClient.store.cart.create.mockResolvedValue(newCart);
const cart = await getOrCreateCart();
expect(cart).toEqual(newCart);
- expect(mockClient.cart.create).toHaveBeenCalled();
+ expect(mockClient.store.cart.create).toHaveBeenCalled();
expect(mockCookieStore.set).toHaveBeenCalledWith(
'_spree_cart_token',
'new_token',
@@ -92,12 +94,12 @@ describe('cart actions', () => {
const mockCart = { id: '1', token: 'cart_token', line_items: [] };
const mockLineItem = { id: 'li_1', quantity: 2, variant_id: 'v1' };
mockCookieStore.get.mockReturnValue({ value: 'cart_token' });
- mockClient.cart.get.mockResolvedValue(mockCart);
- mockClient.orders.lineItems.create.mockResolvedValue(mockLineItem);
+ mockClient.store.cart.get.mockResolvedValue(mockCart);
+ mockClient.store.orders.lineItems.create.mockResolvedValue(mockLineItem);
const result = await addItem('v1', 2);
expect(result).toEqual(mockLineItem);
- expect(mockClient.orders.lineItems.create).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.lineItems.create).toHaveBeenCalledWith(
'1',
{ variant_id: 'v1', quantity: 2 },
expect.objectContaining({ orderToken: 'cart_token' })
@@ -110,11 +112,11 @@ describe('cart actions', () => {
it('deletes line item and invalidates cache', async () => {
const mockCart = { id: '1', token: 'cart_token' };
mockCookieStore.get.mockReturnValue({ value: 'cart_token' });
- mockClient.cart.get.mockResolvedValue(mockCart);
- mockClient.orders.lineItems.delete.mockResolvedValue(undefined);
+ mockClient.store.cart.get.mockResolvedValue(mockCart);
+ mockClient.store.orders.lineItems.delete.mockResolvedValue(undefined);
await removeItem('li_1');
- expect(mockClient.orders.lineItems.delete).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.lineItems.delete).toHaveBeenCalledWith(
'1',
'li_1',
expect.objectContaining({ orderToken: 'cart_token' })
@@ -148,11 +150,11 @@ describe('cart actions', () => {
mockCookieStore.get
.mockReturnValueOnce({ value: 'cart_token' })
.mockReturnValueOnce({ value: 'jwt_token' });
- mockClient.cart.associate.mockResolvedValue(mockCart);
+ mockClient.store.cart.associate.mockResolvedValue(mockCart);
const result = await associateCart();
expect(result).toEqual(mockCart);
- expect(mockClient.cart.associate).toHaveBeenCalledWith({
+ expect(mockClient.store.cart.associate).toHaveBeenCalledWith({
orderToken: 'cart_token',
token: 'jwt_token',
});
diff --git a/packages/next/tests/actions/checkout.test.ts b/packages/next/tests/actions/checkout.test.ts
index 0cfad098b7..7dd25ed083 100644
--- a/packages/next/tests/actions/checkout.test.ts
+++ b/packages/next/tests/actions/checkout.test.ts
@@ -3,19 +3,21 @@ import { mockCookieStore } from '../setup';
import { initSpreeNext, resetClient } from '../../src/config';
const mockClient = {
- orders: {
- get: vi.fn(),
- update: vi.fn(),
- advance: vi.fn(),
- next: vi.fn(),
- complete: vi.fn(),
- shipments: {
- list: vi.fn(),
+ store: {
+ orders: {
+ get: vi.fn(),
update: vi.fn(),
- },
- couponCodes: {
- apply: vi.fn(),
- remove: vi.fn(),
+ advance: vi.fn(),
+ next: vi.fn(),
+ complete: vi.fn(),
+ shipments: {
+ list: vi.fn(),
+ update: vi.fn(),
+ },
+ couponCodes: {
+ apply: vi.fn(),
+ remove: vi.fn(),
+ },
},
},
};
@@ -41,7 +43,7 @@ describe('checkout actions', () => {
beforeEach(() => {
vi.clearAllMocks();
resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });
+ initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
// Default: cart token and access token available
mockCookieStore.get
.mockReturnValueOnce({ value: 'order_token_123' }) // getCartToken
@@ -51,11 +53,11 @@ describe('checkout actions', () => {
describe('getCheckout', () => {
it('fetches order with includes and auth options', async () => {
const mockOrder = { id: '1', number: 'R123', line_items: [{ id: 'li1' }] };
- mockClient.orders.get.mockResolvedValue(mockOrder);
+ mockClient.store.orders.get.mockResolvedValue(mockOrder);
const result = await getCheckout('1');
expect(result).toEqual(mockOrder);
- expect(mockClient.orders.get).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.get).toHaveBeenCalledWith(
'1',
{ includes: 'line_items,shipments,ship_address,bill_address' },
{ orderToken: 'order_token_123', token: 'jwt_token_abc' }
@@ -70,11 +72,11 @@ describe('checkout actions', () => {
ship_address: { firstname: 'John', lastname: 'Doe', address1: '123 Main St', city: 'NY', zipcode: '10001', country_iso: 'US' },
};
- mockClient.orders.update.mockResolvedValue(mockOrder);
+ mockClient.store.orders.update.mockResolvedValue(mockOrder);
const result = await updateAddresses('1', addressParams);
expect(result).toEqual(mockOrder);
- expect(mockClient.orders.update).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.update).toHaveBeenCalledWith(
'1',
addressParams,
{ orderToken: 'order_token_123', token: 'jwt_token_abc' }
@@ -86,11 +88,11 @@ describe('checkout actions', () => {
describe('advance', () => {
it('advances checkout and revalidates', async () => {
const mockOrder = { id: '1', state: 'delivery' };
- mockClient.orders.advance.mockResolvedValue(mockOrder);
+ mockClient.store.orders.advance.mockResolvedValue(mockOrder);
const result = await advance('1');
expect(result).toEqual(mockOrder);
- expect(mockClient.orders.advance).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.advance).toHaveBeenCalledWith(
'1',
{ orderToken: 'order_token_123', token: 'jwt_token_abc' }
);
@@ -101,11 +103,11 @@ describe('checkout actions', () => {
describe('next', () => {
it('moves checkout to next step and revalidates', async () => {
const mockOrder = { id: '1', state: 'payment' };
- mockClient.orders.next.mockResolvedValue(mockOrder);
+ mockClient.store.orders.next.mockResolvedValue(mockOrder);
const result = await next('1');
expect(result).toEqual(mockOrder);
- expect(mockClient.orders.next).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.next).toHaveBeenCalledWith(
'1',
{ orderToken: 'order_token_123', token: 'jwt_token_abc' }
);
@@ -116,11 +118,11 @@ describe('checkout actions', () => {
describe('getShipments', () => {
it('returns shipments for the order', async () => {
const mockShipments = { data: [{ id: 's1', shipping_rates: [] }] };
- mockClient.orders.shipments.list.mockResolvedValue(mockShipments);
+ mockClient.store.orders.shipments.list.mockResolvedValue(mockShipments);
const result = await getShipments('1');
expect(result).toEqual(mockShipments);
- expect(mockClient.orders.shipments.list).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.shipments.list).toHaveBeenCalledWith(
'1',
{ orderToken: 'order_token_123', token: 'jwt_token_abc' }
);
@@ -130,11 +132,11 @@ describe('checkout actions', () => {
describe('selectShippingRate', () => {
it('selects shipping rate and revalidates checkout', async () => {
const mockShipment = { id: 's1', selected_shipping_rate_id: 'sr1' };
- mockClient.orders.shipments.update.mockResolvedValue(mockShipment);
+ mockClient.store.orders.shipments.update.mockResolvedValue(mockShipment);
const result = await selectShippingRate('1', 's1', 'sr1');
expect(result).toEqual(mockShipment);
- expect(mockClient.orders.shipments.update).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.shipments.update).toHaveBeenCalledWith(
'1',
's1',
{ selected_shipping_rate_id: 'sr1' },
@@ -147,11 +149,11 @@ describe('checkout actions', () => {
describe('applyCoupon', () => {
it('applies coupon and revalidates checkout and cart', async () => {
const mockOrder = { id: '1', promo_total: -10 };
- mockClient.orders.couponCodes.apply.mockResolvedValue(mockOrder);
+ mockClient.store.orders.couponCodes.apply.mockResolvedValue(mockOrder);
const result = await applyCoupon('1', 'SAVE10');
expect(result).toEqual(mockOrder);
- expect(mockClient.orders.couponCodes.apply).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.couponCodes.apply).toHaveBeenCalledWith(
'1',
'SAVE10',
{ orderToken: 'order_token_123', token: 'jwt_token_abc' }
@@ -164,11 +166,11 @@ describe('checkout actions', () => {
describe('removeCoupon', () => {
it('removes coupon and revalidates checkout and cart', async () => {
const mockOrder = { id: '1', promo_total: 0 };
- mockClient.orders.couponCodes.remove.mockResolvedValue(mockOrder);
+ mockClient.store.orders.couponCodes.remove.mockResolvedValue(mockOrder);
const result = await removeCoupon('1', 'promo_1');
expect(result).toEqual(mockOrder);
- expect(mockClient.orders.couponCodes.remove).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.couponCodes.remove).toHaveBeenCalledWith(
'1',
'promo_1',
{ orderToken: 'order_token_123', token: 'jwt_token_abc' }
@@ -181,11 +183,11 @@ describe('checkout actions', () => {
describe('complete', () => {
it('completes checkout and revalidates checkout and cart', async () => {
const mockOrder = { id: '1', state: 'complete' };
- mockClient.orders.complete.mockResolvedValue(mockOrder);
+ mockClient.store.orders.complete.mockResolvedValue(mockOrder);
const result = await complete('1');
expect(result).toEqual(mockOrder);
- expect(mockClient.orders.complete).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.complete).toHaveBeenCalledWith(
'1',
{ orderToken: 'order_token_123', token: 'jwt_token_abc' }
);
diff --git a/packages/next/tests/actions/credit-cards.test.ts b/packages/next/tests/actions/credit-cards.test.ts
index f11c58ac44..501869814c 100644
--- a/packages/next/tests/actions/credit-cards.test.ts
+++ b/packages/next/tests/actions/credit-cards.test.ts
@@ -3,14 +3,16 @@ import { mockCookieStore } from '../setup';
import { initSpreeNext, resetClient } from '../../src/config';
const mockClient = {
- customer: {
- creditCards: {
- list: vi.fn(),
- delete: vi.fn(),
+ store: {
+ customer: {
+ creditCards: {
+ list: vi.fn(),
+ delete: vi.fn(),
+ },
+ },
+ auth: {
+ refresh: vi.fn(),
},
- },
- auth: {
- refresh: vi.fn(),
},
};
@@ -38,18 +40,18 @@ describe('credit card actions', () => {
beforeEach(() => {
vi.clearAllMocks();
resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });
+ initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
mockCookieStore.get.mockReturnValue({ value: makeFutureJwt() });
});
describe('listCreditCards', () => {
it('returns credit cards list', async () => {
const mockCards = { data: [{ id: '1', last_digits: '4242' }] };
- mockClient.customer.creditCards.list.mockResolvedValue(mockCards);
+ mockClient.store.customer.creditCards.list.mockResolvedValue(mockCards);
const result = await listCreditCards();
expect(result).toEqual(mockCards);
- expect(mockClient.customer.creditCards.list).toHaveBeenCalledWith(
+ expect(mockClient.store.customer.creditCards.list).toHaveBeenCalledWith(
undefined,
expect.objectContaining({ token: expect.any(String) })
);
@@ -58,10 +60,10 @@ describe('credit card actions', () => {
describe('deleteCreditCard', () => {
it('deletes card and revalidates', async () => {
- mockClient.customer.creditCards.delete.mockResolvedValue(undefined);
+ mockClient.store.customer.creditCards.delete.mockResolvedValue(undefined);
await deleteCreditCard('1');
- expect(mockClient.customer.creditCards.delete).toHaveBeenCalledWith(
+ expect(mockClient.store.customer.creditCards.delete).toHaveBeenCalledWith(
'1',
expect.objectContaining({ token: expect.any(String) })
);
diff --git a/packages/next/tests/actions/gift-cards.test.ts b/packages/next/tests/actions/gift-cards.test.ts
index fd85e09722..a511ebcd7f 100644
--- a/packages/next/tests/actions/gift-cards.test.ts
+++ b/packages/next/tests/actions/gift-cards.test.ts
@@ -3,14 +3,16 @@ import { mockCookieStore } from '../setup';
import { initSpreeNext, resetClient } from '../../src/config';
const mockClient = {
- customer: {
- giftCards: {
- list: vi.fn(),
- get: vi.fn(),
+ store: {
+ customer: {
+ giftCards: {
+ list: vi.fn(),
+ get: vi.fn(),
+ },
+ },
+ auth: {
+ refresh: vi.fn(),
},
- },
- auth: {
- refresh: vi.fn(),
},
};
@@ -37,18 +39,18 @@ describe('gift card actions', () => {
beforeEach(() => {
vi.clearAllMocks();
resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });
+ initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
mockCookieStore.get.mockReturnValue({ value: makeFutureJwt() });
});
describe('listGiftCards', () => {
it('returns gift cards list', async () => {
const mockCards = { data: [{ id: '1', code: 'GIFT100', balance: 100 }] };
- mockClient.customer.giftCards.list.mockResolvedValue(mockCards);
+ mockClient.store.customer.giftCards.list.mockResolvedValue(mockCards);
const result = await listGiftCards();
expect(result).toEqual(mockCards);
- expect(mockClient.customer.giftCards.list).toHaveBeenCalledWith(
+ expect(mockClient.store.customer.giftCards.list).toHaveBeenCalledWith(
undefined,
expect.objectContaining({ token: expect.any(String) })
);
@@ -58,11 +60,11 @@ describe('gift card actions', () => {
describe('getGiftCard', () => {
it('returns a single gift card', async () => {
const mockCard = { id: '1', code: 'GIFT100', balance: 100 };
- mockClient.customer.giftCards.get.mockResolvedValue(mockCard);
+ mockClient.store.customer.giftCards.get.mockResolvedValue(mockCard);
const result = await getGiftCard('1');
expect(result).toEqual(mockCard);
- expect(mockClient.customer.giftCards.get).toHaveBeenCalledWith(
+ expect(mockClient.store.customer.giftCards.get).toHaveBeenCalledWith(
'1',
expect.objectContaining({ token: expect.any(String) })
);
diff --git a/packages/next/tests/actions/orders.test.ts b/packages/next/tests/actions/orders.test.ts
index 8ff2504bc2..448b8985cd 100644
--- a/packages/next/tests/actions/orders.test.ts
+++ b/packages/next/tests/actions/orders.test.ts
@@ -3,12 +3,14 @@ import { mockCookieStore } from '../setup';
import { initSpreeNext, resetClient } from '../../src/config';
const mockClient = {
- orders: {
- list: vi.fn(),
- get: vi.fn(),
- },
- auth: {
- refresh: vi.fn(),
+ store: {
+ orders: {
+ list: vi.fn(),
+ get: vi.fn(),
+ },
+ auth: {
+ refresh: vi.fn(),
+ },
},
};
@@ -35,7 +37,7 @@ describe('order actions', () => {
beforeEach(() => {
vi.clearAllMocks();
resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });
+ initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
mockCookieStore.get.mockReturnValue({ value: makeFutureJwt() });
});
@@ -45,11 +47,11 @@ describe('order actions', () => {
data: [{ id: '1', number: 'R001' }],
meta: { total_count: 1, total_pages: 1 },
};
- mockClient.orders.list.mockResolvedValue(mockResponse);
+ mockClient.store.orders.list.mockResolvedValue(mockResponse);
const result = await listOrders({ page: 1 });
expect(result).toEqual(mockResponse);
- expect(mockClient.orders.list).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.list).toHaveBeenCalledWith(
{ page: 1 },
expect.objectContaining({ token: expect.any(String) })
);
@@ -57,11 +59,11 @@ describe('order actions', () => {
it('works without params', async () => {
const mockResponse = { data: [], meta: { total_count: 0, total_pages: 0 } };
- mockClient.orders.list.mockResolvedValue(mockResponse);
+ mockClient.store.orders.list.mockResolvedValue(mockResponse);
const result = await listOrders();
expect(result).toEqual(mockResponse);
- expect(mockClient.orders.list).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.list).toHaveBeenCalledWith(
undefined,
expect.objectContaining({ token: expect.any(String) })
);
@@ -71,11 +73,11 @@ describe('order actions', () => {
describe('getOrder', () => {
it('returns a single order by id', async () => {
const mockOrder = { id: '1', number: 'R001', state: 'complete' };
- mockClient.orders.get.mockResolvedValue(mockOrder);
+ mockClient.store.orders.get.mockResolvedValue(mockOrder);
const result = await getOrder('1');
expect(result).toEqual(mockOrder);
- expect(mockClient.orders.get).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.get).toHaveBeenCalledWith(
'1',
undefined,
expect.objectContaining({ token: expect.any(String) })
@@ -84,11 +86,11 @@ describe('order actions', () => {
it('passes params through', async () => {
const mockOrder = { id: '1', number: 'R001' };
- mockClient.orders.get.mockResolvedValue(mockOrder);
+ mockClient.store.orders.get.mockResolvedValue(mockOrder);
const result = await getOrder('R001', { includes: 'line_items' });
expect(result).toEqual(mockOrder);
- expect(mockClient.orders.get).toHaveBeenCalledWith(
+ expect(mockClient.store.orders.get).toHaveBeenCalledWith(
'R001',
{ includes: 'line_items' },
expect.objectContaining({ token: expect.any(String) })
diff --git a/packages/next/tests/auth-helpers.test.ts b/packages/next/tests/auth-helpers.test.ts
index 5ecc9893b0..46aa88e0ba 100644
--- a/packages/next/tests/auth-helpers.test.ts
+++ b/packages/next/tests/auth-helpers.test.ts
@@ -3,8 +3,10 @@ import { mockCookieStore } from './setup';
import { initSpreeNext, resetClient } from '../src/config';
const mockClient = {
- auth: {
- refresh: vi.fn(),
+ store: {
+ auth: {
+ refresh: vi.fn(),
+ },
},
};
@@ -35,7 +37,7 @@ describe('auth-helpers', () => {
beforeEach(() => {
vi.clearAllMocks();
resetClient();
- initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });
+ initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
});
describe('getAuthOptions', () => {
@@ -52,7 +54,7 @@ describe('auth-helpers', () => {
const options = await getAuthOptions();
expect(options).toEqual({ token: jwt });
- expect(mockClient.auth.refresh).not.toHaveBeenCalled();
+ expect(mockClient.store.auth.refresh).not.toHaveBeenCalled();
});
it('refreshes token when near expiry', async () => {
@@ -60,11 +62,11 @@ describe('auth-helpers', () => {
const jwt = makeJwt(nearExp);
const newJwt = 'refreshed_token';
mockCookieStore.get.mockReturnValue({ value: jwt });
- mockClient.auth.refresh.mockResolvedValue({ token: newJwt });
+ mockClient.store.auth.refresh.mockResolvedValue({ token: newJwt });
const options = await getAuthOptions();
expect(options).toEqual({ token: newJwt });
- expect(mockClient.auth.refresh).toHaveBeenCalledWith({ token: jwt });
+ expect(mockClient.store.auth.refresh).toHaveBeenCalledWith({ token: jwt });
expect(mockCookieStore.set).toHaveBeenCalledWith(
'_spree_jwt',
newJwt,
@@ -76,7 +78,7 @@ describe('auth-helpers', () => {
const nearExp = Math.floor(Date.now() / 1000) + 1800;
const jwt = makeJwt(nearExp);
mockCookieStore.get.mockReturnValue({ value: jwt });
- mockClient.auth.refresh.mockRejectedValue(new Error('Refresh failed'));
+ mockClient.store.auth.refresh.mockRejectedValue(new Error('Refresh failed'));
const options = await getAuthOptions();
expect(options).toEqual({ token: jwt });
@@ -88,7 +90,7 @@ describe('auth-helpers', () => {
const options = await getAuthOptions();
expect(options).toEqual({ token: malformedJwt });
- expect(mockClient.auth.refresh).not.toHaveBeenCalled();
+ expect(mockClient.store.auth.refresh).not.toHaveBeenCalled();
});
});
@@ -122,7 +124,7 @@ describe('auth-helpers', () => {
const fn = vi.fn()
.mockRejectedValueOnce(error401)
.mockResolvedValueOnce({ data: 'retried' });
- mockClient.auth.refresh.mockResolvedValue({ token: newJwt });
+ mockClient.store.auth.refresh.mockResolvedValue({ token: newJwt });
const result = await withAuthRefresh(fn);
expect(result).toEqual({ data: 'retried' });
@@ -142,7 +144,7 @@ describe('auth-helpers', () => {
const error401 = new SpreeError({ error: { message: 'Unauthorized' } } as any, 401);
const fn = vi.fn().mockRejectedValue(error401);
- mockClient.auth.refresh.mockRejectedValue(new Error('Refresh failed'));
+ mockClient.store.auth.refresh.mockRejectedValue(new Error('Refresh failed'));
await expect(withAuthRefresh(fn)).rejects.toThrow('Unauthorized');
// Token should be cleared
@@ -162,7 +164,7 @@ describe('auth-helpers', () => {
const fn = vi.fn().mockRejectedValue(error500);
await expect(withAuthRefresh(fn)).rejects.toThrow('Server error');
- expect(mockClient.auth.refresh).not.toHaveBeenCalled();
+ expect(mockClient.store.auth.refresh).not.toHaveBeenCalled();
});
});
});
diff --git a/packages/next/tests/config.test.ts b/packages/next/tests/config.test.ts
index 0e7173f4a7..8f93b34b7f 100644
--- a/packages/next/tests/config.test.ts
+++ b/packages/next/tests/config.test.ts
@@ -5,18 +5,18 @@ describe('config', () => {
beforeEach(() => {
resetClient();
delete process.env.SPREE_API_URL;
- delete process.env.SPREE_API_KEY;
+ delete process.env.SPREE_PUBLISHABLE_KEY;
});
it('initializes from explicit config', () => {
- initSpreeNext({ baseUrl: 'https://api.test.com', apiKey: 'pk_test' });
+ initSpreeNext({ baseUrl: 'https://api.test.com', publishableKey: 'pk_test' });
const client = getClient();
expect(client).toBeDefined();
});
it('auto-initializes from env vars', () => {
process.env.SPREE_API_URL = 'https://api.env.com';
- process.env.SPREE_API_KEY = 'pk_env';
+ process.env.SPREE_PUBLISHABLE_KEY = 'pk_env';
const client = getClient();
expect(client).toBeDefined();
});
diff --git a/packages/sdk/CHANGELOG.md b/packages/sdk/CHANGELOG.md
index fb76787d1d..54499151ff 100644
--- a/packages/sdk/CHANGELOG.md
+++ b/packages/sdk/CHANGELOG.md
@@ -1,5 +1,17 @@
# @spree/sdk
+## 0.2.0
+
+### Minor Changes
+
+- Restructure SDK to support dual API namespaces: `client.store.*` (Store API) and `client.admin.*` (Admin API)
+
+### Internal
+
+- Extract request infrastructure into `request.ts` with `createRequestFn()` factory
+- Split monolithic `client.ts` into `store-client.ts`, `admin-client.ts`, and composed `client.ts`
+- Add `StoreClient` and `AdminClient` exports
+
## 0.1.8
### Patch Changes
diff --git a/packages/sdk/README.md b/packages/sdk/README.md
index 77ccf89b5f..9eb39b5c5e 100644
--- a/packages/sdk/README.md
+++ b/packages/sdk/README.md
@@ -20,72 +20,84 @@ import { createSpreeClient } from '@spree/sdk';
// Initialize the client
const client = createSpreeClient({
baseUrl: 'https://api.mystore.com',
- apiKey: 'your-publishable-api-key',
+ publishableKey: 'spree_pk_xxx', // Store API
+ secretKey: 'spree_sk_xxx', // Admin API (optional)
});
-// Browse products
-const products = await client.products.list({
+// Browse products (Store API)
+const products = await client.store.products.list({
per_page: 10,
includes: 'variants,images',
});
// Get a single product
-const product = await client.products.get('ruby-on-rails-tote');
+const product = await client.store.products.get('ruby-on-rails-tote');
// Authentication
-const { token, user } = await client.auth.login({
+const { token, user } = await client.store.auth.login({
password: 'password123',
});
// Create a cart and add items
-const cart = await client.cart.create();
-await client.orders.lineItems.create(cart.id, {
+const cart = await client.store.cart.create();
+await client.store.orders.lineItems.create(cart.id, {
variant_id: 'var_abc123',
quantity: 2,
}, { orderToken: cart.token });
// Checkout flow
-await client.orders.next(cart.id, { orderToken: cart.token });
-await client.orders.complete(cart.id, { orderToken: cart.token });
+await client.store.orders.next(cart.id, { orderToken: cart.token });
+await client.store.orders.complete(cart.id, { orderToken: cart.token });
```
+## Client Architecture
+
+The SDK exposes two API namespaces:
+
+```typescript
+client.store // Store API — customer-facing (products, cart, checkout, account)
+client.admin // Admin API — administrative (coming soon)
+```
+
+All Store API endpoints live under `client.store.*`. The Admin API namespace is ready for future endpoints.
+
## Authentication
The SDK supports multiple authentication modes:
-### 1. API Key Only (Guest/Public Access)
+### 1. Publishable Key Only (Guest/Public Access)
```typescript
const client = createSpreeClient({
baseUrl: 'https://api.mystore.com',
- apiKey: 'pk_your-publishable-key',
+ publishableKey: 'spree_pk_xxx',
});
// Public endpoints work without user authentication
-const products = await client.products.list();
+const products = await client.store.products.list();
```
-### 2. API Key + JWT (Authenticated Customer)
+### 2. Publishable Key + JWT (Authenticated Customer)
```typescript
// Login to get tokens
-const { token, user } = await client.auth.login({
+const { token, user } = await client.store.auth.login({
password: 'password123',
});
// Use token for authenticated requests
-const orders = await client.orders.list({}, { token });
+const orders = await client.store.orders.list({}, { token });
// Refresh token when needed
-const newTokens = await client.auth.refresh({ token });
+const newTokens = await client.store.auth.refresh({ token });
```
### 3. Register New Customer
```typescript
-const { token, user } = await client.auth.register({
+const { token, user } = await client.store.auth.register({
password: 'password123',
password_confirmation: 'password123',
@@ -100,24 +112,24 @@ For guest checkout, use the `token` (or `order_token`) returned when creating a
```typescript
// Create a cart (guest)
-const cart = await client.cart.create();
+const cart = await client.store.cart.create();
// Use orderToken for all cart operations
const options = { orderToken: cart.token };
// Add items
-await client.orders.lineItems.create(cart.id, {
+await client.store.orders.lineItems.create(cart.id, {
variant_id: 'var_abc123',
quantity: 1,
}, options);
// Update order with email
-await client.orders.update(cart.id, {
+await client.store.orders.update(cart.id, {
}, options);
// Complete checkout
-await client.orders.complete(cart.id, options);
+await client.store.orders.complete(cart.id, options);
```
## API Reference
@@ -126,14 +138,14 @@ await client.orders.complete(cart.id, options);
```typescript
// Get current store information
-const store = await client.store.get();
+const store = await client.store.store.get();
```
### Products
```typescript
// List products with filtering
-const products = await client.products.list({
+const products = await client.store.products.list({
page: 1,
per_page: 25,
'q[name_cont]': 'shirt',
@@ -141,12 +153,12 @@ const products = await client.products.list({
});
// Get single product by ID or slug
-const product = await client.products.get('ruby-on-rails-tote', {
+const product = await client.store.products.get('ruby-on-rails-tote', {
includes: 'variants,images',
});
// Get available filters (price range, availability, options, taxons)
-const filters = await client.products.filters({
+const filters = await client.store.products.filters({
taxon_id: 'txn_abc123', // Optional: scope filters to a taxon
});
```
@@ -155,28 +167,28 @@ const filters = await client.products.filters({
```typescript
// List taxonomies
-const taxonomies = await client.taxonomies.list({
+const taxonomies = await client.store.taxonomies.list({
includes: 'taxons',
});
// Get taxonomy with taxons
-const categories = await client.taxonomies.get('tax_123', {
+const categories = await client.store.taxonomies.get('tax_123', {
includes: 'root,taxons',
});
// List taxons with filtering
-const taxons = await client.taxons.list({
+const taxons = await client.store.taxons.list({
'q[depth_eq]': 1, // Top-level categories only
'q[taxonomy_id_eq]': '123', // Filter by taxonomy
});
// Get single taxon by ID or permalink
-const taxon = await client.taxons.get('categories/clothing', {
+const taxon = await client.store.taxons.get('categories/clothing', {
includes: 'ancestors,children', // For breadcrumbs and subcategories
});
// List products in a category
-const categoryProducts = await client.taxons.products.list('categories/clothing', {
+const categoryProducts = await client.store.taxons.products.list('categories/clothing', {
page: 1,
per_page: 12,
includes: 'images,default_variant',
@@ -187,14 +199,14 @@ const categoryProducts = await client.taxons.products.list('categories/clothing'
```typescript
// Get current cart
-const cart = await client.cart.get({ orderToken: 'xxx' });
+const cart = await client.store.cart.get({ orderToken: 'xxx' });
// Create a new cart
-const newCart = await client.cart.create();
+const newCart = await client.store.cart.create();
// Associate guest cart with authenticated user
// (after user logs in, merge their guest cart with their account)
-await client.cart.associate({
+await client.store.cart.associate({
token: jwtToken, // User's JWT token
orderToken: cart.token, // Guest cart token
});
@@ -204,19 +216,19 @@ await client.cart.associate({
```typescript
// List orders for authenticated customer
-const orders = await client.orders.list({}, { token });
+const orders = await client.store.orders.list({}, { token });
// Create a new order (cart)
-const cart = await client.orders.create();
+const cart = await client.store.orders.create();
const options = { orderToken: cart.order_token };
// Get order by ID or number
-const order = await client.orders.get('R123456789', {
+const order = await client.store.orders.get('R123456789', {
includes: 'line_items,shipments',
}, options);
// Update order (email, addresses)
-await client.orders.update(cart.id, {
+await client.store.orders.update(cart.id, {
ship_address: {
firstname: 'John',
@@ -232,9 +244,9 @@ await client.orders.update(cart.id, {
}, options);
// Checkout flow
-await client.orders.next(cart.id, options); // Move to next step
-await client.orders.advance(cart.id, options); // Advance through all steps
-await client.orders.complete(cart.id, options); // Complete the order
+await client.store.orders.next(cart.id, options); // Move to next step
+await client.store.orders.advance(cart.id, options); // Advance through all steps
+await client.store.orders.complete(cart.id, options); // Complete the order
```
### Line Items
@@ -243,18 +255,18 @@ await client.orders.complete(cart.id, options); // Complete the order
const options = { orderToken: cart.token };
// Add item
-await client.orders.lineItems.create(cart.id, {
+await client.store.orders.lineItems.create(cart.id, {
variant_id: 'var_123',
quantity: 2,
}, options);
// Update item quantity
-await client.orders.lineItems.update(cart.id, lineItemId, {
+await client.store.orders.lineItems.update(cart.id, lineItemId, {
quantity: 3,
}, options);
// Remove item
-await client.orders.lineItems.delete(cart.id, lineItemId, options);
+await client.store.orders.lineItems.delete(cart.id, lineItemId, options);
```
### Coupon Codes
@@ -263,10 +275,10 @@ await client.orders.lineItems.delete(cart.id, lineItemId, options);
const options = { orderToken: cart.token };
// Apply a coupon code
-await client.orders.couponCodes.apply(cart.id, 'SAVE20', options);
+await client.store.orders.couponCodes.apply(cart.id, 'SAVE20', options);
// Remove a coupon code
-await client.orders.couponCodes.remove(cart.id, 'promo_xxx', options);
+await client.store.orders.couponCodes.remove(cart.id, 'promo_xxx', options);
```
### Store Credits
@@ -275,13 +287,13 @@ await client.orders.couponCodes.remove(cart.id, 'promo_xxx', options);
const options = { orderToken: cart.token };
// Apply store credit to order (applies maximum available by default)
-await client.orders.addStoreCredit(cart.id, undefined, options);
+await client.store.orders.addStoreCredit(cart.id, undefined, options);
// Apply specific amount of store credit
-await client.orders.addStoreCredit(cart.id, 25.00, options);
+await client.store.orders.addStoreCredit(cart.id, 25.00, options);
// Remove store credit from order
-await client.orders.removeStoreCredit(cart.id, options);
+await client.store.orders.removeStoreCredit(cart.id, options);
```
### Shipments
@@ -290,10 +302,10 @@ await client.orders.removeStoreCredit(cart.id, options);
const options = { orderToken: cart.token };
// List shipments for an order
-const shipments = await client.orders.shipments.list(cart.id, options);
+const shipments = await client.store.orders.shipments.list(cart.id, options);
// Select a shipping rate
-await client.orders.shipments.update(cart.id, shipmentId, {
+await client.store.orders.shipments.update(cart.id, shipmentId, {
selected_shipping_rate_id: 'rate_xxx',
}, options);
```
@@ -304,23 +316,23 @@ await client.orders.shipments.update(cart.id, shipmentId, {
const options = { orderToken: cart.token };
// Get available payment methods for an order
-const methods = await client.orders.paymentMethods.list(cart.id, options);
+const methods = await client.store.orders.paymentMethods.list(cart.id, options);
// List payments on an order
-const payments = await client.orders.payments.list(cart.id, options);
+const payments = await client.store.orders.payments.list(cart.id, options);
// Get a specific payment
-const payment = await client.orders.payments.get(cart.id, paymentId, options);
+const payment = await client.store.orders.payments.get(cart.id, paymentId, options);
```
### Geography
```typescript
// List countries available for checkout
-const { data: countries } = await client.countries.list();
+const { data: countries } = await client.store.countries.list();
// Get country by ISO code (includes states)
-const usa = await client.countries.get('US');
+const usa = await client.store.countries.get('US');
console.log(usa.states); // Array of states
```
@@ -330,10 +342,10 @@ console.log(usa.states); // Array of states
const options = { token: jwtToken };
// Get profile
-const profile = await client.customer.get(options);
+const profile = await client.store.customer.get(options);
// Update profile
-await client.customer.update({
+await client.store.customer.update({
first_name: 'John',
last_name: 'Doe',
}, options);
@@ -345,13 +357,13 @@ await client.customer.update({
const options = { token: jwtToken };
// List addresses
-const { data: addresses } = await client.customer.addresses.list({}, options);
+const { data: addresses } = await client.store.customer.addresses.list({}, options);
// Get address by ID
-const address = await client.customer.addresses.get('addr_xxx', options);
+const address = await client.store.customer.addresses.get('addr_xxx', options);
// Create address
-await client.customer.addresses.create({
+await client.store.customer.addresses.create({
firstname: 'John',
lastname: 'Doe',
address1: '123 Main St',
@@ -362,10 +374,14 @@ await client.customer.addresses.create({
}, options);
// Update address
-await client.customer.addresses.update('addr_xxx', { city: 'Brooklyn' }, options);
+await client.store.customer.addresses.update('addr_xxx', { city: 'Brooklyn' }, options);
// Delete address
-await client.customer.addresses.delete('addr_xxx', options);
+await client.store.customer.addresses.delete('addr_xxx', options);
+
+// Mark as default billing or shipping address
+await client.store.customer.addresses.markAsDefault('addr_xxx', 'billing', options);
+await client.store.customer.addresses.markAsDefault('addr_xxx', 'shipping', options);
```
### Customer Credit Cards
@@ -374,13 +390,13 @@ await client.customer.addresses.delete('addr_xxx', options);
const options = { token: jwtToken };
// List saved credit cards
-const { data: cards } = await client.customer.creditCards.list({}, options);
+const { data: cards } = await client.store.customer.creditCards.list({}, options);
// Get credit card by ID
-const card = await client.customer.creditCards.get('cc_xxx', options);
+const card = await client.store.customer.creditCards.get('cc_xxx', options);
// Delete credit card
-await client.customer.creditCards.delete('cc_xxx', options);
+await client.store.customer.creditCards.delete('cc_xxx', options);
```
### Wishlists
@@ -389,26 +405,26 @@ await client.customer.creditCards.delete('cc_xxx', options);
const options = { token: jwtToken };
// List wishlists
-const { data: wishlists } = await client.wishlists.list({}, options);
+const { data: wishlists } = await client.store.wishlists.list({}, options);
// Get wishlist by ID
-const wishlist = await client.wishlists.get('wl_xxx', {
+const wishlist = await client.store.wishlists.get('wl_xxx', {
includes: 'wished_items',
}, options);
// Create wishlist
-const newWishlist = await client.wishlists.create({
+const newWishlist = await client.store.wishlists.create({
name: 'Birthday Ideas',
is_private: true,
}, options);
// Update wishlist
-await client.wishlists.update('wl_xxx', {
+await client.store.wishlists.update('wl_xxx', {
name: 'Updated Name',
}, options);
// Delete wishlist
-await client.wishlists.delete('wl_xxx', options);
+await client.store.wishlists.delete('wl_xxx', options);
```
### Wishlist Items
@@ -417,18 +433,18 @@ await client.wishlists.delete('wl_xxx', options);
const options = { token: jwtToken };
// Add item to wishlist
-await client.wishlists.items.create('wl_xxx', {
+await client.store.wishlists.items.create('wl_xxx', {
variant_id: 'var_123',
quantity: 1,
}, options);
// Update item quantity
-await client.wishlists.items.update('wl_xxx', 'wi_xxx', {
+await client.store.wishlists.items.update('wl_xxx', 'wi_xxx', {
quantity: 2,
}, options);
// Remove item from wishlist
-await client.wishlists.items.delete('wl_xxx', 'wi_xxx', options);
+await client.store.wishlists.items.delete('wl_xxx', 'wi_xxx', options);
```
## Nested Resources
@@ -437,25 +453,26 @@ The SDK uses a resource builder pattern for nested resources:
| Parent Resource | Nested Resource | Available Methods |
|-----------------|-----------------|-------------------|
-| `orders` | `lineItems` | `create`, `update`, `delete` |
-| `orders` | `payments` | `list`, `get` |
-| `orders` | `paymentMethods` | `list` |
-| `orders` | `shipments` | `list`, `update` |
-| `orders` | `couponCodes` | `apply`, `remove` |
-| `customer` | `addresses` | `list`, `get`, `create`, `update`, `delete` |
-| `customer` | `creditCards` | `list`, `get`, `delete` |
-| `taxons` | `products` | `list` |
-| `wishlists` | `items` | `create`, `update`, `delete` |
+| `store.orders` | `lineItems` | `create`, `update`, `delete` |
+| `store.orders` | `payments` | `list`, `get` |
+| `store.orders` | `paymentMethods` | `list` |
+| `store.orders` | `shipments` | `list`, `update` |
+| `store.orders` | `couponCodes` | `apply`, `remove` |
+| `store.customer` | `addresses` | `list`, `get`, `create`, `update`, `delete`, `markAsDefault` |
+| `store.customer` | `creditCards` | `list`, `get`, `delete` |
+| `store.customer` | `giftCards` | `list`, `get` |
+| `store.taxons` | `products` | `list` |
+| `store.wishlists` | `items` | `create`, `update`, `delete` |
Example:
```typescript
-// Nested resources follow the pattern: client.parent.nested.method(parentId, ...)
-await client.orders.lineItems.create(orderId, params, options);
-await client.orders.payments.list(orderId, options);
-await client.orders.shipments.update(orderId, shipmentId, params, options);
-await client.customer.addresses.list({}, options);
-await client.taxons.products.list(taxonId, params, options);
-await client.wishlists.items.create(wishlistId, params, options);
+// Nested resources follow the pattern: client.store.parent.nested.method(parentId, ...)
+await client.store.orders.lineItems.create(orderId, params, options);
+await client.store.orders.payments.list(orderId, options);
+await client.store.orders.shipments.update(orderId, shipmentId, params, options);
+await client.store.customer.addresses.list({}, options);
+await client.store.taxons.products.list(taxonId, params, options);
+await client.store.wishlists.items.create(wishlistId, params, options);
```
## Localization & Currency
@@ -464,13 +481,13 @@ Pass locale and currency headers with any request:
```typescript
// Set locale and currency per request
-const products = await client.products.list({}, {
+const products = await client.store.products.list({}, {
locale: 'fr',
currency: 'EUR',
});
// Works with all endpoints
-const taxon = await client.taxons.get('categories/clothing', {
+const taxon = await client.store.taxons.get('categories/clothing', {
includes: 'ancestors',
}, {
locale: 'de',
@@ -484,7 +501,7 @@ const taxon = await client.taxons.get('categories/clothing', {
import { SpreeError } from '@spree/sdk';
try {
- await client.products.get('non-existent');
+ await client.store.products.get('non-existent');
} catch (error) {
if (error instanceof SpreeError) {
console.log(error.code); // 'record_not_found'
@@ -513,8 +530,8 @@ import type {
} from '@spree/sdk';
// All responses are fully typed
-const products: PaginatedResponse<StoreProduct> = await client.products.list();
-const taxon: StoreTaxon = await client.taxons.get('clothing');
+const products: PaginatedResponse<StoreProduct> = await client.store.products.list();
+const taxon: StoreTaxon = await client.store.taxons.get('clothing');
```
## Available Types
@@ -541,6 +558,7 @@ The SDK exports all Store API types:
- `StoreShippingRate` - Shipping rate option
- `StoreShippingMethod` - Shipping method
- `StoreCreditCard` - Saved credit card
+- `StoreGiftCard` - Gift card
### Product Types
- `StoreImage` - Product image
@@ -553,6 +571,14 @@ The SDK exports all Store API types:
- `StoreWishlist` - Wishlist
- `StoreWishedItem` - Wishlist item
+### Client Types
+- `SpreeClient` - Main client class
+- `StoreClient` - Store API client
+- `AdminClient` - Admin API client
+- `SpreeClientConfig` - Client configuration
+- `RequestOptions` - Per-request options
+- `RetryConfig` - Retry behavior configuration
+
### Utility Types
- `PaginatedResponse<T>` - Paginated API response
- `AuthTokens` - JWT tokens from login
@@ -568,7 +594,7 @@ import { createSpreeClient } from '@spree/sdk';
const client = createSpreeClient({
baseUrl: 'https://api.mystore.com',
- apiKey: 'your-api-key',
+ publishableKey: 'spree_pk_xxx',
fetch: customFetchImplementation,
});
```
diff --git a/packages/sdk/console.ts b/packages/sdk/console.ts
index 57c7acfeeb..0e3ebb2567 100644
--- a/packages/sdk/console.ts
+++ b/packages/sdk/console.ts
@@ -2,15 +2,15 @@ import * as repl from 'node:repl';
import { createSpreeClient, SpreeError } from './src';
const baseUrl = process.env.SPREE_URL || 'http://localhost:3000';
-const apiKey = process.env.SPREE_API_KEY || '';
+const publishableKey = process.env.SPREE_PUBLISHABLE_KEY || '';
-if (!apiKey) {
- console.log('Usage: SPREE_API_KEY=spree_pk_xxx npx tsx console.ts');
- console.log(' SPREE_API_KEY=spree_pk_xxx SPREE_URL=https://api.mystore.com npx tsx console.ts');
+if (!publishableKey) {
+ console.log('Usage: SPREE_PUBLISHABLE_KEY=spree_pk_xxx npx tsx console.ts');
+ console.log(' SPREE_PUBLISHABLE_KEY=spree_pk_xxx SPREE_URL=https://api.mystore.com npx tsx console.ts');
console.log('');
}
-const client = createSpreeClient({ baseUrl, apiKey });
+const client = createSpreeClient({ baseUrl, publishableKey });
console.log('Spree SDK Console');
console.log(`Connected to: ${baseUrl}`);
@@ -20,10 +20,10 @@ console.log(' client - SpreeClient instance');
console.log(' createSpreeClient - Create new client');
console.log('');
console.log('Examples:');
-console.log(' await client.store.get()');
-console.log(' await client.products.list()');
-console.log(' await client.products.get("my-product", {}, { locale: "fr" })');
-console.log(' await client.taxons.get("categories/clothing", {}, { currency: "EUR" })');
+console.log(' await client.store.store.get()');
+console.log(' await client.store.products.list()');
+console.log(' await client.store.products.get("my-product", {}, { locale: "fr" })');
+console.log(' await client.store.taxons.get("categories/clothing", {}, { currency: "EUR" })');
console.log('');
const r = repl.start({ prompt: 'spree> ', useGlobal: true });
diff --git a/packages/sdk/package.json b/packages/sdk/package.json
index cdf7872354..2a004178c8 100644
--- a/packages/sdk/package.json
+++ b/packages/sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@spree/sdk",
- "version": "0.1.8",
+ "version": "0.2.0",
"description": "Official TypeScript SDK for Spree Commerce API",
"type": "module",
"main": "./dist/index.cjs",
diff --git a/packages/sdk/src/admin-client.ts b/packages/sdk/src/admin-client.ts
new file mode 100644
index 0000000000..591c3530d0
--- /dev/null
+++ b/packages/sdk/src/admin-client.ts
@@ -0,0 +1,13 @@
+import type { RequestFn } from './request';
+
+export class AdminClient {
+ /** @internal */
+ private readonly request: RequestFn;
+
+ constructor(request: RequestFn) {
+ this.request = request;
+
+ // Prevent "unused" TS error — will be used as admin endpoints are added
+ void this.request;
+ }
+}
diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts
index 33a3e99f4c..a0177dcba3 100644
--- a/packages/sdk/src/client.ts
+++ b/packages/sdk/src/client.ts
@@ -1,107 +1,40 @@
-import type {
- AuthTokens,
- LoginCredentials,
- RegisterParams,
- ErrorResponse,
- PaginatedResponse,
- ListParams,
- ProductListParams,
- ProductFiltersParams,
- ProductFiltersResponse,
- TaxonListParams,
- OrderListParams,
- AddLineItemParams,
- UpdateLineItemParams,
- UpdateOrderParams,
- AddressParams,
- StoreCreditCard,
- StoreGiftCard,
- StoreProduct,
- StoreOrder,
- StoreLineItem,
- StoreCountry,
- StoreTaxonomy,
- StoreTaxon,
- StorePayment,
- StorePaymentMethod,
- StoreShipment,
- StoreStore,
- StoreWishlist,
- StoreWishedItem,
- StoreAddress,
- StoreCustomer,
-} from './types';
+import { createRequestFn } from './request';
+import type { RetryConfig, RequestConfig } from './request';
+import { StoreClient } from './store-client';
+import { AdminClient } from './admin-client';
// Re-export types for convenience
-export type { AddressParams, StoreCreditCard };
-
-export interface RetryConfig {
- /** Maximum number of retries (default: 2) */
- maxRetries?: number;
- /** HTTP status codes to retry on (default: [429, 500, 502, 503, 504]) */
- retryOnStatus?: number[];
- /** Base delay in ms for exponential backoff (default: 300) */
- baseDelay?: number;
- /** Maximum delay in ms (default: 10000) */
- maxDelay?: number;
- /** Whether to retry on network errors (default: true) */
- retryOnNetworkError?: boolean;
-}
+export type { AddressParams, StoreCreditCard } from './types';
export interface SpreeClientConfig {
/** Base URL of the Spree API (e.g., 'https://api.mystore.com') */
baseUrl: string;
- /** Publishable API key for store access */
- apiKey: string;
+ /** Publishable API key for Store API access */
+ publishableKey: string;
+ /** Secret API key for Admin API access (optional) */
+ secretKey?: string;
/** Custom fetch implementation (optional, defaults to global fetch) */
fetch?: typeof fetch;
/** Retry configuration. Enabled by default. Pass false to disable. */
retry?: RetryConfig | false;
}
-export interface RequestOptions {
- /** Bearer token for authenticated requests */
- token?: string;
- /** Order token for guest checkout */
- orderToken?: string;
- /** Locale for translated content (e.g., 'en', 'fr') */
- locale?: string;
- /** Currency for prices (e.g., 'USD', 'EUR') */
- currency?: string;
- /** Custom headers */
- headers?: Record<string, string>;
-}
-
-export class SpreeError extends Error {
- public readonly code: string;
- public readonly status: number;
- public readonly details?: Record<string, string[]>;
-
- constructor(response: ErrorResponse, status: number) {
- super(response.error.message);
- this.name = 'SpreeError';
- this.code = response.error.code;
- this.status = status;
- this.details = response.error.details;
- }
-}
-
export class SpreeClient {
- private readonly baseUrl: string;
- private readonly apiKey: string;
- private readonly fetchFn: typeof fetch;
- private readonly retryConfig: Required<RetryConfig> | false;
+ /** Store API — customer-facing endpoints (products, cart, checkout, account) */
+ readonly store: StoreClient;
+ /** Admin API — administrative endpoints (manage orders, products, settings) */
+ readonly admin: AdminClient;
constructor(config: SpreeClientConfig) {
- this.baseUrl = config.baseUrl.replace(/\/$/, '');
- this.apiKey = config.apiKey;
+ const baseUrl = config.baseUrl.replace(/\/$/, '');
// Bind fetch to globalThis to avoid "Illegal invocation" errors in browsers
- this.fetchFn = config.fetch || fetch.bind(globalThis);
+ const fetchFn = config.fetch || fetch.bind(globalThis);
+ let retryConfig: Required<RetryConfig> | false;
if (config.retry === false) {
- this.retryConfig = false;
+ retryConfig = false;
} else {
- this.retryConfig = {
+ retryConfig = {
maxRetries: config.retry?.maxRetries ?? 2,
retryOnStatus: config.retry?.retryOnStatus ?? [429, 500, 502, 503, 504],
baseDelay: config.retry?.baseDelay ?? 300,
@@ -109,861 +42,27 @@ export class SpreeClient {
retryOnNetworkError: config.retry?.retryOnNetworkError ?? true,
};
}
- }
- private calculateDelay(attempt: number, config: Required<RetryConfig>): number {
- const exponentialDelay = config.baseDelay * Math.pow(2, attempt);
- const jitter = Math.random() * config.baseDelay;
- return Math.min(exponentialDelay + jitter, config.maxDelay);
- }
+ const requestConfig: RequestConfig = { baseUrl, fetchFn, retryConfig };
- private sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms));
- }
-
- private shouldRetryOnStatus(method: string, status: number, config: Required<RetryConfig>): boolean {
- const isIdempotent = method === 'GET' || method === 'HEAD';
- // Idempotent methods: retry on all configured statuses
- // Non-idempotent: only retry on 429 (rate limit)
- if (isIdempotent) {
- return config.retryOnStatus.includes(status);
- }
- return status === 429;
- }
-
- private shouldRetryOnNetworkError(method: string, config: Required<RetryConfig>): boolean {
- if (!config.retryOnNetworkError) return false;
- return method === 'GET' || method === 'HEAD';
- }
-
- private async request<T>(
- method: string,
- path: string,
- options: RequestOptions & {
- body?: unknown;
- params?: Record<string, string | number | undefined>;
- } = {}
- ): Promise<T> {
- const { token, orderToken, locale, currency, headers = {}, body, params } = options;
-
- // Build URL with query params
- const url = new URL(`${this.baseUrl}/api/v3/store${path}`);
- if (params) {
- Object.entries(params).forEach(([key, value]) => {
- if (value !== undefined) {
- // Handle arrays by appending each value with the same key (Rails-style)
- if (Array.isArray(value)) {
- value.forEach((v) => url.searchParams.append(key, String(v)));
- } else {
- url.searchParams.set(key, String(value));
- }
- }
- });
- }
- if (orderToken) {
- url.searchParams.set('order_token', orderToken);
- }
-
- // Build headers
- const requestHeaders: Record<string, string> = {
- 'Content-Type': 'application/json',
- 'x-spree-api-key': this.apiKey,
- ...headers,
- };
-
- if (token) {
- requestHeaders['Authorization'] = `Bearer ${token}`;
- }
-
- if (orderToken) {
- requestHeaders['x-spree-order-token'] = orderToken;
- }
-
- if (locale) {
- requestHeaders['x-spree-locale'] = locale;
- }
+ const storeRequestFn = createRequestFn(
+ requestConfig,
+ '/api/v3/store',
+ { headerName: 'x-spree-api-key', headerValue: config.publishableKey }
+ );
- if (currency) {
- requestHeaders['x-spree-currency'] = currency;
- }
-
- const maxAttempts = this.retryConfig ? this.retryConfig.maxRetries + 1 : 1;
-
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
- try {
- const response = await this.fetchFn(url.toString(), {
- method,
- headers: requestHeaders,
- body: body ? JSON.stringify(body) : undefined,
- });
-
- if (!response.ok) {
- const isLastAttempt = attempt >= maxAttempts - 1;
-
- if (!isLastAttempt && this.retryConfig && this.shouldRetryOnStatus(method, response.status, this.retryConfig)) {
- const retryAfter = response.headers.get('Retry-After');
- const delay = retryAfter
- ? Math.min(parseInt(retryAfter, 10) * 1000, this.retryConfig.maxDelay)
- : this.calculateDelay(attempt, this.retryConfig);
- await this.sleep(delay);
- continue;
- }
-
- const errorBody = await response.json() as ErrorResponse;
- throw new SpreeError(errorBody, response.status);
- }
-
- // Handle 204 No Content
- if (response.status === 204) {
- return undefined as T;
- }
-
- return response.json() as Promise<T>;
- } catch (error) {
- if (error instanceof SpreeError) {
- throw error;
- }
-
- const isLastAttempt = attempt >= maxAttempts - 1;
-
- if (!isLastAttempt && this.retryConfig && this.shouldRetryOnNetworkError(method, this.retryConfig)) {
- const delay = this.calculateDelay(attempt, this.retryConfig);
- await this.sleep(delay);
- continue;
- }
-
- throw error;
+ const adminRequestFn = createRequestFn(
+ requestConfig,
+ '/api/v3/admin',
+ {
+ headerName: 'Authorization',
+ headerValue: config.secretKey ? `Bearer ${config.secretKey}` : '',
}
- }
+ );
- // This should never be reached, but TypeScript needs it
- throw new Error('Unexpected end of retry loop');
+ this.store = new StoreClient(storeRequestFn);
+ this.admin = new AdminClient(adminRequestFn);
}
-
- // ============================================
- // Authentication
- // ============================================
-
- readonly auth = {
- /**
- * Login with email and password
- */
- login: (credentials: LoginCredentials): Promise<AuthTokens> =>
- this.request<AuthTokens>('POST', '/auth/login', { body: credentials }),
-
- /**
- * Register a new customer account
- */
- register: (params: RegisterParams): Promise<AuthTokens> =>
- this.request<AuthTokens>('POST', '/auth/register', { body: params }),
-
- /**
- * Refresh access token (requires valid Bearer token)
- */
- refresh: (options: RequestOptions): Promise<AuthTokens> =>
- this.request<AuthTokens>('POST', '/auth/refresh', options),
- };
-
- // ============================================
- // Store
- // ============================================
-
- readonly store = {
- /**
- * Get current store information
- */
- get: (options?: RequestOptions): Promise<StoreStore> =>
- this.request<StoreStore>('GET', '/store', options),
- };
-
- // ============================================
- // Products
- // ============================================
-
- readonly products = {
- /**
- * List products
- */
- list: (
- params?: ProductListParams,
- options?: RequestOptions
- ): Promise<PaginatedResponse<StoreProduct>> =>
- this.request<PaginatedResponse<StoreProduct>>('GET', '/products', {
- ...options,
- params: params as Record<string, string | number | undefined>,
- }),
-
- /**
- * Get a product by ID or slug
- */
- get: (
- idOrSlug: string,
- params?: { includes?: string },
- options?: RequestOptions
- ): Promise<StoreProduct> =>
- this.request<StoreProduct>('GET', `/products/${idOrSlug}`, {
- ...options,
- params,
- }),
-
- /**
- * Get available filters for products
- * Returns filter options (price range, availability, option types, taxons) with counts
- */
- filters: (
- params?: ProductFiltersParams,
- options?: RequestOptions
- ): Promise<ProductFiltersResponse> =>
- this.request<ProductFiltersResponse>('GET', '/products/filters', {
- ...options,
- params: params as Record<string, string | number | undefined>,
- }),
- };
-
- // ============================================
- // Taxonomies & Taxons
- // ============================================
-
- readonly taxonomies = {
- /**
- * List taxonomies
- */
- list: (
- params?: ListParams,
- options?: RequestOptions
- ): Promise<PaginatedResponse<StoreTaxonomy>> =>
- this.request<PaginatedResponse<StoreTaxonomy>>('GET', '/taxonomies', {
- ...options,
- params: params as Record<string, string | number | undefined>,
- }),
-
- /**
- * Get a taxonomy by ID
- */
- get: (
- id: string,
- params?: { includes?: string },
- options?: RequestOptions
- ): Promise<StoreTaxonomy> =>
- this.request<StoreTaxonomy>('GET', `/taxonomies/${id}`, {
- ...options,
- params,
- }),
- };
-
- readonly taxons = {
- /**
- * List taxons
- */
- list: (
- params?: TaxonListParams,
- options?: RequestOptions
- ): Promise<PaginatedResponse<StoreTaxon>> =>
- this.request<PaginatedResponse<StoreTaxon>>('GET', '/taxons', {
- ...options,
- params: params as Record<string, string | number | undefined>,
- }),
-
- /**
- * Get a taxon by ID or permalink
- */
- get: (
- idOrPermalink: string,
- params?: { includes?: string },
- options?: RequestOptions
- ): Promise<StoreTaxon> =>
- this.request<StoreTaxon>('GET', `/taxons/${idOrPermalink}`, {
- ...options,
- params,
- }),
-
- /**
- * Nested resource: Products in a taxon
- */
- products: {
- /**
- * List products in a taxon
- * @param taxonId - Taxon ID (prefix_id) or permalink
- */
- list: (
- taxonId: string,
- params?: ProductListParams,
- options?: RequestOptions
- ): Promise<PaginatedResponse<StoreProduct>> =>
- this.request<PaginatedResponse<StoreProduct>>(
- 'GET',
- `/taxons/${taxonId}/products`,
- {
- ...options,
- params: params as Record<string, string | number | undefined>,
- }
- ),
- },
- };
-
- // ============================================
- // Geography
- // ============================================
-
- readonly countries = {
- /**
- * List countries available for checkout
- * Returns countries from the store's checkout zone without states
- */
- list: (options?: RequestOptions): Promise<{ data: StoreCountry[] }> =>
- this.request<{ data: StoreCountry[] }>('GET', '/countries', options),
-
- /**
- * Get a country by ISO code with states
- * @param iso - ISO 3166-1 alpha-2 code (e.g., "US", "DE")
- */
- get: (iso: string, options?: RequestOptions): Promise<StoreCountry> =>
- this.request<StoreCountry>('GET', `/countries/${iso}`, options),
- };
-
- // ============================================
- // Cart (convenience wrapper for current incomplete order)
- // ============================================
-
- readonly cart = {
- /**
- * Get current cart (returns null if none exists)
- * Pass orderToken for guest checkout, or use JWT for authenticated users
- */
- get: (options?: RequestOptions): Promise<StoreOrder & { token: string }> =>
- this.request<StoreOrder & { token: string }>('GET', '/cart', options),
-
- /**
- * Create a new cart (alias for orders.create)
- */
- create: (options?: RequestOptions): Promise<StoreOrder & { token: string }> =>
- this.request<StoreOrder & { token: string }>('POST', '/orders', options),
-
- /**
- * Associate a guest cart with the currently authenticated user
- * Requires both JWT token (for authentication) and orderToken (to identify the cart)
- * @param options - Must include both `token` (JWT) and `orderToken` (guest cart token)
- */
- associate: (options: RequestOptions): Promise<StoreOrder & { token: string }> =>
- this.request<StoreOrder & { token: string }>('PATCH', '/cart/associate', options),
- };
-
- // ============================================
- // Orders (all orders - complete and incomplete)
- // ============================================
-
- readonly orders = {
- /**
- * List orders for the authenticated customer
- */
- list: (
- params?: OrderListParams,
- options?: RequestOptions
- ): Promise<PaginatedResponse<StoreOrder>> =>
- this.request<PaginatedResponse<StoreOrder>>('GET', '/orders', {
- ...options,
- params: params as Record<string, string | number | undefined>,
- }),
-
- /**
- * Create a new order (cart)
- */
- create: (options?: RequestOptions): Promise<StoreOrder & { order_token: string }> =>
- this.request<StoreOrder & { order_token: string }>('POST', '/orders', options),
-
- /**
- * Get an order by ID or number
- */
- get: (
- idOrNumber: string,
- params?: { includes?: string },
- options?: RequestOptions
- ): Promise<StoreOrder> =>
- this.request<StoreOrder>('GET', `/orders/${idOrNumber}`, {
- ...options,
- params,
- }),
-
- /**
- * Update an order
- */
- update: (
- idOrNumber: string,
- params: UpdateOrderParams,
- options?: RequestOptions
- ): Promise<StoreOrder> =>
- this.request<StoreOrder>('PATCH', `/orders/${idOrNumber}`, {
- ...options,
- body: params,
- }),
-
- /**
- * Advance order to next checkout step
- */
- next: (idOrNumber: string, options?: RequestOptions): Promise<StoreOrder> =>
- this.request<StoreOrder>('PATCH', `/orders/${idOrNumber}/next`, options),
-
- /**
- * Advance through all checkout steps
- */
- advance: (idOrNumber: string, options?: RequestOptions): Promise<StoreOrder> =>
- this.request<StoreOrder>('PATCH', `/orders/${idOrNumber}/advance`, options),
-
- /**
- * Complete the order
- */
- complete: (idOrNumber: string, options?: RequestOptions): Promise<StoreOrder> =>
- this.request<StoreOrder>('PATCH', `/orders/${idOrNumber}/complete`, options),
-
- /**
- * Add store credit to order
- */
- addStoreCredit: (
- idOrNumber: string,
- amount?: number,
- options?: RequestOptions
- ): Promise<StoreOrder> =>
- this.request<StoreOrder>('POST', `/orders/${idOrNumber}/store_credits`, {
- ...options,
- body: amount ? { amount } : undefined,
- }),
-
- /**
- * Remove store credit from order
- */
- removeStoreCredit: (
- idOrNumber: string,
- options?: RequestOptions
- ): Promise<StoreOrder> =>
- this.request<StoreOrder>('DELETE', `/orders/${idOrNumber}/store_credits`, options),
-
- /**
- * Nested resource: Line items
- */
- lineItems: {
- /**
- * Add a line item to an order
- */
- create: (
- orderId: string,
- params: AddLineItemParams,
- options?: RequestOptions
- ): Promise<StoreLineItem> =>
- this.request<StoreLineItem>('POST', `/orders/${orderId}/line_items`, {
- ...options,
- body: params,
- }),
-
- /**
- * Update a line item
- */
- update: (
- orderId: string,
- lineItemId: string,
- params: UpdateLineItemParams,
- options?: RequestOptions
- ): Promise<StoreLineItem> =>
- this.request<StoreLineItem>(
- 'PATCH',
- `/orders/${orderId}/line_items/${lineItemId}`,
- { ...options, body: params }
- ),
-
- /**
- * Remove a line item from an order
- */
- delete: (
- orderId: string,
- lineItemId: string,
- options?: RequestOptions
- ): Promise<void> =>
- this.request<void>(
- 'DELETE',
- `/orders/${orderId}/line_items/${lineItemId}`,
- options
- ),
- },
-
- /**
- * Nested resource: Payments
- */
- payments: {
- /**
- * List payments for an order
- */
- list: (
- orderId: string,
- options?: RequestOptions
- ): Promise<{ data: StorePayment[]; meta: object }> =>
- this.request<{ data: StorePayment[]; meta: object }>(
- 'GET',
- `/orders/${orderId}/payments`,
- options
- ),
-
- /**
- * Get a payment by ID
- */
- get: (
- orderId: string,
- paymentId: string,
- options?: RequestOptions
- ): Promise<StorePayment> =>
- this.request<StorePayment>(
- 'GET',
- `/orders/${orderId}/payments/${paymentId}`,
- options
- ),
- },
-
- /**
- * Nested resource: Payment methods
- */
- paymentMethods: {
- /**
- * List available payment methods for an order
- */
- list: (
- orderId: string,
- options?: RequestOptions
- ): Promise<PaginatedResponse<StorePaymentMethod>> =>
- this.request<PaginatedResponse<StorePaymentMethod>>(
- 'GET',
- `/orders/${orderId}/payment_methods`,
- options
- ),
- },
-
- /**
- * Nested resource: Coupon codes
- */
- couponCodes: {
- /**
- * Apply a coupon code to an order
- */
- apply: (
- orderId: string,
- code: string,
- options?: RequestOptions
- ): Promise<StoreOrder> =>
- this.request<StoreOrder>('POST', `/orders/${orderId}/coupon_codes`, {
- ...options,
- body: { code },
- }),
-
- /**
- * Remove a coupon code from an order
- * @param promotionId - The promotion prefix_id (e.g., 'promo_xxx')
- */
- remove: (
- orderId: string,
- promotionId: string,
- options?: RequestOptions
- ): Promise<StoreOrder> =>
- this.request<StoreOrder>(
- 'DELETE',
- `/orders/${orderId}/coupon_codes/${promotionId}`,
- options
- ),
- },
-
- /**
- * Nested resource: Shipments
- */
- shipments: {
- /**
- * List shipments for an order
- */
- list: (
- orderId: string,
- options?: RequestOptions
- ): Promise<{ data: StoreShipment[] }> =>
- this.request<{ data: StoreShipment[] }>(
- 'GET',
- `/orders/${orderId}/shipments`,
- options
- ),
-
- /**
- * Update a shipment (e.g., select shipping rate)
- */
- update: (
- orderId: string,
- shipmentId: string,
- params: { selected_shipping_rate_id: string },
- options?: RequestOptions
- ): Promise<StoreShipment> =>
- this.request<StoreShipment>(
- 'PATCH',
- `/orders/${orderId}/shipments/${shipmentId}`,
- { ...options, body: params }
- ),
- },
- };
-
- // ============================================
- // Customer
- // ============================================
-
- readonly customer = {
- /**
- * Get current customer profile
- */
- get: (options?: RequestOptions): Promise<StoreCustomer> =>
- this.request<StoreCustomer>('GET', '/customer', options),
-
- /**
- * Update current customer profile
- */
- update: (
- params: {
- first_name?: string
- last_name?: string
- email?: string
- password?: string
- password_confirmation?: string
- accepts_email_marketing?: boolean
- phone?: string
- },
- options?: RequestOptions
- ): Promise<StoreCustomer> =>
- this.request<StoreCustomer>('PATCH', '/customer', {
- ...options,
- body: params,
- }),
-
- /**
- * Nested resource: Addresses
- */
- addresses: {
- /**
- * List customer addresses
- */
- list: (
- params?: ListParams,
- options?: RequestOptions
- ): Promise<PaginatedResponse<StoreAddress>> =>
- this.request<PaginatedResponse<StoreAddress>>(
- 'GET',
- '/customer/addresses',
- { ...options, params: params as Record<string, string | number | undefined> }
- ),
-
- /**
- * Get an address by ID
- */
- get: (id: string, options?: RequestOptions): Promise<StoreAddress> =>
- this.request<StoreAddress>('GET', `/customer/addresses/${id}`, options),
-
- /**
- * Create an address
- */
- create: (
- params: AddressParams,
- options?: RequestOptions
- ): Promise<StoreAddress> =>
- this.request<StoreAddress>('POST', '/customer/addresses', {
- ...options,
- body: params,
- }),
-
- /**
- * Update an address
- */
- update: (
- id: string,
- params: Partial<AddressParams>,
- options?: RequestOptions
- ): Promise<StoreAddress> =>
- this.request<StoreAddress>('PATCH', `/customer/addresses/${id}`, {
- ...options,
- body: params,
- }),
-
- /**
- * Delete an address
- */
- delete: (id: string, options?: RequestOptions): Promise<void> =>
- this.request<void>('DELETE', `/customer/addresses/${id}`, options),
-
- /**
- * Mark an address as default billing or shipping
- */
- markAsDefault: (
- id: string,
- kind: 'billing' | 'shipping',
- options?: RequestOptions
- ): Promise<StoreAddress> =>
- this.request<StoreAddress>('PATCH', `/customer/addresses/${id}/mark_as_default`, {
- ...options,
- body: { kind },
- }),
- },
-
- /**
- * Nested resource: Credit Cards
- */
- creditCards: {
- /**
- * List customer credit cards
- */
- list: (
- params?: ListParams,
- options?: RequestOptions
- ): Promise<PaginatedResponse<StoreCreditCard>> =>
- this.request<PaginatedResponse<StoreCreditCard>>(
- 'GET',
- '/customer/credit_cards',
- { ...options, params: params as Record<string, string | number | undefined> }
- ),
-
- /**
- * Get a credit card by ID
- */
- get: (id: string, options?: RequestOptions): Promise<StoreCreditCard> =>
- this.request<StoreCreditCard>('GET', `/customer/credit_cards/${id}`, options),
-
- /**
- * Delete a credit card
- */
- delete: (id: string, options?: RequestOptions): Promise<void> =>
- this.request<void>('DELETE', `/customer/credit_cards/${id}`, options),
- },
-
- /**
- * Nested resource: Gift Cards
- */
- giftCards: {
- /**
- * List customer gift cards
- * Returns gift cards associated with the current user, ordered by newest first
- */
- list: (
- params?: ListParams,
- options?: RequestOptions
- ): Promise<PaginatedResponse<StoreGiftCard>> =>
- this.request<PaginatedResponse<StoreGiftCard>>(
- 'GET',
- '/customer/gift_cards',
- { ...options, params: params as Record<string, string | number | undefined> }
- ),
-
- /**
- * Get a gift card by ID
- */
- get: (id: string, options?: RequestOptions): Promise<StoreGiftCard> =>
- this.request<StoreGiftCard>('GET', `/customer/gift_cards/${id}`, options),
- },
- };
-
- // ============================================
- // Wishlists
- // ============================================
-
- readonly wishlists = {
- /**
- * List wishlists
- */
- list: (
- params?: ListParams,
- options?: RequestOptions
- ): Promise<PaginatedResponse<StoreWishlist>> =>
- this.request<PaginatedResponse<StoreWishlist>>('GET', '/wishlists', {
- ...options,
- params: params as Record<string, string | number | undefined>,
- }),
-
- /**
- * Get a wishlist by ID
- */
- get: (
- id: string,
- params?: { includes?: string },
- options?: RequestOptions
- ): Promise<StoreWishlist> =>
- this.request<StoreWishlist>('GET', `/wishlists/${id}`, {
- ...options,
- params,
- }),
-
- /**
- * Create a wishlist
- */
- create: (
- params: { name: string; is_private?: boolean; is_default?: boolean },
- options?: RequestOptions
- ): Promise<StoreWishlist> =>
- this.request<StoreWishlist>('POST', '/wishlists', {
- ...options,
- body: params,
- }),
-
- /**
- * Update a wishlist
- */
- update: (
- id: string,
- params: { name?: string; is_private?: boolean; is_default?: boolean },
- options?: RequestOptions
- ): Promise<StoreWishlist> =>
- this.request<StoreWishlist>('PATCH', `/wishlists/${id}`, {
- ...options,
- body: params,
- }),
-
- /**
- * Delete a wishlist
- */
- delete: (id: string, options?: RequestOptions): Promise<void> =>
- this.request<void>('DELETE', `/wishlists/${id}`, options),
-
- /**
- * Nested resource: Wishlist items
- */
- items: {
- /**
- * Add an item to a wishlist
- */
- create: (
- wishlistId: string,
- params: { variant_id: string; quantity?: number },
- options?: RequestOptions
- ): Promise<StoreWishedItem> =>
- this.request<StoreWishedItem>('POST', `/wishlists/${wishlistId}/items`, {
- ...options,
- body: params,
- }),
-
- /**
- * Update a wishlist item
- */
- update: (
- wishlistId: string,
- itemId: string,
- params: { quantity: number },
- options?: RequestOptions
- ): Promise<StoreWishedItem> =>
- this.request<StoreWishedItem>(
- 'PATCH',
- `/wishlists/${wishlistId}/items/${itemId}`,
- { ...options, body: params }
- ),
-
- /**
- * Remove an item from a wishlist
- */
- delete: (
- wishlistId: string,
- itemId: string,
- options?: RequestOptions
- ): Promise<void> =>
- this.request<void>(
- 'DELETE',
- `/wishlists/${wishlistId}/items/${itemId}`,
- options
- ),
- },
- };
}
/**
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
index 5b1d920369..af1d5f38c0 100644
--- a/packages/sdk/src/index.ts
+++ b/packages/sdk/src/index.ts
@@ -1,6 +1,14 @@
// Main client
-export { SpreeClient, SpreeError, createSpreeClient } from './client';
-export type { SpreeClientConfig, RequestOptions, RetryConfig } from './client';
+export { SpreeClient, createSpreeClient } from './client';
+export type { SpreeClientConfig } from './client';
+
+// Sub-clients
+export { StoreClient } from './store-client';
+export { AdminClient } from './admin-client';
+
+// Request infrastructure
+export { SpreeError } from './request';
+export type { RequestOptions, RetryConfig } from './request';
// All types
export * from './types';
diff --git a/packages/sdk/src/request.ts b/packages/sdk/src/request.ts
new file mode 100644
index 0000000000..7f8e44d695
--- /dev/null
+++ b/packages/sdk/src/request.ts
@@ -0,0 +1,195 @@
+import type { ErrorResponse } from './types';
+
+export interface RetryConfig {
+ /** Maximum number of retries (default: 2) */
+ maxRetries?: number;
+ /** HTTP status codes to retry on (default: [429, 500, 502, 503, 504]) */
+ retryOnStatus?: number[];
+ /** Base delay in ms for exponential backoff (default: 300) */
+ baseDelay?: number;
+ /** Maximum delay in ms (default: 10000) */
+ maxDelay?: number;
+ /** Whether to retry on network errors (default: true) */
+ retryOnNetworkError?: boolean;
+}
+
+export interface RequestOptions {
+ /** Bearer token for authenticated requests */
+ token?: string;
+ /** Order token for guest checkout */
+ orderToken?: string;
+ /** Locale for translated content (e.g., 'en', 'fr') */
+ locale?: string;
+ /** Currency for prices (e.g., 'USD', 'EUR') */
+ currency?: string;
+ /** Custom headers */
+ headers?: Record<string, string>;
+}
+
+export interface InternalRequestOptions extends RequestOptions {
+ body?: unknown;
+ params?: Record<string, string | number | undefined>;
+}
+
+export class SpreeError extends Error {
+ public readonly code: string;
+ public readonly status: number;
+ public readonly details?: Record<string, string[]>;
+
+ constructor(response: ErrorResponse, status: number) {
+ super(response.error.message);
+ this.name = 'SpreeError';
+ this.code = response.error.code;
+ this.status = status;
+ this.details = response.error.details;
+ }
+}
+
+export type RequestFn = <T>(
+ method: string,
+ path: string,
+ options?: InternalRequestOptions
+) => Promise<T>;
+
+function calculateDelay(attempt: number, config: Required<RetryConfig>): number {
+ const exponentialDelay = config.baseDelay * Math.pow(2, attempt);
+ const jitter = Math.random() * config.baseDelay;
+ return Math.min(exponentialDelay + jitter, config.maxDelay);
+}
+
+function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
+function shouldRetryOnStatus(method: string, status: number, config: Required<RetryConfig>): boolean {
+ const isIdempotent = method === 'GET' || method === 'HEAD';
+ if (isIdempotent) {
+ return config.retryOnStatus.includes(status);
+ }
+ return status === 429;
+}
+
+function shouldRetryOnNetworkError(method: string, config: Required<RetryConfig>): boolean {
+ if (!config.retryOnNetworkError) return false;
+ return method === 'GET' || method === 'HEAD';
+}
+
+export interface RequestConfig {
+ baseUrl: string;
+ fetchFn: typeof fetch;
+ retryConfig: Required<RetryConfig> | false;
+}
+
+export interface AuthConfig {
+ headerName: string;
+ headerValue: string;
+}
+
+/**
+ * Creates a bound request function for a specific API scope (store or admin).
+ */
+export function createRequestFn(
+ config: RequestConfig,
+ basePath: string,
+ auth: AuthConfig
+): RequestFn {
+ return async function request<T>(
+ method: string,
+ path: string,
+ options: InternalRequestOptions = {}
+ ): Promise<T> {
+ const { token, orderToken, locale, currency, headers = {}, body, params } = options;
+
+ // Build URL with query params
+ const url = new URL(`${config.baseUrl}${basePath}${path}`);
+ if (params) {
+ Object.entries(params).forEach(([key, value]) => {
+ if (value !== undefined) {
+ if (Array.isArray(value)) {
+ value.forEach((v) => url.searchParams.append(key, String(v)));
+ } else {
+ url.searchParams.set(key, String(value));
+ }
+ }
+ });
+ }
+ if (orderToken) {
+ url.searchParams.set('order_token', orderToken);
+ }
+
+ // Build headers
+ const requestHeaders: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ [auth.headerName]: auth.headerValue,
+ ...headers,
+ };
+
+ if (token) {
+ requestHeaders['Authorization'] = `Bearer ${token}`;
+ }
+
+ if (orderToken) {
+ requestHeaders['x-spree-order-token'] = orderToken;
+ }
+
+ if (locale) {
+ requestHeaders['x-spree-locale'] = locale;
+ }
+
+ if (currency) {
+ requestHeaders['x-spree-currency'] = currency;
+ }
+
+ const maxAttempts = config.retryConfig ? config.retryConfig.maxRetries + 1 : 1;
+
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
+ try {
+ const response = await config.fetchFn(url.toString(), {
+ method,
+ headers: requestHeaders,
+ body: body ? JSON.stringify(body) : undefined,
+ });
+
+ if (!response.ok) {
+ const isLastAttempt = attempt >= maxAttempts - 1;
+
+ if (!isLastAttempt && config.retryConfig && shouldRetryOnStatus(method, response.status, config.retryConfig)) {
+ const retryAfter = response.headers.get('Retry-After');
+ const delay = retryAfter
+ ? Math.min(parseInt(retryAfter, 10) * 1000, config.retryConfig.maxDelay)
+ : calculateDelay(attempt, config.retryConfig);
+ await sleep(delay);
+ continue;
+ }
+
+ const errorBody = await response.json() as ErrorResponse;
+ throw new SpreeError(errorBody, response.status);
+ }
+
+ // Handle 204 No Content
+ if (response.status === 204) {
+ return undefined as T;
+ }
+
+ return response.json() as Promise<T>;
+ } catch (error) {
+ if (error instanceof SpreeError) {
+ throw error;
+ }
+
+ const isLastAttempt = attempt >= maxAttempts - 1;
+
+ if (!isLastAttempt && config.retryConfig && shouldRetryOnNetworkError(method, config.retryConfig)) {
+ const delay = calculateDelay(attempt, config.retryConfig);
+ await sleep(delay);
+ continue;
+ }
+
+ throw error;
+ }
+ }
+
+ // This should never be reached, but TypeScript needs it
+ throw new Error('Unexpected end of retry loop');
+ };
+}
diff --git a/packages/sdk/src/store-client.ts b/packages/sdk/src/store-client.ts
new file mode 100644
index 0000000000..b1ca286114
--- /dev/null
+++ b/packages/sdk/src/store-client.ts
@@ -0,0 +1,766 @@
+import type { RequestFn, RequestOptions } from './request';
+import type {
+ AuthTokens,
+ LoginCredentials,
+ RegisterParams,
+ PaginatedResponse,
+ ListParams,
+ ProductListParams,
+ ProductFiltersParams,
+ ProductFiltersResponse,
+ TaxonListParams,
+ OrderListParams,
+ AddLineItemParams,
+ UpdateLineItemParams,
+ UpdateOrderParams,
+ AddressParams,
+ StoreCreditCard,
+ StoreGiftCard,
+ StoreProduct,
+ StoreOrder,
+ StoreLineItem,
+ StoreCountry,
+ StoreTaxonomy,
+ StoreTaxon,
+ StorePayment,
+ StorePaymentMethod,
+ StoreShipment,
+ StoreStore,
+ StoreWishlist,
+ StoreWishedItem,
+ StoreAddress,
+ StoreCustomer,
+} from './types';
+
+export class StoreClient {
+ private readonly request: RequestFn;
+
+ constructor(request: RequestFn) {
+ this.request = request;
+ }
+
+ // ============================================
+ // Authentication
+ // ============================================
+
+ readonly auth = {
+ /**
+ * Login with email and password
+ */
+ login: (credentials: LoginCredentials): Promise<AuthTokens> =>
+ this.request<AuthTokens>('POST', '/auth/login', { body: credentials }),
+
+ /**
+ * Register a new customer account
+ */
+ register: (params: RegisterParams): Promise<AuthTokens> =>
+ this.request<AuthTokens>('POST', '/auth/register', { body: params }),
+
+ /**
+ * Refresh access token (requires valid Bearer token)
+ */
+ refresh: (options: RequestOptions): Promise<AuthTokens> =>
+ this.request<AuthTokens>('POST', '/auth/refresh', options),
+ };
+
+ // ============================================
+ // Store
+ // ============================================
+
+ readonly store = {
+ /**
+ * Get current store information
+ */
+ get: (options?: RequestOptions): Promise<StoreStore> =>
+ this.request<StoreStore>('GET', '/store', options),
+ };
+
+ // ============================================
+ // Products
+ // ============================================
+
+ readonly products = {
+ /**
+ * List products
+ */
+ list: (
+ params?: ProductListParams,
+ options?: RequestOptions
+ ): Promise<PaginatedResponse<StoreProduct>> =>
+ this.request<PaginatedResponse<StoreProduct>>('GET', '/products', {
+ ...options,
+ params: params as Record<string, string | number | undefined>,
+ }),
+
+ /**
+ * Get a product by ID or slug
+ */
+ get: (
+ idOrSlug: string,
+ params?: { includes?: string },
+ options?: RequestOptions
+ ): Promise<StoreProduct> =>
+ this.request<StoreProduct>('GET', `/products/${idOrSlug}`, {
+ ...options,
+ params,
+ }),
+
+ /**
+ * Get available filters for products
+ * Returns filter options (price range, availability, option types, taxons) with counts
+ */
+ filters: (
+ params?: ProductFiltersParams,
+ options?: RequestOptions
+ ): Promise<ProductFiltersResponse> =>
+ this.request<ProductFiltersResponse>('GET', '/products/filters', {
+ ...options,
+ params: params as Record<string, string | number | undefined>,
+ }),
+ };
+
+ // ============================================
+ // Taxonomies & Taxons
+ // ============================================
+
+ readonly taxonomies = {
+ /**
+ * List taxonomies
+ */
+ list: (
+ params?: ListParams,
+ options?: RequestOptions
+ ): Promise<PaginatedResponse<StoreTaxonomy>> =>
+ this.request<PaginatedResponse<StoreTaxonomy>>('GET', '/taxonomies', {
+ ...options,
+ params: params as Record<string, string | number | undefined>,
+ }),
+
+ /**
+ * Get a taxonomy by ID
+ */
+ get: (
+ id: string,
+ params?: { includes?: string },
+ options?: RequestOptions
+ ): Promise<StoreTaxonomy> =>
+ this.request<StoreTaxonomy>('GET', `/taxonomies/${id}`, {
+ ...options,
+ params,
+ }),
+ };
+
+ readonly taxons = {
+ /**
+ * List taxons
+ */
+ list: (
+ params?: TaxonListParams,
+ options?: RequestOptions
+ ): Promise<PaginatedResponse<StoreTaxon>> =>
+ this.request<PaginatedResponse<StoreTaxon>>('GET', '/taxons', {
+ ...options,
+ params: params as Record<string, string | number | undefined>,
+ }),
+
+ /**
+ * Get a taxon by ID or permalink
+ */
+ get: (
+ idOrPermalink: string,
+ params?: { includes?: string },
+ options?: RequestOptions
+ ): Promise<StoreTaxon> =>
+ this.request<StoreTaxon>('GET', `/taxons/${idOrPermalink}`, {
+ ...options,
+ params,
+ }),
+
+ /**
+ * Nested resource: Products in a taxon
+ */
+ products: {
+ /**
+ * List products in a taxon
+ * @param taxonId - Taxon ID (prefix_id) or permalink
+ */
+ list: (
+ taxonId: string,
+ params?: ProductListParams,
+ options?: RequestOptions
+ ): Promise<PaginatedResponse<StoreProduct>> =>
+ this.request<PaginatedResponse<StoreProduct>>(
+ 'GET',
+ `/taxons/${taxonId}/products`,
+ {
+ ...options,
+ params: params as Record<string, string | number | undefined>,
+ }
+ ),
+ },
+ };
+
+ // ============================================
+ // Geography
+ // ============================================
+
+ readonly countries = {
+ /**
+ * List countries available for checkout
+ * Returns countries from the store's checkout zone without states
+ */
+ list: (options?: RequestOptions): Promise<{ data: StoreCountry[] }> =>
+ this.request<{ data: StoreCountry[] }>('GET', '/countries', options),
+
+ /**
+ * Get a country by ISO code with states
+ * @param iso - ISO 3166-1 alpha-2 code (e.g., "US", "DE")
+ */
+ get: (iso: string, options?: RequestOptions): Promise<StoreCountry> =>
+ this.request<StoreCountry>('GET', `/countries/${iso}`, options),
+ };
+
+ // ============================================
+ // Cart (convenience wrapper for current incomplete order)
+ // ============================================
+
+ readonly cart = {
+ /**
+ * Get current cart (returns null if none exists)
+ * Pass orderToken for guest checkout, or use JWT for authenticated users
+ */
+ get: (options?: RequestOptions): Promise<StoreOrder & { token: string }> =>
+ this.request<StoreOrder & { token: string }>('GET', '/cart', options),
+
+ /**
+ * Create a new cart (alias for orders.create)
+ */
+ create: (options?: RequestOptions): Promise<StoreOrder & { token: string }> =>
+ this.request<StoreOrder & { token: string }>('POST', '/orders', options),
+
+ /**
+ * Associate a guest cart with the currently authenticated user
+ * Requires both JWT token (for authentication) and orderToken (to identify the cart)
+ * @param options - Must include both `token` (JWT) and `orderToken` (guest cart token)
+ */
+ associate: (options: RequestOptions): Promise<StoreOrder & { token: string }> =>
+ this.request<StoreOrder & { token: string }>('PATCH', '/cart/associate', options),
+ };
+
+ // ============================================
+ // Orders (all orders - complete and incomplete)
+ // ============================================
+
+ readonly orders = {
+ /**
+ * List orders for the authenticated customer
+ */
+ list: (
+ params?: OrderListParams,
+ options?: RequestOptions
+ ): Promise<PaginatedResponse<StoreOrder>> =>
+ this.request<PaginatedResponse<StoreOrder>>('GET', '/orders', {
+ ...options,
+ params: params as Record<string, string | number | undefined>,
+ }),
+
+ /**
+ * Create a new order (cart)
+ */
+ create: (options?: RequestOptions): Promise<StoreOrder & { order_token: string }> =>
+ this.request<StoreOrder & { order_token: string }>('POST', '/orders', options),
+
+ /**
+ * Get an order by ID or number
+ */
+ get: (
+ idOrNumber: string,
+ params?: { includes?: string },
+ options?: RequestOptions
+ ): Promise<StoreOrder> =>
+ this.request<StoreOrder>('GET', `/orders/${idOrNumber}`, {
+ ...options,
+ params,
+ }),
+
+ /**
+ * Update an order
+ */
+ update: (
+ idOrNumber: string,
+ params: UpdateOrderParams,
+ options?: RequestOptions
+ ): Promise<StoreOrder> =>
+ this.request<StoreOrder>('PATCH', `/orders/${idOrNumber}`, {
+ ...options,
+ body: params,
+ }),
+
+ /**
+ * Advance order to next checkout step
+ */
+ next: (idOrNumber: string, options?: RequestOptions): Promise<StoreOrder> =>
+ this.request<StoreOrder>('PATCH', `/orders/${idOrNumber}/next`, options),
+
+ /**
+ * Advance through all checkout steps
+ */
+ advance: (idOrNumber: string, options?: RequestOptions): Promise<StoreOrder> =>
+ this.request<StoreOrder>('PATCH', `/orders/${idOrNumber}/advance`, options),
+
+ /**
+ * Complete the order
+ */
+ complete: (idOrNumber: string, options?: RequestOptions): Promise<StoreOrder> =>
+ this.request<StoreOrder>('PATCH', `/orders/${idOrNumber}/complete`, options),
+
+ /**
+ * Add store credit to order
+ */
+ addStoreCredit: (
+ idOrNumber: string,
+ amount?: number,
+ options?: RequestOptions
+ ): Promise<StoreOrder> =>
+ this.request<StoreOrder>('POST', `/orders/${idOrNumber}/store_credits`, {
+ ...options,
+ body: amount ? { amount } : undefined,
+ }),
+
+ /**
+ * Remove store credit from order
+ */
+ removeStoreCredit: (
+ idOrNumber: string,
+ options?: RequestOptions
+ ): Promise<StoreOrder> =>
+ this.request<StoreOrder>('DELETE', `/orders/${idOrNumber}/store_credits`, options),
+
+ /**
+ * Nested resource: Line items
+ */
+ lineItems: {
+ /**
+ * Add a line item to an order
+ */
+ create: (
+ orderId: string,
+ params: AddLineItemParams,
+ options?: RequestOptions
+ ): Promise<StoreLineItem> =>
+ this.request<StoreLineItem>('POST', `/orders/${orderId}/line_items`, {
+ ...options,
+ body: params,
+ }),
+
+ /**
+ * Update a line item
+ */
+ update: (
+ orderId: string,
+ lineItemId: string,
+ params: UpdateLineItemParams,
+ options?: RequestOptions
+ ): Promise<StoreLineItem> =>
+ this.request<StoreLineItem>(
+ 'PATCH',
+ `/orders/${orderId}/line_items/${lineItemId}`,
+ { ...options, body: params }
+ ),
+
+ /**
+ * Remove a line item from an order
+ */
+ delete: (
+ orderId: string,
+ lineItemId: string,
+ options?: RequestOptions
+ ): Promise<void> =>
+ this.request<void>(
+ 'DELETE',
+ `/orders/${orderId}/line_items/${lineItemId}`,
+ options
+ ),
+ },
+
+ /**
+ * Nested resource: Payments
+ */
+ payments: {
+ /**
+ * List payments for an order
+ */
+ list: (
+ orderId: string,
+ options?: RequestOptions
+ ): Promise<{ data: StorePayment[]; meta: object }> =>
+ this.request<{ data: StorePayment[]; meta: object }>(
+ 'GET',
+ `/orders/${orderId}/payments`,
+ options
+ ),
+
+ /**
+ * Get a payment by ID
+ */
+ get: (
+ orderId: string,
+ paymentId: string,
+ options?: RequestOptions
+ ): Promise<StorePayment> =>
+ this.request<StorePayment>(
+ 'GET',
+ `/orders/${orderId}/payments/${paymentId}`,
+ options
+ ),
+ },
+
+ /**
+ * Nested resource: Payment methods
+ */
+ paymentMethods: {
+ /**
+ * List available payment methods for an order
+ */
+ list: (
+ orderId: string,
+ options?: RequestOptions
+ ): Promise<PaginatedResponse<StorePaymentMethod>> =>
+ this.request<PaginatedResponse<StorePaymentMethod>>(
+ 'GET',
+ `/orders/${orderId}/payment_methods`,
+ options
+ ),
+ },
+
+ /**
+ * Nested resource: Coupon codes
+ */
+ couponCodes: {
+ /**
+ * Apply a coupon code to an order
+ */
+ apply: (
+ orderId: string,
+ code: string,
+ options?: RequestOptions
+ ): Promise<StoreOrder> =>
+ this.request<StoreOrder>('POST', `/orders/${orderId}/coupon_codes`, {
+ ...options,
+ body: { code },
+ }),
+
+ /**
+ * Remove a coupon code from an order
+ * @param promotionId - The promotion prefix_id (e.g., 'promo_xxx')
+ */
+ remove: (
+ orderId: string,
+ promotionId: string,
+ options?: RequestOptions
+ ): Promise<StoreOrder> =>
+ this.request<StoreOrder>(
+ 'DELETE',
+ `/orders/${orderId}/coupon_codes/${promotionId}`,
+ options
+ ),
+ },
+
+ /**
+ * Nested resource: Shipments
+ */
+ shipments: {
+ /**
+ * List shipments for an order
+ */
+ list: (
+ orderId: string,
+ options?: RequestOptions
+ ): Promise<{ data: StoreShipment[] }> =>
+ this.request<{ data: StoreShipment[] }>(
+ 'GET',
+ `/orders/${orderId}/shipments`,
+ options
+ ),
+
+ /**
+ * Update a shipment (e.g., select shipping rate)
+ */
+ update: (
+ orderId: string,
+ shipmentId: string,
+ params: { selected_shipping_rate_id: string },
+ options?: RequestOptions
+ ): Promise<StoreShipment> =>
+ this.request<StoreShipment>(
+ 'PATCH',
+ `/orders/${orderId}/shipments/${shipmentId}`,
+ { ...options, body: params }
+ ),
+ },
+ };
+
+ // ============================================
+ // Customer
+ // ============================================
+
+ readonly customer = {
+ /**
+ * Get current customer profile
+ */
+ get: (options?: RequestOptions): Promise<StoreCustomer> =>
+ this.request<StoreCustomer>('GET', '/customer', options),
+
+ /**
+ * Update current customer profile
+ */
+ update: (
+ params: {
+ first_name?: string
+ last_name?: string
+ email?: string
+ password?: string
+ password_confirmation?: string
+ accepts_email_marketing?: boolean
+ phone?: string
+ },
+ options?: RequestOptions
+ ): Promise<StoreCustomer> =>
+ this.request<StoreCustomer>('PATCH', '/customer', {
+ ...options,
+ body: params,
+ }),
+
+ /**
+ * Nested resource: Addresses
+ */
+ addresses: {
+ /**
+ * List customer addresses
+ */
+ list: (
+ params?: ListParams,
+ options?: RequestOptions
+ ): Promise<PaginatedResponse<StoreAddress>> =>
+ this.request<PaginatedResponse<StoreAddress>>(
+ 'GET',
+ '/customer/addresses',
+ { ...options, params: params as Record<string, string | number | undefined> }
+ ),
+
+ /**
+ * Get an address by ID
+ */
+ get: (id: string, options?: RequestOptions): Promise<StoreAddress> =>
+ this.request<StoreAddress>('GET', `/customer/addresses/${id}`, options),
+
+ /**
+ * Create an address
+ */
+ create: (
+ params: AddressParams,
+ options?: RequestOptions
+ ): Promise<StoreAddress> =>
+ this.request<StoreAddress>('POST', '/customer/addresses', {
+ ...options,
+ body: params,
+ }),
+
+ /**
+ * Update an address
+ */
+ update: (
+ id: string,
+ params: Partial<AddressParams>,
+ options?: RequestOptions
+ ): Promise<StoreAddress> =>
+ this.request<StoreAddress>('PATCH', `/customer/addresses/${id}`, {
+ ...options,
+ body: params,
+ }),
+
+ /**
+ * Delete an address
+ */
+ delete: (id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/customer/addresses/${id}`, options),
+
+ /**
+ * Mark an address as default billing or shipping
+ */
+ markAsDefault: (
+ id: string,
+ kind: 'billing' | 'shipping',
+ options?: RequestOptions
+ ): Promise<StoreAddress> =>
+ this.request<StoreAddress>('PATCH', `/customer/addresses/${id}/mark_as_default`, {
+ ...options,
+ body: { kind },
+ }),
+ },
+
+ /**
+ * Nested resource: Credit Cards
+ */
+ creditCards: {
+ /**
+ * List customer credit cards
+ */
+ list: (
+ params?: ListParams,
+ options?: RequestOptions
+ ): Promise<PaginatedResponse<StoreCreditCard>> =>
+ this.request<PaginatedResponse<StoreCreditCard>>(
+ 'GET',
+ '/customer/credit_cards',
+ { ...options, params: params as Record<string, string | number | undefined> }
+ ),
+
+ /**
+ * Get a credit card by ID
+ */
+ get: (id: string, options?: RequestOptions): Promise<StoreCreditCard> =>
+ this.request<StoreCreditCard>('GET', `/customer/credit_cards/${id}`, options),
+
+ /**
+ * Delete a credit card
+ */
+ delete: (id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/customer/credit_cards/${id}`, options),
+ },
+
+ /**
+ * Nested resource: Gift Cards
+ */
+ giftCards: {
+ /**
+ * List customer gift cards
+ * Returns gift cards associated with the current user, ordered by newest first
+ */
+ list: (
+ params?: ListParams,
+ options?: RequestOptions
+ ): Promise<PaginatedResponse<StoreGiftCard>> =>
+ this.request<PaginatedResponse<StoreGiftCard>>(
+ 'GET',
+ '/customer/gift_cards',
+ { ...options, params: params as Record<string, string | number | undefined> }
+ ),
+
+ /**
+ * Get a gift card by ID
+ */
+ get: (id: string, options?: RequestOptions): Promise<StoreGiftCard> =>
+ this.request<StoreGiftCard>('GET', `/customer/gift_cards/${id}`, options),
+ },
+ };
+
+ // ============================================
+ // Wishlists
+ // ============================================
+
+ readonly wishlists = {
+ /**
+ * List wishlists
+ */
+ list: (
+ params?: ListParams,
+ options?: RequestOptions
+ ): Promise<PaginatedResponse<StoreWishlist>> =>
+ this.request<PaginatedResponse<StoreWishlist>>('GET', '/wishlists', {
+ ...options,
+ params: params as Record<string, string | number | undefined>,
+ }),
+
+ /**
+ * Get a wishlist by ID
+ */
+ get: (
+ id: string,
+ params?: { includes?: string },
+ options?: RequestOptions
+ ): Promise<StoreWishlist> =>
+ this.request<StoreWishlist>('GET', `/wishlists/${id}`, {
+ ...options,
+ params,
+ }),
+
+ /**
+ * Create a wishlist
+ */
+ create: (
+ params: { name: string; is_private?: boolean; is_default?: boolean },
+ options?: RequestOptions
+ ): Promise<StoreWishlist> =>
+ this.request<StoreWishlist>('POST', '/wishlists', {
+ ...options,
+ body: params,
+ }),
+
+ /**
+ * Update a wishlist
+ */
+ update: (
+ id: string,
+ params: { name?: string; is_private?: boolean; is_default?: boolean },
+ options?: RequestOptions
+ ): Promise<StoreWishlist> =>
+ this.request<StoreWishlist>('PATCH', `/wishlists/${id}`, {
+ ...options,
+ body: params,
+ }),
+
+ /**
+ * Delete a wishlist
+ */
+ delete: (id: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/wishlists/${id}`, options),
+
+ /**
+ * Nested resource: Wishlist items
+ */
+ items: {
+ /**
+ * Add an item to a wishlist
+ */
+ create: (
+ wishlistId: string,
+ params: { variant_id: string; quantity?: number },
+ options?: RequestOptions
+ ): Promise<StoreWishedItem> =>
+ this.request<StoreWishedItem>('POST', `/wishlists/${wishlistId}/items`, {
+ ...options,
+ body: params,
+ }),
+
+ /**
+ * Update a wishlist item
+ */
+ update: (
+ wishlistId: string,
+ itemId: string,
+ params: { quantity: number },
+ options?: RequestOptions
+ ): Promise<StoreWishedItem> =>
+ this.request<StoreWishedItem>(
+ 'PATCH',
+ `/wishlists/${wishlistId}/items/${itemId}`,
+ { ...options, body: params }
+ ),
+
+ /**
+ * Remove an item from a wishlist
+ */
+ delete: (
+ wishlistId: string,
+ itemId: string,
+ options?: RequestOptions
+ ): Promise<void> =>
+ this.request<void>(
+ 'DELETE',
+ `/wishlists/${wishlistId}/items/${itemId}`,
+ options
+ ),
+ },
+ };
+}
diff --git a/packages/sdk/tests/auth.test.ts b/packages/sdk/tests/auth.test.ts
index 68beafb3ef..ba148ffc38 100644
--- a/packages/sdk/tests/auth.test.ts
+++ b/packages/sdk/tests/auth.test.ts
@@ -9,7 +9,7 @@ describe('auth', () => {
describe('login', () => {
it('returns auth tokens on successful login', async () => {
const client = createTestClient();
- const result = await client.auth.login({
+ const result = await client.store.auth.login({
password: 'password123',
});
@@ -30,7 +30,7 @@ describe('auth', () => {
const client = createTestClient();
await expect(
- client.auth.login({ email: '[email protected]', password: 'wrong' })
+ client.store.auth.login({ email: '[email protected]', password: 'wrong' })
).rejects.toThrow('Invalid credentials');
});
});
@@ -38,7 +38,7 @@ describe('auth', () => {
describe('register', () => {
it('returns auth tokens on successful registration', async () => {
const client = createTestClient();
- const result = await client.auth.register({
+ const result = await client.store.auth.register({
password: 'password123',
password_confirmation: 'password123',
@@ -68,7 +68,7 @@ describe('auth', () => {
const client = createTestClient();
try {
- await client.auth.register({
+ await client.store.auth.register({
password: 'password123',
password_confirmation: 'password123',
@@ -85,7 +85,7 @@ describe('auth', () => {
describe('refresh', () => {
it('returns new tokens', async () => {
const client = createTestClient();
- const result = await client.auth.refresh({ token: 'old-token' });
+ const result = await client.store.auth.refresh({ token: 'old-token' });
expect(result.token).toBe('refreshed-jwt-token');
});
diff --git a/packages/sdk/tests/cart.test.ts b/packages/sdk/tests/cart.test.ts
index e58ee19ede..65317efb5d 100644
--- a/packages/sdk/tests/cart.test.ts
+++ b/packages/sdk/tests/cart.test.ts
@@ -8,28 +8,28 @@ describe('cart', () => {
describe('get', () => {
it('returns the current cart', async () => {
- const result = await client.cart.get({ token: 'user-jwt' });
+ const result = await client.store.cart.get({ token: 'user-jwt' });
expect(result.id).toBe('order_1');
expect(result.token).toBeDefined();
});
it('works with order token for guest checkout', async () => {
- const result = await client.cart.get({ orderToken: 'guest-token' });
+ const result = await client.store.cart.get({ orderToken: 'guest-token' });
expect(result).toBeDefined();
});
});
describe('create', () => {
it('creates a new cart', async () => {
- const result = await client.cart.create();
+ const result = await client.store.cart.create();
expect(result.token).toBeDefined();
});
});
describe('associate', () => {
it('associates guest cart with authenticated user', async () => {
- const result = await client.cart.associate({
+ const result = await client.store.cart.associate({
token: 'user-jwt',
orderToken: 'guest-token',
});
diff --git a/packages/sdk/tests/client.test.ts b/packages/sdk/tests/client.test.ts
index e3d33b0e63..52b5d97620 100644
--- a/packages/sdk/tests/client.test.ts
+++ b/packages/sdk/tests/client.test.ts
@@ -6,7 +6,7 @@ describe('SpreeClient', () => {
it('creates a client via constructor', () => {
const client = new SpreeClient({
baseUrl: TEST_BASE_URL,
- apiKey: TEST_API_KEY,
+ publishableKey: TEST_API_KEY,
});
expect(client).toBeInstanceOf(SpreeClient);
});
@@ -14,7 +14,7 @@ describe('SpreeClient', () => {
it('creates a client via factory function', () => {
const client = createSpreeClient({
baseUrl: TEST_BASE_URL,
- apiKey: TEST_API_KEY,
+ publishableKey: TEST_API_KEY,
});
expect(client).toBeInstanceOf(SpreeClient);
});
@@ -22,10 +22,10 @@ describe('SpreeClient', () => {
it('strips trailing slash from baseUrl', async () => {
const client = createSpreeClient({
baseUrl: `${TEST_BASE_URL}/`,
- apiKey: TEST_API_KEY,
+ publishableKey: TEST_API_KEY,
});
// Should not throw - the trailing slash is handled
- const store = await client.store.get();
+ const store = await client.store.store.get();
expect(store).toBeDefined();
});
@@ -41,15 +41,15 @@ describe('SpreeClient', () => {
const client = createSpreeClient({
baseUrl: TEST_BASE_URL,
- apiKey: TEST_API_KEY,
+ publishableKey: TEST_API_KEY,
fetch: customFetch,
});
- await client.store.get();
+ await client.store.store.get();
expect(capturedUrl).toContain('/api/v3/store/store');
});
- it('sends x-spree-api-key header on every request', async () => {
+ it('sends x-spree-api-key header on every store request', async () => {
let capturedHeaders: Record<string, string> = {};
const customFetch = async (input: string | URL | Request, init?: RequestInit) => {
capturedHeaders = Object.fromEntries(
@@ -63,11 +63,11 @@ describe('SpreeClient', () => {
const client = createSpreeClient({
baseUrl: TEST_BASE_URL,
- apiKey: 'my-secret-key',
+ publishableKey: 'my-secret-key',
fetch: customFetch,
});
- await client.store.get();
+ await client.store.store.get();
expect(capturedHeaders['x-spree-api-key']).toBe('my-secret-key');
});
@@ -85,11 +85,11 @@ describe('SpreeClient', () => {
const client = createSpreeClient({
baseUrl: TEST_BASE_URL,
- apiKey: TEST_API_KEY,
+ publishableKey: TEST_API_KEY,
fetch: customFetch,
});
- await client.store.get({ token: 'my-jwt-token' });
+ await client.store.store.get({ token: 'my-jwt-token' });
expect(capturedHeaders['Authorization']).toBe('Bearer my-jwt-token');
});
@@ -107,30 +107,40 @@ describe('SpreeClient', () => {
const client = createSpreeClient({
baseUrl: TEST_BASE_URL,
- apiKey: TEST_API_KEY,
+ publishableKey: TEST_API_KEY,
fetch: customFetch,
});
- await client.store.get({ locale: 'fr', currency: 'EUR' });
+ await client.store.store.get({ locale: 'fr', currency: 'EUR' });
expect(capturedHeaders['x-spree-locale']).toBe('fr');
expect(capturedHeaders['x-spree-currency']).toBe('EUR');
});
- it('exposes all resource namespaces', () => {
+ it('exposes store and admin namespaces', () => {
const client = createSpreeClient({
baseUrl: TEST_BASE_URL,
- apiKey: TEST_API_KEY,
+ publishableKey: TEST_API_KEY,
});
- expect(client.auth).toBeDefined();
expect(client.store).toBeDefined();
- expect(client.products).toBeDefined();
- expect(client.taxonomies).toBeDefined();
- expect(client.taxons).toBeDefined();
- expect(client.countries).toBeDefined();
- expect(client.cart).toBeDefined();
- expect(client.orders).toBeDefined();
- expect(client.customer).toBeDefined();
- expect(client.wishlists).toBeDefined();
+ expect(client.admin).toBeDefined();
+ });
+
+ it('exposes all resource namespaces under store', () => {
+ const client = createSpreeClient({
+ baseUrl: TEST_BASE_URL,
+ publishableKey: TEST_API_KEY,
+ });
+
+ expect(client.store.auth).toBeDefined();
+ expect(client.store.store).toBeDefined();
+ expect(client.store.products).toBeDefined();
+ expect(client.store.taxonomies).toBeDefined();
+ expect(client.store.taxons).toBeDefined();
+ expect(client.store.countries).toBeDefined();
+ expect(client.store.cart).toBeDefined();
+ expect(client.store.orders).toBeDefined();
+ expect(client.store.customer).toBeDefined();
+ expect(client.store.wishlists).toBeDefined();
});
});
diff --git a/packages/sdk/tests/customer.test.ts b/packages/sdk/tests/customer.test.ts
index b21af12d28..fd5c5d7b89 100644
--- a/packages/sdk/tests/customer.test.ts
+++ b/packages/sdk/tests/customer.test.ts
@@ -9,14 +9,14 @@ describe('customer', () => {
describe('get', () => {
it('returns customer profile', async () => {
- const result = await client.customer.get(opts);
+ const result = await client.store.customer.get(opts);
expect(result.email).toBe('[email protected]');
});
});
describe('update', () => {
it('updates customer profile', async () => {
- const result = await client.customer.update(
+ const result = await client.store.customer.update(
{ first_name: 'Updated' },
opts
);
@@ -26,17 +26,17 @@ describe('customer', () => {
describe('addresses', () => {
it('lists addresses', async () => {
- const result = await client.customer.addresses.list(undefined, opts);
+ const result = await client.store.customer.addresses.list(undefined, opts);
expect(result.data).toHaveLength(1);
});
it('gets an address by ID', async () => {
- const result = await client.customer.addresses.get('addr_1', opts);
+ const result = await client.store.customer.addresses.get('addr_1', opts);
expect(result.city).toBe('New York');
});
it('creates an address', async () => {
- const result = await client.customer.addresses.create(
+ const result = await client.store.customer.addresses.create(
{
firstname: 'Test',
lastname: 'User',
@@ -51,7 +51,7 @@ describe('customer', () => {
});
it('updates an address', async () => {
- const result = await client.customer.addresses.update(
+ const result = await client.store.customer.addresses.update(
'addr_1',
{ city: 'Updated City' },
opts
@@ -61,37 +61,37 @@ describe('customer', () => {
it('deletes an address', async () => {
await expect(
- client.customer.addresses.delete('addr_1', opts)
+ client.store.customer.addresses.delete('addr_1', opts)
).resolves.toBeUndefined();
});
});
describe('creditCards', () => {
it('lists credit cards', async () => {
- const result = await client.customer.creditCards.list(undefined, opts);
+ const result = await client.store.customer.creditCards.list(undefined, opts);
expect(result.data).toBeDefined();
});
it('gets a credit card', async () => {
- const result = await client.customer.creditCards.get('cc_1', opts);
+ const result = await client.store.customer.creditCards.get('cc_1', opts);
expect(result).toBeDefined();
});
it('deletes a credit card', async () => {
await expect(
- client.customer.creditCards.delete('cc_1', opts)
+ client.store.customer.creditCards.delete('cc_1', opts)
).resolves.toBeUndefined();
});
});
describe('giftCards', () => {
it('lists gift cards', async () => {
- const result = await client.customer.giftCards.list(undefined, opts);
+ const result = await client.store.customer.giftCards.list(undefined, opts);
expect(result.data).toBeDefined();
});
it('gets a gift card', async () => {
- const result = await client.customer.giftCards.get('gc_1', opts);
+ const result = await client.store.customer.giftCards.get('gc_1', opts);
expect(result).toBeDefined();
});
});
diff --git a/packages/sdk/tests/error-handling.test.ts b/packages/sdk/tests/error-handling.test.ts
index 8fcd67a3dc..87fddf2214 100644
--- a/packages/sdk/tests/error-handling.test.ts
+++ b/packages/sdk/tests/error-handling.test.ts
@@ -24,7 +24,7 @@ describe('error handling', () => {
const client = createTestClient();
try {
- await client.products.get('nonexistent');
+ await client.store.products.get('nonexistent');
expect.unreachable('Should have thrown');
} catch (error) {
expect(error).toBeInstanceOf(SpreeError);
@@ -57,7 +57,7 @@ describe('error handling', () => {
const client = createTestClient();
try {
- await client.customer.addresses.create(
+ await client.store.customer.addresses.create(
{ firstname: 'A', lastname: 'B', address1: '', city: '', zipcode: '00000', country_iso: 'US' },
{ token: 'jwt' }
);
@@ -87,7 +87,7 @@ describe('error handling', () => {
const client = createTestClient();
try {
- await client.store.get();
+ await client.store.store.get();
expect.unreachable('Should have thrown');
} catch (error) {
const spreeError = error as SpreeError;
@@ -113,7 +113,7 @@ describe('error handling', () => {
const client = createTestClient();
try {
- await client.customer.get();
+ await client.store.customer.get();
expect.unreachable('Should have thrown');
} catch (error) {
const spreeError = error as SpreeError;
@@ -124,7 +124,7 @@ describe('error handling', () => {
it('handles 204 No Content responses', async () => {
const client = createTestClient();
- const result = await client.orders.lineItems.delete('order_1', 'li_1', { token: 'jwt' });
+ const result = await client.store.orders.lineItems.delete('order_1', 'li_1', { token: 'jwt' });
expect(result).toBeUndefined();
});
});
diff --git a/packages/sdk/tests/helpers.ts b/packages/sdk/tests/helpers.ts
index c08e5bfe04..26c409943b 100644
--- a/packages/sdk/tests/helpers.ts
+++ b/packages/sdk/tests/helpers.ts
@@ -6,6 +6,6 @@ export const TEST_API_KEY = 'test-publishable-key';
export function createTestClient() {
return createSpreeClient({
baseUrl: TEST_BASE_URL,
- apiKey: TEST_API_KEY,
+ publishableKey: TEST_API_KEY,
});
}
diff --git a/packages/sdk/tests/orders.test.ts b/packages/sdk/tests/orders.test.ts
index 589e985494..c7678419bc 100644
--- a/packages/sdk/tests/orders.test.ts
+++ b/packages/sdk/tests/orders.test.ts
@@ -9,7 +9,7 @@ describe('orders', () => {
describe('list', () => {
it('returns paginated orders', async () => {
- const result = await client.orders.list(undefined, opts);
+ const result = await client.store.orders.list(undefined, opts);
expect(result.data).toHaveLength(1);
expect(result.meta.page).toBe(1);
});
@@ -17,21 +17,21 @@ describe('orders', () => {
describe('create', () => {
it('creates a new order and returns order_token', async () => {
- const result = await client.orders.create();
+ const result = await client.store.orders.create();
expect(result.order_token).toBe('new-order-token');
});
});
describe('get', () => {
it('returns an order by number', async () => {
- const result = await client.orders.get('R123456', undefined, opts);
+ const result = await client.store.orders.get('R123456', undefined, opts);
expect(result.number).toBe('R123456');
});
});
describe('update', () => {
it('updates order attributes', async () => {
- const result = await client.orders.update(
+ const result = await client.store.orders.update(
'order_1',
{ email: '[email protected]' },
opts
@@ -42,24 +42,24 @@ describe('orders', () => {
describe('checkout flow', () => {
it('advances to next step', async () => {
- const result = await client.orders.next('order_1', opts);
+ const result = await client.store.orders.next('order_1', opts);
expect(result.state).toBe('address');
});
it('advances through all steps', async () => {
- const result = await client.orders.advance('order_1', opts);
+ const result = await client.store.orders.advance('order_1', opts);
expect(result.state).toBe('complete');
});
it('completes the order', async () => {
- const result = await client.orders.complete('order_1', opts);
+ const result = await client.store.orders.complete('order_1', opts);
expect(result.state).toBe('complete');
});
});
describe('lineItems', () => {
it('creates a line item', async () => {
- const result = await client.orders.lineItems.create(
+ const result = await client.store.orders.lineItems.create(
'order_1',
{ variant_id: 'var_1', quantity: 2 },
opts
@@ -68,7 +68,7 @@ describe('orders', () => {
});
it('updates a line item', async () => {
- const result = await client.orders.lineItems.update(
+ const result = await client.store.orders.lineItems.update(
'order_1',
'li_1',
{ quantity: 5 },
@@ -79,14 +79,14 @@ describe('orders', () => {
it('deletes a line item', async () => {
await expect(
- client.orders.lineItems.delete('order_1', 'li_1', opts)
+ client.store.orders.lineItems.delete('order_1', 'li_1', opts)
).resolves.toBeUndefined();
});
});
describe('couponCodes', () => {
it('applies a coupon code', async () => {
- const result = await client.orders.couponCodes.apply(
+ const result = await client.store.orders.couponCodes.apply(
'order_1',
'SAVE10',
opts
@@ -95,7 +95,7 @@ describe('orders', () => {
});
it('removes a coupon code', async () => {
- const result = await client.orders.couponCodes.remove(
+ const result = await client.store.orders.couponCodes.remove(
'order_1',
'promo_1',
opts
@@ -106,12 +106,12 @@ describe('orders', () => {
describe('shipments', () => {
it('lists shipments', async () => {
- const result = await client.orders.shipments.list('order_1', opts);
+ const result = await client.store.orders.shipments.list('order_1', opts);
expect(result.data).toBeDefined();
});
it('updates a shipment', async () => {
- const result = await client.orders.shipments.update(
+ const result = await client.store.orders.shipments.update(
'order_1',
'ship_1',
{ selected_shipping_rate_id: 'rate_1' },
@@ -123,12 +123,12 @@ describe('orders', () => {
describe('storeCredits', () => {
it('adds store credit', async () => {
- const result = await client.orders.addStoreCredit('order_1', 10, opts);
+ const result = await client.store.orders.addStoreCredit('order_1', 10, opts);
expect(result).toBeDefined();
});
it('removes store credit', async () => {
- const result = await client.orders.removeStoreCredit('order_1', opts);
+ const result = await client.store.orders.removeStoreCredit('order_1', opts);
expect(result).toBeDefined();
});
});
diff --git a/packages/sdk/tests/products.test.ts b/packages/sdk/tests/products.test.ts
index fae7e1d63a..d9afefb108 100644
--- a/packages/sdk/tests/products.test.ts
+++ b/packages/sdk/tests/products.test.ts
@@ -9,7 +9,7 @@ describe('products', () => {
describe('list', () => {
it('returns paginated products', async () => {
- const result = await client.products.list();
+ const result = await client.store.products.list();
expect(result.data).toHaveLength(1);
expect(result.data[0].name).toBe('Test Product');
@@ -18,7 +18,7 @@ describe('products', () => {
});
it('passes query parameters', async () => {
- const result = await client.products.list({
+ const result = await client.store.products.list({
page: 2,
per_page: 10,
'q[name_cont]': 'shirt',
@@ -32,21 +32,21 @@ describe('products', () => {
describe('get', () => {
it('returns a product by slug', async () => {
- const result = await client.products.get('test-product');
+ const result = await client.store.products.get('test-product');
expect(result.name).toBe(fixtures.product.name);
expect(result.slug).toBe('test-product');
});
it('returns a product by ID', async () => {
- const result = await client.products.get('prod_1');
+ const result = await client.store.products.get('prod_1');
expect(result.id).toBe('prod_1');
});
});
describe('filters', () => {
it('returns filter options', async () => {
- const result = await client.products.filters();
+ const result = await client.store.products.filters();
expect(result.filters).toBeDefined();
expect(result.sort_options).toBeDefined();
diff --git a/packages/sdk/tests/retry.test.ts b/packages/sdk/tests/retry.test.ts
index 7e7ca248a2..15a37ebdf8 100644
--- a/packages/sdk/tests/retry.test.ts
+++ b/packages/sdk/tests/retry.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect, vi } from 'vitest';
-import { createSpreeClient, SpreeError } from '../src/client';
+import { createSpreeClient } from '../src/client';
+import { SpreeError } from '../src/request';
function jsonResponse(body: object, status = 200, headers: Record<string, string> = {}): Response {
return new Response(JSON.stringify(body), {
@@ -16,7 +17,7 @@ function errorResponse(status: number, code = 'error', message = 'Error', header
}
describe('Retry logic', () => {
- const baseConfig = { baseUrl: 'https://api.test.com', apiKey: 'pk_test' };
+ const baseConfig = { baseUrl: 'https://api.test.com', publishableKey: 'pk_test' };
describe('GET requests', () => {
it('retries on 500 and succeeds', async () => {
@@ -25,7 +26,7 @@ describe('Retry logic', () => {
.mockResolvedValueOnce(jsonResponse({ name: 'Test Store' }));
const client = createSpreeClient({ ...baseConfig, fetch: mockFetch });
- const result = await client.store.get();
+ const result = await client.store.store.get();
expect(result).toEqual({ name: 'Test Store' });
expect(mockFetch).toHaveBeenCalledTimes(2);
@@ -37,7 +38,7 @@ describe('Retry logic', () => {
.mockResolvedValueOnce(jsonResponse({ name: 'Test Store' }));
const client = createSpreeClient({ ...baseConfig, fetch: mockFetch });
- const result = await client.store.get();
+ const result = await client.store.store.get();
expect(result).toEqual({ name: 'Test Store' });
expect(mockFetch).toHaveBeenCalledTimes(2);
@@ -50,7 +51,7 @@ describe('Retry logic', () => {
.mockResolvedValueOnce(jsonResponse({ name: 'Test Store' }));
const client = createSpreeClient({ ...baseConfig, fetch: mockFetch });
- const result = await client.store.get();
+ const result = await client.store.store.get();
expect(result).toEqual({ name: 'Test Store' });
expect(mockFetch).toHaveBeenCalledTimes(3);
@@ -62,7 +63,7 @@ describe('Retry logic', () => {
const client = createSpreeClient({ ...baseConfig, fetch: mockFetch });
- await expect(client.store.get()).rejects.toThrow(SpreeError);
+ await expect(client.store.store.get()).rejects.toThrow(SpreeError);
// 1 initial + 2 retries = 3 attempts
expect(mockFetch).toHaveBeenCalledTimes(3);
});
@@ -73,7 +74,7 @@ describe('Retry logic', () => {
.mockResolvedValueOnce(jsonResponse({ name: 'Test Store' }));
const client = createSpreeClient({ ...baseConfig, fetch: mockFetch });
- const result = await client.store.get();
+ const result = await client.store.store.get();
expect(result).toEqual({ name: 'Test Store' });
expect(mockFetch).toHaveBeenCalledTimes(2);
@@ -85,7 +86,7 @@ describe('Retry logic', () => {
const client = createSpreeClient({ ...baseConfig, fetch: mockFetch });
- await expect(client.store.get()).rejects.toThrow(SpreeError);
+ await expect(client.store.store.get()).rejects.toThrow(SpreeError);
expect(mockFetch).toHaveBeenCalledTimes(1);
});
@@ -95,7 +96,7 @@ describe('Retry logic', () => {
const client = createSpreeClient({ ...baseConfig, fetch: mockFetch });
- await expect(client.store.get()).rejects.toThrow(SpreeError);
+ await expect(client.store.store.get()).rejects.toThrow(SpreeError);
expect(mockFetch).toHaveBeenCalledTimes(1);
});
});
@@ -107,7 +108,7 @@ describe('Retry logic', () => {
.mockResolvedValueOnce(jsonResponse({ token: 'abc', user: { id: '1', email: '[email protected]' } }));
const client = createSpreeClient({ ...baseConfig, fetch: mockFetch });
- const result = await client.auth.login({ email: '[email protected]', password: 'pass' });
+ const result = await client.store.auth.login({ email: '[email protected]', password: 'pass' });
expect(result.token).toBe('abc');
expect(mockFetch).toHaveBeenCalledTimes(2);
@@ -120,7 +121,7 @@ describe('Retry logic', () => {
const client = createSpreeClient({ ...baseConfig, fetch: mockFetch });
await expect(
- client.auth.login({ email: '[email protected]', password: 'pass' })
+ client.store.auth.login({ email: '[email protected]', password: 'pass' })
).rejects.toThrow(SpreeError);
expect(mockFetch).toHaveBeenCalledTimes(1);
});
@@ -132,7 +133,7 @@ describe('Retry logic', () => {
const client = createSpreeClient({ ...baseConfig, fetch: mockFetch });
await expect(
- client.auth.login({ email: '[email protected]', password: 'pass' })
+ client.store.auth.login({ email: '[email protected]', password: 'pass' })
).rejects.toThrow(TypeError);
expect(mockFetch).toHaveBeenCalledTimes(1);
});
@@ -145,7 +146,7 @@ describe('Retry logic', () => {
const client = createSpreeClient({ ...baseConfig, fetch: mockFetch, retry: false });
- await expect(client.store.get()).rejects.toThrow(SpreeError);
+ await expect(client.store.store.get()).rejects.toThrow(SpreeError);
expect(mockFetch).toHaveBeenCalledTimes(1);
});
});
@@ -161,7 +162,7 @@ describe('Retry logic', () => {
retry: { maxRetries: 4, baseDelay: 10 },
});
- await expect(client.store.get()).rejects.toThrow(SpreeError);
+ await expect(client.store.store.get()).rejects.toThrow(SpreeError);
// 1 initial + 4 retries = 5 attempts
expect(mockFetch).toHaveBeenCalledTimes(5);
});
@@ -178,7 +179,7 @@ describe('Retry logic', () => {
retry: { baseDelay: 10 },
});
- const result = await client.store.get();
+ const result = await client.store.store.get();
const elapsed = Date.now() - start;
expect(result).toEqual({ name: 'Test Store' });
diff --git a/packages/sdk/tests/wishlists.test.ts b/packages/sdk/tests/wishlists.test.ts
index 616d192b16..1115c85df6 100644
--- a/packages/sdk/tests/wishlists.test.ts
+++ b/packages/sdk/tests/wishlists.test.ts
@@ -8,17 +8,17 @@ describe('wishlists', () => {
const opts = { token: 'user-jwt' };
it('lists wishlists', async () => {
- const result = await client.wishlists.list(undefined, opts);
+ const result = await client.store.wishlists.list(undefined, opts);
expect(result.data).toHaveLength(1);
});
it('gets a wishlist', async () => {
- const result = await client.wishlists.get('wl_1', undefined, opts);
+ const result = await client.store.wishlists.get('wl_1', undefined, opts);
expect(result.name).toBe('My Wishlist');
});
it('creates a wishlist', async () => {
- const result = await client.wishlists.create(
+ const result = await client.store.wishlists.create(
{ name: 'My Wishlist' },
opts
);
@@ -26,7 +26,7 @@ describe('wishlists', () => {
});
it('updates a wishlist', async () => {
- const result = await client.wishlists.update(
+ const result = await client.store.wishlists.update(
'wl_1',
{ name: 'Updated Wishlist' },
opts
@@ -36,13 +36,13 @@ describe('wishlists', () => {
it('deletes a wishlist', async () => {
await expect(
- client.wishlists.delete('wl_1', opts)
+ client.store.wishlists.delete('wl_1', opts)
).resolves.toBeUndefined();
});
describe('items', () => {
it('adds an item', async () => {
- const result = await client.wishlists.items.create(
+ const result = await client.store.wishlists.items.create(
'wl_1',
{ variant_id: 'var_1', quantity: 1 },
opts
@@ -51,7 +51,7 @@ describe('wishlists', () => {
});
it('updates an item', async () => {
- const result = await client.wishlists.items.update(
+ const result = await client.store.wishlists.items.update(
'wl_1',
'wi_1',
{ quantity: 3 },
@@ -62,7 +62,7 @@ describe('wishlists', () => {
it('removes an item', async () => {
await expect(
- client.wishlists.items.delete('wl_1', 'wi_1', opts)
+ client.store.wishlists.items.delete('wl_1', 'wi_1', opts)
).resolves.toBeUndefined();
});
});