@commercengine/storefront-sdk 0.3.11 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,113 +0,0 @@
1
- import createClient from "openapi-fetch";
2
- import type { paths } from "../types/storefront";
3
- import { ApiErrorResponse, ApiResult } from "../types/storefront-api-types";
4
- import type { StorefrontSDKOptions } from "../index";
5
- /**
6
- * Available API environments
7
- */
8
- export declare enum Environment {
9
- /**
10
- * Staging environment
11
- */
12
- Staging = "staging",
13
- /**
14
- * Production environment
15
- */
16
- Production = "production"
17
- }
18
- /**
19
- * Base API client for Storefront API
20
- */
21
- export declare class StorefrontAPIClient {
22
- protected client: ReturnType<typeof createClient<paths>>;
23
- protected config: StorefrontSDKOptions;
24
- private readonly baseUrl;
25
- private initializationPromise;
26
- /**
27
- * Create a new StorefrontAPIClient
28
- *
29
- * @param config - Configuration for the API client
30
- */
31
- constructor(config: StorefrontSDKOptions);
32
- /**
33
- * Set up timeout middleware
34
- */
35
- private setupTimeoutMiddleware;
36
- /**
37
- * Constructs the base URL from the configuration
38
- *
39
- * @param config - The client configuration
40
- * @returns The constructed base URL
41
- */
42
- private getBaseUrlFromConfig;
43
- /**
44
- * Get the base URL of the API
45
- *
46
- * @returns The base URL of the API
47
- */
48
- getBaseUrl(): string;
49
- /**
50
- * Get the authorization header value
51
- * If using token storage, gets the current token from storage
52
- * Otherwise returns the manual token
53
- *
54
- * @returns The Authorization header value or empty string if no token is set
55
- */
56
- getAuthorizationHeader(): Promise<string>;
57
- /**
58
- * Set authentication tokens
59
- *
60
- * @param accessToken - The access token (required)
61
- * @param refreshToken - The refresh token (optional)
62
- *
63
- * Behavior:
64
- * - If tokenStorage is provided: Stores tokens for automatic management
65
- * - If tokenStorage is not provided: Only stores access token for manual management
66
- */
67
- setTokens(accessToken: string, refreshToken?: string): Promise<void>;
68
- /**
69
- * Clear all authentication tokens
70
- *
71
- * Behavior:
72
- * - If tokenStorage is provided: Clears both access and refresh tokens from storage
73
- * - If tokenStorage is not provided: Clears the manual access token
74
- */
75
- clearTokens(): Promise<void>;
76
- /**
77
- * Set the X-Api-Key header
78
- *
79
- * @param apiKey - The API key to set
80
- */
81
- setApiKey(apiKey: string): void;
82
- /**
83
- * Clear the X-Api-Key header
84
- */
85
- clearApiKey(): void;
86
- /**
87
- * Execute a request and handle the response
88
- *
89
- * @param apiCall - Function that executes the API request
90
- * @returns Promise with the API response
91
- */
92
- protected executeRequest<T>(apiCall: () => Promise<{
93
- data?: {
94
- message?: string;
95
- success?: boolean;
96
- content?: T;
97
- };
98
- error?: ApiErrorResponse;
99
- response: Response;
100
- }>): Promise<ApiResult<T>>;
101
- /**
102
- * Initialize tokens in storage (private helper method)
103
- */
104
- private initializeTokens;
105
- /**
106
- * Merge default headers with method-level headers
107
- * Method-level headers take precedence over default headers
108
- *
109
- * @param methodHeaders - Headers passed to the specific method call
110
- * @returns Merged headers object with proper HTTP header names
111
- */
112
- protected mergeHeaders<T extends Record<string, any> = Record<string, any>>(methodHeaders?: T): T;
113
- }
@@ -1,297 +0,0 @@
1
- import createClient from "openapi-fetch";
2
- import { createDefaultAuthMiddleware } from "./middleware";
3
- import { getPathnameFromUrl, isAnonymousAuthEndpoint } from "./auth-utils";
4
- import { createDebugMiddleware } from "./logger-utils";
5
- import { mergeHeaders } from "./header-utils";
6
- /**
7
- * Available API environments
8
- */
9
- export var Environment;
10
- (function (Environment) {
11
- /**
12
- * Staging environment
13
- */
14
- Environment["Staging"] = "staging";
15
- /**
16
- * Production environment
17
- */
18
- Environment["Production"] = "production";
19
- })(Environment || (Environment = {}));
20
- /**
21
- * Base API client for Storefront API
22
- */
23
- export class StorefrontAPIClient {
24
- client;
25
- config;
26
- baseUrl;
27
- initializationPromise = null;
28
- /**
29
- * Create a new StorefrontAPIClient
30
- *
31
- * @param config - Configuration for the API client
32
- */
33
- constructor(config) {
34
- this.config = { ...config };
35
- // Determine base URL from environment or use custom URL if provided
36
- this.baseUrl = this.getBaseUrlFromConfig(this.config);
37
- this.client = createClient({
38
- baseUrl: this.baseUrl,
39
- });
40
- // Set up auth middleware if token storage is provided
41
- if (this.config.tokenStorage) {
42
- const authMiddleware = createDefaultAuthMiddleware({
43
- apiKey: this.config.apiKey,
44
- baseUrl: this.baseUrl,
45
- tokenStorage: this.config.tokenStorage,
46
- onTokensUpdated: this.config.onTokensUpdated,
47
- onTokensCleared: this.config.onTokensCleared,
48
- });
49
- this.client.use(authMiddleware);
50
- // If initial tokens were provided, store them in tokenStorage
51
- if (this.config.accessToken) {
52
- this.initializationPromise = this.initializeTokens(this.config.accessToken, this.config.refreshToken);
53
- // Clear the manual tokens since we're using storage
54
- this.config.accessToken = undefined;
55
- this.config.refreshToken = undefined;
56
- }
57
- }
58
- else {
59
- // For manual token management, add simple header injection middleware
60
- this.client.use({
61
- onRequest: async ({ request }) => {
62
- const pathname = getPathnameFromUrl(request.url);
63
- // Handle anonymous auth endpoint - use API key
64
- if (isAnonymousAuthEndpoint(pathname)) {
65
- if (this.config.apiKey) {
66
- request.headers.set("X-Api-Key", this.config.apiKey);
67
- }
68
- // Also send existing access token if available for continuity
69
- if (this.config.accessToken) {
70
- request.headers.set("Authorization", `Bearer ${this.config.accessToken}`);
71
- }
72
- return request;
73
- }
74
- // For all other endpoints, use access token
75
- if (this.config.accessToken) {
76
- request.headers.set("Authorization", `Bearer ${this.config.accessToken}`);
77
- }
78
- return request;
79
- },
80
- });
81
- }
82
- // Set up timeout middleware if configured
83
- if (this.config.timeout) {
84
- this.setupTimeoutMiddleware();
85
- }
86
- // Set up debug middleware if enabled
87
- if (this.config.debug) {
88
- const debugMiddleware = createDebugMiddleware(this.config.logger);
89
- this.client.use(debugMiddleware);
90
- }
91
- }
92
- /**
93
- * Set up timeout middleware
94
- */
95
- setupTimeoutMiddleware() {
96
- this.client.use({
97
- onRequest: async ({ request }) => {
98
- // Add timeout signal
99
- const controller = new AbortController();
100
- const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
101
- // Merge with existing signal if present
102
- if (request.signal) {
103
- request.signal.addEventListener("abort", () => controller.abort());
104
- }
105
- // Create new request with timeout signal
106
- const newRequest = new Request(request, {
107
- signal: controller.signal,
108
- });
109
- // Clean up timeout when request completes
110
- controller.signal.addEventListener("abort", () => clearTimeout(timeoutId));
111
- return newRequest;
112
- },
113
- });
114
- }
115
- /**
116
- * Constructs the base URL from the configuration
117
- *
118
- * @param config - The client configuration
119
- * @returns The constructed base URL
120
- */
121
- getBaseUrlFromConfig(config) {
122
- // If explicit baseUrl is provided, use it
123
- if (config.baseUrl) {
124
- return config.baseUrl;
125
- }
126
- // Otherwise construct URL based on environment and storeId
127
- const env = config.environment || Environment.Production;
128
- switch (env) {
129
- case Environment.Staging:
130
- return `https://staging.api.commercengine.io/api/v1/${config.storeId}/storefront`;
131
- case Environment.Production:
132
- default:
133
- return `https://prod.api.commercengine.io/api/v1/${config.storeId}/storefront`;
134
- }
135
- }
136
- /**
137
- * Get the base URL of the API
138
- *
139
- * @returns The base URL of the API
140
- */
141
- getBaseUrl() {
142
- return this.baseUrl;
143
- }
144
- /**
145
- * Get the authorization header value
146
- * If using token storage, gets the current token from storage
147
- * Otherwise returns the manual token
148
- *
149
- * @returns The Authorization header value or empty string if no token is set
150
- */
151
- async getAuthorizationHeader() {
152
- // Wait for initialization to complete if using token storage
153
- if (this.config.tokenStorage && this.initializationPromise) {
154
- await this.initializationPromise;
155
- }
156
- if (this.config.tokenStorage) {
157
- const token = await this.config.tokenStorage.getAccessToken();
158
- return token ? `Bearer ${token}` : "";
159
- }
160
- return this.config.accessToken ? `Bearer ${this.config.accessToken}` : "";
161
- }
162
- /**
163
- * Set authentication tokens
164
- *
165
- * @param accessToken - The access token (required)
166
- * @param refreshToken - The refresh token (optional)
167
- *
168
- * Behavior:
169
- * - If tokenStorage is provided: Stores tokens for automatic management
170
- * - If tokenStorage is not provided: Only stores access token for manual management
171
- */
172
- async setTokens(accessToken, refreshToken) {
173
- if (this.config.tokenStorage) {
174
- // Automatic token management
175
- await this.config.tokenStorage.setAccessToken(accessToken);
176
- if (refreshToken) {
177
- await this.config.tokenStorage.setRefreshToken(refreshToken);
178
- }
179
- }
180
- else {
181
- // Manual token management - only access token
182
- this.config.accessToken = accessToken;
183
- if (refreshToken) {
184
- console.warn("Refresh token provided but ignored in manual token management mode. Use tokenStorage for automatic management.");
185
- }
186
- }
187
- }
188
- /**
189
- * Clear all authentication tokens
190
- *
191
- * Behavior:
192
- * - If tokenStorage is provided: Clears both access and refresh tokens from storage
193
- * - If tokenStorage is not provided: Clears the manual access token
194
- */
195
- async clearTokens() {
196
- if (this.config.tokenStorage) {
197
- await this.config.tokenStorage.clearTokens();
198
- }
199
- else {
200
- this.config.accessToken = undefined;
201
- }
202
- }
203
- /**
204
- * Set the X-Api-Key header
205
- *
206
- * @param apiKey - The API key to set
207
- */
208
- setApiKey(apiKey) {
209
- this.config.apiKey = apiKey;
210
- }
211
- /**
212
- * Clear the X-Api-Key header
213
- */
214
- clearApiKey() {
215
- this.config.apiKey = undefined;
216
- }
217
- /**
218
- * Execute a request and handle the response
219
- *
220
- * @param apiCall - Function that executes the API request
221
- * @returns Promise with the API response
222
- */
223
- async executeRequest(apiCall) {
224
- try {
225
- const { data, error, response } = await apiCall();
226
- // Debug logging is now handled by middleware
227
- // openapi-fetch returns error for 4xx/5xx, data for 2xx
228
- if (error) {
229
- return {
230
- data: null,
231
- error,
232
- response,
233
- };
234
- }
235
- // If response has content, return it directly
236
- if (data && data.content !== undefined) {
237
- return {
238
- data: data.content,
239
- error: null,
240
- response,
241
- };
242
- }
243
- // If no content, return the response object (with message, success, etc.)
244
- return {
245
- data: data,
246
- error: null,
247
- response,
248
- };
249
- }
250
- catch (err) {
251
- // This handles network errors or other unexpected errors
252
- // Network errors don't have Response objects, so we create a mock response
253
- const mockResponse = new Response(null, {
254
- status: 0,
255
- statusText: "Network Error",
256
- });
257
- const errorResult = {
258
- data: null,
259
- error: {
260
- success: false,
261
- code: "NETWORK_ERROR",
262
- message: "Network error occurred",
263
- error: err,
264
- },
265
- response: mockResponse,
266
- };
267
- // Network errors are logged by middleware if debug is enabled
268
- return errorResult;
269
- }
270
- }
271
- /**
272
- * Initialize tokens in storage (private helper method)
273
- */
274
- async initializeTokens(accessToken, refreshToken) {
275
- try {
276
- if (this.config.tokenStorage) {
277
- await this.config.tokenStorage.setAccessToken(accessToken);
278
- if (refreshToken) {
279
- await this.config.tokenStorage.setRefreshToken(refreshToken);
280
- }
281
- }
282
- }
283
- catch (error) {
284
- console.warn("Failed to initialize tokens in storage:", error);
285
- }
286
- }
287
- /**
288
- * Merge default headers with method-level headers
289
- * Method-level headers take precedence over default headers
290
- *
291
- * @param methodHeaders - Headers passed to the specific method call
292
- * @returns Merged headers object with proper HTTP header names
293
- */
294
- mergeHeaders(methodHeaders) {
295
- return mergeHeaders(this.config.defaultHeaders, methodHeaders);
296
- }
297
- }
@@ -1,87 +0,0 @@
1
- import type { ApiResult, CreateCustomerBody, CreateAddressBody, CreateAddressContent, CreateAddressPathParams, CreateCustomerContent, DeleteAddressPathParams, DeleteAddressResponse, GetAddressDetailContent, GetAddressDetailPathParams, GetCustomerDetailContent, GetCustomerDetailPathParams, GetLoyaltyDetailsContent, GetLoyaltyDetailsPathParams, ListAddressesContent, ListAddressesPathParams, ListLoyaltyActivitiesContent, ListLoyaltyActivitiesPathParams, ListUserReviewsContent, ListUserReviewsPathParams, UpdateAddressDetailBody, UpdateAddressDetailContent, UpdateAddressDetailPathParams, UpdateCustomerBody, UpdateCustomerContent, UpdateCustomerPathParams } from "../types/storefront-api-types";
2
- import { StorefrontAPIClient } from "./client";
3
- /**
4
- * Client for interacting with customer endpoints
5
- */
6
- export declare class CustomerClient extends StorefrontAPIClient {
7
- /**
8
- * Create a customer
9
- *
10
- * @param body - Customer creation body
11
- * @returns Promise with customer details
12
- */
13
- createCustomer(body: CreateCustomerBody): Promise<ApiResult<CreateCustomerContent>>;
14
- /**
15
- * Get customer details
16
- *
17
- * @param pathParams - Path parameters
18
- * @returns Promise with customer details
19
- */
20
- getCustomer(pathParams: GetCustomerDetailPathParams): Promise<ApiResult<GetCustomerDetailContent>>;
21
- /**
22
- * Update a customer
23
- *
24
- * @param pathParams - Path parameters
25
- * @param body - Customer update body
26
- * @returns Promise with customer details
27
- */
28
- updateCustomer(pathParams: UpdateCustomerPathParams, body: UpdateCustomerBody): Promise<ApiResult<UpdateCustomerContent>>;
29
- /**
30
- * Get all saved addresses for a customer
31
- *
32
- * @param pathParams - Path parameters
33
- * @returns Promise with addresses
34
- */
35
- listAddresses(pathParams: ListAddressesPathParams): Promise<ApiResult<ListAddressesContent>>;
36
- /**
37
- * Create a new address for a customer
38
- *
39
- * @param pathParams - Path parameters
40
- * @param body - Address creation body
41
- * @returns Promise with address details
42
- */
43
- createAddress(pathParams: CreateAddressPathParams, body: CreateAddressBody): Promise<ApiResult<CreateAddressContent>>;
44
- /**
45
- * Get an address for a customer
46
- *
47
- * @param pathParams - Path parameters
48
- * @returns Promise with address details
49
- */
50
- getAddress(pathParams: GetAddressDetailPathParams): Promise<ApiResult<GetAddressDetailContent>>;
51
- /**
52
- * Update an address for a customer
53
- *
54
- * @param pathParams - Path parameters
55
- * @param body - Address update body
56
- * @returns Promise with address details
57
- */
58
- updateAddress(pathParams: UpdateAddressDetailPathParams, body: UpdateAddressDetailBody): Promise<ApiResult<UpdateAddressDetailContent>>;
59
- /**
60
- * Delete an address for a customer
61
- *
62
- * @param pathParams - Path parameters
63
- * @returns Promise with address details
64
- */
65
- deleteAddress(pathParams: DeleteAddressPathParams): Promise<ApiResult<DeleteAddressResponse>>;
66
- /**
67
- * Get customer loyalty details
68
- *
69
- * @param pathParams - Path parameters
70
- * @returns Promise with loyalty details
71
- */
72
- getLoyaltyDetails(pathParams: GetLoyaltyDetailsPathParams): Promise<ApiResult<GetLoyaltyDetailsContent>>;
73
- /**
74
- * List all loyalty points activity for a customer
75
- *
76
- * @param pathParams - Path parameters
77
- * @returns Promise with loyalty points activity
78
- */
79
- listLoyaltyPointsActivity(pathParams: ListLoyaltyActivitiesPathParams): Promise<ApiResult<ListLoyaltyActivitiesContent>>;
80
- /**
81
- * List all reviews left by a customer
82
- *
83
- * @param pathParams - Path parameters
84
- * @returns Promise with reviews
85
- */
86
- listCustomerReviews(pathParams: ListUserReviewsPathParams): Promise<ApiResult<ListUserReviewsContent>>;
87
- }
@@ -1,153 +0,0 @@
1
- import { StorefrontAPIClient } from "./client";
2
- /**
3
- * Client for interacting with customer endpoints
4
- */
5
- export class CustomerClient extends StorefrontAPIClient {
6
- /**
7
- * Create a customer
8
- *
9
- * @param body - Customer creation body
10
- * @returns Promise with customer details
11
- */
12
- async createCustomer(body) {
13
- return this.executeRequest(() => this.client.POST("/customers", {
14
- body: body,
15
- }));
16
- }
17
- /**
18
- * Get customer details
19
- *
20
- * @param pathParams - Path parameters
21
- * @returns Promise with customer details
22
- */
23
- async getCustomer(pathParams) {
24
- return this.executeRequest(() => this.client.GET("/customers/{id}", {
25
- params: {
26
- path: pathParams,
27
- },
28
- }));
29
- }
30
- /**
31
- * Update a customer
32
- *
33
- * @param pathParams - Path parameters
34
- * @param body - Customer update body
35
- * @returns Promise with customer details
36
- */
37
- async updateCustomer(pathParams, body) {
38
- return this.executeRequest(() => this.client.PUT("/customers/{id}", {
39
- params: {
40
- path: pathParams,
41
- },
42
- body: body,
43
- }));
44
- }
45
- /**
46
- * Get all saved addresses for a customer
47
- *
48
- * @param pathParams - Path parameters
49
- * @returns Promise with addresses
50
- */
51
- async listAddresses(pathParams) {
52
- return this.executeRequest(() => this.client.GET("/customers/{user_id}/addresses", {
53
- params: {
54
- path: pathParams,
55
- },
56
- }));
57
- }
58
- /**
59
- * Create a new address for a customer
60
- *
61
- * @param pathParams - Path parameters
62
- * @param body - Address creation body
63
- * @returns Promise with address details
64
- */
65
- async createAddress(pathParams, body) {
66
- return this.executeRequest(() => this.client.POST("/customers/{user_id}/addresses", {
67
- params: {
68
- path: pathParams,
69
- },
70
- body: body,
71
- }));
72
- }
73
- /**
74
- * Get an address for a customer
75
- *
76
- * @param pathParams - Path parameters
77
- * @returns Promise with address details
78
- */
79
- async getAddress(pathParams) {
80
- return this.executeRequest(() => this.client.GET("/customers/{user_id}/addresses/{address_id}", {
81
- params: {
82
- path: pathParams,
83
- },
84
- }));
85
- }
86
- /**
87
- * Update an address for a customer
88
- *
89
- * @param pathParams - Path parameters
90
- * @param body - Address update body
91
- * @returns Promise with address details
92
- */
93
- async updateAddress(pathParams, body) {
94
- return this.executeRequest(() => this.client.PUT("/customers/{user_id}/addresses/{address_id}", {
95
- params: {
96
- path: pathParams,
97
- },
98
- body: body,
99
- }));
100
- }
101
- /**
102
- * Delete an address for a customer
103
- *
104
- * @param pathParams - Path parameters
105
- * @returns Promise with address details
106
- */
107
- async deleteAddress(pathParams) {
108
- return this.executeRequest(() => this.client.DELETE("/customers/{user_id}/addresses/{address_id}", {
109
- params: {
110
- path: pathParams,
111
- },
112
- }));
113
- }
114
- /**
115
- * Get customer loyalty details
116
- *
117
- * @param pathParams - Path parameters
118
- * @returns Promise with loyalty details
119
- */
120
- async getLoyaltyDetails(pathParams) {
121
- return this.executeRequest(() => this.client.GET("/customers/{user_id}/loyalty", {
122
- params: {
123
- path: pathParams,
124
- },
125
- }));
126
- }
127
- /**
128
- * List all loyalty points activity for a customer
129
- *
130
- * @param pathParams - Path parameters
131
- * @returns Promise with loyalty points activity
132
- */
133
- async listLoyaltyPointsActivity(pathParams) {
134
- return this.executeRequest(() => this.client.GET("/customers/{user_id}/loyalty-points-activity", {
135
- params: {
136
- path: pathParams,
137
- },
138
- }));
139
- }
140
- /**
141
- * List all reviews left by a customer
142
- *
143
- * @param pathParams - Path parameters
144
- * @returns Promise with reviews
145
- */
146
- async listCustomerReviews(pathParams) {
147
- return this.executeRequest(() => this.client.GET("/customers/{user_id}/reviews", {
148
- params: {
149
- path: pathParams,
150
- },
151
- }));
152
- }
153
- }
@@ -1,26 +0,0 @@
1
- import type { SupportedDefaultHeaders } from "../index";
2
- /**
3
- * Transform SDK header parameters to actual HTTP header names
4
- * Headers not in the transformation map are passed through unchanged
5
- *
6
- * @param headers - Headers object with SDK parameter names
7
- * @returns Headers object with actual HTTP header names
8
- */
9
- export declare function transformHeaders(headers: SupportedDefaultHeaders): Record<string, string>;
10
- /**
11
- * Merge default headers with method-level headers
12
- * Method-level headers take precedence over default headers
13
- * Automatically transforms SDK parameter names to HTTP header names
14
- *
15
- * @param defaultHeaders - Default headers from SDK configuration
16
- * @param methodHeaders - Headers passed to the specific method call
17
- * @returns Merged headers object with proper HTTP header names
18
- */
19
- export declare function mergeHeaders<T extends Record<string, any> = Record<string, any>>(defaultHeaders?: SupportedDefaultHeaders, methodHeaders?: T): T;
20
- /**
21
- * Get the list of supported header transformations
22
- * Useful for debugging or documentation purposes
23
- *
24
- * @returns Copy of the header transformations mapping
25
- */
26
- export declare function getHeaderTransformations(): Record<string, string>;