@eldrajs/theme-nuxt 0.3.1 → 0.3.3

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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,17 @@ Release-please writes the generated notes from commit messages and does not repl
5
5
 
6
6
  ## Unreleased
7
7
 
8
+ - **Prerender reads shared lists once per build (WS-406).** `nuxi generate` created a client per
9
+ route, so the page list, the route-template list and the category list behind link resolution
10
+ were read once per route (the category list about 136 times in one staging build). During a
11
+ prerender they are now read once per gateway, organisation and locale and shared across routes;
12
+ a failed read is not remembered. SSR requests and the browser are unchanged and never share
13
+ reads. New subpath `@eldrajs/theme-nuxt/prerender` (`memoizeForPrerender`, `prerenderMemoScope`,
14
+ `prerenderMemoStats`) for a theme's own build-wide reads; the build logs the counts once, and the
15
+ starter shares its category read with the module's (one read per locale).
16
+ `ELDRA_GATEWAY_URL` should be the edge API host: the edge recognises the build token, so builds
17
+ and browsers use the same base.
18
+
8
19
  - **A build sends a read-only build token for its own rate-limit bucket (WS-403, WS-409).**
9
20
  `ELDRA_BUILD_TOKEN` (`eldra_bld_…`, created in Studio → Settings → Developers → Build tokens) is
10
21
  sent as `X-Eldra-Build-Token` by the module's build-time reads and by the clients of a
package/README.md CHANGED
@@ -24,6 +24,17 @@ export default defineNuxtConfig({
24
24
  });
25
25
  ```
26
26
 
27
+ Environment: `ELDRA_GATEWAY_URL` and `ELDRA_ORG_ID` are required for a real build. Point
28
+ `ELDRA_GATEWAY_URL` at the **edge API host**: the edge recognises the build token
29
+ (`X-Eldra-Build-Token`, its own rate bucket), so the build's reads and the visitor's browser both
30
+ go through the same host.
31
+
32
+ During a prerender the page list, route-template list and category list are read once per build
33
+ (and locale), not once per route (`@eldrajs/theme-nuxt/prerender`); request-time rendering never
34
+ shares reads. One process is one build: the shared reads live for the length of one `nuxi generate`
35
+ and are cleared when a prerender starts. The build logs one line with the counts
36
+ (`[eldra] prerender shared reads: N made, M avoided`).
37
+
27
38
  ```vue
28
39
  <script setup lang="ts">
29
40
  import { EldraLayout } from '@eldrajs/theme-vue';
package/dist/module.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "compatibility": {
5
5
  "nuxt": ">=3.13.0"
6
6
  },
7
- "version": "0.3.1",
7
+ "version": "0.3.3",
8
8
  "builder": {
9
9
  "@nuxt/module-builder": "0.8.4",
10
10
  "unbuild": "unknown"
package/dist/module.mjs CHANGED
@@ -17,6 +17,8 @@ import { normalizeLocale } from '../dist/runtime/locale.js';
17
17
  import { resolveLocaleRouting, readStoreLocales, localePathFor } from '../dist/runtime/locales.js';
18
18
  import { readThemeMessages, resolveSiteMessages } from '../dist/runtime/messages.js';
19
19
  import { listAllEntries } from '../dist/runtime/resolveRoute.js';
20
+ import { prerenderMemoStats } from '../dist/runtime/prerenderMemo.js';
21
+ import { clearPrerenderMemo } from '../dist/runtime/prerenderMemoState.js';
20
22
  import { readSeo } from '../dist/runtime/seo.js';
21
23
  import { readSiteIcons, resolveSiteIcons } from '../dist/runtime/siteIcons.js';
22
24
  import { readSiteProfile, resolveSiteProfile } from '../dist/runtime/siteProfile.js';
@@ -307,10 +309,15 @@ const eldraModule = defineNuxtModule({
307
309
  writeFileSync(join(publicDir, "_redirects"), built.content);
308
310
  };
309
311
  nitro.hooks.hook("compiled", () => {
312
+ const { loads, hits } = prerenderMemoStats();
313
+ if (loads + hits > 0) {
314
+ console.info(`[eldra] prerender shared reads: ${loads} made, ${hits} avoided`);
315
+ }
310
316
  writeSiteIconFiles(nitro.options.output.publicDir);
311
317
  writeCrawlFiles(nitro.options.output.publicDir);
312
318
  writeRedirects(nitro.options.output.publicDir);
313
319
  });
320
+ nitro.hooks.hook("prerender:init", () => clearPrerenderMemo());
314
321
  nitro.hooks.hook("prerender:done", () => {
315
322
  const publicDir = nitro.options.output.publicDir;
316
323
  mkdirSync(publicDir, { recursive: true });
@@ -14,6 +14,12 @@ export interface LinkTargetSources {
14
14
  * the title a blank label falls back to — no extra read.
15
15
  */
16
16
  pages?: readonly EntryDoc[];
17
+ /**
18
+ * The prerender memo scope (`prerenderMemoScope`) for this site and locale. When set, the whole
19
+ * category list is read once per build instead of once per route (WS-406); `null` or omitted
20
+ * reads it every time, which is what a request-time render does regardless.
21
+ */
22
+ memoScope?: string | null;
17
23
  }
18
24
  /**
19
25
  * What the site knows about every object its links point at, keyed
@@ -1,5 +1,6 @@
1
1
  import { buildCategoryTree } from "./catalog.js";
2
2
  import { localeQuery } from "./locale.js";
3
+ import { CATEGORIES_MEMO_NAME, memoizeForPrerender } from "./prerenderMemo.js";
3
4
  const CHUNK_SIZE = 50;
4
5
  const PAGE_SIZE = 100;
5
6
  const MAX_PAGES = 100;
@@ -30,7 +31,15 @@ export async function collectLinkTargets(client, keys, locale, sources = {}) {
30
31
  const listCategories = client.catalog.listCategories?.bind(client.catalog);
31
32
  const wantedCategories = byType.get("category") ?? [];
32
33
  if (listCategories !== void 0 && wantedCategories.length > 0) {
33
- reads.push(readCategoriesInto(targets, wantedCategories, listCategories, locale));
34
+ reads.push(
35
+ readCategoriesInto(
36
+ targets,
37
+ wantedCategories,
38
+ listCategories,
39
+ locale,
40
+ sources.memoScope ?? null
41
+ )
42
+ );
34
43
  }
35
44
  if ((byType.get("entry") ?? []).length > 0) {
36
45
  for (const schemaApiId of sources.entrySchemaApiIds ?? []) {
@@ -100,15 +109,19 @@ function chunks(ids) {
100
109
  }
101
110
  return result;
102
111
  }
103
- async function readCategoriesInto(into, wanted, listCategories, locale) {
112
+ async function readCategoriesInto(into, wanted, listCategories, locale, memoScope) {
104
113
  const ids = new Set(wanted);
105
- const docs = [];
114
+ let docs;
106
115
  try {
107
- for (let page = 1; page <= MAX_PAGES; page += 1) {
108
- const list = await listCategories({ ...localeQuery(locale), page, pageSize: PAGE_SIZE });
109
- docs.push(...list.data);
110
- if (list.meta?.hasNext !== true || list.data.length === 0) break;
111
- }
116
+ docs = await memoizeForPrerender(memoScope, CATEGORIES_MEMO_NAME, async () => {
117
+ const all = [];
118
+ for (let page = 1; page <= MAX_PAGES; page += 1) {
119
+ const list = await listCategories({ ...localeQuery(locale), page, pageSize: PAGE_SIZE });
120
+ all.push(...list.data);
121
+ if (list.meta?.hasNext !== true || list.data.length === 0) break;
122
+ }
123
+ return all;
124
+ });
112
125
  } catch {
113
126
  return;
114
127
  }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * A per-build memo for the reads every prerendered route repeats (WS-406).
3
+ *
4
+ * `nuxi generate` resolves each route with a fresh client, so the page list, the route-template
5
+ * list and the category list were read once **per route**: a 130-route build sent the same
6
+ * `categories?page=1&pageSize=100` read about 136 times. The lists do not change while one build
7
+ * runs, so during a prerender the first route to ask starts the read and every later route shares
8
+ * the in-flight promise.
9
+ *
10
+ * Scope, deliberately narrow:
11
+ *
12
+ * - **Prerender only.** Outside `import.meta.prerender` on the server (SSR requests, the browser,
13
+ * `nuxi dev`) `memoizeForPrerender` just runs the loader: a long-lived server must never answer
14
+ * from a list a merchant has since edited, and a browser session has no build to share with.
15
+ * - **Keyed by gateway, organisation and locale** (plus the read's name), so two sites or two
16
+ * locales in one process never share an answer.
17
+ * - **Failures are not remembered.** A rejected read drops its entry so the next route tries again.
18
+ * - **One build.** The map lives in the module that `nuxi generate` loads once, so it ends with the
19
+ * process; {@link clearPrerenderMemo} empties it for anything that outlives one (tests).
20
+ */
21
+ /** The memo name the kit reads the whole category list under; a theme that reads the same list
22
+ * (the gateway serves the tree as a whole) uses it too, so the build makes one read, not two. */
23
+ export declare const CATEGORIES_MEMO_NAME = "categories";
24
+ /** The memo scope for one site and locale, or `null` when the caller has no credentials to key on
25
+ * (such a read is never shared). */
26
+ export declare function prerenderMemoScope(gatewayUrl: string | undefined, orgId: string | undefined, locale: string | undefined): string | null;
27
+ /**
28
+ * Run `load` once per `(scope, name)` for the length of a prerender; run it every time otherwise.
29
+ * A `null` scope never shares.
30
+ */
31
+ export declare function memoizeForPrerender<T>(scope: string | null, name: string, load: () => Promise<T>): Promise<T>;
32
+ /** How many reads the memo ran (`loads`) and how many it answered from a shared one (`hits`). */
33
+ export declare function prerenderMemoStats(): {
34
+ loads: number;
35
+ hits: number;
36
+ };
@@ -0,0 +1,25 @@
1
+ import { counters, isPrerender, memo } from "./prerenderMemoState.js";
2
+ export const CATEGORIES_MEMO_NAME = "categories";
3
+ export function prerenderMemoScope(gatewayUrl, orgId, locale) {
4
+ if (!gatewayUrl || !orgId) return null;
5
+ return `${gatewayUrl}|${orgId}|${locale ?? ""}`;
6
+ }
7
+ export function memoizeForPrerender(scope, name, load) {
8
+ if (scope === null || !isPrerender()) return load();
9
+ const key = `${scope}|${name}`;
10
+ const existing = memo.get(key);
11
+ if (existing !== void 0) {
12
+ counters.hits += 1;
13
+ return existing;
14
+ }
15
+ counters.loads += 1;
16
+ const pending = load().catch((cause) => {
17
+ if (memo.get(key) === pending) memo.delete(key);
18
+ throw cause;
19
+ });
20
+ memo.set(key, pending);
21
+ return pending;
22
+ }
23
+ export function prerenderMemoStats() {
24
+ return { loads: counters.loads, hits: counters.hits };
25
+ }
@@ -0,0 +1,10 @@
1
+ export declare const memo: Map<string, Promise<unknown>>;
2
+ export declare const counters: {
3
+ loads: number;
4
+ hits: number;
5
+ };
6
+ export declare function isPrerender(): boolean;
7
+ /** Empty the memo and its counters. */
8
+ export declare function clearPrerenderMemo(): void;
9
+ /** Test seam: `true`/`false` overrides the prerender check, `undefined` restores it. */
10
+ export declare function forcePrerenderMemoForTests(value: boolean | undefined): void;
@@ -0,0 +1,20 @@
1
+ const KEY = Symbol.for("@eldrajs/theme-nuxt:prerender-memo");
2
+ const holder = globalThis;
3
+ const store = holder[KEY] ??= {
4
+ memo: /* @__PURE__ */ new Map(),
5
+ counters: { loads: 0, hits: 0 },
6
+ forced: void 0
7
+ };
8
+ export const memo = store.memo;
9
+ export const counters = store.counters;
10
+ export function isPrerender() {
11
+ return store.forced ?? (import.meta.server === true && import.meta.prerender === true);
12
+ }
13
+ export function clearPrerenderMemo() {
14
+ memo.clear();
15
+ counters.loads = 0;
16
+ counters.hits = 0;
17
+ }
18
+ export function forcePrerenderMemoForTests(value) {
19
+ store.forced = value;
20
+ }
@@ -41,6 +41,13 @@ export declare const EMPTY_ELDRA_ROUTE: ResolvedEldraRoute;
41
41
  export interface EldraRouteSchemas {
42
42
  pageSchema: string;
43
43
  routeTemplateSchema: string;
44
+ /**
45
+ * The site's gateway and organisation. When both are given, the page and route-template lists
46
+ * (and the category list behind link resolution) are read once per build during a prerender
47
+ * instead of once per route (WS-406, see `./prerenderMemo.ts`). Without them nothing is shared.
48
+ */
49
+ gatewayUrl?: string;
50
+ orgId?: string;
44
51
  }
45
52
  /**
46
53
  * Resolve one request path against the site's pages and route templates.
@@ -8,6 +8,7 @@ import { linkTargetKeys } from "@eldrajs/theme-core/links";
8
8
  import { loadCatalogEntry } from "./catalog.js";
9
9
  import { collectLinkTargets } from "./links.js";
10
10
  import { localeQuery } from "./locale.js";
11
+ import { memoizeForPrerender, prerenderMemoScope } from "./prerenderMemo.js";
11
12
  export const EMPTY_ELDRA_ROUTE = {
12
13
  page: null,
13
14
  template: null,
@@ -17,9 +18,18 @@ export const EMPTY_ELDRA_ROUTE = {
17
18
  };
18
19
  export async function resolveEldraRoute(client, schemas, path, locale) {
19
20
  try {
21
+ const scope = prerenderMemoScope(schemas.gatewayUrl, schemas.orgId, locale);
20
22
  const [pages, templates] = await Promise.all([
21
- listAllEntries(client, schemas.pageSchema, locale),
22
- listRouteTemplates(client, schemas.routeTemplateSchema, locale)
23
+ memoizeForPrerender(
24
+ scope,
25
+ `entries:${schemas.pageSchema}`,
26
+ () => listAllEntries(client, schemas.pageSchema, locale)
27
+ ),
28
+ memoizeForPrerender(
29
+ scope,
30
+ `entries:${schemas.routeTemplateSchema}`,
31
+ () => listRouteTemplates(client, schemas.routeTemplateSchema, locale)
32
+ )
23
33
  ]);
24
34
  const match = resolveRoute(path, { pages, templates });
25
35
  if (match === null) return EMPTY_ELDRA_ROUTE;
@@ -33,7 +43,7 @@ export async function resolveEldraRoute(client, schemas, path, locale) {
33
43
  template: null,
34
44
  entry: null,
35
45
  catalog: null,
36
- links: await linkState(client, pages, templates, page, locale)
46
+ links: await linkState(client, pages, templates, page, locale, scope)
37
47
  };
38
48
  }
39
49
  const schemaApiId = plainString(match.template.data.schemaApiId);
@@ -65,7 +75,7 @@ export async function resolveEldraRoute(client, schemas, path, locale) {
65
75
  slug: plainString(entry2.data.slug),
66
76
  path: plainString(entry2.data.path)
67
77
  } : { kind: catalogKind, slug: slugValue },
68
- links: await linkState(client, pages, templates, template2, locale)
78
+ links: await linkState(client, pages, templates, template2, locale, scope)
69
79
  };
70
80
  }
71
81
  const [template, entry] = await Promise.all([
@@ -80,18 +90,19 @@ export async function resolveEldraRoute(client, schemas, path, locale) {
80
90
  template,
81
91
  entry,
82
92
  catalog: null,
83
- links: await linkState(client, pages, templates, template, locale)
93
+ links: await linkState(client, pages, templates, template, locale, scope)
84
94
  };
85
95
  } catch (cause) {
86
96
  if (cause instanceof EldraClientError && cause.status === 404) return EMPTY_ELDRA_ROUTE;
87
97
  throw cause;
88
98
  }
89
99
  }
90
- async function linkState(client, pages, templates, document, locale) {
100
+ async function linkState(client, pages, templates, document, locale, memoScope) {
91
101
  const keys = collectDocumentTargetKeys(document);
92
102
  const targets = keys.length === 0 ? /* @__PURE__ */ new Map() : await collectLinkTargets(client, keys, locale, {
93
103
  entrySchemaApiIds: entryTemplateSchemas(templates),
94
- pages
104
+ pages,
105
+ memoScope
95
106
  });
96
107
  return { pages, templates, targets };
97
108
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eldrajs/theme-nuxt",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Nuxt module for Eldra themes: wires @eldrajs/vite-plugin-theme, the gateway client, draft overlays and the Studio preview bridge into a Nuxt 4 site.",
5
5
  "keywords": [
6
6
  "cms",
@@ -33,6 +33,10 @@
33
33
  "types": "./dist/runtime/commerce.d.ts",
34
34
  "import": "./dist/runtime/commerce.js"
35
35
  },
36
+ "./prerender": {
37
+ "types": "./dist/runtime/prerenderMemo.d.ts",
38
+ "import": "./dist/runtime/prerenderMemo.js"
39
+ },
36
40
  "./locales": {
37
41
  "types": "./dist/runtime/locales.d.ts",
38
42
  "import": "./dist/runtime/locales.js"
@@ -46,10 +50,10 @@
46
50
  "dependencies": {
47
51
  "@nuxt/kit": "^4.0.0",
48
52
  "defu": "^6.1.4",
53
+ "@eldrajs/sdk": "^0.3.2",
49
54
  "@eldrajs/theme-core": "^0.3.1",
50
- "@eldrajs/theme-vue": "^0.2.2",
51
55
  "@eldrajs/vite-plugin-theme": "^0.3.1",
52
- "@eldrajs/sdk": "^0.3.1"
56
+ "@eldrajs/theme-vue": "^0.2.2"
53
57
  },
54
58
  "devDependencies": {
55
59
  "@nuxt/module-builder": "^0.8.4",