@commercengine/storefront-sdk 0.8.1 → 0.9.0

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