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.

Wire Biome lint into all packages and CI

Damian Legawiec6166c44ae414
diff --git a/.github/workflows/packages.yml b/.github/workflows/packages.yml
index a8c5742700..72f7b9e92d 100644
--- a/.github/workflows/packages.yml
+++ b/.github/workflows/packages.yml
@@ -48,7 +48,7 @@ jobs:
- run: pnpm install --frozen-lockfile
- - run: pnpm turbo typecheck test build
+ - run: pnpm turbo lint typecheck test build
sdk-integration:
name: "SDK Integration Tests"
diff --git a/package.json b/package.json
index fda15ea8fb..c1d5e083fa 100644
--- a/package.json
+++ b/package.json
@@ -7,6 +7,8 @@
"build": "turbo build",
"test": "turbo test",
"lint": "turbo lint",
+ "lint:fix": "turbo lint:fix",
+ "format": "turbo format",
"typecheck": "turbo typecheck",
"clean": "turbo clean",
"server:setup": "git clone --depth 1 https://github.com/spree/spree-starter.git server && rm -rf server/.git server/.gitignore && echo 'SPREE_PATH=..' > server/.env && echo '\nServer cloned to server/. Next steps:\n cd server\n # edit .env if needed (DATABASE_USERNAME, etc.)\n bin/setup\n bin/dev\n'",
@@ -19,6 +21,7 @@
"server:down": "docker compose down"
},
"devDependencies": {
+ "@biomejs/biome": "^2.4.13",
"turbo": "^2.9.6"
},
"packageManager": "[email protected]",
diff --git a/packages/admin-sdk/.changeset/config.json b/packages/admin-sdk/.changeset/config.json
index 95ea990266..0fbbd8c795 100644
--- a/packages/admin-sdk/.changeset/config.json
+++ b/packages/admin-sdk/.changeset/config.json
@@ -1,9 +1,6 @@
{
"$schema": "https://unpkg.com/@changesets/[email protected]/schema.json",
- "changelog": [
- "@changesets/changelog-github",
- { "repo": "spree/spree" }
- ],
+ "changelog": ["@changesets/changelog-github", { "repo": "spree/spree" }],
"commit": false,
"fixed": [],
"linked": [],
diff --git a/packages/admin-sdk/biome.json b/packages/admin-sdk/biome.json
index cbf6832d91..aa04ce3dcf 100644
--- a/packages/admin-sdk/biome.json
+++ b/packages/admin-sdk/biome.json
@@ -1,7 +1,8 @@
{
"$schema": "https://biomejs.dev/schemas/2.4.13/schema.json",
- "extends": ["//"],
+ "root": false,
+ "extends": ["../../biome.json"],
"files": {
- "includes": ["src/**", "tests/**", "!src/types/generated/**", "!src/zod/generated/**"]
+ "includes": ["src/**", "tests/**", "!src/types/generated", "!src/zod/generated"]
}
}
diff --git a/packages/admin-sdk/package.json b/packages/admin-sdk/package.json
index 3b001c13c9..e92560afeb 100644
--- a/packages/admin-sdk/package.json
+++ b/packages/admin-sdk/package.json
@@ -39,6 +39,9 @@
"typecheck": "tsc --noEmit",
"test": "vitest run --passWithNoTests",
"test:watch": "vitest",
+ "lint": "biome check src tests",
+ "lint:fix": "biome check --fix src tests",
+ "format": "biome format --write src tests",
"clean": "rm -rf dist",
"prepublishOnly": "npm run build",
"changeset": "changeset",
diff --git a/packages/admin-sdk/scripts/generate-admin-client.ts b/packages/admin-sdk/scripts/generate-admin-client.ts
index 2492cf4585..06825cbbfa 100644
--- a/packages/admin-sdk/scripts/generate-admin-client.ts
+++ b/packages/admin-sdk/scripts/generate-admin-client.ts
@@ -13,8 +13,8 @@
* - Generates request param interfaces for create/update bodies
*/
-import * as fs from 'node:fs';
-import * as path from 'node:path';
+import * as fs from 'node:fs'
+import * as path from 'node:path'
// ---------------------------------------------------------------------------
// YAML Parser (minimal, no dependency)
@@ -27,112 +27,116 @@ function parseYaml(text: string): unknown {
// Actually, Node 18+ doesn't have built-in YAML. Let's do a minimal parser.
// The rswag output is simple enough: no anchors, no multi-doc, no flow style.
- const lines = text.split('\n');
- const root: Record<string, unknown> = {};
+ const lines = text.split('\n')
+ const root: Record<string, unknown> = {}
const stack: { indent: number; obj: Record<string, unknown> | unknown[] }[] = [
{ indent: -1, obj: root },
- ];
+ ]
function currentContainer() {
- return stack[stack.length - 1];
+ return stack[stack.length - 1]
}
- function setValue(container: Record<string, unknown> | unknown[], key: string | null, value: unknown) {
+ function setValue(
+ container: Record<string, unknown> | unknown[],
+ key: string | null,
+ value: unknown,
+ ) {
if (Array.isArray(container)) {
- container.push(value);
+ container.push(value)
} else if (key) {
- container[key] = value;
+ container[key] = value
}
}
for (let i = 0; i < lines.length; i++) {
- const raw = lines[i];
- if (raw.trimStart().startsWith('#') || raw.trim() === '' || raw.trim() === '---') continue;
+ const raw = lines[i]
+ if (raw.trimStart().startsWith('#') || raw.trim() === '' || raw.trim() === '---') continue
- const indent = raw.search(/\S/);
- const trimmed = raw.trim();
+ const indent = raw.search(/\S/)
+ const trimmed = raw.trim()
// Pop stack to find parent
while (stack.length > 1 && indent <= currentContainer().indent) {
- stack.pop();
+ stack.pop()
}
- const isArrayItem = trimmed.startsWith('- ');
- const content = isArrayItem ? trimmed.slice(2).trim() : trimmed;
+ const isArrayItem = trimmed.startsWith('- ')
+ const content = isArrayItem ? trimmed.slice(2).trim() : trimmed
if (isArrayItem) {
// Ensure parent value is an array
- const parent = currentContainer();
+ const parent = currentContainer()
// The parent's current value should be an array
// If the content is "key: value", it's an object in the array
if (content.includes(': ')) {
- const obj: Record<string, unknown> = {};
- const [k, ...rest] = content.split(': ');
- const v = rest.join(': ').trim();
- obj[k.trim()] = parseScalar(v);
+ const obj: Record<string, unknown> = {}
+ const [k, ...rest] = content.split(': ')
+ const v = rest.join(': ').trim()
+ obj[k.trim()] = parseScalar(v)
if (Array.isArray(parent.obj)) {
- parent.obj.push(obj);
+ parent.obj.push(obj)
}
- stack.push({ indent: indent + 2, obj });
+ stack.push({ indent: indent + 2, obj })
} else {
if (Array.isArray(parent.obj)) {
- parent.obj.push(parseScalar(content));
+ parent.obj.push(parseScalar(content))
}
}
- continue;
+ continue
}
// key: value or key:
- const colonIdx = content.indexOf(':');
- if (colonIdx === -1) continue;
+ const colonIdx = content.indexOf(':')
+ if (colonIdx === -1) continue
- const key = content.slice(0, colonIdx).trim();
- const rawValue = content.slice(colonIdx + 1).trim();
+ const key = content.slice(0, colonIdx).trim()
+ const rawValue = content.slice(colonIdx + 1).trim()
if (rawValue === '' || rawValue === '|' || rawValue === '>') {
// Nested object or block scalar
if (rawValue === '|' || rawValue === '>') {
// Block scalar — collect indented lines
- const blockLines: string[] = [];
- const blockIndent = indent + 2;
+ const blockLines: string[] = []
+ const blockIndent = indent + 2
while (i + 1 < lines.length) {
- const nextLine = lines[i + 1];
- const nextIndent = nextLine.search(/\S/);
+ const nextLine = lines[i + 1]
+ const nextIndent = nextLine.search(/\S/)
if (nextIndent >= blockIndent || nextLine.trim() === '') {
- blockLines.push(nextLine.slice(blockIndent));
- i++;
+ blockLines.push(nextLine.slice(blockIndent))
+ i++
} else {
- break;
+ break
}
}
- const text = blockLines.join(rawValue === '|' ? '\n' : ' ').trim();
- setValue(currentContainer().obj, key, text);
+ const text = blockLines.join(rawValue === '|' ? '\n' : ' ').trim()
+ setValue(currentContainer().obj, key, text)
} else {
// Check if next line starts with '- ' (array)
- const nextLine = lines[i + 1]?.trim();
- const child: Record<string, unknown> | unknown[] = nextLine?.startsWith('- ') ? [] : {};
- setValue(currentContainer().obj, key, child);
- stack.push({ indent, obj: child });
+ const nextLine = lines[i + 1]?.trim()
+ const child: Record<string, unknown> | unknown[] = nextLine?.startsWith('- ') ? [] : {}
+ setValue(currentContainer().obj, key, child)
+ stack.push({ indent, obj: child })
}
} else {
- setValue(currentContainer().obj, key, parseScalar(rawValue));
+ setValue(currentContainer().obj, key, parseScalar(rawValue))
}
}
- return root;
+ return root
}
function parseScalar(s: string): unknown {
- if (s === 'true') return true;
- if (s === 'false') return false;
- if (s === 'null') return null;
- if (/^-?\d+$/.test(s)) return parseInt(s, 10);
- if (/^-?\d+\.\d+$/.test(s)) return parseFloat(s);
+ if (s === 'true') return true
+ if (s === 'false') return false
+ if (s === 'null') return null
+ if (/^-?\d+$/.test(s)) return parseInt(s, 10)
+ if (/^-?\d+\.\d+$/.test(s)) return parseFloat(s)
// Strip quotes
if ((s.startsWith("'") && s.endsWith("'")) || (s.startsWith('"') && s.endsWith('"'))) {
- return s.slice(1, -1);
+ return s.slice(1, -1)
}
- return s;
+ return s
}
// ---------------------------------------------------------------------------
@@ -140,40 +144,43 @@ function parseScalar(s: string): unknown {
// ---------------------------------------------------------------------------
interface OpenApiSpec {
- paths: Record<string, Record<string, OpenApiOperation>>;
- components?: { schemas?: Record<string, unknown> };
- tags?: Array<{ name: string; description?: string }>;
+ paths: Record<string, Record<string, OpenApiOperation>>
+ components?: { schemas?: Record<string, unknown> }
+ tags?: Array<{ name: string; description?: string }>
}
interface OpenApiOperation {
- summary?: string;
- description?: string;
- tags?: string[];
- parameters?: OpenApiParameter[];
+ summary?: string
+ description?: string
+ tags?: string[]
+ parameters?: OpenApiParameter[]
requestBody?: {
- content?: Record<string, { schema?: OpenApiSchema }>;
- };
- responses?: Record<string, { description?: string; content?: Record<string, { schema?: OpenApiSchema }> }>;
+ content?: Record<string, { schema?: OpenApiSchema }>
+ }
+ responses?: Record<
+ string,
+ { description?: string; content?: Record<string, { schema?: OpenApiSchema }> }
+ >
}
interface OpenApiParameter {
- name: string;
- in: string;
- required?: boolean;
- description?: string;
- schema?: OpenApiSchema;
+ name: string
+ in: string
+ required?: boolean
+ description?: string
+ schema?: OpenApiSchema
}
interface OpenApiSchema {
- type?: string;
- properties?: Record<string, OpenApiSchema>;
- items?: OpenApiSchema;
- required?: string[];
- $ref?: string;
- enum?: unknown[];
- nullable?: boolean;
- description?: string;
- example?: unknown;
+ type?: string
+ properties?: Record<string, OpenApiSchema>
+ items?: OpenApiSchema
+ required?: string[]
+ $ref?: string
+ enum?: unknown[]
+ nullable?: boolean
+ description?: string
+ example?: unknown
}
// ---------------------------------------------------------------------------
@@ -181,151 +188,157 @@ interface OpenApiSchema {
// ---------------------------------------------------------------------------
interface ResourceEndpoint {
- method: string; // GET, POST, PATCH, DELETE
- path: string;
- operation: OpenApiOperation;
- action: 'list' | 'get' | 'create' | 'update' | 'delete' | 'custom';
- customAction?: string;
+ method: string // GET, POST, PATCH, DELETE
+ path: string
+ operation: OpenApiOperation
+ action: 'list' | 'get' | 'create' | 'update' | 'delete' | 'custom'
+ customAction?: string
}
interface Resource {
/** e.g. 'products', 'option_types' */
- name: string;
+ name: string
/** e.g. 'Products' — from tag */
- tag: string;
+ tag: string
/** The base path for this resource, e.g. '/api/v3/admin/products' */
- basePath: string;
+ basePath: string
/** Parent resource name if nested, e.g. 'products' for variants */
- parentName?: string;
+ parentName?: string
/** Parent path param, e.g. 'product_id' */
- parentParam?: string;
+ parentParam?: string
/** Grandparent resource name for deeply nested, e.g. 'products' for variant assets */
- grandparentName?: string;
+ grandparentName?: string
/** Grandparent path param, e.g. 'product_id' for variant assets */
- grandparentParam?: string;
- endpoints: ResourceEndpoint[];
+ grandparentParam?: string
+ endpoints: ResourceEndpoint[]
}
-const API_PREFIX = '/api/v3/admin';
+const API_PREFIX = '/api/v3/admin'
-function classifyAction(method: string, path: string, basePath: string): { action: ResourceEndpoint['action']; customAction?: string } {
- const relative = path.slice(basePath.length);
+function classifyAction(
+ method: string,
+ path: string,
+ basePath: string,
+): { action: ResourceEndpoint['action']; customAction?: string } {
+ const relative = path.slice(basePath.length)
- if (method === 'GET' && (relative === '' || relative === '/')) return { action: 'list' };
- if (method === 'GET' && relative === '/{id}') return { action: 'get' };
- if (method === 'POST' && (relative === '' || relative === '/')) return { action: 'create' };
- if (method === 'PATCH' && relative === '/{id}') return { action: 'update' };
- if (method === 'PUT' && relative === '/{id}') return { action: 'update' };
- if (method === 'DELETE' && relative === '/{id}') return { action: 'delete' };
+ if (method === 'GET' && (relative === '' || relative === '/')) return { action: 'list' }
+ if (method === 'GET' && relative === '/{id}') return { action: 'get' }
+ if (method === 'POST' && (relative === '' || relative === '/')) return { action: 'create' }
+ if (method === 'PATCH' && relative === '/{id}') return { action: 'update' }
+ if (method === 'PUT' && relative === '/{id}') return { action: 'update' }
+ if (method === 'DELETE' && relative === '/{id}') return { action: 'delete' }
// Custom actions like POST /products/{id}/clone
- const customMatch = relative.match(/^\/{id}\/(\w+)$/);
- if (customMatch) return { action: 'custom', customAction: customMatch[1] };
+ const customMatch = relative.match(/^\/{id}\/(\w+)$/)
+ if (customMatch) return { action: 'custom', customAction: customMatch[1] }
// Member-less custom: POST /products/import
- const rootCustom = relative.match(/^\/(\w+)$/);
- if (rootCustom) return { action: 'custom', customAction: rootCustom[1] };
+ const rootCustom = relative.match(/^\/(\w+)$/)
+ if (rootCustom) return { action: 'custom', customAction: rootCustom[1] }
- return { action: 'custom', customAction: relative.replace(/[{}\/]/g, '_').replace(/^_+|_+$/g, '') };
+ return { action: 'custom', customAction: relative.replace(/[{}/]/g, '_').replace(/^_+|_+$/g, '') }
}
function analyzeResources(spec: OpenApiSpec): Resource[] {
- const resourceMap = new Map<string, Resource>();
+ const resourceMap = new Map<string, Resource>()
for (const [fullPath, methods] of Object.entries(spec.paths)) {
- if (!fullPath.startsWith(API_PREFIX)) continue;
+ if (!fullPath.startsWith(API_PREFIX)) continue
- const apiPath = fullPath.slice(API_PREFIX.length); // e.g. '/products', '/products/{id}'
+ const apiPath = fullPath.slice(API_PREFIX.length) // e.g. '/products', '/products/{id}'
// Skip auth paths — these are hand-written in the AdminClient class
- if (apiPath.startsWith('/auth')) continue;
+ if (apiPath.startsWith('/auth')) continue
for (const [method, operation] of Object.entries(methods)) {
- if (!operation || typeof operation !== 'object') continue;
- const httpMethod = method.toUpperCase();
- if (!['GET', 'POST', 'PATCH', 'PUT', 'DELETE'].includes(httpMethod)) continue;
+ if (!operation || typeof operation !== 'object') continue
+ const httpMethod = method.toUpperCase()
+ if (!['GET', 'POST', 'PATCH', 'PUT', 'DELETE'].includes(httpMethod)) continue
- const tag = operation.tags?.[0] || 'Unknown';
+ const tag = operation.tags?.[0] || 'Unknown'
// Determine resource name and nesting
// /products → resource=products
// /products/{id} → resource=products
// /products/{product_id}/variants → resource=variants, parent=products
// /products/{product_id}/variants/{variant_id}/assets → resource=assets, parent=variants, grandparent=products
- const segments = apiPath.split('/').filter(Boolean);
+ const segments = apiPath.split('/').filter(Boolean)
- let resourceName: string;
- let basePath: string;
- let parentName: string | undefined;
- let parentParam: string | undefined;
- let grandparentName: string | undefined;
- let grandparentParam: string | undefined;
+ let resourceName: string
+ let basePath: string
+ let parentName: string | undefined
+ let parentParam: string | undefined
+ let grandparentName: string | undefined
+ let grandparentParam: string | undefined
if (segments.length >= 5 && segments[1].startsWith('{') && segments[3].startsWith('{')) {
// 5+ segments: /parent/{id}/child/{id}/something
// If the 5th segment is a resource name (has collection/member endpoints), it's deeply nested.
// If it's a custom action name (no sub-paths with /{id}), it's a member action on the child resource.
- const fifthSegment = segments[4];
- const potentialDeepBasePath = `${API_PREFIX}/${segments[0]}/${segments[1]}/${segments[2]}/${segments[3]}/${fifthSegment}`;
+ const fifthSegment = segments[4]
+ const potentialDeepBasePath = `${API_PREFIX}/${segments[0]}/${segments[1]}/${segments[2]}/${segments[3]}/${fifthSegment}`
const hasDeepCollection = Object.keys(spec.paths).some(
- (p) => p === potentialDeepBasePath && (spec.paths[p]?.get || spec.paths[p]?.post)
- );
- const hasDeepMember = Object.keys(spec.paths).some(
- (p) => p.startsWith(potentialDeepBasePath + '/{')
- );
+ (p) => p === potentialDeepBasePath && (spec.paths[p]?.get || spec.paths[p]?.post),
+ )
+ const hasDeepMember = Object.keys(spec.paths).some((p) =>
+ p.startsWith(`${potentialDeepBasePath}/{`),
+ )
if (hasDeepCollection || hasDeepMember) {
// Deeply nested resource: /products/{product_id}/variants/{variant_id}/assets
- grandparentName = segments[0];
- grandparentParam = segments[1].slice(1, -1);
- parentName = segments[2];
- parentParam = segments[3].slice(1, -1);
- resourceName = segments[4];
- basePath = potentialDeepBasePath;
+ grandparentName = segments[0]
+ grandparentParam = segments[1].slice(1, -1)
+ parentName = segments[2]
+ parentParam = segments[3].slice(1, -1)
+ resourceName = segments[4]
+ basePath = potentialDeepBasePath
} else {
// Custom member action on nested resource: /orders/{order_id}/payments/{id}/capture
- parentName = segments[0];
- parentParam = segments[1].slice(1, -1);
- resourceName = segments[2];
- basePath = `${API_PREFIX}/${segments[0]}/${segments[1]}/${segments[2]}`;
+ parentName = segments[0]
+ parentParam = segments[1].slice(1, -1)
+ resourceName = segments[2]
+ basePath = `${API_PREFIX}/${segments[0]}/${segments[1]}/${segments[2]}`
}
} else if (segments.length >= 3 && segments[1].startsWith('{') && segments[1].endsWith('}')) {
// Check if this is a member action (e.g., /orders/{id}/cancel) vs a nested resource
// Member actions: only have /parent/{id}/action (no further /{id})
// Nested resources: have /parent/{id}/resource and /parent/{id}/resource/{id}
- const isMemberAction = segments.length === 3 && !segments[2].startsWith('{');
+ const isMemberAction = segments.length === 3 && !segments[2].startsWith('{')
// Look ahead: is there a collection endpoint for this sub-path?
// If there's only single-verb endpoints and no collection/show patterns, treat as member action
- const subPathPrefix = `${API_PREFIX}/${segments[0]}/${segments[1]}/${segments[2]}`;
+ const subPathPrefix = `${API_PREFIX}/${segments[0]}/${segments[1]}/${segments[2]}`
const hasCollectionOrMember = Object.keys(spec.paths).some(
- (p) => p.startsWith(subPathPrefix) && p !== fullPath && p.includes('/{id}')
- );
+ (p) => p.startsWith(subPathPrefix) && p !== fullPath && p.includes('/{id}'),
+ )
const hasCollectionEndpoint = Object.keys(spec.paths).some(
- (p) => p === subPathPrefix && spec.paths[p]?.get
- );
+ (p) => p === subPathPrefix && spec.paths[p]?.get,
+ )
if (isMemberAction && !hasCollectionOrMember && !hasCollectionEndpoint) {
// This is a member action on the parent resource (e.g., PATCH /orders/{id}/cancel)
- resourceName = segments[0];
- basePath = `${API_PREFIX}/${segments[0]}`;
+ resourceName = segments[0]
+ basePath = `${API_PREFIX}/${segments[0]}`
// Classify as a custom action on the parent resource
} else {
// Nested resource: /products/{product_id}/variants...
- parentName = segments[0];
- parentParam = segments[1].slice(1, -1); // remove { }
- resourceName = segments[2];
- basePath = `${API_PREFIX}/${segments[0]}/${segments[1]}/${segments[2]}`;
+ parentName = segments[0]
+ parentParam = segments[1].slice(1, -1) // remove { }
+ resourceName = segments[2]
+ basePath = `${API_PREFIX}/${segments[0]}/${segments[1]}/${segments[2]}`
}
} else {
- resourceName = segments[0];
- basePath = `${API_PREFIX}/${segments[0]}`;
+ resourceName = segments[0]
+ basePath = `${API_PREFIX}/${segments[0]}`
}
const resourceKey = grandparentName
? `${grandparentName}.${parentName}.${resourceName}`
- : parentName ? `${parentName}.${resourceName}` : resourceName;
- const { action, customAction } = classifyAction(httpMethod, fullPath, basePath);
+ : parentName
+ ? `${parentName}.${resourceName}`
+ : resourceName
+ const { action, customAction } = classifyAction(httpMethod, fullPath, basePath)
if (!resourceMap.has(resourceKey)) {
resourceMap.set(resourceKey, {
@@ -337,7 +350,7 @@ function analyzeResources(spec: OpenApiSpec): Resource[] {
grandparentName,
grandparentParam,
endpoints: [],
- });
+ })
}
resourceMap.get(resourceKey)!.endpoints.push({
@@ -346,11 +359,11 @@ function analyzeResources(spec: OpenApiSpec): Resource[] {
operation,
action,
customAction,
- });
+ })
}
}
- return Array.from(resourceMap.values());
+ return Array.from(resourceMap.values())
}
// ---------------------------------------------------------------------------
@@ -363,22 +376,22 @@ function singularPascal(name: string): string {
const pascal = name
.split('_')
.map((s) => s.charAt(0).toUpperCase() + s.slice(1))
- .join('');
+ .join('')
// Simple singularization
- if (pascal.endsWith('ies')) return pascal.slice(0, -3) + 'y';
- if (pascal.endsWith('ses')) return pascal.slice(0, -2);
- if (pascal.endsWith('s')) return pascal.slice(0, -1);
- return pascal;
+ if (pascal.endsWith('ies')) return `${pascal.slice(0, -3)}y`
+ if (pascal.endsWith('ses')) return pascal.slice(0, -2)
+ if (pascal.endsWith('s')) return pascal.slice(0, -1)
+ return pascal
}
/** 'option_types' → 'optionTypes' */
function camelCase(name: string): string {
- return name.replace(/_(\w)/g, (_, c) => c.toUpperCase());
+ return name.replace(/_(\w)/g, (_, c) => c.toUpperCase())
}
function getResponseType(resource: Resource): string {
- return `Admin${singularPascal(resource.name)}`;
+ return `Admin${singularPascal(resource.name)}`
}
// ---------------------------------------------------------------------------
@@ -387,56 +400,55 @@ function getResponseType(resource: Resource): string {
function schemaToTsType(schema: OpenApiSchema, indent = 2): string {
if (schema.$ref) {
- const refName = schema.$ref.split('/').pop()!;
- return refName;
+ const refName = schema.$ref.split('/').pop()!
+ return refName
}
if (schema.type === 'string') {
- if (schema.enum) return schema.enum.map((e) => `'${e}'`).join(' | ');
- return 'string';
+ if (schema.enum) return schema.enum.map((e) => `'${e}'`).join(' | ')
+ return 'string'
}
- if (schema.type === 'number' || schema.type === 'integer') return 'number';
- if (schema.type === 'boolean') return 'boolean';
+ if (schema.type === 'number' || schema.type === 'integer') return 'number'
+ if (schema.type === 'boolean') return 'boolean'
if (schema.type === 'array' && schema.items) {
- const itemType = schemaToTsType(schema.items, indent);
- return `Array<${itemType}>`;
+ const itemType = schemaToTsType(schema.items, indent)
+ return `Array<${itemType}>`
}
if (schema.type === 'object' && schema.properties) {
- const required = new Set(schema.required || []);
- const pad = ' '.repeat(indent);
+ const required = new Set(schema.required || [])
+ const pad = ' '.repeat(indent)
const lines = Object.entries(schema.properties).map(([key, prop]) => {
- const opt = required.has(key) ? '' : '?';
- const type = schemaToTsType(prop as OpenApiSchema, indent + 2);
- return `${pad}${key}${opt}: ${type};`;
- });
- return `{\n${lines.join('\n')}\n${' '.repeat(indent - 2)}}`;
+ const opt = required.has(key) ? '' : '?'
+ const type = schemaToTsType(prop as OpenApiSchema, indent + 2)
+ return `${pad}${key}${opt}: ${type};`
+ })
+ return `{\n${lines.join('\n')}\n${' '.repeat(indent - 2)}}`
}
- return 'unknown';
+ return 'unknown'
}
function generateRequestParamType(
resource: Resource,
action: 'create' | 'update',
- operation: OpenApiOperation
+ operation: OpenApiOperation,
): { typeName: string; typeBody: string } | null {
// Find request body schema
- const bodyParam = operation.parameters?.find((p) => p.name === 'body' && p.in === 'body');
- const bodySchema = (bodyParam as unknown as { schema?: OpenApiSchema })?.schema;
+ const bodyParam = operation.parameters?.find((p) => p.name === 'body' && p.in === 'body')
+ const bodySchema = (bodyParam as unknown as { schema?: OpenApiSchema })?.schema
// Also check requestBody (OpenAPI 3.0 style)
- const requestBodySchema =
- operation.requestBody?.content?.['application/json']?.schema;
+ const requestBodySchema = operation.requestBody?.content?.['application/json']?.schema
- const schema = bodySchema || requestBodySchema;
- if (!schema?.properties) return null;
+ const schema = bodySchema || requestBodySchema
+ if (!schema?.properties) return null
- const typeName = `Admin${singularPascal(resource.name)}${action === 'create' ? 'Create' : 'Update'}Params`;
- const typeBody = schemaToTsType(schema);
+ const typeName = `Admin${singularPascal(resource.name)}${action === 'create' ? 'Create' : 'Update'}Params`
+ const typeBody = schemaToTsType(schema)
- return { typeName, typeBody };
+ return { typeName, typeBody }
}
// ---------------------------------------------------------------------------
@@ -444,396 +456,413 @@ function generateRequestParamType(
// ---------------------------------------------------------------------------
function generateResourceMethods(resource: Resource, paramTypes: Map<string, string>): string {
- const lines: string[] = [];
- const responseType = getResponseType(resource);
+ const lines: string[] = []
+ const responseType = getResponseType(resource)
// Build parent param declarations and URL prefix
- const parentParams: { name: string; camel: string }[] = [];
+ const parentParams: { name: string; camel: string }[] = []
if (resource.grandparentParam) {
- parentParams.push({ name: resource.grandparentParam, camel: camelCase(resource.grandparentParam) });
+ parentParams.push({
+ name: resource.grandparentParam,
+ camel: camelCase(resource.grandparentParam),
+ })
}
if (resource.parentParam) {
- parentParams.push({ name: resource.parentParam, camel: camelCase(resource.parentParam) });
+ parentParams.push({ name: resource.parentParam, camel: camelCase(resource.parentParam) })
}
// Build URL prefix: e.g. `/products/${productId}/variants/${variantId}/assets`
- let urlPrefix: string;
+ let urlPrefix: string
if (resource.grandparentName && resource.parentName) {
- urlPrefix = `/${resource.grandparentName}/\${${parentParams[0].camel}}/${resource.parentName}/\${${parentParams[1].camel}}/${resource.name}`;
+ urlPrefix = `/${resource.grandparentName}/\${${parentParams[0].camel}}/${resource.parentName}/\${${parentParams[1].camel}}/${resource.name}`
} else if (resource.parentName) {
- urlPrefix = `/${resource.parentName}/\${${parentParams[0].camel}}/${resource.name}`;
+ urlPrefix = `/${resource.parentName}/\${${parentParams[0].camel}}/${resource.name}`
} else {
- urlPrefix = `/${resource.name}`;
+ urlPrefix = `/${resource.name}`
}
- const hasParent = parentParams.length > 0;
- const useBacktick = hasParent;
+ const hasParent = parentParams.length > 0
+ const _useBacktick = hasParent
- const parentParamDecls = parentParams.map((p) => ` ${p.camel}: string,`);
+ const parentParamDecls = parentParams.map((p) => ` ${p.camel}: string,`)
// Build path string for generated code. Always uses backtick template literal.
function collectionPath() {
- return `\`${urlPrefix}\``;
+ return `\`${urlPrefix}\``
}
function memberPath(suffix = '') {
- return `\`${urlPrefix}/\${id}${suffix}\``;
+ return `\`${urlPrefix}/\${id}${suffix}\``
}
for (const endpoint of resource.endpoints) {
- const { action, method, operation, customAction } = endpoint;
+ const { action, method, operation, customAction } = endpoint
- const summary = operation.summary || '';
- const jsdoc = summary ? ` /** ${summary} */` : '';
+ const summary = operation.summary || ''
+ const jsdoc = summary ? ` /** ${summary} */` : ''
switch (action) {
case 'list': {
- if (jsdoc) lines.push(jsdoc);
- lines.push(` list: (`);
- lines.push(...parentParamDecls);
- lines.push(` params?: ListParams,`);
- lines.push(` options?: RequestOptions`);
- lines.push(` ): Promise<PaginatedResponse<${responseType}>> =>`);
- lines.push(` this.request<PaginatedResponse<${responseType}>>('GET', ${collectionPath()}, {`);
- lines.push(` ...options,`);
- lines.push(` params: transformListParams({ ...params }),`);
- lines.push(` }),`);
- break;
+ if (jsdoc) lines.push(jsdoc)
+ lines.push(` list: (`)
+ lines.push(...parentParamDecls)
+ lines.push(` params?: ListParams,`)
+ lines.push(` options?: RequestOptions`)
+ lines.push(` ): Promise<PaginatedResponse<${responseType}>> =>`)
+ lines.push(
+ ` this.request<PaginatedResponse<${responseType}>>('GET', ${collectionPath()}, {`,
+ )
+ lines.push(` ...options,`)
+ lines.push(` params: transformListParams({ ...params }),`)
+ lines.push(` }),`)
+ break
}
case 'get': {
- if (jsdoc) lines.push(jsdoc);
- lines.push(` get: (`);
- lines.push(...parentParamDecls);
- lines.push(` id: string,`);
- lines.push(` params?: { expand?: string[] },`);
- lines.push(` options?: RequestOptions`);
- lines.push(` ): Promise<${responseType}> =>`);
- lines.push(` this.request<${responseType}>('GET', ${memberPath()}, {`);
- lines.push(` ...options,`);
- lines.push(` params: getParams(params),`);
- lines.push(` }),`);
- break;
+ if (jsdoc) lines.push(jsdoc)
+ lines.push(` get: (`)
+ lines.push(...parentParamDecls)
+ lines.push(` id: string,`)
+ lines.push(` params?: { expand?: string[] },`)
+ lines.push(` options?: RequestOptions`)
+ lines.push(` ): Promise<${responseType}> =>`)
+ lines.push(` this.request<${responseType}>('GET', ${memberPath()}, {`)
+ lines.push(` ...options,`)
+ lines.push(` params: getParams(params),`)
+ lines.push(` }),`)
+ break
}
case 'create': {
- const createTypeName = `Admin${singularPascal(resource.name)}CreateParams`;
- const paramType = paramTypes.has(createTypeName) ? createTypeName : 'Record<string, unknown>';
- if (jsdoc) lines.push(jsdoc);
- lines.push(` create: (`);
- lines.push(...parentParamDecls);
- lines.push(` params: ${paramType},`);
- lines.push(` options?: RequestOptions`);
- lines.push(` ): Promise<${responseType}> =>`);
- lines.push(` this.request<${responseType}>('POST', ${collectionPath()}, {`);
- lines.push(` ...options,`);
- lines.push(` body: params,`);
- lines.push(` }),`);
- break;
+ const createTypeName = `Admin${singularPascal(resource.name)}CreateParams`
+ const paramType = paramTypes.has(createTypeName)
+ ? createTypeName
+ : 'Record<string, unknown>'
+ if (jsdoc) lines.push(jsdoc)
+ lines.push(` create: (`)
+ lines.push(...parentParamDecls)
+ lines.push(` params: ${paramType},`)
+ lines.push(` options?: RequestOptions`)
+ lines.push(` ): Promise<${responseType}> =>`)
+ lines.push(` this.request<${responseType}>('POST', ${collectionPath()}, {`)
+ lines.push(` ...options,`)
+ lines.push(` body: params,`)
+ lines.push(` }),`)
+ break
}
case 'update': {
- const updateTypeName = `Admin${singularPascal(resource.name)}UpdateParams`;
- const paramType = paramTypes.has(updateTypeName) ? updateTypeName : 'Record<string, unknown>';
- if (jsdoc) lines.push(jsdoc);
- lines.push(` update: (`);
- lines.push(...parentParamDecls);
- lines.push(` id: string,`);
- lines.push(` params: ${paramType},`);
- lines.push(` options?: RequestOptions`);
- lines.push(` ): Promise<${responseType}> =>`);
- lines.push(` this.request<${responseType}>('PATCH', ${memberPath()}, {`);
- lines.push(` ...options,`);
- lines.push(` body: params,`);
- lines.push(` }),`);
- break;
+ const updateTypeName = `Admin${singularPascal(resource.name)}UpdateParams`
+ const paramType = paramTypes.has(updateTypeName)
+ ? updateTypeName
+ : 'Record<string, unknown>'
+ if (jsdoc) lines.push(jsdoc)
+ lines.push(` update: (`)
+ lines.push(...parentParamDecls)
+ lines.push(` id: string,`)
+ lines.push(` params: ${paramType},`)
+ lines.push(` options?: RequestOptions`)
+ lines.push(` ): Promise<${responseType}> =>`)
+ lines.push(` this.request<${responseType}>('PATCH', ${memberPath()}, {`)
+ lines.push(` ...options,`)
+ lines.push(` body: params,`)
+ lines.push(` }),`)
+ break
}
case 'delete': {
- if (jsdoc) lines.push(jsdoc);
- lines.push(` delete: (`);
- lines.push(...parentParamDecls);
- lines.push(` id: string,`);
- lines.push(` options?: RequestOptions`);
- lines.push(` ): Promise<void> =>`);
- lines.push(` this.request<void>('DELETE', ${memberPath()}, options),`);
- break;
+ if (jsdoc) lines.push(jsdoc)
+ lines.push(` delete: (`)
+ lines.push(...parentParamDecls)
+ lines.push(` id: string,`)
+ lines.push(` options?: RequestOptions`)
+ lines.push(` ): Promise<void> =>`)
+ lines.push(` this.request<void>('DELETE', ${memberPath()}, options),`)
+ break
}
case 'custom': {
- if (!customAction) break;
- const fnName = camelCase(customAction);
- if (jsdoc) lines.push(jsdoc);
+ if (!customAction) break
+ const fnName = camelCase(customAction)
+ if (jsdoc) lines.push(jsdoc)
if (method === 'POST' || method === 'PATCH') {
- lines.push(` ${fnName}: (`);
- lines.push(...parentParamDecls);
- lines.push(` id: string,`);
- lines.push(` params?: Record<string, unknown>,`);
- lines.push(` options?: RequestOptions`);
- lines.push(` ): Promise<${responseType}> =>`);
- lines.push(` this.request<${responseType}>('${method}', ${memberPath(`/${customAction}`)}, {`);
- lines.push(` ...options,`);
- lines.push(` body: params,`);
- lines.push(` }),`);
+ lines.push(` ${fnName}: (`)
+ lines.push(...parentParamDecls)
+ lines.push(` id: string,`)
+ lines.push(` params?: Record<string, unknown>,`)
+ lines.push(` options?: RequestOptions`)
+ lines.push(` ): Promise<${responseType}> =>`)
+ lines.push(
+ ` this.request<${responseType}>('${method}', ${memberPath(`/${customAction}`)}, {`,
+ )
+ lines.push(` ...options,`)
+ lines.push(` body: params,`)
+ lines.push(` }),`)
}
- break;
+ break
}
}
- lines.push('');
+ lines.push('')
}
- return lines.join('\n');
+ return lines.join('\n')
}
function generateParamsFile(paramTypes: Map<string, string>): string {
- const out: string[] = [];
+ const out: string[] = []
- out.push(`// This file is auto-generated by scripts/generate-admin-client.ts`);
- out.push(`// Do not edit manually. Run: npm run generate:admin-client`);
- out.push(``);
- out.push(`// Request parameter types (generated from OpenAPI request bodies)`);
- out.push(``);
+ out.push(`// This file is auto-generated by scripts/generate-admin-client.ts`)
+ out.push(`// Do not edit manually. Run: npm run generate:admin-client`)
+ out.push(``)
+ out.push(`// Request parameter types (generated from OpenAPI request bodies)`)
+ out.push(``)
for (const [name, body] of paramTypes) {
- out.push(`export interface ${name} ${body}`);
- out.push(``);
+ out.push(`export interface ${name} ${body}`)
+ out.push(``)
}
- return out.join('\n');
+ return out.join('\n')
}
function generateClient(spec: OpenApiSpec): { client: string; params: string } {
- const resources = analyzeResources(spec);
+ const resources = analyzeResources(spec)
// Collect all param types from request bodies
- const paramTypes = new Map<string, string>();
+ const paramTypes = new Map<string, string>()
for (const resource of resources) {
for (const endpoint of resource.endpoints) {
if (endpoint.action === 'create' || endpoint.action === 'update') {
- const result = generateRequestParamType(resource, endpoint.action, endpoint.operation);
+ const result = generateRequestParamType(resource, endpoint.action, endpoint.operation)
if (result) {
- paramTypes.set(result.typeName, result.typeBody);
+ paramTypes.set(result.typeName, result.typeBody)
}
}
}
}
// Collect all response types used
- const responseTypes = new Set<string>();
+ const responseTypes = new Set<string>()
for (const resource of resources) {
- responseTypes.add(getResponseType(resource));
+ responseTypes.add(getResponseType(resource))
}
// Group resources: top-level, 1-level nested, deeply nested (2-level)
- const topLevel = resources.filter((r) => !r.parentName);
- const nested = resources.filter((r) => r.parentName && !r.grandparentName);
- const deeplyNested = resources.filter((r) => r.grandparentName);
+ const topLevel = resources.filter((r) => !r.parentName)
+ const nested = resources.filter((r) => r.parentName && !r.grandparentName)
+ const deeplyNested = resources.filter((r) => r.grandparentName)
// Build imports
- const importedTypes = [...responseTypes].sort();
- const paramTypeNames = [...paramTypes.keys()].sort();
+ const importedTypes = [...responseTypes].sort()
+ const paramTypeNames = [...paramTypes.keys()].sort()
// Build client output
- const out: string[] = [];
-
- out.push(`// This file is auto-generated by scripts/generate-admin-client.ts`);
- out.push(`// Do not edit manually. Run: npm run generate:admin-client`);
- out.push(``);
- out.push(`import type { RequestFn, RequestOptions } from '@spree/sdk-core';`);
- out.push(`import { transformListParams, getParams } from '@spree/sdk-core';`);
- out.push(`import type { PaginatedResponse, ListParams } from '@spree/sdk-core';`);
- out.push(``);
- out.push(`export interface AuthTokens {`);
- out.push(` token: string;`);
- out.push(` refresh_token?: string;`);
- out.push(` user: {`);
- out.push(` id: string;`);
- out.push(` email: string;`);
- out.push(` first_name: string | null;`);
- out.push(` last_name: string | null;`);
- out.push(` };`);
- out.push(`}`);
- out.push(``);
- out.push(`export interface LoginCredentials {`);
- out.push(` email: string;`);
- out.push(` password: string;`);
- out.push(`}`);
+ const out: string[] = []
+
+ out.push(`// This file is auto-generated by scripts/generate-admin-client.ts`)
+ out.push(`// Do not edit manually. Run: npm run generate:admin-client`)
+ out.push(``)
+ out.push(`import type { RequestFn, RequestOptions } from '@spree/sdk-core';`)
+ out.push(`import { transformListParams, getParams } from '@spree/sdk-core';`)
+ out.push(`import type { PaginatedResponse, ListParams } from '@spree/sdk-core';`)
+ out.push(``)
+ out.push(`export interface AuthTokens {`)
+ out.push(` token: string;`)
+ out.push(` refresh_token?: string;`)
+ out.push(` user: {`)
+ out.push(` id: string;`)
+ out.push(` email: string;`)
+ out.push(` first_name: string | null;`)
+ out.push(` last_name: string | null;`)
+ out.push(` };`)
+ out.push(`}`)
+ out.push(``)
+ out.push(`export interface LoginCredentials {`)
+ out.push(` email: string;`)
+ out.push(` password: string;`)
+ out.push(`}`)
if (importedTypes.length > 0) {
- out.push(`import type {`);
+ out.push(`import type {`)
for (const t of importedTypes) {
- out.push(` ${t},`);
+ out.push(` ${t},`)
}
- out.push(`} from './types';`);
+ out.push(`} from './types';`)
}
// Import param types from admin-params
if (paramTypeNames.length > 0) {
- out.push(`import type {`);
+ out.push(`import type {`)
for (const name of paramTypeNames) {
- out.push(` ${name},`);
+ out.push(` ${name},`)
}
- out.push(`} from './params';`);
+ out.push(`} from './params';`)
}
- out.push(``);
+ out.push(``)
// Re-export param types so consumers can import from either file
if (paramTypeNames.length > 0) {
- out.push(`export type {`);
+ out.push(`export type {`)
for (const name of paramTypeNames) {
- out.push(` ${name},`);
+ out.push(` ${name},`)
}
- out.push(`} from './params';`);
- out.push(``);
+ out.push(`} from './params';`)
+ out.push(``)
}
- out.push(``);
+ out.push(``)
// Class
- out.push(`export class AdminClient {`);
- out.push(` /** @internal */`);
- out.push(` readonly request: RequestFn;`);
- out.push(``);
- out.push(` constructor(request: RequestFn) {`);
- out.push(` this.request = request;`);
- out.push(` }`);
- out.push(``);
- out.push(` // ============================================`);
- out.push(` // Authentication (hand-written, not auto-generated)`);
- out.push(` // ============================================`);
- out.push(``);
- out.push(` readonly auth = {`);
- out.push(` /** Login with email and password */`);
- out.push(` login: (credentials: LoginCredentials, options?: RequestOptions): Promise<AuthTokens> =>`);
- out.push(` this.request<AuthTokens>('POST', '/auth/login', { ...options, body: credentials }),`);
- out.push(``);
- out.push(` /** Refresh access token (requires valid Bearer token) */`);
- out.push(` refresh: (options?: RequestOptions): Promise<AuthTokens> =>`);
- out.push(` this.request<AuthTokens>('POST', '/auth/refresh', options),`);
- out.push(` };`);
+ out.push(`export class AdminClient {`)
+ out.push(` /** @internal */`)
+ out.push(` readonly request: RequestFn;`)
+ out.push(``)
+ out.push(` constructor(request: RequestFn) {`)
+ out.push(` this.request = request;`)
+ out.push(` }`)
+ out.push(``)
+ out.push(` // ============================================`)
+ out.push(` // Authentication (hand-written, not auto-generated)`)
+ out.push(` // ============================================`)
+ out.push(``)
+ out.push(` readonly auth = {`)
+ out.push(` /** Login with email and password */`)
+ out.push(
+ ` login: (credentials: LoginCredentials, options?: RequestOptions): Promise<AuthTokens> =>`,
+ )
+ out.push(
+ ` this.request<AuthTokens>('POST', '/auth/login', { ...options, body: credentials }),`,
+ )
+ out.push(``)
+ out.push(` /** Refresh access token (requires valid Bearer token) */`)
+ out.push(` refresh: (options?: RequestOptions): Promise<AuthTokens> =>`)
+ out.push(` this.request<AuthTokens>('POST', '/auth/refresh', options),`)
+ out.push(` };`)
// Top-level resources
for (const resource of topLevel) {
- const propName = camelCase(resource.name);
- const nestedResources = nested.filter((n) => n.parentName === resource.name);
+ const propName = camelCase(resource.name)
+ const nestedResources = nested.filter((n) => n.parentName === resource.name)
- out.push(``);
- out.push(` // ============================================`);
- out.push(` // ${resource.tag}`);
- out.push(` // ============================================`);
- out.push(``);
- out.push(` readonly ${propName} = {`);
- out.push(generateResourceMethods(resource, paramTypes));
+ out.push(``)
+ out.push(` // ============================================`)
+ out.push(` // ${resource.tag}`)
+ out.push(` // ============================================`)
+ out.push(``)
+ out.push(` readonly ${propName} = {`)
+ out.push(generateResourceMethods(resource, paramTypes))
// Add nested resources as sub-objects
for (const nestedResource of nestedResources) {
- const nestedPropName = camelCase(nestedResource.name);
+ const nestedPropName = camelCase(nestedResource.name)
// Find deeply nested resources under this nested resource
const deepChildren = deeplyNested.filter(
- (d) => d.grandparentName === resource.name && d.parentName === nestedResource.name
- );
+ (d) => d.grandparentName === resource.name && d.parentName === nestedResource.name,
+ )
- out.push(` /** Nested: ${resource.name}/{id}/${nestedResource.name} */`);
- out.push(` ${nestedPropName}: {`);
+ out.push(` /** Nested: ${resource.name}/{id}/${nestedResource.name} */`)
+ out.push(` ${nestedPropName}: {`)
// Indent nested methods by 2 more spaces
const nestedMethods = generateResourceMethods(nestedResource, paramTypes)
.split('\n')
.map((line) => (line.trim() ? ` ${line}` : line))
- .join('\n');
- out.push(nestedMethods);
+ .join('\n')
+ out.push(nestedMethods)
// Add deeply nested resources as sub-sub-objects
for (const deepResource of deepChildren) {
- const deepPropName = camelCase(deepResource.name);
- out.push(` /** Nested: ${resource.name}/{id}/${nestedResource.name}/{id}/${deepResource.name} */`);
- out.push(` ${deepPropName}: {`);
+ const deepPropName = camelCase(deepResource.name)
+ out.push(
+ ` /** Nested: ${resource.name}/{id}/${nestedResource.name}/{id}/${deepResource.name} */`,
+ )
+ out.push(` ${deepPropName}: {`)
const deepMethods = generateResourceMethods(deepResource, paramTypes)
.split('\n')
.map((line) => (line.trim() ? ` ${line}` : line))
- .join('\n');
- out.push(deepMethods);
- out.push(` },`);
- out.push(``);
+ .join('\n')
+ out.push(deepMethods)
+ out.push(` },`)
+ out.push(``)
}
- out.push(` },`);
- out.push(``);
+ out.push(` },`)
+ out.push(``)
}
- out.push(` };`);
+ out.push(` };`)
}
// Any orphan nested resources (parent not in spec yet)
- const orphanNested = nested.filter(
- (n) => !topLevel.some((t) => t.name === n.parentName)
- );
+ const orphanNested = nested.filter((n) => !topLevel.some((t) => t.name === n.parentName))
for (const resource of orphanNested) {
- const propName = `${camelCase(resource.parentName!)}${singularPascal(resource.name).replace(/s$/, '')}s`;
- out.push(``);
- out.push(` // ============================================`);
- out.push(` // ${resource.tag} (nested under ${resource.parentName})`);
- out.push(` // ============================================`);
- out.push(``);
- out.push(` readonly ${propName} = {`);
- out.push(generateResourceMethods(resource, paramTypes));
- out.push(` };`);
+ const propName = `${camelCase(resource.parentName!)}${singularPascal(resource.name).replace(/s$/, '')}s`
+ out.push(``)
+ out.push(` // ============================================`)
+ out.push(` // ${resource.tag} (nested under ${resource.parentName})`)
+ out.push(` // ============================================`)
+ out.push(``)
+ out.push(` readonly ${propName} = {`)
+ out.push(generateResourceMethods(resource, paramTypes))
+ out.push(` };`)
}
- out.push(`}`);
- out.push(``);
+ out.push(`}`)
+ out.push(``)
return {
client: out.join('\n'),
params: generateParamsFile(paramTypes),
- };
+ }
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
-const SPEC_PATH = path.resolve(import.meta.dirname, '../../../docs/api-reference/admin.yaml');
-const OUTPUT_PATH = path.resolve(import.meta.dirname, '../src/admin-client.ts');
-const PARAMS_PATH = path.resolve(import.meta.dirname, '../src/params.ts');
+const SPEC_PATH = path.resolve(import.meta.dirname, '../../../docs/api-reference/admin.yaml')
+const OUTPUT_PATH = path.resolve(import.meta.dirname, '../src/admin-client.ts')
+const PARAMS_PATH = path.resolve(import.meta.dirname, '../src/params.ts')
if (!fs.existsSync(SPEC_PATH)) {
- console.error(`Admin API spec not found at: ${SPEC_PATH}`);
- console.error('Run `bundle exec rake rswag:specs:swaggerize` first to generate it.');
- process.exit(1);
+ console.error(`Admin API spec not found at: ${SPEC_PATH}`)
+ console.error('Run `bundle exec rake rswag:specs:swaggerize` first to generate it.')
+ process.exit(1)
}
-console.log(`Reading: ${SPEC_PATH}`);
-const yamlContent = fs.readFileSync(SPEC_PATH, 'utf-8');
+console.log(`Reading: ${SPEC_PATH}`)
+const yamlContent = fs.readFileSync(SPEC_PATH, 'utf-8')
// Use a proper YAML parser — try to import js-yaml or yaml, fall back to JSON conversion via CLI
-let spec: OpenApiSpec;
+let spec: OpenApiSpec
try {
// Try dynamic import of yaml (common in Node projects)
- const yamlModule = await import('yaml');
- spec = yamlModule.parse(yamlContent) as OpenApiSpec;
+ const yamlModule = await import('yaml')
+ spec = yamlModule.parse(yamlContent) as OpenApiSpec
} catch {
try {
// Try js-yaml
- const jsYaml = await import('js-yaml');
- spec = jsYaml.load(yamlContent) as OpenApiSpec;
+ const jsYaml = await import('js-yaml')
+ spec = jsYaml.load(yamlContent) as OpenApiSpec
} catch {
// Last resort: use our minimal parser
- console.warn('No YAML parser found (yaml or js-yaml). Using minimal built-in parser.');
- spec = parseYaml(yamlContent) as OpenApiSpec;
+ console.warn('No YAML parser found (yaml or js-yaml). Using minimal built-in parser.')
+ spec = parseYaml(yamlContent) as OpenApiSpec
}
}
-const { client, params } = generateClient(spec);
+const { client, params } = generateClient(spec)
-fs.writeFileSync(PARAMS_PATH, params, 'utf-8');
-console.log(`Generated: ${PARAMS_PATH}`);
+fs.writeFileSync(PARAMS_PATH, params, 'utf-8')
+console.log(`Generated: ${PARAMS_PATH}`)
-fs.writeFileSync(OUTPUT_PATH, client, 'utf-8');
-console.log(`Generated: ${OUTPUT_PATH}`);
+fs.writeFileSync(OUTPUT_PATH, client, 'utf-8')
+console.log(`Generated: ${OUTPUT_PATH}`)
// Summary
-const resources = analyzeResources(spec);
-console.log(`\nResources (${resources.length}):`);
+const resources = analyzeResources(spec)
+console.log(`\nResources (${resources.length}):`)
for (const r of resources) {
- const prefix = r.parentName ? ` └─ ${r.parentName}/{id}/` : ' ';
- console.log(`${prefix}${r.name} (${r.endpoints.map((e) => `${e.method} ${e.action}`).join(', ')})`);
+ const prefix = r.parentName ? ` └─ ${r.parentName}/{id}/` : ' '
+ console.log(
+ `${prefix}${r.name} (${r.endpoints.map((e) => `${e.method} ${e.action}`).join(', ')})`,
+ )
}
diff --git a/packages/admin-sdk/src/admin-client.ts b/packages/admin-sdk/src/admin-client.ts
index 29d3a2297d..f1b98d27e3 100644
--- a/packages/admin-sdk/src/admin-client.ts
+++ b/packages/admin-sdk/src/admin-client.ts
@@ -1,109 +1,129 @@
-import type { RequestFn, RequestOptions } from '@spree/sdk-core';
-import { transformListParams, getParams } from '@spree/sdk-core';
-import type { PaginatedResponse, ListParams } from '@spree/sdk-core';
+import type { ListParams, PaginatedResponse, RequestFn, RequestOptions } from '@spree/sdk-core'
+import { getParams, transformListParams } from '@spree/sdk-core'
export interface DashboardAnalytics {
- currency: string;
- date_from: string;
- date_to: string;
+ currency: string
+ date_from: string
+ date_to: string
summary: {
- sales_total: number;
- display_sales_total: string;
- sales_growth: number;
- orders_count: number;
- orders_growth: number;
- avg_order_value: number;
- display_avg_order_value: string;
- avg_order_value_growth: number;
- };
+ sales_total: number
+ display_sales_total: string
+ sales_growth: number
+ orders_count: number
+ orders_growth: number
+ avg_order_value: number
+ display_avg_order_value: string
+ avg_order_value_growth: number
+ }
chart_data: Array<{
- date: string;
- sales: number;
- orders: number;
- avg_order_value: number;
- }>;
+ date: string
+ sales: number
+ orders: number
+ avg_order_value: number
+ }>
top_products: Array<{
- id: string;
- name: string;
- slug: string;
- image_url: string | null;
- price: string | null;
- quantity: number;
- total: string;
- }>;
+ id: string
+ name: string
+ slug: string
+ image_url: string | null
+ price: string | null
+ quantity: number
+ total: string
+ }>
}
export interface AuthTokens {
- token: string;
- refresh_token?: string;
+ token: string
+ refresh_token?: string
user: {
- id: string;
- email: string;
- first_name: string | null;
- last_name: string | null;
- };
+ id: string
+ email: string
+ first_name: string | null
+ last_name: string | null
+ }
}
export interface LoginCredentials {
- email: string;
- password: string;
+ email: string
+ password: string
}
export interface PermissionRule {
/** true for `can`, false for `cannot` */
- allow: boolean;
+ allow: boolean
/** Action names, e.g. ["read", "update"] or ["manage"] */
- actions: string[];
+ actions: string[]
/** Subject class names, e.g. ["Spree::Product"] or ["all"] */
- subjects: string[];
+ subjects: string[]
/** Whether the server rule has per-record conditions. If true, the action may be denied at the record level and the SPA should expect possible 403. */
- has_conditions: boolean;
+ has_conditions: boolean
}
export interface MeResponse {
user: {
- id: string;
- email: string;
- first_name: string | null;
- last_name: string | null;
- };
- permissions: PermissionRule[];
+ id: string
+ email: string
+ first_name: string | null
+ last_name: string | null
+ }
+ permissions: PermissionRule[]
}
-import type { Store, Product, Order, Media, Category, TaxCategory, Country, Variant, PaymentMethod, Customer, CreditCard, Payment, Address, StoreCredit, LineItem, Fulfillment, Refund, Adjustment, OptionType } from './types';
+
import type {
- StoreUpdateParams,
- ProductUpdateParams,
- OrderCreateParams,
- OrderUpdateParams,
- OrderCompleteParams,
- OrderCancelParams,
- OrderApproveParams,
- GiftCardApplyParams,
- StoreCreditApplyParams,
- PaymentCreateParams,
- CustomerCreateParams,
- CustomerUpdateParams,
CustomerAddressParams,
+ CustomerCreateParams,
CustomerStoreCreditCreateParams,
CustomerStoreCreditUpdateParams,
- MediaCreateParams,
- MediaUpdateParams,
+ CustomerUpdateParams,
+ DirectUploadCreateParams,
+ FulfillmentUpdateParams,
+ GiftCardApplyParams,
LineItemCreateParams,
LineItemUpdateParams,
- FulfillmentUpdateParams,
- VariantCreateParams,
- VariantUpdateParams,
+ MediaCreateParams,
+ MediaUpdateParams,
OptionTypeCreateParams,
OptionTypeUpdateParams,
- DirectUploadCreateParams,
-} from './params';
+ OrderApproveParams,
+ OrderCancelParams,
+ OrderCompleteParams,
+ OrderCreateParams,
+ OrderUpdateParams,
+ PaymentCreateParams,
+ ProductUpdateParams,
+ StoreCreditApplyParams,
+ StoreUpdateParams,
+ VariantCreateParams,
+ VariantUpdateParams,
+} from './params'
+import type {
+ Address,
+ Adjustment,
+ Category,
+ Country,
+ CreditCard,
+ Customer,
+ Fulfillment,
+ LineItem,
+ Media,
+ OptionType,
+ Order,
+ Payment,
+ PaymentMethod,
+ Product,
+ Refund,
+ Store,
+ StoreCredit,
+ TaxCategory,
+ Variant,
+} from './types'
export class AdminClient {
/** @internal */
- readonly request: RequestFn;
+ readonly request: RequestFn
constructor(request: RequestFn) {
- this.request = request;
+ this.request = request
}
// ============================================
@@ -116,7 +136,7 @@ export class AdminClient {
refresh: (params: { refresh_token: string }, options?: RequestOptions): Promise<AuthTokens> =>
this.request<AuthTokens>('POST', '/auth/refresh', { ...options, body: params }),
- };
+ }
// ============================================
// Current admin user + permissions
@@ -126,19 +146,22 @@ export class AdminClient {
/** Get the current admin user profile and their serialized permissions. */
show: (options?: RequestOptions): Promise<MeResponse> =>
this.request<MeResponse>('GET', '/me', options),
- };
+ }
// ============================================
// Dashboard
// ============================================
readonly dashboard = {
- analytics: (params?: { date_from?: string; date_to?: string; currency?: string }, options?: RequestOptions): Promise<DashboardAnalytics> =>
+ analytics: (
+ params?: { date_from?: string; date_to?: string; currency?: string },
+ options?: RequestOptions,
+ ): Promise<DashboardAnalytics> =>
this.request<DashboardAnalytics>('GET', '/dashboard/analytics', {
...options,
params: params as Record<string, string>,
}),
- };
+ }
// ============================================
// Store Settings
@@ -150,14 +173,17 @@ export class AdminClient {
update: (params: StoreUpdateParams, options?: RequestOptions): Promise<Store> =>
this.request<Store>('PATCH', '/store', { ...options, body: params }),
- };
+ }
// ============================================
// Products
// ============================================
readonly products = {
- list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Product>> =>
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Product>> =>
this.request<PaginatedResponse<Product>>('GET', '/products', {
...options,
params: params ? transformListParams(params) : undefined,
@@ -176,69 +202,147 @@ export class AdminClient {
this.request<void>('DELETE', `/products/${id}`, options),
media: {
- list: (productId: string, params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Media>> =>
+ list: (
+ productId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Media>> =>
this.request<PaginatedResponse<Media>>('GET', `/products/${productId}/media`, {
...options,
params: params ? transformListParams(params) : undefined,
}),
- create: (productId: string, params: MediaCreateParams, options?: RequestOptions): Promise<Media> =>
+ create: (
+ productId: string,
+ params: MediaCreateParams,
+ options?: RequestOptions,
+ ): Promise<Media> =>
this.request<Media>('POST', `/products/${productId}/media`, { ...options, body: params }),
- update: (productId: string, id: string, params: MediaUpdateParams, options?: RequestOptions): Promise<Media> =>
- this.request<Media>('PATCH', `/products/${productId}/media/${id}`, { ...options, body: params }),
+ update: (
+ productId: string,
+ id: string,
+ params: MediaUpdateParams,
+ options?: RequestOptions,
+ ): Promise<Media> =>
+ this.request<Media>('PATCH', `/products/${productId}/media/${id}`, {
+ ...options,
+ body: params,
+ }),
delete: (productId: string, id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/products/${productId}/media/${id}`, options),
},
variants: {
- list: (productId: string, params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Variant>> =>
+ list: (
+ productId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Variant>> =>
this.request<PaginatedResponse<Variant>>('GET', `/products/${productId}/variants`, {
...options,
params: params ? transformListParams(params) : undefined,
}),
- get: (productId: string, id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<Variant> =>
+ get: (
+ productId: string,
+ id: string,
+ params?: { expand?: string[] },
+ options?: RequestOptions,
+ ): Promise<Variant> =>
this.request<Variant>('GET', `/products/${productId}/variants/${id}`, {
...options,
params: getParams(params),
}),
- create: (productId: string, params: VariantCreateParams, options?: RequestOptions): Promise<Variant> =>
- this.request<Variant>('POST', `/products/${productId}/variants`, { ...options, body: params }),
+ create: (
+ productId: string,
+ params: VariantCreateParams,
+ options?: RequestOptions,
+ ): Promise<Variant> =>
+ this.request<Variant>('POST', `/products/${productId}/variants`, {
+ ...options,
+ body: params,
+ }),
- update: (productId: string, id: string, params: VariantUpdateParams, options?: RequestOptions): Promise<Variant> =>
- this.request<Variant>('PATCH', `/products/${productId}/variants/${id}`, { ...options, body: params }),
+ update: (
+ productId: string,
+ id: string,
+ params: VariantUpdateParams,
+ options?: RequestOptions,
+ ): Promise<Variant> =>
+ this.request<Variant>('PATCH', `/products/${productId}/variants/${id}`, {
+ ...options,
+ body: params,
+ }),
delete: (productId: string, id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/products/${productId}/variants/${id}`, options),
media: {
- list: (productId: string, variantId: string, params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Media>> =>
- this.request<PaginatedResponse<Media>>('GET', `/products/${productId}/variants/${variantId}/media`, {
+ list: (
+ productId: string,
+ variantId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Media>> =>
+ this.request<PaginatedResponse<Media>>(
+ 'GET',
+ `/products/${productId}/variants/${variantId}/media`,
+ {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ },
+ ),
+
+ create: (
+ productId: string,
+ variantId: string,
+ params: MediaCreateParams,
+ options?: RequestOptions,
+ ): Promise<Media> =>
+ this.request<Media>('POST', `/products/${productId}/variants/${variantId}/media`, {
...options,
- params: params ? transformListParams(params) : undefined,
+ body: params,
}),
- create: (productId: string, variantId: string, params: MediaCreateParams, options?: RequestOptions): Promise<Media> =>
- this.request<Media>('POST', `/products/${productId}/variants/${variantId}/media`, { ...options, body: params }),
-
- update: (productId: string, variantId: string, id: string, params: MediaUpdateParams, options?: RequestOptions): Promise<Media> =>
- this.request<Media>('PATCH', `/products/${productId}/variants/${variantId}/media/${id}`, { ...options, body: params }),
+ update: (
+ productId: string,
+ variantId: string,
+ id: string,
+ params: MediaUpdateParams,
+ options?: RequestOptions,
+ ): Promise<Media> =>
+ this.request<Media>('PATCH', `/products/${productId}/variants/${variantId}/media/${id}`, {
+ ...options,
+ body: params,
+ }),
- delete: (productId: string, variantId: string, id: string, options?: RequestOptions): Promise<void> =>
- this.request<void>('DELETE', `/products/${productId}/variants/${variantId}/media/${id}`, options),
+ delete: (
+ productId: string,
+ variantId: string,
+ id: string,
+ options?: RequestOptions,
+ ): Promise<void> =>
+ this.request<void>(
+ 'DELETE',
+ `/products/${productId}/variants/${variantId}/media/${id}`,
+ options,
+ ),
},
},
- };
+ }
// ============================================
// Orders
// ============================================
readonly orders = {
- list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Order>> =>
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Order>> =>
this.request<PaginatedResponse<Order>>('GET', '/orders', {
...options,
params: params ? transformListParams(params) : undefined,
@@ -253,13 +357,21 @@ export class AdminClient {
create: (params: OrderCreateParams, options?: RequestOptions): Promise<Order> =>
this.request<Order>('POST', '/orders', { ...options, body: params }),
- update: (id: string, params: OrderUpdateParams | Record<string, unknown>, options?: RequestOptions): Promise<Order> =>
+ update: (
+ id: string,
+ params: OrderUpdateParams | Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<Order> =>
this.request<Order>('PATCH', `/orders/${id}`, { ...options, body: params }),
delete: (id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/orders/${id}`, options),
- complete: (id: string, params?: OrderCompleteParams, options?: RequestOptions): Promise<Order> =>
+ complete: (
+ id: string,
+ params?: OrderCompleteParams,
+ options?: RequestOptions,
+ ): Promise<Order> =>
this.request<Order>('PATCH', `/orders/${id}/complete`, { ...options, body: params }),
cancel: (id: string, params?: OrderCancelParams, options?: RequestOptions): Promise<Order> =>
@@ -275,7 +387,11 @@ export class AdminClient {
this.request<void>('POST', `/orders/${id}/resend_confirmation`, options),
giftCards: {
- apply: (orderId: string, params: GiftCardApplyParams, options?: RequestOptions): Promise<unknown> =>
+ apply: (
+ orderId: string,
+ params: GiftCardApplyParams,
+ options?: RequestOptions,
+ ): Promise<unknown> =>
this.request('POST', `/orders/${orderId}/gift_cards`, { ...options, body: params }),
remove: (orderId: string, id: string, options?: RequestOptions): Promise<void> =>
@@ -283,54 +399,103 @@ export class AdminClient {
},
storeCredits: {
- apply: (orderId: string, params?: StoreCreditApplyParams, options?: RequestOptions): Promise<Order> =>
- this.request<Order>('POST', `/orders/${orderId}/store_credits`, { ...options, body: params }),
+ apply: (
+ orderId: string,
+ params?: StoreCreditApplyParams,
+ options?: RequestOptions,
+ ): Promise<Order> =>
+ this.request<Order>('POST', `/orders/${orderId}/store_credits`, {
+ ...options,
+ body: params,
+ }),
remove: (orderId: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/orders/${orderId}/store_credits`, options),
},
items: {
- list: (orderId: string, params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<LineItem>> =>
+ list: (
+ orderId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<LineItem>> =>
this.request<PaginatedResponse<LineItem>>('GET', `/orders/${orderId}/items`, {
...options,
params: params ? transformListParams(params) : undefined,
}),
- get: (orderId: string, id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<LineItem> =>
+ get: (
+ orderId: string,
+ id: string,
+ params?: { expand?: string[] },
+ options?: RequestOptions,
+ ): Promise<LineItem> =>
this.request<LineItem>('GET', `/orders/${orderId}/items/${id}`, {
...options,
params: getParams(params),
}),
- create: (orderId: string, params: LineItemCreateParams, options?: RequestOptions): Promise<LineItem> =>
+ create: (
+ orderId: string,
+ params: LineItemCreateParams,
+ options?: RequestOptions,
+ ): Promise<LineItem> =>
this.request<LineItem>('POST', `/orders/${orderId}/items`, { ...options, body: params }),
- update: (orderId: string, id: string, params: LineItemUpdateParams, options?: RequestOptions): Promise<LineItem> =>
- this.request<LineItem>('PATCH', `/orders/${orderId}/items/${id}`, { ...options, body: params }),
+ update: (
+ orderId: string,
+ id: string,
+ params: LineItemUpdateParams,
+ options?: RequestOptions,
+ ): Promise<LineItem> =>
+ this.request<LineItem>('PATCH', `/orders/${orderId}/items/${id}`, {
+ ...options,
+ body: params,
+ }),
delete: (orderId: string, id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/orders/${orderId}/items/${id}`, options),
},
fulfillments: {
- list: (orderId: string, params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Fulfillment>> =>
+ list: (
+ orderId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Fulfillment>> =>
this.request<PaginatedResponse<Fulfillment>>('GET', `/orders/${orderId}/fulfillments`, {
...options,
params: params ? transformListParams(params) : undefined,
}),
- get: (orderId: string, id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<Fulfillment> =>
+ get: (
+ orderId: string,
+ id: string,
+ params?: { expand?: string[] },
+ options?: RequestOptions,
+ ): Promise<Fulfillment> =>
this.request<Fulfillment>('GET', `/orders/${orderId}/fulfillments/${id}`, {
...options,
params: getParams(params),
}),
- update: (orderId: string, id: string, params: FulfillmentUpdateParams, options?: RequestOptions): Promise<Fulfillment> =>
- this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}`, { ...options, body: params }),
+ update: (
+ orderId: string,
+ id: string,
+ params: FulfillmentUpdateParams,
+ options?: RequestOptions,
+ ): Promise<Fulfillment> =>
+ this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}`, {
+ ...options,
+ body: params,
+ }),
fulfill: (orderId: string, id: string, options?: RequestOptions): Promise<Fulfillment> =>
- this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}/fulfill`, options),
+ this.request<Fulfillment>(
+ 'PATCH',
+ `/orders/${orderId}/fulfillments/${id}/fulfill`,
+ options,
+ ),
cancel: (orderId: string, id: string, options?: RequestOptions): Promise<Fulfillment> =>
this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}/cancel`, options),
@@ -338,24 +503,45 @@ export class AdminClient {
resume: (orderId: string, id: string, options?: RequestOptions): Promise<Fulfillment> =>
this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}/resume`, options),
- split: (orderId: string, id: string, params: { quantity: number; line_item_id?: string }, options?: RequestOptions): Promise<Fulfillment> =>
- this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}/split`, { ...options, body: params }),
+ split: (
+ orderId: string,
+ id: string,
+ params: { quantity: number; line_item_id?: string },
+ options?: RequestOptions,
+ ): Promise<Fulfillment> =>
+ this.request<Fulfillment>('PATCH', `/orders/${orderId}/fulfillments/${id}/split`, {
+ ...options,
+ body: params,
+ }),
},
payments: {
- list: (orderId: string, params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Payment>> =>
+ list: (
+ orderId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Payment>> =>
this.request<PaginatedResponse<Payment>>('GET', `/orders/${orderId}/payments`, {
...options,
params: params ? transformListParams(params) : undefined,
}),
- get: (orderId: string, id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<Payment> =>
+ get: (
+ orderId: string,
+ id: string,
+ params?: { expand?: string[] },
+ options?: RequestOptions,
+ ): Promise<Payment> =>
this.request<Payment>('GET', `/orders/${orderId}/payments/${id}`, {
...options,
params: getParams(params),
}),
- create: (orderId: string, params: PaymentCreateParams, options?: RequestOptions): Promise<Payment> =>
+ create: (
+ orderId: string,
+ params: PaymentCreateParams,
+ options?: RequestOptions,
+ ): Promise<Payment> =>
this.request<Payment>('POST', `/orders/${orderId}/payments`, { ...options, body: params }),
capture: (orderId: string, id: string, options?: RequestOptions): Promise<Payment> =>
@@ -366,18 +552,35 @@ export class AdminClient {
},
refunds: {
- list: (orderId: string, params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Refund>> =>
+ list: (
+ orderId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Refund>> =>
this.request<PaginatedResponse<Refund>>('GET', `/orders/${orderId}/refunds`, {
...options,
params: params ? transformListParams(params) : undefined,
}),
- create: (orderId: string, params: { payment_id: string; amount: number; reason_id?: string; refund_reason_id?: string }, options?: RequestOptions): Promise<Refund> =>
+ create: (
+ orderId: string,
+ params: {
+ payment_id: string
+ amount: number
+ reason_id?: string
+ refund_reason_id?: string
+ },
+ options?: RequestOptions,
+ ): Promise<Refund> =>
this.request<Refund>('POST', `/orders/${orderId}/refunds`, { ...options, body: params }),
},
adjustments: {
- list: (orderId: string, params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Adjustment>> =>
+ list: (
+ orderId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Adjustment>> =>
this.request<PaginatedResponse<Adjustment>>('GET', `/orders/${orderId}/adjustments`, {
...options,
params: params ? transformListParams(params) : undefined,
@@ -386,20 +589,27 @@ export class AdminClient {
get: (orderId: string, id: string, options?: RequestOptions): Promise<Adjustment> =>
this.request<Adjustment>('GET', `/orders/${orderId}/adjustments/${id}`, options),
},
- };
+ }
// ============================================
// Option Types
// ============================================
readonly optionTypes = {
- list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<OptionType>> =>
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<OptionType>> =>
this.request<PaginatedResponse<OptionType>>('GET', '/option_types', {
...options,
params: params ? transformListParams(params) : undefined,
}),
- get: (id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<OptionType> =>
+ get: (
+ id: string,
+ params?: { expand?: string[] },
+ options?: RequestOptions,
+ ): Promise<OptionType> =>
this.request<OptionType>('GET', `/option_types/${id}`, {
...options,
params: getParams(params),
@@ -408,68 +618,102 @@ export class AdminClient {
create: (params: OptionTypeCreateParams, options?: RequestOptions): Promise<OptionType> =>
this.request<OptionType>('POST', '/option_types', { ...options, body: params }),
- update: (id: string, params: OptionTypeUpdateParams, options?: RequestOptions): Promise<OptionType> =>
+ update: (
+ id: string,
+ params: OptionTypeUpdateParams,
+ options?: RequestOptions,
+ ): Promise<OptionType> =>
this.request<OptionType>('PATCH', `/option_types/${id}`, { ...options, body: params }),
delete: (id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/option_types/${id}`, options),
- };
+ }
// ============================================
// Payment Methods
// ============================================
readonly paymentMethods = {
- list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<PaymentMethod>> =>
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<PaymentMethod>> =>
this.request<PaginatedResponse<PaymentMethod>>('GET', '/payment_methods', {
...options,
params: params ? transformListParams(params) : undefined,
}),
- get: (id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<PaymentMethod> =>
+ get: (
+ id: string,
+ params?: { expand?: string[] },
+ options?: RequestOptions,
+ ): Promise<PaymentMethod> =>
this.request<PaymentMethod>('GET', `/payment_methods/${id}`, {
...options,
params: getParams(params),
}),
- };
+ }
// ============================================
// Tags
// ============================================
readonly tags = {
- list: (params: { taggable_type: string; q?: string }, options?: RequestOptions): Promise<{ data: Array<{ name: string }> }> =>
+ list: (
+ params: { taggable_type: string; q?: string },
+ options?: RequestOptions,
+ ): Promise<{ data: Array<{ name: string }> }> =>
this.request<{ data: Array<{ name: string }> }>('GET', '/tags', {
...options,
params,
}),
- };
+ }
// ============================================
// Customers
// ============================================
readonly customers = {
- list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Customer>> =>
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Customer>> =>
this.request<PaginatedResponse<Customer>>('GET', '/customers', {
...options,
params: params ? transformListParams(params) : undefined,
}),
- get: (id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<Customer> =>
+ get: (
+ id: string,
+ params?: { expand?: string[] },
+ options?: RequestOptions,
+ ): Promise<Customer> =>
this.request<Customer>('GET', `/customers/${id}`, {
...options,
params: getParams(params),
}),
creditCards: {
- list: (customerId: string, params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<CreditCard>> =>
- this.request<PaginatedResponse<CreditCard>>('GET', `/customers/${customerId}/credit_cards`, {
- ...options,
- params: params ? transformListParams(params) : undefined,
- }),
-
- get: (customerId: string, id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<CreditCard> =>
+ list: (
+ customerId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<CreditCard>> =>
+ this.request<PaginatedResponse<CreditCard>>(
+ 'GET',
+ `/customers/${customerId}/credit_cards`,
+ {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ },
+ ),
+
+ get: (
+ customerId: string,
+ id: string,
+ params?: { expand?: string[] },
+ options?: RequestOptions,
+ ): Promise<CreditCard> =>
this.request<CreditCard>('GET', `/customers/${customerId}/credit_cards/${id}`, {
...options,
params: getParams(params),
@@ -482,77 +726,139 @@ export class AdminClient {
create: (params: CustomerCreateParams, options?: RequestOptions): Promise<Customer> =>
this.request<Customer>('POST', '/customers', { ...options, body: params }),
- update: (id: string, params: CustomerUpdateParams, options?: RequestOptions): Promise<Customer> =>
+ update: (
+ id: string,
+ params: CustomerUpdateParams,
+ options?: RequestOptions,
+ ): Promise<Customer> =>
this.request<Customer>('PATCH', `/customers/${id}`, { ...options, body: params }),
delete: (id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/customers/${id}`, options),
addresses: {
- list: (customerId: string, params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Address>> =>
+ list: (
+ customerId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Address>> =>
this.request<PaginatedResponse<Address>>('GET', `/customers/${customerId}/addresses`, {
...options,
params: params ? transformListParams(params) : undefined,
}),
- get: (customerId: string, id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<Address> =>
+ get: (
+ customerId: string,
+ id: string,
+ params?: { expand?: string[] },
+ options?: RequestOptions,
+ ): Promise<Address> =>
this.request<Address>('GET', `/customers/${customerId}/addresses/${id}`, {
...options,
params: getParams(params),
}),
- create: (customerId: string, params: CustomerAddressParams, options?: RequestOptions): Promise<Address> =>
- this.request<Address>('POST', `/customers/${customerId}/addresses`, { ...options, body: params }),
+ create: (
+ customerId: string,
+ params: CustomerAddressParams,
+ options?: RequestOptions,
+ ): Promise<Address> =>
+ this.request<Address>('POST', `/customers/${customerId}/addresses`, {
+ ...options,
+ body: params,
+ }),
- update: (customerId: string, id: string, params: CustomerAddressParams, options?: RequestOptions): Promise<Address> =>
- this.request<Address>('PATCH', `/customers/${customerId}/addresses/${id}`, { ...options, body: params }),
+ update: (
+ customerId: string,
+ id: string,
+ params: CustomerAddressParams,
+ options?: RequestOptions,
+ ): Promise<Address> =>
+ this.request<Address>('PATCH', `/customers/${customerId}/addresses/${id}`, {
+ ...options,
+ body: params,
+ }),
delete: (customerId: string, id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/customers/${customerId}/addresses/${id}`, options),
},
storeCredits: {
- list: (customerId: string, params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<StoreCredit>> =>
- this.request<PaginatedResponse<StoreCredit>>('GET', `/customers/${customerId}/store_credits`, {
- ...options,
- params: params ? transformListParams(params) : undefined,
- }),
-
- get: (customerId: string, id: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<StoreCredit> =>
+ list: (
+ customerId: string,
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<StoreCredit>> =>
+ this.request<PaginatedResponse<StoreCredit>>(
+ 'GET',
+ `/customers/${customerId}/store_credits`,
+ {
+ ...options,
+ params: params ? transformListParams(params) : undefined,
+ },
+ ),
+
+ get: (
+ customerId: string,
+ id: string,
+ params?: { expand?: string[] },
+ options?: RequestOptions,
+ ): Promise<StoreCredit> =>
this.request<StoreCredit>('GET', `/customers/${customerId}/store_credits/${id}`, {
...options,
params: getParams(params),
}),
- create: (customerId: string, params: CustomerStoreCreditCreateParams, options?: RequestOptions): Promise<StoreCredit> =>
- this.request<StoreCredit>('POST', `/customers/${customerId}/store_credits`, { ...options, body: params }),
+ create: (
+ customerId: string,
+ params: CustomerStoreCreditCreateParams,
+ options?: RequestOptions,
+ ): Promise<StoreCredit> =>
+ this.request<StoreCredit>('POST', `/customers/${customerId}/store_credits`, {
+ ...options,
+ body: params,
+ }),
- update: (customerId: string, id: string, params: CustomerStoreCreditUpdateParams, options?: RequestOptions): Promise<StoreCredit> =>
- this.request<StoreCredit>('PATCH', `/customers/${customerId}/store_credits/${id}`, { ...options, body: params }),
+ update: (
+ customerId: string,
+ id: string,
+ params: CustomerStoreCreditUpdateParams,
+ options?: RequestOptions,
+ ): Promise<StoreCredit> =>
+ this.request<StoreCredit>('PATCH', `/customers/${customerId}/store_credits/${id}`, {
+ ...options,
+ body: params,
+ }),
delete: (customerId: string, id: string, options?: RequestOptions): Promise<void> =>
this.request<void>('DELETE', `/customers/${customerId}/store_credits/${id}`, options),
},
- };
+ }
// ============================================
// Categories
// ============================================
readonly categories = {
- list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Category>> =>
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Category>> =>
this.request<PaginatedResponse<Category>>('GET', '/categories', {
...options,
params: params ? transformListParams(params) : undefined,
}),
- };
+ }
// ============================================
// Variants (top-level, for search/autocomplete)
// ============================================
readonly variants = {
- list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Variant>> =>
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Variant>> =>
this.request<PaginatedResponse<Variant>>('GET', '/variants', {
...options,
params: params ? transformListParams(params) : undefined,
@@ -563,50 +869,62 @@ export class AdminClient {
...options,
params: getParams(params),
}),
- };
+ }
// ============================================
// Tax Categories
// ============================================
readonly taxCategories = {
- list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<TaxCategory>> =>
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<TaxCategory>> =>
this.request<PaginatedResponse<TaxCategory>>('GET', '/tax_categories', {
...options,
params: params ? transformListParams(params) : undefined,
}),
- };
+ }
// ============================================
// Countries
// ============================================
readonly countries = {
- list: (params?: ListParams & Record<string, unknown>, options?: RequestOptions): Promise<PaginatedResponse<Country>> =>
+ list: (
+ params?: ListParams & Record<string, unknown>,
+ options?: RequestOptions,
+ ): Promise<PaginatedResponse<Country>> =>
this.request<PaginatedResponse<Country>>('GET', '/countries', {
...options,
params: params ? transformListParams(params) : undefined,
}),
- get: (iso: string, params?: { expand?: string[] }, options?: RequestOptions): Promise<Country> =>
+ get: (
+ iso: string,
+ params?: { expand?: string[] },
+ options?: RequestOptions,
+ ): Promise<Country> =>
this.request<Country>('GET', `/countries/${iso}`, {
...options,
params: getParams(params),
}),
- };
+ }
// ============================================
// Direct Uploads (Active Storage)
// ============================================
readonly directUploads = {
- create: (params: DirectUploadCreateParams, options?: RequestOptions): Promise<{
- direct_upload: { url: string; headers: Record<string, string> };
- signed_id: string;
- }> =>
- this.request('POST', '/direct_uploads', { ...options, body: params }),
- };
+ create: (
+ params: DirectUploadCreateParams,
+ options?: RequestOptions,
+ ): Promise<{
+ direct_upload: { url: string; headers: Record<string, string> }
+ signed_id: string
+ }> => this.request('POST', '/direct_uploads', { ...options, body: params }),
+ }
}
// Re-export for type convenience
-export type { PaginatedResponse, ListParams, RequestOptions };
+export type { ListParams, PaginatedResponse, RequestOptions }
diff --git a/packages/admin-sdk/src/client.ts b/packages/admin-sdk/src/client.ts
index c467f00e0b..0d8d540be2 100644
--- a/packages/admin-sdk/src/client.ts
+++ b/packages/admin-sdk/src/client.ts
@@ -1,59 +1,59 @@
-import { createRequestFn, resolveRetryConfig, SpreeError } from '@spree/sdk-core';
-import type { RetryConfig, RequestConfig, RequestFn, InternalRequestOptions } from '@spree/sdk-core';
-import { AdminClient } from './admin-client';
+import type { InternalRequestOptions, RequestConfig, RequestFn, RetryConfig } from '@spree/sdk-core'
+import { createRequestFn, resolveRetryConfig, SpreeError } from '@spree/sdk-core'
+import { AdminClient } from './admin-client'
export interface AdminClientConfig {
/** Base URL of the Spree API (e.g., 'https://api.mystore.com') */
- baseUrl: string;
+ baseUrl: string
/** Secret API key for server-to-server integrations (mutually exclusive with jwtToken) */
- secretKey?: string;
+ secretKey?: string
/** JWT token for admin SPA sessions (mutually exclusive with secretKey) */
- jwtToken?: string;
+ jwtToken?: string
/** Store ID header for multi-store routing (e.g., 'store_k5nR8xLq') */
- storeId?: string;
+ storeId?: string
/** Custom fetch implementation (optional, defaults to global fetch) */
- fetch?: typeof fetch;
+ fetch?: typeof fetch
/** Retry configuration. Enabled by default. Pass false to disable. */
- retry?: RetryConfig | false;
+ retry?: RetryConfig | false
}
export interface Client extends AdminClient {
/** Set or change the target store for subsequent requests (multi-store routing) */
- setStore(storeId: string): void;
+ setStore(storeId: string): void
/** Set JWT token for authenticated admin sessions */
- setToken(token: string): void;
+ setToken(token: string): void
/**
* Register a callback that fires on 401 responses.
* Return `true` to retry the original request (after refreshing the token via setToken).
* Return `false` to let the error propagate.
*/
- onUnauthorized(handler: () => Promise<boolean>): void;
+ onUnauthorized(handler: () => Promise<boolean>): void
}
export function createAdminClient(config: AdminClientConfig): Client {
if (!config.secretKey && config.jwtToken === undefined) {
- throw new Error('Admin client requires either secretKey or jwtToken');
+ throw new Error('Admin client requires either secretKey or jwtToken')
}
- const baseUrl = config.baseUrl.replace(/\/$/, '');
- const fetchFn = config.fetch || fetch.bind(globalThis);
- const retryConfig = resolveRetryConfig(config.retry);
- const requestConfig: RequestConfig = { baseUrl, fetchFn, retryConfig };
+ const baseUrl = config.baseUrl.replace(/\/$/, '')
+ const fetchFn = config.fetch || fetch.bind(globalThis)
+ const retryConfig = resolveRetryConfig(config.retry)
+ const requestConfig: RequestConfig = { baseUrl, fetchFn, retryConfig }
- let currentToken = config.jwtToken;
- let currentStoreId = config.storeId;
- let unauthorizedHandler: (() => Promise<boolean>) | null = null;
+ let currentToken = config.jwtToken
+ let currentStoreId = config.storeId
+ let unauthorizedHandler: (() => Promise<boolean>) | null = null
- const basePath = '/api/v3/admin';
+ const basePath = '/api/v3/admin'
const dynamicRequestFn: RequestFn = async <T>(
method: string,
path: string,
- options: InternalRequestOptions = {}
+ options: InternalRequestOptions = {},
): Promise<T> => {
- const extraHeaders: Record<string, string> = {};
+ const extraHeaders: Record<string, string> = {}
if (currentStoreId) {
- extraHeaders['X-Spree-Store-Id'] = currentStoreId;
+ extraHeaders['X-Spree-Store-Id'] = currentStoreId
}
const mergedOptions: InternalRequestOptions = {
@@ -62,20 +62,20 @@ export function createAdminClient(config: AdminClientConfig): Client {
...extraHeaders,
...options.headers,
},
- };
+ }
const makeRequest = () => {
// Secret keys go in `X-Spree-Api-Key` (server-to-server integrations).
// JWT tokens go in `Authorization: Bearer` (admin SPA sessions).
const auth = config.secretKey
? { headerName: 'X-Spree-Api-Key', headerValue: config.secretKey }
- : { headerName: 'Authorization', headerValue: currentToken ? `Bearer ${currentToken}` : '' };
- const requestFn = createRequestFn(requestConfig, basePath, auth);
- return requestFn<T>(method, path, mergedOptions);
- };
+ : { headerName: 'Authorization', headerValue: currentToken ? `Bearer ${currentToken}` : '' }
+ const requestFn = createRequestFn(requestConfig, basePath, auth)
+ return requestFn<T>(method, path, mergedOptions)
+ }
try {
- return await makeRequest();
+ return await makeRequest()
} catch (error) {
// On 401, try the unauthorized handler (token refresh) and retry once
if (
@@ -84,29 +84,29 @@ export function createAdminClient(config: AdminClientConfig): Client {
unauthorizedHandler &&
!path.includes('/auth/') // Don't retry auth endpoints
) {
- const shouldRetry = await unauthorizedHandler();
+ const shouldRetry = await unauthorizedHandler()
if (shouldRetry) {
- return makeRequest();
+ return makeRequest()
}
}
- throw error;
+ throw error
}
- };
+ }
- const adminClient = new AdminClient(dynamicRequestFn);
- const client = Object.create(adminClient) as Client;
+ const adminClient = new AdminClient(dynamicRequestFn)
+ const client = Object.create(adminClient) as Client
client.setStore = (storeId: string) => {
- currentStoreId = storeId;
- };
+ currentStoreId = storeId
+ }
client.setToken = (token: string) => {
- currentToken = token;
- };
+ currentToken = token
+ }
client.onUnauthorized = (handler: () => Promise<boolean>) => {
- unauthorizedHandler = handler;
- };
+ unauthorizedHandler = handler
+ }
- return client;
+ return client
}
diff --git a/packages/admin-sdk/src/index.ts b/packages/admin-sdk/src/index.ts
index 18df56716d..e8e58110ed 100644
--- a/packages/admin-sdk/src/index.ts
+++ b/packages/admin-sdk/src/index.ts
@@ -1,14 +1,19 @@
// Main client
-export { createAdminClient } from './client';
-export type { AdminClientConfig, Client } from './client';
-
-// Admin client class (for advanced use / subclassing)
-export { AdminClient } from './admin-client';
-export type { AuthTokens, LoginCredentials, PermissionRule, MeResponse, DashboardAnalytics } from './admin-client';
+export type { RequestOptions, RetryConfig } from '@spree/sdk-core'
// Request infrastructure (re-export from sdk-core)
-export { SpreeError } from '@spree/sdk-core';
-export type { RequestOptions, RetryConfig } from '@spree/sdk-core';
+export { SpreeError } from '@spree/sdk-core'
+export type {
+ AuthTokens,
+ DashboardAnalytics,
+ LoginCredentials,
+ MeResponse,
+ PermissionRule,
+} from './admin-client'
+// Admin client class (for advanced use / subclassing)
+export { AdminClient } from './admin-client'
+export type { AdminClientConfig, Client } from './client'
+export { createAdminClient } from './client'
// All types
-export * from './types';
+export * from './types'
diff --git a/packages/admin-sdk/src/params.ts b/packages/admin-sdk/src/params.ts
index 7869b8f8e3..c2e14e5a4a 100644
--- a/packages/admin-sdk/src/params.ts
+++ b/packages/admin-sdk/src/params.ts
@@ -2,330 +2,330 @@
// Based on the Admin API OpenAPI specification
export interface StoreUpdateParams {
- name?: string;
- url?: string;
- mail_from_address?: string;
- customer_support_email?: string;
- new_order_notifications_email?: string;
- description?: string;
- address?: string;
- contact_phone?: string;
- seo_title?: string;
- meta_keywords?: string;
- meta_description?: string;
- default_currency?: string;
- default_locale?: string;
- supported_currencies?: string;
- supported_locales?: string;
+ name?: string
+ url?: string
+ mail_from_address?: string
+ customer_support_email?: string
+ new_order_notifications_email?: string
+ description?: string
+ address?: string
+ contact_phone?: string
+ seo_title?: string
+ meta_keywords?: string
+ meta_description?: string
+ default_currency?: string
+ default_locale?: string
+ supported_currencies?: string
+ supported_locales?: string
}
export interface OptionTypeCreateParams {
- name: string;
- presentation: string;
- position?: number;
- filterable?: boolean;
+ name: string
+ presentation: string
+ position?: number
+ filterable?: boolean
option_values?: Array<{
- name?: string;
- presentation?: string;
- position?: number;
- }>;
+ name?: string
+ presentation?: string
+ position?: number
+ }>
}
export interface OptionTypeUpdateParams {
- name?: string;
- presentation?: string;
- position?: number;
- filterable?: boolean;
+ name?: string
+ presentation?: string
+ position?: number
+ filterable?: boolean
option_values?: Array<{
- id?: string;
- name?: string;
- presentation?: string;
- position?: number;
- }>;
+ id?: string
+ name?: string
+ presentation?: string
+ position?: number
+ }>
}
export interface LineItemCreateParams {
- variant_id: string;
- quantity?: number;
+ variant_id: string
+ quantity?: number
}
export interface LineItemUpdateParams {
- quantity?: number;
+ quantity?: number
}
export interface PaymentCreateParams {
- payment_method_id: string;
- amount?: number;
- source_id?: string;
+ payment_method_id: string
+ amount?: number
+ source_id?: string
}
export interface RefundCreateParams {
- payment_id: string;
- amount: number;
- refund_reason_id?: string;
+ payment_id: string
+ amount: number
+ refund_reason_id?: string
}
export interface FulfillmentUpdateParams {
- tracking?: string;
- selected_delivery_rate_id?: string;
+ tracking?: string
+ selected_delivery_rate_id?: string
}
export interface AddressInputParams {
- first_name?: string;
- last_name?: string;
- address1?: string;
- address2?: string;
- city?: string;
- postal_code?: string;
- country_iso?: string;
- state_abbr?: string;
- phone?: string;
+ first_name?: string
+ last_name?: string
+ address1?: string
+ address2?: string
+ city?: string
+ postal_code?: string
+ country_iso?: string
+ state_abbr?: string
+ phone?: string
}
export interface OrderCreateParams {
- email?: string;
- customer_id?: string;
- user_id?: string;
- use_customer_default_address?: boolean;
- currency?: string;
- market_id?: string;
- locale?: string;
- customer_note?: string;
- internal_note?: string;
- metadata?: Record<string, unknown>;
- shipping_address?: AddressInputParams;
- shipping_address_id?: string;
- billing_address?: AddressInputParams;
- billing_address_id?: string;
+ email?: string
+ customer_id?: string
+ user_id?: string
+ use_customer_default_address?: boolean
+ currency?: string
+ market_id?: string
+ locale?: string
+ customer_note?: string
+ internal_note?: string
+ metadata?: Record<string, unknown>
+ shipping_address?: AddressInputParams
+ shipping_address_id?: string
+ billing_address?: AddressInputParams
+ billing_address_id?: string
items?: Array<{
- variant_id: string;
- quantity: number;
- metadata?: Record<string, unknown>;
- }>;
- coupon_code?: string;
+ variant_id: string
+ quantity: number
+ metadata?: Record<string, unknown>
+ }>
+ coupon_code?: string
}
export interface OrderUpdateParams {
- email?: string;
- customer_id?: string;
- customer_note?: string;
- internal_note?: string;
- ship_address?: AddressInputParams;
- bill_address?: AddressInputParams;
+ email?: string
+ customer_id?: string
+ customer_note?: string
+ internal_note?: string
+ ship_address?: AddressInputParams
+ bill_address?: AddressInputParams
line_items?: Array<{
- variant_id?: string;
- quantity?: number;
- }>;
+ variant_id?: string
+ quantity?: number
+ }>
}
export interface OrderCompleteParams {
- payment_pending?: boolean;
- notify_customer?: boolean;
+ payment_pending?: boolean
+ notify_customer?: boolean
}
export interface OrderCancelParams {
- reason?: 'customer' | 'declined' | 'fraud' | 'inventory' | 'staff' | 'other' | 'expired';
- note?: string;
- restock_items?: boolean;
- refund_payments?: boolean;
- refund_amount?: number;
- notify_customer?: boolean;
+ reason?: 'customer' | 'declined' | 'fraud' | 'inventory' | 'staff' | 'other' | 'expired'
+ note?: string
+ restock_items?: boolean
+ refund_payments?: boolean
+ refund_amount?: number
+ notify_customer?: boolean
}
export interface OrderApproveParams {
- level?: string;
- note?: string;
+ level?: string
+ note?: string
}
export interface GiftCardApplyParams {
- code: string;
+ code: string
}
export interface StoreCreditApplyParams {
- amount?: number;
+ amount?: number
}
export interface CustomerCreateParams {
- email: string;
- first_name?: string;
- last_name?: string;
- phone?: string;
- accepts_email_marketing?: boolean;
- internal_note?: string;
- metadata?: Record<string, unknown>;
- tags?: string[];
+ email: string
+ first_name?: string
+ last_name?: string
+ phone?: string
+ accepts_email_marketing?: boolean
+ internal_note?: string
+ metadata?: Record<string, unknown>
+ tags?: string[]
}
export interface CustomerUpdateParams {
- email?: string;
- first_name?: string;
- last_name?: string;
- phone?: string;
- accepts_email_marketing?: boolean;
- internal_note?: string;
- metadata?: Record<string, unknown>;
- tags?: string[];
+ email?: string
+ first_name?: string
+ last_name?: string
+ phone?: string
+ accepts_email_marketing?: boolean
+ internal_note?: string
+ metadata?: Record<string, unknown>
+ tags?: string[]
}
export interface CustomerAddressParams {
- firstname?: string;
- lastname?: string;
- first_name?: string;
- last_name?: string;
- address1?: string;
- address2?: string;
- city?: string;
- zipcode?: string;
- postal_code?: string;
- country_id?: string;
- state_id?: string;
- country_iso?: string;
- state_abbr?: string;
- phone?: string;
- company?: string;
- label?: string;
- is_default_billing?: boolean;
- is_default_shipping?: boolean;
+ firstname?: string
+ lastname?: string
+ first_name?: string
+ last_name?: string
+ address1?: string
+ address2?: string
+ city?: string
+ zipcode?: string
+ postal_code?: string
+ country_id?: string
+ state_id?: string
+ country_iso?: string
+ state_abbr?: string
+ phone?: string
+ company?: string
+ label?: string
+ is_default_billing?: boolean
+ is_default_shipping?: boolean
}
export interface CustomerStoreCreditCreateParams {
- amount: number;
- currency: string;
- category_id: string;
- memo?: string;
+ amount: number
+ currency: string
+ category_id: string
+ memo?: string
}
export interface CustomerStoreCreditUpdateParams {
- amount?: number;
- category_id?: string;
- memo?: string;
+ amount?: number
+ category_id?: string
+ memo?: string
}
export interface DirectUploadCreateParams {
blob: {
- filename: string;
- byte_size: number;
- checksum: string;
- content_type: string;
- };
+ filename: string
+ byte_size: number
+ checksum: string
+ content_type: string
+ }
}
export interface MediaCreateParams {
- alt?: string;
- position?: number;
- type?: string;
- url?: string;
- signed_id?: string;
+ alt?: string
+ position?: number
+ type?: string
+ url?: string
+ signed_id?: string
}
export interface MediaUpdateParams {
- alt?: string;
- position?: number;
+ alt?: string
+ position?: number
}
export interface ProductCreateParams {
- name: string;
- description?: string;
- slug?: string;
- status?: 'draft' | 'active' | 'archived';
- sku?: string;
- tax_category_id?: string;
- category_ids?: Array<string>;
- tags?: Array<string>;
- variants?: VariantCreateParams[];
+ name: string
+ description?: string
+ slug?: string
+ status?: 'draft' | 'active' | 'archived'
+ sku?: string
+ tax_category_id?: string
+ category_ids?: Array<string>
+ tags?: Array<string>
+ variants?: VariantCreateParams[]
}
export interface ProductUpdateParams {
- name?: string;
- description?: string;
- slug?: string;
- status?: 'draft' | 'active' | 'archived';
- sku?: string;
- tax_category_id?: string;
- category_ids?: Array<string>;
- tags?: Array<string>;
- variants?: VariantUpdateParams[];
+ name?: string
+ description?: string
+ slug?: string
+ status?: 'draft' | 'active' | 'archived'
+ sku?: string
+ tax_category_id?: string
+ category_ids?: Array<string>
+ tags?: Array<string>
+ variants?: VariantUpdateParams[]
}
export interface CategoryCreateParams {
- name: string;
- parent_id?: string;
- position?: number;
- description?: string;
- permalink?: string;
- meta_title?: string;
- meta_description?: string;
- meta_keywords?: string;
- hide_from_nav?: boolean;
- sort_order?: string;
+ name: string
+ parent_id?: string
+ position?: number
+ description?: string
+ permalink?: string
+ meta_title?: string
+ meta_description?: string
+ meta_keywords?: string
+ hide_from_nav?: boolean
+ sort_order?: string
}
export interface CategoryUpdateParams {
- name?: string;
- parent_id?: string;
- position?: number;
- description?: string;
- permalink?: string;
- meta_title?: string;
- meta_description?: string;
- meta_keywords?: string;
- hide_from_nav?: boolean;
- sort_order?: string;
+ name?: string
+ parent_id?: string
+ position?: number
+ description?: string
+ permalink?: string
+ meta_title?: string
+ meta_description?: string
+ meta_keywords?: string
+ hide_from_nav?: boolean
+ sort_order?: string
}
export interface VariantOptionPair {
- name: string;
- value: string;
+ name: string
+ value: string
}
export interface VariantPrice {
- currency: string;
- amount: number;
- compare_at_amount?: number;
+ currency: string
+ amount: number
+ compare_at_amount?: number
}
export interface VariantStockItem {
- stock_location_id: string;
- count_on_hand: number;
- backorderable?: boolean;
+ stock_location_id: string
+ count_on_hand: number
+ backorderable?: boolean
}
export interface VariantCreateParams {
- sku?: string;
- compare_at_price?: number;
- cost_price?: number;
- cost_currency?: string;
- weight?: number;
- height?: number;
- width?: number;
- depth?: number;
- weight_unit?: string;
- dimensions_unit?: string;
- track_inventory?: boolean;
- tax_category_id?: string;
- position?: number;
- barcode?: string;
- options?: VariantOptionPair[];
- prices?: VariantPrice[];
- stock_items?: VariantStockItem[];
+ sku?: string
+ compare_at_price?: number
+ cost_price?: number
+ cost_currency?: string
+ weight?: number
+ height?: number
+ width?: number
+ depth?: number
+ weight_unit?: string
+ dimensions_unit?: string
+ track_inventory?: boolean
+ tax_category_id?: string
+ position?: number
+ barcode?: string
+ options?: VariantOptionPair[]
+ prices?: VariantPrice[]
+ stock_items?: VariantStockItem[]
}
export interface VariantUpdateParams {
- sku?: string;
- compare_at_price?: number;
- cost_price?: number;
- cost_currency?: string;
- weight?: number;
- height?: number;
- width?: number;
- depth?: number;
- weight_unit?: string;
- dimensions_unit?: string;
- track_inventory?: boolean;
- tax_category_id?: string;
- position?: number;
- barcode?: string;
- options?: VariantOptionPair[];
- prices?: VariantPrice[];
- stock_items?: VariantStockItem[];
+ sku?: string
+ compare_at_price?: number
+ cost_price?: number
+ cost_currency?: string
+ weight?: number
+ height?: number
+ width?: number
+ depth?: number
+ weight_unit?: string
+ dimensions_unit?: string
+ track_inventory?: boolean
+ tax_category_id?: string
+ position?: number
+ barcode?: string
+ options?: VariantOptionPair[]
+ prices?: VariantPrice[]
+ stock_items?: VariantStockItem[]
}
diff --git a/packages/admin-sdk/src/types/index.ts b/packages/admin-sdk/src/types/index.ts
index 7c252ba87f..25800467aa 100644
--- a/packages/admin-sdk/src/types/index.ts
+++ b/packages/admin-sdk/src/types/index.ts
@@ -1,48 +1,48 @@
// Re-export shared types from sdk-core
export type {
- LocaleDefaults,
- PaginationMeta,
- ListResponse,
- PaginatedResponse,
ErrorResponse,
ListParams,
-} from '@spree/sdk-core';
+ ListResponse,
+ LocaleDefaults,
+ PaginatedResponse,
+ PaginationMeta,
+} from '@spree/sdk-core'
// Admin-specific generated types
-export type { default as Address } from './generated/Address';
-export type { default as Adjustment } from './generated/Adjustment';
-export type { default as AdminUser } from './generated/AdminUser';
-export type { default as AllowedOrigin } from './generated/AllowedOrigin';
-export type { default as Category } from './generated/Category';
-export type { default as Country } from './generated/Country';
-export type { default as CreditCard } from './generated/CreditCard';
-export type { default as CustomField } from './generated/CustomField';
-export type { default as Customer } from './generated/Customer';
-export type { default as DeliveryMethod } from './generated/DeliveryMethod';
-export type { default as DeliveryRate } from './generated/DeliveryRate';
-export type { default as DigitalLink } from './generated/DigitalLink';
-export type { default as Discount } from './generated/Discount';
-export type { default as Fulfillment } from './generated/Fulfillment';
-export type { default as GiftCard } from './generated/GiftCard';
-export type { default as LineItem } from './generated/LineItem';
-export type { default as Market } from './generated/Market';
-export type { default as Media } from './generated/Media';
-export type { default as OptionType } from './generated/OptionType';
-export type { default as OptionValue } from './generated/OptionValue';
-export type { default as Order } from './generated/Order';
-export type { default as Payment } from './generated/Payment';
-export type { default as PaymentMethod } from './generated/PaymentMethod';
-export type { default as PaymentSource } from './generated/PaymentSource';
-export type { default as Price } from './generated/Price';
-export type { default as PriceHistory } from './generated/PriceHistory';
-export type { default as Product } from './generated/Product';
-export type { default as Refund } from './generated/Refund';
-export type { default as Reimbursement } from './generated/Reimbursement';
-export type { default as ReturnAuthorization } from './generated/ReturnAuthorization';
-export type { default as State } from './generated/State';
-export type { default as StockItem } from './generated/StockItem';
-export type { default as StockLocation } from './generated/StockLocation';
-export type { default as Store } from './generated/Store';
-export type { default as StoreCredit } from './generated/StoreCredit';
-export type { default as TaxCategory } from './generated/TaxCategory';
-export type { default as Variant } from './generated/Variant';
+export type { default as Address } from './generated/Address'
+export type { default as Adjustment } from './generated/Adjustment'
+export type { default as AdminUser } from './generated/AdminUser'
+export type { default as AllowedOrigin } from './generated/AllowedOrigin'
+export type { default as Category } from './generated/Category'
+export type { default as Country } from './generated/Country'
+export type { default as CreditCard } from './generated/CreditCard'
+export type { default as Customer } from './generated/Customer'
+export type { default as CustomField } from './generated/CustomField'
+export type { default as DeliveryMethod } from './generated/DeliveryMethod'
+export type { default as DeliveryRate } from './generated/DeliveryRate'
+export type { default as DigitalLink } from './generated/DigitalLink'
+export type { default as Discount } from './generated/Discount'
+export type { default as Fulfillment } from './generated/Fulfillment'
+export type { default as GiftCard } from './generated/GiftCard'
+export type { default as LineItem } from './generated/LineItem'
+export type { default as Market } from './generated/Market'
+export type { default as Media } from './generated/Media'
+export type { default as OptionType } from './generated/OptionType'
+export type { default as OptionValue } from './generated/OptionValue'
+export type { default as Order } from './generated/Order'
+export type { default as Payment } from './generated/Payment'
+export type { default as PaymentMethod } from './generated/PaymentMethod'
+export type { default as PaymentSource } from './generated/PaymentSource'
+export type { default as Price } from './generated/Price'
+export type { default as PriceHistory } from './generated/PriceHistory'
+export type { default as Product } from './generated/Product'
+export type { default as Refund } from './generated/Refund'
+export type { default as Reimbursement } from './generated/Reimbursement'
+export type { default as ReturnAuthorization } from './generated/ReturnAuthorization'
+export type { default as State } from './generated/State'
+export type { default as StockItem } from './generated/StockItem'
+export type { default as StockLocation } from './generated/StockLocation'
+export type { default as Store } from './generated/Store'
+export type { default as StoreCredit } from './generated/StoreCredit'
+export type { default as TaxCategory } from './generated/TaxCategory'
+export type { default as Variant } from './generated/Variant'
diff --git a/packages/admin-sdk/tsup.config.ts b/packages/admin-sdk/tsup.config.ts
index beb647703b..ef64090ff3 100644
--- a/packages/admin-sdk/tsup.config.ts
+++ b/packages/admin-sdk/tsup.config.ts
@@ -1,5 +1,5 @@
-import { defineConfig } from 'tsup';
-import path from 'node:path';
+import path from 'node:path'
+import { defineConfig } from 'tsup'
export default defineConfig({
entry: {
@@ -18,6 +18,6 @@ export default defineConfig({
esbuildOptions(options) {
options.alias = {
'@/types': path.resolve(import.meta.dirname, 'src/types/generated/index.ts'),
- };
+ }
},
-});
+})
diff --git a/packages/admin-sdk/vitest.config.ts b/packages/admin-sdk/vitest.config.ts
index 7538deb3c9..e2145082eb 100644
--- a/packages/admin-sdk/vitest.config.ts
+++ b/packages/admin-sdk/vitest.config.ts
@@ -1,5 +1,5 @@
-import { defineConfig } from 'vitest/config';
-import path from 'node:path';
+import path from 'node:path'
+import { defineConfig } from 'vitest/config'
export default defineConfig({
resolve: {
@@ -16,4 +16,4 @@ export default defineConfig({
exclude: ['src/types/**'],
},
},
-});
+})
diff --git a/packages/admin/biome.json b/packages/admin/biome.json
index a6826114b0..9a92f56b46 100644
--- a/packages/admin/biome.json
+++ b/packages/admin/biome.json
@@ -1,6 +1,7 @@
{
"$schema": "https://biomejs.dev/schemas/2.4.13/schema.json",
- "extends": ["//"],
+ "root": false,
+ "extends": ["../../biome.json"],
"files": {
"includes": ["src/**", "!src/routeTree.gen.ts", "!src/**/*.css"]
},
diff --git a/packages/admin/package.json b/packages/admin/package.json
index 6f0bea4907..089268bbf7 100644
--- a/packages/admin/package.json
+++ b/packages/admin/package.json
@@ -40,7 +40,6 @@
"zod": "^4.3.6"
},
"devDependencies": {
- "@biomejs/biome": "^2.4.13",
"@tailwindcss/vite": "^4.2.4",
"@tanstack/router-plugin": "^1.167.29",
"@types/node": "^25.6.0",
diff --git a/packages/admin/tsconfig.json b/packages/admin/tsconfig.json
index 59578c322c..2b78387c74 100644
--- a/packages/admin/tsconfig.json
+++ b/packages/admin/tsconfig.json
@@ -1,13 +1,10 @@
{
"files": [],
- "references": [
- { "path": "./tsconfig.app.json" },
- { "path": "./tsconfig.node.json" },
- ],
+ "references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }],
"compilerOptions": {
"baseUrl": ".",
"paths": {
- "@/*": ["./src/*"],
- },
- },
+ "@/*": ["./src/*"]
+ }
+ }
}
diff --git a/packages/admin/vite.config.ts b/packages/admin/vite.config.ts
index 7dad18947b..1b043bc98b 100644
--- a/packages/admin/vite.config.ts
+++ b/packages/admin/vite.config.ts
@@ -1,8 +1,8 @@
-import { defineConfig } from 'vite'
-import react from '@vitejs/plugin-react'
+import path from 'node:path'
import tailwindcss from '@tailwindcss/vite'
import { TanStackRouterVite } from '@tanstack/router-plugin/vite'
-import path from 'path'
+import react from '@vitejs/plugin-react'
+import { defineConfig } from 'vite'
export default defineConfig({
plugins: [TanStackRouterVite(), react(), tailwindcss()],
diff --git a/packages/cli/.changeset/config.json b/packages/cli/.changeset/config.json
index 95ea990266..0fbbd8c795 100644
--- a/packages/cli/.changeset/config.json
+++ b/packages/cli/.changeset/config.json
@@ -1,9 +1,6 @@
{
"$schema": "https://unpkg.com/@changesets/[email protected]/schema.json",
- "changelog": [
- "@changesets/changelog-github",
- { "repo": "spree/spree" }
- ],
+ "changelog": ["@changesets/changelog-github", { "repo": "spree/spree" }],
"commit": false,
"fixed": [],
"linked": [],
diff --git a/packages/cli/biome.json b/packages/cli/biome.json
index 023405807a..aa61cf8253 100644
--- a/packages/cli/biome.json
+++ b/packages/cli/biome.json
@@ -1,6 +1,7 @@
{
"$schema": "https://biomejs.dev/schemas/2.4.13/schema.json",
- "extends": ["//"],
+ "root": false,
+ "extends": ["../../biome.json"],
"files": {
"includes": ["src/**", "tests/**"]
}
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 38fcab306e..f303ce886b 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -15,6 +15,9 @@
"dev": "tsup --watch",
"test": "vitest run",
"typecheck": "tsc --noEmit",
+ "lint": "biome check src tests",
+ "lint:fix": "biome check --fix src tests",
+ "format": "biome format --write src tests",
"clean": "rm -rf dist",
"prepublishOnly": "npm run build",
"changeset": "changeset",
diff --git a/packages/cli/src/commands/api-key.ts b/packages/cli/src/commands/api-key.ts
index c5aa185d99..67d7092f44 100644
--- a/packages/cli/src/commands/api-key.ts
+++ b/packages/cli/src/commands/api-key.ts
@@ -1,14 +1,12 @@
-import type { Command } from 'commander'
import * as p from '@clack/prompts'
-import pc from 'picocolors'
+import type { Command } from 'commander'
import { printTable } from 'console-table-printer'
+import pc from 'picocolors'
import { detectProject } from '../context.js'
import { rakeTask } from '../docker.js'
export function registerApiKeyCommand(program: Command): void {
- const apiKey = program
- .command('api-key')
- .description('Manage API keys')
+ const apiKey = program.command('api-key').description('Manage API keys')
apiKey
.command('create')
diff --git a/packages/cli/src/commands/dev.ts b/packages/cli/src/commands/dev.ts
index fc781719dd..fc801adeca 100644
--- a/packages/cli/src/commands/dev.ts
+++ b/packages/cli/src/commands/dev.ts
@@ -1,9 +1,9 @@
-import type { Command } from 'commander'
import * as p from '@clack/prompts'
+import type { Command } from 'commander'
import pc from 'picocolors'
+import { DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from '../constants.js'
import { detectProject } from '../context.js'
import { dockerCompose, streamLogs } from '../docker.js'
-import { DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from '../constants.js'
export function registerDevCommand(program: Command): void {
program
diff --git a/packages/cli/src/commands/eject.ts b/packages/cli/src/commands/eject.ts
index 772002dfc4..dde2fa19a5 100644
--- a/packages/cli/src/commands/eject.ts
+++ b/packages/cli/src/commands/eject.ts
@@ -1,7 +1,7 @@
import fs from 'node:fs'
import path from 'node:path'
-import { Command } from 'commander'
import * as p from '@clack/prompts'
+import type { Command } from 'commander'
import pc from 'picocolors'
import { detectProject } from '../context.js'
import { dockerCompose } from '../docker.js'
diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.ts
index 4a8df5ba5b..794424fbd8 100644
--- a/packages/cli/src/commands/init.ts
+++ b/packages/cli/src/commands/init.ts
@@ -1,13 +1,13 @@
-import type { Command } from 'commander'
-import * as p from '@clack/prompts'
-import pc from 'picocolors'
-import { execaCommand } from 'execa'
-import { platform } from 'node:os'
import fs from 'node:fs'
+import { platform } from 'node:os'
import path from 'node:path'
+import * as p from '@clack/prompts'
+import type { Command } from 'commander'
+import { execaCommand } from 'execa'
+import pc from 'picocolors'
+import { DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from '../constants.js'
import { detectProject } from '../context.js'
import { dockerCompose, rakeTask, streamLogs } from '../docker.js'
-import { DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from '../constants.js'
const HEALTH_CHECK_INTERVAL_MS = 3000
const HEALTH_CHECK_TIMEOUT_MS = 120_000
@@ -109,7 +109,10 @@ export function updateStorefrontEnv(projectDir: string, apiKey: string): void {
if (!fs.existsSync(envPath)) return
const content = fs.readFileSync(envPath, 'utf-8')
- fs.writeFileSync(envPath, content.replace(/SPREE_PUBLISHABLE_KEY=.*/, `SPREE_PUBLISHABLE_KEY=${apiKey}`))
+ fs.writeFileSync(
+ envPath,
+ content.replace(/SPREE_PUBLISHABLE_KEY=.*/, `SPREE_PUBLISHABLE_KEY=${apiKey}`),
+ )
}
async function openBrowser(url: string): Promise<void> {
diff --git a/packages/cli/src/commands/open.ts b/packages/cli/src/commands/open.ts
index 043819d5d2..908879b7c1 100644
--- a/packages/cli/src/commands/open.ts
+++ b/packages/cli/src/commands/open.ts
@@ -1,6 +1,6 @@
+import { platform } from 'node:os'
import type { Command } from 'commander'
import { execaCommand } from 'execa'
-import { platform } from 'node:os'
import { detectProject } from '../context.js'
export function registerOpenCommand(program: Command): void {
diff --git a/packages/cli/src/commands/sample-data.ts b/packages/cli/src/commands/sample-data.ts
index b1a28f1021..ef7a8c4097 100644
--- a/packages/cli/src/commands/sample-data.ts
+++ b/packages/cli/src/commands/sample-data.ts
@@ -1,5 +1,5 @@
-import type { Command } from 'commander'
import * as p from '@clack/prompts'
+import type { Command } from 'commander'
import { detectProject } from '../context.js'
import { rakeTask } from '../docker.js'
diff --git a/packages/cli/src/commands/seed.ts b/packages/cli/src/commands/seed.ts
index 3908ea794b..9428f82367 100644
--- a/packages/cli/src/commands/seed.ts
+++ b/packages/cli/src/commands/seed.ts
@@ -1,5 +1,5 @@
-import type { Command } from 'commander'
import * as p from '@clack/prompts'
+import type { Command } from 'commander'
import { detectProject } from '../context.js'
import { rakeTask } from '../docker.js'
diff --git a/packages/cli/src/commands/stop.ts b/packages/cli/src/commands/stop.ts
index ab9baf27bc..adea01fab8 100644
--- a/packages/cli/src/commands/stop.ts
+++ b/packages/cli/src/commands/stop.ts
@@ -1,5 +1,5 @@
-import type { Command } from 'commander'
import * as p from '@clack/prompts'
+import type { Command } from 'commander'
import { detectProject } from '../context.js'
import { dockerCompose } from '../docker.js'
diff --git a/packages/cli/src/commands/update.ts b/packages/cli/src/commands/update.ts
index 5809de23f6..7d84af89b3 100644
--- a/packages/cli/src/commands/update.ts
+++ b/packages/cli/src/commands/update.ts
@@ -1,5 +1,5 @@
-import type { Command } from 'commander'
import * as p from '@clack/prompts'
+import type { Command } from 'commander'
import { detectProject } from '../context.js'
import { dockerCompose } from '../docker.js'
diff --git a/packages/cli/src/commands/user.ts b/packages/cli/src/commands/user.ts
index 92b28d4eed..ad78cb037c 100644
--- a/packages/cli/src/commands/user.ts
+++ b/packages/cli/src/commands/user.ts
@@ -1,13 +1,11 @@
-import type { Command } from 'commander'
import * as p from '@clack/prompts'
+import type { Command } from 'commander'
import pc from 'picocolors'
import { detectProject } from '../context.js'
import { rakeTask } from '../docker.js'
export function registerUserCommand(program: Command): void {
- const user = program
- .command('user')
- .description('Manage admin users')
+ const user = program.command('user').description('Manage admin users')
user
.command('create')
diff --git a/packages/cli/src/context.ts b/packages/cli/src/context.ts
index 03ec2be412..87e89077aa 100644
--- a/packages/cli/src/context.ts
+++ b/packages/cli/src/context.ts
@@ -1,7 +1,7 @@
import fs from 'node:fs'
import path from 'node:path'
-import type { ProjectContext } from './types.js'
import { DEFAULT_SPREE_PORT } from './constants.js'
+import type { ProjectContext } from './types.js'
export function detectProject(cwd: string = process.cwd()): ProjectContext {
const composeFile = path.join(cwd, 'docker-compose.yml')
@@ -9,7 +9,7 @@ export function detectProject(cwd: string = process.cwd()): ProjectContext {
if (!fs.existsSync(composeFile)) {
throw new Error(
'Not a Spree project directory. No docker-compose.yml found.\n' +
- 'Run this command from a directory created with create-spree-app.',
+ 'Run this command from a directory created with create-spree-app.',
)
}
diff --git a/packages/cli/src/docker.ts b/packages/cli/src/docker.ts
index 679715babc..98be42668a 100644
--- a/packages/cli/src/docker.ts
+++ b/packages/cli/src/docker.ts
@@ -1,10 +1,6 @@
-import { execa, type Options as ExecaOptions } from 'execa'
+import { type Options as ExecaOptions, execa } from 'execa'
-export async function dockerCompose(
- args: string[],
- projectDir: string,
- options?: ExecaOptions,
-) {
+export async function dockerCompose(args: string[], projectDir: string, options?: ExecaOptions) {
return execa('docker', ['compose', ...args], {
cwd: projectDir,
...options,
@@ -43,10 +39,7 @@ export async function railsConsole(projectDir: string): Promise<void> {
})
}
-export async function streamLogs(
- service: string,
- projectDir: string,
-): Promise<void> {
+export async function streamLogs(service: string, projectDir: string): Promise<void> {
await execa('docker', ['compose', 'logs', '-f', service], {
cwd: projectDir,
stdio: 'inherit',
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 3ca5da2abe..27c47d9fcb 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -1,17 +1,17 @@
import { Command } from 'commander'
import pc from 'picocolors'
+import { registerApiKeyCommand } from './commands/api-key.js'
+import { registerConsoleCommand } from './commands/console.js'
import { registerDevCommand } from './commands/dev.js'
-import { registerStopCommand } from './commands/stop.js'
-import { registerUpdateCommand } from './commands/update.js'
-import { registerLogsCommand } from './commands/logs.js'
+import { registerEjectCommand } from './commands/eject.js'
import { registerInitCommand } from './commands/init.js'
-import { registerConsoleCommand } from './commands/console.js'
-import { registerUserCommand } from './commands/user.js'
-import { registerApiKeyCommand } from './commands/api-key.js'
-import { registerSeedCommand } from './commands/seed.js'
+import { registerLogsCommand } from './commands/logs.js'
import { registerOpenCommand } from './commands/open.js'
import { registerSampleDataCommand } from './commands/sample-data.js'
-import { registerEjectCommand } from './commands/eject.js'
+import { registerSeedCommand } from './commands/seed.js'
+import { registerStopCommand } from './commands/stop.js'
+import { registerUpdateCommand } from './commands/update.js'
+import { registerUserCommand } from './commands/user.js'
const program = new Command()
.name('spree')
diff --git a/packages/cli/tests/context.test.ts b/packages/cli/tests/context.test.ts
index d7ee7c210a..0e92502448 100644
--- a/packages/cli/tests/context.test.ts
+++ b/packages/cli/tests/context.test.ts
@@ -1,7 +1,7 @@
-import { describe, it, expect, afterEach } from 'vitest'
import fs from 'node:fs'
-import path from 'node:path'
import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
import { detectProject } from '../src/context'
describe('detectProject', () => {
diff --git a/packages/cli/tests/env.test.ts b/packages/cli/tests/env.test.ts
index 058a46c4a3..acd5aa1722 100644
--- a/packages/cli/tests/env.test.ts
+++ b/packages/cli/tests/env.test.ts
@@ -1,7 +1,7 @@
-import { describe, it, expect, afterEach } from 'vitest'
import fs from 'node:fs'
-import path from 'node:path'
import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
import { readPortFromEnv } from '../src/context'
describe('readPortFromEnv', () => {
diff --git a/packages/cli/tests/init.test.ts b/packages/cli/tests/init.test.ts
index fe4e19497c..3361622c46 100644
--- a/packages/cli/tests/init.test.ts
+++ b/packages/cli/tests/init.test.ts
@@ -1,7 +1,7 @@
-import { describe, it, expect, afterEach } from 'vitest'
import fs from 'node:fs'
-import path from 'node:path'
import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
import { updateStorefrontEnv } from '../src/commands/init'
describe('updateStorefrontEnv', () => {
diff --git a/packages/create-spree-app/.changeset/config.json b/packages/create-spree-app/.changeset/config.json
index 95ea990266..0fbbd8c795 100644
--- a/packages/create-spree-app/.changeset/config.json
+++ b/packages/create-spree-app/.changeset/config.json
@@ -1,9 +1,6 @@
{
"$schema": "https://unpkg.com/@changesets/[email protected]/schema.json",
- "changelog": [
- "@changesets/changelog-github",
- { "repo": "spree/spree" }
- ],
+ "changelog": ["@changesets/changelog-github", { "repo": "spree/spree" }],
"commit": false,
"fixed": [],
"linked": [],
diff --git a/packages/create-spree-app/biome.json b/packages/create-spree-app/biome.json
new file mode 100644
index 0000000000..aa61cf8253
--- /dev/null
+++ b/packages/create-spree-app/biome.json
@@ -0,0 +1,8 @@
+{
+ "$schema": "https://biomejs.dev/schemas/2.4.13/schema.json",
+ "root": false,
+ "extends": ["../../biome.json"],
+ "files": {
+ "includes": ["src/**", "tests/**"]
+ }
+}
diff --git a/packages/create-spree-app/package.json b/packages/create-spree-app/package.json
index da89d598ad..cbbc03934e 100644
--- a/packages/create-spree-app/package.json
+++ b/packages/create-spree-app/package.json
@@ -13,6 +13,9 @@
"dev": "tsup --watch",
"test": "vitest run",
"typecheck": "tsc --noEmit",
+ "lint": "biome check src tests",
+ "lint:fix": "biome check --fix src tests",
+ "format": "biome format --write src tests",
"clean": "rm -rf dist",
"prepublishOnly": "npm run build",
"changeset": "changeset",
diff --git a/packages/create-spree-app/src/index.ts b/packages/create-spree-app/src/index.ts
index 722077a457..9b3cb9bae8 100644
--- a/packages/create-spree-app/src/index.ts
+++ b/packages/create-spree-app/src/index.ts
@@ -1,12 +1,12 @@
-import { Command } from 'commander'
import * as p from '@clack/prompts'
-import pc from 'picocolors'
+import { Command } from 'commander'
import getPort, { portNumbers } from 'get-port'
+import pc from 'picocolors'
+import { DEFAULT_SPREE_PORT } from './constants.js'
import { runPrompts } from './prompts.js'
import { scaffold } from './scaffold.js'
-import { detectPackageManager } from './utils.js'
-import { DEFAULT_SPREE_PORT } from './constants.js'
import type { PackageManager } from './types.js'
+import { detectPackageManager } from './utils.js'
const program = new Command()
.name('create-spree-app')
diff --git a/packages/create-spree-app/src/prompts.ts b/packages/create-spree-app/src/prompts.ts
index f7aaac5f2b..c671487cd1 100644
--- a/packages/create-spree-app/src/prompts.ts
+++ b/packages/create-spree-app/src/prompts.ts
@@ -1,5 +1,5 @@
import * as p from '@clack/prompts'
-import type { ScaffoldOptions, PackageManager } from './types.js'
+import type { PackageManager, ScaffoldOptions } from './types.js'
interface PromptFlags {
directory?: string
diff --git a/packages/create-spree-app/src/scaffold.ts b/packages/create-spree-app/src/scaffold.ts
index 23627cb351..5114f8d0e0 100644
--- a/packages/create-spree-app/src/scaffold.ts
+++ b/packages/create-spree-app/src/scaffold.ts
@@ -1,18 +1,23 @@
-import * as p from '@clack/prompts'
-import pc from 'picocolors'
import fs from 'node:fs'
import path from 'node:path'
+import * as p from '@clack/prompts'
import { execa } from 'execa'
-import type { ScaffoldOptions } from './types.js'
+import pc from 'picocolors'
+import { downloadBackend } from './backend.js'
import { DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from './constants.js'
-import { generateSecretKeyBase, isDockerRunning } from './utils.js'
+import {
+ downloadStorefront,
+ installRootDeps,
+ installStorefrontDeps,
+ writeStorefrontEnv,
+} from './storefront.js'
+import { agentsMdContent, rootClaudeMdContent } from './templates/claude-md.js'
import { envContent } from './templates/env.js'
+import { gitignoreContent } from './templates/gitignore.js'
import { rootPackageJsonContent } from './templates/package-json.js'
import { readmeContent } from './templates/readme.js'
-import { gitignoreContent } from './templates/gitignore.js'
-import { rootClaudeMdContent, agentsMdContent } from './templates/claude-md.js'
-import { downloadStorefront, installRootDeps, installStorefrontDeps, writeStorefrontEnv } from './storefront.js'
-import { downloadBackend } from './backend.js'
+import type { ScaffoldOptions } from './types.js'
+import { generateSecretKeyBase, isDockerRunning } from './utils.js'
export async function scaffold(options: ScaffoldOptions): Promise<void> {
const projectDir = path.resolve(options.directory)
@@ -107,7 +112,11 @@ export async function scaffold(options: ScaffoldOptions): Promise<void> {
}
}
-function printSuccessWithoutDocker(projectName: string, hasStorefront: boolean, port: number): void {
+function printSuccessWithoutDocker(
+ projectName: string,
+ hasStorefront: boolean,
+ port: number,
+): void {
const lines: string[] = [
'',
`${pc.bold('Next steps:')}`,
diff --git a/packages/create-spree-app/src/storefront.ts b/packages/create-spree-app/src/storefront.ts
index dcb255c431..b1bd7bfd6c 100644
--- a/packages/create-spree-app/src/storefront.ts
+++ b/packages/create-spree-app/src/storefront.ts
@@ -3,8 +3,8 @@ import path from 'node:path'
import { execa } from 'execa'
import { STOREFRONT_REPO } from './constants.js'
import { storefrontEnvContent } from './templates/env.js'
-import { installCommand } from './utils.js'
import type { PackageManager } from './types.js'
+import { installCommand } from './utils.js'
export async function downloadStorefront(projectDir: string): Promise<void> {
const storefrontDir = path.join(projectDir, 'apps', 'storefront')
diff --git a/packages/create-spree-app/src/templates/package-json.ts b/packages/create-spree-app/src/templates/package-json.ts
index 8141e2e05e..896b270231 100644
--- a/packages/create-spree-app/src/templates/package-json.ts
+++ b/packages/create-spree-app/src/templates/package-json.ts
@@ -20,5 +20,5 @@ export function rootPackageJsonContent(name: string): string {
},
}
- return JSON.stringify(pkg, null, 2) + '\n'
+ return `${JSON.stringify(pkg, null, 2)}\n`
}
diff --git a/packages/create-spree-app/src/templates/readme.ts b/packages/create-spree-app/src/templates/readme.ts
index 8bd98350ed..6c1995c734 100644
--- a/packages/create-spree-app/src/templates/readme.ts
+++ b/packages/create-spree-app/src/templates/readme.ts
@@ -1,4 +1,4 @@
-import { STOREFRONT_PORT, DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD } from '../constants.js'
+import { DEFAULT_ADMIN_EMAIL, DEFAULT_ADMIN_PASSWORD, STOREFRONT_PORT } from '../constants.js'
export function readmeContent(name: string, hasStorefront: boolean, port: number): string {
let content = `# ${name}
diff --git a/packages/create-spree-app/src/utils.ts b/packages/create-spree-app/src/utils.ts
index 95a4743d9b..2d3241d75e 100644
--- a/packages/create-spree-app/src/utils.ts
+++ b/packages/create-spree-app/src/utils.ts
@@ -1,5 +1,5 @@
-import { execaCommand } from 'execa'
import crypto from 'node:crypto'
+import { execaCommand } from 'execa'
import type { PackageManager } from './types.js'
export function detectPackageManager(): PackageManager {
@@ -31,4 +31,3 @@ export function runCommand(pm: PackageManager): string {
if (pm === 'yarn') return 'yarn'
return 'pnpm'
}
-
diff --git a/packages/create-spree-app/tests/scaffold.test.ts b/packages/create-spree-app/tests/scaffold.test.ts
index 9a4472d57e..5b2f588d21 100644
--- a/packages/create-spree-app/tests/scaffold.test.ts
+++ b/packages/create-spree-app/tests/scaffold.test.ts
@@ -1,7 +1,7 @@
-import { describe, it, expect, afterEach, vi } from 'vitest'
import fs from 'node:fs'
-import path from 'node:path'
import os from 'node:os'
+import path from 'node:path'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import { scaffold } from '../src/scaffold'
const FAKE_COMPOSE = `x-app: &app
@@ -203,7 +203,7 @@ describe('scaffold (no-start)', () => {
start: false,
packageManager: 'npm',
port: 3000,
- })
+ }),
).rejects.toThrow('process.exit called')
mockExit.mockRestore()
diff --git a/packages/create-spree-app/tests/templates.test.ts b/packages/create-spree-app/tests/templates.test.ts
index 79d8cfe0de..cbd3969c7d 100644
--- a/packages/create-spree-app/tests/templates.test.ts
+++ b/packages/create-spree-app/tests/templates.test.ts
@@ -1,8 +1,8 @@
-import { describe, it, expect } from 'vitest'
+import { describe, expect, it } from 'vitest'
import { envContent, storefrontEnvContent } from '../src/templates/env'
+import { gitignoreContent } from '../src/templates/gitignore'
import { rootPackageJsonContent } from '../src/templates/package-json'
import { readmeContent } from '../src/templates/readme'
-import { gitignoreContent } from '../src/templates/gitignore'
describe('envContent', () => {
it('includes the provided secret key', () => {
diff --git a/packages/create-spree-app/tests/utils.test.ts b/packages/create-spree-app/tests/utils.test.ts
index e04534c569..4e2ef587eb 100644
--- a/packages/create-spree-app/tests/utils.test.ts
+++ b/packages/create-spree-app/tests/utils.test.ts
@@ -1,5 +1,10 @@
-import { describe, it, expect, beforeEach } from 'vitest'
-import { detectPackageManager, generateSecretKeyBase, installCommand, runCommand } from '../src/utils'
+import { beforeEach, describe, expect, it } from 'vitest'
+import {
+ detectPackageManager,
+ generateSecretKeyBase,
+ installCommand,
+ runCommand,
+} from '../src/utils'
describe('detectPackageManager', () => {
const originalEnv = process.env.npm_config_user_agent
diff --git a/packages/sdk-core/biome.json b/packages/sdk-core/biome.json
index 023405807a..aa61cf8253 100644
--- a/packages/sdk-core/biome.json
+++ b/packages/sdk-core/biome.json
@@ -1,6 +1,7 @@
{
"$schema": "https://biomejs.dev/schemas/2.4.13/schema.json",
- "extends": ["//"],
+ "root": false,
+ "extends": ["../../biome.json"],
"files": {
"includes": ["src/**", "tests/**"]
}
diff --git a/packages/sdk-core/package.json b/packages/sdk-core/package.json
index b1f08ede65..71085e8d03 100644
--- a/packages/sdk-core/package.json
+++ b/packages/sdk-core/package.json
@@ -26,6 +26,9 @@
"build": "tsup",
"dev": "tsup --watch",
"typecheck": "tsc --noEmit",
+ "lint": "biome check src",
+ "lint:fix": "biome check --fix src",
+ "format": "biome format --write src",
"clean": "rm -rf dist"
},
"devDependencies": {
diff --git a/packages/sdk-core/packages/sdk/src/zod/index.ts b/packages/sdk-core/packages/sdk/src/zod/index.ts
index 69e4e4eb8b..99735f6415 100644
--- a/packages/sdk-core/packages/sdk/src/zod/index.ts
+++ b/packages/sdk-core/packages/sdk/src/zod/index.ts
@@ -1 +1 @@
-export * from './generated';
+export * from './generated'
diff --git a/packages/sdk-core/src/helpers.ts b/packages/sdk-core/src/helpers.ts
index ce935ebc03..ffb0822015 100644
--- a/packages/sdk-core/src/helpers.ts
+++ b/packages/sdk-core/src/helpers.ts
@@ -1,28 +1,33 @@
/** Serialize expand/fields arrays into comma-separated query params */
-export function getParams(params?: { expand?: string[]; fields?: string[] }): Record<string, string> | undefined {
- if (!params) return undefined;
- const result: Record<string, string> = {};
- if (params.expand?.length) result.expand = params.expand.join(',');
- if (params.fields?.length) result.fields = params.fields.join(',');
- return Object.keys(result).length > 0 ? result : undefined;
+export function getParams(params?: {
+ expand?: string[]
+ fields?: string[]
+}): Record<string, string> | undefined {
+ if (!params) return undefined
+ const result: Record<string, string> = {}
+ if (params.expand?.length) result.expand = params.expand.join(',')
+ if (params.fields?.length) result.fields = params.fields.join(',')
+ return Object.keys(result).length > 0 ? result : undefined
}
/** Resolve retry config with defaults */
export interface ResolvedRetryConfig {
- maxRetries: number;
- retryOnStatus: number[];
- baseDelay: number;
- maxDelay: number;
- retryOnNetworkError: boolean;
+ maxRetries: number
+ retryOnStatus: number[]
+ baseDelay: number
+ maxDelay: number
+ retryOnNetworkError: boolean
}
-export function resolveRetryConfig(retry?: import('./request').RetryConfig | false): ResolvedRetryConfig | false {
- if (retry === false) return false;
+export function resolveRetryConfig(
+ retry?: import('./request').RetryConfig | false,
+): ResolvedRetryConfig | false {
+ if (retry === false) return false
return {
maxRetries: retry?.maxRetries ?? 2,
retryOnStatus: retry?.retryOnStatus ?? [429, 500, 502, 503, 504],
baseDelay: retry?.baseDelay ?? 300,
maxDelay: retry?.maxDelay ?? 10000,
retryOnNetworkError: retry?.retryOnNetworkError ?? true,
- };
+ }
}
diff --git a/packages/sdk-core/src/index.ts b/packages/sdk-core/src/index.ts
index eb3727f901..ecec11b050 100644
--- a/packages/sdk-core/src/index.ts
+++ b/packages/sdk-core/src/index.ts
@@ -1,28 +1,26 @@
// Request infrastructure
-export { SpreeError, createRequestFn } from './request';
+
+export type { ResolvedRetryConfig } from './helpers'
+// Helpers
+export { getParams, resolveRetryConfig } from './helpers'
+// Params
+export { transformListParams } from './params'
export type {
- RetryConfig,
- RequestOptions,
+ AuthConfig,
InternalRequestOptions,
- RequestFn,
RequestConfig,
- AuthConfig,
-} from './request';
-
+ RequestFn,
+ RequestOptions,
+ RetryConfig,
+} from './request'
+export { createRequestFn, SpreeError } from './request'
// Shared types
export type {
- LocaleDefaults,
- PaginationMeta,
- ListResponse,
- PaginatedResponse,
+ AddressParams,
ErrorResponse,
ListParams,
- AddressParams,
-} from './types';
-
-// Params
-export { transformListParams } from './params';
-
-// Helpers
-export { getParams, resolveRetryConfig } from './helpers';
-export type { ResolvedRetryConfig } from './helpers';
+ ListResponse,
+ LocaleDefaults,
+ PaginatedResponse,
+ PaginationMeta,
+} from './types'
diff --git a/packages/sdk-core/src/params.ts b/packages/sdk-core/src/params.ts
index 78697e800c..4d48d75873 100644
--- a/packages/sdk-core/src/params.ts
+++ b/packages/sdk-core/src/params.ts
@@ -1,9 +1,9 @@
/**
* Keys that are passed through to the API without wrapping in q[...].
*/
-const PASSTHROUGH_KEYS = new Set(['page', 'limit', 'expand', 'sort', 'fields']);
+const PASSTHROUGH_KEYS = new Set(['page', 'limit', 'expand', 'sort', 'fields'])
-type ParamValue = string | number | boolean | (string | number)[] | undefined;
+type ParamValue = string | number | boolean | (string | number)[] | undefined
/**
* Transforms flat SDK params into Ransack-compatible query params.
@@ -12,34 +12,34 @@ type ParamValue = string | number | boolean | (string | number)[] | undefined;
* - Keys already in `q[...]` format pass through (backward compat)
* - All other keys are wrapped: `name_cont` → `q[name_cont]`
*/
-export function transformListParams(
- params: Record<string, unknown>
-): Record<string, ParamValue> {
- const result: Record<string, ParamValue> = {};
+export function transformListParams(params: Record<string, unknown>): Record<string, ParamValue> {
+ const result: Record<string, ParamValue> = {}
for (const [key, value] of Object.entries(params)) {
- if (value === undefined) continue;
+ if (value === undefined) continue
if (PASSTHROUGH_KEYS.has(key)) {
// Join arrays for passthrough keys (e.g., expand: ['variants', 'media'] → 'variants,media')
- result[key] = Array.isArray(value) ? (value as (string | number)[]).join(',') : value as ParamValue;
- continue;
+ result[key] = Array.isArray(value)
+ ? (value as (string | number)[]).join(',')
+ : (value as ParamValue)
+ continue
}
// Backward compat: already-wrapped q[...] keys pass through
if (key.startsWith('q[')) {
- result[key] = value as ParamValue;
- continue;
+ result[key] = value as ParamValue
+ continue
}
// Array values get [] suffix automatically: `foo: [1,2]` → `q[foo][]`
if (Array.isArray(value)) {
- const base = key.endsWith('[]') ? key.slice(0, -2) : key;
- result[`q[${base}][]`] = value as ParamValue;
+ const base = key.endsWith('[]') ? key.slice(0, -2) : key
+ result[`q[${base}][]`] = value as ParamValue
} else {
- result[`q[${key}]`] = value as ParamValue;
+ result[`q[${key}]`] = value as ParamValue
}
}
- return result;
+ return result
}
diff --git a/packages/sdk-core/src/request.ts b/packages/sdk-core/src/request.ts
index 95b41fed4e..241ec6a60d 100644
--- a/packages/sdk-core/src/request.ts
+++ b/packages/sdk-core/src/request.ts
@@ -1,96 +1,105 @@
-import type { ErrorResponse, LocaleDefaults } from './types';
+import type { ErrorResponse, LocaleDefaults } from './types'
export interface RetryConfig {
/** Maximum number of retries (default: 2) */
- maxRetries?: number;
+ maxRetries?: number
/** HTTP status codes to retry on (default: [429, 500, 502, 503, 504]) */
- retryOnStatus?: number[];
+ retryOnStatus?: number[]
/** Base delay in ms for exponential backoff (default: 300) */
- baseDelay?: number;
+ baseDelay?: number
/** Maximum delay in ms (default: 10000) */
- maxDelay?: number;
+ maxDelay?: number
/** Whether to retry on network errors (default: true) */
- retryOnNetworkError?: boolean;
+ retryOnNetworkError?: boolean
}
export interface RequestOptions {
/** Bearer token for authenticated requests */
- token?: string;
+ token?: string
/** Spree token for guest cart/checkout/order access */
- spreeToken?: string;
+ spreeToken?: string
/** Locale for translated content (e.g., 'en', 'fr') */
- locale?: string;
+ locale?: string
/** Currency for prices (e.g., 'USD', 'EUR') */
- currency?: string;
+ currency?: string
/** Country ISO code for market resolution (e.g., 'US', 'DE') */
- country?: string;
+ country?: string
/** Idempotency key for safe retries of mutating requests (max 255 characters) */
- idempotencyKey?: string;
+ idempotencyKey?: string
/** Custom headers */
- headers?: Record<string, string>;
+ headers?: Record<string, string>
}
export interface InternalRequestOptions extends RequestOptions {
- body?: unknown;
- params?: Record<string, string | number | boolean | (string | number)[] | undefined>;
+ body?: unknown
+ params?: Record<string, string | number | boolean | (string | number)[] | undefined>
}
export class SpreeError extends Error {
- public readonly code: string;
- public readonly status: number;
- public readonly details?: Record<string, string[]>;
+ 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;
+ 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>;
+ 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);
+ const exponentialDelay = config.baseDelay * 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));
+ return new Promise((resolve) => setTimeout(resolve, ms))
}
function generateIdempotencyKey(): string {
- return `spree-sdk-retry-${crypto.randomUUID()}`;
+ return `spree-sdk-retry-${crypto.randomUUID()}`
}
-function shouldRetryOnStatus(method: string, status: number, config: Required<RetryConfig>, hasIdempotencyKey: boolean): boolean {
- const isIdempotent = method === 'GET' || method === 'HEAD' || hasIdempotencyKey;
+function shouldRetryOnStatus(
+ method: string,
+ status: number,
+ config: Required<RetryConfig>,
+ hasIdempotencyKey: boolean,
+): boolean {
+ const isIdempotent = method === 'GET' || method === 'HEAD' || hasIdempotencyKey
if (isIdempotent) {
- return config.retryOnStatus.includes(status);
+ return config.retryOnStatus.includes(status)
}
- return status === 429;
+ return status === 429
}
-function shouldRetryOnNetworkError(method: string, config: Required<RetryConfig>, hasIdempotencyKey: boolean): boolean {
- if (!config.retryOnNetworkError) return false;
- return method === 'GET' || method === 'HEAD' || hasIdempotencyKey;
+function shouldRetryOnNetworkError(
+ method: string,
+ config: Required<RetryConfig>,
+ hasIdempotencyKey: boolean,
+): boolean {
+ if (!config.retryOnNetworkError) return false
+ return method === 'GET' || method === 'HEAD' || hasIdempotencyKey
}
export interface RequestConfig {
- baseUrl: string;
- fetchFn: typeof fetch;
- retryConfig: Required<RetryConfig> | false;
+ baseUrl: string
+ fetchFn: typeof fetch
+ retryConfig: Required<RetryConfig> | false
}
export interface AuthConfig {
- headerName: string;
- headerValue: string;
+ headerName: string
+ headerValue: string
}
/**
@@ -100,74 +109,77 @@ export function createRequestFn(
config: RequestConfig,
basePath: string,
auth: AuthConfig,
- defaults?: LocaleDefaults
+ defaults?: LocaleDefaults,
): RequestFn {
return async function request<T>(
method: string,
path: string,
- options: InternalRequestOptions = {}
+ options: InternalRequestOptions = {},
): Promise<T> {
- const { token, spreeToken, idempotencyKey, headers = {}, body, params } = options;
+ const { token, spreeToken, idempotencyKey, headers = {}, body, params } = options
// Per-request options override client-level defaults
- const locale = options.locale ?? defaults?.locale;
- const currency = options.currency ?? defaults?.currency;
- const country = options.country ?? defaults?.country;
+ const locale = options.locale ?? defaults?.locale
+ const currency = options.currency ?? defaults?.currency
+ const country = options.country ?? defaults?.country
// Build URL with query params
- const url = new URL(`${config.baseUrl}${basePath}${path}`);
+ 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)));
+ for (const v of value) {
+ url.searchParams.append(key, String(v))
+ }
} else {
- url.searchParams.set(key, String(value));
+ url.searchParams.set(key, String(value))
}
}
- });
+ })
}
// Build headers
const requestHeaders: Record<string, string> = {
'Content-Type': 'application/json',
...headers,
- };
+ }
if (auth.headerName && auth.headerValue) {
- requestHeaders[auth.headerName] = auth.headerValue;
+ requestHeaders[auth.headerName] = auth.headerValue
}
if (token) {
- requestHeaders['Authorization'] = `Bearer ${token}`;
+ requestHeaders.Authorization = `Bearer ${token}`
}
if (spreeToken) {
- requestHeaders['x-spree-token'] = spreeToken;
+ requestHeaders['x-spree-token'] = spreeToken
}
if (locale) {
- requestHeaders['x-spree-locale'] = locale;
+ requestHeaders['x-spree-locale'] = locale
}
if (currency) {
- requestHeaders['x-spree-currency'] = currency;
+ requestHeaders['x-spree-currency'] = currency
}
if (country) {
- requestHeaders['x-spree-country'] = country;
+ requestHeaders['x-spree-country'] = country
}
// Auto-generate idempotency key for mutating requests when retries are enabled (Stripe-style).
// User-supplied keys take precedence over auto-generated ones.
- const isMutating = method !== 'GET' && method !== 'HEAD';
- const effectiveIdempotencyKey = idempotencyKey ?? (isMutating && config.retryConfig ? generateIdempotencyKey() : undefined);
+ const isMutating = method !== 'GET' && method !== 'HEAD'
+ const effectiveIdempotencyKey =
+ idempotencyKey ?? (isMutating && config.retryConfig ? generateIdempotencyKey() : undefined)
if (effectiveIdempotencyKey) {
- requestHeaders['Idempotency-Key'] = effectiveIdempotencyKey;
+ requestHeaders['Idempotency-Key'] = effectiveIdempotencyKey
}
- const hasIdempotencyKey = !!effectiveIdempotencyKey;
- const maxAttempts = config.retryConfig ? config.retryConfig.maxRetries + 1 : 1;
+ const hasIdempotencyKey = !!effectiveIdempotencyKey
+ const maxAttempts = config.retryConfig ? config.retryConfig.maxRetries + 1 : 1
for (let attempt = 0; attempt < maxAttempts; attempt++) {
try {
@@ -175,57 +187,65 @@ export function createRequestFn(
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, hasIdempotencyKey)) {
- const retryAfter = response.headers.get('Retry-After');
+ const isLastAttempt = attempt >= maxAttempts - 1
+
+ if (
+ !isLastAttempt &&
+ config.retryConfig &&
+ shouldRetryOnStatus(method, response.status, config.retryConfig, hasIdempotencyKey)
+ ) {
+ 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;
+ : calculateDelay(attempt, config.retryConfig)
+ await sleep(delay)
+ continue
}
- const errorBody = await response.json() as ErrorResponse;
- throw new SpreeError(errorBody, response.status);
+ const errorBody = (await response.json()) as ErrorResponse
+ throw new SpreeError(errorBody, response.status)
}
// Handle 204 No Content (empty body)
if (response.status === 204) {
- return undefined as T;
+ return undefined as T
}
// Handle 202 Accepted — may or may not have a body
if (response.status === 202) {
- const contentType = response.headers.get('content-type');
- if (contentType && contentType.includes('application/json')) {
- return response.json() as Promise<T>;
+ const contentType = response.headers.get('content-type')
+ if (contentType?.includes('application/json')) {
+ return response.json() as Promise<T>
}
- return undefined as T;
+ return undefined as T
}
- return response.json() as Promise<T>;
+ return response.json() as Promise<T>
} catch (error) {
if (error instanceof SpreeError) {
- throw error;
+ throw error
}
- const isLastAttempt = attempt >= maxAttempts - 1;
+ const isLastAttempt = attempt >= maxAttempts - 1
- if (!isLastAttempt && config.retryConfig && shouldRetryOnNetworkError(method, config.retryConfig, hasIdempotencyKey)) {
- const delay = calculateDelay(attempt, config.retryConfig);
- await sleep(delay);
- continue;
+ if (
+ !isLastAttempt &&
+ config.retryConfig &&
+ shouldRetryOnNetworkError(method, config.retryConfig, hasIdempotencyKey)
+ ) {
+ const delay = calculateDelay(attempt, config.retryConfig)
+ await sleep(delay)
+ continue
}
- throw error;
+ throw error
}
}
// This should never be reached, but TypeScript needs it
- throw new Error('Unexpected end of retry loop');
- };
+ throw new Error('Unexpected end of retry loop')
+ }
}
diff --git a/packages/sdk-core/src/types.ts b/packages/sdk-core/src/types.ts
index 47ada6c062..37777567aa 100644
--- a/packages/sdk-core/src/types.ts
+++ b/packages/sdk-core/src/types.ts
@@ -1,71 +1,71 @@
// Locale defaults for client-level configuration
export interface LocaleDefaults {
- locale?: string;
- currency?: string;
- country?: string;
+ locale?: string
+ currency?: string
+ country?: string
}
// API Response types
export interface PaginationMeta {
- page: number;
- limit: number;
- count: number;
- pages: number;
- from: number;
- to: number;
- in: number;
- previous: number | null;
- next: number | null;
+ page: number
+ limit: number
+ count: number
+ pages: number
+ from: number
+ to: number
+ in: number
+ previous: number | null
+ next: number | null
}
export interface ListResponse<T> {
- data: T[];
+ data: T[]
}
export interface PaginatedResponse<T> extends ListResponse<T> {
- meta: PaginationMeta;
+ meta: PaginationMeta
}
export interface ErrorResponse {
error: {
- code: string;
- message: string;
- details?: Record<string, string[]>;
- };
+ code: string
+ message: string
+ details?: Record<string, string[]>
+ }
}
// Query params
export interface ListParams {
- page?: number;
- limit?: number;
+ page?: number
+ limit?: number
/** Sort order. Prefix with - for descending, e.g. '-created_at', 'name'. Comma-separated for multiple fields. */
- sort?: string;
+ sort?: string
/** Associations to expand. Supports dot notation for nested expand (max 4 levels), e.g. ['variants', 'variants.media'] */
- expand?: string[];
+ expand?: string[]
/** Fields to include in response, e.g. ['name', 'slug', 'price']. Omit to return all fields. 'id' is always included. */
- fields?: string[];
+ fields?: string[]
}
// Address params
export interface AddressParams {
- first_name: string;
- last_name: string;
- address1: string;
- address2?: string;
- city: string;
- postal_code: string;
- phone?: string;
- company?: string;
+ first_name: string
+ last_name: string
+ address1: string
+ address2?: string
+ city: string
+ postal_code: string
+ phone?: string
+ company?: string
/** ISO 3166-1 alpha-2 country code (e.g., "US", "DE") */
- country_iso: string;
+ country_iso: string
/** ISO 3166-2 subdivision code without country prefix (e.g., "CA", "NY") */
- state_abbr?: string;
+ state_abbr?: string
/** State name - used for countries without predefined states */
- state_name?: string;
+ state_name?: string
/** When true, relaxes validation requirements (name, phone, postal_code, street) */
- quick_checkout?: boolean;
+ quick_checkout?: boolean
/** Set as default billing address */
- is_default_billing?: boolean;
+ is_default_billing?: boolean
/** Set as default shipping address */
- is_default_shipping?: boolean;
+ is_default_shipping?: boolean
}
diff --git a/packages/sdk-core/tsup.config.ts b/packages/sdk-core/tsup.config.ts
index e4da34c239..3b22e6dbc1 100644
--- a/packages/sdk-core/tsup.config.ts
+++ b/packages/sdk-core/tsup.config.ts
@@ -1,4 +1,4 @@
-import { defineConfig } from 'tsup';
+import { defineConfig } from 'tsup'
export default defineConfig({
entry: {
@@ -11,4 +11,4 @@ export default defineConfig({
clean: true,
treeshake: true,
minify: false,
-});
+})
diff --git a/packages/sdk/.changeset/config.json b/packages/sdk/.changeset/config.json
index 95ea990266..0fbbd8c795 100644
--- a/packages/sdk/.changeset/config.json
+++ b/packages/sdk/.changeset/config.json
@@ -1,9 +1,6 @@
{
"$schema": "https://unpkg.com/@changesets/[email protected]/schema.json",
- "changelog": [
- "@changesets/changelog-github",
- { "repo": "spree/spree" }
- ],
+ "changelog": ["@changesets/changelog-github", { "repo": "spree/spree" }],
"commit": false,
"fixed": [],
"linked": [],
diff --git a/packages/sdk/biome.json b/packages/sdk/biome.json
index cbf6832d91..aa04ce3dcf 100644
--- a/packages/sdk/biome.json
+++ b/packages/sdk/biome.json
@@ -1,7 +1,8 @@
{
"$schema": "https://biomejs.dev/schemas/2.4.13/schema.json",
- "extends": ["//"],
+ "root": false,
+ "extends": ["../../biome.json"],
"files": {
- "includes": ["src/**", "tests/**", "!src/types/generated/**", "!src/zod/generated/**"]
+ "includes": ["src/**", "tests/**", "!src/types/generated", "!src/zod/generated"]
}
}
diff --git a/packages/sdk/console.ts b/packages/sdk/console.ts
index 150048926e..86ff8328ef 100644
--- a/packages/sdk/console.ts
+++ b/packages/sdk/console.ts
@@ -1,37 +1,35 @@
-import * as repl from "node:repl";
-import { createClient, SpreeError } from "./src";
+import * as repl from 'node:repl'
+import { createClient, SpreeError } from './src'
-const baseUrl = process.env.SPREE_URL || "http://localhost:3000";
-const publishableKey = process.env.SPREE_PUBLISHABLE_KEY || "";
+const baseUrl = process.env.SPREE_URL || 'http://localhost:3000'
+const publishableKey = process.env.SPREE_PUBLISHABLE_KEY || ''
if (!publishableKey) {
- console.log("Usage: SPREE_PUBLISHABLE_KEY=spree_pk_xxx npx tsx console.ts");
+ 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("");
+ ' SPREE_PUBLISHABLE_KEY=spree_pk_xxx SPREE_URL=https://api.mystore.com npx tsx console.ts',
+ )
+ console.log('')
}
-const client = createClient({ baseUrl, publishableKey });
+const client = createClient({ baseUrl, publishableKey })
-console.log("Spree SDK Console");
-console.log(`Connected to: ${baseUrl}`);
-console.log("");
-console.log("Available:");
-console.log(" client - Client instance");
-console.log(" createClient - Create new client");
-console.log("");
-console.log("Examples:");
-console.log(" await client.products.list()");
-console.log(' await client.products.get("my-product", {}, { locale: "fr" })');
-console.log(
- ' await client.categories.get("clothing/shirts", {}, { currency: "EUR" })',
-);
-console.log("");
+console.log('Spree SDK Console')
+console.log(`Connected to: ${baseUrl}`)
+console.log('')
+console.log('Available:')
+console.log(' client - Client instance')
+console.log(' createClient - Create new client')
+console.log('')
+console.log('Examples:')
+console.log(' await client.products.list()')
+console.log(' await client.products.get("my-product", {}, { locale: "fr" })')
+console.log(' await client.categories.get("clothing/shirts", {}, { currency: "EUR" })')
+console.log('')
-const r = repl.start({ prompt: "spree> ", useGlobal: true });
+const r = repl.start({ prompt: 'spree> ', useGlobal: true })
// Make await work at top level
-r.context.client = client;
-r.context.createClient = createClient;
-r.context.SpreeError = SpreeError;
+r.context.client = client
+r.context.createClient = createClient
+r.context.SpreeError = SpreeError
diff --git a/packages/sdk/package.json b/packages/sdk/package.json
index b0c665d22f..2f8f46e8f9 100644
--- a/packages/sdk/package.json
+++ b/packages/sdk/package.json
@@ -62,6 +62,9 @@
"test:integration": "vitest run --config vitest.integration.config.ts",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
+ "lint": "biome check src tests",
+ "lint:fix": "biome check --fix src tests",
+ "format": "biome format --write src tests",
"clean": "rm -rf dist",
"prepublishOnly": "npm run build",
"changeset": "changeset",
diff --git a/packages/sdk/scripts/generate-zod.ts b/packages/sdk/scripts/generate-zod.ts
index 4b356939f9..44047d0b19 100644
--- a/packages/sdk/scripts/generate-zod.ts
+++ b/packages/sdk/scripts/generate-zod.ts
@@ -1,173 +1,191 @@
-import * as fs from 'node:fs';
-import * as path from 'node:path';
+import * as fs from 'node:fs'
+import * as path from 'node:path'
-const TYPES_DIR = path.resolve(import.meta.dirname, '../src/types/generated');
-const ZOD_DIR = path.resolve(import.meta.dirname, '../src/zod/generated');
+const TYPES_DIR = path.resolve(import.meta.dirname, '../src/types/generated')
+const ZOD_DIR = path.resolve(import.meta.dirname, '../src/zod/generated')
interface FieldDef {
- name: string;
- type: string;
- optional: boolean;
+ name: string
+ type: string
+ optional: boolean
}
interface ParsedType {
- typeName: string;
- fields: FieldDef[];
+ typeName: string
+ fields: FieldDef[]
}
function parseTypeFile(content: string): ParsedType | null {
- const typeNameMatch = content.match(/^(?:type\s+(\w+)\s*=\s*\{|interface\s+(\w+)\s*\{)/m);
- if (!typeNameMatch) return null;
- const typeName = typeNameMatch[1] || typeNameMatch[2];
+ const typeNameMatch = content.match(/^(?:type\s+(\w+)\s*=\s*\{|interface\s+(\w+)\s*\{)/m)
+ if (!typeNameMatch) return null
+ const typeName = typeNameMatch[1] || typeNameMatch[2]
// Find the body between braces, handling nested braces (e.g., inline object types)
- const typeStart = content.indexOf('{', content.search(/^(?:type\s+\w+\s*=\s*\{|interface\s+\w+\s*\{)/m));
- if (typeStart === -1) return null;
- let depth = 1;
- let i = typeStart + 1;
+ const typeStart = content.indexOf(
+ '{',
+ content.search(/^(?:type\s+\w+\s*=\s*\{|interface\s+\w+\s*\{)/m),
+ )
+ if (typeStart === -1) return null
+ let depth = 1
+ let i = typeStart + 1
while (i < content.length && depth > 0) {
- if (content[i] === '{') depth++;
- else if (content[i] === '}') depth--;
- i++;
+ if (content[i] === '{') depth++
+ else if (content[i] === '}') depth--
+ i++
}
- if (depth !== 0) return null;
- const body = content.slice(typeStart + 1, i - 1);
- const fields: FieldDef[] = [];
- const fieldRegex = /^\s+(\w+)(\?)?\s*:\s*(.+?)\s*;?\s*$/gm;
- let match: RegExpExecArray | null;
+ if (depth !== 0) return null
+ const body = content.slice(typeStart + 1, i - 1)
+ const fields: FieldDef[] = []
+ const fieldRegex = /^\s+(\w+)(\?)?\s*:\s*(.+?)\s*;?\s*$/gm
+ let match: RegExpExecArray | null
while ((match = fieldRegex.exec(body)) !== null) {
fields.push({
name: match[1],
type: match[3].replace(/;$/, '').trim(),
optional: match[2] === '?',
- });
+ })
}
- return { typeName, fields };
+ return { typeName, fields }
}
function isTypeReference(typeStr: string): boolean {
- return /^[A-Z]\w+$/.test(typeStr);
+ return /^[A-Z]\w+$/.test(typeStr)
}
function isPrimitive(t: string): boolean {
- return t === 'string' || t === 'number' || t === 'boolean';
+ return t === 'string' || t === 'number' || t === 'boolean'
}
-function primitiveOrRef(inner: string, referencedTypes: Set<string>, cyclicTypes: Set<string>): string {
- if (isPrimitive(inner)) return `z.${inner}()`;
+function primitiveOrRef(
+ inner: string,
+ referencedTypes: Set<string>,
+ cyclicTypes: Set<string>,
+): string {
+ if (isPrimitive(inner)) return `z.${inner}()`
if (isTypeReference(inner)) {
- referencedTypes.add(inner);
+ referencedTypes.add(inner)
if (cyclicTypes.has(inner)) {
- return `z.lazy(() => ${inner}Schema)`;
+ return `z.lazy(() => ${inner}Schema)`
}
- return `${inner}Schema`;
+ return `${inner}Schema`
}
- return 'z.any()';
+ return 'z.any()'
}
/** Parse an inline object type like {step: string, field: string} into a z.object() expression */
-function inlineObjectToZod(inner: string, referencedTypes: Set<string>, cyclicTypes: Set<string>): string | null {
- const trimmed = inner.trim();
- if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) return null;
- const body = trimmed.slice(1, -1);
- const fields = body.split(',').map(f => f.trim()).filter(Boolean);
- const zodFields: string[] = [];
+function inlineObjectToZod(
+ inner: string,
+ referencedTypes: Set<string>,
+ cyclicTypes: Set<string>,
+): string | null {
+ const trimmed = inner.trim()
+ if (!trimmed.startsWith('{') || !trimmed.endsWith('}')) return null
+ const body = trimmed.slice(1, -1)
+ const fields = body
+ .split(',')
+ .map((f) => f.trim())
+ .filter(Boolean)
+ const zodFields: string[] = []
for (const field of fields) {
- const match = field.match(/^(\w+)\s*:\s*(.+)$/);
- if (!match) return null;
- const [, name, type] = match;
- zodFields.push(`${name}: ${typeToZod(type.trim(), referencedTypes, cyclicTypes)}`);
+ const match = field.match(/^(\w+)\s*:\s*(.+)$/)
+ if (!match) return null
+ const [, name, type] = match
+ zodFields.push(`${name}: ${typeToZod(type.trim(), referencedTypes, cyclicTypes)}`)
}
- return `z.object({ ${zodFields.join(', ')} })`;
+ return `z.object({ ${zodFields.join(', ')} })`
}
-function typeToZod(typeStr: string, referencedTypes: Set<string>, cyclicTypes: Set<string>): string {
- const t = typeStr.trim();
+function typeToZod(
+ typeStr: string,
+ referencedTypes: Set<string>,
+ cyclicTypes: Set<string>,
+): string {
+ const t = typeStr.trim()
// Record<string, unknown> | null
if (/^Record<string,\s*unknown>\s*\|\s*null$/.test(t)) {
- return 'z.record(z.string(), z.unknown()).nullable()';
+ return 'z.record(z.string(), z.unknown()).nullable()'
}
if (/^Record<string,\s*unknown>$/.test(t)) {
- return 'z.record(z.string(), z.unknown())';
+ return 'z.record(z.string(), z.unknown())'
}
- if (t === 'any') return 'z.any()';
+ if (t === 'any') return 'z.any()'
// Array<T> | null
- const arrayNullableMatch = t.match(/^Array<(.+)>\s*\|\s*null$/);
+ const arrayNullableMatch = t.match(/^Array<(.+)>\s*\|\s*null$/)
if (arrayNullableMatch) {
- const inner = arrayNullableMatch[1].trim();
- const inlineObj = inlineObjectToZod(inner, referencedTypes, cyclicTypes);
- if (inlineObj) return `z.array(${inlineObj}).nullable()`;
- return `z.array(${primitiveOrRef(inner, referencedTypes, cyclicTypes)}).nullable()`;
+ const inner = arrayNullableMatch[1].trim()
+ const inlineObj = inlineObjectToZod(inner, referencedTypes, cyclicTypes)
+ if (inlineObj) return `z.array(${inlineObj}).nullable()`
+ return `z.array(${primitiveOrRef(inner, referencedTypes, cyclicTypes)}).nullable()`
}
// Array<T>
- const arrayMatch = t.match(/^Array<(.+)>$/);
+ const arrayMatch = t.match(/^Array<(.+)>$/)
if (arrayMatch) {
- const inner = arrayMatch[1].trim();
- const inlineObj = inlineObjectToZod(inner, referencedTypes, cyclicTypes);
- if (inlineObj) return `z.array(${inlineObj})`;
- return `z.array(${primitiveOrRef(inner, referencedTypes, cyclicTypes)})`;
+ const inner = arrayMatch[1].trim()
+ const inlineObj = inlineObjectToZod(inner, referencedTypes, cyclicTypes)
+ if (inlineObj) return `z.array(${inlineObj})`
+ return `z.array(${primitiveOrRef(inner, referencedTypes, cyclicTypes)})`
}
// String literal unions: 'a' | 'b' | 'c'
- if (/^'[^']*'(\s*\|\s*'[^']*')+$/.test(t)) return 'z.string()';
+ if (/^'[^']*'(\s*\|\s*'[^']*')+$/.test(t)) return 'z.string()'
// String literal union | null
- if (/^'[^']*'(\s*\|\s*'[^']*')*\s*\|\s*null$/.test(t)) return 'z.string().nullable()';
+ if (/^'[^']*'(\s*\|\s*'[^']*')*\s*\|\s*null$/.test(t)) return 'z.string().nullable()'
// T | null
- const nullableMatch = t.match(/^(\w+)\s*\|\s*null$/);
+ const nullableMatch = t.match(/^(\w+)\s*\|\s*null$/)
if (nullableMatch) {
- const base = nullableMatch[1].trim();
- if (isPrimitive(base)) return `z.${base}().nullable()`;
+ const base = nullableMatch[1].trim()
+ if (isPrimitive(base)) return `z.${base}().nullable()`
if (isTypeReference(base)) {
- referencedTypes.add(base);
+ referencedTypes.add(base)
if (cyclicTypes.has(base)) {
- return `z.lazy(() => ${base}Schema).nullable()`;
+ return `z.lazy(() => ${base}Schema).nullable()`
}
- return `${base}Schema.nullable()`;
+ return `${base}Schema.nullable()`
}
}
// Simple primitive
- if (isPrimitive(t)) return `z.${t}()`;
+ if (isPrimitive(t)) return `z.${t}()`
// Type reference
if (isTypeReference(t)) {
- referencedTypes.add(t);
+ referencedTypes.add(t)
if (cyclicTypes.has(t)) {
- return `z.lazy(() => ${t}Schema)`;
+ return `z.lazy(() => ${t}Schema)`
}
- return `${t}Schema`;
+ return `${t}Schema`
}
- return 'z.any()';
+ return 'z.any()'
}
function generateZodFile(parsed: ParsedType, cyclicTypes: Set<string>): string {
- const referencedTypes = new Set<string>();
- const fieldLines: string[] = [];
+ const referencedTypes = new Set<string>()
+ const fieldLines: string[] = []
for (const field of parsed.fields) {
- let zodExpr = typeToZod(field.type, referencedTypes, cyclicTypes);
- if (field.optional) zodExpr += '.optional()';
- fieldLines.push(` ${field.name}: ${zodExpr},`);
+ let zodExpr = typeToZod(field.type, referencedTypes, cyclicTypes)
+ if (field.optional) zodExpr += '.optional()'
+ fieldLines.push(` ${field.name}: ${zodExpr},`)
}
// Don't import self-references (self-referencing types use z.lazy)
const refImports = Array.from(referencedTypes)
.filter((ref) => ref !== parsed.typeName)
.sort()
- .map((ref) => `import { ${ref}Schema } from './${ref}';`);
+ .map((ref) => `import { ${ref}Schema } from './${ref}';`)
- const isCyclic = cyclicTypes.has(parsed.typeName);
+ const isCyclic = cyclicTypes.has(parsed.typeName)
// For cyclic types, add explicit type annotation to break circular inference
const schemaDecl = isCyclic
? `export const ${parsed.typeName}Schema: z.ZodObject<any> = z.object({`
- : `export const ${parsed.typeName}Schema = z.object({`;
+ : `export const ${parsed.typeName}Schema = z.object({`
const lines: string[] = [
'// This file is auto-generated. Do not edit directly.',
@@ -180,121 +198,121 @@ function generateZodFile(parsed: ParsedType, cyclicTypes: Set<string>): string {
'',
`export type ${parsed.typeName} = z.infer<typeof ${parsed.typeName}Schema>;`,
'',
- ];
+ ]
- return lines.join('\n');
+ return lines.join('\n')
}
/** Extract type references from field types */
function extractTypeRefs(fields: FieldDef[]): Set<string> {
- const refs = new Set<string>();
+ const refs = new Set<string>()
for (const field of fields) {
- const t = field.type.trim();
+ const t = field.type.trim()
// Array<T>
- const arrayMatch = t.match(/Array<(\w+)>/);
- if (arrayMatch && isTypeReference(arrayMatch[1])) refs.add(arrayMatch[1]);
+ const arrayMatch = t.match(/Array<(\w+)>/)
+ if (arrayMatch && isTypeReference(arrayMatch[1])) refs.add(arrayMatch[1])
// T | null
- const nullableMatch = t.match(/^(\w+)\s*\|\s*null$/);
- if (nullableMatch && isTypeReference(nullableMatch[1])) refs.add(nullableMatch[1]);
+ const nullableMatch = t.match(/^(\w+)\s*\|\s*null$/)
+ if (nullableMatch && isTypeReference(nullableMatch[1])) refs.add(nullableMatch[1])
// Plain T
- if (isTypeReference(t)) refs.add(t);
+ if (isTypeReference(t)) refs.add(t)
}
- return refs;
+ return refs
}
/** Detect all types involved in circular dependencies */
function detectCyclicTypes(parsedTypes: Map<string, ParsedType>): Set<string> {
- const deps = new Map<string, Set<string>>();
+ const deps = new Map<string, Set<string>>()
for (const [name, parsed] of parsedTypes) {
- deps.set(name, extractTypeRefs(parsed.fields));
+ deps.set(name, extractTypeRefs(parsed.fields))
}
- const cyclic = new Set<string>();
- const visited = new Set<string>();
- const inStack = new Set<string>();
+ const cyclic = new Set<string>()
+ const visited = new Set<string>()
+ const inStack = new Set<string>()
function dfs(node: string, path: string[]): void {
if (inStack.has(node)) {
// Found a cycle — mark all nodes in the cycle
- const cycleStart = path.indexOf(node);
+ const cycleStart = path.indexOf(node)
for (let i = cycleStart; i < path.length; i++) {
- cyclic.add(path[i]);
+ cyclic.add(path[i])
}
- return;
+ return
}
- if (visited.has(node)) return;
+ if (visited.has(node)) return
- visited.add(node);
- inStack.add(node);
- path.push(node);
+ visited.add(node)
+ inStack.add(node)
+ path.push(node)
for (const dep of deps.get(node) ?? []) {
if (deps.has(dep)) {
- dfs(dep, path);
+ dfs(dep, path)
}
}
- path.pop();
- inStack.delete(node);
+ path.pop()
+ inStack.delete(node)
}
for (const name of deps.keys()) {
- dfs(name, []);
+ dfs(name, [])
}
- return cyclic;
+ return cyclic
}
function main(): void {
if (fs.existsSync(ZOD_DIR)) {
- fs.rmSync(ZOD_DIR, { recursive: true });
+ fs.rmSync(ZOD_DIR, { recursive: true })
}
- fs.mkdirSync(ZOD_DIR, { recursive: true });
+ fs.mkdirSync(ZOD_DIR, { recursive: true })
const files = fs
.readdirSync(TYPES_DIR)
.filter((f) => f.endsWith('.ts') && f !== 'index.ts')
- .sort();
+ .sort()
// First pass: parse all type files
- const parsedTypes = new Map<string, ParsedType>();
+ const parsedTypes = new Map<string, ParsedType>()
for (const file of files) {
- const filePath = path.join(TYPES_DIR, file);
- const content = fs.readFileSync(filePath, 'utf-8');
- const parsed = parseTypeFile(content);
+ const filePath = path.join(TYPES_DIR, file)
+ const content = fs.readFileSync(filePath, 'utf-8')
+ const parsed = parseTypeFile(content)
if (!parsed) {
- console.warn(`Skipping ${file}: could not parse type definition`);
- continue;
+ console.warn(`Skipping ${file}: could not parse type definition`)
+ continue
}
- parsedTypes.set(parsed.typeName, parsed);
+ parsedTypes.set(parsed.typeName, parsed)
}
// Detect cycles
- const cyclicTypes = detectCyclicTypes(parsedTypes);
+ const cyclicTypes = detectCyclicTypes(parsedTypes)
if (cyclicTypes.size > 0) {
- console.log(`Detected circular dependencies: ${Array.from(cyclicTypes).join(', ')}`);
- console.log('Using z.lazy() for these references.\n');
+ console.log(`Detected circular dependencies: ${Array.from(cyclicTypes).join(', ')}`)
+ console.log('Using z.lazy() for these references.\n')
}
- const generatedNames: string[] = [];
+ const generatedNames: string[] = []
for (const [, parsed] of parsedTypes) {
fs.writeFileSync(
path.join(ZOD_DIR, `${parsed.typeName}.ts`),
generateZodFile(parsed, cyclicTypes),
- 'utf-8'
- );
- generatedNames.push(parsed.typeName);
- console.log(`Generated: ${parsed.typeName}.ts`);
+ 'utf-8',
+ )
+ generatedNames.push(parsed.typeName)
+ console.log(`Generated: ${parsed.typeName}.ts`)
}
const indexLines = [
'// This file is auto-generated. Do not edit directly.',
...generatedNames.map((n) => `export { ${n}Schema, type ${n} } from './${n}';`),
'',
- ];
- fs.writeFileSync(path.join(ZOD_DIR, 'index.ts'), indexLines.join('\n'), 'utf-8');
- console.log(`\nGenerated barrel: index.ts (${generatedNames.length} schemas)`);
+ ]
+ fs.writeFileSync(path.join(ZOD_DIR, 'index.ts'), indexLines.join('\n'), 'utf-8')
+ console.log(`\nGenerated barrel: index.ts (${generatedNames.length} schemas)`)
}
-main();
+main()
diff --git a/packages/sdk/src/client.ts b/packages/sdk/src/client.ts
index 22438f5d10..a5d63f1917 100644
--- a/packages/sdk/src/client.ts
+++ b/packages/sdk/src/client.ts
@@ -1,31 +1,31 @@
-import { createRequestFn, resolveRetryConfig } from '@spree/sdk-core';
-import type { RetryConfig, RequestConfig, LocaleDefaults } from '@spree/sdk-core';
-import { StoreClient } from './store-client';
+import type { LocaleDefaults, RequestConfig, RetryConfig } from '@spree/sdk-core'
+import { createRequestFn, resolveRetryConfig } from '@spree/sdk-core'
+import { StoreClient } from './store-client'
export interface ClientConfig {
/** Base URL of the Spree API (e.g., 'https://api.mystore.com') */
- baseUrl: string;
+ baseUrl: string
/** Publishable API key for Store API access */
- publishableKey: string;
+ publishableKey: string
/** Custom fetch implementation (optional, defaults to global fetch) */
- fetch?: typeof fetch;
+ fetch?: typeof fetch
/** Retry configuration. Enabled by default. Pass false to disable. */
- retry?: RetryConfig | false;
+ retry?: RetryConfig | false
/** Default locale for API requests (e.g., 'fr') */
- locale?: string;
+ locale?: string
/** Default currency for API requests (e.g., 'EUR') */
- currency?: string;
+ currency?: string
/** Default country ISO code for market resolution (e.g., 'FR') */
- country?: string;
+ country?: string
}
export interface Client extends StoreClient {
/** Set default locale for all subsequent requests */
- setLocale(locale: string): void;
+ setLocale(locale: string): void
/** Set default currency for all subsequent requests */
- setCurrency(currency: string): void;
+ setCurrency(currency: string): void
/** Set default country for all subsequent requests */
- setCountry(country: string): void;
+ setCountry(country: string): void
}
/**
@@ -40,41 +40,41 @@ export interface Client extends StoreClient {
* ```
*/
export function createClient(config: ClientConfig): Client {
- const baseUrl = config.baseUrl.replace(/\/$/, '');
- const fetchFn = config.fetch || fetch.bind(globalThis);
+ const baseUrl = config.baseUrl.replace(/\/$/, '')
+ const fetchFn = config.fetch || fetch.bind(globalThis)
const defaults: LocaleDefaults = {
locale: config.locale,
currency: config.currency,
country: config.country,
- };
+ }
- const retryConfig = resolveRetryConfig(config.retry);
+ const retryConfig = resolveRetryConfig(config.retry)
- const requestConfig: RequestConfig = { baseUrl, fetchFn, retryConfig };
+ const requestConfig: RequestConfig = { baseUrl, fetchFn, retryConfig }
const requestFn = createRequestFn(
requestConfig,
'/api/v3/store',
{ headerName: 'x-spree-api-key', headerValue: config.publishableKey },
- defaults
- );
+ defaults,
+ )
- const storeClient = new StoreClient(requestFn);
+ const storeClient = new StoreClient(requestFn)
// Build the flat client by spreading StoreClient's prototype methods/properties
// and adding locale/currency/country setters
- const client = Object.create(storeClient) as Client;
+ const client = Object.create(storeClient) as Client
client.setLocale = (locale: string) => {
- defaults.locale = locale;
- };
+ defaults.locale = locale
+ }
client.setCurrency = (currency: string) => {
- defaults.currency = currency;
- };
+ defaults.currency = currency
+ }
client.setCountry = (country: string) => {
- defaults.country = country;
- };
+ defaults.country = country
+ }
- return client;
+ return client
}
diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.ts
index 178f70499c..85e8129807 100644
--- a/packages/sdk/src/index.ts
+++ b/packages/sdk/src/index.ts
@@ -1,13 +1,12 @@
// Main client
-export { createClient } from './client';
-export type { ClientConfig, Client } from './client';
-
-// Store client class (for advanced use / subclassing)
-export { StoreClient } from './store-client';
+export type { RequestFn, RequestOptions, RetryConfig } from '@spree/sdk-core'
// Request infrastructure (re-export from sdk-core)
-export { SpreeError } from '@spree/sdk-core';
-export type { RequestFn, RequestOptions, RetryConfig } from '@spree/sdk-core';
+export { SpreeError } from '@spree/sdk-core'
+export type { Client, ClientConfig } from './client'
+export { createClient } from './client'
+// Store client class (for advanced use / subclassing)
+export { StoreClient } from './store-client'
// All types
-export * from './types';
+export * from './types'
diff --git a/packages/sdk/src/store-client.ts b/packages/sdk/src/store-client.ts
index 4d446e93f8..38fc367431 100644
--- a/packages/sdk/src/store-client.ts
+++ b/packages/sdk/src/store-client.ts
@@ -1,52 +1,53 @@
-import type { RequestFn, RequestOptions } from '@spree/sdk-core';
-import { transformListParams, getParams } from '@spree/sdk-core';
import type {
+ AddressParams,
+ ListParams,
ListResponse,
PaginatedResponse,
- ListParams,
- AddressParams,
-} from '@spree/sdk-core';
+ RequestFn,
+ RequestOptions,
+} from '@spree/sdk-core'
+import { getParams, transformListParams } from '@spree/sdk-core'
import type {
+ AddLineItemParams,
+ Address,
AuthTokens,
- LoginCredentials,
- RegisterParams,
- ProductListParams,
- ProductFiltersParams,
- ProductFiltersResponse,
+ Cart,
+ Category,
CategoryListParams,
- OrderListParams,
+ CompletePaymentSessionParams,
+ CompletePaymentSetupSessionParams,
+ Country,
CreateCartParams,
- AddLineItemParams,
- UpdateLineItemParams,
- UpdateCartParams,
CreatePaymentParams,
CreatePaymentSessionParams,
- UpdatePaymentSessionParams,
- CompletePaymentSessionParams,
CreatePaymentSetupSessionParams,
- CompletePaymentSetupSessionParams,
- RequestPasswordResetParams,
- ResetPasswordParams,
- Cart,
CreditCard,
- GiftCard,
- Product,
- Order,
- Country,
Currency,
+ Customer,
+ GiftCard,
Locale,
+ LoginCredentials,
Market,
- Policy,
- Category,
+ Order,
+ OrderListParams,
Payment,
PaymentSession,
PaymentSetupSession,
+ Policy,
+ Product,
+ ProductFiltersParams,
+ ProductFiltersResponse,
+ ProductListParams,
+ RegisterParams,
+ RequestPasswordResetParams,
+ ResetPasswordParams,
StoreCredit,
+ UpdateCartParams,
+ UpdateLineItemParams,
+ UpdatePaymentSessionParams,
Wishlist,
WishlistItem,
- Address,
- Customer,
-} from './types';
+} from './types'
export class StoreClient {
/**
@@ -60,10 +61,10 @@ export class StoreClient {
* const brands = await client.request<PaginatedResponse<Brand>>('GET', '/brands')
* ```
*/
- readonly request: RequestFn;
+ readonly request: RequestFn
constructor(request: RequestFn) {
- this.request = request;
+ this.request = request
}
// ============================================
@@ -90,7 +91,7 @@ export class StoreClient {
*/
logout: (params: { refresh_token: string }, options?: RequestOptions): Promise<void> =>
this.request<void>('POST', '/auth/logout', { ...options, body: params }),
- };
+ }
// ============================================
// Products
@@ -102,7 +103,7 @@ export class StoreClient {
*/
list: (
params?: ProductListParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<PaginatedResponse<Product>> =>
this.request<PaginatedResponse<Product>>('GET', '/products', {
...options,
@@ -115,7 +116,7 @@ export class StoreClient {
get: (
idOrSlug: string,
params?: { expand?: string[]; fields?: string[] },
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Product> =>
this.request<Product>('GET', `/products/${idOrSlug}`, {
...options,
@@ -128,13 +129,13 @@ export class StoreClient {
*/
filters: (
params?: ProductFiltersParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<ProductFiltersResponse> =>
this.request<ProductFiltersResponse>('GET', '/products/filters', {
...options,
params: params as Record<string, string | number | undefined>,
}),
- };
+ }
// ============================================
// Categories
@@ -146,7 +147,7 @@ export class StoreClient {
*/
list: (
params?: CategoryListParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<PaginatedResponse<Category>> =>
this.request<PaginatedResponse<Category>>('GET', '/categories', {
...options,
@@ -159,13 +160,13 @@ export class StoreClient {
get: (
idOrPermalink: string,
params?: { expand?: string[]; fields?: string[] },
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Category> =>
this.request<Category>('GET', `/categories/${idOrPermalink}`, {
...options,
params: getParams(params),
}),
- };
+ }
// ============================================
// Countries, Currencies & Locales
@@ -187,13 +188,13 @@ export class StoreClient {
get: (
iso: string,
params?: { expand?: string[]; fields?: string[] },
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Country> =>
this.request<Country>('GET', `/countries/${iso}`, {
...options,
params: getParams(params),
}),
- };
+ }
readonly currencies = {
/**
@@ -201,7 +202,7 @@ export class StoreClient {
*/
list: (options?: RequestOptions): Promise<ListResponse<Currency>> =>
this.request<ListResponse<Currency>>('GET', '/currencies', options),
- };
+ }
readonly locales = {
/**
@@ -209,7 +210,7 @@ export class StoreClient {
*/
list: (options?: RequestOptions): Promise<ListResponse<Locale>> =>
this.request<ListResponse<Locale>>('GET', '/locales', options),
- };
+ }
// ============================================
// Policies
@@ -228,7 +229,7 @@ export class StoreClient {
*/
get: (id: string, options?: RequestOptions): Promise<Policy> =>
this.request<Policy>('GET', `/policies/${id}`, options),
- };
+ }
// ============================================
// Markets
@@ -266,15 +267,8 @@ export class StoreClient {
* List countries belonging to a market
* @param marketId - Market prefixed ID
*/
- list: (
- marketId: string,
- options?: RequestOptions
- ): Promise<ListResponse<Country>> =>
- this.request<ListResponse<Country>>(
- 'GET',
- `/markets/${marketId}/countries`,
- options
- ),
+ list: (marketId: string, options?: RequestOptions): Promise<ListResponse<Country>> =>
+ this.request<ListResponse<Country>>('GET', `/markets/${marketId}/countries`, options),
/**
* Get a country by ISO code within a market
@@ -285,15 +279,14 @@ export class StoreClient {
marketId: string,
iso: string,
params?: { expand?: string[]; fields?: string[] },
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Country> =>
- this.request<Country>(
- 'GET',
- `/markets/${marketId}/countries/${iso}`,
- { ...options, params: getParams(params) }
- ),
+ this.request<Country>('GET', `/markets/${marketId}/countries/${iso}`, {
+ ...options,
+ params: getParams(params),
+ }),
},
- };
+ }
// ============================================
// Carts
@@ -328,11 +321,7 @@ export class StoreClient {
* @param cartId - Cart prefixed ID
* @param params - Cart update parameters
*/
- update: (
- cartId: string,
- params: UpdateCartParams,
- options?: RequestOptions
- ): Promise<Cart> =>
+ update: (cartId: string, params: UpdateCartParams, options?: RequestOptions): Promise<Cart> =>
this.request<Cart>('PATCH', `/carts/${cartId}`, {
...options,
body: params,
@@ -373,7 +362,7 @@ export class StoreClient {
create: (
cartId: string,
params: AddLineItemParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Cart> =>
this.request<Cart>('POST', `/carts/${cartId}/items`, {
...options,
@@ -389,29 +378,20 @@ export class StoreClient {
cartId: string,
lineItemId: string,
params: UpdateLineItemParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Cart> =>
- this.request<Cart>(
- 'PATCH',
- `/carts/${cartId}/items/${lineItemId}`,
- { ...options, body: params }
- ),
+ this.request<Cart>('PATCH', `/carts/${cartId}/items/${lineItemId}`, {
+ ...options,
+ body: params,
+ }),
/**
* Remove a line item from the cart.
* Returns the updated cart with recalculated totals.
* @param cartId - Cart prefixed ID
*/
- delete: (
- cartId: string,
- lineItemId: string,
- options?: RequestOptions
- ): Promise<Cart> =>
- this.request<Cart>(
- 'DELETE',
- `/carts/${cartId}/items/${lineItemId}`,
- options
- ),
+ delete: (cartId: string, lineItemId: string, options?: RequestOptions): Promise<Cart> =>
+ this.request<Cart>('DELETE', `/carts/${cartId}/items/${lineItemId}`, options),
},
/**
@@ -423,11 +403,7 @@ export class StoreClient {
* @param cartId - Cart prefixed ID
* @param code - Promotion discount code to apply (e.g., 'SAVE10')
*/
- apply: (
- cartId: string,
- code: string,
- options?: RequestOptions
- ): Promise<Cart> =>
+ apply: (cartId: string, code: string, options?: RequestOptions): Promise<Cart> =>
this.request<Cart>('POST', `/carts/${cartId}/discount_codes`, {
...options,
body: { code },
@@ -438,16 +414,8 @@ export class StoreClient {
* @param cartId - Cart prefixed ID
* @param code - The discount code string to remove (e.g., 'SAVE10')
*/
- remove: (
- cartId: string,
- code: string,
- options?: RequestOptions
- ): Promise<Cart> =>
- this.request<Cart>(
- 'DELETE',
- `/carts/${cartId}/discount_codes/${code}`,
- options
- ),
+ remove: (cartId: string, code: string, options?: RequestOptions): Promise<Cart> =>
+ this.request<Cart>('DELETE', `/carts/${cartId}/discount_codes/${code}`, options),
},
/**
@@ -461,11 +429,7 @@ export class StoreClient {
* @param cartId - Cart prefixed ID
* @param code - Gift card code to apply
*/
- apply: (
- cartId: string,
- code: string,
- options?: RequestOptions
- ): Promise<Cart> =>
+ apply: (cartId: string, code: string, options?: RequestOptions): Promise<Cart> =>
this.request<Cart>('POST', `/carts/${cartId}/gift_cards`, {
...options,
body: { code },
@@ -476,16 +440,8 @@ export class StoreClient {
* @param cartId - Cart prefixed ID
* @param giftCardId - Gift card prefixed ID (e.g., 'gc_abc123')
*/
- remove: (
- cartId: string,
- giftCardId: string,
- options?: RequestOptions
- ): Promise<Cart> =>
- this.request<Cart>(
- 'DELETE',
- `/carts/${cartId}/gift_cards/${giftCardId}`,
- options
- ),
+ remove: (cartId: string, giftCardId: string, options?: RequestOptions): Promise<Cart> =>
+ this.request<Cart>('DELETE', `/carts/${cartId}/gift_cards/${giftCardId}`, options),
},
/**
@@ -501,13 +457,12 @@ export class StoreClient {
cartId: string,
fulfillmentId: string,
params: { selected_delivery_rate_id: string },
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Cart> =>
- this.request<Cart>(
- 'PATCH',
- `/carts/${cartId}/fulfillments/${fulfillmentId}`,
- { ...options, body: params }
- ),
+ this.request<Cart>('PATCH', `/carts/${cartId}/fulfillments/${fulfillmentId}`, {
+ ...options,
+ body: params,
+ }),
},
/**
@@ -522,13 +477,9 @@ export class StoreClient {
create: (
cartId: string,
params: CreatePaymentParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Payment> =>
- this.request<Payment>(
- 'POST',
- `/carts/${cartId}/payments`,
- { ...options, body: params }
- ),
+ this.request<Payment>('POST', `/carts/${cartId}/payments`, { ...options, body: params }),
},
/**
@@ -543,27 +494,22 @@ export class StoreClient {
create: (
cartId: string,
params: CreatePaymentSessionParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<PaymentSession> =>
- this.request<PaymentSession>(
- 'POST',
- `/carts/${cartId}/payment_sessions`,
- { ...options, body: params }
- ),
+ this.request<PaymentSession>('POST', `/carts/${cartId}/payment_sessions`, {
+ ...options,
+ body: params,
+ }),
/**
* Get a payment session by ID
* @param cartId - Cart prefixed ID
*/
- get: (
- cartId: string,
- sessionId: string,
- options?: RequestOptions
- ): Promise<PaymentSession> =>
+ get: (cartId: string, sessionId: string, options?: RequestOptions): Promise<PaymentSession> =>
this.request<PaymentSession>(
'GET',
`/carts/${cartId}/payment_sessions/${sessionId}`,
- options
+ options,
),
/**
@@ -575,13 +521,12 @@ export class StoreClient {
cartId: string,
sessionId: string,
params: UpdatePaymentSessionParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<PaymentSession> =>
- this.request<PaymentSession>(
- 'PATCH',
- `/carts/${cartId}/payment_sessions/${sessionId}`,
- { ...options, body: params }
- ),
+ this.request<PaymentSession>('PATCH', `/carts/${cartId}/payment_sessions/${sessionId}`, {
+ ...options,
+ body: params,
+ }),
/**
* Complete a payment session.
@@ -592,12 +537,12 @@ export class StoreClient {
cartId: string,
sessionId: string,
params?: CompletePaymentSessionParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<PaymentSession> =>
this.request<PaymentSession>(
'PATCH',
`/carts/${cartId}/payment_sessions/${sessionId}/complete`,
- { ...options, body: params }
+ { ...options, body: params },
),
},
@@ -609,11 +554,7 @@ export class StoreClient {
* Apply store credit to the cart
* @param cartId - Cart prefixed ID
*/
- apply: (
- cartId: string,
- amount?: number,
- options?: RequestOptions
- ): Promise<Cart> =>
+ apply: (cartId: string, amount?: number, options?: RequestOptions): Promise<Cart> =>
this.request<Cart>('POST', `/carts/${cartId}/store_credits`, {
...options,
body: amount ? { amount } : undefined,
@@ -624,13 +565,9 @@ export class StoreClient {
* @param cartId - Cart prefixed ID
*/
remove: (cartId: string, options?: RequestOptions): Promise<Cart> =>
- this.request<Cart>(
- 'DELETE',
- `/carts/${cartId}/store_credits`,
- options
- ),
+ this.request<Cart>('DELETE', `/carts/${cartId}/store_credits`, options),
},
- };
+ }
// ============================================
// Orders (post-purchase, read-only)
@@ -644,13 +581,13 @@ export class StoreClient {
get: (
id: string,
params?: { expand?: string[]; fields?: string[] },
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Order> =>
this.request<Order>('GET', `/orders/${id}`, {
...options,
params: getParams(params),
}),
- };
+ }
// ============================================
// Customer
@@ -662,7 +599,7 @@ export class StoreClient {
*/
create: (params: RegisterParams): Promise<AuthTokens> =>
this.request<AuthTokens>('POST', '/customers', { body: params }),
- };
+ }
readonly customer = {
/**
@@ -688,7 +625,7 @@ export class StoreClient {
/** Arbitrary key-value metadata (stored, not returned in responses) */
metadata?: Record<string, unknown>
},
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Customer> =>
this.request<Customer>('PATCH', '/customers/me', {
...options,
@@ -702,15 +639,11 @@ export class StoreClient {
/**
* List customer addresses
*/
- list: (
- params?: ListParams,
- options?: RequestOptions
- ): Promise<PaginatedResponse<Address>> =>
- this.request<PaginatedResponse<Address>>(
- 'GET',
- '/customers/me/addresses',
- { ...options, params: transformListParams({ ...params }) }
- ),
+ list: (params?: ListParams, options?: RequestOptions): Promise<PaginatedResponse<Address>> =>
+ this.request<PaginatedResponse<Address>>('GET', '/customers/me/addresses', {
+ ...options,
+ params: transformListParams({ ...params }),
+ }),
/**
* Get an address by ID
@@ -721,10 +654,7 @@ export class StoreClient {
/**
* Create an address
*/
- create: (
- params: AddressParams,
- options?: RequestOptions
- ): Promise<Address> =>
+ create: (params: AddressParams, options?: RequestOptions): Promise<Address> =>
this.request<Address>('POST', '/customers/me/addresses', {
...options,
body: params,
@@ -736,7 +666,7 @@ export class StoreClient {
update: (
id: string,
params: Partial<AddressParams>,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Address> =>
this.request<Address>('PATCH', `/customers/me/addresses/${id}`, {
...options,
@@ -759,13 +689,12 @@ export class StoreClient {
*/
list: (
params?: ListParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<PaginatedResponse<CreditCard>> =>
- this.request<PaginatedResponse<CreditCard>>(
- 'GET',
- '/customers/me/credit_cards',
- { ...options, params: transformListParams({ ...params }) }
- ),
+ this.request<PaginatedResponse<CreditCard>>('GET', '/customers/me/credit_cards', {
+ ...options,
+ params: transformListParams({ ...params }),
+ }),
/**
* Get a credit card by ID
@@ -788,15 +717,11 @@ export class StoreClient {
* List customer gift cards
* Returns gift cards associated with the current user, ordered by newest first
*/
- list: (
- params?: ListParams,
- options?: RequestOptions
- ): Promise<PaginatedResponse<GiftCard>> =>
- this.request<PaginatedResponse<GiftCard>>(
- 'GET',
- '/customers/me/gift_cards',
- { ...options, params: transformListParams({ ...params }) }
- ),
+ list: (params?: ListParams, options?: RequestOptions): Promise<PaginatedResponse<GiftCard>> =>
+ this.request<PaginatedResponse<GiftCard>>('GET', '/customers/me/gift_cards', {
+ ...options,
+ params: transformListParams({ ...params }),
+ }),
/**
* Get a gift card by ID
@@ -816,13 +741,12 @@ export class StoreClient {
*/
list: (
params?: ListParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<PaginatedResponse<StoreCredit>> =>
- this.request<PaginatedResponse<StoreCredit>>(
- 'GET',
- '/customers/me/store_credits',
- { ...options, params: transformListParams({ ...params }) }
- ),
+ this.request<PaginatedResponse<StoreCredit>>('GET', '/customers/me/store_credits', {
+ ...options,
+ params: transformListParams({ ...params }),
+ }),
/**
* Get a store credit by ID
@@ -840,7 +764,7 @@ export class StoreClient {
*/
list: (
params?: OrderListParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<PaginatedResponse<Order>> =>
this.request<PaginatedResponse<Order>>('GET', '/customers/me/orders', {
...options,
@@ -853,7 +777,7 @@ export class StoreClient {
get: (
id: string,
params?: { expand?: string[]; fields?: string[] },
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Order> =>
this.request<Order>('GET', `/customers/me/orders/${id}`, {
...options,
@@ -871,19 +795,22 @@ export class StoreClient {
*/
create: (
params: CreatePaymentSetupSessionParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<PaymentSetupSession> =>
- this.request<PaymentSetupSession>(
- 'POST',
- '/customers/me/payment_setup_sessions',
- { ...options, body: params }
- ),
+ this.request<PaymentSetupSession>('POST', '/customers/me/payment_setup_sessions', {
+ ...options,
+ body: params,
+ }),
/**
* Get a payment setup session by ID
*/
get: (id: string, options?: RequestOptions): Promise<PaymentSetupSession> =>
- this.request<PaymentSetupSession>('GET', `/customers/me/payment_setup_sessions/${id}`, options),
+ this.request<PaymentSetupSession>(
+ 'GET',
+ `/customers/me/payment_setup_sessions/${id}`,
+ options,
+ ),
/**
* Complete a payment setup session
@@ -892,16 +819,15 @@ export class StoreClient {
complete: (
id: string,
params?: CompletePaymentSetupSessionParams,
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<PaymentSetupSession> =>
this.request<PaymentSetupSession>(
'PATCH',
`/customers/me/payment_setup_sessions/${id}/complete`,
- { ...options, body: params }
+ { ...options, body: params },
),
},
-
- };
+ }
// ============================================
// Password Resets
@@ -922,16 +848,9 @@ export class StoreClient {
* Returns a JWT token on success (auto-login).
* @param token - Password reset token from the email
*/
- update: (
- token: string,
- params: ResetPasswordParams
- ): Promise<AuthTokens> =>
- this.request<AuthTokens>(
- 'PATCH',
- `/password_resets/${token}`,
- { body: params }
- ),
- };
+ update: (token: string, params: ResetPasswordParams): Promise<AuthTokens> =>
+ this.request<AuthTokens>('PATCH', `/password_resets/${token}`, { body: params }),
+ }
// ============================================
// Wishlists
@@ -941,10 +860,7 @@ export class StoreClient {
/**
* List wishlists
*/
- list: (
- params?: ListParams,
- options?: RequestOptions
- ): Promise<PaginatedResponse<Wishlist>> =>
+ list: (params?: ListParams, options?: RequestOptions): Promise<PaginatedResponse<Wishlist>> =>
this.request<PaginatedResponse<Wishlist>>('GET', '/wishlists', {
...options,
params: transformListParams({ ...params }),
@@ -956,7 +872,7 @@ export class StoreClient {
get: (
id: string,
params?: { expand?: string[]; fields?: string[] },
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Wishlist> =>
this.request<Wishlist>('GET', `/wishlists/${id}`, {
...options,
@@ -968,7 +884,7 @@ export class StoreClient {
*/
create: (
params: { name: string; is_private?: boolean; is_default?: boolean },
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Wishlist> =>
this.request<Wishlist>('POST', '/wishlists', {
...options,
@@ -981,7 +897,7 @@ export class StoreClient {
update: (
id: string,
params: { name?: string; is_private?: boolean; is_default?: boolean },
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<Wishlist> =>
this.request<Wishlist>('PATCH', `/wishlists/${id}`, {
...options,
@@ -1004,7 +920,7 @@ export class StoreClient {
create: (
wishlistId: string,
params: { variant_id: string; quantity?: number },
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<WishlistItem> =>
this.request<WishlistItem>('POST', `/wishlists/${wishlistId}/items`, {
...options,
@@ -1018,27 +934,18 @@ export class StoreClient {
wishlistId: string,
itemId: string,
params: { quantity: number },
- options?: RequestOptions
+ options?: RequestOptions,
): Promise<WishlistItem> =>
- this.request<WishlistItem>(
- 'PATCH',
- `/wishlists/${wishlistId}/items/${itemId}`,
- { ...options, body: params }
- ),
+ this.request<WishlistItem>('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
- ),
+ delete: (wishlistId: string, itemId: string, options?: RequestOptions): Promise<void> =>
+ this.request<void>('DELETE', `/wishlists/${wishlistId}/items/${itemId}`, options),
},
- };
+ }
}
diff --git a/packages/sdk/src/types/index.ts b/packages/sdk/src/types/index.ts
index 06d9cd4e47..3d561252cb 100644
--- a/packages/sdk/src/types/index.ts
+++ b/packages/sdk/src/types/index.ts
@@ -1,5 +1,5 @@
-import type { ListParams, AddressParams } from '@spree/sdk-core';
-import type { Cart as CartType } from './generated';
+import type { AddressParams, ListParams } from '@spree/sdk-core'
+import type { Cart as CartType } from './generated'
// Re-export all generated types (unprefixed: Product, Order, etc.)
export type {
@@ -11,23 +11,26 @@ export type {
CreditCard,
Currency,
Customer,
- DigitalLink,
+ CustomField,
+ DeliveryMethod,
+ DeliveryRate,
Digital,
+ DigitalLink,
Discount,
- GiftCardBatch,
+ Fulfillment,
GiftCard,
- Media,
+ GiftCardBatch,
Invitation,
LineItem,
Locale,
Market,
- CustomField,
+ Media,
NewsletterSubscriber,
OptionType,
OptionValue,
Order,
- PaymentMethod,
Payment,
+ PaymentMethod,
PaymentSession,
PaymentSetupSession,
PaymentSource,
@@ -38,278 +41,275 @@ export type {
Refund,
ReturnAuthorization,
ReturnItem,
- DeliveryMethod,
- DeliveryRate,
- Fulfillment,
State,
StockLocation,
StoreCredit,
Variant,
- WishlistItem,
Wishlist,
-} from './generated';
+ WishlistItem,
+} from './generated'
// Checkout requirement — a single unsatisfied checkout prerequisite
export interface CheckoutRequirement {
/** Checkout step this requirement belongs to (e.g. "address", "payment") */
- step: string;
+ step: string
/** Field that needs to be satisfied (e.g. "email", "shipping_address") */
- field: string;
+ field: string
/** Human-readable message describing what's needed */
- message: string;
+ message: string
}
// Cart warning type — convenience alias for the inline type from the generated Cart
-export type CartWarning = CartType['warnings'][number];
+export type CartWarning = CartType['warnings'][number]
// Hand-written domain types
export type {
- LocaleDefaults,
- PaginationMeta,
- ListResponse,
- PaginatedResponse,
+ AddressParams,
ErrorResponse,
ListParams,
- AddressParams,
-} from '@spree/sdk-core';
+ ListResponse,
+ LocaleDefaults,
+ PaginatedResponse,
+ PaginationMeta,
+} from '@spree/sdk-core'
// Store auth types
export interface AuthTokens {
- token: string;
- refresh_token: string;
+ token: string
+ refresh_token: string
user: {
- id: string;
- email: string;
- first_name: string | null;
- last_name: string | null;
- };
+ id: string
+ email: string
+ first_name: string | null
+ last_name: string | null
+ }
}
export interface LoginCredentials {
- email: string;
- password: string;
+ email: string
+ password: string
}
export interface RequestPasswordResetParams {
- email: string;
- redirect_url?: string;
+ email: string
+ redirect_url?: string
}
export interface ResetPasswordParams {
- password: string;
- password_confirmation: string;
+ password: string
+ password_confirmation: string
}
export interface RegisterParams {
- email: string;
- password: string;
- password_confirmation: string;
- first_name?: string;
- last_name?: string;
- phone?: string;
- accepts_email_marketing?: boolean;
+ email: string
+ password: string
+ password_confirmation: string
+ first_name?: string
+ last_name?: string
+ phone?: string
+ accepts_email_marketing?: boolean
/** Arbitrary key-value metadata (stored, not returned in responses) */
- metadata?: Record<string, unknown>;
+ metadata?: Record<string, unknown>
}
export interface ProductListParams extends ListParams {
/** Sort: 'price', '-price', 'best_selling', 'name', '-name', '-available_on', 'available_on' */
- sort?: string;
+ sort?: string
/** Full-text search across name and SKU */
- search?: string;
+ search?: string
/** Filter: name contains */
- name_cont?: string;
+ name_cont?: string
/** Filter: price >= value */
- price_gte?: number;
+ price_gte?: number
/** Filter: price <= value */
- price_lte?: number;
+ price_lte?: number
/** Filter by option value prefix IDs */
- with_option_value_ids?: string[];
+ with_option_value_ids?: string[]
/** Filter: only in-stock products */
- in_stock?: boolean;
+ in_stock?: boolean
/** Filter: only out-of-stock products */
- out_of_stock?: boolean;
+ out_of_stock?: boolean
/** Filter: products in category (includes descendants) */
- in_category?: string;
+ in_category?: string
/** Filter: products in any of the given categories (includes descendants, OR logic) */
- in_categories?: string[];
+ in_categories?: string[]
/** Any additional Ransack predicate */
- [key: string]: string | number | boolean | (string | number)[] | undefined;
+ [key: string]: string | number | boolean | (string | number)[] | undefined
}
export interface CategoryListParams extends ListParams {
/** Sort order, e.g. 'name', '-created_at' */
- sort?: string;
+ sort?: string
/** Filter: name contains */
- name_cont?: string;
- parent_id_eq?: string | number;
- depth_eq?: number;
+ name_cont?: string
+ parent_id_eq?: string | number
+ depth_eq?: number
/** Any additional Ransack predicate */
- [key: string]: string | number | boolean | (string | number)[] | undefined;
+ [key: string]: string | number | boolean | (string | number)[] | undefined
}
export interface OrderListParams extends ListParams {
/** Sort order, e.g. 'completed_at desc' */
- sort?: string;
+ sort?: string
/** Full-text search across number, email, customer name */
- search?: string;
- state_eq?: string;
- completed_at_gte?: string;
- completed_at_lte?: string;
+ search?: string
+ state_eq?: string
+ completed_at_gte?: string
+ completed_at_lte?: string
/** Any additional Ransack predicate */
- [key: string]: string | number | boolean | (string | number)[] | undefined;
+ [key: string]: string | number | boolean | (string | number)[] | undefined
}
// Line item input for bulk cart/order operations
export interface LineItemInput {
/** Prefixed variant ID (e.g., "variant_k5nR8xLq") */
- variant_id: string;
+ variant_id: string
/** Quantity to set (defaults to 1 if omitted) */
- quantity?: number;
+ quantity?: number
/** Arbitrary key-value metadata (merged with existing on upsert) */
- metadata?: Record<string, unknown>;
+ metadata?: Record<string, unknown>
}
// Cart operations
export interface CreateCartParams {
/** Arbitrary key-value metadata (stored, not returned in responses) */
- metadata?: Record<string, unknown>;
+ metadata?: Record<string, unknown>
/** Items to add to the cart on creation */
- items?: LineItemInput[];
+ items?: LineItemInput[]
}
export interface AddLineItemParams {
- variant_id: string;
- quantity: number;
+ variant_id: string
+ quantity: number
/** Arbitrary key-value metadata (stored, not returned in responses) */
- metadata?: Record<string, unknown>;
+ metadata?: Record<string, unknown>
}
export interface UpdateLineItemParams {
- quantity?: number;
+ quantity?: number
/** Arbitrary key-value metadata (merged with existing) */
- metadata?: Record<string, unknown>;
+ metadata?: Record<string, unknown>
}
export interface UpdateCartParams {
- email?: string;
- currency?: string;
- locale?: string;
- customer_note?: string;
+ email?: string
+ currency?: string
+ locale?: string
+ customer_note?: string
/** Arbitrary key-value metadata (merged with existing) */
- metadata?: Record<string, unknown>;
+ metadata?: Record<string, unknown>
/** Existing address ID to use as billing address */
- billing_address_id?: string;
+ billing_address_id?: string
/** Existing address ID to use as shipping address */
- shipping_address_id?: string;
+ shipping_address_id?: string
/** New billing address */
- billing_address?: AddressParams;
+ billing_address?: AddressParams
/** New shipping address */
- shipping_address?: AddressParams;
+ shipping_address?: AddressParams
/** When true, copies shipping address to billing address */
- use_shipping?: boolean;
+ use_shipping?: boolean
/** Items to upsert (sets quantity for existing, creates new) */
- items?: LineItemInput[];
+ items?: LineItemInput[]
}
// Payments
export interface CreatePaymentParams {
- payment_method_id: string;
- amount?: string;
- metadata?: Record<string, unknown>;
+ payment_method_id: string
+ amount?: string
+ metadata?: Record<string, unknown>
}
// Payment Sessions
export interface CreatePaymentSessionParams {
- payment_method_id: string;
- amount?: string;
- external_data?: Record<string, unknown>;
+ payment_method_id: string
+ amount?: string
+ external_data?: Record<string, unknown>
}
export interface UpdatePaymentSessionParams {
- amount?: string;
- external_data?: Record<string, unknown>;
+ amount?: string
+ external_data?: Record<string, unknown>
}
export interface CompletePaymentSessionParams {
- session_result?: string;
- external_data?: Record<string, unknown>;
+ session_result?: string
+ external_data?: Record<string, unknown>
}
// Payment Setup Sessions
export interface CreatePaymentSetupSessionParams {
- payment_method_id: string;
- external_data?: Record<string, unknown>;
+ payment_method_id: string
+ external_data?: Record<string, unknown>
}
export interface CompletePaymentSetupSessionParams {
- external_data?: Record<string, unknown>;
+ external_data?: Record<string, unknown>
}
// Product Filters types
export interface FilterOption {
- id: string;
- count: number;
+ id: string
+ count: number
}
export interface OptionFilterOption extends FilterOption {
- name: string;
- label: string;
- position: number;
- color_code: string | null;
- image_url: string | null;
+ name: string
+ label: string
+ position: number
+ color_code: string | null
+ image_url: string | null
}
export interface CategoryFilterOption {
- id: string;
- name: string;
- permalink: string;
- count: number;
+ id: string
+ name: string
+ permalink: string
+ count: number
}
export interface PriceRangeFilter {
- id: 'price';
- type: 'price_range';
- min: number;
- max: number;
- currency: string;
+ id: 'price'
+ type: 'price_range'
+ min: number
+ max: number
+ currency: string
}
export interface AvailabilityFilter {
- id: 'availability';
- type: 'availability';
- options: FilterOption[];
+ id: 'availability'
+ type: 'availability'
+ options: FilterOption[]
}
export interface OptionFilter {
- id: string;
- type: 'option';
- name: string;
- label: string;
- kind: string;
- options: OptionFilterOption[];
+ id: string
+ type: 'option'
+ name: string
+ label: string
+ kind: string
+ options: OptionFilterOption[]
}
export interface CategoryFilter {
- id: 'categories';
- type: 'category';
- options: CategoryFilterOption[];
+ id: 'categories'
+ type: 'category'
+ options: CategoryFilterOption[]
}
-export type ProductFilter = PriceRangeFilter | AvailabilityFilter | OptionFilter | CategoryFilter;
+export type ProductFilter = PriceRangeFilter | AvailabilityFilter | OptionFilter | CategoryFilter
export interface SortOption {
- id: string;
+ id: string
}
export interface ProductFiltersResponse {
- filters: ProductFilter[];
- sort_options: SortOption[];
- default_sort: string;
- total_count: number;
+ filters: ProductFilter[]
+ sort_options: SortOption[]
+ default_sort: string
+ total_count: number
}
export interface ProductFiltersParams {
- category_id?: string;
- q?: Record<string, unknown>;
+ category_id?: string
+ q?: Record<string, unknown>
}
diff --git a/packages/sdk/src/webhooks.ts b/packages/sdk/src/webhooks.ts
index 5a88efd153..990157eb78 100644
--- a/packages/sdk/src/webhooks.ts
+++ b/packages/sdk/src/webhooks.ts
@@ -39,9 +39,7 @@ export function verifyWebhookSignature(
const age = Math.abs(Math.floor(Date.now() / 1000) - ts)
if (age > toleranceSeconds) return false
- const expected = createHmac('sha256', secret)
- .update(`${timestamp}.${payload}`)
- .digest('hex')
+ const expected = createHmac('sha256', secret).update(`${timestamp}.${payload}`).digest('hex')
try {
return timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
diff --git a/packages/sdk/src/zod/index.ts b/packages/sdk/src/zod/index.ts
index 69e4e4eb8b..99735f6415 100644
--- a/packages/sdk/src/zod/index.ts
+++ b/packages/sdk/src/zod/index.ts
@@ -1 +1 @@
-export * from './generated';
+export * from './generated'
diff --git a/packages/sdk/tests/auth.test.ts b/packages/sdk/tests/auth.test.ts
index ef751b6b85..d301843007 100644
--- a/packages/sdk/tests/auth.test.ts
+++ b/packages/sdk/tests/auth.test.ts
@@ -1,65 +1,68 @@
-import { describe, it, expect } from 'vitest';
-import { server } from './mocks/server';
-import { http, HttpResponse } from 'msw';
-import { createTestClient, TEST_BASE_URL } from './helpers';
+import { HttpResponse, http } from 'msw'
+import { describe, expect, it } from 'vitest'
+import { createTestClient, TEST_BASE_URL } from './helpers'
+import { server } from './mocks/server'
-const API_PREFIX = `${TEST_BASE_URL}/api/v3/store`;
+const API_PREFIX = `${TEST_BASE_URL}/api/v3/store`
describe('auth', () => {
describe('login', () => {
it('returns auth tokens on successful login', async () => {
- const client = createTestClient();
+ const client = createTestClient()
const result = await client.auth.login({
password: 'password123',
- });
+ })
- expect(result.token).toBe('test-jwt-token');
- expect(result.user.email).toBe('[email protected]');
- });
+ expect(result.token).toBe('test-jwt-token')
+ expect(result.user.email).toBe('[email protected]')
+ })
it('throws SpreeError on invalid credentials', async () => {
server.use(
http.post(`${API_PREFIX}/auth/login`, () =>
HttpResponse.json(
{ error: { code: 'unauthorized', message: 'Invalid credentials' } },
- { status: 401 }
- )
- )
- );
+ { status: 401 },
+ ),
+ ),
+ )
- const client = createTestClient();
+ const client = createTestClient()
await expect(
- client.auth.login({ email: '[email protected]', password: 'wrong' })
- ).rejects.toThrow('Invalid credentials');
- });
- });
+ client.auth.login({ email: '[email protected]', password: 'wrong' }),
+ ).rejects.toThrow('Invalid credentials')
+ })
+ })
describe('register (via customers.create)', () => {
it('returns auth tokens on successful registration', async () => {
- const client = createTestClient();
+ const client = createTestClient()
const result = await client.customers.create({
password: 'password123',
password_confirmation: 'password123',
first_name: 'New',
last_name: 'User',
- });
+ })
- expect(result.token).toBeDefined();
- expect(result.user).toBeDefined();
- });
+ expect(result.token).toBeDefined()
+ expect(result.user).toBeDefined()
+ })
it('sends phone, accepts_email_marketing, and metadata', async () => {
- let capturedBody: Record<string, unknown> = {};
+ let capturedBody: Record<string, unknown> = {}
server.use(
http.post(`${API_PREFIX}/customers`, async ({ request }) => {
- capturedBody = await request.json() as Record<string, unknown>;
- return HttpResponse.json({ token: 'test-jwt-token', user: { id: 'user_1', email: '[email protected]', first_name: null, last_name: null } });
- })
- );
+ capturedBody = (await request.json()) as Record<string, unknown>
+ return HttpResponse.json({
+ token: 'test-jwt-token',
+ user: { id: 'user_1', email: '[email protected]', first_name: null, last_name: null },
+ })
+ }),
+ )
- const client = createTestClient();
+ const client = createTestClient()
await client.customers.create({
password: 'password123',
@@ -67,12 +70,12 @@ describe('auth', () => {
phone: '+1234567890',
accepts_email_marketing: true,
metadata: { source: 'storefront' },
- });
+ })
- expect(capturedBody.phone).toBe('+1234567890');
- expect(capturedBody.accepts_email_marketing).toBe(true);
- expect(capturedBody.metadata).toEqual({ source: 'storefront' });
- });
+ expect(capturedBody.phone).toBe('+1234567890')
+ expect(capturedBody.accepts_email_marketing).toBe(true)
+ expect(capturedBody.metadata).toEqual({ source: 'storefront' })
+ })
it('throws SpreeError on validation failure', async () => {
server.use(
@@ -85,42 +88,42 @@ describe('auth', () => {
details: { email: ['has already been taken'] },
},
},
- { status: 422 }
- )
- )
- );
+ { status: 422 },
+ ),
+ ),
+ )
- const client = createTestClient();
+ const client = createTestClient()
try {
await client.customers.create({
password: 'password123',
password_confirmation: 'password123',
- });
- expect.unreachable('Should have thrown');
+ })
+ expect.unreachable('Should have thrown')
} catch (error: any) {
- expect(error.code).toBe('unprocessable_entity');
- expect(error.status).toBe(422);
- expect(error.details?.email).toContain('has already been taken');
+ expect(error.code).toBe('unprocessable_entity')
+ expect(error.status).toBe(422)
+ expect(error.details?.email).toContain('has already been taken')
}
- });
- });
+ })
+ })
describe('refresh', () => {
it('returns new access token and rotated refresh token', async () => {
- const client = createTestClient();
- const result = await client.auth.refresh({ refresh_token: 'rt_old' });
+ const client = createTestClient()
+ const result = await client.auth.refresh({ refresh_token: 'rt_old' })
- expect(result.token).toBe('refreshed-jwt-token');
- expect(result.refresh_token).toBe('rt_refreshed');
- });
- });
+ expect(result.token).toBe('refreshed-jwt-token')
+ expect(result.refresh_token).toBe('rt_refreshed')
+ })
+ })
describe('logout', () => {
it('revokes the refresh token', async () => {
- const client = createTestClient();
- await client.auth.logout({ refresh_token: 'rt_login' });
+ const client = createTestClient()
+ await client.auth.logout({ refresh_token: 'rt_login' })
// 204 No Content — no error means success
- });
- });
-});
+ })
+ })
+})
diff --git a/packages/sdk/tests/cart.test.ts b/packages/sdk/tests/cart.test.ts
index 6972b0a10a..896c73b5c5 100644
--- a/packages/sdk/tests/cart.test.ts
+++ b/packages/sdk/tests/cart.test.ts
@@ -1,128 +1,121 @@
-import { describe, it, expect, beforeAll } from 'vitest';
-import { createTestClient } from './helpers';
-import type { Client } from '../src';
+import { beforeAll, describe, expect, it } from 'vitest'
+import type { Client } from '../src'
+import { createTestClient } from './helpers'
describe('carts', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
- const opts = { token: 'user-jwt' };
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
+ const opts = { token: 'user-jwt' }
describe('list', () => {
it('lists all active carts for authenticated user', async () => {
- const result = await client.carts.list({ token: 'user-jwt' });
- expect(result.data).toHaveLength(1);
- expect(result.data[0].id).toBe('cart_1');
- expect(result.meta.count).toBe(1);
- });
- });
+ const result = await client.carts.list({ token: 'user-jwt' })
+ expect(result.data).toHaveLength(1)
+ expect(result.data[0].id).toBe('cart_1')
+ expect(result.meta.count).toBe(1)
+ })
+ })
describe('get', () => {
it('returns a cart by ID', async () => {
- const result = await client.carts.get('cart_1', opts);
+ const result = await client.carts.get('cart_1', opts)
- expect(result.id).toBe('cart_1');
- expect(result.token).toBeDefined();
- expect(result.state).toBeDefined();
- expect(result.checkout_steps).toBeDefined();
- });
+ expect(result.id).toBe('cart_1')
+ expect(result.token).toBeDefined()
+ expect(result.state).toBeDefined()
+ expect(result.checkout_steps).toBeDefined()
+ })
it('works with spreeToken for guest checkout', async () => {
- const result = await client.carts.get('cart_1', { spreeToken: 'guest-token' });
- expect(result).toBeDefined();
- });
- });
+ const result = await client.carts.get('cart_1', { spreeToken: 'guest-token' })
+ expect(result).toBeDefined()
+ })
+ })
describe('create', () => {
it('creates a new cart', async () => {
- const result = await client.carts.create();
- expect(result.token).toBe('new-cart-token');
- });
- });
+ const result = await client.carts.create()
+ expect(result.token).toBe('new-cart-token')
+ })
+ })
describe('update', () => {
it('updates cart info', async () => {
- const result = await client.carts.update(
- 'cart_1',
- { email: '[email protected]' },
- opts
- );
- expect(result.id).toBe('cart_1');
- });
- });
+ const result = await client.carts.update('cart_1', { email: '[email protected]' }, opts)
+ expect(result.id).toBe('cart_1')
+ })
+ })
describe('delete', () => {
it('deletes a cart by ID', async () => {
- await expect(client.carts.delete('cart_1', opts)).resolves.toBeUndefined();
- });
- });
+ await expect(client.carts.delete('cart_1', opts)).resolves.toBeUndefined()
+ })
+ })
describe('associate', () => {
it('associates guest cart with authenticated user', async () => {
const result = await client.carts.associate('cart_1', {
token: 'user-jwt',
spreeToken: 'guest-token',
- });
- expect(result).toBeDefined();
- });
- });
+ })
+ expect(result).toBeDefined()
+ })
+ })
describe('complete', () => {
it('completes the cart and returns an order', async () => {
- const result = await client.carts.complete('cart_1', opts);
- expect(result.id).toBe('or_1');
- expect(result.completed_at).toBeDefined();
- });
- });
+ const result = await client.carts.complete('cart_1', opts)
+ expect(result.id).toBe('or_1')
+ expect(result.completed_at).toBeDefined()
+ })
+ })
describe('items', () => {
it('adds an item to the cart', async () => {
const result = await client.carts.items.create(
'cart_1',
{ variant_id: 'var_1', quantity: 2 },
- opts
- );
- expect(result.id).toBe('cart_1');
- });
+ opts,
+ )
+ expect(result.id).toBe('cart_1')
+ })
it('updates a line item', async () => {
- const result = await client.carts.items.update(
- 'cart_1',
- 'li_1',
- { quantity: 5 },
- opts
- );
- expect(result.id).toBe('cart_1');
- });
+ const result = await client.carts.items.update('cart_1', 'li_1', { quantity: 5 }, opts)
+ expect(result.id).toBe('cart_1')
+ })
it('removes a line item', async () => {
- const result = await client.carts.items.delete('cart_1', 'li_1', opts);
- expect(result.id).toBe('cart_1');
- });
- });
+ const result = await client.carts.items.delete('cart_1', 'li_1', opts)
+ expect(result.id).toBe('cart_1')
+ })
+ })
describe('discountCodes', () => {
it('applies a discount code', async () => {
- const result = await client.carts.discountCodes.apply('cart_1', 'SAVE10', opts);
- expect(result.id).toBe('cart_1');
- });
+ const result = await client.carts.discountCodes.apply('cart_1', 'SAVE10', opts)
+ expect(result.id).toBe('cart_1')
+ })
it('removes a discount code by code string', async () => {
- const result = await client.carts.discountCodes.remove('cart_1', 'SAVE10', opts);
- expect(result.id).toBe('cart_1');
- });
- });
+ const result = await client.carts.discountCodes.remove('cart_1', 'SAVE10', opts)
+ expect(result.id).toBe('cart_1')
+ })
+ })
describe('giftCards', () => {
it('applies a gift card', async () => {
- const result = await client.carts.giftCards.apply('cart_1', 'GC-ABCD-1234', opts);
- expect(result.id).toBe('cart_1');
- });
+ const result = await client.carts.giftCards.apply('cart_1', 'GC-ABCD-1234', opts)
+ expect(result.id).toBe('cart_1')
+ })
it('removes a gift card by prefixed ID', async () => {
- const result = await client.carts.giftCards.remove('cart_1', 'gc_abc123', opts);
- expect(result.id).toBe('cart_1');
- });
- });
+ const result = await client.carts.giftCards.remove('cart_1', 'gc_abc123', opts)
+ expect(result.id).toBe('cart_1')
+ })
+ })
describe('fulfillments', () => {
it('selects a delivery rate', async () => {
@@ -130,21 +123,21 @@ describe('carts', () => {
'cart_1',
'ful_1',
{ selected_delivery_rate_id: 'rate_1' },
- opts
- );
- expect(result.id).toBe('cart_1');
- });
- });
+ opts,
+ )
+ expect(result.id).toBe('cart_1')
+ })
+ })
describe('storeCredits', () => {
it('applies store credit', async () => {
- const result = await client.carts.storeCredits.apply('cart_1', 10, opts);
- expect(result.id).toBe('cart_1');
- });
+ const result = await client.carts.storeCredits.apply('cart_1', 10, opts)
+ expect(result.id).toBe('cart_1')
+ })
it('removes store credit', async () => {
- const result = await client.carts.storeCredits.remove('cart_1', opts);
- expect(result.id).toBe('cart_1');
- });
- });
-});
+ const result = await client.carts.storeCredits.remove('cart_1', opts)
+ expect(result.id).toBe('cart_1')
+ })
+ })
+})
diff --git a/packages/sdk/tests/categories.test.ts b/packages/sdk/tests/categories.test.ts
index 1f4d553d79..808631bdad 100644
--- a/packages/sdk/tests/categories.test.ts
+++ b/packages/sdk/tests/categories.test.ts
@@ -1,27 +1,28 @@
-import { describe, it, expect, beforeAll } from 'vitest';
-import { createTestClient } from './helpers';
-import { fixtures } from './mocks/handlers';
-import type { Client } from '../src';
+import { beforeAll, describe, expect, it } from 'vitest'
+import type { Client } from '../src'
+import { createTestClient } from './helpers'
+import { fixtures } from './mocks/handlers'
describe('categories', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
describe('list', () => {
it('returns paginated categories', async () => {
- const result = await client.categories.list();
+ const result = await client.categories.list()
- expect(result.data).toHaveLength(1);
- expect(result.data[0].name).toBe('Clothing');
- expect(result.meta.page).toBe(1);
- });
- });
+ expect(result.data).toHaveLength(1)
+ expect(result.data[0].name).toBe('Clothing')
+ expect(result.meta.page).toBe(1)
+ })
+ })
describe('get', () => {
it('returns a category by ID', async () => {
- const result = await client.categories.get('ctg_1');
- expect(result.name).toBe(fixtures.category.name);
- });
- });
-
-});
+ const result = await client.categories.get('ctg_1')
+ expect(result.name).toBe(fixtures.category.name)
+ })
+ })
+})
diff --git a/packages/sdk/tests/client.test.ts b/packages/sdk/tests/client.test.ts
index 07b19f8f8c..c783454e5b 100644
--- a/packages/sdk/tests/client.test.ts
+++ b/packages/sdk/tests/client.test.ts
@@ -1,141 +1,205 @@
-import { describe, it, expect } from 'vitest';
-import { createClient } from '../src';
-import { TEST_BASE_URL, TEST_API_KEY } from './helpers';
+import { describe, expect, it } from 'vitest'
+import { createClient } from '../src'
+import { TEST_API_KEY, TEST_BASE_URL } from './helpers'
describe('createClient', () => {
it('creates a client via factory function', () => {
const client = createClient({
baseUrl: TEST_BASE_URL,
publishableKey: TEST_API_KEY,
- });
- expect(client).toBeDefined();
- expect(client.products).toBeDefined();
- });
+ })
+ expect(client).toBeDefined()
+ expect(client.products).toBeDefined()
+ })
it('strips trailing slash from baseUrl', async () => {
const client = createClient({
baseUrl: `${TEST_BASE_URL}/`,
publishableKey: TEST_API_KEY,
- });
- const result = await client.products.list();
- expect(result.data).toBeDefined();
- });
+ })
+ const result = await client.products.list()
+ expect(result.data).toBeDefined()
+ })
it('accepts a custom fetch implementation', async () => {
- let capturedUrl = '';
+ let capturedUrl = ''
const customFetch = async (input: string | URL | Request, _init?: RequestInit) => {
- capturedUrl = input.toString();
- return new Response(JSON.stringify({ data: [], meta: { page: 1, limit: 25, count: 0, pages: 0, from: 0, to: 0, in: 0, previous: null, next: null } }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- });
- };
+ capturedUrl = input.toString()
+ return new Response(
+ JSON.stringify({
+ data: [],
+ meta: {
+ page: 1,
+ limit: 25,
+ count: 0,
+ pages: 0,
+ from: 0,
+ to: 0,
+ in: 0,
+ previous: null,
+ next: null,
+ },
+ }),
+ {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ )
+ }
const client = createClient({
baseUrl: TEST_BASE_URL,
publishableKey: TEST_API_KEY,
fetch: customFetch,
- });
+ })
- await client.products.list();
- expect(capturedUrl).toContain('/api/v3/store/products');
- });
+ await client.products.list()
+ expect(capturedUrl).toContain('/api/v3/store/products')
+ })
it('sends x-spree-api-key header on every request', async () => {
- let capturedHeaders: Record<string, string> = {};
+ let capturedHeaders: Record<string, string> = {}
const customFetch = async (_input: string | URL | Request, init?: RequestInit) => {
capturedHeaders = Object.fromEntries(
- Object.entries(init?.headers as Record<string, string> || {})
- );
- return new Response(JSON.stringify({ data: [], meta: { page: 1, limit: 25, count: 0, pages: 0, from: 0, to: 0, in: 0, previous: null, next: null } }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- });
- };
+ Object.entries((init?.headers as Record<string, string>) || {}),
+ )
+ return new Response(
+ JSON.stringify({
+ data: [],
+ meta: {
+ page: 1,
+ limit: 25,
+ count: 0,
+ pages: 0,
+ from: 0,
+ to: 0,
+ in: 0,
+ previous: null,
+ next: null,
+ },
+ }),
+ {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ )
+ }
const client = createClient({
baseUrl: TEST_BASE_URL,
publishableKey: 'my-secret-key',
fetch: customFetch,
- });
+ })
- await client.products.list();
- expect(capturedHeaders['x-spree-api-key']).toBe('my-secret-key');
- });
+ await client.products.list()
+ expect(capturedHeaders['x-spree-api-key']).toBe('my-secret-key')
+ })
it('sends Authorization header when token is provided', async () => {
- let capturedHeaders: Record<string, string> = {};
+ let capturedHeaders: Record<string, string> = {}
const customFetch = async (_input: string | URL | Request, init?: RequestInit) => {
capturedHeaders = Object.fromEntries(
- Object.entries(init?.headers as Record<string, string> || {})
- );
- return new Response(JSON.stringify({ data: [], meta: { page: 1, limit: 25, count: 0, pages: 0, from: 0, to: 0, in: 0, previous: null, next: null } }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- });
- };
+ Object.entries((init?.headers as Record<string, string>) || {}),
+ )
+ return new Response(
+ JSON.stringify({
+ data: [],
+ meta: {
+ page: 1,
+ limit: 25,
+ count: 0,
+ pages: 0,
+ from: 0,
+ to: 0,
+ in: 0,
+ previous: null,
+ next: null,
+ },
+ }),
+ {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ )
+ }
const client = createClient({
baseUrl: TEST_BASE_URL,
publishableKey: TEST_API_KEY,
fetch: customFetch,
- });
+ })
- await client.products.list({}, { token: 'my-jwt-token' });
- expect(capturedHeaders['Authorization']).toBe('Bearer my-jwt-token');
- });
+ await client.products.list({}, { token: 'my-jwt-token' })
+ expect(capturedHeaders.Authorization).toBe('Bearer my-jwt-token')
+ })
it('sends locale and currency headers when provided', async () => {
- let capturedHeaders: Record<string, string> = {};
+ let capturedHeaders: Record<string, string> = {}
const customFetch = async (_input: string | URL | Request, init?: RequestInit) => {
capturedHeaders = Object.fromEntries(
- Object.entries(init?.headers as Record<string, string> || {})
- );
- return new Response(JSON.stringify({ data: [], meta: { page: 1, limit: 25, count: 0, pages: 0, from: 0, to: 0, in: 0, previous: null, next: null } }), {
- status: 200,
- headers: { 'Content-Type': 'application/json' },
- });
- };
+ Object.entries((init?.headers as Record<string, string>) || {}),
+ )
+ return new Response(
+ JSON.stringify({
+ data: [],
+ meta: {
+ page: 1,
+ limit: 25,
+ count: 0,
+ pages: 0,
+ from: 0,
+ to: 0,
+ in: 0,
+ previous: null,
+ next: null,
+ },
+ }),
+ {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ )
+ }
const client = createClient({
baseUrl: TEST_BASE_URL,
publishableKey: TEST_API_KEY,
fetch: customFetch,
- });
+ })
- await client.products.list({}, { locale: 'fr', currency: 'EUR' });
- expect(capturedHeaders['x-spree-locale']).toBe('fr');
- expect(capturedHeaders['x-spree-currency']).toBe('EUR');
- });
+ await client.products.list({}, { locale: 'fr', currency: 'EUR' })
+ expect(capturedHeaders['x-spree-locale']).toBe('fr')
+ expect(capturedHeaders['x-spree-currency']).toBe('EUR')
+ })
it('exposes all resource namespaces directly', () => {
const client = createClient({
baseUrl: TEST_BASE_URL,
publishableKey: TEST_API_KEY,
- });
-
- expect(client.auth).toBeDefined();
- expect(client.products).toBeDefined();
- expect(client.categories).toBeDefined();
- expect(client.countries).toBeDefined();
- expect(client.currencies).toBeDefined();
- expect(client.locales).toBeDefined();
- expect(client.carts).toBeDefined();
- expect(client.orders).toBeDefined();
- expect(client.customer).toBeDefined();
- expect(client.wishlists).toBeDefined();
- });
+ })
+
+ expect(client.auth).toBeDefined()
+ expect(client.products).toBeDefined()
+ expect(client.categories).toBeDefined()
+ expect(client.countries).toBeDefined()
+ expect(client.currencies).toBeDefined()
+ expect(client.locales).toBeDefined()
+ expect(client.carts).toBeDefined()
+ expect(client.orders).toBeDefined()
+ expect(client.customer).toBeDefined()
+ expect(client.wishlists).toBeDefined()
+ })
it('supports setLocale, setCurrency, setCountry', () => {
const client = createClient({
baseUrl: TEST_BASE_URL,
publishableKey: TEST_API_KEY,
- });
+ })
expect(() => {
- client.setLocale('fr');
- client.setCurrency('EUR');
- client.setCountry('FR');
- }).not.toThrow();
- });
-});
+ client.setLocale('fr')
+ client.setCurrency('EUR')
+ client.setCountry('FR')
+ }).not.toThrow()
+ })
+})
diff --git a/packages/sdk/tests/customer.test.ts b/packages/sdk/tests/customer.test.ts
index a1fd2d2021..1f473a5052 100644
--- a/packages/sdk/tests/customer.test.ts
+++ b/packages/sdk/tests/customer.test.ts
@@ -1,65 +1,68 @@
-import { describe, it, expect, beforeAll } from 'vitest';
-import { http, HttpResponse } from 'msw';
-import { server } from './mocks/server';
-import { createTestClient, TEST_BASE_URL } from './helpers';
-import { fixtures } from './mocks/handlers';
-import type { Client } from '../src';
+import { HttpResponse, http } from 'msw'
+import { beforeAll, describe, expect, it } from 'vitest'
+import type { Client } from '../src'
+import { createTestClient, TEST_BASE_URL } from './helpers'
+import { fixtures } from './mocks/handlers'
+import { server } from './mocks/server'
-const API_PREFIX = `${TEST_BASE_URL}/api/v3/store`;
+const API_PREFIX = `${TEST_BASE_URL}/api/v3/store`
describe('customer', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
- const opts = { token: 'user-jwt' };
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
+ const opts = { token: 'user-jwt' }
describe('get', () => {
it('returns customer profile', async () => {
- const result = await client.customer.get(opts);
- expect(result.email).toBe('[email protected]');
- });
- });
+ const result = await client.customer.get(opts)
+ expect(result.email).toBe('[email protected]')
+ })
+ })
describe('update', () => {
it('updates customer profile', async () => {
- const result = await client.customer.update(
- { first_name: 'Updated' },
- opts
- );
- expect(result.first_name).toBe('Updated');
- });
+ const result = await client.customer.update({ first_name: 'Updated' }, opts)
+ expect(result.first_name).toBe('Updated')
+ })
it('sends phone, accepts_email_marketing, and metadata', async () => {
- let capturedBody: Record<string, unknown> = {};
+ let capturedBody: Record<string, unknown> = {}
server.use(
http.patch(`${API_PREFIX}/customers/me`, async ({ request }) => {
- capturedBody = await request.json() as Record<string, unknown>;
- return HttpResponse.json({ ...fixtures.user, phone: '+1234567890', accepts_email_marketing: true });
- })
- );
+ capturedBody = (await request.json()) as Record<string, unknown>
+ return HttpResponse.json({
+ ...fixtures.user,
+ phone: '+1234567890',
+ accepts_email_marketing: true,
+ })
+ }),
+ )
const result = await client.customer.update(
{ phone: '+1234567890', accepts_email_marketing: true, metadata: { source: 'app' } },
- opts
- );
+ opts,
+ )
- expect(capturedBody.phone).toBe('+1234567890');
- expect(capturedBody.accepts_email_marketing).toBe(true);
- expect(capturedBody.metadata).toEqual({ source: 'app' });
- expect(result.phone).toBe('+1234567890');
- expect(result.accepts_email_marketing).toBe(true);
- });
- });
+ expect(capturedBody.phone).toBe('+1234567890')
+ expect(capturedBody.accepts_email_marketing).toBe(true)
+ expect(capturedBody.metadata).toEqual({ source: 'app' })
+ expect(result.phone).toBe('+1234567890')
+ expect(result.accepts_email_marketing).toBe(true)
+ })
+ })
describe('addresses', () => {
it('lists addresses', async () => {
- const result = await client.customer.addresses.list(undefined, opts);
- expect(result.data).toHaveLength(1);
- });
+ const result = await client.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);
- expect(result.city).toBe('New York');
- });
+ const result = await client.customer.addresses.get('addr_1', opts)
+ expect(result.city).toBe('New York')
+ })
it('creates an address', async () => {
const result = await client.customer.addresses.create(
@@ -71,84 +74,80 @@ describe('customer', () => {
postal_code: '10001',
country_iso: 'US',
},
- opts
- );
- expect(result.id).toBeDefined();
- });
+ opts,
+ )
+ expect(result.id).toBeDefined()
+ })
it('updates an address', async () => {
const result = await client.customer.addresses.update(
'addr_1',
{ city: 'Updated City' },
- opts
- );
- expect(result.city).toBe('Updated City');
- });
+ opts,
+ )
+ expect(result.city).toBe('Updated City')
+ })
it('deletes an address', async () => {
- await expect(
- client.customer.addresses.delete('addr_1', opts)
- ).resolves.toBeUndefined();
- });
- });
+ await expect(client.customer.addresses.delete('addr_1', opts)).resolves.toBeUndefined()
+ })
+ })
describe('creditCards', () => {
it('lists credit cards', async () => {
- const result = await client.customer.creditCards.list(undefined, opts);
- expect(result.data).toBeDefined();
- });
+ const result = await client.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);
- expect(result).toBeDefined();
- });
+ const result = await client.customer.creditCards.get('cc_1', opts)
+ expect(result).toBeDefined()
+ })
it('deletes a credit card', async () => {
- await expect(
- client.customer.creditCards.delete('cc_1', opts)
- ).resolves.toBeUndefined();
- });
- });
+ await expect(client.customer.creditCards.delete('cc_1', opts)).resolves.toBeUndefined()
+ })
+ })
describe('orders', () => {
it('lists customer orders', async () => {
- const result = await client.customer.orders.list(undefined, opts);
- expect(result.data).toHaveLength(1);
- expect(result.meta.page).toBe(1);
- });
+ const result = await client.customer.orders.list(undefined, opts)
+ expect(result.data).toHaveLength(1)
+ expect(result.meta.page).toBe(1)
+ })
it('gets a customer order by ID', async () => {
- const result = await client.customer.orders.get('or_abc123', undefined, opts);
- expect(result.id).toBe('or_1');
- });
- });
+ const result = await client.customer.orders.get('or_abc123', undefined, opts)
+ expect(result.id).toBe('or_1')
+ })
+ })
describe('giftCards', () => {
it('lists gift cards', async () => {
- const result = await client.customer.giftCards.list(undefined, opts);
- expect(result.data).toBeDefined();
- });
+ const result = await client.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);
- expect(result).toBeDefined();
- });
- });
+ const result = await client.customer.giftCards.get('gc_1', opts)
+ expect(result).toBeDefined()
+ })
+ })
describe('storeCredits', () => {
it('lists store credits', async () => {
- const result = await client.customer.storeCredits.list(undefined, opts);
- expect(result.data).toHaveLength(1);
- expect(result.data[0].id).toBe('credit_1');
- expect(result.data[0].amount).toBe('100.00');
- expect(result.data[0].amount_remaining).toBe('75.00');
- expect(result.data[0].currency).toBe('USD');
- });
+ const result = await client.customer.storeCredits.list(undefined, opts)
+ expect(result.data).toHaveLength(1)
+ expect(result.data[0].id).toBe('credit_1')
+ expect(result.data[0].amount).toBe('100.00')
+ expect(result.data[0].amount_remaining).toBe('75.00')
+ expect(result.data[0].currency).toBe('USD')
+ })
it('gets a store credit by ID', async () => {
- const result = await client.customer.storeCredits.get('credit_1', opts);
- expect(result.id).toBe('credit_1');
- expect(result.amount).toBe('100.00');
- });
- });
-});
+ const result = await client.customer.storeCredits.get('credit_1', opts)
+ expect(result.id).toBe('credit_1')
+ expect(result.amount).toBe('100.00')
+ })
+ })
+})
diff --git a/packages/sdk/tests/error-handling.test.ts b/packages/sdk/tests/error-handling.test.ts
index 2eb3b16731..2dcc14b5ff 100644
--- a/packages/sdk/tests/error-handling.test.ts
+++ b/packages/sdk/tests/error-handling.test.ts
@@ -1,10 +1,10 @@
-import { describe, it, expect } from 'vitest';
-import { server } from './mocks/server';
-import { http, HttpResponse } from 'msw';
-import { SpreeError } from '../src';
-import { createTestClient, TEST_BASE_URL } from './helpers';
+import { HttpResponse, http } from 'msw'
+import { describe, expect, it } from 'vitest'
+import { SpreeError } from '../src'
+import { createTestClient, TEST_BASE_URL } from './helpers'
+import { server } from './mocks/server'
-const API_PREFIX = `${TEST_BASE_URL}/api/v3/store`;
+const API_PREFIX = `${TEST_BASE_URL}/api/v3/store`
describe('error handling', () => {
it('throws SpreeError with correct properties on 4xx', async () => {
@@ -17,24 +17,24 @@ describe('error handling', () => {
message: 'Product not found',
},
},
- { status: 404 }
- )
- )
- );
+ { status: 404 },
+ ),
+ ),
+ )
- const client = createTestClient();
+ const client = createTestClient()
try {
- await client.products.get('nonexistent');
- expect.unreachable('Should have thrown');
+ await client.products.get('nonexistent')
+ expect.unreachable('Should have thrown')
} catch (error) {
- expect(error).toBeInstanceOf(SpreeError);
- const spreeError = error as SpreeError;
- expect(spreeError.code).toBe('not_found');
- expect(spreeError.status).toBe(404);
- expect(spreeError.message).toBe('Product not found');
- expect(spreeError.name).toBe('SpreeError');
+ expect(error).toBeInstanceOf(SpreeError)
+ const spreeError = error as SpreeError
+ expect(spreeError.code).toBe('not_found')
+ expect(spreeError.status).toBe(404)
+ expect(spreeError.message).toBe('Product not found')
+ expect(spreeError.name).toBe('SpreeError')
}
- });
+ })
it('throws SpreeError with details on 422', async () => {
server.use(
@@ -45,30 +45,37 @@ describe('error handling', () => {
code: 'unprocessable_entity',
message: 'Validation failed',
details: {
- address1: ['can\'t be blank'],
- city: ['can\'t be blank'],
+ address1: ["can't be blank"],
+ city: ["can't be blank"],
},
},
},
- { status: 422 }
- )
- )
- );
+ { status: 422 },
+ ),
+ ),
+ )
- const client = createTestClient();
+ const client = createTestClient()
try {
await client.customer.addresses.create(
- { first_name: 'A', last_name: 'B', address1: '', city: '', postal_code: '00000', country_iso: 'US' },
- { token: 'jwt' }
- );
- expect.unreachable('Should have thrown');
+ {
+ first_name: 'A',
+ last_name: 'B',
+ address1: '',
+ city: '',
+ postal_code: '00000',
+ country_iso: 'US',
+ },
+ { token: 'jwt' },
+ )
+ expect.unreachable('Should have thrown')
} catch (error) {
- const spreeError = error as SpreeError;
- expect(spreeError.status).toBe(422);
- expect(spreeError.details).toHaveProperty('address1');
- expect(spreeError.details).toHaveProperty('city');
+ const spreeError = error as SpreeError
+ expect(spreeError.status).toBe(422)
+ expect(spreeError.details).toHaveProperty('address1')
+ expect(spreeError.details).toHaveProperty('city')
}
- });
+ })
it('throws SpreeError on 500 server error', async () => {
server.use(
@@ -80,21 +87,21 @@ describe('error handling', () => {
message: 'Something went wrong',
},
},
- { status: 500 }
- )
- )
- );
+ { status: 500 },
+ ),
+ ),
+ )
- const client = createTestClient();
+ const client = createTestClient()
try {
- await client.countries.list();
- expect.unreachable('Should have thrown');
+ await client.countries.list()
+ expect.unreachable('Should have thrown')
} catch (error) {
- const spreeError = error as SpreeError;
- expect(spreeError.status).toBe(500);
- expect(spreeError.code).toBe('internal_server_error');
+ const spreeError = error as SpreeError
+ expect(spreeError.status).toBe(500)
+ expect(spreeError.code).toBe('internal_server_error')
}
- });
+ })
it('throws SpreeError on 401 unauthorized', async () => {
server.use(
@@ -106,25 +113,25 @@ describe('error handling', () => {
message: 'You must be logged in',
},
},
- { status: 401 }
- )
- )
- );
+ { status: 401 },
+ ),
+ ),
+ )
- const client = createTestClient();
+ const client = createTestClient()
try {
- await client.customer.get();
- expect.unreachable('Should have thrown');
+ await client.customer.get()
+ expect.unreachable('Should have thrown')
} catch (error) {
- const spreeError = error as SpreeError;
- expect(spreeError.status).toBe(401);
- expect(spreeError.code).toBe('unauthorized');
+ const spreeError = error as SpreeError
+ expect(spreeError.status).toBe(401)
+ expect(spreeError.code).toBe('unauthorized')
}
- });
+ })
it('handles 204 No Content responses', async () => {
- const client = createTestClient();
- const result = await client.carts.delete('cart_1', { token: 'jwt' });
- expect(result).toBeUndefined();
- });
-});
+ const client = createTestClient()
+ const result = await client.carts.delete('cart_1', { token: 'jwt' })
+ expect(result).toBeUndefined()
+ })
+})
diff --git a/packages/sdk/tests/helpers.ts b/packages/sdk/tests/helpers.ts
index af50a99b6e..d026db4ef3 100644
--- a/packages/sdk/tests/helpers.ts
+++ b/packages/sdk/tests/helpers.ts
@@ -1,11 +1,11 @@
-import { createClient } from '../src';
+import { createClient } from '../src'
-export const TEST_BASE_URL = 'https://demo.spreecommerce.org';
-export const TEST_API_KEY = 'test-publishable-key';
+export const TEST_BASE_URL = 'https://demo.spreecommerce.org'
+export const TEST_API_KEY = 'test-publishable-key'
export function createTestClient() {
return createClient({
baseUrl: TEST_BASE_URL,
publishableKey: TEST_API_KEY,
- });
-}
\ No newline at end of file
+ })
+}
diff --git a/packages/sdk/tests/integration/auth.test.ts b/packages/sdk/tests/integration/auth.test.ts
index 3a740af84b..8bd9c6b97b 100644
--- a/packages/sdk/tests/integration/auth.test.ts
+++ b/packages/sdk/tests/integration/auth.test.ts
@@ -1,32 +1,32 @@
-import { describe, it, expect } from 'vitest';
-import { client } from './helpers';
-import { getCredentials } from './setup';
+import { describe, expect, it } from 'vitest'
+import { client } from './helpers'
+import { getCredentials } from './setup'
describe('auth', () => {
it('logs in with email/password and returns JWT', async () => {
- const creds = getCredentials();
+ const creds = getCredentials()
const result = await client().auth.login({
email: creds.user_email,
password: creds.user_password,
- });
+ })
- expect(result.token).toBeDefined();
- expect(result.refresh_token).toBeDefined();
- expect(result.user.email).toBe(creds.user_email);
- });
+ expect(result.token).toBeDefined()
+ expect(result.refresh_token).toBeDefined()
+ expect(result.user.email).toBe(creds.user_email)
+ })
it('refreshes a token', async () => {
- const creds = getCredentials();
+ const creds = getCredentials()
const login = await client().auth.login({
email: creds.user_email,
password: creds.user_password,
- });
+ })
const result = await client().auth.refresh({
refresh_token: login.refresh_token,
- });
+ })
- expect(result.token).toBeDefined();
- expect(result.token).not.toBe(login.token);
- });
-});
+ expect(result.token).toBeDefined()
+ expect(result.token).not.toBe(login.token)
+ })
+})
diff --git a/packages/sdk/tests/integration/cart.test.ts b/packages/sdk/tests/integration/cart.test.ts
index ff4f7450bf..c8103f269a 100644
--- a/packages/sdk/tests/integration/cart.test.ts
+++ b/packages/sdk/tests/integration/cart.test.ts
@@ -1,105 +1,123 @@
-import { describe, it, expect } from 'vitest';
-import { client, buildCart } from './helpers';
+import { describe, expect, it } from 'vitest'
+import { buildCart, client } from './helpers'
describe('cart items', () => {
it('creates a cart, adds item, updates, removes', async () => {
- const c = client();
-
- const products = await c.products.list();
- const variantId = products.data.find(p => p.purchasable && p.default_variant_id)!.default_variant_id;
-
- const cart = await c.carts.create();
- expect(cart.id).toMatch(/^cart_/);
- expect(cart.token).toBeDefined();
- expect(cart).toHaveProperty('items');
- expect(cart).toHaveProperty('fulfillments');
- expect(cart).toHaveProperty('payment_methods');
- expect(cart).toHaveProperty('payments');
-
- const opts = { spreeToken: cart.token };
-
- const updated = await c.carts.items.create(cart.id, { variant_id: variantId, quantity: 2 }, opts);
- expect(updated.items.length).toBe(1);
- expect(updated.items[0].quantity).toBe(2);
-
- const lineItemId = updated.items[0].id;
- const after = await c.carts.items.update(cart.id, lineItemId, { quantity: 1 }, opts);
- expect(after.items[0].quantity).toBe(1);
-
- const empty = await c.carts.items.delete(cart.id, lineItemId, opts);
- expect(empty.items.length).toBe(0);
- });
-});
+ const c = client()
+
+ const products = await c.products.list()
+ const variantId = products.data.find(
+ (p) => p.purchasable && p.default_variant_id,
+ )!.default_variant_id
+
+ const cart = await c.carts.create()
+ expect(cart.id).toMatch(/^cart_/)
+ expect(cart.token).toBeDefined()
+ expect(cart).toHaveProperty('items')
+ expect(cart).toHaveProperty('fulfillments')
+ expect(cart).toHaveProperty('payment_methods')
+ expect(cart).toHaveProperty('payments')
+
+ const opts = { spreeToken: cart.token }
+
+ const updated = await c.carts.items.create(
+ cart.id,
+ { variant_id: variantId, quantity: 2 },
+ opts,
+ )
+ expect(updated.items.length).toBe(1)
+ expect(updated.items[0].quantity).toBe(2)
+
+ const lineItemId = updated.items[0].id
+ const after = await c.carts.items.update(cart.id, lineItemId, { quantity: 1 }, opts)
+ expect(after.items[0].quantity).toBe(1)
+
+ const empty = await c.carts.items.delete(cart.id, lineItemId, opts)
+ expect(empty.items.length).toBe(0)
+ })
+})
describe('cart addresses', () => {
it('sets shipping and billing addresses', async () => {
- const { cart } = await buildCart('address');
+ const { cart } = await buildCart('address')
- expect(cart.shipping_address).toBeDefined();
- expect(cart.billing_address).toBeDefined();
- expect(cart.email).toBeDefined();
- });
-});
+ expect(cart.shipping_address).toBeDefined()
+ expect(cart.billing_address).toBeDefined()
+ expect(cart.email).toBeDefined()
+ })
+})
describe('cart fulfillments', () => {
it('selects a delivery rate', async () => {
- const { cart } = await buildCart('delivery');
+ const { cart } = await buildCart('delivery')
- expect(Number(cart.delivery_total)).toBeGreaterThan(0);
- });
-});
+ expect(Number(cart.delivery_total)).toBeGreaterThan(0)
+ })
+})
describe('cart payment sessions', () => {
it('creates and gets a payment session', async () => {
- const { c, cart, opts, creds } = await buildCart('delivery');
+ const { c, cart, opts, creds } = await buildCart('delivery')
- const session = await c.carts.paymentSessions.create(cart.id, {
- payment_method_id: creds.bogus_payment_method_id,
- }, opts);
+ const session = await c.carts.paymentSessions.create(
+ cart.id,
+ {
+ payment_method_id: creds.bogus_payment_method_id,
+ },
+ opts,
+ )
- expect(session.id).toMatch(/^ps_/);
- expect(session.status).toBe('pending');
- expect(session.payment_method_id).toBe(creds.bogus_payment_method_id);
+ expect(session.id).toMatch(/^ps_/)
+ expect(session.status).toBe('pending')
+ expect(session.payment_method_id).toBe(creds.bogus_payment_method_id)
- const fetched = await c.carts.paymentSessions.get(cart.id, session.id, opts);
- expect(fetched.id).toBe(session.id);
- });
+ const fetched = await c.carts.paymentSessions.get(cart.id, session.id, opts)
+ expect(fetched.id).toBe(session.id)
+ })
it('completes a payment session', async () => {
- const { c, cart, opts, session } = await buildCart('payment');
+ const { c, cart, opts, session } = await buildCart('payment')
- const completed = await c.carts.paymentSessions.complete(cart.id, session!.id, undefined, opts);
- expect(completed.status).toBe('completed');
- });
-});
+ const completed = await c.carts.paymentSessions.complete(cart.id, session!.id, undefined, opts)
+ expect(completed.status).toBe('completed')
+ })
+})
describe('cart completion', () => {
it('completes cart with Check payment and returns order', async () => {
- const { c, cart, opts, creds } = await buildCart('delivery');
-
- const payment = await c.carts.payments.create(cart.id, {
- payment_method_id: creds.check_payment_method_id,
- }, opts);
- expect(payment.id).toMatch(/^py_/);
-
- const order = await c.carts.complete(cart.id, opts);
-
- expect(order.id).toMatch(/^or_/);
- expect(order.number).toBeDefined();
- expect(order.completed_at).toBeDefined();
- expect(order.payment_status).toBeDefined();
- expect(order.items.length).toBeGreaterThan(0);
- });
+ const { c, cart, opts, creds } = await buildCart('delivery')
+
+ const payment = await c.carts.payments.create(
+ cart.id,
+ {
+ payment_method_id: creds.check_payment_method_id,
+ },
+ opts,
+ )
+ expect(payment.id).toMatch(/^py_/)
+
+ const order = await c.carts.complete(cart.id, opts)
+
+ expect(order.id).toMatch(/^or_/)
+ expect(order.number).toBeDefined()
+ expect(order.completed_at).toBeDefined()
+ expect(order.payment_status).toBeDefined()
+ expect(order.items.length).toBeGreaterThan(0)
+ })
it('gets a completed order as guest via spree token', async () => {
- const { c, cart, opts, creds } = await buildCart('delivery');
- await c.carts.payments.create(cart.id, { payment_method_id: creds.check_payment_method_id }, opts);
- const order = await c.carts.complete(cart.id, opts);
-
- const fetched = await c.orders.get(order.id, undefined, opts);
-
- expect(fetched.id).toBe(order.id);
- expect(fetched.number).toBe(order.number);
- expect(fetched.completed_at).toBeDefined();
- });
-});
+ const { c, cart, opts, creds } = await buildCart('delivery')
+ await c.carts.payments.create(
+ cart.id,
+ { payment_method_id: creds.check_payment_method_id },
+ opts,
+ )
+ const order = await c.carts.complete(cart.id, opts)
+
+ const fetched = await c.orders.get(order.id, undefined, opts)
+
+ expect(fetched.id).toBe(order.id)
+ expect(fetched.number).toBe(order.number)
+ expect(fetched.completed_at).toBeDefined()
+ })
+})
diff --git a/packages/sdk/tests/integration/catalog.test.ts b/packages/sdk/tests/integration/catalog.test.ts
index 4132c19619..c189b03f0b 100644
--- a/packages/sdk/tests/integration/catalog.test.ts
+++ b/packages/sdk/tests/integration/catalog.test.ts
@@ -1,50 +1,50 @@
-import { describe, it, expect } from 'vitest';
-import { client } from './helpers';
-import { getCredentials } from './setup';
+import { describe, expect, it } from 'vitest'
+import { client } from './helpers'
+import { getCredentials } from './setup'
describe('products', () => {
it('lists products with correct shape', async () => {
- const result = await client().products.list();
+ const result = await client().products.list()
- expect(result.data).toBeInstanceOf(Array);
- expect(result.data.length).toBeGreaterThan(0);
- expect(result.meta).toHaveProperty('count');
+ expect(result.data).toBeInstanceOf(Array)
+ expect(result.data.length).toBeGreaterThan(0)
+ expect(result.meta).toHaveProperty('count')
- const product = result.data[0];
- expect(product.id).toMatch(/^prod_/);
- expect(product).toHaveProperty('name');
- expect(product).toHaveProperty('slug');
- expect(product).toHaveProperty('price');
- expect(product).toHaveProperty('purchasable');
- expect(product).toHaveProperty('in_stock');
- });
+ const product = result.data[0]
+ expect(product.id).toMatch(/^prod_/)
+ expect(product).toHaveProperty('name')
+ expect(product).toHaveProperty('slug')
+ expect(product).toHaveProperty('price')
+ expect(product).toHaveProperty('purchasable')
+ expect(product).toHaveProperty('in_stock')
+ })
it('gets a product by slug', async () => {
- const creds = getCredentials();
- const product = await client().products.get(creds.product_slug);
+ const creds = getCredentials()
+ const product = await client().products.get(creds.product_slug)
- expect(product.id).toBe(creds.product_id);
- expect(product.slug).toBe(creds.product_slug);
- });
+ expect(product.id).toBe(creds.product_id)
+ expect(product.slug).toBe(creds.product_slug)
+ })
it('returns product filters', async () => {
- const result = await client().products.filters();
+ const result = await client().products.filters()
- expect(result).toHaveProperty('filters');
- expect(result).toHaveProperty('sort_options');
- });
-});
+ expect(result).toHaveProperty('filters')
+ expect(result).toHaveProperty('sort_options')
+ })
+})
describe('categories', () => {
it('lists categories', async () => {
- const result = await client().categories.list();
+ const result = await client().categories.list()
- expect(result.data).toBeInstanceOf(Array);
- expect(result.data.length).toBeGreaterThan(0);
+ expect(result.data).toBeInstanceOf(Array)
+ expect(result.data.length).toBeGreaterThan(0)
- const category = result.data[0];
- expect(category.id).toMatch(/^ctg_/);
- expect(category).toHaveProperty('name');
- expect(category).toHaveProperty('permalink');
- });
-});
+ const category = result.data[0]
+ expect(category.id).toMatch(/^ctg_/)
+ expect(category).toHaveProperty('name')
+ expect(category).toHaveProperty('permalink')
+ })
+})
diff --git a/packages/sdk/tests/integration/customer.test.ts b/packages/sdk/tests/integration/customer.test.ts
index 0d3aaab9f6..3b9aa6107d 100644
--- a/packages/sdk/tests/integration/customer.test.ts
+++ b/packages/sdk/tests/integration/customer.test.ts
@@ -1,120 +1,149 @@
-import { describe, it, expect } from 'vitest';
-import { client, authOpts } from './helpers';
-import { getCredentials } from './setup';
+import { describe, expect, it } from 'vitest'
+import { authOpts, client } from './helpers'
+import { getCredentials } from './setup'
describe('customer profile', () => {
it('gets current customer profile', async () => {
- const customer = await client().customer.get(authOpts());
+ const customer = await client().customer.get(authOpts())
- expect(customer.email).toBe(getCredentials().user_email);
- expect(customer).toHaveProperty('first_name');
- expect(customer).toHaveProperty('last_name');
- });
-});
+ expect(customer.email).toBe(getCredentials().user_email)
+ expect(customer).toHaveProperty('first_name')
+ expect(customer).toHaveProperty('last_name')
+ })
+})
describe('customer addresses', () => {
it('creates an address and lists with is_default fields', async () => {
- await client().customer.addresses.create({
- first_name: 'List',
- last_name: 'Test',
- address1: '50 Wall St',
- city: 'New York',
- postal_code: '10005',
- country_iso: 'US',
- state_abbr: 'NY',
- }, authOpts());
-
- const result = await client().customer.addresses.list(undefined, authOpts());
-
- expect(result.data.length).toBeGreaterThan(0);
- const address = result.data[0];
- expect(address.id).toMatch(/^addr_/);
- expect(address).toHaveProperty('is_default_billing');
- expect(address).toHaveProperty('is_default_shipping');
- expect(typeof address.is_default_billing).toBe('boolean');
- expect(typeof address.is_default_shipping).toBe('boolean');
- });
+ await client().customer.addresses.create(
+ {
+ first_name: 'List',
+ last_name: 'Test',
+ address1: '50 Wall St',
+ city: 'New York',
+ postal_code: '10005',
+ country_iso: 'US',
+ state_abbr: 'NY',
+ },
+ authOpts(),
+ )
+
+ const result = await client().customer.addresses.list(undefined, authOpts())
+
+ expect(result.data.length).toBeGreaterThan(0)
+ const address = result.data[0]
+ expect(address.id).toMatch(/^addr_/)
+ expect(address).toHaveProperty('is_default_billing')
+ expect(address).toHaveProperty('is_default_shipping')
+ expect(typeof address.is_default_billing).toBe('boolean')
+ expect(typeof address.is_default_shipping).toBe('boolean')
+ })
it('creates an address with is_default_billing', async () => {
- const address = await client().customer.addresses.create({
- first_name: 'Integration',
- last_name: 'Test',
- address1: '100 Broadway',
- city: 'New York',
- postal_code: '10005',
- country_iso: 'US',
- state_abbr: 'NY',
- is_default_billing: true,
- }, authOpts());
-
- expect(address.id).toMatch(/^addr_/);
- expect(address.is_default_billing).toBe(true);
- expect(address.city).toBe('New York');
- });
+ const address = await client().customer.addresses.create(
+ {
+ first_name: 'Integration',
+ last_name: 'Test',
+ address1: '100 Broadway',
+ city: 'New York',
+ postal_code: '10005',
+ country_iso: 'US',
+ state_abbr: 'NY',
+ is_default_billing: true,
+ },
+ authOpts(),
+ )
+
+ expect(address.id).toMatch(/^addr_/)
+ expect(address.is_default_billing).toBe(true)
+ expect(address.city).toBe('New York')
+ })
it('updates an address and sets default shipping', async () => {
- const created = await client().customer.addresses.create({
- first_name: 'Update',
- last_name: 'Test',
- address1: '200 Park Ave',
- city: 'New York',
- postal_code: '10166',
- country_iso: 'US',
- state_abbr: 'NY',
- }, authOpts());
+ const created = await client().customer.addresses.create(
+ {
+ first_name: 'Update',
+ last_name: 'Test',
+ address1: '200 Park Ave',
+ city: 'New York',
+ postal_code: '10166',
+ country_iso: 'US',
+ state_abbr: 'NY',
+ },
+ authOpts(),
+ )
const updated = await client().customer.addresses.update(
created.id,
{ is_default_shipping: true, city: 'Brooklyn' },
- authOpts()
- );
+ authOpts(),
+ )
- expect(updated.id).toBe(created.id);
- expect(updated.is_default_shipping).toBe(true);
- expect(updated.city).toBe('Brooklyn');
- });
-});
+ expect(updated.id).toBe(created.id)
+ expect(updated.is_default_shipping).toBe(true)
+ expect(updated.city).toBe('Brooklyn')
+ })
+})
describe('customer orders', () => {
it('completes an order and lists/views it in order history', async () => {
- const creds = getCredentials();
- const c = client();
+ const creds = getCredentials()
+ const c = client()
- const products = await c.products.list();
- const variantId = products.data.find(p => p.purchasable && p.default_variant_id)!.default_variant_id;
+ const products = await c.products.list()
+ const variantId = products.data.find(
+ (p) => p.purchasable && p.default_variant_id,
+ )!.default_variant_id
- const cart = await c.carts.create(undefined, authOpts());
- const opts = { ...authOpts(), spreeToken: cart.token };
+ const cart = await c.carts.create(undefined, authOpts())
+ const opts = { ...authOpts(), spreeToken: cart.token }
- await c.carts.items.create(cart.id, { variant_id: variantId, quantity: 1 }, opts);
+ await c.carts.items.create(cart.id, { variant_id: variantId, quantity: 1 }, opts)
const address = {
- first_name: 'Order', last_name: 'History',
- address1: '1 Times Square', city: 'New York', postal_code: '10036',
- country_iso: creds.country_iso, state_abbr: 'NY', phone: '555-0100',
- };
- const withAddr = await c.carts.update(cart.id, {
- email: creds.user_email,
- shipping_address: address,
- billing_address: address,
- }, opts);
-
- const ful = withAddr.fulfillments[0];
- await c.carts.fulfillments.update(cart.id, ful.id, { selected_delivery_rate_id: ful.delivery_rates[0].id }, opts);
- await c.carts.payments.create(cart.id, { payment_method_id: creds.check_payment_method_id }, opts);
- const order = await c.carts.complete(cart.id, opts);
+ first_name: 'Order',
+ last_name: 'History',
+ address1: '1 Times Square',
+ city: 'New York',
+ postal_code: '10036',
+ country_iso: creds.country_iso,
+ state_abbr: 'NY',
+ phone: '555-0100',
+ }
+ const withAddr = await c.carts.update(
+ cart.id,
+ {
+ email: creds.user_email,
+ shipping_address: address,
+ billing_address: address,
+ },
+ opts,
+ )
+
+ const ful = withAddr.fulfillments[0]
+ await c.carts.fulfillments.update(
+ cart.id,
+ ful.id,
+ { selected_delivery_rate_id: ful.delivery_rates[0].id },
+ opts,
+ )
+ await c.carts.payments.create(
+ cart.id,
+ { payment_method_id: creds.check_payment_method_id },
+ opts,
+ )
+ const order = await c.carts.complete(cart.id, opts)
// List
- const orders = await c.customer.orders.list(undefined, authOpts());
- expect(orders.data.length).toBeGreaterThan(0);
- const found = orders.data.find(o => o.id === order.id);
- expect(found).toBeDefined();
- expect(found!.number).toBe(order.number);
+ const orders = await c.customer.orders.list(undefined, authOpts())
+ expect(orders.data.length).toBeGreaterThan(0)
+ const found = orders.data.find((o) => o.id === order.id)
+ expect(found).toBeDefined()
+ expect(found!.number).toBe(order.number)
// Detail
- const detail = await c.customer.orders.get(order.id, undefined, authOpts());
- expect(detail.id).toBe(order.id);
- expect(detail.completed_at).toBeDefined();
- expect(detail.items.length).toBeGreaterThan(0);
- });
-});
+ const detail = await c.customer.orders.get(order.id, undefined, authOpts())
+ expect(detail.id).toBe(order.id)
+ expect(detail.completed_at).toBeDefined()
+ expect(detail.items.length).toBeGreaterThan(0)
+ })
+})
diff --git a/packages/sdk/tests/integration/global-setup.ts b/packages/sdk/tests/integration/global-setup.ts
index 6f88bc846c..b3630bd1bc 100644
--- a/packages/sdk/tests/integration/global-setup.ts
+++ b/packages/sdk/tests/integration/global-setup.ts
@@ -2,17 +2,22 @@
* Global setup — runs once before all integration test files.
* Seeds the database, boots a Rails server, and provides credentials.
*/
-import { execSync, spawn, type ChildProcess } from 'child_process';
-import { resolve } from 'path';
-import { writeFileSync } from 'fs';
-import type { GlobalSetupContext } from 'vitest/node';
+import { type ChildProcess, execSync, spawn } from 'node:child_process'
+import { writeFileSync } from 'node:fs'
+import { resolve } from 'node:path'
-const API_GEM_DIR = resolve(__dirname, '../../../../spree/api');
-const RAILS = 'bundle exec spec/dummy/bin/rails';
-const PORT = process.env.INTEGRATION_PORT || '3010';
-const CREDENTIALS_FILE = resolve(__dirname, '.credentials.json');
+const API_GEM_DIR = resolve(__dirname, '../../../../spree/api')
+const RAILS = 'bundle exec spec/dummy/bin/rails'
+const PORT = process.env.INTEGRATION_PORT || '3010'
+const CREDENTIALS_FILE = resolve(__dirname, '.credentials.json')
-const execOpts = { cwd: API_GEM_DIR, encoding: 'utf-8' as const, timeout: 120_000, maxBuffer: 10 * 1024 * 1024, env: { ...process.env, RAILS_ENV: 'test', PORT } };
+const execOpts = {
+ cwd: API_GEM_DIR,
+ encoding: 'utf-8' as const,
+ timeout: 120_000,
+ maxBuffer: 10 * 1024 * 1024,
+ env: { ...process.env, RAILS_ENV: 'test', PORT },
+}
const CREDENTIALS_RUBY = [
'require "json"',
@@ -28,52 +33,65 @@ const CREDENTIALS_RUBY = [
'c = s.taxonomies.first&.root&.children&.first',
'port = ENV.fetch("PORT", 3010)',
'puts JSON.generate(base_url: "http://localhost:#{port}", publishable_key: k.token, jwt_token: jwt, user_email: u.email, user_password: "spree123", product_slug: p&.slug, product_id: p&.prefixed_id, variant_id: p&.default_variant&.prefixed_id, category_id: c&.prefixed_id, category_permalink: c&.permalink, country_iso: "US", store_name: s.name, bogus_payment_method_id: pm.prefixed_id, check_payment_method_id: check.prefixed_id)',
-].join('; ');
+].join('; ')
-let serverProcess: ChildProcess | null = null;
+let serverProcess: ChildProcess | null = null
function waitForServer(url: string, timeoutMs = 30_000): Promise<void> {
- const start = Date.now();
+ const start = Date.now()
return new Promise((resolve, reject) => {
const check = async () => {
try {
- const res = await fetch(url);
- if (res.ok || res.status === 401) { resolve(); return; }
- } catch { /* not ready */ }
- if (Date.now() - start > timeoutMs) { reject(new Error(`Server did not start within ${timeoutMs}ms`)); return; }
- setTimeout(check, 500);
- };
- check();
- });
+ const res = await fetch(url)
+ if (res.ok || res.status === 401) {
+ resolve()
+ return
+ }
+ } catch {
+ /* not ready */
+ }
+ if (Date.now() - start > timeoutMs) {
+ reject(new Error(`Server did not start within ${timeoutMs}ms`))
+ return
+ }
+ setTimeout(check, 500)
+ }
+ check()
+ })
}
export async function setup() {
// 1. Seed + load sample data
- execSync(`${RAILS} runner "Spree::Seeds::All.call; Spree::SampleData::Loader.call"`, execOpts);
+ execSync(`${RAILS} runner "Spree::Seeds::All.call; Spree::SampleData::Loader.call"`, execOpts)
// 2. Extract credentials and write to temp file (shared with test files)
- const output = execSync(`${RAILS} runner '${CREDENTIALS_RUBY}'`, execOpts);
- const jsonMatch = output.match(/\{.*\}\s*$/);
- if (!jsonMatch) throw new Error(`Failed to parse credentials:\n${output}`);
- writeFileSync(CREDENTIALS_FILE, jsonMatch[0]);
+ const output = execSync(`${RAILS} runner '${CREDENTIALS_RUBY}'`, execOpts)
+ const jsonMatch = output.match(/\{.*\}\s*$/)
+ if (!jsonMatch) throw new Error(`Failed to parse credentials:\n${output}`)
+ writeFileSync(CREDENTIALS_FILE, jsonMatch[0])
// 3. Boot Rails server
serverProcess = spawn(
- 'bundle', ['exec', 'spec/dummy/bin/rails', 'server', '-p', PORT, '-e', 'test'],
- { cwd: API_GEM_DIR, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, RAILS_ENV: 'test', PORT } }
- );
+ 'bundle',
+ ['exec', 'spec/dummy/bin/rails', 'server', '-p', PORT, '-e', 'test'],
+ {
+ cwd: API_GEM_DIR,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, RAILS_ENV: 'test', PORT },
+ },
+ )
serverProcess.stderr?.on('data', (data: Buffer) => {
- const msg = data.toString();
- if (msg.includes('Error') || msg.includes('error')) console.error('[rails]', msg);
- });
+ const msg = data.toString()
+ if (msg.includes('Error') || msg.includes('error')) console.error('[rails]', msg)
+ })
- await waitForServer(`http://localhost:${PORT}/api/v3/store/products`);
+ await waitForServer(`http://localhost:${PORT}/api/v3/store/products`)
}
export async function teardown() {
if (serverProcess) {
- serverProcess.kill('SIGTERM');
- serverProcess = null;
+ serverProcess.kill('SIGTERM')
+ serverProcess = null
}
}
diff --git a/packages/sdk/tests/integration/helpers.ts b/packages/sdk/tests/integration/helpers.ts
index a85ddf7326..a0268bce7a 100644
--- a/packages/sdk/tests/integration/helpers.ts
+++ b/packages/sdk/tests/integration/helpers.ts
@@ -1,17 +1,16 @@
-import { createClient } from '../../src';
-import { getCredentials, type TestCredentials } from './setup';
-import type { Client } from '../../src';
+import { createClient } from '../../src'
+import { getCredentials } from './setup'
export function client() {
- const creds = getCredentials();
+ const creds = getCredentials()
return createClient({
baseUrl: creds.base_url,
publishableKey: creds.publishable_key,
- });
+ })
}
export function authOpts() {
- return { token: getCredentials().jwt_token };
+ return { token: getCredentials().jwt_token }
}
export function testAddress(overrides: Record<string, string> = {}) {
@@ -25,40 +24,55 @@ export function testAddress(overrides: Record<string, string> = {}) {
state_abbr: 'NY',
phone: '555-0100',
...overrides,
- };
+ }
}
/**
* Build a cart through the checkout to a given step.
*/
export async function buildCart(throughStep: 'item' | 'address' | 'delivery' | 'payment') {
- const creds = getCredentials();
- const c = client();
+ const creds = getCredentials()
+ const c = client()
- const products = await c.products.list();
- const variantId = products.data.find(p => p.purchasable && p.default_variant_id)!.default_variant_id;
+ const products = await c.products.list()
+ const variantId = products.data.find(
+ (p) => p.purchasable && p.default_variant_id,
+ )!.default_variant_id
- const cart = await c.carts.create();
- const opts = { spreeToken: cart.token };
+ const cart = await c.carts.create()
+ const opts = { spreeToken: cart.token }
- await c.carts.items.create(cart.id, { variant_id: variantId, quantity: 1 }, opts);
- if (throughStep === 'item') return { c, cart, opts, creds };
+ await c.carts.items.create(cart.id, { variant_id: variantId, quantity: 1 }, opts)
+ if (throughStep === 'item') return { c, cart, opts, creds }
- const withAddr = await c.carts.update(cart.id, {
- email: `test-${Date.now()}@example.com`,
- shipping_address: testAddress(),
- billing_address: testAddress(),
- }, opts);
- if (throughStep === 'address') return { c, cart: withAddr, opts, creds };
+ const withAddr = await c.carts.update(
+ cart.id,
+ {
+ email: `test-${Date.now()}@example.com`,
+ shipping_address: testAddress(),
+ billing_address: testAddress(),
+ },
+ opts,
+ )
+ if (throughStep === 'address') return { c, cart: withAddr, opts, creds }
- const ful = withAddr.fulfillments[0];
- const withRate = await c.carts.fulfillments.update(cart.id, ful.id, {
- selected_delivery_rate_id: ful.delivery_rates[0].id,
- }, opts);
- if (throughStep === 'delivery') return { c, cart: withRate, opts, creds };
+ const ful = withAddr.fulfillments[0]
+ const withRate = await c.carts.fulfillments.update(
+ cart.id,
+ ful.id,
+ {
+ selected_delivery_rate_id: ful.delivery_rates[0].id,
+ },
+ opts,
+ )
+ if (throughStep === 'delivery') return { c, cart: withRate, opts, creds }
- const session = await c.carts.paymentSessions.create(cart.id, {
- payment_method_id: creds.bogus_payment_method_id,
- }, opts);
- return { c, cart: withRate, opts, creds, session };
+ const session = await c.carts.paymentSessions.create(
+ cart.id,
+ {
+ payment_method_id: creds.bogus_payment_method_id,
+ },
+ opts,
+ )
+ return { c, cart: withRate, opts, creds, session }
}
diff --git a/packages/sdk/tests/integration/markets.test.ts b/packages/sdk/tests/integration/markets.test.ts
index 0f6c3cd66a..2e9b74e12d 100644
--- a/packages/sdk/tests/integration/markets.test.ts
+++ b/packages/sdk/tests/integration/markets.test.ts
@@ -1,37 +1,37 @@
-import { describe, it, expect } from 'vitest';
-import { client } from './helpers';
+import { describe, expect, it } from 'vitest'
+import { client } from './helpers'
describe('markets', () => {
it('lists markets', async () => {
- const result = await client().markets.list();
+ const result = await client().markets.list()
- expect(result.data.length).toBeGreaterThan(0);
- const market = result.data[0];
- expect(market.id).toMatch(/^mkt_/);
- expect(market).toHaveProperty('name');
- expect(market).toHaveProperty('currency');
- });
+ expect(result.data.length).toBeGreaterThan(0)
+ const market = result.data[0]
+ expect(market.id).toMatch(/^mkt_/)
+ expect(market).toHaveProperty('name')
+ expect(market).toHaveProperty('currency')
+ })
it('resolves market by country', async () => {
- const market = await client().markets.resolve('US');
- expect(market.id).toMatch(/^mkt_/);
- });
-});
+ const market = await client().markets.resolve('US')
+ expect(market.id).toMatch(/^mkt_/)
+ })
+})
describe('countries', () => {
it('lists countries', async () => {
- const result = await client().countries.list();
+ const result = await client().countries.list()
- expect(result.data.length).toBeGreaterThan(0);
- const country = result.data[0];
- expect(country).toHaveProperty('iso');
- expect(country).toHaveProperty('name');
- });
+ expect(result.data.length).toBeGreaterThan(0)
+ const country = result.data[0]
+ expect(country).toHaveProperty('iso')
+ expect(country).toHaveProperty('name')
+ })
it('gets a country with states', async () => {
- const country = await client().countries.get('US', { expand: ['states'] });
+ const country = await client().countries.get('US', { expand: ['states'] })
- expect(country.iso).toBe('US');
- expect(country.name).toBe('United States');
- });
-});
+ expect(country.iso).toBe('US')
+ expect(country.name).toBe('United States')
+ })
+})
diff --git a/packages/sdk/tests/integration/setup.ts b/packages/sdk/tests/integration/setup.ts
index 3974e6195c..86c07cc1f7 100644
--- a/packages/sdk/tests/integration/setup.ts
+++ b/packages/sdk/tests/integration/setup.ts
@@ -1,33 +1,33 @@
/**
* Per-file setup — reads credentials written by global-setup.ts.
*/
-import { readFileSync } from 'fs';
-import { resolve } from 'path';
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
export interface TestCredentials {
- base_url: string;
- publishable_key: string;
- jwt_token: string;
- user_email: string;
- user_password: string;
- product_slug: string;
- product_id: string;
- variant_id: string;
- category_id: string;
- category_permalink: string;
- country_iso: string;
- store_name: string;
- bogus_payment_method_id: string;
- check_payment_method_id: string;
+ base_url: string
+ publishable_key: string
+ jwt_token: string
+ user_email: string
+ user_password: string
+ product_slug: string
+ product_id: string
+ variant_id: string
+ category_id: string
+ category_permalink: string
+ country_iso: string
+ store_name: string
+ bogus_payment_method_id: string
+ check_payment_method_id: string
}
-const CREDENTIALS_FILE = resolve(__dirname, '.credentials.json');
+const CREDENTIALS_FILE = resolve(__dirname, '.credentials.json')
-let credentials: TestCredentials | null = null;
+let credentials: TestCredentials | null = null
export function getCredentials(): TestCredentials {
if (!credentials) {
- credentials = JSON.parse(readFileSync(CREDENTIALS_FILE, 'utf-8'));
+ credentials = JSON.parse(readFileSync(CREDENTIALS_FILE, 'utf-8'))
}
- return credentials!;
+ return credentials!
}
diff --git a/packages/sdk/tests/markets.test.ts b/packages/sdk/tests/markets.test.ts
index ffd42e4f6b..49ed754251 100644
--- a/packages/sdk/tests/markets.test.ts
+++ b/packages/sdk/tests/markets.test.ts
@@ -1,113 +1,121 @@
-import { describe, it, expect, beforeAll } from 'vitest';
-import { createTestClient } from './helpers';
-import { fixtures } from './mocks/handlers';
-import type { Client } from '../src';
+import { beforeAll, describe, expect, it } from 'vitest'
+import type { Client } from '../src'
+import { createTestClient } from './helpers'
+import { fixtures } from './mocks/handlers'
describe('countries', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
describe('list', () => {
it('returns all countries', async () => {
- const result = await client.countries.list();
+ const result = await client.countries.list()
- expect(result.data).toHaveLength(1);
- expect(result.data[0].iso).toBe('US');
- expect(result.data[0].name).toBe('United States');
- });
- });
+ expect(result.data).toHaveLength(1)
+ expect(result.data[0].iso).toBe('US')
+ expect(result.data[0].name).toBe('United States')
+ })
+ })
describe('get', () => {
it('returns a country by ISO code', async () => {
- const result = await client.countries.get('US');
- expect(result.iso).toBe(fixtures.country.iso);
- expect(result.name).toBe('United States');
- });
- });
-});
+ const result = await client.countries.get('US')
+ expect(result.iso).toBe(fixtures.country.iso)
+ expect(result.name).toBe('United States')
+ })
+ })
+})
describe('currencies', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
describe('list', () => {
it('returns all currencies', async () => {
- const result = await client.currencies.list();
+ const result = await client.currencies.list()
- expect(result.data).toHaveLength(1);
- expect(result.data[0].iso_code).toBe('USD');
- expect(result.data[0].name).toBe('United States Dollar');
- expect(result.data[0].symbol).toBe('$');
- });
- });
-});
+ expect(result.data).toHaveLength(1)
+ expect(result.data[0].iso_code).toBe('USD')
+ expect(result.data[0].name).toBe('United States Dollar')
+ expect(result.data[0].symbol).toBe('$')
+ })
+ })
+})
describe('locales', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
describe('list', () => {
it('returns all locales', async () => {
- const result = await client.locales.list();
+ const result = await client.locales.list()
- expect(result.data).toHaveLength(1);
- expect(result.data[0].code).toBe('en');
- expect(result.data[0].name).toBe('English');
- });
- });
-});
+ expect(result.data).toHaveLength(1)
+ expect(result.data[0].code).toBe('en')
+ expect(result.data[0].name).toBe('English')
+ })
+ })
+})
describe('markets', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
describe('list', () => {
it('returns all markets', async () => {
- const result = await client.markets.list();
-
- expect(result.data).toHaveLength(1);
- expect(result.data[0].id).toBe('mkt_1');
- expect(result.data[0].name).toBe('North America');
- expect(result.data[0].currency).toBe('USD');
- expect(result.data[0].default_locale).toBe('en');
- expect(result.data[0].supported_locales).toEqual(['en', 'es']);
- expect(result.data[0].tax_inclusive).toBe(false);
- expect(result.data[0].default).toBe(true);
- expect(result.data[0].countries).toHaveLength(1);
- });
- });
+ const result = await client.markets.list()
+
+ expect(result.data).toHaveLength(1)
+ expect(result.data[0].id).toBe('mkt_1')
+ expect(result.data[0].name).toBe('North America')
+ expect(result.data[0].currency).toBe('USD')
+ expect(result.data[0].default_locale).toBe('en')
+ expect(result.data[0].supported_locales).toEqual(['en', 'es'])
+ expect(result.data[0].tax_inclusive).toBe(false)
+ expect(result.data[0].default).toBe(true)
+ expect(result.data[0].countries).toHaveLength(1)
+ })
+ })
describe('get', () => {
it('returns a market by prefixed ID', async () => {
- const result = await client.markets.get('mkt_1');
+ const result = await client.markets.get('mkt_1')
- expect(result.id).toBe('mkt_1');
- expect(result.name).toBe('North America');
- expect(result.currency).toBe('USD');
- });
- });
+ expect(result.id).toBe('mkt_1')
+ expect(result.name).toBe('North America')
+ expect(result.currency).toBe('USD')
+ })
+ })
describe('resolve', () => {
it('resolves a market by country ISO', async () => {
- const result = await client.markets.resolve('US');
+ const result = await client.markets.resolve('US')
- expect(result.id).toBe('mkt_1');
- expect(result.currency).toBe('USD');
- });
- });
+ expect(result.id).toBe('mkt_1')
+ expect(result.currency).toBe('USD')
+ })
+ })
describe('countries', () => {
it('lists countries in a market', async () => {
- const result = await client.markets.countries.list('mkt_1');
+ const result = await client.markets.countries.list('mkt_1')
- expect(result.data).toHaveLength(1);
- expect(result.data[0].iso).toBe('US');
- });
+ expect(result.data).toHaveLength(1)
+ expect(result.data[0].iso).toBe('US')
+ })
it('gets a country in a market', async () => {
- const result = await client.markets.countries.get('mkt_1', 'US');
+ const result = await client.markets.countries.get('mkt_1', 'US')
- expect(result.iso).toBe('US');
- });
- });
-});
+ expect(result.iso).toBe('US')
+ })
+ })
+})
diff --git a/packages/sdk/tests/mocks/handlers.ts b/packages/sdk/tests/mocks/handlers.ts
index c3bf39a1be..3043d604cb 100644
--- a/packages/sdk/tests/mocks/handlers.ts
+++ b/packages/sdk/tests/mocks/handlers.ts
@@ -1,7 +1,7 @@
-import { http, HttpResponse } from 'msw';
+import { HttpResponse, http } from 'msw'
-const BASE_URL = 'https://demo.spreecommerce.org';
-const API_PREFIX = `${BASE_URL}/api/v3/store`;
+const BASE_URL = 'https://demo.spreecommerce.org'
+const API_PREFIX = `${BASE_URL}/api/v3/store`
// Reusable fixture data
export const fixtures = {
@@ -84,7 +84,13 @@ export const fixtures = {
tax_inclusive: false,
default: true,
countries: [
- { iso: 'US', iso3: 'USA', name: 'United States', states_required: true, zipcode_required: true },
+ {
+ iso: 'US',
+ iso3: 'USA',
+ name: 'United States',
+ states_required: true,
+ zipcode_required: true,
+ },
],
},
currency: {
@@ -107,31 +113,37 @@ export const fixtures = {
quantity: 1,
variant_id: 'var_1',
},
-};
+}
-const paginationMeta = { page: 1, limit: 25, count: 1, pages: 1 };
+const paginationMeta = { page: 1, limit: 25, count: 1, pages: 1 }
export const handlers = [
// Auth
http.post(`${API_PREFIX}/auth/login`, () =>
- HttpResponse.json({ token: 'test-jwt-token', refresh_token: 'rt_login', user: fixtures.user })
+ HttpResponse.json({ token: 'test-jwt-token', refresh_token: 'rt_login', user: fixtures.user }),
),
http.post(`${API_PREFIX}/customers`, () =>
- HttpResponse.json({ token: 'test-jwt-token', refresh_token: 'rt_register', user: fixtures.user })
+ HttpResponse.json({
+ token: 'test-jwt-token',
+ refresh_token: 'rt_register',
+ user: fixtures.user,
+ }),
),
http.post(`${API_PREFIX}/auth/refresh`, () =>
- HttpResponse.json({ token: 'refreshed-jwt-token', refresh_token: 'rt_refreshed', user: fixtures.user })
+ HttpResponse.json({
+ token: 'refreshed-jwt-token',
+ refresh_token: 'rt_refreshed',
+ user: fixtures.user,
+ }),
),
- http.post(`${API_PREFIX}/auth/logout`, () =>
- new HttpResponse(null, { status: 204 })
- ),
+ http.post(`${API_PREFIX}/auth/logout`, () => new HttpResponse(null, { status: 204 })),
// Products
http.get(`${API_PREFIX}/products`, () =>
- HttpResponse.json({ data: [fixtures.product], meta: paginationMeta })
+ HttpResponse.json({ data: [fixtures.product], meta: paginationMeta }),
),
http.get(`${API_PREFIX}/products/filters`, () =>
@@ -140,163 +152,151 @@ export const handlers = [
sort_options: [{ id: 'default', label: 'Default' }],
default_sort: 'default',
total_count: 1,
- })
+ }),
),
- http.get(`${API_PREFIX}/products/:id`, () =>
- HttpResponse.json(fixtures.product)
- ),
+ http.get(`${API_PREFIX}/products/:id`, () => HttpResponse.json(fixtures.product)),
// Categories
http.get(`${API_PREFIX}/categories`, () =>
- HttpResponse.json({ data: [fixtures.category], meta: paginationMeta })
+ HttpResponse.json({ data: [fixtures.category], meta: paginationMeta }),
),
- http.get(`${API_PREFIX}/categories/:id`, () =>
- HttpResponse.json(fixtures.category)
- ),
+ http.get(`${API_PREFIX}/categories/:id`, () => HttpResponse.json(fixtures.category)),
// Countries
- http.get(`${API_PREFIX}/countries`, () =>
- HttpResponse.json({ data: [fixtures.country] })
- ),
+ http.get(`${API_PREFIX}/countries`, () => HttpResponse.json({ data: [fixtures.country] })),
- http.get(`${API_PREFIX}/countries/:iso`, () =>
- HttpResponse.json(fixtures.country)
- ),
+ http.get(`${API_PREFIX}/countries/:iso`, () => HttpResponse.json(fixtures.country)),
// Currencies
- http.get(`${API_PREFIX}/currencies`, () =>
- HttpResponse.json({ data: [fixtures.currency] })
- ),
+ http.get(`${API_PREFIX}/currencies`, () => HttpResponse.json({ data: [fixtures.currency] })),
// Locales
- http.get(`${API_PREFIX}/locales`, () =>
- HttpResponse.json({ data: [fixtures.locale] })
- ),
+ http.get(`${API_PREFIX}/locales`, () => HttpResponse.json({ data: [fixtures.locale] })),
// Markets
- http.get(`${API_PREFIX}/markets`, () =>
- HttpResponse.json({ data: [fixtures.market] })
- ),
+ http.get(`${API_PREFIX}/markets`, () => HttpResponse.json({ data: [fixtures.market] })),
- http.get(`${API_PREFIX}/markets/resolve`, () =>
- HttpResponse.json(fixtures.market)
- ),
+ http.get(`${API_PREFIX}/markets/resolve`, () => HttpResponse.json(fixtures.market)),
http.get(`${API_PREFIX}/markets/:id/countries`, () =>
- HttpResponse.json({ data: [fixtures.country] })
+ HttpResponse.json({ data: [fixtures.country] }),
),
- http.get(`${API_PREFIX}/markets/:id/countries/:iso`, () =>
- HttpResponse.json(fixtures.country)
- ),
+ http.get(`${API_PREFIX}/markets/:id/countries/:iso`, () => HttpResponse.json(fixtures.country)),
- http.get(`${API_PREFIX}/markets/:id`, () =>
- HttpResponse.json(fixtures.market)
- ),
+ http.get(`${API_PREFIX}/markets/:id`, () => HttpResponse.json(fixtures.market)),
// Carts
http.get(`${API_PREFIX}/carts`, () =>
- HttpResponse.json({ data: [fixtures.cart], meta: { page: 1, limit: 25, count: 1, pages: 1, from: 1, to: 1, in: 1, previous: null, next: null } })
+ HttpResponse.json({
+ data: [fixtures.cart],
+ meta: {
+ page: 1,
+ limit: 25,
+ count: 1,
+ pages: 1,
+ from: 1,
+ to: 1,
+ in: 1,
+ previous: null,
+ next: null,
+ },
+ }),
),
http.post(`${API_PREFIX}/carts`, () =>
- HttpResponse.json({ ...fixtures.cart, token: 'new-cart-token' })
+ HttpResponse.json({ ...fixtures.cart, token: 'new-cart-token' }),
),
- http.get(`${API_PREFIX}/carts/:cartId`, () =>
- HttpResponse.json(fixtures.cart)
- ),
+ http.get(`${API_PREFIX}/carts/:cartId`, () => HttpResponse.json(fixtures.cart)),
- http.patch(`${API_PREFIX}/carts/:cartId`, () =>
- HttpResponse.json(fixtures.cart)
- ),
+ http.patch(`${API_PREFIX}/carts/:cartId`, () => HttpResponse.json(fixtures.cart)),
- http.delete(`${API_PREFIX}/carts/:cartId`, () =>
- new HttpResponse(null, { status: 204 })
- ),
+ http.delete(`${API_PREFIX}/carts/:cartId`, () => new HttpResponse(null, { status: 204 })),
- http.patch(`${API_PREFIX}/carts/:cartId/associate`, () =>
- HttpResponse.json(fixtures.cart)
- ),
+ http.patch(`${API_PREFIX}/carts/:cartId/associate`, () => HttpResponse.json(fixtures.cart)),
- http.post(`${API_PREFIX}/carts/:cartId/complete`, () =>
- HttpResponse.json(fixtures.order)
- ),
+ http.post(`${API_PREFIX}/carts/:cartId/complete`, () => HttpResponse.json(fixtures.order)),
// Carts > Items
- http.post(`${API_PREFIX}/carts/:cartId/items`, () =>
- HttpResponse.json(fixtures.cart)
- ),
+ http.post(`${API_PREFIX}/carts/:cartId/items`, () => HttpResponse.json(fixtures.cart)),
- http.patch(`${API_PREFIX}/carts/:cartId/items/:id`, () =>
- HttpResponse.json(fixtures.cart)
- ),
+ http.patch(`${API_PREFIX}/carts/:cartId/items/:id`, () => HttpResponse.json(fixtures.cart)),
- http.delete(`${API_PREFIX}/carts/:cartId/items/:id`, () =>
- HttpResponse.json(fixtures.cart)
- ),
+ http.delete(`${API_PREFIX}/carts/:cartId/items/:id`, () => HttpResponse.json(fixtures.cart)),
// Carts > Discount Codes
- http.post(`${API_PREFIX}/carts/:cartId/discount_codes`, () =>
- HttpResponse.json(fixtures.cart)
- ),
+ http.post(`${API_PREFIX}/carts/:cartId/discount_codes`, () => HttpResponse.json(fixtures.cart)),
http.delete(`${API_PREFIX}/carts/:cartId/discount_codes/:code`, () =>
- HttpResponse.json(fixtures.cart)
+ HttpResponse.json(fixtures.cart),
),
// Carts > Gift Cards
- http.post(`${API_PREFIX}/carts/:cartId/gift_cards`, () =>
- HttpResponse.json(fixtures.cart)
- ),
+ http.post(`${API_PREFIX}/carts/:cartId/gift_cards`, () => HttpResponse.json(fixtures.cart)),
- http.delete(`${API_PREFIX}/carts/:cartId/gift_cards/:id`, () =>
- HttpResponse.json(fixtures.cart)
- ),
+ http.delete(`${API_PREFIX}/carts/:cartId/gift_cards/:id`, () => HttpResponse.json(fixtures.cart)),
// Carts > Fulfillments
http.patch(`${API_PREFIX}/carts/:cartId/fulfillments/:id`, () =>
- HttpResponse.json(fixtures.cart)
+ HttpResponse.json(fixtures.cart),
),
// Carts > Payments
http.post(`${API_PREFIX}/carts/:cartId/payments`, () =>
- HttpResponse.json({
- id: 'py_2',
- payment_method_id: 'pm_2',
- state: 'checkout',
- response_code: null,
- number: 'P5678',
- amount: '19.99',
- display_amount: '$19.99',
- source_type: null,
- source_id: null,
- source: null,
- created_at: '2026-02-17T00:00:00.000Z',
- updated_at: '2026-02-17T00:00:00.000Z',
- payment_method: { id: 'pm_2', name: 'Check', description: null, type: 'Spree::PaymentMethod::Check', session_required: false },
- }, { status: 201 })
+ HttpResponse.json(
+ {
+ id: 'py_2',
+ payment_method_id: 'pm_2',
+ state: 'checkout',
+ response_code: null,
+ number: 'P5678',
+ amount: '19.99',
+ display_amount: '$19.99',
+ source_type: null,
+ source_id: null,
+ source: null,
+ created_at: '2026-02-17T00:00:00.000Z',
+ updated_at: '2026-02-17T00:00:00.000Z',
+ payment_method: {
+ id: 'pm_2',
+ name: 'Check',
+ description: null,
+ type: 'Spree::PaymentMethod::Check',
+ session_required: false,
+ },
+ },
+ { status: 201 },
+ ),
),
// Carts > Payment Sessions
http.post(`${API_PREFIX}/carts/:cartId/payment_sessions`, () =>
- HttpResponse.json({
- id: 'ps_1',
- status: 'pending',
- amount: '99.99',
- currency: 'USD',
- external_id: 'bogus_abc123',
- external_data: { client_secret: 'bogus_secret_xyz' },
- expires_at: null,
- customer_external_id: null,
- payment_method_id: 'pm_1',
- order_id: 'order_1',
- created_at: '2026-02-13T00:00:00.000Z',
- updated_at: '2026-02-13T00:00:00.000Z',
- payment_method: { id: 'pm_1', name: 'Credit Card', description: null, type: 'Spree::Gateway::Bogus' },
- }, { status: 201 })
+ HttpResponse.json(
+ {
+ id: 'ps_1',
+ status: 'pending',
+ amount: '99.99',
+ currency: 'USD',
+ external_id: 'bogus_abc123',
+ external_data: { client_secret: 'bogus_secret_xyz' },
+ expires_at: null,
+ customer_external_id: null,
+ payment_method_id: 'pm_1',
+ order_id: 'order_1',
+ created_at: '2026-02-13T00:00:00.000Z',
+ updated_at: '2026-02-13T00:00:00.000Z',
+ payment_method: {
+ id: 'pm_1',
+ name: 'Credit Card',
+ description: null,
+ type: 'Spree::Gateway::Bogus',
+ },
+ },
+ { status: 201 },
+ ),
),
http.get(`${API_PREFIX}/carts/:cartId/payment_sessions/:id`, () =>
@@ -313,8 +313,13 @@ export const handlers = [
order_id: 'order_1',
created_at: '2026-02-13T00:00:00.000Z',
updated_at: '2026-02-13T00:00:00.000Z',
- payment_method: { id: 'pm_1', name: 'Credit Card', description: null, type: 'Spree::Gateway::Bogus' },
- })
+ payment_method: {
+ id: 'pm_1',
+ name: 'Credit Card',
+ description: null,
+ type: 'Spree::Gateway::Bogus',
+ },
+ }),
),
http.patch(`${API_PREFIX}/carts/:cartId/payment_sessions/:id/complete`, () =>
@@ -331,8 +336,13 @@ export const handlers = [
order_id: 'order_1',
created_at: '2026-02-13T00:00:00.000Z',
updated_at: '2026-02-13T00:00:00.000Z',
- payment_method: { id: 'pm_1', name: 'Credit Card', description: null, type: 'Spree::Gateway::Bogus' },
- })
+ payment_method: {
+ id: 'pm_1',
+ name: 'Credit Card',
+ description: null,
+ type: 'Spree::Gateway::Bogus',
+ },
+ }),
),
http.patch(`${API_PREFIX}/carts/:cartId/payment_sessions/:id`, () =>
@@ -349,100 +359,95 @@ export const handlers = [
order_id: 'order_1',
created_at: '2026-02-13T00:00:00.000Z',
updated_at: '2026-02-13T00:00:00.000Z',
- payment_method: { id: 'pm_1', name: 'Credit Card', description: null, type: 'Spree::Gateway::Bogus' },
- })
+ payment_method: {
+ id: 'pm_1',
+ name: 'Credit Card',
+ description: null,
+ type: 'Spree::Gateway::Bogus',
+ },
+ }),
),
// Carts > Store Credits
- http.post(`${API_PREFIX}/carts/:cartId/store_credits`, () =>
- HttpResponse.json(fixtures.cart)
- ),
+ http.post(`${API_PREFIX}/carts/:cartId/store_credits`, () => HttpResponse.json(fixtures.cart)),
- http.delete(`${API_PREFIX}/carts/:cartId/store_credits`, () =>
- HttpResponse.json(fixtures.cart)
- ),
+ http.delete(`${API_PREFIX}/carts/:cartId/store_credits`, () => HttpResponse.json(fixtures.cart)),
// Orders (read-only, single lookup)
- http.get(`${API_PREFIX}/orders/:id`, () =>
- HttpResponse.json(fixtures.order)
- ),
+ http.get(`${API_PREFIX}/orders/:id`, () => HttpResponse.json(fixtures.order)),
// Customer
- http.get(`${API_PREFIX}/customers/me`, () =>
- HttpResponse.json(fixtures.user)
- ),
+ http.get(`${API_PREFIX}/customers/me`, () => HttpResponse.json(fixtures.user)),
http.patch(`${API_PREFIX}/customers/me`, () =>
- HttpResponse.json({ ...fixtures.user, first_name: 'Updated' })
+ HttpResponse.json({ ...fixtures.user, first_name: 'Updated' }),
),
// Customer > Orders
http.get(`${API_PREFIX}/customers/me/orders`, () =>
- HttpResponse.json({ data: [fixtures.order], meta: paginationMeta })
+ HttpResponse.json({ data: [fixtures.order], meta: paginationMeta }),
),
- http.get(`${API_PREFIX}/customers/me/orders/:id`, () =>
- HttpResponse.json(fixtures.order)
- ),
+ http.get(`${API_PREFIX}/customers/me/orders/:id`, () => HttpResponse.json(fixtures.order)),
// Customer > Addresses
http.get(`${API_PREFIX}/customers/me/addresses`, () =>
- HttpResponse.json({ data: [fixtures.address], meta: paginationMeta })
+ HttpResponse.json({ data: [fixtures.address], meta: paginationMeta }),
),
- http.get(`${API_PREFIX}/customers/me/addresses/:id`, () =>
- HttpResponse.json(fixtures.address)
- ),
+ http.get(`${API_PREFIX}/customers/me/addresses/:id`, () => HttpResponse.json(fixtures.address)),
- http.post(`${API_PREFIX}/customers/me/addresses`, () =>
- HttpResponse.json(fixtures.address)
- ),
+ http.post(`${API_PREFIX}/customers/me/addresses`, () => HttpResponse.json(fixtures.address)),
http.patch(`${API_PREFIX}/customers/me/addresses/:id`, () =>
- HttpResponse.json({ ...fixtures.address, city: 'Updated City' })
+ HttpResponse.json({ ...fixtures.address, city: 'Updated City' }),
),
- http.delete(`${API_PREFIX}/customers/me/addresses/:id`, () =>
- new HttpResponse(null, { status: 204 })
+ http.delete(
+ `${API_PREFIX}/customers/me/addresses/:id`,
+ () => new HttpResponse(null, { status: 204 }),
),
// Customer > Credit Cards
http.get(`${API_PREFIX}/customers/me/credit_cards`, () =>
- HttpResponse.json({ data: [], meta: paginationMeta })
+ HttpResponse.json({ data: [], meta: paginationMeta }),
),
http.get(`${API_PREFIX}/customers/me/credit_cards/:id`, () =>
- HttpResponse.json({ id: 'cc_1', last4: '1234' })
+ HttpResponse.json({ id: 'cc_1', last4: '1234' }),
),
- http.delete(`${API_PREFIX}/customers/me/credit_cards/:id`, () =>
- new HttpResponse(null, { status: 204 })
+ http.delete(
+ `${API_PREFIX}/customers/me/credit_cards/:id`,
+ () => new HttpResponse(null, { status: 204 }),
),
// Customer > Gift Cards
http.get(`${API_PREFIX}/customers/me/gift_cards`, () =>
- HttpResponse.json({ data: [], meta: paginationMeta })
+ HttpResponse.json({ data: [], meta: paginationMeta }),
),
http.get(`${API_PREFIX}/customers/me/gift_cards/:id`, () =>
- HttpResponse.json({ id: 'gc_1', code: 'GIFT123', balance: '50.00' })
+ HttpResponse.json({ id: 'gc_1', code: 'GIFT123', balance: '50.00' }),
),
// Customer > Store Credits
http.get(`${API_PREFIX}/customers/me/store_credits`, () =>
HttpResponse.json({
- data: [{
- id: 'credit_1',
- amount: '100.00',
- amount_used: '25.00',
- amount_remaining: '75.00',
- display_amount: '$100.00',
- display_amount_used: '$25.00',
- display_amount_remaining: '$75.00',
- currency: 'USD',
- }],
+ data: [
+ {
+ id: 'credit_1',
+ amount: '100.00',
+ amount_used: '25.00',
+ amount_remaining: '75.00',
+ display_amount: '$100.00',
+ display_amount_used: '$25.00',
+ display_amount_remaining: '$75.00',
+ currency: 'USD',
+ },
+ ],
meta: paginationMeta,
- })
+ }),
),
http.get(`${API_PREFIX}/customers/me/store_credits/:id`, () =>
@@ -455,25 +460,33 @@ export const handlers = [
display_amount_used: '$25.00',
display_amount_remaining: '$75.00',
currency: 'USD',
- })
+ }),
),
// Customer > Payment Setup Sessions
http.post(`${API_PREFIX}/customers/me/payment_setup_sessions`, () =>
- HttpResponse.json({
- id: 'pss_1',
- status: 'pending',
- external_id: 'seti_abc123',
- external_client_secret: 'seti_secret_xyz',
- external_data: { client_secret: 'seti_secret_xyz' },
- payment_method_id: 'pm_1',
- payment_source_id: null,
- payment_source_type: null,
- customer_id: 'user_1',
- created_at: '2026-02-18T00:00:00.000Z',
- updated_at: '2026-02-18T00:00:00.000Z',
- payment_method: { id: 'pm_1', name: 'Credit Card', description: null, type: 'Spree::Gateway::Bogus' },
- }, { status: 201 })
+ HttpResponse.json(
+ {
+ id: 'pss_1',
+ status: 'pending',
+ external_id: 'seti_abc123',
+ external_client_secret: 'seti_secret_xyz',
+ external_data: { client_secret: 'seti_secret_xyz' },
+ payment_method_id: 'pm_1',
+ payment_source_id: null,
+ payment_source_type: null,
+ customer_id: 'user_1',
+ created_at: '2026-02-18T00:00:00.000Z',
+ updated_at: '2026-02-18T00:00:00.000Z',
+ payment_method: {
+ id: 'pm_1',
+ name: 'Credit Card',
+ description: null,
+ type: 'Spree::Gateway::Bogus',
+ },
+ },
+ { status: 201 },
+ ),
),
http.get(`${API_PREFIX}/customers/me/payment_setup_sessions/:id`, () =>
@@ -489,8 +502,13 @@ export const handlers = [
customer_id: 'user_1',
created_at: '2026-02-18T00:00:00.000Z',
updated_at: '2026-02-18T00:00:00.000Z',
- payment_method: { id: 'pm_1', name: 'Credit Card', description: null, type: 'Spree::Gateway::Bogus' },
- })
+ payment_method: {
+ id: 'pm_1',
+ name: 'Credit Card',
+ description: null,
+ type: 'Spree::Gateway::Bogus',
+ },
+ }),
),
http.patch(`${API_PREFIX}/customers/me/payment_setup_sessions/:id/complete`, () =>
@@ -506,70 +524,93 @@ export const handlers = [
customer_id: 'user_1',
created_at: '2026-02-18T00:00:00.000Z',
updated_at: '2026-02-18T00:00:00.000Z',
- payment_method: { id: 'pm_1', name: 'Credit Card', description: null, type: 'Spree::Gateway::Bogus' },
- })
+ payment_method: {
+ id: 'pm_1',
+ name: 'Credit Card',
+ description: null,
+ type: 'Spree::Gateway::Bogus',
+ },
+ }),
),
// Password Resets
http.post(`${API_PREFIX}/password_resets`, () =>
HttpResponse.json(
- { message: 'If an account exists for that email, password reset instructions have been sent.' },
- { status: 202 }
- )
+ {
+ message: 'If an account exists for that email, password reset instructions have been sent.',
+ },
+ { status: 202 },
+ ),
),
http.patch(`${API_PREFIX}/password_resets/:token`, () =>
- HttpResponse.json({ token: 'new-jwt-token', user: fixtures.user })
+ HttpResponse.json({ token: 'new-jwt-token', user: fixtures.user }),
),
// Policies
http.get(`${API_PREFIX}/policies`, () =>
HttpResponse.json({
data: [
- { id: 'pol_1', name: 'Return Policy', slug: 'return-policy', body: 'Return within 30 days.', body_html: '<p>Return within 30 days.</p>', created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z' },
- { id: 'pol_2', name: 'Privacy Policy', slug: 'privacy-policy', body: 'We respect your privacy.', body_html: '<p>We respect your privacy.</p>', created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z' },
- ]
- })
+ {
+ id: 'pol_1',
+ name: 'Return Policy',
+ slug: 'return-policy',
+ body: 'Return within 30 days.',
+ body_html: '<p>Return within 30 days.</p>',
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ },
+ {
+ id: 'pol_2',
+ name: 'Privacy Policy',
+ slug: 'privacy-policy',
+ body: 'We respect your privacy.',
+ body_html: '<p>We respect your privacy.</p>',
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ },
+ ],
+ }),
),
http.get(`${API_PREFIX}/policies/:id`, () =>
HttpResponse.json({
- id: 'pol_1', name: 'Return Policy', slug: 'return-policy', body: 'Return within 30 days.', body_html: '<p>Return within 30 days.</p>',
- created_at: '2026-01-01T00:00:00Z', updated_at: '2026-01-01T00:00:00Z'
- })
+ id: 'pol_1',
+ name: 'Return Policy',
+ slug: 'return-policy',
+ body: 'Return within 30 days.',
+ body_html: '<p>Return within 30 days.</p>',
+ created_at: '2026-01-01T00:00:00Z',
+ updated_at: '2026-01-01T00:00:00Z',
+ }),
),
// Wishlists
http.get(`${API_PREFIX}/wishlists`, () =>
- HttpResponse.json({ data: [fixtures.wishlist], meta: paginationMeta })
+ HttpResponse.json({ data: [fixtures.wishlist], meta: paginationMeta }),
),
- http.get(`${API_PREFIX}/wishlists/:id`, () =>
- HttpResponse.json(fixtures.wishlist)
- ),
+ http.get(`${API_PREFIX}/wishlists/:id`, () => HttpResponse.json(fixtures.wishlist)),
- http.post(`${API_PREFIX}/wishlists`, () =>
- HttpResponse.json(fixtures.wishlist)
- ),
+ http.post(`${API_PREFIX}/wishlists`, () => HttpResponse.json(fixtures.wishlist)),
http.patch(`${API_PREFIX}/wishlists/:id`, () =>
- HttpResponse.json({ ...fixtures.wishlist, name: 'Updated Wishlist' })
+ HttpResponse.json({ ...fixtures.wishlist, name: 'Updated Wishlist' }),
),
- http.delete(`${API_PREFIX}/wishlists/:id`, () =>
- new HttpResponse(null, { status: 204 })
- ),
+ http.delete(`${API_PREFIX}/wishlists/:id`, () => new HttpResponse(null, { status: 204 })),
// Wishlist Items
http.post(`${API_PREFIX}/wishlists/:wishlistId/items`, () =>
- HttpResponse.json(fixtures.wishlistItem)
+ HttpResponse.json(fixtures.wishlistItem),
),
http.patch(`${API_PREFIX}/wishlists/:wishlistId/items/:id`, () =>
- HttpResponse.json({ ...fixtures.wishlistItem, quantity: 3 })
+ HttpResponse.json({ ...fixtures.wishlistItem, quantity: 3 }),
),
- http.delete(`${API_PREFIX}/wishlists/:wishlistId/items/:id`, () =>
- new HttpResponse(null, { status: 204 })
+ http.delete(
+ `${API_PREFIX}/wishlists/:wishlistId/items/:id`,
+ () => new HttpResponse(null, { status: 204 }),
),
-];
+]
diff --git a/packages/sdk/tests/mocks/server.ts b/packages/sdk/tests/mocks/server.ts
index e52fee0a67..86f7d6154a 100644
--- a/packages/sdk/tests/mocks/server.ts
+++ b/packages/sdk/tests/mocks/server.ts
@@ -1,4 +1,4 @@
-import { setupServer } from 'msw/node';
-import { handlers } from './handlers';
+import { setupServer } from 'msw/node'
+import { handlers } from './handlers'
-export const server = setupServer(...handlers);
+export const server = setupServer(...handlers)
diff --git a/packages/sdk/tests/orders.test.ts b/packages/sdk/tests/orders.test.ts
index 80e504d7f7..8fdd8e20d1 100644
--- a/packages/sdk/tests/orders.test.ts
+++ b/packages/sdk/tests/orders.test.ts
@@ -1,37 +1,39 @@
-import { describe, it, expect, beforeAll } from 'vitest';
-import { createTestClient } from './helpers';
-import type { Client } from '../src';
+import { beforeAll, describe, expect, it } from 'vitest'
+import type { Client } from '../src'
+import { createTestClient } from './helpers'
describe('orders', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
- const opts = { token: 'user-jwt' };
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
+ const opts = { token: 'user-jwt' }
describe('get', () => {
it('returns an order by prefixed ID', async () => {
- const result = await client.orders.get('or_abc123', undefined, opts);
- expect(result.id).toBe('or_1');
- expect(result.completed_at).toBeDefined();
- });
+ const result = await client.orders.get('or_abc123', undefined, opts)
+ expect(result.id).toBe('or_1')
+ expect(result.completed_at).toBeDefined()
+ })
it('works with order token for guest access', async () => {
const result = await client.orders.get('or_abc123', undefined, {
spreeToken: 'guest-token',
- });
- expect(result).toBeDefined();
- });
- });
+ })
+ expect(result).toBeDefined()
+ })
+ })
describe('customer.orders', () => {
it('lists customer orders', async () => {
- const result = await client.customer.orders.list(undefined, opts);
- expect(result.data).toHaveLength(1);
- expect(result.meta.page).toBe(1);
- });
+ const result = await client.customer.orders.list(undefined, opts)
+ expect(result.data).toHaveLength(1)
+ expect(result.meta.page).toBe(1)
+ })
it('gets a customer order by ID', async () => {
- const result = await client.customer.orders.get('or_abc123', undefined, opts);
- expect(result.id).toBe('or_1');
- });
- });
-});
+ const result = await client.customer.orders.get('or_abc123', undefined, opts)
+ expect(result.id).toBe('or_1')
+ })
+ })
+})
diff --git a/packages/sdk/tests/params.test.ts b/packages/sdk/tests/params.test.ts
index 29b0fa5783..657f24b81b 100644
--- a/packages/sdk/tests/params.test.ts
+++ b/packages/sdk/tests/params.test.ts
@@ -1,95 +1,95 @@
-import { describe, it, expect } from 'vitest';
-import { transformListParams } from '@spree/sdk-core';
+import { transformListParams } from '@spree/sdk-core'
+import { describe, expect, it } from 'vitest'
describe('transformListParams', () => {
it('passes through pagination params unchanged', () => {
- const result = transformListParams({ page: 2, limit: 10 });
- expect(result).toEqual({ page: 2, limit: 10 });
- });
+ const result = transformListParams({ page: 2, limit: 10 })
+ expect(result).toEqual({ page: 2, limit: 10 })
+ })
it('joins expand array into comma-separated string', () => {
- const result = transformListParams({ expand: ['variants', 'media'] });
- expect(result).toEqual({ expand: 'variants,media' });
- });
+ const result = transformListParams({ expand: ['variants', 'media'] })
+ expect(result).toEqual({ expand: 'variants,media' })
+ })
it('joins single-element expand array', () => {
- const result = transformListParams({ expand: ['variants'] });
- expect(result).toEqual({ expand: 'variants' });
- });
+ const result = transformListParams({ expand: ['variants'] })
+ expect(result).toEqual({ expand: 'variants' })
+ })
it('handles empty expand array', () => {
- const result = transformListParams({ expand: [] });
- expect(result).toEqual({ expand: '' });
- });
+ const result = transformListParams({ expand: [] })
+ expect(result).toEqual({ expand: '' })
+ })
it('passes through descending sort param unchanged', () => {
- const result = transformListParams({ sort: '-price' });
- expect(result).toEqual({ sort: '-price' });
- });
+ const result = transformListParams({ sort: '-price' })
+ expect(result).toEqual({ sort: '-price' })
+ })
it('passes through ascending sort param unchanged', () => {
- const result = transformListParams({ sort: 'name' });
- expect(result).toEqual({ sort: 'name' });
- });
+ const result = transformListParams({ sort: 'name' })
+ expect(result).toEqual({ sort: 'name' })
+ })
it('wraps filter keys in q[...]', () => {
const result = transformListParams({
name_cont: 'shirt',
price_gte: 20,
price_lte: 100,
- });
+ })
expect(result).toEqual({
'q[name_cont]': 'shirt',
'q[price_gte]': 20,
'q[price_lte]': 100,
- });
- });
+ })
+ })
it('transforms search', () => {
- const result = transformListParams({ search: 'shirt' });
- expect(result).toEqual({ 'q[search]': 'shirt' });
- });
+ const result = transformListParams({ search: 'shirt' })
+ expect(result).toEqual({ 'q[search]': 'shirt' })
+ })
it('passes through already-wrapped q[...] keys (backward compat)', () => {
- const result = transformListParams({ 'q[name_cont]': 'shirt' });
- expect(result).toEqual({ 'q[name_cont]': 'shirt' });
- });
+ const result = transformListParams({ 'q[name_cont]': 'shirt' })
+ expect(result).toEqual({ 'q[name_cont]': 'shirt' })
+ })
it('skips undefined values', () => {
- const result = transformListParams({ name_cont: undefined, page: 1 });
- expect(result).toEqual({ page: 1 });
- });
+ const result = transformListParams({ name_cont: undefined, page: 1 })
+ expect(result).toEqual({ page: 1 })
+ })
it('wraps array values with [] suffix automatically', () => {
const result = transformListParams({
with_option_value_ids: ['optval_abc', 'optval_def'],
- });
+ })
expect(result).toEqual({
'q[with_option_value_ids][]': ['optval_abc', 'optval_def'],
- });
- });
+ })
+ })
it('handles array values even when key already has [] suffix', () => {
const result = transformListParams({
'with_option_value_ids[]': ['optval_abc'],
- });
+ })
expect(result).toEqual({
'q[with_option_value_ids][]': ['optval_abc'],
- });
- });
+ })
+ })
it('joins fields array into comma-separated string', () => {
- const result = transformListParams({ fields: ['name', 'slug', 'price'] });
- expect(result).toEqual({ fields: 'name,slug,price' });
- });
+ const result = transformListParams({ fields: ['name', 'slug', 'price'] })
+ expect(result).toEqual({ fields: 'name,slug,price' })
+ })
it('passes fields through without wrapping in q[...]', () => {
- const result = transformListParams({ fields: ['name', 'slug'], name_cont: 'shirt' });
+ const result = transformListParams({ fields: ['name', 'slug'], name_cont: 'shirt' })
expect(result).toEqual({
fields: 'name,slug',
'q[name_cont]': 'shirt',
- });
- });
+ })
+ })
it('handles a full combined query', () => {
const result = transformListParams({
@@ -100,7 +100,7 @@ describe('transformListParams', () => {
name_cont: 'shirt',
price_gte: 20,
in_category: 'ctg_abc123',
- });
+ })
expect(result).toEqual({
page: 1,
limit: 12,
@@ -109,6 +109,6 @@ describe('transformListParams', () => {
'q[name_cont]': 'shirt',
'q[price_gte]': 20,
'q[in_category]': 'ctg_abc123',
- });
- });
-});
+ })
+ })
+})
diff --git a/packages/sdk/tests/password-resets.test.ts b/packages/sdk/tests/password-resets.test.ts
index 9ff254a96f..cfe63cfb81 100644
--- a/packages/sdk/tests/password-resets.test.ts
+++ b/packages/sdk/tests/password-resets.test.ts
@@ -1,94 +1,102 @@
-import { describe, it, expect } from 'vitest';
-import { server } from './mocks/server';
-import { http, HttpResponse } from 'msw';
-import { createTestClient, TEST_BASE_URL } from './helpers';
+import { HttpResponse, http } from 'msw'
+import { describe, expect, it } from 'vitest'
+import { createTestClient, TEST_BASE_URL } from './helpers'
+import { server } from './mocks/server'
-const API_PREFIX = `${TEST_BASE_URL}/api/v3/store`;
+const API_PREFIX = `${TEST_BASE_URL}/api/v3/store`
describe('passwordResets', () => {
describe('create (request password reset)', () => {
it('returns a message on success', async () => {
- const client = createTestClient();
+ const client = createTestClient()
const result = await client.passwordResets.create({
- });
+ })
- expect(result.message).toBeDefined();
- });
+ expect(result.message).toBeDefined()
+ })
it('sends email in request body', async () => {
- let capturedBody: Record<string, unknown> = {};
+ let capturedBody: Record<string, unknown> = {}
server.use(
http.post(`${API_PREFIX}/password_resets`, async ({ request }) => {
- capturedBody = await request.json() as Record<string, unknown>;
+ capturedBody = (await request.json()) as Record<string, unknown>
return HttpResponse.json(
- { message: 'If an account exists for that email, password reset instructions have been sent.' },
- { status: 202 }
- );
- })
- );
+ {
+ message:
+ 'If an account exists for that email, password reset instructions have been sent.',
+ },
+ { status: 202 },
+ )
+ }),
+ )
- const client = createTestClient();
- await client.passwordResets.create({ email: '[email protected]' });
+ const client = createTestClient()
+ await client.passwordResets.create({ email: '[email protected]' })
- expect(capturedBody.email).toBe('[email protected]');
- });
- });
+ expect(capturedBody.email).toBe('[email protected]')
+ })
+ })
describe('update (reset password with token)', () => {
it('returns auth tokens on successful reset', async () => {
- const client = createTestClient();
- const result = await client.passwordResets.update(
- 'valid-reset-token',
- {
- password: 'newsecurepassword',
- password_confirmation: 'newsecurepassword',
- }
- );
+ const client = createTestClient()
+ const result = await client.passwordResets.update('valid-reset-token', {
+ password: 'newsecurepassword',
+ password_confirmation: 'newsecurepassword',
+ })
- expect(result.token).toBe('new-jwt-token');
- expect(result.user.email).toBe('[email protected]');
- });
+ expect(result.token).toBe('new-jwt-token')
+ expect(result.user.email).toBe('[email protected]')
+ })
it('sends token in URL path', async () => {
- let capturedUrl = '';
+ let capturedUrl = ''
server.use(
http.patch(`${API_PREFIX}/password_resets/:token`, ({ request }) => {
- capturedUrl = request.url;
- return HttpResponse.json({ token: 'new-jwt-token', user: { id: 'user_1', email: '[email protected]', first_name: null, last_name: null } });
- })
- );
+ capturedUrl = request.url
+ return HttpResponse.json({
+ token: 'new-jwt-token',
+ user: { id: 'user_1', email: '[email protected]', first_name: null, last_name: null },
+ })
+ }),
+ )
- const client = createTestClient();
+ const client = createTestClient()
await client.passwordResets.update('my-reset-token', {
password: 'newsecurepassword',
password_confirmation: 'newsecurepassword',
- });
+ })
- expect(capturedUrl).toContain('/password_resets/my-reset-token');
- });
+ expect(capturedUrl).toContain('/password_resets/my-reset-token')
+ })
it('throws SpreeError on invalid token', async () => {
server.use(
http.patch(`${API_PREFIX}/password_resets/:token`, () =>
HttpResponse.json(
- { error: { code: 'password_reset_token_invalid', message: 'Password reset token is invalid or has expired.' } },
- { status: 422 }
- )
- )
- );
+ {
+ error: {
+ code: 'password_reset_token_invalid',
+ message: 'Password reset token is invalid or has expired.',
+ },
+ },
+ { status: 422 },
+ ),
+ ),
+ )
- const client = createTestClient();
+ const client = createTestClient()
try {
await client.passwordResets.update('expired-token', {
password: 'newsecurepassword',
password_confirmation: 'newsecurepassword',
- });
- expect.unreachable('Should have thrown');
+ })
+ expect.unreachable('Should have thrown')
} catch (error: any) {
- expect(error.code).toBe('password_reset_token_invalid');
- expect(error.status).toBe(422);
+ expect(error.code).toBe('password_reset_token_invalid')
+ expect(error.status).toBe(422)
}
- });
- });
-});
+ })
+ })
+})
diff --git a/packages/sdk/tests/payment-sessions.test.ts b/packages/sdk/tests/payment-sessions.test.ts
index 7e43cef9e8..d91daa3ea2 100644
--- a/packages/sdk/tests/payment-sessions.test.ts
+++ b/packages/sdk/tests/payment-sessions.test.ts
@@ -1,46 +1,48 @@
-import { describe, it, expect, beforeAll } from 'vitest';
-import { createTestClient } from './helpers';
-import type { Client } from '../src';
+import { beforeAll, describe, expect, it } from 'vitest'
+import type { Client } from '../src'
+import { createTestClient } from './helpers'
describe('paymentSessions', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
- const opts = { token: 'user-jwt' };
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
+ const opts = { token: 'user-jwt' }
describe('create', () => {
it('creates a payment session', async () => {
const result = await client.carts.paymentSessions.create(
'cart_1',
{ payment_method_id: 'pm_1' },
- opts
- );
- expect(result.id).toBe('ps_1');
- expect(result.status).toBe('pending');
- expect(result.payment_method_id).toBe('pm_1');
- expect(result.order_id).toBe('order_1');
- expect(result.external_data).toHaveProperty('client_secret');
- });
+ opts,
+ )
+ expect(result.id).toBe('ps_1')
+ expect(result.status).toBe('pending')
+ expect(result.payment_method_id).toBe('pm_1')
+ expect(result.order_id).toBe('order_1')
+ expect(result.external_data).toHaveProperty('client_secret')
+ })
it('accepts optional amount and external_data', async () => {
const result = await client.carts.paymentSessions.create(
'cart_1',
{ payment_method_id: 'pm_1', amount: '50.00', external_data: { channel: 'Web' } },
- opts
- );
- expect(result.id).toBe('ps_1');
- });
- });
+ opts,
+ )
+ expect(result.id).toBe('ps_1')
+ })
+ })
describe('get', () => {
it('returns a payment session by ID', async () => {
- const result = await client.carts.paymentSessions.get('cart_1', 'ps_1', opts);
- expect(result.id).toBe('ps_1');
- expect(result.status).toBe('pending');
- expect(result.amount).toBe('99.99');
- expect(result.currency).toBe('USD');
- expect(result.external_id).toBe('bogus_abc123');
- });
- });
+ const result = await client.carts.paymentSessions.get('cart_1', 'ps_1', opts)
+ expect(result.id).toBe('ps_1')
+ expect(result.status).toBe('pending')
+ expect(result.amount).toBe('99.99')
+ expect(result.currency).toBe('USD')
+ expect(result.external_id).toBe('bogus_abc123')
+ })
+ })
describe('update', () => {
it('updates a payment session', async () => {
@@ -48,12 +50,12 @@ describe('paymentSessions', () => {
'cart_1',
'ps_1',
{ amount: '50.00' },
- opts
- );
- expect(result.id).toBe('ps_1');
- expect(result.amount).toBe('50.00');
- });
- });
+ opts,
+ )
+ expect(result.id).toBe('ps_1')
+ expect(result.amount).toBe('50.00')
+ })
+ })
describe('complete', () => {
it('completes a payment session', async () => {
@@ -61,20 +63,15 @@ describe('paymentSessions', () => {
'cart_1',
'ps_1',
{ session_result: 'success' },
- opts
- );
- expect(result.id).toBe('ps_1');
- expect(result.status).toBe('completed');
- });
+ opts,
+ )
+ expect(result.id).toBe('ps_1')
+ expect(result.status).toBe('completed')
+ })
it('completes without params', async () => {
- const result = await client.carts.paymentSessions.complete(
- 'cart_1',
- 'ps_1',
- undefined,
- opts
- );
- expect(result.status).toBe('completed');
- });
- });
-});
+ const result = await client.carts.paymentSessions.complete('cart_1', 'ps_1', undefined, opts)
+ expect(result.status).toBe('completed')
+ })
+ })
+})
diff --git a/packages/sdk/tests/payment-setup-sessions.test.ts b/packages/sdk/tests/payment-setup-sessions.test.ts
index 0af7d89e7a..cdd350f732 100644
--- a/packages/sdk/tests/payment-setup-sessions.test.ts
+++ b/packages/sdk/tests/payment-setup-sessions.test.ts
@@ -1,66 +1,61 @@
-import { describe, it, expect, beforeAll } from 'vitest';
-import { createTestClient } from './helpers';
-import type { Client } from '../src';
+import { beforeAll, describe, expect, it } from 'vitest'
+import type { Client } from '../src'
+import { createTestClient } from './helpers'
describe('paymentSetupSessions', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
- const opts = { token: 'user-jwt' };
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
+ const opts = { token: 'user-jwt' }
describe('create', () => {
it('creates a payment setup session', async () => {
const result = await client.customer.paymentSetupSessions.create(
{ payment_method_id: 'pm_1' },
- opts
- );
- expect(result.id).toBe('pss_1');
- expect(result.status).toBe('pending');
- expect(result.payment_method_id).toBe('pm_1');
- expect(result.external_client_secret).toBe('seti_secret_xyz');
- });
+ opts,
+ )
+ expect(result.id).toBe('pss_1')
+ expect(result.status).toBe('pending')
+ expect(result.payment_method_id).toBe('pm_1')
+ expect(result.external_client_secret).toBe('seti_secret_xyz')
+ })
it('accepts optional external_data', async () => {
const result = await client.customer.paymentSetupSessions.create(
{ payment_method_id: 'pm_1', external_data: { channel: 'Web' } },
- opts
- );
- expect(result.id).toBe('pss_1');
- });
- });
+ opts,
+ )
+ expect(result.id).toBe('pss_1')
+ })
+ })
describe('get', () => {
it('returns a payment setup session by ID', async () => {
- const result = await client.customer.paymentSetupSessions.get(
- 'pss_1',
- opts
- );
- expect(result.id).toBe('pss_1');
- expect(result.status).toBe('pending');
- expect(result.external_id).toBe('seti_abc123');
- expect(result.customer_id).toBe('user_1');
- });
- });
+ const result = await client.customer.paymentSetupSessions.get('pss_1', opts)
+ expect(result.id).toBe('pss_1')
+ expect(result.status).toBe('pending')
+ expect(result.external_id).toBe('seti_abc123')
+ expect(result.customer_id).toBe('user_1')
+ })
+ })
describe('complete', () => {
it('completes a payment setup session', async () => {
- const result = await client.customer.paymentSetupSessions.complete(
- 'pss_1',
- undefined,
- opts
- );
- expect(result.id).toBe('pss_1');
- expect(result.status).toBe('completed');
- expect(result.payment_source_id).toBe('cc_1');
- expect(result.payment_source_type).toBe('Spree::CreditCard');
- });
+ const result = await client.customer.paymentSetupSessions.complete('pss_1', undefined, opts)
+ expect(result.id).toBe('pss_1')
+ expect(result.status).toBe('completed')
+ expect(result.payment_source_id).toBe('cc_1')
+ expect(result.payment_source_type).toBe('Spree::CreditCard')
+ })
it('completes with external_data', async () => {
const result = await client.customer.paymentSetupSessions.complete(
'pss_1',
{ external_data: { setup_intent_id: 'seti_123' } },
- opts
- );
- expect(result.status).toBe('completed');
- });
- });
-});
+ opts,
+ )
+ expect(result.status).toBe('completed')
+ })
+ })
+})
diff --git a/packages/sdk/tests/payments.test.ts b/packages/sdk/tests/payments.test.ts
index bb484ff13f..208c7a0218 100644
--- a/packages/sdk/tests/payments.test.ts
+++ b/packages/sdk/tests/payments.test.ts
@@ -1,44 +1,46 @@
-import { describe, it, expect, beforeAll } from 'vitest';
-import { createTestClient } from './helpers';
-import type { Client } from '../src';
+import { beforeAll, describe, expect, it } from 'vitest'
+import type { Client } from '../src'
+import { createTestClient } from './helpers'
describe('payments', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
- const opts = { token: 'user-jwt' };
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
+ const opts = { token: 'user-jwt' }
describe('create', () => {
it('creates a payment for a non-session payment method', async () => {
const result = await client.carts.payments.create(
'cart_1',
{ payment_method_id: 'pm_2' },
- opts
- );
- expect(result.id).toBe('py_2');
- expect(result.state).toBe('checkout');
- expect(result.payment_method_id).toBe('pm_2');
- expect(result.source_type).toBeNull();
- expect(result.source).toBeNull();
- });
+ opts,
+ )
+ expect(result.id).toBe('py_2')
+ expect(result.state).toBe('checkout')
+ expect(result.payment_method_id).toBe('pm_2')
+ expect(result.source_type).toBeNull()
+ expect(result.source).toBeNull()
+ })
it('accepts optional amount', async () => {
const result = await client.carts.payments.create(
'cart_1',
{ payment_method_id: 'pm_2', amount: '50.00' },
- opts
- );
- expect(result.id).toBe('py_2');
- });
+ opts,
+ )
+ expect(result.id).toBe('py_2')
+ })
it('includes payment_method association', async () => {
const result = await client.carts.payments.create(
'cart_1',
{ payment_method_id: 'pm_2' },
- opts
- );
- expect(result.payment_method.id).toBe('pm_2');
- expect(result.payment_method.name).toBe('Check');
- expect(result.payment_method.session_required).toBe(false);
- });
- });
-});
+ opts,
+ )
+ expect(result.payment_method.id).toBe('pm_2')
+ expect(result.payment_method.name).toBe('Check')
+ expect(result.payment_method.session_required).toBe(false)
+ })
+ })
+})
diff --git a/packages/sdk/tests/policies.test.ts b/packages/sdk/tests/policies.test.ts
index f31680821a..122fd8ae99 100644
--- a/packages/sdk/tests/policies.test.ts
+++ b/packages/sdk/tests/policies.test.ts
@@ -1,26 +1,28 @@
-import { describe, it, expect, beforeAll } from 'vitest';
-import { createTestClient } from './helpers';
-import type { Client } from '../src';
+import { beforeAll, describe, expect, it } from 'vitest'
+import type { Client } from '../src'
+import { createTestClient } from './helpers'
describe('policies', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
it('lists store policies', async () => {
- const result = await client.policies.list();
- expect(result.data).toHaveLength(2);
- expect(result.data[0].slug).toBe('return-policy');
- expect(result.data[0].name).toBe('Return Policy');
- expect(result.data[0].body).toBe('Return within 30 days.');
- expect(result.data[0].body_html).toBe('<p>Return within 30 days.</p>');
- });
+ const result = await client.policies.list()
+ expect(result.data).toHaveLength(2)
+ expect(result.data[0].slug).toBe('return-policy')
+ expect(result.data[0].name).toBe('Return Policy')
+ expect(result.data[0].body).toBe('Return within 30 days.')
+ expect(result.data[0].body_html).toBe('<p>Return within 30 days.</p>')
+ })
it('gets a policy by slug', async () => {
- const result = await client.policies.get('return-policy');
- expect(result.id).toBe('pol_1');
- expect(result.name).toBe('Return Policy');
- expect(result.slug).toBe('return-policy');
- expect(result.body).toBe('Return within 30 days.');
- expect(result.body_html).toBe('<p>Return within 30 days.</p>');
- });
-});
+ const result = await client.policies.get('return-policy')
+ expect(result.id).toBe('pol_1')
+ expect(result.name).toBe('Return Policy')
+ expect(result.slug).toBe('return-policy')
+ expect(result.body).toBe('Return within 30 days.')
+ expect(result.body_html).toBe('<p>Return within 30 days.</p>')
+ })
+})
diff --git a/packages/sdk/tests/products.test.ts b/packages/sdk/tests/products.test.ts
index 144a287243..dfc7342e52 100644
--- a/packages/sdk/tests/products.test.ts
+++ b/packages/sdk/tests/products.test.ts
@@ -1,93 +1,95 @@
-import { describe, it, expect, beforeAll } from 'vitest';
-import { createTestClient } from './helpers';
-import { fixtures } from './mocks/handlers';
-import type { Client } from '../src';
+import { beforeAll, describe, expect, it } from 'vitest'
+import type { Client } from '../src'
+import { createTestClient } from './helpers'
+import { fixtures } from './mocks/handlers'
describe('products', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
describe('list', () => {
it('returns paginated products', async () => {
- const result = await client.products.list();
+ const result = await client.products.list()
- expect(result.data).toHaveLength(1);
- expect(result.data[0].name).toBe('Test Product');
- expect(result.meta.page).toBe(1);
- expect(result.meta.count).toBe(1);
- });
+ expect(result.data).toHaveLength(1)
+ expect(result.data[0].name).toBe('Test Product')
+ expect(result.meta.page).toBe(1)
+ expect(result.meta.count).toBe(1)
+ })
it('passes query parameters', async () => {
const result = await client.products.list({
page: 2,
limit: 10,
name_cont: 'shirt',
- });
+ })
// MSW handler returns the same fixture regardless of params,
// but the request is formed correctly (tested via custom fetch in client tests)
- expect(result.data).toBeDefined();
- });
- });
+ expect(result.data).toBeDefined()
+ })
+ })
describe('get', () => {
it('returns a product by slug', async () => {
- const result = await client.products.get('test-product');
+ const result = await client.products.get('test-product')
- expect(result.name).toBe(fixtures.product.name);
- expect(result.slug).toBe('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');
- expect(result.id).toBe('prod_1');
- });
+ const result = await client.products.get('prod_1')
+ expect(result.id).toBe('prod_1')
+ })
it('sends expand array as comma-separated query param', async () => {
- let capturedUrl = '';
- const { createClient } = await import('../src');
+ let capturedUrl = ''
+ const { createClient } = await import('../src')
const customClient = createClient({
baseUrl: 'https://demo.spreecommerce.org',
publishableKey: 'test-key',
fetch: async (url, init) => {
- capturedUrl = url.toString();
- return globalThis.fetch(url, init);
+ capturedUrl = url.toString()
+ return globalThis.fetch(url, init)
},
- });
+ })
await customClient.products.get('test-product', {
expand: ['variants', 'media'],
- });
+ })
- expect(capturedUrl).toContain('expand=variants%2Cmedia');
- });
+ expect(capturedUrl).toContain('expand=variants%2Cmedia')
+ })
it('omits expand param when array is empty', async () => {
- let capturedUrl = '';
- const { createClient } = await import('../src');
+ let capturedUrl = ''
+ const { createClient } = await import('../src')
const customClient = createClient({
baseUrl: 'https://demo.spreecommerce.org',
publishableKey: 'test-key',
fetch: async (url, init) => {
- capturedUrl = url.toString();
- return globalThis.fetch(url, init);
+ capturedUrl = url.toString()
+ return globalThis.fetch(url, init)
},
- });
+ })
- await customClient.products.get('test-product', { expand: [] });
+ await customClient.products.get('test-product', { expand: [] })
- expect(capturedUrl).not.toContain('expand');
- });
- });
+ expect(capturedUrl).not.toContain('expand')
+ })
+ })
describe('filters', () => {
it('returns filter options', async () => {
- const result = await client.products.filters();
-
- expect(result.filters).toBeDefined();
- expect(result.sort_options).toBeDefined();
- expect(result.default_sort).toBe('default');
- expect(result.total_count).toBe(1);
- });
- });
-});
+ const result = await client.products.filters()
+
+ expect(result.filters).toBeDefined()
+ expect(result.sort_options).toBeDefined()
+ expect(result.default_sort).toBe('default')
+ expect(result.total_count).toBe(1)
+ })
+ })
+})
diff --git a/packages/sdk/tests/retry.test.ts b/packages/sdk/tests/retry.test.ts
index 81c261f173..7543fe36a2 100644
--- a/packages/sdk/tests/retry.test.ts
+++ b/packages/sdk/tests/retry.test.ts
@@ -1,248 +1,284 @@
-import { describe, it, expect, vi } from 'vitest';
-import { createClient } from '../src/client';
-import { SpreeError } from '@spree/sdk-core';
+import { SpreeError } from '@spree/sdk-core'
+import { describe, expect, it, vi } from 'vitest'
+import { createClient } from '../src/client'
function jsonResponse(body: object, status = 200, headers: Record<string, string> = {}): Response {
return new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json', ...headers },
- });
+ })
}
-function errorResponse(status: number, code = 'error', message = 'Error', headers: Record<string, string> = {}): Response {
- return new Response(
- JSON.stringify({ error: { code, message } }),
- { status, headers: { 'Content-Type': 'application/json', ...headers } }
- );
+function errorResponse(
+ status: number,
+ code = 'error',
+ message = 'Error',
+ headers: Record<string, string> = {},
+): Response {
+ return new Response(JSON.stringify({ error: { code, message } }), {
+ status,
+ headers: { 'Content-Type': 'application/json', ...headers },
+ })
}
-const paginatedEmpty = { data: [], meta: { page: 1, limit: 25, count: 0, pages: 0, from: 0, to: 0, in: 0, previous: null, next: null } };
+const paginatedEmpty = {
+ data: [],
+ meta: {
+ page: 1,
+ limit: 25,
+ count: 0,
+ pages: 0,
+ from: 0,
+ to: 0,
+ in: 0,
+ previous: null,
+ next: null,
+ },
+}
describe('Retry logic', () => {
- const baseConfig = { baseUrl: 'https://api.test.com', publishableKey: 'pk_test' };
+ const baseConfig = { baseUrl: 'https://api.test.com', publishableKey: 'pk_test' }
describe('GET requests', () => {
it('retries on 500 and succeeds', async () => {
- const mockFetch = vi.fn()
+ const mockFetch = vi
+ .fn()
.mockResolvedValueOnce(errorResponse(500))
- .mockResolvedValueOnce(jsonResponse(paginatedEmpty));
+ .mockResolvedValueOnce(jsonResponse(paginatedEmpty))
- const client = createClient({ ...baseConfig, fetch: mockFetch });
- const result = await client.products.list();
+ const client = createClient({ ...baseConfig, fetch: mockFetch })
+ const result = await client.products.list()
- expect(result).toEqual(paginatedEmpty);
- expect(mockFetch).toHaveBeenCalledTimes(2);
- });
+ expect(result).toEqual(paginatedEmpty)
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ })
it('retries on 429 and succeeds', async () => {
- const mockFetch = vi.fn()
+ const mockFetch = vi
+ .fn()
.mockResolvedValueOnce(errorResponse(429, 'rate_limited', 'Too many requests'))
- .mockResolvedValueOnce(jsonResponse(paginatedEmpty));
+ .mockResolvedValueOnce(jsonResponse(paginatedEmpty))
- const client = createClient({ ...baseConfig, fetch: mockFetch });
- const result = await client.products.list();
+ const client = createClient({ ...baseConfig, fetch: mockFetch })
+ const result = await client.products.list()
- expect(result).toEqual(paginatedEmpty);
- expect(mockFetch).toHaveBeenCalledTimes(2);
- });
+ expect(result).toEqual(paginatedEmpty)
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ })
it('retries on 502, 503, 504', async () => {
- const mockFetch = vi.fn()
+ const mockFetch = vi
+ .fn()
.mockResolvedValueOnce(errorResponse(502))
.mockResolvedValueOnce(errorResponse(503))
- .mockResolvedValueOnce(jsonResponse(paginatedEmpty));
+ .mockResolvedValueOnce(jsonResponse(paginatedEmpty))
- const client = createClient({ ...baseConfig, fetch: mockFetch });
- const result = await client.products.list();
+ const client = createClient({ ...baseConfig, fetch: mockFetch })
+ const result = await client.products.list()
- expect(result).toEqual(paginatedEmpty);
- expect(mockFetch).toHaveBeenCalledTimes(3);
- });
+ expect(result).toEqual(paginatedEmpty)
+ expect(mockFetch).toHaveBeenCalledTimes(3)
+ })
it('throws after max retries exhausted', async () => {
- const mockFetch = vi.fn()
- .mockResolvedValue(errorResponse(500, 'server_error', 'Internal error'));
+ const mockFetch = vi
+ .fn()
+ .mockResolvedValue(errorResponse(500, 'server_error', 'Internal error'))
- const client = createClient({ ...baseConfig, fetch: mockFetch });
+ const client = createClient({ ...baseConfig, fetch: mockFetch })
- await expect(client.products.list()).rejects.toThrow(SpreeError);
+ await expect(client.products.list()).rejects.toThrow(SpreeError)
// 1 initial + 2 retries = 3 attempts
- expect(mockFetch).toHaveBeenCalledTimes(3);
- });
+ expect(mockFetch).toHaveBeenCalledTimes(3)
+ })
it('retries on network errors for GET', async () => {
- const mockFetch = vi.fn()
+ const mockFetch = vi
+ .fn()
.mockRejectedValueOnce(new TypeError('fetch failed'))
- .mockResolvedValueOnce(jsonResponse(paginatedEmpty));
+ .mockResolvedValueOnce(jsonResponse(paginatedEmpty))
- const client = createClient({ ...baseConfig, fetch: mockFetch });
- const result = await client.products.list();
+ const client = createClient({ ...baseConfig, fetch: mockFetch })
+ const result = await client.products.list()
- expect(result).toEqual(paginatedEmpty);
- expect(mockFetch).toHaveBeenCalledTimes(2);
- });
+ expect(result).toEqual(paginatedEmpty)
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ })
it('does not retry on 400 (client error)', async () => {
- const mockFetch = vi.fn()
- .mockResolvedValueOnce(errorResponse(400, 'bad_request', 'Bad request'));
+ const mockFetch = vi
+ .fn()
+ .mockResolvedValueOnce(errorResponse(400, 'bad_request', 'Bad request'))
- const client = createClient({ ...baseConfig, fetch: mockFetch });
+ const client = createClient({ ...baseConfig, fetch: mockFetch })
- await expect(client.products.list()).rejects.toThrow(SpreeError);
- expect(mockFetch).toHaveBeenCalledTimes(1);
- });
+ await expect(client.products.list()).rejects.toThrow(SpreeError)
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
it('does not retry on 401 (unauthorized)', async () => {
- const mockFetch = vi.fn()
- .mockResolvedValueOnce(errorResponse(401, 'unauthorized', 'Unauthorized'));
+ const mockFetch = vi
+ .fn()
+ .mockResolvedValueOnce(errorResponse(401, 'unauthorized', 'Unauthorized'))
- const client = createClient({ ...baseConfig, fetch: mockFetch });
+ const client = createClient({ ...baseConfig, fetch: mockFetch })
- await expect(client.products.list()).rejects.toThrow(SpreeError);
- expect(mockFetch).toHaveBeenCalledTimes(1);
- });
- });
+ await expect(client.products.list()).rejects.toThrow(SpreeError)
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
+ })
describe('POST requests (auto-idempotency)', () => {
it('retries POST on 429', async () => {
- const mockFetch = vi.fn()
+ const mockFetch = vi
+ .fn()
.mockResolvedValueOnce(errorResponse(429, 'rate_limited', 'Too many requests'))
- .mockResolvedValueOnce(jsonResponse({ token: 'abc', user: { id: '1', email: '[email protected]' } }));
+ .mockResolvedValueOnce(jsonResponse({ token: 'abc', user: { id: '1', email: '[email protected]' } }))
- const client = createClient({ ...baseConfig, fetch: mockFetch });
- const result = await client.auth.login({ email: '[email protected]', password: 'pass' });
+ const client = createClient({ ...baseConfig, fetch: mockFetch })
+ const result = await client.auth.login({ email: '[email protected]', password: 'pass' })
- expect(result.token).toBe('abc');
- expect(mockFetch).toHaveBeenCalledTimes(2);
- });
+ expect(result.token).toBe('abc')
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ })
it('retries POST on 500 with auto-generated idempotency key', async () => {
- const mockFetch = vi.fn()
+ const mockFetch = vi
+ .fn()
.mockResolvedValueOnce(errorResponse(500, 'server_error', 'Internal error'))
- .mockResolvedValueOnce(jsonResponse({ token: 'abc', user: { id: '1', email: '[email protected]' } }));
+ .mockResolvedValueOnce(jsonResponse({ token: 'abc', user: { id: '1', email: '[email protected]' } }))
- const client = createClient({ ...baseConfig, fetch: mockFetch });
- const result = await client.auth.login({ email: '[email protected]', password: 'pass' });
+ const client = createClient({ ...baseConfig, fetch: mockFetch })
+ const result = await client.auth.login({ email: '[email protected]', password: 'pass' })
- expect(result.token).toBe('abc');
- expect(mockFetch).toHaveBeenCalledTimes(2);
- });
+ expect(result.token).toBe('abc')
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ })
it('retries POST on network errors with auto-generated idempotency key', async () => {
- const mockFetch = vi.fn()
+ const mockFetch = vi
+ .fn()
.mockRejectedValueOnce(new TypeError('fetch failed'))
- .mockResolvedValueOnce(jsonResponse({ token: 'abc', user: { id: '1', email: '[email protected]' } }));
+ .mockResolvedValueOnce(jsonResponse({ token: 'abc', user: { id: '1', email: '[email protected]' } }))
- const client = createClient({ ...baseConfig, fetch: mockFetch });
- const result = await client.auth.login({ email: '[email protected]', password: 'pass' });
+ const client = createClient({ ...baseConfig, fetch: mockFetch })
+ const result = await client.auth.login({ email: '[email protected]', password: 'pass' })
- expect(result.token).toBe('abc');
- expect(mockFetch).toHaveBeenCalledTimes(2);
- });
+ expect(result.token).toBe('abc')
+ expect(mockFetch).toHaveBeenCalledTimes(2)
+ })
it('sends auto-generated Idempotency-Key header on POST', async () => {
- const mockFetch = vi.fn()
- .mockResolvedValueOnce(jsonResponse({ token: 'abc', user: { id: '1', email: '[email protected]' } }));
+ const mockFetch = vi
+ .fn()
+ .mockResolvedValueOnce(jsonResponse({ token: 'abc', user: { id: '1', email: '[email protected]' } }))
- const client = createClient({ ...baseConfig, fetch: mockFetch });
- await client.auth.login({ email: '[email protected]', password: 'pass' });
+ const client = createClient({ ...baseConfig, fetch: mockFetch })
+ await client.auth.login({ email: '[email protected]', password: 'pass' })
- const headers = mockFetch.mock.calls[0][1].headers;
- expect(headers['Idempotency-Key']).toMatch(/^spree-sdk-retry-/);
- });
+ const headers = mockFetch.mock.calls[0][1].headers
+ expect(headers['Idempotency-Key']).toMatch(/^spree-sdk-retry-/)
+ })
it('does not send Idempotency-Key on GET', async () => {
- const mockFetch = vi.fn()
- .mockResolvedValueOnce(jsonResponse({ data: [], meta: {} }));
+ const mockFetch = vi.fn().mockResolvedValueOnce(jsonResponse({ data: [], meta: {} }))
- const client = createClient({ ...baseConfig, fetch: mockFetch });
- await client.products.list();
+ const client = createClient({ ...baseConfig, fetch: mockFetch })
+ await client.products.list()
- const headers = mockFetch.mock.calls[0][1].headers;
- expect(headers['Idempotency-Key']).toBeUndefined();
- });
+ const headers = mockFetch.mock.calls[0][1].headers
+ expect(headers['Idempotency-Key']).toBeUndefined()
+ })
it('does NOT retry POST when retries are disabled', async () => {
- const mockFetch = vi.fn()
- .mockResolvedValueOnce(errorResponse(500, 'server_error', 'Internal error'));
+ const mockFetch = vi
+ .fn()
+ .mockResolvedValueOnce(errorResponse(500, 'server_error', 'Internal error'))
- const client = createClient({ ...baseConfig, fetch: mockFetch, retry: false });
+ const client = createClient({ ...baseConfig, fetch: mockFetch, retry: false })
- await expect(
- client.auth.login({ email: '[email protected]', password: 'pass' })
- ).rejects.toThrow(SpreeError);
- expect(mockFetch).toHaveBeenCalledTimes(1);
- });
+ await expect(client.auth.login({ email: '[email protected]', password: 'pass' })).rejects.toThrow(
+ SpreeError,
+ )
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
it('does not send Idempotency-Key when retries are disabled', async () => {
- const mockFetch = vi.fn()
- .mockResolvedValueOnce(jsonResponse({ token: 'abc', user: { id: '1', email: '[email protected]' } }));
+ const mockFetch = vi
+ .fn()
+ .mockResolvedValueOnce(jsonResponse({ token: 'abc', user: { id: '1', email: '[email protected]' } }))
- const client = createClient({ ...baseConfig, fetch: mockFetch, retry: false });
- await client.auth.login({ email: '[email protected]', password: 'pass' });
+ const client = createClient({ ...baseConfig, fetch: mockFetch, retry: false })
+ await client.auth.login({ email: '[email protected]', password: 'pass' })
- const headers = mockFetch.mock.calls[0][1].headers;
- expect(headers['Idempotency-Key']).toBeUndefined();
- });
+ const headers = mockFetch.mock.calls[0][1].headers
+ expect(headers['Idempotency-Key']).toBeUndefined()
+ })
it('uses user-supplied key over auto-generated one', async () => {
- const mockFetch = vi.fn()
- .mockResolvedValueOnce(jsonResponse({ number: 'R123', token: 'cart-token' }));
+ const mockFetch = vi
+ .fn()
+ .mockResolvedValueOnce(jsonResponse({ number: 'R123', token: 'cart-token' }))
- const client = createClient({ ...baseConfig, fetch: mockFetch });
- await client.carts.create(undefined, { idempotencyKey: 'my-custom-key' });
+ const client = createClient({ ...baseConfig, fetch: mockFetch })
+ await client.carts.create(undefined, { idempotencyKey: 'my-custom-key' })
- const headers = mockFetch.mock.calls[0][1].headers;
- expect(headers['Idempotency-Key']).toBe('my-custom-key');
- });
- });
+ const headers = mockFetch.mock.calls[0][1].headers
+ expect(headers['Idempotency-Key']).toBe('my-custom-key')
+ })
+ })
describe('retry: false disables retries', () => {
it('does not retry when retry is disabled', async () => {
- const mockFetch = vi.fn()
- .mockResolvedValueOnce(errorResponse(500, 'server_error', 'Internal error'));
+ const mockFetch = vi
+ .fn()
+ .mockResolvedValueOnce(errorResponse(500, 'server_error', 'Internal error'))
- const client = createClient({ ...baseConfig, fetch: mockFetch, retry: false });
+ const client = createClient({ ...baseConfig, fetch: mockFetch, retry: false })
- await expect(client.products.list()).rejects.toThrow(SpreeError);
- expect(mockFetch).toHaveBeenCalledTimes(1);
- });
- });
+ await expect(client.products.list()).rejects.toThrow(SpreeError)
+ expect(mockFetch).toHaveBeenCalledTimes(1)
+ })
+ })
describe('custom retry config', () => {
it('respects custom maxRetries', async () => {
- const mockFetch = vi.fn()
- .mockResolvedValue(errorResponse(500, 'server_error', 'Internal error'));
+ const mockFetch = vi
+ .fn()
+ .mockResolvedValue(errorResponse(500, 'server_error', 'Internal error'))
const client = createClient({
...baseConfig,
fetch: mockFetch,
retry: { maxRetries: 4, baseDelay: 10 },
- });
+ })
- await expect(client.products.list()).rejects.toThrow(SpreeError);
+ await expect(client.products.list()).rejects.toThrow(SpreeError)
// 1 initial + 4 retries = 5 attempts
- expect(mockFetch).toHaveBeenCalledTimes(5);
- });
+ expect(mockFetch).toHaveBeenCalledTimes(5)
+ })
it('respects Retry-After header', async () => {
- const start = Date.now();
- const mockFetch = vi.fn()
- .mockResolvedValueOnce(errorResponse(429, 'rate_limited', 'Too many requests', { 'Retry-After': '1' }))
- .mockResolvedValueOnce(jsonResponse(paginatedEmpty));
+ const start = Date.now()
+ const mockFetch = vi
+ .fn()
+ .mockResolvedValueOnce(
+ errorResponse(429, 'rate_limited', 'Too many requests', { 'Retry-After': '1' }),
+ )
+ .mockResolvedValueOnce(jsonResponse(paginatedEmpty))
const client = createClient({
...baseConfig,
fetch: mockFetch,
retry: { baseDelay: 10 },
- });
+ })
- const result = await client.products.list();
- const elapsed = Date.now() - start;
+ const result = await client.products.list()
+ const elapsed = Date.now() - start
- expect(result).toEqual(paginatedEmpty);
+ expect(result).toEqual(paginatedEmpty)
// Retry-After: 1 = 1000ms delay
- expect(elapsed).toBeGreaterThanOrEqual(900);
- });
- });
-});
+ expect(elapsed).toBeGreaterThanOrEqual(900)
+ })
+ })
+})
diff --git a/packages/sdk/tests/setup.ts b/packages/sdk/tests/setup.ts
index dfeeaaed85..e7d6d1a8fe 100644
--- a/packages/sdk/tests/setup.ts
+++ b/packages/sdk/tests/setup.ts
@@ -1,6 +1,6 @@
-import { afterAll, afterEach, beforeAll } from 'vitest';
-import { server } from './mocks/server';
+import { afterAll, afterEach, beforeAll } from 'vitest'
+import { server } from './mocks/server'
-beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
-afterEach(() => server.resetHandlers());
-afterAll(() => server.close());
+beforeAll(() => server.listen({ onUnhandledRequest: 'error' }))
+afterEach(() => server.resetHandlers())
+afterAll(() => server.close())
diff --git a/packages/sdk/tests/webhooks.test.ts b/packages/sdk/tests/webhooks.test.ts
index 1ab399d8b3..a59aa20d6b 100644
--- a/packages/sdk/tests/webhooks.test.ts
+++ b/packages/sdk/tests/webhooks.test.ts
@@ -1,11 +1,9 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { createHmac } from 'node:crypto'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { verifyWebhookSignature, type WebhookEvent } from '../src/webhooks'
function sign(payload: string, secret: string, timestamp: number): string {
- return createHmac('sha256', secret)
- .update(`${timestamp}.${payload}`)
- .digest('hex')
+ return createHmac('sha256', secret).update(`${timestamp}.${payload}`).digest('hex')
}
describe('verifyWebhookSignature', () => {
@@ -31,7 +29,9 @@ describe('verifyWebhookSignature', () => {
it('rejects an invalid signature', () => {
const timestamp = Math.floor(Date.now() / 1000)
- expect(verifyWebhookSignature(payload, 'invalid_signature', String(timestamp), secret)).toBe(false)
+ expect(verifyWebhookSignature(payload, 'invalid_signature', String(timestamp), secret)).toBe(
+ false,
+ )
})
it('rejects a wrong secret', () => {
@@ -68,7 +68,9 @@ describe('verifyWebhookSignature', () => {
const signature = sign(payload, secret, oldTimestamp)
// Default 300s tolerance rejects it
- expect(verifyWebhookSignature(payload, signature, String(oldTimestamp), secret, 300)).toBe(false)
+ expect(verifyWebhookSignature(payload, signature, String(oldTimestamp), secret, 300)).toBe(
+ false,
+ )
// Custom 900s tolerance accepts it
expect(verifyWebhookSignature(payload, signature, String(oldTimestamp), secret, 900)).toBe(true)
})
@@ -88,7 +90,10 @@ describe('verifyWebhookSignature', () => {
describe('WebhookEvent type', () => {
it('types data field generically', () => {
- interface OrderData { number: string; email: string }
+ interface OrderData {
+ number: string
+ email: string
+ }
const event: WebhookEvent<OrderData> = {
id: 'evt_123',
diff --git a/packages/sdk/tests/wishlists.test.ts b/packages/sdk/tests/wishlists.test.ts
index 8328aeea4c..3df70a770b 100644
--- a/packages/sdk/tests/wishlists.test.ts
+++ b/packages/sdk/tests/wishlists.test.ts
@@ -1,69 +1,55 @@
-import { describe, it, expect, beforeAll } from 'vitest';
-import { createTestClient } from './helpers';
-import type { Client } from '../src';
+import { beforeAll, describe, expect, it } from 'vitest'
+import type { Client } from '../src'
+import { createTestClient } from './helpers'
describe('wishlists', () => {
- let client: Client;
- beforeAll(() => { client = createTestClient(); });
- const opts = { token: 'user-jwt' };
+ let client: Client
+ beforeAll(() => {
+ client = createTestClient()
+ })
+ const opts = { token: 'user-jwt' }
it('lists wishlists', async () => {
- const result = await client.wishlists.list(undefined, opts);
- expect(result.data).toHaveLength(1);
- });
+ const result = await client.wishlists.list(undefined, opts)
+ expect(result.data).toHaveLength(1)
+ })
it('gets a wishlist', async () => {
- const result = await client.wishlists.get('wl_1', undefined, opts);
- expect(result.name).toBe('My Wishlist');
- });
+ const result = await client.wishlists.get('wl_1', undefined, opts)
+ expect(result.name).toBe('My Wishlist')
+ })
it('creates a wishlist', async () => {
- const result = await client.wishlists.create(
- { name: 'My Wishlist' },
- opts
- );
- expect(result.name).toBe('My Wishlist');
- });
+ const result = await client.wishlists.create({ name: 'My Wishlist' }, opts)
+ expect(result.name).toBe('My Wishlist')
+ })
it('updates a wishlist', async () => {
- const result = await client.wishlists.update(
- 'wl_1',
- { name: 'Updated Wishlist' },
- opts
- );
- expect(result.name).toBe('Updated Wishlist');
- });
+ const result = await client.wishlists.update('wl_1', { name: 'Updated Wishlist' }, opts)
+ expect(result.name).toBe('Updated Wishlist')
+ })
it('deletes a wishlist', async () => {
- await expect(
- client.wishlists.delete('wl_1', opts)
- ).resolves.toBeUndefined();
- });
+ await expect(client.wishlists.delete('wl_1', opts)).resolves.toBeUndefined()
+ })
describe('items', () => {
it('adds an item', async () => {
const result = await client.wishlists.items.create(
'wl_1',
{ variant_id: 'var_1', quantity: 1 },
- opts
- );
- expect(result.variant_id).toBe('var_1');
- });
+ opts,
+ )
+ expect(result.variant_id).toBe('var_1')
+ })
it('updates an item', async () => {
- const result = await client.wishlists.items.update(
- 'wl_1',
- 'wi_1',
- { quantity: 3 },
- opts
- );
- expect(result.quantity).toBe(3);
- });
+ const result = await client.wishlists.items.update('wl_1', 'wi_1', { quantity: 3 }, opts)
+ expect(result.quantity).toBe(3)
+ })
it('removes an item', async () => {
- await expect(
- client.wishlists.items.delete('wl_1', 'wi_1', opts)
- ).resolves.toBeUndefined();
- });
- });
-});
+ await expect(client.wishlists.items.delete('wl_1', 'wi_1', opts)).resolves.toBeUndefined()
+ })
+ })
+})
diff --git a/packages/sdk/tsup.config.ts b/packages/sdk/tsup.config.ts
index f4a80e3896..6a2e034d18 100644
--- a/packages/sdk/tsup.config.ts
+++ b/packages/sdk/tsup.config.ts
@@ -1,4 +1,4 @@
-import { defineConfig } from 'tsup';
+import { defineConfig } from 'tsup'
export default defineConfig({
entry: {
@@ -18,6 +18,6 @@ export default defineConfig({
esbuildOptions(options) {
options.alias = {
'@/types': './src/types/generated/index.ts',
- };
+ }
},
-});
+})
diff --git a/packages/sdk/vitest.config.ts b/packages/sdk/vitest.config.ts
index 59b3b211cf..4b300c0e75 100644
--- a/packages/sdk/vitest.config.ts
+++ b/packages/sdk/vitest.config.ts
@@ -1,5 +1,5 @@
-import { defineConfig } from 'vitest/config';
-import path from 'path';
+import path from 'node:path'
+import { defineConfig } from 'vitest/config'
export default defineConfig({
resolve: {
@@ -18,4 +18,4 @@ export default defineConfig({
exclude: ['src/types/**'],
},
},
-});
+})
diff --git a/packages/sdk/vitest.integration.config.ts b/packages/sdk/vitest.integration.config.ts
index e06a6acfdf..3cc1a126d7 100644
--- a/packages/sdk/vitest.integration.config.ts
+++ b/packages/sdk/vitest.integration.config.ts
@@ -1,5 +1,5 @@
-import { defineConfig } from 'vitest/config';
-import path from 'path';
+import path from 'node:path'
+import { defineConfig } from 'vitest/config'
export default defineConfig({
resolve: {
@@ -16,4 +16,4 @@ export default defineConfig({
// Run sequentially — tests share server + SQLite database
fileParallelism: false,
},
-});
+})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 83dfbdd934..e1900cde4a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -12,6 +12,9 @@ importers:
specifier: ^1.4.1
devDependencies:
+ '@biomejs/biome':
+ specifier: ^2.4.13
+ version: 2.4.13
turbo:
specifier: ^2.9.6
version: 2.9.6
@@ -97,9 +100,6 @@ importers:
specifier: ^4.3.6
version: 4.3.6
devDependencies:
- '@biomejs/biome':
- specifier: ^2.4.13
- version: 2.4.13
'@tailwindcss/vite':
specifier: ^4.2.4
diff --git a/turbo.json b/turbo.json
index ef61010d4f..c753e3efe5 100644
--- a/turbo.json
+++ b/turbo.json
@@ -14,6 +14,12 @@
"dependsOn": ["^build"]
},
"lint": {},
+ "lint:fix": {
+ "cache": false
+ },
+ "format": {
+ "cache": false
+ },
"typecheck": {
"dependsOn": ["^build"]
},