@vtex/faststore 0.0.6 → 0.0.7

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.
Files changed (132) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/catalog.json +161 -20
  3. package/dist/cli/UnreachableCaseError-Crd168Vu.js +10 -0
  4. package/dist/cli/UnreachableCaseError-Crd168Vu.js.map +1 -0
  5. package/dist/cli/cacheControl-CEojH_TM.js +158 -0
  6. package/dist/cli/cacheControl-CEojH_TM.js.map +1 -0
  7. package/dist/cli/cachePolicy-m2vASMRW.js +26 -0
  8. package/dist/cli/cachePolicy-m2vASMRW.js.map +1 -0
  9. package/dist/cli/computeCoreSchemaHash-DPJZj-qJ.js +10 -0
  10. package/dist/cli/computeCoreSchemaHash-DPJZj-qJ.js.map +1 -0
  11. package/dist/cli/default-BCQHcwbL.js +253 -0
  12. package/dist/cli/default-BCQHcwbL.js.map +1 -0
  13. package/dist/cli/disableSuggestions-yO9UqiWn.js +21 -0
  14. package/dist/cli/disableSuggestions-yO9UqiWn.js.map +1 -0
  15. package/dist/cli/dist-C1JhdHfo.js +2001 -0
  16. package/dist/cli/dist-C1JhdHfo.js.map +1 -0
  17. package/dist/cli/graphql-DG9thCDG.js +14589 -0
  18. package/dist/cli/graphql-DG9thCDG.js.map +1 -0
  19. package/dist/cli/index.d.ts +350 -0
  20. package/dist/cli/index.js +35047 -0
  21. package/dist/cli/index.js.map +1 -0
  22. package/dist/cli/index.min-BsIHDfFK.js +613 -0
  23. package/dist/cli/index.min-BsIHDfFK.js.map +1 -0
  24. package/dist/cli/inlineTrace-uLgOJ3TH.js +52 -0
  25. package/dist/cli/inlineTrace-uLgOJ3TH.js.map +1 -0
  26. package/dist/cli/internalPlugin-DnuwN4_4.js +11 -0
  27. package/dist/cli/internalPlugin-DnuwN4_4.js.map +1 -0
  28. package/dist/cli/packageVersion-DQAnIEil.js +6 -0
  29. package/dist/cli/packageVersion-DQAnIEil.js.map +1 -0
  30. package/dist/cli/rolldown-runtime-BMI-E3GI.js +44 -0
  31. package/dist/cli/schemaIsSubgraph-DoGh3OYj.js +17 -0
  32. package/dist/cli/schemaIsSubgraph-DoGh3OYj.js.map +1 -0
  33. package/dist/cli/schemaReporting-K-me-3-v.js +199 -0
  34. package/dist/cli/schemaReporting-K-me-3-v.js.map +1 -0
  35. package/dist/cli/server-runtime.js +49859 -0
  36. package/dist/cli/server-runtime.js.map +1 -0
  37. package/dist/cli/traceTreeBuilder-BIcV2U7b.js +9118 -0
  38. package/dist/cli/traceTreeBuilder-BIcV2U7b.js.map +1 -0
  39. package/dist/cli/usageReporting-Bpl8vSZX.js +10201 -0
  40. package/dist/cli/usageReporting-Bpl8vSZX.js.map +1 -0
  41. package/dist/cli/v4-CBhFvC49.js +42 -0
  42. package/dist/cli/v4-CBhFvC49.js.map +1 -0
  43. package/dist/components.d.ts +5 -3
  44. package/dist/components.js +5 -3
  45. package/dist/content-types.json +93 -0
  46. package/dist/core/dist/define-component.d.ts +37 -0
  47. package/dist/core/dist/index.d.ts +2 -2
  48. package/dist/docs/account-entry-point.md +1 -1
  49. package/dist/docs/account-menu-identity.md +160 -0
  50. package/dist/docs/account-menu.md +106 -23
  51. package/dist/docs/avatar.md +103 -0
  52. package/dist/docs/my-account-profile.md +1 -1
  53. package/dist/docs/product-shelf.md +20 -13
  54. package/dist/index.d.ts +2 -2
  55. package/dist/internal/client.js +1 -1
  56. package/dist/internal/content.d.ts +2 -2
  57. package/dist/internal/server.d.ts +4 -1
  58. package/dist/internal/server.js +4 -1
  59. package/dist/matter/account-access-gate/account-access-gate.js.map +1 -1
  60. package/dist/matter/account-entry-point/account-entry-point.js +1 -1
  61. package/dist/matter/account-entry-point/account-entry-point.js.map +1 -1
  62. package/dist/matter/account-menu/account-menu.d.ts +70 -0
  63. package/dist/matter/account-menu/account-menu.js +201 -9
  64. package/dist/matter/account-menu/account-menu.js.map +1 -1
  65. package/dist/matter/account-menu/sign-out-failure.js +50 -0
  66. package/dist/matter/account-menu/sign-out-failure.js.map +1 -0
  67. package/dist/matter/account-menu-identity/account-menu-identity.d.ts +21 -0
  68. package/dist/matter/account-menu-identity/account-menu-identity.js +88 -0
  69. package/dist/matter/account-menu-identity/account-menu-identity.js.map +1 -0
  70. package/dist/matter/card-entry/card-entry.js +1 -0
  71. package/dist/matter/card-entry/card-entry.js.map +1 -1
  72. package/dist/matter/cart/cart.js +1 -1
  73. package/dist/matter/client-preferences/client-preferences-fieldset.js +2 -2
  74. package/dist/matter/client-profile-form/client-profile-fieldset.js +2 -2
  75. package/dist/matter/identity-summary/identity-summary.js +2 -1
  76. package/dist/matter/identity-summary/identity-summary.js.map +1 -1
  77. package/dist/matter/my-account-profile/my-account-profile.d.ts +3 -0
  78. package/dist/matter/my-account-profile/my-account-profile.js +2 -1
  79. package/dist/matter/my-account-profile/my-account-profile.js.map +1 -1
  80. package/dist/matter/payment/payment-controller.js +1 -0
  81. package/dist/matter/payment/payment-controller.js.map +1 -1
  82. package/dist/matter/payment/payment.js +1 -0
  83. package/dist/matter/payment/payment.js.map +1 -1
  84. package/dist/matter/product-shelf/product-shelf.d.ts +61 -31
  85. package/dist/matter/product-shelf/product-shelf.js +157 -57
  86. package/dist/matter/product-shelf/product-shelf.js.map +1 -1
  87. package/dist/matter/saved-cards/saved-cards.js +1 -0
  88. package/dist/matter/saved-cards/saved-cards.js.map +1 -1
  89. package/dist/matter/shipping-address/shipping-address.js +2 -2
  90. package/dist/particles/avatar/avatar.d.ts +17 -0
  91. package/dist/particles/avatar/avatar.js +65 -0
  92. package/dist/particles/avatar/avatar.js.map +1 -0
  93. package/dist/schema.graphql +65 -26
  94. package/dist/sdk/analytics/use-analytics-actions.js +2 -1
  95. package/dist/sdk/analytics/use-analytics-actions.js.map +1 -1
  96. package/dist/sdk/cart/use-cart-actions.js +9 -8
  97. package/dist/sdk/cart/use-cart-actions.js.map +1 -1
  98. package/dist/sdk/cart/use-cart-validate-on-open.js +2 -1
  99. package/dist/sdk/cart/use-cart-validate-on-open.js.map +1 -1
  100. package/dist/sdk/content/create-content-runtime.d.ts +22 -1
  101. package/dist/sdk/content/create-content-runtime.js +89 -1
  102. package/dist/sdk/content/create-content-runtime.js.map +1 -1
  103. package/dist/sdk/data/empty-content-value.js +16 -0
  104. package/dist/sdk/data/empty-content-value.js.map +1 -0
  105. package/dist/sdk/data/hot-data-provider.js +2 -1
  106. package/dist/sdk/data/hot-data-provider.js.map +1 -1
  107. package/dist/sdk/data/index.js +2 -2
  108. package/dist/sdk/data/reactive-list-item-data-provider.js +2 -2
  109. package/dist/sdk/data/variables-from-content.d.ts +43 -0
  110. package/dist/sdk/data/variables-from-content.js +57 -0
  111. package/dist/sdk/data/variables-from-content.js.map +1 -0
  112. package/dist/sdk/generated/gql.js +2 -1
  113. package/dist/sdk/generated/gql.js.map +1 -1
  114. package/dist/sdk/generated/graphql.js +85 -1
  115. package/dist/sdk/generated/graphql.js.map +1 -1
  116. package/dist/sdk/identity/use-identity-actions.js +5 -4
  117. package/dist/sdk/identity/use-identity-actions.js.map +1 -1
  118. package/dist/sdk/payment/use-payment-actions.js +1 -1
  119. package/dist/sdk/payment/use-place-order.js +1 -1
  120. package/dist/sdk/region/use-region-actions.js +2 -1
  121. package/dist/sdk/region/use-region-actions.js.map +1 -1
  122. package/dist/sdk/session/read-server-session.d.ts +21 -0
  123. package/dist/sdk/session/read-server-session.js +61 -0
  124. package/dist/sdk/session/read-server-session.js.map +1 -0
  125. package/dist/sdk/session/use-session-actions.js +5 -4
  126. package/dist/sdk/session/use-session-actions.js.map +1 -1
  127. package/dist/sdk/session/use-session-revalidation.js +2 -1
  128. package/dist/sdk/session/use-session-revalidation.js.map +1 -1
  129. package/dist/sdk/shipping/use-shipping-actions.js +3 -2
  130. package/dist/sdk/shipping/use-shipping-actions.js.map +1 -1
  131. package/dist/utils/safe-href.d.ts +11 -0
  132. package/package.json +13 -2
@@ -1 +1 @@
1
- {"version":3,"file":"use-analytics-actions.js","names":[],"sources":["../../../src/sdk/analytics/use-analytics-actions.ts"],"sourcesContent":["'use client';\n\nimport { defineActions } from '@vtex/fs-core';\nimport { useCallback, useMemo, useRef } from 'react';\nimport {\n type AnalyticsDestination,\n DEFAULT_ANALYTICS_DESTINATION,\n resolveAnalyticsDestination,\n useAnalyticsDestination,\n} from './analytics-destination.js';\n\n/**\n * The `analytics` action namespace (specs/analytics-events.md) — a dispatcher-flavor namespace\n * (docs/storefront-core/adr-0010-actions-own-the-write-side.md; docs/storefront-core/rfc-actions.md\n * § \"Three binding flavors\") that pushes the two standard payment analytics events,\n * `add_payment_info` and `purchase`, to a `window` array — `window.dataLayer` by default, the\n * GTM/GA4-recognizable event convention. It never touches the Apollo cache, never issues a GraphQL\n * operation, and never throws: a broken tag-manager script can never block payment submission or\n * order placement.\n *\n * The destination array is configurable at build time\n * (specs/make-the-analytics-destination-configurable-for.md; T120) — see\n * `./analytics-destination.js` for the resolution precedence, validation, and the\n * `AnalyticsDestinationProvider`. The pushed entry's shape is a data *contract* (a well-known\n * browser-global array shape), not a *provider* — no vendor SDK, no server call. A future\n * platform/foundation epic may replace this sink with a real `AnalyticsContext`; the\n * `track(event: AnalyticsEvent): void` signature and `AnalyticsActions` type are the stable public\n * contract every call site depends on until then (US-4).\n */\n\nexport type AnalyticsMoney = Readonly<{\n amount: number;\n currencyCode: string;\n}>;\n\nexport type AnalyticsLineItem = Readonly<{\n sku: string;\n name: string;\n price: AnalyticsMoney;\n quantity: number;\n}>;\n\n/** Dispatched by T7's CardEntry, before opening the transaction. */\nexport type AddPaymentInfoEvent = Readonly<{\n name: 'add_payment_info';\n value: AnalyticsMoney;\n /**\n * Derived from the selected method's `groupName` at the moment this fires (T140, Decision 5).\n * Optional because the event fires on the cart total, before a method is necessarily selected —\n * omitted rather than a guessed literal, so a downstream consumer never reads a false payment kind.\n * `toEcommercePayload` below drops the corresponding key entirely when this is absent.\n */\n paymentType?: 'Credit Card' | 'Debit Card';\n items?: readonly AnalyticsLineItem[];\n}>;\n\n/** Dispatched by T13's usePlaceOrder, after a successful gateway callback. */\nexport type PurchaseEvent = Readonly<{\n name: 'purchase';\n transactionId: string;\n value: AnalyticsMoney;\n items?: readonly AnalyticsLineItem[];\n}>;\n\nexport type AnalyticsEvent = AddPaymentInfoEvent | PurchaseEvent;\n\nexport type AnalyticsActions = Readonly<{\n /** Push a standard analytics event to window.dataLayer. Fire-and-forget; never throws. */\n track: (event: AnalyticsEvent) => void;\n}>;\n\n/** The shape pushed onto window.dataLayer — GTM/GA4's own event convention. */\nexport type AnalyticsDataLayerEvent = Readonly<{\n event: 'add_payment_info' | 'purchase';\n ecommerce: Record<string, unknown>;\n}>;\n\nfunction toEcommerceItems(items: readonly AnalyticsLineItem[] | undefined) {\n return (items ?? []).map((item) => ({\n item_id: item.sku,\n item_name: item.name,\n price: item.price.amount,\n quantity: item.quantity,\n }));\n}\n\nfunction toEcommercePayload(event: AnalyticsEvent): Record<string, unknown> {\n if (event.name === 'add_payment_info') {\n return {\n currency: event.value.currencyCode,\n value: event.value.amount,\n // T140, Decision 5: the key itself must be absent when `paymentType` is, not merely `undefined`\n // — `pushToDataLayer` pushes this object as-is with no serialization step to strip it, and\n // `'payment_type' in ecommerce` would otherwise still report true.\n ...(event.paymentType !== undefined ? { payment_type: event.paymentType } : {}),\n items: toEcommerceItems(event.items),\n };\n }\n return {\n transaction_id: event.transactionId,\n currency: event.value.currencyCode,\n value: event.value.amount,\n items: toEcommerceItems(event.items),\n };\n}\n\n// `Reflect.get`/`Reflect.set` below match `storefront-provider.tsx`'s existing pattern for a\n// dynamic `window` key — they are not a security mechanism. `Reflect.set(target, k, v)` invokes\n// an inherited setter and creates no own property, exactly like `window[k] = v` would; it adds no\n// hardening on its own. What actually blocks prototype pollution is\n// `isValidAnalyticsDestination`'s denylist and identifier pattern, checked by the caller before\n// `destination` ever reaches this function, plus the non-array guard immediately below.\n//\n// The cast below, not a `declare global` augmentation of `Window`, is what keeps this typed: a\n// global augmentation here would ship inside this package's own `.d.ts` output and hand every\n// consumer's `window.dataLayer` this package's narrow event union, wrong for a store that also\n// pushes its own GTM events (packages/components/scripts/dist-type-boundary.test.ts). `destination`\n// is a runtime string anyway — `Window` has nothing to look up a dynamic key against — so the local\n// cast is also the only type-safe option, not merely the non-leaking one.\nfunction pushToDataLayer(event: AnalyticsEvent, destination: AnalyticsDestination): void {\n if (typeof window === 'undefined') return;\n\n let layer = Reflect.get(window, destination) as AnalyticsDataLayerEvent[] | undefined;\n if (layer === undefined) {\n layer = [];\n Reflect.set(window, destination, layer);\n } else if (!Array.isArray(layer)) {\n console.error(`[analytics.track] window.${destination} already exists and is not an array; the event was dropped`);\n return;\n }\n\n layer.push({ event: event.name, ecommerce: toEcommercePayload(event) });\n}\n\n/**\n * The `analytics` namespace hook. Registered with the first-party action registry via\n * `analyticsActions` below; the compiler-emitted `AnalyticsActionProvider` calls it and threads\n * the narrowed methods into each consumer's `$actions.analytics`. Dispatcher flavor: no\n * `useMutation`, no cache read or write (ADR-0010). Fire-and-forget — `track` never throws, so a\n * broken tag-manager script can never block payment submission or order placement.\n */\nexport function useAnalyticsActions(): AnalyticsActions {\n const override = useAnalyticsDestination();\n // Scoped to this hook instance, not the module: \"logs once\" means once per mounted\n // `useAnalyticsActions()`, so two independent call sites each still get their own first warning.\n const hasLoggedRejectionRef = useRef(false);\n\n const track = useCallback<AnalyticsActions['track']>(\n (event) => {\n // The SSR guard runs before any destination resolution is attempted — not just before the\n // write. Preserved from the pre-T120 behaviour (US-3, \"SSR — no destination resolution\n // attempted at all\").\n if (typeof window === 'undefined') return;\n let destination: AnalyticsDestination = DEFAULT_ANALYTICS_DESTINATION;\n try {\n destination = resolveAnalyticsDestination({\n override,\n hasLoggedRejection: hasLoggedRejectionRef,\n });\n pushToDataLayer(event, destination);\n } catch (error) {\n console.error(`[analytics.track] window.${destination} push failed`, error);\n }\n },\n [override],\n );\n\n return useMemo(() => ({ track }), [track]);\n}\n\n/**\n * Declares the `analytics` action namespace — the single source of truth for its method/payload\n * metadata, runtime provider, and `use` hook (mirrors `cartActions`, `shippingActions`). The\n * native catalog builder (`scripts/build-catalog.mjs`) statically reads this call to emit\n * `actions.json`; at runtime `AnalyticsActionProvider` calls `useAnalyticsActions` directly.\n *\n * The `payload` below is a flattened, best-effort scalar approximation of `AnalyticsEvent` for\n * catalog/docs tooling: `ActionPayloadField.type` supports only scalar primitives and cannot\n * express a discriminated union or a nested `items` array. The TS `AnalyticsEvent` union above is\n * the source of truth for the real call shape.\n */\nexport const analyticsActions = defineActions({\n namespace: 'analytics',\n description:\n 'Dispatcher-flavor namespace that pushes standard add_payment_info / purchase events to window.dataLayer. Never touches the Apollo cache.',\n provider: { name: 'AnalyticsActionProvider', importPath: '@vtex/faststore/internal/client' },\n methods: {\n track: {\n description:\n 'Push a standard analytics event (add_payment_info | purchase) to window.dataLayer. Fire-and-forget; never throws.',\n payload: [\n { name: 'name', type: 'string' },\n { name: 'currencyCode', type: 'string' },\n { name: 'amount', type: 'number' },\n { name: 'paymentType', type: 'string', optional: true },\n { name: 'transactionId', type: 'string', optional: true },\n ],\n },\n },\n use: useAnalyticsActions,\n});\n"],"mappings":";;;;;;AA6EA,SAAS,iBAAiB,OAAiD;CACzE,QAAQ,SAAS,CAAC,EAAA,CAAG,KAAK,UAAU;EAClC,SAAS,KAAK;EACd,WAAW,KAAK;EAChB,OAAO,KAAK,MAAM;EAClB,UAAU,KAAK;CACjB,EAAE;AACJ;AAEA,SAAS,mBAAmB,OAAgD;CAC1E,IAAI,MAAM,SAAS,oBACjB,OAAO;EACL,UAAU,MAAM,MAAM;EACtB,OAAO,MAAM,MAAM;EAInB,GAAI,MAAM,gBAAgB,KAAA,IAAY,EAAE,cAAc,MAAM,YAAY,IAAI,CAAC;EAC7E,OAAO,iBAAiB,MAAM,KAAK;CACrC;CAEF,OAAO;EACL,gBAAgB,MAAM;EACtB,UAAU,MAAM,MAAM;EACtB,OAAO,MAAM,MAAM;EACnB,OAAO,iBAAiB,MAAM,KAAK;CACrC;AACF;AA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actions.ts"],"sourcesContent":["'use client';\n\nimport { defineActions } from '@vtex/fs-core';\nimport { useCallback, useMemo, useRef } from 'react';\nimport { loggableErrorName } from '../../utils/loggable-error-name.js';\nimport {\n type AnalyticsDestination,\n DEFAULT_ANALYTICS_DESTINATION,\n resolveAnalyticsDestination,\n useAnalyticsDestination,\n} from './analytics-destination.js';\n\n/**\n * The `analytics` action namespace (specs/analytics-events.md) — a dispatcher-flavor namespace\n * (docs/storefront-core/adr-0010-actions-own-the-write-side.md; docs/storefront-core/rfc-actions.md\n * § \"Three binding flavors\") that pushes the two standard payment analytics events,\n * `add_payment_info` and `purchase`, to a `window` array — `window.dataLayer` by default, the\n * GTM/GA4-recognizable event convention. It never touches the Apollo cache, never issues a GraphQL\n * operation, and never throws: a broken tag-manager script can never block payment submission or\n * order placement.\n *\n * The destination array is configurable at build time\n * (specs/make-the-analytics-destination-configurable-for.md; T120) — see\n * `./analytics-destination.js` for the resolution precedence, validation, and the\n * `AnalyticsDestinationProvider`. The pushed entry's shape is a data *contract* (a well-known\n * browser-global array shape), not a *provider* — no vendor SDK, no server call. A future\n * platform/foundation epic may replace this sink with a real `AnalyticsContext`; the\n * `track(event: AnalyticsEvent): void` signature and `AnalyticsActions` type are the stable public\n * contract every call site depends on until then (US-4).\n */\n\nexport type AnalyticsMoney = Readonly<{\n amount: number;\n currencyCode: string;\n}>;\n\nexport type AnalyticsLineItem = Readonly<{\n sku: string;\n name: string;\n price: AnalyticsMoney;\n quantity: number;\n}>;\n\n/** Dispatched by T7's CardEntry, before opening the transaction. */\nexport type AddPaymentInfoEvent = Readonly<{\n name: 'add_payment_info';\n value: AnalyticsMoney;\n /**\n * Derived from the selected method's `groupName` at the moment this fires (T140, Decision 5).\n * Optional because the event fires on the cart total, before a method is necessarily selected —\n * omitted rather than a guessed literal, so a downstream consumer never reads a false payment kind.\n * `toEcommercePayload` below drops the corresponding key entirely when this is absent.\n */\n paymentType?: 'Credit Card' | 'Debit Card';\n items?: readonly AnalyticsLineItem[];\n}>;\n\n/** Dispatched by T13's usePlaceOrder, after a successful gateway callback. */\nexport type PurchaseEvent = Readonly<{\n name: 'purchase';\n transactionId: string;\n value: AnalyticsMoney;\n items?: readonly AnalyticsLineItem[];\n}>;\n\nexport type AnalyticsEvent = AddPaymentInfoEvent | PurchaseEvent;\n\nexport type AnalyticsActions = Readonly<{\n /** Push a standard analytics event to window.dataLayer. Fire-and-forget; never throws. */\n track: (event: AnalyticsEvent) => void;\n}>;\n\n/** The shape pushed onto window.dataLayer — GTM/GA4's own event convention. */\nexport type AnalyticsDataLayerEvent = Readonly<{\n event: 'add_payment_info' | 'purchase';\n ecommerce: Record<string, unknown>;\n}>;\n\nfunction toEcommerceItems(items: readonly AnalyticsLineItem[] | undefined) {\n return (items ?? []).map((item) => ({\n item_id: item.sku,\n item_name: item.name,\n price: item.price.amount,\n quantity: item.quantity,\n }));\n}\n\nfunction toEcommercePayload(event: AnalyticsEvent): Record<string, unknown> {\n if (event.name === 'add_payment_info') {\n return {\n currency: event.value.currencyCode,\n value: event.value.amount,\n // T140, Decision 5: the key itself must be absent when `paymentType` is, not merely `undefined`\n // — `pushToDataLayer` pushes this object as-is with no serialization step to strip it, and\n // `'payment_type' in ecommerce` would otherwise still report true.\n ...(event.paymentType !== undefined ? { payment_type: event.paymentType } : {}),\n items: toEcommerceItems(event.items),\n };\n }\n return {\n transaction_id: event.transactionId,\n currency: event.value.currencyCode,\n value: event.value.amount,\n items: toEcommerceItems(event.items),\n };\n}\n\n// `Reflect.get`/`Reflect.set` below match `storefront-provider.tsx`'s existing pattern for a\n// dynamic `window` key — they are not a security mechanism. `Reflect.set(target, k, v)` invokes\n// an inherited setter and creates no own property, exactly like `window[k] = v` would; it adds no\n// hardening on its own. What actually blocks prototype pollution is\n// `isValidAnalyticsDestination`'s denylist and identifier pattern, checked by the caller before\n// `destination` ever reaches this function, plus the non-array guard immediately below.\n//\n// The cast below, not a `declare global` augmentation of `Window`, is what keeps this typed: a\n// global augmentation here would ship inside this package's own `.d.ts` output and hand every\n// consumer's `window.dataLayer` this package's narrow event union, wrong for a store that also\n// pushes its own GTM events (packages/components/scripts/dist-type-boundary.test.ts). `destination`\n// is a runtime string anyway — `Window` has nothing to look up a dynamic key against — so the local\n// cast is also the only type-safe option, not merely the non-leaking one.\nfunction pushToDataLayer(event: AnalyticsEvent, destination: AnalyticsDestination): void {\n if (typeof window === 'undefined') return;\n\n let layer = Reflect.get(window, destination) as AnalyticsDataLayerEvent[] | undefined;\n if (layer === undefined) {\n layer = [];\n Reflect.set(window, destination, layer);\n } else if (!Array.isArray(layer)) {\n console.error(`[analytics.track] window.${destination} already exists and is not an array; the event was dropped`);\n return;\n }\n\n layer.push({ event: event.name, ecommerce: toEcommercePayload(event) });\n}\n\n/**\n * The `analytics` namespace hook. Registered with the first-party action registry via\n * `analyticsActions` below; the compiler-emitted `AnalyticsActionProvider` calls it and threads\n * the narrowed methods into each consumer's `$actions.analytics`. Dispatcher flavor: no\n * `useMutation`, no cache read or write (ADR-0010). Fire-and-forget — `track` never throws, so a\n * broken tag-manager script can never block payment submission or order placement.\n */\nexport function useAnalyticsActions(): AnalyticsActions {\n const override = useAnalyticsDestination();\n // Scoped to this hook instance, not the module: \"logs once\" means once per mounted\n // `useAnalyticsActions()`, so two independent call sites each still get their own first warning.\n const hasLoggedRejectionRef = useRef(false);\n\n const track = useCallback<AnalyticsActions['track']>(\n (event) => {\n // The SSR guard runs before any destination resolution is attempted — not just before the\n // write. Preserved from the pre-T120 behaviour (US-3, \"SSR — no destination resolution\n // attempted at all\").\n if (typeof window === 'undefined') return;\n let destination: AnalyticsDestination = DEFAULT_ANALYTICS_DESTINATION;\n try {\n destination = resolveAnalyticsDestination({\n override,\n hasLoggedRejection: hasLoggedRejectionRef,\n });\n pushToDataLayer(event, destination);\n } catch (error) {\n console.error(`[analytics.track] window.${destination} push failed`, loggableErrorName(error));\n }\n },\n [override],\n );\n\n return useMemo(() => ({ track }), [track]);\n}\n\n/**\n * Declares the `analytics` action namespace — the single source of truth for its method/payload\n * metadata, runtime provider, and `use` hook (mirrors `cartActions`, `shippingActions`). The\n * native catalog builder (`scripts/build-catalog.mjs`) statically reads this call to emit\n * `actions.json`; at runtime `AnalyticsActionProvider` calls `useAnalyticsActions` directly.\n *\n * The `payload` below is a flattened, best-effort scalar approximation of `AnalyticsEvent` for\n * catalog/docs tooling: `ActionPayloadField.type` supports only scalar primitives and cannot\n * express a discriminated union or a nested `items` array. The TS `AnalyticsEvent` union above is\n * the source of truth for the real call shape.\n */\nexport const analyticsActions = defineActions({\n namespace: 'analytics',\n description:\n 'Dispatcher-flavor namespace that pushes standard add_payment_info / purchase events to window.dataLayer. Never touches the Apollo cache.',\n provider: { name: 'AnalyticsActionProvider', importPath: '@vtex/faststore/internal/client' },\n methods: {\n track: {\n description:\n 'Push a standard analytics event (add_payment_info | purchase) to window.dataLayer. Fire-and-forget; never throws.',\n payload: [\n { name: 'name', type: 'string' },\n { name: 'currencyCode', type: 'string' },\n { name: 'amount', type: 'number' },\n { name: 'paymentType', type: 'string', optional: true },\n { name: 'transactionId', type: 'string', optional: true },\n ],\n },\n },\n use: useAnalyticsActions,\n});\n"],"mappings":";;;;;;;AA8EA,SAAS,iBAAiB,OAAiD;CACzE,QAAQ,SAAS,CAAC,EAAA,CAAG,KAAK,UAAU;EAClC,SAAS,KAAK;EACd,WAAW,KAAK;EAChB,OAAO,KAAK,MAAM;EAClB,UAAU,KAAK;CACjB,EAAE;AACJ;AAEA,SAAS,mBAAmB,OAAgD;CAC1E,IAAI,MAAM,SAAS,oBACjB,OAAO;EACL,UAAU,MAAM,MAAM;EACtB,OAAO,MAAM,MAAM;EAInB,GAAI,MAAM,gBAAgB,KAAA,IAAY,EAAE,cAAc,MAAM,YAAY,IAAI,CAAC;EAC7E,OAAO,iBAAiB,MAAM,KAAK;CACrC;CAEF,OAAO;EACL,gBAAgB,MAAM;EACtB,UAAU,MAAM,MAAM;EACtB,OAAO,MAAM,MAAM;EACnB,OAAO,iBAAiB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
  "use client";
2
2
  import { defineActions } from "../../core/dist/actions/registry.js";
3
3
  import "../../core/dist/index.js";
4
+ import { loggableErrorName } from "../../utils/loggable-error-name.js";
4
5
  import { CART_COUPON_APPLY, CART_COUPON_REMOVE, CART_ITEMS_REMOVE, CART_ITEM_ADD, CART_ITEM_QUANTITY_DECREASE, CART_ITEM_QUANTITY_INCREASE, CART_ITEM_REMOVE, CART_VALIDATE, CartFragment } from "./operations.js";
5
6
  import { cartCouponErrorsVar, cartLastAddVar, cartUserErrorsVar, orderFormIdVar } from "../state/cart.js";
6
7
  import { buildOptimisticDecrease, buildOptimisticIncrease, buildOptimisticRemove, buildOptimisticRemoveItems } from "./optimistic.js";
@@ -134,7 +135,7 @@ function useCartActions() {
134
135
  if (errors.length === 0) cartLastAddVar(cartLastAddVar() + 1);
135
136
  return publishWrite(errors);
136
137
  } catch (error) {
137
- console.error("[cart.addItem] cartItemAdd failed", error);
138
+ console.error("[cart.addItem] cartItemAdd failed", loggableErrorName(error));
138
139
  return publish([NETWORK_USER_ERROR]);
139
140
  }
140
141
  }, [addMutation]);
@@ -148,7 +149,7 @@ function useCartActions() {
148
149
  optimisticResponse: buildOptimisticRemove(found.cart, found.line)
149
150
  }))).data?.cartItemRemove?.userErrors ?? []);
150
151
  } catch (error) {
151
- console.error("[cart.removeItem] cartItemRemove failed", error);
152
+ console.error("[cart.removeItem] cartItemRemove failed", loggableErrorName(error));
152
153
  return publish([NETWORK_USER_ERROR]);
153
154
  }
154
155
  }, [requireLine, removeMutation]);
@@ -165,7 +166,7 @@ function useCartActions() {
165
166
  optimisticResponse: buildOptimisticRemoveItems(cart, lines)
166
167
  }))).data?.cartItemsRemove?.userErrors ?? []);
167
168
  } catch (error) {
168
- console.error("[cart.removeItems] cartItemsRemove failed", error);
169
+ console.error("[cart.removeItems] cartItemsRemove failed", loggableErrorName(error));
169
170
  return publish([NETWORK_USER_ERROR]);
170
171
  }
171
172
  }, [readCart, removeItemsMutation]);
@@ -183,7 +184,7 @@ function useCartActions() {
183
184
  optimisticResponse: buildOptimisticIncrease(found.cart, found.line, by)
184
185
  }))).data?.cartItemQuantityIncrease?.userErrors ?? []);
185
186
  } catch (error) {
186
- console.error("[cart.increaseQuantity] cartItemQuantityIncrease failed", error);
187
+ console.error("[cart.increaseQuantity] cartItemQuantityIncrease failed", loggableErrorName(error));
187
188
  return publish([NETWORK_USER_ERROR]);
188
189
  }
189
190
  }, [requireLine, increaseMutation]);
@@ -201,7 +202,7 @@ function useCartActions() {
201
202
  optimisticResponse: buildOptimisticDecrease(found.cart, found.line, by)
202
203
  }))).data?.cartItemQuantityDecrease?.userErrors ?? []);
203
204
  } catch (error) {
204
- console.error("[cart.decreaseQuantity] cartItemQuantityDecrease failed", error);
205
+ console.error("[cart.decreaseQuantity] cartItemQuantityDecrease failed", loggableErrorName(error));
205
206
  return publish([NETWORK_USER_ERROR]);
206
207
  }
207
208
  }, [requireLine, decreaseMutation]);
@@ -212,7 +213,7 @@ function useCartActions() {
212
213
  hydrateCartId(result.data?.cartCouponApply?.cart?.id ?? null);
213
214
  return publishCouponWrite(result.data?.cartCouponApply?.userErrors ?? []);
214
215
  } catch (error) {
215
- console.error("[cart.applyCoupon] cartCouponApply failed", error);
216
+ console.error("[cart.applyCoupon] cartCouponApply failed", loggableErrorName(error));
216
217
  return publishCoupon([NETWORK_USER_ERROR]);
217
218
  }
218
219
  }, [applyCouponMutation]);
@@ -223,7 +224,7 @@ function useCartActions() {
223
224
  hydrateCartId(result.data?.cartCouponRemove?.cart?.id ?? null);
224
225
  return publishCouponWrite(result.data?.cartCouponRemove?.userErrors ?? []);
225
226
  } catch (error) {
226
- console.error("[cart.removeCoupon] cartCouponRemove failed", error);
227
+ console.error("[cart.removeCoupon] cartCouponRemove failed", loggableErrorName(error));
227
228
  return publishCoupon([NETWORK_USER_ERROR]);
228
229
  }
229
230
  }, [removeCouponMutation]);
@@ -235,7 +236,7 @@ function useCartActions() {
235
236
  if (errors.length === 0) markAvailabilityFresh();
236
237
  return errors;
237
238
  } catch (error) {
238
- console.error("[cart.validate] cartValidate failed", error);
239
+ console.error("[cart.validate] cartValidate failed", loggableErrorName(error));
239
240
  return [NETWORK_USER_ERROR];
240
241
  }
241
242
  }, [validateMutation]);
@@ -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 * (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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgD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S,CAAC;IAAE,MAAM;IAAO,MAAM;GAAW,CAAC;EAC7C;EACA,kBAAkB;GAChB,aAAa;GACb,SAAS,CACP;IAAE,MAAM;IAAM,MAAM;GAAS,GAC7B;IAAE,MAAM;IAAM,MAAM;IAAU,UAAU;GAAK,CAC/C;EACF;EACA,kBAAkB;GAChB,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"}
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 { loggableErrorName } from '../../utils/loggable-error-name.js';\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', loggableErrorName(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', loggableErrorName(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', loggableErrorName(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', loggableErrorName(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', loggableErrorName(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', loggableErrorName(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', loggableErrorName(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', loggableErrorName(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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,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,kBAAkB,QAAyC;CACzE,MAAM,SAAS,eAAe;CAC9B,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,UAAU,OAAO,MAAM,SAAS;EAAE,YAAY;EAAQ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ils/loggable-error-name.js";
2
3
  import { cartAvailabilityFreshAtVar, cartWritesInFlightVar, miniCartOpenVar } from "../state/cart.js";
3
4
  import { readCartFromCache } from "./use-cart-actions.js";
4
5
  import { useApolloClient, useReactiveVar } from "@apollo/client/react";
@@ -34,7 +35,7 @@ function useCartValidateOnOpen(validate) {
34
35
  if (!cart || cart.items.length === 0) return;
35
36
  pending.current = true;
36
37
  Promise.resolve(validate()).catch((error) => {
37
- console.error("[cart.validateOnOpen] validate rejected", error);
38
+ console.error("[cart.validateOnOpen] validate rejected", loggableErrorName(error));
38
39
  }).finally(() => {
39
40
  pending.current = false;
40
41
  });
@@ -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 (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
+ {"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 { loggableErrorName } from '../../utils/loggable-error-name.js';\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', loggableErrorName(error));\n })\n .finally(() => {\n pending.current = false;\n });\n }, [open, validate, client]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA4BA,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,kBAAkB,KAAK,CAAC;EACnF,CAAC,CAAC,CACD,cAAc;GACb,QAAQ,UAAU;EACpB,CAAC;CACL,GAAG;EAAC;EAAM;EAAU;CAAM,CAAC;AAC7B"}
@@ -33,8 +33,28 @@ export type ContentEntryBoundaryProps = {
33
33
  value: unknown;
34
34
  children: ReactNode;
35
35
  };
36
+ /** The coordinates of one item read. Object arguments, so two strings cannot be swapped at the call site. */
37
+ export type ReadContentItemArgs = {
38
+ contentTypeId: string;
39
+ slug: string;
40
+ locale: string;
41
+ };
42
+ /**
43
+ * One item read. `found` is the resolved entry. `not-found` is HTTP 404 only. `unavailable` is every
44
+ * other failure with nothing stored. There is no `invalid` arm: a 200 JSON object is the blob.
45
+ */
46
+ export type ContentItemResult = {
47
+ status: 'found';
48
+ blob: Record<string, unknown>;
49
+ } | {
50
+ status: 'not-found';
51
+ } | {
52
+ status: 'unavailable';
53
+ reason: string;
54
+ };
36
55
  export type ContentRuntime = {
37
56
  readContentSlices: (args: ReadContentSlicesArgs) => Promise<ContentSlices>;
57
+ readContentItem: (args: ReadContentItemArgs) => Promise<ContentItemResult>;
38
58
  ContentEntryBoundary: FC<ContentEntryBoundaryProps>;
39
59
  };
40
60
  /**
@@ -61,7 +81,8 @@ export type ContentEntryResult = {
61
81
  * `ContentEntryBoundary` the compiler wraps around each content-backed element. One read per scope
62
82
  * yields every element's `$content` value keyed by `element.id`, so a page issues at most two Data
63
83
  * Plane reads (its own entry plus its layout's) regardless of content-backed component count. Draft
64
- * Mode switches the same read to Control Plane's preview endpoint through a server-only credential.
84
+ * Mode switches that composite read to Control Plane's preview endpoint through a server-only
85
+ * credential. `readContentItem` reads one entry by slug and does not consult Draft Mode.
65
86
  */
66
87
  export declare function createContentRuntime(config: ContentRuntimeConfig): ContentRuntime;
67
88
  //#endregion
@@ -48,7 +48,8 @@ const PREVIEW_COOKIE = "__fs_content_preview";
48
48
  * `ContentEntryBoundary` the compiler wraps around each content-backed element. One read per scope
49
49
  * yields every element's `$content` value keyed by `element.id`, so a page issues at most two Data
50
50
  * Plane reads (its own entry plus its layout's) regardless of content-backed component count. Draft
51
- * Mode switches the same read to Control Plane's preview endpoint through a server-only credential.
51
+ * Mode switches that composite read to Control Plane's preview endpoint through a server-only
52
+ * credential. `readContentItem` reads one entry by slug and does not consult Draft Mode.
52
53
  */
53
54
  function createContentRuntime(config) {
54
55
  const lastGood = /* @__PURE__ */ new Map();
@@ -119,6 +120,37 @@ function createContentRuntime(config) {
119
120
  };
120
121
  }
121
122
  }
123
+ /**
124
+ * The by-slug read plus the same fallback. Not a parameter of `readPublished`: the key, the URL,
125
+ * and the result taxonomy differ, and folding them together would put a slug on the composite log
126
+ * line. A `not-found` returns before the map is read or written.
127
+ */
128
+ async function readPublishedItem(contentTypeId, slug, locale) {
129
+ const key = `item\u0000${contentTypeId}\u0000${slug}\u0000${locale}`;
130
+ try {
131
+ const result = await readItemBySlug(config.account, config.storeId, locale, contentTypeId, slug);
132
+ if (result.status === "found") retainBlob(key, result.blob, {
133
+ contentTypeId,
134
+ slug,
135
+ locale
136
+ });
137
+ return { result };
138
+ } catch (error) {
139
+ const reason = transientReason(error);
140
+ const stored = lastGood.get(key);
141
+ if (stored === void 0) return { result: {
142
+ status: "unavailable",
143
+ reason
144
+ } };
145
+ return {
146
+ result: {
147
+ status: "found",
148
+ blob: stored
149
+ },
150
+ staleReason: reason
151
+ };
152
+ }
153
+ }
122
154
  const read = cache(async (contentTypeId, entryId, locale) => {
123
155
  await connection();
124
156
  const { isEnabled: draft } = await draftMode();
@@ -175,8 +207,27 @@ function createContentRuntime(config) {
175
207
  });
176
208
  return slices;
177
209
  }
210
+ const readItem = cache(async (contentTypeId, slug, locale) => {
211
+ await connection();
212
+ const { result, staleReason } = await readPublishedItem(contentTypeId, slug, locale);
213
+ const stale = staleReason !== void 0;
214
+ const { level, event } = stale ? STALE_READ_EVENT : READ_EVENTS[result.status];
215
+ const reason = staleReason ?? (result.status === "unavailable" ? result.reason : void 0);
216
+ if (!(!stale && result.status === "found" && process.env.NODE_ENV === "production")) logEvent(level, event, {
217
+ contentTypeId,
218
+ slug,
219
+ locale,
220
+ source: "data-plane",
221
+ ...reason === void 0 ? {} : { reason }
222
+ });
223
+ return result;
224
+ });
225
+ async function readContentItem({ contentTypeId, slug, locale }) {
226
+ return readItem(contentTypeId, slug, locale);
227
+ }
178
228
  return {
179
229
  readContentSlices,
230
+ readContentItem,
180
231
  ContentEntryBoundary
181
232
  };
182
233
  }
@@ -231,6 +282,32 @@ async function readPublishedEntry(account, storeId, locale, contentTypeId, entry
231
282
  };
232
283
  }
233
284
  /**
285
+ * One entry from the Data Plane by slug. A 404 resolves `not-found` before `json()`. Any other
286
+ * non-OK status, a non-JSON body, or a non-object body throws, and `readPublishedItem` decides
287
+ * between the stored blob and `unavailable`. A 200 object is `found` with no field-schema check.
288
+ * `locale_metadata` is the platform envelope (it carries an inline SVG) and this path has no slicer,
289
+ * so that own property is removed before the blob is returned or retained. No other key is dropped.
290
+ * A list body is not an object, so it throws rather than resolving `not-found`.
291
+ */
292
+ async function readItemBySlug(account, storeId, locale, contentTypeId, slug) {
293
+ const url = buildDataPlaneSlugUrl(account, storeId, locale, contentTypeId, slug);
294
+ const response = await fetch(url, { signal: AbortSignal.timeout(ENTRY_REQUEST_TIMEOUT_MS) });
295
+ if (response.status === 404) return { status: "not-found" };
296
+ if (!response.ok) throw new Error(`content upstream status ${response.status}`);
297
+ let payload;
298
+ try {
299
+ payload = await response.json();
300
+ } catch {
301
+ throw new Error("content response is not JSON");
302
+ }
303
+ if (!isRecord(payload)) throw new Error("content response is not an object");
304
+ if (Object.hasOwn(payload, "locale_metadata")) delete payload.locale_metadata;
305
+ return {
306
+ status: "found",
307
+ blob: payload
308
+ };
309
+ }
310
+ /**
234
311
  * The Draft Mode read: the same composite entry resolved through Control Plane's preview endpoint
235
312
  * with a server-only credential, bypassing all caches. The branch comes from a SIGNED preview
236
313
  * context cookie whose HMAC is re-verified here against the broker secret — a tampered cookie fails
@@ -330,6 +407,17 @@ function buildDataPlaneUrl(account, storeId, locale, contentTypeId, entryId) {
330
407
  entryId
331
408
  ].map(encodeURIComponent).join("/")}?locale=${encodeURIComponent(locale)}`;
332
409
  }
410
+ /** Same origin and `locale` query as `buildDataPlaneUrl`. The slug is one segment: it is not split on `/`. */
411
+ function buildDataPlaneSlugUrl(account, storeId, locale, contentTypeId, slug) {
412
+ return `https://${account}.vtexcommercestable.com.br/api/content-platform/data/${[
413
+ account,
414
+ storeId,
415
+ contentTypeId,
416
+ "entries",
417
+ "slug",
418
+ slug
419
+ ].map(encodeURIComponent).join("/")}?locale=${encodeURIComponent(locale)}`;
420
+ }
333
421
  /**
334
422
  * Slices one element's value out of the composite blob by its `element.id` and validates it against
335
423
  * that element's per-component model. Omits only this component on a missing key, a non-object