@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.
@@ -1,402 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/storefront.ts
31
- var storefront_exports = {};
32
- __export(storefront_exports, {
33
- default: () => storefront_default,
34
- storefront: () => storefront
35
- });
36
- module.exports = __toCommonJS(storefront_exports);
37
-
38
- // src/sdk-manager.ts
39
- var import_react = require("react");
40
- var import_storefront_sdk = require("@commercengine/storefront-sdk");
41
-
42
- // src/token-storage.ts
43
- var ClientTokenStorage = class {
44
- constructor(options = {}) {
45
- const prefix = options.prefix || "ce_";
46
- this.accessTokenKey = `${prefix}access_token`;
47
- this.refreshTokenKey = `${prefix}refresh_token`;
48
- this.options = {
49
- maxAge: options.maxAge || 30 * 24 * 60 * 60,
50
- // 30 days default
51
- path: options.path || "/",
52
- domain: options.domain,
53
- secure: options.secure ?? (typeof window !== "undefined" && window.location?.protocol === "https:"),
54
- sameSite: options.sameSite || "Lax"
55
- };
56
- }
57
- async getAccessToken() {
58
- return this.getCookie(this.accessTokenKey);
59
- }
60
- async setAccessToken(token) {
61
- this.setCookie(this.accessTokenKey, token);
62
- }
63
- async getRefreshToken() {
64
- return this.getCookie(this.refreshTokenKey);
65
- }
66
- async setRefreshToken(token) {
67
- this.setCookie(this.refreshTokenKey, token);
68
- }
69
- async clearTokens() {
70
- this.deleteCookie(this.accessTokenKey);
71
- this.deleteCookie(this.refreshTokenKey);
72
- }
73
- getCookie(name) {
74
- if (typeof document === "undefined") return null;
75
- const value = `; ${document.cookie}`;
76
- const parts = value.split(`; ${name}=`);
77
- if (parts.length === 2) {
78
- const cookieValue = parts.pop()?.split(";").shift();
79
- return cookieValue ? decodeURIComponent(cookieValue) : null;
80
- }
81
- return null;
82
- }
83
- setCookie(name, value) {
84
- if (typeof document === "undefined") return;
85
- const encodedValue = encodeURIComponent(value);
86
- let cookieString = `${name}=${encodedValue}`;
87
- if (this.options.maxAge) {
88
- cookieString += `; Max-Age=${this.options.maxAge}`;
89
- }
90
- if (this.options.path) {
91
- cookieString += `; Path=${this.options.path}`;
92
- }
93
- if (this.options.domain) {
94
- cookieString += `; Domain=${this.options.domain}`;
95
- }
96
- if (this.options.secure) {
97
- cookieString += `; Secure`;
98
- }
99
- if (this.options.sameSite) {
100
- cookieString += `; SameSite=${this.options.sameSite}`;
101
- }
102
- document.cookie = cookieString;
103
- }
104
- deleteCookie(name) {
105
- if (typeof document === "undefined") return;
106
- let cookieString = `${name}=; Max-Age=0`;
107
- if (this.options.path) {
108
- cookieString += `; Path=${this.options.path}`;
109
- }
110
- if (this.options.domain) {
111
- cookieString += `; Domain=${this.options.domain}`;
112
- }
113
- document.cookie = cookieString;
114
- }
115
- };
116
- var ServerTokenStorage = class {
117
- constructor(cookieStore, options = {}) {
118
- const prefix = options.prefix || "ce_";
119
- this.accessTokenKey = `${prefix}access_token`;
120
- this.refreshTokenKey = `${prefix}refresh_token`;
121
- this.cookieStore = cookieStore;
122
- this.options = {
123
- maxAge: options.maxAge || 30 * 24 * 60 * 60,
124
- // 30 days default
125
- path: options.path || "/",
126
- domain: options.domain,
127
- secure: options.secure ?? process.env.NODE_ENV === "production",
128
- sameSite: options.sameSite || "Lax"
129
- };
130
- }
131
- async getAccessToken() {
132
- try {
133
- return this.cookieStore.get(this.accessTokenKey)?.value || null;
134
- } catch (error) {
135
- console.warn(`Could not get access token from server cookies:`, error);
136
- return null;
137
- }
138
- }
139
- async setAccessToken(token) {
140
- try {
141
- this.cookieStore.set(this.accessTokenKey, token, {
142
- maxAge: this.options.maxAge,
143
- path: this.options.path,
144
- domain: this.options.domain,
145
- secure: this.options.secure,
146
- sameSite: this.options.sameSite?.toLowerCase(),
147
- httpOnly: false
148
- // Allow client-side access for SDK flexibility
149
- });
150
- } catch (error) {
151
- console.warn(`Could not set access token on server:`, error);
152
- }
153
- }
154
- async getRefreshToken() {
155
- try {
156
- return this.cookieStore.get(this.refreshTokenKey)?.value || null;
157
- } catch (error) {
158
- console.warn(`Could not get refresh token from server cookies:`, error);
159
- return null;
160
- }
161
- }
162
- async setRefreshToken(token) {
163
- try {
164
- this.cookieStore.set(this.refreshTokenKey, token, {
165
- maxAge: this.options.maxAge,
166
- path: this.options.path,
167
- domain: this.options.domain,
168
- secure: this.options.secure,
169
- sameSite: this.options.sameSite?.toLowerCase(),
170
- httpOnly: false
171
- // Allow client-side access for SDK flexibility
172
- });
173
- } catch (error) {
174
- console.warn(`Could not set refresh token on server:`, error);
175
- }
176
- }
177
- async clearTokens() {
178
- try {
179
- this.cookieStore.delete(this.accessTokenKey);
180
- this.cookieStore.delete(this.refreshTokenKey);
181
- } catch (error) {
182
- console.warn(`Could not clear tokens on server:`, error);
183
- }
184
- }
185
- };
186
-
187
- // src/build-token-cache.ts
188
- var store = /* @__PURE__ */ new Map();
189
- function isExpired(token) {
190
- if (!token) return true;
191
- if (!token.expiresAt) return false;
192
- return Date.now() > token.expiresAt - 3e4;
193
- }
194
- function getCachedToken(key) {
195
- const token = store.get(key);
196
- return isExpired(token) ? null : token;
197
- }
198
- function setCachedToken(key, token) {
199
- const expiresAt = token.ttlSeconds != null ? Date.now() + token.ttlSeconds * 1e3 : void 0;
200
- store.set(key, {
201
- accessToken: token.accessToken,
202
- refreshToken: token.refreshToken ?? null,
203
- expiresAt
204
- });
205
- }
206
- function clearCachedToken(key) {
207
- store.delete(key);
208
- }
209
-
210
- // src/build-caching-memory-storage.ts
211
- var DEFAULT_TTL_SECONDS = 5 * 60;
212
- var BuildCachingMemoryTokenStorage = class {
213
- constructor(cacheKey, ttlSeconds = DEFAULT_TTL_SECONDS) {
214
- this.cacheKey = cacheKey;
215
- this.ttlSeconds = ttlSeconds;
216
- this.access = null;
217
- this.refresh = null;
218
- }
219
- async getAccessToken() {
220
- if (this.access) {
221
- console.log(`\u{1F535} [BuildCache] Using instance token for key: ${this.cacheKey}`);
222
- return this.access;
223
- }
224
- const cached = getCachedToken(this.cacheKey);
225
- if (cached?.accessToken) {
226
- console.log(`\u{1F7E2} [BuildCache] Using cached token for key: ${this.cacheKey}`);
227
- this.access = cached.accessToken;
228
- this.refresh = cached.refreshToken ?? null;
229
- return this.access;
230
- }
231
- console.log(`\u{1F7E1} [BuildCache] No cached token found for key: ${this.cacheKey}`);
232
- return null;
233
- }
234
- async setAccessToken(token) {
235
- console.log(`\u{1F7E0} [BuildCache] Caching new access token for key: ${this.cacheKey}`);
236
- this.access = token;
237
- setCachedToken(this.cacheKey, {
238
- accessToken: token,
239
- refreshToken: this.refresh,
240
- ttlSeconds: this.ttlSeconds
241
- });
242
- }
243
- async getRefreshToken() {
244
- return this.refresh;
245
- }
246
- async setRefreshToken(token) {
247
- this.refresh = token;
248
- setCachedToken(this.cacheKey, {
249
- accessToken: this.access ?? "",
250
- refreshToken: token,
251
- ttlSeconds: this.ttlSeconds
252
- });
253
- }
254
- async clearTokens() {
255
- this.access = null;
256
- this.refresh = null;
257
- clearCachedToken(this.cacheKey);
258
- }
259
- };
260
-
261
- // src/sdk-manager.ts
262
- var globalConfig = null;
263
- function getEnvConfig() {
264
- return {
265
- storeId: process.env.NEXT_PUBLIC_STORE_ID || "",
266
- environment: process.env.NEXT_PUBLIC_ENVIRONMENT === "production" ? import_storefront_sdk.Environment.Production : import_storefront_sdk.Environment.Staging,
267
- apiKey: process.env.NEXT_PUBLIC_API_KEY
268
- };
269
- }
270
- function getConfig() {
271
- if (globalConfig) {
272
- return globalConfig;
273
- }
274
- return getEnvConfig();
275
- }
276
- var clientSDK = null;
277
- function hasRequestContext() {
278
- try {
279
- const { cookies } = require("next/headers");
280
- cookies();
281
- return true;
282
- } catch {
283
- return false;
284
- }
285
- }
286
- function createTokenStorage(cookieStore, options, config) {
287
- if (typeof window !== "undefined") {
288
- return new ClientTokenStorage(options);
289
- }
290
- if (cookieStore) {
291
- return new ServerTokenStorage(cookieStore, options);
292
- }
293
- const shouldCache = process.env.NEXT_BUILD_CACHE_TOKENS === "true";
294
- if (shouldCache && config) {
295
- const cacheKey = `${config.storeId}:${config.environment || "production"}`;
296
- console.log(`\u{1F680} [BuildCache] Using BuildCachingMemoryTokenStorage with key: ${cacheKey}`);
297
- return new BuildCachingMemoryTokenStorage(cacheKey);
298
- }
299
- console.log(`\u{1F504} [Build] Using standard MemoryTokenStorage (caching disabled)`);
300
- return new import_storefront_sdk.MemoryTokenStorage();
301
- }
302
- var getServerSDKCached = (0, import_react.cache)((cookieStore) => {
303
- const config = getEnvConfig();
304
- return new import_storefront_sdk.StorefrontSDK({
305
- ...config,
306
- tokenStorage: createTokenStorage(
307
- cookieStore,
308
- config.tokenStorageOptions,
309
- config
310
- )
311
- });
312
- });
313
- var buildTimeSDK = null;
314
- function getBuildTimeSDK() {
315
- const config = getEnvConfig();
316
- if (!buildTimeSDK) {
317
- buildTimeSDK = new import_storefront_sdk.StorefrontSDK({
318
- ...config,
319
- tokenStorage: createTokenStorage(
320
- void 0,
321
- config.tokenStorageOptions,
322
- config
323
- )
324
- });
325
- }
326
- return buildTimeSDK;
327
- }
328
- function getStorefrontSDK(cookieStore) {
329
- if (typeof window !== "undefined") {
330
- if (cookieStore) {
331
- console.warn(
332
- "Cookie store passed in client environment - this will be ignored"
333
- );
334
- }
335
- const config = getConfig();
336
- if (!clientSDK) {
337
- clientSDK = new import_storefront_sdk.StorefrontSDK({
338
- ...config,
339
- tokenStorage: createTokenStorage(
340
- void 0,
341
- config.tokenStorageOptions,
342
- config
343
- )
344
- });
345
- }
346
- return clientSDK;
347
- }
348
- if (cookieStore) {
349
- return getServerSDKCached(cookieStore);
350
- }
351
- if (hasRequestContext()) {
352
- let autoDetectMessage = "";
353
- try {
354
- require.resolve("next/headers");
355
- autoDetectMessage = `
356
-
357
- \u{1F50D} Auto-detection attempted but failed. You may be in:
358
- - Server Action (use: const sdk = getStorefrontSDK(await cookies()))
359
- - API Route (use: const sdk = getStorefrontSDK(cookies()))
360
- - Server Component in App Router (use: const sdk = getStorefrontSDK(cookies()))
361
- `;
362
- } catch {
363
- autoDetectMessage = `
364
-
365
- \u{1F4A1} Make sure you have Next.js installed and are in a server context.
366
- `;
367
- }
368
- throw new Error(
369
- `
370
- \u{1F6A8} Server Environment Detected!
371
-
372
- You're calling getStorefrontSDK() on the server without cookies.
373
- Please pass the Next.js cookie store:
374
-
375
- \u2705 Correct usage:
376
- import { cookies } from 'next/headers';
377
-
378
- // Server Actions & Route Handlers
379
- const sdk = getStorefrontSDK(await cookies());
380
-
381
- // API Routes & Server Components (App Router)
382
- const sdk = getStorefrontSDK(cookies());
383
-
384
- \u274C Your current usage:
385
- const sdk = getStorefrontSDK(); // Missing cookies!
386
- ${autoDetectMessage}
387
- This is required for server-side token access.
388
- `.trim()
389
- );
390
- }
391
- return getBuildTimeSDK();
392
- }
393
-
394
- // src/storefront.ts
395
- function storefront(cookieStore) {
396
- return getStorefrontSDK(cookieStore);
397
- }
398
- var storefront_default = storefront;
399
- // Annotate the CommonJS export names for ESM import in node:
400
- 0 && (module.exports = {
401
- storefront
402
- });
@@ -1,40 +0,0 @@
1
- import { StorefrontSDK } from '@commercengine/storefront-sdk';
2
-
3
- /**
4
- * Universal storefront SDK export
5
- *
6
- * This provides a simple unified interface that works in all Next.js contexts:
7
- * - Client components: automatically uses client token storage
8
- * - Server components: requires cookies() to be passed
9
- * - SSG/ISR: automatically uses memory storage with optional build caching
10
- *
11
- * Usage:
12
- * ```typescript
13
- * // Client-side
14
- * import { storefront } from '@commercengine/storefront-sdk-nextjs/storefront'
15
- * const products = await storefront().catalog.listProducts()
16
- *
17
- * // Server-side
18
- * import { storefront } from '@commercengine/storefront-sdk-nextjs/storefront'
19
- * import { cookies } from 'next/headers'
20
- * const products = await storefront(cookies()).catalog.listProducts()
21
- * ```
22
- */
23
-
24
- type NextCookieStore = {
25
- get: (name: string) => {
26
- value: string;
27
- } | undefined;
28
- set: (name: string, value: string, options?: any) => void;
29
- delete: (name: string) => void;
30
- };
31
- /**
32
- * Universal storefront SDK accessor
33
- *
34
- * @param cookieStore - Next.js cookie store (required on server-side)
35
- * @returns StorefrontSDK instance configured for the current environment
36
- */
37
- declare function storefront(): StorefrontSDK;
38
- declare function storefront(cookieStore: NextCookieStore): StorefrontSDK;
39
-
40
- export { storefront as default, storefront };
@@ -1,40 +0,0 @@
1
- import { StorefrontSDK } from '@commercengine/storefront-sdk';
2
-
3
- /**
4
- * Universal storefront SDK export
5
- *
6
- * This provides a simple unified interface that works in all Next.js contexts:
7
- * - Client components: automatically uses client token storage
8
- * - Server components: requires cookies() to be passed
9
- * - SSG/ISR: automatically uses memory storage with optional build caching
10
- *
11
- * Usage:
12
- * ```typescript
13
- * // Client-side
14
- * import { storefront } from '@commercengine/storefront-sdk-nextjs/storefront'
15
- * const products = await storefront().catalog.listProducts()
16
- *
17
- * // Server-side
18
- * import { storefront } from '@commercengine/storefront-sdk-nextjs/storefront'
19
- * import { cookies } from 'next/headers'
20
- * const products = await storefront(cookies()).catalog.listProducts()
21
- * ```
22
- */
23
-
24
- type NextCookieStore = {
25
- get: (name: string) => {
26
- value: string;
27
- } | undefined;
28
- set: (name: string, value: string, options?: any) => void;
29
- delete: (name: string) => void;
30
- };
31
- /**
32
- * Universal storefront SDK accessor
33
- *
34
- * @param cookieStore - Next.js cookie store (required on server-side)
35
- * @returns StorefrontSDK instance configured for the current environment
36
- */
37
- declare function storefront(): StorefrontSDK;
38
- declare function storefront(cookieStore: NextCookieStore): StorefrontSDK;
39
-
40
- export { storefront as default, storefront };