@commercengine/storefront-sdk-nextjs 0.1.0-alpha.1 → 0.1.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,107 +1,43 @@
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.js';
1
+ import { StorefrontRuntimeConfig } from "./sdk-manager-B9xDQQuv.js";
2
+ import { AuthClient, BrowserTokenStorage, CartClient, CatalogClient, CookieTokenStorage, CustomerClient, Environment, HelpersClient, MemoryTokenStorage, OrderClient, ResponseUtils, ShippingClient, StoreConfigClient, StorefrontAPIClient, StorefrontSDK, StorefrontSDK as StorefrontSDK$1 } from "@commercengine/storefront-sdk";
3
+ export * from "@commercengine/storefront-sdk";
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
- }
5
+ //#region src/create-storefront.d.ts
84
6
  type NextCookieStore = {
85
- get: (name: string) => {
86
- value: string;
87
- } | undefined;
88
- set: (name: string, value: string, options?: any) => void;
89
- delete: (name: string) => void;
7
+ get: (name: string) => {
8
+ name: string;
9
+ value: string;
10
+ } | undefined;
11
+ set: (name: string, value: string, opts?: Record<string, unknown>) => void;
12
+ delete: (name: string) => void;
90
13
  };
91
14
  /**
92
- * Smart SDK getter that automatically detects environment
15
+ * Creates a configured storefront function that works universally across all Next.js contexts
93
16
  *
94
17
  * 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
18
+ * ```typescript
19
+ * // lib/storefront.ts
20
+ * import { createStorefront } from "@commercengine/storefront-sdk-nextjs";
21
+ *
22
+ * export const storefront = createStorefront({
23
+ * debug: true,
24
+ * logger: (msg, ...args) => console.log('[DEBUG]', msg, ...args)
25
+ * });
26
+ * ```
27
+ *
28
+ * @param config Optional configuration for advanced options (defaults to empty if not provided)
29
+ * @returns A storefront function that works in all Next.js contexts
104
30
  */
105
- declare function initializeStorefrontSDK(config: NextJSSDKConfig): void;
106
-
107
- export { ClientTokenStorage, type NextJSSDKConfig, type NextJSTokenStorageOptions, ServerTokenStorage, getStorefrontSDK, initializeStorefrontSDK as i };
31
+ declare function createStorefront(config?: StorefrontRuntimeConfig): {
32
+ (): StorefrontSDK$1;
33
+ (cookieStore: NextCookieStore): StorefrontSDK$1;
34
+ (options: {
35
+ isRootLayout: true;
36
+ }): StorefrontSDK$1;
37
+ (cookieStore: NextCookieStore, options: {
38
+ isRootLayout?: boolean;
39
+ }): StorefrontSDK$1;
40
+ };
41
+ //#endregion
42
+ export { AuthClient, BrowserTokenStorage, CartClient, CatalogClient, CookieTokenStorage, CustomerClient, Environment, HelpersClient, MemoryTokenStorage, OrderClient, ResponseUtils, ShippingClient, StoreConfigClient, StorefrontAPIClient, type StorefrontRuntimeConfig, StorefrontSDK, createStorefront };
43
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/create-storefront.ts"],"sourcesContent":[],"mappings":";;;;;KAQK,eAAA;;;;EAAA,CAAA,GAAA,SAAA;EAwBW,GAAA,EAAA,CAAA,IAAA,EAAA,MAAA,EAAgB,KAAA,EAAA,MAAA,EAAA,IAAA,CAAA,EAtBY,MAsBZ,CAAA,MAAA,EAAA,OAAA,CAAA,EAAA,GAAA,IAAA;EAAA,MAAA,EAAA,CAAA,IAAA,EAAA,MAAA,EAAA,GAAA,IAAA;;;;;;;;;;;;;;;;;;;iBAAhB,gBAAA,UAA0B;MAKjB;gBACU,kBAAkB;;;MACG;gBACrB;;MAAuD"}
package/dist/index.js CHANGED
@@ -1,380 +1,57 @@
1
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
- }) : x)(function(x) {
4
- if (typeof require !== "undefined") return require.apply(this, arguments);
5
- throw Error('Dynamic require of "' + x + '" is not supported');
6
- });
7
-
8
- // src/sdk-manager.ts
9
- import { cache } from "react";
10
- import {
11
- StorefrontSDK,
12
- MemoryTokenStorage,
13
- Environment
14
- } from "@commercengine/storefront-sdk";
15
-
16
- // src/token-storage.ts
17
- var ClientTokenStorage = class {
18
- constructor(options = {}) {
19
- const prefix = options.prefix || "ce_";
20
- this.accessTokenKey = `${prefix}access_token`;
21
- this.refreshTokenKey = `${prefix}refresh_token`;
22
- this.options = {
23
- maxAge: options.maxAge || 30 * 24 * 60 * 60,
24
- // 30 days default
25
- path: options.path || "/",
26
- domain: options.domain,
27
- secure: options.secure ?? (typeof window !== "undefined" && window.location?.protocol === "https:"),
28
- sameSite: options.sameSite || "Lax"
29
- };
30
- }
31
- async getAccessToken() {
32
- return this.getCookie(this.accessTokenKey);
33
- }
34
- async setAccessToken(token) {
35
- this.setCookie(this.accessTokenKey, token);
36
- }
37
- async getRefreshToken() {
38
- return this.getCookie(this.refreshTokenKey);
39
- }
40
- async setRefreshToken(token) {
41
- this.setCookie(this.refreshTokenKey, token);
42
- }
43
- async clearTokens() {
44
- this.deleteCookie(this.accessTokenKey);
45
- this.deleteCookie(this.refreshTokenKey);
46
- }
47
- getCookie(name) {
48
- if (typeof document === "undefined") return null;
49
- const value = `; ${document.cookie}`;
50
- const parts = value.split(`; ${name}=`);
51
- if (parts.length === 2) {
52
- const cookieValue = parts.pop()?.split(";").shift();
53
- return cookieValue ? decodeURIComponent(cookieValue) : null;
54
- }
55
- return null;
56
- }
57
- setCookie(name, value) {
58
- if (typeof document === "undefined") return;
59
- const encodedValue = encodeURIComponent(value);
60
- let cookieString = `${name}=${encodedValue}`;
61
- if (this.options.maxAge) {
62
- cookieString += `; Max-Age=${this.options.maxAge}`;
63
- }
64
- if (this.options.path) {
65
- cookieString += `; Path=${this.options.path}`;
66
- }
67
- if (this.options.domain) {
68
- cookieString += `; Domain=${this.options.domain}`;
69
- }
70
- if (this.options.secure) {
71
- cookieString += `; Secure`;
72
- }
73
- if (this.options.sameSite) {
74
- cookieString += `; SameSite=${this.options.sameSite}`;
75
- }
76
- document.cookie = cookieString;
77
- }
78
- deleteCookie(name) {
79
- if (typeof document === "undefined") return;
80
- let cookieString = `${name}=; Max-Age=0`;
81
- if (this.options.path) {
82
- cookieString += `; Path=${this.options.path}`;
83
- }
84
- if (this.options.domain) {
85
- cookieString += `; Domain=${this.options.domain}`;
86
- }
87
- document.cookie = cookieString;
88
- }
89
- };
90
- var ServerTokenStorage = class {
91
- constructor(cookieStore, options = {}) {
92
- const prefix = options.prefix || "ce_";
93
- this.accessTokenKey = `${prefix}access_token`;
94
- this.refreshTokenKey = `${prefix}refresh_token`;
95
- this.cookieStore = cookieStore;
96
- this.options = {
97
- maxAge: options.maxAge || 30 * 24 * 60 * 60,
98
- // 30 days default
99
- path: options.path || "/",
100
- domain: options.domain,
101
- secure: options.secure ?? process.env.NODE_ENV === "production",
102
- sameSite: options.sameSite || "Lax"
103
- };
104
- }
105
- async getAccessToken() {
106
- try {
107
- return this.cookieStore.get(this.accessTokenKey)?.value || null;
108
- } catch (error) {
109
- console.warn(`Could not get access token from server cookies:`, error);
110
- return null;
111
- }
112
- }
113
- async setAccessToken(token) {
114
- try {
115
- this.cookieStore.set(this.accessTokenKey, token, {
116
- maxAge: this.options.maxAge,
117
- path: this.options.path,
118
- domain: this.options.domain,
119
- secure: this.options.secure,
120
- sameSite: this.options.sameSite?.toLowerCase(),
121
- httpOnly: false
122
- // Allow client-side access for SDK flexibility
123
- });
124
- } catch (error) {
125
- console.warn(`Could not set access token on server:`, error);
126
- }
127
- }
128
- async getRefreshToken() {
129
- try {
130
- return this.cookieStore.get(this.refreshTokenKey)?.value || null;
131
- } catch (error) {
132
- console.warn(`Could not get refresh token from server cookies:`, error);
133
- return null;
134
- }
135
- }
136
- async setRefreshToken(token) {
137
- try {
138
- this.cookieStore.set(this.refreshTokenKey, token, {
139
- maxAge: this.options.maxAge,
140
- path: this.options.path,
141
- domain: this.options.domain,
142
- secure: this.options.secure,
143
- sameSite: this.options.sameSite?.toLowerCase(),
144
- httpOnly: false
145
- // Allow client-side access for SDK flexibility
146
- });
147
- } catch (error) {
148
- console.warn(`Could not set refresh token on server:`, error);
149
- }
150
- }
151
- async clearTokens() {
152
- try {
153
- this.cookieStore.delete(this.accessTokenKey);
154
- this.cookieStore.delete(this.refreshTokenKey);
155
- } catch (error) {
156
- console.warn(`Could not clear tokens on server:`, error);
157
- }
158
- }
159
- };
160
-
161
- // src/build-token-cache.ts
162
- var store = /* @__PURE__ */ new Map();
163
- function isExpired(token) {
164
- if (!token) return true;
165
- if (!token.expiresAt) return false;
166
- return Date.now() > token.expiresAt - 3e4;
167
- }
168
- function getCachedToken(key) {
169
- const token = store.get(key);
170
- return isExpired(token) ? null : token;
171
- }
172
- function setCachedToken(key, token) {
173
- const expiresAt = token.ttlSeconds != null ? Date.now() + token.ttlSeconds * 1e3 : void 0;
174
- store.set(key, {
175
- accessToken: token.accessToken,
176
- refreshToken: token.refreshToken ?? null,
177
- expiresAt
178
- });
179
- }
180
- function clearCachedToken(key) {
181
- store.delete(key);
182
- }
183
-
184
- // src/build-caching-memory-storage.ts
185
- var DEFAULT_TTL_SECONDS = 5 * 60;
186
- var BuildCachingMemoryTokenStorage = class {
187
- constructor(cacheKey, ttlSeconds = DEFAULT_TTL_SECONDS) {
188
- this.cacheKey = cacheKey;
189
- this.ttlSeconds = ttlSeconds;
190
- this.access = null;
191
- this.refresh = null;
192
- }
193
- async getAccessToken() {
194
- if (this.access) {
195
- console.log(`\u{1F535} [BuildCache] Using instance token for key: ${this.cacheKey}`);
196
- return this.access;
197
- }
198
- const cached = getCachedToken(this.cacheKey);
199
- if (cached?.accessToken) {
200
- console.log(`\u{1F7E2} [BuildCache] Using cached token for key: ${this.cacheKey}`);
201
- this.access = cached.accessToken;
202
- this.refresh = cached.refreshToken ?? null;
203
- return this.access;
204
- }
205
- console.log(`\u{1F7E1} [BuildCache] No cached token found for key: ${this.cacheKey}`);
206
- return null;
207
- }
208
- async setAccessToken(token) {
209
- console.log(`\u{1F7E0} [BuildCache] Caching new access token for key: ${this.cacheKey}`);
210
- this.access = token;
211
- setCachedToken(this.cacheKey, {
212
- accessToken: token,
213
- refreshToken: this.refresh,
214
- ttlSeconds: this.ttlSeconds
215
- });
216
- }
217
- async getRefreshToken() {
218
- return this.refresh;
219
- }
220
- async setRefreshToken(token) {
221
- this.refresh = token;
222
- setCachedToken(this.cacheKey, {
223
- accessToken: this.access ?? "",
224
- refreshToken: token,
225
- ttlSeconds: this.ttlSeconds
226
- });
227
- }
228
- async clearTokens() {
229
- this.access = null;
230
- this.refresh = null;
231
- clearCachedToken(this.cacheKey);
232
- }
233
- };
234
-
235
- // src/sdk-manager.ts
236
- var globalConfig = null;
237
- function getEnvConfig() {
238
- return {
239
- storeId: process.env.NEXT_PUBLIC_STORE_ID || "",
240
- environment: process.env.NEXT_PUBLIC_ENVIRONMENT === "production" ? Environment.Production : Environment.Staging,
241
- apiKey: process.env.NEXT_PUBLIC_API_KEY
242
- };
243
- }
244
- function getConfig() {
245
- if (globalConfig) {
246
- return globalConfig;
247
- }
248
- return getEnvConfig();
249
- }
250
- var clientSDK = null;
251
- function hasRequestContext() {
252
- try {
253
- const { cookies } = __require("next/headers");
254
- cookies();
255
- return true;
256
- } catch {
257
- return false;
258
- }
259
- }
260
- function createTokenStorage(cookieStore, options, config) {
261
- if (typeof window !== "undefined") {
262
- return new ClientTokenStorage(options);
263
- }
264
- if (cookieStore) {
265
- return new ServerTokenStorage(cookieStore, options);
266
- }
267
- const shouldCache = process.env.NEXT_BUILD_CACHE_TOKENS === "true";
268
- if (shouldCache && config) {
269
- const cacheKey = `${config.storeId}:${config.environment || "production"}`;
270
- console.log(`\u{1F680} [BuildCache] Using BuildCachingMemoryTokenStorage with key: ${cacheKey}`);
271
- return new BuildCachingMemoryTokenStorage(cacheKey);
272
- }
273
- console.log(`\u{1F504} [Build] Using standard MemoryTokenStorage (caching disabled)`);
274
- return new MemoryTokenStorage();
275
- }
276
- var getServerSDKCached = cache((cookieStore) => {
277
- const config = getEnvConfig();
278
- return new StorefrontSDK({
279
- ...config,
280
- tokenStorage: createTokenStorage(
281
- cookieStore,
282
- config.tokenStorageOptions,
283
- config
284
- )
285
- });
286
- });
287
- var buildTimeSDK = null;
288
- function getBuildTimeSDK() {
289
- const config = getEnvConfig();
290
- if (!buildTimeSDK) {
291
- buildTimeSDK = new StorefrontSDK({
292
- ...config,
293
- tokenStorage: createTokenStorage(
294
- void 0,
295
- config.tokenStorageOptions,
296
- config
297
- )
298
- });
299
- }
300
- return buildTimeSDK;
301
- }
302
- function getStorefrontSDK(cookieStore) {
303
- if (typeof window !== "undefined") {
304
- if (cookieStore) {
305
- console.warn(
306
- "Cookie store passed in client environment - this will be ignored"
307
- );
308
- }
309
- const config = getConfig();
310
- if (!clientSDK) {
311
- clientSDK = new StorefrontSDK({
312
- ...config,
313
- tokenStorage: createTokenStorage(
314
- void 0,
315
- config.tokenStorageOptions,
316
- config
317
- )
318
- });
319
- }
320
- return clientSDK;
321
- }
322
- if (cookieStore) {
323
- return getServerSDKCached(cookieStore);
324
- }
325
- if (hasRequestContext()) {
326
- let autoDetectMessage = "";
327
- try {
328
- __require.resolve("next/headers");
329
- autoDetectMessage = `
330
-
331
- \u{1F50D} Auto-detection attempted but failed. You may be in:
332
- - Server Action (use: const sdk = getStorefrontSDK(await cookies()))
333
- - API Route (use: const sdk = getStorefrontSDK(cookies()))
334
- - Server Component in App Router (use: const sdk = getStorefrontSDK(cookies()))
335
- `;
336
- } catch {
337
- autoDetectMessage = `
338
-
339
- \u{1F4A1} Make sure you have Next.js installed and are in a server context.
340
- `;
341
- }
342
- throw new Error(
343
- `
344
- \u{1F6A8} Server Environment Detected!
345
-
346
- You're calling getStorefrontSDK() on the server without cookies.
347
- Please pass the Next.js cookie store:
348
-
349
- \u2705 Correct usage:
350
- import { cookies } from 'next/headers';
351
-
352
- // Server Actions & Route Handlers
353
- const sdk = getStorefrontSDK(await cookies());
354
-
355
- // API Routes & Server Components (App Router)
356
- const sdk = getStorefrontSDK(cookies());
357
-
358
- \u274C Your current usage:
359
- const sdk = getStorefrontSDK(); // Missing cookies!
360
- ${autoDetectMessage}
361
- This is required for server-side token access.
362
- `.trim()
363
- );
364
- }
365
- return getBuildTimeSDK();
366
- }
367
-
368
- // src/storefront.ts
369
- function storefront(cookieStore) {
370
- return getStorefrontSDK(cookieStore);
371
- }
372
-
373
- // src/index.ts
374
- export * from "@commercengine/storefront-sdk";
375
- export {
376
- ClientTokenStorage,
377
- ServerTokenStorage,
378
- getStorefrontSDK,
379
- storefront
380
- };
1
+ import { getStorefrontSDK, setGlobalStorefrontConfig } from "./sdk-manager-CdgrfSVp.js";
2
+ import { AuthClient, BrowserTokenStorage, CartClient, CatalogClient, CookieTokenStorage, CustomerClient, Environment, HelpersClient, MemoryTokenStorage, OrderClient, ResponseUtils, ShippingClient, StoreConfigClient, StorefrontAPIClient, StorefrontSDK } from "@commercengine/storefront-sdk";
3
+
4
+ //#region src/create-storefront.ts
5
+ /**
6
+ * Creates a configured storefront function that works universally across all Next.js contexts
7
+ *
8
+ * Usage:
9
+ * ```typescript
10
+ * // lib/storefront.ts
11
+ * import { createStorefront } from "@commercengine/storefront-sdk-nextjs";
12
+ *
13
+ * export const storefront = createStorefront({
14
+ * debug: true,
15
+ * logger: (msg, ...args) => console.log('[DEBUG]', msg, ...args)
16
+ * });
17
+ * ```
18
+ *
19
+ * @param config Optional configuration for advanced options (defaults to empty if not provided)
20
+ * @returns A storefront function that works in all Next.js contexts
21
+ */
22
+ function createStorefront(config) {
23
+ if (config) setGlobalStorefrontConfig(config);
24
+ function storefront(cookieStoreOrOptions, options) {
25
+ if (typeof window !== "undefined") return getStorefrontSDK();
26
+ let cookieStore;
27
+ let isRootLayout = false;
28
+ if (cookieStoreOrOptions) if ("isRootLayout" in cookieStoreOrOptions) isRootLayout = cookieStoreOrOptions.isRootLayout;
29
+ else {
30
+ cookieStore = cookieStoreOrOptions;
31
+ isRootLayout = options?.isRootLayout || false;
32
+ }
33
+ if (cookieStore) return getStorefrontSDK(cookieStore);
34
+ if (process.env.NEXT_IS_BUILD === "true" || process.env.NEXT_BUILD_CACHE_TOKENS === "true") return getStorefrontSDK();
35
+ if (isRootLayout) return getStorefrontSDK();
36
+ throw new Error([
37
+ "🚨 Server context requires cookies for user continuity!",
38
+ "",
39
+ "You're calling storefront() on the server without cookies.",
40
+ "This breaks user session continuity and analytics tracking.",
41
+ "",
42
+ "✅ Correct usage:",
43
+ " import { cookies } from 'next/headers'",
44
+ " const sdk = storefront(cookies())",
45
+ "",
46
+ "📍 Root Layout exception:",
47
+ " const sdk = storefront({ isRootLayout: true })",
48
+ "",
49
+ "This is required to maintain consistent user identity across requests."
50
+ ].join("\n"));
51
+ }
52
+ return storefront;
53
+ }
54
+
55
+ //#endregion
56
+ export { AuthClient, BrowserTokenStorage, CartClient, CatalogClient, CookieTokenStorage, CustomerClient, Environment, HelpersClient, MemoryTokenStorage, OrderClient, ResponseUtils, ShippingClient, StoreConfigClient, StorefrontAPIClient, StorefrontSDK, createStorefront };
57
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["cookieStore: NextCookieStore | undefined"],"sources":["../src/create-storefront.ts"],"sourcesContent":["import {\n getStorefrontSDK,\n setGlobalStorefrontConfig,\n type StorefrontRuntimeConfig,\n} from \"./sdk-manager\";\nimport type { StorefrontSDK } from \"@commercengine/storefront-sdk\";\n\n// Structural type so we don't import next/headers at module scope\ntype NextCookieStore = {\n get: (name: string) => { name: string; value: string } | undefined;\n set: (name: string, value: string, opts?: Record<string, unknown>) => void;\n delete: (name: string) => void;\n};\n\n\n/**\n * Creates a configured storefront function that works universally across all Next.js contexts\n *\n * Usage:\n * ```typescript\n * // lib/storefront.ts\n * import { createStorefront } from \"@commercengine/storefront-sdk-nextjs\";\n *\n * export const storefront = createStorefront({\n * debug: true,\n * logger: (msg, ...args) => console.log('[DEBUG]', msg, ...args)\n * });\n * ```\n *\n * @param config Optional configuration for advanced options (defaults to empty if not provided)\n * @returns A storefront function that works in all Next.js contexts\n */\nexport function createStorefront(config?: StorefrontRuntimeConfig) {\n if (config) {\n setGlobalStorefrontConfig(config);\n }\n\n function storefront(): StorefrontSDK;\n function storefront(cookieStore: NextCookieStore): StorefrontSDK;\n function storefront(options: { isRootLayout: true }): StorefrontSDK;\n function storefront(cookieStore: NextCookieStore, options: { isRootLayout?: boolean }): StorefrontSDK;\n function storefront(\n cookieStoreOrOptions?: NextCookieStore | { isRootLayout: true }, \n options?: { isRootLayout?: boolean }\n ): StorefrontSDK {\n // Client path\n if (typeof window !== \"undefined\") {\n return getStorefrontSDK();\n }\n\n // Parse parameters to handle different overloads\n let cookieStore: NextCookieStore | undefined;\n let isRootLayout = false;\n\n if (cookieStoreOrOptions) {\n if ('isRootLayout' in cookieStoreOrOptions) {\n // First parameter is options object\n isRootLayout = cookieStoreOrOptions.isRootLayout;\n } else {\n // First parameter is cookie store\n cookieStore = cookieStoreOrOptions;\n isRootLayout = options?.isRootLayout || false;\n }\n }\n\n // Server path with explicit cookies\n if (cookieStore) {\n return getStorefrontSDK(cookieStore);\n }\n\n // Server path without cookies:\n // 1. Always allow build contexts (no request context available)\n if (\n process.env.NEXT_IS_BUILD === \"true\" ||\n process.env.NEXT_BUILD_CACHE_TOKENS === \"true\"\n ) {\n return getStorefrontSDK();\n }\n\n // 2. Allow root layout with explicit flag\n if (isRootLayout) {\n return getStorefrontSDK();\n }\n\n // 3. All other server contexts must pass cookies - throw helpful error\n throw new Error(\n [\n \"🚨 Server context requires cookies for user continuity!\",\n \"\",\n \"You're calling storefront() on the server without cookies.\",\n \"This breaks user session continuity and analytics tracking.\",\n \"\",\n \"✅ Correct usage:\",\n \" import { cookies } from 'next/headers'\",\n \" const sdk = storefront(cookies())\",\n \"\",\n \"📍 Root Layout exception:\",\n \" const sdk = storefront({ isRootLayout: true })\",\n \"\",\n \"This is required to maintain consistent user identity across requests.\",\n ].join(\"\\n\")\n );\n }\n\n return storefront;\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,iBAAiB,QAAkC;AACjE,KAAI,OACF,2BAA0B;CAO5B,SAAS,WACP,sBACA,SACe;AAEf,MAAI,OAAO,WAAW,YACpB,QAAO;EAIT,IAAIA;EACJ,IAAI,eAAe;AAEnB,MAAI,qBACF,KAAI,kBAAkB,qBAEpB,gBAAe,qBAAqB;OAC/B;AAEL,iBAAc;AACd,kBAAe,SAAS,gBAAgB;;AAK5C,MAAI,YACF,QAAO,iBAAiB;AAK1B,MACE,QAAQ,IAAI,kBAAkB,UAC9B,QAAQ,IAAI,4BAA4B,OAExC,QAAO;AAIT,MAAI,aACF,QAAO;AAIT,QAAM,IAAI,MACR;GACE;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;IACA,KAAK;;AAIX,QAAO"}