@commercengine/storefront-sdk 0.3.12 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,237 +1,2409 @@
1
- import { StorefrontAPIClient, Environment } from "./lib/client";
2
- import { CatalogClient } from "./lib/catalog";
3
- import { CartClient } from "./lib/cart";
4
- import { AuthClient } from "./lib/auth";
5
- import { OrderClient } from "./lib/order";
6
- import { ShippingClient } from "./lib/shipping";
7
- import { HelpersClient } from "./lib/helper";
8
- import { CustomerClient } from "./lib/customer";
9
- import { MemoryTokenStorage, BrowserTokenStorage, CookieTokenStorage, } from "./lib/middleware";
10
- import { extractUserInfoFromToken, getUserIdFromToken, isUserLoggedIn, isUserAnonymous, } from "./lib/jwt-utils";
11
- import { ResponseUtils } from "./lib/logger-utils";
12
- /**
13
- * Main SDK class for the Storefront API
14
- */
15
- export class StorefrontSDK {
16
- /**
17
- * Client for catalog-related endpoints (products, categories, etc.)
18
- */
19
- catalog;
20
- /**
21
- * Client for cart-related endpoints
22
- */
23
- cart;
24
- /**
25
- * Client for authentication-related endpoints
26
- */
27
- auth;
28
- /**
29
- * Client for customer-related endpoints
30
- */
31
- customer;
32
- /**
33
- * Client for helper-related endpoints
34
- */
35
- helpers;
36
- /**
37
- * Client for shipping-related endpoints
38
- */
39
- shipping;
40
- /**
41
- * Client for order-related endpoints
42
- */
43
- order;
44
- /**
45
- * Create a new StorefrontSDK instance
46
- *
47
- * @param options - Configuration options for the SDK
48
- */
49
- constructor(options) {
50
- // Convert options to internal config format
51
- const config = {
52
- storeId: options.storeId,
53
- environment: options.environment,
54
- baseUrl: options.baseUrl,
55
- accessToken: options.accessToken,
56
- refreshToken: options.refreshToken,
57
- apiKey: options.apiKey,
58
- timeout: options.timeout,
59
- tokenStorage: options.tokenStorage,
60
- onTokensUpdated: options.onTokensUpdated,
61
- onTokensCleared: options.onTokensCleared,
62
- defaultHeaders: options.defaultHeaders,
63
- debug: options.debug,
64
- logger: options.logger,
65
- };
66
- this.catalog = new CatalogClient(config);
67
- this.cart = new CartClient(config);
68
- this.auth = new AuthClient(config);
69
- this.customer = new CustomerClient(config);
70
- this.helpers = new HelpersClient(config);
71
- this.shipping = new ShippingClient(config);
72
- this.order = new OrderClient(config);
73
- }
74
- /**
75
- * Set authentication tokens for all clients
76
- *
77
- * @param accessToken - The access token (required)
78
- * @param refreshToken - The refresh token (optional)
79
- *
80
- * Behavior:
81
- * - If tokenStorage is provided: Stores tokens for automatic management
82
- * - If tokenStorage is not provided: Only stores access token for manual management
83
- */
84
- async setTokens(accessToken, refreshToken) {
85
- await this.catalog.setTokens(accessToken, refreshToken);
86
- await this.cart.setTokens(accessToken, refreshToken);
87
- await this.auth.setTokens(accessToken, refreshToken);
88
- await this.customer.setTokens(accessToken, refreshToken);
89
- await this.helpers.setTokens(accessToken, refreshToken);
90
- await this.shipping.setTokens(accessToken, refreshToken);
91
- await this.order.setTokens(accessToken, refreshToken);
92
- }
93
- /**
94
- * Clear all authentication tokens from all clients
95
- *
96
- * Behavior:
97
- * - If tokenStorage is provided: Clears both access and refresh tokens from storage
98
- * - If tokenStorage is not provided: Clears the manual access token
99
- */
100
- async clearTokens() {
101
- await this.catalog.clearTokens();
102
- await this.cart.clearTokens();
103
- await this.auth.clearTokens();
104
- await this.customer.clearTokens();
105
- await this.helpers.clearTokens();
106
- await this.shipping.clearTokens();
107
- await this.order.clearTokens();
108
- }
109
- /**
110
- * Set the API key for all clients
111
- *
112
- * @param apiKey - The API key to set
113
- */
114
- setApiKey(apiKey) {
115
- this.catalog.setApiKey(apiKey);
116
- this.cart.setApiKey(apiKey);
117
- this.auth.setApiKey(apiKey);
118
- this.customer.setApiKey(apiKey);
119
- this.helpers.setApiKey(apiKey);
120
- this.shipping.setApiKey(apiKey);
121
- this.order.setApiKey(apiKey);
122
- }
123
- /**
124
- * Clear the API key from all clients
125
- */
126
- clearApiKey() {
127
- this.catalog.clearApiKey();
128
- this.cart.clearApiKey();
129
- this.auth.clearApiKey();
130
- this.customer.clearApiKey();
131
- this.helpers.clearApiKey();
132
- this.shipping.clearApiKey();
133
- this.order.clearApiKey();
134
- }
135
- /**
136
- * Get the current access token if using token storage
137
- */
138
- async getAccessToken() {
139
- return await this.auth
140
- .getAuthorizationHeader()
141
- .then((header) => header.startsWith("Bearer ") ? header.substring(7) : null);
142
- }
143
- /**
144
- * Get user information from the current access token
145
- *
146
- * @returns User information extracted from JWT token, or null if no token or invalid token
147
- */
148
- async getUserInfo() {
149
- const token = await this.getAccessToken();
150
- if (!token)
151
- return null;
152
- return extractUserInfoFromToken(token);
153
- }
154
- /**
155
- * Get the current user ID from the access token
156
- *
157
- * @returns User ID (ulid) or null if no token or invalid token
158
- */
159
- async getUserId() {
160
- const token = await this.getAccessToken();
161
- if (!token)
162
- return null;
163
- return getUserIdFromToken(token);
164
- }
165
- /**
166
- * Check if the current user is logged in (not anonymous)
167
- *
168
- * @returns True if user is logged in, false if anonymous or no token
169
- */
170
- async isLoggedIn() {
171
- const token = await this.getAccessToken();
172
- if (!token)
173
- return false;
174
- return isUserLoggedIn(token);
175
- }
176
- /**
177
- * Check if the current user is anonymous
178
- *
179
- * @returns True if user is anonymous or no token, false if logged in
180
- */
181
- async isAnonymous() {
182
- const token = await this.getAccessToken();
183
- if (!token)
184
- return true;
185
- return isUserAnonymous(token);
186
- }
187
- /**
188
- * Get the customer ID from the current access token
189
- *
190
- * @returns Customer ID or null if no token, invalid token, or user has no customer ID
191
- */
192
- async getCustomerId() {
193
- const userInfo = await this.getUserInfo();
194
- return userInfo?.customerId || null;
195
- }
196
- /**
197
- * Get the customer group ID from the current access token
198
- *
199
- * @returns Customer group ID or null if no token, invalid token, or user has no customer group
200
- */
201
- async getCustomerGroupId() {
202
- const userInfo = await this.getUserInfo();
203
- return userInfo?.customerGroupId || null;
204
- }
205
- /**
206
- * Set default headers for all clients
207
- *
208
- * @param headers - Default headers to set (only supported headers allowed)
209
- */
210
- setDefaultHeaders(headers) {
211
- // Update config for all clients
212
- const newConfig = { ...this.catalog["config"], defaultHeaders: headers };
213
- this.catalog["config"] = newConfig;
214
- this.cart["config"] = newConfig;
215
- this.auth["config"] = newConfig;
216
- this.customer["config"] = newConfig;
217
- this.helpers["config"] = newConfig;
218
- this.shipping["config"] = newConfig;
219
- this.order["config"] = newConfig;
220
- }
221
- /**
222
- * Get current default headers
223
- *
224
- * @returns Current default headers
225
- */
226
- getDefaultHeaders() {
227
- return this.catalog["config"].defaultHeaders;
1
+ // src/lib/client.ts
2
+ import createClient from "openapi-fetch";
3
+
4
+ // src/lib/jwt-utils.ts
5
+ import { decodeJwt } from "jose";
6
+ function extractUserInfoFromToken(token) {
7
+ try {
8
+ const payload = decodeJwt(token);
9
+ return {
10
+ id: payload.ulid,
11
+ email: payload.email,
12
+ phone: payload.phone,
13
+ username: payload.username,
14
+ firstName: payload.first_name,
15
+ lastName: payload.last_name,
16
+ storeId: payload.store_id,
17
+ isLoggedIn: payload.is_logged_in,
18
+ isAnonymous: !payload.is_logged_in,
19
+ customerId: payload.customer_id,
20
+ customerGroupId: payload.customer_group_id,
21
+ anonymousId: payload.anonymous_id,
22
+ tokenExpiry: new Date(payload.exp * 1e3),
23
+ tokenIssuedAt: new Date(payload.iat * 1e3)
24
+ };
25
+ } catch (error) {
26
+ console.warn("Failed to decode JWT token:", error);
27
+ return null;
28
+ }
29
+ }
30
+ function isTokenExpired(token, bufferSeconds = 30) {
31
+ try {
32
+ const payload = decodeJwt(token);
33
+ if (!payload.exp) return true;
34
+ const currentTime = Math.floor(Date.now() / 1e3);
35
+ const expiryTime = payload.exp;
36
+ return currentTime >= expiryTime - bufferSeconds;
37
+ } catch (error) {
38
+ console.warn("Failed to decode JWT token:", error);
39
+ return true;
40
+ }
41
+ }
42
+ function getUserIdFromToken(token) {
43
+ const userInfo = extractUserInfoFromToken(token);
44
+ return userInfo?.id || null;
45
+ }
46
+ function isUserLoggedIn(token) {
47
+ const userInfo = extractUserInfoFromToken(token);
48
+ return userInfo?.isLoggedIn || false;
49
+ }
50
+ function isUserAnonymous(token) {
51
+ const userInfo = extractUserInfoFromToken(token);
52
+ return userInfo?.isAnonymous || true;
53
+ }
54
+
55
+ // src/lib/auth-utils.ts
56
+ function getPathnameFromUrl(url) {
57
+ try {
58
+ const urlObj = new URL(url);
59
+ return urlObj.pathname;
60
+ } catch {
61
+ return url.split("?")[0];
62
+ }
63
+ }
64
+ function isAnonymousAuthEndpoint(pathname) {
65
+ return pathname.endsWith("/auth/anonymous");
66
+ }
67
+ function isTokenReturningEndpoint(pathname) {
68
+ const tokenEndpoints = [
69
+ "/auth/login/password",
70
+ "/auth/register/phone",
71
+ "/auth/register/email",
72
+ "/auth/verify-otp",
73
+ "/auth/refresh-token"
74
+ ];
75
+ return tokenEndpoints.some((endpoint) => pathname.endsWith(endpoint));
76
+ }
77
+ function isLogoutEndpoint(pathname) {
78
+ return pathname.endsWith("/auth/logout");
79
+ }
80
+
81
+ // src/lib/middleware.ts
82
+ var MemoryTokenStorage = class {
83
+ accessToken = null;
84
+ refreshToken = null;
85
+ async getAccessToken() {
86
+ return this.accessToken;
87
+ }
88
+ async setAccessToken(token) {
89
+ this.accessToken = token;
90
+ }
91
+ async getRefreshToken() {
92
+ return this.refreshToken;
93
+ }
94
+ async setRefreshToken(token) {
95
+ this.refreshToken = token;
96
+ }
97
+ async clearTokens() {
98
+ this.accessToken = null;
99
+ this.refreshToken = null;
100
+ }
101
+ };
102
+ var BrowserTokenStorage = class {
103
+ accessTokenKey;
104
+ refreshTokenKey;
105
+ constructor(prefix = "storefront_") {
106
+ this.accessTokenKey = `${prefix}access_token`;
107
+ this.refreshTokenKey = `${prefix}refresh_token`;
108
+ }
109
+ async getAccessToken() {
110
+ if (typeof localStorage === "undefined") return null;
111
+ return localStorage.getItem(this.accessTokenKey);
112
+ }
113
+ async setAccessToken(token) {
114
+ if (typeof localStorage !== "undefined") {
115
+ localStorage.setItem(this.accessTokenKey, token);
116
+ }
117
+ }
118
+ async getRefreshToken() {
119
+ if (typeof localStorage === "undefined") return null;
120
+ return localStorage.getItem(this.refreshTokenKey);
121
+ }
122
+ async setRefreshToken(token) {
123
+ if (typeof localStorage !== "undefined") {
124
+ localStorage.setItem(this.refreshTokenKey, token);
125
+ }
126
+ }
127
+ async clearTokens() {
128
+ if (typeof localStorage !== "undefined") {
129
+ localStorage.removeItem(this.accessTokenKey);
130
+ localStorage.removeItem(this.refreshTokenKey);
131
+ }
132
+ }
133
+ };
134
+ var CookieTokenStorage = class {
135
+ accessTokenKey;
136
+ refreshTokenKey;
137
+ options;
138
+ constructor(options = {}) {
139
+ const prefix = options.prefix || "storefront_";
140
+ this.accessTokenKey = `${prefix}access_token`;
141
+ this.refreshTokenKey = `${prefix}refresh_token`;
142
+ this.options = {
143
+ maxAge: options.maxAge || 7 * 24 * 60 * 60,
144
+ // 7 days default
145
+ path: options.path || "/",
146
+ domain: options.domain,
147
+ secure: options.secure ?? (typeof window !== "undefined" && window.location?.protocol === "https:"),
148
+ sameSite: options.sameSite || "Lax",
149
+ httpOnly: false
150
+ // Must be false for client-side access
151
+ };
152
+ }
153
+ async getAccessToken() {
154
+ return this.getCookie(this.accessTokenKey);
155
+ }
156
+ async setAccessToken(token) {
157
+ this.setCookie(this.accessTokenKey, token);
158
+ }
159
+ async getRefreshToken() {
160
+ return this.getCookie(this.refreshTokenKey);
161
+ }
162
+ async setRefreshToken(token) {
163
+ this.setCookie(this.refreshTokenKey, token);
164
+ }
165
+ async clearTokens() {
166
+ this.deleteCookie(this.accessTokenKey);
167
+ this.deleteCookie(this.refreshTokenKey);
168
+ }
169
+ getCookie(name) {
170
+ if (typeof document === "undefined") return null;
171
+ const value = `; ${document.cookie}`;
172
+ const parts = value.split(`; ${name}=`);
173
+ if (parts.length === 2) {
174
+ const cookieValue = parts.pop()?.split(";").shift();
175
+ return cookieValue ? decodeURIComponent(cookieValue) : null;
176
+ }
177
+ return null;
178
+ }
179
+ setCookie(name, value) {
180
+ if (typeof document === "undefined") return;
181
+ const encodedValue = encodeURIComponent(value);
182
+ let cookieString = `${name}=${encodedValue}`;
183
+ if (this.options.maxAge) {
184
+ cookieString += `; Max-Age=${this.options.maxAge}`;
185
+ }
186
+ if (this.options.path) {
187
+ cookieString += `; Path=${this.options.path}`;
188
+ }
189
+ if (this.options.domain) {
190
+ cookieString += `; Domain=${this.options.domain}`;
191
+ }
192
+ if (this.options.secure) {
193
+ cookieString += `; Secure`;
194
+ }
195
+ if (this.options.sameSite) {
196
+ cookieString += `; SameSite=${this.options.sameSite}`;
197
+ }
198
+ document.cookie = cookieString;
199
+ }
200
+ deleteCookie(name) {
201
+ if (typeof document === "undefined") return;
202
+ let cookieString = `${name}=; Max-Age=0`;
203
+ if (this.options.path) {
204
+ cookieString += `; Path=${this.options.path}`;
205
+ }
206
+ if (this.options.domain) {
207
+ cookieString += `; Domain=${this.options.domain}`;
208
+ }
209
+ document.cookie = cookieString;
210
+ }
211
+ };
212
+ function createAuthMiddleware(config) {
213
+ let isRefreshing = false;
214
+ let refreshPromise = null;
215
+ const refreshTokens = async () => {
216
+ if (isRefreshing && refreshPromise) {
217
+ return refreshPromise;
218
+ }
219
+ isRefreshing = true;
220
+ refreshPromise = (async () => {
221
+ try {
222
+ const refreshToken = await config.tokenStorage.getRefreshToken();
223
+ let newTokens;
224
+ if (refreshToken && !isTokenExpired(refreshToken)) {
225
+ if (config.refreshTokenFn) {
226
+ newTokens = await config.refreshTokenFn(refreshToken);
227
+ } else {
228
+ const response = await fetch(
229
+ `${config.baseUrl}/auth/refresh-token`,
230
+ {
231
+ method: "POST",
232
+ headers: {
233
+ "Content-Type": "application/json"
234
+ },
235
+ body: JSON.stringify({ refresh_token: refreshToken })
236
+ }
237
+ );
238
+ if (!response.ok) {
239
+ throw new Error(`Token refresh failed: ${response.status}`);
240
+ }
241
+ const data = await response.json();
242
+ newTokens = data.content;
243
+ }
244
+ } else {
245
+ const currentAccessToken = await config.tokenStorage.getAccessToken();
246
+ if (!currentAccessToken) {
247
+ throw new Error("No tokens available for refresh");
248
+ }
249
+ const reason = refreshToken ? "refresh token expired" : "no refresh token available";
250
+ const response = await fetch(`${config.baseUrl}/auth/anonymous`, {
251
+ method: "POST",
252
+ headers: {
253
+ "Content-Type": "application/json",
254
+ ...config.apiKey && { "X-Api-Key": config.apiKey },
255
+ Authorization: `Bearer ${currentAccessToken}`
256
+ // For user_id continuity
257
+ }
258
+ });
259
+ if (!response.ok) {
260
+ throw new Error(
261
+ `Anonymous token fallback failed: ${response.status}`
262
+ );
263
+ }
264
+ const data = await response.json();
265
+ newTokens = data.content;
266
+ console.info(
267
+ `Token refreshed via anonymous fallback (${reason}) - user may need to re-authenticate for privileged operations`
268
+ );
269
+ }
270
+ await config.tokenStorage.setAccessToken(newTokens.access_token);
271
+ await config.tokenStorage.setRefreshToken(newTokens.refresh_token);
272
+ config.onTokensUpdated?.(
273
+ newTokens.access_token,
274
+ newTokens.refresh_token
275
+ );
276
+ } catch (error) {
277
+ console.error("Token refresh failed:", error);
278
+ await config.tokenStorage.clearTokens();
279
+ config.onTokensCleared?.();
280
+ throw error;
281
+ } finally {
282
+ isRefreshing = false;
283
+ refreshPromise = null;
284
+ }
285
+ })();
286
+ return refreshPromise;
287
+ };
288
+ return {
289
+ async onRequest({ request }) {
290
+ const pathname = getPathnameFromUrl(request.url);
291
+ if (isAnonymousAuthEndpoint(pathname)) {
292
+ if (config.apiKey) {
293
+ request.headers.set("X-Api-Key", config.apiKey);
294
+ }
295
+ const existingToken = await config.tokenStorage.getAccessToken();
296
+ if (existingToken) {
297
+ request.headers.set("Authorization", `Bearer ${existingToken}`);
298
+ }
299
+ return request;
300
+ }
301
+ let accessToken = await config.tokenStorage.getAccessToken();
302
+ if (accessToken && isTokenExpired(accessToken)) {
303
+ try {
304
+ await refreshTokens();
305
+ accessToken = await config.tokenStorage.getAccessToken();
306
+ } catch (error) {
307
+ }
308
+ }
309
+ if (accessToken) {
310
+ request.headers.set("Authorization", `Bearer ${accessToken}`);
311
+ }
312
+ return request;
313
+ },
314
+ async onResponse({ request, response }) {
315
+ const pathname = getPathnameFromUrl(request.url);
316
+ if (response.ok) {
317
+ if (isTokenReturningEndpoint(pathname) || isAnonymousAuthEndpoint(pathname)) {
318
+ try {
319
+ const data = await response.clone().json();
320
+ const content = data.content;
321
+ if (content?.access_token && content?.refresh_token) {
322
+ await config.tokenStorage.setAccessToken(content.access_token);
323
+ await config.tokenStorage.setRefreshToken(content.refresh_token);
324
+ config.onTokensUpdated?.(
325
+ content.access_token,
326
+ content.refresh_token
327
+ );
328
+ }
329
+ } catch (error) {
330
+ console.warn("Failed to extract tokens from response:", error);
331
+ }
332
+ } else if (isLogoutEndpoint(pathname)) {
333
+ await config.tokenStorage.clearTokens();
334
+ config.onTokensCleared?.();
335
+ }
336
+ }
337
+ if (response.status === 401 && !isAnonymousAuthEndpoint(pathname)) {
338
+ const currentToken = await config.tokenStorage.getAccessToken();
339
+ if (currentToken && isTokenExpired(currentToken, 0)) {
340
+ try {
341
+ await refreshTokens();
342
+ const newToken = await config.tokenStorage.getAccessToken();
343
+ if (newToken) {
344
+ const retryRequest = request.clone();
345
+ retryRequest.headers.set("Authorization", `Bearer ${newToken}`);
346
+ return fetch(retryRequest);
347
+ }
348
+ } catch (error) {
349
+ console.warn("Token refresh failed on 401 response:", error);
350
+ }
351
+ }
352
+ }
353
+ return response;
354
+ }
355
+ };
356
+ }
357
+ function createDefaultAuthMiddleware(options) {
358
+ const tokenStorage = options.tokenStorage || (typeof localStorage !== "undefined" ? new BrowserTokenStorage() : new MemoryTokenStorage());
359
+ return createAuthMiddleware({
360
+ tokenStorage,
361
+ apiKey: options.apiKey,
362
+ baseUrl: options.baseUrl,
363
+ onTokensUpdated: options.onTokensUpdated,
364
+ onTokensCleared: options.onTokensCleared
365
+ });
366
+ }
367
+
368
+ // src/lib/logger-utils.ts
369
+ var ResponseUtils = class {
370
+ /**
371
+ * Get response headers as a plain object
372
+ */
373
+ static getHeaders(response) {
374
+ return Object.fromEntries(response.headers.entries());
375
+ }
376
+ /**
377
+ * Get specific header value
378
+ */
379
+ static getHeader(response, name) {
380
+ return response.headers.get(name);
381
+ }
382
+ /**
383
+ * Check if response was successful
384
+ */
385
+ static isSuccess(response) {
386
+ return response.ok;
387
+ }
388
+ /**
389
+ * Get response metadata
390
+ */
391
+ static getMetadata(response) {
392
+ return {
393
+ status: response.status,
394
+ statusText: response.statusText,
395
+ ok: response.ok,
396
+ url: response.url,
397
+ redirected: response.redirected,
398
+ type: response.type,
399
+ headers: Object.fromEntries(response.headers.entries())
400
+ };
401
+ }
402
+ /**
403
+ * Clone and read response as text (useful for debugging)
404
+ * Note: This can only be called once per response
405
+ */
406
+ static async getText(response) {
407
+ const cloned = response.clone();
408
+ return await cloned.text();
409
+ }
410
+ /**
411
+ * Clone and read response as JSON (useful for debugging)
412
+ * Note: This can only be called once per response
413
+ */
414
+ static async getJSON(response) {
415
+ const cloned = response.clone();
416
+ return await cloned.json();
417
+ }
418
+ /**
419
+ * Format response information for debugging
420
+ */
421
+ static format(response) {
422
+ const metadata = this.getMetadata(response);
423
+ return `${metadata.status} ${metadata.statusText} - ${metadata.url}`;
424
+ }
425
+ };
426
+ var DebugLogger = class {
427
+ logger;
428
+ responseTextCache = /* @__PURE__ */ new Map();
429
+ constructor(logger) {
430
+ this.logger = logger || ((level, message, data) => {
431
+ console.log(`[${level.toUpperCase()}]`, message);
432
+ if (data) console.log(data);
433
+ });
434
+ }
435
+ /**
436
+ * Log debug information about API request
437
+ */
438
+ logRequest(request, requestBody) {
439
+ this.logger("info", "API Request Debug Info", {
440
+ method: request.method,
441
+ url: request.url,
442
+ headers: Object.fromEntries(request.headers.entries()),
443
+ body: requestBody,
444
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
445
+ });
446
+ }
447
+ /**
448
+ * Log debug information about API response
449
+ */
450
+ async logResponse(response, responseBody) {
451
+ if (responseBody && typeof responseBody === "string") {
452
+ this.responseTextCache.set(response.url, responseBody);
453
+ }
454
+ this.logger("info", "API Response Debug Info", {
455
+ url: response.url,
456
+ status: response.status,
457
+ statusText: response.statusText,
458
+ ok: response.ok,
459
+ headers: Object.fromEntries(response.headers.entries()),
460
+ redirected: response.redirected,
461
+ type: response.type,
462
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
463
+ });
464
+ if (responseBody) {
465
+ this.logger("info", "API Response Data", {
466
+ data: responseBody,
467
+ contentType: response.headers.get("content-type"),
468
+ contentLength: response.headers.get("content-length")
469
+ });
470
+ }
471
+ }
472
+ /**
473
+ * Log error information
474
+ */
475
+ logError(message, error) {
476
+ this.logger("error", message, error);
477
+ }
478
+ /**
479
+ * Get cached response text for a URL (if available)
480
+ */
481
+ getCachedResponseText(url) {
482
+ return this.responseTextCache.get(url) || null;
483
+ }
484
+ /**
485
+ * Clear cached response texts
486
+ */
487
+ clearCache() {
488
+ this.responseTextCache.clear();
489
+ }
490
+ };
491
+ async function extractRequestBody(request) {
492
+ if (request.method === "GET" || request.method === "HEAD") {
493
+ return null;
494
+ }
495
+ try {
496
+ const clonedRequest = request.clone();
497
+ const contentType = request.headers.get("content-type")?.toLowerCase();
498
+ if (contentType?.startsWith("application/json")) {
499
+ return await clonedRequest.json();
500
+ } else if (contentType?.startsWith("multipart/form-data")) {
501
+ return "[FormData - cannot display]";
502
+ } else if (contentType?.startsWith("text/")) {
503
+ return await clonedRequest.text();
504
+ }
505
+ return "[Request body - unknown format]";
506
+ } catch (error) {
507
+ return "[Request body unavailable]";
508
+ }
509
+ }
510
+ function createDebugMiddleware(logger) {
511
+ const debugLogger = new DebugLogger(logger);
512
+ return {
513
+ async onRequest({ request }) {
514
+ const requestBody = await extractRequestBody(request);
515
+ debugLogger.logRequest(request, requestBody);
516
+ return request;
517
+ },
518
+ async onResponse({ response }) {
519
+ const cloned = response.clone();
520
+ let responseBody = null;
521
+ try {
522
+ const contentType = response.headers.get("content-type")?.toLowerCase();
523
+ if (contentType?.startsWith("application/json")) {
524
+ responseBody = await cloned.json();
525
+ } else if (contentType?.startsWith("text/")) {
526
+ responseBody = await cloned.text();
527
+ }
528
+ } catch (error) {
529
+ }
530
+ await debugLogger.logResponse(response, responseBody);
531
+ return response;
532
+ },
533
+ async onError({ error, request }) {
534
+ debugLogger.logError("API Request Failed", {
535
+ error: {
536
+ name: error instanceof Error ? error.name : "Unknown",
537
+ message: error instanceof Error ? error.message : String(error),
538
+ stack: error instanceof Error ? error.stack : void 0
539
+ },
540
+ request: {
541
+ method: request.method,
542
+ url: request.url,
543
+ headers: Object.fromEntries(request.headers.entries())
544
+ },
545
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
546
+ });
547
+ throw error;
228
548
  }
549
+ };
229
550
  }
230
- // Export the main SDK class
231
- export default StorefrontSDK;
232
- // Export individual clients for advanced usage
233
- export { StorefrontAPIClient, AuthClient, CartClient, CatalogClient, CustomerClient, HelpersClient, ShippingClient, OrderClient, ResponseUtils, };
234
- // Export environment enum
235
- export { Environment };
236
- // Export token storage types
237
- export { MemoryTokenStorage, BrowserTokenStorage, CookieTokenStorage, };
551
+
552
+ // src/lib/header-utils.ts
553
+ var HEADER_TRANSFORMATIONS = {
554
+ customer_group_id: "x-customer-group-id"
555
+ // Future transformations can be added here:
556
+ // some_param: "X-Some-Header",
557
+ // another_param: "X-Another-Header",
558
+ };
559
+ function transformHeaders(headers) {
560
+ const transformed = {};
561
+ for (const [key, value] of Object.entries(headers)) {
562
+ if (value !== void 0) {
563
+ const headerName = HEADER_TRANSFORMATIONS[key] || key;
564
+ transformed[headerName] = value;
565
+ }
566
+ }
567
+ return transformed;
568
+ }
569
+ function mergeHeaders(defaultHeaders, methodHeaders) {
570
+ const merged = {};
571
+ if (defaultHeaders) {
572
+ const transformedDefaults = transformHeaders(defaultHeaders);
573
+ Object.assign(merged, transformedDefaults);
574
+ }
575
+ if (methodHeaders) {
576
+ Object.assign(merged, methodHeaders);
577
+ }
578
+ Object.keys(merged).forEach((key) => {
579
+ if (merged[key] === void 0) {
580
+ delete merged[key];
581
+ }
582
+ });
583
+ return merged;
584
+ }
585
+
586
+ // src/lib/client.ts
587
+ var Environment = /* @__PURE__ */ ((Environment2) => {
588
+ Environment2["Staging"] = "staging";
589
+ Environment2["Production"] = "production";
590
+ return Environment2;
591
+ })(Environment || {});
592
+ var StorefrontAPIClient = class {
593
+ client;
594
+ config;
595
+ baseUrl;
596
+ initializationPromise = null;
597
+ /**
598
+ * Create a new StorefrontAPIClient
599
+ *
600
+ * @param config - Configuration for the API client
601
+ */
602
+ constructor(config) {
603
+ this.config = { ...config };
604
+ this.baseUrl = this.getBaseUrlFromConfig(this.config);
605
+ this.client = createClient({
606
+ baseUrl: this.baseUrl
607
+ });
608
+ if (this.config.tokenStorage) {
609
+ const authMiddleware = createDefaultAuthMiddleware({
610
+ apiKey: this.config.apiKey,
611
+ baseUrl: this.baseUrl,
612
+ tokenStorage: this.config.tokenStorage,
613
+ onTokensUpdated: this.config.onTokensUpdated,
614
+ onTokensCleared: this.config.onTokensCleared
615
+ });
616
+ this.client.use(authMiddleware);
617
+ if (this.config.accessToken) {
618
+ this.initializationPromise = this.initializeTokens(
619
+ this.config.accessToken,
620
+ this.config.refreshToken
621
+ );
622
+ this.config.accessToken = void 0;
623
+ this.config.refreshToken = void 0;
624
+ }
625
+ } else {
626
+ this.client.use({
627
+ onRequest: async ({ request }) => {
628
+ const pathname = getPathnameFromUrl(request.url);
629
+ if (isAnonymousAuthEndpoint(pathname)) {
630
+ if (this.config.apiKey) {
631
+ request.headers.set("X-Api-Key", this.config.apiKey);
632
+ }
633
+ if (this.config.accessToken) {
634
+ request.headers.set(
635
+ "Authorization",
636
+ `Bearer ${this.config.accessToken}`
637
+ );
638
+ }
639
+ return request;
640
+ }
641
+ if (this.config.accessToken) {
642
+ request.headers.set(
643
+ "Authorization",
644
+ `Bearer ${this.config.accessToken}`
645
+ );
646
+ }
647
+ return request;
648
+ }
649
+ });
650
+ }
651
+ if (this.config.timeout) {
652
+ this.setupTimeoutMiddleware();
653
+ }
654
+ if (this.config.debug) {
655
+ const debugMiddleware = createDebugMiddleware(this.config.logger);
656
+ this.client.use(debugMiddleware);
657
+ }
658
+ }
659
+ /**
660
+ * Set up timeout middleware
661
+ */
662
+ setupTimeoutMiddleware() {
663
+ this.client.use({
664
+ onRequest: async ({ request }) => {
665
+ const controller = new AbortController();
666
+ const timeoutId = setTimeout(
667
+ () => controller.abort(),
668
+ this.config.timeout
669
+ );
670
+ if (request.signal) {
671
+ request.signal.addEventListener("abort", () => controller.abort());
672
+ }
673
+ const newRequest = new Request(request, {
674
+ signal: controller.signal
675
+ });
676
+ controller.signal.addEventListener(
677
+ "abort",
678
+ () => clearTimeout(timeoutId)
679
+ );
680
+ return newRequest;
681
+ }
682
+ });
683
+ }
684
+ /**
685
+ * Constructs the base URL from the configuration
686
+ *
687
+ * @param config - The client configuration
688
+ * @returns The constructed base URL
689
+ */
690
+ getBaseUrlFromConfig(config) {
691
+ if (config.baseUrl) {
692
+ return config.baseUrl;
693
+ }
694
+ const env = config.environment || "production" /* Production */;
695
+ switch (env) {
696
+ case "staging" /* Staging */:
697
+ return `https://staging.api.commercengine.io/api/v1/${config.storeId}/storefront`;
698
+ case "production" /* Production */:
699
+ default:
700
+ return `https://prod.api.commercengine.io/api/v1/${config.storeId}/storefront`;
701
+ }
702
+ }
703
+ /**
704
+ * Get the base URL of the API
705
+ *
706
+ * @returns The base URL of the API
707
+ */
708
+ getBaseUrl() {
709
+ return this.baseUrl;
710
+ }
711
+ /**
712
+ * Get the authorization header value
713
+ * If using token storage, gets the current token from storage
714
+ * Otherwise returns the manual token
715
+ *
716
+ * @returns The Authorization header value or empty string if no token is set
717
+ */
718
+ async getAuthorizationHeader() {
719
+ if (this.config.tokenStorage && this.initializationPromise) {
720
+ await this.initializationPromise;
721
+ }
722
+ if (this.config.tokenStorage) {
723
+ const token = await this.config.tokenStorage.getAccessToken();
724
+ return token ? `Bearer ${token}` : "";
725
+ }
726
+ return this.config.accessToken ? `Bearer ${this.config.accessToken}` : "";
727
+ }
728
+ /**
729
+ * Set authentication tokens
730
+ *
731
+ * @param accessToken - The access token (required)
732
+ * @param refreshToken - The refresh token (optional)
733
+ *
734
+ * Behavior:
735
+ * - If tokenStorage is provided: Stores tokens for automatic management
736
+ * - If tokenStorage is not provided: Only stores access token for manual management
737
+ */
738
+ async setTokens(accessToken, refreshToken) {
739
+ if (this.config.tokenStorage) {
740
+ await this.config.tokenStorage.setAccessToken(accessToken);
741
+ if (refreshToken) {
742
+ await this.config.tokenStorage.setRefreshToken(refreshToken);
743
+ }
744
+ } else {
745
+ this.config.accessToken = accessToken;
746
+ if (refreshToken) {
747
+ console.warn(
748
+ "Refresh token provided but ignored in manual token management mode. Use tokenStorage for automatic management."
749
+ );
750
+ }
751
+ }
752
+ }
753
+ /**
754
+ * Clear all authentication tokens
755
+ *
756
+ * Behavior:
757
+ * - If tokenStorage is provided: Clears both access and refresh tokens from storage
758
+ * - If tokenStorage is not provided: Clears the manual access token
759
+ */
760
+ async clearTokens() {
761
+ if (this.config.tokenStorage) {
762
+ await this.config.tokenStorage.clearTokens();
763
+ } else {
764
+ this.config.accessToken = void 0;
765
+ }
766
+ }
767
+ /**
768
+ * Set the X-Api-Key header
769
+ *
770
+ * @param apiKey - The API key to set
771
+ */
772
+ setApiKey(apiKey) {
773
+ this.config.apiKey = apiKey;
774
+ }
775
+ /**
776
+ * Clear the X-Api-Key header
777
+ */
778
+ clearApiKey() {
779
+ this.config.apiKey = void 0;
780
+ }
781
+ /**
782
+ * Execute a request and handle the response
783
+ *
784
+ * @param apiCall - Function that executes the API request
785
+ * @returns Promise with the API response
786
+ */
787
+ async executeRequest(apiCall) {
788
+ try {
789
+ const { data, error, response } = await apiCall();
790
+ if (error) {
791
+ return {
792
+ data: null,
793
+ error,
794
+ response
795
+ };
796
+ }
797
+ if (data && data.content !== void 0) {
798
+ return {
799
+ data: data.content,
800
+ error: null,
801
+ response
802
+ };
803
+ }
804
+ return {
805
+ data,
806
+ error: null,
807
+ response
808
+ };
809
+ } catch (err) {
810
+ const mockResponse = new Response(null, {
811
+ status: 0,
812
+ statusText: "Network Error"
813
+ });
814
+ const errorResult = {
815
+ data: null,
816
+ error: {
817
+ success: false,
818
+ code: "NETWORK_ERROR",
819
+ message: "Network error occurred",
820
+ error: err
821
+ },
822
+ response: mockResponse
823
+ };
824
+ return errorResult;
825
+ }
826
+ }
827
+ /**
828
+ * Initialize tokens in storage (private helper method)
829
+ */
830
+ async initializeTokens(accessToken, refreshToken) {
831
+ try {
832
+ if (this.config.tokenStorage) {
833
+ await this.config.tokenStorage.setAccessToken(accessToken);
834
+ if (refreshToken) {
835
+ await this.config.tokenStorage.setRefreshToken(refreshToken);
836
+ }
837
+ }
838
+ } catch (error) {
839
+ console.warn("Failed to initialize tokens in storage:", error);
840
+ }
841
+ }
842
+ /**
843
+ * Merge default headers with method-level headers
844
+ * Method-level headers take precedence over default headers
845
+ *
846
+ * @param methodHeaders - Headers passed to the specific method call
847
+ * @returns Merged headers object with proper HTTP header names
848
+ */
849
+ mergeHeaders(methodHeaders) {
850
+ return mergeHeaders(this.config.defaultHeaders, methodHeaders);
851
+ }
852
+ };
853
+
854
+ // src/lib/catalog.ts
855
+ var CatalogClient = class extends StorefrontAPIClient {
856
+ /**
857
+ * List all products
858
+ *
859
+ * @param options - Optional query parameters
860
+ * @param headers - Optional header parameters (customer_group_id, etc.)
861
+ * @returns Promise with products and pagination info
862
+ */
863
+ async listProducts(options, headers) {
864
+ const mergedHeaders = this.mergeHeaders(headers);
865
+ return this.executeRequest(
866
+ () => this.client.GET("/catalog/products", {
867
+ params: {
868
+ query: options,
869
+ header: mergedHeaders
870
+ }
871
+ })
872
+ );
873
+ }
874
+ /**
875
+ * List all skus
876
+ *
877
+ * @param options - Optional query parameters
878
+ * @param headers - Optional header parameters (customer_group_id, etc.)
879
+ * @returns Promise with skus and pagination info
880
+ */
881
+ async listSkus(options, headers) {
882
+ const mergedHeaders = this.mergeHeaders(headers);
883
+ return this.executeRequest(
884
+ () => this.client.GET("/catalog/skus", {
885
+ params: {
886
+ query: options,
887
+ header: mergedHeaders
888
+ }
889
+ })
890
+ );
891
+ }
892
+ /**
893
+ * Get details for a specific product
894
+ *
895
+ * @param pathParams - The path parameters (product ID or slug)
896
+ * @param headers - Optional header parameters (customer_group_id, etc.)
897
+ * @returns Promise with product details
898
+ */
899
+ async getProductDetail(pathParams, headers) {
900
+ const mergedHeaders = this.mergeHeaders(headers);
901
+ return this.executeRequest(
902
+ () => this.client.GET("/catalog/products/{product_id_or_slug}", {
903
+ params: {
904
+ path: pathParams,
905
+ header: mergedHeaders
906
+ }
907
+ })
908
+ );
909
+ }
910
+ /**
911
+ * List variants for a specific product
912
+ *
913
+ * @param pathParams - The path parameters (product ID)
914
+ * @param headers - Optional header parameters (customer_group_id, etc.)
915
+ * @returns Promise with variants
916
+ */
917
+ async listProductVariants(pathParams, headers) {
918
+ const mergedHeaders = this.mergeHeaders(headers);
919
+ return this.executeRequest(
920
+ () => this.client.GET("/catalog/products/{product_id}/variants", {
921
+ params: {
922
+ path: pathParams,
923
+ header: mergedHeaders
924
+ }
925
+ })
926
+ );
927
+ }
928
+ /**
929
+ * Get details for a specific variant
930
+ *
931
+ * @param pathParams - The path parameters (product ID and variant ID)
932
+ * @param headers - Optional header parameters (customer_group_id, etc.)
933
+ * @returns Promise with variant details
934
+ */
935
+ async getVariantDetail(pathParams, headers) {
936
+ const mergedHeaders = this.mergeHeaders(headers);
937
+ return this.executeRequest(
938
+ () => this.client.GET("/catalog/products/{product_id}/variants/{variant_id}", {
939
+ params: {
940
+ path: pathParams,
941
+ header: mergedHeaders
942
+ }
943
+ })
944
+ );
945
+ }
946
+ /**
947
+ * List all categories
948
+ *
949
+ * @param options - Optional query parameters
950
+ * @returns Promise with categories and pagination info
951
+ */
952
+ async listCategories(options) {
953
+ return this.executeRequest(
954
+ () => this.client.GET("/catalog/categories", {
955
+ params: { query: options }
956
+ })
957
+ );
958
+ }
959
+ /**
960
+ * List reviews for a specific product
961
+ *
962
+ * @param pathParams - The path parameters (product ID)
963
+ * @param queryParams - Optional query parameters
964
+ * @returns Promise with reviews and pagination info
965
+ */
966
+ async listProductReviews(pathParams, queryParams) {
967
+ return this.executeRequest(
968
+ () => this.client.GET("/catalog/products/{product_id}/reviews", {
969
+ params: {
970
+ path: pathParams,
971
+ query: queryParams
972
+ }
973
+ })
974
+ );
975
+ }
976
+ /**
977
+ * Create a review for a specific product
978
+ *
979
+ * @param pathParams - The path parameters (product ID)
980
+ * @param formData - The review data
981
+ * @returns Promise that resolves when the review is created
982
+ */
983
+ async createProductReview(pathParams, formData) {
984
+ return this.executeRequest(
985
+ () => this.client.POST("/catalog/products/{product_id}/reviews", {
986
+ params: {
987
+ path: pathParams
988
+ },
989
+ body: formData,
990
+ bodySerializer: (body) => {
991
+ const fd = new FormData();
992
+ for (const [key, value] of Object.entries(body)) {
993
+ if (value !== void 0 && value !== null) {
994
+ if (value instanceof File || value instanceof Blob) {
995
+ fd.append(key, value);
996
+ } else {
997
+ fd.append(key, String(value));
998
+ }
999
+ }
1000
+ }
1001
+ return fd;
1002
+ }
1003
+ })
1004
+ );
1005
+ }
1006
+ /**
1007
+ * Search for products
1008
+ *
1009
+ * @param searchData - The search parameters
1010
+ * @returns Promise with search results, facet distribution, facet stats, and pagination
1011
+ */
1012
+ async searchProducts(searchData, headers) {
1013
+ const mergedHeaders = this.mergeHeaders(headers);
1014
+ return this.executeRequest(
1015
+ () => this.client.POST("/catalog/products/search", {
1016
+ body: searchData,
1017
+ header: mergedHeaders
1018
+ })
1019
+ );
1020
+ }
1021
+ /**
1022
+ * List cross-sell products
1023
+ *
1024
+ * @param options - Optional query parameters
1025
+ * @param headers - Optional header parameters (customer_group_id, etc.)
1026
+ * @returns Promise with cross-sell products
1027
+ */
1028
+ async listCrossSellProducts(options, headers) {
1029
+ const mergedHeaders = this.mergeHeaders(headers);
1030
+ return this.executeRequest(
1031
+ () => this.client.GET("/catalog/products/cross-sell", {
1032
+ params: {
1033
+ query: options,
1034
+ header: mergedHeaders
1035
+ }
1036
+ })
1037
+ );
1038
+ }
1039
+ /**
1040
+ * List up-sell products
1041
+ *
1042
+ * @param options - Optional query parameters
1043
+ * @param headers - Optional header parameters (customer_group_id, etc.)
1044
+ * @returns Promise with up-sell products
1045
+ */
1046
+ async listUpSellProducts(options, headers) {
1047
+ const mergedHeaders = this.mergeHeaders(headers);
1048
+ return this.executeRequest(
1049
+ () => this.client.GET("/catalog/products/up-sell", {
1050
+ params: {
1051
+ query: options,
1052
+ header: mergedHeaders
1053
+ }
1054
+ })
1055
+ );
1056
+ }
1057
+ /**
1058
+ * List similar products
1059
+ *
1060
+ * @param options - Optional query parameters
1061
+ * @param headers - Optional header parameters (customer_group_id, etc.)
1062
+ * @returns Promise with similar products
1063
+ */
1064
+ async listSimilarProducts(options, headers) {
1065
+ const mergedHeaders = this.mergeHeaders(headers);
1066
+ return this.executeRequest(
1067
+ () => this.client.GET("/catalog/products/similar", {
1068
+ params: {
1069
+ query: options,
1070
+ header: mergedHeaders
1071
+ }
1072
+ })
1073
+ );
1074
+ }
1075
+ };
1076
+
1077
+ // src/lib/cart.ts
1078
+ var CartClient = class extends StorefrontAPIClient {
1079
+ /**
1080
+ * Create a new cart
1081
+ *
1082
+ * @param payload - Object containing the items to add to the cart
1083
+ * @returns Promise with the created cart
1084
+ */
1085
+ async createCart(payload) {
1086
+ return this.executeRequest(
1087
+ () => this.client.POST("/carts", {
1088
+ body: payload
1089
+ })
1090
+ );
1091
+ }
1092
+ /**
1093
+ * Get cart details - either by ID or using the stored cart ID
1094
+ *
1095
+ * @param cartId - The ID of the cart
1096
+ * @returns Promise with cart details
1097
+ */
1098
+ async getCart(cartId) {
1099
+ return this.executeRequest(
1100
+ () => this.client.GET("/carts/{id}", {
1101
+ params: {
1102
+ path: cartId
1103
+ }
1104
+ })
1105
+ );
1106
+ }
1107
+ /**
1108
+ * Delete a cart - either by ID or using the stored cart ID
1109
+ *
1110
+ * @param cartId - The ID of the cart
1111
+ * @returns Promise that resolves when the cart is deleted
1112
+ */
1113
+ async deleteCart(cartId) {
1114
+ return this.executeRequest(
1115
+ () => this.client.DELETE("/carts/{id}", {
1116
+ params: {
1117
+ path: cartId
1118
+ }
1119
+ })
1120
+ );
1121
+ }
1122
+ /**
1123
+ * Update cart items (add, update quantity, remove)
1124
+ *
1125
+ * @param cartId - The cart id
1126
+ * @param body - The body of the request
1127
+ * @returns Promise with updated cart
1128
+ */
1129
+ async addDeleteCartItem(cartId, body) {
1130
+ return this.executeRequest(
1131
+ () => this.client.POST("/carts/{id}/items", {
1132
+ params: {
1133
+ path: cartId
1134
+ },
1135
+ body
1136
+ })
1137
+ );
1138
+ }
1139
+ /**
1140
+ * Get cart details by user ID
1141
+ *
1142
+ * @param userId - The ID of the user
1143
+ * @returns Promise with cart details
1144
+ */
1145
+ async getUserCart(userId) {
1146
+ return this.executeRequest(
1147
+ () => this.client.GET("/carts/users/{user_id}", {
1148
+ params: {
1149
+ path: userId
1150
+ }
1151
+ })
1152
+ );
1153
+ }
1154
+ /**
1155
+ * Delete a cart by user ID
1156
+ *
1157
+ * @param userId - The ID of the user
1158
+ * @returns Promise that resolves when the cart is deleted
1159
+ */
1160
+ async deleteUserCart(userId) {
1161
+ return this.executeRequest(
1162
+ () => this.client.DELETE("/carts/users/{user_id}", {
1163
+ params: {
1164
+ path: userId
1165
+ },
1166
+ body: void 0
1167
+ })
1168
+ );
1169
+ }
1170
+ /**
1171
+ * Update cart addresses
1172
+ *
1173
+ * @param cartId - The ID of the cart
1174
+ * @param addressData - The address data
1175
+ * @returns Promise with updated cart
1176
+ */
1177
+ async updateCartAddress(cartId, addressData) {
1178
+ return this.executeRequest(
1179
+ () => this.client.POST("/carts/{id}/address", {
1180
+ params: {
1181
+ path: cartId
1182
+ },
1183
+ body: addressData
1184
+ })
1185
+ );
1186
+ }
1187
+ /**
1188
+ * Apply a coupon to the cart
1189
+ *
1190
+ * @param cartId - The ID of the cart
1191
+ * @param couponCode - The coupon code
1192
+ * @returns Promise with updated cart
1193
+ */
1194
+ async applyCoupon(cartId, couponCode) {
1195
+ return this.executeRequest(
1196
+ () => this.client.POST("/carts/{id}/coupon", {
1197
+ params: {
1198
+ path: cartId
1199
+ },
1200
+ body: couponCode
1201
+ })
1202
+ );
1203
+ }
1204
+ /**
1205
+ * Remove a coupon from the cart
1206
+ *
1207
+ * @param cartId - The ID of the cart
1208
+ * @returns Promise with updated cart
1209
+ */
1210
+ async removeCoupon(cartId) {
1211
+ return this.executeRequest(
1212
+ () => this.client.DELETE("/carts/{id}/coupon", {
1213
+ params: {
1214
+ path: cartId
1215
+ },
1216
+ body: void 0
1217
+ })
1218
+ );
1219
+ }
1220
+ /**
1221
+ * Redeem loyalty points
1222
+ *
1223
+ * @param cartId - The ID of the cart
1224
+ * @param points - The number of points to redeem
1225
+ * @returns Promise with updated cart
1226
+ */
1227
+ async redeemLoyaltyPoints(cartId, points) {
1228
+ return this.executeRequest(
1229
+ () => this.client.POST("/carts/{id}/loyalty-points", {
1230
+ params: {
1231
+ path: cartId
1232
+ },
1233
+ body: points
1234
+ })
1235
+ );
1236
+ }
1237
+ /**
1238
+ * Remove loyalty points
1239
+ *
1240
+ * @param cartId - The ID of the cart
1241
+ * @returns Promise with updated cart
1242
+ */
1243
+ async removeLoyaltyPoints(cartId) {
1244
+ return this.executeRequest(
1245
+ () => this.client.DELETE("/carts/{id}/loyalty-points", {
1246
+ params: {
1247
+ path: cartId
1248
+ },
1249
+ body: void 0
1250
+ })
1251
+ );
1252
+ }
1253
+ /**
1254
+ * Update shipping method
1255
+ *
1256
+ * @param cartId - The ID of the cart
1257
+ * @param body - The body of the request
1258
+ * @returns Promise with updated cart
1259
+ */
1260
+ async updateShippingMethod(cartId, body) {
1261
+ return this.executeRequest(
1262
+ () => this.client.POST("/carts/{id}/shipping-method", {
1263
+ params: {
1264
+ path: cartId
1265
+ },
1266
+ body
1267
+ })
1268
+ );
1269
+ }
1270
+ /**
1271
+ * Use credit balance
1272
+ *
1273
+ * @param cartId - The ID of the cart
1274
+ * @param body - The body of the request
1275
+ * @returns Promise with updated cart
1276
+ */
1277
+ async redeemCreditBalance(cartId, body) {
1278
+ return this.executeRequest(
1279
+ () => this.client.POST("/carts/{id}/credit-balance", {
1280
+ params: {
1281
+ path: cartId
1282
+ },
1283
+ body
1284
+ })
1285
+ );
1286
+ }
1287
+ /**
1288
+ * Remove credit balance
1289
+ *
1290
+ * @param cartId - The ID of the cart
1291
+ * @returns Promise with updated cart
1292
+ */
1293
+ async removeCreditBalance(cartId) {
1294
+ return this.executeRequest(
1295
+ () => this.client.DELETE("/carts/{id}/credit-balance", {
1296
+ params: {
1297
+ path: cartId
1298
+ },
1299
+ body: void 0
1300
+ })
1301
+ );
1302
+ }
1303
+ /**
1304
+ * Redeem gift card
1305
+ *
1306
+ * @param cartId - The ID of the cart
1307
+ * @param body - The body of the request
1308
+ * @returns Promise with updated cart
1309
+ */
1310
+ async redeemGiftCard(cartId, body) {
1311
+ return this.executeRequest(
1312
+ () => this.client.POST("/carts/{id}/gift-card", {
1313
+ params: {
1314
+ path: cartId
1315
+ },
1316
+ body
1317
+ })
1318
+ );
1319
+ }
1320
+ /**
1321
+ * Remove gift card
1322
+ *
1323
+ * @param cartId - The ID of the cart
1324
+ * @returns Promise with updated cart
1325
+ */
1326
+ async removeGiftCard(cartId) {
1327
+ return this.executeRequest(
1328
+ () => this.client.DELETE("/carts/{id}/gift-card", {
1329
+ params: {
1330
+ path: cartId
1331
+ },
1332
+ body: void 0
1333
+ })
1334
+ );
1335
+ }
1336
+ /**
1337
+ * Get wishlist items
1338
+ *
1339
+ * @param userId - The ID of the user
1340
+ * @returns Promise with wishlist items
1341
+ */
1342
+ async getWishlist(userId) {
1343
+ return this.executeRequest(
1344
+ () => this.client.GET("/wishlist/{user_id}", {
1345
+ params: {
1346
+ path: userId
1347
+ }
1348
+ })
1349
+ );
1350
+ }
1351
+ /**
1352
+ * Add item to wishlist
1353
+ *
1354
+ * @param userId - The ID of the user
1355
+ * @param itemId - The ID of the item
1356
+ * @returns Promise with updated wishlist
1357
+ */
1358
+ async addToWishlist(userId, itemId) {
1359
+ return this.executeRequest(
1360
+ () => this.client.POST("/wishlist/{user_id}", {
1361
+ params: {
1362
+ path: userId
1363
+ },
1364
+ body: itemId
1365
+ })
1366
+ );
1367
+ }
1368
+ /**
1369
+ * Remove item from wishlist
1370
+ *
1371
+ * @param userId - The ID of the user
1372
+ * @param itemId - The ID of the item
1373
+ * @returns Promise with updated wishlist
1374
+ */
1375
+ async removeFromWishlist(userId, body) {
1376
+ return this.executeRequest(
1377
+ () => this.client.DELETE("/wishlist/{user_id}", {
1378
+ params: {
1379
+ path: userId
1380
+ },
1381
+ body
1382
+ })
1383
+ );
1384
+ }
1385
+ /**
1386
+ * Get all available coupons
1387
+ *
1388
+ * @param headers - Optional header parameters (customer_group_id, etc.)
1389
+ * @returns Promise with all available coupons
1390
+ */
1391
+ async getAvailableCoupons(headers) {
1392
+ const mergedHeaders = this.mergeHeaders(headers);
1393
+ return this.executeRequest(
1394
+ () => this.client.GET("/carts/available-coupons", {
1395
+ params: {
1396
+ header: mergedHeaders
1397
+ }
1398
+ })
1399
+ );
1400
+ }
1401
+ /**
1402
+ * Get all available promotions
1403
+ *
1404
+ * @param headers - Optional header parameters (customer_group_id, etc.)
1405
+ * @returns Promise with all available promotions
1406
+ */
1407
+ async getAvailablePromotions(headers) {
1408
+ const mergedHeaders = this.mergeHeaders(headers);
1409
+ return this.executeRequest(
1410
+ () => this.client.GET("/carts/available-promotions", {
1411
+ params: {
1412
+ header: mergedHeaders
1413
+ }
1414
+ })
1415
+ );
1416
+ }
1417
+ };
1418
+
1419
+ // src/lib/auth.ts
1420
+ var AuthClient = class extends StorefrontAPIClient {
1421
+ /**
1422
+ * Get anonymous token for guest users
1423
+ */
1424
+ async getAnonymousToken() {
1425
+ return this.executeRequest(
1426
+ () => this.client.POST("/auth/anonymous")
1427
+ );
1428
+ }
1429
+ /**
1430
+ * Login with phone number
1431
+ *
1432
+ * @param phoneNumber - Phone number (without country code)
1433
+ * @param countryCode - Country code (defaults to +91)
1434
+ * @param registerIfNotExists - Whether to register if user doesn't exist
1435
+ * @returns Promise with OTP token and action
1436
+ */
1437
+ async loginWithPhone(body) {
1438
+ return this.executeRequest(
1439
+ () => this.client.POST("/auth/login/phone", {
1440
+ body
1441
+ })
1442
+ );
1443
+ }
1444
+ /**
1445
+ * Login with WhatsApp
1446
+ *
1447
+ * @param phoneNumber - Phone number (without country code)
1448
+ * @param countryCode - Country code (defaults to +91)
1449
+ * @param registerIfNotExists - Whether to register if user doesn't exist
1450
+ * @returns Promise with OTP token and action
1451
+ */
1452
+ async loginWithWhatsApp(body) {
1453
+ return this.executeRequest(
1454
+ () => this.client.POST("/auth/login/whatsapp", {
1455
+ body
1456
+ })
1457
+ );
1458
+ }
1459
+ /**
1460
+ * Login with email
1461
+ *
1462
+ * @param email - Email address
1463
+ * @param registerIfNotExists - Whether to register if user doesn't exist
1464
+ * @returns Promise with OTP token and action
1465
+ */
1466
+ async loginWithEmail(body) {
1467
+ return this.executeRequest(
1468
+ () => this.client.POST("/auth/login/email", {
1469
+ body
1470
+ })
1471
+ );
1472
+ }
1473
+ /**
1474
+ * Login with password
1475
+ *
1476
+ * @param credentials - Login credentials
1477
+ * @returns Promise with user info and tokens
1478
+ */
1479
+ async loginWithPassword(body) {
1480
+ return this.executeRequest(
1481
+ () => this.client.POST("/auth/login/password", {
1482
+ body
1483
+ })
1484
+ );
1485
+ }
1486
+ /**
1487
+ * Forgot password
1488
+ *
1489
+ * @param email - Email address
1490
+ * @returns Promise with user info and tokens
1491
+ */
1492
+ async forgotPassword(body) {
1493
+ return this.executeRequest(
1494
+ () => this.client.POST("/auth/forgot-password", {
1495
+ body
1496
+ })
1497
+ );
1498
+ }
1499
+ /**
1500
+ * Reset password
1501
+ *
1502
+ * @param email - Email address
1503
+ * @returns Promise with user info and tokens
1504
+ */
1505
+ async resetPassword(body) {
1506
+ return this.executeRequest(
1507
+ () => this.client.POST("/auth/reset-password", {
1508
+ body
1509
+ })
1510
+ );
1511
+ }
1512
+ /**
1513
+ * Change password
1514
+ *
1515
+ * @param oldPassword - Old password
1516
+ * @param newPassword - New password
1517
+ * @param newPasswordConfirmation - New password confirmation
1518
+ * @returns Promise with new access token and refresh token
1519
+ */
1520
+ async changePassword(body) {
1521
+ return this.executeRequest(
1522
+ () => this.client.POST("/auth/change-password", {
1523
+ body
1524
+ })
1525
+ );
1526
+ }
1527
+ /**
1528
+ * Verify OTP
1529
+ *
1530
+ * @param otp - One-time password
1531
+ * @param otpToken - OTP token from login request
1532
+ * @param otpAction - OTP action from login request
1533
+ * @returns Promise with user info and tokens
1534
+ */
1535
+ async verifyOtp(body) {
1536
+ return this.executeRequest(
1537
+ () => this.client.POST("/auth/verify-otp", {
1538
+ body
1539
+ })
1540
+ );
1541
+ }
1542
+ /**
1543
+ * Register with phone
1544
+ *
1545
+ * @param options - Registration details
1546
+ * @returns Promise with user info and tokens
1547
+ */
1548
+ async registerWithPhone(body) {
1549
+ return this.executeRequest(
1550
+ () => this.client.POST("/auth/register/phone", {
1551
+ body
1552
+ })
1553
+ );
1554
+ }
1555
+ /**
1556
+ * Register with email
1557
+ *
1558
+ * @param options - Registration details
1559
+ * @returns Promise with user info and tokens
1560
+ */
1561
+ async registerWithEmail(body) {
1562
+ return this.executeRequest(
1563
+ () => this.client.POST("/auth/register/email", {
1564
+ body
1565
+ })
1566
+ );
1567
+ }
1568
+ /**
1569
+ * Refresh the access token using a refresh token
1570
+ * @param refreshToken - The refresh token to use for refreshing the access token
1571
+ * @returns Promise with the new access token and refresh token
1572
+ */
1573
+ async refreshToken(body) {
1574
+ return this.executeRequest(
1575
+ () => this.client.POST("/auth/refresh-token", {
1576
+ body
1577
+ })
1578
+ );
1579
+ }
1580
+ /**
1581
+ * Logout
1582
+ *
1583
+ * @returns Promise that resolves when logout is complete
1584
+ */
1585
+ async logout() {
1586
+ return this.executeRequest(
1587
+ () => this.client.POST("/auth/logout")
1588
+ );
1589
+ }
1590
+ /**
1591
+ * Get user details
1592
+ *
1593
+ * @param userId - User ID
1594
+ * @returns Promise with user details
1595
+ */
1596
+ async getUserDetails(pathParams) {
1597
+ return this.executeRequest(
1598
+ () => this.client.GET("/auth/user/{id}", {
1599
+ params: {
1600
+ path: pathParams
1601
+ }
1602
+ })
1603
+ );
1604
+ }
1605
+ /**
1606
+ * Update user details
1607
+ *
1608
+ * @param userId - User ID
1609
+ * @returns Promise with user details
1610
+ */
1611
+ async updateUserDetails(pathParams, body) {
1612
+ return this.executeRequest(
1613
+ () => this.client.PUT("/auth/user/{id}", {
1614
+ params: {
1615
+ path: pathParams
1616
+ },
1617
+ body
1618
+ })
1619
+ );
1620
+ }
1621
+ /**
1622
+ * Add profile image
1623
+ *
1624
+ * @param userId - User ID
1625
+ * @returns Promise with user details
1626
+ */
1627
+ async addProfileImage(pathParams, formData) {
1628
+ return this.executeRequest(
1629
+ () => this.client.POST("/auth/user/{id}/profile-image", {
1630
+ params: {
1631
+ path: pathParams
1632
+ },
1633
+ body: formData,
1634
+ bodySerializer: (body) => {
1635
+ const fd = new FormData();
1636
+ for (const [key, value] of Object.entries(body)) {
1637
+ if (value !== void 0 && value !== null) {
1638
+ fd.append(key, value);
1639
+ }
1640
+ }
1641
+ return fd;
1642
+ }
1643
+ })
1644
+ );
1645
+ }
1646
+ /**
1647
+ * Update profile image
1648
+ *
1649
+ * @param userId - User ID
1650
+ * @returns Promise with user details
1651
+ */
1652
+ async updateProfileImage(pathParams, formData) {
1653
+ return this.executeRequest(
1654
+ () => this.client.PUT("/auth/user/{id}/profile-image", {
1655
+ params: {
1656
+ path: pathParams
1657
+ },
1658
+ body: formData,
1659
+ bodySerializer: (body) => {
1660
+ const fd = new FormData();
1661
+ for (const [key, value] of Object.entries(body)) {
1662
+ if (value !== void 0 && value !== null) {
1663
+ fd.append(key, value);
1664
+ }
1665
+ }
1666
+ return fd;
1667
+ }
1668
+ })
1669
+ );
1670
+ }
1671
+ /**
1672
+ * Delete profile image
1673
+ *
1674
+ * @param userId - User ID
1675
+ * @returns Promise with user details
1676
+ */
1677
+ async deleteProfileImage(pathParams) {
1678
+ return this.executeRequest(
1679
+ () => this.client.DELETE("/auth/user/{id}/profile-image", {
1680
+ params: {
1681
+ path: pathParams
1682
+ }
1683
+ })
1684
+ );
1685
+ }
1686
+ /**
1687
+ * Get profile image
1688
+ *
1689
+ * @param userId - User ID
1690
+ * @returns Promise with user details
1691
+ */
1692
+ async getProfileImage(pathParams) {
1693
+ return this.executeRequest(
1694
+ () => this.client.GET("/auth/user/{id}/profile-image", {
1695
+ params: {
1696
+ path: pathParams
1697
+ }
1698
+ })
1699
+ );
1700
+ }
1701
+ /**
1702
+ * Deactivate user account
1703
+ *
1704
+ * @param userId - User ID
1705
+ * @returns Promise with user details
1706
+ */
1707
+ async deactivateUserAccount(pathParams) {
1708
+ return this.executeRequest(
1709
+ () => this.client.PUT("/auth/user/{id}/deactivate", {
1710
+ params: {
1711
+ path: pathParams
1712
+ }
1713
+ })
1714
+ );
1715
+ }
1716
+ /**
1717
+ * Get user notification preferences
1718
+ *
1719
+ * @param userId - User ID
1720
+ * @returns Promise with user details
1721
+ */
1722
+ async getUserNotificationPreferences(pathParams) {
1723
+ return this.executeRequest(
1724
+ () => this.client.GET("/auth/user/{id}/notification-preferences", {
1725
+ params: {
1726
+ path: pathParams
1727
+ }
1728
+ })
1729
+ );
1730
+ }
1731
+ /**
1732
+ * Update user notification preferences
1733
+ *
1734
+ * @param userId - User ID
1735
+ * @returns Promise with user details
1736
+ */
1737
+ async updateUserNotificationPreferences(pathParams, body) {
1738
+ return this.executeRequest(
1739
+ () => this.client.PUT("/auth/user/{id}/notification-preferences", {
1740
+ params: {
1741
+ path: pathParams
1742
+ },
1743
+ body
1744
+ })
1745
+ );
1746
+ }
1747
+ /**
1748
+ * Create user notification preference
1749
+ *
1750
+ * @param userId - User ID
1751
+ * @returns Promise with user details
1752
+ */
1753
+ async createUserNotificationPreference(pathParams, body) {
1754
+ return this.executeRequest(
1755
+ () => this.client.POST("/auth/user/{id}/notification-preferences", {
1756
+ params: {
1757
+ path: pathParams
1758
+ },
1759
+ body
1760
+ })
1761
+ );
1762
+ }
1763
+ /**
1764
+ * Generate OTP
1765
+ *
1766
+ * @param body - OTP generation body
1767
+ * @returns Promise with OTP generation response
1768
+ */
1769
+ async generateOtp(body) {
1770
+ return this.executeRequest(
1771
+ () => this.client.POST("/auth/generate-otp", {
1772
+ body
1773
+ })
1774
+ );
1775
+ }
1776
+ /**
1777
+ * Check whether email or phone is already verified
1778
+ *
1779
+ * @param body - OTP generation body
1780
+ * @returns Promise with OTP generation response
1781
+ */
1782
+ async checkEmailOrPhoneIsVerified(body) {
1783
+ return this.executeRequest(
1784
+ () => this.client.POST("/auth/verified-email-phone", {
1785
+ body
1786
+ })
1787
+ );
1788
+ }
1789
+ };
1790
+
1791
+ // src/lib/order.ts
1792
+ var OrderClient = class extends StorefrontAPIClient {
1793
+ /**
1794
+ * Get order details
1795
+ *
1796
+ * @param orderNumber - Order number
1797
+ * @returns Promise with order details
1798
+ */
1799
+ async getOrderDetails(pathParams) {
1800
+ return this.executeRequest(
1801
+ () => this.client.GET("/orders/{order_number}", {
1802
+ params: {
1803
+ path: pathParams
1804
+ }
1805
+ })
1806
+ );
1807
+ }
1808
+ /**
1809
+ * Create order
1810
+ *
1811
+ * @param cartId - Cart ID
1812
+ * @param paymentGateway - Payment gateway
1813
+ * @param paymentGatewayParams - Params for the selected payment gateway
1814
+ * @returns Promise with order details
1815
+ */
1816
+ async createOrder(body) {
1817
+ return this.executeRequest(
1818
+ () => this.client.POST("/orders", {
1819
+ body
1820
+ })
1821
+ );
1822
+ }
1823
+ /**
1824
+ * List all orders
1825
+ *
1826
+ * @param queryParams - Query parameters
1827
+ * @returns Promise with order details
1828
+ */
1829
+ async listOrders(queryParams) {
1830
+ return this.executeRequest(
1831
+ () => this.client.GET("/orders", {
1832
+ params: {
1833
+ query: queryParams
1834
+ }
1835
+ })
1836
+ );
1837
+ }
1838
+ /**
1839
+ * Get payment status for an order
1840
+ *
1841
+ * @param orderNumber - Order number
1842
+ * @returns Promise with payment status
1843
+ */
1844
+ async getPaymentStatus(orderNumber) {
1845
+ return this.executeRequest(
1846
+ () => this.client.GET("/orders/{order_number}/payment-status", {
1847
+ params: {
1848
+ path: { order_number: orderNumber }
1849
+ }
1850
+ })
1851
+ );
1852
+ }
1853
+ /**
1854
+ * Get all shipments for an order
1855
+ *
1856
+ * @param orderNumber - Order number
1857
+ * @returns Promise with shipments
1858
+ */
1859
+ async listOrderShipments(pathParams) {
1860
+ return this.executeRequest(
1861
+ () => this.client.GET("/orders/{order_number}/shipments", {
1862
+ params: {
1863
+ path: pathParams
1864
+ }
1865
+ })
1866
+ );
1867
+ }
1868
+ /**
1869
+ * List order payments
1870
+ *
1871
+ * @param orderNumber - Order number
1872
+ * @returns Promise with payments
1873
+ */
1874
+ async listOrderPayments(pathParams) {
1875
+ return this.executeRequest(
1876
+ () => this.client.GET("/orders/{order_number}/payments", {
1877
+ params: {
1878
+ path: pathParams
1879
+ }
1880
+ })
1881
+ );
1882
+ }
1883
+ /**
1884
+ * List order refunds
1885
+ *
1886
+ * @param orderNumber - Order number
1887
+ * @returns Promise with refunds
1888
+ */
1889
+ async listOrderRefunds(pathParams) {
1890
+ return this.executeRequest(
1891
+ () => this.client.GET("/orders/{order_number}/refunds", {
1892
+ params: {
1893
+ path: pathParams
1894
+ }
1895
+ })
1896
+ );
1897
+ }
1898
+ /**
1899
+ * Cancel an order
1900
+ *
1901
+ * @param orderNumber - Order number
1902
+ * @returns Promise with order details
1903
+ */
1904
+ async cancelOrder(pathParams, body) {
1905
+ return this.executeRequest(
1906
+ () => this.client.POST("/orders/{order_number}/cancel", {
1907
+ params: {
1908
+ path: pathParams
1909
+ },
1910
+ body
1911
+ })
1912
+ );
1913
+ }
1914
+ /**
1915
+ * Retry payment for an order
1916
+ *
1917
+ * @param orderNumber - Order number
1918
+ * @returns Promise with order details
1919
+ */
1920
+ async retryOrderPayment(pathParams, body) {
1921
+ return this.executeRequest(
1922
+ () => this.client.POST("/orders/{order_number}/retry-payment", {
1923
+ params: {
1924
+ path: pathParams
1925
+ },
1926
+ body
1927
+ })
1928
+ );
1929
+ }
1930
+ };
1931
+
1932
+ // src/lib/shipping.ts
1933
+ var ShippingClient = class extends StorefrontAPIClient {
1934
+ /**
1935
+ * Get shipping options for an order
1936
+ *
1937
+ * @param body - Shipping methods body
1938
+ * @returns Promise with shipping options
1939
+ */
1940
+ async getShippingMethods(body) {
1941
+ return this.executeRequest(
1942
+ () => this.client.POST("/shipping/shipping-methods", {
1943
+ body
1944
+ })
1945
+ );
1946
+ }
1947
+ /**
1948
+ * Check pincode deliverability
1949
+ *
1950
+ * @param pathParams - Path parameters
1951
+ * @returns Promise with pincode deliverability result
1952
+ */
1953
+ async checkPincodeDeliverability(pathParams) {
1954
+ return this.executeRequest(
1955
+ () => this.client.GET("/shipping/serviceability/{pincode}", {
1956
+ params: {
1957
+ path: pathParams
1958
+ }
1959
+ })
1960
+ );
1961
+ }
1962
+ };
1963
+
1964
+ // src/lib/helper.ts
1965
+ var HelpersClient = class extends StorefrontAPIClient {
1966
+ /**
1967
+ * Get a list of countries
1968
+ *
1969
+ * @returns Promise with countries
1970
+ */
1971
+ async listCountries() {
1972
+ return this.executeRequest(
1973
+ () => this.client.GET("/common/countries", {})
1974
+ );
1975
+ }
1976
+ /**
1977
+ * - Get a list of states for a country
1978
+ *
1979
+ * @param pathParams - Path parameters
1980
+ * @returns Promise with states
1981
+ */
1982
+ async listCountryStates(pathParams) {
1983
+ return this.executeRequest(
1984
+ () => this.client.GET("/common/countries/{country_iso_code}/states", {
1985
+ params: {
1986
+ path: pathParams
1987
+ }
1988
+ })
1989
+ );
1990
+ }
1991
+ /**
1992
+ * Get pincodes for a country
1993
+ *
1994
+ * @param pathParams - Path parameters
1995
+ * @returns Promise with pincodes
1996
+ */
1997
+ async listCountryPincodes(pathParams) {
1998
+ return this.executeRequest(
1999
+ () => this.client.GET("/common/countries/{country_iso_code}/pincodes", {
2000
+ params: {
2001
+ path: pathParams
2002
+ }
2003
+ })
2004
+ );
2005
+ }
2006
+ };
2007
+
2008
+ // src/lib/customer.ts
2009
+ var CustomerClient = class extends StorefrontAPIClient {
2010
+ /**
2011
+ * Create a customer
2012
+ *
2013
+ * @param body - Customer creation body
2014
+ * @returns Promise with customer details
2015
+ */
2016
+ async createCustomer(body) {
2017
+ return this.executeRequest(
2018
+ () => this.client.POST("/customers", {
2019
+ body
2020
+ })
2021
+ );
2022
+ }
2023
+ /**
2024
+ * Get customer details
2025
+ *
2026
+ * @param pathParams - Path parameters
2027
+ * @returns Promise with customer details
2028
+ */
2029
+ async getCustomer(pathParams) {
2030
+ return this.executeRequest(
2031
+ () => this.client.GET("/customers/{id}", {
2032
+ params: {
2033
+ path: pathParams
2034
+ }
2035
+ })
2036
+ );
2037
+ }
2038
+ /**
2039
+ * Update a customer
2040
+ *
2041
+ * @param pathParams - Path parameters
2042
+ * @param body - Customer update body
2043
+ * @returns Promise with customer details
2044
+ */
2045
+ async updateCustomer(pathParams, body) {
2046
+ return this.executeRequest(
2047
+ () => this.client.PUT("/customers/{id}", {
2048
+ params: {
2049
+ path: pathParams
2050
+ },
2051
+ body
2052
+ })
2053
+ );
2054
+ }
2055
+ /**
2056
+ * Get all saved addresses for a customer
2057
+ *
2058
+ * @param pathParams - Path parameters
2059
+ * @returns Promise with addresses
2060
+ */
2061
+ async listAddresses(pathParams) {
2062
+ return this.executeRequest(
2063
+ () => this.client.GET("/customers/{user_id}/addresses", {
2064
+ params: {
2065
+ path: pathParams
2066
+ }
2067
+ })
2068
+ );
2069
+ }
2070
+ /**
2071
+ * Create a new address for a customer
2072
+ *
2073
+ * @param pathParams - Path parameters
2074
+ * @param body - Address creation body
2075
+ * @returns Promise with address details
2076
+ */
2077
+ async createAddress(pathParams, body) {
2078
+ return this.executeRequest(
2079
+ () => this.client.POST("/customers/{user_id}/addresses", {
2080
+ params: {
2081
+ path: pathParams
2082
+ },
2083
+ body
2084
+ })
2085
+ );
2086
+ }
2087
+ /**
2088
+ * Get an address for a customer
2089
+ *
2090
+ * @param pathParams - Path parameters
2091
+ * @returns Promise with address details
2092
+ */
2093
+ async getAddress(pathParams) {
2094
+ return this.executeRequest(
2095
+ () => this.client.GET("/customers/{user_id}/addresses/{address_id}", {
2096
+ params: {
2097
+ path: pathParams
2098
+ }
2099
+ })
2100
+ );
2101
+ }
2102
+ /**
2103
+ * Update an address for a customer
2104
+ *
2105
+ * @param pathParams - Path parameters
2106
+ * @param body - Address update body
2107
+ * @returns Promise with address details
2108
+ */
2109
+ async updateAddress(pathParams, body) {
2110
+ return this.executeRequest(
2111
+ () => this.client.PUT("/customers/{user_id}/addresses/{address_id}", {
2112
+ params: {
2113
+ path: pathParams
2114
+ },
2115
+ body
2116
+ })
2117
+ );
2118
+ }
2119
+ /**
2120
+ * Delete an address for a customer
2121
+ *
2122
+ * @param pathParams - Path parameters
2123
+ * @returns Promise with address details
2124
+ */
2125
+ async deleteAddress(pathParams) {
2126
+ return this.executeRequest(
2127
+ () => this.client.DELETE("/customers/{user_id}/addresses/{address_id}", {
2128
+ params: {
2129
+ path: pathParams
2130
+ }
2131
+ })
2132
+ );
2133
+ }
2134
+ /**
2135
+ * Get customer loyalty details
2136
+ *
2137
+ * @param pathParams - Path parameters
2138
+ * @returns Promise with loyalty details
2139
+ */
2140
+ async getLoyaltyDetails(pathParams) {
2141
+ return this.executeRequest(
2142
+ () => this.client.GET("/customers/{user_id}/loyalty", {
2143
+ params: {
2144
+ path: pathParams
2145
+ }
2146
+ })
2147
+ );
2148
+ }
2149
+ /**
2150
+ * List all loyalty points activity for a customer
2151
+ *
2152
+ * @param pathParams - Path parameters
2153
+ * @returns Promise with loyalty points activity
2154
+ */
2155
+ async listLoyaltyPointsActivity(pathParams) {
2156
+ return this.executeRequest(
2157
+ () => this.client.GET("/customers/{user_id}/loyalty-points-activity", {
2158
+ params: {
2159
+ path: pathParams
2160
+ }
2161
+ })
2162
+ );
2163
+ }
2164
+ /**
2165
+ * List all reviews left by a customer
2166
+ *
2167
+ * @param pathParams - Path parameters
2168
+ * @returns Promise with reviews
2169
+ */
2170
+ async listCustomerReviews(pathParams) {
2171
+ return this.executeRequest(
2172
+ () => this.client.GET("/customers/{user_id}/reviews", {
2173
+ params: {
2174
+ path: pathParams
2175
+ }
2176
+ })
2177
+ );
2178
+ }
2179
+ };
2180
+
2181
+ // src/index.ts
2182
+ var StorefrontSDK = class {
2183
+ /**
2184
+ * Client for catalog-related endpoints (products, categories, etc.)
2185
+ */
2186
+ catalog;
2187
+ /**
2188
+ * Client for cart-related endpoints
2189
+ */
2190
+ cart;
2191
+ /**
2192
+ * Client for authentication-related endpoints
2193
+ */
2194
+ auth;
2195
+ /**
2196
+ * Client for customer-related endpoints
2197
+ */
2198
+ customer;
2199
+ /**
2200
+ * Client for helper-related endpoints
2201
+ */
2202
+ helpers;
2203
+ /**
2204
+ * Client for shipping-related endpoints
2205
+ */
2206
+ shipping;
2207
+ /**
2208
+ * Client for order-related endpoints
2209
+ */
2210
+ order;
2211
+ /**
2212
+ * Create a new StorefrontSDK instance
2213
+ *
2214
+ * @param options - Configuration options for the SDK
2215
+ */
2216
+ constructor(options) {
2217
+ const config = {
2218
+ storeId: options.storeId,
2219
+ environment: options.environment,
2220
+ baseUrl: options.baseUrl,
2221
+ accessToken: options.accessToken,
2222
+ refreshToken: options.refreshToken,
2223
+ apiKey: options.apiKey,
2224
+ timeout: options.timeout,
2225
+ tokenStorage: options.tokenStorage,
2226
+ onTokensUpdated: options.onTokensUpdated,
2227
+ onTokensCleared: options.onTokensCleared,
2228
+ defaultHeaders: options.defaultHeaders,
2229
+ debug: options.debug,
2230
+ logger: options.logger
2231
+ };
2232
+ this.catalog = new CatalogClient(config);
2233
+ this.cart = new CartClient(config);
2234
+ this.auth = new AuthClient(config);
2235
+ this.customer = new CustomerClient(config);
2236
+ this.helpers = new HelpersClient(config);
2237
+ this.shipping = new ShippingClient(config);
2238
+ this.order = new OrderClient(config);
2239
+ }
2240
+ /**
2241
+ * Set authentication tokens for all clients
2242
+ *
2243
+ * @param accessToken - The access token (required)
2244
+ * @param refreshToken - The refresh token (optional)
2245
+ *
2246
+ * Behavior:
2247
+ * - If tokenStorage is provided: Stores tokens for automatic management
2248
+ * - If tokenStorage is not provided: Only stores access token for manual management
2249
+ */
2250
+ async setTokens(accessToken, refreshToken) {
2251
+ await this.catalog.setTokens(accessToken, refreshToken);
2252
+ await this.cart.setTokens(accessToken, refreshToken);
2253
+ await this.auth.setTokens(accessToken, refreshToken);
2254
+ await this.customer.setTokens(accessToken, refreshToken);
2255
+ await this.helpers.setTokens(accessToken, refreshToken);
2256
+ await this.shipping.setTokens(accessToken, refreshToken);
2257
+ await this.order.setTokens(accessToken, refreshToken);
2258
+ }
2259
+ /**
2260
+ * Clear all authentication tokens from all clients
2261
+ *
2262
+ * Behavior:
2263
+ * - If tokenStorage is provided: Clears both access and refresh tokens from storage
2264
+ * - If tokenStorage is not provided: Clears the manual access token
2265
+ */
2266
+ async clearTokens() {
2267
+ await this.catalog.clearTokens();
2268
+ await this.cart.clearTokens();
2269
+ await this.auth.clearTokens();
2270
+ await this.customer.clearTokens();
2271
+ await this.helpers.clearTokens();
2272
+ await this.shipping.clearTokens();
2273
+ await this.order.clearTokens();
2274
+ }
2275
+ /**
2276
+ * Set the API key for all clients
2277
+ *
2278
+ * @param apiKey - The API key to set
2279
+ */
2280
+ setApiKey(apiKey) {
2281
+ this.catalog.setApiKey(apiKey);
2282
+ this.cart.setApiKey(apiKey);
2283
+ this.auth.setApiKey(apiKey);
2284
+ this.customer.setApiKey(apiKey);
2285
+ this.helpers.setApiKey(apiKey);
2286
+ this.shipping.setApiKey(apiKey);
2287
+ this.order.setApiKey(apiKey);
2288
+ }
2289
+ /**
2290
+ * Clear the API key from all clients
2291
+ */
2292
+ clearApiKey() {
2293
+ this.catalog.clearApiKey();
2294
+ this.cart.clearApiKey();
2295
+ this.auth.clearApiKey();
2296
+ this.customer.clearApiKey();
2297
+ this.helpers.clearApiKey();
2298
+ this.shipping.clearApiKey();
2299
+ this.order.clearApiKey();
2300
+ }
2301
+ /**
2302
+ * Get the current access token if using token storage
2303
+ */
2304
+ async getAccessToken() {
2305
+ return await this.auth.getAuthorizationHeader().then(
2306
+ (header) => header.startsWith("Bearer ") ? header.substring(7) : null
2307
+ );
2308
+ }
2309
+ /**
2310
+ * Get user information from the current access token
2311
+ *
2312
+ * @returns User information extracted from JWT token, or null if no token or invalid token
2313
+ */
2314
+ async getUserInfo() {
2315
+ const token = await this.getAccessToken();
2316
+ if (!token) return null;
2317
+ return extractUserInfoFromToken(token);
2318
+ }
2319
+ /**
2320
+ * Get the current user ID from the access token
2321
+ *
2322
+ * @returns User ID (ulid) or null if no token or invalid token
2323
+ */
2324
+ async getUserId() {
2325
+ const token = await this.getAccessToken();
2326
+ if (!token) return null;
2327
+ return getUserIdFromToken(token);
2328
+ }
2329
+ /**
2330
+ * Check if the current user is logged in (not anonymous)
2331
+ *
2332
+ * @returns True if user is logged in, false if anonymous or no token
2333
+ */
2334
+ async isLoggedIn() {
2335
+ const token = await this.getAccessToken();
2336
+ if (!token) return false;
2337
+ return isUserLoggedIn(token);
2338
+ }
2339
+ /**
2340
+ * Check if the current user is anonymous
2341
+ *
2342
+ * @returns True if user is anonymous or no token, false if logged in
2343
+ */
2344
+ async isAnonymous() {
2345
+ const token = await this.getAccessToken();
2346
+ if (!token) return true;
2347
+ return isUserAnonymous(token);
2348
+ }
2349
+ /**
2350
+ * Get the customer ID from the current access token
2351
+ *
2352
+ * @returns Customer ID or null if no token, invalid token, or user has no customer ID
2353
+ */
2354
+ async getCustomerId() {
2355
+ const userInfo = await this.getUserInfo();
2356
+ return userInfo?.customerId || null;
2357
+ }
2358
+ /**
2359
+ * Get the customer group ID from the current access token
2360
+ *
2361
+ * @returns Customer group ID or null if no token, invalid token, or user has no customer group
2362
+ */
2363
+ async getCustomerGroupId() {
2364
+ const userInfo = await this.getUserInfo();
2365
+ return userInfo?.customerGroupId || null;
2366
+ }
2367
+ /**
2368
+ * Set default headers for all clients
2369
+ *
2370
+ * @param headers - Default headers to set (only supported headers allowed)
2371
+ */
2372
+ setDefaultHeaders(headers) {
2373
+ const newConfig = { ...this.catalog["config"], defaultHeaders: headers };
2374
+ this.catalog["config"] = newConfig;
2375
+ this.cart["config"] = newConfig;
2376
+ this.auth["config"] = newConfig;
2377
+ this.customer["config"] = newConfig;
2378
+ this.helpers["config"] = newConfig;
2379
+ this.shipping["config"] = newConfig;
2380
+ this.order["config"] = newConfig;
2381
+ }
2382
+ /**
2383
+ * Get current default headers
2384
+ *
2385
+ * @returns Current default headers
2386
+ */
2387
+ getDefaultHeaders() {
2388
+ return this.catalog["config"].defaultHeaders;
2389
+ }
2390
+ };
2391
+ var index_default = StorefrontSDK;
2392
+ export {
2393
+ AuthClient,
2394
+ BrowserTokenStorage,
2395
+ CartClient,
2396
+ CatalogClient,
2397
+ CookieTokenStorage,
2398
+ CustomerClient,
2399
+ Environment,
2400
+ HelpersClient,
2401
+ MemoryTokenStorage,
2402
+ OrderClient,
2403
+ ResponseUtils,
2404
+ ShippingClient,
2405
+ StorefrontAPIClient,
2406
+ StorefrontSDK,
2407
+ index_default as default
2408
+ };
2409
+ //# sourceMappingURL=index.js.map