@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
package/CHANGELOG.md CHANGED
@@ -5,6 +5,83 @@ 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
+
8
85
  - The runtime registers the theme's own id (`manifest.theme.id`) with `registerBlockFields`, and
9
86
  the draft projection validates slots against bare block ids when a published entry's
10
87
  `schemaApiId` is `<themeId>:<apiId>`. Route-template targets (a merchant's own schema) and
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.2.0",
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,18 +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';
10
15
  import { buildSiteIconOutput } from '../dist/runtime/siteIconAssets.js';
11
16
  import { normalizeLocale } from '../dist/runtime/locale.js';
12
17
  import { resolveLocaleRouting, readStoreLocales, localePathFor } from '../dist/runtime/locales.js';
13
18
  import { readThemeMessages, resolveSiteMessages } from '../dist/runtime/messages.js';
14
19
  import { listAllEntries } from '../dist/runtime/resolveRoute.js';
20
+ import { readSeo } from '../dist/runtime/seo.js';
15
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
+ }
16
35
 
17
36
  const eldraModule = defineNuxtModule({
18
37
  meta: {
@@ -29,17 +48,20 @@ const eldraModule = defineNuxtModule({
29
48
  studioOrigins: [],
30
49
  pageSchema: "page",
31
50
  routeTemplateSchema: "route-template",
32
- tailwind: false
51
+ tailwind: false,
52
+ siteUrl: process.env.ELDRA_SITE_URL ?? ""
33
53
  },
34
54
  async setup(options, nuxt) {
35
55
  const resolver = createResolver(import.meta.url);
36
56
  const studioOrigins = validateStudioOrigins(options.studioOrigins);
57
+ const buildTarget = options.buildTarget ?? resolveBuildTarget(process.env.ELDRA_BUILD_TARGET);
37
58
  const themeOptions = {
38
59
  framework: "nuxt",
39
60
  routes: options.routes,
40
61
  customPages: options.customPages,
41
62
  templates: options.templates,
42
63
  templateRoles: options.templateRoles,
64
+ formSeeds: options.formSeeds,
43
65
  themeDir: nuxt.options.rootDir,
44
66
  tailwind: options.tailwind,
45
67
  breakpoints: options.breakpoints
@@ -75,13 +97,50 @@ const eldraModule = defineNuxtModule({
75
97
  // `null`, not `undefined`: the key has to survive the payload so a
76
98
  // storefront's own client (`examples/starter-nuxt`'s storefront plugin)
77
99
  // reads the same policy the module's reads use.
78
- 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"
79
125
  };
80
126
  addPlugin(resolver.resolve("./runtime/plugin"));
127
+ addPlugin(resolver.resolve("./runtime/analyticsPlugin"));
81
128
  addImports([
82
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
+ })),
83
141
  // The route key a theme's catch-all page gives `<NuxtPage>`; see `./runtime/routePath`.
84
142
  { name: "eldraRouteKey", from: resolver.resolve("./runtime/routePath") },
143
+ { name: "useEldraForms", from: resolver.resolve("./runtime/composables/useEldraForms") },
85
144
  { name: "useEldra", from: "@eldrajs/theme-vue" },
86
145
  // The active content locale and the path helpers around it. Re-exported from theme-vue
87
146
  // rather than defined here: the state lives on the theme context so a **block** can read it
@@ -92,6 +151,10 @@ const eldraModule = defineNuxtModule({
92
151
  { name: "useEldraPreview", from: "@eldrajs/theme-vue" }
93
152
  ]);
94
153
  let localeRouting = resolveLocaleRouting(null, options.locale);
154
+ const crawlRoutes = [];
155
+ let crawlSetting = null;
156
+ let crawlSiteUrl = options.siteUrl ?? "";
157
+ let redirectsSetting = null;
95
158
  nuxt.hook("prerender:routes", async (ctx) => {
96
159
  if (options.gatewayUrl === "" || options.orgId === "") {
97
160
  console.warn('[eldra] ELDRA_GATEWAY_URL / ELDRA_ORG_ID not set \u2014 prerendering "/" only');
@@ -109,7 +172,8 @@ const eldraModule = defineNuxtModule({
109
172
  listRouteTemplateEntries(client, options.routeTemplateSchema, locale)
110
173
  ]);
111
174
  const generated = /* @__PURE__ */ new Set();
112
- const addRoute = (path) => {
175
+ const addRoute = (path, meta = {}) => {
176
+ crawlRoutes.push({ path, ...meta });
113
177
  ctx.routes.add(path);
114
178
  for (const prefixed of localeRouting.prefixed) {
115
179
  ctx.routes.add(localePathFor(path, prefixed, localeRouting));
@@ -118,7 +182,7 @@ const eldraModule = defineNuxtModule({
118
182
  for (const page of pages) {
119
183
  const path = resolvePagePath(page, pages);
120
184
  generated.add(path);
121
- addRoute(path);
185
+ addRoute(path, { lastmod: page.updatedAt, seo: page.data.seo });
122
186
  }
123
187
  const codeOwned = new Set((options.customPages ?? []).map((page) => page.path));
124
188
  const entriesBySchema = /* @__PURE__ */ new Map();
@@ -138,7 +202,11 @@ const eldraModule = defineNuxtModule({
138
202
  catalogPromise = listCatalogDocs(client, catalogKind, locale);
139
203
  catalogByKind.set(catalogKind, catalogPromise);
140
204
  }
141
- for (const path of catalogDocRoutes(catalogKind, await catalogPromise, pattern)) {
205
+ for (const { path, doc } of catalogDocRouteRefs(
206
+ catalogKind,
207
+ await catalogPromise,
208
+ pattern
209
+ )) {
142
210
  if (codeOwned.has(path))
143
211
  continue;
144
212
  if (generated.has(path)) {
@@ -146,7 +214,7 @@ const eldraModule = defineNuxtModule({
146
214
  continue;
147
215
  }
148
216
  generated.add(path);
149
- addRoute(path);
217
+ addRoute(path, { lastmod: doc.updatedAt, seo: template.data.seo });
150
218
  }
151
219
  continue;
152
220
  }
@@ -168,9 +236,18 @@ const eldraModule = defineNuxtModule({
168
236
  );
169
237
  }
170
238
  generated.add(path);
171
- addRoute(path);
239
+ addRoute(path, {
240
+ lastmod: entry.updatedAt,
241
+ seo: entry.data.seo,
242
+ templateSeo: template.data.seo
243
+ });
172
244
  }
173
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
+ }
174
251
  });
175
252
  let siteIconFiles = [];
176
253
  nuxt.hooks.hook(
@@ -183,12 +260,58 @@ const eldraModule = defineNuxtModule({
183
260
  for (const file of siteIconFiles)
184
261
  writeFileSync(join(publicDir, file.name), file.data);
185
262
  };
186
- nitro.hooks.hook("compiled", () => writeSiteIconFiles(nitro.options.output.publicDir));
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
+ });
187
308
  nitro.hooks.hook("prerender:done", () => {
188
309
  const publicDir = nitro.options.output.publicDir;
189
310
  mkdirSync(publicDir, { recursive: true });
190
311
  copyGeneratedManifest(nuxt.options.rootDir, publicDir);
191
312
  writeSiteIconFiles(publicDir);
313
+ writeCrawlFiles(publicDir);
314
+ writeRedirects(publicDir);
192
315
  const target = join(publicDir, "_headers");
193
316
  const existing = existsSync(target) ? readFileSync(target, "utf8").replace(/^\s*Content-Security-Policy:\s*frame-ancestors[^\r\n]*(?:\r?\n|$)/gim, "").trimEnd() + "\n\n" : "";
194
317
  const ancestors = ["'self'", ...studioOrigins].join(" ");
@@ -211,19 +334,55 @@ const eldraModule = defineNuxtModule({
211
334
  orgId: options.orgId,
212
335
  retry: options.retry
213
336
  });
214
- const [commerce, locales, platformMessages, platformDesignTokens, platformSiteIcons] = 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([
215
349
  readStoreCommerce(platformClient),
216
350
  readStoreLocales(platformClient),
217
351
  readThemeMessages(platformClient),
218
352
  readDesignTokens(platformClient),
219
- nuxt.options.dev ? Promise.resolve(null) : readSiteIcons(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)
220
369
  ]);
370
+ crawlSetting = platformCrawl;
371
+ redirectsSetting = platformRedirects;
372
+ crawlSiteUrl = options.siteUrl || platformCrawl?.siteUrl || "";
373
+ nuxt.options.runtimeConfig.public.eldraSeo.siteUrl = crawlSiteUrl;
221
374
  const runtimeEldra = nuxt.options.runtimeConfig.public.eldra;
222
375
  runtimeEldra.commerce = commerce;
223
376
  runtimeEldra.locales = locales;
224
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
+ });
225
384
  const resolvedSiteIcons = resolveSiteIcons(platformSiteIcons, {
226
- siteName: siteName(nuxt.options.app.head.title, nuxt.options.rootDir),
385
+ siteName: platformSeoName(platformSeo) || siteName(nuxt.options.app.head.title, nuxt.options.rootDir),
227
386
  primaryToken: platformDesignTokens?.colors.primary?.value ?? themePrimaryToken(nuxt.options.rootDir)
228
387
  });
229
388
  const siteIcons = resolvedSiteIcons === null ? null : buildSiteIconOutput(resolvedSiteIcons, nuxt.options.app.baseURL);
@@ -283,6 +442,12 @@ function packageVersion(path) {
283
442
  return "0.0.0";
284
443
  }
285
444
  }
445
+ function platformSeoName(setting) {
446
+ return setting?.site.name?.trim() ?? "";
447
+ }
448
+ function seoSiteName(title) {
449
+ return typeof title === "string" ? title.trim() : "";
450
+ }
286
451
  function siteName(title, rootDir) {
287
452
  if (typeof title === "string" && title.trim() !== "")
288
453
  return title;
@@ -0,0 +1,83 @@
1
+ import { type Analytics, type AnalyticsSender } from '@eldrajs/theme-core';
2
+ /** What reaches the browser in `runtimeConfig.public.eldra.analytics`. */
3
+ export interface AnalyticsRuntimeConfig {
4
+ /** The build's decision: a production build with an organisation and no opt-out. */
5
+ enabled: boolean;
6
+ /** A first-party origin that receives events instead of the gateway. */
7
+ eventOrigin: string | null;
8
+ }
9
+ /** The module's `analytics` option. */
10
+ export type AnalyticsOption = false | {
11
+ enabled?: boolean;
12
+ eventOrigin?: string;
13
+ };
14
+ export interface AnalyticsBuildInput {
15
+ option: AnalyticsOption | undefined;
16
+ /** `ELDRA_ANALYTICS` (`off` opts out) and `ELDRA_ANALYTICS_ORIGIN`, so a deploy can override. */
17
+ env: Record<string, string | undefined>;
18
+ dev: boolean;
19
+ production: boolean;
20
+ orgId: string;
21
+ warn?: (message: string) => void;
22
+ }
23
+ /** `value` when it is a bare origin (`https://host[:port]`, no path), otherwise `null`. */
24
+ export declare function parseEventOrigin(value: string): string | null;
25
+ /**
26
+ * Decides at build time whether the deployed site reports, and where to. Reporting is on only for
27
+ * a production build (never `nuxi dev`, never a preview build, which is the Studio preview host's)
28
+ * that has an organisation id — a credential-less build has nothing to report to — and has not
29
+ * opted out. An invalid `eventOrigin` is warned about and ignored, like the module's other
30
+ * fail-soft platform reads.
31
+ */
32
+ export declare function resolveAnalyticsConfig(input: AnalyticsBuildInput): AnalyticsRuntimeConfig;
33
+ /**
34
+ * A host that is never the live site: a developer's machine and the Studio preview host. A build
35
+ * that is production by default (a local `nuxi generate`) must not report visits from there.
36
+ */
37
+ export declare function isNonSiteHost(hostname: string | undefined): boolean;
38
+ /**
39
+ * Whether this document reports: a browser (never the server), not a dev server, a build that
40
+ * decided to report, and not a Studio preview frame.
41
+ */
42
+ export declare function shouldReport(input: {
43
+ client: boolean;
44
+ dev: boolean;
45
+ config: AnalyticsRuntimeConfig | undefined;
46
+ studioPreviewFrame: boolean;
47
+ /** The document's hostname: a local or preview host never reports. */
48
+ hostname?: string;
49
+ }): boolean;
50
+ /**
51
+ * Appends the tracker `<script>` to the document, once. Returns `false` when the config yields no
52
+ * tag (no organisation) or one is already there. `onLoad` runs when the script has loaded, which
53
+ * is when events queued before it can be sent.
54
+ */
55
+ export declare function installTrackerScript(doc: Document, config: {
56
+ gatewayUrl: string;
57
+ orgId: string;
58
+ eventOrigin: string | null;
59
+ }, onLoad: () => void): boolean;
60
+ /** The tracker's global, once `script.js` has installed it. */
61
+ export declare function trackerGlobal(win: {
62
+ eldra?: AnalyticsSender;
63
+ }): AnalyticsSender | undefined;
64
+ /** The shape `useEldraAnalytics()` returns. */
65
+ export type EldraAnalytics = Pick<Analytics, 'track' | 'enabled'>;
66
+ /**
67
+ * The plugin's whole decision, apart from Nuxt: builds the analytics object and, when this
68
+ * document reports, installs the tracker tag. `isFrame` is "this document is a Studio preview
69
+ * frame" (`isStudioPreviewFrame`), which never reports.
70
+ */
71
+ export declare function setupAnalytics(input: {
72
+ client: boolean;
73
+ dev: boolean;
74
+ config: AnalyticsRuntimeConfig | undefined;
75
+ isFrame: boolean;
76
+ gatewayUrl: string;
77
+ orgId: string;
78
+ doc: Document | undefined;
79
+ win: {
80
+ eldra?: AnalyticsSender;
81
+ } | undefined;
82
+ hostname?: string;
83
+ }): Analytics;