@vtex/faststore 0.0.3 → 0.0.5
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/CHANGELOG.md +41 -0
- package/README.md +7 -3
- package/dist/catalog.json +337 -1
- package/dist/components.d.ts +5 -1
- package/dist/components.js +8 -4
- package/dist/content-types.json +73 -0
- package/dist/docs/account-access-gate.md +153 -0
- package/dist/docs/account-entry-point.md +1 -2
- package/dist/docs/account-menu.md +164 -0
- package/dist/docs/buy-button.md +1 -1
- package/dist/docs/cart.md +1 -1
- package/dist/docs/my-account-profile.md +208 -0
- package/dist/docs/session.md +1 -1
- package/dist/docs/sign-in-redirect.md +1 -1
- package/dist/matter/account-access-gate/account-access-gate.d.ts +86 -0
- package/dist/matter/account-access-gate/account-access-gate.js +283 -0
- package/dist/matter/account-access-gate/account-access-gate.js.map +1 -0
- package/dist/matter/account-access-gate/sign-out-intent.d.ts +17 -0
- package/dist/matter/account-access-gate/sign-out-intent.js +62 -0
- package/dist/matter/account-access-gate/sign-out-intent.js.map +1 -0
- package/dist/matter/account-entry-point/account-entry-point.js +2 -2
- package/dist/matter/account-entry-point/account-entry-point.js.map +1 -1
- package/dist/matter/account-menu/account-menu.d.ts +88 -0
- package/dist/matter/account-menu/account-menu.js +246 -0
- package/dist/matter/account-menu/account-menu.js.map +1 -0
- package/dist/matter/cart/cart.d.ts +1 -1
- package/dist/matter/cart/cart.js +2 -2
- package/dist/matter/cart/cart.js.map +1 -1
- package/dist/matter/delivery-options/delivery-options.js.map +1 -1
- package/dist/matter/my-account-profile/my-account-profile.d.ts +291 -0
- package/dist/matter/my-account-profile/my-account-profile.js +856 -0
- package/dist/matter/my-account-profile/my-account-profile.js.map +1 -0
- package/dist/matter/shipping-address/shipping-address.js +2 -2
- package/dist/matter/shipping-address/shipping-address.js.map +1 -1
- package/dist/matter/shipping-simulator/shipping-simulator.js.map +1 -1
- package/dist/particles/footer-social/footer-social.js +1 -1
- package/dist/particles/incentives/incentives.js +1 -1
- package/dist/sdk/actions/cart-action-provider.d.ts +1 -1
- package/dist/sdk/actions/cart-action-provider.js +1 -1
- package/dist/sdk/actions/cart-action-provider.js.map +1 -1
- package/dist/sdk/actions/session-action-provider.d.ts +1 -1
- package/dist/sdk/actions/session-action-provider.js +1 -1
- package/dist/sdk/actions/session-action-provider.js.map +1 -1
- package/dist/sdk/actions/shipping-action-provider.d.ts +1 -1
- package/dist/sdk/actions/shipping-action-provider.js +1 -1
- package/dist/sdk/actions/shipping-action-provider.js.map +1 -1
- package/dist/sdk/cache/storefront-cache.js +1 -1
- package/dist/sdk/cache/storefront-cache.js.map +1 -1
- package/dist/sdk/cart/operations.d.ts +4 -4
- package/dist/sdk/cart/operations.js +1 -1
- package/dist/sdk/cart/operations.js.map +1 -1
- package/dist/sdk/cart/optimistic.js +1 -1
- package/dist/sdk/cart/optimistic.js.map +1 -1
- package/dist/sdk/cart/use-cart-actions.d.ts +1 -1
- package/dist/sdk/cart/use-cart-actions.js +3 -3
- package/dist/sdk/cart/use-cart-actions.js.map +1 -1
- package/dist/sdk/cart/use-cart-validate-on-open.js +1 -1
- package/dist/sdk/cart/use-cart-validate-on-open.js.map +1 -1
- package/dist/sdk/cart/write-gate.js +1 -1
- package/dist/sdk/cart/write-gate.js.map +1 -1
- package/dist/sdk/data/page-reactive-data-root.d.ts +2 -2
- package/dist/sdk/data/page-reactive-data-root.js.map +1 -1
- package/dist/sdk/data/reactive-data-provider.d.ts +1 -1
- package/dist/sdk/data/reactive-data-provider.js +1 -1
- package/dist/sdk/data/reactive-data-provider.js.map +1 -1
- package/dist/sdk/data/reactive-list-item-data-provider.d.ts +1 -1
- package/dist/sdk/data/reactive-list-item-data-provider.js +1 -1
- package/dist/sdk/data/reactive-list-item-data-provider.js.map +1 -1
- package/dist/sdk/data/use-reactive-entity.js +1 -1
- package/dist/sdk/data/use-reactive-entity.js.map +1 -1
- package/dist/sdk/generated/gql.js +2 -1
- package/dist/sdk/generated/gql.js.map +1 -1
- package/dist/sdk/generated/graphql.js +85 -1
- package/dist/sdk/generated/graphql.js.map +1 -1
- package/dist/sdk/identity/operations.js.map +1 -1
- package/dist/sdk/identity/use-identity-actions.d.ts +1 -1
- package/dist/sdk/identity/use-identity-actions.js.map +1 -1
- package/dist/sdk/session/auth-operations.d.ts +1 -1
- package/dist/sdk/session/auth-operations.js.map +1 -1
- package/dist/sdk/session/use-session-actions.d.ts +1 -1
- package/dist/sdk/session/use-session-actions.js.map +1 -1
- package/dist/sdk/session/use-session-revalidation.js +65 -0
- package/dist/sdk/session/use-session-revalidation.js.map +1 -0
- package/dist/sdk/shipping/option-select-operations.d.ts +1 -1
- package/dist/sdk/shipping/option-select-operations.js.map +1 -1
- package/dist/sdk/shipping/request-timeout.js +1 -1
- package/dist/sdk/shipping/request-timeout.js.map +1 -1
- package/dist/sdk/shipping/shipping-operations.d.ts +1 -1
- package/dist/sdk/shipping/shipping-operations.js.map +1 -1
- package/dist/sdk/shipping/use-shipping-actions.d.ts +2 -2
- package/dist/sdk/shipping/use-shipping-actions.js.map +1 -1
- package/dist/sdk/state/cart.d.ts +3 -4
- package/dist/sdk/state/cart.js +6 -7
- package/dist/sdk/state/cart.js.map +1 -1
- package/dist/utils/safe-href.js +3 -3
- package/dist/utils/safe-href.js.map +1 -1
- package/package.json +1 -18
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-cart-actions.js","names":[],"sources":["../../../src/sdk/cart/use-cart-actions.ts"],"sourcesContent":["'use client';\n\nimport type { ApolloClient } from '@apollo/client';\nimport { useApolloClient, useMutation } from '@apollo/client/react';\nimport { defineActions } from '@vtex/fs-core';\nimport { useCallback, useMemo } from 'react';\nimport { cartCouponErrorsVar, cartLastAddVar, cartUserErrorsVar, orderFormIdVar } from '../state/cart.js';\nimport {\n CART_COUPON_APPLY,\n CART_COUPON_REMOVE,\n CART_ITEM_ADD,\n CART_ITEM_QUANTITY_DECREASE,\n CART_ITEM_QUANTITY_INCREASE,\n CART_ITEM_REMOVE,\n CART_ITEMS_REMOVE,\n CART_VALIDATE,\n type CartEntity,\n CartFragment,\n type CartItemEntity,\n type CartUserError,\n} from './operations.js';\nimport {\n buildOptimisticDecrease,\n buildOptimisticIncrease,\n buildOptimisticRemove,\n buildOptimisticRemoveItems,\n} from './optimistic.js';\nimport { markAvailabilityFresh, trackCartWrite } from './write-gate.js';\n\n/**\n * The `cart` action namespace — the consolidated, context-free owner of every cart write\n * (specs/actions.md, docs/storefront-core/adr-0010-actions-own-the-write-side.md).\n *\n * It replaces `useCartMutations` + the mutation handlers `CartRoot` used to publish through\n * `CartDataContext`. A handler reads the current cart from the normalized Apollo cache (keyed by\n * `orderFormIdVar`), not from component props or React context, so any component anywhere in the\n * tree can dispatch a write through the compiler-injected `$actions.cart.*` prop — the cache is the\n * only meeting point between the read side and the write side (ADR-0010).\n *\n * `userErrors` from every call are published to `cartUserErrorsVar` (cleared at the start of the\n * next call) so `CartError` can surface them without a data context, and also returned to the caller.\n */\n\n/**\n * Thrown by the existing-line handlers (remove / quantity) when invoked before the cart resolves.\n * The first `addItem` mints the cart and hydrates `orderFormIdVar`; until then there is no cached\n * cart entity to read for the optimistic response.\n */\nexport class CartNotReadyError extends Error {\n constructor(message?: string) {\n super(message ?? 'CartNotReadyError: no cart in cache yet; add an item (or load the cart) before mutating a line.');\n this.name = 'CartNotReadyError';\n }\n}\n\nexport type AddItemPayload = Readonly<{\n variantId: string;\n quantity?: number;\n /** Seller global Node ID, e.g. base64(\"Seller:1\"). The server rejects raw ids with INVALID_SELLER_ID. */\n seller: string;\n}>;\n\n/** Existing-line payloads address the line by its opaque cart-item `id`; the handler reads the rest from cache. */\nexport type CartLinePayload = Readonly<{ id: string }>;\n\n/** Batch payloads address several lines by their opaque cart-item `id`s. */\nexport type CartLinesPayload = Readonly<{ ids: readonly string[] }>;\n\nexport type CartQuantityPayload = Readonly<{ id: string; by?: number }>;\n\n/** Coupon writes address the coupon by its `code`; the server resolves the cart from the cookie. */\nexport type CartCouponPayload = Readonly<{ code: string }>;\n\n/**\n * The `cart` namespace surface. Item writes return the resulting `userErrors` (empty on success)\n * and publish them to `cartUserErrorsVar`; coupon writes publish to the dedicated\n * `cartCouponErrorsVar` (specs/fspg-830-coupon-entry.md AD-2).\n */\nexport type CartActions = Readonly<{\n /** Add an item to the cart. Async (no optimistic response). Creates the cart on first add. */\n addItem: (payload: AddItemPayload) => Promise<readonly CartUserError[]>;\n /** Remove a line entirely. Optimistic. */\n removeItem: (payload: CartLinePayload) => Promise<readonly CartUserError[]>;\n /** Remove several lines in one mutation. Optimistic. Ids missing from the cache are skipped. */\n removeItems: (payload: CartLinesPayload) => Promise<readonly CartUserError[]>;\n /** Increase a line's quantity by N (default 1). Optimistic. */\n increaseQuantity: (payload: CartQuantityPayload) => Promise<readonly CartUserError[]>;\n /** Decrease a line's quantity by N (default 1). Optimistic. Removes the line when result <= 0. */\n decreaseQuantity: (payload: CartQuantityPayload) => Promise<readonly CartUserError[]>;\n /** Apply a coupon code. Async (no optimistic). Publishes userErrors to cartCouponErrorsVar. */\n applyCoupon: (payload: CartCouponPayload) => Promise<readonly CartUserError[]>;\n /** Remove a coupon code by code. Async (no optimistic). Publishes userErrors to cartCouponErrorsVar. */\n removeCoupon: (payload: CartCouponPayload) => Promise<readonly CartUserError[]>;\n /**\n * Re-check the active cart against the platform and adopt corrected availability. Async (no\n * optimistic), read-only upstream. Returns userErrors (empty on success) to its caller and stamps\n * the freshness window on success. Unlike the item writes it does NOT publish to\n * `cartUserErrorsVar` — a speculative open-time failure must raise no error banner (Decision 6).\n */\n validate: () => Promise<readonly CartUserError[]>;\n}>;\n\nconst NETWORK_USER_ERROR: CartUserError = {\n code: 'NETWORK_ERROR',\n message: 'Unable to update cart. Please try again.',\n};\n\nfunction publish(errors: readonly CartUserError[]): readonly CartUserError[] {\n cartUserErrorsVar(errors);\n return errors;\n}\n\n/** Coupon-scoped publish — keeps coupon feedback off the shared item-error channel (AD-2). */\nfunction publishCoupon(errors: readonly CartUserError[]): readonly CartUserError[] {\n cartCouponErrorsVar(errors);\n return errors;\n}\n\n/**\n * Publish a write's outcome and, when it came back clean, stamp the availability freshness window —\n * a clean write's payload carries the platform's recomputed cart, which is what lets the\n * validate-on-open call skip (specs/mini-cart-validation-wiring.md, Decision 2). Used only on paths\n * where a mutation actually reached the server: a `userErrors` response carries `cart: null` and a\n * no-op (unknown line) issues no request, so neither refreshes availability.\n */\nfunction publishWrite(errors: readonly CartUserError[]): readonly CartUserError[] {\n if (errors.length === 0) markAvailabilityFresh();\n return publish(errors);\n}\n\n/** Coupon-channel counterpart of `publishWrite`. */\nfunction publishCouponWrite(errors: readonly CartUserError[]): readonly CartUserError[] {\n if (errors.length === 0) markAvailabilityFresh();\n return publishCoupon(errors);\n}\n\n/**\n * Backfill `orderFormIdVar` from a mutation's returned `cart.id` when local state is still cold.\n * A coupon op can be the first cart write (SSR cold / drawer closed on first load); without this the\n * later `requireLine` paths short-circuit on `orderFormIdVar() === null` and throw `CartNotReadyError`.\n * Mirrors the `addItem` first-add handoff.\n */\nfunction hydrateCartId(cartId: string | null): void {\n if (cartId && orderFormIdVar() === null) orderFormIdVar(cartId);\n}\n\n/**\n * Read the live cart entity from the normalized cache (ADR-0010), keyed by `orderFormIdVar`. Returns\n * null before the cart is minted/loaded. Module-level so it can be shared with the read-only callers\n * that live outside this hook — the pre-checkout gate re-reads the corrected cart this way after\n * `validate` resolves, because Apollo commits the mutation's cache write before the promise settles\n * (specs/mini-cart-validation-wiring.md, Decision 3). The codegen `CartFragment` document embeds its\n * nested fragments, so it is a self-contained read.\n */\nexport function readCartFromCache(client: ApolloClient): CartEntity | null {\n const cartId = orderFormIdVar();\n if (!cartId) return null;\n const cacheId = client.cache.identify({ __typename: 'Cart', id: cartId });\n if (!cacheId) return null;\n return (\n client.cache.readFragment<CartEntity>({ id: cacheId, fragment: CartFragment, fragmentName: 'CartFragment' }) ?? null\n );\n}\n\n/**\n * The `cart` namespace hook. Registered with the first-party action registry via `cartActions`\n * below; the compiler-emitted `CartActionProvider` calls it and threads the narrowed methods into\n * each consumer's `$actions.cart`.\n */\nexport function useCartActions(): CartActions {\n const client = useApolloClient();\n\n const [addMutation] = useMutation(CART_ITEM_ADD);\n const [removeMutation] = useMutation(CART_ITEM_REMOVE);\n const [removeItemsMutation] = useMutation(CART_ITEMS_REMOVE);\n const [increaseMutation] = useMutation(CART_ITEM_QUANTITY_INCREASE);\n const [decreaseMutation] = useMutation(CART_ITEM_QUANTITY_DECREASE);\n const [applyCouponMutation] = useMutation(CART_COUPON_APPLY);\n const [removeCouponMutation] = useMutation(CART_COUPON_REMOVE);\n const [validateMutation] = useMutation(CART_VALIDATE);\n\n const readCart = useCallback((): CartEntity | null => readCartFromCache(client), [client]);\n\n const requireLine = useCallback(\n (id: string): { cart: CartEntity; line: CartItemEntity } | null => {\n const cart = readCart();\n if (!cart) throw new CartNotReadyError();\n const line = cart.items.find((item) => item.id === id);\n if (!line) return null;\n return { cart, line };\n },\n [readCart],\n );\n\n const addItem = useCallback<CartActions['addItem']>(\n async (payload) => {\n cartUserErrorsVar([]);\n try {\n const result = await trackCartWrite(\n addMutation({\n variables: {\n input: { variantId: payload.variantId, quantity: payload.quantity ?? 1, seller: payload.seller },\n },\n }),\n );\n // Very-first add: the server minted a cart from the empty transport context. Hydrate the\n // var so the existing-line handlers unlock without requiring a cart query.\n if (orderFormIdVar() === null) {\n const newId = result.data?.cartItemAdd?.cart?.id ?? null;\n if (newId) orderFormIdVar(newId);\n }\n const errors = result.data?.cartItemAdd?.userErrors ?? [];\n // Bump the add-success pulse only on the clean branch; the post-add behavior components\n // (CartOpenOnAdd / CartRedirectOnAdd) key their effect on it. The userErrors and\n // network-catch branches leave it untouched (specs/fspg-822-minicart-open-on-add.md).\n if (errors.length === 0) cartLastAddVar(cartLastAddVar() + 1);\n return publishWrite(errors);\n } catch (error) {\n console.error('[cart.addItem] cartItemAdd failed', error);\n return publish([NETWORK_USER_ERROR]);\n }\n },\n [addMutation],\n );\n\n const removeItem = useCallback<CartActions['removeItem']>(\n async (payload) => {\n const found = requireLine(payload.id);\n if (!found) return publish([]);\n cartUserErrorsVar([]);\n try {\n const result = await trackCartWrite(\n removeMutation({\n variables: { input: { variantId: found.line.variant.variantId } },\n optimisticResponse: buildOptimisticRemove(found.cart, found.line),\n }),\n );\n return publishWrite(result.data?.cartItemRemove?.userErrors ?? []);\n } catch (error) {\n console.error('[cart.removeItem] cartItemRemove failed', error);\n return publish([NETWORK_USER_ERROR]);\n }\n },\n [requireLine, removeMutation],\n );\n\n const removeItems = useCallback<CartActions['removeItems']>(\n async (payload) => {\n const cart = readCart();\n if (!cart) throw new CartNotReadyError();\n // Client-side tolerance mirroring removeItem's not-found no-op: ids without a cached line\n // are skipped, and the surviving set is deduped before the single mutation.\n const lines = cart.items.filter((item) => payload.ids.includes(item.id));\n if (lines.length === 0) return publish([]);\n const variantIds = [...new Set(lines.map((line) => line.variant.variantId))];\n cartUserErrorsVar([]);\n try {\n const result = await trackCartWrite(\n removeItemsMutation({\n variables: { input: { variantIds } },\n optimisticResponse: buildOptimisticRemoveItems(cart, lines),\n }),\n );\n return publishWrite(result.data?.cartItemsRemove?.userErrors ?? []);\n } catch (error) {\n console.error('[cart.removeItems] cartItemsRemove failed', error);\n return publish([NETWORK_USER_ERROR]);\n }\n },\n [readCart, removeItemsMutation],\n );\n\n const increaseQuantity = useCallback<CartActions['increaseQuantity']>(\n async (payload) => {\n const by = payload.by ?? 1;\n const found = requireLine(payload.id);\n if (!found) return publish([]);\n cartUserErrorsVar([]);\n try {\n const result = await trackCartWrite(\n increaseMutation({\n variables: { input: { variantId: found.line.variant.variantId, quantityToAdd: by } },\n optimisticResponse: buildOptimisticIncrease(found.cart, found.line, by),\n }),\n );\n return publishWrite(result.data?.cartItemQuantityIncrease?.userErrors ?? []);\n } catch (error) {\n console.error('[cart.increaseQuantity] cartItemQuantityIncrease failed', error);\n return publish([NETWORK_USER_ERROR]);\n }\n },\n [requireLine, increaseMutation],\n );\n\n const decreaseQuantity = useCallback<CartActions['decreaseQuantity']>(\n async (payload) => {\n const by = payload.by ?? 1;\n const found = requireLine(payload.id);\n if (!found) return publish([]);\n cartUserErrorsVar([]);\n try {\n const result = await trackCartWrite(\n decreaseMutation({\n variables: { input: { variantId: found.line.variant.variantId, quantityToRemove: by } },\n optimisticResponse: buildOptimisticDecrease(found.cart, found.line, by),\n }),\n );\n return publishWrite(result.data?.cartItemQuantityDecrease?.userErrors ?? []);\n } catch (error) {\n console.error('[cart.decreaseQuantity] cartItemQuantityDecrease failed', error);\n return publish([NETWORK_USER_ERROR]);\n }\n },\n [requireLine, decreaseMutation],\n );\n\n // Coupons are cart-level: no `requireLine` gate (AD-9). No optimistic response and no client\n // rollback — totals and `isUnmatchedCondition` are server-computed and the server rolls back its\n // own single-coupon rejections; the returned cart (spreading the extended CartFragment)\n // self-updates the cache and every reactive subscriber (specs/fspg-830-coupon-entry.md AD-3/AD-8).\n const applyCoupon = useCallback<CartActions['applyCoupon']>(\n async (payload) => {\n cartCouponErrorsVar([]);\n try {\n const result = await trackCartWrite(applyCouponMutation({ variables: { input: { code: payload.code } } }));\n hydrateCartId(result.data?.cartCouponApply?.cart?.id ?? null);\n return publishCouponWrite(result.data?.cartCouponApply?.userErrors ?? []);\n } catch (error) {\n console.error('[cart.applyCoupon] cartCouponApply failed', error);\n return publishCoupon([NETWORK_USER_ERROR]);\n }\n },\n [applyCouponMutation],\n );\n\n const removeCoupon = useCallback<CartActions['removeCoupon']>(\n async (payload) => {\n cartCouponErrorsVar([]);\n try {\n const result = await trackCartWrite(removeCouponMutation({ variables: { input: { code: payload.code } } }));\n hydrateCartId(result.data?.cartCouponRemove?.cart?.id ?? null);\n return publishCouponWrite(result.data?.cartCouponRemove?.userErrors ?? []);\n } catch (error) {\n console.error('[cart.removeCoupon] cartCouponRemove failed', error);\n return publishCoupon([NETWORK_USER_ERROR]);\n }\n },\n [removeCouponMutation],\n );\n\n // Read-only upstream (specs/mini-cart-validate-operation.md): re-simulates the cart and returns it\n // with `variant.availability` corrected, spreading CartFragment so the guard, the per-line alert,\n // and the badge re-render off the cache. Deliberately unlike the item writes: it does NOT register\n // as an in-flight write (it would gate itself) and it does NOT publish to cartUserErrorsVar — the\n // open call is speculative and the pre-checkout call is fail-open, so a failure must raise no error\n // banner (Decision 6). It stamps the freshness window on success so open-on-add does not re-check.\n const validate = useCallback<CartActions['validate']>(async () => {\n try {\n const result = await validateMutation();\n // Hydrate as the coupon writes do: the corrected cart is now in the cache, and the pre-checkout\n // gate finds it by `orderFormIdVar`. Without this a cold var would leave the gate reading null\n // and passing a cart it never actually checked.\n hydrateCartId(result.data?.cartValidate?.cart?.id ?? null);\n const errors = result.data?.cartValidate?.userErrors ?? [];\n if (errors.length === 0) markAvailabilityFresh();\n return errors;\n } catch (error) {\n console.error('[cart.validate] cartValidate failed', error);\n return [NETWORK_USER_ERROR];\n }\n }, [validateMutation]);\n\n return useMemo(\n () => ({\n addItem,\n removeItem,\n removeItems,\n increaseQuantity,\n decreaseQuantity,\n applyCoupon,\n removeCoupon,\n validate,\n }),\n [addItem, removeItem, removeItems, increaseQuantity, decreaseQuantity, applyCoupon, removeCoupon, validate],\n );\n}\n\n/**\n * Declares the `cart` action namespace — the single source of truth for its method/payload metadata,\n * runtime provider, and `use` hook (mirrors `defineComponent`). The native catalog builder\n * (`@vtex/faststore-catalog`'s `buildPackageCatalog`) statically reads this call to emit `actions.json`;\n * at runtime `CartActionProvider` calls `useCartActions` directly.\n */\nexport const cartActions = defineActions({\n namespace: 'cart',\n description: 'Mutation-backed writes against the current cart (consolidates useCartMutations / CartRoot).',\n provider: { name: 'CartActionProvider', importPath: '@vtex/faststore/internal/client' },\n methods: {\n addItem: {\n description: 'Add an item to the cart (async strategy). Creates the cart on first add.',\n payload: [\n { name: 'variantId', type: 'string' },\n { name: 'seller', type: 'string' },\n { name: 'quantity', type: 'number', optional: true },\n ],\n },\n removeItem: {\n description: 'Remove a line from the cart (optimistic strategy).',\n payload: [{ name: 'id', type: 'string' }],\n },\n removeItems: {\n description: 'Remove several lines from the cart in one call (optimistic strategy).',\n payload: [{ name: 'ids', type: 'string[]' }],\n },\n increaseQuantity: {\n description: \"Increase a line's quantity by N (default 1, optimistic strategy).\",\n payload: [\n { name: 'id', type: 'string' },\n { name: 'by', type: 'number', optional: true },\n ],\n },\n decreaseQuantity: {\n description: \"Decrease a line's quantity by N (default 1, optimistic). Removes the line at <= 0.\",\n payload: [\n { name: 'id', type: 'string' },\n { name: 'by', type: 'number', optional: true },\n ],\n },\n applyCoupon: {\n description: 'Apply a coupon code to the cart (async strategy). Server recomputes totals.',\n payload: [{ name: 'code', type: 'string' }],\n },\n removeCoupon: {\n description: 'Remove a coupon code from the cart (async strategy). Server recomputes totals.',\n payload: [{ name: 'code', type: 'string' }],\n },\n validate: {\n description:\n 'Re-check the active cart against the platform and adopt corrected availability (async, read-only upstream).',\n payload: [],\n },\n },\n use: useCartActions,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,YAAY,SAAkB;EAC5B,MAAM,WAAW,iGAAiG;EAClH,KAAK,OAAO;CACd;AACF;AAiDA,MAAM,qBAAoC;CACxC,MAAM;CACN,SAAS;AACX;AAEA,SAAS,QAAQ,QAA4D;CAC3E,kBAAkB,MAAM;CACxB,OAAO;AACT;;AAGA,SAAS,cAAc,QAA4D;CACjF,oBAAoB,MAAM;CAC1B,OAAO;AACT;;;;;;;;AASA,SAAS,aAAa,QAA4D;CAChF,IAAI,OAAO,WAAW,GAAG,sBAAsB;CAC/C,OAAO,QAAQ,MAAM;AACvB;;AAGA,SAAS,mBAAmB,QAA4D;CACtF,IAAI,OAAO,WAAW,GAAG,sBAAsB;CAC/C,OAAO,cAAc,MAAM;AAC7B;;;;;;;AAQA,SAAS,cAAc,QAA6B;CAClD,IAAI,UAAU,eAAe,MAAM,MAAM,eAAe,MAAM;AAChE;;;;;;;;;AAUA,SAAgB,kBAAk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../../../src/sdk/cart/use-cart-actions.ts"],"sourcesContent":["'use client';\n\nimport type { ApolloClient } from '@apollo/client';\nimport { useApolloClient, useMutation } from '@apollo/client/react';\nimport { defineActions } from '@vtex/fs-core';\nimport { useCallback, useMemo } from 'react';\nimport { cartCouponErrorsVar, cartLastAddVar, cartUserErrorsVar, orderFormIdVar } from '../state/cart.js';\nimport {\n CART_COUPON_APPLY,\n CART_COUPON_REMOVE,\n CART_ITEM_ADD,\n CART_ITEM_QUANTITY_DECREASE,\n CART_ITEM_QUANTITY_INCREASE,\n CART_ITEM_REMOVE,\n CART_ITEMS_REMOVE,\n CART_VALIDATE,\n type CartEntity,\n CartFragment,\n type CartItemEntity,\n type CartUserError,\n} from './operations.js';\nimport {\n buildOptimisticDecrease,\n buildOptimisticIncrease,\n buildOptimisticRemove,\n buildOptimisticRemoveItems,\n} from './optimistic.js';\nimport { markAvailabilityFresh, trackCartWrite } from './write-gate.js';\n\n/**\n * The `cart` action namespace — the consolidated, context-free owner of every cart write\n * (docs/storefront-core/reference-free-particle-model.md § The cart write contract, docs/storefront-core/adr-0010-actions-own-the-write-side.md).\n *\n * It replaces `useCartMutations` + the mutation handlers `CartRoot` used to publish through\n * `CartDataContext`. A handler reads the current cart from the normalized Apollo cache (keyed by\n * `orderFormIdVar`), not from component props or React context, so any component anywhere in the\n * tree can dispatch a write through the compiler-injected `$actions.cart.*` prop — the cache is the\n * only meeting point between the read side and the write side (ADR-0010).\n *\n * `userErrors` from every call are published to `cartUserErrorsVar` (cleared at the start of the\n * next call) so `CartError` can surface them without a data context, and also returned to the caller.\n */\n\n/**\n * Thrown by the existing-line handlers (remove / quantity) when invoked before the cart resolves.\n * The first `addItem` mints the cart and hydrates `orderFormIdVar`; until then there is no cached\n * cart entity to read for the optimistic response.\n */\nexport class CartNotReadyError extends Error {\n constructor(message?: string) {\n super(message ?? 'CartNotReadyError: no cart in cache yet; add an item (or load the cart) before mutating a line.');\n this.name = 'CartNotReadyError';\n }\n}\n\nexport type AddItemPayload = Readonly<{\n variantId: string;\n quantity?: number;\n /** Seller global Node ID, e.g. base64(\"Seller:1\"). The server rejects raw ids with INVALID_SELLER_ID. */\n seller: string;\n}>;\n\n/** Existing-line payloads address the line by its opaque cart-item `id`; the handler reads the rest from cache. */\nexport type CartLinePayload = Readonly<{ id: string }>;\n\n/** Batch payloads address several lines by their opaque cart-item `id`s. */\nexport type CartLinesPayload = Readonly<{ ids: readonly string[] }>;\n\nexport type CartQuantityPayload = Readonly<{ id: string; by?: number }>;\n\n/** Coupon writes address the coupon by its `code`; the server resolves the cart from the cookie. */\nexport type CartCouponPayload = Readonly<{ code: string }>;\n\n/**\n * The `cart` namespace surface. Item writes return the resulting `userErrors` (empty on success)\n * and publish them to `cartUserErrorsVar`; coupon writes publish to the dedicated\n * `cartCouponErrorsVar` (docs/storefront-core/reference-free-particle-model.md § The cart write contract).\n */\nexport type CartActions = Readonly<{\n /** Add an item to the cart. Async (no optimistic response). Creates the cart on first add. */\n addItem: (payload: AddItemPayload) => Promise<readonly CartUserError[]>;\n /** Remove a line entirely. Optimistic. */\n removeItem: (payload: CartLinePayload) => Promise<readonly CartUserError[]>;\n /** Remove several lines in one mutation. Optimistic. Ids missing from the cache are skipped. */\n removeItems: (payload: CartLinesPayload) => Promise<readonly CartUserError[]>;\n /** Increase a line's quantity by N (default 1). Optimistic. */\n increaseQuantity: (payload: CartQuantityPayload) => Promise<readonly CartUserError[]>;\n /** Decrease a line's quantity by N (default 1). Optimistic. Removes the line when result <= 0. */\n decreaseQuantity: (payload: CartQuantityPayload) => Promise<readonly CartUserError[]>;\n /** Apply a coupon code. Async (no optimistic). Publishes userErrors to cartCouponErrorsVar. */\n applyCoupon: (payload: CartCouponPayload) => Promise<readonly CartUserError[]>;\n /** Remove a coupon code by code. Async (no optimistic). Publishes userErrors to cartCouponErrorsVar. */\n removeCoupon: (payload: CartCouponPayload) => Promise<readonly CartUserError[]>;\n /**\n * Re-check the active cart against the platform and adopt corrected availability. Async (no\n * optimistic), read-only upstream. Returns userErrors (empty on success) to its caller and stamps\n * the freshness window on success. Unlike the item writes it does NOT publish to\n * `cartUserErrorsVar` — a speculative open-time failure must raise no error banner (Decision 6).\n */\n validate: () => Promise<readonly CartUserError[]>;\n}>;\n\nconst NETWORK_USER_ERROR: CartUserError = {\n code: 'NETWORK_ERROR',\n message: 'Unable to update cart. Please try again.',\n};\n\nfunction publish(errors: readonly CartUserError[]): readonly CartUserError[] {\n cartUserErrorsVar(errors);\n return errors;\n}\n\n/** Coupon-scoped publish — keeps coupon feedback off the shared item-error channel (AD-2). */\nfunction publishCoupon(errors: readonly CartUserError[]): readonly CartUserError[] {\n cartCouponErrorsVar(errors);\n return errors;\n}\n\n/**\n * Publish a write's outcome and, when it came back clean, stamp the availability freshness window —\n * a clean write's payload carries the platform's recomputed cart, which is what lets the\n * validate-on-open call skip (docs/storefront-core/reference-free-particle-model.md § The cart write contract). Used only on paths\n * where a mutation actually reached the server: a `userErrors` response carries `cart: null` and a\n * no-op (unknown line) issues no request, so neither refreshes availability.\n */\nfunction publishWrite(errors: readonly CartUserError[]): readonly CartUserError[] {\n if (errors.length === 0) markAvailabilityFresh();\n return publish(errors);\n}\n\n/** Coupon-channel counterpart of `publishWrite`. */\nfunction publishCouponWrite(errors: readonly CartUserError[]): readonly CartUserError[] {\n if (errors.length === 0) markAvailabilityFresh();\n return publishCoupon(errors);\n}\n\n/**\n * Backfill `orderFormIdVar` from a mutation's returned `cart.id` when local state is still cold.\n * A coupon op can be the first cart write (SSR cold / drawer closed on first load); without this the\n * later `requireLine` paths short-circuit on `orderFormIdVar() === null` and throw `CartNotReadyError`.\n * Mirrors the `addItem` first-add handoff.\n */\nfunction hydrateCartId(cartId: string | null): void {\n if (cartId && orderFormIdVar() === null) orderFormIdVar(cartId);\n}\n\n/**\n * Read the live cart entity from the normalized cache (ADR-0010), keyed by `orderFormIdVar`. Returns\n * null before the cart is minted/loaded. Module-level so it can be shared with the read-only callers\n * that live outside this hook — the pre-checkout gate re-reads the corrected cart this way after\n * `validate` resolves, because Apollo commits the mutation's cache write before the promise settles\n * (docs/storefront-core/reference-cart.md § Validation). The codegen `CartFragment` document embeds its\n * nested fragments, so it is a self-contained read.\n */\nexport function readCartFromCache(client: ApolloClient): CartEntity | null {\n const cartId = orderFormIdVar();\n if (!cartId) return null;\n const cacheId = client.cache.identify({ __typename: 'Cart', id: cartId });\n if (!cacheId) return null;\n return (\n client.cache.readFragment<CartEntity>({ id: cacheId, fragment: CartFragment, fragmentName: 'CartFragment' }) ?? null\n );\n}\n\n/**\n * The `cart` namespace hook. Registered with the first-party action registry via `cartActions`\n * below; the compiler-emitted `CartActionProvider` calls it and threads the narrowed methods into\n * each consumer's `$actions.cart`.\n */\nexport function useCartActions(): CartActions {\n const client = useApolloClient();\n\n const [addMutation] = useMutation(CART_ITEM_ADD);\n const [removeMutation] = useMutation(CART_ITEM_REMOVE);\n const [removeItemsMutation] = useMutation(CART_ITEMS_REMOVE);\n const [increaseMutation] = useMutation(CART_ITEM_QUANTITY_INCREASE);\n const [decreaseMutation] = useMutation(CART_ITEM_QUANTITY_DECREASE);\n const [applyCouponMutation] = useMutation(CART_COUPON_APPLY);\n const [removeCouponMutation] = useMutation(CART_COUPON_REMOVE);\n const [validateMutation] = useMutation(CART_VALIDATE);\n\n const readCart = useCallback((): CartEntity | null => readCartFromCache(client), [client]);\n\n const requireLine = useCallback(\n (id: string): { cart: CartEntity; line: CartItemEntity } | null => {\n const cart = readCart();\n if (!cart) throw new CartNotReadyError();\n const line = cart.items.find((item) => item.id === id);\n if (!line) return null;\n return { cart, line };\n },\n [readCart],\n );\n\n const addItem = useCallback<CartActions['addItem']>(\n async (payload) => {\n cartUserErrorsVar([]);\n try {\n const result = await trackCartWrite(\n addMutation({\n variables: {\n input: { variantId: payload.variantId, quantity: payload.quantity ?? 1, seller: payload.seller },\n },\n }),\n );\n // Very-first add: the server minted a cart from the empty transport context. Hydrate the\n // var so the existing-line handlers unlock without requiring a cart query.\n if (orderFormIdVar() === null) {\n const newId = result.data?.cartItemAdd?.cart?.id ?? null;\n if (newId) orderFormIdVar(newId);\n }\n const errors = result.data?.cartItemAdd?.userErrors ?? [];\n // Bump the add-success pulse only on the clean branch; the post-add behavior components\n // (CartOpenOnAdd / CartRedirectOnAdd) key their effect on it. The userErrors and\n // network-catch branches leave it untouched (docs/storefront-core/reference-free-particle-model.md § The cart write contract).\n if (errors.length === 0) cartLastAddVar(cartLastAddVar() + 1);\n return publishWrite(errors);\n } catch (error) {\n console.error('[cart.addItem] cartItemAdd failed', error);\n return publish([NETWORK_USER_ERROR]);\n }\n },\n [addMutation],\n );\n\n const removeItem = useCallback<CartActions['removeItem']>(\n async (payload) => {\n const found = requireLine(payload.id);\n if (!found) return publish([]);\n cartUserErrorsVar([]);\n try {\n const result = await trackCartWrite(\n removeMutation({\n variables: { input: { variantId: found.line.variant.variantId } },\n optimisticResponse: buildOptimisticRemove(found.cart, found.line),\n }),\n );\n return publishWrite(result.data?.cartItemRemove?.userErrors ?? []);\n } catch (error) {\n console.error('[cart.removeItem] cartItemRemove failed', error);\n return publish([NETWORK_USER_ERROR]);\n }\n },\n [requireLine, removeMutation],\n );\n\n const removeItems = useCallback<CartActions['removeItems']>(\n async (payload) => {\n const cart = readCart();\n if (!cart) throw new CartNotReadyError();\n // Client-side tolerance mirroring removeItem's not-found no-op: ids without a cached line\n // are skipped, and the surviving set is deduped before the single mutation.\n const lines = cart.items.filter((item) => payload.ids.includes(item.id));\n if (lines.length === 0) return publish([]);\n const variantIds = [...new Set(lines.map((line) => line.variant.variantId))];\n cartUserErrorsVar([]);\n try {\n const result = await trackCartWrite(\n removeItemsMutation({\n variables: { input: { variantIds } },\n optimisticResponse: buildOptimisticRemoveItems(cart, lines),\n }),\n );\n return publishWrite(result.data?.cartItemsRemove?.userErrors ?? []);\n } catch (error) {\n console.error('[cart.removeItems] cartItemsRemove failed', error);\n return publish([NETWORK_USER_ERROR]);\n }\n },\n [readCart, removeItemsMutation],\n );\n\n const increaseQuantity = useCallback<CartActions['increaseQuantity']>(\n async (payload) => {\n const by = payload.by ?? 1;\n const found = requireLine(payload.id);\n if (!found) return publish([]);\n cartUserErrorsVar([]);\n try {\n const result = await trackCartWrite(\n increaseMutation({\n variables: { input: { variantId: found.line.variant.variantId, quantityToAdd: by } },\n optimisticResponse: buildOptimisticIncrease(found.cart, found.line, by),\n }),\n );\n return publishWrite(result.data?.cartItemQuantityIncrease?.userErrors ?? []);\n } catch (error) {\n console.error('[cart.increaseQuantity] cartItemQuantityIncrease failed', error);\n return publish([NETWORK_USER_ERROR]);\n }\n },\n [requireLine, increaseMutation],\n );\n\n const decreaseQuantity = useCallback<CartActions['decreaseQuantity']>(\n async (payload) => {\n const by = payload.by ?? 1;\n const found = requireLine(payload.id);\n if (!found) return publish([]);\n cartUserErrorsVar([]);\n try {\n const result = await trackCartWrite(\n decreaseMutation({\n variables: { input: { variantId: found.line.variant.variantId, quantityToRemove: by } },\n optimisticResponse: buildOptimisticDecrease(found.cart, found.line, by),\n }),\n );\n return publishWrite(result.data?.cartItemQuantityDecrease?.userErrors ?? []);\n } catch (error) {\n console.error('[cart.decreaseQuantity] cartItemQuantityDecrease failed', error);\n return publish([NETWORK_USER_ERROR]);\n }\n },\n [requireLine, decreaseMutation],\n );\n\n // Coupons are cart-level: no `requireLine` gate (AD-9). No optimistic response and no client\n // rollback — totals and `isUnmatchedCondition` are server-computed and the server rolls back its\n // own single-coupon rejections; the returned cart (spreading the extended CartFragment)\n // self-updates the cache and every reactive subscriber (docs/storefront-core/reference-free-particle-model.md § The cart write contract).\n const applyCoupon = useCallback<CartActions['applyCoupon']>(\n async (payload) => {\n cartCouponErrorsVar([]);\n try {\n const result = await trackCartWrite(applyCouponMutation({ variables: { input: { code: payload.code } } }));\n hydrateCartId(result.data?.cartCouponApply?.cart?.id ?? null);\n return publishCouponWrite(result.data?.cartCouponApply?.userErrors ?? []);\n } catch (error) {\n console.error('[cart.applyCoupon] cartCouponApply failed', error);\n return publishCoupon([NETWORK_USER_ERROR]);\n }\n },\n [applyCouponMutation],\n );\n\n const removeCoupon = useCallback<CartActions['removeCoupon']>(\n async (payload) => {\n cartCouponErrorsVar([]);\n try {\n const result = await trackCartWrite(removeCouponMutation({ variables: { input: { code: payload.code } } }));\n hydrateCartId(result.data?.cartCouponRemove?.cart?.id ?? null);\n return publishCouponWrite(result.data?.cartCouponRemove?.userErrors ?? []);\n } catch (error) {\n console.error('[cart.removeCoupon] cartCouponRemove failed', error);\n return publishCoupon([NETWORK_USER_ERROR]);\n }\n },\n [removeCouponMutation],\n );\n\n // Read-only upstream (docs/storefront-core/reference-free-particle-model.md § The cart write contract): re-simulates the cart and returns it\n // with `variant.availability` corrected, spreading CartFragment so the guard, the per-line alert,\n // and the badge re-render off the cache. Deliberately unlike the item writes: it does NOT register\n // as an in-flight write (it would gate itself) and it does NOT publish to cartUserErrorsVar — the\n // open call is speculative and the pre-checkout call is fail-open, so a failure must raise no error\n // banner (Decision 6). It stamps the freshness window on success so open-on-add does not re-check.\n const validate = useCallback<CartActions['validate']>(async () => {\n try {\n const result = await validateMutation();\n // Hydrate as the coupon writes do: the corrected cart is now in the cache, and the pre-checkout\n // gate finds it by `orderFormIdVar`. Without this a cold var would leave the gate reading null\n // and passing a cart it never actually checked.\n hydrateCartId(result.data?.cartValidate?.cart?.id ?? null);\n const errors = result.data?.cartValidate?.userErrors ?? [];\n if (errors.length === 0) markAvailabilityFresh();\n return errors;\n } catch (error) {\n console.error('[cart.validate] cartValidate failed', error);\n return [NETWORK_USER_ERROR];\n }\n }, [validateMutation]);\n\n return useMemo(\n () => ({\n addItem,\n removeItem,\n removeItems,\n increaseQuantity,\n decreaseQuantity,\n applyCoupon,\n removeCoupon,\n validate,\n }),\n [addItem, removeItem, removeItems, increaseQuantity, decreaseQuantity, applyCoupon, removeCoupon, validate],\n );\n}\n\n/**\n * Declares the `cart` action namespace — the single source of truth for its method/payload metadata,\n * runtime provider, and `use` hook (mirrors `defineComponent`). The native catalog builder\n * (`@vtex/faststore-catalog`'s `buildPackageCatalog`) statically reads this call to emit `actions.json`;\n * at runtime `CartActionProvider` calls `useCartActions` directly.\n */\nexport const cartActions = defineActions({\n namespace: 'cart',\n description: 'Mutation-backed writes against the current cart (consolidates useCartMutations / CartRoot).',\n provider: { name: 'CartActionProvider', importPath: '@vtex/faststore/internal/client' },\n methods: {\n addItem: {\n description: 'Add an item to the cart (async strategy). Creates the cart on first add.',\n payload: [\n { name: 'variantId', type: 'string' },\n { name: 'seller', type: 'string' },\n { name: 'quantity', type: 'number', optional: true },\n ],\n },\n removeItem: {\n description: 'Remove a line from the cart (optimistic strategy).',\n payload: [{ name: 'id', type: 'string' }],\n },\n removeItems: {\n description: 'Remove several lines from the cart in one call (optimistic strategy).',\n payload: [{ name: 'ids', type: 'string[]' }],\n },\n increaseQuantity: {\n description: \"Increase a line's quantity by N (default 1, optimistic strategy).\",\n payload: [\n { name: 'id', type: 'string' },\n { name: 'by', type: 'number', optional: true },\n ],\n },\n decreaseQuantity: {\n description: \"Decrease a line's quantity by N (default 1, optimistic). Removes the line at <= 0.\",\n payload: [\n { name: 'id', type: 'string' },\n { name: 'by', type: 'number', optional: true },\n ],\n },\n applyCoupon: {\n description: 'Apply a coupon code to the cart (async strategy). Server recomputes totals.',\n payload: [{ name: 'code', type: 'string' }],\n },\n removeCoupon: {\n description: 'Remove a coupon code from the cart (async strategy). Server recomputes totals.',\n payload: [{ name: 'code', type: 'string' }],\n },\n validate: {\n description:\n 'Re-check the active cart against the platform and adopt corrected availability (async, read-only upstream).',\n payload: [],\n },\n },\n use: useCartActions,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,YAAY,SAAkB;EAC5B,MAAM,WAAW,iGAAiG;EAClH,KAAK,OAAO;CACd;AACF;AAiDA,MAAM,qBAAoC;CACxC,MAAM;CACN,SAAS;AACX;AAEA,SAAS,QAAQ,QAA4D;CAC3E,kBAAkB,MAAM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B,aAAa;GACb,SAAS,CACP;IAAE,MAAM;IAAM,MAAM;GAAS,GAC7B;IAAE,MAAM;IAAM,MAAM;IAAU,UAAU;GAAK,CAC/C;EACF;EACA,aAAa;GACX,aAAa;GACb,SAAS,CAAC;IAAE,MAAM;IAAQ,MAAM;GAAS,CAAC;EAC5C;EACA,cAAc;GACZ,aAAa;GACb,SAAS,CAAC;IAAE,MAAM;IAAQ,MAAM;GAAS,CAAC;EAC5C;EACA,UAAU;GACR,aACE;GACF,SAAS,CAAC;EACZ;CACF;CACA,KAAK;AACP,CAAC"}
|
|
@@ -5,7 +5,7 @@ import { useApolloClient, useReactiveVar } from "@apollo/client/react";
|
|
|
5
5
|
import { useEffect, useRef } from "react";
|
|
6
6
|
//#region src/sdk/cart/use-cart-validate-on-open.ts
|
|
7
7
|
/**
|
|
8
|
-
* Runs stock validation when the mini-cart overlay opens (
|
|
8
|
+
* Runs stock validation when the mini-cart overlay opens (docs/storefront-core/reference-cart.md § Validation).
|
|
9
9
|
*
|
|
10
10
|
* `miniCartOpenVar` is the overlay's single source of truth — the add-pulse open, the header trigger,
|
|
11
11
|
* and manual close all route through it — so watching its closed→open edge covers every way the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-cart-validate-on-open.js","names":[],"sources":["../../../src/sdk/cart/use-cart-validate-on-open.ts"],"sourcesContent":["'use client';\n\nimport { useApolloClient, useReactiveVar } from '@apollo/client/react';\nimport { useEffect, useRef } from 'react';\nimport {\n CART_VALIDATE_STALENESS_MS,\n cartAvailabilityFreshAtVar,\n cartWritesInFlightVar,\n miniCartOpenVar,\n} from '../state/cart.js';\nimport { readCartFromCache } from './use-cart-actions.js';\n\n/**\n * Runs stock validation when the mini-cart overlay opens (
|
|
1
|
+
{"version":3,"file":"use-cart-validate-on-open.js","names":[],"sources":["../../../src/sdk/cart/use-cart-validate-on-open.ts"],"sourcesContent":["'use client';\n\nimport { useApolloClient, useReactiveVar } from '@apollo/client/react';\nimport { useEffect, useRef } from 'react';\nimport {\n CART_VALIDATE_STALENESS_MS,\n cartAvailabilityFreshAtVar,\n cartWritesInFlightVar,\n miniCartOpenVar,\n} from '../state/cart.js';\nimport { readCartFromCache } from './use-cart-actions.js';\n\n/**\n * Runs stock validation when the mini-cart overlay opens (docs/storefront-core/reference-cart.md § Validation).\n *\n * `miniCartOpenVar` is the overlay's single source of truth — the add-pulse open, the header trigger,\n * and manual close all route through it — so watching its closed→open edge covers every way the\n * drawer opens. The call is bounded and cooperative: it fires at most once per transition, and skips\n * when there is nothing to gain — no validate action wired, a cart write in flight, availability\n * refreshed within the staleness window (which is why open-on-add does not re-validate), or an empty\n * cart. `validate` is the compiler-injected `$actions.cart.validate`; when it is absent the hook is a\n * no-op, so a store without the action wired pays nothing.\n *\n * A dispatch is reserved synchronously with a ref latch, cleared when the call settles. Freshness is\n * only stamped once `validate` resolves, so a close-and-reopen during that window would otherwise slip\n * past the staleness guard and fire a second call; the latch closes that gap.\n */\nexport function useCartValidateOnOpen(validate: (() => Promise<unknown>) | undefined): void {\n const client = useApolloClient();\n const open = useReactiveVar(miniCartOpenVar);\n const wasOpen = useRef(open);\n const pending = useRef(false);\n\n useEffect(() => {\n const opened = open && !wasOpen.current;\n wasOpen.current = open;\n if (!opened || !validate || pending.current) return;\n // A write in flight (or one that just settled, inside the window) already refreshed availability.\n if (cartWritesInFlightVar() > 0) return;\n if (Date.now() - cartAvailabilityFreshAtVar() < CART_VALIDATE_STALENESS_MS) return;\n // Nothing to validate on an empty cart, and T1 would only round-trip a single read for it.\n const cart = readCartFromCache(client);\n if (!cart || cart.items.length === 0) return;\n pending.current = true;\n // The current wiring never rejects (useCartActions().validate catches and resolves with\n // [NETWORK_USER_ERROR]); this guards a differently-injected validate so a rejection cannot\n // escape as an unhandled promise rejection.\n void Promise.resolve(validate())\n .catch((error) => {\n console.error('[cart.validateOnOpen] validate rejected', error);\n })\n .finally(() => {\n pending.current = false;\n });\n }, [open, validate, client]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,sBAAsB,UAAsD;CAC1F,MAAM,SAAS,gBAAgB;CAC/B,MAAM,OAAO,eAAe,eAAe;CAC3C,MAAM,UAAU,OAAO,IAAI;CAC3B,MAAM,UAAU,OAAO,KAAK;CAE5B,gBAAgB;EACd,MAAM,SAAS,QAAQ,CAAC,QAAQ;EAChC,QAAQ,UAAU;EAClB,IAAI,CAAC,UAAU,CAAC,YAAY,QAAQ,SAAS;EAE7C,IAAI,sBAAsB,IAAI,GAAG;EACjC,IAAI,KAAK,IAAI,IAAI,2BAA2B,IAAA,KAAgC;EAE5E,MAAM,OAAO,kBAAkB,MAAM;EACrC,IAAI,CAAC,QAAQ,KAAK,MAAM,WAAW,GAAG;EACtC,QAAQ,UAAU;EAIlB,QAAa,QAAQ,SAAS,CAAC,CAAC,CAC7B,OAAO,UAAU;GAChB,QAAQ,MAAM,2CAA2C,KAAK;EAChE,CAAC,CAAC,CACD,cAAc;GACb,QAAQ,UAAU;EACpB,CAAC;CACL,GAAG;EAAC;EAAM;EAAU;CAAM,CAAC;AAC7B"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { cartAvailabilityFreshAtVar, cartWritesInFlightVar } from "../state/cart.js";
|
|
2
2
|
//#region src/sdk/cart/write-gate.ts
|
|
3
3
|
/**
|
|
4
|
-
* In-flight cart-write registry (
|
|
4
|
+
* In-flight cart-write registry (docs/storefront-core/reference-free-particle-model.md § The cart write contract).
|
|
5
5
|
*
|
|
6
6
|
* The stock-validation wiring needs two things the mutation contract never had to expose, because
|
|
7
7
|
* the open-time validate is the first cart call that is not user-initiated:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"write-gate.js","names":[],"sources":["../../../src/sdk/cart/write-gate.ts"],"sourcesContent":["import { cartAvailabilityFreshAtVar, cartWritesInFlightVar } from '../state/cart.js';\n\n/**\n * In-flight cart-write registry (
|
|
1
|
+
{"version":3,"file":"write-gate.js","names":[],"sources":["../../../src/sdk/cart/write-gate.ts"],"sourcesContent":["import { cartAvailabilityFreshAtVar, cartWritesInFlightVar } from '../state/cart.js';\n\n/**\n * In-flight cart-write registry (docs/storefront-core/reference-free-particle-model.md § The cart write contract).\n *\n * The stock-validation wiring needs two things the mutation contract never had to expose, because\n * the open-time validate is the first cart call that is not user-initiated:\n *\n * - an observable \"is a write running\" signal, so the open call can *skip* while one is (that\n * write's response already carries current availability); and\n * - an `await`-settlement primitive, so the pre-checkout call can *wait* for any write before it\n * re-checks the cart it is about to send to checkout.\n *\n * Both derive from one module-scoped set of pending write promises. `validate` is read-only upstream\n * and must never register here — it would gate itself.\n */\n\nconst inFlight = new Set<Promise<unknown>>();\n\n/**\n * Stamp \"availability is fresh as of now\". Called only where the client actually received current\n * availability: a cart write that came back clean, or a successful `validate`. A write answered with\n * `userErrors` carries `cart: null` (mutation contract), so it learned nothing and must not stamp —\n * otherwise the next overlay open would skip validation on the strength of a rejected write.\n */\nexport function markAvailabilityFresh(): void {\n cartAvailabilityFreshAtVar(Date.now());\n}\n\n/**\n * Register a cart write's promise for the lifetime of the call, publishing the reactive in-flight\n * count so the validate-on-open call can skip while a write is outstanding. Tracking only — the\n * freshness stamp belongs to the caller, which is the only place that can see whether the payload\n * came back clean. Returns the same promise so callers can `await trackCartWrite(mutation(...))`.\n */\nexport function trackCartWrite<T>(promise: Promise<T>): Promise<T> {\n inFlight.add(promise);\n cartWritesInFlightVar(inFlight.size);\n const clear = () => {\n inFlight.delete(promise);\n cartWritesInFlightVar(inFlight.size);\n };\n promise.then(clear, clear);\n return promise;\n}\n\n/**\n * Resolve once every write registered at call time has settled (fulfilled or rejected). Writes\n * started afterwards are not awaited — this captures \"any in-flight write\" at the moment the\n * pre-checkout call fires, which is exactly the ordering guarantee the checkout gate needs.\n */\nexport function awaitCartWrites(): Promise<void> {\n return Promise.allSettled(inFlight).then(() => undefined);\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiBA,MAAM,2BAAW,IAAI,IAAsB;;;;;;;AAQ3C,SAAgB,wBAA8B;CAC5C,2BAA2B,KAAK,IAAI,CAAC;AACvC;;;;;;;AAQA,SAAgB,eAAkB,SAAiC;CACjE,SAAS,IAAI,OAAO;CACpB,sBAAsB,SAAS,IAAI;CACnC,MAAM,cAAc;EAClB,SAAS,OAAO,OAAO;EACvB,sBAAsB,SAAS,IAAI;CACrC;CACA,QAAQ,KAAK,OAAO,KAAK;CACzB,OAAO;AACT;;;;;;AAOA,SAAgB,kBAAiC;CAC/C,OAAO,QAAQ,WAAW,QAAQ,CAAC,CAAC,WAAW,KAAA,CAAS;AAC1D"}
|
|
@@ -30,7 +30,7 @@ export type ReactiveRootContextValue<TData = unknown> = Readonly<{
|
|
|
30
30
|
/**
|
|
31
31
|
* Error from the underlying useQuery. With non-null root fields (e.g. `cart: Cart!`), a failed
|
|
32
32
|
* fetch nulls the whole operation's `data` — descendants need this to tell "fetch failed" apart
|
|
33
|
-
* from "entity is legitimately absent" (
|
|
33
|
+
* from "entity is legitimately absent" (docs/storefront-core/reference-free-particle-model.md § Read side — data).
|
|
34
34
|
*/
|
|
35
35
|
error: ErrorLike | undefined;
|
|
36
36
|
}>;
|
|
@@ -44,7 +44,7 @@ export declare const ReactiveRootContext: import("react").Context<Readonly<{
|
|
|
44
44
|
/**
|
|
45
45
|
* Error from the underlying useQuery. With non-null root fields (e.g. `cart: Cart!`), a failed
|
|
46
46
|
* fetch nulls the whole operation's `data` — descendants need this to tell "fetch failed" apart
|
|
47
|
-
* from "entity is legitimately absent" (
|
|
47
|
+
* from "entity is legitimately absent" (docs/storefront-core/reference-free-particle-model.md § Read side — data).
|
|
48
48
|
*/
|
|
49
49
|
error: ErrorLike | undefined;
|
|
50
50
|
}>>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"page-reactive-data-root.js","names":[],"sources":["../../../src/sdk/data/page-reactive-data-root.tsx"],"sourcesContent":["'use client';\n\nimport type { ErrorLike, OperationVariables, ReactiveVar, TypedDocumentNode } from '@apollo/client';\nimport { useApolloClient, useQuery } from '@apollo/client/react';\nimport { type DocumentNode, Kind, type OperationDefinitionNode } from 'graphql';\nimport { createContext, type ReactNode, useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\n\n// Reactive vars resolvable by name from a Server Component. Functions cannot cross the\n// Server→Client boundary in RSC, so the compiler emits string keys and this component resolves\n// them at runtime. New reactive vars must be registered here to be addressable from generated\n// pages. Currently empty: cart context travels on the transport, so no cart entry is needed\n// (specs/cart-context-client-migrate.md).\nconst REACTIVE_VAR_REGISTRY: Record<string, ReactiveVar<unknown>> = {};\n\n/**\n * Compile-time-stable map keyed by the operation's variable names. Each value is either an Apollo\n * reactive variable (`makeVar`) or the string name of one registered in REACTIVE_VAR_REGISTRY —\n * Server Components must pass strings because functions cannot cross the RSC boundary. Vars that\n * have not yet resolved should hold `null`; the runtime treats both `null` and `undefined` as\n * \"not yet ready\" and keeps `useQuery` skipped.\n */\nexport type ClientVariablesMap<TVars> = Partial<{\n [K in keyof TVars]: ReactiveVar<TVars[K] | null> | string;\n}>;\n\nfunction resolveReactiveVar(value: ReactiveVar<unknown> | string): ReactiveVar<unknown> | undefined {\n if (typeof value === 'function') return value;\n const resolved = REACTIVE_VAR_REGISTRY[value];\n if (!resolved) {\n throw new Error(\n `PageReactiveDataRoot: clientVariables entry \"${value}\" is not registered. Add it to REACTIVE_VAR_REGISTRY in page-reactive-data-root.tsx.`,\n );\n }\n return resolved;\n}\n\nexport type PageReactiveDataRootProps<TData, TVars extends OperationVariables> = Readonly<{\n /** The composed PAGE_QUERY operation document. */\n query: TypedDocumentNode<TData, TVars>;\n /** Variables the server used when calling fetchPageData. Only used to seed the client cache. */\n serverVariables?: TVars;\n /** Server-rendered PAGE_QUERY result. When present and shape-matched, seeded into the cache once. */\n initialData?: TData | null;\n /** Reactive vars whose current values are merged into operation variables at render time. */\n clientVariables?: ClientVariablesMap<TVars>;\n children: ReactNode;\n}>;\n\nexport type ReactiveRootContextValue<TData = unknown> = Readonly<{\n /** Current root query data exposed to descendant `ReactiveDataProvider`s. */\n rootQueryData: TData | undefined;\n /** Whether the underlying useQuery is currently in flight. */\n loading: boolean;\n /** False when at least one required variable has not been provided yet. */\n hasAllRequiredVariables: boolean;\n /**\n * Error from the underlying useQuery. With non-null root fields (e.g. `cart: Cart!`), a failed\n * fetch nulls the whole operation's `data` — descendants need this to tell \"fetch failed\" apart\n * from \"entity is legitimately absent\" (specs/cart-context-client-migrate.md US-5).\n */\n error: ErrorLike | undefined;\n}>;\n\nexport const ReactiveRootContext = createContext<ReactiveRootContextValue>({\n rootQueryData: undefined,\n loading: false,\n hasAllRequiredVariables: false,\n error: undefined,\n});\n\nfunction getOperationDefinition(query: DocumentNode): OperationDefinitionNode | undefined {\n for (const definition of query.definitions) {\n if (definition.kind === Kind.OPERATION_DEFINITION) return definition;\n }\n return undefined;\n}\n\nfunction getRequiredVariableNames(query: DocumentNode): string[] {\n const op = getOperationDefinition(query);\n if (!op?.variableDefinitions) return [];\n const required: string[] = [];\n for (const def of op.variableDefinitions) {\n if (def.type.kind === Kind.NON_NULL_TYPE && def.defaultValue === undefined) {\n required.push(def.variable.name.value);\n }\n }\n return required;\n}\n\nfunction getTopLevelFieldNames(query: DocumentNode): Set<string> {\n const op = getOperationDefinition(query);\n const names = new Set<string>();\n if (!op) return names;\n for (const sel of op.selectionSet.selections) {\n if (sel.kind === Kind.FIELD) {\n names.add((sel.alias ?? sel.name).value);\n }\n }\n return names;\n}\n\nfunction shapeMatches(query: DocumentNode, data: unknown): boolean {\n if (data == null || typeof data !== 'object') return false;\n const expected = getTopLevelFieldNames(query);\n if (expected.size === 0) return false;\n const actual = data as Record<string, unknown>;\n // Require AT LEAST ONE top-level field name to be present in `data`. The operation's full\n // top-level shape may include fields the server did not return; partial seeds still help. A total\n // miss (no overlap at all) signals a shape mismatch and we skip the seed.\n for (const key of expected) {\n if (key in actual) return true;\n }\n return false;\n}\n\n/**\n * Reads the current values of every reactive var in `clientVariables` into a plain object via a\n * single `useSyncExternalStore` call (no hooks-in-loop). Apollo's `ReactiveVar.onNextChange` fires\n * once per registration, so the subscriber re-attaches after each notification to stay listening.\n */\nfunction useClientVariableValues<TVars>(clientVariables: ClientVariablesMap<TVars> | undefined): Partial<TVars> {\n // Keep the latest map identity reachable from inside subscribe()/getSnapshot() without forcing\n // useSyncExternalStore to tear down the underlying subscription.\n const varsRef = useRef(clientVariables);\n // react-doctor-disable-next-line no-ref-current-in-render -- keeps the latest map reachable from the stable subscribe()/getSnapshot() callbacks below\n varsRef.current = clientVariables;\n\n const subscribe = useCallback((notify: () => void): (() => void) => {\n const cv = varsRef.current;\n if (!cv) return () => {};\n\n const activeUnsubs: Array<() => void> = [];\n let cancelled = false;\n\n const attach = (rv: ReactiveVar<unknown>): void => {\n if (cancelled) return;\n const unsub = rv.onNextChange(() => {\n notify();\n // onNextChange fires only once — re-attach to keep listening for subsequent changes.\n attach(rv);\n });\n activeUnsubs.push(unsub);\n };\n\n for (const rv of Object.values(cv)) {\n if (rv === undefined || rv === null) continue;\n const resolved = resolveReactiveVar(rv as ReactiveVar<unknown> | string);\n if (resolved) attach(resolved);\n }\n\n return () => {\n cancelled = true;\n for (const u of activeUnsubs) u();\n };\n }, []);\n\n const lastSnapshotRef = useRef<{ json: string; value: Record<string, unknown> } | null>(null);\n\n const getSnapshot = (): string => {\n const cv = varsRef.current;\n const snap: Record<string, unknown> = {};\n if (cv) {\n for (const [key, reactiveVar] of Object.entries(cv)) {\n if (reactiveVar === undefined || reactiveVar === null) continue;\n const resolved = resolveReactiveVar(reactiveVar as ReactiveVar<unknown> | string);\n if (!resolved) continue;\n const value = resolved();\n if (value !== null && value !== undefined) snap[key] = value;\n }\n }\n const json = JSON.stringify(snap);\n // useSyncExternalStore expects a stable snapshot reference until the value changes (Object.is\n // identity check) — return the cached `json` whenever the contents are unchanged.\n if (lastSnapshotRef.current && lastSnapshotRef.current.json === json) {\n return lastSnapshotRef.current.json;\n }\n lastSnapshotRef.current = { json, value: snap };\n return json;\n };\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n return (lastSnapshotRef.current?.value ?? {}) as Partial<TVars>;\n}\n\nexport function PageReactiveDataRoot<TData = unknown, TVars extends OperationVariables = OperationVariables>(\n props: PageReactiveDataRootProps<TData, TVars>,\n): ReactNode {\n const { query, serverVariables, initialData, clientVariables, children } = props;\n const client = useApolloClient();\n const seededRef = useRef(false);\n\n const clientValues = useClientVariableValues<TVars>(clientVariables);\n const mergedVariables = { ...(serverVariables ?? ({} as TVars)), ...clientValues } as TVars;\n\n const requiredNames = getRequiredVariableNames(query);\n const mergedRecord = mergedVariables as Record<string, unknown>;\n const hasAllRequiredVariables = requiredNames.every((name) => {\n const v = mergedRecord[name];\n return v !== null && v !== undefined;\n });\n\n // Ref- and shape-guarded one-time cache seed from server props. We use `useEffect` (not\n // `useLayoutEffect`) to avoid the SSR-pass warning emitted by React 19 — the resulting \"first\n // render shows fallbackData, second render shows cache slice\" behaviour is acceptable because\n // initialData is the same value `ReactiveDataProvider` falls back to anyway.\n useEffect(() => {\n if (seededRef.current) return;\n if (!serverVariables || initialData == null) return;\n if (!shapeMatches(query, initialData)) return;\n client.cache.writeQuery({ query, variables: serverVariables, data: initialData });\n seededRef.current = true;\n }, [client, query, serverVariables, initialData]);\n\n const { data, loading, error } = useQuery(query, {\n variables: mergedVariables,\n fetchPolicy: 'cache-first',\n skip: !hasAllRequiredVariables,\n });\n\n const contextValue: ReactiveRootContextValue<TData> = useMemo(\n () => ({\n rootQueryData: (data ?? undefined) as TData | undefined,\n loading,\n hasAllRequiredVariables,\n error,\n }),\n [data, loading, hasAllRequiredVariables, error],\n );\n\n return (\n <ReactiveRootContext.Provider value={contextValue as ReactiveRootContextValue}>\n {children}\n </ReactiveRootContext.Provider>\n );\n}\n"],"mappings":";;;;;;AAYA,MAAM,wBAA8D,CAAC;AAarE,SAAS,mBAAmB,OAAwE;CAClG,IAAI,OAAO,UAAU,YAAY,OAAO;CACxC,MAAM,WAAW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Y,OAAO,KAAK;CAE9B,MAAM,eAAe,wBAA+B,eAAe;CACnE,MAAM,kBAAkB;EAAE,GAAI,mBAAoB,CAAC;EAAc,GAAG;CAAa;CAEjF,MAAM,gBAAgB,yBAAyB,KAAK;CACpD,MAAM,eAAe;CACrB,MAAM,0BAA0B,cAAc,OAAO,SAAS;EAC5D,MAAM,IAAI,aAAa;EACvB,OAAO,MAAM,QAAQ,MAAM,KAAA;CAC7B,CAAC;CAMD,gBAAgB;EACd,IAAI,UAAU,SAAS;EACvB,IAAI,CAAC,mBAAmB,eAAe,MAAM;EAC7C,IAAI,CAAC,aAAa,OAAO,WAAW,GAAG;EACvC,OAAO,MAAM,WAAW;GAAE;GAAO,WAAW;GAAiB,MAAM;EAAY,CAAC;EAChF,UAAU,UAAU;CACtB,GAAG;EAAC;EAAQ;EAAO;EAAiB;CAAW,CAAC;CAEhD,MAAM,EAAE,MAAM,SAAS,UAAU,SAAS,OAAO;EAC/C,WAAW;EACX,aAAa;EACb,MAAM,CAAC;CACT,CAAC;CAED,MAAM,eAAgD,eAC7C;EACL,eAAgB,QAAQ,KAAA;EACxB;EACA;EACA;CACF,IACA;EAAC;EAAM;EAAS;EAAyB;CAAK,CAChD;CAEA,OACE,oBAAC,oBAAoB,UAArB;EAA8B,OAAO;EAClC;CAC2B,CAAA;AAElC"}
|
|
1
|
+
{"version":3,"file":"page-reactive-data-root.js","names":[],"sources":["../../../src/sdk/data/page-reactive-data-root.tsx"],"sourcesContent":["'use client';\n\nimport type { ErrorLike, OperationVariables, ReactiveVar, TypedDocumentNode } from '@apollo/client';\nimport { useApolloClient, useQuery } from '@apollo/client/react';\nimport { type DocumentNode, Kind, type OperationDefinitionNode } from 'graphql';\nimport { createContext, type ReactNode, useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react';\n\n// Reactive vars resolvable by name from a Server Component. Functions cannot cross the\n// Server→Client boundary in RSC, so the compiler emits string keys and this component resolves\n// them at runtime. New reactive vars must be registered here to be addressable from generated\n// pages. Currently empty: cart context travels on the transport, so no cart entry is needed\n// (docs/storefront-core/reference-cart.md § Cart context).\nconst REACTIVE_VAR_REGISTRY: Record<string, ReactiveVar<unknown>> = {};\n\n/**\n * Compile-time-stable map keyed by the operation's variable names. Each value is either an Apollo\n * reactive variable (`makeVar`) or the string name of one registered in REACTIVE_VAR_REGISTRY —\n * Server Components must pass strings because functions cannot cross the RSC boundary. Vars that\n * have not yet resolved should hold `null`; the runtime treats both `null` and `undefined` as\n * \"not yet ready\" and keeps `useQuery` skipped.\n */\nexport type ClientVariablesMap<TVars> = Partial<{\n [K in keyof TVars]: ReactiveVar<TVars[K] | null> | string;\n}>;\n\nfunction resolveReactiveVar(value: ReactiveVar<unknown> | string): ReactiveVar<unknown> | undefined {\n if (typeof value === 'function') return value;\n const resolved = REACTIVE_VAR_REGISTRY[value];\n if (!resolved) {\n throw new Error(\n `PageReactiveDataRoot: clientVariables entry \"${value}\" is not registered. Add it to REACTIVE_VAR_REGISTRY in page-reactive-data-root.tsx.`,\n );\n }\n return resolved;\n}\n\nexport type PageReactiveDataRootProps<TData, TVars extends OperationVariables> = Readonly<{\n /** The composed PAGE_QUERY operation document. */\n query: TypedDocumentNode<TData, TVars>;\n /** Variables the server used when calling fetchPageData. Only used to seed the client cache. */\n serverVariables?: TVars;\n /** Server-rendered PAGE_QUERY result. When present and shape-matched, seeded into the cache once. */\n initialData?: TData | null;\n /** Reactive vars whose current values are merged into operation variables at render time. */\n clientVariables?: ClientVariablesMap<TVars>;\n children: ReactNode;\n}>;\n\nexport type ReactiveRootContextValue<TData = unknown> = Readonly<{\n /** Current root query data exposed to descendant `ReactiveDataProvider`s. */\n rootQueryData: TData | undefined;\n /** Whether the underlying useQuery is currently in flight. */\n loading: boolean;\n /** False when at least one required variable has not been provided yet. */\n hasAllRequiredVariables: boolean;\n /**\n * Error from the underlying useQuery. With non-null root fields (e.g. `cart: Cart!`), a failed\n * fetch nulls the whole operation's `data` — descendants need this to tell \"fetch failed\" apart\n * from \"entity is legitimately absent\" (docs/storefront-core/reference-free-particle-model.md § Read side — data).\n */\n error: ErrorLike | undefined;\n}>;\n\nexport const ReactiveRootContext = createContext<ReactiveRootContextValue>({\n rootQueryData: undefined,\n loading: false,\n hasAllRequiredVariables: false,\n error: undefined,\n});\n\nfunction getOperationDefinition(query: DocumentNode): OperationDefinitionNode | undefined {\n for (const definition of query.definitions) {\n if (definition.kind === Kind.OPERATION_DEFINITION) return definition;\n }\n return undefined;\n}\n\nfunction getRequiredVariableNames(query: DocumentNode): string[] {\n const op = getOperationDefinition(query);\n if (!op?.variableDefinitions) return [];\n const required: string[] = [];\n for (const def of op.variableDefinitions) {\n if (def.type.kind === Kind.NON_NULL_TYPE && def.defaultValue === undefined) {\n required.push(def.variable.name.value);\n }\n }\n return required;\n}\n\nfunction getTopLevelFieldNames(query: DocumentNode): Set<string> {\n const op = getOperationDefinition(query);\n const names = new Set<string>();\n if (!op) return names;\n for (const sel of op.selectionSet.selections) {\n if (sel.kind === Kind.FIELD) {\n names.add((sel.alias ?? sel.name).value);\n }\n }\n return names;\n}\n\nfunction shapeMatches(query: DocumentNode, data: unknown): boolean {\n if (data == null || typeof data !== 'object') return false;\n const expected = getTopLevelFieldNames(query);\n if (expected.size === 0) return false;\n const actual = data as Record<string, unknown>;\n // Require AT LEAST ONE top-level field name to be present in `data`. The operation's full\n // top-level shape may include fields the server did not return; partial seeds still help. A total\n // miss (no overlap at all) signals a shape mismatch and we skip the seed.\n for (const key of expected) {\n if (key in actual) return true;\n }\n return false;\n}\n\n/**\n * Reads the current values of every reactive var in `clientVariables` into a plain object via a\n * single `useSyncExternalStore` call (no hooks-in-loop). Apollo's `ReactiveVar.onNextChange` fires\n * once per registration, so the subscriber re-attaches after each notification to stay listening.\n */\nfunction useClientVariableValues<TVars>(clientVariables: ClientVariablesMap<TVars> | undefined): Partial<TVars> {\n // Keep the latest map identity reachable from inside subscribe()/getSnapshot() without forcing\n // useSyncExternalStore to tear down the underlying subscription.\n const varsRef = useRef(clientVariables);\n // react-doctor-disable-next-line no-ref-current-in-render -- keeps the latest map reachable from the stable subscribe()/getSnapshot() callbacks below\n varsRef.current = clientVariables;\n\n const subscribe = useCallback((notify: () => void): (() => void) => {\n const cv = varsRef.current;\n if (!cv) return () => {};\n\n const activeUnsubs: Array<() => void> = [];\n let cancelled = false;\n\n const attach = (rv: ReactiveVar<unknown>): void => {\n if (cancelled) return;\n const unsub = rv.onNextChange(() => {\n notify();\n // onNextChange fires only once — re-attach to keep listening for subsequent changes.\n attach(rv);\n });\n activeUnsubs.push(unsub);\n };\n\n for (const rv of Object.values(cv)) {\n if (rv === undefined || rv === null) continue;\n const resolved = resolveReactiveVar(rv as ReactiveVar<unknown> | string);\n if (resolved) attach(resolved);\n }\n\n return () => {\n cancelled = true;\n for (const u of activeUnsubs) u();\n };\n }, []);\n\n const lastSnapshotRef = useRef<{ json: string; value: Record<string, unknown> } | null>(null);\n\n const getSnapshot = (): string => {\n const cv = varsRef.current;\n const snap: Record<string, unknown> = {};\n if (cv) {\n for (const [key, reactiveVar] of Object.entries(cv)) {\n if (reactiveVar === undefined || reactiveVar === null) continue;\n const resolved = resolveReactiveVar(reactiveVar as ReactiveVar<unknown> | string);\n if (!resolved) continue;\n const value = resolved();\n if (value !== null && value !== undefined) snap[key] = value;\n }\n }\n const json = JSON.stringify(snap);\n // useSyncExternalStore expects a stable snapshot reference until the value changes (Object.is\n // identity check) — return the cached `json` whenever the contents are unchanged.\n if (lastSnapshotRef.current && lastSnapshotRef.current.json === json) {\n return lastSnapshotRef.current.json;\n }\n lastSnapshotRef.current = { json, value: snap };\n return json;\n };\n\n useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n\n return (lastSnapshotRef.current?.value ?? {}) as Partial<TVars>;\n}\n\nexport function PageReactiveDataRoot<TData = unknown, TVars extends OperationVariables = OperationVariables>(\n props: PageReactiveDataRootProps<TData, TVars>,\n): ReactNode {\n const { query, serverVariables, initialData, clientVariables, children } = props;\n const client = useApolloClient();\n const seededRef = useRef(false);\n\n const clientValues = useClientVariableValues<TVars>(clientVariables);\n const mergedVariables = { ...(serverVariables ?? ({} as TVars)), ...clientValues } as TVars;\n\n const requiredNames = getRequiredVariableNames(query);\n const mergedRecord = mergedVariables as Record<string, unknown>;\n const hasAllRequiredVariables = requiredNames.every((name) => {\n const v = mergedRecord[name];\n return v !== null && v !== undefined;\n });\n\n // Ref- and shape-guarded one-time cache seed from server props. We use `useEffect` (not\n // `useLayoutEffect`) to avoid the SSR-pass warning emitted by React 19 — the resulting \"first\n // render shows fallbackData, second render shows cache slice\" behaviour is acceptable because\n // initialData is the same value `ReactiveDataProvider` falls back to anyway.\n useEffect(() => {\n if (seededRef.current) return;\n if (!serverVariables || initialData == null) return;\n if (!shapeMatches(query, initialData)) return;\n client.cache.writeQuery({ query, variables: serverVariables, data: initialData });\n seededRef.current = true;\n }, [client, query, serverVariables, initialData]);\n\n const { data, loading, error } = useQuery(query, {\n variables: mergedVariables,\n fetchPolicy: 'cache-first',\n skip: !hasAllRequiredVariables,\n });\n\n const contextValue: ReactiveRootContextValue<TData> = useMemo(\n () => ({\n rootQueryData: (data ?? undefined) as TData | undefined,\n loading,\n hasAllRequiredVariables,\n error,\n }),\n [data, loading, hasAllRequiredVariables, error],\n );\n\n return (\n <ReactiveRootContext.Provider value={contextValue as ReactiveRootContextValue}>\n {children}\n </ReactiveRootContext.Provider>\n );\n}\n"],"mappings":";;;;;;AAYA,MAAM,wBAA8D,CAAC;AAarE,SAAS,mBAAmB,OAAwE;CAClG,IAAI,OAAO,UAAU,YAAY,OAAO;CACxC,MAAM,WAAW,sBAAsB;CACvC,IAAI,CAAC,UACH,MAAM,IAAI,MACR,gDAAgD,MAAM,qFACxD;CAEF,OAAO;AACT;AA6BA,MAAa,sBAAsB,cAAwC;CACzE,eAAe,KAAA;CACf,SAAS;CACT,yBAAyB;CACzB,OAAO,KAAA;AACT,CAAC;AAED,SAAS,uBAAuB,OAA0D;CACxF,KAAK,MAAM,cAAc,MAAM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MAAM,QAAQ,MAAM,KAAA;CAC7B,CAAC;CAMD,gBAAgB;EACd,IAAI,UAAU,SAAS;EACvB,IAAI,CAAC,mBAAmB,eAAe,MAAM;EAC7C,IAAI,CAAC,aAAa,OAAO,WAAW,GAAG;EACvC,OAAO,MAAM,WAAW;GAAE;GAAO,WAAW;GAAiB,MAAM;EAAY,CAAC;EAChF,UAAU,UAAU;CACtB,GAAG;EAAC;EAAQ;EAAO;EAAiB;CAAW,CAAC;CAEhD,MAAM,EAAE,MAAM,SAAS,UAAU,SAAS,OAAO;EAC/C,WAAW;EACX,aAAa;EACb,MAAM,CAAC;CACT,CAAC;CAED,MAAM,eAAgD,eAC7C;EACL,eAAgB,QAAQ,KAAA;EACxB;EACA;EACA;CACF,IACA;EAAC;EAAM;EAAS;EAAyB;CAAK,CAChD;CAEA,OACE,oBAAC,oBAAoB,UAArB;EAA8B,OAAO;EAClC;CAC2B,CAAA;AAElC"}
|
|
@@ -18,7 +18,7 @@ export type ReactiveDataProviderProps = Readonly<{
|
|
|
18
18
|
* Resolves its entity slice via `useReactiveEntity` (the shared single-entity resolve; see that
|
|
19
19
|
* hook's doc for the cache-read details) and writes it, unmodified, into `DataOverrideContext`.
|
|
20
20
|
*
|
|
21
|
-
* See
|
|
21
|
+
* See docs/storefront-core/reference-data-layer-runtime.md § Per-component subscription and rfc-data-layer.md §"Reactive fetch".
|
|
22
22
|
*/
|
|
23
23
|
export declare function ReactiveDataProvider({ entityFragment, fragmentName, rootField, fallbackData, children }: ReactiveDataProviderProps): ReactNode;
|
|
24
24
|
//#endregion
|
|
@@ -9,7 +9,7 @@ import { jsx } from "react/jsx-runtime";
|
|
|
9
9
|
* Resolves its entity slice via `useReactiveEntity` (the shared single-entity resolve; see that
|
|
10
10
|
* hook's doc for the cache-read details) and writes it, unmodified, into `DataOverrideContext`.
|
|
11
11
|
*
|
|
12
|
-
* See
|
|
12
|
+
* See docs/storefront-core/reference-data-layer-runtime.md § Per-component subscription and rfc-data-layer.md §"Reactive fetch".
|
|
13
13
|
*/
|
|
14
14
|
function ReactiveDataProvider({ entityFragment, fragmentName, rootField, fallbackData, children }) {
|
|
15
15
|
const resolved = useReactiveEntity(entityFragment, fragmentName, rootField, fallbackData);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reactive-data-provider.js","names":[],"sources":["../../../src/sdk/data/reactive-data-provider.tsx"],"sourcesContent":["'use client';\n\nimport type { DocumentNode } from '@apollo/client';\nimport type { ReactNode } from 'react';\nimport { DataOverrideContext } from './data-override-context.js';\nimport { useReactiveEntity } from './use-reactive-entity.js';\n\nexport type ReactiveDataProviderProps = Readonly<{\n /** Derived `fragment <X>_<EntityType> on <EntityType>` document emitted by the compiler. */\n entityFragment: DocumentNode;\n /** Name of the derived fragment, passed to `useFragment`. */\n fragmentName: string;\n /** Top-level field of the page query (e.g. 'cart') used to extract the entity ref. */\n rootField: string;\n /** Server-rendered fragment payload; used until the cache resolves a complete entity slice. */\n fallbackData: unknown;\n children: ReactNode;\n}>;\n\n/**\n * Per-particle reactive subscriber (AD-4 / AD-D2).\n *\n * Resolves its entity slice via `useReactiveEntity` (the shared single-entity resolve; see that\n * hook's doc for the cache-read details) and writes it, unmodified, into `DataOverrideContext`.\n *\n * See
|
|
1
|
+
{"version":3,"file":"reactive-data-provider.js","names":[],"sources":["../../../src/sdk/data/reactive-data-provider.tsx"],"sourcesContent":["'use client';\n\nimport type { DocumentNode } from '@apollo/client';\nimport type { ReactNode } from 'react';\nimport { DataOverrideContext } from './data-override-context.js';\nimport { useReactiveEntity } from './use-reactive-entity.js';\n\nexport type ReactiveDataProviderProps = Readonly<{\n /** Derived `fragment <X>_<EntityType> on <EntityType>` document emitted by the compiler. */\n entityFragment: DocumentNode;\n /** Name of the derived fragment, passed to `useFragment`. */\n fragmentName: string;\n /** Top-level field of the page query (e.g. 'cart') used to extract the entity ref. */\n rootField: string;\n /** Server-rendered fragment payload; used until the cache resolves a complete entity slice. */\n fallbackData: unknown;\n children: ReactNode;\n}>;\n\n/**\n * Per-particle reactive subscriber (AD-4 / AD-D2).\n *\n * Resolves its entity slice via `useReactiveEntity` (the shared single-entity resolve; see that\n * hook's doc for the cache-read details) and writes it, unmodified, into `DataOverrideContext`.\n *\n * See docs/storefront-core/reference-data-layer-runtime.md § Per-component subscription and rfc-data-layer.md §\"Reactive fetch\".\n */\nexport function ReactiveDataProvider({\n entityFragment,\n fragmentName,\n rootField,\n fallbackData,\n children,\n}: ReactiveDataProviderProps): ReactNode {\n const resolved = useReactiveEntity(entityFragment, fragmentName, rootField, fallbackData);\n\n return <DataOverrideContext value={resolved}>{children}</DataOverrideContext>;\n}\n"],"mappings":";;;;;;;;;;;;;AA2BA,SAAgB,qBAAqB,EACnC,gBACA,cACA,WACA,cACA,YACuC;CACvC,MAAM,WAAW,kBAAkB,gBAAgB,cAAc,WAAW,YAAY;CAExF,OAAO,oBAAC,qBAAD;EAAqB,OAAO;EAAW;CAA8B,CAAA;AAC9E"}
|
|
@@ -19,7 +19,7 @@ export type ReactiveListItemDataProviderProps = Readonly<{
|
|
|
19
19
|
* line's server-rendered slice (`fallbackData`) so descendants always see a value. The resolved
|
|
20
20
|
* slice is published through the same `DataOverrideContext` seam reactive components read today.
|
|
21
21
|
*
|
|
22
|
-
* See
|
|
22
|
+
* See docs/storefront-core/reference-free-particle-model.md § Per-item delivery for iterated matters.
|
|
23
23
|
*/
|
|
24
24
|
export declare function ReactiveListItemDataProvider({ entityFragment, fragmentName, children }: ReactiveListItemDataProviderProps): ReactNode;
|
|
25
25
|
//#endregion
|
|
@@ -15,7 +15,7 @@ import { jsx } from "react/jsx-runtime";
|
|
|
15
15
|
* line's server-rendered slice (`fallbackData`) so descendants always see a value. The resolved
|
|
16
16
|
* slice is published through the same `DataOverrideContext` seam reactive components read today.
|
|
17
17
|
*
|
|
18
|
-
* See
|
|
18
|
+
* See docs/storefront-core/reference-free-particle-model.md § Per-item delivery for iterated matters.
|
|
19
19
|
*/
|
|
20
20
|
function ReactiveListItemDataProvider({ entityFragment, fragmentName, children }) {
|
|
21
21
|
const ref = useListItemRef();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reactive-list-item-data-provider.js","names":[],"sources":["../../../src/sdk/data/reactive-list-item-data-provider.tsx"],"sourcesContent":["'use client';\n\nimport type { DocumentNode } from '@apollo/client';\nimport { useApolloClient, useFragment } from '@apollo/client/react';\nimport type { ReactNode } from 'react';\nimport { DataOverrideContext } from './data-override-context.js';\nimport { useListItemRef } from './list-item-ref-context.js';\n\nexport type ReactiveListItemDataProviderProps = Readonly<{\n /** Derived `fragment <X>_<ListElementEntity> on <ListElementEntity>` document emitted by the compiler. */\n entityFragment: DocumentNode;\n /** Name of the derived fragment, passed to `useFragment`. */\n fragmentName: string;\n children: ReactNode;\n}>;\n\n/**\n * Per-iterated-line reactive subscriber.\n *\n * The list-item sibling of `ReactiveDataProvider`: instead of deriving the entity ref from a\n * top-level page-query field, it reads the current line's ref from `ListItemRefContext` (published\n * per line by the iterator, e.g. `CartList`) and subscribes to that one normalized entity\n * (`CartItem:<id>`) via `useFragment`. The hook never triggers a network request — it is purely a\n * cache reader. When the ref is unresolved or the cache slice is incomplete, it falls back to the\n * line's server-rendered slice (`fallbackData`) so descendants always see a value. The resolved\n * slice is published through the same `DataOverrideContext` seam reactive components read today.\n *\n * See
|
|
1
|
+
{"version":3,"file":"reactive-list-item-data-provider.js","names":[],"sources":["../../../src/sdk/data/reactive-list-item-data-provider.tsx"],"sourcesContent":["'use client';\n\nimport type { DocumentNode } from '@apollo/client';\nimport { useApolloClient, useFragment } from '@apollo/client/react';\nimport type { ReactNode } from 'react';\nimport { DataOverrideContext } from './data-override-context.js';\nimport { useListItemRef } from './list-item-ref-context.js';\n\nexport type ReactiveListItemDataProviderProps = Readonly<{\n /** Derived `fragment <X>_<ListElementEntity> on <ListElementEntity>` document emitted by the compiler. */\n entityFragment: DocumentNode;\n /** Name of the derived fragment, passed to `useFragment`. */\n fragmentName: string;\n children: ReactNode;\n}>;\n\n/**\n * Per-iterated-line reactive subscriber.\n *\n * The list-item sibling of `ReactiveDataProvider`: instead of deriving the entity ref from a\n * top-level page-query field, it reads the current line's ref from `ListItemRefContext` (published\n * per line by the iterator, e.g. `CartList`) and subscribes to that one normalized entity\n * (`CartItem:<id>`) via `useFragment`. The hook never triggers a network request — it is purely a\n * cache reader. When the ref is unresolved or the cache slice is incomplete, it falls back to the\n * line's server-rendered slice (`fallbackData`) so descendants always see a value. The resolved\n * slice is published through the same `DataOverrideContext` seam reactive components read today.\n *\n * See docs/storefront-core/reference-free-particle-model.md § Per-item delivery for iterated matters.\n */\nexport function ReactiveListItemDataProvider({\n entityFragment,\n fragmentName,\n children,\n}: ReactiveListItemDataProviderProps): ReactNode {\n const ref = useListItemRef();\n const client = useApolloClient();\n\n // Derive a stable cache identifier when both __typename and id are present. `cache.identify`\n // returns undefined when the inputs are not normalisable, which we treat the same as a missing\n // ref — useFragment then has nothing to subscribe to and the line shows its fallback slice.\n let from: string | undefined;\n if (ref?.__typename != null && ref.id != null) {\n from = client.cache.identify({ __typename: ref.__typename, id: ref.id });\n }\n\n // useFragment must be called unconditionally to satisfy the Rules of Hooks. When `from` is\n // undefined, Apollo's useFragment returns `{ data: {}, complete: false }` and never reads the\n // cache; the empty-string sentinel keeps the hook invoked but the read a no-op.\n const fragmentResult = useFragment({\n fragment: entityFragment,\n fragmentName,\n from: from ?? '',\n });\n\n const resolved = from && fragmentResult.complete ? fragmentResult.data : ref?.fallbackData;\n\n return <DataOverrideContext value={resolved}>{children}</DataOverrideContext>;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,6BAA6B,EAC3C,gBACA,cACA,YAC+C;CAC/C,MAAM,MAAM,eAAe;CAC3B,MAAM,SAAS,gBAAgB;CAK/B,IAAI;CACJ,IAAI,KAAK,cAAc,QAAQ,IAAI,MAAM,MACvC,OAAO,OAAO,MAAM,SAAS;EAAE,YAAY,IAAI;EAAY,IAAI,IAAI;CAAG,CAAC;CAMzE,MAAM,iBAAiB,YAAY;EACjC,UAAU;EACV;EACA,MAAM,QAAQ;CAChB,CAAC;CAED,MAAM,WAAW,QAAQ,eAAe,WAAW,eAAe,OAAO,KAAK;CAE9E,OAAO,oBAAC,qBAAD;EAAqB,OAAO;EAAW;CAA8B,CAAA;AAC9E"}
|
|
@@ -16,7 +16,7 @@ import { useContext } from "react";
|
|
|
16
16
|
* This hook is intentionally single-entity: it has no notion of merging/composing multiple
|
|
17
17
|
* entities' slices — that's layered on top by `EntitySubscriber`.
|
|
18
18
|
*
|
|
19
|
-
* See
|
|
19
|
+
* See docs/storefront-core/reference-data-layer-runtime.md § Per-component subscription and rfc-data-layer.md §"Reactive fetch".
|
|
20
20
|
*/
|
|
21
21
|
function useReactiveEntity(entityFragment, fragmentName, rootField, fallbackData) {
|
|
22
22
|
const ctx = useContext(ReactiveRootContext);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-reactive-entity.js","names":[],"sources":["../../../src/sdk/data/use-reactive-entity.ts"],"sourcesContent":["'use client';\n\nimport type { DocumentNode } from '@apollo/client';\nimport { useApolloClient, useFragment } from '@apollo/client/react';\nimport { useContext } from 'react';\nimport { ReactiveRootContext } from './page-reactive-data-root.js';\n\ntype EntityRef = {\n __typename?: string;\n id?: string | number;\n};\n\n/**\n * Shared single-entity resolve logic used by BOTH `ReactiveDataProvider` and `EntitySubscriber`\n * (AD-4 / AD-D2).\n *\n * Reads the root query data exposed by `PageReactiveDataRoot` via context, derives the entity ref\n * for the configured `rootField`, and subscribes to the cache via `useFragment`. The hook never\n * triggers a network request — it is purely a cache reader. When the entity ref is unresolved or\n * the cache slice is incomplete, falls back to `fallbackData` (the server-rendered payload) so\n * descendants always see a value.\n *\n * This hook is intentionally single-entity: it has no notion of merging/composing multiple\n * entities' slices — that's layered on top by `EntitySubscriber`.\n *\n * See
|
|
1
|
+
{"version":3,"file":"use-reactive-entity.js","names":[],"sources":["../../../src/sdk/data/use-reactive-entity.ts"],"sourcesContent":["'use client';\n\nimport type { DocumentNode } from '@apollo/client';\nimport { useApolloClient, useFragment } from '@apollo/client/react';\nimport { useContext } from 'react';\nimport { ReactiveRootContext } from './page-reactive-data-root.js';\n\ntype EntityRef = {\n __typename?: string;\n id?: string | number;\n};\n\n/**\n * Shared single-entity resolve logic used by BOTH `ReactiveDataProvider` and `EntitySubscriber`\n * (AD-4 / AD-D2).\n *\n * Reads the root query data exposed by `PageReactiveDataRoot` via context, derives the entity ref\n * for the configured `rootField`, and subscribes to the cache via `useFragment`. The hook never\n * triggers a network request — it is purely a cache reader. When the entity ref is unresolved or\n * the cache slice is incomplete, falls back to `fallbackData` (the server-rendered payload) so\n * descendants always see a value.\n *\n * This hook is intentionally single-entity: it has no notion of merging/composing multiple\n * entities' slices — that's layered on top by `EntitySubscriber`.\n *\n * See docs/storefront-core/reference-data-layer-runtime.md § Per-component subscription and rfc-data-layer.md §\"Reactive fetch\".\n */\nexport function useReactiveEntity(\n entityFragment: DocumentNode,\n fragmentName: string,\n rootField: string,\n fallbackData: unknown,\n): unknown {\n const ctx = useContext(ReactiveRootContext);\n const client = useApolloClient();\n\n const root = ctx.rootQueryData as Record<string, unknown> | undefined;\n const rootSlice = root?.[rootField] as EntityRef | null | undefined;\n\n // Derive a stable cache identifier when both __typename and id are present. `cache.identify`\n // returns undefined when the inputs are not normalisable (no id, no keyFields), which we treat\n // the same as a missing ref — useFragment then has nothing to subscribe to.\n let from: string | undefined;\n if (rootSlice?.__typename != null && rootSlice.id != null) {\n from = client.cache.identify({ __typename: rootSlice.__typename, id: rootSlice.id });\n }\n\n // useFragment must be called unconditionally to satisfy the Rules of Hooks. When `from` is\n // undefined, Apollo's useFragment returns `{ data: {}, complete: false }` and never reads the\n // cache. Pass an empty string as a sentinel so the hook is invoked but the read is a no-op.\n const fragmentResult = useFragment({\n fragment: entityFragment,\n fragmentName,\n from: from ?? '',\n });\n\n return from && fragmentResult.complete ? fragmentResult.data : fallbackData;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA2BA,SAAgB,kBACd,gBACA,cACA,WACA,cACS;CACT,MAAM,MAAM,WAAW,mBAAmB;CAC1C,MAAM,SAAS,gBAAgB;CAG/B,MAAM,YADO,IAAI,gBACQ;CAKzB,IAAI;CACJ,IAAI,WAAW,cAAc,QAAQ,UAAU,MAAM,MACnD,OAAO,OAAO,MAAM,SAAS;EAAE,YAAY,UAAU;EAAY,IAAI,UAAU;CAAG,CAAC;CAMrF,MAAM,iBAAiB,YAAY;EACjC,UAAU;EACV;EACA,MAAM,QAAQ;CAChB,CAAC;CAED,OAAO,QAAQ,eAAe,WAAW,eAAe,OAAO;AACjE"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { BuyButtonDataFragmentDoc, CartCouponApplyDocument, CartCouponRemoveDocument, CartDataFragmentDoc, CartDiscountLinesDataFragmentDoc, CartFragmentFragmentDoc, CartItemAddDocument, CartItemCompositionsDataFragmentDoc, CartItemCustomizationsDataFragmentDoc, CartItemDiscountsDataFragmentDoc, CartItemFragmentFragmentDoc, CartItemQuantityDataFragmentDoc, CartItemQuantityDecreaseDocument, CartItemQuantityIncreaseDocument, CartItemRemoveDocument, CartItemRootDataFragmentDoc, CartItemSellerInfoDataFragmentDoc, CartItemVariationsDataFragmentDoc, CartItemsRemoveDocument, CartMarkdownDataFragmentDoc, CartShippingSimulationDocument, CartTotalizerDataFragmentDoc, CartValidateDocument, MoneyFragmentFragmentDoc, PricingDataFragmentDoc, ProductGalleryDataFragmentDoc, ProductInformationDataFragmentDoc, RegionDataFragmentDoc, RegionFragmentFragmentDoc, SessionDataFragmentDoc, SessionFragmentFragmentDoc, ShippingAddressUpdateDocument, ShippingSimulationDocument, VariantBuyButtonDataFragmentDoc, VariantBuyButtonQueryDocument, VariantGalleryDataFragmentDoc, VariantGalleryQueryDocument, VariantPricingDataFragmentDoc, VariantPricingQueryDocument, VariantSelectorDataFragmentDoc } from "./graphql.js";
|
|
1
|
+
import { AccountSessionRevalidateDocument, BuyButtonDataFragmentDoc, CartCouponApplyDocument, CartCouponRemoveDocument, CartDataFragmentDoc, CartDiscountLinesDataFragmentDoc, CartFragmentFragmentDoc, CartItemAddDocument, CartItemCompositionsDataFragmentDoc, CartItemCustomizationsDataFragmentDoc, CartItemDiscountsDataFragmentDoc, CartItemFragmentFragmentDoc, CartItemQuantityDataFragmentDoc, CartItemQuantityDecreaseDocument, CartItemQuantityIncreaseDocument, CartItemRemoveDocument, CartItemRootDataFragmentDoc, CartItemSellerInfoDataFragmentDoc, CartItemVariationsDataFragmentDoc, CartItemsRemoveDocument, CartMarkdownDataFragmentDoc, CartShippingSimulationDocument, CartTotalizerDataFragmentDoc, CartValidateDocument, MoneyFragmentFragmentDoc, PricingDataFragmentDoc, ProductGalleryDataFragmentDoc, ProductInformationDataFragmentDoc, RegionDataFragmentDoc, RegionFragmentFragmentDoc, SessionDataFragmentDoc, SessionFragmentFragmentDoc, ShippingAddressUpdateDocument, ShippingSimulationDocument, VariantBuyButtonDataFragmentDoc, VariantBuyButtonQueryDocument, VariantGalleryDataFragmentDoc, VariantGalleryQueryDocument, VariantPricingDataFragmentDoc, VariantPricingQueryDocument, VariantSelectorDataFragmentDoc } from "./graphql.js";
|
|
2
2
|
//#region src/sdk/generated/gql.ts
|
|
3
3
|
const documents = {
|
|
4
4
|
"\n fragment BuyButtonData on Query {\n productBySlug(slug: $slug) {\n id\n title\n slug\n images(first: 1) {\n edges {\n node {\n url\n altText\n }\n }\n }\n variants(first: 1) {\n edges {\n node {\n id\n sku\n availableForSale\n sellers {\n id\n isDefault\n offer {\n price { amount currencyCode }\n listPrice { amount currencyCode }\n }\n }\n }\n }\n }\n }\n }\n": BuyButtonDataFragmentDoc,
|
|
@@ -38,6 +38,7 @@ const documents = {
|
|
|
38
38
|
"\n mutation CartValidate {\n cartValidate {\n __typename\n cart {\n ...CartFragment\n }\n userErrors {\n code\n message\n }\n }\n }\n": CartValidateDocument,
|
|
39
39
|
"\n fragment RegionFragment on Region {\n __typename\n id\n postalCode\n city\n }\n": RegionFragmentFragmentDoc,
|
|
40
40
|
"\n fragment SessionFragment on Session {\n __typename\n id\n loggedIn\n canEditData\n isIdentified\n }\n": SessionFragmentFragmentDoc,
|
|
41
|
+
"\n query AccountSessionRevalidate {\n session {\n ...SessionFragment\n }\n }\n": AccountSessionRevalidateDocument,
|
|
41
42
|
"\n query CartShippingSimulation($input: CartShippingSimulateInput!) {\n cartShippingSimulation(input: $input) {\n shippingOptions {\n id\n name\n channel\n shippingEstimate {\n value\n unit\n }\n price {\n amount\n currencyCode\n }\n listPrice {\n amount\n currencyCode\n }\n }\n userErrors {\n code\n message\n }\n }\n }\n": CartShippingSimulationDocument,
|
|
42
43
|
"\n query ShippingSimulation($input: ShippingSimulateInput!) {\n shippingSimulation(input: $input) {\n shippingOptions {\n id\n name\n channel\n shippingEstimate {\n value\n unit\n }\n price {\n amount\n currencyCode\n }\n listPrice {\n amount\n currencyCode\n }\n }\n userErrors {\n code\n message\n }\n }\n }\n": ShippingSimulationDocument,
|
|
43
44
|
"\n mutation ShippingAddressUpdate($input: ShippingAddressUpdateInput!) {\n shippingAddressUpdate(input: $input) {\n shipping {\n __typename\n id\n address {\n __typename\n id\n recipientName\n postalCode\n country\n street\n number\n complement\n neighborhood\n city\n state\n }\n savedAddresses {\n __typename\n id\n recipientName\n postalCode\n country\n street\n number\n complement\n neighborhood\n city\n state\n }\n options {\n __typename\n id\n name\n channel\n shippingEstimate {\n value\n unit\n }\n price {\n amount\n currencyCode\n }\n listPrice {\n amount\n currencyCode\n }\n }\n selectedOptionId\n }\n cart {\n ...CartFragment\n }\n userErrors {\n code\n message\n }\n }\n }\n \n": ShippingAddressUpdateDocument
|