@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,1330 @@
1
+ const MENU_TYPES = new Set([
2
+ 'FRONTPAGE', 'COLLECTION', 'COLLECTIONS', 'PRODUCT', 'CATALOG', 'PAGE', 'BLOG', 'ARTICLE', 'SEARCH', 'SHOP_POLICY', 'HTTP',
3
+ ]);
4
+ export function image(i) {
5
+ if (!i?.url)
6
+ return null;
7
+ return {
8
+ url: i.url,
9
+ ...(i.altText ? { altText: i.altText } : {}),
10
+ ...(typeof i.width === 'number' ? { width: i.width } : {}),
11
+ ...(typeof i.height === 'number' ? { height: i.height } : {}),
12
+ ...(i.width && i.height ? { aspectRatio: i.width / i.height } : {}),
13
+ };
14
+ }
15
+ /** Plain text of an HTML body, for the surfaces that show text only (cards, meta description). */
16
+ export function plainText(html) {
17
+ return String(html ?? '')
18
+ .replace(/<[^>]*>/g, ' ')
19
+ .replace(/&nbsp;/g, ' ')
20
+ .replace(/&amp;/g, '&')
21
+ .replace(/&lt;/g, '<')
22
+ .replace(/&gt;/g, '>')
23
+ .replace(/&quot;/g, '"')
24
+ .replace(/&#39;/g, "'")
25
+ .replace(/\s+/g, ' ')
26
+ .trim();
27
+ }
28
+ /** `quantityAvailable` when the platform sent a usable one (an integer 0–999), else undefined. */
29
+ function stock(v) {
30
+ const q = v.quantityAvailable;
31
+ return typeof q === 'number' && Number.isInteger(q) && q >= 0 && q <= 999 ? q : undefined;
32
+ }
33
+ function variant(v) {
34
+ const q = stock(v);
35
+ return {
36
+ id: v.id,
37
+ title: v.title,
38
+ price: v.price,
39
+ compareAtPrice: v.compareAtPrice ?? null,
40
+ availableForSale: v.availableForSale,
41
+ selectedOptions: v.selectedOptions.map((o) => ({ name: o.name, value: o.value })),
42
+ image: image(v.image),
43
+ sku: v.sku ?? null,
44
+ // The platform sends a count only for a variant that stops selling at zero — DENY.
45
+ ...(q !== undefined ? { inventoryQuantity: q, inventoryPolicy: 'DENY' } : {}),
46
+ ...pickupIds(v.pickupLocationIds),
47
+ };
48
+ }
49
+ /**
50
+ * `ProductVariant.pickupLocationIds` (storefront-query rev 2.52, theme-abi alpha.24, O3): the ids of `Shop.locations`
51
+ * where the variant can be picked up. Kept only as a list of short strings (at most 50); absent stays absent.
52
+ */
53
+ function pickupIds(raw) {
54
+ if (!Array.isArray(raw))
55
+ return {};
56
+ return { pickupLocationIds: [...new Set(raw.filter((x) => typeof x === 'string' && x.length > 0 && x.length <= 128))].slice(0, 50) };
57
+ }
58
+ export function product(p) {
59
+ const variants = p.variants?.nodes ?? [];
60
+ const first = variants.find((v) => v.availableForSale) ?? variants[0];
61
+ const min = p.priceRange.minVariantPrice;
62
+ const was = p.compareAtPriceRange?.maxVariantPrice;
63
+ return {
64
+ id: p.id,
65
+ handle: p.handle,
66
+ title: p.title,
67
+ templateSuffix: p.templateSuffix ?? null,
68
+ price: min,
69
+ compareAtPrice: was && Number(was.amount) > Number(min.amount) ? was : null,
70
+ featuredImage: image(p.featuredImage),
71
+ ...(first ? { variantId: first.id } : {}),
72
+ availableForSale: p.availableForSale,
73
+ vendor: p.vendor ?? null,
74
+ productType: p.productType ?? null,
75
+ tags: [...p.tags],
76
+ description: plainText(p.descriptionHtml),
77
+ descriptionHtml: p.descriptionHtml,
78
+ images: p.images.map(image).filter((i) => i !== null),
79
+ options: p.options.map((o) => ({ name: o.name, values: [...o.values] })),
80
+ variants: variants.map(variant),
81
+ seo: { title: p.seo?.title ?? null, description: p.seo?.description ?? null },
82
+ ...metafieldsOf(p),
83
+ ...(p.collections ? { collections: p.collections.map((c) => ({ handle: c.handle, title: c.title })) } : {}),
84
+ ...lowStock(p.lowStockThreshold),
85
+ // `Product.isGiftCard` (storefront-query rev 2.50, NEW-PROD-12): read as unknown, the kit builds against older ABI types
86
+ ...(p.isGiftCard === true ? { isGiftCard: true } : {}),
87
+ ...productAutomaticDiscounts(p.automaticDiscounts),
88
+ ...productMedia(p.media),
89
+ ...productRating(p.rating),
90
+ ...productReviews(p.reviews),
91
+ ...productSellingPlanGroups(p.sellingPlanGroups),
92
+ };
93
+ }
94
+ /**
95
+ * Published reviews asked for on the product route and by `fetchProduct` (`reviewsFirst`, storefront-query rev 2.38 /
96
+ * theme-abi alpha.19): the most a product document carries, so the section pages them without another call.
97
+ */
98
+ export const REVIEWS_FIRST = 50;
99
+ const isStarRating = (n) => typeof n === 'number' && Number.isInteger(n) && n >= 1 && n <= 5;
100
+ const SECOND_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/;
101
+ const oneLine = (v, max) => (typeof v === 'string' && v.trim() !== '' ? v.trim().slice(0, max) : null);
102
+ /**
103
+ * storefront-query rev 2.45 (O4): the storefront-readable metafields of a product, collection, page, article or the
104
+ * shop — `"namespace.key" → {type, value}` as the platform stores it — as the display strings a section setting
105
+ * bound to a dynamic source shows. Read as unknown: the ABI types older than rev 2.45 carry `metafields` on Product
106
+ * only, and a malformed entry must not break a page. Absent ⇒ no member, so a resource without metafields converts
107
+ * exactly as before.
108
+ */
109
+ export function metafieldsOf(raw) {
110
+ const map = raw?.metafields;
111
+ if (!map || typeof map !== 'object' || Array.isArray(map))
112
+ return {};
113
+ const out = {};
114
+ for (const [k, v] of Object.entries(map)) {
115
+ if (!/^[^.\s]{1,64}\.[^\s]{1,64}$/.test(k))
116
+ continue;
117
+ out[k] = metafieldText(v);
118
+ // A metaobject reference carries its entry's fields: each is a source of its own, `<ns>.<key>.<field>`.
119
+ const fields = v?.value?.fields;
120
+ if (/metaobject_reference$/.test(String(v?.type ?? '')) && fields && typeof fields === 'object' && !Array.isArray(fields)) {
121
+ for (const [f, fv] of Object.entries(fields))
122
+ if (/^[A-Za-z0-9_][A-Za-z0-9_-]{0,63}$/.test(f))
123
+ out[`${k}.${f}`] = textOf(fv, 0);
124
+ }
125
+ }
126
+ return Object.keys(out).length ? { metafields: out } : {};
127
+ }
128
+ /**
129
+ * One metafield → the text a theme shows. The platform sends `{type, value}`; an older answer may send the bare
130
+ * value. Text, number, boolean, url, date and color values are their own string; `rich_text` is the HTML or the
131
+ * rich-text JSON tree's text; a file / image reference is its URL (a string, or an object's `url`); a measurement
132
+ * (`dimension`, `weight`, `volume`) is "value unit"; money is "amount currency"; `rating` its value; a `list.*` value
133
+ * joins its items with ", "; a product / collection / page / article / metaobject reference (`{id, handle}`) is its
134
+ * handle, a list of them the handles joined with ",". Anything else (an object with none of these) is null — never
135
+ * "[object Object]".
136
+ */
137
+ export function metafieldText(entry) {
138
+ const typed = entry !== null && typeof entry === 'object' && !Array.isArray(entry) && 'value' in entry && 'type' in entry;
139
+ const type = typed ? String(entry.type ?? '') : '';
140
+ let value = typed ? entry.value : entry;
141
+ if (typeof value === 'string' && /^list\./.test(type) && value.trim().startsWith('[')) {
142
+ try {
143
+ value = JSON.parse(value);
144
+ }
145
+ catch {
146
+ /* keep the string */
147
+ }
148
+ }
149
+ // A list of references (`list.product_reference` …): the handles, comma-separated, the shape a list setting holds.
150
+ if (/^list\..*_reference$/.test(type) && Array.isArray(value)) {
151
+ const handles = value.map((x) => (x && typeof x === 'object' ? x.handle ?? x.url : null)).filter((h) => typeof h === 'string' && h !== '');
152
+ return handles.length ? handles.join(',') : null;
153
+ }
154
+ return textOf(value, 0);
155
+ }
156
+ function textOf(v, depth) {
157
+ if (v === null || v === undefined || depth > 4)
158
+ return null;
159
+ if (typeof v === 'string')
160
+ return v;
161
+ if (typeof v === 'number')
162
+ return Number.isFinite(v) ? String(v) : null;
163
+ if (typeof v === 'boolean')
164
+ return v ? 'true' : 'false';
165
+ if (Array.isArray(v)) {
166
+ const parts = v.map((x) => textOf(x, depth + 1)).filter((x) => x !== null && x !== '');
167
+ return parts.length ? parts.join(', ') : null;
168
+ }
169
+ if (typeof v === 'object') {
170
+ const o = v;
171
+ // A resource reference the projector resolved (`{id, handle}`): its handle, what a picker setting holds.
172
+ if (typeof o.handle === 'string' && o.handle)
173
+ return o.handle;
174
+ if (typeof o.url === 'string')
175
+ return o.url;
176
+ if (typeof o.src === 'string')
177
+ return o.src;
178
+ if (o.amount !== undefined && (typeof o.currency_code === 'string' || typeof o.currencyCode === 'string'))
179
+ return `${String(o.amount)} ${String(o.currency_code ?? o.currencyCode)}`;
180
+ if (o.value !== undefined && typeof o.unit === 'string')
181
+ return `${String(o.value)} ${o.unit}`;
182
+ if (o.value !== undefined && (o.scale_max !== undefined || o.scaleMax !== undefined))
183
+ return textOf(o.value, depth + 1);
184
+ // rich_text JSON tree (`{type: 'root', children: [...]}`): its text, paragraphs on their own line
185
+ if (Array.isArray(o.children)) {
186
+ const sep = o.type === 'root' || o.type === 'list' ? '\n' : '';
187
+ const parts = o.children.map((c) => (c && typeof c === 'object' && typeof c.value === 'string' ? (c.value) : textOf(c, depth + 1))).filter((x) => typeof x === 'string');
188
+ return parts.length ? parts.join(sep) : null;
189
+ }
190
+ if (typeof o.value === 'string' || typeof o.value === 'number')
191
+ return String(o.value);
192
+ }
193
+ return null;
194
+ }
195
+ /**
196
+ * `Product.rating` (storefront-query rev 2.38, theme-abi alpha.19, NEW-PROD-10): the aggregate over the product's
197
+ * PUBLISHED reviews — the mean (1–5), how many, and counts of 5, 4, 3, 2, 1 stars. The platform sends it only for a
198
+ * product with at least one published review; absent or not whole ⇒ absent, never an invented 0. Read as unknown:
199
+ * the kit builds against older ABI types.
200
+ */
201
+ export function productRating(raw) {
202
+ if (!raw || typeof raw !== 'object')
203
+ return {};
204
+ const r = raw;
205
+ const value = typeof r.value === 'number' && r.value >= 1 && r.value <= 5 ? r.value : null;
206
+ const count = typeof r.count === 'number' && Number.isInteger(r.count) && r.count >= 1 ? r.count : null;
207
+ const d = Array.isArray(r.distribution) && r.distribution.length === 5 && r.distribution.every((n) => typeof n === 'number' && Number.isInteger(n) && n >= 0) ? r.distribution : null;
208
+ if (value === null || count === null || d === null)
209
+ return {};
210
+ return { rating: { value, count, distribution: [d[0], d[1], d[2], d[3], d[4]] } };
211
+ }
212
+ /**
213
+ * `Product.reviews` (storefront-query rev 2.38): the connection of published reviews the product route asked for with
214
+ * `reviewsFirst`. Whole entries only (a display name, a body, a 1–5 rating, a second-precision date); an entry that
215
+ * is not whole is left out, and `totalCount` says how many the platform holds. Absent ⇒ absent (not asked for, or
216
+ * an older region).
217
+ */
218
+ export function productReviews(raw) {
219
+ if (!raw || typeof raw !== 'object' || !Array.isArray(raw.nodes))
220
+ return {};
221
+ const c = raw;
222
+ const nodes = [];
223
+ for (const n of c.nodes.slice(0, 50)) {
224
+ if (!n || typeof n !== 'object')
225
+ continue;
226
+ const r = n;
227
+ const id = oneLine(r['id'], 128);
228
+ const author = oneLine(r['author'], 120);
229
+ const body = typeof r['body'] === 'string' && r['body'].trim() !== '' ? r['body'].trim().slice(0, 5000) : null;
230
+ const createdAt = typeof r['createdAt'] === 'string' && SECOND_TIMESTAMP.test(r['createdAt']) ? r['createdAt'] : null;
231
+ if (!id || !author || !body || !createdAt || !isStarRating(r['rating']))
232
+ continue;
233
+ const title = oneLine(r['title'], 150);
234
+ const reply = r['reply'] && typeof r['reply'] === 'object' ? r['reply'] : null;
235
+ const replyBody = reply && typeof reply.body === 'string' && reply.body.trim() !== '' ? reply.body.trim().slice(0, 5000) : null;
236
+ const replyAt = reply && typeof reply.createdAt === 'string' && SECOND_TIMESTAMP.test(reply.createdAt) ? reply.createdAt : null;
237
+ nodes.push({
238
+ id,
239
+ rating: r['rating'],
240
+ ...(title ? { title } : {}),
241
+ body,
242
+ author,
243
+ createdAt,
244
+ verifiedPurchase: r['verifiedPurchase'] === true,
245
+ ...(replyBody && replyAt ? { reply: { body: replyBody, createdAt: replyAt } } : {}),
246
+ });
247
+ }
248
+ const totalCount = typeof c.totalCount === 'number' && Number.isInteger(c.totalCount) && c.totalCount >= nodes.length ? c.totalCount : nodes.length;
249
+ return { reviews: { nodes, totalCount } };
250
+ }
251
+ const SELLING_PLAN_INTERVALS = new Set(['DAY', 'WEEK', 'MONTH', 'YEAR']);
252
+ const DECIMAL = /^\d{1,15}(\.\d{1,4})?$/;
253
+ /**
254
+ * `Product.sellingPlanGroups` (storefront-query rev 2.39, theme-abi alpha.20, NEW-SUB-1): the product's selling plan
255
+ * groups with their SUBSCRIPTION plans. A plan must be whole (an id, a name, a known interval, a whole interval count;
256
+ * a discount with a known type and a positive decimal value, a percentage at most 100) or it is left out; a group
257
+ * left with no plan is left out; none left ⇒ no member. Read as unknown: the kit builds against older ABI types.
258
+ */
259
+ export function productSellingPlanGroups(raw) {
260
+ if (!Array.isArray(raw))
261
+ return {};
262
+ const out = [];
263
+ for (const g of raw.slice(0, 10)) {
264
+ if (!g || typeof g !== 'object')
265
+ continue;
266
+ const r = g;
267
+ const name = typeof r.name === 'string' ? r.name.trim() : '';
268
+ if (typeof r.id !== 'string' || !r.id || !name || !Array.isArray(r.plans))
269
+ continue;
270
+ const sellingPlans = [];
271
+ for (const p of r.plans.slice(0, 20)) {
272
+ if (!p || typeof p !== 'object')
273
+ continue;
274
+ const q = p;
275
+ const planName = typeof q.name === 'string' ? q.name.trim() : '';
276
+ const interval = typeof q.interval === 'string' && SELLING_PLAN_INTERVALS.has(q.interval) ? q.interval : null;
277
+ const count = typeof q.intervalCount === 'number' && Number.isInteger(q.intervalCount) && q.intervalCount >= 1 ? q.intervalCount : null;
278
+ if (typeof q.id !== 'string' || !q.id || !planName || !interval || count === null)
279
+ continue;
280
+ let discount = null;
281
+ if (q.discount !== undefined && q.discount !== null) {
282
+ const d = q.discount;
283
+ const type = d.type === 'percentage' || d.type === 'fixed' || d.type === 'price' ? d.type : null;
284
+ const value = typeof d.value === 'string' && DECIMAL.test(d.value) ? Number(d.value) : NaN;
285
+ if (!type || !(value >= 0) || (type === 'percentage' && (value <= 0 || value > 100)) || (type === 'fixed' && value <= 0))
286
+ continue;
287
+ discount = { type, value };
288
+ }
289
+ const options = Array.isArray(q.options) ? q.options.filter((o) => !!o && typeof o === 'object' && typeof o.name === 'string' && typeof o.value === 'string').map((o) => ({ name: o.name, value: o.value })) : [];
290
+ sellingPlans.push({
291
+ id: q.id,
292
+ name: planName.slice(0, 255),
293
+ description: typeof q.description === 'string' && q.description.trim() ? q.description.trim() : null,
294
+ recurringDeliveries: true,
295
+ options,
296
+ interval,
297
+ intervalCount: count,
298
+ ...(discount ? { discount } : {}),
299
+ });
300
+ }
301
+ if (!sellingPlans.length)
302
+ continue;
303
+ const options = Array.isArray(r.options) ? r.options.filter((o) => !!o && typeof o === 'object' && typeof o.name === 'string' && Array.isArray(o.values)).map((o) => ({ name: o.name, values: o.values.filter((v) => typeof v === 'string') })) : [];
304
+ const variantIds = Array.isArray(r.variantIds) ? r.variantIds.filter((v) => typeof v === 'string' && v !== '') : [];
305
+ out.push({
306
+ id: r.id,
307
+ name: name.slice(0, 255),
308
+ appName: null,
309
+ description: typeof r.description === 'string' && r.description.trim() ? r.description.trim() : null,
310
+ options,
311
+ sellingPlans,
312
+ ...(variantIds.length ? { variantIds } : {}),
313
+ });
314
+ }
315
+ return out.length ? { sellingPlanGroups: out } : {};
316
+ }
317
+ const VIDEO_TYPES = new Set(['video/mp4', 'video/webm', 'video/quicktime']);
318
+ const HTTPS = /^https:\/\/\S+$/;
319
+ /** rev 2.52: the only players an external video may use — each host's privacy-enhanced embed, by id. */
320
+ const EMBED_URL = /^https:\/\/(www\.youtube-nocookie\.com\/embed|player\.vimeo\.com\/video)\/[A-Za-z0-9_-]{1,20}$/;
321
+ /**
322
+ * `Product.media` (storefront-query rev 2.34, theme-abi alpha.17, QA NEW-PROD-2): the gallery in the merchant's order
323
+ * with each HOSTED video. The platform sends it only when the product has a video; images-only products have none and
324
+ * the gallery stays `images`. An item that is not whole (an image without a URL, a video without an https mp4 / webm /
325
+ * quicktime source) is left out; no video left ⇒ no `media`. Read as unknown: the kit builds against older ABI types.
326
+ */
327
+ export function productMedia(raw) {
328
+ if (!Array.isArray(raw))
329
+ return {};
330
+ const out = [];
331
+ for (const [i, m] of raw.slice(0, 250).entries()) {
332
+ if (!m || typeof m !== 'object')
333
+ continue;
334
+ const r = m;
335
+ const alt = typeof r.alt === 'string' && r.alt.trim() ? r.alt.trim() : null;
336
+ if (r.mediaContentType === 'IMAGE') {
337
+ const img = image(r.image);
338
+ if (img)
339
+ out.push({ id: `media-${i}`, type: 'image', alt: alt ?? img.altText ?? null, image: img });
340
+ continue;
341
+ }
342
+ // rev 2.52 (alpha.24): a YouTube / Vimeo video, by its privacy-enhanced player only
343
+ if (r.mediaContentType === 'EXTERNAL_VIDEO') {
344
+ const host = r.host === 'YOUTUBE' || r.host === 'VIMEO' ? r.host : null;
345
+ const embedUrl = typeof r.embedUrl === 'string' && EMBED_URL.test(r.embedUrl) ? r.embedUrl : null;
346
+ if (host && embedUrl && embedUrl.includes(host === 'YOUTUBE' ? 'youtube-nocookie' : 'vimeo'))
347
+ out.push({ id: `media-${i}`, type: 'external_video', alt, host, embedUrl });
348
+ continue;
349
+ }
350
+ // rev 2.52 (alpha.24): a 3D model — one binary glTF file of the store's library, and its USDZ for iOS Quick Look when
351
+ // the merchant gave one (theme-abi-v2 "Host capability: 3D models"). A source is an https media URL or the platform's
352
+ // same-origin model path (`/_tq/model/…`, which the read model may hand over directly).
353
+ if (r.mediaContentType === 'MODEL_3D' && Array.isArray(r.sources)) {
354
+ const sources = r.sources;
355
+ const pick = (type) => sources.find((s) => Boolean(s) && typeof s.url === 'string' && (HTTPS.test(s.url) || s.url.startsWith('/_tq/model/')) && s.mimeType === type);
356
+ const src = pick('model/gltf-binary');
357
+ if (!src)
358
+ continue;
359
+ const usdz = pick('model/vnd.usdz+zip');
360
+ const poster = image(r.previewImage);
361
+ out.push({ id: `media-${i}`, type: 'model_3d', alt, previewImage: poster && HTTPS.test(poster.url) ? poster : null, sources: [{ url: src.url, mimeType: src.mimeType, format: 'glb' }, ...(usdz ? [{ url: usdz.url, mimeType: usdz.mimeType, format: 'usdz' }] : [])] });
362
+ continue;
363
+ }
364
+ if (r.mediaContentType !== 'VIDEO' || !Array.isArray(r.sources))
365
+ continue;
366
+ const sources = r.sources
367
+ .filter((s) => Boolean(s) && typeof s.url === 'string' && HTTPS.test(s.url) && VIDEO_TYPES.has(String(s.mimeType)))
368
+ .map((s) => ({ url: s.url, mimeType: s.mimeType }));
369
+ if (!sources.length)
370
+ continue;
371
+ const poster = image(r.previewImage);
372
+ out.push({ id: `media-${i}`, type: 'video', alt, previewImage: poster && HTTPS.test(poster.url) ? poster : null, sources });
373
+ }
374
+ return out.some((m) => m.type !== 'image') ? { media: out } : {};
375
+ }
376
+ const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:\d{2})$/;
377
+ /**
378
+ * `Product.automaticDiscounts` (storefront-query rev 2.31, QA D8): the store's unconditional automatic discounts on
379
+ * this product. Each entry must be whole (a title, a known type, a positive value — a percentage at most 100 — and
380
+ * ISO dates with the end after the start) or it is left out: a guessed discount is worse than none.
381
+ */
382
+ export function productAutomaticDiscounts(raw) {
383
+ if (!Array.isArray(raw))
384
+ return {};
385
+ const out = [];
386
+ for (const d of raw.slice(0, 50)) {
387
+ if (!d || typeof d !== 'object')
388
+ continue;
389
+ const r = d;
390
+ const value = typeof r.value === 'string' && /^\d{1,15}(\.\d{1,4})?$/.test(r.value) ? Number(r.value) : NaN;
391
+ const type = r.valueType === 'percentage' || r.valueType === 'fixed' ? r.valueType : null;
392
+ const title = typeof r.title === 'string' ? r.title.trim() : '';
393
+ const starts = typeof r.startsAt === 'string' && ISO.test(r.startsAt) ? r.startsAt : null;
394
+ const ends = r.endsAt === undefined || r.endsAt === null ? undefined : typeof r.endsAt === 'string' && ISO.test(r.endsAt) ? r.endsAt : null;
395
+ if (typeof r.id !== 'string' || !r.id || !title || !type || !(value > 0) || (type === 'percentage' && value > 100) || !starts || ends === null)
396
+ continue;
397
+ if (ends !== undefined && Date.parse(ends) <= Date.parse(starts))
398
+ continue;
399
+ out.push({ id: r.id, title: title.slice(0, 255), valueType: type, value, startsAt: starts, ...(ends ? { endsAt: ends } : {}) });
400
+ }
401
+ return out.length ? { automaticDiscounts: out } : {};
402
+ }
403
+ /** `Product.lowStockThreshold` (storefront-query rev 2.26): the product's own low-stock threshold, when the merchant set one (D-8). */
404
+ function lowStock(v) {
405
+ return typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= 9999 ? { lowStockThreshold: v } : {};
406
+ }
407
+ /**
408
+ * ABI facet → the storefront filter Nova's listing reads (`platform/runtime/render/product-listing.ts`
409
+ * `RawFilter`): `input` is the JSON of the filter object the listing hands back to
410
+ * `collectionProducts({ filters })`, which `abiFilters` turns into the ABI `{key, value}` entries.
411
+ * A PRICE_RANGE facet becomes one value whose input carries the store's bounds (`{price: {min, max}}`).
412
+ * A variant-option value (storefront-query rev 2.35, facet `filter.v.option.<name>`, ABI key `option.<name>`) becomes
413
+ * `{variantOption: {name, value}}` — the reference platform's ProductFilter shape; the option name is kept exactly as the merchant wrote it.
414
+ */
415
+ const FILTER_INPUT_KEY = { vendor: 'productVendor', productType: 'productType', tag: 'tag' };
416
+ /** The ABI filter key prefix of a variant option (storefront-query rev 2.35). */
417
+ const OPTION_KEY = 'option.';
418
+ const OPTION_NAME_MAX = 255;
419
+ const optionName = (n) => typeof n === 'string' && n.length > 0 && n.length <= OPTION_NAME_MAX;
420
+ /**
421
+ * Metafield filters (storefront-query NEW-OS-30 phase C): ABI key `metafield.p.<namespace>.<key>` (a product metafield)
422
+ * or `metafield.v.<namespace>.<key>` (a variant metafield), facet `filter.p.m.<namespace>.<key>` /
423
+ * `filter.v.m.<namespace>.<key>`. The listing's filter object is the reference platform's ProductFilter shape
424
+ * `{productMetafield: {namespace, key, value}}` / `{variantMetafield: {namespace, key, value}}`.
425
+ * A metafield key is lowercase `^[a-z][a-z0-9_]*$` and never holds a dot, so the namespace is everything before the
426
+ * last dot (1–64 characters).
427
+ */
428
+ const METAFIELD_KEY = /^metafield\.(p|v)\.(.{1,64})\.([a-z][a-z0-9_]{0,63})$/;
429
+ const METAFIELD_KEY_PART = /^[a-z][a-z0-9_]{0,63}$/;
430
+ const metafieldNamespace = (n) => typeof n === 'string' && n.length > 0 && n.length <= 64;
431
+ const METAFIELD_INPUT = { p: 'productMetafield', v: 'variantMetafield' };
432
+ /** One ABI facet value's `{key, value}` → the listing's filter object, or null for a key the kit does not know. */
433
+ function filterInput(key, value) {
434
+ if (key === 'available')
435
+ return { available: value === 'true' };
436
+ if (FILTER_INPUT_KEY[key])
437
+ return { [FILTER_INPUT_KEY[key]]: value };
438
+ if (key.startsWith(OPTION_KEY) && optionName(key.slice(OPTION_KEY.length)))
439
+ return { variantOption: { name: key.slice(OPTION_KEY.length), value } };
440
+ const m = METAFIELD_KEY.exec(key);
441
+ if (m)
442
+ return { [METAFIELD_INPUT[m[1]]]: { namespace: m[2], key: m[3], value } };
443
+ return null;
444
+ }
445
+ /** `{namespace, key, value}` of a metafield filter object → the ABI key + value, or null when malformed. */
446
+ function metafieldFilter(scope, raw) {
447
+ if (!raw || typeof raw !== 'object')
448
+ return null;
449
+ const { namespace, key, value } = raw;
450
+ if (!metafieldNamespace(namespace) || typeof key !== 'string' || !METAFIELD_KEY_PART.test(key) || typeof value !== 'string')
451
+ return null;
452
+ return { key: `metafield.${scope}.${namespace}.${key}`, value };
453
+ }
454
+ export function filters(list) {
455
+ const out = [];
456
+ for (const f of list ?? []) {
457
+ if (f.type === 'PRICE_RANGE') {
458
+ if (!f.range)
459
+ continue;
460
+ const min = Number(f.range.min.amount);
461
+ const max = Number(f.range.max.amount);
462
+ if (!Number.isFinite(min) || !Number.isFinite(max))
463
+ continue;
464
+ out.push({ id: f.id, label: f.label, type: 'PRICE_RANGE', values: [{ id: f.id, label: f.label, count: 0, input: JSON.stringify({ price: { min, max } }) }] });
465
+ continue;
466
+ }
467
+ const values = [];
468
+ for (const v of f.values) {
469
+ const { key, value } = v.input;
470
+ const input = filterInput(key, value);
471
+ if (input)
472
+ values.push({ id: v.id, label: v.label, count: v.count, input: JSON.stringify(input) });
473
+ }
474
+ if (values.length)
475
+ out.push({ id: f.id, label: f.label, type: f.type, values });
476
+ }
477
+ return out;
478
+ }
479
+ /** A decimal amount the data plane accepts (`^(0|[1-9][0-9]{0,14})(\.[0-9]{1,4})?$`), or null. */
480
+ function amount(n) {
481
+ if (typeof n !== 'number' || !Number.isFinite(n) || n < 0 || n >= 1e15)
482
+ return null;
483
+ return Number.isInteger(n) ? String(n) : n.toFixed(4).replace(/\.?0+$/, '');
484
+ }
485
+ /** The listing's filter objects (`{productVendor}`, `{available}`, `{price: {min, max}}`, `{variantOption: {name, value}}`, `{productMetafield | variantMetafield: {namespace, key, value}}`, …) → ABI `filters`. Unknown shapes are dropped. */
486
+ export function abiFilters(list) {
487
+ const out = [];
488
+ for (const f of list ?? []) {
489
+ if (typeof f.available === 'boolean')
490
+ out.push({ key: 'available', value: String(f.available) });
491
+ else if (typeof f.productVendor === 'string')
492
+ out.push({ key: 'vendor', value: f.productVendor });
493
+ else if (typeof f.productType === 'string')
494
+ out.push({ key: 'productType', value: f.productType });
495
+ else if (typeof f.tag === 'string')
496
+ out.push({ key: 'tag', value: f.tag });
497
+ else if (f.productMetafield !== undefined || f.variantMetafield !== undefined) {
498
+ const mf = f.productMetafield !== undefined ? metafieldFilter('p', f.productMetafield) : metafieldFilter('v', f.variantMetafield);
499
+ if (mf)
500
+ out.push(mf);
501
+ }
502
+ else if (f.variantOption && typeof f.variantOption === 'object') {
503
+ const { name, value } = f.variantOption;
504
+ if (optionName(name) && typeof value === 'string')
505
+ out.push({ key: `${OPTION_KEY}${name}`, value });
506
+ }
507
+ else if (f.price && typeof f.price === 'object') {
508
+ const { min, max } = f.price;
509
+ const lo = amount(min);
510
+ const hi = amount(max);
511
+ if (lo !== null)
512
+ out.push({ key: 'price.min', value: lo });
513
+ if (hi !== null)
514
+ out.push({ key: 'price.max', value: hi });
515
+ }
516
+ }
517
+ return out;
518
+ }
519
+ export function collection(c) {
520
+ return {
521
+ id: c.id,
522
+ handle: c.handle,
523
+ title: c.title,
524
+ templateSuffix: c.templateSuffix ?? null,
525
+ // Nova renders a collection description as text (CollectionBanner, MainCollection).
526
+ description: plainText(c.descriptionHtml) || null,
527
+ image: c.image?.url ? { url: c.image.url, ...(c.image.altText ? { altText: c.image.altText } : {}) } : null,
528
+ products: (c.products?.nodes ?? []).map(product),
529
+ ...(typeof c.products?.totalCount === 'number' ? { productsCount: c.products.totalCount } : {}),
530
+ seo: { title: c.seo?.title ?? null, description: c.seo?.description ?? null },
531
+ ...(c.filters ? { filters: filters(c.filters) } : {}),
532
+ ...metafieldsOf(c),
533
+ };
534
+ }
535
+ export function page(p) {
536
+ return {
537
+ handle: p.handle,
538
+ title: p.title,
539
+ body: p.body,
540
+ bodySummary: plainText(p.body).slice(0, 160),
541
+ templateSuffix: p.templateSuffix ?? null,
542
+ seo: { title: p.seo?.title ?? null, description: p.seo?.description ?? null },
543
+ ...metafieldsOf(p),
544
+ };
545
+ }
546
+ export function article(a) {
547
+ return {
548
+ id: a.id,
549
+ handle: a.handle,
550
+ title: a.title,
551
+ excerpt: a.excerpt ?? null,
552
+ contentHtml: a.contentHtml,
553
+ image: image(a.image),
554
+ author: a.author?.name ?? null,
555
+ publishedAt: a.publishedAt,
556
+ tags: [...a.tags],
557
+ blogHandle: a.blog?.handle,
558
+ seo: { title: a.seo?.title ?? null, description: a.seo?.description ?? null },
559
+ ...articleComments(a.comments),
560
+ ...metafieldsOf(a),
561
+ };
562
+ }
563
+ /**
564
+ * `Article.comments` (storefront-query rev 2.44, NEW-OS-26): the article's comments when its blog accepts them —
565
+ * `moderated` (a new comment waits for the merchant), `count` (published comments) and, on the article route and
566
+ * `content.article` only, `nodes` (the newest published, at most 50). Whole entries only (an id, a display name, a body,
567
+ * a second-precision date); an entry that is not whole is left out. Absent or not whole ⇒ absent: the blog takes no
568
+ * comments (or the region is older), so the theme shows neither a list nor a form. Read as unknown: the kit builds
569
+ * against older ABI types.
570
+ */
571
+ export function articleComments(raw) {
572
+ if (!raw || typeof raw !== 'object')
573
+ return {};
574
+ const c = raw;
575
+ if (typeof c.moderated !== 'boolean')
576
+ return {};
577
+ if (typeof c.count !== 'number' || !Number.isInteger(c.count) || c.count < 0)
578
+ return {};
579
+ const out = { moderated: c.moderated, count: c.count };
580
+ if (Array.isArray(c.nodes)) {
581
+ const nodes = [];
582
+ for (const n of c.nodes.slice(0, 50)) {
583
+ if (!n || typeof n !== 'object')
584
+ continue;
585
+ const r = n;
586
+ const id = oneLine(r['id'], 128);
587
+ const author = oneLine(r['author'], 120);
588
+ const body = typeof r['body'] === 'string' && r['body'].trim() !== '' ? r['body'].trim().slice(0, 5000) : null;
589
+ const createdAt = typeof r['createdAt'] === 'string' && SECOND_TIMESTAMP.test(r['createdAt']) ? r['createdAt'] : null;
590
+ if (!id || !author || !body || !createdAt)
591
+ continue;
592
+ nodes.push({ id, author, body, createdAt });
593
+ }
594
+ out.nodes = nodes;
595
+ }
596
+ return { comments: out };
597
+ }
598
+ export function blog(b) {
599
+ return {
600
+ id: b.id,
601
+ handle: b.handle,
602
+ title: b.title,
603
+ articles: (b.articles?.nodes ?? []).map((a) => ({ ...article(a), blogHandle: a.blog?.handle ?? b.handle })),
604
+ seo: { title: b.seo?.title ?? null, description: b.seo?.description ?? null },
605
+ };
606
+ }
607
+ function menuItem(i) {
608
+ // ABI Menu-1: the linked collection's image, carried only when the platform sent one
609
+ const img = image(i.image);
610
+ return {
611
+ id: i.id,
612
+ title: i.title,
613
+ url: i.url,
614
+ type: (MENU_TYPES.has(i.type) ? i.type : 'HTTP'),
615
+ ...(img ? { image: img } : {}),
616
+ items: i.items.map(menuItem),
617
+ };
618
+ }
619
+ export function menu(m) {
620
+ return { id: `menu:${m.handle}`, handle: m.handle, title: m.title, items: m.items.map(menuItem) };
621
+ }
622
+ /** Nova's `shop.policies` slots, keyed by the policy handles the platform uses. */
623
+ const POLICY_SLOT = {
624
+ 'privacy-policy': 'privacy',
625
+ 'refund-policy': 'refund',
626
+ 'terms-of-service': 'termsOfService',
627
+ 'shipping-policy': 'shipping',
628
+ 'subscription-policy': 'subscription',
629
+ };
630
+ export function policy(p) {
631
+ return { handle: p.handle, title: p.title, url: p.url, body: p.body };
632
+ }
633
+ export function shop(s, policies = [], country = '') {
634
+ const slots = {};
635
+ for (const p of policies) {
636
+ const slot = POLICY_SLOT[p.handle];
637
+ slots[slot ?? p.handle] = policy(p);
638
+ }
639
+ const primary = s.brand?.colors?.primary;
640
+ const social = socialLinks(s.socialLinks);
641
+ let host = '';
642
+ try {
643
+ host = new URL(s.primaryDomain.url).host;
644
+ }
645
+ catch {
646
+ host = '';
647
+ }
648
+ const seo = shopSeo(s.seo);
649
+ const extra = s;
650
+ const contact = shopContact(extra.contact);
651
+ const banner = cookieBanner(extra.cookieBanner);
652
+ const links = policyLinks(extra.policyLinks);
653
+ const freeShipping = freeShippingFor(extra.freeShipping, country);
654
+ const moneyFormat = shopMoneyFormat(extra.moneyFormat);
655
+ const address = shopAddress(extra.contact?.address);
656
+ const locations = shopLocations(extra.locations);
657
+ const popups = shopPopups(extra.popups);
658
+ const loyalty = shopLoyalty(extra.loyalty);
659
+ const referrals = shopReferrals(extra.referrals);
660
+ const fonts = brandFonts(s.brand?.fonts);
661
+ const spam = spamProtection(s.spamProtection);
662
+ return {
663
+ name: s.name,
664
+ description: s.description ?? null,
665
+ ...(seo ? { seo } : {}),
666
+ ...contact,
667
+ ...(extra.taxesIncluded === true ? { taxesIncluded: true } : {}),
668
+ ...(freeShipping ? { freeShippingThreshold: freeShipping } : {}),
669
+ ...(banner ? { consentBanner: banner } : {}),
670
+ ...(extra.accounts && typeof extra.accounts === 'object' && extra.accounts.signInLinks === false ? { signInLinks: false } : {}),
671
+ ...(links ? { policyLinks: links } : {}),
672
+ ...(moneyFormat ? { moneyFormat } : {}),
673
+ ...(address ? { address } : {}),
674
+ ...(locations.length ? { locations } : {}),
675
+ ...(popups.length ? { popups } : {}),
676
+ ...(loyalty ? { loyalty } : {}),
677
+ ...(referrals ? { referrals } : {}),
678
+ ...(spam ? { spamProtection: spam } : {}),
679
+ brand: s.brand
680
+ ? {
681
+ logo: image(s.brand.logo),
682
+ squareLogo: image(s.brand.squareLogo),
683
+ ...(primary ? { colors: { primary: [{ background: primary }], secondary: [] } } : {}),
684
+ ...(fonts.length ? { fonts } : {}),
685
+ // storefront-query rev 2.72 (board 35 #110): Settings › Brand slogan, short description and cover image.
686
+ ...brandStoryOf(s.brand),
687
+ }
688
+ : null,
689
+ policies: slots,
690
+ primaryDomain: { host, url: s.primaryDomain.url, sslEnabled: s.primaryDomain.url.startsWith('https:') },
691
+ ...(social.length ? { socialLinks: social } : {}),
692
+ paymentSettings: { acceptedCardBrands: [...(s.paymentSettings.acceptedCardBrands ?? [])], supportedDigitalWallets: [], currencyCode: s.paymentSettings.currencyCode },
693
+ ...metafieldsOf(s),
694
+ };
695
+ }
696
+ /**
697
+ * Settings › Preferences › Spam protection (A4, storefront-query rev 2.44 `shop.spamProtection`): the store's two
698
+ * Cloudflare Turnstile switches and the platform's public widget site key. Read as unknown so the kit builds against an
699
+ * ABI without the member. Kept only whole: two booleans and a site key of 1–128 `[A-Za-z0-9_-]`; anything else is
700
+ * no member, so the theme renders no widget (today's behaviour).
701
+ */
702
+ export function spamProtection(raw) {
703
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
704
+ return null;
705
+ const r = raw;
706
+ if (typeof r.contactForms !== 'boolean' || typeof r.authPages !== 'boolean')
707
+ return null;
708
+ if (typeof r.siteKey !== 'string' || !/^[A-Za-z0-9_-]{1,128}$/.test(r.siteKey))
709
+ return null;
710
+ return { contactForms: r.contactForms, authPages: r.authPages, siteKey: r.siteKey };
711
+ }
712
+ /**
713
+ * storefront-query rev 2.72 `Shop.brand.slogan` / `shortDescription` / `coverImage` (board 35 #110), each only when it
714
+ * is a non-empty string (at most 100 / 150 characters) or an image with a URL.
715
+ */
716
+ export function brandStoryOf(b) {
717
+ const t = (v, max) => (typeof v === 'string' && v.trim() && v.trim().length <= max ? v.trim() : null);
718
+ const slogan = t(b?.slogan, 100);
719
+ const shortDescription = t(b?.shortDescription, 150);
720
+ const coverImage = image(b?.coverImage ?? null);
721
+ return { ...(slogan ? { slogan } : {}), ...(shortDescription ? { shortDescription } : {}), ...(coverImage ? { coverImage } : {}) };
722
+ }
723
+ /**
724
+ * Settings › Brand fonts (`Shop.brand.fonts`, NEW-OS-12): the merchant's family names in priority order —
725
+ * a theme maps `[0]` → headings, `[1]` → body (`Shop.brand.fonts` in runtime/kit/storefront.ts). Carried by
726
+ * storefront-query rev 2.42 (`shop.brand.fonts`, at most 6) and theme-abi `Shop.brand.fonts`; read as unknown so the
727
+ * kit still builds against an ABI without the member: trimmed, non-empty, at most 100 characters, no control
728
+ * character, first occurrence only, at most 10. [] when none, so a store without brand fonts keeps the shop it had.
729
+ */
730
+ export function brandFonts(raw) {
731
+ if (!Array.isArray(raw))
732
+ return [];
733
+ const out = [];
734
+ for (const v of raw) {
735
+ if (typeof v !== 'string')
736
+ continue;
737
+ const name = v.trim().replace(/\s+/g, ' ');
738
+ // eslint-disable-next-line no-control-regex
739
+ if (!name || name.length > 100 || /[\u0000-\u001f\u007f]/.test(name) || out.includes(name))
740
+ continue;
741
+ out.push(name);
742
+ if (out.length === 10)
743
+ break;
744
+ }
745
+ return out;
746
+ }
747
+ // ── rev 2.48 (NEW-MKT-10): loyalty and referrals ─────────────────────────────
748
+ const LOYALTY_NUMBER = /^(0|[1-9][0-9]{0,11})(\.[0-9]{1,4})?$/;
749
+ const EARN_KINDS = new Set(['purchase', 'account', 'birthday', 'review', 'newsletter', 'social', 'custom']);
750
+ const REWARD_KINDS = new Set(['amountOff', 'percentOff', 'freeShipping', 'freeProduct', 'storeCredit']);
751
+ const isRecord = (x) => typeof x === 'object' && x !== null && !Array.isArray(x);
752
+ const loyaltyNumber = (x) => (typeof x === 'string' && LOYALTY_NUMBER.test(x) ? x : null);
753
+ const boundedCount = (x, max) => (typeof x === 'number' && Number.isInteger(x) && x >= 0 && x <= max ? x : null);
754
+ const currencyMoney = (x) => isRecord(x) && typeof x.amount === 'string' && /^-?[0-9]+(\.[0-9]+)?$/.test(x.amount) && typeof x.currencyCode === 'string' && /^[A-Z]{3}$/.test(x.currencyCode)
755
+ ? { amount: x.amount, currencyCode: x.currencyCode }
756
+ : null;
757
+ const httpsUrl = (x) => {
758
+ const t = text(x, 2048);
759
+ if (!t)
760
+ return null;
761
+ try {
762
+ return new URL(t).protocol === 'https:' ? t : null;
763
+ }
764
+ catch {
765
+ return null;
766
+ }
767
+ };
768
+ /**
769
+ * rev 2.48 `Shop.loyalty` → the program as any shopper may read it: a name, the earn rates (positive, one per
770
+ * currency), the pending days, the tier basis; each tier, way to earn and reward only when whole (a known kind, a name,
771
+ * counts in range), in the platform's order. Null when absent or unusable — never a guessed rate.
772
+ */
773
+ export function shopLoyalty(raw) {
774
+ if (!isRecord(raw))
775
+ return null;
776
+ const name = text(raw.name, 200);
777
+ const pendingDays = boundedCount(raw.pendingDays, 3650);
778
+ if (!name || CONTROL.test(name) || pendingDays === null || !Array.isArray(raw.earnRates))
779
+ return null;
780
+ const seen = new Set();
781
+ const earnRates = [];
782
+ for (const r of raw.earnRates) {
783
+ if (!isRecord(r) || typeof r.currencyCode !== 'string' || !/^[A-Z]{3}$/.test(r.currencyCode) || seen.has(r.currencyCode))
784
+ continue;
785
+ const pointsPerUnit = loyaltyNumber(r.pointsPerUnit);
786
+ if (pointsPerUnit === null || Number(pointsPerUnit) <= 0)
787
+ continue;
788
+ seen.add(r.currencyCode);
789
+ earnRates.push({ currencyCode: r.currencyCode, pointsPerUnit });
790
+ }
791
+ const tiers = [];
792
+ for (const t of Array.isArray(raw.tiers) ? raw.tiers : []) {
793
+ if (!isRecord(t))
794
+ continue;
795
+ const tierName = text(t.name, 200);
796
+ const threshold = loyaltyNumber(t.threshold);
797
+ const earnMultiplier = loyaltyNumber(t.earnMultiplier);
798
+ if (tierName && threshold !== null && earnMultiplier !== null)
799
+ tiers.push({ name: tierName, threshold, earnMultiplier });
800
+ }
801
+ const rules = [];
802
+ for (const r of Array.isArray(raw.rules) ? raw.rules : []) {
803
+ if (!isRecord(r) || typeof r.kind !== 'string' || !EARN_KINDS.has(r.kind))
804
+ continue;
805
+ const ruleName = text(r.name, 200);
806
+ const points = boundedCount(r.points, 1_000_000);
807
+ if (!ruleName || points === null)
808
+ continue;
809
+ const url = r.kind === 'social' ? httpsUrl(r.url) : null;
810
+ rules.push({ kind: r.kind, name: ruleName, points, ...(url ? { url } : {}) });
811
+ }
812
+ const rewards = [];
813
+ for (const r of Array.isArray(raw.rewards) ? raw.rewards : []) {
814
+ if (!isRecord(r) || typeof r.kind !== 'string' || !REWARD_KINDS.has(r.kind))
815
+ continue;
816
+ const rewardName = text(r.name, 200);
817
+ const points = boundedCount(r.points, 10_000_000);
818
+ if (!rewardName || points === null || points < 1)
819
+ continue;
820
+ const value = r.value === undefined ? null : loyaltyNumber(r.value);
821
+ if (r.value !== undefined && value === null)
822
+ continue;
823
+ const minimumSubtotal = r.minimumSubtotal === undefined ? null : currencyMoney(r.minimumSubtotal);
824
+ rewards.push({
825
+ name: rewardName,
826
+ kind: r.kind,
827
+ points,
828
+ ...(value !== null ? { value } : {}),
829
+ ...(minimumSubtotal ? { minimumSubtotal } : {}),
830
+ });
831
+ }
832
+ const pointValue = raw.pointValue === undefined ? null : currencyMoney(raw.pointValue);
833
+ return {
834
+ name,
835
+ earnRates,
836
+ ...(pointValue ? { pointValue } : {}),
837
+ pendingDays,
838
+ tierBasis: raw.tierBasis === 'spend' ? 'spend' : 'points',
839
+ ...(tiers.length ? { tiers } : {}),
840
+ ...(rules.length ? { rules } : {}),
841
+ ...(rewards.length ? { rewards } : {}),
842
+ };
843
+ }
844
+ /** rev 2.48 `Shop.referrals` → the friend offer and the advocate reward, both whole; null otherwise. */
845
+ export function shopReferrals(raw) {
846
+ if (!isRecord(raw) || !isRecord(raw.friendReward) || !isRecord(raw.advocateReward))
847
+ return null;
848
+ const f = raw.friendReward;
849
+ const a = raw.advocateReward;
850
+ const friendValue = loyaltyNumber(f.value);
851
+ if ((f.kind !== 'percentage' && f.kind !== 'fixed') || friendValue === null)
852
+ return null;
853
+ if (a.kind !== 'percentageCode' && a.kind !== 'fixedCode' && a.kind !== 'storeCredit' && a.kind !== 'points')
854
+ return null;
855
+ const minimumSubtotal = f.minimumSubtotal === undefined ? null : currencyMoney(f.minimumSubtotal);
856
+ const advocateValue = a.value === undefined ? null : loyaltyNumber(a.value);
857
+ const advocatePoints = a.points === undefined ? null : boundedCount(a.points, 1_000_000);
858
+ if (a.kind === 'points' ? advocatePoints === null : advocateValue === null)
859
+ return null;
860
+ return {
861
+ friendReward: { kind: f.kind, value: friendValue, ...(minimumSubtotal ? { minimumSubtotal } : {}) },
862
+ advocateReward: {
863
+ kind: a.kind,
864
+ ...(advocateValue !== null ? { value: advocateValue } : {}),
865
+ ...(advocatePoints !== null ? { points: advocatePoints } : {}),
866
+ },
867
+ };
868
+ }
869
+ const ADDRESS_KEYS = ['address1', 'address2', 'city', 'province', 'zip', 'country'];
870
+ /**
871
+ * rev 2.34 `PostalAddress` (`Shop.contact.address`, `ShopLocation.address`) → each member that is a non-empty string
872
+ * of at most 255 characters with no control character; `countryCode` only when two upper-case letters. Null when none.
873
+ */
874
+ export function shopAddress(raw) {
875
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
876
+ return null;
877
+ const r = raw;
878
+ const out = {};
879
+ for (const k of ADDRESS_KEYS) {
880
+ const v = text(r[k], 255);
881
+ if (v && !CONTROL.test(v))
882
+ out[k] = v;
883
+ }
884
+ if (typeof r.countryCode === 'string' && /^[A-Z]{2}$/.test(r.countryCode))
885
+ out.countryCode = r.countryCode;
886
+ return Object.keys(out).length ? out : null;
887
+ }
888
+ const PICKUP_READY_IN = new Set(['4h', '24h', '1-2d', '2-4d', '5d+']);
889
+ /** rev 2.34 `Shop.locations` → whole entries only (an id, a name, an address), in the platform's order, at most 50. */
890
+ export function shopLocations(raw) {
891
+ if (!Array.isArray(raw))
892
+ return [];
893
+ const out = [];
894
+ for (const l of raw.slice(0, 50)) {
895
+ if (!l || typeof l !== 'object')
896
+ continue;
897
+ const r = l;
898
+ const id = text(r.id, 128);
899
+ const name = text(r.name, 255);
900
+ const address = shopAddress(r.address);
901
+ if (!id || !name || !address)
902
+ continue;
903
+ const phone = text(r.phone, 50);
904
+ // rev 2.52 (O3): the merchant's expected pickup time, one of five values
905
+ const readyIn = typeof r.pickupReadyIn === 'string' && PICKUP_READY_IN.has(r.pickupReadyIn) ? r.pickupReadyIn : null;
906
+ // rev 2.73 (board 35 #117): pickup / storefront marks and the weekly opening hours
907
+ const hours = openingHours(r.openingHours);
908
+ out.push({
909
+ id,
910
+ name,
911
+ address,
912
+ ...(phone && /^[0-9+()\-. ]+$/.test(phone) ? { phone } : {}),
913
+ ...(readyIn ? { pickupReadyIn: readyIn } : {}),
914
+ ...(typeof r.pickup === 'boolean' ? { pickup: r.pickup } : {}),
915
+ ...(typeof r.storefront === 'boolean' ? { storefront: r.storefront } : {}),
916
+ ...(hours ? { openingHours: hours } : {}),
917
+ });
918
+ }
919
+ return out;
920
+ }
921
+ const WEEKDAYS = ['MONDAY', 'TUESDAY', 'WEDNESDAY', 'THURSDAY', 'FRIDAY', 'SATURDAY', 'SUNDAY'];
922
+ const HH_MM = /^([01]\d|2[0-3]):[0-5]\d$/;
923
+ /** rev 2.73 `ShopLocation.openingHours` → whole periods only (a weekday once, 24-hour times), Monday first; null when absent. */
924
+ export function openingHours(raw) {
925
+ if (!Array.isArray(raw))
926
+ return null;
927
+ const out = [];
928
+ for (const p of raw.slice(0, 7)) {
929
+ const r = (p && typeof p === 'object' ? p : {});
930
+ const day = WEEKDAYS.find((d) => d === r.day);
931
+ if (!day || out.some((o) => o.day === day) || typeof r.opens !== 'string' || typeof r.closes !== 'string' || !HH_MM.test(r.opens) || !HH_MM.test(r.closes))
932
+ continue;
933
+ out.push({ day, opens: r.opens, closes: r.closes });
934
+ }
935
+ return out.sort((a, b) => WEEKDAYS.indexOf(a.day) - WEEKDAYS.indexOf(b.day));
936
+ }
937
+ const POPUP_KINDS = new Set(['newsletter', 'announcement']);
938
+ const POPUP_TRIGGERS = new Set(['delay', 'scroll', 'exitIntent']);
939
+ const POPUP_PAGES = new Set(['all', 'home', 'product', 'collection', 'cart']);
940
+ /** A link a pop-up button may follow: a path on the store (never `//host`) or an https URL. */
941
+ const POPUP_LINK = /^(\/(?!\/)\S*|https:\/\/\S+)$/;
942
+ const LANGUAGE_TAG = /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/;
943
+ const intIn = (v, min, max) => typeof v === 'number' && Number.isInteger(v) && v >= min && v <= max;
944
+ /**
945
+ * rev 2.37 `Shop.popups` → whole pop-ups only (an id, a known kind and trigger, a trigger value that fits it, a
946
+ * frequency, at least one known page, a language, a heading and a button label), in the platform's order, at most 20.
947
+ * Text is plain and trimmed; a link only on an announcement and only when it is a store path or https; an image only
948
+ * when https. Anything else is dropped, never guessed.
949
+ */
950
+ export function shopPopups(raw) {
951
+ if (!Array.isArray(raw))
952
+ return [];
953
+ const out = [];
954
+ for (const p of raw.slice(0, 20)) {
955
+ if (!p || typeof p !== 'object')
956
+ continue;
957
+ const r = p;
958
+ const id = text(r.id, 128);
959
+ const kind = typeof r.kind === 'string' && POPUP_KINDS.has(r.kind) ? r.kind : null;
960
+ const trigger = typeof r.trigger === 'string' && POPUP_TRIGGERS.has(r.trigger) ? r.trigger : null;
961
+ const heading = text(r.heading, 120);
962
+ const ctaLabel = text(r.ctaLabel, 40);
963
+ const language = typeof r.language === 'string' && LANGUAGE_TAG.test(r.language) ? r.language : null;
964
+ if (!id || !kind || !trigger || !heading || !ctaLabel || !language || !intIn(r.frequencyDays, 0, 365))
965
+ continue;
966
+ const value = r.triggerValue;
967
+ if (!(trigger === 'scroll' ? intIn(value, 1, 100) : trigger === 'exitIntent' ? value === 0 : intIn(value, 0, 600)))
968
+ continue;
969
+ const pages = Array.isArray(r.pages) ? [...new Set(r.pages.filter((x) => typeof x === 'string' && POPUP_PAGES.has(x)))] : [];
970
+ if (!pages.length)
971
+ continue;
972
+ const body = text(r.body, 600);
973
+ const consentText = text(r.consentText, 600);
974
+ const img = r.image && typeof r.image === 'object' ? r.image : null;
975
+ const imageUrl = img && typeof img.url === 'string' && img.url.startsWith('https://') && !/\s/.test(img.url) ? img.url : null;
976
+ const ctaUrl = kind === 'announcement' && typeof r.ctaUrl === 'string' && POPUP_LINK.test(r.ctaUrl) ? r.ctaUrl : null;
977
+ out.push({
978
+ id,
979
+ kind,
980
+ trigger,
981
+ triggerValue: value,
982
+ frequencyDays: r.frequencyDays,
983
+ pages,
984
+ ...(typeof r.startsAt === 'string' && SECOND_TIMESTAMP.test(r.startsAt) ? { startsAt: r.startsAt } : {}),
985
+ ...(typeof r.endsAt === 'string' && SECOND_TIMESTAMP.test(r.endsAt) ? { endsAt: r.endsAt } : {}),
986
+ language,
987
+ heading,
988
+ ...(body ? { body } : {}),
989
+ ctaLabel,
990
+ ...(consentText ? { consentText } : {}),
991
+ ...(imageUrl ? { image: { url: imageUrl, altText: text(img.altText, 512) ?? null } } : {}),
992
+ ...(ctaUrl ? { ctaUrl } : {}),
993
+ ...(kind === 'newsletter' && r.discountOffered === true ? { discountOffered: true } : {}),
994
+ });
995
+ }
996
+ return out;
997
+ }
998
+ /** One `{{amount…}}` token (the merchant's currency-format patterns). */
999
+ export const MONEY_FORMAT_TOKEN = /\{\{\s*(amount|amount_no_decimals|amount_with_comma_separator|amount_no_decimals_with_comma_separator|amount_with_apostrophe_separator|amount_no_decimals_with_space_separator|amount_with_space_separator|amount_with_period_and_space_separator)\s*\}\}/;
1000
+ // eslint-disable-next-line no-control-regex
1001
+ const CONTROL = /[\u0000-\u001f\u007f]/;
1002
+ /**
1003
+ * rev 2.31 `Shop.moneyFormat` → the patterns a theme may format base-currency amounts with, each only when it is a
1004
+ * string of at most 50 characters holding an amount token. Null when neither is usable: a pattern the theme cannot
1005
+ * read must never replace the price.
1006
+ */
1007
+ export function shopMoneyFormat(raw) {
1008
+ if (!raw || typeof raw !== 'object')
1009
+ return null;
1010
+ const r = raw;
1011
+ const ok = (v) => typeof v === 'string' && v.length > 0 && v.length <= 50 && !CONTROL.test(v) && MONEY_FORMAT_TOKEN.test(v);
1012
+ const out = {};
1013
+ if (ok(r.withCurrency))
1014
+ out.withCurrency = r.withCurrency;
1015
+ if (ok(r.withoutCurrency))
1016
+ out.withoutCurrency = r.withoutCurrency;
1017
+ return out.withCurrency || out.withoutCurrency ? out : null;
1018
+ }
1019
+ const text = (v, max = 2000) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : undefined);
1020
+ /** D-7 `Shop.contact` → the shop's public email / phone, each only when set. */
1021
+ export function shopContact(raw) {
1022
+ if (!raw || typeof raw !== 'object')
1023
+ return {};
1024
+ const r = raw;
1025
+ const email = text(r.email, 255);
1026
+ const phone = text(r.phone, 50);
1027
+ return {
1028
+ ...(email && /^[^\s@<>"]+@[^\s@<>"]+\.[^\s@<>"]+$/.test(email) ? { email } : {}),
1029
+ ...(phone && /^[0-9+()\-. ]+$/.test(phone) ? { phone } : {}),
1030
+ };
1031
+ }
1032
+ /** A link target the banner may use: a site path or an absolute https URL. */
1033
+ function safeHref(v) {
1034
+ const t = text(v, 2048);
1035
+ if (!t)
1036
+ return undefined;
1037
+ if (t.startsWith('/') && !t.startsWith('//'))
1038
+ return t;
1039
+ try {
1040
+ const u = new URL(t);
1041
+ return u.protocol === 'https:' && u.hostname ? u.href : undefined;
1042
+ }
1043
+ catch {
1044
+ return undefined;
1045
+ }
1046
+ }
1047
+ const POSITIONS = new Set(['bottom', 'bottom-left', 'bottom-right', 'bottom-center', 'center']);
1048
+ const BANNER_TEXT = ['title', 'body', 'privacyLinkLabel', 'acceptLabel', 'declineLabel', 'manageLabel'];
1049
+ const PREFS_TEXT = [
1050
+ 'title', 'introTitle', 'introBody', 'acceptAllLabel', 'declineAllLabel', 'saveLabel', 'bulletTitle',
1051
+ 'requiredTitle', 'requiredDescription', 'personalizationTitle', 'personalizationDescription',
1052
+ 'marketingTitle', 'marketingDescription', 'analyticsTitle', 'analyticsDescription',
1053
+ ];
1054
+ function texts(raw, keys) {
1055
+ const out = {};
1056
+ if (!raw || typeof raw !== 'object')
1057
+ return out;
1058
+ for (const k of keys) {
1059
+ const v = text(raw[k]);
1060
+ if (v)
1061
+ out[k] = v;
1062
+ }
1063
+ return out;
1064
+ }
1065
+ /** D-2 `Shop.cookieBanner` → the banner config Nova renders. Null when absent or not an object (old data = today's banner). */
1066
+ export function cookieBanner(raw) {
1067
+ if (!raw || typeof raw !== 'object')
1068
+ return null;
1069
+ const r = raw;
1070
+ const position = typeof r.position === 'string' && POSITIONS.has(r.position) ? r.position : 'bottom';
1071
+ const colorTheme = r.colorTheme === 'dark' || r.colorTheme === 'custom' ? r.colorTheme : 'light';
1072
+ const regions = Array.isArray(r.regions) ? r.regions.filter((x) => typeof x === 'string' && /^[A-Z]{2}(-[A-Z0-9]{1,3})?$/.test(x)) : [];
1073
+ const privacyLinkUrl = safeHref(r.privacyLinkUrl);
1074
+ const t = texts(r.text, BANNER_TEXT);
1075
+ const p = texts(r.preferences, PREFS_TEXT);
1076
+ const prefs = r.preferences && typeof r.preferences === 'object' ? r.preferences : null;
1077
+ const bullets = prefs?.bulletsEnabled === true && Array.isArray(prefs.bullets) ? prefs.bullets.map((b) => text(b, 500)).filter((b) => Boolean(b)).slice(0, 3) : [];
1078
+ // Rev 2.69 (board 35 #42): the merchant's custom colours, each `#rrggbb` or the whole set is dropped.
1079
+ const c = colorTheme === 'custom' && r.colors && typeof r.colors === 'object' ? r.colors : null;
1080
+ const hex = (v) => typeof v === 'string' && /^#[0-9a-f]{6}$/.test(v);
1081
+ const colors = c && hex(c.background) && hex(c.text) && hex(c.button) && hex(c.buttonText) ? { background: c.background, text: c.text, button: c.button, buttonText: c.buttonText } : null;
1082
+ return {
1083
+ enabled: r.enabled === true,
1084
+ // "Use automated settings" — never saved means on (contract rev 2).
1085
+ automated: r.automated !== false,
1086
+ position,
1087
+ colorTheme,
1088
+ regions,
1089
+ ...(privacyLinkUrl ? { privacyLinkUrl } : {}),
1090
+ ...(colors ? { colors } : {}),
1091
+ text: t,
1092
+ preferences: { ...p, ...(bullets.length ? { bullets } : {}) },
1093
+ };
1094
+ }
1095
+ /** D-6 `Shop.policyLinks` → the store's published policies (title + site path). Null when absent. */
1096
+ export function policyLinks(raw) {
1097
+ if (!Array.isArray(raw))
1098
+ return null;
1099
+ const out = [];
1100
+ for (const l of raw) {
1101
+ const handle = typeof l?.handle === 'string' && /^[a-z0-9][a-z0-9-]{0,63}$/.test(l.handle) ? l.handle : '';
1102
+ const title = text(l?.title, 200);
1103
+ if (!handle || !title || out.some((o) => o.handle === handle))
1104
+ continue;
1105
+ out.push({ handle, title, url: `/policies/${handle}` });
1106
+ }
1107
+ return out;
1108
+ }
1109
+ /**
1110
+ * D-5 `Shop.freeShipping` → the lowest "free over" threshold for the shopper's country, or null when the
1111
+ * country's zone has none (or the platform sent nothing). The amount is already in the market's currency.
1112
+ */
1113
+ export function freeShippingFor(raw, country) {
1114
+ if (!Array.isArray(raw) || !country)
1115
+ return null;
1116
+ const c = country.toUpperCase();
1117
+ for (const e of raw) {
1118
+ if (!e || !Array.isArray(e.countries) || !e.countries.includes(c))
1119
+ continue;
1120
+ const m = e.minimumSubtotal;
1121
+ if (m && typeof m.amount === 'string' && /^\d{1,15}(\.\d{1,4})?$/.test(m.amount) && typeof m.currencyCode === 'string' && /^[A-Z]{3}$/.test(m.currencyCode)) {
1122
+ return { amount: m.amount, currencyCode: m.currencyCode };
1123
+ }
1124
+ return null;
1125
+ }
1126
+ return null;
1127
+ }
1128
+ /**
1129
+ * `Shop.seo` (the home page's title, meta description and social image — an optional ABI field the
1130
+ * platform may not send yet), read defensively: trimmed non-empty text, an absolute `https:` image
1131
+ * URL, positive integer sizes. Anything else is "not set". Null when nothing is set.
1132
+ */
1133
+ export function shopSeo(raw) {
1134
+ if (!raw || typeof raw !== 'object')
1135
+ return null;
1136
+ const r = raw;
1137
+ const text = (v, max) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : undefined);
1138
+ const size = (v) => (typeof v === 'number' && Number.isInteger(v) && v > 0 ? v : undefined);
1139
+ const title = text(r.title, 300);
1140
+ const description = text(r.description, 1000);
1141
+ let image;
1142
+ const img = r.image;
1143
+ if (img && typeof img === 'object' && typeof img.url === 'string') {
1144
+ try {
1145
+ const u = new URL(img.url);
1146
+ if (u.protocol === 'https:' && u.hostname) {
1147
+ const alt = text(img.altText, 500);
1148
+ const width = size(img.width);
1149
+ const height = size(img.height);
1150
+ image = { url: u.href, ...(alt ? { altText: alt } : {}), ...(width ? { width } : {}), ...(height ? { height } : {}) };
1151
+ }
1152
+ }
1153
+ catch {
1154
+ /* not a URL */
1155
+ }
1156
+ }
1157
+ if (!title && !description && !image)
1158
+ return null;
1159
+ return { ...(title ? { title } : {}), ...(description ? { description } : {}), ...(image ? { image } : {}) };
1160
+ }
1161
+ /**
1162
+ * `Shop.socialLinks` → Nova's: only absolute `https:` URLs with a network slug, one link per network
1163
+ * (the first wins). Anything else is dropped — a footer link must never point somewhere unsafe.
1164
+ */
1165
+ export function socialLinks(list) {
1166
+ const out = [];
1167
+ for (const l of list ?? []) {
1168
+ const platform = typeof l?.platform === 'string' ? l.platform.trim().toLowerCase() : '';
1169
+ if (!/^[a-z0-9][a-z0-9_-]{0,31}$/.test(platform) || out.some((o) => o.platform === platform))
1170
+ continue;
1171
+ let url;
1172
+ try {
1173
+ url = new URL(String(l.url));
1174
+ }
1175
+ catch {
1176
+ continue;
1177
+ }
1178
+ if (url.protocol !== 'https:' || !url.hostname)
1179
+ continue;
1180
+ out.push({ platform, url: url.href });
1181
+ }
1182
+ return out;
1183
+ }
1184
+ export function searchResults(r) {
1185
+ return {
1186
+ totalCount: (r.products.totalCount ?? r.products.nodes.length) + (r.pages.totalCount ?? r.pages.nodes.length) + (r.articles.totalCount ?? r.articles.nodes.length),
1187
+ products: r.products.nodes.map(product),
1188
+ pages: r.pages.nodes.map((p) => ({ handle: p.handle, title: p.title })),
1189
+ articles: r.articles.nodes.map(article),
1190
+ filters: [],
1191
+ pageInfo: {
1192
+ hasNextPage: r.products.pageInfo.hasNextPage,
1193
+ hasPreviousPage: false,
1194
+ startCursor: null,
1195
+ endCursor: r.products.pageInfo.endCursor ?? null,
1196
+ },
1197
+ };
1198
+ }
1199
+ /**
1200
+ * The cart-level amount taken off between the subtotal and the total.
1201
+ *
1202
+ * The ABI cart has no discount allocations, only `cost.subtotalAmount`, `cost.totalTaxAmount` and
1203
+ * `cost.totalAmount`. Before checkout those are related by
1204
+ * `total = subtotal − cart discount + tax`, so the discount is what reconciles the three figures
1205
+ * the summary prints. Without it the cart showed "Subtotal $64.00 · Tax $0.00 · Estimated total
1206
+ * $60.80" with nothing explaining the $3.20.
1207
+ *
1208
+ * Computed in minor units at the subtotal's own precision (never `toFixed(2)` — JPY has none, KWD
1209
+ * three). Null when nothing was taken off, when the figures are not one currency, or when an
1210
+ * amount is not a number: a guessed discount is worse than none.
1211
+ */
1212
+ export function cartDiscount(c) {
1213
+ const { subtotalAmount: sub, totalAmount: total } = c.cost;
1214
+ const tax = c.cost.totalTaxAmount ?? null;
1215
+ if (!sub || !total || sub.currencyCode !== total.currencyCode)
1216
+ return null;
1217
+ if (tax && tax.currencyCode !== sub.currencyCode)
1218
+ return null;
1219
+ const decimals = Math.max(...[sub, total, ...(tax ? [tax] : [])].map((m) => (m.amount.split('.')[1] ?? '').length));
1220
+ const scale = 10 ** decimals;
1221
+ const minor = (m) => Math.round(Number(m.amount) * scale);
1222
+ const off = minor(sub) + (tax ? minor(tax) : 0) - minor(total);
1223
+ if (!Number.isFinite(off) || off <= 0)
1224
+ return null;
1225
+ return { amount: (off / scale).toFixed(decimals), currencyCode: sub.currencyCode };
1226
+ }
1227
+ /**
1228
+ * The ABI line's `sellingPlanAllocation` (theme-abi alpha.20, NEW-SUB-2) → the runtime line's: the plan's id and
1229
+ * name, the per-delivery unit price the line is priced at and the one-time unit it was discounted from. Anything not
1230
+ * whole maps to nothing: the line then shows as one-time, which is what it was charged as when the host sent no plan.
1231
+ */
1232
+ export function cartLineSellingPlan(raw) {
1233
+ if (!raw || typeof raw !== 'object')
1234
+ return {};
1235
+ const a = raw;
1236
+ const money = (v) => (v && typeof v === 'object' && typeof v.amount === 'string' && typeof v.currencyCode === 'string' ? v : null);
1237
+ const perDeliveryPrice = money(a.perDeliveryPrice);
1238
+ const compareAtPrice = money(a.compareAtPrice);
1239
+ if (typeof a.sellingPlanId !== 'string' || !a.sellingPlanId || typeof a.name !== 'string' || !a.name || !perDeliveryPrice || !compareAtPrice)
1240
+ return {};
1241
+ return { sellingPlanAllocation: { sellingPlanId: a.sellingPlanId, sellingPlanName: a.name, perDeliveryPrice, compareAtPrice } };
1242
+ }
1243
+ /** The ABI cart → the lines/totals CartProvider renders (lib/tanqory/cart.tsx CartState fields). */
1244
+ export function cartState(c) {
1245
+ return {
1246
+ id: c.id,
1247
+ version: c.version,
1248
+ lines: c.lines.map((l) => ({
1249
+ id: l.id,
1250
+ variantId: l.merchandise.id,
1251
+ quantity: l.quantity,
1252
+ title: l.merchandise.product.title,
1253
+ ...(l.merchandise.title && l.merchandise.title !== 'Default Title' ? { variantTitle: l.merchandise.title } : {}),
1254
+ image: image(l.merchandise.image ?? l.merchandise.product.featuredImage),
1255
+ price: l.merchandise.price,
1256
+ // The merchandise is a whole ProductVariant: its options, compare-at and availability are the
1257
+ // line's (the cart shows "Queen · Oat", the struck compare-at and "No longer available").
1258
+ selectedOptions: (l.merchandise.selectedOptions ?? []).map((o) => ({ name: o.name, value: o.value })),
1259
+ ...(l.merchandise.compareAtPrice ? { compareAtPrice: l.merchandise.compareAtPrice } : {}),
1260
+ ...(typeof l.merchandise.availableForSale === 'boolean' ? { availableForSale: l.merchandise.availableForSale } : {}),
1261
+ lineSubtotal: l.cost.subtotalAmount,
1262
+ ...(l.cost.totalAmount ? { lineTotal: l.cost.totalAmount } : {}),
1263
+ ...cartLineDiscountAllocations(l, c.cost.subtotalAmount?.currencyCode),
1264
+ productHandle: l.merchandise.product.handle,
1265
+ // theme-abi Cart-4: the line's product id, when the platform sends it
1266
+ ...(typeof l.merchandise.product.id === 'string' && l.merchandise.product.id ? { productId: l.merchandise.product.id } : {}),
1267
+ attributes: Object.entries(l.attributes).map(([key, value]) => ({ key, value })),
1268
+ ...cartLineSellingPlan(l.sellingPlanAllocation),
1269
+ })),
1270
+ subtotal: c.cost.subtotalAmount,
1271
+ total: c.cost.totalAmount,
1272
+ tax: c.cost.totalTaxAmount ?? null,
1273
+ note: c.note ?? null,
1274
+ totalQuantity: c.totalQuantity,
1275
+ checkoutUrl: c.checkoutUrl,
1276
+ discountCodes: c.discountCodes.map((d) => ({ code: d.code, applicable: d.applicable })),
1277
+ discountAmount: cartDiscount(c),
1278
+ ...cartDiscountAllocations(c),
1279
+ };
1280
+ }
1281
+ /**
1282
+ * A line's own discounts by name, when the host sends them beside the ABI line (storefront-edge reads store-api's
1283
+ * `CartLine.discountAllocations`, line-level only; not yet in the Theme ABI `CartLine`, so read as unknown). Same rules
1284
+ * as the cart's: a name (title or code) and an amount in the cart's currency, else the whole list is dropped.
1285
+ */
1286
+ export function cartLineDiscountAllocations(l, currency) {
1287
+ const raw = l?.discountAllocations;
1288
+ if (!Array.isArray(raw) || raw.length === 0 || !currency)
1289
+ return {};
1290
+ const out = [];
1291
+ for (const a of raw) {
1292
+ if (!a || typeof a !== 'object')
1293
+ return {};
1294
+ const r = a;
1295
+ const title = typeof r.title === 'string' && r.title.trim() ? r.title.trim().slice(0, 255) : null;
1296
+ const code = typeof r.code === 'string' && r.code.trim() ? r.code.trim().slice(0, 255) : null;
1297
+ const m = r.amount;
1298
+ if ((!title && !code) || !m || typeof m.amount !== 'string' || !/^\d{1,15}(\.\d{1,4})?$/.test(m.amount) || m.currencyCode !== currency)
1299
+ return {};
1300
+ if (Number(m.amount) > 0)
1301
+ out.push({ title, code, amount: { amount: m.amount, currencyCode: m.currencyCode } });
1302
+ }
1303
+ return out.length ? { discountAllocations: out } : {};
1304
+ }
1305
+ /**
1306
+ * The cart's order-level discounts by name, when the host sends them beside the ABI cart (storefront-edge reads
1307
+ * store-api's `Cart.discountAllocations`; not yet in the Theme ABI `Cart`, so read as unknown). Each entry needs a
1308
+ * name (a title or a code) and an amount in the cart's currency; anything else drops the whole list rather than
1309
+ * show a partial one.
1310
+ */
1311
+ export function cartDiscountAllocations(c) {
1312
+ const raw = c.discountAllocations;
1313
+ if (!Array.isArray(raw) || raw.length === 0)
1314
+ return {};
1315
+ const currency = c.cost.subtotalAmount?.currencyCode;
1316
+ const out = [];
1317
+ for (const a of raw) {
1318
+ if (!a || typeof a !== 'object')
1319
+ return {};
1320
+ const r = a;
1321
+ const title = typeof r.title === 'string' && r.title.trim() ? r.title.trim().slice(0, 255) : null;
1322
+ const code = typeof r.code === 'string' && r.code.trim() ? r.code.trim().slice(0, 255) : null;
1323
+ const m = r.amount;
1324
+ if ((!title && !code) || !m || typeof m.amount !== 'string' || !/^\d{1,15}(\.\d{1,4})?$/.test(m.amount) || m.currencyCode !== currency)
1325
+ return {};
1326
+ if (Number(m.amount) > 0)
1327
+ out.push({ title, code, amount: { amount: m.amount, currencyCode: m.currencyCode } });
1328
+ }
1329
+ return out.length ? { discountAllocations: out } : {};
1330
+ }