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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +125 -10
  3. package/dist/abi/canvas-live.d.ts +67 -0
  4. package/dist/abi/canvas-live.js +154 -0
  5. package/dist/abi/cart.d.ts +59 -0
  6. package/dist/abi/cart.js +387 -0
  7. package/dist/abi/convert.d.ts +344 -0
  8. package/dist/abi/convert.js +1278 -0
  9. package/dist/abi/data-api.d.ts +15 -0
  10. package/dist/abi/data-api.js +209 -0
  11. package/dist/abi/jcs.d.ts +6 -0
  12. package/dist/abi/jcs.js +28 -0
  13. package/dist/abi/labels.d.ts +3 -0
  14. package/dist/abi/labels.js +34 -0
  15. package/dist/abi/page-data.d.ts +256 -0
  16. package/dist/abi/page-data.js +678 -0
  17. package/dist/abi/page.d.ts +28 -0
  18. package/dist/abi/page.js +57 -0
  19. package/dist/abi/referrals.d.ts +23 -0
  20. package/dist/abi/referrals.js +89 -0
  21. package/dist/abi/rewards.d.ts +27 -0
  22. package/dist/abi/rewards.js +82 -0
  23. package/dist/abi/seo.d.ts +47 -0
  24. package/dist/abi/seo.js +68 -0
  25. package/dist/abi/shell.d.ts +23 -0
  26. package/dist/abi/shell.js +10 -0
  27. package/dist/abi/state-pack.d.ts +17 -0
  28. package/dist/abi/state-pack.js +43 -0
  29. package/dist/abi/wire.d.ts +38 -0
  30. package/dist/abi/wire.js +84 -0
  31. package/dist/build.d.ts +116 -0
  32. package/dist/build.js +310 -0
  33. package/dist/client.d.ts +19 -0
  34. package/dist/client.js +87 -0
  35. package/dist/contract.d.ts +6 -0
  36. package/dist/contract.js +6 -0
  37. package/dist/headless/ai.d.ts +132 -0
  38. package/dist/headless/ai.js +99 -0
  39. package/dist/headless/hooks.d.ts +276 -0
  40. package/dist/headless/hooks.js +540 -0
  41. package/dist/headless/i18n.d.ts +13 -0
  42. package/dist/headless/i18n.js +45 -0
  43. package/dist/headless/index.d.ts +37 -0
  44. package/dist/headless/index.js +38 -0
  45. package/dist/headless/money.d.ts +25 -0
  46. package/dist/headless/money.js +61 -0
  47. package/dist/headless/page.d.ts +43 -0
  48. package/dist/headless/page.js +53 -0
  49. package/dist/headless/platform.d.ts +55 -0
  50. package/dist/headless/platform.js +77 -0
  51. package/dist/headless/primitives/cart.d.ts +90 -0
  52. package/dist/headless/primitives/cart.js +153 -0
  53. package/dist/headless/primitives/collection.d.ts +68 -0
  54. package/dist/headless/primitives/collection.js +80 -0
  55. package/dist/headless/primitives/product.d.ts +101 -0
  56. package/dist/headless/primitives/product.js +117 -0
  57. package/dist/headless/primitives/storefront.d.ts +106 -0
  58. package/dist/headless/primitives/storefront.js +186 -0
  59. package/dist/headless/primitives/util.d.ts +19 -0
  60. package/dist/headless/primitives/util.js +42 -0
  61. package/dist/headless/strings.d.ts +9 -0
  62. package/dist/headless/strings.js +190 -0
  63. package/dist/headless/structured-data.d.ts +31 -0
  64. package/dist/headless/structured-data.js +57 -0
  65. package/dist/headless/theme.d.ts +99 -0
  66. package/dist/headless/theme.js +54 -0
  67. package/dist/index.d.ts +20 -0
  68. package/dist/index.js +18 -553
  69. package/dist/runtime/data/StoreProvider.d.ts +84 -0
  70. package/dist/runtime/data/StoreProvider.js +373 -0
  71. package/dist/runtime/data/handle.d.ts +14 -0
  72. package/dist/runtime/data/handle.js +16 -0
  73. package/dist/runtime/data/routes.d.ts +87 -0
  74. package/dist/runtime/data/routes.js +158 -0
  75. package/dist/runtime/data/to-ui.d.ts +281 -0
  76. package/dist/runtime/data/to-ui.js +977 -0
  77. package/dist/runtime/entries/register.d.ts +9 -0
  78. package/dist/runtime/entries/register.js +9 -0
  79. package/dist/runtime/entries/sections.d.ts +16 -0
  80. package/dist/runtime/entries/sections.js +19 -0
  81. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  82. package/dist/runtime/kit/SectionTree.js +100 -0
  83. package/dist/runtime/kit/analytics.d.ts +63 -0
  84. package/dist/runtime/kit/analytics.js +250 -0
  85. package/dist/runtime/kit/cart.d.ts +215 -0
  86. package/dist/runtime/kit/cart.js +545 -0
  87. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  88. package/dist/runtime/kit/composition.js +3 -0
  89. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  90. package/dist/runtime/kit/config.js +6 -0
  91. package/dist/runtime/kit/consent.d.ts +29 -0
  92. package/dist/runtime/kit/consent.js +159 -0
  93. package/dist/runtime/kit/contract/content.d.ts +199 -0
  94. package/dist/runtime/kit/contract/content.js +106 -0
  95. package/dist/runtime/kit/contract/field-types.d.ts +337 -0
  96. package/dist/runtime/kit/contract/field-types.js +206 -0
  97. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  98. package/dist/runtime/kit/contract/groups.js +402 -0
  99. package/dist/runtime/kit/contract/index.d.ts +33 -0
  100. package/dist/runtime/kit/contract/index.js +33 -0
  101. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  102. package/dist/runtime/kit/contract/transform.js +133 -0
  103. package/dist/runtime/kit/contract/validate.d.ts +75 -0
  104. package/dist/runtime/kit/contract/validate.js +480 -0
  105. package/dist/runtime/kit/data.d.ts +720 -0
  106. package/dist/runtime/kit/data.js +1117 -0
  107. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  108. package/dist/runtime/kit/defineSection.js +10 -0
  109. package/dist/{types → runtime/kit}/dynamic-source.d.ts +40 -18
  110. package/dist/runtime/kit/dynamic-source.js +294 -0
  111. package/dist/runtime/kit/index.d.ts +24 -0
  112. package/dist/runtime/kit/index.js +24 -0
  113. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  114. package/dist/runtime/kit/jsx-to-json.js +28 -0
  115. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  116. package/dist/runtime/kit/mount.js +124 -0
  117. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  118. package/dist/runtime/kit/registry.js +12 -0
  119. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  120. package/dist/runtime/kit/ssg.js +56 -0
  121. package/dist/runtime/kit/storefront.d.ts +639 -0
  122. package/dist/runtime/kit/storefront.js +723 -0
  123. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  124. package/dist/runtime/kit/theme-context.js +25 -0
  125. package/dist/runtime/kit/types.d.ts +147 -0
  126. package/dist/runtime/kit/types.js +1 -0
  127. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  128. package/dist/runtime/platform/TrackingPixels.js +63 -0
  129. package/dist/runtime/platform/environment.d.ts +68 -0
  130. package/dist/runtime/platform/environment.js +85 -0
  131. package/dist/runtime/platform/locale.d.ts +27 -0
  132. package/dist/runtime/platform/locale.js +42 -0
  133. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  134. package/dist/runtime/platform/route-analytics.js +72 -0
  135. package/dist/runtime/platform/safe-href.d.ts +25 -0
  136. package/dist/runtime/platform/safe-href.js +69 -0
  137. package/dist/runtime/platform/safe-values.d.ts +37 -0
  138. package/dist/runtime/platform/safe-values.js +140 -0
  139. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  140. package/dist/runtime/render/SectionRenderer.js +166 -0
  141. package/dist/runtime/render/listing-query.d.ts +52 -0
  142. package/dist/runtime/render/listing-query.js +122 -0
  143. package/dist/runtime/render/localized-copy.d.ts +86 -0
  144. package/dist/runtime/render/localized-copy.js +129 -0
  145. package/dist/runtime/render/product-listing.d.ts +11 -0
  146. package/dist/runtime/render/product-listing.js +243 -0
  147. package/dist/runtime/render/section-actions.d.ts +66 -0
  148. package/dist/runtime/render/section-actions.js +202 -0
  149. package/dist/runtime/render/starter.d.ts +11 -0
  150. package/dist/runtime/render/starter.js +81 -0
  151. package/dist/runtime/seo/head.d.ts +115 -0
  152. package/dist/runtime/seo/head.js +281 -0
  153. package/dist/runtime/seo/structured-data.d.ts +83 -0
  154. package/dist/runtime/seo/structured-data.js +252 -0
  155. package/dist/runtime/shell/PageShell.d.ts +18 -0
  156. package/dist/runtime/shell/PageShell.js +113 -0
  157. package/dist/runtime/shell/RuntimeBridge.d.ts +14 -0
  158. package/dist/runtime/shell/RuntimeBridge.js +93 -0
  159. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  160. package/dist/runtime/shell/overlay-state.js +59 -0
  161. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  162. package/dist/runtime/shell/preview-mode.js +11 -0
  163. package/dist/runtime/shell/spa-router.d.ts +14 -0
  164. package/dist/runtime/shell/spa-router.js +76 -0
  165. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  166. package/dist/runtime/shell/url-redirects.js +37 -0
  167. package/dist/runtime/slots.d.ts +74 -0
  168. package/dist/runtime/slots.js +16 -0
  169. package/dist/runtime.d.ts +34 -0
  170. package/dist/runtime.js +40 -0
  171. package/dist/sdk/app-block.d.ts +29 -0
  172. package/dist/sdk/app-block.js +22 -0
  173. package/dist/sdk/index.d.ts +26 -0
  174. package/dist/sdk/index.js +26 -0
  175. package/dist/sdk/referrals.d.ts +62 -0
  176. package/dist/sdk/referrals.js +20 -0
  177. package/dist/sdk/rewards.d.ts +85 -0
  178. package/dist/sdk/rewards.js +29 -0
  179. package/dist/sdk/runtime-context.d.ts +202 -0
  180. package/dist/sdk/runtime-context.js +73 -0
  181. package/dist/sdk/schema.d.ts +206 -0
  182. package/dist/sdk/schema.js +121 -0
  183. package/dist/sdk/server-render.d.ts +8 -0
  184. package/dist/sdk/server-render.js +12 -0
  185. package/dist/sdk/store-lookup.d.ts +27 -0
  186. package/dist/sdk/store-lookup.js +29 -0
  187. package/dist/sdk/store.d.ts +149 -0
  188. package/dist/sdk/store.js +5 -0
  189. package/dist/sdk/sx.d.ts +40 -0
  190. package/dist/sdk/sx.js +112 -0
  191. package/dist/sdk/theme.d.ts +191 -0
  192. package/dist/sdk/theme.js +10 -0
  193. package/dist/sdk/types.d.ts +757 -0
  194. package/dist/sdk/types.js +7 -0
  195. package/dist/server.d.ts +111 -0
  196. package/dist/server.js +533 -0
  197. package/docs/headless-api.md +220 -0
  198. package/package.json +76 -22
  199. package/dist/index.js.map +0 -1
  200. package/dist/ssg-BZ5FYTw7.js +0 -1802
  201. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  202. package/dist/ssg.js +0 -8
  203. package/dist/ssg.js.map +0 -1
  204. package/dist/types/cart.d.ts +0 -86
  205. package/dist/types/data.d.ts +0 -357
  206. package/dist/types/editor.d.ts +0 -5
  207. package/dist/types/index.d.ts +0 -20
  208. package/dist/types/preview-bridge.d.ts +0 -9
  209. package/dist/types/storefront.d.ts +0 -333
  210. package/dist/types/types.d.ts +0 -44
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The ABI page as Nova's runtime reads it — shared by the server entry and the browser entry so
3
+ * both build the identical tree.
4
+ */
5
+ import type { ContentNode } from '../runtime/kit/types.js';
6
+ /**
7
+ * The ABI's PageDoc regions → the flat section list, regions in template order, each node tagged with its area. A
8
+ * node of any other region (a section group the theme's layout declares: an `aside`, a custom group) renders in that
9
+ * order inside <main> as before, and keeps its region id (`region`, `data-tq-region` on its wrapper) so the theme's
10
+ * CSS can place the group, e.g. as a sidebar.
11
+ */
12
+ export declare function nodesOf(regions: readonly {
13
+ region?: string;
14
+ id?: string;
15
+ sections: readonly unknown[];
16
+ }[]): ContentNode[];
17
+ /**
18
+ * The route names a resource the store does not have (unknown page, collection, product, blog):
19
+ * the page answers 404, so the shopper sees the theme's not-found section in place of the
20
+ * template's main sections (which would otherwise render nothing). Header and footer stay.
21
+ * Live pages only — the editor canvas keeps the template it is editing.
22
+ */
23
+ export declare function notFoundTree(nodes: readonly ContentNode[]): ContentNode[];
24
+ /**
25
+ * The location (path + query) the store layer routes on: the canonical path, plus `q` (and its
26
+ * `sort`) on search, a listing's sort / filters, `cart_link` on the cart and `variant` on a product (page-data.ts pageParamsOf).
27
+ */
28
+ export declare function locationOf(canonical: string, params: Readonly<Record<string, string>>, listing?: string): string;
@@ -0,0 +1,57 @@
1
+ import { getThemeBundle } from '../runtime/slots.js';
2
+ /** The theme's `templates/404.json`, from the bundle the entry handed the runtime (`ThemeBundle.templates`). */
3
+ function notFoundTemplate() {
4
+ const hit = Object.entries(getThemeBundle().templates).find(([path]) => /(^|\/)404\.json$/.test(path));
5
+ return (hit?.[1]?.default ?? {});
6
+ }
7
+ /** Region → the layout area the runtime's SectionTree splits on (header zone → <main> → footer zone). */
8
+ const AREA = { announcement: 'header', header: 'header', footer: 'footer' };
9
+ /** The regions the runtime places by themselves: the header zone, the page's own `main`, the footer zone. */
10
+ const PLACED = new Set(['announcement', 'header', 'main', 'footer']);
11
+ /**
12
+ * The ABI's PageDoc regions → the flat section list, regions in template order, each node tagged with its area. A
13
+ * node of any other region (a section group the theme's layout declares: an `aside`, a custom group) renders in that
14
+ * order inside <main> as before, and keeps its region id (`region`, `data-tq-region` on its wrapper) so the theme's
15
+ * CSS can place the group, e.g. as a sidebar.
16
+ */
17
+ export function nodesOf(regions) {
18
+ return regions.flatMap((r) => {
19
+ const id = r.region ?? r.id ?? '';
20
+ const group = id && !PLACED.has(id) ? { region: id } : {};
21
+ return r.sections.map((n) => ({ ...n, area: AREA[id] ?? 'template', ...group }));
22
+ });
23
+ }
24
+ /**
25
+ * The route names a resource the store does not have (unknown page, collection, product, blog):
26
+ * the page answers 404, so the shopper sees the theme's not-found section in place of the
27
+ * template's main sections (which would otherwise render nothing). Header and footer stay.
28
+ * Live pages only — the editor canvas keeps the template it is editing.
29
+ */
30
+ export function notFoundTree(nodes) {
31
+ const section = (notFoundTemplate().sections ?? []).find((s) => s.type === 'not-found');
32
+ const main = { type: 'not-found', id: 'route-missing', settings: { ...(section?.settings ?? {}) }, area: 'template' };
33
+ return [...nodes.filter((n) => n.area === 'header'), main, ...nodes.filter((n) => n.area === 'footer')];
34
+ }
35
+ /**
36
+ * The location (path + query) the store layer routes on: the canonical path, plus `q` (and its
37
+ * `sort`) on search, a listing's sort / filters, `cart_link` on the cart and `variant` on a product (page-data.ts pageParamsOf).
38
+ */
39
+ export function locationOf(canonical, params, listing = '') {
40
+ let path = '/';
41
+ try {
42
+ path = new URL(canonical).pathname || '/';
43
+ }
44
+ catch {
45
+ path = '/';
46
+ }
47
+ if (typeof params.q === 'string' && params.q) {
48
+ const sort = typeof params.sort === 'string' && params.sort ? `&sort=${encodeURIComponent(params.sort)}` : '';
49
+ return `${path}?q=${encodeURIComponent(params.q)}${sort}`;
50
+ }
51
+ // A collection page's sort / filters (listing-query.ts): the listing reads them from the location.
52
+ const cartLink = typeof params.cart_link === 'string' && params.cart_link ? `cart_link=${encodeURIComponent(params.cart_link)}` : '';
53
+ // A product URL's `?variant=` (page-data.ts variantOf): the product page opens on that variant.
54
+ const variant = typeof params.variant === 'string' && params.variant ? `variant=${encodeURIComponent(params.variant)}` : '';
55
+ const query = [listing, cartLink, variant].filter(Boolean).join('&');
56
+ return query ? `${path}?${query}` : path;
57
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The referral program over Theme ABI v2 (army #7751): `useReferrals()` driven by the data ops `referral.state` and
3
+ * `referral.offer` (the `?ref=` code) and the actions `referral.claim` and `referral.invite`, which the host answers
4
+ * from studio-accounts (`/account/referrals/*`) with the shopper's session. A `?ref=CODE` visit keeps the code for
5
+ * the session (sessionStorage) and in the first-party session cookie `tanqory_ref`, a claimed friend code in
6
+ * `tanqory_ref_claim`; studio-checkouts reads both (the `ref` attribute, the friend's code applied). Browser only;
7
+ * a host without the ops, or referrals off, is the same as off.
8
+ */
9
+ import { type ReactNode } from 'react';
10
+ import { type FriendOffer, type ReferralState } from '../sdk/referrals.js';
11
+ import type { AbiRemote } from './wire.js';
12
+ export declare const REF_COOKIE = "tanqory_ref";
13
+ export declare const CLAIM_COOKIE = "tanqory_ref_claim";
14
+ /** The `?ref=` code of this visit, else the one kept earlier this session; kept for the session either way. */
15
+ export declare function keepRefCode(search: string): string | null;
16
+ /** The `referral.state` answer when it is the shopper's own link, else null. */
17
+ export declare function referralStateOf(data: unknown): ReferralState | null;
18
+ /** The `referral.offer` answer when it is an offer for this shopper, else null. */
19
+ export declare function friendOfferOf(data: unknown, claimedCode: string | null): FriendOffer | null;
20
+ export declare function AbiReferralsProvider({ remote, children }: {
21
+ remote: AbiRemote | null;
22
+ children: ReactNode;
23
+ }): JSX.Element;
@@ -0,0 +1,89 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * The referral program over Theme ABI v2 (army #7751): `useReferrals()` driven by the data ops `referral.state` and
4
+ * `referral.offer` (the `?ref=` code) and the actions `referral.claim` and `referral.invite`, which the host answers
5
+ * from studio-accounts (`/account/referrals/*`) with the shopper's session. A `?ref=CODE` visit keeps the code for
6
+ * the session (sessionStorage) and in the first-party session cookie `tanqory_ref`, a claimed friend code in
7
+ * `tanqory_ref_claim`; studio-checkouts reads both (the `ref` attribute, the friend's code applied). Browser only;
8
+ * a host without the ops, or referrals off, is the same as off.
9
+ */
10
+ import { useCallback, useEffect, useMemo, useState } from 'react';
11
+ import { ReferralsContext } from '../sdk/referrals.js';
12
+ export const REF_COOKIE = 'tanqory_ref';
13
+ export const CLAIM_COOKIE = 'tanqory_ref_claim';
14
+ const REF_KEY = 'nova:ref';
15
+ const CLAIMED_KEY = 'nova:ref-claimed';
16
+ // store-api's link and claim codes: letters, digits and dashes.
17
+ const CODE = /^[A-Za-z0-9-]{3,40}$/;
18
+ function session(key, value) {
19
+ try {
20
+ if (value !== undefined)
21
+ sessionStorage.setItem(key, value);
22
+ return sessionStorage.getItem(key);
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ function setSessionCookie(name, value) {
29
+ document.cookie = `${name}=${encodeURIComponent(value)}; Path=/; SameSite=Lax${location.protocol === 'https:' ? '; Secure' : ''}`;
30
+ }
31
+ /** The `?ref=` code of this visit, else the one kept earlier this session; kept for the session either way. */
32
+ export function keepRefCode(search) {
33
+ const fromUrl = new URLSearchParams(search).get('ref')?.trim() ?? '';
34
+ const code = CODE.test(fromUrl) ? fromUrl : session(REF_KEY) ?? '';
35
+ if (!CODE.test(code))
36
+ return null;
37
+ session(REF_KEY, code);
38
+ setSessionCookie(REF_COOKIE, code);
39
+ return code;
40
+ }
41
+ /** The `referral.state` answer when it is the shopper's own link, else null. */
42
+ export function referralStateOf(data) {
43
+ const s = data;
44
+ return s && s.enabled === true && typeof s.shareUrl === 'string' && s.shareUrl && s.offer && s.stats ? s : null;
45
+ }
46
+ /** The `referral.offer` answer when it is an offer for this shopper, else null. */
47
+ export function friendOfferOf(data, claimedCode) {
48
+ const o = data;
49
+ return o && o.enabled === true && typeof o.code === 'string' && o.offer ? { ...o, claimedCode } : null;
50
+ }
51
+ const claimError = (code) => code === 'self' || code === 'referral_self_claim' ? 'self' : code === 'email' || code === 'referral_email_invalid' ? 'email' : 'failed';
52
+ export function AbiReferralsProvider({ remote, children }) {
53
+ const [state, setState] = useState(null);
54
+ const [friend, setFriend] = useState(null);
55
+ useEffect(() => {
56
+ if (!remote)
57
+ return;
58
+ let cancelled = false;
59
+ remote
60
+ .data('referral.state', [])
61
+ .then((d) => !cancelled && setState(referralStateOf(d)))
62
+ .catch(() => { });
63
+ const code = keepRefCode(window.location.search);
64
+ if (code) {
65
+ remote
66
+ .data('referral.offer', [code])
67
+ .then((d) => !cancelled && setFriend(friendOfferOf(d, session(CLAIMED_KEY))))
68
+ .catch(() => { });
69
+ }
70
+ return () => {
71
+ cancelled = true;
72
+ };
73
+ }, [remote]);
74
+ const claim = useCallback(async (email) => {
75
+ if (!remote || !friend)
76
+ return { ok: false, error: 'failed' };
77
+ const env = await remote.action('referral.claim', [{ code: friend.code, email: email.trim() }]).catch(() => null);
78
+ const code = env?.ok ? env.data?.code : null;
79
+ if (typeof code !== 'string' || !CODE.test(code))
80
+ return { ok: false, error: env && !env.ok ? claimError(env.error.code) : 'failed' };
81
+ session(CLAIMED_KEY, code);
82
+ setSessionCookie(CLAIM_COOKIE, code);
83
+ setFriend((f) => f && { ...f, claimedCode: code });
84
+ return { ok: true, code };
85
+ }, [remote, friend]);
86
+ const invite = useCallback(async (email) => !!remote && remote.action('referral.invite', [{ email: email.trim() }]).then((env) => env.ok, () => false), [remote]);
87
+ const value = useMemo(() => ({ state, friend, claim, invite }), [state, friend, claim, invite]);
88
+ return _jsx(ReferralsContext.Provider, { value: value, children: children });
89
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The loyalty program over Theme ABI v2 (army #7749): `useRewards()` driven by
3
+ * `GET /_tq/data/loyalty.state`, `POST /_tq/actions/loyalty.redeem` and `POST /_tq/actions/loyalty.join`.
4
+ *
5
+ * - The host answers them from studio-accounts (`/account/rewards/state`, `/redeem`, `/join`) with
6
+ * the shopper's session, which the theme never sees.
7
+ * - Browser only: the server render and the editor canvas pass `remote` null, so the state stays
8
+ * null there and the launcher and hints render nothing (SSR and hydration agree).
9
+ * - A host that does not offer `loyalty.state` yet, or a store with loyalty off, is the same as off.
10
+ */
11
+ import { type ReactNode } from 'react';
12
+ import { type RewardsState } from '../sdk/rewards.js';
13
+ import type { AbiRemote } from './wire.js';
14
+ /**
15
+ * Whether the storefront host answers the `loyalty.*` and `referral.*` ops. It does not yet: Theme ABI v2
16
+ * (2.0.0-alpha.11) has no loyalty or referral capability, and the edge answers those ops 404. Asking on every page
17
+ * would log a failed request in every shopper's console, and conformance fails the build on that (§10.5). Until
18
+ * the ABI and the edge offer them, the browser entry never asks (main.abi.tsx). The launcher, the earn hints and the
19
+ * share panel stay hidden, the same as for a store with the program off. A `?ref=` code is still kept for checkout.
20
+ */
21
+ export declare const HOST_OFFERS_LOYALTY = false;
22
+ /** The `loyalty.state` answer when it is a program the shopper can see, else null. */
23
+ export declare function rewardsStateOf(data: unknown): RewardsState | null;
24
+ export declare function AbiRewardsProvider({ remote, children }: {
25
+ remote: AbiRemote | null;
26
+ children: ReactNode;
27
+ }): JSX.Element;
@@ -0,0 +1,82 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * The loyalty program over Theme ABI v2 (army #7749): `useRewards()` driven by
4
+ * `GET /_tq/data/loyalty.state`, `POST /_tq/actions/loyalty.redeem` and `POST /_tq/actions/loyalty.join`.
5
+ *
6
+ * - The host answers them from studio-accounts (`/account/rewards/state`, `/redeem`, `/join`) with
7
+ * the shopper's session, which the theme never sees.
8
+ * - Browser only: the server render and the editor canvas pass `remote` null, so the state stays
9
+ * null there and the launcher and hints render nothing (SSR and hydration agree).
10
+ * - A host that does not offer `loyalty.state` yet, or a store with loyalty off, is the same as off.
11
+ */
12
+ import { useCallback, useEffect, useMemo, useState } from 'react';
13
+ import { RewardsContext } from '../sdk/rewards.js';
14
+ import { AbiReferralsProvider } from './referrals.js';
15
+ /**
16
+ * Whether the storefront host answers the `loyalty.*` and `referral.*` ops. It does not yet: Theme ABI v2
17
+ * (2.0.0-alpha.11) has no loyalty or referral capability, and the edge answers those ops 404. Asking on every page
18
+ * would log a failed request in every shopper's console, and conformance fails the build on that (§10.5). Until
19
+ * the ABI and the edge offer them, the browser entry never asks (main.abi.tsx). The launcher, the earn hints and the
20
+ * share panel stay hidden, the same as for a store with the program off. A `?ref=` code is still kept for checkout.
21
+ */
22
+ export const HOST_OFFERS_LOYALTY = false;
23
+ /** The `loyalty.state` answer when it is a program the shopper can see, else null. */
24
+ export function rewardsStateOf(data) {
25
+ const s = data;
26
+ return s && s.enabled === true && s.program && typeof s.program === 'object' ? { ...s, ways: Array.isArray(s.ways) ? s.ways : [] } : null;
27
+ }
28
+ /** A fresh idempotency key per redeem tap: a retried request never spends the points twice. */
29
+ function redeemKey() {
30
+ const c = globalThis.crypto;
31
+ return c && typeof c.randomUUID === 'function' ? c.randomUUID() : `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 14)}`;
32
+ }
33
+ export function AbiRewardsProvider({ remote, children }) {
34
+ const [state, setState] = useState(null);
35
+ useEffect(() => {
36
+ if (!remote)
37
+ return;
38
+ let cancelled = false;
39
+ remote
40
+ .data('loyalty.state', [])
41
+ .then((d) => !cancelled && setState(rewardsStateOf(d)))
42
+ .catch(() => { });
43
+ return () => {
44
+ cancelled = true;
45
+ };
46
+ }, [remote]);
47
+ const redeem = useCallback(async (rewardId) => {
48
+ if (!remote)
49
+ return { ok: false, error: 'failed' };
50
+ try {
51
+ const env = await remote.action('loyalty.redeem', [{ rewardId, key: redeemKey() }]);
52
+ const data = (env.ok ? env.data : null);
53
+ if (env.ok && data?.redemption?.code) {
54
+ const next = rewardsStateOf(data.state);
55
+ if (next)
56
+ setState(next);
57
+ return { ok: true, code: data.redemption.code };
58
+ }
59
+ return { ok: false, error: !env.ok && env.error.code === 'loyalty_insufficient_points' ? 'insufficient' : 'failed' };
60
+ }
61
+ catch {
62
+ return { ok: false, error: 'failed' };
63
+ }
64
+ }, [remote]);
65
+ const join = useCallback(async () => {
66
+ if (!remote)
67
+ return false;
68
+ try {
69
+ const env = await remote.action('loyalty.join', []);
70
+ const next = env.ok ? rewardsStateOf(env.data?.state) : null;
71
+ if (next)
72
+ setState(next);
73
+ return env.ok;
74
+ }
75
+ catch {
76
+ return false;
77
+ }
78
+ }, [remote]);
79
+ const value = useMemo(() => ({ state, redeem, join }), [state, redeem, join]);
80
+ // The referral program (army #7751) rides on the same remote, so the editor canvas has neither.
81
+ return _jsx(RewardsContext.Provider, { value: value, children: _jsx(AbiReferralsProvider, { remote: remote, children: children }) });
82
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The home page's head under Theme ABI v2: what a search result and a shared link show for the store.
3
+ *
4
+ * Source order, each field on its own:
5
+ * title the store's home page title (`Shop.seo.title`) → the shop name (computeHead)
6
+ * description `Shop.seo.description` → `Shop.description` → one sentence from the shop name
7
+ * image `Shop.seo.image` → the brand's square logo → its logo → the home hero's image,
8
+ * only an absolute https: URL (a scraper cannot resolve anything else)
9
+ *
10
+ * `Shop.seo` is an optional ABI field the platform may not send yet; lib/abi/convert.ts `shopSeo`
11
+ * reads it defensively, so its absence leaves the fallbacks.
12
+ */
13
+ import type { Shop } from '../runtime/kit/storefront.js';
14
+ export interface HomeHead {
15
+ title?: string;
16
+ description: string;
17
+ image: string;
18
+ imageAlt?: string;
19
+ imageWidth?: number;
20
+ imageHeight?: number;
21
+ }
22
+ interface Node {
23
+ type?: string;
24
+ settings?: Record<string, unknown>;
25
+ blocks?: readonly Node[];
26
+ }
27
+ /** The first hero's image on the page (its background image setting), when it is an absolute https: URL. */
28
+ export declare function heroImageOf(nodes: readonly Node[]): string;
29
+ export declare function homeHead(shop: Shop, shopName: string, nodes: readonly Node[], sentence: string): HomeHead;
30
+ /** One `<link rel="alternate" hreflang>` of a page. */
31
+ export interface HreflangAlternate {
32
+ hreflang: string;
33
+ href: string;
34
+ }
35
+ /**
36
+ * The language alternates of a page (Theme ABI v2 §2, "Market and language selection"): the platform serves every
37
+ * published language on the same URL and picks one from `?locale=<language>`, so the alternate for a language is
38
+ * the page's canonical URL with that parameter. `x-default` is the canonical URL itself, where the gateway applies
39
+ * the shopper's remembered choice, else the store's default language.
40
+ *
41
+ * `canonical` is `ctx.route.canonical` (absolute, same origin, no query: ABI §2.4); `languages` is
42
+ * `ctx.locale.availableLanguages`. A store that publishes fewer than two languages has no alternates.
43
+ * Markets are not alternates here: a market changes prices and currency, not the page's language, and the ABI
44
+ * defines no per-market URL other than the shopper's `?country=` choice.
45
+ */
46
+ export declare function hreflangAlternates(canonical: string, languages: readonly string[]): HreflangAlternate[];
47
+ export {};
@@ -0,0 +1,68 @@
1
+ const https = (url) => {
2
+ if (typeof url !== 'string' || !url.trim())
3
+ return '';
4
+ try {
5
+ const u = new URL(url.trim());
6
+ return u.protocol === 'https:' && u.hostname ? u.href : '';
7
+ }
8
+ catch {
9
+ return '';
10
+ }
11
+ };
12
+ /** The first hero's image on the page (its background image setting), when it is an absolute https: URL. */
13
+ export function heroImageOf(nodes) {
14
+ for (const n of nodes) {
15
+ if (n.type === 'hero') {
16
+ const url = https(n.settings?.backgroundImage);
17
+ if (url)
18
+ return url;
19
+ }
20
+ }
21
+ return '';
22
+ }
23
+ export function homeHead(shop, shopName, nodes, sentence) {
24
+ const seo = shop.seo;
25
+ const description = seo?.description || (shop.description ?? '').trim() || (sentence ? sentence.split('{name}').join(shopName) : '');
26
+ const own = https(seo?.image?.url);
27
+ const image = own || https(shop.brand?.squareLogo?.url) || https(shop.brand?.logo?.url) || heroImageOf(nodes);
28
+ return {
29
+ ...(seo?.title ? { title: seo.title } : {}),
30
+ description,
31
+ image,
32
+ ...(own && seo?.image?.altText ? { imageAlt: seo.image.altText } : {}),
33
+ ...(own && seo?.image?.width ? { imageWidth: seo.image.width } : {}),
34
+ ...(own && seo?.image?.height ? { imageHeight: seo.image.height } : {}),
35
+ };
36
+ }
37
+ /**
38
+ * The language alternates of a page (Theme ABI v2 §2, "Market and language selection"): the platform serves every
39
+ * published language on the same URL and picks one from `?locale=<language>`, so the alternate for a language is
40
+ * the page's canonical URL with that parameter. `x-default` is the canonical URL itself, where the gateway applies
41
+ * the shopper's remembered choice, else the store's default language.
42
+ *
43
+ * `canonical` is `ctx.route.canonical` (absolute, same origin, no query: ABI §2.4); `languages` is
44
+ * `ctx.locale.availableLanguages`. A store that publishes fewer than two languages has no alternates.
45
+ * Markets are not alternates here: a market changes prices and currency, not the page's language, and the ABI
46
+ * defines no per-market URL other than the shopper's `?country=` choice.
47
+ */
48
+ export function hreflangAlternates(canonical, languages) {
49
+ const seen = new Set();
50
+ const langs = [];
51
+ for (const l of languages) {
52
+ if (typeof l !== 'string' || !/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(l))
53
+ continue;
54
+ const k = l.toLowerCase();
55
+ if (seen.has(k))
56
+ continue;
57
+ seen.add(k);
58
+ langs.push(l);
59
+ }
60
+ if (langs.length < 2 || !/^https?:\/\//.test(canonical))
61
+ return [];
62
+ const base = canonical.split('#')[0];
63
+ const sep = base.includes('?') ? '&' : '?';
64
+ return [
65
+ ...langs.map((l) => ({ hreflang: l, href: `${base}${sep}locale=${encodeURIComponent(l)}` })),
66
+ { hreflang: 'x-default', href: base },
67
+ ];
68
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The page shell under Theme ABI v2 — what platform/runtime/shell/PageShell.tsx is for the
3
+ * redesign, minus everything the ABI gives to the platform:
4
+ *
5
+ * - no soft navigation: under ABI v2 every navigation is a full page load, because a template's
6
+ * content is the store's revision, which only the server has (the theme's own starter
7
+ * templates would render the wrong page);
8
+ * - no tracking pixels and no analytics beacons: the platform owns both (§4, §10.5);
9
+ * - the plane (preview vs live) is `ctx.mode`, handed in by the entry — never read from the URL.
10
+ *
11
+ * Provider order is the redesign's: theme Provider → StoreProvider → OverlayProvider →
12
+ * RuntimeBridge → theme Layout → the page's sections.
13
+ */
14
+ import type { ReactNode } from 'react';
15
+ export declare function AbiShell({ location, locale, contentLanguage, settings, preview, labels, children }: {
16
+ location: string;
17
+ locale: string;
18
+ contentLanguage?: string;
19
+ settings: Record<string, unknown>;
20
+ preview: boolean;
21
+ labels?: Readonly<Record<string, string>>;
22
+ children: ReactNode;
23
+ }): JSX.Element;
@@ -0,0 +1,10 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { getThemeBundle } from '../runtime/slots.js';
3
+ import { StoreProvider } from '../runtime/data/StoreProvider.js';
4
+ import { OverlayProvider } from '../runtime/shell/overlay-state.js';
5
+ import { RuntimeBridge } from '../runtime/shell/RuntimeBridge.js';
6
+ export function AbiShell({ location, locale, contentLanguage, settings, preview, labels, children }) {
7
+ const { Provider, Layout } = getThemeBundle().theme;
8
+ const mode = preview ? 'editor' : 'storefront';
9
+ return (_jsx(Provider, { mode: mode, locale: locale, contentLanguage: contentLanguage, settings: settings, ...(labels && Object.keys(labels).length ? { labels } : {}), children: _jsx(StoreProvider, { location: location, locale: locale, settings: settings, ...(labels && Object.keys(labels).length ? { labels } : {}), children: _jsx(OverlayProvider, { children: _jsx(RuntimeBridge, { mode: mode, locale: locale, settings: settings, children: _jsx(Layout, { children: children }) }) }) }) }));
10
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * The page data as it travels in the hydration block (`<script id="tq-state">`, server.tsx → client.tsx), without its
3
+ * second copy of the listing's products.
4
+ *
5
+ * page-data.ts keeps every product of a collection twice: in `collections[h].products` (the listing's order) and in
6
+ * `products[handle]` (what a product card or block looks up by handle). On Dev's 2,972-product ick39, /collections/all
7
+ * carried the same 50 products in both: 208 KB of a 605 KB page. Here a collection's product that is byte-for-byte the
8
+ * page's `products[handle]` travels as `{ "$tqProduct": handle }`, and the browser puts the product back before
9
+ * anything reads the data, so the hydrated state is the one the server rendered with (a fresh copy per place, as
10
+ * JSON.parse gave before). A product that differs from its `products` entry travels as it is.
11
+ */
12
+ import type { PageData } from './page-data.js';
13
+ export declare const PRODUCT_REF = "$tqProduct";
14
+ /** The page data with each collection product that equals its `products[handle]` replaced by a reference. */
15
+ export declare function packPageData(pd: PageData): PageData;
16
+ /** The page data as the server had it: every reference back to a copy of its `products[handle]`. */
17
+ export declare function unpackPageData(pd: PageData): PageData;
@@ -0,0 +1,43 @@
1
+ export const PRODUCT_REF = '$tqProduct';
2
+ const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
3
+ const isRef = (v) => typeof v === 'object' && v !== null && !Array.isArray(v) && Object.keys(v).length === 1 && typeof v[PRODUCT_REF] === 'string';
4
+ /** The page data with each collection product that equals its `products[handle]` replaced by a reference. */
5
+ export function packPageData(pd) {
6
+ const products = pd.products ?? {};
7
+ const text = new Map();
8
+ const same = (p) => {
9
+ if (typeof p?.handle !== 'string' || !has(products, p.handle))
10
+ return false;
11
+ let t = text.get(p.handle);
12
+ if (t === undefined)
13
+ text.set(p.handle, (t = JSON.stringify(products[p.handle])));
14
+ return JSON.stringify(p) === t;
15
+ };
16
+ let changed = false;
17
+ const collections = {};
18
+ for (const [h, c] of Object.entries(pd.collections ?? {})) {
19
+ if (!c || !Array.isArray(c.products) || c.products.length === 0) {
20
+ collections[h] = c;
21
+ continue;
22
+ }
23
+ const list = c.products.map((p) => (same(p) ? { [PRODUCT_REF]: p.handle } : p));
24
+ if (list.some((p, i) => p !== c.products[i]))
25
+ changed = true;
26
+ collections[h] = { ...c, products: list };
27
+ }
28
+ return changed ? { ...pd, collections } : pd;
29
+ }
30
+ /** The page data as the server had it: every reference back to a copy of its `products[handle]`. */
31
+ export function unpackPageData(pd) {
32
+ const products = pd?.products ?? {};
33
+ for (const c of Object.values(pd?.collections ?? {})) {
34
+ if (!c || !Array.isArray(c.products))
35
+ continue;
36
+ for (let i = 0; i < c.products.length; i++) {
37
+ const p = c.products[i];
38
+ if (isRef(p) && has(products, p[PRODUCT_REF]))
39
+ c.products[i] = structuredClone(products[p[PRODUCT_REF]]);
40
+ }
41
+ }
42
+ return pd;
43
+ }
@@ -0,0 +1,38 @@
1
+ /** Mirrors render-context.v2.d.ts `WireEnvelope` (not yet in theme-abi 2.0.0-alpha.2). */
2
+ export type WireEnvelope<T> = {
3
+ ok: true;
4
+ data: T;
5
+ dataVersion: string;
6
+ } | {
7
+ ok: false;
8
+ error: {
9
+ code: string;
10
+ message?: string;
11
+ requestId: string;
12
+ refusal?: unknown;
13
+ };
14
+ data?: T;
15
+ };
16
+ export interface AbiRemote {
17
+ /** Resolves with `data` of an ok envelope; rejects with AbiWireError otherwise. */
18
+ data(op: string, args: readonly unknown[]): Promise<unknown>;
19
+ /** Resolves with the full envelope, so a caller can read `data` on a conflict. */
20
+ action(name: `${string}.${string}`, args: readonly unknown[]): Promise<WireEnvelope<unknown>>;
21
+ }
22
+ export declare class AbiWireError extends Error {
23
+ readonly status: number;
24
+ readonly code: string | null;
25
+ /** The server's `Retry-After`, in ms from now; null when it sent none (or one we cannot read). */
26
+ readonly retryAfterMs: number | null;
27
+ constructor(status: number, code: string | null,
28
+ /** The server's `Retry-After`, in ms from now; null when it sent none (or one we cannot read). */
29
+ retryAfterMs?: number | null);
30
+ }
31
+ /**
32
+ * `Retry-After` (RFC 9110 §10.2.3) as ms from `now`: delay-seconds or an HTTP-date. A rate-limited
33
+ * `/_tq/data` answers `429` with `retry-after: 30`; the cart waits that long rather than hammering
34
+ * the same budget (QA test-2 F1).
35
+ */
36
+ export declare function parseRetryAfter(value: string | null, now?: number): number | null;
37
+ /** Browser-only; the routes are relative to the page's own origin. */
38
+ export declare function createAbiRemote(): AbiRemote;
@@ -0,0 +1,84 @@
1
+ import { canonicalize } from './jcs.js';
2
+ /** `PLATFORM_ROUTES` values (the type pins them to the contract; scripts/abi/build.mjs re-checks at build). */
3
+ const DATA = '/_tq/data/';
4
+ const ACTIONS = '/_tq/actions/';
5
+ const MAX_ACTION_BYTES = 8 * 1024;
6
+ export class AbiWireError extends Error {
7
+ constructor(status, code,
8
+ /** The server's `Retry-After`, in ms from now; null when it sent none (or one we cannot read). */
9
+ retryAfterMs = null) {
10
+ super(`[nova] /_tq request failed: HTTP ${status}${code ? ` ${code}` : ''}`);
11
+ this.status = status;
12
+ this.code = code;
13
+ this.retryAfterMs = retryAfterMs;
14
+ this.name = 'AbiWireError';
15
+ }
16
+ }
17
+ /**
18
+ * `Retry-After` (RFC 9110 §10.2.3) as ms from `now`: delay-seconds or an HTTP-date. A rate-limited
19
+ * `/_tq/data` answers `429` with `retry-after: 30`; the cart waits that long rather than hammering
20
+ * the same budget (QA test-2 F1).
21
+ */
22
+ export function parseRetryAfter(value, now = Date.now()) {
23
+ if (value === null)
24
+ return null;
25
+ const v = value.trim();
26
+ if (/^\d+$/.test(v))
27
+ return Number(v) * 1000;
28
+ const at = Date.parse(v);
29
+ return Number.isNaN(at) ? null : Math.max(0, at - now);
30
+ }
31
+ function base64url(text) {
32
+ const bytes = new TextEncoder().encode(text);
33
+ let bin = '';
34
+ for (const b of bytes)
35
+ bin += String.fromCharCode(b);
36
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
37
+ }
38
+ function csrfToken() {
39
+ return document.querySelector('meta[name="tq-csrf"]')?.content || null;
40
+ }
41
+ async function envelope(res) {
42
+ let body = null;
43
+ try {
44
+ body = await res.json();
45
+ }
46
+ catch {
47
+ body = null;
48
+ }
49
+ if (body && typeof body === 'object' && 'ok' in body)
50
+ return body;
51
+ return { ok: false, error: { code: res.ok ? 'invalid_envelope' : 'unavailable', requestId: '' } };
52
+ }
53
+ /** Browser-only; the routes are relative to the page's own origin. */
54
+ export function createAbiRemote() {
55
+ return {
56
+ async data(op, args) {
57
+ const qs = args.length ? `?a=${base64url(canonicalize(args))}` : '';
58
+ const res = await fetch(`${DATA}${op}${qs}`, { method: 'GET', credentials: 'same-origin', headers: { accept: 'application/json' } });
59
+ const env = await envelope(res);
60
+ if (!env.ok)
61
+ throw new AbiWireError(res.status, env.error.code, parseRetryAfter(res.headers.get('retry-after')));
62
+ return env.data;
63
+ },
64
+ async action(name, args) {
65
+ const body = JSON.stringify({ v: 2, args });
66
+ if (new TextEncoder().encode(body).length > MAX_ACTION_BYTES)
67
+ throw new AbiWireError(413, 'invalid_argument');
68
+ const post = async () => {
69
+ const token = csrfToken();
70
+ return fetch(`${ACTIONS}${name}`, {
71
+ method: 'POST',
72
+ credentials: 'same-origin',
73
+ headers: { 'content-type': 'application/json', accept: 'application/json', ...(token ? { 'x-tq-csrf': token } : {}) },
74
+ body,
75
+ });
76
+ };
77
+ let env = await envelope(await post());
78
+ // §4.1: a first visit has no CSRF cookie yet — the token is re-read once and the call retried.
79
+ if (!env.ok && env.error.code === 'csrf_failed')
80
+ env = await envelope(await post());
81
+ return env;
82
+ },
83
+ };
84
+ }