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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +128 -10
  3. package/dist/abi/canvas-live.d.ts +72 -0
  4. package/dist/abi/canvas-live.js +159 -0
  5. package/dist/abi/cart.d.ts +60 -0
  6. package/dist/abi/cart.js +396 -0
  7. package/dist/abi/convert.d.ts +360 -0
  8. package/dist/abi/convert.js +1330 -0
  9. package/dist/abi/data-api.d.ts +15 -0
  10. package/dist/abi/data-api.js +213 -0
  11. package/dist/abi/jcs.d.ts +6 -0
  12. package/dist/abi/jcs.js +28 -0
  13. package/dist/abi/labels.d.ts +3 -0
  14. package/dist/abi/labels.js +34 -0
  15. package/dist/abi/page-data.d.ts +264 -0
  16. package/dist/abi/page-data.js +746 -0
  17. package/dist/abi/page.d.ts +28 -0
  18. package/dist/abi/page.js +57 -0
  19. package/dist/abi/referrals.d.ts +23 -0
  20. package/dist/abi/referrals.js +89 -0
  21. package/dist/abi/rewards.d.ts +27 -0
  22. package/dist/abi/rewards.js +82 -0
  23. package/dist/abi/seo.d.ts +47 -0
  24. package/dist/abi/seo.js +68 -0
  25. package/dist/abi/shell.d.ts +23 -0
  26. package/dist/abi/shell.js +10 -0
  27. package/dist/abi/state-pack.d.ts +17 -0
  28. package/dist/abi/state-pack.js +43 -0
  29. package/dist/abi/wire.d.ts +46 -0
  30. package/dist/abi/wire.js +114 -0
  31. package/dist/build.d.ts +121 -0
  32. package/dist/build.js +401 -0
  33. package/dist/chunks.d.ts +23 -0
  34. package/dist/chunks.js +41 -0
  35. package/dist/client.d.ts +26 -0
  36. package/dist/client.js +101 -0
  37. package/dist/contract.d.ts +6 -0
  38. package/dist/contract.js +6 -0
  39. package/dist/headless/ai.d.ts +132 -0
  40. package/dist/headless/ai.js +99 -0
  41. package/dist/headless/hooks.d.ts +276 -0
  42. package/dist/headless/hooks.js +544 -0
  43. package/dist/headless/i18n.d.ts +13 -0
  44. package/dist/headless/i18n.js +45 -0
  45. package/dist/headless/index.d.ts +44 -0
  46. package/dist/headless/index.js +48 -0
  47. package/dist/headless/lazy-component.d.ts +72 -0
  48. package/dist/headless/lazy-component.js +225 -0
  49. package/dist/headless/lazy-section.d.ts +38 -0
  50. package/dist/headless/lazy-section.js +97 -0
  51. package/dist/headless/model.d.ts +73 -0
  52. package/dist/headless/model.js +115 -0
  53. package/dist/headless/money.d.ts +17 -0
  54. package/dist/headless/money.js +63 -0
  55. package/dist/headless/page.d.ts +45 -0
  56. package/dist/headless/page.js +53 -0
  57. package/dist/headless/platform.d.ts +55 -0
  58. package/dist/headless/platform.js +77 -0
  59. package/dist/headless/primitives/cart.d.ts +90 -0
  60. package/dist/headless/primitives/cart.js +153 -0
  61. package/dist/headless/primitives/collection.d.ts +68 -0
  62. package/dist/headless/primitives/collection.js +80 -0
  63. package/dist/headless/primitives/product.d.ts +101 -0
  64. package/dist/headless/primitives/product.js +117 -0
  65. package/dist/headless/primitives/storefront.d.ts +106 -0
  66. package/dist/headless/primitives/storefront.js +187 -0
  67. package/dist/headless/primitives/util.d.ts +19 -0
  68. package/dist/headless/primitives/util.js +42 -0
  69. package/dist/headless/strings.d.ts +9 -0
  70. package/dist/headless/strings.js +198 -0
  71. package/dist/headless/structured-data.d.ts +31 -0
  72. package/dist/headless/structured-data.js +57 -0
  73. package/dist/headless/tanqory-money.generated.d.ts +493 -0
  74. package/dist/headless/tanqory-money.generated.js +507 -0
  75. package/dist/headless/theme.d.ts +109 -0
  76. package/dist/headless/theme.js +62 -0
  77. package/dist/index.d.ts +21 -0
  78. package/dist/index.js +21 -553
  79. package/dist/runtime/data/StoreProvider.d.ts +84 -0
  80. package/dist/runtime/data/StoreProvider.js +380 -0
  81. package/dist/runtime/data/handle.d.ts +14 -0
  82. package/dist/runtime/data/handle.js +16 -0
  83. package/dist/runtime/data/routes.d.ts +87 -0
  84. package/dist/runtime/data/routes.js +158 -0
  85. package/dist/runtime/data/to-ui.d.ts +286 -0
  86. package/dist/runtime/data/to-ui.js +1009 -0
  87. package/dist/runtime/entries/register.d.ts +9 -0
  88. package/dist/runtime/entries/register.js +9 -0
  89. package/dist/runtime/entries/sections.d.ts +16 -0
  90. package/dist/runtime/entries/sections.js +19 -0
  91. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  92. package/dist/runtime/kit/SectionTree.js +100 -0
  93. package/dist/runtime/kit/analytics.d.ts +63 -0
  94. package/dist/runtime/kit/analytics.js +250 -0
  95. package/dist/runtime/kit/cart.d.ts +222 -0
  96. package/dist/runtime/kit/cart.js +545 -0
  97. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  98. package/dist/runtime/kit/composition.js +3 -0
  99. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  100. package/dist/runtime/kit/config.js +6 -0
  101. package/dist/runtime/kit/consent.d.ts +29 -0
  102. package/dist/runtime/kit/consent.js +159 -0
  103. package/dist/runtime/kit/contract/content.d.ts +213 -0
  104. package/dist/runtime/kit/contract/content.js +119 -0
  105. package/dist/runtime/kit/contract/field-types.d.ts +360 -0
  106. package/dist/runtime/kit/contract/field-types.js +216 -0
  107. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  108. package/dist/runtime/kit/contract/groups.js +402 -0
  109. package/dist/runtime/kit/contract/index.d.ts +33 -0
  110. package/dist/runtime/kit/contract/index.js +33 -0
  111. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  112. package/dist/runtime/kit/contract/transform.js +133 -0
  113. package/dist/runtime/kit/contract/validate.d.ts +77 -0
  114. package/dist/runtime/kit/contract/validate.js +520 -0
  115. package/dist/runtime/kit/data.d.ts +732 -0
  116. package/dist/runtime/kit/data.js +1131 -0
  117. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  118. package/dist/runtime/kit/defineSection.js +10 -0
  119. package/dist/runtime/kit/dynamic-source.d.ts +118 -0
  120. package/dist/runtime/kit/dynamic-source.js +311 -0
  121. package/dist/runtime/kit/index.d.ts +24 -0
  122. package/dist/runtime/kit/index.js +24 -0
  123. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  124. package/dist/runtime/kit/jsx-to-json.js +28 -0
  125. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  126. package/dist/runtime/kit/mount.js +124 -0
  127. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  128. package/dist/runtime/kit/registry.js +12 -0
  129. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  130. package/dist/runtime/kit/ssg.js +56 -0
  131. package/dist/runtime/kit/storefront.d.ts +652 -0
  132. package/dist/runtime/kit/storefront.js +723 -0
  133. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  134. package/dist/runtime/kit/theme-context.js +25 -0
  135. package/dist/runtime/kit/types.d.ts +155 -0
  136. package/dist/runtime/kit/types.js +1 -0
  137. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  138. package/dist/runtime/platform/TrackingPixels.js +63 -0
  139. package/dist/runtime/platform/environment.d.ts +68 -0
  140. package/dist/runtime/platform/environment.js +85 -0
  141. package/dist/runtime/platform/locale.d.ts +27 -0
  142. package/dist/runtime/platform/locale.js +42 -0
  143. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  144. package/dist/runtime/platform/route-analytics.js +72 -0
  145. package/dist/runtime/platform/safe-href.d.ts +25 -0
  146. package/dist/runtime/platform/safe-href.js +69 -0
  147. package/dist/runtime/platform/safe-values.d.ts +37 -0
  148. package/dist/runtime/platform/safe-values.js +140 -0
  149. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  150. package/dist/runtime/render/SectionRenderer.js +199 -0
  151. package/dist/runtime/render/listing-query.d.ts +52 -0
  152. package/dist/runtime/render/listing-query.js +122 -0
  153. package/dist/runtime/render/localized-copy.d.ts +86 -0
  154. package/dist/runtime/render/localized-copy.js +129 -0
  155. package/dist/runtime/render/product-listing.d.ts +11 -0
  156. package/dist/runtime/render/product-listing.js +243 -0
  157. package/dist/runtime/render/resolved.d.ts +47 -0
  158. package/dist/runtime/render/resolved.js +80 -0
  159. package/dist/runtime/render/section-actions.d.ts +67 -0
  160. package/dist/runtime/render/section-actions.js +205 -0
  161. package/dist/runtime/render/starter.d.ts +11 -0
  162. package/dist/runtime/render/starter.js +96 -0
  163. package/dist/runtime/seo/head.d.ts +115 -0
  164. package/dist/runtime/seo/head.js +281 -0
  165. package/dist/runtime/seo/structured-data.d.ts +83 -0
  166. package/dist/runtime/seo/structured-data.js +252 -0
  167. package/dist/runtime/shell/PageShell.d.ts +18 -0
  168. package/dist/runtime/shell/PageShell.js +118 -0
  169. package/dist/runtime/shell/RuntimeBridge.d.ts +18 -0
  170. package/dist/runtime/shell/RuntimeBridge.js +124 -0
  171. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  172. package/dist/runtime/shell/overlay-state.js +59 -0
  173. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  174. package/dist/runtime/shell/preview-mode.js +11 -0
  175. package/dist/runtime/shell/spa-router.d.ts +14 -0
  176. package/dist/runtime/shell/spa-router.js +76 -0
  177. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  178. package/dist/runtime/shell/url-redirects.js +37 -0
  179. package/dist/runtime/slots.d.ts +74 -0
  180. package/dist/runtime/slots.js +16 -0
  181. package/dist/runtime.d.ts +34 -0
  182. package/dist/runtime.js +40 -0
  183. package/dist/sdk/app-block.d.ts +29 -0
  184. package/dist/sdk/app-block.js +22 -0
  185. package/dist/sdk/font-hooks.d.ts +7 -0
  186. package/dist/sdk/font-hooks.js +21 -0
  187. package/dist/sdk/fonts.d.ts +144 -0
  188. package/dist/sdk/fonts.js +241 -0
  189. package/dist/sdk/index.d.ts +32 -0
  190. package/dist/sdk/index.js +36 -0
  191. package/dist/sdk/motion-hooks.d.ts +23 -0
  192. package/dist/sdk/motion-hooks.js +46 -0
  193. package/dist/sdk/motion.d.ts +78 -0
  194. package/dist/sdk/motion.js +292 -0
  195. package/dist/sdk/referrals.d.ts +62 -0
  196. package/dist/sdk/referrals.js +20 -0
  197. package/dist/sdk/rewards.d.ts +85 -0
  198. package/dist/sdk/rewards.js +29 -0
  199. package/dist/sdk/runtime-context.d.ts +230 -0
  200. package/dist/sdk/runtime-context.js +73 -0
  201. package/dist/sdk/schema.d.ts +249 -0
  202. package/dist/sdk/schema.js +168 -0
  203. package/dist/sdk/server-render.d.ts +8 -0
  204. package/dist/sdk/server-render.js +12 -0
  205. package/dist/sdk/store-lookup.d.ts +32 -0
  206. package/dist/sdk/store-lookup.js +48 -0
  207. package/dist/sdk/store.d.ts +164 -0
  208. package/dist/sdk/store.js +5 -0
  209. package/dist/sdk/sx.d.ts +45 -0
  210. package/dist/sdk/sx.js +117 -0
  211. package/dist/sdk/theme.d.ts +212 -0
  212. package/dist/sdk/theme.js +27 -0
  213. package/dist/sdk/types.d.ts +789 -0
  214. package/dist/sdk/types.js +7 -0
  215. package/dist/server.d.ts +112 -0
  216. package/dist/server.js +589 -0
  217. package/dist/vite-chunks.d.ts +10 -0
  218. package/dist/vite-chunks.js +44 -0
  219. package/docs/headless-api.md +250 -0
  220. package/package.json +72 -26
  221. package/dist/index.js.map +0 -1
  222. package/dist/ssg-BZ5FYTw7.js +0 -1802
  223. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  224. package/dist/ssg.js +0 -8
  225. package/dist/ssg.js.map +0 -1
  226. package/dist/types/cart.d.ts +0 -86
  227. package/dist/types/data.d.ts +0 -357
  228. package/dist/types/dynamic-source.d.ts +0 -84
  229. package/dist/types/editor.d.ts +0 -5
  230. package/dist/types/index.d.ts +0 -20
  231. package/dist/types/preview-bridge.d.ts +0 -9
  232. package/dist/types/storefront.d.ts +0 -333
  233. package/dist/types/types.d.ts +0 -44
package/dist/server.js ADDED
@@ -0,0 +1,589 @@
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, `ctx.cache.hint()` and two live-only platform hints the
15
+ * gateway acts on (`x-tq-speculation: on` ⇒ prerender rules, `x-tq-turnstile: on` ⇒ Turnstile in the CSP);
16
+ * - the clock: `ctx.now()`;
17
+ * - tenancy: nothing derived from `ctx` outlives the render (module scope holds only the theme).
18
+ *
19
+ * The built entry is ONE file with no imports: the theme's bundler inlines this module and its
20
+ * dependencies (react-dom/server included).
21
+ */
22
+ import { labelsOf } from './abi/labels.js';
23
+ import { packPageData } from './abi/state-pack.js';
24
+ import { renderToString } from 'react-dom/server';
25
+ import { setThemeBundle } from './runtime/slots.js';
26
+ import { sectionModules } from './runtime/entries/sections.js';
27
+ import { registerSections } from './runtime/kit/registry.js';
28
+ import { SectionTree } from './runtime/kit/SectionTree.js';
29
+ import { DataProvider } from './runtime/kit/data.js';
30
+ import { ThemeProvider } from './runtime/kit/theme-context.js';
31
+ import { PreviewModeProvider } from './runtime/shell/preview-mode.js';
32
+ import { computeHead, documentTitle, headFrom, routeTitleOf, shopNameOf } from './runtime/seo/head.js';
33
+ import { articleJsonLd, homeJsonLd, jsonLdTag } from './runtime/seo/structured-data.js';
34
+ import { localeStrings, themeLocaleOf } from './runtime/platform/locale.js';
35
+ import { AbiShell } from './abi/shell.js';
36
+ import { homeHead, hreflangAlternates } from './abi/seo.js';
37
+ import { AbiCartProvider } from './abi/cart.js';
38
+ import { listingQueryOfRequest, loadPageData, pageParamsOf, searchQueryOf, searchSortOf } from './abi/page-data.js';
39
+ import { createDataApi } from './abi/data-api.js';
40
+ import { collectStyles, STYLE_RULES_ID } from './sdk/sx.js';
41
+ import { FONT_IMPORTS_ID, fontImportCss } from './sdk/fonts.js';
42
+ import { ServerRenderProvider } from './sdk/server-render.js';
43
+ import { locationOf, nodesOf, notFoundTree } from './abi/page.js';
44
+ import { HeadSinkContext, PageInfoContext } from './headless/page.js';
45
+ import { ChunkSinkContext } from './headless/lazy-section.js';
46
+ import { ResolvedSinkContext } from './runtime/render/resolved.js';
47
+ import { absoluteOn, breadcrumbJsonLd, collectionJsonLd } from './headless/structured-data.js';
48
+ const RTL = new Set(['ar', 'he', 'fa', 'ur', 'yi', 'ps', 'dv', 'ckb']);
49
+ const esc = (v) => String(v ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
50
+ /** JSON for a non-executable `<script type="application/json">` data block. */
51
+ const LINE_SEP = String.fromCharCode(0x2028);
52
+ const PARA_SEP = String.fromCharCode(0x2029);
53
+ const jsonBlock = (v) => JSON.stringify(v).replace(/</g, '\\u003c').split(LINE_SEP).join('\\u2028').split(PARA_SEP).join('\\u2029');
54
+ /** Cache tags: ≤ 8, ^[a-z0-9:_-]{1,64}$ (CacheHint). */
55
+ function tagsFor(ctx) {
56
+ const ok = (t) => /^[a-z0-9:_-]{1,64}$/.test(t);
57
+ const tags = [`kind:${ctx.route.kind.replace(/[^a-z0-9_-]/g, '-')}`];
58
+ if (ctx.route.handle && ok(`${ctx.route.kind}:${ctx.route.handle}`))
59
+ tags.push(`${ctx.route.kind}:${ctx.route.handle}`);
60
+ return tags.filter(ok).slice(0, 8);
61
+ }
62
+ /**
63
+ * Script/style tags for this artifact's client bundle — every URL under assets.base with SRI (§2.2). A client-chunks
64
+ * artifact (§2.2.1 revision 2): the page's rendered chunk keys (`tq-chunks`, keys only) and the boot, and never a
65
+ * modulepreload link (WebKit stores a preloaded module without checking its integrity); the import map that checks
66
+ * every chunk fetch is importMapTag, the first thing in <head>.
67
+ */
68
+ /** The isEntry script entry of this artifact's client manifest, if any. */
69
+ const clientEntry = (ctx) => Object.values(ctx.assets.manifest).find((e) => e.isEntry && e.kind === 'script');
70
+ /**
71
+ * A client-chunks artifact's one import map (§2.2.1 revision 2), its exact signed text, or ''. Emitted as the first
72
+ * element of <head> that can load a module; its CSP hash is asserted per render and admitted only because it is in the
73
+ * signed inlineScriptHashes. Only when assets are on the shop's origin (§2.5): the map's path-absolute keys name
74
+ * `/assets/…` there; anywhere else the page carries no map, the boot's probe pair fails and it loads the single bundle.
75
+ */
76
+ function importMapTag(ctx) {
77
+ const e = clientEntry(ctx);
78
+ if (!e?.core || typeof e.importMap !== 'string')
79
+ return '';
80
+ let sameOrigin = false;
81
+ try {
82
+ sameOrigin = new URL(ctx.assets.base).origin === new URL(ctx.route.canonical).origin && new URL(ctx.assets.base).pathname.replace(/\/$/, '') === '';
83
+ }
84
+ catch {
85
+ sameOrigin = false;
86
+ }
87
+ return sameOrigin ? `<script type="importmap">${e.importMap}</script>` : '';
88
+ }
89
+ /** sha256 of the exact bytes between the tags, as the bare CSP token (`sha256-<base64>`) the gateway expects. */
90
+ async function scriptHashToken(text) {
91
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
92
+ let bin = '';
93
+ for (const b of new Uint8Array(digest))
94
+ bin += String.fromCharCode(b);
95
+ return `sha256-${btoa(bin)}`;
96
+ }
97
+ function assetTags(ctx, chunks) {
98
+ const base = ctx.assets.base;
99
+ const entries = Object.values(ctx.assets.manifest);
100
+ const byFile = new Map(entries.map((e) => [e.file, e]));
101
+ // theme-abi-v2 §2.2.2: on a preview host (the editor canvas) the preview profile's bundle, with the full definitions;
102
+ // everywhere else the shopper profile's isEntry script. A live host answers 404 for the preview file anyway.
103
+ const previewEntry = ctx.mode === 'preview' ? entries.find((e) => e.profile === 'preview' && e.kind === 'script') : undefined;
104
+ const entry = previewEntry ?? entries.find((e) => e.isEntry && e.kind === 'script');
105
+ if (!entry)
106
+ return '';
107
+ const link = (file, rel) => {
108
+ const e = byFile.get(file);
109
+ return e ? `<link rel="${rel}" href="${esc(`${base}/${e.file}`)}" integrity="${esc(e.integrity)}" crossorigin="anonymous">` : '';
110
+ };
111
+ return [
112
+ ...(entry.css ?? []).map((f) => link(f, 'stylesheet')),
113
+ ...(entry.core ? [] : (entry.imports ?? []).map((f) => link(f, 'modulepreload'))),
114
+ // The section chunks this page rendered, by key only (the boot takes every file and hash from its own table).
115
+ ...(entry.core ? [`<script type="application/json" id="tq-chunks">${jsonBlock([...(chunks ?? [])].filter((k) => entry.chunks?.[k]).sort())}</script>`] : []),
116
+ `<script type="module" src="${esc(`${base}/${entry.file}`)}" integrity="${esc(entry.integrity)}" crossorigin="anonymous"></script>`,
117
+ ].join('');
118
+ }
119
+ /**
120
+ * NEW-OS-11 "Instant page transitions": under ABI v2 every navigation is a full page load (abi/shell.tsx),
121
+ * so the theme setting `enableSpaNavigation` turns on CROSS-DOCUMENT view transitions instead: the browser
122
+ * cross-fades the next server-rendered page in place of a white flash (Chrome/Edge 126+, Safari 18.2+;
123
+ * others load normally). Live storefront only, never the editor canvas, and none for reduced motion.
124
+ * Inline <style>, so it is announced by hash like every other block (no CSP change).
125
+ */
126
+ export const VIEW_TRANSITIONS_ID = 'tq-view-transitions';
127
+ export const VIEW_TRANSITIONS_CSS = '@view-transition{navigation:auto}' +
128
+ '@media (prefers-reduced-motion:reduce){::view-transition-group(*),::view-transition-old(*),::view-transition-new(*){animation:none!important}}';
129
+ /** `sha256-<base64>` of the text of every inline <style> element, in document order, deduplicated. */
130
+ async function styleHashes(html) {
131
+ const out = [];
132
+ for (const m of html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/g)) {
133
+ const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(m[1])));
134
+ let bin = '';
135
+ for (const b of digest)
136
+ bin += String.fromCharCode(b);
137
+ const h = `sha256-${btoa(bin)}`;
138
+ if (!out.includes(h))
139
+ out.push(h);
140
+ }
141
+ return out;
142
+ }
143
+ /** A discount code as the edge passes it on: printable, no space, no markup character, at most 64. */
144
+ const DISCOUNT_CODE = /^[^\s<>"'&\u0000-\u001f\u007f]{1,64}$/;
145
+ const MONEY_AMOUNT = /^(0|[1-9][0-9]{0,14})(\.[0-9]{1,4})?$/;
146
+ const CURRENCY = /^[A-Z]{3}$/;
147
+ const GIFT_CARD_STATUS = new Set(['ACTIVE', 'PARTIAL', 'EMPTY', 'EXPIRED', 'DEACTIVATED']);
148
+ const RFC3339 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;
149
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
150
+ const moneyOf = (v) => isRecord(v) && typeof v['amount'] === 'string' && MONEY_AMOUNT.test(v['amount']) && typeof v['currencyCode'] === 'string' && CURRENCY.test(v['currencyCode']) ? { amount: v['amount'], currencyCode: v['currencyCode'] } : null;
151
+ /**
152
+ * The gift card balance view the `gift-card-balance` form answers (NEW-PROD-12), member by member, or null when the
153
+ * answer is not that shape: the theme never sees a code, a buyer or anything the lookup does not promise.
154
+ */
155
+ export function giftCardBalanceOf(v) {
156
+ if (!isRecord(v))
157
+ return null;
158
+ const last = v['lastCharacters'];
159
+ const balance = moneyOf(v['balance']);
160
+ const initialValue = moneyOf(v['initialValue']);
161
+ const status = v['status'];
162
+ const expiresOn = v['expiresOn'];
163
+ if (typeof last !== 'string' || !/^[A-Za-z0-9]{1,8}$/.test(last) || !balance || !initialValue)
164
+ return null;
165
+ if (typeof v['enabled'] !== 'boolean' || typeof status !== 'string' || !GIFT_CARD_STATUS.has(status))
166
+ return null;
167
+ if (expiresOn !== null && (typeof expiresOn !== 'string' || !RFC3339.test(expiresOn)))
168
+ return null;
169
+ return { lastCharacters: last, balance, initialValue, enabled: v['enabled'], status: status, expiresOn };
170
+ }
171
+ /**
172
+ * The render of a declared form's POST (theme-abi §1 rows 2, 6, 8): a verified post is submitted through
173
+ * `ctx.actions.form.submit` — the platform routes it (newsletter → the store's subscriber list, contact → the
174
+ * merchant) — and the page renders its outcome. A post that failed the origin or CSRF check never ran (`expired`:
175
+ * the shopper reloads and submits again). Null on every GET.
176
+ */
177
+ async function nativeFormResult(ctx) {
178
+ const req = ctx.request;
179
+ // Post/Redirect/Get (storefront-edge core/form-flash.ts): the GET after an accepted POST carries what the POST came
180
+ // to, so the page says the same thanks it said before, and a reload sends nothing again.
181
+ const flash = req.formFlash;
182
+ if (flash && typeof flash.formId === 'string' && /^[a-z][a-z0-9-]{0,39}$/.test(flash.formId) && flash.status === 'ok')
183
+ return { formId: flash.formId, status: 'ok' };
184
+ if (req.formError)
185
+ return { formId: '*', status: 'expired' };
186
+ if (!req.formId || !req.form)
187
+ return null;
188
+ const formId = req.formId;
189
+ const email = typeof req.form.email === 'string' && req.form.email ? req.form.email.slice(0, 320) : undefined;
190
+ const failed = (status) => ({ formId, status, ...(email ? { email } : {}) });
191
+ const actions = ctx.actions;
192
+ if (!actions?.form)
193
+ return failed('unavailable');
194
+ try {
195
+ const r = await actions.form.submit(formId, req.form);
196
+ // NEW-MKT-4: a pop-up sign-up's code, for this shopper only (not in the ABI result type yet: read as unknown)
197
+ if (r.ok) {
198
+ // NEW-PROD-12: the gift card balance view the platform answered to this shopper (not in the ABI result type yet)
199
+ const giftCard = giftCardBalanceOf(r.giftCard);
200
+ return {
201
+ formId,
202
+ status: 'ok',
203
+ ...(typeof r.discountCode === 'string' && DISCOUNT_CODE.test(r.discountCode) ? { discountCode: r.discountCode } : {}),
204
+ // double opt-in: the sign-up waits for the emailed confirmation (only the literal `true` counts)
205
+ ...(r.pendingConfirmation === true ? { pendingConfirmation: true } : {}),
206
+ ...(giftCard ? { giftCard } : {}),
207
+ };
208
+ }
209
+ return failed(r.reason === 'invalid' ? 'invalid' : r.reason === 'rate_limited' ? 'rate_limited' : 'unavailable');
210
+ }
211
+ catch (e) {
212
+ ctx.log.warn('form submit failed', { formId, error: String(e?.name ?? e) });
213
+ return failed('unavailable');
214
+ }
215
+ }
216
+ /**
217
+ * The ABI `render(request, ctx)` for one theme. Call it once at module scope: it hands the theme
218
+ * bundle to the runtime and registers the theme's sections (store-independent state only).
219
+ */
220
+ export function createRender(options) {
221
+ const { manifest, bundle } = options;
222
+ const effectiveSettings = options.effectiveSettings ?? ((s) => s);
223
+ const transformNodes = options.transformNodes ?? ((n) => n);
224
+ const shopSettings = options.shopSettings ?? ((s) => s);
225
+ // ── store-independent module state ─────────────────────────────────────────
226
+ setThemeBundle(bundle);
227
+ registerSections(Object.values(sectionModules()).map((m) => m.default));
228
+ const LOCALE_MAPS = Object.fromEntries(Object.entries(bundle.locales).map(([path, mod]) => [path.match(/\/([^/]+)\.json$/)?.[1] ?? 'en', mod.default]));
229
+ const COMPONENTS = manifest.components;
230
+ /** The planner's view of a section: its attributes (resource settings name what to load). */
231
+ const defOf = (type) => (COMPONENTS[type] ? { name: type, attributes: COMPONENTS[type].attributes ?? {} } : undefined);
232
+ /** Global setting defaults from the manifest (a store's settings may omit a key it never set). */
233
+ const SETTING_DEFAULTS = Object.fromEntries((manifest.settingsSchema ?? []).flatMap((g) => g.items.filter((it) => it.default !== undefined).map((it) => [it.key, it.default])));
234
+ /** The theme's interface language: the request's, else the theme setting's, else English. */
235
+ function uiLanguage(language, settings) {
236
+ const primary = language.split('-')[0].toLowerCase();
237
+ if (LOCALE_MAPS[primary])
238
+ return primary;
239
+ return themeLocaleOf(settings.locale, Object.keys(LOCALE_MAPS));
240
+ }
241
+ return async function render(_request, ctx) {
242
+ let settings = effectiveSettings({ ...SETTING_DEFAULTS, ...ctx.content.settings });
243
+ const nodes = transformNodes(nodesOf(ctx.content.page.regions), settings);
244
+ const searchQuery = searchQueryOf(ctx);
245
+ const searchSort = searchSortOf(ctx);
246
+ const params = pageParamsOf(ctx, searchQuery, searchSort);
247
+ const listing = listingQueryOfRequest(ctx);
248
+ const location = locationOf(ctx.route.canonical, params, listing);
249
+ const now = ctx.now();
250
+ const sf = options.storefront;
251
+ // The merchant's wording for the theme's strings: one call beside the plan's first round (headless `t()`, and every
252
+ // theme's `labels`: the store's translations of its own words, abi/labels.ts; board 35 #41).
253
+ // A non-headless theme asks only on a live page and only when the host offers the read (the editor shows the theme's words).
254
+ const wantStrings = sf ? sf.merchantStrings !== false : ctx.mode !== 'preview' && typeof ctx.data.localization?.strings === 'function';
255
+ const stringsCall = wantStrings && ctx.capabilities.has('data:localization')
256
+ ? ctx.data.localization.strings(ctx.locale.language).catch((e) => {
257
+ const name = e?.name;
258
+ if (name === 'DataLimitError' || name === 'CapabilityError')
259
+ throw e;
260
+ ctx.log.warn('merchant strings unavailable', { error: String(e?.message ?? e) });
261
+ return {};
262
+ })
263
+ : null;
264
+ let pd;
265
+ let merchantStrings = {};
266
+ try {
267
+ if (sf) {
268
+ const [loaded, strings] = await Promise.all([
269
+ loadPageData(ctx, nodes, defOf, [], searchQuery, searchSort, listing, { ...(sf.plan ?? {}), reservedCalls: stringsCall ? 1 : 0 }),
270
+ stringsCall ?? Promise.resolve({}),
271
+ ]);
272
+ pd = loaded;
273
+ merchantStrings = strings;
274
+ }
275
+ else {
276
+ const [loaded, strings] = await Promise.all([
277
+ // the strings read is one call beside the plan's first round: the plan stays inside the limit with it
278
+ loadPageData(ctx, nodes, defOf, [], searchQuery, searchSort, listing, stringsCall ? { reservedCalls: 1 } : undefined),
279
+ stringsCall ?? Promise.resolve({}),
280
+ ]);
281
+ pd = loaded;
282
+ merchantStrings = strings;
283
+ }
284
+ }
285
+ catch (e) {
286
+ const name = e?.name;
287
+ // A breach or a missing capability is the host's to report (ABI error value, §8) — never swallowed.
288
+ if (name === 'DataLimitError' || name === 'CapabilityError')
289
+ throw e;
290
+ ctx.log.error('page data unavailable', { error: String(e?.message ?? e) });
291
+ return new Response('<!doctype html><html lang="' + esc(ctx.locale.language) + '"><title>Temporarily unavailable</title><h1>This store is temporarily unavailable</h1></html>', {
292
+ status: 503,
293
+ headers: { 'content-type': 'text/html; charset=utf-8' },
294
+ });
295
+ }
296
+ // The store's shop record may still adjust the settings (the theme's hook). The browser
297
+ // hydrates from `state.settings`, so both renders use the same values.
298
+ settings = shopSettings(settings, pd.shop);
299
+ // Native forms (§1): a newsletter / contact form posts to this same page; a POST's render submits it.
300
+ pd = { ...pd, formEndpoint: new URL(ctx.route.canonical).pathname, formResult: await nativeFormResult(ctx), routeParams: { ...ctx.route.params } };
301
+ // Cache (§5): the platform default applies; hints may only tighten or vary. Only the cart route is
302
+ // personal (the account page is the platform's iframe).
303
+ ctx.cache.hint({
304
+ tags: tagsFor(ctx),
305
+ ...(ctx.route.kind === 'cart' ? { private: true } : {}),
306
+ vary: [...(pd.localization.country.isoCode ? ['x-tq-country'] : []), ...(pd.signedIn !== null ? ['isSignedIn'] : [])],
307
+ });
308
+ const data = createDataApi(pd, null);
309
+ const lang = ctx.locale.language;
310
+ const declared = ctx.locale.direction;
311
+ const dir = declared ?? (RTL.has(lang.split('-')[0].toLowerCase()) ? 'rtl' : 'ltr');
312
+ const ui = uiLanguage(lang, settings);
313
+ const strings = localeStrings(ui, LOCALE_MAPS);
314
+ const preview = ctx.mode === 'preview';
315
+ // Headless themes: the page facts (also copied into the hydration state) and this render's head sink (<Seo>).
316
+ const page = sf ? pageInfoOf(ctx, params, ui, preview, strings, merchantStrings) : null;
317
+ // The theme's own words as the merchant translated them for this language (abi/labels.ts); the editor shows the theme's.
318
+ const labels = preview ? {} : labelsOf(merchantStrings, ctx.locale.market);
319
+ const sink = sf ? { jsonLd: [] } : null;
320
+ // Client chunks (theme-abi-v2 §2.2.1): the keys of the lazy sections this render drew, for the head's preloads.
321
+ const chunkSink = new Set();
322
+ // §2.2.2: every rendered node's resolved settings, for the page state (the shopper bundle needs no schema)
323
+ const resolvedSink = new Map();
324
+ // Dynamic style values become class rules collected for THIS render (sdk/sx.ts): the
325
+ // platform CSP has `style-src-attr 'none'`, so no `style=""` attribute may reach the page.
326
+ const { result: body, css: styleRules, fonts: fontFamilies } = collectStyles(() => renderToString(_jsx(ChunkSinkContext.Provider, { value: chunkSink, children: _jsx(ResolvedSinkContext.Provider, { value: resolvedSink, children: _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, labels: labels, children: _jsx(SectionTree, { tree: (!preview && pd.routeMissing ? notFoundTree(nodes) : nodes) }) }) }) }) }) }) }) }) }) })));
327
+ const canonicalPath = new URL(ctx.route.canonical).pathname;
328
+ let head = computeHead(canonicalPath, data, settings, new URL(ctx.route.canonical).origin);
329
+ const shopName = shopNameOf(settings.shopName, pd.shop.name);
330
+ if (ctx.route.kind === 'blog' && ctx.route.handle && pd.blogs[ctx.route.handle]) {
331
+ const b = pd.blogs[ctx.route.handle];
332
+ head = { ...head, ...headFrom(b.seo, b.title, shopName) };
333
+ }
334
+ else if (ctx.route.kind === 'article' && ctx.route.handle) {
335
+ const a = Object.values(pd.articles).find((x) => x.handle === ctx.route.handle);
336
+ if (a)
337
+ head = { ...head, ...headFrom(a.seo, a.title, shopName, a.excerpt, a.image?.url) };
338
+ }
339
+ // The home page: the store's own search & social settings, then the fallbacks (abi/seo.ts).
340
+ let imageMeta = {};
341
+ if (ctx.route.kind === 'home') {
342
+ const home = homeHead(pd.shop, shopName, nodes, strings['seo.homeDescription'] ?? '');
343
+ head = { ...head, ...(home.title ? { title: home.title } : {}), description: home.description, image: home.image };
344
+ imageMeta = { alt: home.imageAlt, width: home.imageWidth, height: home.imageHeight };
345
+ }
346
+ else if ((ctx.route.kind === 'collection' || ctx.route.kind === 'collections') && !head.description) {
347
+ // SEO-13: a listing without its own text (`/collections/all`, the collection list, an empty collection
348
+ // description) falls back to the store's description like the home page — never no meta description at all.
349
+ const home = homeHead(pd.shop, shopName, nodes, strings['seo.homeDescription'] ?? '');
350
+ head = { ...head, description: home.description, ...(!head.image && home.image ? { image: home.image } : {}) };
351
+ }
352
+ // Routes with no resource of their own name the page in the title (board 35 #76): "Cart — <shop>", "Search: mug —
353
+ // <shop>", "Collections — <shop>", "<policy title> — <shop>", "Page not found — <shop>".
354
+ const routeTitle = routeTitleOf({
355
+ kind: ctx.route.kind,
356
+ missing: pd.routeMissing,
357
+ t: (key) => labels[key] ?? strings[key],
358
+ searchQuery,
359
+ policyTitle: ctx.route.kind === 'policy' && ctx.route.handle
360
+ ? Object.values(pd.shop.policies ?? {}).find((p) => p?.handle === ctx.route.handle)?.title
361
+ : null,
362
+ });
363
+ if (routeTitle)
364
+ head = { ...head, title: documentTitle({ resourceTitle: routeTitle, shopName }) };
365
+ // An unknown product, collection, page or blog, or an unpublished policy, is a real 404, not a 200 with an empty template.
366
+ const status = ctx.route.kind === 'not_found' || pd.routeMissing ? 404 : 200;
367
+ // SEO-01 / SEO-05 / SEO-09: the page's own structured data, for every theme (a headless theme's storefrontHead adds
368
+ // its breadcrumbs and, for a collection, the same CollectionPage — so that one is only added here without it).
369
+ const pageJsonLd = [];
370
+ if (status === 200 && !preview) {
371
+ const origin = new URL(ctx.route.canonical).origin;
372
+ if (ctx.route.kind === 'home')
373
+ pageJsonLd.push(...homeJsonLd(pd.shop, { origin, shopName, language: lang }));
374
+ else if (ctx.route.kind === 'collection' && !sf && ctx.route.handle && pd.collections[ctx.route.handle]) {
375
+ const c = collectionJsonLd(pd.collections[ctx.route.handle], { url: ctx.route.canonical, origin });
376
+ if (c)
377
+ pageJsonLd.push(c);
378
+ }
379
+ else if (ctx.route.kind === 'article' && ctx.route.handle) {
380
+ const a = Object.values(pd.articles).find((x) => x.handle === ctx.route.handle);
381
+ const b = ctx.route.blogHandle ? pd.blogs[ctx.route.blogHandle] : undefined;
382
+ const ld = articleJsonLd(a, { url: ctx.route.canonical, origin, shopName, ...(b?.title ? { blogTitle: b.title } : {}) });
383
+ if (ld)
384
+ pageJsonLd.push(ld);
385
+ }
386
+ }
387
+ // <Seo> in a headless theme: what its components said about this page wins over the defaults above.
388
+ let extraHead = '';
389
+ if (sf && sink) {
390
+ head = { ...head, ...(sink.title ? { title: sink.title } : {}), ...(sink.description ? { description: sink.description } : {}), ...(sink.image ? { image: sink.image } : {}) };
391
+ extraHead = storefrontHead(ctx, sf, sink, pd, bundle, ui, status);
392
+ }
393
+ const meta = [
394
+ head.description ? `<meta name="description" content="${esc(head.description)}">` : '',
395
+ `<link rel="canonical" href="${esc(ctx.route.canonical)}">`,
396
+ head.title ? `<meta property="og:title" content="${esc(head.title)}">` : '',
397
+ head.description ? `<meta property="og:description" content="${esc(head.description)}">` : '',
398
+ head.image ? `<meta property="og:image" content="${esc(head.image)}">` : '',
399
+ head.image && imageMeta.width ? `<meta property="og:image:width" content="${imageMeta.width}">` : '',
400
+ head.image && imageMeta.height ? `<meta property="og:image:height" content="${imageMeta.height}">` : '',
401
+ head.image && imageMeta.alt ? `<meta property="og:image:alt" content="${esc(imageMeta.alt)}">` : '',
402
+ head.type ? `<meta property="og:type" content="${esc(head.type)}">` : '',
403
+ `<meta property="og:url" content="${esc(ctx.route.canonical)}">`,
404
+ head.siteName ? `<meta property="og:site_name" content="${esc(head.siteName)}">` : '',
405
+ `<meta name="twitter:card" content="${head.image ? 'summary_large_image' : 'summary'}">`,
406
+ head.title ? `<meta name="twitter:title" content="${esc(head.title)}">` : '',
407
+ head.description ? `<meta name="twitter:description" content="${esc(head.description)}">` : '',
408
+ head.image ? `<meta name="twitter:image" content="${esc(head.image)}">` : '',
409
+ head.favicon ? `<link rel="icon" href="${esc(head.favicon)}">` : '',
410
+ ...(options.hreflang !== false && status === 200
411
+ ? hreflangAlternates(ctx.route.canonical, ctx.locale.availableLanguages).map((a) => `<link rel="alternate" hreflang="${esc(a.hreflang)}" href="${esc(a.href)}">`)
412
+ : []),
413
+ jsonLdTag(head.jsonLd),
414
+ ...pageJsonLd.map((b) => jsonLdTag(b)),
415
+ extraHead,
416
+ ].filter(Boolean).join('\n ');
417
+ // What the browser needs to rebuild the same tree: this page's content and the data it rendered.
418
+ const state = { route: { ...ctx.route, params }, page: ctx.content.page, settings, data: pd, now, preview, ui, lang, ...(listing ? { listing } : {}), ...(page ? { kit: page } : {}), ...(Object.keys(labels).length ? { labels } : {}), ...(resolvedSink.size && manifest?.client?.editorProfile === true ? { resolved: Object.fromEntries(resolvedSink) } : {}) };
419
+ // §2.2.1 revision 2: the one import map, first, before anything that can load a module
420
+ const mapTag = importMapTag(ctx);
421
+ const html = `<!doctype html>
422
+ <html lang="${esc(lang)}" dir="${dir}">
423
+ <head>
424
+ <meta charset="utf-8">
425
+ ${mapTag}<meta name="viewport" content="width=device-width, initial-scale=1">
426
+ <title>${esc(head.title)}</title>
427
+ ${meta}
428
+ ${assetTags(ctx, chunkSink)}
429
+ ${fontFamilies.length ? `<style id="${FONT_IMPORTS_ID}">${fontImportCss(fontFamilies)}</style>` : ''}
430
+ ${styleRules ? `<style id="${STYLE_RULES_ID}">${styleRules}</style>` : ''}
431
+ ${!preview && settings.enableSpaNavigation !== false ? `<style id="${VIEW_TRANSITIONS_ID}">${VIEW_TRANSITIONS_CSS}</style>` : ''}
432
+ </head>
433
+ <body data-tq-mode="${esc(ctx.mode)}">
434
+ <script type="application/json" id="tq-state">${jsonBlock({ ...state, data: packPageData(state.data) })}</script>
435
+ <div id="root">${body}</div>
436
+ </body>
437
+ </html>`;
438
+ // §5: no 'unsafe-inline'. Every inline <style> block is announced by hash (`style-src-elem`).
439
+ const headers = new Headers({ 'content-type': 'text/html; charset=utf-8' });
440
+ for (const hash of await styleHashes(html))
441
+ headers.append('x-tq-csp-style-hash', hash);
442
+ if (mapTag)
443
+ headers.append('x-tq-csp-script-hash', await scriptHashToken(clientEntry(ctx).importMap));
444
+ const modelRendered = sink?.model === true;
445
+ for (const [name, value] of Object.entries(platformHints(preview, settings, pd.shop, Object.values(pd.products ?? {}), modelRendered)))
446
+ headers.set(name, value);
447
+ // NEW-PROD-2: a 3D model on the page ⇒ the theme's viewer styles are announced too (bounded by the edge's budget);
448
+ // on a preview host as well, where the gateway also opens the viewer (`x-tq-media: model`, platformHints)
449
+ if (modelRendered || pageMedia(Object.values(pd.products ?? {})).model)
450
+ for (const hash of options.modelViewerStyleHashes ?? [])
451
+ if (/^sha(256|384|512)-[A-Za-z0-9+/=]+$/.test(hash))
452
+ headers.append('x-tq-csp-style-hash', hash);
453
+ // the platform accepted this POST's form: the gateway may answer with a redirect to the page (Post/Redirect/Get,
454
+ // storefront-edge core/form-flash.ts) instead of this page, so a reload does not send it again
455
+ const formId = ctx.request.formId;
456
+ if (typeof formId === 'string' && pd.formResult?.status === 'ok' && pd.formResult.formId === formId)
457
+ headers.set('x-tq-form-done', formId);
458
+ return new Response(html, { status, headers });
459
+ };
460
+ }
461
+ /**
462
+ * The hints the storefront gateway acts on (storefront-edge core/platform-hints.ts); it drops every `x-tq-*` before the
463
+ * page leaves, so a browser never sees them. Live only, except `x-tq-media: model`.
464
+ * x-tq-speculation: on NEW-OS-11 part 2 — `enableSpaNavigation` is not off: the gateway adds its
465
+ * `Speculation-Rules` header, so hovering a link prerenders the next page.
466
+ * x-tq-turnstile: on A4 — the store's spam protection asks for the Turnstile widget on a form this theme can show
467
+ * (`shop.spamProtection`, either switch): the gateway allows Cloudflare Turnstile in the CSP.
468
+ * x-tq-media: video, model NEW-PROD-2 — a product on the page has a YouTube / Vimeo video (the gateway frames
469
+ * `www.youtube-nocookie.com` and `player.vimeo.com`) and/or a 3D model (`connect-src blob:`).
470
+ * In the editor canvas / a draft preview only `x-tq-media: model`: the 3D viewer runs there too (the gateway honours
471
+ * `model` on a preview host and ignores the rest, core/platform-hints.ts says why).
472
+ */
473
+ export function platformHints(preview, settings, shop, products = [], modelRendered = false) {
474
+ // NEW-PROD-2 (rev 2.52): a YouTube / Vimeo video ⇒ the gateway frames those two players; a 3D model ⇒ it lets the
475
+ // viewer read its file (same-origin model route, `blob:` textures)
476
+ const m = pageMedia(products);
477
+ // a `<ModelViewer>` the render drew (a `model` setting, B.4) counts like a product's model
478
+ const model = m.model || modelRendered;
479
+ if (preview)
480
+ return model ? { 'x-tq-media': 'model' } : {};
481
+ const out = {};
482
+ if (settings.enableSpaNavigation !== false)
483
+ out['x-tq-speculation'] = 'on';
484
+ const sp = shop?.spamProtection;
485
+ if (sp && (sp.contactForms || sp.authPages))
486
+ out['x-tq-turnstile'] = 'on';
487
+ const media = [...(m.video ? ['video'] : []), ...(model ? ['model'] : [])];
488
+ if (media.length)
489
+ out['x-tq-media'] = media.join(', ');
490
+ return out;
491
+ }
492
+ /** Which kinds of third-party / 3D media the page's products carry (kit `ProductMedia.type`). */
493
+ export function pageMedia(products) {
494
+ let video = false;
495
+ let model = false;
496
+ for (const p of products)
497
+ for (const m of p?.media ?? []) {
498
+ if (m?.type === 'external_video')
499
+ video = true;
500
+ else if (m?.type === 'model_3d')
501
+ model = true;
502
+ }
503
+ return { video, model };
504
+ }
505
+ /** The headless providers around the tree; a plain pass-through when the theme does not use them. */
506
+ function PageExtras({ page, sink, children }) {
507
+ if (!page)
508
+ return children;
509
+ return (_jsx(PageInfoContext.Provider, { value: page, children: _jsx(HeadSinkContext.Provider, { value: sink, children: children }) }));
510
+ }
511
+ /** `PageInfo` for this render: route facts, languages, assets, and only the merchant strings that differ from the theme's. */
512
+ function pageInfoOf(ctx, params, ui, preview, theme, merchant) {
513
+ const lang = ctx.locale.language;
514
+ // The merchant's strings are for the page's language; a theme rendering another language keeps its own words.
515
+ const sameLanguage = lang.split('-')[0].toLowerCase() === ui;
516
+ const strings = {};
517
+ if (sameLanguage)
518
+ for (const [k, v] of Object.entries(merchant))
519
+ if (typeof v === 'string' && v !== theme[k])
520
+ strings[k] = v;
521
+ return {
522
+ kind: ctx.route.kind,
523
+ ...(ctx.route.handle ? { handle: ctx.route.handle } : {}),
524
+ ...(ctx.route.blogHandle ? { blogHandle: ctx.route.blogHandle } : {}),
525
+ params,
526
+ canonical: ctx.route.canonical,
527
+ language: lang,
528
+ ui,
529
+ languages: [...new Set(ctx.locale.availableLanguages)],
530
+ preview,
531
+ assetsBase: ctx.assets.base,
532
+ strings,
533
+ };
534
+ }
535
+ /** Robots, breadcrumbs, collection page and the theme's own JSON-LD (headless themes). */
536
+ function storefrontHead(ctx, sf, sink, pd, bundle, ui, status) {
537
+ const out = [];
538
+ const canonical = ctx.route.canonical;
539
+ let origin = '';
540
+ try {
541
+ origin = new URL(canonical).origin;
542
+ }
543
+ catch {
544
+ origin = '';
545
+ }
546
+ if (sink.noindex)
547
+ out.push('<meta name="robots" content="noindex">');
548
+ const blocks = [];
549
+ if (sf.structuredData !== false && status === 200 && origin) {
550
+ const home = bundle.theme.labels(ui).home;
551
+ const crumbs = [{ name: home, url: absoluteOn(origin, '/') }];
552
+ const h = ctx.route.handle;
553
+ if (ctx.route.kind === 'product' && h && pd.products[h]) {
554
+ const p = pd.products[h];
555
+ const c = p.collections?.find((x) => x && x.handle && x.title);
556
+ if (c)
557
+ crumbs.push({ name: c.title, url: absoluteOn(origin, `/collections/${encodeURIComponent(c.handle)}`) });
558
+ crumbs.push({ name: p.title });
559
+ }
560
+ else if (ctx.route.kind === 'collection' && h && pd.collections[h]) {
561
+ const c = pd.collections[h];
562
+ crumbs.push({ name: c.title });
563
+ const page = collectionJsonLd(c, { url: canonical, origin });
564
+ if (page)
565
+ blocks.push(page);
566
+ }
567
+ else if (ctx.route.kind === 'page' && h && pd.pages[h]) {
568
+ crumbs.push({ name: pd.pages[h].title });
569
+ }
570
+ else if (ctx.route.kind === 'article' && h) {
571
+ const a = Object.values(pd.articles).find((x) => x.handle === h);
572
+ const b = ctx.route.blogHandle ? pd.blogs[ctx.route.blogHandle] : undefined;
573
+ if (b)
574
+ crumbs.push({ name: b.title, url: absoluteOn(origin, `/blogs/${encodeURIComponent(b.handle)}`) });
575
+ if (a)
576
+ crumbs.push({ name: a.title });
577
+ }
578
+ const trail = crumbs.length > 1 ? breadcrumbJsonLd(crumbs) : null;
579
+ if (trail)
580
+ blocks.push(trail);
581
+ }
582
+ // The theme's own blocks never repeat the Product the render already prints (exactly one per product page).
583
+ for (const b of sink.jsonLd)
584
+ if (![b['@type']].flat().includes('Product'))
585
+ blocks.push(b);
586
+ for (const b of blocks)
587
+ out.push(jsonLdTag(b));
588
+ return out.filter(Boolean).join('\n ');
589
+ }
@@ -0,0 +1,10 @@
1
+ export interface TanqoryChunksPlugin {
2
+ name: string;
3
+ transform(code: string, id: string): {
4
+ code: string;
5
+ map: null;
6
+ } | null;
7
+ }
8
+ export declare function tanqoryChunks(options?: {
9
+ root?: string;
10
+ }): TanqoryChunksPlugin;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * `@tanqory/theme-kit/vite-chunks` — a theme's own Vite builds and tests with client chunks (theme-abi-v2.md §2.2.1).
3
+ *
4
+ * The platform bundler (build-service) rewrites a client-chunks theme's `import('./x')` itself: through the boot's gate
5
+ * in the browser, into a static import on the server. A theme's own toolchain needs the server half too: React's
6
+ * renderToString cannot wait for a module, so a lazy section must already be loaded when the server (or a test) renders
7
+ * it. `tanqoryChunks()` gives Vite the same rewrite for the builds that render without a browser:
8
+ *
9
+ * import('./Hero') → __tqChunkStatic("src/sections/Hero/Hero", __tq_chunk_0) (+ import * as __tq_chunk_0 from './Hero')
10
+ *
11
+ * Use it in the SSR build and in Vitest; leave the theme's own client build alone (Vite splits `import()` natively there).
12
+ * Only relative literal specifiers are rewritten, the same rule the platform enforces (a computed one is left for the
13
+ * platform build to refuse).
14
+ */
15
+ const IMPORT_CALL = /(?<![\w$.])import\s*\(\s*(['"])(\.{1,2}\/[^'"\n]+)\1\s*\)/g;
16
+ export function tanqoryChunks(options = {}) {
17
+ return {
18
+ name: 'tanqory-chunks-static',
19
+ transform(code, id) {
20
+ const file = id.split('?')[0];
21
+ // after Vite's own TypeScript transform (no `enforce`), so a type-position `import('./x').T` is already gone; only
22
+ // theme source, never a test (a test's own `await import()` stays dynamic)
23
+ if (file.includes('/node_modules/') || /\/tests?\//.test(file) || /\.test\.[jt]sx?$/.test(file) || !/\.(tsx?|jsx?|mjs)$/.test(file))
24
+ return null;
25
+ if (!/(?<![\w$.])import\s*\(/.test(code))
26
+ return null;
27
+ const head = [];
28
+ let n = 0;
29
+ const cwd = globalThis.process?.cwd?.() ?? '';
30
+ const root = (options.root ?? cwd).replace(/\/$/, '');
31
+ const dir = file.slice(0, file.lastIndexOf('/'));
32
+ const out = code.replace(IMPORT_CALL, (_m, _q, spec) => {
33
+ const name = `__tq_chunk_${n++}`;
34
+ head.push(`import * as ${name} from ${JSON.stringify(spec)};`);
35
+ const abs = new URL(spec, `file://${dir}/`).pathname;
36
+ const key = abs.startsWith(`${root}/`) ? abs.slice(root.length + 1) : abs;
37
+ return `__tqChunkStatic(${JSON.stringify(key)}, ${name})`;
38
+ });
39
+ if (!n)
40
+ return null;
41
+ return { code: `import { __tqChunkStatic } from '@tanqory/theme-kit/chunks';\n${head.join('\n')}\n${out}`, map: null };
42
+ },
43
+ };
44
+ }