@preprio/toolkit 0.5.0-rc.2 → 0.5.0-rc.4

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 (50) hide show
  1. package/README.md +209 -10
  2. package/dist/astro/index.cjs +1194 -1
  3. package/dist/astro/index.d.cts +47 -1
  4. package/dist/astro/index.d.ts +47 -1
  5. package/dist/astro/index.js +1197 -1
  6. package/dist/chunk-46ISDRHT.js +26 -0
  7. package/dist/chunk-74KY5EAM.js +1219 -0
  8. package/dist/chunk-AHBN6FQP.js +184 -0
  9. package/dist/{chunk-FLPNN3CV.js → chunk-PDNCNTDB.js} +1370 -623
  10. package/dist/chunk-S3VT4UWM.js +75 -0
  11. package/dist/chunk-TG6N3C22.js +246 -0
  12. package/dist/chunk-URXSDJOU.js +356 -0
  13. package/dist/index.cjs +3166 -392
  14. package/dist/index.d.cts +238 -4
  15. package/dist/index.d.ts +238 -4
  16. package/dist/index.js +189 -149
  17. package/dist/live-preview-H4643QYF.js +18 -0
  18. package/dist/nextjs/components.cjs +1522 -359
  19. package/dist/nextjs/components.d.cts +1 -1
  20. package/dist/nextjs/components.d.ts +1 -1
  21. package/dist/nextjs/components.js +4 -1
  22. package/dist/nextjs/index.cjs +1085 -6
  23. package/dist/nextjs/index.d.cts +73 -1
  24. package/dist/nextjs/index.d.ts +73 -1
  25. package/dist/nextjs/index.js +1079 -7
  26. package/dist/nextjs/live-action.cjs +285 -0
  27. package/dist/nextjs/live-action.d.cts +12 -0
  28. package/dist/nextjs/live-action.d.ts +12 -0
  29. package/dist/nextjs/live-action.js +68 -0
  30. package/dist/nextjs/live.cjs +1896 -0
  31. package/dist/nextjs/live.d.cts +52 -0
  32. package/dist/nextjs/live.d.ts +52 -0
  33. package/dist/nextjs/live.js +265 -0
  34. package/dist/nuxt/index.cjs +1 -1
  35. package/dist/nuxt/index.js +1 -1
  36. package/dist/nuxt/live-preview-O2ZTJNW4.js +1520 -0
  37. package/dist/nuxt/live.cjs +1720 -0
  38. package/dist/nuxt/live.d.cts +43 -0
  39. package/dist/nuxt/live.d.ts +43 -0
  40. package/dist/nuxt/live.js +94 -0
  41. package/dist/{pixel-B3oQNbZ3.d.cts → pixel-CX422dCO.d.cts} +10 -1
  42. package/dist/{pixel-B3oQNbZ3.d.ts → pixel-CX422dCO.d.ts} +10 -1
  43. package/dist/react/components.cjs +1522 -359
  44. package/dist/react/components.d.cts +9 -0
  45. package/dist/react/components.d.ts +9 -0
  46. package/dist/react/components.js +1522 -359
  47. package/dist/sveltekit/index.cjs +1 -1
  48. package/dist/sveltekit/index.js +1 -1
  49. package/package.json +12 -1
  50. package/src/astro/PreprToolbar.astro +7 -1
package/dist/index.cjs CHANGED
@@ -34,9 +34,14 @@ __export(src_exports, {
34
34
  getPreprUUIDFromHeaders: () => getPreprUUIDFromHeaders,
35
35
  getToolbarPropsFromHeaders: () => getToolbarPropsFromHeaders,
36
36
  loadTrackingPixel: () => loadTrackingPixel,
37
+ normalizeQuery: () => normalizeQuery,
38
+ parsePatchLog: () => parsePatchLog,
39
+ previewAttrs: () => previewAttrs,
37
40
  processPreprRequest: () => processPreprRequest,
41
+ readLiveLogFromRequest: () => readLiveLogFromRequest,
38
42
  resolveFeatures: () => resolveFeatures,
39
43
  setTrackingParam: () => setTrackingParam,
44
+ startHtmlLivePreview: () => startHtmlLivePreview,
40
45
  stegaClean: () => stegaClean,
41
46
  trackEvent: () => trackEvent,
42
47
  validatePreprToken: () => validatePreprToken
@@ -44,7 +49,7 @@ __export(src_exports, {
44
49
  module.exports = __toCommonJS(src_exports);
45
50
 
46
51
  // src/version.ts
47
- var VERSION = "0.5.0-rc.2";
52
+ var VERSION = "0.5.0-rc.4";
48
53
 
49
54
  // src/core/features.ts
50
55
  function isEnabled(config) {
@@ -75,6 +80,7 @@ var PARAM_SEGMENT = "prepr_preview_segment";
75
80
  var PARAM_VARIANT = "prepr_preview_ab";
76
81
  var PARAM_HIDE_BAR = "prepr_hide_bar";
77
82
  var ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;
83
+ var HEADER_LIVE_RENDER = "x-prepr-live";
78
84
 
79
85
  // src/core/cookies.ts
80
86
  function getCookie(name) {
@@ -116,6 +122,40 @@ function crossSiteCookieOptions() {
116
122
  return { sameSite: "None", secure: true };
117
123
  }
118
124
 
125
+ // src/core/locales/de.json
126
+ var de_default = {
127
+ common: {
128
+ viewingAs: "Ansicht als:",
129
+ user: "Benutzer",
130
+ off: "Aus",
131
+ on: "An",
132
+ reset: "Zur\xFCcksetzen",
133
+ toolbar: "Symbolleiste"
134
+ },
135
+ adaptiveContent: {
136
+ adaptiveContent: "Adaptive Inhalte",
137
+ enablePreview: "Vorschaumodus",
138
+ segment: "Segment",
139
+ ABVariant: "A/B-Variante",
140
+ chooseSegment: "Segment w\xE4hlen",
141
+ searchSegments: "Segmente suchen",
142
+ none: "Keine Segmente",
143
+ allOtherUsers: "Alle anderen Benutzer",
144
+ offDescription: "Die Website als echter Benutzer ansehen (Cookies verwenden)",
145
+ onDescription: "Mit der Symbolleiste Segmente und A/B-Varianten simulieren"
146
+ },
147
+ editingTools: {
148
+ editingTools: "Bearbeitungswerkzeuge",
149
+ editMode: "Bearbeitungsmodus",
150
+ ariaCloseEditMode: "Bearbeitungsmodus schlie\xDFen"
151
+ },
152
+ visualEditor: {
153
+ edit: "Bearbeiten",
154
+ otherItem: "anderes Element",
155
+ linkedItem: "verkn\xFCpftes Element"
156
+ }
157
+ };
158
+
119
159
  // src/core/locales/en.json
120
160
  var en_default = {
121
161
  common: {
@@ -142,6 +182,45 @@ var en_default = {
142
182
  editingTools: "Editing tools",
143
183
  editMode: "Edit mode",
144
184
  ariaCloseEditMode: "Close edit mode"
185
+ },
186
+ visualEditor: {
187
+ edit: "Edit",
188
+ otherItem: "other item",
189
+ linkedItem: "linked item"
190
+ }
191
+ };
192
+
193
+ // src/core/locales/fr.json
194
+ var fr_default = {
195
+ common: {
196
+ viewingAs: "Affichage en tant que :",
197
+ user: "Utilisateur",
198
+ off: "D\xE9sactiv\xE9",
199
+ on: "Activ\xE9",
200
+ reset: "R\xE9initialiser",
201
+ toolbar: "Barre d'outils"
202
+ },
203
+ adaptiveContent: {
204
+ adaptiveContent: "Contenu adaptatif",
205
+ enablePreview: "Mode aper\xE7u",
206
+ segment: "Segment",
207
+ ABVariant: "Variante A/B",
208
+ chooseSegment: "Choisir un segment",
209
+ searchSegments: "Rechercher des segments",
210
+ none: "Aucun segment",
211
+ allOtherUsers: "Tous les autres utilisateurs",
212
+ offDescription: "Voir le site comme un vrai utilisateur (utiliser les cookies)",
213
+ onDescription: "Utilisez la barre d'outils pour simuler des segments et des variantes A/B"
214
+ },
215
+ editingTools: {
216
+ editingTools: "Outils d'\xE9dition",
217
+ editMode: "Mode \xE9dition",
218
+ ariaCloseEditMode: "Fermer le mode \xE9dition"
219
+ },
220
+ visualEditor: {
221
+ edit: "Modifier",
222
+ otherItem: "autre \xE9l\xE9ment",
223
+ linkedItem: "\xE9l\xE9ment li\xE9"
145
224
  }
146
225
  };
147
226
 
@@ -171,13 +250,20 @@ var nl_default = {
171
250
  editingTools: "Editing Tools",
172
251
  editMode: "Edit mode",
173
252
  ariaCloseEditMode: "Edit mode sluiten"
253
+ },
254
+ visualEditor: {
255
+ edit: "Bewerken",
256
+ otherItem: "ander item",
257
+ linkedItem: "gekoppeld item"
174
258
  }
175
259
  };
176
260
 
177
261
  // src/core/i18n.ts
178
262
  var dictionaries = {
179
263
  en: en_default,
180
- nl: nl_default
264
+ nl: nl_default,
265
+ fr: fr_default,
266
+ de: de_default
181
267
  };
182
268
  var LOCALES = Object.keys(dictionaries);
183
269
  function isLocale(value) {
@@ -211,6 +297,9 @@ var trustedParentOrigin = null;
211
297
  function setTrustedParentOrigin(origin) {
212
298
  trustedParentOrigin = origin;
213
299
  }
300
+ function getTrustedParentOrigin() {
301
+ return trustedParentOrigin;
302
+ }
214
303
  function sendPreprEvent(event, data, options) {
215
304
  if (typeof window !== "undefined") {
216
305
  const message = {
@@ -270,49 +359,47 @@ function createScopedLogger(scopeName) {
270
359
  prefix: `[Prepr][${scopeName}]`
271
360
  });
272
361
  }
273
- function throttle(func, delay) {
274
- let timeoutId = null;
275
- let lastExecTime = 0;
276
- const throttledFunc = ((...args) => {
277
- const currentTime = Date.now();
278
- const timeSinceLastExec = currentTime - lastExecTime;
279
- if (timeSinceLastExec >= delay) {
280
- func(...args);
281
- lastExecTime = currentTime;
282
- } else {
283
- if (timeoutId) {
284
- clearTimeout(timeoutId);
285
- }
286
- timeoutId = setTimeout(() => {
287
- func(...args);
288
- lastExecTime = Date.now();
289
- timeoutId = null;
290
- }, delay - timeSinceLastExec);
291
- }
292
- });
293
- throttledFunc.cancel = () => {
294
- if (timeoutId) {
295
- clearTimeout(timeoutId);
296
- timeoutId = null;
297
- }
298
- };
299
- return throttledFunc;
300
- }
301
- function createElementCache(query, ttl = 1e3) {
302
- let cache = null;
303
- let lastCacheTime = 0;
304
- return () => {
305
- const now = Date.now();
306
- if (!cache || now - lastCacheTime > ttl) {
307
- cache = document.querySelectorAll(query);
308
- lastCacheTime = now;
309
- }
310
- return cache;
311
- };
312
- }
313
362
 
314
363
  // src/core/iframe-bridge.ts
315
364
  var debug = createScopedLogger("iframe-bridge");
365
+ var MAX_REFERENCES = 500;
366
+ var MAX_HREF_LENGTH = 8192;
367
+ var MAX_ASSETS = 500;
368
+ var MAX_ASSET_KEY_LENGTH = 2048;
369
+ var MAX_ASSET_FIELD_LENGTH = 512;
370
+ function parseIds(value) {
371
+ if (!Array.isArray(value)) return void 0;
372
+ return value.slice(0, MAX_REFERENCES).filter((id) => typeof id === "string" && id.length > 0);
373
+ }
374
+ function parseReferences(value) {
375
+ if (!Array.isArray(value)) return void 0;
376
+ const list = [];
377
+ for (const entry of value.slice(0, MAX_REFERENCES)) {
378
+ const id = entry?.id;
379
+ const field = entry?.field;
380
+ if (typeof id === "string" && id && typeof field === "string" && field) {
381
+ list.push({ id, field });
382
+ }
383
+ }
384
+ return list;
385
+ }
386
+ function boundedString(value, max) {
387
+ return typeof value === "string" && value && value.length <= max ? value : void 0;
388
+ }
389
+ function parseAssets(value) {
390
+ if (!Array.isArray(value)) return void 0;
391
+ const list = [];
392
+ for (const entry of value.slice(0, MAX_ASSETS)) {
393
+ if (!entry || typeof entry !== "object") continue;
394
+ const raw = entry;
395
+ const key = boundedString(raw.key, MAX_ASSET_KEY_LENGTH);
396
+ const field = boundedString(raw.field, MAX_ASSET_FIELD_LENGTH);
397
+ if (!key || !field) continue;
398
+ const entryId = boundedString(raw.entryId, MAX_ASSET_FIELD_LENGTH);
399
+ list.push(entryId ? { key, field, entryId } : { key, field });
400
+ }
401
+ return list;
402
+ }
316
403
  var EDITOR_BASE_DOMAIN = "prepr.io";
317
404
  function isAllowedEditorOrigin(origin, allowed) {
318
405
  if (allowed) {
@@ -334,6 +421,10 @@ function isAllowedEditorOrigin(origin, allowed) {
334
421
  function createIframeBridge(store, options = {}) {
335
422
  const allowedOrigins = options.allowedEditorOrigins;
336
423
  const onScrollToField = options.onScrollToField;
424
+ const onHandshake = options.onHandshake;
425
+ const onReferences = options.onReferences;
426
+ const onAssets = options.onAssets;
427
+ const onAllowNavigation = options.onAllowNavigation;
337
428
  let parentOrigin = null;
338
429
  const onKeyDown = (event) => {
339
430
  const key = event.key.toLowerCase();
@@ -354,8 +445,43 @@ function createIframeBridge(store, options = {}) {
354
445
  setTimeout(() => window.scrollTo(0, top), 1);
355
446
  }
356
447
  store?.set({ previewMode: true, editMode: data.editMode ?? true });
448
+ const itemId = typeof data.itemId === "string" && data.itemId ? data.itemId : void 0;
449
+ const referencedIds = parseReferences(data.referencedIds);
450
+ const componentIds = parseIds(data.componentIds);
451
+ const uiLocale = isLocale(data.uiLocale) ? data.uiLocale : void 0;
452
+ const navigationGuard = data.navigationGuard === true;
453
+ const assets = parseAssets(data.assets);
454
+ try {
455
+ onHandshake?.({
456
+ ...itemId && { itemId },
457
+ ...referencedIds && { referencedIds },
458
+ ...componentIds && { componentIds },
459
+ ...uiLocale && { uiLocale },
460
+ ...navigationGuard && { navigationGuard },
461
+ ...assets && { assets }
462
+ });
463
+ } catch (error) {
464
+ debug.warn("handshake handler failed", error);
465
+ }
357
466
  }
358
467
  if (!parentOrigin || evt.origin !== parentOrigin) return;
468
+ if (data?.event === "prepr:references") {
469
+ const assets = parseAssets(data.assets);
470
+ if (assets) {
471
+ try {
472
+ onAssets?.(assets);
473
+ } catch (error) {
474
+ debug.warn("assets handler failed", error);
475
+ }
476
+ }
477
+ const referencedIds = parseReferences(data.referencedIds);
478
+ if (!referencedIds) return;
479
+ try {
480
+ onReferences?.(referencedIds, parseIds(data.componentIds));
481
+ } catch (error) {
482
+ debug.warn("references handler failed", error);
483
+ }
484
+ }
359
485
  if (data?.event === "prepr:getScrollPosition") {
360
486
  const currentScrollY = window.scrollY || document.documentElement.scrollTop;
361
487
  sendPreprEvent("getScrollPosition", { value: currentScrollY });
@@ -363,12 +489,32 @@ function createIframeBridge(store, options = {}) {
363
489
  if (data?.event === "prepr:scrollToField") {
364
490
  if (typeof data.field !== "string" || !data.field) return;
365
491
  if (data.id !== void 0 && typeof data.id !== "string") return;
492
+ const block = typeof data.block === "number" && Number.isInteger(data.block) ? data.block : void 0;
493
+ const entryId = typeof data.entryId === "string" && data.entryId ? data.entryId : void 0;
494
+ const fieldById = typeof data.fieldById === "string" && data.fieldById ? data.fieldById : void 0;
366
495
  try {
367
- onScrollToField?.({ field: data.field, id: data.id });
496
+ onScrollToField?.({
497
+ field: data.field,
498
+ id: data.id,
499
+ block,
500
+ entryId,
501
+ fieldById
502
+ });
368
503
  } catch (error) {
369
504
  debug.warn("scrollToField handler failed", error);
370
505
  }
371
506
  }
507
+ if (data?.event === "prepr:allowNavigation") {
508
+ const href = data.href;
509
+ if (typeof href !== "string" || !href || href.length > MAX_HREF_LENGTH) {
510
+ return;
511
+ }
512
+ try {
513
+ onAllowNavigation?.(href);
514
+ } catch (error) {
515
+ debug.warn("allowNavigation handler failed", error);
516
+ }
517
+ }
372
518
  };
373
519
  return {
374
520
  start() {
@@ -476,29 +622,43 @@ function tagEncodedElement(element, decoded) {
476
622
  element.setAttribute("data-prepr-origin", decoded.origin);
477
623
  const { id, field, locale } = parseEditHref(decoded.href);
478
624
  setOrRemove(element, "data-prepr-id", id);
479
- setOrRemove(element, "data-prepr-field", field);
625
+ const fieldHint = element.getAttribute("data-prepr-edit-target")?.trim() || void 0;
626
+ setOrRemove(element, "data-prepr-field", field ?? fieldHint);
480
627
  setOrRemove(element, "data-prepr-locale", locale);
481
628
  }
629
+ function readEditPayload(element) {
630
+ return {
631
+ href: element.getAttribute("data-prepr-href") ?? "",
632
+ origin: element.getAttribute("data-prepr-origin") ?? "",
633
+ id: element.getAttribute("data-prepr-id") ?? void 0,
634
+ field: element.getAttribute("data-prepr-field") ?? void 0,
635
+ locale: element.getAttribute("data-prepr-locale") ?? void 0,
636
+ entryId: element.getAttribute("data-prepr-entry-id") || void 0
637
+ };
638
+ }
482
639
 
483
640
  // src/core/stega/auto-clean.ts
484
641
  var debug3 = createScopedLogger("stega:auto-clean");
642
+ var cleanedNodes = /* @__PURE__ */ new WeakMap();
485
643
  function createStegaAutoClean(options) {
486
644
  const stripText = options?.enabled ?? true;
487
645
  let observer = null;
488
646
  let processing = false;
489
- let cleaned = /* @__PURE__ */ new WeakMap();
490
647
  let pendingHidden = /* @__PURE__ */ new Set();
491
648
  let pendingDirty = /* @__PURE__ */ new Set();
492
649
  let debounceTimeout = null;
493
650
  function cleanTextNode(textNode) {
494
651
  if (isIgnoredTextNode(textNode)) return false;
495
652
  const textContent = textNode.textContent;
496
- const info = cleaned.get(textNode);
653
+ const info = cleanedNodes.get(textNode);
497
654
  const settled = stripText ? info?.cleaned : info?.original;
498
655
  if (info && textContent === settled) {
499
656
  if (!info.decoded) return false;
500
657
  const shown = resolveEditTarget(textNode);
501
- if (!shown) return false;
658
+ if (!shown) {
659
+ pendingHidden.add(textNode);
660
+ return false;
661
+ }
502
662
  pendingHidden.delete(textNode);
503
663
  if (shown.hasAttribute("data-prepr-encoded")) return false;
504
664
  tagEncodedElement(shown, info.decoded);
@@ -509,7 +669,7 @@ function createStegaAutoClean(options) {
509
669
  if (!encoded || stripped === textContent) return false;
510
670
  const decoded = decodeStega(textContent);
511
671
  if (!decoded?.href && !stripText) return false;
512
- cleaned.set(textNode, {
672
+ cleanedNodes.set(textNode, {
513
673
  original: textContent,
514
674
  cleaned: stripped,
515
675
  decoded: decoded?.href ? decoded : null
@@ -551,7 +711,7 @@ function createStegaAutoClean(options) {
551
711
  }
552
712
  if (mutation.type === "characterData" && mutation.target.nodeType === Node.TEXT_NODE) {
553
713
  const textNode = mutation.target;
554
- const info = cleaned.get(textNode);
714
+ const info = cleanedNodes.get(textNode);
555
715
  const text = textNode.textContent ?? "";
556
716
  const settled = stripText ? info?.cleaned : info?.original;
557
717
  if (text !== settled && (0, import_stega2.vercelStegaSplit)(text).encoded) {
@@ -594,7 +754,16 @@ function createStegaAutoClean(options) {
594
754
  retryPendingHidden();
595
755
  }, 50);
596
756
  }
757
+ let resizeTimeout = null;
758
+ function handleResize() {
759
+ if (pendingHidden.size === 0 || resizeTimeout) return;
760
+ resizeTimeout = setTimeout(() => {
761
+ resizeTimeout = null;
762
+ retryPendingHidden();
763
+ }, 100);
764
+ }
597
765
  function setupObserver() {
766
+ window.addEventListener("resize", handleResize, { passive: true });
598
767
  observer = new MutationObserver(handleMutations);
599
768
  observer.observe(document.body, {
600
769
  childList: true,
@@ -617,11 +786,15 @@ function createStegaAutoClean(options) {
617
786
  clearTimeout(debounceTimeout);
618
787
  debounceTimeout = null;
619
788
  }
789
+ if (resizeTimeout) {
790
+ clearTimeout(resizeTimeout);
791
+ resizeTimeout = null;
792
+ }
620
793
  if (observer) {
621
794
  observer.disconnect();
622
795
  observer = null;
796
+ window.removeEventListener("resize", handleResize);
623
797
  }
624
- cleaned = /* @__PURE__ */ new WeakMap();
625
798
  pendingHidden = /* @__PURE__ */ new Set();
626
799
  pendingDirty = /* @__PURE__ */ new Set();
627
800
  debug3.log("stega auto-clean stopped");
@@ -629,6 +802,439 @@ function createStegaAutoClean(options) {
629
802
  return { start, stop };
630
803
  }
631
804
 
805
+ // src/core/visual-editor/overlay.ts
806
+ var HOST_TAG = "prepr-visual-editor";
807
+ var SCROLL_SETTLE_MS = 120;
808
+ var LABEL_SPACE_PX = 22;
809
+ var BOX_PADDING_PX = 3;
810
+ var LABEL_MARGIN_PX = 4;
811
+ var PROBE_POINTS = [
812
+ [0.5, 0.5],
813
+ [0.15, 0.2],
814
+ [0.85, 0.2],
815
+ [0.15, 0.8],
816
+ [0.85, 0.8]
817
+ ];
818
+ function overlapsBox(area, rect) {
819
+ return area.left < rect.right + BOX_PADDING_PX && area.right > rect.left - BOX_PADDING_PX && area.top < rect.bottom + BOX_PADDING_PX && area.bottom > rect.top - BOX_PADDING_PX;
820
+ }
821
+ function overlaps(a2, b2) {
822
+ return a2.left < b2.right && b2.left < a2.right && a2.top < b2.bottom && b2.top < a2.bottom;
823
+ }
824
+ function coverOf(hit, target, x2, y2) {
825
+ let cover = hit.getBoundingClientRect();
826
+ for (let el = hit.parentElement; el && !el.contains(target) && el !== document.body; el = el.parentElement) {
827
+ const r2 = el.getBoundingClientRect();
828
+ if (x2 < r2.left || x2 >= r2.right || y2 < r2.top || y2 >= r2.bottom) break;
829
+ cover = r2;
830
+ }
831
+ return cover;
832
+ }
833
+ function mergeAreas(areas) {
834
+ const merged = areas.slice();
835
+ for (let i2 = 0; i2 < merged.length; i2++) {
836
+ for (let j2 = i2 + 1; j2 < merged.length; j2++) {
837
+ if (!overlaps(merged[i2], merged[j2])) continue;
838
+ merged[i2] = {
839
+ left: Math.min(merged[i2].left, merged[j2].left),
840
+ top: Math.min(merged[i2].top, merged[j2].top),
841
+ right: Math.max(merged[i2].right, merged[j2].right),
842
+ bottom: Math.max(merged[i2].bottom, merged[j2].bottom)
843
+ };
844
+ merged.splice(j2, 1);
845
+ j2 = i2;
846
+ }
847
+ }
848
+ return merged;
849
+ }
850
+ function findCovers(target, rect) {
851
+ const width = window.innerWidth;
852
+ const height = window.innerHeight;
853
+ const covers = [];
854
+ const seen = /* @__PURE__ */ new Set();
855
+ let probed = false;
856
+ let reached = false;
857
+ for (const [fx, fy] of PROBE_POINTS) {
858
+ const x2 = rect.left + rect.width * fx;
859
+ const y2 = rect.top + rect.height * fy;
860
+ if (x2 < 0 || y2 < 0 || x2 >= width || y2 >= height) continue;
861
+ probed = true;
862
+ const hit = document.elementFromPoint(x2, y2);
863
+ if (!hit || hit === target || target.contains(hit)) {
864
+ reached = true;
865
+ continue;
866
+ }
867
+ if (seen.has(hit)) continue;
868
+ seen.add(hit);
869
+ if (covers.some(
870
+ (c2) => x2 >= c2.left && x2 < c2.right && y2 >= c2.top && y2 < c2.bottom
871
+ )) {
872
+ continue;
873
+ }
874
+ covers.push(coverOf(hit, target, x2, y2));
875
+ }
876
+ if (!probed) return [];
877
+ return reached ? mergeAreas(covers) : null;
878
+ }
879
+ function clipPath(x2, y2, covers) {
880
+ const far = 1e5;
881
+ const points = [
882
+ `${-far}px ${-far}px`,
883
+ `${far}px ${-far}px`,
884
+ `${far}px ${far}px`,
885
+ `${-far}px ${far}px`,
886
+ `${-far}px ${-far}px`
887
+ ];
888
+ for (const c2 of covers) {
889
+ const l2 = c2.left - x2;
890
+ const t3 = c2.top - y2;
891
+ const r2 = c2.right - x2;
892
+ const b2 = c2.bottom - y2;
893
+ points.push(
894
+ `${l2}px ${t3}px`,
895
+ `${r2}px ${t3}px`,
896
+ `${r2}px ${b2}px`,
897
+ `${l2}px ${b2}px`,
898
+ `${l2}px ${t3}px`,
899
+ `${-far}px ${-far}px`
900
+ );
901
+ }
902
+ return `polygon(evenodd, ${points.join(", ")})`;
903
+ }
904
+ var STYLES = `
905
+ :host {
906
+ all: initial;
907
+ position: fixed;
908
+ inset: 0;
909
+ pointer-events: none;
910
+ z-index: 2147483646;
911
+ contain: strict;
912
+ }
913
+ .box {
914
+ position: absolute;
915
+ top: 0;
916
+ left: 0;
917
+ box-sizing: border-box;
918
+ border-radius: 6px;
919
+ opacity: 0;
920
+ will-change: transform, width, height;
921
+ transition:
922
+ transform 180ms cubic-bezier(0.2, 0.8, 0.2, 1),
923
+ width 180ms cubic-bezier(0.2, 0.8, 0.2, 1),
924
+ height 180ms cubic-bezier(0.2, 0.8, 0.2, 1),
925
+ opacity 140ms ease;
926
+ }
927
+ .box[data-visible] { opacity: 1; }
928
+ .box[data-instant], :host([data-scrolling]) .box {
929
+ transition: opacity 140ms ease;
930
+ }
931
+ .hover {
932
+ border: 1.5px solid rgba(79, 70, 229, 0.9);
933
+ background: rgba(79, 70, 229, 0.06);
934
+ }
935
+ .selected {
936
+ border: 2px solid #4f46e5;
937
+ box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.18);
938
+ }
939
+ .label {
940
+ position: absolute;
941
+ left: -2px;
942
+ bottom: 100%;
943
+ margin-bottom: 4px;
944
+ padding: 3px 7px;
945
+ border-radius: 5px;
946
+ background: #4f46e5;
947
+ color: #fff;
948
+ font: 500 11px/1.3 ui-sans-serif, system-ui, -apple-system, 'Segoe UI', sans-serif;
949
+ letter-spacing: 0.01em;
950
+ white-space: nowrap;
951
+ display: flex;
952
+ max-width: 240px;
953
+ box-shadow: 0 1px 3px rgba(15, 23, 42, 0.25);
954
+ }
955
+ .text {
956
+ min-width: 0;
957
+ overflow: hidden;
958
+ text-overflow: ellipsis;
959
+ }
960
+ .hover .label { background: rgba(79, 70, 229, 0.92); }
961
+ /* Content of another item than the one open in the editor: still clickable,
962
+ but visibly not part of the item being edited. */
963
+ .hover[data-item-kind='other'] {
964
+ border: 1.5px dashed #a5b4fc;
965
+ background: rgba(100, 116, 139, 0.05);
966
+ }
967
+ .hover[data-item-kind='other'] .label { background: #64748b; }
968
+ .hover[data-item-kind='referenced'] {
969
+ border: 1.5px solid #a5b4fc;
970
+ background: rgba(79, 70, 229, 0.03);
971
+ }
972
+ .hover[data-item-kind='referenced'] .label { background: #818cf8; }
973
+ .box[data-label-covered] .label { visibility: hidden; }
974
+ .box[data-label-inside] .label {
975
+ bottom: auto;
976
+ top: 2px;
977
+ left: 2px;
978
+ margin: 0;
979
+ }
980
+ /* A clickable hover label (edit mode on the live site). Only while shown, so
981
+ a fading box never leaves an invisible click target behind. */
982
+ :host([data-label-action]) .hover[data-visible] .label {
983
+ pointer-events: auto;
984
+ cursor: pointer;
985
+ }
986
+ :host([data-label-action]) .hover .label::after {
987
+ content: '\\2197';
988
+ margin-left: 5px;
989
+ }
990
+ :host([data-label-action]) .hover .label:hover { background: #4338ca; }
991
+ /* Bridges the gap between the label and its element, so the pointer can
992
+ travel from one to the other without the hover ending on the way. */
993
+ :host([data-label-action]) .hover .label::before {
994
+ content: '';
995
+ position: absolute;
996
+ left: 0;
997
+ right: 0;
998
+ top: 100%;
999
+ height: ${LABEL_MARGIN_PX + BOX_PADDING_PX + 2}px;
1000
+ }
1001
+ @media (prefers-reduced-motion: reduce) {
1002
+ .box { transition: opacity 80ms linear; }
1003
+ }
1004
+ `;
1005
+ var VisualEditorOverlay = class {
1006
+ constructor(options = {}) {
1007
+ this.host = null;
1008
+ this.hoverBox = null;
1009
+ this.selectedBox = null;
1010
+ this.frame = null;
1011
+ this.scrollTimeout = null;
1012
+ this.resizeObserver = null;
1013
+ this.onLabelClick = options.onLabelClick;
1014
+ }
1015
+ mount() {
1016
+ if (this.host) return;
1017
+ const host = document.createElement(HOST_TAG);
1018
+ const shadow = host.attachShadow({ mode: "open" });
1019
+ const style = document.createElement("style");
1020
+ style.textContent = STYLES;
1021
+ shadow.appendChild(style);
1022
+ this.hoverBox = this.createBox(shadow, "hover");
1023
+ this.selectedBox = this.createBox(shadow, "selected");
1024
+ const onLabelClick = this.onLabelClick;
1025
+ if (onLabelClick) {
1026
+ host.setAttribute("data-label-action", "");
1027
+ const hoverBox = this.hoverBox;
1028
+ hoverBox.label.addEventListener("click", () => {
1029
+ if (hoverBox.target) onLabelClick(hoverBox.target);
1030
+ });
1031
+ }
1032
+ document.documentElement.appendChild(host);
1033
+ this.host = host;
1034
+ if (typeof ResizeObserver !== "undefined") {
1035
+ this.resizeObserver = new ResizeObserver(() => this.schedule());
1036
+ }
1037
+ }
1038
+ unmount() {
1039
+ if (this.frame !== null) cancelAnimationFrame(this.frame);
1040
+ if (this.scrollTimeout) clearTimeout(this.scrollTimeout);
1041
+ this.frame = null;
1042
+ this.scrollTimeout = null;
1043
+ this.resizeObserver?.disconnect();
1044
+ this.resizeObserver = null;
1045
+ this.host?.remove();
1046
+ this.host = null;
1047
+ this.hoverBox = null;
1048
+ this.selectedBox = null;
1049
+ }
1050
+ /**
1051
+ * Whether a pointer event target is this chrome: events from inside the
1052
+ * shadow root reach the page retargeted to its host.
1053
+ */
1054
+ owns(node) {
1055
+ return node !== null && node === this.host;
1056
+ }
1057
+ getHoverTarget() {
1058
+ return this.hoverBox?.target ?? null;
1059
+ }
1060
+ getSelectedTarget() {
1061
+ return this.selectedBox?.target ?? null;
1062
+ }
1063
+ setHover(target, label, options = {}) {
1064
+ if (target) {
1065
+ this.hoverBox?.root.setAttribute(
1066
+ "data-item-kind",
1067
+ options.kind ?? "current"
1068
+ );
1069
+ }
1070
+ this.retarget(this.hoverBox, target, label);
1071
+ }
1072
+ setSelected(target, label) {
1073
+ this.retarget(this.selectedBox, target, label);
1074
+ }
1075
+ /** Call on every scroll; positions follow in the next frame, untransitioned. */
1076
+ onScroll() {
1077
+ if (!this.host) return;
1078
+ this.host.setAttribute("data-scrolling", "");
1079
+ if (this.scrollTimeout) clearTimeout(this.scrollTimeout);
1080
+ this.scrollTimeout = setTimeout(() => {
1081
+ this.host?.removeAttribute("data-scrolling");
1082
+ this.scrollTimeout = null;
1083
+ }, SCROLL_SETTLE_MS);
1084
+ this.schedule();
1085
+ }
1086
+ /** Re-measure both boxes in the next animation frame. */
1087
+ schedule() {
1088
+ if (this.frame !== null || !this.host) return;
1089
+ this.frame = requestAnimationFrame(() => {
1090
+ this.frame = null;
1091
+ this.render();
1092
+ });
1093
+ }
1094
+ createBox(shadow, kind) {
1095
+ const root = document.createElement("div");
1096
+ root.className = `box ${kind}`;
1097
+ const label = document.createElement("div");
1098
+ label.className = "label";
1099
+ const text = document.createElement("span");
1100
+ text.className = "text";
1101
+ label.appendChild(text);
1102
+ root.appendChild(label);
1103
+ shadow.appendChild(root);
1104
+ return { root, label, text, target: null };
1105
+ }
1106
+ retarget(box, target, label) {
1107
+ if (!box || box.target === target) return;
1108
+ const previous = box.target;
1109
+ if (previous) this.resizeObserver?.unobserve(previous);
1110
+ box.target = target;
1111
+ if (target) {
1112
+ this.resizeObserver?.observe(target);
1113
+ box.text.textContent = label;
1114
+ if (!box.root.hasAttribute("data-visible")) {
1115
+ box.root.setAttribute("data-instant", "");
1116
+ }
1117
+ }
1118
+ this.schedule();
1119
+ }
1120
+ render() {
1121
+ const hover = this.hoverBox ? this.measure(this.hoverBox) : null;
1122
+ const selected = this.selectedBox ? this.measure(this.selectedBox) : null;
1123
+ if (this.hoverBox) this.paint(this.hoverBox, hover, selected);
1124
+ if (this.selectedBox) this.paint(this.selectedBox, selected, hover);
1125
+ }
1126
+ measure(box) {
1127
+ const target = box.target;
1128
+ if (!target) return null;
1129
+ if (!target.isConnected) {
1130
+ this.resizeObserver?.unobserve(target);
1131
+ box.target = null;
1132
+ return null;
1133
+ }
1134
+ const rect = target.getBoundingClientRect();
1135
+ if (rect.width === 0 && rect.height === 0) return null;
1136
+ const covers = findCovers(target, rect);
1137
+ if (!covers) return null;
1138
+ return {
1139
+ rect,
1140
+ covers,
1141
+ labelWidth: covers.length ? box.label.offsetWidth : 0,
1142
+ labelHeight: covers.length ? box.label.offsetHeight : 0
1143
+ };
1144
+ }
1145
+ paint(box, measurement, other = null) {
1146
+ const root = box.root;
1147
+ if (!measurement) {
1148
+ root.removeAttribute("data-visible");
1149
+ return;
1150
+ }
1151
+ const { rect, covers } = measurement;
1152
+ const x2 = rect.left - BOX_PADDING_PX;
1153
+ const y2 = rect.top - BOX_PADDING_PX;
1154
+ const labelAbove = {
1155
+ left: x2 - 2,
1156
+ top: y2 - LABEL_SPACE_PX,
1157
+ right: x2 - 2 + (measurement.labelWidth || Math.min(240, rect.width)),
1158
+ bottom: y2
1159
+ };
1160
+ const labelInside = y2 < LABEL_SPACE_PX || other !== null && other.rect !== rect && overlapsBox(labelAbove, other.rect);
1161
+ root.style.transform = `translate3d(${x2}px, ${y2}px, 0)`;
1162
+ root.style.width = `${rect.width + BOX_PADDING_PX * 2}px`;
1163
+ root.style.height = `${rect.height + BOX_PADDING_PX * 2}px`;
1164
+ root.toggleAttribute("data-label-inside", labelInside);
1165
+ root.style.clipPath = covers.length ? clipPath(x2, y2, covers) : "";
1166
+ const labelLeft = labelInside ? x2 + 2 : x2 - 2;
1167
+ const labelTop = labelInside ? y2 + 2 : y2 - LABEL_MARGIN_PX - measurement.labelHeight;
1168
+ const label = {
1169
+ left: labelLeft,
1170
+ top: labelTop,
1171
+ right: labelLeft + measurement.labelWidth,
1172
+ bottom: labelTop + measurement.labelHeight
1173
+ };
1174
+ root.toggleAttribute(
1175
+ "data-label-covered",
1176
+ covers.some((c2) => overlaps(c2, label))
1177
+ );
1178
+ if (root.hasAttribute("data-instant")) {
1179
+ root.setAttribute("data-visible", "");
1180
+ requestAnimationFrame(() => root.removeAttribute("data-instant"));
1181
+ return;
1182
+ }
1183
+ root.setAttribute("data-visible", "");
1184
+ }
1185
+ };
1186
+
1187
+ // src/core/visual-editor/field-path.ts
1188
+ var INDEX_SEGMENT = /^\d+$/;
1189
+ var WORD_SEPARATORS = /[_-]+/g;
1190
+ function normalizeFieldPath(path) {
1191
+ return path.split(".").map(
1192
+ (segment) => INDEX_SEGMENT.test(segment) ? String(Number.parseInt(segment, 10)) : segment
1193
+ ).join(".");
1194
+ }
1195
+ var GENERIC_LEAVES = /* @__PURE__ */ new Set(["value", "text", "body", "content", "label"]);
1196
+ function humanize(name) {
1197
+ const words = name.replace(WORD_SEPARATORS, " ").trim();
1198
+ return words.charAt(0).toUpperCase() + words.slice(1);
1199
+ }
1200
+ function fieldLabel(path, locale = "en") {
1201
+ if (!path) return t("visualEditor.edit", locale);
1202
+ const segments = path.split(".").filter((s2) => s2 && s2 !== "items" && !INDEX_SEGMENT.test(s2));
1203
+ const name = segments[segments.length - 1];
1204
+ if (!name) return t("visualEditor.edit", locale);
1205
+ const parent = segments[segments.length - 2];
1206
+ if (parent && GENERIC_LEAVES.has(name)) {
1207
+ return `${humanize(parent)} \u203A ${humanize(name)}`;
1208
+ }
1209
+ return humanize(name);
1210
+ }
1211
+ function findFieldElement(lookup) {
1212
+ if (!lookup.field) return null;
1213
+ const candidates = document.querySelectorAll(
1214
+ "[data-prepr-encoded]"
1215
+ );
1216
+ if (lookup.entryId) {
1217
+ for (const candidate of candidates) {
1218
+ if (candidate.getAttribute("data-prepr-entry-id") === lookup.entryId) {
1219
+ return candidate;
1220
+ }
1221
+ }
1222
+ }
1223
+ for (const path of [lookup.field, lookup.fieldById]) {
1224
+ if (!path) continue;
1225
+ const wanted = normalizeFieldPath(path);
1226
+ for (const candidate of candidates) {
1227
+ const field = candidate.getAttribute("data-prepr-field");
1228
+ if (!field || normalizeFieldPath(field) !== wanted) continue;
1229
+ if (lookup.id && candidate.getAttribute("data-prepr-id") !== lookup.id) {
1230
+ continue;
1231
+ }
1232
+ return candidate;
1233
+ }
1234
+ }
1235
+ return null;
1236
+ }
1237
+
632
1238
  // src/core/stega/elements.ts
633
1239
  var debug4 = createScopedLogger("stega:elements");
634
1240
  var StegaElements = class {
@@ -718,235 +1324,22 @@ var StegaElements = class {
718
1324
  attributeFilter: ["class", "style", "hidden", "open", "aria-expanded"]
719
1325
  });
720
1326
  }
721
- /** Drops the active class but keeps the data attributes, unlike cleanup(). */
722
- cleanupVisuals() {
723
- document.querySelectorAll(".prepr-overlay-active").forEach((element) => element.classList.remove("prepr-overlay-active"));
724
- }
725
- cleanup() {
1327
+ /**
1328
+ * Stops watching for new content. Tags stay on their elements: the page's
1329
+ * stega characters are stripped once they are read, so a tag removed here
1330
+ * could never be rebuilt when edit mode is turned back on.
1331
+ */
1332
+ disconnect() {
726
1333
  if (this.observer) {
727
1334
  this.observer.disconnect();
728
1335
  this.observer = null;
729
1336
  }
730
- document.querySelectorAll("[data-prepr-encoded]").forEach((element) => {
731
- element.removeAttribute("data-prepr-encoded");
732
- element.removeAttribute("data-prepr-href");
733
- element.removeAttribute("data-prepr-origin");
734
- element.removeAttribute("data-prepr-id");
735
- element.removeAttribute("data-prepr-field");
736
- element.removeAttribute("data-prepr-locale");
737
- element.classList.remove("prepr-overlay-active");
738
- });
739
1337
  this.elements = void 0;
740
1338
  }
741
1339
  };
742
1340
 
743
- // src/core/stega/overlay.ts
744
- var debug5 = createScopedLogger("stega:overlay");
745
- var StegaOverlay = class {
746
- constructor(onEdit) {
747
- this.overlay = null;
748
- this.tooltip = null;
749
- this.hideTimeout = null;
750
- this.currentElement = null;
751
- this.onEdit = onEdit;
752
- }
753
- create() {
754
- const overlay = document.createElement("div");
755
- overlay.className = "prepr-overlay";
756
- overlay.style.display = "none";
757
- const tooltip = document.createElement("div");
758
- tooltip.className = "prepr-tooltip";
759
- tooltip.style.display = "none";
760
- document.body.appendChild(overlay);
761
- document.body.appendChild(tooltip);
762
- this.overlay = overlay;
763
- this.tooltip = tooltip;
764
- return { overlay, tooltip };
765
- }
766
- getTooltip() {
767
- return this.tooltip;
768
- }
769
- hasCurrentElement() {
770
- return this.currentElement !== null;
771
- }
772
- clearHideTimeout() {
773
- if (this.hideTimeout) {
774
- clearTimeout(this.hideTimeout);
775
- this.hideTimeout = null;
776
- }
777
- }
778
- show(element) {
779
- if (!this.overlay || !this.tooltip) return;
780
- this.clearHideTimeout();
781
- if (this.currentElement && this.currentElement !== element) {
782
- this.currentElement.classList.remove("prepr-overlay-active");
783
- }
784
- const rect = element.getBoundingClientRect();
785
- const href = element.getAttribute("data-prepr-href");
786
- const origin = element.getAttribute("data-prepr-origin");
787
- const id = element.getAttribute("data-prepr-id") ?? void 0;
788
- const field = element.getAttribute("data-prepr-field") ?? void 0;
789
- const locale = element.getAttribute("data-prepr-locale") ?? void 0;
790
- debug5.log("showing overlay", { href, origin });
791
- const overlay = this.overlay;
792
- overlay.style.display = "block";
793
- overlay.style.top = `${rect.top + window.scrollY - 2}px`;
794
- overlay.style.left = `${rect.left + window.scrollX - 4}px`;
795
- overlay.style.width = `${rect.width + 8}px`;
796
- overlay.style.height = `${rect.height + 4}px`;
797
- const tooltip = this.tooltip;
798
- if (href && origin) {
799
- const MIN_WIDTH_FOR_TEXT = 80;
800
- const isCompact = rect.width < MIN_WIDTH_FOR_TEXT;
801
- tooltip.textContent = isCompact ? "\u2197" : `${origin} \u2197`;
802
- tooltip.style.display = "block";
803
- tooltip.style.minWidth = isCompact ? "auto" : "80px";
804
- requestAnimationFrame(() => {
805
- let top = rect.top + window.scrollY - tooltip.clientHeight - 2;
806
- let left = rect.right + 4 - tooltip.clientWidth;
807
- const minTop = window.scrollY + 4;
808
- const maxTop = window.scrollY + window.innerHeight - tooltip.clientHeight - 4;
809
- const minLeft = window.scrollX + 4;
810
- const maxLeft = window.scrollX + window.innerWidth - tooltip.clientWidth - 4;
811
- const below = top < minTop;
812
- if (below) {
813
- top = rect.bottom + window.scrollY + 2;
814
- }
815
- top = Math.max(minTop, Math.min(top, maxTop));
816
- left = Math.max(minLeft, Math.min(left, maxLeft));
817
- tooltip.dataset.preprPlacement = below ? "below" : "above";
818
- tooltip.style.top = `${top}px`;
819
- tooltip.style.left = `${left}px`;
820
- });
821
- tooltip.onclick = () => {
822
- this.onEdit({ href, origin, id, field, locale });
823
- };
824
- }
825
- this.currentElement = element;
826
- element.classList.add("prepr-overlay-active");
827
- }
828
- hideImmediate() {
829
- this.clearHideTimeout();
830
- if (this.overlay) this.overlay.style.display = "none";
831
- if (this.tooltip) this.tooltip.style.display = "none";
832
- if (this.currentElement) {
833
- this.currentElement.classList.remove("prepr-overlay-active");
834
- this.currentElement = null;
835
- }
836
- }
837
- hide() {
838
- if (!this.overlay || !this.tooltip) return;
839
- this.clearHideTimeout();
840
- this.hideTimeout = setTimeout(() => this.hideImmediate(), 100);
841
- }
842
- cleanup() {
843
- this.clearHideTimeout();
844
- if (this.overlay) {
845
- this.overlay.style.display = "none";
846
- this.overlay.parentNode?.removeChild(this.overlay);
847
- this.overlay = null;
848
- }
849
- if (this.tooltip) {
850
- this.tooltip.style.display = "none";
851
- this.tooltip.parentNode?.removeChild(this.tooltip);
852
- this.tooltip = null;
853
- }
854
- if (this.currentElement) {
855
- this.currentElement.classList.remove("prepr-overlay-active");
856
- this.currentElement = null;
857
- }
858
- }
859
- };
860
-
861
- // src/core/stega/proximity.ts
862
- var debug6 = createScopedLogger("stega:proximity");
863
- var StegaProximity = class {
864
- constructor() {
865
- this.highlighted = /* @__PURE__ */ new Set();
866
- this.visible = /* @__PURE__ */ new Set();
867
- this.observer = null;
868
- this.getEncodedElements = createElementCache(
869
- "[data-prepr-encoded]",
870
- 200
871
- );
872
- }
873
- /** Call after the encoded element set changes — rebuilds the observer. */
874
- refreshObserving() {
875
- try {
876
- if (typeof IntersectionObserver === "undefined") return;
877
- if (this.observer) {
878
- this.observer.disconnect();
879
- this.observer = null;
880
- }
881
- this.visible = /* @__PURE__ */ new Set();
882
- this.observer = new IntersectionObserver(
883
- (entries) => {
884
- entries.forEach((entry) => {
885
- const el = entry.target;
886
- if (entry.isIntersecting) {
887
- this.visible.add(el);
888
- } else {
889
- this.visible.delete(el);
890
- }
891
- });
892
- },
893
- { root: null, rootMargin: "0px", threshold: 0 }
894
- );
895
- const nodes = this.getEncodedElements();
896
- nodes.forEach((el) => this.observer.observe(el));
897
- debug6.log("observing", nodes.length, "encoded elements");
898
- } catch (error) {
899
- debug6.log("error setting up IntersectionObserver", error);
900
- }
901
- }
902
- stopObserving() {
903
- if (this.observer) {
904
- this.observer.disconnect();
905
- this.observer = null;
906
- this.visible.clear();
907
- }
908
- }
909
- updateElementGradients(cursorX, cursorY) {
910
- const candidates = this.visible.size > 0 ? Array.from(this.visible) : Array.from(this.getEncodedElements());
911
- const newHighlighted = /* @__PURE__ */ new Set();
912
- candidates.forEach((element) => {
913
- const rect = element.getBoundingClientRect();
914
- const distance = Math.min(
915
- Math.abs(cursorX - rect.left),
916
- Math.abs(cursorX - rect.right),
917
- Math.abs(cursorY - rect.top),
918
- Math.abs(cursorY - rect.bottom)
919
- );
920
- if (distance < 150) {
921
- const relativeX = cursorX - rect.left;
922
- const relativeY = cursorY - rect.top;
923
- element.style.setProperty("--cursor-x", `${relativeX}px`);
924
- element.style.setProperty("--cursor-y", `${relativeY}px`);
925
- const baseGradientSize = Math.max(
926
- 150,
927
- Math.max(rect.width, rect.height) * 1.1
928
- );
929
- const distanceScale = Math.max(0, (400 - distance) / 400);
930
- const gradientSize = baseGradientSize * distanceScale;
931
- element.style.setProperty("--gradient-size", `${gradientSize}px`);
932
- element.classList.add("prepr-proximity-highlight");
933
- newHighlighted.add(element);
934
- } else {
935
- element.classList.remove("prepr-proximity-highlight");
936
- }
937
- });
938
- this.highlighted = newHighlighted;
939
- }
940
- clearAllHighlights() {
941
- this.highlighted.forEach(
942
- (element) => element.classList.remove("prepr-proximity-highlight")
943
- );
944
- this.highlighted.clear();
945
- }
946
- };
947
-
948
1341
  // src/core/stega/stega.generated.ts
949
- var STEGA_STYLES = '[data-prepr-encoded]{position:relative}.prepr-overlay{pointer-events:none;z-index:10000;border:2px solid #4f46e5;border-radius:4px 0 4px 4px;transition:all .2s ease-in-out;position:absolute}.prepr-tooltip{color:#fff;white-space:nowrap;z-index:10001;text-align:center;pointer-events:auto;cursor:pointer;background-color:#4f46e5;border-radius:4px 4px 0 0;min-width:80px;padding:4px 8px;font-size:12px;line-height:1;transition:opacity .2s ease-in-out;position:absolute}.prepr-tooltip[data-prepr-placement=below]{border-radius:0 0 4px 4px}.prepr-tooltip:hover{background-color:#4338ca}.prepr-proximity-highlight{z-index:1;position:relative}.prepr-proximity-highlight,.prepr-proximity-highlight *{overflow:visible!important}.prepr-proximity-highlight:before{content:"";pointer-events:none;background:radial-gradient(circle var(--gradient-size) at var(--cursor-x) var(--cursor-y), #4f46e526 0%, #2563eb00 70%);z-index:9999;border:2px solid #4f46e526;border-radius:4px;transition:all .2s;position:absolute;top:-2px;bottom:-2px;left:-4px;right:-4px;overflow:visible}';
1342
+ var STEGA_STYLES = '@property --prepr-presence{syntax:"<number>";inherits:true;initial-value:1}[data-prepr-encoded]{outline:1px dashed rgba(79,70,229,calc(.3 * var(--prepr-presence,1)));outline-offset:2px}';
950
1343
 
951
1344
  // src/core/stega/styles.ts
952
1345
  var STEGA_STYLE_MARKER = "data-prepr-stega";
@@ -966,46 +1359,80 @@ function removeStegaStyles() {
966
1359
  }
967
1360
 
968
1361
  // src/core/stega/scan.ts
969
- var debug7 = createScopedLogger("stega:scan");
1362
+ var debug5 = createScopedLogger("stega:scan");
1363
+ var ENCODED_SELECTOR = "[data-prepr-encoded]";
1364
+ var PRESENCE_FADE_MS = 400;
970
1365
  var EDITOR_MODE_STYLES = "[data-prepr-encoded]{cursor:pointer}";
1366
+ function fadeInPresence() {
1367
+ const root = document.documentElement;
1368
+ if (typeof root.animate !== "function") return;
1369
+ if (window.matchMedia?.("(prefers-reduced-motion: reduce)").matches) return;
1370
+ root.animate(
1371
+ { "--prepr-presence": ["0", "1"] },
1372
+ { duration: PRESENCE_FADE_MS, easing: "ease-out" }
1373
+ );
1374
+ }
971
1375
  function createStegaController(opts) {
972
1376
  const tooltipEnabled = opts.tooltip ?? true;
973
- const overlay = new StegaOverlay(opts.onEdit);
974
- const proximity = new StegaProximity();
1377
+ const locale = opts.locale ?? "en";
975
1378
  const elements = new StegaElements();
1379
+ const overlay = new VisualEditorOverlay({
1380
+ onLabelClick: (target) => opts.onEdit(readEditPayload(target))
1381
+ });
976
1382
  let initialized = false;
977
- let throttledMouseMove = null;
978
- const handleTooltipMouseEnter = () => {
979
- overlay.clearHideTimeout();
1383
+ let pointerFrame = null;
1384
+ let pointerTarget = null;
1385
+ let pointerX = 0;
1386
+ let pointerY = 0;
1387
+ let hitTestPending = false;
1388
+ const updateHover = () => {
1389
+ pointerFrame = null;
1390
+ if (hitTestPending) {
1391
+ hitTestPending = false;
1392
+ pointerTarget = document.elementFromPoint(pointerX, pointerY);
1393
+ }
1394
+ if (overlay.owns(pointerTarget)) return;
1395
+ const encoded = pointerTarget instanceof Element ? pointerTarget.closest(ENCODED_SELECTOR) : null;
1396
+ overlay.setHover(
1397
+ encoded,
1398
+ encoded ? fieldLabel(encoded.getAttribute("data-prepr-field"), locale) : ""
1399
+ );
980
1400
  };
981
- const handleTooltipMouseLeave = () => {
982
- if (!overlay.hasCurrentElement()) {
983
- overlay.hide();
1401
+ const scheduleHover = () => {
1402
+ if (pointerFrame === null) {
1403
+ pointerFrame = requestAnimationFrame(updateHover);
984
1404
  }
985
1405
  };
1406
+ const handlePointer = (e2) => {
1407
+ pointerTarget = e2.target;
1408
+ pointerX = e2.clientX;
1409
+ pointerY = e2.clientY;
1410
+ hitTestPending = false;
1411
+ scheduleHover();
1412
+ };
1413
+ const handlePointerLeave = () => {
1414
+ pointerTarget = null;
1415
+ hitTestPending = false;
1416
+ overlay.setHover(null, "");
1417
+ };
986
1418
  const handleScroll = () => {
987
- overlay.hideImmediate();
988
- proximity.clearAllHighlights();
1419
+ overlay.onScroll();
1420
+ if (pointerTarget === null) return;
1421
+ hitTestPending = true;
1422
+ scheduleHover();
989
1423
  };
1424
+ const handleResize = () => overlay.schedule();
990
1425
  const handleClick = (e2) => {
991
1426
  const target = e2.target;
992
- const encoded = target?.closest(
993
- "[data-prepr-encoded]"
994
- );
1427
+ const encoded = target?.closest(ENCODED_SELECTOR);
995
1428
  if (!encoded) return;
996
1429
  e2.preventDefault();
997
1430
  e2.stopPropagation();
998
- opts.onEdit({
999
- href: encoded.getAttribute("data-prepr-href") ?? "",
1000
- origin: encoded.getAttribute("data-prepr-origin") ?? "",
1001
- id: encoded.getAttribute("data-prepr-id") ?? void 0,
1002
- field: encoded.getAttribute("data-prepr-field") ?? void 0,
1003
- locale: encoded.getAttribute("data-prepr-locale") ?? void 0
1004
- });
1431
+ opts.onEdit(readEditPayload(encoded));
1005
1432
  };
1006
1433
  const start = () => {
1007
1434
  if (initialized) {
1008
- debug7.log("already initialized, skipping setup");
1435
+ debug5.log("already initialized, skipping setup");
1009
1436
  return;
1010
1437
  }
1011
1438
  if (!tooltipEnabled) {
@@ -1015,73 +1442,64 @@ function createStegaController(opts) {
1015
1442
  });
1016
1443
  document.addEventListener("click", handleClick, { capture: true });
1017
1444
  initialized = true;
1018
- debug7.log("stega controller started (editor mode)");
1445
+ debug5.log("stega controller started (headless)");
1019
1446
  return;
1020
1447
  }
1021
1448
  injectStegaStyles();
1022
- const { tooltip } = overlay.create();
1023
- tooltip.addEventListener("mouseenter", handleTooltipMouseEnter);
1024
- tooltip.addEventListener("mouseleave", handleTooltipMouseLeave);
1449
+ fadeInPresence();
1450
+ overlay.mount();
1025
1451
  elements.scanDocument(true);
1026
- proximity.refreshObserving();
1027
- elements.setupMutationObserver(() => proximity.refreshObserving());
1028
- throttledMouseMove = throttle((e2) => {
1029
- const mouseEvent = e2;
1030
- const target = mouseEvent.target;
1031
- if (!target) return;
1032
- if (target.closest(".prepr-tooltip")) return;
1033
- proximity.updateElementGradients(mouseEvent.clientX, mouseEvent.clientY);
1034
- const encoded = target.closest("[data-prepr-encoded]");
1035
- if (encoded) {
1036
- overlay.show(encoded);
1037
- } else {
1038
- overlay.hide();
1039
- }
1040
- }, 16);
1041
- document.addEventListener("mousemove", throttledMouseMove, {
1042
- passive: true
1452
+ elements.setupMutationObserver(() => {
1453
+ if (pointerTarget === null) return;
1454
+ hitTestPending = true;
1455
+ scheduleHover();
1043
1456
  });
1457
+ document.addEventListener("pointermove", handlePointer, { passive: true });
1458
+ document.addEventListener("pointerdown", handlePointer, { passive: true });
1459
+ document.documentElement.addEventListener(
1460
+ "pointerleave",
1461
+ handlePointerLeave
1462
+ );
1044
1463
  window.addEventListener("scroll", handleScroll, {
1045
1464
  capture: true,
1046
1465
  passive: true
1047
1466
  });
1467
+ window.addEventListener("resize", handleResize, { passive: true });
1048
1468
  initialized = true;
1049
- debug7.log("stega controller started");
1469
+ debug5.log("stega controller started");
1050
1470
  };
1051
1471
  const stop = () => {
1052
1472
  if (!initialized) return;
1473
+ initialized = false;
1053
1474
  if (!tooltipEnabled) {
1054
1475
  document.removeEventListener("click", handleClick, { capture: true });
1055
- elements.cleanup();
1476
+ elements.disconnect();
1056
1477
  removeStegaStyles();
1057
- initialized = false;
1058
- debug7.log("stega controller stopped (editor mode)");
1478
+ debug5.log("stega controller stopped (headless)");
1059
1479
  return;
1060
1480
  }
1061
- if (throttledMouseMove) {
1062
- document.removeEventListener("mousemove", throttledMouseMove);
1063
- throttledMouseMove.cancel();
1064
- throttledMouseMove = null;
1065
- }
1481
+ if (pointerFrame !== null) cancelAnimationFrame(pointerFrame);
1482
+ pointerFrame = null;
1483
+ pointerTarget = null;
1484
+ hitTestPending = false;
1485
+ document.removeEventListener("pointermove", handlePointer);
1486
+ document.removeEventListener("pointerdown", handlePointer);
1487
+ document.documentElement.removeEventListener(
1488
+ "pointerleave",
1489
+ handlePointerLeave
1490
+ );
1066
1491
  window.removeEventListener("scroll", handleScroll, { capture: true });
1067
- const tooltip = overlay.getTooltip();
1068
- if (tooltip) {
1069
- tooltip.removeEventListener("mouseenter", handleTooltipMouseEnter);
1070
- tooltip.removeEventListener("mouseleave", handleTooltipMouseLeave);
1071
- }
1072
- overlay.cleanup();
1073
- proximity.clearAllHighlights();
1074
- proximity.stopObserving();
1075
- elements.cleanup();
1492
+ window.removeEventListener("resize", handleResize);
1493
+ overlay.unmount();
1494
+ elements.disconnect();
1076
1495
  removeStegaStyles();
1077
- initialized = false;
1078
- debug7.log("stega controller stopped");
1496
+ debug5.log("stega controller stopped");
1079
1497
  };
1080
1498
  return { start, stop };
1081
1499
  }
1082
1500
 
1083
1501
  // src/core/stega/scroll-to-field.ts
1084
- var debug8 = createScopedLogger("stega:scroll");
1502
+ var debug6 = createScopedLogger("stega:scroll");
1085
1503
  var FLASH_DURATION_MS = 1200;
1086
1504
  var flashTimeout = null;
1087
1505
  function scrollToField(request) {
@@ -1098,7 +1516,7 @@ function scrollToField(request) {
1098
1516
  break;
1099
1517
  }
1100
1518
  if (!target) {
1101
- debug8.log("no element found for field", field);
1519
+ debug6.log("no element found for field", field);
1102
1520
  return false;
1103
1521
  }
1104
1522
  target.scrollIntoView({ behavior: "smooth", block: "center" });
@@ -1528,7 +1946,7 @@ var CLOSE_ICON_SVG = `<svg width="10" height="10" viewBox="0 0 10 10" fill="none
1528
1946
  </svg>`;
1529
1947
 
1530
1948
  // src/core/ui/toolbar.generated.ts
1531
- var TOOLBAR_CSS = ":host{--prepr-primary:#4338ca;--prepr-bg:#eef2ff;--prepr-text:#1f2937;--prepr-radius:8px;--prepr-shadow:0px 0px 40px 0px #1f29373d;--prepr-z-index:10000;--prepr-primary-50:#eef2ff;--prepr-primary-100:#e0e7ff;--prepr-primary-800:#3730a3;--prepr-indigo-600:#4f46e5;--prepr-indigo-50:#eef2ff;--prepr-indigo-700:#4338ca;--prepr-secondary-400:#fb923c;--prepr-secondary-500:#f97316;--prepr-gray-100:#f3f4f6;--prepr-gray-200:#e5e7eb;--prepr-gray-300:#d1d5db;--prepr-gray-400:#9ca3af;--prepr-gray-500:#6b7280;--prepr-gray-700:#374151;--prepr-gray-800:#1f2937;--prepr-gray-900:#111827;--prepr-shadow-sm:0px 0px 12px 0px #c3c3c3cc;color:var(--prepr-text);box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;font-size:14px;line-height:1.5}:host *,:host :before,:host :after,*,:before,:after{box-sizing:border-box}button{font-family:inherit;font-size:inherit;margin:0}.prepr-regular-text{font-size:.875rem;font-weight:500;line-height:1.5}.prepr-backdrop{z-index:calc(var(--prepr-z-index) - 1);opacity:0;pointer-events:none;background:#0000001a;transition:opacity .2s ease-in-out;position:fixed;top:0;bottom:0;left:0;right:0}.prepr-backdrop[data-open=true]{opacity:1;pointer-events:auto;animation:.2s ease-in-out prepr-fade-in}.prepr-container{z-index:var(--prepr-z-index);justify-content:flex-end;align-items:center;display:flex;position:fixed;top:calc(50% - 64px);right:0}.prepr-toggle-holder{padding:.5rem}.prepr-toggle{cursor:pointer;background:var(--prepr-primary);color:#fff;border:none;border-radius:9999px;justify-content:center;align-items:center;width:2.25rem;height:2.25rem;display:flex}.prepr-toggle>span{display:flex}.prepr-toggle svg{color:#fff}.prepr-panel{z-index:var(--prepr-z-index);opacity:0;pointer-events:none;justify-content:flex-end;padding:.75rem;transition:opacity .2s ease-in-out;display:flex;position:fixed;top:50%;right:0;transform:translateY(-50%)}.prepr-panel[data-open=true]{opacity:1;pointer-events:auto;animation:.2s ease-in-out prepr-fade-in}.prepr-content{box-shadow:var(--prepr-shadow);border-radius:var(--prepr-radius);background:var(--prepr-bg);flex-direction:column;gap:2.5rem;width:100%;padding:1.5rem;display:flex}@media (min-width:640px){.prepr-panel{margin-right:4rem;padding:0}.prepr-content{width:502px;padding:2.5rem}}.prepr-header{justify-content:space-between;align-items:center;gap:.5rem;display:flex}.prepr-header-left{align-items:flex-start;gap:.75rem;display:flex}.prepr-badge{background:var(--prepr-primary-100);height:1.5rem;color:var(--prepr-primary);border-radius:4px;align-items:center;padding:.25rem .75rem;font-size:.875rem;display:flex}.prepr-header-close{cursor:pointer;background:var(--prepr-primary-100);width:2rem;height:2rem;color:var(--prepr-gray-700);border:none;border-radius:6px;justify-content:center;align-items:center;display:flex}.prepr-section{flex-direction:column;gap:.5rem;display:flex}.prepr-section-label{color:var(--prepr-gray-400);font-size:.875rem}.prepr-row{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:.5rem 1.5rem;display:flex}.prepr-row-title{color:var(--prepr-gray-800);margin:0;font-size:1rem;font-weight:600}.prepr-radiogroup{border-radius:var(--prepr-radius);border:1px solid var(--prepr-gray-300);background:#fff;align-items:center;gap:.25rem;height:2.5rem;padding:.25rem;display:flex}.prepr-radiogroup[data-disabled=true]{cursor:not-allowed;opacity:.5}.prepr-radiogroup[data-disabled=true] .prepr-radio{pointer-events:none}.prepr-radio{cursor:pointer;white-space:nowrap;text-align:center;height:2rem;color:var(--prepr-gray-900);background:0 0;border:none;border-radius:6px;justify-content:center;align-items:center;padding:.5rem 1.125rem;font-size:.875rem;font-weight:500;transition:all .2s ease-in-out;display:flex}.prepr-radio[data-checked=true]{background:var(--prepr-indigo-600);color:#fff;box-shadow:var(--prepr-shadow-sm)}.prepr-radio[data-checked=true][data-off=true]{background:var(--prepr-gray-800);color:#fff}.prepr-radio-variant{width:82px}.prepr-listbox{position:relative}.prepr-segment-button{border-radius:var(--prepr-radius);border:1px solid var(--prepr-gray-300);width:240px;height:2.5rem;color:var(--prepr-gray-500);cursor:pointer;background:#fff;flex-shrink:0;align-items:center;gap:.5rem;padding:0 .5rem;font-size:.875rem;font-weight:500;display:flex;overflow:hidden}@media (min-width:768px){.prepr-segment-button{padding:0 1rem}}.prepr-segment-button:disabled{cursor:not-allowed;background:var(--prepr-gray-200);color:var(--prepr-gray-400)}.prepr-segment-button[aria-expanded=true]{border-bottom-color:#fff;border-bottom-right-radius:0;border-bottom-left-radius:0}.prepr-segment-label{white-space:nowrap;text-overflow:ellipsis;text-align:left;width:100%;margin-right:auto;overflow:hidden}.prepr-segment-caret{color:var(--prepr-gray-800);display:flex}.prepr-options{z-index:calc(var(--prepr-z-index) + 1);border-left:1px solid var(--prepr-gray-300);border-right:1px solid var(--prepr-gray-300);border-bottom:1px solid var(--prepr-gray-300);-ms-overflow-style:none;scrollbar-width:none;background:#fff;border-radius:0 0 6px 6px;width:240px;max-height:300px;margin:0;padding:0;list-style:none;position:absolute;top:100%;left:0;overflow-y:auto;box-shadow:0 20px 25px -5px #0000001a,0 8px 10px -6px #0000001a}.prepr-options::-webkit-scrollbar{display:none}.prepr-options[hidden]{display:none}.prepr-option-search{background:#fff;padding:.5rem;position:-webkit-sticky;position:sticky;top:0}.prepr-segment-search{border:1px solid var(--prepr-gray-300);border-radius:var(--prepr-radius);width:100%;height:2rem;font:inherit;color:var(--prepr-gray-900);box-sizing:border-box;background:#fff;padding:0 .5rem;font-size:.875rem}.prepr-segment-search::placeholder{color:var(--prepr-gray-400)}.prepr-segment-search:focus{border-color:var(--prepr-gray-400);outline:none}.prepr-option{cursor:pointer;width:100%;color:var(--prepr-gray-900);background:#fff;align-items:center;padding:.5rem 1rem;font-size:.875rem;font-weight:500;display:flex}.prepr-option:hover{background:var(--prepr-gray-100)}.prepr-option[aria-selected=true]{background:var(--prepr-indigo-50);color:var(--prepr-indigo-700)}.prepr-option-label{white-space:nowrap;text-overflow:ellipsis;text-align:left;width:100%;margin-right:auto;overflow:hidden}.prepr-reset{background:var(--prepr-secondary-400);color:#fff;cursor:pointer;border:none;border-radius:6px;justify-content:center;align-items:center;gap:.5rem;width:100%;height:2.5rem;padding:.5rem .75rem;font-size:.875rem;font-weight:500;display:flex}.prepr-reset:hover:not(:disabled){background:var(--prepr-secondary-500)}.prepr-reset:disabled{background:var(--prepr-gray-400);color:var(--prepr-gray-500);cursor:not-allowed}@media (min-width:768px){.prepr-reset{width:108px}}.prepr-indicators{z-index:var(--prepr-z-index);gap:.75rem;display:flex;position:fixed;bottom:1.5rem;right:1.5rem}.prepr-status-pill{background:var(--prepr-primary);color:#fff;cursor:pointer;border:none;border-radius:9999px;align-items:center;gap:.5rem;padding:.5rem 1rem;font-size:.75rem;font-weight:500;transition:background-color .15s;display:flex;box-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a}.prepr-status-pill[data-interactive=false]{cursor:default;opacity:1;color:#fff}.prepr-status-pill[data-interactive=true]:hover{background:var(--prepr-primary-800)}.prepr-status-pill[hidden]{display:none}.prepr-status-viewing{color:#fff9;font-size:10px}.prepr-status-segment{text-overflow:ellipsis;white-space:nowrap;max-width:120px;display:inline-block;overflow:hidden}.prepr-status-variant{text-overflow:ellipsis;white-space:nowrap;background:#fff3;border-radius:4px;max-width:80px;padding:0 .5rem;display:inline-block;overflow:hidden}.prepr-status-x{color:#fff;width:.75rem;height:.75rem}.prepr-close-edit-pill{background:var(--prepr-primary-50);color:var(--prepr-gray-800);cursor:pointer;border:none;border-radius:9999px;align-items:center;gap:.5rem;padding:.5rem 1rem;font-size:.75rem;font-weight:500;transition:background-color .15s;display:flex;box-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a}.prepr-close-edit-pill:hover{background:var(--prepr-primary-100)}.prepr-close-edit-pill[hidden]{display:none}.prepr-close-edit-x{width:1rem;height:1rem;color:var(--prepr-gray-500);transition:color .15s}.prepr-close-edit-pill:hover .prepr-close-edit-x{color:var(--prepr-gray-700)}.prepr-tip{z-index:calc(var(--prepr-z-index) + 2);overflow-wrap:break-word;background:var(--prepr-gray-900);color:#fff;pointer-events:none;border-radius:6px;width:auto;max-width:min(420px,100vw - 16px);padding:.5rem .75rem;font-size:.75rem;font-weight:500;position:fixed;box-shadow:0 20px 25px -5px #0000001a,0 8px 10px -6px #0000001a}.prepr-tip-arrow{border-left:6px solid #0000;border-right:6px solid #0000;border-top:6px solid var(--prepr-gray-900);width:0;height:0;position:absolute;top:100%;transform:translate(-50%)}[hidden]{display:none!important}@keyframes prepr-fade-in{0%{opacity:0}to{opacity:1}}";
1949
+ var TOOLBAR_CSS = ":host{--prepr-primary:#4338ca;--prepr-bg:#eef2ff;--prepr-text:#1f2937;--prepr-radius:8px;--prepr-shadow:0px 0px 40px 0px #1f29373d;--prepr-z-index:10000;--prepr-primary-50:#eef2ff;--prepr-primary-100:#e0e7ff;--prepr-primary-800:#3730a3;--prepr-indigo-600:#4f46e5;--prepr-indigo-50:#eef2ff;--prepr-indigo-700:#4338ca;--prepr-secondary-400:#fb923c;--prepr-secondary-500:#f97316;--prepr-gray-100:#f3f4f6;--prepr-gray-200:#e5e7eb;--prepr-gray-300:#d1d5db;--prepr-gray-400:#9ca3af;--prepr-gray-500:#6b7280;--prepr-gray-700:#374151;--prepr-gray-800:#1f2937;--prepr-gray-900:#111827;--prepr-shadow-sm:0px 0px 12px 0px #c3c3c3cc;color:var(--prepr-text);box-sizing:border-box;font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif;font-size:14px;line-height:1.5}:host *,:host :before,:host :after,*,:before,:after{box-sizing:border-box}button{font-family:inherit;font-size:inherit;margin:0}.prepr-regular-text{font-size:.875rem;font-weight:500;line-height:1.5}.prepr-backdrop{z-index:calc(var(--prepr-z-index) - 1);opacity:0;pointer-events:none;background:#0000001a;transition:opacity .2s ease-in-out;position:fixed;top:0;bottom:0;left:0;right:0}.prepr-backdrop[data-open=true]{opacity:1;pointer-events:auto;animation:.2s ease-in-out prepr-fade-in}.prepr-container{z-index:var(--prepr-z-index);justify-content:flex-end;align-items:center;display:flex;position:fixed;top:calc(50% - 64px);right:0}.prepr-toggle-holder{padding:.5rem}.prepr-toggle{cursor:pointer;background:var(--prepr-primary);color:#fff;border:none;border-radius:9999px;justify-content:center;align-items:center;width:2.25rem;height:2.25rem;display:flex}.prepr-toggle>span{display:flex}.prepr-toggle svg{color:#fff}.prepr-panel{z-index:var(--prepr-z-index);opacity:0;pointer-events:none;justify-content:flex-end;padding:.75rem;transition:opacity .2s ease-in-out;display:flex;position:fixed;top:50%;right:0;transform:translateY(-50%)}.prepr-panel[data-open=true]{opacity:1;pointer-events:auto;animation:.2s ease-in-out prepr-fade-in}.prepr-content{box-shadow:var(--prepr-shadow);border-radius:var(--prepr-radius);background:var(--prepr-bg);flex-direction:column;gap:2.5rem;width:100%;padding:1.5rem;display:flex}@media (min-width:640px){.prepr-panel{margin-right:4rem;padding:0}.prepr-content{width:502px;padding:2.5rem}}.prepr-header{justify-content:space-between;align-items:center;gap:.5rem;display:flex}.prepr-header-left{align-items:flex-start;gap:.75rem;display:flex}.prepr-badge{background:var(--prepr-primary-100);height:1.5rem;color:var(--prepr-primary);border-radius:4px;align-items:center;padding:.25rem .75rem;font-size:.875rem;display:flex}.prepr-header-close{cursor:pointer;background:var(--prepr-primary-100);width:2rem;height:2rem;color:var(--prepr-gray-700);border:none;border-radius:6px;justify-content:center;align-items:center;display:flex}.prepr-section{flex-direction:column;gap:.5rem;display:flex}.prepr-section-label{color:var(--prepr-gray-400);font-size:.875rem}.prepr-row{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:.5rem 1.5rem;display:flex}.prepr-row-title{color:var(--prepr-gray-800);margin:0;font-size:1rem;font-weight:600}.prepr-radiogroup{border-radius:var(--prepr-radius);border:1px solid var(--prepr-gray-300);background:#fff;align-items:center;gap:.25rem;height:2.5rem;padding:.25rem;display:flex}.prepr-radiogroup[data-disabled=true]{cursor:not-allowed;opacity:.5}.prepr-radiogroup[data-disabled=true] .prepr-radio{pointer-events:none}.prepr-radio{cursor:pointer;white-space:nowrap;text-align:center;height:2rem;color:var(--prepr-gray-900);background:0 0;border:none;border-radius:6px;justify-content:center;align-items:center;padding:.5rem 1.125rem;font-size:.875rem;font-weight:500;transition:all .2s ease-in-out;display:flex}.prepr-radio[data-checked=true]{background:var(--prepr-indigo-600);color:#fff;box-shadow:var(--prepr-shadow-sm)}.prepr-radio[data-checked=true][data-off=true]{background:var(--prepr-gray-800);color:#fff}.prepr-radio-variant{width:82px}.prepr-listbox{position:relative}.prepr-segment-button{border-radius:var(--prepr-radius);border:1px solid var(--prepr-gray-300);width:240px;height:2.5rem;color:var(--prepr-gray-500);cursor:pointer;background:#fff;flex-shrink:0;align-items:center;gap:.5rem;padding:0 .5rem;font-size:.875rem;font-weight:500;display:flex;overflow:hidden}@media (min-width:768px){.prepr-segment-button{padding:0 1rem}}.prepr-segment-button:disabled{cursor:not-allowed;background:var(--prepr-gray-200);color:var(--prepr-gray-400)}.prepr-segment-button[aria-expanded=true]{border-bottom-color:#fff;border-bottom-right-radius:0;border-bottom-left-radius:0}.prepr-segment-label{white-space:nowrap;text-overflow:ellipsis;text-align:left;width:100%;margin-right:auto;overflow:hidden}.prepr-segment-caret{color:var(--prepr-gray-800);display:flex}.prepr-options{z-index:calc(var(--prepr-z-index) + 1);border-left:1px solid var(--prepr-gray-300);border-right:1px solid var(--prepr-gray-300);border-bottom:1px solid var(--prepr-gray-300);-ms-overflow-style:none;scrollbar-width:none;background:#fff;border-radius:0 0 6px 6px;width:240px;max-height:300px;margin:0;padding:0;list-style:none;position:absolute;top:100%;left:0;overflow-y:auto;box-shadow:0 20px 25px -5px #0000001a,0 8px 10px -6px #0000001a}.prepr-options::-webkit-scrollbar{display:none}.prepr-options[hidden]{display:none}.prepr-option-search{background:#fff;padding:.5rem;position:-webkit-sticky;position:sticky;top:0}.prepr-segment-search{border:1px solid var(--prepr-gray-300);border-radius:var(--prepr-radius);width:100%;height:2rem;font:inherit;color:var(--prepr-gray-900);box-sizing:border-box;background:#fff;padding:0 .5rem;font-size:.875rem}@media (pointer:coarse){.prepr-segment-search{font-size:16px}}.prepr-segment-search::placeholder{color:var(--prepr-gray-400)}.prepr-segment-search:focus{border-color:var(--prepr-gray-400);outline:none}.prepr-option{cursor:pointer;width:100%;color:var(--prepr-gray-900);background:#fff;align-items:center;padding:.5rem 1rem;font-size:.875rem;font-weight:500;display:flex}.prepr-option:hover{background:var(--prepr-gray-100)}.prepr-option[aria-selected=true]{background:var(--prepr-indigo-50);color:var(--prepr-indigo-700)}.prepr-option-label{white-space:nowrap;text-overflow:ellipsis;text-align:left;width:100%;margin-right:auto;overflow:hidden}.prepr-reset{background:var(--prepr-secondary-400);color:#fff;cursor:pointer;border:none;border-radius:6px;justify-content:center;align-items:center;gap:.5rem;width:100%;height:2.5rem;padding:.5rem .75rem;font-size:.875rem;font-weight:500;display:flex}.prepr-reset:hover:not(:disabled){background:var(--prepr-secondary-500)}.prepr-reset:disabled{background:var(--prepr-gray-400);color:var(--prepr-gray-500);cursor:not-allowed}@media (min-width:768px){.prepr-reset{width:108px}}.prepr-indicators{z-index:var(--prepr-z-index);gap:.75rem;display:flex;position:fixed;bottom:1.5rem;right:1.5rem}.prepr-status-pill{background:var(--prepr-primary);color:#fff;cursor:pointer;border:none;border-radius:9999px;align-items:center;gap:.5rem;padding:.5rem 1rem;font-size:.75rem;font-weight:500;transition:background-color .15s;display:flex;box-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a}.prepr-status-pill[data-interactive=false]{cursor:default;opacity:1;color:#fff}.prepr-status-pill[data-interactive=true]:hover{background:var(--prepr-primary-800)}.prepr-status-pill[hidden]{display:none}.prepr-status-viewing{color:#fff9;font-size:10px}.prepr-status-segment{text-overflow:ellipsis;white-space:nowrap;max-width:120px;display:inline-block;overflow:hidden}.prepr-status-variant{text-overflow:ellipsis;white-space:nowrap;background:#fff3;border-radius:4px;max-width:80px;padding:0 .5rem;display:inline-block;overflow:hidden}.prepr-status-x{color:#fff;width:.75rem;height:.75rem}.prepr-close-edit-pill{background:var(--prepr-primary-50);color:var(--prepr-gray-800);cursor:pointer;border:none;border-radius:9999px;align-items:center;gap:.5rem;padding:.5rem 1rem;font-size:.75rem;font-weight:500;transition:background-color .15s;display:flex;box-shadow:0 10px 15px -3px #0000001a,0 4px 6px -4px #0000001a}.prepr-close-edit-pill:hover{background:var(--prepr-primary-100)}.prepr-close-edit-pill[hidden]{display:none}.prepr-close-edit-x{width:1rem;height:1rem;color:var(--prepr-gray-500);transition:color .15s}.prepr-close-edit-pill:hover .prepr-close-edit-x{color:var(--prepr-gray-700)}.prepr-tip{z-index:calc(var(--prepr-z-index) + 2);overflow-wrap:break-word;background:var(--prepr-gray-900);color:#fff;pointer-events:none;border-radius:6px;width:auto;max-width:min(420px,100vw - 16px);padding:.5rem .75rem;font-size:.75rem;font-weight:500;position:fixed;box-shadow:0 20px 25px -5px #0000001a,0 8px 10px -6px #0000001a}.prepr-tip-arrow{border-left:6px solid #0000;border-right:6px solid #0000;border-top:6px solid var(--prepr-gray-900);width:0;height:0;position:absolute;top:100%;transform:translate(-50%)}[hidden]{display:none!important}@keyframes prepr-fade-in{0%{opacity:0}to{opacity:1}}";
1532
1950
 
1533
1951
  // ../../node_modules/.pnpm/preact@10.29.7/node_modules/preact/jsx-runtime/dist/jsxRuntime.mjs
1534
1952
  var f2 = 0;
@@ -2223,49 +2641,767 @@ function definePreprToolbar() {
2223
2641
  }
2224
2642
  }
2225
2643
 
2226
- // src/core/create-preview.ts
2227
- var debug9 = createScopedLogger("create-preview");
2228
- var controllerStores = /* @__PURE__ */ new WeakMap();
2229
- function defaultNavigation() {
2230
- return {
2231
- navigate: (url) => window.location.assign(url),
2232
- currentPath: () => window.location.pathname + window.location.search
2233
- };
2644
+ // src/core/visual-editor/asset-images.ts
2645
+ var MAX_URL_LENGTH = 4096;
2646
+ var MIN_KEY_SEGMENTS = 2;
2647
+ var TRANSFORM_OPTION = /^[a-z]{1,3}_[\w.-]*$/i;
2648
+ var FORMAT_PLACEHOLDER = "{format}";
2649
+ var PROXY_PARAMS = ["url", "href", "src", "image"];
2650
+ var ABSOLUTE_HTTP = /^https?:\/\//i;
2651
+ var SOURCE_URL_ATTRIBUTES = ["src", "data-src"];
2652
+ var SOURCE_SET_ATTRIBUTES = ["srcset", "data-srcset"];
2653
+ var ASSET_ATTR = "data-prepr-asset";
2654
+ var ASSET_SOURCE_ATTRIBUTES = [
2655
+ ...SOURCE_URL_ATTRIBUTES,
2656
+ ...SOURCE_SET_ATTRIBUTES
2657
+ ];
2658
+ var TAG_ATTRIBUTES = [
2659
+ "data-prepr-encoded",
2660
+ "data-prepr-id",
2661
+ "data-prepr-field",
2662
+ "data-prepr-entry-id",
2663
+ ASSET_ATTR
2664
+ ];
2665
+ function decodeSegment(segment) {
2666
+ try {
2667
+ return decodeURIComponent(segment);
2668
+ } catch {
2669
+ return segment;
2670
+ }
2234
2671
  }
2235
- function safeEditUrl(href) {
2672
+ function isTransformSegment(segment) {
2673
+ return segment === FORMAT_PLACEHOLDER || segment.split(",").every((option) => TRANSFORM_OPTION.test(option));
2674
+ }
2675
+ function assetKey(url, depth = 0) {
2676
+ if (!url || url.length > MAX_URL_LENGTH) return null;
2677
+ let parsed;
2236
2678
  try {
2237
- const url = new URL(href, window.location.href);
2238
- return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
2679
+ parsed = new URL(url, "https://base.invalid");
2239
2680
  } catch {
2240
2681
  return null;
2241
2682
  }
2683
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
2684
+ if (depth === 0) {
2685
+ for (const name of PROXY_PARAMS) {
2686
+ const inner = parsed.searchParams.get(name);
2687
+ if (inner && ABSOLUTE_HTTP.test(inner)) return assetKey(inner, 1);
2688
+ }
2689
+ }
2690
+ const segments = parsed.pathname.split("/").filter(Boolean).map(decodeSegment);
2691
+ const file = segments.pop();
2692
+ if (!file) return null;
2693
+ const kept = segments.filter((segment) => !isTransformSegment(segment));
2694
+ kept.push(file);
2695
+ return kept.length >= MIN_KEY_SEGMENTS ? kept.join("/") : null;
2242
2696
  }
2243
- function buildSegments(data) {
2244
- return [{ _id: "all_other_users", name: "All other users" }, ...data];
2697
+ function srcsetUrls(srcset) {
2698
+ const urls = [];
2699
+ let expectUrl = true;
2700
+ for (const token of srcset.split(/\s+/)) {
2701
+ if (!token) continue;
2702
+ if (!expectUrl) {
2703
+ const comma = token.indexOf(",");
2704
+ if (comma === -1) continue;
2705
+ expectUrl = true;
2706
+ const rest = token.slice(comma + 1);
2707
+ if (!rest) continue;
2708
+ urls.push(rest.replace(/,+$/, ""));
2709
+ expectUrl = rest.endsWith(",");
2710
+ continue;
2711
+ }
2712
+ const url = token.replace(/^,+|,+$/g, "");
2713
+ if (url) urls.push(url);
2714
+ expectUrl = token.endsWith(",");
2715
+ }
2716
+ return urls;
2245
2717
  }
2246
- function resolveLocale(options) {
2247
- const explicit = options?.locale;
2248
- if (isLocale(explicit)) return explicit;
2249
- if (typeof navigator !== "undefined") {
2250
- const candidates = Array.isArray(navigator.languages) && navigator.languages.length ? navigator.languages : [navigator.language];
2251
- const match = candidates.filter(Boolean).map((l2) => l2.toLowerCase().split("-")[0]).find(isLocale);
2252
- if (match) return match;
2718
+ function createAssetIndex(assets) {
2719
+ const index = /* @__PURE__ */ new Map();
2720
+ for (const asset of assets) {
2721
+ const key = assetKey(asset.key);
2722
+ if (key && !index.has(key)) index.set(key, asset);
2253
2723
  }
2254
- return "en";
2724
+ return index;
2255
2725
  }
2256
- function createPreprPreview(opts = {}) {
2257
- const { props, options } = opts;
2258
- const navigation = opts.navigation ?? defaultNavigation();
2259
- initDebugLogger(options?.debug ?? false);
2260
- const noop = () => ({ destroy: () => {
2261
- } });
2262
- if (typeof window === "undefined" || typeof document === "undefined") {
2263
- return noop();
2726
+ function urlsOf(img) {
2727
+ const urls = [];
2728
+ const collect = (el) => {
2729
+ for (const name of SOURCE_URL_ATTRIBUTES) {
2730
+ const value = el.getAttribute(name);
2731
+ if (value) urls.push(value);
2732
+ }
2733
+ for (const name of SOURCE_SET_ATTRIBUTES) {
2734
+ const value = el.getAttribute(name);
2735
+ if (value) urls.push(...srcsetUrls(value));
2736
+ }
2737
+ };
2738
+ collect(img);
2739
+ const picture = img.parentElement;
2740
+ if (picture?.tagName === "PICTURE") {
2741
+ for (const source of picture.children) {
2742
+ if (source.tagName === "SOURCE") collect(source);
2743
+ }
2264
2744
  }
2265
- const isIframe = window.parent !== window;
2266
- const search = new URLSearchParams(window.location.search);
2267
- const hideBar = search.get(PARAM_HIDE_BAR) === "true";
2268
- if (hideBar) {
2745
+ return urls;
2746
+ }
2747
+ function matchAsset(img, index, keys) {
2748
+ for (const url of urlsOf(img)) {
2749
+ let key = keys.get(url);
2750
+ if (key === void 0) {
2751
+ key = assetKey(url);
2752
+ keys.set(url, key);
2753
+ }
2754
+ const asset = key ? index.get(key) : void 0;
2755
+ if (asset) return asset;
2756
+ }
2757
+ return void 0;
2758
+ }
2759
+ function setIfChanged(el, name, value) {
2760
+ if (value === null) {
2761
+ if (el.hasAttribute(name)) el.removeAttribute(name);
2762
+ } else if (el.getAttribute(name) !== value) {
2763
+ el.setAttribute(name, value);
2764
+ }
2765
+ }
2766
+ function untagAssetImage(img) {
2767
+ for (const name of TAG_ATTRIBUTES) img.removeAttribute(name);
2768
+ }
2769
+ function tagAssetImages(index, itemId, keys) {
2770
+ for (const img of document.getElementsByTagName("img")) {
2771
+ const ours = img.hasAttribute(ASSET_ATTR);
2772
+ if (!ours && img.hasAttribute("data-prepr-encoded")) continue;
2773
+ const asset = index.size ? matchAsset(img, index, keys) : void 0;
2774
+ if (!asset) {
2775
+ if (ours) untagAssetImage(img);
2776
+ continue;
2777
+ }
2778
+ setIfChanged(img, "data-prepr-encoded", "");
2779
+ setIfChanged(img, ASSET_ATTR, "");
2780
+ setIfChanged(img, "data-prepr-id", itemId);
2781
+ setIfChanged(img, "data-prepr-field", asset.field);
2782
+ setIfChanged(img, "data-prepr-entry-id", asset.entryId ?? null);
2783
+ }
2784
+ }
2785
+ function untagAssetImages() {
2786
+ document.querySelectorAll(`img[${ASSET_ATTR}]`).forEach(untagAssetImage);
2787
+ }
2788
+
2789
+ // src/core/visual-editor/navigation-guard.ts
2790
+ var debug7 = createScopedLogger("navigation-guard");
2791
+ var trimSlash = (path) => path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path;
2792
+ function resolve(url) {
2793
+ try {
2794
+ return new URL(url, document.baseURI);
2795
+ } catch {
2796
+ return null;
2797
+ }
2798
+ }
2799
+ function leavesPage(url) {
2800
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
2801
+ const here = window.location;
2802
+ return url.origin !== here.origin || trimSlash(url.pathname) !== trimSlash(here.pathname);
2803
+ }
2804
+ function leavingLinkHref(target) {
2805
+ if (!(target instanceof Element)) return null;
2806
+ const link = target.closest("a[href]");
2807
+ if (!link || link.hasAttribute("download")) return null;
2808
+ const linkTarget = link.getAttribute("target");
2809
+ if (linkTarget && linkTarget !== "_self") return null;
2810
+ const href = link.getAttribute("href") ?? "";
2811
+ if (href.startsWith("#")) return null;
2812
+ const url = resolve(href);
2813
+ return url && leavesPage(url) ? url.href : null;
2814
+ }
2815
+ function submitterAttr(submitter, attr) {
2816
+ if (!submitter?.hasAttribute(attr)) return null;
2817
+ if (attr === "formaction") return submitter.formAction;
2818
+ if (attr === "formmethod") return submitter.formMethod;
2819
+ return submitter.formTarget;
2820
+ }
2821
+ function submissionUrl(form, submitter) {
2822
+ const method = (submitterAttr(submitter, "formmethod") ?? form.method).toLowerCase();
2823
+ if (method === "dialog") return null;
2824
+ const target = submitterAttr(submitter, "formtarget") ?? form.target;
2825
+ if (target && target !== "_self") return null;
2826
+ const url = resolve(
2827
+ submitterAttr(submitter, "formaction") ?? (form.action || location.href)
2828
+ );
2829
+ if (!url) return null;
2830
+ if (method === "get") {
2831
+ let data;
2832
+ try {
2833
+ data = new FormData(form, submitter);
2834
+ } catch {
2835
+ data = new FormData(form);
2836
+ }
2837
+ const query = new URLSearchParams();
2838
+ data.forEach((value, key) => {
2839
+ query.append(key, typeof value === "string" ? value : value.name);
2840
+ });
2841
+ url.search = query.toString();
2842
+ }
2843
+ return url;
2844
+ }
2845
+ function createNavigationGuard(opts) {
2846
+ let active = false;
2847
+ let permitted = null;
2848
+ let pendingForm = null;
2849
+ let originalPush = null;
2850
+ let guardedPush = null;
2851
+ const isPermitted = (url) => permitted === url.href;
2852
+ const guarding = () => active && opts.showsEditedContent();
2853
+ const report = (href) => {
2854
+ debug7.log("blocked navigation to", href);
2855
+ opts.onBlocked(href);
2856
+ };
2857
+ const onSubmit = (e2) => {
2858
+ if (e2.defaultPrevented || !(e2.target instanceof HTMLFormElement)) return;
2859
+ if (!guarding()) return;
2860
+ const submitter = e2.submitter ?? null;
2861
+ const url = submissionUrl(e2.target, submitter);
2862
+ if (!url || !leavesPage(url) || isPermitted(url)) return;
2863
+ e2.preventDefault();
2864
+ pendingForm = { form: e2.target, submitter, href: url.href };
2865
+ report(url.href);
2866
+ };
2867
+ const onNavigate = (event) => {
2868
+ const e2 = event;
2869
+ if (e2.navigationType === "traverse" || e2.navigationType === "reload") {
2870
+ return;
2871
+ }
2872
+ if (!e2.cancelable || e2.hashChange || e2.downloadRequest !== null) return;
2873
+ if (!guarding()) return;
2874
+ if (e2.navigationType === "replace" && e2.destination.sameDocument) return;
2875
+ const url = resolve(e2.destination.url);
2876
+ if (!url || !leavesPage(url) || isPermitted(url)) return;
2877
+ e2.preventDefault();
2878
+ report(url.href);
2879
+ if (e2.destination.sameDocument) window.location.reload();
2880
+ };
2881
+ const navigation = () => window.navigation;
2882
+ function installPushGuard() {
2883
+ const original = history.pushState;
2884
+ const guard = function(data, unused, url) {
2885
+ if (guarding() && guardedPush === guard && url != null) {
2886
+ const target = resolve(url);
2887
+ if (target && leavesPage(target) && !isPermitted(target)) {
2888
+ report(target.href);
2889
+ window.location.reload();
2890
+ return;
2891
+ }
2892
+ }
2893
+ return original.call(this, data, unused, url);
2894
+ };
2895
+ originalPush = original;
2896
+ guardedPush = guard;
2897
+ history.pushState = guard;
2898
+ }
2899
+ function uninstallPushGuard() {
2900
+ if (history.pushState === guardedPush && originalPush) {
2901
+ history.pushState = originalPush;
2902
+ }
2903
+ originalPush = null;
2904
+ guardedPush = null;
2905
+ }
2906
+ return {
2907
+ start() {
2908
+ if (active) return;
2909
+ active = true;
2910
+ installPushGuard();
2911
+ window.addEventListener("submit", onSubmit);
2912
+ navigation()?.addEventListener("navigate", onNavigate);
2913
+ },
2914
+ stop() {
2915
+ if (!active) return;
2916
+ active = false;
2917
+ uninstallPushGuard();
2918
+ window.removeEventListener("submit", onSubmit);
2919
+ navigation()?.removeEventListener("navigate", onNavigate);
2920
+ pendingForm = null;
2921
+ },
2922
+ isActive: guarding,
2923
+ block(href) {
2924
+ report(href);
2925
+ },
2926
+ permit(href) {
2927
+ permitted = resolve(href)?.href ?? null;
2928
+ },
2929
+ allow(href) {
2930
+ const url = resolve(href);
2931
+ if (!url || url.protocol !== "http:" && url.protocol !== "https:") {
2932
+ debug7.warn("ignored navigation to unsupported URL");
2933
+ return;
2934
+ }
2935
+ permitted = url.href;
2936
+ const form = pendingForm;
2937
+ pendingForm = null;
2938
+ if (form && form.href === url.href && form.form.isConnected) {
2939
+ try {
2940
+ form.form.requestSubmit(form.submitter ?? void 0);
2941
+ } catch {
2942
+ form.form.requestSubmit();
2943
+ }
2944
+ return;
2945
+ }
2946
+ window.location.assign(url.href);
2947
+ }
2948
+ };
2949
+ }
2950
+
2951
+ // src/core/visual-editor/index.ts
2952
+ var debug8 = createScopedLogger("visual-editor");
2953
+ var ENCODED_SELECTOR2 = "[data-prepr-encoded]";
2954
+ var REFERENCE_ATTR = "data-prepr-reference";
2955
+ var REFERENCE_SELECTOR = `[${REFERENCE_ATTR}]`;
2956
+ var CURSOR_STYLE_MARKER = "data-prepr-visual-editor";
2957
+ var CURSOR_STYLES = `${ENCODED_SELECTOR2}{cursor:pointer}html[data-prepr-ve-suspended] ${ENCODED_SELECTOR2}{cursor:auto}`;
2958
+ var SUSPENDED_ATTR = "data-prepr-ve-suspended";
2959
+ var FIND_RETRY_MS = 150;
2960
+ var FIND_RETRIES = 6;
2961
+ var MAX_CACHED_KEYS = 2e3;
2962
+ var LAYOUT_MUTATIONS = {
2963
+ childList: true,
2964
+ subtree: true,
2965
+ characterData: true,
2966
+ attributes: true,
2967
+ attributeFilter: [
2968
+ "class",
2969
+ "style",
2970
+ "hidden",
2971
+ "open",
2972
+ "data-prepr-encoded",
2973
+ // An image swapped by a carousel or lazy loader can show another asset.
2974
+ ...ASSET_SOURCE_ATTRIBUTES
2975
+ ]
2976
+ };
2977
+ function scrollIntoFrame(el) {
2978
+ const rect = el.getBoundingClientRect();
2979
+ const offset = Math.max(0, (window.innerHeight - rect.height) / 2);
2980
+ window.scrollTo({
2981
+ top: Math.max(0, window.scrollY + rect.top - offset),
2982
+ behavior: "smooth"
2983
+ });
2984
+ }
2985
+ var isVisible = (el) => typeof el.checkVisibility === "function" ? el.checkVisibility() : el.getClientRects().length > 0;
2986
+ function createVisualEditor(opts) {
2987
+ const overlay = new VisualEditorOverlay();
2988
+ let running = false;
2989
+ let currentItemId = null;
2990
+ let locale = opts.locale ?? "en";
2991
+ let suspended = false;
2992
+ let pointerFrame = null;
2993
+ let lastPointerTarget = null;
2994
+ let lastPointerX = 0;
2995
+ let lastPointerY = 0;
2996
+ let mutationFrame = null;
2997
+ let mutationObserver = null;
2998
+ let selection = null;
2999
+ let findTimeout = null;
3000
+ let settlePendingFind = null;
3001
+ let guardEnabled = false;
3002
+ let assetIndex = /* @__PURE__ */ new Map();
3003
+ const assetKeys = /* @__PURE__ */ new Map();
3004
+ const guard = createNavigationGuard({
3005
+ onBlocked: (href) => opts.onNavigationBlocked?.(href),
3006
+ showsEditedContent: () => showsEditedContent()
3007
+ });
3008
+ const encodedFrom = (node) => node instanceof Element ? node.closest(ENCODED_SELECTOR2) : null;
3009
+ const labelFor = (el) => fieldLabel(el.getAttribute("data-prepr-field"), locale);
3010
+ let references = null;
3011
+ let ownComponents = /* @__PURE__ */ new Set();
3012
+ const isCurrentItem = (el) => {
3013
+ if (currentItemId === null) return true;
3014
+ const id = el.getAttribute("data-prepr-id");
3015
+ return !id || id === currentItemId || ownComponents.has(id);
3016
+ };
3017
+ const showsEditedContent = () => {
3018
+ for (const el of document.querySelectorAll(ENCODED_SELECTOR2)) {
3019
+ if (isCurrentItem(el) && isVisible(el)) return true;
3020
+ }
3021
+ return false;
3022
+ };
3023
+ const linkedIdOf = (el) => {
3024
+ if (!references) return null;
3025
+ const id = el.getAttribute("data-prepr-id") ?? "";
3026
+ if (references.has(id)) return id;
3027
+ let container = el.closest(REFERENCE_SELECTOR);
3028
+ while (container) {
3029
+ const linked = container.getAttribute(REFERENCE_ATTR) ?? "";
3030
+ if (references.has(linked)) return linked;
3031
+ container = container.parentElement?.closest(REFERENCE_SELECTOR) ?? null;
3032
+ }
3033
+ return null;
3034
+ };
3035
+ const itemKind = (el) => {
3036
+ if (isCurrentItem(el)) return "current";
3037
+ if (!references) return "other";
3038
+ return linkedIdOf(el) ? "referenced" : null;
3039
+ };
3040
+ const referenceFieldOf = (el) => {
3041
+ const linked = linkedIdOf(el);
3042
+ return linked ? references?.get(linked) : void 0;
3043
+ };
3044
+ const hoverLabel = (el, kind) => {
3045
+ if (kind === "other") {
3046
+ return `${labelFor(el)} \xB7 ${t("visualEditor.otherItem", locale)}`;
3047
+ }
3048
+ if (kind === "referenced") {
3049
+ const via = referenceFieldOf(el);
3050
+ const prefix = via ? `${fieldLabel(via, locale)} \u203A ` : "";
3051
+ return `${prefix}${labelFor(el)} \xB7 ${t("visualEditor.linkedItem", locale)}`;
3052
+ }
3053
+ return labelFor(el);
3054
+ };
3055
+ const setSuspended = (value) => {
3056
+ if (suspended === value) return;
3057
+ suspended = value;
3058
+ document.documentElement.toggleAttribute(SUSPENDED_ATTR, value);
3059
+ if (value) overlay.setHover(null, "");
3060
+ };
3061
+ const updateHover = () => {
3062
+ pointerFrame = null;
3063
+ overlay.schedule();
3064
+ if (suspended) return;
3065
+ const encoded = encodedFrom(lastPointerTarget);
3066
+ const target = encoded === overlay.getSelectedTarget() ? null : encoded;
3067
+ if (!target) {
3068
+ overlay.setHover(null, "");
3069
+ return;
3070
+ }
3071
+ const kind = itemKind(target);
3072
+ if (!kind) {
3073
+ overlay.setHover(null, "");
3074
+ return;
3075
+ }
3076
+ overlay.setHover(target, hoverLabel(target, kind), { kind });
3077
+ };
3078
+ const handlePointerMove = (e2) => {
3079
+ setSuspended(e2.altKey);
3080
+ lastPointerTarget = e2.target;
3081
+ lastPointerX = e2.clientX;
3082
+ lastPointerY = e2.clientY;
3083
+ if (pointerFrame === null) {
3084
+ pointerFrame = requestAnimationFrame(updateHover);
3085
+ }
3086
+ };
3087
+ const handlePointerLeave = () => {
3088
+ lastPointerTarget = null;
3089
+ overlay.setHover(null, "");
3090
+ };
3091
+ const handleClick = (e2) => {
3092
+ if (e2.altKey) {
3093
+ const href = leavingLinkHref(e2.target);
3094
+ if (href && guard.isActive()) guard.permit(href);
3095
+ return;
3096
+ }
3097
+ const encoded = encodedFrom(e2.target);
3098
+ const kind = encoded ? itemKind(encoded) : null;
3099
+ if (!encoded || !kind) {
3100
+ clearSelection();
3101
+ if (e2.ctrlKey || e2.metaKey || e2.shiftKey || !showsEditedContent()) return;
3102
+ const href = leavingLinkHref(e2.target);
3103
+ if (!href) return;
3104
+ e2.preventDefault();
3105
+ if (guard.isActive()) {
3106
+ e2.stopPropagation();
3107
+ guard.block(href);
3108
+ }
3109
+ return;
3110
+ }
3111
+ e2.preventDefault();
3112
+ e2.stopPropagation();
3113
+ const item = listItemIn(encoded, e2.target);
3114
+ if (kind === "current")
3115
+ select(item?.element ?? encoded, encoded, item?.index);
3116
+ const referenceField = kind === "referenced" ? referenceFieldOf(encoded) : void 0;
3117
+ const linkedId = kind === "referenced" ? linkedIdOf(encoded) : null;
3118
+ opts.onEdit({
3119
+ ...readEditPayload(encoded),
3120
+ ...linkedId && { id: linkedId },
3121
+ ...item && { block: item.index },
3122
+ ...referenceField && { referenceField }
3123
+ });
3124
+ };
3125
+ const handleKey = (e2) => {
3126
+ if (e2.key === "Alt") setSuspended(e2.type === "keydown");
3127
+ if (e2.type === "keydown" && e2.key === "Escape") {
3128
+ clearSelection();
3129
+ }
3130
+ };
3131
+ const handleBlur = () => setSuspended(false);
3132
+ const handleScroll = () => overlay.onScroll();
3133
+ const handleResize = () => overlay.schedule();
3134
+ const handleSettled = () => overlay.schedule();
3135
+ function listItemIn(encoded, target) {
3136
+ if (!(target instanceof Element)) return null;
3137
+ const li = target.closest("li");
3138
+ if (!li || !encoded.contains(li) || !li.parentElement) return null;
3139
+ const items = Array.from(li.parentElement.children).filter(
3140
+ (child) => child.tagName === "LI"
3141
+ );
3142
+ return { element: li, index: items.indexOf(li) };
3143
+ }
3144
+ function nthListItem(encoded, block) {
3145
+ const list = encoded.querySelector("ul, ol");
3146
+ if (!list) return null;
3147
+ const items = Array.from(list.children).filter(
3148
+ (child) => child.tagName === "LI"
3149
+ );
3150
+ return items[block] ?? null;
3151
+ }
3152
+ function select(el, field, block) {
3153
+ const entryId = field.getAttribute("data-prepr-entry-id");
3154
+ selection = {
3155
+ lookup: {
3156
+ field: field.getAttribute("data-prepr-field") ?? "",
3157
+ id: field.getAttribute("data-prepr-id") ?? void 0,
3158
+ ...entryId && { entryId },
3159
+ ...block !== void 0 && { block }
3160
+ },
3161
+ label: field
3162
+ };
3163
+ overlay.setSelected(el, labelFor(field));
3164
+ if (overlay.getHoverTarget() === el) overlay.setHover(null, "");
3165
+ }
3166
+ function clearSelection() {
3167
+ selection = null;
3168
+ overlay.setSelected(null, "");
3169
+ }
3170
+ function reselect() {
3171
+ if (!selection) return;
3172
+ const current = overlay.getSelectedTarget();
3173
+ if (current?.isConnected && selection.label.isConnected) return;
3174
+ const found = findFieldElement(selection.lookup);
3175
+ if (!found || !isCurrentItem(found)) {
3176
+ overlay.setSelected(null, "");
3177
+ return;
3178
+ }
3179
+ const { block } = selection.lookup;
3180
+ const el = block !== void 0 ? nthListItem(found, block) ?? found : found;
3181
+ select(el, found, block);
3182
+ }
3183
+ function tagAssets() {
3184
+ if (assetKeys.size > MAX_CACHED_KEYS) assetKeys.clear();
3185
+ tagAssetImages(assetIndex, currentItemId, assetKeys);
3186
+ }
3187
+ const handleLayoutFrame = () => {
3188
+ mutationFrame = null;
3189
+ if (assetIndex.size) tagAssets();
3190
+ reselect();
3191
+ const hovered = overlay.getHoverTarget();
3192
+ if (hovered && !hovered.isConnected) {
3193
+ lastPointerTarget = document.elementFromPoint(lastPointerX, lastPointerY);
3194
+ updateHover();
3195
+ return;
3196
+ }
3197
+ overlay.schedule();
3198
+ };
3199
+ const handleMutations = () => {
3200
+ if (mutationFrame !== null) return;
3201
+ if (!selection && !overlay.getHoverTarget() && !assetIndex.size) return;
3202
+ mutationFrame = requestAnimationFrame(handleLayoutFrame);
3203
+ };
3204
+ function injectCursorStyles() {
3205
+ if (document.querySelector(`style[${CURSOR_STYLE_MARKER}]`)) return;
3206
+ const style = document.createElement("style");
3207
+ style.setAttribute(CURSOR_STYLE_MARKER, "");
3208
+ style.textContent = CURSOR_STYLES;
3209
+ document.head.appendChild(style);
3210
+ }
3211
+ function start() {
3212
+ if (running) return;
3213
+ running = true;
3214
+ overlay.mount();
3215
+ injectCursorStyles();
3216
+ document.addEventListener("pointermove", handlePointerMove, {
3217
+ passive: true
3218
+ });
3219
+ document.documentElement.addEventListener(
3220
+ "pointerleave",
3221
+ handlePointerLeave
3222
+ );
3223
+ document.addEventListener("click", handleClick, { capture: true });
3224
+ window.addEventListener("keydown", handleKey);
3225
+ window.addEventListener("keyup", handleKey);
3226
+ window.addEventListener("blur", handleBlur);
3227
+ window.addEventListener("scroll", handleScroll, {
3228
+ capture: true,
3229
+ passive: true
3230
+ });
3231
+ window.addEventListener("resize", handleResize, { passive: true });
3232
+ document.addEventListener("transitionend", handleSettled, {
3233
+ capture: true,
3234
+ passive: true
3235
+ });
3236
+ document.addEventListener("animationend", handleSettled, {
3237
+ capture: true,
3238
+ passive: true
3239
+ });
3240
+ mutationObserver = new MutationObserver(handleMutations);
3241
+ mutationObserver.observe(document.body, LAYOUT_MUTATIONS);
3242
+ if (assetIndex.size) tagAssets();
3243
+ syncGuard();
3244
+ debug8.log("visual editor started");
3245
+ }
3246
+ function stop() {
3247
+ if (!running) return;
3248
+ running = false;
3249
+ if (pointerFrame !== null) cancelAnimationFrame(pointerFrame);
3250
+ if (mutationFrame !== null) cancelAnimationFrame(mutationFrame);
3251
+ mutationObserver?.disconnect();
3252
+ mutationObserver = null;
3253
+ cancelFind();
3254
+ pointerFrame = null;
3255
+ mutationFrame = null;
3256
+ selection = null;
3257
+ lastPointerTarget = null;
3258
+ setSuspended(false);
3259
+ document.removeEventListener("pointermove", handlePointerMove);
3260
+ document.documentElement.removeEventListener(
3261
+ "pointerleave",
3262
+ handlePointerLeave
3263
+ );
3264
+ document.removeEventListener("click", handleClick, { capture: true });
3265
+ window.removeEventListener("keydown", handleKey);
3266
+ window.removeEventListener("keyup", handleKey);
3267
+ window.removeEventListener("blur", handleBlur);
3268
+ window.removeEventListener("scroll", handleScroll, { capture: true });
3269
+ window.removeEventListener("resize", handleResize);
3270
+ document.removeEventListener("transitionend", handleSettled, {
3271
+ capture: true
3272
+ });
3273
+ document.removeEventListener("animationend", handleSettled, {
3274
+ capture: true
3275
+ });
3276
+ document.querySelectorAll(`style[${CURSOR_STYLE_MARKER}]`).forEach((node) => node.remove());
3277
+ overlay.unmount();
3278
+ untagAssetImages();
3279
+ guard.stop();
3280
+ debug8.log("visual editor stopped");
3281
+ }
3282
+ function cancelFind() {
3283
+ if (findTimeout) clearTimeout(findTimeout);
3284
+ findTimeout = null;
3285
+ settlePendingFind?.();
3286
+ settlePendingFind = null;
3287
+ }
3288
+ function focusField(lookup) {
3289
+ cancelFind();
3290
+ return new Promise((resolve2) => {
3291
+ let attempt = 0;
3292
+ const finish = (found) => {
3293
+ settlePendingFind = null;
3294
+ resolve2(found);
3295
+ };
3296
+ settlePendingFind = () => resolve2(false);
3297
+ const tryFind = () => {
3298
+ findTimeout = null;
3299
+ const found = findFieldElement(lookup);
3300
+ if (found) {
3301
+ const el = lookup.block !== void 0 ? nthListItem(found, lookup.block) ?? found : found;
3302
+ scrollIntoFrame(el);
3303
+ if (running && isCurrentItem(found)) select(el, found, lookup.block);
3304
+ finish(true);
3305
+ return;
3306
+ }
3307
+ if (++attempt >= FIND_RETRIES) {
3308
+ debug8.log("no element renders field", lookup.field);
3309
+ finish(false);
3310
+ return;
3311
+ }
3312
+ findTimeout = setTimeout(tryFind, FIND_RETRY_MS);
3313
+ };
3314
+ tryFind();
3315
+ });
3316
+ }
3317
+ function setCurrentItem(itemId, referenceList, componentIds) {
3318
+ currentItemId = itemId;
3319
+ if (referenceList) setReferences(referenceList, componentIds);
3320
+ else if (componentIds) ownComponents = new Set(componentIds);
3321
+ if (running && assetIndex.size) tagAssets();
3322
+ const selected = overlay.getSelectedTarget();
3323
+ const owner = selected ? encodedFrom(selected) : null;
3324
+ if (owner && !isCurrentItem(owner)) clearSelection();
3325
+ }
3326
+ function setAssets(assets) {
3327
+ const hadAssets = assetIndex.size > 0;
3328
+ assetIndex = createAssetIndex(assets);
3329
+ if (running && (hadAssets || assetIndex.size)) tagAssets();
3330
+ }
3331
+ function setReferences(referenceList, componentIds) {
3332
+ if (componentIds) ownComponents = new Set(componentIds);
3333
+ references = /* @__PURE__ */ new Map();
3334
+ for (const { id, field } of referenceList) {
3335
+ if (!references.has(id)) references.set(id, field);
3336
+ }
3337
+ }
3338
+ function setLocale(value) {
3339
+ locale = value;
3340
+ }
3341
+ function syncGuard() {
3342
+ if (running && guardEnabled) guard.start();
3343
+ else guard.stop();
3344
+ }
3345
+ function setNavigationGuard(enabled) {
3346
+ guardEnabled = enabled;
3347
+ syncGuard();
3348
+ }
3349
+ return {
3350
+ start,
3351
+ stop,
3352
+ setCurrentItem,
3353
+ setReferences,
3354
+ setAssets,
3355
+ setLocale,
3356
+ focusField,
3357
+ setNavigationGuard,
3358
+ allowNavigation: (href) => guard.allow(href)
3359
+ };
3360
+ }
3361
+
3362
+ // src/core/create-preview.ts
3363
+ var debug9 = createScopedLogger("create-preview");
3364
+ var controllerStores = /* @__PURE__ */ new WeakMap();
3365
+ function defaultNavigation() {
3366
+ return {
3367
+ navigate: (url) => window.location.assign(url),
3368
+ currentPath: () => window.location.pathname + window.location.search
3369
+ };
3370
+ }
3371
+ function safeEditUrl(href) {
3372
+ try {
3373
+ const url = new URL(href, window.location.href);
3374
+ return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
3375
+ } catch {
3376
+ return null;
3377
+ }
3378
+ }
3379
+ function buildSegments(data) {
3380
+ return [{ _id: "all_other_users", name: "All other users" }, ...data];
3381
+ }
3382
+ function resolveLocale(options) {
3383
+ const explicit = options?.locale;
3384
+ if (isLocale(explicit)) return explicit;
3385
+ if (typeof navigator !== "undefined") {
3386
+ const candidates = Array.isArray(navigator.languages) && navigator.languages.length ? navigator.languages : [navigator.language];
3387
+ const match = candidates.filter(Boolean).map((l2) => l2.toLowerCase().split("-")[0]).find(isLocale);
3388
+ if (match) return match;
3389
+ }
3390
+ return "en";
3391
+ }
3392
+ function createPreprPreview(opts = {}) {
3393
+ const { props, options } = opts;
3394
+ const navigation = opts.navigation ?? defaultNavigation();
3395
+ initDebugLogger(options?.debug ?? false);
3396
+ const noop = () => ({ destroy: () => {
3397
+ } });
3398
+ if (typeof window === "undefined" || typeof document === "undefined") {
3399
+ return noop();
3400
+ }
3401
+ const isIframe = window.parent !== window;
3402
+ const search = new URLSearchParams(window.location.search);
3403
+ const hideBar = search.get(PARAM_HIDE_BAR) === "true";
3404
+ if (hideBar) {
2269
3405
  debug9.log(`${PARAM_HIDE_BAR}=true \u2014 no visible toolbar`);
2270
3406
  }
2271
3407
  const mountUi = (options?.ui ?? true) && !isIframe && !hideBar;
@@ -2295,29 +3431,45 @@ function createPreprPreview(opts = {}) {
2295
3431
  el.connect(store, (key) => t(key, locale));
2296
3432
  }
2297
3433
  const editingEnabled = features.editMode || isIframe;
2298
- const stega = createStegaController({
2299
- // The CMS deep-link tooltip is chrome, so it follows the same decision as
2300
- // the bar: noise inside the editor (clicking the element itself requests
2301
- // the edit there), and unwanted in a headless preview that asked for no UI.
2302
- tooltip: mountUi,
2303
- // In the editor, ask the parent to focus the field instead of opening a new
2304
- // tab. Standalone previews keep the window.open behaviour.
2305
- onEdit: ({ href, id, field, locale: contentLocale }) => {
2306
- const safeHref = href ? safeEditUrl(href) : null;
2307
- if (href && !safeHref) {
2308
- debug9.warn("ignored edit request with unsupported href scheme");
2309
- return;
2310
- }
2311
- if (isIframe) {
2312
- sendPreprEvent("field_edit_requested", {
2313
- id,
2314
- field,
2315
- locale: contentLocale
2316
- });
2317
- } else if (safeHref) {
2318
- window.open(safeHref, "_blank", "noopener,noreferrer");
2319
- }
3434
+ const onEdit = ({
3435
+ href,
3436
+ id,
3437
+ field,
3438
+ locale: contentLocale,
3439
+ block,
3440
+ entryId,
3441
+ referenceField
3442
+ }) => {
3443
+ const safeHref = href ? safeEditUrl(href) : null;
3444
+ if (href && !safeHref) {
3445
+ debug9.warn("ignored edit request with unsupported href scheme");
3446
+ return;
2320
3447
  }
3448
+ if (isIframe) {
3449
+ sendPreprEvent("field_edit_requested", {
3450
+ id,
3451
+ field,
3452
+ locale: contentLocale,
3453
+ ...block !== void 0 && { block },
3454
+ ...entryId && { entryId },
3455
+ ...referenceField && { referenceField }
3456
+ });
3457
+ } else if (safeHref) {
3458
+ window.open(safeHref, "_blank", "noopener,noreferrer");
3459
+ }
3460
+ };
3461
+ const visualEditor = isIframe ? createVisualEditor({
3462
+ onEdit,
3463
+ locale,
3464
+ onNavigationBlocked: (href) => sendPreprEvent("navigation_blocked", { href })
3465
+ }) : null;
3466
+ const stega = visualEditor ?? createStegaController({
3467
+ // The edit-mode marks and hover label are chrome, so they follow the
3468
+ // same decision as the bar: unwanted in a headless preview that asked
3469
+ // for no UI.
3470
+ tooltip: mountUi,
3471
+ onEdit,
3472
+ locale
2321
3473
  });
2322
3474
  const autoClean = createStegaAutoClean({
2323
3475
  enabled: options?.autoClean
@@ -2340,10 +3492,30 @@ function createPreprPreview(opts = {}) {
2340
3492
  });
2341
3493
  const bridge = createIframeBridge(store, {
2342
3494
  allowedEditorOrigins: options?.allowedEditorOrigins,
3495
+ onHandshake: ({
3496
+ itemId,
3497
+ referencedIds,
3498
+ componentIds,
3499
+ uiLocale,
3500
+ navigationGuard,
3501
+ assets
3502
+ }) => {
3503
+ if (uiLocale) visualEditor?.setLocale(uiLocale);
3504
+ visualEditor?.setCurrentItem(itemId ?? null, referencedIds, componentIds);
3505
+ visualEditor?.setNavigationGuard(navigationGuard === true);
3506
+ if (assets) visualEditor?.setAssets(assets);
3507
+ },
3508
+ onAssets: (assets) => visualEditor?.setAssets(assets),
3509
+ onAllowNavigation: (href) => visualEditor?.allowNavigation(href),
3510
+ onReferences: (referencedIds, componentIds) => visualEditor?.setReferences(referencedIds, componentIds),
2343
3511
  // The editor selecting a field scrolls the matching element into view. The
2344
3512
  // lookup relies on the attributes the stega scan writes, so it finds
2345
3513
  // nothing until encoded content has been tagged.
2346
- onScrollToField: ({ field, id }) => {
3514
+ onScrollToField: ({ field, id, block, entryId, fieldById }) => {
3515
+ if (visualEditor) {
3516
+ void visualEditor.focusField({ field, id, block, entryId, fieldById });
3517
+ return;
3518
+ }
2347
3519
  if (!scrollToField({ field, id })) {
2348
3520
  debug9.log("no element on this page renders field", field);
2349
3521
  }
@@ -2374,6 +3546,1603 @@ function createPreprPreview(opts = {}) {
2374
3546
  return controller;
2375
3547
  }
2376
3548
 
3549
+ // src/core/preview-attrs.ts
3550
+ function previewAttrs(target, options) {
3551
+ if (!options.enabled || !target.id || !target.field) return {};
3552
+ const attrs = {
3553
+ "data-prepr-encoded": "",
3554
+ "data-prepr-id": target.id,
3555
+ "data-prepr-field": target.field
3556
+ };
3557
+ if (target.locale) attrs["data-prepr-locale"] = target.locale;
3558
+ if (target.entryId) attrs["data-prepr-entry-id"] = target.entryId;
3559
+ return attrs;
3560
+ }
3561
+
3562
+ // src/core/live-preview/normalize-query.ts
3563
+ var import_stega6 = require("@vercel/stega");
3564
+
3565
+ // src/core/live-preview/field-name.ts
3566
+ var UPPERCASE_BOUNDARY = /(.)(?=[A-Z])/g;
3567
+ function graphqlFieldName(apiId) {
3568
+ return apiId.replace(UPPERCASE_BOUNDARY, "$1_").toLowerCase();
3569
+ }
3570
+ function fieldKeyIn(record, apiId) {
3571
+ if (Object.prototype.hasOwnProperty.call(record, apiId)) return apiId;
3572
+ const name = graphqlFieldName(apiId);
3573
+ return Object.prototype.hasOwnProperty.call(record, name) ? name : void 0;
3574
+ }
3575
+ var TEXT_BODY_FIELDS = [
3576
+ { name: "body", plain: false },
3577
+ { name: "html", plain: false },
3578
+ { name: "text", plain: true }
3579
+ ];
3580
+ var TAG_PATTERN = /<[^>]+>/g;
3581
+ function plainTextFromHtml(html) {
3582
+ return html.replace(TAG_PATTERN, "");
3583
+ }
3584
+ function isTextEntry(record) {
3585
+ const typename = record.__typename;
3586
+ if (typeof typename === "string") return typename === "Text";
3587
+ return "html" in record || "text" in record && "format" in record;
3588
+ }
3589
+
3590
+ // src/core/live-preview/index-snapshot.ts
3591
+ var debug10 = createScopedLogger("live-preview");
3592
+ function indexSnapshot(data) {
3593
+ const index = /* @__PURE__ */ new Map();
3594
+ const visited = /* @__PURE__ */ new WeakSet();
3595
+ const path = [];
3596
+ function walk(node) {
3597
+ if (node === null || typeof node !== "object") return;
3598
+ if (visited.has(node)) return;
3599
+ visited.add(node);
3600
+ if (Array.isArray(node)) {
3601
+ for (let i2 = 0; i2 < node.length; i2++) {
3602
+ path.push(i2);
3603
+ walk(node[i2]);
3604
+ path.pop();
3605
+ }
3606
+ return;
3607
+ }
3608
+ const record = node;
3609
+ if (typeof record._id === "string") {
3610
+ const paths = index.get(record._id);
3611
+ if (paths) paths.push([...path]);
3612
+ else index.set(record._id, [[...path]]);
3613
+ } else if (typeof record.__typename === "string") {
3614
+ debug10.log("item without _id will not live-update", {
3615
+ __typename: record.__typename
3616
+ });
3617
+ }
3618
+ for (const key in record) {
3619
+ if (!Object.prototype.hasOwnProperty.call(record, key)) continue;
3620
+ path.push(key);
3621
+ walk(record[key]);
3622
+ path.pop();
3623
+ }
3624
+ }
3625
+ walk(data);
3626
+ return index;
3627
+ }
3628
+
3629
+ // src/core/live-preview/patch.ts
3630
+ var import_stega5 = require("@vercel/stega");
3631
+ var INDEX_SEGMENT2 = /^\d+$/;
3632
+ var FORBIDDEN_SEGMENTS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
3633
+ function isPlainObject(value) {
3634
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3635
+ }
3636
+ function mergeObject(current, incoming) {
3637
+ let changed = false;
3638
+ const next = { ...current };
3639
+ for (const key of Object.keys(current)) {
3640
+ if (!(key in incoming) || incoming[key] === void 0) continue;
3641
+ const value = isPlainObject(current[key]) && isPlainObject(incoming[key]) ? mergeObject(current[key], incoming[key]) : incoming[key];
3642
+ if (value !== current[key]) {
3643
+ next[key] = value;
3644
+ changed = true;
3645
+ }
3646
+ }
3647
+ return changed ? next : current;
3648
+ }
3649
+ function shapeLike(template, incoming) {
3650
+ const out = {};
3651
+ for (const key of Object.keys(template)) {
3652
+ const value = incoming[key];
3653
+ out[key] = value === void 0 ? null : isPlainObject(template[key]) && isPlainObject(value) ? shapeLike(template[key], value) : value;
3654
+ }
3655
+ return out;
3656
+ }
3657
+ function mergeStructured(current, incoming) {
3658
+ if (incoming === null || Array.isArray(incoming) && !incoming.length) {
3659
+ if (Array.isArray(current)) return current.length ? [] : current;
3660
+ return null;
3661
+ }
3662
+ const list = Array.isArray(incoming) ? incoming : [incoming];
3663
+ if (current === null || current === void 0) return incoming;
3664
+ if (Array.isArray(current)) {
3665
+ const template = current.find(isPlainObject);
3666
+ return list.map((entry) => {
3667
+ const match = current.find(
3668
+ (c2) => isPlainObject(c2) && c2._id !== void 0 && c2._id === entry._id
3669
+ );
3670
+ if (isPlainObject(match)) return mergeObject(match, entry);
3671
+ return isPlainObject(template) ? shapeLike(template, entry) : entry;
3672
+ });
3673
+ }
3674
+ if (isPlainObject(current)) return mergeObject(current, list[0]);
3675
+ return current;
3676
+ }
3677
+ function isPatchable(current) {
3678
+ return current === null || typeof current === "string" || typeof current === "number" || typeof current === "boolean";
3679
+ }
3680
+ function cloneNode(node) {
3681
+ return Array.isArray(node) ? [...node] : { ...node };
3682
+ }
3683
+ function patchSnapshot(snapshot, index, itemId, field, value) {
3684
+ const paths = index.get(itemId);
3685
+ if (!paths?.length) return snapshot;
3686
+ let root = snapshot;
3687
+ let changed = false;
3688
+ const markChanged = () => {
3689
+ changed = true;
3690
+ };
3691
+ for (const path of paths) {
3692
+ for (const [target, targetValue] of expandTextBody(
3693
+ root,
3694
+ path,
3695
+ field,
3696
+ value
3697
+ )) {
3698
+ root = patchAtPath(root, path, target, targetValue, markChanged);
3699
+ }
3700
+ }
3701
+ return changed ? root : snapshot;
3702
+ }
3703
+ function expandTextBody(root, path, field, value) {
3704
+ const segments = field.split(".");
3705
+ if (segments[segments.length - 1] !== "body" || typeof value !== "string") {
3706
+ return [[field, value]];
3707
+ }
3708
+ let node = root;
3709
+ for (const step of path) {
3710
+ node = node[step];
3711
+ }
3712
+ for (const segment of segments.slice(0, -1)) {
3713
+ if (node === null || typeof node !== "object") return [[field, value]];
3714
+ const record2 = node;
3715
+ node = INDEX_SEGMENT2.test(segment) ? record2[Number(segment)] : record2[fieldKeyIn(record2, segment) ?? segment];
3716
+ }
3717
+ if (node === null || typeof node !== "object" || Array.isArray(node)) {
3718
+ return [[field, value]];
3719
+ }
3720
+ const record = node;
3721
+ if (!isTextEntry(record)) return [[field, value]];
3722
+ const prefix = segments.slice(0, -1);
3723
+ const writes = [];
3724
+ for (const { name, plain } of TEXT_BODY_FIELDS) {
3725
+ if (!(name in record)) continue;
3726
+ writes.push([
3727
+ [...prefix, name].join("."),
3728
+ plain ? plainTextFromHtml(value) : value
3729
+ ]);
3730
+ }
3731
+ return writes.length ? writes : [[field, value]];
3732
+ }
3733
+ function patchAtPath(root, path, field, value, markChanged) {
3734
+ const segments = field.split(".");
3735
+ if (segments.some((s2) => FORBIDDEN_SEGMENTS.has(s2))) return root;
3736
+ let node = root;
3737
+ for (const step of path) {
3738
+ node = node[step];
3739
+ }
3740
+ const fullPath = [...path];
3741
+ for (const segment of segments) {
3742
+ let step = segment;
3743
+ if (INDEX_SEGMENT2.test(segment)) {
3744
+ step = Number(segment);
3745
+ } else if (node !== null && typeof node === "object") {
3746
+ step = fieldKeyIn(node, segment) ?? segment;
3747
+ }
3748
+ fullPath.push(step);
3749
+ node = node !== null && typeof node === "object" ? node[step] : void 0;
3750
+ }
3751
+ return writeAtPath(root, fullPath, value, markChanged);
3752
+ }
3753
+ function writeAtPath(root, fullPath, value, markChanged = () => {
3754
+ }) {
3755
+ if (!fullPath.length) return root;
3756
+ if (fullPath.some((s2) => FORBIDDEN_SEGMENTS.has(String(s2)))) return root;
3757
+ const last = fullPath.length - 1;
3758
+ let node = root;
3759
+ for (let i2 = 0; i2 < last; i2++) {
3760
+ if (node === null || typeof node !== "object") return root;
3761
+ node = node[fullPath[i2]];
3762
+ }
3763
+ if (node === null || typeof node !== "object") return root;
3764
+ const container = node;
3765
+ const key = fullPath[last];
3766
+ if (!(key in container)) return root;
3767
+ let next;
3768
+ if (value === null || typeof value === "object") {
3769
+ next = mergeStructured(container[key], value);
3770
+ } else if (!isPatchable(container[key])) {
3771
+ return root;
3772
+ } else {
3773
+ next = keepEditLink(container[key], value);
3774
+ }
3775
+ if (container[key] === next) return root;
3776
+ const newRoot = cloneNode(root);
3777
+ let cursor = newRoot;
3778
+ for (let i2 = 0; i2 < last; i2++) {
3779
+ const child = cloneNode(cursor[fullPath[i2]]);
3780
+ cursor[fullPath[i2]] = child;
3781
+ cursor = child;
3782
+ }
3783
+ cursor[key] = next;
3784
+ markChanged();
3785
+ return newRoot;
3786
+ }
3787
+ function listKeysOf(entry) {
3788
+ if (!isPlainObject(entry)) return [];
3789
+ const keys = [];
3790
+ if (typeof entry._id === "string") keys.push(entry._id);
3791
+ const first = Array.isArray(entry.items) ? entry.items[0] : null;
3792
+ if (isPlainObject(first) && typeof first._id === "string") {
3793
+ keys.push(first._id);
3794
+ }
3795
+ return keys;
3796
+ }
3797
+ function buildText(entry, template) {
3798
+ const body = typeof entry.body === "string" ? entry.body : "";
3799
+ const full = {
3800
+ __typename: "Text",
3801
+ _id: entry._id,
3802
+ body,
3803
+ html: body,
3804
+ text: plainTextFromHtml(body),
3805
+ format: entry.format ?? null
3806
+ };
3807
+ if (!template) return full;
3808
+ const out = {};
3809
+ for (const key of Object.keys(template)) {
3810
+ out[key] = key in full ? full[key] : null;
3811
+ }
3812
+ return out;
3813
+ }
3814
+ function syncList(current, entries, build) {
3815
+ if (current === null || current === void 0) {
3816
+ const built = syncList([], entries, build);
3817
+ return built.length ? built : current;
3818
+ }
3819
+ if (!Array.isArray(current)) return current;
3820
+ const byKey = /* @__PURE__ */ new Map();
3821
+ const templates = /* @__PURE__ */ new Map();
3822
+ for (const c2 of current) {
3823
+ for (const key of listKeysOf(c2)) byKey.set(key, c2);
3824
+ if (isPlainObject(c2) && typeof c2.__typename === "string") {
3825
+ if (!templates.has(c2.__typename)) templates.set(c2.__typename, c2);
3826
+ }
3827
+ }
3828
+ if (!entries.length) return current.length ? [] : current;
3829
+ if (current.length && !byKey.size) return current;
3830
+ if (current.length && !entries.some((e2) => byKey.has(e2._id))) return current;
3831
+ const next = [];
3832
+ for (const entry of entries) {
3833
+ const existing = byKey.get(entry._id);
3834
+ const built = existing === void 0 && entry.fields ? build?.(entry) : void 0;
3835
+ if (existing !== void 0) {
3836
+ next.push(existing);
3837
+ } else if (built) {
3838
+ next.push(built);
3839
+ } else if (entry.__typename === "Text") {
3840
+ next.push(buildText(entry, templates.get("Text")));
3841
+ }
3842
+ }
3843
+ const same = next.length === current.length && next.every((n2, i2) => n2 === current[i2]);
3844
+ return same ? current : next;
3845
+ }
3846
+ function syncListSnapshot(snapshot, index, itemId, field, entries) {
3847
+ const paths = index.get(itemId);
3848
+ if (!paths?.length) return snapshot;
3849
+ const fieldPath = field.split(".");
3850
+ if (fieldPath.some((s2) => FORBIDDEN_SEGMENTS.has(s2))) return snapshot;
3851
+ let root = snapshot;
3852
+ for (const path of paths) {
3853
+ root = syncListAtPath(root, [...path, ...fieldPath], entries);
3854
+ }
3855
+ return root;
3856
+ }
3857
+ function syncListAtPath(root, fullPath, entries, build) {
3858
+ if (!fullPath.length) return root;
3859
+ if (fullPath.some((s2) => FORBIDDEN_SEGMENTS.has(String(s2)))) return root;
3860
+ let node = root;
3861
+ for (const key of fullPath) {
3862
+ node = node !== null && typeof node === "object" ? node[key] : void 0;
3863
+ }
3864
+ const next = syncList(node, entries, build);
3865
+ if (next === node) return root;
3866
+ const newRoot = cloneNode(root);
3867
+ let cursor = newRoot;
3868
+ for (let i2 = 0; i2 < fullPath.length - 1; i2++) {
3869
+ const child = cloneNode(cursor[fullPath[i2]]);
3870
+ cursor[fullPath[i2]] = child;
3871
+ cursor = child;
3872
+ }
3873
+ cursor[fullPath[fullPath.length - 1]] = next;
3874
+ return newRoot;
3875
+ }
3876
+ function keepEditLink(current, value) {
3877
+ if (typeof current !== "string" || typeof value !== "string") return value;
3878
+ const { encoded } = (0, import_stega5.vercelStegaSplit)(current);
3879
+ if (!encoded || (0, import_stega5.vercelStegaSplit)(value).encoded) return value;
3880
+ return value + encoded;
3881
+ }
3882
+
3883
+ // src/core/live-preview/query-document.ts
3884
+ var NAME_START = /[_A-Za-z]/;
3885
+ var NAME_CONTINUE = /[_0-9A-Za-z]/;
3886
+ var PUNCT = /* @__PURE__ */ new Set([
3887
+ "!",
3888
+ "$",
3889
+ "&",
3890
+ "(",
3891
+ ")",
3892
+ ":",
3893
+ "=",
3894
+ "@",
3895
+ "[",
3896
+ "]",
3897
+ "{",
3898
+ "|",
3899
+ "}"
3900
+ ]);
3901
+ function tokenize(source) {
3902
+ const tokens = [];
3903
+ let i2 = 0;
3904
+ const n2 = source.length;
3905
+ while (i2 < n2) {
3906
+ const ch = source[i2];
3907
+ if (ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "," || ch === "\uFEFF") {
3908
+ i2++;
3909
+ } else if (ch === "#") {
3910
+ while (i2 < n2 && source[i2] !== "\n" && source[i2] !== "\r") i2++;
3911
+ } else if (ch === "." && source.startsWith("...", i2)) {
3912
+ tokens.push({ type: "punct", value: "..." });
3913
+ i2 += 3;
3914
+ } else if (PUNCT.has(ch)) {
3915
+ tokens.push({ type: "punct", value: ch });
3916
+ i2++;
3917
+ } else if (NAME_START.test(ch)) {
3918
+ const start = i2;
3919
+ while (i2 < n2 && NAME_CONTINUE.test(source[i2])) i2++;
3920
+ tokens.push({ type: "name", value: source.slice(start, i2) });
3921
+ } else if (ch === '"') {
3922
+ if (source.startsWith('"""', i2)) {
3923
+ i2 += 3;
3924
+ while (i2 < n2 && !source.startsWith('"""', i2)) {
3925
+ i2 += source.startsWith('\\"""', i2) ? 4 : 1;
3926
+ }
3927
+ if (i2 >= n2) throw new SyntaxError("Unterminated block string");
3928
+ i2 += 3;
3929
+ } else {
3930
+ i2++;
3931
+ while (i2 < n2 && source[i2] !== '"') {
3932
+ if (source[i2] === "\n" || source[i2] === "\r") {
3933
+ throw new SyntaxError("Unterminated string");
3934
+ }
3935
+ i2 += source[i2] === "\\" ? 2 : 1;
3936
+ }
3937
+ if (i2 >= n2) throw new SyntaxError("Unterminated string");
3938
+ i2++;
3939
+ }
3940
+ tokens.push({ type: "value" });
3941
+ } else if (ch === "-" || ch >= "0" && ch <= "9") {
3942
+ i2++;
3943
+ while (i2 < n2 && /[0-9.eE+-]/.test(source[i2])) i2++;
3944
+ tokens.push({ type: "value" });
3945
+ } else {
3946
+ throw new SyntaxError(`Unexpected character "${ch}"`);
3947
+ }
3948
+ }
3949
+ return tokens;
3950
+ }
3951
+ function parseSource(source, operationName) {
3952
+ const tokens = tokenize(source);
3953
+ let pos = 0;
3954
+ const peek = () => tokens[pos];
3955
+ const isPunct = (value) => {
3956
+ const t3 = tokens[pos];
3957
+ return t3?.type === "punct" && t3.value === value;
3958
+ };
3959
+ const expectPunct = (value) => {
3960
+ if (!isPunct(value)) throw new SyntaxError(`Expected "${value}"`);
3961
+ pos++;
3962
+ };
3963
+ const expectName = () => {
3964
+ const t3 = tokens[pos];
3965
+ if (t3?.type !== "name") throw new SyntaxError("Expected a name");
3966
+ pos++;
3967
+ return t3.value;
3968
+ };
3969
+ const skipParens = () => {
3970
+ expectPunct("(");
3971
+ let depth = 1;
3972
+ while (depth > 0) {
3973
+ const t3 = tokens[pos++];
3974
+ if (!t3) throw new SyntaxError("Unbalanced parentheses");
3975
+ if (t3.type === "punct" && t3.value === "(") depth++;
3976
+ else if (t3.type === "punct" && t3.value === ")") depth--;
3977
+ }
3978
+ };
3979
+ const skipDirectives = () => {
3980
+ while (isPunct("@")) {
3981
+ pos++;
3982
+ expectName();
3983
+ if (isPunct("(")) skipParens();
3984
+ }
3985
+ };
3986
+ const parseSelectionSet = () => {
3987
+ expectPunct("{");
3988
+ const selections = [];
3989
+ while (!isPunct("}")) {
3990
+ if (!peek()) throw new SyntaxError("Unterminated selection set");
3991
+ selections.push(parseSelection());
3992
+ }
3993
+ pos++;
3994
+ return selections;
3995
+ };
3996
+ const parseSelection = () => {
3997
+ if (isPunct("...")) {
3998
+ pos++;
3999
+ const t3 = peek();
4000
+ if (t3?.type === "name" && t3.value !== "on") {
4001
+ pos++;
4002
+ skipDirectives();
4003
+ return { kind: "spread", name: t3.value };
4004
+ }
4005
+ let on = null;
4006
+ if (t3?.type === "name") {
4007
+ pos++;
4008
+ on = expectName();
4009
+ }
4010
+ skipDirectives();
4011
+ return { kind: "inline", on, selections: parseSelectionSet() };
4012
+ }
4013
+ let name = expectName();
4014
+ const key = name;
4015
+ if (isPunct(":")) {
4016
+ pos++;
4017
+ name = expectName();
4018
+ }
4019
+ let hasArgs = false;
4020
+ if (isPunct("(")) {
4021
+ hasArgs = true;
4022
+ skipParens();
4023
+ }
4024
+ skipDirectives();
4025
+ const selections = isPunct("{") ? parseSelectionSet() : null;
4026
+ return { kind: "field", name, key, hasArgs, selections };
4027
+ };
4028
+ const fragments = /* @__PURE__ */ new Map();
4029
+ const operations = [];
4030
+ while (pos < tokens.length) {
4031
+ if (isPunct("{")) {
4032
+ operations.push({ name: null, selections: parseSelectionSet() });
4033
+ continue;
4034
+ }
4035
+ const keyword = expectName();
4036
+ if (keyword === "fragment") {
4037
+ const name = expectName();
4038
+ if (expectName() !== "on") throw new SyntaxError('Expected "on"');
4039
+ const on = expectName();
4040
+ skipDirectives();
4041
+ fragments.set(name, { on, selections: parseSelectionSet() });
4042
+ } else if (keyword === "query" || keyword === "mutation" || keyword === "subscription") {
4043
+ const t3 = peek();
4044
+ let name = null;
4045
+ if (t3?.type === "name") name = expectName();
4046
+ if (isPunct("(")) skipParens();
4047
+ skipDirectives();
4048
+ operations.push({ name, selections: parseSelectionSet() });
4049
+ } else {
4050
+ throw new SyntaxError(`Unexpected "${keyword}"`);
4051
+ }
4052
+ }
4053
+ return { operation: pickOperation(operations, operationName), fragments };
4054
+ }
4055
+ function pickOperation(operations, operationName) {
4056
+ const op = operationName ? operations.find((o2) => o2.name === operationName) : operations[0];
4057
+ if (!op) throw new SyntaxError("The document has no operation");
4058
+ return op.selections;
4059
+ }
4060
+ function fromAstSelections(set) {
4061
+ return set.selections.map((s2) => {
4062
+ if (s2.kind === "FragmentSpread")
4063
+ return { kind: "spread", name: s2.name.value };
4064
+ if (s2.kind === "InlineFragment") {
4065
+ return {
4066
+ kind: "inline",
4067
+ on: s2.typeCondition?.name.value ?? null,
4068
+ selections: fromAstSelections(s2.selectionSet)
4069
+ };
4070
+ }
4071
+ const name = s2.name.value;
4072
+ return {
4073
+ kind: "field",
4074
+ name,
4075
+ key: s2.alias?.value ?? name,
4076
+ hasArgs: Boolean(s2.arguments?.length),
4077
+ selections: s2.selectionSet ? fromAstSelections(s2.selectionSet) : null
4078
+ };
4079
+ });
4080
+ }
4081
+ function fromAst(doc, operationName) {
4082
+ const fragments = /* @__PURE__ */ new Map();
4083
+ const operations = [];
4084
+ for (const def of doc.definitions ?? []) {
4085
+ if (def.kind === "FragmentDefinition" && def.name && def.typeCondition && def.selectionSet) {
4086
+ fragments.set(def.name.value, {
4087
+ on: def.typeCondition.name.value,
4088
+ selections: fromAstSelections(def.selectionSet)
4089
+ });
4090
+ } else if (def.kind === "OperationDefinition" && def.selectionSet) {
4091
+ operations.push({
4092
+ name: def.name?.value ?? null,
4093
+ selections: fromAstSelections(def.selectionSet)
4094
+ });
4095
+ }
4096
+ }
4097
+ return { operation: pickOperation(operations, operationName), fragments };
4098
+ }
4099
+ var astCache = /* @__PURE__ */ new WeakMap();
4100
+ var sourceCache = /* @__PURE__ */ new Map();
4101
+ var SOURCE_CACHE_LIMIT = 200;
4102
+ function readQueryDocument(query, operationName) {
4103
+ const cacheKey = operationName ?? "";
4104
+ if (typeof query === "object" && query !== null && query.kind === "Document") {
4105
+ let byName = astCache.get(query);
4106
+ if (!byName) astCache.set(query, byName = /* @__PURE__ */ new Map());
4107
+ let parsed2 = byName.get(cacheKey);
4108
+ if (!parsed2) {
4109
+ parsed2 = fromAst(
4110
+ query,
4111
+ operationName
4112
+ );
4113
+ byName.set(cacheKey, parsed2);
4114
+ }
4115
+ return parsed2;
4116
+ }
4117
+ const source = String(query);
4118
+ const sourceKey = `${cacheKey}
4119
+ ${source}`;
4120
+ let parsed = sourceCache.get(sourceKey);
4121
+ if (!parsed) {
4122
+ parsed = parseSource(source, operationName);
4123
+ if (sourceCache.size >= SOURCE_CACHE_LIMIT) {
4124
+ sourceCache.delete(sourceCache.keys().next().value);
4125
+ }
4126
+ sourceCache.set(sourceKey, parsed);
4127
+ }
4128
+ return parsed;
4129
+ }
4130
+ var fieldsCache = /* @__PURE__ */ new WeakMap();
4131
+ function collectFields(selections, typename, doc, options = {}) {
4132
+ const cacheKey = `${options.strict ? "s" : "l"}:${typename ?? ""}`;
4133
+ let cached = fieldsCache.get(selections);
4134
+ if (!cached) {
4135
+ cached = /* @__PURE__ */ new Map();
4136
+ fieldsCache.set(selections, cached);
4137
+ }
4138
+ const hit = cached.get(cacheKey);
4139
+ if (hit) return hit;
4140
+ const fields = resolveFields(selections, typename, doc, options);
4141
+ cached.set(cacheKey, fields);
4142
+ return fields;
4143
+ }
4144
+ function resolveFields(selections, typename, doc, options) {
4145
+ const exact = /* @__PURE__ */ new Map();
4146
+ const loose = /* @__PURE__ */ new Map();
4147
+ const merged = /* @__PURE__ */ new Map();
4148
+ const walkedMatched = /* @__PURE__ */ new Set();
4149
+ const walkedLoose = /* @__PURE__ */ new Set();
4150
+ const add = (target, s2) => {
4151
+ let field = target.get(s2.key);
4152
+ if (!field) {
4153
+ field = { name: s2.name, key: s2.key, hasArgs: s2.hasArgs, selections: [] };
4154
+ target.set(s2.key, field);
4155
+ merged.set(field, /* @__PURE__ */ new Set());
4156
+ }
4157
+ const done = merged.get(field);
4158
+ if (s2.selections && !done.has(s2.selections)) {
4159
+ done.add(s2.selections);
4160
+ field.selections = [...field.selections, ...s2.selections];
4161
+ }
4162
+ };
4163
+ const applies = (on, list) => conditionMatches(on, typename) || typename !== void 0 && typeConditions(list, doc).includes(typename);
4164
+ const walk = (list, matched) => {
4165
+ for (const s2 of list) {
4166
+ if (s2.kind === "field") {
4167
+ add(matched ? exact : loose, s2);
4168
+ } else if (s2.kind === "inline") {
4169
+ walk(s2.selections, matched && applies(s2.on, s2.selections));
4170
+ } else {
4171
+ const fragment = doc.fragments.get(s2.name);
4172
+ if (!fragment) continue;
4173
+ const asMatched = matched && applies(fragment.on, fragment.selections);
4174
+ if (walkedMatched.has(fragment)) continue;
4175
+ if (!asMatched && walkedLoose.has(fragment)) continue;
4176
+ (asMatched ? walkedMatched : walkedLoose).add(fragment);
4177
+ walk(fragment.selections, asMatched);
4178
+ }
4179
+ }
4180
+ };
4181
+ walk(selections, true);
4182
+ if (!options.strict) {
4183
+ for (const [key, field] of loose) {
4184
+ if (!exact.has(key)) exact.set(key, field);
4185
+ }
4186
+ }
4187
+ return exact;
4188
+ }
4189
+ function conditionMatches(on, typename) {
4190
+ return on === null || typename === void 0 || on === typename;
4191
+ }
4192
+ var conditionsCache = /* @__PURE__ */ new WeakMap();
4193
+ function typeConditions(selections, doc) {
4194
+ const hit = conditionsCache.get(selections);
4195
+ if (hit) return hit;
4196
+ const names = /* @__PURE__ */ new Set();
4197
+ const seen = /* @__PURE__ */ new Set();
4198
+ const walk = (list) => {
4199
+ for (const s2 of list) {
4200
+ if (s2.kind === "inline") {
4201
+ if (s2.on) names.add(s2.on);
4202
+ walk(s2.selections);
4203
+ } else if (s2.kind === "spread") {
4204
+ const fragment = doc.fragments.get(s2.name);
4205
+ if (!fragment || seen.has(fragment)) continue;
4206
+ seen.add(fragment);
4207
+ names.add(fragment.on);
4208
+ walk(fragment.selections);
4209
+ }
4210
+ }
4211
+ };
4212
+ walk(selections);
4213
+ const conditions = [...names];
4214
+ conditionsCache.set(selections, conditions);
4215
+ return conditions;
4216
+ }
4217
+
4218
+ // src/core/live-preview/validate.ts
4219
+ function isScalar(v2) {
4220
+ return typeof v2 === "string" || typeof v2 === "number" || typeof v2 === "boolean";
4221
+ }
4222
+ var MAX_DEPTH = 3;
4223
+ var MAX_ENTRIES = 50;
4224
+ var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
4225
+ var SAFE_URL = /^https?:\/\//i;
4226
+ var URL_KEY = /^(?:url|href|src|link)$|(?:_url|Url)$/;
4227
+ var URL_IGNORED_ANYWHERE = /[\t\n\r]/g;
4228
+ var SCRIPT_SCHEME = /^(?:javascript|vbscript|data):/i;
4229
+ function isSafeLinkValue(value) {
4230
+ const stripped = value.replace(URL_IGNORED_ANYWHERE, "");
4231
+ let start = 0;
4232
+ while (start < stripped.length && stripped.charCodeAt(start) <= 32) start++;
4233
+ return !SCRIPT_SCHEME.test(stripped.slice(start));
4234
+ }
4235
+ function isUrlKey(key) {
4236
+ return URL_KEY.test(key);
4237
+ }
4238
+ function isSafeKeyValue(key, value) {
4239
+ if (typeof value !== "string") return true;
4240
+ if (key === "url") return SAFE_URL.test(value);
4241
+ return !isUrlKey(key) || isSafeLinkValue(value);
4242
+ }
4243
+ function isLiveValue(v2, depth = 0) {
4244
+ if (v2 === null || isScalar(v2)) return true;
4245
+ if (depth >= MAX_DEPTH) return false;
4246
+ if (Array.isArray(v2)) {
4247
+ return depth === 0 && v2.length <= MAX_ENTRIES && v2.every((entry) => isPlainRecord(entry) && isLiveValue(entry, depth + 1));
4248
+ }
4249
+ if (!isPlainRecord(v2)) return false;
4250
+ const keys = Object.keys(v2);
4251
+ if (keys.length > MAX_ENTRIES) return false;
4252
+ return keys.every((key) => {
4253
+ if (FORBIDDEN_KEYS.has(key)) return false;
4254
+ const value = v2[key];
4255
+ if (!isSafeKeyValue(key, value)) return false;
4256
+ return !Array.isArray(value) && isLiveValue(value, depth + 1);
4257
+ });
4258
+ }
4259
+ function isLiveFieldChange(field, value) {
4260
+ if (!isLiveValue(value)) return false;
4261
+ const name = field.slice(field.lastIndexOf(".") + 1);
4262
+ return typeof value !== "string" || !isUrlKey(name) || isSafeLinkValue(value);
4263
+ }
4264
+ var MAX_LIST_ENTRIES = 200;
4265
+ function parseListEntries(value) {
4266
+ if (!Array.isArray(value) || value.length > MAX_LIST_ENTRIES) return null;
4267
+ const list = [];
4268
+ for (const raw of value) {
4269
+ if (!isPlainRecord(raw) || typeof raw._id !== "string" || !raw._id) {
4270
+ return null;
4271
+ }
4272
+ const entry = { _id: raw._id };
4273
+ if (typeof raw.__typename === "string") entry.__typename = raw.__typename;
4274
+ if (typeof raw.body === "string") entry.body = raw.body;
4275
+ if (typeof raw.format === "string" || raw.format === null) {
4276
+ entry.format = raw.format;
4277
+ }
4278
+ if (typeof raw.typeName === "string" && raw.typeName.length <= 200) {
4279
+ entry.typeName = raw.typeName;
4280
+ }
4281
+ if (raw.fields !== void 0) {
4282
+ if (!isPlainRecord(raw.fields) || !isFieldValue(raw.fields, 0)) {
4283
+ return null;
4284
+ }
4285
+ entry.fields = raw.fields;
4286
+ }
4287
+ list.push(entry);
4288
+ }
4289
+ return list;
4290
+ }
4291
+ function isPlainRecord(v2) {
4292
+ return v2 !== null && typeof v2 === "object" && Object.getPrototypeOf(v2) === Object.prototype;
4293
+ }
4294
+ var MAX_FIELD_DEPTH = 6;
4295
+ var MAX_FIELD_KEYS = 100;
4296
+ function isFieldValue(v2, depth) {
4297
+ if (v2 === null || isScalar(v2)) return true;
4298
+ if (depth >= MAX_FIELD_DEPTH) return false;
4299
+ if (Array.isArray(v2)) {
4300
+ return v2.length <= MAX_ENTRIES && v2.every(
4301
+ (entry) => isScalar(entry) || isPlainRecord(entry) && isFieldValue(entry, depth + 1)
4302
+ );
4303
+ }
4304
+ if (!isPlainRecord(v2)) return false;
4305
+ const keys = Object.keys(v2);
4306
+ if (keys.length > MAX_FIELD_KEYS) return false;
4307
+ return keys.every((key) => {
4308
+ if (FORBIDDEN_KEYS.has(key)) return false;
4309
+ const value = v2[key];
4310
+ if (!isSafeKeyValue(key, value)) return false;
4311
+ return isFieldValue(value, depth + 1);
4312
+ });
4313
+ }
4314
+ var MAX_EDIT_LENGTH = 1e3;
4315
+ function parseEditTarget(raw) {
4316
+ if (!isPlainRecord(raw)) return void 0;
4317
+ const { item, field } = raw;
4318
+ if (typeof item !== "string" || !item || item.length > MAX_EDIT_LENGTH) {
4319
+ return void 0;
4320
+ }
4321
+ if (typeof field !== "string" || !field || field.length > MAX_EDIT_LENGTH) {
4322
+ return void 0;
4323
+ }
4324
+ return { item, field };
4325
+ }
4326
+
4327
+ // src/core/live-preview/normalize-query.ts
4328
+ var debug11 = createScopedLogger("live-preview:normalize");
4329
+ var MAX_LOG_ENTRIES = 500;
4330
+ var MAX_LOG_SOURCE_LENGTH = 1e6;
4331
+ var INDEX_SEGMENT3 = /^\d+$/;
4332
+ var FORBIDDEN_SEGMENTS2 = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
4333
+ var ENVELOPE_KEYS = /* @__PURE__ */ new Set(["data", "errors", "extensions"]);
4334
+ function parsePatchLog(raw) {
4335
+ let value = raw;
4336
+ if (typeof value === "string") {
4337
+ if (!value || value.length > MAX_LOG_SOURCE_LENGTH) return [];
4338
+ try {
4339
+ value = JSON.parse(value);
4340
+ } catch {
4341
+ return [];
4342
+ }
4343
+ }
4344
+ if (!Array.isArray(value)) return [];
4345
+ const log = [];
4346
+ for (const entry of value.slice(-MAX_LOG_ENTRIES)) {
4347
+ if (!isPlainRecord(entry)) continue;
4348
+ const { type, itemId, field } = entry;
4349
+ if (typeof itemId !== "string" || !itemId) continue;
4350
+ if (typeof field !== "string" || !field) continue;
4351
+ if (type === "field" && isLiveFieldChange(field, entry.value)) {
4352
+ const edit = parseEditTarget(entry.edit);
4353
+ log.push(
4354
+ edit ? { type, itemId, field, value: entry.value, edit } : { type, itemId, field, value: entry.value }
4355
+ );
4356
+ } else if (type === "list") {
4357
+ const entries = parseListEntries(entry.entries);
4358
+ if (entries) log.push({ type, itemId, field, entries });
4359
+ }
4360
+ }
4361
+ return log;
4362
+ }
4363
+ function normalizeQuery(query, result, options = {}) {
4364
+ return applyPatchLog(
4365
+ query,
4366
+ result,
4367
+ parsePatchLog(options.log),
4368
+ options.operationName
4369
+ );
4370
+ }
4371
+ function applyPatchLog(query, result, log, operationName) {
4372
+ if (!log.length || result === null || typeof result !== "object") {
4373
+ return result;
4374
+ }
4375
+ if (isEnvelope(result)) {
4376
+ const data = applyPatchLog(query, result.data, log, operationName);
4377
+ return data === result.data ? result : { ...result, data };
4378
+ }
4379
+ let doc = null;
4380
+ try {
4381
+ doc = readQueryDocument(query, operationName);
4382
+ } catch (error) {
4383
+ debug11.log("could not read the query; applying fields by literal path", {
4384
+ error: String(error)
4385
+ });
4386
+ }
4387
+ let root = result;
4388
+ let index = null;
4389
+ for (const patch of log) {
4390
+ try {
4391
+ index ?? (index = indexSnapshot(root));
4392
+ const next = applyPatch(root, index, patch, doc, result);
4393
+ if (next !== root) {
4394
+ root = next;
4395
+ if (patch.type === "list" || !isScalarValue(patch.value)) {
4396
+ index = null;
4397
+ }
4398
+ }
4399
+ } catch (error) {
4400
+ debug11.log("could not apply a change", {
4401
+ itemId: patch.itemId,
4402
+ field: patch.field,
4403
+ error: String(error)
4404
+ });
4405
+ }
4406
+ }
4407
+ return root;
4408
+ }
4409
+ function isScalarValue(value) {
4410
+ return value === null || typeof value !== "object";
4411
+ }
4412
+ function applyPatch(root, index, patch, doc, result) {
4413
+ const ownerPaths = index.get(patch.itemId);
4414
+ if (!ownerPaths?.length) return root;
4415
+ const segments = patch.field.split(".");
4416
+ if (segments.some((s2) => !s2 || FORBIDDEN_SEGMENTS2.has(s2))) return root;
4417
+ const targets = [];
4418
+ const plain = /* @__PURE__ */ new Set();
4419
+ for (const ownerPath of ownerPaths) {
4420
+ if (doc) {
4421
+ const resolved = resolveTargets(root, doc, ownerPath, segments);
4422
+ root = resolved.root;
4423
+ targets.push(...resolved.targets);
4424
+ resolved.plain.forEach((target) => plain.add(target));
4425
+ } else {
4426
+ targets.push([...ownerPath, ...segments.map(toPathSegment)]);
4427
+ }
4428
+ }
4429
+ if (!targets.length) {
4430
+ debug11.log("no field in the query matches", {
4431
+ itemId: patch.itemId,
4432
+ field: patch.field
4433
+ });
4434
+ return root;
4435
+ }
4436
+ if (patch.type === "field") {
4437
+ for (const target of targets) {
4438
+ const pushed = plain.has(target) && typeof patch.value === "string" ? plainTextFromHtml(patch.value) : patch.value;
4439
+ let value = keepEditLink(readAtPath(root, target), pushed);
4440
+ if (patch.edit && typeof value === "string" && !(0, import_stega6.vercelStegaSplit)(value).encoded) {
4441
+ value = editLinksFor(result, patch.edit.item)?.encode(
4442
+ value,
4443
+ patch.edit.field
4444
+ ) ?? value;
4445
+ }
4446
+ root = writeAtPath(root, target, value);
4447
+ }
4448
+ } else {
4449
+ for (const target of targets) {
4450
+ const selections = doc ? selectionsAt(root, doc, target) : null;
4451
+ const build = doc && selections ? (entry) => buildEntry(doc, selections, entry, {
4452
+ links: editLinks(result, entry),
4453
+ lists: listKeysIn(result)
4454
+ }) : void 0;
4455
+ root = syncListAtPath(root, target, patch.entries, build);
4456
+ }
4457
+ }
4458
+ return root;
4459
+ }
4460
+ function readAtPath(root, path) {
4461
+ let node = root;
4462
+ for (const step of path) {
4463
+ if (node === null || typeof node !== "object") return void 0;
4464
+ node = node[step];
4465
+ }
4466
+ return node;
4467
+ }
4468
+ function isEnvelope(value) {
4469
+ if (Array.isArray(value) || !("data" in value)) return false;
4470
+ return Object.keys(value).every((key) => ENVELOPE_KEYS.has(key));
4471
+ }
4472
+ function toPathSegment(segment) {
4473
+ return INDEX_SEGMENT3.test(segment) ? Number(segment) : segment;
4474
+ }
4475
+ function typenameOf(node) {
4476
+ const typename = node.__typename;
4477
+ return typeof typename === "string" ? typename : void 0;
4478
+ }
4479
+ function selectionsAt(root, doc, path) {
4480
+ let node = root;
4481
+ let selections = doc.operation;
4482
+ for (const step of path) {
4483
+ if (Array.isArray(node)) {
4484
+ node = node[step];
4485
+ continue;
4486
+ }
4487
+ if (node === null || typeof node !== "object") return null;
4488
+ const field = collectFields(selections, typenameOf(node), doc).get(
4489
+ String(step)
4490
+ );
4491
+ if (!field) return null;
4492
+ selections = field.selections;
4493
+ node = node[String(step)];
4494
+ }
4495
+ return selections;
4496
+ }
4497
+ function resolveTargets(root, doc, ownerPath, segments) {
4498
+ let owner = root;
4499
+ for (const step of ownerPath) {
4500
+ owner = owner[step];
4501
+ }
4502
+ const selections = selectionsAt(root, doc, ownerPath);
4503
+ if (!selections) return { root, targets: [], plain: /* @__PURE__ */ new Set() };
4504
+ let current = root;
4505
+ const out = [];
4506
+ const plain = /* @__PURE__ */ new Set();
4507
+ const walk = (node, sel, i2, path) => {
4508
+ if (i2 === segments.length) {
4509
+ out.push(path);
4510
+ return;
4511
+ }
4512
+ const segment = segments[i2];
4513
+ if (Array.isArray(node)) {
4514
+ if (INDEX_SEGMENT3.test(segment)) {
4515
+ const position = Number(segment);
4516
+ if (position < node.length) {
4517
+ walk(node[position], sel, i2 + 1, [...path, position]);
4518
+ }
4519
+ } else if (segment === "items") {
4520
+ walk(node, sel, i2 + 1, path);
4521
+ }
4522
+ return;
4523
+ }
4524
+ if (node === null || typeof node !== "object") return;
4525
+ const record = node;
4526
+ const wanted = graphqlFieldName(segment);
4527
+ const textBody = i2 === segments.length - 1 && segment === "body" && isTextEntry(record) ? TEXT_BODY_FIELDS : null;
4528
+ let matched = false;
4529
+ for (const field of collectFields(sel, typenameOf(node), doc).values()) {
4530
+ const alias = textBody?.find((f3) => f3.name === field.name);
4531
+ if (field.name !== segment && field.name !== wanted && !alias) continue;
4532
+ if (!Object.prototype.hasOwnProperty.call(record, field.key)) continue;
4533
+ matched = true;
4534
+ const fieldPath = [...path, field.key];
4535
+ if (alias?.plain) plain.add(fieldPath);
4536
+ let value = record[field.key];
4537
+ const next = segments[i2 + 1];
4538
+ if (value === null && field.selections.length && next !== void 0 && next !== "items" && !INDEX_SEGMENT3.test(next)) {
4539
+ const typename = resolveTypename(
4540
+ doc,
4541
+ field.selections,
4542
+ void 0,
4543
+ void 0
4544
+ );
4545
+ if (typename !== void 0) {
4546
+ value = fillObject(doc, field.selections, typename, {}, void 0, {
4547
+ links: null,
4548
+ lists: listKeysIn(root)
4549
+ });
4550
+ current = writeAtPath(current, fieldPath, value);
4551
+ }
4552
+ }
4553
+ walk(value, field.selections, i2 + 1, fieldPath);
4554
+ }
4555
+ if (!matched && segment === "items") walk(node, sel, i2 + 1, path);
4556
+ };
4557
+ walk(owner, selections, 0, ownerPath);
4558
+ return { root: current, targets: out, plain };
4559
+ }
4560
+ var NON_ALPHANUMERIC = /[^a-z0-9]/gi;
4561
+ var typeKey = (name) => name.replace(NON_ALPHANUMERIC, "").toLowerCase();
4562
+ function resolveTypename(doc, selections, typename, typeName) {
4563
+ const known = typeConditions(selections, doc);
4564
+ const explicit = typeof typename === "string" ? typename : void 0;
4565
+ if (!known.length) return explicit ?? null;
4566
+ if (explicit && known.includes(explicit)) return explicit;
4567
+ for (const candidate of [explicit, typeName]) {
4568
+ if (typeof candidate !== "string" || !candidate) continue;
4569
+ const match = known.find((name) => typeKey(name) === typeKey(candidate));
4570
+ if (match) return match;
4571
+ }
4572
+ const named = explicit !== void 0 || typeof typeName === "string";
4573
+ return known.length === 1 && !named ? known[0] : void 0;
4574
+ }
4575
+ function buildEntry(doc, selections, entry, ctx) {
4576
+ const typename = resolveTypename(
4577
+ doc,
4578
+ selections,
4579
+ entry.__typename,
4580
+ entry.typeName
4581
+ );
4582
+ if (typename === void 0) return void 0;
4583
+ return fillObject(
4584
+ doc,
4585
+ selections,
4586
+ typename,
4587
+ entry.fields ?? {},
4588
+ entry._id,
4589
+ ctx
4590
+ );
4591
+ }
4592
+ function fillObject(doc, selections, typename, values, id, ctx) {
4593
+ const out = {};
4594
+ const { links } = ctx;
4595
+ const lists = ctx.lists(typename);
4596
+ const edit = isPlainRecord(values.__edit) ? values.__edit : null;
4597
+ const apiIdOf = /* @__PURE__ */ new Map();
4598
+ for (const key of Object.keys(values)) {
4599
+ apiIdOf.set(key, key);
4600
+ const name = graphqlFieldName(key);
4601
+ if (!apiIdOf.has(name)) apiIdOf.set(name, key);
4602
+ }
4603
+ if (edit && isPlainRecord(edit.apiIds)) {
4604
+ for (const [name, apiId] of Object.entries(edit.apiIds)) {
4605
+ if (typeof apiId === "string") apiIdOf.set(name, apiId);
4606
+ }
4607
+ }
4608
+ const valueOf = (name) => {
4609
+ if (Object.prototype.hasOwnProperty.call(values, name)) return values[name];
4610
+ const key = apiIdOf.get(name);
4611
+ return key !== void 0 && key in values ? values[key] : void 0;
4612
+ };
4613
+ const editField = (name) => {
4614
+ if (!edit) return null;
4615
+ if (typeof edit.field === "string")
4616
+ return name === "body" ? edit.field : null;
4617
+ if (typeof edit.path !== "string") return null;
4618
+ const apiId = apiIdOf.get(name) ?? name;
4619
+ const text = Array.isArray(edit.text) ? edit.text : [];
4620
+ if (!text.includes(apiId) && !text.includes(name)) return null;
4621
+ return `${edit.path}.items.${apiId}`;
4622
+ };
4623
+ const fields = collectFields(selections, typename ?? void 0, doc, {
4624
+ strict: true
4625
+ });
4626
+ for (const field of fields.values()) {
4627
+ if (field.name === "__typename") {
4628
+ out[field.key] = typename;
4629
+ } else if (field.name === "_id") {
4630
+ out[field.key] = typeof id === "string" ? id : values._id ?? null;
4631
+ } else if (field.selections.length) {
4632
+ const value = valueOf(field.name);
4633
+ out[field.key] = value == null && lists.has(field.key) ? [] : fillNested(doc, field.selections, value, ctx);
4634
+ } else {
4635
+ const value = valueOf(field.name);
4636
+ if (Array.isArray(value) && value.every(isScalarItem)) {
4637
+ out[field.key] = value;
4638
+ continue;
4639
+ }
4640
+ if (value == null && lists.has(field.key)) {
4641
+ out[field.key] = [];
4642
+ continue;
4643
+ }
4644
+ const scalar = value === void 0 || value !== null && typeof value === "object" ? null : value;
4645
+ const target = typeof scalar === "string" ? editField(field.name) : null;
4646
+ out[field.key] = target && links ? links.encode(scalar, target) : scalar;
4647
+ }
4648
+ }
4649
+ return out;
4650
+ }
4651
+ function fillNested(doc, selections, value, ctx) {
4652
+ const one = (item) => {
4653
+ if (!isPlainRecord(item)) return null;
4654
+ const typename = resolveTypename(
4655
+ doc,
4656
+ selections,
4657
+ item.__typename,
4658
+ item.typeName
4659
+ );
4660
+ if (typename === void 0) return null;
4661
+ return fillObject(doc, selections, typename, item, item._id, ctx);
4662
+ };
4663
+ if (Array.isArray(value)) return value.map(one).filter((v2) => v2 !== null);
4664
+ return value === void 0 ? null : one(value);
4665
+ }
4666
+ function isScalarItem(value) {
4667
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
4668
+ }
4669
+ var NO_KEYS = /* @__PURE__ */ new Set();
4670
+ var listKeysCache = /* @__PURE__ */ new WeakMap();
4671
+ function listKeysIn(result) {
4672
+ return (typename) => {
4673
+ if (!typename || result === null || typeof result !== "object") {
4674
+ return NO_KEYS;
4675
+ }
4676
+ let byType = listKeysCache.get(result);
4677
+ if (!byType) {
4678
+ byType = /* @__PURE__ */ new Map();
4679
+ const seen = /* @__PURE__ */ new WeakSet();
4680
+ const walk = (node) => {
4681
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
4682
+ seen.add(node);
4683
+ if (Array.isArray(node)) {
4684
+ node.forEach(walk);
4685
+ return;
4686
+ }
4687
+ const record = node;
4688
+ const type = typeof record.__typename === "string" ? record.__typename : null;
4689
+ for (const [key, value] of Object.entries(record)) {
4690
+ if (type && Array.isArray(value)) {
4691
+ let keys = byType.get(type);
4692
+ if (!keys) byType.set(type, keys = /* @__PURE__ */ new Set());
4693
+ keys.add(key);
4694
+ }
4695
+ walk(value);
4696
+ }
4697
+ };
4698
+ walk(result);
4699
+ listKeysCache.set(result, byType);
4700
+ }
4701
+ return byType.get(typename) ?? NO_KEYS;
4702
+ };
4703
+ }
4704
+ var EDIT_PATH = /\/content\/edit\/[^/?#]+/;
4705
+ function editLinks(result, entry) {
4706
+ const edit = entry.fields?.__edit;
4707
+ if (!isPlainRecord(edit) || typeof edit.item !== "string") return null;
4708
+ return editLinksFor(result, edit.item);
4709
+ }
4710
+ var ITEM_ID = /^[A-Za-z0-9_-]+$/;
4711
+ function editLinksFor(result, item) {
4712
+ if (!ITEM_ID.test(item)) return null;
4713
+ const template = findEditLink(result);
4714
+ if (!template) return null;
4715
+ return {
4716
+ encode(text, field) {
4717
+ if ((0, import_stega6.vercelStegaSplit)(text).encoded) return text;
4718
+ let href;
4719
+ try {
4720
+ href = new URL(template.href);
4721
+ } catch {
4722
+ return text;
4723
+ }
4724
+ href.pathname = href.pathname.replace(
4725
+ EDIT_PATH,
4726
+ () => `/content/edit/${item}`
4727
+ );
4728
+ href.searchParams.set("field", field);
4729
+ const link = href.toString().replace(/%2E/gi, ".").replace(/%2F/gi, "/");
4730
+ return (0, import_stega6.vercelStegaCombine)(text, { origin: template.origin, href: link });
4731
+ }
4732
+ };
4733
+ }
4734
+ var linkCache = /* @__PURE__ */ new WeakMap();
4735
+ function findEditLink(root) {
4736
+ if (root === null || typeof root !== "object") return null;
4737
+ if (linkCache.has(root)) return linkCache.get(root) ?? null;
4738
+ let found = null;
4739
+ const seen = /* @__PURE__ */ new WeakSet();
4740
+ const walk = (node) => {
4741
+ if (found) return;
4742
+ if (typeof node === "string") {
4743
+ if (!(0, import_stega6.vercelStegaSplit)(node).encoded) return;
4744
+ try {
4745
+ const decoded = (0, import_stega6.vercelStegaDecode)(node);
4746
+ if (typeof decoded?.origin === "string" && typeof decoded.href === "string" && EDIT_PATH.test(decoded.href)) {
4747
+ found = { origin: decoded.origin, href: decoded.href };
4748
+ }
4749
+ } catch {
4750
+ }
4751
+ return;
4752
+ }
4753
+ if (node === null || typeof node !== "object" || seen.has(node)) return;
4754
+ seen.add(node);
4755
+ for (const value of Object.values(node)) walk(value);
4756
+ };
4757
+ walk(root);
4758
+ linkCache.set(root, found);
4759
+ return found;
4760
+ }
4761
+
4762
+ // src/core/live-preview/bridge-events.ts
4763
+ var debug12 = createScopedLogger("live-preview:bridge");
4764
+ function createLiveBridge(store, options = {}) {
4765
+ let parentOrigin = null;
4766
+ const onMessage = (evt) => {
4767
+ const data = evt?.data;
4768
+ if (data?.event === "prepr:initVE" && !parentOrigin) {
4769
+ if (isAllowedEditorOrigin(evt.origin, options.allowedEditorOrigins?.())) {
4770
+ parentOrigin = evt.origin;
4771
+ } else {
4772
+ debug12.warn("ignored live preview handshake from origin", evt.origin);
4773
+ }
4774
+ return;
4775
+ }
4776
+ const trusted = parentOrigin ?? getTrustedParentOrigin();
4777
+ if (!trusted || evt.origin !== trusted) return;
4778
+ if (data?.event === "prepr:fieldChange") {
4779
+ if (typeof data.itemId === "string" && typeof data.field === "string" && data.field && isLiveFieldChange(data.field, data.value)) {
4780
+ const edit = parseEditTarget(data.edit);
4781
+ if (edit) store.pushPatch(data.itemId, data.field, data.value, edit);
4782
+ else store.pushPatch(data.itemId, data.field, data.value);
4783
+ } else {
4784
+ debug12.log("dropped malformed fieldChange", data);
4785
+ }
4786
+ return;
4787
+ }
4788
+ if (data?.event === "prepr:listChange") {
4789
+ const list = parseListEntries(data.entries);
4790
+ if (typeof data.itemId === "string" && typeof data.field === "string" && data.field && list) {
4791
+ store.pushList(data.itemId, data.field, list);
4792
+ } else {
4793
+ debug12.log("dropped malformed listChange", data);
4794
+ }
4795
+ return;
4796
+ }
4797
+ if (data?.event === "prepr:itemChanged") {
4798
+ if (typeof data.itemId === "string") {
4799
+ store.invalidate(data.itemId);
4800
+ } else {
4801
+ debug12.log("dropped malformed itemChanged", data);
4802
+ }
4803
+ }
4804
+ };
4805
+ return {
4806
+ start() {
4807
+ window.addEventListener("message", onMessage);
4808
+ sendPreprEvent(
4809
+ "live_ready",
4810
+ options.strictMode?.() ? { strictMode: true } : void 0,
4811
+ { allowUntrustedTarget: true }
4812
+ );
4813
+ },
4814
+ stop() {
4815
+ window.removeEventListener("message", onMessage);
4816
+ }
4817
+ };
4818
+ }
4819
+
4820
+ // src/core/live-preview/live-store.ts
4821
+ var debug13 = createScopedLogger("live-preview");
4822
+ var INVALIDATE_DEBOUNCE_MS = 150;
4823
+ var MAX_LOG_ENTRIES2 = 500;
4824
+ function withPatch(log, patch) {
4825
+ let previous = -1;
4826
+ for (let i2 = log.length - 1; i2 >= 0; i2--) {
4827
+ const p2 = log[i2];
4828
+ if (p2.type === patch.type && p2.itemId === patch.itemId && p2.field === patch.field) {
4829
+ previous = i2;
4830
+ break;
4831
+ }
4832
+ }
4833
+ if (previous === -1) return [...log, patch];
4834
+ const since = log.slice(previous + 1);
4835
+ const listPrefix = `${patch.field}.`;
4836
+ const dependsOnPosition = since.some(
4837
+ (p2) => p2.type === "list" || patch.type === "list" && p2.itemId === patch.itemId && p2.field.startsWith(listPrefix)
4838
+ );
4839
+ if (dependsOnPosition) return [...log, patch];
4840
+ return [...log.slice(0, previous), ...since, patch];
4841
+ }
4842
+ function createLiveStore(options = {}) {
4843
+ const accepts = (patch) => options.accept ? options.accept(patch) : true;
4844
+ const entries = /* @__PURE__ */ new Set();
4845
+ const invalidateListeners = /* @__PURE__ */ new Set();
4846
+ const pendingInvalidates = /* @__PURE__ */ new Map();
4847
+ let defaultFetcher = null;
4848
+ let log = [];
4849
+ const logListeners = /* @__PURE__ */ new Set();
4850
+ function record(patch) {
4851
+ log = withPatch(log, patch).slice(-MAX_LOG_ENTRIES2);
4852
+ logListeners.forEach((fn) => fn(log));
4853
+ }
4854
+ function notify(entry) {
4855
+ entry.listeners.forEach((fn) => fn());
4856
+ }
4857
+ async function refetch(entry) {
4858
+ const fetcher = entry.opts.fetcher ?? defaultFetcher;
4859
+ if (!fetcher || entry.opts.query == null) return;
4860
+ const token = ++entry.fetchToken;
4861
+ try {
4862
+ const result = await fetcher(entry.opts.query, entry.opts.variables);
4863
+ if (token !== entry.fetchToken || !entries.has(entry)) return;
4864
+ entry.snapshot = result;
4865
+ entry.index = indexSnapshot(result);
4866
+ notify(entry);
4867
+ } catch (error) {
4868
+ debug13.log("refetch failed, keeping previous snapshot", error);
4869
+ }
4870
+ }
4871
+ function runInvalidate(itemId) {
4872
+ pendingInvalidates.delete(itemId);
4873
+ invalidateListeners.forEach((fn) => fn(itemId));
4874
+ for (const entry of entries) {
4875
+ if (entry.index.has(itemId)) void refetch(entry);
4876
+ }
4877
+ }
4878
+ return {
4879
+ register(data, opts = {}) {
4880
+ const entry = {
4881
+ snapshot: data,
4882
+ index: indexSnapshot(data),
4883
+ opts,
4884
+ listeners: /* @__PURE__ */ new Set(),
4885
+ fetchToken: 0
4886
+ };
4887
+ for (const patch of log) {
4888
+ if (patch.type === "field") {
4889
+ entry.snapshot = patchSnapshot(
4890
+ entry.snapshot,
4891
+ entry.index,
4892
+ patch.itemId,
4893
+ patch.field,
4894
+ patch.value
4895
+ );
4896
+ } else {
4897
+ const next = syncListSnapshot(
4898
+ entry.snapshot,
4899
+ entry.index,
4900
+ patch.itemId,
4901
+ patch.field,
4902
+ patch.entries
4903
+ );
4904
+ if (next !== entry.snapshot) {
4905
+ entry.snapshot = next;
4906
+ entry.index = indexSnapshot(next);
4907
+ }
4908
+ }
4909
+ }
4910
+ entries.add(entry);
4911
+ return {
4912
+ getSnapshot: () => entry.snapshot,
4913
+ subscribe(fn) {
4914
+ entry.listeners.add(fn);
4915
+ return () => entry.listeners.delete(fn);
4916
+ },
4917
+ unregister() {
4918
+ entry.listeners.clear();
4919
+ entries.delete(entry);
4920
+ }
4921
+ };
4922
+ },
4923
+ pushPatch(itemId, field, value, edit) {
4924
+ const patch = edit ? { type: "field", itemId, field, value, edit } : { type: "field", itemId, field, value };
4925
+ if (!accepts(patch)) return;
4926
+ record(patch);
4927
+ for (const entry of entries) {
4928
+ const next = patchSnapshot(
4929
+ entry.snapshot,
4930
+ entry.index,
4931
+ itemId,
4932
+ field,
4933
+ value
4934
+ );
4935
+ if (next !== entry.snapshot) {
4936
+ entry.snapshot = next;
4937
+ notify(entry);
4938
+ }
4939
+ }
4940
+ },
4941
+ pushList(itemId, field, list) {
4942
+ const patch = { type: "list", itemId, field, entries: list };
4943
+ if (!accepts(patch)) return;
4944
+ record(patch);
4945
+ for (const entry of entries) {
4946
+ const next = syncListSnapshot(
4947
+ entry.snapshot,
4948
+ entry.index,
4949
+ itemId,
4950
+ field,
4951
+ list
4952
+ );
4953
+ if (next !== entry.snapshot) {
4954
+ entry.snapshot = next;
4955
+ entry.index = indexSnapshot(next);
4956
+ notify(entry);
4957
+ }
4958
+ }
4959
+ },
4960
+ invalidate(itemId) {
4961
+ if (log.length) {
4962
+ log = [];
4963
+ logListeners.forEach((fn) => fn(log));
4964
+ }
4965
+ const pending = pendingInvalidates.get(itemId);
4966
+ if (pending) clearTimeout(pending);
4967
+ pendingInvalidates.set(
4968
+ itemId,
4969
+ setTimeout(() => runInvalidate(itemId), INVALIDATE_DEBOUNCE_MS)
4970
+ );
4971
+ },
4972
+ setFetcher(fetcher) {
4973
+ defaultFetcher = fetcher;
4974
+ },
4975
+ onInvalidate(fn) {
4976
+ invalidateListeners.add(fn);
4977
+ return () => invalidateListeners.delete(fn);
4978
+ },
4979
+ getLog: () => log,
4980
+ onLogChange(fn) {
4981
+ logListeners.add(fn);
4982
+ return () => logListeners.delete(fn);
4983
+ }
4984
+ };
4985
+ }
4986
+
4987
+ // src/core/live-preview/morph.ts
4988
+ function morphElement(current, next) {
4989
+ syncAttributes(current, next);
4990
+ morphChildren(current, next);
4991
+ }
4992
+ var SKIP_ATTR = "data-prepr-morph-skip";
4993
+ var RUNTIME_ATTR_PREFIXES = ["data-prepr-"];
4994
+ function isRuntimeAttribute(name) {
4995
+ return RUNTIME_ATTR_PREFIXES.some((prefix) => name.startsWith(prefix));
4996
+ }
4997
+ function syncAttributes(current, next) {
4998
+ for (const { name } of Array.from(current.attributes)) {
4999
+ if (!next.hasAttribute(name) && !isRuntimeAttribute(name)) {
5000
+ current.removeAttribute(name);
5001
+ }
5002
+ }
5003
+ for (const { name, value } of Array.from(next.attributes)) {
5004
+ if (current.getAttribute(name) !== value) current.setAttribute(name, value);
5005
+ }
5006
+ }
5007
+ function isSkipped(node) {
5008
+ return node.nodeType === Node.ELEMENT_NODE && (node.hasAttribute(SKIP_ATTR) || node.localName === "prepr-toolbar");
5009
+ }
5010
+ function sameKind(a2, b2) {
5011
+ if (a2.nodeType !== b2.nodeType) return false;
5012
+ if (a2.nodeType !== Node.ELEMENT_NODE) return true;
5013
+ const ea = a2;
5014
+ const eb = b2;
5015
+ return ea.localName === eb.localName && ea.id === eb.id;
5016
+ }
5017
+ function morphChildren(current, next) {
5018
+ const wanted = Array.from(next.childNodes).filter((n2) => !isSkipped(n2));
5019
+ const existing = Array.from(current.childNodes).filter((n2) => !isSkipped(n2));
5020
+ wanted.forEach((target, i2) => {
5021
+ const node = existing[i2];
5022
+ if (node && sameKind(node, target)) {
5023
+ if (node.nodeType === Node.ELEMENT_NODE) {
5024
+ const element = node;
5025
+ if (element.localName === "script") return;
5026
+ if (element.localName === "astro-island" && !element.isEqualNode(target)) {
5027
+ element.replaceWith(adopt(target, current));
5028
+ return;
5029
+ }
5030
+ morphElement(element, target);
5031
+ } else if (node.nodeValue !== target.nodeValue) {
5032
+ node.nodeValue = target.nodeValue;
5033
+ }
5034
+ return;
5035
+ }
5036
+ const replacement = adopt(target, current);
5037
+ if (node) node.replaceWith(replacement);
5038
+ else current.appendChild(replacement);
5039
+ });
5040
+ for (const extra of existing.slice(wanted.length)) extra.remove();
5041
+ }
5042
+ function adopt(node, parent) {
5043
+ const copy = parent.ownerDocument.importNode(node, true);
5044
+ if (copy.nodeType === Node.ELEMENT_NODE) {
5045
+ const element = copy;
5046
+ const scripts = element.localName === "script" ? [element] : Array.from(element.querySelectorAll("script"));
5047
+ scripts.forEach((s2) => s2.setAttribute("data-prepr-morphed", ""));
5048
+ }
5049
+ return copy;
5050
+ }
5051
+
5052
+ // src/core/live-preview/html-live.ts
5053
+ var debug14 = createScopedLogger("live-preview:html");
5054
+ var COMPLETE_DOCUMENT = /<\/html>\s*$/i;
5055
+ var SYNC_DEBOUNCE_MS = 150;
5056
+ function startHtmlLivePreview(options = {}) {
5057
+ if (typeof window === "undefined" || window.self === window.top) {
5058
+ return { stop() {
5059
+ } };
5060
+ }
5061
+ const store = createLiveStore();
5062
+ const bridge = createLiveBridge(store, {
5063
+ allowedEditorOrigins: () => options.allowedEditorOrigins,
5064
+ strictMode: () => options.strictMode
5065
+ });
5066
+ bridge.start();
5067
+ let timer = null;
5068
+ let inFlight = false;
5069
+ let pending = null;
5070
+ let stopped = false;
5071
+ const render = async (log) => {
5072
+ inFlight = true;
5073
+ try {
5074
+ const response = await fetch(window.location.href, {
5075
+ method: log.length ? "POST" : "GET",
5076
+ headers: log.length ? { "Content-Type": "application/json", [HEADER_LIVE_RENDER]: "1" } : {},
5077
+ body: log.length ? JSON.stringify({ log }) : void 0,
5078
+ credentials: "same-origin",
5079
+ cache: "no-store"
5080
+ });
5081
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
5082
+ const html = await response.text();
5083
+ if (stopped) return;
5084
+ if (!COMPLETE_DOCUMENT.test(html)) {
5085
+ throw new Error("incomplete page; a component failed to render");
5086
+ }
5087
+ const next = new DOMParser().parseFromString(html, "text/html");
5088
+ if (next.title && next.title !== document.title)
5089
+ document.title = next.title;
5090
+ morphElement(document.body, next.body);
5091
+ } catch (error) {
5092
+ debug14.log("re-render failed", error);
5093
+ } finally {
5094
+ inFlight = false;
5095
+ }
5096
+ if (pending && !stopped) {
5097
+ const queued = pending;
5098
+ pending = null;
5099
+ void render(queued);
5100
+ }
5101
+ };
5102
+ const schedule = (log) => {
5103
+ if (timer) clearTimeout(timer);
5104
+ timer = setTimeout(() => {
5105
+ timer = null;
5106
+ if (inFlight) pending = log;
5107
+ else void render(log);
5108
+ }, SYNC_DEBOUNCE_MS);
5109
+ };
5110
+ const offLog = store.onLogChange((log) => {
5111
+ if (log.length) schedule(log);
5112
+ });
5113
+ const offInvalidate = store.onInvalidate(() => schedule([]));
5114
+ return {
5115
+ stop() {
5116
+ stopped = true;
5117
+ if (timer) clearTimeout(timer);
5118
+ offLog();
5119
+ offInvalidate();
5120
+ bridge.stop();
5121
+ }
5122
+ };
5123
+ }
5124
+
5125
+ // src/core/live-preview/live-request.ts
5126
+ var MAX_BODY_BYTES = 1e6;
5127
+ async function readLiveLogFromRequest(request) {
5128
+ try {
5129
+ if (request.method !== "POST") return [];
5130
+ if (request.headers.get(HEADER_LIVE_RENDER) !== "1") return [];
5131
+ const origin = request.headers.get("origin");
5132
+ if (!origin || origin !== new URL(request.url).origin) return [];
5133
+ const type = request.headers.get("content-type") ?? "";
5134
+ if (!type.toLowerCase().startsWith("application/json")) return [];
5135
+ const length = Number(request.headers.get("content-length") ?? "0");
5136
+ if (length > MAX_BODY_BYTES) return [];
5137
+ const text = await request.clone().text();
5138
+ if (text.length > MAX_BODY_BYTES) return [];
5139
+ const body = JSON.parse(text);
5140
+ return parsePatchLog(body?.log);
5141
+ } catch {
5142
+ return [];
5143
+ }
5144
+ }
5145
+
2377
5146
  // src/core/server.ts
2378
5147
  var PreprError = class extends Error {
2379
5148
  constructor(message, code, context, originalError) {
@@ -2772,9 +5541,14 @@ function setTrackingParam(key, value) {
2772
5541
  getPreprUUIDFromHeaders,
2773
5542
  getToolbarPropsFromHeaders,
2774
5543
  loadTrackingPixel,
5544
+ normalizeQuery,
5545
+ parsePatchLog,
5546
+ previewAttrs,
2775
5547
  processPreprRequest,
5548
+ readLiveLogFromRequest,
2776
5549
  resolveFeatures,
2777
5550
  setTrackingParam,
5551
+ startHtmlLivePreview,
2778
5552
  stegaClean,
2779
5553
  trackEvent,
2780
5554
  validatePreprToken