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

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 (202) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -10
  3. package/dist/abi/canvas-live.d.ts +49 -0
  4. package/dist/abi/canvas-live.js +88 -0
  5. package/dist/abi/cart.d.ts +48 -0
  6. package/dist/abi/cart.js +256 -0
  7. package/dist/abi/convert.d.ts +126 -0
  8. package/dist/abi/convert.js +493 -0
  9. package/dist/abi/data-api.d.ts +11 -0
  10. package/dist/abi/data-api.js +178 -0
  11. package/dist/abi/jcs.d.ts +6 -0
  12. package/dist/abi/jcs.js +28 -0
  13. package/dist/abi/page-data.d.ts +198 -0
  14. package/dist/abi/page-data.js +577 -0
  15. package/dist/abi/page.d.ts +23 -0
  16. package/dist/abi/page.js +46 -0
  17. package/dist/abi/referrals.d.ts +23 -0
  18. package/dist/abi/referrals.js +89 -0
  19. package/dist/abi/rewards.d.ts +27 -0
  20. package/dist/abi/rewards.js +82 -0
  21. package/dist/abi/seo.d.ts +47 -0
  22. package/dist/abi/seo.js +68 -0
  23. package/dist/abi/shell.d.ts +22 -0
  24. package/dist/abi/shell.js +10 -0
  25. package/dist/abi/wire.d.ts +38 -0
  26. package/dist/abi/wire.js +84 -0
  27. package/dist/build.d.ts +113 -0
  28. package/dist/build.js +294 -0
  29. package/dist/client.d.ts +19 -0
  30. package/dist/client.js +76 -0
  31. package/dist/contract.d.ts +6 -0
  32. package/dist/contract.js +6 -0
  33. package/dist/headless/ai.d.ts +132 -0
  34. package/dist/headless/ai.js +99 -0
  35. package/dist/headless/hooks.d.ts +273 -0
  36. package/dist/headless/hooks.js +533 -0
  37. package/dist/headless/i18n.d.ts +13 -0
  38. package/dist/headless/i18n.js +45 -0
  39. package/dist/headless/index.d.ts +36 -0
  40. package/dist/headless/index.js +38 -0
  41. package/dist/headless/money.d.ts +25 -0
  42. package/dist/headless/money.js +61 -0
  43. package/dist/headless/page.d.ts +43 -0
  44. package/dist/headless/page.js +53 -0
  45. package/dist/headless/platform.d.ts +55 -0
  46. package/dist/headless/platform.js +77 -0
  47. package/dist/headless/primitives/cart.d.ts +90 -0
  48. package/dist/headless/primitives/cart.js +153 -0
  49. package/dist/headless/primitives/collection.d.ts +68 -0
  50. package/dist/headless/primitives/collection.js +80 -0
  51. package/dist/headless/primitives/product.d.ts +101 -0
  52. package/dist/headless/primitives/product.js +117 -0
  53. package/dist/headless/primitives/storefront.d.ts +106 -0
  54. package/dist/headless/primitives/storefront.js +186 -0
  55. package/dist/headless/primitives/util.d.ts +19 -0
  56. package/dist/headless/primitives/util.js +42 -0
  57. package/dist/headless/strings.d.ts +9 -0
  58. package/dist/headless/strings.js +186 -0
  59. package/dist/headless/structured-data.d.ts +31 -0
  60. package/dist/headless/structured-data.js +57 -0
  61. package/dist/headless/theme.d.ts +99 -0
  62. package/dist/headless/theme.js +54 -0
  63. package/dist/index.d.ts +20 -0
  64. package/dist/index.js +18 -553
  65. package/dist/runtime/data/StoreProvider.d.ts +56 -0
  66. package/dist/runtime/data/StoreProvider.js +308 -0
  67. package/dist/runtime/data/handle.d.ts +14 -0
  68. package/dist/runtime/data/handle.js +16 -0
  69. package/dist/runtime/data/routes.d.ts +87 -0
  70. package/dist/runtime/data/routes.js +154 -0
  71. package/dist/runtime/data/to-ui.d.ts +237 -0
  72. package/dist/runtime/data/to-ui.js +759 -0
  73. package/dist/runtime/entries/register.d.ts +9 -0
  74. package/dist/runtime/entries/register.js +9 -0
  75. package/dist/runtime/entries/sections.d.ts +16 -0
  76. package/dist/runtime/entries/sections.js +19 -0
  77. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  78. package/dist/runtime/kit/SectionTree.js +100 -0
  79. package/dist/runtime/kit/analytics.d.ts +63 -0
  80. package/dist/runtime/kit/analytics.js +233 -0
  81. package/dist/runtime/kit/cart.d.ts +167 -0
  82. package/dist/runtime/kit/cart.js +544 -0
  83. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  84. package/dist/runtime/kit/composition.js +3 -0
  85. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  86. package/dist/runtime/kit/config.js +6 -0
  87. package/dist/runtime/kit/consent.d.ts +29 -0
  88. package/dist/runtime/kit/consent.js +159 -0
  89. package/dist/runtime/kit/contract/content.d.ts +164 -0
  90. package/dist/runtime/kit/contract/content.js +83 -0
  91. package/dist/runtime/kit/contract/field-types.d.ts +290 -0
  92. package/dist/runtime/kit/contract/field-types.js +129 -0
  93. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  94. package/dist/runtime/kit/contract/groups.js +402 -0
  95. package/dist/runtime/kit/contract/index.d.ts +33 -0
  96. package/dist/runtime/kit/contract/index.js +33 -0
  97. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  98. package/dist/runtime/kit/contract/transform.js +133 -0
  99. package/dist/runtime/kit/contract/validate.d.ts +67 -0
  100. package/dist/runtime/kit/contract/validate.js +388 -0
  101. package/dist/{types → runtime/kit}/data.d.ts +276 -7
  102. package/dist/runtime/kit/data.js +1117 -0
  103. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  104. package/dist/runtime/kit/defineSection.js +10 -0
  105. package/dist/{types → runtime/kit}/dynamic-source.d.ts +4 -4
  106. package/dist/runtime/kit/dynamic-source.js +143 -0
  107. package/dist/runtime/kit/index.d.ts +24 -0
  108. package/dist/runtime/kit/index.js +24 -0
  109. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  110. package/dist/runtime/kit/jsx-to-json.js +28 -0
  111. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  112. package/dist/runtime/kit/mount.js +124 -0
  113. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  114. package/dist/runtime/kit/registry.js +12 -0
  115. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  116. package/dist/runtime/kit/ssg.js +56 -0
  117. package/dist/{types → runtime/kit}/storefront.d.ts +206 -7
  118. package/dist/runtime/kit/storefront.js +723 -0
  119. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  120. package/dist/runtime/kit/theme-context.js +25 -0
  121. package/dist/runtime/kit/types.d.ts +142 -0
  122. package/dist/runtime/kit/types.js +1 -0
  123. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  124. package/dist/runtime/platform/TrackingPixels.js +63 -0
  125. package/dist/runtime/platform/environment.d.ts +68 -0
  126. package/dist/runtime/platform/environment.js +85 -0
  127. package/dist/runtime/platform/locale.d.ts +27 -0
  128. package/dist/runtime/platform/locale.js +42 -0
  129. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  130. package/dist/runtime/platform/route-analytics.js +72 -0
  131. package/dist/runtime/platform/safe-href.d.ts +25 -0
  132. package/dist/runtime/platform/safe-href.js +69 -0
  133. package/dist/runtime/platform/safe-values.d.ts +37 -0
  134. package/dist/runtime/platform/safe-values.js +140 -0
  135. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  136. package/dist/runtime/render/SectionRenderer.js +111 -0
  137. package/dist/runtime/render/listing-query.d.ts +47 -0
  138. package/dist/runtime/render/listing-query.js +114 -0
  139. package/dist/runtime/render/localized-copy.d.ts +86 -0
  140. package/dist/runtime/render/localized-copy.js +129 -0
  141. package/dist/runtime/render/product-listing.d.ts +11 -0
  142. package/dist/runtime/render/product-listing.js +240 -0
  143. package/dist/runtime/render/section-actions.d.ts +44 -0
  144. package/dist/runtime/render/section-actions.js +169 -0
  145. package/dist/runtime/render/starter.d.ts +11 -0
  146. package/dist/runtime/render/starter.js +81 -0
  147. package/dist/runtime/seo/head.d.ts +87 -0
  148. package/dist/runtime/seo/head.js +224 -0
  149. package/dist/runtime/seo/structured-data.d.ts +22 -0
  150. package/dist/runtime/seo/structured-data.js +115 -0
  151. package/dist/runtime/shell/PageShell.d.ts +18 -0
  152. package/dist/runtime/shell/PageShell.js +113 -0
  153. package/dist/runtime/shell/RuntimeBridge.d.ts +14 -0
  154. package/dist/runtime/shell/RuntimeBridge.js +82 -0
  155. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  156. package/dist/runtime/shell/overlay-state.js +59 -0
  157. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  158. package/dist/runtime/shell/preview-mode.js +11 -0
  159. package/dist/runtime/shell/spa-router.d.ts +14 -0
  160. package/dist/runtime/shell/spa-router.js +76 -0
  161. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  162. package/dist/runtime/shell/url-redirects.js +37 -0
  163. package/dist/runtime/slots.d.ts +74 -0
  164. package/dist/runtime/slots.js +16 -0
  165. package/dist/runtime.d.ts +34 -0
  166. package/dist/runtime.js +40 -0
  167. package/dist/sdk/index.d.ts +24 -0
  168. package/dist/sdk/index.js +24 -0
  169. package/dist/sdk/referrals.d.ts +62 -0
  170. package/dist/sdk/referrals.js +20 -0
  171. package/dist/sdk/rewards.d.ts +85 -0
  172. package/dist/sdk/rewards.js +29 -0
  173. package/dist/sdk/runtime-context.d.ts +120 -0
  174. package/dist/sdk/runtime-context.js +73 -0
  175. package/dist/sdk/schema.d.ts +197 -0
  176. package/dist/sdk/schema.js +121 -0
  177. package/dist/sdk/server-render.d.ts +8 -0
  178. package/dist/sdk/server-render.js +12 -0
  179. package/dist/sdk/store-lookup.d.ts +27 -0
  180. package/dist/sdk/store-lookup.js +29 -0
  181. package/dist/sdk/store.d.ts +115 -0
  182. package/dist/sdk/store.js +1 -0
  183. package/dist/sdk/sx.d.ts +40 -0
  184. package/dist/sdk/sx.js +112 -0
  185. package/dist/sdk/theme.d.ts +152 -0
  186. package/dist/sdk/theme.js +10 -0
  187. package/dist/sdk/types.d.ts +395 -0
  188. package/dist/sdk/types.js +7 -0
  189. package/dist/server.d.ts +65 -0
  190. package/dist/server.js +370 -0
  191. package/docs/headless-api.md +220 -0
  192. package/package.json +77 -23
  193. package/dist/index.js.map +0 -1
  194. package/dist/ssg-BZ5FYTw7.js +0 -1802
  195. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  196. package/dist/ssg.js +0 -8
  197. package/dist/ssg.js.map +0 -1
  198. package/dist/types/cart.d.ts +0 -86
  199. package/dist/types/editor.d.ts +0 -5
  200. package/dist/types/index.d.ts +0 -20
  201. package/dist/types/preview-bridge.d.ts +0 -9
  202. package/dist/types/types.d.ts +0 -44
package/dist/server.js ADDED
@@ -0,0 +1,370 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * `@tanqory/theme-kit/server` — the Theme ABI v2 serve entry (theme-abi-v2.md §1) as a factory.
4
+ *
5
+ * // entry.abi.tsx
6
+ * export const manifest = manifestJson as unknown as ThemeManifest
7
+ * export const render = createRender({ manifest, bundle })
8
+ *
9
+ * The theme's sections render through the kit runtime: StoreProvider → SectionRenderer → each
10
+ * section's `data()` binding. What the ABI decides is only where data and the page come from:
11
+ *
12
+ * - routing: the template and resource come from `ctx.route`, never from the URL;
13
+ * - data: every read is `ctx.data`, planned in abi/page-data.ts (≤ 4 calls, ≤ 2 rounds);
14
+ * - headers: only `content-type`, the style hashes and `ctx.cache.hint()`;
15
+ * - the clock: `ctx.now()`;
16
+ * - tenancy: nothing derived from `ctx` outlives the render (module scope holds only the theme).
17
+ *
18
+ * The built entry is ONE file with no imports: the theme's bundler inlines this module and its
19
+ * dependencies (react-dom/server included).
20
+ */
21
+ import { renderToString } from 'react-dom/server';
22
+ import { setThemeBundle } from './runtime/slots.js';
23
+ import { sectionModules } from './runtime/entries/sections.js';
24
+ import { registerSections } from './runtime/kit/registry.js';
25
+ import { SectionTree } from './runtime/kit/SectionTree.js';
26
+ import { DataProvider } from './runtime/kit/data.js';
27
+ import { ThemeProvider } from './runtime/kit/theme-context.js';
28
+ import { PreviewModeProvider } from './runtime/shell/preview-mode.js';
29
+ import { computeHead, headFrom, shopNameOf } from './runtime/seo/head.js';
30
+ import { jsonLdTag } from './runtime/seo/structured-data.js';
31
+ import { localeStrings, themeLocaleOf } from './runtime/platform/locale.js';
32
+ import { AbiShell } from './abi/shell.js';
33
+ import { homeHead, hreflangAlternates } from './abi/seo.js';
34
+ import { AbiCartProvider } from './abi/cart.js';
35
+ import { listingQueryOfRequest, loadPageData, pageParamsOf, searchQueryOf, searchSortOf } from './abi/page-data.js';
36
+ import { createDataApi } from './abi/data-api.js';
37
+ import { collectStyles, STYLE_RULES_ID } from './sdk/sx.js';
38
+ import { ServerRenderProvider } from './sdk/server-render.js';
39
+ import { locationOf, nodesOf, notFoundTree } from './abi/page.js';
40
+ import { HeadSinkContext, PageInfoContext } from './headless/page.js';
41
+ import { absoluteOn, breadcrumbJsonLd, collectionJsonLd } from './headless/structured-data.js';
42
+ const RTL = new Set(['ar', 'he', 'fa', 'ur', 'yi', 'ps', 'dv', 'ckb']);
43
+ const esc = (v) => String(v ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
44
+ /** JSON for a non-executable `<script type="application/json">` data block. */
45
+ const LINE_SEP = String.fromCharCode(0x2028);
46
+ const PARA_SEP = String.fromCharCode(0x2029);
47
+ const jsonBlock = (v) => JSON.stringify(v).replace(/</g, '\\u003c').split(LINE_SEP).join('\\u2028').split(PARA_SEP).join('\\u2029');
48
+ /** Cache tags: ≤ 8, ^[a-z0-9:_-]{1,64}$ (CacheHint). */
49
+ function tagsFor(ctx) {
50
+ const ok = (t) => /^[a-z0-9:_-]{1,64}$/.test(t);
51
+ const tags = [`kind:${ctx.route.kind.replace(/[^a-z0-9_-]/g, '-')}`];
52
+ if (ctx.route.handle && ok(`${ctx.route.kind}:${ctx.route.handle}`))
53
+ tags.push(`${ctx.route.kind}:${ctx.route.handle}`);
54
+ return tags.filter(ok).slice(0, 8);
55
+ }
56
+ /** Script/style tags for this artifact's client bundle — every URL under assets.base with SRI (§2.2). */
57
+ function assetTags(ctx) {
58
+ const base = ctx.assets.base;
59
+ const entries = Object.values(ctx.assets.manifest);
60
+ const byFile = new Map(entries.map((e) => [e.file, e]));
61
+ const entry = entries.find((e) => e.isEntry && e.kind === 'script');
62
+ if (!entry)
63
+ return '';
64
+ const link = (file, rel) => {
65
+ const e = byFile.get(file);
66
+ return e ? `<link rel="${rel}" href="${esc(`${base}/${e.file}`)}" integrity="${esc(e.integrity)}" crossorigin="anonymous">` : '';
67
+ };
68
+ return [
69
+ ...(entry.css ?? []).map((f) => link(f, 'stylesheet')),
70
+ ...(entry.imports ?? []).map((f) => link(f, 'modulepreload')),
71
+ `<script type="module" src="${esc(`${base}/${entry.file}`)}" integrity="${esc(entry.integrity)}" crossorigin="anonymous"></script>`,
72
+ ].join('');
73
+ }
74
+ /** `sha256-<base64>` of the text of every inline <style> element, in document order, deduplicated. */
75
+ async function styleHashes(html) {
76
+ const out = [];
77
+ for (const m of html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/g)) {
78
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(m[1])));
79
+ let bin = '';
80
+ for (const b of digest)
81
+ bin += String.fromCharCode(b);
82
+ const h = `sha256-${btoa(bin)}`;
83
+ if (!out.includes(h))
84
+ out.push(h);
85
+ }
86
+ return out;
87
+ }
88
+ /**
89
+ * The render of a declared form's POST (theme-abi §1 rows 2, 6, 8): a verified post is submitted through
90
+ * `ctx.actions.form.submit` — the platform routes it (newsletter → the store's subscriber list, contact → the
91
+ * merchant) — and the page renders its outcome. A post that failed the origin or CSRF check never ran (`expired`:
92
+ * the shopper reloads and submits again). Null on every GET.
93
+ */
94
+ async function nativeFormResult(ctx) {
95
+ const req = ctx.request;
96
+ if (req.formError)
97
+ return { formId: '*', status: 'expired' };
98
+ if (!req.formId || !req.form)
99
+ return null;
100
+ const formId = req.formId;
101
+ const email = typeof req.form.email === 'string' && req.form.email ? req.form.email.slice(0, 320) : undefined;
102
+ const failed = (status) => ({ formId, status, ...(email ? { email } : {}) });
103
+ const actions = ctx.actions;
104
+ if (!actions?.form)
105
+ return failed('unavailable');
106
+ try {
107
+ const r = await actions.form.submit(formId, req.form);
108
+ if (r.ok)
109
+ return { formId, status: 'ok' };
110
+ return failed(r.reason === 'invalid' ? 'invalid' : r.reason === 'rate_limited' ? 'rate_limited' : 'unavailable');
111
+ }
112
+ catch (e) {
113
+ ctx.log.warn('form submit failed', { formId, error: String(e?.name ?? e) });
114
+ return failed('unavailable');
115
+ }
116
+ }
117
+ /**
118
+ * The ABI `render(request, ctx)` for one theme. Call it once at module scope: it hands the theme
119
+ * bundle to the runtime and registers the theme's sections (store-independent state only).
120
+ */
121
+ export function createRender(options) {
122
+ const { manifest, bundle } = options;
123
+ const effectiveSettings = options.effectiveSettings ?? ((s) => s);
124
+ const transformNodes = options.transformNodes ?? ((n) => n);
125
+ const shopSettings = options.shopSettings ?? ((s) => s);
126
+ // ── store-independent module state ─────────────────────────────────────────
127
+ setThemeBundle(bundle);
128
+ registerSections(Object.values(sectionModules()).map((m) => m.default));
129
+ const LOCALE_MAPS = Object.fromEntries(Object.entries(bundle.locales).map(([path, mod]) => [path.match(/\/([^/]+)\.json$/)?.[1] ?? 'en', mod.default]));
130
+ const COMPONENTS = manifest.components;
131
+ /** The planner's view of a section: its attributes (resource settings name what to load). */
132
+ const defOf = (type) => (COMPONENTS[type] ? { name: type, attributes: COMPONENTS[type].attributes ?? {} } : undefined);
133
+ /** Global setting defaults from the manifest (a store's settings may omit a key it never set). */
134
+ const SETTING_DEFAULTS = Object.fromEntries((manifest.settingsSchema ?? []).flatMap((g) => g.items.filter((it) => it.default !== undefined).map((it) => [it.key, it.default])));
135
+ /** The theme's interface language: the request's, else the theme setting's, else English. */
136
+ function uiLanguage(language, settings) {
137
+ const primary = language.split('-')[0].toLowerCase();
138
+ if (LOCALE_MAPS[primary])
139
+ return primary;
140
+ return themeLocaleOf(settings.locale, Object.keys(LOCALE_MAPS));
141
+ }
142
+ return async function render(_request, ctx) {
143
+ let settings = effectiveSettings({ ...SETTING_DEFAULTS, ...ctx.content.settings });
144
+ const nodes = transformNodes(nodesOf(ctx.content.page.regions), settings);
145
+ const searchQuery = searchQueryOf(ctx);
146
+ const searchSort = searchSortOf(ctx);
147
+ const params = pageParamsOf(ctx, searchQuery, searchSort);
148
+ const listing = listingQueryOfRequest(ctx);
149
+ const location = locationOf(ctx.route.canonical, params, listing);
150
+ const now = ctx.now();
151
+ const sf = options.storefront;
152
+ // The merchant's wording for the theme's strings: one call beside the plan's first round (headless `t()`).
153
+ const stringsCall = sf && sf.merchantStrings !== false && ctx.capabilities.has('data:localization')
154
+ ? ctx.data.localization.strings(ctx.locale.language).catch((e) => {
155
+ const name = e?.name;
156
+ if (name === 'DataLimitError' || name === 'CapabilityError')
157
+ throw e;
158
+ ctx.log.warn('merchant strings unavailable', { error: String(e?.message ?? e) });
159
+ return {};
160
+ })
161
+ : null;
162
+ let pd;
163
+ let merchantStrings = {};
164
+ try {
165
+ if (sf) {
166
+ const [loaded, strings] = await Promise.all([
167
+ loadPageData(ctx, nodes, defOf, [], searchQuery, searchSort, listing, { ...(sf.plan ?? {}), reservedCalls: stringsCall ? 1 : 0 }),
168
+ stringsCall ?? Promise.resolve({}),
169
+ ]);
170
+ pd = loaded;
171
+ merchantStrings = strings;
172
+ }
173
+ else
174
+ pd = await loadPageData(ctx, nodes, defOf, [], searchQuery, searchSort, listing);
175
+ }
176
+ catch (e) {
177
+ const name = e?.name;
178
+ // A breach or a missing capability is the host's to report (ABI error value, §8) — never swallowed.
179
+ if (name === 'DataLimitError' || name === 'CapabilityError')
180
+ throw e;
181
+ ctx.log.error('page data unavailable', { error: String(e?.message ?? e) });
182
+ return new Response('<!doctype html><html lang="' + esc(ctx.locale.language) + '"><title>Temporarily unavailable</title><h1>This store is temporarily unavailable</h1></html>', {
183
+ status: 503,
184
+ headers: { 'content-type': 'text/html; charset=utf-8' },
185
+ });
186
+ }
187
+ // The store's shop record may still adjust the settings (the theme's hook). The browser
188
+ // hydrates from `state.settings`, so both renders use the same values.
189
+ settings = shopSettings(settings, pd.shop);
190
+ // Native forms (§1): a newsletter / contact form posts to this same page; a POST's render submits it.
191
+ pd = { ...pd, formEndpoint: new URL(ctx.route.canonical).pathname, formResult: await nativeFormResult(ctx) };
192
+ // Cache (§5): the platform default applies; hints may only tighten or vary. Only the cart route is
193
+ // personal (the account page is the platform's iframe).
194
+ ctx.cache.hint({
195
+ tags: tagsFor(ctx),
196
+ ...(ctx.route.kind === 'cart' ? { private: true } : {}),
197
+ vary: [...(pd.localization.country.isoCode ? ['x-tq-country'] : []), ...(pd.signedIn !== null ? ['isSignedIn'] : [])],
198
+ });
199
+ const data = createDataApi(pd, null);
200
+ const lang = ctx.locale.language;
201
+ const declared = ctx.locale.direction;
202
+ const dir = declared ?? (RTL.has(lang.split('-')[0].toLowerCase()) ? 'rtl' : 'ltr');
203
+ const ui = uiLanguage(lang, settings);
204
+ const strings = localeStrings(ui, LOCALE_MAPS);
205
+ const preview = ctx.mode === 'preview';
206
+ // Headless themes: the page facts (also copied into the hydration state) and this render's head sink (<Seo>).
207
+ const page = sf ? pageInfoOf(ctx, params, ui, preview, strings, merchantStrings) : null;
208
+ const sink = sf ? { jsonLd: [] } : null;
209
+ // Dynamic style values become class rules collected for THIS render (sdk/sx.ts): the
210
+ // platform CSP has `style-src-attr 'none'`, so no `style=""` attribute may reach the page.
211
+ const { result: body, css: styleRules } = collectStyles(() => renderToString(_jsx(PageExtras, { page: page, sink: sink, children: _jsx(ServerRenderProvider, { value: true, children: _jsx(PreviewModeProvider, { value: preview, children: _jsx(DataProvider, { value: data, children: _jsx(ThemeProvider, { settings: settings, locale: strings, children: _jsx(AbiCartProvider, { initial: pd.cart, remote: null, children: _jsx(AbiShell, { location: location, locale: ui, contentLanguage: lang, settings: settings, preview: preview, children: _jsx(SectionTree, { tree: (!preview && pd.routeMissing ? notFoundTree(nodes) : nodes) }) }) }) }) }) }) }) })));
212
+ const canonicalPath = new URL(ctx.route.canonical).pathname;
213
+ let head = computeHead(canonicalPath, data, settings, new URL(ctx.route.canonical).origin);
214
+ const shopName = shopNameOf(settings.shopName, pd.shop.name);
215
+ if (ctx.route.kind === 'blog' && ctx.route.handle && pd.blogs[ctx.route.handle]) {
216
+ const b = pd.blogs[ctx.route.handle];
217
+ head = { ...head, ...headFrom(b.seo, b.title, shopName) };
218
+ }
219
+ else if (ctx.route.kind === 'article' && ctx.route.handle) {
220
+ const a = Object.values(pd.articles).find((x) => x.handle === ctx.route.handle);
221
+ if (a)
222
+ head = { ...head, ...headFrom(a.seo, a.title, shopName, a.excerpt, a.image?.url) };
223
+ }
224
+ // The home page: the store's own search & social settings, then the fallbacks (abi/seo.ts).
225
+ let imageMeta = {};
226
+ if (ctx.route.kind === 'home') {
227
+ const home = homeHead(pd.shop, shopName, nodes, strings['seo.homeDescription'] ?? '');
228
+ head = { ...head, ...(home.title ? { title: home.title } : {}), description: home.description, image: home.image };
229
+ imageMeta = { alt: home.imageAlt, width: home.imageWidth, height: home.imageHeight };
230
+ }
231
+ // An unknown product, collection, page or blog, or an unpublished policy, is a real 404, not a 200 with an empty template.
232
+ const status = ctx.route.kind === 'not_found' || pd.routeMissing ? 404 : 200;
233
+ // <Seo> in a headless theme: what its components said about this page wins over the defaults above.
234
+ let extraHead = '';
235
+ if (sf && sink) {
236
+ head = { ...head, ...(sink.title ? { title: sink.title } : {}), ...(sink.description ? { description: sink.description } : {}), ...(sink.image ? { image: sink.image } : {}) };
237
+ extraHead = storefrontHead(ctx, sf, sink, pd, bundle, ui, status);
238
+ }
239
+ const meta = [
240
+ head.description ? `<meta name="description" content="${esc(head.description)}">` : '',
241
+ `<link rel="canonical" href="${esc(ctx.route.canonical)}">`,
242
+ head.title ? `<meta property="og:title" content="${esc(head.title)}">` : '',
243
+ head.description ? `<meta property="og:description" content="${esc(head.description)}">` : '',
244
+ head.image ? `<meta property="og:image" content="${esc(head.image)}">` : '',
245
+ head.image && imageMeta.width ? `<meta property="og:image:width" content="${imageMeta.width}">` : '',
246
+ head.image && imageMeta.height ? `<meta property="og:image:height" content="${imageMeta.height}">` : '',
247
+ head.image && imageMeta.alt ? `<meta property="og:image:alt" content="${esc(imageMeta.alt)}">` : '',
248
+ head.type ? `<meta property="og:type" content="${esc(head.type)}">` : '',
249
+ `<meta property="og:url" content="${esc(ctx.route.canonical)}">`,
250
+ head.siteName ? `<meta property="og:site_name" content="${esc(head.siteName)}">` : '',
251
+ `<meta name="twitter:card" content="${head.image ? 'summary_large_image' : 'summary'}">`,
252
+ head.title ? `<meta name="twitter:title" content="${esc(head.title)}">` : '',
253
+ head.description ? `<meta name="twitter:description" content="${esc(head.description)}">` : '',
254
+ head.image ? `<meta name="twitter:image" content="${esc(head.image)}">` : '',
255
+ head.favicon ? `<link rel="icon" href="${esc(head.favicon)}">` : '',
256
+ ...(options.hreflang !== false && status === 200
257
+ ? hreflangAlternates(ctx.route.canonical, ctx.locale.availableLanguages).map((a) => `<link rel="alternate" hreflang="${esc(a.hreflang)}" href="${esc(a.href)}">`)
258
+ : []),
259
+ jsonLdTag(head.jsonLd),
260
+ extraHead,
261
+ ].filter(Boolean).join('\n ');
262
+ // What the browser needs to rebuild the same tree: this page's content and the data it rendered.
263
+ const state = { route: { ...ctx.route, params }, page: ctx.content.page, settings, data: pd, now, preview, ui, lang, ...(listing ? { listing } : {}), ...(page ? { kit: page } : {}) };
264
+ const html = `<!doctype html>
265
+ <html lang="${esc(lang)}" dir="${dir}">
266
+ <head>
267
+ <meta charset="utf-8">
268
+ <meta name="viewport" content="width=device-width, initial-scale=1">
269
+ <title>${esc(head.title)}</title>
270
+ ${meta}
271
+ ${assetTags(ctx)}
272
+ ${styleRules ? `<style id="${STYLE_RULES_ID}">${styleRules}</style>` : ''}
273
+ </head>
274
+ <body data-tq-mode="${esc(ctx.mode)}">
275
+ <script type="application/json" id="tq-state">${jsonBlock(state)}</script>
276
+ <div id="root">${body}</div>
277
+ </body>
278
+ </html>`;
279
+ // §5: no 'unsafe-inline'. Every inline <style> block is announced by hash (`style-src-elem`).
280
+ const headers = new Headers({ 'content-type': 'text/html; charset=utf-8' });
281
+ for (const hash of await styleHashes(html))
282
+ headers.append('x-tq-csp-style-hash', hash);
283
+ return new Response(html, { status, headers });
284
+ };
285
+ }
286
+ /** The headless providers around the tree; a plain pass-through when the theme does not use them. */
287
+ function PageExtras({ page, sink, children }) {
288
+ if (!page)
289
+ return children;
290
+ return (_jsx(PageInfoContext.Provider, { value: page, children: _jsx(HeadSinkContext.Provider, { value: sink, children: children }) }));
291
+ }
292
+ /** `PageInfo` for this render: route facts, languages, assets, and only the merchant strings that differ from the theme's. */
293
+ function pageInfoOf(ctx, params, ui, preview, theme, merchant) {
294
+ const lang = ctx.locale.language;
295
+ // The merchant's strings are for the page's language; a theme rendering another language keeps its own words.
296
+ const sameLanguage = lang.split('-')[0].toLowerCase() === ui;
297
+ const strings = {};
298
+ if (sameLanguage)
299
+ for (const [k, v] of Object.entries(merchant))
300
+ if (typeof v === 'string' && v !== theme[k])
301
+ strings[k] = v;
302
+ return {
303
+ kind: ctx.route.kind,
304
+ ...(ctx.route.handle ? { handle: ctx.route.handle } : {}),
305
+ ...(ctx.route.blogHandle ? { blogHandle: ctx.route.blogHandle } : {}),
306
+ params,
307
+ canonical: ctx.route.canonical,
308
+ language: lang,
309
+ ui,
310
+ languages: [...new Set(ctx.locale.availableLanguages)],
311
+ preview,
312
+ assetsBase: ctx.assets.base,
313
+ strings,
314
+ };
315
+ }
316
+ /** Robots, breadcrumbs, collection page and the theme's own JSON-LD (headless themes). */
317
+ function storefrontHead(ctx, sf, sink, pd, bundle, ui, status) {
318
+ const out = [];
319
+ const canonical = ctx.route.canonical;
320
+ let origin = '';
321
+ try {
322
+ origin = new URL(canonical).origin;
323
+ }
324
+ catch {
325
+ origin = '';
326
+ }
327
+ if (sink.noindex)
328
+ out.push('<meta name="robots" content="noindex">');
329
+ const blocks = [];
330
+ if (sf.structuredData !== false && status === 200 && origin) {
331
+ const home = bundle.theme.labels(ui).home;
332
+ const crumbs = [{ name: home, url: absoluteOn(origin, '/') }];
333
+ const h = ctx.route.handle;
334
+ if (ctx.route.kind === 'product' && h && pd.products[h]) {
335
+ const p = pd.products[h];
336
+ const c = p.collections?.find((x) => x && x.handle && x.title);
337
+ if (c)
338
+ crumbs.push({ name: c.title, url: absoluteOn(origin, `/collections/${encodeURIComponent(c.handle)}`) });
339
+ crumbs.push({ name: p.title });
340
+ }
341
+ else if (ctx.route.kind === 'collection' && h && pd.collections[h]) {
342
+ const c = pd.collections[h];
343
+ crumbs.push({ name: c.title });
344
+ const page = collectionJsonLd(c, { url: canonical, origin });
345
+ if (page)
346
+ blocks.push(page);
347
+ }
348
+ else if (ctx.route.kind === 'page' && h && pd.pages[h]) {
349
+ crumbs.push({ name: pd.pages[h].title });
350
+ }
351
+ else if (ctx.route.kind === 'article' && h) {
352
+ const a = Object.values(pd.articles).find((x) => x.handle === h);
353
+ const b = ctx.route.blogHandle ? pd.blogs[ctx.route.blogHandle] : undefined;
354
+ if (b)
355
+ crumbs.push({ name: b.title, url: absoluteOn(origin, `/blogs/${encodeURIComponent(b.handle)}`) });
356
+ if (a)
357
+ crumbs.push({ name: a.title });
358
+ }
359
+ const trail = crumbs.length > 1 ? breadcrumbJsonLd(crumbs) : null;
360
+ if (trail)
361
+ blocks.push(trail);
362
+ }
363
+ // The theme's own blocks never repeat the Product the render already prints (exactly one per product page).
364
+ for (const b of sink.jsonLd)
365
+ if (![b['@type']].flat().includes('Product'))
366
+ blocks.push(b);
367
+ for (const b of blocks)
368
+ out.push(jsonLdTag(b));
369
+ return out.filter(Boolean).join('\n ');
370
+ }
@@ -0,0 +1,220 @@
1
+ # Headless API (`@tanqory/theme-kit/headless`)
2
+
3
+ Every storefront function, none of the styling. Your theme owns all markup and CSS; the kit supplies data,
4
+ behaviour and accessible primitives that render semantic HTML carrying the platform's `tq-storefront-hooks/1`
5
+ attributes. Each primitive accepts `className` and most accept render-prop `children` for full control.
6
+
7
+ The kit ships no CSS. The only class it adds is `visuallyHidden()` (an `sx()` rule). There is never a `style=""`
8
+ attribute: the platform CSP has `style-src-attr 'none'`. Use classes or `sx()` for dynamic values.
9
+
10
+ ```
11
+ @tanqory/theme-kit/headless hooks, primitives, defineSection / defineBlock / defineTheme, t(), formatMoney, <Seo>, <Image>, ai.*
12
+ @tanqory/theme-kit/server createRender({ manifest, bundle, storefront: {} }) the ABI render(request, ctx)
13
+ @tanqory/theme-kit/client hydrate({ bundle }) the browser entry; live edit on the editor canvas
14
+ @tanqory/theme-kit/build buildManifest(...), checkContent, withKitStrings the manifest from your declarations (Node, pure)
15
+ ```
16
+
17
+ ## 1. A theme in four files
18
+
19
+ ```tsx
20
+ // theme.tsx
21
+ import { defineTheme, defineSection, defineBlock, field, ai, useMenu, CartToggle, CartDrawer, ConsentBanner } from '@tanqory/theme-kit/headless'
22
+
23
+ const header = defineSection({
24
+ type: 'header', title: 'Header', zone: 'header',
25
+ settings: { menu: field.resource('menu', 'main-menu', { label: 'Menu' }) },
26
+ ai: ai.headerMenu('menu'),
27
+ component: ({ settings }) => {
28
+ const menu = useMenu(settings.menu)
29
+ return <header className="mast"><nav aria-label="Main">…{menu?.items…}</nav><CartToggle className="mast__cart" /></header>
30
+ },
31
+ })
32
+
33
+ export default defineTheme({
34
+ name: 'My theme',
35
+ sections: [header, /* hero, product, collection, cart, search, footer, not-found … */],
36
+ Layout: ({ children }) => <>{children}<CartDrawer className="drawer">{(cart) => …}</CartDrawer><ConsentBanner className="consent" /></>,
37
+ })
38
+ ```
39
+
40
+ ```tsx
41
+ // entry.server.tsx — built into ONE file with no imports
42
+ import { createRender } from '@tanqory/theme-kit/server'
43
+ import { bundle } from './bundle'
44
+ import manifestJson from './generated/manifest.json'
45
+ export const manifest = manifestJson
46
+ export const render = createRender({ manifest, bundle, storefront: { plan: { localization: true } } })
47
+ ```
48
+
49
+ ```tsx
50
+ // entry.client.tsx
51
+ import { hydrate } from '@tanqory/theme-kit/client'
52
+ import { bundle } from './bundle'
53
+ hydrate({ bundle })
54
+ ```
55
+
56
+ ```ts
57
+ // bundle.ts
58
+ import type { ThemeBundle } from '@tanqory/theme-kit/headless'
59
+ import theme from './theme'
60
+ export const bundle: ThemeBundle = {
61
+ theme, templates: {}, groups: {}, settings: {}, settingsSchema: {}, customSections: {}, manifest: null,
62
+ locales: import.meta.glob('./locales/*.json', { eager: true }),
63
+ }
64
+ ```
65
+
66
+ The manifest comes from your declarations: `buildManifest({ name, version, theme, settings, templates, forms })`
67
+ (see §7). `examples/aurora` in this repository is a complete theme built this way.
68
+
69
+ ## 2. `createRender({ storefront })`
70
+
71
+ `storefront` turns on what the headless API relies on. `storefront: {}` is enough; every member defaults to on.
72
+ Without it, the render is the 2.0.0-alpha.0 one, plus the hreflang alternates every theme gets from 2.0.0-alpha.2 (`createRender({ hreflang: false })` leaves them out).
73
+
74
+ | Member | Default | Effect |
75
+ |---|---|---|
76
+ | `structuredData` | `true` | BreadcrumbList JSON-LD (product, collection, page, article) and CollectionPage + ItemList on a collection. The product page's single Product JSON-LD is printed in every mode |
77
+ | `merchantStrings` | `true` | Reads the merchant's dashboard wording for your strings (`ctx.data.localization.strings`, one call beside the first round; the data plan keeps the call limit with it) and lets `t()` prefer it |
78
+ | `plan.localization` | `false` | Reads the shopper's country and lists the store's countries (the page then varies on `x-tq-country`). Needed by `<LocalizationForm>`'s country select |
79
+ | `plan.account` | `false` | Reads `request.isSignedIn` (the page then varies on it) for `useCustomer().signedIn` |
80
+ | `plan.recommendations` | `false` | Loads the product's recommendations in the server render (otherwise the browser loads them) |
81
+ | `plan.collections` | `false` | Loads the store's collection list |
82
+
83
+ The data plan also keeps its section conventions: a `header` or `footer` section with a `showLocale: true`
84
+ setting reads the country, a `header` section reads sign-in state unless `showAccount` is `false`, a
85
+ `product-recommendations` section loads recommendations, and a `collection-list` section loads every
86
+ collection. A section of type `not-found` renders the body of a 404 page.
87
+
88
+ The render also provides `usePage()` (route kind, handle, params, canonical, languages, assets base, merchant
89
+ strings) and copies it into the hydration state, so the browser renders from the same bytes.
90
+
91
+ ## 3. Declaring sections and blocks
92
+
93
+ ```ts
94
+ defineSection({
95
+ type: 'hero', // persisted: never rename once stores saved it
96
+ title: 'Hero', description?, category?, zone?: 'header' | 'main' | 'footer',
97
+ settings: { heading: field.text('After dark', { label: 'Heading' }), image: field.resource('image') },
98
+ blocks?: [defineBlock({ type: 'slide', title: 'Slide', settings: {…} })],
99
+ presets?: [{ name: 'Hero', settings?, blocks? }], // presets[0] is the editor's "Add section" preview
100
+ requires?: ['product'], // offered only on templates of these route kinds
101
+ ai?: ai.hero({ heading: 'heading', image: 'image' }),
102
+ component: ({ settings, blocks }) => …,
103
+ })
104
+ ```
105
+
106
+ The component receives `settings` resolved against the schema (defaults filled, coerced; a resource setting is
107
+ its handle string) and `blocks` in the merchant's order (`{ type, settings }`). The section renderer wraps every
108
+ section in its `data-tq-node="<id>"` element (`class="tq-node"`; style it `display: contents` to keep it out of
109
+ your layout), and
110
+ on the editor canvas a setting edit re-renders the section in place (`tq:canvas`, announced with
111
+ `tq:canvas-live`). You write nothing for either.
112
+
113
+ `field.*`: `text`, `textarea`, `richtext`, `url`, `color`, `boolean`, `select(options, default, { optionLabels })`,
114
+ `range(default, min, max, step, { unit })`, `number(…)`, `resource('image' | 'video' | 'menu' | 'collection' |
115
+ 'product' | 'page' | 'blog' | 'article', default?)`. Every field takes `{ label, info, placeholder, group }`.
116
+
117
+ ## 4. Data hooks
118
+
119
+ | Hook | Returns |
120
+ |---|---|
121
+ | `useSettings()` | the theme's global settings: the manifest defaults with the store's saved values over them |
122
+ | `useShop()` | `Shop`: name, logo, contact, social, payment methods, policies, consent banner config |
123
+ | `useMenu(handle)` | `Menu \| null` (items carry `active` for the current route) |
124
+ | `useProduct(handleOrProduct?)` | `{ product, variant, options[{ name, values[{ value, selected, available, variantId }] }], selectOption, selectVariant, price, compareAtPrice, onSale, available, quantityAvailable, image, quantity, setQuantity, unavailable }`. Without an argument: the enclosing `<ProductForm>`'s product, else the route's, opened on `?variant=` in the server render. A variant choice keeps `?variant=` in the URL |
125
+ | `useCollection(handle?)` | `{ collection, products, total, status, facets, selected, price, filtered, toggleFilter, setPrice, clearFilters, sort, sortOptions, setSort, hasMore, loadMore, page, pageHref }`. Inside `<CollectionProvider>` every caller shares one state. The route collection's sort and filters live in the URL (`?sort=`, `?filter.<facet>=`); the server renders `?sort=` and `?page=N`, a change re-asks the data plane |
126
+ | `useSearch()` | `{ query, products, articles, pages, total, sort, sortOptions, href(q, sort?) }` for `/search?q=` |
127
+ | `usePredictiveSearch(query, { limit, debounceMs })` | `{ results: { products[{ handle, title, url, price, image }], collections, queries } \| null, loading }` (browser, `data:search`) |
128
+ | `useCart()` | `{ cart, lines, itemCount, subtotal, total, checkoutUrl, ready, loading, loadError, isOpen, justAdded, open, close, add(variantId, qty), setQuantity, remove, setNote, isBusy(id), hasFailed(id), refusal(id) }` |
129
+ | `useCustomer()` | `{ signedIn: boolean \| null, accountUrl, accountHref }`. Customer data never reaches theme code |
130
+ | `useLocalization()` | `{ country, language, countries[{ code, name, currencyCode, currencySymbol, current }], languages[{ code, name, current }], changeCountry, changeLanguage, href({ country, language }) }` |
131
+ | `useRecommendations()` | `{ products, loading }` for the route's product |
132
+ | `useConsent()` | `{ required, accept, reject, decide, reopen, privacyUrl, text }` (`required` is never true on a preview render) |
133
+ | `usePageContent()` / `useBlog(handle?)` / `useArticle()` / `usePolicy()` | the route's content page `{ title, html }`, blog (with its articles), article (with `contentHtml`), published policy |
134
+ | `usePage()` | `{ kind, handle, params, canonical, language, ui, languages, preview, assetsBase, strings }` |
135
+
136
+ ## 5. Primitives
137
+
138
+ | Primitive | Renders | Behaviour |
139
+ |---|---|---|
140
+ | `<ProductForm product?>` | `<form data-tq-product-form>` | shares one product state; submit adds the selected variant and quantity (`cart.create` / `cart.addLines`), which opens the cart; a sold-out variant is never sent |
141
+ | `<VariantPicker>` | `<div data-tq-variant-picker>` → `<fieldset><legend>` + a labelled `<input type="radio">` per value (`data-selected`, `data-available` on the label) | selecting updates price, stock, image and `?variant=`; `renderValue` for swatches |
142
+ | `<ProductPrice>` | `<span data-tq-price>`, regular price in `<s>` on a sale | formatted in the market currency |
143
+ | `<ProductQuantity>` | labelled `<input type="number" min="1">` | |
144
+ | `<AddToCart>` | `<button type="submit" data-tq-action="cart:add">` | disabled and "Sold out" when the variant cannot be bought; "Adding…" in flight |
145
+ | `<CartToggle drawer?>` | `<a href="/cart" data-tq-action="cart:open" aria-haspopup="dialog" aria-expanded>` | opens the drawer (plain link without JavaScript) |
146
+ | `<CartDrawer>` | `role="dialog" aria-modal="true"` (+ optional backdrop) while open | focus moves in, Tab is trapped, Escape closes, focus returns to the opener |
147
+ | `<CartLine line>` | `<li data-tq-cart-line>` | gives its controls the line |
148
+ | `<CartLineQuantity>` | labelled `<input type="number" data-tq-quantity>` | saved on Enter or blur; 0 removes; invalid input is put back |
149
+ | `<CartLineIncrement>` / `<CartLineDecrement>` / `<CartLineRemove>` | buttons `data-tq-action="cart:increment"` / `cart:decrement` / `cart:remove` | disabled while the line's request is open |
150
+ | `<CheckoutButton>` | `<a data-tq-action="cart:checkout" href={Cart.checkoutUrl}>` | checkout is the platform's |
151
+ | `<CollectionProvider handle?>` | nothing | one `useCollection()` state for the subtree |
152
+ | `<SortSelect>` | `<form method="get">` + labelled `<select name="sort" data-tq-sort>` | re-sorts in place; without JavaScript the form submits `?sort=` |
153
+ | `<FacetFilters>` | `<div data-tq-filter>` → `<fieldset>` + checkbox per value (`data-active`), price from/to, "Clear filters" | |
154
+ | `<Pagination>` | `<nav data-tq-pagination>` → "Load more" `<a rel="next" href="?page=N">` | appends in place; a real page link without JavaScript |
155
+ | `<SearchForm>` | `<form role="search" action="/search">` + `<input type="search" name="q" data-tq-search>` + polite live region | predictive suggestions as links |
156
+ | `<LocalizationForm>` | `<form method="get" data-tq-localization>` + `<select name="country">` ("Japan (JPY ¥)") + `<select name="locale">` | a choice loads `?country=` / `?locale=` |
157
+ | `<NewsletterForm>` / `<ContactForm>` | `<form method="post" data-tq-form="newsletter\|contact">` + honeypot | native platform post (declare `forms` in the manifest); the gateway's CSRF fields are kept on hydration; status messages after the post |
158
+ | `<ConsentBanner>` | `<section data-tq-consent-banner aria-label>` | only when the platform asks; the merchant's wording wins; never in preview |
159
+ | `<AccountSlot>` | `<iframe data-tq-slot="account" sandbox="allow-scripts allow-forms allow-same-origin">` | the platform's account area on the customer route |
160
+
161
+ ## 6. Platform helpers
162
+
163
+ - **`t()`**: `const t = useTranslate(); t('product.addToCart')`, `t('cart.cartCount', { count })`. Lookup order:
164
+ the merchant's dashboard wording → your `locales/<lang>.json` → the kit's words for that language
165
+ (`KIT_STRINGS`, English and Thai) → English → the key. `withKitStrings(locales)` (build) lays your files over
166
+ the kit's, so every key the primitives use exists in every locale you ship.
167
+ - **`formatMoney(money, { display, trimZeros })`**: `$37.50`, `¥5,625`, `฿1,312.50`, `1.250 KWD`. The currency's
168
+ own minor units (`currencyDecimals`), identical on the server and in the browser.
169
+ - **`<Image image alt>`**: `image` is an image from the data or an image setting's URL; `https:` URLs, or `asset:client/<file>` under the artifact's asset base; anything
170
+ else renders `fallback`. Intrinsic width/height, `loading="lazy"`, `decoding="async"` by default.
171
+ - **`<Seo title description image noindex jsonLd>`**: overrides for this page's head, collected during the
172
+ server render. Title, description, canonical, Open Graph and the Product/Collection/Breadcrumb
173
+ JSON-LD are already printed from the data, and so are the hreflang alternates (every theme, `createRender({ hreflang })`, default on); a Product object in `jsonLd` is ignored (exactly one per page).
174
+ - **`<SkipLink>`**: to `#main`, the `<main>` the section renderer wraps the page body in.
175
+
176
+ ## 7. The manifest (`@tanqory/theme-kit/build`)
177
+
178
+ ```js
179
+ import { buildManifest, checkContent, withKitStrings } from '@tanqory/theme-kit/build'
180
+ import { validateManifest, validateFieldValue } from '@tanqory/theme-abi'
181
+
182
+ const { manifest, problems } = buildManifest({
183
+ name: '@acme/theme', version: '1.0.0', theme,
184
+ settings, // defineSettings({...}) → settingsSchema, grouped by `group`
185
+ templates: { index: { route: 'home' }, product: { route: 'product' }, '404': { route: 'not_found' }, … },
186
+ forms: { newsletter: true, contact: true },
187
+ capabilities: { server: ['data:inventory'], browser: ['data:inventory'] },
188
+ checkValue: validateFieldValue,
189
+ })
190
+ ```
191
+
192
+ It derives `components` (sections and blocks with their attributes, regions, children, parents, requires,
193
+ presets), `settingsSchema`, `routes`, `templates`, `regions` (header and footer shared, `main` per template),
194
+ `forms` and `x-tanqory-ai`. Validate the result with `validateManifest` before writing it.
195
+
196
+ **Capabilities.** The defaults are what the kit's runtime calls (`SERVER_CAPABILITIES`, `BROWSER_CAPABILITIES`).
197
+ `data:shop` is always declared: the platform gives shop data to the browser snapshot only to a theme that
198
+ declares it (decision D6). Add `data:inventory` to show stock counts.
199
+
200
+ ## 8. AI compatibility
201
+
202
+ Declare which of your sections play the roles Tanqory AI fills; the build prints the profile as
203
+ `manifest["x-tanqory-ai"]` (draft v0) and `checkAiProfile` verifies every component, block and setting it names.
204
+
205
+ | Helper | Role | Keys (setting types) |
206
+ |---|---|---|
207
+ | `ai.hero({ heading, subheading?, image?, button?, link?, block? })` | `hero` | text / image / text / url |
208
+ | `ai.headerMenu(setting)` | `headerMenu` | a `menu` setting |
209
+ | `ai.footerMenu(setting, { block })` | `footerMenus` | a `menu` setting (usually on a block) |
210
+ | `ai.footerBrand({ block? })` | `footerBrand` | |
211
+ | `ai.productGrid(setting, { heading? })` | `productGrid` | a `collection` or `product` setting |
212
+ | `ai.richText({ heading?, body? })` | `richText` | text settings |
213
+
214
+ ## 9. Storefront hooks emitted (`tq-storefront-hooks/1`)
215
+
216
+ `data-tq-action="cart:add|cart:open|cart:checkout|cart:remove|cart:increment"`, `data-tq-quantity`,
217
+ `data-tq-price`, `data-tq-variant-picker`, `data-tq-sort`, `data-tq-filter`, `data-tq-pagination`,
218
+ `data-tq-localization`, `data-tq-search`, `data-tq-consent-banner`, plus `data-tq-form`, `data-tq-slot="account"`
219
+ and `data-tq-node` from the platform contract. A menu button for a mobile menu is the theme's own markup: give it
220
+ `data-tq-action="menu:open"`.