@commercengine/storefront-sdk 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,7 +1,13 @@
1
1
  import { StorefrontAPIClient, Environment } from "./lib/client";
2
2
  import { CatalogClient } from "./lib/catalog";
3
3
  import { CartClient } from "./lib/cart";
4
- import { AuthClient, TokenStorage } from "./lib/auth";
4
+ import { AuthClient } from "./lib/auth";
5
+ import { OrderClient } from "./lib/order";
6
+ import { ShippingClient } from "./lib/shipping";
7
+ import { HelpersClient } from "./lib/helper";
8
+ import { CustomerClient } from "./lib/customer";
9
+ import { TokenStorage, MemoryTokenStorage, BrowserTokenStorage, createDefaultAuthMiddleware, createAuthMiddleware, type AuthMiddlewareConfig } from "./lib/middleware";
10
+ import { type UserInfo } from "./lib/jwt-utils";
5
11
  /**
6
12
  * SDK initialization options
7
13
  */
@@ -19,7 +25,7 @@ export interface StorefrontSDKOptions {
19
25
  */
20
26
  baseUrl?: string;
21
27
  /**
22
- * Optional authentication token
28
+ * Optional authentication token (for manual token management)
23
29
  */
24
30
  token?: string;
25
31
  /**
@@ -32,10 +38,18 @@ export interface StorefrontSDKOptions {
32
38
  */
33
39
  timeout?: number;
34
40
  /**
35
- * Optional token storage strategy
36
- * Defaults to MemoryTokenStorage if not provided
41
+ * Optional token storage for automatic token management
42
+ * If provided, enables automatic token refresh and management
37
43
  */
38
44
  tokenStorage?: TokenStorage;
45
+ /**
46
+ * Callback when tokens are updated (login/refresh)
47
+ */
48
+ onTokensUpdated?: (accessToken: string, refreshToken: string) => void;
49
+ /**
50
+ * Callback when tokens are cleared (logout/error)
51
+ */
52
+ onTokensCleared?: () => void;
39
53
  }
40
54
  /**
41
55
  * Main SDK class for the Storefront API
@@ -54,13 +68,21 @@ export declare class StorefrontSDK {
54
68
  */
55
69
  readonly auth: AuthClient;
56
70
  /**
57
- * The client storage instance used by this SDK
71
+ * Client for customer-related endpoints
58
72
  */
59
- private readonly clientStorage;
73
+ readonly customer: CustomerClient;
60
74
  /**
61
- * Whether the SDK has been initialized
75
+ * Client for helper-related endpoints
62
76
  */
63
- private isInitialized;
77
+ readonly helpers: HelpersClient;
78
+ /**
79
+ * Client for shipping-related endpoints
80
+ */
81
+ readonly shipping: ShippingClient;
82
+ /**
83
+ * Client for order-related endpoints
84
+ */
85
+ readonly order: OrderClient;
64
86
  /**
65
87
  * Create a new StorefrontSDK instance
66
88
  *
@@ -68,58 +90,68 @@ export declare class StorefrontSDK {
68
90
  */
69
91
  constructor(options: StorefrontSDKOptions);
70
92
  /**
71
- * Set up storage with automatic fallback for non-browser environments
93
+ * Set the authentication token for all clients
72
94
  */
73
- private setupStorage;
95
+ setToken(token: string): Promise<void>;
74
96
  /**
75
- * Initialize the SDK
76
- * This method should be called before using any SDK features
77
- * It ensures tokens are available and valid
78
- * @returns Promise that resolves when initialization is complete
97
+ * Clear the authentication token from all clients
79
98
  */
80
- init(): Promise<void>;
99
+ clearToken(): Promise<void>;
81
100
  /**
82
- * Get the current user ID if available
101
+ * Set the API key for all clients
102
+ *
103
+ * @param apiKey - The API key to set
83
104
  */
84
- getUserId(): Promise<string | null>;
105
+ setApiKey(apiKey: string): void;
85
106
  /**
86
- * Get the current cart ID if one is stored
87
- *
88
- * @returns The current cart ID or null if none exists
107
+ * Clear the API key from all clients
89
108
  */
90
- getCartId(): Promise<string | null>;
109
+ clearApiKey(): void;
91
110
  /**
92
- * Set a specific cart ID to use
111
+ * Get the current access token if using token storage
112
+ */
113
+ getAccessToken(): Promise<string | null>;
114
+ /**
115
+ * Get user information from the current access token
93
116
  *
94
- * @param cartId - The cart ID to use
117
+ * @returns User information extracted from JWT token, or null if no token or invalid token
95
118
  */
96
- setCartId(cartId: string): Promise<void>;
119
+ getUserInfo(): Promise<UserInfo | null>;
97
120
  /**
98
- * Clear the current cart ID
121
+ * Get the current user ID from the access token
122
+ *
123
+ * @returns User ID (ulid) or null if no token or invalid token
99
124
  */
100
- clearCartId(): Promise<void>;
125
+ getUserId(): Promise<string | null>;
101
126
  /**
102
- * Set the authentication token for all clients
103
- * Also stores the token in the configured storage
127
+ * Check if the current user is logged in (not anonymous)
128
+ *
129
+ * @returns True if user is logged in, false if anonymous or no token
104
130
  */
105
- setToken(token: string): Promise<void>;
131
+ isLoggedIn(): Promise<boolean>;
106
132
  /**
107
- * Clear the authentication token from all clients and storage
133
+ * Check if the current user is anonymous
134
+ *
135
+ * @returns True if user is anonymous or no token, false if logged in
108
136
  */
109
- clearToken(): Promise<void>;
137
+ isAnonymous(): Promise<boolean>;
110
138
  /**
111
- * Set the API key for all clients
139
+ * Get the customer ID from the current access token
112
140
  *
113
- * @param apiKey - The API key to set
141
+ * @returns Customer ID or null if no token, invalid token, or user has no customer ID
114
142
  */
115
- setApiKey(apiKey: string): void;
143
+ getCustomerId(): Promise<string | null>;
116
144
  /**
117
- * Clear the API key from all clients
145
+ * Get the customer group ID from the current access token
146
+ *
147
+ * @returns Customer group ID or null if no token, invalid token, or user has no customer group
118
148
  */
119
- clearApiKey(): void;
149
+ getCustomerGroupId(): Promise<string | null>;
120
150
  }
121
151
  export default StorefrontSDK;
122
- export { StorefrontAPIClient, CatalogClient, CartClient, AuthClient };
152
+ export { StorefrontAPIClient, AuthClient, CartClient, CatalogClient, CustomerClient, HelpersClient, ShippingClient, OrderClient };
123
153
  export { Environment };
124
- export { TokenStorage, MemoryTokenStorage, BrowserTokenStorage, CookieTokenStorage, NextCookieTokenStorage, createTokenStorage, } from "./lib/auth";
154
+ export { TokenStorage, MemoryTokenStorage, BrowserTokenStorage, createDefaultAuthMiddleware, createAuthMiddleware, type AuthMiddlewareConfig };
155
+ export { extractUserInfoFromToken, getUserIdFromToken, isUserLoggedIn, isUserAnonymous, isTokenExpired, type UserInfo, type JwtPayload } from "./lib/jwt-utils";
125
156
  export type { components, operations, paths } from "./types/storefront";
157
+ export type * from "./types/storefront-api-types";
package/dist/index.js CHANGED
@@ -1,31 +1,51 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.createTokenStorage = exports.NextCookieTokenStorage = exports.CookieTokenStorage = exports.BrowserTokenStorage = exports.MemoryTokenStorage = exports.Environment = exports.AuthClient = exports.CartClient = exports.CatalogClient = exports.StorefrontAPIClient = exports.StorefrontSDK = void 0;
4
- const client_1 = require("./lib/client");
5
- Object.defineProperty(exports, "StorefrontAPIClient", { enumerable: true, get: function () { return client_1.StorefrontAPIClient; } });
6
- Object.defineProperty(exports, "Environment", { enumerable: true, get: function () { return client_1.Environment; } });
7
- const catalog_1 = require("./lib/catalog");
8
- Object.defineProperty(exports, "CatalogClient", { enumerable: true, get: function () { return catalog_1.CatalogClient; } });
9
- const cart_1 = require("./lib/cart");
10
- Object.defineProperty(exports, "CartClient", { enumerable: true, get: function () { return cart_1.CartClient; } });
11
- const auth_1 = require("./lib/auth");
12
- Object.defineProperty(exports, "AuthClient", { enumerable: true, get: function () { return auth_1.AuthClient; } });
1
+ import { StorefrontAPIClient, Environment, } from "./lib/client";
2
+ import { CatalogClient } from "./lib/catalog";
3
+ import { CartClient } from "./lib/cart";
4
+ import { AuthClient } from "./lib/auth";
5
+ import { OrderClient } from "./lib/order";
6
+ import { ShippingClient } from "./lib/shipping";
7
+ import { HelpersClient } from "./lib/helper";
8
+ import { CustomerClient } from "./lib/customer";
9
+ import { MemoryTokenStorage, BrowserTokenStorage, createDefaultAuthMiddleware, createAuthMiddleware } from "./lib/middleware";
10
+ import { extractUserInfoFromToken, getUserIdFromToken, isUserLoggedIn, isUserAnonymous } from "./lib/jwt-utils";
13
11
  /**
14
12
  * Main SDK class for the Storefront API
15
13
  */
16
- class StorefrontSDK {
14
+ export class StorefrontSDK {
15
+ /**
16
+ * Client for catalog-related endpoints (products, categories, etc.)
17
+ */
18
+ catalog;
19
+ /**
20
+ * Client for cart-related endpoints
21
+ */
22
+ cart;
23
+ /**
24
+ * Client for authentication-related endpoints
25
+ */
26
+ auth;
27
+ /**
28
+ * Client for customer-related endpoints
29
+ */
30
+ customer;
31
+ /**
32
+ * Client for helper-related endpoints
33
+ */
34
+ helpers;
35
+ /**
36
+ * Client for shipping-related endpoints
37
+ */
38
+ shipping;
39
+ /**
40
+ * Client for order-related endpoints
41
+ */
42
+ order;
17
43
  /**
18
44
  * Create a new StorefrontSDK instance
19
45
  *
20
46
  * @param options - Configuration options for the SDK
21
47
  */
22
48
  constructor(options) {
23
- /**
24
- * Whether the SDK has been initialized
25
- */
26
- this.isInitialized = false;
27
- // Set up client storage with fallback handling
28
- this.clientStorage = this.setupStorage(options.tokenStorage);
29
49
  // Convert options to internal config format
30
50
  const config = {
31
51
  storeId: options.storeId,
@@ -34,145 +54,144 @@ class StorefrontSDK {
34
54
  token: options.token,
35
55
  apiKey: options.apiKey,
36
56
  timeout: options.timeout,
57
+ tokenStorage: options.tokenStorage,
58
+ onTokensUpdated: options.onTokensUpdated,
59
+ onTokensCleared: options.onTokensCleared,
37
60
  };
38
- this.catalog = new catalog_1.CatalogClient(config);
39
- this.cart = new cart_1.CartClient(config);
40
- this.auth = new auth_1.AuthClient(config, this.clientStorage);
41
- // Set client storage for cart management
42
- this.cart.setClientStorage(this.clientStorage);
61
+ this.catalog = new CatalogClient(config);
62
+ this.cart = new CartClient(config);
63
+ this.auth = new AuthClient(config);
64
+ this.customer = new CustomerClient(config);
65
+ this.helpers = new HelpersClient(config);
66
+ this.shipping = new ShippingClient(config);
67
+ this.order = new OrderClient(config);
43
68
  }
44
69
  /**
45
- * Set up storage with automatic fallback for non-browser environments
46
- */
47
- setupStorage(requestedStorage) {
48
- if (!requestedStorage) {
49
- return new auth_1.MemoryTokenStorage();
50
- }
51
- try {
52
- // Test if the requested storage is available
53
- requestedStorage.getItem("test");
54
- // Check if it's a ClientStorage implementation
55
- if ("getCartId" in requestedStorage &&
56
- "setCartId" in requestedStorage &&
57
- "clearCartId" in requestedStorage) {
58
- return requestedStorage;
59
- }
60
- // If it's just a TokenStorage, wrap it in a MemoryTokenStorage for cart functionality
61
- console.warn("Provided storage does not implement ClientStorage interface, wrapping with MemoryTokenStorage for cart functionality");
62
- return new auth_1.MemoryTokenStorage();
63
- }
64
- catch (e) {
65
- // If storage access fails, fallback to memory storage
66
- console.warn("Requested storage is not available in this environment, falling back to memory storage");
67
- return new auth_1.MemoryTokenStorage();
68
- }
70
+ * Set the authentication token for all clients
71
+ */
72
+ async setToken(token) {
73
+ await this.catalog.setToken(token);
74
+ await this.cart.setToken(token);
75
+ await this.auth.setToken(token);
76
+ await this.customer.setToken(token);
77
+ await this.helpers.setToken(token);
78
+ await this.shipping.setToken(token);
79
+ await this.order.setToken(token);
69
80
  }
70
81
  /**
71
- * Initialize the SDK
72
- * This method should be called before using any SDK features
73
- * It ensures tokens are available and valid
74
- * @returns Promise that resolves when initialization is complete
75
- */
76
- async init() {
77
- if (this.isInitialized) {
78
- return;
79
- }
80
- try {
81
- // Try to get existing tokens from storage
82
- const accessToken = await this.clientStorage.getItem("access_token");
83
- const userData = await this.clientStorage.getItem("user_data");
84
- if (accessToken && userData) {
85
- // Set the token for all clients
86
- await this.setToken(accessToken);
87
- }
88
- else {
89
- // If no token exists or no user data, get a new anonymous token
90
- const authResponse = await this.auth.getAnonymousToken();
91
- await this.setToken(authResponse.access_token);
92
- // Store user data
93
- await this.clientStorage.setItem("user_data", JSON.stringify(authResponse.user));
94
- }
95
- this.isInitialized = true;
96
- }
97
- catch (error) {
98
- console.error("Failed to initialize SDK:", error);
99
- throw error;
100
- }
82
+ * Clear the authentication token from all clients
83
+ */
84
+ async clearToken() {
85
+ await this.catalog.clearToken();
86
+ await this.cart.clearToken();
87
+ await this.auth.clearToken();
88
+ await this.customer.clearToken();
89
+ await this.helpers.clearToken();
90
+ await this.shipping.clearToken();
91
+ await this.order.clearToken();
101
92
  }
102
93
  /**
103
- * Get the current user ID if available
94
+ * Set the API key for all clients
95
+ *
96
+ * @param apiKey - The API key to set
104
97
  */
105
- async getUserId() {
106
- return this.clientStorage.getItem("user_id");
98
+ setApiKey(apiKey) {
99
+ this.catalog.setApiKey(apiKey);
100
+ this.cart.setApiKey(apiKey);
101
+ this.auth.setApiKey(apiKey);
102
+ this.customer.setApiKey(apiKey);
103
+ this.helpers.setApiKey(apiKey);
104
+ this.shipping.setApiKey(apiKey);
105
+ this.order.setApiKey(apiKey);
107
106
  }
108
107
  /**
109
- * Get the current cart ID if one is stored
110
- *
111
- * @returns The current cart ID or null if none exists
108
+ * Clear the API key from all clients
109
+ */
110
+ clearApiKey() {
111
+ this.catalog.clearApiKey();
112
+ this.cart.clearApiKey();
113
+ this.auth.clearApiKey();
114
+ this.customer.clearApiKey();
115
+ this.helpers.clearApiKey();
116
+ this.shipping.clearApiKey();
117
+ this.order.clearApiKey();
118
+ }
119
+ /**
120
+ * Get the current access token if using token storage
112
121
  */
113
- async getCartId() {
114
- return this.clientStorage.getCartId();
122
+ async getAccessToken() {
123
+ return await this.auth.getAuthorizationHeader().then(header => header.startsWith('Bearer ') ? header.substring(7) : null);
115
124
  }
116
125
  /**
117
- * Set a specific cart ID to use
126
+ * Get user information from the current access token
118
127
  *
119
- * @param cartId - The cart ID to use
128
+ * @returns User information extracted from JWT token, or null if no token or invalid token
120
129
  */
121
- async setCartId(cartId) {
122
- await this.clientStorage.setCartId(cartId);
130
+ async getUserInfo() {
131
+ const token = await this.getAccessToken();
132
+ if (!token)
133
+ return null;
134
+ return extractUserInfoFromToken(token);
123
135
  }
124
136
  /**
125
- * Clear the current cart ID
137
+ * Get the current user ID from the access token
138
+ *
139
+ * @returns User ID (ulid) or null if no token or invalid token
126
140
  */
127
- async clearCartId() {
128
- await this.clientStorage.clearCartId();
141
+ async getUserId() {
142
+ const token = await this.getAccessToken();
143
+ if (!token)
144
+ return null;
145
+ return getUserIdFromToken(token);
129
146
  }
130
147
  /**
131
- * Set the authentication token for all clients
132
- * Also stores the token in the configured storage
148
+ * Check if the current user is logged in (not anonymous)
149
+ *
150
+ * @returns True if user is logged in, false if anonymous or no token
133
151
  */
134
- async setToken(token) {
135
- this.catalog.setToken(token);
136
- this.cart.setToken(token);
137
- this.auth.setToken(token);
138
- await this.clientStorage.setItem("access_token", token);
152
+ async isLoggedIn() {
153
+ const token = await this.getAccessToken();
154
+ if (!token)
155
+ return false;
156
+ return isUserLoggedIn(token);
139
157
  }
140
158
  /**
141
- * Clear the authentication token from all clients and storage
159
+ * Check if the current user is anonymous
160
+ *
161
+ * @returns True if user is anonymous or no token, false if logged in
142
162
  */
143
- async clearToken() {
144
- this.catalog.clearToken();
145
- this.cart.clearToken();
146
- this.auth.clearToken();
147
- await this.clientStorage.removeItem("access_token");
148
- await this.clientStorage.removeItem("refresh_token");
163
+ async isAnonymous() {
164
+ const token = await this.getAccessToken();
165
+ if (!token)
166
+ return true;
167
+ return isUserAnonymous(token);
149
168
  }
150
169
  /**
151
- * Set the API key for all clients
170
+ * Get the customer ID from the current access token
152
171
  *
153
- * @param apiKey - The API key to set
172
+ * @returns Customer ID or null if no token, invalid token, or user has no customer ID
154
173
  */
155
- setApiKey(apiKey) {
156
- this.catalog.setApiKey(apiKey);
157
- this.cart.setApiKey(apiKey);
158
- this.auth.setApiKey(apiKey);
174
+ async getCustomerId() {
175
+ const userInfo = await this.getUserInfo();
176
+ return userInfo?.customerId || null;
159
177
  }
160
178
  /**
161
- * Clear the API key from all clients
179
+ * Get the customer group ID from the current access token
180
+ *
181
+ * @returns Customer group ID or null if no token, invalid token, or user has no customer group
162
182
  */
163
- clearApiKey() {
164
- this.catalog.clearApiKey();
165
- this.cart.clearApiKey();
166
- this.auth.clearApiKey();
183
+ async getCustomerGroupId() {
184
+ const userInfo = await this.getUserInfo();
185
+ return userInfo?.customerGroupId || null;
167
186
  }
168
187
  }
169
- exports.StorefrontSDK = StorefrontSDK;
170
188
  // Export the main SDK class
171
- exports.default = StorefrontSDK;
172
- // Export token storage types
173
- var auth_2 = require("./lib/auth");
174
- Object.defineProperty(exports, "MemoryTokenStorage", { enumerable: true, get: function () { return auth_2.MemoryTokenStorage; } });
175
- Object.defineProperty(exports, "BrowserTokenStorage", { enumerable: true, get: function () { return auth_2.BrowserTokenStorage; } });
176
- Object.defineProperty(exports, "CookieTokenStorage", { enumerable: true, get: function () { return auth_2.CookieTokenStorage; } });
177
- Object.defineProperty(exports, "NextCookieTokenStorage", { enumerable: true, get: function () { return auth_2.NextCookieTokenStorage; } });
178
- Object.defineProperty(exports, "createTokenStorage", { enumerable: true, get: function () { return auth_2.createTokenStorage; } });
189
+ export default StorefrontSDK;
190
+ // Export individual clients for advanced usage
191
+ export { StorefrontAPIClient, AuthClient, CartClient, CatalogClient, CustomerClient, HelpersClient, ShippingClient, OrderClient };
192
+ // Export environment enum
193
+ export { Environment };
194
+ // Export token storage types and middleware
195
+ export { MemoryTokenStorage, BrowserTokenStorage, createDefaultAuthMiddleware, createAuthMiddleware };
196
+ // Export JWT utilities
197
+ export { extractUserInfoFromToken, getUserIdFromToken, isUserLoggedIn, isUserAnonymous, isTokenExpired } from "./lib/jwt-utils";