payload-live-preview 1.8.0 → 2.0.0-beta.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 (98) hide show
  1. package/README.md +301 -93
  2. package/dist/adapters/astro/PreviewBoundary.astro +66 -0
  3. package/dist/adapters/astro/RichText.astro +6 -0
  4. package/dist/adapters/astro/index.d.ts +165 -134
  5. package/dist/adapters/astro/index.js +1 -1
  6. package/dist/adapters/astro/index.js.map +1 -1
  7. package/dist/adapters/astro/middleware-entry.d.ts +4 -9
  8. package/dist/adapters/astro/middleware-entry.js +1 -1
  9. package/dist/adapters/astro/middleware-entry.js.map +1 -1
  10. package/dist/adapters/nextjs/index.d.ts +13 -80
  11. package/dist/adapters/nextjs/index.js +1 -1
  12. package/dist/adapters/nextjs/index.js.map +1 -1
  13. package/dist/adapters/nuxt/index.d.ts +46 -106
  14. package/dist/adapters/nuxt/index.js +1 -1
  15. package/dist/adapters/nuxt/index.js.map +1 -1
  16. package/dist/adapters/sveltekit/index.d.ts +10 -75
  17. package/dist/adapters/sveltekit/index.js +1 -1
  18. package/dist/adapters/sveltekit/index.js.map +1 -1
  19. package/dist/client.cjs +2 -0
  20. package/dist/client.cjs.map +1 -0
  21. package/dist/client.d.cts +747 -0
  22. package/dist/client.d.ts +747 -0
  23. package/dist/client.js +2 -0
  24. package/dist/client.js.map +1 -0
  25. package/dist/codegen-astro.d.ts +5 -27
  26. package/dist/codegen-astro.js +1 -1
  27. package/dist/codegen-astro.js.map +1 -1
  28. package/dist/codegen-cli.d.ts +3 -16
  29. package/dist/codegen-cli.js +1 -1
  30. package/dist/codegen-cli.js.map +1 -1
  31. package/dist/codegen.cjs +1 -1
  32. package/dist/codegen.cjs.map +1 -1
  33. package/dist/codegen.d.cts +37 -124
  34. package/dist/codegen.d.ts +37 -124
  35. package/dist/codegen.js +1 -1
  36. package/dist/codegen.js.map +1 -1
  37. package/dist/core.cjs +1 -1
  38. package/dist/core.cjs.map +1 -1
  39. package/dist/core.d.cts +647 -1100
  40. package/dist/core.d.ts +647 -1100
  41. package/dist/core.js +1 -1
  42. package/dist/core.js.map +1 -1
  43. package/dist/doctor-cli.d.ts +3 -28
  44. package/dist/doctor-cli.js +1 -1
  45. package/dist/doctor-cli.js.map +1 -1
  46. package/dist/doctor.d.ts +16 -32
  47. package/dist/doctor.js +1 -1
  48. package/dist/doctor.js.map +1 -1
  49. package/dist/fragment.cjs +2 -0
  50. package/dist/fragment.cjs.map +1 -0
  51. package/dist/fragment.d.cts +333 -0
  52. package/dist/fragment.d.ts +333 -0
  53. package/dist/fragment.js +2 -0
  54. package/dist/fragment.js.map +1 -0
  55. package/dist/index.cjs +1 -1
  56. package/dist/index.cjs.map +1 -1
  57. package/dist/index.d.cts +885 -1531
  58. package/dist/index.d.ts +885 -1531
  59. package/dist/index.js +1 -1
  60. package/dist/index.js.map +1 -1
  61. package/dist/lexical.cjs +2 -0
  62. package/dist/lexical.cjs.map +1 -0
  63. package/dist/lexical.d.cts +90 -0
  64. package/dist/lexical.d.ts +90 -0
  65. package/dist/lexical.js +2 -0
  66. package/dist/lexical.js.map +1 -0
  67. package/dist/middleware-CEPsY1P7.d.ts +40 -0
  68. package/dist/migrate.d.ts +73 -0
  69. package/dist/migrate.js +2 -0
  70. package/dist/migrate.js.map +1 -0
  71. package/dist/options-CEzzfHJu.d.ts +197 -0
  72. package/dist/payload.cjs +1 -1
  73. package/dist/payload.cjs.map +1 -1
  74. package/dist/payload.d.cts +11 -80
  75. package/dist/payload.d.ts +11 -80
  76. package/dist/payload.js +1 -1
  77. package/dist/payload.js.map +1 -1
  78. package/dist/plugins.cjs +2 -0
  79. package/dist/plugins.cjs.map +1 -0
  80. package/dist/plugins.d.cts +509 -0
  81. package/dist/plugins.d.ts +509 -0
  82. package/dist/plugins.js +2 -0
  83. package/dist/plugins.js.map +1 -0
  84. package/dist/{probe-tMHdim5y.d.ts → probe-CYtvj_Lm.d.ts} +43 -77
  85. package/dist/server.cjs +2 -0
  86. package/dist/server.cjs.map +1 -0
  87. package/dist/server.d.cts +435 -0
  88. package/dist/server.d.ts +435 -0
  89. package/dist/server.js +2 -0
  90. package/dist/server.js.map +1 -0
  91. package/dist/structural.cjs +3 -0
  92. package/dist/structural.cjs.map +1 -0
  93. package/dist/structural.d.cts +243 -0
  94. package/dist/structural.d.ts +243 -0
  95. package/dist/structural.js +3 -0
  96. package/dist/structural.js.map +1 -0
  97. package/package.json +86 -7
  98. package/dist/middleware-DD4Hwomt.d.ts +0 -189
@@ -0,0 +1,747 @@
1
+ /** Connection status and the heartbeat that decides a disconnect. */
2
+ type ConnectionStatus = 'disconnected' | 'connecting' | 'connected';
3
+
4
+ /**
5
+ * Shape of the `inspect()` snapshot. It only re-reads what the page already
6
+ * shows — origins from the injected script, field names from the DOM,
7
+ * counters derived from both — so it stays available in production, where a
8
+ * misbehaving preview is exactly the case worth diagnosing. Reading one
9
+ * performs no I/O and transmits nothing.
10
+ */
11
+
12
+ /** Origin trust as the runtime currently sees it. */
13
+ interface InspectionOrigins {
14
+ /** Configured origins; empty means the referrer and localhost heuristics decide instead. */
15
+ readonly trusted: readonly string[];
16
+ /** The origin locked onto by the first accepted update; every other is then refused. */
17
+ readonly locked: string | undefined;
18
+ }
19
+ /** Protocol versions and the capabilities they enable. */
20
+ interface InspectionProtocol {
21
+ /** This library's protocol version. */
22
+ readonly ours: number;
23
+ /** The remote party's version, or `undefined` if it never announced one. */
24
+ readonly theirs: number | undefined;
25
+ /** `min(ours, theirs ?? 1)` — what both sides actually share. */
26
+ readonly negotiated: number;
27
+ /** Capability flags enabled at the negotiated version. */
28
+ readonly capabilities: readonly string[];
29
+ /** The subset of `capabilities` seen on the wire rather than granted by version. */
30
+ readonly observed: readonly string[];
31
+ /** The Payload profile the observed capabilities imply: `unknown`, `payload-2` or `payload-3`. */
32
+ readonly profile: string;
33
+ }
34
+ /** Revision accounting for the update pipeline. */
35
+ interface InspectionRevisions {
36
+ /** Updates accepted since the runtime started. */
37
+ readonly accepted: number;
38
+ /**
39
+ * Updates that were still in flight when a newer one arrived and were
40
+ * therefore abandoned. A number that tracks `accepted` closely means the
41
+ * editor is out-typing the pipeline, which is normal; it is only a problem
42
+ * when the last update is among the abandoned ones.
43
+ */
44
+ readonly superseded: number;
45
+ /**
46
+ * Updates whose scheduled writes reached the DOM. What is neither
47
+ * superseded nor completed is in flight or was cancelled; a `superseded`
48
+ * that tracks `accepted` while `completed` stays low is the editor
49
+ * out-typing the pipeline.
50
+ */
51
+ readonly completed: number;
52
+ /**
53
+ * Bindings not scheduled because their value was identical to the one last
54
+ * applied. Cumulative since start; always `0` unless `skipUnchanged` is on.
55
+ * A large number beside a small `accepted` is the optimisation working.
56
+ */
57
+ readonly skippedUnchanged: number;
58
+ /** Revision currently in flight, or `undefined` when the pipeline is idle. */
59
+ readonly active: number | undefined;
60
+ }
61
+ /** What the DOM offers the runtime to write into. */
62
+ interface InspectionBindings {
63
+ /** Elements carrying a binding. */
64
+ readonly elements: number;
65
+ /** Distinct field names across those elements. */
66
+ readonly fields: number;
67
+ /** Those field names, sorted. */
68
+ readonly fieldNames: readonly string[];
69
+ /**
70
+ * Bound fields some update carried no value for, so the binding kept its old
71
+ * text — why a binding can stay stale while its siblings update. Cumulative.
72
+ */
73
+ readonly absentFields: readonly string[];
74
+ /**
75
+ * Field names that arrived but matched no binding — a markup problem.
76
+ * A name in neither this list nor `fieldNames` was never sent. Cumulative.
77
+ */
78
+ readonly orphanFields: readonly string[];
79
+ /** Whether `scopeBindingsByOwner` is active. */
80
+ readonly ownerScoped: boolean;
81
+ /** Distinct document owners currently on the page, sorted. */
82
+ readonly owners: readonly string[];
83
+ }
84
+ /** Scheduler work in progress. */
85
+ interface InspectionScheduler {
86
+ /** Writes buffered for the next flush. */
87
+ readonly pending: number;
88
+ /** Writes held back offscreen above `visibilityGateThreshold`; applied when scrolled into view. */
89
+ readonly deferred: number;
90
+ /** The binding count above which the visibility gate starts deferring. */
91
+ readonly visibilityGateThreshold: number;
92
+ /** Whether the binding count is above that threshold right now. */
93
+ readonly visibilityGateActive: boolean;
94
+ /** Stats of the most recent flush, or `undefined` if none has run. */
95
+ readonly lastFlush: {
96
+ readonly applied: number;
97
+ /** Which fields the flush wrote; a count alone cannot say a binding was skipped. */
98
+ readonly appliedFields: readonly string[];
99
+ readonly deferred: number;
100
+ readonly durationMs: number;
101
+ } | undefined;
102
+ }
103
+ /** A point-in-time read; plain values only, with no references into runtime internals. */
104
+ interface LivePreviewInspection {
105
+ /** Package version that produced this snapshot. */
106
+ readonly version: string;
107
+ /** Whether the runtime is started, and whether it has been destroyed. */
108
+ readonly started: boolean;
109
+ /** Connection status as reported to the `connect`/`disconnect` events. */
110
+ readonly status: ConnectionStatus;
111
+ readonly origins: InspectionOrigins;
112
+ readonly protocol: InspectionProtocol;
113
+ readonly revisions: InspectionRevisions;
114
+ readonly bindings: InspectionBindings;
115
+ readonly scheduler: InspectionScheduler;
116
+ /** Field types with a registered renderer, sorted. */
117
+ readonly renderers: readonly string[];
118
+ /** Registered plugins and their live registrations; empty on a bare runtime. */
119
+ readonly plugins: readonly PluginInspection[];
120
+ /** Server-rendered fragment boundaries: whether a handler exists and what happened to renders. */
121
+ readonly fragments: InspectionFragments;
122
+ /** Route refreshes: whether a strategy exists, how many ran, failed, or were stopped by the loop guard. */
123
+ readonly route: InspectionRoute;
124
+ }
125
+ /** The route strategy as `inspect()` reports it. */
126
+ interface InspectionRoute {
127
+ readonly handler: boolean;
128
+ readonly refreshes: number;
129
+ readonly failed: number;
130
+ /** Second refresh requests for one revision, refused with LP0805. */
131
+ readonly loopStopped: number;
132
+ }
133
+ /** The fragment strategy as `inspect()` reports it. */
134
+ interface InspectionFragments {
135
+ /** Whether a fragment handler is configured; without one, boundaries are patched. */
136
+ readonly handler: boolean;
137
+ readonly inFlight: number;
138
+ readonly rendered: number;
139
+ readonly failed: number;
140
+ readonly superseded: number;
141
+ }
142
+ /** One plugin as `inspect().plugins` reports it. */
143
+ interface PluginInspection {
144
+ readonly name: string;
145
+ readonly version: string | undefined;
146
+ /** `initializing` while `init` runs, `active` afterwards, `tearing-down` while `destroy` runs. */
147
+ readonly state: 'initializing' | 'active' | 'tearing-down';
148
+ /** Live registrations owned by the plugin's scope, by kind. */
149
+ readonly registrations: {
150
+ readonly transforms: number;
151
+ readonly renderers: number;
152
+ readonly subscriptions: number;
153
+ readonly cleanups: number;
154
+ };
155
+ }
156
+
157
+ /** Payload's `DocumentEvent` shape (admin `providers/DocumentEvents`). */
158
+ interface PayloadDocumentEventDetail {
159
+ readonly entitySlug: string;
160
+ readonly operation?: 'create' | 'update';
161
+ readonly id?: string | number;
162
+ readonly updatedAt?: string;
163
+ readonly [extra: string]: unknown;
164
+ }
165
+ /** A validated update as events expose it. */
166
+ interface PayloadLivePreviewData {
167
+ readonly fields: Record<string, unknown>;
168
+ readonly schema?: readonly PayloadFieldSchema[];
169
+ readonly globalSlug?: string;
170
+ readonly collectionSlug?: string;
171
+ readonly locale?: string;
172
+ }
173
+ /** The subset of Payload's field schema the runtime reads; extra properties are kept opaquely. */
174
+ interface PayloadFieldSchema {
175
+ readonly name: string;
176
+ readonly type: PayloadFieldType;
177
+ readonly label?: string;
178
+ readonly required?: boolean;
179
+ readonly localized?: boolean;
180
+ readonly fields?: readonly PayloadFieldSchema[];
181
+ readonly blocks?: readonly PayloadBlockSchema[];
182
+ readonly relationTo?: string | readonly string[];
183
+ readonly hasMany?: boolean;
184
+ readonly admin?: {
185
+ readonly condition?: PayloadFieldCondition;
186
+ };
187
+ readonly [extra: string]: unknown;
188
+ }
189
+ interface PayloadBlockSchema {
190
+ readonly slug: string;
191
+ readonly fields: readonly PayloadFieldSchema[];
192
+ readonly [extra: string]: unknown;
193
+ }
194
+ /** Payload's core field types. `tabs` is a structural container; `group` flattens. */
195
+ type PayloadFieldType = 'text' | 'textarea' | 'richText' | 'email' | 'number' | 'checkbox' | 'date' | 'select' | 'radio' | 'array' | 'blocks' | 'group' | 'tabs' | 'row' | 'collapsible' | 'relationship' | 'upload' | 'point' | 'json' | 'code' | 'ui';
196
+ /** `admin.condition` is a function in source and cannot cross `postMessage`; modelled, not consumed. */
197
+ type PayloadFieldCondition = (data: unknown, siblingData: unknown) => boolean;
198
+
199
+ /**
200
+ * Every diagnostic code the runtime and tools emit, so a consumer can branch
201
+ * on `e.code` instead of matching message text. A code is never reused for a
202
+ * different meaning; a retired one stays reserved.
203
+ *
204
+ * Browser-side reporting sites write the literal (`code: 'LP0603'`) rather than
205
+ * reading it from this record: the frozen table would then ship in the inline
206
+ * runtime for the sake of six characters. Server-side tools may import it.
207
+ */
208
+ /**
209
+ * Every diagnostic code the runtime can report, by name.
210
+ *
211
+ * ```ts
212
+ * client.events.on('error', (e) => {
213
+ * if (e.code === DIAGNOSTIC_CODES.TransformThrew) reportToSentry(e.error);
214
+ * });
215
+ * ```
216
+ */
217
+ declare const DIAGNOSTIC_CODES: Readonly<{
218
+ /** No trusted origin configured in production; nothing will be accepted. */
219
+ readonly NoTrustedOrigin: "LP0101";
220
+ /** Origin trust rests on `document.referrer`, so any framing site is trusted. */
221
+ readonly ReferrerOnlyTrust: "LP0102";
222
+ /** A plugin declares a runtime range this runtime does not satisfy; it was refused. */
223
+ readonly PluginIncompatible: "LP0103";
224
+ /** An update named a field with no binding anchor on the page. */
225
+ readonly OrphanField: "LP0201";
226
+ /** Owner scoping is on and the update names no document it could belong to. */
227
+ readonly UnattributableUpdate: "LP0202";
228
+ /** The visibility gate held offscreen writes back until they scroll into view. */
229
+ readonly VisibilityGateDeferred: "LP0301";
230
+ /** A value was refused because the attribute or the value itself is unsafe. */
231
+ readonly UnsafeAttributeWrite: "LP0401";
232
+ /** A text element has structured children, so replacing its text was skipped. */
233
+ readonly TextTargetHasChildren: "LP0402";
234
+ /** A structural container has no array template, so the update was skipped. */
235
+ readonly MissingArrayTemplate: "LP0403";
236
+ /** A structural item has no `id`; it pairs positionally, so an insert re-renders every row after it. */
237
+ readonly StructuralItemUnkeyed: "LP0404";
238
+ /** Two structural items share a key; later ones pair positionally. */
239
+ readonly StructuralDuplicateKey: "LP0405";
240
+ /** Every structural key changed while the length did not; the source generates keys per message. */
241
+ readonly StructuralUnstableKeys: "LP0406";
242
+ /** A binding asks for a delivery strategy this release does not have; it is left unchanged. */
243
+ readonly UnsupportedStrategy: "LP0407";
244
+ /** A message was rejected before it reached the update pipeline. */
245
+ readonly MessageRejected: "LP0501";
246
+ /** A preview token was rejected. */
247
+ readonly TokenRejected: "LP0502";
248
+ /** A consumer event handler threw. */
249
+ readonly HandlerThrew: "LP0601";
250
+ /** A consumer transform threw; the original value was kept. */
251
+ readonly TransformThrew: "LP0602";
252
+ /** A renderer threw while writing a value. */
253
+ readonly RendererThrew: "LP0603";
254
+ /** Runtime startup failed. */
255
+ readonly StartupFailed: "LP0605";
256
+ /** Sending the ready handshake failed. */
257
+ readonly ReadyFailed: "LP0606";
258
+ /** The audit found no runtime in a response that carried preview intent. */
259
+ readonly AuditRuntimeMissing: "LP0701";
260
+ /** The preview response declares no `frame-ancestors`. */
261
+ readonly AuditNoFrameAncestors: "LP0702";
262
+ /** `X-Frame-Options` forbids framing, which no CSP can undo. */
263
+ readonly AuditFrameOptionsBlocks: "LP0703";
264
+ /** Binding attributes are served to anonymous visitors. */
265
+ readonly AuditBindingsExposed: "LP0704";
266
+ /** More bindings than the default visibility gate will write eagerly. */
267
+ readonly AuditGateThresholdExceeded: "LP0705";
268
+ /** Owner markers exist, but some bindings are outside all of them. */
269
+ readonly AuditUnownedBindings: "LP0706";
270
+ /** The preview response carries no bindings at all. */
271
+ readonly AuditNoBindings: "LP0707";
272
+ /** The URL did not return an HTML page, so nothing else can be judged. */
273
+ readonly AuditNotAPage: "LP0708";
274
+ /** A fragment request failed (network, timeout, server error); the boundary was patched instead. */
275
+ readonly FragmentRequestFailed: "LP0801";
276
+ /** The fragment response had the wrong content type or shape; the boundary was patched instead. */
277
+ readonly FragmentResponseInvalid: "LP0802";
278
+ /** The fragment endpoint refused the preview (not authorized); the boundary was patched instead. */
279
+ readonly FragmentUnauthorized: "LP0803";
280
+ /** A fragment response arrived for a revision that was already superseded and was discarded. */
281
+ readonly FragmentSuperseded: "LP0804";
282
+ /** A route refresh was requested again for the same revision; the loop guard stopped it. */
283
+ readonly RouteRefreshLoop: "LP0805";
284
+ /** A boundary asks for the fragment strategy but no fragment handler is configured; it is patched. */
285
+ readonly FragmentStrategyUnavailable: "LP0806";
286
+ /** A readiness row is not yet at its 2.0 value; `pll doctor --v2` reports it. */
287
+ readonly V2ReadinessGap: "LP0709";
288
+ /** The preview runtime is served to anonymous visitors, not only inside the admin frame. */
289
+ readonly RuntimeOnPublicPage: "LP0710";
290
+ }>;
291
+ /** A diagnostic code, as it appears in log output and on the `error` event. */
292
+ type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[keyof typeof DIAGNOSTIC_CODES];
293
+
294
+ /**
295
+ * How a bound region is brought up to date: the runtime patches it, a server
296
+ * renders a `data-payload-fragment` boundary from the unsaved form state, or
297
+ * the whole route refreshes. Core carries only the seam — which boundaries a
298
+ * strategy owns and what it may do — so a patch-only page pays for nothing
299
+ * more; the orchestration lives in `payload-live-preview/fragment`.
300
+ */
301
+
302
+ /** What produced an update: the runtime's DOM patching, a server-rendered fragment, or a route refresh. */
303
+ type UpdateSource = 'patch' | 'fragment' | 'route';
304
+ /** One revision, as a strategy sees it, with the runtime capabilities it may use. */
305
+ interface FragmentContext {
306
+ readonly root: ParentNode;
307
+ readonly revision: number;
308
+ readonly receivedAt: number;
309
+ readonly fields: Readonly<Record<string, unknown>>;
310
+ readonly locale: string | undefined;
311
+ readonly collectionSlug: string | undefined;
312
+ readonly globalSlug: string | undefined;
313
+ /** Aborted when a newer revision arrives or the runtime stops. */
314
+ readonly signal: AbortSignal;
315
+ /** Whether this revision is still the current one. */
316
+ readonly isCurrent: () => boolean;
317
+ /** Morph server-rendered HTML into a boundary (Trusted Types and the keyed morph apply). */
318
+ readonly morph: (boundary: Element, html: string) => void;
319
+ /** Patch the boundary's own bindings from this revision — the deterministic fallback. */
320
+ readonly patch: (boundary: Element) => void;
321
+ /** Debug log through the runtime's logger, with the diagnostic code. */
322
+ readonly log: (code: DiagnosticCode, detail: string) => void;
323
+ /** Report a boundary rendered. */
324
+ readonly rendered: (boundary: Element, id: string, key: string | undefined) => void;
325
+ /** Report a boundary failed and patched instead; emits the `error` and `fragmentRender` events. */
326
+ readonly failed: (boundary: Element, id: string, key: string | undefined, code: DiagnosticCode, reason: string) => void;
327
+ }
328
+ interface FragmentReport {
329
+ readonly rendered: number;
330
+ readonly failed: number;
331
+ readonly superseded: number;
332
+ }
333
+ /** A fragment strategy: which boundaries it owns for a revision, and how it renders them. */
334
+ interface FragmentStrategy {
335
+ /** The boundaries this update re-renders; their inner bindings are left to the strategy. */
336
+ readonly plan: (root: ParentNode, changedFields: ReadonlySet<string>) => readonly Element[];
337
+ /** Render the planned boundaries; resolves once every one settled. */
338
+ readonly render: (context: FragmentContext, boundaries: readonly Element[]) => Promise<FragmentReport>;
339
+ }
340
+ /** One revision, as the route strategy sees it. */
341
+ interface RouteContext {
342
+ readonly revision: number;
343
+ readonly receivedAt: number;
344
+ /** Aborted when a newer revision arrives or the runtime stops. */
345
+ readonly signal: AbortSignal;
346
+ readonly isCurrent: () => boolean;
347
+ readonly log: (code: DiagnosticCode, detail: string) => void;
348
+ }
349
+ /**
350
+ * Whether a revision needs the whole route re-rendered, and how. After a
351
+ * refresh the runtime rescans and re-applies the revision, so the unsaved
352
+ * state lands on the fresh markup.
353
+ */
354
+ interface RouteStrategy {
355
+ readonly plan: (root: ParentNode, changedFields: ReadonlySet<string>) => boolean;
356
+ readonly refresh: (context: RouteContext) => Promise<'refreshed' | 'failed' | 'superseded'>;
357
+ }
358
+ interface StrategyHandlers {
359
+ readonly fragment?: FragmentStrategy;
360
+ readonly route?: RouteStrategy;
361
+ }
362
+
363
+ /** Public event payloads. The map keys are the valid event names; `EventEmitter` is generic over it. */
364
+
365
+ interface LivePreviewEventMap {
366
+ /** Once per startup attempt, after observers, cache and message listening are active. A rolled-back attempt emits it again on retry. */
367
+ readonly init: {
368
+ readonly timestamp: number;
369
+ };
370
+ /** The first accepted data-bearing update from a trusted origin. */
371
+ readonly connect: {
372
+ readonly origin: string;
373
+ readonly timestamp: number;
374
+ };
375
+ /** The heartbeat timed out, the runtime was destroyed, or the page was suspended for navigation (`'unload'`). */
376
+ readonly disconnect: {
377
+ readonly reason: 'timeout' | 'destroy' | 'unload';
378
+ readonly timestamp: number;
379
+ };
380
+ /** Before the DOM is mutated for an update; `cancel()` skips exactly this revision. */
381
+ readonly beforeUpdate: {
382
+ readonly data: PayloadLivePreviewData;
383
+ readonly revision?: number;
384
+ /** When the runtime accepted the message, Unix milliseconds. */
385
+ readonly receivedAt?: number;
386
+ /** The strategy that produced the update. */
387
+ readonly source?: UpdateSource;
388
+ readonly cancel: () => void;
389
+ };
390
+ /** After each applied, still-current batch. Visibility replay may emit another for the same revision; cancelled, obsolete and deferred-only batches emit none. */
391
+ readonly afterUpdate: {
392
+ readonly data: PayloadLivePreviewData;
393
+ readonly updatedCount: number;
394
+ readonly durationMs: number;
395
+ readonly revision?: number;
396
+ readonly receivedAt?: number;
397
+ readonly source?: UpdateSource;
398
+ };
399
+ /** Each successful, still-current element write. */
400
+ readonly elementUpdate: {
401
+ readonly element: Element;
402
+ readonly fieldName: string;
403
+ readonly previousValue: unknown;
404
+ readonly nextValue: unknown;
405
+ readonly revision?: number;
406
+ readonly receivedAt?: number;
407
+ readonly source?: UpdateSource;
408
+ };
409
+ /** The element cache was rebuilt (initial scan or mutation). */
410
+ readonly cacheRefresh: {
411
+ readonly elementCount: number;
412
+ readonly fieldCount: number;
413
+ readonly durationMs: number;
414
+ };
415
+ /** Once per fragment boundary and revision: rendered by the server, or failed (with the LP08xx code) and patched instead. */
416
+ readonly fragmentRender: {
417
+ readonly element: Element;
418
+ readonly id: string;
419
+ readonly key: string | undefined;
420
+ readonly status: 'rendered' | 'failed';
421
+ readonly code?: DiagnosticCode;
422
+ readonly revision: number;
423
+ readonly receivedAt: number;
424
+ };
425
+ /** A `payload-document-event` message arrived (document save). */
426
+ readonly documentSave: {
427
+ readonly timestamp: number;
428
+ };
429
+ /** A data update carried `externallyUpdatedRelationship`: a related document changed in an admin drawer, so the update re-renders unconditionally. */
430
+ readonly relationshipUpdate: {
431
+ readonly detail: PayloadDocumentEventDetail;
432
+ readonly timestamp: number;
433
+ };
434
+ /** An error the runtime caught but cannot fully recover from. Branch on `code`; `context` is the human-readable origin. */
435
+ readonly error: {
436
+ readonly error: Error;
437
+ readonly context: string;
438
+ readonly code: DiagnosticCode;
439
+ };
440
+ /** During destroy, after observers and the message listener are removed; listeners are released by the owning client afterwards. */
441
+ readonly destroy: {
442
+ readonly timestamp: number;
443
+ };
444
+ }
445
+ /** Handlers may return a promise; they are awaited in registration order, which `beforeUpdate.cancel()` relies on. */
446
+ type EventHandler<TPayload> = (payload: TPayload) => void | Promise<void>;
447
+ type Unsubscribe = () => void;
448
+
449
+ /**
450
+ * Per-instance typed emitter: handlers run sequentially in registration order,
451
+ * may be async, and a throwing one is logged and isolated. See ADR 0002.
452
+ */
453
+
454
+ declare class EventEmitter<TMap extends object = LivePreviewEventMap> {
455
+ #private;
456
+ on<E extends keyof TMap>(event: E, handler: EventHandler<TMap[E]>): Unsubscribe;
457
+ once<E extends keyof TMap>(event: E, handler: EventHandler<TMap[E]>): Unsubscribe;
458
+ off<E extends keyof TMap>(event: E, handler: EventHandler<TMap[E]>): void;
459
+ /** Dispatch to every handler: regular ones first, then `once` handlers. */
460
+ emit<E extends keyof TMap>(event: E, payload: TMap[E]): Promise<void>;
461
+ /**
462
+ * Dispatch while `shouldContinue()` holds — checked around every handler, so
463
+ * an obsolete transaction cannot resume across an await.
464
+ * @internal
465
+ */
466
+ emitWhile<E extends keyof TMap>(event: E, payload: TMap[E], shouldContinue: () => boolean): Promise<boolean>;
467
+ /** Registered handlers for `event`, `on` and `once` together. */
468
+ listenerCount(event: keyof TMap): number;
469
+ /** Remove every handler, or only those of `event`. */
470
+ removeAllListeners(event?: keyof TMap): void;
471
+ /** Event names with at least one handler. */
472
+ eventNames(): (keyof TMap)[];
473
+ }
474
+
475
+ /** Types shared by the runtime primitives. */
476
+
477
+ /** Payload's field set plus the DOM-binding categories `html`, `url`, `image` and `structural-array`. */
478
+ type FieldType = PayloadFieldType | 'html' | 'url' | 'image' | 'structural-array';
479
+ /** A namespaced project renderer key, so a typo of a built-in type can never become one. */
480
+ type CustomRendererKey = `${string}:${string}`;
481
+ /** What a renderer may be registered under and an element may ask for. */
482
+ type RendererKey = FieldType | CustomRendererKey;
483
+ /**
484
+ * A project rich-text renderer, shared by SSR and preview. Its output goes
485
+ * through the sanitizer; call the same `sanitizeHtml()` server-side for byte equality.
486
+ */
487
+ type RichTextRenderer = (value: unknown, context: {
488
+ readonly fieldName: string;
489
+ readonly element: Element;
490
+ readonly locale: string | undefined;
491
+ }) => string;
492
+ /** One registered binding. Several may share a field name when it renders in several places. */
493
+ interface CachedElement {
494
+ /** The bound DOM element. */
495
+ readonly element: Element;
496
+ /** Payload field path, e.g., `title` or `hero.subtitle`. */
497
+ readonly fieldName: string;
498
+ /** Resolved from attributes and tag heuristics; the schema may override it unless explicit. */
499
+ readonly fieldType: RendererKey;
500
+ /** Whether `data-payload-type` set the type, in which case the schema must not override it. */
501
+ readonly explicitFieldType?: boolean;
502
+ /** Fields this binding depends on (`data-payload-depends`); a change in any re-applies it under `skipUnchanged`. */
503
+ readonly dependsOn?: readonly string[];
504
+ /** Raw `data-payload-strategy` value. */
505
+ readonly strategy?: string;
506
+ /** How the runtime brings this binding up to date; `'unknown'` for an unrecognised strategy. Resolved by the cache. */
507
+ readonly strategyKind?: UpdateSource | 'unknown';
508
+ /** Nearest enclosing `data-payload-fragment` boundary. Resolved by the cache. */
509
+ readonly fragmentBoundary?: Element;
510
+ /** `data-payload-boundary`: an anchor that hides itself while its field is empty. */
511
+ readonly boundary?: boolean;
512
+ /** Write the value into this attribute instead of the content; policed writes. */
513
+ readonly targetAttribute?: string;
514
+ /** Optional sibling-field path bound to the element's `href` attribute. */
515
+ readonly hrefField?: string;
516
+ /** Optional sibling-field path bound to the element's `src` attribute. */
517
+ readonly srcField?: string;
518
+ /** Optional sibling-field path bound to the element's `alt` attribute. */
519
+ readonly altField?: string;
520
+ /** Optional inline template for array/blocks rendering. */
521
+ readonly arrayTemplate?: string;
522
+ /** Optional separator for primitive-array stringification. */
523
+ readonly arraySeparator?: string;
524
+ /** Optional locale code locked onto this element (overrides the global locale). */
525
+ readonly locale?: string;
526
+ /** The document this binding belongs to, from the nearest `data-payload-owner`. */
527
+ readonly owner?: string;
528
+ }
529
+ /** What a renderer is given; `allFields` lets it resolve a sibling field. */
530
+ interface RenderContext {
531
+ /** Full field map for the current update — used for sibling lookups. */
532
+ readonly allFields: Record<string, unknown>;
533
+ /** Active locale, or `undefined` when none is established. */
534
+ readonly locale: string | undefined;
535
+ /** Optional schema descriptor for the field, when available. */
536
+ readonly schema: PayloadFieldSchema | undefined;
537
+ /** The project's rich-text renderer, when the client was configured with one. */
538
+ readonly renderRichText?: RichTextRenderer;
539
+ }
540
+ /**
541
+ * A renderer writes one value into its element. It must not throw: one bad
542
+ * field may not stop an update. The result stays `void` — the internal
543
+ * no-write sentinel is not part of the contract.
544
+ */
545
+ interface FieldRenderer {
546
+ readonly name: RendererKey;
547
+ render(target: CachedElement, value: unknown, context: RenderContext): void;
548
+ }
549
+
550
+ /**
551
+ * Plugin compatibility claims. The range grammar is the subset a plugin
552
+ * author writes (`*`, `1.2.3`, `^`, `~`, `>=`, `>`, `<`, `<=`, space-joined
553
+ * conjunctions, `||` alternatives); prerelease tags are ignored.
554
+ */
555
+ interface PluginCompatibility {
556
+ /** A semver range the runtime's `VERSION` must satisfy, e.g. `>=2.0.0`. */
557
+ readonly runtime?: string;
558
+ /** The highest postMessage protocol version the plugin understands. */
559
+ readonly protocol?: number;
560
+ }
561
+
562
+ /** Plugin contract: a scoped, per-instance context for renderers, transforms and events. */
563
+
564
+ /** Idempotent handle that releases one plugin-owned resource. */
565
+ type PluginDisposer = () => void;
566
+ /** The client's event surface scoped to one registration: bulk removal and introspection see only this plugin's listeners. */
567
+ interface PluginEvents {
568
+ readonly on: <E extends keyof LivePreviewEventMap>(event: E, handler: EventHandler<LivePreviewEventMap[E]>) => Unsubscribe;
569
+ readonly once: <E extends keyof LivePreviewEventMap>(event: E, handler: EventHandler<LivePreviewEventMap[E]>) => Unsubscribe;
570
+ readonly off: <E extends keyof LivePreviewEventMap>(event: E, handler: EventHandler<LivePreviewEventMap[E]>) => void;
571
+ /** Emit through the owning client's event channel. */
572
+ readonly emit: <E extends keyof LivePreviewEventMap>(event: E, payload: LivePreviewEventMap[E]) => Promise<void>;
573
+ /** Guarded emit; dispatch stops when the predicate turns false or this registration is removed. */
574
+ readonly emitWhile: <E extends keyof LivePreviewEventMap>(event: E, payload: LivePreviewEventMap[E], shouldContinue: () => boolean) => Promise<boolean>;
575
+ readonly listenerCount: (event: keyof LivePreviewEventMap) => number;
576
+ readonly removeAllListeners: (event?: keyof LivePreviewEventMap) => void;
577
+ readonly eventNames: () => (keyof LivePreviewEventMap)[];
578
+ }
579
+ /**
580
+ * Synchronous value transform run in registration order; returning a thenable
581
+ * is a contract error (`LP0602`) that dispatches the untransformed value.
582
+ */
583
+ type FieldTransform = (value: unknown, context: {
584
+ readonly fieldName: string;
585
+ readonly element: Element;
586
+ readonly allFields: Record<string, unknown>;
587
+ }) => unknown;
588
+ interface PluginContext {
589
+ readonly events: PluginEvents;
590
+ /** Register a renderer layer owned by this registration. */
591
+ readonly registerFieldRenderer: (renderer: FieldRenderer) => void;
592
+ /** Register an ordered transform owned by this registration. */
593
+ readonly registerTransform: (fieldName: string, transform: FieldTransform) => void;
594
+ /** Register a synchronous cleanup run on rollback, `unuse()` and client destruction. */
595
+ readonly registerCleanup?: (cleanup: PluginDisposer) => void;
596
+ readonly getConfig: () => Readonly<Record<string, unknown>>;
597
+ readonly log: (...args: unknown[]) => void;
598
+ }
599
+ /** `init` runs once per registration, `destroy` on removal; both may return a promise. */
600
+ interface LivePreviewPlugin {
601
+ readonly name: string;
602
+ readonly version?: string;
603
+ /** Checked at registration; a plugin this runtime does not fit is refused (`LP0103`). */
604
+ readonly compat?: PluginCompatibility;
605
+ readonly init: (context: PluginContext) => void | Promise<void>;
606
+ readonly destroy?: () => void | Promise<void>;
607
+ }
608
+
609
+ /**
610
+ * The two defaults profiles, row by row. 2.0 ships `v2`; `defaults: 'v1'` opts
611
+ * back into the 1.x table for a staged migration. Each row belongs to exactly
612
+ * one side — the adapter's request decision or the browser runtime — and a
613
+ * test asserts the profile assigns every readiness row that has an option, so
614
+ * a row added later cannot be forgotten. See ADR 0007.
615
+ */
616
+ /** `'v2'` is the 2.0 default; `'v1'` is the 1.x table. */
617
+ type DefaultsProfile = 'v1' | 'v2';
618
+ /** How the runtime decides which windows may post updates. */
619
+ type EventSourcePolicy = 'any' | 'parent-or-opener';
620
+
621
+ /**
622
+ * `LivePreviewClient` configuration. Defaults are the 2.0 rows; `defaults: 'v1'`
623
+ * restores the 1.x values named per option (ADR 0007).
624
+ */
625
+
626
+ interface LivePreviewClientConfig {
627
+ /** Explicit trusted admin origins. */
628
+ readonly allowedOrigins?: readonly string[];
629
+ /** Payload origin; every update is then re-fetched through the REST API so relations arrive populated. Requires `mergeDepth`. */
630
+ readonly serverURL?: string;
631
+ /** REST route prefix used with `serverURL`. Default `/api`. */
632
+ readonly apiRoute?: string;
633
+ /** Population depth used with `serverURL`. Required with it; `defaults: 'v1'` falls back to `1`. */
634
+ readonly mergeDepth?: number;
635
+ /** Custom fetch for the `serverURL` merge request: attach auth headers or route through a proxy. */
636
+ readonly mergeFetch?: typeof fetch;
637
+ /** Verbose console output. Defaults to dev-mode detection. */
638
+ readonly debug?: boolean;
639
+ /** Debounce window for incoming updates. Default 50 ms. */
640
+ readonly debounceMs?: number;
641
+ /** Heartbeat timeout in ms; `0` disables it (default), because the admin posts only on edits. */
642
+ readonly heartbeatMs?: number;
643
+ /** IntersectionObserver `rootMargin`. Default `200px`. */
644
+ readonly intersectionRootMargin?: string;
645
+ /** Update only bindings under a matching `data-payload-owner`; an unowned binding is then never updated. Default `false`. */
646
+ readonly scopeBindingsByOwner?: boolean;
647
+ /** Skip a binding whose value did not change. Default `true`; `defaults: 'v1'` sets `false`. */
648
+ readonly skipUnchanged?: boolean;
649
+ /** Scroll the preview to the field being edited when its value changes. Default `false`. */
650
+ readonly revealEditedField?: boolean;
651
+ /** Fields whose change re-applies other bindings regardless of their own value: `{ price: ['priceLabel'] }`. Used with `skipUnchanged`. */
652
+ readonly dependencies?: Readonly<Record<string, readonly string[]>>;
653
+ /** Strategy handlers beyond patching; `createFragmentStrategy()` from `payload-live-preview/fragment` builds one. */
654
+ readonly strategies?: StrategyHandlers;
655
+ /** Apply every update regardless of visibility. Default `false`. */
656
+ readonly disableVisibilityGate?: boolean;
657
+ /** Cache size above which off-screen updates wait for intersection. Default `50`. */
658
+ readonly visibilityGateThreshold?: number;
659
+ /** Mount an `aria-live` region for connections, applied updates and heartbeat disconnects. Default `true`. */
660
+ readonly enableA11y?: boolean;
661
+ /** Locale of the announcement strings. Defaults to the detected locale. */
662
+ readonly a11yLocale?: string;
663
+ /** Document root. Default `document`. */
664
+ readonly root?: Document | Element;
665
+ /** Renderer resolution ahead of the registry; return `undefined` to fall through. */
666
+ readonly resolveRenderer?: (fieldType: RendererKey, target: CachedElement) => FieldRenderer | undefined;
667
+ /** The project's rich-text renderer, shared with SSR. Its output is sanitized. */
668
+ readonly renderRichText?: RichTextRenderer;
669
+ /** Ignore `document.referrer` as an origin source. Default `true`; `defaults: 'v1'` sets `false`. */
670
+ readonly disableReferrerDetection?: boolean;
671
+ /** Disable the dev-mode localhost matcher. Default `false`. */
672
+ readonly disableLocalhostMatching?: boolean;
673
+ /** Which windows may post updates. Default `'parent-or-opener'`; `defaults: 'v1'` sets `'any'`. */
674
+ readonly eventSourcePolicy?: EventSourcePolicy;
675
+ /** Sanitizer policy for rich text and HTML writes. Default `'strict'`; `defaults: 'v1'` sets `'compat'`. */
676
+ readonly sanitizerPolicy?: 'compat' | 'strict';
677
+ /** `'v2'` (default) is the 2.0 table; `'v1'` restores every 1.x row at once. Explicit options win. */
678
+ readonly defaults?: DefaultsProfile;
679
+ /** Start the runtime in the constructor. Default `true`. */
680
+ readonly autoStart?: boolean;
681
+ /** Preview-token validator; every update must then carry a `previewToken` it approves. Stock Payload sends none. */
682
+ readonly validateToken?: (token: string | undefined, origin: string) => boolean | Promise<boolean>;
683
+ }
684
+
685
+ /**
686
+ * `LivePreviewClient`: a `LivePreviewRuntime` with its own emitter, plugin
687
+ * manager and renderer registry. A page that only needs a working preview uses
688
+ * `generateInlineScript()` instead.
689
+ */
690
+
691
+ declare class LivePreviewClient {
692
+ #private;
693
+ constructor(rawConfig?: LivePreviewClientConfig);
694
+ /**
695
+ * Start the runtime: `true` while eligible and started or scheduled for DOM
696
+ * readiness, `false` once destroyed or outside a preview context.
697
+ */
698
+ start(): boolean;
699
+ /**
700
+ * Release the message ingress, keeping plugins and renderers, for `pagehide`:
701
+ * a bfcache restore re-runs no script, so an attached client would return
702
+ * bound to a frozen page. `false` when nothing was running.
703
+ */
704
+ suspend(): boolean;
705
+ /** Reacquire after `suspend()`: the same path as `start()`, because a restored document needs the same rebuild. */
706
+ resume(): boolean;
707
+ /** Stop the runtime and tear down every plugin. Idempotent; concurrent callers share one promise. */
708
+ destroy(): Promise<void>;
709
+ use(plugin: LivePreviewPlugin): Promise<void>;
710
+ /** Unregister a plugin and release everything its registration owned. Still allowed from a destroy hook during teardown. */
711
+ unuse(name: string): Promise<void>;
712
+ refreshCache(): void;
713
+ get events(): EventEmitter;
714
+ /** Names of the registered plugins. */
715
+ get plugins(): readonly string[];
716
+ get status(): 'disconnected' | 'connecting' | 'connected';
717
+ /**
718
+ * Point-in-time read of runtime state, no I/O: `bindings.orphanFields` when a
719
+ * field refuses to update, `scheduler.deferred` when updates stop below the fold.
720
+ */
721
+ inspect(): LivePreviewInspection;
722
+ /** Number of accepted updates so far. */
723
+ get updateCount(): number;
724
+ /** `true` once `destroy()` has been called. */
725
+ get destroyed(): boolean;
726
+ }
727
+ /** A started client, or `null` when the page is not a preview context. */
728
+ declare function initLivePreview(config?: LivePreviewClientConfig): LivePreviewClient | null;
729
+
730
+ /**
731
+ * Admin-side reporter for "reveal the edited section": it names the field the
732
+ * editor's cursor is in so the preview scrolls there without a keystroke.
733
+ */
734
+ /** The preview window (usually `iframe.contentWindow`) messages are posted to. */
735
+ interface FocusReportTarget {
736
+ postMessage: (message: unknown, targetOrigin: string) => void;
737
+ }
738
+ interface PreviewFocusMessage {
739
+ readonly type: 'payload-live-preview-focus';
740
+ readonly field: string;
741
+ }
742
+ /** Post one focus report. `targetOrigin` must be the preview's exact origin, never `'*'`. */
743
+ declare function reportPreviewFocus(target: FocusReportTarget, field: string, targetOrigin: string): void;
744
+ /** A reporter bound to a preview window and origin; `resolveTarget` runs per report, so a re-created iframe is addressed freshly. */
745
+ declare function createPreviewFocusReporter(resolveTarget: () => FocusReportTarget | null | undefined, targetOrigin: string): (field: string) => void;
746
+
747
+ export { type CachedElement, type ConnectionStatus, type CustomRendererKey, DIAGNOSTIC_CODES, type DefaultsProfile, type DiagnosticCode, EventEmitter, type EventHandler, type EventSourcePolicy, type FieldRenderer, type FieldTransform, type FieldType, type FocusReportTarget, type FragmentContext, type FragmentReport, type FragmentStrategy, type InspectionBindings, type InspectionFragments, type InspectionOrigins, type InspectionProtocol, type InspectionRevisions, type InspectionRoute, type InspectionScheduler, LivePreviewClient, type LivePreviewClientConfig, type LivePreviewEventMap, type LivePreviewInspection, type LivePreviewPlugin, type PayloadBlockSchema, type PayloadDocumentEventDetail, type PayloadFieldCondition, type PayloadFieldSchema, type PayloadFieldType, type PayloadLivePreviewData, type PluginCompatibility, type PluginContext, type PluginDisposer, type PluginEvents, type PluginInspection, type PreviewFocusMessage, type RenderContext, type RendererKey, type RichTextRenderer, type RouteContext, type RouteStrategy, type StrategyHandlers, type Unsubscribe, type UpdateSource, createPreviewFocusReporter, initLivePreview, reportPreviewFocus };