@websolutespa/bom-next 4.0.0-next.12 → 4.0.0-next.13

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,16 @@
1
1
  # @websolutespa/bom-next
2
2
 
3
+ ## 4.0.0-next.13
4
+
5
+ ### Minor Changes
6
+
7
+ - **Security: Draft Mode only for editors.** `previewHandler` turned Next.js Draft Mode on for any visitor (its secret check was commented out), and draft renders then showed unpublished pages to anyone.
8
+
9
+ - New `getPreviewHandler(config, { roles })` for `src/app/api/-preview/route.ts`: it turns Draft Mode on for a logged-in editor (admin, contributor, editor: the admin session cookie, or the `_token` Bowl adds to the admin's preview URL, for an admin on another origin) or for `secret` equal to `MIXER_SECRET`; everyone else gets 401 and no cookie. The redirect accepts path segments only.
10
+ - `previewHandler(request)` is deprecated: without the config it cannot authenticate a user, so it now requires `secret` (`MIXER_SECRET`). Switch the route to `export const GET = getPreviewHandler(config)`.
11
+ - Draft reads: Bowl now serves drafts to the editing roles only, so `getPayload` reads a draft render without an editor session as an editor identity (`previewer`), and only while Draft Mode is really on; a `draft: true` read outside Draft Mode reads the published site. `PREVIEW_ROLES` and `previewer` are exported.
12
+ - **Indexing policy.** `buildPageMetadata` (and `getPageMetadata`) take `indexable: boolean | (page) => boolean`; a page that is not indexable gets `robots: 'noindex, nofollow'` over its own `meta.robots`. The default is `isIndexableDeployment()`: indexable only with `PRODUCTION=true` and without `NOINDEX=true`, as the BOM 3 `Meta` component did, so staging and preview deployments are no longer indexable. **A production site must set `PRODUCTION=true`.**
13
+
3
14
  ## 4.0.0-next.12
4
15
 
5
16
  ### Patch Changes
package/README.md CHANGED
@@ -57,7 +57,7 @@ export const generateMetadata = getPageMetadata('post_detail', {
57
57
  <JsonLd data={buildPageStructuredData(page, layout, { brand: { name: 'Example' } })} />
58
58
  ```
59
59
 
60
- `buildPageMetadata(page, layout, options)` is the same builder for custom routes. URLs are resolved against `NEXT_PUBLIC_URL` unless `baseUrl` is passed. Robots come from `meta.robots`, or `meta.robot` (the `@payloadcms/plugin-seo` field).
60
+ `buildPageMetadata(page, layout, options)` is the same builder for custom routes. URLs are resolved against `NEXT_PUBLIC_URL` unless `baseUrl` is passed. Robots come from `meta.robots`, or `meta.robot` (the `@payloadcms/plugin-seo` field), on indexable pages only. `indexable` (`boolean` or `(page) => boolean`) decides; the default, `isIndexableDeployment()`, makes pages indexable only with `PRODUCTION=true` and without `NOINDEX=true`, so staging and preview deployments answer `noindex, nofollow`. Set `PRODUCTION=true` in production.
61
61
 
62
62
  The client `MetaDataProvider` only computes values for `useMetaData`; the `next/head` based `Meta`, `OpenGraph` and `StructuredData` components of the mixer packages render nothing in the App Router.
63
63
 
@@ -71,6 +71,10 @@ The client `MetaDataProvider` only computes values for `useMetaData`; the `next/
71
71
 
72
72
  The server context (`getContext`) reads routes from the Bowl route store and caches the rest per market, locale and user for `MEMORY_CACHE_DURATION` seconds (default 300). Any route store change, local or from another instance through Redis, clears it. Draft contexts are never cached.
73
73
 
74
+ ## Preview
75
+
76
+ `getPreviewHandler(config)` is the `/api/-preview` route (`export const GET = getPreviewHandler(config)`). It turns Next.js Draft Mode on and redirects to the page, only for an editor (`PREVIEW_ROLES`: admin, contributor, editor; the admin session cookie, or the `_token` Bowl adds to the admin's preview URL) or with `secret` equal to `MIXER_SECRET`; anyone else gets 401 and no cookie. Templates pass `draft: (await draftMode()).isEnabled` to `createPageContext`; draft renders without an editor session read as `previewer` (an editing role), and only while Draft Mode is on, because Bowl serves drafts to the editing roles only. The old `previewHandler(request)` is deprecated and accepts only the secret.
77
+
74
78
  ## Cache
75
79
 
76
80
  Pages are tagged from their route by `createPageContext` and `createLayoutContext`, and invalidated by the Bowl change hooks and the Bowl cache panel (`/admin/cache`). The site exposes its side of the panel with one route:
@@ -1 +1 @@
1
- {"version":3,"file":"user.d.ts","names":[],"sources":["../../src/client/user.tsx"],"mappings":";;;;;KAMK,SAAA,GAAY,QAAA,GAAW,KAAA;AAAA,KAEhB,eAAA;EACV,IAAA,GAAO,SAAA;EACP,OAAA,GAAU,IAAA,GAAO,SAAA;AAAA;AAAA,cAGN,WAAA,EAAW,KAAA,CAAA,OAAA,CAAA,eAAA;;iBAsBR,cAAA,CAAA;AA3BhB;;;;AAAA,iBAmCgB,YAAA,CAAA;EACd,WAAA;EACA;AAAA;EAEA,WAAA,GAAc,SAAA;EACd,QAAA,EAAU,SAAA;AAAA,IACX,KAAA,CAAA,GAAA,CAAA,OAAA"}
1
+ {"version":3,"file":"user.d.ts","names":[],"sources":["../../src/client/user.tsx"],"mappings":";;;;;KAMK,SAAA,GAAY,QAAA,GAAW,KAAA;AAAA,KAEhB,eAAA;EACV,IAAA,GAAO,SAAA;EACP,OAAA,GAAU,IAAA,GAAO,SAAA;AAAA;AAAA,cAGN,WAAA,EAAW,KAAA,CAAA,OAAA,CAAA,eAAA;;iBAuBR,cAAA,CAAA;AA5BhB;;;;AAAA,iBAoCgB,YAAA,CAAA;EACd,WAAA;EACA;AAAA;EAEA,WAAA,GAAc,SAAA;EACd,QAAA,EAAU,SAAA;AAAA,IACX,KAAA,CAAA,GAAA,CAAA,OAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"user.js","names":[],"sources":["../../src/client/user.tsx"],"sourcesContent":["'use client';\n\nimport { createContext, ReactNode, useCallback, useEffect, useState } from 'react';\nimport { localApiGet } from '../lib/http';\nimport { IEndUser, IUser } from '../types';\n\ntype UserValue = IEndUser | IUser | null;\n\nexport type UserContextType = {\n user?: UserValue;\n setUser: (user?: UserValue) => void;\n};\n\nexport const UserContext = createContext<UserContextType>({\n setUser: () => {\n console.log('not implemented');\n },\n});\n\n// One `/auth/me` request per browser session, shared by every UserProvider\n// mount; `setUser` and `invalidateUser` keep it current after login/logout.\nlet mePromise: Promise<UserValue> | undefined;\n\nfunction getMe(): Promise<UserValue> {\n if (!mePromise) {\n mePromise = localApiGet<UserValue>('/auth/me').catch((error) => {\n console.warn('UserProvider.getMe.error', error);\n mePromise = undefined;\n return null;\n });\n }\n return mePromise;\n}\n\n/** Forces the next UserProvider mount to read `/auth/me` again. */\nexport function invalidateUser() {\n mePromise = undefined;\n}\n\n/**\n * Provides the current user. Pass `initialUser` (a user or `null`) when the\n * server already knows it, to skip the `/auth/me` request entirely.\n */\nexport function UserProvider({\n initialUser,\n children,\n}: {\n initialUser?: UserValue;\n children: ReactNode;\n}) {\n const [user, setUserState] = useState<UserValue | undefined>(initialUser);\n useEffect(() => {\n if (initialUser !== undefined) {\n mePromise = Promise.resolve(initialUser);\n return;\n }\n let active = true;\n getMe().then((user) => {\n if (active) {\n setUserState(user);\n }\n });\n return () => {\n active = false;\n };\n }, [initialUser]);\n const setUser = useCallback((user?: UserValue) => {\n mePromise = user === undefined ? undefined : Promise.resolve(user);\n setUserState(user);\n }, []);\n return <UserContext.Provider value={{ user, setUser }}>{children}</UserContext.Provider>;\n}\n"],"mappings":";;;;AAaA,MAAa,cAAc,cAA+B,EACxD,eAAe;AACb,SAAQ,IAAI,kBAAkB;GAEjC,CAAC;AAIF,IAAI;AAEJ,SAAS,QAA4B;AACnC,KAAI,CAAC,UACH,aAAY,YAAuB,WAAW,CAAC,OAAO,UAAU;AAC9D,UAAQ,KAAK,4BAA4B,MAAM;AAC/C,cAAY,KAAA;AACZ,SAAO;GACP;AAEJ,QAAO;;;AAIT,SAAgB,iBAAiB;AAC/B,aAAY,KAAA;;;;;;AAOd,SAAgB,aAAa,EAC3B,aACA,YAIC;CACD,MAAM,CAAC,MAAM,gBAAgB,SAAgC,YAAY;AACzE,iBAAgB;AACd,MAAI,gBAAgB,KAAA,GAAW;AAC7B,eAAY,QAAQ,QAAQ,YAAY;AACxC;;EAEF,IAAI,SAAS;AACb,SAAO,CAAC,MAAM,SAAS;AACrB,OAAI,OACF,cAAa,KAAK;IAEpB;AACF,eAAa;AACX,YAAS;;IAEV,CAAC,YAAY,CAAC;CACjB,MAAM,UAAU,aAAa,SAAqB;AAChD,cAAY,SAAS,KAAA,IAAY,KAAA,IAAY,QAAQ,QAAQ,KAAK;AAClE,eAAa,KAAK;IACjB,EAAE,CAAC;AACN,QAAO,CAAC,YAAY,SAAS,OAAO;EAAE;EAAM;EAAS,GAAG,SAAS,EAAE,YAAY"}
1
+ {"version":3,"file":"user.js","names":[],"sources":["../../src/client/user.tsx"],"sourcesContent":["'use client';\n\nimport { createContext, ReactNode, useCallback, useEffect, useState } from 'react';\nimport { localApiGet } from '../lib/http';\nimport { IEndUser, IUser } from '../types';\n\ntype UserValue = IEndUser | IUser | null;\n\nexport type UserContextType = {\n user?: UserValue;\n setUser: (user?: UserValue) => void;\n};\n\nexport const UserContext = createContext<UserContextType>({\n setUser: () => {\n console.log('not implemented');\n },\n});\n\n// One `/auth/me` request per page load, shared by every UserProvider mount and client navigation;\n// `setUser` and `invalidateUser` keep it current after login/logout. Not persisted (sessionStorage): a stored user\n// would go stale after a logout or login in another tab. Pass `initialUser` where the server knows the user.\nlet mePromise: Promise<UserValue> | undefined;\n\nfunction getMe(): Promise<UserValue> {\n if (!mePromise) {\n mePromise = localApiGet<UserValue>('/auth/me').catch((error) => {\n console.warn('UserProvider.getMe.error', error);\n mePromise = undefined;\n return null;\n });\n }\n return mePromise;\n}\n\n/** Forces the next UserProvider mount to read `/auth/me` again. */\nexport function invalidateUser() {\n mePromise = undefined;\n}\n\n/**\n * Provides the current user. Pass `initialUser` (a user or `null`) when the\n * server already knows it, to skip the `/auth/me` request entirely.\n */\nexport function UserProvider({\n initialUser,\n children,\n}: {\n initialUser?: UserValue;\n children: ReactNode;\n}) {\n const [user, setUserState] = useState<UserValue | undefined>(initialUser);\n useEffect(() => {\n if (initialUser !== undefined) {\n mePromise = Promise.resolve(initialUser);\n return;\n }\n let active = true;\n getMe().then((user) => {\n if (active) {\n setUserState(user);\n }\n });\n return () => {\n active = false;\n };\n }, [initialUser]);\n const setUser = useCallback((user?: UserValue) => {\n mePromise = user === undefined ? undefined : Promise.resolve(user);\n setUserState(user);\n }, []);\n return <UserContext.Provider value={{ user, setUser }}>{children}</UserContext.Provider>;\n}\n"],"mappings":";;;;AAaA,MAAa,cAAc,cAA+B,EACxD,eAAe;AACb,SAAQ,IAAI,kBAAkB;GAEjC,CAAC;AAKF,IAAI;AAEJ,SAAS,QAA4B;AACnC,KAAI,CAAC,UACH,aAAY,YAAuB,WAAW,CAAC,OAAO,UAAU;AAC9D,UAAQ,KAAK,4BAA4B,MAAM;AAC/C,cAAY,KAAA;AACZ,SAAO;GACP;AAEJ,QAAO;;;AAIT,SAAgB,iBAAiB;AAC/B,aAAY,KAAA;;;;;;AAOd,SAAgB,aAAa,EAC3B,aACA,YAIC;CACD,MAAM,CAAC,MAAM,gBAAgB,SAAgC,YAAY;AACzE,iBAAgB;AACd,MAAI,gBAAgB,KAAA,GAAW;AAC7B,eAAY,QAAQ,QAAQ,YAAY;AACxC;;EAEF,IAAI,SAAS;AACb,SAAO,CAAC,MAAM,SAAS;AACrB,OAAI,OACF,cAAa,KAAK;IAEpB;AACF,eAAa;AACX,YAAS;;IAEV,CAAC,YAAY,CAAC;CACjB,MAAM,UAAU,aAAa,SAAqB;AAChD,cAAY,SAAS,KAAA,IAAY,KAAA,IAAY,QAAQ,QAAQ,KAAK;AAClE,eAAa,KAAK;IACjB,EAAE,CAAC;AACN,QAAO,CAAC,YAAY,SAAS,OAAO;EAAE;EAAM;EAAS,GAAG,SAAS,EAAE,YAAY"}
@@ -1,3 +1,4 @@
1
+ import { PREVIEW_ROLES } from "../lib/const.js";
1
2
  import { BomCacheLife, BomCacheProfile, BomProfileName, bomProfiles, resolveProfile } from "../server/cache/profiles.js";
2
3
  import { BomCachedOptions, documentTags, normalizeTags } from "../server/cache/cached-types.js";
3
4
  import { bomCached } from "../server/cache/cached.js";
@@ -13,7 +14,7 @@ import { getAuthMeHandler } from "../server/handlers/auth.handler.js";
13
14
  import { getCaptionsVTT } from "../server/handlers/captions.handler.js";
14
15
  import { collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler } from "../server/handlers/collection.handler.js";
15
16
  import { indexGetHandler } from "../server/handlers/index.handler.js";
16
- import { previewHandler } from "../server/handlers/preview.handler.js";
17
+ import { getPreviewHandler, previewHandler } from "../server/handlers/preview.handler.js";
17
18
  import { getRegistry, getRegistryItem } from "../server/handlers/registry.handler.js";
18
19
  import { CdnPurgeHandler, cloudflarePurgeHandler, getRevalidateHandler, resolveCdnPurgeHandler } from "../server/handlers/revalidate.handler.js";
19
20
  import { getCompiledRedirects, getRouteHandler } from "../server/handlers/route.handler.js";
@@ -21,7 +22,7 @@ import { ISiteMap, getSiteMapIndex, getSiteMapXML, getSiteMapXSL } from "../serv
21
22
  import { getStaticParams, getStaticParamsFromPayload, getStaticParams_ } from "../server/handlers/static-params.handler.js";
22
23
  import { getVarsHandler } from "../server/handlers/vars.handler.js";
23
24
  import { createContextHelpers } from "../server/helpers.js";
24
- import { PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataSearchParams, buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, resolveMetadataUrl, toPlainText } from "../lib/page-metadata.js";
25
+ import { PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataSearchParams, buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, isIndexableDeployment, resolveMetadataUrl, toPlainText } from "../lib/page-metadata.js";
25
26
  import { JsonLd, PageStructuredDataOptions, buildPageStructuredData } from "../server/json-ld.js";
26
27
  import { decorateLazyComponents, withLazyProps } from "../server/lazy.js";
27
28
  import { getLocalApi } from "../server/local-api.js";
@@ -30,4 +31,4 @@ import { buildBaseOptions, buildReadOptions, clearMixerContextCache, filterRoute
30
31
  import { PAGE_ENVELOPE_FIELDS, getPage, withEnvelopeSelect } from "../server/page.js";
31
32
  import { getHrefBeforeRedirect, getNextUrl } from "../server/utils.js";
32
33
  import { getUtmz } from "../server/utmz.js";
33
- export { BomCacheLife, BomCacheProfile, BomCachedOptions, BomProfileName, CacheAction, CacheActionResult, CacheBackend, CacheInspector, CacheMode, CacheTagAction, CachedFunction, CachedPage, CdnPurgeHandler, GetPageMetadataOptions, ISiteMap, JsonLd, PAGE_ENVELOPE_FIELDS, PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataProps, PageMetadataSearchParams, PageStructuredDataOptions, ProcessCache, ProcessCacheStatus, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getLocalApi, getMetadata, getMixerContext, getNextUrl, getOptions, getPage, getPageAlternates, getPageContext, getPageMetadata, getPageXDefault, getPaginationQuery, getPayload, getPayloadInstance, getRegistry, getRegistryItem, getRevalidateHandler, getRouteHandler, getRoutes, getSearchParams, getSiteMapIndex, getSiteMapXML, getSiteMapXSL, getStaticParams, getStaticParamsFromPayload, getStaticParams_, getUtmz, getVarsHandler, indexGetHandler, inheritParentMetadata, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
34
+ export { BomCacheLife, BomCacheProfile, BomCachedOptions, BomProfileName, CacheAction, CacheActionResult, CacheBackend, CacheInspector, CacheMode, CacheTagAction, CachedFunction, CachedPage, CdnPurgeHandler, GetPageMetadataOptions, ISiteMap, JsonLd, PAGE_ENVELOPE_FIELDS, PREVIEW_ROLES, PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataProps, PageMetadataSearchParams, PageStructuredDataOptions, ProcessCache, ProcessCacheStatus, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getLocalApi, getMetadata, getMixerContext, getNextUrl, getOptions, getPage, getPageAlternates, getPageContext, getPageMetadata, getPageXDefault, getPaginationQuery, getPayload, getPayloadInstance, getPreviewHandler, getRegistry, getRegistryItem, getRevalidateHandler, getRouteHandler, getRoutes, getSearchParams, getSiteMapIndex, getSiteMapXML, getSiteMapXSL, getStaticParams, getStaticParamsFromPayload, getStaticParams_, getUtmz, getVarsHandler, indexGetHandler, inheritParentMetadata, isIndexableDeployment, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
@@ -1,4 +1,5 @@
1
- import { buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, resolveMetadataUrl, toPlainText } from "../lib/page-metadata.js";
1
+ import { PREVIEW_ROLES } from "../lib/const.js";
2
+ import { buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, isIndexableDeployment, resolveMetadataUrl, toPlainText } from "../lib/page-metadata.js";
2
3
  import { bomProfiles, resolveProfile } from "../server/cache/profiles.js";
3
4
  import { getHrefBeforeRedirect, getNextUrl } from "../server/utils.js";
4
5
  import { bomCached } from "../server/cache/cached.js";
@@ -17,7 +18,7 @@ import { getCaptionsVTT } from "../server/handlers/captions.handler.js";
17
18
  import { getLocalApi } from "../server/local-api.js";
18
19
  import { collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler } from "../server/handlers/collection.handler.js";
19
20
  import { indexGetHandler } from "../server/handlers/index.handler.js";
20
- import { previewHandler } from "../server/handlers/preview.handler.js";
21
+ import { getPreviewHandler, previewHandler } from "../server/handlers/preview.handler.js";
21
22
  import { getRegistry, getRegistryItem } from "../server/handlers/registry.handler.js";
22
23
  import { cloudflarePurgeHandler, getRevalidateHandler, resolveCdnPurgeHandler } from "../server/handlers/revalidate.handler.js";
23
24
  import { getCompiledRedirects, getRouteHandler } from "../server/handlers/route.handler.js";
@@ -29,4 +30,4 @@ import { createContextHelpers } from "../server/helpers.js";
29
30
  import { JsonLd, buildPageStructuredData } from "../server/json-ld.js";
30
31
  import { decorateLazyComponents, withLazyProps } from "../server/lazy.js";
31
32
  import { getUtmz } from "../server/utmz.js";
32
- export { JsonLd, PAGE_ENVELOPE_FIELDS, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getLocalApi, getMetadata, getMixerContext, getNextUrl, getOptions, getPage, getPageAlternates, getPageContext, getPageMetadata, getPageXDefault, getPaginationQuery, getPayload, getPayloadInstance, getRegistry, getRegistryItem, getRevalidateHandler, getRouteHandler, getRoutes, getSearchParams, getSiteMapIndex, getSiteMapXML, getSiteMapXSL, getStaticParams, getStaticParamsFromPayload, getStaticParams_, getUtmz, getVarsHandler, indexGetHandler, inheritParentMetadata, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
33
+ export { JsonLd, PAGE_ENVELOPE_FIELDS, PREVIEW_ROLES, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getLocalApi, getMetadata, getMixerContext, getNextUrl, getOptions, getPage, getPageAlternates, getPageContext, getPageMetadata, getPageXDefault, getPaginationQuery, getPayload, getPayloadInstance, getPreviewHandler, getRegistry, getRegistryItem, getRevalidateHandler, getRouteHandler, getRoutes, getSearchParams, getSiteMapIndex, getSiteMapXML, getSiteMapXSL, getStaticParams, getStaticParamsFromPayload, getStaticParams_, getUtmz, getVarsHandler, indexGetHandler, inheritParentMetadata, isIndexableDeployment, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@ import { StructuredDataType } from "./lib/structured-data.js";
4
4
  import { TwitterCardApp, TwitterCardBase, TwitterCardPlayer, TwitterCardSummary, TwitterCardSummaryLargeImage, TwitterCardType } from "./lib/twitter-card.js";
5
5
  import { IAlternate, IBrand, IMeta, IMetaData } from "./lib/meta-data.js";
6
6
  import { buildBreadcrumb } from "./lib/breadcrumb.js";
7
- import { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, guest } from "./lib/const.js";
7
+ import { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, PREVIEW_ROLES, guest, previewer } from "./lib/const.js";
8
8
  import { LabelService, getLabelFromLabels, interpolateText } from "./lib/label.js";
9
9
  import { LayoutDefaults } from "./lib/layout.defaults.js";
10
10
  import { getLink } from "./lib/link.js";
@@ -15,4 +15,4 @@ import { getPublicUrl, resolveHref, sanitizeHref, sanitizeRedirectFrom, sanitize
15
15
  import { IMockCollection, IMockDocument, IMockGlobal, IMockLocale, IMockLocalized, IMockMedia, IMockMenu, IMockMenuItem, IMockPage, IMockStore } from "./mock.js";
16
16
  import { ErrorContext, RequestInfo } from "./instrumentation/types.js";
17
17
  import { BaseOptions, ComponentContext, ComponentProps, DraftOption, IContext, IEndUser, ILazyComponent, ILazyComponentFunc, ILazyComponentProps, ILazyFuncProps, ILazyModules, ILazyProps, ILazyStaticProps, ILazyStaticPropsFunc, ILazyableProps, ILazyedProps, INullableLazyableProps, IPageContext, IUser, LayoutContext, LayoutContextOptions, LayoutFor, LayoutOption, LayoutOptions, LocalProvider, MarketLocaleParams, MixerContext, NotFoundContext, NotFoundParams, PageContext, PageContextOptions, PageDocument, PageEnvelope, PageEnvelopeField, PageLayoutContext, PageParams, PageSelect, PartialPageProps, Populated, ReadOptions, ReadonlyHeaders, SearchParams, TypedPage, TypedPageContext, WithEnvelopeSelect } from "./types.js";
18
- export { ApiRequestOptions, BaseOptions, BuildStrategy, ComponentContext, ComponentProps, DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, DraftOption, ErrorContext, IAlternate, IBrand, IContext, IEndUser, ILazyComponent, ILazyComponentFunc, ILazyComponentProps, ILazyFuncProps, ILazyModules, ILazyProps, ILazyStaticProps, ILazyStaticPropsFunc, ILazyableProps, ILazyedProps, IMeta, IMetaData, IMockCollection, IMockDocument, IMockGlobal, IMockLocale, IMockLocalized, IMockMedia, IMockMenu, IMockMenuItem, IMockPage, IMockStore, INullableLazyableProps, IPageContext, IPaginationInfo, IPaginationItem, IPaginationOptions, IUser, LabelService, LayoutContext, LayoutContextOptions, LayoutDefaults, LayoutFor, LayoutOption, LayoutOptions, LocalProvider, MarketLocaleParams, MixerContext, NextPhase, NotFoundContext, NotFoundParams, OpenGraphArticle, OpenGraphAudio, OpenGraphBase, OpenGraphBook, OpenGraphBusiness, OpenGraphImage, OpenGraphMusic, OpenGraphPlace, OpenGraphProduct, OpenGraphProductGroup, OpenGraphProfile, OpenGraphRestaurant, OpenGraphType, OpenGraphVideo, OpenGraphWebsite, PageContext, PageContextOptions, PageDocument, PageEnvelope, PageEnvelopeField, PageLayoutContext, PageParams, PageSelect, PartialPageProps, Populated, ReadOptions, ReadonlyHeaders, RequestInfo, SearchParams, StoreStrategy, StructuredDataType, TwitterCardApp, TwitterCardBase, TwitterCardPlayer, TwitterCardSummary, TwitterCardSummaryLargeImage, TwitterCardType, TypedPage, TypedPageContext, WithEnvelopeSelect, buildBreadcrumb, buildStrategy, getLabelFromLabels, getLink, getLocalApiRequestOptions, getLocalApiUrl, getMoreItems, getPagedItems, getPaginationInfo, getPublicUrl, getRemoteApiRequestOptions, getRouteLinkCategory, getRouteTemplate, guest, interpolateText, isPaginationInfo, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut, newRouteLink, nextPhase, resolveHref, resolveRoute, routeToLink, routeToRouteLink, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, storeCacheDuration, storeStrategy, trimTerminalSlash };
18
+ export { ApiRequestOptions, BaseOptions, BuildStrategy, ComponentContext, ComponentProps, DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, DraftOption, ErrorContext, IAlternate, IBrand, IContext, IEndUser, ILazyComponent, ILazyComponentFunc, ILazyComponentProps, ILazyFuncProps, ILazyModules, ILazyProps, ILazyStaticProps, ILazyStaticPropsFunc, ILazyableProps, ILazyedProps, IMeta, IMetaData, IMockCollection, IMockDocument, IMockGlobal, IMockLocale, IMockLocalized, IMockMedia, IMockMenu, IMockMenuItem, IMockPage, IMockStore, INullableLazyableProps, IPageContext, IPaginationInfo, IPaginationItem, IPaginationOptions, IUser, LabelService, LayoutContext, LayoutContextOptions, LayoutDefaults, LayoutFor, LayoutOption, LayoutOptions, LocalProvider, MarketLocaleParams, MixerContext, NextPhase, NotFoundContext, NotFoundParams, OpenGraphArticle, OpenGraphAudio, OpenGraphBase, OpenGraphBook, OpenGraphBusiness, OpenGraphImage, OpenGraphMusic, OpenGraphPlace, OpenGraphProduct, OpenGraphProductGroup, OpenGraphProfile, OpenGraphRestaurant, OpenGraphType, OpenGraphVideo, OpenGraphWebsite, PREVIEW_ROLES, PageContext, PageContextOptions, PageDocument, PageEnvelope, PageEnvelopeField, PageLayoutContext, PageParams, PageSelect, PartialPageProps, Populated, ReadOptions, ReadonlyHeaders, RequestInfo, SearchParams, StoreStrategy, StructuredDataType, TwitterCardApp, TwitterCardBase, TwitterCardPlayer, TwitterCardSummary, TwitterCardSummaryLargeImage, TwitterCardType, TypedPage, TypedPageContext, WithEnvelopeSelect, buildBreadcrumb, buildStrategy, getLabelFromLabels, getLink, getLocalApiRequestOptions, getLocalApiUrl, getMoreItems, getPagedItems, getPaginationInfo, getPublicUrl, getRemoteApiRequestOptions, getRouteLinkCategory, getRouteTemplate, guest, interpolateText, isPaginationInfo, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut, newRouteLink, nextPhase, previewer, resolveHref, resolveRoute, routeToLink, routeToRouteLink, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, storeCacheDuration, storeStrategy, trimTerminalSlash };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { getRouteLinkCategory, getRouteTemplate, newRouteLink, resolveRoute, routeToLink, routeToRouteLink } from "./lib/route.js";
2
2
  import { buildBreadcrumb } from "./lib/breadcrumb.js";
3
- import { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, guest } from "./lib/const.js";
3
+ import { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, PREVIEW_ROLES, guest, previewer } from "./lib/const.js";
4
4
  import { getLocalApiRequestOptions, getLocalApiUrl, getRemoteApiRequestOptions, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut } from "./lib/http.js";
5
5
  import { LabelService, getLabelFromLabels, interpolateText } from "./lib/label.js";
6
6
  import { LayoutDefaults } from "./lib/layout.defaults.js";
@@ -8,4 +8,4 @@ import { getLink } from "./lib/link.js";
8
8
  import { getMoreItems, getPagedItems, getPaginationInfo, isPaginationInfo } from "./lib/pagination.js";
9
9
  import { BuildStrategy, NextPhase, StoreStrategy, buildStrategy, nextPhase, storeCacheDuration, storeStrategy } from "./lib/store.js";
10
10
  import { getPublicUrl, resolveHref, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, trimTerminalSlash } from "./lib/utils.js";
11
- export { BuildStrategy, DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, LabelService, LayoutDefaults, NextPhase, StoreStrategy, buildBreadcrumb, buildStrategy, getLabelFromLabels, getLink, getLocalApiRequestOptions, getLocalApiUrl, getMoreItems, getPagedItems, getPaginationInfo, getPublicUrl, getRemoteApiRequestOptions, getRouteLinkCategory, getRouteTemplate, guest, interpolateText, isPaginationInfo, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut, newRouteLink, nextPhase, resolveHref, resolveRoute, routeToLink, routeToRouteLink, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, storeCacheDuration, storeStrategy, trimTerminalSlash };
11
+ export { BuildStrategy, DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, LabelService, LayoutDefaults, NextPhase, PREVIEW_ROLES, StoreStrategy, buildBreadcrumb, buildStrategy, getLabelFromLabels, getLink, getLocalApiRequestOptions, getLocalApiUrl, getMoreItems, getPagedItems, getPaginationInfo, getPublicUrl, getRemoteApiRequestOptions, getRouteLinkCategory, getRouteTemplate, guest, interpolateText, isPaginationInfo, localApiDelete, localApiFetch, localApiGet, localApiPatch, localApiPost, localApiPut, newRouteLink, nextPhase, previewer, resolveHref, resolveRoute, routeToLink, routeToRouteLink, sanitizeHref, sanitizeRedirectFrom, sanitizeRedirectTo, sanitizeRedirectUrl, storeCacheDuration, storeStrategy, trimTerminalSlash };
@@ -2,6 +2,14 @@ import { Config, User } from "@websolutespa/payload-plugin-bowl";
2
2
 
3
3
  //#region src/lib/const.d.ts
4
4
  declare const guest: User & Config["user"];
5
+ /** Roles that read drafts and may turn Draft Mode on: Bowl's editing roles (`rolesUser`). */
6
+ declare const PREVIEW_ROLES: string[];
7
+ /**
8
+ * The reader of Draft Mode renders without an editor session (static templates pass no headers; the admin may run
9
+ * on another origin). Draft Mode is turned on only for editors (`getPreviewHandler`) and Bowl serves drafts to the
10
+ * editing roles only, so these reads use an editing role. `getPayload` uses it only while Next.js Draft Mode is on.
11
+ */
12
+ declare const previewer: User & Config["user"];
5
13
  /**
6
14
  * Default population depth for page documents read by `createPageContext`.
7
15
  *
@@ -16,5 +24,5 @@ declare const DEFAULT_PAGE_DEPTH = 2;
16
24
  */
17
25
  declare const DEFAULT_LAYOUT_DEPTH = 1;
18
26
  //#endregion
19
- export { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, guest };
27
+ export { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, PREVIEW_ROLES, guest, previewer };
20
28
  //# sourceMappingURL=const.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"const.d.ts","names":[],"sources":["../../src/lib/const.ts"],"mappings":";;;cAEa,KAAA,EAAqD,IAAA,GAAO,MAAA;;AAAzE;;;;;AASA;cAAa,kBAAA;;;;AAMb;cAAa,oBAAA"}
1
+ {"version":3,"file":"const.d.ts","names":[],"sources":["../../src/lib/const.ts"],"mappings":";;;cAEa,KAAA,EAAqD,IAAA,GAAO,MAAA;;cAG5D,aAAA;;;;;AAAb;cAOa,SAAA,EAA0D,IAAA,GAAO,MAAA;;;;AAA9E;;;;cASa,kBAAA;AAAb;;;;AAAA,cAMa,oBAAA"}
package/dist/lib/const.js CHANGED
@@ -3,6 +3,21 @@ const guest = {
3
3
  collection: "users",
4
4
  roles: ["guest"]
5
5
  };
6
+ /** Roles that read drafts and may turn Draft Mode on: Bowl's editing roles (`rolesUser`). */
7
+ const PREVIEW_ROLES = [
8
+ "admin",
9
+ "contributor",
10
+ "editor"
11
+ ];
12
+ /**
13
+ * The reader of Draft Mode renders without an editor session (static templates pass no headers; the admin may run
14
+ * on another origin). Draft Mode is turned on only for editors (`getPreviewHandler`) and Bowl serves drafts to the
15
+ * editing roles only, so these reads use an editing role. `getPayload` uses it only while Next.js Draft Mode is on.
16
+ */
17
+ const previewer = {
18
+ collection: "users",
19
+ roles: ["editor"]
20
+ };
6
21
  /**
7
22
  * Default population depth for page documents read by `createPageContext`.
8
23
  *
@@ -17,6 +32,6 @@ const DEFAULT_PAGE_DEPTH = 2;
17
32
  */
18
33
  const DEFAULT_LAYOUT_DEPTH = 1;
19
34
  //#endregion
20
- export { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, guest };
35
+ export { DEFAULT_LAYOUT_DEPTH, DEFAULT_PAGE_DEPTH, PREVIEW_ROLES, guest, previewer };
21
36
 
22
37
  //# sourceMappingURL=const.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"const.js","names":[],"sources":["../../src/lib/const.ts"],"sourcesContent":["import type { Config, User } from '@websolutespa/payload-plugin-bowl';\n\nexport const guest = { collection: 'users', roles: ['guest'] } as User & Config['user'];\n\n/**\n * Default population depth for page documents read by `createPageContext`.\n *\n * - `0`: relationships and uploads are returned as ids.\n * - `1`: direct relationships and uploads are populated, including those inside blocks.\n * - `2`: relationships of relationships are populated too (e.g. the cover of a related card).\n */\nexport const DEFAULT_PAGE_DEPTH = 2;\n\n/**\n * Default population depth for the layout reads (app global, menus, labels, markets).\n * `1` populates the app logo and menu media.\n */\nexport const DEFAULT_LAYOUT_DEPTH = 1;\n"],"mappings":";AAEA,MAAa,QAAQ;CAAE,YAAY;CAAS,OAAO,CAAC,QAAQ;CAAE;;;;;;;;AAS9D,MAAa,qBAAqB;;;;;AAMlC,MAAa,uBAAuB"}
1
+ {"version":3,"file":"const.js","names":[],"sources":["../../src/lib/const.ts"],"sourcesContent":["import type { Config, User } from '@websolutespa/payload-plugin-bowl';\n\nexport const guest = { collection: 'users', roles: ['guest'] } as User & Config['user'];\n\n/** Roles that read drafts and may turn Draft Mode on: Bowl's editing roles (`rolesUser`). */\nexport const PREVIEW_ROLES = ['admin', 'contributor', 'editor'];\n\n/**\n * The reader of Draft Mode renders without an editor session (static templates pass no headers; the admin may run\n * on another origin). Draft Mode is turned on only for editors (`getPreviewHandler`) and Bowl serves drafts to the\n * editing roles only, so these reads use an editing role. `getPayload` uses it only while Next.js Draft Mode is on.\n */\nexport const previewer = { collection: 'users', roles: ['editor'] } as User & Config['user'];\n\n/**\n * Default population depth for page documents read by `createPageContext`.\n *\n * - `0`: relationships and uploads are returned as ids.\n * - `1`: direct relationships and uploads are populated, including those inside blocks.\n * - `2`: relationships of relationships are populated too (e.g. the cover of a related card).\n */\nexport const DEFAULT_PAGE_DEPTH = 2;\n\n/**\n * Default population depth for the layout reads (app global, menus, labels, markets).\n * `1` populates the app logo and menu media.\n */\nexport const DEFAULT_LAYOUT_DEPTH = 1;\n"],"mappings":";AAEA,MAAa,QAAQ;CAAE,YAAY;CAAS,OAAO,CAAC,QAAQ;CAAE;;AAG9D,MAAa,gBAAgB;CAAC;CAAS;CAAe;CAAS;;;;;;AAO/D,MAAa,YAAY;CAAE,YAAY;CAAS,OAAO,CAAC,SAAS;CAAE;;;;;;;;AASnE,MAAa,qBAAqB;;;;;AAMlC,MAAa,uBAAuB"}
@@ -16,9 +16,20 @@ type PageMetadataContext = {
16
16
  type PageMetadataOptions = {
17
17
  brand?: PageMetadataBrand; /** Absolute origin for canonical, alternates and images. Default `NEXT_PUBLIC_URL`. */
18
18
  baseUrl?: string; /** Request search params; `pagination[page]` > 1 is kept in the canonical URL. */
19
- searchParams?: PageMetadataSearchParams; /** Per-page override applied to the computed metadata. */
19
+ searchParams?: PageMetadataSearchParams;
20
+ /**
21
+ * Whether search engines may index the page. When false (or a function returning false), `robots` is
22
+ * `noindex, nofollow`, over the page's own `meta.robots`. Default: {@link isIndexableDeployment}, so staging
23
+ * and preview deployments are never indexed.
24
+ */
25
+ indexable?: boolean | ((page: IPage) => boolean); /** Per-page override applied to the computed metadata. */
20
26
  extend?: (metadata: Metadata, context: PageMetadataContext) => Metadata;
21
27
  };
28
+ /**
29
+ * The deployment policy: pages are indexable only in production (`PRODUCTION=true`, as the BOM 3 `Meta` component
30
+ * required) and unless `NOINDEX=true`. Every other deployment (staging, previews, local) is `noindex`.
31
+ */
32
+ declare function isIndexableDeployment(env?: NodeJS.ProcessEnv): boolean;
22
33
  /** Converts CMS HTML (titles, abstracts) to a single line of plain text. */
23
34
  declare function toPlainText(html?: string | null): string;
24
35
  /** Resolves a relative href against `baseUrl`; absolute URLs are returned as is. */
@@ -45,5 +56,5 @@ declare function buildPageMetadata(page: IPage, layout?: ILayout, options?: Page
45
56
  */
46
57
  declare function inheritParentMetadata(metadata: Metadata, parent?: ResolvedMetadata): Metadata;
47
58
  //#endregion
48
- export { PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataSearchParams, buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, resolveMetadataUrl, toPlainText };
59
+ export { PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataSearchParams, buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, isIndexableDeployment, resolveMetadataUrl, toPlainText };
49
60
  //# sourceMappingURL=page-metadata.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"page-metadata.d.ts","names":[],"sources":["../../src/lib/page-metadata.ts"],"mappings":";;;;;KAcY,iBAAA;mDAEV,IAAA,UAF2B;EAI3B,IAAA,WAJ2B;EAM3B,WAAA;AAAA;AAAA,KAGU,wBAAA,GACR,eAAA,GACA,MAAA;AAAA,KAEQ,mBAAA;EACV,IAAA,EAAM,KAAA;EACN,MAAA,GAAS,OAAA;AAAA;AAAA,KAGC,mBAAA;EACV,KAAA,GAAQ,iBAAA,EARA;EAUR,OAAA,WAR6B;EAU7B,YAAA,GAAe,wBAAA,EARC;EAUhB,MAAA,IAAU,QAAA,EAAU,QAAA,EAAU,OAAA,EAAS,mBAAA,KAAwB,QAAA;AAAA;;iBAajD,WAAA,CAAY,IAAA;;iBAuBZ,kBAAA,CAAmB,IAAA,sBAA0B,OAAA;AA3C7D;AAAA,iBAiEgB,kBAAA,CAAmB,YAAA,GAAe,wBAAA;;;;;iBAUlC,iBAAA,CACd,IAAA,EAAM,IAAA,CAAK,KAAA,iBACX,MAAA,EAAQ,IAAA,CAAK,OAAA,cACb,OAAA,WACC,UAAA;;iBAkCa,eAAA,CACd,IAAA,EAAM,IAAA,CAAK,KAAA,iBACX,MAAA,EAAQ,IAAA,CAAK,OAAA,0BACb,OAAA,WACC,UAAA;;;;;;iBA2Ba,iBAAA,CACd,IAAA,EAAM,KAAA,EACN,MAAA,GAAS,OAAA,EACT,OAAA,GAAS,mBAAA,GACR,QAAA;;;;;;iBAkEa,qBAAA,CAAsB,QAAA,EAAU,QAAA,EAAU,MAAA,GAAS,gBAAA,GAAmB,QAAA"}
1
+ {"version":3,"file":"page-metadata.d.ts","names":[],"sources":["../../src/lib/page-metadata.ts"],"mappings":";;;;;KAeY,iBAAA;mDAEV,IAAA,UAF2B;EAI3B,IAAA,WAJ2B;EAM3B,WAAA;AAAA;AAAA,KAGU,wBAAA,GACR,eAAA,GACA,MAAA;AAAA,KAEQ,mBAAA;EACV,IAAA,EAAM,KAAA;EACN,MAAA,GAAS,OAAA;AAAA;AAAA,KAGC,mBAAA;EACV,KAAA,GAAQ,iBAAA,EARA;EAUR,OAAA,WAR6B;EAU7B,YAAA,GAAe,wBAAA;EARC;;;;;EAchB,SAAA,eAAwB,IAAA,EAAM,KAAA,eAdd;EAgBhB,MAAA,IAAU,QAAA,EAAU,QAAA,EAAU,OAAA,EAAS,mBAAA,KAAwB,QAAA;AAAA;;;;;iBAOjD,qBAAA,CAAsB,GAAA,GAAK,MAAA,CAAO,UAAA;;iBAclC,WAAA,CAAY,IAAA;;iBAuBZ,kBAAA,CAAmB,IAAA,sBAA0B,OAAA;;iBAsB7C,kBAAA,CAAmB,YAAA,GAAe,wBAAA;;;;;iBAUlC,iBAAA,CACd,IAAA,EAAM,IAAA,CAAK,KAAA,iBACX,MAAA,EAAQ,IAAA,CAAK,OAAA,cACb,OAAA,WACC,UAAA;;iBAkCa,eAAA,CACd,IAAA,EAAM,IAAA,CAAK,KAAA,iBACX,MAAA,EAAQ,IAAA,CAAK,OAAA,0BACb,OAAA,WACC,UAAA;;;;;;iBA2Ba,iBAAA,CACd,IAAA,EAAM,KAAA,EACN,MAAA,GAAS,OAAA,EACT,OAAA,GAAS,mBAAA,GACR,QAAA;;AA9IH;;;;iBAoNgB,qBAAA,CAAsB,QAAA,EAAU,QAAA,EAAU,MAAA,GAAS,gBAAA,GAAmB,QAAA"}
@@ -1,7 +1,14 @@
1
1
  import { getPublicUrl } from "./utils.js";
2
- import { defaultLocale, defaultMarket, getMetaRobots } from "@websolutespa/bom-core";
2
+ import { defaultLocale, defaultMarket, getIsProduction, getMetaRobots } from "@websolutespa/bom-core";
3
3
  import { convert } from "html-to-text";
4
4
  //#region src/lib/page-metadata.ts
5
+ /**
6
+ * The deployment policy: pages are indexable only in production (`PRODUCTION=true`, as the BOM 3 `Meta` component
7
+ * required) and unless `NOINDEX=true`. Every other deployment (staging, previews, local) is `noindex`.
8
+ */
9
+ function isIndexableDeployment(env = process.env) {
10
+ return getIsProduction() && env.NOINDEX !== "true";
11
+ }
5
12
  /** Converts CMS HTML (titles, abstracts) to a single line of plain text. */
6
13
  function toPlainText(html) {
7
14
  if (!html) return "";
@@ -114,7 +121,7 @@ function buildPageMetadata(page, layout, options = {}) {
114
121
  const image = resolveMetadataUrl(getMediaUrl(meta.image) || getMediaUrl(page.media) || options.brand?.logo, baseUrl);
115
122
  const canonicalBase = resolveMetadataUrl(page.href, baseUrl);
116
123
  const canonical = canonicalBase ? `${canonicalBase}${getPaginationQuery(options.searchParams)}` : void 0;
117
- const robots = getMetaRobots(meta);
124
+ const robots = (typeof options.indexable === "function" ? options.indexable(page) : options.indexable ?? isIndexableDeployment()) ? getMetaRobots(meta) : "noindex, nofollow";
118
125
  const languages = {};
119
126
  if (layout) {
120
127
  getPageAlternates(page, layout, baseUrl).forEach((alternate) => {
@@ -187,6 +194,6 @@ function inheritParentMetadata(metadata, parent) {
187
194
  };
188
195
  }
189
196
  //#endregion
190
- export { buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, resolveMetadataUrl, toPlainText };
197
+ export { buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, isIndexableDeployment, resolveMetadataUrl, toPlainText };
191
198
 
192
199
  //# sourceMappingURL=page-metadata.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"page-metadata.js","names":[],"sources":["../../src/lib/page-metadata.ts"],"sourcesContent":["import {\n defaultLocale,\n defaultMarket,\n getMetaRobots,\n ILayout,\n IMedia,\n IPage,\n IRoute,\n} from '@websolutespa/bom-core';\nimport { convert } from 'html-to-text';\nimport type { Metadata, ResolvedMetadata } from 'next';\nimport type { IAlternate } from './meta-data';\nimport { getPublicUrl } from './utils';\n\nexport type PageMetadataBrand = {\n /** Site name, used for Open Graph `siteName`. */\n name: string;\n /** Fallback image when the page has no meta image or media. */\n logo?: string;\n /** Twitter handle, used for `twitter:site` and `twitter:creator`. */\n twitterName?: string;\n};\n\nexport type PageMetadataSearchParams =\n | URLSearchParams\n | Record<string, string | string[] | undefined>;\n\nexport type PageMetadataContext = {\n page: IPage;\n layout?: ILayout;\n};\n\nexport type PageMetadataOptions = {\n brand?: PageMetadataBrand;\n /** Absolute origin for canonical, alternates and images. Default `NEXT_PUBLIC_URL`. */\n baseUrl?: string;\n /** Request search params; `pagination[page]` > 1 is kept in the canonical URL. */\n searchParams?: PageMetadataSearchParams;\n /** Per-page override applied to the computed metadata. */\n extend?: (metadata: Metadata, context: PageMetadataContext) => Metadata;\n};\n\ntype PageMetaFields = {\n title?: string;\n description?: string;\n keywords?: string;\n robots?: string;\n robot?: string;\n image?: IMedia | string | null;\n};\n\n/** Converts CMS HTML (titles, abstracts) to a single line of plain text. */\nexport function toPlainText(html?: string | null): string {\n if (!html) {\n return '';\n }\n return convert(html, {\n wordwrap: false,\n selectors: [\n { selector: 'a', options: { ignoreHref: true } },\n { selector: 'img', format: 'skip' },\n // keep the original case and drop list bullets: this text ends up in meta tags\n ...['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].map((selector) => ({\n selector,\n options: { uppercase: false },\n })),\n { selector: 'ul', options: { itemPrefix: ' ' } },\n { selector: 'table', format: 'dataTable', options: { uppercaseHeaderCells: false } },\n ],\n })\n .replace(/\\s+/g, ' ')\n .trim();\n}\n\n/** Resolves a relative href against `baseUrl`; absolute URLs are returned as is. */\nexport function resolveMetadataUrl(href: string | undefined, baseUrl: string): string | undefined {\n if (!href) {\n return undefined;\n }\n return /^https?:\\/\\//.test(href) ? href : `${baseUrl}${href}`;\n}\n\nfunction getSearchParam(\n searchParams: PageMetadataSearchParams | undefined,\n key: string\n): string | undefined {\n if (!searchParams) {\n return undefined;\n }\n if (searchParams instanceof URLSearchParams) {\n return searchParams.get(key) ?? undefined;\n }\n const value = searchParams[key];\n return Array.isArray(value) ? value[0] : value;\n}\n\n/** Returns `?pagination[page]=N` for pages after the first, otherwise an empty string. */\nexport function getPaginationQuery(searchParams?: PageMetadataSearchParams): string {\n const value = getSearchParam(searchParams, 'pagination[page]');\n const page = value ? parseInt(value) : NaN;\n return Number.isInteger(page) && page > 1 ? `?pagination[page]=${page}` : '';\n}\n\n/**\n * Builds hreflang alternates from the page's routes. Markets with countries\n * produce one `locale-COUNTRY` entry per country; others use the locale only.\n */\nexport function getPageAlternates(\n page: Pick<IPage, 'alternates'>,\n layout: Pick<ILayout, 'markets'>,\n baseUrl: string\n): IAlternate[] {\n const alternates: IAlternate[] = [];\n (page.alternates || []).forEach((alternate: IRoute) => {\n const market = layout.markets.find((x) => x.id === alternate.market);\n if (!market) {\n return;\n }\n const href = resolveMetadataUrl(alternate.id, baseUrl) as string;\n const countries = (market.countries || []) as Array<\n string | { alpha2Code?: string; id?: string }\n >;\n if (countries.length > 0) {\n countries.forEach((country) => {\n const code = typeof country === 'string' ? country : country.alpha2Code || country.id;\n if (code) {\n alternates.push({\n id: `${alternate.market}-${alternate.locale}-${code}`,\n href,\n hrefLang: `${alternate.locale}-${code.toUpperCase()}`,\n });\n }\n });\n } else {\n alternates.push({\n id: `${alternate.market}-${alternate.locale}`,\n href,\n hrefLang: alternate.locale,\n });\n }\n });\n return alternates;\n}\n\n/** The alternate for the default market and locale, used as `x-default`. */\nexport function getPageXDefault(\n page: Pick<IPage, 'alternates'>,\n layout: Pick<ILayout, 'markets' | 'locales'>,\n baseUrl: string\n): IAlternate | undefined {\n const market = layout.markets.find((x) => x.isDefault)?.id || defaultMarket;\n const locale = layout.locales.find((x) => x.isDefault)?.id || defaultLocale;\n const alternate = (page.alternates || []).find((x) => x.market === market && x.locale === locale);\n if (!alternate) {\n return undefined;\n }\n return {\n id: `${alternate.market}-${alternate.locale}`,\n href: resolveMetadataUrl(alternate.id, baseUrl) as string,\n hrefLang: alternate.locale,\n };\n}\n\nfunction getMediaUrl(media: unknown): string | undefined {\n if (media && typeof media === 'object') {\n const { src, url } = media as { src?: string; url?: string };\n return src || url;\n }\n return undefined;\n}\n\n/**\n * Builds the Next.js `Metadata` for a page: plain-text title and description,\n * canonical (keeping pagination), hreflang alternates with `x-default`,\n * robots, keywords, Open Graph and Twitter card.\n */\nexport function buildPageMetadata(\n page: IPage,\n layout?: ILayout,\n options: PageMetadataOptions = {}\n): Metadata {\n const baseUrl = (options.baseUrl ?? getPublicUrl()).replace(/\\/$/, '');\n const meta = ((page as { meta?: PageMetaFields }).meta || {}) as PageMetaFields;\n const title = toPlainText(meta.title || page.title);\n const description =\n toPlainText(meta.description || (page as { abstract?: string }).abstract) || undefined;\n const image = resolveMetadataUrl(\n getMediaUrl(meta.image) ||\n getMediaUrl((page as { media?: unknown }).media) ||\n options.brand?.logo,\n baseUrl\n );\n const canonicalBase = resolveMetadataUrl(page.href, baseUrl);\n const canonical = canonicalBase\n ? `${canonicalBase}${getPaginationQuery(options.searchParams)}`\n : undefined;\n const robots = getMetaRobots(meta);\n\n const languages: Record<string, string> = {};\n if (layout) {\n getPageAlternates(page, layout, baseUrl).forEach((alternate) => {\n languages[alternate.hrefLang] = alternate.href;\n });\n const xDefault = getPageXDefault(page, layout, baseUrl);\n if (xDefault) {\n languages['x-default'] = xDefault.href;\n }\n }\n\n const images = image ? [{ url: image, alt: title }] : undefined;\n const metadata: Metadata = {\n title,\n description,\n ...(meta.keywords ? { keywords: meta.keywords } : {}),\n ...(robots ? { robots } : {}),\n alternates: {\n canonical,\n ...(Object.keys(languages).length > 0 ? { languages } : {}),\n },\n openGraph: {\n type: 'website',\n title,\n description,\n url: canonical,\n siteName: options.brand?.name,\n locale: layout?.locale ?? page.locale,\n images,\n },\n twitter: {\n card: image ? 'summary_large_image' : 'summary',\n title,\n description,\n images: image ? [image] : undefined,\n ...(options.brand?.twitterName\n ? { site: options.brand.twitterName, creator: options.brand.twitterName }\n : {}),\n },\n };\n return options.extend ? options.extend(metadata, { page, layout }) : metadata;\n}\n\n/**\n * Next.js replaces nested `openGraph` and `twitter` objects instead of merging\n * them, so a page that sets them would drop the layout's images, site name or\n * handles. Fills the fields the page left empty from the parent metadata.\n */\nexport function inheritParentMetadata(metadata: Metadata, parent?: ResolvedMetadata): Metadata {\n if (!parent) {\n return metadata;\n }\n const openGraph = metadata.openGraph;\n const twitter = metadata.twitter;\n return {\n ...metadata,\n ...(openGraph\n ? {\n openGraph: {\n ...openGraph,\n images: openGraph.images ?? parent.openGraph?.images,\n siteName: openGraph.siteName ?? parent.openGraph?.siteName,\n },\n }\n : {}),\n ...(twitter\n ? {\n twitter: {\n ...twitter,\n // without a page image, the card type follows the inherited images\n ...(!twitter.images && parent.twitter?.images ? { card: parent.twitter.card } : {}),\n images: twitter.images ?? parent.twitter?.images,\n site: twitter.site ?? parent.twitter?.site,\n creator: twitter.creator ?? parent.twitter?.creator,\n } as Metadata['twitter'],\n }\n : {}),\n };\n}\n"],"mappings":";;;;;AAoDA,SAAgB,YAAY,MAA8B;AACxD,KAAI,CAAC,KACH,QAAO;AAET,QAAO,QAAQ,MAAM;EACnB,UAAU;EACV,WAAW;GACT;IAAE,UAAU;IAAK,SAAS,EAAE,YAAY,MAAM;IAAE;GAChD;IAAE,UAAU;IAAO,QAAQ;IAAQ;GAEnC,GAAG;IAAC;IAAM;IAAM;IAAM;IAAM;IAAM;IAAK,CAAC,KAAK,cAAc;IACzD;IACA,SAAS,EAAE,WAAW,OAAO;IAC9B,EAAE;GACH;IAAE,UAAU;IAAM,SAAS,EAAE,YAAY,KAAK;IAAE;GAChD;IAAE,UAAU;IAAS,QAAQ;IAAa,SAAS,EAAE,sBAAsB,OAAO;IAAE;GACrF;EACF,CAAC,CACC,QAAQ,QAAQ,IAAI,CACpB,MAAM;;;AAIX,SAAgB,mBAAmB,MAA0B,SAAqC;AAChG,KAAI,CAAC,KACH;AAEF,QAAO,eAAe,KAAK,KAAK,GAAG,OAAO,GAAG,UAAU;;AAGzD,SAAS,eACP,cACA,KACoB;AACpB,KAAI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AAE;EAC5B,YAAY;GACV;GACA,GAAI,OAAO,KAAK,UAAU,CAAC,SAAS,IAAI,EAAE,WAAW,GAAG,EAAE;GAC3D;EACD,WAAW;GACT,MAAM;GACN;GACA;GACA,KAAK;GACL,UAAU,QAAQ,OAAO;GACzB,QAAQ,QAAQ,UAAU,KAAK;GAC/B;GACD;EACD,SAAS;GACP,MAAM,QAAQ,wBAAwB;GACtC;GACA;GACA,QAAQ,QAAQ,CAAC,MAAM,GAAG,KAAA;GAC1B,GAAI,QAAQ,OAAO,cACf;IAAE,MAAM,QAAQ,MAAM;IAAa,SAAS,QAAQ,MAAM;IAAa,GACvE,EAAE;GACP;EACF;AACD,QAAO,QAAQ,SAAS,QAAQ,OAAO,UAAU;EAAE;EAAM;EAAQ,CAAC,GAAG;;;;;;;AAQvE,SAAgB,sBAAsB,UAAoB,QAAqC;AAC7F,KAAI,CAAC,OACH,QAAO;CAET,MAAM,YAAY,SAAS;CAC3B,MAAM,UAAU,SAAS;AACzB,QAAO;EACL,GAAG;EACH,GAAI,YACA,EACE,WAAW;GACT,GAAG;GACH,QAAQ,UAAU,UAAU,OAAO,WAAW;GAC9C,UAAU,UAAU,YAAY,OAAO,WAAW;GACnD,EACF,GACD,EAAE;EACN,GAAI,UACA,EACE,SAAS;GACP,GAAG;GAEH,GAAI,CAAC,QAAQ,UAAU,OAAO,SAAS,SAAS,EAAE,MAAM,OAAO,QAAQ,MAAM,GAAG,EAAE;GAClF,QAAQ,QAAQ,UAAU,OAAO,SAAS;GAC1C,MAAM,QAAQ,QAAQ,OAAO,SAAS;GACtC,SAAS,QAAQ,WAAW,OAAO,SAAS;GAC7C,EACF,GACD,EAAE;EACP"}
1
+ {"version":3,"file":"page-metadata.js","names":[],"sources":["../../src/lib/page-metadata.ts"],"sourcesContent":["import {\n defaultLocale,\n defaultMarket,\n getIsProduction,\n getMetaRobots,\n ILayout,\n IMedia,\n IPage,\n IRoute,\n} from '@websolutespa/bom-core';\nimport { convert } from 'html-to-text';\nimport type { Metadata, ResolvedMetadata } from 'next';\nimport type { IAlternate } from './meta-data';\nimport { getPublicUrl } from './utils';\n\nexport type PageMetadataBrand = {\n /** Site name, used for Open Graph `siteName`. */\n name: string;\n /** Fallback image when the page has no meta image or media. */\n logo?: string;\n /** Twitter handle, used for `twitter:site` and `twitter:creator`. */\n twitterName?: string;\n};\n\nexport type PageMetadataSearchParams =\n | URLSearchParams\n | Record<string, string | string[] | undefined>;\n\nexport type PageMetadataContext = {\n page: IPage;\n layout?: ILayout;\n};\n\nexport type PageMetadataOptions = {\n brand?: PageMetadataBrand;\n /** Absolute origin for canonical, alternates and images. Default `NEXT_PUBLIC_URL`. */\n baseUrl?: string;\n /** Request search params; `pagination[page]` > 1 is kept in the canonical URL. */\n searchParams?: PageMetadataSearchParams;\n /**\n * Whether search engines may index the page. When false (or a function returning false), `robots` is\n * `noindex, nofollow`, over the page's own `meta.robots`. Default: {@link isIndexableDeployment}, so staging\n * and preview deployments are never indexed.\n */\n indexable?: boolean | ((page: IPage) => boolean);\n /** Per-page override applied to the computed metadata. */\n extend?: (metadata: Metadata, context: PageMetadataContext) => Metadata;\n};\n\n/**\n * The deployment policy: pages are indexable only in production (`PRODUCTION=true`, as the BOM 3 `Meta` component\n * required) and unless `NOINDEX=true`. Every other deployment (staging, previews, local) is `noindex`.\n */\nexport function isIndexableDeployment(env: NodeJS.ProcessEnv = process.env): boolean {\n return getIsProduction() && env.NOINDEX !== 'true';\n}\n\ntype PageMetaFields = {\n title?: string;\n description?: string;\n keywords?: string;\n robots?: string;\n robot?: string;\n image?: IMedia | string | null;\n};\n\n/** Converts CMS HTML (titles, abstracts) to a single line of plain text. */\nexport function toPlainText(html?: string | null): string {\n if (!html) {\n return '';\n }\n return convert(html, {\n wordwrap: false,\n selectors: [\n { selector: 'a', options: { ignoreHref: true } },\n { selector: 'img', format: 'skip' },\n // keep the original case and drop list bullets: this text ends up in meta tags\n ...['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].map((selector) => ({\n selector,\n options: { uppercase: false },\n })),\n { selector: 'ul', options: { itemPrefix: ' ' } },\n { selector: 'table', format: 'dataTable', options: { uppercaseHeaderCells: false } },\n ],\n })\n .replace(/\\s+/g, ' ')\n .trim();\n}\n\n/** Resolves a relative href against `baseUrl`; absolute URLs are returned as is. */\nexport function resolveMetadataUrl(href: string | undefined, baseUrl: string): string | undefined {\n if (!href) {\n return undefined;\n }\n return /^https?:\\/\\//.test(href) ? href : `${baseUrl}${href}`;\n}\n\nfunction getSearchParam(\n searchParams: PageMetadataSearchParams | undefined,\n key: string\n): string | undefined {\n if (!searchParams) {\n return undefined;\n }\n if (searchParams instanceof URLSearchParams) {\n return searchParams.get(key) ?? undefined;\n }\n const value = searchParams[key];\n return Array.isArray(value) ? value[0] : value;\n}\n\n/** Returns `?pagination[page]=N` for pages after the first, otherwise an empty string. */\nexport function getPaginationQuery(searchParams?: PageMetadataSearchParams): string {\n const value = getSearchParam(searchParams, 'pagination[page]');\n const page = value ? parseInt(value) : NaN;\n return Number.isInteger(page) && page > 1 ? `?pagination[page]=${page}` : '';\n}\n\n/**\n * Builds hreflang alternates from the page's routes. Markets with countries\n * produce one `locale-COUNTRY` entry per country; others use the locale only.\n */\nexport function getPageAlternates(\n page: Pick<IPage, 'alternates'>,\n layout: Pick<ILayout, 'markets'>,\n baseUrl: string\n): IAlternate[] {\n const alternates: IAlternate[] = [];\n (page.alternates || []).forEach((alternate: IRoute) => {\n const market = layout.markets.find((x) => x.id === alternate.market);\n if (!market) {\n return;\n }\n const href = resolveMetadataUrl(alternate.id, baseUrl) as string;\n const countries = (market.countries || []) as Array<\n string | { alpha2Code?: string; id?: string }\n >;\n if (countries.length > 0) {\n countries.forEach((country) => {\n const code = typeof country === 'string' ? country : country.alpha2Code || country.id;\n if (code) {\n alternates.push({\n id: `${alternate.market}-${alternate.locale}-${code}`,\n href,\n hrefLang: `${alternate.locale}-${code.toUpperCase()}`,\n });\n }\n });\n } else {\n alternates.push({\n id: `${alternate.market}-${alternate.locale}`,\n href,\n hrefLang: alternate.locale,\n });\n }\n });\n return alternates;\n}\n\n/** The alternate for the default market and locale, used as `x-default`. */\nexport function getPageXDefault(\n page: Pick<IPage, 'alternates'>,\n layout: Pick<ILayout, 'markets' | 'locales'>,\n baseUrl: string\n): IAlternate | undefined {\n const market = layout.markets.find((x) => x.isDefault)?.id || defaultMarket;\n const locale = layout.locales.find((x) => x.isDefault)?.id || defaultLocale;\n const alternate = (page.alternates || []).find((x) => x.market === market && x.locale === locale);\n if (!alternate) {\n return undefined;\n }\n return {\n id: `${alternate.market}-${alternate.locale}`,\n href: resolveMetadataUrl(alternate.id, baseUrl) as string,\n hrefLang: alternate.locale,\n };\n}\n\nfunction getMediaUrl(media: unknown): string | undefined {\n if (media && typeof media === 'object') {\n const { src, url } = media as { src?: string; url?: string };\n return src || url;\n }\n return undefined;\n}\n\n/**\n * Builds the Next.js `Metadata` for a page: plain-text title and description,\n * canonical (keeping pagination), hreflang alternates with `x-default`,\n * robots, keywords, Open Graph and Twitter card.\n */\nexport function buildPageMetadata(\n page: IPage,\n layout?: ILayout,\n options: PageMetadataOptions = {}\n): Metadata {\n const baseUrl = (options.baseUrl ?? getPublicUrl()).replace(/\\/$/, '');\n const meta = ((page as { meta?: PageMetaFields }).meta || {}) as PageMetaFields;\n const title = toPlainText(meta.title || page.title);\n const description =\n toPlainText(meta.description || (page as { abstract?: string }).abstract) || undefined;\n const image = resolveMetadataUrl(\n getMediaUrl(meta.image) ||\n getMediaUrl((page as { media?: unknown }).media) ||\n options.brand?.logo,\n baseUrl\n );\n const canonicalBase = resolveMetadataUrl(page.href, baseUrl);\n const canonical = canonicalBase\n ? `${canonicalBase}${getPaginationQuery(options.searchParams)}`\n : undefined;\n const indexable =\n typeof options.indexable === 'function'\n ? options.indexable(page)\n : (options.indexable ?? isIndexableDeployment());\n const robots = indexable ? getMetaRobots(meta) : 'noindex, nofollow';\n\n const languages: Record<string, string> = {};\n if (layout) {\n getPageAlternates(page, layout, baseUrl).forEach((alternate) => {\n languages[alternate.hrefLang] = alternate.href;\n });\n const xDefault = getPageXDefault(page, layout, baseUrl);\n if (xDefault) {\n languages['x-default'] = xDefault.href;\n }\n }\n\n const images = image ? [{ url: image, alt: title }] : undefined;\n const metadata: Metadata = {\n title,\n description,\n ...(meta.keywords ? { keywords: meta.keywords } : {}),\n ...(robots ? { robots } : {}),\n alternates: {\n canonical,\n ...(Object.keys(languages).length > 0 ? { languages } : {}),\n },\n openGraph: {\n type: 'website',\n title,\n description,\n url: canonical,\n siteName: options.brand?.name,\n locale: layout?.locale ?? page.locale,\n images,\n },\n twitter: {\n card: image ? 'summary_large_image' : 'summary',\n title,\n description,\n images: image ? [image] : undefined,\n ...(options.brand?.twitterName\n ? { site: options.brand.twitterName, creator: options.brand.twitterName }\n : {}),\n },\n };\n return options.extend ? options.extend(metadata, { page, layout }) : metadata;\n}\n\n/**\n * Next.js replaces nested `openGraph` and `twitter` objects instead of merging\n * them, so a page that sets them would drop the layout's images, site name or\n * handles. Fills the fields the page left empty from the parent metadata.\n */\nexport function inheritParentMetadata(metadata: Metadata, parent?: ResolvedMetadata): Metadata {\n if (!parent) {\n return metadata;\n }\n const openGraph = metadata.openGraph;\n const twitter = metadata.twitter;\n return {\n ...metadata,\n ...(openGraph\n ? {\n openGraph: {\n ...openGraph,\n images: openGraph.images ?? parent.openGraph?.images,\n siteName: openGraph.siteName ?? parent.openGraph?.siteName,\n },\n }\n : {}),\n ...(twitter\n ? {\n twitter: {\n ...twitter,\n // without a page image, the card type follows the inherited images\n ...(!twitter.images && parent.twitter?.images ? { card: parent.twitter.card } : {}),\n images: twitter.images ?? parent.twitter?.images,\n site: twitter.site ?? parent.twitter?.site,\n creator: twitter.creator ?? parent.twitter?.creator,\n } as Metadata['twitter'],\n }\n : {}),\n };\n}\n"],"mappings":";;;;;;;;AAqDA,SAAgB,sBAAsB,MAAyB,QAAQ,KAAc;AACnF,QAAO,iBAAiB,IAAI,IAAI,YAAY;;;AAa9C,SAAgB,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sBAAsB,UAAoB,QAAqC;AAC7F,KAAI,CAAC,OACH,QAAO;CAET,MAAM,YAAY,SAAS;CAC3B,MAAM,UAAU,SAAS;AACzB,QAAO;EACL,GAAG;EACH,GAAI,YACA,EACE,WAAW;GACT,GAAG;GACH,QAAQ,UAAU,UAAU,OAAO,WAAW;GAC9C,UAAU,UAAU,YAAY,OAAO,WAAW;GACnD,EACF,GACD,EAAE;EACN,GAAI,UACA,EACE,SAAS;GACP,GAAG;GAEH,GAAI,CAAC,QAAQ,UAAU,OAAO,SAAS,SAAS,EAAE,MAAM,OAAO,QAAQ,MAAM,GAAG,EAAE;GAClF,QAAQ,QAAQ,UAAU,OAAO,SAAS;GAC1C,MAAM,QAAQ,QAAQ,OAAO,SAAS;GACtC,SAAS,QAAQ,WAAW,OAAO,SAAS;GAC7C,EACF,GACD,EAAE;EACP"}
@@ -1,7 +1,31 @@
1
- import { NextRequest, NextResponse } from "next/server";
1
+ import { PREVIEW_ROLES } from "../../lib/const.js";
2
+ import { NextRequest } from "next/server";
3
+ import { SanitizedConfig } from "payload";
2
4
 
3
5
  //#region src/server/handlers/preview.handler.d.ts
4
- declare function previewHandler(request: NextRequest): Promise<NextResponse<unknown>>;
6
+ /**
7
+ * The `/api/-preview` route: turns Draft Mode on for an editor and redirects to the page. Draft Mode shows
8
+ * unpublished content (bom-next reads it with an editing role), so only these callers get the cookie:
9
+ * - a logged-in editor: the admin session cookie (admin and site on one origin), or the `_token` Bowl adds to
10
+ * the admin's preview URL (admin on another origin);
11
+ * - `secret` equal to `MIXER_SECRET`.
12
+ * Everyone else gets 401 and no cookie.
13
+ *
14
+ * ```ts
15
+ * // src/app/api/-preview/route.ts
16
+ * export const GET = getPreviewHandler(config);
17
+ * ```
18
+ */
19
+ declare function getPreviewHandler(config: Promise<SanitizedConfig>, {
20
+ roles
21
+ }?: {
22
+ roles?: string[];
23
+ }): (request: NextRequest) => Promise<Response>;
24
+ /**
25
+ * @deprecated Use `getPreviewHandler(config)`, which also accepts an editor session. Without the config this
26
+ * handler cannot authenticate a user, so it turns Draft Mode on only with `secret` equal to `MIXER_SECRET`.
27
+ */
28
+ declare function previewHandler(request: NextRequest): Promise<Response>;
5
29
  //#endregion
6
- export { previewHandler };
30
+ export { getPreviewHandler, previewHandler };
7
31
  //# sourceMappingURL=preview.handler.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"preview.handler.d.ts","names":[],"sources":["../../../src/server/handlers/preview.handler.ts"],"mappings":";;;iBAKsB,cAAA,CAAe,OAAA,EAAS,WAAA,GAAW,OAAA,CAAA,YAAA"}
1
+ {"version":3,"file":"preview.handler.d.ts","names":[],"sources":["../../../src/server/handlers/preview.handler.ts"],"mappings":";;;;;;AAuDA;;;;;;;;;;;;iBAAgB,iBAAA,CACd,MAAA,EAAQ,OAAA,CAAQ,eAAA;EACd;AAAA;EAA2B,KAAA;AAAA,KAEN,OAAA,EAAS,WAAA,KAAc,OAAA,CAAQ,QAAA;;;;;iBA6BlC,cAAA,CAAe,OAAA,EAAS,WAAA,GAAc,OAAA,CAAQ,QAAA"}
@@ -1,15 +1,66 @@
1
+ import { PREVIEW_ROLES } from "../../lib/const.js";
1
2
  import { NextResponse } from "next/server";
2
3
  import { draftMode } from "next/headers";
4
+ import { getPayload } from "payload";
3
5
  //#region src/server/handlers/preview.handler.ts
4
- async function previewHandler(request) {
5
- const { searchParams } = new URL(request.url);
6
- const { marketId, localeId, templateId, documentId, _status, _live } = Object.fromEntries(searchParams);
6
+ const SEGMENT = /^[\w-]+$/;
7
+ function hasSecret(params) {
8
+ return Boolean(process.env.MIXER_SECRET) && params.secret === process.env.MIXER_SECRET;
9
+ }
10
+ /** Turns Draft Mode on and redirects to the internal page path. */
11
+ async function enablePreview(params) {
12
+ const { marketId, localeId, templateId, documentId, _live } = params;
13
+ if (![
14
+ marketId,
15
+ localeId,
16
+ templateId,
17
+ documentId
18
+ ].every((value) => value && SEGMENT.test(value))) return new Response("Bad Request", { status: 400 });
7
19
  const destination = `/${marketId}/${localeId}/${templateId}/${documentId}${_live ? "?_live=true" : ""}`;
8
20
  (await draftMode()).enable();
9
- const path = `${process.env.NEXT_PUBLIC_URL}${destination}`;
10
- return NextResponse.redirect(path, { status: 303 });
21
+ return NextResponse.redirect(`${process.env.NEXT_PUBLIC_URL}${destination}`, { status: 303 });
22
+ }
23
+ /**
24
+ * The `/api/-preview` route: turns Draft Mode on for an editor and redirects to the page. Draft Mode shows
25
+ * unpublished content (bom-next reads it with an editing role), so only these callers get the cookie:
26
+ * - a logged-in editor: the admin session cookie (admin and site on one origin), or the `_token` Bowl adds to
27
+ * the admin's preview URL (admin on another origin);
28
+ * - `secret` equal to `MIXER_SECRET`.
29
+ * Everyone else gets 401 and no cookie.
30
+ *
31
+ * ```ts
32
+ * // src/app/api/-preview/route.ts
33
+ * export const GET = getPreviewHandler(config);
34
+ * ```
35
+ */
36
+ function getPreviewHandler(config, { roles = PREVIEW_ROLES } = {}) {
37
+ return async function(request) {
38
+ const params = Object.fromEntries(request.nextUrl.searchParams);
39
+ if (!hasSecret(params)) {
40
+ const payload = await getPayload({ config });
41
+ const isEditor = async (headers) => {
42
+ try {
43
+ const { user } = await payload.auth({ headers });
44
+ return (user?.roles ?? []).some((role) => roles.includes(role));
45
+ } catch {
46
+ return false;
47
+ }
48
+ };
49
+ if (!(await isEditor(request.headers) || Boolean(params._token) && await isEditor(new Headers({ authorization: `JWT ${params._token}` })))) return new Response("Unauthorized", { status: 401 });
50
+ }
51
+ return enablePreview(params);
52
+ };
53
+ }
54
+ /**
55
+ * @deprecated Use `getPreviewHandler(config)`, which also accepts an editor session. Without the config this
56
+ * handler cannot authenticate a user, so it turns Draft Mode on only with `secret` equal to `MIXER_SECRET`.
57
+ */
58
+ async function previewHandler(request) {
59
+ const params = Object.fromEntries(request.nextUrl.searchParams);
60
+ if (!hasSecret(params)) return new Response("Unauthorized", { status: 401 });
61
+ return enablePreview(params);
11
62
  }
12
63
  //#endregion
13
- export { previewHandler };
64
+ export { getPreviewHandler, previewHandler };
14
65
 
15
66
  //# sourceMappingURL=preview.handler.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"preview.handler.js","names":[],"sources":["../../../src/server/handlers/preview.handler.ts"],"sourcesContent":["import { draftMode } from 'next/headers';\nimport { NextRequest, NextResponse } from 'next/server';\n\n// http://localhost:3000/api/-preview?marketId=ww&localeId=it&templateId=homepage&documentId=6a6b33177d8f191df34b33a3\n\nexport async function previewHandler(request: NextRequest) {\n const { searchParams } = new URL(request.url);\n const params = Object.fromEntries(searchParams) as {\n marketId: string;\n localeId: string;\n templateId: string;\n documentId: string;\n _status: 'published' | 'draft';\n _live: string;\n _token: string;\n };\n /*\n if (params.secret !== process.env.MIXER_SECRET) {\n return new Response('Invalid token', { status: 401 })\n }\n */\n /*\n const headersList = await headers()\n const userAgent = headersList.get('user-agent')\n */\n const { marketId, localeId, templateId, documentId, _status, _live } = params;\n const destination = `/${marketId}/${localeId}/${templateId}/${documentId}${_live ? '?_live=true' : ''}`;\n /*\n response.setPreviewData({ _status });\n response.setDraftMode({ enable: true });\n response.redirect(307, destination);\n redirect(destination, RedirectType.replace);\n */\n const draft = await draftMode();\n draft.enable();\n const path = `${process.env.NEXT_PUBLIC_URL}${destination}`;\n return NextResponse.redirect(path, {\n status: 303,\n });\n /*\n return NextResponse.redirect(path, {\n status: 303,\n });\n */\n /*\n return new Response(null, {\n status: 303,\n headers: {\n Location: path,\n },\n });\n */\n /*\n redirect(path);\n return;\n */\n /*\n return NextResponse.json({\n destination: destination,\n permanent: false\n });\n */\n}\n"],"mappings":";;;AAKA,eAAsB,eAAe,SAAsB;CACzD,MAAM,EAAE,iBAAiB,IAAI,IAAI,QAAQ,IAAI;CAmB7C,MAAM,EAAE,UAAU,UAAU,YAAY,YAAY,SAAS,UAlB9C,OAAO,YAAY,aAAa;CAmB/C,MAAM,cAAc,IAAI,SAAS,GAAG,SAAS,GAAG,WAAW,GAAG,aAAa,QAAQ,gBAAgB;AAQnG,EADc,MAAM,WAAW,EACzB,QAAQ;CACd,MAAM,OAAO,GAAG,QAAQ,IAAI,kBAAkB;AAC9C,QAAO,aAAa,SAAS,MAAM,EACjC,QAAQ,KACT,CAAC"}
1
+ {"version":3,"file":"preview.handler.js","names":[],"sources":["../../../src/server/handlers/preview.handler.ts"],"sourcesContent":["import { draftMode } from 'next/headers';\nimport { NextRequest, NextResponse } from 'next/server';\nimport { getPayload, SanitizedConfig } from 'payload';\nimport { PREVIEW_ROLES } from '../../lib/const';\n\n// http://localhost:3000/api/-preview?marketId=ww&localeId=it&templateId=homepage&documentId=6a6b33177d8f191df34b33a3\n\nexport { PREVIEW_ROLES };\n\ntype PreviewParams = {\n marketId?: string;\n localeId?: string;\n templateId?: string;\n documentId?: string;\n _live?: string;\n /** the editor's token, added by Bowl to the admin's preview URL */\n _token?: string;\n /** `MIXER_SECRET`, for a caller without an editor session */\n secret?: string;\n};\n\n// path segments only: the destination stays on this site\nconst SEGMENT = /^[\\w-]+$/;\n\nfunction hasSecret(params: PreviewParams): boolean {\n return Boolean(process.env.MIXER_SECRET) && params.secret === process.env.MIXER_SECRET;\n}\n\n/** Turns Draft Mode on and redirects to the internal page path. */\nasync function enablePreview(params: PreviewParams): Promise<Response> {\n const { marketId, localeId, templateId, documentId, _live } = params;\n if (\n ![marketId, localeId, templateId, documentId].every((value) => value && SEGMENT.test(value))\n ) {\n return new Response('Bad Request', { status: 400 });\n }\n const destination = `/${marketId}/${localeId}/${templateId}/${documentId}${_live ? '?_live=true' : ''}`;\n const draft = await draftMode();\n draft.enable();\n return NextResponse.redirect(`${process.env.NEXT_PUBLIC_URL}${destination}`, { status: 303 });\n}\n\n/**\n * The `/api/-preview` route: turns Draft Mode on for an editor and redirects to the page. Draft Mode shows\n * unpublished content (bom-next reads it with an editing role), so only these callers get the cookie:\n * - a logged-in editor: the admin session cookie (admin and site on one origin), or the `_token` Bowl adds to\n * the admin's preview URL (admin on another origin);\n * - `secret` equal to `MIXER_SECRET`.\n * Everyone else gets 401 and no cookie.\n *\n * ```ts\n * // src/app/api/-preview/route.ts\n * export const GET = getPreviewHandler(config);\n * ```\n */\nexport function getPreviewHandler(\n config: Promise<SanitizedConfig>,\n { roles = PREVIEW_ROLES }: { roles?: string[] } = {}\n) {\n return async function (request: NextRequest): Promise<Response> {\n const params = Object.fromEntries(request.nextUrl.searchParams) as PreviewParams;\n if (!hasSecret(params)) {\n const payload = await getPayload({ config });\n const isEditor = async (headers: Headers) => {\n try {\n const { user } = await payload.auth({ headers });\n const userRoles = (user as { roles?: string[] } | null)?.roles ?? [];\n return userRoles.some((role) => roles.includes(role));\n } catch {\n return false;\n }\n };\n const allowed =\n (await isEditor(request.headers)) ||\n (Boolean(params._token) &&\n (await isEditor(new Headers({ authorization: `JWT ${params._token}` }))));\n if (!allowed) {\n return new Response('Unauthorized', { status: 401 });\n }\n }\n return enablePreview(params);\n };\n}\n\n/**\n * @deprecated Use `getPreviewHandler(config)`, which also accepts an editor session. Without the config this\n * handler cannot authenticate a user, so it turns Draft Mode on only with `secret` equal to `MIXER_SECRET`.\n */\nexport async function previewHandler(request: NextRequest): Promise<Response> {\n const params = Object.fromEntries(request.nextUrl.searchParams) as PreviewParams;\n if (!hasSecret(params)) {\n return new Response('Unauthorized', { status: 401 });\n }\n return enablePreview(params);\n}\n"],"mappings":";;;;;AAsBA,MAAM,UAAU;AAEhB,SAAS,UAAU,QAAgC;AACjD,QAAO,QAAQ,QAAQ,IAAI,aAAa,IAAI,OAAO,WAAW,QAAQ,IAAI;;;AAI5E,eAAe,cAAc,QAA0C;CACrE,MAAM,EAAE,UAAU,UAAU,YAAY,YAAY,UAAU;AAC9D,KACE,CAAC;EAAC;EAAU;EAAU;EAAY;EAAW,CAAC,OAAO,UAAU,SAAS,QAAQ,KAAK,MAAM,CAAC,CAE5F,QAAO,IAAI,SAAS,eAAe,EAAE,QAAQ,KAAK,CAAC;CAErD,MAAM,cAAc,IAAI,SAAS,GAAG,SAAS,GAAG,WAAW,GAAG,aAAa,QAAQ,gBAAgB;AAEnG,EADc,MAAM,WAAW,EACzB,QAAQ;AACd,QAAO,aAAa,SAAS,GAAG,QAAQ,IAAI,kBAAkB,eAAe,EAAE,QAAQ,KAAK,CAAC;;;;;;;;;;;;;;;AAgB/F,SAAgB,kBACd,QACA,EAAE,QAAQ,kBAAwC,EAAE,EACpD;AACA,QAAO,eAAgB,SAAyC;EAC9D,MAAM,SAAS,OAAO,YAAY,QAAQ,QAAQ,aAAa;AAC/D,MAAI,CAAC,UAAU,OAAO,EAAE;GACtB,MAAM,UAAU,MAAM,WAAW,EAAE,QAAQ,CAAC;GAC5C,MAAM,WAAW,OAAO,YAAqB;AAC3C,QAAI;KACF,MAAM,EAAE,SAAS,MAAM,QAAQ,KAAK,EAAE,SAAS,CAAC;AAEhD,aADmB,MAAsC,SAAS,EAAE,EACnD,MAAM,SAAS,MAAM,SAAS,KAAK,CAAC;YAC/C;AACN,YAAO;;;AAOX,OAAI,EAHD,MAAM,SAAS,QAAQ,QAAQ,IAC/B,QAAQ,OAAO,OAAO,IACpB,MAAM,SAAS,IAAI,QAAQ,EAAE,eAAe,OAAO,OAAO,UAAU,CAAC,CAAC,EAEzE,QAAO,IAAI,SAAS,gBAAgB,EAAE,QAAQ,KAAK,CAAC;;AAGxD,SAAO,cAAc,OAAO;;;;;;;AAQhC,eAAsB,eAAe,SAAyC;CAC5E,MAAM,SAAS,OAAO,YAAY,QAAQ,QAAQ,aAAa;AAC/D,KAAI,CAAC,UAAU,OAAO,CACpB,QAAO,IAAI,SAAS,gBAAgB,EAAE,QAAQ,KAAK,CAAC;AAEtD,QAAO,cAAc,OAAO"}
@@ -1,5 +1,5 @@
1
1
  import { LayoutOption, PageContextOptions, PageParams, PageSelect } from "../types.js";
2
- import { PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataSearchParams, buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, resolveMetadataUrl, toPlainText } from "../lib/page-metadata.js";
2
+ import { PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataSearchParams, buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, isIndexableDeployment, resolveMetadataUrl, toPlainText } from "../lib/page-metadata.js";
3
3
  import { CollectionSlug, SanitizedConfig } from "payload";
4
4
  import { Metadata, ResolvingMetadata } from "next";
5
5
 
@@ -100,7 +100,7 @@ declare function resolveDraft(draft?: DraftOption): Promise<boolean>;
100
100
  declare function getPayload$1({
101
101
  config,
102
102
  headers,
103
- draft
103
+ draft: requestedDraft
104
104
  }: {
105
105
  config: Promise<SanitizedConfig>;
106
106
  headers?: ReadonlyHeaders;
@@ -1 +1 @@
1
- {"version":3,"file":"mixer.d.ts","names":[],"sources":["../../src/server/mixer.ts"],"mappings":";;;;;;;;;;iBAmEgB,sBAAA,CAAA;AAAA,iBAIA,WAAA,CAAA;EACd,MAAA;EACA,MAAA;EACA,IAAA;EACA;AAAA;EAEA,MAAA;EACA,MAAA;EACA,IAAA,GAAO,IAAA,GAAO,MAAA;EACd,KAAA;AAAA;AAAA,iBAeoB,UAAA,CAAA,GAAU,OAAA,CAAA,QAAA;AAAA,iBAYV,UAAA,CAAW,IAAA,EAAM,OAAA,CAAQ,QAAA,IAAS,OAAA;AAAA,iBAUxC,eAAA,CAAgB,OAAA,EAAS,WAAA;;;;;;;;gBAAA,eAAA;AAAA;AAAA,cAa5B,kBAAA,GAAkB,KAAA;EACb,MAAA,EAAQ,eAAA,GAAkB,OAAA,CAAQ,eAAA;AAAA,MAAkB,OAAA,CAAA,WAAA;AAAA,iBAGtD,UAAA,CAAA;EACd,MAAA;EACA,IAAA;EACA;AAAA;EAEA,MAAA;EACA,IAAA,GAAO,IAAA,GAAO,MAAA;EACd,KAAA;AAAA;;;;;;;;AA9CF;;;;iBA+EsB,WAAA,CAAA;EACpB,OAAA;EACA;AAAA;EAEA,OAAA,EAAS,WAAA;EACT,MAAA;EACA,MAAA;EACA,IAAA,GAAO,IAAA,GAAO,MAAA;EACd,KAAA;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AA;AAAA,iBAMhE,cAAA,CAAe,KAAA;EAAS,KAAA;AAAA,gBAA8B,OAAA;;;;AA5OtE;;iBAyPgB,gBAAA,CAAA;EACd,IAAA;EACA,MAAA;EACA,KAAA;EACA,KAAA;EACA,MAAA;EACA,QAAA;EACA;AAAA,GACC,WAAA;EACD,IAAA;EACA,MAAA;AAAA;;oBAFY,OAAA,CAAA,UAAA;EAAA;;UAKQ,WAAA;kBACe,mBAAA;;;;;;;;;;iBAiBrB,gBAAA,CAAiB,IAAA,OAAW,MAAA,UAAgB,KAAA;;oBAA5B,OAAA,CAAA,UAAA;EAAA;;UAlBV,WAAA;kBACe,mBAAA"}
@@ -1,4 +1,4 @@
1
- import { guest } from "../lib/const.js";
1
+ import { PREVIEW_ROLES, guest, previewer } from "../lib/const.js";
2
2
  import { debug } from "../lib/debug.js";
3
3
  import { TtlCache } from "../lib/ttl-cache.js";
4
4
  import { defaultLocale, defaultMarket, isObject } from "@websolutespa/bom-core";
@@ -170,6 +170,10 @@ async function loadMixerContext({ payload, market, locale, user, draft }) {
170
170
  richText: false
171
171
  };
172
172
  }
173
+ /** Whether the user has an editing role, the ones Bowl serves drafts to. */
174
+ function hasPreviewRole(user) {
175
+ return (user?.roles ?? []).some((role) => PREVIEW_ROLES.includes(role));
176
+ }
173
177
  /**
174
178
  * Resolves a draft option to a boolean.
175
179
  * Defaults to `false`. `'auto'` is an explicit opt-in that reads Next's `draftMode()`
@@ -196,7 +200,7 @@ async function resolveDraft(draft = false) {
196
200
  * const headers = await getHeaders();
197
201
  * const { payload, user, getContext } = await getPayload({ config, headers });
198
202
  */
199
- async function getPayload$1({ config, headers, draft = false }) {
203
+ async function getPayload$1({ config, headers, draft: requestedDraft = false }) {
200
204
  const payload = await getPayload({ config });
201
205
  await setContext({ payload });
202
206
  let user = guest;
@@ -209,6 +213,11 @@ async function getPayload$1({ config, headers, draft = false }) {
209
213
  } catch (error) {
210
214
  console.log("getPayload.error", error);
211
215
  }
216
+ let draft = requestedDraft;
217
+ if (draft && !hasPreviewRole(user)) {
218
+ draft = await resolveDraft("auto");
219
+ if (draft) user = previewer;
220
+ }
212
221
  const contexts = /* @__PURE__ */ new Map();
213
222
  return {
214
223
  payload,
@@ -1 +1 @@
1
- {"version":3,"file":"mixer.js","names":["getPayload_","getRoutes","getPayload"],"sources":["../../src/server/mixer.ts"],"sourcesContent":["import {\n defaultLocale,\n defaultMarket,\n ILocale,\n IMarket,\n IRoute,\n isObject,\n} from '@websolutespa/bom-core';\nimport type { Config, User } from '@websolutespa/payload-plugin-bowl';\nimport {\n getRouteStore,\n getRouteStoreDraftRoutes,\n getRouteStoreRoutes,\n onRouteStoreChange,\n} from '@websolutespa/payload-plugin-bowl';\nimport { draftMode } from 'next/headers';\nimport { NextRequest } from 'next/server';\nimport {\n BasePayload,\n getPayload as getPayload_,\n Payload,\n SanitizedConfig,\n TypedFallbackLocale,\n TypedLocale,\n} from 'payload';\nimport { cache } from 'react';\nimport { guest } from '../lib/const';\nimport { debug } from '../lib/debug';\nimport { TtlCache } from '../lib/ttl-cache';\nimport type {\n BaseOptions,\n DraftOption,\n IContext,\n MixerContext,\n ReadOptions,\n ReadonlyHeaders,\n} from '../types';\nimport type { MixerPayload } from './mixer-payload';\n\n// Context entries live for MEMORY_CACHE_DURATION seconds (default 300) and\n// are dropped as soon as the Bowl route store reports a change, locally or\n// from another instance through Redis.\nconst CONTEXT_CACHE_DURATION =\n (process.env.MEMORY_CACHE_DURATION ? parseInt(process.env.MEMORY_CACHE_DURATION) : 5 * 60) * 1000;\nconst CONTEXT_CACHE_MAX = 500;\n\ntype MixerCacheState = {\n cache: TtlCache<MixerContext>;\n subscribed?: boolean;\n};\n\nconst getMixerCacheState = (): MixerCacheState => {\n // A new global key: `_mixer` held an InMemoryCache in earlier versions and\n // can survive a dev hot reload with that shape.\n const globalForMixer = globalThis as typeof globalThis & { _bomMixerContext?: MixerCacheState };\n if (!globalForMixer._bomMixerContext) {\n globalForMixer._bomMixerContext = { cache: new TtlCache<MixerContext>(CONTEXT_CACHE_MAX) };\n }\n const state = globalForMixer._bomMixerContext;\n if (!state.subscribed) {\n state.subscribed = true;\n onRouteStoreChange(() => state.cache.clear());\n }\n return state;\n};\n\n/** Drops every cached mixer context on this instance. */\nexport function clearMixerContextCache() {\n getMixerCacheState().cache.clear();\n}\n\nexport function getCacheKey({\n market = 'all',\n locale = 'all',\n user = guest,\n draft = 'false',\n}: {\n market?: string;\n locale?: string;\n user?: User & Config['user'];\n draft?: string;\n}) {\n const roles = (user?.roles || ['guest']) as string[];\n const tenants = (\n 'tenants' in user && Array.isArray(user.tenants)\n ? user.tenants.map((x: any) => (isObject(x) ? x.id : x))\n : []\n ) as string[];\n roles.sort();\n tenants.sort();\n const keys = [market, locale, draft === 'false' ? 'published' : 'draft', ...roles, ...tenants];\n const key = `context-${keys.join('-')}`;\n return key;\n}\n\nexport async function getContext() {\n let context: IContext | undefined = (globalThis as any)._context;\n if (!context) {\n context = {\n payload: undefined,\n context: undefined,\n } as unknown as IContext;\n (globalThis as any)._context = context;\n }\n return context;\n}\n\nexport async function setContext(data: Partial<IContext>) {\n const context = await getContext();\n if (data.payload) {\n context.payload = data.payload;\n }\n if (data.context) {\n context.context = data.context;\n }\n}\n\nexport function getSearchParams(request: NextRequest) {\n const searchParams = request.nextUrl.searchParams;\n const params = Object.fromEntries(searchParams.entries());\n return {\n market: params.market || defaultMarket,\n locale: params.locale || defaultLocale,\n defaultMarket,\n defaultLocale,\n params,\n searchParams: request.nextUrl.searchParams,\n };\n}\n\nexport const getPayloadInstance = cache(\n async (props: { config: SanitizedConfig | Promise<SanitizedConfig> }) => await getPayload_(props)\n);\n\nexport function getOptions({\n locale = 'all',\n user = guest,\n draft = false,\n}: {\n locale?: string;\n user?: User & Config['user'];\n draft?: boolean;\n}) {\n const localized: BaseOptions = {\n locale: locale as TypedLocale,\n fallbackLocale: defaultLocale as TypedLocale,\n draft,\n depth: 0,\n pagination: false,\n limit: 10000,\n user,\n overrideAccess: false,\n };\n const unlocalized: BaseOptions = {\n locale: 'all',\n fallbackLocale: defaultLocale as TypedLocale,\n draft,\n depth: 0,\n pagination: false,\n limit: 10000,\n user,\n overrideAccess: false,\n };\n return { localized, unlocalized };\n}\n\n/**\n * Returns all routes from the Bowl route store: published routes, or the\n * published routes overlaid with draft pages when `draft` is true.\n *\n * The route store is Guest-readable by design (see payload-plugin-bowl's\n * \"Route Resolution\"), so `market`, `locale` and `user` no longer change the\n * result; they are kept for backward compatibility.\n */\nexport async function getRoutes({\n payload,\n draft = false,\n}: {\n payload: BasePayload;\n market?: string;\n locale?: string;\n user?: User & Config['user'];\n draft?: boolean;\n}): Promise<IRoute[]> {\n const store = await getRouteStore(payload as Payload);\n return draft ? getRouteStoreDraftRoutes(payload as Payload, store) : getRouteStoreRoutes(store);\n}\n\nexport async function getMixerContext({\n payload,\n market,\n locale,\n user = guest,\n draft = false,\n}: {\n payload: BasePayload;\n market: string;\n locale: string;\n user?: User & Config['user'];\n draft?: boolean;\n}): Promise<MixerContext> {\n const load = () => loadMixerContext({ payload, market, locale, user, draft });\n // Draft previews must reflect the latest save, so they are never cached.\n if (draft) {\n const context = await load();\n await setContext({ context });\n return context;\n }\n const cacheKey = getCacheKey({ market, locale, user, draft: 'false' });\n const context = await getMixerCacheState().cache.getOrSet(\n cacheKey,\n () => CONTEXT_CACHE_DURATION,\n () => {\n debug('getContext miss', cacheKey);\n return load();\n }\n );\n await setContext({ context });\n return context;\n}\n\nasync function loadMixerContext({\n payload,\n market,\n locale,\n user,\n draft,\n}: {\n payload: BasePayload;\n market: string;\n locale: string;\n user: User & Config['user'];\n draft: boolean;\n}): Promise<MixerContext> {\n const { localized } = getOptions({ locale, user, draft });\n // Independent reads: run them concurrently. Routes come from the route\n // store, which keeps pages and media in memory.\n const [localeResult, marketRequest, categoryRequest, routes] = await Promise.all([\n payload.findGlobal({\n ...localized,\n slug: 'locale',\n }) as Promise<{ items: ILocale[] }>,\n payload.find({\n ...localized,\n collection: 'market',\n }),\n payload.find({\n ...localized,\n collection: 'category',\n depth: 2,\n }),\n getRoutes({ payload, draft }),\n ]);\n const locales = localeResult.items.filter((x) => x.isActive) as unknown as ILocale[];\n const localeIds = locales.map((x) => x.id) as string[];\n const markets = marketRequest.docs.filter((x) => x.isActive) as unknown as IMarket[];\n const marketIds = markets.map((x) => x.id);\n const categories = categoryRequest.docs;\n const currentRoutes = filterRoutes(routes, market, locale);\n\n return {\n locale,\n localeIds,\n locales,\n market,\n marketIds,\n markets,\n routes,\n currentRoutes,\n categories: categories as unknown as MixerContext['categories'],\n richText: false,\n };\n}\n\n/**\n * Resolves a draft option to a boolean.\n * Defaults to `false`. `'auto'` is an explicit opt-in that reads Next's `draftMode()`\n * (a cookie read); outside a request scope (build, scripts) it resolves to false.\n * Prefer passing `(await draftMode()).isEnabled` from the template.\n */\nexport async function resolveDraft(draft: DraftOption = false): Promise<boolean> {\n if (typeof draft === 'boolean') {\n return draft;\n }\n try {\n return (await draftMode()).isEnabled;\n } catch {\n return false;\n }\n}\n\n/**\n * Runtime (request-time) payload accessor.\n *\n * By default, operates as the guest user for static generation. For auth:\n * call getHeaders() directly in your page/route/layout, then pass it here.\n * This function never reads request data itself: in draft mode pass the\n * request `headers` too, otherwise drafts are read as the guest user.\n *\n * Example:\n * const headers = await getHeaders();\n * const { payload, user, getContext } = await getPayload({ config, headers });\n */\nexport async function getPayload({\n config,\n headers,\n draft = false,\n}: {\n config: Promise<SanitizedConfig>;\n headers?: ReadonlyHeaders;\n draft?: boolean;\n}) {\n const payload = await getPayload_({ config });\n await setContext({ payload: payload as MixerPayload });\n\n let user: User & Config['user'] = guest;\n if (headers) {\n try {\n const auth = await payload.auth({ headers, canSetHeaders: false });\n if (auth.user) {\n user = auth.user as typeof user;\n }\n } catch (error) {\n console.log('getPayload.error', error);\n }\n }\n\n // Draft contexts bypass the shared cache, so share them at least between\n // the callers of this instance (one request when obtained per request).\n const contexts = new Map<string, Promise<MixerContext>>();\n return {\n payload: payload as MixerPayload,\n user,\n draft,\n getContext: (market: string, locale: string) => {\n const key = `${market}|${locale}`;\n let context = contexts.get(key);\n if (!context) {\n context = getMixerContext({ payload, market, locale, user, draft });\n contexts.set(key, context);\n context.catch(() => contexts.delete(key));\n }\n return context;\n },\n };\n}\n\nexport function filterRoutes(routes: IRoute[], market: string, locale: string): IRoute[] {\n market = market === 'all' ? defaultMarket : market;\n locale = locale === 'all' ? defaultLocale : locale;\n return routes.filter((x) => x.market === market && x.locale === locale);\n}\n\nexport function getAuthHeaders(token: { value: string } | undefined): Headers {\n if (token) {\n return new Headers({ Authorization: `JWT ${token.value}` });\n } else {\n return new Headers({ Authorization: `users API-Key ${process.env.STORE_API_KEY}` });\n }\n}\n\n/**\n * Produces the read options shared across payload.find / findByID / findGlobal calls.\n * For payload.find, add pagination: false and limit: 10000 at the call site.\n * `select`, `populate` and `joins` are only included when provided.\n */\nexport function buildReadOptions({\n user,\n locale,\n draft = false,\n depth,\n select,\n populate,\n joins,\n}: ReadOptions & {\n user: any;\n locale: string;\n}) {\n return {\n locale: locale as TypedLocale,\n fallbackLocale: defaultLocale as TypedFallbackLocale,\n draft,\n depth,\n // the logged in user or the guest: bowl decorates only reads with a user, as for the http api\n user: user || guest,\n overrideAccess: false,\n ...(select !== undefined ? { select } : {}),\n ...(populate !== undefined ? { populate } : {}),\n // joins are collection specific: typed by the caller's options, untyped here\n ...(joins !== undefined ? ({ joins } as {}) : {}),\n };\n}\n\n/**\n * @deprecated Use `buildReadOptions({ user, locale, draft, depth })`.\n * Kept for backward compatibility: reads at depth 0.\n */\nexport function buildBaseOptions(user: any, locale: string, draft?: boolean) {\n return buildReadOptions({ user, locale, draft, depth: 0 });\n}\n\n/**\n * Payload proxy example\n *\n *\n * import type { Payload, PayloadRequest } from '../types/index.js'\n\nimport { commitTransaction } from './commitTransaction.js'\nimport { initTransaction } from './initTransaction.js'\nimport { killTransaction } from './killTransaction.js'\n\nconst localOperations = [\n 'count',\n 'countGlobalVersions',\n 'countVersions',\n 'create',\n 'delete',\n 'duplicate',\n 'find',\n 'findByID',\n 'delete',\n 'duplicate',\n 'find',\n 'findByID',\n 'findGlobal',\n 'findGlobalVersionByID',\n 'findGlobalVersions',\n 'findVersionByID',\n 'findVersionByID',\n 'login',\n 'update',\n 'updateGlobal',\n 'restoreVersion',\n 'restoreGlobalVersion',\n] satisfies (keyof Payload)[]\n\ntype LocalOperation = (typeof localOperations)[number]\n\nconst isLocalOperation = (key: string): key is LocalOperation => {\n return localOperations.includes(key as LocalOperation)\n}\n\nexport const withTransaction = async <T>(\n payload: Payload,\n callback: (transaction: Payload) => Promise<T>,\n) => {\n const transactionReq = { payload } as PayloadRequest\n await initTransaction(transactionReq)\n\n const proxy = new Proxy(payload, {\n get(target, property: keyof Payload, receiver) {\n if (isLocalOperation(property)) {\n const operation = Reflect.get(target, property, receiver)\n\n return function (options) {\n let req: Partial<PayloadRequest> = options.req\n\n if (!req) {\n req = {}\n }\n\n if (!req.transactionID) {\n req = { ...req, transactionID: transactionReq.transactionID }\n }\n\n return (operation as (...args: unknown[]) => void)({\n ...options,\n req,\n })\n }\n }\n\n return Reflect.get(target, property, receiver)\n },\n })\n\n try {\n const result = await callback(proxy)\n await commitTransaction(transactionReq)\n return result\n } catch (e) {\n await killTransaction(transactionReq)\n throw e\n }\n}\n\n// -----------------\n\nconst { one, two } = await withTransaction(payload, async (transaction) => {\n const one = await transaction.create({ collection: 'posts', data: { title: 'one' } })\n const two = await transaction.create({ collection: 'posts', data: { title: 'two' } })\n\n return { one, two }\n})\n\n */\n"],"mappings":";;;;;;;;;AA0CA,MAAM,0BACH,QAAQ,IAAI,wBAAwB,SAAS,QAAQ,IAAI,sBAAsB,GAAG,OAAU;AAC/F,MAAM,oBAAoB;AAO1B,MAAM,2BAA4C;CAGhD,MAAM,iBAAiB;AACvB,KAAI,CAAC,eAAe,iBAClB,gBAAe,mBAAmB,EAAE,OAAO,IAAI,SAAuB,kBAAkB,EAAE;CAE5F,MAAM,QAAQ,eAAe;AAC7B,KAA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UAAS,WAAW,QAAQ,gBAAgB;AAC5C,QAAO,OAAO,QAAQ,MAAM,EAAE,WAAW,UAAU,EAAE,WAAW,OAAO;;AAGzE,SAAgB,eAAe,OAA+C;AAC5E,KAAI,MACF,QAAO,IAAI,QAAQ,EAAE,eAAe,OAAO,MAAM,SAAS,CAAC;KAE3D,QAAO,IAAI,QAAQ,EAAE,eAAe,iBAAiB,QAAQ,IAAI,iBAAiB,CAAC;;;;;;;AASvF,SAAgB,iBAAiB,EAC/B,MACA,QACA,QAAQ,OACR,OACA,QACA,UACA,SAIC;AACD,QAAO;EACG;EACR,gBAAgB;EAChB;EACA;EAEA,MAAM,QAAQ;EACd,gBAAgB;EAChB,GAAI,WAAW,KAAA,IAAY,EAAE,QAAQ,GAAG,EAAE;EAC1C,GAAI,aAAa,KAAA,IAAY,EAAE,UAAU,GAAG,EAAE;EAE9C,GAAI,UAAU,KAAA,IAAa,EAAE,OAAO,GAAU,EAAE;EACjD;;;;;;AAOH,SAAgB,iBAAiB,MAAW,QAAgB,OAAiB;AAC3E,QAAO,iBAAiB;EAAE;EAAM;EAAQ;EAAO,OAAO;EAAG,CAAC"}
1
+ {"version":3,"file":"mixer.js","names":["getPayload_","getRoutes","getPayload"],"sources":["../../src/server/mixer.ts"],"sourcesContent":["import {\n defaultLocale,\n defaultMarket,\n ILocale,\n IMarket,\n IRoute,\n isObject,\n} from '@websolutespa/bom-core';\nimport type { Config, User } from '@websolutespa/payload-plugin-bowl';\nimport {\n getRouteStore,\n getRouteStoreDraftRoutes,\n getRouteStoreRoutes,\n onRouteStoreChange,\n} from '@websolutespa/payload-plugin-bowl';\nimport { draftMode } from 'next/headers';\nimport { NextRequest } from 'next/server';\nimport {\n BasePayload,\n getPayload as getPayload_,\n Payload,\n SanitizedConfig,\n TypedFallbackLocale,\n TypedLocale,\n} from 'payload';\nimport { cache } from 'react';\nimport { guest, PREVIEW_ROLES, previewer } from '../lib/const';\nimport { debug } from '../lib/debug';\nimport { TtlCache } from '../lib/ttl-cache';\nimport type {\n BaseOptions,\n DraftOption,\n IContext,\n MixerContext,\n ReadOptions,\n ReadonlyHeaders,\n} from '../types';\nimport type { MixerPayload } from './mixer-payload';\n\n// Context entries live for MEMORY_CACHE_DURATION seconds (default 300) and\n// are dropped as soon as the Bowl route store reports a change, locally or\n// from another instance through Redis.\nconst CONTEXT_CACHE_DURATION =\n (process.env.MEMORY_CACHE_DURATION ? parseInt(process.env.MEMORY_CACHE_DURATION) : 5 * 60) * 1000;\nconst CONTEXT_CACHE_MAX = 500;\n\ntype MixerCacheState = {\n cache: TtlCache<MixerContext>;\n subscribed?: boolean;\n};\n\nconst getMixerCacheState = (): MixerCacheState => {\n // A new global key: `_mixer` held an InMemoryCache in earlier versions and\n // can survive a dev hot reload with that shape.\n const globalForMixer = globalThis as typeof globalThis & { _bomMixerContext?: MixerCacheState };\n if (!globalForMixer._bomMixerContext) {\n globalForMixer._bomMixerContext = { cache: new TtlCache<MixerContext>(CONTEXT_CACHE_MAX) };\n }\n const state = globalForMixer._bomMixerContext;\n if (!state.subscribed) {\n state.subscribed = true;\n onRouteStoreChange(() => state.cache.clear());\n }\n return state;\n};\n\n/** Drops every cached mixer context on this instance. */\nexport function clearMixerContextCache() {\n getMixerCacheState().cache.clear();\n}\n\nexport function getCacheKey({\n market = 'all',\n locale = 'all',\n user = guest,\n draft = 'false',\n}: {\n market?: string;\n locale?: string;\n user?: User & Config['user'];\n draft?: string;\n}) {\n const roles = (user?.roles || ['guest']) as string[];\n const tenants = (\n 'tenants' in user && Array.isArray(user.tenants)\n ? user.tenants.map((x: any) => (isObject(x) ? x.id : x))\n : []\n ) as string[];\n roles.sort();\n tenants.sort();\n const keys = [market, locale, draft === 'false' ? 'published' : 'draft', ...roles, ...tenants];\n const key = `context-${keys.join('-')}`;\n return key;\n}\n\nexport async function getContext() {\n let context: IContext | undefined = (globalThis as any)._context;\n if (!context) {\n context = {\n payload: undefined,\n context: undefined,\n } as unknown as IContext;\n (globalThis as any)._context = context;\n }\n return context;\n}\n\nexport async function setContext(data: Partial<IContext>) {\n const context = await getContext();\n if (data.payload) {\n context.payload = data.payload;\n }\n if (data.context) {\n context.context = data.context;\n }\n}\n\nexport function getSearchParams(request: NextRequest) {\n const searchParams = request.nextUrl.searchParams;\n const params = Object.fromEntries(searchParams.entries());\n return {\n market: params.market || defaultMarket,\n locale: params.locale || defaultLocale,\n defaultMarket,\n defaultLocale,\n params,\n searchParams: request.nextUrl.searchParams,\n };\n}\n\nexport const getPayloadInstance = cache(\n async (props: { config: SanitizedConfig | Promise<SanitizedConfig> }) => await getPayload_(props)\n);\n\nexport function getOptions({\n locale = 'all',\n user = guest,\n draft = false,\n}: {\n locale?: string;\n user?: User & Config['user'];\n draft?: boolean;\n}) {\n const localized: BaseOptions = {\n locale: locale as TypedLocale,\n fallbackLocale: defaultLocale as TypedLocale,\n draft,\n depth: 0,\n pagination: false,\n limit: 10000,\n user,\n overrideAccess: false,\n };\n const unlocalized: BaseOptions = {\n locale: 'all',\n fallbackLocale: defaultLocale as TypedLocale,\n draft,\n depth: 0,\n pagination: false,\n limit: 10000,\n user,\n overrideAccess: false,\n };\n return { localized, unlocalized };\n}\n\n/**\n * Returns all routes from the Bowl route store: published routes, or the\n * published routes overlaid with draft pages when `draft` is true.\n *\n * The route store is Guest-readable by design (see payload-plugin-bowl's\n * \"Route Resolution\"), so `market`, `locale` and `user` no longer change the\n * result; they are kept for backward compatibility.\n */\nexport async function getRoutes({\n payload,\n draft = false,\n}: {\n payload: BasePayload;\n market?: string;\n locale?: string;\n user?: User & Config['user'];\n draft?: boolean;\n}): Promise<IRoute[]> {\n const store = await getRouteStore(payload as Payload);\n return draft ? getRouteStoreDraftRoutes(payload as Payload, store) : getRouteStoreRoutes(store);\n}\n\nexport async function getMixerContext({\n payload,\n market,\n locale,\n user = guest,\n draft = false,\n}: {\n payload: BasePayload;\n market: string;\n locale: string;\n user?: User & Config['user'];\n draft?: boolean;\n}): Promise<MixerContext> {\n const load = () => loadMixerContext({ payload, market, locale, user, draft });\n // Draft previews must reflect the latest save, so they are never cached.\n if (draft) {\n const context = await load();\n await setContext({ context });\n return context;\n }\n const cacheKey = getCacheKey({ market, locale, user, draft: 'false' });\n const context = await getMixerCacheState().cache.getOrSet(\n cacheKey,\n () => CONTEXT_CACHE_DURATION,\n () => {\n debug('getContext miss', cacheKey);\n return load();\n }\n );\n await setContext({ context });\n return context;\n}\n\nasync function loadMixerContext({\n payload,\n market,\n locale,\n user,\n draft,\n}: {\n payload: BasePayload;\n market: string;\n locale: string;\n user: User & Config['user'];\n draft: boolean;\n}): Promise<MixerContext> {\n const { localized } = getOptions({ locale, user, draft });\n // Independent reads: run them concurrently. Routes come from the route\n // store, which keeps pages and media in memory.\n const [localeResult, marketRequest, categoryRequest, routes] = await Promise.all([\n payload.findGlobal({\n ...localized,\n slug: 'locale',\n }) as Promise<{ items: ILocale[] }>,\n payload.find({\n ...localized,\n collection: 'market',\n }),\n payload.find({\n ...localized,\n collection: 'category',\n depth: 2,\n }),\n getRoutes({ payload, draft }),\n ]);\n const locales = localeResult.items.filter((x) => x.isActive) as unknown as ILocale[];\n const localeIds = locales.map((x) => x.id) as string[];\n const markets = marketRequest.docs.filter((x) => x.isActive) as unknown as IMarket[];\n const marketIds = markets.map((x) => x.id);\n const categories = categoryRequest.docs;\n const currentRoutes = filterRoutes(routes, market, locale);\n\n return {\n locale,\n localeIds,\n locales,\n market,\n marketIds,\n markets,\n routes,\n currentRoutes,\n categories: categories as unknown as MixerContext['categories'],\n richText: false,\n };\n}\n\n/** Whether the user has an editing role, the ones Bowl serves drafts to. */\nfunction hasPreviewRole(user: User | null | undefined): boolean {\n const roles = ((user as { roles?: string[] } | null)?.roles ?? []) as string[];\n return roles.some((role) => PREVIEW_ROLES.includes(role));\n}\n\n/**\n * Resolves a draft option to a boolean.\n * Defaults to `false`. `'auto'` is an explicit opt-in that reads Next's `draftMode()`\n * (a cookie read); outside a request scope (build, scripts) it resolves to false.\n * Prefer passing `(await draftMode()).isEnabled` from the template.\n */\nexport async function resolveDraft(draft: DraftOption = false): Promise<boolean> {\n if (typeof draft === 'boolean') {\n return draft;\n }\n try {\n return (await draftMode()).isEnabled;\n } catch {\n return false;\n }\n}\n\n/**\n * Runtime (request-time) payload accessor.\n *\n * By default, operates as the guest user for static generation. For auth:\n * call getHeaders() directly in your page/route/layout, then pass it here.\n * This function never reads request data itself: in draft mode pass the\n * request `headers` too, otherwise drafts are read as the guest user.\n *\n * Example:\n * const headers = await getHeaders();\n * const { payload, user, getContext } = await getPayload({ config, headers });\n */\nexport async function getPayload({\n config,\n headers,\n draft: requestedDraft = false,\n}: {\n config: Promise<SanitizedConfig>;\n headers?: ReadonlyHeaders;\n draft?: boolean;\n}) {\n const payload = await getPayload_({ config });\n await setContext({ payload: payload as MixerPayload });\n\n let user: User & Config['user'] = guest;\n if (headers) {\n try {\n const auth = await payload.auth({ headers, canSetHeaders: false });\n if (auth.user) {\n user = auth.user as typeof user;\n }\n } catch (error) {\n console.log('getPayload.error', error);\n }\n }\n\n // a draft read as a non-editor: the previewer identity while Draft Mode is on (an editor turned it on, see\n // getPreviewHandler), the published site otherwise. Bowl serves drafts to the editing roles only.\n let draft = requestedDraft;\n if (draft && !hasPreviewRole(user)) {\n // only an actual Draft Mode request: the cookie read happens on the draft path alone, which is dynamic anyway\n draft = await resolveDraft('auto');\n if (draft) {\n user = previewer;\n }\n }\n\n // Draft contexts bypass the shared cache, so share them at least between\n // the callers of this instance (one request when obtained per request).\n const contexts = new Map<string, Promise<MixerContext>>();\n return {\n payload: payload as MixerPayload,\n user,\n draft,\n getContext: (market: string, locale: string) => {\n const key = `${market}|${locale}`;\n let context = contexts.get(key);\n if (!context) {\n context = getMixerContext({ payload, market, locale, user, draft });\n contexts.set(key, context);\n context.catch(() => contexts.delete(key));\n }\n return context;\n },\n };\n}\n\nexport function filterRoutes(routes: IRoute[], market: string, locale: string): IRoute[] {\n market = market === 'all' ? defaultMarket : market;\n locale = locale === 'all' ? defaultLocale : locale;\n return routes.filter((x) => x.market === market && x.locale === locale);\n}\n\nexport function getAuthHeaders(token: { value: string } | undefined): Headers {\n if (token) {\n return new Headers({ Authorization: `JWT ${token.value}` });\n } else {\n return new Headers({ Authorization: `users API-Key ${process.env.STORE_API_KEY}` });\n }\n}\n\n/**\n * Produces the read options shared across payload.find / findByID / findGlobal calls.\n * For payload.find, add pagination: false and limit: 10000 at the call site.\n * `select`, `populate` and `joins` are only included when provided.\n */\nexport function buildReadOptions({\n user,\n locale,\n draft = false,\n depth,\n select,\n populate,\n joins,\n}: ReadOptions & {\n user: any;\n locale: string;\n}) {\n return {\n locale: locale as TypedLocale,\n fallbackLocale: defaultLocale as TypedFallbackLocale,\n draft,\n depth,\n // the logged in user or the guest: bowl decorates only reads with a user, as for the http api\n user: user || guest,\n overrideAccess: false,\n ...(select !== undefined ? { select } : {}),\n ...(populate !== undefined ? { populate } : {}),\n // joins are collection specific: typed by the caller's options, untyped here\n ...(joins !== undefined ? ({ joins } as {}) : {}),\n };\n}\n\n/**\n * @deprecated Use `buildReadOptions({ user, locale, draft, depth })`.\n * Kept for backward compatibility: reads at depth 0.\n */\nexport function buildBaseOptions(user: any, locale: string, draft?: boolean) {\n return buildReadOptions({ user, locale, draft, depth: 0 });\n}\n\n/**\n * Payload proxy example\n *\n *\n * import type { Payload, PayloadRequest } from '../types/index.js'\n\nimport { commitTransaction } from './commitTransaction.js'\nimport { initTransaction } from './initTransaction.js'\nimport { killTransaction } from './killTransaction.js'\n\nconst localOperations = [\n 'count',\n 'countGlobalVersions',\n 'countVersions',\n 'create',\n 'delete',\n 'duplicate',\n 'find',\n 'findByID',\n 'delete',\n 'duplicate',\n 'find',\n 'findByID',\n 'findGlobal',\n 'findGlobalVersionByID',\n 'findGlobalVersions',\n 'findVersionByID',\n 'findVersionByID',\n 'login',\n 'update',\n 'updateGlobal',\n 'restoreVersion',\n 'restoreGlobalVersion',\n] satisfies (keyof Payload)[]\n\ntype LocalOperation = (typeof localOperations)[number]\n\nconst isLocalOperation = (key: string): key is LocalOperation => {\n return localOperations.includes(key as LocalOperation)\n}\n\nexport const withTransaction = async <T>(\n payload: Payload,\n callback: (transaction: Payload) => Promise<T>,\n) => {\n const transactionReq = { payload } as PayloadRequest\n await initTransaction(transactionReq)\n\n const proxy = new Proxy(payload, {\n get(target, property: keyof Payload, receiver) {\n if (isLocalOperation(property)) {\n const operation = Reflect.get(target, property, receiver)\n\n return function (options) {\n let req: Partial<PayloadRequest> = options.req\n\n if (!req) {\n req = {}\n }\n\n if (!req.transactionID) {\n req = { ...req, transactionID: transactionReq.transactionID }\n }\n\n return (operation as (...args: unknown[]) => void)({\n ...options,\n req,\n })\n }\n }\n\n return Reflect.get(target, property, receiver)\n },\n })\n\n try {\n const result = await callback(proxy)\n await commitTransaction(transactionReq)\n return result\n } catch (e) {\n await killTransaction(transactionReq)\n throw e\n }\n}\n\n// -----------------\n\nconst { one, two } = await withTransaction(payload, async (transaction) => {\n const one = await transaction.create({ collection: 'posts', data: { title: 'one' } })\n const two = await transaction.create({ collection: 'posts', data: { title: 'two' } })\n\n return { one, two }\n})\n\n */\n"],"mappings":";;;;;;;;;AA0CA,MAAM,0BACH,QAAQ,IAAI,wBAAwB,SAAS,QAAQ,IAAI,sBAAsB,GAAG,OAAU;AAC/F,MAAM,oBAAoB;AAO1B,MAAM,2BAA4C;CAGhD,MAAM,iBAAiB;AACvB,KAAI,CAAC,eAAe,iBAClB,gBAAe,mBAAmB,EAAE,OAAO,IAAI,SAAuB,kBAAkB,EAAE;CAE5F,MAAM,QAAQ,eAAe;AAC7B,KAAI,CAAC,MAAM,YAAY;AACrB,QAAM,aAAa;AACnB,2BAAyB,MAAM,MAAM,OAAO,CAAC;;AAE/C,QAAO;;;AAIT,SAAgB,yBAAyB;AACvC,qBAAoB,CAAC,MAAM,OAAO;;AAGpC,SAAgB,YAAY,EAC1B,SAAS,OACT,SAAS,OACT,OAAO,OACP,QAAQ,WAMP;CACD,MAAM,QAAS,MAAM,SAAS,CAAC,QA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C5C,QAAO,OAAO,QAAQ,MAAM,EAAE,WAAW,UAAU,EAAE,WAAW,OAAO;;AAGzE,SAAgB,eAAe,OAA+C;AAC5E,KAAI,MACF,QAAO,IAAI,QAAQ,EAAE,eAAe,OAAO,MAAM,SAAS,CAAC;KAE3D,QAAO,IAAI,QAAQ,EAAE,eAAe,iBAAiB,QAAQ,IAAI,iBAAiB,CAAC;;;;;;;AASvF,SAAgB,iBAAiB,EAC/B,MACA,QACA,QAAQ,OACR,OACA,QACA,UACA,SAIC;AACD,QAAO;EACG;EACR,gBAAgB;EAChB;EACA;EAEA,MAAM,QAAQ;EACd,gBAAgB;EAChB,GAAI,WAAW,KAAA,IAAY,EAAE,QAAQ,GAAG,EAAE;EAC1C,GAAI,aAAa,KAAA,IAAY,EAAE,UAAU,GAAG,EAAE;EAE9C,GAAI,UAAU,KAAA,IAAa,EAAE,OAAO,GAAU,EAAE;EACjD;;;;;;AAOH,SAAgB,iBAAiB,MAAW,QAAgB,OAAiB;AAC3E,QAAO,iBAAiB;EAAE;EAAM;EAAQ;EAAO,OAAO;EAAG,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@websolutespa/bom-next",
3
- "version": "4.0.0-next.12",
3
+ "version": "4.0.0-next.13",
4
4
  "description": "Next module of the BOM Repository",
5
5
  "keywords": [
6
6
  "bom",
@@ -47,7 +47,7 @@
47
47
  "@websolutespa/bom-cli": "^4.0.0-next.11",
48
48
  "@websolutespa/bom-core": "^4.0.0-next.10",
49
49
  "@websolutespa/oxc": "^4.0.0-next.10",
50
- "@websolutespa/payload-plugin-bowl": "^4.0.0-next.11",
50
+ "@websolutespa/payload-plugin-bowl": "^4.0.0-next.12",
51
51
  "@websolutespa/payload-utils": "^4.0.0-next.10",
52
52
  "@websolutespa/test": "^4.0.0-next.10",
53
53
  "@websolutespa/tsconfig": "^4.0.0-next.10",
@@ -17,8 +17,9 @@ export const UserContext = createContext<UserContextType>({
17
17
  },
18
18
  });
19
19
 
20
- // One `/auth/me` request per browser session, shared by every UserProvider
21
- // mount; `setUser` and `invalidateUser` keep it current after login/logout.
20
+ // One `/auth/me` request per page load, shared by every UserProvider mount and client navigation;
21
+ // `setUser` and `invalidateUser` keep it current after login/logout. Not persisted (sessionStorage): a stored user
22
+ // would go stale after a logout or login in another tab. Pass `initialUser` where the server knows the user.
22
23
  let mePromise: Promise<UserValue> | undefined;
23
24
 
24
25
  function getMe(): Promise<UserValue> {
package/src/lib/const.ts CHANGED
@@ -2,6 +2,16 @@ import type { Config, User } from '@websolutespa/payload-plugin-bowl';
2
2
 
3
3
  export const guest = { collection: 'users', roles: ['guest'] } as User & Config['user'];
4
4
 
5
+ /** Roles that read drafts and may turn Draft Mode on: Bowl's editing roles (`rolesUser`). */
6
+ export const PREVIEW_ROLES = ['admin', 'contributor', 'editor'];
7
+
8
+ /**
9
+ * The reader of Draft Mode renders without an editor session (static templates pass no headers; the admin may run
10
+ * on another origin). Draft Mode is turned on only for editors (`getPreviewHandler`) and Bowl serves drafts to the
11
+ * editing roles only, so these reads use an editing role. `getPayload` uses it only while Next.js Draft Mode is on.
12
+ */
13
+ export const previewer = { collection: 'users', roles: ['editor'] } as User & Config['user'];
14
+
5
15
  /**
6
16
  * Default population depth for page documents read by `createPageContext`.
7
17
  *
@@ -1,7 +1,7 @@
1
1
  // @vitest-environment node
2
2
 
3
3
  import type { ILayout, IPage } from '@websolutespa/bom-core';
4
- import { describe, expect, test } from 'vitest';
4
+ import { afterEach, beforeEach, describe, expect, test } from 'vitest';
5
5
  import {
6
6
  buildPageMetadata,
7
7
  getPaginationQuery,
@@ -56,6 +56,38 @@ describe('getPaginationQuery', () => {
56
56
  });
57
57
 
58
58
  describe('buildPageMetadata', () => {
59
+ // the page's own robots apply in production; elsewhere every page is noindex (tested below)
60
+ beforeEach(() => {
61
+ process.env.PRODUCTION = 'true';
62
+ });
63
+ afterEach(() => {
64
+ delete process.env.PRODUCTION;
65
+ delete process.env.NOINDEX;
66
+ });
67
+
68
+ test('is noindex outside production, with NOINDEX=true, or when not indexable', () => {
69
+ const indexed = { ...page, meta: { robots: 'index, follow' } } as unknown as IPage;
70
+ expect(buildPageMetadata(indexed, layout, { baseUrl }).robots).toBe('index, follow');
71
+ expect(buildPageMetadata(indexed, layout, { baseUrl, indexable: false }).robots).toBe(
72
+ 'noindex, nofollow'
73
+ );
74
+ expect(
75
+ buildPageMetadata(indexed, layout, {
76
+ baseUrl,
77
+ indexable: (item) => item.title !== page.title,
78
+ }).robots
79
+ ).toBe('noindex, nofollow');
80
+ process.env.NOINDEX = 'true';
81
+ expect(buildPageMetadata(indexed, layout, { baseUrl }).robots).toBe('noindex, nofollow');
82
+ delete process.env.NOINDEX;
83
+ delete process.env.PRODUCTION;
84
+ expect(buildPageMetadata(indexed, layout, { baseUrl }).robots).toBe('noindex, nofollow');
85
+ // an explicit decision wins over the deployment policy
86
+ expect(buildPageMetadata(indexed, layout, { baseUrl, indexable: true }).robots).toBe(
87
+ 'index, follow'
88
+ );
89
+ });
90
+
59
91
  test('builds title, description, canonical, hreflang, robots and social tags', () => {
60
92
  const metadata = buildPageMetadata(page, layout, {
61
93
  baseUrl,
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  defaultLocale,
3
3
  defaultMarket,
4
+ getIsProduction,
4
5
  getMetaRobots,
5
6
  ILayout,
6
7
  IMedia,
@@ -36,10 +37,24 @@ export type PageMetadataOptions = {
36
37
  baseUrl?: string;
37
38
  /** Request search params; `pagination[page]` > 1 is kept in the canonical URL. */
38
39
  searchParams?: PageMetadataSearchParams;
40
+ /**
41
+ * Whether search engines may index the page. When false (or a function returning false), `robots` is
42
+ * `noindex, nofollow`, over the page's own `meta.robots`. Default: {@link isIndexableDeployment}, so staging
43
+ * and preview deployments are never indexed.
44
+ */
45
+ indexable?: boolean | ((page: IPage) => boolean);
39
46
  /** Per-page override applied to the computed metadata. */
40
47
  extend?: (metadata: Metadata, context: PageMetadataContext) => Metadata;
41
48
  };
42
49
 
50
+ /**
51
+ * The deployment policy: pages are indexable only in production (`PRODUCTION=true`, as the BOM 3 `Meta` component
52
+ * required) and unless `NOINDEX=true`. Every other deployment (staging, previews, local) is `noindex`.
53
+ */
54
+ export function isIndexableDeployment(env: NodeJS.ProcessEnv = process.env): boolean {
55
+ return getIsProduction() && env.NOINDEX !== 'true';
56
+ }
57
+
43
58
  type PageMetaFields = {
44
59
  title?: string;
45
60
  description?: string;
@@ -194,7 +209,11 @@ export function buildPageMetadata(
194
209
  const canonical = canonicalBase
195
210
  ? `${canonicalBase}${getPaginationQuery(options.searchParams)}`
196
211
  : undefined;
197
- const robots = getMetaRobots(meta);
212
+ const indexable =
213
+ typeof options.indexable === 'function'
214
+ ? options.indexable(page)
215
+ : (options.indexable ?? isIndexableDeployment());
216
+ const robots = indexable ? getMetaRobots(meta) : 'noindex, nofollow';
198
217
 
199
218
  const languages: Record<string, string> = {};
200
219
  if (layout) {
@@ -0,0 +1,92 @@
1
+ // @vitest-environment node
2
+
3
+ import { NextRequest } from 'next/server';
4
+ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
5
+
6
+ const enable = vi.fn();
7
+ vi.mock('next/headers', () => ({ draftMode: async () => ({ enable, isEnabled: false }) }));
8
+
9
+ // the users the mocked Payload knows, by Authorization header or cookie
10
+ const sessions: Record<string, { roles: string[] }> = {
11
+ 'JWT editor-token': { roles: ['editor'] },
12
+ 'JWT user-token': { roles: ['user'] },
13
+ 'payload-token=admin-cookie': { roles: ['admin'] },
14
+ };
15
+ vi.mock('payload', () => ({
16
+ getPayload: async () => ({
17
+ auth: async ({ headers }: { headers: Headers }) => ({
18
+ user:
19
+ sessions[headers.get('authorization') ?? ''] ??
20
+ sessions[headers.get('cookie') ?? ''] ??
21
+ null,
22
+ }),
23
+ }),
24
+ }));
25
+
26
+ const { getPreviewHandler, previewHandler } = await import('./preview.handler');
27
+
28
+ const page = 'marketId=ww&localeId=en&templateId=contact&documentId=6a6b33177d8f191df34b33a3';
29
+ const request = (query: string, headers: Record<string, string> = {}) =>
30
+ new NextRequest(`http://localhost:3000/api/-preview?${query}`, { headers });
31
+ const handler = getPreviewHandler(Promise.resolve({} as never));
32
+
33
+ beforeEach(() => {
34
+ process.env.NEXT_PUBLIC_URL = 'http://localhost:3000';
35
+ process.env.MIXER_SECRET = 'mixer-secret';
36
+ enable.mockClear();
37
+ });
38
+
39
+ afterEach(() => {
40
+ delete process.env.MIXER_SECRET;
41
+ });
42
+
43
+ describe('getPreviewHandler', () => {
44
+ test('refuses an anonymous visitor and sets no Draft Mode cookie', async () => {
45
+ const res = await handler(request(page));
46
+ expect(res.status).toBe(401);
47
+ expect(enable).not.toHaveBeenCalled();
48
+ });
49
+
50
+ test('refuses a logged-in visitor without an editing role, and an invalid token', async () => {
51
+ expect((await handler(request(page, { authorization: 'JWT user-token' }))).status).toBe(401);
52
+ expect((await handler(request(`${page}&_token=forged`))).status).toBe(401);
53
+ expect(enable).not.toHaveBeenCalled();
54
+ });
55
+
56
+ test('lets an editor in through the admin session cookie or the _token of the preview URL', async () => {
57
+ const byCookie = await handler(request(page, { cookie: 'payload-token=admin-cookie' }));
58
+ expect(byCookie.status).toBe(303);
59
+ expect(byCookie.headers.get('location')).toBe(
60
+ 'http://localhost:3000/ww/en/contact/6a6b33177d8f191df34b33a3'
61
+ );
62
+ const byToken = await handler(request(`${page}&_token=editor-token&_live=true`));
63
+ expect(byToken.status).toBe(303);
64
+ expect(byToken.headers.get('location')).toMatch(/\?_live=true$/);
65
+ expect(enable).toHaveBeenCalledTimes(2);
66
+ });
67
+
68
+ test('accepts MIXER_SECRET, never an empty one', async () => {
69
+ expect((await handler(request(`${page}&secret=mixer-secret`))).status).toBe(303);
70
+ delete process.env.MIXER_SECRET;
71
+ expect((await handler(request(`${page}&secret=`))).status).toBe(401);
72
+ });
73
+
74
+ test('keeps the redirect on this site', async () => {
75
+ const res = await handler(
76
+ request('marketId=ww&localeId=en&templateId=..%2F%2Fevil.com&documentId=1', {
77
+ cookie: 'payload-token=admin-cookie',
78
+ })
79
+ );
80
+ expect(res.status).toBe(400);
81
+ expect(enable).not.toHaveBeenCalled();
82
+ });
83
+ });
84
+
85
+ describe('previewHandler (deprecated)', () => {
86
+ test('turns Draft Mode on only with MIXER_SECRET', async () => {
87
+ expect(
88
+ (await previewHandler(request(page, { cookie: 'payload-token=admin-cookie' }))).status
89
+ ).toBe(401);
90
+ expect((await previewHandler(request(`${page}&secret=mixer-secret`))).status).toBe(303);
91
+ });
92
+ });
@@ -1,63 +1,95 @@
1
1
  import { draftMode } from 'next/headers';
2
2
  import { NextRequest, NextResponse } from 'next/server';
3
+ import { getPayload, SanitizedConfig } from 'payload';
4
+ import { PREVIEW_ROLES } from '../../lib/const';
3
5
 
4
6
  // http://localhost:3000/api/-preview?marketId=ww&localeId=it&templateId=homepage&documentId=6a6b33177d8f191df34b33a3
5
7
 
6
- export async function previewHandler(request: NextRequest) {
7
- const { searchParams } = new URL(request.url);
8
- const params = Object.fromEntries(searchParams) as {
9
- marketId: string;
10
- localeId: string;
11
- templateId: string;
12
- documentId: string;
13
- _status: 'published' | 'draft';
14
- _live: string;
15
- _token: string;
16
- };
17
- /*
18
- if (params.secret !== process.env.MIXER_SECRET) {
19
- return new Response('Invalid token', { status: 401 })
8
+ export { PREVIEW_ROLES };
9
+
10
+ type PreviewParams = {
11
+ marketId?: string;
12
+ localeId?: string;
13
+ templateId?: string;
14
+ documentId?: string;
15
+ _live?: string;
16
+ /** the editor's token, added by Bowl to the admin's preview URL */
17
+ _token?: string;
18
+ /** `MIXER_SECRET`, for a caller without an editor session */
19
+ secret?: string;
20
+ };
21
+
22
+ // path segments only: the destination stays on this site
23
+ const SEGMENT = /^[\w-]+$/;
24
+
25
+ function hasSecret(params: PreviewParams): boolean {
26
+ return Boolean(process.env.MIXER_SECRET) && params.secret === process.env.MIXER_SECRET;
27
+ }
28
+
29
+ /** Turns Draft Mode on and redirects to the internal page path. */
30
+ async function enablePreview(params: PreviewParams): Promise<Response> {
31
+ const { marketId, localeId, templateId, documentId, _live } = params;
32
+ if (
33
+ ![marketId, localeId, templateId, documentId].every((value) => value && SEGMENT.test(value))
34
+ ) {
35
+ return new Response('Bad Request', { status: 400 });
20
36
  }
21
- */
22
- /*
23
- const headersList = await headers()
24
- const userAgent = headersList.get('user-agent')
25
- */
26
- const { marketId, localeId, templateId, documentId, _status, _live } = params;
27
37
  const destination = `/${marketId}/${localeId}/${templateId}/${documentId}${_live ? '?_live=true' : ''}`;
28
- /*
29
- response.setPreviewData({ _status });
30
- response.setDraftMode({ enable: true });
31
- response.redirect(307, destination);
32
- redirect(destination, RedirectType.replace);
33
- */
34
38
  const draft = await draftMode();
35
39
  draft.enable();
36
- const path = `${process.env.NEXT_PUBLIC_URL}${destination}`;
37
- return NextResponse.redirect(path, {
38
- status: 303,
39
- });
40
- /*
41
- return NextResponse.redirect(path, {
42
- status: 303,
43
- });
44
- */
45
- /*
46
- return new Response(null, {
47
- status: 303,
48
- headers: {
49
- Location: path,
50
- },
51
- });
52
- */
53
- /*
54
- redirect(path);
55
- return;
56
- */
57
- /*
58
- return NextResponse.json({
59
- destination: destination,
60
- permanent: false
61
- });
62
- */
40
+ return NextResponse.redirect(`${process.env.NEXT_PUBLIC_URL}${destination}`, { status: 303 });
41
+ }
42
+
43
+ /**
44
+ * The `/api/-preview` route: turns Draft Mode on for an editor and redirects to the page. Draft Mode shows
45
+ * unpublished content (bom-next reads it with an editing role), so only these callers get the cookie:
46
+ * - a logged-in editor: the admin session cookie (admin and site on one origin), or the `_token` Bowl adds to
47
+ * the admin's preview URL (admin on another origin);
48
+ * - `secret` equal to `MIXER_SECRET`.
49
+ * Everyone else gets 401 and no cookie.
50
+ *
51
+ * ```ts
52
+ * // src/app/api/-preview/route.ts
53
+ * export const GET = getPreviewHandler(config);
54
+ * ```
55
+ */
56
+ export function getPreviewHandler(
57
+ config: Promise<SanitizedConfig>,
58
+ { roles = PREVIEW_ROLES }: { roles?: string[] } = {}
59
+ ) {
60
+ return async function (request: NextRequest): Promise<Response> {
61
+ const params = Object.fromEntries(request.nextUrl.searchParams) as PreviewParams;
62
+ if (!hasSecret(params)) {
63
+ const payload = await getPayload({ config });
64
+ const isEditor = async (headers: Headers) => {
65
+ try {
66
+ const { user } = await payload.auth({ headers });
67
+ const userRoles = (user as { roles?: string[] } | null)?.roles ?? [];
68
+ return userRoles.some((role) => roles.includes(role));
69
+ } catch {
70
+ return false;
71
+ }
72
+ };
73
+ const allowed =
74
+ (await isEditor(request.headers)) ||
75
+ (Boolean(params._token) &&
76
+ (await isEditor(new Headers({ authorization: `JWT ${params._token}` }))));
77
+ if (!allowed) {
78
+ return new Response('Unauthorized', { status: 401 });
79
+ }
80
+ }
81
+ return enablePreview(params);
82
+ };
83
+ }
84
+
85
+ /**
86
+ * @deprecated Use `getPreviewHandler(config)`, which also accepts an editor session. Without the config this
87
+ * handler cannot authenticate a user, so it turns Draft Mode on only with `secret` equal to `MIXER_SECRET`.
88
+ */
89
+ export async function previewHandler(request: NextRequest): Promise<Response> {
90
+ const params = Object.fromEntries(request.nextUrl.searchParams) as PreviewParams;
91
+ if (!hasSecret(params)) {
92
+ return new Response('Unauthorized', { status: 401 });
93
+ }
94
+ return enablePreview(params);
63
95
  }
@@ -24,7 +24,7 @@ import {
24
24
  TypedLocale,
25
25
  } from 'payload';
26
26
  import { cache } from 'react';
27
- import { guest } from '../lib/const';
27
+ import { guest, PREVIEW_ROLES, previewer } from '../lib/const';
28
28
  import { debug } from '../lib/debug';
29
29
  import { TtlCache } from '../lib/ttl-cache';
30
30
  import type {
@@ -272,6 +272,12 @@ async function loadMixerContext({
272
272
  };
273
273
  }
274
274
 
275
+ /** Whether the user has an editing role, the ones Bowl serves drafts to. */
276
+ function hasPreviewRole(user: User | null | undefined): boolean {
277
+ const roles = ((user as { roles?: string[] } | null)?.roles ?? []) as string[];
278
+ return roles.some((role) => PREVIEW_ROLES.includes(role));
279
+ }
280
+
275
281
  /**
276
282
  * Resolves a draft option to a boolean.
277
283
  * Defaults to `false`. `'auto'` is an explicit opt-in that reads Next's `draftMode()`
@@ -304,7 +310,7 @@ export async function resolveDraft(draft: DraftOption = false): Promise<boolean>
304
310
  export async function getPayload({
305
311
  config,
306
312
  headers,
307
- draft = false,
313
+ draft: requestedDraft = false,
308
314
  }: {
309
315
  config: Promise<SanitizedConfig>;
310
316
  headers?: ReadonlyHeaders;
@@ -325,6 +331,17 @@ export async function getPayload({
325
331
  }
326
332
  }
327
333
 
334
+ // a draft read as a non-editor: the previewer identity while Draft Mode is on (an editor turned it on, see
335
+ // getPreviewHandler), the published site otherwise. Bowl serves drafts to the editing roles only.
336
+ let draft = requestedDraft;
337
+ if (draft && !hasPreviewRole(user)) {
338
+ // only an actual Draft Mode request: the cookie read happens on the draft path alone, which is dynamic anyway
339
+ draft = await resolveDraft('auto');
340
+ if (draft) {
341
+ user = previewer;
342
+ }
343
+ }
344
+
328
345
  // Draft contexts bypass the shared cache, so share them at least between
329
346
  // the callers of this instance (one request when obtained per request).
330
347
  const contexts = new Map<string, Promise<MixerContext>>();