@eldrajs/theme-nuxt 0.1.1 → 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 (42) hide show
  1. package/CHANGELOG.md +99 -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 +231 -11
  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/drafts.js +7 -1
  25. package/dist/runtime/forms.d.ts +29 -0
  26. package/dist/runtime/forms.js +154 -0
  27. package/dist/runtime/localeState.d.ts +6 -4
  28. package/dist/runtime/localeState.js +7 -15
  29. package/dist/runtime/plugin.js +7 -2
  30. package/dist/runtime/redirects.d.ts +74 -0
  31. package/dist/runtime/redirects.js +190 -0
  32. package/dist/runtime/seo.d.ts +23 -0
  33. package/dist/runtime/seo.js +95 -0
  34. package/dist/runtime/seoHead.d.ts +27 -0
  35. package/dist/runtime/seoHead.js +28 -0
  36. package/dist/runtime/siteIconAssets.d.ts +19 -0
  37. package/dist/runtime/siteIconAssets.js +29 -0
  38. package/dist/runtime/siteIcons.d.ts +74 -0
  39. package/dist/runtime/siteIcons.js +96 -0
  40. package/dist/runtime/siteProfile.d.ts +56 -0
  41. package/dist/runtime/siteProfile.js +69 -0
  42. package/package.json +6 -5
package/CHANGELOG.md CHANGED
@@ -5,6 +5,105 @@ Release-please writes the generated notes from commit messages and does not repl
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ - **Baked form definitions keep `consentText` (WS-386).** `toFormDefinition` carries a subscribing
9
+ form's consent sentence per locale and refuses a malformed one, like the other localized texts.
10
+
11
+ - **The analytics tracker never loads on `localhost` or `*.previews.eldra.dev` (WS-387).** A local
12
+ `nuxi generate` is a production build now, so the browser skips the tracker on a developer's
13
+ machine and on the Studio preview host. `ELDRA_BUILD_TARGET` is also read once in `setup()`, so a
14
+ mistyped value warns once, in context, instead of at import.
15
+
16
+ - **Baked form definitions accept `number` and `url` fields (WS-386).** `readFormDefinitions` no
17
+ longer drops a form that has one.
18
+
19
+ - **Breaking: a build is production unless `ELDRA_BUILD_TARGET=preview` (WS-387).** The marker
20
+ flipped. Before, only `ELDRA_BUILD_TARGET=production` was a production build and everything else
21
+ was a noindex preview; now an unset or empty variable is production, `preview` is the preview
22
+ (noindex, `robots.txt` `Disallow: /`, no sitemap, no analytics), and any other value warns and
23
+ counts as production. `nuxi dev` is unchanged: always a preview, with no tracker. A pipeline that
24
+ must not be indexed sets `ELDRA_BUILD_TARGET=preview`; the starter's CI files no longer set
25
+ `production`. The `buildTarget` module option still overrides.
26
+
27
+ - **`_redirects` rules that would match `/.eldra/manifest.json` are dropped (WS-384).** A theme's own
28
+ `public/_redirects` catch-all (or a platform rule) used to make every deploy fail the validator's
29
+ manifest check; the build now drops such a rule with one warning naming it and ships the rest.
30
+ - **Form definitions are read at build time and baked in (WS-386).** The module reads
31
+ `GET /site/v1/forms/{key}` for every key in the new `formSeeds` option (also passed to
32
+ `@eldrajs/vite-plugin-theme`) and the new `forms: string[]` option, once per `nuxi generate`, each key
33
+ independently fail-soft — one warning naming the key, never a failed build, and one form's failure
34
+ never costs another its definition. The validated definitions are written to
35
+ `runtimeConfig.public.eldra.forms` and read with the new auto-imported `useEldraForms()`; the starter's
36
+ `forms.definition` serves a baked key with no request and fetches any other when the page opens.
37
+ `nuxi dev` reads none.
38
+ - **Built-in analytics: the Eldra tracker, `useEldraAnalytics`, the `analytics` option.** A production
39
+ build (`ELDRA_BUILD_TARGET=production`) with an organisation id loads the tracker
40
+ (`analyticsTrackerScript` from `@eldrajs/sdk`) through a client plugin, so a deployed site reports
41
+ pageviews, SPA navigations included, with no code. Never `nuxi dev`, a preview build, a credential-less
42
+ build or a Studio preview frame. New module option `analytics: false | { enabled?, eventOrigin? }`
43
+ (env `ELDRA_ANALYTICS=off`, `ELDRA_ANALYTICS_ORIGIN`) on `runtimeConfig.public.eldra.analytics`; an
44
+ invalid `eventOrigin` is warned about and ignored. New auto-import `useEldraAnalytics()` returns
45
+ `{ track(name, props?), enabled }`, a no-op wherever tracking is off. No cookie or storage identifier.
46
+ Documented in `docs/themes.md`.
47
+
48
+ - **Structured data: `useStructuredData`, `provideStructuredData`, `useSiteProfile`.** Writes a
49
+ page's schema.org JSON-LD (nodes from `@eldrajs/theme-core`'s builders) into the head as one
50
+ `<script type="application/ld+json">` under a fixed key, for `enabled` pages only (pass
51
+ `!seo.noindex`). New module option `structuredData: { disable }` (`true`, or the node kinds
52
+ `product`, `breadcrumb`, `itemList`, `organization`, `website`) on `runtimeConfig.public.eldra`;
53
+ editing a node at runtime is `provideStructuredData((type, node, { path, locale }) => node |
54
+ null)`. The build reads the shop's profile from `GET /site/v1/site-profile` (`readSiteProfile`,
55
+ `./runtime/siteProfile.ts`; fail-soft like the other platform reads, build-only) and carries it,
56
+ with the site name and the site icon's 512 px rendering filling its gaps, on
57
+ `runtimeConfig.public.eldra.siteProfile`; `useSiteProfile()` returns it with the site origin.
58
+ Documented in `docs/theme-seo.md`.
59
+
60
+ - **`sitemap.xml` and `robots.txt`, generated from the prerendered routes.** `nuxi generate` writes
61
+ both into the static output. A preview build (the default) writes `Disallow: /` and no sitemap; a
62
+ production build (`ELDRA_BUILD_TARGET=production`) writes `Allow: /`, the merchant's own lines
63
+ and the sitemap line, and a sitemap with every content path once per locale, `xhtml:link`
64
+ hreflang alternates plus `x-default`, `lastmod` from the entry's or product's `updatedAt`, noindex
65
+ pages left out and a same-origin `seo.canonicalUrl` as the `loc`. It splits into a
66
+ `sitemapindex` and children past 50,000 URLs or 50 MiB. The origin is `ELDRA_SITE_URL`, else the
67
+ production URL from a seventh fail-soft read, `GET /site/v1/crawl` (`readCrawlSettings`,
68
+ `./runtime/crawl.ts`, production builds only); with neither, nothing is written and one line says
69
+ why. A theme's own `public/robots.txt` or `public/sitemap.xml` is never replaced (one line, `[eldra]
70
+ <file> generation skipped: theme ships its own`). New module option `sitemap` (`false`, or
71
+ `{ maxUrls, maxBytes }`). The head's hreflang `<link>`s are absolute when the origin is known. The
72
+ runtime `eldraSeo.siteUrl` now follows the same origin. Documented in `docs/theme-seo.md`.
73
+
74
+ - **Page titles and SEO metadata, set in Studio.** A sixth fail-soft read, `GET /site/v1/seo`
75
+ (`readSeo`, `./runtime/seo.ts`), carries the site's title pattern, description, share image,
76
+ Twitter handle and per-context patterns (one warning and the default pattern
77
+ `{{page.title}} · {{site.name}}` when it fails). A new auto-imported composable,
78
+ `useEldraSeo(context, data, options?)`, sets `<title>`, description, canonical link, `og:*`,
79
+ `twitter:*` and `robots` through the resolver in `@eldrajs/theme-core`. New module options
80
+ `siteUrl` (`ELDRA_SITE_URL`; without it no canonical, `og:url` or relative image is written) and
81
+ `buildTarget` (`ELDRA_BUILD_TARGET`): anything but `production` is a preview build, and a preview
82
+ build, `nuxi dev` and a page framed by Studio are always `noindex`. The public runtime config
83
+ gains `eldraSeo`. Documented in `docs/theme-seo.md`.
84
+
85
+ - The runtime registers the theme's own id (`manifest.theme.id`) with `registerBlockFields`, and
86
+ the draft projection validates slots against bare block ids when a published entry's
87
+ `schemaApiId` is `<themeId>:<apiId>`. Route-template targets (a merchant's own schema) and
88
+ `catalog:*` are unchanged. The theme must declare `eldra.themeId` in `package.json` (see the
89
+ `@eldrajs/vite-plugin-theme` changelog).
90
+
91
+ - **Site icons, set in Studio and rendered by the media worker.** A fifth fail-soft read, `GET
92
+ /site/v1/site-icons` (`readSiteIcons`, `./runtime/siteIcons.ts`), answers the site's icon (a
93
+ media-library raster, square, at least 512 px), background colour, theme colour, short name and
94
+ `icons`, the URLs of the variants the media worker renders (`null` when no icon is set). When an
95
+ icon is set, `nuxi generate` writes only `site.webmanifest` into the static output (on both
96
+ nitro `compiled` and `prerender:done`) and adds `<link rel="icon" type="image/png"
97
+ sizes="32x32">`, `<link rel="apple-touch-icon">`, `<link rel="manifest">` and `<meta
98
+ name="theme-color">` to every page; the icon tags point at the media URLs. No image is fetched or
99
+ processed at build time and no `favicon.ico` is generated (the theme's own `public/favicon.ico`
100
+ stays the root fallback). The theme colour defaults to the primary design token and the short name
101
+ to the site name. With no icon set or a failed read, nothing is written or tagged and the theme's
102
+ `public/` files stay. The icons replace the theme's own icon, manifest and `theme-color` tags in
103
+ `app.head`. `sharp` was removed (an earlier draft of this feature generated the files with it):
104
+ native image processing in every theme build was fragile, and the media worker renders the sizes.
105
+ Documented in `docs/themes.md` (Site icons).
106
+
8
107
  - **The deployed site now carries Studio's design-token overrides, not only the open preview.** A
9
108
  fourth fail-soft read, alongside the store's currency, its locales and the theme-message overrides
10
109
  — `GET /site/v1/design-tokens`, same client, same retry policy, absent gateway or any error
package/dist/module.d.mts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { NuxtModule } from '@nuxt/schema';
2
- import { EldraRetryOptions } from '@eldrajs/theme-core';
3
- import { ManifestRoute, DeclaredThemeCodePage, DeclaredSeed, ManifestTemplateRoles } from '@eldrajs/vite-plugin-theme';
2
+ import { EldraRetryOptions, StructuredDataType, SitemapLimits } from '@eldrajs/theme-core';
3
+ import { ManifestRoute, DeclaredThemeCodePage, DeclaredSeed, ManifestTemplateRoles, DeclaredFormSeed } from '@eldrajs/vite-plugin-theme';
4
4
  import { LayoutBreakpoints } from '@eldrajs/theme-core/layout';
5
+ import { AnalyticsOption } from '../dist/runtime/analytics.js';
5
6
 
6
7
  interface ModuleOptions {
7
8
  gatewayUrl: string;
@@ -22,6 +23,13 @@ interface ModuleOptions {
22
23
  * `templates` layouts may reference. See that package's changelog for the
23
24
  * validation rules. */
24
25
  templateRoles?: ManifestTemplateRoles;
26
+ /** The forms a site is created with on its first deploy (at most 8). The build also reads each
27
+ * one's definition from the platform and bakes it into the site, so a form renders with no
28
+ * request in the visitor's browser. Never overwrites a form the merchant has edited. */
29
+ formSeeds?: DeclaredFormSeed[];
30
+ /** Further form keys to bake at build time, for forms a theme references that it does not seed
31
+ * (a merchant-made form a block names by default). Each read is independently fail-soft. */
32
+ forms?: string[];
25
33
  tailwind?: boolean;
26
34
  /** The theme's own tablet/normal layout breakpoints (min-width px), so
27
35
  * Studio's UI can react to the theme's actual ranges (its side panels
@@ -49,6 +57,44 @@ interface ModuleOptions {
49
57
  * storefront building its own commerce client reads the same policy.
50
58
  */
51
59
  retry?: EldraRetryOptions;
60
+ /**
61
+ * The site's public origin (`https://shop.example`), used for canonical URLs and absolute share
62
+ * images. Defaults to `ELDRA_SITE_URL`. Without it no canonical or `og:url` is written, because
63
+ * both must be absolute and a guessed host is worse than none.
64
+ */
65
+ siteUrl?: string;
66
+ /**
67
+ * Which schema.org JSON-LD a page may write (`useStructuredData`): `disable` is `true` for none,
68
+ * or the node kinds to leave out (`'product' | 'breadcrumb' | 'itemList' | 'organization' |
69
+ * 'website'`). A function cannot be serialised into the runtime config, so editing a node is
70
+ * `provideStructuredData(extend)` at runtime instead.
71
+ */
72
+ structuredData?: {
73
+ disable?: StructuredDataType[] | boolean;
74
+ };
75
+ /**
76
+ * `'production'` for the build that serves the public site (the default); `'preview'` is a preview
77
+ * build, which is always `noindex`. Defaults to `ELDRA_BUILD_TARGET`: production unless that is
78
+ * `preview`.
79
+ */
80
+ buildTarget?: 'production' | 'preview';
81
+ /**
82
+ * `sitemap.xml` (and `robots.txt`) generation. Both are written into the static output of a
83
+ * `nuxi generate`/`build` from the prerendered routes; a `public/robots.txt` or
84
+ * `public/sitemap.xml` of the theme's own is never replaced. `false` turns the sitemap off.
85
+ * The limits are sitemaps.org's (50,000 URLs, 50 MiB per file) and exist as options for tests.
86
+ */
87
+ sitemap?: false | SitemapLimits;
88
+ /**
89
+ * Built-in analytics on the deployed site: the Eldra tracker (`@eldrajs/sdk`'s
90
+ * `analyticsTrackerScript`) is loaded on **production** builds that have an organisation id —
91
+ * never under `nuxi dev`, in a preview build, in a Studio preview frame or without credentials —
92
+ * and `useEldraAnalytics().track()` sends custom events. `false` (or `{ enabled: false }`, or
93
+ * `ELDRA_ANALYTICS=off`) opts out. `eventOrigin` (or `ELDRA_ANALYTICS_ORIGIN`) is a first-party
94
+ * origin (`https://shop.example`, no path) that receives events instead of the gateway, for a
95
+ * proxy on the site's own domain. No cookie or storage identifier is written.
96
+ */
97
+ analytics?: AnalyticsOption;
52
98
  }
53
99
  declare const eldraModule: NuxtModule<ModuleOptions>;
54
100
 
package/dist/module.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  import { NuxtModule } from '@nuxt/schema';
2
- import { EldraRetryOptions } from '@eldrajs/theme-core';
3
- import { ManifestRoute, DeclaredThemeCodePage, DeclaredSeed, ManifestTemplateRoles } from '@eldrajs/vite-plugin-theme';
2
+ import { EldraRetryOptions, StructuredDataType, SitemapLimits } from '@eldrajs/theme-core';
3
+ import { ManifestRoute, DeclaredThemeCodePage, DeclaredSeed, ManifestTemplateRoles, DeclaredFormSeed } from '@eldrajs/vite-plugin-theme';
4
4
  import { LayoutBreakpoints } from '@eldrajs/theme-core/layout';
5
+ import { AnalyticsOption } from '../dist/runtime/analytics.js';
5
6
 
6
7
  interface ModuleOptions {
7
8
  gatewayUrl: string;
@@ -22,6 +23,13 @@ interface ModuleOptions {
22
23
  * `templates` layouts may reference. See that package's changelog for the
23
24
  * validation rules. */
24
25
  templateRoles?: ManifestTemplateRoles;
26
+ /** The forms a site is created with on its first deploy (at most 8). The build also reads each
27
+ * one's definition from the platform and bakes it into the site, so a form renders with no
28
+ * request in the visitor's browser. Never overwrites a form the merchant has edited. */
29
+ formSeeds?: DeclaredFormSeed[];
30
+ /** Further form keys to bake at build time, for forms a theme references that it does not seed
31
+ * (a merchant-made form a block names by default). Each read is independently fail-soft. */
32
+ forms?: string[];
25
33
  tailwind?: boolean;
26
34
  /** The theme's own tablet/normal layout breakpoints (min-width px), so
27
35
  * Studio's UI can react to the theme's actual ranges (its side panels
@@ -49,6 +57,44 @@ interface ModuleOptions {
49
57
  * storefront building its own commerce client reads the same policy.
50
58
  */
51
59
  retry?: EldraRetryOptions;
60
+ /**
61
+ * The site's public origin (`https://shop.example`), used for canonical URLs and absolute share
62
+ * images. Defaults to `ELDRA_SITE_URL`. Without it no canonical or `og:url` is written, because
63
+ * both must be absolute and a guessed host is worse than none.
64
+ */
65
+ siteUrl?: string;
66
+ /**
67
+ * Which schema.org JSON-LD a page may write (`useStructuredData`): `disable` is `true` for none,
68
+ * or the node kinds to leave out (`'product' | 'breadcrumb' | 'itemList' | 'organization' |
69
+ * 'website'`). A function cannot be serialised into the runtime config, so editing a node is
70
+ * `provideStructuredData(extend)` at runtime instead.
71
+ */
72
+ structuredData?: {
73
+ disable?: StructuredDataType[] | boolean;
74
+ };
75
+ /**
76
+ * `'production'` for the build that serves the public site (the default); `'preview'` is a preview
77
+ * build, which is always `noindex`. Defaults to `ELDRA_BUILD_TARGET`: production unless that is
78
+ * `preview`.
79
+ */
80
+ buildTarget?: 'production' | 'preview';
81
+ /**
82
+ * `sitemap.xml` (and `robots.txt`) generation. Both are written into the static output of a
83
+ * `nuxi generate`/`build` from the prerendered routes; a `public/robots.txt` or
84
+ * `public/sitemap.xml` of the theme's own is never replaced. `false` turns the sitemap off.
85
+ * The limits are sitemaps.org's (50,000 URLs, 50 MiB per file) and exist as options for tests.
86
+ */
87
+ sitemap?: false | SitemapLimits;
88
+ /**
89
+ * Built-in analytics on the deployed site: the Eldra tracker (`@eldrajs/sdk`'s
90
+ * `analyticsTrackerScript`) is loaded on **production** builds that have an organisation id —
91
+ * never under `nuxi dev`, in a preview build, in a Studio preview frame or without credentials —
92
+ * and `useEldraAnalytics().track()` sends custom events. `false` (or `{ enabled: false }`, or
93
+ * `ELDRA_ANALYTICS=off`) opts out. `eventOrigin` (or `ELDRA_ANALYTICS_ORIGIN`) is a first-party
94
+ * origin (`https://shop.example`, no path) that receives events instead of the gateway, for a
95
+ * proxy on the site's own domain. No cookie or storage identifier is written.
96
+ */
97
+ analytics?: AnalyticsOption;
52
98
  }
53
99
  declare const eldraModule: NuxtModule<ModuleOptions>;
54
100
 
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=3.13.0"
6
6
  },
7
- "version": "0.1.1",
7
+ "version": "0.3.0",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "0.8.4",
10
10
  "unbuild": "unknown"
package/dist/module.mjs CHANGED
@@ -1,16 +1,37 @@
1
1
  import { mkdirSync, existsSync, readFileSync, writeFileSync, copyFileSync, cpSync } from 'node:fs';
2
- import { join } from 'node:path';
2
+ import { join, resolve } from 'node:path';
3
3
  import { defineNuxtModule, createResolver, addVitePlugin, addPlugin, addImports } from '@nuxt/kit';
4
4
  import { createEldraClient, resolvePagePath, parseDynamicRoutePattern, catalogRouteTarget, buildDynamicRoutePath, normalizeThemeDesignTokens, EldraClientError, stripStega } from '@eldrajs/theme-core';
5
5
  import { createEldraClient as createEldraClient$1 } from '@eldrajs/sdk';
6
6
  import eldraTheme from '@eldrajs/vite-plugin-theme';
7
- import { listCatalogDocs, catalogDocRoutes } from '../dist/runtime/catalog.js';
7
+ import { listCatalogDocs, catalogDocRouteRefs } from '../dist/runtime/catalog.js';
8
+ import { resolveAnalyticsConfig } from '../dist/runtime/analytics.js';
9
+ import { readCrawlSettings } from '../dist/runtime/crawl.js';
10
+ import { buildCrawlFiles } from '../dist/runtime/crawlOutput.js';
11
+ import { readRedirects, buildRedirectsFile, readThemeRedirects } from '../dist/runtime/redirects.js';
8
12
  import { readStoreCommerce } from '../dist/runtime/commerce.js';
9
13
  import { readDesignTokens } from '../dist/runtime/designTokens.js';
14
+ import { readFormDefinitions } from '../dist/runtime/forms.js';
15
+ import { buildSiteIconOutput } from '../dist/runtime/siteIconAssets.js';
10
16
  import { normalizeLocale } from '../dist/runtime/locale.js';
11
17
  import { resolveLocaleRouting, readStoreLocales, localePathFor } from '../dist/runtime/locales.js';
12
18
  import { readThemeMessages, resolveSiteMessages } from '../dist/runtime/messages.js';
13
19
  import { listAllEntries } from '../dist/runtime/resolveRoute.js';
20
+ import { readSeo } from '../dist/runtime/seo.js';
21
+ import { readSiteIcons, resolveSiteIcons } from '../dist/runtime/siteIcons.js';
22
+ import { readSiteProfile, resolveSiteProfile } from '../dist/runtime/siteProfile.js';
23
+
24
+ function resolveBuildTarget(value, warn = (message) => console.warn(message)) {
25
+ const target = value?.trim().toLowerCase() ?? "";
26
+ if (target === "preview")
27
+ return "preview";
28
+ if (target !== "" && target !== "production") {
29
+ warn(
30
+ `[eldra] ELDRA_BUILD_TARGET="${value}" is not "production" or "preview"; treating this as a production build.`
31
+ );
32
+ }
33
+ return "production";
34
+ }
14
35
 
15
36
  const eldraModule = defineNuxtModule({
16
37
  meta: {
@@ -27,17 +48,20 @@ const eldraModule = defineNuxtModule({
27
48
  studioOrigins: [],
28
49
  pageSchema: "page",
29
50
  routeTemplateSchema: "route-template",
30
- tailwind: false
51
+ tailwind: false,
52
+ siteUrl: process.env.ELDRA_SITE_URL ?? ""
31
53
  },
32
54
  async setup(options, nuxt) {
33
55
  const resolver = createResolver(import.meta.url);
34
56
  const studioOrigins = validateStudioOrigins(options.studioOrigins);
57
+ const buildTarget = options.buildTarget ?? resolveBuildTarget(process.env.ELDRA_BUILD_TARGET);
35
58
  const themeOptions = {
36
59
  framework: "nuxt",
37
60
  routes: options.routes,
38
61
  customPages: options.customPages,
39
62
  templates: options.templates,
40
63
  templateRoles: options.templateRoles,
64
+ formSeeds: options.formSeeds,
41
65
  themeDir: nuxt.options.rootDir,
42
66
  tailwind: options.tailwind,
43
67
  breakpoints: options.breakpoints
@@ -73,13 +97,50 @@ const eldraModule = defineNuxtModule({
73
97
  // `null`, not `undefined`: the key has to survive the payload so a
74
98
  // storefront's own client (`examples/starter-nuxt`'s storefront plugin)
75
99
  // reads the same policy the module's reads use.
76
- retry: options.retry ?? null
100
+ retry: options.retry ?? null,
101
+ // Which structured-data nodes pages may write; `useStructuredData` reads it. `false` rather
102
+ // than `undefined`: the key has to survive the payload.
103
+ structuredData: { disable: options.structuredData?.disable ?? false },
104
+ // The `Organization` node's inputs (name, logo, social links, contact), filled in below once
105
+ // the platform read settles. Written here first for the same reason `commerce` is.
106
+ siteProfile: null,
107
+ // The form definitions the build baked (`./runtime/forms.ts`), filled in below once the
108
+ // platform read settles. Written here first for the same reason `commerce` is.
109
+ forms: {},
110
+ // Whether the deployed site reports to the Eldra tracker, and to which origin; see
111
+ // `./runtime/analytics.ts` and the `analytics` option.
112
+ analytics: resolveAnalyticsConfig({
113
+ option: options.analytics,
114
+ env: process.env,
115
+ dev: nuxt.options.dev,
116
+ production: buildTarget === "production",
117
+ orgId: options.orgId
118
+ })
119
+ };
120
+ nuxt.options.runtimeConfig.public.eldraSeo = {
121
+ setting: null,
122
+ siteUrl: options.siteUrl ?? "",
123
+ siteName: seoSiteName(nuxt.options.app.head.title),
124
+ isPreview: nuxt.options.dev || buildTarget !== "production"
77
125
  };
78
126
  addPlugin(resolver.resolve("./runtime/plugin"));
127
+ addPlugin(resolver.resolve("./runtime/analyticsPlugin"));
79
128
  addImports([
80
129
  { name: "useEldraPage", from: resolver.resolve("./runtime/composables/useEldraPage") },
130
+ { name: "useEldraSeo", from: resolver.resolve("./runtime/composables/useEldraSeo") },
131
+ {
132
+ name: "useEldraAnalytics",
133
+ from: resolver.resolve("./runtime/composables/useEldraAnalytics")
134
+ },
135
+ // schema.org JSON-LD: write a page's nodes (opt-out per kind via the `structuredData` option,
136
+ // runtime edits via `provideStructuredData`) and read the shop's profile for `Organization`.
137
+ ...["useStructuredData", "provideStructuredData", "useSiteProfile"].map((name) => ({
138
+ name,
139
+ from: resolver.resolve("./runtime/composables/useStructuredData")
140
+ })),
81
141
  // The route key a theme's catch-all page gives `<NuxtPage>`; see `./runtime/routePath`.
82
142
  { name: "eldraRouteKey", from: resolver.resolve("./runtime/routePath") },
143
+ { name: "useEldraForms", from: resolver.resolve("./runtime/composables/useEldraForms") },
83
144
  { name: "useEldra", from: "@eldrajs/theme-vue" },
84
145
  // The active content locale and the path helpers around it. Re-exported from theme-vue
85
146
  // rather than defined here: the state lives on the theme context so a **block** can read it
@@ -90,6 +151,10 @@ const eldraModule = defineNuxtModule({
90
151
  { name: "useEldraPreview", from: "@eldrajs/theme-vue" }
91
152
  ]);
92
153
  let localeRouting = resolveLocaleRouting(null, options.locale);
154
+ const crawlRoutes = [];
155
+ let crawlSetting = null;
156
+ let crawlSiteUrl = options.siteUrl ?? "";
157
+ let redirectsSetting = null;
93
158
  nuxt.hook("prerender:routes", async (ctx) => {
94
159
  if (options.gatewayUrl === "" || options.orgId === "") {
95
160
  console.warn('[eldra] ELDRA_GATEWAY_URL / ELDRA_ORG_ID not set \u2014 prerendering "/" only');
@@ -107,7 +172,8 @@ const eldraModule = defineNuxtModule({
107
172
  listRouteTemplateEntries(client, options.routeTemplateSchema, locale)
108
173
  ]);
109
174
  const generated = /* @__PURE__ */ new Set();
110
- const addRoute = (path) => {
175
+ const addRoute = (path, meta = {}) => {
176
+ crawlRoutes.push({ path, ...meta });
111
177
  ctx.routes.add(path);
112
178
  for (const prefixed of localeRouting.prefixed) {
113
179
  ctx.routes.add(localePathFor(path, prefixed, localeRouting));
@@ -116,7 +182,7 @@ const eldraModule = defineNuxtModule({
116
182
  for (const page of pages) {
117
183
  const path = resolvePagePath(page, pages);
118
184
  generated.add(path);
119
- addRoute(path);
185
+ addRoute(path, { lastmod: page.updatedAt, seo: page.data.seo });
120
186
  }
121
187
  const codeOwned = new Set((options.customPages ?? []).map((page) => page.path));
122
188
  const entriesBySchema = /* @__PURE__ */ new Map();
@@ -136,7 +202,11 @@ const eldraModule = defineNuxtModule({
136
202
  catalogPromise = listCatalogDocs(client, catalogKind, locale);
137
203
  catalogByKind.set(catalogKind, catalogPromise);
138
204
  }
139
- for (const path of catalogDocRoutes(catalogKind, await catalogPromise, pattern)) {
205
+ for (const { path, doc } of catalogDocRouteRefs(
206
+ catalogKind,
207
+ await catalogPromise,
208
+ pattern
209
+ )) {
140
210
  if (codeOwned.has(path))
141
211
  continue;
142
212
  if (generated.has(path)) {
@@ -144,7 +214,7 @@ const eldraModule = defineNuxtModule({
144
214
  continue;
145
215
  }
146
216
  generated.add(path);
147
- addRoute(path);
217
+ addRoute(path, { lastmod: doc.updatedAt, seo: template.data.seo });
148
218
  }
149
219
  continue;
150
220
  }
@@ -166,17 +236,82 @@ const eldraModule = defineNuxtModule({
166
236
  );
167
237
  }
168
238
  generated.add(path);
169
- addRoute(path);
239
+ addRoute(path, {
240
+ lastmod: entry.updatedAt,
241
+ seo: entry.data.seo,
242
+ templateSeo: template.data.seo
243
+ });
170
244
  }
171
245
  }
246
+ for (const page of options.customPages ?? []) {
247
+ if (/[:*]/.test(page.path) || generated.has(page.path))
248
+ continue;
249
+ crawlRoutes.push({ path: page.path, codeOwned: true });
250
+ }
172
251
  });
252
+ let siteIconFiles = [];
173
253
  nuxt.hooks.hook(
174
254
  "nitro:init",
175
255
  (nitro) => {
256
+ const writeSiteIconFiles = (publicDir) => {
257
+ if (siteIconFiles.length === 0)
258
+ return;
259
+ mkdirSync(publicDir, { recursive: true });
260
+ for (const file of siteIconFiles)
261
+ writeFileSync(join(publicDir, file.name), file.data);
262
+ };
263
+ const crawlLogged = /* @__PURE__ */ new Set();
264
+ const writeCrawlFiles = (publicDir) => {
265
+ const files = buildCrawlFiles({
266
+ target: buildTarget === "production" ? "production" : "preview",
267
+ siteUrl: crawlSiteUrl,
268
+ robotsExtra: crawlSetting?.robotsExtra,
269
+ routes: crawlRoutes,
270
+ routing: localeRouting,
271
+ sitemap: options.sitemap,
272
+ themePublicDir: resolve(nuxt.options.rootDir, nuxt.options.dir.public ?? "public"),
273
+ log: (message) => {
274
+ if (crawlLogged.has(message))
275
+ return;
276
+ crawlLogged.add(message);
277
+ console.warn(message);
278
+ }
279
+ });
280
+ if (files.length === 0)
281
+ return;
282
+ mkdirSync(publicDir, { recursive: true });
283
+ for (const file of files)
284
+ writeFileSync(join(publicDir, file.name), file.content);
285
+ };
286
+ const writeRedirects = (publicDir) => {
287
+ const built = buildRedirectsFile(
288
+ redirectsSetting?.rules ?? [],
289
+ localeRouting,
290
+ readThemeRedirects(resolve(nuxt.options.rootDir, nuxt.options.dir.public ?? "public"))
291
+ );
292
+ for (const warning of built.warnings) {
293
+ if (crawlLogged.has(warning))
294
+ continue;
295
+ crawlLogged.add(warning);
296
+ console.warn(warning);
297
+ }
298
+ if (built.content === null)
299
+ return;
300
+ mkdirSync(publicDir, { recursive: true });
301
+ writeFileSync(join(publicDir, "_redirects"), built.content);
302
+ };
303
+ nitro.hooks.hook("compiled", () => {
304
+ writeSiteIconFiles(nitro.options.output.publicDir);
305
+ writeCrawlFiles(nitro.options.output.publicDir);
306
+ writeRedirects(nitro.options.output.publicDir);
307
+ });
176
308
  nitro.hooks.hook("prerender:done", () => {
177
309
  const publicDir = nitro.options.output.publicDir;
178
310
  mkdirSync(publicDir, { recursive: true });
179
311
  copyGeneratedManifest(nuxt.options.rootDir, publicDir);
312
+ writeSiteIconFiles(publicDir);
313
+ writeCrawlFiles(publicDir);
314
+ writeRedirects(publicDir);
180
315
  const target = join(publicDir, "_headers");
181
316
  const existing = existsSync(target) ? readFileSync(target, "utf8").replace(/^\s*Content-Security-Policy:\s*frame-ancestors[^\r\n]*(?:\r?\n|$)/gim, "").trimEnd() + "\n\n" : "";
182
317
  const ancestors = ["'self'", ...studioOrigins].join(" ");
@@ -199,16 +334,75 @@ const eldraModule = defineNuxtModule({
199
334
  orgId: options.orgId,
200
335
  retry: options.retry
201
336
  });
202
- const [commerce, locales, platformMessages, platformDesignTokens] = await Promise.all([
337
+ const [
338
+ commerce,
339
+ locales,
340
+ platformMessages,
341
+ platformDesignTokens,
342
+ platformSiteIcons,
343
+ platformSeo,
344
+ platformSiteProfile,
345
+ platformCrawl,
346
+ platformForms,
347
+ platformRedirects
348
+ ] = await Promise.all([
203
349
  readStoreCommerce(platformClient),
204
350
  readStoreLocales(platformClient),
205
351
  readThemeMessages(platformClient),
206
- readDesignTokens(platformClient)
352
+ readDesignTokens(platformClient),
353
+ nuxt.options.dev ? Promise.resolve(null) : readSiteIcons(platformClient),
354
+ nuxt.options.dev ? Promise.resolve(null) : readSeo(platformClient),
355
+ // The site profile is the eighth read, on the same terms (build-only, fail-soft).
356
+ nuxt.options.dev ? Promise.resolve(null) : readSiteProfile(platformClient),
357
+ // The crawl settings matter only to a production build: a preview build writes `Disallow: /`
358
+ // and no sitemap whatever they say.
359
+ nuxt.options.dev || buildTarget !== "production" ? Promise.resolve(null) : readCrawlSettings(platformClient),
360
+ // The form definitions the theme seeds or names, one independently fail-soft read each.
361
+ // Build-only: `nuxi dev` has nothing to bake, and the storefront fetches them live there.
362
+ nuxt.options.dev ? Promise.resolve({}) : readFormDefinitions(platformClient, [
363
+ ...(options.formSeeds ?? []).map((seed) => seed.key),
364
+ ...options.forms ?? []
365
+ ]),
366
+ // The redirect rules are a tenth read on the same terms (build-only, fail-soft): they become
367
+ // the platform block of the static output's `_redirects`.
368
+ nuxt.options.dev ? Promise.resolve(null) : readRedirects(platformClient)
207
369
  ]);
370
+ crawlSetting = platformCrawl;
371
+ redirectsSetting = platformRedirects;
372
+ crawlSiteUrl = options.siteUrl || platformCrawl?.siteUrl || "";
373
+ nuxt.options.runtimeConfig.public.eldraSeo.siteUrl = crawlSiteUrl;
208
374
  const runtimeEldra = nuxt.options.runtimeConfig.public.eldra;
209
375
  runtimeEldra.commerce = commerce;
210
376
  runtimeEldra.locales = locales;
211
377
  runtimeEldra.designTokens = platformDesignTokens;
378
+ runtimeEldra.forms = platformForms;
379
+ nuxt.options.runtimeConfig.public.eldraSeo.setting = platformSeo;
380
+ runtimeEldra.siteProfile = resolveSiteProfile(platformSiteProfile, {
381
+ siteName: platformSeoName(platformSeo) || seoSiteName(nuxt.options.app.head.title) || "",
382
+ iconLogoUrl: platformSiteIcons?.icons?.icon512 ?? null
383
+ });
384
+ const resolvedSiteIcons = resolveSiteIcons(platformSiteIcons, {
385
+ siteName: platformSeoName(platformSeo) || siteName(nuxt.options.app.head.title, nuxt.options.rootDir),
386
+ primaryToken: platformDesignTokens?.colors.primary?.value ?? themePrimaryToken(nuxt.options.rootDir)
387
+ });
388
+ const siteIcons = resolvedSiteIcons === null ? null : buildSiteIconOutput(resolvedSiteIcons, nuxt.options.app.baseURL);
389
+ if (siteIcons !== null) {
390
+ siteIconFiles = siteIcons.files;
391
+ const replacedRels = /* @__PURE__ */ new Set(["icon", "shortcut icon", "apple-touch-icon", "manifest"]);
392
+ const generatesThemeColor = siteIcons.meta.some((tag) => tag.name === "theme-color");
393
+ nuxt.options.app.head.link = [
394
+ ...(nuxt.options.app.head.link ?? []).filter(
395
+ (tag) => !replacedRels.has(String(tag.rel ?? "").toLowerCase())
396
+ ),
397
+ ...siteIcons.link
398
+ ];
399
+ nuxt.options.app.head.meta = [
400
+ ...(nuxt.options.app.head.meta ?? []).filter(
401
+ (tag) => !generatesThemeColor || String(tag.name ?? "").toLowerCase() !== "theme-color"
402
+ ),
403
+ ...siteIcons.meta
404
+ ];
405
+ }
212
406
  localeRouting = resolveLocaleRouting(locales, options.locale);
213
407
  themeOptions.resolveMessages = (manifestMessages) => resolveSiteMessages(manifestMessages, platformMessages, locales);
214
408
  themeOptions.resolveTokens = (manifestTokens) => platformDesignTokens ?? normalizeThemeDesignTokens(manifestTokens);
@@ -248,6 +442,32 @@ function packageVersion(path) {
248
442
  return "0.0.0";
249
443
  }
250
444
  }
445
+ function platformSeoName(setting) {
446
+ return setting?.site.name?.trim() ?? "";
447
+ }
448
+ function seoSiteName(title) {
449
+ return typeof title === "string" ? title.trim() : "";
450
+ }
451
+ function siteName(title, rootDir) {
452
+ if (typeof title === "string" && title.trim() !== "")
453
+ return title;
454
+ try {
455
+ const pkg = JSON.parse(readFileSync(join(rootDir, "package.json"), "utf8"));
456
+ return typeof pkg.name === "string" ? pkg.name.replace(/^@[^/]+\//, "") : null;
457
+ } catch {
458
+ return null;
459
+ }
460
+ }
461
+ function themePrimaryToken(rootDir) {
462
+ try {
463
+ const tokens = normalizeThemeDesignTokens(
464
+ JSON.parse(readFileSync(join(rootDir, "tokens.json"), "utf8"))
465
+ );
466
+ return tokens.colors.primary?.value ?? null;
467
+ } catch {
468
+ return null;
469
+ }
470
+ }
251
471
  function copyGeneratedManifest(rootDir, publicDir) {
252
472
  const sourceDir = join(rootDir, ".eldra");
253
473
  const sourceManifest = join(sourceDir, "manifest.json");