@commercengine/storefront-sdk 0.3.12 → 0.4.0

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