@eldrajs/theme-nuxt 0.1.1 → 0.2.0

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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,28 @@ Release-please writes the generated notes from commit messages and does not repl
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ - The runtime registers the theme's own id (`manifest.theme.id`) with `registerBlockFields`, and
9
+ the draft projection validates slots against bare block ids when a published entry's
10
+ `schemaApiId` is `<themeId>:<apiId>`. Route-template targets (a merchant's own schema) and
11
+ `catalog:*` are unchanged. The theme must declare `eldra.themeId` in `package.json` (see the
12
+ `@eldrajs/vite-plugin-theme` changelog).
13
+
14
+ - **Site icons, set in Studio and rendered by the media worker.** A fifth fail-soft read, `GET
15
+ /site/v1/site-icons` (`readSiteIcons`, `./runtime/siteIcons.ts`), answers the site's icon (a
16
+ media-library raster, square, at least 512 px), background colour, theme colour, short name and
17
+ `icons`, the URLs of the variants the media worker renders (`null` when no icon is set). When an
18
+ icon is set, `nuxi generate` writes only `site.webmanifest` into the static output (on both
19
+ nitro `compiled` and `prerender:done`) and adds `<link rel="icon" type="image/png"
20
+ sizes="32x32">`, `<link rel="apple-touch-icon">`, `<link rel="manifest">` and `<meta
21
+ name="theme-color">` to every page; the icon tags point at the media URLs. No image is fetched or
22
+ processed at build time and no `favicon.ico` is generated (the theme's own `public/favicon.ico`
23
+ stays the root fallback). The theme colour defaults to the primary design token and the short name
24
+ to the site name. With no icon set or a failed read, nothing is written or tagged and the theme's
25
+ `public/` files stay. The icons replace the theme's own icon, manifest and `theme-color` tags in
26
+ `app.head`. `sharp` was removed (an earlier draft of this feature generated the files with it):
27
+ native image processing in every theme build was fragile, and the media worker renders the sizes.
28
+ Documented in `docs/themes.md` (Site icons).
29
+
8
30
  - **The deployed site now carries Studio's design-token overrides, not only the open preview.** A
9
31
  fourth fail-soft read, alongside the store's currency, its locales and the theme-message overrides
10
32
  — `GET /site/v1/design-tokens`, same client, same retry policy, absent gateway or any error
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=3.13.0"
6
6
  },
7
- "version": "0.1.1",
7
+ "version": "0.2.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "0.8.4",
10
10
  "unbuild": "unknown"
package/dist/module.mjs CHANGED
@@ -7,10 +7,12 @@ import eldraTheme from '@eldrajs/vite-plugin-theme';
7
7
  import { listCatalogDocs, catalogDocRoutes } from '../dist/runtime/catalog.js';
8
8
  import { readStoreCommerce } from '../dist/runtime/commerce.js';
9
9
  import { readDesignTokens } from '../dist/runtime/designTokens.js';
10
+ import { buildSiteIconOutput } from '../dist/runtime/siteIconAssets.js';
10
11
  import { normalizeLocale } from '../dist/runtime/locale.js';
11
12
  import { resolveLocaleRouting, readStoreLocales, localePathFor } from '../dist/runtime/locales.js';
12
13
  import { readThemeMessages, resolveSiteMessages } from '../dist/runtime/messages.js';
13
14
  import { listAllEntries } from '../dist/runtime/resolveRoute.js';
15
+ import { readSiteIcons, resolveSiteIcons } from '../dist/runtime/siteIcons.js';
14
16
 
15
17
  const eldraModule = defineNuxtModule({
16
18
  meta: {
@@ -170,13 +172,23 @@ const eldraModule = defineNuxtModule({
170
172
  }
171
173
  }
172
174
  });
175
+ let siteIconFiles = [];
173
176
  nuxt.hooks.hook(
174
177
  "nitro:init",
175
178
  (nitro) => {
179
+ const writeSiteIconFiles = (publicDir) => {
180
+ if (siteIconFiles.length === 0)
181
+ return;
182
+ mkdirSync(publicDir, { recursive: true });
183
+ for (const file of siteIconFiles)
184
+ writeFileSync(join(publicDir, file.name), file.data);
185
+ };
186
+ nitro.hooks.hook("compiled", () => writeSiteIconFiles(nitro.options.output.publicDir));
176
187
  nitro.hooks.hook("prerender:done", () => {
177
188
  const publicDir = nitro.options.output.publicDir;
178
189
  mkdirSync(publicDir, { recursive: true });
179
190
  copyGeneratedManifest(nuxt.options.rootDir, publicDir);
191
+ writeSiteIconFiles(publicDir);
180
192
  const target = join(publicDir, "_headers");
181
193
  const existing = existsSync(target) ? readFileSync(target, "utf8").replace(/^\s*Content-Security-Policy:\s*frame-ancestors[^\r\n]*(?:\r?\n|$)/gim, "").trimEnd() + "\n\n" : "";
182
194
  const ancestors = ["'self'", ...studioOrigins].join(" ");
@@ -199,16 +211,39 @@ const eldraModule = defineNuxtModule({
199
211
  orgId: options.orgId,
200
212
  retry: options.retry
201
213
  });
202
- const [commerce, locales, platformMessages, platformDesignTokens] = await Promise.all([
214
+ const [commerce, locales, platformMessages, platformDesignTokens, platformSiteIcons] = await Promise.all([
203
215
  readStoreCommerce(platformClient),
204
216
  readStoreLocales(platformClient),
205
217
  readThemeMessages(platformClient),
206
- readDesignTokens(platformClient)
218
+ readDesignTokens(platformClient),
219
+ nuxt.options.dev ? Promise.resolve(null) : readSiteIcons(platformClient)
207
220
  ]);
208
221
  const runtimeEldra = nuxt.options.runtimeConfig.public.eldra;
209
222
  runtimeEldra.commerce = commerce;
210
223
  runtimeEldra.locales = locales;
211
224
  runtimeEldra.designTokens = platformDesignTokens;
225
+ const resolvedSiteIcons = resolveSiteIcons(platformSiteIcons, {
226
+ siteName: siteName(nuxt.options.app.head.title, nuxt.options.rootDir),
227
+ primaryToken: platformDesignTokens?.colors.primary?.value ?? themePrimaryToken(nuxt.options.rootDir)
228
+ });
229
+ const siteIcons = resolvedSiteIcons === null ? null : buildSiteIconOutput(resolvedSiteIcons, nuxt.options.app.baseURL);
230
+ if (siteIcons !== null) {
231
+ siteIconFiles = siteIcons.files;
232
+ const replacedRels = /* @__PURE__ */ new Set(["icon", "shortcut icon", "apple-touch-icon", "manifest"]);
233
+ const generatesThemeColor = siteIcons.meta.some((tag) => tag.name === "theme-color");
234
+ nuxt.options.app.head.link = [
235
+ ...(nuxt.options.app.head.link ?? []).filter(
236
+ (tag) => !replacedRels.has(String(tag.rel ?? "").toLowerCase())
237
+ ),
238
+ ...siteIcons.link
239
+ ];
240
+ nuxt.options.app.head.meta = [
241
+ ...(nuxt.options.app.head.meta ?? []).filter(
242
+ (tag) => !generatesThemeColor || String(tag.name ?? "").toLowerCase() !== "theme-color"
243
+ ),
244
+ ...siteIcons.meta
245
+ ];
246
+ }
212
247
  localeRouting = resolveLocaleRouting(locales, options.locale);
213
248
  themeOptions.resolveMessages = (manifestMessages) => resolveSiteMessages(manifestMessages, platformMessages, locales);
214
249
  themeOptions.resolveTokens = (manifestTokens) => platformDesignTokens ?? normalizeThemeDesignTokens(manifestTokens);
@@ -248,6 +283,26 @@ function packageVersion(path) {
248
283
  return "0.0.0";
249
284
  }
250
285
  }
286
+ function siteName(title, rootDir) {
287
+ if (typeof title === "string" && title.trim() !== "")
288
+ return title;
289
+ try {
290
+ const pkg = JSON.parse(readFileSync(join(rootDir, "package.json"), "utf8"));
291
+ return typeof pkg.name === "string" ? pkg.name.replace(/^@[^/]+\//, "") : null;
292
+ } catch {
293
+ return null;
294
+ }
295
+ }
296
+ function themePrimaryToken(rootDir) {
297
+ try {
298
+ const tokens = normalizeThemeDesignTokens(
299
+ JSON.parse(readFileSync(join(rootDir, "tokens.json"), "utf8"))
300
+ );
301
+ return tokens.colors.primary?.value ?? null;
302
+ } catch {
303
+ return null;
304
+ }
305
+ }
251
306
  function copyGeneratedManifest(rootDir, publicDir) {
252
307
  const sourceDir = join(rootDir, ".eldra");
253
308
  const sourceManifest = join(sourceDir, "manifest.json");
@@ -1,4 +1,5 @@
1
1
  import {
2
+ blockApiIdOf,
2
3
  normalizeLayoutDocument
3
4
  } from "@eldrajs/theme-core";
4
5
  import themeManifest from "virtual:eldra/manifest";
@@ -63,7 +64,12 @@ function layoutBlockEntryIds(value, byId, draftSchemaApiIds) {
63
64
  if (value === void 0) return null;
64
65
  const slotContext = {
65
66
  slotCatalog: THEME_SLOT_CATALOG,
66
- entryApiId: (entryId) => byId.get(entryId)?.schemaApiId ?? draftSchemaApiIds[entryId]
67
+ // The slot catalog is keyed by the bare block id; a published entry's
68
+ // schemaApiId is the wire spelling `<themeId>:<apiId>`.
69
+ entryApiId: (entryId) => {
70
+ const schemaApiId = byId.get(entryId)?.schemaApiId ?? draftSchemaApiIds[entryId];
71
+ return typeof schemaApiId === "string" ? blockApiIdOf(schemaApiId, themeManifest.theme?.id) : void 0;
72
+ }
67
73
  };
68
74
  try {
69
75
  return normalizeLayoutDocument(value, void 0, void 0, slotContext).blockEntryIds;
@@ -24,7 +24,7 @@ import { primePrerenderedRoutes } from "./staticRoutes.js";
24
24
  export default defineNuxtPlugin({
25
25
  name: "eldra-theme",
26
26
  setup(nuxtApp) {
27
- registerBlockFields(blockFields);
27
+ registerBlockFields(blockFields, manifest.theme.id);
28
28
  const cfg = useRuntimeConfig().public.eldra;
29
29
  const storeLocales = resolveStoreLocales(cfg.locales);
30
30
  const routing = resolveLocaleRouting(storeLocales, cfg.locale);
@@ -0,0 +1,19 @@
1
+ import type { ResolvedSiteIcons } from './siteIcons.js';
2
+ /** One file the build writes into the static output. */
3
+ export interface GeneratedIconFile {
4
+ /** Path relative to the site root. */
5
+ name: string;
6
+ data: Buffer;
7
+ }
8
+ export interface SiteIconOutput {
9
+ /** Only `site.webmanifest`: every image is linked straight from the media CDN. */
10
+ files: GeneratedIconFile[];
11
+ link: Record<string, string>[];
12
+ meta: Record<string, string>[];
13
+ }
14
+ /**
15
+ * The web manifest and head tags for a resolved site icon setting. Pure and in-memory — no image
16
+ * is fetched or processed here: the media worker renders every size (always PNG), Core builds the
17
+ * URLs, and this only points at them. The manifest is same-origin JSON (a browser requires it).
18
+ */
19
+ export declare function buildSiteIconOutput(setting: Pick<ResolvedSiteIcons, 'icons' | 'backgroundColor' | 'themeColor' | 'shortName' | 'name'>, baseURL?: string): SiteIconOutput;
@@ -0,0 +1,29 @@
1
+ export function buildSiteIconOutput(setting, baseURL = "/") {
2
+ const base = baseURL.endsWith("/") ? baseURL : `${baseURL}/`;
3
+ const { icons } = setting;
4
+ const name = setting.name ?? setting.shortName;
5
+ const manifest = {
6
+ ...name === null ? {} : { name },
7
+ ...setting.shortName === null ? {} : { short_name: setting.shortName },
8
+ icons: [
9
+ { src: icons.icon192, sizes: "192x192", type: "image/png" },
10
+ { src: icons.icon512, sizes: "512x512", type: "image/png" },
11
+ { src: icons.maskable512, sizes: "512x512", type: "image/png", purpose: "maskable" }
12
+ ],
13
+ ...setting.themeColor === null ? {} : { theme_color: setting.themeColor },
14
+ background_color: setting.backgroundColor,
15
+ display: "standalone",
16
+ start_url: base
17
+ };
18
+ return {
19
+ files: [
20
+ { name: "site.webmanifest", data: Buffer.from(JSON.stringify(manifest, null, 2) + "\n") }
21
+ ],
22
+ link: [
23
+ { rel: "icon", type: "image/png", sizes: "32x32", href: icons.favicon32 },
24
+ { rel: "apple-touch-icon", href: icons.appleTouch180 },
25
+ { rel: "manifest", href: `${base}site.webmanifest` }
26
+ ],
27
+ meta: setting.themeColor === null ? [] : [{ name: "theme-color", content: setting.themeColor }]
28
+ };
29
+ }
@@ -0,0 +1,74 @@
1
+ import type { EldraClient } from '@eldrajs/sdk';
2
+ /**
3
+ * The site's icon setting exactly as `GET /site/v1/site-icons` answers it (and Studio's
4
+ * `PUT /sites/{siteId}/site-icons` stores it). `iconUrl: null` means "no icons set": the theme's
5
+ * own `public/` files and head tags stay. The colour and short-name defaults (the theme's primary
6
+ * token, the site name) are resolved by the **build** — `resolveSiteIcons` below — never by Core.
7
+ */
8
+ export interface SiteIconsSetting {
9
+ revision: number;
10
+ /** The media-library asset URL (`{media}/public/{orgId}/assets/{assetId}`), or `null` when no icon is set. */
11
+ iconUrl: string | null;
12
+ /** `#rrggbb`. Paints the iOS icon and the maskable Android icon, which cannot be transparent. */
13
+ backgroundColor: string;
14
+ /** `#rrggbb`, or `null` for the theme's primary design token. */
15
+ themeColor: string | null;
16
+ /** 1–12 characters, or `null` for the site name. */
17
+ shortName: string | null;
18
+ /**
19
+ * The rendered variants, built by Core (the only place that knows the media worker's icon
20
+ * suffixes) — `null` exactly when `iconUrl` is `null`. The build links to these, never renders.
21
+ */
22
+ icons: SiteIconUrls | null;
23
+ }
24
+ /** Absolute media URLs of the icon variants the media worker renders (always `image/png`). */
25
+ export interface SiteIconUrls {
26
+ favicon32: string;
27
+ appleTouch180: string;
28
+ icon192: string;
29
+ icon512: string;
30
+ maskable512: string;
31
+ }
32
+ /**
33
+ * The slice of an `@eldrajs/sdk` client this read needs — a whole `EldraClient` satisfies it. The
34
+ * same narrow shape, for the same reasons, as `DesignTokensReader`: `GET /site/v1/site-icons` is a
35
+ * site-module read with no typed `features.*` method, so the client's generic `request` carries it.
36
+ */
37
+ export interface SiteIconsReader {
38
+ request: EldraClient['request'];
39
+ }
40
+ /** The one line a build prints when it could not read the platform's site icons. */
41
+ export declare const SITE_ICONS_WARNING = "[eldra] could not read the platform\u2019s site icons \u2014 keeping the theme\u2019s own icon files";
42
+ /** How long the build waits for the answer; see `READ_TIMEOUT_MS` in `./designTokens.ts`. */
43
+ export declare const READ_TIMEOUT_MS = 10000;
44
+ /** Android's launcher shows at most about this many characters of `short_name`. */
45
+ export declare const SHORT_NAME_MAX = 12;
46
+ /**
47
+ * The platform's site-icon setting, or `null`.
48
+ *
49
+ * Fail-soft exactly like `readDesignTokens`: no client, an unreachable gateway, a timeout and a
50
+ * response that is not the documented shape all end in `null` and **one** warning, so a theme keeps
51
+ * deploying with the icon files it ships. A well-formed answer with `iconUrl: null` is **not** a
52
+ * failure — it is the normal "nothing set" state — and warns nothing.
53
+ */
54
+ export declare function readSiteIcons(reader: SiteIconsReader | null, warn?: (message: string) => void): Promise<SiteIconsSetting | null>;
55
+ /** The values the generated files and tags are made from, defaults filled in. */
56
+ export interface ResolvedSiteIcons {
57
+ iconUrl: string;
58
+ icons: SiteIconUrls;
59
+ backgroundColor: string;
60
+ /** `null` when neither the setting nor the theme gives one — the meta tag is then omitted. */
61
+ themeColor: string | null;
62
+ /** `null` when neither the setting nor a site name gives one. */
63
+ shortName: string | null;
64
+ name: string | null;
65
+ }
66
+ /**
67
+ * Fills in the defaults Core deliberately does not store: the theme colour falls back to the
68
+ * theme's primary design token, the short name to the site name (cut to Android's limit). `null`
69
+ * when no icon is set, which is the signal to leave the theme's own files alone.
70
+ */
71
+ export declare function resolveSiteIcons(setting: SiteIconsSetting | null, defaults: {
72
+ siteName?: string | null;
73
+ primaryToken?: string | null;
74
+ }): ResolvedSiteIcons | null;
@@ -0,0 +1,96 @@
1
+ const ICON_URL_KEYS = ["favicon32", "appleTouch180", "icon192", "icon512", "maskable512"];
2
+ export const SITE_ICONS_WARNING = "[eldra] could not read the platform\u2019s site icons \u2014 keeping the theme\u2019s own icon files";
3
+ export const READ_TIMEOUT_MS = 1e4;
4
+ export const SHORT_NAME_MAX = 12;
5
+ const HEX_COLOR = /^#[0-9a-f]{6}$/i;
6
+ export async function readSiteIcons(reader, warn = console.warn) {
7
+ const read = reader === null ? { setting: null, cause: null } : await readOrNull(reader);
8
+ if (read.setting === null) {
9
+ warn(read.cause === null ? SITE_ICONS_WARNING : `${SITE_ICONS_WARNING} (${read.cause})`);
10
+ return null;
11
+ }
12
+ return read.setting;
13
+ }
14
+ async function readOrNull(reader) {
15
+ const controller = new AbortController();
16
+ const timer = setTimeout(
17
+ () => controller.abort(new Error(`timed out after ${READ_TIMEOUT_MS}ms`)),
18
+ READ_TIMEOUT_MS
19
+ );
20
+ try {
21
+ const response = await reader.request({
22
+ path: "/site/v1/site-icons",
23
+ signal: controller.signal
24
+ });
25
+ const setting = toSiteIconsSetting(response);
26
+ return {
27
+ setting,
28
+ cause: setting === null ? "the platform published an unusable response" : null
29
+ };
30
+ } catch (error) {
31
+ return { setting: null, cause: error instanceof Error ? error.message : String(error) };
32
+ } finally {
33
+ clearTimeout(timer);
34
+ }
35
+ }
36
+ function toSiteIconsSetting(value) {
37
+ if (typeof value !== "object" || value === null) return null;
38
+ const record = value;
39
+ if (typeof record.revision !== "number" || !Number.isFinite(record.revision)) return null;
40
+ const { iconUrl, backgroundColor, themeColor, shortName } = record;
41
+ if (iconUrl !== null && typeof iconUrl !== "string") return null;
42
+ if (typeof backgroundColor !== "string" || !HEX_COLOR.test(backgroundColor)) return null;
43
+ if (themeColor !== null && (typeof themeColor !== "string" || !HEX_COLOR.test(themeColor))) {
44
+ return null;
45
+ }
46
+ if (shortName !== null && typeof shortName !== "string") return null;
47
+ const icons = toSiteIconUrls(record.icons);
48
+ if (icons === void 0) return null;
49
+ if ((iconUrl === null || iconUrl === "") !== (icons === null)) return null;
50
+ return {
51
+ revision: record.revision,
52
+ iconUrl: iconUrl === "" ? null : iconUrl,
53
+ backgroundColor: backgroundColor.toLowerCase(),
54
+ themeColor: themeColor === null ? null : themeColor.toLowerCase(),
55
+ shortName: shortName === null ? null : truncateRunes(shortName.trim(), SHORT_NAME_MAX) || null,
56
+ icons
57
+ };
58
+ }
59
+ function toSiteIconUrls(value) {
60
+ if (value === null) return null;
61
+ if (typeof value !== "object") return void 0;
62
+ const record = value;
63
+ const urls = {};
64
+ for (const key of ICON_URL_KEYS) {
65
+ const url = record[key];
66
+ if (typeof url !== "string" || !isAbsoluteHttpUrl(url)) return void 0;
67
+ urls[key] = url;
68
+ }
69
+ return urls;
70
+ }
71
+ function isAbsoluteHttpUrl(value) {
72
+ try {
73
+ const { protocol, hostname } = new URL(value);
74
+ if (protocol === "https:") return true;
75
+ return protocol === "http:" && (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]");
76
+ } catch {
77
+ return false;
78
+ }
79
+ }
80
+ export function resolveSiteIcons(setting, defaults) {
81
+ if (setting === null || setting.iconUrl === null || setting.icons === null) return null;
82
+ const siteName = defaults.siteName?.trim() || null;
83
+ const primary = defaults.primaryToken ?? null;
84
+ const name = siteName ?? setting.shortName;
85
+ return {
86
+ iconUrl: setting.iconUrl,
87
+ icons: setting.icons,
88
+ backgroundColor: setting.backgroundColor,
89
+ themeColor: setting.themeColor ?? (primary !== null && HEX_COLOR.test(primary) ? primary : null),
90
+ shortName: setting.shortName ?? (siteName === null ? null : truncateRunes(siteName, 12)),
91
+ name
92
+ };
93
+ }
94
+ function truncateRunes(value, max) {
95
+ return Array.from(value).slice(0, max).join("").trim();
96
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eldrajs/theme-nuxt",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Nuxt module for Eldra themes: wires @eldrajs/vite-plugin-theme, the gateway client, draft overlays and the Studio preview bridge into a Nuxt 4 site.",
5
5
  "keywords": [
6
6
  "cms",
@@ -47,9 +47,9 @@
47
47
  "@nuxt/kit": "^4.0.0",
48
48
  "defu": "^6.1.4",
49
49
  "@eldrajs/sdk": "^0.2.9",
50
- "@eldrajs/theme-core": "^0.1.0",
51
- "@eldrajs/theme-vue": "^0.1.0",
52
- "@eldrajs/vite-plugin-theme": "^0.1.0"
50
+ "@eldrajs/theme-core": "^0.2.0",
51
+ "@eldrajs/theme-vue": "^0.2.0",
52
+ "@eldrajs/vite-plugin-theme": "^0.2.0"
53
53
  },
54
54
  "devDependencies": {
55
55
  "@nuxt/module-builder": "^0.8.4",