@eldrajs/theme-nuxt 0.0.0-stage → 0.1.1

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 (41) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/LICENSE +21 -0
  3. package/README.md +324 -2
  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 +265 -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 +83 -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/staticRoutes.d.ts +14 -0
  38. package/dist/runtime/staticRoutes.js +26 -0
  39. package/dist/types.d.mts +7 -0
  40. package/dist/types.d.ts +7 -0
  41. package/package.json +66 -3
@@ -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;
@@ -0,0 +1,109 @@
1
+ import { normalizeLocale } from "./locale.js";
2
+ export const LOCALES_READ_FAILED_WARNING = "[eldra] could not read the organisation\u2019s content locales \u2014 serving one unprefixed site";
3
+ export const READ_TIMEOUT_MS = 1e4;
4
+ export async function readStoreLocales(reader, warn = console.warn) {
5
+ if (reader === null) return null;
6
+ const controller = new AbortController();
7
+ const timer = setTimeout(
8
+ () => controller.abort(new Error(`timed out after ${READ_TIMEOUT_MS}ms`)),
9
+ READ_TIMEOUT_MS
10
+ );
11
+ try {
12
+ return toStoreLocales(
13
+ await reader.features.getLocales(void 0, { signal: controller.signal })
14
+ );
15
+ } catch (error) {
16
+ warn(`${LOCALES_READ_FAILED_WARNING} (${describe(error)})`);
17
+ return null;
18
+ } finally {
19
+ clearTimeout(timer);
20
+ }
21
+ }
22
+ export function toStoreLocales(value) {
23
+ if (value === null || typeof value !== "object") return null;
24
+ const record = value;
25
+ const defaultLocale = normalizeLocale(typeof record.default === "string" ? record.default : null);
26
+ if (defaultLocale === void 0) return null;
27
+ if (!Array.isArray(record.supported)) return null;
28
+ const supported = [defaultLocale];
29
+ for (const entry of record.supported) {
30
+ const locale = normalizeLocale(typeof entry === "string" ? entry : null);
31
+ if (locale === void 0) return null;
32
+ if (!supported.includes(locale)) supported.push(locale);
33
+ }
34
+ return { default: defaultLocale, supported };
35
+ }
36
+ export function resolveStoreLocales(value) {
37
+ return toStoreLocales(value);
38
+ }
39
+ export function resolveLocaleRouting(locales, override) {
40
+ const configured = normalizeLocale(override);
41
+ if (locales === null) {
42
+ return {
43
+ default: configured,
44
+ supported: configured === void 0 ? [] : [configured],
45
+ prefixed: [],
46
+ override: configured
47
+ };
48
+ }
49
+ const matched = matchLocale(configured, locales.supported);
50
+ const defaultLocale = matched ?? locales.default;
51
+ return {
52
+ default: defaultLocale,
53
+ supported: [defaultLocale, ...locales.supported.filter((locale) => locale !== defaultLocale)],
54
+ prefixed: locales.supported.filter((locale) => locale !== defaultLocale),
55
+ override: configured
56
+ };
57
+ }
58
+ export function localePrefixOf(path, routing) {
59
+ const segment = path.replace(/^\/+/, "").split("/", 1)[0] ?? "";
60
+ return segment === "" ? void 0 : matchLocale(segment, routing.prefixed);
61
+ }
62
+ export function stripLocalePrefix(path, routing) {
63
+ const locale = localePrefixOf(path, routing);
64
+ if (locale === void 0) return path;
65
+ const rest = path.replace(/^\/+/, "").slice(locale.length);
66
+ return rest === "" || rest === "/" ? "/" : rest.startsWith("/") ? rest : `/${rest}`;
67
+ }
68
+ export function localeForPath(path, routing) {
69
+ return localePrefixOf(path, routing) ?? routing.override;
70
+ }
71
+ export function activeLocaleForPath(path, routing) {
72
+ return localePrefixOf(path, routing) ?? routing.default;
73
+ }
74
+ export function localePathFor(path, locale, routing) {
75
+ const [bare, rest] = splitHref(path);
76
+ const base = stripLocalePrefix(bare, routing);
77
+ const target = matchLocale(locale, routing.prefixed);
78
+ if (target === void 0) return `${base}${rest}`;
79
+ return base === "/" ? `/${target}${rest}` : `/${target}${base}${rest}`;
80
+ }
81
+ export function localeHref(href, locale, routing) {
82
+ const target = matchLocale(locale, routing.prefixed);
83
+ if (target === void 0) return href;
84
+ if (!href.startsWith("/") || href.startsWith("//")) return href;
85
+ const [path, rest] = splitHref(href);
86
+ const segment = path.replace(/^\/+/, "").split("/", 1)[0] ?? "";
87
+ if (segment !== "" && matchLocale(segment, routing.supported) !== void 0) return href;
88
+ return path === "/" ? `/${target}${rest}` : `/${target}${path}${rest}`;
89
+ }
90
+ export function localeDisplayName(locale) {
91
+ try {
92
+ return new Intl.DisplayNames([locale], { type: "language" }).of(locale) ?? locale;
93
+ } catch {
94
+ return locale;
95
+ }
96
+ }
97
+ function splitHref(href) {
98
+ const cut = href.search(/[?#]/);
99
+ return cut === -1 ? [href, ""] : [href.slice(0, cut), href.slice(cut)];
100
+ }
101
+ function matchLocale(candidate, locales) {
102
+ const wanted = normalizeLocale(candidate);
103
+ if (wanted === void 0) return void 0;
104
+ const lower = wanted.toLowerCase();
105
+ return locales.find((locale) => locale.toLowerCase() === lower);
106
+ }
107
+ function describe(error) {
108
+ return error instanceof Error ? error.message : String(error);
109
+ }
@@ -0,0 +1,59 @@
1
+ import type { EldraClient } from '@eldrajs/sdk';
2
+ import { type ThemeMessages } from '@eldrajs/theme-core/i18n';
3
+ import type { StoreLocales } from './locales.js';
4
+ /**
5
+ * What `virtual:eldra/messages` reaches a theme as, on `context.messages`: the manifest's own
6
+ * message catalogue (or the fallback catalogue, for a theme with no `i18n/` directory), merged
7
+ * with the platform's theme-message overrides and resolved over the organisation's locales — see
8
+ * `resolveSiteMessages` below, the one place this module calls the theme-core helper.
9
+ *
10
+ * Re-exported from `@eldrajs/theme-core/i18n` under the name this package's own reads use, the
11
+ * same way `./commerce.ts`/`./locales.ts` alias the SDK's organisation types.
12
+ */
13
+ export type { ThemeMessages };
14
+ /**
15
+ * The slice of an `@eldrajs/sdk` client this read needs — a whole `EldraClient` satisfies it.
16
+ * Narrow on purpose, like `StoreCommerceReader`/`StoreLocalesReader`: it is what lets this read's
17
+ * own tests hand it a client that answers, omits or throws with no gateway anywhere near them.
18
+ *
19
+ * `request` rather than a `features.*` method: the public route this reads
20
+ * (`GET /site/v1/theme-messages`) is a **site**-module read, not an organisation-feature one, so
21
+ * there is no typed `EldraFeatureClient` method for it to call through — the client's own generic
22
+ * escape hatch carries the same base URL, org header and retry policy every other read here uses.
23
+ */
24
+ export interface ThemeMessagesReader {
25
+ request: EldraClient['request'];
26
+ }
27
+ /**
28
+ * The one line a build prints when it could not read the platform's theme-message overrides. Said
29
+ * unconditionally whenever the read comes back `null` — absent gateway credentials included — the
30
+ * same discipline `commerce.ts`'s `NO_CURRENCY_WARNING` follows and for the same reason: "serving
31
+ * the theme's own defaults" is the real, useful thing to know happened, not a fault to hide.
32
+ */
33
+ export declare const THEME_MESSAGES_WARNING = "[eldra] could not read the platform\u2019s theme-message overrides \u2014 serving the theme\u2019s own defaults";
34
+ /**
35
+ * How long the build waits for the answer. A bound rather than none, for the same reason
36
+ * `commerce.ts`/`locales.ts` have one: this read is optional, and a theme-message override nobody
37
+ * can fetch must not be the reason a deploy never finishes.
38
+ *
39
+ * Exported so the test that proves the bound can assert the value rather than restate it.
40
+ */
41
+ export declare const READ_TIMEOUT_MS = 10000;
42
+ /**
43
+ * The platform's theme-message overrides for the build-time merge, or `null`.
44
+ *
45
+ * Fail-soft by construction, exactly like `readStoreCommerce`: a gateway that cannot be reached, a
46
+ * read that times out, a response that is not the shape the gateway documents, and a site built
47
+ * with no gateway credentials at all end the same way — `null` and **one** warning — so a theme
48
+ * keeps deploying while serving its own default texts.
49
+ */
50
+ export declare function readThemeMessages(reader: ThemeMessagesReader | null, warn?: (message: string) => void): Promise<ThemeMessages | null>;
51
+ /**
52
+ * Calls `@eldrajs/theme-core/i18n`'s `resolveMessageCatalogue` with the build-time inputs this
53
+ * module's `resolveMessages` option needs: the theme's own manifest messages, the platform's
54
+ * overrides (or `null`), and the organisation's locales — falling back to the theme's own
55
+ * locales/default locale when the organisation's are unknown (no gateway, or the locales read
56
+ * itself failed), which is what lets a **credential-less build** still produce a full key set for
57
+ * every locale from the manifest alone.
58
+ */
59
+ export declare function resolveSiteMessages(themeMessages: ThemeMessages, platform: ThemeMessages | null, locales: StoreLocales | null): ThemeMessages;