@websolutespa/bom-next 4.0.0-next.14 → 4.0.0-next.16
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 +22 -0
- package/README.md +12 -1
- package/dist/client/live-preview.d.ts +14 -0
- package/dist/client/live-preview.d.ts.map +1 -0
- package/dist/client/live-preview.js +55 -0
- package/dist/client/live-preview.js.map +1 -0
- package/dist/client/page.d.ts.map +1 -1
- package/dist/client/page.js +5 -1
- package/dist/client/page.js.map +1 -1
- package/dist/exports/client.d.ts +2 -1
- package/dist/exports/client.js +2 -1
- package/dist/exports/server.d.ts +4 -3
- package/dist/exports/server.js +3 -2
- package/dist/lib/live-preview.js +21 -0
- package/dist/lib/live-preview.js.map +1 -0
- package/dist/lib/ttl-cache.js +5 -2
- package/dist/lib/ttl-cache.js.map +1 -1
- package/dist/server/cache/executor.js +1 -1
- package/dist/server/cache/mode/classic.js +1 -1
- package/dist/server/cache/mode/components.js +1 -1
- package/dist/server/context.d.ts +38 -2
- package/dist/server/context.d.ts.map +1 -1
- package/dist/server/context.js +58 -2
- package/dist/server/context.js.map +1 -1
- package/dist/server/handlers/preview.handler.d.ts.map +1 -1
- package/dist/server/handlers/preview.handler.js +34 -4
- package/dist/server/handlers/preview.handler.js.map +1 -1
- package/dist/server/lazy.d.ts +24 -2
- package/dist/server/lazy.d.ts.map +1 -1
- package/dist/server/lazy.js +80 -7
- package/dist/server/lazy.js.map +1 -1
- package/dist/server/live-preview-store.js +59 -0
- package/dist/server/live-preview-store.js.map +1 -0
- package/dist/server/live-preview.actions.js +38 -0
- package/dist/server/live-preview.actions.js.map +1 -0
- package/dist/server/live-preview.d.ts +11 -0
- package/dist/server/live-preview.d.ts.map +1 -0
- package/dist/server/live-preview.js +39 -0
- package/dist/server/live-preview.js.map +1 -0
- package/dist/server/mixer.d.ts +6 -1
- package/dist/server/mixer.d.ts.map +1 -1
- package/dist/server/mixer.js +7 -3
- package/dist/server/mixer.js.map +1 -1
- package/dist/types.d.ts +5 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -2
- package/src/client/live-preview.test.tsx +110 -0
- package/src/client/live-preview.tsx +64 -0
- package/src/client/page.tsx +7 -1
- package/src/exports/client.ts +1 -0
- package/src/exports/server.ts +24 -23
- package/src/lib/live-preview.ts +35 -0
- package/src/lib/ttl-cache.test.ts +57 -0
- package/src/lib/ttl-cache.ts +75 -72
- package/src/server/context.test.ts +810 -645
- package/src/server/context.ts +580 -488
- package/src/server/handlers/preview.handler.test.ts +33 -1
- package/src/server/handlers/preview.handler.ts +43 -4
- package/src/server/lazy.cache.test.ts +168 -0
- package/src/server/lazy.ts +130 -16
- package/src/server/live-preview-store.ts +104 -0
- package/src/server/live-preview.actions.test.ts +113 -0
- package/src/server/live-preview.actions.ts +61 -0
- package/src/server/live-preview.ts +50 -0
- package/src/server/mixer.ts +3 -0
- package/src/server/request-data.test.ts +6 -1
- package/src/types.ts +5 -0
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
# @websolutespa/bom-next
|
|
2
2
|
|
|
3
|
+
## 4.0.0-next.16
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 13f1d9c: With Cache Components, the server decorators registered with `withLazyProps` run in their own `'use cache'` scope (`bom:fn:lazy-props`) on public renders, keyed by the page read and the block. A decorator that reads Payload (a listing) no longer fails the prerender with "unstable value `Date.now()`", and the tags it attaches with `tagPage` invalidate its entry and the page. It receives the guest Payload instance and the mixer context of the page's market and locale, and its result must be serializable. Drafts, authenticated pages, live preview and the classic model call decorators directly, as before. `withLazyProps(key, fn, { life, cache })` sets the lifetime (default `bom-page`) or opts a decorator out with `cache: false`. No change is needed in apps.
|
|
8
|
+
- 75c14fa: **Live preview.** Payload's live preview now works on the page collections, with no code in the app: while the editor types, the preview shows the unsaved values.
|
|
9
|
+
- **bom-next.** For a live preview URL (`_live`) the preview handler sets the `bom-live` cookie next to Draft Mode. `PageProvider` listens to the admin and sends each edit to a Server Action, which keeps the unsaved values for the session and renders the route again; `createPageContext` reads the page with those values in place of the stored ones (Bowl's hooks and population still run, nothing is written). `decorateLazyComponents` does not run the `withLazyProps` loaders again while the editor types: a block keeps what its loader returned and its unsaved values override it; a new block is loaded once. On save everything is read and loaded again. New exports: `isLivePreview()` (server), `LivePreviewListener` (client), `ReadOptions.data`. See "Live preview" in the README for the limits (in-memory per instance, Server Action body size).
|
|
10
|
+
- **payload-plugin-bowl.** `admin.livePreview.collections` is the page collections again (it was emptied waiting for this). The app's `admin.livePreview` now adds to Bowl's defaults instead of replacing them. `getLivePreviewURL` accepts populated `markets` and `template`, and adds the editor's `_token` when the site is not on the admin's origin. The page detail endpoint accepts the unsaved document of a live preview request (`data` in the body of a POST with a GET method override), as Payload's own does.
|
|
11
|
+
- **payload-bowl-live-preview.** New `subscribeLive` (debounced edits and save events, no merge: for a frontend that renders on the server). `mergeData` calls `serverURL` + `apiRoute` (it called the page's own origin), takes the `market` instead of a fixed `ww`, and keeps the current data on an error response. `useLivePreview` no longer breaks the rules of hooks or resubscribes on every render, and keeps the page fields Bowl does not send back; the mixer apps pass the live page to `PageProvider`. `payload` is now a peer dependency. `formatAdminURL` is removed.
|
|
12
|
+
|
|
13
|
+
### Patch Changes
|
|
14
|
+
|
|
15
|
+
- bd87aa7: `decorateLazyComponents` decorates every copy of the page that `createPageContext` returned in the request. When `generateMetadata` read the same page after the template, the stored context page was the metadata's copy, so the template rendered its blocks without the decorators' data (seen with Cache Components, where render timing varies). Cached decorators also receive a deep copy of their block.
|
|
16
|
+
- Updated dependencies [75c14fa]
|
|
17
|
+
- @websolutespa/payload-bowl-live-preview@4.0.0-next.11
|
|
18
|
+
|
|
19
|
+
## 4.0.0-next.15
|
|
20
|
+
|
|
21
|
+
### Patch Changes
|
|
22
|
+
|
|
23
|
+
- Use monotonic timing for TTL cache
|
|
24
|
+
|
|
3
25
|
## 4.0.0-next.14
|
|
4
26
|
|
|
5
27
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -75,6 +75,17 @@ The server context (`getContext`) reads routes from the Bowl route store and cac
|
|
|
75
75
|
|
|
76
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
77
|
|
|
78
|
+
## Live preview
|
|
79
|
+
|
|
80
|
+
Payload's live preview works with no code in the app: Bowl enables it on the page collections and points the preview window to `/api/-preview?...&_live=true`, and `PageProvider` listens to the admin.
|
|
81
|
+
|
|
82
|
+
- **Session.** For a live preview URL the preview handler also sets the `bom-live` cookie (a session id and the origin of the admin: `PAYLOAD_PUBLIC_SERVER_URL`, else `NEXT_PUBLIC_URL`). A request is a live preview only with Draft Mode on and that cookie (`isLivePreview()`).
|
|
83
|
+
- **Each edit.** The preview window receives the unsaved form values from the admin, waits for a pause in typing and sends them to the `setLivePreviewData` Server Action, which keeps them for the session and renders the route again. `createPageContext` then reads the page with those values in place of the stored ones (the `data` option of the Payload local API): Bowl's hooks, rich text and populated relations run as for a saved document. Nothing is written to the database.
|
|
84
|
+
- **Blocks.** While the editor types, `decorateLazyComponents` does not run the `withLazyProps` loaders again: each block keeps what its loader returned on the last full render, and the block's unsaved values override it (`{ ...loaded, ...block }`, matched by block `id`). So a property the loader adds (`items`) stays, and a property the block has in the CMS wins. A block added in the admin, or one without an `id`, is loaded once.
|
|
85
|
+
- **Save.** On a save (or autosave) the unsaved values and the loader results are dropped and the route renders again from the saved draft, loaders included.
|
|
86
|
+
|
|
87
|
+
Limits: the unsaved values live in the memory of the server instance that received them (a later request served by another instance shows the saved draft until the next edit), for 30 minutes; an edit is a Server Action call, so the document must fit Next's `serverActions.bodySizeLimit` (1 MB by default); globals and the layout update on save only. A page that does not use `PageProvider` mounts `<LivePreviewListener />` from `@websolutespa/bom-next/client` instead.
|
|
88
|
+
|
|
78
89
|
## Cache
|
|
79
90
|
|
|
80
91
|
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:
|
|
@@ -91,7 +102,7 @@ export const dynamic = 'force-dynamic';
|
|
|
91
102
|
- `bomCached(name, fn, { life, tags, resultTags })` caches a data function by name. `life` is a BOM profile (`bom-layout`, `bom-page`, `bom-listing`, `bom-static`, see `bomProfiles`) or an inline profile. `documentTags(collection, result)` tags a result by its documents. Every entry carries `bom:fn:<name>`, so the panel lists and revalidates it.
|
|
92
103
|
- `withBom(nextConfig)` (`@websolutespa/bom-next/config`) wires the caching model:
|
|
93
104
|
- **Classic ISR** (default): `bomCached` uses `unstable_cache`, templates keep `generateStaticParams` and `export const revalidate`.
|
|
94
|
-
- **`cacheComponents: true`**: `bomCached` and `tagPage` use `'use cache'`, `cacheLife` and `cacheTag`; the BOM profiles are registered as `cacheLife` profiles, `cacheHandlers.default` is the BOM `'use cache'` handler, and `createPageContext` reads public pages and layouts through cached functions. Templates must drop `export const revalidate`. `getStaticParams` returns at least one route per template (Cache Components refuses an empty list), so every template needs one published page at build time.
|
|
105
|
+
- **`cacheComponents: true`**: `bomCached` and `tagPage` use `'use cache'`, `cacheLife` and `cacheTag`; the BOM profiles are registered as `cacheLife` profiles, `cacheHandlers.default` is the BOM `'use cache'` handler, and `createPageContext` reads public pages and layouts through cached functions. Server decorators (`withLazyProps`) run in their own cached scope on public renders (`bom:fn:lazy-props`, keyed by the page read and the block): their Payload reads are cached, the tags they attach with `tagPage` invalidate them and the page, and their result must be serializable. `withLazyProps(key, fn, { life })` changes the lifetime (default `bom-page`); `{ cache: false }` runs a decorator that reads no data directly. Drafts, authenticated pages and live preview call decorators directly. Templates must drop `export const revalidate`. `getStaticParams` returns at least one route per template (Cache Components refuses an empty list), so every template needs one published page at build time.
|
|
95
106
|
- **`REDIS_URL` at build time**: `cacheHandler` is the shared Redis handler (`@websolutespa/bom-next/cache-handlers/isr`), which applies `revalidateTag(tag, 'max')` as stale-while-revalidate across instances; `'use cache'` entries share its tag keys.
|
|
96
107
|
- `registerIntrumentation()` registers the in-process cache executor; Bowl uses `/api/-cache` (Bearer `MIXER_SECRET`) when it runs in another process.
|
|
97
108
|
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/client/live-preview.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Connects the page to the admin's live preview: each edit is sent to the server, which renders the route
|
|
4
|
+
* again with the unsaved values, and a save renders it from the saved draft. Does nothing outside a live
|
|
5
|
+
* preview window. `PageProvider` mounts it, so a page using that provider needs nothing else.
|
|
6
|
+
*/
|
|
7
|
+
declare function LivePreviewListener({
|
|
8
|
+
debounce
|
|
9
|
+
}: {
|
|
10
|
+
debounce?: number;
|
|
11
|
+
}): null;
|
|
12
|
+
//#endregion
|
|
13
|
+
export { LivePreviewListener };
|
|
14
|
+
//# sourceMappingURL=live-preview.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"live-preview.d.ts","names":[],"sources":["../../src/client/live-preview.tsx"],"mappings":";;AAwBA;;;;iBAAgB,mBAAA,CAAA;EAAsB;AAAA;EAAc,QAAA;AAAA"}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { LIVE_COOKIE, parseLiveCookie } from "../lib/live-preview.js";
|
|
3
|
+
import { clearLivePreviewData, setLivePreviewData } from "../server/live-preview.actions.js";
|
|
4
|
+
import { startTransition, useEffect } from "react";
|
|
5
|
+
import { ready, subscribeLive } from "@websolutespa/payload-bowl-live-preview";
|
|
6
|
+
//#region src/client/live-preview.tsx
|
|
7
|
+
function readLiveCookie() {
|
|
8
|
+
const pair = document.cookie.split("; ").find((item) => item.startsWith(`${LIVE_COOKIE}=`));
|
|
9
|
+
if (!pair) return;
|
|
10
|
+
try {
|
|
11
|
+
return parseLiveCookie(decodeURIComponent(pair.slice(LIVE_COOKIE.length + 1)));
|
|
12
|
+
} catch {
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Connects the page to the admin's live preview: each edit is sent to the server, which renders the route
|
|
18
|
+
* again with the unsaved values, and a save renders it from the saved draft. Does nothing outside a live
|
|
19
|
+
* preview window. `PageProvider` mounts it, so a page using that provider needs nothing else.
|
|
20
|
+
*/
|
|
21
|
+
function LivePreviewListener({ debounce }) {
|
|
22
|
+
useEffect(() => {
|
|
23
|
+
if (window.parent === window && !window.opener) return;
|
|
24
|
+
const live = readLiveCookie();
|
|
25
|
+
if (!live) return;
|
|
26
|
+
const { serverURL } = live;
|
|
27
|
+
const unsubscribe = subscribeLive({
|
|
28
|
+
debounce,
|
|
29
|
+
serverURL,
|
|
30
|
+
onData: ({ collectionSlug, data, locale }) => {
|
|
31
|
+
if (!collectionSlug || data.id === void 0 || data.id === null) return;
|
|
32
|
+
startTransition(async () => {
|
|
33
|
+
await setLivePreviewData({
|
|
34
|
+
collection: collectionSlug,
|
|
35
|
+
id: String(data.id),
|
|
36
|
+
locale,
|
|
37
|
+
data
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
},
|
|
41
|
+
onDocumentEvent: () => {
|
|
42
|
+
startTransition(async () => {
|
|
43
|
+
await clearLivePreviewData();
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
ready({ serverURL });
|
|
48
|
+
return unsubscribe;
|
|
49
|
+
}, [debounce]);
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
export { LivePreviewListener };
|
|
54
|
+
|
|
55
|
+
//# sourceMappingURL=live-preview.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"live-preview.js","names":[],"sources":["../../src/client/live-preview.tsx"],"sourcesContent":["'use client';\r\n\r\nimport { ready, subscribeLive } from '@websolutespa/payload-bowl-live-preview';\r\nimport { startTransition, useEffect } from 'react';\r\nimport { LIVE_COOKIE, parseLiveCookie, type LiveCookie } from '../lib/live-preview';\r\nimport { clearLivePreviewData, setLivePreviewData } from '../server/live-preview.actions';\r\n\r\nfunction readLiveCookie(): LiveCookie | undefined {\r\n const pair = document.cookie.split('; ').find((item) => item.startsWith(`${LIVE_COOKIE}=`));\r\n if (!pair) {\r\n return undefined;\r\n }\r\n try {\r\n return parseLiveCookie(decodeURIComponent(pair.slice(LIVE_COOKIE.length + 1)));\r\n } catch {\r\n return undefined;\r\n }\r\n}\r\n\r\n/**\r\n * Connects the page to the admin's live preview: each edit is sent to the server, which renders the route\r\n * again with the unsaved values, and a save renders it from the saved draft. Does nothing outside a live\r\n * preview window. `PageProvider` mounts it, so a page using that provider needs nothing else.\r\n */\r\nexport function LivePreviewListener({ debounce }: { debounce?: number }) {\r\n useEffect(() => {\r\n // the admin's iframe or popup, opened through the preview handler\r\n if (window.parent === window && !window.opener) {\r\n return;\r\n }\r\n const live = readLiveCookie();\r\n if (!live) {\r\n return;\r\n }\r\n const { serverURL } = live;\r\n const unsubscribe = subscribeLive({\r\n debounce,\r\n serverURL,\r\n onData: ({ collectionSlug, data, locale }) => {\r\n if (!collectionSlug || data.id === undefined || data.id === null) {\r\n return;\r\n }\r\n startTransition(async () => {\r\n await setLivePreviewData({\r\n collection: collectionSlug,\r\n id: String(data.id),\r\n locale,\r\n data,\r\n });\r\n });\r\n },\r\n onDocumentEvent: () => {\r\n startTransition(async () => {\r\n await clearLivePreviewData();\r\n });\r\n },\r\n });\r\n // the admin sends nothing until the preview window says it is listening\r\n ready({ serverURL });\r\n return unsubscribe;\r\n }, [debounce]);\r\n\r\n return null;\r\n}\r\n"],"mappings":";;;;;;AAOA,SAAS,iBAAyC;CAChD,MAAM,OAAO,SAAS,OAAO,MAAM,KAAK,CAAC,MAAM,SAAS,KAAK,WAAW,GAAG,YAAY,GAAG,CAAC;AAC3F,KAAI,CAAC,KACH;AAEF,KAAI;AACF,SAAO,gBAAgB,mBAAmB,KAAK,MAAM,YAAY,SAAS,EAAE,CAAC,CAAC;SACxE;AACN;;;;;;;;AASJ,SAAgB,oBAAoB,EAAE,YAAmC;AACvE,iBAAgB;AAEd,MAAI,OAAO,WAAW,UAAU,CAAC,OAAO,OACtC;EAEF,MAAM,OAAO,gBAAgB;AAC7B,MAAI,CAAC,KACH;EAEF,MAAM,EAAE,cAAc;EACtB,MAAM,cAAc,cAAc;GAChC;GACA;GACA,SAAS,EAAE,gBAAgB,MAAM,aAAa;AAC5C,QAAI,CAAC,kBAAkB,KAAK,OAAO,KAAA,KAAa,KAAK,OAAO,KAC1D;AAEF,oBAAgB,YAAY;AAC1B,WAAM,mBAAmB;MACvB,YAAY;MACZ,IAAI,OAAO,KAAK,GAAG;MACnB;MACA;MACD,CAAC;MACF;;GAEJ,uBAAuB;AACrB,oBAAgB,YAAY;AAC1B,WAAM,sBAAsB;MAC5B;;GAEL,CAAC;AAEF,QAAM,EAAE,WAAW,CAAC;AACpB,SAAO;IACN,CAAC,SAAS,CAAC;AAEd,QAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"page.d.ts","names":[],"sources":["../../src/client/page.tsx"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"page.d.ts","names":[],"sources":["../../src/client/page.tsx"],"mappings":";;;;;KAMY,YAAA,GAAe,UAAA,CAAW,KAAA;AAAA,cAEzB,WAAA,QAAW,OAAA;EAAA;MAAqD,uBAAA,CAAA,UAAA;;;;;;;;;;;;;;;;;;;;;;;;sEAgB6qjB,IAAA;MAAA;;;;0EAAjzT,IAAA;MAAA,oCAAqE,IAAA;IAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sEAA3lO,IAAA;IAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAdn6B,YAAA,CAAA;EACd,IAAA;EACA;AAAA;EAEA,IAAA,EAAM,UAAA,CAAW,KAAA;EACjB,QAAA,GAAW,KAAA,CAAM,SAAA;AAAA,IAClB,KAAA,CAAA,GAAA,CAAA,OAAA"}
|
package/dist/client/page.js
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
"use client";
|
|
2
|
+
import { LivePreviewListener } from "./live-preview.js";
|
|
2
3
|
import { createContext } from "react";
|
|
3
4
|
//#region src/client/page.tsx
|
|
4
5
|
const PageContext = createContext(void 0);
|
|
5
6
|
function PageProvider({ page, children }) {
|
|
6
|
-
return <PageContext.Provider value={page}>
|
|
7
|
+
return <PageContext.Provider value={page}>
|
|
8
|
+
<LivePreviewListener />
|
|
9
|
+
{children}
|
|
10
|
+
</PageContext.Provider>;
|
|
7
11
|
}
|
|
8
12
|
//#endregion
|
|
9
13
|
export { PageContext, PageProvider };
|
package/dist/client/page.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"page.js","names":[],"sources":["../../src/client/page.tsx"],"sourcesContent":["'use client';\r\n\r\nimport { ILocalized, IPage } from '@websolutespa/bom-core';\r\nimport { createContext } from 'react';\r\n\r\nexport type IPageContext = ILocalized<IPage>;\r\n\r\nexport const PageContext = createContext<IPageContext | undefined>(undefined);\r\n\r\nexport function PageProvider({\r\n page,\r\n children,\r\n}: {\r\n page: ILocalized<IPage>;\r\n children?: React.ReactNode;\r\n}) {\r\n return <PageContext.Provider value={page}
|
|
1
|
+
{"version":3,"file":"page.js","names":[],"sources":["../../src/client/page.tsx"],"sourcesContent":["'use client';\r\n\r\nimport { ILocalized, IPage } from '@websolutespa/bom-core';\r\nimport { createContext } from 'react';\r\nimport { LivePreviewListener } from './live-preview';\r\n\r\nexport type IPageContext = ILocalized<IPage>;\r\n\r\nexport const PageContext = createContext<IPageContext | undefined>(undefined);\r\n\r\nexport function PageProvider({\r\n page,\r\n children,\r\n}: {\r\n page: ILocalized<IPage>;\r\n children?: React.ReactNode;\r\n}) {\r\n return (\r\n <PageContext.Provider value={page}>\r\n <LivePreviewListener />\r\n {children}\r\n </PageContext.Provider>\r\n );\r\n}\r\n"],"mappings":";;;;AAQA,MAAa,cAAc,cAAwC,KAAA,EAAU;AAE7E,SAAgB,aAAa,EAC3B,MACA,YAIC;AACD,QACE,CAAC,YAAY,SAAS,OAAO,MAAM;MACjC,CAAC,sBAAsB;OACtB,SAAS;IACZ,EAAE,YAAY"}
|
package/dist/exports/client.d.ts
CHANGED
|
@@ -2,6 +2,7 @@ import { Client } from "../client/client.js";
|
|
|
2
2
|
import { ExtraContext, ExtraProvider, IExtraContext } from "../client/extra.js";
|
|
3
3
|
import { ILabelContext, LabelContext, LabelProvider } from "../client/label.js";
|
|
4
4
|
import { ILayoutContext, LayoutContext, LayoutProvider } from "../client/layout.js";
|
|
5
|
+
import { LivePreviewListener } from "../client/live-preview.js";
|
|
5
6
|
import { localCollectionDelete, localCollectionFetch, localCollectionGet, localCollectionPatch, localCollectionPost, localCollectionPut } from "../client/local.collection.js";
|
|
6
7
|
import { IMetaDataContext, IMetaDataOptions, MetaDataContext, MetaDataProvider } from "../client/metadata.js";
|
|
7
8
|
import { IPageContext, PageContext, PageProvider } from "../client/page.js";
|
|
@@ -17,4 +18,4 @@ import { usePage } from "../client/usePage.js";
|
|
|
17
18
|
import { UserContext, UserContextType, UserProvider, invalidateUser } from "../client/user.js";
|
|
18
19
|
import { useUser } from "../client/useUser.js";
|
|
19
20
|
import { captureRouterTransitionStart, registerClientIntrumentation } from "../instrumentation/client.js";
|
|
20
|
-
export { Client, ExtraContext, ExtraProvider, IExtraContext, ILabelContext, ILayoutContext, IMetaDataContext, IMetaDataOptions, IPageContext, LabelContext, LabelProvider, LayoutContext, LayoutProvider, MetaDataContext, MetaDataProvider, PageContext, PageProvider, UserContext, UserContextType, UserProvider, captureRouterTransitionStart, invalidateUser, localCollectionDelete, localCollectionFetch, localCollectionGet, localCollectionPatch, localCollectionPost, localCollectionPut, registerClientIntrumentation, useApi, useApiDelete, useApiFetch, useApiGet, useApiPatch, useApiPost, useApiPut, useCollectionApi, useCollectionApiDelete, useCollectionApiGet, useCollectionApiPatch, useCollectionApiPost, useCollectionApiPut, useExtra, useHttpDelete, useHttpFetch, useHttpGet, useHttpPatch, useHttpPost, useHttpPut, useLabel, useLayout, useLink, useMetaData, usePage, useUser };
|
|
21
|
+
export { Client, ExtraContext, ExtraProvider, IExtraContext, ILabelContext, ILayoutContext, IMetaDataContext, IMetaDataOptions, IPageContext, LabelContext, LabelProvider, LayoutContext, LayoutProvider, LivePreviewListener, MetaDataContext, MetaDataProvider, PageContext, PageProvider, UserContext, UserContextType, UserProvider, captureRouterTransitionStart, invalidateUser, localCollectionDelete, localCollectionFetch, localCollectionGet, localCollectionPatch, localCollectionPost, localCollectionPut, registerClientIntrumentation, useApi, useApiDelete, useApiFetch, useApiGet, useApiPatch, useApiPost, useApiPut, useCollectionApi, useCollectionApiDelete, useCollectionApiGet, useCollectionApiPatch, useCollectionApiPost, useCollectionApiPut, useExtra, useHttpDelete, useHttpFetch, useHttpGet, useHttpPatch, useHttpPost, useHttpPut, useLabel, useLayout, useLink, useMetaData, usePage, useUser };
|
package/dist/exports/client.js
CHANGED
|
@@ -2,6 +2,7 @@ import { LayoutContext, LayoutProvider } from "../client/layout.js";
|
|
|
2
2
|
import { useLayout } from "../client/useLayout.js";
|
|
3
3
|
import { LabelContext, LabelProvider } from "../client/label.js";
|
|
4
4
|
import { useLabel } from "../client/useLabel.js";
|
|
5
|
+
import { LivePreviewListener } from "../client/live-preview.js";
|
|
5
6
|
import { PageContext, PageProvider } from "../client/page.js";
|
|
6
7
|
import { usePage } from "../client/usePage.js";
|
|
7
8
|
import { Client } from "../client/client.js";
|
|
@@ -17,4 +18,4 @@ import { useMetaData } from "../client/useMetaData.js";
|
|
|
17
18
|
import { UserContext, UserProvider, invalidateUser } from "../client/user.js";
|
|
18
19
|
import { useUser } from "../client/useUser.js";
|
|
19
20
|
import { captureRouterTransitionStart, registerClientIntrumentation } from "../instrumentation/client.js";
|
|
20
|
-
export { Client, ExtraContext, ExtraProvider, LabelContext, LabelProvider, LayoutContext, LayoutProvider, MetaDataContext, MetaDataProvider, PageContext, PageProvider, UserContext, UserProvider, captureRouterTransitionStart, invalidateUser, localCollectionDelete, localCollectionFetch, localCollectionGet, localCollectionPatch, localCollectionPost, localCollectionPut, registerClientIntrumentation, useApi, useApiDelete, useApiFetch, useApiGet, useApiPatch, useApiPost, useApiPut, useCollectionApi, useCollectionApiDelete, useCollectionApiGet, useCollectionApiPatch, useCollectionApiPost, useCollectionApiPut, useExtra, useHttpDelete, useHttpFetch, useHttpGet, useHttpPatch, useHttpPost, useHttpPut, useLabel, useLayout, useLink, useMetaData, usePage, useUser };
|
|
21
|
+
export { Client, ExtraContext, ExtraProvider, LabelContext, LabelProvider, LayoutContext, LayoutProvider, LivePreviewListener, MetaDataContext, MetaDataProvider, PageContext, PageProvider, UserContext, UserProvider, captureRouterTransitionStart, invalidateUser, localCollectionDelete, localCollectionFetch, localCollectionGet, localCollectionPatch, localCollectionPost, localCollectionPut, registerClientIntrumentation, useApi, useApiDelete, useApiFetch, useApiGet, useApiPatch, useApiPost, useApiPut, useCollectionApi, useCollectionApiDelete, useCollectionApiGet, useCollectionApiPatch, useCollectionApiPost, useCollectionApiPut, useExtra, useHttpDelete, useHttpFetch, useHttpGet, useHttpPatch, useHttpPost, useHttpPut, useLabel, useLayout, useLink, useMetaData, usePage, useUser };
|
package/dist/exports/server.d.ts
CHANGED
|
@@ -9,7 +9,8 @@ import { createInspector } from "../server/cache/inspector/index.js";
|
|
|
9
9
|
import { ProcessCache, ProcessCacheStatus, clearProcessCaches, processCaches, registerProcessCache } from "../server/cache/registry.js";
|
|
10
10
|
import { readCacheReport, registerLocalCacheExecutor } from "../server/cache/local-executor.js";
|
|
11
11
|
import { tagPage } from "../server/cache/tag-page.js";
|
|
12
|
-
import {
|
|
12
|
+
import { isLivePreview } from "../server/live-preview.js";
|
|
13
|
+
import { CachedPageRead, createLayoutContext, createNotFoundContext, createPageContext, getCachedPageRead, getIssuedPages, getLiveContext, getPageContext, loadCachedPageContext, setPageContext, stableStringify } from "../server/context.js";
|
|
13
14
|
import { getAuthMeHandler } from "../server/handlers/auth.handler.js";
|
|
14
15
|
import { getCaptionsVTT } from "../server/handlers/captions.handler.js";
|
|
15
16
|
import { collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler } from "../server/handlers/collection.handler.js";
|
|
@@ -24,7 +25,7 @@ import { getVarsHandler } from "../server/handlers/vars.handler.js";
|
|
|
24
25
|
import { createContextHelpers } from "../server/helpers.js";
|
|
25
26
|
import { PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataSearchParams, buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, isIndexableDeployment, resolveMetadataUrl, toPlainText } from "../lib/page-metadata.js";
|
|
26
27
|
import { JsonLd, PageStructuredDataOptions, buildPageStructuredData } from "../server/json-ld.js";
|
|
27
|
-
import { decorateLazyComponents, withLazyProps } from "../server/lazy.js";
|
|
28
|
+
import { LazyPropsOptions, decorateLazyComponents, withLazyProps } from "../server/lazy.js";
|
|
28
29
|
import { getLocalApi } from "../server/local-api.js";
|
|
29
30
|
import { GetPageMetadataOptions, PageMetadataProps, getMetadata, getPageMetadata } from "../server/metadata.js";
|
|
30
31
|
import { buildBaseOptions, buildReadOptions, clearMixerContextCache, filterRoutes, getAuthHeaders, getCacheKey, getContext, getMixerContext, getOptions, getPayload, getPayloadInstance, getRoutes, getSearchParams, resolveDraft, setContext } from "../server/mixer.js";
|
|
@@ -32,4 +33,4 @@ import { PAGE_ENVELOPE_FIELDS, getPage, withEnvelopeSelect } from "../server/pag
|
|
|
32
33
|
import { RateLimitOptions, RateLimitResult, RateLimiter, RedisCounter, createRateLimiter } from "../server/rate-limit.js";
|
|
33
34
|
import { getHrefBeforeRedirect, getNextUrl } from "../server/utils.js";
|
|
34
35
|
import { getUtmz } from "../server/utmz.js";
|
|
35
|
-
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, RateLimitOptions, RateLimitResult, RateLimiter, RedisCounter, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, createRateLimiter, 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 };
|
|
36
|
+
export { BomCacheLife, BomCacheProfile, BomCachedOptions, BomProfileName, CacheAction, CacheActionResult, CacheBackend, CacheInspector, CacheMode, CacheTagAction, CachedFunction, CachedPage, CachedPageRead, CdnPurgeHandler, GetPageMetadataOptions, ISiteMap, JsonLd, LazyPropsOptions, PAGE_ENVELOPE_FIELDS, PREVIEW_ROLES, PageMetadataBrand, PageMetadataContext, PageMetadataOptions, PageMetadataProps, PageMetadataSearchParams, PageStructuredDataOptions, ProcessCache, ProcessCacheStatus, RateLimitOptions, RateLimitResult, RateLimiter, RedisCounter, applyCacheAction, bomCached, bomProfiles, buildBaseOptions, buildPageMetadata, buildPageStructuredData, buildReadOptions, cacheModes, clearMixerContextCache, clearProcessCaches, cloudflarePurgeHandler, collectionDeleteHandler, collectionGetHandler, collectionPatchHandler, collectionPostHandler, createContextHelpers, createInspector, createLayoutContext, createNotFoundContext, createPageContext, createRateLimiter, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCachedPageRead, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getIssuedPages, getLiveContext, 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, isLivePreview, loadCachedPageContext, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
|
package/dist/exports/server.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { PREVIEW_ROLES } from "../lib/const.js";
|
|
2
|
+
import { isLivePreview } from "../server/live-preview.js";
|
|
2
3
|
import { buildPageMetadata, getPageAlternates, getPageXDefault, getPaginationQuery, inheritParentMetadata, isIndexableDeployment, resolveMetadataUrl, toPlainText } from "../lib/page-metadata.js";
|
|
3
4
|
import { bomProfiles, resolveProfile } from "../server/cache/profiles.js";
|
|
4
5
|
import { getHrefBeforeRedirect, getNextUrl } from "../server/utils.js";
|
|
@@ -12,7 +13,7 @@ import { readCacheReport, registerLocalCacheExecutor } from "../server/cache/loc
|
|
|
12
13
|
import { getCacheHandler, parseCacheAction } from "../server/cache/handler.js";
|
|
13
14
|
import { tagPage } from "../server/cache/tag-page.js";
|
|
14
15
|
import { PAGE_ENVELOPE_FIELDS, getPage, withEnvelopeSelect } from "../server/page.js";
|
|
15
|
-
import { createLayoutContext, createNotFoundContext, createPageContext, getPageContext, setPageContext, stableStringify } from "../server/context.js";
|
|
16
|
+
import { createLayoutContext, createNotFoundContext, createPageContext, getCachedPageRead, getIssuedPages, getLiveContext, getPageContext, loadCachedPageContext, setPageContext, stableStringify } from "../server/context.js";
|
|
16
17
|
import { getAuthMeHandler } from "../server/handlers/auth.handler.js";
|
|
17
18
|
import { getCaptionsVTT } from "../server/handlers/captions.handler.js";
|
|
18
19
|
import { getLocalApi } from "../server/local-api.js";
|
|
@@ -31,4 +32,4 @@ import { JsonLd, buildPageStructuredData } from "../server/json-ld.js";
|
|
|
31
32
|
import { decorateLazyComponents, withLazyProps } from "../server/lazy.js";
|
|
32
33
|
import { createRateLimiter } from "../server/rate-limit.js";
|
|
33
34
|
import { getUtmz } from "../server/utmz.js";
|
|
34
|
-
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, createRateLimiter, 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 };
|
|
35
|
+
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, createRateLimiter, decorateLazyComponents, dedupeTags, documentTags, filterRoutes, getAuthHeaders, getAuthMeHandler, getCacheHandler, getCacheKey, getCachedPageRead, getCaptionsVTT, getCompiledRedirects, getContext, getHrefBeforeRedirect, getIssuedPages, getLiveContext, 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, isLivePreview, loadCachedPageContext, normalizeTags, parseCacheAction, previewHandler, processCaches, readCacheReport, registerLocalCacheExecutor, registerProcessCache, resolveCdnPurgeHandler, resolveDraft, resolveMetadataUrl, resolveProfile, setContext, setPageContext, stableStringify, tagPage, toPlainText, warmHeader, warmLimit, warmUrls, withEnvelopeSelect, withLazyProps };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
//#region src/lib/live-preview.ts
|
|
2
|
+
/** Cookie of a live preview session, set by the preview handler next to the Draft Mode cookie. */
|
|
3
|
+
const LIVE_COOKIE = "bom-live";
|
|
4
|
+
const SESSION = /^[\w-]{8,64}$/;
|
|
5
|
+
function serializeLiveCookie(value) {
|
|
6
|
+
return JSON.stringify(value);
|
|
7
|
+
}
|
|
8
|
+
function parseLiveCookie(value) {
|
|
9
|
+
if (!value) return;
|
|
10
|
+
try {
|
|
11
|
+
const parsed = JSON.parse(value);
|
|
12
|
+
if (parsed && typeof parsed.session === "string" && SESSION.test(parsed.session) && typeof parsed.serverURL === "string") return {
|
|
13
|
+
session: parsed.session,
|
|
14
|
+
serverURL: parsed.serverURL
|
|
15
|
+
};
|
|
16
|
+
} catch {}
|
|
17
|
+
}
|
|
18
|
+
//#endregion
|
|
19
|
+
export { LIVE_COOKIE, parseLiveCookie, serializeLiveCookie };
|
|
20
|
+
|
|
21
|
+
//# sourceMappingURL=live-preview.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"live-preview.js","names":[],"sources":["../../src/lib/live-preview.ts"],"sourcesContent":["/** Cookie of a live preview session, set by the preview handler next to the Draft Mode cookie. */\r\nexport const LIVE_COOKIE = 'bom-live';\r\n\r\nexport type LiveCookie = {\r\n /** key of the unsaved data kept on the server */\r\n session: string;\r\n /** origin of the admin: the only origin live preview messages are accepted from */\r\n serverURL: string;\r\n};\r\n\r\nconst SESSION = /^[\\w-]{8,64}$/;\r\n\r\nexport function serializeLiveCookie(value: LiveCookie): string {\r\n return JSON.stringify(value);\r\n}\r\n\r\nexport function parseLiveCookie(value: string | undefined | null): LiveCookie | undefined {\r\n if (!value) {\r\n return undefined;\r\n }\r\n try {\r\n const parsed = JSON.parse(value) as Partial<LiveCookie> | null;\r\n if (\r\n parsed &&\r\n typeof parsed.session === 'string' &&\r\n SESSION.test(parsed.session) &&\r\n typeof parsed.serverURL === 'string'\r\n ) {\r\n return { session: parsed.session, serverURL: parsed.serverURL };\r\n }\r\n } catch {\r\n // not a live preview cookie\r\n }\r\n return undefined;\r\n}\r\n"],"mappings":";;AACA,MAAa,cAAc;AAS3B,MAAM,UAAU;AAEhB,SAAgB,oBAAoB,OAA2B;AAC7D,QAAO,KAAK,UAAU,MAAM;;AAG9B,SAAgB,gBAAgB,OAA0D;AACxF,KAAI,CAAC,MACH;AAEF,KAAI;EACF,MAAM,SAAS,KAAK,MAAM,MAAM;AAChC,MACE,UACA,OAAO,OAAO,YAAY,YAC1B,QAAQ,KAAK,OAAO,QAAQ,IAC5B,OAAO,OAAO,cAAc,SAE5B,QAAO;GAAE,SAAS,OAAO;GAAS,WAAW,OAAO;GAAW;SAE3D"}
|
package/dist/lib/ttl-cache.js
CHANGED
|
@@ -4,6 +4,9 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Values are stored as promises so concurrent requests for the same key share
|
|
6
6
|
* one upstream call. Rejected promises are evicted immediately.
|
|
7
|
+
*
|
|
8
|
+
* Expiry uses `performance.now()` (monotonic, process-relative), not `Date.now()`: the cache is read while
|
|
9
|
+
* rendering, and with Cache Components Next.js fails a prerender that reads the current time.
|
|
7
10
|
*/
|
|
8
11
|
var TtlCache = class {
|
|
9
12
|
entries = /* @__PURE__ */ new Map();
|
|
@@ -14,7 +17,7 @@ var TtlCache = class {
|
|
|
14
17
|
return this.entries.size;
|
|
15
18
|
}
|
|
16
19
|
async getOrSet(key, ttl, factory) {
|
|
17
|
-
const now =
|
|
20
|
+
const now = performance.now();
|
|
18
21
|
const entry = this.entries.get(key);
|
|
19
22
|
if (entry && entry.expires > now) {
|
|
20
23
|
this.entries.delete(key);
|
|
@@ -31,7 +34,7 @@ var TtlCache = class {
|
|
|
31
34
|
try {
|
|
32
35
|
const resolved = await value;
|
|
33
36
|
const duration = ttl(resolved);
|
|
34
|
-
if (duration > 0 && this.entries.get(key) === pending) pending.expires =
|
|
37
|
+
if (duration > 0 && this.entries.get(key) === pending) pending.expires = performance.now() + duration;
|
|
35
38
|
else if (this.entries.get(key) === pending) this.entries.delete(key);
|
|
36
39
|
return resolved;
|
|
37
40
|
} catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ttl-cache.js","names":[],"sources":["../../src/lib/ttl-cache.ts"],"sourcesContent":["type TtlCacheEntry<T> = {\
|
|
1
|
+
{"version":3,"file":"ttl-cache.js","names":[],"sources":["../../src/lib/ttl-cache.ts"],"sourcesContent":["type TtlCacheEntry<T> = {\n value: Promise<T>;\n expires: number;\n};\n\n/**\n * Small per-instance TTL cache with LRU eviction and in-flight de-duplication.\n *\n * Values are stored as promises so concurrent requests for the same key share\n * one upstream call. Rejected promises are evicted immediately.\n *\n * Expiry uses `performance.now()` (monotonic, process-relative), not `Date.now()`: the cache is read while\n * rendering, and with Cache Components Next.js fails a prerender that reads the current time.\n */\nexport class TtlCache<T> {\n private readonly entries = new Map<string, TtlCacheEntry<T>>();\n\n constructor(private readonly maxSize: number) {}\n\n get size() {\n return this.entries.size;\n }\n\n async getOrSet(key: string, ttl: (value: T) => number, factory: () => Promise<T>): Promise<T> {\n const now = performance.now();\n const entry = this.entries.get(key);\n if (entry && entry.expires > now) {\n // Re-insert to mark the entry as most recently used.\n this.entries.delete(key);\n this.entries.set(key, entry);\n return entry.value;\n }\n if (entry) {\n this.entries.delete(key);\n }\n const value = factory();\n // Until the value settles, keep it long enough to de-duplicate concurrent calls.\n const pending: TtlCacheEntry<T> = { value, expires: Number.POSITIVE_INFINITY };\n this.set(key, pending);\n try {\n const resolved = await value;\n const duration = ttl(resolved);\n if (duration > 0 && this.entries.get(key) === pending) {\n pending.expires = performance.now() + duration;\n } else if (this.entries.get(key) === pending) {\n this.entries.delete(key);\n }\n return resolved;\n } catch (error) {\n if (this.entries.get(key) === pending) {\n this.entries.delete(key);\n }\n throw error;\n }\n }\n\n delete(key: string) {\n this.entries.delete(key);\n }\n\n clear() {\n this.entries.clear();\n }\n\n private set(key: string, entry: TtlCacheEntry<T>) {\n if (this.entries.size >= this.maxSize) {\n // Maps iterate in insertion order, so the first key is the least recently used.\n const oldest = this.entries.keys().next().value;\n if (oldest !== undefined) {\n this.entries.delete(oldest);\n }\n }\n this.entries.set(key, entry);\n }\n}\n"],"mappings":";;;;;;;;;;AAcA,IAAa,WAAb,MAAyB;CACvB,0BAA2B,IAAI,KAA+B;CAE9D,YAAY,SAAkC;AAAjB,OAAA,UAAA;;CAE7B,IAAI,OAAO;AACT,SAAO,KAAK,QAAQ;;CAGtB,MAAM,SAAS,KAAa,KAA2B,SAAuC;EAC5F,MAAM,MAAM,YAAY,KAAK;EAC7B,MAAM,QAAQ,KAAK,QAAQ,IAAI,IAAI;AACnC,MAAI,SAAS,MAAM,UAAU,KAAK;AAEhC,QAAK,QAAQ,OAAO,IAAI;AACxB,QAAK,QAAQ,IAAI,KAAK,MAAM;AAC5B,UAAO,MAAM;;AAEf,MAAI,MACF,MAAK,QAAQ,OAAO,IAAI;EAE1B,MAAM,QAAQ,SAAS;EAEvB,MAAM,UAA4B;GAAE;GAAO,SAAS,OAAO;GAAmB;AAC9E,OAAK,IAAI,KAAK,QAAQ;AACtB,MAAI;GACF,MAAM,WAAW,MAAM;GACvB,MAAM,WAAW,IAAI,SAAS;AAC9B,OAAI,WAAW,KAAK,KAAK,QAAQ,IAAI,IAAI,KAAK,QAC5C,SAAQ,UAAU,YAAY,KAAK,GAAG;YAC7B,KAAK,QAAQ,IAAI,IAAI,KAAK,QACnC,MAAK,QAAQ,OAAO,IAAI;AAE1B,UAAO;WACA,OAAO;AACd,OAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,QAC5B,MAAK,QAAQ,OAAO,IAAI;AAE1B,SAAM;;;CAIV,OAAO,KAAa;AAClB,OAAK,QAAQ,OAAO,IAAI;;CAG1B,QAAQ;AACN,OAAK,QAAQ,OAAO;;CAGtB,IAAY,KAAa,OAAyB;AAChD,MAAI,KAAK,QAAQ,QAAQ,KAAK,SAAS;GAErC,MAAM,SAAS,KAAK,QAAQ,MAAM,CAAC,MAAM,CAAC;AAC1C,OAAI,WAAW,KAAA,EACb,MAAK,QAAQ,OAAO,OAAO;;AAG/B,OAAK,QAAQ,IAAI,KAAK,MAAM"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { clearProcessCaches } from "./registry.js";
|
|
2
|
-
import { after } from "next/server";
|
|
3
2
|
import { revalidatePath, revalidateTag } from "next/cache";
|
|
3
|
+
import { after } from "next/server";
|
|
4
4
|
//#region src/server/cache/executor.ts
|
|
5
5
|
const cacheModes = ["revalidate", "invalidate"];
|
|
6
6
|
const warmLimit = 200;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { resolveProfile } from "../profiles.js";
|
|
2
2
|
import { normalizeTags } from "../cached-types.js";
|
|
3
|
+
import { unstable_cache } from "next/cache";
|
|
3
4
|
import "server-only";
|
|
4
5
|
import { functionTag } from "@websolutespa/payload-plugin-bowl";
|
|
5
|
-
import { unstable_cache } from "next/cache";
|
|
6
6
|
//#region src/server/cache/mode/classic.ts
|
|
7
7
|
/**
|
|
8
8
|
* Classic caching model (ISR pages, `unstable_cache` data): the default implementation of
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { resolveProfile } from "../profiles.js";
|
|
2
2
|
import { normalizeTags } from "../cached-types.js";
|
|
3
|
+
import { cacheLife, cacheTag } from "next/cache";
|
|
3
4
|
import "server-only";
|
|
4
5
|
import { functionTag } from "@websolutespa/payload-plugin-bowl";
|
|
5
|
-
import { cacheLife, cacheTag } from "next/cache";
|
|
6
6
|
//#region src/server/cache/mode/components.ts
|
|
7
7
|
/**
|
|
8
8
|
* Cache Components model (`'use cache'`, `cacheLife`, `cacheTag`): `withBom()` aliases
|
package/dist/server/context.d.ts
CHANGED
|
@@ -1,9 +1,45 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { MixerPayload } from "./mixer-payload.js";
|
|
2
|
+
import { IPageContext, LayoutContextOptions, LayoutOption, LayoutOptions, MixerContext, PageContextOptions, PageSelect, ReadOptions, ReadonlyHeaders, TypedPageContext } from "../types.js";
|
|
3
|
+
import { LiveContext } from "./live-preview.js";
|
|
2
4
|
import { CollectionSlug, SanitizedConfig } from "payload";
|
|
3
5
|
|
|
4
6
|
//#region src/server/context.d.ts
|
|
5
7
|
/** JSON serialization with sorted keys, so equivalent options produce the same key. */
|
|
6
8
|
declare function stableStringify(value: unknown): string;
|
|
9
|
+
/**
|
|
10
|
+
* Serializable description of a page context read through the cached loaders. Code that must run in its own
|
|
11
|
+
* `'use cache'` scope (the lazy decorators) receives it as a cache key argument and rebuilds the same context there
|
|
12
|
+
* with `loadCachedPageContext`, since the payload instance and the `label`/`link` functions cannot cross the scope.
|
|
13
|
+
*/
|
|
14
|
+
type CachedPageRead = {
|
|
15
|
+
market: string;
|
|
16
|
+
locale: string;
|
|
17
|
+
slug: string;
|
|
18
|
+
id: string;
|
|
19
|
+
page: ReadOptions; /** Depth of the public layout read. */
|
|
20
|
+
layout: number;
|
|
21
|
+
};
|
|
22
|
+
/** The cached read of the page context created in this request: set only for public Cache Components renders. */
|
|
23
|
+
declare function getCachedPageRead(): CachedPageRead | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* Rebuilds, inside a cache scope, the context `createPageContext` produced for a cached read: the guest Payload
|
|
26
|
+
* instance, the mixer context of the market and locale, and the page context. The page and layout come from the
|
|
27
|
+
* same cached loaders, so they are cache hits.
|
|
28
|
+
*/
|
|
29
|
+
declare function loadCachedPageContext(read: CachedPageRead): Promise<{
|
|
30
|
+
payload: MixerPayload;
|
|
31
|
+
context: MixerContext;
|
|
32
|
+
pageContext: TypedPageContext<string, undefined, LayoutOptions>;
|
|
33
|
+
}>;
|
|
34
|
+
/**
|
|
35
|
+
* Every page object `createPageContext` returned in this request. Each caller gets its own shallow copy, and only
|
|
36
|
+
* the last one is stored as the context page: when `generateMetadata` reads the same page after the template, the
|
|
37
|
+
* template's copy is no longer the stored one. `decorateLazyComponents` uses this list to decorate every copy of
|
|
38
|
+
* the page it decorates.
|
|
39
|
+
*/
|
|
40
|
+
declare function getIssuedPages(): object[];
|
|
41
|
+
/** The live preview session of the page created in this request, if any. */
|
|
42
|
+
declare function getLiveContext(): LiveContext | undefined;
|
|
7
43
|
declare function getPageContext<TSlug extends CollectionSlug = CollectionSlug>(): Promise<TypedPageContext<TSlug>>;
|
|
8
44
|
declare function setPageContext<TSlug extends CollectionSlug, TSelect extends PageSelect<TSlug> = undefined, TLayout extends LayoutOption = LayoutOptions>(data: Partial<TypedPageContext<TSlug, TSelect, TLayout>>): Promise<void>;
|
|
9
45
|
/**
|
|
@@ -39,5 +75,5 @@ declare function createLayoutContext(market: string, locale: string, options: La
|
|
|
39
75
|
/** @deprecated Use `createLayoutContext(market, locale, { config, headers })`. */
|
|
40
76
|
declare function createLayoutContext(market: string, locale: string, config: Promise<SanitizedConfig>, headers?: ReadonlyHeaders): Promise<IPageContext>;
|
|
41
77
|
//#endregion
|
|
42
|
-
export { createLayoutContext, createNotFoundContext, createPageContext, getPageContext, setPageContext, stableStringify };
|
|
78
|
+
export { CachedPageRead, createLayoutContext, createNotFoundContext, createPageContext, getCachedPageRead, getIssuedPages, getLiveContext, getPageContext, loadCachedPageContext, setPageContext, stableStringify };
|
|
43
79
|
//# sourceMappingURL=context.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.ts","names":[],"sources":["../../src/server/context.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"context.d.ts","names":[],"sources":["../../src/server/context.ts"],"mappings":";;;;;;;iBAwEgB,eAAA,CAAgB,KAAA;AAAhC;;;;;AAAA,KA2HY,cAAA;EACV,MAAA;EACA,MAAA;EACA,IAAA;EACA,EAAA;EACA,IAAA,EAAM,WAAA,EAFN;EAIA,MAAA;AAAA;;iBAIc,iBAAA,CAAA,GAAqB,cAAA;;;AAArC;;;iBASsB,qBAAA,CAAsB,IAAA,EAAM,cAAA,GAAc,OAAA;;;;;;;;;;;iBAwDhD,cAAA,CAAA;;iBAWA,cAAA,CAAA,GAAkB,WAAA;AAAA,iBAIZ,cAAA,eAA6B,cAAA,GAAiB,cAAA,CAAA,CAAA,GAAmB,OAAA,CACrF,gBAAA,CAAiB,KAAA;AAAA,iBAWG,cAAA,eACN,cAAA,kBACE,UAAA,CAAW,KAAA,+BACX,YAAA,GAAe,aAAA,CAAA,CAC/B,IAAA,EAAM,OAAA,CAAQ,gBAAA,CAAiB,KAAA,EAAO,OAAA,EAAS,OAAA,KAAS,OAAA;;;;;;;;;;AA/B1D;;;;;AAWA;;iBA2CgB,iBAAA,eACA,cAAA,kBACE,UAAA,CAAW,KAAA,+BACX,YAAA,GAAe,aAAA,CAAA,CAE/B,MAAA,UACA,MAAA,UACA,IAAA,EAAM,KAAA,EACN,EAAA,UACA,OAAA,EAAS,kBAAA,CAAmB,KAAA,EAAO,OAAA,EAAS,OAAA,IAC3C,OAAA,CAAQ,gBAAA,CAAiB,KAAA,EAAO,OAAA,EAAS,OAAA;;iBAE5B,iBAAA,eAAgC,cAAA,CAAA,CAC9C,MAAA,UACA,MAAA,UACA,IAAA,EAAM,KAAA,EACN,EAAA,UACA,MAAA,EAAQ,OAAA,CAAQ,eAAA,GAChB,OAAA,GAAU,eAAA,GACT,OAAA,CAAQ,gBAAA,CAAiB,KAAA;AA1D5B;;;;AAAA,iBA0LgB,qBAAA,eACA,cAAA,kBACE,UAAA,CAAW,KAAA,+BACX,YAAA,GAAe,aAAA,CAAA,CAE/B,MAAA,UACA,MAAA,UACA,IAAA,EAAM,KAAA,EACN,EAAA,UACA,OAAA,EAAS,kBAAA,CAAmB,KAAA,EAAO,OAAA,EAAS,OAAA,IAC3C,OAAA,CAAQ,gBAAA,CAAiB,KAAA,EAAO,OAAA,EAAS,OAAA;;iBAE5B,qBAAA,eAAoC,cAAA,CAAA,CAClD,MAAA,UACA,MAAA,UACA,IAAA,EAAM,KAAA,EACN,EAAA,UACA,MAAA,EAAQ,OAAA,CAAQ,eAAA,GAChB,OAAA,GAAU,eAAA,GACT,OAAA,CAAQ,gBAAA,CAAiB,KAAA;;;;iBA+BZ,mBAAA,CACd,MAAA,UACA,MAAA,UACA,OAAA,EAAS,oBAAA,GACR,OAAA,CAAQ,YAAA;;iBAEK,mBAAA,CACd,MAAA,UACA,MAAA,UACA,MAAA,EAAQ,OAAA,CAAQ,eAAA,GAChB,OAAA,GAAU,eAAA,GACT,OAAA,CAAQ,YAAA"}
|
package/dist/server/context.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import "../lib/const.js";
|
|
2
2
|
import { getLabelFromLabels } from "../lib/label.js";
|
|
3
3
|
import { getLink } from "../lib/link.js";
|
|
4
|
+
import { resolveLivePreview } from "./live-preview.js";
|
|
4
5
|
import { bomCached } from "./cache/cached.js";
|
|
5
6
|
import { getPayload, resolveDraft } from "./mixer.js";
|
|
6
7
|
import { tagPage } from "./cache/tag-page.js";
|
|
@@ -123,6 +124,28 @@ const cachedLayout = bomCached("layout-context", async (market, locale, depth) =
|
|
|
123
124
|
function isCachedRead(draft, headers) {
|
|
124
125
|
return cacheMode === "components" && !draft && !headers;
|
|
125
126
|
}
|
|
127
|
+
/** The cached read of the page context created in this request: set only for public Cache Components renders. */
|
|
128
|
+
function getCachedPageRead() {
|
|
129
|
+
return PageContext().get("cachedRead");
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Rebuilds, inside a cache scope, the context `createPageContext` produced for a cached read: the guest Payload
|
|
133
|
+
* instance, the mixer context of the market and locale, and the page context. The page and layout come from the
|
|
134
|
+
* same cached loaders, so they are cache hits.
|
|
135
|
+
*/
|
|
136
|
+
async function loadCachedPageContext(read) {
|
|
137
|
+
const { payload, user, getContext } = await cachedLoadPayload();
|
|
138
|
+
const [context, layout, page] = await Promise.all([
|
|
139
|
+
getContext(read.market, read.locale),
|
|
140
|
+
cachedLayout(read.market, read.locale, read.layout),
|
|
141
|
+
cachedPage(read.market, read.locale, read.slug, read.id, read.page)
|
|
142
|
+
]);
|
|
143
|
+
return {
|
|
144
|
+
payload,
|
|
145
|
+
context,
|
|
146
|
+
pageContext: toPageContext(layout, page, user)
|
|
147
|
+
};
|
|
148
|
+
}
|
|
126
149
|
function loadLayout(market, locale, payload, user, mixerContext, readOptions) {
|
|
127
150
|
const read = {
|
|
128
151
|
depth: readOptions.depth ?? 1,
|
|
@@ -145,6 +168,25 @@ function toPageContext(layout, page, user) {
|
|
|
145
168
|
link: (category) => layout ? getLink(category, layout) : void 0
|
|
146
169
|
};
|
|
147
170
|
}
|
|
171
|
+
/**
|
|
172
|
+
* Every page object `createPageContext` returned in this request. Each caller gets its own shallow copy, and only
|
|
173
|
+
* the last one is stored as the context page: when `generateMetadata` reads the same page after the template, the
|
|
174
|
+
* template's copy is no longer the stored one. `decorateLazyComponents` uses this list to decorate every copy of
|
|
175
|
+
* the page it decorates.
|
|
176
|
+
*/
|
|
177
|
+
function getIssuedPages() {
|
|
178
|
+
const context = PageContext();
|
|
179
|
+
let pages = context.get("pages");
|
|
180
|
+
if (!pages) {
|
|
181
|
+
pages = [];
|
|
182
|
+
context.set("pages", pages);
|
|
183
|
+
}
|
|
184
|
+
return pages;
|
|
185
|
+
}
|
|
186
|
+
/** The live preview session of the page created in this request, if any. */
|
|
187
|
+
function getLiveContext() {
|
|
188
|
+
return PageContext().get("live");
|
|
189
|
+
}
|
|
148
190
|
async function getPageContext() {
|
|
149
191
|
return {
|
|
150
192
|
layout: PageContext().get("layout"),
|
|
@@ -163,12 +205,15 @@ async function createPageContext(market, locale, slug, id, optionsOrConfig, head
|
|
|
163
205
|
const draft = await resolveDraft(options.draft);
|
|
164
206
|
const { payload, user, getContext } = await getRequestPayload(options.config, options.headers, draft);
|
|
165
207
|
const context = await getContext(market, locale);
|
|
208
|
+
const live = draft ? await resolveLivePreview(market, locale, String(slug), id) : void 0;
|
|
209
|
+
PageContext().set("live", live);
|
|
166
210
|
const pageRead = {
|
|
167
211
|
draft,
|
|
168
212
|
depth: options.depth ?? 2,
|
|
169
213
|
select: options.select,
|
|
170
214
|
populate: options.populate,
|
|
171
|
-
joins: options.joins
|
|
215
|
+
joins: options.joins,
|
|
216
|
+
...live?.data ? { data: live.data } : {}
|
|
172
217
|
};
|
|
173
218
|
const cached = isCachedRead(draft, options.headers);
|
|
174
219
|
if (cached) cachedLoadConfig = options.config;
|
|
@@ -190,6 +235,16 @@ async function createPageContext(market, locale, slug, id, optionsOrConfig, head
|
|
|
190
235
|
});
|
|
191
236
|
})();
|
|
192
237
|
const [layout, page] = await Promise.all([layoutPromise, pagePromise]);
|
|
238
|
+
const layoutDraft = layoutOptions === false || layoutOptions?.draft === void 0 ? draft : await resolveDraft(layoutOptions.draft);
|
|
239
|
+
const cachedRead = cached && !layoutDraft ? {
|
|
240
|
+
market,
|
|
241
|
+
locale,
|
|
242
|
+
slug: String(slug),
|
|
243
|
+
id,
|
|
244
|
+
page: pageRead,
|
|
245
|
+
layout: layoutOptions !== false && layoutOptions?.depth || 1
|
|
246
|
+
} : void 0;
|
|
247
|
+
PageContext().set("cachedRead", cachedRead);
|
|
193
248
|
if (!draft) {
|
|
194
249
|
const breadcrumb = page?.breadcrumb;
|
|
195
250
|
await tagPage(() => [...routeCacheTags({
|
|
@@ -201,6 +256,7 @@ async function createPageContext(market, locale, slug, id, optionsOrConfig, head
|
|
|
201
256
|
}), ...layout ? layoutCacheTags(market, locale) : []]);
|
|
202
257
|
}
|
|
203
258
|
const pageContext = toPageContext(layout, page, user);
|
|
259
|
+
if (pageContext.page) getIssuedPages().push(pageContext.page);
|
|
204
260
|
if (layout) await setPageContext(pageContext);
|
|
205
261
|
else await setPageContext({
|
|
206
262
|
page: pageContext.page,
|
|
@@ -244,6 +300,6 @@ async function createLayoutContext(market, locale, optionsOrConfig, headers) {
|
|
|
244
300
|
return pageContext;
|
|
245
301
|
}
|
|
246
302
|
//#endregion
|
|
247
|
-
export { createLayoutContext, createNotFoundContext, createPageContext, getPageContext, setPageContext, stableStringify };
|
|
303
|
+
export { createLayoutContext, createNotFoundContext, createPageContext, getCachedPageRead, getIssuedPages, getLiveContext, getPageContext, loadCachedPageContext, setPageContext, stableStringify };
|
|
248
304
|
|
|
249
305
|
//# sourceMappingURL=context.js.map
|