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.
Files changed (60) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +137 -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 +76 -0
  10. package/dist/cloudflare.js +1071 -0
  11. package/dist/cloudflare.js.map +1 -0
  12. package/dist/data-D0qotTtt.d.ts +177 -0
  13. package/dist/host-DreYJEmR.js +615 -0
  14. package/dist/host-DreYJEmR.js.map +1 -0
  15. package/dist/host.d.ts +160 -0
  16. package/dist/host.js +3 -0
  17. package/dist/index-4Zm_NjhC.d.ts +221 -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/link-session-Dr4YkKFy.js +52 -0
  23. package/dist/link-session-Dr4YkKFy.js.map +1 -0
  24. package/dist/next-client.d.ts +15 -0
  25. package/dist/next-client.js +78 -0
  26. package/dist/next-client.js.map +1 -0
  27. package/dist/next.d.ts +38 -0
  28. package/dist/next.js +117 -0
  29. package/dist/next.js.map +1 -0
  30. package/dist/node-labels-CDiW5rMq.js +122 -0
  31. package/dist/node-labels-CDiW5rMq.js.map +1 -0
  32. package/dist/page-documents-BFFcH8lD.d.ts +54 -0
  33. package/dist/page-documents-mGfw_flR.js +67 -0
  34. package/dist/page-documents-mGfw_flR.js.map +1 -0
  35. package/dist/perspective-BmS9TVtr.js +106 -0
  36. package/dist/perspective-BmS9TVtr.js.map +1 -0
  37. package/dist/preview-links-BZDZyIey.js +119 -0
  38. package/dist/preview-links-BZDZyIey.js.map +1 -0
  39. package/dist/preview-links-DM6BCiLV.d.ts +87 -0
  40. package/dist/protocol-BNO38gYy.js +280 -0
  41. package/dist/protocol-BNO38gYy.js.map +1 -0
  42. package/dist/protocol-BnRCy2wJ.d.ts +386 -0
  43. package/dist/server.d.ts +4 -0
  44. package/dist/server.js +495 -0
  45. package/dist/server.js.map +1 -0
  46. package/dist/shell-DZotxRXX.d.ts +37 -0
  47. package/dist/studio.d.ts +93 -0
  48. package/dist/studio.js +1263 -0
  49. package/dist/studio.js.map +1 -0
  50. package/dist/sveltekit.d.ts +281 -0
  51. package/dist/sveltekit.js +395 -0
  52. package/dist/sveltekit.js.map +1 -0
  53. package/package.json +120 -39
  54. package/dist/index.d.mts +0 -21
  55. package/dist/index.js.map +0 -1
  56. package/dist/index.mjs +0 -8
  57. package/dist/index.mjs.map +0 -1
  58. package/sanity.json +0 -8
  59. package/src/index.ts +0 -27
  60. package/v2-incompatible.js +0 -11
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2025 Dennis Regalado
3
+ Copyright (c) 2026 Dennis Regalado
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,35 +1,156 @@
1
1
  # sanity-plugin-visual-editor
2
2
 
3
- > This is a **Sanity Studio v3** plugin.
3
+ Visual Editor, preview bar, click-to-edit overlays, short preview links, and Cloudflare realtime live edits for **Sanity + SvelteKit** (and Next.js).
4
4
 
5
- ## Installation
5
+ ## What you get
6
6
 
7
- ```sh
8
- npm install sanity-plugin-visual-editor
7
+ - **Studio Visual Editor (`sanity-plugin-visual-editor/studio`)**: Replaces Presentation with a unified toolbar, desktop/tablet/mobile viewport switcher, document pane, `defineLocations` / `defineDocuments`, and automatic keystroke-level **live edits** (including Portable Text).
8
+ - **One-stop server handler (`sanity-plugin-visual-editor/sveltekit`)**: One `createSvelteKitVisualEditor(config)` + `visualEditor.handle` in `hooks.server.ts` handles perspective cookies, `?studio-preview` bypass, `/__visual-editor/*` endpoints, `/p/<code>` short preview links (with customizable error HTML), `/api/preview/*` live-edit sessions, and Cloudflare WebSocket `101` upgrades.
9
+ - **One-call storefront client (`sanity-plugin-visual-editor/host`)**: `connectVisualEditor(...)` mounts the preview bar or Visual Editor click-to-edit overlay and subscribes to realtime hub invalidations.
10
+ - **Zero-dependency annotations (`sanity-plugin-visual-editor`)**: `sanityAttr(doc, path, { enabled })` and `createSanityAttr(doc, { enabled })` emit `data-sanity` attributes for click-to-edit overlays.
11
+ - **Cloudflare Realtime Hub (`sanity-plugin-visual-editor/cloudflare`)**: Drop-in `PreviewHub` Durable Object + Worker entry for sub-second draft updates across all tabs.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ bun add sanity-plugin-visual-editor
9
17
  ```
10
18
 
11
- ## Usage
19
+ ## Quick Start (SvelteKit × Sanity × Cloudflare)
12
20
 
13
- Add it as a plugin in `sanity.config.ts` (or .js):
21
+ ### 1. Sanity Studio (`sanity.studio.ts`)
14
22
 
15
23
  ```ts
16
24
  import {defineConfig} from 'sanity'
17
- import {myPlugin} from 'sanity-plugin-visual-editor'
25
+ import {defineDocuments, defineLocations, visualEditor} from 'sanity-plugin-visual-editor/studio'
18
26
 
19
27
  export default defineConfig({
20
- //...
21
- plugins: [myPlugin({})],
28
+ // ...
29
+ plugins: [
30
+ visualEditor({
31
+ previewUrl: {initial: '/', previewMode: {enable: '/preview/enable'}},
32
+ resolve: {
33
+ mainDocuments: defineDocuments([
34
+ {route: '/', type: 'homepage'},
35
+ {route: '/pages/:slug', type: 'page'},
36
+ ]),
37
+ locations: {
38
+ page: defineLocations({
39
+ select: {title: 'title', slug: 'slug.current'},
40
+ resolve: (doc) => ({
41
+ locations: [{title: doc?.title || 'Untitled', href: `/pages/${doc?.slug}`}],
42
+ }),
43
+ }),
44
+ },
45
+ },
46
+ // Live edits are enabled by default; pass `liveEdit: false` to disable.
47
+ }),
48
+ ],
22
49
  })
23
50
  ```
24
51
 
25
- ## License
52
+ ### 2. Server Config (`src/lib/server/visual-editor.ts`)
53
+
54
+ ```ts
55
+ import {env} from 'cloudflare:workers'
56
+ import {SANITY_PREVIEW_SECRET} from '$app/env/private'
57
+ import {serverClient} from '$sanity/client.server'
58
+ import {kvStore, type PreviewHubFetcher} from 'sanity-plugin-visual-editor/server'
59
+ import {createSvelteKitVisualEditor} from 'sanity-plugin-visual-editor/sveltekit'
60
+
61
+ export const visualEditor = createSvelteKitVisualEditor({
62
+ secret: () => SANITY_PREVIEW_SECRET,
63
+ client: serverClient,
64
+ brand: {title: 'My Store'},
65
+ studioPath: '/studio',
66
+ pageDocuments: MAIN_DOCUMENTS,
67
+ search: {routes, types},
68
+ links: {store: () => kvStore(env.PREVIEW_LINKS)},
69
+ hub: () => env.PREVIEW_HUB as PreviewHubFetcher | undefined,
70
+ // Optional: customize expired / unavailable `/p/<code>` HTML screens
71
+ // renderLinkError: ({expired, brand}) => `<html>...</html>`,
72
+ })
73
+ ```
26
74
 
27
- [MIT](LICENSE) © Dennis Regalado
75
+ ### 3. Server Hook (`src/hooks.server.ts`)
28
76
 
29
- ## Develop & test
77
+ ```ts
78
+ import {sequence} from '@sveltejs/kit/hooks'
79
+ import {visualEditor} from '$lib/server/visual-editor'
80
+
81
+ export const handle = sequence(handleSanity, visualEditor.handle)
82
+ ```
83
+
84
+ ### 4. Storefront Layout (`src/routes/+layout.svelte`)
85
+
86
+ ```svelte
87
+ <script lang="ts">
88
+ import {goto, refreshAll} from '$app/navigation'
89
+ import {page} from '$app/state'
90
+ import type {PreviewBarHost} from 'sanity-plugin-visual-editor/host'
91
+
92
+ let host: PreviewBarHost | undefined = $state.raw()
93
+ $effect(() => {
94
+ if (!preview) return
95
+ let cancelled = false
96
+ import('sanity-plugin-visual-editor/host').then(({connectVisualEditor}) => {
97
+ if (cancelled) return
98
+ host = connectVisualEditor({
99
+ enabled: true,
100
+ position: 'top',
101
+ refresh: refreshAll,
102
+ navigate: (href) => goto(href),
103
+ })
104
+ })
105
+ return () => {
106
+ cancelled = true
107
+ host?.destroy()
108
+ host = undefined
109
+ }
110
+ })
111
+ $effect(() => host?.setPath(page.url.pathname + page.url.search))
112
+ </script>
113
+ ```
30
114
 
31
- This plugin uses [@sanity/plugin-kit](https://github.com/sanity-io/plugin-kit)
32
- with default configuration for build & watch scripts.
115
+ ### 5. Click-to-Edit Annotations
116
+
117
+ ```svelte
118
+ <script lang="ts">
119
+ import {sanityAttr} from 'sanity-plugin-visual-editor'
120
+ </script>
121
+
122
+ <h1 {...sanityAttr(pageDoc, 'heading', {enabled: preview})}>
123
+ {pageDoc.heading}
124
+ </h1>
125
+
126
+ <section {...sanityAttr(pageDoc, ['sections', {_key: section._key}, 'title'], {enabled: preview})}>
127
+ ...
128
+ </section>
129
+ ```
130
+
131
+ ### 6. Cloudflare Realtime Preview Hub Worker (`workers/preview-hub/src/index.ts`)
132
+
133
+ ```ts
134
+ export {PreviewHub, default} from 'sanity-plugin-visual-editor/cloudflare'
135
+ ```
136
+
137
+ ## Subpath Exports
138
+
139
+ | Subpath | Purpose |
140
+ | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
141
+ | `sanity-plugin-visual-editor` | Core helpers (`sanityAttr`, `createSanityAttr`, `STUDIO_PREVIEW_PARAM`, protocol & path utilities) |
142
+ | `sanity-plugin-visual-editor/studio` | Sanity Studio plugin (`visualEditor`, `liveEditPlugin`, `defineLocations`, `defineDocuments`) |
143
+ | `sanity-plugin-visual-editor/sveltekit` | SvelteKit factory & hook (`createSvelteKitVisualEditor`, `handleVisualEditor`) |
144
+ | `sanity-plugin-visual-editor/server` | Framework-agnostic server handlers, `createPreviewHubClient`, `kvStore`, `renderPreviewLinkErrorHtml` |
145
+ | `sanity-plugin-visual-editor/host` | Storefront host, click-to-edit overlays, & realtime subscriber (`connectVisualEditor`, `subscribePreviewEvents`) |
146
+ | `sanity-plugin-visual-editor/bar` | React + `@sanity/ui` bar UI (`mountPreviewBar`) |
147
+ | `sanity-plugin-visual-editor/cloudflare` | Cloudflare Durable Object `PreviewHub` + Worker fetch handler |
148
+ | `sanity-plugin-visual-editor/next` & `/next/client` | Next.js App Router adapter |
149
+
150
+ ## Verification
151
+
152
+ After setup or upgrades, follow [TESTING.md](./TESTING.md) (designed for both humans and AI agents) to verify `/p/<code>` links, Visual Editor, click-to-edit overlays, keystroke live edits, Preview Hub stats, and Cloudflare WebSocket `101` upgrades end-to-end.
153
+
154
+ ## License
33
155
 
34
- See [Testing a plugin in Sanity Studio](https://github.com/sanity-io/plugin-kit#testing-a-plugin-in-sanity-studio)
35
- on how to run this plugin with hotreload in the studio.
156
+ MIT
package/TESTING.md ADDED
@@ -0,0 +1,133 @@
1
+ # Agent Verification Playbook (`TESTING.md`)
2
+
3
+ Run this checklist after completing `README.md` setup (or upgrading `sanity-plugin-visual-editor`) on any **SvelteKit × Sanity × Cloudflare** or **Next.js × Sanity × Cloudflare** project.
4
+
5
+ Every check below has concrete pass/fail criteria so an AI agent or developer can verify the full stack in ~2 minutes without leaving dirty edits in Sanity.
6
+
7
+ ---
8
+
9
+ ## 0. Start Local Services
10
+
11
+ Run both the app dev server and the local Cloudflare Preview Hub worker:
12
+
13
+ ```bash
14
+ # Terminal 1: Storefront + embedded Studio (e.g. http://localhost:5173 or http://localhost:3000)
15
+ bun run dev
16
+
17
+ # Terminal 2: Realtime Preview Hub Durable Object (http://localhost:8787)
18
+ cd workers/preview-hub && bun run dev
19
+ ```
20
+
21
+ Set `BASE_URL` to your app's local origin (`http://localhost:5173` for SvelteKit, `http://localhost:3000` for Next.js).
22
+
23
+ > **Note on WebSockets in dev:** `vite dev` and `next dev` do not forward WebSocket `upgrade` requests to app hooks/routes. In dev mode, `subscribePreviewEvents` and `liveEditPlugin` automatically fall back to `GET /api/preview/events` (`polling >= 1`) and `POST /api/preview/live-edit`. To verify real `101` WebSockets (`sockets >= 1`), run Check 7b against `wrangler dev` (`bun run build && bun run preview`).
24
+
25
+ ---
26
+
27
+ ## 1. Expired Short Preview Link (`/p/<code>`)
28
+
29
+ 1. Navigate to `${BASE_URL}/p/nonexistent-e2e-check`.
30
+ 2. **Pass criteria:**
31
+ - HTTP status is **404** (not a framework 500 or generic storefront 404).
32
+ - Response is the styled HTML error screen (custom `renderLinkError` or default `"Preview link expired"` with brand title) and includes `<meta name="robots" content="noindex" />`.
33
+ - Zero console errors.
34
+
35
+ ---
36
+
37
+ ## 2. Studio Visual Editor (`/studio/visual-editor`)
38
+
39
+ 1. Navigate to `${BASE_URL}/studio/visual-editor?preview=/` (sign in to Sanity Studio if prompted).
40
+ 2. **Pass criteria:**
41
+ - Top toolbar renders: Workspace menu, Perspective/Releases menu, Page picker, Search, Viewport toggle, Inspector toggle, Share button, Exit.
42
+ - Center `iframe[title="Preview"]` loads `/` (`200`) and the right-hand Studio Document Pane opens the page's document.
43
+ - Network shows `POST /api/preview/live-edit/session?sanity-preview-secret=...` → **204 No Content**.
44
+ - Zero console errors or 404/500 responses on `/__visual-editor/*` or `/api/preview/*`.
45
+
46
+ ---
47
+
48
+ ## 3. Click-to-Edit Overlays (`sanityAttr`)
49
+
50
+ 1. Inside `/studio/visual-editor?preview=/`, ensure the **Inspector** button is active (`Deactivate inspector` / `[aria-pressed="true"]`).
51
+ 2. Inspect `iframe[title="Preview"]` for `[data-sanity]` attributes.
52
+ 3. Hover an annotated element (e.g. a hero heading) and click it.
53
+ 4. **Pass criteria:**
54
+ - At least one `[data-sanity]` element is present inside the preview iframe (`id=...;type=...;path=...`).
55
+ - Hovering draws the blue overlay bounding box and field label pill.
56
+ - Clicking opens/focuses the matching field in the Studio Document Pane.
57
+
58
+ ---
59
+
60
+ ## 4. Keystroke Live-Edit Round-Trip (Non-Destructive)
61
+
62
+ 1. Wait ~2–3 seconds after `/studio/visual-editor?preview=/` loads so the storefront subscriber connects (`polling >= 1` in dev, or `sockets >= 1` in Workers).
63
+ 2. Pick a visible text field in the focused Document Pane (e.g. a heading). Record its exact original value.
64
+ 3. Append `" E2E"` to the input (**do not publish**).
65
+ 4. **Pass criteria:**
66
+ - `POST /api/preview/live-edit` returns **202 Accepted** (never `401` or `503`).
67
+ - Within ~1 second, the matching element inside `iframe[title="Preview"]` updates live to include `" E2E"`.
68
+ 5. **Cleanup (mandatory):** Immediately revert the input to its exact original value, wait ~2 seconds, and confirm both the input and the storefront iframe match the original text.
69
+
70
+ ---
71
+
72
+ ## 5. Standalone Preview Bar (`/__visual-editor`)
73
+
74
+ 1. With preview mode active, navigate to `${BASE_URL}/`.
75
+ 2. **Pass criteria:**
76
+ - `iframe[title="Sanity preview bar"][src*="/__visual-editor"]` mounts cleanly.
77
+ - `GET /__visual-editor/document?path=%2F` returns **200**.
78
+ - **Search** (signed in) opens the Studio's own search, filtered to your configured document types; picking a result opens its page.
79
+ - **Perspective** menu opens and lists Drafts / Published / Releases.
80
+ - **Share** opens, calls `POST /__visual-editor/share` (**200**), and displays a `/p/<code>` link + QR code. Save that `/p/<code>` URL for Check 6.
81
+
82
+ ---
83
+
84
+ ## 6. Valid Short Preview Link Round-Trip (`/p/<code>`)
85
+
86
+ 1. In the standalone preview bar's menu, click **Exit preview** (`POST /__visual-editor/exit` → **204**).
87
+ 2. Reload `${BASE_URL}/` and confirm `iframe[title="Sanity preview bar"]` is gone (`count === 0`) and `[data-sanity]` count is `0`.
88
+ 3. Navigate to the `/p/<code>` URL minted in Check 5.
89
+ 4. **Pass criteria:**
90
+ - Redirects (`307`) to `/` and sets the preview + perspective cookies (`Set-Cookie` headers).
91
+ - Preview bar re-mounts on `/` with the shared perspective active.
92
+
93
+ ---
94
+
95
+ ## 7. Realtime Preview Hub & WebSocket Check (`/api/preview/hub/stats`)
96
+
97
+ ### 7a. Local Dev (`vite dev` / `next dev`)
98
+
99
+ While `${BASE_URL}/` is open in preview mode, fetch `${BASE_URL}/api/preview/hub/stats` in another tab:
100
+
101
+ - **Pass criteria (`200 OK` JSON):**
102
+ - `mirror: true`
103
+ - `entries > 0` and `local.ok > 0`
104
+ - `polling >= 1` (HTTP long-poll fallback active)
105
+ - `upstream.Listener.error === ""` and `upstream["Live Content API"].error === ""`
106
+
107
+ ### 7b. Cloudflare Worker (`wrangler dev` or Deployed Preview)
108
+
109
+ Build and run the Worker locally (SvelteKit: `bun run build && bun run preview`; Next.js: `opennextjs-cloudflare build && wrangler dev` with custom `worker.ts`), open a `/p/<code>` preview tab, and fetch `/api/preview/hub/stats`:
110
+
111
+ - **Pass criteria:**
112
+ - **`sockets >= 1`** and `polling === 0` (confirms real `101 Switching Protocols` WebSocket upgrade to `PreviewHub`).
113
+
114
+ ---
115
+
116
+ ## 8. Studio Thumbnail & Production Isolation
117
+
118
+ 1. While preview mode is active, navigate to `${BASE_URL}/?studio-preview`.
119
+ - **Pass:** Preview bar does **not** mount; published content is served (no drafts).
120
+ 2. Exit preview mode and inspect `${BASE_URL}/`.
121
+ - **Pass:** `0` `[data-sanity]` attributes in the DOM; `/__visual-editor` and `/api/preview/hub/stats` reject non-preview requests (`403` / `404`).
122
+
123
+ ---
124
+
125
+ ## Common Failure Signatures
126
+
127
+ | Symptom | Likely Cause |
128
+ | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
129
+ | `POST /api/preview/live-edit/session` returns `204`, followed by `401 POST /api/preview/live-edit` | Server handler used `event.cookies.set(...)` on a direct `new Response(...)` instead of appending `Set-Cookie` headers directly on the `Response`. |
130
+ | `HTTP 503 Worker "...-preview-hub" not found` | Local `workers/preview-hub` (`wrangler dev`) is not running, or `PREVIEW_HUB` service binding name in `wrangler.jsonc` does not match. |
131
+ | `polling: 0` and `sockets: 0` in `vite dev` / `next dev` | Preview hub subscriber did not mount (`connectVisualEditor`), or WebSocket open-timeout is missing. |
132
+ | `sockets: 0` on Cloudflare Worker (`wrangler dev` / prod) | In SvelteKit: `visualEditor.handle` must run **before** other hooks that wrap responses. In Next.js: WebSocket upgrades must be intercepted in the OpenNext custom `worker.ts` before `openNextHandler.fetch()`. |
133
+ | `0` `[data-sanity]` elements in Check 3 | Storefront components have not wired `{...sanityAttr(doc, path, { enabled: preview })}` yet, or `enabled` is `false`. |