@konfiqo/storefront-react 0.6.0 → 0.7.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/README.md CHANGED
@@ -11,7 +11,7 @@ the payment form and the checkout challenge.
11
11
  "build your own storefront" guide.
12
12
  - No styling: components render a plain `<div>` you can give a `className`.
13
13
  - No runtime dependencies. Peer dependencies: `@konfiqo/storefront-sdk`
14
- `^0.6.0` and `react` ≥ 18. Install the SDK yourself, so your code and this
14
+ `^0.7.0` and `react` ≥ 18. Install the SDK yourself, so your code and this
15
15
  package share one copy (`isStorefrontError` also recognises errors from a
16
16
  second copy, but one copy keeps the bundle small).
17
17
  - Server-rendering safe: nothing touches `window`, `document` or storage
@@ -61,7 +61,7 @@ read, and a stale answer never replaces a newer one.
61
61
 
62
62
  | Hook | SDK call | Notes |
63
63
  | --------------------- | ----------------------- | ---------------------------------------------------------------------------------------------- |
64
- | `useStore()` | `store.get()` | Currency, theme, legal texts, `checkoutChallenge`. |
64
+ | `useStore()` | `store.get()` | Currency, theme, `company`, `checkoutChallenge`. |
65
65
  | `useCategories()` | `categories.list()` | The category tree. |
66
66
  | `useProducts(params)` | `products.list(params)` | `{ category?, q?, page?, pageSize? }`. Reads again when a value changes (not on a new object). |
67
67
  | `useProduct(slug)` | `products.get(slug)` | `null` / empty slug: reads nothing. Unknown slug: `error.code === 'product_not_found'`. |
@@ -80,15 +80,31 @@ In the Next.js App Router, prefer reading the catalog **on the server**
80
80
  with the SDK directly (cacheable, no `Origin`); the hooks are for client
81
81
  components.
82
82
 
83
+ ## Blog
84
+
85
+ Read posts with `client.blog.list()` and `client.blog.get(slug)` on the
86
+ server, and render the body with `renderContent`. The `tree` of a post is
87
+ the same tree that `<Content>` renders.
88
+
89
+ ```tsx
90
+ import { renderContent } from '@konfiqo/storefront-react';
91
+
92
+ const post = await client.blog.get(slug);
93
+ return <article>{renderContent(post.tree)}</article>;
94
+ ```
95
+
96
+ `renderContent` needs a `<StorefrontProvider>` for the default components
97
+ (`ProductGrid`, `Image` and others).
98
+
83
99
  ## `useCart()`
84
100
 
85
101
  ```tsx
86
102
  const {
87
- cart, // Cart | null — the server's view; null until the buyer has one
103
+ cart, // Cart | null. The server's view; null until the buyer has one
88
104
  status, // 'idle' (before the first read, and on the server) | 'loading' | 'ready'
89
105
  isUpdating, // a write is in progress
90
106
  error, // the last read / write error, or null
91
- previousCartId, // string | null — an ordered cart a write moved away from (see below)
107
+ previousCartId, // string | null. An ordered cart a write moved away from (see below)
92
108
  itemCount, // total units (for a badge)
93
109
  addLine, // ({ variantId, quantity, personalization? }) => Promise<Cart>
94
110
  updateLine, // (lineId, { quantity }) => Promise<Cart>, lineId = cart line `id`
@@ -97,8 +113,8 @@ const {
97
113
  setAddress, // ({ shipping, billing? }) => Promise<Cart>
98
114
  setShippingOption, // (optionId) => Promise<Cart>
99
115
  shippingOptions, // (options?) => Promise<ShippingOptionList>, { items: [] } without a cart
100
- refresh, // () => Promise<void> — read the cart again
101
- reset, // () => void — forget the cart (e.g. after its order is paid)
116
+ refresh, // () => Promise<void>. Reads the cart again
117
+ reset, // () => void. Forgets the cart (e.g. after its order is paid)
102
118
  } = useCart();
103
119
  ```
104
120
 
@@ -144,7 +160,7 @@ const {
144
160
 
145
161
  ## Cart storage
146
162
 
147
- - **`defaultCartStorage()`** — the provider's default storage (null on a
163
+ - **`defaultCartStorage()`** is the provider's default storage (null on a
148
164
  server). `getItem` reads the `__Host-konfiqo_cart` cookie first and
149
165
  rewrites it on every read, renewing its expiry; when the cookie is gone
150
166
  (Safari keeps script-written cookies 7 days) it reads `localStorage` and
@@ -152,7 +168,7 @@ const {
152
168
  clears both and writes a `storefront:cart:<storeId>:cleared` tombstone in
153
169
  `localStorage`; while it is there no frontend on the store origin restores
154
170
  the old id from `localStorage`. The next `setItem` removes it.
155
- - **`useCartStorage()`** — a getter for the storage this provider uses
171
+ - **`useCartStorage()`** is a getter for the storage this provider uses
156
172
  (call it in an effect or handler, never during render). Use it to save a
157
173
  cart id learned out of band (`saveCartId(getStorage(), storeId, id)`) or
158
174
  to clear one (`clearCartId(getStorage(), storeId)`).
@@ -165,10 +181,15 @@ const {
165
181
  ```tsx
166
182
  const { checkout, isPending, result, error, attempts, reset } = useCheckout();
167
183
 
168
- const result = await checkout({ turnstileToken }); // CheckoutResult
184
+ const result = await checkout({ agreementsHash, turnstileToken }); // CheckoutResult
169
185
  ```
170
186
 
171
- - Calls `carts.checkout(cartId, { turnstileToken })` for the provider's cart.
187
+ - Calls `carts.checkout(cartId, { agreementsHash, turnstileToken })` for the
188
+ provider's cart. `agreementsHash` is required: load the agreements with
189
+ `client.carts.agreements(cartId)`, show them, and pass the hash. On
190
+ `agreements_changed`, load them again, show the new texts and call
191
+ `checkout()` with the new hash (see "Legal texts and agreements" in the
192
+ SDK README).
172
193
  Without a cart it rejects with `checkout_incomplete`
173
194
  (`details.missing: ['lines']`) without a request. A second call while one
174
195
  is in flight returns the same promise.
@@ -192,6 +213,8 @@ const result = await checkout({ turnstileToken }); // CheckoutResult
192
213
  break;
193
214
  case 'out_of_stock': // error.details.variantIds
194
215
  case 'checkout_incomplete': // error.details.missing
216
+ case 'agreements_changed': // load the agreements again, show them
217
+ case 'legal_not_confirmed': // the store takes no orders yet
195
218
  case 'invalid_buyer_details': // error.details.field
196
219
  case 'checkout_in_progress':
197
220
  case 'challenge_required':
@@ -219,8 +242,8 @@ const result = await checkout({ turnstileToken }); // CheckoutResult
219
242
  ```
220
243
 
221
244
  Presents payment with the SDK's `mountPayment`: the provider's embedded
222
- form inside the `<div>` (its scripts run once — also under React Strict
223
- Mode, which mounts effects twice), a top-level redirect (`redirect`), or
245
+ form inside the `<div>` (its scripts run once, including under React
246
+ Strict Mode, which mounts effects twice), a top-level redirect (`redirect`), or
224
247
  `onClosed(page)` (`closed`: `paid`, `cancelled`, `processing`, …). The form
225
248
  is removed on unmount.
226
249
 
@@ -229,7 +252,7 @@ is removed on unmount.
229
252
  or storage: the embedded content runs as script.
230
253
  - Card data goes from the provider's form to the provider; it never
231
254
  touches your code. Never put a Konfiqo secret (a storefront key, an API
232
- key) in client code — the browser only ever needs the publishable key.
255
+ key) in client code; the browser only ever needs the publishable key.
233
256
 
234
257
  ## `<CheckoutChallenge>`
235
258
 
@@ -239,6 +262,7 @@ Turnstile token:
239
262
  ```tsx
240
263
  const { data: store } = useStore();
241
264
  const [token, setToken] = useState<string | null>(null);
265
+ // agreementsHash: from client.carts.agreements(cartId), accepted by the buyer
242
266
  const { checkout } = useCheckout();
243
267
 
244
268
  <CheckoutChallenge
@@ -249,7 +273,7 @@ const { checkout } = useCheckout();
249
273
  />
250
274
  <button
251
275
  disabled={!!store?.checkoutChallenge && !token}
252
- onClick={() => checkout({ turnstileToken: token })}
276
+ onClick={() => checkout({ agreementsHash, turnstileToken: token })}
253
277
  >
254
278
  {t('checkout.pay')}
255
279
  </button>
@@ -290,12 +314,12 @@ const { order, error, isLoading, isPolling, refetch } = useOrder(id, token, {
290
314
 
291
315
  - Reads `orders.get(orderId, token)`. Missing `orderId` or `token`: reads
292
316
  nothing.
293
- - `pollUntilFinal`: reads again with backoff — 2 s, 4 s, 8 s, then every
294
- 15 s — until the order is settled (`isOrderSettled`): any status past
317
+ - `pollUntilFinal`: reads again with a growing delay (2 s, 4 s, 8 s, then every
318
+ 15 s) until the order is settled (`isOrderSettled`): any status past
295
319
  `pendingPayment` (`paid`, `fulfilling`, `shipped`, `delivered`,
296
320
  `cancelled`, `refunded`, …), or a pending order whose payment `failed` /
297
321
  `expired` (the buyer checks out again). Transient errors
298
- (`network_error`, `timeout`, `rate_limited` — honouring `retryAfter` —,
322
+ (`network_error`, `timeout`, `rate_limited` (honouring `retryAfter`),
299
323
  `order_unavailable`, `http_error`) keep polling and keep the last
300
324
  `order`; other errors (`order_not_found`) stop it. Unmounting stops
301
325
  polling and aborts the read.
@@ -380,7 +404,12 @@ export function Tracking({
380
404
  variant id). Ids follow the product feed rows: pass `variantId` as soon
381
405
  as a variant is chosen; before that, `view_item` names the product as a
382
406
  `product_group`. Prices are in minor units, in the `currency` given to
383
- `AdPixelsLoader` (ISO 4217, default `'TRY'`).
407
+ `AdPixelsLoader` (ISO 4217, default `'TRY'`). Events fired before the
408
+ shopper's choice is read (for example from a mount effect during
409
+ hydration) are held, up to 20. They are copied when held, so later
410
+ changes to the object you passed do not alter them. The first
411
+ configuration sends them if it carries a `marketing` grant; otherwise
412
+ they are dropped, and a later grant does not send them.
384
413
  - **Which pixels and cookies a host may use.** On a default store domain,
385
414
  filter with the SDK's `onDefaultDomain`, `pixelsForHost` and
386
415
  `cookiesForHost`. They are server-safe, so call them in server
@@ -398,6 +427,15 @@ export function Tracking({
398
427
  change: pixel scripts already loaded on the previous page read the full
399
428
  URL (GA4 history page views, Meta automatic events) and would send the
400
429
  secret.
430
+ - **Hardening for pixels loaded on an earlier page.** Meta is loaded with
431
+ `fbq('set', 'autoConfig', false, pixelId)` before `fbq('init', pixelId)`,
432
+ so Meta sends no automatic button-click or page-metadata events. Every
433
+ Google `config` call and every Google event the SDK sends carries an
434
+ explicit `page_location` that is the current page URL with the `token`
435
+ query parameter removed, and with the whole query string and fragment
436
+ removed on the secret pages above. Each event reads the URL again, so it
437
+ is right after a client-side route change. `scrubbedLocation()` returns
438
+ that URL.
401
439
  - **Tests.** `resetAnalytics()` and `resetPixels()` forget the module
402
440
  state between tests. They are for tests only; do not call them in
403
441
  production code.
package/dist/index.cjs CHANGED
@@ -53,6 +53,7 @@ __export(index_exports, {
53
53
  renderContent: () => renderContent,
54
54
  resetAnalytics: () => resetAnalytics,
55
55
  resetPixels: () => resetPixels,
56
+ scrubbedLocation: () => scrubbedLocation,
56
57
  track: () => track,
57
58
  useAccount: () => useAccount,
58
59
  useCart: () => useCart,
@@ -345,7 +346,7 @@ var CartStore = class {
345
346
  * anyway); a second call while one is in flight returns the same
346
347
  * promise. The cart is read again afterwards.
347
348
  */
348
- checkout = (options = {}) => {
349
+ checkout = (options) => {
349
350
  if (this.pendingCheckout) return this.pendingCheckout;
350
351
  this.checkoutStarted = true;
351
352
  this.setCheckout({ isPending: true, error: null });
@@ -362,6 +363,7 @@ var CartStore = class {
362
363
  );
363
364
  }
364
365
  return this.client.carts.checkout(id, {
366
+ agreementsHash: options.agreementsHash,
365
367
  turnstileToken: options.turnstileToken || void 0
366
368
  });
367
369
  });
@@ -725,7 +727,10 @@ function useCheckout() {
725
727
  if (store.checkoutStarted) void store.refresh();
726
728
  }, [store]);
727
729
  const checkout = (0, import_react5.useCallback)(
728
- (options = {}) => store.checkout({ turnstileToken: options.turnstileToken ?? void 0 }),
730
+ (options) => store.checkout({
731
+ agreementsHash: options.agreementsHash,
732
+ turnstileToken: options.turnstileToken ?? void 0
733
+ }),
729
734
  [store]
730
735
  );
731
736
  return { ...snapshot, checkout, reset: store.clearCheckout };
@@ -1241,7 +1246,9 @@ function ConsentProvider({
1241
1246
  const [decidedVersion, setDecidedVersion] = (0, import_react10.useState)(null);
1242
1247
  const opener = (0, import_react10.useRef)(null);
1243
1248
  const onDecisionRef = (0, import_react10.useRef)(onDecision);
1244
- onDecisionRef.current = onDecision;
1249
+ (0, import_react10.useInsertionEffect)(() => {
1250
+ onDecisionRef.current = onDecision;
1251
+ });
1245
1252
  const categories = (0, import_react10.useMemo)(
1246
1253
  () => OPTIONAL_CATEGORIES.filter((c) => cookies.some((k) => k.category === c)),
1247
1254
  [cookies]
@@ -1474,12 +1481,17 @@ var pixels;
1474
1481
  var currency = DEFAULT_CURRENCY;
1475
1482
  var granted = false;
1476
1483
  var loaded = /* @__PURE__ */ new Set();
1484
+ var configured = false;
1485
+ var MAX_EARLY = 20;
1486
+ var early = [];
1477
1487
  function resetPixels() {
1478
1488
  pixels = void 0;
1479
1489
  currency = DEFAULT_CURRENCY;
1480
1490
  granted = false;
1481
1491
  optedOut = false;
1482
1492
  loaded.clear();
1493
+ configured = false;
1494
+ early.length = 0;
1483
1495
  }
1484
1496
  var major = (minor) => minor / 100;
1485
1497
  function addScript(src) {
@@ -1507,6 +1519,7 @@ function loadMeta(id) {
1507
1519
  }
1508
1520
  w.fbq.disablePushState = true;
1509
1521
  addScript("https://connect.facebook.net/en_US/fbevents.js");
1522
+ w.fbq("set", "autoConfig", false, id);
1510
1523
  w.fbq("init", id);
1511
1524
  }
1512
1525
  var TT_METHODS = [
@@ -1575,13 +1588,24 @@ function loadGoogle(g) {
1575
1588
  for (const id of ids) {
1576
1589
  w.gtag("config", id, {
1577
1590
  send_page_view: false,
1578
- cookie_domain: cookieDomain
1591
+ cookie_domain: cookieDomain,
1592
+ page_location: scrubbedLocation()
1579
1593
  });
1580
1594
  }
1581
1595
  }
1582
1596
  function onSecretPage(path = typeof location === "undefined" ? "" : location.pathname) {
1583
1597
  return path.startsWith("/orders/") || path.startsWith("/cart/recover");
1584
1598
  }
1599
+ function scrubbedLocation() {
1600
+ const url = new URL(location.href);
1601
+ if (onSecretPage(url.pathname)) {
1602
+ url.search = "";
1603
+ url.hash = "";
1604
+ } else {
1605
+ url.searchParams.delete("token");
1606
+ }
1607
+ return url.toString();
1608
+ }
1585
1609
  function loadAll(p) {
1586
1610
  if (p.meta && !loaded.has("meta")) {
1587
1611
  loaded.add("meta");
@@ -1699,6 +1723,8 @@ function optIn(p) {
1699
1723
  }
1700
1724
  }
1701
1725
  function configurePixels(next, isGranted, opts = {}) {
1726
+ const held = configured ? [] : early.splice(0);
1727
+ configured = true;
1702
1728
  try {
1703
1729
  pixels = next;
1704
1730
  currency = opts.currency ?? DEFAULT_CURRENCY;
@@ -1715,6 +1741,7 @@ function configurePixels(next, isGranted, opts = {}) {
1715
1741
  writeMarker(false);
1716
1742
  }
1717
1743
  }
1744
+ for (const e of held) send2(e);
1718
1745
  } catch {
1719
1746
  }
1720
1747
  }
@@ -1731,7 +1758,23 @@ function markPurchased(orderId) {
1731
1758
  } catch {
1732
1759
  }
1733
1760
  }
1761
+ function copyEvent(e) {
1762
+ try {
1763
+ return structuredClone(e);
1764
+ } catch {
1765
+ return { ...e };
1766
+ }
1767
+ }
1734
1768
  function firePixel(e) {
1769
+ if (!configured) {
1770
+ if (typeof window === "undefined" || onSecretPage()) return;
1771
+ early.push(copyEvent(e));
1772
+ if (early.length > MAX_EARLY) early.shift();
1773
+ return;
1774
+ }
1775
+ send2(e);
1776
+ }
1777
+ function send2(e) {
1735
1778
  try {
1736
1779
  if (!granted || !pixels || onSecretPage()) return;
1737
1780
  loadAll(pixels);
@@ -1846,7 +1889,9 @@ function tiktok(ttq, e) {
1846
1889
  );
1847
1890
  }
1848
1891
  }
1849
- function google(gtag, g, e) {
1892
+ function google(rawGtag, g, e) {
1893
+ const page_location = scrubbedLocation();
1894
+ const gtag = (command, name, params) => rawGtag(command, name, { ...params, page_location });
1850
1895
  const item = (id, quantity, priceMinor) => ({
1851
1896
  item_id: id,
1852
1897
  quantity,
@@ -1937,6 +1982,7 @@ function AdPixelsLoader({
1937
1982
  renderContent,
1938
1983
  resetAnalytics,
1939
1984
  resetPixels,
1985
+ scrubbedLocation,
1940
1986
  track,
1941
1987
  useAccount,
1942
1988
  useCart,