@tanqory/theme-kit 0.1.0 → 2.0.0-alpha.19

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 (233) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +128 -10
  3. package/dist/abi/canvas-live.d.ts +72 -0
  4. package/dist/abi/canvas-live.js +159 -0
  5. package/dist/abi/cart.d.ts +60 -0
  6. package/dist/abi/cart.js +396 -0
  7. package/dist/abi/convert.d.ts +360 -0
  8. package/dist/abi/convert.js +1330 -0
  9. package/dist/abi/data-api.d.ts +15 -0
  10. package/dist/abi/data-api.js +213 -0
  11. package/dist/abi/jcs.d.ts +6 -0
  12. package/dist/abi/jcs.js +28 -0
  13. package/dist/abi/labels.d.ts +3 -0
  14. package/dist/abi/labels.js +34 -0
  15. package/dist/abi/page-data.d.ts +264 -0
  16. package/dist/abi/page-data.js +746 -0
  17. package/dist/abi/page.d.ts +28 -0
  18. package/dist/abi/page.js +57 -0
  19. package/dist/abi/referrals.d.ts +23 -0
  20. package/dist/abi/referrals.js +89 -0
  21. package/dist/abi/rewards.d.ts +27 -0
  22. package/dist/abi/rewards.js +82 -0
  23. package/dist/abi/seo.d.ts +47 -0
  24. package/dist/abi/seo.js +68 -0
  25. package/dist/abi/shell.d.ts +23 -0
  26. package/dist/abi/shell.js +10 -0
  27. package/dist/abi/state-pack.d.ts +17 -0
  28. package/dist/abi/state-pack.js +43 -0
  29. package/dist/abi/wire.d.ts +46 -0
  30. package/dist/abi/wire.js +114 -0
  31. package/dist/build.d.ts +121 -0
  32. package/dist/build.js +401 -0
  33. package/dist/chunks.d.ts +23 -0
  34. package/dist/chunks.js +41 -0
  35. package/dist/client.d.ts +26 -0
  36. package/dist/client.js +101 -0
  37. package/dist/contract.d.ts +6 -0
  38. package/dist/contract.js +6 -0
  39. package/dist/headless/ai.d.ts +132 -0
  40. package/dist/headless/ai.js +99 -0
  41. package/dist/headless/hooks.d.ts +276 -0
  42. package/dist/headless/hooks.js +544 -0
  43. package/dist/headless/i18n.d.ts +13 -0
  44. package/dist/headless/i18n.js +45 -0
  45. package/dist/headless/index.d.ts +44 -0
  46. package/dist/headless/index.js +48 -0
  47. package/dist/headless/lazy-component.d.ts +72 -0
  48. package/dist/headless/lazy-component.js +225 -0
  49. package/dist/headless/lazy-section.d.ts +38 -0
  50. package/dist/headless/lazy-section.js +97 -0
  51. package/dist/headless/model.d.ts +73 -0
  52. package/dist/headless/model.js +115 -0
  53. package/dist/headless/money.d.ts +17 -0
  54. package/dist/headless/money.js +63 -0
  55. package/dist/headless/page.d.ts +45 -0
  56. package/dist/headless/page.js +53 -0
  57. package/dist/headless/platform.d.ts +55 -0
  58. package/dist/headless/platform.js +77 -0
  59. package/dist/headless/primitives/cart.d.ts +90 -0
  60. package/dist/headless/primitives/cart.js +153 -0
  61. package/dist/headless/primitives/collection.d.ts +68 -0
  62. package/dist/headless/primitives/collection.js +80 -0
  63. package/dist/headless/primitives/product.d.ts +101 -0
  64. package/dist/headless/primitives/product.js +117 -0
  65. package/dist/headless/primitives/storefront.d.ts +106 -0
  66. package/dist/headless/primitives/storefront.js +187 -0
  67. package/dist/headless/primitives/util.d.ts +19 -0
  68. package/dist/headless/primitives/util.js +42 -0
  69. package/dist/headless/strings.d.ts +9 -0
  70. package/dist/headless/strings.js +198 -0
  71. package/dist/headless/structured-data.d.ts +31 -0
  72. package/dist/headless/structured-data.js +57 -0
  73. package/dist/headless/tanqory-money.generated.d.ts +493 -0
  74. package/dist/headless/tanqory-money.generated.js +507 -0
  75. package/dist/headless/theme.d.ts +109 -0
  76. package/dist/headless/theme.js +62 -0
  77. package/dist/index.d.ts +21 -0
  78. package/dist/index.js +21 -553
  79. package/dist/runtime/data/StoreProvider.d.ts +84 -0
  80. package/dist/runtime/data/StoreProvider.js +380 -0
  81. package/dist/runtime/data/handle.d.ts +14 -0
  82. package/dist/runtime/data/handle.js +16 -0
  83. package/dist/runtime/data/routes.d.ts +87 -0
  84. package/dist/runtime/data/routes.js +158 -0
  85. package/dist/runtime/data/to-ui.d.ts +286 -0
  86. package/dist/runtime/data/to-ui.js +1009 -0
  87. package/dist/runtime/entries/register.d.ts +9 -0
  88. package/dist/runtime/entries/register.js +9 -0
  89. package/dist/runtime/entries/sections.d.ts +16 -0
  90. package/dist/runtime/entries/sections.js +19 -0
  91. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  92. package/dist/runtime/kit/SectionTree.js +100 -0
  93. package/dist/runtime/kit/analytics.d.ts +63 -0
  94. package/dist/runtime/kit/analytics.js +250 -0
  95. package/dist/runtime/kit/cart.d.ts +222 -0
  96. package/dist/runtime/kit/cart.js +545 -0
  97. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  98. package/dist/runtime/kit/composition.js +3 -0
  99. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  100. package/dist/runtime/kit/config.js +6 -0
  101. package/dist/runtime/kit/consent.d.ts +29 -0
  102. package/dist/runtime/kit/consent.js +159 -0
  103. package/dist/runtime/kit/contract/content.d.ts +213 -0
  104. package/dist/runtime/kit/contract/content.js +119 -0
  105. package/dist/runtime/kit/contract/field-types.d.ts +360 -0
  106. package/dist/runtime/kit/contract/field-types.js +216 -0
  107. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  108. package/dist/runtime/kit/contract/groups.js +402 -0
  109. package/dist/runtime/kit/contract/index.d.ts +33 -0
  110. package/dist/runtime/kit/contract/index.js +33 -0
  111. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  112. package/dist/runtime/kit/contract/transform.js +133 -0
  113. package/dist/runtime/kit/contract/validate.d.ts +77 -0
  114. package/dist/runtime/kit/contract/validate.js +520 -0
  115. package/dist/runtime/kit/data.d.ts +732 -0
  116. package/dist/runtime/kit/data.js +1131 -0
  117. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  118. package/dist/runtime/kit/defineSection.js +10 -0
  119. package/dist/runtime/kit/dynamic-source.d.ts +118 -0
  120. package/dist/runtime/kit/dynamic-source.js +311 -0
  121. package/dist/runtime/kit/index.d.ts +24 -0
  122. package/dist/runtime/kit/index.js +24 -0
  123. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  124. package/dist/runtime/kit/jsx-to-json.js +28 -0
  125. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  126. package/dist/runtime/kit/mount.js +124 -0
  127. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  128. package/dist/runtime/kit/registry.js +12 -0
  129. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  130. package/dist/runtime/kit/ssg.js +56 -0
  131. package/dist/runtime/kit/storefront.d.ts +652 -0
  132. package/dist/runtime/kit/storefront.js +723 -0
  133. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  134. package/dist/runtime/kit/theme-context.js +25 -0
  135. package/dist/runtime/kit/types.d.ts +155 -0
  136. package/dist/runtime/kit/types.js +1 -0
  137. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  138. package/dist/runtime/platform/TrackingPixels.js +63 -0
  139. package/dist/runtime/platform/environment.d.ts +68 -0
  140. package/dist/runtime/platform/environment.js +85 -0
  141. package/dist/runtime/platform/locale.d.ts +27 -0
  142. package/dist/runtime/platform/locale.js +42 -0
  143. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  144. package/dist/runtime/platform/route-analytics.js +72 -0
  145. package/dist/runtime/platform/safe-href.d.ts +25 -0
  146. package/dist/runtime/platform/safe-href.js +69 -0
  147. package/dist/runtime/platform/safe-values.d.ts +37 -0
  148. package/dist/runtime/platform/safe-values.js +140 -0
  149. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  150. package/dist/runtime/render/SectionRenderer.js +199 -0
  151. package/dist/runtime/render/listing-query.d.ts +52 -0
  152. package/dist/runtime/render/listing-query.js +122 -0
  153. package/dist/runtime/render/localized-copy.d.ts +86 -0
  154. package/dist/runtime/render/localized-copy.js +129 -0
  155. package/dist/runtime/render/product-listing.d.ts +11 -0
  156. package/dist/runtime/render/product-listing.js +243 -0
  157. package/dist/runtime/render/resolved.d.ts +47 -0
  158. package/dist/runtime/render/resolved.js +80 -0
  159. package/dist/runtime/render/section-actions.d.ts +67 -0
  160. package/dist/runtime/render/section-actions.js +205 -0
  161. package/dist/runtime/render/starter.d.ts +11 -0
  162. package/dist/runtime/render/starter.js +96 -0
  163. package/dist/runtime/seo/head.d.ts +115 -0
  164. package/dist/runtime/seo/head.js +281 -0
  165. package/dist/runtime/seo/structured-data.d.ts +83 -0
  166. package/dist/runtime/seo/structured-data.js +252 -0
  167. package/dist/runtime/shell/PageShell.d.ts +18 -0
  168. package/dist/runtime/shell/PageShell.js +118 -0
  169. package/dist/runtime/shell/RuntimeBridge.d.ts +18 -0
  170. package/dist/runtime/shell/RuntimeBridge.js +124 -0
  171. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  172. package/dist/runtime/shell/overlay-state.js +59 -0
  173. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  174. package/dist/runtime/shell/preview-mode.js +11 -0
  175. package/dist/runtime/shell/spa-router.d.ts +14 -0
  176. package/dist/runtime/shell/spa-router.js +76 -0
  177. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  178. package/dist/runtime/shell/url-redirects.js +37 -0
  179. package/dist/runtime/slots.d.ts +74 -0
  180. package/dist/runtime/slots.js +16 -0
  181. package/dist/runtime.d.ts +34 -0
  182. package/dist/runtime.js +40 -0
  183. package/dist/sdk/app-block.d.ts +29 -0
  184. package/dist/sdk/app-block.js +22 -0
  185. package/dist/sdk/font-hooks.d.ts +7 -0
  186. package/dist/sdk/font-hooks.js +21 -0
  187. package/dist/sdk/fonts.d.ts +144 -0
  188. package/dist/sdk/fonts.js +241 -0
  189. package/dist/sdk/index.d.ts +32 -0
  190. package/dist/sdk/index.js +36 -0
  191. package/dist/sdk/motion-hooks.d.ts +23 -0
  192. package/dist/sdk/motion-hooks.js +46 -0
  193. package/dist/sdk/motion.d.ts +78 -0
  194. package/dist/sdk/motion.js +292 -0
  195. package/dist/sdk/referrals.d.ts +62 -0
  196. package/dist/sdk/referrals.js +20 -0
  197. package/dist/sdk/rewards.d.ts +85 -0
  198. package/dist/sdk/rewards.js +29 -0
  199. package/dist/sdk/runtime-context.d.ts +230 -0
  200. package/dist/sdk/runtime-context.js +73 -0
  201. package/dist/sdk/schema.d.ts +249 -0
  202. package/dist/sdk/schema.js +168 -0
  203. package/dist/sdk/server-render.d.ts +8 -0
  204. package/dist/sdk/server-render.js +12 -0
  205. package/dist/sdk/store-lookup.d.ts +32 -0
  206. package/dist/sdk/store-lookup.js +48 -0
  207. package/dist/sdk/store.d.ts +164 -0
  208. package/dist/sdk/store.js +5 -0
  209. package/dist/sdk/sx.d.ts +45 -0
  210. package/dist/sdk/sx.js +117 -0
  211. package/dist/sdk/theme.d.ts +212 -0
  212. package/dist/sdk/theme.js +27 -0
  213. package/dist/sdk/types.d.ts +789 -0
  214. package/dist/sdk/types.js +7 -0
  215. package/dist/server.d.ts +112 -0
  216. package/dist/server.js +589 -0
  217. package/dist/vite-chunks.d.ts +10 -0
  218. package/dist/vite-chunks.js +44 -0
  219. package/docs/headless-api.md +250 -0
  220. package/package.json +72 -26
  221. package/dist/index.js.map +0 -1
  222. package/dist/ssg-BZ5FYTw7.js +0 -1802
  223. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  224. package/dist/ssg.js +0 -8
  225. package/dist/ssg.js.map +0 -1
  226. package/dist/types/cart.d.ts +0 -86
  227. package/dist/types/data.d.ts +0 -357
  228. package/dist/types/dynamic-source.d.ts +0 -84
  229. package/dist/types/editor.d.ts +0 -5
  230. package/dist/types/index.d.ts +0 -20
  231. package/dist/types/preview-bridge.d.ts +0 -9
  232. package/dist/types/storefront.d.ts +0 -333
  233. package/dist/types/types.d.ts +0 -44
@@ -0,0 +1,396 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * The cart over Theme ABI v2 (theme-abi-v2.md §4): the same `useCart()` every section already uses,
4
+ * driven by `POST /_tq/actions/cart.*` and `GET /_tq/data/cart.get` instead of a GraphQL endpoint
5
+ * (wire envelope: lib/abi/wire.ts).
6
+ *
7
+ * - Identity is the platform's cart cookie — invisible to the theme. There is no cart id in
8
+ * localStorage any more; `cart.get` answers for the current shopper.
9
+ * - Every mutation carries the cart `version`; a stale version answers `cart_version_conflict`
10
+ * with the current cart, which is applied and the mutation retried once.
11
+ * - Server render never mutates (§4 A3): on the server `remote` is null, the cart route renders
12
+ * the cart the platform resolved (`snapshot().resource.cart`) and every other page renders the
13
+ * empty cart until the browser has asked for it.
14
+ * - A first `cart.get` that FAILS is not an empty cart (QA test-2 F1: a 429 showed "Your cart is
15
+ * empty" over a cart holding a line). `ready` stays false, `loadError` records the code, and the
16
+ * load is retried after the server's `Retry-After` (else exponential backoff). Surfaces show
17
+ * "Couldn't load your cart — retrying". An add before the cart has loaded reads it first; it
18
+ * never `cart.create`s over a cart it could not see.
19
+ *
20
+ * A refused write may say why (theme-abi Cart-1, alpha.13; Cart-3 adds a company location's quantity rule): `refusal`
21
+ * on the `invalid` CartResult, or `error.refusal` when `cart.create` is refused. It is kept for `lastRefusal()`, so the surface
22
+ * that made the write can word it ("You can buy up to 5 of this item").
23
+ *
24
+ * A line write the platform cut for stock (theme-abi Cart-2: the answered cart's `warnings`, the store's
25
+ * MERCHANDISE_OUT_OF_STOCK / MERCHANDISE_NOT_ENOUGH_STOCK) is accepted, but `add` does not pretend it worked: for the
26
+ * variant it added, `lastAddStock()` says `out_of_stock` (nothing added; `add` resolves false) or `not_enough_stock`
27
+ * with how many were added (false when none), counted from the line's quantity before and after.
28
+ *
29
+ * Not in the ABI cart, so not offered: gift-card codes and cart-level attributes after creation.
30
+ * Those methods resolve and set `error`, never pretend to succeed (MISMATCHES.md).
31
+ */
32
+ import { useCallback, useEffect, useRef, useState } from 'react';
33
+ import { CartContext } from '../runtime/kit/cart.js';
34
+ import { cartState } from './convert.js';
35
+ import { AbiWireError } from './wire.js';
36
+ const ZERO = { amount: '0.00', currencyCode: 'USD' };
37
+ function stateOf(c, ready) {
38
+ if (!c) {
39
+ return { id: null, lines: [], subtotal: ZERO, total: ZERO, totalQuantity: 0, checkoutUrl: null, discountCodes: [], discountAmount: null, appliedGiftCards: [], loading: false, ready, error: null };
40
+ }
41
+ // `discountAmount` is the cart-level amount off, derived from the cart's own totals (convert.ts).
42
+ const s = cartState(c);
43
+ return { ...s, appliedGiftCards: [], loading: false, ready, error: null };
44
+ }
45
+ const QUANTITY_RULE_PARTS = new Set(['minimum', 'maximum', 'increment']);
46
+ /**
47
+ * The refusal the platform sent with a refused write (theme-abi Cart-1 / Cart-3), or null. Only a code this
48
+ * theme knows counts: `cart_limit_exceeded` (`maxQuantity` only when it is a whole number of at least 1) and
49
+ * `quantity_rule` with a `rule` of `minimum`, `maximum` or `increment` (anything else is no refusal).
50
+ */
51
+ export function refusalOf(raw) {
52
+ if (typeof raw !== 'object' || raw === null)
53
+ return null;
54
+ const code = raw.code;
55
+ if (code === 'quantity_rule') {
56
+ const rule = raw.rule;
57
+ return typeof rule === 'string' && QUANTITY_RULE_PARTS.has(rule) ? { code: 'quantity_rule', rule: rule } : null;
58
+ }
59
+ if (code !== 'cart_limit_exceeded')
60
+ return null;
61
+ const max = raw.maxQuantity;
62
+ return typeof max === 'number' && Number.isSafeInteger(max) && max >= 1 ? { code: 'cart_limit_exceeded', maxQuantity: max } : { code: 'cart_limit_exceeded' };
63
+ }
64
+ /**
65
+ * What stock let an add of `variantId` put in the cart (theme-abi Cart-2), from the answered cart's `warnings` on that
66
+ * variant's lines and each line's quantity `before` the write (by line id; a new line had 0). Null when no warning
67
+ * names such a line (nothing was cut, or the platform does not tell). A warning with an unknown code is ignored.
68
+ */
69
+ export function addStockOf(cart, variantId, before) {
70
+ const raw = cart?.warnings;
71
+ if (!cart || !Array.isArray(raw))
72
+ return null;
73
+ let outOfStock = false;
74
+ let cut = false;
75
+ let added = 0;
76
+ for (const w of raw) {
77
+ const code = w?.code;
78
+ if (code !== 'out_of_stock' && code !== 'not_enough_stock')
79
+ continue;
80
+ const line = cart.lines.find((l) => l.id === w.lineId);
81
+ if (!line || line.merchandise.id !== variantId)
82
+ continue;
83
+ cut = true;
84
+ if (code === 'out_of_stock')
85
+ outOfStock = true;
86
+ added += Math.max(0, line.quantity - (before.get(line.id) ?? 0));
87
+ }
88
+ if (!cut)
89
+ return null;
90
+ return outOfStock && added === 0 ? { code: 'out_of_stock' } : { code: 'not_enough_stock', added };
91
+ }
92
+ /** Discount codes compare case-insensitively (store-api stores them upper-cased). */
93
+ const sameCode = (a, b) => a.localeCompare(b, undefined, { sensitivity: 'accent' }) === 0;
94
+ const UNSUPPORTED = 'unsupported';
95
+ const MAX_RETRY_MS = 5 * 60_000;
96
+ const MAX_BACKOFF_MS = 30_000;
97
+ /** The wire code of a failed request, for `loadError` / `error`. */
98
+ export function wireCode(e) {
99
+ if (e instanceof AbiWireError)
100
+ return e.code ?? `http_${e.status}`;
101
+ return 'network_error';
102
+ }
103
+ /**
104
+ * When to try `cart.get` again after failure number `attempt` (0-based), or null when another try
105
+ * cannot help. The server's Retry-After wins; a 4xx that is not about timing (403
106
+ * capability_denied, 400 …) is final; everything else (network, 5xx, 429 without the header)
107
+ * backs off 1 s, 2 s, 4 s … up to 30 s.
108
+ */
109
+ export function retryDelay(e, attempt) {
110
+ if (e instanceof AbiWireError) {
111
+ if (e.retryAfterMs !== null)
112
+ return Math.min(Math.max(e.retryAfterMs, 1000), MAX_RETRY_MS);
113
+ if (e.status >= 400 && e.status < 500 && e.status !== 408 && e.status !== 425 && e.status !== 429)
114
+ return null;
115
+ }
116
+ return Math.min(1000 * 2 ** attempt, MAX_BACKOFF_MS);
117
+ }
118
+ export function AbiCartProvider({ initial, remote, children }) {
119
+ const [state, setState] = useState(() => stateOf(initial, initial !== null));
120
+ const cartRef = useRef(initial);
121
+ /** True once the shopper's cart is known (server-resolved, or a `cart.get` answered). */
122
+ const loadedRef = useRef(initial !== null);
123
+ const inFlight = useRef(null);
124
+ /** Why the latest write was refused, when the platform said (Cart-1). */
125
+ const refusalRef = useRef(null);
126
+ const lastRefusal = useCallback(() => refusalRef.current, []);
127
+ /** Why the code the latest applyDiscountCode refused does not apply (the ABI cart's `discountCodes[].refusal`), else null. */
128
+ const discountRefusalRef = useRef(null);
129
+ const lastDiscountRefusal = useCallback(() => discountRefusalRef.current, []);
130
+ /** The earlier codes the latest applyDiscountCode took off because the new code does not combine with them. */
131
+ const discountReplacedRef = useRef([]);
132
+ const lastDiscountReplaced = useCallback(() => discountReplacedRef.current, []);
133
+ /** What stock let the latest add put in the cart when the platform cut it (Cart-2), else null. */
134
+ const stockRef = useRef(null);
135
+ const lastAddStock = useCallback(() => stockRef.current, []);
136
+ /** The wire code of the latest failed write (`invalid` = the store refused it), else null. */
137
+ const failRef = useRef(null);
138
+ const apply = useCallback((c) => {
139
+ cartRef.current = c;
140
+ loadedRef.current = true;
141
+ setState(stateOf(c, true));
142
+ }, []);
143
+ const fail = useCallback((message) => setState((s) => ({ ...s, loading: false, error: message })), []);
144
+ const failState = fail;
145
+ useEffect(() => {
146
+ if (!remote || loadedRef.current)
147
+ return;
148
+ let cancelled = false;
149
+ let timer;
150
+ let attempt = 0;
151
+ const load = () => {
152
+ // A mutation may have loaded the cart while this attempt was waiting.
153
+ if (cancelled || loadedRef.current)
154
+ return;
155
+ remote
156
+ .data('cart.get', [])
157
+ .then((c) => { if (!cancelled && !loadedRef.current)
158
+ apply(c ?? null); })
159
+ .catch((e) => {
160
+ if (cancelled || loadedRef.current)
161
+ return;
162
+ const delay = retryDelay(e, attempt++);
163
+ // Not ready, not empty: the surfaces say the cart could not be loaded.
164
+ setState((s) => ({ ...s, ready: false, loadError: wireCode(e), loadRetrying: delay !== null }));
165
+ if (delay !== null)
166
+ timer = setTimeout(load, delay);
167
+ });
168
+ };
169
+ load();
170
+ return () => {
171
+ cancelled = true;
172
+ if (timer !== undefined)
173
+ clearTimeout(timer);
174
+ };
175
+ }, [remote, apply]);
176
+ /** Run one versioned mutation; on a version conflict apply the current cart and retry once. */
177
+ const mutate = useCallback(async (name, args) => {
178
+ if (!remote)
179
+ return false;
180
+ const fail = (code) => {
181
+ failRef.current = code;
182
+ failState(code);
183
+ };
184
+ const run = async () => {
185
+ failRef.current = null;
186
+ for (let attempt = 0; attempt < 2; attempt++) {
187
+ refusalRef.current = null;
188
+ const version = cartRef.current?.version ?? 0;
189
+ const env = await remote.action(name, args(version));
190
+ // ok ⇒ `data` is the CartResult; a stale version ⇒ error.code cart_version_conflict with the
191
+ // current cart in `data` (§4 wire envelope).
192
+ if (env.ok) {
193
+ const r = env.data;
194
+ if (r.ok) {
195
+ apply(r.cart);
196
+ return true;
197
+ }
198
+ if (r.reason === 'cart_version_conflict') {
199
+ apply(r.cart);
200
+ continue;
201
+ }
202
+ if (r.reason === 'invalid')
203
+ refusalRef.current = refusalOf(r.refusal);
204
+ fail(r.reason);
205
+ return false;
206
+ }
207
+ if (env.error.code === 'cart_version_conflict' && env.data) {
208
+ apply(env.data);
209
+ continue;
210
+ }
211
+ refusalRef.current = refusalOf(env.error.refusal);
212
+ fail(env.error.code);
213
+ return false;
214
+ }
215
+ fail('cart_version_conflict');
216
+ return false;
217
+ };
218
+ setState((s) => ({ ...s, loading: true }));
219
+ // Mutations are serialised: two quick taps must not race on the same version.
220
+ const prev = inFlight.current ?? Promise.resolve();
221
+ const next = prev.catch(() => undefined).then(run);
222
+ inFlight.current = next;
223
+ try {
224
+ return await next;
225
+ }
226
+ catch (e) {
227
+ fail(e.message);
228
+ return false;
229
+ }
230
+ }, [remote, apply, failState]);
231
+ const add = useCallback(async (input) => {
232
+ const quantity = input.quantity ?? 1;
233
+ refusalRef.current = null;
234
+ stockRef.current = null;
235
+ if (quantity < 1 || !remote)
236
+ return false;
237
+ const attributes = Object.fromEntries((input.attributes ?? []).filter((a) => a.value.trim() !== '').map((a) => [a.key, a.value]));
238
+ // A subscription line names its plan (theme-abi alpha.20 `CartLineInput.sellingPlanId`); checkout prices it.
239
+ const sellingPlanId = typeof input.sellingPlanId === 'string' && input.sellingPlanId.trim() !== '' ? input.sellingPlanId.trim() : undefined;
240
+ const line = { merchandiseId: input.variantId, quantity, ...(Object.keys(attributes).length ? { attributes } : {}), ...(sellingPlanId ? { sellingPlanId } : {}) };
241
+ // Cart-2: the answered cart (now cartRef) says whether stock cut this add; nothing added ⇒ the add did not work.
242
+ const stocked = (before) => {
243
+ const stock = addStockOf(cartRef.current, input.variantId, before);
244
+ stockRef.current = stock;
245
+ return stock === null || (stock.code === 'not_enough_stock' && stock.added > 0);
246
+ };
247
+ if (!cartRef.current && !loadedRef.current) {
248
+ // The shopper may already hold a cart we have not read (first load pending or failed):
249
+ // read it now, and never create a second cart over one we could not see.
250
+ setState((s) => ({ ...s, loading: true }));
251
+ try {
252
+ apply((await remote.data('cart.get', [])) ?? null);
253
+ }
254
+ catch (e) {
255
+ fail(wireCode(e));
256
+ return false;
257
+ }
258
+ }
259
+ if (!cartRef.current) {
260
+ setState((s) => ({ ...s, loading: true }));
261
+ try {
262
+ const env = await remote.action('cart.create', [{ lines: [line] }]);
263
+ if (!env.ok) {
264
+ refusalRef.current = refusalOf(env.error.refusal);
265
+ fail(env.error.code);
266
+ return false;
267
+ }
268
+ apply(env.data);
269
+ return stocked(new Map());
270
+ }
271
+ catch (e) {
272
+ fail(e.message);
273
+ return false;
274
+ }
275
+ }
276
+ // the line quantities this add starts from (a version conflict re-reads the cart; the retry starts from that)
277
+ let before = new Map();
278
+ const added = await mutate('cart.addLines', (v) => {
279
+ before = new Map((cartRef.current?.lines ?? []).map((l) => [l.id, l.quantity]));
280
+ return [[line], v];
281
+ });
282
+ return added && stocked(before);
283
+ }, [remote, apply, fail, mutate]);
284
+ const updateQuantity = useCallback(async (lineId, quantity) => {
285
+ if (quantity <= 0)
286
+ await mutate('cart.removeLines', (v) => [[lineId], v]);
287
+ else
288
+ await mutate('cart.updateLines', (v) => [[{ id: lineId, quantity }], v]);
289
+ }, [mutate]);
290
+ const remove = useCallback(async (lineId) => { await mutate('cart.removeLines', (v) => [[lineId], v]); }, [mutate]);
291
+ const clear = useCallback(async () => {
292
+ const ids = cartRef.current?.lines.map((l) => l.id) ?? [];
293
+ if (ids.length)
294
+ await mutate('cart.removeLines', (v) => [ids, v]);
295
+ }, [mutate]);
296
+ const applyDiscountCodes = useCallback(async (codes) => {
297
+ const current = cartRef.current?.discountCodes.map((d) => d.code) ?? [];
298
+ for (const code of current.filter((c) => !codes.includes(c)))
299
+ if (!(await mutate('cart.removeDiscountCode', (v) => [code, v])))
300
+ return;
301
+ for (const code of codes.filter((c) => !current.includes(c)))
302
+ if (!(await mutate('cart.applyDiscountCode', (v) => [code, v])))
303
+ return;
304
+ }, [mutate]);
305
+ /**
306
+ * Codes add up (board 35 #14): the store holds a list (the reference's `cartDiscountCodesUpdate` "replaces all existing
307
+ * discount codes with the provided list", and the gateway's `cart.applyDiscountCode` sends the new code with the current
308
+ * ones), so codes set to combine stay on the cart together, as checkout takes them. A new code the store keeps as not
309
+ * applicable is taken off again and the other codes are left as they were, so checkout never receives a code the
310
+ * shopper was told did not work. A new code that applies can push an earlier one out when the two do not combine: the
311
+ * store then keeps the earlier one as not applicable, it is taken off and `lastDiscountReplaced` names it. A gateway that
312
+ * answers a refusal as `invalid` (it drops the cart store-api sent with `DISCOUNT_INAPPLICABLE`) is read back with
313
+ * `cart.get`.
314
+ */
315
+ const applyDiscountCode = useCallback(async (raw) => {
316
+ discountRefusalRef.current = null;
317
+ discountReplacedRef.current = [];
318
+ const code = raw.trim();
319
+ if (!code || code.length > 255 || !remote)
320
+ return code ? 'failed' : 'not_applicable';
321
+ const held = () => cartRef.current?.discountCodes ?? [];
322
+ const find = (c) => held().find((d) => sameCode(d.code, c));
323
+ if (find(code)?.applicable)
324
+ return 'applied';
325
+ // Codes the cart holds that do not apply (left from an older kit that kept them) go first: they would only be refused.
326
+ for (const d of held())
327
+ if (!sameCode(d.code, code) && !d.applicable && !(await mutate('cart.removeDiscountCode', (v) => [d.code, v])))
328
+ return 'failed';
329
+ const before = held().filter((d) => d.applicable).map((d) => d.code);
330
+ if (!(await mutate('cart.applyDiscountCode', (v) => [code, v]))) {
331
+ const refused = failRef.current === 'invalid';
332
+ try {
333
+ apply((await remote.data('cart.get', [])) ?? null);
334
+ }
335
+ catch {
336
+ /* keep what we have */
337
+ }
338
+ if (!find(code))
339
+ return refused ? 'not_applicable' : 'failed';
340
+ }
341
+ const hit = find(code);
342
+ if (!hit)
343
+ return 'failed';
344
+ if (!hit.applicable) {
345
+ // Kept before the refused code is taken off again: the next cart no longer has it.
346
+ discountRefusalRef.current = hit.refusal ?? null;
347
+ await mutate('cart.removeDiscountCode', (v) => [hit.code, v]);
348
+ return 'not_applicable';
349
+ }
350
+ // An earlier code the new one pushed out (they do not combine) leaves the cart, and the shopper is told.
351
+ const pushedOut = before.filter((c) => find(c)?.applicable === false);
352
+ for (const c of pushedOut)
353
+ await mutate('cart.removeDiscountCode', (v) => [c, v]);
354
+ discountReplacedRef.current = pushedOut;
355
+ return 'applied';
356
+ }, [remote, mutate, apply]);
357
+ const removeDiscountCode = useCallback(async (raw) => {
358
+ const code = raw.trim();
359
+ const hit = cartRef.current?.discountCodes.find((d) => sameCode(d.code, code));
360
+ if (!hit)
361
+ return true;
362
+ return mutate('cart.removeDiscountCode', (v) => [hit.code, v]);
363
+ }, [mutate]);
364
+ const updateNote = useCallback(async (note) => { await mutate('cart.updateNote', (v) => [note, v]); }, [mutate]);
365
+ const unsupported = useCallback(async () => fail(UNSUPPORTED), [fail]);
366
+ const reload = useCallback(async () => {
367
+ if (!remote)
368
+ return;
369
+ try {
370
+ apply((await remote.data('cart.get', [])) ?? null);
371
+ }
372
+ catch {
373
+ /* keep the cart on screen; the next mutation re-syncs it */
374
+ }
375
+ }, [remote, apply]);
376
+ const value = {
377
+ ...state,
378
+ add,
379
+ updateQuantity,
380
+ remove,
381
+ clear,
382
+ applyDiscountCodes,
383
+ applyGiftCardCodes: unsupported,
384
+ removeGiftCards: unsupported,
385
+ updateNote,
386
+ updateAttributes: unsupported,
387
+ reload,
388
+ lastRefusal,
389
+ lastAddStock,
390
+ applyDiscountCode,
391
+ removeDiscountCode,
392
+ lastDiscountRefusal,
393
+ lastDiscountReplaced,
394
+ };
395
+ return _jsx(CartContext.Provider, { value: value, children: children });
396
+ }