@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.js CHANGED
@@ -1,10 +1,4 @@
1
1
  "use client";
2
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
- }) : x)(function(x) {
5
- if (typeof require !== "undefined") return require.apply(this, arguments);
6
- throw Error('Dynamic require of "' + x + '" is not supported');
7
- });
8
2
 
9
3
  // src/sdk-manager.ts
10
4
  import { cache } from "react";
@@ -193,21 +187,17 @@ var BuildCachingMemoryTokenStorage = class {
193
187
  }
194
188
  async getAccessToken() {
195
189
  if (this.access) {
196
- console.log(`\u{1F535} [BuildCache] Using instance token for key: ${this.cacheKey}`);
197
190
  return this.access;
198
191
  }
199
192
  const cached = getCachedToken(this.cacheKey);
200
193
  if (cached?.accessToken) {
201
- console.log(`\u{1F7E2} [BuildCache] Using cached token for key: ${this.cacheKey}`);
202
194
  this.access = cached.accessToken;
203
195
  this.refresh = cached.refreshToken ?? null;
204
196
  return this.access;
205
197
  }
206
- console.log(`\u{1F7E1} [BuildCache] No cached token found for key: ${this.cacheKey}`);
207
198
  return null;
208
199
  }
209
200
  async setAccessToken(token) {
210
- console.log(`\u{1F7E0} [BuildCache] Caching new access token for key: ${this.cacheKey}`);
211
201
  this.access = token;
212
202
  setCachedToken(this.cacheKey, {
213
203
  accessToken: token,
@@ -234,30 +224,63 @@ var BuildCachingMemoryTokenStorage = class {
234
224
  };
235
225
 
236
226
  // src/sdk-manager.ts
237
- var globalConfig = null;
238
- function getEnvConfig() {
239
- return {
240
- storeId: process.env.NEXT_PUBLIC_STORE_ID || "",
241
- environment: process.env.NEXT_PUBLIC_ENVIRONMENT === "production" ? Environment.Production : Environment.Staging,
242
- apiKey: process.env.NEXT_PUBLIC_API_KEY
243
- };
244
- }
245
227
  function getConfig() {
246
- if (globalConfig) {
247
- return globalConfig;
228
+ const envStoreId = process.env.NEXT_PUBLIC_STORE_ID;
229
+ const envApiKey = process.env.NEXT_PUBLIC_API_KEY;
230
+ const envEnvironment = process.env.NEXT_PUBLIC_ENVIRONMENT;
231
+ const envBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL;
232
+ const envTimeout = process.env.NEXT_PUBLIC_API_TIMEOUT ? parseInt(process.env.NEXT_PUBLIC_API_TIMEOUT, 10) : void 0;
233
+ const envDebug = process.env.NEXT_PUBLIC_DEBUG_MODE === "true";
234
+ const envDefaultHeaders = {};
235
+ if (process.env.NEXT_PUBLIC_DEFAULT_CUSTOMER_GROUP_ID) {
236
+ envDefaultHeaders.customer_group_id = process.env.NEXT_PUBLIC_DEFAULT_CUSTOMER_GROUP_ID;
248
237
  }
249
- return getEnvConfig();
250
- }
251
- var clientSDK = null;
252
- function hasRequestContext() {
253
- try {
254
- const { cookies } = __require("next/headers");
255
- cookies();
256
- return true;
257
- } catch {
258
- return false;
238
+ const storeId = globalStorefrontConfig?.storeId || envStoreId;
239
+ const apiKey = globalStorefrontConfig?.apiKey || envApiKey;
240
+ const environment = globalStorefrontConfig?.environment || (envEnvironment === "production" ? Environment.Production : Environment.Staging);
241
+ const baseUrl = globalStorefrontConfig?.baseUrl || envBaseUrl;
242
+ const timeout = globalStorefrontConfig?.timeout || envTimeout;
243
+ const debug = globalStorefrontConfig?.debug !== void 0 ? globalStorefrontConfig.debug : envDebug;
244
+ const defaultHeaders = {
245
+ ...envDefaultHeaders,
246
+ ...globalStorefrontConfig?.defaultHeaders
247
+ };
248
+ if (!storeId || !apiKey) {
249
+ throw new Error(
250
+ `StorefrontSDK configuration missing! Please set the following environment variables:
251
+
252
+ NEXT_PUBLIC_STORE_ID=your-store-id
253
+ NEXT_PUBLIC_API_KEY=your-api-key
254
+ NEXT_PUBLIC_ENVIRONMENT=staging (or production)
255
+
256
+ These variables are required for both client and server contexts to work.`
257
+ );
259
258
  }
259
+ const config = {
260
+ storeId,
261
+ apiKey,
262
+ environment
263
+ };
264
+ if (baseUrl) config.baseUrl = baseUrl;
265
+ if (timeout) config.timeout = timeout;
266
+ if (debug) config.debug = debug;
267
+ const logger = globalStorefrontConfig?.logger;
268
+ const accessToken = globalStorefrontConfig?.accessToken;
269
+ const refreshToken = globalStorefrontConfig?.refreshToken;
270
+ const onTokensUpdated = globalStorefrontConfig?.onTokensUpdated;
271
+ const onTokensCleared = globalStorefrontConfig?.onTokensCleared;
272
+ const tokenStorageOptions = globalStorefrontConfig?.tokenStorageOptions;
273
+ if (logger) config.logger = logger;
274
+ if (accessToken) config.accessToken = accessToken;
275
+ if (refreshToken) config.refreshToken = refreshToken;
276
+ if (onTokensUpdated) config.onTokensUpdated = onTokensUpdated;
277
+ if (onTokensCleared) config.onTokensCleared = onTokensCleared;
278
+ if (Object.keys(defaultHeaders).length > 0) config.defaultHeaders = defaultHeaders;
279
+ if (tokenStorageOptions) config.tokenStorageOptions = tokenStorageOptions;
280
+ return config;
260
281
  }
282
+ var globalStorefrontConfig = null;
283
+ var clientSDK = null;
261
284
  function createTokenStorage(cookieStore, options, config) {
262
285
  if (typeof window !== "undefined") {
263
286
  return new ClientTokenStorage(options);
@@ -268,14 +291,12 @@ function createTokenStorage(cookieStore, options, config) {
268
291
  const shouldCache = process.env.NEXT_BUILD_CACHE_TOKENS === "true";
269
292
  if (shouldCache && config) {
270
293
  const cacheKey = `${config.storeId}:${config.environment || "production"}`;
271
- console.log(`\u{1F680} [BuildCache] Using BuildCachingMemoryTokenStorage with key: ${cacheKey}`);
272
294
  return new BuildCachingMemoryTokenStorage(cacheKey);
273
295
  }
274
- console.log(`\u{1F504} [Build] Using standard MemoryTokenStorage (caching disabled)`);
275
296
  return new MemoryTokenStorage();
276
297
  }
277
298
  var getServerSDKCached = cache((cookieStore) => {
278
- const config = getEnvConfig();
299
+ const config = getConfig();
279
300
  return new StorefrontSDK({
280
301
  ...config,
281
302
  tokenStorage: createTokenStorage(
@@ -287,7 +308,7 @@ var getServerSDKCached = cache((cookieStore) => {
287
308
  });
288
309
  var buildTimeSDK = null;
289
310
  function getBuildTimeSDK() {
290
- const config = getEnvConfig();
311
+ const config = getConfig();
291
312
  if (!buildTimeSDK) {
292
313
  buildTimeSDK = new StorefrontSDK({
293
314
  ...config,
@@ -323,67 +344,27 @@ function getStorefrontSDK(cookieStore) {
323
344
  if (cookieStore) {
324
345
  return getServerSDKCached(cookieStore);
325
346
  }
326
- if (hasRequestContext()) {
327
- let autoDetectMessage = "";
328
- try {
329
- __require.resolve("next/headers");
330
- autoDetectMessage = `
331
-
332
- \u{1F50D} Auto-detection attempted but failed. You may be in:
333
- - Server Action (use: const sdk = getStorefrontSDK(await cookies()))
334
- - API Route (use: const sdk = getStorefrontSDK(cookies()))
335
- - Server Component in App Router (use: const sdk = getStorefrontSDK(cookies()))
336
- `;
337
- } catch {
338
- autoDetectMessage = `
339
-
340
- \u{1F4A1} Make sure you have Next.js installed and are in a server context.
341
- `;
342
- }
343
- throw new Error(
344
- `
345
- \u{1F6A8} Server Environment Detected!
346
-
347
- You're calling getStorefrontSDK() on the server without cookies.
348
- Please pass the Next.js cookie store:
349
-
350
- \u2705 Correct usage:
351
- import { cookies } from 'next/headers';
352
-
353
- // Server Actions & Route Handlers
354
- const sdk = getStorefrontSDK(await cookies());
355
-
356
- // API Routes & Server Components (App Router)
357
- const sdk = getStorefrontSDK(cookies());
358
-
359
- \u274C Your current usage:
360
- const sdk = getStorefrontSDK(); // Missing cookies!
361
- ${autoDetectMessage}
362
- This is required for server-side token access.
363
- `.trim()
364
- );
365
- }
366
347
  return getBuildTimeSDK();
367
348
  }
368
- function initializeStorefrontSDK(config) {
369
- globalConfig = config;
349
+ function initializeStorefrontSDK() {
370
350
  clientSDK = null;
371
351
  buildTimeSDK = null;
372
352
  }
373
353
 
374
- // src/storefront.ts
375
- function storefront(cookieStore) {
376
- return getStorefrontSDK(cookieStore);
377
- }
378
-
379
354
  // src/init-client.ts
380
355
  import { useEffect } from "react";
381
- function StorefrontSDKInitializer({
382
- config
383
- }) {
356
+ async function bootstrapTokens() {
357
+ const sdk = getStorefrontSDK();
358
+ const accessToken = await sdk.getAccessToken();
359
+ if (!accessToken) {
360
+ await sdk.auth.getAnonymousToken();
361
+ }
362
+ }
363
+ function StorefrontSDKInitializer({ runtimeConfig } = {}) {
384
364
  useEffect(() => {
385
- initializeStorefrontSDK(config);
386
- }, [config]);
365
+ initializeStorefrontSDK();
366
+ bootstrapTokens().catch(console.error);
367
+ }, [runtimeConfig]);
387
368
  return null;
388
369
  }
389
370
 
@@ -393,6 +374,5 @@ export {
393
374
  ClientTokenStorage,
394
375
  StorefrontSDKInitializer,
395
376
  getStorefrontSDK,
396
- initializeStorefrontSDK,
397
- storefront
377
+ initializeStorefrontSDK
398
378
  };
package/dist/index.cjs CHANGED
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,24 +15,12 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
19
 
31
20
  // src/index.ts
32
21
  var index_exports = {};
33
22
  __export(index_exports, {
34
- ClientTokenStorage: () => ClientTokenStorage,
35
- ServerTokenStorage: () => ServerTokenStorage,
36
- getStorefrontSDK: () => getStorefrontSDK,
37
- storefront: () => storefront
23
+ createStorefront: () => createStorefront
38
24
  });
39
25
  module.exports = __toCommonJS(index_exports);
40
26
 
@@ -221,21 +207,17 @@ var BuildCachingMemoryTokenStorage = class {
221
207
  }
222
208
  async getAccessToken() {
223
209
  if (this.access) {
224
- console.log(`\u{1F535} [BuildCache] Using instance token for key: ${this.cacheKey}`);
225
210
  return this.access;
226
211
  }
227
212
  const cached = getCachedToken(this.cacheKey);
228
213
  if (cached?.accessToken) {
229
- console.log(`\u{1F7E2} [BuildCache] Using cached token for key: ${this.cacheKey}`);
230
214
  this.access = cached.accessToken;
231
215
  this.refresh = cached.refreshToken ?? null;
232
216
  return this.access;
233
217
  }
234
- console.log(`\u{1F7E1} [BuildCache] No cached token found for key: ${this.cacheKey}`);
235
218
  return null;
236
219
  }
237
220
  async setAccessToken(token) {
238
- console.log(`\u{1F7E0} [BuildCache] Caching new access token for key: ${this.cacheKey}`);
239
221
  this.access = token;
240
222
  setCachedToken(this.cacheKey, {
241
223
  accessToken: token,
@@ -262,30 +244,63 @@ var BuildCachingMemoryTokenStorage = class {
262
244
  };
263
245
 
264
246
  // src/sdk-manager.ts
265
- var globalConfig = null;
266
- function getEnvConfig() {
267
- return {
268
- storeId: process.env.NEXT_PUBLIC_STORE_ID || "",
269
- environment: process.env.NEXT_PUBLIC_ENVIRONMENT === "production" ? import_storefront_sdk.Environment.Production : import_storefront_sdk.Environment.Staging,
270
- apiKey: process.env.NEXT_PUBLIC_API_KEY
271
- };
272
- }
273
247
  function getConfig() {
274
- if (globalConfig) {
275
- return globalConfig;
248
+ const envStoreId = process.env.NEXT_PUBLIC_STORE_ID;
249
+ const envApiKey = process.env.NEXT_PUBLIC_API_KEY;
250
+ const envEnvironment = process.env.NEXT_PUBLIC_ENVIRONMENT;
251
+ const envBaseUrl = process.env.NEXT_PUBLIC_API_BASE_URL;
252
+ const envTimeout = process.env.NEXT_PUBLIC_API_TIMEOUT ? parseInt(process.env.NEXT_PUBLIC_API_TIMEOUT, 10) : void 0;
253
+ const envDebug = process.env.NEXT_PUBLIC_DEBUG_MODE === "true";
254
+ const envDefaultHeaders = {};
255
+ if (process.env.NEXT_PUBLIC_DEFAULT_CUSTOMER_GROUP_ID) {
256
+ envDefaultHeaders.customer_group_id = process.env.NEXT_PUBLIC_DEFAULT_CUSTOMER_GROUP_ID;
276
257
  }
277
- return getEnvConfig();
278
- }
279
- var clientSDK = null;
280
- function hasRequestContext() {
281
- try {
282
- const { cookies } = require("next/headers");
283
- cookies();
284
- return true;
285
- } catch {
286
- return false;
258
+ const storeId = globalStorefrontConfig?.storeId || envStoreId;
259
+ const apiKey = globalStorefrontConfig?.apiKey || envApiKey;
260
+ const environment = globalStorefrontConfig?.environment || (envEnvironment === "production" ? import_storefront_sdk.Environment.Production : import_storefront_sdk.Environment.Staging);
261
+ const baseUrl = globalStorefrontConfig?.baseUrl || envBaseUrl;
262
+ const timeout = globalStorefrontConfig?.timeout || envTimeout;
263
+ const debug = globalStorefrontConfig?.debug !== void 0 ? globalStorefrontConfig.debug : envDebug;
264
+ const defaultHeaders = {
265
+ ...envDefaultHeaders,
266
+ ...globalStorefrontConfig?.defaultHeaders
267
+ };
268
+ if (!storeId || !apiKey) {
269
+ throw new Error(
270
+ `StorefrontSDK configuration missing! Please set the following environment variables:
271
+
272
+ NEXT_PUBLIC_STORE_ID=your-store-id
273
+ NEXT_PUBLIC_API_KEY=your-api-key
274
+ NEXT_PUBLIC_ENVIRONMENT=staging (or production)
275
+
276
+ These variables are required for both client and server contexts to work.`
277
+ );
287
278
  }
279
+ const config = {
280
+ storeId,
281
+ apiKey,
282
+ environment
283
+ };
284
+ if (baseUrl) config.baseUrl = baseUrl;
285
+ if (timeout) config.timeout = timeout;
286
+ if (debug) config.debug = debug;
287
+ const logger = globalStorefrontConfig?.logger;
288
+ const accessToken = globalStorefrontConfig?.accessToken;
289
+ const refreshToken = globalStorefrontConfig?.refreshToken;
290
+ const onTokensUpdated = globalStorefrontConfig?.onTokensUpdated;
291
+ const onTokensCleared = globalStorefrontConfig?.onTokensCleared;
292
+ const tokenStorageOptions = globalStorefrontConfig?.tokenStorageOptions;
293
+ if (logger) config.logger = logger;
294
+ if (accessToken) config.accessToken = accessToken;
295
+ if (refreshToken) config.refreshToken = refreshToken;
296
+ if (onTokensUpdated) config.onTokensUpdated = onTokensUpdated;
297
+ if (onTokensCleared) config.onTokensCleared = onTokensCleared;
298
+ if (Object.keys(defaultHeaders).length > 0) config.defaultHeaders = defaultHeaders;
299
+ if (tokenStorageOptions) config.tokenStorageOptions = tokenStorageOptions;
300
+ return config;
288
301
  }
302
+ var globalStorefrontConfig = null;
303
+ var clientSDK = null;
289
304
  function createTokenStorage(cookieStore, options, config) {
290
305
  if (typeof window !== "undefined") {
291
306
  return new ClientTokenStorage(options);
@@ -296,14 +311,12 @@ function createTokenStorage(cookieStore, options, config) {
296
311
  const shouldCache = process.env.NEXT_BUILD_CACHE_TOKENS === "true";
297
312
  if (shouldCache && config) {
298
313
  const cacheKey = `${config.storeId}:${config.environment || "production"}`;
299
- console.log(`\u{1F680} [BuildCache] Using BuildCachingMemoryTokenStorage with key: ${cacheKey}`);
300
314
  return new BuildCachingMemoryTokenStorage(cacheKey);
301
315
  }
302
- console.log(`\u{1F504} [Build] Using standard MemoryTokenStorage (caching disabled)`);
303
316
  return new import_storefront_sdk.MemoryTokenStorage();
304
317
  }
305
318
  var getServerSDKCached = (0, import_react.cache)((cookieStore) => {
306
- const config = getEnvConfig();
319
+ const config = getConfig();
307
320
  return new import_storefront_sdk.StorefrontSDK({
308
321
  ...config,
309
322
  tokenStorage: createTokenStorage(
@@ -315,7 +328,7 @@ var getServerSDKCached = (0, import_react.cache)((cookieStore) => {
315
328
  });
316
329
  var buildTimeSDK = null;
317
330
  function getBuildTimeSDK() {
318
- const config = getEnvConfig();
331
+ const config = getConfig();
319
332
  if (!buildTimeSDK) {
320
333
  buildTimeSDK = new import_storefront_sdk.StorefrontSDK({
321
334
  ...config,
@@ -351,61 +364,63 @@ function getStorefrontSDK(cookieStore) {
351
364
  if (cookieStore) {
352
365
  return getServerSDKCached(cookieStore);
353
366
  }
354
- if (hasRequestContext()) {
355
- let autoDetectMessage = "";
356
- try {
357
- require.resolve("next/headers");
358
- autoDetectMessage = `
359
-
360
- \u{1F50D} Auto-detection attempted but failed. You may be in:
361
- - Server Action (use: const sdk = getStorefrontSDK(await cookies()))
362
- - API Route (use: const sdk = getStorefrontSDK(cookies()))
363
- - Server Component in App Router (use: const sdk = getStorefrontSDK(cookies()))
364
- `;
365
- } catch {
366
- autoDetectMessage = `
367
+ return getBuildTimeSDK();
368
+ }
369
+ function setGlobalStorefrontConfig(config) {
370
+ globalStorefrontConfig = config;
371
+ clientSDK = null;
372
+ buildTimeSDK = null;
373
+ }
367
374
 
368
- \u{1F4A1} Make sure you have Next.js installed and are in a server context.
369
- `;
375
+ // src/create-storefront.ts
376
+ function createStorefront(config) {
377
+ if (config) {
378
+ setGlobalStorefrontConfig(config);
379
+ }
380
+ function storefront(cookieStoreOrOptions, options) {
381
+ if (typeof window !== "undefined") {
382
+ return getStorefrontSDK();
383
+ }
384
+ let cookieStore;
385
+ let isRootLayout = false;
386
+ if (cookieStoreOrOptions) {
387
+ if ("isRootLayout" in cookieStoreOrOptions) {
388
+ isRootLayout = cookieStoreOrOptions.isRootLayout;
389
+ } else {
390
+ cookieStore = cookieStoreOrOptions;
391
+ isRootLayout = options?.isRootLayout || false;
392
+ }
393
+ }
394
+ if (cookieStore) {
395
+ return getStorefrontSDK(cookieStore);
396
+ }
397
+ if (process.env.NEXT_IS_BUILD === "true" || process.env.NEXT_BUILD_CACHE_TOKENS === "true") {
398
+ return getStorefrontSDK();
399
+ }
400
+ if (isRootLayout) {
401
+ return getStorefrontSDK();
370
402
  }
371
403
  throw new Error(
372
- `
373
- \u{1F6A8} Server Environment Detected!
374
-
375
- You're calling getStorefrontSDK() on the server without cookies.
376
- Please pass the Next.js cookie store:
377
-
378
- \u2705 Correct usage:
379
- import { cookies } from 'next/headers';
380
-
381
- // Server Actions & Route Handlers
382
- const sdk = getStorefrontSDK(await cookies());
383
-
384
- // API Routes & Server Components (App Router)
385
- const sdk = getStorefrontSDK(cookies());
386
-
387
- \u274C Your current usage:
388
- const sdk = getStorefrontSDK(); // Missing cookies!
389
- ${autoDetectMessage}
390
- This is required for server-side token access.
391
- `.trim()
404
+ [
405
+ "\u{1F6A8} Server context requires cookies for user continuity!",
406
+ "",
407
+ "You're calling storefront() on the server without cookies.",
408
+ "This breaks user session continuity and analytics tracking.",
409
+ "",
410
+ "\u2705 Correct usage:",
411
+ " import { cookies } from 'next/headers'",
412
+ " const sdk = storefront(cookies())",
413
+ "",
414
+ "\u{1F4CD} Root Layout exception:",
415
+ " const sdk = storefront({ isRootLayout: true })",
416
+ "",
417
+ "This is required to maintain consistent user identity across requests."
418
+ ].join("\n")
392
419
  );
393
420
  }
394
- return getBuildTimeSDK();
421
+ return storefront;
395
422
  }
396
-
397
- // src/storefront.ts
398
- function storefront(cookieStore) {
399
- return getStorefrontSDK(cookieStore);
400
- }
401
-
402
- // src/index.ts
403
- __reExport(index_exports, require("@commercengine/storefront-sdk"), module.exports);
404
423
  // Annotate the CommonJS export names for ESM import in node:
405
424
  0 && (module.exports = {
406
- ClientTokenStorage,
407
- ServerTokenStorage,
408
- getStorefrontSDK,
409
- storefront,
410
- ...require("@commercengine/storefront-sdk")
425
+ createStorefront
411
426
  });
package/dist/index.d.cts CHANGED
@@ -1,107 +1,41 @@
1
- import { TokenStorage, StorefrontSDK, StorefrontSDKOptions } from '@commercengine/storefront-sdk';
2
- export * from '@commercengine/storefront-sdk';
3
- export { StorefrontSDK, StorefrontSDKOptions } from '@commercengine/storefront-sdk';
4
- export { default as storefront } from './storefront.cjs';
1
+ import { StorefrontSDK } from '@commercengine/storefront-sdk';
2
+ export { StorefrontSDK } from '@commercengine/storefront-sdk';
3
+ import { S as StorefrontRuntimeConfig } from './server-CwxgXezP.cjs';
5
4
 
6
- /**
7
- * Configuration options for NextJSTokenStorage
8
- */
9
- interface NextJSTokenStorageOptions {
10
- /**
11
- * Prefix for cookie names (default: "ce_")
12
- */
13
- prefix?: string;
14
- /**
15
- * Maximum age of cookies in seconds (default: 30 days)
16
- */
17
- maxAge?: number;
18
- /**
19
- * Cookie path (default: "/")
20
- */
21
- path?: string;
22
- /**
23
- * Cookie domain (default: current domain)
24
- */
25
- domain?: string;
26
- /**
27
- * Whether cookies should be secure (default: auto-detect based on environment)
28
- */
29
- secure?: boolean;
30
- /**
31
- * SameSite cookie attribute (default: "Lax")
32
- */
33
- sameSite?: "Strict" | "Lax" | "None";
34
- }
35
- /**
36
- * Client-side token storage that uses document.cookie
37
- */
38
- declare class ClientTokenStorage implements TokenStorage {
39
- private accessTokenKey;
40
- private refreshTokenKey;
41
- private options;
42
- constructor(options?: NextJSTokenStorageOptions);
43
- getAccessToken(): Promise<string | null>;
44
- setAccessToken(token: string): Promise<void>;
45
- getRefreshToken(): Promise<string | null>;
46
- setRefreshToken(token: string): Promise<void>;
47
- clearTokens(): Promise<void>;
48
- private getCookie;
49
- private setCookie;
50
- private deleteCookie;
51
- }
52
- type NextCookieStore$1 = {
53
- get: (name: string) => {
54
- value: string;
55
- } | undefined;
56
- set: (name: string, value: string, options?: any) => void;
57
- delete: (name: string) => void;
58
- };
59
- /**
60
- * Server-side token storage that uses Next.js cookies API
61
- */
62
- declare class ServerTokenStorage implements TokenStorage {
63
- private accessTokenKey;
64
- private refreshTokenKey;
65
- private options;
66
- private cookieStore;
67
- constructor(cookieStore: NextCookieStore$1, options?: NextJSTokenStorageOptions);
68
- getAccessToken(): Promise<string | null>;
69
- setAccessToken(token: string): Promise<void>;
70
- getRefreshToken(): Promise<string | null>;
71
- setRefreshToken(token: string): Promise<void>;
72
- clearTokens(): Promise<void>;
73
- }
74
-
75
- /**
76
- * Configuration for the NextJS SDK wrapper
77
- */
78
- interface NextJSSDKConfig extends Omit<StorefrontSDKOptions, "tokenStorage"> {
79
- /**
80
- * Token storage configuration options
81
- */
82
- tokenStorageOptions?: NextJSTokenStorageOptions;
83
- }
84
5
  type NextCookieStore = {
85
6
  get: (name: string) => {
7
+ name: string;
86
8
  value: string;
87
9
  } | undefined;
88
- set: (name: string, value: string, options?: any) => void;
10
+ set: (name: string, value: string, opts?: Record<string, unknown>) => void;
89
11
  delete: (name: string) => void;
90
12
  };
91
13
  /**
92
- * Smart SDK getter that automatically detects environment
14
+ * Creates a configured storefront function that works universally across all Next.js contexts
93
15
  *
94
16
  * Usage:
95
- * - Client-side: getStorefrontSDK()
96
- * - Server-side with request context: getStorefrontSDK(await cookies())
97
- * - SSG/ISR (no request context): getStorefrontSDK() (uses memory storage)
98
- */
99
- declare function getStorefrontSDK(): StorefrontSDK;
100
- declare function getStorefrontSDK(cookieStore: NextCookieStore): StorefrontSDK;
101
- /**
102
- * Initialize the SDK with configuration (internal use)
103
- * This should be called once in your app via StorefrontSDKInitializer
17
+ * ```typescript
18
+ * // lib/storefront.ts
19
+ * import { createStorefront } from "@commercengine/storefront-sdk-nextjs";
20
+ *
21
+ * export const storefront = createStorefront({
22
+ * debug: true,
23
+ * logger: (msg, ...args) => console.log('[DEBUG]', msg, ...args)
24
+ * });
25
+ * ```
26
+ *
27
+ * @param config Optional configuration for advanced options (defaults to empty if not provided)
28
+ * @returns A storefront function that works in all Next.js contexts
104
29
  */
105
- declare function initializeStorefrontSDK(config: NextJSSDKConfig): void;
30
+ declare function createStorefront(config?: StorefrontRuntimeConfig): {
31
+ (): StorefrontSDK;
32
+ (cookieStore: NextCookieStore): StorefrontSDK;
33
+ (options: {
34
+ isRootLayout: true;
35
+ }): StorefrontSDK;
36
+ (cookieStore: NextCookieStore, options: {
37
+ isRootLayout?: boolean;
38
+ }): StorefrontSDK;
39
+ };
106
40
 
107
- export { ClientTokenStorage, type NextJSSDKConfig, type NextJSTokenStorageOptions, ServerTokenStorage, getStorefrontSDK, initializeStorefrontSDK as i };
41
+ export { StorefrontRuntimeConfig, createStorefront };