@eldrajs/theme-cli 0.2.7 → 0.2.8

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 (50) hide show
  1. package/CHANGELOG.md +1 -0
  2. package/package.json +3 -3
  3. package/template/.eldra/manifest.json +160 -132
  4. package/template/.eldra/previews.json +35 -35
  5. package/template/blocks/announcement-bar/preview.png +0 -0
  6. package/template/blocks/article/preview.png +0 -0
  7. package/template/blocks/article-list/preview.png +0 -0
  8. package/template/blocks/breadcrumbs/preview.png +0 -0
  9. package/template/blocks/cart/preview.png +0 -0
  10. package/template/blocks/collection-grid/preview.png +0 -0
  11. package/template/blocks/collection-header/preview.png +0 -0
  12. package/template/blocks/contact/preview.png +0 -0
  13. package/template/blocks/cta/preview.png +0 -0
  14. package/template/blocks/faq/preview.png +0 -0
  15. package/template/blocks/feature-grid/preview.png +0 -0
  16. package/template/blocks/footer/preview.png +0 -0
  17. package/template/blocks/form/preview.png +0 -0
  18. package/template/blocks/gallery/preview.png +0 -0
  19. package/template/blocks/hero/preview.png +0 -0
  20. package/template/blocks/image/preview.png +0 -0
  21. package/template/blocks/logo-cloud/preview.png +0 -0
  22. package/template/blocks/navigation/Block.vue +54 -11
  23. package/template/blocks/navigation/__tests__/Block.spec.ts +91 -8
  24. package/template/blocks/navigation/block.json +11 -3
  25. package/template/blocks/navigation/mock.json +134 -129
  26. package/template/blocks/navigation/preview.png +0 -0
  27. package/template/blocks/newsletter/preview.png +0 -0
  28. package/template/blocks/order-status/preview.png +0 -0
  29. package/template/blocks/pricing-table/preview.png +0 -0
  30. package/template/blocks/product-carousel/preview.png +0 -0
  31. package/template/blocks/product-detail/preview.png +0 -0
  32. package/template/blocks/quote/preview.png +0 -0
  33. package/template/blocks/rich-text/preview.png +0 -0
  34. package/template/blocks/search/preview.png +0 -0
  35. package/template/blocks/split-content/preview.png +0 -0
  36. package/template/blocks/stats/preview.png +0 -0
  37. package/template/blocks/tabs/preview.png +0 -0
  38. package/template/blocks/team/preview.png +0 -0
  39. package/template/blocks/testimonials/preview.png +0 -0
  40. package/template/blocks/timeline/preview.png +0 -0
  41. package/template/blocks/trust-strip/preview.png +0 -0
  42. package/template/blocks/video-embed/preview.png +0 -0
  43. package/template/blocks/wishlist/preview.png +0 -0
  44. package/template/package.json +1 -1
  45. package/template/public/images/bowl.webp +0 -0
  46. package/template/test/prerenderFailure.spec.ts +4 -3
  47. package/template/test/previewParity.browser.spec.ts +1152 -0
  48. package/template/test/starter.spec.ts +6 -1
  49. package/template/test/support/previewParity.ts +302 -0
  50. package/template/test/support/previewParityContent.ts +726 -0
@@ -1180,7 +1180,12 @@ describe('seeded templates and pages (app/templates.ts)', () => {
1180
1180
  it('ships no showAccount field, at a version that tells Core to retire it', () => {
1181
1181
  const navigation = scanned.manifest!.blocks.find((block) => block.apiId === 'navigation')!;
1182
1182
  expect(navigation.fields.map((field) => field.fieldId)).not.toContain('showAccount');
1183
- expect(navigation.version).toBe(4);
1183
+ // Version 5 is the `groupsToSections` step (WS-1362); the retirement happened at 4 and stays.
1184
+ expect(navigation.version).toBe(5);
1185
+ expect(navigation.migrations?.at(-1)).toEqual({
1186
+ version: 5,
1187
+ groupsToSections: [{ field: 'links' }],
1188
+ });
1184
1189
  // No step names it: a retire has no rename to declare.
1185
1190
  const named = (navigation.migrations ?? []).flatMap((step) => [
1186
1191
  ...(step.renames ?? []).map((rename) => rename.from),
@@ -0,0 +1,302 @@
1
+ import { normalizeThemeDesignTokens } from '@eldrajs/theme-core';
2
+ import { flattenMessages, type ThemeMessages } from '@eldrajs/theme-core/i18n';
3
+ import { readFileSync } from 'node:fs';
4
+ import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
5
+ import { extname, join } from 'node:path';
6
+ import starterTokens from '../../tokens.json';
7
+ import starterEnUs from '../../i18n/en-US.json';
8
+ import starterIsIs from '../../i18n/is-IS.json';
9
+ import { DEFAULT_LOCALE, ORG_ID, PREFIXED_LOCALE } from './mockGateway';
10
+ import { coreRead, isCoreRead, type ContentVersion } from './previewParityContent';
11
+ import { startStaticServer, type StaticServer } from './staticServer';
12
+
13
+ /**
14
+ * The servers of the preview parity harness (`test/previewParity.browser.spec.ts`, WS-1358): a
15
+ * stand-in gateway whose CMS reads are Core's two perspectives (`./previewParityContent.ts`), and a
16
+ * stand-in for the preview router that serves a pinned build the way it serves a session.
17
+ *
18
+ * Everything the content gateway does not own (the catalog, carts, the organisation, the site
19
+ * profile) is forwarded to the starter's own mock gateway (`./mockGateway.ts`), so commerce reads
20
+ * are exactly what every other generated-site test sees.
21
+ */
22
+
23
+ export interface ContentGateway {
24
+ url: string;
25
+ /** What a public read answers: `pinned` while the session's deployment is built, `next` after. */
26
+ published: ContentVersion;
27
+ /**
28
+ * The resolved design-token catalog `/site/v1/design-tokens` answers: what the site has saved.
29
+ * Core answers for every organisation with a site, so this is never a 404: before anything is
30
+ * saved it is the theme's own catalog (`SITE_DESIGN_TOKENS`).
31
+ */
32
+ designTokens: Record<string, unknown>;
33
+ /**
34
+ * The theme-text overrides the site has saved, per locale. `/site/v1/theme-messages` answers the
35
+ * theme's catalogue resolved over them, exactly as Core does (`coreThemeMessages`); `{}` before
36
+ * anything is saved.
37
+ */
38
+ themeMessageOverrides: Record<string, Record<string, string>>;
39
+ /** `pathname + search` of every request answered from the draft perspective. */
40
+ draftReads: string[];
41
+ close(): Promise<void>;
42
+ }
43
+
44
+ /** The site settings the content gateway answers itself, as Core's web-gateway does. */
45
+ const SITE_SETTINGS = new Set(['/site/v1/design-tokens', '/site/v1/theme-messages']);
46
+
47
+ /** What Core answers for the site's design tokens before any is saved: the theme's own catalog. */
48
+ export const SITE_DESIGN_TOKENS = normalizeThemeDesignTokens(starterTokens) as unknown as Record<
49
+ string,
50
+ unknown
51
+ >;
52
+
53
+ /** The theme's catalogue as Core holds it on the Site row: the manifest's flattened `i18n/` files. */
54
+ const SITE_THEME: ThemeMessages = {
55
+ defaultLocale: DEFAULT_LOCALE,
56
+ locales: {
57
+ [DEFAULT_LOCALE]: flattenMessages(starterEnUs),
58
+ [PREFIXED_LOCALE]: flattenMessages(starterIsIs),
59
+ },
60
+ };
61
+ /** The organisation's locales (`mockGateway`'s), default first. */
62
+ const ORG_LOCALES = [DEFAULT_LOCALE, PREFIXED_LOCALE];
63
+
64
+ /**
65
+ * What Core answers at `/site/v1/theme-messages` (site-service `GetPublicThemeMessages` and
66
+ * `resolveThemeMessages`, ported as they are): the **fully resolved** catalogue, not the overrides —
67
+ * for every organisation locale, every key of the theme's default locale, each through
68
+ * `override(locale) → theme(locale) → override(orgDefault) → theme(orgDefault) →
69
+ * theme(themeDefault)`, where a value is present only when it is not blank, and `""` when no tier
70
+ * has one; `defaultLocale` is the organisation's. Keys sorted, as Go writes a map.
71
+ */
72
+ export function coreThemeMessages(
73
+ overrides: Record<string, Record<string, string>>,
74
+ theme: ThemeMessages = SITE_THEME,
75
+ orgLocales: readonly string[] = ORG_LOCALES,
76
+ orgDefault: string = DEFAULT_LOCALE
77
+ ): ThemeMessages {
78
+ const present = (messages: Record<string, string> | undefined, key: string) => {
79
+ const value = messages?.[key];
80
+ return value !== undefined && value.trim() !== '' ? value : undefined;
81
+ };
82
+ const keys = Object.keys(theme.locales[theme.defaultLocale] ?? {}).sort();
83
+ const locales: Record<string, Record<string, string>> = {};
84
+ for (const locale of [...orgLocales].sort()) {
85
+ const resolved: Record<string, string> = {};
86
+ for (const key of keys) {
87
+ resolved[key] =
88
+ present(overrides[locale], key) ??
89
+ present(theme.locales[locale], key) ??
90
+ present(overrides[orgDefault], key) ??
91
+ present(theme.locales[orgDefault], key) ??
92
+ present(theme.locales[theme.defaultLocale], key) ??
93
+ '';
94
+ }
95
+ locales[locale] = resolved;
96
+ }
97
+ return { defaultLocale: orgDefault, locales };
98
+ }
99
+
100
+ /**
101
+ * The CMS half of a gateway, in both of Core's perspectives: a request carrying
102
+ * `X-Preview-Session` reads the drafts (always `next`, in the draft shape, marked
103
+ * `Eldra-Preview: draft` as Core marks a session's answers), any other reads the published
104
+ * version. Everything else goes to `upstream`, the starter's own mock gateway.
105
+ */
106
+ export function startContentGateway(upstream: string): Promise<ContentGateway> {
107
+ const state: ContentGateway = {
108
+ url: '',
109
+ published: 'pinned',
110
+ designTokens: SITE_DESIGN_TOKENS,
111
+ themeMessageOverrides: {},
112
+ draftReads: [],
113
+ close: () => Promise.resolve(),
114
+ };
115
+ const server = createServer((req, res) => {
116
+ void handle(req, res).catch((error: unknown) => {
117
+ res.statusCode = 502;
118
+ res.end(JSON.stringify({ error: String(error) }));
119
+ });
120
+ });
121
+
122
+ const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
123
+ const url = new URL(req.url ?? '/', 'http://localhost');
124
+ const draft = req.headers['x-preview-session'] !== undefined;
125
+ if (!isCoreRead(url.pathname) && !SITE_SETTINGS.has(url.pathname)) {
126
+ await forward(req, res, `${upstream}${url.pathname}${url.search}`);
127
+ return;
128
+ }
129
+ res.setHeader('access-control-allow-origin', '*');
130
+ res.setHeader('access-control-allow-headers', '*');
131
+ res.setHeader('cache-control', 'no-store');
132
+ res.setHeader('content-type', 'application/json');
133
+ if (req.method === 'OPTIONS') {
134
+ res.statusCode = 204;
135
+ res.end();
136
+ return;
137
+ }
138
+ if (req.headers['x-org-id'] !== ORG_ID) {
139
+ res.statusCode = 400;
140
+ res.end(JSON.stringify({ error: 'missing org id' }));
141
+ return;
142
+ }
143
+ // Site settings are not drafts: Core reads the Site row, the same answer in both perspectives,
144
+ // never marked `Eldra-Preview: draft`.
145
+ if (url.pathname === '/site/v1/design-tokens') {
146
+ res.end(JSON.stringify({ revision: 9, resolved: state.designTokens }));
147
+ return;
148
+ }
149
+ if (url.pathname === '/site/v1/theme-messages') {
150
+ res.end(JSON.stringify(coreThemeMessages(state.themeMessageOverrides)));
151
+ return;
152
+ }
153
+ if (draft) {
154
+ res.setHeader('eldra-preview', 'draft');
155
+ state.draftReads.push(url.pathname + url.search);
156
+ }
157
+ const { status, body } = coreRead(draft ? 'draft' : 'public', state.published, url);
158
+ res.statusCode = status;
159
+ res.end(JSON.stringify(body));
160
+ };
161
+
162
+ return new Promise((resolve) => {
163
+ server.listen(0, '127.0.0.1', () => {
164
+ const address = server.address();
165
+ if (typeof address !== 'object' || address === null) return;
166
+ state.url = `http://127.0.0.1:${address.port}`;
167
+ state.close = () => closeServer(server);
168
+ resolve(state);
169
+ });
170
+ });
171
+ }
172
+
173
+ /** Passes a request through to `target`, status, headers and body as they are. */
174
+ async function forward(req: IncomingMessage, res: ServerResponse, target: string): Promise<void> {
175
+ const chunks: Buffer[] = [];
176
+ for await (const chunk of req) chunks.push(chunk as Buffer);
177
+ const headers: Record<string, string> = {};
178
+ for (const [name, value] of Object.entries(req.headers)) {
179
+ if (value === undefined || name === 'host' || name === 'connection') continue;
180
+ headers[name] = Array.isArray(value) ? value.join(', ') : value;
181
+ }
182
+ const upstream = await fetch(target, {
183
+ method: req.method,
184
+ headers,
185
+ body: chunks.length > 0 ? Buffer.concat(chunks) : undefined,
186
+ redirect: 'manual',
187
+ });
188
+ const out: Record<string, string> = {};
189
+ upstream.headers.forEach((value, name) => {
190
+ if (!['content-encoding', 'content-length', 'transfer-encoding', 'connection'].includes(name)) {
191
+ out[name] = value;
192
+ }
193
+ });
194
+ res.writeHead(upstream.status, out).end(Buffer.from(await upstream.arrayBuffer()));
195
+ }
196
+
197
+ /** What the stand-in router keeps for the session: the secret, never the browser's. */
198
+ export const SESSION_SECRET = 'eldra_prv_parity-session-secret';
199
+
200
+ /**
201
+ * Exactly what the router prepends right after `<head>` in every page it serves for a session
202
+ * (site-deploy-worker `withPreviewHead`, WS-1376): the robots tag, the session marker, and the early
203
+ * hide — a `<style>` whose 12 s animation keeps the body hidden until the kit sets
204
+ * `data-eldra-preview-ready` on `<html>` (after it, the page shows with a notice if the kit never
205
+ * did) and its `<noscript>` twin. Copied byte for byte (788 bytes), CSS escapes included.
206
+ */
207
+ const SESSION_HEAD = String.raw`<meta name="robots" content="noindex, nofollow"><meta name="eldra-preview" content="session"><style>html:not([data-eldra-preview-ready]) body{animation:eldra-preview-veil 12s step-end}html:not([data-eldra-preview-ready])::before{content:"Forsko\f0 unin f\f3 r ekki \ed gang. \de etta er \fa tgefna s\ed \f0 an.\a The preview could not start. This is the published page.";display:block;white-space:pre-line;padding:8px 16px;font:14px/1.4 system-ui,sans-serif;color:#1f2328;background:#fff8c5;border-bottom:1px solid #d4a72c;animation:eldra-preview-veil 12s step-end}@keyframes eldra-preview-veil{from,to{visibility:hidden}}</style><noscript><style>html:not([data-eldra-preview-ready]) body,html:not([data-eldra-preview-ready])::before{visibility:visible;animation:none}</style></noscript>`;
208
+
209
+ export interface SessionRouter {
210
+ origin: string;
211
+ close(): Promise<void>;
212
+ }
213
+
214
+ /**
215
+ * The preview router, as far as a page can tell (site-deploy-worker `src/preview-router.ts`): the
216
+ * session's pinned deployment, served by the same static host a published site has (so the same
217
+ * trailing-slash redirect), with the theme's own robots tag replaced by `SESSION_HEAD` (the robots
218
+ * tag, the session marker and the early hide) in every HTML document, and the draft read proxy at
219
+ * `/__eldra/gateway/*` adding the organisation and `X-Preview-Session` itself.
220
+ */
221
+ export async function startSessionRouter(
222
+ publicDir: string,
223
+ gatewayUrl: string
224
+ ): Promise<SessionRouter> {
225
+ const statics: StaticServer = await startStaticServer(publicDir);
226
+ const server: Server = createServer((req, res) => {
227
+ void handle(req, res).catch((error: unknown) => {
228
+ res.statusCode = 502;
229
+ res.end(String(error));
230
+ });
231
+ });
232
+ const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
233
+ const url = new URL(req.url ?? '/', 'http://localhost');
234
+ if (url.pathname.startsWith('/__eldra/gateway/')) {
235
+ const chunks: Buffer[] = [];
236
+ for await (const chunk of req) chunks.push(chunk as Buffer);
237
+ const headers: Record<string, string> = {
238
+ accept: 'application/json',
239
+ 'x-org-id': ORG_ID,
240
+ 'x-preview-session': SESSION_SECRET,
241
+ };
242
+ const language = req.headers['accept-language'];
243
+ if (typeof language === 'string') headers['accept-language'] = language;
244
+ if (req.method === 'POST') headers['content-type'] = 'application/json';
245
+ const rest = url.pathname.slice('/__eldra/gateway'.length);
246
+ const upstream = await fetch(`${gatewayUrl}${rest}${url.search}`, {
247
+ method: req.method,
248
+ headers,
249
+ body: req.method === 'POST' ? Buffer.concat(chunks) : undefined,
250
+ });
251
+ const out: Record<string, string> = { 'cache-control': 'no-store' };
252
+ const type = upstream.headers.get('content-type');
253
+ if (type) out['content-type'] = type;
254
+ const marker = upstream.headers.get('eldra-preview');
255
+ if (marker) out['eldra-preview'] = marker;
256
+ res.writeHead(upstream.status, out).end(Buffer.from(await upstream.arrayBuffer()));
257
+ return;
258
+ }
259
+ const upstream = await fetch(`${statics.origin}${url.pathname}${url.search}`, {
260
+ redirect: 'manual',
261
+ });
262
+ const out: Record<string, string> = {};
263
+ upstream.headers.forEach((value, name) => {
264
+ if (!['content-length', 'transfer-encoding', 'connection'].includes(name)) out[name] = value;
265
+ });
266
+ let body: Buffer | string = Buffer.from(await upstream.arrayBuffer());
267
+ // A page the pinned build does not have (a draft-only page): the host answers the build's own
268
+ // not-found document, and the app resolves the route from the drafts.
269
+ if (upstream.status === 404 && extname(url.pathname) === '') {
270
+ body = readFileSync(join(publicDir, '404.html'));
271
+ out['content-type'] = 'text/html; charset=utf-8';
272
+ }
273
+ if ((out['content-type'] ?? '').startsWith('text/html')) {
274
+ body = body
275
+ .toString('utf8')
276
+ .replace(/<meta name="robots"[^>]*>/g, '')
277
+ // The router drops a ready attribute the page itself carries: only the kit lifts the hide.
278
+ .replace(/(<html\b[^>]*?)\s+data-eldra-preview-ready(?:="[^"]*")?/, '$1')
279
+ .replace('<head>', `<head>${SESSION_HEAD}`);
280
+ }
281
+ res.writeHead(upstream.status, out).end(body);
282
+ };
283
+ const origin = await new Promise<string>((resolve) => {
284
+ server.listen(0, '127.0.0.1', () => {
285
+ const address = server.address();
286
+ if (typeof address === 'object' && address !== null) {
287
+ resolve(`http://127.0.0.1:${address.port}`);
288
+ }
289
+ });
290
+ });
291
+ return {
292
+ origin,
293
+ close: async () => {
294
+ await closeServer(server);
295
+ await statics.close();
296
+ },
297
+ };
298
+ }
299
+
300
+ function closeServer(server: Server): Promise<void> {
301
+ return new Promise((resolve) => server.close(() => resolve()));
302
+ }