@commercengine/storefront-sdk 0.8.0 → 0.8.2

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 DELETED
@@ -1,4311 +0,0 @@
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
- StoreConfigClient: () => StoreConfigClient,
46
- StorefrontAPIClient: () => StorefrontAPIClient,
47
- StorefrontSDK: () => StorefrontSDK,
48
- default: () => index_default
49
- });
50
- module.exports = __toCommonJS(index_exports);
51
-
52
- // src/lib/client.ts
53
- var import_openapi_fetch = __toESM(require("openapi-fetch"), 1);
54
-
55
- // src/lib/jwt-utils.ts
56
- var import_jose = require("jose");
57
- function extractUserInfoFromToken(token) {
58
- try {
59
- const payload = (0, import_jose.decodeJwt)(token);
60
- return {
61
- id: payload.ulid,
62
- email: payload.email,
63
- phone: payload.phone,
64
- username: payload.username,
65
- firstName: payload.first_name,
66
- lastName: payload.last_name,
67
- storeId: payload.store_id,
68
- isLoggedIn: payload.is_logged_in,
69
- isAnonymous: !payload.is_logged_in,
70
- customerId: payload.customer_id,
71
- customerGroupId: payload.customer_group_id,
72
- anonymousId: payload.anonymous_id,
73
- tokenExpiry: new Date(payload.exp * 1e3),
74
- tokenIssuedAt: new Date(payload.iat * 1e3)
75
- };
76
- } catch (error) {
77
- console.warn("Failed to decode JWT token:", error);
78
- return null;
79
- }
80
- }
81
- function isTokenExpired(token, bufferSeconds = 30) {
82
- try {
83
- const payload = (0, import_jose.decodeJwt)(token);
84
- if (!payload.exp) return true;
85
- const currentTime = Math.floor(Date.now() / 1e3);
86
- const expiryTime = payload.exp;
87
- return currentTime >= expiryTime - bufferSeconds;
88
- } catch (error) {
89
- console.warn("Failed to decode JWT token:", error);
90
- return true;
91
- }
92
- }
93
- function getUserIdFromToken(token) {
94
- const userInfo = extractUserInfoFromToken(token);
95
- return userInfo?.id || null;
96
- }
97
- function isUserLoggedIn(token) {
98
- const userInfo = extractUserInfoFromToken(token);
99
- return userInfo?.isLoggedIn || false;
100
- }
101
- function isUserAnonymous(token) {
102
- const userInfo = extractUserInfoFromToken(token);
103
- return userInfo?.isAnonymous || true;
104
- }
105
-
106
- // src/lib/auth-utils.ts
107
- function getPathnameFromUrl(url) {
108
- try {
109
- const urlObj = new URL(url);
110
- return urlObj.pathname;
111
- } catch {
112
- return url.split("?")[0];
113
- }
114
- }
115
- function isAnonymousAuthEndpoint(pathname) {
116
- return pathname.endsWith("/auth/anonymous");
117
- }
118
- function isTokenReturningEndpoint(pathname) {
119
- const tokenEndpoints = [
120
- "/auth/login/password",
121
- "/auth/register/phone",
122
- "/auth/register/email",
123
- "/auth/verify-otp",
124
- "/auth/refresh-token"
125
- ];
126
- return tokenEndpoints.some((endpoint) => pathname.endsWith(endpoint));
127
- }
128
- function isLogoutEndpoint(pathname) {
129
- return pathname.endsWith("/auth/logout");
130
- }
131
-
132
- // src/lib/middleware.ts
133
- var MemoryTokenStorage = class {
134
- accessToken = null;
135
- refreshToken = null;
136
- async getAccessToken() {
137
- return this.accessToken;
138
- }
139
- async setAccessToken(token) {
140
- this.accessToken = token;
141
- }
142
- async getRefreshToken() {
143
- return this.refreshToken;
144
- }
145
- async setRefreshToken(token) {
146
- this.refreshToken = token;
147
- }
148
- async clearTokens() {
149
- this.accessToken = null;
150
- this.refreshToken = null;
151
- }
152
- };
153
- var BrowserTokenStorage = class {
154
- accessTokenKey;
155
- refreshTokenKey;
156
- constructor(prefix = "storefront_") {
157
- this.accessTokenKey = `${prefix}access_token`;
158
- this.refreshTokenKey = `${prefix}refresh_token`;
159
- }
160
- async getAccessToken() {
161
- if (typeof localStorage === "undefined") return null;
162
- return localStorage.getItem(this.accessTokenKey);
163
- }
164
- async setAccessToken(token) {
165
- if (typeof localStorage !== "undefined") {
166
- localStorage.setItem(this.accessTokenKey, token);
167
- }
168
- }
169
- async getRefreshToken() {
170
- if (typeof localStorage === "undefined") return null;
171
- return localStorage.getItem(this.refreshTokenKey);
172
- }
173
- async setRefreshToken(token) {
174
- if (typeof localStorage !== "undefined") {
175
- localStorage.setItem(this.refreshTokenKey, token);
176
- }
177
- }
178
- async clearTokens() {
179
- if (typeof localStorage !== "undefined") {
180
- localStorage.removeItem(this.accessTokenKey);
181
- localStorage.removeItem(this.refreshTokenKey);
182
- }
183
- }
184
- };
185
- var CookieTokenStorage = class {
186
- accessTokenKey;
187
- refreshTokenKey;
188
- options;
189
- constructor(options = {}) {
190
- const prefix = options.prefix || "storefront_";
191
- this.accessTokenKey = `${prefix}access_token`;
192
- this.refreshTokenKey = `${prefix}refresh_token`;
193
- this.options = {
194
- maxAge: options.maxAge || 7 * 24 * 60 * 60,
195
- // 7 days default
196
- path: options.path || "/",
197
- domain: options.domain,
198
- secure: options.secure ?? (typeof window !== "undefined" && window.location?.protocol === "https:"),
199
- sameSite: options.sameSite || "Lax",
200
- httpOnly: false
201
- // Must be false for client-side access
202
- };
203
- }
204
- async getAccessToken() {
205
- return this.getCookie(this.accessTokenKey);
206
- }
207
- async setAccessToken(token) {
208
- this.setCookie(this.accessTokenKey, token);
209
- }
210
- async getRefreshToken() {
211
- return this.getCookie(this.refreshTokenKey);
212
- }
213
- async setRefreshToken(token) {
214
- this.setCookie(this.refreshTokenKey, token);
215
- }
216
- async clearTokens() {
217
- this.deleteCookie(this.accessTokenKey);
218
- this.deleteCookie(this.refreshTokenKey);
219
- }
220
- getCookie(name) {
221
- if (typeof document === "undefined") return null;
222
- const value = `; ${document.cookie}`;
223
- const parts = value.split(`; ${name}=`);
224
- if (parts.length === 2) {
225
- const cookieValue = parts.pop()?.split(";").shift();
226
- return cookieValue ? decodeURIComponent(cookieValue) : null;
227
- }
228
- return null;
229
- }
230
- setCookie(name, value) {
231
- if (typeof document === "undefined") return;
232
- const encodedValue = encodeURIComponent(value);
233
- let cookieString = `${name}=${encodedValue}`;
234
- if (this.options.maxAge) {
235
- cookieString += `; Max-Age=${this.options.maxAge}`;
236
- }
237
- if (this.options.path) {
238
- cookieString += `; Path=${this.options.path}`;
239
- }
240
- if (this.options.domain) {
241
- cookieString += `; Domain=${this.options.domain}`;
242
- }
243
- if (this.options.secure) {
244
- cookieString += `; Secure`;
245
- }
246
- if (this.options.sameSite) {
247
- cookieString += `; SameSite=${this.options.sameSite}`;
248
- }
249
- document.cookie = cookieString;
250
- }
251
- deleteCookie(name) {
252
- if (typeof document === "undefined") return;
253
- let cookieString = `${name}=; Max-Age=0`;
254
- if (this.options.path) {
255
- cookieString += `; Path=${this.options.path}`;
256
- }
257
- if (this.options.domain) {
258
- cookieString += `; Domain=${this.options.domain}`;
259
- }
260
- document.cookie = cookieString;
261
- }
262
- };
263
- function createAuthMiddleware(config) {
264
- let isRefreshing = false;
265
- let refreshPromise = null;
266
- let hasAssessedTokens = false;
267
- const assessTokenStateOnce = async () => {
268
- if (hasAssessedTokens) return;
269
- hasAssessedTokens = true;
270
- try {
271
- const accessToken = await config.tokenStorage.getAccessToken();
272
- const refreshToken = await config.tokenStorage.getRefreshToken();
273
- if (!accessToken && refreshToken) {
274
- await config.tokenStorage.clearTokens();
275
- console.info("Cleaned up orphaned refresh token");
276
- }
277
- } catch (error) {
278
- console.warn("Token state assessment failed:", error);
279
- }
280
- };
281
- const refreshTokens = async () => {
282
- if (isRefreshing && refreshPromise) {
283
- return refreshPromise;
284
- }
285
- isRefreshing = true;
286
- refreshPromise = (async () => {
287
- try {
288
- const refreshToken = await config.tokenStorage.getRefreshToken();
289
- let newTokens;
290
- if (refreshToken && !isTokenExpired(refreshToken)) {
291
- if (config.refreshTokenFn) {
292
- newTokens = await config.refreshTokenFn(refreshToken);
293
- } else {
294
- const response = await fetch(
295
- `${config.baseUrl}/auth/refresh-token`,
296
- {
297
- method: "POST",
298
- headers: {
299
- "Content-Type": "application/json"
300
- },
301
- body: JSON.stringify({ refresh_token: refreshToken })
302
- }
303
- );
304
- if (!response.ok) {
305
- throw new Error(`Token refresh failed: ${response.status}`);
306
- }
307
- const data = await response.json();
308
- newTokens = data.content;
309
- }
310
- } else {
311
- const currentAccessToken = await config.tokenStorage.getAccessToken();
312
- if (!currentAccessToken) {
313
- throw new Error("No tokens available for refresh");
314
- }
315
- const reason = refreshToken ? "refresh token expired" : "no refresh token available";
316
- const response = await fetch(`${config.baseUrl}/auth/anonymous`, {
317
- method: "POST",
318
- headers: {
319
- "Content-Type": "application/json",
320
- ...config.apiKey && { "X-Api-Key": config.apiKey },
321
- Authorization: `Bearer ${currentAccessToken}`
322
- // For user_id continuity
323
- }
324
- });
325
- if (!response.ok) {
326
- throw new Error(
327
- `Anonymous token fallback failed: ${response.status}`
328
- );
329
- }
330
- const data = await response.json();
331
- newTokens = data.content;
332
- console.info(
333
- `Token refreshed via anonymous fallback (${reason}) - user may need to re-authenticate for privileged operations`
334
- );
335
- }
336
- await config.tokenStorage.setAccessToken(newTokens.access_token);
337
- await config.tokenStorage.setRefreshToken(newTokens.refresh_token);
338
- config.onTokensUpdated?.(
339
- newTokens.access_token,
340
- newTokens.refresh_token
341
- );
342
- } catch (error) {
343
- console.error("Token refresh failed:", error);
344
- await config.tokenStorage.clearTokens();
345
- config.onTokensCleared?.();
346
- throw error;
347
- } finally {
348
- isRefreshing = false;
349
- refreshPromise = null;
350
- }
351
- })();
352
- return refreshPromise;
353
- };
354
- return {
355
- async onRequest({ request }) {
356
- const pathname = getPathnameFromUrl(request.url);
357
- await assessTokenStateOnce();
358
- if (isAnonymousAuthEndpoint(pathname)) {
359
- if (config.apiKey) {
360
- request.headers.set("X-Api-Key", config.apiKey);
361
- }
362
- const existingToken = await config.tokenStorage.getAccessToken();
363
- if (existingToken && !isTokenExpired(existingToken) && isUserLoggedIn(existingToken)) {
364
- return new Response(
365
- JSON.stringify({
366
- message: "Cannot create anonymous session while authenticated",
367
- success: false,
368
- code: "USER_ALREADY_AUTHENTICATED"
369
- }),
370
- {
371
- status: 400,
372
- headers: { "Content-Type": "application/json" }
373
- }
374
- );
375
- }
376
- if (existingToken) {
377
- request.headers.set("Authorization", `Bearer ${existingToken}`);
378
- }
379
- return request;
380
- }
381
- let accessToken = await config.tokenStorage.getAccessToken();
382
- if (!accessToken) {
383
- try {
384
- const response = await fetch(`${config.baseUrl}/auth/anonymous`, {
385
- method: "POST",
386
- headers: {
387
- "Content-Type": "application/json",
388
- ...config.apiKey && { "X-Api-Key": config.apiKey }
389
- }
390
- });
391
- if (response.ok) {
392
- const data = await response.json();
393
- const tokens = data.content;
394
- if (tokens?.access_token && tokens?.refresh_token) {
395
- await config.tokenStorage.setAccessToken(tokens.access_token);
396
- await config.tokenStorage.setRefreshToken(tokens.refresh_token);
397
- accessToken = tokens.access_token;
398
- config.onTokensUpdated?.(tokens.access_token, tokens.refresh_token);
399
- console.info("Automatically created anonymous session for first API request");
400
- }
401
- }
402
- } catch (error) {
403
- console.warn("Failed to automatically create anonymous tokens:", error);
404
- }
405
- }
406
- if (accessToken && isTokenExpired(accessToken)) {
407
- try {
408
- await refreshTokens();
409
- accessToken = await config.tokenStorage.getAccessToken();
410
- } catch (error) {
411
- }
412
- }
413
- if (accessToken) {
414
- request.headers.set("Authorization", `Bearer ${accessToken}`);
415
- }
416
- return request;
417
- },
418
- async onResponse({ request, response }) {
419
- const pathname = getPathnameFromUrl(request.url);
420
- if (response.ok) {
421
- if (isTokenReturningEndpoint(pathname) || isAnonymousAuthEndpoint(pathname)) {
422
- try {
423
- const data = await response.clone().json();
424
- const content = data.content;
425
- if (content?.access_token && content?.refresh_token) {
426
- await config.tokenStorage.setAccessToken(content.access_token);
427
- await config.tokenStorage.setRefreshToken(content.refresh_token);
428
- config.onTokensUpdated?.(
429
- content.access_token,
430
- content.refresh_token
431
- );
432
- }
433
- } catch (error) {
434
- console.warn("Failed to extract tokens from response:", error);
435
- }
436
- } else if (isLogoutEndpoint(pathname)) {
437
- await config.tokenStorage.clearTokens();
438
- config.onTokensCleared?.();
439
- }
440
- }
441
- if (response.status === 401 && !isAnonymousAuthEndpoint(pathname)) {
442
- const currentToken = await config.tokenStorage.getAccessToken();
443
- if (currentToken && isTokenExpired(currentToken, 0)) {
444
- try {
445
- await refreshTokens();
446
- const newToken = await config.tokenStorage.getAccessToken();
447
- if (newToken) {
448
- const retryRequest = request.clone();
449
- retryRequest.headers.set("Authorization", `Bearer ${newToken}`);
450
- return fetch(retryRequest);
451
- }
452
- } catch (error) {
453
- console.warn("Token refresh failed on 401 response:", error);
454
- }
455
- }
456
- }
457
- return response;
458
- }
459
- };
460
- }
461
- function createDefaultAuthMiddleware(options) {
462
- const tokenStorage = options.tokenStorage || (typeof localStorage !== "undefined" ? new BrowserTokenStorage() : new MemoryTokenStorage());
463
- return createAuthMiddleware({
464
- tokenStorage,
465
- apiKey: options.apiKey,
466
- baseUrl: options.baseUrl,
467
- onTokensUpdated: options.onTokensUpdated,
468
- onTokensCleared: options.onTokensCleared
469
- });
470
- }
471
-
472
- // src/lib/logger-utils.ts
473
- var ResponseUtils = class {
474
- /**
475
- * Get response headers as a plain object
476
- */
477
- static getHeaders(response) {
478
- return Object.fromEntries(response.headers.entries());
479
- }
480
- /**
481
- * Get specific header value
482
- */
483
- static getHeader(response, name) {
484
- return response.headers.get(name);
485
- }
486
- /**
487
- * Check if response was successful
488
- */
489
- static isSuccess(response) {
490
- return response.ok;
491
- }
492
- /**
493
- * Get response metadata
494
- */
495
- static getMetadata(response) {
496
- return {
497
- status: response.status,
498
- statusText: response.statusText,
499
- ok: response.ok,
500
- url: response.url,
501
- redirected: response.redirected,
502
- type: response.type,
503
- headers: Object.fromEntries(response.headers.entries())
504
- };
505
- }
506
- /**
507
- * Clone and read response as text (useful for debugging)
508
- * Note: This can only be called once per response
509
- */
510
- static async getText(response) {
511
- const cloned = response.clone();
512
- return await cloned.text();
513
- }
514
- /**
515
- * Clone and read response as JSON (useful for debugging)
516
- * Note: This can only be called once per response
517
- */
518
- static async getJSON(response) {
519
- const cloned = response.clone();
520
- return await cloned.json();
521
- }
522
- /**
523
- * Format response information for debugging
524
- */
525
- static format(response) {
526
- const metadata = this.getMetadata(response);
527
- return `${metadata.status} ${metadata.statusText} - ${metadata.url}`;
528
- }
529
- };
530
- var DebugLogger = class {
531
- logger;
532
- responseTextCache = /* @__PURE__ */ new Map();
533
- constructor(logger) {
534
- this.logger = logger || ((level, message, data) => {
535
- console.log(`[${level.toUpperCase()}]`, message);
536
- if (data) console.log(data);
537
- });
538
- }
539
- /**
540
- * Log debug information about API request
541
- */
542
- logRequest(request, requestBody) {
543
- this.logger("info", "API Request Debug Info", {
544
- method: request.method,
545
- url: request.url,
546
- headers: Object.fromEntries(request.headers.entries()),
547
- body: requestBody,
548
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
549
- });
550
- }
551
- /**
552
- * Log debug information about API response
553
- */
554
- async logResponse(response, responseBody) {
555
- if (responseBody && typeof responseBody === "string") {
556
- this.responseTextCache.set(response.url, responseBody);
557
- }
558
- this.logger("info", "API Response Debug Info", {
559
- url: response.url,
560
- status: response.status,
561
- statusText: response.statusText,
562
- ok: response.ok,
563
- headers: Object.fromEntries(response.headers.entries()),
564
- redirected: response.redirected,
565
- type: response.type,
566
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
567
- });
568
- if (responseBody) {
569
- this.logger("info", "API Response Data", {
570
- data: responseBody,
571
- contentType: response.headers.get("content-type"),
572
- contentLength: response.headers.get("content-length")
573
- });
574
- }
575
- }
576
- /**
577
- * Log error information
578
- */
579
- logError(message, error) {
580
- this.logger("error", message, error);
581
- }
582
- /**
583
- * Get cached response text for a URL (if available)
584
- */
585
- getCachedResponseText(url) {
586
- return this.responseTextCache.get(url) || null;
587
- }
588
- /**
589
- * Clear cached response texts
590
- */
591
- clearCache() {
592
- this.responseTextCache.clear();
593
- }
594
- };
595
- async function extractRequestBody(request) {
596
- if (request.method === "GET" || request.method === "HEAD") {
597
- return null;
598
- }
599
- try {
600
- const clonedRequest = request.clone();
601
- const contentType = request.headers.get("content-type")?.toLowerCase();
602
- if (contentType?.startsWith("application/json")) {
603
- return await clonedRequest.json();
604
- } else if (contentType?.startsWith("multipart/form-data")) {
605
- return "[FormData - cannot display]";
606
- } else if (contentType?.startsWith("text/")) {
607
- return await clonedRequest.text();
608
- }
609
- return "[Request body - unknown format]";
610
- } catch (error) {
611
- return "[Request body unavailable]";
612
- }
613
- }
614
- function createDebugMiddleware(logger) {
615
- const debugLogger = new DebugLogger(logger);
616
- return {
617
- async onRequest({ request }) {
618
- const requestBody = await extractRequestBody(request);
619
- debugLogger.logRequest(request, requestBody);
620
- return request;
621
- },
622
- async onResponse({ response }) {
623
- const cloned = response.clone();
624
- let responseBody = null;
625
- try {
626
- const contentType = response.headers.get("content-type")?.toLowerCase();
627
- if (contentType?.startsWith("application/json")) {
628
- responseBody = await cloned.json();
629
- } else if (contentType?.startsWith("text/")) {
630
- responseBody = await cloned.text();
631
- }
632
- } catch (error) {
633
- }
634
- await debugLogger.logResponse(response, responseBody);
635
- return response;
636
- },
637
- async onError({ error, request }) {
638
- debugLogger.logError("API Request Failed", {
639
- error: {
640
- name: error instanceof Error ? error.name : "Unknown",
641
- message: error instanceof Error ? error.message : String(error),
642
- stack: error instanceof Error ? error.stack : void 0
643
- },
644
- request: {
645
- method: request.method,
646
- url: request.url,
647
- headers: Object.fromEntries(request.headers.entries())
648
- },
649
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
650
- });
651
- throw error;
652
- }
653
- };
654
- }
655
-
656
- // src/lib/header-utils.ts
657
- var HEADER_TRANSFORMATIONS = {
658
- customer_group_id: "x-customer-group-id"
659
- // Future transformations can be added here:
660
- // some_param: "X-Some-Header",
661
- // another_param: "X-Another-Header",
662
- };
663
- function transformHeaders(headers) {
664
- const transformed = {};
665
- for (const [key, value] of Object.entries(headers)) {
666
- if (value !== void 0) {
667
- const headerName = HEADER_TRANSFORMATIONS[key] || key;
668
- transformed[headerName] = value;
669
- }
670
- }
671
- return transformed;
672
- }
673
- function mergeHeaders(defaultHeaders, methodHeaders) {
674
- const merged = {};
675
- if (defaultHeaders) {
676
- const transformedDefaults = transformHeaders(defaultHeaders);
677
- Object.assign(merged, transformedDefaults);
678
- }
679
- if (methodHeaders) {
680
- Object.assign(merged, methodHeaders);
681
- }
682
- Object.keys(merged).forEach((key) => {
683
- if (merged[key] === void 0) {
684
- delete merged[key];
685
- }
686
- });
687
- return merged;
688
- }
689
-
690
- // src/lib/client.ts
691
- var Environment = /* @__PURE__ */ ((Environment2) => {
692
- Environment2["Staging"] = "staging";
693
- Environment2["Production"] = "production";
694
- return Environment2;
695
- })(Environment || {});
696
- var StorefrontAPIClient = class {
697
- client;
698
- config;
699
- baseUrl;
700
- initializationPromise = null;
701
- /**
702
- * Create a new StorefrontAPIClient
703
- *
704
- * @param config - Configuration for the API client
705
- */
706
- constructor(config) {
707
- this.config = { ...config };
708
- this.baseUrl = this.getBaseUrlFromConfig(this.config);
709
- this.client = (0, import_openapi_fetch.default)({
710
- baseUrl: this.baseUrl
711
- });
712
- if (this.config.tokenStorage) {
713
- const authMiddleware = createDefaultAuthMiddleware({
714
- apiKey: this.config.apiKey,
715
- baseUrl: this.baseUrl,
716
- tokenStorage: this.config.tokenStorage,
717
- onTokensUpdated: this.config.onTokensUpdated,
718
- onTokensCleared: this.config.onTokensCleared
719
- });
720
- this.client.use(authMiddleware);
721
- if (this.config.accessToken) {
722
- this.initializationPromise = this.initializeTokens(
723
- this.config.accessToken,
724
- this.config.refreshToken
725
- );
726
- this.config.accessToken = void 0;
727
- this.config.refreshToken = void 0;
728
- }
729
- } else {
730
- this.client.use({
731
- onRequest: async ({ request }) => {
732
- const pathname = getPathnameFromUrl(request.url);
733
- if (isAnonymousAuthEndpoint(pathname)) {
734
- if (this.config.apiKey) {
735
- request.headers.set("X-Api-Key", this.config.apiKey);
736
- }
737
- if (this.config.accessToken) {
738
- request.headers.set(
739
- "Authorization",
740
- `Bearer ${this.config.accessToken}`
741
- );
742
- }
743
- return request;
744
- }
745
- if (this.config.accessToken) {
746
- request.headers.set(
747
- "Authorization",
748
- `Bearer ${this.config.accessToken}`
749
- );
750
- }
751
- return request;
752
- }
753
- });
754
- }
755
- if (this.config.timeout) {
756
- this.setupTimeoutMiddleware();
757
- }
758
- if (this.config.debug) {
759
- const debugMiddleware = createDebugMiddleware(this.config.logger);
760
- this.client.use(debugMiddleware);
761
- }
762
- }
763
- /**
764
- * Set up timeout middleware
765
- */
766
- setupTimeoutMiddleware() {
767
- this.client.use({
768
- onRequest: async ({ request }) => {
769
- const controller = new AbortController();
770
- const timeoutId = setTimeout(
771
- () => controller.abort(),
772
- this.config.timeout
773
- );
774
- if (request.signal) {
775
- request.signal.addEventListener("abort", () => controller.abort());
776
- }
777
- const newRequest = new Request(request, {
778
- signal: controller.signal
779
- });
780
- controller.signal.addEventListener(
781
- "abort",
782
- () => clearTimeout(timeoutId)
783
- );
784
- return newRequest;
785
- }
786
- });
787
- }
788
- /**
789
- * Constructs the base URL from the configuration
790
- *
791
- * @param config - The client configuration
792
- * @returns The constructed base URL
793
- */
794
- getBaseUrlFromConfig(config) {
795
- if (config.baseUrl) {
796
- return config.baseUrl;
797
- }
798
- const env = config.environment || "production" /* Production */;
799
- switch (env) {
800
- case "staging" /* Staging */:
801
- return `https://staging.api.commercengine.io/api/v1/${config.storeId}/storefront`;
802
- case "production" /* Production */:
803
- default:
804
- return `https://prod.api.commercengine.io/api/v1/${config.storeId}/storefront`;
805
- }
806
- }
807
- /**
808
- * Get the base URL of the API
809
- *
810
- * @returns The base URL of the API
811
- */
812
- getBaseUrl() {
813
- return this.baseUrl;
814
- }
815
- /**
816
- * Get the authorization header value
817
- * If using token storage, gets the current token from storage
818
- * Otherwise returns the manual token
819
- *
820
- * @returns The Authorization header value or empty string if no token is set
821
- */
822
- async getAuthorizationHeader() {
823
- if (this.config.tokenStorage && this.initializationPromise) {
824
- await this.initializationPromise;
825
- }
826
- if (this.config.tokenStorage) {
827
- const token = await this.config.tokenStorage.getAccessToken();
828
- return token ? `Bearer ${token}` : "";
829
- }
830
- return this.config.accessToken ? `Bearer ${this.config.accessToken}` : "";
831
- }
832
- /**
833
- * Set authentication tokens
834
- *
835
- * @param accessToken - The access token (required)
836
- * @param refreshToken - The refresh token (optional)
837
- *
838
- * Behavior:
839
- * - If tokenStorage is provided: Stores tokens for automatic management
840
- * - If tokenStorage is not provided: Only stores access token for manual management
841
- */
842
- async setTokens(accessToken, refreshToken) {
843
- if (this.config.tokenStorage) {
844
- await this.config.tokenStorage.setAccessToken(accessToken);
845
- if (refreshToken) {
846
- await this.config.tokenStorage.setRefreshToken(refreshToken);
847
- }
848
- } else {
849
- this.config.accessToken = accessToken;
850
- if (refreshToken) {
851
- console.warn(
852
- "Refresh token provided but ignored in manual token management mode. Use tokenStorage for automatic management."
853
- );
854
- }
855
- }
856
- }
857
- /**
858
- * Clear all authentication tokens
859
- *
860
- * Behavior:
861
- * - If tokenStorage is provided: Clears both access and refresh tokens from storage
862
- * - If tokenStorage is not provided: Clears the manual access token
863
- */
864
- async clearTokens() {
865
- if (this.config.tokenStorage) {
866
- await this.config.tokenStorage.clearTokens();
867
- } else {
868
- this.config.accessToken = void 0;
869
- }
870
- }
871
- /**
872
- * Set the X-Api-Key header
873
- *
874
- * @param apiKey - The API key to set
875
- */
876
- setApiKey(apiKey) {
877
- this.config.apiKey = apiKey;
878
- }
879
- /**
880
- * Clear the X-Api-Key header
881
- */
882
- clearApiKey() {
883
- this.config.apiKey = void 0;
884
- }
885
- /**
886
- * Execute a request and handle the response
887
- *
888
- * @param apiCall - Function that executes the API request
889
- * @returns Promise with the API response
890
- */
891
- async executeRequest(apiCall) {
892
- try {
893
- const { data, error, response } = await apiCall();
894
- if (error) {
895
- return {
896
- data: null,
897
- error,
898
- response
899
- };
900
- }
901
- if (data && data.content !== void 0) {
902
- return {
903
- data: data.content,
904
- error: null,
905
- response
906
- };
907
- }
908
- return {
909
- data,
910
- error: null,
911
- response
912
- };
913
- } catch (err) {
914
- const mockResponse = new Response(null, {
915
- status: 0,
916
- statusText: "Network Error"
917
- });
918
- const errorResult = {
919
- data: null,
920
- error: {
921
- success: false,
922
- code: "NETWORK_ERROR",
923
- message: "Network error occurred",
924
- error: err
925
- },
926
- response: mockResponse
927
- };
928
- return errorResult;
929
- }
930
- }
931
- /**
932
- * Initialize tokens in storage (private helper method)
933
- */
934
- async initializeTokens(accessToken, refreshToken) {
935
- try {
936
- if (this.config.tokenStorage) {
937
- await this.config.tokenStorage.setAccessToken(accessToken);
938
- if (refreshToken) {
939
- await this.config.tokenStorage.setRefreshToken(refreshToken);
940
- }
941
- }
942
- } catch (error) {
943
- console.warn("Failed to initialize tokens in storage:", error);
944
- }
945
- }
946
- /**
947
- * Merge default headers with method-level headers
948
- * Method-level headers take precedence over default headers
949
- *
950
- * @param methodHeaders - Headers passed to the specific method call
951
- * @returns Merged headers object with proper HTTP header names
952
- */
953
- mergeHeaders(methodHeaders) {
954
- return mergeHeaders(this.config.defaultHeaders, methodHeaders);
955
- }
956
- };
957
-
958
- // src/lib/catalog.ts
959
- var CatalogClient = class extends StorefrontAPIClient {
960
- /**
961
- * List all products
962
- *
963
- * @param options - Optional query parameters
964
- * @param headers - Optional header parameters (customer_group_id, etc.)
965
- * @returns Promise with products and pagination info
966
- *
967
- * @example
968
- * ```typescript
969
- * // Basic product listing
970
- * const { data, error } = await sdk.catalog.listProducts();
971
- *
972
- * if (error) {
973
- * console.error("Failed to list products:", error);
974
- * return;
975
- * }
976
- *
977
- * console.log("Products found:", data.products?.length || 0);
978
- * console.log("Pagination:", data.pagination);
979
- *
980
- * // With filtering and pagination
981
- * const { data: filteredData, error: filteredError } = await sdk.catalog.listProducts({
982
- * page: 1,
983
- * limit: 20,
984
- * sort_by: JSON.stringify({ "created_at": "desc" }),
985
- * category_slug: ["electronics", "smartphones"]
986
- * });
987
- *
988
- * // Override customer group ID for this specific request
989
- * const { data: overrideData, error: overrideError } = await sdk.catalog.listProducts(
990
- * {
991
- * page: 1,
992
- * limit: 20,
993
- * sort_by: JSON.stringify({ "created_at": "desc" }),
994
- * category_slug: ["electronics", "smartphones"]
995
- * },
996
- * {
997
- * "x-customer-group-id": "01H9XYZ12345USERID" // Override default SDK config
998
- * }
999
- * );
1000
- *
1001
- * if (filteredError) {
1002
- * console.error("Failed to get filtered products:", filteredError);
1003
- * return;
1004
- * }
1005
- *
1006
- * filteredData.products?.forEach(product => {
1007
- * console.log(`Product: ${product.name} - ${product.price}`);
1008
- * });
1009
- * ```
1010
- */
1011
- async listProducts(options, headers) {
1012
- const mergedHeaders = this.mergeHeaders(headers);
1013
- return this.executeRequest(
1014
- () => this.client.GET("/catalog/products", {
1015
- params: {
1016
- query: options,
1017
- header: mergedHeaders
1018
- }
1019
- })
1020
- );
1021
- }
1022
- /**
1023
- * List all skus
1024
- *
1025
- * @param options - Optional query parameters
1026
- * @param headers - Optional header parameters (customer_group_id, etc.)
1027
- * @returns Promise with skus and pagination info
1028
- *
1029
- * @example
1030
- * ```typescript
1031
- * // Basic SKU listing
1032
- * const { data, error } = await sdk.catalog.listSkus();
1033
- *
1034
- * if (error) {
1035
- * console.error("Failed to list SKUs:", error);
1036
- * return;
1037
- * }
1038
- *
1039
- * console.log("SKUs found:", data.skus?.length || 0);
1040
- * console.log("Pagination:", data.pagination);
1041
- *
1042
- * // With pagination
1043
- * const { data: skuData, error: skuError } = await sdk.catalog.listSkus({
1044
- * page: 1,
1045
- * limit: 50
1046
- * });
1047
- *
1048
- * // Override customer group ID for this specific request
1049
- * const { data: overrideData, error: overrideError } = await sdk.catalog.listSkus(
1050
- * {
1051
- * page: 1,
1052
- * limit: 50
1053
- * },
1054
- * {
1055
- * "x-customer-group-id": "01H9XYZ12345USERID" // Override default SDK config
1056
- * }
1057
- * );
1058
- *
1059
- * if (skuError) {
1060
- * console.error("Failed to get SKUs:", skuError);
1061
- * return;
1062
- * }
1063
- *
1064
- * skuData.skus?.forEach(sku => {
1065
- * console.log(`SKU: ${sku.sku} - Price: ${sku.price}`);
1066
- * });
1067
- * ```
1068
- */
1069
- async listSkus(options, headers) {
1070
- const mergedHeaders = this.mergeHeaders(headers);
1071
- return this.executeRequest(
1072
- () => this.client.GET("/catalog/skus", {
1073
- params: {
1074
- query: options,
1075
- header: mergedHeaders
1076
- }
1077
- })
1078
- );
1079
- }
1080
- /**
1081
- * Get details for a specific product
1082
- *
1083
- * @param pathParams - The path parameters (product ID or slug)
1084
- * @param headers - Optional header parameters (customer_group_id, etc.)
1085
- * @returns Promise with product details
1086
- *
1087
- * @example
1088
- * ```typescript
1089
- * // Get product by ID
1090
- * const { data, error } = await sdk.catalog.getProductDetail(
1091
- * { product_id_or_slug: "prod_123" }
1092
- * );
1093
- *
1094
- * if (error) {
1095
- * console.error("Failed to get product details:", error);
1096
- * return;
1097
- * }
1098
- *
1099
- * console.log("Product:", data.product.name);
1100
- * console.log("Price:", data.product.price);
1101
- * console.log("Description:", data.product.description);
1102
- *
1103
- * // Get product by slug
1104
- * const { data: slugData, error: slugError } = await sdk.catalog.getProductDetail({
1105
- * product_id_or_slug: "detox-candy"
1106
- * });
1107
- *
1108
- * // Override customer group ID for this specific request
1109
- * const { data: overrideData, error: overrideError } = await sdk.catalog.getProductDetail(
1110
- * { product_id_or_slug: "detox-candy" },
1111
- * {
1112
- * "x-customer-group-id": "premium_customers" // Override default SDK config
1113
- * }
1114
- * );
1115
- *
1116
- * if (slugError) {
1117
- * console.error("Failed to get product by slug:", slugError);
1118
- * return;
1119
- * }
1120
- *
1121
- * console.log("Product with custom pricing:", slugData.product.price);
1122
- * ```
1123
- */
1124
- async getProductDetail(pathParams, headers) {
1125
- const mergedHeaders = this.mergeHeaders(headers);
1126
- return this.executeRequest(
1127
- () => this.client.GET("/catalog/products/{product_id_or_slug}", {
1128
- params: {
1129
- path: pathParams,
1130
- header: mergedHeaders
1131
- }
1132
- })
1133
- );
1134
- }
1135
- /**
1136
- * List all variants for a specific product
1137
- *
1138
- * @param pathParams - The path parameters (product ID)
1139
- * @param headers - Optional header parameters (customer_group_id, etc.)
1140
- * @returns Promise with product variants and pagination info
1141
- *
1142
- * @example
1143
- * ```typescript
1144
- * const { data, error } = await sdk.catalog.listProductVariants(
1145
- * { product_id: "prod_123" }
1146
- * );
1147
- *
1148
- * if (error) {
1149
- * console.error("Failed to list product variants:", error);
1150
- * return;
1151
- * }
1152
- *
1153
- * console.log("Variants found:", data.variants?.length || 0);
1154
- *
1155
- * data.variants?.forEach(variant => {
1156
- * console.log(`Variant: ${variant.name} - SKU: ${variant.sku} - Price: ${variant.price}`);
1157
- * });
1158
- *
1159
- * // Override customer group ID for this specific request
1160
- * const { data: overrideData, error: overrideError } = await sdk.catalog.listProductVariants(
1161
- * { product_id: "prod_123" },
1162
- * {
1163
- * "x-customer-group-id": "wholesale_customers" // Override default SDK config
1164
- * }
1165
- * );
1166
- * ```
1167
- */
1168
- async listProductVariants(pathParams, headers) {
1169
- const mergedHeaders = this.mergeHeaders(headers);
1170
- return this.executeRequest(
1171
- () => this.client.GET("/catalog/products/{product_id}/variants", {
1172
- params: {
1173
- path: pathParams,
1174
- header: mergedHeaders
1175
- }
1176
- })
1177
- );
1178
- }
1179
- /**
1180
- * Get details for a specific product variant
1181
- *
1182
- * @param pathParams - The path parameters (product ID and variant ID)
1183
- * @param headers - Optional header parameters (customer_group_id, etc.)
1184
- * @returns Promise with variant details
1185
- *
1186
- * @example
1187
- * ```typescript
1188
- * const { data, error } = await sdk.catalog.getVariantDetail(
1189
- * {
1190
- * product_id: "prod_123",
1191
- * variant_id: "var_456"
1192
- * }
1193
- * );
1194
- *
1195
- * if (error) {
1196
- * console.error("Failed to get variant details:", error);
1197
- * return;
1198
- * }
1199
- *
1200
- * console.log("Variant:", data.variant.name);
1201
- * console.log("SKU:", data.variant.sku);
1202
- * console.log("Price:", data.variant.price);
1203
- * console.log("Stock:", data.variant.stock);
1204
- * ```
1205
- */
1206
- async getVariantDetail(pathParams, headers) {
1207
- const mergedHeaders = this.mergeHeaders(headers);
1208
- return this.executeRequest(
1209
- () => this.client.GET("/catalog/products/{product_id}/variants/{variant_id}", {
1210
- params: {
1211
- path: pathParams,
1212
- header: mergedHeaders
1213
- }
1214
- })
1215
- );
1216
- }
1217
- /**
1218
- * List all product categories
1219
- *
1220
- * @param options - Optional query parameters
1221
- * @returns Promise with categories and pagination info
1222
- *
1223
- * @example
1224
- * ```typescript
1225
- * // Basic category listing
1226
- * const { data, error } = await sdk.catalog.listCategories();
1227
- *
1228
- * if (error) {
1229
- * console.error("Failed to list categories:", error);
1230
- * return;
1231
- * }
1232
- *
1233
- * console.log("Categories found:", data.categories?.length || 0);
1234
- *
1235
- * data.categories?.forEach(category => {
1236
- * console.log(`Category: ${category.name} - ${category.description}`);
1237
- * });
1238
- *
1239
- * // With pagination
1240
- * const { data: catData, error: catError } = await sdk.catalog.listCategories({
1241
- * page: 1,
1242
- * limit: 10
1243
- * });
1244
- * ```
1245
- */
1246
- async listCategories(options) {
1247
- return this.executeRequest(
1248
- () => this.client.GET("/catalog/categories", {
1249
- params: {
1250
- query: options
1251
- }
1252
- })
1253
- );
1254
- }
1255
- /**
1256
- * List all reviews for a specific product
1257
- *
1258
- * @param pathParams - The path parameters (product ID)
1259
- * @param queryParams - Optional query parameters
1260
- * @returns Promise with product reviews and pagination info
1261
- *
1262
- * @example
1263
- * ```typescript
1264
- * const { data, error } = await sdk.catalog.listProductReviews(
1265
- * { product_id: "prod_123" }
1266
- * );
1267
- *
1268
- * if (error) {
1269
- * console.error("Failed to list product reviews:", error);
1270
- * return;
1271
- * }
1272
- *
1273
- * console.log("Reviews found:", data.reviews?.length || 0);
1274
- *
1275
- * data.reviews?.forEach(review => {
1276
- * console.log(`Review by ${review.customer_name}: ${review.rating}/5`);
1277
- * console.log("Comment:", review.comment);
1278
- * });
1279
- *
1280
- * // With pagination
1281
- * const { data: reviewData, error: reviewError } = await sdk.catalog.listProductReviews(
1282
- * { product_id: "prod_123" },
1283
- * {
1284
- * page: 1,
1285
- * limit: 5
1286
- * }
1287
- * );
1288
- * ```
1289
- */
1290
- async listProductReviews(pathParams, queryParams) {
1291
- return this.executeRequest(
1292
- () => this.client.GET("/catalog/products/{product_id}/reviews", {
1293
- params: {
1294
- path: pathParams,
1295
- query: queryParams
1296
- }
1297
- })
1298
- );
1299
- }
1300
- /**
1301
- * Create a product review
1302
- *
1303
- * @param pathParams - The path parameters (product ID)
1304
- * @param formData - The review data including rating, comment, and optional images
1305
- * @returns Promise with review creation response
1306
- *
1307
- * @example
1308
- * ```typescript
1309
- * const { data, error } = await sdk.catalog.createProductReview(
1310
- * { product_id: "prod_123" },
1311
- * {
1312
- * rating: 5,
1313
- * comment: "Excellent product! Highly recommended.",
1314
- * images: [
1315
- * new File(["image data"], "review1.jpg", { type: "image/jpeg" }),
1316
- * new File(["image data"], "review2.jpg", { type: "image/jpeg" })
1317
- * ]
1318
- * }
1319
- * );
1320
- *
1321
- * if (error) {
1322
- * console.error("Failed to create review:", error);
1323
- * return;
1324
- * }
1325
- *
1326
- * console.log("Review created successfully:", data.message);
1327
- * ```
1328
- */
1329
- async createProductReview(pathParams, formData) {
1330
- return this.executeRequest(
1331
- () => this.client.POST("/catalog/products/{product_id}/reviews", {
1332
- params: {
1333
- path: pathParams
1334
- },
1335
- body: formData,
1336
- bodySerializer: (body) => {
1337
- const fd = new FormData();
1338
- for (const [key, value] of Object.entries(body)) {
1339
- if (value !== void 0 && value !== null) {
1340
- if (value instanceof File || value instanceof Blob) {
1341
- fd.append(key, value);
1342
- } else {
1343
- fd.append(key, String(value));
1344
- }
1345
- }
1346
- }
1347
- return fd;
1348
- }
1349
- })
1350
- );
1351
- }
1352
- /**
1353
- * Search for products
1354
- *
1355
- * @param searchData - The search query and filters
1356
- * @param headers - Optional header parameters (customer_group_id, etc.)
1357
- * @returns Promise with search results including products, facets, and pagination
1358
- *
1359
- * @example
1360
- * ```typescript
1361
- * const { data, error } = await sdk.catalog.searchProducts({
1362
- * query: "smartphone",
1363
- * filters: {
1364
- * category: ["electronics", "mobile"],
1365
- * price_range: { min: 100, max: 1000 },
1366
- * brand: ["Apple", "Samsung"] // facet names depend on product configuration
1367
- * },
1368
- * page: 1,
1369
- * limit: 20
1370
- * });
1371
- *
1372
- * if (error) {
1373
- * console.error("Failed to search products:", error);
1374
- * return;
1375
- * }
1376
- *
1377
- * console.log("Search results:", data.skus?.length || 0, "products found");
1378
- * console.log("Facet distribution:", data.facet_distribution);
1379
- * console.log("Price range:", data.facet_stats.price_range);
1380
- *
1381
- * data.skus?.forEach(sku => {
1382
- * console.log(`Found: ${sku.name} - ${sku.price}`);
1383
- * });
1384
- *
1385
- * // Override customer group ID for this specific request
1386
- * const { data: overrideData, error: overrideError } = await sdk.catalog.searchProducts(
1387
- * {
1388
- * query: "laptop",
1389
- * filters: { category: ["computers"] }
1390
- * },
1391
- * {
1392
- * "x-customer-group-id": "01H9XYZ12345USERID" // Override default SDK config
1393
- * }
1394
- * );
1395
- * ```
1396
- */
1397
- async searchProducts(searchData, headers) {
1398
- const mergedHeaders = this.mergeHeaders(headers);
1399
- return this.executeRequest(
1400
- () => this.client.POST("/catalog/products/search", {
1401
- params: {
1402
- header: mergedHeaders
1403
- },
1404
- body: searchData
1405
- })
1406
- );
1407
- }
1408
- /**
1409
- * List cross-sell products
1410
- *
1411
- * @param options - Optional query parameters for filtering and pagination
1412
- * @param headers - Optional header parameters (customer_group_id, etc.)
1413
- * @returns Promise with cross-sell products
1414
- * @example
1415
- * ```typescript
1416
- * // Basic usage - get cross-sell products for cart items
1417
- * const { data, error } = await sdk.catalog.listCrossSellProducts({
1418
- * product_id: ["prod_01H9XYZ12345ABCDE", "prod_01H9ABC67890FGHIJ"]
1419
- * });
1420
- *
1421
- * // Advanced usage with pagination and custom sorting
1422
- * const { data, error } = await sdk.catalog.listCrossSellProducts({
1423
- * product_id: ["prod_01H9XYZ12345ABCDE"],
1424
- * page: 1,
1425
- * limit: 10,
1426
- * sort_by: '{"price":"asc"}'
1427
- * });
1428
- *
1429
- * // Override customer group ID for this specific request
1430
- * const { data, error } = await sdk.catalog.listCrossSellProducts(
1431
- * {
1432
- * product_id: ["prod_01H9XYZ12345ABCDE"],
1433
- * page: 1,
1434
- * limit: 10
1435
- * },
1436
- * {
1437
- * "x-customer-group-id": "01H9XYZ12345USERID" // Override default SDK config
1438
- * }
1439
- * );
1440
- *
1441
- * if (error) {
1442
- * console.error("Failed to get cross-sell products:", error.message);
1443
- * } else {
1444
- * console.log("Cross-sell products found:", data.content.products.length);
1445
- * console.log("Pagination:", data.content.pagination);
1446
- *
1447
- * data.content.products.forEach(product => {
1448
- * console.log(`Product: ${product.name} - ${product.price}`);
1449
- * });
1450
- * }
1451
- * ```
1452
- */
1453
- async listCrossSellProducts(options, headers) {
1454
- const mergedHeaders = this.mergeHeaders(headers);
1455
- return this.executeRequest(
1456
- () => this.client.GET("/catalog/products/cross-sell", {
1457
- params: {
1458
- query: options,
1459
- header: mergedHeaders
1460
- }
1461
- })
1462
- );
1463
- }
1464
- /**
1465
- * List up-sell products
1466
- *
1467
- * @param options - Optional query parameters for filtering and pagination
1468
- * @param headers - Optional header parameters (customer_group_id, etc.)
1469
- * @returns Promise with up-sell products
1470
- * @example
1471
- * ```typescript
1472
- * // Basic usage - get up-sell products for cart items
1473
- * const { data, error } = await sdk.catalog.listUpSellProducts({
1474
- * product_id: ["prod_01H9XYZ12345ABCDE"]
1475
- * });
1476
- *
1477
- * // Advanced usage with pagination and custom sorting
1478
- * const { data, error } = await sdk.catalog.listUpSellProducts({
1479
- * product_id: ["prod_01H9XYZ12345ABCDE"],
1480
- * page: 1,
1481
- * limit: 15,
1482
- * sort_by: '{"relevance":"desc"}'
1483
- * });
1484
- *
1485
- * // Override customer group ID for this specific request
1486
- * const { data, error } = await sdk.catalog.listUpSellProducts(
1487
- * {
1488
- * product_id: ["prod_01H9XYZ12345ABCDE"],
1489
- * page: 1,
1490
- * limit: 15
1491
- * },
1492
- * {
1493
- * "x-customer-group-id": "01H9XYZ12345USERID" // Override default SDK config
1494
- * }
1495
- * );
1496
- *
1497
- * if (error) {
1498
- * console.error("Failed to get up-sell products:", error.message);
1499
- * } else {
1500
- * console.log("Up-sell products found:", data.content.products.length);
1501
- * console.log("Pagination:", data.content.pagination);
1502
- *
1503
- * data.content.products.forEach(product => {
1504
- * console.log(`Up-sell: ${product.name} - ${product.price}`);
1505
- * });
1506
- * }
1507
- * ```
1508
- */
1509
- async listUpSellProducts(options, headers) {
1510
- const mergedHeaders = this.mergeHeaders(headers);
1511
- return this.executeRequest(
1512
- () => this.client.GET("/catalog/products/up-sell", {
1513
- params: {
1514
- query: options,
1515
- header: mergedHeaders
1516
- }
1517
- })
1518
- );
1519
- }
1520
- /**
1521
- * List similar products
1522
- *
1523
- * @param options - Optional query parameters for filtering and pagination
1524
- * @param headers - Optional header parameters (customer_group_id, etc.)
1525
- * @returns Promise with similar products
1526
- * @example
1527
- * ```typescript
1528
- * // Basic usage - get similar products for a specific product
1529
- * const { data, error } = await sdk.catalog.listSimilarProducts({
1530
- * product_id: ["prod_01H9XYZ12345ABCDE"]
1531
- * });
1532
- *
1533
- * // Advanced usage with pagination and custom sorting
1534
- * const { data, error } = await sdk.catalog.listSimilarProducts({
1535
- * product_id: ["prod_01H9XYZ12345ABCDE"],
1536
- * page: 1,
1537
- * limit: 20,
1538
- * sort_by: '{"relevance":"desc"}'
1539
- * });
1540
- *
1541
- * // Override customer group ID for this specific request
1542
- * const { data, error } = await sdk.catalog.listSimilarProducts(
1543
- * {
1544
- * product_id: ["prod_01H9XYZ12345ABCDE"],
1545
- * page: 1,
1546
- * limit: 20
1547
- * },
1548
- * {
1549
- * "x-customer-group-id": "01H9XYZ12345USERID" // Override default SDK config
1550
- * }
1551
- * );
1552
- *
1553
- * if (error) {
1554
- * console.error("Failed to get similar products:", error.message);
1555
- * } else {
1556
- * console.log("Similar products found:", data.content.products.length);
1557
- * console.log("Pagination:", data.content.pagination);
1558
- *
1559
- * data.content.products.forEach(product => {
1560
- * console.log(`Similar: ${product.name} - ${product.price}`);
1561
- * });
1562
- * }
1563
- * ```
1564
- */
1565
- async listSimilarProducts(options, headers) {
1566
- const mergedHeaders = this.mergeHeaders(headers);
1567
- return this.executeRequest(
1568
- () => this.client.GET("/catalog/products/similar", {
1569
- params: {
1570
- query: options,
1571
- header: mergedHeaders
1572
- }
1573
- })
1574
- );
1575
- }
1576
- };
1577
-
1578
- // src/lib/cart.ts
1579
- var CartClient = class extends StorefrontAPIClient {
1580
- /**
1581
- * Create a new cart
1582
- *
1583
- * @param payload - Object containing the items to add to the cart
1584
- * @returns Promise with the created cart
1585
- * @example
1586
- * ```typescript
1587
- * const { data, error } = await sdk.cart.createCart({
1588
- * items: [
1589
- * {
1590
- * product_id: "01H9XYZ12345ABCDE",
1591
- * variant_id: null,
1592
- * quantity: 2
1593
- * },
1594
- * {
1595
- * product_id: "01H9ABC67890FGHIJ",
1596
- * variant_id: "01H9XYZ67890KLMNO",
1597
- * quantity: 1
1598
- * }
1599
- * ],
1600
- * metadata: {
1601
- * "source": "web",
1602
- * "campaign": "summer_sale"
1603
- * }
1604
- * });
1605
- *
1606
- * if (error) {
1607
- * console.error("Failed to create cart:", error.message);
1608
- * } else {
1609
- * console.log("Cart created:", data.cart.id);
1610
- * }
1611
- * ```
1612
- */
1613
- async createCart(payload) {
1614
- return this.executeRequest(
1615
- () => this.client.POST("/carts", {
1616
- body: payload
1617
- })
1618
- );
1619
- }
1620
- /**
1621
- * Get cart details - either by ID or using the stored cart ID
1622
- *
1623
- * @param cartId - The ID of the cart
1624
- * @returns Promise with cart details
1625
- * @example
1626
- * ```typescript
1627
- * const { data, error } = await sdk.cart.getCart({
1628
- * id: "01H9CART12345ABCDE"
1629
- * });
1630
- *
1631
- * if (error) {
1632
- * console.error("Failed to get cart:", error.message);
1633
- * } else {
1634
- * const cart = data.cart;
1635
- * console.log("Cart total:", cart.total_amount);
1636
- * console.log("Items count:", cart.items.length);
1637
- * }
1638
- * ```
1639
- */
1640
- async getCart(cartId) {
1641
- return this.executeRequest(
1642
- () => this.client.GET("/carts/{id}", {
1643
- params: {
1644
- path: cartId
1645
- }
1646
- })
1647
- );
1648
- }
1649
- /**
1650
- * Delete a cart - either by ID or using the stored cart ID
1651
- *
1652
- * @param cartId - The ID of the cart
1653
- * @returns Promise that resolves when the cart is deleted
1654
- * @example
1655
- * ```typescript
1656
- * const { data, error } = await sdk.cart.deleteCart({
1657
- * id: "01H9CART12345ABCDE"
1658
- * });
1659
- *
1660
- * if (error) {
1661
- * console.error("Failed to delete cart:", error.message);
1662
- * } else {
1663
- * console.log("Cart deleted:", data.message);
1664
- * }
1665
- * ```
1666
- */
1667
- async deleteCart(cartId) {
1668
- return this.executeRequest(
1669
- () => this.client.DELETE("/carts/{id}", {
1670
- params: {
1671
- path: cartId
1672
- }
1673
- })
1674
- );
1675
- }
1676
- /**
1677
- * Update cart items (add, update quantity, remove)
1678
- *
1679
- * @param cartId - The cart id
1680
- * @param body - The body of the request
1681
- * @returns Promise with updated cart
1682
- * @example
1683
- * ```typescript
1684
- * // Add item to cart
1685
- * const { data, error } = await sdk.cart.addDeleteCartItem(
1686
- * { id: "01H9CART12345ABCDE" },
1687
- * {
1688
- * product_id: "01H9XYZ12345ABCDE",
1689
- * variant_id: null,
1690
- * quantity: 3
1691
- * }
1692
- * );
1693
- *
1694
- * if (error) {
1695
- * console.error("Failed to update cart:", error.message);
1696
- * } else {
1697
- * console.log("Cart updated:", data.cart.items.length);
1698
- * }
1699
- *
1700
- * // Remove item from cart (set quantity to 0)
1701
- * const { data: removeData, error: removeError } = await sdk.cart.addDeleteCartItem(
1702
- * { id: "01H9CART12345ABCDE" },
1703
- * {
1704
- * product_id: "01H9XYZ12345ABCDE",
1705
- * variant_id: null,
1706
- * quantity: 0
1707
- * }
1708
- * );
1709
- * ```
1710
- */
1711
- async addDeleteCartItem(cartId, body) {
1712
- return this.executeRequest(
1713
- () => this.client.POST("/carts/{id}/items", {
1714
- params: {
1715
- path: cartId
1716
- },
1717
- body
1718
- })
1719
- );
1720
- }
1721
- /**
1722
- * Get cart details by user ID
1723
- *
1724
- * @param userId - The ID of the user
1725
- * @returns Promise with cart details
1726
- * @example
1727
- * ```typescript
1728
- * const { data, error } = await sdk.cart.getUserCart({
1729
- * user_id: "01H9USER12345ABCDE"
1730
- * });
1731
- *
1732
- * if (error) {
1733
- * console.error("Failed to get user cart:", error.message);
1734
- * } else {
1735
- * console.log("User cart ID:", data.cart.id);
1736
- * console.log("Cart value:", data.cart.subtotal_amount);
1737
- * }
1738
- * ```
1739
- */
1740
- async getUserCart(userId) {
1741
- return this.executeRequest(
1742
- () => this.client.GET("/carts/users/{user_id}", {
1743
- params: {
1744
- path: userId
1745
- }
1746
- })
1747
- );
1748
- }
1749
- /**
1750
- * Delete a cart by user ID
1751
- *
1752
- * @param userId - The ID of the user
1753
- * @returns Promise that resolves when the cart is deleted
1754
- * @example
1755
- * ```typescript
1756
- * const { data, error } = await sdk.cart.deleteUserCart({
1757
- * user_id: "01H9USER12345ABCDE"
1758
- * });
1759
- *
1760
- * if (error) {
1761
- * console.error("Failed to delete user cart:", error.message);
1762
- * } else {
1763
- * console.log("User cart cleared:", data.message);
1764
- * }
1765
- * ```
1766
- */
1767
- async deleteUserCart(userId) {
1768
- return this.executeRequest(
1769
- () => this.client.DELETE("/carts/users/{user_id}", {
1770
- params: {
1771
- path: userId
1772
- },
1773
- body: void 0
1774
- })
1775
- );
1776
- }
1777
- /**
1778
- * Update cart addresses
1779
- *
1780
- * @param cartId - The ID of the cart
1781
- * @param addressData - The address data
1782
- * @returns Promise with updated cart
1783
- * @example
1784
- * ```typescript
1785
- * // For registered users with saved addresses
1786
- * const { data, error } = await sdk.cart.updateCartAddress(
1787
- * { id: "01H9CART12345ABCDE" },
1788
- * {
1789
- * billing_address_id: "01H9ADDR12345BILL",
1790
- * shipping_address_id: "01H9ADDR12345SHIP"
1791
- * }
1792
- * );
1793
- *
1794
- * if (error) {
1795
- * console.error("Failed to update cart address:", error.message);
1796
- * } else {
1797
- * console.log("Addresses updated:", data.message);
1798
- * }
1799
- *
1800
- * // For guest checkout with new addresses
1801
- * const { data: guestData, error: guestError } = await sdk.cart.updateCartAddress(
1802
- * { id: "01H9CART12345ABCDE" },
1803
- * {
1804
- * billing_address: {
1805
- * first_name: "John",
1806
- * last_name: "Doe",
1807
- * email: "john@example.com",
1808
- * phone: "9876543210",
1809
- * country_code: "+91",
1810
- * address_line1: "123 Main Street",
1811
- * address_line2: "Apt 4B",
1812
- * city: "Mumbai",
1813
- * state: "Maharashtra",
1814
- * pincode: "400001",
1815
- * country: "India",
1816
- * landmark: "Near Station",
1817
- * tax_identification_number: null,
1818
- * business_name: null
1819
- * },
1820
- * shipping_address: {
1821
- * first_name: "John",
1822
- * last_name: "Doe",
1823
- * email: "john@example.com",
1824
- * phone: "9876543210",
1825
- * country_code: "+91",
1826
- * address_line1: "456 Oak Avenue",
1827
- * address_line2: null,
1828
- * city: "Pune",
1829
- * state: "Maharashtra",
1830
- * pincode: "411001",
1831
- * country: "India",
1832
- * landmark: "Near Mall",
1833
- * tax_identification_number: null,
1834
- * business_name: null
1835
- * }
1836
- * }
1837
- * );
1838
- * ```
1839
- */
1840
- async updateCartAddress(cartId, addressData) {
1841
- return this.executeRequest(
1842
- () => this.client.POST("/carts/{id}/address", {
1843
- params: {
1844
- path: cartId
1845
- },
1846
- body: addressData
1847
- })
1848
- );
1849
- }
1850
- /**
1851
- * Apply a coupon to the cart
1852
- *
1853
- * @param cartId - The ID of the cart
1854
- * @param couponCode - The coupon code
1855
- * @returns Promise with updated cart
1856
- * @example
1857
- * ```typescript
1858
- * const { data, error } = await sdk.cart.applyCoupon(
1859
- * { id: "01H9CART12345ABCDE" },
1860
- * { coupon_code: "FLAT100OFF" }
1861
- * );
1862
- *
1863
- * if (error) {
1864
- * console.error("Failed to apply coupon:", error.message);
1865
- * } else {
1866
- * console.log("Coupon applied, new total:", data.cart.total_amount);
1867
- * console.log("Discount amount:", data.cart.coupon_discount_amount);
1868
- * }
1869
- * ```
1870
- */
1871
- async applyCoupon(cartId, couponCode) {
1872
- return this.executeRequest(
1873
- () => this.client.POST("/carts/{id}/coupon", {
1874
- params: {
1875
- path: cartId
1876
- },
1877
- body: couponCode
1878
- })
1879
- );
1880
- }
1881
- /**
1882
- * Remove a coupon from the cart
1883
- *
1884
- * @param cartId - The ID of the cart
1885
- * @returns Promise with updated cart
1886
- * @example
1887
- * ```typescript
1888
- * const { data, error } = await sdk.cart.removeCoupon({
1889
- * id: "01H9CART12345ABCDE"
1890
- * });
1891
- *
1892
- * if (error) {
1893
- * console.error("Failed to remove coupon:", error.message);
1894
- * } else {
1895
- * console.log("Coupon removed, new total:", data.cart.total_amount);
1896
- * }
1897
- * ```
1898
- */
1899
- async removeCoupon(cartId) {
1900
- return this.executeRequest(
1901
- () => this.client.DELETE("/carts/{id}/coupon", {
1902
- params: {
1903
- path: cartId
1904
- },
1905
- body: void 0
1906
- })
1907
- );
1908
- }
1909
- /**
1910
- * Redeem loyalty points
1911
- *
1912
- * @param cartId - The ID of the cart
1913
- * @param points - The number of points to redeem
1914
- * @returns Promise with updated cart
1915
- * @example
1916
- * ```typescript
1917
- * const { data, error } = await sdk.cart.redeemLoyaltyPoints(
1918
- * { id: "01H9CART12345ABCDE" },
1919
- * { points: 500 }
1920
- * );
1921
- *
1922
- * if (error) {
1923
- * console.error("Failed to redeem loyalty points:", error.message);
1924
- * } else {
1925
- * console.log("Points redeemed, new total:", data.cart.total_amount);
1926
- * console.log("Points discount:", data.cart.loyalty_points_discount_amount);
1927
- * }
1928
- * ```
1929
- */
1930
- async redeemLoyaltyPoints(cartId, points) {
1931
- return this.executeRequest(
1932
- () => this.client.POST("/carts/{id}/loyalty-points", {
1933
- params: {
1934
- path: cartId
1935
- },
1936
- body: points
1937
- })
1938
- );
1939
- }
1940
- /**
1941
- * Remove loyalty points
1942
- *
1943
- * @param cartId - The ID of the cart
1944
- * @returns Promise with updated cart
1945
- * @example
1946
- * ```typescript
1947
- * const { data, error } = await sdk.cart.removeLoyaltyPoints({
1948
- * id: "01H9CART12345ABCDE"
1949
- * });
1950
- *
1951
- * if (error) {
1952
- * console.error("Failed to remove loyalty points:", error.message);
1953
- * } else {
1954
- * console.log("Loyalty points removed, new total:", data.cart.total_amount);
1955
- * }
1956
- * ```
1957
- */
1958
- async removeLoyaltyPoints(cartId) {
1959
- return this.executeRequest(
1960
- () => this.client.DELETE("/carts/{id}/loyalty-points", {
1961
- params: {
1962
- path: cartId
1963
- },
1964
- body: void 0
1965
- })
1966
- );
1967
- }
1968
- /**
1969
- * Update shipping method
1970
- *
1971
- * @param cartId - The ID of the cart
1972
- * @param body - The body of the request
1973
- * @returns Promise with updated cart
1974
- * @example
1975
- * ```typescript
1976
- * const { data, error } = await sdk.cart.updateShippingMethod(
1977
- * { id: "01H9CART12345ABCDE" },
1978
- * {
1979
- * shipping_method_id: "01H9SHIP12345FAST",
1980
- * estimated_delivery_date: "2024-01-15"
1981
- * }
1982
- * );
1983
- *
1984
- * if (error) {
1985
- * console.error("Failed to update shipping method:", error.message);
1986
- * } else {
1987
- * console.log("Shipping method updated:", data.cart.shipping_method?.name);
1988
- * console.log("Shipping cost:", data.cart.shipping_cost);
1989
- * }
1990
- * ```
1991
- */
1992
- async updateShippingMethod(cartId, body) {
1993
- return this.executeRequest(
1994
- () => this.client.POST("/carts/{id}/shipping-method", {
1995
- params: {
1996
- path: cartId
1997
- },
1998
- body
1999
- })
2000
- );
2001
- }
2002
- /**
2003
- * Use credit balance
2004
- *
2005
- * @param cartId - The ID of the cart
2006
- * @param body - The body of the request
2007
- * @returns Promise with updated cart
2008
- * @example
2009
- * ```typescript
2010
- * const { data, error } = await sdk.cart.redeemCreditBalance(
2011
- * { id: "01H9CART12345ABCDE" },
2012
- * { amount: 250.00 }
2013
- * );
2014
- *
2015
- * if (error) {
2016
- * console.error("Failed to redeem credit balance:", error.message);
2017
- * } else {
2018
- * console.log("Credit applied, new total:", data.cart.total_amount);
2019
- * console.log("Credit discount:", data.cart.credit_balance_discount_amount);
2020
- * }
2021
- * ```
2022
- */
2023
- async redeemCreditBalance(cartId, body) {
2024
- return this.executeRequest(
2025
- () => this.client.POST("/carts/{id}/credit-balance", {
2026
- params: {
2027
- path: cartId
2028
- },
2029
- body
2030
- })
2031
- );
2032
- }
2033
- /**
2034
- * Remove credit balance
2035
- *
2036
- * @param cartId - The ID of the cart
2037
- * @returns Promise with updated cart
2038
- * @example
2039
- * ```typescript
2040
- * const { data, error } = await sdk.cart.removeCreditBalance({
2041
- * id: "01H9CART12345ABCDE"
2042
- * });
2043
- *
2044
- * if (error) {
2045
- * console.error("Failed to remove credit balance:", error.message);
2046
- * } else {
2047
- * console.log("Credit balance removed, new total:", data.cart.total_amount);
2048
- * }
2049
- * ```
2050
- */
2051
- async removeCreditBalance(cartId) {
2052
- return this.executeRequest(
2053
- () => this.client.DELETE("/carts/{id}/credit-balance", {
2054
- params: {
2055
- path: cartId
2056
- },
2057
- body: void 0
2058
- })
2059
- );
2060
- }
2061
- /**
2062
- * Redeem gift card
2063
- *
2064
- * @param cartId - The ID of the cart
2065
- * @param body - The body of the request
2066
- * @returns Promise with updated cart
2067
- * @example
2068
- * ```typescript
2069
- * const { data, error } = await sdk.cart.redeemGiftCard(
2070
- * { id: "01H9CART12345ABCDE" },
2071
- * {
2072
- * gift_card_code: "GIFT2024-ABCD-1234",
2073
- * amount: 100.00
2074
- * }
2075
- * );
2076
- *
2077
- * if (error) {
2078
- * console.error("Failed to redeem gift card:", error.message);
2079
- * } else {
2080
- * console.log("Gift card applied, new total:", data.cart.total_amount);
2081
- * console.log("Gift card discount:", data.cart.gift_card_discount_amount);
2082
- * }
2083
- * ```
2084
- */
2085
- async redeemGiftCard(cartId, body) {
2086
- return this.executeRequest(
2087
- () => this.client.POST("/carts/{id}/gift-card", {
2088
- params: {
2089
- path: cartId
2090
- },
2091
- body
2092
- })
2093
- );
2094
- }
2095
- /**
2096
- * Remove gift card
2097
- *
2098
- * @param cartId - The ID of the cart
2099
- * @returns Promise with updated cart
2100
- * @example
2101
- * ```typescript
2102
- * const { data, error } = await sdk.cart.removeGiftCard({
2103
- * id: "01H9CART12345ABCDE"
2104
- * });
2105
- *
2106
- * if (error) {
2107
- * console.error("Failed to remove gift card:", error.message);
2108
- * } else {
2109
- * console.log("Gift card removed, new total:", data.cart.total_amount);
2110
- * }
2111
- * ```
2112
- */
2113
- async removeGiftCard(cartId) {
2114
- return this.executeRequest(
2115
- () => this.client.DELETE("/carts/{id}/gift-card", {
2116
- params: {
2117
- path: cartId
2118
- },
2119
- body: void 0
2120
- })
2121
- );
2122
- }
2123
- /**
2124
- * Get wishlist items
2125
- *
2126
- * @param userId - The ID of the user
2127
- * @returns Promise with wishlist items
2128
- * @example
2129
- * ```typescript
2130
- * const { data, error } = await sdk.cart.getWishlist({
2131
- * user_id: "01H9USER12345ABCDE"
2132
- * });
2133
- *
2134
- * if (error) {
2135
- * console.error("Failed to get wishlist:", error.message);
2136
- * } else {
2137
- * const products = data.products;
2138
- * console.log("Wishlist items:", products.length);
2139
- * products.forEach(product => {
2140
- * console.log("Product:", product.name, "Price:", product.price);
2141
- * });
2142
- * }
2143
- * ```
2144
- */
2145
- async getWishlist(userId) {
2146
- return this.executeRequest(
2147
- () => this.client.GET("/wishlist/{user_id}", {
2148
- params: {
2149
- path: userId
2150
- }
2151
- })
2152
- );
2153
- }
2154
- /**
2155
- * Add item to wishlist
2156
- *
2157
- * @param userId - The ID of the user
2158
- * @param itemId - The ID of the item
2159
- * @returns Promise with updated wishlist
2160
- * @example
2161
- * ```typescript
2162
- * const { data, error } = await sdk.cart.addToWishlist(
2163
- * { user_id: "01H9USER12345ABCDE" },
2164
- * {
2165
- * product_id: "01F3Z7KG06J4ACWH1C4926KJEC",
2166
- * variant_id: null
2167
- * }
2168
- * );
2169
- *
2170
- * if (error) {
2171
- * console.error("Failed to add to wishlist:", error.message);
2172
- * } else {
2173
- * const products = data.products;
2174
- * console.log("Item added to wishlist, total items:", products.length);
2175
- * }
2176
- * ```
2177
- */
2178
- async addToWishlist(userId, itemId) {
2179
- return this.executeRequest(
2180
- () => this.client.POST("/wishlist/{user_id}", {
2181
- params: {
2182
- path: userId
2183
- },
2184
- body: itemId
2185
- })
2186
- );
2187
- }
2188
- /**
2189
- * Remove item from wishlist
2190
- *
2191
- * @param userId - The ID of the user
2192
- * @param body - The body containing product details to remove
2193
- * @returns Promise with updated wishlist
2194
- * @example
2195
- * ```typescript
2196
- * const { data, error } = await sdk.cart.removeFromWishlist(
2197
- * { user_id: "01H9USER12345ABCDE" },
2198
- * {
2199
- * product_id: "01F3Z7KG06J4ACWH1C4926KJEC",
2200
- * variant_id: null
2201
- * }
2202
- * );
2203
- *
2204
- * if (error) {
2205
- * console.error("Failed to remove from wishlist:", error.message);
2206
- * } else {
2207
- * const products = data.products;
2208
- * console.log("Item removed from wishlist, remaining items:", products.length);
2209
- * }
2210
- * ```
2211
- */
2212
- async removeFromWishlist(userId, body) {
2213
- return this.executeRequest(
2214
- () => this.client.DELETE("/wishlist/{user_id}", {
2215
- params: {
2216
- path: userId
2217
- },
2218
- body
2219
- })
2220
- );
2221
- }
2222
- /**
2223
- * Get all available coupons
2224
- *
2225
- * @param headers - Optional header parameters (customer_group_id, etc.)
2226
- * @returns Promise with all available coupons
2227
- * @example
2228
- * ```typescript
2229
- * // Get all available coupons
2230
- * const { data, error } = await sdk.cart.getAvailableCoupons();
2231
- *
2232
- * if (error) {
2233
- * console.error("Failed to get available coupons:", error.message);
2234
- * } else {
2235
- * const coupons = data.coupons || [];
2236
- * console.log("Available coupons:", coupons.length);
2237
- * coupons.forEach(coupon => {
2238
- * console.log("Coupon:", coupon.code, "Discount:", coupon.discount_amount);
2239
- * });
2240
- * }
2241
- *
2242
- * // Override customer group ID for this specific request
2243
- * const { data: overrideData, error: overrideError } = await sdk.cart.getAvailableCoupons({
2244
- * "x-customer-group-id": "01H9GROUP12345ABC" // Override default SDK config
2245
- * });
2246
- * ```
2247
- */
2248
- async getAvailableCoupons(headers) {
2249
- const mergedHeaders = this.mergeHeaders(headers);
2250
- return this.executeRequest(
2251
- () => this.client.GET("/carts/available-coupons", {
2252
- params: {
2253
- header: mergedHeaders
2254
- }
2255
- })
2256
- );
2257
- }
2258
- /**
2259
- * Get all available promotions
2260
- *
2261
- * @param headers - Optional header parameters (customer_group_id, etc.)
2262
- * @returns Promise with all available promotions
2263
- * @example
2264
- * ```typescript
2265
- * // Get all available promotions
2266
- * const { data, error } = await sdk.cart.getAvailablePromotions();
2267
- *
2268
- * if (error) {
2269
- * console.error("Failed to get available promotions:", error.message);
2270
- * } else {
2271
- * const promotions = data.promotions || [];
2272
- * console.log("Available promotions:", promotions.length);
2273
- * promotions.forEach(promotion => {
2274
- * console.log("Promotion:", promotion.name, "Type:", promotion.promotion_type);
2275
- * });
2276
- * }
2277
- *
2278
- * // Override customer group ID for this specific request
2279
- * const { data: overrideData, error: overrideError } = await sdk.cart.getAvailablePromotions({
2280
- * "x-customer-group-id": "01H9GROUP12345ABC" // Override default SDK config
2281
- * });
2282
- * ```
2283
- */
2284
- async getAvailablePromotions(headers) {
2285
- const mergedHeaders = this.mergeHeaders(headers);
2286
- return this.executeRequest(
2287
- () => this.client.GET("/carts/available-promotions", {
2288
- params: {
2289
- header: mergedHeaders
2290
- }
2291
- })
2292
- );
2293
- }
2294
- /**
2295
- * Evaluate promotions
2296
- *
2297
- * @param cartId - The ID of the cart
2298
- * @returns Promise with evaluated promotions
2299
- * @example
2300
- * ```typescript
2301
- * const { data, error } = await sdk.cart.evaluatePromotions({
2302
- * id: "01H9CART12345ABCDE"
2303
- * });
2304
- *
2305
- * if (error) {
2306
- * console.error("Failed to evaluate promotions:", error.message);
2307
- * } else {
2308
- * const applicable = data.applicable_promotions || [];
2309
- * const inapplicable = data.inapplicable_promotions || [];
2310
- *
2311
- * console.log("Applicable promotions:", applicable.length);
2312
- * applicable.forEach(promo => {
2313
- * console.log(`- ${promo.name}: ${promo.savings_message}`);
2314
- * });
2315
- *
2316
- * console.log("Inapplicable promotions:", inapplicable.length);
2317
- * inapplicable.forEach(promo => {
2318
- * console.log(`- ${promo.name}: ${promo.reason}`);
2319
- * });
2320
- * }
2321
- * ```
2322
- */
2323
- async evaluatePromotions(cartId) {
2324
- return this.executeRequest(
2325
- () => this.client.GET("/carts/{id}/evaluate-promotions", {
2326
- params: {
2327
- path: cartId
2328
- }
2329
- })
2330
- );
2331
- }
2332
- /**
2333
- * Evaluate coupons
2334
- *
2335
- * @param cartId - The ID of the cart
2336
- * @returns Promise with evaluated coupons
2337
- * @example
2338
- * ```typescript
2339
- * const { data, error } = await sdk.cart.evaluateCoupons({
2340
- * id: "01H9CART12345ABCDE"
2341
- * });
2342
- *
2343
- * if (error) {
2344
- * console.error("Failed to evaluate coupons:", error.message);
2345
- * } else {
2346
- * const applicable = data.applicable_coupons || [];
2347
- * const inapplicable = data.inapplicable_coupons || [];
2348
- *
2349
- * console.log("Applicable coupons:", applicable.length);
2350
- * applicable.forEach(coupon => {
2351
- * console.log(`- ${coupon.code}: Save $${coupon.estimated_discount}`);
2352
- * });
2353
- *
2354
- * console.log("Inapplicable coupons:", inapplicable.length);
2355
- * inapplicable.forEach(coupon => {
2356
- * console.log(`- ${coupon.code}: ${coupon.reason}`);
2357
- * });
2358
- * }
2359
- * ```
2360
- */
2361
- async evaluateCoupons(cartId) {
2362
- return this.executeRequest(
2363
- () => this.client.GET("/carts/{id}/evaluate-coupons", {
2364
- params: {
2365
- path: cartId
2366
- }
2367
- })
2368
- );
2369
- }
2370
- };
2371
-
2372
- // src/lib/auth.ts
2373
- var AuthClient = class extends StorefrontAPIClient {
2374
- /**
2375
- * Get anonymous token for guest users
2376
- *
2377
- * @example
2378
- * ```typescript
2379
- * // Get token for guest browsing
2380
- * const { data, error } = await sdk.auth.getAnonymousToken();
2381
- *
2382
- * if (error) {
2383
- * console.error("Failed to get anonymous token:", error.message);
2384
- * } else {
2385
- * console.log("Anonymous token:", data.access_token);
2386
- * // Store token or proceed with guest operations
2387
- * }
2388
- * ```
2389
- */
2390
- async getAnonymousToken() {
2391
- return this.executeRequest(() => this.client.POST("/auth/anonymous"));
2392
- }
2393
- /**
2394
- * Login with phone number
2395
- *
2396
- * @param body - Login request body containing phone number and options
2397
- * @returns Promise with OTP token and action
2398
- * @example
2399
- * ```typescript
2400
- * // Login with phone number
2401
- * const { data, error } = await sdk.auth.loginWithPhone({
2402
- * phoneNumber: "9876543210",
2403
- * countryCode: "+91",
2404
- * registerIfNotExists: true
2405
- * });
2406
- *
2407
- * if (error) {
2408
- * console.error("Login failed:", error.message);
2409
- * } else {
2410
- * console.log("OTP sent. Token:", data.otpToken);
2411
- * console.log("Action:", data.action); // "login" or "register"
2412
- * // Redirect user to OTP verification screen
2413
- * }
2414
- * ```
2415
- */
2416
- async loginWithPhone(body) {
2417
- return this.executeRequest(
2418
- () => this.client.POST("/auth/login/phone", {
2419
- body
2420
- })
2421
- );
2422
- }
2423
- /**
2424
- * Login with WhatsApp
2425
- *
2426
- * @param body - Login request body containing phone number and options
2427
- * @returns Promise with OTP token and action
2428
- * @example
2429
- * ```typescript
2430
- * // Login with WhatsApp number
2431
- * const { data, error } = await sdk.auth.loginWithWhatsApp({
2432
- * phone: "9876543210",
2433
- * country_code: "+91",
2434
- * register_if_not_exists: true
2435
- * });
2436
- *
2437
- * if (error) {
2438
- * console.error("WhatsApp login failed:", error.message);
2439
- * } else {
2440
- * console.log("OTP sent to WhatsApp. Token:", data.otp_token);
2441
- * console.log("Action:", data.otp_action); // "login" or "register"
2442
- * }
2443
- * ```
2444
- */
2445
- async loginWithWhatsApp(body) {
2446
- return this.executeRequest(
2447
- () => this.client.POST("/auth/login/whatsapp", {
2448
- body
2449
- })
2450
- );
2451
- }
2452
- /**
2453
- * Login with email
2454
- *
2455
- * @param body - Login request body containing email and options
2456
- * @returns Promise with OTP token and action
2457
- * @example
2458
- * ```typescript
2459
- * // Login with email address
2460
- * const { data, error } = await sdk.auth.loginWithEmail({
2461
- * email: "customer@example.com",
2462
- * registerIfNotExists: true
2463
- * });
2464
- *
2465
- * if (error) {
2466
- * console.error("Email login failed:", error.message);
2467
- * } else {
2468
- * console.log("OTP sent to email. Token:", data.otpToken);
2469
- * console.log("Action:", data.action); // "login" or "register"
2470
- * // Show OTP input form
2471
- * }
2472
- * ```
2473
- */
2474
- async loginWithEmail(body) {
2475
- return this.executeRequest(
2476
- () => this.client.POST("/auth/login/email", {
2477
- body
2478
- })
2479
- );
2480
- }
2481
- /**
2482
- * Login with password
2483
- *
2484
- * @param body - Login credentials containing email/phone and password
2485
- * @returns Promise with user info and tokens
2486
- * @example
2487
- * ```typescript
2488
- * // Login with email and password
2489
- * const { data, error } = await sdk.auth.loginWithPassword({
2490
- * email: "customer@example.com",
2491
- * password: "securePassword123"
2492
- * });
2493
- *
2494
- * if (error) {
2495
- * console.error("Password login failed:", error.message);
2496
- * } else {
2497
- * console.log("Login successful:", data.user.email);
2498
- * console.log("Access token:", data.access_token);
2499
- * }
2500
- * ```
2501
- */
2502
- async loginWithPassword(body) {
2503
- return this.executeRequest(
2504
- () => this.client.POST("/auth/login/password", {
2505
- body
2506
- })
2507
- );
2508
- }
2509
- /**
2510
- * Forgot password
2511
- *
2512
- * @param body - Request body containing email address
2513
- * @returns Promise with password reset information
2514
- * @example
2515
- * ```typescript
2516
- * // Send password reset email
2517
- * const { data, error } = await sdk.auth.forgotPassword({
2518
- * email: "customer@example.com"
2519
- * });
2520
- *
2521
- * if (error) {
2522
- * console.error("Password reset failed:", error.message);
2523
- * } else {
2524
- * console.log("Reset email sent successfully");
2525
- * // Show confirmation message to user
2526
- * }
2527
- * ```
2528
- */
2529
- async forgotPassword(body) {
2530
- return this.executeRequest(
2531
- () => this.client.POST("/auth/forgot-password", {
2532
- body
2533
- })
2534
- );
2535
- }
2536
- /**
2537
- * Reset password
2538
- *
2539
- * @param body - Reset password request body containing new password and OTP token
2540
- * @returns Promise with new access and refresh tokens
2541
- * @example
2542
- * ```typescript
2543
- * // Reset password with OTP token from forgot password flow
2544
- * const { data, error } = await sdk.auth.resetPassword({
2545
- * new_password: "newSecurePassword123",
2546
- * confirm_password: "newSecurePassword123",
2547
- * otp_token: "abc123otptoken"
2548
- * });
2549
- *
2550
- * if (error) {
2551
- * console.error("Password reset failed:", error.message);
2552
- * } else {
2553
- * console.log("Password reset successful");
2554
- * console.log("New access token:", data.access_token);
2555
- * }
2556
- * ```
2557
- */
2558
- async resetPassword(body) {
2559
- return this.executeRequest(
2560
- () => this.client.POST("/auth/reset-password", {
2561
- body
2562
- })
2563
- );
2564
- }
2565
- /**
2566
- * Change password
2567
- *
2568
- * @param body - Change password request body containing old and new passwords
2569
- * @returns Promise with new access and refresh tokens
2570
- * @example
2571
- * ```typescript
2572
- * // Change user's password
2573
- * const { data, error } = await sdk.auth.changePassword({
2574
- * old_password: "currentPassword123",
2575
- * new_password: "newSecurePassword456",
2576
- * confirm_password: "newSecurePassword456"
2577
- * });
2578
- *
2579
- * if (error) {
2580
- * console.error("Password change failed:", error.message);
2581
- * } else {
2582
- * console.log("Password changed successfully");
2583
- * console.log("New access token:", data.access_token);
2584
- * }
2585
- * ```
2586
- */
2587
- async changePassword(body) {
2588
- return this.executeRequest(
2589
- () => this.client.POST("/auth/change-password", {
2590
- body
2591
- })
2592
- );
2593
- }
2594
- /**
2595
- * Verify OTP
2596
- *
2597
- * @param body - OTP verification data including code and tokens
2598
- * @returns Promise with user info and tokens
2599
- * @example
2600
- * ```typescript
2601
- * // Verify OTP after login attempt
2602
- * const { data, error } = await sdk.auth.verifyOtp({
2603
- * otp: "1234",
2604
- * otpToken: "56895455",
2605
- * otpAction: "login" // or "register"
2606
- * });
2607
- *
2608
- * if (error) {
2609
- * console.error("OTP verification failed:", error.message);
2610
- * // Show error message, allow retry
2611
- * } else {
2612
- * console.log("Login successful:", data.user.email);
2613
- * console.log("User ID:", data.user.id);
2614
- * }
2615
- * ```
2616
- */
2617
- async verifyOtp(body) {
2618
- return this.executeRequest(
2619
- () => this.client.POST("/auth/verify-otp", {
2620
- body
2621
- })
2622
- );
2623
- }
2624
- /**
2625
- * Register with phone
2626
- *
2627
- * @param body - Registration details including phone number and user information
2628
- * @returns Promise with user info and tokens
2629
- * @example
2630
- * ```typescript
2631
- * // Register a new user with phone number
2632
- * const { data, error } = await sdk.auth.registerWithPhone({
2633
- * phone: "9876543210",
2634
- * country_code: "+91",
2635
- * first_name: "John",
2636
- * last_name: "Doe",
2637
- * email: "john.doe@example.com"
2638
- * });
2639
- *
2640
- * if (error) {
2641
- * console.error("Phone registration failed:", error.message);
2642
- * } else {
2643
- * console.log("Registration successful:", data.user.first_name);
2644
- * console.log("User ID:", data.user.id);
2645
- * console.log("Access token:", data.access_token);
2646
- * }
2647
- * ```
2648
- */
2649
- async registerWithPhone(body) {
2650
- return this.executeRequest(
2651
- () => this.client.POST("/auth/register/phone", {
2652
- body
2653
- })
2654
- );
2655
- }
2656
- /**
2657
- * Register with email
2658
- *
2659
- * @param body - Registration details including email and user information
2660
- * @returns Promise with user info and tokens
2661
- * @example
2662
- * ```typescript
2663
- * // Register a new user with email address
2664
- * const { data, error } = await sdk.auth.registerWithEmail({
2665
- * email: "jane.smith@example.com",
2666
- * first_name: "Jane",
2667
- * last_name: "Smith",
2668
- * phone: "9876543210"
2669
- * });
2670
- *
2671
- * if (error) {
2672
- * console.error("Email registration failed:", error.message);
2673
- * } else {
2674
- * console.log("Registration successful:", data.user.email);
2675
- * console.log("User ID:", data.user.id);
2676
- * console.log("Access token:", data.access_token);
2677
- * }
2678
- * ```
2679
- */
2680
- async registerWithEmail(body) {
2681
- return this.executeRequest(
2682
- () => this.client.POST("/auth/register/email", {
2683
- body
2684
- })
2685
- );
2686
- }
2687
- /**
2688
- * Refresh the access token using a refresh token
2689
- * @param body - Request body containing the refresh token
2690
- * @returns Promise with the new access token and refresh token
2691
- * @example
2692
- * ```typescript
2693
- * // Refresh access token when it expires
2694
- * const { data, error } = await sdk.auth.refreshToken({
2695
- * refresh_token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
2696
- * });
2697
- *
2698
- * if (error) {
2699
- * console.error("Token refresh failed:", error.message);
2700
- * // Redirect to login
2701
- * } else {
2702
- * console.log("Token refreshed successfully");
2703
- * console.log("New access token:", data.access_token);
2704
- * console.log("New refresh token:", data.refresh_token);
2705
- * }
2706
- * ```
2707
- */
2708
- async refreshToken(body) {
2709
- return this.executeRequest(
2710
- () => this.client.POST("/auth/refresh-token", {
2711
- body
2712
- })
2713
- );
2714
- }
2715
- /**
2716
- * Logout
2717
- *
2718
- * @returns Promise that resolves when logout is complete
2719
- * @example
2720
- * ```typescript
2721
- * // Logout current user
2722
- * const { data, error } = await sdk.auth.logout();
2723
- *
2724
- * if (error) {
2725
- * console.error("Logout failed:", error.message);
2726
- * } else {
2727
- * console.log("Logout successful");
2728
- * console.log("Session ended for user:", data.user.email);
2729
- * }
2730
- * ```
2731
- */
2732
- async logout() {
2733
- return this.executeRequest(() => this.client.POST("/auth/logout"));
2734
- }
2735
- /**
2736
- * Get user details
2737
- *
2738
- * @param pathParams - Path parameters containing user ID
2739
- * @returns Promise with user details
2740
- * @example
2741
- * ```typescript
2742
- * // Get details for a specific user
2743
- * const { data, error } = await sdk.auth.getUserDetails({
2744
- * id: "01H9XYZ12345USERID"
2745
- * });
2746
- *
2747
- * if (error) {
2748
- * console.error("Failed to get user details:", error.message);
2749
- * } else {
2750
- * console.log("User details:", data.user);
2751
- * console.log("Email:", data.user.email);
2752
- * console.log("Phone:", data.user.phoneNumber);
2753
- * console.log("Created:", data.user.createdAt);
2754
- * }
2755
- * ```
2756
- */
2757
- async getUserDetails(pathParams) {
2758
- return this.executeRequest(
2759
- () => this.client.GET("/auth/user/{id}", {
2760
- params: {
2761
- path: pathParams
2762
- }
2763
- })
2764
- );
2765
- }
2766
- /**
2767
- * Update user details
2768
- *
2769
- * @param pathParams - Path parameters containing user ID
2770
- * @param body - Updated user information
2771
- * @returns Promise with updated user details
2772
- * @example
2773
- * ```typescript
2774
- * // Update user profile information
2775
- * const { data, error } = await sdk.auth.updateUserDetails(
2776
- * { id: "01H9XYZ12345USERID" },
2777
- * {
2778
- * first_name: "John",
2779
- * last_name: "Doe",
2780
- * email: "john.doe@example.com",
2781
- * phone: "9876543210",
2782
- * country_code: "+91"
2783
- * }
2784
- * );
2785
- *
2786
- * if (error) {
2787
- * console.error("Failed to update user:", error.message);
2788
- * } else {
2789
- * console.log("User updated successfully:", data.user.first_name);
2790
- * }
2791
- * ```
2792
- */
2793
- async updateUserDetails(pathParams, body) {
2794
- return this.executeRequest(
2795
- () => this.client.PUT("/auth/user/{id}", {
2796
- params: {
2797
- path: pathParams
2798
- },
2799
- body
2800
- })
2801
- );
2802
- }
2803
- /**
2804
- * Add profile image
2805
- *
2806
- * @param pathParams - Path parameters containing user ID
2807
- * @param formData - Form data containing the image file
2808
- * @returns Promise with profile image URL
2809
- * @example
2810
- * ```typescript
2811
- * // Add profile image for a user
2812
- * const imageFile = document.getElementById('file-input').files[0];
2813
- * const { data, error } = await sdk.auth.addProfileImage(
2814
- * { id: "01H9XYZ12345USERID" },
2815
- * { image: imageFile }
2816
- * );
2817
- *
2818
- * if (error) {
2819
- * console.error("Failed to add profile image:", error.message);
2820
- * } else {
2821
- * console.log("Profile image added successfully");
2822
- * console.log("Image URL:", data.profile_image_url);
2823
- * }
2824
- * ```
2825
- */
2826
- async addProfileImage(pathParams, formData) {
2827
- return this.executeRequest(
2828
- () => this.client.POST("/auth/user/{id}/profile-image", {
2829
- params: {
2830
- path: pathParams
2831
- },
2832
- body: formData,
2833
- bodySerializer: (body) => {
2834
- const fd = new FormData();
2835
- for (const [key, value] of Object.entries(body)) {
2836
- if (value !== void 0 && value !== null) {
2837
- fd.append(key, value);
2838
- }
2839
- }
2840
- return fd;
2841
- }
2842
- })
2843
- );
2844
- }
2845
- /**
2846
- * Update profile image
2847
- *
2848
- * @param pathParams - Path parameters containing user ID
2849
- * @param formData - Form data containing the new image file
2850
- * @returns Promise with updated profile image URL
2851
- * @example
2852
- * ```typescript
2853
- * // Update existing profile image
2854
- * const newImageFile = document.getElementById('file-input').files[0];
2855
- * const { data, error } = await sdk.auth.updateProfileImage(
2856
- * { id: "01H9XYZ12345USERID" },
2857
- * { image: newImageFile }
2858
- * );
2859
- *
2860
- * if (error) {
2861
- * console.error("Failed to update profile image:", error.message);
2862
- * } else {
2863
- * console.log("Profile image updated successfully");
2864
- * console.log("New image URL:", data.profile_image_url);
2865
- * }
2866
- * ```
2867
- */
2868
- async updateProfileImage(pathParams, formData) {
2869
- return this.executeRequest(
2870
- () => this.client.PUT("/auth/user/{id}/profile-image", {
2871
- params: {
2872
- path: pathParams
2873
- },
2874
- body: formData,
2875
- bodySerializer: (body) => {
2876
- const fd = new FormData();
2877
- for (const [key, value] of Object.entries(body)) {
2878
- if (value !== void 0 && value !== null) {
2879
- fd.append(key, value);
2880
- }
2881
- }
2882
- return fd;
2883
- }
2884
- })
2885
- );
2886
- }
2887
- /**
2888
- * Delete profile image
2889
- *
2890
- * @param pathParams - Path parameters containing user ID
2891
- * @returns Promise with deletion confirmation
2892
- * @example
2893
- * ```typescript
2894
- * // Delete user's profile image
2895
- * const { data, error } = await sdk.auth.deleteProfileImage({
2896
- * id: "01H9XYZ12345USERID"
2897
- * });
2898
- *
2899
- * if (error) {
2900
- * console.error("Failed to delete profile image:", error.message);
2901
- * } else {
2902
- * console.log("Profile image deleted successfully");
2903
- * console.log("Success:", data.success);
2904
- * }
2905
- * ```
2906
- */
2907
- async deleteProfileImage(pathParams) {
2908
- return this.executeRequest(
2909
- () => this.client.DELETE("/auth/user/{id}/profile-image", {
2910
- params: {
2911
- path: pathParams
2912
- }
2913
- })
2914
- );
2915
- }
2916
- /**
2917
- * Get profile image
2918
- *
2919
- * @param pathParams - Path parameters containing user ID
2920
- * @returns Promise with profile image URL
2921
- * @example
2922
- * ```typescript
2923
- * // Get user's profile image URL
2924
- * const { data, error } = await sdk.auth.getProfileImage({
2925
- * id: "01H9XYZ12345USERID"
2926
- * });
2927
- *
2928
- * if (error) {
2929
- * console.error("Failed to get profile image:", error.message);
2930
- * } else {
2931
- * console.log("Profile image URL:", data.profile_image_url);
2932
- * }
2933
- * ```
2934
- */
2935
- async getProfileImage(pathParams) {
2936
- return this.executeRequest(
2937
- () => this.client.GET("/auth/user/{id}/profile-image", {
2938
- params: {
2939
- path: pathParams
2940
- }
2941
- })
2942
- );
2943
- }
2944
- /**
2945
- * Deactivate user account
2946
- *
2947
- * @param pathParams - Path parameters containing user ID
2948
- * @returns Promise with deactivation confirmation
2949
- * @example
2950
- * ```typescript
2951
- * // Deactivate a user account
2952
- * const { data, error } = await sdk.auth.deactivateUserAccount({
2953
- * id: "01H9XYZ12345USERID"
2954
- * });
2955
- *
2956
- * if (error) {
2957
- * console.error("Failed to deactivate account:", error.message);
2958
- * } else {
2959
- * console.log("Account deactivated successfully");
2960
- * console.log("Success:", data.success);
2961
- * }
2962
- * ```
2963
- */
2964
- async deactivateUserAccount(pathParams) {
2965
- return this.executeRequest(
2966
- () => this.client.PUT("/auth/user/{id}/deactivate", {
2967
- params: {
2968
- path: pathParams
2969
- }
2970
- })
2971
- );
2972
- }
2973
- /**
2974
- * Get user notification preferences
2975
- *
2976
- * @param pathParams - Path parameters containing user ID
2977
- * @returns Promise with user's notification preferences
2978
- * @example
2979
- * ```typescript
2980
- * // Get user's notification preferences
2981
- * const { data, error } = await sdk.auth.getUserNotificationPreferences({
2982
- * id: "01H9XYZ12345USERID"
2983
- * });
2984
- *
2985
- * if (error) {
2986
- * console.error("Failed to get preferences:", error.message);
2987
- * } else {
2988
- * console.log("Notification preferences:", data.notification_preferences);
2989
- * }
2990
- * ```
2991
- */
2992
- async getUserNotificationPreferences(pathParams) {
2993
- return this.executeRequest(
2994
- () => this.client.GET("/auth/user/{id}/notification-preferences", {
2995
- params: {
2996
- path: pathParams
2997
- }
2998
- })
2999
- );
3000
- }
3001
- /**
3002
- * Update user notification preferences
3003
- *
3004
- * @param pathParams - Path parameters containing user ID
3005
- * @param body - Updated notification preferences
3006
- * @returns Promise with updated notification preferences
3007
- * @example
3008
- * ```typescript
3009
- * // Update user's notification preferences
3010
- * const { data, error } = await sdk.auth.updateUserNotificationPreferences(
3011
- * { id: "01H9XYZ12345USERID" },
3012
- * {
3013
- * email_notifications: true,
3014
- * sms_notifications: false,
3015
- * push_notifications: true
3016
- * }
3017
- * );
3018
- *
3019
- * if (error) {
3020
- * console.error("Failed to update preferences:", error.message);
3021
- * } else {
3022
- * console.log("Preferences updated successfully");
3023
- * }
3024
- * ```
3025
- */
3026
- async updateUserNotificationPreferences(pathParams, body) {
3027
- return this.executeRequest(
3028
- () => this.client.PUT("/auth/user/{id}/notification-preferences", {
3029
- params: {
3030
- path: pathParams
3031
- },
3032
- body
3033
- })
3034
- );
3035
- }
3036
- /**
3037
- * Create user notification preference
3038
- *
3039
- * @param pathParams - Path parameters containing user ID
3040
- * @param body - Notification preferences to create
3041
- * @returns Promise with created notification preferences
3042
- * @example
3043
- * ```typescript
3044
- * // Create notification preferences for a user
3045
- * const { data, error } = await sdk.auth.createUserNotificationPreference(
3046
- * { id: "01H9XYZ12345USERID" },
3047
- * {
3048
- * email_notifications: true,
3049
- * sms_notifications: true,
3050
- * push_notifications: false
3051
- * }
3052
- * );
3053
- *
3054
- * if (error) {
3055
- * console.error("Failed to create preferences:", error.message);
3056
- * } else {
3057
- * console.log("Preferences created successfully");
3058
- * }
3059
- * ```
3060
- */
3061
- async createUserNotificationPreference(pathParams, body) {
3062
- return this.executeRequest(
3063
- () => this.client.POST("/auth/user/{id}/notification-preferences", {
3064
- params: {
3065
- path: pathParams
3066
- },
3067
- body
3068
- })
3069
- );
3070
- }
3071
- /**
3072
- * Generate OTP
3073
- *
3074
- * @param body - OTP generation body (phone or email)
3075
- * @returns Promise with OTP token and action
3076
- * @example
3077
- * ```typescript
3078
- * // Generate OTP for phone number
3079
- * const { data, error } = await sdk.auth.generateOtp({
3080
- * phone: "9876543210",
3081
- * country_code: "+91"
3082
- * });
3083
- *
3084
- * if (error) {
3085
- * console.error("OTP generation failed:", error.message);
3086
- * } else {
3087
- * console.log("OTP sent successfully");
3088
- * console.log("OTP token:", data.otp_token);
3089
- * console.log("Action:", data.otp_action);
3090
- * }
3091
- * ```
3092
- */
3093
- async generateOtp(body) {
3094
- return this.executeRequest(
3095
- () => this.client.POST("/auth/generate-otp", {
3096
- body
3097
- })
3098
- );
3099
- }
3100
- /**
3101
- * Check whether email or phone is already verified
3102
- *
3103
- * @param body - Request body containing phone numbers or email addresses to verify
3104
- * @returns Promise with verification status for provided contacts
3105
- * @example
3106
- * ```typescript
3107
- * // Check verification status for multiple contacts
3108
- * const { data, error } = await sdk.auth.checkEmailOrPhoneIsVerified({
3109
- * phone: ["9876543210", "9123456789"],
3110
- * email: ["user1@example.com", "user2@example.com"]
3111
- * });
3112
- *
3113
- * if (error) {
3114
- * console.error("Verification check failed:", error.message);
3115
- * } else {
3116
- * console.log("Verified phones:", data.verified_phone);
3117
- * console.log("Verified emails:", data.verified_email);
3118
- * }
3119
- * ```
3120
- */
3121
- async checkEmailOrPhoneIsVerified(body) {
3122
- return this.executeRequest(
3123
- () => this.client.POST("/auth/verified-email-phone", {
3124
- body
3125
- })
3126
- );
3127
- }
3128
- };
3129
-
3130
- // src/lib/order.ts
3131
- var OrderClient = class extends StorefrontAPIClient {
3132
- /**
3133
- * Get order details
3134
- *
3135
- * @param orderNumber - Order number
3136
- * @returns Promise with order details
3137
- * @example
3138
- * ```typescript
3139
- * const { data, error } = await sdk.order.getOrderDetails({
3140
- * order_number: "ORD-2024-001"
3141
- * });
3142
- *
3143
- * if (error) {
3144
- * console.error("Failed to get order details:", error.message);
3145
- * } else {
3146
- * console.log("Order details:", data.content.order);
3147
- * console.log("Order status:", data.content.order.status);
3148
- * console.log("Total amount:", data.content.order.total_amount);
3149
- * }
3150
- * ```
3151
- */
3152
- async getOrderDetails(pathParams) {
3153
- return this.executeRequest(
3154
- () => this.client.GET("/orders/{order_number}", {
3155
- params: {
3156
- path: pathParams
3157
- }
3158
- })
3159
- );
3160
- }
3161
- /**
3162
- * Create order
3163
- *
3164
- * @param body - Order creation request body
3165
- * @returns Promise with order details
3166
- * @example
3167
- * ```typescript
3168
- * // Example with PayU payment gateway
3169
- * const { data, error } = await sdk.order.createOrder({
3170
- * cart_id: "cart_01H9XYZ12345ABCDE",
3171
- * payment_gateway: "PAYU",
3172
- * payment_gateway_params: {
3173
- * payment_gateway: "PAYU",
3174
- * furl: "https://yourapp.com/payment/failure",
3175
- * surl: "https://yourapp.com/payment/success"
3176
- * }
3177
- * });
3178
- *
3179
- * // Example with Juspay payment gateway
3180
- * const { data, error } = await sdk.order.createOrder({
3181
- * cart_id: "cart_01H9XYZ12345ABCDE",
3182
- * payment_gateway: "JUSPAY",
3183
- * payment_gateway_params: {
3184
- * payment_gateway: "JUSPAY",
3185
- * action: "paymentPage",
3186
- * integration_type: "hyper-checkout",
3187
- * return_url: "https://yourapp.com/payment/return",
3188
- * gateway_reference_id: "juspay_gateway_ref_123"
3189
- * }
3190
- * });
3191
- *
3192
- * if (error) {
3193
- * console.error("Failed to create order:", error.message);
3194
- * } else {
3195
- * console.log("Order created:", data.content.order.id);
3196
- * console.log("Payment required:", data.content.payment_required);
3197
- * console.log("Payment info:", data.content.payment_info);
3198
- * }
3199
- * ```
3200
- */
3201
- async createOrder(body) {
3202
- return this.executeRequest(
3203
- () => this.client.POST("/orders", {
3204
- body
3205
- })
3206
- );
3207
- }
3208
- /**
3209
- * List all orders
3210
- *
3211
- * @param queryParams - Query parameters for filtering and pagination
3212
- * @returns Promise with order list
3213
- * @example
3214
- * ```typescript
3215
- * // Basic usage - only required parameter
3216
- * const { data, error } = await sdk.order.listOrders({
3217
- * user_id: "user_01H9XYZ12345ABCDE"
3218
- * });
3219
- *
3220
- * // Advanced usage with optional parameters
3221
- * const { data, error } = await sdk.order.listOrders({
3222
- * user_id: "user_01H9XYZ12345ABCDE",
3223
- * page: 1,
3224
- * limit: 20,
3225
- * sort_by: '{"created_at":"desc"}',
3226
- * status: ["confirmed", "shipped", "delivered"]
3227
- * });
3228
- *
3229
- * if (error) {
3230
- * console.error("Failed to list orders:", error.message);
3231
- * } else {
3232
- * console.log("Orders found:", data.content.orders?.length || 0);
3233
- * console.log("Pagination:", data.content.pagination);
3234
- *
3235
- * data.content.orders?.forEach(order => {
3236
- * console.log(`Order ${order.order_number}: ${order.status}`);
3237
- * });
3238
- * }
3239
- * ```
3240
- */
3241
- async listOrders(queryParams) {
3242
- return this.executeRequest(
3243
- () => this.client.GET("/orders", {
3244
- params: {
3245
- query: queryParams
3246
- }
3247
- })
3248
- );
3249
- }
3250
- /**
3251
- * Get payment status for an order
3252
- *
3253
- * @param orderNumber - Order number
3254
- * @returns Promise with payment status
3255
- * @example
3256
- * ```typescript
3257
- * const { data, error } = await sdk.order.getPaymentStatus("ORD-2024-001");
3258
- *
3259
- * if (error) {
3260
- * console.error("Failed to get payment status:", error.message);
3261
- * } else {
3262
- * console.log("Payment status:", data.content.status);
3263
- * console.log("Amount paid:", data.content.amount_paid);
3264
- * console.log("Amount unpaid:", data.content.amount_unpaid);
3265
- * console.log("Retry available:", data.content.is_retry_available);
3266
- * }
3267
- * ```
3268
- */
3269
- async getPaymentStatus(orderNumber) {
3270
- return this.executeRequest(
3271
- () => this.client.GET("/orders/{order_number}/payment-status", {
3272
- params: {
3273
- path: { order_number: orderNumber }
3274
- }
3275
- })
3276
- );
3277
- }
3278
- /**
3279
- * Get all shipments for an order
3280
- *
3281
- * @param pathParams - Order number path parameters
3282
- * @returns Promise with shipments
3283
- * @example
3284
- * ```typescript
3285
- * const { data, error } = await sdk.order.listOrderShipments({
3286
- * order_number: "ORD-2024-001"
3287
- * });
3288
- *
3289
- * if (error) {
3290
- * console.error("Failed to get order shipments:", error.message);
3291
- * } else {
3292
- * console.log("Shipments found:", data.content.shipments?.length || 0);
3293
- *
3294
- * data.content.shipments?.forEach(shipment => {
3295
- * console.log(`Shipment ${shipment.id}: ${shipment.status}`);
3296
- * console.log("Tracking number:", shipment.tracking_number);
3297
- * console.log("Carrier:", shipment.carrier);
3298
- * });
3299
- * }
3300
- * ```
3301
- */
3302
- async listOrderShipments(pathParams) {
3303
- return this.executeRequest(
3304
- () => this.client.GET("/orders/{order_number}/shipments", {
3305
- params: {
3306
- path: pathParams
3307
- }
3308
- })
3309
- );
3310
- }
3311
- /**
3312
- * List order payments
3313
- *
3314
- * @param pathParams - Order number path parameters
3315
- * @returns Promise with payments
3316
- * @example
3317
- * ```typescript
3318
- * const { data, error } = await sdk.order.listOrderPayments({
3319
- * order_number: "ORD-2024-001"
3320
- * });
3321
- *
3322
- * if (error) {
3323
- * console.error("Failed to get order payments:", error.message);
3324
- * } else {
3325
- * console.log("Payments found:", data.content.payments?.length || 0);
3326
- *
3327
- * data.content.payments?.forEach(payment => {
3328
- * console.log(`Payment ${payment.id}: ${payment.status}`);
3329
- * console.log("Amount:", payment.amount);
3330
- * console.log("Gateway:", payment.payment_gateway);
3331
- * console.log("Transaction ID:", payment.transaction_id);
3332
- * });
3333
- * }
3334
- * ```
3335
- */
3336
- async listOrderPayments(pathParams) {
3337
- return this.executeRequest(
3338
- () => this.client.GET("/orders/{order_number}/payments", {
3339
- params: {
3340
- path: pathParams
3341
- }
3342
- })
3343
- );
3344
- }
3345
- /**
3346
- * List order refunds
3347
- *
3348
- * @param pathParams - Order number path parameters
3349
- * @returns Promise with refunds
3350
- * @example
3351
- * ```typescript
3352
- * const { data, error } = await sdk.order.listOrderRefunds({
3353
- * order_number: "ORD-2024-001"
3354
- * });
3355
- *
3356
- * if (error) {
3357
- * console.error("Failed to get order refunds:", error.message);
3358
- * } else {
3359
- * console.log("Refunds found:", data.content.refunds?.length || 0);
3360
- *
3361
- * data.content.refunds?.forEach(refund => {
3362
- * console.log(`Refund ${refund.id}: ${refund.status}`);
3363
- * console.log("Amount:", refund.amount);
3364
- * console.log("Reason:", refund.reason);
3365
- * console.log("Processed at:", refund.processed_at);
3366
- * });
3367
- * }
3368
- * ```
3369
- */
3370
- async listOrderRefunds(pathParams) {
3371
- return this.executeRequest(
3372
- () => this.client.GET("/orders/{order_number}/refunds", {
3373
- params: {
3374
- path: pathParams
3375
- }
3376
- })
3377
- );
3378
- }
3379
- /**
3380
- * Cancel an order
3381
- *
3382
- * @param pathParams - Order number path parameters
3383
- * @param body - Cancellation request body
3384
- * @returns Promise with order details
3385
- * @example
3386
- * ```typescript
3387
- * const { data, error } = await sdk.order.cancelOrder(
3388
- * { order_number: "ORD-2024-001" },
3389
- * {
3390
- * cancellation_reason: "Customer requested cancellation",
3391
- * refund_mode: "original_payment_mode",
3392
- * feedback: "Customer changed their mind about the purchase"
3393
- * }
3394
- * );
3395
- *
3396
- * if (error) {
3397
- * console.error("Failed to cancel order:", error.message);
3398
- * } else {
3399
- * console.log("Order cancelled successfully");
3400
- * console.log("Updated order status:", data.content.order?.status);
3401
- * console.log("Cancellation reason:", data.content.order?.cancellation_reason);
3402
- * }
3403
- * ```
3404
- */
3405
- async cancelOrder(pathParams, body) {
3406
- return this.executeRequest(
3407
- () => this.client.POST("/orders/{order_number}/cancel", {
3408
- params: {
3409
- path: pathParams
3410
- },
3411
- body
3412
- })
3413
- );
3414
- }
3415
- /**
3416
- * Retry payment for an order
3417
- *
3418
- * @param pathParams - Order number path parameters
3419
- * @param body - Payment retry request body
3420
- * @returns Promise with payment information
3421
- * @example
3422
- * ```typescript
3423
- * // Example with PayU payment gateway
3424
- * const { data, error } = await sdk.order.retryOrderPayment(
3425
- * { order_number: "ORD-2024-001" },
3426
- * {
3427
- * payment_gateway_params: {
3428
- * payment_gateway: "PAYU",
3429
- * furl: "https://yourapp.com/payment/failure",
3430
- * surl: "https://yourapp.com/payment/success"
3431
- * }
3432
- * }
3433
- * );
3434
- *
3435
- * // Example with Juspay payment gateway
3436
- * const { data, error } = await sdk.order.retryOrderPayment(
3437
- * { order_number: "ORD-2024-001" },
3438
- * {
3439
- * payment_gateway_params: {
3440
- * payment_gateway: "JUSPAY",
3441
- * action: "paymentPage",
3442
- * integration_type: "hyper-checkout",
3443
- * return_url: "https://yourapp.com/payment/return",
3444
- * gateway_reference_id: "juspay_gateway_ref_123"
3445
- * }
3446
- * }
3447
- * );
3448
- *
3449
- * if (error) {
3450
- * console.error("Failed to retry payment:", error.message);
3451
- * } else {
3452
- * console.log("Payment retry initiated");
3453
- * console.log("Payment info:", data.content.payment_info);
3454
- * console.log("Transaction ID:", data.content.payment_info.transaction_id);
3455
- * }
3456
- * ```
3457
- */
3458
- async retryOrderPayment(pathParams, body) {
3459
- return this.executeRequest(
3460
- () => this.client.POST("/orders/{order_number}/retry-payment", {
3461
- params: {
3462
- path: pathParams
3463
- },
3464
- body
3465
- })
3466
- );
3467
- }
3468
- };
3469
-
3470
- // src/lib/shipping.ts
3471
- var ShippingClient = class extends StorefrontAPIClient {
3472
- /**
3473
- * Get shipping options for an order
3474
- *
3475
- * @param body - Shipping methods body
3476
- * @returns Promise with shipping options
3477
- * @example
3478
- * ```typescript
3479
- * const { data, error } = await sdk.shipping.getShippingMethods({
3480
- * delivery_pincode: "400001",
3481
- * cart_id: "cart_01H9XYZ12345ABCDE"
3482
- * });
3483
- *
3484
- * if (error) {
3485
- * console.error("Failed to get shipping methods:", error.message);
3486
- * } else {
3487
- * console.log("Is serviceable:", data.content.is_serviceable);
3488
- * console.log("Available shipping methods:", data.content.shipping_methods?.length || 0);
3489
- *
3490
- * data.content.shipping_methods?.forEach(method => {
3491
- * console.log(`Method: ${method.name} (${method.shipping_type})`);
3492
- * console.log(`Shipping cost: ${method.shipping_amount}`);
3493
- * console.log(`Estimated delivery: ${method.estimated_delivery_days} days`);
3494
- *
3495
- * method.courier_companies?.forEach(courier => {
3496
- * console.log(` - ${courier.name}: ${courier.shipping_amount} (${courier.mode})`);
3497
- * console.log(` Rating: ${courier.rating}/5, Recommended: ${courier.is_recommended}`);
3498
- * });
3499
- * });
3500
- * }
3501
- * ```
3502
- */
3503
- async getShippingMethods(body) {
3504
- return this.executeRequest(
3505
- () => this.client.POST("/shipping/shipping-methods", {
3506
- body
3507
- })
3508
- );
3509
- }
3510
- /**
3511
- * Check pincode deliverability
3512
- *
3513
- * @param pathParams - Path parameters
3514
- * @returns Promise with pincode deliverability result
3515
- * @example
3516
- * ```typescript
3517
- * const { data, error } = await sdk.shipping.checkPincodeDeliverability({
3518
- * pincode: "400001"
3519
- * });
3520
- *
3521
- * if (error) {
3522
- * console.error("Failed to check pincode serviceability:", error.message);
3523
- * } else {
3524
- * console.log("Pincode serviceable:", data.content.is_serviceable);
3525
- *
3526
- * if (data.content.is_serviceable) {
3527
- * console.log("Delivery is available to this pincode");
3528
- * } else {
3529
- * console.log("Delivery is not available to this pincode");
3530
- * }
3531
- * }
3532
- * ```
3533
- */
3534
- async checkPincodeDeliverability(pathParams) {
3535
- return this.executeRequest(
3536
- () => this.client.GET("/shipping/serviceability/{pincode}", {
3537
- params: {
3538
- path: pathParams
3539
- }
3540
- })
3541
- );
3542
- }
3543
- };
3544
-
3545
- // src/lib/helper.ts
3546
- var HelpersClient = class extends StorefrontAPIClient {
3547
- /**
3548
- * Get a list of countries
3549
- *
3550
- * @returns Promise with countries
3551
- *
3552
- * @example
3553
- * ```typescript
3554
- * const { data, error } = await sdk.helpers.listCountries();
3555
- *
3556
- * if (error) {
3557
- * console.error("Failed to get countries:", error);
3558
- * return;
3559
- * }
3560
- *
3561
- * console.log("Countries found:", data.countries?.length || 0);
3562
- *
3563
- * data.countries?.forEach(country => {
3564
- * console.log(`Country: ${country.name} (${country.iso_code})`);
3565
- * console.log("Phone code:", country.phone_code);
3566
- * console.log("Currency:", country.currency?.code);
3567
- * });
3568
- * ```
3569
- */
3570
- async listCountries() {
3571
- return this.executeRequest(() => this.client.GET("/common/countries", {}));
3572
- }
3573
- /**
3574
- * Get a list of states for a country
3575
- *
3576
- * @param pathParams - Path parameters
3577
- * @returns Promise with states
3578
- *
3579
- * @example
3580
- * ```typescript
3581
- * const { data, error } = await sdk.helpers.listCountryStates({
3582
- * country_iso_code: "IN"
3583
- * });
3584
- *
3585
- * if (error) {
3586
- * console.error("Failed to get states:", error);
3587
- * return;
3588
- * }
3589
- *
3590
- * console.log("States found:", data.states?.length || 0);
3591
- *
3592
- * data.states?.forEach(state => {
3593
- * console.log(`State: ${state.name} (${state.iso_code})`);
3594
- * console.log("Type:", state.type);
3595
- * });
3596
- *
3597
- * // Get states for different country
3598
- * const { data: usStates, error: usError } = await sdk.helpers.listCountryStates({
3599
- * country_iso_code: "US"
3600
- * });
3601
- *
3602
- * if (usError) {
3603
- * console.error("Failed to get US states:", usError);
3604
- * return;
3605
- * }
3606
- *
3607
- * console.log("US States:", usStates.states?.map(s => s.name).join(", "));
3608
- * ```
3609
- */
3610
- async listCountryStates(pathParams) {
3611
- return this.executeRequest(
3612
- () => this.client.GET("/common/countries/{country_iso_code}/states", {
3613
- params: {
3614
- path: pathParams
3615
- }
3616
- })
3617
- );
3618
- }
3619
- /**
3620
- * Get pincodes for a country
3621
- *
3622
- * @param pathParams - Path parameters
3623
- * @returns Promise with pincodes
3624
- *
3625
- * @example
3626
- * ```typescript
3627
- * const { data, error } = await sdk.helpers.listCountryPincodes({
3628
- * country_iso_code: "IN"
3629
- * });
3630
- *
3631
- * if (error) {
3632
- * console.error("Failed to get pincodes:", error);
3633
- * return;
3634
- * }
3635
- *
3636
- * console.log("Pincodes found:", data.pincodes?.length || 0);
3637
- *
3638
- * data.pincodes?.forEach(pincode => {
3639
- * console.log(`Pincode: ${pincode.pincode} - ${pincode.city}, ${pincode.state}`);
3640
- * console.log("District:", pincode.district);
3641
- * console.log("Area:", pincode.area);
3642
- * });
3643
- *
3644
- * // Get pincodes for different country
3645
- * const { data: usPincodes, error: usError } = await sdk.helpers.listCountryPincodes({
3646
- * country_iso_code: "US"
3647
- * });
3648
- *
3649
- * if (usError) {
3650
- * console.error("Failed to get US pincodes:", usError);
3651
- * return;
3652
- * }
3653
- *
3654
- * console.log("US Pincodes:", usPincodes.pincodes?.map(p => p.pincode).join(", "));
3655
- * ```
3656
- */
3657
- async listCountryPincodes(pathParams) {
3658
- return this.executeRequest(
3659
- () => this.client.GET("/common/countries/{country_iso_code}/pincodes", {
3660
- params: {
3661
- path: pathParams
3662
- }
3663
- })
3664
- );
3665
- }
3666
- };
3667
-
3668
- // src/lib/customer.ts
3669
- var CustomerClient = class extends StorefrontAPIClient {
3670
- /**
3671
- * Create a customer
3672
- *
3673
- * @param body - Customer creation body
3674
- * @returns Promise with customer details
3675
- *
3676
- * @example
3677
- * ```typescript
3678
- * const { data, error } = await sdk.customer.createCustomer({
3679
- * first_name: "John",
3680
- * last_name: "Doe",
3681
- * email: "john.doe@example.com",
3682
- * phone: "+1234567890",
3683
- * password: "securePassword123"
3684
- * });
3685
- *
3686
- * if (error) {
3687
- * console.error("Failed to create customer:", error);
3688
- * return;
3689
- * }
3690
- *
3691
- * console.log("Customer created:", data.customer_detail);
3692
- * ```
3693
- */
3694
- async createCustomer(body) {
3695
- return this.executeRequest(
3696
- () => this.client.POST("/customers", {
3697
- body
3698
- })
3699
- );
3700
- }
3701
- /**
3702
- * Get customer details
3703
- *
3704
- * @param pathParams - Path parameters
3705
- * @returns Promise with customer details
3706
- *
3707
- * @example
3708
- * ```typescript
3709
- * const { data, error } = await sdk.customer.getCustomer({
3710
- * id: "customer_123"
3711
- * });
3712
- *
3713
- * if (error) {
3714
- * console.error("Failed to get customer:", error);
3715
- * return;
3716
- * }
3717
- *
3718
- * console.log("Customer details:", data.customer_detail);
3719
- * ```
3720
- */
3721
- async getCustomer(pathParams) {
3722
- return this.executeRequest(
3723
- () => this.client.GET("/customers/{id}", {
3724
- params: {
3725
- path: pathParams
3726
- }
3727
- })
3728
- );
3729
- }
3730
- /**
3731
- * Update a customer
3732
- *
3733
- * @param pathParams - Path parameters
3734
- * @param body - Customer update body
3735
- * @returns Promise with customer details
3736
- *
3737
- * @example
3738
- * ```typescript
3739
- * const { data, error } = await sdk.customer.updateCustomer(
3740
- * { id: "customer_123" },
3741
- * {
3742
- * first_name: "John",
3743
- * last_name: "Smith",
3744
- * email: "john.smith@example.com"
3745
- * }
3746
- * );
3747
- *
3748
- * if (error) {
3749
- * console.error("Failed to update customer:", error);
3750
- * return;
3751
- * }
3752
- *
3753
- * console.log("Customer updated:", data.customer_detail);
3754
- * ```
3755
- */
3756
- async updateCustomer(pathParams, body) {
3757
- return this.executeRequest(
3758
- () => this.client.PUT("/customers/{id}", {
3759
- params: {
3760
- path: pathParams
3761
- },
3762
- body
3763
- })
3764
- );
3765
- }
3766
- /**
3767
- * Get all saved addresses for a customer
3768
- *
3769
- * @param pathParams - Path parameters
3770
- * @returns Promise with addresses
3771
- *
3772
- * @example
3773
- * ```typescript
3774
- * const { data, error } = await sdk.customer.listAddresses({
3775
- * user_id: "user_456"
3776
- * });
3777
- *
3778
- * if (error) {
3779
- * console.error("Failed to list addresses:", error);
3780
- * return;
3781
- * }
3782
- *
3783
- * console.log("Addresses:", data.addresses);
3784
- * console.log("Pagination:", data.pagination);
3785
- *
3786
- * // With pagination
3787
- * const { data: page2, error: page2Error } = await sdk.customer.listAddresses({
3788
- * user_id: "user_456",
3789
- * page: 2,
3790
- * limit: 10
3791
- * });
3792
- * ```
3793
- */
3794
- async listAddresses(pathParams) {
3795
- return this.executeRequest(
3796
- () => this.client.GET("/customers/{user_id}/addresses", {
3797
- params: {
3798
- path: pathParams
3799
- }
3800
- })
3801
- );
3802
- }
3803
- /**
3804
- * Create a new address for a customer
3805
- *
3806
- * @param pathParams - Path parameters
3807
- * @param body - Address creation body
3808
- * @returns Promise with address details
3809
- *
3810
- * @example
3811
- * ```typescript
3812
- * const { data, error } = await sdk.customer.createAddress(
3813
- * { user_id: "user_456" },
3814
- * {
3815
- * address_line1: "123 Main Street",
3816
- * address_line2: "Apt 4B",
3817
- * city: "New York",
3818
- * state: "NY",
3819
- * country: "US",
3820
- * pincode: "10001",
3821
- * is_default_billing: true,
3822
- * is_default_shipping: false
3823
- * }
3824
- * );
3825
- *
3826
- * if (error) {
3827
- * console.error("Failed to create address:", error);
3828
- * return;
3829
- * }
3830
- *
3831
- * console.log("Address created:", data.address);
3832
- * ```
3833
- */
3834
- async createAddress(pathParams, body) {
3835
- return this.executeRequest(
3836
- () => this.client.POST("/customers/{user_id}/addresses", {
3837
- params: {
3838
- path: pathParams
3839
- },
3840
- body
3841
- })
3842
- );
3843
- }
3844
- /**
3845
- * Get an address for a customer
3846
- *
3847
- * @param pathParams - Path parameters
3848
- * @returns Promise with address details
3849
- *
3850
- * @example
3851
- * ```typescript
3852
- * const { data, error } = await sdk.customer.getAddress({
3853
- * user_id: "user_456",
3854
- * address_id: "addr_789"
3855
- * });
3856
- *
3857
- * if (error) {
3858
- * console.error("Failed to get address:", error);
3859
- * return;
3860
- * }
3861
- *
3862
- * console.log("Address details:", data.address);
3863
- * ```
3864
- */
3865
- async getAddress(pathParams) {
3866
- return this.executeRequest(
3867
- () => this.client.GET("/customers/{user_id}/addresses/{address_id}", {
3868
- params: {
3869
- path: pathParams
3870
- }
3871
- })
3872
- );
3873
- }
3874
- /**
3875
- * Update an address for a customer
3876
- *
3877
- * @param pathParams - Path parameters
3878
- * @param body - Address update body
3879
- * @returns Promise with address details
3880
- *
3881
- * @example
3882
- * ```typescript
3883
- * const { data, error } = await sdk.customer.updateAddress(
3884
- * {
3885
- * user_id: "user_456",
3886
- * address_id: "addr_789"
3887
- * },
3888
- * {
3889
- * address_line1: "456 Oak Avenue",
3890
- * city: "Los Angeles",
3891
- * state: "CA",
3892
- * pincode: "90210"
3893
- * }
3894
- * );
3895
- *
3896
- * if (error) {
3897
- * console.error("Failed to update address:", error);
3898
- * return;
3899
- * }
3900
- *
3901
- * console.log("Address updated:", data.address);
3902
- * ```
3903
- */
3904
- async updateAddress(pathParams, body) {
3905
- return this.executeRequest(
3906
- () => this.client.PUT("/customers/{user_id}/addresses/{address_id}", {
3907
- params: {
3908
- path: pathParams
3909
- },
3910
- body
3911
- })
3912
- );
3913
- }
3914
- /**
3915
- * Delete an address for a customer
3916
- *
3917
- * @param pathParams - Path parameters
3918
- * @returns Promise with deletion response
3919
- *
3920
- * @example
3921
- * ```typescript
3922
- * const { data, error } = await sdk.customer.deleteAddress({
3923
- * user_id: "user_456",
3924
- * address_id: "addr_789"
3925
- * });
3926
- *
3927
- * if (error) {
3928
- * console.error("Failed to delete address:", error);
3929
- * return;
3930
- * }
3931
- *
3932
- * console.log("Address deleted:", data.message);
3933
- * ```
3934
- */
3935
- async deleteAddress(pathParams) {
3936
- return this.executeRequest(
3937
- () => this.client.DELETE("/customers/{user_id}/addresses/{address_id}", {
3938
- params: {
3939
- path: pathParams
3940
- }
3941
- })
3942
- );
3943
- }
3944
- /**
3945
- * Get customer loyalty details
3946
- *
3947
- * @param pathParams - Path parameters
3948
- * @returns Promise with loyalty details
3949
- *
3950
- * @example
3951
- * ```typescript
3952
- * const { data, error } = await sdk.customer.getLoyaltyDetails({
3953
- * user_id: "user_456"
3954
- * });
3955
- *
3956
- * if (error) {
3957
- * console.error("Failed to get loyalty details:", error);
3958
- * return;
3959
- * }
3960
- *
3961
- * console.log("Loyalty info:", data.loyalty);
3962
- * console.log("Points balance:", data.loyalty_point_balance);
3963
- * ```
3964
- */
3965
- async getLoyaltyDetails(pathParams) {
3966
- return this.executeRequest(
3967
- () => this.client.GET("/customers/{user_id}/loyalty", {
3968
- params: {
3969
- path: pathParams
3970
- }
3971
- })
3972
- );
3973
- }
3974
- /**
3975
- * List all loyalty points activity for a customer
3976
- *
3977
- * @param pathParams - Path parameters
3978
- * @returns Promise with loyalty points activity
3979
- *
3980
- * @example
3981
- * ```typescript
3982
- * const { data, error } = await sdk.customer.listLoyaltyPointsActivity({
3983
- * user_id: "user_456"
3984
- * });
3985
- *
3986
- * if (error) {
3987
- * console.error("Failed to get loyalty activity:", error);
3988
- * return;
3989
- * }
3990
- *
3991
- * console.log("Loyalty activity:", data.loyalty_points_activity);
3992
- *
3993
- * // With pagination and sorting
3994
- * const { data: sortedData, error: sortedError } = await sdk.customer.listLoyaltyPointsActivity({
3995
- * user_id: "user_456",
3996
- * page: 1,
3997
- * limit: 20,
3998
- * sort_by: JSON.stringify({ "created_at": "desc" })
3999
- * });
4000
- * ```
4001
- */
4002
- async listLoyaltyPointsActivity(pathParams) {
4003
- return this.executeRequest(
4004
- () => this.client.GET("/customers/{user_id}/loyalty-points-activity", {
4005
- params: {
4006
- path: pathParams
4007
- }
4008
- })
4009
- );
4010
- }
4011
- /**
4012
- * List all reviews left by a customer
4013
- *
4014
- * @param pathParams - Path parameters
4015
- * @returns Promise with reviews
4016
- *
4017
- * @example
4018
- * ```typescript
4019
- * const { data, error } = await sdk.customer.listCustomerReviews({
4020
- * user_id: "user_456"
4021
- * });
4022
- *
4023
- * if (error) {
4024
- * console.error("Failed to get customer reviews:", error);
4025
- * return;
4026
- * }
4027
- *
4028
- * console.log("Customer reviews:", data.reviews);
4029
- * console.log("Ready for review:", data.ready_for_review);
4030
- * ```
4031
- */
4032
- async listCustomerReviews(pathParams) {
4033
- return this.executeRequest(
4034
- () => this.client.GET("/customers/{user_id}/reviews", {
4035
- params: {
4036
- path: pathParams
4037
- }
4038
- })
4039
- );
4040
- }
4041
- };
4042
-
4043
- // src/lib/store-config.ts
4044
- var StoreConfigClient = class extends StorefrontAPIClient {
4045
- /**
4046
- * Get store config
4047
- *
4048
- * @returns Promise with store configuration data
4049
- *
4050
- * @example
4051
- * ```typescript
4052
- * const { data, error } = await sdk.storeConfig.getStoreConfig();
4053
- *
4054
- * if (error) {
4055
- * console.error('Failed to get store config:', error.message);
4056
- * return;
4057
- * }
4058
- *
4059
- * // Access store configuration data
4060
- * const storeConfig = data.store_config;
4061
- * console.log('Store brand:', storeConfig.brand.name);
4062
- * console.log('Currency:', storeConfig.currency.code);
4063
- * console.log('KYC enabled:', storeConfig.is_kyc_enabled);
4064
- * console.log('Customer groups enabled:', storeConfig.is_customer_group_enabled);
4065
- * ```
4066
- */
4067
- async getStoreConfig() {
4068
- return this.executeRequest(() => this.client.GET("/store/config"));
4069
- }
4070
- };
4071
-
4072
- // src/index.ts
4073
- var StorefrontSDK = class {
4074
- /**
4075
- * Client for catalog-related endpoints (products, categories, etc.)
4076
- */
4077
- catalog;
4078
- /**
4079
- * Client for cart-related endpoints
4080
- */
4081
- cart;
4082
- /**
4083
- * Client for authentication-related endpoints
4084
- */
4085
- auth;
4086
- /**
4087
- * Client for customer-related endpoints
4088
- */
4089
- customer;
4090
- /**
4091
- * Client for helper-related endpoints
4092
- */
4093
- helpers;
4094
- /**
4095
- * Client for shipping-related endpoints
4096
- */
4097
- shipping;
4098
- /**
4099
- * Client for order-related endpoints
4100
- */
4101
- order;
4102
- /**
4103
- * Client for store config-related endpoints
4104
- */
4105
- store;
4106
- /**
4107
- * Create a new StorefrontSDK instance
4108
- *
4109
- * @param options - Configuration options for the SDK
4110
- */
4111
- constructor(options) {
4112
- const config = {
4113
- storeId: options.storeId,
4114
- environment: options.environment,
4115
- baseUrl: options.baseUrl,
4116
- accessToken: options.accessToken,
4117
- refreshToken: options.refreshToken,
4118
- apiKey: options.apiKey,
4119
- timeout: options.timeout,
4120
- tokenStorage: options.tokenStorage,
4121
- onTokensUpdated: options.onTokensUpdated,
4122
- onTokensCleared: options.onTokensCleared,
4123
- defaultHeaders: options.defaultHeaders,
4124
- debug: options.debug,
4125
- logger: options.logger
4126
- };
4127
- this.catalog = new CatalogClient(config);
4128
- this.cart = new CartClient(config);
4129
- this.auth = new AuthClient(config);
4130
- this.customer = new CustomerClient(config);
4131
- this.helpers = new HelpersClient(config);
4132
- this.shipping = new ShippingClient(config);
4133
- this.order = new OrderClient(config);
4134
- this.store = new StoreConfigClient(config);
4135
- }
4136
- /**
4137
- * Set authentication tokens for all clients
4138
- *
4139
- * @param accessToken - The access token (required)
4140
- * @param refreshToken - The refresh token (optional)
4141
- *
4142
- * Behavior:
4143
- * - If tokenStorage is provided: Stores tokens for automatic management
4144
- * - If tokenStorage is not provided: Only stores access token for manual management
4145
- */
4146
- async setTokens(accessToken, refreshToken) {
4147
- await this.catalog.setTokens(accessToken, refreshToken);
4148
- await this.cart.setTokens(accessToken, refreshToken);
4149
- await this.auth.setTokens(accessToken, refreshToken);
4150
- await this.customer.setTokens(accessToken, refreshToken);
4151
- await this.helpers.setTokens(accessToken, refreshToken);
4152
- await this.shipping.setTokens(accessToken, refreshToken);
4153
- await this.order.setTokens(accessToken, refreshToken);
4154
- await this.store.setTokens(accessToken, refreshToken);
4155
- }
4156
- /**
4157
- * Clear all authentication tokens from all clients
4158
- *
4159
- * Behavior:
4160
- * - If tokenStorage is provided: Clears both access and refresh tokens from storage
4161
- * - If tokenStorage is not provided: Clears the manual access token
4162
- */
4163
- async clearTokens() {
4164
- await this.catalog.clearTokens();
4165
- await this.cart.clearTokens();
4166
- await this.auth.clearTokens();
4167
- await this.customer.clearTokens();
4168
- await this.helpers.clearTokens();
4169
- await this.shipping.clearTokens();
4170
- await this.order.clearTokens();
4171
- await this.store.clearTokens();
4172
- }
4173
- /**
4174
- * Set the API key for all clients
4175
- *
4176
- * @param apiKey - The API key to set
4177
- */
4178
- setApiKey(apiKey) {
4179
- this.catalog.setApiKey(apiKey);
4180
- this.cart.setApiKey(apiKey);
4181
- this.auth.setApiKey(apiKey);
4182
- this.customer.setApiKey(apiKey);
4183
- this.helpers.setApiKey(apiKey);
4184
- this.shipping.setApiKey(apiKey);
4185
- this.order.setApiKey(apiKey);
4186
- this.store.setApiKey(apiKey);
4187
- }
4188
- /**
4189
- * Clear the API key from all clients
4190
- */
4191
- clearApiKey() {
4192
- this.catalog.clearApiKey();
4193
- this.cart.clearApiKey();
4194
- this.auth.clearApiKey();
4195
- this.customer.clearApiKey();
4196
- this.helpers.clearApiKey();
4197
- this.shipping.clearApiKey();
4198
- this.order.clearApiKey();
4199
- this.store.clearApiKey();
4200
- }
4201
- /**
4202
- * Get the current access token if using token storage
4203
- */
4204
- async getAccessToken() {
4205
- return await this.auth.getAuthorizationHeader().then(
4206
- (header) => header.startsWith("Bearer ") ? header.substring(7) : null
4207
- );
4208
- }
4209
- /**
4210
- * Get user information from the current access token
4211
- *
4212
- * @returns User information extracted from JWT token, or null if no token or invalid token
4213
- */
4214
- async getUserInfo() {
4215
- const token = await this.getAccessToken();
4216
- if (!token) return null;
4217
- return extractUserInfoFromToken(token);
4218
- }
4219
- /**
4220
- * Get the current user ID from the access token
4221
- *
4222
- * @returns User ID (ulid) or null if no token or invalid token
4223
- */
4224
- async getUserId() {
4225
- const token = await this.getAccessToken();
4226
- if (!token) return null;
4227
- return getUserIdFromToken(token);
4228
- }
4229
- /**
4230
- * Check if the current user is logged in (not anonymous)
4231
- *
4232
- * @returns True if user is logged in, false if anonymous or no token
4233
- */
4234
- async isLoggedIn() {
4235
- const token = await this.getAccessToken();
4236
- if (!token) return false;
4237
- return isUserLoggedIn(token);
4238
- }
4239
- /**
4240
- * Check if the current user is anonymous
4241
- *
4242
- * @returns True if user is anonymous or no token, false if logged in
4243
- */
4244
- async isAnonymous() {
4245
- const token = await this.getAccessToken();
4246
- if (!token) return true;
4247
- return isUserAnonymous(token);
4248
- }
4249
- /**
4250
- * Get the customer ID from the current access token
4251
- *
4252
- * @returns Customer ID or null if no token, invalid token, or user has no customer ID
4253
- */
4254
- async getCustomerId() {
4255
- const userInfo = await this.getUserInfo();
4256
- return userInfo?.customerId || null;
4257
- }
4258
- /**
4259
- * Get the customer group ID from the current access token
4260
- *
4261
- * @returns Customer group ID or null if no token, invalid token, or user has no customer group
4262
- */
4263
- async getCustomerGroupId() {
4264
- const userInfo = await this.getUserInfo();
4265
- return userInfo?.customerGroupId || null;
4266
- }
4267
- /**
4268
- * Set default headers for all clients
4269
- *
4270
- * @param headers - Default headers to set (only supported headers allowed)
4271
- */
4272
- setDefaultHeaders(headers) {
4273
- const newConfig = { ...this.catalog["config"], defaultHeaders: headers };
4274
- this.catalog["config"] = newConfig;
4275
- this.cart["config"] = newConfig;
4276
- this.auth["config"] = newConfig;
4277
- this.customer["config"] = newConfig;
4278
- this.helpers["config"] = newConfig;
4279
- this.shipping["config"] = newConfig;
4280
- this.order["config"] = newConfig;
4281
- this.store["config"] = newConfig;
4282
- }
4283
- /**
4284
- * Get current default headers
4285
- *
4286
- * @returns Current default headers
4287
- */
4288
- getDefaultHeaders() {
4289
- return this.catalog["config"].defaultHeaders;
4290
- }
4291
- };
4292
- var index_default = StorefrontSDK;
4293
- // Annotate the CommonJS export names for ESM import in node:
4294
- 0 && (module.exports = {
4295
- AuthClient,
4296
- BrowserTokenStorage,
4297
- CartClient,
4298
- CatalogClient,
4299
- CookieTokenStorage,
4300
- CustomerClient,
4301
- Environment,
4302
- HelpersClient,
4303
- MemoryTokenStorage,
4304
- OrderClient,
4305
- ResponseUtils,
4306
- ShippingClient,
4307
- StoreConfigClient,
4308
- StorefrontAPIClient,
4309
- StorefrontSDK
4310
- });
4311
- //# sourceMappingURL=index.cjs.map