sanity-plugin-visual-editor 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +263 -16
  3. package/TESTING.md +133 -0
  4. package/dist/PreviewBar-D_rw0bhP.js +3503 -0
  5. package/dist/PreviewBar-D_rw0bhP.js.map +1 -0
  6. package/dist/bar.d.ts +22 -0
  7. package/dist/bar.js +67 -0
  8. package/dist/bar.js.map +1 -0
  9. package/dist/cloudflare.d.ts +87 -0
  10. package/dist/cloudflare.js +1134 -0
  11. package/dist/cloudflare.js.map +1 -0
  12. package/dist/data-D0qotTtt.d.ts +177 -0
  13. package/dist/host-x2eXr-LJ.js +619 -0
  14. package/dist/host-x2eXr-LJ.js.map +1 -0
  15. package/dist/host.d.ts +162 -0
  16. package/dist/host.js +3 -0
  17. package/dist/index-hDzatlg7.d.ts +276 -0
  18. package/dist/index.d.ts +18 -18
  19. package/dist/index.js +7 -8
  20. package/dist/link-search-JtZkxz4k.js +14 -0
  21. package/dist/link-search-JtZkxz4k.js.map +1 -0
  22. package/dist/next-client.d.ts +22 -0
  23. package/dist/next-client.js +112 -0
  24. package/dist/next-client.js.map +1 -0
  25. package/dist/next.d.ts +135 -0
  26. package/dist/next.js +176 -0
  27. package/dist/next.js.map +1 -0
  28. package/dist/node-labels-CDiW5rMq.js +122 -0
  29. package/dist/node-labels-CDiW5rMq.js.map +1 -0
  30. package/dist/page-documents-BFFcH8lD.d.ts +54 -0
  31. package/dist/page-documents-mGfw_flR.js +67 -0
  32. package/dist/page-documents-mGfw_flR.js.map +1 -0
  33. package/dist/perspective-BmS9TVtr.js +106 -0
  34. package/dist/perspective-BmS9TVtr.js.map +1 -0
  35. package/dist/preview-links-BZDZyIey.js +119 -0
  36. package/dist/preview-links-BZDZyIey.js.map +1 -0
  37. package/dist/preview-links-DM6BCiLV.d.ts +87 -0
  38. package/dist/protocol-BNO38gYy.js +280 -0
  39. package/dist/protocol-BNO38gYy.js.map +1 -0
  40. package/dist/protocol-BnRCy2wJ.d.ts +386 -0
  41. package/dist/server-B8MqMyaN.js +748 -0
  42. package/dist/server-B8MqMyaN.js.map +1 -0
  43. package/dist/server.d.ts +4 -0
  44. package/dist/server.js +3 -0
  45. package/dist/shell-DZotxRXX.d.ts +37 -0
  46. package/dist/studio.d.ts +93 -0
  47. package/dist/studio.js +1263 -0
  48. package/dist/studio.js.map +1 -0
  49. package/dist/sveltekit.d.ts +281 -0
  50. package/dist/sveltekit.js +394 -0
  51. package/dist/sveltekit.js.map +1 -0
  52. package/package.json +120 -39
  53. package/dist/index.d.mts +0 -21
  54. package/dist/index.js.map +0 -1
  55. package/dist/index.mjs +0 -8
  56. package/dist/index.mjs.map +0 -1
  57. package/sanity.json +0 -8
  58. package/src/index.ts +0 -27
  59. package/v2-incompatible.js +0 -11
package/dist/index.d.ts CHANGED
@@ -1,21 +1,21 @@
1
- import {Plugin as Plugin_2} from 'sanity'
2
-
1
+ import { C as SearchConfig, D as SearchRoute, E as SearchKindOption, O as searchKinds, S as ROUTE_KIND, T as SearchKind, _ as releaseIdOf, a as PERSPECTIVE_COOKIE, b as serializePerspective, c as RELEASES_QUERY, d as ReleaseType, f as activeReleases, g as perspectiveTone, h as perspectiveStack, i as DRAFTS, l as RELEASE_TYPES, m as parsePerspective, n as PreviewBarData, o as PUBLISHED, p as isScheduledDraft, r as PreviewLinkErrorData, s as PreviewPerspective, t as PreviewBarBrand, u as ReleaseDocument, v as releaseTone, w as SearchDocumentType, x as sortReleases, y as selectionOf } from "./data-D0qotTtt.js";
2
+ import { _ as previewLinkExpiry, a as PREVIEW_LINK_ROUTE, c as PreviewLinkValue, d as generatePreviewLinkCode, f as isPreviewLinkCode, g as parsePreviewLinkValue, h as normalizePreviewPathname, i as PREVIEW_LINK_KEY_PREFIX, l as assertLinkTtl, m as memoryStore, n as MIN_LINK_TTL_SECONDS, o as PREVIEW_LINK_TTL_SECONDS, p as kvStore, r as PREVIEW_LINK_CODE_LENGTH, s as PreviewLinkStore, t as KVNamespaceLike, u as createPreviewLink, v as previewLinkKey } from "./preview-links-DM6BCiLV.js";
3
+ import { A as SanityAttrDocument, B as humanizeFieldName, C as LabelSchemaType, D as describePath, E as createNodeDescriber, F as StudioPath, G as studioPathToString, H as parseSanityNode, I as StudioPathSegment, J as toUrlPath, K as toPanePath, L as createSanityAttr, M as SanityAttrPath, N as SanityDataAttribute, O as MAX_EDIT_PATH_LENGTH, P as SanityNode, R as describeSanityPath, S as LabelSchema, T as clientDocumentFetcher, U as publishedDocumentId, V as matchFocusedNodes, W as sanityAttr, _ as isPreviewBarFrame, a as PREVIEW_BAR_POSITION_PARAM, b as readPreviewBarPosition, c as PaneSide, d as PreviewBarMessage, f as PreviewBarPosition, g as isInspectorShortcut, h as STUDIO_PREVIEW_PARAM, i as PREVIEW_BAR_HEIGHT, j as SanityAttrOptions, k as SANITY_NODE_ATTRIBUTE, l as PreviewBarContext, m as PreviewBarViewport, n as PREVIEW_BAR_CONTEXT_PARAM, o as PREVIEW_BAR_ROUTE, p as PreviewBarSelection, q as toStudioPath, r as PREVIEW_BAR_FRAME_NAME, s as PREVIEW_PANEL_MIN_PAGE_WIDTH, t as MAX_DESCRIBE_NODES, u as PreviewBarDocument, v as isPreviewBarMessage, w as NodeLabel, x as DocumentFetcher, y as readPreviewBarContext, z as encodeSanityNode } from "./protocol-BnRCy2wJ.js";
4
+ import { a as matchRoute, i as findPageDocumentRule, n as PageDocument, r as PageDocumentRule, t as DocumentResolverContext } from "./page-documents-BFFcH8lD.js";
3
5
  /**
4
- * Usage in `sanity.config.ts` (or .js)
5
- *
6
- * ```ts
7
- * import {defineConfig} from 'sanity'
8
- * import {myPlugin} from 'sanity-plugin-visual-editor'
6
+ * Same-origin path checks, shared by everything that turns an untrusted string into a page on this
7
+ * site: short links, `postMessage` paths and the Visual Editor's `?preview=` parameter.
8
+ */
9
+ /**
10
+ * `value` as a root-relative path on this site (pathname, query and hash, normalized), or `null`.
9
11
  *
10
- * export default defineConfig({
11
- * // ...
12
- * plugins: [myPlugin()],
13
- * })
14
- * ```
15
- * @public
12
+ * Checks the input and the result: browsers read `\` as `/` and drop tabs and newlines, and
13
+ * resolving dot segments can turn `/.//host` or `/%2e%2e//host` into `//host`, which is another
14
+ * site once it lands in a `Location` header or `new URL(path, origin)`. A path whose first segment
15
+ * starts with an encoded slash or backslash (`/%2f…`, `/%5c…`) is refused too, since a server that
16
+ * decodes it before redirecting would do the same.
16
17
  */
17
- export declare const myPlugin: Plugin_2<void | MyPluginConfig>
18
-
19
- declare interface MyPluginConfig {}
20
-
21
- export {}
18
+ export declare function sameOriginPath(value: unknown): string | null;
19
+ /** Whether `value` is a root-relative path that stays on this site; see `sameOriginPath`. */
20
+ export declare function isSameOriginPath(value: unknown): value is string;
21
+ export { DRAFTS, DocumentFetcher, DocumentResolverContext, KVNamespaceLike, LabelSchema, LabelSchemaType, MAX_DESCRIBE_NODES, MAX_EDIT_PATH_LENGTH, MIN_LINK_TTL_SECONDS, NodeLabel, PERSPECTIVE_COOKIE, PREVIEW_BAR_CONTEXT_PARAM, PREVIEW_BAR_FRAME_NAME, PREVIEW_BAR_HEIGHT, PREVIEW_BAR_POSITION_PARAM, PREVIEW_BAR_ROUTE, PREVIEW_LINK_CODE_LENGTH, PREVIEW_LINK_KEY_PREFIX, PREVIEW_LINK_ROUTE, PREVIEW_LINK_TTL_SECONDS, PREVIEW_PANEL_MIN_PAGE_WIDTH, PUBLISHED, PageDocument, PageDocumentRule, PaneSide, PreviewBarBrand, PreviewBarContext, PreviewBarData, PreviewBarDocument, PreviewBarMessage, PreviewBarPosition, PreviewBarSelection, PreviewBarViewport, PreviewLinkErrorData, PreviewLinkStore, PreviewLinkValue, PreviewPerspective, RELEASES_QUERY, RELEASE_TYPES, ROUTE_KIND, ReleaseDocument, ReleaseType, SANITY_NODE_ATTRIBUTE, STUDIO_PREVIEW_PARAM, SanityAttrDocument, SanityAttrOptions, SanityAttrPath, SanityDataAttribute, SanityNode, SearchConfig, SearchDocumentType, SearchKind, SearchKindOption, SearchRoute, StudioPath, StudioPathSegment, activeReleases, assertLinkTtl, clientDocumentFetcher, createNodeDescriber, createPreviewLink, createSanityAttr, describePath, describeSanityPath, encodeSanityNode, findPageDocumentRule, generatePreviewLinkCode, humanizeFieldName, isInspectorShortcut, isPreviewBarFrame, isPreviewBarMessage, isPreviewLinkCode, isScheduledDraft, kvStore, matchFocusedNodes, matchRoute, memoryStore, normalizePreviewPathname, parsePerspective, parsePreviewLinkValue, parseSanityNode, perspectiveStack, perspectiveTone, previewLinkExpiry, previewLinkKey, publishedDocumentId, readPreviewBarContext, readPreviewBarPosition, releaseIdOf, releaseTone, sanityAttr, searchKinds, selectionOf, serializePerspective, sortReleases, studioPathToString, toPanePath, toStudioPath, toUrlPath };
package/dist/index.js CHANGED
@@ -1,8 +1,7 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: !0 });
3
- var sanity = require("sanity");
4
- const myPlugin = sanity.definePlugin((config = {}) => (console.log("hello from sanity-plugin-visual-editor"), {
5
- name: "sanity-plugin-visual-editor"
6
- }));
7
- exports.myPlugin = myPlugin;
8
- //# sourceMappingURL=index.js.map
1
+ import { n as searchKinds, t as ROUTE_KIND } from "./link-search-JtZkxz4k.js";
2
+ import { a as RELEASE_TYPES, c as parsePerspective, d as releaseIdOf, f as releaseTone, h as sortReleases, i as RELEASES_QUERY, l as perspectiveStack, m as serializePerspective, n as PERSPECTIVE_COOKIE, o as activeReleases, p as selectionOf, r as PUBLISHED, s as isScheduledDraft, t as DRAFTS, u as perspectiveTone } from "./perspective-BmS9TVtr.js";
3
+ import { C as sanityAttr, D as toUrlPath, E as toStudioPath, O as isSameOriginPath, S as publishedDocumentId, T as toPanePath, _ as describeSanityPath, a as PREVIEW_BAR_POSITION_PARAM, b as matchFocusedNodes, c as STUDIO_PREVIEW_PARAM, d as isPreviewBarMessage, f as readPreviewBarContext, g as createSanityAttr, h as SANITY_NODE_ATTRIBUTE, i as PREVIEW_BAR_HEIGHT, k as sameOriginPath, l as isInspectorShortcut, m as MAX_EDIT_PATH_LENGTH, n as PREVIEW_BAR_CONTEXT_PARAM, o as PREVIEW_BAR_ROUTE, p as readPreviewBarPosition, r as PREVIEW_BAR_FRAME_NAME, s as PREVIEW_PANEL_MIN_PAGE_WIDTH, t as MAX_DESCRIBE_NODES, u as isPreviewBarFrame, v as encodeSanityNode, w as studioPathToString, x as parseSanityNode, y as humanizeFieldName } from "./protocol-BNO38gYy.js";
4
+ import { a as PREVIEW_LINK_TTL_SECONDS, c as generatePreviewLinkCode, d as memoryStore, f as normalizePreviewPathname, h as previewLinkKey, i as PREVIEW_LINK_ROUTE, l as isPreviewLinkCode, m as previewLinkExpiry, n as PREVIEW_LINK_CODE_LENGTH, o as assertLinkTtl, p as parsePreviewLinkValue, r as PREVIEW_LINK_KEY_PREFIX, s as createPreviewLink, t as MIN_LINK_TTL_SECONDS, u as kvStore } from "./preview-links-BZDZyIey.js";
5
+ import { n as matchRoute, t as findPageDocumentRule } from "./page-documents-mGfw_flR.js";
6
+ import { n as createNodeDescriber, r as describePath, t as clientDocumentFetcher } from "./node-labels-CDiW5rMq.js";
7
+ export { DRAFTS, MAX_DESCRIBE_NODES, MAX_EDIT_PATH_LENGTH, MIN_LINK_TTL_SECONDS, PERSPECTIVE_COOKIE, PREVIEW_BAR_CONTEXT_PARAM, PREVIEW_BAR_FRAME_NAME, PREVIEW_BAR_HEIGHT, PREVIEW_BAR_POSITION_PARAM, PREVIEW_BAR_ROUTE, PREVIEW_LINK_CODE_LENGTH, PREVIEW_LINK_KEY_PREFIX, PREVIEW_LINK_ROUTE, PREVIEW_LINK_TTL_SECONDS, PREVIEW_PANEL_MIN_PAGE_WIDTH, PUBLISHED, RELEASES_QUERY, RELEASE_TYPES, ROUTE_KIND, SANITY_NODE_ATTRIBUTE, STUDIO_PREVIEW_PARAM, activeReleases, assertLinkTtl, clientDocumentFetcher, createNodeDescriber, createPreviewLink, createSanityAttr, describePath, describeSanityPath, encodeSanityNode, findPageDocumentRule, generatePreviewLinkCode, humanizeFieldName, isInspectorShortcut, isPreviewBarFrame, isPreviewBarMessage, isPreviewLinkCode, isSameOriginPath, isScheduledDraft, kvStore, matchFocusedNodes, matchRoute, memoryStore, normalizePreviewPathname, parsePerspective, parsePreviewLinkValue, parseSanityNode, perspectiveStack, perspectiveTone, previewLinkExpiry, previewLinkKey, publishedDocumentId, readPreviewBarContext, readPreviewBarPosition, releaseIdOf, releaseTone, sameOriginPath, sanityAttr, searchKinds, selectionOf, serializePerspective, sortReleases, studioPathToString, toPanePath, toStudioPath, toUrlPath };
@@ -0,0 +1,14 @@
1
+ const ROUTE_KIND = "route";
2
+ /** The kinds the bar can filter by: routes first (when there are any), then each type. */
3
+ function searchKinds(config) {
4
+ return [...config.routes?.length ? [{
5
+ kind: ROUTE_KIND,
6
+ title: "Route"
7
+ }] : [], ...(config.types ?? []).map((type) => ({
8
+ kind: type.type,
9
+ title: type.title
10
+ }))];
11
+ }
12
+ export { searchKinds as n, ROUTE_KIND as t };
13
+
14
+ //# sourceMappingURL=link-search-JtZkxz4k.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"link-search-JtZkxz4k.js","names":[],"sources":["../src/core/link-search.ts"],"sourcesContent":["/**\n * The bar's search config: the site's fixed routes and the document types that have pages. The\n * Studio's own search (Studio layer) is filtered to these types, and `/resolve` turns a picked\n * document into its page with `fields.slug`, `filter` and `href`.\n */\n\n/** A fixed page with no document behind it, such as the homepage or the cart. */\nexport type SearchRoute = {\n title: string\n path: string\n /** Shown in place of a thumbnail. */\n emoji?: string\n}\n\n/** A document type the search lists, and how its documents become links. */\nexport type SearchDocumentType = {\n /** The schema type name (`_type`). */\n type: string\n /** The schema type's title: the result badge and the types filter label. */\n title: string\n /** Shown when a document has no image. */\n emoji?: string\n /**\n * GROQ expressions, evaluated per document. `title` and `slug` are required; a document without a\n * slug is left out (it has no page to open).\n * @example { title: 'store.title', slug: 'store.slug.current', image: 'store.previewImageUrl' }\n */\n fields: {\n title: string\n slug: string\n subtitle?: string\n /** An image URL: Sanity and Shopify CDN URLs are resized for the 33px thumbnail. */\n image?: string\n }\n /**\n * Plain field paths to boost, like the Studio's preview fields (title 10, subtitle 5). Defaults\n * to `fields.title` and `fields.subtitle`; set this when those are computed expressions, and\n * `subtitle: null` to boost the title only.\n */\n boost?: {title?: string; subtitle?: string | null}\n /** An extra GROQ filter, e.g. `store.isDeleted != true`. */\n filter?: string\n /** The page a document opens, from its slug. */\n href: (slug: string) => string\n}\n\nexport type SearchConfig = {\n routes?: SearchRoute[]\n types?: SearchDocumentType[]\n}\n\n/** `'route'` stands for the fixed routes; anything else is a document type name. */\nexport type SearchKind = string\nexport const ROUTE_KIND = 'route'\n\n/** The types filter, as the bar receives it: serializable, no functions. */\nexport type SearchKindOption = {kind: SearchKind; title: string}\n\n/** The kinds the bar can filter by: routes first (when there are any), then each type. */\nexport function searchKinds(config: SearchConfig): SearchKindOption[] {\n return [\n ...(config.routes?.length ? [{kind: ROUTE_KIND, title: 'Route'}] : []),\n ...(config.types ?? []).map((type) => ({kind: type.type, title: type.title})),\n ]\n}\n"],"mappings":"AAqDA,MAAa,aAAa;;AAM1B,SAAgB,YAAY,QAA0C;CACpE,OAAO,CACL,GAAI,OAAO,QAAQ,SAAS,CAAC;EAAC,MAAM;EAAY,OAAO;CAAO,CAAC,IAAI,CAAC,GACpE,IAAI,OAAO,SAAS,CAAC,EAAA,CAAG,KAAK,UAAU;EAAC,MAAM,KAAK;EAAM,OAAO,KAAK;CAAK,EAAE,CAC9E;AACF"}
@@ -0,0 +1,22 @@
1
+ import { n as PreviewBarData, r as PreviewLinkErrorData } from "./data-D0qotTtt.js";
2
+ import { LiveTicket } from "./next.js";
3
+ /**
4
+ * Mounts the bar's frame in the top window while draft mode is on. In the Studio's Visual Editor
5
+ * tool's frame (`isPreviewBarFrame()`), it answers the tool instead (`mountPreviewBarFrame`): the
6
+ * tool shows its own bar above the page. Other frames are skipped.
7
+ *
8
+ * With `live` (`await visualEditor.live()`), it follows the realtime preview hub and calls
9
+ * `router.refresh()` when a result the page read changes: the Server Components run again and
10
+ * read the new result from the hub. One refresh at a time; changes that arrive meanwhile are
11
+ * picked up by one more.
12
+ */
13
+ export declare function PreviewBarHost({ basePath, live }: {
14
+ basePath?: string;
15
+ live?: LiveTicket | null;
16
+ }): null;
17
+ /** The bar itself, for `app/__visual-editor/page.tsx`. */
18
+ export declare function PreviewBarFrame({ data }: {
19
+ data: PreviewBarData;
20
+ }): import("react").JSX.Element;
21
+ /** The expired-link page, for `/p/[code]` and its `not-found.tsx`. */
22
+ export declare function PreviewLinkErrorFrame(props: PreviewLinkErrorData): import("react").JSX.Element;
@@ -0,0 +1,112 @@
1
+ "use client";
2
+ import { u as isPreviewBarFrame } from "./protocol-BNO38gYy.js";
3
+ import { n as isTopWindow } from "./host-x2eXr-LJ.js";
4
+ import { useCallback, useEffect, useRef, useState, useTransition } from "react";
5
+ import { jsx } from "react/jsx-runtime";
6
+ import { usePathname, useRouter } from "next/navigation";
7
+ /**
8
+ * Next.js client components. `PreviewBarHost` goes in the site's root layout (rendered only in
9
+ * draft mode) and follows the realtime preview hub when given a live ticket; `PreviewBarFrame` and
10
+ * `PreviewLinkErrorFrame` render the bar's page and the expired-link page. React and Sanity UI load only from the frames' dynamic imports, so the host
11
+ * stays a few KB.
12
+ */
13
+ /** The hub a ticket names (`<hub>.<expires>.<signature>`), to tell when the tab must move. */
14
+ function ticketHub(ticket) {
15
+ if (!ticket) return null;
16
+ let last = ticket.lastIndexOf("."), middle = ticket.lastIndexOf(".", last - 1);
17
+ return middle > 0 ? ticket.slice(0, middle) : null;
18
+ }
19
+ /**
20
+ * Mounts the bar's frame in the top window while draft mode is on. In the Studio's Visual Editor
21
+ * tool's frame (`isPreviewBarFrame()`), it answers the tool instead (`mountPreviewBarFrame`): the
22
+ * tool shows its own bar above the page. Other frames are skipped.
23
+ *
24
+ * With `live` (`await visualEditor.live()`), it follows the realtime preview hub and calls
25
+ * `router.refresh()` when a result the page read changes: the Server Components run again and
26
+ * read the new result from the hub. One refresh at a time; changes that arrive meanwhile are
27
+ * picked up by one more.
28
+ */
29
+ function PreviewBarHost({ basePath, live }) {
30
+ let router = useRouter(), pathname = usePathname(), [host, setHost] = useState(null), [refreshing, startRefresh] = useTransition(), refreshingRef = useRef(!1), stale = useRef(!1);
31
+ refreshingRef.current = refreshing;
32
+ let refresh = useCallback(() => {
33
+ refreshingRef.current ? stale.current = !0 : startRefresh(() => router.refresh());
34
+ }, [router]);
35
+ useEffect(() => {
36
+ !refreshing && stale.current && (stale.current = !1, startRefresh(() => router.refresh()));
37
+ }, [refreshing, router]);
38
+ let hub = ticketHub(live?.ticket), ticket = useRef(live?.ticket);
39
+ return ticket.current = live?.ticket, useEffect(() => {
40
+ if (!host || !hub || !ticket.current) return;
41
+ let cancelled = !1, stop, params = { ticket: ticket.current };
42
+ return import("./host.js").then(({ subscribePreviewEvents }) => {
43
+ cancelled || (stop = subscribePreviewEvents(refresh, {
44
+ params,
45
+ onStatus: (status) => host.setLiveStatus(status)
46
+ }));
47
+ }), () => {
48
+ cancelled = !0, stop?.();
49
+ };
50
+ }, [
51
+ host,
52
+ hub,
53
+ refresh
54
+ ]), useEffect(() => {
55
+ let frame = isPreviewBarFrame();
56
+ if (!frame && !isTopWindow()) return;
57
+ let cancelled = !1, mounted;
58
+ return import("./host.js").then(({ mountPreviewBarHost, mountPreviewBarFrame }) => {
59
+ if (cancelled) return;
60
+ let options = {
61
+ refresh: () => router.refresh(),
62
+ navigate: (href) => router.push(href)
63
+ };
64
+ mounted = frame ? mountPreviewBarFrame(options) : mountPreviewBarHost({
65
+ ...options,
66
+ basePath
67
+ }), setHost(mounted);
68
+ }), () => {
69
+ cancelled = !0, mounted?.destroy(), setHost(null);
70
+ };
71
+ }, [basePath, router]), useEffect(() => {
72
+ host?.setPath(window.location.pathname + window.location.search);
73
+ }, [host, pathname]), null;
74
+ }
75
+ /**
76
+ * Mounts a React root from the lazily loaded bar module into this component's element. The
77
+ * cancellation check runs before mounting, so React's development double-run of effects never
78
+ * mounts two roots on one element.
79
+ */
80
+ function useMounted(mount, deps) {
81
+ let ref = useRef(null);
82
+ return useEffect(() => {
83
+ let element = ref.current;
84
+ if (!element) return;
85
+ let unmount, cancelled = !1;
86
+ return import("./bar.js").then((bar) => {
87
+ cancelled || (unmount = mount(bar, element));
88
+ }), () => {
89
+ cancelled = !0, unmount?.();
90
+ };
91
+ }, deps), ref;
92
+ }
93
+ /** The bar itself, for `app/__visual-editor/page.tsx`. */
94
+ function PreviewBarFrame({ data }) {
95
+ let ref = useMounted(({ mountPreviewBar }, element) => mountPreviewBar(element, data), [data]);
96
+ return /* @__PURE__ */ jsx("div", {
97
+ ref,
98
+ style: { height: "100%" }
99
+ });
100
+ }
101
+ /** The expired-link page, for `/p/[code]` and its `not-found.tsx`. */
102
+ function PreviewLinkErrorFrame(props) {
103
+ let ref = useMounted(({ mountPreviewLinkError }, element) => mountPreviewLinkError(element, props), [
104
+ props.expired,
105
+ props.brand,
106
+ props.studioPath
107
+ ]);
108
+ return /* @__PURE__ */ jsx("div", { ref });
109
+ }
110
+ export { PreviewBarFrame, PreviewBarHost, PreviewLinkErrorFrame };
111
+
112
+ //# sourceMappingURL=next-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next-client.js","names":[],"sources":["../src/next/client.tsx"],"sourcesContent":["'use client'\n/**\n * Next.js client components. `PreviewBarHost` goes in the site's root layout (rendered only in\n * draft mode) and follows the realtime preview hub when given a live ticket; `PreviewBarFrame` and\n * `PreviewLinkErrorFrame` render the bar's page and the expired-link page. React and Sanity UI load only from the frames' dynamic imports, so the host\n * stays a few KB.\n */\nimport {usePathname, useRouter} from 'next/navigation'\nimport {useCallback, useEffect, useRef, useState, useTransition} from 'react'\n\nimport type {PreviewBarData, PreviewLinkErrorData} from '../core/data'\nimport {isPreviewBarFrame} from '../core/protocol'\nimport {isTopWindow, type PreviewBarHost as Host} from '../host'\nimport type {LiveTicket} from './index'\n\n/** The hub a ticket names (`<hub>.<expires>.<signature>`), to tell when the tab must move. */\nfunction ticketHub(ticket: string | undefined) {\n if (!ticket) return null\n const last = ticket.lastIndexOf('.')\n const middle = ticket.lastIndexOf('.', last - 1)\n return middle > 0 ? ticket.slice(0, middle) : null\n}\n\n/**\n * Mounts the bar's frame in the top window while draft mode is on. In the Studio's Visual Editor\n * tool's frame (`isPreviewBarFrame()`), it answers the tool instead (`mountPreviewBarFrame`): the\n * tool shows its own bar above the page. Other frames are skipped.\n *\n * With `live` (`await visualEditor.live()`), it follows the realtime preview hub and calls\n * `router.refresh()` when a result the page read changes: the Server Components run again and\n * read the new result from the hub. One refresh at a time; changes that arrive meanwhile are\n * picked up by one more.\n */\nexport function PreviewBarHost({basePath, live}: {basePath?: string; live?: LiveTicket | null}) {\n const router = useRouter()\n const pathname = usePathname()\n const [host, setHost] = useState<Host | null>(null)\n const [refreshing, startRefresh] = useTransition()\n const refreshingRef = useRef(false)\n const stale = useRef(false)\n refreshingRef.current = refreshing\n\n const refresh = useCallback(() => {\n if (refreshingRef.current) {\n stale.current = true\n return\n }\n startRefresh(() => router.refresh())\n }, [router])\n\n useEffect(() => {\n if (refreshing || !stale.current) return\n stale.current = false\n startRefresh(() => router.refresh())\n }, [refreshing, router])\n\n // The ticket changes hourly (and with the perspective); the socket only moves with its hub.\n const hub = ticketHub(live?.ticket)\n const ticket = useRef(live?.ticket)\n ticket.current = live?.ticket\n\n useEffect(() => {\n if (!host || !hub || !ticket.current) return\n let cancelled = false\n let stop: (() => void) | undefined\n const params = {ticket: ticket.current}\n import('../host').then(({subscribePreviewEvents}) => {\n if (cancelled) return\n stop = subscribePreviewEvents(refresh, {\n params,\n onStatus: (status) => host.setLiveStatus(status),\n })\n })\n return () => {\n cancelled = true\n stop?.()\n }\n }, [host, hub, refresh])\n\n useEffect(() => {\n const frame = isPreviewBarFrame()\n if (!frame && !isTopWindow()) return\n let cancelled = false\n let mounted: Host | undefined\n import('../host').then(({mountPreviewBarHost, mountPreviewBarFrame}) => {\n if (cancelled) return\n const options = {\n // Server components rerun with the new perspective cookie; client state stays.\n refresh: () => router.refresh(),\n navigate: (href: string) => router.push(href),\n }\n mounted = frame ? mountPreviewBarFrame(options) : mountPreviewBarHost({...options, basePath})\n setHost(mounted)\n })\n return () => {\n cancelled = true\n mounted?.destroy()\n setHost(null)\n }\n }, [basePath, router])\n\n // Keep the bar's path current after client-side navigation.\n useEffect(() => {\n host?.setPath(window.location.pathname + window.location.search)\n }, [host, pathname])\n\n return null\n}\n\ntype BarModule = typeof import('../bar')\n\n/**\n * Mounts a React root from the lazily loaded bar module into this component's element. The\n * cancellation check runs before mounting, so React's development double-run of effects never\n * mounts two roots on one element.\n */\nfunction useMounted(mount: (bar: BarModule, element: HTMLElement) => () => void, deps: unknown[]) {\n const ref = useRef<HTMLDivElement>(null)\n useEffect(() => {\n const element = ref.current\n if (!element) return\n let unmount: (() => void) | undefined\n let cancelled = false\n import('../bar').then((bar) => {\n if (!cancelled) unmount = mount(bar, element)\n })\n return () => {\n cancelled = true\n unmount?.()\n }\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, deps)\n return ref\n}\n\n/** The bar itself, for `app/__visual-editor/page.tsx`. */\nexport function PreviewBarFrame({data}: {data: PreviewBarData}) {\n const ref = useMounted(({mountPreviewBar}, element) => mountPreviewBar(element, data), [data])\n return <div ref={ref} style={{height: '100%'}} />\n}\n\n/** The expired-link page, for `/p/[code]` and its `not-found.tsx`. */\nexport function PreviewLinkErrorFrame(props: PreviewLinkErrorData) {\n const ref = useMounted(\n ({mountPreviewLinkError}, element) => mountPreviewLinkError(element, props),\n [props.expired, props.brand, props.studioPath],\n )\n return <div ref={ref} />\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,SAAS,UAAU,QAA4B;CAC7C,IAAI,CAAC,QAAQ,OAAO;CACpB,IAAM,OAAO,OAAO,YAAY,GAAG,GAC7B,SAA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reviewBarOptions, r as PreviewClient, t as PreviewBar } from "./index-hDzatlg7.js";
3
+ import { validatePreviewUrl } from "@sanity/preview-url-secret";
4
+ export type NextPreviewBarOptions = {
5
+ /** From `createPreviewBar` (`sanity-plugin-visual-editor/server`). */
6
+ bar: PreviewBar;
7
+ /** A server Sanity client with a read token (e.g. `client.withConfig({token})`). */
8
+ client: PreviewClient;
9
+ };
10
+ type RouteContext = {
11
+ params: Promise<Record<string, string | string[] | undefined>>;
12
+ };
13
+ export declare function createNextPreviewBar(options: NextPreviewBarOptions): {
14
+ /** `app/__visual-editor/[action]/route.ts`: `export const {GET, POST} = previewBar.handlers`. */
15
+ handlers: {
16
+ GET: (request: Request, { params }: RouteContext) => Promise<Response>;
17
+ POST: (request: Request, { params }: RouteContext) => Promise<Response>;
18
+ };
19
+ /**
20
+ * `app/__visual-editor/page.tsx`: the bar's data, or a 404 outside draft mode. Pass it to
21
+ * `<PreviewBarFrame data={…} />`.
22
+ */
23
+ loadBar(): Promise<PreviewBarData>;
24
+ /**
25
+ * `app/p/[code]/page.tsx`: redirects a live link to the open handler; calls `notFound()` for
26
+ * an unknown, malformed or expired one (render `<PreviewLinkErrorFrame expired />` in that
27
+ * segment's `not-found.tsx`). Returns `'unavailable'` when the store can't be read, for the
28
+ * page to render `<PreviewLinkErrorFrame expired={false} />`.
29
+ */
30
+ checkLink(code: string): Promise<"unavailable">;
31
+ /**
32
+ * `app/__visual-editor/open/[code]/route.ts`: `export const GET = previewBar.openLink`. Turns
33
+ * draft mode on until the link expires, marks the session as opened from a link (so it can't
34
+ * mint links), sets the stored perspective and redirects to the stored page; a link that has
35
+ * gone meanwhile goes back to `/p/<code>` for the expired page.
36
+ */
37
+ openLink(request: Request, { params }: RouteContext): Promise<Response>;
38
+ };
39
+ export type NextPreviewBar = ReturnType<typeof createNextPreviewBar>;
40
+ /** What a draft-mode page hands its tab to follow the hub: see `PreviewBarHost`'s `live`. */
41
+ export type LiveTicket = {
42
+ ticket: string;
43
+ };
44
+ export type NextVisualEditorOptions = PreviewBarOptions & {
45
+ /** A server Sanity client with a read token (e.g. `client.withConfig({token})`). */
46
+ client: PreviewClient & Parameters<typeof validatePreviewUrl>[0];
47
+ /**
48
+ * The realtime preview hub's service binding, e.g. `() => getCloudflareContext().env.PREVIEW_HUB`.
49
+ * Without it (or when it returns `undefined`), there is no live preview: `live()` and `hub()`
50
+ * return `null` and the site reads Sanity directly.
51
+ */
52
+ hub?: () => PreviewHubFetcher | undefined;
53
+ /**
54
+ * Signs live tickets and the Studio's live-edit cookie; without it there is no live preview,
55
+ * as without `hub`. The Worker entry (`createPreviewRoutes(...).upgrade`) must use the same value.
56
+ */
57
+ secret?: string | (() => string);
58
+ /** The hub routes' base path. Default `/api/preview`. */
59
+ routesPath?: string;
60
+ };
61
+ /**
62
+ * One-stop Next.js setup: the preview bar (`createPreviewBar` + `createNextPreviewBar`) and the
63
+ * realtime preview hub. Route files re-export its handlers; see the README.
64
+ */
65
+ export declare function createNextVisualEditor(options: NextVisualEditorOptions): {
66
+ bar: {
67
+ /** `app/__visual-editor/[action]/route.ts`: `export const {GET, POST} = previewBar.handlers`. */
68
+ handlers: {
69
+ GET: (request: Request, { params }: RouteContext) => Promise<Response>;
70
+ POST: (request: Request, { params }: RouteContext) => Promise<Response>;
71
+ };
72
+ /**
73
+ * `app/__visual-editor/page.tsx`: the bar's data, or a 404 outside draft mode. Pass it to
74
+ * `<PreviewBarFrame data={…} />`.
75
+ */
76
+ loadBar(): Promise<PreviewBarData>;
77
+ /**
78
+ * `app/p/[code]/page.tsx`: redirects a live link to the open handler; calls `notFound()` for
79
+ * an unknown, malformed or expired one (render `<PreviewLinkErrorFrame expired />` in that
80
+ * segment's `not-found.tsx`). Returns `'unavailable'` when the store can't be read, for the
81
+ * page to render `<PreviewLinkErrorFrame expired={false} />`.
82
+ */
83
+ checkLink(code: string): Promise<"unavailable">;
84
+ /**
85
+ * `app/__visual-editor/open/[code]/route.ts`: `export const GET = previewBar.openLink`. Turns
86
+ * draft mode on until the link expires, marks the session as opened from a link (so it can't
87
+ * mint links), sets the stored perspective and redirects to the stored page; a link that has
88
+ * gone meanwhile goes back to `/p/<code>` for the expired page.
89
+ */
90
+ openLink(request: Request, { params }: RouteContext): Promise<Response>;
91
+ };
92
+ /** `app/api/preview/[...path]/route.ts`: `export const {GET, POST} = visualEditor.routes`. */
93
+ routes: {
94
+ GET: (request: Request) => Promise<Response>;
95
+ POST: (request: Request) => Promise<Response>;
96
+ };
97
+ /**
98
+ * For the root layout, in draft mode: `<PreviewBarHost live={await visualEditor.live()} />`.
99
+ * A signed ticket for this request's hub, or `null` when there is nothing to follow
100
+ * (no hub binding, draft mode off, or the Published perspective). Fresh on every render, so a
101
+ * perspective switch (which refreshes the page) moves the tab to the new hub.
102
+ */
103
+ live(): Promise<LiveTicket | null>;
104
+ /**
105
+ * For Server Components' reads in draft mode: this request's hub, or `null` (read Sanity as
106
+ * usual). `await hub.query(query, params)` returns the result, unsaved Studio edits included.
107
+ */
108
+ hub(): Promise<PreviewHub | null>;
109
+ /** `app/__visual-editor/[action]/route.ts`: `export const {GET, POST} = previewBar.handlers`. */
110
+ handlers: {
111
+ GET: (request: Request, { params }: RouteContext) => Promise<Response>;
112
+ POST: (request: Request, { params }: RouteContext) => Promise<Response>;
113
+ };
114
+ /**
115
+ * `app/__visual-editor/page.tsx`: the bar's data, or a 404 outside draft mode. Pass it to
116
+ * `<PreviewBarFrame data={…} />`.
117
+ */
118
+ loadBar(): Promise<PreviewBarData>;
119
+ /**
120
+ * `app/p/[code]/page.tsx`: redirects a live link to the open handler; calls `notFound()` for
121
+ * an unknown, malformed or expired one (render `<PreviewLinkErrorFrame expired />` in that
122
+ * segment's `not-found.tsx`). Returns `'unavailable'` when the store can't be read, for the
123
+ * page to render `<PreviewLinkErrorFrame expired={false} />`.
124
+ */
125
+ checkLink(code: string): Promise<"unavailable">;
126
+ /**
127
+ * `app/__visual-editor/open/[code]/route.ts`: `export const GET = previewBar.openLink`. Turns
128
+ * draft mode on until the link expires, marks the session as opened from a link (so it can't
129
+ * mint links), sets the stored perspective and redirects to the stored page; a link that has
130
+ * gone meanwhile goes back to `/p/<code>` for the expired page.
131
+ */
132
+ openLink(request: Request, { params }: RouteContext): Promise<Response>;
133
+ };
134
+ export type NextVisualEditor = ReturnType<typeof createNextVisualEditor>;
135
+ export {};
package/dist/next.js ADDED
@@ -0,0 +1,176 @@
1
+ import { c as parsePerspective, m as serializePerspective, n as PERSPECTIVE_COOKIE } from "./perspective-BmS9TVtr.js";
2
+ import { _ as createPreviewHubClient, g as createLiveTicket, t as createPreviewBar, u as createPreviewRoutes, v as previewHubName, x as LINK_SESSION_COOKIE } from "./server-B8MqMyaN.js";
3
+ import { cookies, draftMode, headers } from "next/headers";
4
+ import { notFound, redirect } from "next/navigation";
5
+ /**
6
+ * Next.js (App Router) adapter, for sites using `next-sanity`'s draft mode. Server side: route
7
+ * handlers, the bar page's data, the short-link checks and the realtime preview hub. The client
8
+ * components live in `sanity-plugin-visual-editor/next/client`. See the README for the routes.
9
+ *
10
+ * Live preview keeps Next's own model: Server Components fetch, and draft mode skips every cache.
11
+ * In draft mode they read through the hub (`visualEditor.hub()`), which holds each result in
12
+ * memory, Studio keystrokes included. The tab follows the hub over a WebSocket and calls
13
+ * `router.refresh()` when a result it shows changes, so the Server Components run again and read
14
+ * the new result. No `revalidateTag`: draft requests never touch the cache.
15
+ *
16
+ * Opening a short link takes two steps because a page can't set cookies while it renders:
17
+ * `/p/[code]` checks the link (rendering the expired page with a 404 when it's gone) and redirects
18
+ * live ones to `<basePath>/open/<code>`, a route handler that turns draft mode on and redirects to
19
+ * the stored page.
20
+ *
21
+ * Draft mode is one cookie (`__prerender_bypass`) whose value is fixed per build, so a link's
22
+ * recipient holds a value that turns draft mode on until the next deploy. `openLink` caps that
23
+ * cookie's lifetime to the link's, and marks the session so it can't mint links, but a recipient
24
+ * who copies the cookie by hand keeps draft mode until the next build. See the README.
25
+ */
26
+ /** Next's draft mode cookie. */
27
+ const DRAFT_MODE_COOKIE = "__prerender_bypass";
28
+ function param(value) {
29
+ return Array.isArray(value) ? value[0] : value;
30
+ }
31
+ /** `next-sanity` and Next's draft mode use these attributes: `None; Secure` off localhost. */
32
+ function cookieOptions(secure) {
33
+ return {
34
+ httpOnly: !0,
35
+ path: "/",
36
+ sameSite: secure ? "none" : "lax",
37
+ secure
38
+ };
39
+ }
40
+ function createNextPreviewBar(options) {
41
+ let { bar, client } = options, basePath = bar.options.basePath;
42
+ async function context(request) {
43
+ let jar = await cookies(), linkExpires = Number(jar.get(LINK_SESSION_COOKIE)?.value);
44
+ return {
45
+ request,
46
+ previewEnabled: (await draftMode()).isEnabled,
47
+ client,
48
+ perspective: parsePerspective(jar.get(PERSPECTIVE_COOKIE)?.value),
49
+ linkSession: Number.isFinite(linkExpires) && linkExpires * 1e3 > Date.now()
50
+ };
51
+ }
52
+ /** A stand-in request for server components, which have headers but no `Request`. */
53
+ async function currentRequest() {
54
+ let list = await headers(), host = list.get("x-forwarded-host") ?? list.get("host") ?? "localhost", protocol = list.get("x-forwarded-proto") ?? (host.startsWith("localhost") ? "http" : "https");
55
+ return new Request(`${protocol}://${host}${basePath}`, { headers: list });
56
+ }
57
+ async function handle(request, { params }) {
58
+ let action = param((await params).action);
59
+ if (request.method === "GET" && action === "document") return bar.pageDocument(await context(request));
60
+ if (request.method === "GET" && action === "resolve") return bar.resolveHref(await context(request));
61
+ if (request.method === "POST") switch (action) {
62
+ case "perspective": return bar.perspective(await context(request));
63
+ case "share": return bar.share(await context(request));
64
+ case "exit": return bar.exit({ request }, async () => {
65
+ (await draftMode()).disable(), (await cookies()).delete(LINK_SESSION_COOKIE);
66
+ });
67
+ }
68
+ return new Response("Not found", { status: 404 });
69
+ }
70
+ return {
71
+ /** `app/__visual-editor/[action]/route.ts`: `export const {GET, POST} = previewBar.handlers`. */
72
+ handlers: {
73
+ GET: handle,
74
+ POST: handle
75
+ },
76
+ /**
77
+ * `app/__visual-editor/page.tsx`: the bar's data, or a 404 outside draft mode. Pass it to
78
+ * `<PreviewBarFrame data={…} />`.
79
+ */
80
+ async loadBar() {
81
+ let data = await bar.loadBar(await context(await currentRequest()));
82
+ return data || notFound(), data;
83
+ },
84
+ /**
85
+ * `app/p/[code]/page.tsx`: redirects a live link to the open handler; calls `notFound()` for
86
+ * an unknown, malformed or expired one (render `<PreviewLinkErrorFrame expired />` in that
87
+ * segment's `not-found.tsx`). Returns `'unavailable'` when the store can't be read, for the
88
+ * page to render `<PreviewLinkErrorFrame expired={false} />`.
89
+ */
90
+ async checkLink(code) {
91
+ let result = await bar.resolveLink(code);
92
+ return result.status === 200 && redirect(`${basePath}/open/${code}`), result.status === 404 && notFound(), "unavailable";
93
+ },
94
+ /**
95
+ * `app/__visual-editor/open/[code]/route.ts`: `export const GET = previewBar.openLink`. Turns
96
+ * draft mode on until the link expires, marks the session as opened from a link (so it can't
97
+ * mint links), sets the stored perspective and redirects to the stored page; a link that has
98
+ * gone meanwhile goes back to `/p/<code>` for the expired page.
99
+ */
100
+ async openLink(request, { params }) {
101
+ let code = param((await params).code) ?? "", result = await bar.resolveLink(code);
102
+ result.status !== 200 && redirect(`${bar.options.linkRoute}${code}`);
103
+ let { expiresAt } = result.link, maxAge = Math.floor((expiresAt - Date.now()) / 1e3);
104
+ maxAge <= 0 && redirect(`${bar.options.linkRoute}${code}`);
105
+ let options = cookieOptions(new URL(request.url).protocol === "https:"), jar = await cookies(), draft = await draftMode();
106
+ if (!draft.isEnabled) {
107
+ draft.enable();
108
+ let bypass = jar.get(DRAFT_MODE_COOKIE)?.value;
109
+ bypass && jar.set(DRAFT_MODE_COOKIE, bypass, {
110
+ ...options,
111
+ maxAge
112
+ }), jar.set(LINK_SESSION_COOKIE, String(Math.floor(expiresAt / 1e3)), {
113
+ ...options,
114
+ maxAge
115
+ });
116
+ }
117
+ jar.set(PERSPECTIVE_COOKIE, serializePerspective(result.link.perspective), options), redirect(result.link.pathname);
118
+ }
119
+ };
120
+ }
121
+ /**
122
+ * One-stop Next.js setup: the preview bar (`createPreviewBar` + `createNextPreviewBar`) and the
123
+ * realtime preview hub. Route files re-export its handlers; see the README.
124
+ */
125
+ function createNextVisualEditor(options) {
126
+ let { client, hub: hubBinding, secret, routesPath, ...barOptions } = options, bar = createNextPreviewBar({
127
+ bar: createPreviewBar(barOptions),
128
+ client
129
+ }), getService = () => hubBinding?.(), { hubFor } = createPreviewHubClient(getService), getSecret = () => (typeof secret == "function" ? secret() : secret) ?? "";
130
+ /** This request's hub name: draft mode on, a preview perspective, a hub binding and a secret. */
131
+ async function requestHub() {
132
+ if (!hubBinding || !getService() || !getSecret() || !(await draftMode()).isEnabled) return null;
133
+ let perspective = parsePerspective((await cookies()).get(PERSPECTIVE_COOKIE)?.value);
134
+ return previewHubName(perspective);
135
+ }
136
+ let routes = createPreviewRoutes({
137
+ secret: getSecret,
138
+ hub: getService,
139
+ client,
140
+ basePath: routesPath,
141
+ fallbackHub: requestHub
142
+ });
143
+ async function handleRoute(request) {
144
+ return await routes.handle(request) ?? new Response("Not found", { status: 404 });
145
+ }
146
+ return {
147
+ ...bar,
148
+ bar,
149
+ /** `app/api/preview/[...path]/route.ts`: `export const {GET, POST} = visualEditor.routes`. */
150
+ routes: {
151
+ GET: handleRoute,
152
+ POST: handleRoute
153
+ },
154
+ /**
155
+ * For the root layout, in draft mode: `<PreviewBarHost live={await visualEditor.live()} />`.
156
+ * A signed ticket for this request's hub, or `null` when there is nothing to follow
157
+ * (no hub binding, draft mode off, or the Published perspective). Fresh on every render, so a
158
+ * perspective switch (which refreshes the page) moves the tab to the new hub.
159
+ */
160
+ async live() {
161
+ let name = await requestHub();
162
+ return name ? { ticket: await createLiveTicket(getSecret(), name) } : null;
163
+ },
164
+ /**
165
+ * For Server Components' reads in draft mode: this request's hub, or `null` (read Sanity as
166
+ * usual). `await hub.query(query, params)` returns the result, unsaved Studio edits included.
167
+ */
168
+ async hub() {
169
+ let name = await requestHub();
170
+ return name ? hubFor(name) : null;
171
+ }
172
+ };
173
+ }
174
+ export { createNextPreviewBar, createNextVisualEditor };
175
+
176
+ //# sourceMappingURL=next.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"next.js","names":[],"sources":["../src/next/index.ts"],"sourcesContent":["/**\n * Next.js (App Router) adapter, for sites using `next-sanity`'s draft mode. Server side: route\n * handlers, the bar page's data, the short-link checks and the realtime preview hub. The client\n * components live in `sanity-plugin-visual-editor/next/client`. See the README for the routes.\n *\n * Live preview keeps Next's own model: Server Components fetch, and draft mode skips every cache.\n * In draft mode they read through the hub (`visualEditor.hub()`), which holds each result in\n * memory, Studio keystrokes included. The tab follows the hub over a WebSocket and calls\n * `router.refresh()` when a result it shows changes, so the Server Components run again and read\n * the new result. No `revalidateTag`: draft requests never touch the cache.\n *\n * Opening a short link takes two steps because a page can't set cookies while it renders:\n * `/p/[code]` checks the link (rendering the expired page with a 404 when it's gone) and redirects\n * live ones to `<basePath>/open/<code>`, a route handler that turns draft mode on and redirects to\n * the stored page.\n *\n * Draft mode is one cookie (`__prerender_bypass`) whose value is fixed per build, so a link's\n * recipient holds a value that turns draft mode on until the next deploy. `openLink` caps that\n * cookie's lifetime to the link's, and marks the session so it can't mint links, but a recipient\n * who copies the cookie by hand keeps draft mode until the next build. See the README.\n */\nimport {cookies, draftMode, headers} from 'next/headers'\nimport {notFound, redirect} from 'next/navigation'\n\nimport type {validatePreviewUrl} from '@sanity/preview-url-secret'\n\nimport type {PreviewBarData} from '../core/data'\nimport {parsePerspective, PERSPECTIVE_COOKIE, serializePerspective} from '../core/perspective'\nimport {\n createPreviewBar,\n createPreviewHubClient,\n createLiveTicket,\n createPreviewRoutes,\n previewHubName,\n type PreviewBar,\n type PreviewBarOptions,\n type PreviewClient,\n type PreviewContext,\n type PreviewHub,\n type PreviewHubFetcher,\n} from '../server'\nimport {LINK_SESSION_COOKIE} from '../server/link-session'\n\n/** Next's draft mode cookie. */\nconst DRAFT_MODE_COOKIE = '__prerender_bypass'\n\nexport type NextPreviewBarOptions = {\n /** From `createPreviewBar` (`sanity-plugin-visual-editor/server`). */\n bar: PreviewBar\n /** A server Sanity client with a read token (e.g. `client.withConfig({token})`). */\n client: PreviewClient\n}\n\ntype RouteContext = {params: Promise<Record<string, string | string[] | undefined>>}\n\nfunction param(value: string | string[] | undefined) {\n return Array.isArray(value) ? value[0] : value\n}\n\n/** `next-sanity` and Next's draft mode use these attributes: `None; Secure` off localhost. */\nfunction cookieOptions(secure: boolean) {\n return {httpOnly: true, path: '/', sameSite: secure ? 'none' : 'lax', secure} as const\n}\n\nexport function createNextPreviewBar(options: NextPreviewBarOptions) {\n const {bar, client} = options\n const basePath = bar.options.basePath\n\n async function context(request: Request): Promise<PreviewContext> {\n const jar = await cookies()\n // The marker holds the link's expiry (seconds); a stale one doesn't count.\n const linkExpires = Number(jar.get(LINK_SESSION_COOKIE)?.value)\n return {\n request,\n previewEnabled: (await draftMode()).isEnabled,\n client,\n perspective: parsePerspective(jar.get(PERSPECTIVE_COOKIE)?.value),\n linkSession: Number.isFinite(linkExpires) && linkExpires * 1000 > Date.now(),\n }\n }\n\n /** A stand-in request for server components, which have headers but no `Request`. */\n async function currentRequest() {\n const list = await headers()\n const host = list.get('x-forwarded-host') ?? list.get('host') ?? 'localhost'\n const protocol =\n list.get('x-forwarded-proto') ?? (host.startsWith('localhost') ? 'http' : 'https')\n return new Request(`${protocol}://${host}${basePath}`, {headers: list})\n }\n\n async function handle(request: Request, {params}: RouteContext) {\n const action = param((await params).action)\n if (request.method === 'GET' && action === 'document') {\n return bar.pageDocument(await context(request))\n }\n if (request.method === 'GET' && action === 'resolve') {\n return bar.resolveHref(await context(request))\n }\n if (request.method === 'POST') {\n switch (action) {\n case 'perspective':\n return bar.perspective(await context(request))\n case 'share':\n return bar.share(await context(request))\n case 'exit':\n // Draft mode's own cookie goes through Next, which merges it into the response.\n return bar.exit({request}, async () => {\n ;(await draftMode()).disable()\n ;(await cookies()).delete(LINK_SESSION_COOKIE)\n })\n }\n }\n return new Response('Not found', {status: 404})\n }\n\n return {\n /** `app/__visual-editor/[action]/route.ts`: `export const {GET, POST} = previewBar.handlers`. */\n handlers: {GET: handle, POST: handle},\n\n /**\n * `app/__visual-editor/page.tsx`: the bar's data, or a 404 outside draft mode. Pass it to\n * `<PreviewBarFrame data={…} />`.\n */\n async loadBar(): Promise<PreviewBarData> {\n const data = await bar.loadBar(await context(await currentRequest()))\n if (!data) notFound()\n return data\n },\n\n /**\n * `app/p/[code]/page.tsx`: redirects a live link to the open handler; calls `notFound()` for\n * an unknown, malformed or expired one (render `<PreviewLinkErrorFrame expired />` in that\n * segment's `not-found.tsx`). Returns `'unavailable'` when the store can't be read, for the\n * page to render `<PreviewLinkErrorFrame expired={false} />`.\n */\n async checkLink(code: string): Promise<'unavailable'> {\n const result = await bar.resolveLink(code)\n if (result.status === 200) redirect(`${basePath}/open/${code}`)\n if (result.status === 404) notFound()\n return 'unavailable'\n },\n\n /**\n * `app/__visual-editor/open/[code]/route.ts`: `export const GET = previewBar.openLink`. Turns\n * draft mode on until the link expires, marks the session as opened from a link (so it can't\n * mint links), sets the stored perspective and redirects to the stored page; a link that has\n * gone meanwhile goes back to `/p/<code>` for the expired page.\n */\n async openLink(request: Request, {params}: RouteContext): Promise<Response> {\n const code = param((await params).code) ?? ''\n const result = await bar.resolveLink(code)\n if (result.status !== 200) redirect(`${bar.options.linkRoute}${code}`)\n const {expiresAt} = result.link\n const maxAge = Math.floor((expiresAt - Date.now()) / 1000)\n if (maxAge <= 0) redirect(`${bar.options.linkRoute}${code}`)\n const secure = new URL(request.url).protocol === 'https:'\n const options = cookieOptions(secure)\n const jar = await cookies()\n const draft = await draftMode()\n // A recipient already in draft mode (an editor) keeps their own session, unmarked.\n if (!draft.isEnabled) {\n draft.enable()\n // `enable()` sets a session cookie; set it again with the link's lifetime. Its value is\n // fixed per build, so this bounds the browser's copy, not a copy taken by hand.\n const bypass = jar.get(DRAFT_MODE_COOKIE)?.value\n if (bypass) jar.set(DRAFT_MODE_COOKIE, bypass, {...options, maxAge})\n jar.set(LINK_SESSION_COOKIE, String(Math.floor(expiresAt / 1000)), {...options, maxAge})\n }\n jar.set(PERSPECTIVE_COOKIE, serializePerspective(result.link.perspective), options)\n redirect(result.link.pathname)\n },\n }\n}\n\nexport type NextPreviewBar = ReturnType<typeof createNextPreviewBar>\n\n/** What a draft-mode page hands its tab to follow the hub: see `PreviewBarHost`'s `live`. */\nexport type LiveTicket = {ticket: string}\n\nexport type NextVisualEditorOptions = PreviewBarOptions & {\n /** A server Sanity client with a read token (e.g. `client.withConfig({token})`). */\n client: PreviewClient & Parameters<typeof validatePreviewUrl>[0]\n /**\n * The realtime preview hub's service binding, e.g. `() => getCloudflareContext().env.PREVIEW_HUB`.\n * Without it (or when it returns `undefined`), there is no live preview: `live()` and `hub()`\n * return `null` and the site reads Sanity directly.\n */\n hub?: () => PreviewHubFetcher | undefined\n /**\n * Signs live tickets and the Studio's live-edit cookie; without it there is no live preview,\n * as without `hub`. The Worker entry (`createPreviewRoutes(...).upgrade`) must use the same value.\n */\n secret?: string | (() => string)\n /** The hub routes' base path. Default `/api/preview`. */\n routesPath?: string\n}\n\n/**\n * One-stop Next.js setup: the preview bar (`createPreviewBar` + `createNextPreviewBar`) and the\n * realtime preview hub. Route files re-export its handlers; see the README.\n */\nexport function createNextVisualEditor(options: NextVisualEditorOptions) {\n const {client, hub: hubBinding, secret, routesPath, ...barOptions} = options\n const bar = createNextPreviewBar({bar: createPreviewBar(barOptions), client})\n const getService = () => hubBinding?.()\n const {hubFor} = createPreviewHubClient(getService)\n const getSecret = () => (typeof secret === 'function' ? secret() : secret) ?? ''\n\n /** This request's hub name: draft mode on, a preview perspective, a hub binding and a secret. */\n async function requestHub(): Promise<string | null> {\n if (!hubBinding || !getService() || !getSecret()) return null\n if (!(await draftMode()).isEnabled) return null\n const perspective = parsePerspective((await cookies()).get(PERSPECTIVE_COOKIE)?.value)\n return previewHubName(perspective)\n }\n\n const routes = createPreviewRoutes({\n secret: getSecret,\n hub: getService,\n client,\n basePath: routesPath,\n fallbackHub: requestHub,\n })\n\n async function handleRoute(request: Request) {\n return (await routes.handle(request)) ?? new Response('Not found', {status: 404})\n }\n\n return {\n ...bar,\n bar,\n\n /** `app/api/preview/[...path]/route.ts`: `export const {GET, POST} = visualEditor.routes`. */\n routes: {GET: handleRoute, POST: handleRoute},\n\n /**\n * For the root layout, in draft mode: `<PreviewBarHost live={await visualEditor.live()} />`.\n * A signed ticket for this request's hub, or `null` when there is nothing to follow\n * (no hub binding, draft mode off, or the Published perspective). Fresh on every render, so a\n * perspective switch (which refreshes the page) moves the tab to the new hub.\n */\n async live(): Promise<LiveTicket | null> {\n const name = await requestHub()\n return name ? {ticket: await createLiveTicket(getSecret(), name)} : null\n },\n\n /**\n * For Server Components' reads in draft mode: this request's hub, or `null` (read Sanity as\n * usual). `await hub.query(query, params)` returns the result, unsaved Studio edits included.\n */\n async hub(): Promise<PreviewHub | null> {\n const name = await requestHub()\n return name ? hubFor(name) : null\n },\n }\n}\n\nexport type NextVisualEditor = ReturnType<typeof createNextVisualEditor>\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA4CA,MAAM,oBAAoB;AAW1B,SAAS,MAAM,OAAsC;CACnD,OAAO,MAAM,QAAQ,KAAK,IAAI,MAAM,KAAK;AAC3C;;AAGA,SAAS,cAAc,QAAiB;CACtC,OAAO;EAAC,UAAU;EAAM,MAAM;EAAK,UAAU,SAAS,SAAS;EAAO;CAAM;AAC9E;AAEA,SAAgB,qBAAqB,SAAgC;CACnE,IAAM,EAAC,KAAK,WAAU,SAChB,WAAW,IAAI,QAAQ;CAE7B,eAAe,QAAQ,SAA2C;EAChE,IAAM,MAAM,MAAM,QAAQ,GAEpB,cAAc,OAAO,IAAI,IAAI,mBAAmB,CAAC,EAAE,KAAK;EAC9D,OAAO;GACL;GACA,iBAAiB,MAAM,UAAU,EAAA,CAAG;GACpC;GACA,aAAa,iBAAiB,IAAI,IAAI,kBAAkB,CAAC,EAAE,KAAK;GAChE,aA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