payload-canvas 0.1.1 → 0.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 (124) hide show
  1. package/README.md +187 -26
  2. package/dist/admin/editor/Canvas.js +30 -8
  3. package/dist/admin/editor/Editor.js +2 -0
  4. package/dist/admin/editor/Inspector.js +14 -7
  5. package/dist/admin/editor/Outline.js +15 -9
  6. package/dist/admin/editor/Overlay.js +2 -1
  7. package/dist/admin/editor/actions.d.ts +5 -0
  8. package/dist/admin/editor/actions.js +23 -1
  9. package/dist/admin/editor/counts.d.ts +6 -0
  10. package/dist/admin/editor/counts.js +10 -0
  11. package/dist/admin/editor/dnd/displace.js +3 -1
  12. package/dist/admin/editor/editor.scss +53 -0
  13. package/dist/admin/editor/inline.d.ts +12 -0
  14. package/dist/admin/editor/inline.js +48 -3
  15. package/dist/admin/editor/insert/spots.js +4 -2
  16. package/dist/admin/editor/live/useMultiplayer.js +8 -2
  17. package/dist/admin/editor/media/ImageEditor.js +21 -15
  18. package/dist/admin/editor/media/actions.d.ts +13 -9
  19. package/dist/admin/editor/media/actions.js +67 -28
  20. package/dist/admin/editor/media/model.d.ts +8 -0
  21. package/dist/admin/editor/media/model.js +14 -6
  22. package/dist/admin/editor/menu/blockMenu.js +13 -8
  23. package/dist/admin/editor/regions/RegionOverlay.d.ts +18 -0
  24. package/dist/admin/editor/regions/RegionOverlay.js +44 -0
  25. package/dist/admin/editor/regions/RegionPane.d.ts +5 -0
  26. package/dist/admin/editor/regions/RegionPane.js +26 -0
  27. package/dist/admin/editor/regions/RegionRows.d.ts +1 -0
  28. package/dist/admin/editor/regions/RegionRows.js +23 -0
  29. package/dist/admin/editor/regions/controller.d.ts +73 -0
  30. package/dist/admin/editor/regions/controller.js +231 -0
  31. package/dist/admin/editor/regions/select.d.ts +17 -0
  32. package/dist/admin/editor/regions/select.js +31 -0
  33. package/dist/admin/editor/runtime.d.ts +6 -0
  34. package/dist/admin/editor/runtime.js +49 -4
  35. package/dist/admin/editor/sections/controller.d.ts +6 -2
  36. package/dist/admin/editor/sections/controller.js +9 -3
  37. package/dist/admin/editor/shortcuts.js +11 -4
  38. package/dist/admin/editor/storage.d.ts +7 -0
  39. package/dist/admin/editor/storage.js +15 -0
  40. package/dist/admin/editor/store.d.ts +39 -0
  41. package/dist/admin/editor/store.js +106 -2
  42. package/dist/admin/editor/templates/Bindable.js +1 -1
  43. package/dist/admin/editor/templates/SamplePicker.js +1 -1
  44. package/dist/admin/editor/topbar/DocumentActions.js +38 -5
  45. package/dist/admin/editor/topbar/closeSave.d.ts +50 -0
  46. package/dist/admin/editor/topbar/closeSave.js +90 -0
  47. package/dist/admin/editor/topbar/document.d.ts +10 -2
  48. package/dist/admin/editor/topbar/document.js +9 -1
  49. package/dist/admin/editor/topbar/drawerLabels.d.ts +22 -0
  50. package/dist/admin/editor/topbar/drawerLabels.js +69 -0
  51. package/dist/admin/editor/topbar/problems.d.ts +9 -0
  52. package/dist/admin/editor/topbar/problems.js +15 -1
  53. package/dist/admin/editor/topbar/settingsDrawer.js +88 -4
  54. package/dist/admin/editor/topbar/settingsFocus.d.ts +11 -0
  55. package/dist/admin/editor/topbar/settingsFocus.js +46 -0
  56. package/dist/admin/editor/ui/payloadA11y.d.ts +17 -0
  57. package/dist/admin/editor/ui/payloadA11y.js +12 -5
  58. package/dist/admin/editor/valueStore.d.ts +2 -0
  59. package/dist/admin/editor/valueStore.js +6 -0
  60. package/dist/core/dropTarget.js +3 -1
  61. package/dist/core/index.d.ts +2 -0
  62. package/dist/core/index.js +2 -0
  63. package/dist/core/payloadBlocks.d.ts +53 -0
  64. package/dist/core/payloadBlocks.js +391 -0
  65. package/dist/core/regions.d.ts +63 -0
  66. package/dist/core/regions.js +239 -0
  67. package/dist/core/types.d.ts +53 -0
  68. package/dist/index.d.ts +1 -0
  69. package/dist/index.js +1 -0
  70. package/dist/live/document.d.ts +9 -1
  71. package/dist/live/document.js +57 -17
  72. package/dist/live/draftAccess.d.ts +36 -0
  73. package/dist/live/draftAccess.js +146 -0
  74. package/dist/live/endpoints.d.ts +11 -2
  75. package/dist/live/endpoints.js +120 -10
  76. package/dist/live/fieldChecks.d.ts +3 -3
  77. package/dist/live/fieldsGuard.d.ts +56 -2
  78. package/dist/live/fieldsGuard.js +107 -11
  79. package/dist/live/index.d.ts +2 -0
  80. package/dist/live/index.js +2 -0
  81. package/dist/live/regions.d.ts +89 -0
  82. package/dist/live/regions.js +401 -0
  83. package/dist/live/runtime.d.ts +1 -1
  84. package/dist/live/runtime.js +5 -2
  85. package/dist/live/session.d.ts +74 -9
  86. package/dist/live/session.js +655 -123
  87. package/dist/live/storage.d.ts +97 -0
  88. package/dist/live/storage.js +269 -0
  89. package/dist/live/types.d.ts +64 -0
  90. package/dist/live/writeGate.d.ts +72 -0
  91. package/dist/live/writeGate.js +478 -0
  92. package/dist/mcp/index.js +56 -12
  93. package/dist/plugin/hook.d.ts +44 -6
  94. package/dist/plugin/hook.js +176 -20
  95. package/dist/plugin/index.d.ts +23 -1
  96. package/dist/plugin/index.js +172 -10
  97. package/dist/plugin/references.d.ts +4 -2
  98. package/dist/plugin/references.js +2 -0
  99. package/dist/plugin/sectionsBuilder.js +3 -3
  100. package/dist/protocol/index.d.ts +28 -2
  101. package/dist/react/canvas/BuilderCanvas.js +198 -8
  102. package/dist/react/canvas/frame.d.ts +70 -0
  103. package/dist/react/canvas/frame.js +66 -0
  104. package/dist/react/canvas/inline/dom.d.ts +7 -1
  105. package/dist/react/canvas/inline/dom.js +19 -9
  106. package/dist/react/canvas/inline/mapper.d.ts +26 -0
  107. package/dist/react/canvas/inline/mapper.js +59 -32
  108. package/dist/react/canvas/inline/session.d.ts +7 -1
  109. package/dist/react/canvas/inline/session.js +6 -2
  110. package/dist/react/canvas/measure.js +26 -1
  111. package/dist/react/index.d.ts +2 -0
  112. package/dist/react/index.js +2 -0
  113. package/dist/react/render/LayoutOutlet.d.ts +11 -0
  114. package/dist/react/render/LayoutOutlet.js +16 -0
  115. package/dist/react/render/canvasFrame.d.ts +46 -0
  116. package/dist/react/render/canvasFrame.js +59 -0
  117. package/dist/react/render/canvasServer.d.ts +13 -0
  118. package/dist/react/render/canvasServer.js +3 -0
  119. package/dist/react/render/canvasServerTypes.d.ts +17 -0
  120. package/dist/react/render/regions.d.ts +13 -0
  121. package/dist/react/render/regions.js +8 -0
  122. package/dist/react/server.d.ts +2 -1
  123. package/dist/react/server.js +1 -0
  124. package/package.json +1 -1
@@ -0,0 +1,146 @@
1
+ // Read access to the live session's state. The session holds the document as editors see it now:
2
+ // its unsaved changes are a draft that is in the database nowhere yet, and it sends that state to
3
+ // every editor (events, operations, MCP). Payload's read access (`access.read`) is true, false or
4
+ // a Where, and a user may read exactly the documents whose stored values match that Where. This
5
+ // asks the same question of the live state: may this user read the document as a draft, now?
6
+ //
7
+ // - `access.read` true: yes. False: no.
8
+ // - A Where: its `_status` conditions are decided for "draft" (every state of the session is one,
9
+ // also before anything is saved). What is left (a tenant, an author, …) runs as Payload's own
10
+ // query (`find` with `draft: true`) on the newest stored version: the session changes only the
11
+ // builder field, every other field is stored. A condition on the builder field itself cannot
12
+ // be decided from stored data (the session's layout is not stored yet), so it counts as false.
13
+ // - A collection without drafts has no draft state: the Where runs as it is, on the document.
14
+ // Nothing is cached: every check runs the access and the query again, so a change of either (a
15
+ // save in the settings drawer, a region, REST, a changed rule) applies to the next check.
16
+ import { executeAccess } from 'payload';
17
+ /** Why the builder refuses a user who may not read the document as a draft. */
18
+ export const DRAFT_NOT_READABLE_MESSAGE = 'You may not read the latest draft of this document, so the builder cannot show it.';
19
+ const STATUS_KEYS = new Set(['_status', 'version._status']);
20
+ /** The values of an `in` / `not_in` condition, as Payload reads them (a list or comma-separated text). */
21
+ const listOf = (value) => (Array.isArray(value) ? value.map(String) : String(value).split(','));
22
+ /** A `_status` condition, decided for a draft. Any other operator counts as false. */
23
+ function statusMatches(condition) {
24
+ if (condition === null || typeof condition !== 'object')
25
+ return false;
26
+ const entries = Object.entries(condition);
27
+ if (entries.length === 0)
28
+ return false;
29
+ return entries.every(([op, value]) => {
30
+ switch (op) {
31
+ case 'equals':
32
+ return String(value) === 'draft';
33
+ case 'not_equals':
34
+ return (typeof value === 'string' || typeof value === 'number') && String(value) !== 'draft';
35
+ case 'in':
36
+ return listOf(value).includes('draft');
37
+ case 'not_in':
38
+ return !listOf(value).includes('draft');
39
+ case 'exists':
40
+ return value === true || value === 'true';
41
+ default:
42
+ return false;
43
+ }
44
+ });
45
+ }
46
+ /** All parts of one level of a Where (its keys are ANDed): false wins, true parts drop out. */
47
+ function allOf(parts) {
48
+ if (parts.includes(false))
49
+ return false;
50
+ const rest = parts.filter((part) => part !== true);
51
+ if (rest.length === 0)
52
+ return true;
53
+ return rest.length === 1 ? rest[0] : { and: rest };
54
+ }
55
+ /**
56
+ * The Where with its `_status` conditions decided for a draft (`drafts`): true (always), false
57
+ * (never), or what is left for Payload's query. A condition on `field` (the builder field) or
58
+ * one this cannot read counts as false. Payload's Where has no negation of a nested Where, so a
59
+ * part that counts as false only ever refuses more, never less.
60
+ */
61
+ export function decideForDraft(where, field, drafts) {
62
+ if (where === null || typeof where !== 'object' || Array.isArray(where))
63
+ return false;
64
+ const parts = [];
65
+ for (const [key, condition] of Object.entries(where)) {
66
+ const lower = key.toLowerCase();
67
+ if (lower === 'and' || lower === 'or') {
68
+ if (!Array.isArray(condition))
69
+ return false;
70
+ // An empty list: Payload's query decides what it means.
71
+ if (condition.length === 0) {
72
+ parts.push({ [lower]: [] });
73
+ continue;
74
+ }
75
+ const items = condition.map((w) => decideForDraft(w, field, drafts));
76
+ if (lower === 'and') {
77
+ parts.push(allOf(items));
78
+ continue;
79
+ }
80
+ if (items.includes(true)) {
81
+ parts.push(true);
82
+ continue;
83
+ }
84
+ const rest = items.filter((item) => item !== false);
85
+ parts.push(rest.length === 0 ? false : rest.length === 1 ? rest[0] : { or: rest });
86
+ continue;
87
+ }
88
+ const path = key.startsWith('version.') ? key.slice('version.'.length) : key;
89
+ if (drafts && STATUS_KEYS.has(key)) {
90
+ parts.push(statusMatches(condition));
91
+ continue;
92
+ }
93
+ if (path === field || path.startsWith(`${field}.`))
94
+ return false;
95
+ parts.push({ [key]: condition });
96
+ }
97
+ return allOf(parts);
98
+ }
99
+ /**
100
+ * Null when the request's user may read the document as the live session holds it (a draft, for
101
+ * collections with drafts), else why the builder refuses. Payload's own access and query decide.
102
+ * Throws when the access or the query fails: callers refuse then.
103
+ */
104
+ export async function liveReadProblem(req, target) {
105
+ const config = req.payload.collections[target.collection]?.config;
106
+ if (!config)
107
+ return DRAFT_NOT_READABLE_MESSAGE;
108
+ // Without `access.read` (never after Payload's sanitizing), executeAccess allows signed-in users.
109
+ const result = await executeAccess({ id: target.id, collectionConfig: config, disableErrors: true, req }, config.access?.read);
110
+ if (!result)
111
+ return DRAFT_NOT_READABLE_MESSAGE;
112
+ // As in Payload: anything but a Where that is not false allows.
113
+ if (typeof result !== 'object')
114
+ return null;
115
+ const decided = decideForDraft(result, target.field, target.drafts);
116
+ if (decided === true)
117
+ return null;
118
+ if (decided === false)
119
+ return DRAFT_NOT_READABLE_MESSAGE;
120
+ // What is left: Payload's own query on the newest stored version (or the document, without drafts).
121
+ const found = await req.payload.find({
122
+ collection: target.collection,
123
+ where: { and: [{ id: { equals: target.id } }, decided] },
124
+ draft: target.drafts,
125
+ depth: 0,
126
+ limit: 1,
127
+ pagination: false,
128
+ select: { id: true },
129
+ overrideAccess: true,
130
+ req,
131
+ });
132
+ return found.docs.length > 0 ? null : DRAFT_NOT_READABLE_MESSAGE;
133
+ }
134
+ /**
135
+ * A commit's access check that first asks `liveReadProblem` again, inside the commit (its lock,
136
+ * on the document as stored when the check ends), because the result goes back to the user. A
137
+ * failing check refuses.
138
+ */
139
+ export function withLiveReadCheck(req, target, access) {
140
+ return async (args) => {
141
+ const problem = await liveReadProblem(req, target).catch(() => DRAFT_NOT_READABLE_MESSAGE);
142
+ if (problem)
143
+ return problem;
144
+ return access ? access(args) : null;
145
+ };
146
+ }
@@ -1,5 +1,6 @@
1
1
  import { type Endpoint, type PayloadRequest } from 'payload';
2
2
  import { type FieldRegistry } from '../core/fieldSemantics.js';
3
+ import type { PayloadBlocksStorage } from '../core/payloadBlocks.js';
3
4
  import type { BlockDefinition, LocaleSettings } from '../core/types.js';
4
5
  import type { LiveRuntime } from './runtime.js';
5
6
  import { type SessionTarget } from './session.js';
@@ -8,10 +9,11 @@ import type { LiveActor, MultiplayerEvent } from './types.js';
8
9
  export declare const LIVE_PATH = "/builder/live";
9
10
  export declare const SSE_HEADERS: Record<string, string>;
10
11
  export type LiveEndpointOptions = {
11
- /** Builder collections, their layout field names and their locales. */
12
+ /** Builder collections, their layout field names, their locales and how they store the layout. */
12
13
  collections: Record<string, {
13
14
  field: string;
14
15
  localization?: LocaleSettings | null;
16
+ payloadBlocks?: PayloadBlocksStorage;
15
17
  }>;
16
18
  blocks: BlockDefinition[];
17
19
  runtime: LiveRuntime;
@@ -20,9 +22,16 @@ export type LiveEndpointOptions = {
20
22
  /** The `validate`, `hooks` and `access` of block props. Default: none. */
21
23
  fieldRegistry?: FieldRegistry;
22
24
  };
23
- /** The session target of a builder document, or null when the collection is not a builder collection. */
25
+ /**
26
+ * The session target of a builder document, or null when the collection is not a builder
27
+ * collection. The route gives the id as text; Payload's `parseDocumentID` turns it into a number
28
+ * for collections with number ids (the Postgres default), so Local API calls, the lock rows and
29
+ * the publish check get the id type the database uses. Collections with text ids keep the text.
30
+ * Without `payload.db` (0.1.x callers passed only `{ collections }`), the id stays as given.
31
+ */
24
32
  export declare function sessionTargetOf(payload: {
25
33
  collections: unknown;
34
+ db?: unknown;
26
35
  }, collections: LiveEndpointOptions['collections'], collection: string, id: string): SessionTarget | null;
27
36
  /** The document of a live endpoint request (`:collection/:id`), or a 404 response. */
28
37
  export declare function targetOf(req: PayloadRequest, collections: LiveEndpointOptions['collections']): SessionTarget | Response;
@@ -9,9 +9,10 @@
9
9
  // Payload passes the handler's Response body through unbuffered, so the stream works inside
10
10
  // Next's route handler. `no-transform` stops compression, `X-Accel-Buffering: no` stops nginx
11
11
  // from buffering.
12
- import { addDataAndFileToRequest } from 'payload';
12
+ import { addDataAndFileToRequest, parseDocumentID } from 'payload';
13
13
  import { EMPTY_FIELD_REGISTRY } from '../core/fieldSemantics.js';
14
- import { normalizeLayout } from '../core/tree.js';
14
+ import { DRAFT_NOT_READABLE_MESSAGE, liveReadProblem, withLiveReadCheck } from './draftAccess.js';
15
+ import { blocksAccessProblem, codecOf, statesThrough, UNREADABLE_BLOCKS_MESSAGE, withBlocksReadCheck } from './storage.js';
15
16
  import { actorFromUser } from './apply.js';
16
17
  import { blockFromBody, propAccessCheck, validateBlockProps } from './fieldChecks.js';
17
18
  import { collaboratorName } from './session.js';
@@ -35,19 +36,26 @@ function statusOf(error) {
35
36
  const status = error?.status;
36
37
  return typeof status === 'number' ? status : 500;
37
38
  }
38
- /** The session target of a builder document, or null when the collection is not a builder collection. */
39
+ /**
40
+ * The session target of a builder document, or null when the collection is not a builder
41
+ * collection. The route gives the id as text; Payload's `parseDocumentID` turns it into a number
42
+ * for collections with number ids (the Postgres default), so Local API calls, the lock rows and
43
+ * the publish check get the id type the database uses. Collections with text ids keep the text.
44
+ * Without `payload.db` (0.1.x callers passed only `{ collections }`), the id stays as given.
45
+ */
39
46
  export function sessionTargetOf(payload, collections, collection, id) {
40
47
  const options = collections[collection];
41
48
  if (!options || !id)
42
49
  return null;
43
- const configs = payload.collections;
44
- const drafts = configs[collection]?.config.versions?.drafts;
50
+ const config = payload.collections[collection]?.config;
51
+ const drafts = config?.versions?.drafts;
45
52
  return {
46
53
  collection,
47
- id,
54
+ id: payload.db ? (parseDocumentID({ collectionSlug: collection, id, payload: payload }) ?? id) : id,
48
55
  field: options.field,
49
56
  drafts: Boolean(drafts),
50
57
  autosave: typeof drafts === 'object' && Boolean(drafts.autosave),
58
+ codec: codecOf(options),
51
59
  };
52
60
  }
53
61
  /** The document of a live endpoint request (`:collection/:id`), or a 404 response. */
@@ -91,6 +99,76 @@ function resumePoint(req, url) {
91
99
  return { seq, ...(sessionId ? { sessionId } : {}) };
92
100
  }
93
101
  export function liveEndpoints(options) {
102
+ /**
103
+ * The event stream. Each event (of every kind, for every storage) is checked, one after the
104
+ * other, when its turn comes and before it goes out:
105
+ * - the user may read the document as the session holds it (a draft): Payload's read access and
106
+ * query, run again for each event (draftAccess.ts), so a change of access or of the stored
107
+ * document (a save in the drawer, a region, REST) applies to the events still waiting too;
108
+ * - a Payload blocks field: every value the event shows, in place (each block with its real
109
+ * parents and siblings, as Payload's read access sees it). A `session` event its layout; a
110
+ * `commit` each state after each of its operations, applied to the state the previous event
111
+ * left (the stream's own copy, taken when each event was sent). So a value one operation
112
+ * writes and a later one removes counts, and so does a value a sibling value hides.
113
+ * Both run on the document's other fields as stored when the check ends (`withCurrentDoc`: a
114
+ * save that commits during the check runs it again). The first refusal ends the stream with an
115
+ * `error` event, before that event or any later one goes out; a check that fails closes it.
116
+ * Reconnects of a Payload blocks field never replay old commits (session.ts).
117
+ */
118
+ const readCheckedSend = (req, target, send, close) => {
119
+ const blocksField = target.codec?.kind === 'payload-blocks';
120
+ let queue = Promise.resolve();
121
+ let ended = false;
122
+ /** The layout as the events sent so far left it (taken when each event was sent). */
123
+ let shown = null;
124
+ const end = (problem) => {
125
+ ended = true;
126
+ send({ type: 'error', error: problem });
127
+ close();
128
+ };
129
+ return (event, id) => {
130
+ // The states this event shows, from the events before it: taken now, in send order.
131
+ let layouts = [];
132
+ if (blocksField && event.type === 'session') {
133
+ shown = event.layout;
134
+ layouts = [shown];
135
+ }
136
+ else if (blocksField && event.type === 'commit') {
137
+ layouts = shown ? statesThrough(shown, event.ops) : null;
138
+ if (layouts && layouts.length > 0)
139
+ shown = layouts[layouts.length - 1];
140
+ }
141
+ queue = queue
142
+ .then(async () => {
143
+ if (ended)
144
+ return;
145
+ // Operations that do not apply to the stream's copy: the stream cannot tell what they show.
146
+ const states = layouts;
147
+ let problem = UNREADABLE_BLOCKS_MESSAGE;
148
+ if (states) {
149
+ const checked = await options.runtime.sessions.withCurrentDoc(target.collection, target.id, async (doc) => {
150
+ const unreadable = await liveReadProblem(req, target);
151
+ if (unreadable || states.length === 0)
152
+ return unreadable;
153
+ return blocksAccessProblem(req, target, { write: false, stored: false, layouts: states, doc });
154
+ });
155
+ // No open session: nothing to check against, so nothing goes out.
156
+ problem = checked ? checked.value : DRAFT_NOT_READABLE_MESSAGE;
157
+ }
158
+ if (ended)
159
+ return;
160
+ if (problem) {
161
+ end(problem);
162
+ return;
163
+ }
164
+ send(event, id);
165
+ })
166
+ .catch(() => {
167
+ ended = true;
168
+ close();
169
+ });
170
+ };
171
+ };
94
172
  const { collections, blocks, runtime } = options;
95
173
  const registry = options.fieldRegistry ?? EMPTY_FIELD_REGISTRY;
96
174
  const heartbeatMs = options.heartbeatMs ?? HEARTBEAT_MS;
@@ -110,6 +188,15 @@ export function liveEndpoints(options) {
110
188
  if (!(await runtime.canUpdate(req, target.collection, target.id))) {
111
189
  return { ok: false, status: 403, error: 'You are not allowed to edit this document', seq: runtime.sessions.peek(target.collection, target.id)?.seq ?? 0 };
112
190
  }
191
+ // The session holds the document as a draft: only users who may read it so change it (the result goes back to them).
192
+ const stale = await liveReadProblem(req, target).catch(() => DRAFT_NOT_READABLE_MESSAGE);
193
+ if (stale)
194
+ return { ok: false, status: 403, error: stale, seq: 0 };
195
+ // A Payload blocks field: only users who may read all of it and update it use the session.
196
+ const live = () => runtime.sessions.peek(target.collection, target.id);
197
+ const denied = await blocksAccessProblem(req, target, { write: true, layouts: [live()?.layout] });
198
+ if (denied)
199
+ return { ok: false, status: 403, error: denied, seq: 0 };
113
200
  const localization = collections[target.collection]?.localization ?? null;
114
201
  return runtime.sessions.commit({
115
202
  target,
@@ -118,8 +205,10 @@ export function liveEndpoints(options) {
118
205
  actor: requestActor(req.user),
119
206
  blocks,
120
207
  localization,
121
- // Field access of block props: a change to a prop the user may not update is refused.
122
- access: propAccessCheck(req, { blocks, registry, collection: target.collection, id: target.id, field: target.field, localization }),
208
+ // Inside the commit, on the document as stored then: the user may still read the draft;
209
+ // field access of block props (a change to a prop the user may not update is refused);
210
+ // a Payload blocks field: and no value the user may not read, in any state of the batch.
211
+ access: withLiveReadCheck(req, target, withBlocksReadCheck(req, target, propAccessCheck(req, { blocks, registry, collection: target.collection, id: target.id, field: target.field, localization }))),
123
212
  ...input,
124
213
  });
125
214
  };
@@ -147,6 +236,14 @@ export function liveEndpoints(options) {
147
236
  catch (error) {
148
237
  return json({ ok: false, error: 'Document not found or not readable' }, statusOf(error) === 403 ? 403 : 404);
149
238
  }
239
+ // A Payload blocks field: only users who may read all of it (the session holds every value).
240
+ // The session holds the document as a draft: a user who may read only other versions gets nothing.
241
+ const stale = await liveReadProblem(req, target).catch(() => DRAFT_NOT_READABLE_MESSAGE);
242
+ if (stale)
243
+ return json({ ok: false, error: stale }, 403);
244
+ const unreadable = await blocksAccessProblem(req, target, { write: false, layouts: [runtime.sessions.peek(target.collection, target.id)?.layout] });
245
+ if (unreadable)
246
+ return json({ ok: false, error: unreadable }, 403);
150
247
  const url = new URL(req.url ?? '', 'http://localhost');
151
248
  const requested = url.searchParams.get('clientId') ?? '';
152
249
  const clientId = CLIENT_ID.test(requested) ? requested : globalThis.crypto.randomUUID();
@@ -159,7 +256,7 @@ export function liveEndpoints(options) {
159
256
  clientId,
160
257
  user: req.user,
161
258
  after: resumePoint(req, url),
162
- send,
259
+ send: readCheckedSend(req, target, send, close),
163
260
  close,
164
261
  }),
165
262
  });
@@ -247,6 +344,13 @@ export function liveEndpoints(options) {
247
344
  if (!(await runtime.canUpdate(req, target.collection, target.id))) {
248
345
  return json({ ok: false, error: 'You are not allowed to edit this document' }, 403);
249
346
  }
347
+ // The session holds the document as a draft: only users who may read it so save it.
348
+ const stale = await liveReadProblem(req, target).catch(() => DRAFT_NOT_READABLE_MESSAGE);
349
+ if (stale)
350
+ return json({ ok: false, error: stale }, 403);
351
+ const denied = await blocksAccessProblem(req, target, { write: true, layouts: [runtime.sessions.peek(target.collection, target.id)?.layout] });
352
+ if (denied)
353
+ return json({ ok: false, error: denied }, 403);
250
354
  const result = await runtime.sessions.flush(target.collection, target.id);
251
355
  return json(result, result.ok ? 200 : 503);
252
356
  },
@@ -308,7 +412,13 @@ export function liveEndpoints(options) {
308
412
  catch (error) {
309
413
  return json({ ok: false, error: 'Document not found or not readable' }, statusOf(error) === 403 ? 403 : 404);
310
414
  }
311
- const layout = runtime.sessions.peek(target.collection, target.id)?.layout ?? normalizeLayout(doc[target.field]);
415
+ const stale = await liveReadProblem(req, target).catch(() => DRAFT_NOT_READABLE_MESSAGE);
416
+ if (stale)
417
+ return json({ ok: false, error: stale }, 403);
418
+ const hidden = await blocksAccessProblem(req, target, { write: false, layouts: [runtime.sessions.peek(target.collection, target.id)?.layout] });
419
+ if (hidden)
420
+ return json({ ok: false, error: hidden }, 403);
421
+ const layout = runtime.sessions.peek(target.collection, target.id)?.layout ?? (target.codec ?? codecOf(undefined)).decode(doc[target.field]);
312
422
  try {
313
423
  const problems = await validateBlockProps(req, {
314
424
  blocks,
@@ -20,7 +20,7 @@ export declare function propAccessCheck(req: PayloadRequest, options: {
20
20
  blocks: readonly BlockDefinition[];
21
21
  registry: FieldRegistry;
22
22
  collection: string;
23
- id: string;
23
+ id: string | number;
24
24
  field: string;
25
25
  /** The document's locales: a translation is a change of its prop too. */
26
26
  localization?: LocaleSettings | null;
@@ -34,7 +34,7 @@ export declare function validateBlockProps(req: PayloadRequest, options: {
34
34
  blocks: readonly BlockDefinition[];
35
35
  registry: FieldRegistry;
36
36
  collection: string;
37
- id: string;
37
+ id: string | number;
38
38
  field: string;
39
39
  block: Block;
40
40
  /** The document (as read by the user), and the layout people see now. */
@@ -53,7 +53,7 @@ export declare function propAccessFor(req: PayloadRequest, options: {
53
53
  blocks: readonly BlockDefinition[];
54
54
  registry: FieldRegistry;
55
55
  collection: string;
56
- id: string;
56
+ id: string | number;
57
57
  field: string;
58
58
  /** The stored layout people edit (the live session's, else the saved draft's). */
59
59
  layout: Layout;
@@ -5,6 +5,8 @@ export declare const KEEP_LOCK_CONTEXT = "builderKeepLock";
5
5
  export declare const LOCKED_DOCUMENTS_SLUG = "payload-locked-documents";
6
6
  type Context = Record<string, unknown>;
7
7
  type Doc = Record<string, unknown>;
8
+ /** True when two stored or form values are the same value (see `normalize`). */
9
+ export declare function sameValue(a: unknown, b: unknown): boolean;
8
10
  /**
9
11
  * The top-level fields whose value in `data` differs from `current`. Leaves out the fields in
10
12
  * `skip` (the layout and the plugin's own fields), the id, the timestamps and `_status`.
@@ -35,6 +37,42 @@ export type FieldClock = {
35
37
  export declare function createFieldClock(maxDocs?: number): FieldClock;
36
38
  /** The process-wide field clock. Kept on `globalThis`, so a dev hot reload keeps it. */
37
39
  export declare function defaultFieldClock(): FieldClock;
40
+ /**
41
+ * The values one field had, by the document's `updatedAt`. A form sends back every field it
42
+ * loaded, also the ones nobody touched in it. With the value the form loaded, a save can tell
43
+ * "left as loaded" (keep the newer stored value) from "changed in this form".
44
+ */
45
+ export type FieldHistory = {
46
+ remember(collection: string, id: string | number, field: string, at: unknown, value: unknown): void;
47
+ /** The value the field had when the document's `updatedAt` was `at`. Undefined: not known. */
48
+ at(collection: string, id: string | number, field: string, at: string): {
49
+ value: unknown;
50
+ } | undefined;
51
+ };
52
+ /** An in-memory field history: the last `perDoc` values of the last `maxDocs` documents. */
53
+ export declare function createFieldHistory(maxDocs?: number, perDoc?: number): FieldHistory;
54
+ /** The process-wide field history. Kept on `globalThis`, so a dev hot reload keeps it. */
55
+ export declare function defaultFieldHistory(): FieldHistory;
56
+ /**
57
+ * Runs in beforeChange of an update from a form (not the plugin's own save), for a field the
58
+ * builder and Payload's editor both write (a Payload blocks field). A form loaded before the
59
+ * field's last change, the builder's settings drawer for example, sends the field back as it
60
+ * loaded it:
61
+ * - left as loaded: the save keeps the newer stored value (`data[field]` becomes it);
62
+ * - changed in the form, and the field changed since: a conflict, also when the same person made
63
+ * both changes (the save would undo their own newer edit on the canvas);
64
+ * - changed in the form, and the field did not change since: the form's value is saved.
65
+ * Returns the conflicts. Remembers the stored value for later forms.
66
+ */
67
+ export declare function keepNewerField(args: {
68
+ history: FieldHistory;
69
+ clock: FieldClock;
70
+ collection: string;
71
+ id: string | number;
72
+ field: string;
73
+ data: Doc;
74
+ originalDoc: Doc | undefined;
75
+ }): FieldConflict[];
38
76
  /** The message of a rejected stale save. */
39
77
  export declare function staleSaveMessage(conflicts: readonly FieldConflict[], labelOf: (field: string) => string): string;
40
78
  /**
@@ -69,6 +107,8 @@ export type StaleCheckArgs = {
69
107
  * got back from its own last save). A save without it (most API clients) is not checked.
70
108
  */
71
109
  export declare function checkStaleSave(args: StaleCheckArgs): FieldConflict[];
110
+ /** The top-level fields `checkStaleSave` saw change in this save (the layout and the plugin's own fields left out). */
111
+ export declare function changedFieldsOf(context: Context | undefined, collection: string, id: unknown): string[];
72
112
  /** Runs in afterChange: records the fields `checkStaleSave` saw change, with the new `updatedAt`. */
73
113
  export declare function recordFieldChanges(args: {
74
114
  clock: FieldClock;
@@ -118,12 +158,26 @@ export declare function restoreLocks(args: {
118
158
  context: Context | undefined;
119
159
  }): Promise<number>;
120
160
  /** Who has the builder's settings drawer open, per document. In memory, like the sessions. */
161
+ /**
162
+ * Who has the settings drawer of a document open. An entry lasts `ttlMs` after it was added or
163
+ * renewed (the drawer takes the lock when it opens and again while it stays open; the user's own
164
+ * saves renew it too), so a drawer whose close never reached the server stops counting after a
165
+ * while instead of until the server restarts.
166
+ */
121
167
  export type SettingsLocks = {
122
- add(collection: string, id: string | number, user: string | number): void;
168
+ /** Adds or renews the user's entry for `ttlMs` (default: the store's time, Payload's lock duration). */
169
+ add(collection: string, id: string | number, user: string | number, ttlMs?: number): void;
123
170
  remove(collection: string, id: string | number, user: string | number): void;
124
171
  has(collection: string, id: string | number, user: string | number): boolean;
172
+ /** Renews the user's entry when it is there. */
173
+ renew(collection: string, id: string | number, user: string | number, ttlMs?: number): void;
125
174
  };
126
- export declare function createSettingsLocks(): SettingsLocks;
175
+ /** How long a settings drawer entry lasts without renewal: Payload's default lock duration. */
176
+ export declare const SETTINGS_HOLD_MS = 300000;
177
+ export declare function createSettingsLocks(options?: {
178
+ ttlMs?: number;
179
+ now?: () => number;
180
+ }): SettingsLocks;
127
181
  /** The process-wide settings drawer holders. Kept on `globalThis`, so a dev hot reload keeps them. */
128
182
  export declare function defaultSettingsLocks(): SettingsLocks;
129
183
  /** The lock helpers that delete rows. Tests pass a fake. */
@@ -64,7 +64,8 @@ function normalize(value) {
64
64
  }
65
65
  return String(value);
66
66
  }
67
- function sameValue(a, b) {
67
+ /** True when two stored or form values are the same value (see `normalize`). */
68
+ export function sameValue(a, b) {
68
69
  return JSON.stringify(normalize(a)) === JSON.stringify(normalize(b));
69
70
  }
70
71
  /**
@@ -118,6 +119,73 @@ export function defaultFieldClock() {
118
119
  store[CLOCK_KEY] ??= createFieldClock();
119
120
  return store[CLOCK_KEY];
120
121
  }
122
+ const historyKey = (collection, id, field) => `${docKey(collection, id)}:${field}`;
123
+ /** An in-memory field history: the last `perDoc` values of the last `maxDocs` documents. */
124
+ export function createFieldHistory(maxDocs = 1000, perDoc = 20) {
125
+ const docs = new Map();
126
+ return {
127
+ remember(collection, id, field, at, value) {
128
+ const time = typeof at === 'string' ? Date.parse(at) : Number.NaN;
129
+ if (!Number.isFinite(time))
130
+ return;
131
+ const key = historyKey(collection, id, field);
132
+ const entry = docs.get(key) ?? new Map();
133
+ docs.delete(key);
134
+ entry.set(time, structuredClone(value));
135
+ while (entry.size > perDoc)
136
+ entry.delete(entry.keys().next().value);
137
+ docs.set(key, entry);
138
+ if (docs.size > maxDocs)
139
+ docs.delete(docs.keys().next().value);
140
+ },
141
+ at(collection, id, field, at) {
142
+ const entry = docs.get(historyKey(collection, id, field));
143
+ const time = Date.parse(at);
144
+ if (!entry || !entry.has(time))
145
+ return undefined;
146
+ return { value: entry.get(time) };
147
+ },
148
+ };
149
+ }
150
+ const HISTORY_KEY = Symbol.for('payload-canvas/field-history');
151
+ /** The process-wide field history. Kept on `globalThis`, so a dev hot reload keeps it. */
152
+ export function defaultFieldHistory() {
153
+ const store = globalThis;
154
+ store[HISTORY_KEY] ??= createFieldHistory();
155
+ return store[HISTORY_KEY];
156
+ }
157
+ /**
158
+ * Runs in beforeChange of an update from a form (not the plugin's own save), for a field the
159
+ * builder and Payload's editor both write (a Payload blocks field). A form loaded before the
160
+ * field's last change, the builder's settings drawer for example, sends the field back as it
161
+ * loaded it:
162
+ * - left as loaded: the save keeps the newer stored value (`data[field]` becomes it);
163
+ * - changed in the form, and the field changed since: a conflict, also when the same person made
164
+ * both changes (the save would undo their own newer edit on the canvas);
165
+ * - changed in the form, and the field did not change since: the form's value is saved.
166
+ * Returns the conflicts. Remembers the stored value for later forms.
167
+ */
168
+ export function keepNewerField(args) {
169
+ const { history, clock, collection, id, field, data, originalDoc } = args;
170
+ if (!originalDoc)
171
+ return [];
172
+ const current = originalDoc[field];
173
+ history.remember(collection, id, field, originalDoc.updatedAt, current);
174
+ const base = data.updatedAt;
175
+ if (!(field in data) || typeof base !== 'string' || base === originalDoc.updatedAt)
176
+ return [];
177
+ if (sameValue(data[field], current))
178
+ return [];
179
+ const loaded = history.at(collection, id, field, base);
180
+ if (loaded && sameValue(data[field], loaded.value)) {
181
+ data[field] = current;
182
+ return [];
183
+ }
184
+ if (loaded && sameValue(loaded.value, current))
185
+ return [];
186
+ // Changed in the form: a conflict when anyone (this person too) changed the field since.
187
+ return clock.conflicts(collection, id, [field], { base, by: 'payload-canvas:anyone' });
188
+ }
121
189
  // ---------------------------------------------------------------------------
122
190
  // Stale-save check (beforeChange) and record (afterChange)
123
191
  // ---------------------------------------------------------------------------
@@ -164,6 +232,11 @@ export function checkStaleSave(args) {
164
232
  }
165
233
  return [];
166
234
  }
235
+ /** The top-level fields `checkStaleSave` saw change in this save (the layout and the plugin's own fields left out). */
236
+ export function changedFieldsOf(context, collection, id) {
237
+ const pending = context?.[CHANGED_FIELDS_CONTEXT];
238
+ return pending?.[docKey(collection, id)] ?? [];
239
+ }
167
240
  /** Runs in afterChange: records the fields `checkStaleSave` saw change, with the new `updatedAt`. */
168
241
  export function recordFieldChanges(args) {
169
242
  const { clock, collection, doc, user, context } = args;
@@ -233,24 +306,46 @@ export async function restoreLocks(args) {
233
306
  }
234
307
  return rows.length;
235
308
  }
236
- export function createSettingsLocks() {
309
+ /** How long a settings drawer entry lasts without renewal: Payload's default lock duration. */
310
+ export const SETTINGS_HOLD_MS = 300_000;
311
+ export function createSettingsLocks(options = {}) {
312
+ const ttl = options.ttlMs ?? SETTINGS_HOLD_MS;
313
+ const now = options.now ?? Date.now;
314
+ /** Per document: user -> the time the entry ends. */
237
315
  const holders = new Map();
316
+ const live = (key) => {
317
+ const users = holders.get(key);
318
+ if (!users)
319
+ return undefined;
320
+ const at = now();
321
+ for (const [user, until] of users)
322
+ if (until <= at)
323
+ users.delete(user);
324
+ if (users.size === 0)
325
+ holders.delete(key);
326
+ return users.size === 0 ? undefined : users;
327
+ };
238
328
  return {
239
- add(collection, id, user) {
329
+ add(collection, id, user, ttlMs = ttl) {
240
330
  const key = docKey(collection, id);
241
- const set = holders.get(key) ?? new Set();
242
- set.add(String(user));
243
- holders.set(key, set);
331
+ const users = live(key) ?? new Map();
332
+ users.set(String(user), now() + ttlMs);
333
+ holders.set(key, users);
244
334
  },
245
335
  remove(collection, id, user) {
246
336
  const key = docKey(collection, id);
247
- const set = holders.get(key);
248
- set?.delete(String(user));
249
- if (set?.size === 0)
337
+ const users = holders.get(key);
338
+ users?.delete(String(user));
339
+ if (users?.size === 0)
250
340
  holders.delete(key);
251
341
  },
252
342
  has(collection, id, user) {
253
- return holders.get(docKey(collection, id))?.has(String(user)) ?? false;
343
+ return live(docKey(collection, id))?.has(String(user)) ?? false;
344
+ },
345
+ renew(collection, id, user, ttlMs = ttl) {
346
+ const users = live(docKey(collection, id));
347
+ if (users?.has(String(user)))
348
+ users.set(String(user), now() + ttlMs);
254
349
  },
255
350
  };
256
351
  }
@@ -286,7 +381,8 @@ export async function takeSettingsLock(args) {
286
381
  const active = rows.filter((row) => lockIsActive(row, duration, now));
287
382
  // Listed also when someone else holds the lock: after "Take over" in Payload's dialog the lock
288
383
  // is the user's, and their saves must keep it. Only the user's own rows are ever kept.
289
- holders.add(collection, id, user.id);
384
+ // As long as Payload's own lock: the drawer takes it again while it stays open.
385
+ holders.add(collection, id, user.id, duration);
290
386
  if (active.some((row) => lockOwner(row) !== String(user.id)))
291
387
  return 'other';
292
388
  if (active.length > 0)