@eldrajs/theme-nuxt 0.2.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +88 -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 +188 -15
  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/buildToken.d.ts +15 -0
  11. package/dist/runtime/buildToken.js +6 -0
  12. package/dist/runtime/catalog.d.ts +5 -0
  13. package/dist/runtime/catalog.js +6 -3
  14. package/dist/runtime/composables/useEldraAnalytics.d.ts +10 -0
  15. package/dist/runtime/composables/useEldraAnalytics.js +6 -0
  16. package/dist/runtime/composables/useEldraBuildToken.d.ts +9 -0
  17. package/dist/runtime/composables/useEldraBuildToken.js +6 -0
  18. package/dist/runtime/composables/useEldraForms.d.ts +8 -0
  19. package/dist/runtime/composables/useEldraForms.js +5 -0
  20. package/dist/runtime/composables/useEldraSeo.d.ts +27 -0
  21. package/dist/runtime/composables/useEldraSeo.js +41 -0
  22. package/dist/runtime/composables/useStructuredData.d.ts +35 -0
  23. package/dist/runtime/composables/useStructuredData.js +55 -0
  24. package/dist/runtime/crawl.d.ts +29 -0
  25. package/dist/runtime/crawl.js +50 -0
  26. package/dist/runtime/crawlOutput.d.ts +54 -0
  27. package/dist/runtime/crawlOutput.js +96 -0
  28. package/dist/runtime/forms.d.ts +29 -0
  29. package/dist/runtime/forms.js +154 -0
  30. package/dist/runtime/localeState.d.ts +6 -4
  31. package/dist/runtime/localeState.js +7 -15
  32. package/dist/runtime/plugin.js +9 -1
  33. package/dist/runtime/redirects.d.ts +74 -0
  34. package/dist/runtime/redirects.js +190 -0
  35. package/dist/runtime/seo.d.ts +23 -0
  36. package/dist/runtime/seo.js +95 -0
  37. package/dist/runtime/seoHead.d.ts +27 -0
  38. package/dist/runtime/seoHead.js +28 -0
  39. package/dist/runtime/siteProfile.d.ts +56 -0
  40. package/dist/runtime/siteProfile.js +69 -0
  41. package/package.json +6 -5
package/CHANGELOG.md CHANGED
@@ -5,6 +5,94 @@ Release-please writes the generated notes from commit messages and does not repl
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ - **A build sends a read-only build token for its own rate-limit bucket (WS-403, WS-409).**
9
+ `ELDRA_BUILD_TOKEN` (`eldra_bld_…`, created in Studio → Settings → Developers → Build tokens) is
10
+ sent as `X-Eldra-Build-Token` by the module's build-time reads and by the clients of a
11
+ `nuxi generate` prerender; never in the browser, `nuxi dev` or a deployed server answering a
12
+ visitor. The site deploy token is never read or sent by the build: keep `ELDRA_DEPLOY_TOKEN` on the
13
+ `eldra-theme deploy` job only. The starter's GitHub, GitLab and Bitbucket pipelines are split
14
+ into a build job (with the build token, uploading `.output/public`) and a deploy job (the pinned
15
+ CLI against that artifact, no project install) so build-time code never sees the deploy token. The token is stored in no runtime config (public or private) and appears in no build output,
16
+ server bundle included: it is read from the environment at call time. New auto-import
17
+ `useEldraBuildToken()` returns it (prerender only) for a theme's own `@eldrajs/sdk` client.
18
+
19
+ - **Baked form definitions keep `consentText` (WS-386).** `toFormDefinition` carries a subscribing
20
+ form's consent sentence per locale and refuses a malformed one, like the other localized texts.
21
+
22
+ - **The analytics tracker never loads on `localhost` or `*.previews.eldra.dev` (WS-387).** A local
23
+ `nuxi generate` is a production build now, so the browser skips the tracker on a developer's
24
+ machine and on the Studio preview host. `ELDRA_BUILD_TARGET` is also read once in `setup()`, so a
25
+ mistyped value warns once, in context, instead of at import.
26
+
27
+ - **Baked form definitions accept `number` and `url` fields (WS-386).** `readFormDefinitions` no
28
+ longer drops a form that has one.
29
+
30
+ - **Breaking: a build is production unless `ELDRA_BUILD_TARGET=preview` (WS-387).** The marker
31
+ flipped. Before, only `ELDRA_BUILD_TARGET=production` was a production build and everything else
32
+ was a noindex preview; now an unset or empty variable is production, `preview` is the preview
33
+ (noindex, `robots.txt` `Disallow: /`, no sitemap, no analytics), and any other value warns and
34
+ counts as production. `nuxi dev` is unchanged: always a preview, with no tracker. A pipeline that
35
+ must not be indexed sets `ELDRA_BUILD_TARGET=preview`; the starter's CI files no longer set
36
+ `production`. The `buildTarget` module option still overrides.
37
+
38
+ - **`_redirects` rules that would match `/.eldra/manifest.json` are dropped (WS-384).** A theme's own
39
+ `public/_redirects` catch-all (or a platform rule) used to make every deploy fail the validator's
40
+ manifest check; the build now drops such a rule with one warning naming it and ships the rest.
41
+ - **Form definitions are read at build time and baked in (WS-386).** The module reads
42
+ `GET /site/v1/forms/{key}` for every key in the new `formSeeds` option (also passed to
43
+ `@eldrajs/vite-plugin-theme`) and the new `forms: string[]` option, once per `nuxi generate`, each key
44
+ independently fail-soft — one warning naming the key, never a failed build, and one form's failure
45
+ never costs another its definition. The validated definitions are written to
46
+ `runtimeConfig.public.eldra.forms` and read with the new auto-imported `useEldraForms()`; the starter's
47
+ `forms.definition` serves a baked key with no request and fetches any other when the page opens.
48
+ `nuxi dev` reads none.
49
+ - **Built-in analytics: the Eldra tracker, `useEldraAnalytics`, the `analytics` option.** A production
50
+ build (`ELDRA_BUILD_TARGET=production`) with an organisation id loads the tracker
51
+ (`analyticsTrackerScript` from `@eldrajs/sdk`) through a client plugin, so a deployed site reports
52
+ pageviews, SPA navigations included, with no code. Never `nuxi dev`, a preview build, a credential-less
53
+ build or a Studio preview frame. New module option `analytics: false | { enabled?, eventOrigin? }`
54
+ (env `ELDRA_ANALYTICS=off`, `ELDRA_ANALYTICS_ORIGIN`) on `runtimeConfig.public.eldra.analytics`; an
55
+ invalid `eventOrigin` is warned about and ignored. New auto-import `useEldraAnalytics()` returns
56
+ `{ track(name, props?), enabled }`, a no-op wherever tracking is off. No cookie or storage identifier.
57
+ Documented in `docs/themes.md`.
58
+
59
+ - **Structured data: `useStructuredData`, `provideStructuredData`, `useSiteProfile`.** Writes a
60
+ page's schema.org JSON-LD (nodes from `@eldrajs/theme-core`'s builders) into the head as one
61
+ `<script type="application/ld+json">` under a fixed key, for `enabled` pages only (pass
62
+ `!seo.noindex`). New module option `structuredData: { disable }` (`true`, or the node kinds
63
+ `product`, `breadcrumb`, `itemList`, `organization`, `website`) on `runtimeConfig.public.eldra`;
64
+ editing a node at runtime is `provideStructuredData((type, node, { path, locale }) => node |
65
+ null)`. The build reads the shop's profile from `GET /site/v1/site-profile` (`readSiteProfile`,
66
+ `./runtime/siteProfile.ts`; fail-soft like the other platform reads, build-only) and carries it,
67
+ with the site name and the site icon's 512 px rendering filling its gaps, on
68
+ `runtimeConfig.public.eldra.siteProfile`; `useSiteProfile()` returns it with the site origin.
69
+ Documented in `docs/theme-seo.md`.
70
+
71
+ - **`sitemap.xml` and `robots.txt`, generated from the prerendered routes.** `nuxi generate` writes
72
+ both into the static output. A preview build (the default) writes `Disallow: /` and no sitemap; a
73
+ production build (`ELDRA_BUILD_TARGET=production`) writes `Allow: /`, the merchant's own lines
74
+ and the sitemap line, and a sitemap with every content path once per locale, `xhtml:link`
75
+ hreflang alternates plus `x-default`, `lastmod` from the entry's or product's `updatedAt`, noindex
76
+ pages left out and a same-origin `seo.canonicalUrl` as the `loc`. It splits into a
77
+ `sitemapindex` and children past 50,000 URLs or 50 MiB. The origin is `ELDRA_SITE_URL`, else the
78
+ production URL from a seventh fail-soft read, `GET /site/v1/crawl` (`readCrawlSettings`,
79
+ `./runtime/crawl.ts`, production builds only); with neither, nothing is written and one line says
80
+ why. A theme's own `public/robots.txt` or `public/sitemap.xml` is never replaced (one line, `[eldra]
81
+ <file> generation skipped: theme ships its own`). New module option `sitemap` (`false`, or
82
+ `{ maxUrls, maxBytes }`). The head's hreflang `<link>`s are absolute when the origin is known. The
83
+ runtime `eldraSeo.siteUrl` now follows the same origin. Documented in `docs/theme-seo.md`.
84
+
85
+ - **Page titles and SEO metadata, set in Studio.** A sixth fail-soft read, `GET /site/v1/seo`
86
+ (`readSeo`, `./runtime/seo.ts`), carries the site's title pattern, description, share image,
87
+ Twitter handle and per-context patterns (one warning and the default pattern
88
+ `{{page.title}} · {{site.name}}` when it fails). A new auto-imported composable,
89
+ `useEldraSeo(context, data, options?)`, sets `<title>`, description, canonical link, `og:*`,
90
+ `twitter:*` and `robots` through the resolver in `@eldrajs/theme-core`. New module options
91
+ `siteUrl` (`ELDRA_SITE_URL`; without it no canonical, `og:url` or relative image is written) and
92
+ `buildTarget` (`ELDRA_BUILD_TARGET`): anything but `production` is a preview build, and a preview
93
+ build, `nuxi dev` and a page framed by Studio are always `noindex`. The public runtime config
94
+ gains `eldraSeo`. Documented in `docs/theme-seo.md`.
95
+
8
96
  - The runtime registers the theme's own id (`manifest.theme.id`) with `registerBlockFields`, and
9
97
  the draft projection validates slots against bare block ids when a published entry's
10
98
  `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.1",
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,55 @@ 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
  };
126
+ const buildToken = (process.env.ELDRA_BUILD_TOKEN ?? "").trim();
80
127
  addPlugin(resolver.resolve("./runtime/plugin"));
128
+ addPlugin(resolver.resolve("./runtime/analyticsPlugin"));
81
129
  addImports([
130
+ {
131
+ name: "useEldraBuildToken",
132
+ from: resolver.resolve("./runtime/composables/useEldraBuildToken")
133
+ },
82
134
  { name: "useEldraPage", from: resolver.resolve("./runtime/composables/useEldraPage") },
135
+ { name: "useEldraSeo", from: resolver.resolve("./runtime/composables/useEldraSeo") },
136
+ {
137
+ name: "useEldraAnalytics",
138
+ from: resolver.resolve("./runtime/composables/useEldraAnalytics")
139
+ },
140
+ // schema.org JSON-LD: write a page's nodes (opt-out per kind via the `structuredData` option,
141
+ // runtime edits via `provideStructuredData`) and read the shop's profile for `Organization`.
142
+ ...["useStructuredData", "provideStructuredData", "useSiteProfile"].map((name) => ({
143
+ name,
144
+ from: resolver.resolve("./runtime/composables/useStructuredData")
145
+ })),
83
146
  // The route key a theme's catch-all page gives `<NuxtPage>`; see `./runtime/routePath`.
84
147
  { name: "eldraRouteKey", from: resolver.resolve("./runtime/routePath") },
148
+ { name: "useEldraForms", from: resolver.resolve("./runtime/composables/useEldraForms") },
85
149
  { name: "useEldra", from: "@eldrajs/theme-vue" },
86
150
  // The active content locale and the path helpers around it. Re-exported from theme-vue
87
151
  // rather than defined here: the state lives on the theme context so a **block** can read it
@@ -92,6 +156,10 @@ const eldraModule = defineNuxtModule({
92
156
  { name: "useEldraPreview", from: "@eldrajs/theme-vue" }
93
157
  ]);
94
158
  let localeRouting = resolveLocaleRouting(null, options.locale);
159
+ const crawlRoutes = [];
160
+ let crawlSetting = null;
161
+ let crawlSiteUrl = options.siteUrl ?? "";
162
+ let redirectsSetting = null;
95
163
  nuxt.hook("prerender:routes", async (ctx) => {
96
164
  if (options.gatewayUrl === "" || options.orgId === "") {
97
165
  console.warn('[eldra] ELDRA_GATEWAY_URL / ELDRA_ORG_ID not set \u2014 prerendering "/" only');
@@ -101,7 +169,8 @@ const eldraModule = defineNuxtModule({
101
169
  const client = createEldraClient({
102
170
  gatewayUrl: options.gatewayUrl,
103
171
  orgId: options.orgId,
104
- retry: options.retry
172
+ retry: options.retry,
173
+ buildToken: buildToken || void 0
105
174
  });
106
175
  const locale = normalizeLocale(options.locale);
107
176
  const [pages, templates] = await Promise.all([
@@ -109,7 +178,8 @@ const eldraModule = defineNuxtModule({
109
178
  listRouteTemplateEntries(client, options.routeTemplateSchema, locale)
110
179
  ]);
111
180
  const generated = /* @__PURE__ */ new Set();
112
- const addRoute = (path) => {
181
+ const addRoute = (path, meta = {}) => {
182
+ crawlRoutes.push({ path, ...meta });
113
183
  ctx.routes.add(path);
114
184
  for (const prefixed of localeRouting.prefixed) {
115
185
  ctx.routes.add(localePathFor(path, prefixed, localeRouting));
@@ -118,7 +188,7 @@ const eldraModule = defineNuxtModule({
118
188
  for (const page of pages) {
119
189
  const path = resolvePagePath(page, pages);
120
190
  generated.add(path);
121
- addRoute(path);
191
+ addRoute(path, { lastmod: page.updatedAt, seo: page.data.seo });
122
192
  }
123
193
  const codeOwned = new Set((options.customPages ?? []).map((page) => page.path));
124
194
  const entriesBySchema = /* @__PURE__ */ new Map();
@@ -138,7 +208,11 @@ const eldraModule = defineNuxtModule({
138
208
  catalogPromise = listCatalogDocs(client, catalogKind, locale);
139
209
  catalogByKind.set(catalogKind, catalogPromise);
140
210
  }
141
- for (const path of catalogDocRoutes(catalogKind, await catalogPromise, pattern)) {
211
+ for (const { path, doc } of catalogDocRouteRefs(
212
+ catalogKind,
213
+ await catalogPromise,
214
+ pattern
215
+ )) {
142
216
  if (codeOwned.has(path))
143
217
  continue;
144
218
  if (generated.has(path)) {
@@ -146,7 +220,7 @@ const eldraModule = defineNuxtModule({
146
220
  continue;
147
221
  }
148
222
  generated.add(path);
149
- addRoute(path);
223
+ addRoute(path, { lastmod: doc.updatedAt, seo: template.data.seo });
150
224
  }
151
225
  continue;
152
226
  }
@@ -168,9 +242,18 @@ const eldraModule = defineNuxtModule({
168
242
  );
169
243
  }
170
244
  generated.add(path);
171
- addRoute(path);
245
+ addRoute(path, {
246
+ lastmod: entry.updatedAt,
247
+ seo: entry.data.seo,
248
+ templateSeo: template.data.seo
249
+ });
172
250
  }
173
251
  }
252
+ for (const page of options.customPages ?? []) {
253
+ if (/[:*]/.test(page.path) || generated.has(page.path))
254
+ continue;
255
+ crawlRoutes.push({ path: page.path, codeOwned: true });
256
+ }
174
257
  });
175
258
  let siteIconFiles = [];
176
259
  nuxt.hooks.hook(
@@ -183,12 +266,58 @@ const eldraModule = defineNuxtModule({
183
266
  for (const file of siteIconFiles)
184
267
  writeFileSync(join(publicDir, file.name), file.data);
185
268
  };
186
- nitro.hooks.hook("compiled", () => writeSiteIconFiles(nitro.options.output.publicDir));
269
+ const crawlLogged = /* @__PURE__ */ new Set();
270
+ const writeCrawlFiles = (publicDir) => {
271
+ const files = buildCrawlFiles({
272
+ target: buildTarget === "production" ? "production" : "preview",
273
+ siteUrl: crawlSiteUrl,
274
+ robotsExtra: crawlSetting?.robotsExtra,
275
+ routes: crawlRoutes,
276
+ routing: localeRouting,
277
+ sitemap: options.sitemap,
278
+ themePublicDir: resolve(nuxt.options.rootDir, nuxt.options.dir.public ?? "public"),
279
+ log: (message) => {
280
+ if (crawlLogged.has(message))
281
+ return;
282
+ crawlLogged.add(message);
283
+ console.warn(message);
284
+ }
285
+ });
286
+ if (files.length === 0)
287
+ return;
288
+ mkdirSync(publicDir, { recursive: true });
289
+ for (const file of files)
290
+ writeFileSync(join(publicDir, file.name), file.content);
291
+ };
292
+ const writeRedirects = (publicDir) => {
293
+ const built = buildRedirectsFile(
294
+ redirectsSetting?.rules ?? [],
295
+ localeRouting,
296
+ readThemeRedirects(resolve(nuxt.options.rootDir, nuxt.options.dir.public ?? "public"))
297
+ );
298
+ for (const warning of built.warnings) {
299
+ if (crawlLogged.has(warning))
300
+ continue;
301
+ crawlLogged.add(warning);
302
+ console.warn(warning);
303
+ }
304
+ if (built.content === null)
305
+ return;
306
+ mkdirSync(publicDir, { recursive: true });
307
+ writeFileSync(join(publicDir, "_redirects"), built.content);
308
+ };
309
+ nitro.hooks.hook("compiled", () => {
310
+ writeSiteIconFiles(nitro.options.output.publicDir);
311
+ writeCrawlFiles(nitro.options.output.publicDir);
312
+ writeRedirects(nitro.options.output.publicDir);
313
+ });
187
314
  nitro.hooks.hook("prerender:done", () => {
188
315
  const publicDir = nitro.options.output.publicDir;
189
316
  mkdirSync(publicDir, { recursive: true });
190
317
  copyGeneratedManifest(nuxt.options.rootDir, publicDir);
191
318
  writeSiteIconFiles(publicDir);
319
+ writeCrawlFiles(publicDir);
320
+ writeRedirects(publicDir);
192
321
  const target = join(publicDir, "_headers");
193
322
  const existing = existsSync(target) ? readFileSync(target, "utf8").replace(/^\s*Content-Security-Policy:\s*frame-ancestors[^\r\n]*(?:\r?\n|$)/gim, "").trimEnd() + "\n\n" : "";
194
323
  const ancestors = ["'self'", ...studioOrigins].join(" ");
@@ -209,21 +338,59 @@ const eldraModule = defineNuxtModule({
209
338
  const platformClient = options.gatewayUrl === "" || options.orgId === "" ? null : createEldraClient$1({
210
339
  apiBaseUrl: options.gatewayUrl,
211
340
  orgId: options.orgId,
212
- retry: options.retry
341
+ retry: options.retry,
342
+ // Not for `nuxi dev`: only a build claims the build bucket.
343
+ buildToken: nuxt.options.dev ? void 0 : buildToken || void 0
213
344
  });
214
- const [commerce, locales, platformMessages, platformDesignTokens, platformSiteIcons] = await Promise.all([
345
+ const [
346
+ commerce,
347
+ locales,
348
+ platformMessages,
349
+ platformDesignTokens,
350
+ platformSiteIcons,
351
+ platformSeo,
352
+ platformSiteProfile,
353
+ platformCrawl,
354
+ platformForms,
355
+ platformRedirects
356
+ ] = await Promise.all([
215
357
  readStoreCommerce(platformClient),
216
358
  readStoreLocales(platformClient),
217
359
  readThemeMessages(platformClient),
218
360
  readDesignTokens(platformClient),
219
- nuxt.options.dev ? Promise.resolve(null) : readSiteIcons(platformClient)
361
+ nuxt.options.dev ? Promise.resolve(null) : readSiteIcons(platformClient),
362
+ nuxt.options.dev ? Promise.resolve(null) : readSeo(platformClient),
363
+ // The site profile is the eighth read, on the same terms (build-only, fail-soft).
364
+ nuxt.options.dev ? Promise.resolve(null) : readSiteProfile(platformClient),
365
+ // The crawl settings matter only to a production build: a preview build writes `Disallow: /`
366
+ // and no sitemap whatever they say.
367
+ nuxt.options.dev || buildTarget !== "production" ? Promise.resolve(null) : readCrawlSettings(platformClient),
368
+ // The form definitions the theme seeds or names, one independently fail-soft read each.
369
+ // Build-only: `nuxi dev` has nothing to bake, and the storefront fetches them live there.
370
+ nuxt.options.dev ? Promise.resolve({}) : readFormDefinitions(platformClient, [
371
+ ...(options.formSeeds ?? []).map((seed) => seed.key),
372
+ ...options.forms ?? []
373
+ ]),
374
+ // The redirect rules are a tenth read on the same terms (build-only, fail-soft): they become
375
+ // the platform block of the static output's `_redirects`.
376
+ nuxt.options.dev ? Promise.resolve(null) : readRedirects(platformClient)
220
377
  ]);
378
+ crawlSetting = platformCrawl;
379
+ redirectsSetting = platformRedirects;
380
+ crawlSiteUrl = options.siteUrl || platformCrawl?.siteUrl || "";
381
+ nuxt.options.runtimeConfig.public.eldraSeo.siteUrl = crawlSiteUrl;
221
382
  const runtimeEldra = nuxt.options.runtimeConfig.public.eldra;
222
383
  runtimeEldra.commerce = commerce;
223
384
  runtimeEldra.locales = locales;
224
385
  runtimeEldra.designTokens = platformDesignTokens;
386
+ runtimeEldra.forms = platformForms;
387
+ nuxt.options.runtimeConfig.public.eldraSeo.setting = platformSeo;
388
+ runtimeEldra.siteProfile = resolveSiteProfile(platformSiteProfile, {
389
+ siteName: platformSeoName(platformSeo) || seoSiteName(nuxt.options.app.head.title) || "",
390
+ iconLogoUrl: platformSiteIcons?.icons?.icon512 ?? null
391
+ });
225
392
  const resolvedSiteIcons = resolveSiteIcons(platformSiteIcons, {
226
- siteName: siteName(nuxt.options.app.head.title, nuxt.options.rootDir),
393
+ siteName: platformSeoName(platformSeo) || siteName(nuxt.options.app.head.title, nuxt.options.rootDir),
227
394
  primaryToken: platformDesignTokens?.colors.primary?.value ?? themePrimaryToken(nuxt.options.rootDir)
228
395
  });
229
396
  const siteIcons = resolvedSiteIcons === null ? null : buildSiteIconOutput(resolvedSiteIcons, nuxt.options.app.baseURL);
@@ -283,6 +450,12 @@ function packageVersion(path) {
283
450
  return "0.0.0";
284
451
  }
285
452
  }
453
+ function platformSeoName(setting) {
454
+ return setting?.site.name?.trim() ?? "";
455
+ }
456
+ function seoSiteName(title) {
457
+ return typeof title === "string" ? title.trim() : "";
458
+ }
286
459
  function siteName(title, rootDir) {
287
460
  if (typeof title === "string" && title.trim() !== "")
288
461
  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;