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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +98 -10
  3. package/dist/abi/canvas-live.d.ts +49 -0
  4. package/dist/abi/canvas-live.js +88 -0
  5. package/dist/abi/cart.d.ts +48 -0
  6. package/dist/abi/cart.js +256 -0
  7. package/dist/abi/convert.d.ts +126 -0
  8. package/dist/abi/convert.js +493 -0
  9. package/dist/abi/data-api.d.ts +11 -0
  10. package/dist/abi/data-api.js +178 -0
  11. package/dist/abi/jcs.d.ts +6 -0
  12. package/dist/abi/jcs.js +28 -0
  13. package/dist/abi/page-data.d.ts +198 -0
  14. package/dist/abi/page-data.js +577 -0
  15. package/dist/abi/page.d.ts +23 -0
  16. package/dist/abi/page.js +46 -0
  17. package/dist/abi/referrals.d.ts +23 -0
  18. package/dist/abi/referrals.js +89 -0
  19. package/dist/abi/rewards.d.ts +27 -0
  20. package/dist/abi/rewards.js +82 -0
  21. package/dist/abi/seo.d.ts +47 -0
  22. package/dist/abi/seo.js +68 -0
  23. package/dist/abi/shell.d.ts +22 -0
  24. package/dist/abi/shell.js +10 -0
  25. package/dist/abi/wire.d.ts +38 -0
  26. package/dist/abi/wire.js +84 -0
  27. package/dist/build.d.ts +113 -0
  28. package/dist/build.js +294 -0
  29. package/dist/client.d.ts +19 -0
  30. package/dist/client.js +76 -0
  31. package/dist/contract.d.ts +6 -0
  32. package/dist/contract.js +6 -0
  33. package/dist/headless/ai.d.ts +132 -0
  34. package/dist/headless/ai.js +99 -0
  35. package/dist/headless/hooks.d.ts +273 -0
  36. package/dist/headless/hooks.js +533 -0
  37. package/dist/headless/i18n.d.ts +13 -0
  38. package/dist/headless/i18n.js +45 -0
  39. package/dist/headless/index.d.ts +36 -0
  40. package/dist/headless/index.js +38 -0
  41. package/dist/headless/money.d.ts +25 -0
  42. package/dist/headless/money.js +61 -0
  43. package/dist/headless/page.d.ts +43 -0
  44. package/dist/headless/page.js +53 -0
  45. package/dist/headless/platform.d.ts +55 -0
  46. package/dist/headless/platform.js +77 -0
  47. package/dist/headless/primitives/cart.d.ts +90 -0
  48. package/dist/headless/primitives/cart.js +153 -0
  49. package/dist/headless/primitives/collection.d.ts +68 -0
  50. package/dist/headless/primitives/collection.js +80 -0
  51. package/dist/headless/primitives/product.d.ts +101 -0
  52. package/dist/headless/primitives/product.js +117 -0
  53. package/dist/headless/primitives/storefront.d.ts +106 -0
  54. package/dist/headless/primitives/storefront.js +186 -0
  55. package/dist/headless/primitives/util.d.ts +19 -0
  56. package/dist/headless/primitives/util.js +42 -0
  57. package/dist/headless/strings.d.ts +9 -0
  58. package/dist/headless/strings.js +186 -0
  59. package/dist/headless/structured-data.d.ts +31 -0
  60. package/dist/headless/structured-data.js +57 -0
  61. package/dist/headless/theme.d.ts +99 -0
  62. package/dist/headless/theme.js +54 -0
  63. package/dist/index.d.ts +20 -0
  64. package/dist/index.js +18 -553
  65. package/dist/runtime/data/StoreProvider.d.ts +56 -0
  66. package/dist/runtime/data/StoreProvider.js +308 -0
  67. package/dist/runtime/data/handle.d.ts +14 -0
  68. package/dist/runtime/data/handle.js +16 -0
  69. package/dist/runtime/data/routes.d.ts +87 -0
  70. package/dist/runtime/data/routes.js +154 -0
  71. package/dist/runtime/data/to-ui.d.ts +237 -0
  72. package/dist/runtime/data/to-ui.js +759 -0
  73. package/dist/runtime/entries/register.d.ts +9 -0
  74. package/dist/runtime/entries/register.js +9 -0
  75. package/dist/runtime/entries/sections.d.ts +16 -0
  76. package/dist/runtime/entries/sections.js +19 -0
  77. package/dist/{types → runtime/kit}/SectionTree.d.ts +2 -1
  78. package/dist/runtime/kit/SectionTree.js +100 -0
  79. package/dist/runtime/kit/analytics.d.ts +63 -0
  80. package/dist/runtime/kit/analytics.js +233 -0
  81. package/dist/runtime/kit/cart.d.ts +167 -0
  82. package/dist/runtime/kit/cart.js +544 -0
  83. package/dist/{types → runtime/kit}/composition.d.ts +1 -1
  84. package/dist/runtime/kit/composition.js +3 -0
  85. package/dist/{types → runtime/kit}/config.d.ts +2 -2
  86. package/dist/runtime/kit/config.js +6 -0
  87. package/dist/runtime/kit/consent.d.ts +29 -0
  88. package/dist/runtime/kit/consent.js +159 -0
  89. package/dist/runtime/kit/contract/content.d.ts +164 -0
  90. package/dist/runtime/kit/contract/content.js +83 -0
  91. package/dist/runtime/kit/contract/field-types.d.ts +290 -0
  92. package/dist/runtime/kit/contract/field-types.js +129 -0
  93. package/dist/runtime/kit/contract/groups.d.ts +230 -0
  94. package/dist/runtime/kit/contract/groups.js +402 -0
  95. package/dist/runtime/kit/contract/index.d.ts +33 -0
  96. package/dist/runtime/kit/contract/index.js +33 -0
  97. package/dist/runtime/kit/contract/transform.d.ts +82 -0
  98. package/dist/runtime/kit/contract/transform.js +133 -0
  99. package/dist/runtime/kit/contract/validate.d.ts +67 -0
  100. package/dist/runtime/kit/contract/validate.js +388 -0
  101. package/dist/{types → runtime/kit}/data.d.ts +276 -7
  102. package/dist/runtime/kit/data.js +1117 -0
  103. package/dist/{types → runtime/kit}/defineSection.d.ts +1 -1
  104. package/dist/runtime/kit/defineSection.js +10 -0
  105. package/dist/{types → runtime/kit}/dynamic-source.d.ts +4 -4
  106. package/dist/runtime/kit/dynamic-source.js +143 -0
  107. package/dist/runtime/kit/index.d.ts +24 -0
  108. package/dist/runtime/kit/index.js +24 -0
  109. package/dist/{types → runtime/kit}/jsx-to-json.d.ts +1 -1
  110. package/dist/runtime/kit/jsx-to-json.js +28 -0
  111. package/dist/{types → runtime/kit}/mount.d.ts +25 -4
  112. package/dist/runtime/kit/mount.js +124 -0
  113. package/dist/{types → runtime/kit}/registry.d.ts +1 -1
  114. package/dist/runtime/kit/registry.js +12 -0
  115. package/dist/{types → runtime/kit}/ssg.d.ts +9 -3
  116. package/dist/runtime/kit/ssg.js +56 -0
  117. package/dist/{types → runtime/kit}/storefront.d.ts +206 -7
  118. package/dist/runtime/kit/storefront.js +723 -0
  119. package/dist/{types → runtime/kit}/theme-context.d.ts +8 -2
  120. package/dist/runtime/kit/theme-context.js +25 -0
  121. package/dist/runtime/kit/types.d.ts +142 -0
  122. package/dist/runtime/kit/types.js +1 -0
  123. package/dist/runtime/platform/TrackingPixels.d.ts +14 -0
  124. package/dist/runtime/platform/TrackingPixels.js +63 -0
  125. package/dist/runtime/platform/environment.d.ts +68 -0
  126. package/dist/runtime/platform/environment.js +85 -0
  127. package/dist/runtime/platform/locale.d.ts +27 -0
  128. package/dist/runtime/platform/locale.js +42 -0
  129. package/dist/runtime/platform/route-analytics.d.ts +15 -0
  130. package/dist/runtime/platform/route-analytics.js +72 -0
  131. package/dist/runtime/platform/safe-href.d.ts +25 -0
  132. package/dist/runtime/platform/safe-href.js +69 -0
  133. package/dist/runtime/platform/safe-values.d.ts +37 -0
  134. package/dist/runtime/platform/safe-values.js +140 -0
  135. package/dist/runtime/render/SectionRenderer.d.ts +4 -0
  136. package/dist/runtime/render/SectionRenderer.js +111 -0
  137. package/dist/runtime/render/listing-query.d.ts +47 -0
  138. package/dist/runtime/render/listing-query.js +114 -0
  139. package/dist/runtime/render/localized-copy.d.ts +86 -0
  140. package/dist/runtime/render/localized-copy.js +129 -0
  141. package/dist/runtime/render/product-listing.d.ts +11 -0
  142. package/dist/runtime/render/product-listing.js +240 -0
  143. package/dist/runtime/render/section-actions.d.ts +44 -0
  144. package/dist/runtime/render/section-actions.js +169 -0
  145. package/dist/runtime/render/starter.d.ts +11 -0
  146. package/dist/runtime/render/starter.js +81 -0
  147. package/dist/runtime/seo/head.d.ts +87 -0
  148. package/dist/runtime/seo/head.js +224 -0
  149. package/dist/runtime/seo/structured-data.d.ts +22 -0
  150. package/dist/runtime/seo/structured-data.js +115 -0
  151. package/dist/runtime/shell/PageShell.d.ts +18 -0
  152. package/dist/runtime/shell/PageShell.js +113 -0
  153. package/dist/runtime/shell/RuntimeBridge.d.ts +14 -0
  154. package/dist/runtime/shell/RuntimeBridge.js +82 -0
  155. package/dist/runtime/shell/overlay-state.d.ts +31 -0
  156. package/dist/runtime/shell/overlay-state.js +59 -0
  157. package/dist/runtime/shell/preview-mode.d.ts +2 -0
  158. package/dist/runtime/shell/preview-mode.js +11 -0
  159. package/dist/runtime/shell/spa-router.d.ts +14 -0
  160. package/dist/runtime/shell/spa-router.js +76 -0
  161. package/dist/runtime/shell/url-redirects.d.ts +6 -0
  162. package/dist/runtime/shell/url-redirects.js +37 -0
  163. package/dist/runtime/slots.d.ts +74 -0
  164. package/dist/runtime/slots.js +16 -0
  165. package/dist/runtime.d.ts +34 -0
  166. package/dist/runtime.js +40 -0
  167. package/dist/sdk/index.d.ts +24 -0
  168. package/dist/sdk/index.js +24 -0
  169. package/dist/sdk/referrals.d.ts +62 -0
  170. package/dist/sdk/referrals.js +20 -0
  171. package/dist/sdk/rewards.d.ts +85 -0
  172. package/dist/sdk/rewards.js +29 -0
  173. package/dist/sdk/runtime-context.d.ts +120 -0
  174. package/dist/sdk/runtime-context.js +73 -0
  175. package/dist/sdk/schema.d.ts +197 -0
  176. package/dist/sdk/schema.js +121 -0
  177. package/dist/sdk/server-render.d.ts +8 -0
  178. package/dist/sdk/server-render.js +12 -0
  179. package/dist/sdk/store-lookup.d.ts +27 -0
  180. package/dist/sdk/store-lookup.js +29 -0
  181. package/dist/sdk/store.d.ts +115 -0
  182. package/dist/sdk/store.js +1 -0
  183. package/dist/sdk/sx.d.ts +40 -0
  184. package/dist/sdk/sx.js +112 -0
  185. package/dist/sdk/theme.d.ts +152 -0
  186. package/dist/sdk/theme.js +10 -0
  187. package/dist/sdk/types.d.ts +395 -0
  188. package/dist/sdk/types.js +7 -0
  189. package/dist/server.d.ts +65 -0
  190. package/dist/server.js +370 -0
  191. package/docs/headless-api.md +220 -0
  192. package/package.json +77 -23
  193. package/dist/index.js.map +0 -1
  194. package/dist/ssg-BZ5FYTw7.js +0 -1802
  195. package/dist/ssg-BZ5FYTw7.js.map +0 -1
  196. package/dist/ssg.js +0 -8
  197. package/dist/ssg.js.map +0 -1
  198. package/dist/types/cart.d.ts +0 -86
  199. package/dist/types/editor.d.ts +0 -5
  200. package/dist/types/index.d.ts +0 -20
  201. package/dist/types/preview-bridge.d.ts +0 -9
  202. package/dist/types/types.d.ts +0 -44
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tanqory
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,17 +1,105 @@
1
- # @tanqory/theme-kit
1
+ # @tanqory/theme-kit (v2, Theme ABI v2)
2
2
 
3
- The Studio framework. Themes depend only on this — it auto-discovers a theme's
4
- `sections/`, `templates/`, `layouts/` and renders the **JSON content tree** to React.
3
+ The platform layer a Tanqory theme is built on: the theme-authoring API, the runtime behind it
4
+ (store data plan over `ctx.data`, cart, SEO head and JSON-LD, localisation, live edit on the editor
5
+ canvas) and the two entry factories that turn a theme into a Theme ABI v2 artifact.
5
6
 
6
- Public API: `defineSection`, `defineSettings`, `defineTheme`, `mount`,
7
- `SectionTree`, `useData` / `useSettings` / `useT`, `createMockData`, `jsxToJSON`.
7
+ A theme supplies its sections, components and styles. Everything else comes from the kit, so a new
8
+ theme does not re-implement cart, variants, markets or live edit.
8
9
 
9
- **Status:** already built & passing (currently at `wordpress/tanqory-theme-kit`).
10
- Move it here as `packages/theme-kit` to consolidate under Studio.
10
+ > **Alpha.** `2.0.0-alpha.*` carries the `alpha` dist-tag (`latest` is still the incompatible v1 kit, `0.x`).
11
+ > The `./runtime` surface may still move between pre-releases.
12
+
13
+ ```bash
14
+ npm create tanqory-theme@latest my-theme # a complete theme on the kit (Blank or a Nova fork)
15
+ # or, in an existing theme:
16
+ npm install @tanqory/theme-kit@alpha react@18.3.1 react-dom@18.3.1
17
+ npm install --save-dev @tanqory/theme-abi@alpha
18
+ ```
19
+
20
+ **Source.** Extracted, behaviour-identical, from the Nova V3 theme's platform layer. Nova V3 renders
21
+ byte-identical HTML on it (render diff over 58 fixture routes, en + th).
22
+
23
+ ## Entry points
24
+
25
+ | Import | What it is |
26
+ |---|---|
27
+ | `@tanqory/theme-kit` | The authoring API: `defineTheme`, `defineSection`, `defineSchema`, `field.*`, `resolveSettings`, `useThemeContext`, `useThemeActions`, `useSearchSuggestions`, `useRewards`, `useReferrals`, `imageFor` / `menuFor` / `collectionFor` / `productFor`, `sx()`, and the data types (`Shop`, `Menu`, `MenuItem`, `Link`, `Image`, `Video`, `Localization`, `Market`, `CartSummary`, `Customer`, `Product`, `Collection`, `Cart`, …). The earlier `Nova*` type names are kept as `@deprecated` aliases. |
28
+ | `@tanqory/theme-kit/headless` | **The headless storefront API** (2.0.0-alpha.1): data hooks (`useProduct`, `useCollection`, `useCart`, `useSearch`, `useLocalization`, …), accessible commerce primitives with no styling (`<ProductForm>`, `<VariantPicker>`, `<AddToCart>`, `<CartDrawer>`, `<FacetFilters>`, `<SortSelect>`, `<LocalizationForm>`, `<NewsletterForm>`, `<ConsentBanner>`, …), `<Seo>`, `<Image>`, `t()`, `formatMoney`, `defineSection` / `defineBlock` / `defineTheme` and the `ai.*` roles. Reference: [docs/headless-api.md](docs/headless-api.md). |
29
+ | `@tanqory/theme-kit/build` | `buildManifest(...)`: the theme's ABI manifest (components, settings, routes, forms, capabilities with `data:shop`, `x-tanqory-ai`) from its declarations; `checkContent`, `withKitStrings`. Pure, for a theme's build script. |
30
+ | `@tanqory/theme-kit/server` | `createRender(options)` → the ABI `render(request, ctx)`. Every theme gets hreflang alternates (`<canonical>?locale=<lang>` per published language, plus `x-default`; 2.0.0-alpha.2, `hreflang: false` turns them off). `storefront: {}` turns on what the headless API needs (Breadcrumb/Collection JSON-LD, `<Seo>`, merchant strings, data-plan flags); absent, the render is otherwise the alpha.0 one. |
31
+ | `@tanqory/theme-kit/client` | `hydrate(options)`: the browser entry. Wires the editor canvas live edit (`tq:canvas` / `tq:canvas-live`) automatically in preview mode. |
32
+ | `@tanqory/theme-kit/runtime` | Low-level runtime pieces (providers, data plan, wire client, cart provider, converters, SEO helpers). For a theme's own tests and for custom entries. |
33
+ | `@tanqory/theme-kit/contract` | The content contract (page and section-group documents, roles, validation, transforms). Pure, loads in Node. |
34
+
35
+ ## Headless themes
36
+
37
+ A theme written against `@tanqory/theme-kit/headless` owns all its markup and CSS and gets every storefront
38
+ function from the kit: variants and `?variant=`, add to cart and the cart drawer, cart lines and checkout
39
+ hand-off, sort / filter / paging, predictive search, market and language, consent, platform forms, account
40
+ slot, SEO and JSON-LD, th/en strings with merchant overrides, live edit on the editor canvas, and the AI-compat
41
+ profile. The primitives render semantic HTML with the `tq-storefront-hooks/1` attributes and accept
42
+ `className` and render-prop children. See [docs/headless-api.md](docs/headless-api.md) and the complete example
43
+ theme Aurora (in the kit's source repository, not part of the published package; `npm create tanqory-theme` gives you an equivalent Blank starter).
44
+
45
+ ## Using it
46
+
47
+ ```tsx
48
+ // entry.abi.tsx: the server entry, built into ONE file with no imports
49
+ import type { ThemeManifest } from '@tanqory/theme-abi'
50
+ import { createRender } from '@tanqory/theme-kit/server'
51
+ import { bundle } from './lib/bundle'
52
+ import manifestJson from './lib/abi/generated/manifest.json'
53
+
54
+ export const manifest = manifestJson as unknown as ThemeManifest
55
+ export const render = createRender({ manifest, bundle })
56
+ ```
57
+
58
+ ```tsx
59
+ // main.abi.tsx: the browser entry
60
+ import { hydrate } from '@tanqory/theme-kit/client'
61
+ import { bundle } from './lib/bundle'
62
+
63
+ hydrate({ bundle })
64
+ ```
65
+
66
+ `bundle` is the theme's `ThemeBundle`: its `defineTheme(...)` definition, `templates/*.json`,
67
+ `groups/*.json`, `locales/*.json`, settings and settings schema. The not-found section shown for an
68
+ unknown product, collection, page or blog comes from the bundle's `templates/404.json`.
69
+
70
+ Optional hooks (all default to "unchanged"):
71
+
72
+ | Hook | Where | Runs |
73
+ |---|---|---|
74
+ | `effectiveSettings(settings)` | `createRender` | first: manifest defaults + the store's values → what the theme renders (and hydrates) with |
75
+ | `transformNodes(nodes, settings)` | `createRender` and `hydrate` (pass the same function to both) | on the page's section nodes before render, server and browser |
76
+ | `shopSettings(settings, shop)` | `createRender` | once the store's shop record is loaded |
77
+
78
+ ## What the compiled output guarantees
79
+
80
+ `pnpm build` runs `tsc` and then `scripts/check-dist.mjs`, which fails the build unless:
81
+
82
+ - every relative import names an existing `.js` file (Node ESM and the platform build sandbox resolve it as written);
83
+ - there is no dynamic `import()` and no `import.meta.glob`, so the theme's server entry stays one file with no imports;
84
+ - there are no `node:` / Node built-in imports and no CSS imports in runtime code;
85
+ - the only bare imports are the peer dependencies (`react`, `react-dom`, `@tanqory/theme-abi`).
86
+
87
+ The runtime reads `import.meta.env` (`DEV`, and the optional `VITE_TANQORY_*` build variables), as
88
+ every theme bundler on the platform defines it. Under Vitest, list the kit in
89
+ `test.server.deps.inline` so it is transformed like the theme's own source.
90
+
91
+ ## Layout
11
92
 
12
93
  ```
13
94
  src/
14
- defineSection.ts · config.ts (defineTheme/defineSettings) · registry.ts
15
- SectionTree.tsx (JSON tree → React) · mount.tsx · data.tsx · theme-context.tsx
16
- jsx-to-json.ts · composition.ts · types.ts · index.ts
95
+ index.ts @tanqory/theme-kit (= sdk/ + ThemeBundle, ContentNode)
96
+ server.tsx @tanqory/theme-kit/server createRender()
97
+ client.tsx @tanqory/theme-kit/client hydrate()
98
+ runtime.ts @tanqory/theme-kit/runtime
99
+ contract.ts @tanqory/theme-kit/contract
100
+ sdk/ the authoring API: schema, theme, runtime context, data types, sx
101
+ runtime/ rendering: section tree, store data layer, cart, SEO head, render helpers, content contract
102
+ abi/ the ABI v2 layer: data plan over ctx.data, data API, wire client, cart, loyalty, live edit
103
+ test/ vitest
104
+ scripts/ check-dist.mjs, check-release-integrity.mjs
17
105
  ```
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Live section edits on the editor canvas (a PREVIEW render only — `ctx.mode === 'preview'`).
3
+ *
4
+ * The platform gateway injects its editor bridge into every preview page.
5
+ * The bridge checks the editor's origin and hands each content message to the page as a `tq:canvas` DOM event; this
6
+ * module applies those messages to the section nodes the page rendered, so a setting edit re-renders its section at
7
+ * once instead of waiting for a save and a reload. The bridge also does selection, scrolling and click-to-select; the
8
+ * theme does none of that here.
9
+ *
10
+ * tanqory-preview-update-section {sectionId, settings, blocks?, order?} that section's settings (and blocks)
11
+ * tq:set-content {doc: ContentNode[]} the editor's tree: every node it names
12
+ * that is on this page takes its settings
13
+ *
14
+ * Structure (add / remove / reorder) is NOT applied here: the editor reloads the canvas for those, from the saved
15
+ * workspace. A node the editor names that this page does not render is ignored, never inserted.
16
+ *
17
+ * Pure (no DOM, no React): the store is the boundary — main.abi.tsx subscribes React to it and wires the window
18
+ * events. Unit-tested in lib/abi/canvas-live.test.ts.
19
+ */
20
+ import type { ContentNode } from '../runtime/kit/types.js';
21
+ export declare const CANVAS_EVENT = "tq:canvas";
22
+ export declare const CANVAS_LIVE_EVENT = "tq:canvas-live";
23
+ export declare const CANVAS_BRIDGE_EVENT = "tq:canvas-bridge";
24
+ /** The message types this theme applies live (announced to the bridge, which tells the editor). */
25
+ export declare const LIVE_TYPES: readonly string[];
26
+ /** The editor's block shapes → an array: an id-keyed map with an `order`, or already an array. */
27
+ export declare function blocksOf(raw: unknown, order: unknown): ContentNode[] | undefined;
28
+ /**
29
+ * The nodes after one canvas message. Returns the SAME array when the message changes nothing on this page (an
30
+ * unknown type, a section that is not here), so React does not re-render for it.
31
+ */
32
+ export declare function applyCanvasMessage(nodes: ContentNode[], msg: unknown): ContentNode[];
33
+ export interface CanvasStore {
34
+ get(): ContentNode[];
35
+ subscribe(listener: () => void): () => void;
36
+ apply(msg: unknown): void;
37
+ }
38
+ /** The page's section nodes as a small external store (React subscribes with useSyncExternalStore). */
39
+ export declare function createCanvasStore(initial: ContentNode[]): CanvasStore;
40
+ interface EventWindow {
41
+ addEventListener(type: string, listener: (e: Event) => void): void;
42
+ dispatchEvent(e: Event): boolean;
43
+ }
44
+ /**
45
+ * Connects the store to the bridge: every `tq:canvas` event is applied, and the theme announces what it applies —
46
+ * now, and again whenever a bridge says it started (it may load after this script).
47
+ */
48
+ export declare function connectCanvas(win: EventWindow, store: CanvasStore, makeEvent: (type: string, detail?: unknown) => Event): void;
49
+ export {};
@@ -0,0 +1,88 @@
1
+ export const CANVAS_EVENT = 'tq:canvas';
2
+ export const CANVAS_LIVE_EVENT = 'tq:canvas-live';
3
+ export const CANVAS_BRIDGE_EVENT = 'tq:canvas-bridge';
4
+ /** The message types this theme applies live (announced to the bridge, which tells the editor). */
5
+ export const LIVE_TYPES = ['tanqory-preview-update-section', 'tq:set-content'];
6
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
7
+ /** The editor's block shapes → an array: an id-keyed map with an `order`, or already an array. */
8
+ export function blocksOf(raw, order) {
9
+ if (Array.isArray(raw))
10
+ return raw.filter((b) => isObj(b) && typeof b.type === 'string');
11
+ if (!isObj(raw))
12
+ return undefined;
13
+ const ids = Array.isArray(order) && order.length ? order.filter((x) => typeof x === 'string') : Object.keys(raw);
14
+ const out = [];
15
+ for (const id of ids) {
16
+ const b = raw[id];
17
+ if (!isObj(b) || typeof b.type !== 'string')
18
+ continue;
19
+ out.push({ ...b, id: typeof b.id === 'string' ? b.id : id });
20
+ }
21
+ return out;
22
+ }
23
+ function patched(node, settings, blocks) {
24
+ return {
25
+ ...node,
26
+ settings: { ...(node.settings ?? {}), ...(isObj(settings) ? settings : {}) },
27
+ ...(blocks ? { blocks } : {}),
28
+ };
29
+ }
30
+ /**
31
+ * The nodes after one canvas message. Returns the SAME array when the message changes nothing on this page (an
32
+ * unknown type, a section that is not here), so React does not re-render for it.
33
+ */
34
+ export function applyCanvasMessage(nodes, msg) {
35
+ if (!isObj(msg))
36
+ return nodes;
37
+ if (msg.type === 'tanqory-preview-update-section') {
38
+ const id = msg.sectionId;
39
+ if (typeof id !== 'string' || !nodes.some((n) => n.id === id))
40
+ return nodes;
41
+ const blocks = blocksOf(msg.blocks, msg.order);
42
+ return nodes.map((n) => (n.id === id ? patched(n, msg.settings, blocks) : n));
43
+ }
44
+ if (msg.type === 'tq:set-content' && Array.isArray(msg.doc)) {
45
+ const byId = new Map();
46
+ for (const d of msg.doc)
47
+ if (isObj(d) && typeof d.id === 'string')
48
+ byId.set(d.id, d);
49
+ if (!nodes.some((n) => n.id !== undefined && byId.has(n.id)))
50
+ return nodes;
51
+ return nodes.map((n) => {
52
+ const d = n.id !== undefined ? byId.get(n.id) : undefined;
53
+ // a node whose TYPE changed is structure, not a setting: leave it for the reload
54
+ return d && d.type === n.type ? patched(n, d.settings, blocksOf(d.blocks, d.order)) : n;
55
+ });
56
+ }
57
+ return nodes;
58
+ }
59
+ /** The page's section nodes as a small external store (React subscribes with useSyncExternalStore). */
60
+ export function createCanvasStore(initial) {
61
+ let nodes = initial;
62
+ const listeners = new Set();
63
+ return {
64
+ get: () => nodes,
65
+ subscribe(l) {
66
+ listeners.add(l);
67
+ return () => listeners.delete(l);
68
+ },
69
+ apply(msg) {
70
+ const next = applyCanvasMessage(nodes, msg);
71
+ if (next === nodes)
72
+ return;
73
+ nodes = next;
74
+ for (const l of listeners)
75
+ l();
76
+ },
77
+ };
78
+ }
79
+ /**
80
+ * Connects the store to the bridge: every `tq:canvas` event is applied, and the theme announces what it applies —
81
+ * now, and again whenever a bridge says it started (it may load after this script).
82
+ */
83
+ export function connectCanvas(win, store, makeEvent) {
84
+ const announce = () => win.dispatchEvent(makeEvent(CANVAS_LIVE_EVENT, { types: [...LIVE_TYPES] }));
85
+ win.addEventListener(CANVAS_EVENT, (e) => store.apply(e.detail));
86
+ win.addEventListener(CANVAS_BRIDGE_EVENT, announce);
87
+ announce();
88
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The cart over Theme ABI v2 (theme-abi-v2.md §4): the same `useCart()` every section already uses,
3
+ * driven by `POST /_tq/actions/cart.*` and `GET /_tq/data/cart.get` instead of a GraphQL endpoint
4
+ * (wire envelope: lib/abi/wire.ts).
5
+ *
6
+ * - Identity is the platform's cart cookie — invisible to the theme. There is no cart id in
7
+ * localStorage any more; `cart.get` answers for the current shopper.
8
+ * - Every mutation carries the cart `version`; a stale version answers `cart_version_conflict`
9
+ * with the current cart, which is applied and the mutation retried once.
10
+ * - Server render never mutates (§4 A3): on the server `remote` is null, the cart route renders
11
+ * the cart the platform resolved (`snapshot().resource.cart`) and every other page renders the
12
+ * empty cart until the browser has asked for it.
13
+ * - A first `cart.get` that FAILS is not an empty cart (QA test-2 F1: a 429 showed "Your cart is
14
+ * empty" over a cart holding a line). `ready` stays false, `loadError` records the code, and the
15
+ * load is retried after the server's `Retry-After` (else exponential backoff). Surfaces show
16
+ * "Couldn't load your cart — retrying". An add before the cart has loaded reads it first; it
17
+ * never `cart.create`s over a cart it could not see.
18
+ *
19
+ * A refused write may say why (theme-abi Cart-1, alpha.13): `refusal` on the `invalid` CartResult,
20
+ * or `error.refusal` when `cart.create` is refused. It is kept for `lastRefusal()`, so the surface
21
+ * that made the write can word it ("You can buy up to 5 of this item").
22
+ *
23
+ * Not in the ABI cart, so not offered: gift-card codes and cart-level attributes after creation.
24
+ * Those methods resolve and set `error`, never pretend to succeed (MISMATCHES.md).
25
+ */
26
+ import { type ReactNode } from 'react';
27
+ import type { Cart as AbiCart } from '@tanqory/theme-abi';
28
+ import { type CartRefusal } from '../runtime/kit/cart.js';
29
+ import { type AbiRemote } from './wire.js';
30
+ /**
31
+ * The refusal the platform sent with a refused write (theme-abi Cart-1), or null. Only a code this
32
+ * theme knows counts; `maxQuantity` only when it is a whole number of at least 1.
33
+ */
34
+ export declare function refusalOf(raw: unknown): CartRefusal | null;
35
+ /** The wire code of a failed request, for `loadError` / `error`. */
36
+ export declare function wireCode(e: unknown): string;
37
+ /**
38
+ * When to try `cart.get` again after failure number `attempt` (0-based), or null when another try
39
+ * cannot help. The server's Retry-After wins; a 4xx that is not about timing (403
40
+ * capability_denied, 400 …) is final; everything else (network, 5xx, 429 without the header)
41
+ * backs off 1 s, 2 s, 4 s … up to 30 s.
42
+ */
43
+ export declare function retryDelay(e: unknown, attempt: number): number | null;
44
+ export declare function AbiCartProvider({ initial, remote, children }: {
45
+ initial: AbiCart | null;
46
+ remote: AbiRemote | null;
47
+ children: ReactNode;
48
+ }): JSX.Element;
@@ -0,0 +1,256 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ /**
3
+ * The cart over Theme ABI v2 (theme-abi-v2.md §4): the same `useCart()` every section already uses,
4
+ * driven by `POST /_tq/actions/cart.*` and `GET /_tq/data/cart.get` instead of a GraphQL endpoint
5
+ * (wire envelope: lib/abi/wire.ts).
6
+ *
7
+ * - Identity is the platform's cart cookie — invisible to the theme. There is no cart id in
8
+ * localStorage any more; `cart.get` answers for the current shopper.
9
+ * - Every mutation carries the cart `version`; a stale version answers `cart_version_conflict`
10
+ * with the current cart, which is applied and the mutation retried once.
11
+ * - Server render never mutates (§4 A3): on the server `remote` is null, the cart route renders
12
+ * the cart the platform resolved (`snapshot().resource.cart`) and every other page renders the
13
+ * empty cart until the browser has asked for it.
14
+ * - A first `cart.get` that FAILS is not an empty cart (QA test-2 F1: a 429 showed "Your cart is
15
+ * empty" over a cart holding a line). `ready` stays false, `loadError` records the code, and the
16
+ * load is retried after the server's `Retry-After` (else exponential backoff). Surfaces show
17
+ * "Couldn't load your cart — retrying". An add before the cart has loaded reads it first; it
18
+ * never `cart.create`s over a cart it could not see.
19
+ *
20
+ * A refused write may say why (theme-abi Cart-1, alpha.13): `refusal` on the `invalid` CartResult,
21
+ * or `error.refusal` when `cart.create` is refused. It is kept for `lastRefusal()`, so the surface
22
+ * that made the write can word it ("You can buy up to 5 of this item").
23
+ *
24
+ * Not in the ABI cart, so not offered: gift-card codes and cart-level attributes after creation.
25
+ * Those methods resolve and set `error`, never pretend to succeed (MISMATCHES.md).
26
+ */
27
+ import { useCallback, useEffect, useRef, useState } from 'react';
28
+ import { CartContext } from '../runtime/kit/cart.js';
29
+ import { cartState } from './convert.js';
30
+ import { AbiWireError } from './wire.js';
31
+ const ZERO = { amount: '0.00', currencyCode: 'USD' };
32
+ function stateOf(c, ready) {
33
+ if (!c) {
34
+ return { id: null, lines: [], subtotal: ZERO, total: ZERO, totalQuantity: 0, checkoutUrl: null, discountCodes: [], discountAmount: null, appliedGiftCards: [], loading: false, ready, error: null };
35
+ }
36
+ // `discountAmount` is the cart-level amount off, derived from the cart's own totals (convert.ts).
37
+ const s = cartState(c);
38
+ return { ...s, appliedGiftCards: [], loading: false, ready, error: null };
39
+ }
40
+ /**
41
+ * The refusal the platform sent with a refused write (theme-abi Cart-1), or null. Only a code this
42
+ * theme knows counts; `maxQuantity` only when it is a whole number of at least 1.
43
+ */
44
+ export function refusalOf(raw) {
45
+ if (typeof raw !== 'object' || raw === null || raw.code !== 'cart_limit_exceeded')
46
+ return null;
47
+ const max = raw.maxQuantity;
48
+ return typeof max === 'number' && Number.isSafeInteger(max) && max >= 1 ? { code: 'cart_limit_exceeded', maxQuantity: max } : { code: 'cart_limit_exceeded' };
49
+ }
50
+ const UNSUPPORTED = 'unsupported';
51
+ const MAX_RETRY_MS = 5 * 60_000;
52
+ const MAX_BACKOFF_MS = 30_000;
53
+ /** The wire code of a failed request, for `loadError` / `error`. */
54
+ export function wireCode(e) {
55
+ if (e instanceof AbiWireError)
56
+ return e.code ?? `http_${e.status}`;
57
+ return 'network_error';
58
+ }
59
+ /**
60
+ * When to try `cart.get` again after failure number `attempt` (0-based), or null when another try
61
+ * cannot help. The server's Retry-After wins; a 4xx that is not about timing (403
62
+ * capability_denied, 400 …) is final; everything else (network, 5xx, 429 without the header)
63
+ * backs off 1 s, 2 s, 4 s … up to 30 s.
64
+ */
65
+ export function retryDelay(e, attempt) {
66
+ if (e instanceof AbiWireError) {
67
+ if (e.retryAfterMs !== null)
68
+ return Math.min(Math.max(e.retryAfterMs, 1000), MAX_RETRY_MS);
69
+ if (e.status >= 400 && e.status < 500 && e.status !== 408 && e.status !== 425 && e.status !== 429)
70
+ return null;
71
+ }
72
+ return Math.min(1000 * 2 ** attempt, MAX_BACKOFF_MS);
73
+ }
74
+ export function AbiCartProvider({ initial, remote, children }) {
75
+ const [state, setState] = useState(() => stateOf(initial, initial !== null));
76
+ const cartRef = useRef(initial);
77
+ /** True once the shopper's cart is known (server-resolved, or a `cart.get` answered). */
78
+ const loadedRef = useRef(initial !== null);
79
+ const inFlight = useRef(null);
80
+ /** Why the latest write was refused, when the platform said (Cart-1). */
81
+ const refusalRef = useRef(null);
82
+ const lastRefusal = useCallback(() => refusalRef.current, []);
83
+ const apply = useCallback((c) => {
84
+ cartRef.current = c;
85
+ loadedRef.current = true;
86
+ setState(stateOf(c, true));
87
+ }, []);
88
+ const fail = useCallback((message) => setState((s) => ({ ...s, loading: false, error: message })), []);
89
+ useEffect(() => {
90
+ if (!remote || loadedRef.current)
91
+ return;
92
+ let cancelled = false;
93
+ let timer;
94
+ let attempt = 0;
95
+ const load = () => {
96
+ // A mutation may have loaded the cart while this attempt was waiting.
97
+ if (cancelled || loadedRef.current)
98
+ return;
99
+ remote
100
+ .data('cart.get', [])
101
+ .then((c) => { if (!cancelled && !loadedRef.current)
102
+ apply(c ?? null); })
103
+ .catch((e) => {
104
+ if (cancelled || loadedRef.current)
105
+ return;
106
+ const delay = retryDelay(e, attempt++);
107
+ // Not ready, not empty: the surfaces say the cart could not be loaded.
108
+ setState((s) => ({ ...s, ready: false, loadError: wireCode(e), loadRetrying: delay !== null }));
109
+ if (delay !== null)
110
+ timer = setTimeout(load, delay);
111
+ });
112
+ };
113
+ load();
114
+ return () => {
115
+ cancelled = true;
116
+ if (timer !== undefined)
117
+ clearTimeout(timer);
118
+ };
119
+ }, [remote, apply]);
120
+ /** Run one versioned mutation; on a version conflict apply the current cart and retry once. */
121
+ const mutate = useCallback(async (name, args) => {
122
+ if (!remote)
123
+ return false;
124
+ const run = async () => {
125
+ for (let attempt = 0; attempt < 2; attempt++) {
126
+ refusalRef.current = null;
127
+ const version = cartRef.current?.version ?? 0;
128
+ const env = await remote.action(name, args(version));
129
+ // ok ⇒ `data` is the CartResult; a stale version ⇒ error.code cart_version_conflict with the
130
+ // current cart in `data` (§4 wire envelope).
131
+ if (env.ok) {
132
+ const r = env.data;
133
+ if (r.ok) {
134
+ apply(r.cart);
135
+ return true;
136
+ }
137
+ if (r.reason === 'cart_version_conflict') {
138
+ apply(r.cart);
139
+ continue;
140
+ }
141
+ if (r.reason === 'invalid')
142
+ refusalRef.current = refusalOf(r.refusal);
143
+ fail(r.reason);
144
+ return false;
145
+ }
146
+ if (env.error.code === 'cart_version_conflict' && env.data) {
147
+ apply(env.data);
148
+ continue;
149
+ }
150
+ refusalRef.current = refusalOf(env.error.refusal);
151
+ fail(env.error.code);
152
+ return false;
153
+ }
154
+ fail('cart_version_conflict');
155
+ return false;
156
+ };
157
+ setState((s) => ({ ...s, loading: true }));
158
+ // Mutations are serialised: two quick taps must not race on the same version.
159
+ const prev = inFlight.current ?? Promise.resolve();
160
+ const next = prev.catch(() => undefined).then(run);
161
+ inFlight.current = next;
162
+ try {
163
+ return await next;
164
+ }
165
+ catch (e) {
166
+ fail(e.message);
167
+ return false;
168
+ }
169
+ }, [remote, apply, fail]);
170
+ const add = useCallback(async (input) => {
171
+ const quantity = input.quantity ?? 1;
172
+ refusalRef.current = null;
173
+ if (quantity < 1 || !remote)
174
+ return false;
175
+ const attributes = Object.fromEntries((input.attributes ?? []).filter((a) => a.value.trim() !== '').map((a) => [a.key, a.value]));
176
+ const line = { merchandiseId: input.variantId, quantity, ...(Object.keys(attributes).length ? { attributes } : {}) };
177
+ if (!cartRef.current && !loadedRef.current) {
178
+ // The shopper may already hold a cart we have not read (first load pending or failed):
179
+ // read it now, and never create a second cart over one we could not see.
180
+ setState((s) => ({ ...s, loading: true }));
181
+ try {
182
+ apply((await remote.data('cart.get', [])) ?? null);
183
+ }
184
+ catch (e) {
185
+ fail(wireCode(e));
186
+ return false;
187
+ }
188
+ }
189
+ if (!cartRef.current) {
190
+ setState((s) => ({ ...s, loading: true }));
191
+ try {
192
+ const env = await remote.action('cart.create', [{ lines: [line] }]);
193
+ if (!env.ok) {
194
+ refusalRef.current = refusalOf(env.error.refusal);
195
+ fail(env.error.code);
196
+ return false;
197
+ }
198
+ apply(env.data);
199
+ return true;
200
+ }
201
+ catch (e) {
202
+ fail(e.message);
203
+ return false;
204
+ }
205
+ }
206
+ return mutate('cart.addLines', (v) => [[line], v]);
207
+ }, [remote, apply, fail, mutate]);
208
+ const updateQuantity = useCallback(async (lineId, quantity) => {
209
+ if (quantity <= 0)
210
+ await mutate('cart.removeLines', (v) => [[lineId], v]);
211
+ else
212
+ await mutate('cart.updateLines', (v) => [[{ id: lineId, quantity }], v]);
213
+ }, [mutate]);
214
+ const remove = useCallback(async (lineId) => { await mutate('cart.removeLines', (v) => [[lineId], v]); }, [mutate]);
215
+ const clear = useCallback(async () => {
216
+ const ids = cartRef.current?.lines.map((l) => l.id) ?? [];
217
+ if (ids.length)
218
+ await mutate('cart.removeLines', (v) => [ids, v]);
219
+ }, [mutate]);
220
+ const applyDiscountCodes = useCallback(async (codes) => {
221
+ const current = cartRef.current?.discountCodes.map((d) => d.code) ?? [];
222
+ for (const code of current.filter((c) => !codes.includes(c)))
223
+ if (!(await mutate('cart.removeDiscountCode', (v) => [code, v])))
224
+ return;
225
+ for (const code of codes.filter((c) => !current.includes(c)))
226
+ if (!(await mutate('cart.applyDiscountCode', (v) => [code, v])))
227
+ return;
228
+ }, [mutate]);
229
+ const updateNote = useCallback(async (note) => { await mutate('cart.updateNote', (v) => [note, v]); }, [mutate]);
230
+ const unsupported = useCallback(async () => fail(UNSUPPORTED), [fail]);
231
+ const reload = useCallback(async () => {
232
+ if (!remote)
233
+ return;
234
+ try {
235
+ apply((await remote.data('cart.get', [])) ?? null);
236
+ }
237
+ catch {
238
+ /* keep the cart on screen; the next mutation re-syncs it */
239
+ }
240
+ }, [remote, apply]);
241
+ const value = {
242
+ ...state,
243
+ add,
244
+ updateQuantity,
245
+ remove,
246
+ clear,
247
+ applyDiscountCodes,
248
+ applyGiftCardCodes: unsupported,
249
+ removeGiftCards: unsupported,
250
+ updateNote,
251
+ updateAttributes: unsupported,
252
+ reload,
253
+ lastRefusal,
254
+ };
255
+ return _jsx(CartContext.Provider, { value: value, children: children });
256
+ }