@eldrajs/theme-nuxt 0.0.0 → 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.
Files changed (45) hide show
  1. package/CHANGELOG.md +255 -0
  2. package/LICENSE +21 -0
  3. package/README.md +323 -1
  4. package/dist/module.cjs +5 -0
  5. package/dist/module.d.mts +56 -0
  6. package/dist/module.d.ts +56 -0
  7. package/dist/module.json +12 -0
  8. package/dist/module.mjs +320 -0
  9. package/dist/runtime/catalog.d.ts +119 -0
  10. package/dist/runtime/catalog.js +226 -0
  11. package/dist/runtime/commerce.d.ts +68 -0
  12. package/dist/runtime/commerce.js +40 -0
  13. package/dist/runtime/composables/useEldraPage.d.ts +17 -0
  14. package/dist/runtime/composables/useEldraPage.js +229 -0
  15. package/dist/runtime/designTokens.d.ts +59 -0
  16. package/dist/runtime/designTokens.js +55 -0
  17. package/dist/runtime/drafts.d.ts +3 -0
  18. package/dist/runtime/drafts.js +89 -0
  19. package/dist/runtime/links.d.ts +32 -0
  20. package/dist/runtime/links.js +132 -0
  21. package/dist/runtime/locale.d.ts +21 -0
  22. package/dist/runtime/locale.js +9 -0
  23. package/dist/runtime/localeState.d.ts +52 -0
  24. package/dist/runtime/localeState.js +48 -0
  25. package/dist/runtime/locales.d.ts +186 -0
  26. package/dist/runtime/locales.js +109 -0
  27. package/dist/runtime/messages.d.ts +59 -0
  28. package/dist/runtime/messages.js +66 -0
  29. package/dist/runtime/origins.d.ts +18 -0
  30. package/dist/runtime/origins.js +28 -0
  31. package/dist/runtime/plugin.d.ts +3 -0
  32. package/dist/runtime/plugin.js +83 -0
  33. package/dist/runtime/resolveRoute.d.ts +81 -0
  34. package/dist/runtime/resolveRoute.js +166 -0
  35. package/dist/runtime/routePath.d.ts +31 -0
  36. package/dist/runtime/routePath.js +7 -0
  37. package/dist/runtime/siteIconAssets.d.ts +19 -0
  38. package/dist/runtime/siteIconAssets.js +29 -0
  39. package/dist/runtime/siteIcons.d.ts +74 -0
  40. package/dist/runtime/siteIcons.js +96 -0
  41. package/dist/runtime/staticRoutes.d.ts +14 -0
  42. package/dist/runtime/staticRoutes.js +26 -0
  43. package/dist/types.d.mts +7 -0
  44. package/dist/types.d.ts +7 -0
  45. package/package.json +60 -2
@@ -0,0 +1,55 @@
1
+ import { normalizeThemeDesignTokens } from "@eldrajs/theme-core";
2
+ export const DESIGN_TOKENS_WARNING = "[eldra] could not read the platform\u2019s design-token overrides \u2014 serving the theme\u2019s own tokens";
3
+ export const READ_TIMEOUT_MS = 1e4;
4
+ export async function readDesignTokens(reader, warn = console.warn) {
5
+ const read = reader === null ? { tokens: null, cause: null } : await readOrNull(reader);
6
+ if (read.tokens === null) {
7
+ warn(read.cause === null ? DESIGN_TOKENS_WARNING : `${DESIGN_TOKENS_WARNING} (${read.cause})`);
8
+ return null;
9
+ }
10
+ return read.tokens;
11
+ }
12
+ async function readOrNull(reader) {
13
+ const controller = new AbortController();
14
+ const timer = setTimeout(
15
+ () => controller.abort(new Error(`timed out after ${READ_TIMEOUT_MS}ms`)),
16
+ READ_TIMEOUT_MS
17
+ );
18
+ try {
19
+ const response = await reader.request({
20
+ path: "/site/v1/design-tokens",
21
+ signal: controller.signal
22
+ });
23
+ const tokens = toResolvedDesignTokens(response);
24
+ return {
25
+ tokens,
26
+ cause: tokens === null ? "the platform published an unusable response" : null
27
+ };
28
+ } catch (error) {
29
+ return { tokens: null, cause: describe(error) };
30
+ } finally {
31
+ clearTimeout(timer);
32
+ }
33
+ }
34
+ function toResolvedDesignTokens(value) {
35
+ if (typeof value !== "object" || value === null) return null;
36
+ const record = value;
37
+ if (typeof record.revision !== "number" || !Number.isFinite(record.revision)) return null;
38
+ if (typeof record.resolved !== "object" || record.resolved === null) return null;
39
+ try {
40
+ return normalizeThemeDesignTokens(record.resolved);
41
+ } catch {
42
+ return null;
43
+ }
44
+ }
45
+ export function resolveSiteDesignTokens(value) {
46
+ if (value === null || value === void 0 || value === "") return null;
47
+ try {
48
+ return normalizeThemeDesignTokens(value);
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+ function describe(error) {
54
+ return error instanceof Error ? error.message : String(error);
55
+ }
@@ -0,0 +1,3 @@
1
+ import { type EntryDoc } from '@eldrajs/theme-core';
2
+ /** Applies in-memory builder updates to resolved entries without putting draft data in URLs. */
3
+ export declare function overlayPreviewDrafts(page: EntryDoc | null | undefined, drafts: Record<string, Record<string, unknown>>, draftSchemaApiIds?: Readonly<Record<string, string>>): EntryDoc | null;
@@ -0,0 +1,89 @@
1
+ import {
2
+ blockApiIdOf,
3
+ normalizeLayoutDocument
4
+ } from "@eldrajs/theme-core";
5
+ import themeManifest from "virtual:eldra/manifest";
6
+ export function overlayPreviewDrafts(page, drafts, draftSchemaApiIds = {}) {
7
+ if (page == null) return null;
8
+ const pageDraft = drafts[page.id];
9
+ const data = pageDraft === void 0 ? { ...page.data } : { ...page.data, ...pageDraft };
10
+ const resolvedById = new Map(
11
+ (Array.isArray(page.data.blocks) ? page.data.blocks : []).filter((block) => isEntryDoc(block)).map((block) => [block.id, block])
12
+ );
13
+ const layoutEntryIds = layoutBlockEntryIds(data.layout, resolvedById, draftSchemaApiIds);
14
+ if (layoutEntryIds !== null) {
15
+ const reusableEntryIds = reusableProjectionEntryIds(
16
+ page.reusableComponentProjection,
17
+ resolvedById,
18
+ draftSchemaApiIds
19
+ );
20
+ const blocks2 = [.../* @__PURE__ */ new Set([...layoutEntryIds, ...reusableEntryIds])].flatMap((entryId) => {
21
+ const published = resolvedById.get(entryId);
22
+ const draft = drafts[entryId];
23
+ if (published !== void 0) {
24
+ return [{ ...published, ...draft === void 0 ? {} : { data: draft } }];
25
+ }
26
+ const schemaApiId = draftSchemaApiIds[entryId];
27
+ return draft !== void 0 && schemaApiId !== void 0 ? [{ id: entryId, schemaApiId, data: draft }] : [];
28
+ });
29
+ return { ...page, data: { ...data, blocks: blocks2 } };
30
+ }
31
+ const blocks = Array.isArray(data.blocks) ? data.blocks.map((block) => resolvedReference(block, resolvedById)) : data.blocks;
32
+ if (!Array.isArray(blocks)) return { ...page, data };
33
+ return {
34
+ ...page,
35
+ data: {
36
+ ...data,
37
+ blocks: blocks.map((block) => {
38
+ if (!isEntryDoc(block)) return block;
39
+ const draft = drafts[block.id];
40
+ return draft === void 0 ? block : { ...block, data: draft };
41
+ })
42
+ }
43
+ };
44
+ }
45
+ function reusableProjectionEntryIds(value, byId, draftSchemaApiIds) {
46
+ if (typeof value !== "object" || value === null) return [];
47
+ const revisions = value.revisions;
48
+ if (!Array.isArray(revisions)) return [];
49
+ return revisions.flatMap((revision) => {
50
+ if (typeof revision !== "object" || revision === null) return [];
51
+ return layoutBlockEntryIds(revision.document, byId, draftSchemaApiIds) ?? [];
52
+ });
53
+ }
54
+ function buildSlotCatalog() {
55
+ const blocks = themeManifest.blocks ?? [];
56
+ const out = {};
57
+ for (const block of blocks) {
58
+ if (block.apiId && Array.isArray(block.slots)) out[block.apiId] = block.slots;
59
+ }
60
+ return out;
61
+ }
62
+ const THEME_SLOT_CATALOG = buildSlotCatalog();
63
+ function layoutBlockEntryIds(value, byId, draftSchemaApiIds) {
64
+ if (value === void 0) return null;
65
+ const slotContext = {
66
+ slotCatalog: THEME_SLOT_CATALOG,
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
+ }
73
+ };
74
+ try {
75
+ return normalizeLayoutDocument(value, void 0, void 0, slotContext).blockEntryIds;
76
+ } catch {
77
+ return null;
78
+ }
79
+ }
80
+ function resolvedReference(value, byId) {
81
+ if (isEntryDoc(value)) return value;
82
+ if (typeof value !== "object" || value === null) return value;
83
+ const reference = value;
84
+ const id = typeof reference.id === "string" ? reference.id : reference.type === "entry" && typeof reference.value === "string" ? reference.value : void 0;
85
+ return typeof id === "string" ? byId.get(id) ?? value : value;
86
+ }
87
+ function isEntryDoc(value) {
88
+ return typeof value === "object" && value !== null && typeof value.id === "string" && typeof value.data === "object" && value.data !== null;
89
+ }
@@ -0,0 +1,32 @@
1
+ import type { EldraClient, EntryDoc } from '@eldrajs/theme-core';
2
+ import type { LinkTargetInfo } from '@eldrajs/theme-core/links';
3
+ export interface LinkTargetSources {
4
+ /**
5
+ * The CMS schemas an `entry` target may belong to. A link target carries
6
+ * `_type: "entry"` and not its schema, so the schemas worth reading are the
7
+ * ones the site has a route template for — an entry no template serves has no
8
+ * href to resolve to anyway.
9
+ */
10
+ entrySchemaApiIds?: readonly string[];
11
+ /**
12
+ * The site's own pages, which route resolution has already listed. A page's
13
+ * path comes from that list rather than from a lookup, so this only supplies
14
+ * the title a blank label falls back to — no extra read.
15
+ */
16
+ pages?: readonly EntryDoc[];
17
+ }
18
+ /**
19
+ * What the site knows about every object its links point at, keyed
20
+ * `${_type}:${id}` — the key `linkTargetKeys` produces.
21
+ *
22
+ * One batched read per type, never one per link: products, collections and
23
+ * categories by an `id:in:` filter in chunks, entries one read per schema the
24
+ * site routes, each paged to the end rather than to the first hundred rows.
25
+ * The category read is skipped entirely by a reader that does not offer one.
26
+ * Only the ids that were asked for are kept, so a gateway that ignores the
27
+ * filter cannot put its whole catalogue into the page's payload. A read that
28
+ * fails leaves those targets unknown rather than throwing — a link whose target
29
+ * cannot be resolved renders unlinked, exactly as a deleted target does, and one
30
+ * failing catalog read must not take a whole page down.
31
+ */
32
+ export declare function collectLinkTargets(client: EldraClient, keys: readonly string[], locale?: string, sources?: LinkTargetSources): Promise<Map<string, LinkTargetInfo>>;
@@ -0,0 +1,132 @@
1
+ import { buildCategoryTree } from "./catalog.js";
2
+ import { localeQuery } from "./locale.js";
3
+ const CHUNK_SIZE = 50;
4
+ const PAGE_SIZE = 100;
5
+ const MAX_PAGES = 100;
6
+ export async function collectLinkTargets(client, keys, locale, sources = {}) {
7
+ const targets = /* @__PURE__ */ new Map();
8
+ const byType = groupIdsByType(keys);
9
+ const reads = [];
10
+ for (const chunk of chunks(byType.get("product"))) {
11
+ reads.push(
12
+ readInto(
13
+ targets,
14
+ "product",
15
+ chunk,
16
+ async (query) => toPage(await client.catalog.listProducts({ ...query, filter: [idFilter(chunk)] }))
17
+ )
18
+ );
19
+ }
20
+ for (const chunk of chunks(byType.get("collection"))) {
21
+ reads.push(
22
+ readInto(
23
+ targets,
24
+ "collection",
25
+ chunk,
26
+ async (query) => toPage(await client.catalog.listCollections({ ...query, filter: [idFilter(chunk)] }))
27
+ )
28
+ );
29
+ }
30
+ const listCategories = client.catalog.listCategories?.bind(client.catalog);
31
+ const wantedCategories = byType.get("category") ?? [];
32
+ if (listCategories !== void 0 && wantedCategories.length > 0) {
33
+ reads.push(readCategoriesInto(targets, wantedCategories, listCategories, locale));
34
+ }
35
+ if ((byType.get("entry") ?? []).length > 0) {
36
+ for (const schemaApiId of sources.entrySchemaApiIds ?? []) {
37
+ for (const chunk of chunks(byType.get("entry"))) {
38
+ reads.push(
39
+ readInto(targets, "entry", chunk, async (query) => {
40
+ const list = await client.getEntries(schemaApiId, {
41
+ ...query,
42
+ depth: 0,
43
+ filter: [idFilter(chunk)]
44
+ });
45
+ return {
46
+ data: list.data.map((entry) => ({ ...entry.data, id: entry.id, schemaApiId })),
47
+ hasNext: list.meta?.hasNext === true
48
+ };
49
+ })
50
+ );
51
+ }
52
+ }
53
+ }
54
+ for (const id of byType.get("page") ?? []) {
55
+ const page = (sources.pages ?? []).find((candidate) => candidate.id === id);
56
+ if (page !== void 0) targets.set(`page:${id}`, toTargetInfo({ ...page.data, id }));
57
+ }
58
+ await Promise.all(reads);
59
+ return targets;
60
+ async function readInto(into, type, wanted, read) {
61
+ const ids = new Set(wanted);
62
+ try {
63
+ for (let page = 1; page <= MAX_PAGES; page += 1) {
64
+ const result = await read({ ...localeQuery(locale), page, pageSize: PAGE_SIZE });
65
+ for (const doc of result.data) {
66
+ const id = text(doc.id);
67
+ if (id === "" || !ids.has(id) || into.has(`${type}:${id}`)) continue;
68
+ into.set(`${type}:${id}`, toTargetInfo(doc));
69
+ }
70
+ if (!result.hasNext || result.data.length === 0) return;
71
+ }
72
+ } catch {
73
+ }
74
+ }
75
+ }
76
+ function toPage(list) {
77
+ return { data: list.data, hasNext: list.meta?.hasNext === true };
78
+ }
79
+ function idFilter(ids) {
80
+ return `id:in:${ids.join(",")}`;
81
+ }
82
+ function groupIdsByType(keys) {
83
+ const byType = /* @__PURE__ */ new Map();
84
+ for (const key of keys) {
85
+ const separator = key.indexOf(":");
86
+ if (separator <= 0) continue;
87
+ const type = key.slice(0, separator);
88
+ const id = key.slice(separator + 1);
89
+ if (id === "") continue;
90
+ const ids = byType.get(type);
91
+ if (ids === void 0) byType.set(type, [id]);
92
+ else if (!ids.includes(id)) ids.push(id);
93
+ }
94
+ return byType;
95
+ }
96
+ function chunks(ids) {
97
+ const result = [];
98
+ for (let start = 0; start < (ids ?? []).length; start += CHUNK_SIZE) {
99
+ result.push((ids ?? []).slice(start, start + CHUNK_SIZE));
100
+ }
101
+ return result;
102
+ }
103
+ async function readCategoriesInto(into, wanted, listCategories, locale) {
104
+ const ids = new Set(wanted);
105
+ const docs = [];
106
+ try {
107
+ for (let page = 1; page <= MAX_PAGES; page += 1) {
108
+ const list = await listCategories({ ...localeQuery(locale), page, pageSize: PAGE_SIZE });
109
+ docs.push(...list.data);
110
+ if (list.meta?.hasNext !== true || list.data.length === 0) break;
111
+ }
112
+ } catch {
113
+ return;
114
+ }
115
+ for (const node of buildCategoryTree(docs).values()) {
116
+ if (!ids.has(node.id) || into.has(`category:${node.id}`)) continue;
117
+ into.set(`category:${node.id}`, { ...toTargetInfo(node.raw), path: node.path });
118
+ }
119
+ }
120
+ function toTargetInfo(doc) {
121
+ const info = {};
122
+ const slug = text(doc.slug);
123
+ if (slug !== "") info.slug = slug;
124
+ const title = text(doc.title) !== "" ? text(doc.title) : text(doc.name);
125
+ if (title !== "") info.title = title;
126
+ const schemaApiId = text(doc.schemaApiId);
127
+ if (schemaApiId !== "") info.schemaApiId = schemaApiId;
128
+ return info;
129
+ }
130
+ function text(value) {
131
+ return typeof value === "string" ? value : "";
132
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * One rule for every locale this module forwards to the gateway: a blank or
3
+ * whitespace-only locale is no locale at all.
4
+ *
5
+ * A site that configures none still carries `""` — `runtimeConfig.public`
6
+ * serialises an absent option as an empty string, and `ELDRA_LOCALE=` does the
7
+ * same — and an empty `?locale=` is not the same request as no `locale` at all:
8
+ * the gateway parses the parameter it was given and answers 400 for a locale it
9
+ * cannot resolve. So normalise once, at every boundary a locale enters
10
+ * (the composable, route resolution, the catalog reads, the module's prerender
11
+ * pass), and let `undefined` mean "the site's default locale".
12
+ */
13
+ export declare function normalizeLocale(value: string | null | undefined): string | undefined;
14
+ /**
15
+ * The `locale` slice of a gateway query, normalised: an object with the key, or
16
+ * an empty one. Spread it rather than assigning `locale: undefined`, so a
17
+ * request without a locale carries no `locale` key at all.
18
+ */
19
+ export declare function localeQuery(value: string | null | undefined): {
20
+ locale?: string;
21
+ };
@@ -0,0 +1,9 @@
1
+ export function normalizeLocale(value) {
2
+ if (typeof value !== "string") return void 0;
3
+ const trimmed = value.trim();
4
+ return trimmed === "" ? void 0 : trimmed;
5
+ }
6
+ export function localeQuery(value) {
7
+ const locale = normalizeLocale(value);
8
+ return locale === void 0 ? {} : { locale };
9
+ }
@@ -0,0 +1,52 @@
1
+ import type { EldraContext, EldraLocaleState } from '@eldrajs/theme-vue';
2
+ import { type EldraLocaleRouting } from './locales.js';
3
+ /** The slice of Nuxt's router this state reads — the committed route, and one navigation. */
4
+ export interface LocaleRouter {
5
+ /** `fullPath` where the router has one; `path` is the fallback for a stub that does not. */
6
+ currentRoute: {
7
+ value: {
8
+ path: string;
9
+ fullPath?: string;
10
+ };
11
+ };
12
+ push: (path: string) => unknown;
13
+ }
14
+ /**
15
+ * The theme context's locale state for a Nuxt site: the active locale derived from the route it is
16
+ * committed to, and the three path helpers derived from the site's routing.
17
+ *
18
+ * **The router's committed route, not `useRoute()`.** This state is built in a plugin, outside any
19
+ * page, and what a link rendered right now should be prefixed with is the route the app is
20
+ * actually on. `useEldraPage` pins a *page component's* own path for its lifetime for a different
21
+ * reason (see its `createActivePath`), and that pin must not reach the links: a page being
22
+ * navigated away from would keep prefixing for the locale it is leaving.
23
+ *
24
+ * **A preview's locale wins.** Studio drives the content locale through the bridge, and in edit
25
+ * mode that is the locale the author is editing — the path in a preview frame may not name it at
26
+ * all. Falling back to the path is what makes the very first render, before the bridge has said
27
+ * hello, still correct for the artifact's own URL.
28
+ */
29
+ export declare function createNuxtEldraLocaleState(routing: EldraLocaleRouting, preview: EldraContext['preview'], router: () => LocaleRouter | undefined,
30
+ /**
31
+ * Each locale's own name, **resolved once on the server and carried in the payload** — see
32
+ * `localeDisplayName` for why neither side may compute its own. A locale the map does not name
33
+ * (one that only exists client-side) falls through to that function.
34
+ */
35
+ names?: Readonly<Record<string, string>>): EldraLocaleState;
36
+ /**
37
+ * `<link rel="alternate">` for every locale the site serves, plus `x-default` for the unprefixed
38
+ * path — the whole set, on every page, which is what tells a search engine that these URLs are one
39
+ * page in several languages rather than duplicates of each other.
40
+ *
41
+ * Empty on a site with one locale or none: a single-locale site has no alternates, and emitting
42
+ * one that points at itself says nothing.
43
+ *
44
+ * The hrefs are **paths**, not absolute URLs. A prerendered artifact does not know the origin it
45
+ * will be served from — the host that generated it is a build machine — and a baked-in wrong
46
+ * origin would be worse than a relative one.
47
+ */
48
+ export declare function localeAlternates(path: string, routing: EldraLocaleRouting): Array<{
49
+ rel: 'alternate';
50
+ hreflang: string;
51
+ href: string;
52
+ }>;
@@ -0,0 +1,48 @@
1
+ import { reactive } from "vue";
2
+ import { normalizeLocale } from "./locale.js";
3
+ import {
4
+ activeLocaleForPath,
5
+ localeDisplayName,
6
+ localeHref,
7
+ localePathFor
8
+ } from "./locales.js";
9
+ import { canonicalRoutePath } from "./routePath.js";
10
+ export function createNuxtEldraLocaleState(routing, preview, router, names = {}) {
11
+ const currentPath = () => canonicalRoutePath(router()?.currentRoute.value.path ?? "/");
12
+ const currentHref = () => {
13
+ const route = router()?.currentRoute.value;
14
+ const full = route?.fullPath ?? route?.path ?? "/";
15
+ const cut = full.search(/[?#]/);
16
+ return cut === -1 ? canonicalRoutePath(full) : canonicalRoutePath(full.slice(0, cut)) + full.slice(cut);
17
+ };
18
+ const active = () => normalizeLocale(preview.locale) ?? activeLocaleForPath(currentPath(), routing) ?? null;
19
+ return reactive({
20
+ get active() {
21
+ return active();
22
+ },
23
+ defaultLocale: routing.default ?? null,
24
+ supported: routing.supported,
25
+ name: (locale) => names[locale] ?? localeDisplayName(locale),
26
+ path: (href) => localeHref(href, active(), routing),
27
+ switchPath: (locale) => localePathFor(currentHref(), locale, routing),
28
+ select: (locale) => {
29
+ void router()?.push(localePathFor(currentHref(), locale, routing));
30
+ }
31
+ });
32
+ }
33
+ export function localeAlternates(path, routing) {
34
+ if (routing.supported.length < 2) return [];
35
+ const alternates = routing.supported.map((locale) => ({
36
+ rel: "alternate",
37
+ hreflang: locale,
38
+ href: localePathFor(path, locale, routing)
39
+ }));
40
+ return [
41
+ ...alternates,
42
+ {
43
+ rel: "alternate",
44
+ hreflang: "x-default",
45
+ href: localePathFor(path, void 0, routing)
46
+ }
47
+ ];
48
+ }
@@ -0,0 +1,186 @@
1
+ import type { EldraFeatureClient, EldraOrganizationLocales } from '@eldrajs/sdk';
2
+ /**
3
+ * Which content locales the site serves, as it reaches a theme on
4
+ * `runtimeConfig.public.eldra.locales`: `{ default, supported }`, or `null`.
5
+ *
6
+ * Published as `@eldrajs/theme-nuxt/locales` beside `@eldrajs/theme-nuxt/commerce`, so a theme
7
+ * reading that key types it from here instead of hand-writing the record — it is the public
8
+ * contract of a public runtime-config key. (Its own subpath rather than the package root:
9
+ * `nuxt-module-build` generates the root's `.d.mts` itself, and that file carries the module and
10
+ * `ModuleOptions` only.)
11
+ *
12
+ * It is the gateway's own organisation `locales` record unchanged, so the shape is declared
13
+ * **once** — in `@eldrajs/sdk`, which is where the read comes from — and aliased here under the
14
+ * name the runtime config uses.
15
+ *
16
+ * Read **once, at build**, from the organisation the site is deployed for
17
+ * (`@eldrajs/sdk`'s `features.getLocales()`), because the prerender pass has to know every locale
18
+ * before it can list a single path: which routes exist *is* this answer, and a value fetched in
19
+ * the browser would arrive long after the artifact was written.
20
+ *
21
+ * `null` is a real answer, not a failure: an organisation that has configured no locales serves
22
+ * one unprefixed site with no language switcher, which is exactly what a theme did before locales
23
+ * existed.
24
+ */
25
+ export type StoreLocales = EldraOrganizationLocales;
26
+ /**
27
+ * The slice of an `@eldrajs/sdk` client this read needs — a whole `EldraClient` satisfies it.
28
+ * Narrow on purpose: it is what lets the module's own tests hand `readStoreLocales` a client that
29
+ * answers, omits or throws with no gateway anywhere near them.
30
+ */
31
+ export interface StoreLocalesReader {
32
+ features: Pick<EldraFeatureClient, 'getLocales'>;
33
+ }
34
+ /**
35
+ * The one line a build prints when it could not learn the organisation's locales. It names the
36
+ * cause, because the outcome — one unprefixed site, no switcher — is indistinguishable from the
37
+ * ordinary state of an organisation that has configured none, and only one of the two is
38
+ * something somebody can fix.
39
+ *
40
+ * There is deliberately **no** warning for the ordinary state. `commerce.ts` warns for its own
41
+ * absent value because a page then renders prices with no symbol; nothing is lost here, so a line
42
+ * every single-locale build printed would only teach its reader to ignore build warnings.
43
+ */
44
+ export declare const LOCALES_READ_FAILED_WARNING = "[eldra] could not read the organisation\u2019s content locales \u2014 serving one unprefixed site";
45
+ /**
46
+ * How long the build waits for the answer. A bound rather than none, for the same reason
47
+ * `commerce.ts` has one: this read is optional, and a locale list nobody can fetch must not be the
48
+ * reason a deploy never finishes.
49
+ *
50
+ * Exported so the test that proves the bound can assert the value rather than restate it.
51
+ */
52
+ export declare const READ_TIMEOUT_MS = 10000;
53
+ /**
54
+ * The organisation's content locales for `runtimeConfig.public.eldra`, or `null`.
55
+ *
56
+ * Fail-soft by construction: a gateway that cannot be reached, a read that times out, a record the
57
+ * SDK refuses and an organisation with no locales at all all end the same way — `null`, and a
58
+ * build that finishes serving one unprefixed site. Only the first three print the line above.
59
+ *
60
+ * `reader` is `null` for a site built without gateway credentials (a scaffolded theme nobody has
61
+ * connected yet, a CI build with no secrets). Same outcome, no request, and no warning: that build
62
+ * has already been told it has no gateway.
63
+ */
64
+ export declare function readStoreLocales(reader: StoreLocalesReader | null, warn?: (message: string) => void): Promise<StoreLocales | null>;
65
+ /**
66
+ * Accepts only a whole answer, and re-checks what the SDK already checked.
67
+ *
68
+ * Not redundant: this same function is what reads the value **back** out of the runtime config in
69
+ * the browser (`resolveStoreLocales`), where it arrives as whatever Nitro serialised — `''` for an
70
+ * absent one, and whatever a theme put there by hand if it wrote the key itself. One validator for
71
+ * both directions means a locale that reaches route resolution is always a usable tag.
72
+ */
73
+ export declare function toStoreLocales(value: unknown): StoreLocales | null;
74
+ /**
75
+ * The locales the **running** site serves, read off `runtimeConfig.public.eldra.locales`.
76
+ *
77
+ * `runtimeConfig.public` serialises an absent object as `''`, exactly as it does for `commerce`
78
+ * and `locale`, so the key is always there and is not always a record.
79
+ */
80
+ export declare function resolveStoreLocales(value: unknown): StoreLocales | null;
81
+ /**
82
+ * How one site's paths and locales line up, resolved once from the organisation's locales and the
83
+ * theme's own `eldra.locale` / `ELDRA_LOCALE`.
84
+ *
85
+ * Four fields rather than one list, because three different questions are asked of it and they
86
+ * have three different answers for the same path:
87
+ *
88
+ * * which locale a **URL with no prefix** is (`default`);
89
+ * * which locales a URL may be **prefixed** with (`prefixed` — never the default: the default
90
+ * lives at `/` only, and `/<default>/...` is not generated and resolves as unknown);
91
+ * * and which locale a **gateway read** carries (`override`, for an unprefixed path — see
92
+ * `localeForPath`).
93
+ */
94
+ export interface EldraLocaleRouting {
95
+ /** The locale served unprefixed. `undefined` when the site configures none. */
96
+ default: string | undefined;
97
+ /** Every locale the site serves, `default` first. Empty when it configures none. */
98
+ supported: readonly string[];
99
+ /** The locales that live under a path prefix: `supported` without `default`. */
100
+ prefixed: readonly string[];
101
+ /**
102
+ * What `eldra.locale` / `ELDRA_LOCALE` asked for, normalised — the locale every gateway read
103
+ * carried before prefixes existed, and still the locale an unprefixed read carries.
104
+ */
105
+ override: string | undefined;
106
+ }
107
+ /**
108
+ * Resolve the routing above.
109
+ *
110
+ * `eldra.locale` keeps exactly the meaning it had: an override of the **default** locale for a
111
+ * single-locale build. So when it names one of the organisation's supported locales, that locale
112
+ * is the one served at `/` and the others are the prefixed ones; when it names something else —
113
+ * or the organisation publishes no locales at all — nothing about the URLs changes and the value
114
+ * is still forwarded on every read, which is what a site deployed against one locale of a
115
+ * multi-locale organisation has always done.
116
+ *
117
+ * The match is case-insensitive and the **stored spelling wins**: `ELDRA_LOCALE=IS-is` selects
118
+ * `is-IS`, so every path, `lang` attribute and `?locale=` on the site uses the one spelling the
119
+ * organisation configured.
120
+ */
121
+ export declare function resolveLocaleRouting(locales: StoreLocales | null, override?: string | null): EldraLocaleRouting;
122
+ /**
123
+ * The locale `path`'s first segment names, or `undefined` when it names none.
124
+ *
125
+ * Matched case-insensitively against the **prefixed** locales only, and answered in the stored
126
+ * spelling: a visitor typing `/IS-is/about` lands on the same content as `/is-IS/about`, while
127
+ * `/<default>/about` matches nothing and resolves as the unknown path it is.
128
+ */
129
+ export declare function localePrefixOf(path: string, routing: EldraLocaleRouting): string | undefined;
130
+ /** `path` with its locale prefix removed, if it has one. Always starts with `/`. */
131
+ export declare function stripLocalePrefix(path: string, routing: EldraLocaleRouting): string;
132
+ /**
133
+ * The locale a **gateway read** for `path` must carry, or `undefined` for "the site's default".
134
+ *
135
+ * A prefixed path reads its own locale; an unprefixed one reads whatever `eldra.locale` asked for,
136
+ * which is `undefined` on the overwhelming majority of sites. Deliberately **not** the resolved
137
+ * default locale: a site that configured no override has never sent one, the gateway's own default
138
+ * is the same document, and sending it would change every request on every existing site for no
139
+ * change in the answer.
140
+ */
141
+ export declare function localeForPath(path: string, routing: EldraLocaleRouting): string | undefined;
142
+ /**
143
+ * The **active content locale** on `path` — what `<html lang>`, the language switcher, the
144
+ * message-set lookup and every `Intl` format use. `undefined` only on a site that configures none.
145
+ */
146
+ export declare function activeLocaleForPath(path: string, routing: EldraLocaleRouting): string | undefined;
147
+ /**
148
+ * `path` as it is spelled under `locale`: unprefixed for the default locale, prefixed for every
149
+ * other one. Any prefix it already carries is replaced, so this is also how a switcher turns the
150
+ * page a visitor is on into the same page in another language.
151
+ *
152
+ * A query and a fragment ride along untouched, which is what makes that switch keep the page the
153
+ * visitor was actually looking at: `/is-IS/search?q=mug` is their search, and landing on
154
+ * `/search` after choosing English would have thrown the query away.
155
+ */
156
+ export declare function localePathFor(path: string, locale: string | null | undefined, routing: EldraLocaleRouting): string;
157
+ /**
158
+ * One same-site href under `locale`, leaving everything else exactly as it was.
159
+ *
160
+ * **Idempotent**, and that is load-bearing rather than defensive: a destination can pass through
161
+ * more than one of the places that prefix (a resolved `link` field handed to a router link, say),
162
+ * and a second prefix would produce `/is-IS/is-IS/products/x` — a path nothing on the site
163
+ * answers. An href whose first segment is already one of the site's locales is returned unchanged.
164
+ *
165
+ * Untouched: anything that is not a path (`https://…`, `mailto:`, `#main`, a protocol-relative
166
+ * `//host/path`), and every path on a site with no prefixed locales. The query and fragment ride
167
+ * along unparsed — only the path part is rewritten.
168
+ */
169
+ export declare function localeHref(href: string, locale: string | null | undefined, routing: EldraLocaleRouting): string;
170
+ /**
171
+ * One locale's name **in that locale** — "íslenska (Ísland)", "American English" — for a language
172
+ * switcher's option label: a visitor hunting for their language is hunting for the word they write
173
+ * it with.
174
+ *
175
+ * The tag itself is the fallback twice over: for a runtime that has no name for it (`of()` answers
176
+ * the tag back), and for one that refuses the tag outright (`Intl` throws `RangeError` for a
177
+ * malformed one, and callers run this inside a render).
178
+ *
179
+ * **The answer is ICU data, and a renderer and a browser do not always have the same of it.** Node
180
+ * answers "íslenska (Ísland)" for `is-IS` where a reduced-ICU browser build answers "Icelandic
181
+ * (Iceland)" — so a switcher that rendered this during SSR and recomputed it on the client would
182
+ * hydrate into a mismatch and repaint, on every page carrying a footer. That is why the runtime
183
+ * plugin resolves these **once, on the server**, and carries them in the payload (`useState`)
184
+ * rather than letting each side compute its own.
185
+ */
186
+ export declare function localeDisplayName(locale: string): string;