@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/client.cjs DELETED
@@ -1,430 +0,0 @@
1
- "use client";
2
- "use strict";
3
- var __create = Object.create;
4
- var __defProp = Object.defineProperty;
5
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getProtoOf = Object.getPrototypeOf;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
20
- };
21
- 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
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
31
-
32
- // src/client.ts
33
- var client_exports = {};
34
- __export(client_exports, {
35
- ClientTokenStorage: () => ClientTokenStorage,
36
- StorefrontSDKInitializer: () => StorefrontSDKInitializer,
37
- getStorefrontSDK: () => getStorefrontSDK,
38
- initializeStorefrontSDK: () => initializeStorefrontSDK,
39
- storefront: () => storefront
40
- });
41
- module.exports = __toCommonJS(client_exports);
42
-
43
- // src/sdk-manager.ts
44
- var import_react = require("react");
45
- var import_storefront_sdk = require("@commercengine/storefront-sdk");
46
-
47
- // src/token-storage.ts
48
- var ClientTokenStorage = class {
49
- constructor(options = {}) {
50
- const prefix = options.prefix || "ce_";
51
- this.accessTokenKey = `${prefix}access_token`;
52
- this.refreshTokenKey = `${prefix}refresh_token`;
53
- this.options = {
54
- maxAge: options.maxAge || 30 * 24 * 60 * 60,
55
- // 30 days default
56
- path: options.path || "/",
57
- domain: options.domain,
58
- secure: options.secure ?? (typeof window !== "undefined" && window.location?.protocol === "https:"),
59
- sameSite: options.sameSite || "Lax"
60
- };
61
- }
62
- async getAccessToken() {
63
- return this.getCookie(this.accessTokenKey);
64
- }
65
- async setAccessToken(token) {
66
- this.setCookie(this.accessTokenKey, token);
67
- }
68
- async getRefreshToken() {
69
- return this.getCookie(this.refreshTokenKey);
70
- }
71
- async setRefreshToken(token) {
72
- this.setCookie(this.refreshTokenKey, token);
73
- }
74
- async clearTokens() {
75
- this.deleteCookie(this.accessTokenKey);
76
- this.deleteCookie(this.refreshTokenKey);
77
- }
78
- getCookie(name) {
79
- if (typeof document === "undefined") return null;
80
- const value = `; ${document.cookie}`;
81
- const parts = value.split(`; ${name}=`);
82
- if (parts.length === 2) {
83
- const cookieValue = parts.pop()?.split(";").shift();
84
- return cookieValue ? decodeURIComponent(cookieValue) : null;
85
- }
86
- return null;
87
- }
88
- setCookie(name, value) {
89
- if (typeof document === "undefined") return;
90
- const encodedValue = encodeURIComponent(value);
91
- let cookieString = `${name}=${encodedValue}`;
92
- if (this.options.maxAge) {
93
- cookieString += `; Max-Age=${this.options.maxAge}`;
94
- }
95
- if (this.options.path) {
96
- cookieString += `; Path=${this.options.path}`;
97
- }
98
- if (this.options.domain) {
99
- cookieString += `; Domain=${this.options.domain}`;
100
- }
101
- if (this.options.secure) {
102
- cookieString += `; Secure`;
103
- }
104
- if (this.options.sameSite) {
105
- cookieString += `; SameSite=${this.options.sameSite}`;
106
- }
107
- document.cookie = cookieString;
108
- }
109
- deleteCookie(name) {
110
- if (typeof document === "undefined") return;
111
- let cookieString = `${name}=; Max-Age=0`;
112
- if (this.options.path) {
113
- cookieString += `; Path=${this.options.path}`;
114
- }
115
- if (this.options.domain) {
116
- cookieString += `; Domain=${this.options.domain}`;
117
- }
118
- document.cookie = cookieString;
119
- }
120
- };
121
- var ServerTokenStorage = class {
122
- constructor(cookieStore, options = {}) {
123
- const prefix = options.prefix || "ce_";
124
- this.accessTokenKey = `${prefix}access_token`;
125
- this.refreshTokenKey = `${prefix}refresh_token`;
126
- this.cookieStore = cookieStore;
127
- this.options = {
128
- maxAge: options.maxAge || 30 * 24 * 60 * 60,
129
- // 30 days default
130
- path: options.path || "/",
131
- domain: options.domain,
132
- secure: options.secure ?? process.env.NODE_ENV === "production",
133
- sameSite: options.sameSite || "Lax"
134
- };
135
- }
136
- async getAccessToken() {
137
- try {
138
- return this.cookieStore.get(this.accessTokenKey)?.value || null;
139
- } catch (error) {
140
- console.warn(`Could not get access token from server cookies:`, error);
141
- return null;
142
- }
143
- }
144
- async setAccessToken(token) {
145
- try {
146
- this.cookieStore.set(this.accessTokenKey, token, {
147
- maxAge: this.options.maxAge,
148
- path: this.options.path,
149
- domain: this.options.domain,
150
- secure: this.options.secure,
151
- sameSite: this.options.sameSite?.toLowerCase(),
152
- httpOnly: false
153
- // Allow client-side access for SDK flexibility
154
- });
155
- } catch (error) {
156
- console.warn(`Could not set access token on server:`, error);
157
- }
158
- }
159
- async getRefreshToken() {
160
- try {
161
- return this.cookieStore.get(this.refreshTokenKey)?.value || null;
162
- } catch (error) {
163
- console.warn(`Could not get refresh token from server cookies:`, error);
164
- return null;
165
- }
166
- }
167
- async setRefreshToken(token) {
168
- try {
169
- this.cookieStore.set(this.refreshTokenKey, token, {
170
- maxAge: this.options.maxAge,
171
- path: this.options.path,
172
- domain: this.options.domain,
173
- secure: this.options.secure,
174
- sameSite: this.options.sameSite?.toLowerCase(),
175
- httpOnly: false
176
- // Allow client-side access for SDK flexibility
177
- });
178
- } catch (error) {
179
- console.warn(`Could not set refresh token on server:`, error);
180
- }
181
- }
182
- async clearTokens() {
183
- try {
184
- this.cookieStore.delete(this.accessTokenKey);
185
- this.cookieStore.delete(this.refreshTokenKey);
186
- } catch (error) {
187
- console.warn(`Could not clear tokens on server:`, error);
188
- }
189
- }
190
- };
191
-
192
- // src/build-token-cache.ts
193
- var store = /* @__PURE__ */ new Map();
194
- function isExpired(token) {
195
- if (!token) return true;
196
- if (!token.expiresAt) return false;
197
- return Date.now() > token.expiresAt - 3e4;
198
- }
199
- function getCachedToken(key) {
200
- const token = store.get(key);
201
- return isExpired(token) ? null : token;
202
- }
203
- function setCachedToken(key, token) {
204
- const expiresAt = token.ttlSeconds != null ? Date.now() + token.ttlSeconds * 1e3 : void 0;
205
- store.set(key, {
206
- accessToken: token.accessToken,
207
- refreshToken: token.refreshToken ?? null,
208
- expiresAt
209
- });
210
- }
211
- function clearCachedToken(key) {
212
- store.delete(key);
213
- }
214
-
215
- // src/build-caching-memory-storage.ts
216
- var DEFAULT_TTL_SECONDS = 5 * 60;
217
- var BuildCachingMemoryTokenStorage = class {
218
- constructor(cacheKey, ttlSeconds = DEFAULT_TTL_SECONDS) {
219
- this.cacheKey = cacheKey;
220
- this.ttlSeconds = ttlSeconds;
221
- this.access = null;
222
- this.refresh = null;
223
- }
224
- async getAccessToken() {
225
- if (this.access) {
226
- console.log(`\u{1F535} [BuildCache] Using instance token for key: ${this.cacheKey}`);
227
- return this.access;
228
- }
229
- const cached = getCachedToken(this.cacheKey);
230
- if (cached?.accessToken) {
231
- console.log(`\u{1F7E2} [BuildCache] Using cached token for key: ${this.cacheKey}`);
232
- this.access = cached.accessToken;
233
- this.refresh = cached.refreshToken ?? null;
234
- return this.access;
235
- }
236
- console.log(`\u{1F7E1} [BuildCache] No cached token found for key: ${this.cacheKey}`);
237
- return null;
238
- }
239
- async setAccessToken(token) {
240
- console.log(`\u{1F7E0} [BuildCache] Caching new access token for key: ${this.cacheKey}`);
241
- this.access = token;
242
- setCachedToken(this.cacheKey, {
243
- accessToken: token,
244
- refreshToken: this.refresh,
245
- ttlSeconds: this.ttlSeconds
246
- });
247
- }
248
- async getRefreshToken() {
249
- return this.refresh;
250
- }
251
- async setRefreshToken(token) {
252
- this.refresh = token;
253
- setCachedToken(this.cacheKey, {
254
- accessToken: this.access ?? "",
255
- refreshToken: token,
256
- ttlSeconds: this.ttlSeconds
257
- });
258
- }
259
- async clearTokens() {
260
- this.access = null;
261
- this.refresh = null;
262
- clearCachedToken(this.cacheKey);
263
- }
264
- };
265
-
266
- // 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
- function getConfig() {
276
- if (globalConfig) {
277
- return globalConfig;
278
- }
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;
289
- }
290
- }
291
- function createTokenStorage(cookieStore, options, config) {
292
- if (typeof window !== "undefined") {
293
- return new ClientTokenStorage(options);
294
- }
295
- if (cookieStore) {
296
- return new ServerTokenStorage(cookieStore, options);
297
- }
298
- const shouldCache = process.env.NEXT_BUILD_CACHE_TOKENS === "true";
299
- if (shouldCache && config) {
300
- const cacheKey = `${config.storeId}:${config.environment || "production"}`;
301
- console.log(`\u{1F680} [BuildCache] Using BuildCachingMemoryTokenStorage with key: ${cacheKey}`);
302
- return new BuildCachingMemoryTokenStorage(cacheKey);
303
- }
304
- console.log(`\u{1F504} [Build] Using standard MemoryTokenStorage (caching disabled)`);
305
- return new import_storefront_sdk.MemoryTokenStorage();
306
- }
307
- var getServerSDKCached = (0, import_react.cache)((cookieStore) => {
308
- const config = getEnvConfig();
309
- return new import_storefront_sdk.StorefrontSDK({
310
- ...config,
311
- tokenStorage: createTokenStorage(
312
- cookieStore,
313
- config.tokenStorageOptions,
314
- config
315
- )
316
- });
317
- });
318
- var buildTimeSDK = null;
319
- function getBuildTimeSDK() {
320
- const config = getEnvConfig();
321
- if (!buildTimeSDK) {
322
- buildTimeSDK = new import_storefront_sdk.StorefrontSDK({
323
- ...config,
324
- tokenStorage: createTokenStorage(
325
- void 0,
326
- config.tokenStorageOptions,
327
- config
328
- )
329
- });
330
- }
331
- return buildTimeSDK;
332
- }
333
- function getStorefrontSDK(cookieStore) {
334
- if (typeof window !== "undefined") {
335
- if (cookieStore) {
336
- console.warn(
337
- "Cookie store passed in client environment - this will be ignored"
338
- );
339
- }
340
- const config = getConfig();
341
- if (!clientSDK) {
342
- clientSDK = new import_storefront_sdk.StorefrontSDK({
343
- ...config,
344
- tokenStorage: createTokenStorage(
345
- void 0,
346
- config.tokenStorageOptions,
347
- config
348
- )
349
- });
350
- }
351
- return clientSDK;
352
- }
353
- if (cookieStore) {
354
- return getServerSDKCached(cookieStore);
355
- }
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
- return getBuildTimeSDK();
397
- }
398
- function initializeStorefrontSDK(config) {
399
- globalConfig = config;
400
- clientSDK = null;
401
- buildTimeSDK = null;
402
- }
403
-
404
- // src/storefront.ts
405
- function storefront(cookieStore) {
406
- return getStorefrontSDK(cookieStore);
407
- }
408
-
409
- // src/init-client.ts
410
- var import_react2 = require("react");
411
- function StorefrontSDKInitializer({
412
- config
413
- }) {
414
- (0, import_react2.useEffect)(() => {
415
- initializeStorefrontSDK(config);
416
- }, [config]);
417
- return null;
418
- }
419
-
420
- // src/client.ts
421
- __reExport(client_exports, require("@commercengine/storefront-sdk"), module.exports);
422
- // Annotate the CommonJS export names for ESM import in node:
423
- 0 && (module.exports = {
424
- ClientTokenStorage,
425
- StorefrontSDKInitializer,
426
- getStorefrontSDK,
427
- initializeStorefrontSDK,
428
- storefront,
429
- ...require("@commercengine/storefront-sdk")
430
- });
package/dist/client.d.cts DELETED
@@ -1,138 +0,0 @@
1
- import { TokenStorage, StorefrontSDK, StorefrontSDKOptions } from '@commercengine/storefront-sdk';
2
- export * from '@commercengine/storefront-sdk';
3
- export { StorefrontSDK, StorefrontSDKOptions } from '@commercengine/storefront-sdk';
4
-
5
- /**
6
- * Configuration options for NextJSTokenStorage
7
- */
8
- interface NextJSTokenStorageOptions {
9
- /**
10
- * Prefix for cookie names (default: "ce_")
11
- */
12
- prefix?: string;
13
- /**
14
- * Maximum age of cookies in seconds (default: 30 days)
15
- */
16
- maxAge?: number;
17
- /**
18
- * Cookie path (default: "/")
19
- */
20
- path?: string;
21
- /**
22
- * Cookie domain (default: current domain)
23
- */
24
- domain?: string;
25
- /**
26
- * Whether cookies should be secure (default: auto-detect based on environment)
27
- */
28
- secure?: boolean;
29
- /**
30
- * SameSite cookie attribute (default: "Lax")
31
- */
32
- sameSite?: "Strict" | "Lax" | "None";
33
- }
34
- /**
35
- * Client-side token storage that uses document.cookie
36
- */
37
- declare class ClientTokenStorage implements TokenStorage {
38
- private accessTokenKey;
39
- private refreshTokenKey;
40
- private options;
41
- constructor(options?: NextJSTokenStorageOptions);
42
- getAccessToken(): Promise<string | null>;
43
- setAccessToken(token: string): Promise<void>;
44
- getRefreshToken(): Promise<string | null>;
45
- setRefreshToken(token: string): Promise<void>;
46
- clearTokens(): Promise<void>;
47
- private getCookie;
48
- private setCookie;
49
- private deleteCookie;
50
- }
51
-
52
- /**
53
- * Configuration for the NextJS SDK wrapper
54
- */
55
- interface NextJSSDKConfig extends Omit<StorefrontSDKOptions, "tokenStorage"> {
56
- /**
57
- * Token storage configuration options
58
- */
59
- tokenStorageOptions?: NextJSTokenStorageOptions;
60
- }
61
- type NextCookieStore$1 = {
62
- get: (name: string) => {
63
- value: string;
64
- } | undefined;
65
- set: (name: string, value: string, options?: any) => void;
66
- delete: (name: string) => void;
67
- };
68
- /**
69
- * Smart SDK getter that automatically detects environment
70
- *
71
- * Usage:
72
- * - Client-side: getStorefrontSDK()
73
- * - Server-side with request context: getStorefrontSDK(await cookies())
74
- * - SSG/ISR (no request context): getStorefrontSDK() (uses memory storage)
75
- */
76
- declare function getStorefrontSDK(): StorefrontSDK;
77
- declare function getStorefrontSDK(cookieStore: NextCookieStore$1): StorefrontSDK;
78
- /**
79
- * Initialize the SDK with configuration (internal use)
80
- * This should be called once in your app via StorefrontSDKInitializer
81
- */
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;
120
-
121
- interface StorefrontSDKInitializerProps {
122
- config: NextJSSDKConfig;
123
- }
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;
137
-
138
- export { ClientTokenStorage, type NextJSSDKConfig, type NextJSTokenStorageOptions, StorefrontSDKInitializer, getStorefrontSDK, initializeStorefrontSDK, storefront };