@viu/emporix-sdk-react 2.13.1 → 2.14.0

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/provider.cjs CHANGED
@@ -1,11 +1,34 @@
1
- 'use strict';
2
-
3
- var react = require('react');
4
- var reactQuery = require('@tanstack/react-query');
5
- var emporixSdk = require('@viu/emporix-sdk');
6
- var jsxRuntime = require('react/jsx-runtime');
1
+ "use client";
2
+ "use strict";
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
7
20
 
8
21
  // src/provider.tsx
22
+ var provider_exports = {};
23
+ __export(provider_exports, {
24
+ EmporixProvider: () => EmporixProvider,
25
+ EmporixSiteContext: () => EmporixSiteContext,
26
+ useEmporix: () => useEmporix
27
+ });
28
+ module.exports = __toCommonJS(provider_exports);
29
+ var import_react3 = require("react");
30
+ var import_react_query2 = require("@tanstack/react-query");
31
+ var import_emporix_sdk2 = require("@viu/emporix-sdk");
9
32
 
10
33
  // src/storage/index.ts
11
34
  function createListenerSet() {
@@ -81,14 +104,23 @@ function createMemoryStorage(opts = {}) {
81
104
  subscribeAll: (l) => all.add(l)
82
105
  };
83
106
  }
84
- var EmporixTelemetryContext = react.createContext(null);
107
+
108
+ // src/telemetry.ts
109
+ var import_react = require("react");
110
+ var EmporixTelemetryContext = (0, import_react.createContext)(null);
85
111
  function useEmporixTelemetry() {
86
- const ctx = react.useContext(EmporixTelemetryContext);
112
+ const ctx = (0, import_react.useContext)(EmporixTelemetryContext);
87
113
  if (!ctx) {
88
114
  throw new Error("useEmporixTelemetry must be used within an EmporixProvider");
89
115
  }
90
116
  return ctx;
91
117
  }
118
+
119
+ // src/company-context.tsx
120
+ var import_react2 = require("react");
121
+ var import_react_query = require("@tanstack/react-query");
122
+ var import_emporix_sdk = require("@viu/emporix-sdk");
123
+ var import_jsx_runtime = require("react/jsx-runtime");
92
124
  var NULL_CTX = {
93
125
  activeCompany: null,
94
126
  myCompanies: [],
@@ -101,90 +133,110 @@ var NULL_CTX = {
101
133
  refetchMyCompanies: async () => {
102
134
  }
103
135
  };
104
- var EmporixCompanyContext = react.createContext(NULL_CTX);
136
+ var EmporixCompanyContext = (0, import_react2.createContext)(NULL_CTX);
105
137
  function CompanyContextProvider({
106
138
  client,
107
139
  storage,
108
140
  initialActiveLegalEntityId,
109
141
  children
110
142
  }) {
111
- const qc = reactQuery.useQueryClient();
143
+ const qc = (0, import_react_query.useQueryClient)();
112
144
  const { emit } = useEmporixTelemetry();
113
- const [myCompanies, setMyCompanies] = react.useState([]);
114
- const [activeCompany, setActive] = react.useState(null);
115
- const [status, setStatus] = react.useState("idle");
116
- const [error, setError] = react.useState(null);
117
- const activeRef = react.useRef(null);
118
- activeRef.current = activeCompany;
119
- const switchTo = react.useCallback(
120
- async (target) => {
121
- const start = Date.now();
122
- const from = activeRef.current?.id ?? null;
123
- const refreshToken = storage.getRefreshToken();
124
- const token = storage.getCustomerToken();
125
- if (!refreshToken || !token) {
126
- setActive(target);
127
- storage.setActiveLegalEntityId(target?.id ?? null);
128
- } else {
129
- const next = await client.customers.refresh({
130
- refreshToken,
131
- ...target ? { legalEntityId: target.id } : {}
132
- });
133
- storage.setCustomerToken(next.customerToken);
134
- if (next.refreshToken) storage.setRefreshToken(next.refreshToken);
135
- storage.setCartId(null);
136
- storage.setActiveLegalEntityId(target?.id ?? null);
137
- setActive(target);
138
- qc.invalidateQueries({
139
- predicate: (q) => Array.isArray(q.queryKey) && q.queryKey.some(
140
- (k) => k === "cart" || k === "companies" || k === "customer" || k === from || target !== null && k === target.id
141
- )
145
+ const [myCompanies, setMyCompanies] = (0, import_react2.useState)([]);
146
+ const [activeCompany, setActive] = (0, import_react2.useState)(null);
147
+ const [status, setStatus] = (0, import_react2.useState)("idle");
148
+ const [error, setError] = (0, import_react2.useState)(null);
149
+ const activeRef = (0, import_react2.useRef)(null);
150
+ (0, import_react2.useEffect)(() => {
151
+ activeRef.current = activeCompany;
152
+ }, [activeCompany]);
153
+ const switchChain = (0, import_react2.useRef)(Promise.resolve());
154
+ const switchTo = (0, import_react2.useCallback)(
155
+ (target) => {
156
+ const run = async () => {
157
+ const start = Date.now();
158
+ const from = activeRef.current?.id ?? null;
159
+ const refreshToken = storage.getRefreshToken();
160
+ const token = storage.getCustomerToken();
161
+ if (!refreshToken || !token) {
162
+ setActive(target);
163
+ storage.setActiveLegalEntityId(target?.id ?? null);
164
+ } else {
165
+ const next = await client.customers.refresh({
166
+ refreshToken,
167
+ ...target ? { legalEntityId: target.id } : {}
168
+ });
169
+ storage.setCustomerToken(next.customerToken);
170
+ if (next.refreshToken) storage.setRefreshToken(next.refreshToken);
171
+ storage.setCartId(null);
172
+ storage.setActiveLegalEntityId(target?.id ?? null);
173
+ setActive(target);
174
+ qc.invalidateQueries({
175
+ predicate: (q) => Array.isArray(q.queryKey) && q.queryKey.some(
176
+ (k) => k === "cart" || k === "companies" || k === "customer" || k === from || target !== null && k === target.id
177
+ )
178
+ });
179
+ }
180
+ emit({
181
+ type: "company:switched",
182
+ from,
183
+ to: target?.id ?? null,
184
+ durationMs: Date.now() - start
142
185
  });
143
- }
144
- emit({
145
- type: "company:switched",
146
- from,
147
- to: target?.id ?? null,
148
- durationMs: Date.now() - start
186
+ };
187
+ const task = switchChain.current.then(run, run);
188
+ switchChain.current = task.catch(() => {
149
189
  });
190
+ return task;
150
191
  },
151
192
  [client, storage, qc, emit]
152
193
  );
153
- const load = react.useCallback(async () => {
154
- const token = storage.getCustomerToken();
155
- if (!token) {
156
- setMyCompanies([]);
157
- setActive(null);
158
- setStatus("idle");
159
- return;
160
- }
161
- setStatus("loading");
162
- try {
163
- const companies = await client.companies.listMine(emporixSdk.auth.customer(token));
164
- setMyCompanies(companies);
165
- const persisted = initialActiveLegalEntityId ?? storage.getActiveLegalEntityId();
166
- const matched = persisted ? companies.find((c) => c.id === persisted) ?? null : null;
167
- if (matched) {
168
- setActive(matched);
169
- if (storage.getActiveLegalEntityId() !== matched.id) {
170
- storage.setActiveLegalEntityId(matched.id ?? null);
171
- }
172
- } else if (companies.length === 1) {
173
- await switchTo(companies[0] ?? null);
174
- } else {
194
+ const load = (0, import_react2.useCallback)(
195
+ async (signal) => {
196
+ const token = storage.getCustomerToken();
197
+ if (!token) {
198
+ if (signal?.cancelled) return;
199
+ setMyCompanies([]);
175
200
  setActive(null);
176
- if (persisted && !matched) storage.setActiveLegalEntityId(null);
201
+ setStatus("idle");
202
+ return;
177
203
  }
178
- setStatus("idle");
179
- } catch (e) {
180
- setError(e);
181
- setStatus("error");
182
- }
183
- }, [client, storage, initialActiveLegalEntityId, switchTo]);
184
- react.useEffect(() => {
185
- void load();
204
+ setStatus("loading");
205
+ try {
206
+ const companies = await client.companies.listMine(import_emporix_sdk.auth.customer(token));
207
+ if (signal?.cancelled) return;
208
+ setMyCompanies(companies);
209
+ const persisted = initialActiveLegalEntityId ?? storage.getActiveLegalEntityId();
210
+ const matched = persisted ? companies.find((c) => c.id === persisted) ?? null : null;
211
+ if (matched) {
212
+ setActive(matched);
213
+ if (storage.getActiveLegalEntityId() !== matched.id) {
214
+ storage.setActiveLegalEntityId(matched.id ?? null);
215
+ }
216
+ } else if (companies.length === 1) {
217
+ await switchTo(companies[0] ?? null);
218
+ } else {
219
+ setActive(null);
220
+ if (persisted && !matched) storage.setActiveLegalEntityId(null);
221
+ }
222
+ if (signal?.cancelled) return;
223
+ setStatus("idle");
224
+ } catch (e) {
225
+ if (signal?.cancelled) return;
226
+ setError(e);
227
+ setStatus("error");
228
+ }
229
+ },
230
+ [client, storage, initialActiveLegalEntityId, switchTo]
231
+ );
232
+ (0, import_react2.useEffect)(() => {
233
+ const signal = { cancelled: false };
234
+ void load(signal);
235
+ return () => {
236
+ signal.cancelled = true;
237
+ };
186
238
  }, [load]);
187
- react.useEffect(() => {
239
+ (0, import_react2.useEffect)(() => {
188
240
  let prev = storage.getCustomerToken();
189
241
  return storage.subscribe?.((next) => {
190
242
  const becameAuth = !prev && next;
@@ -193,7 +245,7 @@ function CompanyContextProvider({
193
245
  if (becameAuth || becameUnauth) void load();
194
246
  });
195
247
  }, [storage, load]);
196
- const setActiveCompany = react.useCallback(
248
+ const setActiveCompany = (0, import_react2.useCallback)(
197
249
  async (legalEntityId) => {
198
250
  setStatus("switching");
199
251
  try {
@@ -213,7 +265,7 @@ function CompanyContextProvider({
213
265
  },
214
266
  [myCompanies, switchTo]
215
267
  );
216
- const value = react.useMemo(() => {
268
+ const value = (0, import_react2.useMemo)(() => {
217
269
  const mode = activeCompany ? "b2b" : myCompanies.length > 1 ? "unresolved" : "b2c";
218
270
  return {
219
271
  activeCompany,
@@ -225,10 +277,13 @@ function CompanyContextProvider({
225
277
  refetchMyCompanies: load
226
278
  };
227
279
  }, [activeCompany, myCompanies, status, error, setActiveCompany, load]);
228
- return /* @__PURE__ */ jsxRuntime.jsx(EmporixCompanyContext.Provider, { value, children });
280
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EmporixCompanyContext.Provider, { value, children });
229
281
  }
230
- var EmporixContext = react.createContext(null);
231
- var EmporixSiteContext = react.createContext(null);
282
+
283
+ // src/provider.tsx
284
+ var import_jsx_runtime2 = require("react/jsx-runtime");
285
+ var EmporixContext = (0, import_react3.createContext)(null);
286
+ var EmporixSiteContext = (0, import_react3.createContext)(null);
232
287
  var DEFAULT_QUERY_OPTIONS = {
233
288
  staleTime: 3e4,
234
289
  refetchOnWindowFocus: false,
@@ -247,27 +302,35 @@ function EmporixProvider({
247
302
  onCustomerSessionExpired,
248
303
  children
249
304
  }) {
250
- const value = react.useMemo(() => {
305
+ const value = (0, import_react3.useMemo)(() => {
251
306
  const s = storage ?? createMemoryStorage(
252
307
  initialCustomerToken !== void 0 ? { initial: initialCustomerToken } : {}
253
308
  );
254
- if (initialCustomerToken && storage && storage.getCustomerToken() === null) {
255
- storage.setCustomerToken(initialCustomerToken);
256
- }
257
309
  return { client, storage: s };
258
310
  }, [client, storage, initialCustomerToken]);
259
- const qc = react.useMemo(
260
- () => queryClient ?? new reactQuery.QueryClient({ defaultOptions: { queries: DEFAULT_QUERY_OPTIONS } }),
261
- [queryClient]
262
- );
263
- react.useState(() => {
311
+ const [fallbackQc] = (0, import_react3.useState)(() => new import_react_query2.QueryClient());
312
+ const qc = queryClient ?? fallbackQc;
313
+ const defaultsRef = (0, import_react3.useRef)(null);
314
+ if (defaultsRef.current !== qc) {
315
+ qc.setQueryDefaults(["emporix"], {
316
+ ...DEFAULT_QUERY_OPTIONS,
317
+ ...qc.getDefaultOptions().queries,
318
+ ...qc.getQueryDefaults(["emporix"])
319
+ });
320
+ defaultsRef.current = qc;
321
+ }
322
+ const wiredRef = (0, import_react3.useRef)(null);
323
+ if (wiredRef.current?.client !== client || wiredRef.current?.storage !== value.storage) {
264
324
  client.tokenProvider.attachAnonymousStore?.({
265
325
  read: () => value.storage.getAnonymousSession(),
266
326
  write: (s) => value.storage.setAnonymousSession(s)
267
327
  });
268
- return null;
269
- });
270
- const safeEmit = react.useCallback(
328
+ if (initialCustomerToken && storage && storage.getCustomerToken() === null) {
329
+ storage.setCustomerToken(initialCustomerToken);
330
+ }
331
+ wiredRef.current = { client, storage: value.storage };
332
+ }
333
+ const safeEmit = (0, import_react3.useCallback)(
271
334
  (event) => {
272
335
  if (!onTelemetry) return;
273
336
  try {
@@ -278,8 +341,8 @@ function EmporixProvider({
278
341
  },
279
342
  [onTelemetry]
280
343
  );
281
- const telemetryValue = react.useMemo(() => ({ emit: safeEmit }), [safeEmit]);
282
- react.useEffect(() => {
344
+ const telemetryValue = (0, import_react3.useMemo)(() => ({ emit: safeEmit }), [safeEmit]);
345
+ (0, import_react3.useEffect)(() => {
283
346
  if (!onTelemetry) return;
284
347
  const startedAt = /* @__PURE__ */ new Map();
285
348
  const unsubQuery = qc.getQueryCache().subscribe((event) => {
@@ -358,7 +421,7 @@ function EmporixProvider({
358
421
  unsubStorage?.();
359
422
  };
360
423
  }, [qc, onTelemetry, client, value.storage, safeEmit]);
361
- react.useEffect(() => {
424
+ (0, import_react3.useEffect)(() => {
362
425
  if (!autoRefreshCustomerToken) return;
363
426
  const storage2 = value.storage;
364
427
  client.setCustomerTokenRefresher({
@@ -388,14 +451,14 @@ function EmporixProvider({
388
451
  });
389
452
  return () => client.setCustomerTokenRefresher(null);
390
453
  }, [autoRefreshCustomerToken, client, value.storage, safeEmit, onCustomerSessionExpired]);
391
- return /* @__PURE__ */ jsxRuntime.jsx(EmporixContext.Provider, { value, children: /* @__PURE__ */ jsxRuntime.jsx(EmporixTelemetryContext.Provider, { value: telemetryValue, children: /* @__PURE__ */ jsxRuntime.jsx(reactQuery.QueryClientProvider, { client: qc, children: /* @__PURE__ */ jsxRuntime.jsx(
454
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(EmporixContext.Provider, { value, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(EmporixTelemetryContext.Provider, { value: telemetryValue, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_query2.QueryClientProvider, { client: qc, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
392
455
  SiteContextProvider,
393
456
  {
394
457
  client,
395
458
  storage: value.storage,
396
459
  ...initialSiteCode !== void 0 ? { initialSiteCode } : {},
397
460
  ...initialLanguage !== void 0 ? { initialLanguage } : {},
398
- children: /* @__PURE__ */ jsxRuntime.jsx(
461
+ children: /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
399
462
  CompanyContextProvider,
400
463
  {
401
464
  client,
@@ -414,30 +477,30 @@ function SiteContextProvider({
414
477
  initialLanguage,
415
478
  children
416
479
  }) {
417
- const qc = reactQuery.useQueryClient();
418
- const [siteCode, setSiteCodeState] = react.useState(() => {
480
+ const qc = (0, import_react_query2.useQueryClient)();
481
+ const [siteCode, setSiteCodeState] = (0, import_react3.useState)(() => {
419
482
  if (initialSiteCode !== void 0) return initialSiteCode;
420
483
  const fromStorage = storage.getSiteCode();
421
484
  if (fromStorage !== null) return fromStorage;
422
485
  return client.config?.credentials?.storefront?.context?.siteCode ?? null;
423
486
  });
424
- const [currency, setCurrencyState] = react.useState(
487
+ const [currency, setCurrencyState] = (0, import_react3.useState)(
425
488
  () => client.config?.credentials?.storefront?.context?.currency ?? null
426
489
  );
427
- const [language, setLanguageState] = react.useState(() => {
490
+ const [language, setLanguageState] = (0, import_react3.useState)(() => {
428
491
  if (initialLanguage !== void 0) return initialLanguage;
429
492
  const fromStorage = storage.getLanguage();
430
493
  if (fromStorage !== null) return fromStorage;
431
494
  return client.config?.credentials?.storefront?.context?.language ?? null;
432
495
  });
433
- const [targetLocation, setTargetLocation] = react.useState(null);
434
- const [isSwitching, setIsSwitching] = react.useState(false);
435
- const [switchError, setSwitchError] = react.useState(null);
436
- react.useEffect(() => {
496
+ const [targetLocation, setTargetLocation] = (0, import_react3.useState)(null);
497
+ const [isSwitching, setIsSwitching] = (0, import_react3.useState)(false);
498
+ const [switchError, setSwitchError] = (0, import_react3.useState)(null);
499
+ (0, import_react3.useEffect)(() => {
437
500
  if (!siteCode || currency !== null && targetLocation !== null && language !== null) return;
438
501
  let cancelled = false;
439
502
  const token = storage.getCustomerToken();
440
- const authCtx = token ? emporixSdk.auth.customer(token) : emporixSdk.auth.anonymous();
503
+ const authCtx = token ? import_emporix_sdk2.auth.customer(token) : import_emporix_sdk2.auth.anonymous();
441
504
  qc.fetchQuery({
442
505
  queryKey: [
443
506
  "emporix",
@@ -461,10 +524,10 @@ function SiteContextProvider({
461
524
  cancelled = true;
462
525
  };
463
526
  }, [siteCode]);
464
- react.useEffect(() => {
527
+ (0, import_react3.useEffect)(() => {
465
528
  if (language) client.setStorefrontContext({ language });
466
529
  }, []);
467
- const setSite = react.useCallback(
530
+ const setSite = (0, import_react3.useCallback)(
468
531
  async (code) => {
469
532
  storage.setSiteCode(code);
470
533
  storage.setCartId(null);
@@ -479,7 +542,7 @@ function SiteContextProvider({
479
542
  setIsSwitching(true);
480
543
  try {
481
544
  const token = storage.getCustomerToken();
482
- const authCtx = token ? emporixSdk.auth.customer(token) : emporixSdk.auth.anonymous();
545
+ const authCtx = token ? import_emporix_sdk2.auth.customer(token) : import_emporix_sdk2.auth.anonymous();
483
546
  const site = await qc.fetchQuery({
484
547
  queryKey: [
485
548
  "emporix",
@@ -514,7 +577,7 @@ function SiteContextProvider({
514
577
  },
515
578
  [client, storage, qc, language]
516
579
  );
517
- const setCurrency = react.useCallback(
580
+ const setCurrency = (0, import_react3.useCallback)(
518
581
  async (next) => {
519
582
  storage.setCartId(null);
520
583
  setCurrencyState(next);
@@ -524,7 +587,7 @@ function SiteContextProvider({
524
587
  setIsSwitching(true);
525
588
  try {
526
589
  const token = storage.getCustomerToken();
527
- const authCtx = token ? emporixSdk.auth.customer(token) : emporixSdk.auth.anonymous();
590
+ const authCtx = token ? import_emporix_sdk2.auth.customer(token) : import_emporix_sdk2.auth.anonymous();
528
591
  await client.sessionContext.patch(
529
592
  { currency: next, ...siteCode ? { siteCode } : {} },
530
593
  authCtx
@@ -537,7 +600,7 @@ function SiteContextProvider({
537
600
  },
538
601
  [client, storage, qc, siteCode]
539
602
  );
540
- const setLanguage = react.useCallback(
603
+ const setLanguage = (0, import_react3.useCallback)(
541
604
  async (next) => {
542
605
  storage.setLanguage(next);
543
606
  setLanguageState(next);
@@ -547,7 +610,7 @@ function SiteContextProvider({
547
610
  setIsSwitching(true);
548
611
  try {
549
612
  const token = storage.getCustomerToken();
550
- const authCtx = token ? emporixSdk.auth.customer(token) : emporixSdk.auth.anonymous();
613
+ const authCtx = token ? import_emporix_sdk2.auth.customer(token) : import_emporix_sdk2.auth.anonymous();
551
614
  await client.sessionContext.patch(
552
615
  { language: next, ...siteCode ? { siteCode } : {} },
553
616
  authCtx
@@ -560,7 +623,7 @@ function SiteContextProvider({
560
623
  },
561
624
  [client, storage, qc, siteCode]
562
625
  );
563
- const value = react.useMemo(
626
+ const value = (0, import_react3.useMemo)(
564
627
  () => ({
565
628
  siteCode,
566
629
  currency,
@@ -574,16 +637,17 @@ function SiteContextProvider({
574
637
  }),
575
638
  [siteCode, currency, targetLocation, language, setSite, setCurrency, setLanguage, isSwitching, switchError]
576
639
  );
577
- return /* @__PURE__ */ jsxRuntime.jsx(EmporixSiteContext.Provider, { value, children });
640
+ return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(EmporixSiteContext.Provider, { value, children });
578
641
  }
579
642
  function useEmporix() {
580
- const ctx = react.useContext(EmporixContext);
643
+ const ctx = (0, import_react3.useContext)(EmporixContext);
581
644
  if (!ctx) throw new Error("useEmporix must be used within an EmporixProvider");
582
645
  return ctx;
583
646
  }
584
-
585
- exports.EmporixProvider = EmporixProvider;
586
- exports.EmporixSiteContext = EmporixSiteContext;
587
- exports.useEmporix = useEmporix;
588
- //# sourceMappingURL=provider.cjs.map
647
+ // Annotate the CommonJS export names for ESM import in node:
648
+ 0 && (module.exports = {
649
+ EmporixProvider,
650
+ EmporixSiteContext,
651
+ useEmporix
652
+ });
589
653
  //# sourceMappingURL=provider.cjs.map