@doswiftly/storefront-operations 16.0.0 → 17.0.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/AGENTS.md CHANGED
@@ -27,10 +27,10 @@ consumer's `codegen.ts` references this package's `.graphql` files as
27
27
  live in the consumer's repo.
28
28
 
29
29
  <!-- AUTOGEN:STATS:BEGIN — auto-regenerated, do not edit by hand -->
30
- - **Schema version**: 16.0.0
30
+ - **Schema version**: 17.0.0
31
31
  - **Queries**: 52
32
- - **Mutations**: 40
33
- - **Fragments**: 102
32
+ - **Mutations**: 41
33
+ - **Fragments**: 104
34
34
  <!-- AUTOGEN:STATS:END -->
35
35
 
36
36
  ## Loading order
package/CHANGELOG.md CHANGED
@@ -1,5 +1,471 @@
1
1
  # Changelog
2
2
 
3
+ ## 17.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - d3f0f04: `cartSelectPaymentMethod` mutation is now method-centric.
8
+
9
+ The buyer picks a payment **category** (`BLIK`, `CARD`, `BANK_TRANSFER`, ...) and the backend resolves the preferred gateway from the merchant's `MerchantPaymentConfig` at `paymentCreate` time. Previously the storefront had to look up a per-provider tile UUID via `availablePaymentMethods` and pass it as `paymentMethodId`.
10
+
11
+ **Breaking** — `CartSelectPaymentMethodInput` shape changed:
12
+
13
+ ```graphql
14
+ # Before
15
+ input CartSelectPaymentMethodInput {
16
+ cartId: ID!
17
+ paymentMethodId: ID! # UUID of a per-provider tile
18
+ }
19
+
20
+ # After
21
+ input CartSelectPaymentMethodInput {
22
+ cartId: ID!
23
+ methodType: PaymentMethodType! # BLIK, CARD, BANK_TRANSFER, ...
24
+ preferredProviderId: String # optional override (provider code)
25
+ }
26
+ ```
27
+
28
+ Migration:
29
+
30
+ ```ts
31
+ // Before
32
+ await sdk.cartSelectPaymentMethod({ input: { cartId, paymentMethodId } });
33
+
34
+ // After
35
+ await sdk.cartSelectPaymentMethod({ input: { cartId, methodType: "BLIK" } });
36
+ // Or with explicit gateway override:
37
+ await sdk.cartSelectPaymentMethod({
38
+ input: { cartId, methodType: "BLIK", preferredProviderId: "payu" },
39
+ });
40
+ ```
41
+
42
+ The `availablePaymentMethods` query now returns deduplicated rows per `PaymentMethodType` (one row per BLIK, CARD, ...) with `providersAvailable` (gateway codes sorted by merchant priority) and `preferredProvider` (head of the list). The legacy `group: BY_PROVIDER` argument was removed — there is one canonical shape.
43
+
44
+ **Why** — A merchant configuring PayU + Przelewy24 would previously see "PayU BLIK" and "P24 BLIK" as two separate tiles on the storefront. After this change the storefront shows one BLIK tile; the merchant chooses which gateway handles BLIK via priority settings, and the buyer never sees the internal routing.
45
+
46
+ **Live capability sync (opt-in)** — gateway adapters may expose an optional `getAvailablePaymentMethods(credentials, { currency, amount, country })` capability returning the gateway-reported active methods (min/max amount, brand image, enabled flag). When supported, the platform caches the response per shop/currency and uses it to refine the storefront picker. Gateways without the capability fall back to a static capability matrix. Gateway HTTP failures are soft-failed — the buyer always sees the merchant's configured methods even when the upstream is temporarily unreachable.
47
+
48
+ - 7931668: Payment instrument preselection — direct deep-link to a specific instrument screen on the hosted gateway page (BLIK code, branded bank, wallet, card brand) instead of the gateway default landing.
49
+
50
+ **Why**: shoppers picking BLIK from the storefront UI now skip the gateway method picker entirely — the redirect lands directly on the BLIK code entry. Same flow for picking mBank, ING, Apple Pay, etc. Industry shorthand calls this "deep-link checkout" — 5-15% conversion uplift on single-instrument funnels.
51
+
52
+ **Breaking schema changes**:
53
+ 1. `CartSelectPaymentMethodInput.preferredProviderId` → `preferredProviderCode`. Rename only — same semantics (override the merchant's preferred provider). Aligns with the `*Code` naming convention (`*Id` reserved for UUIDs, `*Code` for lowercase string identifiers like `payu` / `przelewy24`).
54
+
55
+ ```graphql
56
+ # Before
57
+ input CartSelectPaymentMethodInput {
58
+ cartId: ID!
59
+ methodType: PaymentMethodType!
60
+ preferredProviderId: String # ← removed
61
+ }
62
+
63
+ # After
64
+ input CartSelectPaymentMethodInput {
65
+ cartId: ID!
66
+ methodType: PaymentMethodType!
67
+ preferredProviderCode: String # ← renamed
68
+ preferredInstrumentCode: String # ← new (additive)
69
+ }
70
+ ```
71
+
72
+ 2. `PaymentMethod.provider` / `PaymentMethod.providersAvailable` / `PaymentMethod.preferredProvider` / `Order.paymentMethod` / `Payment.provider` are now the typed `ProviderCode` enum (UPPERCASE: `PAYU`, `PRZELEWY24`, `STRIPE`, `CASH_ON_DELIVERY`, `BANK_TRANSFER`, `MANUAL_PAYMENT`, `GIFT_CARD`, `TEST_GATEWAY`) instead of `String`. Replace any `if (provider === 'payu')` storefront branches with the imported enum.
73
+
74
+ ```ts
75
+ // Before
76
+ if (paymentMethod.provider === "payu") {
77
+ /* ... */
78
+ }
79
+
80
+ // After
81
+ import { ProviderCode } from "@doswiftly/storefront-sdk";
82
+ if (paymentMethod.provider === ProviderCode.PAYU) {
83
+ /* ... */
84
+ }
85
+ ```
86
+
87
+ 3. `PaymentMethod.amountLimits` removed from the SDK fragment. The field still exists on the schema for backward-compat, but the SDK no longer selects it — most storefronts never used it and the data is provider-specific (PayU/P24 report limits per method, not per checkout). Re-add it to your local fragment if you need it.
88
+
89
+ **Additive (backward-compatible)**:
90
+ - `PaymentMethod.instruments: [PaymentMethodInstrument!]` — concrete instruments exposed by the gateway (BLIK code, branded banks, wallets, card brands). Each instrument carries `providerCode`, `instrumentCode`, `displayName`, `brandImageUrl`, `displayHint` (semantic UX hint: `PIN_ENTRY` / `WALLET_TAP` / `BANK_LIST` / `CARD_FORM`), `enabled`. `null` when the gateway doesn't expose granular data; empty array when all instruments are disabled.
91
+ - `cartSelectPaymentMethod(input: { preferredInstrumentCode })` — pass the chosen instrument's `instrumentCode` to persist it on the cart. Eager validation cross-checks against the gateway's live capabilities — invalid codes return `userErrors[].code = 'CART_INVALID_INSTRUMENT_CODE'`.
92
+ - `Cart.selectedPaymentInstrumentCode: String` — round-trips the persisted choice so the storefront can re-render the selected instrument on cart refresh.
93
+ - `Order.paymentInstrumentCode: String` — propagated from cart at `cartComplete`; the gateway adapter uses it to build the deep-link payload at `paymentCreate`.
94
+
95
+ **Usage example** — instrument-level deep-link checkout:
96
+
97
+ ```ts
98
+ import { useCartManager, ProviderCode } from "@doswiftly/storefront-sdk";
99
+
100
+ const { selectPaymentMethod, complete, createPayment } = useCartManager();
101
+
102
+ // 1. Render the instrument tiles from the gateway-reported list
103
+ const method = availablePaymentMethods.methods.find((m) => m.type === "BLIK");
104
+ const instrument = method?.instruments?.find(
105
+ (i) => i.instrumentCode === "blik",
106
+ );
107
+
108
+ // 2. Persist the buyer's choice on the cart
109
+ await selectPaymentMethod({
110
+ methodType: "BLIK",
111
+ preferredProviderCode: "payu",
112
+ preferredInstrumentCode: instrument.instrumentCode,
113
+ });
114
+
115
+ // 3. Complete the cart — instrument propagates to the Order
116
+ const { order } = await complete();
117
+
118
+ // 4. Initiate payment — gateway redirects directly to the BLIK code screen
119
+ const session = await createPayment(order.id);
120
+ window.location.href = session.redirectUrl;
121
+ ```
122
+
123
+ **Error handling**:
124
+ - `userErrors[].code === 'CART_INVALID_INSTRUMENT_CODE'` — instrument code is not available with the chosen provider (gateway disabled it, merchant config changed, typo). Refresh `availablePaymentMethods` and re-prompt the buyer.
125
+ - `paymentCreate` failed gateway initiation with the preselected instrument? The order's `paymentInstrumentCode` is automatically cleared (best-effort) — the next `paymentCreate` call falls back to the gateway default landing page. Storefront just retries.
126
+
127
+ **Rate limits**:
128
+ - `availablePaymentMethods` Query: 60 requests/min per IP+shop. Live capability lookups (OAuth + gateway list call) are expensive — hitting the limit returns `extensions.code: 'THROTTLED'` with `retryAfter`. Don't poll; cache the result for the duration of the checkout step.
129
+
130
+ **Gateway API version pinning**:
131
+ - PayU API pinned to `v2_1`, Przelewy24 API pinned to `v1`. When the upstream gateway ships a major version migration, the SDK / operations packages will bump major together with the constant update.
132
+
133
+ **Migration checklist for existing storefronts**:
134
+ - [ ] Rename `preferredProviderId` → `preferredProviderCode` everywhere in storefront mutations.
135
+ - [ ] Replace string comparisons (`provider === 'payu'`) with `ProviderCode` enum.
136
+ - [ ] Re-add `amountLimits` to your local PaymentMethod fragment if you used it.
137
+ - [ ] (Optional) Render the new `instruments` array as tiles to enable instrument-level deep-link checkout — 1-2 extra hours of UI work, measurable conversion impact on single-instrument flows.
138
+
139
+ ### Minor Changes
140
+
141
+ - fd82b62: `PaymentMethod` type gains availability + amount limit fields.
142
+
143
+ The storefront `PaymentMethod` returned by `availablePaymentMethods` (and `Cart.availablePaymentMethods` / `Cart.selectedPaymentMethod`) now carries three additional fields:
144
+ - **`available: Boolean!`** — `false` when the resolving gateway is temporarily unavailable (incident, maintenance) or reported the method as disabled. Storefront should gray-out the tile instead of hiding it — gives merchants observability into routing failures.
145
+ - **`unavailableReason: PaymentMethodUnavailableReason`** — diagnostic enum (`GATEWAY_DOWN`, `GATEWAY_DISABLED`, `NO_INSTRUMENTS`, `CREDENTIALS_INVALID`). Null when `available` is true. Use for context-aware copy ("Provider is temporarily down" vs "Method not configured").
146
+ - **`amountLimits: PaymentMethodAmountLimits`** — gateway-reported min/max transaction amount in the resolving currency (e.g. BLIK 1-20000 PLN). Filter the picker against cart total. Null when the gateway does not report limits.
147
+
148
+ ```graphql
149
+ fragment PaymentMethod on PaymentMethod {
150
+ # existing fields (id, name, provider, type, icon, ...)
151
+ providersAvailable
152
+ preferredProvider
153
+ available
154
+ unavailableReason
155
+ amountLimits {
156
+ min
157
+ max
158
+ currency
159
+ }
160
+ }
161
+ ```
162
+
163
+ **Currency** is automatically resolved from the storefront context (cascade: `@inContext(currency:)` directive → `X-Preferred-Currency` header → cookie → `Accept-Language` → shop default). Override per query via the `@inContext(currency: "EUR")` directive — no new schema argument.
164
+
165
+ **Migration example** for storefront pickers:
166
+
167
+ ```ts
168
+ const { methods } = await sdk.cart.availablePaymentMethods();
169
+ return methods.map((method) => (
170
+ <PaymentTile
171
+ key={method.type}
172
+ type={method.type}
173
+ disabled={!method.available}
174
+ tooltip={method.unavailableReason && reasonCopy[method.unavailableReason]}
175
+ badge={method.amountLimits && cart.total > method.amountLimits.max ? 'Cart too large' : null}
176
+ />
177
+ ));
178
+ ```
179
+
180
+ Backend additionally sanitizes provider error messages (strips OAuth tokens, URLs, JSON secret keys, stack traces) before returning them in admin diagnostic responses — internal logs keep the full error for diagnostics.
181
+
182
+ - c878d14: Payment instrument preselection — storefront UX completion (distinct error code + warnings array + explicit deselect mutation).
183
+
184
+ **Why**: storefront dispatching dla instrument failure stał się context-aware. Dziś generic `PAYMENT_FAILED` post-auto-clear nie pozwalał odróżnić "instrument cleared, retry default landing OK" od "real gateway outage, retry kolejnym attempt". Plus brak explicit deselect — accordion "wróć do wyboru metody" UI wymagał hack typu re-select method.
185
+
186
+ **Additive (backward-compatible)**:
187
+ 1. `PaymentErrorCode.INSTRUMENT_PRESELECTION_FAILED` — new enum value. Wystawiany po auto-clear `Order.paymentInstrumentCode` post-`InvalidPaymentInstrumentError`. Distinct od `PAYMENT_FAILED` (generic gateway failure fallback dla credentials / network / 5xx / circuit breaker).
188
+ 2. `PaymentCreatePayload.warnings: [PaymentWarning!]!` — new field, default empty array. Emitted post-auto-clear z entry `{ code: INSTRUMENT_CLEARED_FOR_RETRY, message, retryHint: null }`. Storefront dispatches retry hint differently (accordion reset / progress bar / itp.).
189
+ 3. `cartClearPaymentSelection(input: { cartId: ID! })` — new mutation. Atomic NULL across all payment selection fields. Idempotent. The cart must be `ACTIVE` — `CONVERTED` carts reject with `userErrors[0].code = 'ALREADY_COMPLETED'`. Rate limit 30/min.
190
+
191
+ **Storefront usage** — handle instrument failure z context-aware retry:
192
+
193
+ ```ts
194
+ import {
195
+ useCartManager,
196
+ type CartMutationOutcome,
197
+ } from "@doswiftly/storefront-sdk";
198
+
199
+ const { selectPaymentMethod, clearPaymentSelection, createPayment } =
200
+ useCartManager();
201
+
202
+ // 1. Klient wybiera BLIK preselect
203
+ await selectPaymentMethod({
204
+ methodType: "BLIK",
205
+ preferredProviderCode: "payu",
206
+ preferredInstrumentCode: "blik",
207
+ });
208
+
209
+ // 2. Try paymentCreate — może rzucić instrument-specific error
210
+ try {
211
+ const session = await createPayment(orderId);
212
+ window.location.href = session.redirectUrl;
213
+ } catch (err) {
214
+ if (err.userErrors?.[0]?.code === "INSTRUMENT_PRESELECTION_FAILED") {
215
+ // Backend auto-cleared instrument — show retry button
216
+ // Warning message available via err.warnings[0].message
217
+ showRetryUI({
218
+ title: "Instrument płatności niedostępny",
219
+ message: err.warnings?.[0]?.message ?? err.message,
220
+ onRetry: () => createPayment(orderId), // next attempt = default landing
221
+ });
222
+ } else if (err.userErrors?.[0]?.code === "PAYMENT_FAILED") {
223
+ // Generic gateway outage — retry z tym samym instrumentem
224
+ showOutageUI({
225
+ message: err.message,
226
+ onRetry: () => createPayment(orderId),
227
+ });
228
+ }
229
+ }
230
+
231
+ // 3. Accordion "wróć do wyboru metody" — explicit deselect
232
+ await clearPaymentSelection({ cartId });
233
+ // Cart.selectedPaymentMethod === null, Cart.selectedPaymentInstrumentCode === null
234
+ ```
235
+
236
+ **Migration guide for existing storefronts**:
237
+ - [ ] Add `warnings[]` to your `paymentCreate` selection set (if you use a custom GraphQL document instead of the SDK helpers).
238
+ - [ ] Branch UI dispatch on `userErrors[0].code === 'INSTRUMENT_PRESELECTION_FAILED'` distinct from `PAYMENT_FAILED`.
239
+ - [ ] (Optional) Replace any accordion-reset hack with `cartClearPaymentSelection({ cartId })` — clearer API, idempotent, single round-trip.
240
+
241
+ **Standards note**: splitting `userErrors[]` (blocking) and `warnings[]` (non-blocking) is a common e-commerce convention. The `INSTRUMENT_PRESELECTION_FAILED` semantics match retry-hint patterns used by major payment gateway SDKs (Stripe `payment_method_unavailable`, etc.).
242
+
243
+ - c553c80: Payment instrument preselection — cart re-validation stale signal + headless instrument components + browser data helper.
244
+
245
+ **Why**: previously the storefront kept showing an obsolete instrument selection until the buyer clicked "pay" — only then did the gateway reject it. The signal is now **proactive**: every cart query re-validates the selection against live gateway capabilities and emits a warning when the method or instrument disappeared. Plus a set of pre-built headless React components so the instrument picker no longer requires manual `displayHint` dispatch.
246
+
247
+ **Additive (backward-compatible)**:
248
+ 1. `Cart.warnings: [CartWarning!]!` — new field, default empty array. Computed at query time. Currently emitted: `PAYMENT_SELECTION_STALE` (code) when `selectedPaymentMethod` or `selectedPaymentInstrumentCode` no longer matches live gateway capabilities. Read-only signal — backend persistence is preserved (clear via `cartClearPaymentSelection` or a fresh `cartSelectPaymentMethod`).
249
+ 2. `Cart.selectedPaymentMethod` re-validation — when the method disappeared from live caps the field returns `null` plus a warning with `target: 'selectedPaymentMethod'`.
250
+ 3. `Cart.selectedPaymentInstrumentCode` re-validation — when only the instrument disappeared (method preserved), the field returns `null` plus a warning with `target: 'selectedPaymentInstrumentCode'` (method-level signal stays intact). Backend persistence is preserved — a re-select gets a fresh state.
251
+ 4. `CartWarningCode.PAYMENT_SELECTION_STALE` — new enum value in the existing `CartWarning` envelope.
252
+ 5. Graceful degradation — when the live capability check fails (gateway timeout / network outage), `Cart` returns the existing selection without a warning (UX continuity over freshness; `cartComplete` time-of-payment validation is the final safety net).
253
+ 6. `<PaymentInstrumentTile>` — new pre-built headless component. Single instrument button with full ARIA contract (`role="radio"`, `aria-checked`, `aria-label`, `data-instrument-code`, `data-display-hint`, `data-selected`). Zero opinionated styling — class props per part (button, icon, label). `displayHint` is emitted as a `data-display-hint` attribute so you can style via CSS attribute selectors.
254
+ 7. `<PaymentInstrumentSection>` — new pre-built headless component. Radio-group container with keyboard navigation (ArrowUp/Down/Left/Right wrap, Home/End jump). Renders one `<PaymentInstrumentTile>` per instrument in the order received from `availablePaymentMethods` (no client-side resort — the backend ordering is the source of truth).
255
+ 8. `getBrowserDataForPayment()` — new helper. Collects PSD2/3DS2 browser context (`userAgent`, `language`, screen dimensions, color depth, timezone offset, IANA timezone, `javaEnabled` fallback). Browser-only — throws `BrowserDataNotAvailableError` in SSR. Forward-looking utility for future 3DS challenge flows.
256
+
257
+ **Storefront usage** — listen to the stale signal in your cart query:
258
+
259
+ ```ts
260
+ const { cart } = useCart(cartId);
261
+
262
+ const staleWarning = cart?.warnings?.find(
263
+ (w) => w.code === "PAYMENT_SELECTION_STALE",
264
+ );
265
+
266
+ if (staleWarning) {
267
+ // The backend signals that the buyer picked a method which is no longer
268
+ // available at the gateway — show a "pick another method" dialog.
269
+ // `target` distinguishes method vs instrument level:
270
+ if (staleWarning.target === "selectedPaymentMethod") {
271
+ // cart.selectedPaymentMethod === null — full re-select required
272
+ } else if (staleWarning.target === "selectedPaymentInstrumentCode") {
273
+ // cart.selectedPaymentMethod is still set, only the instrument cleared
274
+ }
275
+ // Backend persistence is preserved — `cartClearPaymentSelection` or
276
+ // a fresh `cartSelectPaymentMethod` is the consumer's responsibility.
277
+ }
278
+ ```
279
+
280
+ **Storefront usage** — instrument picker with pre-built components:
281
+
282
+ ```tsx
283
+ import { PaymentInstrumentSection } from "@doswiftly/storefront-sdk/react";
284
+ import { useState } from "react";
285
+
286
+ function CheckoutPaymentStep({ method }: { method: PaymentMethod }) {
287
+ const [instrumentCode, setInstrumentCode] = useState<string | undefined>(
288
+ undefined,
289
+ );
290
+
291
+ return (
292
+ <PaymentInstrumentSection
293
+ method={method}
294
+ selectedInstrumentCode={instrumentCode}
295
+ onSelectInstrument={(code) => {
296
+ setInstrumentCode(code);
297
+ cart.selectPaymentMethod({
298
+ methodType: method.type,
299
+ preferredProviderCode: method.preferredProvider,
300
+ preferredInstrumentCode: code,
301
+ });
302
+ }}
303
+ sectionClassName="grid grid-cols-2 gap-2"
304
+ tileClassName="rounded border p-3 hover:bg-gray-50 data-[selected=true]:border-blue-500"
305
+ labelClassName="font-semibold"
306
+ ariaLabel="Pick a payment instrument"
307
+ />
308
+ );
309
+ }
310
+ ```
311
+
312
+ **Storefront usage** — browser data for future 3DS flows:
313
+
314
+ ```ts
315
+ import { getBrowserDataForPayment, BrowserDataNotAvailableError } from '@doswiftly/storefront-sdk/react';
316
+
317
+ function handleCheckoutSubmit() {
318
+ try {
319
+ const browserData = getBrowserDataForPayment();
320
+ // Pass to paymentCreate input when the gateway requires a 3DS challenge
321
+ await cart.createPayment({ ..., browserData });
322
+ } catch (err) {
323
+ if (err instanceof BrowserDataNotAvailableError) {
324
+ // SSR / no DOM — skip browser data; the gateway uses its default flow
325
+ }
326
+ throw err;
327
+ }
328
+ }
329
+ ```
330
+
331
+ **Migration checklist for existing storefronts**:
332
+ - [ ] Add `warnings { message code target }` to your cart query selection set (if you use a custom GraphQL document instead of the SDK fragments — SDK fragments are updated automatically).
333
+ - [ ] Branch UI on `cart.warnings[].code === 'PAYMENT_SELECTION_STALE'` to show a re-prompt dialog before checkout submit.
334
+ - [ ] (Optional) Replace a custom instrument picker with `<PaymentInstrumentSection>` — saves boilerplate, ships full ARIA + keyboard nav out of the box.
335
+ - [ ] (Forward-looking) Adopt `getBrowserDataForPayment()` in checkout submit handlers when 3DS flows become relevant (currently optional — the gateway accepts an undefined `browserData`).
336
+
337
+ **Standards reference**: `PaymentInstrumentSection` follows the WAI-ARIA radiogroup pattern (https://www.w3.org/WAI/ARIA/apg/patterns/radio/). The browser data helper shape matches the EMVCo 3DS2 BrowserData specification.
338
+
339
+ ## 16.1.0
340
+
341
+ ### Minor Changes
342
+
343
+ - 1e6062e: Read the gift card recipient back from the cart.
344
+
345
+ `cartUpdateGiftCardRecipient` already persisted the recipient (email, name,
346
+ personalised message) on a gift card line — but the `CartLine` type didn't
347
+ expose any field to read it. Storefronts that render the checkout server-side
348
+ (SSR, deep link, "back to cart" navigation) had no way to know that the buyer
349
+ had already filled in the recipient form on a previous visit. The recipient
350
+ dialog opened blank, like nothing had been saved.
351
+
352
+ **New field** — `CartLine.giftCardRecipient: GiftCardLineRecipient`
353
+
354
+ ```graphql
355
+ type GiftCardLineRecipient {
356
+ recipientEmail: String
357
+ recipientName: String
358
+ message: String
359
+ }
360
+ ```
361
+
362
+ All three fields are individually nullable so a partial set (email only, no
363
+ name or message) is representable as-is. The field on `CartLine` itself is
364
+ nullable — `null` means the buyer has not set a recipient yet, in which case
365
+ the gift card is delivered to the order `customerEmail` on completion.
366
+
367
+ `null` is also what you get for any non-gift-card line — there is no risk of
368
+ the field reporting a stale recipient from a previous line at the same index.
369
+
370
+ **Use it to seed your form**
371
+
372
+ ```tsx
373
+ const cart = await cartClient.get(cartId);
374
+ const giftLine = cart?.lines.edges.find(
375
+ (e) => e.node.productType === "GIFT_CARD",
376
+ );
377
+
378
+ <GiftRecipientForm
379
+ defaultValues={
380
+ giftLine?.node.giftCardRecipient ?? {
381
+ recipientEmail: "",
382
+ recipientName: "",
383
+ message: "",
384
+ }
385
+ }
386
+ onSubmit={(values) =>
387
+ cartClient.updateGiftCardRecipient(cartId, giftLine!.node.id, values)
388
+ }
389
+ />;
390
+ ```
391
+
392
+ **Migration**
393
+
394
+ Additive change — no rename, no signature change. The `CartLine` fragment
395
+ shipped by the SDK already includes the new field after this release, so
396
+ upgrading immediately unlocks the read path. No client code changes required
397
+ to keep existing flows working.
398
+
399
+ - ac2e306: Distinguish recoverable session loss from permanent cart denial.
400
+
401
+ Adds a new `CART_UNAUTHENTICATED` code to the cart error envelope. Until now,
402
+ both "your sign-in expired" and "this cart belongs to someone else" surfaced
403
+ as `CART_FORBIDDEN`, so a storefront had no way to know whether to send the
404
+ buyer to `/login` (recoverable) or to drop the cart cookie (permanent).
405
+ After the typical ~24h session TTL, the buyer would silently lose their
406
+ checkout state instead of being prompted to re-authenticate.
407
+
408
+ **New code** — `CART_UNAUTHENTICATED`
409
+
410
+ | Condition | Code | Recovery |
411
+ | ------------------------------------------------------------------------------------- | ---------------------------- | ----------------------------------------------------------- |
412
+ | Anonymous request **or** expired/invalid session on a cart that belongs to a customer | `CART_UNAUTHENTICATED` | Re-authenticate. Cart is preserved (`cart-id` cookie kept). |
413
+ | Authenticated as a **different** customer than the cart owner | `CART_FORBIDDEN` (unchanged) | Drop the cart cookie and start over. |
414
+
415
+ The cart resource itself is intact in the `CART_UNAUTHENTICATED` case — the
416
+ buyer's saved address, line items, discount codes, and gift cards return as
417
+ soon as they sign in.
418
+
419
+ **New SDK signal** — `runner.onSessionExpired(...)`
420
+
421
+ The recovery runner now exposes a separate event for session loss, distinct
422
+ from `onExpired` (which is for cart-resource lifecycle: cart not found, cart
423
+ already completed). Subscribe once at the provider level and route the buyer
424
+ to `/login` with a `return_to` parameter; the cart cookie stays put.
425
+
426
+ ```ts
427
+ // app/providers.tsx
428
+ const unsubExpired = runner.onExpired(() => {
429
+ // cart resource gone — start fresh
430
+ router.push("/cart/new");
431
+ });
432
+
433
+ const unsubSession = runner.onSessionExpired(() => {
434
+ // session gone, cart preserved — sign back in
435
+ router.push(`/login?return_to=${encodeURIComponent(location.pathname)}`);
436
+ });
437
+ ```
438
+
439
+ The session branch throws `CartSessionRequiredError` (re-exported alongside
440
+ `CartRecoveryNotPossibleError`) and does **not** invoke `recreateAndRun` —
441
+ recreating the cart on a stale session would discard the buyer's progress.
442
+
443
+ **Imperative handling**
444
+
445
+ If you handle mutation errors directly (Server Action, custom hook), add one
446
+ case to your existing switch:
447
+
448
+ ```ts
449
+ switch (err.userErrors[0]?.code) {
450
+ case "CART_UNAUTHENTICATED":
451
+ redirect(`/login?return_to=${encodeURIComponent("/checkout")}`);
452
+ break;
453
+ case "CART_FORBIDDEN":
454
+ cookies().delete("cart-id");
455
+ redirect("/cart/expired");
456
+ break;
457
+ // ...existing cases for CART_NOT_FOUND / ALREADY_COMPLETED
458
+ }
459
+ ```
460
+
461
+ **Migration**
462
+
463
+ Additive change — no rename, no signature change. Existing `case 'CART_FORBIDDEN'`
464
+ branches keep working as before. Opt in to the new code at your own pace; until
465
+ you add the case, anonymous and cross-customer denials fall into your existing
466
+ default branch (one will be recoverable, one will not — adding the case lets
467
+ you distinguish them).
468
+
3
469
  ## 16.0.0
4
470
 
5
471
  ### Major Changes
package/README.md CHANGED
@@ -380,12 +380,13 @@ full executable body of each operation.
380
380
  | `CartSetShippingAddress` | Phase 3 unify-cart-graphql-surface: wszystkie fulfillment + payment + completion operations teraz na Cart aggregate (zamiast Checkout dual-aggregate). Klient robi typowy checkout flow: cart create/add items → setShipping/Billing/Method → selectPayment → (optional) applyGiftCard → cartComplete → Order created. Sets the shipping address on the cart (full replace, not patch). Triggers cart re-pricing (tax recalculation per address country/region). Address format validated against `CartAddressInput` constraints (firstName/lastName/streetLine1/city/country/postalCode required). Errors: `INVALID_ADDRESS`, `CART_NOT_FOUND`. |
381
381
  | `CartSetBillingAddress` | Sets the billing address on the cart (full replace). Independent of shipping address — pass it explicitly even when "billing same as shipping". Errors: `INVALID_ADDRESS`, `CART_NOT_FOUND`. |
382
382
  | `CartSelectShippingMethod` | Selects a shipping method by `shippingMethodId` (typed `ID!`, a stable shipping-method UUID — NOT a per-request token). The id comes from a list of methods available for the current address + cart subtotal (queryable separately). Errors: `SHIPPING_METHOD_REQUIRED`, `ZIP_CODE_NOT_SUPPORTED`, `CART_NOT_FOUND`. |
383
- | `CartSelectPaymentMethod` | Selects a payment method by `paymentMethodId` (UUID from `availablePaymentMethods` query). Validates existence + active status; no pre-authorization performed here. Errors: `PAYMENT_METHOD_REQUIRED`, `INVALID_PAYMENT`, `CART_NOT_FOUND`. |
383
+ | `CartSelectPaymentMethod` | Selects a payment method on the cart by category (`methodType` BLIK, CARD, BANK_TRANSFER, ...). Optional `preferredProviderId` overrides the merchant priority when the buyer explicitly picks a gateway from `PaymentMethod.providersAvailable`. The backend resolves the gateway routing from `MerchantPaymentConfig` at `cartComplete`; the selection persisted here is the category. Errors: `PAYMENT_METHOD_REQUIRED`, `CART_NOT_FOUND`, `CART_UNAUTHENTICATED`. |
384
384
  | `CartApplyGiftCard` | Applies a gift card to the cart, stackable with discount codes. Consumption is FIFO: each card consumes `min(remainingBalance, paymentDue)` against the current cart total in the order they were applied. The gift card balance is NOT debited yet — actual deduction happens atomically at `cartComplete`. Errors: `GIFT_CARD_NOT_FOUND`, `GIFT_CARD_DEPLETED`, `GIFT_CARD_UNUSABLE`. |
385
385
  | `CartRemoveGiftCard` | Removes a gift card from the applied list and recalculates FIFO `appliedAmount` for the remaining cards. Since gift card balances are only debited at `cartComplete`, removing before completion has no effect on the underlying gift card balance. |
386
386
  | `CartUpdateGiftCardRecipient` | Sets per-line-item recipient details (name, email, message) for digital gift card products in the cart (line items where the variant represents a gift-card SKU). Required before `cartComplete` for any line item with a gift-card variant. Recipient details propagated to the resulting order. |
387
387
  | `CartComplete` | Finalizes the cart — creates the `Order`, deducts gift cards, sends order-created confirmation — all atomically. **Idempotent on `idempotencyKey`** (auto-generated from cartId + minute timestamp if caller omits it). Returns `order` field after completion. Note: `paymentUrl` is intentionally NOT in payload — for hosted gateways (online providers) the storefront calls a separate `paymentCreate` mutation after this returns (check `order.canCreatePayment` first). Errors: `EMAIL_REQUIRED`, `SHIPPING_ADDRESS_REQUIRED`, `SHIPPING_METHOD_REQUIRED`, `PAYMENT_METHOD_REQUIRED`, `INSUFFICIENT_STOCK`, `ALREADY_COMPLETED`. |
388
- | `PaymentCreate` | Initiates a payment session for an order created by `cartComplete` — call this when `order.canCreatePayment` is `true` (orders with an offline payment method like cash-on-delivery skip this step). `orderId` is required; `returnUrl` / `cancelUrl` are optional and, when supplied, must point to a verified domain of the shop (open-redirect protected). Branch on the returned `payment.flow`: `ONLINE_REDIRECT` → redirect to `payment.redirectUrl`, `ONLINE_EMBEDDED` → render a widget with `payment.clientSecret`, `INSTANT_DIRECT` → already settled, read `payment.status`. Public, but ownership-checked — an authenticated customer cannot pay for another customer's order. **Idempotent** — calling it again for the same order returns the existing still-valid session instead of creating a duplicate (safe to retry). Rate limit: 5 requests/minute. `userErrors[].code`: `ORDER_NOT_FOUND`, `ORDER_ALREADY_PAID`, `ORDER_NOT_PAYABLE`, `PAYMENT_PROVIDER_NOT_CONFIGURED`, `RETURN_URL_INVALID`, `INVALID_ID_FORMAT`, `PAYMENT_FAILED`. |
388
+ | `PaymentCreate` | Initiates a payment session for an order created by `cartComplete` — call this when `order.canCreatePayment` is `true` (orders with an offline payment method like cash-on-delivery skip this step). `orderId` is required; `returnUrl` / `cancelUrl` are optional and, when supplied, must point to a verified domain of the shop (open-redirect protected). Branch on the returned `payment.flow`: `ONLINE_REDIRECT` → redirect to `payment.redirectUrl`, `ONLINE_EMBEDDED` → render a widget with `payment.clientSecret`, `INSTANT_DIRECT` → already settled, read `payment.status`. Public, but ownership-checked — an authenticated customer cannot pay for another customer's order. **Idempotent** — calling it again for the same order returns the existing still-valid session instead of creating a duplicate (safe to retry). Rate limit: 5 requests/minute. `userErrors[].code`: `ORDER_NOT_FOUND`, `ORDER_ALREADY_PAID`, `ORDER_NOT_PAYABLE`, `PAYMENT_PROVIDER_NOT_CONFIGURED`, `RETURN_URL_INVALID`, `INVALID_ID_FORMAT`, `PAYMENT_FAILED`, `INSTRUMENT_PRESELECTION_FAILED`. `warnings[]` array zawiera `INSTRUMENT_CLEARED_FOR_RETRY` post-auto-clear instrument-specific failure (storefront retry hint: next attempt uses gateway default landing). |
389
+ | `CartClearPaymentSelection` | Clears all payment selection state on the cart in a single atomic operation. Use for accordion "back to method picker" flows w storefront UI. Idempotent — calling twice yields the same end state. Cart MUSI być `ACTIVE` (CONVERTED carts reject z `ALREADY_COMPLETED`). Rate limit: 30 requests/minute per IP+shop. |
389
390
 
390
391
  #### Return Mutations
391
392
 
@@ -508,9 +509,11 @@ full executable body of each operation.
508
509
 
509
510
  | Fragment | On Type | Description |
510
511
  | --- | --- | --- |
511
- | `PaymentMethod` | `PaymentMethod` | Single payment method enabled for the shop type (CARD / BANK_TRANSFER / BLIK / PAYPAL / APPLE_PAY / GOOGLE_PAY / CASH_ON_DELIVERY / OTHER), provider, icon, supported currencies, default flag, sort position. Spread on the checkout payment step. |
512
+ | `PaymentMethodInstrument` | `PaymentMethodInstrument` | A single concrete instrument exposed by a gateway provider (BLIK code, branded bank, wallet, card brand). Pass `instrumentCode` as `preferredInstrumentCode` in `cartSelectPaymentMethod` for direct deep-link to that instrument screen on the gateway. `displayHint` is a semantic UX hint (`PIN_ENTRY`, `WALLET_TAP`, `BANK_LIST`, `CARD_FORM`) — storefront branches rendering accordingly. `enabled: false` means the gateway reported the instrument as temporarily disabled — gray out, don't hide. |
513
+ | `PaymentMethod` | `PaymentMethod` | Single payment method enabled for the shop — method-centric. `type` is the category (CARD, BLIK, BANK_TRANSFER, CASH_ON_DELIVERY, OTHER) — drive iconography here. `provider`, `providersAvailable`, `preferredProvider` are `ProviderCode` enum (UPPERCASE: `PAYU`, `PRZELEWY24`, ...). `available` is `false` when the resolving gateway is temporarily unavailable or reported the method as disabled — gray-out the tile, don't hide it; `unavailableReason` carries the diagnostic. `instruments` lists concrete gateway-side instruments (BLIK code, branded banks, wallets) when the gateway exposes granular data — pass `instrumentCode` as `preferredInstrumentCode` in `cartSelectPaymentMethod` for direct deep-link to that instrument screen on the gateway. Spread on the checkout payment step. |
512
514
  | `AvailablePaymentMethods` | `AvailablePaymentMethods` | Active payment methods list with the merchant's `defaultMethod`. Returned by the `availablePaymentMethods` query. |
513
515
  | `PaymentSession` | `PaymentSession` | Initiated payment session for an order — returned by the `paymentCreate` mutation. Branch on `flow`: `ONLINE_REDIRECT` (redirect the browser to `redirectUrl`), `ONLINE_EMBEDDED` (render an in-page widget with `clientSecret`), `INSTANT_DIRECT` (settled with no UI — read `status`). `expiresAt` is ISO 8601, present when the gateway session has a TTL. |
516
+ | `PaymentWarning` | `PaymentWarning` | Non-blocking signal emitted alongside `userErrors[]` in `paymentCreate` payload — backend state change context (e.g. an auto-clear of preselected instrument after gateway rejection). Pre-translated by backend per shop locale. `code === 'INSTRUMENT_CLEARED_FOR_RETRY'` signals storefront that the next `paymentCreate` will land on the gateway default landing page (server-side cleared `Order.paymentInstrumentCode` after `INSTRUMENT_PRESELECTION_FAILED`). `retryHint` is optional context for UI dispatch — currently unused for `INSTRUMENT_CLEARED_FOR_RETRY`, reserved for future warning codes. |
514
517
 
515
518
  #### Shipments / Tracking
516
519
 
package/fragments.graphql CHANGED
@@ -427,6 +427,11 @@ fragment CartLine on CartLine {
427
427
  productHandle
428
428
  productType
429
429
  requiresShipping
430
+ giftCardRecipient {
431
+ recipientEmail
432
+ recipientName
433
+ message
434
+ }
430
435
  }
431
436
 
432
437
  # Buyer identity associated with the cart. Note: only `customerId` is currently persisted server-side; `email`, `phone`, `countryCode` are accepted in the input but ignored.
@@ -505,6 +510,7 @@ fragment Cart on Cart {
505
510
  selectedPaymentMethod {
506
511
  ...CartSelectedPaymentMethod
507
512
  }
513
+ selectedPaymentInstrumentCode
508
514
  appliedGiftCards {
509
515
  ...CartAppliedGiftCard
510
516
  }
@@ -695,7 +701,23 @@ fragment ShopConfigFields on Shop {
695
701
  # Payment Methods
696
702
  # ============================================
697
703
 
698
- # Single payment method enabled for the shop type (CARD / BANK_TRANSFER / BLIK / PAYPAL / APPLE_PAY / GOOGLE_PAY / CASH_ON_DELIVERY / OTHER), provider, icon, supported currencies, default flag, sort position. Spread on the checkout payment step.
704
+ # A single concrete instrument exposed by a gateway provider (BLIK code, branded bank, wallet, card brand). Pass `instrumentCode` as `preferredInstrumentCode` in `cartSelectPaymentMethod` for direct deep-link to that instrument screen on the gateway. `displayHint` is a semantic UX hint (`PIN_ENTRY`, `WALLET_TAP`, `BANK_LIST`, `CARD_FORM`) — storefront branches rendering accordingly. `enabled: false` means the gateway reported the instrument as temporarily disabled — gray out, don't hide.
705
+ fragment PaymentMethodInstrument on PaymentMethodInstrument {
706
+ providerCode
707
+ instrumentCode
708
+ type
709
+ displayName
710
+ displayHint
711
+ brandImageUrl
712
+ enabled
713
+ }
714
+
715
+ # Single payment method enabled for the shop — method-centric.
716
+ # `type` is the category (CARD, BLIK, BANK_TRANSFER, CASH_ON_DELIVERY, OTHER) — drive iconography here.
717
+ # `provider`, `providersAvailable`, `preferredProvider` are `ProviderCode` enum (UPPERCASE: `PAYU`, `PRZELEWY24`, ...).
718
+ # `available` is `false` when the resolving gateway is temporarily unavailable or reported the method as disabled — gray-out the tile, don't hide it; `unavailableReason` carries the diagnostic.
719
+ # `instruments` lists concrete gateway-side instruments (BLIK code, branded banks, wallets) when the gateway exposes granular data — pass `instrumentCode` as `preferredInstrumentCode` in `cartSelectPaymentMethod` for direct deep-link to that instrument screen on the gateway.
720
+ # Spread on the checkout payment step.
699
721
  fragment PaymentMethod on PaymentMethod {
700
722
  id
701
723
  name
@@ -706,6 +728,13 @@ fragment PaymentMethod on PaymentMethod {
706
728
  isDefault
707
729
  supportedCurrencies
708
730
  position
731
+ providersAvailable
732
+ preferredProvider
733
+ available
734
+ unavailableReason
735
+ instruments {
736
+ ...PaymentMethodInstrument
737
+ }
709
738
  }
710
739
 
711
740
  # Active payment methods list with the merchant's `defaultMethod`. Returned by the `availablePaymentMethods` query.
@@ -730,6 +759,13 @@ fragment PaymentSession on PaymentSession {
730
759
  expiresAt
731
760
  }
732
761
 
762
+ # Non-blocking signal emitted alongside `userErrors[]` in `paymentCreate` payload — backend state change context (e.g. an auto-clear of preselected instrument after gateway rejection). Pre-translated by backend per shop locale. `code === 'INSTRUMENT_CLEARED_FOR_RETRY'` signals storefront that the next `paymentCreate` will land on the gateway default landing page (server-side cleared `Order.paymentInstrumentCode` after `INSTRUMENT_PRESELECTION_FAILED`). `retryHint` is optional context for UI dispatch — currently unused for `INSTRUMENT_CLEARED_FOR_RETRY`, reserved for future warning codes.
763
+ fragment PaymentWarning on PaymentWarning {
764
+ message
765
+ code
766
+ retryHint
767
+ }
768
+
733
769
  # ============================================
734
770
  # Discount Code Validation
735
771
  # ============================================