@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
@@ -0,0 +1,283 @@
1
+ import { nextTick, reactive, ref } from 'vue';
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
+ import {
4
+ cartIdFromCheckoutUrl,
5
+ formatValue,
6
+ SEARCH_DEBOUNCE_MS,
7
+ withAnalytics,
8
+ } from '../../app/storefront/analytics';
9
+ import { createCartStore, type CartOps } from '../../app/storefront/cart';
10
+ import type {
11
+ StorefrontCartLine,
12
+ StorefrontProduct,
13
+ StorefrontResult,
14
+ StorefrontSearchResponse,
15
+ StorefrontSource,
16
+ } from '../../app/storefront/types';
17
+
18
+ const line: StorefrontCartLine = {
19
+ id: 'line-1',
20
+ productId: 'p1',
21
+ variantId: 'v1',
22
+ title: 'Mug',
23
+ url: '/products/mug',
24
+ variantLabel: '',
25
+ quantity: 2,
26
+ unitPrice: 12.5,
27
+ lineTotal: 25,
28
+ image: null,
29
+ max: null,
30
+ };
31
+
32
+ function result<T>(initial: T | null): StorefrontResult<T> {
33
+ return {
34
+ data: ref(initial) as StorefrontResult<T>['data'],
35
+ pending: ref(false),
36
+ error: ref(null),
37
+ loading: ref(false),
38
+ revalidating: ref(new Set()),
39
+ refresh: () => Promise.resolve(),
40
+ };
41
+ }
42
+
43
+ function makeSource(overrides: { product?: StorefrontResult<StorefrontProduct> } = {}) {
44
+ const lines = [line];
45
+ const ops: CartOps = {
46
+ init: () => Promise.resolve({ lines: [], totals: { subtotal: 0, shipping: null, total: 0 } }),
47
+ add: () => Promise.resolve({ lines, totals: { subtotal: 25, shipping: null, total: 25 } }),
48
+ setQuantity: (_id, quantity) =>
49
+ Promise.resolve({
50
+ lines: [{ ...line, quantity }],
51
+ totals: { subtotal: 12.5 * quantity, shipping: null, total: 12.5 * quantity },
52
+ }),
53
+ remove: () => Promise.resolve({ lines: [], totals: { subtotal: 0, shipping: null, total: 0 } }),
54
+ applyDiscount: () => Promise.reject(new Error('unused')),
55
+ removeDiscount: () => Promise.reject(new Error('unused')),
56
+ checkoutUrl: ref('https://pay.example/checkout/org-1/cart-9'),
57
+ };
58
+ const cart = createCartStore(ops);
59
+ const route = reactive({ productHandle: 'mug' as string | null });
60
+ const searchResult = result<StorefrontSearchResponse>(null);
61
+ const product = overrides.product ?? result<StorefrontProduct>(null);
62
+ const source = {
63
+ commerce: { currency: 'USD', taxInclusivePricing: false, defaultTaxRate: 0 },
64
+ route,
65
+ cart,
66
+ catalog: { product: () => product },
67
+ search: { run: () => searchResult },
68
+ } as unknown as StorefrontSource;
69
+ return { source, cart, route, searchResult, product };
70
+ }
71
+
72
+ describe('formatValue / cartIdFromCheckoutUrl', () => {
73
+ it('writes major units with a dot', () => {
74
+ expect(formatValue(28)).toBe('28');
75
+ expect(formatValue(28.5)).toBe('28.5');
76
+ expect(formatValue(0.1 + 0.2)).toBe('0.3');
77
+ });
78
+
79
+ it('reads the cart id off the platform checkout URL', () => {
80
+ expect(cartIdFromCheckoutUrl('https://pay.example/checkout/org-1/cart-9')).toBe('cart-9');
81
+ expect(cartIdFromCheckoutUrl('https://pay.example/elsewhere')).toBeUndefined();
82
+ expect(cartIdFromCheckoutUrl(null)).toBeUndefined();
83
+ });
84
+ });
85
+
86
+ describe('withAnalytics', () => {
87
+ beforeEach(() => vi.useFakeTimers());
88
+ afterEach(() => vi.useRealTimers());
89
+
90
+ it('tracks add_to_cart only when the add succeeded', async () => {
91
+ const { source } = makeSource();
92
+ const track = vi.fn();
93
+ const wrapped = withAnalytics(source, track);
94
+ await wrapped.cart.add({ productId: 'p1', variantId: 'v1', quantity: 2 });
95
+ expect(track).toHaveBeenCalledWith('add_to_cart', {
96
+ product_id: 'p1',
97
+ variant_id: 'v1',
98
+ quantity: 2,
99
+ value: '25',
100
+ currency: 'USD',
101
+ });
102
+ });
103
+
104
+ it('does not track a refused add', async () => {
105
+ const { source } = makeSource();
106
+ const track = vi.fn();
107
+ const failing = {
108
+ ...source,
109
+ cart: { ...source.cart, add: () => Promise.resolve({ message: 'no' }) },
110
+ } as unknown as StorefrontSource;
111
+ await withAnalytics(failing, track).cart.add({ productId: 'p1', variantId: 'v1', quantity: 1 });
112
+ expect(track).not.toHaveBeenCalled();
113
+ });
114
+
115
+ it('tracks remove_from_cart with the removed line', async () => {
116
+ const { source, cart } = makeSource();
117
+ const track = vi.fn();
118
+ const wrapped = withAnalytics(source, track);
119
+ await cart.add({ productId: 'p1', variantId: 'v1', quantity: 2 });
120
+ await wrapped.cart.remove('line-1');
121
+ expect(track).toHaveBeenCalledWith('remove_from_cart', {
122
+ product_id: 'p1',
123
+ variant_id: 'v1',
124
+ quantity: 2,
125
+ value: '25',
126
+ currency: 'USD',
127
+ });
128
+ });
129
+
130
+ it('tracks a quantity change as the difference', async () => {
131
+ const { source, cart } = makeSource();
132
+ const track = vi.fn();
133
+ const wrapped = withAnalytics(source, track);
134
+ await cart.add({ productId: 'p1', variantId: 'v1', quantity: 2 });
135
+ await wrapped.cart.setQuantity('line-1', 5);
136
+ expect(track).toHaveBeenLastCalledWith('add_to_cart', {
137
+ product_id: 'p1',
138
+ variant_id: 'v1',
139
+ quantity: 3,
140
+ value: '37.5',
141
+ currency: 'USD',
142
+ });
143
+ await wrapped.cart.setQuantity('line-1', 4);
144
+ expect(track).toHaveBeenLastCalledWith('remove_from_cart', {
145
+ product_id: 'p1',
146
+ variant_id: 'v1',
147
+ quantity: 1,
148
+ value: '12.5',
149
+ currency: 'USD',
150
+ });
151
+ await wrapped.cart.setQuantity('line-1', 4);
152
+ expect(track).toHaveBeenCalledTimes(2);
153
+ });
154
+
155
+ it('tracks an undone removal as an add', async () => {
156
+ const { source, cart } = makeSource();
157
+ const track = vi.fn();
158
+ const wrapped = withAnalytics(source, track);
159
+ await cart.add({ productId: 'p1', variantId: 'v1', quantity: 2 });
160
+ await wrapped.cart.remove('line-1');
161
+ await wrapped.cart.undoRemove();
162
+ expect(track).toHaveBeenCalledTimes(2);
163
+ expect(track).toHaveBeenLastCalledWith('add_to_cart', {
164
+ product_id: 'p1',
165
+ variant_id: 'v1',
166
+ quantity: 2,
167
+ value: '25',
168
+ currency: 'USD',
169
+ });
170
+ });
171
+
172
+ it('tracks begin_checkout from the cart state when the shopper follows the link', async () => {
173
+ const { source, cart } = makeSource();
174
+ const track = vi.fn();
175
+ await cart.add({ productId: 'p1', variantId: 'v1', quantity: 2 });
176
+ withAnalytics(source, track).cart.beginCheckout();
177
+ expect(track).toHaveBeenCalledWith('begin_checkout', {
178
+ cart_id: 'cart-9',
179
+ item_count: 2,
180
+ value: '25',
181
+ currency: 'USD',
182
+ });
183
+ });
184
+
185
+ it('tracks product_view once per visit, and again after leaving the product', async () => {
186
+ const product = result<StorefrontProduct>({
187
+ handle: 'mug',
188
+ productId: 'p1',
189
+ variantId: 'v1',
190
+ price: { amount: 12.5 },
191
+ } as StorefrontProduct);
192
+ const { source, route } = makeSource({ product });
193
+ const track = vi.fn();
194
+ const wrapped = withAnalytics(source, track);
195
+ wrapped.catalog.product(ref('mug'));
196
+ wrapped.catalog.product(ref('mug'));
197
+ expect(track).toHaveBeenCalledTimes(1);
198
+ expect(track).toHaveBeenCalledWith('product_view', {
199
+ product_id: 'p1',
200
+ handle: 'mug',
201
+ variant_id: 'v1',
202
+ value: '12.5',
203
+ currency: 'USD',
204
+ });
205
+ // A refresh re-resolves the same product: no second view.
206
+ product.data.value = { ...product.data.value! };
207
+ await nextTick();
208
+ expect(track).toHaveBeenCalledTimes(1);
209
+ // Leaving and coming back is a new visit.
210
+ route.productHandle = null;
211
+ await nextTick();
212
+ route.productHandle = 'mug';
213
+ await nextTick();
214
+ product.data.value = { ...product.data.value! };
215
+ await nextTick();
216
+ expect(track).toHaveBeenCalledTimes(2);
217
+ });
218
+
219
+ it('does not count a related product as a view', () => {
220
+ const product = result<StorefrontProduct>({
221
+ handle: 'other',
222
+ productId: 'p2',
223
+ variantId: 'v2',
224
+ price: { amount: 1 },
225
+ } as StorefrontProduct);
226
+ const { source } = makeSource({ product });
227
+ const track = vi.fn();
228
+ withAnalytics(source, track).catalog.product(ref('other'));
229
+ expect(track).not.toHaveBeenCalled();
230
+ });
231
+
232
+ it('debounces search and sends the settled query once', async () => {
233
+ const { source, searchResult } = makeSource();
234
+ const track = vi.fn();
235
+ const query = ref('');
236
+ withAnalytics(source, track).search.run(query);
237
+ for (const text of ['m', 'mu', ' mug ']) {
238
+ query.value = text;
239
+ searchResult.data.value = { query: text, total: 3 } as StorefrontSearchResponse;
240
+ await nextTick();
241
+ vi.advanceTimersByTime(SEARCH_DEBOUNCE_MS / 4);
242
+ }
243
+ expect(track).not.toHaveBeenCalled();
244
+ vi.advanceTimersByTime(SEARCH_DEBOUNCE_MS);
245
+ expect(track).toHaveBeenCalledTimes(1);
246
+ expect(track).toHaveBeenCalledWith('search', { query: 'mug', result_count: 3 });
247
+ // The same settled query is not sent again.
248
+ searchResult.data.value = { query: 'mug', total: 3 } as StorefrontSearchResponse;
249
+ await nextTick();
250
+ vi.advanceTimersByTime(SEARCH_DEBOUNCE_MS * 2);
251
+ expect(track).toHaveBeenCalledTimes(1);
252
+ });
253
+
254
+ it('sends a query once when the header panel and the search page both run it', async () => {
255
+ const { source, searchResult } = makeSource();
256
+ const track = vi.fn();
257
+ const wrapped = withAnalytics(source, track);
258
+ const panel = ref('mug');
259
+ wrapped.search.run(panel);
260
+ searchResult.data.value = { query: 'mug', total: 3 } as StorefrontSearchResponse;
261
+ await nextTick();
262
+ vi.advanceTimersByTime(SEARCH_DEBOUNCE_MS * 2);
263
+ expect(track).toHaveBeenCalledTimes(1);
264
+ // The results page mounts with the same query.
265
+ wrapped.search.run(ref('mug'));
266
+ await nextTick();
267
+ vi.advanceTimersByTime(SEARCH_DEBOUNCE_MS * 2);
268
+ expect(track).toHaveBeenCalledTimes(1);
269
+ });
270
+
271
+ it('ignores an empty query and a result for a different query', async () => {
272
+ const { source, searchResult } = makeSource();
273
+ const track = vi.fn();
274
+ const query = ref('mug');
275
+ withAnalytics(source, track).search.run(query);
276
+ searchResult.data.value = { query: 'cup', total: 1 } as StorefrontSearchResponse;
277
+ await nextTick();
278
+ query.value = '';
279
+ await nextTick();
280
+ vi.advanceTimersByTime(SEARCH_DEBOUNCE_MS * 2);
281
+ expect(track).not.toHaveBeenCalled();
282
+ });
283
+ });
@@ -0,0 +1,385 @@
1
+ import { ref } from 'vue';
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+ import {
4
+ createEldraClient,
5
+ EldraHttpError,
6
+ type EldraFormDefinition,
7
+ type EldraHttpRequest,
8
+ } from '@eldrajs/sdk';
9
+ import { createGatewayStorefront } from '../../app/storefront/gateway';
10
+ import { localizeFormDefinition, pickLocalized } from '../../app/storefront/forms';
11
+ import type { StorefrontRoute } from '../../app/storefront/types';
12
+
13
+ /**
14
+ * The forms half of `createGatewayStorefront` over the **real** SDK client with a stub transport:
15
+ * what `forms.definition` serves (a baked definition with no request, any other fetched, every
16
+ * per-locale text resolved for the page) and what `forms.submit` sends and how it reads each answer
17
+ * (`422` field messages, `429`, `413`, an unreachable platform, the `formsEndpoint` override).
18
+ */
19
+ const definition: EldraFormDefinition = {
20
+ key: 'contact',
21
+ name: 'Contact',
22
+ fields: [
23
+ {
24
+ id: 'email',
25
+ type: 'email',
26
+ required: true,
27
+ label: { 'en-US': 'Email address', 'is-IS': 'Netfang' },
28
+ placeholder: { 'en-US': 'name@example.com' },
29
+ },
30
+ {
31
+ id: 'topic',
32
+ type: 'select',
33
+ required: false,
34
+ label: { 'en-US': 'Topic' },
35
+ options: [{ value: 'order', label: { 'en-US': 'An order', 'is-IS': 'Pöntun' } }],
36
+ validation: { maxLength: 40 },
37
+ },
38
+ ],
39
+ honeypotField: 'website',
40
+ turnstileSiteKey: '1x00000000000000000000AA',
41
+ success: {
42
+ message: { 'en-US': 'Thanks.', 'is-IS': 'Takk.' },
43
+ redirect: { 'en-US': '/thanks' },
44
+ },
45
+ kinds: ['store', 'notify'],
46
+ };
47
+
48
+ function route(): StorefrontRoute {
49
+ return {
50
+ productHandle: null,
51
+ collectionHandle: null,
52
+ categorySlug: null,
53
+ categoryPath: null,
54
+ orderToken: null,
55
+ query: null,
56
+ page: 1,
57
+ sort: null,
58
+ columns: null,
59
+ filters: {},
60
+ setQuery: () => {},
61
+ };
62
+ }
63
+
64
+ function problem(status: number, body: unknown = {}): EldraHttpError {
65
+ return new EldraHttpError(new Response('{}', { status, statusText: `S${status}` }), body);
66
+ }
67
+
68
+ function setup(
69
+ answer: (request: EldraHttpRequest) => unknown,
70
+ options: Partial<Parameters<typeof createGatewayStorefront>[1]> = {}
71
+ ) {
72
+ const requests: EldraHttpRequest[] = [];
73
+ const client = createEldraClient({
74
+ apiBaseUrl: 'https://api.example.test/api',
75
+ orgId: 'org-1',
76
+ httpClient: (async (request: EldraHttpRequest) => {
77
+ requests.push(request);
78
+ return answer(request);
79
+ }) as never,
80
+ });
81
+ const storefront = createGatewayStorefront(client, { route: route(), ...options });
82
+ return { storefront, requests };
83
+ }
84
+
85
+ afterEach(() => {
86
+ vi.unstubAllGlobals();
87
+ });
88
+
89
+ describe('pickLocalized', () => {
90
+ it('prefers the exact tag, then the same language, then the first entry', () => {
91
+ const map = { 'en-US': 'Name', 'is-IS': 'Nafn' };
92
+ expect(pickLocalized(map, 'is-IS')).toBe('Nafn');
93
+ expect(pickLocalized(map, 'is')).toBe('Nafn');
94
+ expect(pickLocalized({ 'en-GB': 'Colour' }, 'en-US')).toBe('Colour');
95
+ expect(pickLocalized(map, 'fr-FR')).toBe('Name');
96
+ expect(pickLocalized(map, undefined)).toBe('Name');
97
+ });
98
+
99
+ it('answers the empty string for nothing', () => {
100
+ expect(pickLocalized({}, 'en-US')).toBe('');
101
+ expect(pickLocalized(undefined, 'en-US')).toBe('');
102
+ });
103
+ });
104
+
105
+ describe('localizeFormDefinition', () => {
106
+ it('resolves every text for the locale and drops what the page does not need', () => {
107
+ const result = localizeFormDefinition(definition, 'is-IS');
108
+
109
+ expect(result.fields[0]).toEqual({
110
+ id: 'email',
111
+ type: 'email',
112
+ required: true,
113
+ label: 'Netfang',
114
+ placeholder: 'name@example.com',
115
+ });
116
+ expect(result.fields[1]?.options).toEqual([{ value: 'order', label: 'Pöntun' }]);
117
+ expect(result.fields[1]?.validation).toEqual({ maxLength: 40 });
118
+ expect(result).toMatchObject({
119
+ key: 'contact',
120
+ honeypotField: 'website',
121
+ turnstileSiteKey: '1x00000000000000000000AA',
122
+ successMessage: 'Takk.',
123
+ successRedirect: '/thanks',
124
+ });
125
+ expect(result).not.toHaveProperty('kinds');
126
+ });
127
+
128
+ it('resolves the consent sentence for the locale, and is empty without one', () => {
129
+ const subscribing = {
130
+ ...definition,
131
+ consentText: { 'en-US': 'I want mail from Shop.', 'is-IS': 'Ég vil póst frá Shop.' },
132
+ };
133
+ expect(localizeFormDefinition(subscribing, 'is-IS').consentText).toBe('Ég vil póst frá Shop.');
134
+ expect(localizeFormDefinition(definition, 'is-IS').consentText).toBe('');
135
+ });
136
+
137
+ it('refuses a field type the theme cannot render rather than showing it as text', () => {
138
+ const odd = {
139
+ ...definition,
140
+ fields: [{ ...definition.fields[0], type: 'signature' }],
141
+ } as unknown as EldraFormDefinition;
142
+ expect(() => localizeFormDefinition(odd, 'en-US')).toThrow(/unsupported field type/);
143
+ });
144
+
145
+ it('carries phone and consent fields through', () => {
146
+ const result = localizeFormDefinition(
147
+ {
148
+ ...definition,
149
+ fields: [
150
+ { id: 'phone', type: 'phone', required: true, label: { 'en-US': 'Phone' } },
151
+ { id: 'ok', type: 'consent', required: true, label: { 'en-US': 'I agree' } },
152
+ ],
153
+ },
154
+ 'en-US'
155
+ );
156
+ expect(result.fields.map((field) => field.type)).toEqual(['phone', 'consent']);
157
+ });
158
+
159
+ it('carries number and url fields through', () => {
160
+ const result = localizeFormDefinition(
161
+ {
162
+ ...definition,
163
+ fields: [
164
+ { id: 'qty', type: 'number', required: true, label: { 'en-US': 'Quantity' } },
165
+ { id: 'site', type: 'url', required: false, label: { 'en-US': 'Website' } },
166
+ ],
167
+ },
168
+ 'en-US'
169
+ );
170
+ expect(result.fields.map((field) => field.type)).toEqual(['number', 'url']);
171
+ });
172
+
173
+ it('has no redirect when the platform names none', () => {
174
+ const { redirect: _drop, ...success } = definition.success;
175
+ expect(localizeFormDefinition({ ...definition, success }, 'en-US').successRedirect).toBeNull();
176
+ });
177
+ });
178
+
179
+ describe('forms.definition', () => {
180
+ it('serves a baked definition with no request, resolved for the page locale', async () => {
181
+ const { storefront, requests } = setup(() => ({}), {
182
+ formDefinitions: { contact: definition },
183
+ formLocale: () => 'is-IS',
184
+ });
185
+
186
+ const result = storefront.forms.definition(ref('contact'));
187
+ await vi.waitFor(() => expect(result.pending.value).toBe(false));
188
+
189
+ expect(requests).toHaveLength(0);
190
+ expect(result.data.value?.fields[0]?.label).toBe('Netfang');
191
+ });
192
+
193
+ it('replaces the baked definition with the live one in a browser, and keeps it when the read fails', async () => {
194
+ vi.stubGlobal('window', {});
195
+ try {
196
+ const live = {
197
+ ...definition,
198
+ turnstileSiteKey: 'live-key',
199
+ fields: [{ ...definition.fields[0], label: { 'en-US': 'Live email' } }],
200
+ };
201
+ const { storefront, requests } = setup(() => live, {
202
+ formDefinitions: { contact: definition },
203
+ });
204
+ const result = storefront.forms.definition(ref('contact'));
205
+ await vi.waitFor(() => expect(result.data.value?.fields[0]?.label).toBe('Live email'));
206
+ expect(requests).toHaveLength(1);
207
+ expect(result.data.value?.turnstileSiteKey).toBe('live-key');
208
+
209
+ const failing = setup(
210
+ () => {
211
+ throw problem(503);
212
+ },
213
+ { formDefinitions: { contact: definition } }
214
+ );
215
+ const kept = failing.storefront.forms.definition(ref('contact'));
216
+ await vi.waitFor(() => expect(failing.requests).toHaveLength(1));
217
+ expect(kept.data.value?.fields[0]?.label).toBe('Email address');
218
+ } finally {
219
+ vi.unstubAllGlobals();
220
+ }
221
+ });
222
+
223
+ it('fetches a form that was not baked', async () => {
224
+ const { storefront, requests } = setup(() => definition);
225
+
226
+ const result = storefront.forms.definition(ref('contact'));
227
+ await vi.waitFor(() => expect(result.pending.value).toBe(false));
228
+
229
+ expect(requests.map((request) => request.url)).toEqual([
230
+ 'https://api.example.test/api/site/v1/forms/contact',
231
+ ]);
232
+ expect(result.data.value?.fields[0]?.label).toBe('Email address');
233
+ });
234
+
235
+ it('leaves data null, with an error, for a form the platform does not know', async () => {
236
+ const { storefront } = setup(() => {
237
+ throw problem(404);
238
+ });
239
+
240
+ const result = storefront.forms.definition(ref('nope'));
241
+ await vi.waitFor(() => expect(result.pending.value).toBe(false));
242
+
243
+ expect(result.data.value).toBeNull();
244
+ expect(result.error.value).not.toBeNull();
245
+ });
246
+ });
247
+
248
+ describe('forms.submit', () => {
249
+ const input = { values: { email: 'anna@example.is' } };
250
+
251
+ it('posts the values with the locale and page path, and omits an empty honeypot and token', async () => {
252
+ const { storefront, requests } = setup(() => ({ ok: true }), { formLocale: () => 'is-IS' });
253
+
254
+ const result = await storefront.forms.submit('contact', { ...input, hp: '' });
255
+
256
+ expect(result).toEqual({ ok: true, pending: false });
257
+ expect(requests[0]?.url).toBe('https://api.example.test/api/site/v1/forms/contact/submissions');
258
+ expect(JSON.parse(requests[0]?.body as string)).toEqual({
259
+ values: { email: 'anna@example.is' },
260
+ locale: 'is-IS',
261
+ pagePath: '/',
262
+ });
263
+ });
264
+
265
+ it('sends the Turnstile token and what a bot typed into the honeypot', async () => {
266
+ const { storefront, requests } = setup(() => ({ ok: true }));
267
+
268
+ await storefront.forms.submit('contact', { ...input, turnstileToken: 'tok', hp: 'spam' });
269
+
270
+ expect(JSON.parse(requests[0]?.body as string)).toMatchObject({
271
+ turnstileToken: 'tok',
272
+ hp: 'spam',
273
+ locale: 'en-US',
274
+ });
275
+ });
276
+
277
+ it('reports a pending double opt-in', async () => {
278
+ const { storefront } = setup(() => ({ ok: true, pending: true }));
279
+
280
+ expect(await storefront.forms.submit('newsletter', input)).toEqual({ ok: true, pending: true });
281
+ });
282
+
283
+ it('keeps a 422’s field-keyed messages', async () => {
284
+ const { storefront } = setup(() => {
285
+ throw problem(422, { errors: { email: ['Not an address.'] }, form: ['Check it.'] });
286
+ });
287
+
288
+ expect(await storefront.forms.submit('contact', input)).toEqual({
289
+ ok: false,
290
+ reason: 'invalid',
291
+ errors: { email: ['Not an address.'] },
292
+ form: ['Check it.'],
293
+ });
294
+ });
295
+
296
+ it.each([
297
+ [429, 'rate-limited'],
298
+ [413, 'too-large'],
299
+ [500, 'unavailable'],
300
+ [404, 'unavailable'],
301
+ ] as const)('reads a %i as %s', async (status, reason) => {
302
+ const { storefront } = setup(() => {
303
+ throw problem(status);
304
+ });
305
+
306
+ expect(await storefront.forms.submit('contact', input)).toEqual({ ok: false, reason });
307
+ });
308
+
309
+ it('reads an unreachable platform as unavailable, never a throw', async () => {
310
+ const { storefront } = setup(() => {
311
+ throw new TypeError('fetch failed');
312
+ });
313
+
314
+ expect(await storefront.forms.submit('contact', input)).toEqual({
315
+ ok: false,
316
+ reason: 'unavailable',
317
+ });
318
+ });
319
+
320
+ describe('with a formsEndpoint override', () => {
321
+ it('posts there instead of to the platform, and a 2xx is a success', async () => {
322
+ const fetchMock = vi.fn(async () => new Response('{}', { status: 200 }));
323
+ vi.stubGlobal('fetch', fetchMock);
324
+ const { storefront, requests } = setup(() => ({ ok: true }), {
325
+ formsEndpoint: 'https://forms.example.test/submit',
326
+ formLocale: () => 'is-IS',
327
+ });
328
+
329
+ const result = await storefront.forms.submit('contact', input);
330
+
331
+ expect(result).toEqual({ ok: true, pending: false });
332
+ expect(requests).toHaveLength(0);
333
+ expect(fetchMock).toHaveBeenCalledOnce();
334
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
335
+ expect(url).toBe('https://forms.example.test/submit');
336
+ expect(JSON.parse(init.body as string)).toEqual({
337
+ kind: 'form',
338
+ key: 'contact',
339
+ values: { email: 'anna@example.is' },
340
+ locale: 'is-IS',
341
+ pagePath: '/',
342
+ });
343
+ });
344
+
345
+ it('forwards the honeypot and the Turnstile token to the endpoint', async () => {
346
+ const fetchMock = vi.fn(async () => new Response('{}', { status: 200 }));
347
+ vi.stubGlobal('fetch', fetchMock);
348
+ const { storefront } = setup(() => ({ ok: true }), {
349
+ formsEndpoint: 'https://forms.example.test/submit',
350
+ });
351
+
352
+ await storefront.forms.submit('contact', { ...input, hp: 'bot', turnstileToken: 'tok' });
353
+
354
+ const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
355
+ expect(JSON.parse(init.body as string)).toMatchObject({ hp: 'bot', turnstileToken: 'tok' });
356
+ });
357
+
358
+ it.each([
359
+ [429, 'rate-limited'],
360
+ [413, 'too-large'],
361
+ [502, 'unavailable'],
362
+ ] as const)('reads the endpoint’s %i as %s', async (status, reason) => {
363
+ vi.stubGlobal(
364
+ 'fetch',
365
+ vi.fn(async () => new Response('{}', { status }))
366
+ );
367
+ const { storefront } = setup(() => ({}), { formsEndpoint: 'https://forms.example.test/s' });
368
+
369
+ expect(await storefront.forms.submit('contact', input)).toEqual({ ok: false, reason });
370
+ });
371
+
372
+ it('reads a network failure as unavailable', async () => {
373
+ vi.stubGlobal(
374
+ 'fetch',
375
+ vi.fn(async () => Promise.reject(new TypeError('offline')))
376
+ );
377
+ const { storefront } = setup(() => ({}), { formsEndpoint: 'https://forms.example.test/s' });
378
+
379
+ expect(await storefront.forms.submit('contact', input)).toEqual({
380
+ ok: false,
381
+ reason: 'unavailable',
382
+ });
383
+ });
384
+ });
385
+ });