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
@@ -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,SAA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,KAAK,EAAE,CAAC,CAAC,EAAE,OACpD,EAAC,OAAO,YAAW,aAAa,QAAQ,KAAK,MAAM,UAAU,KAAK,IAAI;GAC5E,OAAO,UACH;IAAC,IAAI,KAAK;IAAI,MAAM,KAAK;IAAM;IAAO,SAAS;GAAI,IACnD;IAAC,IAAI,KAAK;IAAI,MAAM,KAAK;IAAM;GAAK;EAC1C,CAAC;CACH;AACF;;AASA,SAAgB,sBACd,QACA,aACiB;CACjB,OAAO,OAAO,QAAQ;EACpB,IAAM,YAAY,MAAM,OACrB,WAAW,EAAC,YAAW,CAAC,CAAC,CACzB,MAAM,kBAAkB,EAAC,IAAG,GAAG,EAAC,KAAK,0BAAyB,CAAC,GAC5D,OAAgC,CAAC;EACvC,IAAI,MAAM,QAAQ,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,OAAO;EAChC,IAAI,KAAK,WAAW,GAAG,GAAG,OAAO,KAAK,MAAM,CAAC,KAAK,mBAAmB,KAAK;OACrE,IAAI,SAAS,OAAO,OAAO;CAClC;CACA,OAAO,WAAW,WAAW,UAAU,SAAS,SAAS;AAC3D;;AAGA,SAAgB,qBACd,OACA,UACA,SAAS,IACgD;CACzD,IAAM,OAAO,SAAS,MAAM,GAAG,CAAC,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC;CAC/C,KAAK,IAAM,QAAQ,OACjB,KAAK,IAAM,SAAS,MAAM,QAAQ,KAAK,KAAK,IAAI,KAAK,QAAQ,CAAC,KAAK,KAAK,GAAG;EACzE,IAAM,SAAS,WAAW,OAAO,QAAQ;EACzC,IAAI,CAAC,QAAQ;EACb,IAAM,UAAU;GAAC;GAAQ;GAAQ;EAAI;EACrC,IAAI,KAAK,MAAM,OAAO;GAAC,QAAQ;GAAkB,QAAQ;IAAC,GAAG;IAAQ,MAAM,KAAK;GAAI;EAAC;EACrF,IAAI,KAAK,SAAS;GAChB,IAAM,WAAW,KAAK,QAAQ,OAAO;GACrC,IAAI,UAAU,OAAO;IAAC,QAAQ,SAAS;IAAQ,QAAQ;KAAC,GAAG;KAAQ,GAAG,SAAS;IAAM;GAAC;EAExF,OACA,IAAI,KAAK,QAAQ;GACf,IAAM,SAAS,OAAO,KAAK,UAAW,aAAa,KAAK,OAAO,OAAO,IAAI,KAAK,QACzE,QAAQ,OAAO,KAAK,UAAW,aAAa,KAAK,OAAO,OAAO,IAAI,KAAK;GAC9E,OAAO;IAAC;IAAQ,QAAQ;KAAC,GAAG;KAAQ,GAAG;IAAK;GAAC;EAC/C;CACF;CAEF,OAAO;AACT"}
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Preview perspective: which content layers (published, drafts, content releases) the site renders
3
+ * in Sanity preview mode. Shared by the server, the host and the bar UI, so it imports nothing.
4
+ *
5
+ * Release ordering, stacking, filtering and tones mirror the Studio's global perspective menu in
6
+ * `sanity@6.23` (`sortReleases`, `getReleasesPerspectiveStack`, `useActiveReleases`,
7
+ * `ReleasesList`, `getReleaseTone`). `test/preview-perspective.test.ts` checks `sortReleases`
8
+ * against the installed `sanity` export; re-check the rest when bumping `sanity`.
9
+ */
10
+ /** Same cookie the Studio's Presentation tool sets through `/preview/enable`. */
11
+ const PERSPECTIVE_COOKIE = "sanity-preview-perspective", PUBLISHED = "published", DRAFTS = "drafts", RELEASES_QUERY = "*[_type == \"system.release\" && _id in path(\"_.releases.*\")]{\n _id,\n _createdAt,\n state,\n publishAt,\n \"metadata\": coalesce(metadata, { \"title\": \"\", \"releaseType\": \"undecided\" })\n} | order(_createdAt desc)", ARCHIVED_RELEASE_STATES = ["archived", "published"], RELEASE_TYPES = [
12
+ "asap",
13
+ "scheduled",
14
+ "undecided"
15
+ ], RELEASE_ID = /^[a-zA-Z0-9_-]{1,64}$/, RESERVED = [
16
+ "raw",
17
+ PUBLISHED,
18
+ "previewDrafts"
19
+ ];
20
+ function releaseIdOf(release) {
21
+ return release._id.startsWith("_.releases.") ? release._id.slice(11) : release._id;
22
+ }
23
+ /** `sortReleases` from `sanity`: undecided (newest first), scheduled (latest first), then ASAP. */
24
+ function sortReleases(releases = []) {
25
+ return [...releases].sort((a, b) => {
26
+ let aType = a.metadata.releaseType, bType = b.metadata.releaseType;
27
+ if (aType === "undecided" && bType !== "undecided") return -1;
28
+ if (aType !== "undecided" && bType === "undecided") return 1;
29
+ if (aType === "undecided" && bType === "undecided") return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime();
30
+ if (aType === "scheduled" && bType === "scheduled") {
31
+ let aPublishAt = a.publishAt || a.metadata.intendedPublishAt;
32
+ if (!aPublishAt) return 1;
33
+ let bPublishAt = b.publishAt || b.metadata.intendedPublishAt;
34
+ return bPublishAt ? new Date(bPublishAt).getTime() - new Date(aPublishAt).getTime() : -1;
35
+ }
36
+ return aType === "asap" && bType !== "asap" ? 1 : aType !== "asap" && bType === "asap" ? -1 : aType === "asap" && bType === "asap" ? new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime() : 0;
37
+ });
38
+ }
39
+ /** `useActiveReleases`: not archived or published, in menu order (ASAP → scheduled → undecided). */
40
+ function activeReleases(releases) {
41
+ return sortReleases(releases.filter((release) => !ARCHIVED_RELEASE_STATES.includes(release.state))).reverse();
42
+ }
43
+ /** The menu hides single-document releases (Scheduled Drafts); the stack still includes them. */
44
+ function isScheduledDraft(release) {
45
+ return release.metadata.cardinality === "one";
46
+ }
47
+ /**
48
+ * `getReleasesPerspectiveStack` (draft model enabled): the selected release, every release that
49
+ * publishes before it, then drafts, minus excluded layers.
50
+ */
51
+ function perspectiveStack({ selected, releases, excluded = [] }) {
52
+ if (!selected || selected === "drafts") return DRAFTS;
53
+ if (selected === "published") return PUBLISHED;
54
+ let sorted = sortReleases(releases).map(releaseIdOf), index = sorted.indexOf(selected);
55
+ return index === -1 ? [selected, DRAFTS] : [...sorted.slice(index), DRAFTS].filter((name) => !excluded.includes(name));
56
+ }
57
+ /** Parses the cookie (`published`, `drafts`, or comma-separated IDs). Invalid values → drafts. */
58
+ function parsePerspective(value) {
59
+ if (!value || value === "drafts") return DRAFTS;
60
+ if (value === "published") return PUBLISHED;
61
+ let stack = value.split(",");
62
+ return stack.length > 32 || stack.some((name) => RESERVED.includes(name)) || !stack.every((name) => name === "drafts" || RELEASE_ID.test(name)) || stack.length === 1 && stack[0] === "drafts" ? DRAFTS : stack;
63
+ }
64
+ function serializePerspective(perspective) {
65
+ return Array.isArray(perspective) ? perspective.join(",") : perspective;
66
+ }
67
+ /**
68
+ * Recovers the menu state from a stored stack: the first layer is the selection, and anything the
69
+ * Studio would have stacked under it but is missing was hidden with the eye toggle.
70
+ */
71
+ function selectionOf(perspective, releases) {
72
+ if (!Array.isArray(perspective)) return {
73
+ selected: perspective,
74
+ excluded: []
75
+ };
76
+ let [selected = DRAFTS] = perspective, full = perspectiveStack({
77
+ selected,
78
+ releases
79
+ });
80
+ return {
81
+ selected,
82
+ excluded: Array.isArray(full) ? full.filter((name) => !perspective.includes(name)) : []
83
+ };
84
+ }
85
+ /**
86
+ * The Studio navbar's tone for a perspective (`RootCard tone={getReleaseTone(selectedPerspective)}`):
87
+ * published is positive, drafts default, a release takes its type's tone.
88
+ */
89
+ function perspectiveTone(perspective, releases) {
90
+ let { selected } = selectionOf(perspective, releases);
91
+ if (selected === "published") return "positive";
92
+ let release = releases.find((candidate) => releaseIdOf(candidate) === selected);
93
+ return release ? releaseTone(release) : "default";
94
+ }
95
+ /** `getReleaseTone` plus `RELEASE_TYPES_TONES`. */
96
+ function releaseTone(release) {
97
+ if (release.state === "archived") return "default";
98
+ switch (release.metadata.releaseType) {
99
+ case "asap": return "caution";
100
+ case "scheduled": return "suggest";
101
+ default: return "neutral";
102
+ }
103
+ }
104
+ export { RELEASE_TYPES as a, parsePerspective as c, releaseIdOf as d, releaseTone as f, sortReleases as h, RELEASES_QUERY as i, perspectiveStack as l, serializePerspective as m, PERSPECTIVE_COOKIE as n, activeReleases as o, selectionOf as p, PUBLISHED as r, isScheduledDraft as s, DRAFTS as t, perspectiveTone as u };
105
+
106
+ //# sourceMappingURL=perspective-BmS9TVtr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"perspective-BmS9TVtr.js","names":[],"sources":["../src/core/perspective.ts"],"sourcesContent":["/**\n * Preview perspective: which content layers (published, drafts, content releases) the site renders\n * in Sanity preview mode. Shared by the server, the host and the bar UI, so it imports nothing.\n *\n * Release ordering, stacking, filtering and tones mirror the Studio's global perspective menu in\n * `sanity@6.23` (`sortReleases`, `getReleasesPerspectiveStack`, `useActiveReleases`,\n * `ReleasesList`, `getReleaseTone`). `test/preview-perspective.test.ts` checks `sortReleases`\n * against the installed `sanity` export; re-check the rest when bumping `sanity`.\n */\n\n/** Same cookie the Studio's Presentation tool sets through `/preview/enable`. */\nexport const PERSPECTIVE_COOKIE = 'sanity-preview-perspective'\n\nexport const PUBLISHED = 'published'\nexport const DRAFTS = 'drafts'\n\n/** A resolved perspective: `published`, `drafts`, or a stack of release IDs ending in drafts. */\nexport type PreviewPerspective = typeof PUBLISHED | typeof DRAFTS | string[]\n\nexport type ReleaseType = 'asap' | 'scheduled' | 'undecided'\n\nexport type ReleaseDocument = {\n _id: string\n _createdAt: string\n state: string\n publishAt?: string | null\n metadata: {\n title?: string\n releaseType: ReleaseType\n intendedPublishAt?: string | null\n cardinality?: 'one' | 'many'\n }\n}\n\n/** The Studio's releases store query (`_.releases.*`, raw perspective). */\nexport const RELEASES_QUERY = `*[_type == \"system.release\" && _id in path(\"_.releases.*\")]{\n\t_id,\n\t_createdAt,\n\tstate,\n\tpublishAt,\n\t\"metadata\": coalesce(metadata, { \"title\": \"\", \"releaseType\": \"undecided\" })\n} | order(_createdAt desc)`\n\nconst RELEASE_DOCUMENTS_PREFIX = '_.releases.'\nconst ARCHIVED_RELEASE_STATES = ['archived', 'published']\nexport const RELEASE_TYPES: ReleaseType[] = ['asap', 'scheduled', 'undecided']\n/** Release IDs are `r` plus random characters; anything else in the cookie is rejected. */\nconst RELEASE_ID = /^[a-zA-Z0-9_-]{1,64}$/\n/** API perspective names that are not releases and must never appear inside a stack. */\nconst RESERVED = ['raw', PUBLISHED, 'previewDrafts']\n\nexport function releaseIdOf(release: ReleaseDocument) {\n return release._id.startsWith(RELEASE_DOCUMENTS_PREFIX)\n ? release._id.slice(RELEASE_DOCUMENTS_PREFIX.length)\n : release._id\n}\n\n/** `sortReleases` from `sanity`: undecided (newest first), scheduled (latest first), then ASAP. */\nexport function sortReleases(releases: ReleaseDocument[] = []) {\n return [...releases].sort((a, b) => {\n const aType = a.metadata.releaseType\n const bType = b.metadata.releaseType\n if (aType === 'undecided' && bType !== 'undecided') return -1\n if (aType !== 'undecided' && bType === 'undecided') return 1\n if (aType === 'undecided' && bType === 'undecided') {\n return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime()\n }\n if (aType === 'scheduled' && bType === 'scheduled') {\n const aPublishAt = a.publishAt || a.metadata.intendedPublishAt\n if (!aPublishAt) return 1\n const bPublishAt = b.publishAt || b.metadata.intendedPublishAt\n return bPublishAt ? new Date(bPublishAt).getTime() - new Date(aPublishAt).getTime() : -1\n }\n if (aType === 'asap' && bType !== 'asap') return 1\n if (aType !== 'asap' && bType === 'asap') return -1\n if (aType === 'asap' && bType === 'asap') {\n return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime()\n }\n return 0\n })\n}\n\n/** `useActiveReleases`: not archived or published, in menu order (ASAP → scheduled → undecided). */\nexport function activeReleases(releases: ReleaseDocument[]) {\n return sortReleases(\n releases.filter((release) => !ARCHIVED_RELEASE_STATES.includes(release.state)),\n ).reverse()\n}\n\n/** The menu hides single-document releases (Scheduled Drafts); the stack still includes them. */\nexport function isScheduledDraft(release: ReleaseDocument) {\n return release.metadata.cardinality === 'one'\n}\n\n/**\n * `getReleasesPerspectiveStack` (draft model enabled): the selected release, every release that\n * publishes before it, then drafts, minus excluded layers.\n */\nexport function perspectiveStack({\n selected,\n releases,\n excluded = [],\n}: {\n selected: string | undefined\n releases: ReleaseDocument[]\n excluded?: string[]\n}): PreviewPerspective {\n if (!selected || selected === DRAFTS) return DRAFTS\n if (selected === PUBLISHED) return PUBLISHED\n const sorted = sortReleases(releases).map(releaseIdOf)\n const index = sorted.indexOf(selected)\n if (index === -1) return [selected, DRAFTS]\n return [...sorted.slice(index), DRAFTS].filter((name) => !excluded.includes(name))\n}\n\n/** Parses the cookie (`published`, `drafts`, or comma-separated IDs). Invalid values → drafts. */\nexport function parsePerspective(value: string | undefined): PreviewPerspective {\n if (!value || value === DRAFTS) return DRAFTS\n if (value === PUBLISHED) return PUBLISHED\n const stack = value.split(',')\n if (stack.length > 32 || stack.some((name) => RESERVED.includes(name))) return DRAFTS\n if (!stack.every((name) => name === DRAFTS || RELEASE_ID.test(name))) return DRAFTS\n return stack.length === 1 && stack[0] === DRAFTS ? DRAFTS : stack\n}\n\nexport function serializePerspective(perspective: PreviewPerspective) {\n return Array.isArray(perspective) ? perspective.join(',') : perspective\n}\n\n/**\n * Recovers the menu state from a stored stack: the first layer is the selection, and anything the\n * Studio would have stacked under it but is missing was hidden with the eye toggle.\n */\nexport function selectionOf(perspective: PreviewPerspective, releases: ReleaseDocument[]) {\n if (!Array.isArray(perspective)) return {selected: perspective, excluded: [] as string[]}\n const [selected = DRAFTS] = perspective\n const full = perspectiveStack({selected, releases})\n const excluded = Array.isArray(full) ? full.filter((name) => !perspective.includes(name)) : []\n return {selected, excluded}\n}\n\n/**\n * The Studio navbar's tone for a perspective (`RootCard tone={getReleaseTone(selectedPerspective)}`):\n * published is positive, drafts default, a release takes its type's tone.\n */\nexport function perspectiveTone(perspective: PreviewPerspective, releases: ReleaseDocument[]) {\n const {selected} = selectionOf(perspective, releases)\n if (selected === PUBLISHED) return 'positive'\n const release = releases.find((candidate) => releaseIdOf(candidate) === selected)\n return release ? releaseTone(release) : 'default'\n}\n\n/** `getReleaseTone` plus `RELEASE_TYPES_TONES`. */\nexport function releaseTone(release: ReleaseDocument) {\n if (release.state === 'archived') return 'default'\n switch (release.metadata.releaseType) {\n case 'asap':\n return 'caution'\n case 'scheduled':\n return 'suggest'\n default:\n return 'neutral'\n }\n}\n"],"mappings":";;;;;;;;;;AAWA,MAAa,qBAAqB,8BAErB,YAAY,aACZ,SAAS,UAqBT,iBAAiB,mOASxB,0BAA0B,CAAC,YAAY,WAAW,GAC3C,gBAA+B;CAAC;CAAQ;CAAa;AAAW,GAEvE,aAAa,yBAEb,WAAW;CAAC;CAAO;CAAW;AAAe;AAEnD,SAAgB,YAAY,SAA0B;CACpD,OAAO,QAAQ,IAAI,WAAW,aAAwB,IAClD,QAAQ,IAAI,MAAM,EAA+B,IACjD,QAAQ;AACd;;AAGA,SAAgB,aAAa,WAA8B,CAAC,GAAG;CAC7D,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC,MAAM,GAAG,MAAM;EAClC,IAAM,QAAQ,EAAE,SAAS,aACnB,QAAQ,EAAE,SAAS;EACzB,IAAI,UAAU,eAAe,UAAU,aAAa,OAAO;EAC3D,IAAI,UAAU,eAAe,UAAU,aAAa,OAAO;EAC3D,IAAI,UAAU,eAAe,UAAU,aACrC,OAAO,IAAI,KAAK,EAAE,UAAU,CAAC,CAAC,QAAQ,IAAI,IAAI,KAAK,EAAE,UAAU,CAAC,CAAC,QAAQ;EAE3E,IAAI,UAAU,eAAe,UAAU,aAAa;GAClD,IAAM,aAAa,EAAE,aAAa,EAAE,SAAS;GAC7C,IAAI,CAAC,YAAY,OAAO;GACxB,IAAM,aAAa,EAAE,aAAa,EAAE,SAAS;GAC7C,OAAO,aAAa,IAAI,KAAK,UAAU,CAAC,CAAC,QAAQ,IAAI,IAAI,KAA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,WAAW,IAAI,YAAY,KAAK,GAAG,IAAI;AAC9D;;;;;AAMA,SAAgB,YAAY,aAAiC,UAA6B;CACxF,IAAI,CAAC,MAAM,QAAQ,WAAW,GAAG,OAAO;EAAC,UAAU;EAAa,UAAU,CAAC;CAAa;CACxF,IAAM,CAAC,WAAW,UAAU,aACtB,OAAO,iBAAiB;EAAC;EAAU;CAAQ,CAAC;CAElD,OAAO;EAAC;EAAU,UADD,MAAM,QAAQ,IAAI,IAAI,KAAK,QAAQ,SAAS,CAAC,YAAY,SAAS,IAAI,CAAC,IAAI,CAAC;CACnE;AAC5B;;;;;AAMA,SAAgB,gBAAgB,aAAiC,UAA6B;CAC5F,IAAM,EAAC,aAAY,YAAY,aAAa,QAAQ;CACpD,IAAI,aAAA,aAAwB,OAAO;CACnC,IAAM,UAAU,SAAS,MAAM,cAAc,YAAY,SAAS,MAAM,QAAQ;CAChF,OAAO,UAAU,YAAY,OAAO,IAAI;AAC1C;;AAGA,SAAgB,YAAY,SAA0B;CACpD,IAAI,QAAQ,UAAU,YAAY,OAAO;CACzC,QAAQ,QAAQ,SAAS,aAAzB;EACE,KAAK,QACH,OAAO;EACT,KAAK,aACH,OAAO;EACT,SACE,OAAO;CACX;AACF"}
@@ -0,0 +1,119 @@
1
+ import { k as sameOriginPath } from "./protocol-BNO38gYy.js";
2
+ /**
3
+ * Short, expiring preview links (`/p/<code>`), like Shopify's "Share preview". The preview bar asks
4
+ * `/__visual-editor/share` for one while Presentation's "Share this preview" is on; opening it sets the
5
+ * preview cookies and redirects to the stored page. A `PreviewLinkStore` (Workers KV,
6
+ * or anything with a TTL) holds `code → { pathname, perspective, createdAt }`, so no secret ever
7
+ * appears in the URL. The store should expire the entry on its own; the server also checks
8
+ * `createdAt` against the TTL, so a store that keeps entries forever doesn't make links permanent.
9
+ */
10
+ /** Links open for 2 days, like Shopify's preview links. */
11
+ const PREVIEW_LINK_TTL_SECONDS = 172800, PREVIEW_LINK_ROUTE = "/p/", PREVIEW_LINK_KEY_PREFIX = "preview-link:", PREVIEW_LINK_CODE_LENGTH = 12, CODE_PATTERN = /* @__PURE__ */ RegExp("^[A-Za-z0-9]{12}$");
12
+ /**
13
+ * A random code from `crypto.getRandomValues`. Bytes ≥ 248 are dropped (248 = 4 × 62) so every
14
+ * character is equally likely.
15
+ */
16
+ function generatePreviewLinkCode(fillRandom = (array) => crypto.getRandomValues(array)) {
17
+ let code = "";
18
+ for (; code.length < 12;) {
19
+ let bytes = /* @__PURE__ */ new Uint8Array(24);
20
+ fillRandom(bytes);
21
+ for (let byte of bytes) if (!(byte >= 248) && (code += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[byte % 62], code.length === 12)) break;
22
+ }
23
+ return code;
24
+ }
25
+ /** Whether `value` could be a code we minted; anything else 404s without a KV read. */
26
+ function isPreviewLinkCode(value) {
27
+ return CODE_PATTERN.test(value);
28
+ }
29
+ function previewLinkKey(code) {
30
+ return `${PREVIEW_LINK_KEY_PREFIX}${code}`;
31
+ }
32
+ /**
33
+ * A root-relative path on this site, normalized (pathname and query, no hash), or `null`. Rejects
34
+ * protocol-relative `//host` and `/\host` (browsers read a backslash as a slash), absolute URLs,
35
+ * control characters and anything that resolves to another origin or to `//host`, before or after
36
+ * dot segments are removed (`/.//host`, `/%2e%2e//host`). See `sameOriginPath`.
37
+ */
38
+ function normalizePreviewPathname(value) {
39
+ if (typeof value != "string" || value.length === 0 || value.length > 2048) return null;
40
+ let path = sameOriginPath(value);
41
+ if (!path) return null;
42
+ let hash = path.indexOf("#");
43
+ return hash === -1 ? path : path.slice(0, hash);
44
+ }
45
+ /** The KV entry and put options for a new link, and when it stops opening. */
46
+ function createPreviewLink({ code, pathname, perspective, now = Date.now(), ttlSeconds = PREVIEW_LINK_TTL_SECONDS, route = "/p/" }) {
47
+ let value = {
48
+ pathname,
49
+ perspective,
50
+ createdAt: new Date(now).toISOString()
51
+ };
52
+ return {
53
+ key: previewLinkKey(code),
54
+ value,
55
+ ttlSeconds,
56
+ path: `${route}${code}`,
57
+ expiresAt: new Date(now + ttlSeconds * 1e3).toISOString()
58
+ };
59
+ }
60
+ /**
61
+ * When a stored link stops opening (ms since the epoch), from its `createdAt` and the TTL, or
62
+ * `null` when `createdAt` isn't a date.
63
+ */
64
+ function previewLinkExpiry(value, ttlSeconds) {
65
+ let createdAt = Date.parse(value.createdAt);
66
+ return Number.isFinite(createdAt) ? createdAt + ttlSeconds * 1e3 : null;
67
+ }
68
+ /** Reads a stored entry back, or `null` when it isn't one of ours (or its path no longer validates). */
69
+ function parsePreviewLinkValue(raw) {
70
+ if (!raw || typeof raw != "object") return null;
71
+ let { pathname, perspective, createdAt } = raw, safePathname = normalizePreviewPathname(pathname);
72
+ return !safePathname || typeof perspective != "string" || typeof createdAt != "string" ? null : {
73
+ pathname: safePathname,
74
+ perspective,
75
+ createdAt
76
+ };
77
+ }
78
+ /** The shortest link lifetime: Workers KV's minimum `expirationTtl`. */
79
+ const MIN_LINK_TTL_SECONDS = 60;
80
+ /**
81
+ * Returns `ttlSeconds` if it's a whole number of seconds, at least `MIN_LINK_TTL_SECONDS`;
82
+ * otherwise throws, so a bad `links.ttlSeconds` fails at startup rather than on every share.
83
+ */
84
+ function assertLinkTtl(ttlSeconds) {
85
+ if (!Number.isInteger(ttlSeconds) || ttlSeconds < 60) throw Error(`sanity-visual-editor: links.ttlSeconds must be a whole number of seconds, at least 60 (got ${String(ttlSeconds)})`);
86
+ return ttlSeconds;
87
+ }
88
+ /** A Cloudflare Workers KV store. KV's minimum TTL is 60 seconds. */
89
+ function kvStore(namespace) {
90
+ return {
91
+ async get(key) {
92
+ if (!namespace) throw Error("sanity-visual-editor: the KV namespace binding is missing");
93
+ return namespace.get(key, "json");
94
+ },
95
+ async put(key, value, ttlSeconds) {
96
+ if (!namespace) throw Error("sanity-visual-editor: the KV namespace binding is missing");
97
+ await namespace.put(key, JSON.stringify(value), { expirationTtl: assertLinkTtl(ttlSeconds) });
98
+ }
99
+ };
100
+ }
101
+ /** An in-memory store for tests and local experiments; entries vanish on restart. */
102
+ function memoryStore(now = Date.now) {
103
+ let entries = /* @__PURE__ */ new Map();
104
+ return {
105
+ async get(key) {
106
+ let entry = entries.get(key);
107
+ return entry ? entry.expiresAt <= now() ? (entries.delete(key), null) : entry.value : null;
108
+ },
109
+ async put(key, value, ttlSeconds) {
110
+ entries.set(key, {
111
+ value,
112
+ expiresAt: now() + ttlSeconds * 1e3
113
+ });
114
+ }
115
+ };
116
+ }
117
+ export { PREVIEW_LINK_TTL_SECONDS as a, generatePreviewLinkCode as c, memoryStore as d, normalizePreviewPathname as f, previewLinkKey as h, PREVIEW_LINK_ROUTE as i, isPreviewLinkCode as l, previewLinkExpiry as m, PREVIEW_LINK_CODE_LENGTH as n, assertLinkTtl as o, parsePreviewLinkValue as p, PREVIEW_LINK_KEY_PREFIX as r, createPreviewLink as s, MIN_LINK_TTL_SECONDS as t, kvStore as u };
118
+
119
+ //# sourceMappingURL=preview-links-BZDZyIey.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preview-links-BZDZyIey.js","names":[],"sources":["../src/core/preview-links.ts"],"sourcesContent":["/**\n * Short, expiring preview links (`/p/<code>`), like Shopify's \"Share preview\". The preview bar asks\n * `/__visual-editor/share` for one while Presentation's \"Share this preview\" is on; opening it sets the\n * preview cookies and redirects to the stored page. A `PreviewLinkStore` (Workers KV,\n * or anything with a TTL) holds `code → { pathname, perspective, createdAt }`, so no secret ever\n * appears in the URL. The store should expire the entry on its own; the server also checks\n * `createdAt` against the TTL, so a store that keeps entries forever doesn't make links permanent.\n */\n\nimport {sameOriginPath} from './paths'\n\n/** Links open for 2 days, like Shopify's preview links. */\nexport const PREVIEW_LINK_TTL_SECONDS = 2 * 24 * 60 * 60\n\n/** Default route prefix for the short links; disallow it in `robots.txt`. */\nexport const PREVIEW_LINK_ROUTE = '/p/'\n\n/** KV key prefix, so the namespace can hold other kinds of entry later. */\nexport const PREVIEW_LINK_KEY_PREFIX = 'preview-link:'\n\n/** Base62: URL-safe, no punctuation at the ends of a link. 12 characters ≈ 71 bits. */\nconst ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\nexport const PREVIEW_LINK_CODE_LENGTH = 12\nconst CODE_PATTERN = new RegExp(`^[A-Za-z0-9]{${PREVIEW_LINK_CODE_LENGTH}}$`)\n\n/** Longest page path (with query) a link may store. */\nconst MAX_PATHNAME_LENGTH = 2048\n\nexport type PreviewLinkValue = {\n /** Root-relative page path, with any query string. */\n pathname: string\n /** Serialized perspective, the `sanity-preview-perspective` cookie value. */\n perspective: string\n /** ISO timestamp. */\n createdAt: string\n}\n\n/**\n * A random code from `crypto.getRandomValues`. Bytes ≥ 248 are dropped (248 = 4 × 62) so every\n * character is equally likely.\n */\nexport function generatePreviewLinkCode(\n fillRandom: (array: Uint8Array<ArrayBuffer>) => void = (array) => crypto.getRandomValues(array),\n) {\n let code = ''\n while (code.length < PREVIEW_LINK_CODE_LENGTH) {\n const bytes = new Uint8Array(PREVIEW_LINK_CODE_LENGTH * 2)\n fillRandom(bytes)\n for (const byte of bytes) {\n if (byte >= 248) continue\n code += ALPHABET[byte % ALPHABET.length]\n if (code.length === PREVIEW_LINK_CODE_LENGTH) break\n }\n }\n return code\n}\n\n/** Whether `value` could be a code we minted; anything else 404s without a KV read. */\nexport function isPreviewLinkCode(value: string) {\n return CODE_PATTERN.test(value)\n}\n\nexport function previewLinkKey(code: string) {\n return `${PREVIEW_LINK_KEY_PREFIX}${code}`\n}\n\n/**\n * A root-relative path on this site, normalized (pathname and query, no hash), or `null`. Rejects\n * protocol-relative `//host` and `/\\host` (browsers read a backslash as a slash), absolute URLs,\n * control characters and anything that resolves to another origin or to `//host`, before or after\n * dot segments are removed (`/.//host`, `/%2e%2e//host`). See `sameOriginPath`.\n */\nexport function normalizePreviewPathname(value: unknown): string | null {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_PATHNAME_LENGTH) {\n return null\n }\n const path = sameOriginPath(value)\n if (!path) return null\n // Neither a pathname nor a query can hold `#`, so the hash starts at the first one.\n const hash = path.indexOf('#')\n return hash === -1 ? path : path.slice(0, hash)\n}\n\n/** The KV entry and put options for a new link, and when it stops opening. */\nexport function createPreviewLink({\n code,\n pathname,\n perspective,\n now = Date.now(),\n ttlSeconds = PREVIEW_LINK_TTL_SECONDS,\n route = PREVIEW_LINK_ROUTE,\n}: {\n code: string\n pathname: string\n perspective: string\n now?: number\n ttlSeconds?: number\n route?: string\n}) {\n const value: PreviewLinkValue = {pathname, perspective, createdAt: new Date(now).toISOString()}\n return {\n key: previewLinkKey(code),\n value,\n ttlSeconds,\n path: `${route}${code}`,\n expiresAt: new Date(now + ttlSeconds * 1000).toISOString(),\n }\n}\n\n/**\n * When a stored link stops opening (ms since the epoch), from its `createdAt` and the TTL, or\n * `null` when `createdAt` isn't a date.\n */\nexport function previewLinkExpiry(value: Pick<PreviewLinkValue, 'createdAt'>, ttlSeconds: number) {\n const createdAt = Date.parse(value.createdAt)\n return Number.isFinite(createdAt) ? createdAt + ttlSeconds * 1000 : null\n}\n\n/** Reads a stored entry back, or `null` when it isn't one of ours (or its path no longer validates). */\nexport function parsePreviewLinkValue(raw: unknown): PreviewLinkValue | null {\n if (!raw || typeof raw !== 'object') return null\n const {pathname, perspective, createdAt} = raw as Record<string, unknown>\n const safePathname = normalizePreviewPathname(pathname)\n if (!safePathname || typeof perspective !== 'string' || typeof createdAt !== 'string') {\n return null\n }\n return {pathname: safePathname, perspective, createdAt}\n}\n\n/**\n * Where short links live. `get` returns the stored value (parsed JSON) or `null`; `put` stores it\n * for `ttlSeconds` and lets it expire on its own. See `kvStore` and `memoryStore`.\n */\nexport type PreviewLinkStore = {\n get(key: string): Promise<unknown>\n put(key: string, value: PreviewLinkValue, ttlSeconds: number): Promise<void>\n}\n\n/** The slice of a Cloudflare Workers KV namespace the store uses. */\nexport type KVNamespaceLike = {\n get(key: string, type: 'json'): Promise<unknown>\n put(key: string, value: string, options: {expirationTtl: number}): Promise<void>\n}\n\n/** The shortest link lifetime: Workers KV's minimum `expirationTtl`. */\nexport const MIN_LINK_TTL_SECONDS = 60\n\n/**\n * Returns `ttlSeconds` if it's a whole number of seconds, at least `MIN_LINK_TTL_SECONDS`;\n * otherwise throws, so a bad `links.ttlSeconds` fails at startup rather than on every share.\n */\nexport function assertLinkTtl(ttlSeconds: number): number {\n if (!Number.isInteger(ttlSeconds) || ttlSeconds < MIN_LINK_TTL_SECONDS) {\n throw new Error(\n `sanity-visual-editor: links.ttlSeconds must be a whole number of seconds, at least ${MIN_LINK_TTL_SECONDS} (got ${String(ttlSeconds)})`,\n )\n }\n return ttlSeconds\n}\n\n/** A Cloudflare Workers KV store. KV's minimum TTL is 60 seconds. */\nexport function kvStore(namespace: KVNamespaceLike | undefined | null): PreviewLinkStore {\n return {\n async get(key) {\n if (!namespace) throw new Error('sanity-visual-editor: the KV namespace binding is missing')\n return namespace.get(key, 'json')\n },\n async put(key, value, ttlSeconds) {\n if (!namespace) throw new Error('sanity-visual-editor: the KV namespace binding is missing')\n await namespace.put(key, JSON.stringify(value), {expirationTtl: assertLinkTtl(ttlSeconds)})\n },\n }\n}\n\n/** An in-memory store for tests and local experiments; entries vanish on restart. */\nexport function memoryStore(now: () => number = Date.now): PreviewLinkStore {\n const entries = new Map<string, {value: PreviewLinkValue; expiresAt: number}>()\n return {\n async get(key) {\n const entry = entries.get(key)\n if (!entry) return null\n if (entry.expiresAt <= now()) {\n entries.delete(key)\n return null\n }\n return entry.value\n },\n async put(key, value, ttlSeconds) {\n entries.set(key, {value, expiresAt: now() + ttlSeconds * 1000})\n },\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAa,2BAA2B,QAG3B,qBAAqB,OAGrB,0BAA0B,iBAI1B,2BAA2B,IAClC,eAAe,gBAAI,OAAO,mBAA4C;;;;;AAkB5E,SAAgB,wBACd,cAAwD,UAAU,OAAO,gBAAgB,KAAK,GAC9F;CACA,IAAI,OAA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B,OAAO,eAAgB,YAAY,OAAO,aAAc,WACpE,OAEF;EAAC,UAAU;EAAc;EAAa;CAAS;AACxD;;AAkBA,MAAa,uBAAuB;;;;;AAMpC,SAAgB,cAAc,YAA4B;CACxD,IAAI,CAAC,OAAO,UAAU,UAAU,KAAK,aAAA,IACnC,MAAU,MACR,8FAAmH,OAAO,UAAU,EAAE,EACxI;CAEF,OAAO;AACT;;AAGA,SAAgB,QAAQ,WAAiE;CACvF,OAAO;EACL,MAAM,IAAI,KAAK;GACb,IAAI,CAAC,WAAW,MAAU,MAAM,2DAA2D;GAC3F,OAAO,UAAU,IAAI,KAAK,MAAM;EAClC;EACA,MAAM,IAAI,KAAK,OAAO,YAAY;GAChC,IAAI,CAAC,WAAW,MAAU,MAAM,2DAA2D;GAC3F,MAAM,UAAU,IAAI,KAAK,KAAK,UAAU,KAAK,GAAG,EAAC,eAAe,cAAc,UAAU,EAAC,CAAC;EAC5F;CACF;AACF;;AAGA,SAAgB,YAAY,MAAoB,KAAK,KAAuB;CAC1E,IAAM,0BAAU,IAAI,IAA0D;CAC9E,OAAO;EACL,MAAM,IAAI,KAAK;GACb,IAAM,QAAQ,QAAQ,IAAI,GAAG;GAM7B,OALK,QACD,MAAM,aAAa,IAAI,KACzB,QAAQ,OAAO,GAAG,GACX,QAEF,MAAM,QALM;EAMrB;EACA,MAAM,IAAI,KAAK,OAAO,YAAY;GAChC,QAAQ,IAAI,KAAK;IAAC;IAAO,WAAW,IAAI,IAAI,aAAa;GAAI,CAAC;EAChE;CACF;AACF"}
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Short, expiring preview links (`/p/<code>`), like Shopify's "Share preview". The preview bar asks
3
+ * `/__visual-editor/share` for one while Presentation's "Share this preview" is on; opening it sets the
4
+ * preview cookies and redirects to the stored page. A `PreviewLinkStore` (Workers KV,
5
+ * or anything with a TTL) holds `code → { pathname, perspective, createdAt }`, so no secret ever
6
+ * appears in the URL. The store should expire the entry on its own; the server also checks
7
+ * `createdAt` against the TTL, so a store that keeps entries forever doesn't make links permanent.
8
+ */
9
+ /** Links open for 2 days, like Shopify's preview links. */
10
+ declare const PREVIEW_LINK_TTL_SECONDS: number;
11
+ /** Default route prefix for the short links; disallow it in `robots.txt`. */
12
+ declare const PREVIEW_LINK_ROUTE = "/p/";
13
+ /** KV key prefix, so the namespace can hold other kinds of entry later. */
14
+ declare const PREVIEW_LINK_KEY_PREFIX = "preview-link:";
15
+ declare const PREVIEW_LINK_CODE_LENGTH = 12;
16
+ type PreviewLinkValue = {
17
+ /** Root-relative page path, with any query string. */
18
+ pathname: string;
19
+ /** Serialized perspective, the `sanity-preview-perspective` cookie value. */
20
+ perspective: string;
21
+ /** ISO timestamp. */
22
+ createdAt: string;
23
+ };
24
+ /**
25
+ * A random code from `crypto.getRandomValues`. Bytes ≥ 248 are dropped (248 = 4 × 62) so every
26
+ * character is equally likely.
27
+ */
28
+ declare function generatePreviewLinkCode(fillRandom?: (array: Uint8Array<ArrayBuffer>) => void): string;
29
+ /** Whether `value` could be a code we minted; anything else 404s without a KV read. */
30
+ declare function isPreviewLinkCode(value: string): boolean;
31
+ declare function previewLinkKey(code: string): string;
32
+ /**
33
+ * A root-relative path on this site, normalized (pathname and query, no hash), or `null`. Rejects
34
+ * protocol-relative `//host` and `/\host` (browsers read a backslash as a slash), absolute URLs,
35
+ * control characters and anything that resolves to another origin or to `//host`, before or after
36
+ * dot segments are removed (`/.//host`, `/%2e%2e//host`). See `sameOriginPath`.
37
+ */
38
+ declare function normalizePreviewPathname(value: unknown): string | null;
39
+ /** The KV entry and put options for a new link, and when it stops opening. */
40
+ declare function createPreviewLink({ code, pathname, perspective, now, ttlSeconds, route }: {
41
+ code: string;
42
+ pathname: string;
43
+ perspective: string;
44
+ now?: number;
45
+ ttlSeconds?: number;
46
+ route?: string;
47
+ }): {
48
+ key: string;
49
+ value: PreviewLinkValue;
50
+ ttlSeconds: number;
51
+ path: string;
52
+ expiresAt: string;
53
+ };
54
+ /**
55
+ * When a stored link stops opening (ms since the epoch), from its `createdAt` and the TTL, or
56
+ * `null` when `createdAt` isn't a date.
57
+ */
58
+ declare function previewLinkExpiry(value: Pick<PreviewLinkValue, 'createdAt'>, ttlSeconds: number): number | null;
59
+ /** Reads a stored entry back, or `null` when it isn't one of ours (or its path no longer validates). */
60
+ declare function parsePreviewLinkValue(raw: unknown): PreviewLinkValue | null;
61
+ /**
62
+ * Where short links live. `get` returns the stored value (parsed JSON) or `null`; `put` stores it
63
+ * for `ttlSeconds` and lets it expire on its own. See `kvStore` and `memoryStore`.
64
+ */
65
+ type PreviewLinkStore = {
66
+ get(key: string): Promise<unknown>;
67
+ put(key: string, value: PreviewLinkValue, ttlSeconds: number): Promise<void>;
68
+ };
69
+ /** The slice of a Cloudflare Workers KV namespace the store uses. */
70
+ type KVNamespaceLike = {
71
+ get(key: string, type: 'json'): Promise<unknown>;
72
+ put(key: string, value: string, options: {
73
+ expirationTtl: number;
74
+ }): Promise<void>;
75
+ };
76
+ /** The shortest link lifetime: Workers KV's minimum `expirationTtl`. */
77
+ declare const MIN_LINK_TTL_SECONDS = 60;
78
+ /**
79
+ * Returns `ttlSeconds` if it's a whole number of seconds, at least `MIN_LINK_TTL_SECONDS`;
80
+ * otherwise throws, so a bad `links.ttlSeconds` fails at startup rather than on every share.
81
+ */
82
+ declare function assertLinkTtl(ttlSeconds: number): number;
83
+ /** A Cloudflare Workers KV store. KV's minimum TTL is 60 seconds. */
84
+ declare function kvStore(namespace: KVNamespaceLike | undefined | null): PreviewLinkStore;
85
+ /** An in-memory store for tests and local experiments; entries vanish on restart. */
86
+ declare function memoryStore(now?: () => number): PreviewLinkStore;
87
+ export { previewLinkExpiry as _, PREVIEW_LINK_ROUTE as a, PreviewLinkValue as c, generatePreviewLinkCode as d, isPreviewLinkCode as f, parsePreviewLinkValue as g, normalizePreviewPathname as h, PREVIEW_LINK_KEY_PREFIX as i, assertLinkTtl as l, memoryStore as m, MIN_LINK_TTL_SECONDS as n, PREVIEW_LINK_TTL_SECONDS as o, kvStore as p, PREVIEW_LINK_CODE_LENGTH as r, PreviewLinkStore as s, KVNamespaceLike as t, createPreviewLink as u, previewLinkKey as v };