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

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 (204) 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 +321 -0
  7. package/dist/abi/convert.d.ts +192 -0
  8. package/dist/abi/convert.js +670 -0
  9. package/dist/abi/data-api.d.ts +15 -0
  10. package/dist/abi/data-api.js +198 -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 +209 -0
  14. package/dist/abi/page-data.js +583 -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 +258 -0
  72. package/dist/runtime/data/to-ui.js +820 -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 +186 -0
  82. package/dist/runtime/kit/cart.js +545 -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/runtime/kit/data.d.ts +636 -0
  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/runtime/kit/storefront.d.ts +566 -0
  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 +48 -0
  144. package/dist/runtime/render/section-actions.js +170 -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 +85 -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 +135 -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 +470 -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/data.d.ts +0 -357
  200. package/dist/types/editor.d.ts +0 -5
  201. package/dist/types/index.d.ts +0 -20
  202. package/dist/types/preview-bridge.d.ts +0 -9
  203. package/dist/types/storefront.d.ts +0 -333
  204. package/dist/types/types.d.ts +0 -44
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Starter content on the live storefront (theme `starterText`).
3
+ *
4
+ * A theme's starter templates guide the merchant with instructions in place of
5
+ * content. Those must never reach a shopper: a field still holding one renders
6
+ * empty, a section whose copy is nothing but starter text is not rendered, and
7
+ * a block holding one is left out (a testimonial nobody wrote, a "Milestone 1").
8
+ * A section the merchant wrote copy into stays — an untouched subtext must not
9
+ * take the merchant's own heading down with it. The editor renders nodes as
10
+ * they are, so the merchant still sees every field to fill.
11
+ */
12
+ import { createContext } from 'react';
13
+ /** True where starter text is the point — the editor's "Add section" preview shows a section as its preset reads. */
14
+ export const ShowStarterContext = createContext(false);
15
+ const plain = (v) => v.replace(/<[^>]*>/g, '').trim();
16
+ // An unset field renders its default, so a default is checked like a saved value.
17
+ const holdsStarter = (type, settings, starter, defaultsOf) => {
18
+ for (const v of Object.values({ ...defaultsOf?.(type), ...settings }))
19
+ if (typeof v === 'string' && starter.has(v.trim()))
20
+ return true;
21
+ return false;
22
+ };
23
+ function pruneBlocks(blocks, starter, defaultsOf) {
24
+ if (!blocks)
25
+ return blocks;
26
+ const kept = [];
27
+ for (const b of blocks) {
28
+ if (holdsStarter(b.type, b.settings, starter, defaultsOf))
29
+ continue;
30
+ kept.push(b.blocks ? { ...b, blocks: pruneBlocks(b.blocks, starter, defaultsOf) } : b);
31
+ }
32
+ return kept;
33
+ }
34
+ /**
35
+ * A section's settings with its starter fields emptied, or null when none of
36
+ * its copy is the merchant's (or its copy fields are unknown).
37
+ */
38
+ function sectionWithoutStarter(node, starter, defaultsOf, copyFieldsOf) {
39
+ const copy = copyFieldsOf?.(node.type);
40
+ if (!copy)
41
+ return null;
42
+ const merged = { ...defaultsOf?.(node.type), ...node.settings };
43
+ const cleared = {};
44
+ let authored = false;
45
+ for (const [k, v] of Object.entries(merged)) {
46
+ if (typeof v !== 'string')
47
+ continue;
48
+ if (starter.has(v.trim()))
49
+ cleared[k] = '';
50
+ // Only saved copy counts: a default nobody wrote does not keep a section up.
51
+ else if (copy.has(k) && k in (node.settings ?? {}) && plain(v))
52
+ authored = true;
53
+ }
54
+ return authored ? { ...node.settings, ...cleared } : null;
55
+ }
56
+ /** The node a shopper sees, or null when the section is still starter content. */
57
+ export function withoutStarter(node, starter, defaultsOf, copyFieldsOf) {
58
+ if (starter.size === 0)
59
+ return node;
60
+ if (holdsStarter(node.type, node.settings, starter, defaultsOf)) {
61
+ const settings = sectionWithoutStarter(node, starter, defaultsOf, copyFieldsOf);
62
+ if (!settings)
63
+ return null;
64
+ node = { ...node, settings };
65
+ }
66
+ if (!node.blocks?.length)
67
+ return node;
68
+ const blocks = pruneBlocks(node.blocks, starter, defaultsOf);
69
+ return blocks && blocks.length === node.blocks.length && blocks.every((b, i) => b === node.blocks[i]) ? node : { ...node, blocks };
70
+ }
71
+ const sets = new WeakMap();
72
+ /** The theme's starter text as a lookup set (built once per theme). */
73
+ export function starterSet(list) {
74
+ if (!list?.length)
75
+ return EMPTY;
76
+ let s = sets.get(list);
77
+ if (!s)
78
+ sets.set(list, (s = new Set(list.map((x) => x.trim()).filter(Boolean))));
79
+ return s;
80
+ }
81
+ const EMPTY = new Set();
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Per-route document head — title, description, canonical, Open Graph, Twitter
3
+ * card and favicon — computed from the merchant's own SEO fields.
4
+ *
5
+ * Extracted from `browser-entry.tsx` so BOTH entry points can use it: the boot path
6
+ * (which runs once) and the SPA router in `layouts/layout.tsx` (which runs on
7
+ * every soft navigation). Previously only boot applied a head, so every page a
8
+ * shopper reached by clicking kept the previous page's <title>, canonical and
9
+ * og: tags — including the link they then shared.
10
+ *
11
+ * Title precedence: the resource's SEO title verbatim (the merchant owns it) →
12
+ * "<resource title> — <shop>" → the shop name. Description: SEO description →
13
+ * page bodySummary → shop description (home only).
14
+ */
15
+ import type { DataApi } from '../kit/index.js';
16
+ import { type JsonLd } from './structured-data.js';
17
+ /**
18
+ * A meta description from a resource's own text when the merchant wrote no SEO
19
+ * one: tags stripped, whitespace collapsed, cut at a word near 160 characters
20
+ * (what results pages show).
21
+ */
22
+ export declare function summary(text: string | null | undefined, max?: number): string;
23
+ /** Build a HeadMeta from a resource's SEO (shared by blog/article, which resolve
24
+ * their SEO asynchronously rather than from the sync bootstrap). */
25
+ export declare function headFrom(seo: {
26
+ title?: string | null;
27
+ description?: string | null;
28
+ keywords?: string[] | null;
29
+ } | null | undefined, resourceTitle: string, shopName: string, fallbackDesc?: string | null, image?: string | null): HeadMeta;
30
+ /**
31
+ * Per-route document head (title + meta description) from the merchant's SEO
32
+ * fields. Precedence — title: the resource's SEO title verbatim (merchant owns
33
+ * it) → "<resource title> — <shop>" → shop name; description: SEO description →
34
+ * page bodySummary → shop description (home only). Runs client-side on every
35
+ * route (the SSG only prerenders home), so product/collection/page pages that
36
+ * are client-rendered still get a correct, unique title + description.
37
+ */
38
+ export interface HeadMeta {
39
+ title: string;
40
+ description: string;
41
+ keywords: string[];
42
+ /** Absolute URL of the page's lead image, for og:image / twitter:image. */
43
+ image: string;
44
+ /** 'website' for the home page, 'product'/'article' for detail pages. */
45
+ type: string;
46
+ /** Shop name — og:site_name. */
47
+ siteName: string;
48
+ /** Absolute URL for the favicon / tab icon (square brand mark). */
49
+ favicon: string;
50
+ /** schema.org JSON-LD for the page (a Product on product routes), or null. */
51
+ jsonLd?: JsonLd | null;
52
+ }
53
+ /** Resolve a possibly-relative asset URL to an absolute one, against the
54
+ * current origin — social scrapers require absolute og:image URLs. */
55
+ export declare function absUrl(url: string | undefined | null): string;
56
+ export declare function computeHead(pathname: string, data: DataApi, settings: {
57
+ shopName?: unknown;
58
+ },
59
+ /** The request origin on the server render; the browser origin when omitted. */
60
+ origin?: string): HeadMeta;
61
+ /**
62
+ * Write the computed head into the live document (client-side).
63
+ *
64
+ * Beyond title/description/keywords this now emits the canonical link + Open
65
+ * Graph + Twitter card tags that were missing entirely — which is why a shared
66
+ * product link previewed as the bare shop name on every page. The canonical and
67
+ * og:url use the page's own URL (the host the storefront is served on is the
68
+ * correct canonical for that page); forcing canonical to a configured primary
69
+ * domain when a shopper is on a different host is the store-api#558 follow-up.
70
+ */
71
+ export declare function applyHead({ title, description, keywords, image, type, siteName, favicon, jsonLd }: HeadMeta): void;
72
+ /**
73
+ * The shop's name as the storefront shows it: the store's own name
74
+ * (Settings › General), else the theme's `shopName` setting (an AI-built theme
75
+ * may still carry the name it was built under), else 'Store'. The store name
76
+ * wins so a rename in Settings reaches the header, footer and titles (D-13).
77
+ */
78
+ export declare function shopNameOf(themeShopName: unknown, storeName: unknown): string;
79
+ /**
80
+ * A route's title: the resource's SEO title verbatim (the merchant owns it),
81
+ * else "<resource title> — <shop>", else the shop name alone.
82
+ */
83
+ export declare function documentTitle(input: {
84
+ seoTitle?: string | null;
85
+ resourceTitle?: string | null;
86
+ shopName: string;
87
+ }): string;
@@ -0,0 +1,224 @@
1
+ import { matchRoute } from '../data/routes.js';
2
+ import { productJsonLd, serializeJsonLd } from './structured-data.js';
3
+ /**
4
+ * A meta description from a resource's own text when the merchant wrote no SEO
5
+ * one: tags stripped, whitespace collapsed, cut at a word near 160 characters
6
+ * (what results pages show).
7
+ */
8
+ export function summary(text, max = 160) {
9
+ const plain = String(text ?? '').replace(/<[^>]*>/g, ' ').replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ').trim();
10
+ if (plain.length <= max)
11
+ return plain;
12
+ const cut = plain.slice(0, max);
13
+ const space = cut.lastIndexOf(' ');
14
+ return `${(space > max * 0.6 ? cut.slice(0, space) : cut).replace(/[\s,.;:–—-]+$/, '')}…`;
15
+ }
16
+ /** Build a HeadMeta from a resource's SEO (shared by blog/article, which resolve
17
+ * their SEO asynchronously rather than from the sync bootstrap). */
18
+ export function headFrom(seo, resourceTitle, shopName, fallbackDesc, image) {
19
+ return {
20
+ title: documentTitle({ seoTitle: seo?.title, resourceTitle, shopName }),
21
+ description: (seo?.description || fallbackDesc || '').trim(),
22
+ keywords: (seo?.keywords ?? []).filter(Boolean),
23
+ image: absUrl(image),
24
+ type: 'article',
25
+ siteName: shopName,
26
+ favicon: '',
27
+ };
28
+ }
29
+ /** Resolve a possibly-relative asset URL to an absolute one, against the
30
+ * current origin — social scrapers require absolute og:image URLs. */
31
+ export function absUrl(url) {
32
+ if (!url)
33
+ return '';
34
+ if (/^https?:\/\//.test(url))
35
+ return url;
36
+ if (typeof window === 'undefined')
37
+ return url;
38
+ return new URL(url, window.location.origin).toString();
39
+ }
40
+ export function computeHead(pathname, data, settings,
41
+ /** The request origin on the server render; the browser origin when omitted. */
42
+ origin) {
43
+ const shop = data.shop;
44
+ // The theme's shop name first, like the header — never the store ACCOUNT's
45
+ // name when the theme names its brand (nova#14).
46
+ const shopName = shopNameOf(settings.shopName, shop?.name);
47
+ let seoTitle;
48
+ let rawTitle;
49
+ let description;
50
+ let keywords = [];
51
+ let image;
52
+ let type = 'website';
53
+ let jsonLd = null;
54
+ const pageOrigin = origin ?? (typeof window === 'undefined' ? '' : window.location.origin);
55
+ const route = matchRoute(pathname);
56
+ const isDetail = {
57
+ pg: route.resource === 'page' ? route.handle : undefined,
58
+ pr: route.resource === 'product' ? route.handle : undefined,
59
+ co: route.resource === 'collection' ? route.handle : undefined,
60
+ };
61
+ if (isDetail.pr) {
62
+ const r = data.productByHandle(isDetail.pr);
63
+ seoTitle = r?.seo?.title;
64
+ rawTitle = r?.title;
65
+ description = r?.seo?.description || summary(r?.description);
66
+ keywords = r?.seo?.keywords ?? [];
67
+ image = r?.featuredImage?.url;
68
+ type = 'product';
69
+ jsonLd = productJsonLd(data.productByHandle(isDetail.pr) ?? null, {
70
+ url: pageOrigin ? `${pageOrigin}${pathname}` : pathname,
71
+ origin: pageOrigin,
72
+ });
73
+ }
74
+ else if (isDetail.co) {
75
+ const r = data.collectionByHandle(isDetail.co);
76
+ seoTitle = r?.seo?.title;
77
+ rawTitle = r?.title;
78
+ description = r?.seo?.description || summary(r?.description);
79
+ keywords = r?.seo?.keywords ?? [];
80
+ image = r?.image?.url;
81
+ }
82
+ else if (isDetail.pg) {
83
+ const r = data.pageByHandle(isDetail.pg);
84
+ seoTitle = r?.seo?.title;
85
+ rawTitle = r?.title;
86
+ description = r?.seo?.description || r?.bodySummary;
87
+ keywords = r?.seo?.keywords ?? [];
88
+ type = 'article';
89
+ }
90
+ const isHome = !isDetail.pg && !isDetail.pr && !isDetail.co;
91
+ const title = documentTitle({ seoTitle, resourceTitle: rawTitle, shopName });
92
+ return {
93
+ title,
94
+ description: (description || (isHome ? shop?.description : '') || '').trim(),
95
+ keywords: keywords.filter(Boolean),
96
+ // og:image fallback chain: the resource's own image → the brand cover image
97
+ // (Settings → Brand, a purpose-built share banner) → the brand logo. Both
98
+ // brand images were SAVED_ONLY — carried on the SDL, rendered nowhere.
99
+ image: absUrl(image || shop?.brand?.coverImage?.url || shop?.brand?.logo?.url),
100
+ type,
101
+ siteName: shopName,
102
+ // The square brand mark makes the best favicon / tab icon; fall back to the
103
+ // primary logo. Also previously SAVED_ONLY.
104
+ favicon: absUrl(shop?.brand?.squareLogo?.url || shop?.brand?.logo?.url),
105
+ jsonLd,
106
+ };
107
+ }
108
+ /**
109
+ * Write the computed head into the live document (client-side).
110
+ *
111
+ * Beyond title/description/keywords this now emits the canonical link + Open
112
+ * Graph + Twitter card tags that were missing entirely — which is why a shared
113
+ * product link previewed as the bare shop name on every page. The canonical and
114
+ * og:url use the page's own URL (the host the storefront is served on is the
115
+ * correct canonical for that page); forcing canonical to a configured primary
116
+ * domain when a shopper is on a different host is the store-api#558 follow-up.
117
+ */
118
+ export function applyHead({ title, description, keywords, image, type, siteName, favicon, jsonLd }) {
119
+ if (typeof document === 'undefined')
120
+ return;
121
+ const head = document.head;
122
+ if (title)
123
+ document.title = title;
124
+ /**
125
+ * Write a head tag, or REMOVE it when the new page has no value for it.
126
+ *
127
+ * Skipping empty values left the previous route's head in place on a soft
128
+ * navigation: opening a product set `og:description`, `og:image` and
129
+ * `keywords`, and clicking through to a page without them kept all three, so
130
+ * sharing that URL previewed the product you had just left — the exact stale
131
+ * -head bug this module exists to fix.
132
+ */
133
+ const upsert = (selector, make, content) => {
134
+ const existing = head.querySelector(selector);
135
+ if (!content) {
136
+ // Only ever remove a tag this function owns, never one the document
137
+ // shipped with that we have no replacement for.
138
+ if (existing && existing.getAttribute('data-tq-head') === 'true')
139
+ existing.remove();
140
+ return;
141
+ }
142
+ let el = existing;
143
+ if (!el) {
144
+ el = make();
145
+ el.setAttribute('data-tq-head', 'true');
146
+ head.appendChild(el);
147
+ }
148
+ if (el.tagName === 'LINK')
149
+ el.setAttribute('href', content);
150
+ else
151
+ el.setAttribute('content', content);
152
+ };
153
+ const meta = (name, content) => upsert(`meta[name="${name}"]`, () => {
154
+ const m = document.createElement('meta');
155
+ m.setAttribute('name', name);
156
+ return m;
157
+ }, content);
158
+ const prop = (property, content) => upsert(`meta[property="${property}"]`, () => {
159
+ const m = document.createElement('meta');
160
+ m.setAttribute('property', property);
161
+ return m;
162
+ }, content);
163
+ const url = window.location.origin + window.location.pathname;
164
+ meta('description', description);
165
+ meta('keywords', keywords.join(', '));
166
+ upsert('link[rel="canonical"]', () => {
167
+ const l = document.createElement('link');
168
+ l.setAttribute('rel', 'canonical');
169
+ return l;
170
+ }, url);
171
+ prop('og:type', type);
172
+ prop('og:url', url);
173
+ prop('og:title', title);
174
+ prop('og:description', description);
175
+ prop('og:site_name', siteName);
176
+ prop('og:image', image);
177
+ meta('twitter:card', image ? 'summary_large_image' : 'summary');
178
+ meta('twitter:title', title);
179
+ meta('twitter:description', description);
180
+ meta('twitter:image', image);
181
+ // JSON-LD: written for a product, removed on the next route that has none (soft navigation must not leave the
182
+ // previous product's structured data behind). Same ownership rule as the other tags.
183
+ const ld = head.querySelector('script[type="application/ld+json"][data-tq-head="true"]');
184
+ if (jsonLd) {
185
+ const el = ld ?? document.createElement('script');
186
+ el.setAttribute('type', 'application/ld+json');
187
+ el.setAttribute('data-tq-head', 'true');
188
+ el.textContent = serializeJsonLd(jsonLd);
189
+ if (!ld)
190
+ head.appendChild(el);
191
+ }
192
+ else if (ld) {
193
+ ld.remove();
194
+ }
195
+ if (favicon) {
196
+ upsert('link[rel="icon"]', () => {
197
+ const l = document.createElement('link');
198
+ l.setAttribute('rel', 'icon');
199
+ return l;
200
+ }, favicon);
201
+ }
202
+ }
203
+ // ── Title: the store's name, like the header ────────────────────────────
204
+ /**
205
+ * The shop's name as the storefront shows it: the store's own name
206
+ * (Settings › General), else the theme's `shopName` setting (an AI-built theme
207
+ * may still carry the name it was built under), else 'Store'. The store name
208
+ * wins so a rename in Settings reaches the header, footer and titles (D-13).
209
+ */
210
+ export function shopNameOf(themeShopName, storeName) {
211
+ const text = (v) => (typeof v === 'string' ? v.trim() : '');
212
+ return text(storeName) || text(themeShopName) || 'Store';
213
+ }
214
+ /**
215
+ * A route's title: the resource's SEO title verbatim (the merchant owns it),
216
+ * else "<resource title> — <shop>", else the shop name alone.
217
+ */
218
+ export function documentTitle(input) {
219
+ const seo = input.seoTitle?.trim();
220
+ if (seo)
221
+ return seo;
222
+ const title = input.resourceTitle?.trim();
223
+ return title ? `${title} — ${input.shopName}` : input.shopName;
224
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * schema.org Product / Offer JSON-LD for search engines and AI answer engines (ChatGPT search, Google, Bing).
3
+ *
4
+ * Built from the product exactly as the buyer sees it: price and currency are the storefront's own `Money`
5
+ * (the buyer's market currency, never a hardcoded THB/USD), availability is claimed only when the storefront knows
6
+ * it, and anything unknown is omitted rather than invented. Pure and free of `window`, so the same builder runs on
7
+ * the server render and on soft navigation.
8
+ */
9
+ import type { Product } from '../kit/data.js';
10
+ export type JsonLd = Record<string, unknown>;
11
+ /**
12
+ * The Product JSON-LD for a product page, or null when there is no product (or no title). `ctx.url` is the page's
13
+ * own absolute URL and `ctx.origin` resolves relative image URLs; both come from the request on the server.
14
+ */
15
+ export declare function productJsonLd(product: Product | null | undefined, ctx: {
16
+ url: string;
17
+ origin: string;
18
+ }): JsonLd | null;
19
+ /** Serialise for embedding in HTML: `<` and the JS line separators cannot end the script element or the string. */
20
+ export declare function serializeJsonLd(data: JsonLd): string;
21
+ /** The `<script type="application/ld+json">` tag, or '' when there is nothing to say. */
22
+ export declare function jsonLdTag(data: JsonLd | null | undefined): string;
@@ -0,0 +1,115 @@
1
+ const SCHEMA = 'https://schema.org';
2
+ const MONEY_AMOUNT = /^\d+(?:\.\d+)?$/;
3
+ const CURRENCY = /^[A-Z]{3}$/;
4
+ const GTIN = /^(?:\d{8}|\d{12,14})$/;
5
+ const MAX_IMAGES = 10;
6
+ const MAX_DESCRIPTION = 5000;
7
+ const text = (v) => (typeof v === 'string' ? v.trim() : '');
8
+ const absolute = (url, origin) => {
9
+ const u = text(url);
10
+ if (!u)
11
+ return '';
12
+ // Crawlers can only fetch http(s): a `data:` placeholder or a `javascript:` URL is never an image URL.
13
+ if (/^https?:\/\//.test(u))
14
+ return u;
15
+ if (/^[a-z][a-z0-9+.-]*:/i.test(u) || !origin)
16
+ return '';
17
+ try {
18
+ return new URL(u, origin).toString();
19
+ }
20
+ catch {
21
+ return '';
22
+ }
23
+ };
24
+ const plain = (html) => html
25
+ .replace(/<[^>]*>/g, ' ')
26
+ .replace(/\s+/g, ' ')
27
+ .trim();
28
+ /** A valid money value, or null: numeric, non-negative amount and an uppercase ISO-4217 code. */
29
+ function validMoney(m) {
30
+ const amount = text(m?.amount);
31
+ const currencyCode = text(m?.currencyCode);
32
+ if (!MONEY_AMOUNT.test(amount) || !CURRENCY.test(currencyCode))
33
+ return null;
34
+ return { amount, currencyCode };
35
+ }
36
+ const availabilityOf = (available) => available === true ? `${SCHEMA}/InStock` : available === false ? `${SCHEMA}/OutOfStock` : undefined;
37
+ function offersOf(product, url) {
38
+ const variants = (product.variants ?? [])
39
+ .map((v) => ({ v, money: validMoney(v.price) }))
40
+ .filter((x) => x.money !== null);
41
+ const currency = variants[0]?.money.currencyCode;
42
+ if (variants.length > 1 && variants.every((x) => x.money.currencyCode === currency)) {
43
+ const amounts = variants.map((x) => Number(x.money.amount));
44
+ const lowIdx = amounts.indexOf(Math.min(...amounts));
45
+ const highIdx = amounts.indexOf(Math.max(...amounts));
46
+ if (amounts[lowIdx] !== amounts[highIdx]) {
47
+ return {
48
+ '@type': 'AggregateOffer',
49
+ url,
50
+ lowPrice: variants[lowIdx].money.amount,
51
+ highPrice: variants[highIdx].money.amount,
52
+ priceCurrency: currency,
53
+ offerCount: variants.length,
54
+ ...(variants.some((x) => x.v.availableForSale)
55
+ ? { availability: `${SCHEMA}/InStock` }
56
+ : { availability: `${SCHEMA}/OutOfStock` }),
57
+ };
58
+ }
59
+ }
60
+ const money = variants[0]?.money ?? validMoney(product.price);
61
+ if (!money)
62
+ return undefined;
63
+ const availability = availabilityOf(variants.length ? variants.some((x) => x.v.availableForSale) : product.availableForSale);
64
+ return {
65
+ '@type': 'Offer',
66
+ url,
67
+ price: money.amount,
68
+ priceCurrency: money.currencyCode,
69
+ ...(availability ? { availability } : {}),
70
+ };
71
+ }
72
+ /**
73
+ * The Product JSON-LD for a product page, or null when there is no product (or no title). `ctx.url` is the page's
74
+ * own absolute URL and `ctx.origin` resolves relative image URLs; both come from the request on the server.
75
+ */
76
+ export function productJsonLd(product, ctx) {
77
+ if (!product)
78
+ return null;
79
+ const name = text(product.title);
80
+ if (!name)
81
+ return null;
82
+ const images = [
83
+ ...new Set([product.featuredImage?.url, ...(product.images ?? []).map((i) => i.url)]
84
+ .map((u) => absolute(u, ctx.origin))
85
+ .filter(Boolean)),
86
+ ].slice(0, MAX_IMAGES);
87
+ const description = (text(product.seo?.description) || plain(text(product.description))).slice(0, MAX_DESCRIPTION);
88
+ const vendor = text(product.vendor);
89
+ const offers = offersOf(product, ctx.url);
90
+ const single = product.variants?.length === 1 ? product.variants[0] : undefined;
91
+ const sku = text(single?.sku);
92
+ const barcode = text(single?.barcode);
93
+ return {
94
+ '@context': SCHEMA,
95
+ '@type': 'Product',
96
+ name,
97
+ url: ctx.url,
98
+ ...(images.length ? { image: images } : {}),
99
+ ...(description ? { description } : {}),
100
+ ...(vendor ? { brand: { '@type': 'Brand', name: vendor } } : {}),
101
+ ...(sku ? { sku } : {}),
102
+ ...(GTIN.test(barcode) ? { gtin: barcode } : {}),
103
+ ...(offers ? { offers } : {}),
104
+ };
105
+ }
106
+ const LINE_SEP = String.fromCharCode(0x2028);
107
+ const PARA_SEP = String.fromCharCode(0x2029);
108
+ /** Serialise for embedding in HTML: `<` and the JS line separators cannot end the script element or the string. */
109
+ export function serializeJsonLd(data) {
110
+ return JSON.stringify(data).replace(/</g, '\\u003c').split(LINE_SEP).join('\\u2028').split(PARA_SEP).join('\\u2029');
111
+ }
112
+ /** The `<script type="application/ld+json">` tag, or '' when there is nothing to say. */
113
+ export function jsonLdTag(data) {
114
+ return data ? `<script type="application/ld+json">${serializeJsonLd(data)}</script>` : '';
115
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The storefront shell: everything a page needs around the theme's sections.
3
+ *
4
+ * theme.Provider the theme's tokens, theme settings, strings (the theme's own component)
5
+ * StoreProvider route context + store data the sections' bindings read
6
+ * RuntimeBridge what the SDK hooks return (cart, overlays, actions, consent)
7
+ * theme.Layout the theme's page layout — sections and page-level overlays
8
+ *
9
+ * The section tree arrives as `children` (mount and the editor's preview bridge
10
+ * both render `<Shell><SectionTree/></Shell>`). With SPA navigation on, a soft
11
+ * navigation away from the landing URL renders the new template's tree instead.
12
+ */
13
+ import { type ReactNode } from 'react';
14
+ /** The locales the theme ships strings for (locales/<code>.json). */
15
+ export declare function themeLocales(): string[];
16
+ export default function PageShell({ children }: {
17
+ children: ReactNode;
18
+ }): JSX.Element;
@@ -0,0 +1,113 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * The storefront shell: everything a page needs around the theme's sections.
4
+ *
5
+ * theme.Provider the theme's tokens, theme settings, strings (the theme's own component)
6
+ * StoreProvider route context + store data the sections' bindings read
7
+ * RuntimeBridge what the SDK hooks return (cart, overlays, actions, consent)
8
+ * theme.Layout the theme's page layout — sections and page-level overlays
9
+ *
10
+ * The section tree arrives as `children` (mount and the editor's preview bridge
11
+ * both render `<Shell><SectionTree/></Shell>`). With SPA navigation on, a soft
12
+ * navigation away from the landing URL renders the new template's tree instead.
13
+ */
14
+ import { useEffect, useMemo, useRef, useState } from 'react';
15
+ import { SectionTree, groupsFromGlob, resolvePageSections, useData, useSettings } from '../kit/index.js';
16
+ import { applyHead, computeHead } from '../seo/head.js';
17
+ import { emitRoute } from '../platform/route-analytics.js';
18
+ import { matchRoute, resolveAsyncVariant, resolvePageTemplate } from '../data/routes.js';
19
+ import { isEditorPreview } from '../platform/environment.js';
20
+ import { themeLocaleOf } from '../platform/locale.js';
21
+ import { OverlayProvider } from './overlay-state.js';
22
+ import { StoreProvider } from '../data/StoreProvider.js';
23
+ import { TrackingPixels } from '../platform/TrackingPixels.js';
24
+ import { useSoftRoute } from './spa-router.js';
25
+ import { useUrlRedirect } from './url-redirects.js';
26
+ import { RuntimeBridge } from './RuntimeBridge.js';
27
+ import { getEditorRuntime, getThemeBundle } from '../slots.js';
28
+ const same = (s) => s;
29
+ const noop = () => { };
30
+ /** The locales the theme ships strings for (locales/<code>.json). */
31
+ export function themeLocales() {
32
+ return Object.keys(getThemeBundle().locales).map((k) => k.match(/\/([^/]+)\.json$/)?.[1] ?? 'en');
33
+ }
34
+ export default function PageShell({ children }) {
35
+ const bundle = getThemeBundle();
36
+ const { theme } = bundle;
37
+ const editor = getEditorRuntime();
38
+ const preview = isEditorPreview();
39
+ const saved = useSettings();
40
+ // The editor runtime is fixed for the page's lifetime, so the hook called here never changes.
41
+ const useLiveSettings = editor?.useLiveSettings ?? same;
42
+ const usePreviewSelection = editor?.usePreviewSelection ?? noop;
43
+ const settings = useLiveSettings(saved, preview);
44
+ usePreviewSelection(preview);
45
+ const data = useData();
46
+ const locale = themeLocaleOf(settings.locale, themeLocales());
47
+ const { templates, groups } = useMemo(() => ({ templates: bundle.templates, groups: groupsFromGlob(bundle.groups) }), [bundle]);
48
+ const templateExists = (name) => Object.keys(templates).some((k) => k.endsWith(`/${name}.json`));
49
+ const lookupTemplate = (name) => {
50
+ for (const [key, mod] of Object.entries(templates))
51
+ if (key.endsWith(`/${name}.json`))
52
+ return resolvePageSections(mod.default, groups);
53
+ return null;
54
+ };
55
+ // Soft navigation is off in the editor: the preview bridge owns the tree
56
+ // there, and a click should select a section, not navigate away.
57
+ const enableSpa = !preview && settings.enableSpaNavigation !== false;
58
+ const location = useSoftRoute(enableSpa);
59
+ const pathname = location.split('?')[0] || '/';
60
+ // The landing route's template was resolved by the entry (including the
61
+ // merchant's templateSuffix); only a navigation AWAY from it is the shell's.
62
+ const entryPath = useRef(pathname);
63
+ const navigatedAway = enableSpa && pathname !== entryPath.current;
64
+ // A page, blog or article's template variant needs its record (not in the sync
65
+ // bootstrap): until it answers, the new page renders empty rather than as
66
+ // the base template it would then have to swap out.
67
+ const route = matchRoute(pathname);
68
+ const needsRecord = navigatedAway && (route.resource === 'blog' || route.resource === 'article' || route.resource === 'page');
69
+ const [asyncVariant, setAsyncVariant] = useState(null);
70
+ useEffect(() => {
71
+ if (!needsRecord)
72
+ return;
73
+ let live = true;
74
+ void resolveAsyncVariant(route, route.template, data, templateExists).then((template) => {
75
+ if (live)
76
+ setAsyncVariant({ path: pathname, template });
77
+ });
78
+ return () => {
79
+ live = false;
80
+ };
81
+ // eslint-disable-next-line react-hooks/exhaustive-deps
82
+ }, [needsRecord, pathname, data]);
83
+ const softTree = useMemo(() => {
84
+ if (!navigatedAway)
85
+ return null;
86
+ const template = needsRecord ? (asyncVariant?.path === pathname ? asyncVariant.template : null) : resolvePageTemplate(pathname, data, templateExists);
87
+ if (!template)
88
+ return [];
89
+ return lookupTemplate(template) ?? lookupTemplate('404') ?? [];
90
+ // eslint-disable-next-line react-hooks/exhaustive-deps
91
+ }, [navigatedAway, needsRecord, asyncVariant, pathname, data, templates, groups]);
92
+ useUrlRedirect(pathname);
93
+ // While the next page's template is still being resolved, keep the current
94
+ // page on screen — the header, footer and content stay put and are swapped in
95
+ // one step when the next tree is ready, instead of flashing an empty page.
96
+ const pending = navigatedAway && needsRecord && asyncVariant?.path !== pathname;
97
+ const shown = useRef({ location, tree: softTree });
98
+ if (!pending)
99
+ shown.current = { location, tree: softTree };
100
+ const view = shown.current;
101
+ const viewPath = view.location.split('?')[0] || '/';
102
+ const viewSearch = view.location.includes('?') ? `?${view.location.split('?')[1] ?? ''}` : '';
103
+ // The head and the page-view follow what is on screen, so a page's title is
104
+ // applied once its record has loaded, not before.
105
+ useEffect(() => {
106
+ if (!enableSpa || typeof window === 'undefined')
107
+ return;
108
+ applyHead(computeHead(viewPath, data, settings));
109
+ emitRoute({ pathname: viewPath, search: viewSearch }, data);
110
+ }, [enableSpa, viewPath, viewSearch, data, settings]);
111
+ const { Provider, Layout } = theme;
112
+ return (_jsx(Provider, { mode: preview ? 'editor' : 'storefront', locale: locale, settings: settings, children: _jsx(StoreProvider, { location: view.location, locale: locale, settings: settings, children: _jsxs(OverlayProvider, { children: [_jsx(RuntimeBridge, { mode: preview ? 'editor' : 'storefront', locale: locale, settings: settings, children: _jsx(Layout, { children: _jsx("div", { style: { display: 'contents' }, children: view.tree ? _jsx(SectionTree, { tree: view.tree }) : children }, view.tree ? viewPath : 'entry') }) }), _jsx(TrackingPixels, {})] }) }) }));
113
+ }