@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,1009 @@
1
+ import { matchRoute } from './routes.js';
2
+ import { safeHref } from '../platform/safe-href.js';
3
+ import { resolveLogo } from '../platform/safe-values.js';
4
+ // ── URLs (the canonical forms of app/data/routes.ts) ─────────────────────────────
5
+ const seg = (handle) => encodeURIComponent(handle);
6
+ export const productUrl = (handle) => `/products/${seg(handle)}`;
7
+ export const collectionUrl = (handle) => `/collections/${seg(handle)}`;
8
+ export const pageUrl = (handle) => `/pages/${seg(handle)}`;
9
+ export const blogUrl = (handle) => `/blogs/${seg(handle)}`;
10
+ export const articleUrl = (blogHandle, articleHandle) => `/blogs/${seg(blogHandle)}/${seg(articleHandle)}`;
11
+ export const policyUrl = (handle) => `/policies/${seg(handle)}`;
12
+ const dim = (n) => (typeof n === 'number' && Number.isFinite(n) && n > 0 ? Math.round(n) : 0);
13
+ /**
14
+ * A runtime image → Image, or null when there is no URL.
15
+ *
16
+ * `width`/`height` are required by the UI type but optional in the runtime (the
17
+ * offline fixture, collection images, article images and the theme logo setting
18
+ * carry none). An unknown dimension is `0` — "unknown", never a guessed size.
19
+ * UI images are CSS-sized (`width:100%; height:100%; object-fit`), and a
20
+ * `0 / 0` aspect-ratio is invalid CSS, so the frame keeps its own ratio.
21
+ */
22
+ export function toImage(img) {
23
+ if (!img || typeof img.url !== 'string' || !img.url.trim())
24
+ return null;
25
+ const alt = typeof img.altText === 'string' && img.altText.trim() ? img.altText : undefined;
26
+ return { src: img.url, ...(alt ? { alt } : {}), width: dim(img.width), height: dim(img.height) };
27
+ }
28
+ /** Decimal string → number, keeping every digit the source sent. null when absent or not a number. */
29
+ export function toMoney(m) {
30
+ if (!m || typeof m.currencyCode !== 'string' || !m.currencyCode)
31
+ return null;
32
+ const raw = typeof m.amount === 'number' ? m.amount : typeof m.amount === 'string' && m.amount.trim() !== '' ? Number(m.amount) : NaN;
33
+ if (!Number.isFinite(raw))
34
+ return null;
35
+ return { amount: raw, currencyCode: m.currencyCode };
36
+ }
37
+ /**
38
+ * A required Money the source could not supply. The UI type has no null here,
39
+ * so this is the ONE place a zero is written — `amount: 0` in the currency we
40
+ * do know. Callers only reach it when the runtime itself had no price.
41
+ */
42
+ function requiredMoney(m, currencyCode) {
43
+ return m ?? { amount: 0, currencyCode };
44
+ }
45
+ /** compareAt only when it is a real sale (was > now) — the runtime's own rule for product cards. */
46
+ function saleOnly(compareAt, price) {
47
+ if (!compareAt || !price)
48
+ return null;
49
+ return compareAt.currencyCode === price.currencyCode && compareAt.amount > price.amount ? compareAt : null;
50
+ }
51
+ function minMax(list) {
52
+ if (!list.length)
53
+ return null;
54
+ let min = list[0];
55
+ let max = list[0];
56
+ for (const m of list) {
57
+ if (m.currencyCode !== min.currencyCode)
58
+ continue;
59
+ if (m.amount < min.amount)
60
+ min = m;
61
+ if (m.amount > max.amount)
62
+ max = m;
63
+ }
64
+ return { min, max };
65
+ }
66
+ const str = (v) => (typeof v === 'string' && v.trim() !== '' ? v : undefined);
67
+ // ── Products ────────────────────────────────────────────────────────────────
68
+ /**
69
+ * A runtime variant → ProductVariant.
70
+ *
71
+ * `quantityAvailable` is the on-hand count only when it LIMITS a purchase:
72
+ * `inventoryPolicy: CONTINUE` sells past zero, so there is no cap, and a
73
+ * negative count under DENY means nothing is purchasable (0). Unknown — no
74
+ * count, or a count that does not limit — is an ABSENT key, never 0 or null.
75
+ */
76
+ export function toVariant(v, fallbackCurrency = '') {
77
+ const price = toMoney(v?.price);
78
+ const currency = price?.currencyCode ?? fallbackCurrency;
79
+ const qty = v?.inventoryQuantity;
80
+ const quantityAvailable = v?.inventoryPolicy === 'CONTINUE' ? undefined : typeof qty === 'number' && Number.isFinite(qty) ? Math.max(0, Math.floor(qty)) : undefined;
81
+ const sku = str(v?.sku);
82
+ return {
83
+ id: v?.id ?? '',
84
+ title: v?.title ?? '',
85
+ ...(sku ? { sku } : {}),
86
+ price: requiredMoney(price, currency),
87
+ compareAtPrice: saleOnly(toMoney(v?.compareAtPrice), price),
88
+ available: v?.availableForSale === true,
89
+ ...(quantityAvailable !== undefined ? { quantityAvailable } : {}),
90
+ selectedOptions: (v?.selectedOptions ?? []).filter((o) => o && typeof o.name === 'string').map((o) => ({ name: o.name, value: o.value ?? '' })),
91
+ image: toImage(v?.image),
92
+ ...(Array.isArray(v?.pickupLocationIds) ? { pickupLocationIds: [...v.pickupLocationIds] } : {}),
93
+ };
94
+ }
95
+ /**
96
+ * A runtime product → Product.
97
+ *
98
+ * The runtime has two product shapes: the CARD (bootstrap, collection pages,
99
+ * search, recommendations) with one price, one compare-at and no variants; and
100
+ * the DETAIL (`fetchProduct`) with options + variants. Ranges come from the
101
+ * variants when they are there. On a card the runtime knows only the minimum
102
+ * price and the maximum compare-at, so both ends of each range are that one
103
+ * value — see the data-gap notes in the report.
104
+ */
105
+ export function toProduct(p) {
106
+ const handle = p?.handle ?? '';
107
+ const cardPrice = toMoney(p?.price);
108
+ const currency = cardPrice?.currencyCode ?? toMoney(p?.variants?.[0]?.price)?.currencyCode ?? '';
109
+ const variants = (p?.variants ?? []).filter(Boolean).map((v) => toVariant(v, currency));
110
+ const variantPrices = minMax(variants.map((v) => v.price).filter((m) => m.currencyCode));
111
+ const min = variantPrices?.min ?? requiredMoney(cardPrice, currency);
112
+ // A card has no variants: its max comes from the card's own range, else it is one price.
113
+ const priceRange = variantPrices ?? { min, max: toMoney(p?.priceMax) ?? min };
114
+ const variantCompare = minMax(variants.map((v) => v.compareAtPrice).filter((m) => Boolean(m)));
115
+ const cardCompare = saleOnly(toMoney(p?.compareAtPrice), cardPrice);
116
+ const compareAtPriceRange = variantCompare ?? (cardCompare ? { min: cardCompare, max: cardCompare } : null);
117
+ const featuredImage = toImage(p?.featuredImage);
118
+ const gallery = (p?.images ?? []).map(toImage).filter((i) => Boolean(i));
119
+ const images = gallery.length ? gallery : featuredImage ? [featuredImage] : [];
120
+ const available = typeof p?.availableForSale === 'boolean'
121
+ ? p.availableForSale
122
+ : variants.length
123
+ ? variants.some((v) => v.available)
124
+ : true; // the runtime omits the flag only on offline fixtures, which are all purchasable
125
+ const vendor = str(p?.vendor);
126
+ const productType = str(p?.productType);
127
+ return {
128
+ // The offline fixture has no ids; the handle is the product's stable key there.
129
+ id: p?.id ?? handle,
130
+ handle,
131
+ title: p?.title ?? '',
132
+ ...(vendor ? { vendor } : {}),
133
+ ...(productType ? { productType } : {}),
134
+ ...(typeof p?.description === 'string' ? { description: p.description } : {}),
135
+ ...(typeof p?.descriptionHtml === 'string' ? { descriptionHtml: p.descriptionHtml } : {}),
136
+ url: productUrl(handle),
137
+ featuredImage: featuredImage ?? images[0] ?? null,
138
+ images,
139
+ options: (p?.options ?? []).filter((o) => o && typeof o.name === 'string').map((o) => ({ name: o.name, values: [...(o.values ?? [])] })),
140
+ variants,
141
+ priceRange,
142
+ compareAtPriceRange,
143
+ available,
144
+ ...(p?.tags?.length ? { tags: [...p.tags] } : {}),
145
+ ...(typeof p?.lowStockThreshold === 'number' ? { lowStockThreshold: p.lowStockThreshold } : {}),
146
+ ...(p?.isGiftCard === true ? { isGiftCard: true } : {}),
147
+ ...(p?.automaticDiscounts?.length ? { automaticDiscounts: p.automaticDiscounts.map((d) => ({ ...d })) } : {}),
148
+ ...toProductMedia(p?.media),
149
+ ...toSellingPlanGroups(p?.sellingPlanGroups),
150
+ // No source: the runtime has no merchant badge field.
151
+ badge: null,
152
+ // The platform's published-review aggregate (Theme ABI `Product.rating`, storefront-query rev 2.38); a product
153
+ // nobody has reviewed carries none, and the card shows no stars (never "0 reviews").
154
+ rating: p?.rating && p.rating.count >= 1 ? { value: p.rating.value, count: p.rating.count } : null,
155
+ };
156
+ }
157
+ export const toProducts = (list) => (list ?? []).filter(Boolean).map(toProduct);
158
+ /** One platform review (Theme ABI `ProductReview`) → the theme's `Review`. */
159
+ export function toReview(r) {
160
+ return {
161
+ id: r.id,
162
+ author: r.author,
163
+ rating: r.rating,
164
+ ...(r.title ? { title: r.title } : {}),
165
+ body: r.body,
166
+ createdAt: r.createdAt,
167
+ verified: r.verifiedPurchase,
168
+ ...(r.reply ? { reply: { body: r.reply.body, createdAt: r.reply.createdAt } } : {}),
169
+ };
170
+ }
171
+ /**
172
+ * The current product's reviews for `StoreContext.reviews` (12F): the platform's aggregate and its newest published
173
+ * reviews (storefront-query rev 2.38). A product nobody has reviewed yet answers `count: 0` with an empty list — the
174
+ * section shows "No reviews yet" and its Write-a-review form. A region that answered the aggregate but not the list
175
+ * (asked without `reviewsFirst`) gives the aggregate with an empty list.
176
+ */
177
+ export function toReviews(p) {
178
+ const rating = p?.rating && p.rating.count >= 1 ? p.rating : null;
179
+ const nodes = p?.reviews?.nodes ?? [];
180
+ return {
181
+ average: rating?.value ?? 0,
182
+ count: rating?.count ?? nodes.length,
183
+ distribution: rating?.distribution ?? [0, 0, 0, 0, 0],
184
+ reviews: nodes.map(toReview),
185
+ };
186
+ }
187
+ /**
188
+ * The runtime's selling plan groups → `Product.sellingPlanGroups` (NEW-SUB-1): only groups whose plans carry a
189
+ * schedule (the Theme ABI source does; the GraphQL driver's plans have none and are left out, as before).
190
+ */
191
+ export function toSellingPlanGroups(list) {
192
+ const groups = [];
193
+ for (const g of list ?? []) {
194
+ if (!g || typeof g.id !== 'string' || !g.id)
195
+ continue;
196
+ const plans = [];
197
+ for (const p of g.sellingPlans ?? []) {
198
+ if (!p || !p.interval || typeof p.intervalCount !== 'number')
199
+ continue;
200
+ plans.push({
201
+ id: p.id,
202
+ name: p.name,
203
+ ...(p.description ? { description: p.description } : {}),
204
+ ...(p.options?.length ? { options: p.options.map((o) => ({ name: o.name, value: o.value })) } : {}),
205
+ interval: p.interval,
206
+ intervalCount: p.intervalCount,
207
+ ...(p.discount ? { discount: { type: p.discount.type, value: p.discount.value } } : {}),
208
+ });
209
+ }
210
+ if (!plans.length)
211
+ continue;
212
+ groups.push({
213
+ id: g.id,
214
+ name: g.name,
215
+ ...(g.description ? { description: g.description } : {}),
216
+ ...(g.options?.length ? { options: g.options.map((o) => ({ name: o.name, values: [...o.values] })) } : {}),
217
+ plans,
218
+ ...(g.variantIds?.length ? { variantIds: [...g.variantIds] } : {}),
219
+ });
220
+ }
221
+ return groups.length ? { sellingPlanGroups: groups } : {};
222
+ }
223
+ /** Products by handle, for StoreContext.products. */
224
+ export function toProductMap(list) {
225
+ const out = {};
226
+ for (const p of toProducts(list))
227
+ if (p.handle && !out[p.handle])
228
+ out[p.handle] = p;
229
+ return out;
230
+ }
231
+ // ── Collections ─────────────────────────────────────────────────────────────
232
+ /**
233
+ * A runtime collection → Collection.
234
+ *
235
+ * `products`: pass the live page (`collectionProducts(...).products`) when you
236
+ * have it. Otherwise the bootstrap cache is used ONLY when it actually has
237
+ * products — an empty cached list can be a shell baked before products were
238
+ * assigned, so it maps to `products: undefined` ("not loaded"), not "empty".
239
+ * Pass `products: []` to state that the collection is known to be empty.
240
+ */
241
+ export function toCollection(c, opts = {}) {
242
+ const handle = c?.handle ?? '';
243
+ const source = opts.products ?? (c?.products?.length ? c.products : null);
244
+ const products = source ? toProducts(source) : undefined;
245
+ const description = str(c?.description ?? undefined);
246
+ return {
247
+ id: c?.id ?? handle,
248
+ handle,
249
+ title: c?.title ?? '',
250
+ ...(description ? { description } : {}),
251
+ url: collectionUrl(handle),
252
+ image: toImage(c?.image),
253
+ productsCount: typeof c?.productsCount === 'number' ? c.productsCount : (products?.length ?? 0),
254
+ ...(products ? { products } : {}),
255
+ };
256
+ }
257
+ /** Collections by handle, for StoreContext.collections (card-level: no product lists). */
258
+ export function toCollectionMap(list, opts = {}) {
259
+ const out = {};
260
+ for (const c of list ?? []) {
261
+ if (!c?.handle || out[c.handle])
262
+ continue;
263
+ const mapped = toCollection(c);
264
+ if (!opts.withProducts)
265
+ delete mapped.products;
266
+ out[c.handle] = mapped;
267
+ }
268
+ return out;
269
+ }
270
+ /**
271
+ * A menu URL the theme can render, or null.
272
+ *
273
+ * Unsafe schemes are dropped (app/platform/safe-href). A menu item that points at one of
274
+ * the store's own resources (any type but HTTP) — or at one of `storeHosts` —
275
+ * may still arrive as an absolute store URL; it becomes a same-origin path so
276
+ * soft navigation and the active rule both work. A genuine external HTTP link
277
+ * is kept absolute.
278
+ */
279
+ export function toMenuHref(url, type, storeHosts = []) {
280
+ const safe = safeHref(url);
281
+ if (!safe)
282
+ return null;
283
+ if (!/^(https?:)?\/\//i.test(safe))
284
+ return safe;
285
+ let parsed;
286
+ try {
287
+ parsed = new URL(safe, 'https://placeholder.invalid');
288
+ }
289
+ catch {
290
+ return null;
291
+ }
292
+ const hosts = storeHosts.map((h) => h.toLowerCase());
293
+ const internal = (type != null && type !== 'HTTP') || hosts.includes(parsed.host.toLowerCase()) || hosts.includes(parsed.hostname.toLowerCase());
294
+ return internal ? `${parsed.pathname || '/'}${parsed.search}${parsed.hash}` : safe;
295
+ }
296
+ /** How specifically `url` matches `here`: path length, or -1. Same rule as the layout's nav. */
297
+ function matchLength(url, here) {
298
+ if (!url || !here || /^[a-z][a-z0-9+.-]*:|^\/\//i.test(url))
299
+ return -1;
300
+ const path = url.split(/[?#]/)[0] || '/';
301
+ if (path === '/')
302
+ return here === '/' ? 1 : -1;
303
+ const p = path.replace(/\/+$/, '');
304
+ return here === p || here.startsWith(`${p}/`) ? p.length : -1;
305
+ }
306
+ function toMenuItems(items, opts) {
307
+ const here = opts.currentPath ? opts.currentPath.split(/[?#]/)[0].replace(/(.)\/+$/, '$1') : '';
308
+ const mapped = (items ?? []).filter((it) => it && typeof it.title === 'string').map((it) => {
309
+ const url = toMenuHref(it.url, it.type, opts.storeHosts);
310
+ const children = toMenuItems(it.items, opts);
311
+ const image = toImage(it.image);
312
+ return { title: it.title, url, ...(children.length ? { items: children } : {}), ...(image ? { image } : {}) };
313
+ });
314
+ if (here) {
315
+ let best = -1;
316
+ let bestLen = -1;
317
+ mapped.forEach((m, i) => {
318
+ const len = matchLength(m.url, here);
319
+ if (len > bestLen) {
320
+ best = i;
321
+ bestLen = len;
322
+ }
323
+ });
324
+ if (best >= 0)
325
+ mapped[best] = { ...mapped[best], active: true };
326
+ }
327
+ return mapped;
328
+ }
329
+ /** A runtime menu → Menu (recursive, every level). null when there is no menu. */
330
+ export function toMenu(menu, opts = {}) {
331
+ if (!menu)
332
+ return null;
333
+ return { handle: menu.handle ?? '', title: menu.title ?? '', items: toMenuItems(menu.items, opts) };
334
+ }
335
+ /** Menus by handle, for StoreContext.menus. Missing menus are left out. */
336
+ export function toMenuMap(menus, opts = {}) {
337
+ const out = {};
338
+ for (const m of menus) {
339
+ const mapped = toMenu(m, opts);
340
+ if (mapped && mapped.handle)
341
+ out[mapped.handle] = mapped;
342
+ }
343
+ return out;
344
+ }
345
+ // ── Shop ────────────────────────────────────────────────────────────────────
346
+ /** Storefront SDL payment enums → the UI's payment marks. Anything else has no mark and is left out. */
347
+ const PAYMENT_MARKS = {
348
+ VISA: 'visa',
349
+ MASTERCARD: 'mastercard',
350
+ AMERICAN_EXPRESS: 'amex',
351
+ AMEX: 'amex',
352
+ JCB: 'jcb',
353
+ DISCOVER: 'discover',
354
+ DINERS_CLUB: 'diners-club',
355
+ DINERS: 'diners-club',
356
+ UNIONPAY: 'unionpay',
357
+ UNION_PAY: 'unionpay',
358
+ CHINA_UNION_PAY: 'unionpay',
359
+ PAYPAL: 'paypal',
360
+ APPLE_PAY: 'apple-pay',
361
+ GOOGLE_PAY: 'google-pay',
362
+ ANDROID_PAY: 'google-pay',
363
+ PROMPTPAY: 'promptpay',
364
+ PROMPT_PAY: 'promptpay',
365
+ TRUEMONEY: 'truemoney',
366
+ TRUE_MONEY: 'truemoney',
367
+ };
368
+ export function toPaymentMethods(settings) {
369
+ const codes = [...(settings?.acceptedCardBrands ?? []), ...(settings?.supportedDigitalWallets ?? [])];
370
+ const out = [];
371
+ for (const c of codes) {
372
+ const mark = typeof c === 'string' ? PAYMENT_MARKS[c.toUpperCase()] : undefined;
373
+ if (mark && !out.includes(mark))
374
+ out.push(mark);
375
+ }
376
+ return out;
377
+ }
378
+ /** Dashboard network slugs the design draws a mark for → its network key. */
379
+ const SOCIAL_MARKS = {
380
+ instagram: 'instagram',
381
+ facebook: 'facebook',
382
+ twitter: 'x',
383
+ x: 'x',
384
+ tiktok: 'tiktok',
385
+ youtube: 'youtube',
386
+ };
387
+ /** Display names of the dashboard's other networks; an unknown slug is shown capitalised. */
388
+ const SOCIAL_NAMES = {
389
+ threads: 'Threads',
390
+ pinterest: 'Pinterest',
391
+ tumblr: 'Tumblr',
392
+ snapchat: 'Snapchat',
393
+ vimeo: 'Vimeo',
394
+ linkedin: 'LinkedIn',
395
+ spotify: 'Spotify',
396
+ whatsapp: 'WhatsApp',
397
+ kakaotalk: 'KakaoTalk',
398
+ };
399
+ const httpsUrl = (v) => {
400
+ if (typeof v !== 'string')
401
+ return undefined;
402
+ try {
403
+ const u = new URL(v);
404
+ return u.protocol === 'https:' && u.hostname ? u.href : undefined;
405
+ }
406
+ catch {
407
+ return undefined;
408
+ }
409
+ };
410
+ /**
411
+ * Settings → Social → the design's drawn networks (`social`) and the rest (`otherSocial`, generic
412
+ * link mark). Only https: URLs; one link per network, the first wins. Empty → both absent.
413
+ */
414
+ export function toSocial(links) {
415
+ const social = {};
416
+ const otherSocial = [];
417
+ for (const l of links ?? []) {
418
+ const platform = typeof l?.platform === 'string' ? l.platform.trim().toLowerCase() : '';
419
+ const url = httpsUrl(l?.url);
420
+ if (!platform || !url)
421
+ continue;
422
+ const mark = SOCIAL_MARKS[platform];
423
+ if (mark) {
424
+ if (!social[mark])
425
+ social[mark] = url;
426
+ }
427
+ else if (!otherSocial.some((o) => o.platform === platform)) {
428
+ otherSocial.push({ platform, label: SOCIAL_NAMES[platform] ?? platform.charAt(0).toUpperCase() + platform.slice(1), url });
429
+ }
430
+ }
431
+ return {
432
+ ...(Object.keys(social).length ? { social } : {}),
433
+ ...(otherSocial.length ? { otherSocial } : {}),
434
+ };
435
+ }
436
+ /**
437
+ * The shop + the theme's Brand settings → Shop.
438
+ *
439
+ * Name: the store name (Settings › General), else the theme's `shopName` setting
440
+ * (a fallback only — D-13). Logo: the theme's
441
+ * `logo` setting, else Settings → Brand (the same precedence as
442
+ * app/platform/safe-values `resolveLogo`, which this reuses).
443
+ */
444
+ /**
445
+ * The product's gallery with its hosted videos (Theme ABI `Product.media`, storefront-query rev 2.34). Only `image` and
446
+ * `video` items with a playable source map; YouTube / Vimeo / 3D never do (the storefront plays no third-party
447
+ * player). No video left ⇒ absent, and the gallery stays `images`.
448
+ */
449
+ export function toProductMedia(list) {
450
+ const out = [];
451
+ for (const m of list ?? []) {
452
+ if (!m)
453
+ continue;
454
+ if (m.type === 'image') {
455
+ const image = toImage(m.image ?? null);
456
+ if (image)
457
+ out.push({ type: 'image', image: !image.alt && m.alt ? { ...image, alt: m.alt } : image });
458
+ continue;
459
+ }
460
+ if (m.type === 'external_video') {
461
+ const embedUrl = str(m.embedUrl ?? undefined);
462
+ const host = m.host === 'YOUTUBE' ? 'youtube' : m.host === 'VIMEO' ? 'vimeo' : null;
463
+ const alt = str(m.alt ?? undefined);
464
+ if (host && embedUrl)
465
+ out.push({ type: 'external_video', host, embedUrl, ...(alt ? { alt } : {}) });
466
+ continue;
467
+ }
468
+ if (m.type === 'model_3d') {
469
+ const src = modelSrc((m.sources ?? []).find((s) => s && s.mimeType === 'model/gltf-binary')?.url);
470
+ if (!src)
471
+ continue;
472
+ // iOS Quick Look: the merchant's own USDZ when there is one (else the viewer makes one from the GLB on the device)
473
+ const iosSrc = modelSrc((m.sources ?? []).find((s) => s && s.mimeType === 'model/vnd.usdz+zip')?.url);
474
+ const poster = toImage(m.previewImage ?? null);
475
+ const alt = str(m.alt ?? undefined);
476
+ out.push({ type: 'model', src, ...(iosSrc ? { iosSrc } : {}), ...(poster ? { poster } : {}), ...(alt ? { alt } : {}) });
477
+ continue;
478
+ }
479
+ if (m.type !== 'video')
480
+ continue;
481
+ const sources = (m.sources ?? []).filter((s) => s && typeof s.url === 'string' && s.url.startsWith('https://') && s.mimeType).map((s) => ({ src: s.url, type: s.mimeType }));
482
+ if (!sources.length)
483
+ continue;
484
+ const poster = toImage(m.previewImage ?? null);
485
+ const alt = str(m.alt ?? undefined);
486
+ out.push({ type: 'video', sources, ...(poster ? { poster } : {}), ...(alt ? { alt } : {}) });
487
+ }
488
+ return out.some((m) => m.type !== 'image') ? { media: out } : {};
489
+ }
490
+ /** The platform's same-origin model route (storefront-edge `/_tq/model/`), which serves a store's own `.glb` / `.usdz` uploads. */
491
+ export const MODEL_ROUTE = '/_tq/model/';
492
+ /**
493
+ * The store-media hosts of the new system's buckets (storefront-edge core/media-hosts.ts): Prod `cdn.mytanqory.com`,
494
+ * Dev `cdn.tanqory.dev` / `cdn.mytanqory.dev`, and a bucket's `pub-<hex>.r2.dev` URL. The old system's `cdn.tanqory.com`
495
+ * serves nothing (404 on every path, 2026-11-19), so it is not one: with it as the only host, every model was dropped.
496
+ */
497
+ const MODEL_URL = /^https:\/\/(cdn\.mytanqory\.com|cdn\.tanqory\.dev|cdn\.mytanqory\.dev|pub-[0-9a-f]{32}\.r2\.dev)\/(stores\/[0-9A-Fa-f-]+\/[A-Za-z0-9._~\/-]+\.(?:glb|usdz))$/;
498
+ /**
499
+ * A store-media `.glb` / `.usdz` URL → its same-origin model route (`/_tq/model/stores/<store>/<path>`): the media host
500
+ * sends no CORS headers, and the page CSP lets a viewer read only its own origin. An already same-origin route path is
501
+ * kept (the read model may hand one over). Anything else ⇒ null (not shown).
502
+ */
503
+ export function modelSrc(url) {
504
+ if (typeof url !== 'string')
505
+ return null;
506
+ if (url.startsWith(MODEL_ROUTE)) {
507
+ const rest = url.slice(MODEL_ROUTE.length);
508
+ return /^stores\/[0-9A-Fa-f-]+\/[A-Za-z0-9._~\/-]+\.(?:glb|usdz)$/.test(rest) && !rest.split('/').some((s) => s === '.' || s === '..') ? url : null;
509
+ }
510
+ const m = MODEL_URL.exec(url);
511
+ return m && !m[2].split('/').some((s) => s === '.' || s === '..') ? `${MODEL_ROUTE}${m[2]}` : null;
512
+ }
513
+ /** A merchant-published postal address → display lines: street (address1, address2), "city province zip", country. */
514
+ export function addressLines(a) {
515
+ if (!a)
516
+ return [];
517
+ const street = [a.address1, a.address2].filter((s) => Boolean(s && s.trim())).join(', ');
518
+ const cityLine = [a.city, a.province, a.zip].filter((s) => Boolean(s && s.trim())).join(' ');
519
+ return [street, cityLine, a.country ?? a.countryCode ?? ''].filter((s) => s.trim() !== '');
520
+ }
521
+ export function toShop(shop, settings = {}) {
522
+ const name = str(shop?.name)?.trim() ?? str(settings.shopName)?.trim() ?? '';
523
+ const resolved = resolveLogo({ logo: settings.logo ?? '' }, shop?.brand ?? null);
524
+ // Dimensions are known only when the logo is the brand's own image.
525
+ const brandLogo = shop?.brand?.logo;
526
+ const logo = resolved
527
+ ? toImage({
528
+ url: resolved.url,
529
+ altText: resolved.altText,
530
+ ...(brandLogo && brandLogo.url === resolved.url ? { width: brandLogo.width, height: brandLogo.height } : {}),
531
+ })
532
+ : null;
533
+ const email = str(shop?.email ?? undefined);
534
+ const phone = str(shop?.phone ?? undefined);
535
+ const paymentMethods = toPaymentMethods(shop?.paymentSettings);
536
+ const freeShipping = toMoney(shop?.freeShippingThreshold ?? null);
537
+ const address = addressLines(shop?.address);
538
+ const slogan = str(shop?.brand?.slogan ?? undefined);
539
+ const shortDescription = str(shop?.brand?.shortDescription ?? undefined);
540
+ const cover = shop?.brand?.coverImage;
541
+ const coverImage = cover?.url ? toImage({ url: cover.url, altText: cover.altText ?? null, width: cover.width, height: cover.height }) : null;
542
+ return {
543
+ name,
544
+ logo,
545
+ ...(slogan ? { slogan } : {}),
546
+ ...(shortDescription ? { shortDescription } : {}),
547
+ ...(coverImage ? { coverImage } : {}),
548
+ ...(email ? { email } : {}),
549
+ ...(phone ? { phone } : {}),
550
+ ...(shop?.taxesIncluded === true ? { taxesIncluded: true } : {}),
551
+ ...(freeShipping && freeShipping.currencyCode ? { freeShippingThreshold: freeShipping } : {}),
552
+ ...(shop?.signInLinks === false ? { signInLinks: false } : {}),
553
+ ...(shop?.policyLinks ? { policyLinks: shop.policyLinks.map((p) => ({ handle: p.handle, title: p.title, url: p.url })) } : {}),
554
+ ...(shop?.consentBanner ? { consentBanner: shop.consentBanner } : {}),
555
+ ...(shop?.paymentSettings?.currencyCode ? { currencyCode: shop.paymentSettings.currencyCode } : {}),
556
+ ...(shop?.moneyFormat && (shop.moneyFormat.withCurrency || shop.moneyFormat.withoutCurrency)
557
+ ? { moneyFormat: { ...(shop.moneyFormat.withCurrency ? { withCurrency: shop.moneyFormat.withCurrency } : {}), ...(shop.moneyFormat.withoutCurrency ? { withoutCurrency: shop.moneyFormat.withoutCurrency } : {}) } }
558
+ : {}),
559
+ ...toSocial(shop?.socialLinks),
560
+ ...(shop?.paymentSettings ? { paymentMethods } : {}),
561
+ ...(address.length ? { address } : {}),
562
+ ...(shop?.popups?.length ? { popups: shop.popups.map(toPopup) } : {}),
563
+ // rev 2.48 (NEW-MKT-10): the programs as the kit shop holds them, copied so a theme can never write back
564
+ ...(shop?.loyalty ? { loyalty: structuredClone(shop.loyalty) } : {}),
565
+ ...(shop?.referrals ? { referrals: structuredClone(shop.referrals) } : {}),
566
+ // A4: the spam-protection switches and the public widget key, copied whole (convert.ts kept them only whole)
567
+ ...(shop?.spamProtection ? { spamProtection: { contactForms: shop.spamProtection.contactForms, authPages: shop.spamProtection.authPages, siteKey: shop.spamProtection.siteKey } } : {}),
568
+ };
569
+ }
570
+ /** A pop-up as the theme sees it: the same members, the image as a theme `Image`. */
571
+ function toPopup(p) {
572
+ const { image, pages, ...rest } = p;
573
+ const img = image ? toImage({ url: image.url, altText: image.altText }) : null;
574
+ return { ...rest, pages: [...pages], ...(img ? { image: img } : {}) };
575
+ }
576
+ // ── Localization ────────────────────────────────────────────────────────────
577
+ function englishLanguageName(code) {
578
+ try {
579
+ const names = new Intl.DisplayNames(['en'], { type: 'language' });
580
+ const n = names.of(code);
581
+ return n && n !== code ? n : undefined;
582
+ }
583
+ catch {
584
+ return undefined;
585
+ }
586
+ }
587
+ function currencySymbol(currency) {
588
+ if (currency?.symbol)
589
+ return currency.symbol;
590
+ const code = currency?.isoCode;
591
+ if (!code)
592
+ return '';
593
+ try {
594
+ const part = new Intl.NumberFormat('en', { style: 'currency', currency: code, currencyDisplay: 'narrowSymbol' })
595
+ .formatToParts(0)
596
+ .find((p) => p.type === 'currency');
597
+ return part?.value ?? code;
598
+ }
599
+ catch {
600
+ return code;
601
+ }
602
+ }
603
+ function toMarket(country, language) {
604
+ const code = language?.isoCode ?? '';
605
+ const english = code ? englishLanguageName(code) : undefined;
606
+ // theme-abi Locale-2: with the platform's names, `name` is the language in the page's language and `endonymName`
607
+ // the language in itself; without them `name` is already the endonym
608
+ const endonym = language?.endonymName;
609
+ return {
610
+ countryCode: country?.isoCode ?? '',
611
+ country: country?.name ?? '',
612
+ currencyCode: country?.currency?.isoCode ?? '',
613
+ currencySymbol: currencySymbol(country?.currency),
614
+ languageCode: code,
615
+ language: endonym ?? language?.name ?? '',
616
+ ...(english ? { languageEnglish: english } : {}),
617
+ ...(endonym && language?.name ? { languageLocalized: language.name } : {}),
618
+ };
619
+ }
620
+ /**
621
+ * Localization → Localization, or null (no Markets: the picker hides).
622
+ *
623
+ * The runtime publishes countries and languages as two independent lists —
624
+ * every published language is available in every country — so `available` is
625
+ * their product. `current` is always included in `available`.
626
+ */
627
+ export function toLocalization(loc) {
628
+ if (!loc || !loc.country)
629
+ return null;
630
+ const countries = loc.availableCountries?.length ? loc.availableCountries : [loc.country];
631
+ const languages = loc.availableLanguages?.length ? loc.availableLanguages : loc.language ? [loc.language] : [null];
632
+ // The choices are the store's countries. A visitor's own country that the store does not sell to is not one of
633
+ // them: offering it (and making it "current") showed a one-market store a country picker for a country it
634
+ // cannot sell to. The current market is then the store's first country, and a one-market store shows no control.
635
+ const sells = countries.some((c) => c.isoCode === loc.country.isoCode);
636
+ const current = toMarket(sells ? loc.country : countries[0], loc.language ?? languages[0]);
637
+ const available = [];
638
+ const key = (m) => `${m.countryCode}|${m.languageCode}`;
639
+ const seen = new Set();
640
+ for (const c of countries) {
641
+ // A market that names its own languages offers only those; otherwise every published language.
642
+ const own = c.availableLanguages?.length ? c.availableLanguages : languages;
643
+ for (const l of own) {
644
+ const m = toMarket(c, l);
645
+ if (!seen.has(key(m))) {
646
+ seen.add(key(m));
647
+ available.push(m);
648
+ }
649
+ }
650
+ }
651
+ if (!seen.has(key(current)))
652
+ available.unshift(current);
653
+ return { current, available };
654
+ }
655
+ // ── Cart ────────────────────────────────────────────────────────────────────
656
+ export function toCartSummary(cart) {
657
+ const lines = cart?.lines ?? [];
658
+ const counted = lines.reduce((n, l) => n + (Number.isFinite(l?.quantity) ? l.quantity : 0), 0);
659
+ return { itemCount: typeof cart?.totalQuantity === 'number' ? cart.totalQuantity : counted, lineCount: lines.length };
660
+ }
661
+ /**
662
+ * One cart line → CartLine.
663
+ *
664
+ * A line carries id + title + image + price, its product as handle + title, and
665
+ * — when the cart source sends the whole variant (Theme ABI v2) — its options,
666
+ * compare-at and availability. No vendor and no stock. `variant.available` is
667
+ * true unless the source says otherwise: the backend accepted the line, and it
668
+ * refuses unpurchasable merchandise at add/update time.
669
+ */
670
+ export function toCartLine(line) {
671
+ const price = toMoney(line?.price);
672
+ const currency = price?.currencyCode ?? toMoney(line?.lineSubtotal)?.currencyCode ?? '';
673
+ const handle = line?.productHandle ?? '';
674
+ const quantity = Number.isFinite(line?.quantity) ? line.quantity : 0;
675
+ // A real sale only (was > now); the line's was-total is that per-unit price × quantity.
676
+ const compareAt = saleOnly(toMoney(line?.compareAtPrice), price);
677
+ // Board 35 #14: the line's total after its own (product) discounts, a Buy X get Y free item included, as the cart's
678
+ // subtotal and checkout count it; the price before them is `cost.subtotal`, only when a discount took something off.
679
+ const subtotal = toMoney(line?.lineSubtotal);
680
+ const total = toMoney(line?.lineTotal);
681
+ const after = total && subtotal && total.currencyCode === subtotal.currencyCode && total.amount < subtotal.amount && total.amount >= 0 ? total : null;
682
+ return {
683
+ id: line?.id ?? '',
684
+ quantity,
685
+ product: { title: line?.title ?? '', handle, url: handle ? productUrl(handle) : '', ...(line?.productId ? { id: line.productId } : {}) },
686
+ variant: {
687
+ id: line?.variantId ?? '',
688
+ title: line?.variantTitle ?? '',
689
+ price: requiredMoney(price, currency),
690
+ compareAtPrice: compareAt,
691
+ available: line?.availableForSale !== false,
692
+ // A cart line never carries a stock count (Theme ABI: CartLine.merchandise has none) — absent.
693
+ selectedOptions: (line?.selectedOptions ?? []).filter((o) => o && typeof o.name === 'string').map((o) => ({ name: o.name, value: o.value ?? '' })),
694
+ image: toImage(line?.image),
695
+ },
696
+ cost: {
697
+ total: requiredMoney(after ?? subtotal, currency),
698
+ compareAtTotal: compareAt ? { amount: Math.round(compareAt.amount * quantity * 1e6) / 1e6, currencyCode: compareAt.currencyCode } : null,
699
+ ...(after && subtotal ? { subtotal } : {}),
700
+ },
701
+ ...toCartLineDiscounts(line?.discountAllocations, currency),
702
+ ...toCartLineSellingPlan(line?.sellingPlanAllocation),
703
+ ...toCartLineAttributes(line?.attributes),
704
+ };
705
+ }
706
+ /** The line's own discounts by name (`line_item.discount_allocations`): a title or a code and a positive amount in the
707
+ * line's currency; none usable ⇒ the key is absent. */
708
+ function toCartLineDiscounts(raw, currency) {
709
+ if (!Array.isArray(raw))
710
+ return {};
711
+ const out = [];
712
+ for (const d of raw) {
713
+ const title = (d?.title ?? d?.code ?? '').trim();
714
+ const amount = toMoney(d?.amount);
715
+ if (title && amount && amount.amount > 0 && (!currency || amount.currencyCode === currency))
716
+ out.push({ title, amount });
717
+ }
718
+ return out.length ? { discounts: out } : {};
719
+ }
720
+ /** The line's custom attributes (a gift card's recipient, NEW-PROD-12) — dropped here before 2.0.0-alpha.14, so a theme
721
+ * could not show who a gift card goes to. Only string key/value pairs with a key pass; none ⇒ the key is absent. */
722
+ function toCartLineAttributes(raw) {
723
+ if (!Array.isArray(raw))
724
+ return {};
725
+ const attributes = raw
726
+ .filter((a) => !!a && typeof a === 'object' && typeof a.key === 'string' && a.key !== '')
727
+ .map((a) => ({ key: a.key, value: typeof a.value === 'string' ? a.value : '' }));
728
+ return attributes.length ? { attributes } : {};
729
+ }
730
+ /** The line's plan (NEW-SUB-2), only when the source carries both of its prices (the Theme ABI does; the GraphQL driver does not). */
731
+ function toCartLineSellingPlan(a) {
732
+ const perDeliveryPrice = toMoney(a?.perDeliveryPrice);
733
+ const compareAtPrice = toMoney(a?.compareAtPrice);
734
+ if (!a || !a.sellingPlanId || !a.sellingPlanName || !perDeliveryPrice || !compareAtPrice)
735
+ return {};
736
+ return { sellingPlan: { id: a.sellingPlanId, name: a.sellingPlanName, perDeliveryPrice, compareAtPrice } };
737
+ }
738
+ /**
739
+ * The full cart (cart page). `discounts` is left out: the runtime keeps no per-code amount. The order-level
740
+ * discount is `discountTotal` (from the cart's own totals) and, when the host names them, `discountAllocations`.
741
+ */
742
+ export function toCart(cart) {
743
+ const lines = (cart?.lines ?? []).filter(Boolean).map(toCartLine);
744
+ const subtotal = toMoney(cart?.subtotal);
745
+ const currency = subtotal?.currencyCode ?? lines[0]?.cost.total.currencyCode ?? '';
746
+ const note = str(cart?.note ?? undefined);
747
+ const off = toMoney(cart?.discountAmount ?? null);
748
+ const discountTotal = off && off.amount > 0 && off.currencyCode === currency ? off : null;
749
+ const codes = (cart?.discountCodes ?? []).filter((d) => d && typeof d.code === 'string' && d.code !== '').map((d) => ({ code: d.code, applicable: d.applicable === true }));
750
+ const allocations = (cart?.discountAllocations ?? [])
751
+ .map((a) => {
752
+ const amount = toMoney(a?.amount);
753
+ const title = str(a?.title ?? undefined);
754
+ const code = str(a?.code ?? undefined);
755
+ return amount && amount.amount > 0 && amount.currencyCode === currency && (title || code) ? { ...(title ? { title } : {}), ...(code ? { code } : {}), amount } : null;
756
+ })
757
+ .filter((a) => a !== null);
758
+ return {
759
+ id: cart?.id ?? '',
760
+ lines,
761
+ ...(note ? { note } : {}),
762
+ itemCount: toCartSummary(cart).itemCount,
763
+ subtotal: requiredMoney(subtotal, currency),
764
+ total: requiredMoney(toMoney(cart?.total) ?? subtotal, currency),
765
+ ...(codes.length ? { discountCodes: codes } : {}),
766
+ ...(discountTotal ? { discountTotal } : {}),
767
+ ...(allocations.length ? { discountAllocations: allocations } : {}),
768
+ };
769
+ }
770
+ // ── Content ─────────────────────────────────────────────────────────────────
771
+ /** A page → the UI's page-body shape (StoreContext.currentPage / pages). */
772
+ export function toPage(page) {
773
+ if (!page)
774
+ return null;
775
+ return { title: page.title ?? '', html: page.body ?? '' };
776
+ }
777
+ /**
778
+ * An article → Article, or null when its blog is unknown (no URL can be built —
779
+ * search results arrive without one). Pass the blog handle when the caller
780
+ * knows it.
781
+ */
782
+ export function toArticle(a, blogHandle) {
783
+ if (!a)
784
+ return null;
785
+ const blog = str(a.blogHandle) ?? str(blogHandle);
786
+ if (!blog || !a.handle)
787
+ return null;
788
+ const excerpt = str(a.excerpt ?? undefined);
789
+ const author = str(a.author ?? undefined);
790
+ return {
791
+ id: a.id ?? a.handle,
792
+ handle: a.handle,
793
+ title: a.title ?? '',
794
+ ...(excerpt ? { excerpt } : {}),
795
+ ...(typeof a.contentHtml === 'string' ? { contentHtml: a.contentHtml } : {}),
796
+ url: articleUrl(blog, a.handle),
797
+ image: toImage(a.image),
798
+ ...(author ? { author } : {}),
799
+ publishedAt: a.publishedAt ?? '',
800
+ ...(a.tags?.length ? { tags: [...a.tags] } : {}),
801
+ blogHandle: blog,
802
+ ...(a.comments ? { comments: { moderated: a.comments.moderated, count: a.comments.count, comments: (a.comments.nodes ?? []).map((c) => ({ id: c.id, author: c.author, body: c.body, createdAt: c.createdAt })) } } : {}),
803
+ };
804
+ }
805
+ export function toBlog(blog) {
806
+ if (!blog || !blog.handle)
807
+ return null;
808
+ return {
809
+ id: blog.id ?? blog.handle,
810
+ handle: blog.handle,
811
+ title: blog.title ?? '',
812
+ url: blogUrl(blog.handle),
813
+ articles: (blog.articles ?? []).map((a) => toArticle(a, blog.handle)).filter((a) => Boolean(a)),
814
+ };
815
+ }
816
+ /**
817
+ * A shop policy → Policy. The URL is the theme's own policy route (the runtime's
818
+ * `url` may be absolute). `bodyHtml` is '' when the payload carries no body.
819
+ */
820
+ export function toPolicy(p) {
821
+ if (!p || !p.handle)
822
+ return null;
823
+ return { handle: p.handle, title: p.title ?? '', bodyHtml: p.body ?? '', url: policyUrl(p.handle) };
824
+ }
825
+ /** Every published policy by handle, for StoreContext.policies. */
826
+ export function toPolicies(shop) {
827
+ const out = {};
828
+ // Every policy the payload carries, not only the five named slots: `convert.shop` keeps a handle outside them
829
+ // (e.g. storefront-query rev 2.33 `data-sharing-opt-out`) under its own handle, and PolicyPage looks it up here.
830
+ for (const p of Object.values(shop?.policies ?? {})) {
831
+ const mapped = toPolicy(p);
832
+ if (mapped)
833
+ out[mapped.handle] = mapped;
834
+ }
835
+ return out;
836
+ }
837
+ /**
838
+ * Store locations: the postal address, phone, and (rev 2.73) the pickup / storefront marks and the weekly opening hours.
839
+ * No email, image or coordinates.
840
+ */
841
+ export function toLocations(list) {
842
+ return (list ?? []).filter(Boolean).map((l) => {
843
+ const a = l.address;
844
+ const cityLine = [a?.city, a?.province, a?.postalCode].filter((s) => Boolean(s && s.trim())).join(' ');
845
+ const address = [a?.address, cityLine, a?.country].filter((s) => Boolean(s && s.trim()));
846
+ const phone = str(a?.phone ?? undefined);
847
+ return {
848
+ id: l.id ?? '',
849
+ name: l.name ?? '',
850
+ address,
851
+ ...(phone ? { phone } : {}),
852
+ ...(l.pickupReadyIn ? { pickupReadyIn: l.pickupReadyIn } : {}),
853
+ ...(typeof l.pickup === 'boolean' ? { pickup: l.pickup } : {}),
854
+ ...(typeof l.storefront === 'boolean' ? { storefront: l.storefront } : {}),
855
+ ...(l.openingHours ? { openingHours: l.openingHours.map((p) => ({ ...p })) } : {}),
856
+ };
857
+ });
858
+ }
859
+ // ── Search + listing ────────────────────────────────────────────────────────
860
+ /**
861
+ * Search → SearchResults. `total` is the backend's count across every type.
862
+ * Articles whose blog is unknown are left out (see toArticle).
863
+ */
864
+ export function toSearchResults(query, r) {
865
+ return {
866
+ query: query ?? '',
867
+ products: toProducts(r?.products),
868
+ articles: (r?.articles ?? []).map((a) => toArticle(a)).filter((a) => Boolean(a)),
869
+ pages: (r?.pages ?? []).filter((p) => p && p.handle).map((p) => ({ title: p.title ?? '', url: pageUrl(p.handle) })),
870
+ total: typeof r?.totalCount === 'number' ? r.totalCount : 0,
871
+ };
872
+ }
873
+ /**
874
+ * Listing filters → Facets. List filters map value-for-value; `active` is set
875
+ * for the values whose `input` the shopper has applied. A PRICE_RANGE filter
876
+ * becomes a price facet only when its input carries the store's bounds and a
877
+ * currency is known.
878
+ */
879
+ export function toFacets(filters, opts = {}) {
880
+ const active = new Set(opts.activeInputs ?? []);
881
+ const out = [];
882
+ for (const f of filters ?? []) {
883
+ if (!f)
884
+ continue;
885
+ if (f.type === 'PRICE_RANGE') {
886
+ const bounds = priceOf(f.values?.[0]?.input);
887
+ if (!bounds || !opts.currencyCode)
888
+ continue;
889
+ const applied = [...active].map(priceOf).find(Boolean);
890
+ out.push({
891
+ id: f.id,
892
+ label: f.label,
893
+ type: 'price',
894
+ range: {
895
+ min: bounds.min ?? 0,
896
+ max: bounds.max ?? bounds.min ?? 0,
897
+ ...(applied?.min != null ? { from: applied.min } : {}),
898
+ ...(applied?.max != null ? { to: applied.max } : {}),
899
+ currencyCode: opts.currencyCode,
900
+ },
901
+ });
902
+ continue;
903
+ }
904
+ out.push({
905
+ id: f.id,
906
+ label: f.label,
907
+ type: 'list',
908
+ values: (f.values ?? []).map((v) => ({ id: v.id, label: v.label, count: Number.isFinite(v.count) ? v.count : 0, active: active.has(v.input) })),
909
+ });
910
+ }
911
+ return out;
912
+ }
913
+ function priceOf(input) {
914
+ if (!input)
915
+ return null;
916
+ try {
917
+ const parsed = JSON.parse(input);
918
+ const p = parsed?.price;
919
+ if (!p || typeof p !== 'object')
920
+ return null;
921
+ const min = typeof p.min === 'number' ? p.min : undefined;
922
+ const max = typeof p.max === 'number' ? p.max : undefined;
923
+ return min == null && max == null ? null : { min, max };
924
+ }
925
+ catch {
926
+ return null;
927
+ }
928
+ }
929
+ /**
930
+ * The trail for a route. The last item is the current page and carries no URL.
931
+ * A route whose own title is unknown returns [] rather than a trail that ends
932
+ * on a link — the breadcrumbs section then renders nothing.
933
+ */
934
+ export function toBreadcrumbs(input) {
935
+ const home = str(input?.labels?.home);
936
+ if (!home)
937
+ return [];
938
+ const m = matchRoute(input.pathname || '/');
939
+ const root = { title: home, url: '/' };
940
+ const title = (t) => str(t?.title);
941
+ const label = (l) => (str(l) ? [root, { title: l }] : []);
942
+ switch (m.template) {
943
+ case 'index':
944
+ return [{ title: home }];
945
+ case 'list-collections':
946
+ return label(input.labels.collections);
947
+ case 'search':
948
+ return label(input.labels.search);
949
+ case 'cart':
950
+ return label(input.labels.cart);
951
+ case 'account':
952
+ return label(input.labels.account);
953
+ case 'collection': {
954
+ const t = title(input.collection);
955
+ if (!t)
956
+ return [];
957
+ const mid = str(input.labels.collections) ? [{ title: input.labels.collections, url: '/collections' }] : [];
958
+ return [root, ...mid, { title: t }];
959
+ }
960
+ case 'product': {
961
+ const t = title(input.product);
962
+ if (!t)
963
+ return [];
964
+ const c = input.collection;
965
+ const via = c?.handle && str(c.title) ? [{ title: c.title, url: collectionUrl(c.handle) }] : [];
966
+ return [root, ...via, { title: t }];
967
+ }
968
+ case 'page': {
969
+ const t = title(input.page);
970
+ return t ? [root, { title: t }] : [];
971
+ }
972
+ case 'policy': {
973
+ const t = title(input.policy);
974
+ return t ? [root, { title: t }] : [];
975
+ }
976
+ case 'blog': {
977
+ const t = title(input.blog);
978
+ return t ? [root, { title: t }] : [];
979
+ }
980
+ case 'article': {
981
+ const t = title(input.article);
982
+ if (!t)
983
+ return [];
984
+ const b = title(input.blog);
985
+ const via = b && m.blogHandle ? [{ title: b, url: blogUrl(m.blogHandle) }] : [];
986
+ return [root, ...via, { title: t }];
987
+ }
988
+ default:
989
+ return [];
990
+ }
991
+ }
992
+ /**
993
+ * Whether the cookie banner shows to a shopper who has not decided yet (Settings › Customer privacy,
994
+ * contract rev 2): the platform's `regionRequiresBanner` first (EEA, UK, unknown location, and the
995
+ * merchant's own regions — or a platform that does not say), then the merchant's switch: with "Use
996
+ * automated settings" the legal floor alone (board 35 #42: it showed to every visitor everywhere), else
997
+ * also the regions the merchant chose. No merchant config (older data) = shown, as before.
998
+ */
999
+ export function consentBannerShows(readout, banner) {
1000
+ if (readout.regionRequiresBanner !== false)
1001
+ return true;
1002
+ if (!banner)
1003
+ return true;
1004
+ if (!banner.enabled || banner.automated)
1005
+ return false;
1006
+ const country = readout.geo?.country?.toUpperCase();
1007
+ const region = readout.geo?.region?.toUpperCase();
1008
+ return Boolean((country && banner.regions.includes(country)) || (region && banner.regions.includes(region)));
1009
+ }