@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,9 @@
1
+ /**
2
+ * The v1 page shell in the glob-map shape `mount()` takes, plus `sectionModules()` (./sections.ts), re-exported
3
+ * here for the callers that import it from this module.
4
+ */
5
+ import PageShell from '../shell/PageShell.js';
6
+ export { sectionModules } from './sections.js';
7
+ export declare function shellModules(): Record<string, {
8
+ default: typeof PageShell;
9
+ }>;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * The v1 page shell in the glob-map shape `mount()` takes, plus `sectionModules()` (./sections.ts), re-exported
3
+ * here for the callers that import it from this module.
4
+ */
5
+ import PageShell from '../shell/PageShell.js';
6
+ export { sectionModules } from './sections.js';
7
+ export function shellModules() {
8
+ return { './runtime/PageShell.tsx': { default: PageShell } };
9
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * What the runtime registers, in the glob-map shape `mount()` / `renderStorefrontHTML()` take
3
+ * (`{ path: { default } }`).
4
+ *
5
+ * Every theme section renders through SectionRenderer (`raw`: it receives the saved node). Custom
6
+ * `sections/*.tsx` (`defineSection` from the old API — the AI section generator writes them) register LAST,
7
+ * so one with the same name overrides the theme's section — which is also what studio-api's catalog does.
8
+ *
9
+ * Kept apart from `shellModules()` (./register.ts): the ABI entries (`createRender`, `hydrate`) need only the
10
+ * sections, and importing the v1 page shell put its router, the runtime barrel and `react-dom/server` into
11
+ * every theme's browser bundle.
12
+ */
13
+ import type { SectionDef } from '../kit/types.js';
14
+ export declare function sectionModules(): Record<string, {
15
+ default: SectionDef;
16
+ }>;
@@ -0,0 +1,19 @@
1
+ import { SectionRenderer } from '../render/SectionRenderer.js';
2
+ import { getThemeBundle } from '../slots.js';
3
+ export function sectionModules() {
4
+ const { theme, customSections } = getThemeBundle();
5
+ const own = theme.sections.map((s) => ({
6
+ name: s.id,
7
+ title: s.id,
8
+ category: s.category,
9
+ ...(s.zone !== 'main' ? { area: s.zone, role: 'layout' } : {}),
10
+ raw: true,
11
+ presets: (s.presets ?? []).map((p) => ({ name: p.name, settings: p.settings, blocks: (p.blocks ?? []).map((b) => ({ type: b.type, settings: b.settings ?? {} })) })),
12
+ component: SectionRenderer,
13
+ }));
14
+ const custom = Object.entries(customSections).filter(([, m]) => m.default?.name);
15
+ return {
16
+ ...Object.fromEntries(own.map((d) => [`./theme/${d.name}`, { default: d }])),
17
+ ...Object.fromEntries(custom),
18
+ };
19
+ }
@@ -1,4 +1,5 @@
1
- import type { ContentNode } from './types';
1
+ import type { ContentNode } from './types.js';
2
+ export declare function usePageTree(): ContentNode[] | null;
2
3
  /**
3
4
  * The heart: render a JSON content tree → React. The editor and the storefront
4
5
  * both render through this — content stays JSON, never HTML.
@@ -0,0 +1,100 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { createContext, useContext } from 'react';
3
+ import { getSection } from './registry.js';
4
+ /** Apply attribute defaults from the section definition onto a node's settings. */
5
+ function resolveAttributes(def, settings) {
6
+ const out = { ...(settings ?? {}) };
7
+ for (const [key, spec] of Object.entries(def.attributes ?? {})) {
8
+ if (out[key] === undefined && spec.default !== undefined)
9
+ out[key] = spec.default;
10
+ }
11
+ return out;
12
+ }
13
+ /** Tolerate both child-block shapes. Templates written by older editor
14
+ * builds carry blocks as an OBJECT MAP keyed by id (the studio editor's
15
+ * internal shape) instead of theme-kit's array — `blocks.map` on that
16
+ * object crashed the ENTIRE storefront render ("o.map is not a function").
17
+ * A malformed template must degrade to "blocks don't render", never to a
18
+ * dead page. */
19
+ function normalizeBlocks(blocks, order) {
20
+ if (Array.isArray(blocks))
21
+ return blocks;
22
+ if (blocks && typeof blocks === 'object') {
23
+ // Build the node list + a lookup keyed by BOTH the map key and the block's
24
+ // own id — the editor's `order` array references the map key ("0".."n"),
25
+ // but be tolerant of templates that order by block id.
26
+ const nodes = [];
27
+ const byRef = new Map();
28
+ for (const [key, raw] of Object.entries(blocks)) {
29
+ if (!raw || typeof raw !== 'object' || typeof raw.type !== 'string')
30
+ continue;
31
+ const node = { ...raw, id: raw.id ?? key };
32
+ nodes.push(node);
33
+ byRef.set(key, node);
34
+ if (node.id)
35
+ byRef.set(node.id, node);
36
+ }
37
+ // The map's key order is NOT the merchant's arrangement — the editor stores
38
+ // the real order in `order`. Honour it (then append any stragglers).
39
+ if (Array.isArray(order) && order.length) {
40
+ const ordered = [];
41
+ const used = new Set();
42
+ for (const ref of order) {
43
+ const n = byRef.get(ref);
44
+ if (n && !used.has(n)) {
45
+ ordered.push(n);
46
+ used.add(n);
47
+ }
48
+ }
49
+ for (const n of nodes)
50
+ if (!used.has(n))
51
+ ordered.push(n);
52
+ return ordered;
53
+ }
54
+ return nodes;
55
+ }
56
+ return [];
57
+ }
58
+ function RenderNode({ node, path, }) {
59
+ const def = getSection(node.type);
60
+ if (!def) {
61
+ console.warn(`[tanqory] unknown section "${node.type}"`);
62
+ return null;
63
+ }
64
+ const Comp = def.component;
65
+ if (def.raw) {
66
+ // A raw section resolves its own settings and blocks; give it the node with
67
+ // the blocks normalised to an ordered array, and nothing pre-rendered.
68
+ const blocks = normalizeBlocks(node.blocks, node.order);
69
+ return (_jsx("div", { "data-tq-node": node.id, "data-tq-section-type": node.type, "data-tq-path": path, className: "tq-node", children: _jsx(Comp, { attributes: node.settings ?? {}, node: { ...node, blocks } }) }));
70
+ }
71
+ const attributes = resolveAttributes(def, node.settings);
72
+ // Wrap each rendered section in a CSS-transparent tag so the editor preview
73
+ // bridge can resolve clicks back to the JSON node (via data-tq-section-id /
74
+ // data-tq-path) without sections having to opt in. `display: contents`
75
+ // means the wrapper participates in layout as if it weren't there.
76
+ return (_jsx("div", { "data-tq-node": node.id, "data-tq-section-type": node.type, "data-tq-path": path, className: "tq-node", children: _jsx(Comp, { attributes: attributes, children: normalizeBlocks(node.blocks, node.order).map((child, i) => (_jsx(RenderNode, { node: child, path: `${path}.${i}` }, child.id ?? i))) }) }));
77
+ }
78
+ /** The page's resolved section list, for a section whose rendering depends on its neighbours (a header over a hero). */
79
+ const PageTreeContext = createContext(null);
80
+ export function usePageTree() {
81
+ return useContext(PageTreeContext);
82
+ }
83
+ /**
84
+ * The heart: render a JSON content tree → React. The editor and the storefront
85
+ * both render through this — content stays JSON, never HTML.
86
+ */
87
+ export function SectionTree({ tree }) {
88
+ const render = (node, i) => _jsx(RenderNode, { node: node, path: String(i) }, node.id ?? i);
89
+ // A page with chrome renders as header zone → <main> → footer zone, so the
90
+ // skip link has a target and the header and footer are not inside <main>. A
91
+ // tree with no chrome (one section in a preview) renders flat.
92
+ const areaOf = (node) => node.area ?? getSection(node.type)?.area;
93
+ if (!tree.some((n) => areaOf(n) === 'header' || areaOf(n) === 'footer'))
94
+ return _jsx(_Fragment, { children: tree.map(render) });
95
+ const indexed = tree.map((node, i) => ({ node, i }));
96
+ const head = indexed.filter(({ node }) => areaOf(node) === 'header');
97
+ const foot = indexed.filter(({ node }) => areaOf(node) === 'footer');
98
+ const body = indexed.filter(({ node }) => areaOf(node) !== 'header' && areaOf(node) !== 'footer');
99
+ return (_jsxs(PageTreeContext.Provider, { value: tree, children: [head.map(({ node, i }) => render(node, i)), _jsx("main", { id: "main", tabIndex: -1, children: body.map(({ node, i }) => render(node, i)) }), foot.map(({ node, i }) => render(node, i))] }));
100
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Storefront analytics — emit customer events to store-api's analytics pipeline
3
+ * so the merchant's dashboards (sessions, device type, reports, live view)
4
+ * populate. The batch is POSTed SAME-ORIGIN to `/api/v1/analytics/events/batch`
5
+ * (the edge worker forwards it to the store's cell — no CORS); the endpoint is
6
+ * public. Payload matches store-api's EventBatchSchema exactly:
7
+ * { storeId, sessionId, visitorId (all UUIDs), events[1..50], context }
8
+ *
9
+ * The theme creates ONE analytics instance for the real storefront (never in the
10
+ * editor/preview plane) and calls `pageViewed()` on each route + the product/
11
+ * cart/checkout emitters from the matching sections.
12
+ *
13
+ * CUSTOMER EVENTS (standard web-pixel): every `track()` also publishes to
14
+ * a client-side bus so the merchant's CONNECTED pixels (Settings → Customer
15
+ * events, injected by the theme's TrackingPixels) can react to live shopper
16
+ * actions. A pixel subscribes with `window.tqAnalytics.subscribe(name, cb)`.
17
+ * Bus delivery is gated on MARKETING consent (pixels are tracking); the internal
18
+ * telemetry POST is gated separately on ANALYTICS consent.
19
+ */
20
+ /** store-api SessionEventType values we emit from the storefront. */
21
+ export type StorefrontEventType = 'PAGE_VIEWED' | 'COLLECTION_VIEWED' | 'PRODUCT_VIEWED' | 'PRODUCT_ADDED_TO_CART' | 'PRODUCT_REMOVED_FROM_CART' | 'CART_VIEWED' | 'CHECKOUT_STARTED' | 'SEARCH_SUBMITTED';
22
+ /** The normalized event delivered to pixel subscribers on the client bus. */
23
+ export interface StorefrontEvent {
24
+ /** Unique per emission (UUID). */
25
+ id: string;
26
+ /** Lowercase contract name, e.g. `product_added_to_cart`. */
27
+ name: string;
28
+ /** The store-api SessionEventType. */
29
+ type: StorefrontEventType;
30
+ /** ISO-8601. */
31
+ timestamp: string;
32
+ /** Event-specific payload (product id, query, quantity…). */
33
+ data: Record<string, unknown>;
34
+ /** Session context (userAgent, referrer, utm, screen, locale, timezone). */
35
+ context: Record<string, unknown>;
36
+ }
37
+ export interface Analytics {
38
+ /** Queue an event; flushes automatically at batchSize / on page hide. */
39
+ track(type: StorefrontEventType, properties?: Record<string, unknown>): void;
40
+ /** Convenience for the current page. */
41
+ pageViewed(properties?: Record<string, unknown>): void;
42
+ /** Force-send the queued events now. */
43
+ flush(): void;
44
+ /** Subscribe to customer events (for pixels/apps). See `subscribe()`. */
45
+ subscribe(eventName: string, cb: (e: StorefrontEvent) => void): () => void;
46
+ }
47
+ export interface AnalyticsOptions {
48
+ storeId: string;
49
+ endpoint?: string;
50
+ batchSize?: number;
51
+ /** Optional consent gate — return false to drop events (GDPR). Defaults to on. */
52
+ consent?: () => boolean;
53
+ }
54
+ /**
55
+ * Subscribe a pixel (or app) to storefront customer events. Pass a contract
56
+ * name (`product_added_to_cart`, `checkout_started`, …) or `all_events` for
57
+ * every event. Recently-fired events replay immediately, so a pixel injected
58
+ * mid-session still receives them. Returns an unsubscribe fn.
59
+ */
60
+ export declare function subscribe(eventName: string, cb: (e: StorefrontEvent) => void): () => void;
61
+ /** The storefront's active analytics instance (or a no-op before creation). */
62
+ export declare function getAnalytics(): Analytics;
63
+ export declare function createAnalytics(opts: AnalyticsOptions): Analytics;
@@ -0,0 +1,233 @@
1
+ /**
2
+ * Storefront analytics — emit customer events to store-api's analytics pipeline
3
+ * so the merchant's dashboards (sessions, device type, reports, live view)
4
+ * populate. The batch is POSTed SAME-ORIGIN to `/api/v1/analytics/events/batch`
5
+ * (the edge worker forwards it to the store's cell — no CORS); the endpoint is
6
+ * public. Payload matches store-api's EventBatchSchema exactly:
7
+ * { storeId, sessionId, visitorId (all UUIDs), events[1..50], context }
8
+ *
9
+ * The theme creates ONE analytics instance for the real storefront (never in the
10
+ * editor/preview plane) and calls `pageViewed()` on each route + the product/
11
+ * cart/checkout emitters from the matching sections.
12
+ *
13
+ * CUSTOMER EVENTS (standard web-pixel): every `track()` also publishes to
14
+ * a client-side bus so the merchant's CONNECTED pixels (Settings → Customer
15
+ * events, injected by the theme's TrackingPixels) can react to live shopper
16
+ * actions. A pixel subscribes with `window.tqAnalytics.subscribe(name, cb)`.
17
+ * Bus delivery is gated on MARKETING consent (pixels are tracking); the internal
18
+ * telemetry POST is gated separately on ANALYTICS consent.
19
+ */
20
+ import { hasConsent } from './consent.js';
21
+ const VISITOR_KEY = 'tq-visitor-id';
22
+ const SESSION_KEY = 'tq-session';
23
+ const SESSION_TTL_MS = 30 * 60 * 1000;
24
+ const DEFAULT_ENDPOINT = '/api/v1/analytics/events/batch';
25
+ const NOOP = { track() { }, pageViewed() { }, flush() { }, subscribe: () => () => { } };
26
+ // ── Customer-event bus (standard web-pixel) ─────────────────────────────
27
+ // Module-scoped so the injected `window.tqAnalytics.subscribe` and the active
28
+ // analytics instance share one stream. Pixels load AFTER the first events fire,
29
+ // so a small buffer replays recent events to late subscribers.
30
+ const ALL_EVENTS = 'all_events';
31
+ const REPLAY_MAX = 50;
32
+ const busSubscribers = new Map();
33
+ const busReplay = [];
34
+ function busPublish(evt) {
35
+ // Pixels are marketing/tracking — deliver (and retain) only once the shopper
36
+ // allows it. Pre-consent events are never buffered (privacy-safe).
37
+ if (!hasConsent('marketing'))
38
+ return;
39
+ busReplay.push(evt);
40
+ if (busReplay.length > REPLAY_MAX)
41
+ busReplay.shift();
42
+ const fire = (set) => {
43
+ if (!set)
44
+ return;
45
+ for (const cb of set) {
46
+ try {
47
+ cb(evt);
48
+ }
49
+ catch {
50
+ /* one pixel throwing must never break the others or the page */
51
+ }
52
+ }
53
+ };
54
+ fire(busSubscribers.get(evt.name));
55
+ fire(busSubscribers.get(ALL_EVENTS));
56
+ }
57
+ /**
58
+ * Subscribe a pixel (or app) to storefront customer events. Pass a contract
59
+ * name (`product_added_to_cart`, `checkout_started`, …) or `all_events` for
60
+ * every event. Recently-fired events replay immediately, so a pixel injected
61
+ * mid-session still receives them. Returns an unsubscribe fn.
62
+ */
63
+ export function subscribe(eventName, cb) {
64
+ let set = busSubscribers.get(eventName);
65
+ if (!set) {
66
+ set = new Set();
67
+ busSubscribers.set(eventName, set);
68
+ }
69
+ set.add(cb);
70
+ for (const e of busReplay) {
71
+ if (eventName === ALL_EVENTS || e.name === eventName) {
72
+ try {
73
+ cb(e);
74
+ }
75
+ catch {
76
+ /* ignore */
77
+ }
78
+ }
79
+ }
80
+ return () => {
81
+ set?.delete(cb);
82
+ };
83
+ }
84
+ // The active instance, so any section can emit via getAnalytics() without the
85
+ // theme threading the instance through props/context.
86
+ let activeAnalytics = NOOP;
87
+ /** The storefront's active analytics instance (or a no-op before creation). */
88
+ export function getAnalytics() {
89
+ return activeAnalytics;
90
+ }
91
+ function uuid() {
92
+ const c = globalThis.crypto;
93
+ if (c?.randomUUID)
94
+ return c.randomUUID();
95
+ // RFC4122-ish fallback for the rare browser without crypto.randomUUID.
96
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {
97
+ const r = (Math.random() * 16) | 0;
98
+ return (ch === 'x' ? r : (r & 0x3) | 0x8).toString(16);
99
+ });
100
+ }
101
+ function persistentId(key) {
102
+ try {
103
+ let v = localStorage.getItem(key);
104
+ if (!v) {
105
+ v = uuid();
106
+ localStorage.setItem(key, v);
107
+ }
108
+ return v;
109
+ }
110
+ catch {
111
+ return uuid();
112
+ }
113
+ }
114
+ /** Rolling 30-minute session id (the commerce standard/GA-style). Refreshed on each event. */
115
+ function sessionId() {
116
+ const now = Date.now();
117
+ try {
118
+ const raw = localStorage.getItem(SESSION_KEY);
119
+ if (raw) {
120
+ const s = JSON.parse(raw);
121
+ if (s.id && now - s.at < SESSION_TTL_MS) {
122
+ localStorage.setItem(SESSION_KEY, JSON.stringify({ id: s.id, at: now }));
123
+ return s.id;
124
+ }
125
+ }
126
+ const id = uuid();
127
+ localStorage.setItem(SESSION_KEY, JSON.stringify({ id, at: now }));
128
+ return id;
129
+ }
130
+ catch {
131
+ return uuid();
132
+ }
133
+ }
134
+ function buildContext() {
135
+ const params = new URLSearchParams(location.search);
136
+ const utm = {};
137
+ for (const [k, dest] of [
138
+ ['utm_source', 'source'],
139
+ ['utm_medium', 'medium'],
140
+ ['utm_campaign', 'campaign'],
141
+ ['utm_term', 'term'],
142
+ ['utm_content', 'content'],
143
+ ]) {
144
+ const v = params.get(k);
145
+ if (v)
146
+ utm[dest] = v;
147
+ }
148
+ return {
149
+ userAgent: navigator.userAgent,
150
+ referrer: document.referrer || '',
151
+ ...(Object.keys(utm).length ? { utm } : {}),
152
+ screen: { width: window.screen.width, height: window.screen.height },
153
+ locale: navigator.language,
154
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
155
+ };
156
+ }
157
+ export function createAnalytics(opts) {
158
+ if (typeof window === 'undefined' || !opts.storeId)
159
+ return NOOP;
160
+ const endpoint = opts.endpoint ?? DEFAULT_ENDPOINT;
161
+ const batchSize = opts.batchSize ?? 10;
162
+ const consent = opts.consent ?? (() => true);
163
+ const queue = [];
164
+ const send = () => {
165
+ if (!queue.length || !consent()) {
166
+ queue.length = 0;
167
+ return;
168
+ }
169
+ const batch = {
170
+ storeId: opts.storeId,
171
+ sessionId: sessionId(),
172
+ visitorId: persistentId(VISITOR_KEY),
173
+ events: queue.splice(0, 50),
174
+ context: buildContext(),
175
+ };
176
+ const body = JSON.stringify(batch);
177
+ try {
178
+ if (navigator.sendBeacon) {
179
+ navigator.sendBeacon(endpoint, new Blob([body], { type: 'application/json' }));
180
+ }
181
+ else {
182
+ void fetch(endpoint, {
183
+ method: 'POST',
184
+ headers: { 'content-type': 'application/json' },
185
+ body,
186
+ keepalive: true,
187
+ }).catch(() => { });
188
+ }
189
+ }
190
+ catch {
191
+ /* best-effort telemetry — never throw into the storefront */
192
+ }
193
+ };
194
+ const track = (type, properties = {}) => {
195
+ // Publish to the pixel bus FIRST (its own marketing-consent gate), so
196
+ // marketing pixels still fire even when analytics telemetry is declined.
197
+ busPublish({
198
+ id: uuid(),
199
+ name: type.toLowerCase(),
200
+ type,
201
+ timestamp: new Date().toISOString(),
202
+ data: properties,
203
+ context: buildContext(),
204
+ });
205
+ // Internal telemetry POST — gated on analytics consent.
206
+ if (!consent())
207
+ return;
208
+ queue.push({
209
+ eventName: type.toLowerCase(),
210
+ eventType: type,
211
+ timestamp: new Date().toISOString(),
212
+ properties,
213
+ });
214
+ if (queue.length >= batchSize)
215
+ send();
216
+ };
217
+ window.addEventListener('visibilitychange', () => {
218
+ if (document.visibilityState === 'hidden')
219
+ send();
220
+ });
221
+ window.addEventListener('pagehide', send);
222
+ window.tqAnalytics ??= {
223
+ subscribe,
224
+ };
225
+ const api = {
226
+ track,
227
+ pageViewed: (properties = {}) => track('PAGE_VIEWED', { pageUrl: location.href, pageTitle: document.title, ...properties }),
228
+ flush: send,
229
+ subscribe,
230
+ };
231
+ activeAnalytics = api;
232
+ return api;
233
+ }
@@ -0,0 +1,186 @@
1
+ import { type ReactNode } from 'react';
2
+ import { type Money } from './data.js';
3
+ export interface CartLine {
4
+ /** Cart line id — the handle used for update/remove. */
5
+ id: string;
6
+ /** The purchasable variant (merchandise) id. */
7
+ variantId: string;
8
+ quantity: number;
9
+ /** Product title shown in the cart. */
10
+ title: string;
11
+ /** Variant title (e.g. "Black / M"); empty for single-variant products. */
12
+ variantTitle?: string;
13
+ image?: {
14
+ url: string;
15
+ altText?: string;
16
+ } | null;
17
+ /** Per-unit price. */
18
+ price: Money;
19
+ /** Line subtotal (price × quantity). */
20
+ lineSubtotal: Money;
21
+ /** Product handle for linking back to the PDP. */
22
+ productHandle?: string;
23
+ /** The variant's options (`Size: Queen`, `Colour: Oat`), when the cart source carries them. */
24
+ selectedOptions?: Array<{
25
+ name: string;
26
+ value: string;
27
+ }>;
28
+ /** Per-unit compare-at price, when the cart source carries one. */
29
+ compareAtPrice?: Money | null;
30
+ /** False when the merchandise can no longer be bought; absent = unknown (treated as purchasable). */
31
+ availableForSale?: boolean;
32
+ /** Custom line properties (`line_item.properties`). */
33
+ attributes?: Array<{
34
+ key: string;
35
+ value?: string | null;
36
+ }>;
37
+ /** Per-line discounts (`line_item.discount_allocations`). */
38
+ discountAllocations?: Array<{
39
+ title?: string | null;
40
+ code?: string | null;
41
+ amount: Money;
42
+ }>;
43
+ /** Subscription plan chosen for this line (`line_item.selling_plan_allocation`). */
44
+ sellingPlanAllocation?: {
45
+ sellingPlanId: string;
46
+ sellingPlanName: string;
47
+ checkoutCharge?: Money | null;
48
+ remainingBalance?: Money | null;
49
+ } | null;
50
+ }
51
+ /** A discount code applied to the cart (`applicable=false` when it didn't qualify). */
52
+ export interface AppliedDiscountCode {
53
+ code: string;
54
+ applicable: boolean;
55
+ }
56
+ /** A gift card applied to the cart — masked (only last 4 chars ever leave the API). */
57
+ export interface AppliedGiftCard {
58
+ id: string;
59
+ lastCharacters: string;
60
+ amountUsed: Money;
61
+ balance: Money;
62
+ }
63
+ export interface CartState {
64
+ /**
65
+ * Why the first load of the cart failed (wire code, e.g. `rate_limited`), while `ready` stays
66
+ * false. A cart we could not read is NOT an empty cart. Absent/null once the cart has loaded.
67
+ */
68
+ loadError?: string | null;
69
+ /** With `loadError`: true while another attempt is scheduled (Retry-After / backoff). */
70
+ loadRetrying?: boolean;
71
+ id: string | null;
72
+ lines: CartLine[];
73
+ subtotal: Money;
74
+ /** Final amount after discounts + gift cards (cost.totalAmount). */
75
+ total: Money;
76
+ /** Estimated tax (cost.totalTaxAmount) — null until known (usually at checkout). */
77
+ tax?: Money | null;
78
+ /** Estimated duties (cost.totalDutyAmount) — null unless cross-border. */
79
+ duty?: Money | null;
80
+ /** Cart-level order note (`cart.note`). */
81
+ note?: string | null;
82
+ /** Cart-level custom attributes (`cart.attributes`). */
83
+ attributes?: {
84
+ key: string;
85
+ value: string | null;
86
+ }[];
87
+ totalQuantity: number;
88
+ checkoutUrl: string | null;
89
+ /** Discount codes applied to the cart. */
90
+ discountCodes: AppliedDiscountCode[];
91
+ /** Total savings across all discount allocations — null when nothing's discounted. */
92
+ discountAmount: Money | null;
93
+ /**
94
+ * The cart's order-level discounts by name (automatic: `title`; code: `code`), when the source sends them.
95
+ * Absent = not known (the Theme ABI cart carries only totals and codes).
96
+ */
97
+ discountAllocations?: Array<{
98
+ title?: string | null;
99
+ code?: string | null;
100
+ amount: Money;
101
+ }>;
102
+ /** Gift cards applied to the cart. */
103
+ appliedGiftCards: AppliedGiftCard[];
104
+ /** True while a mutation/bootstrap is in flight. */
105
+ loading: boolean;
106
+ /** True once the client has hydrated cart state post-mount. */
107
+ ready: boolean;
108
+ error: string | null;
109
+ }
110
+ export interface AddToCartInput {
111
+ /** Line properties the buyer filled in (a gift card recipient, an engraving), shown on the order. */
112
+ attributes?: Array<{
113
+ key: string;
114
+ value: string;
115
+ }>;
116
+ variantId: string;
117
+ quantity?: number;
118
+ /** Display data — used only by the in-memory MOCK driver (editor/offline). */
119
+ product?: {
120
+ title: string;
121
+ price: Money;
122
+ image?: {
123
+ url: string;
124
+ altText?: string;
125
+ } | null;
126
+ handle?: string;
127
+ variantTitle?: string;
128
+ };
129
+ }
130
+ /**
131
+ * Why the platform refused a cart write, when it said (theme-abi 2.0.0-alpha.13 `CartRefusal`, Cart-1).
132
+ * `cart_limit_exceeded`: more of one product than the merchant's "Maximum quantity per product" allows;
133
+ * `maxQuantity` is that limit when the platform knows it.
134
+ */
135
+ export interface CartRefusal {
136
+ code: 'cart_limit_exceeded';
137
+ maxQuantity?: number;
138
+ }
139
+ export interface CartApi extends CartState {
140
+ /** Re-read the cart after something outside this provider changed it. Never rejects. */
141
+ reload?: (id?: string) => Promise<void>;
142
+ /**
143
+ * Resolves `true` when the line is in the cart, `false` when the backend
144
+ * refused it (sold out, quantity rule, expired cart, network) — `error` then
145
+ * holds the reason. Never rejects, so a caller must check the result before
146
+ * treating the add as done.
147
+ */
148
+ add: (input: AddToCartInput) => Promise<boolean>;
149
+ updateQuantity: (lineId: string, quantity: number) => Promise<void>;
150
+ remove: (lineId: string) => Promise<void>;
151
+ clear: () => Promise<void>;
152
+ /** Apply discount codes (replaces the current set; [] clears them). LIVE only. */
153
+ applyDiscountCodes: (codes: string[]) => Promise<void>;
154
+ /** Apply gift card codes to the cart. LIVE only. */
155
+ applyGiftCardCodes: (codes: string[]) => Promise<void>;
156
+ /** Remove applied gift cards by id. LIVE only. */
157
+ removeGiftCards: (ids: string[]) => Promise<void>;
158
+ /** Set the cart-level order note (`cart.note`). LIVE only. */
159
+ updateNote: (note: string) => Promise<void>;
160
+ /** Replace the cart-level custom attributes (`cart.attributes`). LIVE only. */
161
+ updateAttributes: (attributes: {
162
+ key: string;
163
+ value: string;
164
+ }[]) => Promise<void>;
165
+ /**
166
+ * The refusal of the latest cart write, when the platform said why (else null). A getter, not
167
+ * state: read it right after `add` / `updateQuantity` resolves, before the next render.
168
+ */
169
+ lastRefusal?: () => CartRefusal | null;
170
+ /**
171
+ * Put one discount code on the cart (it replaces the code there: the store holds one) and say how it went; never
172
+ * rejects. `not_applicable`: the store keeps the code but does not apply it — it is taken off again and the code the
173
+ * cart held before is put back. Absent where the source cannot tell (the GraphQL driver).
174
+ */
175
+ applyDiscountCode?: (code: string) => Promise<DiscountCodeResult>;
176
+ /** Take a discount code off the cart; resolves true once it is gone. Present with `applyDiscountCode`. */
177
+ removeDiscountCode?: (code: string) => Promise<boolean>;
178
+ }
179
+ /** How applying a discount code went. */
180
+ export type DiscountCodeResult = 'applied' | 'not_applicable' | 'failed';
181
+ /** Exported so another cart driver (lib/abi/cart.tsx, Theme ABI v2) can provide the same `useCart()`. */
182
+ export declare const CartContext: import("react").Context<CartApi | null>;
183
+ export declare function CartProvider({ children }: {
184
+ children: ReactNode;
185
+ }): JSX.Element;
186
+ export declare function useCart(): CartApi;