@eldrajs/theme-cli 0.2.7 → 0.2.9

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 (169) hide show
  1. package/CHANGELOG.md +2 -0
  2. package/package.json +3 -3
  3. package/template/.eldra/block-types.d.ts +28 -7
  4. package/template/.eldra/manifest.json +1152 -445
  5. package/template/.eldra/previews.json +35 -35
  6. package/template/README.md +32 -0
  7. package/template/app/assets/main.css +23 -0
  8. package/template/app/plugins/eldra-storefront.ts +3 -0
  9. package/template/app/storefront/demo.ts +75 -24
  10. package/template/app/storefront/gateway.ts +16 -2
  11. package/template/blocks/announcement-bar/preview.png +0 -0
  12. package/template/blocks/article/preview.json +4 -4
  13. package/template/blocks/article/preview.png +0 -0
  14. package/template/blocks/article-list/Block.vue +48 -19
  15. package/template/blocks/article-list/__tests__/Block.spec.ts +15 -0
  16. package/template/blocks/article-list/preview.json +43 -43
  17. package/template/blocks/article-list/preview.png +0 -0
  18. package/template/blocks/breadcrumbs/preview.png +0 -0
  19. package/template/blocks/cart/preview.png +0 -0
  20. package/template/blocks/collection-grid/Block.vue +260 -9
  21. package/template/blocks/collection-grid/__tests__/Block.spec.ts +202 -0
  22. package/template/blocks/collection-grid/block.json +3 -3
  23. package/template/blocks/collection-grid/preview.png +0 -0
  24. package/template/blocks/collection-header/Block.vue +65 -52
  25. package/template/blocks/collection-header/preview.json +4 -4
  26. package/template/blocks/collection-header/preview.png +0 -0
  27. package/template/blocks/contact/preview.png +0 -0
  28. package/template/blocks/cta/preview.json +4 -4
  29. package/template/blocks/cta/preview.png +0 -0
  30. package/template/blocks/faq/preview.png +0 -0
  31. package/template/blocks/feature-grid/Block.vue +73 -4
  32. package/template/blocks/feature-grid/__tests__/Block.spec.ts +43 -1
  33. package/template/blocks/feature-grid/block.json +2 -2
  34. package/template/blocks/feature-grid/preview.json +49 -24
  35. package/template/blocks/feature-grid/preview.png +0 -0
  36. package/template/blocks/footer/Block.vue +186 -71
  37. package/template/blocks/footer/__tests__/Block.spec.ts +127 -32
  38. package/template/blocks/footer/block.json +42 -4
  39. package/template/blocks/footer/mock.json +31 -34
  40. package/template/blocks/footer/preview.png +0 -0
  41. package/template/blocks/form/preview.png +0 -0
  42. package/template/blocks/gallery/preview.json +24 -24
  43. package/template/blocks/gallery/preview.png +0 -0
  44. package/template/blocks/hero/Block.vue +117 -19
  45. package/template/blocks/hero/__tests__/Block.spec.ts +46 -0
  46. package/template/blocks/hero/block.json +36 -1
  47. package/template/blocks/hero/preview.json +33 -25
  48. package/template/blocks/hero/preview.png +0 -0
  49. package/template/blocks/image/preview.json +4 -4
  50. package/template/blocks/image/preview.png +0 -0
  51. package/template/blocks/logo-cloud/preview.png +0 -0
  52. package/template/blocks/navigation/Block.vue +665 -184
  53. package/template/blocks/navigation/__tests__/Block.spec.ts +496 -75
  54. package/template/blocks/navigation/__tests__/fixtures/menu.json +182 -0
  55. package/template/blocks/navigation/block.json +110 -6
  56. package/template/blocks/navigation/mock.json +372 -140
  57. package/template/blocks/navigation/preview.json +311 -0
  58. package/template/blocks/navigation/preview.png +0 -0
  59. package/template/blocks/newsletter/Block.vue +248 -144
  60. package/template/blocks/newsletter/__tests__/Block.spec.ts +42 -0
  61. package/template/blocks/newsletter/block.json +61 -2
  62. package/template/blocks/newsletter/preview.json +35 -0
  63. package/template/blocks/newsletter/preview.png +0 -0
  64. package/template/blocks/order-status/preview.png +0 -0
  65. package/template/blocks/pricing-table/preview.png +0 -0
  66. package/template/blocks/product-carousel/Block.vue +272 -26
  67. package/template/blocks/product-carousel/__tests__/Block.spec.ts +90 -0
  68. package/template/blocks/product-carousel/block.json +61 -0
  69. package/template/blocks/product-carousel/preview.json +12 -0
  70. package/template/blocks/product-carousel/preview.png +0 -0
  71. package/template/blocks/product-detail/Block.vue +148 -96
  72. package/template/blocks/product-detail/__tests__/Block.spec.ts +98 -74
  73. package/template/blocks/product-detail/block.json +11 -4
  74. package/template/blocks/product-detail/mock.json +53 -22
  75. package/template/blocks/product-detail/parts/Gallery.vue +52 -103
  76. package/template/blocks/product-detail/preview.png +0 -0
  77. package/template/blocks/quote/preview.png +0 -0
  78. package/template/blocks/rich-text/preview.png +0 -0
  79. package/template/blocks/search/Block.vue +1 -0
  80. package/template/blocks/search/TypeSection.vue +1 -0
  81. package/template/blocks/search/__tests__/Block.spec.ts +23 -0
  82. package/template/blocks/search/preview.png +0 -0
  83. package/template/blocks/split-content/Block.vue +98 -20
  84. package/template/blocks/split-content/__tests__/Block.spec.ts +57 -18
  85. package/template/blocks/split-content/block.json +72 -6
  86. package/template/blocks/split-content/preview.json +34 -13
  87. package/template/blocks/split-content/preview.png +0 -0
  88. package/template/blocks/stats/preview.png +0 -0
  89. package/template/blocks/tabs/preview.json +16 -16
  90. package/template/blocks/tabs/preview.png +0 -0
  91. package/template/blocks/team/preview.png +0 -0
  92. package/template/blocks/testimonials/preview.png +0 -0
  93. package/template/blocks/timeline/preview.png +0 -0
  94. package/template/blocks/trust-strip/Block.vue +67 -1
  95. package/template/blocks/trust-strip/__tests__/Block.spec.ts +30 -1
  96. package/template/blocks/trust-strip/block.json +4 -4
  97. package/template/blocks/trust-strip/preview.json +21 -0
  98. package/template/blocks/trust-strip/preview.png +0 -0
  99. package/template/blocks/video-embed/preview.png +0 -0
  100. package/template/blocks/wishlist/preview.png +0 -0
  101. package/template/i18n/en-US.json +16 -9
  102. package/template/i18n/is-IS.json +16 -9
  103. package/template/package.json +1 -1
  104. package/template/pages/article.page.json +19 -18
  105. package/template/pages/cart.page.json +3 -13
  106. package/template/pages/category.page.json +15 -7
  107. package/template/pages/collection.page.json +15 -14
  108. package/template/pages/home.page.json +217 -182
  109. package/template/pages/product.page.json +46 -36
  110. package/template/pages/products.page.json +3 -13
  111. package/template/pages/search.page.json +3 -13
  112. package/template/pages/wishlist.page.json +3 -13
  113. package/template/public/images/CREDITS.md +28 -0
  114. package/template/public/images/bowl.webp +0 -0
  115. package/template/public/images/clay-hands.webp +0 -0
  116. package/template/public/images/coffee-table.webp +0 -0
  117. package/template/public/images/cup.webp +0 -0
  118. package/template/public/images/enamel-cups.webp +0 -0
  119. package/template/public/images/hero.webp +0 -0
  120. package/template/public/images/kitchen.webp +0 -0
  121. package/template/public/images/mug.webp +0 -0
  122. package/template/public/images/northwind-mark.svg +1 -0
  123. package/template/public/images/planters.webp +0 -0
  124. package/template/public/images/plates.webp +0 -0
  125. package/template/public/images/reading.webp +0 -0
  126. package/template/public/images/sweater.webp +0 -0
  127. package/template/public/images/terracotta.webp +0 -0
  128. package/template/public/images/throws.webp +0 -0
  129. package/template/public/images/vase.webp +0 -0
  130. package/template/public/images/wheel.webp +0 -0
  131. package/template/public/images/yarn-tools.webp +0 -0
  132. package/template/public/images/yarn.webp +0 -0
  133. package/template/stories/generated/collection-grid.stories.ts +6 -0
  134. package/template/stories/generated/feature-grid.stories.ts +6 -0
  135. package/template/stories/generated/footer.stories.ts +4 -4
  136. package/template/stories/generated/hero.stories.ts +6 -0
  137. package/template/stories/generated/navigation.stories.ts +14 -1
  138. package/template/stories/generated/newsletter.stories.ts +2 -1
  139. package/template/stories/generated/product-carousel.stories.ts +12 -0
  140. package/template/stories/generated/split-content.stories.ts +12 -0
  141. package/template/stories/generated/trust-strip.stories.ts +8 -1
  142. package/template/stories/pages/article.stories.ts +2 -1
  143. package/template/stories/pages/cart.stories.ts +2 -1
  144. package/template/stories/pages/category.stories.ts +2 -1
  145. package/template/stories/pages/collection.stories.ts +2 -1
  146. package/template/stories/pages/home.stories.ts +2 -1
  147. package/template/stories/pages/product.stories.ts +2 -1
  148. package/template/stories/pages/products.stories.ts +2 -1
  149. package/template/stories/pages/search.stories.ts +2 -1
  150. package/template/stories/pages/wishlist.stories.ts +2 -1
  151. package/template/stories/support/demoChrome.ts +32 -0
  152. package/template/stories/support/pageBlocks.ts +2 -4
  153. package/template/test/countPill.browser.spec.ts +21 -13
  154. package/template/test/localePrefix.spec.ts +11 -6
  155. package/template/test/pages/article.spec.ts +1 -1
  156. package/template/test/pages/category.spec.ts +34 -11
  157. package/template/test/pages/collection.spec.ts +182 -148
  158. package/template/test/pages/home.spec.ts +35 -40
  159. package/template/test/pages/hydration.spec.ts +4 -4
  160. package/template/test/pages/product.spec.ts +17 -14
  161. package/template/test/pages/seededPages.spec.ts +11 -6
  162. package/template/test/prerenderFailure.spec.ts +4 -3
  163. package/template/test/prerenderRefresh.browser.spec.ts +36 -15
  164. package/template/test/previewParity.browser.spec.ts +1152 -0
  165. package/template/test/starter.spec.ts +37 -16
  166. package/template/test/storefront/gatewayPrerender.spec.ts +26 -0
  167. package/template/test/support/previewParity.ts +302 -0
  168. package/template/test/support/previewParityContent.ts +726 -0
  169. package/template/tokens.json +13 -13
@@ -0,0 +1,1152 @@
1
+ import { chromium, type Browser, type Page } from '@playwright/test';
2
+ import { normalizeThemeDesignTokens } from '@eldrajs/theme-core';
3
+ import { execa } from 'execa';
4
+ import { cpSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join, relative, sep } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest';
9
+ import starterTokens from '../tokens.json';
10
+ import { ORG_ID, startMockGateway, type MockGateway } from './support/mockGateway';
11
+ import {
12
+ SITE_DESIGN_TOKENS,
13
+ startContentGateway,
14
+ startSessionRouter,
15
+ type ContentGateway,
16
+ type SessionRouter,
17
+ } from './support/previewParity';
18
+ import {
19
+ EDIT_CASES,
20
+ FOCUS_MID_PATH,
21
+ PARITY_PATHS,
22
+ STARTER_BLOCK_TYPES,
23
+ inLocale,
24
+ sampleData,
25
+ type EditCase,
26
+ } from './support/previewParityContent';
27
+ import { startStaticServer, type StaticServer } from './support/staticServer';
28
+
29
+ /**
30
+ * **A draft preview renders exactly what Publish puts live** (WS-1358, the release gate of draft
31
+ * preview, WS-1293).
32
+ *
33
+ * Two real `nuxi generate` builds of this starter, both production builds:
34
+ *
35
+ * - **live** — what Publish deploys: a build made after the content was published, prerendered
36
+ * from the public read, served by a static host and hydrated by Nuxt.
37
+ * - **pinned** — the deployment a preview session pins: a build made *before* the edit, with the
38
+ * older content baked in. The stand-in preview router serves it with the session marker and
39
+ * answers its draft reads from the preview perspective (`X-Preview-Session`), so the page
40
+ * hydrates the older prerender, then renders the new content client-side.
41
+ *
42
+ * Both are given exactly the same content, in Core's two read shapes
43
+ * (`./support/previewParityContent.ts`). After both have hydrated and settled, at 1280 and 390
44
+ * wide, they must be the same: node for node, in the async data and state they hold, in their
45
+ * console errors, and pixel for pixel.
46
+ *
47
+ * **What a session may differ in, and nothing else** (WS-1358): the router's `noindex, nofollow`
48
+ * robots tag, the session marker it adds (`eldra-preview`), its early hide (a `<style>` and a
49
+ * `<noscript>` after the marker, lifted by the kit's `data-eldra-preview-ready` on `<html>`,
50
+ * WS-1376), and the session's own UI — the veil, the banner and the notices, which all live in the
51
+ * `[data-eldra-preview-session]` host on `<body>`. `normalise()` removes exactly those, from the
52
+ * session's page only; the live page is asserted to have none of them.
53
+ *
54
+ * Besides them, the comparison does not read Nuxt's two hydration-state scripts (`#__NUXT_DATA__`
55
+ * and the `window.__NUXT__` config): they are the build's own state — the pinned build's payload is,
56
+ * by construction, the older content, and each build has its own build id — and are never rendered.
57
+ * What they hydrate into is compared instead (`payload.data`, `payload.state`), and so is every node
58
+ * they produce. Comments are not compared either: Vue's fragment anchors are `<!--[-->` in a server
59
+ * render and empty in a client render, and draw nothing.
60
+ *
61
+ * Known differences are pinned, each in its own test, so a change in either direction is seen:
62
+ * `EDIT_EXPECTATIONS` (structural edits renumber `useId()` ids), `FOCUS_MID_PATH` (focus given late
63
+ * scrolls late), the entry metadata (`DRAFT_METADATA`), and the catalog re-reads
64
+ * (`CATALOG_REREADS`). Design tokens and theme texts saved after the pinned build show in a session
65
+ * (WS-1394), in their own case at the end.
66
+ */
67
+
68
+ const templateDir = fileURLToPath(new URL('..', import.meta.url));
69
+ const nuxi = join(templateDir, 'node_modules', '.bin', 'nuxi');
70
+ const SKIPPED_FROM_COPY = new Set(['node_modules', '.nuxt', '.output', '.git', 'storybook-static']);
71
+ const SITE_URL = 'https://shop.example.test';
72
+ const WIDTHS = [1280, 390] as const;
73
+
74
+ let upstream: MockGateway;
75
+ let gateway: ContentGateway;
76
+ let scratch: string;
77
+ let live: StaticServer;
78
+ let router: SessionRouter;
79
+ let browser: Browser;
80
+
81
+ /** A copy of the starter, generated against the content gateway as a production build. */
82
+ async function build(name: string, env: Record<string, string> = {}): Promise<string> {
83
+ const root = join(scratch, name);
84
+ cpSync(templateDir, root, {
85
+ recursive: true,
86
+ filter: (source) => {
87
+ const [first] = relative(templateDir, source).split(sep);
88
+ return first === undefined || !SKIPPED_FROM_COPY.has(first);
89
+ },
90
+ });
91
+ symlinkSync(join(templateDir, 'node_modules'), join(root, 'node_modules'), 'dir');
92
+ const generated = await execa(nuxi, ['generate'], {
93
+ cwd: root,
94
+ env: {
95
+ ELDRA_GATEWAY_URL: gateway.url,
96
+ ELDRA_ORG_ID: ORG_ID,
97
+ ELDRA_BUILD_TARGET: 'production',
98
+ ELDRA_SITE_URL: SITE_URL,
99
+ ...env,
100
+ },
101
+ reject: false,
102
+ timeout: 600_000,
103
+ });
104
+ if (generated.exitCode !== 0) {
105
+ throw new Error(`nuxi generate (${name}) failed\n${generated.stdout}\n${generated.stderr}`);
106
+ }
107
+ return join(root, '.output', 'public');
108
+ }
109
+
110
+ interface Capture {
111
+ /** The normalised document, one node per line. */
112
+ dom: string[];
113
+ /** A session's document the moment its veil dropped, normalised the same way. */
114
+ veilDrop?: string[];
115
+ /** Every async data entry and every `useState` the app holds once settled, keys sorted, without
116
+ * the entry metadata a draft reads differently (`DRAFT_METADATA`). */
117
+ data: string;
118
+ /** The same, with the metadata. */
119
+ dataWithMetadata: string;
120
+ /** Console errors, page errors, anything Vue said about hydration, and failed requests. */
121
+ warnings: string[];
122
+ /** Where the page ended up, and what holds focus. */
123
+ scrollY: number;
124
+ focused: string;
125
+ }
126
+
127
+ /** Opens `path` in a fresh page at `width`, waits for it to settle, and runs `then` on it. */
128
+ async function open<T>(
129
+ origin: string,
130
+ path: string,
131
+ width: number,
132
+ session: boolean,
133
+ then: (page: Page, warnings: string[]) => Promise<T>
134
+ ): Promise<T> {
135
+ const context = await browser.newContext({
136
+ viewport: { width, height: 900 },
137
+ deviceScaleFactor: 1,
138
+ reducedMotion: 'reduce',
139
+ colorScheme: 'light',
140
+ locale: 'en-US',
141
+ timezoneId: 'Atlantic/Reykjavik',
142
+ });
143
+ const page = await context.newPage();
144
+ await page.addInitScript(installSerialiser);
145
+ const warnings: string[] = [];
146
+ page.on('console', (message) => {
147
+ const text = message.text();
148
+ if (/hydrat|mismatch/i.test(text) || message.type() === 'error') {
149
+ warnings.push(`${message.type()}: ${text.slice(0, 300)}`);
150
+ }
151
+ });
152
+ page.on('pageerror', (error) => warnings.push(`pageerror: ${error.message.slice(0, 300)}`));
153
+ page.on('response', (response) => {
154
+ if (response.status() >= 400) {
155
+ warnings.push(`${response.status()}: ${new URL(response.url()).pathname}`);
156
+ }
157
+ });
158
+ try {
159
+ await page.goto(`${origin}${path}`, { waitUntil: 'networkidle' });
160
+ if (session) {
161
+ // The draft is on screen once the veil is down (`hidden`) and the app is no longer busy.
162
+ // Checked every frame, and the document copied in the frame it first holds: what the
163
+ // merchant sees the moment the veil drops, compared with the settled page below
164
+ // (`VEIL_DROP_DIFFERENCES`), so a change that lands after the veil is caught.
165
+ await page.waitForFunction(
166
+ (additions) => {
167
+ const veil = document
168
+ .querySelector('[data-eldra-preview-session]')
169
+ ?.shadowRoot?.querySelector('.veil');
170
+ const shown =
171
+ veil?.hasAttribute('hidden') === true &&
172
+ !document.getElementById('__nuxt')?.hasAttribute('aria-busy');
173
+ if (shown) {
174
+ const win = window as unknown as {
175
+ __eldraSerialise: (skip: readonly string[]) => unknown;
176
+ __eldraVeilDrop?: unknown;
177
+ };
178
+ win.__eldraVeilDrop = win.__eldraSerialise(additions);
179
+ }
180
+ return shown;
181
+ },
182
+ SESSION_ADDITIONS,
183
+ { timeout: 30_000, polling: 'raf' }
184
+ );
185
+ }
186
+ await settle(page);
187
+ return await then(page, warnings);
188
+ } finally {
189
+ await context.close();
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Nothing in flight, every font loaded, and two frames drawn — and with `images`, every image on
195
+ * the page loaded and decoded first. A lazily loaded image below the fold starts loading only when
196
+ * it nears the viewport, which a full-page screenshot makes a race; so for the pixels both pages'
197
+ * images are switched to eager loading, the same change on both sides, before anything is drawn.
198
+ */
199
+ async function settle(page: Page, images = false): Promise<void> {
200
+ await page.waitForLoadState('networkidle');
201
+ await page.evaluate(async (eager) => {
202
+ if (eager) {
203
+ for (const image of document.images) image.loading = 'eager';
204
+ await Promise.all([...document.images].map((image) => image.decode().catch(() => undefined)));
205
+ }
206
+ await document.fonts.ready;
207
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
208
+ }, images);
209
+ await page.waitForLoadState('networkidle');
210
+ // The storefront's own refresh is over: no busy region, no dimmed or spinning block, no
211
+ // "Updating…" status (the treatment `prerenderRefresh.browser.spec.ts` samples).
212
+ await page.waitForFunction(
213
+ () =>
214
+ document.querySelectorAll(
215
+ '#__nuxt [aria-busy="true"], .eldra\\:eldra-revalidating, [data-part="spinner"]'
216
+ ).length === 0 &&
217
+ ![...document.querySelectorAll('[role="status"]')].some((node) =>
218
+ /Updating/i.test(node.textContent ?? '')
219
+ ),
220
+ undefined,
221
+ { timeout: 15_000 }
222
+ );
223
+ // The same condition on both pages, whatever the machine's speed: the app has hydrated, no async
224
+ // data entry has a read in flight, and the whole document (head, body, every attribute) has not
225
+ // changed for `QUIET_MS` — measured from the last change, not from a fixed point. A head-only
226
+ // check let a busy machine capture a page whose head manager or header had not yet written
227
+ // (an `og:url` and a header height a beat behind the other page).
228
+ await page.waitForFunction(
229
+ () => {
230
+ const nuxt = (
231
+ document.getElementById('__nuxt') as unknown as {
232
+ __vue_app__?: {
233
+ config: {
234
+ globalProperties: {
235
+ $nuxt?: {
236
+ isHydrating?: boolean;
237
+ _asyncDataPromises?: Record<string, Promise<unknown> | undefined>;
238
+ };
239
+ };
240
+ };
241
+ };
242
+ }
243
+ ).__vue_app__?.config.globalProperties.$nuxt;
244
+ return (
245
+ nuxt !== undefined &&
246
+ nuxt.isHydrating !== true &&
247
+ Object.values(nuxt._asyncDataPromises ?? {}).every((promise) => promise === undefined)
248
+ );
249
+ },
250
+ undefined,
251
+ { timeout: 30_000 }
252
+ );
253
+ await page.waitForLoadState('networkidle');
254
+ await page.evaluate(
255
+ (quiet) =>
256
+ new Promise<void>((resolve, reject) => {
257
+ let timer: ReturnType<typeof setTimeout>;
258
+ const done = (): void => {
259
+ observer.disconnect();
260
+ clearTimeout(giveUp);
261
+ resolve();
262
+ };
263
+ const observer = new MutationObserver(() => {
264
+ clearTimeout(timer);
265
+ timer = setTimeout(done, quiet);
266
+ });
267
+ observer.observe(document.documentElement, {
268
+ subtree: true,
269
+ childList: true,
270
+ attributes: true,
271
+ characterData: true,
272
+ });
273
+ timer = setTimeout(done, quiet);
274
+ const giveUp = setTimeout(() => {
275
+ observer.disconnect();
276
+ reject(new Error(`the document did not stay unchanged for ${quiet} ms within 30 s`));
277
+ }, 30_000);
278
+ }),
279
+ QUIET_MS
280
+ );
281
+ await page.waitForLoadState('networkidle');
282
+ }
283
+
284
+ /** How long the document must stay unchanged before a page counts as settled. */
285
+ const QUIET_MS = 750;
286
+
287
+ /**
288
+ * On the session's page, removes exactly the differences a session is allowed; on the live page,
289
+ * asserts there are none of them to remove.
290
+ */
291
+ /**
292
+ * What a session adds to the page: its host, the router's two meta tags, and the router's early
293
+ * hide (WS-1376) — a `<style>` and its `<noscript>` twin, put right after the session marker. The
294
+ * kit's `data-eldra-preview-ready` on `<html>` (which lifts that hide) is the one added attribute:
295
+ * `PREVIEW_READY` below.
296
+ */
297
+ const SESSION_ADDITIONS = [
298
+ '[data-eldra-preview-session]',
299
+ 'meta[name="eldra-preview"]',
300
+ 'meta[name="robots"][content="noindex, nofollow"]',
301
+ 'meta[name="eldra-preview"] + style',
302
+ 'meta[name="eldra-preview"] + style + noscript',
303
+ ];
304
+ /** The attribute the kit sets on `<html>` once the router's early hide may lift. */
305
+ const PREVIEW_READY = 'data-eldra-preview-ready';
306
+ const SESSION_COUNTS = SESSION_ADDITIONS.map(() => 1);
307
+ const LIVE_COUNTS = SESSION_ADDITIONS.map(() => 0);
308
+
309
+ async function normalise(page: Page, session: boolean): Promise<void> {
310
+ const found = await page.evaluate(
311
+ ([remove, selectors, readyAttribute]) => {
312
+ const counts = selectors.map((selector) => document.querySelectorAll(selector).length);
313
+ const ready = document.documentElement.hasAttribute(readyAttribute);
314
+ if (remove) {
315
+ // Found first, removed after: a selector may name its place after another addition
316
+ // (`meta[name="eldra-preview"] + style`).
317
+ const nodes = selectors.flatMap((selector) => [...document.querySelectorAll(selector)]);
318
+ for (const node of nodes) node.remove();
319
+ document.documentElement.removeAttribute(readyAttribute);
320
+ }
321
+ const noindex = [...document.querySelectorAll('meta[name="robots"]')].some((meta) =>
322
+ /noindex/i.test(meta.getAttribute('content') ?? '')
323
+ );
324
+ return { counts, noindex, ready };
325
+ },
326
+ [session, SESSION_ADDITIONS, PREVIEW_READY] as const
327
+ );
328
+ if (session) {
329
+ // Exactly one robots tag, the router's `noindex, nofollow`, on every session page: the
330
+ // session's own head entry keeps it once the theme's head manager runs, a page only the draft
331
+ // has (which hydrates the not-found document's `noindex`) included. And the router's early
332
+ // hide is lifted: the kit set the ready attribute.
333
+ expect(found).toEqual({ counts: SESSION_COUNTS, noindex: false, ready: true });
334
+ } else {
335
+ expect(found).toEqual({ counts: LIVE_COUNTS, noindex: false, ready: false });
336
+ }
337
+ }
338
+
339
+ /**
340
+ * The document, one node per line: tag and sorted attributes, or text, shadow roots walked;
341
+ * hydration state left out. One function for every capture, installed in the page before it loads
342
+ * (`installSerialiser`), so the settled page and the frame the veil drops are written the same way.
343
+ * `skip` leaves out the elements a session is allowed to add (`SESSION_ADDITIONS`) without removing
344
+ * them, which the veil-drop frame cannot do; the settled capture removes them first (`normalise`).
345
+ */
346
+ function installSerialiser(): void {
347
+ (
348
+ window as unknown as {
349
+ __eldraSerialise: (skip: readonly string[]) => {
350
+ lines: string[];
351
+ counts: number[];
352
+ noindex: boolean;
353
+ ready: boolean;
354
+ };
355
+ }
356
+ ).__eldraSerialise = (skip) => {
357
+ // With additions to skip, the kit's ready attribute on `<html>` is one of them.
358
+ const readyAttribute = 'data-eldra-preview-ready';
359
+ const lines: string[] = [];
360
+ const walk = (node: Node, depth: number): void => {
361
+ const indent = ' '.repeat(depth);
362
+ if (node.nodeType === Node.TEXT_NODE) {
363
+ if ((node.textContent ?? '') !== '') lines.push(`${indent}"${node.textContent}"`);
364
+ return;
365
+ }
366
+ // A shadow root is a fragment, not an element: its children are walked under its host.
367
+ if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) {
368
+ for (const child of node.childNodes) walk(child, depth);
369
+ return;
370
+ }
371
+ if (node.nodeType !== Node.ELEMENT_NODE) return;
372
+ const element = node as Element;
373
+ if (skip.some((selector) => element.matches(selector))) return;
374
+ if (element.id === '__NUXT_DATA__' || element.hasAttribute('data-nuxt-data')) return;
375
+ if (element.tagName === 'SCRIPT' && /window\.__NUXT__/.test(element.textContent ?? ''))
376
+ return;
377
+ // A `style` attribute as the browser holds it (`style.cssText`), not as it was written: a
378
+ // style the server rendered is the attribute text it wrote (`aspect-ratio:auto;`), one Vue
379
+ // set in the browser is the CSSOM's own serialisation (`aspect-ratio: auto;`, numbers to six
380
+ // significant digits), and a declaration list left empty is no style at all. Both sides go
381
+ // through the same CSSOM, so the rounding is the same on both: what is compared is the value
382
+ // the browser applies, which the stored data (a framing's focal point) decides on both.
383
+ const attributes = [...element.attributes]
384
+ .filter((attribute) => attribute.name !== 'style')
385
+ .filter(
386
+ (attribute) =>
387
+ skip.length === 0 ||
388
+ element !== document.documentElement ||
389
+ attribute.name !== readyAttribute
390
+ )
391
+ .map((attribute) => `${attribute.name}="${attribute.value}"`);
392
+ const style = (element as HTMLElement).style?.cssText ?? '';
393
+ if (style !== '') attributes.push(`style="${style}"`);
394
+ attributes.sort();
395
+ lines.push(
396
+ `${indent}<${element.tagName.toLowerCase()}${attributes.map((a) => ` ${a}`).join('')}>`
397
+ );
398
+ if (element.shadowRoot) {
399
+ lines.push(`${indent} #shadow-root`);
400
+ walk(element.shadowRoot, depth + 2);
401
+ }
402
+ const children =
403
+ element instanceof HTMLTemplateElement ? element.content.childNodes : element.childNodes;
404
+ for (const child of children) walk(child, depth + 1);
405
+ };
406
+ walk(document.documentElement, 0);
407
+ const counts = skip.map((selector) => document.querySelectorAll(selector).length);
408
+ const noindex = [...document.querySelectorAll('meta[name="robots"]')]
409
+ .filter((meta) => !skip.some((selector) => meta.matches(selector)))
410
+ .some((meta) => /noindex/i.test(meta.getAttribute('content') ?? ''));
411
+ const ready = document.documentElement.hasAttribute(readyAttribute);
412
+ return { lines, counts, noindex, ready };
413
+ };
414
+ }
415
+
416
+ function serialise(page: Page): Promise<string[]> {
417
+ return page.evaluate(
418
+ () =>
419
+ (
420
+ window as unknown as { __eldraSerialise: (skip: readonly string[]) => { lines: string[] } }
421
+ ).__eldraSerialise([]).lines
422
+ );
423
+ }
424
+
425
+ /**
426
+ * The head's chunk hints, compared as a set: a `modulepreload` for each chunk the page renders and
427
+ * (Nuxt 4.7) a `prefetch` for each block chunk it does not. Their order is the order the
428
+ * prerender's async render happened to collect each chunk in, which differs between any two builds
429
+ * of the same content (two Publish builds included), not something a session does. Moved to the
430
+ * end, sorted.
431
+ */
432
+ const PRELOADS = '(chunk hints, as a set)';
433
+ const chunkHint = (line: string): boolean =>
434
+ line.includes('rel="modulepreload"') ||
435
+ (line.includes('rel="prefetch"') && /href="[^"]*\/_nuxt\/[^"]+\.js"/.test(line));
436
+ function preloadsAsASet(lines: readonly string[]): string[] {
437
+ return [
438
+ ...lines.filter((line) => !chunkHint(line)),
439
+ PRELOADS,
440
+ ...lines
441
+ .filter(chunkHint)
442
+ .map((line) => line.trim())
443
+ .sort(),
444
+ ];
445
+ }
446
+
447
+ /**
448
+ * **Known difference: entry metadata.** The fields of an entry's envelope a session reads
449
+ * differently: it reads the draft (its own save time, the last publish time or none), the live build
450
+ * read the snapshot Publish made of it (the publish time). They are removed from entry envelopes (an
451
+ * object with `id`, `schemaId` and `data`) before the async data is compared; the spec asserts they
452
+ * did differ, and that the DOM is the same regardless, so nothing the starter renders reads them.
453
+ * An entry's `status` (`CHANGED` or `DRAFT` on a draft read) is not among them: the public read
454
+ * does not carry it and the session's client drops it, so the spec asserts neither page has one.
455
+ */
456
+ const DRAFT_METADATA = ['updatedAt', 'publishedAt'];
457
+ // Likewise every media item's `linkId` (asset-service's link row, one per owner), wherever it is.
458
+
459
+ /** Every async data entry and `useState` the app holds, in key order. */
460
+ function asyncData(page: Page): Promise<{ withMetadata: string; withoutMetadata: string }> {
461
+ return page.evaluate((metadata) => {
462
+ const app = (
463
+ document.getElementById('__nuxt') as unknown as {
464
+ __vue_app__?: {
465
+ config: {
466
+ globalProperties: {
467
+ $nuxt?: {
468
+ payload: { data: Record<string, unknown>; state: Record<string, unknown> };
469
+ };
470
+ };
471
+ };
472
+ };
473
+ }
474
+ ).__vue_app__;
475
+ const payload = app?.config.globalProperties.$nuxt?.payload;
476
+ const value = { data: payload?.data ?? {}, state: payload?.state ?? {} };
477
+ // Key order is not content: Core's own JSON is a Go map's, sorted, and a mock's is not.
478
+ const sorted = (input: unknown, strip: boolean): unknown => {
479
+ if (Array.isArray(input)) return input.map((item) => sorted(item, strip));
480
+ if (input instanceof Map) return sorted(Object.fromEntries(input), strip);
481
+ if (typeof input !== 'object' || input === null) return input;
482
+ const record = input as Record<string, unknown>;
483
+ const isEntry = 'id' in record && 'schemaId' in record && 'data' in record;
484
+ return Object.fromEntries(
485
+ Object.keys(record)
486
+ .filter((key) => !(strip && ((isEntry && metadata.includes(key)) || key === 'linkId')))
487
+ .sort()
488
+ .map((key) => [key, sorted(record[key], strip)])
489
+ );
490
+ };
491
+ return {
492
+ withMetadata: JSON.stringify(sorted(value, false), null, 1),
493
+ withoutMetadata: JSON.stringify(sorted(value, true), null, 1),
494
+ };
495
+ }, DRAFT_METADATA);
496
+ }
497
+
498
+ /**
499
+ * Nothing changes after the veil drops: the session's document the moment the veil is hidden is
500
+ * its settled document. `headerMayHide` allows the one difference pinned on the page with a field
501
+ * focused mid-page: the starter header's `-translate-y-full` (its hide-on-scroll), only there.
502
+ */
503
+ function expectNoChangeAfterTheVeil(session: Capture, headerMayHide = false): void {
504
+ expect(session.veilDrop, 'the session was captured when its veil dropped').toBeDefined();
505
+ const atDrop = session.veilDrop ?? [];
506
+ if (!headerMayHide) {
507
+ expect(atDrop.join('\n')).toBe(session.dom.join('\n'));
508
+ return;
509
+ }
510
+ expect(atDrop.length).toBe(session.dom.length);
511
+ const changed = atDrop
512
+ .map((line, index) => [line, session.dom[index]!] as const)
513
+ .filter(([before, after]) => before !== after);
514
+ for (const [before, after] of changed) {
515
+ expect(before).toMatch(/^\s*<header /);
516
+ expect(before.replace(' -translate-y-full', '')).toBe(after.replace(' -translate-y-full', ''));
517
+ }
518
+ expect(changed.length).toBeLessThanOrEqual(1);
519
+ }
520
+
521
+ function capture(origin: string, path: string, width: number, session: boolean): Promise<Capture> {
522
+ return open(origin, path, width, session, async (page, warnings) => {
523
+ let veilDrop: string[] | undefined;
524
+ if (session) {
525
+ const atDrop = await page.evaluate(
526
+ () =>
527
+ (
528
+ window as unknown as {
529
+ __eldraVeilDrop: {
530
+ lines: string[];
531
+ counts: number[];
532
+ noindex: boolean;
533
+ ready: boolean;
534
+ };
535
+ }
536
+ ).__eldraVeilDrop
537
+ );
538
+ // The same additions the settled page has, and nothing else that says noindex; and the
539
+ // router's early hide was lifted in the very frame the veil dropped.
540
+ expect({ counts: atDrop.counts, noindex: atDrop.noindex, ready: atDrop.ready }).toEqual({
541
+ counts: SESSION_COUNTS,
542
+ noindex: false,
543
+ ready: true,
544
+ });
545
+ veilDrop = preloadsAsASet(atDrop.lines);
546
+ }
547
+ await normalise(page, session);
548
+ const data = await asyncData(page);
549
+ const where = await page.evaluate(() => {
550
+ const active = document.activeElement;
551
+ return {
552
+ scrollY: Math.round(window.scrollY),
553
+ focused:
554
+ active === null || active === document.body
555
+ ? 'body'
556
+ : `${active.tagName.toLowerCase()}[aria-label="${active.getAttribute('aria-label') ?? ''}"]`,
557
+ };
558
+ });
559
+ return {
560
+ dom: preloadsAsASet(await serialise(page)),
561
+ veilDrop,
562
+ data: data.withoutMetadata,
563
+ dataWithMetadata: data.withMetadata,
564
+ warnings,
565
+ ...where,
566
+ };
567
+ });
568
+ }
569
+
570
+ /** A full-page screenshot, after the same normalisation as the DOM. */
571
+ function screenshot(
572
+ origin: string,
573
+ path: string,
574
+ width: number,
575
+ session: boolean
576
+ ): Promise<Buffer> {
577
+ return open(origin, path, width, session, async (page) => {
578
+ await normalise(page, session);
579
+ await settle(page, true);
580
+ return page.screenshot({ fullPage: true, animations: 'disabled', caret: 'hide' });
581
+ });
582
+ }
583
+
584
+ /** Where a pixel test that fails leaves both screenshots and their difference, for CI to upload. */
585
+ const PIXEL_FAILURES = join(templateDir, 'test-results', 'preview-parity');
586
+
587
+ interface PixelDifference {
588
+ differing: number;
589
+ size: string;
590
+ /** The smallest rectangle holding every differing pixel, `x,y wxh`; none when nothing differs. */
591
+ region?: string;
592
+ /** A PNG of the session's screenshot with every differing pixel painted magenta. */
593
+ diff?: string;
594
+ }
595
+
596
+ /**
597
+ * How many pixels of `a` and `b` differ, decoded and compared by Chromium itself — a canvas reads
598
+ * both PNGs back as RGBA, so no image library is needed. Different sizes count every pixel.
599
+ */
600
+ async function differingPixels(a: Buffer, b: Buffer): Promise<PixelDifference> {
601
+ const context = await browser.newContext();
602
+ const page = await context.newPage();
603
+ try {
604
+ return await page.evaluate(
605
+ async ([left, right]) => {
606
+ const decode = async (base64: string): Promise<ImageData> => {
607
+ const blob = await (await fetch(`data:image/png;base64,${base64}`)).blob();
608
+ const bitmap = await createImageBitmap(blob);
609
+ const canvas = new OffscreenCanvas(bitmap.width, bitmap.height);
610
+ const context2d = canvas.getContext('2d')!;
611
+ context2d.drawImage(bitmap, 0, 0);
612
+ return context2d.getImageData(0, 0, bitmap.width, bitmap.height);
613
+ };
614
+ const [one, two] = await Promise.all([decode(left), decode(right)]);
615
+ const size = `${one.width}x${one.height} vs ${two.width}x${two.height}`;
616
+ if (one.width !== two.width || one.height !== two.height) {
617
+ return { differing: Math.max(one.width * one.height, two.width * two.height), size };
618
+ }
619
+ let differing = 0;
620
+ let [minX, minY, maxX, maxY] = [one.width, one.height, -1, -1];
621
+ const marked = new ImageData(new Uint8ClampedArray(one.data), one.width, one.height);
622
+ for (let i = 0; i < one.data.length; i += 4) {
623
+ if (
624
+ one.data[i] !== two.data[i] ||
625
+ one.data[i + 1] !== two.data[i + 1] ||
626
+ one.data[i + 2] !== two.data[i + 2] ||
627
+ one.data[i + 3] !== two.data[i + 3]
628
+ ) {
629
+ differing += 1;
630
+ const x = (i / 4) % one.width;
631
+ const y = Math.floor(i / 4 / one.width);
632
+ [minX, minY] = [Math.min(minX, x), Math.min(minY, y)];
633
+ [maxX, maxY] = [Math.max(maxX, x), Math.max(maxY, y)];
634
+ marked.data.set([255, 0, 255, 255], i);
635
+ }
636
+ }
637
+ if (differing === 0) return { differing, size };
638
+ const canvas = new OffscreenCanvas(one.width, one.height);
639
+ canvas.getContext('2d')!.putImageData(marked, 0, 0);
640
+ const png = new Uint8Array(await (await canvas.convertToBlob()).arrayBuffer());
641
+ let binary = '';
642
+ for (const byte of png) binary += String.fromCharCode(byte);
643
+ return {
644
+ differing,
645
+ size,
646
+ region: `${minX},${minY} ${maxX - minX + 1}x${maxY - minY + 1}`,
647
+ diff: btoa(binary),
648
+ };
649
+ },
650
+ [a.toString('base64'), b.toString('base64')] as const
651
+ );
652
+ } finally {
653
+ await context.close();
654
+ }
655
+ }
656
+
657
+ /**
658
+ * Not one pixel differs. When one does, both screenshots and the difference are written to
659
+ * `PIXEL_FAILURES` (CI uploads the folder when the job fails), and the failure names where on the
660
+ * page the differing pixels are.
661
+ */
662
+ async function expectSamePixels(
663
+ path: string,
664
+ width: number,
665
+ session: Buffer,
666
+ published: Buffer
667
+ ): Promise<void> {
668
+ const { diff, ...result } = await differingPixels(session, published);
669
+ if (result.differing !== 0) {
670
+ const folder = join(PIXEL_FAILURES, `${path.replace(/[^a-z0-9-]+/gi, '_')}-${width}`);
671
+ mkdirSync(folder, { recursive: true });
672
+ writeFileSync(join(folder, 'session.png'), session);
673
+ writeFileSync(join(folder, 'live.png'), published);
674
+ if (diff !== undefined) writeFileSync(join(folder, 'diff.png'), Buffer.from(diff, 'base64'));
675
+ }
676
+ expect(
677
+ result,
678
+ `the session's pixels against the live page's: ${JSON.stringify(result)}`
679
+ ).toMatchObject({ differing: 0 });
680
+ }
681
+
682
+ /**
683
+ * **Known difference: the session re-reads the catalog.** It re-runs every async data entry the
684
+ * server filled, the storefront's commerce reads among them, so a commerce read the prerender made
685
+ * (and baked in, failure included) is asked again in a session, where the live page answers it from
686
+ * its payload. Here: the sample `collection-grid` names a collection the mock catalog does not have.
687
+ * Exactly these extra failed requests, and nothing else, are allowed per path.
688
+ */
689
+ const CATALOG_REREADS: Record<string, string[]> = {
690
+ '/': ['404: /catalog/v1/collections/winter-knitwear/products'],
691
+ [FOCUS_MID_PATH]: ['404: /catalog/v1/collections/winter-knitwear/products'],
692
+ // Not a re-read: the pinned build has no file for a page only the draft has, so the host answers
693
+ // the document itself with its not-found page, status 404.
694
+ '/draft-only': ['404: /draft-only/'],
695
+ };
696
+ const BROWSER_404_LINE =
697
+ 'error: Failed to load resource: the server responded with a status of 404 (Not Found)';
698
+
699
+ function expectSameWarnings(
700
+ path: string,
701
+ session: readonly string[],
702
+ published: readonly string[]
703
+ ): void {
704
+ const extra = [...session];
705
+ for (const line of published) {
706
+ const at = extra.indexOf(line);
707
+ expect(at, `the session lacks the live page's "${line}"`).not.toBe(-1);
708
+ extra.splice(at, 1);
709
+ }
710
+ const allowed = CATALOG_REREADS[path] ?? [];
711
+ // The browser's console reports each failed request once more, as its own line.
712
+ expect(extra.sort()).toEqual([...allowed, ...allowed.map(() => BROWSER_404_LINE)].sort());
713
+ }
714
+
715
+ /** A `useId()` value: Vue's default prefix, then the numbers. */
716
+ const USE_ID = /\bv-\d+(?:-\d+)+/g;
717
+
718
+ /**
719
+ * Each distinct `useId()` value replaced by its order of first appearance, so two documents that
720
+ * differ only in how the ids were numbered compare equal. Used for the pinned cases only.
721
+ */
722
+ function renumberIds(lines: readonly string[]): string[] {
723
+ const seen = new Map<string, string>();
724
+ return lines.map((line) =>
725
+ line.replace(USE_ID, (token) => {
726
+ if (!seen.has(token)) seen.set(token, `v#${seen.size}`);
727
+ return seen.get(token)!;
728
+ })
729
+ );
730
+ }
731
+
732
+ /**
733
+ * Lines aligned one to one (the documents differ only in id numbering): every `useId()` value the
734
+ * session numbered differently, as `live → session`, and the block types whose markup holds them.
735
+ */
736
+ function renumbered(
737
+ published: readonly string[],
738
+ session: readonly string[]
739
+ ): { ids: Record<string, string>; blocks: string[] } {
740
+ const ids: Record<string, string> = {};
741
+ const blocks: string[] = [];
742
+ const indent = (line: string): number => line.length - line.trimStart().length;
743
+ const schemaAt = (index: number): string => {
744
+ let depth = indent(published[index]!);
745
+ for (let i = index; i >= 0; i -= 1) {
746
+ const line = published[i]!;
747
+ if (indent(line) > depth) continue;
748
+ depth = indent(line);
749
+ const schema = /data-eldra-block="/.test(line)
750
+ ? line.match(/data-eldra-schema="([^"]+)"/)?.[1]
751
+ : undefined;
752
+ if (schema !== undefined) return schema;
753
+ }
754
+ return '(none)';
755
+ };
756
+ for (let i = 0; i < published.length; i += 1) {
757
+ const before = published[i]!.match(USE_ID) ?? [];
758
+ const after = session[i]!.match(USE_ID) ?? [];
759
+ before.forEach((token, at) => {
760
+ if (after[at] === token) return;
761
+ ids[token] = after[at]!;
762
+ const schema = schemaAt(i);
763
+ if (!blocks.includes(schema)) blocks.push(schema);
764
+ });
765
+ }
766
+ return { ids, blocks };
767
+ }
768
+
769
+ /** The document without its chunk hints (`preloadsAsASet` put them last). */
770
+ function bodyOf(dom: readonly string[]): string[] {
771
+ return dom.slice(0, dom.indexOf(PRELOADS));
772
+ }
773
+
774
+ /**
775
+ * The chunk hints, by path and kind. A chunk the page renders is preloaded; one it does not is
776
+ * prefetched. A session's runtime that loads a chunk no link names yet adds a `modulepreload` as an
777
+ * absolute URL on its own origin (`late`); one the pinned page already prefetched keeps that link.
778
+ */
779
+ function hintsOf(dom: readonly string[]): {
780
+ paths: string[];
781
+ preloaded: string[];
782
+ prefetched: string[];
783
+ late: string[];
784
+ } {
785
+ const late: string[] = [];
786
+ const preloaded = new Set<string>();
787
+ const prefetched = new Set<string>();
788
+ for (const line of dom.slice(dom.indexOf(PRELOADS) + 1)) {
789
+ const href = line.match(/href="([^"]+)"/)?.[1] ?? line;
790
+ if (router !== undefined && href.startsWith(router.origin)) {
791
+ late.push(href.slice(router.origin.length));
792
+ continue;
793
+ }
794
+ (line.includes('rel="modulepreload"') ? preloaded : prefetched).add(href);
795
+ }
796
+ return {
797
+ paths: [...new Set([...preloaded, ...prefetched, ...late])].sort(),
798
+ preloaded: [...preloaded].sort(),
799
+ prefetched: [...prefetched].filter((path) => !preloaded.has(path)).sort(),
800
+ late: [...new Set(late)].sort(),
801
+ };
802
+ }
803
+
804
+ /**
805
+ * **Known difference: structural edits renumber `useId()` ids.** The session hydrates the pinned
806
+ * build's page and patches it to the draft. Vue numbers each `useId()` by the order the app created
807
+ * the component, and an instance keeps the number it was hydrated with; a component created after
808
+ * hydration takes the next free number. So an edit that creates components the pinned page did not
809
+ * have — or that moves existing ones relative to where the prerender numbered them — leaves ids that
810
+ * Publish's prerender would number differently. Each id still matches its own `aria-labelledby` /
811
+ * `aria-controls` on the page, and no pixel differs. Pinned per edit: whether it renumbers, which
812
+ * blocks' ids, exactly which ids, and which chunk hints arrive late or stay behind.
813
+ */
814
+ const EDIT_EXPECTATIONS: Record<
815
+ EditCase,
816
+ {
817
+ renumbers: boolean;
818
+ blocks: string[];
819
+ ids: Record<string, string>;
820
+ /** How many chunks the live page preloads and the session only prefetches (needed late). */
821
+ lateChunks: number;
822
+ /** How many chunks the session still preloads and the live page only prefetches (stale). */
823
+ staleChunks: number;
824
+ /** The session hydrated the pinned build's not-found document (a page only the draft has). */
825
+ notFoundDocument?: true;
826
+ }
827
+ > = {
828
+ // A block added between two: it and every block after it.
829
+ 'edit-add': {
830
+ renumbers: true,
831
+ blocks: ['quote', 'tabs', 'faq'],
832
+ ids: { 'v-0-1-0': 'v-0-3-0', 'v-0-2-0': 'v-0-1-0', 'v-0-2-1': 'v-0-1-1', 'v-0-3-0': 'v-0-2-0' },
833
+ lateChunks: 1,
834
+ staleChunks: 0,
835
+ },
836
+ // A block removed: every block after it.
837
+ 'edit-remove': {
838
+ renumbers: true,
839
+ blocks: ['tabs', 'faq'],
840
+ ids: { 'v-0-1-0': 'v-0-2-0', 'v-0-1-1': 'v-0-2-1', 'v-0-2-0': 'v-0-3-0' },
841
+ lateChunks: 0,
842
+ staleChunks: 1,
843
+ },
844
+ // Two blocks swapped: both.
845
+ 'edit-reorder': {
846
+ renumbers: true,
847
+ blocks: ['faq', 'tabs'],
848
+ ids: { 'v-0-1-0': 'v-0-2-0', 'v-0-2-0': 'v-0-1-0', 'v-0-2-1': 'v-0-1-1' },
849
+ lateChunks: 0,
850
+ staleChunks: 0,
851
+ },
852
+ // A block replaced by one of another type: the new block only.
853
+ 'edit-type': {
854
+ renumbers: true,
855
+ blocks: ['cta'],
856
+ ids: { 'v-0-1-0': 'v-0-3-0' },
857
+ lateChunks: 1,
858
+ staleChunks: 1,
859
+ },
860
+ // An item added inside a list block: its ids are the block's own, numbered by index.
861
+ 'edit-faq-item': { renumbers: false, blocks: [], ids: {}, lateChunks: 0, staleChunks: 0 },
862
+ 'edit-tab-item': { renumbers: false, blocks: [], ids: {}, lateChunks: 0, staleChunks: 0 },
863
+ // A page only the draft has: the session hydrates the not-found document, then builds the whole
864
+ // page in the browser — in the order a prerender would, so nothing is renumbered.
865
+ 'draft-only': {
866
+ renumbers: false,
867
+ blocks: [],
868
+ ids: {},
869
+ lateChunks: 4,
870
+ staleChunks: 0,
871
+ notFoundDocument: true,
872
+ },
873
+ };
874
+
875
+ describe('a draft preview renders exactly what Publish puts live', () => {
876
+ beforeAll(async () => {
877
+ upstream = await startMockGateway();
878
+ gateway = await startContentGateway(upstream.url);
879
+ scratch = mkdtempSync(join(tmpdir(), 'eldra-preview-parity-'));
880
+ // The deployment the session pins: built while the older content was live.
881
+ gateway.published = 'pinned';
882
+ const pinned = await build('pinned');
883
+ // Publish: the drafts become the published content, and the site is rebuilt.
884
+ gateway.published = 'next';
885
+ const published = await build('live');
886
+ live = await startStaticServer(published);
887
+ router = await startSessionRouter(pinned, gateway.url);
888
+ browser = await chromium.launch();
889
+ }, 1_500_000);
890
+
891
+ afterAll(async () => {
892
+ await browser?.close();
893
+ await router?.close();
894
+ await live?.close();
895
+ await gateway?.close();
896
+ await upstream?.close();
897
+ if (scratch !== undefined) rmSync(scratch, { recursive: true, force: true });
898
+ });
899
+
900
+ it('places every starter block type on the parity page', () => {
901
+ expect(STARTER_BLOCK_TYPES.length).toBeGreaterThanOrEqual(35);
902
+ });
903
+
904
+ it('answers localized fields without changing any block’s own sample data', () => {
905
+ for (const apiId of STARTER_BLOCK_TYPES) {
906
+ for (const locale of ['en-US', 'is-IS']) {
907
+ expect(inLocale(sampleData(apiId), locale), `${apiId} in ${locale}`).toEqual(
908
+ sampleData(apiId)
909
+ );
910
+ }
911
+ }
912
+ });
913
+
914
+ for (const path of PARITY_PATHS) {
915
+ for (const width of WIDTHS) {
916
+ it(`${path} at ${width}: the session's DOM is the live page's`, async () => {
917
+ const reads = gateway.draftReads.length;
918
+ const published = await capture(live.origin, path, width, false);
919
+ const session = await capture(router.origin, path, width, true);
920
+ // The session really read the drafts, and the live page really rendered something.
921
+ expect(gateway.draftReads.length).toBeGreaterThan(reads);
922
+ expect(published.dom.length).toBeGreaterThan(50);
923
+ expect(published.dom.some((line) => line.includes('data-eldra-invalid-layout'))).toBe(
924
+ false
925
+ );
926
+ expect(published.dom.some((line) => line.includes('data-eldra-missing-block'))).toBe(false);
927
+ expect(session.dom.join('\n')).toBe(published.dom.join('\n'));
928
+ expectNoChangeAfterTheVeil(session);
929
+ expect(session.data).toBe(published.data);
930
+ // The metadata does differ — the session read drafts — and reaches nothing above.
931
+ expect(session.dataWithMetadata).not.toBe(published.dataWithMetadata);
932
+ expect(session.dataWithMetadata).toContain('"updatedAt": "2026-11-20T10:00:00Z"');
933
+ expect(session.dataWithMetadata).not.toMatch(/"status": "(CHANGED|DRAFT|PUBLISHED)"/);
934
+ expect(published.dataWithMetadata).not.toMatch(/"status": "(CHANGED|DRAFT|PUBLISHED)"/);
935
+ expect(session.scrollY).toBe(published.scrollY);
936
+ expect(session.focused).toBe(published.focused);
937
+ expectSameWarnings(path, session.warnings, published.warnings);
938
+ });
939
+
940
+ it(`${path} at ${width}: 0 pixels differ`, async () => {
941
+ const published = await screenshot(live.origin, path, width, false);
942
+ const session = await screenshot(router.origin, path, width, true);
943
+ await expectSamePixels(path, width, session, published);
944
+ });
945
+ }
946
+ }
947
+
948
+ for (const edit of EDIT_CASES) {
949
+ const path = `/${edit}`;
950
+ const expected = EDIT_EXPECTATIONS[edit];
951
+ for (const width of WIDTHS) {
952
+ it(`${path} at ${width}: ${expected.renumbers ? 'renumbers ids (known)' : 'the session’s DOM is the live page’s'}`, async () => {
953
+ const published = await capture(live.origin, path, width, false);
954
+ const session = await capture(router.origin, path, width, true);
955
+ const liveHints = hintsOf(published.dom);
956
+ const sessionHints = hintsOf(session.dom);
957
+ expectNoChangeAfterTheVeil(session);
958
+ expectSameWarnings(path, session.warnings, published.warnings);
959
+ expect(session.focused).toBe(published.focused);
960
+ expect(session.scrollY).toBe(published.scrollY);
961
+ // Chunk hints: the same chunks are named, and only the edited blocks' change kind. A block
962
+ // type the pinned page did not render is needed late: the live page preloads its chunk and
963
+ // the session either keeps the pinned page's prefetch (Vite adds no hint for a chunk a
964
+ // link already names) or, where nothing named it, gets a late `modulepreload` from the
965
+ // runtime as an absolute URL. One the draft no longer renders stays preloaded from the
966
+ // pinned page where the live page prefetches it (stale). Pinned per edit by count, so a
967
+ // flip on an unrelated chunk fails.
968
+ expect(sessionHints.paths).toEqual(liveHints.paths);
969
+ expect(sessionHints.late.filter((hint) => !liveHints.preloaded.includes(hint))).toEqual([]);
970
+ const needed = liveHints.preloaded.filter((hint) => !sessionHints.preloaded.includes(hint));
971
+ expect(needed).toHaveLength(expected.lateChunks);
972
+ const stale = sessionHints.preloaded.filter((hint) => !liveHints.preloaded.includes(hint));
973
+ expect(stale).toHaveLength(expected.staleChunks);
974
+ let liveBody = bodyOf(published.dom);
975
+ let sessionBody = bodyOf(session.dom);
976
+ let sessionData = session.data;
977
+ if (expected.notFoundDocument) {
978
+ // The session hydrated the pinned build's not-found document: its payload preload is
979
+ // that document's, and the session holds that document's route as well (re-read once,
980
+ // like every route the server filled), beside the draft page's.
981
+ const payloadHint = (line: string): boolean =>
982
+ line.includes('rel="preload"') && line.includes('_payload.json');
983
+ expect(liveBody.filter(payloadHint).join('')).toContain(`href="${path}/_payload.json`);
984
+ expect(sessionBody.filter(payloadHint).join('')).toContain('href="/404/_payload.json');
985
+ liveBody = liveBody.filter((line) => !payloadHint(line));
986
+ sessionBody = sessionBody.filter((line) => !payloadHint(line));
987
+ // Nuxt ends the head it renders with its prefetch template. The not-found document has no
988
+ // breadcrumb list, so the session's head manager adds that script after the template,
989
+ // where the live page's server render put it before. Only that: the template is the live
990
+ // head's last element, and only the breadcrumb script follows it in the session's.
991
+ const prefetchTemplate = (line: string): boolean =>
992
+ line.trim() === '<template data-nuxt-prefetch="">';
993
+ const afterTemplate = (body: readonly string[]): string[] => {
994
+ const at = body.findIndex(prefetchTemplate);
995
+ const end = body.findIndex((line) => line.trim() === '<body>');
996
+ expect(body.filter(prefetchTemplate)).toHaveLength(1);
997
+ expect(at).toBeLessThan(end);
998
+ return body.slice(at + 1, end);
999
+ };
1000
+ expect(afterTemplate(liveBody)).toEqual([]);
1001
+ const trailing = afterTemplate(sessionBody);
1002
+ expect(trailing[0]).toContain('data-hid="eldra-ld"');
1003
+ expect(trailing.slice(1).every((line) => !line.trim().startsWith('<'))).toBe(true);
1004
+ liveBody = liveBody.filter((line) => !prefetchTemplate(line));
1005
+ sessionBody = sessionBody.filter((line) => !prefetchTemplate(line));
1006
+ const parsed = JSON.parse(sessionData) as { data: Record<string, unknown> };
1007
+ expect(Object.keys(parsed.data)).toContain('eldra-page:/404');
1008
+ delete parsed.data['eldra-page:/404'];
1009
+ sessionData = JSON.stringify(parsed, null, 1);
1010
+ }
1011
+ expect(sessionData).toBe(published.data);
1012
+ if (!expected.renumbers) {
1013
+ expect(sessionBody.join('\n')).toBe(liveBody.join('\n'));
1014
+ return;
1015
+ }
1016
+ // Unequal as they are; equal once the ids are renumbered; and exactly these ids moved.
1017
+ expect(sessionBody.join('\n')).not.toBe(liveBody.join('\n'));
1018
+ expect(renumberIds(sessionBody)).toEqual(renumberIds(liveBody));
1019
+ const moved = renumbered(liveBody, sessionBody);
1020
+ expect(moved.blocks).toEqual(expected.blocks);
1021
+ expect(moved.ids).toEqual(expected.ids);
1022
+ });
1023
+
1024
+ it(`${path} at ${width}: 0 pixels differ`, async () => {
1025
+ const published = await screenshot(live.origin, path, width, false);
1026
+ const session = await screenshot(router.origin, path, width, true);
1027
+ await expectSamePixels(path, width, session, published);
1028
+ });
1029
+ }
1030
+ }
1031
+
1032
+ /**
1033
+ * **Known difference: focus given late, and scroll-driven state.** A component that focuses on
1034
+ * mount (the search results page's field) is hydrated in a session while the app is inert under
1035
+ * the veil, so the focus is given only once the draft is shown (`replayCoveredFocus`), seconds
1036
+ * later than on the live page. Both end with the field focused and the page scrolled to it; but
1037
+ * what reacts to scroll events then runs in a different order against the page's other late work
1038
+ * (the storefront's catalog refresh), and the starter header's hide-on-scroll ends hidden on the
1039
+ * live page and, in about half the runs, shown in the session. Pinned here with the field
1040
+ * mid-page: the focus and the scroll position must match, and the header's `-translate-y-full`
1041
+ * is the only thing allowed to differ. On the real `/search` page, where the field stands near
1042
+ * the top and the header never hides, the two match exactly (`/` above).
1043
+ */
1044
+ for (const width of [1280] as const) {
1045
+ it(`${FOCUS_MID_PATH} at ${width}: a field focused mid-page is focused and scrolled to, the header may differ (known)`, async () => {
1046
+ const published = await capture(live.origin, FOCUS_MID_PATH, width, false);
1047
+ const session = await capture(router.origin, FOCUS_MID_PATH, width, true);
1048
+ expect(published.focused).toBe('input[aria-label="Search the shop"]');
1049
+ expect(session.focused).toBe(published.focused);
1050
+ expect(session.scrollY).toBe(published.scrollY);
1051
+ expect(published.scrollY).toBeGreaterThan(900);
1052
+ const differing = published.dom
1053
+ .map((line, index) => [line, session.dom[index]!] as const)
1054
+ .filter(([before, after]) => before !== after);
1055
+ expect(session.dom.length).toBe(published.dom.length);
1056
+ for (const [before, after] of differing) {
1057
+ expect(before).toMatch(/^\s*<header /);
1058
+ expect(before.replace(' -translate-y-full', '')).toBe(
1059
+ after.replace(' -translate-y-full', '')
1060
+ );
1061
+ }
1062
+ expect(differing.length).toBeLessThanOrEqual(1);
1063
+ expectNoChangeAfterTheVeil(session, true);
1064
+ expect(session.data).toBe(published.data);
1065
+ expectSameWarnings(FOCUS_MID_PATH, session.warnings, published.warnings);
1066
+ });
1067
+ }
1068
+
1069
+ /**
1070
+ * **Design tokens and theme texts saved after the pinned deploy (the owner's decision, 2026-11-23):
1071
+ * a preview shows them as soon as they are saved** (WS-1394). A build reads the site's tokens and
1072
+ * theme texts once and bakes them in (`@eldrajs/theme-nuxt`'s module, `readDesignTokens` and
1073
+ * `readThemeMessages`); a session reads both again through the router once it has hydrated, before
1074
+ * its veil comes down, and puts them where the build put its own (`previewSessionSite.ts`). So a
1075
+ * session on the pinned build shows what a build made after the save shows.
1076
+ */
1077
+ describe('design tokens and theme texts saved after the pinned deploy show in a session', () => {
1078
+ let republished: StaticServer;
1079
+ /** The header's primary navigation label, as the theme ships it and as saved. */
1080
+ const SHIPPED_LABEL = 'Primary navigation';
1081
+ const SAVED_LABEL = 'Site navigation, saved after the pinned build';
1082
+
1083
+ beforeAll(async () => {
1084
+ const tokens = normalizeThemeDesignTokens(starterTokens);
1085
+ // Saved: the platform answers them from now on. What Publish would then put live is a build
1086
+ // made with them.
1087
+ gateway.designTokens = {
1088
+ ...tokens,
1089
+ colors: { ...tokens.colors, primary: { ...tokens.colors.primary!, value: '#0b57d0' } },
1090
+ } as unknown as Record<string, unknown>;
1091
+ gateway.themeMessageOverrides = { 'en-US': { 'header.primary': SAVED_LABEL } };
1092
+ republished = await startStaticServer(await build('resaved'));
1093
+ }, 900_000);
1094
+
1095
+ afterAll(async () => {
1096
+ gateway.designTokens = SITE_DESIGN_TOKENS;
1097
+ gateway.themeMessageOverrides = {};
1098
+ await republished?.close();
1099
+ });
1100
+
1101
+ /** The primary colour token, and which of the two navigation labels the page carries. */
1102
+ const look = (origin: string, session: boolean) =>
1103
+ open(origin, '/', 1280, session, (page) =>
1104
+ page.evaluate(
1105
+ ([shipped, saved]) => ({
1106
+ primary: getComputedStyle(document.documentElement)
1107
+ .getPropertyValue('--eldra-color-primary')
1108
+ .trim(),
1109
+ labels: [...document.querySelectorAll('#__nuxt [aria-label]')]
1110
+ .map((node) => node.getAttribute('aria-label'))
1111
+ .filter((label) => label === shipped || label === saved),
1112
+ // A session's document in the frame its veil dropped (`open`): what the merchant saw
1113
+ // first, which must already carry the saved values.
1114
+ veilDrop:
1115
+ (window as unknown as { __eldraVeilDrop?: { lines: string[] } }).__eldraVeilDrop
1116
+ ?.lines ?? null,
1117
+ }),
1118
+ [SHIPPED_LABEL, SAVED_LABEL] as const
1119
+ )
1120
+ );
1121
+
1122
+ it('a session shows the saved tokens, not the pinned build\u2019s', async () => {
1123
+ const pinned = await look(live.origin, false);
1124
+ const publishLive = await look(republished.origin, false);
1125
+ const session = await look(router.origin, true);
1126
+ expect(publishLive.primary).toBe('#0b57d0');
1127
+ expect(pinned.primary).not.toBe(publishLive.primary);
1128
+ // Already in the frame the veil dropped: the layout's token style carries the saved colour.
1129
+ const tokenStyle = (lines: readonly string[]) =>
1130
+ lines.filter((line) => line.includes('--eldra-color-primary:'));
1131
+ expect(session.veilDrop).not.toBeNull();
1132
+ expect(tokenStyle(session.veilDrop!).join('\n')).toContain('--eldra-color-primary:#0b57d0;');
1133
+ expect(session.primary).toBe(publishLive.primary);
1134
+ });
1135
+
1136
+ it('a session shows theme texts saved after the pinned deploy', async () => {
1137
+ const pinned = await look(live.origin, false);
1138
+ const publishLive = await look(republished.origin, false);
1139
+ const session = await look(router.origin, true);
1140
+ expect(pinned.labels).toContain(SHIPPED_LABEL);
1141
+ expect(pinned.labels).not.toContain(SAVED_LABEL);
1142
+ expect(publishLive.labels).toContain(SAVED_LABEL);
1143
+ expect(publishLive.labels).not.toContain(SHIPPED_LABEL);
1144
+ expect(session.labels).toEqual(publishLive.labels);
1145
+ // Already in the frame the veil dropped.
1146
+ expect(session.veilDrop).not.toBeNull();
1147
+ const drop = session.veilDrop!.join('\n');
1148
+ expect(drop).toContain(`aria-label="${SAVED_LABEL}"`);
1149
+ expect(drop).not.toContain(`aria-label="${SHIPPED_LABEL}"`);
1150
+ });
1151
+ });
1152
+ });