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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/README.md +4 -1
  2. package/dist/abi/canvas-live.d.ts +7 -2
  3. package/dist/abi/canvas-live.js +8 -3
  4. package/dist/abi/cart.d.ts +5 -4
  5. package/dist/abi/cart.js +14 -5
  6. package/dist/abi/convert.d.ts +18 -2
  7. package/dist/abi/convert.js +56 -4
  8. package/dist/abi/data-api.js +4 -0
  9. package/dist/abi/page-data.d.ts +11 -3
  10. package/dist/abi/page-data.js +71 -3
  11. package/dist/abi/wire.d.ts +8 -0
  12. package/dist/abi/wire.js +32 -2
  13. package/dist/build.d.ts +7 -2
  14. package/dist/build.js +96 -5
  15. package/dist/chunks.d.ts +23 -0
  16. package/dist/chunks.js +41 -0
  17. package/dist/client.d.ts +7 -0
  18. package/dist/client.js +16 -2
  19. package/dist/headless/hooks.js +5 -1
  20. package/dist/headless/index.d.ts +8 -1
  21. package/dist/headless/index.js +11 -1
  22. package/dist/headless/lazy-component.d.ts +72 -0
  23. package/dist/headless/lazy-component.js +225 -0
  24. package/dist/headless/lazy-section.d.ts +38 -0
  25. package/dist/headless/lazy-section.js +97 -0
  26. package/dist/headless/model.d.ts +73 -0
  27. package/dist/headless/model.js +115 -0
  28. package/dist/headless/money.d.ts +1 -9
  29. package/dist/headless/money.js +24 -22
  30. package/dist/headless/page.d.ts +2 -0
  31. package/dist/headless/primitives/storefront.js +2 -1
  32. package/dist/headless/strings.js +8 -0
  33. package/dist/headless/tanqory-money.generated.d.ts +493 -0
  34. package/dist/headless/tanqory-money.generated.js +507 -0
  35. package/dist/headless/theme.d.ts +13 -3
  36. package/dist/headless/theme.js +12 -4
  37. package/dist/index.d.ts +1 -0
  38. package/dist/index.js +3 -0
  39. package/dist/runtime/data/StoreProvider.js +10 -3
  40. package/dist/runtime/data/to-ui.d.ts +12 -7
  41. package/dist/runtime/data/to-ui.js +48 -16
  42. package/dist/runtime/kit/cart.d.ts +10 -3
  43. package/dist/runtime/kit/contract/content.d.ts +14 -0
  44. package/dist/runtime/kit/contract/content.js +13 -0
  45. package/dist/runtime/kit/contract/field-types.d.ts +26 -3
  46. package/dist/runtime/kit/contract/field-types.js +11 -1
  47. package/dist/runtime/kit/contract/validate.d.ts +2 -0
  48. package/dist/runtime/kit/contract/validate.js +49 -9
  49. package/dist/runtime/kit/data.d.ts +12 -0
  50. package/dist/runtime/kit/data.js +36 -22
  51. package/dist/runtime/kit/dynamic-source.d.ts +12 -0
  52. package/dist/runtime/kit/dynamic-source.js +17 -0
  53. package/dist/runtime/kit/storefront.d.ts +14 -1
  54. package/dist/runtime/kit/types.d.ts +8 -0
  55. package/dist/runtime/render/SectionRenderer.js +44 -11
  56. package/dist/runtime/render/resolved.d.ts +47 -0
  57. package/dist/runtime/render/resolved.js +80 -0
  58. package/dist/runtime/render/section-actions.d.ts +2 -1
  59. package/dist/runtime/render/section-actions.js +4 -1
  60. package/dist/runtime/render/starter.js +19 -4
  61. package/dist/runtime/seo/head.d.ts +1 -1
  62. package/dist/runtime/shell/PageShell.js +6 -1
  63. package/dist/runtime/shell/RuntimeBridge.d.ts +4 -0
  64. package/dist/runtime/shell/RuntimeBridge.js +37 -6
  65. package/dist/runtime/slots.d.ts +1 -1
  66. package/dist/sdk/font-hooks.d.ts +7 -0
  67. package/dist/sdk/font-hooks.js +21 -0
  68. package/dist/sdk/fonts.d.ts +144 -0
  69. package/dist/sdk/fonts.js +241 -0
  70. package/dist/sdk/index.d.ts +7 -1
  71. package/dist/sdk/index.js +11 -1
  72. package/dist/sdk/motion-hooks.d.ts +23 -0
  73. package/dist/sdk/motion-hooks.js +46 -0
  74. package/dist/sdk/motion.d.ts +78 -0
  75. package/dist/sdk/motion.js +292 -0
  76. package/dist/sdk/runtime-context.d.ts +32 -4
  77. package/dist/sdk/schema.d.ts +47 -4
  78. package/dist/sdk/schema.js +47 -0
  79. package/dist/sdk/store-lookup.d.ts +5 -0
  80. package/dist/sdk/store-lookup.js +19 -0
  81. package/dist/sdk/store.d.ts +15 -0
  82. package/dist/sdk/sx.d.ts +5 -0
  83. package/dist/sdk/sx.js +7 -2
  84. package/dist/sdk/theme.d.ts +21 -0
  85. package/dist/sdk/theme.js +17 -0
  86. package/dist/sdk/types.d.ts +36 -4
  87. package/dist/server.d.ts +5 -4
  88. package/dist/server.js +76 -20
  89. package/dist/vite-chunks.d.ts +10 -0
  90. package/dist/vite-chunks.js +44 -0
  91. package/docs/headless-api.md +33 -3
  92. package/package.json +10 -18
package/dist/sdk/sx.js CHANGED
@@ -36,12 +36,13 @@ let serverSink = null;
36
36
  */
37
37
  export function collectStyles(render) {
38
38
  const rules = new Map();
39
+ const fonts = new Set();
39
40
  const prev = serverSink;
40
41
  serverSink = { add: (c, d) => { if (!rules.has(c))
41
- rules.set(c, d); } };
42
+ rules.set(c, d); }, font: (f) => fonts.add(f) };
42
43
  try {
43
44
  const result = render();
44
- return { result, css: [...rules].map(([c, d]) => `.${c}{${d}}`).join('') };
45
+ return { result, css: [...rules].map(([c, d]) => `.${c}{${d}}`).join(''), fonts: [...fonts].sort() };
45
46
  }
46
47
  finally {
47
48
  serverSink = prev;
@@ -105,6 +106,10 @@ export function sx(style) {
105
106
  (serverSink ?? getBrowserSink())?.add(className, decl);
106
107
  return className;
107
108
  }
109
+ /** During a server render: note a catalogue font family the page uses (fonts.ts). No-op in the browser. */
110
+ export function registerFontFamily(family) {
111
+ serverSink?.font?.(family);
112
+ }
108
113
  /** Join class names, skipping empty ones. */
109
114
  export function cx(...names) {
110
115
  const s = names.filter(Boolean).join(' ');
@@ -21,6 +21,14 @@ export interface SectionPreset {
21
21
  }[];
22
22
  }
23
23
  /** What a section's data binding receives besides the saved node and the store. */
24
+ import { type ResolvedNode } from '../runtime/render/resolved.js';
25
+ /**
26
+ * The key a block's resolution is filed under in `binding.resolved.blocks`: the block's id, else `#<its position in its
27
+ * parent as saved>`. Pass the saved block `data()` received and its index in that list: the kit keeps the block's
28
+ * saved position on it, so an id-less block finds its resolution on the server (which hands `data()` the list without
29
+ * starter blocks) and in the browser (which hands it the list as saved) alike.
30
+ */
31
+ export { blockKey as resolvedBlockKey } from '../runtime/render/resolved.js';
24
32
  export interface SectionBindingContext {
25
33
  /** The platform actions (for callback props: add to cart, search …). */
26
34
  actions: ThemeActions;
@@ -33,6 +41,13 @@ export interface SectionBindingContext {
33
41
  /** This section is that first body section. */
34
42
  isFirstBodySection: boolean;
35
43
  };
44
+ /**
45
+ * This node's settings as `resolveSettings` returns them (with the section's schema and its block schemas), and its
46
+ * blocks' by block id (or `#<index>`). theme-abi-v2 §2.2.2: the server resolves; in the browser the kit takes the
47
+ * page state's copy, so `data()` can read `resolved` instead of resolving with an imported schema, and a section
48
+ * defined with `defineClientSection` ships no schema to shoppers.
49
+ */
50
+ resolved?: ResolvedNode;
36
51
  }
37
52
  export interface ThemeSection<P = any> {
38
53
  /** The persisted section type — never changes once stores have saved it. */
@@ -189,3 +204,9 @@ export interface SettingSpec {
189
204
  export declare function defineSettings<T extends Record<string, SettingSpec>>(settings: T): T;
190
205
  export declare function defineTheme(theme: ThemeDefinition): ThemeDefinition;
191
206
  export declare function defineSection<P>(section: ThemeSection<P>): ThemeSection<P>;
207
+ /**
208
+ * A section for the shopper bundle (theme-abi-v2 §2.2.2): its id, component and `data()` only, with no schema, presets
209
+ * or block metadata. Its `data()` reads `binding.resolved` (the server's resolution, from the page state). The full
210
+ * definition (`defineSection`) stays the theme's source of truth for the server, the editor and the manifest.
211
+ */
212
+ export declare function defineClientSection<P>(section: Pick<ThemeSection<P>, 'id' | 'component' | 'data'> & Partial<Pick<ThemeSection<P>, 'category' | 'zone' | 'listing'>>): ThemeSection<P>;
package/dist/sdk/theme.js CHANGED
@@ -1,3 +1,12 @@
1
+ /** What a section's data binding receives besides the saved node and the store. */
2
+ import { CLIENT_ONLY_SCHEMA } from '../runtime/render/resolved.js';
3
+ /**
4
+ * The key a block's resolution is filed under in `binding.resolved.blocks`: the block's id, else `#<its position in its
5
+ * parent as saved>`. Pass the saved block `data()` received and its index in that list: the kit keeps the block's
6
+ * saved position on it, so an id-less block finds its resolution on the server (which hands `data()` the list without
7
+ * starter blocks) and in the browser (which hands it the list as saved) alike.
8
+ */
9
+ export { blockKey as resolvedBlockKey } from '../runtime/render/resolved.js';
1
10
  /** Declare the theme's settings (the Theme panel). */
2
11
  export function defineSettings(settings) {
3
12
  return settings;
@@ -8,3 +17,11 @@ export function defineTheme(theme) {
8
17
  export function defineSection(section) {
9
18
  return section;
10
19
  }
20
+ /**
21
+ * A section for the shopper bundle (theme-abi-v2 §2.2.2): its id, component and `data()` only, with no schema, presets
22
+ * or block metadata. Its `data()` reads `binding.resolved` (the server's resolution, from the page state). The full
23
+ * definition (`defineSection`) stays the theme's source of truth for the server, the editor and the manifest.
24
+ */
25
+ export function defineClientSection(section) {
26
+ return { ...section, schema: CLIENT_ONLY_SCHEMA };
27
+ }
@@ -58,6 +58,12 @@ export interface Shop {
58
58
  name: string;
59
59
  /** Settings → Brand → logo. The header resolves: logo image → header.logo text → name. */
60
60
  logo?: Image | null;
61
+ /** Settings → Brand → slogan, when set (board 35 #110). A theme shows it only where the merchant turns its option on. */
62
+ slogan?: string;
63
+ /** Settings → Brand → short description, when set (board 35 #110). */
64
+ shortDescription?: string;
65
+ /** Settings → Brand → cover image, when set (board 35 #110). */
66
+ coverImage?: Image;
61
67
  email?: string;
62
68
  phone?: string;
63
69
  social?: Partial<Record<SocialNetwork, string>>;
@@ -214,11 +220,21 @@ export interface ShopPopup {
214
220
  /** The merchant's cookie banner (Settings › Customer privacy). Text members are present only when typed. */
215
221
  export interface ConsentBannerConfig {
216
222
  enabled: boolean;
217
- /** "Use automated settings": shown wherever the shopper has not decided, not only in `regions`. */
223
+ /**
224
+ * "Use automated settings": the platform decides where the banner shows (its legal floor, `consent.get`
225
+ * `regionRequiresBanner`), and `regions` is not used. Off: also in `regions` (board 35 #42).
226
+ */
218
227
  automated: boolean;
219
228
  position: 'bottom' | 'bottom-left' | 'bottom-right' | 'bottom-center' | 'center';
220
- /** custom = the theme's own colours. */
229
+ /** custom = the merchant's `colors` when sent, else the theme's own colours. */
221
230
  colorTheme: 'light' | 'dark' | 'custom';
231
+ /** With `colorTheme` custom: the merchant's own colours (`#rrggbb`), storefront-query rev 2.69. */
232
+ colors?: {
233
+ background: string;
234
+ text: string;
235
+ button: string;
236
+ buttonText: string;
237
+ };
222
238
  /** Countries ("TH") or subdivisions ("US-CA") the merchant chose. */
223
239
  regions: string[];
224
240
  privacyLinkUrl?: string;
@@ -400,7 +416,10 @@ export interface CartLineAttribute {
400
416
  export interface CartLine {
401
417
  id: string;
402
418
  quantity: number;
403
- product: Pick<Product, 'title' | 'handle' | 'url' | 'vendor'>;
419
+ /** `id`: the product's id (theme-abi Cart-4), when the cart source sends it — the same id as `Product.id`. */
420
+ product: Pick<Product, 'title' | 'handle' | 'url' | 'vendor'> & {
421
+ id?: string;
422
+ };
404
423
  variant: ProductVariant;
405
424
  /**
406
425
  * `total`: what the line costs after its own discounts (a product discount, a Buy X get Y free item), as the cart's
@@ -509,7 +528,8 @@ export type ProductMediaItem = {
509
528
  */
510
529
  | {
511
530
  type: 'model';
512
- src: string;
531
+ src: string; /** iOS Quick Look file (`.usdz`), same-origin; absent ⇒ the viewer makes one. */
532
+ iosSrc?: string;
513
533
  poster?: Image;
514
534
  alt?: string;
515
535
  };
@@ -667,6 +687,12 @@ export interface UgcPost {
667
687
  url?: string;
668
688
  productHandles?: string[];
669
689
  }
690
+ /** rev 2.73 (board 35 #117): one weekly opening period; `closes` earlier than `opens` closes after midnight. */
691
+ export interface StoreOpeningPeriod {
692
+ day: 'MONDAY' | 'TUESDAY' | 'WEDNESDAY' | 'THURSDAY' | 'FRIDAY' | 'SATURDAY' | 'SUNDAY';
693
+ opens: string;
694
+ closes: string;
695
+ }
670
696
  export interface StoreLocation {
671
697
  id: string;
672
698
  name: string;
@@ -677,6 +703,12 @@ export interface StoreLocation {
677
703
  hours?: string;
678
704
  /** rev 2.52 (O3): the location's expected pickup time ("Usually ready in …"), for a theme to word. */
679
705
  pickupReadyIn?: '4h' | '24h' | '1-2d' | '2-4d' | '5d+';
706
+ /** rev 2.73 (board 35 #117): offers local pickup; absent ⇒ yes (the rev 2.34 reading). */
707
+ pickup?: boolean;
708
+ /** rev 2.73: Physical storefront on, so a store locator lists it; absent ⇒ yes (the rev 2.34 reading). */
709
+ storefront?: boolean;
710
+ /** rev 2.73: the weekly opening hours, Monday first, 24-hour local `HH:MM`; a day not listed is closed; absent ⇒ not set. */
711
+ openingHours?: StoreOpeningPeriod[];
680
712
  image?: Image | null;
681
713
  url?: string;
682
714
  }
package/dist/server.d.ts CHANGED
@@ -82,21 +82,22 @@ export declare function giftCardBalanceOf(v: unknown): GiftCardBalance | null;
82
82
  */
83
83
  export declare function createRender(options: RenderOptions): RenderFunction;
84
84
  /**
85
- * The live-only hints the storefront gateway acts on (storefront-edge core/platform-hints.ts); it drops every `x-tq-*`
86
- * before the page leaves, so a browser never sees them.
85
+ * The hints the storefront gateway acts on (storefront-edge core/platform-hints.ts); it drops every `x-tq-*` before the
86
+ * page leaves, so a browser never sees them. Live only, except `x-tq-media: model`.
87
87
  * x-tq-speculation: on NEW-OS-11 part 2 — `enableSpaNavigation` is not off: the gateway adds its
88
88
  * `Speculation-Rules` header, so hovering a link prerenders the next page.
89
89
  * x-tq-turnstile: on A4 — the store's spam protection asks for the Turnstile widget on a form this theme can show
90
90
  * (`shop.spamProtection`, either switch): the gateway allows Cloudflare Turnstile in the CSP.
91
91
  * x-tq-media: video, model NEW-PROD-2 — a product on the page has a YouTube / Vimeo video (the gateway frames
92
92
  * `www.youtube-nocookie.com` and `player.vimeo.com`) and/or a 3D model (`connect-src blob:`).
93
- * Never in the editor canvas (a preview host ignores them too).
93
+ * In the editor canvas / a draft preview only `x-tq-media: model`: the 3D viewer runs there too (the gateway honours
94
+ * `model` on a preview host and ignores the rest, core/platform-hints.ts says why).
94
95
  */
95
96
  export declare function platformHints(preview: boolean, settings: Record<string, unknown>, shop: Pick<Shop, 'spamProtection'> | null | undefined, products?: readonly {
96
97
  media?: readonly {
97
98
  type?: string;
98
99
  }[] | null;
99
- }[]): Record<string, string>;
100
+ }[], modelRendered?: boolean): Record<string, string>;
100
101
  /** Which kinds of third-party / 3D media the page's products carry (kit `ProductMedia.type`). */
101
102
  export declare function pageMedia(products: readonly {
102
103
  media?: readonly {
package/dist/server.js CHANGED
@@ -38,9 +38,12 @@ import { AbiCartProvider } from './abi/cart.js';
38
38
  import { listingQueryOfRequest, loadPageData, pageParamsOf, searchQueryOf, searchSortOf } from './abi/page-data.js';
39
39
  import { createDataApi } from './abi/data-api.js';
40
40
  import { collectStyles, STYLE_RULES_ID } from './sdk/sx.js';
41
+ import { FONT_IMPORTS_ID, fontImportCss } from './sdk/fonts.js';
41
42
  import { ServerRenderProvider } from './sdk/server-render.js';
42
43
  import { locationOf, nodesOf, notFoundTree } from './abi/page.js';
43
44
  import { HeadSinkContext, PageInfoContext } from './headless/page.js';
45
+ import { ChunkSinkContext } from './headless/lazy-section.js';
46
+ import { ResolvedSinkContext } from './runtime/render/resolved.js';
44
47
  import { absoluteOn, breadcrumbJsonLd, collectionJsonLd } from './headless/structured-data.js';
45
48
  const RTL = new Set(['ar', 'he', 'fa', 'ur', 'yi', 'ps', 'dv', 'ckb']);
46
49
  const esc = (v) => String(v ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
@@ -56,12 +59,49 @@ function tagsFor(ctx) {
56
59
  tags.push(`${ctx.route.kind}:${ctx.route.handle}`);
57
60
  return tags.filter(ok).slice(0, 8);
58
61
  }
59
- /** Script/style tags for this artifact's client bundle — every URL under assets.base with SRI (§2.2). */
60
- function assetTags(ctx) {
62
+ /**
63
+ * Script/style tags for this artifact's client bundle — every URL under assets.base with SRI (§2.2). A client-chunks
64
+ * artifact (§2.2.1 revision 2): the page's rendered chunk keys (`tq-chunks`, keys only) and the boot, and never a
65
+ * modulepreload link (WebKit stores a preloaded module without checking its integrity); the import map that checks
66
+ * every chunk fetch is importMapTag, the first thing in <head>.
67
+ */
68
+ /** The isEntry script entry of this artifact's client manifest, if any. */
69
+ const clientEntry = (ctx) => Object.values(ctx.assets.manifest).find((e) => e.isEntry && e.kind === 'script');
70
+ /**
71
+ * A client-chunks artifact's one import map (§2.2.1 revision 2), its exact signed text, or ''. Emitted as the first
72
+ * element of <head> that can load a module; its CSP hash is asserted per render and admitted only because it is in the
73
+ * signed inlineScriptHashes. Only when assets are on the shop's origin (§2.5): the map's path-absolute keys name
74
+ * `/assets/…` there; anywhere else the page carries no map, the boot's probe pair fails and it loads the single bundle.
75
+ */
76
+ function importMapTag(ctx) {
77
+ const e = clientEntry(ctx);
78
+ if (!e?.core || typeof e.importMap !== 'string')
79
+ return '';
80
+ let sameOrigin = false;
81
+ try {
82
+ sameOrigin = new URL(ctx.assets.base).origin === new URL(ctx.route.canonical).origin && new URL(ctx.assets.base).pathname.replace(/\/$/, '') === '';
83
+ }
84
+ catch {
85
+ sameOrigin = false;
86
+ }
87
+ return sameOrigin ? `<script type="importmap">${e.importMap}</script>` : '';
88
+ }
89
+ /** sha256 of the exact bytes between the tags, as the bare CSP token (`sha256-<base64>`) the gateway expects. */
90
+ async function scriptHashToken(text) {
91
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
92
+ let bin = '';
93
+ for (const b of new Uint8Array(digest))
94
+ bin += String.fromCharCode(b);
95
+ return `sha256-${btoa(bin)}`;
96
+ }
97
+ function assetTags(ctx, chunks) {
61
98
  const base = ctx.assets.base;
62
99
  const entries = Object.values(ctx.assets.manifest);
63
100
  const byFile = new Map(entries.map((e) => [e.file, e]));
64
- const entry = entries.find((e) => e.isEntry && e.kind === 'script');
101
+ // theme-abi-v2 §2.2.2: on a preview host (the editor canvas) the preview profile's bundle, with the full definitions;
102
+ // everywhere else the shopper profile's isEntry script. A live host answers 404 for the preview file anyway.
103
+ const previewEntry = ctx.mode === 'preview' ? entries.find((e) => e.profile === 'preview' && e.kind === 'script') : undefined;
104
+ const entry = previewEntry ?? entries.find((e) => e.isEntry && e.kind === 'script');
65
105
  if (!entry)
66
106
  return '';
67
107
  const link = (file, rel) => {
@@ -70,7 +110,9 @@ function assetTags(ctx) {
70
110
  };
71
111
  return [
72
112
  ...(entry.css ?? []).map((f) => link(f, 'stylesheet')),
73
- ...(entry.imports ?? []).map((f) => link(f, 'modulepreload')),
113
+ ...(entry.core ? [] : (entry.imports ?? []).map((f) => link(f, 'modulepreload'))),
114
+ // The section chunks this page rendered, by key only (the boot takes every file and hash from its own table).
115
+ ...(entry.core ? [`<script type="application/json" id="tq-chunks">${jsonBlock([...(chunks ?? [])].filter((k) => entry.chunks?.[k]).sort())}</script>`] : []),
74
116
  `<script type="module" src="${esc(`${base}/${entry.file}`)}" integrity="${esc(entry.integrity)}" crossorigin="anonymous"></script>`,
75
117
  ].join('');
76
118
  }
@@ -275,9 +317,13 @@ export function createRender(options) {
275
317
  // The theme's own words as the merchant translated them for this language (abi/labels.ts); the editor shows the theme's.
276
318
  const labels = preview ? {} : labelsOf(merchantStrings, ctx.locale.market);
277
319
  const sink = sf ? { jsonLd: [] } : null;
320
+ // Client chunks (theme-abi-v2 §2.2.1): the keys of the lazy sections this render drew, for the head's preloads.
321
+ const chunkSink = new Set();
322
+ // §2.2.2: every rendered node's resolved settings, for the page state (the shopper bundle needs no schema)
323
+ const resolvedSink = new Map();
278
324
  // Dynamic style values become class rules collected for THIS render (sdk/sx.ts): the
279
325
  // platform CSP has `style-src-attr 'none'`, so no `style=""` attribute may reach the page.
280
- const { result: body, css: styleRules } = collectStyles(() => renderToString(_jsx(PageExtras, { page: page, sink: sink, children: _jsx(ServerRenderProvider, { value: true, children: _jsx(PreviewModeProvider, { value: preview, children: _jsx(DataProvider, { value: data, children: _jsx(ThemeProvider, { settings: settings, locale: strings, children: _jsx(AbiCartProvider, { initial: pd.cart, remote: null, children: _jsx(AbiShell, { location: location, locale: ui, contentLanguage: lang, settings: settings, preview: preview, labels: labels, children: _jsx(SectionTree, { tree: (!preview && pd.routeMissing ? notFoundTree(nodes) : nodes) }) }) }) }) }) }) }) })));
326
+ const { result: body, css: styleRules, fonts: fontFamilies } = collectStyles(() => renderToString(_jsx(ChunkSinkContext.Provider, { value: chunkSink, children: _jsx(ResolvedSinkContext.Provider, { value: resolvedSink, children: _jsx(PageExtras, { page: page, sink: sink, children: _jsx(ServerRenderProvider, { value: true, children: _jsx(PreviewModeProvider, { value: preview, children: _jsx(DataProvider, { value: data, children: _jsx(ThemeProvider, { settings: settings, locale: strings, children: _jsx(AbiCartProvider, { initial: pd.cart, remote: null, children: _jsx(AbiShell, { location: location, locale: ui, contentLanguage: lang, settings: settings, preview: preview, labels: labels, children: _jsx(SectionTree, { tree: (!preview && pd.routeMissing ? notFoundTree(nodes) : nodes) }) }) }) }) }) }) }) }) }) })));
281
327
  const canonicalPath = new URL(ctx.route.canonical).pathname;
282
328
  let head = computeHead(canonicalPath, data, settings, new URL(ctx.route.canonical).origin);
283
329
  const shopName = shopNameOf(settings.shopName, pd.shop.name);
@@ -369,15 +415,18 @@ export function createRender(options) {
369
415
  extraHead,
370
416
  ].filter(Boolean).join('\n ');
371
417
  // What the browser needs to rebuild the same tree: this page's content and the data it rendered.
372
- const state = { route: { ...ctx.route, params }, page: ctx.content.page, settings, data: pd, now, preview, ui, lang, ...(listing ? { listing } : {}), ...(page ? { kit: page } : {}), ...(Object.keys(labels).length ? { labels } : {}) };
418
+ const state = { route: { ...ctx.route, params }, page: ctx.content.page, settings, data: pd, now, preview, ui, lang, ...(listing ? { listing } : {}), ...(page ? { kit: page } : {}), ...(Object.keys(labels).length ? { labels } : {}), ...(resolvedSink.size && manifest?.client?.editorProfile === true ? { resolved: Object.fromEntries(resolvedSink) } : {}) };
419
+ // §2.2.1 revision 2: the one import map, first, before anything that can load a module
420
+ const mapTag = importMapTag(ctx);
373
421
  const html = `<!doctype html>
374
422
  <html lang="${esc(lang)}" dir="${dir}">
375
423
  <head>
376
424
  <meta charset="utf-8">
377
- <meta name="viewport" content="width=device-width, initial-scale=1">
425
+ ${mapTag}<meta name="viewport" content="width=device-width, initial-scale=1">
378
426
  <title>${esc(head.title)}</title>
379
427
  ${meta}
380
- ${assetTags(ctx)}
428
+ ${assetTags(ctx, chunkSink)}
429
+ ${fontFamilies.length ? `<style id="${FONT_IMPORTS_ID}">${fontImportCss(fontFamilies)}</style>` : ''}
381
430
  ${styleRules ? `<style id="${STYLE_RULES_ID}">${styleRules}</style>` : ''}
382
431
  ${!preview && settings.enableSpaNavigation !== false ? `<style id="${VIEW_TRANSITIONS_ID}">${VIEW_TRANSITIONS_CSS}</style>` : ''}
383
432
  </head>
@@ -390,10 +439,14 @@ export function createRender(options) {
390
439
  const headers = new Headers({ 'content-type': 'text/html; charset=utf-8' });
391
440
  for (const hash of await styleHashes(html))
392
441
  headers.append('x-tq-csp-style-hash', hash);
393
- for (const [name, value] of Object.entries(platformHints(preview, settings, pd.shop, Object.values(pd.products ?? {}))))
442
+ if (mapTag)
443
+ headers.append('x-tq-csp-script-hash', await scriptHashToken(clientEntry(ctx).importMap));
444
+ const modelRendered = sink?.model === true;
445
+ for (const [name, value] of Object.entries(platformHints(preview, settings, pd.shop, Object.values(pd.products ?? {}), modelRendered)))
394
446
  headers.set(name, value);
395
- // NEW-PROD-2: a 3D model on the page ⇒ the theme's viewer styles are announced too (bounded by the edge's budget)
396
- if (!preview && pageMedia(Object.values(pd.products ?? {})).model)
447
+ // NEW-PROD-2: a 3D model on the page ⇒ the theme's viewer styles are announced too (bounded by the edge's budget);
448
+ // on a preview host as well, where the gateway also opens the viewer (`x-tq-media: model`, platformHints)
449
+ if (modelRendered || pageMedia(Object.values(pd.products ?? {})).model)
397
450
  for (const hash of options.modelViewerStyleHashes ?? [])
398
451
  if (/^sha(256|384|512)-[A-Za-z0-9+/=]+$/.test(hash))
399
452
  headers.append('x-tq-csp-style-hash', hash);
@@ -406,29 +459,32 @@ export function createRender(options) {
406
459
  };
407
460
  }
408
461
  /**
409
- * The live-only hints the storefront gateway acts on (storefront-edge core/platform-hints.ts); it drops every `x-tq-*`
410
- * before the page leaves, so a browser never sees them.
462
+ * The hints the storefront gateway acts on (storefront-edge core/platform-hints.ts); it drops every `x-tq-*` before the
463
+ * page leaves, so a browser never sees them. Live only, except `x-tq-media: model`.
411
464
  * x-tq-speculation: on NEW-OS-11 part 2 — `enableSpaNavigation` is not off: the gateway adds its
412
465
  * `Speculation-Rules` header, so hovering a link prerenders the next page.
413
466
  * x-tq-turnstile: on A4 — the store's spam protection asks for the Turnstile widget on a form this theme can show
414
467
  * (`shop.spamProtection`, either switch): the gateway allows Cloudflare Turnstile in the CSP.
415
468
  * x-tq-media: video, model NEW-PROD-2 — a product on the page has a YouTube / Vimeo video (the gateway frames
416
469
  * `www.youtube-nocookie.com` and `player.vimeo.com`) and/or a 3D model (`connect-src blob:`).
417
- * Never in the editor canvas (a preview host ignores them too).
470
+ * In the editor canvas / a draft preview only `x-tq-media: model`: the 3D viewer runs there too (the gateway honours
471
+ * `model` on a preview host and ignores the rest, core/platform-hints.ts says why).
418
472
  */
419
- export function platformHints(preview, settings, shop, products = []) {
473
+ export function platformHints(preview, settings, shop, products = [], modelRendered = false) {
474
+ // NEW-PROD-2 (rev 2.52): a YouTube / Vimeo video ⇒ the gateway frames those two players; a 3D model ⇒ it lets the
475
+ // viewer read its file (same-origin model route, `blob:` textures)
476
+ const m = pageMedia(products);
477
+ // a `<ModelViewer>` the render drew (a `model` setting, B.4) counts like a product's model
478
+ const model = m.model || modelRendered;
420
479
  if (preview)
421
- return {};
480
+ return model ? { 'x-tq-media': 'model' } : {};
422
481
  const out = {};
423
482
  if (settings.enableSpaNavigation !== false)
424
483
  out['x-tq-speculation'] = 'on';
425
484
  const sp = shop?.spamProtection;
426
485
  if (sp && (sp.contactForms || sp.authPages))
427
486
  out['x-tq-turnstile'] = 'on';
428
- // NEW-PROD-2 (rev 2.52): a YouTube / Vimeo video ⇒ the gateway frames those two players; a 3D model ⇒ it lets the
429
- // viewer read its file (same-origin model route, `blob:` textures)
430
- const m = pageMedia(products);
431
- const media = [...(m.video ? ['video'] : []), ...(m.model ? ['model'] : [])];
487
+ const media = [...(m.video ? ['video'] : []), ...(model ? ['model'] : [])];
432
488
  if (media.length)
433
489
  out['x-tq-media'] = media.join(', ');
434
490
  return out;
@@ -0,0 +1,10 @@
1
+ export interface TanqoryChunksPlugin {
2
+ name: string;
3
+ transform(code: string, id: string): {
4
+ code: string;
5
+ map: null;
6
+ } | null;
7
+ }
8
+ export declare function tanqoryChunks(options?: {
9
+ root?: string;
10
+ }): TanqoryChunksPlugin;
@@ -0,0 +1,44 @@
1
+ /**
2
+ * `@tanqory/theme-kit/vite-chunks` — a theme's own Vite builds and tests with client chunks (theme-abi-v2.md §2.2.1).
3
+ *
4
+ * The platform bundler (build-service) rewrites a client-chunks theme's `import('./x')` itself: through the boot's gate
5
+ * in the browser, into a static import on the server. A theme's own toolchain needs the server half too: React's
6
+ * renderToString cannot wait for a module, so a lazy section must already be loaded when the server (or a test) renders
7
+ * it. `tanqoryChunks()` gives Vite the same rewrite for the builds that render without a browser:
8
+ *
9
+ * import('./Hero') → __tqChunkStatic("src/sections/Hero/Hero", __tq_chunk_0) (+ import * as __tq_chunk_0 from './Hero')
10
+ *
11
+ * Use it in the SSR build and in Vitest; leave the theme's own client build alone (Vite splits `import()` natively there).
12
+ * Only relative literal specifiers are rewritten, the same rule the platform enforces (a computed one is left for the
13
+ * platform build to refuse).
14
+ */
15
+ const IMPORT_CALL = /(?<![\w$.])import\s*\(\s*(['"])(\.{1,2}\/[^'"\n]+)\1\s*\)/g;
16
+ export function tanqoryChunks(options = {}) {
17
+ return {
18
+ name: 'tanqory-chunks-static',
19
+ transform(code, id) {
20
+ const file = id.split('?')[0];
21
+ // after Vite's own TypeScript transform (no `enforce`), so a type-position `import('./x').T` is already gone; only
22
+ // theme source, never a test (a test's own `await import()` stays dynamic)
23
+ if (file.includes('/node_modules/') || /\/tests?\//.test(file) || /\.test\.[jt]sx?$/.test(file) || !/\.(tsx?|jsx?|mjs)$/.test(file))
24
+ return null;
25
+ if (!/(?<![\w$.])import\s*\(/.test(code))
26
+ return null;
27
+ const head = [];
28
+ let n = 0;
29
+ const cwd = globalThis.process?.cwd?.() ?? '';
30
+ const root = (options.root ?? cwd).replace(/\/$/, '');
31
+ const dir = file.slice(0, file.lastIndexOf('/'));
32
+ const out = code.replace(IMPORT_CALL, (_m, _q, spec) => {
33
+ const name = `__tq_chunk_${n++}`;
34
+ head.push(`import * as ${name} from ${JSON.stringify(spec)};`);
35
+ const abs = new URL(spec, `file://${dir}/`).pathname;
36
+ const key = abs.startsWith(`${root}/`) ? abs.slice(root.length + 1) : abs;
37
+ return `__tqChunkStatic(${JSON.stringify(key)}, ${name})`;
38
+ });
39
+ if (!n)
40
+ return null;
41
+ return { code: `import { __tqChunkStatic } from '@tanqory/theme-kit/chunks';\n${head.join('\n')}\n${out}`, map: null };
42
+ },
43
+ };
44
+ }
@@ -112,7 +112,14 @@ on the editor canvas a setting edit re-renders the section in place (`tq:canvas`
112
112
 
113
113
  `field.*`: `text`, `textarea`, `richtext`, `url`, `color`, `boolean`, `select(options, default, { optionLabels })`,
114
114
  `range(default, min, max, step, { unit })`, `number(…)`, `resource('image' | 'video' | 'menu' | 'collection' |
115
- 'product' | 'page' | 'blog' | 'article', default?)`. Every field takes `{ label, info, placeholder, group }`.
115
+ 'product' | 'page' | 'blog' | 'article', default?)`, `model({ label })`. Every field takes `{ label, info, placeholder, group }`.
116
+
117
+ A 3D model setting is `field.model({ label: '3D model' })`: the editor lists the store's 3D model files (MODEL_3D) and
118
+ the value is the `.glb` file's https URL; show it with `<ModelViewer media={{ src: value }} />`. `field.resource('model')`
119
+ builds the same `model` setting in the manifest (`{ type: 'model' }`), but `model` is not one of the resource kinds the
120
+ TypeScript types list, so a typed theme writes `field.model()`. Either way the manifest declares field-type registry 4
121
+ (the build sets it when the theme names none). A product's own models need no setting: they are `useProduct().media`
122
+ items of `type: 'model'` (added in the dashboard or by the MCP tool `add_product_models`).
116
123
 
117
124
  ## 4. Data hooks
118
125
 
@@ -157,6 +164,8 @@ on the editor canvas a setting edit re-renders the section in place (`tq:canvas`
157
164
  | `<NewsletterForm>` / `<ContactForm>` | `<form method="post" data-tq-form="newsletter\|contact">` + honeypot | native platform post (declare `forms` in the manifest); the gateway's CSRF fields are kept on hydration; status messages after the post |
158
165
  | `<ConsentBanner>` | `<section data-tq-consent-banner aria-label>` | only when the platform asks; the merchant's wording wins; never in preview |
159
166
  | `<AccountSlot>` | `<iframe data-tq-slot="account" sandbox="allow-scripts allow-forms allow-same-origin">` | the platform's account area on the customer route |
167
+ | `<ModelViewer media alt? ar? fallback?>` | a poster and a "View in 3D" `<button>`; then the platform's `<model-viewer>` | a product's 3D model (`useProduct().media` items of `type: 'model'`, or a `model` setting's value as `{ src: value }`). The platform serves the viewer from the shop's own origin and loads it only when the shopper presses the button, so the theme bundle carries 0 KB of 3D code. `alt` defaults to the model's own alt text (give a setting or the product title, never a literal); `ar` (default on) offers "View in your space". A custom theme writes no WebGL, WebGPU, `<model-viewer>`, Worker or WebAssembly of its own: the checks refuse them (`no_3d_code`, `no_worker`, `no_wasm`). A 2D `<canvas>` is allowed. |
168
+ | `<ModelViewerBase media labels alt? ar? fallback?>` | the same markup as `<ModelViewer>` | for a theme whose locale files carry the four `media.*` keys: `labels` is `{ view3d, loading3d, unavailable, viewInYourSpace }` in the theme's own words. It does not use `t()`, so the kit's fallback word table (English and Thai, about 3 KB gzip) stays out of the theme's client bundle. `<ModelViewer>` is this with the kit's words. |
160
169
 
161
170
  ## 6. Platform helpers
162
171
 
@@ -164,14 +173,35 @@ on the editor canvas a setting edit re-renders the section in place (`tq:canvas`
164
173
  the merchant's dashboard wording → your `locales/<lang>.json` → the kit's words for that language
165
174
  (`KIT_STRINGS`, English and Thai) → English → the key. `withKitStrings(locales)` (build) lays your files over
166
175
  the kit's, so every key the primitives use exists in every locale you ship.
167
- - **`formatMoney(money, { display, trimZeros })`**: `$37.50`, `¥5,625`, `฿1,312.50`, `1.250 KWD`. The currency's
168
- own minor units (`currencyDecimals`), identical on the server and in the browser.
176
+ - **`formatMoney(money, { display, trimZeros })`**: `$37.50`, `¥5,625`, `฿1,312.50`, `1.250 KWD`, `Rp15,000`. The
177
+ digits a price is shown with (`displayDigits`: ISO 4217's, HUF IDR TWD whole), exact, identical on the server and
178
+ in the browser. `currencyDecimals` is the amount's ISO 4217 digits (IDR 2), not what is shown.
179
+ - **Money maths**: `currencyDigits`, `displayDigits`, `displayAmount`, `roundMoney`, `toFixedDigits`, `mul`, `sub`,
180
+ `div` from `@tanqory/theme-kit`: the platform's one currency table and exact decimal maths, for a theme's own price
181
+ arithmetic (never a JS number's `toFixed` or a digits table of its own).
169
182
  - **`<Image image alt>`**: `image` is an image from the data or an image setting's URL; `https:` URLs, or `asset:client/<file>` under the artifact's asset base; anything
170
183
  else renders `fallback`. Intrinsic width/height, `loading="lazy"`, `decoding="async"` by default.
171
184
  - **`<Seo title description image noindex jsonLd>`**: overrides for this page's head, collected during the
172
185
  server render. Title, description, canonical, Open Graph and the Product/Collection/Breadcrumb
173
186
  JSON-LD are already printed from the data, and so are the hreflang alternates (every theme, `createRender({ hreflang })`, default on); a Product object in `jsonLd` is ignored (exactly one per page).
174
187
  - **`<SkipLink>`**: to `#main`, the `<main>` the section renderer wraps the page body in.
188
+ - **Fonts** (`fontSetting`, `field.font`, `useFont`, `FONT_CATALOGUE`): a font setting is a `select` the editor draws
189
+ as its font picker, offering the platform catalogue first (17 families, 8 of them Thai: Noto Sans Thai, Noto Serif
190
+ Thai, IBM Plex Sans Thai, Sarabun, Prompt, Kanit, Anuphan, Mitr), then the theme's own fonts (`themeFonts`), then the
191
+ device's faces (`system-sans`, `system-serif`, `system-mono`, `system-rounded`).
192
+
193
+ ```tsx
194
+ // src/settings.ts
195
+ export const settings = defineSettings({ headingFont: fontSetting({ label: 'Heading font', group: 'Typography', default: 'Prompt' }) })
196
+ // src/theme.tsx (Layout)
197
+ const heading = useFont(useSettings().headingFont) // '"Prompt", sans-serif', and Prompt loads
198
+ return <div className={sx({ '--font-heading': heading })}>{children}</div>
199
+ ```
200
+
201
+ A catalogue family loads from the store's own `/_tq/fonts` (the server imports it in the kit's hashed `<style>`; a
202
+ family picked on the editor canvas is fetched and inserted through the CSSOM), so no rule of the storefront changes.
203
+ A theme font is a WOFF2 the theme ships under `assets/` with its own `@font-face` in `src/styles/*.css`;
204
+ `useFont(value, themeFonts)` names it. A value that is not one of the offered fonts writes no CSS.
175
205
 
176
206
  ## 7. The manifest (`@tanqory/theme-kit/build`)
177
207
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanqory/theme-kit",
3
- "version": "2.0.0-alpha.17",
3
+ "version": "2.0.0-alpha.19",
4
4
  "description": "Tanqory theme kit for Theme ABI v2: the headless storefront API (data hooks, accessible commerce primitives, SEO, i18n, live edit), the runtime behind it (data plan, cart, wire client) and the render/hydrate entry factories a theme builds on.",
5
5
  "license": "MIT",
6
6
  "author": "Tanqory",
@@ -17,6 +17,7 @@
17
17
  "url": "git+https://github.com/tanqory/tanqory-platform-theme-kit.git"
18
18
  },
19
19
  "type": "module",
20
+ "sideEffects": false,
20
21
  "engines": {
21
22
  "node": ">=20.0.0",
22
23
  "pnpm": ">=9.7.0"
@@ -37,6 +38,14 @@
37
38
  "types": "./dist/client.d.ts",
38
39
  "default": "./dist/client.js"
39
40
  },
41
+ "./chunks": {
42
+ "types": "./dist/chunks.d.ts",
43
+ "default": "./dist/chunks.js"
44
+ },
45
+ "./vite-chunks": {
46
+ "types": "./dist/vite-chunks.d.ts",
47
+ "default": "./dist/vite-chunks.js"
48
+ },
40
49
  "./headless": {
41
50
  "types": "./dist/headless/index.d.ts",
42
51
  "default": "./dist/headless/index.js"
@@ -76,22 +85,5 @@
76
85
  "@tanqory/theme-abi": ">=2.0.0-alpha.11",
77
86
  "react": "~18.3.1",
78
87
  "react-dom": "~18.3.1"
79
- },
80
- "devDependencies": {
81
- "@tanqory/theme-abi": "link:../theme-abi",
82
- "@testing-library/dom": "^10.4.0",
83
- "@testing-library/react": "^16.3.0",
84
- "@testing-library/user-event": "^14.6.1",
85
- "@types/node": "^22.20.5",
86
- "@types/react": "^18.3.12",
87
- "@types/react-dom": "^18.3.1",
88
- "axe-core": "^4.10.3",
89
- "husky": "^9.1.7",
90
- "jsdom": "^25.0.1",
91
- "react": "18.3.1",
92
- "react-dom": "18.3.1",
93
- "typescript": "~5.9.3",
94
- "vite": "^5.4.10",
95
- "vitest": "^3.2.4"
96
88
  }
97
89
  }