@eldrajs/theme-cli 0.2.0 → 0.2.2

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 +31 -2
  6. package/template/.gitlab-ci.yml +37 -8
  7. package/template/.storybook/main.ts +3 -0
  8. package/template/README.md +25 -13
  9. package/template/app/components/FormHoneypot.vue +21 -0
  10. package/template/app/composables/useFormSpam.ts +56 -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 +22 -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 +25 -3
  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 +66 -9
  34. package/template/blocks/footer/__tests__/Block.spec.ts +136 -17
  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
@@ -1,11 +1,17 @@
1
1
  <script setup lang="ts">
2
2
  import { computed } from 'vue';
3
- import { EldraBlockZone, EldraLayout, getBlockSchemaApiId } from '@eldrajs/theme-vue';
3
+ import {
4
+ EldraBlockZone,
5
+ EldraLayout,
6
+ getBlockSchemaApiId,
7
+ useEldraLocale,
8
+ } from '@eldrajs/theme-vue';
4
9
  import { Button, Container, Section } from '@eldrajs/ui';
5
10
  import EldraRouterLink from '../components/EldraRouterLink.vue';
6
11
  import { useI18n } from 'vue-i18n';
7
12
  import { partitionPageBlocks } from '../utils/pageStructure';
8
- import { pageTitle } from '../utils/pageTitle';
13
+ import { seoInput } from '../utils/seoInput';
14
+ import { useMoney } from '../storefront/money';
9
15
 
10
16
  const {
11
17
  page,
@@ -41,18 +47,48 @@ const isNotFound = computed(
41
47
  () => isNotFoundRoute.value || (page.value === null && template.value === null)
42
48
  );
43
49
 
44
- useHead(() => ({
45
- title: pageTitle({
50
+ // The title, description, canonical, Open Graph and robots tags come from the platform's SEO
51
+ // settings (Studio, Website and theme) and the route's own `seo` field, resolved by the one
52
+ // resolver Studio's previews share. A catalog route is named by the object it shows — the shared
53
+ // route template's own title names the template ("Product" on every product page) — and the
54
+ // not-found shell names itself and is never indexed. See `docs/theme-seo.md`.
55
+ const money = useMoney();
56
+ const { supported } = useEldraLocale();
57
+ // The product's category name for `product.category`: the deepest level of the trail the product
58
+ // page draws (same cache key as the blocks and `usePageStructuredData`, so no extra read).
59
+ const seoProduct = useStorefront().catalog.product(
60
+ computed(() => (catalog.value?.kind === 'product' ? catalog.value.slug : null))
61
+ ).data;
62
+ const seo = computed(() =>
63
+ seoInput({
64
+ productCategory: seoProduct.value?.categoryTrail.at(-1)?.label ?? null,
46
65
  isNotFound: isNotFound.value,
47
66
  notFoundTitle: t('notFound.title'),
48
- // A catalog-backed route (a product, a collection) renders through a shared route template
49
- // whose own title names the template — "Product" on every product page. The object's own
50
- // title is on the resolved catalog `entry`, which is what the tab, the bookmark and the
51
- // search result should say.
52
- catalogTitle: catalog.value === null ? null : entry.value?.data.title,
53
- documentTitle: (template.value ?? page.value)?.data.title,
54
- }),
55
- }));
67
+ catalog: catalog.value,
68
+ entry: entry.value,
69
+ page: page.value,
70
+ template: template.value,
71
+ path: route.path,
72
+ locales: supported,
73
+ formatPrice: money.format,
74
+ })
75
+ );
76
+ const resolvedSeo = useEldraSeo(
77
+ () => seo.value.context,
78
+ () => seo.value.data,
79
+ () => seo.value.options
80
+ );
81
+ // The schema.org JSON-LD (`Product`, `BreadcrumbList`, `ItemList`, `Organization`, `WebSite`), from
82
+ // the same product, price and stock the page renders; a `noindex` page carries none. See
83
+ // `app/composables/usePageStructuredData.ts` and `docs/theme-seo.md`.
84
+ usePageStructuredData({
85
+ catalog,
86
+ isNotFound,
87
+ isHome: computed(() => seo.value.context === 'home'),
88
+ seo: resolvedSeo,
89
+ title: computed(() => String(seo.value.data['page.title'] ?? '')),
90
+ path: computed(() => route.path),
91
+ });
56
92
 
57
93
  /**
58
94
  * The page's flat block list, cut into the three landmark regions — see
@@ -1,6 +1,6 @@
1
1
  import { defineNuxtPlugin, useAsyncData, useRouter, useRuntimeConfig } from 'nuxt/app';
2
2
  import { getCurrentInstance, nextTick, reactive, watchEffect } from 'vue';
3
- import { createEldraClient, type EldraRetryOptions } from '@eldrajs/sdk';
3
+ import { createEldraClient, type EldraFormDefinition, type EldraRetryOptions } from '@eldrajs/sdk';
4
4
  import {
5
5
  STOREFRONT_KEY,
6
6
  type StorefrontRoute,
@@ -13,6 +13,7 @@ import {
13
13
  type StorefrontPrerenderHandle,
14
14
  type StorefrontRuntime,
15
15
  } from '../storefront/gateway';
16
+ import { withAnalytics } from '../storefront/analytics';
16
17
  import { createVolatileRefresher } from '../storefront/refresh';
17
18
  import {
18
19
  prerenderThroughAsyncData,
@@ -172,6 +173,7 @@ export default defineNuxtPlugin({
172
173
  orgId?: string;
173
174
  commerce?: unknown;
174
175
  retry?: EldraRetryOptions | null;
176
+ forms?: Record<string, EldraFormDefinition> | '';
175
177
  };
176
178
  formsEndpoint?: string;
177
179
  };
@@ -185,6 +187,9 @@ export default defineNuxtPlugin({
185
187
  // @eldrajs/theme-nuxt's, and a rate limit that only one of them waits
186
188
  // out still fails the build.
187
189
  retry: publicConfig.eldra?.retry ?? undefined,
190
+ // The read-only build token (`ELDRA_BUILD_TOKEN`), from the build environment and only during a prerender (`undefined` in
191
+ // the browser): it gives the build its own rate-limit budget at the gateway.
192
+ buildToken: useEldraBuildToken(),
188
193
  });
189
194
 
190
195
  let source: StorefrontSource | null = null;
@@ -280,9 +285,24 @@ export default defineNuxtPlugin({
280
285
  ? undefined
281
286
  : activeLocale.active,
282
287
  formsEndpoint: publicConfig.formsEndpoint,
288
+ // The form definitions the build baked (`@eldrajs/theme-nuxt`'s `forms` read); a form the
289
+ // build could not read, or the merchant made after it, is fetched when the page opens.
290
+ formDefinitions:
291
+ typeof publicConfig.eldra?.forms === 'object' ? publicConfig.eldra.forms : undefined,
292
+ // The default locale included: a submission always says which language it was written in,
293
+ // where `locale` above is `undefined` for it so catalogue reads keep their old keys.
294
+ formLocale: () => activeLocale.active ?? activeLocale.defaultLocale ?? undefined,
283
295
  runtime,
284
296
  });
285
297
 
286
- nuxtApp.vueApp.provide(STOREFRONT_KEY, source);
298
+ // Commerce events (`app/storefront/analytics.ts`) go through the tracker `@eldrajs/theme-nuxt`
299
+ // loads on a deployed site; everywhere else (dev, preview, no organisation, opted out)
300
+ // `enabled` is false and the source is provided untouched. The unwrapped `source` stays the one
301
+ // the refresher above reads.
302
+ const analytics = useEldraAnalytics();
303
+ nuxtApp.vueApp.provide(
304
+ STOREFRONT_KEY,
305
+ analytics.enabled ? withAnalytics(source, analytics.track) : source
306
+ );
287
307
  },
288
308
  });
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The slugs of the pages this theme seeds (`PAGE_SEEDS` in `./templates.ts`, which reads files and
3
+ * so cannot be imported at runtime). The storefront asks it whether a surface exists before it
4
+ * advertises it: the `WebSite` markup names a `SearchAction` only when the `search` page is seeded.
5
+ * `test/seededPages.spec.ts` fails when the two lists drift.
6
+ */
7
+ export const SEEDED_PAGE_SLUGS: readonly string[] = ['cart', 'wishlist', 'search', 'products'];
@@ -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
+ }