@commercengine/storefront-sdk-nextjs 0.1.0-alpha.1 → 1.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.cjs CHANGED
@@ -1,10 +1,8 @@
1
1
  "use client";
2
2
  "use strict";
3
- var __create = Object.create;
4
3
  var __defProp = Object.defineProperty;
5
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
7
  var __export = (target, all) => {
10
8
  for (var name in all)
@@ -19,14 +17,6 @@ var __copyProps = (to, from, except, desc) => {
19
17
  return to;
20
18
  };
21
19
  var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
22
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
23
- // If the importer is in node compatibility mode or this is not an ESM
24
- // file that has been converted to a CommonJS file using a Babel-
25
- // compatible transform (i.e. "__esModule" has not been set), then set
26
- // "default" to the CommonJS "module.exports" for node compatibility.
27
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
28
- mod
29
- ));
30
20
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
21
 
32
22
  // src/client.ts
@@ -35,8 +25,7 @@ __export(client_exports, {
35
25
  ClientTokenStorage: () => ClientTokenStorage,
36
26
  StorefrontSDKInitializer: () => StorefrontSDKInitializer,
37
27
  getStorefrontSDK: () => getStorefrontSDK,
38
- initializeStorefrontSDK: () => initializeStorefrontSDK,
39
- storefront: () => storefront
28
+ initializeStorefrontSDK: () => initializeStorefrontSDK
40
29
  });
41
30
  module.exports = __toCommonJS(client_exports);
42
31
 
@@ -223,21 +212,17 @@ var BuildCachingMemoryTokenStorage = class {
223
212
  }
224
213
  async getAccessToken() {
225
214
  if (this.access) {
226
- console.log(`\u{1F535} [BuildCache] Using instance token for key: ${this.cacheKey}`);
227
215
  return this.access;
228
216
  }
229
217
  const cached = getCachedToken(this.cacheKey);
230
218
  if (cached?.accessToken) {
231
- console.log(`\u{1F7E2} [BuildCache] Using cached token for key: ${this.cacheKey}`);
232
219
  this.access = cached.accessToken;
233
220
  this.refresh = cached.refreshToken ?? null;
234
221
  return this.access;
235
222
  }
236
- console.log(`\u{1F7E1} [BuildCache] No cached token found for key: ${this.cacheKey}`);
237
223
  return null;
238
224
  }
239
225
  async setAccessToken(token) {
240
- console.log(`\u{1F7E0} [BuildCache] Caching new access token for key: ${this.cacheKey}`);
241
226
  this.access = token;
242
227
  setCachedToken(this.cacheKey, {
243
228
  accessToken: token,
@@ -264,30 +249,63 @@ var BuildCachingMemoryTokenStorage = class {
264
249
  };
265
250
 
266
251
  // src/sdk-manager.ts
267
- var globalConfig = null;
268
- function getEnvConfig() {
269
- return {
270
- storeId: process.env.NEXT_PUBLIC_STORE_ID || "",
271
- environment: process.env.NEXT_PUBLIC_ENVIRONMENT === "production" ? import_storefront_sdk.Environment.Production : import_storefront_sdk.Environment.Staging,
272
- apiKey: process.env.NEXT_PUBLIC_API_KEY
273
- };
274
- }
275
252
  function getConfig() {
276
- if (globalConfig) {
277
- return globalConfig;
253
+ const envStoreId = process.env.NEXT_PUBLIC_STORE_ID;
254
+ const envApiKey = process.env.NEXT_PUBLIC_API_KEY;
255
+ const envEnvironment = process.env.NEXT_PUBLIC_ENVIRONMENT;
256
+ const envBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL;
257
+ const envTimeout = process.env.NEXT_PUBLIC_API_TIMEOUT ? parseInt(process.env.NEXT_PUBLIC_API_TIMEOUT, 10) : void 0;
258
+ const envDebug = process.env.NEXT_PUBLIC_DEBUG_MODE === "true";
259
+ const envDefaultHeaders = {};
260
+ if (process.env.NEXT_PUBLIC_DEFAULT_CUSTOMER_GROUP_ID) {
261
+ envDefaultHeaders.customer_group_id = process.env.NEXT_PUBLIC_DEFAULT_CUSTOMER_GROUP_ID;
278
262
  }
279
- return getEnvConfig();
280
- }
281
- var clientSDK = null;
282
- function hasRequestContext() {
283
- try {
284
- const { cookies } = require("next/headers");
285
- cookies();
286
- return true;
287
- } catch {
288
- return false;
263
+ const storeId = globalStorefrontConfig?.storeId || envStoreId;
264
+ const apiKey = globalStorefrontConfig?.apiKey || envApiKey;
265
+ const environment = globalStorefrontConfig?.environment || (envEnvironment === "production" ? import_storefront_sdk.Environment.Production : import_storefront_sdk.Environment.Staging);
266
+ const baseUrl = globalStorefrontConfig?.baseUrl || envBaseUrl;
267
+ const timeout = globalStorefrontConfig?.timeout || envTimeout;
268
+ const debug = globalStorefrontConfig?.debug !== void 0 ? globalStorefrontConfig.debug : envDebug;
269
+ const defaultHeaders = {
270
+ ...envDefaultHeaders,
271
+ ...globalStorefrontConfig?.defaultHeaders
272
+ };
273
+ if (!storeId || !apiKey) {
274
+ throw new Error(
275
+ `StorefrontSDK configuration missing! Please set the following environment variables:
276
+
277
+ NEXT_PUBLIC_STORE_ID=your-store-id
278
+ NEXT_PUBLIC_API_KEY=your-api-key
279
+ NEXT_PUBLIC_ENVIRONMENT=staging (or production)
280
+
281
+ These variables are required for both client and server contexts to work.`
282
+ );
289
283
  }
284
+ const config = {
285
+ storeId,
286
+ apiKey,
287
+ environment
288
+ };
289
+ if (baseUrl) config.baseUrl = baseUrl;
290
+ if (timeout) config.timeout = timeout;
291
+ if (debug) config.debug = debug;
292
+ const logger = globalStorefrontConfig?.logger;
293
+ const accessToken = globalStorefrontConfig?.accessToken;
294
+ const refreshToken = globalStorefrontConfig?.refreshToken;
295
+ const onTokensUpdated = globalStorefrontConfig?.onTokensUpdated;
296
+ const onTokensCleared = globalStorefrontConfig?.onTokensCleared;
297
+ const tokenStorageOptions = globalStorefrontConfig?.tokenStorageOptions;
298
+ if (logger) config.logger = logger;
299
+ if (accessToken) config.accessToken = accessToken;
300
+ if (refreshToken) config.refreshToken = refreshToken;
301
+ if (onTokensUpdated) config.onTokensUpdated = onTokensUpdated;
302
+ if (onTokensCleared) config.onTokensCleared = onTokensCleared;
303
+ if (Object.keys(defaultHeaders).length > 0) config.defaultHeaders = defaultHeaders;
304
+ if (tokenStorageOptions) config.tokenStorageOptions = tokenStorageOptions;
305
+ return config;
290
306
  }
307
+ var globalStorefrontConfig = null;
308
+ var clientSDK = null;
291
309
  function createTokenStorage(cookieStore, options, config) {
292
310
  if (typeof window !== "undefined") {
293
311
  return new ClientTokenStorage(options);
@@ -298,14 +316,12 @@ function createTokenStorage(cookieStore, options, config) {
298
316
  const shouldCache = process.env.NEXT_BUILD_CACHE_TOKENS === "true";
299
317
  if (shouldCache && config) {
300
318
  const cacheKey = `${config.storeId}:${config.environment || "production"}`;
301
- console.log(`\u{1F680} [BuildCache] Using BuildCachingMemoryTokenStorage with key: ${cacheKey}`);
302
319
  return new BuildCachingMemoryTokenStorage(cacheKey);
303
320
  }
304
- console.log(`\u{1F504} [Build] Using standard MemoryTokenStorage (caching disabled)`);
305
321
  return new import_storefront_sdk.MemoryTokenStorage();
306
322
  }
307
323
  var getServerSDKCached = (0, import_react.cache)((cookieStore) => {
308
- const config = getEnvConfig();
324
+ const config = getConfig();
309
325
  return new import_storefront_sdk.StorefrontSDK({
310
326
  ...config,
311
327
  tokenStorage: createTokenStorage(
@@ -317,7 +333,7 @@ var getServerSDKCached = (0, import_react.cache)((cookieStore) => {
317
333
  });
318
334
  var buildTimeSDK = null;
319
335
  function getBuildTimeSDK() {
320
- const config = getEnvConfig();
336
+ const config = getConfig();
321
337
  if (!buildTimeSDK) {
322
338
  buildTimeSDK = new import_storefront_sdk.StorefrontSDK({
323
339
  ...config,
@@ -353,67 +369,27 @@ function getStorefrontSDK(cookieStore) {
353
369
  if (cookieStore) {
354
370
  return getServerSDKCached(cookieStore);
355
371
  }
356
- if (hasRequestContext()) {
357
- let autoDetectMessage = "";
358
- try {
359
- require.resolve("next/headers");
360
- autoDetectMessage = `
361
-
362
- \u{1F50D} Auto-detection attempted but failed. You may be in:
363
- - Server Action (use: const sdk = getStorefrontSDK(await cookies()))
364
- - API Route (use: const sdk = getStorefrontSDK(cookies()))
365
- - Server Component in App Router (use: const sdk = getStorefrontSDK(cookies()))
366
- `;
367
- } catch {
368
- autoDetectMessage = `
369
-
370
- \u{1F4A1} Make sure you have Next.js installed and are in a server context.
371
- `;
372
- }
373
- throw new Error(
374
- `
375
- \u{1F6A8} Server Environment Detected!
376
-
377
- You're calling getStorefrontSDK() on the server without cookies.
378
- Please pass the Next.js cookie store:
379
-
380
- \u2705 Correct usage:
381
- import { cookies } from 'next/headers';
382
-
383
- // Server Actions & Route Handlers
384
- const sdk = getStorefrontSDK(await cookies());
385
-
386
- // API Routes & Server Components (App Router)
387
- const sdk = getStorefrontSDK(cookies());
388
-
389
- \u274C Your current usage:
390
- const sdk = getStorefrontSDK(); // Missing cookies!
391
- ${autoDetectMessage}
392
- This is required for server-side token access.
393
- `.trim()
394
- );
395
- }
396
372
  return getBuildTimeSDK();
397
373
  }
398
- function initializeStorefrontSDK(config) {
399
- globalConfig = config;
374
+ function initializeStorefrontSDK() {
400
375
  clientSDK = null;
401
376
  buildTimeSDK = null;
402
377
  }
403
378
 
404
- // src/storefront.ts
405
- function storefront(cookieStore) {
406
- return getStorefrontSDK(cookieStore);
407
- }
408
-
409
379
  // src/init-client.ts
410
380
  var import_react2 = require("react");
411
- function StorefrontSDKInitializer({
412
- config
413
- }) {
381
+ async function bootstrapTokens() {
382
+ const sdk = getStorefrontSDK();
383
+ const accessToken = await sdk.getAccessToken();
384
+ if (!accessToken) {
385
+ await sdk.auth.getAnonymousToken();
386
+ }
387
+ }
388
+ function StorefrontSDKInitializer({ runtimeConfig } = {}) {
414
389
  (0, import_react2.useEffect)(() => {
415
- initializeStorefrontSDK(config);
416
- }, [config]);
390
+ initializeStorefrontSDK();
391
+ bootstrapTokens().catch(console.error);
392
+ }, [runtimeConfig]);
417
393
  return null;
418
394
  }
419
395
 
@@ -425,6 +401,5 @@ __reExport(client_exports, require("@commercengine/storefront-sdk"), module.expo
425
401
  StorefrontSDKInitializer,
426
402
  getStorefrontSDK,
427
403
  initializeStorefrontSDK,
428
- storefront,
429
404
  ...require("@commercengine/storefront-sdk")
430
405
  });
package/dist/client.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { TokenStorage, StorefrontSDK, StorefrontSDKOptions } from '@commercengine/storefront-sdk';
1
+ import { TokenStorage, StorefrontSDK, StorefrontSDKOptions, Environment, SupportedDefaultHeaders, DebugLoggerFn } from '@commercengine/storefront-sdk';
2
2
  export * from '@commercengine/storefront-sdk';
3
3
  export { StorefrontSDK, StorefrontSDKOptions } from '@commercengine/storefront-sdk';
4
4
 
@@ -58,7 +58,35 @@ interface NextJSSDKConfig extends Omit<StorefrontSDKOptions, "tokenStorage"> {
58
58
  */
59
59
  tokenStorageOptions?: NextJSTokenStorageOptions;
60
60
  }
61
- type NextCookieStore$1 = {
61
+ /**
62
+ * Runtime configuration overrides that can be passed to storefront() function
63
+ * These override environment variables for that specific request
64
+ */
65
+ interface StorefrontRuntimeConfig {
66
+ /**
67
+ * Override environment variables
68
+ */
69
+ storeId?: string;
70
+ apiKey?: string;
71
+ environment?: Environment;
72
+ baseUrl?: string;
73
+ timeout?: number;
74
+ debug?: boolean;
75
+ /**
76
+ * Advanced options not available via environment variables
77
+ */
78
+ accessToken?: string;
79
+ refreshToken?: string;
80
+ defaultHeaders?: SupportedDefaultHeaders;
81
+ logger?: DebugLoggerFn;
82
+ onTokensUpdated?: (accessToken: string, refreshToken: string) => void;
83
+ onTokensCleared?: () => void;
84
+ /**
85
+ * Token storage configuration
86
+ */
87
+ tokenStorageOptions?: NextJSTokenStorageOptions;
88
+ }
89
+ type NextCookieStore = {
62
90
  get: (name: string) => {
63
91
  value: string;
64
92
  } | undefined;
@@ -74,65 +102,20 @@ type NextCookieStore$1 = {
74
102
  * - SSG/ISR (no request context): getStorefrontSDK() (uses memory storage)
75
103
  */
76
104
  declare function getStorefrontSDK(): StorefrontSDK;
77
- declare function getStorefrontSDK(cookieStore: NextCookieStore$1): StorefrontSDK;
105
+ declare function getStorefrontSDK(cookieStore: NextCookieStore): StorefrontSDK;
78
106
  /**
79
- * Initialize the SDK with configuration (internal use)
107
+ * Initialize the SDK (internal use)
80
108
  * This should be called once in your app via StorefrontSDKInitializer
81
109
  */
82
- declare function initializeStorefrontSDK(config: NextJSSDKConfig): void;
83
-
84
- /**
85
- * Universal storefront SDK export
86
- *
87
- * This provides a simple unified interface that works in all Next.js contexts:
88
- * - Client components: automatically uses client token storage
89
- * - Server components: requires cookies() to be passed
90
- * - SSG/ISR: automatically uses memory storage with optional build caching
91
- *
92
- * Usage:
93
- * ```typescript
94
- * // Client-side
95
- * import { storefront } from '@commercengine/storefront-sdk-nextjs/storefront'
96
- * const products = await storefront().catalog.listProducts()
97
- *
98
- * // Server-side
99
- * import { storefront } from '@commercengine/storefront-sdk-nextjs/storefront'
100
- * import { cookies } from 'next/headers'
101
- * const products = await storefront(cookies()).catalog.listProducts()
102
- * ```
103
- */
104
-
105
- type NextCookieStore = {
106
- get: (name: string) => {
107
- value: string;
108
- } | undefined;
109
- set: (name: string, value: string, options?: any) => void;
110
- delete: (name: string) => void;
111
- };
112
- /**
113
- * Universal storefront SDK accessor
114
- *
115
- * @param cookieStore - Next.js cookie store (required on server-side)
116
- * @returns StorefrontSDK instance configured for the current environment
117
- */
118
- declare function storefront(): StorefrontSDK;
119
- declare function storefront(cookieStore: NextCookieStore): StorefrontSDK;
110
+ declare function initializeStorefrontSDK(): void;
120
111
 
121
112
  interface StorefrontSDKInitializerProps {
122
- config: NextJSSDKConfig;
113
+ /**
114
+ * Optional runtime configuration overrides for client-side API calls
115
+ * These settings will apply to all client-side storefront() calls
116
+ */
117
+ runtimeConfig?: StorefrontRuntimeConfig;
123
118
  }
124
- /**
125
- * Client-side initialization component
126
- * Use this in your root layout to initialize the SDK once
127
- *
128
- * The core SDK middleware now automatically handles everything:
129
- * - Creates anonymous tokens automatically on first API request (if no tokens exist)
130
- * - Token state assessment and cleanup on first request per page load
131
- * - Expired token refresh with automatic anonymous fallback
132
- * - Graceful handling of partial token states
133
- *
134
- * No manual token creation needed - just make API calls and everything works!
135
- */
136
- declare function StorefrontSDKInitializer({ config, }: StorefrontSDKInitializerProps): null;
119
+ declare function StorefrontSDKInitializer({ runtimeConfig }?: StorefrontSDKInitializerProps): null;
137
120
 
138
- export { ClientTokenStorage, type NextJSSDKConfig, type NextJSTokenStorageOptions, StorefrontSDKInitializer, getStorefrontSDK, initializeStorefrontSDK, storefront };
121
+ export { ClientTokenStorage, type NextJSSDKConfig, type NextJSTokenStorageOptions, StorefrontSDKInitializer, getStorefrontSDK, initializeStorefrontSDK };
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { TokenStorage, StorefrontSDK, StorefrontSDKOptions } from '@commercengine/storefront-sdk';
1
+ import { TokenStorage, StorefrontSDK, StorefrontSDKOptions, Environment, SupportedDefaultHeaders, DebugLoggerFn } from '@commercengine/storefront-sdk';
2
2
  export * from '@commercengine/storefront-sdk';
3
3
  export { StorefrontSDK, StorefrontSDKOptions } from '@commercengine/storefront-sdk';
4
4
 
@@ -58,7 +58,35 @@ interface NextJSSDKConfig extends Omit<StorefrontSDKOptions, "tokenStorage"> {
58
58
  */
59
59
  tokenStorageOptions?: NextJSTokenStorageOptions;
60
60
  }
61
- type NextCookieStore$1 = {
61
+ /**
62
+ * Runtime configuration overrides that can be passed to storefront() function
63
+ * These override environment variables for that specific request
64
+ */
65
+ interface StorefrontRuntimeConfig {
66
+ /**
67
+ * Override environment variables
68
+ */
69
+ storeId?: string;
70
+ apiKey?: string;
71
+ environment?: Environment;
72
+ baseUrl?: string;
73
+ timeout?: number;
74
+ debug?: boolean;
75
+ /**
76
+ * Advanced options not available via environment variables
77
+ */
78
+ accessToken?: string;
79
+ refreshToken?: string;
80
+ defaultHeaders?: SupportedDefaultHeaders;
81
+ logger?: DebugLoggerFn;
82
+ onTokensUpdated?: (accessToken: string, refreshToken: string) => void;
83
+ onTokensCleared?: () => void;
84
+ /**
85
+ * Token storage configuration
86
+ */
87
+ tokenStorageOptions?: NextJSTokenStorageOptions;
88
+ }
89
+ type NextCookieStore = {
62
90
  get: (name: string) => {
63
91
  value: string;
64
92
  } | undefined;
@@ -74,65 +102,20 @@ type NextCookieStore$1 = {
74
102
  * - SSG/ISR (no request context): getStorefrontSDK() (uses memory storage)
75
103
  */
76
104
  declare function getStorefrontSDK(): StorefrontSDK;
77
- declare function getStorefrontSDK(cookieStore: NextCookieStore$1): StorefrontSDK;
105
+ declare function getStorefrontSDK(cookieStore: NextCookieStore): StorefrontSDK;
78
106
  /**
79
- * Initialize the SDK with configuration (internal use)
107
+ * Initialize the SDK (internal use)
80
108
  * This should be called once in your app via StorefrontSDKInitializer
81
109
  */
82
- declare function initializeStorefrontSDK(config: NextJSSDKConfig): void;
83
-
84
- /**
85
- * Universal storefront SDK export
86
- *
87
- * This provides a simple unified interface that works in all Next.js contexts:
88
- * - Client components: automatically uses client token storage
89
- * - Server components: requires cookies() to be passed
90
- * - SSG/ISR: automatically uses memory storage with optional build caching
91
- *
92
- * Usage:
93
- * ```typescript
94
- * // Client-side
95
- * import { storefront } from '@commercengine/storefront-sdk-nextjs/storefront'
96
- * const products = await storefront().catalog.listProducts()
97
- *
98
- * // Server-side
99
- * import { storefront } from '@commercengine/storefront-sdk-nextjs/storefront'
100
- * import { cookies } from 'next/headers'
101
- * const products = await storefront(cookies()).catalog.listProducts()
102
- * ```
103
- */
104
-
105
- type NextCookieStore = {
106
- get: (name: string) => {
107
- value: string;
108
- } | undefined;
109
- set: (name: string, value: string, options?: any) => void;
110
- delete: (name: string) => void;
111
- };
112
- /**
113
- * Universal storefront SDK accessor
114
- *
115
- * @param cookieStore - Next.js cookie store (required on server-side)
116
- * @returns StorefrontSDK instance configured for the current environment
117
- */
118
- declare function storefront(): StorefrontSDK;
119
- declare function storefront(cookieStore: NextCookieStore): StorefrontSDK;
110
+ declare function initializeStorefrontSDK(): void;
120
111
 
121
112
  interface StorefrontSDKInitializerProps {
122
- config: NextJSSDKConfig;
113
+ /**
114
+ * Optional runtime configuration overrides for client-side API calls
115
+ * These settings will apply to all client-side storefront() calls
116
+ */
117
+ runtimeConfig?: StorefrontRuntimeConfig;
123
118
  }
124
- /**
125
- * Client-side initialization component
126
- * Use this in your root layout to initialize the SDK once
127
- *
128
- * The core SDK middleware now automatically handles everything:
129
- * - Creates anonymous tokens automatically on first API request (if no tokens exist)
130
- * - Token state assessment and cleanup on first request per page load
131
- * - Expired token refresh with automatic anonymous fallback
132
- * - Graceful handling of partial token states
133
- *
134
- * No manual token creation needed - just make API calls and everything works!
135
- */
136
- declare function StorefrontSDKInitializer({ config, }: StorefrontSDKInitializerProps): null;
119
+ declare function StorefrontSDKInitializer({ runtimeConfig }?: StorefrontSDKInitializerProps): null;
137
120
 
138
- export { ClientTokenStorage, type NextJSSDKConfig, type NextJSTokenStorageOptions, StorefrontSDKInitializer, getStorefrontSDK, initializeStorefrontSDK, storefront };
121
+ export { ClientTokenStorage, type NextJSSDKConfig, type NextJSTokenStorageOptions, StorefrontSDKInitializer, getStorefrontSDK, initializeStorefrontSDK };