@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,1131 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { createContext, useContext } from 'react';
3
+ import { createStorefrontMethods, BOOTSTRAP_SHOP_MENU, BOOTSTRAP_SHOP_MENU_FRAGMENTS, readBootstrapShopMenu, } from './storefront.js';
4
+ import { displayAmount } from '../../headless/tanqory-money.generated.js';
5
+ /** Build a `recommendations` object from a product list (parity with the commerce standard
6
+ * `recommendations` legacy templating object, whose `.products` our API returns directly). */
7
+ export function toRecommendations(products, intent = 'related') {
8
+ return { products, productsCount: products.length, intent, performed: true };
9
+ }
10
+ const DataContext = createContext(null);
11
+ /**
12
+ * Handles are Unicode now (a Thai title no longer collapses to "4" or ""), and
13
+ * a theme reads the handle out of `location.pathname`, which hands it back
14
+ * PERCENT-ENCODED — "เสื้อยืด" arrives as "%E0%B9%80…". Our indexes are keyed by
15
+ * the real handle, so an exact lookup misses and the theme quietly renders a
16
+ * fallback: nova's PDP showed a different product's data, and computeHead fell
17
+ * back to the shop name, so every non-Latin product lost its SEO title.
18
+ *
19
+ * Fixing the themes is not enough — a marketplace theme ships its own copy of
20
+ * the code and cannot be force-updated. Normalizing here reaches every theme,
21
+ * old and new, on the next rebuild (theme-kit is part of the runtime's dist
22
+ * fingerprint). A handle can't contain `%`, so this is a no-op for one that is
23
+ * already decoded; malformed input falls back to the raw string.
24
+ */
25
+ function decodeHandle(handle) {
26
+ if (!handle || !handle.includes('%'))
27
+ return handle;
28
+ try {
29
+ return decodeURIComponent(handle);
30
+ }
31
+ catch {
32
+ return handle;
33
+ }
34
+ }
35
+ /** Wraps the app with a theme-provided data source (mock or live). */
36
+ export function DataProvider({ value, children }) {
37
+ return _jsx(DataContext.Provider, { value: value, children: children });
38
+ }
39
+ export function useData() {
40
+ const ctx = useContext(DataContext);
41
+ if (!ctx)
42
+ throw new Error('useData must be used within <DataProvider>');
43
+ return ctx;
44
+ }
45
+ /** Build an offline data source from fixture collections (theme passes its JSON). */
46
+ export function createMockData(input) {
47
+ const fixture = Array.isArray(input) ? { collections: input } : input;
48
+ const collections = fixture.collections ?? [];
49
+ // Flatten products from every collection once; subsequent lookups are O(1)
50
+ // by handle. A product appearing in multiple collections returns the first
51
+ // occurrence — matching the storefront's "canonical product page" semantics.
52
+ //
53
+ // Exception: the SAME product arrives in two shapes. Collection/top listings
54
+ // come from the card fragment, which carries no `seo`; the current route's
55
+ // product is fetched with `seo { title description keywords }` and appended
56
+ // afterwards. First-wins therefore indexed the seo-less card and dropped the
57
+ // detail copy, so computeHead() found no seo.title and fell back to
58
+ // "<product> — <shop>", emitting no description at all. Let the record that
59
+ // actually has SEO win, whatever order it arrives in.
60
+ const productsByHandle = new Map();
61
+ const allProducts = [];
62
+ for (const c of collections) {
63
+ for (const p of c.products) {
64
+ const prev = productsByHandle.get(p.handle);
65
+ if (!prev) {
66
+ productsByHandle.set(p.handle, p);
67
+ allProducts.push(p);
68
+ }
69
+ else if (!prev.seo && p.seo) {
70
+ productsByHandle.set(p.handle, p);
71
+ const i = allProducts.indexOf(prev);
72
+ if (i !== -1)
73
+ allProducts[i] = p;
74
+ }
75
+ }
76
+ }
77
+ // ── Offline fixtures so EVERY commerce-standard object resolves in mock mode ──
78
+ // The live source (createLiveData) serves these from the Storefront GraphQL
79
+ // API; mock mode must mirror the same shapes so a developer can build header
80
+ // menus, blog, search, customer + shop sections fully offline (no store).
81
+ const mkItem = (id, title, url, type = 'HTTP') => ({ id, title, url, type, items: [] });
82
+ const mkMenu = (handle, title, items) => ({ id: `mock/menu/${handle}`, handle, title, items });
83
+ const mainMenu = mkMenu('main-menu', 'Main menu', [
84
+ { ...mkItem('mm-shop', 'Shop', '/collections/all', 'COLLECTIONS'),
85
+ // submenu: the store's collections, so the header dropdown is real data
86
+ items: collections.slice(0, 6).map((c, i) => mkItem(`mm-shop-${i}`, c.title, `/collections/${c.handle}`, 'COLLECTION')) },
87
+ mkItem('mm-collections', 'Collections', '/collections', 'CATALOG'),
88
+ mkItem('mm-about', 'About', '/pages/about', 'PAGE'),
89
+ mkItem('mm-journal', 'Journal', '/blogs/news', 'BLOG'),
90
+ ]);
91
+ const menus = new Map([
92
+ ['main-menu', mainMenu],
93
+ ['footer', mkMenu('footer', 'Footer', [
94
+ mkItem('fm-privacy', 'Privacy policy', '/policies/privacy-policy', 'SHOP_POLICY'),
95
+ mkItem('fm-contact', 'Contact', '/pages/contact', 'PAGE'),
96
+ ])],
97
+ ['footer-shop', mkMenu('footer-shop', 'Shop', [
98
+ mkItem('fs-all', 'All products', '/collections/all'),
99
+ mkItem('fs-new', 'New arrivals', '/collections/new'),
100
+ mkItem('fs-sale', 'Sale', '/collections/sale'),
101
+ mkItem('fs-gift', 'Gift cards', '/products/gift-card'),
102
+ ])],
103
+ ['footer-help', mkMenu('footer-help', 'Help', [
104
+ mkItem('fh-contact', 'Contact', '/pages/contact'),
105
+ mkItem('fh-ship', 'Shipping', '/pages/shipping'),
106
+ mkItem('fh-returns', 'Returns', '/pages/returns'),
107
+ mkItem('fh-faq', 'FAQ', '/pages/faq'),
108
+ ])],
109
+ ['footer-company', mkMenu('footer-company', 'Company', [
110
+ mkItem('fc-about', 'About', '/pages/about'),
111
+ mkItem('fc-journal', 'Journal', '/blogs/news'),
112
+ mkItem('fc-sustain', 'Sustainability', '/pages/sustainability'),
113
+ mkItem('fc-press', 'Press', '/pages/press'),
114
+ ])],
115
+ ]);
116
+ for (const m of fixture.menus ?? [])
117
+ menus.set(m.handle, m);
118
+ const sampleArticles = [
119
+ {
120
+ id: 'mock/article/welcome',
121
+ handle: 'welcome',
122
+ title: 'Welcome to the shop',
123
+ excerpt: 'A quick hello and what to expect.',
124
+ contentHtml: '<p>Welcome — this is mock article content for local development.</p>',
125
+ image: null,
126
+ author: 'Studio',
127
+ publishedAt: '2024-01-01T00:00:00.000Z',
128
+ tags: ['news'],
129
+ blogHandle: 'news',
130
+ },
131
+ {
132
+ id: 'mock/article/behind-the-design',
133
+ handle: 'behind-the-design',
134
+ title: 'Behind the design',
135
+ excerpt: 'How this starter theme is built.',
136
+ contentHtml: '<p>Built with Tanqory theme-kit sections.</p>',
137
+ image: null,
138
+ author: 'Studio',
139
+ publishedAt: '2024-01-02T00:00:00.000Z',
140
+ tags: ['design'],
141
+ blogHandle: 'news',
142
+ },
143
+ ];
144
+ const blogs = fixture.blogs?.length
145
+ ? fixture.blogs.map((bl) => ({ ...bl, articles: bl.articles.map((a) => ({ ...a, blogHandle: a.blogHandle ?? bl.handle })) }))
146
+ : [{ id: 'mock/blog/news', handle: 'news', title: 'News', articles: sampleArticles }];
147
+ const articles = blogs.flatMap((bl) => bl.articles);
148
+ const blogFor = (handle) => blogs.find((bl) => bl.handle === handle || bl.handle === decodeHandle(handle)) ?? null;
149
+ const pages = fixture.pages ?? [];
150
+ const pageFor = (handle) => pages.find((pg) => pg.handle === handle || pg.handle === decodeHandle(handle)) ?? null;
151
+ const sampleShop = {
152
+ name: 'nova',
153
+ description: 'A clean starter storefront powered by Tanqory.',
154
+ brand: { logo: null, slogan: 'Modern essentials', shortDescription: 'Starter theme' },
155
+ policies: {
156
+ privacy: { handle: 'privacy-policy', title: 'Privacy policy', url: '/policies/privacy-policy', body: '<p>Mock privacy policy.</p>' },
157
+ refund: { handle: 'refund-policy', title: 'Refund policy', url: '/policies/refund-policy', body: '<p>Mock refund policy.</p>' },
158
+ termsOfService: { handle: 'terms-of-service', title: 'Terms of service', url: '/policies/terms-of-service', body: '<p>Mock terms of service.</p>' },
159
+ shipping: { handle: 'shipping-policy', title: 'Shipping policy', url: '/policies/shipping-policy', body: '<p>Mock shipping policy.</p>' },
160
+ subscription: null,
161
+ },
162
+ cookieBanner: { enabled: true, dataSharingTitle: 'Do not sell or share my personal information', dataSharingVisible: true },
163
+ };
164
+ const shop = fixture.shop
165
+ ? {
166
+ ...sampleShop,
167
+ ...fixture.shop,
168
+ brand: { ...sampleShop.brand, ...(fixture.shop.brand ?? {}) },
169
+ policies: { ...sampleShop.policies, ...(fixture.shop.policies ?? {}) },
170
+ }
171
+ : sampleShop;
172
+ const EMPTY_PI = { hasNextPage: false, hasPreviousPage: false, startCursor: null, endCursor: null };
173
+ const match = (q) => {
174
+ const needle = q.trim().toLowerCase();
175
+ return needle ? allProducts.filter((p) => p.title.toLowerCase().includes(needle)) : [];
176
+ };
177
+ return {
178
+ collectionByHandle: (handle) => collections.find((c) => c.handle === handle || c.handle === decodeHandle(handle)) ?? null,
179
+ allCollections: () => collections,
180
+ productByHandle: (handle) => productsByHandle.get(handle) ?? productsByHandle.get(decodeHandle(handle)) ?? null,
181
+ pageByHandle: (handle) => pageFor(handle),
182
+ // Localization mirrors what the store DASHBOARD (Markets) would publish —
183
+ // NOT a theme config list. Countries carry their currency; languages are the
184
+ // store's published locales. The live source fills this from store-api.
185
+ localization: fixture.localization ?? {
186
+ country: { isoCode: 'TH', name: 'Thailand', currency: { isoCode: 'THB', symbol: '฿' }, market: null },
187
+ availableCountries: [
188
+ { isoCode: 'TH', name: 'Thailand', currency: { isoCode: 'THB', symbol: '฿' }, market: null },
189
+ { isoCode: 'US', name: 'United States', currency: { isoCode: 'USD', symbol: '$' }, market: null },
190
+ { isoCode: 'JP', name: 'Japan', currency: { isoCode: 'JPY', symbol: '¥' }, market: null },
191
+ { isoCode: 'SG', name: 'Singapore', currency: { isoCode: 'SGD', symbol: 'S$' }, market: null },
192
+ { isoCode: 'GB', name: 'United Kingdom', currency: { isoCode: 'GBP', symbol: '£' }, market: null },
193
+ ],
194
+ language: { isoCode: 'en', name: 'English' },
195
+ availableLanguages: [
196
+ { isoCode: 'en', name: 'English' },
197
+ { isoCode: 'th', name: 'ไทย' },
198
+ { isoCode: 'ja', name: '日本語' },
199
+ ],
200
+ },
201
+ // ── commerce-standard extensions, served offline from the fixtures above so
202
+ // themes built against `useData()` behave the same in mock + live. ──
203
+ shop,
204
+ menu: (handle) => menus.get(handle) ?? menus.get(decodeHandle(handle)) ?? null,
205
+ fetchMenu: async (handle) => menus.get(handle) ?? menus.get(decodeHandle(handle)) ?? null,
206
+ notifyBackInStock: async () => 'subscribed',
207
+ listMenus: async () => Array.from(menus.values()).map((m) => ({
208
+ handle: m.handle,
209
+ title: m.title,
210
+ itemsCount: m.items.length,
211
+ })),
212
+ pixels: async () => [],
213
+ locations: async () => fixture.locations ?? [],
214
+ search: async (query, opts) => {
215
+ const types = opts?.types ?? ['PRODUCT', 'PAGE', 'ARTICLE'];
216
+ const products = types.includes('PRODUCT') ? match(query) : [];
217
+ const arts = types.includes('ARTICLE')
218
+ ? articles.filter((a) => a.title.toLowerCase().includes(query.trim().toLowerCase()))
219
+ : [];
220
+ const needle = query.trim().toLowerCase();
221
+ const pgs = types.includes('PAGE') && needle ? pages.filter((pg) => pg.title.toLowerCase().includes(needle)) : [];
222
+ return { totalCount: products.length + arts.length + pgs.length, products, pages: pgs, articles: arts, filters: [], pageInfo: EMPTY_PI };
223
+ },
224
+ predictiveSearch: async (query, opts) => {
225
+ const products = match(query).slice(0, opts?.limit ?? 4);
226
+ return {
227
+ queries: products.slice(0, 3).map((p) => p.title),
228
+ products,
229
+ collections: collections
230
+ .filter((c) => c.title.toLowerCase().includes(query.trim().toLowerCase()))
231
+ .slice(0, 3)
232
+ .map((c) => ({ handle: c.handle, title: c.title, image: null })),
233
+ pages: [],
234
+ articles: [],
235
+ };
236
+ },
237
+ collectionProducts: async (handle, opts) => {
238
+ const c = collections.find((x) => x.handle === handle);
239
+ const list = c?.products ?? [];
240
+ // Real cursor paging over the fixture, so "Load more" and numbered pages
241
+ // behave offline as they do live. The cursor is the offset.
242
+ const start = Math.max(0, Number(opts?.after ?? 0) || 0);
243
+ const end = start + (opts?.first ?? 24);
244
+ return {
245
+ products: list.slice(start, end),
246
+ filters: [],
247
+ pageInfo: {
248
+ hasNextPage: end < list.length,
249
+ hasPreviousPage: start > 0,
250
+ startCursor: String(start),
251
+ endCursor: String(Math.min(end, list.length)),
252
+ },
253
+ };
254
+ },
255
+ productRecommendations: async (productId) => {
256
+ const base = allProducts.find((p) => p.id === productId);
257
+ const picked = (base && fixture.recommendations?.[base.handle]) ?? [];
258
+ const listed = picked.flatMap((h) => productsByHandle.get(h) ?? []);
259
+ return listed.length ? listed : allProducts.filter((p) => p.id !== productId).slice(0, 4);
260
+ },
261
+ blogByHandle: async (handle) => blogFor(handle),
262
+ articleByHandle: async (blogHandle, articleHandle) => blogFor(blogHandle)?.articles.find((a) => a.handle === articleHandle || a.handle === decodeHandle(articleHandle)) ?? null,
263
+ metaobject: async () => null,
264
+ metaobjects: async () => [],
265
+ customer: {
266
+ login: async () => ({ token: null, expiresAt: null, errors: ['Customer accounts need live data (mock mode).'] }),
267
+ logout: async () => { },
268
+ renew: async () => ({ token: null, expiresAt: null, errors: ['Customer accounts need live data (mock mode).'] }),
269
+ register: async () => ({ ok: false, errors: ['Customer accounts need live data (mock mode).'] }),
270
+ get: async () => null,
271
+ orders: async () => [],
272
+ paymentMethods: async () => [],
273
+ orderByLookup: async () => null,
274
+ createAddress: async () => ({ ok: false, errors: ['mock mode'] }),
275
+ updateAddress: async () => ({ ok: false, errors: ['mock mode'] }),
276
+ deleteAddress: async () => ({ ok: false, errors: ['mock mode'] }),
277
+ setDefaultAddress: async () => ({ ok: false, errors: ['mock mode'] }),
278
+ },
279
+ };
280
+ }
281
+ // Bootstrap fetches BOTH collections AND a flat product list. The flat list
282
+ // powers a synthesized "featured" virtual collection when the store has live
283
+ // products but the merchant hasn't built a real collection yet — without it,
284
+ // a brand-new merchant's first Active product would never appear on the
285
+ // storefront (collections-only bootstrap = empty homepage).
286
+ // Shared product-card selection for every grid/list. Scalars + featuredImage +
287
+ // price + compareAtPrice (sale badge) + facets (vendor/type/tags) — all cheap
288
+ // (cost 0–1). Heavy fields (gallery, variants, metafields, sellingPlans,
289
+ // storeAvailability) stay on the PDP query only.
290
+ const PRODUCT_CARD_FIELDS = /* GraphQL */ `
291
+ fragment ProductCardBoot on Product {
292
+ id
293
+ handle
294
+ title
295
+ availableForSale
296
+ vendor
297
+ productType
298
+ tags
299
+ publishedAt
300
+ createdAt
301
+ onlineStoreUrl
302
+ featuredImage { url altText width height }
303
+ priceRange { minVariantPrice { amount currencyCode } maxVariantPrice { amount currencyCode } }
304
+ compareAtPriceRange { minVariantPrice { amount currencyCode } maxVariantPrice { amount currencyCode } }
305
+ firstAvailableVariant { id }
306
+ templateSuffix
307
+ }
308
+ `;
309
+ const COLLECTIONS_QUERY = /* GraphQL */ `
310
+ ${BOOTSTRAP_SHOP_MENU_FRAGMENTS}
311
+ ${PRODUCT_CARD_FIELDS}
312
+ query NovaBootstrap($first: Int!, $productFirst: Int!, $productsTop: Int!, $pageHandle: String, $productHandle: String, $collectionHandle: String, $policyBodies: Boolean = false) {
313
+ ${BOOTSTRAP_SHOP_MENU}
314
+ policyBodies: shop @include(if: $policyBodies) {
315
+ privacyPolicy { handle body }
316
+ refundPolicy { handle body }
317
+ termsOfService { handle body }
318
+ shippingPolicy { handle body }
319
+ subscriptionPolicy { handle body }
320
+ }
321
+ page(handle: $pageHandle) {
322
+ handle
323
+ title
324
+ body
325
+ bodySummary
326
+ author
327
+ publishedAt
328
+ updatedAt
329
+ templateSuffix
330
+ seo { title description keywords }
331
+ }
332
+ product(handle: $productHandle) { ...ProductCardBoot description seo { title description keywords } }
333
+ collection(handle: $collectionHandle) {
334
+ id
335
+ handle
336
+ title
337
+ description
338
+ image { url altText width height }
339
+ productsCount { count }
340
+ templateSuffix
341
+ seo { title description keywords }
342
+ }
343
+ collections(first: $first) {
344
+ edges {
345
+ node {
346
+ id
347
+ handle
348
+ title
349
+ image { url altText width height }
350
+ productsCount { count }
351
+ templateSuffix
352
+ products(first: $productFirst) {
353
+ edges {
354
+ node { ...ProductCardBoot }
355
+ }
356
+ }
357
+ }
358
+ }
359
+ }
360
+ products(first: $productsTop) {
361
+ edges {
362
+ node { ...ProductCardBoot }
363
+ }
364
+ }
365
+ localization {
366
+ country {
367
+ isoCode
368
+ name
369
+ currency { isoCode name symbol }
370
+ market { id handle name }
371
+ }
372
+ availableCountries {
373
+ isoCode
374
+ name
375
+ currency { isoCode name symbol }
376
+ market { id handle name }
377
+ }
378
+ language { isoCode name }
379
+ availableLanguages { isoCode name }
380
+ }
381
+ }
382
+ `;
383
+ // Reduced bootstrap. `localization` and the nested `collections.products` are
384
+ // non-nullable in the storefront schema, so if a cell errors on either (e.g. an
385
+ // older / partially-broken store-api) GraphQL nulls the ENTIRE response and the
386
+ // whole boot falls back to mock. This variant drops both optional pieces so the
387
+ // essentials — shop, menus, page, collections, top products — still load.
388
+ const SAFE_COLLECTIONS_QUERY = /* GraphQL */ `
389
+ ${BOOTSTRAP_SHOP_MENU_FRAGMENTS}
390
+ ${PRODUCT_CARD_FIELDS}
391
+ query NovaBootstrapSafe($first: Int!, $productsTop: Int!, $pageHandle: String, $productHandle: String, $collectionHandle: String, $policyBodies: Boolean = false) {
392
+ ${BOOTSTRAP_SHOP_MENU}
393
+ policyBodies: shop @include(if: $policyBodies) {
394
+ privacyPolicy { handle body }
395
+ refundPolicy { handle body }
396
+ termsOfService { handle body }
397
+ shippingPolicy { handle body }
398
+ subscriptionPolicy { handle body }
399
+ }
400
+ page(handle: $pageHandle) {
401
+ handle
402
+ title
403
+ body
404
+ bodySummary
405
+ author
406
+ publishedAt
407
+ updatedAt
408
+ templateSuffix
409
+ seo { title description keywords }
410
+ }
411
+ product(handle: $productHandle) { ...ProductCardBoot description seo { title description keywords } }
412
+ collection(handle: $collectionHandle) {
413
+ id
414
+ handle
415
+ title
416
+ description
417
+ image { url altText width height }
418
+ productsCount { count }
419
+ templateSuffix
420
+ seo { title description keywords }
421
+ }
422
+ collections(first: $first) {
423
+ edges {
424
+ node {
425
+ id
426
+ handle
427
+ title
428
+ image { url altText width height }
429
+ productsCount { count }
430
+ templateSuffix
431
+ }
432
+ }
433
+ }
434
+ products(first: $productsTop) {
435
+ edges {
436
+ node { ...ProductCardBoot }
437
+ }
438
+ }
439
+ }
440
+ `;
441
+ function normalizeImage(img) {
442
+ if (!img || !img.url)
443
+ return null;
444
+ const width = img.width ?? null;
445
+ const height = img.height ?? null;
446
+ return {
447
+ url: img.url,
448
+ ...(img.altText ? { altText: img.altText } : {}),
449
+ ...(width != null ? { width } : {}),
450
+ ...(height != null ? { height } : {}),
451
+ ...(width && height ? { aspectRatio: width / height } : {}),
452
+ };
453
+ }
454
+ function normalizeProduct(p) {
455
+ const price = p.priceRange?.minVariantPrice ?? { amount: '0', currencyCode: 'USD' };
456
+ // Only surface compareAtPrice when it's a REAL sale (was > now) — the backend
457
+ // returns the range even when equal, which would render a pointless strikethrough.
458
+ // The card pairs it with the LOWEST price, so it takes the lowest "was" too:
459
+ // the highest one (the dearest size's) turned a 22% sale into a "-49%" badge.
460
+ const compareAt = p.compareAtPriceRange?.minVariantPrice ?? p.compareAtPriceRange?.maxVariantPrice;
461
+ const onSale = compareAt && Number(compareAt.amount) > Number(price.amount);
462
+ return {
463
+ id: p.id,
464
+ handle: p.handle,
465
+ title: p.title,
466
+ price,
467
+ ...(p.priceRange?.maxVariantPrice && Number(p.priceRange.maxVariantPrice.amount) > Number(price.amount) ? { priceMax: p.priceRange.maxVariantPrice } : {}),
468
+ featuredImage: normalizeImage(p.featuredImage),
469
+ ...(onSale ? { compareAtPrice: compareAt } : {}),
470
+ ...(p.vendor ? { vendor: p.vendor } : {}),
471
+ ...(p.productType ? { productType: p.productType } : {}),
472
+ ...(p.tags?.length ? { tags: p.tags } : {}),
473
+ ...(p.publishedAt ? { publishedAt: p.publishedAt } : {}),
474
+ ...(p.createdAt ? { createdAt: p.createdAt } : {}),
475
+ ...(p.onlineStoreUrl ? { onlineStoreUrl: p.onlineStoreUrl } : {}),
476
+ ...(p.firstAvailableVariant?.id ? { variantId: p.firstAvailableVariant.id } : {}),
477
+ ...(typeof p.availableForSale === 'boolean' ? { availableForSale: p.availableForSale } : {}),
478
+ ...(p.templateSuffix ? { templateSuffix: p.templateSuffix } : {}),
479
+ ...(p.seo ? { seo: { title: p.seo.title ?? null, description: p.seo.description ?? null, keywords: p.seo.keywords ?? [] } } : {}),
480
+ // The route's own product carries its plain description (bootstrap) — the meta description fallback.
481
+ ...(p.description ? { description: p.description } : {}),
482
+ };
483
+ }
484
+ function normalizeCollection(c) {
485
+ return {
486
+ ...(c.id ? { id: c.id } : {}),
487
+ handle: c.handle,
488
+ title: c.title,
489
+ ...(c.description ? { description: c.description } : {}),
490
+ image: normalizeImage(c.image),
491
+ ...(typeof c.productsCount?.count === 'number'
492
+ ? { productsCount: c.productsCount.count }
493
+ : {}),
494
+ // Nested products are optional — the reduced bootstrap (used when a cell
495
+ // errors on the nested products field) omits them.
496
+ ...(c.templateSuffix ? { templateSuffix: c.templateSuffix } : {}),
497
+ ...(c.seo ? { seo: { title: c.seo.title ?? null, description: c.seo.description ?? null, keywords: c.seo.keywords ?? [] } } : {}),
498
+ products: (c.products?.edges ?? []).map((e) => normalizeProduct(e.node)),
499
+ };
500
+ }
501
+ // Single-product fetch (PDP) — full options + variants for the variant picker.
502
+ // Kept out of the bootstrap (variants(first:100) @cost=100/product would blow
503
+ // the cost budget) and fetched lazily only on the product page.
504
+ const PRODUCT_QUERY = /* GraphQL */ `
505
+ query NovaProduct($handle: String!, $identifiers: [MetafieldIdentifier!]!) {
506
+ product(handle: $handle) {
507
+ id
508
+ handle
509
+ title
510
+ description
511
+ descriptionHtml
512
+ vendor
513
+ productType
514
+ tags
515
+ availableForSale
516
+ isGiftCard
517
+ totalInventory
518
+ featuredImage { url altText width height }
519
+ images(first: 20) { nodes { url altText width height } }
520
+ media(first: 20) {
521
+ nodes {
522
+ __typename
523
+ ... on MediaImage { id alt image { url altText width height } }
524
+ ... on Video { id alt previewImage { url altText width height } sources { url mimeType format } }
525
+ ... on Model3d { id alt previewImage { url altText width height } sources { url mimeType format } }
526
+ ... on ExternalVideo { id alt host embedUrl previewImage { url altText width height } }
527
+ }
528
+ }
529
+ priceRange { minVariantPrice { amount currencyCode } maxVariantPrice { amount currencyCode } }
530
+ compareAtPriceRange { minVariantPrice { amount currencyCode } maxVariantPrice { amount currencyCode } }
531
+ options(first: 10) { name values }
532
+ collections(first: 10) { nodes { handle title } }
533
+ seo { title description keywords }
534
+ templateSuffix
535
+ variants(first: 50) {
536
+ nodes {
537
+ id
538
+ title
539
+ availableForSale
540
+ sku
541
+ barcode
542
+ inventoryQuantity
543
+ inventoryPolicy
544
+ requiresShipping
545
+ taxable
546
+ weight { value unit }
547
+ price { amount currencyCode }
548
+ compareAtPrice { amount currencyCode }
549
+ image { url altText width height }
550
+ selectedOptions { name value }
551
+ unitPrice { amount currencyCode }
552
+ unitPriceMeasurement { measuredType quantityValue quantityUnit referenceValue referenceUnit }
553
+ quantityRule { minimum maximum increment }
554
+ storeAvailability(first: 5) {
555
+ nodes { available quantityAvailable pickUpTime location { id name } }
556
+ }
557
+ }
558
+ }
559
+ sellingPlanGroups(first: 5) {
560
+ nodes {
561
+ name
562
+ appName
563
+ options { name values }
564
+ sellingPlans(first: 10) {
565
+ nodes { id name description recurringDeliveries options { name value } }
566
+ }
567
+ }
568
+ }
569
+ metafields(identifiers: $identifiers) { namespace key value }
570
+ firstAvailableVariant { id }
571
+ }
572
+ }
573
+ `;
574
+ function normalizeProductDetail(p) {
575
+ const base = normalizeProduct(p);
576
+ const variants = (p.variants?.nodes ?? []).map((v) => ({
577
+ id: v.id,
578
+ title: v.title,
579
+ price: v.price ?? base.price,
580
+ ...(v.compareAtPrice && Number(v.compareAtPrice.amount) > Number((v.price ?? base.price).amount)
581
+ ? { compareAtPrice: v.compareAtPrice }
582
+ : {}),
583
+ availableForSale: v.availableForSale,
584
+ ...(v.sku ? { sku: v.sku } : {}),
585
+ ...(v.barcode ? { barcode: v.barcode } : {}),
586
+ ...(typeof v.inventoryQuantity === 'number' ? { inventoryQuantity: v.inventoryQuantity } : {}),
587
+ ...(v.inventoryPolicy ? { inventoryPolicy: v.inventoryPolicy } : {}),
588
+ ...(typeof v.requiresShipping === 'boolean' ? { requiresShipping: v.requiresShipping } : {}),
589
+ ...(typeof v.taxable === 'boolean' ? { taxable: v.taxable } : {}),
590
+ ...(v.weight ? { weight: v.weight } : {}),
591
+ ...(v.selectedOptions?.length ? { selectedOptions: v.selectedOptions } : {}),
592
+ image: normalizeImage(v.image),
593
+ ...(v.unitPrice ? { unitPrice: v.unitPrice } : {}),
594
+ ...(v.unitPriceMeasurement ? { unitPriceMeasurement: v.unitPriceMeasurement } : {}),
595
+ ...(v.quantityRule ? { quantityRule: v.quantityRule } : {}),
596
+ ...(v.storeAvailability?.nodes?.length
597
+ ? {
598
+ storeAvailability: v.storeAvailability.nodes.map((s) => ({
599
+ available: s.available,
600
+ quantityAvailable: s.quantityAvailable,
601
+ pickUpTime: s.pickUpTime ?? null,
602
+ location: s.location,
603
+ })),
604
+ }
605
+ : {}),
606
+ }));
607
+ const images = (p.images?.nodes ?? [])
608
+ .map(normalizeImage)
609
+ .filter((i) => i !== null);
610
+ const TYPE_MAP = {
611
+ MediaImage: 'image',
612
+ Video: 'video',
613
+ Model3d: 'model_3d',
614
+ ExternalVideo: 'external_video',
615
+ };
616
+ const media = (p.media?.nodes ?? []).map((m) => ({
617
+ id: m.id,
618
+ type: TYPE_MAP[m.__typename] ?? 'image',
619
+ alt: m.alt ?? null,
620
+ ...(m.image ? { image: normalizeImage(m.image) } : {}),
621
+ ...(m.previewImage ? { previewImage: normalizeImage(m.previewImage) } : {}),
622
+ ...(m.sources?.length ? { sources: m.sources } : {}),
623
+ ...(m.host ? { host: m.host } : {}),
624
+ ...(m.embedUrl ? { embedUrl: m.embedUrl } : {}),
625
+ }));
626
+ const sellingPlanGroups = (p.sellingPlanGroups?.nodes ?? []).map((g) => ({
627
+ name: g.name,
628
+ appName: g.appName ?? null,
629
+ options: g.options ?? [],
630
+ sellingPlans: (g.sellingPlans?.nodes ?? []).map((sp) => ({
631
+ id: sp.id,
632
+ name: sp.name,
633
+ description: sp.description ?? null,
634
+ recurringDeliveries: sp.recurringDeliveries,
635
+ options: sp.options ?? [],
636
+ })),
637
+ }));
638
+ const metafields = {};
639
+ for (const m of p.metafields ?? []) {
640
+ if (m)
641
+ metafields[`${m.namespace}.${m.key}`] = m.value;
642
+ }
643
+ return {
644
+ ...base,
645
+ ...(p.description ? { description: p.description } : {}),
646
+ ...(p.descriptionHtml ? { descriptionHtml: p.descriptionHtml } : {}),
647
+ ...(typeof p.isGiftCard === 'boolean' ? { isGiftCard: p.isGiftCard } : {}),
648
+ ...(typeof p.totalInventory === 'number' ? { totalInventory: p.totalInventory } : {}),
649
+ ...(images.length ? { images } : {}),
650
+ ...(media.length ? { media } : {}),
651
+ ...(p.options?.length ? { options: p.options } : {}),
652
+ ...(p.seo ? { seo: { title: p.seo.title ?? null, description: p.seo.description ?? null, keywords: p.seo.keywords ?? [] } } : {}),
653
+ ...(variants.length ? { variants } : {}),
654
+ ...(sellingPlanGroups.length ? { sellingPlanGroups } : {}),
655
+ ...(p.collections?.nodes?.length
656
+ ? { collections: p.collections.nodes.map((c) => ({ handle: c.handle, title: c.title })) }
657
+ : {}),
658
+ ...(Object.keys(metafields).length ? { metafields } : {}),
659
+ };
660
+ }
661
+ /**
662
+ * One request path for the bootstrap AND every post-boot interaction (the
663
+ * cart's mutations, the PDP's lazy product fetch) — same endpoint, same
664
+ * publishable-key + country headers, same error handling.
665
+ */
666
+ function makeGraphqlRequest(opts) {
667
+ const maybeFetch = opts.fetcher ?? globalThis.fetch;
668
+ if (!maybeFetch) {
669
+ throw new Error('[theme-kit] createLiveData: fetch is not available in this environment');
670
+ }
671
+ // Capture into a definitely-defined const so the narrowing survives into the
672
+ // graphqlRequest closure below (TS drops `!undefined` narrowing across scopes).
673
+ const f = maybeFetch;
674
+ const endpoint = opts.endpoint.replace(/\/$/, '');
675
+ const url = `${endpoint}/api/v1/stores/${encodeURIComponent(opts.storeId)}/graphql`;
676
+ return async function graphqlRequest(query, variables) {
677
+ const res = await f(url, {
678
+ method: 'POST',
679
+ headers: {
680
+ 'content-type': 'application/json',
681
+ ...(opts.token ? { 'x-publishable-key': opts.token } : {}),
682
+ // X-Tanqory-Country triggers backend Market resolution; if the store
683
+ // has an active Market with this country, Money.currencyCode + amount
684
+ // come back already-converted in the target currency.
685
+ ...(opts.country ? { 'x-tanqory-country': opts.country.toUpperCase() } : {}),
686
+ // X-Tanqory-Lang triggers translation overlay: product/collection/page
687
+ // content comes back in this locale where the merchant has translations.
688
+ ...(opts.locale ? { 'x-tanqory-lang': opts.locale.toLowerCase() } : {}),
689
+ },
690
+ body: JSON.stringify({ query, variables }),
691
+ });
692
+ if (!res.ok) {
693
+ throw new Error(`[theme-kit] GraphQL HTTP ${res.status} from ${url} — ${await res.text().catch(() => '')}`);
694
+ }
695
+ const json = (await res.json());
696
+ if (json.errors?.length) {
697
+ const msg = json.errors.map((e) => e.message).join('; ');
698
+ // Partial success: GraphQL nulls the failed field(s) but still returns the
699
+ // rest of `data`. Only fail hard when NOTHING came back — otherwise log and
700
+ // use what we got, so one flaky field (e.g. `localization` on an older
701
+ // cell) can't blank the entire storefront / fall the whole boot to mock.
702
+ if (json.data == null) {
703
+ throw new Error(`[theme-kit] GraphQL errors: ${msg}`);
704
+ }
705
+ if (typeof console !== 'undefined') {
706
+ // eslint-disable-next-line no-console
707
+ console.warn(`[theme-kit] GraphQL partial errors (using partial data): ${msg}`);
708
+ }
709
+ }
710
+ return json.data;
711
+ };
712
+ }
713
+ export async function createLiveData(opts) {
714
+ const graphqlRequest = makeGraphqlRequest(opts);
715
+ // Defaults stay under store-api's GraphQL cost budget (1000). Cost formula
716
+ // for the bootstrap query: 3*N + 4*N*M + 4*T (N = collectionLimit,
717
+ // M = productLimitPerCollection, T = topProductLimit). 10 + 10 + 24 = 526
718
+ // — plenty of headroom for a homepage prefetch. Bump in opts.prefetch only
719
+ // if you're sure the store's cost-budget limit is higher than 1000.
720
+ const collectionLimit = opts.prefetch?.collectionLimit ?? 10;
721
+ const productLimitPerCollection = opts.prefetch?.productLimitPerCollection ?? 10;
722
+ const topProductLimit = opts.prefetch?.topProductLimit ?? 24;
723
+ let boot;
724
+ try {
725
+ boot = await graphqlRequest(COLLECTIONS_QUERY, {
726
+ first: collectionLimit,
727
+ productFirst: productLimitPerCollection,
728
+ productsTop: topProductLimit,
729
+ pageHandle: opts.pageHandle ?? null,
730
+ productHandle: opts.productHandle ?? null,
731
+ collectionHandle: opts.collectionHandle ?? null,
732
+ policyBodies: opts.policyBodies === true,
733
+ });
734
+ }
735
+ catch (err) {
736
+ // The full query nulls out entirely if the cell errors on an optional field
737
+ // (localization, nested collection products). Retry once with the reduced
738
+ // query so the storefront still renders real shop/menus/collections/products
739
+ // instead of falling all the way back to mock.
740
+ if (typeof console !== 'undefined') {
741
+ // eslint-disable-next-line no-console
742
+ console.warn(`[theme-kit] full bootstrap failed, retrying without optional fields: ${err.message}`);
743
+ }
744
+ boot = await graphqlRequest(SAFE_COLLECTIONS_QUERY, {
745
+ first: collectionLimit,
746
+ productsTop: topProductLimit,
747
+ pageHandle: opts.pageHandle ?? null,
748
+ productHandle: opts.productHandle ?? null,
749
+ collectionHandle: opts.collectionHandle ?? null,
750
+ policyBodies: opts.policyBodies === true,
751
+ });
752
+ }
753
+ return buildLiveData(boot, graphqlRequest, opts);
754
+ }
755
+ /**
756
+ * Build a live DataApi SYNCHRONOUSLY from a previously-fetched bootstrap
757
+ * payload (`data.getSnapshot()`, serialized into the SSG HTML as
758
+ * `window.__TQ_STATE__` by the prerender step). This is what makes hydration
759
+ * deterministic: the client's first render uses the EXACT data the server
760
+ * rendered with — no network round-trip, no drift, no mock fallback — and
761
+ * mount()'s `revalidate` swaps in fresh data after hydration (SWR).
762
+ */
763
+ export function createLiveDataFromSnapshot(snapshot, opts) {
764
+ const graphqlRequest = makeGraphqlRequest(opts);
765
+ return buildLiveData((snapshot ?? undefined), graphqlRequest, opts);
766
+ }
767
+ /** Assemble the DataApi from a bootstrap payload + a live requester. Shared by
768
+ * createLiveData (fetches the bootstrap) and createLiveDataFromSnapshot
769
+ * (reuses the serialized one) so both paths render identically. */
770
+ function buildLiveData(boot, graphqlRequest, opts) {
771
+ const productLimitPerCollection = opts.prefetch?.productLimitPerCollection ?? 10;
772
+ const collections = (boot?.collections.edges ?? []).map((e) => normalizeCollection(e.node));
773
+ const topProducts = (boot?.products.edges ?? []).map((e) => normalizeProduct(e.node));
774
+ // Index the current detail route's product/collection (prefetched by handle)
775
+ // so productByHandle/collectionByHandle resolve it even when it isn't in the
776
+ // top set — this is what lets the theme pick its templateSuffix variant.
777
+ if (boot?.product)
778
+ topProducts.push(normalizeProduct(boot.product));
779
+ // Themes commonly reference `featured` / `frontpage` / `all` as their homepage
780
+ // collection. Synthesize one when the merchant hasn't created a real
781
+ // collection yet but DOES have Active products — otherwise their first
782
+ // product would never appear on the storefront. Also ensure `allProducts`
783
+ // is wired even when no products exist outside of collections.
784
+ if (boot?.collection && !collections.some((c) => c.handle === boot.collection.handle)) {
785
+ collections.push(normalizeCollection(boot.collection));
786
+ }
787
+ // Only for a store with no collection at all: synthesized next to real ones,
788
+ // "Featured" showed up in every collection list as a collection the
789
+ // merchant never made (English title, first product's image).
790
+ const realCollections = collections.slice();
791
+ if (topProducts.length > 0 && collections.length === 0) {
792
+ collections.unshift({
793
+ handle: 'featured',
794
+ title: 'Featured',
795
+ image: topProducts[0].featuredImage ?? null,
796
+ products: topProducts.slice(0, productLimitPerCollection),
797
+ });
798
+ }
799
+ // Mirror as `all` too — many themes (incl. our nova templates) reference it.
800
+ if (topProducts.length > 0 && !collections.some((c) => c.handle === 'all')) {
801
+ collections.push({
802
+ handle: 'all',
803
+ title: 'All products',
804
+ image: topProducts[0].featuredImage ?? null,
805
+ products: topProducts,
806
+ });
807
+ }
808
+ // Reuse the createMockData factory — same cache shape, same DataApi.
809
+ // It also indexes products by handle so productByHandle() works even for
810
+ // products fetched only via the top-level products() query.
811
+ const data = createMockData(collections);
812
+ // `all` (and a stand-in `featured`) stay addressable by handle, but a list of
813
+ // the store's collections lists only the ones the merchant made.
814
+ if (realCollections.length > 0)
815
+ data.allCollections = () => realCollections;
816
+ const pageNode = boot?.page;
817
+ if (pageNode) {
818
+ // Cache only the page that matched the URL. pageByHandle returns null
819
+ // for everything else — themes should only call it for the current page.
820
+ const page = {
821
+ handle: pageNode.handle,
822
+ title: pageNode.title,
823
+ body: pageNode.body,
824
+ ...(pageNode.bodySummary ? { bodySummary: pageNode.bodySummary } : {}),
825
+ ...(pageNode.author ? { author: pageNode.author } : {}),
826
+ ...(pageNode.publishedAt ? { publishedAt: pageNode.publishedAt } : {}),
827
+ ...(pageNode.updatedAt ? { updatedAt: pageNode.updatedAt } : {}),
828
+ ...(pageNode.templateSuffix ? { templateSuffix: pageNode.templateSuffix } : {}),
829
+ };
830
+ data.pageByHandle = (handle) => handle === page.handle || decodeHandle(handle) === page.handle ? page : null;
831
+ }
832
+ const loc = boot?.localization;
833
+ if (loc) {
834
+ // Only expose the localization payload when the store actually has Markets
835
+ // (availableCountries non-empty). With zero markets, leave `null` so the
836
+ // theme's country picker hides itself instead of showing a hardcoded list
837
+ // that doesn't match what the merchant has configured.
838
+ data.localization =
839
+ loc.availableCountries.length > 0
840
+ ? {
841
+ country: loc.country,
842
+ availableCountries: loc.availableCountries,
843
+ // Published languages come straight from the store (StoreLanguage →
844
+ // SDL `availableLanguages`); the theme just renders the picker.
845
+ language: loc.language,
846
+ availableLanguages: loc.availableLanguages,
847
+ }
848
+ : null;
849
+ }
850
+ // Post-boot capabilities: the raw GraphQL escape hatch (cart mutations live
851
+ // on top of this) and an on-demand single-product fetch (PDP variant picker).
852
+ data.graphql = graphqlRequest;
853
+ data.fetchProduct = async (handle, fpOpts) => {
854
+ // Never reject: a failed detail fetch (cost budget, cold cell, network)
855
+ // must degrade to the prefetched card data, not crash the product page
856
+ // with an unhandled rejection mid-hydration.
857
+ try {
858
+ const res = await graphqlRequest(PRODUCT_QUERY, {
859
+ handle,
860
+ identifiers: fpOpts?.metafields ?? [],
861
+ });
862
+ return res?.product ? normalizeProductDetail(res.product) : null;
863
+ }
864
+ catch (err) {
865
+ if (typeof console !== 'undefined') {
866
+ // eslint-disable-next-line no-console
867
+ console.warn(`[theme-kit] fetchProduct(${handle}) failed: ${err.message}`);
868
+ }
869
+ return null;
870
+ }
871
+ };
872
+ const toMfMap = (arr) => {
873
+ const out = {};
874
+ for (const m of arr ?? [])
875
+ if (m)
876
+ out[`${m.namespace}.${m.key}`] = m.value;
877
+ return out;
878
+ };
879
+ data.fetchShopMetafields = async (identifiers) => {
880
+ if (!identifiers.length)
881
+ return {};
882
+ const res = await graphqlRequest(`query NovaShopMetafields($identifiers: [MetafieldIdentifier!]!) {
883
+ shop { metafields(identifiers: $identifiers) { namespace key value } }
884
+ }`, { identifiers });
885
+ return toMfMap(res?.shop?.metafields);
886
+ };
887
+ data.fetchCollectionMetafields = async (handle, identifiers) => {
888
+ if (!identifiers.length || !handle)
889
+ return {};
890
+ const res = await graphqlRequest(`query NovaCollectionMetafields($handle: String!, $identifiers: [MetafieldIdentifier!]!) {
891
+ collection(handle: $handle) { metafields(identifiers: $identifiers) { namespace key value } }
892
+ }`, { handle, identifiers });
893
+ return toMfMap(res?.collection?.metafields);
894
+ };
895
+ // ─── commerce-standard storefront extensions ───────────────────
896
+ // Shop info + the two standard menus came back in the bootstrap → expose
897
+ // them synchronously (the layout's header/footer render at hydration).
898
+ const { shop, menus } = readBootstrapShopMenu(boot);
899
+ data.shop = shop;
900
+ data.menu = (handle) => menus.get(handle) ?? menus.get(decodeHandle(handle)) ?? null;
901
+ // The rest (search, blog, recommendations, metaobjects, customer account)
902
+ // are lazy — attach them on the same requester. fetchMenu shares `menus` so
903
+ // a later fetch warms the same cache the sync menu() reads.
904
+ Object.assign(data, createStorefrontMethods(graphqlRequest, { normalizeProduct }, menus));
905
+ // One request per blog / article: the SPA router reads the record for its
906
+ // template variant and the section reads it for its posts — the same answer.
907
+ const memo = (fn, keyOf) => {
908
+ if (!fn)
909
+ return fn;
910
+ const inflight = new Map();
911
+ return (...a) => {
912
+ const k = keyOf(...a);
913
+ let p = inflight.get(k);
914
+ if (!p) {
915
+ p = fn(...a).catch((e) => {
916
+ inflight.delete(k);
917
+ throw e;
918
+ });
919
+ inflight.set(k, p);
920
+ }
921
+ return p;
922
+ };
923
+ };
924
+ data.blogByHandle = memo(data.blogByHandle, (h, o) => `${decodeHandle(h)}|${o?.articles ?? ''}`);
925
+ data.articleByHandle = memo(data.articleByHandle, (b, a) => `${decodeHandle(b)}/${decodeHandle(a)}`);
926
+ // The bootstrap carries only the landing page. A page reached by soft
927
+ // navigation is fetched here, and pageByHandle answers for it afterwards —
928
+ // its body and its template variant (page.contact) need the record.
929
+ const fetchedPages = new Map();
930
+ const landingPage = data.pageByHandle;
931
+ data.pageByHandle = (handle) => landingPage(handle) ?? fetchedPages.get(decodeHandle(handle)) ?? null;
932
+ data.fetchPage = async (handle) => {
933
+ const known = data.pageByHandle(handle);
934
+ if (known)
935
+ return known;
936
+ const res = await graphqlRequest(`query NovaPage($handle: String!) {
937
+ page(handle: $handle) { handle title body bodySummary author publishedAt updatedAt templateSuffix seo { title description keywords } }
938
+ }`, { handle: decodeHandle(handle) });
939
+ const n = res?.page;
940
+ if (!n)
941
+ return null;
942
+ const page = {
943
+ handle: n.handle,
944
+ title: n.title,
945
+ body: n.body ?? '',
946
+ ...(n.bodySummary ? { bodySummary: n.bodySummary } : {}),
947
+ ...(n.author ? { author: n.author } : {}),
948
+ ...(n.publishedAt ? { publishedAt: n.publishedAt } : {}),
949
+ ...(n.updatedAt ? { updatedAt: n.updatedAt } : {}),
950
+ ...(n.templateSuffix ? { templateSuffix: n.templateSuffix } : {}),
951
+ ...(n.seo ? { seo: n.seo } : {}),
952
+ };
953
+ fetchedPages.set(page.handle, page);
954
+ return page;
955
+ };
956
+ // List every store menu (Dashboard → Navigation) for the editor's link_list
957
+ // picker — the storefront `menus` query (id/handle/title/itemsCount).
958
+ data.listMenus = async () => {
959
+ const res = await graphqlRequest(`query NovaMenus { menus { handle title itemsCount } }`);
960
+ return res?.menus ?? [];
961
+ };
962
+ data.notifyBackInStock = async (input) => {
963
+ const f = opts.fetcher ?? globalThis.fetch;
964
+ if (!f)
965
+ throw new Error('[theme-kit] notifyBackInStock: fetch is not available');
966
+ const res = await f(`${opts.endpoint.replace(/\/$/, '')}/api/v1/stores/${encodeURIComponent(opts.storeId)}/storefront/back-in-stock`, {
967
+ method: 'POST',
968
+ headers: {
969
+ 'content-type': 'application/json',
970
+ ...(opts.token ? { 'x-publishable-key': opts.token } : {}),
971
+ },
972
+ body: JSON.stringify({
973
+ // store-api wants the bare UUID; tolerate a `gid://…/<uuid>` form
974
+ variantId: input.variantId.split('/').pop(),
975
+ email: input.email,
976
+ ...(input.locale ? { locale: input.locale } : {}),
977
+ ...(input.country ? { country: input.country.toUpperCase() } : {}),
978
+ }),
979
+ });
980
+ if (!res.ok)
981
+ throw new Error(`[theme-kit] notify-me HTTP ${res.status}`);
982
+ const json = (await res.json().catch(() => ({})));
983
+ return json.status === 'available' ? 'available' : 'subscribed';
984
+ };
985
+ data.pixels = async () => {
986
+ const res = await graphqlRequest(`query NovaPixels { customPixels { id name provider providerPixelId code } }`);
987
+ return res?.customPixels ?? [];
988
+ };
989
+ data.locations = async () => {
990
+ const res = await graphqlRequest(`query NovaLocations { locations { id name code address { country address city province postalCode phone } } }`);
991
+ return res?.locations ?? [];
992
+ };
993
+ // The raw serializable bootstrap this DataApi was built from. entry-server
994
+ // embeds it into the SSG HTML (window.__TQ_STATE__) so the client can
995
+ // rebuild the SAME DataApi synchronously at hydration — see
996
+ // createLiveDataFromSnapshot. null when there was no live bootstrap.
997
+ data.getSnapshot = () => boot ?? null;
998
+ return data;
999
+ }
1000
+ // ─── Deterministic money formatting ─────────────────────────────────────────
1001
+ // Intl.NumberFormat's currency output depends on the environment's ICU data
1002
+ // (the build pod's Node vs each visitor's browser can format the SAME Money
1003
+ // differently, e.g. "THB 120.00" vs "฿120.00") — which breaks SSR hydration
1004
+ // (React #425 text mismatch). Format manually instead: identical output
1005
+ // everywhere, by construction.
1006
+ // The decimals come from the platform's one currency table (@tanqory/money, generated copy in
1007
+ // headless/tanqory-money.generated.ts; docs/STANDARDS.md API-6): ISO 4217's, HUF, IDR and TWD in whole units.
1008
+ const CURRENCY_FORMAT = {
1009
+ THB: { symbol: '฿' },
1010
+ USD: { symbol: '$' },
1011
+ EUR: { symbol: '€' },
1012
+ GBP: { symbol: '£' },
1013
+ JPY: { symbol: '¥' },
1014
+ KRW: { symbol: '₩' },
1015
+ VND: { symbol: '₫' },
1016
+ IDR: { symbol: 'Rp' },
1017
+ SGD: { symbol: 'S$' },
1018
+ HKD: { symbol: 'HK$' },
1019
+ TWD: { symbol: 'NT$' },
1020
+ AUD: { symbol: 'A$' },
1021
+ NZD: { symbol: 'NZ$' },
1022
+ CAD: { symbol: 'CA$' },
1023
+ CNY: { symbol: 'CN¥' },
1024
+ INR: { symbol: '₹' },
1025
+ MYR: { symbol: 'RM' },
1026
+ PHP: { symbol: '₱' },
1027
+ };
1028
+ /** The grouped numeric part of a Money, without symbol or code.
1029
+ * `stripZeros` drops a `.00`-style fraction (`money_without_trailing_zeros`). */
1030
+ function moneyDigits(money, stripZeros = false) {
1031
+ const n = Number(money.amount);
1032
+ if (!Number.isFinite(n))
1033
+ return null;
1034
+ // Exact decimal text (a JS number's toFixed rounds 1.005 to 1.00); the number itself only when the text is not a decimal.
1035
+ let fixed = null;
1036
+ for (const v of [money.amount, n]) {
1037
+ try {
1038
+ fixed = displayAmount(v, money.currencyCode);
1039
+ break;
1040
+ }
1041
+ catch {
1042
+ // the next form, then none
1043
+ }
1044
+ }
1045
+ if (fixed === null)
1046
+ return null;
1047
+ let [int, frac] = fixed.replace(/^-/, '').split('.');
1048
+ if (stripZeros && frac && /^0+$/.test(frac))
1049
+ frac = '';
1050
+ const grouped = int.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
1051
+ return `${fixed.startsWith('-') ? '-' : ''}${grouped}${frac ? `.${frac}` : ''}`;
1052
+ }
1053
+ /** standard `money` — symbol + amount (e.g. "฿120.00"). */
1054
+ export function formatMoney(money) {
1055
+ const num = moneyDigits(money);
1056
+ if (num === null)
1057
+ return `${money.amount} ${money.currencyCode}`;
1058
+ const info = CURRENCY_FORMAT[money.currencyCode];
1059
+ return info ? `${info.symbol}${num}` : `${num} ${money.currencyCode}`;
1060
+ }
1061
+ /** standard `money_with_currency` — symbol + amount + ISO code (e.g. "฿120.00 THB"). */
1062
+ export function formatMoneyWithCurrency(money) {
1063
+ const num = moneyDigits(money);
1064
+ if (num === null)
1065
+ return `${money.amount} ${money.currencyCode}`;
1066
+ const info = CURRENCY_FORMAT[money.currencyCode];
1067
+ return info
1068
+ ? `${info.symbol}${num} ${money.currencyCode}`
1069
+ : `${num} ${money.currencyCode}`;
1070
+ }
1071
+ /** standard `money_without_currency` — bare grouped amount (e.g. "120.00"). */
1072
+ export function formatMoneyWithoutCurrency(money) {
1073
+ return moneyDigits(money) ?? `${money.amount}`;
1074
+ }
1075
+ /** standard `money_without_trailing_zeros` — symbol + amount, dropping a `.00`
1076
+ * fraction (e.g. "฿120", but "฿120.50" stays). */
1077
+ export function formatMoneyWithoutTrailingZeros(money) {
1078
+ const num = moneyDigits(money, true);
1079
+ if (num === null)
1080
+ return `${money.amount} ${money.currencyCode}`;
1081
+ const info = CURRENCY_FORMAT[money.currencyCode];
1082
+ return info ? `${info.symbol}${num}` : `${num} ${money.currencyCode}`;
1083
+ }
1084
+ /** standard `date` / `time_tag` — format an ISO date deterministically (identical
1085
+ * output on server + client to keep SSR hydration stable). Defaults to a medium
1086
+ * date; pass Intl options to customize. */
1087
+ export function formatDate(input, opts = { year: 'numeric', month: 'short', day: 'numeric' }, locale = 'en-US') {
1088
+ if (!input)
1089
+ return '';
1090
+ const d = input instanceof Date ? input : new Date(input);
1091
+ if (Number.isNaN(d.getTime()))
1092
+ return '';
1093
+ try {
1094
+ return new Intl.DateTimeFormat(locale, { ...opts, timeZone: 'UTC' }).format(d);
1095
+ }
1096
+ catch {
1097
+ return d.toISOString().slice(0, 10);
1098
+ }
1099
+ }
1100
+ /** standard `weight_with_unit` — format a variant weight (e.g. "1.5 kg"). */
1101
+ export function formatWeight(weight) {
1102
+ if (!weight || !Number.isFinite(weight.value))
1103
+ return '';
1104
+ const unit = { GRAMS: 'g', KILOGRAMS: 'kg', OUNCES: 'oz', POUNDS: 'lb' }[weight.unit] ?? weight.unit.toLowerCase();
1105
+ const n = Number.isInteger(weight.value) ? weight.value : Number(weight.value.toFixed(2));
1106
+ return `${n} ${unit}`;
1107
+ }
1108
+ /** standard `image_url` — append CDN transform params (width/height/crop) to an
1109
+ * image URL. No-op when the src is empty or no transform is requested. React
1110
+ * themes render the `<img>` themselves, so there is no separate `image_tag`. */
1111
+ export function imageUrl(src, opts = {}) {
1112
+ if (!src)
1113
+ return '';
1114
+ const { width, height, crop } = opts;
1115
+ if (!width && !height && !crop)
1116
+ return src;
1117
+ try {
1118
+ const url = new URL(src, 'https://cdn.tanqory.com');
1119
+ if (width)
1120
+ url.searchParams.set('width', String(width));
1121
+ if (height)
1122
+ url.searchParams.set('height', String(height));
1123
+ if (crop)
1124
+ url.searchParams.set('crop', crop);
1125
+ // Preserve relative URLs (return path+query) vs absolute.
1126
+ return /^https?:\/\//i.test(src) ? url.toString() : `${url.pathname}${url.search}`;
1127
+ }
1128
+ catch {
1129
+ return src;
1130
+ }
1131
+ }