@konfiqo/storefront-react 0.0.0-stage → 0.5.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Konfiqo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,347 @@
1
- # Temporary Holding Version
1
+ # @konfiqo/storefront-react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ React hooks and components for
4
+ [`@konfiqo/storefront-sdk`](https://www.npmjs.com/package/@konfiqo/storefront-sdk)
5
+ ([source](https://github.com/Konfiqo/storefront-sdk/tree/main/packages/sdk)): a provider, read hooks for
6
+ the catalog, a shared cart with its writes, checkout, buyer order status,
7
+ the payment form and the checkout challenge.
8
+
9
+ - A thin layer over the SDK: every request is an SDK call, every error a
10
+ `StorefrontError`. Read the SDK README for the API, error codes and the
11
+ "build your own storefront" guide.
12
+ - No styling: components render a plain `<div>` you can give a `className`.
13
+ - No runtime dependencies. Peer dependencies: `@konfiqo/storefront-sdk`
14
+ `^0.5.0` and `react` ≥ 18. Install the SDK yourself, so your code and this
15
+ package share one copy (`isStorefrontError` also recognises errors from a
16
+ second copy, but one copy keeps the bundle small).
17
+ - Server-rendering safe: nothing touches `window`, `document` or storage
18
+ during render; requests start in effects.
19
+
20
+ ```bash
21
+ npm install @konfiqo/storefront-react @konfiqo/storefront-sdk
22
+ ```
23
+
24
+ ## Provider
25
+
26
+ ```tsx
27
+ import { StorefrontProvider } from '@konfiqo/storefront-react';
28
+
29
+ <StorefrontProvider
30
+ storeId={storeId}
31
+ config={{
32
+ baseUrl: 'https://commerce.example.com',
33
+ publishableKey: 'pk_live_…',
34
+ }}
35
+ >
36
+ <App />
37
+ </StorefrontProvider>;
38
+ ```
39
+
40
+ | Prop | Type | Description |
41
+ | ------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
42
+ | `storeId` | `string` | Any string stable for this store (e.g. its publishable key, or one the operator gives you). Namespaces the saved cart id (`storefront:cart:<storeId>`). |
43
+ | `config` | `ClientConfig` | The SDK's `StorefrontClientOptions` without `serverKey`, `trustedStorefrontKey` and `buyerIp` (the type is exported by this package). The provider also refuses those three at run time (it throws), because props of a client component reach the browser. Use them only in a server-side SDK client. |
44
+ | `client` | `StorefrontClient` | An existing client, instead of `config`. |
45
+ | `cartStorage` | `CartIdStorage \| null` | Where the cart id is kept. Default `defaultCartStorage()`: the `__Host-konfiqo_cart` cookie backed by `window.localStorage` (read lazily, never during render; see [Cart storage](#cart-storage)). `null`: in memory only. Any `{ getItem, setItem, removeItem }` works. |
46
+
47
+ Everything under one provider shares one cart: a header badge and the cart
48
+ page see the same state. The cart state is keyed by `storeId` only: a new
49
+ client (e.g. a `config.fetch` with a new identity) is picked up for the
50
+ next request without dropping the cart. With the default storage, a cart
51
+ id changed in another tab (`storage` event for this store's key) is
52
+ followed: the cart is read again (or cleared). `useStorefrontClient()`
53
+ returns the client for calls the hooks do not cover (e.g.
54
+ `client.media.url(key)`).
55
+
56
+ ## Catalog hooks
57
+
58
+ Each returns `{ data, error, isLoading, refetch }`. Every read has its own
59
+ `AbortSignal`: changing a parameter or unmounting cancels the previous
60
+ read, and a stale answer never replaces a newer one.
61
+
62
+ | Hook | SDK call | Notes |
63
+ | --------------------- | ----------------------- | ---------------------------------------------------------------------------------------------- |
64
+ | `useStore()` | `store.get()` | Currency, theme, legal texts, `checkoutChallenge`. |
65
+ | `useCategories()` | `categories.list()` | The category tree. |
66
+ | `useProducts(params)` | `products.list(params)` | `{ category?, q?, page?, pageSize? }`. Reads again when a value changes (not on a new object). |
67
+ | `useProduct(slug)` | `products.get(slug)` | `null` / empty slug: reads nothing. Unknown slug: `error.code === 'product_not_found'`. |
68
+
69
+ ```tsx
70
+ function Category({ slug }: { slug: string }) {
71
+ const [page, setPage] = useState(1);
72
+ const { data, error, isLoading } = useProducts({ category: slug, page });
73
+ if (error) return <p>{t('errors.catalog')}</p>;
74
+ if (isLoading || !data) return <Spinner />;
75
+ return <Grid products={data.items} />;
76
+ }
77
+ ```
78
+
79
+ In the Next.js App Router, prefer reading the catalog **on the server**
80
+ with the SDK directly (cacheable, no `Origin`); the hooks are for client
81
+ components.
82
+
83
+ ## `useCart()`
84
+
85
+ ```tsx
86
+ const {
87
+ cart, // Cart | null — the server's view; null until the buyer has one
88
+ status, // 'idle' (before the first read, and on the server) | 'loading' | 'ready'
89
+ isUpdating, // a write is in progress
90
+ error, // the last read / write error, or null
91
+ previousCartId, // string | null — an ordered cart a write moved away from (see below)
92
+ itemCount, // total units (for a badge)
93
+ addLine, // ({ variantId, quantity, personalization? }) => Promise<Cart>
94
+ updateLine, // (lineId, { quantity }) => Promise<Cart>, lineId = cart line `id`
95
+ removeLine, // (lineId) => Promise<Cart>
96
+ setCustomer, // (CustomerInput) => Promise<Cart>
97
+ setAddress, // ({ shipping, billing? }) => Promise<Cart>
98
+ setShippingOption, // (optionId) => Promise<Cart>
99
+ 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)
102
+ } = useCart();
103
+ ```
104
+
105
+ - **Lazy cart.** The saved cart id is read after mount. No cart is created
106
+ until the first write: browsing never makes one. The new id is saved in
107
+ `cartStorage`.
108
+ - **Server view only.** Every write answers the updated cart and replaces
109
+ the state: prices and totals are never computed in the browser. Writes
110
+ run one at a time in call order.
111
+ - **Errors.** A write rejects with the `StorefrontError` (and sets
112
+ `error`); catch it where you call it:
113
+
114
+ ```tsx
115
+ try {
116
+ await addLine({ variantId, quantity: 1 });
117
+ } catch (e) {
118
+ if (isStorefrontError(e) && e.code === 'insufficient_stock')
119
+ showOnlyLeft(e.details.available);
120
+ }
121
+ ```
122
+
123
+ - **Expired or unknown cart.** `cart_not_found`, `cart_read_only` with
124
+ `status: "expired"`, or a cart read as `expired`: the id is cleared and
125
+ `cart` becomes `null`; the next write starts a new cart.
126
+ - **Ordered cart.** A **read** that answers `status: "ordered"` keeps the
127
+ cart: show the order / payment state (its payment may still be open).
128
+ A **write** that gets `cart_read_only` with `status: "ordered"` (the
129
+ buyer keeps shopping after checking out) moves on: the ordered cart's id
130
+ goes to `previousCartId` (offer "continue your payment" for it), a fresh
131
+ cart is created and the write is replayed on it **once**; the promise
132
+ resolves with the fresh cart. Call `reset()` once the order is paid
133
+ (it also clears `previousCartId`).
134
+ - **`reset()`** wins over anything in flight: a read, write or checkout
135
+ that started before it does not bring the old cart (or its checkout
136
+ result) back, and does not save its id again. A write that was still
137
+ creating the cart rejects with `aborted` and is not applied to that cart.
138
+ - **Another tab** changing the cart id drops reads and writes in flight on
139
+ the old cart, but not a checkout in flight: its result (and the
140
+ once-only `token`) is kept.
141
+ - **Failed payment.** Reading a cart whose payment failed reopens it on the
142
+ server: after the buyer comes back, `refresh()` (or a fresh mount) shows
143
+ `status: "open"` again and the buyer can check out again.
144
+
145
+ ## Cart storage
146
+
147
+ - **`defaultCartStorage()`** — the provider's default storage (null on a
148
+ server). `getItem` reads the `__Host-konfiqo_cart` cookie first and
149
+ rewrites it on every read, renewing its expiry; when the cookie is gone
150
+ (Safari keeps script-written cookies 7 days) it reads `localStorage` and
151
+ writes the id back into the cookie. `setItem` writes both. `removeItem`
152
+ clears both and writes a `storefront:cart:<storeId>:cleared` tombstone in
153
+ `localStorage`; while it is there no frontend on the store origin restores
154
+ the old id from `localStorage`. The next `setItem` removes it.
155
+ - **`useCartStorage()`** — a getter for the storage this provider uses
156
+ (call it in an effect or handler, never during render). Use it to save a
157
+ cart id learned out of band (`saveCartId(getStorage(), storeId, id)`) or
158
+ to clear one (`clearCartId(getStorage(), storeId)`).
159
+ - Clear a cart only this way (or with `reset()`). Deleting the cookie by
160
+ hand or with `cookieCartStorage()` alone writes no tombstone, and the
161
+ hosted storefront restores the old cart from `localStorage`.
162
+
163
+ ## `useCheckout()`
164
+
165
+ ```tsx
166
+ const { checkout, isPending, result, error, attempts, reset } = useCheckout();
167
+
168
+ const result = await checkout({ turnstileToken }); // CheckoutResult
169
+ ```
170
+
171
+ - Calls `carts.checkout(cartId, { turnstileToken })` for the provider's cart.
172
+ Without a cart it rejects with `checkout_incomplete`
173
+ (`details.missing: ['lines']`) without a request. A second call while one
174
+ is in flight returns the same promise.
175
+ - **Never aborted.** The server may place the order even if the browser
176
+ stops waiting, so a checkout keeps running when the component unmounts.
177
+ The state lives in the provider: when a component using `useCheckout()`
178
+ mounts again it sees the result, and the cart is read again. The cart is
179
+ also read again after every checkout (now `ordered`, or the new prices).
180
+ - **Keep `result.token`.** It is returned only once (by the checkout that
181
+ placed the order) and is the buyer's only key to `useOrder`. Build the
182
+ order status URL from it; do not log it or send it to analytics.
183
+ - **Errors** are typed (switch on `error.code`; see the SDK README):
184
+
185
+ ```tsx
186
+ if (isStorefrontError(error)) {
187
+ switch (error.code) {
188
+ case 'cart_changed':
189
+ // error.details: { lines, subtotalMinor, shippingMinor, totalMinor, shippingOptions }
190
+ // Show the new totals and let the buyer confirm; then checkout() again.
191
+ // Never re-submit silently.
192
+ break;
193
+ case 'out_of_stock': // error.details.variantIds
194
+ case 'checkout_incomplete': // error.details.missing
195
+ case 'invalid_buyer_details': // error.details.field
196
+ case 'checkout_in_progress':
197
+ case 'challenge_required':
198
+ case 'challenge_failed':
199
+ case 'too_many_open_orders':
200
+ case 'payment_unavailable':
201
+ }
202
+ }
203
+ ```
204
+
205
+ ## `<PaymentForm>`
206
+
207
+ ```tsx
208
+ {
209
+ result && (
210
+ <PaymentForm
211
+ presentation={result}
212
+ onClosed={(page) => router.push(orderStatusUrl)}
213
+ onUnsupported={() => setFallback(true)}
214
+ onError={() => setFallback(true)}
215
+ className="payment"
216
+ />
217
+ );
218
+ }
219
+ ```
220
+
221
+ 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
224
+ `onClosed(page)` (`closed`: `paid`, `cancelled`, `processing`, …). The form
225
+ is removed on unmount.
226
+
227
+ - Pass the **unmodified result of `checkout()`**. Never build a
228
+ presentation, `embed` or redirect `url` from user input, URL parameters
229
+ or storage: the embedded content runs as script.
230
+ - Card data goes from the provider's form to the provider; it never
231
+ 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.
233
+
234
+ ## `<CheckoutChallenge>`
235
+
236
+ When `store.checkoutChallenge` is set, checkout needs a Cloudflare
237
+ Turnstile token:
238
+
239
+ ```tsx
240
+ const { data: store } = useStore();
241
+ const [token, setToken] = useState<string | null>(null);
242
+ const { checkout } = useCheckout();
243
+
244
+ <CheckoutChallenge
245
+ siteKey={store?.checkoutChallenge?.siteKey}
246
+ onToken={setToken}
247
+ onExpired={() => setToken(null)}
248
+ onError={() => setChallengeFailed(true)}
249
+ />
250
+ <button
251
+ disabled={!!store?.checkoutChallenge && !token}
252
+ onClick={() => checkout({ turnstileToken: token })}
253
+ >
254
+ {t('checkout.pay')}
255
+ </button>
256
+ ```
257
+
258
+ - Uses the SDK's `renderTurnstile` (Cloudflare's official script, loaded
259
+ once; a failed load can be retried by mounting again). Without a
260
+ `siteKey` it renders an empty `<div>`.
261
+ - Tokens are **single-use**: under the provider the widget resets itself
262
+ after every settled `useCheckout()` call and calls `onExpired` (drop the
263
+ token; a new one arrives through `onToken`). To reset it yourself, use a
264
+ ref: `ref.current.reset()`.
265
+ - On your own domain, it must be in the store's domains / allowed origins
266
+ and in the widget's hostname list (see the SDK README).
267
+
268
+ ## `useAccount()`
269
+
270
+ ```tsx
271
+ const { account, status, error, refresh } = useAccount();
272
+ ```
273
+
274
+ `status` is `loading` until the first read answers, `signedOut` on a 401, and
275
+ `signedIn` with the `Account` otherwise. Sign in / out and saves go through
276
+ `useStorefrontClient().account` (`requestCode`, `signIn`, `signOut`,
277
+ `updateProfile`, `saveAddresses`); call `refresh()` after each. A failure
278
+ other than 401 (network, timeout) sets `error` and keeps the last account.
279
+ The session is an HttpOnly cookie: use a same-origin `baseUrl`. For
280
+ server-side calls forward the buyer's `cookie` (see the SDK README).
281
+
282
+ ## `useOrder(orderId, token, { pollUntilFinal })`
283
+
284
+ ```tsx
285
+ // app/orders/[id]/page.tsx renders <OrderStatus id={id} token={token} />
286
+ const { order, error, isLoading, isPolling, refetch } = useOrder(id, token, {
287
+ pollUntilFinal: true,
288
+ });
289
+ ```
290
+
291
+ - Reads `orders.get(orderId, token)`. Missing `orderId` or `token`: reads
292
+ 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
295
+ `pendingPayment` (`paid`, `fulfilling`, `shipped`, `delivered`,
296
+ `cancelled`, `refunded`, …), or a pending order whose payment `failed` /
297
+ `expired` (the buyer checks out again). Transient errors
298
+ (`network_error`, `timeout`, `rate_limited` — honouring `retryAfter` —,
299
+ `order_unavailable`, `http_error`) keep polling and keep the last
300
+ `order`; other errors (`order_not_found`) stop it. Unmounting stops
301
+ polling and aborts the read.
302
+ - The token is the buyer's only key to the order: the hook never logs it.
303
+ Do not send the page URL (which carries it) to analytics.
304
+
305
+ Also exported: `isOrderSettled(order)`, `orderPollDelay(attempt)`,
306
+ `ORDER_POLL_MIN_MS`, `ORDER_POLL_MAX_MS`, `isDeadCartError(e)`.
307
+
308
+ ## Next.js App Router
309
+
310
+ - The package is marked `'use client'`: import the provider, hooks and
311
+ components from client components. Put the provider in a small client
312
+ component and render it from your (server) layout:
313
+
314
+ ```tsx
315
+ // app/providers.tsx
316
+ 'use client';
317
+ import { StorefrontProvider } from '@konfiqo/storefront-react';
318
+
319
+ export function Providers({
320
+ storeId,
321
+ publishableKey,
322
+ children,
323
+ }: {
324
+ storeId: string;
325
+ publishableKey: string;
326
+ children: React.ReactNode;
327
+ }) {
328
+ return (
329
+ <StorefrontProvider
330
+ storeId={storeId}
331
+ config={{
332
+ baseUrl: process.env.NEXT_PUBLIC_COMMERCE_URL!,
333
+ publishableKey,
334
+ }}
335
+ >
336
+ {children}
337
+ </StorefrontProvider>
338
+ );
339
+ }
340
+ ```
341
+
342
+ - Read the catalog in server components with the SDK; use the hooks for
343
+ the cart, checkout and the order status page (they run in the buyer's
344
+ browser, whose origin must be in the store's `allowedOrigins`).
345
+ - On the server render, `useCart()` reports `status: 'idle'` and no cart;
346
+ the saved cart is read after hydration. Render a neutral badge until
347
+ `status === 'ready'` to avoid a layout jump.