@commercengine/storefront-sdk 0.3.12 → 0.4.1

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