@commercengine/storefront-sdk-nextjs 0.1.0-alpha.0 → 0.1.0-alpha.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.js ADDED
@@ -0,0 +1,398 @@
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
+
9
+ // src/sdk-manager.ts
10
+ import { cache } from "react";
11
+ import {
12
+ StorefrontSDK,
13
+ MemoryTokenStorage,
14
+ Environment
15
+ } from "@commercengine/storefront-sdk";
16
+
17
+ // src/token-storage.ts
18
+ var ClientTokenStorage = class {
19
+ constructor(options = {}) {
20
+ const prefix = options.prefix || "ce_";
21
+ this.accessTokenKey = `${prefix}access_token`;
22
+ this.refreshTokenKey = `${prefix}refresh_token`;
23
+ this.options = {
24
+ maxAge: options.maxAge || 30 * 24 * 60 * 60,
25
+ // 30 days default
26
+ path: options.path || "/",
27
+ domain: options.domain,
28
+ secure: options.secure ?? (typeof window !== "undefined" && window.location?.protocol === "https:"),
29
+ sameSite: options.sameSite || "Lax"
30
+ };
31
+ }
32
+ async getAccessToken() {
33
+ return this.getCookie(this.accessTokenKey);
34
+ }
35
+ async setAccessToken(token) {
36
+ this.setCookie(this.accessTokenKey, token);
37
+ }
38
+ async getRefreshToken() {
39
+ return this.getCookie(this.refreshTokenKey);
40
+ }
41
+ async setRefreshToken(token) {
42
+ this.setCookie(this.refreshTokenKey, token);
43
+ }
44
+ async clearTokens() {
45
+ this.deleteCookie(this.accessTokenKey);
46
+ this.deleteCookie(this.refreshTokenKey);
47
+ }
48
+ getCookie(name) {
49
+ if (typeof document === "undefined") return null;
50
+ const value = `; ${document.cookie}`;
51
+ const parts = value.split(`; ${name}=`);
52
+ if (parts.length === 2) {
53
+ const cookieValue = parts.pop()?.split(";").shift();
54
+ return cookieValue ? decodeURIComponent(cookieValue) : null;
55
+ }
56
+ return null;
57
+ }
58
+ setCookie(name, value) {
59
+ if (typeof document === "undefined") return;
60
+ const encodedValue = encodeURIComponent(value);
61
+ let cookieString = `${name}=${encodedValue}`;
62
+ if (this.options.maxAge) {
63
+ cookieString += `; Max-Age=${this.options.maxAge}`;
64
+ }
65
+ if (this.options.path) {
66
+ cookieString += `; Path=${this.options.path}`;
67
+ }
68
+ if (this.options.domain) {
69
+ cookieString += `; Domain=${this.options.domain}`;
70
+ }
71
+ if (this.options.secure) {
72
+ cookieString += `; Secure`;
73
+ }
74
+ if (this.options.sameSite) {
75
+ cookieString += `; SameSite=${this.options.sameSite}`;
76
+ }
77
+ document.cookie = cookieString;
78
+ }
79
+ deleteCookie(name) {
80
+ if (typeof document === "undefined") return;
81
+ let cookieString = `${name}=; Max-Age=0`;
82
+ if (this.options.path) {
83
+ cookieString += `; Path=${this.options.path}`;
84
+ }
85
+ if (this.options.domain) {
86
+ cookieString += `; Domain=${this.options.domain}`;
87
+ }
88
+ document.cookie = cookieString;
89
+ }
90
+ };
91
+ var ServerTokenStorage = class {
92
+ constructor(cookieStore, options = {}) {
93
+ const prefix = options.prefix || "ce_";
94
+ this.accessTokenKey = `${prefix}access_token`;
95
+ this.refreshTokenKey = `${prefix}refresh_token`;
96
+ this.cookieStore = cookieStore;
97
+ this.options = {
98
+ maxAge: options.maxAge || 30 * 24 * 60 * 60,
99
+ // 30 days default
100
+ path: options.path || "/",
101
+ domain: options.domain,
102
+ secure: options.secure ?? process.env.NODE_ENV === "production",
103
+ sameSite: options.sameSite || "Lax"
104
+ };
105
+ }
106
+ async getAccessToken() {
107
+ try {
108
+ return this.cookieStore.get(this.accessTokenKey)?.value || null;
109
+ } catch (error) {
110
+ console.warn(`Could not get access token from server cookies:`, error);
111
+ return null;
112
+ }
113
+ }
114
+ async setAccessToken(token) {
115
+ try {
116
+ this.cookieStore.set(this.accessTokenKey, token, {
117
+ maxAge: this.options.maxAge,
118
+ path: this.options.path,
119
+ domain: this.options.domain,
120
+ secure: this.options.secure,
121
+ sameSite: this.options.sameSite?.toLowerCase(),
122
+ httpOnly: false
123
+ // Allow client-side access for SDK flexibility
124
+ });
125
+ } catch (error) {
126
+ console.warn(`Could not set access token on server:`, error);
127
+ }
128
+ }
129
+ async getRefreshToken() {
130
+ try {
131
+ return this.cookieStore.get(this.refreshTokenKey)?.value || null;
132
+ } catch (error) {
133
+ console.warn(`Could not get refresh token from server cookies:`, error);
134
+ return null;
135
+ }
136
+ }
137
+ async setRefreshToken(token) {
138
+ try {
139
+ this.cookieStore.set(this.refreshTokenKey, token, {
140
+ maxAge: this.options.maxAge,
141
+ path: this.options.path,
142
+ domain: this.options.domain,
143
+ secure: this.options.secure,
144
+ sameSite: this.options.sameSite?.toLowerCase(),
145
+ httpOnly: false
146
+ // Allow client-side access for SDK flexibility
147
+ });
148
+ } catch (error) {
149
+ console.warn(`Could not set refresh token on server:`, error);
150
+ }
151
+ }
152
+ async clearTokens() {
153
+ try {
154
+ this.cookieStore.delete(this.accessTokenKey);
155
+ this.cookieStore.delete(this.refreshTokenKey);
156
+ } catch (error) {
157
+ console.warn(`Could not clear tokens on server:`, error);
158
+ }
159
+ }
160
+ };
161
+
162
+ // src/build-token-cache.ts
163
+ var store = /* @__PURE__ */ new Map();
164
+ function isExpired(token) {
165
+ if (!token) return true;
166
+ if (!token.expiresAt) return false;
167
+ return Date.now() > token.expiresAt - 3e4;
168
+ }
169
+ function getCachedToken(key) {
170
+ const token = store.get(key);
171
+ return isExpired(token) ? null : token;
172
+ }
173
+ function setCachedToken(key, token) {
174
+ const expiresAt = token.ttlSeconds != null ? Date.now() + token.ttlSeconds * 1e3 : void 0;
175
+ store.set(key, {
176
+ accessToken: token.accessToken,
177
+ refreshToken: token.refreshToken ?? null,
178
+ expiresAt
179
+ });
180
+ }
181
+ function clearCachedToken(key) {
182
+ store.delete(key);
183
+ }
184
+
185
+ // src/build-caching-memory-storage.ts
186
+ var DEFAULT_TTL_SECONDS = 5 * 60;
187
+ var BuildCachingMemoryTokenStorage = class {
188
+ constructor(cacheKey, ttlSeconds = DEFAULT_TTL_SECONDS) {
189
+ this.cacheKey = cacheKey;
190
+ this.ttlSeconds = ttlSeconds;
191
+ this.access = null;
192
+ this.refresh = null;
193
+ }
194
+ async getAccessToken() {
195
+ if (this.access) {
196
+ console.log(`\u{1F535} [BuildCache] Using instance token for key: ${this.cacheKey}`);
197
+ return this.access;
198
+ }
199
+ const cached = getCachedToken(this.cacheKey);
200
+ if (cached?.accessToken) {
201
+ console.log(`\u{1F7E2} [BuildCache] Using cached token for key: ${this.cacheKey}`);
202
+ this.access = cached.accessToken;
203
+ this.refresh = cached.refreshToken ?? null;
204
+ return this.access;
205
+ }
206
+ console.log(`\u{1F7E1} [BuildCache] No cached token found for key: ${this.cacheKey}`);
207
+ return null;
208
+ }
209
+ async setAccessToken(token) {
210
+ console.log(`\u{1F7E0} [BuildCache] Caching new access token for key: ${this.cacheKey}`);
211
+ this.access = token;
212
+ setCachedToken(this.cacheKey, {
213
+ accessToken: token,
214
+ refreshToken: this.refresh,
215
+ ttlSeconds: this.ttlSeconds
216
+ });
217
+ }
218
+ async getRefreshToken() {
219
+ return this.refresh;
220
+ }
221
+ async setRefreshToken(token) {
222
+ this.refresh = token;
223
+ setCachedToken(this.cacheKey, {
224
+ accessToken: this.access ?? "",
225
+ refreshToken: token,
226
+ ttlSeconds: this.ttlSeconds
227
+ });
228
+ }
229
+ async clearTokens() {
230
+ this.access = null;
231
+ this.refresh = null;
232
+ clearCachedToken(this.cacheKey);
233
+ }
234
+ };
235
+
236
+ // 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
+ function getConfig() {
246
+ if (globalConfig) {
247
+ return globalConfig;
248
+ }
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;
259
+ }
260
+ }
261
+ function createTokenStorage(cookieStore, options, config) {
262
+ if (typeof window !== "undefined") {
263
+ return new ClientTokenStorage(options);
264
+ }
265
+ if (cookieStore) {
266
+ return new ServerTokenStorage(cookieStore, options);
267
+ }
268
+ const shouldCache = process.env.NEXT_BUILD_CACHE_TOKENS === "true";
269
+ if (shouldCache && config) {
270
+ const cacheKey = `${config.storeId}:${config.environment || "production"}`;
271
+ console.log(`\u{1F680} [BuildCache] Using BuildCachingMemoryTokenStorage with key: ${cacheKey}`);
272
+ return new BuildCachingMemoryTokenStorage(cacheKey);
273
+ }
274
+ console.log(`\u{1F504} [Build] Using standard MemoryTokenStorage (caching disabled)`);
275
+ return new MemoryTokenStorage();
276
+ }
277
+ var getServerSDKCached = cache((cookieStore) => {
278
+ const config = getEnvConfig();
279
+ return new StorefrontSDK({
280
+ ...config,
281
+ tokenStorage: createTokenStorage(
282
+ cookieStore,
283
+ config.tokenStorageOptions,
284
+ config
285
+ )
286
+ });
287
+ });
288
+ var buildTimeSDK = null;
289
+ function getBuildTimeSDK() {
290
+ const config = getEnvConfig();
291
+ if (!buildTimeSDK) {
292
+ buildTimeSDK = new StorefrontSDK({
293
+ ...config,
294
+ tokenStorage: createTokenStorage(
295
+ void 0,
296
+ config.tokenStorageOptions,
297
+ config
298
+ )
299
+ });
300
+ }
301
+ return buildTimeSDK;
302
+ }
303
+ function getStorefrontSDK(cookieStore) {
304
+ if (typeof window !== "undefined") {
305
+ if (cookieStore) {
306
+ console.warn(
307
+ "Cookie store passed in client environment - this will be ignored"
308
+ );
309
+ }
310
+ const config = getConfig();
311
+ if (!clientSDK) {
312
+ clientSDK = new StorefrontSDK({
313
+ ...config,
314
+ tokenStorage: createTokenStorage(
315
+ void 0,
316
+ config.tokenStorageOptions,
317
+ config
318
+ )
319
+ });
320
+ }
321
+ return clientSDK;
322
+ }
323
+ if (cookieStore) {
324
+ return getServerSDKCached(cookieStore);
325
+ }
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
+ return getBuildTimeSDK();
367
+ }
368
+ function initializeStorefrontSDK(config) {
369
+ globalConfig = config;
370
+ clientSDK = null;
371
+ buildTimeSDK = null;
372
+ }
373
+
374
+ // src/storefront.ts
375
+ function storefront(cookieStore) {
376
+ return getStorefrontSDK(cookieStore);
377
+ }
378
+
379
+ // src/init-client.ts
380
+ import { useEffect } from "react";
381
+ function StorefrontSDKInitializer({
382
+ config
383
+ }) {
384
+ useEffect(() => {
385
+ initializeStorefrontSDK(config);
386
+ }, [config]);
387
+ return null;
388
+ }
389
+
390
+ // src/client.ts
391
+ export * from "@commercengine/storefront-sdk";
392
+ export {
393
+ ClientTokenStorage,
394
+ StorefrontSDKInitializer,
395
+ getStorefrontSDK,
396
+ initializeStorefrontSDK,
397
+ storefront
398
+ };