@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,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;
@@ -0,0 +1,66 @@
1
+ import {
2
+ isForbiddenLocaleTag,
3
+ resolveMessageCatalogue
4
+ } from "@eldrajs/theme-core/i18n";
5
+ export const THEME_MESSAGES_WARNING = "[eldra] could not read the platform\u2019s theme-message overrides \u2014 serving the theme\u2019s own defaults";
6
+ export const READ_TIMEOUT_MS = 1e4;
7
+ export async function readThemeMessages(reader, warn = console.warn) {
8
+ const read = reader === null ? { messages: null, cause: null } : await readOrNull(reader);
9
+ if (read.messages === null) {
10
+ warn(
11
+ read.cause === null ? THEME_MESSAGES_WARNING : `${THEME_MESSAGES_WARNING} (${read.cause})`
12
+ );
13
+ return null;
14
+ }
15
+ return read.messages;
16
+ }
17
+ async function readOrNull(reader) {
18
+ const controller = new AbortController();
19
+ const timer = setTimeout(
20
+ () => controller.abort(new Error(`timed out after ${READ_TIMEOUT_MS}ms`)),
21
+ READ_TIMEOUT_MS
22
+ );
23
+ try {
24
+ const response = await reader.request({
25
+ path: "/site/v1/theme-messages",
26
+ signal: controller.signal
27
+ });
28
+ const messages = toThemeMessages(response);
29
+ return {
30
+ messages,
31
+ cause: messages === null ? "the platform published an unusable response" : null
32
+ };
33
+ } catch (error) {
34
+ return { messages: null, cause: describe(error) };
35
+ } finally {
36
+ clearTimeout(timer);
37
+ }
38
+ }
39
+ function toThemeMessages(value) {
40
+ if (typeof value !== "object" || value === null) return null;
41
+ const record = value;
42
+ if (typeof record.defaultLocale !== "string" || record.defaultLocale === "") return null;
43
+ if (typeof record.locales !== "object" || record.locales === null) return null;
44
+ const locales = {};
45
+ for (const tag of Object.keys(record.locales)) {
46
+ if (isForbiddenLocaleTag(tag)) return null;
47
+ const entry = record.locales[tag];
48
+ if (typeof entry !== "object" || entry === null) return null;
49
+ const flat = {};
50
+ for (const key of Object.keys(entry)) {
51
+ const text = entry[key];
52
+ if (typeof text !== "string") return null;
53
+ flat[key] = text;
54
+ }
55
+ locales[tag] = flat;
56
+ }
57
+ return { defaultLocale: record.defaultLocale, locales };
58
+ }
59
+ export function resolveSiteMessages(themeMessages, platform, locales) {
60
+ const orgLocales = locales?.supported ?? Object.keys(themeMessages.locales);
61
+ const orgDefaultLocale = locales?.default ?? themeMessages.defaultLocale;
62
+ return resolveMessageCatalogue(themeMessages, platform, orgLocales, orgDefaultLocale);
63
+ }
64
+ function describe(error) {
65
+ return error instanceof Error ? error.message : String(error);
66
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Converts configured CSP-style origins to the exact parent origin required by
3
+ * the bridge contract. Wildcards are used only to authorize document.referrer;
4
+ * createThemeBridge still receives an exact URL origin and never posts to `*`.
5
+ */
6
+ export declare function resolveBridgeOrigins(configured: string[], referrer: string): string[];
7
+ /**
8
+ * Whether this document could be a Studio preview frame **at all** — framed, by an origin the
9
+ * site's `studioOrigins` allow.
10
+ *
11
+ * `EldraContext.preview.active` is the answer once the bridge has said hello, and everything that
12
+ * reacts to editing waits for it. This is the question one tick earlier, and it exists because one
13
+ * decision cannot wait: a static build answers an unknown route as "not found" straight out of the
14
+ * build manifest, and it must never do that to Studio, where the route being previewed is a draft
15
+ * the build has never seen. Framed by anything else — another site, a stranger's page — the bridge
16
+ * will never activate, so the ordinary static answer is the right one.
17
+ */
18
+ export declare function isStudioPreviewFrame(configured: string[]): boolean;
@@ -0,0 +1,28 @@
1
+ export function resolveBridgeOrigins(configured, referrer) {
2
+ let referrerOrigin = null;
3
+ try {
4
+ referrerOrigin = referrer === "" ? null : new URL(referrer).origin;
5
+ } catch {
6
+ referrerOrigin = null;
7
+ }
8
+ const exact = configured.filter((origin) => !origin.includes("*"));
9
+ if (referrerOrigin === null) return exact;
10
+ if (configured.some((pattern) => originMatches(pattern, referrerOrigin))) {
11
+ return [.../* @__PURE__ */ new Set([...exact, referrerOrigin])];
12
+ }
13
+ return exact;
14
+ }
15
+ function originMatches(pattern, origin) {
16
+ if (!pattern.includes("*")) return pattern === origin;
17
+ const match = /^(https:|http:)\/\/\*\.([^/:]+)(?::(\d+))?$/.exec(pattern);
18
+ if (match === null) return false;
19
+ const candidate = new URL(origin);
20
+ const expectedPort = match[3] ?? "";
21
+ const suffix = match[2];
22
+ return candidate.protocol === match[1] && candidate.port === expectedPort && candidate.hostname.endsWith(`.${suffix}`) && candidate.hostname !== suffix;
23
+ }
24
+ export function isStudioPreviewFrame(configured) {
25
+ if (!import.meta.client) return false;
26
+ if (window.parent === window) return false;
27
+ return resolveBridgeOrigins(configured, document.referrer).length > 0;
28
+ }
@@ -0,0 +1,3 @@
1
+ import 'virtual:eldra/tokens.css';
2
+ declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
3
+ export default _default;
@@ -0,0 +1,83 @@
1
+ import {
2
+ createEldraClient,
3
+ normalizeThemeDesignTokens
4
+ } from "@eldrajs/theme-core";
5
+ import {
6
+ ELDRA_KEY,
7
+ createEldraLinkState,
8
+ createEldraPreviewState,
9
+ registerBlockFields,
10
+ startEldraPreview
11
+ } from "@eldrajs/theme-vue";
12
+ import { defineNuxtPlugin, useHead, useRuntimeConfig, useState } from "nuxt/app";
13
+ import { reactive } from "vue";
14
+ import blockFields from "virtual:eldra/block-fields";
15
+ import manifest from "virtual:eldra/manifest";
16
+ import messages from "virtual:eldra/messages";
17
+ import "virtual:eldra/tokens.css";
18
+ import { resolveSiteDesignTokens } from "./designTokens.js";
19
+ import { createNuxtEldraLocaleState, localeAlternates } from "./localeState.js";
20
+ import { localeDisplayName, resolveLocaleRouting, resolveStoreLocales } from "./locales.js";
21
+ import { resolveBridgeOrigins } from "./origins.js";
22
+ import { canonicalRoutePath } from "./routePath.js";
23
+ import { primePrerenderedRoutes } from "./staticRoutes.js";
24
+ export default defineNuxtPlugin({
25
+ name: "eldra-theme",
26
+ setup(nuxtApp) {
27
+ registerBlockFields(blockFields, manifest.theme.id);
28
+ const cfg = useRuntimeConfig().public.eldra;
29
+ const storeLocales = resolveStoreLocales(cfg.locales);
30
+ const routing = resolveLocaleRouting(storeLocales, cfg.locale);
31
+ const client = createEldraClient({
32
+ gatewayUrl: cfg.gatewayUrl,
33
+ orgId: cfg.orgId,
34
+ stega: true,
35
+ retry: cfg.retry ?? void 0,
36
+ defaultLocale: storeLocales?.default ?? routing.default ?? null
37
+ });
38
+ const preview = createEldraPreviewState();
39
+ const router = () => nuxtApp.$router;
40
+ const localeNames = useState(
41
+ "eldra-locale-names",
42
+ () => Object.fromEntries(routing.supported.map((locale) => [locale, localeDisplayName(locale)]))
43
+ );
44
+ const context = {
45
+ client,
46
+ // The platform's resolved design-token catalog, when the build's own platform read settled
47
+ // with one (`@eldrajs/theme-nuxt`'s module, `readDesignTokens`/`resolveTokens` over
48
+ // `@eldrajs/theme-core`'s `normalizeThemeDesignTokens`) — falling back to the manifest's own
49
+ // `tokens.json`, normalized exactly as a credential-less build already does, when it did not.
50
+ designTokens: reactive(
51
+ resolveSiteDesignTokens(cfg.designTokens) ?? normalizeThemeDesignTokens(manifest.tokens)
52
+ ),
53
+ // Already the merged/resolved catalogue — @eldrajs/theme-nuxt's module (`resolveMessages`,
54
+ // over `@eldrajs/theme-core/i18n`) built this build's content; nothing left to normalize.
55
+ messages: reactive(messages),
56
+ links: createEldraLinkState(),
57
+ locales: createNuxtEldraLocaleState(routing, preview, router, localeNames.value),
58
+ preview
59
+ };
60
+ nuxtApp.vueApp.provide(ELDRA_KEY, context);
61
+ useHead(() => ({
62
+ htmlAttrs: { lang: context.locales?.active ?? void 0 },
63
+ link: localeAlternates(canonicalRoutePath(router()?.currentRoute.value.path ?? "/"), routing)
64
+ }));
65
+ if (import.meta.client) primePrerenderedRoutes();
66
+ if (import.meta.client && window.parent !== window) {
67
+ const allowedOrigins = resolveBridgeOrigins(cfg.studioOrigins, document.referrer);
68
+ if (allowedOrigins.length === 0) {
69
+ console.warn("[eldra] preview disabled: parent origin is not an allowed Studio origin");
70
+ } else {
71
+ nuxtApp.hook("app:mounted", () => {
72
+ const runtime = startEldraPreview(context, {
73
+ allowedOrigins,
74
+ onNavigate: (path) => {
75
+ void nuxtApp.$router.push(path);
76
+ }
77
+ });
78
+ window.addEventListener("pagehide", () => runtime.destroy(), { once: true });
79
+ });
80
+ }
81
+ }
82
+ }
83
+ });
@@ -0,0 +1,81 @@
1
+ import { type EldraClient, type EntryDoc } from '@eldrajs/theme-core';
2
+ import { type LinkTargetInfo } from '@eldrajs/theme-core/links';
3
+ import { type CatalogRouteRef } from './catalog.js';
4
+ export interface ResolvedEldraRoute {
5
+ page: EntryDoc | null;
6
+ template: EntryDoc | null;
7
+ entry: EntryDoc | null;
8
+ /** Set only for a catalog-backed route template: which catalog object the
9
+ * template is rendering, so a storefront surface can set its route context
10
+ * without re-parsing the path. */
11
+ catalog: CatalogRouteRef | null;
12
+ /**
13
+ * What `resolveLink` needs to turn this document's `link` values into hrefs.
14
+ * Filled from the page and route-template lists this resolution already
15
+ * reads, plus one batched read per target type — and filled *here*, under the
16
+ * page's own async-data key, so a `nuxi generate` build bakes it into the
17
+ * payload and a prerendered page resolves every href with no client request.
18
+ */
19
+ links: {
20
+ pages: EntryDoc[];
21
+ templates: EntryDoc[];
22
+ targets: Map<string, LinkTargetInfo>;
23
+ };
24
+ /**
25
+ * Why this resolution carries no document — set **only** when the reason is a failure, never
26
+ * for a route that honestly has no page (no match, or a 404 from the gateway).
27
+ *
28
+ * It travels with the resolution because the resolution is *shared*. `useAsyncData` keeps one
29
+ * entry per key and the **first** registration's handler is the only one that ever runs
30
+ * (`nuxt/dist/app/composables/asyncData.js`: a later call with the same key reuses the existing
31
+ * entry), so a second `useEldraPage()` for the same route — a plugin's, beside the page
32
+ * component's — is handed this value and nothing else. A failure kept in the composable's own
33
+ * `ref` therefore reached only whichever call happened to register first, and every other
34
+ * consumer saw an empty route, which is indistinguishable from "there is no such page". That is
35
+ * how a transient gateway failure was rendered — and, under `nuxi generate`, written to disk —
36
+ * as the not-found shell over a collection that exists.
37
+ */
38
+ error?: string;
39
+ }
40
+ export declare const EMPTY_ELDRA_ROUTE: ResolvedEldraRoute;
41
+ export interface EldraRouteSchemas {
42
+ pageSchema: string;
43
+ routeTemplateSchema: string;
44
+ }
45
+ /**
46
+ * Resolve one request path against the site's pages and route templates.
47
+ *
48
+ * Every read below puts the locale through `localeQuery`, so a blank one — what
49
+ * a site that configured none actually carries — becomes no `locale` key at
50
+ * all rather than an empty `?locale=` the gateway answers with 400.
51
+ *
52
+ * A miss — no match, a template without a usable slug, or a 404 from the
53
+ * gateway for the matched page, entry or catalog object — resolves to the
54
+ * empty route, which the theme renders as its not-found shell. Every other
55
+ * failure is thrown, so the caller can show its error branch instead of
56
+ * silently claiming the page does not exist.
57
+ */
58
+ export declare function resolveEldraRoute(client: EldraClient, schemas: EldraRouteSchemas, path: string, locale?: string): Promise<ResolvedEldraRoute>;
59
+ /**
60
+ * How deep the generic walk below goes before it gives up.
61
+ *
62
+ * The bound is not a guess at how a document is shaped: the block grammar caps
63
+ * composite nesting at 5, each of those levels costs two steps here (the object
64
+ * and the array around it), and the document adds its own envelope — blocks, a
65
+ * layout tree, a reusable component's projection — on top. 64 is far past every
66
+ * one of those together, while still ending a walk through a value that
67
+ * somehow refers back to itself.
68
+ */
69
+ export declare const MAX_TARGET_WALK_DEPTH = 64;
70
+ /**
71
+ * Every target key the document's blocks name, deduplicated. Walks the block
72
+ * data generically rather than knowing which fields are links, so a theme
73
+ * adding a link field needs no change here.
74
+ *
75
+ * Reaching the bound is reported rather than swallowed. A key this walk misses
76
+ * is a target never read, so its link renders unlinked on the generated site —
77
+ * which looks exactly like a target that was deleted. A build has to be able to
78
+ * tell those two apart.
79
+ */
80
+ export declare function collectDocumentTargetKeys(document: EntryDoc | null, warn?: (message: string) => void): string[];
81
+ export declare function listAllEntries(client: EldraClient, schemaApiId: string, locale?: string): Promise<EntryDoc[]>;
@@ -0,0 +1,166 @@
1
+ import {
2
+ catalogRouteTarget,
3
+ EldraClientError,
4
+ resolveRoute,
5
+ stripStega
6
+ } from "@eldrajs/theme-core";
7
+ import { linkTargetKeys } from "@eldrajs/theme-core/links";
8
+ import { loadCatalogEntry } from "./catalog.js";
9
+ import { collectLinkTargets } from "./links.js";
10
+ import { localeQuery } from "./locale.js";
11
+ export const EMPTY_ELDRA_ROUTE = {
12
+ page: null,
13
+ template: null,
14
+ entry: null,
15
+ catalog: null,
16
+ links: { pages: [], templates: [], targets: /* @__PURE__ */ new Map() }
17
+ };
18
+ export async function resolveEldraRoute(client, schemas, path, locale) {
19
+ try {
20
+ const [pages, templates] = await Promise.all([
21
+ listAllEntries(client, schemas.pageSchema, locale),
22
+ listRouteTemplates(client, schemas.routeTemplateSchema, locale)
23
+ ]);
24
+ const match = resolveRoute(path, { pages, templates });
25
+ if (match === null) return EMPTY_ELDRA_ROUTE;
26
+ if (match.kind === "static") {
27
+ const page = await client.getEntry(schemas.pageSchema, match.entry.id, {
28
+ depth: 3,
29
+ ...localeQuery(locale)
30
+ });
31
+ return {
32
+ page,
33
+ template: null,
34
+ entry: null,
35
+ catalog: null,
36
+ links: await linkState(client, pages, templates, page, locale)
37
+ };
38
+ }
39
+ const schemaApiId = plainString(match.template.data.schemaApiId);
40
+ const slugField = plainString(match.template.data.slugField);
41
+ const slugValue = match.params[slugField];
42
+ if (schemaApiId === "" || slugField === "" || slugValue === void 0) return EMPTY_ELDRA_ROUTE;
43
+ const loadTemplate = client.getEntry(schemas.routeTemplateSchema, match.template.id, {
44
+ depth: 3,
45
+ ...localeQuery(locale)
46
+ });
47
+ const catalogKind = catalogRouteTarget(schemaApiId);
48
+ if (catalogKind !== null) {
49
+ const [template2, entry2] = await Promise.all([
50
+ loadTemplate,
51
+ loadCatalogEntry(client, catalogKind, slugValue, locale)
52
+ ]);
53
+ if (entry2 === null) return EMPTY_ELDRA_ROUTE;
54
+ return {
55
+ page: null,
56
+ template: template2,
57
+ entry: entry2,
58
+ // A category is addressed by its canonical path, so the route context
59
+ // carries both: the **leaf's** slug, which is what a surface filtering
60
+ // by one category needs, and the path, which is what a link back to this
61
+ // page is built from. The two other kinds are one segment, and the
62
+ // resolved projection carries no path for them.
63
+ catalog: catalogKind === "category" ? {
64
+ kind: catalogKind,
65
+ slug: plainString(entry2.data.slug),
66
+ path: plainString(entry2.data.path)
67
+ } : { kind: catalogKind, slug: slugValue },
68
+ links: await linkState(client, pages, templates, template2, locale)
69
+ };
70
+ }
71
+ const [template, entry] = await Promise.all([
72
+ loadTemplate,
73
+ client.getEntryByUniqueField(schemaApiId, slugField, slugValue, {
74
+ depth: 3,
75
+ ...localeQuery(locale)
76
+ })
77
+ ]);
78
+ return {
79
+ page: null,
80
+ template,
81
+ entry,
82
+ catalog: null,
83
+ links: await linkState(client, pages, templates, template, locale)
84
+ };
85
+ } catch (cause) {
86
+ if (cause instanceof EldraClientError && cause.status === 404) return EMPTY_ELDRA_ROUTE;
87
+ throw cause;
88
+ }
89
+ }
90
+ async function linkState(client, pages, templates, document, locale) {
91
+ const keys = collectDocumentTargetKeys(document);
92
+ const targets = keys.length === 0 ? /* @__PURE__ */ new Map() : await collectLinkTargets(client, keys, locale, {
93
+ entrySchemaApiIds: entryTemplateSchemas(templates),
94
+ pages
95
+ });
96
+ return { pages, templates, targets };
97
+ }
98
+ export const MAX_TARGET_WALK_DEPTH = 64;
99
+ export function collectDocumentTargetKeys(document, warn = (message) => console.warn(message)) {
100
+ if (document === null) return [];
101
+ const keys = [];
102
+ const seen = /* @__PURE__ */ new Set();
103
+ let truncated = false;
104
+ const visit = (value, depth) => {
105
+ if (depth > MAX_TARGET_WALK_DEPTH) {
106
+ truncated = true;
107
+ return;
108
+ }
109
+ if (Array.isArray(value)) {
110
+ for (const item of value) visit(item, depth + 1);
111
+ return;
112
+ }
113
+ if (typeof value !== "object" || value === null) return;
114
+ for (const key of linkTargetKeys(value)) {
115
+ if (!seen.has(key)) {
116
+ seen.add(key);
117
+ keys.push(key);
118
+ }
119
+ }
120
+ for (const nested of Object.values(value)) visit(nested, depth + 1);
121
+ };
122
+ visit(document.data, 0);
123
+ if (truncated) {
124
+ warn(
125
+ `[eldra] stopped looking for link targets ${MAX_TARGET_WALK_DEPTH} levels into entry ${document.id}; any link nested deeper than that renders without a destination`
126
+ );
127
+ }
128
+ return keys;
129
+ }
130
+ function entryTemplateSchemas(templates) {
131
+ const schemas = [];
132
+ for (const template of templates) {
133
+ const schemaApiId = plainString(template.data.schemaApiId);
134
+ if (schemaApiId === "" || schemaApiId.startsWith("catalog:") || schemas.includes(schemaApiId)) {
135
+ continue;
136
+ }
137
+ schemas.push(schemaApiId);
138
+ }
139
+ return schemas;
140
+ }
141
+ export async function listAllEntries(client, schemaApiId, locale) {
142
+ const entries = [];
143
+ let page = 1;
144
+ for (; ; ) {
145
+ const response = await client.getEntries(schemaApiId, {
146
+ page,
147
+ pageSize: 100,
148
+ depth: 0,
149
+ ...localeQuery(locale)
150
+ });
151
+ entries.push(...response.data);
152
+ if (!response.meta.hasNext) return entries;
153
+ page += 1;
154
+ }
155
+ }
156
+ async function listRouteTemplates(client, schemaApiId, locale) {
157
+ try {
158
+ return await listAllEntries(client, schemaApiId, locale);
159
+ } catch (cause) {
160
+ if (cause instanceof EldraClientError && cause.status === 404) return [];
161
+ throw cause;
162
+ }
163
+ }
164
+ function plainString(value) {
165
+ return typeof value === "string" ? stripStega(value).trim() : "";
166
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * One request path, reduced to the identity the theme resolves content for.
3
+ *
4
+ * A generated site is written as `<route>/index.html`, and static hosts disagree about which URL
5
+ * that file lives at: some serve `/products/ash-glaze-mug`, others answer it with a 308 to
6
+ * `/products/ash-glaze-mug/` (the deployed Eldra preview host is one of them). Both are the same
7
+ * page — the same CMS route, the same prerendered payload — so everything keyed by the path must
8
+ * agree, or the browser treats the page it was *served* as a different route from the one it was
9
+ * *built* as.
10
+ *
11
+ * That is not cosmetic. Nuxt's own hydration path compares `window.location` with the path the
12
+ * payload was prerendered at, and when they differ it re-navigates twice (`hasDeferredRoute` in
13
+ * `nuxt/dist/pages/runtime/plugins/router.js`) — which re-creates the page component, and with it
14
+ * every block on it, so every block's `setup` runs a second time and every read it makes goes out
15
+ * again. Canonicalising here is what makes those two navigations land on the same route identity
16
+ * and change nothing.
17
+ */
18
+ export declare function canonicalRoutePath(path: string): string;
19
+ /**
20
+ * The route key a theme's catch-all page should give `<NuxtPage>` (`:page-key="eldraRouteKey"`),
21
+ * auto-imported by this module.
22
+ *
23
+ * Nuxt's default key for a catch-all route interpolates the splat parameter, so
24
+ * `/products/ash-glaze-mug` and `/products/ash-glaze-mug/` produce **different** keys
25
+ * (`products,ash-glaze-mug` vs `products,ash-glaze-mug,`) and Vue destroys and re-creates the page
26
+ * when the router moves between them. Keying by the canonical path instead means the page — and
27
+ * the block tree under it — survives that move.
28
+ */
29
+ export declare function eldraRouteKey(route: {
30
+ path: string;
31
+ }): string;
@@ -0,0 +1,7 @@
1
+ export function canonicalRoutePath(path) {
2
+ const trimmed = path.replace(/\/+$/, "");
3
+ return trimmed === "" ? "/" : trimmed;
4
+ }
5
+ export function eldraRouteKey(route) {
6
+ return canonicalRoutePath(route.path);
7
+ }