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

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 (210) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +125 -10
  3. package/dist/abi/canvas-live.d.ts +67 -0
  4. package/dist/abi/canvas-live.js +154 -0
  5. package/dist/abi/cart.d.ts +59 -0
  6. package/dist/abi/cart.js +387 -0
  7. package/dist/abi/convert.d.ts +344 -0
  8. package/dist/abi/convert.js +1278 -0
  9. package/dist/abi/data-api.d.ts +15 -0
  10. package/dist/abi/data-api.js +209 -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 +256 -0
  16. package/dist/abi/page-data.js +678 -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 +38 -0
  30. package/dist/abi/wire.js +84 -0
  31. package/dist/build.d.ts +116 -0
  32. package/dist/build.js +310 -0
  33. package/dist/client.d.ts +19 -0
  34. package/dist/client.js +87 -0
  35. package/dist/contract.d.ts +6 -0
  36. package/dist/contract.js +6 -0
  37. package/dist/headless/ai.d.ts +132 -0
  38. package/dist/headless/ai.js +99 -0
  39. package/dist/headless/hooks.d.ts +276 -0
  40. package/dist/headless/hooks.js +540 -0
  41. package/dist/headless/i18n.d.ts +13 -0
  42. package/dist/headless/i18n.js +45 -0
  43. package/dist/headless/index.d.ts +37 -0
  44. package/dist/headless/index.js +38 -0
  45. package/dist/headless/money.d.ts +25 -0
  46. package/dist/headless/money.js +61 -0
  47. package/dist/headless/page.d.ts +43 -0
  48. package/dist/headless/page.js +53 -0
  49. package/dist/headless/platform.d.ts +55 -0
  50. package/dist/headless/platform.js +77 -0
  51. package/dist/headless/primitives/cart.d.ts +90 -0
  52. package/dist/headless/primitives/cart.js +153 -0
  53. package/dist/headless/primitives/collection.d.ts +68 -0
  54. package/dist/headless/primitives/collection.js +80 -0
  55. package/dist/headless/primitives/product.d.ts +101 -0
  56. package/dist/headless/primitives/product.js +117 -0
  57. package/dist/headless/primitives/storefront.d.ts +106 -0
  58. package/dist/headless/primitives/storefront.js +186 -0
  59. package/dist/headless/primitives/util.d.ts +19 -0
  60. package/dist/headless/primitives/util.js +42 -0
  61. package/dist/headless/strings.d.ts +9 -0
  62. package/dist/headless/strings.js +190 -0
  63. package/dist/headless/structured-data.d.ts +31 -0
  64. package/dist/headless/structured-data.js +57 -0
  65. package/dist/headless/theme.d.ts +99 -0
  66. package/dist/headless/theme.js +54 -0
  67. package/dist/index.d.ts +20 -0
  68. package/dist/index.js +18 -553
  69. package/dist/runtime/data/StoreProvider.d.ts +84 -0
  70. package/dist/runtime/data/StoreProvider.js +373 -0
  71. package/dist/runtime/data/handle.d.ts +14 -0
  72. package/dist/runtime/data/handle.js +16 -0
  73. package/dist/runtime/data/routes.d.ts +87 -0
  74. package/dist/runtime/data/routes.js +158 -0
  75. package/dist/runtime/data/to-ui.d.ts +281 -0
  76. package/dist/runtime/data/to-ui.js +977 -0
  77. package/dist/runtime/entries/register.d.ts +9 -0
  78. package/dist/runtime/entries/register.js +9 -0
  79. package/dist/runtime/entries/sections.d.ts +16 -0
  80. package/dist/runtime/entries/sections.js +19 -0
  81. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  82. package/dist/runtime/kit/SectionTree.js +100 -0
  83. package/dist/runtime/kit/analytics.d.ts +63 -0
  84. package/dist/runtime/kit/analytics.js +250 -0
  85. package/dist/runtime/kit/cart.d.ts +215 -0
  86. package/dist/runtime/kit/cart.js +545 -0
  87. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  88. package/dist/runtime/kit/composition.js +3 -0
  89. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  90. package/dist/runtime/kit/config.js +6 -0
  91. package/dist/runtime/kit/consent.d.ts +29 -0
  92. package/dist/runtime/kit/consent.js +159 -0
  93. package/dist/runtime/kit/contract/content.d.ts +199 -0
  94. package/dist/runtime/kit/contract/content.js +106 -0
  95. package/dist/runtime/kit/contract/field-types.d.ts +337 -0
  96. package/dist/runtime/kit/contract/field-types.js +206 -0
  97. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  98. package/dist/runtime/kit/contract/groups.js +402 -0
  99. package/dist/runtime/kit/contract/index.d.ts +33 -0
  100. package/dist/runtime/kit/contract/index.js +33 -0
  101. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  102. package/dist/runtime/kit/contract/transform.js +133 -0
  103. package/dist/runtime/kit/contract/validate.d.ts +75 -0
  104. package/dist/runtime/kit/contract/validate.js +480 -0
  105. package/dist/runtime/kit/data.d.ts +720 -0
  106. package/dist/runtime/kit/data.js +1117 -0
  107. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  108. package/dist/runtime/kit/defineSection.js +10 -0
  109. package/dist/{types → runtime/kit}/dynamic-source.d.ts +40 -18
  110. package/dist/runtime/kit/dynamic-source.js +294 -0
  111. package/dist/runtime/kit/index.d.ts +24 -0
  112. package/dist/runtime/kit/index.js +24 -0
  113. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  114. package/dist/runtime/kit/jsx-to-json.js +28 -0
  115. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  116. package/dist/runtime/kit/mount.js +124 -0
  117. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  118. package/dist/runtime/kit/registry.js +12 -0
  119. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  120. package/dist/runtime/kit/ssg.js +56 -0
  121. package/dist/runtime/kit/storefront.d.ts +639 -0
  122. package/dist/runtime/kit/storefront.js +723 -0
  123. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  124. package/dist/runtime/kit/theme-context.js +25 -0
  125. package/dist/runtime/kit/types.d.ts +147 -0
  126. package/dist/runtime/kit/types.js +1 -0
  127. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  128. package/dist/runtime/platform/TrackingPixels.js +63 -0
  129. package/dist/runtime/platform/environment.d.ts +68 -0
  130. package/dist/runtime/platform/environment.js +85 -0
  131. package/dist/runtime/platform/locale.d.ts +27 -0
  132. package/dist/runtime/platform/locale.js +42 -0
  133. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  134. package/dist/runtime/platform/route-analytics.js +72 -0
  135. package/dist/runtime/platform/safe-href.d.ts +25 -0
  136. package/dist/runtime/platform/safe-href.js +69 -0
  137. package/dist/runtime/platform/safe-values.d.ts +37 -0
  138. package/dist/runtime/platform/safe-values.js +140 -0
  139. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  140. package/dist/runtime/render/SectionRenderer.js +166 -0
  141. package/dist/runtime/render/listing-query.d.ts +52 -0
  142. package/dist/runtime/render/listing-query.js +122 -0
  143. package/dist/runtime/render/localized-copy.d.ts +86 -0
  144. package/dist/runtime/render/localized-copy.js +129 -0
  145. package/dist/runtime/render/product-listing.d.ts +11 -0
  146. package/dist/runtime/render/product-listing.js +243 -0
  147. package/dist/runtime/render/section-actions.d.ts +66 -0
  148. package/dist/runtime/render/section-actions.js +202 -0
  149. package/dist/runtime/render/starter.d.ts +11 -0
  150. package/dist/runtime/render/starter.js +81 -0
  151. package/dist/runtime/seo/head.d.ts +115 -0
  152. package/dist/runtime/seo/head.js +281 -0
  153. package/dist/runtime/seo/structured-data.d.ts +83 -0
  154. package/dist/runtime/seo/structured-data.js +252 -0
  155. package/dist/runtime/shell/PageShell.d.ts +18 -0
  156. package/dist/runtime/shell/PageShell.js +113 -0
  157. package/dist/runtime/shell/RuntimeBridge.d.ts +14 -0
  158. package/dist/runtime/shell/RuntimeBridge.js +93 -0
  159. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  160. package/dist/runtime/shell/overlay-state.js +59 -0
  161. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  162. package/dist/runtime/shell/preview-mode.js +11 -0
  163. package/dist/runtime/shell/spa-router.d.ts +14 -0
  164. package/dist/runtime/shell/spa-router.js +76 -0
  165. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  166. package/dist/runtime/shell/url-redirects.js +37 -0
  167. package/dist/runtime/slots.d.ts +74 -0
  168. package/dist/runtime/slots.js +16 -0
  169. package/dist/runtime.d.ts +34 -0
  170. package/dist/runtime.js +40 -0
  171. package/dist/sdk/app-block.d.ts +29 -0
  172. package/dist/sdk/app-block.js +22 -0
  173. package/dist/sdk/index.d.ts +26 -0
  174. package/dist/sdk/index.js +26 -0
  175. package/dist/sdk/referrals.d.ts +62 -0
  176. package/dist/sdk/referrals.js +20 -0
  177. package/dist/sdk/rewards.d.ts +85 -0
  178. package/dist/sdk/rewards.js +29 -0
  179. package/dist/sdk/runtime-context.d.ts +202 -0
  180. package/dist/sdk/runtime-context.js +73 -0
  181. package/dist/sdk/schema.d.ts +206 -0
  182. package/dist/sdk/schema.js +121 -0
  183. package/dist/sdk/server-render.d.ts +8 -0
  184. package/dist/sdk/server-render.js +12 -0
  185. package/dist/sdk/store-lookup.d.ts +27 -0
  186. package/dist/sdk/store-lookup.js +29 -0
  187. package/dist/sdk/store.d.ts +149 -0
  188. package/dist/sdk/store.js +5 -0
  189. package/dist/sdk/sx.d.ts +40 -0
  190. package/dist/sdk/sx.js +112 -0
  191. package/dist/sdk/theme.d.ts +191 -0
  192. package/dist/sdk/theme.js +10 -0
  193. package/dist/sdk/types.d.ts +757 -0
  194. package/dist/sdk/types.js +7 -0
  195. package/dist/server.d.ts +111 -0
  196. package/dist/server.js +533 -0
  197. package/docs/headless-api.md +220 -0
  198. package/package.json +76 -22
  199. package/dist/index.js.map +0 -1
  200. package/dist/ssg-BZ5FYTw7.js +0 -1802
  201. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  202. package/dist/ssg.js +0 -8
  203. package/dist/ssg.js.map +0 -1
  204. package/dist/types/cart.d.ts +0 -86
  205. package/dist/types/data.d.ts +0 -357
  206. package/dist/types/editor.d.ts +0 -5
  207. package/dist/types/index.d.ts +0 -20
  208. package/dist/types/preview-bridge.d.ts +0 -9
  209. package/dist/types/storefront.d.ts +0 -333
  210. package/dist/types/types.d.ts +0 -44
@@ -0,0 +1,678 @@
1
+ import * as convert from './convert.js';
2
+ import { isBoundSource, resolveBoundSource } from '../runtime/kit/dynamic-source.js';
3
+ import { searchOrder } from './data-api.js';
4
+ import { filterRequests, listingQueryOf, stateFromQuery } from '../runtime/render/listing-query.js';
5
+ /** Hard limits (theme-abi-v2.md §8). The host enforces them; the theme plans inside them. */
6
+ const MAX_DATA_CALLS = 4;
7
+ /** Products per listing request — the page size platform/runtime/render/product-listing.ts asks for. */
8
+ const LISTING_FIRST = 24;
9
+ /** Product tags are the merchant's internal labels, never a shopper filter (product-listing.ts). */
10
+ const HIDDEN_FACETS = new Set(['filter.tag']);
11
+ /**
12
+ * The listing state of this request (`?sort=` and `?filter.*=`, platform/runtime/render/listing-query.ts):
13
+ * only on the collection route. `sort` may also arrive as the ABI's query-derived route param.
14
+ * Cache-safe for the same reason as the search query: a request with a query string is neither served
15
+ * from nor stored in the shared cache (§5.1).
16
+ */
17
+ export function listingQueryOfRequest(ctx) {
18
+ if (ctx.route.kind !== 'collection')
19
+ return '';
20
+ let search;
21
+ try {
22
+ search = new URL(ctx.request.url).searchParams;
23
+ }
24
+ catch {
25
+ search = new URLSearchParams();
26
+ }
27
+ const sort = ctx.route.params['sort'];
28
+ if (typeof sort === 'string' && sort && !search.has('sort'))
29
+ search.set('sort', sort);
30
+ return listingQueryOf(search);
31
+ }
32
+ /** Results per type the search page loads — the same page size sections/SearchResults.tsx asks the browser wire for. */
33
+ const SEARCH_FIRST = 48;
34
+ const normQuery = (q) => q.trim().toLowerCase();
35
+ /**
36
+ * The search query of this request: the `q` route param (theme-abi-v2.md §2.1), else — for a
37
+ * gateway that does not forward it yet — the `q` of the request's own query string. Only on the
38
+ * search route. Shopper-typed text: every place that prints it escapes it (React does).
39
+ * Reading the raw query is cache-safe: a request with any query string is neither served from nor
40
+ * stored in the shared cache (§5.1).
41
+ */
42
+ export function searchQueryOf(ctx) {
43
+ if (ctx.route.kind !== 'search')
44
+ return null;
45
+ const param = ctx.route.params['q'];
46
+ if (typeof param === 'string')
47
+ return param;
48
+ try {
49
+ return new URL(ctx.request.url).searchParams.get('q');
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ }
55
+ /**
56
+ * The search page's sort (`?sort=`, the ABI's query-derived `sort` route param on the search kind):
57
+ * a sort id lib/abi/data-api.ts `searchOrder` knows, else null (relevance). Only on the search route.
58
+ */
59
+ export function searchSortOf(ctx) {
60
+ if (ctx.route.kind !== 'search')
61
+ return null;
62
+ let sort = ctx.route.params['sort'];
63
+ if (typeof sort !== 'string') {
64
+ try {
65
+ sort = new URL(ctx.request.url).searchParams.get('sort') ?? undefined;
66
+ }
67
+ catch {
68
+ sort = undefined;
69
+ }
70
+ }
71
+ return searchOrder(sort) ? sort : null;
72
+ }
73
+ /**
74
+ * The variant a product URL names (`/products/<handle>?variant=<id>`): a shared link, or checkout's way
75
+ * back to the product. Only on the product route; the section opens on it only when it is a variant
76
+ * of that product (ProductDetails ignores any other id). Read from the request's own query string:
77
+ * a request with a query is never served from or stored in the shared cache (§5.1).
78
+ */
79
+ export function variantOf(ctx) {
80
+ if (ctx.route.kind !== 'product')
81
+ return null;
82
+ let v = ctx.route.params['variant'];
83
+ if (typeof v !== 'string') {
84
+ try {
85
+ v = new URL(ctx.request.url).searchParams.get('variant');
86
+ }
87
+ catch {
88
+ v = null;
89
+ }
90
+ }
91
+ const id = typeof v === 'string' ? v.trim() : '';
92
+ return id && id.length <= 200 && /^[A-Za-z0-9_:/.\-]+$/.test(id) ? id : null;
93
+ }
94
+ /** The reasons the platform router sends a cart permalink it could not open to `/cart?cart_link=` with. */
95
+ const CART_LINK_REASONS = new Set(['unavailable', 'failed']);
96
+ /**
97
+ * Why a cart permalink (`/cart/<variant>:<qty>`) landed on the cart page: the router's
98
+ * `?cart_link=` reason (apps/storefront/router/cart-permalink.mjs), else null. Only on the cart
99
+ * route, and only a reason the router sends. The cart route is a private response already (§5).
100
+ */
101
+ export function cartLinkOf(ctx) {
102
+ if (ctx.route.kind !== 'cart')
103
+ return null;
104
+ try {
105
+ const reason = new URL(ctx.request.url).searchParams.get('cart_link');
106
+ return reason && CART_LINK_REASONS.has(reason) ? reason : null;
107
+ }
108
+ catch {
109
+ return null;
110
+ }
111
+ }
112
+ /**
113
+ * The route params the page renders with: the route's own, plus `q` (`searchQueryOf`), its `sort`
114
+ * (`searchSortOf`) and `cart_link` (`cartLinkOf`) when only the request's query string has them.
115
+ * They travel in the page state, so the hydrating browser builds the same location.
116
+ */
117
+ export function pageParamsOf(ctx, searchQuery, searchSort = null) {
118
+ const params = { ...ctx.route.params };
119
+ if (searchQuery !== null && params['q'] === undefined)
120
+ params['q'] = searchQuery;
121
+ // the sort the page was loaded with — the same id the browser's store keys its search on
122
+ if (searchSort !== null && params['sort'] === undefined)
123
+ params['sort'] = searchSort;
124
+ const cartLink = cartLinkOf(ctx);
125
+ if (cartLink !== null)
126
+ params['cart_link'] = cartLink;
127
+ const variant = variantOf(ctx);
128
+ if (variant !== null)
129
+ params['variant'] = variant;
130
+ return params;
131
+ }
132
+ const RESOURCE_KINDS = new Set(['collection', 'product', 'menu', 'page', 'blog']);
133
+ /** Capability each route kind's snapshot resource needs (capability-security §2 / render-context Capability). */
134
+ const RESOURCE_CAPABILITY = {
135
+ product: 'data:catalog', collection: 'data:catalog', collections: 'data:catalog',
136
+ page: 'data:content', blog: 'data:content', article: 'data:content', policy: 'data:content', metaobject: 'data:content',
137
+ search: 'data:search', cart: 'data:cart', customer: 'data:customer',
138
+ };
139
+ /** Capability each round-2 call needs. */
140
+ const NEED_CAPABILITY = {
141
+ collection: 'data:catalog', product: 'data:catalog', page: 'data:content', blog: 'data:content', menu: 'data:shop',
142
+ };
143
+ /** Sections that call `allCollections()`. */
144
+ /** Sections that show recommendations for the route's product. */
145
+ const SHOWS_RECOMMENDATIONS = new Set(['product-recommendations']);
146
+ const LISTS_ALL_COLLECTIONS = new Set(['collection-list', 'collection-links', 'not-found', 'search-results', 'cart-items']);
147
+ function walk(nodes, visit) {
148
+ for (const n of nodes) {
149
+ visit(n);
150
+ if (Array.isArray(n.blocks))
151
+ walk(n.blocks, visit);
152
+ }
153
+ }
154
+ /** Resource settings on this page (effective value = node setting, else the attribute default). */
155
+ export function pageNeeds(nodes, defs) {
156
+ const needs = [];
157
+ /** The menu handles the header shows: when every one is empty the drawer lists the collections instead. */
158
+ const headerMenus = [];
159
+ let listsCollections = false;
160
+ let showsLocale = false;
161
+ let showsAccount = false;
162
+ let showsRecommendations = false;
163
+ walk(nodes, (n) => {
164
+ const def = defs(n.type);
165
+ if (!def)
166
+ return;
167
+ if (LISTS_ALL_COLLECTIONS.has(n.type))
168
+ listsCollections = true;
169
+ if (SHOWS_RECOMMENDATIONS.has(n.type))
170
+ showsRecommendations = true;
171
+ const settings = (n.settings ?? {});
172
+ // The header's locale control and the footer's region control (on by default) both list countries.
173
+ if ((n.type === 'header' || n.type === 'footer') && (settings.showLocale ?? def.attributes?.showLocale?.default) === true)
174
+ showsLocale = true;
175
+ if (n.type === 'header' && (settings.showAccount ?? def.attributes?.showAccount?.default) !== false)
176
+ showsAccount = true;
177
+ for (const [key, spec] of Object.entries(def.attributes ?? {})) {
178
+ if (!RESOURCE_KINDS.has(spec.type))
179
+ continue;
180
+ const value = settings[key] ?? spec.default;
181
+ if (typeof value !== 'string' || !value.trim())
182
+ continue;
183
+ needs.push({ kind: spec.type, handle: value.trim(), ref: `${n.id}.${key}` });
184
+ if (n.type === 'header' && spec.type === 'menu')
185
+ headerMenus.push(value.trim());
186
+ }
187
+ });
188
+ return { needs, listsCollections, showsLocale, showsAccount, showsRecommendations, headerMenus };
189
+ }
190
+ /**
191
+ * Picker settings connected to a dynamic source (E1 slice 3): a product, collection or page setting bound to a
192
+ * metafield of the route's resource or the shop (`{ '@source': 'product.metafields.custom.related' }`) names the
193
+ * handle that metafield holds (the projector writes a reference as `{id, handle}`). Those handles are needs like a
194
+ * saved handle, fetched in round 2. A bound value that resolves to nothing is no need: the setting's default renders.
195
+ */
196
+ export function boundResourceNeeds(nodes, defs, sources) {
197
+ const out = [];
198
+ walk(nodes, (n) => {
199
+ const def = defs(n.type);
200
+ if (!def)
201
+ return;
202
+ const settings = (n.settings ?? {});
203
+ for (const [key, spec] of Object.entries(def.attributes ?? {})) {
204
+ const kind = spec.type;
205
+ if (kind !== 'product' && kind !== 'collection' && kind !== 'page')
206
+ continue;
207
+ const v = settings[key];
208
+ if (!isBoundSource(v))
209
+ continue;
210
+ const handle = (resolveBoundSource(v['@source'], sources) ?? '').trim();
211
+ if (handle && !handle.startsWith('gid://') && !handle.includes(','))
212
+ out.push({ kind, handle, ref: `${n.id}.${key}` });
213
+ }
214
+ });
215
+ return out;
216
+ }
217
+ function languageName(code, inLanguage) {
218
+ try {
219
+ return new Intl.DisplayNames([inLanguage], { type: 'language' }).of(code) ?? code;
220
+ }
221
+ catch {
222
+ return code;
223
+ }
224
+ }
225
+ function intlRegionName(code, inLanguage) {
226
+ try {
227
+ return new Intl.DisplayNames([inLanguage], { type: 'region' }).of(code) ?? code;
228
+ }
229
+ catch {
230
+ return code;
231
+ }
232
+ }
233
+ /**
234
+ * `ctx.locale` → Nova's Localization. `locale.country` is a personalising input (§2): it is read
235
+ * only when the page shows the country switcher, and the caller hints `vary: ['x-tq-country']`
236
+ * for exactly that case. Otherwise the country stays blank and nothing on the page depends on it.
237
+ */
238
+ export function localizationOf(ctx, shipsTo, readCountry) {
239
+ const lang = ctx.locale.language;
240
+ const currency = { isoCode: ctx.locale.currency };
241
+ const market = { id: ctx.locale.market, handle: ctx.locale.market, name: ctx.locale.market };
242
+ const country = readCountry ? ctx.locale.country : '';
243
+ const languages = [...new Set(ctx.locale.availableLanguages)];
244
+ // theme-abi Locale-2: the platform's CLDR names in the page's language, when it sends them. The isolate's own
245
+ // Intl.DisplayNames has no data for some languages (Burmese: English names), so it is only the fallback.
246
+ const names = displayNamesOf(ctx);
247
+ const language = (l) => {
248
+ const n = names?.languages[l];
249
+ return n ? { isoCode: l, name: n.name, endonymName: n.endonymName } : { isoCode: l, name: languageName(l, l) };
250
+ };
251
+ const regionName = (iso, inLanguage) => names?.countries[iso] ?? intlRegionName(iso, inLanguage);
252
+ // The store's active markets, when the platform names them (`ctx.locale.markets`, optional): each
253
+ // country gets its own market, currency and languages. Absent ⇒ one market for every country.
254
+ const byCountry = new Map();
255
+ for (const m of marketsOf(ctx)) {
256
+ const own = { id: m.id, handle: m.id, name: m.id };
257
+ const langs = [...new Set(m.languages)].filter((l) => languages.length === 0 || languages.includes(l));
258
+ for (const c of m.countries) {
259
+ const iso = c.toUpperCase();
260
+ if (!/^[A-Z]{2}$/.test(iso) || byCountry.has(iso))
261
+ continue;
262
+ byCountry.set(iso, { isoCode: iso, name: regionName(iso, lang), currency: { isoCode: m.currency }, market: own, ...(langs.length ? { availableLanguages: langs.map(language) } : {}) });
263
+ }
264
+ }
265
+ const countryOf = (c) => byCountry.get(c) ?? { isoCode: c, name: c ? regionName(c, lang) : '', currency, market };
266
+ const countries = byCountry.size ? [...byCountry.keys()] : shipsTo;
267
+ return {
268
+ country: country ? countryOf(country) : { isoCode: '', name: '', currency, market },
269
+ availableCountries: readCountry ? countries.map(countryOf) : [],
270
+ language: language(lang),
271
+ availableLanguages: languages.map(language),
272
+ };
273
+ }
274
+ /** `ctx.locale.displayNames` (theme-abi Locale-2, optional), read defensively: only string names; null when absent. */
275
+ export function displayNamesOf(ctx) {
276
+ const raw = ctx.locale.displayNames;
277
+ if (!raw || typeof raw !== 'object')
278
+ return null;
279
+ const countries = {};
280
+ const languages = {};
281
+ if (raw.countries && typeof raw.countries === 'object') {
282
+ for (const [k, v] of Object.entries(raw.countries))
283
+ if (/^[A-Z]{2}$/.test(k) && typeof v === 'string' && v)
284
+ countries[k] = v;
285
+ }
286
+ if (raw.languages && typeof raw.languages === 'object') {
287
+ for (const [k, v] of Object.entries(raw.languages)) {
288
+ const n = v;
289
+ if (n && typeof n.name === 'string' && n.name && typeof n.endonymName === 'string' && n.endonymName)
290
+ languages[k] = { name: n.name, endonymName: n.endonymName };
291
+ }
292
+ }
293
+ return { countries, languages };
294
+ }
295
+ /** `ctx.locale.markets`, read defensively: only well-formed entries; [] when the platform sends none. */
296
+ export function marketsOf(ctx) {
297
+ const raw = ctx.locale.markets;
298
+ if (!Array.isArray(raw))
299
+ return [];
300
+ const strings = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x.length > 0) : []);
301
+ return raw.flatMap((m) => {
302
+ const r = m;
303
+ if (!r || typeof r.id !== 'string' || !r.id || typeof r.currency !== 'string' || !/^[A-Z]{3}$/.test(r.currency))
304
+ return [];
305
+ return [{ id: r.id, currency: r.currency, countries: strings(r.countries), languages: strings(r.languages) }];
306
+ });
307
+ }
308
+ /** Load a page's data through `ctx.data`. */
309
+ export async function loadPageData(ctx, nodes, defs,
310
+ /** Menu handles named by GLOBAL settings (header/footer menu pickers), not by a node. */
311
+ settingMenus = [],
312
+ /**
313
+ * The search query this page renders (`searchQueryOf`). When the snapshot answered a different
314
+ * query — a gateway that does not forward `q` as a route param answers the empty one — the
315
+ * search is run once in round 2, so the server HTML holds the results the browser would show.
316
+ */
317
+ searchQuery = null,
318
+ /** The search sort of this request (`searchSortOf`); null = relevance. */
319
+ searchSort = null,
320
+ /** The collection listing's URL state (`listingQueryOfRequest`); '' = none. */
321
+ listingQuery = '',
322
+ /**
323
+ * What the theme asks the plan for regardless of its section types (`RenderOptions.storefront.plan`), and the
324
+ * data calls the caller makes beside this plan in round 1 (`reservedCalls`). Absent: the plan reads only the
325
+ * section conventions (`pageNeeds`), exactly as before.
326
+ */
327
+ plan) {
328
+ const found = pageNeeds(nodes, defs);
329
+ const { needs, headerMenus } = found;
330
+ const listsAll = found.listsCollections || plan?.collections === true;
331
+ const showsLocale = found.showsLocale || plan?.localization === true;
332
+ const showsAccount = found.showsAccount || plan?.account === true;
333
+ const showsRecommendations = found.showsRecommendations || plan?.recommendations === true;
334
+ for (const handle of settingMenus)
335
+ needs.push({ kind: 'menu', handle, ref: `settings.${handle}` });
336
+ let calls = plan?.reservedCalls ?? 0;
337
+ const can = (cap) => ctx.capabilities.has(cap);
338
+ // §3 (rev 2026-10-07, IA-2): snapshot() never throws for a denied capability — the resource comes
339
+ // back null and `denied` names the capability. Hosts built before that revision (conformance
340
+ // runner 1966cca among them) still throw, so when the route's resource capability is not in
341
+ // ctx.capabilities Nova does not ask for it at all: shop + menus in one round, and the template
342
+ // renders its "nothing here" state. Either way nothing outside the grant is ever called.
343
+ const resourceCap = RESOURCE_CAPABILITY[ctx.route.kind];
344
+ let snapshot;
345
+ if (!resourceCap || can(resourceCap)) {
346
+ calls++;
347
+ // Opt-in answers (Theme ABI, storefront-query rev 2.19): the collection page's facets, and the
348
+ // product page's collections (its breadcrumb). Asked for only on the route that shows them.
349
+ const optIn = ctx.route.kind === 'collection' ? { facets: true } : ctx.route.kind === 'product' ? { productCollections: true } : {};
350
+ // `policyLinks` (theme-abi alpha.14): the store's published policies on every page — the footer lists
351
+ // them when its legal menu is empty, and the cookie banner links the privacy policy only when published.
352
+ // `reviewsFirst` (storefront-query rev 2.38, NEW-PROD-10): the product page's newest published reviews.
353
+ // A data plane from before either member refuses an unknown option (strict `opts`): ask again without the
354
+ // newest member, then without both, and the page keeps the older behaviour (no review list; no policy links).
355
+ const ask = (extra) => ctx.data.snapshot({ resolve: 'all', ...optIn, ...extra });
356
+ const attempts = ctx.route.kind === 'product' ? [{ policyLinks: true, reviewsFirst: convert.REVIEWS_FIRST }, { policyLinks: true }, {}] : [{ policyLinks: true }, {}];
357
+ let answered = null;
358
+ for (const [i, extra] of attempts.entries()) {
359
+ try {
360
+ answered = await ask(extra);
361
+ break;
362
+ }
363
+ catch (e) {
364
+ const name = e?.name;
365
+ if (name === 'DataLimitError' || name === 'CapabilityError' || i === attempts.length - 1)
366
+ throw e;
367
+ calls++;
368
+ }
369
+ }
370
+ snapshot = answered;
371
+ }
372
+ else {
373
+ calls += 2;
374
+ const [shopRecord, menuList] = await Promise.all([ctx.data.shop.get(), ctx.data.shop.menus()]);
375
+ snapshot = {
376
+ shop: shopRecord,
377
+ menus: Object.fromEntries(menuList.map((m) => [m.handle, m])),
378
+ resource: { kind: 'not_found' },
379
+ refs: {},
380
+ pixels: [],
381
+ };
382
+ }
383
+ const products = {};
384
+ const collections = {};
385
+ const pages = {};
386
+ const blogs = {};
387
+ const articles = {};
388
+ const menus = {};
389
+ const policies = [];
390
+ let collectionList = null;
391
+ let search = null;
392
+ let policyHandle = null;
393
+ let cart = null;
394
+ let metaobject = null;
395
+ for (const m of Object.values(snapshot.menus ?? {}))
396
+ menus[m.handle] = convert.menu(m);
397
+ const putProduct = (p) => { if (p)
398
+ products[p.handle] = convert.product(p); };
399
+ const putCollection = (c) => {
400
+ if (!c)
401
+ return;
402
+ const nc = convert.collection(c);
403
+ collections[c.handle] = nc;
404
+ for (const p of c.products?.nodes ?? [])
405
+ if (!products[p.handle])
406
+ products[p.handle] = convert.product(p);
407
+ };
408
+ // A `catalog.collections()` entry is a CARD: the platform sends it with an empty product page
409
+ // (`products.nodes: []`, the real `totalCount`). It must never replace a collection a section
410
+ // loaded with its products — that emptied the featured collection on every page that also lists
411
+ // collections (home with a collection list, the cart), and the section then rendered nothing.
412
+ const putCard = (c) => { if (!collections[c.handle])
413
+ collections[c.handle] = convert.collection(c); };
414
+ /** A listed card answers a collection need only when it carries the products (or there are none). */
415
+ const cardAnswers = (handle) => collectionList?.some((c) => c.handle === handle && ((c.products?.length ?? 0) > 0 || c.productsCount === 0)) ?? false;
416
+ const putPage = (p) => { if (p)
417
+ pages[p.handle] = convert.page(p); };
418
+ const putBlog = (b) => {
419
+ if (!b)
420
+ return;
421
+ blogs[b.handle] = convert.blog(b);
422
+ for (const a of b.articles?.nodes ?? [])
423
+ articles[`${b.handle}/${a.handle}`] = { ...convert.article(a), blogHandle: b.handle };
424
+ };
425
+ const putArticle = (a, blogHandle) => { if (a)
426
+ articles[`${blogHandle}/${a.handle}`] = { ...convert.article(a), blogHandle }; };
427
+ const r = snapshot.resource;
428
+ switch (r.kind) {
429
+ case 'product':
430
+ putProduct(r.product);
431
+ break;
432
+ case 'collection':
433
+ putCollection(r.collection);
434
+ break;
435
+ case 'collections':
436
+ if (r.collections) {
437
+ collectionList = r.collections.nodes.map(convert.collection);
438
+ r.collections.nodes.forEach(putCard);
439
+ }
440
+ break;
441
+ case 'page':
442
+ putPage(r.page);
443
+ break;
444
+ case 'blog':
445
+ putBlog(r.blog);
446
+ break;
447
+ case 'article':
448
+ putBlog(r.blog);
449
+ if (r.article)
450
+ putArticle(r.article, r.blog?.handle ?? ctx.route.blogHandle ?? '');
451
+ break;
452
+ case 'policy':
453
+ if (r.policy) {
454
+ policies.push(r.policy);
455
+ policyHandle = r.policy.handle;
456
+ }
457
+ break;
458
+ case 'metaobject':
459
+ metaobject = metaobjectPageOf(r.metaobject, ctx.route.handle);
460
+ break;
461
+ // The snapshot applies the route's `sort` param (rev 2.19). When the sort came only from the URL (a gateway
462
+ // that does not forward it), the snapshot's order is relevance: it is not used, and round 2 asks for the sort.
463
+ case 'search':
464
+ if (r.result && (!searchSort || typeof ctx.route.params['sort'] === 'string')) {
465
+ search = { query: r.result.query, ...(searchSort ? { sort: searchSort } : {}), result: convert.searchResults(r.result) };
466
+ r.result.products.nodes.forEach(putProduct);
467
+ }
468
+ break;
469
+ case 'cart':
470
+ cart = r.cart;
471
+ break;
472
+ default: break;
473
+ }
474
+ // Picker settings bound to a metafield of the route's resource or the shop: their handles join the needs.
475
+ const routeSources = {
476
+ shop: { ...snapshot.shop, ...convert.metafieldsOf(snapshot.shop) },
477
+ ...(r.kind === 'product' && r.product ? { product: products[r.product.handle] } : {}),
478
+ ...(r.kind === 'collection' && r.collection ? { collection: collections[r.collection.handle] } : {}),
479
+ ...(r.kind === 'page' && r.page ? { page: pages[r.page.handle] } : {}),
480
+ ...(metaobject ? { metaobjectPage: metaobject } : {}),
481
+ };
482
+ for (const b of boundResourceNeeds(nodes, defs, routeSources))
483
+ needs.push(b);
484
+ // refs the platform resolved (`${nodeId}.${settingKey}`)
485
+ const missing = [];
486
+ for (const need of needs) {
487
+ if (need.kind === 'menu' && menus[need.handle])
488
+ continue;
489
+ const has = Object.prototype.hasOwnProperty.call(snapshot.refs ?? {}, need.ref);
490
+ if (has) {
491
+ const v = snapshot.refs[need.ref];
492
+ if (v && need.kind === 'collection')
493
+ putCollection(v);
494
+ else if (v && need.kind === 'product')
495
+ putProduct(v);
496
+ else if (v && need.kind === 'menu')
497
+ menus[need.handle] = convert.menu(v);
498
+ else if (v && need.kind === 'page')
499
+ putPage(v);
500
+ else if (v && need.kind === 'blog')
501
+ putBlog(v);
502
+ continue;
503
+ }
504
+ if (need.kind === 'collection' && collections[need.handle])
505
+ continue;
506
+ if (need.kind === 'product' && products[need.handle])
507
+ continue;
508
+ if (need.kind === 'page' && pages[need.handle])
509
+ continue;
510
+ if (need.kind === 'blog' && blogs[need.handle])
511
+ continue;
512
+ if (!missing.some((m) => m.kind === need.kind && m.handle === need.handle))
513
+ missing.push(need);
514
+ }
515
+ // A header whose menu has no items (a new store's empty `main-menu`) lists the store's collections in
516
+ // its mobile drawer, so they are loaded too. Decided on what round 1 answered: a menu it did not
517
+ // answer is fetched in round 2 alongside, and may well be empty.
518
+ const headerMenuEmpty = headerMenus.length > 0 && headerMenus.every((h) => !(menus[h]?.items?.length));
519
+ const listsCollections = listsAll || headerMenuEmpty;
520
+ // round 2 — started together (one round), never past the hard call limit
521
+ const round = [];
522
+ const unresolved = [];
523
+ const take = () => (calls < MAX_DATA_CALLS ? (calls++, true) : false);
524
+ const missingMenus = missing.filter((m) => m.kind === 'menu').map((m) => m.handle);
525
+ if (missingMenus.length) {
526
+ if (take())
527
+ round.push(ctx.data.shop.menus(missingMenus).then((list) => { for (const m of list)
528
+ menus[m.handle] = convert.menu(m); }));
529
+ else
530
+ unresolved.push(...missingMenus.map((h) => `menu:${h}`));
531
+ }
532
+ const wantQuery = ctx.route.kind === 'search' ? (searchQuery ?? '').trim() : '';
533
+ const order = searchOrder(searchSort);
534
+ if (wantQuery && normQuery(search?.query ?? '') !== normQuery(wantQuery) && can('data:search')) {
535
+ if (take()) {
536
+ round.push(ctx.data.catalog.search({ query: wantQuery, first: SEARCH_FIRST, types: ['product', 'page', 'article'], ...(order ? { sortKey: order.sortKey, ...(order.reverse ? { reverse: true } : {}) } : {}) }).then((r) => {
537
+ // Keyed by the query (and sort) the page asked for, so `searchSync(q, sort)` matches on server and browser alike.
538
+ search = { query: wantQuery, ...(searchSort ? { sort: searchSort } : {}), result: convert.searchResults(r) };
539
+ r.products.nodes.forEach(putProduct);
540
+ }).catch((e) => {
541
+ // A breach or a missing capability is the host's to report (entry.abi.tsx). Anything else —
542
+ // a shopper query the data plane refuses (over 1,024 code units ⇒ invalid_argument) — must
543
+ // not take the page down: the search renders its "no results" state. The empty answer is
544
+ // recorded for this query so the browser's first render is the same "no results", not a
545
+ // skeleton that differs from the server HTML.
546
+ const name = e?.name;
547
+ if (name === 'DataLimitError' || name === 'CapabilityError')
548
+ throw e;
549
+ ctx.log.warn('page data: search unavailable', { error: String(e?.message ?? e) });
550
+ const none = { nodes: [], pageInfo: { hasNextPage: false } };
551
+ search = { query: wantQuery, ...(searchSort ? { sort: searchSort } : {}), result: convert.searchResults({ query: wantQuery, products: none, pages: none, articles: none, collections: none }) };
552
+ }));
553
+ }
554
+ else
555
+ unresolved.push('search');
556
+ }
557
+ // A shared filtered collection URL: the first filtered page, when one request answers it.
558
+ let listingSeed = null;
559
+ const listed = ctx.route.kind === 'collection' && ctx.route.handle ? collections[ctx.route.handle] : undefined;
560
+ if (listingQuery && listed && can('data:catalog')) {
561
+ const facets = (listed.filters ?? []).filter((f) => !HIDDEN_FACETS.has(f.id));
562
+ const requests = filterRequests(stateFromQuery(listingQuery, facets), facets, 2);
563
+ const only = requests.length === 1 ? requests[0] : null;
564
+ const filters = only ? convert.abiFilters(only) : [];
565
+ if (only && filters.length) {
566
+ const handle = listed.handle;
567
+ if (take()) {
568
+ round.push(ctx.data.catalog.collection(handle, { productsFirst: LISTING_FIRST, filters }).then((c) => {
569
+ if (!c)
570
+ return;
571
+ listingSeed = { handle, key: JSON.stringify(only), products: (c.products?.nodes ?? []).map(convert.product), pageInfo: { hasNextPage: Boolean(c.products?.pageInfo?.hasNextPage), endCursor: c.products?.pageInfo?.endCursor ?? null } };
572
+ }));
573
+ }
574
+ else
575
+ unresolved.push(`listing:${handle}`);
576
+ }
577
+ }
578
+ const recommendations = {};
579
+ const recFor = ctx.route.kind === 'product' ? ctx.route.handle : undefined;
580
+ if (showsRecommendations && recFor && products[recFor] && can('data:products.recommendations')) {
581
+ if (take())
582
+ round.push(ctx.data.catalog.recommendations(recFor, 'related', 8).then((list) => { recommendations[recFor] = list.map(convert.product); }));
583
+ else
584
+ unresolved.push(`recommendations:${recFor}`);
585
+ }
586
+ if (listsCollections && !collectionList && can('data:catalog')) {
587
+ if (take())
588
+ round.push(ctx.data.catalog.collections({ first: 50 }).then((c) => { collectionList = c.nodes.map(convert.collection); c.nodes.forEach(putCard); }));
589
+ else
590
+ unresolved.push('collections');
591
+ }
592
+ for (const need of missing) {
593
+ if (need.kind === 'menu')
594
+ continue;
595
+ if (need.kind === 'collection' && cardAnswers(need.handle))
596
+ continue;
597
+ const call = need.kind === 'collection' ? () => ctx.data.catalog.collection(need.handle).then(putCollection)
598
+ : need.kind === 'product' ? () => ctx.data.catalog.product(need.handle).then(putProduct)
599
+ : need.kind === 'page' ? () => ctx.data.content.page(need.handle).then(putPage)
600
+ : () => ctx.data.content.blog(need.handle).then(putBlog);
601
+ if (!can(NEED_CAPABILITY[need.kind]))
602
+ unresolved.push(`${need.kind}:${need.handle}`);
603
+ else if (take())
604
+ round.push(call());
605
+ else
606
+ unresolved.push(`${need.kind}:${need.handle}`);
607
+ }
608
+ if (round.length)
609
+ await Promise.all(round);
610
+ const denied = snapshot.denied ?? [];
611
+ if (denied.length)
612
+ ctx.log.info('page data: capabilities denied by the store grant', { denied });
613
+ if (unresolved.length)
614
+ ctx.log.warn('page data: resources left unresolved inside the data-call limit', { unresolved });
615
+ return {
616
+ route: ctx.route.kind,
617
+ shop: convert.shop(snapshot.shop, policies, ctx.locale.country ?? ''),
618
+ menus,
619
+ products,
620
+ collections,
621
+ collectionList,
622
+ pages,
623
+ blogs,
624
+ articles,
625
+ ...(ctx.route.kind === 'metaobject' ? { metaobject } : {}),
626
+ search,
627
+ listingSeed,
628
+ recommendations,
629
+ policyHandle,
630
+ accountUrls: ctx.route.kind === 'customer'
631
+ ? { orders: ctx.data.customer.accountUrl('orders'), addresses: ctx.data.customer.accountUrl('addresses'), profile: ctx.data.customer.accountUrl('profile') }
632
+ : null,
633
+ cart,
634
+ localization: localizationOf(ctx, snapshot.shop.shipsToCountries ?? [], showsLocale),
635
+ // A personalising input (§2): read only when the account menu renders; the caller varies on it.
636
+ signedIn: showsAccount ? ctx.request.isSignedIn : null,
637
+ unresolved,
638
+ routeMissing: routeMissingOf(ctx.route, { products, collections, pages, blogs, articles, policies, metaobject }),
639
+ };
640
+ }
641
+ /**
642
+ * The snapshot's entry of a metaobject page → the record dynamic sources read (`metaobject.<field>`). `routeHandle` is
643
+ * the platform's `route.handle`, `<definition url handle>/<entry handle>`: the definition's half names the page's URL.
644
+ * Exported for tests.
645
+ */
646
+ export function metaobjectPageOf(m, routeHandle) {
647
+ if (!m || typeof m.handle !== 'string' || typeof m.type !== 'string')
648
+ return null;
649
+ const cut = typeof routeHandle === 'string' ? routeHandle.indexOf('/') : -1;
650
+ const definitionHandle = cut > 0 ? routeHandle.slice(0, cut) : '';
651
+ const fields = m.fields && typeof m.fields === 'object' && !Array.isArray(m.fields) ? m.fields : {};
652
+ // storefront-query rev 2.62: `Metaobject.seo` — strings kept, anything else dropped
653
+ const s = m.seo && typeof m.seo === 'object' && !Array.isArray(m.seo) ? m.seo : null;
654
+ const seo = s ? { title: typeof s['title'] === 'string' ? s['title'] : null, description: typeof s['description'] === 'string' ? s['description'] : null } : null;
655
+ return { handle: m.handle, type: m.type, definitionHandle, url: definitionHandle ? `/pages/${encodeURIComponent(definitionHandle)}/${encodeURIComponent(m.handle)}` : '', fields, ...(seo && (seo.title || seo.description) ? { seo } : {}) };
656
+ }
657
+ /** An unknown (or not yet published) resource on a resource route is a real 404. Exported for tests. */
658
+ export function routeMissingOf(route, found) {
659
+ const h = route.handle;
660
+ if (!h)
661
+ return false;
662
+ switch (route.kind) {
663
+ case 'product': return !found.products[h];
664
+ case 'collection': return !found.collections[h];
665
+ case 'page': return !found.pages[h];
666
+ case 'blog': return !found.blogs[h];
667
+ // Articles are keyed `<blog>/<article>`; without the blog handle any article with this handle counts.
668
+ case 'article': {
669
+ const blog = route.blogHandle;
670
+ return blog ? !found.articles[`${blog}/${h}`] : !Object.values(found.articles).some((a) => a?.handle === h);
671
+ }
672
+ // The snapshot answers a policy route with the store's PUBLISHED policy for the handle, else null.
673
+ case 'policy': return found.policies.length === 0;
674
+ // A metaobject page: the snapshot answers the entry of the route's definition and handle, else null.
675
+ case 'metaobject': return !found.metaobject;
676
+ default: return false;
677
+ }
678
+ }