Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Bootstrap TypeScript SDK client :rocket:
Damian Legawiec51087cdf0bc4
diff --git a/.gitignore b/.gitignoreindex b035a3f022..bfb59ef36f 100644--- a/.gitignore+++ b/.gitignore@@ -59,4 +59,6 @@ TODObrakeman-*.**/app/assets/builds.claude-*/.claude\ No newline at end of file+*/.claude+**/node_modules+**/package-lock.json\ No newline at end of filediff --git a/sdk/.gitignore b/sdk/.gitignorenew file mode 100644index 0000000000..dd6e803c7f--- /dev/null+++ b/sdk/.gitignore@@ -0,0 +1,4 @@+node_modules/+dist/+*.log+.DS_Storediff --git a/sdk/.npmignore b/sdk/.npmignorenew file mode 100644index 0000000000..9112ebbfb7--- /dev/null+++ b/sdk/.npmignore@@ -0,0 +1,6 @@+src/+tsconfig.json+tsup.config.ts+.gitignore+node_modules/+*.logdiff --git a/sdk/README.md b/sdk/README.mdnew file mode 100644index 0000000000..db888969a1--- /dev/null+++ b/sdk/README.md@@ -0,0 +1,292 @@+# @spree/sdk++Official TypeScript SDK for Spree Commerce API v3.++## Installation++```bash+npm install @spree/sdk+# or+yarn add @spree/sdk+# or+pnpm add @spree/sdk+```++## Quick Start++```typescript+import { createSpreeClient } from '@spree/sdk';++// Initialize the client+const spree = createSpreeClient({+ baseUrl: 'https://api.mystore.com',+ apiKey: 'your-publishable-api-key',+});++// Browse products+const products = await spree.products.list({+ per_page: 10,+ includes: 'variants,images',+});++// Get a single product+const product = await spree.products.get('ruby-on-rails-tote');++// Authentication+const tokens = await spree.auth.login({+ email: '[email protected]',+ password: 'password123',+});++// Create a cart+const cart = await spree.orders.create();++// Add items to cart+await spree.lineItems.create(cart.number, {+ variant_id: 'var_abc123',+ quantity: 2,+}, { orderToken: cart.order_token });++// Checkout flow+await spree.orders.next(cart.number, { orderToken: cart.order_token });+await spree.orders.complete(cart.number, { orderToken: cart.order_token });+```++## Authentication++The SDK supports two authentication modes:++### 1. API Key Only (Guest/Public Access)++```typescript+const spree = createSpreeClient({+ baseUrl: 'https://api.mystore.com',+ apiKey: 'pk_your-publishable-key',+});++// Public endpoints work without authentication+const products = await spree.products.list();+```++### 2. API Key + JWT (Authenticated Customer)++```typescript+// Login to get tokens+const tokens = await spree.auth.login({+ email: '[email protected]',+ password: 'password123',+});++// Use token for authenticated requests+const orders = await spree.orders.list({}, { token: tokens.access_token });++// Refresh token when needed+const newTokens = await spree.auth.refresh(tokens.refresh_token);+```++## Guest Checkout++For guest checkout, use the `order_token` returned when creating an order:++```typescript+// Create a cart (guest)+const cart = await spree.orders.create();++// Use orderToken for all cart operations+const options = { orderToken: cart.order_token };++// Add items+await spree.lineItems.create(cart.number, {+ variant_id: 'var_abc123',+ quantity: 1,+}, options);++// Update order with email+await spree.orders.update(cart.number, {+ email: '[email protected]',+}, options);++// Complete checkout+await spree.orders.complete(cart.number, options);+```++## API Reference++### Products++```typescript+// List products with filtering+const products = await spree.products.list({+ page: 1,+ per_page: 25,+ 'q[name_cont]': 'shirt',+ includes: 'variants,images,taxons',+});++// Get single product by ID or slug+const product = await spree.products.get('ruby-on-rails-tote', {+ includes: 'variants,images',+});+```++### Cart & Checkout++```typescript+// Create cart+const cart = await spree.orders.create();++// Add item+await spree.lineItems.create(orderId, {+ variant_id: 'var_123',+ quantity: 2,+});++// Update item quantity+await spree.lineItems.update(orderId, lineItemId, {+ quantity: 3,+});++// Remove item+await spree.lineItems.delete(orderId, lineItemId);++// Update order (email, addresses)+await spree.orders.update(orderId, {+ email: '[email protected]',+ bill_address_attributes: {+ firstname: 'John',+ lastname: 'Doe',+ address1: '123 Main St',+ city: 'New York',+ zipcode: '10001',+ phone: '+1 555 123 4567',+ country_id: 'ctry_usa',+ },+});++// Checkout flow+await spree.orders.next(orderId); // Move to next step+await spree.orders.advance(orderId); // Advance through all steps+await spree.orders.complete(orderId); // Complete the order+```++### Payments++```typescript+// Get available payment methods+const methods = await spree.paymentMethods.list(orderId);++// Create a payment+await spree.payments.create(orderId, {+ payment_method_id: 'pm_credit_card',+ source_attributes: {+ number: '4111111111111111',+ month: '12',+ year: '2025',+ verification_value: '123',+ name: 'John Doe',+ },+});+```++### Geography++```typescript+// List countries+const countries = await spree.countries.list();++// Get country by ISO code+const usa = await spree.countries.get('US');++// List states for a country+const states = await spree.states.list({ country_id: 'ctry_usa' });+```++### Categories (Taxonomies & Taxons)++```typescript+// List taxonomies+const taxonomies = await spree.taxonomies.list();++// Get taxonomy with taxons+const categories = await spree.taxonomies.get('tax_123', {+ includes: 'taxons',+});++// Get single taxon+const taxon = await spree.taxons.get('categories/clothing');+```++### Customer Account++```typescript+// Get profile+const profile = await spree.customer.get({ token });++// Update profile+await spree.customer.update({+ first_name: 'John',+ last_name: 'Doe',+}, { token });++// Manage addresses+const addresses = await spree.addresses.list({}, { token });+await spree.addresses.create({ ... }, { token });+await spree.addresses.update(addressId, { ... }, { token });+await spree.addresses.delete(addressId, { token });+```++### Wishlists++```typescript+// List wishlists+const wishlists = await spree.wishlists.list({}, { token });++// Create wishlist+const wishlist = await spree.wishlists.create({+ name: 'Birthday Ideas',+ is_private: true,+}, { token });++// Add item to wishlist+await spree.wishlists.addItem(wishlistId, {+ variant_id: 'var_123',+}, { token });++// Remove item+await spree.wishlists.removeItem(wishlistId, itemId, { token });+```++## Error Handling++```typescript+import { SpreeError } from '@spree/sdk';++try {+ await spree.products.get('non-existent');+} catch (error) {+ if (error instanceof SpreeError) {+ console.log(error.code); // 'record_not_found'+ console.log(error.message); // 'Product not found'+ console.log(error.status); // 404+ }+}+```++## TypeScript Support++The SDK includes full TypeScript support with generated types from the API serializers:++```typescript+import type {+ StoreProduct,+ StoreOrder,+ StoreVariant,+ PaginatedResponse,+} from '@spree/sdk';++const products: PaginatedResponse<StoreProduct> = await spree.products.list();+```++## License++BSD-3-Clausediff --git a/sdk/console.ts b/sdk/console.tsnew file mode 100644index 0000000000..4f4ae0df32--- /dev/null+++ b/sdk/console.ts@@ -0,0 +1,34 @@+import * as repl from 'node:repl';+import { createSpreeClient, SpreeClient, SpreeError } from './src';++const baseUrl = process.env.SPREE_URL || 'http://localhost:3000';+const apiKey = process.env.SPREE_API_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');+ console.log('');+}++const client = createSpreeClient({ baseUrl, apiKey });++console.log('Spree SDK Console');+console.log(`Connected to: ${baseUrl}`);+console.log('');+console.log('Available:');+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('');++const r = repl.start({ prompt: 'spree> ', useGlobal: true });++// Make await work at top level+r.context.client = client;+r.context.createSpreeClient = createSpreeClient;+r.context.SpreeError = SpreeError;diff --git a/sdk/package.json b/sdk/package.jsonnew file mode 100644index 0000000000..812baa52af--- /dev/null+++ b/sdk/package.json@@ -0,0 +1,81 @@+{+ "name": "@spree/sdk",+ "version": "0.1.0",+ "description": "Official TypeScript SDK for Spree Commerce API",+ "type": "module",+ "main": "./dist/index.cjs",+ "module": "./dist/index.js",+ "types": "./dist/index.d.ts",+ "exports": {+ ".": {+ "import": {+ "types": "./dist/index.d.ts",+ "default": "./dist/index.js"+ },+ "require": {+ "types": "./dist/index.d.cts",+ "default": "./dist/index.cjs"+ }+ },+ "./types": {+ "import": {+ "types": "./dist/types/index.d.ts",+ "default": "./dist/types/index.js"+ },+ "require": {+ "types": "./dist/types/index.d.cts",+ "default": "./dist/types/index.cjs"+ }+ }+ },+ "files": [+ "dist",+ "README.md"+ ],+ "scripts": {+ "build": "tsup",+ "dev": "tsup --watch",+ "console": "tsx console.ts",+ "lint": "eslint src --ext .ts",+ "typecheck": "tsc --noEmit",+ "clean": "rm -rf dist",+ "prepublishOnly": "npm run build"+ },+ "keywords": [+ "spree",+ "commerce",+ "ecommerce",+ "api",+ "sdk",+ "typescript",+ "headless"+ ],+ "author": "Vendo Connect Inc.",+ "license": "BSD-3-Clause",+ "repository": {+ "type": "git",+ "url": "https://github.com/spree/spree.git",+ "directory": "sdk"+ },+ "homepage": "https://spreecommerce.org",+ "bugs": {+ "url": "https://github.com/spree/spree/issues"+ },+ "devDependencies": {+ "@types/node": "^20.0.0",+ "tsup": "^8.0.0",+ "tsx": "^4.0.0",+ "typescript": "^5.3.0"+ },+ "peerDependencies": {+ "typescript": ">=4.7.0"+ },+ "peerDependenciesMeta": {+ "typescript": {+ "optional": true+ }+ },+ "engines": {+ "node": ">=18.0.0"+ }+}diff --git a/sdk/src/client.ts b/sdk/src/client.tsnew file mode 100644index 0000000000..0c4289eea8--- /dev/null+++ b/sdk/src/client.ts@@ -0,0 +1,645 @@+import type {+ AuthTokens,+ LoginCredentials,+ RegisterParams,+ ErrorResponse,+ PaginatedResponse,+ ListParams,+ ProductListParams,+ OrderListParams,+ AddLineItemParams,+ UpdateLineItemParams,+ CreatePaymentParams,+ UpdateOrderParams,+ StoreProduct,+ StoreOrder,+ StoreLineItem,+ StoreCountry,+ StoreTaxonomy,+ StoreTaxon,+ StorePaymentMethod,+ StorePayment,+ StoreStore,+ StoreWishlist,+ StoreAddress,+ StoreUser,+} 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;+ /** Custom fetch implementation (optional, defaults to global fetch) */+ fetch?: typeof fetch;+}++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;++ constructor(config: SpreeClientConfig) {+ this.baseUrl = config.baseUrl.replace(/\/$/, '');+ this.apiKey = config.apiKey;+ this.fetchFn = config.fetch || fetch;+ }++ 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) {+ 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 (locale) {+ requestHeaders['x-spree-locale'] = locale;+ }++ if (currency) {+ requestHeaders['x-spree-currency'] = currency;+ }++ const response = await this.fetchFn(url.toString(), {+ method,+ headers: requestHeaders,+ body: body ? JSON.stringify(body) : undefined,+ });++ if (!response.ok) {+ 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>;+ }++ // ============================================+ // 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 using refresh token+ */+ refresh: (refreshToken: string): Promise<AuthTokens> =>+ this.request<AuthTokens>('POST', '/auth/refresh', {+ body: { refresh_token: refreshToken },+ }),+ };++ // ============================================+ // 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,+ }),+ };++ // ============================================+ // 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 = {+ /**+ * 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,+ }),+ };++ // ============================================+ // 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),+ };++ // ============================================+ // Orders (Cart & Checkout)+ // ============================================++ 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,+ order: UpdateOrderParams,+ options?: RequestOptions+ ): Promise<StoreOrder> =>+ this.request<StoreOrder>('PATCH', `/orders/${idOrNumber}`, {+ ...options,+ body: { order },+ }),++ /**+ * 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),+ };++ // ============================================+ // Line Items+ // ============================================++ readonly 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+ ),+ };++ // ============================================+ // Payments+ // ============================================++ readonly payments = {+ /**+ * List payments for an order+ */+ list: (+ orderId: string,+ options?: RequestOptions+ ): Promise<PaginatedResponse<StorePayment>> =>+ this.request<PaginatedResponse<StorePayment>>(+ '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+ ),++ /**+ * Create a payment+ */+ create: (+ orderId: string,+ params: CreatePaymentParams,+ options?: RequestOptions+ ): Promise<StoreOrder> =>+ this.request<StoreOrder>('POST', `/orders/${orderId}/payments`, {+ ...options,+ body: params,+ }),+ };++ readonly 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+ ),+ };++ // ============================================+ // Customer+ // ============================================++ readonly customer = {+ /**+ * Get current customer profile+ */+ get: (options?: RequestOptions): Promise<StoreUser> =>+ this.request<StoreUser>('GET', '/customers/me', options),++ /**+ * Update current customer profile+ */+ update: (+ params: { first_name?: string; last_name?: string; email?: string },+ options?: RequestOptions+ ): Promise<StoreUser> =>+ this.request<StoreUser>('PATCH', '/customers/me', {+ ...options,+ body: { user: params },+ }),+ };++ // ============================================+ // Addresses+ // ============================================++ readonly addresses = {+ /**+ * List customer addresses+ */+ list: (+ params?: ListParams,+ options?: RequestOptions+ ): Promise<PaginatedResponse<StoreAddress>> =>+ this.request<PaginatedResponse<StoreAddress>>(+ 'GET',+ '/customers/me/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', `/customers/me/addresses/${id}`, options),++ /**+ * Create an address+ */+ create: (+ address: Omit<StoreAddress, 'id'>,+ options?: RequestOptions+ ): Promise<StoreAddress> =>+ this.request<StoreAddress>('POST', '/customers/me/addresses', {+ ...options,+ body: { address },+ }),++ /**+ * Update an address+ */+ update: (+ id: string,+ address: Partial<Omit<StoreAddress, 'id'>>,+ options?: RequestOptions+ ): Promise<StoreAddress> =>+ this.request<StoreAddress>('PATCH', `/customers/me/addresses/${id}`, {+ ...options,+ body: { address },+ }),++ /**+ * Delete an address+ */+ delete: (id: string, options?: RequestOptions): Promise<void> =>+ this.request<void>('DELETE', `/customers/me/addresses/${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: (+ wishlist: { name: string; is_private?: boolean; is_default?: boolean },+ options?: RequestOptions+ ): Promise<StoreWishlist> =>+ this.request<StoreWishlist>('POST', '/wishlists', {+ ...options,+ body: { wishlist },+ }),++ /**+ * Update a wishlist+ */+ update: (+ id: string,+ wishlist: { name?: string; is_private?: boolean; is_default?: boolean },+ options?: RequestOptions+ ): Promise<StoreWishlist> =>+ this.request<StoreWishlist>('PATCH', `/wishlists/${id}`, {+ ...options,+ body: { wishlist },+ }),++ /**+ * Delete a wishlist+ */+ delete: (id: string, options?: RequestOptions): Promise<void> =>+ this.request<void>('DELETE', `/wishlists/${id}`, options),++ /**+ * Add an item to a wishlist+ */+ addItem: (+ wishlistId: string,+ params: { variant_id: string; quantity?: number },+ options?: RequestOptions+ ): Promise<StoreWishlist> =>+ this.request<StoreWishlist>('POST', `/wishlists/${wishlistId}/items`, {+ ...options,+ body: params,+ }),++ /**+ * Remove an item from a wishlist+ */+ removeItem: (+ wishlistId: string,+ itemId: string,+ options?: RequestOptions+ ): Promise<void> =>+ this.request<void>(+ 'DELETE',+ `/wishlists/${wishlistId}/items/${itemId}`,+ options+ ),+ };+}++/**+ * Create a new Spree SDK client+ */+export function createSpreeClient(config: SpreeClientConfig): SpreeClient {+ return new SpreeClient(config);+}diff --git a/sdk/src/index.ts b/sdk/src/index.tsnew file mode 100644index 0000000000..2567c7c5e9--- /dev/null+++ b/sdk/src/index.ts@@ -0,0 +1,6 @@+// Main client+export { SpreeClient, SpreeError, createSpreeClient } from './client';+export type { SpreeClientConfig, RequestOptions } from './client';++// All types+export * from './types';diff --git a/sdk/src/types/index.ts b/sdk/src/types/index.tsnew file mode 100644index 0000000000..5419fccc70--- /dev/null+++ b/sdk/src/types/index.ts@@ -0,0 +1,102 @@+// Re-export all generated types+export * from './generated';++// API Response types+export interface PaginationMeta {+ page: number;+ limit: number;+ count: number;+ pages: number;+}++export interface PaginatedResponse<T> {+ data: T[];+ meta: PaginationMeta;+}++export interface ErrorResponse {+ error: {+ code: string;+ message: string;+ details?: Record<string, string[]>;+ };+}++// Auth types+export interface AuthTokens {+ access_token: string;+ refresh_token: string;+ token_type: 'Bearer';+ expires_in: number;+}++export interface LoginCredentials {+ email: string;+ password: string;+}++export interface RegisterParams {+ email: string;+ password: string;+ password_confirmation: string;+ first_name?: string;+ last_name?: string;+}++// Query params+export interface ListParams {+ page?: number;+ per_page?: number;+ includes?: string;+}++export interface ProductListParams extends ListParams {+ 'q[name_cont]'?: string;+ 'q[price_gte]'?: number;+ 'q[price_lte]'?: number;+ 'q[taxons_id_eq]'?: string;+}++export interface OrderListParams extends ListParams {+ 'q[state_eq]'?: string;+ 'q[completed_at_gte]'?: string;+ 'q[completed_at_lte]'?: string;+}++// Cart operations+export interface AddLineItemParams {+ variant_id: string;+ quantity: number;+}++export interface UpdateLineItemParams {+ quantity: number;+}++// Payment params+export interface CreatePaymentParams {+ payment_method_id: string;+ amount?: number;+ source_attributes?: Record<string, unknown>;+}++// Address params+export interface AddressParams {+ firstname: string;+ lastname: string;+ address1: string;+ address2?: string;+ city: string;+ zipcode: string;+ phone: string;+ country_id: string;+ state_id?: string;+ state_name?: string;+}++export interface UpdateOrderParams {+ email?: string;+ special_instructions?: string;+ bill_address_attributes?: AddressParams;+ ship_address_attributes?: AddressParams;+}diff --git a/sdk/tsconfig.json b/sdk/tsconfig.jsonnew file mode 100644index 0000000000..6b1719f1c9--- /dev/null+++ b/sdk/tsconfig.json@@ -0,0 +1,29 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "lib": ["ES2022", "DOM"],+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": true,+ "declarationMap": true,+ "sourceMap": true,+ "outDir": "./dist",+ "rootDir": "./src",+ "baseUrl": ".",+ "paths": {+ "@/*": ["./src/*"],+ "@/types": ["./src/types/generated/index.ts"]+ },+ "resolveJsonModule": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "noImplicitReturns": true,+ "noFallthroughCasesInSwitch": true+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules", "dist"]+}diff --git a/sdk/tsup.config.ts b/sdk/tsup.config.tsnew file mode 100644index 0000000000..6c4d000d66--- /dev/null+++ b/sdk/tsup.config.ts@@ -0,0 +1,22 @@+import { defineConfig } from 'tsup';++export default defineConfig({+ entry: {+ index: 'src/index.ts',+ 'types/index': 'src/types/index.ts',+ },+ format: ['cjs', 'esm'],+ dts: true,+ splitting: false,+ sourcemap: true,+ clean: true,+ treeshake: true,+ minify: false,+ external: [],+ esbuildOptions(options) {+ options.alias = {+ '@/types': './src/types/generated/index.ts',+ '@': './src',+ };+ },+});