@eldrajs/theme-cli 0.2.0 → 0.2.1

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 (66) hide show
  1. package/package.json +3 -3
  2. package/template/.eldra/block-types.d.ts +12 -3
  3. package/template/.eldra/manifest.json +315 -25
  4. package/template/.eldra/previews.json +35 -34
  5. package/template/.github/workflows/eldra-deploy.yml +2 -0
  6. package/template/.gitlab-ci.yml +2 -0
  7. package/template/.storybook/main.ts +3 -0
  8. package/template/README.md +22 -10
  9. package/template/app/components/FormHoneypot.vue +21 -0
  10. package/template/app/composables/useFormSpam.ts +55 -0
  11. package/template/app/composables/usePageStructuredData.ts +112 -0
  12. package/template/app/composables/useTurnstile.ts +111 -0
  13. package/template/app/formSeeds.ts +93 -0
  14. package/template/app/pages/[...slug].vue +48 -12
  15. package/template/app/plugins/eldra-storefront.ts +19 -2
  16. package/template/app/seededPages.ts +7 -0
  17. package/template/app/storefront/analytics.ts +202 -0
  18. package/template/app/storefront/cart.ts +7 -0
  19. package/template/app/storefront/demo.ts +48 -2
  20. package/template/app/storefront/forms.ts +133 -0
  21. package/template/app/storefront/gateway.ts +113 -7
  22. package/template/app/storefront/structuredData.ts +161 -0
  23. package/template/app/storefront/types.ts +101 -2
  24. package/template/app/utils/seoInput.ts +172 -0
  25. package/template/bitbucket-pipelines.yml +3 -1
  26. package/template/blocks/breadcrumbs/Block.vue +1 -0
  27. package/template/blocks/cart/Block.vue +1 -0
  28. package/template/blocks/cart/parts/Summary.vue +1 -0
  29. package/template/blocks/contact/Block.vue +50 -21
  30. package/template/blocks/contact/__tests__/Block.spec.ts +89 -8
  31. package/template/blocks/contact/block.json +2 -9
  32. package/template/blocks/contact/mock.json +1 -2
  33. package/template/blocks/footer/Block.vue +56 -6
  34. package/template/blocks/footer/__tests__/Block.spec.ts +70 -16
  35. package/template/blocks/footer/preview.png +0 -0
  36. package/template/blocks/form/Block.vue +614 -0
  37. package/template/blocks/form/__tests__/Block.spec.ts +536 -0
  38. package/template/blocks/form/block.json +69 -0
  39. package/template/blocks/form/mock.json +25 -0
  40. package/template/blocks/form/preview.png +0 -0
  41. package/template/blocks/form/validate.ts +68 -0
  42. package/template/blocks/newsletter/Block.vue +57 -3
  43. package/template/blocks/newsletter/__tests__/Block.spec.ts +89 -31
  44. package/template/blocks/newsletter/block.json +4 -5
  45. package/template/blocks/newsletter/mock.json +1 -1
  46. package/template/blocks/newsletter/preview.png +0 -0
  47. package/template/i18n/en-US.json +33 -2
  48. package/template/i18n/is-IS.json +33 -2
  49. package/template/nuxt.config.ts +6 -0
  50. package/template/stories/generated/form.stories.ts +68 -0
  51. package/template/test/formValidate.spec.ts +46 -0
  52. package/template/test/prerenderFailure.spec.ts +1 -1
  53. package/template/test/prerenderRefresh.browser.spec.ts +5 -1
  54. package/template/test/seededPages.spec.ts +13 -0
  55. package/template/test/seoInput.spec.ts +119 -0
  56. package/template/test/slugPage.spec.ts +62 -26
  57. package/template/test/slugPageTemplate.spec.ts +5 -1
  58. package/template/test/starter.spec.ts +41 -3
  59. package/template/test/storefront/analytics.spec.ts +283 -0
  60. package/template/test/storefront/forms.spec.ts +385 -0
  61. package/template/test/storefront/structuredData.spec.ts +138 -0
  62. package/template/test/structuredData.generate.spec.ts +159 -0
  63. package/template/test/support/mockGateway.ts +29 -1
  64. package/template/test/support/turnstileForms.ts +53 -0
  65. package/template/app/utils/pageTitle.ts +0 -37
  66. package/template/test/pageTitle.spec.ts +0 -49
@@ -0,0 +1,202 @@
1
+ import { watch, type Ref } from 'vue';
2
+ import type {
3
+ StorefrontCartLine,
4
+ StorefrontProduct,
5
+ StorefrontResult,
6
+ StorefrontSearchResponse,
7
+ StorefrontSource,
8
+ } from './types';
9
+
10
+ /**
11
+ * Commerce analytics for the storefront, as a wrapper around a `StorefrontSource` — the same
12
+ * layer `app/storefront/feedback.ts` reports failures from, and for the same reason: blocks call
13
+ * `useStorefront()` and know nothing about tracking, so a block can neither forget an event nor
14
+ * send one twice. `app/plugins/eldra-storefront.ts` wraps the source it provides with the
15
+ * `useEldraAnalytics().track` of `@eldrajs/theme-nuxt`; this file touches no Nuxt global.
16
+ *
17
+ * Events (the contract the platform's analytics ingest stores; props are strings):
18
+ *
19
+ * | name | props |
20
+ * | ------------------ | ------------------------------------------------------------------ |
21
+ * | `product_view` | `product_id`, `handle`, `variant_id`, `value`, `currency` |
22
+ * | `add_to_cart` | `product_id`, `variant_id`, `quantity`, `value`, `currency` |
23
+ * | `remove_from_cart` | the same |
24
+ * | `begin_checkout` | `cart_id`, `item_count`, `value`, `currency` |
25
+ * | `search` | `query` (trimmed, 100 characters), `result_count` |
26
+ *
27
+ * `add_to_cart` / `remove_from_cart` also cover a quantity change (the difference) and an undone
28
+ * removal (an add). `search` is sent once per settled query across the header panel and the
29
+ * search page.
30
+ *
31
+ * `value` is major units with `.` as the decimal separator and `currency` is ISO 4217. `purchase`
32
+ * is never sent from the browser: it belongs to the order module.
33
+ *
34
+ * Nothing here identifies a shopper or stores anything in the browser.
35
+ */
36
+
37
+ export type Track = (name: string, props?: Record<string, string | number | undefined>) => void;
38
+
39
+ /** How long a search query must stay put before it counts, so partial typing is never sent. */
40
+ export const SEARCH_DEBOUNCE_MS = 800;
41
+ /** A search query is cut to this many characters. */
42
+ export const SEARCH_QUERY_MAX = 100;
43
+
44
+ /** Major units as a decimal string (`28`, `28.5`, `28.05`), never exponent notation. */
45
+ export function formatValue(amount: number): string {
46
+ return String(Math.round(amount * 10000) / 10000);
47
+ }
48
+
49
+ /** The cart id a checkout URL ends with (`{checkoutUrl}/checkout/{orgId}/{cartId}`), if it does. */
50
+ export function cartIdFromCheckoutUrl(url: string | null): string | undefined {
51
+ if (url === null) return undefined;
52
+ const segments = url.split(/[?#]/)[0]!.split('/').filter(Boolean);
53
+ return segments.length >= 3 && segments[segments.length - 3] === 'checkout'
54
+ ? segments[segments.length - 1]
55
+ : undefined;
56
+ }
57
+
58
+ export function withAnalytics(source: StorefrontSource, track: Track): StorefrontSource {
59
+ const currency = (): string | undefined => source.commerce?.currency;
60
+
61
+ function lineProps(
62
+ line: Pick<StorefrontCartLine, 'productId' | 'variantId' | 'unitPrice'>,
63
+ quantity: number
64
+ ): Record<string, string | number | undefined> {
65
+ return {
66
+ product_id: line.productId,
67
+ variant_id: line.variantId,
68
+ quantity,
69
+ value: formatValue(line.unitPrice * quantity),
70
+ currency: currency(),
71
+ };
72
+ }
73
+
74
+ // `product_view` once per product per visit: several blocks may read the same product, and a
75
+ // volatile refresh re-resolves it, so the dedupe lives here, on the route — it resets when the
76
+ // route's product changes (including to none), so A -> cart -> A is two visits.
77
+ let viewed: string | null = null;
78
+ watch(
79
+ () => source.route.productHandle,
80
+ () => {
81
+ viewed = null;
82
+ }
83
+ );
84
+
85
+ const catalog: StorefrontSource['catalog'] = {
86
+ ...source.catalog,
87
+ product(handle) {
88
+ const result = source.catalog.product(handle);
89
+ watch(
90
+ () => result.data.value,
91
+ (product: StorefrontProduct | null) => {
92
+ if (product === null || product === undefined || viewed === product.handle) return;
93
+ // Only the page's own product: a "related" read is not a view.
94
+ if (source.route.productHandle !== product.handle) return;
95
+ viewed = product.handle;
96
+ track('product_view', {
97
+ product_id: product.productId,
98
+ handle: product.handle,
99
+ variant_id: product.variantId,
100
+ value: formatValue(product.price.amount),
101
+ currency: currency(),
102
+ });
103
+ },
104
+ { immediate: true }
105
+ );
106
+ return result;
107
+ },
108
+ };
109
+
110
+ const cart: StorefrontSource['cart'] = {
111
+ ...source.cart,
112
+ async add(input) {
113
+ const failure = await source.cart.add(input);
114
+ if (failure === null) {
115
+ // The price comes from the line the cart now holds for the variant, which is what the
116
+ // shopper was charged for; a variant the cart cannot show yet is sent without a value.
117
+ const line = source.cart.lines.value.find((l) => l.variantId === input.variantId);
118
+ track('add_to_cart', {
119
+ ...(line ? lineProps(line, input.quantity) : { quantity: input.quantity }),
120
+ product_id: input.productId,
121
+ variant_id: input.variantId,
122
+ currency: currency(),
123
+ });
124
+ }
125
+ return failure;
126
+ },
127
+ async remove(lineId) {
128
+ const line = source.cart.lines.value.find((l) => l.id === lineId);
129
+ const failure = await source.cart.remove(lineId);
130
+ if (failure === null && line !== undefined) {
131
+ track('remove_from_cart', lineProps(line, line.quantity));
132
+ }
133
+ return failure;
134
+ },
135
+ async setQuantity(lineId, quantity) {
136
+ const before = source.cart.lines.value.find((l) => l.id === lineId);
137
+ const failure = await source.cart.setQuantity(lineId, quantity);
138
+ if (failure === null && before !== undefined) {
139
+ // The cart's own answer, not the request: the backend may clamp to stock.
140
+ const after = source.cart.lines.value.find((l) => l.id === lineId);
141
+ const diff = (after?.quantity ?? 0) - before.quantity;
142
+ if (diff !== 0) {
143
+ track(diff > 0 ? 'add_to_cart' : 'remove_from_cart', lineProps(before, Math.abs(diff)));
144
+ }
145
+ }
146
+ return failure;
147
+ },
148
+ async undoRemove() {
149
+ // Undo puts a line back that `remove` already counted as removed, so it is an add.
150
+ const restored = source.cart.lastRemoved.value?.line;
151
+ const failure = await source.cart.undoRemove();
152
+ if (failure === null && restored !== undefined) {
153
+ track('add_to_cart', lineProps(restored, restored.quantity));
154
+ }
155
+ return failure;
156
+ },
157
+ beginCheckout() {
158
+ source.cart.beginCheckout();
159
+ const totals = source.cart.totals.value;
160
+ track('begin_checkout', {
161
+ cart_id: cartIdFromCheckoutUrl(source.cart.checkoutUrl.value),
162
+ item_count: source.cart.count.value,
163
+ value: totals ? formatValue(totals.total) : undefined,
164
+ currency: currency(),
165
+ });
166
+ },
167
+ };
168
+
169
+ // One `search` per settled query per visit, across surfaces: the header panel and the search
170
+ // page both run a search, and a shopper who presses Enter on "mug" searched once, not twice.
171
+ // It lives here, on the source, so the page that takes over sees what the panel already sent.
172
+ let lastSent: string | null = null;
173
+ const search: StorefrontSource['search'] = {
174
+ ...source.search,
175
+ run(query: Ref<string>): StorefrontResult<StorefrontSearchResponse> {
176
+ const result = source.search.run(query);
177
+ let timer: ReturnType<typeof setTimeout> | undefined;
178
+ watch(
179
+ [query, result.data],
180
+ ([text, response]) => {
181
+ clearTimeout(timer);
182
+ const trimmed = (text ?? '').trim();
183
+ // Only a result that answers *this* query counts, and only once typing has stopped.
184
+ if (trimmed === '' || response === null || response === undefined) return;
185
+ if (response.query.trim() !== trimmed || trimmed === lastSent) return;
186
+ timer = setTimeout(() => {
187
+ if (lastSent === trimmed) return;
188
+ lastSent = trimmed;
189
+ track('search', {
190
+ query: trimmed.slice(0, SEARCH_QUERY_MAX),
191
+ result_count: response.total,
192
+ });
193
+ }, SEARCH_DEBOUNCE_MS);
194
+ },
195
+ { immediate: true }
196
+ );
197
+ return result;
198
+ },
199
+ };
200
+
201
+ return { ...source, catalog, cart, search };
202
+ }
@@ -66,6 +66,12 @@ export interface CartStore {
66
66
  applyDiscount(code: string): Promise<StorefrontAck>;
67
67
  removeDiscount(code: string): Promise<StorefrontFailure | null>;
68
68
  checkoutUrl: ComputedRef<string | null>;
69
+ /**
70
+ * The shopper followed the Check out link. Does nothing here — the link itself does the
71
+ * navigating — and exists as the one hook `app/storefront/analytics.ts` listens on to record a
72
+ * `begin_checkout`, which a source-level wrapper cannot observe from a plain `href`.
73
+ */
74
+ beginCheckout: () => void;
69
75
  }
70
76
 
71
77
  /**
@@ -177,6 +183,7 @@ export function createCartStore(ops: CartOps): CartStore {
177
183
  drawerHosted,
178
184
  lastRemoved,
179
185
  checkoutUrl,
186
+ beginCheckout: () => undefined,
180
187
  add: (input) => run(() => ops.add(input)),
181
188
  setQuantity: (lineId, quantity) => run(() => ops.setQuantity(lineId, quantity)),
182
189
  async remove(lineId) {
@@ -1,4 +1,6 @@
1
1
  import { nextTick, reactive, ref, watch, type Ref } from 'vue';
2
+ import { starterFormSeeds } from '../formSeeds';
3
+ import { localizeFormDefinition } from './forms';
2
4
  import { createCartStore, type CartOps, type CartSnapshot } from './cart';
3
5
  import { createHistoryStore, createWishlistStore } from './history';
4
6
  import { roundMoney } from './money';
@@ -25,6 +27,7 @@ import type {
25
27
  StorefrontCollectionSelector,
26
28
  StorefrontCommerce,
27
29
  StorefrontForms,
30
+ StorefrontFormSubmitResult,
28
31
  StorefrontMedia,
29
32
  StorefrontOrder,
30
33
  StorefrontOrderStatus,
@@ -1129,7 +1132,10 @@ export interface DemoStorefrontOptions {
1129
1132
  query?: string;
1130
1133
  collectionHandle?: string;
1131
1134
  productHandle?: string;
1135
+ /** Makes `forms.submit` (and `catalog.notifyBackInStock`) fail, for the "service is down" states. */
1132
1136
  failForms?: boolean;
1137
+ /** The locale the demo forms are written in; `en-US` by default. */
1138
+ formLocale?: string;
1133
1139
  /** Seeds the cart with these lines, e.g. `DEMO_CART_LINES` — the demo cart is empty otherwise. */
1134
1140
  cartLines?: StorefrontCartLine[];
1135
1141
  /** Seeds `route.sort` — restores `collection-grid`'s sort choice the way a shared URL would. */
@@ -1292,8 +1298,48 @@ export function createDemoStorefront(options: DemoStorefrontOptions = {}): Store
1292
1298
  };
1293
1299
 
1294
1300
  const forms: StorefrontForms = {
1295
- subscribe: () => ack(),
1296
- sendMessage: () => ack(),
1301
+ definition: (key) =>
1302
+ createDemoResult([key], () => {
1303
+ const seed = starterFormSeeds().find((candidate) => candidate.key === key.value);
1304
+ if (seed === undefined) return null;
1305
+ return localizeFormDefinition(
1306
+ {
1307
+ key: seed.key,
1308
+ name: seed.name,
1309
+ fields: seed.fields,
1310
+ honeypotField: 'website',
1311
+ turnstileSiteKey: null,
1312
+ success: seed.success,
1313
+ kinds: [
1314
+ 'store',
1315
+ ...(seed.actions.notify ? (['notify'] as const) : []),
1316
+ ...(seed.actions.subscribe ? (['subscribe'] as const) : []),
1317
+ ],
1318
+ // The platform fills `{shop}` in before it answers; the demo store is Northwind Goods.
1319
+ ...(seed.actions.subscribe?.consentText
1320
+ ? {
1321
+ consentText: Object.fromEntries(
1322
+ Object.entries(seed.actions.subscribe.consentText).map(([locale, text]) => [
1323
+ locale,
1324
+ text.replaceAll('{shop}', 'Northwind Goods'),
1325
+ ])
1326
+ ),
1327
+ }
1328
+ : {}),
1329
+ },
1330
+ options.formLocale ?? 'en-US'
1331
+ );
1332
+ }),
1333
+ // Always succeeds, like the demo's other writes; a spec that needs a refusal replaces `submit`.
1334
+ submit: async (key): Promise<StorefrontFormSubmitResult> => {
1335
+ await nextTick();
1336
+ if (options.failForms) return { ok: false, reason: 'unavailable' };
1337
+ return {
1338
+ ok: true,
1339
+ pending:
1340
+ starterFormSeeds().find((seed) => seed.key === key)?.actions.subscribe !== undefined,
1341
+ };
1342
+ },
1297
1343
  };
1298
1344
 
1299
1345
  return {
@@ -0,0 +1,133 @@
1
+ import type { EldraFormDefinition, EldraFormSubmitResult } from '@eldrajs/sdk';
2
+ import type {
3
+ StorefrontFormDefinition,
4
+ StorefrontFormField,
5
+ StorefrontFormFieldType,
6
+ StorefrontFormSubmitResult,
7
+ } from './types';
8
+
9
+ /**
10
+ * Picks the text for `locale` out of a per-locale map the platform publishes
11
+ * (`{ 'en-US': 'Name', 'is-IS': 'Nafn' }`): the exact tag, then the same language
12
+ * (`is` for `is-IS`), then the map's first entry, then `''`. The platform never guesses a
13
+ * fallback for the page, so this is the one place the page does.
14
+ */
15
+ export function pickLocalized(
16
+ map: Record<string, string> | undefined,
17
+ locale: string | undefined
18
+ ): string {
19
+ if (map === undefined) return '';
20
+ const entries = Object.entries(map);
21
+ if (entries.length === 0) return '';
22
+ if (locale !== undefined) {
23
+ const exact = map[locale];
24
+ if (exact !== undefined) return exact;
25
+ const language = locale.split('-')[0]?.toLowerCase();
26
+ const sameLanguage = entries.find(([tag]) => tag.split('-')[0]?.toLowerCase() === language);
27
+ if (sameLanguage !== undefined) return sameLanguage[1];
28
+ }
29
+ return entries[0]?.[1] ?? '';
30
+ }
31
+
32
+ const FORM_FIELD_TYPES: ReadonlySet<string> = new Set<StorefrontFormFieldType>([
33
+ 'text',
34
+ 'email',
35
+ 'phone',
36
+ 'textarea',
37
+ 'select',
38
+ 'checkbox',
39
+ 'consent',
40
+ 'number',
41
+ 'url',
42
+ ]);
43
+
44
+ /**
45
+ * A definition as the platform serves it, with every per-locale text resolved for `locale`.
46
+ * Throws on a field type this theme cannot render: a form with a field it would show as the wrong
47
+ * control (a `consent` as a text box) is refused whole, so the block shows its load-failed state
48
+ * instead of collecting values the platform would reject.
49
+ */
50
+ export function localizeFormDefinition(
51
+ raw: EldraFormDefinition,
52
+ locale: string | undefined
53
+ ): StorefrontFormDefinition {
54
+ for (const field of raw.fields) {
55
+ if (!FORM_FIELD_TYPES.has(field.type)) {
56
+ throw new Error(`form “${raw.key}”: unsupported field type “${String(field.type)}”`);
57
+ }
58
+ }
59
+ const fields = raw.fields.map((field): StorefrontFormField => {
60
+ const out: StorefrontFormField = {
61
+ id: field.id,
62
+ type: field.type,
63
+ required: field.required,
64
+ label: pickLocalized(field.label, locale),
65
+ };
66
+ if (field.placeholder !== undefined) {
67
+ const placeholder = pickLocalized(field.placeholder, locale);
68
+ if (placeholder !== '') out.placeholder = placeholder;
69
+ }
70
+ if (field.options !== undefined) {
71
+ out.options = field.options.map((option) => ({
72
+ value: option.value,
73
+ label: pickLocalized(option.label, locale),
74
+ }));
75
+ }
76
+ if (field.validation !== undefined) out.validation = field.validation;
77
+ return out;
78
+ });
79
+ const redirect = pickLocalized(raw.success.redirect, locale);
80
+ return {
81
+ key: raw.key,
82
+ name: raw.name,
83
+ fields,
84
+ honeypotField: raw.honeypotField,
85
+ turnstileSiteKey: raw.turnstileSiteKey,
86
+ successMessage: pickLocalized(raw.success.message, locale),
87
+ successRedirect: redirect === '' ? null : redirect,
88
+ consentText: pickLocalized(raw.consentText, locale),
89
+ };
90
+ }
91
+
92
+ /** The SDK's submit answer in the storefront's own shape. */
93
+ export function toSubmitResult(result: EldraFormSubmitResult): StorefrontFormSubmitResult {
94
+ return result.status === 'ok'
95
+ ? { ok: true, pending: result.pending }
96
+ : { ok: false, reason: 'invalid', errors: result.errors, form: result.form };
97
+ }
98
+
99
+ /** What a rejected submit (`EldraHttpError`, a network failure) means to a visitor. */
100
+ export function submitFailure(error: unknown): StorefrontFormSubmitResult {
101
+ const status =
102
+ typeof error === 'object' && error !== null && 'status' in error
103
+ ? (error as { status: unknown }).status
104
+ : undefined;
105
+ if (status === 429) return { ok: false, reason: 'rate-limited' };
106
+ if (status === 413) return { ok: false, reason: 'too-large' };
107
+ return { ok: false, reason: 'unavailable' };
108
+ }
109
+
110
+ /**
111
+ * Posts a submission to the theme's own `formsEndpoint` (the override that predates the platform
112
+ * forms API, kept for a site that already has a form backend). `{ kind: 'form', key, values,
113
+ * locale, pagePath }` as JSON; any 2xx is a success, anything else — or no network — is
114
+ * `unavailable`. `unsupported` is what a call with neither the platform nor an endpoint gets.
115
+ */
116
+ export async function postToFormsEndpoint(
117
+ endpoint: string,
118
+ body: Record<string, unknown>
119
+ ): Promise<StorefrontFormSubmitResult> {
120
+ try {
121
+ const response = await fetch(endpoint, {
122
+ method: 'POST',
123
+ headers: { 'Content-Type': 'application/json' },
124
+ body: JSON.stringify({ kind: 'form', ...body }),
125
+ });
126
+ if (response.ok) return { ok: true, pending: false };
127
+ if (response.status === 429) return { ok: false, reason: 'rate-limited' };
128
+ if (response.status === 413) return { ok: false, reason: 'too-large' };
129
+ return { ok: false, reason: 'unavailable' };
130
+ } catch {
131
+ return { ok: false, reason: 'unavailable' };
132
+ }
133
+ }
@@ -1,8 +1,19 @@
1
1
  import { onWatcherCleanup, ref, watch, type Ref } from 'vue';
2
- import { createCartSession, EldraHttpError, type EldraClient } from '@eldrajs/sdk';
2
+ import {
3
+ createCartSession,
4
+ EldraHttpError,
5
+ type EldraClient,
6
+ type EldraFormDefinition,
7
+ } from '@eldrajs/sdk';
3
8
  import { safeHref } from '../utils/links';
4
9
  import { createCartStore, type CartOps, type CartSnapshot } from './cart';
5
10
  import { createHistoryStore, createWishlistStore } from './history';
11
+ import {
12
+ localizeFormDefinition,
13
+ postToFormsEndpoint,
14
+ submitFailure,
15
+ toSubmitResult,
16
+ } from './forms';
6
17
  import { fromMinorUnits, roundMoney, toMinorUnits } from './money';
7
18
  import { chunkIds, collectVolatileTargets } from './volatile';
8
19
  import { canonicalAvailabilityValues, OPTION_SOURCE_PREFIX } from './facets';
@@ -51,9 +62,10 @@ import type {
51
62
  * generated *test* fixture never imported here) — the same thing a real customer theme has to do
52
63
  * before its own `eldra()` Vite plugin has generated a contract against their tenant.
53
64
  *
54
- * `forms.subscribe`/`forms.sendMessage`/`catalog.notifyBackInStock` have no gateway endpoint
55
- * today: this posts to `options.formsEndpoint` when the plugin configured one, and resolves
56
- * `{ ok: false, reason: 'unsupported' }` otherwise.
65
+ * `catalog.notifyBackInStock` has no gateway endpoint today: this posts to `options.formsEndpoint`
66
+ * when the plugin configured one, and resolves `{ ok: false, reason: 'unsupported' }` otherwise.
67
+ * Forms are the platform's own (`client.forms`, `GET /site/v1/forms/{key}`); `formsEndpoint` only
68
+ * overrides where a *submission* goes.
57
69
  */
58
70
 
59
71
  // ---------------------------------------------------------------------------------------------
@@ -189,6 +201,8 @@ interface RawProductOption {
189
201
  interface RawProductVariant {
190
202
  id: string;
191
203
  sku: string;
204
+ /** Free text; the structured data validates it as a GTIN before it writes one. */
205
+ barcode?: string | null;
192
206
  price: number;
193
207
  compareAtPrice?: number;
194
208
  status: string;
@@ -223,6 +237,8 @@ interface RawProductDetails {
223
237
  * knows the response carries it rather than inferring the catalogue only ever assigns one.
224
238
  */
225
239
  categoryIds?: string[] | null;
240
+ /** Per-product brand, for `Product.brand` in the structured data. */
241
+ brand?: string | null;
226
242
  description?: Record<string, unknown>;
227
243
  mediaLinks?: RawMediaItem[] | null;
228
244
  options?: RawProductOption[] | null;
@@ -584,6 +600,16 @@ function mapProductDetails(
584
600
  ? (stock?.get(countableVariant.id)?.availableQuantity ?? null)
585
601
  : null,
586
602
  stock: variantStock(firstAvailable, stock),
603
+ brand: raw.brand?.trim() || null,
604
+ // Each variant's own price and stock state, for the page's structured data: the same
605
+ // `variantStock` rule the buy box's line uses, so the markup and the page cannot disagree.
606
+ variants: variants.map((variant) => ({
607
+ sku: variant.sku,
608
+ barcode: variant.barcode ?? null,
609
+ price: variant.price,
610
+ compareAt: variant.compareAtPrice ?? null,
611
+ stock: variantStock(variant, stock),
612
+ })),
587
613
  available: raw.status === 'ACTIVE',
588
614
  productId: raw.id,
589
615
  // The variant an add would send, paired with `productId` above: the cart service looks the two
@@ -1869,7 +1895,24 @@ async function detailSnapshots(
1869
1895
 
1870
1896
  export interface GatewayStorefrontOptions {
1871
1897
  route: StorefrontRoute;
1898
+ /**
1899
+ * Overrides where form submissions go (`forms.submit`); see `postToFormsEndpoint`. Form
1900
+ * definitions still come from the platform. Also the endpoint `catalog.notifyBackInStock` posts to.
1901
+ */
1872
1902
  formsEndpoint?: string;
1903
+ /**
1904
+ * The form definitions the build baked (`@eldrajs/theme-nuxt`, `eldra.forms` in the runtime
1905
+ * config), by form key. A key found here is the first paint (and the prerendered HTML); the
1906
+ * browser then re-reads it live, because the platform serves definitions with no rebuild. Any
1907
+ * other key is fetched.
1908
+ */
1909
+ formDefinitions?: Record<string, EldraFormDefinition>;
1910
+ /**
1911
+ * The locale a submission reports and a definition's text resolves to: the page's active content
1912
+ * locale, the default locale included (unlike `locale`, which is `undefined` there so reads keep
1913
+ * their pre-locale keys). Omitted — a story, a spec — `en-US`.
1914
+ */
1915
+ formLocale?: () => string | undefined;
1873
1916
  /**
1874
1917
  * What the store sells in (`StorefrontCommerce`) — the platform's own answer, which only the app
1875
1918
  * layer can read (`app/plugins/eldra-storefront.ts`, off the runtime config). Omitted — a
@@ -2235,10 +2278,73 @@ export function createGatewayStorefront(
2235
2278
  ),
2236
2279
  };
2237
2280
 
2281
+ const formLocale = (): string => options.formLocale?.() ?? locale?.() ?? 'en-US';
2238
2282
  const forms: StorefrontForms = {
2239
- subscribe: (input) => postToEndpoint(options.formsEndpoint, { kind: 'subscribe', ...input }),
2240
- sendMessage: (input) =>
2241
- postToEndpoint(options.formsEndpoint, { kind: 'sendMessage', ...input }),
2283
+ definition: (key) => {
2284
+ const result = createGatewayResult(
2285
+ [key],
2286
+ async (signal) => {
2287
+ // Re-resolved against the page's locale on every read, so a language switch relabels a
2288
+ // baked definition too: only the platform's per-locale maps are baked, never one language.
2289
+ if (key.value === '') return null;
2290
+ const raw =
2291
+ options.formDefinitions?.[key.value] ??
2292
+ (await rawClient.forms.get(key.value, { signal }));
2293
+ return localizeFormDefinition(raw, formLocale());
2294
+ },
2295
+ { method: 'forms.definition', runtime, locale: () => formLocale() }
2296
+ );
2297
+ // The platform serves a definition live (`GET /site/v1/forms/{key}`, no rebuild when a
2298
+ // merchant edits a form), so the baked copy is only the first paint: once the page is open
2299
+ // in a browser the live definition replaces it, which is what makes a field added in Studio
2300
+ // render, and what turns the spam-check widget on when Turnstile was enabled after the
2301
+ // build. A failed read keeps the baked definition on screen.
2302
+ if (typeof window !== 'undefined' && options.formDefinitions !== undefined) {
2303
+ let generation = 0;
2304
+ const revalidate = async (): Promise<void> => {
2305
+ const requested = key.value;
2306
+ if (requested === '' || options.formDefinitions?.[requested] === undefined) return;
2307
+ generation += 1;
2308
+ const mine = generation;
2309
+ try {
2310
+ const raw = await rawClient.forms.get(requested);
2311
+ if (mine !== generation || key.value !== requested) return;
2312
+ result.data.value = localizeFormDefinition(raw, formLocale());
2313
+ } catch {
2314
+ // Offline, a transient 5xx, or a type this theme cannot render: keep what is shown.
2315
+ }
2316
+ };
2317
+ void revalidate();
2318
+ watch(key, () => void revalidate());
2319
+ }
2320
+ return result;
2321
+ },
2322
+ submit: async (key, input) => {
2323
+ const pagePath = typeof location === 'undefined' ? '/' : location.pathname;
2324
+ if (options.formsEndpoint) {
2325
+ return postToFormsEndpoint(options.formsEndpoint, {
2326
+ key,
2327
+ values: input.values,
2328
+ locale: formLocale(),
2329
+ pagePath,
2330
+ ...(input.turnstileToken ? { turnstileToken: input.turnstileToken } : {}),
2331
+ ...(input.hp ? { hp: input.hp } : {}),
2332
+ });
2333
+ }
2334
+ try {
2335
+ return toSubmitResult(
2336
+ await rawClient.forms.submit(key, {
2337
+ values: input.values,
2338
+ locale: formLocale(),
2339
+ pagePath,
2340
+ ...(input.turnstileToken ? { turnstileToken: input.turnstileToken } : {}),
2341
+ ...(input.hp ? { hp: input.hp } : {}),
2342
+ })
2343
+ );
2344
+ } catch (error) {
2345
+ return submitFailure(error);
2346
+ }
2347
+ },
2242
2348
  };
2243
2349
 
2244
2350
  return {