@eldrajs/theme-nuxt 0.2.0 → 0.3.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 (37) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/dist/module.d.mts +48 -2
  3. package/dist/module.d.ts +48 -2
  4. package/dist/module.json +1 -1
  5. package/dist/module.mjs +178 -13
  6. package/dist/runtime/analytics.d.ts +83 -0
  7. package/dist/runtime/analytics.js +83 -0
  8. package/dist/runtime/analyticsPlugin.d.ts +15 -0
  9. package/dist/runtime/analyticsPlugin.js +21 -0
  10. package/dist/runtime/catalog.d.ts +5 -0
  11. package/dist/runtime/catalog.js +6 -3
  12. package/dist/runtime/composables/useEldraAnalytics.d.ts +10 -0
  13. package/dist/runtime/composables/useEldraAnalytics.js +6 -0
  14. package/dist/runtime/composables/useEldraForms.d.ts +8 -0
  15. package/dist/runtime/composables/useEldraForms.js +5 -0
  16. package/dist/runtime/composables/useEldraSeo.d.ts +27 -0
  17. package/dist/runtime/composables/useEldraSeo.js +41 -0
  18. package/dist/runtime/composables/useStructuredData.d.ts +35 -0
  19. package/dist/runtime/composables/useStructuredData.js +55 -0
  20. package/dist/runtime/crawl.d.ts +29 -0
  21. package/dist/runtime/crawl.js +50 -0
  22. package/dist/runtime/crawlOutput.d.ts +54 -0
  23. package/dist/runtime/crawlOutput.js +96 -0
  24. package/dist/runtime/forms.d.ts +29 -0
  25. package/dist/runtime/forms.js +154 -0
  26. package/dist/runtime/localeState.d.ts +6 -4
  27. package/dist/runtime/localeState.js +7 -15
  28. package/dist/runtime/plugin.js +6 -1
  29. package/dist/runtime/redirects.d.ts +74 -0
  30. package/dist/runtime/redirects.js +190 -0
  31. package/dist/runtime/seo.d.ts +23 -0
  32. package/dist/runtime/seo.js +95 -0
  33. package/dist/runtime/seoHead.d.ts +27 -0
  34. package/dist/runtime/seoHead.js +28 -0
  35. package/dist/runtime/siteProfile.d.ts +56 -0
  36. package/dist/runtime/siteProfile.js +69 -0
  37. package/package.json +6 -5
@@ -0,0 +1,83 @@
1
+ import { createAnalytics } from "@eldrajs/theme-core";
2
+ import { analyticsTrackerScript } from "@eldrajs/sdk";
3
+ export function parseEventOrigin(value) {
4
+ try {
5
+ const url = new URL(value);
6
+ return (url.protocol === "https:" || url.protocol === "http:") && url.origin === value ? value : null;
7
+ } catch {
8
+ return null;
9
+ }
10
+ }
11
+ export function resolveAnalyticsConfig(input) {
12
+ const warn = input.warn ?? ((message) => console.warn(message));
13
+ const option = input.option;
14
+ const optedOut = option === false || option !== void 0 && option.enabled === false || input.env.ELDRA_ANALYTICS?.trim().toLowerCase() === "off";
15
+ const rawOrigin = (input.env.ELDRA_ANALYTICS_ORIGIN ?? "").trim() || (option !== void 0 && option !== false ? option.eventOrigin ?? "" : "");
16
+ let eventOrigin = null;
17
+ if (rawOrigin !== "") {
18
+ eventOrigin = parseEventOrigin(rawOrigin);
19
+ if (eventOrigin === null) {
20
+ warn(
21
+ `[eldra] analytics.eventOrigin "${rawOrigin}" is not an origin (https://host, no path) \u2014 ignored`
22
+ );
23
+ }
24
+ }
25
+ return {
26
+ enabled: !optedOut && !input.dev && input.production && input.orgId !== "",
27
+ eventOrigin
28
+ };
29
+ }
30
+ export function isNonSiteHost(hostname) {
31
+ if (hostname === void 0) return false;
32
+ const host = hostname.toLowerCase();
33
+ return host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]" || host === "::1" || host === "previews.eldra.dev" || host.endsWith(".previews.eldra.dev");
34
+ }
35
+ export function shouldReport(input) {
36
+ return input.client && !input.dev && input.config?.enabled === true && !input.studioPreviewFrame && !isNonSiteHost(input.hostname);
37
+ }
38
+ export function installTrackerScript(doc, config, onLoad) {
39
+ if (doc.querySelector('script[data-org][src$="/js/script.js"]') !== null) return false;
40
+ const attrs = analyticsTrackerScript({
41
+ apiBaseUrl: config.gatewayUrl || void 0,
42
+ orgId: config.orgId,
43
+ eventOrigin: config.eventOrigin ?? void 0
44
+ });
45
+ if (attrs === void 0) return false;
46
+ const tag = doc.createElement("script");
47
+ tag.src = attrs.src;
48
+ tag.defer = true;
49
+ tag.crossOrigin = attrs.crossorigin;
50
+ tag.setAttribute("data-org", attrs["data-org"]);
51
+ if (attrs["data-api"] !== void 0) tag.setAttribute("data-api", attrs["data-api"]);
52
+ tag.addEventListener("load", onLoad, { once: true });
53
+ doc.head.appendChild(tag);
54
+ return true;
55
+ }
56
+ export function trackerGlobal(win) {
57
+ return typeof win.eldra === "function" ? win.eldra : void 0;
58
+ }
59
+ export function setupAnalytics(input) {
60
+ const active = shouldReport({
61
+ hostname: input.hostname,
62
+ client: input.client,
63
+ dev: input.dev,
64
+ config: input.config,
65
+ studioPreviewFrame: input.isFrame
66
+ });
67
+ const analytics = createAnalytics({
68
+ enabled: active,
69
+ sender: () => input.win === void 0 ? void 0 : trackerGlobal(input.win)
70
+ });
71
+ if (active && input.config !== void 0 && input.doc !== void 0) {
72
+ installTrackerScript(
73
+ input.doc,
74
+ {
75
+ gatewayUrl: input.gatewayUrl,
76
+ orgId: input.orgId,
77
+ eventOrigin: input.config.eventOrigin
78
+ },
79
+ () => analytics.flush()
80
+ );
81
+ }
82
+ return analytics;
83
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Loads the Eldra tracker on the deployed site and provides `$eldraAnalytics`
3
+ * (`useEldraAnalytics()`).
4
+ *
5
+ * The tag is added **at runtime**, not written into the generated HTML, because the Studio preview
6
+ * serves the same bundle in an iframe and a static `<script>` cannot decide not to run there. The
7
+ * build has already decided everything it can (`resolveAnalyticsConfig`: production build, an
8
+ * organisation, no opt-out); what is left is the one thing only the browser knows — whether this
9
+ * document is a Studio preview frame, which never reports.
10
+ *
11
+ * The tracker handles pageviews itself, including client-side navigations (it patches
12
+ * `history.pushState`), so no router hook is needed here.
13
+ */
14
+ declare const _default: import("nuxt/app").Plugin<Record<string, unknown>> & import("nuxt/app").ObjectPlugin<Record<string, unknown>>;
15
+ export default _default;
@@ -0,0 +1,21 @@
1
+ import { defineNuxtPlugin, useRuntimeConfig } from "nuxt/app";
2
+ import { setupAnalytics } from "./analytics.js";
3
+ import { isStudioPreviewFrame } from "./origins.js";
4
+ export default defineNuxtPlugin({
5
+ name: "eldra-analytics",
6
+ setup(nuxtApp) {
7
+ const cfg = useRuntimeConfig().public.eldra;
8
+ const analytics = setupAnalytics({
9
+ client: import.meta.client,
10
+ dev: import.meta.dev,
11
+ config: cfg.analytics,
12
+ isFrame: import.meta.client && isStudioPreviewFrame(cfg.studioOrigins),
13
+ gatewayUrl: cfg.gatewayUrl,
14
+ orgId: cfg.orgId,
15
+ hostname: import.meta.client ? window.location.hostname : void 0,
16
+ doc: import.meta.client ? document : void 0,
17
+ win: import.meta.client ? window : void 0
18
+ });
19
+ nuxtApp.provide("eldraAnalytics", analytics);
20
+ }
21
+ });
@@ -116,4 +116,9 @@ export declare function listCatalogDocs(client: EldraClient, kind: CatalogRouteK
116
116
  * list does not hold — has no route at all, which is exactly what the resolver
117
117
  * would answer for it at request time.
118
118
  */
119
+ export declare function catalogDocRouteRefs(kind: CatalogRouteKind, docs: readonly CatalogDoc[], pattern: string, warn?: (message: string) => void): Array<{
120
+ path: string;
121
+ doc: CatalogDoc;
122
+ }>;
123
+ /** The paths alone: `catalogDocRouteRefs` without the records they came from. */
119
124
  export declare function catalogDocRoutes(kind: CatalogRouteKind, docs: readonly CatalogDoc[], pattern: string, warn?: (message: string) => void): string[];
@@ -158,7 +158,7 @@ export async function listCatalogDocs(client, kind, locale) {
158
158
  page += 1;
159
159
  }
160
160
  }
161
- export function catalogDocRoutes(kind, docs, pattern, warn = (message) => console.warn(message)) {
161
+ export function catalogDocRouteRefs(kind, docs, pattern, warn = (message) => console.warn(message)) {
162
162
  const paths = [];
163
163
  if (kind === "category") {
164
164
  for (const node of buildCategoryTree(docs).values()) {
@@ -169,7 +169,7 @@ export function catalogDocRoutes(kind, docs, pattern, warn = (message) => consol
169
169
  );
170
170
  continue;
171
171
  }
172
- paths.push(path);
172
+ paths.push({ path, doc: node.raw });
173
173
  }
174
174
  return paths;
175
175
  }
@@ -184,10 +184,13 @@ export function catalogDocRoutes(kind, docs, pattern, warn = (message) => consol
184
184
  );
185
185
  continue;
186
186
  }
187
- paths.push(path);
187
+ paths.push({ path, doc });
188
188
  }
189
189
  return paths;
190
190
  }
191
+ export function catalogDocRoutes(kind, docs, pattern, warn = (message) => console.warn(message)) {
192
+ return catalogDocRouteRefs(kind, docs, pattern, warn).map((ref) => ref.path);
193
+ }
191
194
  function isActive(doc) {
192
195
  const status = doc.status;
193
196
  return typeof status !== "string" || status.toUpperCase() === ACTIVE_STATUS;
@@ -0,0 +1,10 @@
1
+ import type { EldraAnalytics } from '../analytics.js';
2
+ /**
3
+ * Records a custom event (`add_to_cart`, `search`, ...) with the Eldra tracker the module loads on
4
+ * deployed sites. Props are stringified and cut to Core's limits; `null`/`undefined` props are
5
+ * dropped. A no-op (`enabled: false`) on the server, in `nuxi dev`, in a Studio preview, on a
6
+ * build without an organisation and when the site opted out — call it freely.
7
+ *
8
+ * Pageviews are not sent from here: the tracker sends them, including for client-side navigations.
9
+ */
10
+ export declare function useEldraAnalytics(): EldraAnalytics;
@@ -0,0 +1,6 @@
1
+ import { useNuxtApp } from "nuxt/app";
2
+ const DISABLED = { enabled: false, track: () => void 0 };
3
+ export function useEldraAnalytics() {
4
+ const injected = useNuxtApp().$eldraAnalytics;
5
+ return injected ?? DISABLED;
6
+ }
@@ -0,0 +1,8 @@
1
+ import type { EldraFormDefinition } from '@eldrajs/sdk';
2
+ /**
3
+ * The form definitions the build baked into the site (`eldra.formSeeds` and `eldra.forms` keys,
4
+ * read once at `nuxi generate` time), by form key. A form that is not here — the merchant made it
5
+ * after the build, or the build's read failed — is fetched in the visitor's browser instead; the
6
+ * storefront's `forms.definition(key)` does both, so a block never calls this directly.
7
+ */
8
+ export declare function useEldraForms(): Record<string, EldraFormDefinition>;
@@ -0,0 +1,5 @@
1
+ import { useRuntimeConfig } from "nuxt/app";
2
+ export function useEldraForms() {
3
+ const eldra = useRuntimeConfig().public.eldra;
4
+ return typeof eldra.forms === "object" && eldra.forms !== null ? eldra.forms : {};
5
+ }
@@ -0,0 +1,27 @@
1
+ import { type ResolvedSeo, type SeoContext, type SeoData, type SeoEntryValue } from '@eldrajs/theme-core';
2
+ import { type ComputedRef, type MaybeRefOrGetter } from 'vue';
3
+ /** What `useEldraSeo` needs beyond the context's variables. */
4
+ export interface UseEldraSeoOptions {
5
+ /** The page's (or catalog route's template's) own `seo` field value. */
6
+ entry?: SeoEntryValue | null;
7
+ /** The route template's `seo` field value, when the route renders through one. */
8
+ template?: SeoEntryValue | null;
9
+ /** The content's own image (a product's first), used when the entry has none. */
10
+ contentImage?: string | null;
11
+ }
12
+ /**
13
+ * Sets the page's `<title>`, description, canonical link, Open Graph and Twitter tags and `robots`
14
+ * from the platform's SEO setting and the route's own `seo` value, by the one resolver Studio's
15
+ * previews share (`resolveSeo` in `@eldrajs/theme-core`).
16
+ *
17
+ * `context` says what the route shows (`page`, `home`, `catalog:product`, ...) and `data` carries
18
+ * that context's variables (`page.title`, `product.name`, ...); `site.*` is filled in here. Every
19
+ * argument may be a ref or a getter, so the tags follow a route change.
20
+ *
21
+ * A **preview build** (`ELDRA_BUILD_TARGET=preview`, `nuxi dev`, or a page framed
22
+ * by Studio) is always `noindex`. A site whose setting could not be read renders with the default
23
+ * pattern (`{{page.title}} · {{site.name}}`).
24
+ *
25
+ * Returns the resolved values, so a page can reuse them (a JSON-LD builder, say).
26
+ */
27
+ export declare function useEldraSeo(context: MaybeRefOrGetter<SeoContext>, data: MaybeRefOrGetter<SeoData>, options?: MaybeRefOrGetter<UseEldraSeoOptions | undefined>): ComputedRef<ResolvedSeo>;
@@ -0,0 +1,41 @@
1
+ import {
2
+ resolveSeo
3
+ } from "@eldrajs/theme-core";
4
+ import { useEldra, useEldraLocale } from "@eldrajs/theme-vue";
5
+ import { useHead, useRoute, useRuntimeConfig } from "nuxt/app";
6
+ import { computed, toValue } from "vue";
7
+ import { isStudioPreviewFrame } from "../origins.js";
8
+ import { buildSeoHead } from "../seoHead.js";
9
+ export function useEldraSeo(context, data, options = {}) {
10
+ const cfg = useRuntimeConfig().public;
11
+ const seoConfig = cfg.eldraSeo;
12
+ const setting = typeof seoConfig.setting === "object" && seoConfig.setting !== null ? seoConfig.setting : null;
13
+ const studioOrigins = cfg.eldra.studioOrigins;
14
+ const route = useRoute();
15
+ const locale = useEldraLocale();
16
+ const eldra = useEldra();
17
+ const resolved = computed(() => {
18
+ const extra = toValue(options) ?? {};
19
+ return resolveSeo({
20
+ locale: locale.active,
21
+ defaultLocale: locale.defaultLocale,
22
+ context: toValue(context),
23
+ site: setting,
24
+ siteName: seoConfig.siteName,
25
+ siteUrl: seoConfig.siteUrl,
26
+ path: route.path,
27
+ entry: extra.entry,
28
+ template: extra.template,
29
+ contentImage: extra.contentImage,
30
+ data: toValue(data),
31
+ isPreview: seoConfig.isPreview || eldra.preview.active || isStudioPreviewFrame(studioOrigins)
32
+ });
33
+ });
34
+ useHead(
35
+ () => buildSeoHead(resolved.value, {
36
+ locale: locale.active,
37
+ siteName: setting?.site.name?.trim() || seoConfig.siteName
38
+ })
39
+ );
40
+ return resolved;
41
+ }
@@ -0,0 +1,35 @@
1
+ import { type StructuredDataEntry, type StructuredDataPolicy } from '@eldrajs/theme-core';
2
+ import { type MaybeRefOrGetter } from 'vue';
3
+ import type { ResolvedSiteProfile } from '../siteProfile.js';
4
+ /** The theme's runtime edit of one node; see `provideStructuredData`. */
5
+ export type StructuredDataExtender = NonNullable<StructuredDataPolicy['extend']>;
6
+ /**
7
+ * Lets a theme edit or drop a node before it is written: `(type, node, { path, locale }) => node |
8
+ * null`. Call it from a plugin or the root component. A function cannot ride in the module option
9
+ * (the runtime config is serialised), so this is the runtime half of `eldra.structuredData`.
10
+ */
11
+ export declare function provideStructuredData(extend: StructuredDataExtender): void;
12
+ /**
13
+ * Writes the page's schema.org JSON-LD into the head as one `<script type="application/ld+json">`.
14
+ * `entries` is what the page built (`buildProductLd` & co. from `@eldrajs/theme-core`, each tagged
15
+ * with its kind), a ref or a getter so it follows a route change. The theme's `disable` option (the
16
+ * module's `eldra.structuredData`) and its `provideStructuredData` extender are applied here, so a
17
+ * page never has to know about either.
18
+ *
19
+ * Nothing is written for no nodes, and nothing for a page that passes `enabled: false` — pass
20
+ * `!seo.noindex` from `useEldraSeo` so a page kept out of the index carries no markup either. One
21
+ * head entry under a fixed key, so two calls in one app replace each other instead of stacking
22
+ * duplicate markup.
23
+ */
24
+ export declare function useStructuredData(entries: MaybeRefOrGetter<readonly StructuredDataEntry[]>, options?: {
25
+ enabled?: MaybeRefOrGetter<boolean>;
26
+ }): void;
27
+ /**
28
+ * The shop's profile for an `Organization` node (name, logo, social links, contact), with the
29
+ * site name and the site icon filling what the merchant left unset, plus the site's origin.
30
+ * `siteUrl` is `''` when the build does not know it; the page then has no absolute URL to write,
31
+ * and should write no node that needs one.
32
+ */
33
+ export declare function useSiteProfile(): ResolvedSiteProfile & {
34
+ siteUrl: string;
35
+ };
@@ -0,0 +1,55 @@
1
+ import {
2
+ applyStructuredDataPolicy,
3
+ serializeLd,
4
+ STRUCTURED_DATA_TYPES
5
+ } from "@eldrajs/theme-core";
6
+ import { useEldraLocale } from "@eldrajs/theme-vue";
7
+ import { useHead, useNuxtApp, useRoute, useRuntimeConfig } from "nuxt/app";
8
+ import { toValue } from "vue";
9
+ const extenders = /* @__PURE__ */ new WeakMap();
10
+ export function provideStructuredData(extend) {
11
+ extenders.set(useNuxtApp(), extend);
12
+ }
13
+ export function useStructuredData(entries, options = {}) {
14
+ const config = useRuntimeConfig().public.eldra;
15
+ const disable = readDisable(config.structuredData?.disable);
16
+ const nuxtApp = useNuxtApp();
17
+ const route = useRoute();
18
+ const locale = useEldraLocale();
19
+ useHead(() => {
20
+ if (toValue(options.enabled) === false) return {};
21
+ const context = { path: route.path, locale: locale.active ?? null };
22
+ const nodes = applyStructuredDataPolicy(
23
+ toValue(entries),
24
+ { disable, extend: extenders.get(nuxtApp) },
25
+ context
26
+ );
27
+ if (nodes.length === 0) return {};
28
+ return {
29
+ script: [{ key: "eldra-ld", type: "application/ld+json", innerHTML: serializeLd(nodes) }]
30
+ };
31
+ });
32
+ }
33
+ function readDisable(value) {
34
+ if (value === true) return true;
35
+ if (!Array.isArray(value)) return [];
36
+ return value.filter(
37
+ (type) => STRUCTURED_DATA_TYPES.includes(type)
38
+ );
39
+ }
40
+ export function useSiteProfile() {
41
+ const config = useRuntimeConfig().public;
42
+ const profile = config.eldra;
43
+ const seo = config.eldraSeo;
44
+ const resolved = typeof profile.siteProfile === "object" ? profile.siteProfile : null;
45
+ return {
46
+ name: resolved?.name || seo.siteName || "",
47
+ logoUrl: resolved?.logoUrl || null,
48
+ sameAs: resolved?.sameAs ?? [],
49
+ contact: {
50
+ email: resolved?.contact?.email || null,
51
+ telephone: resolved?.contact?.telephone || null
52
+ },
53
+ siteUrl: seo.siteUrl ?? ""
54
+ };
55
+ }
@@ -0,0 +1,29 @@
1
+ import type { EldraClient } from '@eldrajs/sdk';
2
+ /**
3
+ * The slice of an `@eldrajs/sdk` client this read needs — a whole `EldraClient` satisfies it. The
4
+ * same narrow shape as `SiteIconsReader`: `GET /site/v1/crawl` is a site-module read with no typed
5
+ * `features.*` method, so the client's generic `request` carries it.
6
+ */
7
+ export interface CrawlReader {
8
+ request: EldraClient['request'];
9
+ }
10
+ /** `GET /site/v1/crawl` as the platform answers it. */
11
+ export interface CrawlSetting {
12
+ revision: number;
13
+ /** The site's public origin (Core's production URL), or `null` when none is set. */
14
+ siteUrl: string | null;
15
+ /** The merchant's own `robots.txt` lines; `''` when none. */
16
+ robotsExtra: string;
17
+ }
18
+ /** The one line a build prints when it could not read the platform's crawl settings. */
19
+ export declare const CRAWL_WARNING = "[eldra] could not read the platform\u2019s crawl settings \u2014 robots.txt has no merchant lines and the site URL comes from ELDRA_SITE_URL";
20
+ /** How long the build waits for the answer; see `READ_TIMEOUT_MS` in `./designTokens.ts`. */
21
+ export declare const READ_TIMEOUT_MS = 10000;
22
+ /**
23
+ * The platform's crawl settings, or `null`.
24
+ *
25
+ * Fail-soft exactly like `readSiteIcons`: no client, an unreachable gateway, a timeout and a
26
+ * response that is not the documented shape all end in `null` and **one** warning, so the theme
27
+ * keeps deploying.
28
+ */
29
+ export declare function readCrawlSettings(reader: CrawlReader | null, warn?: (message: string) => void): Promise<CrawlSetting | null>;
@@ -0,0 +1,50 @@
1
+ import { siteOrigin } from "@eldrajs/theme-core";
2
+ export const CRAWL_WARNING = "[eldra] could not read the platform\u2019s crawl settings \u2014 robots.txt has no merchant lines and the site URL comes from ELDRA_SITE_URL";
3
+ export const READ_TIMEOUT_MS = 1e4;
4
+ export async function readCrawlSettings(reader, warn = console.warn) {
5
+ const read = reader === null ? { setting: null, cause: null } : await readOrNull(reader);
6
+ if (read.setting === null) {
7
+ warn(read.cause === null ? CRAWL_WARNING : `${CRAWL_WARNING} (${read.cause})`);
8
+ return null;
9
+ }
10
+ return read.setting;
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/crawl",
21
+ signal: controller.signal
22
+ });
23
+ const setting = toCrawlSetting(response);
24
+ return {
25
+ setting,
26
+ cause: setting === null ? "the platform published an unusable response" : null
27
+ };
28
+ } catch (error) {
29
+ return {
30
+ setting: null,
31
+ cause: error instanceof Error ? error.message : String(error)
32
+ };
33
+ } finally {
34
+ clearTimeout(timer);
35
+ }
36
+ }
37
+ function toCrawlSetting(value) {
38
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
39
+ const record = value;
40
+ if (typeof record.revision !== "number" || !Number.isFinite(record.revision)) return null;
41
+ let siteUrl = null;
42
+ if (record.siteUrl !== null && record.siteUrl !== void 0) {
43
+ if (typeof record.siteUrl !== "string") return null;
44
+ siteUrl = record.siteUrl.trim() === "" ? null : siteOrigin(record.siteUrl);
45
+ if (record.siteUrl.trim() !== "" && siteUrl === null) return null;
46
+ }
47
+ const extra = record.robotsExtra;
48
+ if (extra !== null && extra !== void 0 && typeof extra !== "string") return null;
49
+ return { revision: record.revision, siteUrl, robotsExtra: extra ?? "" };
50
+ }
@@ -0,0 +1,54 @@
1
+ import { type SitemapLimits, type SitemapPage } from '@eldrajs/theme-core';
2
+ import { type EldraLocaleRouting } from './locales.js';
3
+ /** One content path the build prerenders, with what the sitemap needs to know about it. */
4
+ export interface CrawlRoute {
5
+ /** The unprefixed path (`/about`); locale variants are derived from it. */
6
+ path: string;
7
+ /** The entry's or catalog record's own `updatedAt`, when the read carried one. */
8
+ lastmod?: unknown;
9
+ /** The entry's or route template's own `seo` field value. */
10
+ seo?: unknown;
11
+ /** The route template's `seo` field value, when the route renders through one (merged like `resolveSeo`). */
12
+ templateSeo?: unknown;
13
+ /** A native code route: served at this exact path only, never under a locale prefix. */
14
+ codeOwned?: boolean;
15
+ }
16
+ export interface CrawlFile {
17
+ name: string;
18
+ content: string;
19
+ }
20
+ /**
21
+ * Turns the build's prerendered routes into `SitemapPage`s: one variant per locale the site
22
+ * serves (every content path exists in every locale, see `addRoute` in `../module.ts`), with the
23
+ * page's `noindex` and its canonical for each locale taken from its own `seo` value — the same
24
+ * field shape `useEldraSeo` reads.
25
+ *
26
+ * A canonical that still holds a `{` (a `{{pattern}}`, or a `{fieldId}` template Studio stored) is skipped: it is resolved per render with the page's
27
+ * variables, which the build does not have here, and a half-resolved URL must not reach the
28
+ * sitemap. `noindex` is a plain boolean, so it needs no such care.
29
+ */
30
+ export declare function toSitemapPages(routes: readonly CrawlRoute[], routing: EldraLocaleRouting): SitemapPage[];
31
+ export interface CrawlOutputInput {
32
+ target: 'production' | 'preview';
33
+ /** The site's origin: `ELDRA_SITE_URL`, else the platform's production URL. */
34
+ siteUrl: string | null | undefined;
35
+ /** The merchant's own `robots.txt` lines from the platform. */
36
+ robotsExtra: string | null | undefined;
37
+ routes: readonly CrawlRoute[];
38
+ routing: EldraLocaleRouting;
39
+ /** `false` turns `sitemap.xml` off. */
40
+ sitemap: false | SitemapLimits | undefined;
41
+ /** The theme's own `public/` directory: a file it ships there is never replaced. */
42
+ themePublicDir: string;
43
+ log: (message: string) => void;
44
+ }
45
+ /**
46
+ * The `robots.txt` and `sitemap.xml` (and its children) a build writes into the static output.
47
+ *
48
+ * * **Preview** (`ELDRA_BUILD_TARGET=preview`): `robots.txt` is
49
+ * `Disallow: /`, and there is no sitemap — a preview host must never be indexed.
50
+ * * **Production** needs an absolute site URL. Without one nothing is written (a sitemap of
51
+ * relative URLs is invalid, and a `Sitemap:` line must be absolute) and one line says why.
52
+ * * A file the theme ships in its own `public/` wins: it is skipped, with one line.
53
+ */
54
+ export declare function buildCrawlFiles(input: CrawlOutputInput): CrawlFile[];
@@ -0,0 +1,96 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import {
4
+ buildRobots,
5
+ buildSitemap,
6
+ siteOrigin,
7
+ stripStega
8
+ } from "@eldrajs/theme-core";
9
+ import { localePathFor } from "./locales.js";
10
+ export function toSitemapPages(routes, routing) {
11
+ return routes.map((route) => {
12
+ const seo = asSeo(route.seo);
13
+ const templateSeo = asSeo(route.templateSeo);
14
+ const locales = route.codeOwned === true ? [] : routing.supported;
15
+ const variants = locales.length === 0 ? [
16
+ {
17
+ locale: routing.default ?? null,
18
+ path: route.path,
19
+ isDefault: true
20
+ }
21
+ ] : locales.map((locale) => ({
22
+ locale,
23
+ path: localePathFor(route.path, locale, routing),
24
+ isDefault: locale === routing.default,
25
+ canonical: canonicalFor(seo, locale, locales.length) ?? canonicalFor(templateSeo, locale, locales.length)
26
+ }));
27
+ const lastmod = route.lastmod;
28
+ return {
29
+ variants,
30
+ lastmod: typeof lastmod === "string" || lastmod instanceof Date ? lastmod : null,
31
+ noindex: seo?.noindex === true || templateSeo?.noindex === true
32
+ };
33
+ });
34
+ }
35
+ function asSeo(value) {
36
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
37
+ }
38
+ function canonicalFor(seo, locale, localeCount) {
39
+ const canonical = seo?.canonicalUrl;
40
+ let raw = null;
41
+ if (typeof canonical === "string") raw = localeCount === 1 ? canonical : null;
42
+ else if (typeof canonical === "object" && canonical !== null && Object.hasOwn(canonical, locale))
43
+ raw = canonical[locale];
44
+ if (typeof raw !== "string") return null;
45
+ const value = stripStega(raw).trim();
46
+ return value === "" || value.includes("{") ? null : value;
47
+ }
48
+ export function buildCrawlFiles(input) {
49
+ const files = [];
50
+ const own = (name) => existsSync(join(input.themePublicDir, name));
51
+ const skipOwn = (name) => {
52
+ if (!own(name)) return false;
53
+ input.log(`[eldra] ${name} generation skipped: theme ships its own`);
54
+ return true;
55
+ };
56
+ if (input.target !== "production") {
57
+ if (!skipOwn("robots.txt")) {
58
+ files.push({
59
+ name: "robots.txt",
60
+ content: buildRobots({ target: "preview" })
61
+ });
62
+ }
63
+ return files;
64
+ }
65
+ const origin = siteOrigin(input.siteUrl);
66
+ if (origin === null) {
67
+ input.log(
68
+ "[eldra] robots.txt and sitemap.xml generation skipped: no absolute site URL (set ELDRA_SITE_URL or the production URL in Studio)"
69
+ );
70
+ return files;
71
+ }
72
+ let sitemapListed = false;
73
+ if (input.sitemap !== false && skipOwn("sitemap.xml")) {
74
+ sitemapListed = true;
75
+ } else if (input.sitemap !== false) {
76
+ const built = buildSitemap({
77
+ pages: toSitemapPages(input.routes, input.routing),
78
+ siteUrl: origin,
79
+ limits: input.sitemap
80
+ });
81
+ for (const file of built) files.push({ name: file.name, content: file.xml });
82
+ sitemapListed = built.length > 0;
83
+ }
84
+ if (!skipOwn("robots.txt")) {
85
+ files.push({
86
+ name: "robots.txt",
87
+ content: buildRobots({
88
+ target: "production",
89
+ siteUrl: origin,
90
+ extra: input.robotsExtra,
91
+ sitemap: sitemapListed
92
+ })
93
+ });
94
+ }
95
+ return files;
96
+ }
@@ -0,0 +1,29 @@
1
+ import type { EldraClient, EldraFormDefinition } from '@eldrajs/sdk';
2
+ /**
3
+ * The slice of an `@eldrajs/sdk` client the build-time form read needs: the typed `forms.get`. A
4
+ * whole `EldraClient` satisfies it.
5
+ */
6
+ export interface FormDefinitionsReader {
7
+ forms: Pick<EldraClient['forms'], 'get'>;
8
+ }
9
+ /** The form definitions a build baked, by form key; a key that could not be read is absent. */
10
+ export type FormDefinitions = Record<string, EldraFormDefinition>;
11
+ /** The one line a build prints per form it could not read; the cause follows in parentheses. */
12
+ export declare const FORM_DEFINITION_WARNING: (key: string) => string;
13
+ /** How long the build waits for one form; see `READ_TIMEOUT_MS` in `./designTokens.ts`. */
14
+ export declare const READ_TIMEOUT_MS = 10000;
15
+ /**
16
+ * The definitions of `keys`, read in parallel at build time, **each independently fail-soft**: no
17
+ * client, an unreachable gateway, a `404` (the form is not seeded yet), a timeout and a response
18
+ * that is not the documented shape all leave that one key out and print **one** warning, so a
19
+ * theme keeps deploying and one form's failure never costs another its definition. A form left out
20
+ * is not a broken form: the storefront fetches it in the visitor's browser instead
21
+ * (`forms.definition` in the starter's gateway storefront).
22
+ */
23
+ export declare function readFormDefinitions(reader: FormDefinitionsReader | null, keys: readonly string[], warn?: (message: string) => void): Promise<FormDefinitions>;
24
+ /**
25
+ * Accepts only a whole answer for `key`: half of an untrusted response never reaches a payload
26
+ * every visitor downloads. A definition whose own `key` differs from the one asked for is refused
27
+ * too, since the starter looks definitions up by the key a block names.
28
+ */
29
+ export declare function toFormDefinition(value: unknown, key: string): EldraFormDefinition | null;