sanity-plugin-visual-editor 1.0.0 → 1.1.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.
- package/LICENSE +1 -1
- package/README.md +137 -16
- package/TESTING.md +133 -0
- package/dist/PreviewBar-D_rw0bhP.js +3503 -0
- package/dist/PreviewBar-D_rw0bhP.js.map +1 -0
- package/dist/bar.d.ts +22 -0
- package/dist/bar.js +67 -0
- package/dist/bar.js.map +1 -0
- package/dist/cloudflare.d.ts +76 -0
- package/dist/cloudflare.js +1071 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/data-D0qotTtt.d.ts +177 -0
- package/dist/host-DreYJEmR.js +615 -0
- package/dist/host-DreYJEmR.js.map +1 -0
- package/dist/host.d.ts +160 -0
- package/dist/host.js +3 -0
- package/dist/index-4Zm_NjhC.d.ts +221 -0
- package/dist/index.d.ts +18 -18
- package/dist/index.js +7 -8
- package/dist/link-search-JtZkxz4k.js +14 -0
- package/dist/link-search-JtZkxz4k.js.map +1 -0
- package/dist/link-session-Dr4YkKFy.js +52 -0
- package/dist/link-session-Dr4YkKFy.js.map +1 -0
- package/dist/next-client.d.ts +15 -0
- package/dist/next-client.js +78 -0
- package/dist/next-client.js.map +1 -0
- package/dist/next.d.ts +38 -0
- package/dist/next.js +117 -0
- package/dist/next.js.map +1 -0
- package/dist/node-labels-CDiW5rMq.js +122 -0
- package/dist/node-labels-CDiW5rMq.js.map +1 -0
- package/dist/page-documents-BFFcH8lD.d.ts +54 -0
- package/dist/page-documents-mGfw_flR.js +67 -0
- package/dist/page-documents-mGfw_flR.js.map +1 -0
- package/dist/perspective-BmS9TVtr.js +106 -0
- package/dist/perspective-BmS9TVtr.js.map +1 -0
- package/dist/preview-links-BZDZyIey.js +119 -0
- package/dist/preview-links-BZDZyIey.js.map +1 -0
- package/dist/preview-links-DM6BCiLV.d.ts +87 -0
- package/dist/protocol-BNO38gYy.js +280 -0
- package/dist/protocol-BNO38gYy.js.map +1 -0
- package/dist/protocol-BnRCy2wJ.d.ts +386 -0
- package/dist/server.d.ts +4 -0
- package/dist/server.js +495 -0
- package/dist/server.js.map +1 -0
- package/dist/shell-DZotxRXX.d.ts +37 -0
- package/dist/studio.d.ts +93 -0
- package/dist/studio.js +1263 -0
- package/dist/studio.js.map +1 -0
- package/dist/sveltekit.d.ts +281 -0
- package/dist/sveltekit.js +395 -0
- package/dist/sveltekit.js.map +1 -0
- package/package.json +120 -39
- package/dist/index.d.mts +0 -21
- package/dist/index.js.map +0 -1
- package/dist/index.mjs +0 -8
- package/dist/index.mjs.map +0 -1
- package/sanity.json +0 -8
- package/src/index.ts +0 -27
- package/v2-incompatible.js +0 -11
|
@@ -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,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Signed, expiring link-session cookies: what a `/p/<code>` link leaves in the browser instead of
|
|
3
|
+
* the site's preview secret. The value is `<expires>.<signature>`, where `expires` is in seconds
|
|
4
|
+
* since the epoch and the signature is HMAC-SHA-256 over it, keyed with the preview secret. It
|
|
5
|
+
* proves "opened a live share link, valid until `expires`" and nothing else, so copying it gains
|
|
6
|
+
* no more than the link itself gave.
|
|
7
|
+
*/
|
|
8
|
+
/** The link-session cookie's default name. */
|
|
9
|
+
const LINK_SESSION_COOKIE = "__sanity_preview_link", encoder = new TextEncoder(), LABEL = "sanity-preview-bar/link-session/v1:";
|
|
10
|
+
function key(secret) {
|
|
11
|
+
if (!secret) throw Error("sanity-visual-editor: the preview secret is empty");
|
|
12
|
+
return crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
13
|
+
name: "HMAC",
|
|
14
|
+
hash: "SHA-256"
|
|
15
|
+
}, !1, ["sign", "verify"]);
|
|
16
|
+
}
|
|
17
|
+
function toBase64Url(bytes) {
|
|
18
|
+
let binary = "";
|
|
19
|
+
for (let byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);
|
|
20
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
21
|
+
}
|
|
22
|
+
function fromBase64Url(value) {
|
|
23
|
+
if (!/^[A-Za-z0-9_-]+$/.test(value)) return null;
|
|
24
|
+
try {
|
|
25
|
+
let binary = atob(value.replace(/-/g, "+").replace(/_/g, "/")), bytes = new Uint8Array(binary.length);
|
|
26
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
27
|
+
return bytes;
|
|
28
|
+
} catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** A link-session cookie value valid until `expiresAt` (ms since the epoch). */
|
|
33
|
+
async function signLinkSession(secret, expiresAt) {
|
|
34
|
+
let expires = String(Math.floor(expiresAt / 1e3));
|
|
35
|
+
return `${expires}.${toBase64Url(await crypto.subtle.sign("HMAC", await key(secret), encoder.encode(LABEL + expires)))}`;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* When a link-session cookie value expires (ms since the epoch), or `null` when it is malformed,
|
|
39
|
+
* forged or expired. The signature check is `crypto.subtle.verify`'s, which is constant-time.
|
|
40
|
+
*/
|
|
41
|
+
async function verifyLinkSession(secret, value, now = Date.now()) {
|
|
42
|
+
if (!value || value.length > 128) return null;
|
|
43
|
+
let match = /^(\d{1,12})\.([A-Za-z0-9_-]+)$/.exec(value);
|
|
44
|
+
if (!match) return null;
|
|
45
|
+
let expiresAt = Number(match[1]) * 1e3;
|
|
46
|
+
if (!(expiresAt > now)) return null;
|
|
47
|
+
let signature = fromBase64Url(match[2]);
|
|
48
|
+
return signature && await crypto.subtle.verify("HMAC", await key(secret), signature, encoder.encode(LABEL + match[1])) ? expiresAt : null;
|
|
49
|
+
}
|
|
50
|
+
export { signLinkSession as n, verifyLinkSession as r, LINK_SESSION_COOKIE as t };
|
|
51
|
+
|
|
52
|
+
//# sourceMappingURL=link-session-Dr4YkKFy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"link-session-Dr4YkKFy.js","names":[],"sources":["../src/server/link-session.ts"],"sourcesContent":["/**\n * Signed, expiring link-session cookies: what a `/p/<code>` link leaves in the browser instead of\n * the site's preview secret. The value is `<expires>.<signature>`, where `expires` is in seconds\n * since the epoch and the signature is HMAC-SHA-256 over it, keyed with the preview secret. It\n * proves \"opened a live share link, valid until `expires`\" and nothing else, so copying it gains\n * no more than the link itself gave.\n */\n\n/** The link-session cookie's default name. */\nexport const LINK_SESSION_COOKIE = '__sanity_preview_link'\n\nconst encoder = new TextEncoder()\nconst LABEL = 'sanity-preview-bar/link-session/v1:'\n\nfunction key(secret: string) {\n if (!secret) throw new Error('sanity-visual-editor: the preview secret is empty')\n return crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n {name: 'HMAC', hash: 'SHA-256'},\n false,\n ['sign', 'verify'],\n )\n}\n\nfunction toBase64Url(bytes: ArrayBuffer) {\n let binary = ''\n for (const byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\nfunction fromBase64Url(value: string) {\n if (!/^[A-Za-z0-9_-]+$/.test(value)) return null\n try {\n const binary = atob(value.replace(/-/g, '+').replace(/_/g, '/'))\n const bytes = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)\n return bytes\n } catch {\n return null\n }\n}\n\n/** A link-session cookie value valid until `expiresAt` (ms since the epoch). */\nexport async function signLinkSession(secret: string, expiresAt: number) {\n const expires = String(Math.floor(expiresAt / 1000))\n const signature = await crypto.subtle.sign(\n 'HMAC',\n await key(secret),\n encoder.encode(LABEL + expires),\n )\n return `${expires}.${toBase64Url(signature)}`\n}\n\n/**\n * When a link-session cookie value expires (ms since the epoch), or `null` when it is malformed,\n * forged or expired. The signature check is `crypto.subtle.verify`'s, which is constant-time.\n */\nexport async function verifyLinkSession(\n secret: string,\n value: string | undefined | null,\n now = Date.now(),\n): Promise<number | null> {\n if (!value || value.length > 128) return null\n const match = /^(\\d{1,12})\\.([A-Za-z0-9_-]+)$/.exec(value)\n if (!match) return null\n const expiresAt = Number(match[1]) * 1000\n if (!(expiresAt > now)) return null\n const signature = fromBase64Url(match[2])\n if (!signature) return null\n const valid = await crypto.subtle.verify(\n 'HMAC',\n await key(secret),\n signature,\n encoder.encode(LABEL + match[1]),\n )\n return valid ? expiresAt : null\n}\n"],"mappings":";;;;;;;;AASA,MAAa,sBAAsB,yBAE7B,UAAU,IAAI,YAAY,GAC1B,QAAQ;AAEd,SAAS,IAAI,QAAgB;CAC3B,IAAI,CAAC,QAAQ,MAAU,MAAM,mDAAmD;CAChF,OAAO,OAAO,OAAO,UACnB,OACA,QAAQ,OAAO,MAAM,GACrB;EAAC,MAAM;EAAQ,MAAM;CAAS,GAC9B,IACA,CAAC,QAAQ,QAAQ,CACnB;AACF;AAEA,SAAS,YAAY,OAAoB;CACvC,IAAI,SAAS;CACb,KAAK,IAAM,QAAQ,IAAI,WAAW,KAAK,GAAG,UAAU,OAAO,aAAa,IAAI;CAC5E,OAAO,KAAK,MAAM,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,GAAG,CAAC,CAAC,QAAQ,OAAO,EAAE;AAC/E;AAEA,SAAS,cAAc,OAAe;CACpC,IAAI,CAAC,mBAAmB,KAAK,KAAK,GAAG,OAAO;CAC5C,IAAI;EACF,IAAM,SAAS,KAAK,MAAM,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,MAAM,GAAG,CAAC,GACzD,QAAQ,IAAI,WAAW,OAAO,MAAM;EAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,MAAM,KAAK,OAAO,WAAW,CAAC;EACtE,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;;AAGA,eAAsB,gBAAgB,QAAgB,WAAmB;CACvE,IAAM,UAAU,OAAO,KAAK,MAAM,YAAY,GAAI,CAAC;CAMnD,OAAO,GAAG,QAAQ,GAAG,YAAY,MALT,OAAO,OAAO,KACpC,QACA,MAAM,IAAI,MAAM,GAChB,QAAQ,OAAO,QAAQ,OAAO,CAChC,CAC0C;AAC5C;;;;;AAMA,eAAsB,kBACpB,QACA,OACA,MAAM,KAAK,IAAI,GACS;CACxB,IAAI,CAAC,SAAS,MAAM,SAAS,KAAK,OAAO;CACzC,IAAM,QAAQ,iCAAiC,KAAK,KAAK;CACzD,IAAI,CAAC,OAAO,OAAO;CACnB,IAAM,YAAY,OAAO,MAAM,EAAE,IAAI;CACrC,IAAI,EAAE,YAAY,MAAM,OAAO;CAC/B,IAAM,YAAY,cAAc,MAAM,EAAE;CAQxC,OAPK,aAOE,MANa,OAAO,OAAO,OAChC,QACA,MAAM,IAAI,MAAM,GAChB,WACA,QAAQ,OAAO,QAAQ,MAAM,EAAE,CACjC,IACe,YAPQ;AAQzB"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { n as PreviewBarData, r as PreviewLinkErrorData } from "./data-D0qotTtt.js";
|
|
2
|
+
/**
|
|
3
|
+
* Mounts the bar's frame in the top window while draft mode is on. In the Studio's Visual Editor
|
|
4
|
+
* tool's frame (`isPreviewBarFrame()`), it answers the tool instead (`mountPreviewBarFrame`): the
|
|
5
|
+
* tool shows its own bar above the page. Other frames are skipped.
|
|
6
|
+
*/
|
|
7
|
+
export declare function PreviewBarHost({ basePath }: {
|
|
8
|
+
basePath?: string;
|
|
9
|
+
}): null;
|
|
10
|
+
/** The bar itself, for `app/__visual-editor/page.tsx`. */
|
|
11
|
+
export declare function PreviewBarFrame({ data }: {
|
|
12
|
+
data: PreviewBarData;
|
|
13
|
+
}): import("react").JSX.Element;
|
|
14
|
+
/** The expired-link page, for `/p/[code]` and its `not-found.tsx`. */
|
|
15
|
+
export declare function PreviewLinkErrorFrame(props: PreviewLinkErrorData): import("react").JSX.Element;
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { u as isPreviewBarFrame } from "./protocol-BNO38gYy.js";
|
|
3
|
+
import { n as isTopWindow } from "./host-DreYJEmR.js";
|
|
4
|
+
import { useEffect, useRef, useState } 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); `PreviewBarFrame` and `PreviewLinkErrorFrame` render the bar's page and the
|
|
10
|
+
* expired-link page. React and Sanity UI load only from the frames' dynamic imports, so the host
|
|
11
|
+
* stays a few KB.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Mounts the bar's frame in the top window while draft mode is on. In the Studio's Visual Editor
|
|
15
|
+
* tool's frame (`isPreviewBarFrame()`), it answers the tool instead (`mountPreviewBarFrame`): the
|
|
16
|
+
* tool shows its own bar above the page. Other frames are skipped.
|
|
17
|
+
*/
|
|
18
|
+
function PreviewBarHost({ basePath }) {
|
|
19
|
+
let router = useRouter(), pathname = usePathname(), [host, setHost] = useState(null);
|
|
20
|
+
return useEffect(() => {
|
|
21
|
+
let frame = isPreviewBarFrame();
|
|
22
|
+
if (!frame && !isTopWindow()) return;
|
|
23
|
+
let cancelled = !1, mounted;
|
|
24
|
+
return import("./host.js").then(({ mountPreviewBarHost, mountPreviewBarFrame }) => {
|
|
25
|
+
if (cancelled) return;
|
|
26
|
+
let options = {
|
|
27
|
+
refresh: () => router.refresh(),
|
|
28
|
+
navigate: (href) => router.push(href)
|
|
29
|
+
};
|
|
30
|
+
mounted = frame ? mountPreviewBarFrame(options) : mountPreviewBarHost({
|
|
31
|
+
...options,
|
|
32
|
+
basePath
|
|
33
|
+
}), setHost(mounted);
|
|
34
|
+
}), () => {
|
|
35
|
+
cancelled = !0, mounted?.destroy(), setHost(null);
|
|
36
|
+
};
|
|
37
|
+
}, [basePath, router]), useEffect(() => {
|
|
38
|
+
host?.setPath(window.location.pathname + window.location.search);
|
|
39
|
+
}, [host, pathname]), null;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Mounts a React root from the lazily loaded bar module into this component's element. The
|
|
43
|
+
* cancellation check runs before mounting, so React's development double-run of effects never
|
|
44
|
+
* mounts two roots on one element.
|
|
45
|
+
*/
|
|
46
|
+
function useMounted(mount, deps) {
|
|
47
|
+
let ref = useRef(null);
|
|
48
|
+
return useEffect(() => {
|
|
49
|
+
let element = ref.current;
|
|
50
|
+
if (!element) return;
|
|
51
|
+
let unmount, cancelled = !1;
|
|
52
|
+
return import("./bar.js").then((bar) => {
|
|
53
|
+
cancelled || (unmount = mount(bar, element));
|
|
54
|
+
}), () => {
|
|
55
|
+
cancelled = !0, unmount?.();
|
|
56
|
+
};
|
|
57
|
+
}, deps), ref;
|
|
58
|
+
}
|
|
59
|
+
/** The bar itself, for `app/__visual-editor/page.tsx`. */
|
|
60
|
+
function PreviewBarFrame({ data }) {
|
|
61
|
+
let ref = useMounted(({ mountPreviewBar }, element) => mountPreviewBar(element, data), [data]);
|
|
62
|
+
return /* @__PURE__ */ jsx("div", {
|
|
63
|
+
ref,
|
|
64
|
+
style: { height: "100%" }
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
/** The expired-link page, for `/p/[code]` and its `not-found.tsx`. */
|
|
68
|
+
function PreviewLinkErrorFrame(props) {
|
|
69
|
+
let ref = useMounted(({ mountPreviewLinkError }, element) => mountPreviewLinkError(element, props), [
|
|
70
|
+
props.expired,
|
|
71
|
+
props.brand,
|
|
72
|
+
props.studioPath
|
|
73
|
+
]);
|
|
74
|
+
return /* @__PURE__ */ jsx("div", { ref });
|
|
75
|
+
}
|
|
76
|
+
export { PreviewBarFrame, PreviewBarHost, PreviewLinkErrorFrame };
|
|
77
|
+
|
|
78
|
+
//# 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); `PreviewBarFrame` and `PreviewLinkErrorFrame` render the bar's page and the\n * 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 {useEffect, useRef, useState} from 'react'\n\nimport type {PreviewBarData, PreviewLinkErrorData} from '../core/data'\nimport {isPreviewBarFrame} from '../core/protocol'\nimport {isTopWindow, type PreviewBarHost as Host} from '../host'\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 */\nexport function PreviewBarHost({basePath}: {basePath?: string}) {\n const router = useRouter()\n const pathname = usePathname()\n const [host, setHost] = useState<Host | null>(null)\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":";;;;;;;;;;;;;;;;;AAmBA,SAAgB,eAAe,EAAC,YAAgC;CAC9D,IAAM,SAAS,UAAU,GACnB,WAAW,YAAY,GACvB,CAAC,MAAM,WAAW,SAAsB,IAAI;CA6BlD,OA3BA,gBAAgB;EACd,IAAM,QAAQ,kBAAkB;EAChC,IAAI,CAAC,SAAS,CAAC,YAAY,GAAG;EAC9B,IAAI,YAAY,IACZ;EAWJ,OAVA,OAAO,YAAU,CAAC,MAAM,EAAC,qBAAqB,2BAA0B;GACtE,IAAI,WAAW;GACf,IAAM,UAAU;IAEd,eAAe,OAAO,QAAQ;IAC9B,WAAW,SAAiB,OAAO,KAAK,IAAI;GAC9C;GACA,UAAU,QAAQ,qBAAqB,OAAO,IAAI,oBAAoB;IAAC,GAAG;IAAS;GAAQ,CAAC,GAC5F,QAAQ,OAAO;EACjB,CAAC,SACY;GACX,YAAY,IACZ,SAAS,QAAQ,GACjB,QAAQ,IAAI;EACd;CACF,GAAG,CAAC,UAAU,MAAM,CAAC,GAGrB,gBAAgB;EACd,MAAM,QAAQ,OAAO,SAAS,WAAW,OAAO,SAAS,MAAM;CACjE,GAAG,CAAC,MAAM,QAAQ,CAAC,GAEZ;AACT;;;;;;AASA,SAAS,WAAW,OAA6D,MAAiB;CAChG,IAAM,MAAM,OAAuB,IAAI;CAevC,OAdA,gBAAgB;EACd,IAAM,UAAU,IAAI;EACpB,IAAI,CAAC,SAAS;EACd,IAAI,SACA,YAAY;EAIhB,OAHA,OAAO,WAAS,CAAC,MAAM,QAAQ;GACxB,cAAW,UAAU,MAAM,KAAK,OAAO;EAC9C,CAAC,SACY;GACX,YAAY,IACZ,UAAU;EACZ;CAEF,GAAG,IAAI,GACA;AACT;;AAGA,SAAgB,gBAAgB,EAAC,QAA+B;CAC9D,IAAM,MAAM,YAAY,EAAC,mBAAkB,YAAY,gBAAgB,SAAS,IAAI,GAAG,CAAC,IAAI,CAAC;CAC7F,OAAO,oBAAC,OAAD;EAAU;EAAK,OAAO,EAAC,QAAQ,OAAM;CAAI,CAAA;AAClD;;AAGA,SAAgB,sBAAsB,OAA6B;CACjE,IAAM,MAAM,YACT,EAAC,yBAAwB,YAAY,sBAAsB,SAAS,KAAK,GAC1E;EAAC,MAAM;EAAS,MAAM;EAAO,MAAM;CAAU,CAC/C;CACA,OAAO,oBAAC,OAAD,EAAU,IAAM,CAAA;AACzB"}
|
package/dist/next.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { n as PreviewBarData } from "./data-D0qotTtt.js";
|
|
2
|
+
import { r as PreviewClient, t as PreviewBar } from "./index-4Zm_NjhC.js";
|
|
3
|
+
export type NextPreviewBarOptions = {
|
|
4
|
+
/** From `createPreviewBar` (`sanity-plugin-visual-editor/server`). */
|
|
5
|
+
bar: PreviewBar;
|
|
6
|
+
/** A server Sanity client with a read token (e.g. `client.withConfig({token})`). */
|
|
7
|
+
client: PreviewClient;
|
|
8
|
+
};
|
|
9
|
+
type RouteContext = {
|
|
10
|
+
params: Promise<Record<string, string | string[] | undefined>>;
|
|
11
|
+
};
|
|
12
|
+
export declare function createNextPreviewBar(options: NextPreviewBarOptions): {
|
|
13
|
+
/** `app/__visual-editor/[action]/route.ts`: `export const {GET, POST} = previewBar.handlers`. */
|
|
14
|
+
handlers: {
|
|
15
|
+
GET: (request: Request, { params }: RouteContext) => Promise<Response>;
|
|
16
|
+
POST: (request: Request, { params }: RouteContext) => Promise<Response>;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* `app/__visual-editor/page.tsx`: the bar's data, or a 404 outside draft mode. Pass it to
|
|
20
|
+
* `<PreviewBarFrame data={…} />`.
|
|
21
|
+
*/
|
|
22
|
+
loadBar(): Promise<PreviewBarData>;
|
|
23
|
+
/**
|
|
24
|
+
* `app/p/[code]/page.tsx`: redirects a live link to the open handler; calls `notFound()` for
|
|
25
|
+
* an unknown, malformed or expired one (render `<PreviewLinkErrorFrame expired />` in that
|
|
26
|
+
* segment's `not-found.tsx`). Returns `'unavailable'` when the store can't be read, for the
|
|
27
|
+
* page to render `<PreviewLinkErrorFrame expired={false} />`.
|
|
28
|
+
*/
|
|
29
|
+
checkLink(code: string): Promise<"unavailable">;
|
|
30
|
+
/**
|
|
31
|
+
* `app/__visual-editor/open/[code]/route.ts`: `export const GET = previewBar.openLink`. Turns
|
|
32
|
+
* draft mode on until the link expires, marks the session as opened from a link (so it can't
|
|
33
|
+
* mint links), sets the stored perspective and redirects to the stored page; a link that has
|
|
34
|
+
* gone meanwhile goes back to `/p/<code>` for the expired page.
|
|
35
|
+
*/
|
|
36
|
+
openLink(request: Request, { params }: RouteContext): Promise<Response>;
|
|
37
|
+
};
|
|
38
|
+
export {};
|
package/dist/next.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { c as parsePerspective, m as serializePerspective, n as PERSPECTIVE_COOKIE } from "./perspective-BmS9TVtr.js";
|
|
2
|
+
import { t as LINK_SESSION_COOKIE } from "./link-session-Dr4YkKFy.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 and the short-link checks. The client components live in
|
|
8
|
+
* `sanity-plugin-visual-editor/next/client`. See the README for the routes.
|
|
9
|
+
*
|
|
10
|
+
* Opening a short link takes two steps because a page can't set cookies while it renders:
|
|
11
|
+
* `/p/[code]` checks the link (rendering the expired page with a 404 when it's gone) and redirects
|
|
12
|
+
* live ones to `<basePath>/open/<code>`, a route handler that turns draft mode on and redirects to
|
|
13
|
+
* the stored page.
|
|
14
|
+
*
|
|
15
|
+
* Draft mode is one cookie (`__prerender_bypass`) whose value is fixed per build, so a link's
|
|
16
|
+
* recipient holds a value that turns draft mode on until the next deploy. `openLink` caps that
|
|
17
|
+
* cookie's lifetime to the link's, and marks the session so it can't mint links, but a recipient
|
|
18
|
+
* who copies the cookie by hand keeps draft mode until the next build. See the README.
|
|
19
|
+
*/
|
|
20
|
+
/** Next's draft mode cookie. */
|
|
21
|
+
const DRAFT_MODE_COOKIE = "__prerender_bypass";
|
|
22
|
+
function param(value) {
|
|
23
|
+
return Array.isArray(value) ? value[0] : value;
|
|
24
|
+
}
|
|
25
|
+
/** `next-sanity` and Next's draft mode use these attributes: `None; Secure` off localhost. */
|
|
26
|
+
function cookieOptions(secure) {
|
|
27
|
+
return {
|
|
28
|
+
httpOnly: !0,
|
|
29
|
+
path: "/",
|
|
30
|
+
sameSite: secure ? "none" : "lax",
|
|
31
|
+
secure
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
function createNextPreviewBar(options) {
|
|
35
|
+
let { bar, client } = options, basePath = bar.options.basePath;
|
|
36
|
+
async function context(request) {
|
|
37
|
+
let jar = await cookies(), linkExpires = Number(jar.get(LINK_SESSION_COOKIE)?.value);
|
|
38
|
+
return {
|
|
39
|
+
request,
|
|
40
|
+
previewEnabled: (await draftMode()).isEnabled,
|
|
41
|
+
client,
|
|
42
|
+
perspective: parsePerspective(jar.get(PERSPECTIVE_COOKIE)?.value),
|
|
43
|
+
linkSession: Number.isFinite(linkExpires) && linkExpires * 1e3 > Date.now()
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
/** A stand-in request for server components, which have headers but no `Request`. */
|
|
47
|
+
async function currentRequest() {
|
|
48
|
+
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");
|
|
49
|
+
return new Request(`${protocol}://${host}${basePath}`, { headers: list });
|
|
50
|
+
}
|
|
51
|
+
async function handle(request, { params }) {
|
|
52
|
+
let action = param((await params).action);
|
|
53
|
+
if (request.method === "GET" && action === "document") return bar.pageDocument(await context(request));
|
|
54
|
+
if (request.method === "GET" && action === "resolve") return bar.resolveHref(await context(request));
|
|
55
|
+
if (request.method === "POST") switch (action) {
|
|
56
|
+
case "perspective": return bar.perspective(await context(request));
|
|
57
|
+
case "share": return bar.share(await context(request));
|
|
58
|
+
case "exit": return bar.exit({ request }, async () => {
|
|
59
|
+
(await draftMode()).disable(), (await cookies()).delete(LINK_SESSION_COOKIE);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return new Response("Not found", { status: 404 });
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
/** `app/__visual-editor/[action]/route.ts`: `export const {GET, POST} = previewBar.handlers`. */
|
|
66
|
+
handlers: {
|
|
67
|
+
GET: handle,
|
|
68
|
+
POST: handle
|
|
69
|
+
},
|
|
70
|
+
/**
|
|
71
|
+
* `app/__visual-editor/page.tsx`: the bar's data, or a 404 outside draft mode. Pass it to
|
|
72
|
+
* `<PreviewBarFrame data={…} />`.
|
|
73
|
+
*/
|
|
74
|
+
async loadBar() {
|
|
75
|
+
let data = await bar.loadBar(await context(await currentRequest()));
|
|
76
|
+
return data || notFound(), data;
|
|
77
|
+
},
|
|
78
|
+
/**
|
|
79
|
+
* `app/p/[code]/page.tsx`: redirects a live link to the open handler; calls `notFound()` for
|
|
80
|
+
* an unknown, malformed or expired one (render `<PreviewLinkErrorFrame expired />` in that
|
|
81
|
+
* segment's `not-found.tsx`). Returns `'unavailable'` when the store can't be read, for the
|
|
82
|
+
* page to render `<PreviewLinkErrorFrame expired={false} />`.
|
|
83
|
+
*/
|
|
84
|
+
async checkLink(code) {
|
|
85
|
+
let result = await bar.resolveLink(code);
|
|
86
|
+
return result.status === 200 && redirect(`${basePath}/open/${code}`), result.status === 404 && notFound(), "unavailable";
|
|
87
|
+
},
|
|
88
|
+
/**
|
|
89
|
+
* `app/__visual-editor/open/[code]/route.ts`: `export const GET = previewBar.openLink`. Turns
|
|
90
|
+
* draft mode on until the link expires, marks the session as opened from a link (so it can't
|
|
91
|
+
* mint links), sets the stored perspective and redirects to the stored page; a link that has
|
|
92
|
+
* gone meanwhile goes back to `/p/<code>` for the expired page.
|
|
93
|
+
*/
|
|
94
|
+
async openLink(request, { params }) {
|
|
95
|
+
let code = param((await params).code) ?? "", result = await bar.resolveLink(code);
|
|
96
|
+
result.status !== 200 && redirect(`${bar.options.linkRoute}${code}`);
|
|
97
|
+
let { expiresAt } = result.link, maxAge = Math.floor((expiresAt - Date.now()) / 1e3);
|
|
98
|
+
maxAge <= 0 && redirect(`${bar.options.linkRoute}${code}`);
|
|
99
|
+
let options = cookieOptions(new URL(request.url).protocol === "https:"), jar = await cookies(), draft = await draftMode();
|
|
100
|
+
if (!draft.isEnabled) {
|
|
101
|
+
draft.enable();
|
|
102
|
+
let bypass = jar.get(DRAFT_MODE_COOKIE)?.value;
|
|
103
|
+
bypass && jar.set(DRAFT_MODE_COOKIE, bypass, {
|
|
104
|
+
...options,
|
|
105
|
+
maxAge
|
|
106
|
+
}), jar.set(LINK_SESSION_COOKIE, String(Math.floor(expiresAt / 1e3)), {
|
|
107
|
+
...options,
|
|
108
|
+
maxAge
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
jar.set(PERSPECTIVE_COOKIE, serializePerspective(result.link.perspective), options), redirect(result.link.pathname);
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
export { createNextPreviewBar };
|
|
116
|
+
|
|
117
|
+
//# sourceMappingURL=next.js.map
|
package/dist/next.js.map
ADDED
|
@@ -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 and the short-link checks. The client components live in\n * `sanity-plugin-visual-editor/next/client`. See the README for the routes.\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 {PreviewBarData} from '../core/data'\nimport {parsePerspective, PERSPECTIVE_COOKIE, serializePerspective} from '../core/perspective'\nimport type {PreviewBar, PreviewClient, PreviewContext} 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, maxA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pB,QAAQ,MAAM,UAAU;GAE9B,IAAI,CAAC,MAAM,WAAW;IACpB,MAAM,OAAO;IAGb,IAAM,SAAS,IAAI,IAAI,iBAAiB,CAAC,EAAE;IACvC,UAAQ,IAAI,IAAI,mBAAmB,QAAQ;KAAC,GAAG;KAAS;IAAM,CAAC,GACnE,IAAI,IAAI,qBAAqB,OAAO,KAAK,MAAM,YAAY,GAAI,CAAC,GAAG;KAAC,GAAG;KAAS;IAAM,CAAC;GACzF;GACA,IAAI,IAAI,oBAAoB,qBAAqB,OAAO,KAAK,WAAW,GAAG,OAAO,GAClF,SAAS,OAAO,KAAK,QAAQ;EAC/B;CACF;AACF"}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { E as toStudioPath, S as publishedDocumentId, _ as describeSanityPath, y as humanizeFieldName } from "./protocol-BNO38gYy.js";
|
|
2
|
+
/**
|
|
3
|
+
* Labels for click-to-edit, and the drift check, from the Studio's schema and the document: the
|
|
4
|
+
* bar (on the site, inside its Studio layer) and the Visual Editor tool answer the overlay's
|
|
5
|
+
* `describe` with these, so field titles reach the page without shipping the schema there.
|
|
6
|
+
*
|
|
7
|
+
* A path that doesn't resolve is reported as `missing`: a field the schema doesn't have (the
|
|
8
|
+
* component's annotation drifted from the schema) or an item or document that doesn't exist.
|
|
9
|
+
*/
|
|
10
|
+
function isRecord(value) {
|
|
11
|
+
return typeof value == "object" && !!value;
|
|
12
|
+
}
|
|
13
|
+
function typeTitle(type) {
|
|
14
|
+
return type.title || humanizeFieldName(type.name);
|
|
15
|
+
}
|
|
16
|
+
/** The array member an item uses: by its `_type`, or the only member there is. */
|
|
17
|
+
function memberFor(of, item) {
|
|
18
|
+
let itemType = isRecord(item) && typeof item._type == "string" ? item._type : void 0;
|
|
19
|
+
return itemType && of.find((member) => member.name === itemType) || (of.length === 1 ? of[0] : void 0);
|
|
20
|
+
}
|
|
21
|
+
/** A Portable Text block by its style's title (`Heading 1`), as the editor's style menu shows it. */
|
|
22
|
+
function blockStyleTitle(member, item) {
|
|
23
|
+
let style = isRecord(item) && typeof item.style == "string" ? item.style : void 0;
|
|
24
|
+
if (!style) return;
|
|
25
|
+
let list = member.fields?.find((field) => field.name === "style")?.type.options?.list ?? [];
|
|
26
|
+
for (let option of list) if (isRecord(option) && option.value === style && typeof option.title == "string") return option.title;
|
|
27
|
+
}
|
|
28
|
+
function itemTitle(member, item, field) {
|
|
29
|
+
return member ? member.to?.length ? typeTitle(member.to[0]) : member.name === "block" ? blockStyleTitle(member, item) ?? "Block" : typeTitle(member) : field ? `${field} item` : "Item";
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The label of a path's last segment, and whether the path resolves. `document` is the document's
|
|
33
|
+
* value, `null` when it doesn't exist, or `undefined` when it wasn't loaded (then only the schema
|
|
34
|
+
* is checked).
|
|
35
|
+
*/
|
|
36
|
+
function describePath(schema, documentType, document, urlPath) {
|
|
37
|
+
let fallback = describeSanityPath(urlPath), path = toStudioPath(urlPath), type = schema.get(documentType);
|
|
38
|
+
if (!path || !type || document === null) return {
|
|
39
|
+
label: fallback,
|
|
40
|
+
missing: !0
|
|
41
|
+
};
|
|
42
|
+
let value = document, label = "";
|
|
43
|
+
for (let segment of path) {
|
|
44
|
+
if (typeof segment == "string") {
|
|
45
|
+
let field = type?.fields?.find((candidate) => candidate.name === segment);
|
|
46
|
+
if (!field) return {
|
|
47
|
+
label: humanizeFieldName(segment),
|
|
48
|
+
missing: !0
|
|
49
|
+
};
|
|
50
|
+
label = field.type.title || humanizeFieldName(segment), type = field.type, value = isRecord(value) ? value[segment] : void 0;
|
|
51
|
+
continue;
|
|
52
|
+
}
|
|
53
|
+
if (!type?.of) return {
|
|
54
|
+
label,
|
|
55
|
+
missing: !0
|
|
56
|
+
};
|
|
57
|
+
let items = Array.isArray(value) ? value : void 0, item = typeof segment == "number" ? items?.[segment] : items?.find((candidate) => isRecord(candidate) && candidate._key === segment._key);
|
|
58
|
+
if (document !== void 0 && item === void 0) return {
|
|
59
|
+
label: label ? `${label} item` : "Item",
|
|
60
|
+
missing: !0
|
|
61
|
+
};
|
|
62
|
+
let member = memberFor(type.of, item);
|
|
63
|
+
if (!member && item === void 0) return {
|
|
64
|
+
label: unresolvedLabel(path, label),
|
|
65
|
+
missing: !1
|
|
66
|
+
};
|
|
67
|
+
label = itemTitle(member, item, label), type = member, value = item;
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
label: label || fallback,
|
|
71
|
+
missing: !1
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/** The label of a path's last segment when the schema can't follow it all the way. */
|
|
75
|
+
function unresolvedLabel(path, label) {
|
|
76
|
+
let last = path[path.length - 1];
|
|
77
|
+
return typeof last == "string" ? humanizeFieldName(last) : label ? `${label} item` : "Item";
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Answers the overlay's `describe`: one fetch for the documents involved (cached briefly, since
|
|
81
|
+
* hovering asks a few at a time), then each node's label and drift.
|
|
82
|
+
*/
|
|
83
|
+
function createNodeDescriber(schema, fetchDocuments, cacheMs = 3e3) {
|
|
84
|
+
let cache = /* @__PURE__ */ new Map();
|
|
85
|
+
return async function describe(nodes) {
|
|
86
|
+
let now = Date.now(), stale = [...new Set(nodes.map((node) => publishedDocumentId(node.id)))].filter((id) => {
|
|
87
|
+
let cached = cache.get(id);
|
|
88
|
+
return !cached || now - cached.at > cacheMs;
|
|
89
|
+
});
|
|
90
|
+
if (stale.length) {
|
|
91
|
+
let fetched = await fetchDocuments(stale);
|
|
92
|
+
for (let id of stale) cache.set(id, {
|
|
93
|
+
at: now,
|
|
94
|
+
value: fetched[id] ?? null
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return nodes.map((node) => {
|
|
98
|
+
let document = cache.get(publishedDocumentId(node.id))?.value, { label, missing } = describePath(schema, node.type, document, node.path);
|
|
99
|
+
return missing ? {
|
|
100
|
+
id: node.id,
|
|
101
|
+
path: node.path,
|
|
102
|
+
label,
|
|
103
|
+
missing: !0
|
|
104
|
+
} : {
|
|
105
|
+
id: node.id,
|
|
106
|
+
path: node.path,
|
|
107
|
+
label
|
|
108
|
+
};
|
|
109
|
+
});
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** A `DocumentFetcher` over a Sanity client, in a perspective stack (`['drafts']`, a release…). */
|
|
113
|
+
function clientDocumentFetcher(client, perspective) {
|
|
114
|
+
return async (ids) => {
|
|
115
|
+
let documents = await client.withConfig({ perspective }).fetch("*[_id in $ids]", { ids }, { tag: "preview-bar.node-labels" }), byId = {};
|
|
116
|
+
if (Array.isArray(documents)) for (let document of documents) isRecord(document) && typeof document._id == "string" && (byId[publishedDocumentId(document._id)] = document);
|
|
117
|
+
return byId;
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
export { createNodeDescriber as n, describePath as r, clientDocumentFetcher as t };
|
|
121
|
+
|
|
122
|
+
//# sourceMappingURL=node-labels-CDiW5rMq.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"node-labels-CDiW5rMq.js","names":[],"sources":["../src/core/node-labels.ts"],"sourcesContent":["/**\n * Labels for click-to-edit, and the drift check, from the Studio's schema and the document: the\n * bar (on the site, inside its Studio layer) and the Visual Editor tool answer the overlay's\n * `describe` with these, so field titles reach the page without shipping the schema there.\n *\n * A path that doesn't resolve is reported as `missing`: a field the schema doesn't have (the\n * component's annotation drifted from the schema) or an item or document that doesn't exist.\n */\nimport {\n describeSanityPath,\n humanizeFieldName,\n publishedDocumentId,\n type SanityNode,\n toStudioPath,\n} from './sanity-node'\n\n/** The parts of a compiled Sanity schema type the labels read. */\nexport type LabelSchemaType = {\n name: string\n title?: string\n jsonType?: string\n fields?: readonly {name: string; type: LabelSchemaType}[]\n of?: readonly LabelSchemaType[]\n to?: readonly LabelSchemaType[]\n options?: {list?: readonly unknown[]}\n}\n\nexport type LabelSchema = {get(name: string): LabelSchemaType | undefined}\n\n/** A node's label for the overlay, keyed by the node's `id` and `path` as the page sent them. */\nexport type NodeLabel = {id: string; path: string; label: string; missing?: boolean}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null\n}\n\nfunction typeTitle(type: LabelSchemaType) {\n return type.title || humanizeFieldName(type.name)\n}\n\n/** The array member an item uses: by its `_type`, or the only member there is. */\nfunction memberFor(of: readonly LabelSchemaType[], item: unknown) {\n const itemType = isRecord(item) && typeof item._type === 'string' ? item._type : undefined\n return (\n (itemType && of.find((member) => member.name === itemType)) ||\n (of.length === 1 ? of[0] : undefined)\n )\n}\n\n/** A Portable Text block by its style's title (`Heading 1`), as the editor's style menu shows it. */\nfunction blockStyleTitle(member: LabelSchemaType, item: unknown) {\n const style = isRecord(item) && typeof item.style === 'string' ? item.style : undefined\n if (!style) return undefined\n const list = member.fields?.find((field) => field.name === 'style')?.type.options?.list ?? []\n for (const option of list) {\n if (isRecord(option) && option.value === style && typeof option.title === 'string')\n return option.title\n }\n return undefined\n}\n\nfunction itemTitle(member: LabelSchemaType | undefined, item: unknown, field: string) {\n if (!member) return field ? `${field} item` : 'Item'\n if (member.to?.length) return typeTitle(member.to[0]!)\n if (member.name === 'block') return blockStyleTitle(member, item) ?? 'Block'\n return typeTitle(member)\n}\n\n/**\n * The label of a path's last segment, and whether the path resolves. `document` is the document's\n * value, `null` when it doesn't exist, or `undefined` when it wasn't loaded (then only the schema\n * is checked).\n */\nexport function describePath(\n schema: LabelSchema,\n documentType: string,\n document: unknown,\n urlPath: string,\n): {label: string; missing: boolean} {\n const fallback = describeSanityPath(urlPath)\n const path = toStudioPath(urlPath)\n let type: LabelSchemaType | undefined = schema.get(documentType)\n if (!path || !type || document === null) return {label: fallback, missing: true}\n let value: unknown = document\n let label = ''\n for (const segment of path) {\n if (typeof segment === 'string') {\n const field: {name: string; type: LabelSchemaType} | undefined = type?.fields?.find(\n (candidate) => candidate.name === segment,\n )\n if (!field) return {label: humanizeFieldName(segment), missing: true}\n label = field.type.title || humanizeFieldName(segment)\n type = field.type\n value = isRecord(value) ? value[segment] : undefined\n continue\n }\n if (!type?.of) return {label, missing: true}\n const items = Array.isArray(value) ? value : undefined\n const item =\n typeof segment === 'number'\n ? items?.[segment]\n : items?.find((candidate) => isRecord(candidate) && candidate._key === segment._key)\n if (document !== undefined && item === undefined)\n return {label: label ? `${label} item` : 'Item', missing: true}\n const member = memberFor(type.of, item)\n // Without the document, an array of several types can't say which one an item is: the rest\n // of the path can't be checked, only labelled.\n if (!member && item === undefined) return {label: unresolvedLabel(path, label), missing: false}\n label = itemTitle(member, item, label)\n type = member\n value = item\n }\n return {label: label || fallback, missing: false}\n}\n\n/** The label of a path's last segment when the schema can't follow it all the way. */\nfunction unresolvedLabel(path: readonly unknown[], label: string) {\n const last = path[path.length - 1]\n if (typeof last === 'string') return humanizeFieldName(last)\n return label ? `${label} item` : 'Item'\n}\n\n/** Fetches documents by published ID, in the editor's perspective; absent ones are left out. */\nexport type DocumentFetcher = (ids: string[]) => Promise<Record<string, unknown>>\n\n/**\n * Answers the overlay's `describe`: one fetch for the documents involved (cached briefly, since\n * hovering asks a few at a time), then each node's label and drift.\n */\nexport function createNodeDescriber(\n schema: LabelSchema,\n fetchDocuments: DocumentFetcher,\n cacheMs = 3000,\n) {\n const cache = new Map<string, {at: number; value: unknown}>()\n return async function describe(nodes: readonly SanityNode[]): Promise<NodeLabel[]> {\n const now = Date.now()\n const ids = [...new Set(nodes.map((node) => publishedDocumentId(node.id)))]\n const stale = ids.filter((id) => {\n const cached = cache.get(id)\n return !cached || now - cached.at > cacheMs\n })\n if (stale.length) {\n const fetched = await fetchDocuments(stale)\n for (const id of stale) cache.set(id, {at: now, value: fetched[id] ?? null})\n }\n return nodes.map((node) => {\n const document = cache.get(publishedDocumentId(node.id))?.value\n const {label, missing} = describePath(schema, node.type, document, node.path)\n return missing\n ? {id: node.id, path: node.path, label, missing: true}\n : {id: node.id, path: node.path, label}\n })\n }\n}\n\ntype PerspectiveClient = {\n withConfig(config: {perspective: unknown}): {\n fetch(query: string, params: Record<string, unknown>, options?: unknown): Promise<unknown>\n }\n}\n\n/** A `DocumentFetcher` over a Sanity client, in a perspective stack (`['drafts']`, a release…). */\nexport function clientDocumentFetcher(\n client: PerspectiveClient,\n perspective: unknown,\n): DocumentFetcher {\n return async (ids) => {\n const documents = await client\n .withConfig({perspective})\n .fetch('*[_id in $ids]', {ids}, {tag: 'preview-bar.node-labels'})\n const byId: Record<string, unknown> = {}\n if (Array.isArray(documents)) {\n for (const document of documents) {\n if (isRecord(document) && typeof document._id === 'string')\n byId[publishedDocumentId(document._id)] = document\n }\n }\n return byId\n }\n}\n"],"mappings":";;;;;;;;;AAgCA,SAAS,SAAS,OAAkD;CAClE,OAAO,OAAO,SAAU,cAAY;AACtC;AAEA,SAAS,UAAU,MAAuB;CACxC,OAAO,KAAK,SAAS,kBAAkB,KAAK,IAAI;AAClD;;AAGA,SAAS,UAAU,IAAgC,MAAe;CAChE,IAAM,WAAW,SAAS,IAAI,KAAK,OAAO,KAAK,SAAU,WAAW,KAAK,QAAQ,KAAA;CACjF,OACG,YAAY,GAAG,MAAM,WAAW,OAAO,SAAS,QAAQ,MACxD,GAAG,WAAW,IAAI,GAAG,KAAK,KAAA;AAE/B;;AAGA,SAAS,gBAAgB,QAAyB,MAAe;CAC/D,IAAM,QAAQ,SAAS,IAAI,KAAK,OAAO,KAAK,SAAU,WAAW,KAAK,QAAQ,KAAA;CAC9E,IAAI,CAAC,OAAO;CACZ,IAAM,OAAO,OAAO,QAAQ,MAAM,UAAU,MAAM,SAAS,OAAO,CAAC,EAAE,KAAK,SAAS,QAAQ,CAAC;CAC5F,KAAK,IAAM,UAAU,MACnB,IAAI,SAAS,MAAM,KAAK,OAAO,UAAU,SAAS,OAAO,OAAO,SAAU,UACxE,OAAO,OAAO;AAGpB;AAEA,SAAS,UAAU,QAAqC,MAAe,OAAe;CAIpF,OAHK,SACD,OAAO,IAAI,SAAe,UAAU,OAAO,GAAG,EAAG,IACjD,OAAO,SAAS,UAAgB,gBAA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AAQ,SAAS,GACpB,KAAA,IAAM,YAAY,WACjB,SAAS,QAAQ,KAAK,OAAO,SAAS,OAAQ,aAChD,KAAK,oBAAoB,SAAS,GAAG,KAAK;EAGhD,OAAO;CACT;AACF"}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Which document a storefront page shows, with the Studio's Presentation API for it
|
|
3
|
+
* (`resolve.mainDocuments` / `defineDocuments`): a route such as `/products/:slug` and either a
|
|
4
|
+
* document type, a GROQ filter that reads the route's params (`$slug`), or a function returning
|
|
5
|
+
* both. Pass the project's own list so the Studio and the site never drift. The first matching rule
|
|
6
|
+
* wins, as in Presentation.
|
|
7
|
+
*/
|
|
8
|
+
/** What a rule's functions receive: the page's origin, its route params and its path. */
|
|
9
|
+
type DocumentResolverContext = {
|
|
10
|
+
origin: string;
|
|
11
|
+
params: Record<string, string>;
|
|
12
|
+
path: string;
|
|
13
|
+
};
|
|
14
|
+
type ContextFn<T> = (context: DocumentResolverContext) => T;
|
|
15
|
+
/** One `defineDocuments` entry (Presentation's `DocumentResolver`). */
|
|
16
|
+
type PageDocumentRule = {
|
|
17
|
+
route: string | string[];
|
|
18
|
+
type: string;
|
|
19
|
+
filter?: never;
|
|
20
|
+
params?: never;
|
|
21
|
+
resolve?: never;
|
|
22
|
+
} | {
|
|
23
|
+
route: string | string[];
|
|
24
|
+
type?: never;
|
|
25
|
+
filter: string | ContextFn<string>;
|
|
26
|
+
/** Extra params for the filter, merged over the route's. */
|
|
27
|
+
params?: Record<string, string> | ContextFn<Record<string, string>>;
|
|
28
|
+
resolve?: never;
|
|
29
|
+
} | {
|
|
30
|
+
route: string | string[];
|
|
31
|
+
type?: never;
|
|
32
|
+
filter?: never;
|
|
33
|
+
params?: never;
|
|
34
|
+
resolve: ContextFn<{
|
|
35
|
+
filter: string;
|
|
36
|
+
params?: Record<string, string>;
|
|
37
|
+
} | undefined>;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Matches `pathname` against a Presentation route: literal segments, `:name` params (one segment)
|
|
41
|
+
* and a trailing `:name*` (the rest of the path). Returns the params, or `null`.
|
|
42
|
+
*/
|
|
43
|
+
declare function matchRoute(route: string, pathname: string): Record<string, string> | null;
|
|
44
|
+
/** The first rule matching `pathname`, as a filter with its params; `null` when none does. */
|
|
45
|
+
declare function findPageDocumentRule(rules: PageDocumentRule[], pathname: string, origin?: string): {
|
|
46
|
+
filter: string;
|
|
47
|
+
params: Record<string, string>;
|
|
48
|
+
} | null;
|
|
49
|
+
/** The page's document as the bar receives it. */
|
|
50
|
+
type PageDocument = {
|
|
51
|
+
_id: string;
|
|
52
|
+
_type: string;
|
|
53
|
+
};
|
|
54
|
+
export { matchRoute as a, findPageDocumentRule as i, PageDocument as n, PageDocumentRule as r, DocumentResolverContext as t };
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Matches `pathname` against a Presentation route: literal segments, `:name` params (one segment)
|
|
3
|
+
* and a trailing `:name*` (the rest of the path). Returns the params, or `null`.
|
|
4
|
+
*/
|
|
5
|
+
function matchRoute(route, pathname) {
|
|
6
|
+
try {
|
|
7
|
+
return matchRouteParts(route, pathname);
|
|
8
|
+
} catch (error) {
|
|
9
|
+
if (error instanceof URIError) return null;
|
|
10
|
+
throw error;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
function matchRouteParts(route, pathname) {
|
|
14
|
+
let routeParts = route.split("/").filter(Boolean), pathParts = pathname.split("?")[0].split("#")[0].split("/").filter(Boolean), params = {};
|
|
15
|
+
for (let index = 0; index < routeParts.length; index++) {
|
|
16
|
+
let part = routeParts[index];
|
|
17
|
+
if (part.startsWith(":") && part.endsWith("*")) return params[part.slice(1, -1)] = pathParts.slice(index).map(decodeURIComponent).join("/"), params;
|
|
18
|
+
let value = pathParts[index];
|
|
19
|
+
if (value === void 0) return null;
|
|
20
|
+
if (part.startsWith(":")) params[part.slice(1)] = decodeURIComponent(value);
|
|
21
|
+
else if (part !== value) return null;
|
|
22
|
+
}
|
|
23
|
+
return routeParts.length === pathParts.length ? params : null;
|
|
24
|
+
}
|
|
25
|
+
/** The first rule matching `pathname`, as a filter with its params; `null` when none does. */
|
|
26
|
+
function findPageDocumentRule(rules, pathname, origin = "") {
|
|
27
|
+
let path = pathname.split("?")[0].split("#")[0];
|
|
28
|
+
for (let rule of rules) for (let route of Array.isArray(rule.route) ? rule.route : [rule.route]) {
|
|
29
|
+
let params = matchRoute(route, pathname);
|
|
30
|
+
if (!params) continue;
|
|
31
|
+
let context = {
|
|
32
|
+
origin,
|
|
33
|
+
params,
|
|
34
|
+
path
|
|
35
|
+
};
|
|
36
|
+
if (rule.type) return {
|
|
37
|
+
filter: "_type == $type",
|
|
38
|
+
params: {
|
|
39
|
+
...params,
|
|
40
|
+
type: rule.type
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
if (rule.resolve) {
|
|
44
|
+
let resolved = rule.resolve(context);
|
|
45
|
+
if (resolved) return {
|
|
46
|
+
filter: resolved.filter,
|
|
47
|
+
params: {
|
|
48
|
+
...params,
|
|
49
|
+
...resolved.params
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
} else if (rule.filter) {
|
|
53
|
+
let filter = typeof rule.filter == "function" ? rule.filter(context) : rule.filter, extra = typeof rule.params == "function" ? rule.params(context) : rule.params;
|
|
54
|
+
return {
|
|
55
|
+
filter,
|
|
56
|
+
params: {
|
|
57
|
+
...params,
|
|
58
|
+
...extra
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
export { matchRoute as n, findPageDocumentRule as t };
|
|
66
|
+
|
|
67
|
+
//# sourceMappingURL=page-documents-mGfw_flR.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"page-documents-mGfw_flR.js","names":[],"sources":["../src/core/page-documents.ts"],"sourcesContent":["/**\n * Which document a storefront page shows, with the Studio's Presentation API for it\n * (`resolve.mainDocuments` / `defineDocuments`): a route such as `/products/:slug` and either a\n * document type, a GROQ filter that reads the route's params (`$slug`), or a function returning\n * both. Pass the project's own list so the Studio and the site never drift. The first matching rule\n * wins, as in Presentation.\n */\n\n/** What a rule's functions receive: the page's origin, its route params and its path. */\nexport type DocumentResolverContext = {\n origin: string\n params: Record<string, string>\n path: string\n}\n\ntype ContextFn<T> = (context: DocumentResolverContext) => T\n\n/** One `defineDocuments` entry (Presentation's `DocumentResolver`). */\nexport type PageDocumentRule =\n | {route: string | string[]; type: string; filter?: never; params?: never; resolve?: never}\n | {\n route: string | string[]\n type?: never\n filter: string | ContextFn<string>\n /** Extra params for the filter, merged over the route's. */\n params?: Record<string, string> | ContextFn<Record<string, string>>\n resolve?: never\n }\n | {\n route: string | string[]\n type?: never\n filter?: never\n params?: never\n resolve: ContextFn<{filter: string; params?: Record<string, string>} | undefined>\n }\n\n/**\n * Matches `pathname` against a Presentation route: literal segments, `:name` params (one segment)\n * and a trailing `:name*` (the rest of the path). Returns the params, or `null`.\n */\nexport function matchRoute(route: string, pathname: string): Record<string, string> | null {\n try {\n return matchRouteParts(route, pathname)\n } catch (error) {\n // A malformed escape (`/products/%E0`) matches nothing.\n if (error instanceof URIError) return null\n throw error\n }\n}\n\nfunction matchRouteParts(route: string, pathname: string): Record<string, string> | null {\n const routeParts = route.split('/').filter(Boolean)\n const pathParts = pathname.split('?')[0].split('#')[0].split('/').filter(Boolean)\n const params: Record<string, string> = {}\n for (let index = 0; index < routeParts.length; index++) {\n const part = routeParts[index]\n if (part.startsWith(':') && part.endsWith('*')) {\n params[part.slice(1, -1)] = pathParts.slice(index).map(decodeURIComponent).join('/')\n return params\n }\n const value = pathParts[index]\n if (value === undefined) return null\n if (part.startsWith(':')) params[part.slice(1)] = decodeURIComponent(value)\n else if (part !== value) return null\n }\n return routeParts.length === pathParts.length ? params : null\n}\n\n/** The first rule matching `pathname`, as a filter with its params; `null` when none does. */\nexport function findPageDocumentRule(\n rules: PageDocumentRule[],\n pathname: string,\n origin = '',\n): {filter: string; params: Record<string, string>} | null {\n const path = pathname.split('?')[0].split('#')[0]\n for (const rule of rules) {\n for (const route of Array.isArray(rule.route) ? rule.route : [rule.route]) {\n const params = matchRoute(route, pathname)\n if (!params) continue\n const context = {origin, params, path}\n if (rule.type) return {filter: '_type == $type', params: {...params, type: rule.type}}\n if (rule.resolve) {\n const resolved = rule.resolve(context)\n if (resolved) return {filter: resolved.filter, params: {...params, ...resolved.params}}\n continue\n }\n if (rule.filter) {\n const filter = typeof rule.filter === 'function' ? rule.filter(context) : rule.filter\n const extra = typeof rule.params === 'function' ? rule.params(context) : rule.params\n return {filter, params: {...params, ...extra}}\n }\n }\n }\n return null\n}\n\n/** The page's document as the bar receives it. */\nexport type PageDocument = {_id: string; _type: string}\n"],"mappings":";;;;AAwCA,SAAgB,WAAW,OAAe,UAAiD;CACzF,IAAI;EACF,OAAO,gBAAgB,OAAO,QAAQ;CACxC,SAAS,OAAO;EAEd,IAAI,iBAAiB,UAAU,OAAO;EACtC,MAAM;CACR;AACF;AAEA,SAAS,gBAAgB,OAAe,UAAiD;CACvF,IAAM,aAAa,MAAM,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,GAC5C,YAAY,SAAS,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,OAAO,OAAO,GAC1E,SAAiC,CAAC;CACxC,KAAK,IAAI,QAAQ,GAAG,QAAQ,WAAW,QAAQ,SAAS;EACtD,IAAM,OAAO,WAAW;EACxB,IAAI,KAAK,WAAW,GAAG,KAAK,KAAK,SAAS,GAAG,GAE3C,OADA,OAAO,KAAK,MAAM,GAAG,EAAE,KAAK,UAAU,MAAM,KAAK,CAAC,CAAC,IAAI,kBAAkB,CAAC,CAAC,KAAK,GAAG,GAC5E;EAET,IAAM,QAAQ,UAAU;EACxB,IAAI,UAAU,KAAA,GAAW,OAA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