@websolutespa/bom-next 4.0.0-next.18 → 4.0.0-next.19

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
@@ -1,5 +1,15 @@
1
1
  # @websolutespa/bom-next
2
2
 
3
+ ## 4.0.0-next.19
4
+
5
+ ### Patch Changes
6
+
7
+ - With Cache Components, a build that reads MongoDB no longer fails with "Unexpected cache miss after cache warming phase" and then "Next.js encountered uncached or runtime data during prerendering" (memory builds were not affected).
8
+ - `createPageContext` and `createLayoutContext` awaited the Payload instance and the mixer context (locales, markets, categories and routes, read from the database) before calling their `'use cache'` loaders. A prerender's warming phase only waits for the cache fills that have started, so it ended with nothing cached and the final prerender missed. On a public read (Cache Components, no draft, no headers) they now call the cached loaders first and load nothing else: the loaders already load the guest Payload instance and the mixer context inside their scope. A cache hit at runtime no longer reads the mixer context either.
9
+ - Drafts, live preview, requests with headers and the classic model load the Payload instance and the mixer context as before, once per call.
10
+ - `decorateLazyComponents`: a decorator registered with `cache: false` on a public read gets the guest Payload instance and the mixer context of the page even when no uncached render has loaded them in the process yet.
11
+ - No change is needed in apps.
12
+
3
13
  ## 4.0.0-next.18
4
14
 
5
15
  ### Patch Changes
@@ -1 +1 @@
1
- {"version":3,"file":"context.d.ts","names":[],"sources":["../../src/server/context.ts"],"mappings":";;;;;;;iBAwEgB,eAAA,CAAgB,KAAA;AAAhC;;;;;AAAA,KA2HY,cAAA;EACV,MAAA;EACA,MAAA;EACA,IAAA;EACA,EAAA;EACA,IAAA,EAAM,WAAA,EAFN;EAIA,MAAA;AAAA;;iBAIc,iBAAA,CAAA,GAAqB,cAAA;;;AAArC;;;iBASsB,qBAAA,CAAsB,IAAA,EAAM,cAAA,GAAc,OAAA;;;;;;;;;;;iBAwDhD,cAAA,CAAA;;iBAWA,cAAA,CAAA,GAAkB,WAAA;AAAA,iBAIZ,cAAA,eAA6B,cAAA,GAAiB,cAAA,CAAA,CAAA,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AAQ,eAAA,GAChB,OAAA,GAAU,eAAA,GACT,OAAA,CAAQ,gBAAA,CAAiB,KAAA;AA1D5B;;;;AAAA,iBA2LgB,qBAAA,eACA,cAAA,kBACE,UAAA,CAAW,KAAA,+BACX,YAAA,GAAe,aAAA,CAAA,CAE/B,MAAA,UACA,MAAA,UACA,IAAA,EAAM,KAAA,EACN,EAAA,UACA,OAAA,EAAS,kBAAA,CAAmB,KAAA,EAAO,OAAA,EAAS,OAAA,IAC3C,OAAA,CAAQ,gBAAA,CAAiB,KAAA,EAAO,OAAA,EAAS,OAAA;;iBAE5B,qBAAA,eAAoC,cAAA,CAAA,CAClD,MAAA,UACA,MAAA,UACA,IAAA,EAAM,KAAA,EACN,EAAA,UACA,MAAA,EAAQ,OAAA,CAAQ,eAAA,GAChB,OAAA,GAAU,eAAA,GACT,OAAA,CAAQ,gBAAA,CAAiB,KAAA;;;;iBA+BZ,mBAAA,CACd,MAAA,UACA,MAAA,UACA,OAAA,EAAS,oBAAA,GACR,OAAA,CAAQ,YAAA;;iBAEK,mBAAA,CACd,MAAA,UACA,MAAA,UACA,MAAA,EAAQ,OAAA,CAAQ,eAAA,GAChB,OAAA,GAAU,eAAA,GACT,OAAA,CAAQ,YAAA"}
@@ -1,4 +1,4 @@
1
- import "../lib/const.js";
1
+ import { guest } from "../lib/const.js";
2
2
  import { getLabelFromLabels } from "../lib/label.js";
3
3
  import { getLink } from "../lib/link.js";
4
4
  import { resolveLivePreview } from "./live-preview.js";
@@ -120,6 +120,20 @@ const cachedLayout = bomCached("layout-context", async (market, locale, depth) =
120
120
  life: "bom-layout",
121
121
  tags: (market, locale) => layoutCacheTags(market, locale)
122
122
  });
123
+ /**
124
+ * Payload instance, user and mixer context of the request, loaded on first use. The cached path never calls it: a
125
+ * prerender warms only the `'use cache'` fills that have started, so uncached I/O awaited before them (the mixer
126
+ * context reads the database) ends the warming phase with nothing cached and fails the final prerender with
127
+ * "Unexpected cache miss after cache warming phase". The cached loaders load the same data inside their scope.
128
+ */
129
+ function lazyRequest(config, headers, draft, market, locale) {
130
+ let promise;
131
+ return () => promise ??= getRequestPayload(config, headers, draft).then(async ({ payload, user, getContext }) => ({
132
+ payload,
133
+ user,
134
+ context: await getContext(market, locale)
135
+ }));
136
+ }
123
137
  /** Whether this read goes through the cached loaders (Cache Components, public, not a draft). */
124
138
  function isCachedRead(draft, headers) {
125
139
  return cacheMode === "components" && !draft && !headers;
@@ -203,8 +217,14 @@ async function setPageContext(data) {
203
217
  async function createPageContext(market, locale, slug, id, optionsOrConfig, headers) {
204
218
  const options = toPageOptions("createPageContext", optionsOrConfig, headers);
205
219
  const draft = await resolveDraft(options.draft);
206
- const { payload, user, getContext } = await getRequestPayload(options.config, options.headers, draft);
207
- const context = await getContext(market, locale);
220
+ const cached = isCachedRead(draft, options.headers);
221
+ if (cached) cachedLoadConfig = options.config;
222
+ const request = lazyRequest(options.config, options.headers, draft, market, locale);
223
+ const { payload, user, context } = cached ? {
224
+ payload: void 0,
225
+ user: guest,
226
+ context: void 0
227
+ } : await request();
208
228
  const live = draft ? await resolveLivePreview(market, locale, String(slug), id) : void 0;
209
229
  PageContext().set("live", live);
210
230
  const pageRead = {
@@ -215,8 +235,6 @@ async function createPageContext(market, locale, slug, id, optionsOrConfig, head
215
235
  joins: options.joins,
216
236
  ...live?.data ? { data: live.data } : {}
217
237
  };
218
- const cached = isCachedRead(draft, options.headers);
219
- if (cached) cachedLoadConfig = options.config;
220
238
  const pagePromise = memoize(stableStringify([
221
239
  "page",
222
240
  market,
@@ -229,7 +247,9 @@ async function createPageContext(market, locale, slug, id, optionsOrConfig, head
229
247
  const layoutOptions = options.layout;
230
248
  const layoutPromise = layoutOptions === false ? Promise.resolve(void 0) : (async () => {
231
249
  const layoutDraft = layoutOptions?.draft === void 0 ? draft : await resolveDraft(layoutOptions.draft);
232
- return cached && !layoutDraft ? cachedLayout(market, locale, layoutOptions?.depth ?? 1) : loadLayout(market, locale, payload, user, context, {
250
+ if (cached && !layoutDraft) return cachedLayout(market, locale, layoutOptions?.depth ?? 1);
251
+ const req = await request();
252
+ return loadLayout(market, locale, req.payload, req.user, req.context, {
233
253
  depth: layoutOptions?.depth,
234
254
  draft: layoutDraft
235
255
  });
@@ -286,14 +306,19 @@ async function createLayoutContext(market, locale, optionsOrConfig, headers) {
286
306
  };
287
307
  } else options = optionsOrConfig;
288
308
  const draft = await resolveDraft(options.draft);
289
- const { payload, user, getContext } = await getRequestPayload(options.config, options.headers, draft);
290
- const context = await getContext(market, locale);
291
309
  const cached = isCachedRead(draft, options.headers);
292
310
  if (cached) cachedLoadConfig = options.config;
293
- const layout = cached ? await cachedLayout(market, locale, options.depth ?? 1) : await loadLayout(market, locale, payload, user, context, {
294
- depth: options.depth,
295
- draft
296
- });
311
+ let user = guest;
312
+ let layout;
313
+ if (cached) layout = await cachedLayout(market, locale, options.depth ?? 1);
314
+ else {
315
+ const req = await lazyRequest(options.config, options.headers, draft, market, locale)();
316
+ user = req.user;
317
+ layout = await loadLayout(market, locale, req.payload, req.user, req.context, {
318
+ depth: options.depth,
319
+ draft
320
+ });
321
+ }
297
322
  if (!draft) await tagPage(() => layoutCacheTags(market, locale));
298
323
  const { page: _page, ...pageContext } = toPageContext(layout, void 0, user);
299
324
  await setPageContext(pageContext);
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../../src/server/context.ts"],"sourcesContent":["import 'server-only';\r\n\r\nimport { getIsDevelopment, type ILayout } from '@websolutespa/bom-core';\r\nimport {\r\n categoryTag,\r\n layoutCacheTags,\r\n routeCacheTags,\r\n type User,\r\n} from '@websolutespa/payload-plugin-bowl';\r\nimport type { CollectionSlug, SanitizedConfig } from 'payload';\r\nimport { cache } from 'react';\r\nimport { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH } from '../lib/const';\r\nimport { getLabelFromLabels } from '../lib/label';\r\nimport { getLink } from '../lib/link';\r\nimport type {\r\n IPageContext,\r\n LayoutContextOptions,\r\n LayoutOption,\r\n LayoutOptions,\r\n MixerContext,\r\n PageContextOptions,\r\n PageSelect,\r\n ReadOptions,\r\n ReadonlyHeaders,\r\n TypedPage,\r\n TypedPageContext,\r\n} from '../types';\r\nimport { getLayout } from './layout';\r\nimport { resolveLivePreview, type LiveContext } from './live-preview';\r\nimport { getPayload, resolveDraft } from './mixer';\r\nimport { cacheMode } from '@websolutespa/bom-next/cache-mode';\r\nimport { bomCached } from './cache/cached';\r\nimport { tagPage } from './cache/tag-page';\r\nimport type { MixerPayload } from './mixer-payload';\r\nimport { getPage } from './page';\r\n\r\n/**\r\n * Per-request context store (React.cache ensures a fresh Map per RSC render).\r\n * Safe to use inside Next.js server components — do NOT call this at build time.\r\n */\r\nconst PageContext = cache(() => {\r\n return new Map<string, any>();\r\n});\r\n\r\n/**\r\n * Per-request memo of page and layout loads, keyed by a serialized string.\r\n * React `cache` compares object arguments by identity, so options objects\r\n * built inline by each caller would never hit: the key is serialized instead.\r\n */\r\nconst RequestMemo = cache(() => {\r\n return new Map<string, Promise<unknown>>();\r\n});\r\n\r\n/** Payload instance + authenticated user, resolved once per request. */\r\nconst getRequestPayload = cache(\r\n (config: Promise<SanitizedConfig>, headers: ReadonlyHeaders | undefined, draft: boolean) => {\r\n return getPayload({ config, headers, draft });\r\n }\r\n);\r\n\r\nfunction memoize<T>(key: string, factory: () => Promise<T>): Promise<T> {\r\n const memo = RequestMemo();\r\n let promise = memo.get(key) as Promise<T> | undefined;\r\n if (!promise) {\r\n promise = factory();\r\n memo.set(key, promise);\r\n promise.catch(() => memo.delete(key));\r\n }\r\n return promise;\r\n}\r\n\r\n/** JSON serialization with sorted keys, so equivalent options produce the same key. */\r\nexport function stableStringify(value: unknown): string {\r\n return JSON.stringify(value, (_, item) => {\r\n if (item && typeof item === 'object' && !Array.isArray(item)) {\r\n return Object.keys(item)\r\n .sort()\r\n .reduce(\r\n (sorted, key) => {\r\n sorted[key] = item[key];\r\n return sorted;\r\n },\r\n {} as Record<string, unknown>\r\n );\r\n }\r\n return item;\r\n });\r\n}\r\n\r\nfunction getUserKey(user: User | null | undefined): string {\r\n if (user && 'id' in user && user.id !== undefined && user.id !== null) {\r\n return `${(user as { collection?: string }).collection || 'user'}:${user.id}`;\r\n }\r\n return 'guest';\r\n}\r\n\r\nfunction isPromiseLike(value: unknown): value is Promise<SanitizedConfig> {\r\n return !!value && typeof (value as PromiseLike<unknown>).then === 'function';\r\n}\r\n\r\nconst warnedLegacySignatures = new Set<string>();\r\n\r\nfunction warnLegacySignature(name: string, signature: string) {\r\n if (getIsDevelopment() && !warnedLegacySignatures.has(name)) {\r\n warnedLegacySignatures.add(name);\r\n console.warn(\r\n `[bom-next] ${name}(..., config, headers) is deprecated. Use ${name}(${signature}, { config, headers }) instead.`\r\n );\r\n }\r\n}\r\n\r\nfunction toPageOptions<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug>,\r\n TLayout extends LayoutOption,\r\n>(\r\n name: string,\r\n optionsOrConfig: PageContextOptions<TSlug, TSelect, TLayout> | Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): PageContextOptions<TSlug, TSelect, TLayout> {\r\n if (isPromiseLike(optionsOrConfig)) {\r\n warnLegacySignature(name, 'market, locale, slug, id');\r\n return { config: optionsOrConfig, headers };\r\n }\r\n return optionsOrConfig;\r\n}\r\n\r\n/**\r\n * Config of the cached loads below. A `'use cache'` function cannot take it as an argument (a promise is not part\r\n * of a cache key), so the context functions set it before calling them; it is the same for every request.\r\n */\r\nlet cachedLoadConfig: Promise<SanitizedConfig> | undefined;\r\n\r\nasync function cachedLoadPayload() {\r\n if (!cachedLoadConfig) {\r\n throw new Error('[bom-next] cached context loaded before createPageContext set its config.');\r\n }\r\n return getPayload({ config: cachedLoadConfig, draft: false });\r\n}\r\n\r\n/**\r\n * Cache Components only: public page and layout reads as cached functions with BOM lifetimes and route tags, so\r\n * the page prerenders and updates on tag invalidation. Classic ISR caches the rendered page instead and never\r\n * calls these. Requests with headers (users, protected pages) and drafts read directly.\r\n */\r\nconst cachedPage = bomCached(\r\n 'page-context',\r\n async (market: string, locale: string, slug: string, id: string, read: ReadOptions) => {\r\n const { payload, user, getContext } = await cachedLoadPayload();\r\n return getPage(\r\n slug as CollectionSlug,\r\n id,\r\n market,\r\n locale,\r\n payload,\r\n user,\r\n await getContext(market, locale),\r\n read\r\n );\r\n },\r\n {\r\n life: 'bom-page',\r\n tags: (market, locale, slug, id) => routeCacheTags({ market, locale, schema: slug, page: id }),\r\n resultTags: (page) =>\r\n ((page as { breadcrumb?: { category?: unknown }[] } | undefined)?.breadcrumb ?? [])\r\n .map((crumb) => crumb.category)\r\n .filter((category): category is string | number =>\r\n /^[\\w.-]{1,96}$/.test(String(category ?? ''))\r\n )\r\n .map((category) => categoryTag(category)),\r\n }\r\n);\r\n\r\nconst cachedLayout = bomCached(\r\n 'layout-context',\r\n async (market: string, locale: string, depth: number) => {\r\n const { payload, user, getContext } = await cachedLoadPayload();\r\n return getLayout(market, locale, payload, user, await getContext(market, locale), {\r\n depth,\r\n draft: false,\r\n });\r\n },\r\n { life: 'bom-layout', tags: (market, locale) => layoutCacheTags(market, locale) }\r\n);\r\n\r\n/** Whether this read goes through the cached loaders (Cache Components, public, not a draft). */\r\nfunction isCachedRead(draft: boolean, headers: ReadonlyHeaders | undefined): boolean {\r\n return cacheMode === 'components' && !draft && !headers;\r\n}\r\n\r\n/**\r\n * Serializable description of a page context read through the cached loaders. Code that must run in its own\r\n * `'use cache'` scope (the lazy decorators) receives it as a cache key argument and rebuilds the same context there\r\n * with `loadCachedPageContext`, since the payload instance and the `label`/`link` functions cannot cross the scope.\r\n */\r\nexport type CachedPageRead = {\r\n market: string;\r\n locale: string;\r\n slug: string;\r\n id: string;\r\n page: ReadOptions;\r\n /** Depth of the public layout read. */\r\n layout: number;\r\n};\r\n\r\n/** The cached read of the page context created in this request: set only for public Cache Components renders. */\r\nexport function getCachedPageRead(): CachedPageRead | undefined {\r\n return PageContext().get('cachedRead');\r\n}\r\n\r\n/**\r\n * Rebuilds, inside a cache scope, the context `createPageContext` produced for a cached read: the guest Payload\r\n * instance, the mixer context of the market and locale, and the page context. The page and layout come from the\r\n * same cached loaders, so they are cache hits.\r\n */\r\nexport async function loadCachedPageContext(read: CachedPageRead) {\r\n const { payload, user, getContext } = await cachedLoadPayload();\r\n const [context, layout, page] = await Promise.all([\r\n getContext(read.market, read.locale),\r\n cachedLayout(read.market, read.locale, read.layout),\r\n cachedPage(read.market, read.locale, read.slug, read.id, read.page),\r\n ]);\r\n return {\r\n payload,\r\n context,\r\n pageContext: toPageContext<CollectionSlug, undefined, LayoutOptions>(\r\n layout,\r\n page as TypedPage<CollectionSlug, undefined> | undefined,\r\n user\r\n ),\r\n };\r\n}\r\n\r\nfunction loadLayout(\r\n market: string,\r\n locale: string,\r\n payload: MixerPayload,\r\n user: User,\r\n mixerContext: MixerContext,\r\n readOptions: { depth?: number; draft: boolean }\r\n): Promise<ILayout> {\r\n const read = { depth: readOptions.depth ?? DEFAULT_LAYOUT_DEPTH, draft: readOptions.draft };\r\n const key = stableStringify(['layout', market, locale, getUserKey(user), read]);\r\n return memoize(key, () => getLayout(market, locale, payload, user, mixerContext, read));\r\n}\r\n\r\nfunction toPageContext<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug>,\r\n TLayout extends LayoutOption,\r\n>(\r\n layout: ILayout | undefined,\r\n page: TypedPage<TSlug, TSelect> | undefined,\r\n user: User\r\n): TypedPageContext<TSlug, TSelect, TLayout> {\r\n return {\r\n layout,\r\n // shallow copy: the memoized document is shared by every caller in the request\r\n page: page ? { ...page } : undefined,\r\n user,\r\n label: getLabelFromLabels(layout?.labels ?? []),\r\n link: (category: string) => (layout ? getLink(category, layout) : undefined),\r\n } as TypedPageContext<TSlug, TSelect, TLayout>;\r\n}\r\n\r\n/**\r\n * Every page object `createPageContext` returned in this request. Each caller gets its own shallow copy, and only\r\n * the last one is stored as the context page: when `generateMetadata` reads the same page after the template, the\r\n * template's copy is no longer the stored one. `decorateLazyComponents` uses this list to decorate every copy of\r\n * the page it decorates.\r\n */\r\nexport function getIssuedPages(): object[] {\r\n const context = PageContext();\r\n let pages = context.get('pages') as object[] | undefined;\r\n if (!pages) {\r\n pages = [];\r\n context.set('pages', pages);\r\n }\r\n return pages;\r\n}\r\n\r\n/** The live preview session of the page created in this request, if any. */\r\nexport function getLiveContext(): LiveContext | undefined {\r\n return PageContext().get('live');\r\n}\r\n\r\nexport async function getPageContext<TSlug extends CollectionSlug = CollectionSlug>(): Promise<\r\n TypedPageContext<TSlug>\r\n> {\r\n return {\r\n layout: PageContext().get('layout'),\r\n page: PageContext().get('page'),\r\n user: PageContext().get('user') || null,\r\n label: PageContext().get('label'),\r\n link: PageContext().get('link'),\r\n } as TypedPageContext<TSlug>;\r\n}\r\n\r\nexport async function setPageContext<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug> = undefined,\r\n TLayout extends LayoutOption = LayoutOptions,\r\n>(data: Partial<TypedPageContext<TSlug, TSelect, TLayout>>) {\r\n const context = PageContext();\r\n for (const key in data) {\r\n context.set(key, data[key as keyof IPageContext]);\r\n }\r\n}\r\n\r\n/**\r\n * Initialises the full page context using Payload local API.\r\n *\r\n * Page and layout are fetched in parallel and memoized per request, so\r\n * `getMetadata` and the page component share the same reads. The mixer\r\n * context (routes + categories) is passed to every payload read so that\r\n * payload-plugin-bowl can enrich responses, including populated documents.\r\n *\r\n * @example\r\n * const { page, label, link } = await createPageContext(market, locale, 'post_detail', id, {\r\n * config,\r\n * depth: 2,\r\n * select: { title: true, abstract: true, media: true, components: true },\r\n * populate: { media: { url: true, alt: true, width: true, height: true, type: true } },\r\n * });\r\n */\r\nexport function createPageContext<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug> = undefined,\r\n TLayout extends LayoutOption = LayoutOptions,\r\n>(\r\n market: string,\r\n locale: string,\r\n slug: TSlug,\r\n id: string,\r\n options: PageContextOptions<TSlug, TSelect, TLayout>\r\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>>;\r\n/** @deprecated Use `createPageContext(market, locale, slug, id, { config, headers })`. */\r\nexport function createPageContext<TSlug extends CollectionSlug>(\r\n market: string,\r\n locale: string,\r\n slug: TSlug,\r\n id: string,\r\n config: Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): Promise<TypedPageContext<TSlug>>;\r\nexport async function createPageContext<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug> = undefined,\r\n TLayout extends LayoutOption = LayoutOptions,\r\n>(\r\n market: string,\r\n locale: string,\r\n slug: TSlug,\r\n id: string,\r\n optionsOrConfig: PageContextOptions<TSlug, TSelect, TLayout> | Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>> {\r\n const options = toPageOptions<TSlug, TSelect, TLayout>(\r\n 'createPageContext',\r\n optionsOrConfig,\r\n headers\r\n );\r\n\r\n const draft = await resolveDraft(options.draft);\r\n const { payload, user, getContext } = await getRequestPayload(\r\n options.config,\r\n options.headers,\r\n draft\r\n );\r\n const context = await getContext(market, locale);\r\n\r\n // live preview: the values the editor has not saved yet replace the stored document (drafts only, never cached)\r\n const live = draft ? await resolveLivePreview(market, locale, String(slug), id) : undefined;\r\n PageContext().set('live', live);\r\n\r\n const pageRead: ReadOptions = {\r\n draft,\r\n depth: options.depth ?? DEFAULT_PAGE_DEPTH,\r\n select: options.select as ReadOptions['select'],\r\n populate: options.populate,\r\n joins: options.joins as ReadOptions['joins'],\r\n ...(live?.data ? { data: live.data } : {}),\r\n };\r\n const cached = isCachedRead(draft, options.headers);\r\n if (cached) {\r\n cachedLoadConfig = options.config;\r\n }\r\n const pageKey = stableStringify(['page', market, locale, slug, id, getUserKey(user), pageRead]);\r\n const pagePromise = memoize(pageKey, () =>\r\n cached\r\n ? (cachedPage(market, locale, String(slug), id, pageRead) as Promise<\r\n TypedPage<TSlug, TSelect> | undefined\r\n >)\r\n : getPage<TSlug, TSelect>(slug, id, market, locale, payload, user, context, pageRead)\r\n );\r\n\r\n const layoutOptions = options.layout;\r\n const layoutPromise =\r\n layoutOptions === false\r\n ? Promise.resolve(undefined)\r\n : (async () => {\r\n const layoutDraft =\r\n layoutOptions?.draft === undefined ? draft : await resolveDraft(layoutOptions.draft);\r\n return cached && !layoutDraft\r\n ? cachedLayout(market, locale, layoutOptions?.depth ?? DEFAULT_LAYOUT_DEPTH)\r\n : loadLayout(market, locale, payload, user, context, {\r\n depth: layoutOptions?.depth,\r\n draft: layoutDraft,\r\n });\r\n })();\r\n\r\n const [layout, page] = await Promise.all([layoutPromise, pagePromise]);\r\n\r\n // lets the lazy decorators run in a cache scope of their own (a public read with a public layout only)\r\n const layoutDraft =\r\n layoutOptions === false || layoutOptions?.draft === undefined\r\n ? draft\r\n : await resolveDraft(layoutOptions.draft);\r\n const cachedRead: CachedPageRead | undefined =\r\n cached && !layoutDraft\r\n ? {\r\n market,\r\n locale,\r\n slug: String(slug),\r\n id,\r\n page: pageRead,\r\n // a template that skips the layout keeps the root layout's (default depth) for this request\r\n layout: (layoutOptions !== false && layoutOptions?.depth) || DEFAULT_LAYOUT_DEPTH,\r\n }\r\n : undefined;\r\n PageContext().set('cachedRead', cachedRead);\r\n\r\n // cache tags of the rendered route (a missing page is tagged too, so publishing it expires the cached 404);\r\n // draft renders bypass the ISR cache\r\n if (!draft) {\r\n const breadcrumb = (page as { breadcrumb?: { category?: unknown }[] } | undefined)?.breadcrumb;\r\n await tagPage(() => [\r\n ...routeCacheTags({\r\n market,\r\n locale,\r\n schema: String(slug),\r\n page: id,\r\n categories: (breadcrumb ?? [])\r\n .map((crumb) => crumb.category)\r\n .filter(\r\n (category): category is string | number =>\r\n typeof category === 'string' || typeof category === 'number'\r\n ),\r\n }),\r\n ...(layout ? layoutCacheTags(market, locale) : []),\r\n ]);\r\n }\r\n\r\n const pageContext = toPageContext<TSlug, TSelect, TLayout>(layout, page, user);\r\n if (pageContext.page) {\r\n getIssuedPages().push(pageContext.page);\r\n }\r\n\r\n if (layout) {\r\n await setPageContext(pageContext);\r\n } else {\r\n // layout skipped: keep any layout already stored for this request\r\n await setPageContext({ page: pageContext.page, user: pageContext.user });\r\n }\r\n\r\n return pageContext;\r\n}\r\n\r\n/**\r\n * Same as createPageContext but without draft mode — used for error/not-found pages\r\n * that should always show published content regardless of draft mode state.\r\n */\r\nexport function createNotFoundContext<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug> = undefined,\r\n TLayout extends LayoutOption = LayoutOptions,\r\n>(\r\n market: string,\r\n locale: string,\r\n slug: TSlug,\r\n id: string,\r\n options: PageContextOptions<TSlug, TSelect, TLayout>\r\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>>;\r\n/** @deprecated Use `createNotFoundContext(market, locale, slug, id, { config, headers })`. */\r\nexport function createNotFoundContext<TSlug extends CollectionSlug>(\r\n market: string,\r\n locale: string,\r\n slug: TSlug,\r\n id: string,\r\n config: Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): Promise<TypedPageContext<TSlug>>;\r\nexport async function createNotFoundContext<\r\n TSlug extends CollectionSlug,\r\n TSelect extends PageSelect<TSlug> = undefined,\r\n TLayout extends LayoutOption = LayoutOptions,\r\n>(\r\n market: string,\r\n locale: string,\r\n slug: TSlug,\r\n id: string,\r\n optionsOrConfig: PageContextOptions<TSlug, TSelect, TLayout> | Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>> {\r\n const options = toPageOptions<TSlug, TSelect, TLayout>(\r\n 'createNotFoundContext',\r\n optionsOrConfig,\r\n headers\r\n );\r\n const layout = (\r\n options.layout === false ? false : { ...options.layout, draft: false }\r\n ) as TLayout;\r\n return createPageContext<TSlug, TSelect, TLayout>(market, locale, slug, id, {\r\n ...options,\r\n draft: false,\r\n layout,\r\n });\r\n}\r\n\r\n/**\r\n * Layout-only context — no page fetch. Used by RootLayout server components.\r\n */\r\nexport function createLayoutContext(\r\n market: string,\r\n locale: string,\r\n options: LayoutContextOptions\r\n): Promise<IPageContext>;\r\n/** @deprecated Use `createLayoutContext(market, locale, { config, headers })`. */\r\nexport function createLayoutContext(\r\n market: string,\r\n locale: string,\r\n config: Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): Promise<IPageContext>;\r\nexport async function createLayoutContext(\r\n market: string,\r\n locale: string,\r\n optionsOrConfig: LayoutContextOptions | Promise<SanitizedConfig>,\r\n headers?: ReadonlyHeaders\r\n): Promise<IPageContext> {\r\n let options: LayoutContextOptions;\r\n if (isPromiseLike(optionsOrConfig)) {\r\n warnLegacySignature('createLayoutContext', 'market, locale');\r\n options = { config: optionsOrConfig, headers };\r\n } else {\r\n options = optionsOrConfig;\r\n }\r\n\r\n const draft = await resolveDraft(options.draft);\r\n const { payload, user, getContext } = await getRequestPayload(\r\n options.config,\r\n options.headers,\r\n draft\r\n );\r\n const context = await getContext(market, locale);\r\n\r\n const cached = isCachedRead(draft, options.headers);\r\n if (cached) {\r\n cachedLoadConfig = options.config;\r\n }\r\n const layout = cached\r\n ? await cachedLayout(market, locale, options.depth ?? DEFAULT_LAYOUT_DEPTH)\r\n : await loadLayout(market, locale, payload, user, context, {\r\n depth: options.depth,\r\n draft,\r\n });\r\n if (!draft) {\r\n await tagPage(() => layoutCacheTags(market, locale));\r\n }\r\n\r\n const { page: _page, ...pageContext } = toPageContext<CollectionSlug, undefined, LayoutOptions>(\r\n layout,\r\n undefined,\r\n user\r\n );\r\n\r\n await setPageContext(pageContext);\r\n\r\n return pageContext as IPageContext;\r\n}\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwCA,MAAM,cAAc,YAAY;AAC9B,wBAAO,IAAI,KAAkB;EAC7B;;;;;;AAOF,MAAM,cAAc,YAAY;AAC9B,wBAAO,IAAI,KAA+B;EAC1C;;AAGF,MAAM,oBAAoB,OACvB,QAAkC,SAAsC,UAAmB;AAC1F,QAAO,WAAW;EAAE;E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;GAAiB;GAAS;OAE9C,WAAU;CAGZ,MAAM,QAAQ,MAAM,aAAa,QAAQ,MAAM;CAC/C,MAAM,EAAE,SAAS,MAAM,eAAe,MAAM,kBAC1C,QAAQ,QACR,QAAQ,SACR,MACD;CACD,MAAM,UAAU,MAAM,WAAW,QAAQ,OAAO;CAEhD,MAAM,SAAS,aAAa,OAAO,QAAQ,QAAQ;AACnD,KAAI,OACF,oBAAmB,QAAQ;CAE7B,MAAM,SAAS,SACX,MAAM,aAAa,QAAQ,QAAQ,QAAQ,SAAA,EAA8B,GACzE,MAAM,WAAW,QAAQ,QAAQ,SAAS,MAAM,SAAS;EACvD,OAAO,QAAQ;EACf;EACD,CAAC;AACN,KAAI,CAAC,MACH,OAAM,cAAc,gBAAgB,QAAQ,OAAO,CAAC;CAGtD,MAAM,EAAE,MAAM,OAAO,GAAG,gBAAgB,cACtC,QACA,KAAA,GACA,KACD;AAED,OAAM,eAAe,YAAY;AAEjC,QAAO"}
1
+ {"version":3,"file":"context.js","names":[],"sources":["../../src/server/context.ts"],"sourcesContent":["import 'server-only';\n\nimport { getIsDevelopment, type ILayout } from '@websolutespa/bom-core';\nimport {\n categoryTag,\n layoutCacheTags,\n routeCacheTags,\n type User,\n} from '@websolutespa/payload-plugin-bowl';\nimport type { CollectionSlug, SanitizedConfig } from 'payload';\nimport { cache } from 'react';\nimport { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, guest } from '../lib/const';\nimport { getLabelFromLabels } from '../lib/label';\nimport { getLink } from '../lib/link';\nimport type {\n IPageContext,\n LayoutContextOptions,\n LayoutOption,\n LayoutOptions,\n MixerContext,\n PageContextOptions,\n PageSelect,\n ReadOptions,\n ReadonlyHeaders,\n TypedPage,\n TypedPageContext,\n} from '../types';\nimport { getLayout } from './layout';\nimport { resolveLivePreview, type LiveContext } from './live-preview';\nimport { getPayload, resolveDraft } from './mixer';\nimport { cacheMode } from '@websolutespa/bom-next/cache-mode';\nimport { bomCached } from './cache/cached';\nimport { tagPage } from './cache/tag-page';\nimport type { MixerPayload } from './mixer-payload';\nimport { getPage } from './page';\n\n/**\n * Per-request context store (React.cache ensures a fresh Map per RSC render).\n * Safe to use inside Next.js server components — do NOT call this at build time.\n */\nconst PageContext = cache(() => {\n return new Map<string, any>();\n});\n\n/**\n * Per-request memo of page and layout loads, keyed by a serialized string.\n * React `cache` compares object arguments by identity, so options objects\n * built inline by each caller would never hit: the key is serialized instead.\n */\nconst RequestMemo = cache(() => {\n return new Map<string, Promise<unknown>>();\n});\n\n/** Payload instance + authenticated user, resolved once per request. */\nconst getRequestPayload = cache(\n (config: Promise<SanitizedConfig>, headers: ReadonlyHeaders | undefined, draft: boolean) => {\n return getPayload({ config, headers, draft });\n }\n);\n\nfunction memoize<T>(key: string, factory: () => Promise<T>): Promise<T> {\n const memo = RequestMemo();\n let promise = memo.get(key) as Promise<T> | undefined;\n if (!promise) {\n promise = factory();\n memo.set(key, promise);\n promise.catch(() => memo.delete(key));\n }\n return promise;\n}\n\n/** JSON serialization with sorted keys, so equivalent options produce the same key. */\nexport function stableStringify(value: unknown): string {\n return JSON.stringify(value, (_, item) => {\n if (item && typeof item === 'object' && !Array.isArray(item)) {\n return Object.keys(item)\n .sort()\n .reduce(\n (sorted, key) => {\n sorted[key] = item[key];\n return sorted;\n },\n {} as Record<string, unknown>\n );\n }\n return item;\n });\n}\n\nfunction getUserKey(user: User | null | undefined): string {\n if (user && 'id' in user && user.id !== undefined && user.id !== null) {\n return `${(user as { collection?: string }).collection || 'user'}:${user.id}`;\n }\n return 'guest';\n}\n\nfunction isPromiseLike(value: unknown): value is Promise<SanitizedConfig> {\n return !!value && typeof (value as PromiseLike<unknown>).then === 'function';\n}\n\nconst warnedLegacySignatures = new Set<string>();\n\nfunction warnLegacySignature(name: string, signature: string) {\n if (getIsDevelopment() && !warnedLegacySignatures.has(name)) {\n warnedLegacySignatures.add(name);\n console.warn(\n `[bom-next] ${name}(..., config, headers) is deprecated. Use ${name}(${signature}, { config, headers }) instead.`\n );\n }\n}\n\nfunction toPageOptions<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug>,\n TLayout extends LayoutOption,\n>(\n name: string,\n optionsOrConfig: PageContextOptions<TSlug, TSelect, TLayout> | Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): PageContextOptions<TSlug, TSelect, TLayout> {\n if (isPromiseLike(optionsOrConfig)) {\n warnLegacySignature(name, 'market, locale, slug, id');\n return { config: optionsOrConfig, headers };\n }\n return optionsOrConfig;\n}\n\n/**\n * Config of the cached loads below. A `'use cache'` function cannot take it as an argument (a promise is not part\n * of a cache key), so the context functions set it before calling them; it is the same for every request.\n */\nlet cachedLoadConfig: Promise<SanitizedConfig> | undefined;\n\nasync function cachedLoadPayload() {\n if (!cachedLoadConfig) {\n throw new Error('[bom-next] cached context loaded before createPageContext set its config.');\n }\n return getPayload({ config: cachedLoadConfig, draft: false });\n}\n\n/**\n * Cache Components only: public page and layout reads as cached functions with BOM lifetimes and route tags, so\n * the page prerenders and updates on tag invalidation. Classic ISR caches the rendered page instead and never\n * calls these. Requests with headers (users, protected pages) and drafts read directly.\n */\nconst cachedPage = bomCached(\n 'page-context',\n async (market: string, locale: string, slug: string, id: string, read: ReadOptions) => {\n const { payload, user, getContext } = await cachedLoadPayload();\n return getPage(\n slug as CollectionSlug,\n id,\n market,\n locale,\n payload,\n user,\n await getContext(market, locale),\n read\n );\n },\n {\n life: 'bom-page',\n tags: (market, locale, slug, id) => routeCacheTags({ market, locale, schema: slug, page: id }),\n resultTags: (page) =>\n ((page as { breadcrumb?: { category?: unknown }[] } | undefined)?.breadcrumb ?? [])\n .map((crumb) => crumb.category)\n .filter((category): category is string | number =>\n /^[\\w.-]{1,96}$/.test(String(category ?? ''))\n )\n .map((category) => categoryTag(category)),\n }\n);\n\nconst cachedLayout = bomCached(\n 'layout-context',\n async (market: string, locale: string, depth: number) => {\n const { payload, user, getContext } = await cachedLoadPayload();\n return getLayout(market, locale, payload, user, await getContext(market, locale), {\n depth,\n draft: false,\n });\n },\n { life: 'bom-layout', tags: (market, locale) => layoutCacheTags(market, locale) }\n);\n\n/**\n * Payload instance, user and mixer context of the request, loaded on first use. The cached path never calls it: a\n * prerender warms only the `'use cache'` fills that have started, so uncached I/O awaited before them (the mixer\n * context reads the database) ends the warming phase with nothing cached and fails the final prerender with\n * \"Unexpected cache miss after cache warming phase\". The cached loaders load the same data inside their scope.\n */\nfunction lazyRequest(\n config: Promise<SanitizedConfig>,\n headers: ReadonlyHeaders | undefined,\n draft: boolean,\n market: string,\n locale: string\n) {\n let promise: Promise<{ payload: MixerPayload; user: User; context: MixerContext }> | undefined;\n return () =>\n (promise ??= getRequestPayload(config, headers, draft).then(\n async ({ payload, user, getContext }) => ({\n payload,\n user,\n context: await getContext(market, locale),\n })\n ));\n}\n\n/** Whether this read goes through the cached loaders (Cache Components, public, not a draft). */\nfunction isCachedRead(draft: boolean, headers: ReadonlyHeaders | undefined): boolean {\n return cacheMode === 'components' && !draft && !headers;\n}\n\n/**\n * Serializable description of a page context read through the cached loaders. Code that must run in its own\n * `'use cache'` scope (the lazy decorators) receives it as a cache key argument and rebuilds the same context there\n * with `loadCachedPageContext`, since the payload instance and the `label`/`link` functions cannot cross the scope.\n */\nexport type CachedPageRead = {\n market: string;\n locale: string;\n slug: string;\n id: string;\n page: ReadOptions;\n /** Depth of the public layout read. */\n layout: number;\n};\n\n/** The cached read of the page context created in this request: set only for public Cache Components renders. */\nexport function getCachedPageRead(): CachedPageRead | undefined {\n return PageContext().get('cachedRead');\n}\n\n/**\n * Rebuilds, inside a cache scope, the context `createPageContext` produced for a cached read: the guest Payload\n * instance, the mixer context of the market and locale, and the page context. The page and layout come from the\n * same cached loaders, so they are cache hits.\n */\nexport async function loadCachedPageContext(read: CachedPageRead) {\n const { payload, user, getContext } = await cachedLoadPayload();\n const [context, layout, page] = await Promise.all([\n getContext(read.market, read.locale),\n cachedLayout(read.market, read.locale, read.layout),\n cachedPage(read.market, read.locale, read.slug, read.id, read.page),\n ]);\n return {\n payload,\n context,\n pageContext: toPageContext<CollectionSlug, undefined, LayoutOptions>(\n layout,\n page as TypedPage<CollectionSlug, undefined> | undefined,\n user\n ),\n };\n}\n\nfunction loadLayout(\n market: string,\n locale: string,\n payload: MixerPayload,\n user: User,\n mixerContext: MixerContext,\n readOptions: { depth?: number; draft: boolean }\n): Promise<ILayout> {\n const read = { depth: readOptions.depth ?? DEFAULT_LAYOUT_DEPTH, draft: readOptions.draft };\n const key = stableStringify(['layout', market, locale, getUserKey(user), read]);\n return memoize(key, () => getLayout(market, locale, payload, user, mixerContext, read));\n}\n\nfunction toPageContext<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug>,\n TLayout extends LayoutOption,\n>(\n layout: ILayout | undefined,\n page: TypedPage<TSlug, TSelect> | undefined,\n user: User\n): TypedPageContext<TSlug, TSelect, TLayout> {\n return {\n layout,\n // shallow copy: the memoized document is shared by every caller in the request\n page: page ? { ...page } : undefined,\n user,\n label: getLabelFromLabels(layout?.labels ?? []),\n link: (category: string) => (layout ? getLink(category, layout) : undefined),\n } as TypedPageContext<TSlug, TSelect, TLayout>;\n}\n\n/**\n * Every page object `createPageContext` returned in this request. Each caller gets its own shallow copy, and only\n * the last one is stored as the context page: when `generateMetadata` reads the same page after the template, the\n * template's copy is no longer the stored one. `decorateLazyComponents` uses this list to decorate every copy of\n * the page it decorates.\n */\nexport function getIssuedPages(): object[] {\n const context = PageContext();\n let pages = context.get('pages') as object[] | undefined;\n if (!pages) {\n pages = [];\n context.set('pages', pages);\n }\n return pages;\n}\n\n/** The live preview session of the page created in this request, if any. */\nexport function getLiveContext(): LiveContext | undefined {\n return PageContext().get('live');\n}\n\nexport async function getPageContext<TSlug extends CollectionSlug = CollectionSlug>(): Promise<\n TypedPageContext<TSlug>\n> {\n return {\n layout: PageContext().get('layout'),\n page: PageContext().get('page'),\n user: PageContext().get('user') || null,\n label: PageContext().get('label'),\n link: PageContext().get('link'),\n } as TypedPageContext<TSlug>;\n}\n\nexport async function setPageContext<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug> = undefined,\n TLayout extends LayoutOption = LayoutOptions,\n>(data: Partial<TypedPageContext<TSlug, TSelect, TLayout>>) {\n const context = PageContext();\n for (const key in data) {\n context.set(key, data[key as keyof IPageContext]);\n }\n}\n\n/**\n * Initialises the full page context using Payload local API.\n *\n * Page and layout are fetched in parallel and memoized per request, so\n * `getMetadata` and the page component share the same reads. The mixer\n * context (routes + categories) is passed to every payload read so that\n * payload-plugin-bowl can enrich responses, including populated documents.\n *\n * @example\n * const { page, label, link } = await createPageContext(market, locale, 'post_detail', id, {\n * config,\n * depth: 2,\n * select: { title: true, abstract: true, media: true, components: true },\n * populate: { media: { url: true, alt: true, width: true, height: true, type: true } },\n * });\n */\nexport function createPageContext<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug> = undefined,\n TLayout extends LayoutOption = LayoutOptions,\n>(\n market: string,\n locale: string,\n slug: TSlug,\n id: string,\n options: PageContextOptions<TSlug, TSelect, TLayout>\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>>;\n/** @deprecated Use `createPageContext(market, locale, slug, id, { config, headers })`. */\nexport function createPageContext<TSlug extends CollectionSlug>(\n market: string,\n locale: string,\n slug: TSlug,\n id: string,\n config: Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): Promise<TypedPageContext<TSlug>>;\nexport async function createPageContext<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug> = undefined,\n TLayout extends LayoutOption = LayoutOptions,\n>(\n market: string,\n locale: string,\n slug: TSlug,\n id: string,\n optionsOrConfig: PageContextOptions<TSlug, TSelect, TLayout> | Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>> {\n const options = toPageOptions<TSlug, TSelect, TLayout>(\n 'createPageContext',\n optionsOrConfig,\n headers\n );\n\n const draft = await resolveDraft(options.draft);\n const cached = isCachedRead(draft, options.headers);\n if (cached) {\n cachedLoadConfig = options.config;\n }\n // a cached read runs no database I/O before the cached loaders (see `lazyRequest`); it is always a guest\n const request = lazyRequest(options.config, options.headers, draft, market, locale);\n const { payload, user, context } = cached\n ? { payload: undefined, user: guest, context: undefined }\n : await request();\n\n // live preview: the values the editor has not saved yet replace the stored document (drafts only, never cached)\n const live = draft ? await resolveLivePreview(market, locale, String(slug), id) : undefined;\n PageContext().set('live', live);\n\n const pageRead: ReadOptions = {\n draft,\n depth: options.depth ?? DEFAULT_PAGE_DEPTH,\n select: options.select as ReadOptions['select'],\n populate: options.populate,\n joins: options.joins as ReadOptions['joins'],\n ...(live?.data ? { data: live.data } : {}),\n };\n const pageKey = stableStringify(['page', market, locale, slug, id, getUserKey(user), pageRead]);\n const pagePromise = memoize(pageKey, () =>\n cached\n ? (cachedPage(market, locale, String(slug), id, pageRead) as Promise<\n TypedPage<TSlug, TSelect> | undefined\n >)\n : getPage<TSlug, TSelect>(slug, id, market, locale, payload!, user, context!, pageRead)\n );\n\n const layoutOptions = options.layout;\n const layoutPromise =\n layoutOptions === false\n ? Promise.resolve(undefined)\n : (async () => {\n const layoutDraft =\n layoutOptions?.draft === undefined ? draft : await resolveDraft(layoutOptions.draft);\n if (cached && !layoutDraft) {\n return cachedLayout(market, locale, layoutOptions?.depth ?? DEFAULT_LAYOUT_DEPTH);\n }\n const req = await request();\n return loadLayout(market, locale, req.payload, req.user, req.context, {\n depth: layoutOptions?.depth,\n draft: layoutDraft,\n });\n })();\n\n const [layout, page] = await Promise.all([layoutPromise, pagePromise]);\n\n // lets the lazy decorators run in a cache scope of their own (a public read with a public layout only)\n const layoutDraft =\n layoutOptions === false || layoutOptions?.draft === undefined\n ? draft\n : await resolveDraft(layoutOptions.draft);\n const cachedRead: CachedPageRead | undefined =\n cached && !layoutDraft\n ? {\n market,\n locale,\n slug: String(slug),\n id,\n page: pageRead,\n // a template that skips the layout keeps the root layout's (default depth) for this request\n layout: (layoutOptions !== false && layoutOptions?.depth) || DEFAULT_LAYOUT_DEPTH,\n }\n : undefined;\n PageContext().set('cachedRead', cachedRead);\n\n // cache tags of the rendered route (a missing page is tagged too, so publishing it expires the cached 404);\n // draft renders bypass the ISR cache\n if (!draft) {\n const breadcrumb = (page as { breadcrumb?: { category?: unknown }[] } | undefined)?.breadcrumb;\n await tagPage(() => [\n ...routeCacheTags({\n market,\n locale,\n schema: String(slug),\n page: id,\n categories: (breadcrumb ?? [])\n .map((crumb) => crumb.category)\n .filter(\n (category): category is string | number =>\n typeof category === 'string' || typeof category === 'number'\n ),\n }),\n ...(layout ? layoutCacheTags(market, locale) : []),\n ]);\n }\n\n const pageContext = toPageContext<TSlug, TSelect, TLayout>(layout, page, user);\n if (pageContext.page) {\n getIssuedPages().push(pageContext.page);\n }\n\n if (layout) {\n await setPageContext(pageContext);\n } else {\n // layout skipped: keep any layout already stored for this request\n await setPageContext({ page: pageContext.page, user: pageContext.user });\n }\n\n return pageContext;\n}\n\n/**\n * Same as createPageContext but without draft mode — used for error/not-found pages\n * that should always show published content regardless of draft mode state.\n */\nexport function createNotFoundContext<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug> = undefined,\n TLayout extends LayoutOption = LayoutOptions,\n>(\n market: string,\n locale: string,\n slug: TSlug,\n id: string,\n options: PageContextOptions<TSlug, TSelect, TLayout>\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>>;\n/** @deprecated Use `createNotFoundContext(market, locale, slug, id, { config, headers })`. */\nexport function createNotFoundContext<TSlug extends CollectionSlug>(\n market: string,\n locale: string,\n slug: TSlug,\n id: string,\n config: Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): Promise<TypedPageContext<TSlug>>;\nexport async function createNotFoundContext<\n TSlug extends CollectionSlug,\n TSelect extends PageSelect<TSlug> = undefined,\n TLayout extends LayoutOption = LayoutOptions,\n>(\n market: string,\n locale: string,\n slug: TSlug,\n id: string,\n optionsOrConfig: PageContextOptions<TSlug, TSelect, TLayout> | Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): Promise<TypedPageContext<TSlug, TSelect, TLayout>> {\n const options = toPageOptions<TSlug, TSelect, TLayout>(\n 'createNotFoundContext',\n optionsOrConfig,\n headers\n );\n const layout = (\n options.layout === false ? false : { ...options.layout, draft: false }\n ) as TLayout;\n return createPageContext<TSlug, TSelect, TLayout>(market, locale, slug, id, {\n ...options,\n draft: false,\n layout,\n });\n}\n\n/**\n * Layout-only context — no page fetch. Used by RootLayout server components.\n */\nexport function createLayoutContext(\n market: string,\n locale: string,\n options: LayoutContextOptions\n): Promise<IPageContext>;\n/** @deprecated Use `createLayoutContext(market, locale, { config, headers })`. */\nexport function createLayoutContext(\n market: string,\n locale: string,\n config: Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): Promise<IPageContext>;\nexport async function createLayoutContext(\n market: string,\n locale: string,\n optionsOrConfig: LayoutContextOptions | Promise<SanitizedConfig>,\n headers?: ReadonlyHeaders\n): Promise<IPageContext> {\n let options: LayoutContextOptions;\n if (isPromiseLike(optionsOrConfig)) {\n warnLegacySignature('createLayoutContext', 'market, locale');\n options = { config: optionsOrConfig, headers };\n } else {\n options = optionsOrConfig;\n }\n\n const draft = await resolveDraft(options.draft);\n const cached = isCachedRead(draft, options.headers);\n if (cached) {\n cachedLoadConfig = options.config;\n }\n // a cached read runs no database I/O before the cached loader (see `lazyRequest`); it is always a guest\n let user: User = guest;\n let layout: ILayout;\n if (cached) {\n layout = await cachedLayout(market, locale, options.depth ?? DEFAULT_LAYOUT_DEPTH);\n } else {\n const req = await lazyRequest(options.config, options.headers, draft, market, locale)();\n user = req.user;\n layout = await loadLayout(market, locale, req.payload, req.user, req.context, {\n depth: options.depth,\n draft,\n });\n }\n if (!draft) {\n await tagPage(() => layoutCacheTags(market, locale));\n }\n\n const { page: _page, ...pageContext } = toPageContext<CollectionSlug, undefined, LayoutOptions>(\n layout,\n undefined,\n user\n );\n\n await setPageContext(pageContext);\n\n return pageContext as IPageContext;\n}\n"],"mappings":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Props(life = "bom-page") {
59
59
  return cached;
60
60
  }
61
61
  async function decorateLazyComponents(extraComponents) {
62
- const context = await getContext();
62
+ const shared = await getContext();
63
63
  const pageContext = await getPageContext();
64
64
  const page = pageContext.page;
65
65
  if (!page) return;
66
66
  const live = getLiveContext();
67
67
  const cachedRead = live ? void 0 : getCachedPageRead();
68
+ let blockContext;
69
+ const getBlockContext = () => blockContext ??= cachedRead && !shared.payload ? loadCachedPageContext(cachedRead).then(({ payload, context }) => ({
70
+ payload,
71
+ context
72
+ })) : Promise.resolve(shared);
68
73
  const components = [...page.components || [], ...extraComponents || []];
69
74
  const decoratedComponents = await Promise.all(components.map((component) => {
70
75
  const key = component.blockType || component.schema || "unkown_type";
71
76
  const entry = LAZY_PROPS[key];
72
77
  if (!entry) return component;
73
78
  if (cachedRead && entry.options.cache !== false) return getCachedLazyProps(entry.options.life)(cachedRead, key, component);
74
- const load = () => entry.fn({
75
- ...context,
79
+ const load = async () => entry.fn({
80
+ ...await getBlockContext(),
76
81
  ...pageContext,
77
82
  component
78
83
  });
@@ -1 +1 @@
1
- {"version":3,"file":"lazy.js","names":[],"sources":["../../src/server/lazy.ts"],"sourcesContent":["import 'server-only';\r\n\r\nimport type { IComponent } from '@websolutespa/bom-core';\r\nimport { routeCacheTags } from '@websolutespa/payload-plugin-bowl';\r\nimport type { ILazyComponent, ILazyStaticPropsFunc } from '../types';\r\nimport { bomCached } from './cache/cached';\r\nimport type { BomCacheLife } from './cache/profiles';\r\nimport {\r\n type CachedPageRead,\r\n getCachedPageRead,\r\n getIssuedPages,\r\n getLiveContext,\r\n getPageContext,\r\n loadCachedPageContext,\r\n} from './context';\r\nimport { getLiveBlock, setLiveBlock } from './live-preview-store';\r\nimport { getContext } from './mixer';\r\n\r\nexport type LazyPropsOptions = {\r\n /**\r\n * Cache Components only: lifetime of the decorator's cached result (default `bom-page`). Its own `tagPage` calls\r\n * still decide what invalidates it.\r\n */\r\n life?: BomCacheLife;\r\n /**\r\n * `false` runs the decorator directly in the render even under Cache Components. Use it only for a decorator\r\n * that reads no data: any Payload or network read outside a cache scope fails the prerender.\r\n */\r\n cache?: boolean;\r\n};\r\n\r\ntype LazyPropsEntry = { fn: ILazyStaticPropsFunc; options: LazyPropsOptions };\r\n\r\n/**\r\n * Decorators by block type. Module scope on purpose: a `'use cache'` function captures enclosing variables as cache\r\n * key arguments, and functions are not serializable.\r\n */\r\nconst LAZY_PROPS: Record<string, LazyPropsEntry> = {};\r\n\r\n/**\r\n * Registers the server decorator of a block type: it loads the data the block needs (for example a listing reads\r\n * its documents) and returns the decorated component.\r\n *\r\n * With Cache Components, on public renders, the decorator runs in its own cache scope (`bom:fn:lazy-props`), keyed\r\n * by the page read and the block: its Payload reads are cached, and the tags it attaches with `tagPage` invalidate\r\n * it and the page. Its result must be serializable (plain data). Drafts, authenticated pages, live preview and the\r\n * classic model call it directly, as before.\r\n */\r\nexport async function withLazyProps<T>(\r\n key: string,\r\n getComponentProps: ILazyStaticPropsFunc<T>,\r\n options: LazyPropsOptions = {}\r\n) {\r\n LAZY_PROPS[key] = { fn: getComponentProps as ILazyStaticPropsFunc, options };\r\n}\r\n\r\nasync function runCachedLazyProps(read: CachedPageRead, key: string, component: ILazyComponent) {\r\n const entry = LAZY_PROPS[key];\r\n if (!entry) {\r\n throw new Error(`[bom-next] lazy props \"${key}\" are not registered in this server bundle.`);\r\n }\r\n const { payload, context, pageContext } = await loadCachedPageContext(read);\r\n // a deep copy, so a decorator that mutates and returns its `component` (the usual pattern) returns a value of\r\n // its own, never an object of the cache key arguments\r\n return entry.fn({ payload, context, ...pageContext, component: structuredClone(component) });\r\n}\r\n\r\n/** One cached function per lifetime: `bomCached` fixes the lifetime at registration. */\r\nconst cachedLazyProps = new Map<string, ReturnType<typeof createCachedLazyProps>>();\r\n\r\nfunction createCachedLazyProps(life: BomCacheLife) {\r\n const name =\r\n typeof life === 'string' && life !== 'bom-page' ? `lazy-props:${life}` : 'lazy-props';\r\n return bomCached(name, runCachedLazyProps, {\r\n life,\r\n tags: (read) =>\r\n routeCacheTags({\r\n market: read.market,\r\n locale: read.locale,\r\n schema: read.slug,\r\n page: read.id,\r\n }),\r\n });\r\n}\r\n\r\nfunction getCachedLazyProps(life: BomCacheLife = 'bom-page') {\r\n const key = typeof life === 'string' ? life : JSON.stringify(life);\r\n let cached = cachedLazyProps.get(key);\r\n if (!cached) {\r\n cached = createCachedLazyProps(life);\r\n cachedLazyProps.set(key, cached);\r\n }\r\n return cached;\r\n}\r\n\r\nexport async function decorateLazyComponents(extraComponents?: IComponent[]) {\r\n const context = await getContext();\r\n const pageContext = await getPageContext();\r\n const page = pageContext.page;\r\n if (!page) {\r\n return;\r\n }\r\n const live = getLiveContext();\r\n const cachedRead = live ? undefined : getCachedPageRead();\r\n const components = [...(page.components || []), ...(extraComponents || [])];\r\n // Decorators are independent data loaders, so run them concurrently;\r\n // Promise.all preserves the original component order.\r\n const decoratedComponents: ILazyComponent[] = await Promise.all(\r\n components.map((component) => {\r\n const key = (component.blockType || component.schema || 'unkown_type') as string;\r\n const entry = LAZY_PROPS[key];\r\n if (!entry) {\r\n return component;\r\n }\r\n if (cachedRead && entry.options.cache !== false) {\r\n // Cache Components, public render: Payload reads in a render outside a cache scope fail the prerender\r\n return getCachedLazyProps(entry.options.life)(cachedRead, key, component as ILazyComponent);\r\n }\r\n const load = () => entry.fn({ ...context, ...pageContext, component });\r\n const blockId = (component as { id?: string | number }).id;\r\n if (!live || blockId === undefined || blockId === null) {\r\n return load();\r\n }\r\n // live preview: while the editor types, a block keeps what its loader returned on the last full render\r\n // and the unsaved values of the block override it; a block the loader has not seen yet is loaded once\r\n const blockKey = `${live.scope}:${blockId}`;\r\n const loaded = live.data ? getLiveBlock(live.session, blockKey) : undefined;\r\n if (loaded) {\r\n return { ...loaded, ...component } as ILazyComponent;\r\n }\r\n return load().then((result) => {\r\n setLiveBlock(live.session, blockKey, { ...result });\r\n return result;\r\n });\r\n })\r\n );\r\n page.components = decoratedComponents;\r\n // the template may hold another copy of this page (a later `createPageContext`, e.g. from `generateMetadata`,\r\n // replaced the stored one): decorate every copy handed out in this request\r\n for (const issued of getIssuedPages() as PageCopy[]) {\r\n if (issued !== page && isSamePage(issued, page as PageCopy)) {\r\n issued.components = decoratedComponents;\r\n }\r\n }\r\n}\r\n\r\ntype PageCopy = { id?: unknown; schema?: unknown; components?: unknown };\r\n\r\nfunction isSamePage(a: PageCopy, b: PageCopy): boolean {\r\n return (\r\n a.id !== undefined &&\r\n String(a.id) === String(b.id) &&\r\n (a.schema === undefined || b.schema === undefined || a.schema === b.schema)\r\n );\r\n}\r\n"],"mappings":";;;;;;;;;;;AAqCA,MAAM,aAA6C,EAAE;;;;;;;;;;AAWrD,eAAsB,cACpB,KACA,mBACA,UAA4B,EAAE,EAC9B;AACA,YAAW,OAAO;EAAE,IAAI;EAA2C;EAAS;;AAG9E,eAAe,mBAAmB,MAAsB,KAAa,WAA2B;CAC9F,MAAM,QAAQ,WAAW;AACzB,KAAI,CAAC,MACH,OAAM,IAAI,MAAM,0BAA0B,IAAI,6CAA6C;CAE7F,MAAM,EAAE,SAAS,SAAS,gBAAgB,MAAM,sBAAsB,KAAK;AAG3E,QAAO,MAAM,GAAG;EAAE;EAAS;EAAS,GAAG;EAAa,WAAW,gBAAgB,UAAU;EAAE,CAAC;;;AAI9F,MAAM,kCAAkB,IAAI,KAAuD;AAEnF,SAAS,sBAAsB,MAAoB;AAGjD,QAAO,UADL,OAAO,SAAS,YAAY,SAAS,aAAa,cAAc,SAAS,cACpD,oBAAoB;EACzC;EACA,OAAO,SACL,eAAe;GACb,QAAQ,KAAK;GACb,QAAQ,KAAK;GACb,QAAQ,KAAK;GACb,MAAM,KAAK;GACZ,CAAC;EACL,CAAC;;AAGJ,SAAS,mBAAmB,OAAqB,YAAY;CAC3D,MAAM,MAAM,OAAO,SAAS,WAAW,OAAO,KAAK,UAAU,KAAK;CAClE,IAAI,SAAS,gBAAgB,IAAI,IAAI;AACrC,KAAI,CAAC,QAAQ;AACX,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AE,OAAO,KAAA,KACT,OAAO,EAAE,GAAG,KAAK,OAAO,EAAE,GAAG,KAC5B,EAAE,WAAW,KAAA,KAAa,EAAE,WAAW,KAAA,KAAa,EAAE,WAAW,EAAE"}
1
+ {"version":3,"file":"lazy.js","names":[],"sources":["../../src/server/lazy.ts"],"sourcesContent":["import 'server-only';\n\nimport type { IComponent } from '@websolutespa/bom-core';\nimport { routeCacheTags } from '@websolutespa/payload-plugin-bowl';\nimport type { IContext, ILazyComponent, ILazyStaticPropsFunc } from '../types';\nimport { bomCached } from './cache/cached';\nimport type { BomCacheLife } from './cache/profiles';\nimport {\n type CachedPageRead,\n getCachedPageRead,\n getIssuedPages,\n getLiveContext,\n getPageContext,\n loadCachedPageContext,\n} from './context';\nimport { getLiveBlock, setLiveBlock } from './live-preview-store';\nimport { getContext } from './mixer';\n\nexport type LazyPropsOptions = {\n /**\n * Cache Components only: lifetime of the decorator's cached result (default `bom-page`). Its own `tagPage` calls\n * still decide what invalidates it.\n */\n life?: BomCacheLife;\n /**\n * `false` runs the decorator directly in the render even under Cache Components. Use it only for a decorator\n * that reads no data: any Payload or network read outside a cache scope fails the prerender.\n */\n cache?: boolean;\n};\n\ntype LazyPropsEntry = { fn: ILazyStaticPropsFunc; options: LazyPropsOptions };\n\n/**\n * Decorators by block type. Module scope on purpose: a `'use cache'` function captures enclosing variables as cache\n * key arguments, and functions are not serializable.\n */\nconst LAZY_PROPS: Record<string, LazyPropsEntry> = {};\n\n/**\n * Registers the server decorator of a block type: it loads the data the block needs (for example a listing reads\n * its documents) and returns the decorated component.\n *\n * With Cache Components, on public renders, the decorator runs in its own cache scope (`bom:fn:lazy-props`), keyed\n * by the page read and the block: its Payload reads are cached, and the tags it attaches with `tagPage` invalidate\n * it and the page. Its result must be serializable (plain data). Drafts, authenticated pages, live preview and the\n * classic model call it directly, as before.\n */\nexport async function withLazyProps<T>(\n key: string,\n getComponentProps: ILazyStaticPropsFunc<T>,\n options: LazyPropsOptions = {}\n) {\n LAZY_PROPS[key] = { fn: getComponentProps as ILazyStaticPropsFunc, options };\n}\n\nasync function runCachedLazyProps(read: CachedPageRead, key: string, component: ILazyComponent) {\n const entry = LAZY_PROPS[key];\n if (!entry) {\n throw new Error(`[bom-next] lazy props \"${key}\" are not registered in this server bundle.`);\n }\n const { payload, context, pageContext } = await loadCachedPageContext(read);\n // a deep copy, so a decorator that mutates and returns its `component` (the usual pattern) returns a value of\n // its own, never an object of the cache key arguments\n return entry.fn({ payload, context, ...pageContext, component: structuredClone(component) });\n}\n\n/** One cached function per lifetime: `bomCached` fixes the lifetime at registration. */\nconst cachedLazyProps = new Map<string, ReturnType<typeof createCachedLazyProps>>();\n\nfunction createCachedLazyProps(life: BomCacheLife) {\n const name =\n typeof life === 'string' && life !== 'bom-page' ? `lazy-props:${life}` : 'lazy-props';\n return bomCached(name, runCachedLazyProps, {\n life,\n tags: (read) =>\n routeCacheTags({\n market: read.market,\n locale: read.locale,\n schema: read.slug,\n page: read.id,\n }),\n });\n}\n\nfunction getCachedLazyProps(life: BomCacheLife = 'bom-page') {\n const key = typeof life === 'string' ? life : JSON.stringify(life);\n let cached = cachedLazyProps.get(key);\n if (!cached) {\n cached = createCachedLazyProps(life);\n cachedLazyProps.set(key, cached);\n }\n return cached;\n}\n\nexport async function decorateLazyComponents(extraComponents?: IComponent[]) {\n const shared = await getContext();\n const pageContext = await getPageContext();\n const page = pageContext.page;\n if (!page) {\n return;\n }\n const live = getLiveContext();\n const cachedRead = live ? undefined : getCachedPageRead();\n // a cached read loads no Payload instance or mixer context outside the cache scopes, so the shared ones can be\n // missing: a decorator called directly (`cache: false`) on a cached read loads them, once per render\n let blockContext: Promise<IContext> | undefined;\n const getBlockContext = () =>\n (blockContext ??=\n cachedRead && !shared.payload\n ? loadCachedPageContext(cachedRead).then(({ payload, context }) => ({ payload, context }))\n : Promise.resolve(shared));\n const components = [...(page.components || []), ...(extraComponents || [])];\n // Decorators are independent data loaders, so run them concurrently;\n // Promise.all preserves the original component order.\n const decoratedComponents: ILazyComponent[] = await Promise.all(\n components.map((component) => {\n const key = (component.blockType || component.schema || 'unkown_type') as string;\n const entry = LAZY_PROPS[key];\n if (!entry) {\n return component;\n }\n if (cachedRead && entry.options.cache !== false) {\n // Cache Components, public render: Payload reads in a render outside a cache scope fail the prerender\n return getCachedLazyProps(entry.options.life)(cachedRead, key, component as ILazyComponent);\n }\n const load = async () =>\n entry.fn({ ...(await getBlockContext()), ...pageContext, component });\n const blockId = (component as { id?: string | number }).id;\n if (!live || blockId === undefined || blockId === null) {\n return load();\n }\n // live preview: while the editor types, a block keeps what its loader returned on the last full render\n // and the unsaved values of the block override it; a block the loader has not seen yet is loaded once\n const blockKey = `${live.scope}:${blockId}`;\n const loaded = live.data ? getLiveBlock(live.session, blockKey) : undefined;\n if (loaded) {\n return { ...loaded, ...component } as ILazyComponent;\n }\n return load().then((result) => {\n setLiveBlock(live.session, blockKey, { ...result });\n return result;\n });\n })\n );\n page.components = decoratedComponents;\n // the template may hold another copy of this page (a later `createPageContext`, e.g. from `generateMetadata`,\n // replaced the stored one): decorate every copy handed out in this request\n for (const issued of getIssuedPages() as PageCopy[]) {\n if (issued !== page && isSamePage(issued, page as PageCopy)) {\n issued.components = decoratedComponents;\n }\n }\n}\n\ntype PageCopy = { id?: unknown; schema?: unknown; components?: unknown };\n\nfunction isSamePage(a: PageCopy, b: PageCopy): boolean {\n return (\n a.id !== undefined &&\n String(a.id) === String(b.id) &&\n (a.schema === undefined || b.schema === undefined || a.schema === b.schema)\n );\n}\n"],"mappings":";;;;;;;;;;;AAqCA,MAAM,aAA6C,EAAE;;;;;;;;;;AAWrD,eAAsB,cACpB,KACA,mBACA,UAA4B,EAAE,EAC9B;AACA,YAAW,OAAO;EAAE,IAAI;EAA2C;EAAS;;AAG9E,eAAe,mBAAmB,MAAsB,KAAa,WAA2B;CAC9F,MAAM,QAAQ,WAAW;AACzB,KAAI,CAAC,MACH,OAAM,IAAI,MAAM,0BAA0B,IAAI,6CAA6C;CAE7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CAAC,MACH,QAAO;AAET,MAAI,cAAc,MAAM,QAAQ,UAAU,MAExC,QAAO,mBAAmB,MAAM,QAAQ,KAAK,CAAC,YAAY,KAAK,UAA4B;EAE7F,MAAM,OAAO,YACX,MAAM,GAAG;GAAE,GAAI,MAAM,iBAAiB;GAAG,GAAG;GAAa;GAAW,CAAC;EACvE,MAAM,UAAW,UAAuC;AACxD,MAAI,CAAC,QAAQ,YAAY,KAAA,KAAa,YAAY,KAChD,QAAO,MAAM;EAIf,MAAM,WAAW,GAAG,KAAK,MAAM,GAAG;EAClC,MAAM,SAAS,KAAK,OAAO,aAAa,KAAK,SAAS,SAAS,GAAG,KAAA;AAClE,MAAI,OACF,QAAO;GAAE,GAAG;GAAQ,GAAG;GAAW;AAEpC,SAAO,MAAM,CAAC,MAAM,WAAW;AAC7B,gBAAa,KAAK,SAAS,UAAU,EAAE,GAAG,QAAQ,CAAC;AACnD,UAAO;IACP;GACF,CACH;AACD,MAAK,aAAa;AAGlB,MAAK,MAAM,UAAU,gBAAgB,CACnC,KAAI,WAAW,QAAQ,WAAW,QAAQ,KAAiB,CACzD,QAAO,aAAa;;AAO1B,SAAS,WAAW,GAAa,GAAsB;AACrD,QACE,EAAE,OAAO,KAAA,KACT,OAAO,EAAE,GAAG,KAAK,OAAO,EAAE,GAAG,KAC5B,EAAE,WAAW,KAAA,KAAa,EAAE,WAAW,KAAA,KAAa,EAAE,WAAW,EAAE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@websolutespa/bom-next",
3
- "version": "4.0.0-next.18",
3
+ "version": "4.0.0-next.19",
4
4
  "description": "Next module of the BOM Repository",
5
5
  "keywords": [
6
6
  "bom",
@@ -48,7 +48,7 @@
48
48
  "@websolutespa/bom-cli": "^4.0.0-next.12",
49
49
  "@websolutespa/bom-core": "^4.0.0-next.12",
50
50
  "@websolutespa/oxc": "^4.0.0-next.11",
51
- "@websolutespa/payload-plugin-bowl": "^4.0.0-next.16",
51
+ "@websolutespa/payload-plugin-bowl": "^4.0.0-next.17",
52
52
  "@websolutespa/payload-utils": "^4.0.0-next.11",
53
53
  "@websolutespa/test": "^4.0.0-next.11",
54
54
  "@websolutespa/tsconfig": "^4.0.0-next.10",
@@ -1,79 +1,113 @@
1
- // @vitest-environment node
2
- import { beforeEach, describe, expect, it, vi } from 'vitest';
3
-
4
- const state = vi.hoisted(() => ({
5
- mode: 'components' as 'classic' | 'components',
6
- cachedCalls: [] as { name: string; args: unknown[] }[],
7
- }));
8
-
9
- vi.mock('server-only', () => ({}));
10
- vi.mock('@websolutespa/bom-next/cache-mode', () => ({
11
- get cacheMode() {
12
- return state.mode;
13
- },
14
- // records which loads go through the cached functions, then runs them
15
- createCached:
16
- (name: string, fn: (...args: unknown[]) => Promise<unknown>) =>
17
- async (...args: unknown[]) => {
18
- state.cachedCalls.push({ name, args });
19
- return fn(...args);
20
- },
21
- attachTags: vi.fn(),
22
- }));
23
-
24
- const { getPage, getLayout, getPayload } = vi.hoisted(() => ({
25
- getPage: vi.fn(async (_slug: string, id: string) => ({ id, breadcrumb: [{ category: 'blog' }] })),
26
- getLayout: vi.fn(async () => ({ labels: [] })),
27
- getPayload: vi.fn(async () => ({ payload: {}, user: null, getContext: async () => ({}) })),
28
- }));
29
- vi.mock('./page', () => ({ getPage }));
30
- vi.mock('./layout', () => ({ getLayout }));
31
- vi.mock('./mixer', () => ({ getPayload, resolveDraft: async (draft?: boolean) => Boolean(draft) }));
32
-
33
- const { createLayoutContext, createPageContext } = await import('./context');
34
-
35
- const config = Promise.resolve({} as never);
36
-
37
- beforeEach(() => {
38
- state.mode = 'components';
39
- state.cachedCalls = [];
40
- vi.clearAllMocks();
41
- });
42
-
43
- describe('createPageContext with Cache Components', () => {
44
- it('reads public pages and layouts through the cached loaders', async () => {
45
- const { page, layout } = await createPageContext('ww', 'en', 'page' as never, 'p1', { config });
46
- expect(page).toMatchObject({ id: 'p1' });
47
- expect(layout).toBeDefined();
48
- expect(state.cachedCalls.map((call) => call.name).sort()).toEqual([
49
- 'layout-context',
50
- 'page-context',
51
- ]);
52
- expect(
53
- state.cachedCalls.find((call) => call.name === 'page-context')?.args.slice(0, 4)
54
- ).toEqual(['ww', 'en', 'page', 'p1']);
55
- // the cached loaders get their Payload instance as a guest, from the config
56
- expect(getPayload).toHaveBeenCalledWith({ config, draft: false });
57
- });
58
-
59
- it('reads directly for requests with headers (users, protected pages) and drafts', async () => {
60
- await createPageContext('ww', 'en', 'page' as never, 'p2', {
61
- config,
62
- headers: new Headers() as never,
63
- });
64
- await createPageContext('ww', 'en', 'page' as never, 'p3', { config, draft: true });
65
- expect(state.cachedCalls).toEqual([]);
66
- expect(getPage).toHaveBeenCalledTimes(2);
67
- });
68
-
69
- it('caches layout-only contexts too', async () => {
70
- await createLayoutContext('ww', 'en', { config });
71
- expect(state.cachedCalls.map((call) => call.name)).toEqual(['layout-context']);
72
- });
73
-
74
- it('never uses the cached loaders in classic mode', async () => {
75
- state.mode = 'classic';
76
- await createPageContext('ww', 'en', 'page' as never, 'p4', { config });
77
- expect(state.cachedCalls).toEqual([]);
78
- });
79
- });
1
+ // @vitest-environment node
2
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ const state = vi.hoisted(() => ({
5
+ mode: 'components' as 'classic' | 'components',
6
+ cachedCalls: [] as { name: string; args: unknown[] }[],
7
+ /** Order of the cached calls and the Payload loads, to check what runs first. */
8
+ events: [] as string[],
9
+ }));
10
+
11
+ vi.mock('server-only', () => ({}));
12
+ vi.mock('@websolutespa/bom-next/cache-mode', () => ({
13
+ get cacheMode() {
14
+ return state.mode;
15
+ },
16
+ // records which loads go through the cached functions, then runs them
17
+ createCached:
18
+ (name: string, fn: (...args: unknown[]) => Promise<unknown>) =>
19
+ async (...args: unknown[]) => {
20
+ state.cachedCalls.push({ name, args });
21
+ state.events.push(`cached:${name}`);
22
+ return fn(...args);
23
+ },
24
+ attachTags: vi.fn(),
25
+ }));
26
+
27
+ const { getPage, getLayout, getPayload } = vi.hoisted(() => ({
28
+ getPage: vi.fn(async (_slug: string, id: string) => ({ id, breadcrumb: [{ category: 'blog' }] })),
29
+ getLayout: vi.fn(async () => ({ labels: [] })),
30
+ getPayload: vi.fn(async () => {
31
+ state.events.push('getPayload');
32
+ return { payload: {}, user: null, getContext: async () => ({}) };
33
+ }),
34
+ }));
35
+ vi.mock('./page', () => ({ getPage }));
36
+ vi.mock('./layout', () => ({ getLayout }));
37
+ vi.mock('./mixer', () => ({ getPayload, resolveDraft: async (draft?: boolean) => Boolean(draft) }));
38
+
39
+ const { createLayoutContext, createPageContext } = await import('./context');
40
+
41
+ const config = Promise.resolve({} as never);
42
+
43
+ beforeEach(() => {
44
+ state.mode = 'components';
45
+ state.cachedCalls = [];
46
+ state.events = [];
47
+ vi.clearAllMocks();
48
+ });
49
+
50
+ describe('createPageContext with Cache Components', () => {
51
+ it('reads public pages and layouts through the cached loaders', async () => {
52
+ const { page, layout } = await createPageContext('ww', 'en', 'page' as never, 'p1', { config });
53
+ expect(page).toMatchObject({ id: 'p1' });
54
+ expect(layout).toBeDefined();
55
+ expect(state.cachedCalls.map((call) => call.name).sort()).toEqual([
56
+ 'layout-context',
57
+ 'page-context',
58
+ ]);
59
+ expect(
60
+ state.cachedCalls.find((call) => call.name === 'page-context')?.args.slice(0, 4)
61
+ ).toEqual(['ww', 'en', 'page', 'p1']);
62
+ // the cached loaders get their Payload instance as a guest, from the config
63
+ expect(getPayload).toHaveBeenCalledWith({ config, draft: false });
64
+ });
65
+
66
+ it('reads directly for requests with headers (users, protected pages) and drafts', async () => {
67
+ await createPageContext('ww', 'en', 'page' as never, 'p2', {
68
+ config,
69
+ headers: new Headers() as never,
70
+ });
71
+ await createPageContext('ww', 'en', 'page' as never, 'p3', { config, draft: true });
72
+ expect(state.cachedCalls).toEqual([]);
73
+ expect(getPage).toHaveBeenCalledTimes(2);
74
+ });
75
+
76
+ it('caches layout-only contexts too', async () => {
77
+ await createLayoutContext('ww', 'en', { config });
78
+ expect(state.cachedCalls.map((call) => call.name)).toEqual(['layout-context']);
79
+ });
80
+
81
+ it('never uses the cached loaders in classic mode', async () => {
82
+ state.mode = 'classic';
83
+ await createPageContext('ww', 'en', 'page' as never, 'p4', { config });
84
+ expect(state.cachedCalls).toEqual([]);
85
+ });
86
+
87
+ // a prerender warms only the cache fills that have started: a database read awaited before them leaves the
88
+ // warming phase empty ("Unexpected cache miss after cache warming phase")
89
+ it('starts the cached loaders before loading Payload or the mixer context', async () => {
90
+ // the request's own load passes its headers (`getRequestPayload`); the cached loaders load as a guest, inside
91
+ // their scope
92
+ const requestLoads = () =>
93
+ getPayload.mock.calls.filter((call) => 'headers' in (call as unknown[] as [object])[0]);
94
+
95
+ await createPageContext('ww', 'en', 'page' as never, 'p5', { config });
96
+ expect(state.events[0]).toBe('cached:page-context');
97
+ expect(state.events).toContain('cached:layout-context');
98
+ expect(requestLoads()).toEqual([]);
99
+
100
+ state.events = [];
101
+ await createLayoutContext('ww', 'en', { config });
102
+ expect(state.events[0]).toBe('cached:layout-context');
103
+ expect(requestLoads()).toEqual([]);
104
+ });
105
+
106
+ it('loads Payload and the mixer context once for a direct read', async () => {
107
+ const headers = new Headers() as never;
108
+ await createPageContext('ww', 'en', 'page' as never, 'p6', { config, headers });
109
+ expect(getPayload).toHaveBeenCalledTimes(1);
110
+ expect(getPayload).toHaveBeenCalledWith({ config, headers, draft: false });
111
+ expect(getLayout).toHaveBeenCalledTimes(1);
112
+ });
113
+ });