@panphora/clayjs 1.24.1 → 1.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/dist/all.js +1 -1
  2. package/dist/clay-dom.js +1 -1
  3. package/dist/clay-events.js +1 -1
  4. package/dist/clay-internals.js +1 -1
  5. package/dist/clay-options.js +1 -1
  6. package/dist/clay-router.js +1 -1
  7. package/dist/clay-ui.js +1 -1
  8. package/dist/clay-utils.js +1 -1
  9. package/dist/clay.js +1 -1
  10. package/dist/clay.standalone.js +2044 -1247
  11. package/dist/m/attrs/{refetch-on-save-DPGJJMGN.js → refetch-on-save-5CBFUJUF.js} +1 -1
  12. package/dist/m/attrs/save-freeze-MH3AOD56.js +1 -0
  13. package/dist/m/{c-SXGEWPFC.js → c-3E2IK5HU.js} +1 -1
  14. package/dist/m/{c-A4L7APIU.js → c-4AE2A2LK.js} +1 -1
  15. package/dist/m/{c-YDW4VCHP.js → c-4Q6QIODW.js} +1 -1
  16. package/dist/m/{c-RO73MKKR.js → c-52OC3OH3.js} +1 -1
  17. package/dist/m/{c-ZGCO4J3H.js → c-5PZYDWTW.js} +1 -1
  18. package/dist/m/c-5Q5XBN56.js +1 -0
  19. package/dist/m/c-5SZ6KFR5.js +1 -0
  20. package/dist/m/{c-ZRGEN6QQ.js → c-AI3H6ETU.js} +2 -2
  21. package/dist/m/{c-7V6MGMX2.js → c-BCWYEG6P.js} +1 -1
  22. package/dist/m/{c-C5AKJVRH.js → c-BJ2RRQBQ.js} +1 -1
  23. package/dist/m/{c-CTGRDT6E.js → c-C6YZNU6E.js} +1 -1
  24. package/dist/m/{c-EDE45NM7.js → c-C7SUMNMI.js} +1 -1
  25. package/dist/m/c-CITLTVQ4.js +4 -0
  26. package/dist/m/{c-STRI73GQ.js → c-CL5LSATX.js} +1 -1
  27. package/dist/m/{c-Z4G2UK6T.js → c-CU33V6RW.js} +1 -1
  28. package/dist/m/{c-6LEYVQJK.js → c-D62HRSZK.js} +1 -1
  29. package/dist/m/{c-DD26VXAP.js → c-DT7E76Z2.js} +1 -1
  30. package/dist/m/{c-P2HKMJAW.js → c-EAV7A6BT.js} +1 -1
  31. package/dist/m/{c-QQFHEODI.js → c-EQ5NBOGA.js} +1 -1
  32. package/dist/m/{c-KQKKIVLW.js → c-FBOO2UY3.js} +1 -1
  33. package/dist/m/{c-JQF2EUCG.js → c-FJDTDGDA.js} +1 -1
  34. package/dist/m/{c-MQKSKQHG.js → c-FKTALXNV.js} +1 -1
  35. package/dist/m/{c-HL6BLJNA.js → c-GDNZEOOZ.js} +1 -1
  36. package/dist/m/{c-SUXHUL7U.js → c-GEAG5XAK.js} +1 -1
  37. package/dist/m/{c-LSVN3OLG.js → c-GY4BREDT.js} +1 -1
  38. package/dist/m/{c-4PO3YGDC.js → c-HGG7M2S3.js} +1 -1
  39. package/dist/m/{c-DDS23EY6.js → c-HXGNH6GY.js} +1 -1
  40. package/dist/m/{c-FLEIU6CG.js → c-IESDKFO6.js} +1 -1
  41. package/dist/m/{c-CJ7QYEWI.js → c-IJHF4IO6.js} +1 -1
  42. package/dist/m/{c-SGGGCIVD.js → c-IL5IVTOG.js} +1 -1
  43. package/dist/m/c-JB5YU57S.js +1 -0
  44. package/dist/m/{c-MP6S4AZU.js → c-JD2VFAYG.js} +2 -2
  45. package/dist/m/{c-CV4T65JE.js → c-JWW6BHWD.js} +3 -3
  46. package/dist/m/{c-42ZNV7LI.js → c-K4M76VPM.js} +1 -1
  47. package/dist/m/{c-6IJEVE6B.js → c-KU3PX7LL.js} +1 -1
  48. package/dist/m/{c-2PVGJFI5.js → c-KYTVZT4D.js} +1 -1
  49. package/dist/m/{c-BGN7RCTJ.js → c-M7ITYKMF.js} +1 -1
  50. package/dist/m/c-MFB74XVN.js +3 -0
  51. package/dist/m/c-MOP5KBWZ.js +1 -0
  52. package/dist/m/{c-YLHTD3KX.js → c-MUM53J5J.js} +1 -1
  53. package/dist/m/{c-YK2L436K.js → c-MV7TEUTD.js} +1 -1
  54. package/dist/m/{c-LA2BW7UY.js → c-MZCOGNZL.js} +1 -1
  55. package/dist/m/{c-XW5TIYYB.js → c-N4GEJMXW.js} +1 -1
  56. package/dist/m/{c-NQAPWM7O.js → c-NADLYVAH.js} +1 -1
  57. package/dist/m/{c-RS77ODLY.js → c-NL4I4KNG.js} +1 -1
  58. package/dist/m/{c-X75G43SZ.js → c-O2QZDVZ2.js} +1 -1
  59. package/dist/m/{c-LTSPHVAK.js → c-OBMZASYQ.js} +1 -1
  60. package/dist/m/{c-LUXAB2XI.js → c-ORLPQFNU.js} +1 -1
  61. package/dist/m/c-P73XPAOA.js +1 -0
  62. package/dist/m/{c-PWJSJEJU.js → c-PNZIJFG7.js} +1 -1
  63. package/dist/m/{c-ZKKAF4UT.js → c-PRZNJUYZ.js} +2 -2
  64. package/dist/m/{c-B7GOFGQR.js → c-Q2CB57UG.js} +1 -1
  65. package/dist/m/{c-TWCXBWS3.js → c-QCDVDZIR.js} +1 -1
  66. package/dist/m/{c-UOOIF2AL.js → c-QDVG4NAZ.js} +1 -1
  67. package/dist/m/c-QWB53KRW.js +1 -0
  68. package/dist/m/{c-GNI7WHKF.js → c-RGAALCDU.js} +1 -1
  69. package/dist/m/c-RHPHMTF2.js +2 -0
  70. package/dist/m/{c-3UW5EJ77.js → c-RWJ3OSCP.js} +1 -1
  71. package/dist/m/{c-5FXEKU4Y.js → c-SEVOS4UE.js} +1 -1
  72. package/dist/m/{c-HDVH3MVC.js → c-SFYTKRU7.js} +1 -1
  73. package/dist/m/{c-47IBJGPQ.js → c-SFZRY6RT.js} +1 -1
  74. package/dist/m/{c-QENKN7QI.js → c-SGG6MUXW.js} +1 -1
  75. package/dist/m/c-SMLAJASY.js +1 -0
  76. package/dist/m/{c-DFKBGSN2.js → c-SUAC5RSG.js} +1 -1
  77. package/dist/m/{c-6RGEQNVV.js → c-SXZYVXD6.js} +1 -1
  78. package/dist/m/{c-ZFO5RW6G.js → c-TCFVG3I4.js} +1 -1
  79. package/dist/m/{c-OCYG4NBQ.js → c-TLQINES7.js} +2 -2
  80. package/dist/m/c-U4TWEIKZ.js +1 -0
  81. package/dist/m/{c-MQYEDF3Q.js → c-U65PREMC.js} +1 -1
  82. package/dist/m/{c-PDBNCJCT.js → c-U7F66I64.js} +1 -1
  83. package/dist/m/{c-LATNQ6Q5.js → c-UD4VDBGJ.js} +1 -1
  84. package/dist/m/{c-PCNJETUA.js → c-V2FPBRO6.js} +1 -1
  85. package/dist/m/{c-ND3Q2G2I.js → c-V4B3RUWB.js} +1 -1
  86. package/dist/m/{c-JWDCQL6J.js → c-V5L6HWVL.js} +1 -1
  87. package/dist/m/c-VMXCX52Q.js +1 -0
  88. package/dist/m/{c-CZHTXGJS.js → c-VO6RSFCO.js} +1 -1
  89. package/dist/m/c-WDFQ7PBU.js +1 -0
  90. package/dist/m/{c-OG6GFSUX.js → c-WGQVSKKC.js} +1 -1
  91. package/dist/m/c-WSTUCBHV.js +1 -0
  92. package/dist/m/{c-FEC6LGFF.js → c-WVCT3ITX.js} +1 -1
  93. package/dist/m/{c-SE3SIY7Y.js → c-X3V4RWMA.js} +1 -1
  94. package/dist/m/{c-HIX5H5L7.js → c-XHZIKRCV.js} +1 -1
  95. package/dist/m/{c-2BLVA6IN.js → c-XQTERKQA.js} +1 -1
  96. package/dist/m/{c-PYG2NGWU.js → c-YFO6ZJLQ.js} +1 -1
  97. package/dist/m/{c-7CM4GMTS.js → c-YX2MC7YL.js} +1 -1
  98. package/dist/m/{c-OYHI67B6.js → c-YYGUHSZR.js} +1 -1
  99. package/dist/m/{c-YYMZWQLR.js → c-Z2OZFX3N.js} +1 -1
  100. package/dist/m/{c-AT7GLQGV.js → c-ZEA3DCG3.js} +1 -1
  101. package/dist/m/{c-T3P3AXEW.js → c-ZJG6C2WL.js} +1 -1
  102. package/dist/m/{c-FVPNX2GO.js → c-ZORVIXUR.js} +1 -1
  103. package/dist/m/{c-SKMIR5HQ.js → c-ZPI7M5U5.js} +1 -1
  104. package/dist/m/core/{admin-attrs-ONRWVXPK.js → admin-attrs-ZI6K6UGM.js} +1 -1
  105. package/dist/m/core/{autosave-TBKAAAFB.js → autosave-BSM2ABJL.js} +1 -1
  106. package/dist/m/core/{conflict-notice-FOEE6I7E.js → conflict-notice-7EQLDYPA.js} +1 -1
  107. package/dist/m/core/draft-mode-M5XNYBMY.js +1 -0
  108. package/dist/m/core/{host-permission-X4BENZEU.js → host-permission-5BYP24GC.js} +1 -1
  109. package/dist/m/core/{is-edit-mode-FFHCQ5DR.js → is-edit-mode-73OXKK5H.js} +1 -1
  110. package/dist/m/core/{persist-6ILUR34S.js → persist-2SZO3PCE.js} +1 -1
  111. package/dist/m/core/{recovery-APWADU4K.js → recovery-VZF7RJZF.js} +1 -1
  112. package/dist/m/core/{save-6HT2LABE.js → save-K6Q47J2X.js} +1 -1
  113. package/dist/m/core/{save-core-EVMNZQ4V.js → save-core-U3Z44XBO.js} +1 -1
  114. package/dist/m/core/{site-edits-G4BOZMV4.js → site-edits-CFMF6GHD.js} +1 -1
  115. package/dist/m/core/{snapshot-FJP5IJL3.js → snapshot-PWCHYFL6.js} +1 -1
  116. package/dist/m/core/unsaved-warning-2WRZLJH5.js +1 -0
  117. package/dist/m/events/{index-B6TGDYMG.js → index-YKQIBZE5.js} +1 -1
  118. package/dist/m/internals/index-FSLC4M7J.js +1 -0
  119. package/dist/m/lib/{cache-bust-NH7VBWHO.js → cache-bust-BL4KUQAJ.js} +1 -1
  120. package/dist/m/{loader-GLLVDUZA.js → loader-RC54UV7H.js} +1 -1
  121. package/dist/m/manifest-3B84C829.js +1 -0
  122. package/dist/m/manifest-edit-1CB79AD4.js +1 -0
  123. package/dist/m/manifest.json +1165 -1115
  124. package/dist/m/options/{options-55LQHSJ4.js → options-LKIZ7YTG.js} +1 -1
  125. package/dist/m/page/{editor-KAZDJNND.js → editor-PKSPJ2XJ.js} +2 -2
  126. package/dist/m/plugins/{ai-edit-LABECCSN.js → ai-edit-3LG6MGS3.js} +1 -1
  127. package/dist/m/plugins/{demo-T7B4RIKL.js → demo-LMCMBILC.js} +1 -1
  128. package/dist/m/plugins/{derive-6LPJOCAV.js → derive-7DR5TUDH.js} +1 -1
  129. package/dist/m/plugins/{indicator-J4ABFARX.js → indicator-CTKX4EY7.js} +1 -1
  130. package/dist/m/plugins/{live-PGBIEMGB.js → live-IFLL6YN5.js} +1 -1
  131. package/dist/m/plugins/{menu-YZL3X2AJ.js → menu-YJZ3JWBC.js} +1 -1
  132. package/dist/m/plugins/{page-WOCNX2IN.js → page-GTDPYGE4.js} +2 -2
  133. package/dist/m/plugins/{page-view-SJODOOGE.js → page-view-NMCCU6MF.js} +1 -1
  134. package/dist/m/plugins/{people-C4TCWFOQ.js → people-6WIWCZEG.js} +1 -1
  135. package/dist/m/plugins/{richclay-Y2NV44NA.js → richclay-L3BZMX4I.js} +2 -2
  136. package/dist/m/plugins/{sortable-XCHQG65Z.js → sortable-365SRRL3.js} +1 -1
  137. package/dist/m/plugins/{source-YK7MO23W.js → source-7LSGOV46.js} +1 -1
  138. package/dist/m/plugins/{undo-VLRBQNPN.js → undo-UES4KS7B.js} +1 -1
  139. package/dist/m/plugins/{upgrade-NNTJBSK2.js → upgrade-MMPZUCDM.js} +1 -1
  140. package/dist/m/plugins/{upload-ZKKJV76X.js → upload-NZET3DNQ.js} +1 -1
  141. package/dist/m/plugins/visitor-drafts-V5YB7XDH.js +20 -0
  142. package/dist/m/plugins/{visitor-drafts-owner-LHUHFU3L.js → visitor-drafts-owner-TLECTYWS.js} +1 -1
  143. package/dist/m/plugins/{visitor-menu-FY4KM2SW.js → visitor-menu-QDV2MYJN.js} +1 -1
  144. package/dist/m/plugins/wire-3YGUO3GE.js +1 -0
  145. package/dist/m/{reader-core-T2S3JC4E.js → reader-core-VR7EL4WV.js} +2 -2
  146. package/dist/m/sync/live-sync-XMXXZS3G.js +1 -0
  147. package/dist/m/vendor/sap-core.vendor-JANUQULT.js +7 -0
  148. package/dist/offline-manifest.json +665 -635
  149. package/docs/guide.md +1 -0
  150. package/entries/sap.js +6 -5
  151. package/package.json +1 -1
  152. package/src/core/draft-mode.js +5 -0
  153. package/src/core/save-core.js +10 -10
  154. package/src/core/save.js +1 -1
  155. package/src/lib/dirty-gate.js +19 -0
  156. package/src/plugins/menu/visitor.js +33 -1
  157. package/src/plugins/visitor-drafts/commit.js +50 -3
  158. package/src/plugins/visitor-drafts/idb.js +8 -2
  159. package/src/plugins/visitor-drafts/recovery-menu.js +118 -0
  160. package/src/plugins/visitor-drafts/recovery.js +64 -0
  161. package/src/plugins/visitor-drafts/session.js +61 -13
  162. package/src/plugins/visitor-drafts/store.js +44 -8
  163. package/src/plugins/visitor-drafts.js +34 -5
  164. package/src/sync/live-sync.js +1 -1
  165. package/src/sync/wire-profile.js +9 -4
  166. package/src/vendor/sap-core.vendor.js +6 -5
  167. package/src/vendor/sap-ownership.vendor.js +181 -11
  168. package/tool-generation/system.md +1 -1
  169. package/dist/m/attrs/save-freeze-JZHKRQLR.js +0 -1
  170. package/dist/m/c-6Q6RGFBF.js +0 -1
  171. package/dist/m/c-APGHGDZM.js +0 -1
  172. package/dist/m/c-EILLN2H2.js +0 -1
  173. package/dist/m/c-HTLYXCUH.js +0 -1
  174. package/dist/m/c-MFOSMAVM.js +0 -3
  175. package/dist/m/c-R23UHMXG.js +0 -1
  176. package/dist/m/c-SGH3UTF3.js +0 -1
  177. package/dist/m/c-U4NTUVDZ.js +0 -1
  178. package/dist/m/c-V2U3F4QX.js +0 -1
  179. package/dist/m/c-VG5XIN4T.js +0 -1
  180. package/dist/m/c-VHSMPITY.js +0 -1
  181. package/dist/m/core/draft-mode-4MCL3LYI.js +0 -1
  182. package/dist/m/core/unsaved-warning-ITZDIZ2I.js +0 -1
  183. package/dist/m/internals/index-HS3CQDFW.js +0 -1
  184. package/dist/m/manifest-50FF1C45.js +0 -1
  185. package/dist/m/manifest-edit-BE1A621D.js +0 -1
  186. package/dist/m/plugins/visitor-drafts-RTZNONHT.js +0 -20
  187. package/dist/m/plugins/wire-M2NR354P.js +0 -1
  188. package/dist/m/sync/live-sync-Z64YREWQ.js +0 -1
  189. package/dist/m/vendor/sap-core.vendor-QAEPMETX.js +0 -6
  190. /package/dist/m/plugins/{richclay-Y2NV44NA.js.LEGAL.txt → richclay-L3BZMX4I.js.LEGAL.txt} +0 -0
@@ -9,6 +9,18 @@
9
9
 
10
10
  export const BEACON = "sap-error";
11
11
 
12
+ // What a plugin paints inside a boundary of its own, as plain data, so a host knows it
13
+ // before that plugin's code has loaded, and in a tab where it never loads:
14
+ // { plugin, within, select, text?, attrs? }
15
+ // `within` selects the boundary, and `select` the elements under it or the boundary
16
+ // itself. `text: true` says the element's text is painted, and `attrs` names painted
17
+ // attributes. Under a boundary only rules and the error marker say what is painted,
18
+ // because the engine stays out of it: its own directives, sap-ignore and templates mean
19
+ // nothing there. First party rules live in this table, because this is the one file
20
+ // ClayJS vendors. None ships yet. A plugin from anyone else gives the same rules in its
21
+ // definition's `ownership` field, and they count once its file has run.
22
+ export const PLUGIN_RULES = [];
23
+
12
24
  const WHEN = /^(show-when|hide-when|option|option-not):/;
13
25
  // Identity and the attributes that declare the record itself are never paint
14
26
  // output. Form state is, unless a bind or persist owns it.
@@ -26,6 +38,67 @@ function inert(el) {
26
38
  return el.localName === "template" || el.hasAttribute("template") || el.hasAttribute("cms-template") || el.hasAttribute("sap-ignore");
27
39
  }
28
40
 
41
+ // An element the engine enters as a scope of its own never starts a plugin boundary.
42
+ const SCOPES = ["sap", "item", "scope", "items", "detail", "each"];
43
+ const NONE = [];
44
+ let known = { rules: NONE, within: "", seen: NONE, counted: 0 };
45
+
46
+ // PLUGIN_RULES, then the rules of every other definition this page has seen, with one
47
+ // selector, `within`, for every boundary a rule names. Built again only when a
48
+ // definition or a rule has arrived.
49
+ function pluginRules() {
50
+ const seen = typeof window !== "undefined" && Array.isArray(window.sapPlugins) ? window.sapPlugins : NONE;
51
+ const counted = seen.length + PLUGIN_RULES.length;
52
+ if (seen === known.seen && counted === known.counted) return known;
53
+ const rules = PLUGIN_RULES.slice();
54
+ for (const def of seen) {
55
+ if (!def || !Array.isArray(def.ownership) || PLUGIN_RULES.some((rule) => rule.plugin === def.name)) continue;
56
+ for (const rule of def.ownership) if (usable(rule)) rules.push({ ...rule, plugin: def.name });
57
+ }
58
+ known = { rules, within: [...new Set(rules.map((rule) => rule.within))].join(","), seen, counted };
59
+ return known;
60
+ }
61
+
62
+ // A rule from a file this project did not write runs inside a host's dirty check, so
63
+ // one that would throw there is left out.
64
+ function usable(rule) {
65
+ if (!rule || typeof rule.within !== "string" || typeof rule.select !== "string" || (rule.attrs && !Array.isArray(rule.attrs))) return false;
66
+ try {
67
+ const nowhere = document.createDocumentFragment();
68
+ nowhere.querySelector(rule.within);
69
+ nowhere.querySelector(rule.select);
70
+ return true;
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ function startsBoundary(el) {
77
+ return !SCOPES.some((name) => el.hasAttribute(name));
78
+ }
79
+
80
+ // The nearest boundary at or above el that `selector` matches and that sits in an app,
81
+ // or null. `host` continues the walk for a subtree that left the page, as in appOf.
82
+ function boundaryAt(el, selector, host = null) {
83
+ for (let cur = el; cur; cur = cur.parentElement) {
84
+ const found = cur.closest(selector);
85
+ if (!found) break;
86
+ if (startsBoundary(found) && appOf(found, host)) return found;
87
+ cur = found;
88
+ }
89
+ return host && !el.isConnected ? boundaryAt(host, selector) : null;
90
+ }
91
+
92
+ // The boundary el sits under, not counting el itself.
93
+ function boundaryAbove(el, selector, host = null) {
94
+ const from = el.parentElement || (el.isConnected ? null : host);
95
+ return from ? boundaryAt(from, selector, host) : null;
96
+ }
97
+
98
+ function ruleApplies(rule, el, live, host = null) {
99
+ return (!live || live(rule.plugin)) && el.matches(rule.select) && !!boundaryAt(el, rule.within, host);
100
+ }
101
+
29
102
  // The [sap] root an element is painted under, or null when it sits outside every
30
103
  // app or inside a subtree the engine never reads. A subtree just removed from the
31
104
  // page has no ancestors left to ask; `host`, the element it was removed from,
@@ -55,9 +128,19 @@ function paintsHidden(el) {
55
128
  return false;
56
129
  }
57
130
 
58
- // True when a sapjs paint writes attribute `name` on `el`.
59
- export function ownsAttr(el, name, host = null) {
131
+ // True when a sapjs paint writes attribute `name` on `el`. `live`, when given, is asked
132
+ // with a plugin's name and says whether that plugin's rules count: a host passes it
133
+ // where the question is "will something repaint this", which is only true of a plugin
134
+ // that is installed.
135
+ export function ownsAttr(el, name, host = null, live = null) {
60
136
  if (!el || el.nodeType !== 1 || !name) return false;
137
+ const { rules, within } = pluginRules();
138
+ if (rules.length && boundaryAt(el, within, host)) {
139
+ for (const rule of rules) {
140
+ if (rule.attrs && rule.attrs.includes(name) && ruleApplies(rule, el, live, host)) return true;
141
+ }
142
+ if (boundaryAbove(el, within, host)) return name === BEACON;
143
+ }
61
144
  if (name === BEACON) return !!appOf(el, host);
62
145
  if (NEVER.has(name)) return false;
63
146
  if (FORM_STATE.has(name) && recordOwnsFormState(el)) return false;
@@ -65,16 +148,30 @@ export function ownsAttr(el, name, host = null) {
65
148
  return el.hasAttribute("attr:" + name) && !declares(el, name) && !!appOf(el, host);
66
149
  }
67
150
 
151
+ const blank = () => ({ attrs: [], classes: [], vars: [], text: false });
152
+
68
153
  // Everything a paint writes on `el`: whole attributes, class tokens, --custom
69
154
  // properties in style, and whether text owns its children. Null when nothing.
70
- export function paintsOf(el) {
71
- if (!el || el.nodeType !== 1 || !appOf(el)) return null;
155
+ // `live` is the same optional question as in ownsAttr.
156
+ export function paintsOf(el, live = null) {
157
+ if (!el || el.nodeType !== 1) return null;
158
+ const { rules, within } = pluginRules();
159
+ if (!rules.length || !boundaryAt(el, within)) return appOf(el) ? enginePaints(el, null) : null;
72
160
  let out = null;
73
- const add = (key, v) => ((out || (out = { attrs: [], classes: [], vars: [], text: false }))[key].push(v));
161
+ for (const rule of rules) if (ruleApplies(rule, el, live)) out = addRule(out, rule);
162
+ // With no boundary above it, el is the boundary, and the engine paints on that.
163
+ if (!boundaryAbove(el, within)) return enginePaints(el, out);
164
+ if (el.hasAttribute(BEACON)) (out || (out = blank())).attrs.push(BEACON);
165
+ return out;
166
+ }
167
+
168
+ // What the engine's own directives paint on el, added to `out`.
169
+ function enginePaints(el, out) {
170
+ const add = (key, v) => ((out || (out = blank()))[key].push(v));
74
171
  for (const a of el.attributes) {
75
172
  const n = a.name;
76
173
  if (n === "text" || n.startsWith("text:")) {
77
- if (!el.hasAttribute("bind")) (out || (out = { attrs: [], classes: [], vars: [], text: false })).text = true;
174
+ if (!el.hasAttribute("bind")) (out || (out = blank())).text = true;
78
175
  }
79
176
  else if (n.startsWith("attr:")) {
80
177
  const target = n.slice(5);
@@ -87,29 +184,102 @@ export function paintsOf(el) {
87
184
  return out;
88
185
  }
89
186
 
187
+ function addRule(out, rule) {
188
+ out = out || blank();
189
+ if (rule.text) out.text = true;
190
+ for (const name of rule.attrs || NONE) if (!out.attrs.includes(name)) out.attrs.push(name);
191
+ return out;
192
+ }
193
+
90
194
  // Calls visit(el, paints) for every painted element under root, in document order.
91
- export function eachPainted(root, visit) {
195
+ // `live` is the same optional question as in ownsAttr.
196
+ export function eachPainted(root, visit, live = null) {
92
197
  if (!root || root.nodeType !== 1 && root.nodeType !== 9) return;
93
198
  const apps = root.nodeType === 1 && root.hasAttribute("sap")
94
199
  ? [root]
95
200
  : [...root.querySelectorAll("[sap]")].filter((app) => !app.parentElement || !app.parentElement.closest("[sap]"));
201
+ const known = pluginRules();
96
202
  for (const app of apps) {
203
+ // A root handed in from under a boundary is asked element by element.
204
+ if (known.rules.length && !boundaryAbove(app, known.within)) {
205
+ walkPainted(app, known, live, visit);
206
+ continue;
207
+ }
97
208
  for (const el of [app, ...app.querySelectorAll("*")]) {
98
- const p = paintsOf(el);
209
+ const p = paintsOf(el, live);
99
210
  if (p) visit(el, p);
100
211
  }
101
212
  }
102
213
  }
103
214
 
215
+ // The same visits as asking paintsOf of el and of every element under it, for an el
216
+ // that is under no boundary. It does not ask paintsOf of an element under a boundary:
217
+ // the boundary is asked for the elements its rules select.
218
+ function walkPainted(el, known, live, visit) {
219
+ if (inert(el)) {
220
+ // A [sap] root in a subtree the engine never reads is an app again.
221
+ let last = null;
222
+ for (const app of el.querySelectorAll("[sap]")) {
223
+ if (last && last.contains(app)) continue;
224
+ walkPainted(app, known, live, visit);
225
+ last = app;
226
+ }
227
+ return;
228
+ }
229
+ const boundary = el.matches(known.within) && startsBoundary(el);
230
+ const p = boundary ? paintsOf(el, live) : enginePaints(el, null);
231
+ if (p) visit(el, p);
232
+ if (boundary) visitBoundary(el, known.rules, live, visit);
233
+ else for (let c = el.firstElementChild; c; c = c.nextElementSibling) walkPainted(c, known, live, visit);
234
+ }
235
+
236
+ function visitBoundary(top, rules, live, visit) {
237
+ const found = new Map();
238
+ const note = (el, rule) => found.set(el, addRule(found.get(el), rule));
239
+ const selects = ["[" + BEACON + "]"];
240
+ let all = NONE;
241
+ for (const rule of rules) {
242
+ if (live && !live(rule.plugin)) continue;
243
+ selects.push(rule.select);
244
+ if (top.matches(rule.within)) {
245
+ const list = top.querySelectorAll(rule.select);
246
+ for (const el of list) note(el, rule);
247
+ if (list.length > all.length) all = list;
248
+ continue;
249
+ }
250
+ // A boundary of another rule, nested in this one.
251
+ for (const inner of top.querySelectorAll(rule.within)) {
252
+ if (!startsBoundary(inner) || !appOf(inner)) continue;
253
+ if (inner.matches(rule.select)) note(inner, rule);
254
+ for (const el of inner.querySelectorAll(rule.select)) note(el, rule);
255
+ }
256
+ }
257
+ // An error marker under a boundary is painted too, whatever the rules select.
258
+ const marked = top.querySelectorAll("[" + BEACON + "]");
259
+ for (const el of marked) {
260
+ const p = found.get(el) || blank();
261
+ p.attrs.push(BEACON);
262
+ found.set(el, p);
263
+ }
264
+ // What one query found is in document order already. When that is not everything
265
+ // found, one more query puts all of it in order.
266
+ if (all.length < found.size) all = top.querySelectorAll(selects.join(","));
267
+ for (const el of all) {
268
+ const p = found.get(el);
269
+ if (p) visit(el, p);
270
+ }
271
+ }
272
+
104
273
  // Removes every painted value from a detached tree, in place: owned attributes,
105
274
  // owned class tokens and --properties, and the children of text paints.
106
- export function stripPaints(root) {
275
+ // `live` is the same optional question as in ownsAttr.
276
+ export function stripPaints(root, live = null) {
107
277
  eachPainted(root, (el, p) => {
108
278
  for (const name of p.attrs) if (el.hasAttribute(name)) el.removeAttribute(name);
109
279
  for (const token of p.classes) if (el.classList.contains(token)) el.classList.remove(token);
110
- if (!el.getAttribute("class") && el.hasAttribute("class") && p.classes.length) el.removeAttribute("class");
280
+ if (p.classes.length && !el.getAttribute("class") && el.hasAttribute("class")) el.removeAttribute("class");
111
281
  for (const v of p.vars) if (el.style.getPropertyValue(v) !== "") el.style.removeProperty(v);
112
282
  if (p.vars.length && el.hasAttribute("style") && !el.getAttribute("style").trim()) el.removeAttribute("style");
113
283
  if (p.text && el.firstChild) el.replaceChildren();
114
- });
284
+ }, live);
115
285
  }
@@ -14,7 +14,7 @@ The tool sits inside someone else's page, so it fits that page instead of bringi
14
14
  - Inherit the page's type and colour: `font: inherit; color: inherit;`, `currentColor` for lines and icons, and the page's custom properties when you know them. Load no fonts.
15
15
  - Separate parts with whitespace first, then a hairline, then a tinted area. Never a card inside a card, and never a coloured stripe on one side of a box: not left, right or top.
16
16
  - No eyebrow text above a heading. Labels use the body face one step smaller, in sentence case, with no letter spacing.
17
- - One filled primary button at most. Fields are flat; buttons are the only raised things. One shadow at most per element.
17
+ - One filled primary button at most. Fill it with `CanvasText` and write its label in `Canvas`, or tint it with `color-mix(in srgb, currentColor 12%, transparent)` and keep the inherited text colour. Never fill an element with `currentColor` while changing its `color`: `currentColor` is that element's own text colour, so the label disappears. Fields are flat; buttons are the only raised things. One shadow at most per element.
18
18
  - Every control shows a visible focus ring with space around it: `outline: 2px solid currentColor; outline-offset: 2px;` on `:focus-visible`.
19
19
  - Checkboxes and radios keep their native behaviour, styled with `accent-color`, 1 to 4 px larger than the default.
20
20
  - A styled select uses `appearance: none`, places its arrow as far from the right edge as the text is from the left, and pads the right so text never runs under it.
@@ -1 +0,0 @@
1
- import{a}from"../c-YK2L436K.js";import"../c-TWCXBWS3.js";import"../c-LA2BW7UY.js";import"../c-IJUK2GPW.js";import"../c-PWJSJEJU.js";import"../c-XQXZAO7N.js";import"../c-S7LK4KUE.js";import"../c-VG5XIN4T.js";import"../c-2YYDMLNZ.js";import"../c-HA6INT6J.js";import"../c-ICMAOOGK.js";import"../c-WRBKEJD4.js";import"../c-VHNSBD2M.js";export{a as default};
@@ -1 +0,0 @@
1
- import{a as r}from"./c-WYFDLITL.js";import{a as p}from"./c-LA2BW7UY.js";import{f as u}from"./c-EDE45NM7.js";import{n as d,o as l}from"./c-ICMAOOGK.js";var n=0,g=0,c=!1,m=!1,y=!1,i=!1;function o(){!u||i||(i=!0,queueMicrotask(()=>{if(i=!1,typeof document>"u")return;let e=C();if(e===y)return;y=e;let t=document.documentElement;e?t.setAttribute("unsaved","true"):t.removeAttribute("unsaved"),document.dispatchEvent(new CustomEvent(e?"clay:dirty":"clay:clean"))}))}var T=`input${r}, textarea${r}, select${r}`,h=`${d}, ${l}`,a=new WeakMap;function v(){let e=[];for(let t of document.querySelectorAll(T))t.closest(h)||e.push(t);return e}function E(e){let t=e.target;!t||t.nodeType!==1||(t.matches("input, textarea, select")||t.isContentEditable)&&(t.closest(h)||(n++,o()))}function x(){m||(m=!0,p.onAnyChange({omitChangeDetails:!0,require:"dirty"},()=>{c||(n++,o())}),document.addEventListener("input",E,!0),document.addEventListener("change",E,!0))}function L(){c=!0}function k(){c=!1}function f(e){return e instanceof HTMLSelectElement?Array.from(e.selectedOptions,t=>t.value).join("\0"):e instanceof HTMLInputElement&&(e.type==="checkbox"||e.type==="radio")?e.checked?"1":"0":e.value}function M(e){return e instanceof HTMLSelectElement?Array.from(e.options).every(t=>t.selected===t.defaultSelected):e instanceof HTMLInputElement?e.type==="checkbox"||e.type==="radio"?e.checked===e.defaultChecked:e.value===e.defaultValue:e instanceof HTMLTextAreaElement?e.hasAttribute("data-value")?e.value===e.getAttribute("data-value"):e.value===e.defaultValue:!0}function S(){for(let e of v()){let t=f(e);if(a.get(e)!==t){if(M(e)){a.set(e,t);continue}return!0}}return!1}function C(){return n>g||S()}function D(){return n}function O(){let e=[];for(let t of v())e.push([t,f(t)]);return{gen:n,probe:e}}function b(){n++,o()}function H(e){if(e){n===e.gen&&(g=e.gen);for(let[t,s]of e.probe)f(t)===s&&a.set(t,s);o()}}typeof document<"u"&&u&&x();typeof window<"u"&&(window.clay=window.clay||{},window.clay.markDirty=b);export{x as a,L as b,k as c,C as d,D as e,O as f,b as g,H as h};
@@ -1 +0,0 @@
1
- import{e as a,f as b,g as c}from"./c-CZHTXGJS.js";import"./c-WN3MXOLT.js";import"./c-QQFHEODI.js";import"./c-EDE45NM7.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-U4NTUVDZ.js";import"./c-HA6INT6J.js";import"./c-ICMAOOGK.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";export{a as PresenceStore,c as default,b as presence};
@@ -1 +0,0 @@
1
- import{j as z}from"./c-U4NTUVDZ.js";import"./c-VHNSBD2M.js";function M(e){let n=e?.name||"";return n==="QuotaExceededError"||n==="NS_ERROR_DOM_QUOTA_REACHED"?"quota":n==="VersionError"?"unknown-schema":n==="DataCloneError"?"uncloneable":n==="AbortError"||n==="TransactionInactiveError"||n==="InvalidStateError"?"aborted":n==="SecurityError"||n==="UnknownError"||n==="NotSupportedError"?"unavailable":"error"}var ve="clay-visitor-drafts",Se=1,P="records",Y="parts",Ee=2e3;function T(e,n){let p=new Error(`visitor-drafts: the draft database failed (${e})`);return p.code=e,n!==void 0&&(p.cause=n),p}function ue(e,n){return new Promise((p,w)=>{let b=[],f=e.openCursor(n);f.onerror=()=>w(f.error),f.onsuccess=()=>{let o=f.result;if(!o)return p(b);b.push([o.key,o.value]),o.continue()}})}function de({factory:e=globalThis.indexedDB,keyRange:n=globalThis.IDBKeyRange,name:p=ve,timeout:w=Ee}={}){return new Promise((b,f)=>{if(!e||typeof e.open!="function"||!n)return f(T("unavailable"));let o;try{o=e.open(p,Se)}catch(d){return f(T(M(d),d))}let S=!1,u=(d,h)=>S?!1:(S=!0,clearTimeout(t),d(h),!0),t=setTimeout(()=>u(f,T("blocked")),w);o.onupgradeneeded=()=>{let d=o.result;d.objectStoreNames.contains(P)||d.createObjectStore(P),d.objectStoreNames.contains(Y)||d.createObjectStore(Y)},o.onsuccess=()=>{let d=o.result;u(b,Oe(d,n))||d.close()},o.onerror=()=>u(f,T(M(o.error),o.error)),o.onblocked=()=>u(f,T("blocked"))})}function Oe(e,n){let p=!1;e.onversionchange=()=>{p=!0;try{e.close()}catch{}};function w(t,d){if(p)throw T("closed");try{return e.transaction(t,d)}catch(h){throw T(M(h),h)}}async function b(t){let d=w(P,"readonly"),h=n.bound(t,t+":\uFFFF");try{let s=await ue(d.objectStore(P),h);return new Map(s.filter(([i])=>i===t||i.startsWith(t+":")))}catch(s){throw T(M(s),s)}}async function f(t,d){let h=w(Y,"readonly"),s=n.bound([t,d],[t,d,[]]);try{let i=await ue(h.objectStore(Y),s);return new Map(i.map(([y,g])=>[y[2],g]))}catch(i){throw T(M(i),i)}}function o(t,d,{timeout:h=0}={}){return new Promise((s,i)=>{let y;try{y=w([P,Y],"readwrite")}catch(l){return i(l)}let g=null,k,D=!1,c,E=(l,v)=>{D||(D=!0,clearTimeout(c),l(v))};h>0&&(c=setTimeout(()=>{g=T("blocked");try{y.abort()}catch{}E(i,g)},h)),y.oncomplete=()=>E(s,k),y.onabort=()=>E(i,g||T(y.error?M(y.error):"aborted",y.error));try{let l=y.objectStore(P),v=n.bound(t+":op:",t+":op:\uFFFF"),O={record:l.get(t),meta:l.get(t+":meta"),v1base:l.get(t+":v1base"),names:l.getAllKeys(v),values:l.getAll(v)};O.values.onsuccess=()=>{if(!D)try{let R={record:O.record.result??null,meta:O.meta.result??null,v1base:O.v1base.result??null,rows:O.names.result.map((N,F)=>[N,O.values.result[F]])},x=d(R);for(let[N,F]of x.puts)l.put(F,N);for(let N of x.deletes)l.delete(N);k=x.result}catch(R){g=T(M(R),R);try{y.abort()}catch{}}}}catch(l){g=T(M(l),l);try{y.abort()}catch{}}})}function S(t,d){return new Promise((h,s)=>{if(!/:op:[^:]+$/.test(t))return s(T("bad-op"));let i;try{i=w(P,"readwrite"),i.objectStore(P).put(d,t),i.commit?.()}catch(y){return s(y instanceof Error&&y.code?y:T(M(y),y))}i.oncomplete=()=>h(),i.onabort=()=>s(T(i.error?M(i.error):"aborted",i.error))})}function u(){p=!0;try{e.close()}catch{}}return{readAll:b,readParts:f,change:o,putRow:S,close:u}}var _=e=>e===void 0?void 0:JSON.parse(JSON.stringify(e)),K=e=>e!==null&&typeof e=="object"&&!Array.isArray(e),Ae=e=>e+":meta",se=(e,n)=>`${e}:op:${n}`,le=(e,n)=>n===void 0?e+":conflict":`${e}:conflict:${n}`,Z=(e,n)=>`${e}:recovery:${n}`,H=e=>K(e)&&e.v===1&&e.w===void 0&&K(e.data),J=e=>typeof e.id=="string"?e.id:"at:"+e.savedAt,he=(e,n)=>`${e}~${n}`;function Q(e){let n=/^(\d+)~/.exec(e??"");return n?Number(n[1]):null}function Ie(e,n,p){let w={...e},b={...e};for(let[f,o]of Object.entries(n))"b"in o?w[f]=o.b:delete w[f],"m"in o?b[f]=o.m:delete b[f];return p(w,b,e)}var oe=e=>K(e)&&typeof e.tab=="string"&&typeof e.reset=="string"&&Array.isArray(e.ops),$=e=>oe(e)?`op:${e.tab}:${e.ops.at(-1)?.seq??e.acked??0}`:J(e);function ie(e,n){if(K(e)&&n.recovery?.includes($(e)))return!0;if(!oe(e))return!1;let p=Math.max(e.acked??0,e.reset===n.reset?n.tabs[e.tab]?.seq??0:0);return e.ops.every(w=>w.seq<=p)}function ae(e=null){return{gen:Q(e)??1,rev:0,reset:e??"",tabs:{},foreign:null,unit:null}}var q=e=>e&&e.blockeditor?{live:e.live,blockeditor:e.blockeditor}:null;function pe(e,n,p){let w=[...e,n?.id,...n?.ancestry??[]].filter(b=>typeof b=="string");return w.length?w.slice(0,32):["root:"+p.reset]}function ke(e,{record:n,seen:p,direct:w,v1base:b,meta:f}){let o=K(p)&&p.v===1&&K(p.data)&&p.w?.reset===f.reset?p:null,S=t=>t&&typeof t.id=="string"?e.indexOf(t.id):-1,u=[[n,S(n)],[o,o&&w?0:S(o)],[b,S(b)]].filter(([,t])=>t>=0);return u.length?u.reduce((t,d)=>d[1]<t[1]?d:t)[0]:null}function Te(e,{seed:n,newId:p,now:w,merge3:b,unitMark:f,marker:o=null,resets:S=[],chains:u=[],local:t=null,seen:d=null,direct:h=!1}){let s=e.meta?_(e.meta):ae(o);!e.meta&&Number.isInteger(t?.w?.rev)&&(s.rev=t.w.rev);let i=e.record?_(e.record):null,y=e.v1base?_(e.v1base):null,g={conflicts:[],recovered:[],released:[],dropped:[],stale:[],applied:{},changed:!e.meta};function k(c,E=[]){let l=$(c);if(s.recovery?.includes(l))return;g.recovered.push(_(c));let v=[l,...(s.recovery??[]).filter(O=>O!==l&&!E.includes(O))].slice(0,8);return g.dropped=[...new Set([...g.dropped,...s.recovery??[]])].filter(O=>!v.includes(O)),s.recovery=v,g.changed=!0,!0}let D=[...S];o&&o!==s.reset&&D.push({ends:Q(o)===null?null:Q(o)-1,marker:o});for(let c of D){if(c.marker===s.reset||s.ended?.includes(c.marker)||c.ends!==null&&c.ends<s.gen)continue;c.ends!==s.gen&&i&&k(i);let E=typeof t?.reset=="string"?t.reset===c.marker:c.ends===null||Array.isArray(t?.ancestry)&&t.ancestry.includes("root:"+c.marker);H(t)&&J(t)!==s.foreign&&!E&&(k(t),s.foreign=J(t)),s.ended=[...s.ended??[],s.reset].slice(-32),Object.assign(s,{gen:s.gen+1,reset:c.marker,tabs:{},unit:null}),s.rev++,i=null,y=null,g.changed=!0}if(!e.meta&&!i&&K(t)&&t.v===1&&K(t.data)&&(t.w===void 0||t.w.reset===s.reset)){let{w:c,...E}=t;i=_(E),c===void 0&&(y=_(E),s.foreign=J(t),s.rev++)}if(e.meta||(s.unit=f(q(i))),e.meta&&H(t)&&J(t)!==s.foreign){let c=J(t),E=Array.isArray(t.ancestry)?t.ancestry:[],l=i?ke(E,{record:i,seen:d,direct:h,v1base:y,meta:s}):null;if(typeof t.reset=="string"&&s.ended?.includes(t.reset))k(t,E)&&g.released.push(_(t));else if(!i)i=_(t),y=_(t),s.unit=f(q(i)),s.rev++;else if(l){let v=b(l.data,t.data,i.data),O=q(t),R=!!O&&f(O)!==f(q(l)),x=R&&q(i)&&f(q(l))!==s.unit;(v.conflict||x)&&g.conflicts.push(_(i));let N=R?O:q(i);i={v:1,savedAt:t.savedAt??new Date(w).toISOString(),id:p(),ancestry:pe(typeof t.id=="string"?[t.id]:[],i,s),data:v.value,...N&&{live:N.live,blockeditor:N.blockeditor}},R&&(s.unit=f(N)),y=_(t),s.rev++}else k(t,E)&&g.released.push(_(t));s.foreign=c,g.changed=!0}for(let c of u){if(!oe(c))continue;if(c.reset!==s.reset){let v=c.reset===e.meta?.reset?e.meta.tabs[c.tab]?.seq??0:0;c.ops.some(O=>O.seq>Math.max(v,c.acked??0))&&k(c),g.stale.includes(c.tab)||g.stale.push(c.tab);continue}let E=s.tabs[c.tab]?.seq??0,l=Math.max(E,Number.isInteger(c.acked)?c.acked:0);for(let v of c.ops){if(v.seq<=l)continue;if(v.seq!==l+1)break;let O=Ie(i?i.data:n,v.keys??{},b),R=v.unit!==void 0&&i&&q(i)&&v.unit.seen!==s.unit;i&&(O.conflict||R)&&g.conflicts.push(_(i));let x=v.unit!==void 0?v.unit.to:q(i),N=p();i={v:1,savedAt:v.savedAt??new Date(w).toISOString(),id:N,ancestry:pe([],i,s),data:O.value,...x&&{live:x.live,blockeditor:x.blockeditor}},v.unit!==void 0&&(s.unit=f(x)),s.rev++,l=v.seq,g.changed=!0}(l!==E||s.tabs[c.tab])&&(s.tabs[c.tab]={seq:l,at:w},g.changed=!0),g.applied[c.tab]=l}for(let[c,E]of Object.entries(s.tabs))w-(E.at??0)>2592e6&&(delete s.tabs[c],g.changed=!0);return{meta:s,record:i,v1base:y,...g}}var X=e=>{if(e==null)return null;try{return JSON.parse(e)}catch{return null}};function me(e,n,p,w){return e.change(n,b=>{let f={meta:X(b.meta),record:X(b.record),v1base:X(b.v1base)},o=b.rows.map(([h,s])=>[h,X(s)]),S=p(f),u=Te(f,{...S,chains:[...o.map(([,h])=>h),...S.chains??[]]}),t=[],d=[];u.changed&&(t.push([Ae(n),JSON.stringify(u.meta)]),u.record?t.push([n,JSON.stringify(u.record)]):f.record&&d.push(n),u.v1base?t.push([n+":v1base",JSON.stringify(u.v1base)]):f.v1base&&d.push(n+":v1base"));for(let h of u.conflicts)t.push([le(n,J(h)),JSON.stringify(h)]);u.conflicts.length&&t.push([le(n),JSON.stringify(u.conflicts[u.conflicts.length-1])]);for(let h of u.recovered)t.push([Z(n,$(h)),JSON.stringify(h)]);for(let h of u.dropped)d.push(Z(n,h));for(let[h,s]of o)ie(s,u.meta)&&d.push(h);return{puts:t,deletes:d,result:u}},w)}var xe=256*1024,Ne=2*1024,_e=new Set(["v","savedAt","id","ancestry","reset","data"]),Re=10*1e3,Me=1500,ge=2e3,De="This draft was started over in another tab.",qe="This draft was started over in another tab. The earlier draft was kept aside in this browser.",Je="A tab that was open before an update saved another copy of this draft. That copy was kept aside, and this draft was not changed. Reload that tab to go on from this draft.",B=e=>{if(e==null)return null;try{return JSON.parse(e)}catch{return null}};function Pe(e,n){let p={},w=Object.keys(e).every(b=>_e.has(b));for(let[b,f]of Object.entries(e.data))JSON.stringify(f).length<Ne?p[b]=f:w=!1;return JSON.stringify({v:2,savedAt:e.savedAt,id:e.id,ancestry:e.ancestry,idb:!0,...w&&{full:!0},data:p,w:n})}async function je({store:e,storage:n,doc:p=document,now:w=()=>Date.now(),reload:b=()=>window.location.reload()}){let f=await de(),{key:o}=e,S=o+":reset",u=r=>{try{return n?.getItem(r)??null}catch{return null}},t=r=>{try{n?.removeItem(r)}catch{}},d=o+":started-over",h=o+":recovery-notice";try{window.sessionStorage.getItem(d)&&(window.sessionStorage.removeItem(d),window.sessionStorage.getItem(h)||import("./c-NVU3DORS.js").then(r=>r.toastPersistent(De,"info")).catch(()=>{}))}catch{}let s=null,i="",y=null,g=null,k=null,D=0,c=!1,E=e.held()?.id,l=null,v=null,O=new Set;try{let r=window.sessionStorage.getItem(h);if(r){window.sessionStorage.removeItem(h);let a=B(r);ce({id:a?.mark??r},!!a?.reset)}}catch{}function R(r){try{window.sessionStorage.setItem(h,JSON.stringify({mark:r,reset:!0}))}catch{}}function x(r){try{window.sessionStorage.setItem(o+":generation",JSON.stringify({marker:i,reset:r}))}catch{}}function N(){let r=u(S);i=r??"";let a=e.journalSlots().filter(I=>I!==e.slotKey).map(I=>B(u(I)));k=e.stopped()?null:g,D=e.chain().ops.at(-1)?.seq??0;let m=e.held();m?.v===1&&m.w!==void 0&&(l=m);let A=k?[k]:[];return{seed:e.seed(),newId:e.newId,merge3:e.merge3,unitMark:e.unitMark,now:w(),marker:r,resets:A,local:m,seen:l,direct:v!==null&&u(o)===v,chains:e.pending()?[...a,e.chain()]:a}}function F(r){let a=w();for(let m of e.journalSlots()){if(m===e.slotKey)continue;let A=B(u(m));ie(A,r)&&a-(A?.at??0)>Re&&t(m)}}function ee({meta:r,record:a}){let m=e.held();if(H(m)&&J(m)!==r.foreign)return void setTimeout(G,0);if((u(S)??"")!==r.reset)return;if(!a)return void(m&&t(o));if(m?.w&&m.w.reset===r.reset&&m.w.rev>=r.rev)return;let A={rev:r.rev,reset:r.reset},I=JSON.stringify({...a,w:A});try{if(I.length<=xe){n.setItem(o,I),l={...a,w:A};return}}catch{}try{n.setItem(o,Pe(a,A))}catch{}}async function te(r){c=!0;let a=e.chain(),m=$(a),A=a.ops.some(C=>C.seq>D)||r.meta.recovery?.includes(m)?m:r.meta.recovery?.includes(E)?E:null;if(e.acknowledge(D),e.stop({keepPending:!0}),e.unsafe()){try{await f.putRow(se(o,e.tab),JSON.stringify(e.chain()))}catch(C){throw e.failed(C)}e.acknowledge(e.chain().ops.at(-1)?.seq??0)}ee(r),A&&R(A);let I=e.held();I?.w&&I.w.reset!==r.meta.reset&&t(o);try{window.sessionStorage.setItem(d,"1")}catch{}return x(r.meta.reset),c=!1,b(),r}async function we(){let r=e.generation(),a=()=>{e.stop(),z(!1)},m=()=>(u(S)??"")!==r&&(y===null||(u(S)??"")!==i);if(m())return a();let A=y??Q(r);if(A===null){let L=await re.catch(()=>f.change(o,({meta:U})=>({puts:[],deletes:[],result:{meta:B(U)??ae(r)}}),{timeout:ge}));if(m())return a();if(A=L.meta.gen,L.meta.reset!==r){g={ends:null,marker:r};let U=await W();if(e.stopped())return a();A=U.meta.gen}}let I=he(A+1,e.newId());g={ends:A,marker:I};let C=u(o);e.held()?.w&&t(o);try{n.setItem(S,I)}catch{}let fe;try{let L=W();u(S)!==I?await L:await Promise.race([L.catch(()=>{}),new Promise(U=>{fe=setTimeout(U,Me)})]),a()}catch(L){if(g=null,C!==null&&u(o)===null&&(u(S)??"")===r)try{n.setItem(o,C)}catch{}throw L}finally{clearTimeout(fe)}}function ce(r,a=!1){console.warn(a?"visitor-drafts: the draft was started over; the earlier draft was kept in this browser's draft database under":"visitor-drafts: a tab on an earlier ClayJS saved a copy that could not be merged exactly; it was kept in this browser's draft database under",Z(o,$(r))),!O.has(a)&&(O.add(a),import("./c-NVU3DORS.js").then(m=>m.toastPersistent(a?qe:Je,"warning")).catch(()=>{}))}function be(r){let{meta:a,record:m}=r;if(i!==a.reset&&(u(S)??"")===i)try{n.setItem(S,a.reset)}catch{}if(k&&k===g&&a.reset!==e.generation()&&(k.marker===a.reset&&x(a.reset),e.stop(),z(!1)),k===g&&(g=null),e.stopped())return c?te(r):(ee(r),r);if(r.conflicts.length&&console.warn("visitor-drafts: another tab changed the same thing; its copy was kept in this browser's draft database under",o+":conflict"),r.stale.includes(e.tab))return te(r);if(a.reset!==e.generation()){if(!e.fresh())return te(r);e.enter(a.reset)}r.released.length&&ce(r.released[0]),y=a.gen,x(a.reset);let A=e.acknowledge(a.tabs[e.tab]?.seq??0);if(F(a),ee(r),e.pending())return r;if(A&&(z(!1),p.dispatchEvent(new CustomEvent("clay:drafts-saved",{detail:{data:m.data}}))),!e.shown())return s=a.rev,r;e.changed()||(m&&a.rev!==s&&e.take(m.data),E=m?.id,s=a.rev);let I=e.externalUnit(m);return I&&p.dispatchEvent(new CustomEvent("clay:drafts-blockeditor-external",{detail:{live:I.live,adopted:()=>e.adoptedUnit(I)}})),r}let V=null,j=null;function ne(r){return V=me(f,o,N,r).then(be,a=>{throw e.pending()?e.failed(a):a}).finally(()=>{V=null}),V}function W(){return j||(V?(j=V.then(()=>{},()=>{}).then(()=>(j=null,ne())),j):ne())}let G=()=>{W().catch(()=>{})};function ye(){e.unsafe()&&f.putRow(se(o,e.tab),JSON.stringify(e.chain())).catch(()=>{}),e.pending()&&G()}window.addEventListener("storage",r=>{if(r.key===o){let[a,m]=[B(r.oldValue),B(r.newValue)];m?.v===1&&m.w!==void 0?l=m:H(m)&&a?.v===1&&a.w!==void 0&&([l,v]=[a,r.newValue])}(r.key===null||r.key===o||r.key===S)&&G()}),window.addEventListener("pageshow",r=>{r.persisted&&G()}),p.addEventListener("clay:drafts-blockeditor-listening",G);let re=ne({timeout:ge});return re.catch(()=>{}),{first:re,sync:W,hide:ye,startOver:we}}export{xe as FULL_COPY_LIMIT,je as openSession};
@@ -1 +0,0 @@
1
- import{a as Qt}from"./c-4ASQPRQL.js";import{a as Ot}from"./c-GQ6F6IDK.js";import{c as F}from"./c-I2SCCUEW.js";import{b as We}from"./c-5VYOWDTI.js";import{a as Vt,d as $,e as Ge,f as R,h as N}from"./c-6Q6RGFBF.js";import{a as Ke,b as Yt,c as jt,d as zt}from"./c-SKMIR5HQ.js";import{a as $t}from"./c-UGHH4MB3.js";import{a as Lt}from"./c-LA2BW7UY.js";import{a as Rt,f as Ft,g as P,h as Ut,i as qt,j as Bt,m as Ht,u as Gt,w as Wt,x as Kt}from"./c-MFOSMAVM.js";import{b as Nt,h as He}from"./c-PGSBXHUE.js";import{a as qe,c as It,g as bt,h as Be}from"./c-6IJEVE6B.js";import{a as be,f as Re,h as Q}from"./c-IJUK2GPW.js";import{b as K,e as Pt,f as A}from"./c-EDE45NM7.js";import{i as Ct,k as Mt,m as xt}from"./c-U4NTUVDZ.js";import{E as Ue,h as Ne,r as Fe,u as kt,y as V,z as me}from"./c-PWJSJEJU.js";import{d as Dt}from"./c-VG5XIN4T.js";import{a as pe}from"./c-2YYDMLNZ.js";import{d as Et,e as wt,g as At,h as Tt}from"./c-HA6INT6J.js";import{k as _t}from"./c-ICMAOOGK.js";var An="clay:debug:autosave";function ve(){try{return localStorage.getItem(An)==="true"}catch{return!1}}function ge(){return import("./c-CFHW5AMY.js").catch(e=>(console.warn("[autosave-debug] Failed to load the debug logger:",e),null))}function he(e,t){ve()&&ge().then(n=>n?.logSaveCheck(e,t))}function re(e,t=""){ve()&&ge().then(n=>n?.logBaseline(e,t))}function Xt(e,t){ve()&&ge().then(n=>n?.logUnloadDiffSync(e,t))}function Jt(){ve()&&ge().then(e=>e?.preloadIfEnabled())}var U=Number.NEGATIVE_INFINITY;function Tn({firstDirtyAt:e=U,lastActivityAt:t=U,finishedAt:n=U,costMs:o=0}={}){let r=e??U,i=t??U,a=n??U,f=Math.min(3e4,Math.max(1200,4*o)),u=Math.max(i,a)+1500,m=Math.max(r+1e4,a+f);return Math.max(a+1200,Math.min(u,m))}function Zt({now:e=()=>Date.now(),setTimer:t=(r,i)=>setTimeout(r,i),clearTimer:n=r=>clearTimeout(r),run:o=()=>{}}={}){let r=null,i=null,a=U,f=0,u=null,m=null,c=!1,p=!1;function S(){return Tn({firstDirtyAt:r,lastActivityAt:i,finishedAt:a,costMs:f})}function y(){if(!c||p)return;let E=S();if(u!==null){if(m===E)return;n(u)}m=E,u=t(d,Math.max(0,E-e()))}function d(){if(u=null,m=null,!(!c||p)){if(e()<S()){y();return}g()}}function g(){c=!1,p=!0,r=null,i=null;let E;try{E=o()}catch{l();return}Promise.resolve(E).then(l,l)}function l(){p=!1,a=e(),c&&y()}function s({at:E=e()}={}){r===null&&(r=E),i=E,c=!0,y()}function v(){c=!0,y()}function M(E){E>0&&(f=Math.max(E,f*.8))}return{noteActivity:s,request:v,noteCost:M,dueAt:S,costEstimate:()=>f,pending:()=>c||p,running:()=>p}}Fe(e=>{for(let t of Tt)e.removeAttribute(t)});Fe(e=>{for(let t of[...Et,...wt,...At])e.removeAttribute(t)});var x=null;function w(e,t="",n="",o=null){x&&(clearTimeout(x),x=null),document.documentElement.setAttribute("savestatus",e);let r=new CustomEvent(`clay:save-${e}`,{detail:{msg:t,msgType:n,timestamp:Date.now(),...o||{}}});document.dispatchEvent(r),Mn(e,r.detail)}var an=Symbol.for("clay.saveFailureClaimed"),Br=e=>{e?.detail&&(e.detail[an]=!0)},Ee=null,un=()=>(Ee??=import("./c-BOMQIQ3V.js").catch(e=>{throw Ee=null,e}),Ee),Cn=()=>{un().then(e=>e.warm(),()=>{})};for(let e of["beforeinput","keydown","pointerdown"])document.addEventListener(e,Cn,{once:!0,capture:!0});function Mn(e,t){if(e==="saved"){Ee?.then(n=>n.clearFailures(),()=>{});return}e!=="error"&&e!=="offline"||t?.[an]||un().then(n=>n.reportFailure(e),n=>{console.error("clayjs: a save failed and the notice for it could not be downloaded",n)})}function ot(){x&&(clearTimeout(x),x=null),document.documentElement.setAttribute("savestatus","offline")}function xn(){x=setTimeout(()=>{w("saving")},500)}window.addEventListener("offline",()=>{ot()});window.addEventListener("online",()=>{document.documentElement.getAttribute("savestatus")==="offline"&&I().then(e=>{e.msgType==="skipped"&&document.documentElement.getAttribute("savestatus")==="offline"&&document.documentElement.setAttribute("savestatus","saved")})});var q=!1,k="",C="",ie=0,we=new Set,D=!1,L=!1,Ae=!1,B=0,je=!1;function Pn(){B++}function ln(){B!==0&&(B--,!(B>0)&&(fe&&(fe=!1,Z=setTimeout(mt,0)),je&&(je=!1,Oe())))}function _n(){return B>0}var Y=0,ne=!1,ae=!1,Te=!1;function de(e=null){return Y===0||dn(e)}function st(){return ne}function Dn(){if(ne)return!0;try{let e=V({flushUndo:!1});return St(e)?!1:e!==C}catch{return!0}}function Ln(){let e="idle",t=0;return{get phase(){return e},get open(){return e==="open"},changedWhileClosed(){return e==="quiesced"&&Ge()!==t},start(){e==="idle"&&(e="open")},quiesce(){e==="open"&&(e="quiesced",t=Ge(),Y++)},resume(){e==="quiesced"&&(e="open",Y--,!(Y>0)&&(zn(),on()))},stop(){if(e==="stopped")return;let n=e==="quiesced";(n||e==="open")&&Dn()&&(Te=!0),e="stopped",n&&(Y--,Y===0&&on())}}}var en=!1,oe=null,ze=null,Xe=!1;function Hr(e=b){if(!oe||oe.generation!==e)return null;let{bytes:t,etag:n}=oe;return{bytes:t,etag:n}}function Gr({represented:e}={}){let t=R(),{forComparison:n,forDirty:o}=me(),r=typeof e?.etag=="string"&&e.etag?e.etag:null;return!(Xe&&r!==null&&r!==ze)&&Te&&(n!==k||o!==C)?{ok:!1,code:"pending-input"}:(Te=!1,ue(n,o),W=n,ee=!1,vt=!0,ze=r,Xe=!0,N(t),document.documentElement.setAttribute("savestatus","saved"),document.dispatchEvent(new CustomEvent("clay:baseline-settled")),{ok:!0})}var it=Promise.resolve(!1),Ce=!1,kn=()=>(Ce=!0,bt().catch(()=>!1).then(e=>(Ce=!1,e)));function Wr(){return{id:"clay:save",order:10,prepare(e={}){let t=Ln();return e.initial===!0&&t.start(),{enable(){it=kn();let n=e.represented?.etag;typeof n=="string"&&n&&It(n),e.initial!==!0&&(On(),t.start())},quiesce:()=>t.quiesce(),resume:()=>t.resume(),dispose:()=>t.stop()}}}}function On(){en||(en=!0,Vt(),be(),En(),wn())}var O=0,Je=!1,Me=!1,at="Waiting for the AI edit to be kept or reverted",j=new Map;function Kr(e=at){O++,j.set(e,(j.get(e)||0)+1)}function Qr({replay:e=!0,reason:t=at}={}){let n=j.get(t)||0;if(n===0||(n===1?j.delete(t):j.set(t,n-1),O--,O>0))return;let o=Je,r=Me;Je=!1,Me=!1,e&&(o?I():r&&Oe())}function Vr(){return O>0}function ut(){return O===0?null:j.keys().next().value||at}function fn(e,t){if(O===0)return!1;Je=!0,Q();let n=h(ut());return e(n),t(n),n}var H=!1,se=null;function In(e){se=e??null,!H&&(H=!0,Pn())}function bn(){H&&(H=!1,se=null,ln())}function Ze(){return H}function $r(e){if(!H||se&&e!==se)return;H=!1,se=null,!We()&&$()||(document.documentElement.getAttribute("savestatus")==="conflict"&&document.documentElement.setAttribute("savestatus","saved"),document.dispatchEvent(new CustomEvent("clay:save-conflict-resolved",{detail:{timestamp:Date.now()}}))),document.dispatchEvent(new CustomEvent("clay:save-conflict-released",{detail:{etag:e??null}})),ln()}function h(e){return{ok:!1,msg:e,msgType:"skipped",code:null,etag:null}}function lt(e){return($()||F())&&(ne=!0),h(e)}function cn(){return{ok:!1,msg:"You are not allowed to save this document.",msgType:"forbidden",code:"forbidden",status:403,sent:!1,etag:null}}function ft(){return Pt()===!1}var ct=new Set,b=0;function Yr(){return b}function jr(e){typeof e=="number"&&(b=e)}function Rn(e=b){let t=Object.freeze({generation:e});return ct.add(t),t}function Nn(e){ct.delete(e)}function dn(e){return!!e&&ct.has(e)&&e.generation===b}function z(e,t){e!=null&&zt({captureId:e,ok:t.ok===!0,etag:t.etag??null})}function Fn(e,t,n,o,r,i=null,a=null,f=!1){if(z(a,e),e.ok)ne=!1,ue(t,n),xe=i,oe={bytes:i,etag:qe(),generation:b},ze=oe.etag,Xe=!0,Te=!1,q=!1,N(r),w("saved",e.msg||"Saved",e.msgType,{etag:e.etag??null,captureId:a}),re(o,`${k.length} chars`),bn();else if(e.msgType==="conflict"){if(f){x&&(clearTimeout(x),x=null),document.documentElement.setAttribute("savestatus","saved");return}In(e.conflictEtag),w("conflict",e.msg,e.msgType,{hadTimeout:e.hadTimeout===!0,changedBy:e.changedBy??null,afterTimeout:e.afterTimeout===!0,etag:e.conflictEtag??null,code:e.code??null,reason:e.reason??null,retryAfter:e.retryAfter??null,captureId:a})}else if(e.msgType!=="skipped"){let u={status:e.status??null,hadTimeout:e.hadTimeout===!0,code:e.code??null,reason:e.reason??null,retryAfter:e.retryAfter??null,captureId:a};navigator.onLine?w("error",e.msg,"",u):w("offline",e.msg,"",u)}}function pn(){if(!(!D&&!L)&&!Ht()){if(D){D=!1,L=!1,I();return}L=!1,nt.request()}}function zr(){return q}function Xr(e){q=e}function Jr(){return k}function dt(){return C}var xe=null;function Zr(){return xe}function ue(e,t){k=e,C=t,ie++}function eo(e){ue(e,e)}var G=()=>typeof performance<"u"&&performance.now?performance.now():Date.now();var Un=4,tn="Save cancelled: the page changed while it prepared",X=null,le=null,Qe=null,mn=!1;function vn(){return Qe||(Qe=import("./c-OG6GFSUX.js").then(e=>(le=e,e),e=>(mn=!0,console.info("clayjs: sliced save off ("+(e&&e.message?e.message:e)+"); saves prepare in one task"),null))),Qe}function qn(){try{return performance.getEntriesByType("navigation")[0]?.decodedBodySize||0}catch{return 0}}var Bn=()=>typeof xe=="string"?xe.length:qn();function Pe(){return mn||document.hidden||Bt()?!1:Bn()>=307200}function nn(e,t,n){return n?"morph":b!==t.generation||!A?"mode":de(e.permit)?ft()?"refused":ie!==t.baselines?"newer save":Math.max(He(),e.blockeditorFormatFloor)>t.floor?"floor":null:"session"}function Hn(e=150,t=2e3){return new Promise(n=>{let o=G(),r=null,i=()=>{document.removeEventListener("clay:sync-applied",a),n()},a=()=>{clearTimeout(r),r=setTimeout(i,Math.max(0,Math.min(e,t-(G()-o))))};document.addEventListener("clay:sync-applied",a),a()})}async function pt({explicit:e,forced:t=!1,forSave:n,forComparison:o,forDirty:r,captureId:i,gateToken:a,costMs:f,blockeditorFormatFloor:u=0,quietConflict:m=!1,laneHeld:c=!1,lane:p=null,capture:S,noteRecovery:y,release:d,callback:g}){if(y(),e&&!t){if(q=r!==C,he("savePage dirty check",!q),!q){Q(),N(a),d();let s=h("No changes to save");return z(i,s),typeof g=="function"&&g(s),{result:s,dispatched:!1}}}else if(!e){let s=!ee||o!==W,v=o!==k;if(he("throttled vs baseline",!s),he("throttled vs lastSave",!v),!(s&&v)){let M=!1;try{M=!v&&(!document.querySelector(_t)||$()&&r===C)}catch(yt){console.error("savePageThrottled: dirty domain check failed",yt)}M&&N(a),nt.noteCost(f),d();let E=h("No changes to save");return z(i,E),typeof g=="function"&&g(E),{result:E,dispatched:!1}}if(q=!0,!c&&P()){D=!0,d();let M=h("Save already in progress");return z(i,M),typeof g=="function"&&g(M),{result:M,dispatched:!1}}}xn();let l={forComparison:o,forDirty:r};return we.add(l),Ae=!0,new Promise(s=>{Gt(n,i,v=>{Ae=!1,we.delete(l);let M=G();Fn(v,l.forComparison,l.forDirty,t?"updated after force save":"updated after save",a,n,i,m),e||nt.noteCost(f+(G()-M)),typeof g=="function"&&g(v),s({result:v,dispatched:!0}),c||pn()},{capture:S,blockeditorFormatFloor:u,lane:p})})}async function Gn(e,t){let n={over:!1},o=()=>{n.over=!0};document.addEventListener("clay:sync-applied",o);try{for(let i=0;i<2;i++){let a=R(),f={generation:b,baselines:ie,floor:Math.max(He(),e.blockeditorFormatFloor)},u=le.beginSaveCapture({requestRefresh:!0,forRequest:!0,pageFormatMarker:f.floor?{name:Nt,content:String(f.floor)}:null});Yt(u.captureId);let m=null,c={get aborted(){let d=nn(e,f,n.over);return d&&(m=d),!!d}},p;try{p=await le.runPreparedSteps(u.steps(),{budgetMs:Un,signal:c})}catch(d){console.error(`${e.explicit?"savePage":"savePageThrottled"}: preparing the save failed`,d),u.drop();let g={msg:d&&d.message?d.message:"Save failed",msgType:"error",code:d?.code??null,etag:null};return w("error",g.msg,"",{sent:!1,code:g.code}),z(u.captureId,g),typeof e.callback=="function"&&e.callback(g),{result:g,dispatched:!1}}let S=p.aborted?m:nn(e,f,n.over);if(!S){let d=p.result;return await pt({explicit:e.explicit,forced:e.forced,forSave:d.forSave,forComparison:d.forComparison,forDirty:d.forDirty,captureId:d.captureId,gateToken:a,costMs:p.activeMs,blockeditorFormatFloor:e.blockeditorFormatFloor,quietConflict:e.quietConflict,laneHeld:!0,lane:t,capture:d,noteRecovery:()=>jt(d.captureId,d.forSave),release:()=>u.drop(),callback:e.callback})}u.drop();let y=h(tn);if(S==="session"&&(ae=!0),z(u.captureId,y),!(S==="floor"&&i===0)){if(S==="morph"&&e.explicit&&i===0){await Hn(),n.over=!1;continue}return typeof e.callback=="function"&&e.callback(y),{result:y,dispatched:!1}}}let r=h(tn);return typeof e.callback=="function"&&e.callback(r),{result:r,dispatched:!1}}finally{document.removeEventListener("clay:sync-applied",o),qt(t)}}function gn(e){let t=Ut();if(!t)return!1;let n=Gn(e,t).catch(o=>{console.error("save: preparing the save failed",o);let r={msg:o&&o.message?o.message:"Save failed",msgType:"error",code:o?.code??null,etag:null};return w("error",r.msg,"",{sent:!1,code:r.code}),typeof e.callback=="function"&&e.callback(r),{result:r,dispatched:!1}});return X=n,n.then(o=>{X===n&&(X=null),e.resolve(o.result),e.settleSoonQueued(o.result),(o.dispatched||D||L||Le.length)&&pn()}),!0}function ke(e,t=()=>{}){return Ce?it.then(()=>ke(e,t)):te?ce.then(()=>De(e,t)):De(e,t)}function _e(e,t){let n=!1,o=setTimeout(()=>{n=!0,w("saving")},500);return e.then(()=>(clearTimeout(o),t())).then(r=>(n&&!P()&&!$()&&document.documentElement.getAttribute("savestatus")==="saving"&&(document.documentElement.setAttribute("savestatus","saved"),document.dispatchEvent(new CustomEvent("clay:save-status",{detail:{state:"saved"}}))),r))}function De({kind:e,permit:t=null},n=()=>{}){let o=e==="explicit";return new Promise(r=>{if(!A&&!window.clay?.testMode){o&&Q();let s=h("Not in edit mode");return T().forEach(v=>v(s)),n(s),r(s)}if(!de(t)){ae=!0;let s=lt("Save session is quiesced");return o&&T().forEach(v=>v(s)),n(s),r(s)}if(ft()){o&&Q();let s=cn();return w("error",s.msg,"",{code:s.code,status:s.status,sent:!1}),T().forEach(v=>v(s)),n(s),r(s)}if(o){let s=fn(n,r);if(s){T().forEach(v=>v(s));return}if(P()){D=!0;let v=h("Save already in progress");return n(v),r(v)}}else{if(O>0){Me=!0;let s=h(ut());return n(s),r(s)}if(P()&&!ee&&Ae){L=!0;let s=h("Save already in progress");return n(s),r(s)}if(X){L=!0;let s=h("Save already in progress");return n(s),r(s)}if(!ee&&!$()){let s=h("No changes to save");return n(s),r(s)}}let i=window.clay?.source?.ensureForSave?.();if(i)return r(_e(i,()=>De({kind:e,permit:t},n)));if(Pe()&&!le){r(_e(vn(),()=>De({kind:e,permit:t},n)));return}let a=o?T():[],f=s=>a.forEach(v=>v(s));if(!navigator.onLine&&ot(),Pe()&&gn({explicit:o,forced:!1,permit:t,blockeditorFormatFloor:0,quietConflict:!1,settleSoonQueued:f,callback:n,resolve:r}))return;let m=G(),c,p,S,y,d,g=R();try{c=Ue({requestRefresh:!0,forRequest:!0}),{forSave:p,forComparison:S,forDirty:y,captureId:d}=c}catch(s){console.error(`${o?"savePage":"savePageThrottled"}: captureForSaveAndComparison failed`,s),o?(Q(),w("error",s.message,"",{sent:!1,code:s.code??null})):w("error",s.message);let v={msg:s.message,msgType:"error",code:o?s.code??null:null,etag:null};typeof n=="function"&&n(v),r(v),f(v);return}let l=G()-m;pt({explicit:o,forSave:p,forComparison:S,forDirty:y,captureId:d,gateToken:g,costMs:l,capture:c,noteRecovery:()=>Ke({captureId:d,html:p}),release:()=>Ne(c),callback:n}).then(s=>{r(s.result),f(s.result)})})}function I(e=()=>{}){return ke({kind:"explicit"},e)}function Wn(e,t=()=>{}){return ke({kind:"explicit",permit:e},t)}function J(e=()=>{},{quietConflict:t=!1,blockeditorFormatFloor:n=0,permit:o=null}={}){return Ce?it.then(()=>J(e,{quietConflict:t,blockeditorFormatFloor:n,permit:o})):new Promise(r=>{if(!A&&!window.clay?.testMode){let l=h("Not in edit mode");return T().forEach(s=>s(l)),e(l),r(l)}if(!de(o)||o&&!dn(o)){let l=lt("Save session is quiesced");return T().forEach(s=>s(l)),e(l),r(l)}if(ft()){let l=cn();return w("error",l.msg,"",{code:l.code,status:l.status,sent:!1}),T().forEach(s=>s(l)),e(l),r(l)}let i=fn(e,r);if(i){T().forEach(l=>l(i));return}if(P()){D=!0;let l=h("Save already in progress");return T().forEach(s=>s(l)),e(l),r(l)}let a=window.clay?.source?.ensureForSave?.();if(a)return r(_e(a,()=>J(e,{quietConflict:t,blockeditorFormatFloor:n,permit:o})));if(!navigator.onLine&&ot(),Pe()&&!le){r(_e(vn(),()=>J(e,{quietConflict:t,blockeditorFormatFloor:n,permit:o})));return}let u=T(),m=l=>u.forEach(s=>s(l));if(Pe()&&gn({explicit:!0,forced:!0,permit:o,blockeditorFormatFloor:n,quietConflict:t,settleSoonQueued:m,callback:e,resolve:r}))return;let c,p,S,y,d,g=R();try{c=Ue({requestRefresh:!0,forRequest:!0}),{forSave:p,forComparison:S,forDirty:y,captureId:d}=c}catch(l){console.error("savePageForce: captureForSaveAndComparison failed",l),w("error",l.message,"",{sent:!1,code:l.code??null});let s={msg:l.message,msgType:"error",code:l.code??null,etag:null};typeof e=="function"&&e(s),r(s),m(s);return}pt({explicit:!0,forced:!0,forSave:p,forComparison:S,forDirty:y,captureId:d,gateToken:g,costMs:0,blockeditorFormatFloor:n,quietConflict:t,capture:c,noteRecovery:()=>Ke({captureId:d,html:p}),release:()=>Ne(c),callback:e}).then(l=>{r(l.result),m(l.result)})})}Kt(e=>J(()=>{},{permit:e}));function Kn(e){let t=["clay:save-saved","clay:save-error","clay:save-offline","clay:save-conflict"];return new Promise((n,o)=>{let r=null,i=()=>{clearTimeout(r);for(let u of t)document.removeEventListener(u,a)},a=()=>{i(),n()},f=e-Date.now();if(f<=0){o(Object.assign(new Error("Save timed out."),{state:"failed"}));return}r=setTimeout(()=>{i(),o(Object.assign(new Error("Save timed out."),{state:"failed"}))},f);for(let u of t)document.addEventListener(u,a)})}function _(e,t){return Object.assign(new Error(e),{state:t})}function Qn(e,t){return new Promise((n,o)=>{let r=t-Date.now();if(r<=0)return o(_("Save timed out.","failed"));let i=setTimeout(()=>{document.removeEventListener(e,a),o(_("Save timed out.","failed"))},r),a=()=>{clearTimeout(i),n()};document.addEventListener(e,a,{once:!0})})}async function to({keepalive:e=!1,timeoutMs:t=15e3,permit:n=null}={}){if(!A)return{state:"view",etag:null};let o=Date.now()+t,r=n||Rn(),i={over:!1},a=null,f=new Promise((u,m)=>{a=setTimeout(()=>m(Object.assign(_("Save timed out.","failed"),{timedOut:!0})),Math.max(0,t))});try{return await Promise.race([Vn(e,o,r,i),f])}catch(u){throw u&&typeof u.state=="string"?u:_(u?.message||"Save failed","failed")}finally{i.over=!0,clearTimeout(a),n||Nn(r)}}async function Vn(e,t,n,o={over:!1}){if(hn()||await Qn("clay:baseline-settled",t),o.over)return null;let r=!1,i=null;for(let a=0;a<4;a++){if(X&&(await X,o.over)||P()&&(await Kn(t),o.over))return null;if(Ze())throw _("This document has a conflict to resolve.","conflict");let f=R();if(!rt()){if(N(f),F())throw _("This document has unsaved work a save cannot write.","blocked");return ne=!1,{state:r?"saved":"clean",etag:i??qe()}}if(o.over)return null;let u=await Ft(e,()=>Wn(n));if(u.msgType!=="skipped"){if(!u.ok)throw _(u.msg||"Save failed",u.msgType==="conflict"||Ze()?"conflict":"failed");r=!0,i=u.etag??null}}throw _("The document kept changing while saving.","failed")}async function no(e=()=>{}){return await Be({fresh:!0}),J(e)}function ro(e){!A||K||Wt(e,t=>{t.ok?window.location.reload():t.msgType==="skipped"?w("error",t.msg||"Template not saved"):w("error",t.msg||"Failed to save template")})}var $n=Ot(e=>ke({kind:"automatic"},e),1200),Yn=250,jn=1e3,Z=null,rn=0,et=[],Le=[],fe=!1,T=()=>{let e=Le;return Le=[],e};function mt(){if(Z=null,B>0||!de()){fe=!0;return}let e=et;if(et=[],P()){Le.push(...e),I();return}I().then(t=>e.forEach(n=>n(t)))}function oo(){let e=Date.now();return Z===null?rn=e:clearTimeout(Z),new Promise(t=>{et.push(t),Z=setTimeout(mt,Math.max(0,Math.min(Yn,rn+jn-e)))})}function zn(){ae&&(ae=!1,Oe())}function on(){fe&&(fe=!1,Z=setTimeout(mt,0))}var W="",ee=!0,vt=!1;function hn(){return vt}var Ve=!1,Xn=250,Jn=1250,$e=null,Sn="clay:paint-heal:"+location.pathname;function yn(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t+e.charCodeAt(n)|0;return String(t>>>0)}function Zn(e){try{return localStorage.getItem(Sn)===yn(e)}catch{return!1}}function er(e){try{localStorage.setItem(Sn,yn(e))}catch{}}function tr(){return Dt(kt({flushUndo:!1}))}function so(e){!A||K||(clearTimeout($e),$e=setTimeout(async()=>{$e=null,te&&await ce;let t=typeof e=="function"?e():e;t==null||!We()||!hn()||Ze()||_n()||V({flushUndo:!1})===C&&t!==tr()&&(Zn(t)||(er(t),J(()=>{},{quietConflict:!0})))},Xn+Math.random()*Jn))}var Se=null,Ye=null,te=0,ce=Promise.resolve(),gt=!1,ht=[];function nr(){return Ye??=import("./c-KNPDOMDY.js").catch(e=>(Ye=null,console.error("style-comparisons failed to load",e),null)),Ye}async function rr(e){try{if(Se||(Se=(await nr())?.styleComparisonStripper??null),!Se)return;let t=Se(e);k=t(k),C=t(C),W=t(W);for(let n of we)n.forComparison=t(n.forComparison),n.forDirty=t(n.forDirty)}catch(t){console.error("style adoption failed",t)}finally{te--,ht.shift()}}var ye=e=>e.replace(/&/g,"&amp;").replace(/"/g,"&quot;");function or(e){if(e.name!==void 0){let n=[`data-name="${ye(e.name)}"`];return e.legacyId!==void 0&&n.push(`id="${ye(e.legacyId)}"`),n}let t=[ye(e.href)];try{let{pathname:n}=new URL(e.href);n&&t.push(ye(n))}catch{}return t}function sr(e){let t=[k,C,W];for(let n of we)t.push(n.forComparison,n.forDirty);return t.some(n=>n&&e.some(o=>o&&n.includes(o)))}function ir(e,t){let n=[];for(let{markers:i,tag:a}of t)for(let f of i)for(let u=e.indexOf(f);u>=0;u=e.indexOf(f,u+f.length)){let m=e.lastIndexOf("<",u);if(m<0||e.slice(m+1,m+1+a.length).toLowerCase()!==a)continue;let c=a==="style"?e.indexOf("</style",u):u;if(c<0)continue;let p=e.indexOf(">",c);p>=0&&n.push([m,p+1])}n.sort((i,a)=>i[0]-a[0]);let o="",r=0;for(let[i,a]of n)i<r||(o+=e.slice(r,i),r=a);return o+e.slice(r)}$t(e=>{let t=or(e);sr(t)&&(te||(gt=!1),te++,ht.push({markers:t,tag:e.name!==void 0?"style":"link"}),ce=ce.then(()=>rr(e)))});function io(){return ce}function St(e){return!te||gt||F()||P()||D||L||ne||typeof e!="string"?!1:e===ir(C,ht)}var ar=500,ur=3e3,lr=1e4,tt=null;function fr(){pe.holdSettle=!1,tt&&tt()}function sn(){if(!A)return;let e=!1,t=null,{forComparison:n,forDirty:o}=me();ue(n,o);let r=ie;W=n,re("immediate capture",`${n.length} chars`);let i=["keydown","pointerdown","drop","input","change","paste"],a=new Set(["Shift","Control","Alt","Meta"]),f=c=>{c.type==="keydown"&&a.has(c.key)||(gt=!0,e||(Ve=!0))};i.forEach(c=>document.addEventListener(c,f,!0));let u=()=>{if(!e){if(e=!0,t&&t(),!Ve&&ie===r){let c=R(),{forComparison:p,forDirty:S}=me();ue(p,S),W=p,N(c),re("settled capture",`${p.length} chars`)}else re("settled skipped",Ve?"user edited":"save occurred during settle");ee=!1,document.documentElement.setAttribute("savestatus","saved"),vt=!0,document.dispatchEvent(new CustomEvent("clay:baseline-settled"))}};tt=u;let m=()=>{pe.holdSettle||u()};t=Lt.onAnyChange({debounce:ar,omitChangeDetails:!0,require:"autosave"},m),setTimeout(()=>{e||m()},ur),setTimeout(()=>{!e&&pe.holdSettle&&fr()},lr)}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",sn):sn();function Oe(e=()=>{}){if(!A){let t=h("Not in edit mode");return e(t),Promise.resolve(t)}if(O>0){Me=!0;let t=h(ut());return e(t),Promise.resolve(t)}if(!de()){ae=!0;let t=lt("Save session is quiesced");return e(t),Promise.resolve(t)}if(B>0){je=!0;let t=h("Autosave suspended");return e(t),Promise.resolve(t)}if(!ee&&Ae){L=!0;let t=h("Save already in progress");return e(t),Promise.resolve(t)}return $n(e).catch(t=>{let n={ok:!1,msg:t?.message||"Save failed",msgType:"error",code:null,etag:null};return w("error",n.msg),n})}var nt=Zt({now:G,run:()=>Oe()});function En(){document.addEventListener("keydown",function(e){if((window.navigator.platform.match("Mac")?e.metaKey:e.ctrlKey)&&e.keyCode==83){if(!A)return;e.preventDefault(),e.isTrusted&&Re(),I()}})}function wn(){document.addEventListener("click",e=>{e.target.closest("[trigger-save]")&&(e.isTrusted&&Re(),I())})}function cr(){A&&(Be(),Rt(),be(),En(),wn())}cr();var ao=I;var Ie=!1;function go({isCurrent:e,reload:t}){return e()?(Ie=!0,setTimeout(()=>{Ie=!1},1e3),t(),!0):!1}Jt();function dr(){return st()?!0:A?F()?!0:K?Mt()||xt():window.clay?.demo?!1:rt():!1}function rt(){if(!A)return!1;try{let e=V();return St(e)?!1:e!==dt()}catch{return!0}}window.addEventListener("beforeunload",e=>{if(!A&&!st())return;if(Ie){Ie=!1;return}if(!((!K||Ct())&&!dr())&&(e.preventDefault(),e.returnValue="",!window.clay?.demo&&!F()))try{let n=V(),o=dt();n!==o&&Xt(n,o)}catch{}});export{go as a,dr as b,rt as c,Br as d,Pn as e,ln as f,_n as g,de as h,st as i,Ln as j,Hr as k,Gr as l,Wr as m,Kr as n,Qr as o,Vr as p,ut as q,Ze as r,$r as s,Yr as t,jr as u,Rn as v,Nn as w,zr as x,Xr as y,Jr as z,dt as A,Zr as B,ue as C,eo as D,I as E,J as F,to as G,no as H,ro as I,oo as J,hn as K,tr as L,so as M,io as N,St as O,fr as P,Oe as Q,nt as R,En as S,wn as T,cr as U,ao as V};
@@ -1,3 +0,0 @@
1
- import{b as D}from"./c-LD6UVV5R.js";import{a as ie,g as se,h as U}from"./c-PGSBXHUE.js";import{a as re,b as oe,c as M}from"./c-6IJEVE6B.js";import{d as w}from"./c-QQFHEODI.js";import{c as q,e as Z,g as Q}from"./c-IJUK2GPW.js";import{b as R,f as N}from"./c-EDE45NM7.js";import{c as Y}from"./c-BPF2NSPV.js";import{g as V}from"./c-U4NTUVDZ.js";import{a as k,g as ee,h as te,i as ne}from"./c-PWJSJEJU.js";var C=null,le=null,A=null;function Ae(e){let t=e?.document?.maxBytes;return Number.isSafeInteger(t)&&t>0?t:null}function ae(e){return C=Ae(e),le=e?.document?.maxBytesMeasures==="file"?"file":null,C}var Te=/<script\b[^>]*\bmerge=(["'])blockeditor\1[^>]*>[\s\S]*?<\/script\s*>/i;function F(e,t=le){if(t!=="file"||typeof e!="string")return e;let n=Te.exec(e);if(!n)return e;let o=n.index,s=o+n[0].length,r=e.lastIndexOf(`
2
- `,o-1)+1,l=e.indexOf(`
3
- `,s),c=l===-1?e.length:l+1;return!/\S/.test(e.slice(r,o))&&!/\S/.test(e.slice(s,c))&&(o=r,s=c),e.slice(0,o)+e.slice(s)}function B(e,t){let n=new TextEncoder().encode(e).byteLength,o=Number.isSafeInteger(t)&&t>0;return{bytes:n,maxBytes:o?t:null,state:o?n>t?"over":n>=Math.ceil(t*.8)?"near":"ok":"unknown"}}function ue(){return C}function j({fresh:e=!1}={}){return e?(A=w({fresh:!0}).then(ae),A):(A||(A=w().then(ae)),A)}function yt({fresh:e=!1}={}){return j({fresh:e}).then(t=>({maxBytes:t}))}async function St(e){let t=await j();return B(F(e),t)}function ce(e){let t=new CustomEvent("clay:save-size",{detail:e});document.dispatchEvent(t),(e.state==="near"||e.state==="over")&&import("./c-BGN7RCTJ.js").then(n=>n.start(t),()=>{})}var L="/_/clayjs/",be=/[\u0000-\u001F\u007F]/,Oe=/^[\t\n\f\r ]|[\t\n\f\r ]$/,Ee=/^https:\/\/clayjs\.com\/v(\d+)\/([\s\S]*)$/,$e=/^https:\/\/clayjs\.com\/(\d+)\.(\d+)\.(\d+)\/([\s\S]*)$/,fe=/^\/_\/clayjs\/(\d+)\.(\d+)\.(\d+)\/([\s\S]*)$/,Re=/%2e|%2f|%5c/i;function ke(e){if(typeof e!="string")return null;let t=/^(\d+)\.\d+\.\d+$/.exec(e);return t?t[1]:null}function Me(e){if(typeof e!="string"||e==="")return null;try{return new URL(e).origin}catch{return null}}function je(e){let t=e.indexOf("#"),n=t<0?"":e.slice(t),o=t<0?e:e.slice(0,t),s=o.indexOf("?"),r=s<0?"":o.slice(s);return{head:s<0?o:o.slice(0,s),search:r,hash:n}}function Le(e){if(e===""||e.includes("\\")||Re.test(e))return null;let t=e.split("/"),n=[];for(let o of t){if(o===""||o==="."||o==="..")return null;let s;try{s=decodeURIComponent(o)}catch{return null}if(s.includes("/")||s.includes("\\")||s==="."||s==="..")return null;n.push(s)}return n.join("/")}function T(e,{documentURL:t}={}){if(typeof e!="string"||e===""||Oe.test(e)||be.test(e))return null;let{head:n,search:o,hash:s}=je(e),r=null,l=null,c=null,u=null,i=Ee.exec(n);if(i&&(r="rolling",c=i[1],u=i[2]),r||(i=$e.exec(n),i&&(r="exact",l=`${i[1]}.${i[2]}.${i[3]}`,c=i[1],u=i[4])),r||(i=fe.exec(n),i&&(r="local",l=`${i[1]}.${i[2]}.${i[3]}`,c=i[1],u=i[4])),!r){let d=Me(t);d&&n.startsWith(`${d}/`)&&(i=fe.exec(n.slice(d.length)),i&&(r="local",l=`${i[1]}.${i[2]}.${i[3]}`,c=i[1],u=i[4]))}if(!r)return null;let a=Le(u);return a===null?null:{kind:r,major:c,version:l,rawPath:u,path:a,search:o,hash:s}}function Pe(e,t){let n=e&&typeof e=="object"?e[t]:null;return n&&typeof n.files=="object"&&n.files?n.files:null}function Ie(e){return!e||typeof e!="object"?[]:Array.isArray(e.entries)?e.entries.filter(t=>t&&typeof t=="object"):[]}function _e(e,t,n){if(!n)return!0;let o=Pe(n,t);return!!(o&&Object.hasOwn(o,e.path))}function de(e,{descriptor:t,releases:n,documentURL:o,aliases:s}={}){let r=T(e,{documentURL:o});if(!r||r.kind!=="local")return e;let l=Ie(t),c=ke(r.version);for(let u of l){if(u.local!==e||typeof u.original!="string")continue;let i=n?.[r.version]?.aliases??s;if(i&&typeof i=="object"&&!r.search&&!r.hash&&Object.hasOwn(i,u.original)&&i[u.original]===r.path)return u.original;let a=T(u.original);if(a&&!(a.kind!=="rolling"&&a.kind!=="exact")&&a.rawPath===r.rawPath&&a.search===r.search&&a.hash===r.hash&&!(a.kind==="rolling"?a.major!==c:a.version!==r.version)&&_e(r,r.version,n))return a.kind==="exact"?u.original:`https://clayjs.com/v${a.major}/${r.rawPath}${r.search}${r.hash}`}for(let u of l){if(typeof u.original!="string")continue;let i=T(u.original);if(i&&!(i.kind!=="rolling"&&i.kind!=="exact")&&i.rawPath===r.rawPath&&!(i.kind==="rolling"?i.major!==c:i.version!==r.version))return i.kind==="rolling"?`https://clayjs.com/v${i.major}/${r.rawPath}${r.search}${r.hash}`:`https://clayjs.com/${i.version}/${r.rawPath}${r.search}${r.hash}`}return`https://clayjs.com/${r.version}/${r.rawPath}${r.search}${r.hash}`}var Ne=Object.freeze({"https://cdn.jsdelivr.net/npm/overtype@2.6.1/dist/overtype.min.js":"compat/overtype-2.6.1.min.js","https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js":"compat/highlight-11.9.0.min.js","https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:ital,wght@0,300;0,400;0,500;0,600;1,400;1,500&family=IBM+Plex+Sans:wght@400;500;600&display=swap":"fonts/ibm-plex.css"}),J="clay-runtime-map",De=new Set(["stylesheet","preload","modulepreload"]),he=null,H=null;function Ue(e){let t;try{t=JSON.parse(e)}catch{return null}return!t||typeof t!="object"||t.schema!==1?null:t}function Ce(){if(typeof document>"u")return null;let e=document.getElementById(J);if(!e)return null;let t=e.textContent??"";return t===he||(he=t,H=Ue(t)),H}var Fe=`script[src*="${L}"], link[href*="${L}"], #${J}`;function pe(e){if(e.querySelector(Fe))return!0;for(let t of e.querySelectorAll("template"))if(pe(t.content))return!0;return!1}function Be(e){let t=[],n=[e];for(;n.length;){let o=n.pop();for(let s of o.children??[])t.push(s),n.push(s),s.content&&n.push(s.content)}return t}function He(e){return e.tagName==="SCRIPT"&&e.hasAttribute("src")?"src":e.tagName!=="LINK"||!e.hasAttribute("href")?null:(e.getAttribute("rel")??"").toLowerCase().split(/\s+/).some(n=>De.has(n))?"href":null}function Je(e){if(!e||!pe(e))return;let t=[],n=!1;for(let r of Be(e)){if(r.getAttribute("id")===J){r.remove();continue}let l=He(r);l&&(t.push({element:r,name:l}),!n&&(r.getAttribute(l)??"").includes(L)&&(n=!0))}if(!n)return;let o=location.href,s=Ce();for(let{element:r,name:l}of t){let c=r.getAttribute(l),u=T(c,{documentURL:o});!u||u.kind!=="local"||r.setAttribute(l,de(c,{descriptor:s,documentURL:o,aliases:Ne}))}}ne(Je);var S=!1,E=null,me="/_/save",Ge=12e3,ge=6e4,Ke=1024*1024,xe="text/plain;charset=UTF-8",P=null,$=!1,G=new Map;function Bt(e,t){t==null?G.delete(e):G.set(e,String(t))}var K=new Set;function Ht(e){return K.add(e),()=>K.delete(e)}async function Jt(e,t){$=!!e;try{return await t()}finally{$=!1}}function zt(){return S}function Gt(){return S?null:(S=!0,E={reserved:!0},E)}function Kt(e){!e||E!==e||(E=null,S=!1)}function Wt(){return $}var I=[],_=[];function Xt(e){return I.push(e),()=>{let t=I.indexOf(e);t>=0&&I.splice(t,1)}}function Yt(e){return _.push(e),()=>{let t=_.indexOf(e);t>=0&&_.splice(t,1)}}function We(e){for(let t of I)try{t(e)}catch(n){console.error("clayjs: onSaveAttempt hook failed:",n)}}function Xe(e){for(let t of _)try{t(e)}catch(n){console.error("clayjs: onSaveOutcome hook failed:",n)}}function ve(e){return{ok:!0,msg:e.msg??"Saved",msgType:e.msgType||"success",code:e.code??null,etag:e.etag??null,...e.siteData?{siteData:e.siteData}:{}}}var b=[],Ye=8,y=null;function Vt(){return y!==null}function ye(){let e=window.crypto?.randomUUID?.();if(e)return e;if(window.crypto?.getRandomValues){let n=new Uint8Array(16);return window.crypto.getRandomValues(n),Array.from(n,o=>o.toString(16).padStart(2,"0")).join("")}let t=()=>Math.random().toString(36).slice(2,12).padEnd(10,"0");return`${Date.now().toString(36)}-${t()}${t()}${t()}`}function Ve(e){b.push(e),b.length>Ye&&b.shift()}function qe(e){return typeof e=="string"&&e!==""&&b.includes(e)}function qt(){b.length=0,y=null}function W(e){let t=e.name==="AbortError",n=!t&&e.status===412,o=!t&&!n&&e.code==="save-already-applied";return{ok:!1,msg:t?"Server not responding":e.message||"Save failed",msgType:t||o?"unknown":n?"conflict":"error",code:t?"timeout":n?"conflict":e.code??null,changedBy:n?e.changedBy??null:null,afterTimeout:n&&y!==null,conflictEtag:n?e.etag??null:null,status:Number.isInteger(e.status)?e.status:null,hadTimeout:t||e.hadTimeout===!0,reason:e.reason??null,retryAfter:e.retryAfter??null,saveOutcome:e.saveOutcome??null,etag:null}}function O(e){return{ok:!1,msg:e,msgType:"skipped",code:null,etag:null}}function Ze(e){let t=new Error(`This document is ${e.bytes} bytes; this host saves at most ${e.maxBytes}`);return t.code="save-too-large",{...W(t),sent:!1,size:e}}var x=null;function Qe(e){return x?null:(x={kind:e},x)}function et(e){x===e&&(x=null)}function tt(){return x?x.kind:null}function nt(){return{ok:!1,msg:"Invalid page conversion metadata",msgType:"error",code:"invalid-header",etag:null}}var rt=3,ot=/^(?:(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT|(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), \d{2}-(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-\d{2} \d{2}:\d{2}:\d{2} GMT|(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (?: \d|\d{2}) \d{2}:\d{2}:\d{2} \d{4})$/;function it(e){if(e==null)return null;let t=String(e).trim();if(!t)return null;if(/^-?\d+$/.test(t))return Math.max(0,Math.min(3600,Number(t)));if(!ot.test(t))return null;let n=Date.parse(t);return Number.isNaN(n)?null:Math.max(0,Math.min(3600,Math.round((n-Date.now())/1e3)))}var st=/^[0-9a-f]{64}$/,at=/^[A-Za-z0-9-]{1,64}$/;function lt(e){if(e==null)return{header:null};if(typeof e!="object")return{invalid:!0};let{source:t,base:n,epoch:o}=e;return typeof n!="string"||!st.test(n)?{invalid:!0}:t==="file"?o!=null?{invalid:!0}:{header:`v1; source=file; base=${n}`}:t==="room"?typeof o!="string"||!at.test(o)?{invalid:!0}:{header:`v1; source=room; base=${n}; epoch=${o}`}:{invalid:!0}}function ut(e,t,n,o,s,r=!1,l=null,c=!0){let u=Y(),i=u?`${me}/${u}`:me,a={method:"POST",credentials:u?"omit":"same-origin",signal:n,headers:{"Document-URL":window.location.href,"Page-URL":window.location.href,"Save-Trigger":t?"user":"auto","Save-ID":o,[ie]:String(1)},body:ct(e)};for(let[d,h]of G)a.headers[d]=h;if(c)for(let d of K){let h=null;try{h=d(e)}catch(g){console.error("clayjs: a save header source failed:",g)}if(h)for(let[g,f]of Object.entries(h))a.headers[g]=String(f)}return typeof a.body!="string"&&(a.headers["Content-Type"]=xe),l&&(a.headers["Blockeditor-Conversion"]=l),s&&(a.headers["If-Match"]=s),r&&e.length<ge&&new Blob([e]).size<ge&&(a.keepalive=!0),{url:ft(i),options:a}}function ct(e){if(e.length<Ke)return e;if(P&&P.content===e)return P.blob;let t=new Blob([e],{type:xe});return P={content:e,blob:t},t}function Se(){let e=re();return oe()&&e?e:null}function ft(e){let t=window.location.origin;return!t||t==="null"?e:new URL(e,t).href}function z(e,t){let n=JSON.stringify(t);return{ok:e>=200&&e<300,status:e,statusText:e===200?"OK":"Insufficient Storage",text:()=>Promise.resolve(n)}}function dt(e){let t=V();return t?Promise.resolve().then(()=>t(e)).then(()=>z(200,{msg:"Saved in this browser",msgType:"success"}),n=>z(507,{msg:"Couldn't save in this browser. Storage is full or turned off.",msgType:"error",code:n?.code||"draft-storage"})):Promise.resolve(z(503,{msg:"Saving in this browser is not ready yet",msgType:"error",code:"draft-not-ready"}))}function ht(e,t,n,{captureId:o=null,conversionHeader:s=null,attempts:r=[]}={}){let l=new AbortController,c=setTimeout(()=>l.abort(),Ge),u=Z(),i=Q(),a=u||i,d=$;$=!1;let{url:h,options:g}=ut(e,a,l.signal,t,n,d,s);return Ve(t),R||(r.some(f=>f.saveId===t&&f.etag===(n??null))||r.push({saveId:t,etag:n??null}),We({captureId:o,saveId:t,html:e,etag:n??null})),(R?dt(e):fetch(h,g)).then(f=>f.text().then(m=>{let p={};if(m)try{p=JSON.parse(m)}catch{if(f.ok)throw new Error("Server sent a response that was not JSON")}if(!f.ok){let v=new Error(p.msg||p.error||`HTTP ${f.status}: ${f.statusText}`);throw v.code=f.status===413?"save-too-large":p.code??null,v.status=f.status,v.changedBy=p.changedBy??null,v.etag=p.etag??null,v.saveId=p.saveId??null,v.reason=typeof p.reason=="string"?p.reason:null,v.saveOutcome=p.saveOutcome??null,v.retryAfter=it(f.headers?.get?.("Retry-After")),v}return M(p.etag??null),y=null,p})).catch(f=>{throw console.error("Failed to save page:",f),f.name==="AbortError"&&(y={saveId:t,etag:n}),a&&q(),f}).finally(()=>{clearTimeout(c)})}async function pt(){let e=y;if(!e)return{landed:null,resend:!1};let n=(await w({fresh:!0})).document,o=typeof n?.etag=="string"&&n.etag?n.etag:null;return o?n.saveId&&n.saveId===e.saveId?(M(o),y=null,{landed:{msg:"Saved",msgType:"success",etag:o},resend:!1}):(n.saveId&&(y=null),{landed:null,resend:!!e.etag,etag:e.etag}):{landed:null,resend:!1}}async function mt(e,{captureId:t=null,conversionHeader:n=null,attempts:o=[]}={}){let s=ye(),r=Se(),l=!1,c=!1,u=0,i=t??k();for(;;)try{return await ht(e,s,r,{captureId:t,conversionHeader:n,attempts:o})}catch(a){if(l&&(a.hadTimeout=!0),a.name==="AbortError"){if(l)throw a;let{landed:d,resend:h,etag:g}=await pt();if(d)return d;if(!h)throw a;r=g,l=!0;continue}if(a.status===412&&!c&&qe(a.saveId)){M(a.etag??null),y=null,s=ye(),r=Se(),c=!0;continue}if(a.code==="blockeditor-converting"&&u<rt){if(k()!==i||(u+=1,await new Promise(d=>setTimeout(d,Math.max(0,a.retryAfter??1)*1e3)),k()!==i))throw a;continue}throw a}}function X(e,t,n,o,s=null,r=0,l=null){return e=se(e,Math.max(U(),r)),new Promise(c=>{let u=[],i=ee(s),a=()=>l!==null&&E===l,d=()=>{a()||(S=!1)},h=(m,p=!1)=>{p&&D(e,t??null,i),te(s),Xe({captureId:t??null,result:m,attempts:u,sent:u.length>0}),typeof n=="function"&&n(m),c(m)};if(!N&&!window.clay?.testMode)return h(O("Not in edit mode"));if(S&&!a())return h(O("Save already in progress"));let g=lt(o);if(g.invalid)return h(nt());if(S=!0,window.clay?.testMode){setTimeout(()=>{d(),h(ve({msg:"Test mode: save skipped"}))},0);return}j();let f=B(F(e),ue());if(ce(f),f.state==="over")return d(),h(Ze(f));mt(e,{captureId:t,conversionHeader:g.header,attempts:u}).then(ve,W).then(m=>{d(),m.code==="save-too-large"&&!m.size&&(m.size=f),m.ok&&D(e,t??null,i,m.siteData??null),h(m)})})}function gt(e,t=()=>{}){return X(e,null,t,null)}function Zt(e,t,n=()=>{},{conversion:o,capture:s=null,blockeditorFormatFloor:r,lane:l=null}={}){return X(e,t,n,o,s,r,l)}function Qt({html:e,captureId:t,conversion:n}){return X(e,t??null,void 0,n)}function en(e,t=()=>{}){return new Promise(n=>{let o=null,s=r=>{et(o),typeof t=="function"&&t(r),n(r)};if(!N)return s(O("Not in edit mode"));if(tt())return s(O("Another document operation is in progress"));if(S)return s(O("Save already in progress"));if(R)return s(!1);o=Qe("replace"),fetch(new URL(e,window.location.href).href).then(r=>{if(!r.ok)throw new Error(`Template fetch failed: HTTP ${r.status} ${r.statusText}`);return r.text()}).then(r=>gt(r)).then(s).catch(r=>{console.error("Failed to fetch template:",r),s(W(r))})})}var we=null;function tn(e){we=e}function nn(){return we}export{j as a,yt as b,St as c,Bt as d,Ht as e,Jt as f,zt as g,Gt as h,Kt as i,Wt as j,Xt as k,Yt as l,Vt as m,ye as n,qt as o,Qe as p,et as q,tt as r,ut as s,gt as t,Zt as u,Qt as v,en as w,tn as x,nn as y};
@@ -1 +0,0 @@
1
- import{a as b,b as c,c as d,d as e,e as f}from"./c-2PVGJFI5.js";import{g as a}from"./c-CV4T65JE.js";import"./c-GO635CRU.js";import"./c-V2V5FKXX.js";import"./c-DD26VXAP.js";import"./c-CTGRDT6E.js";import"./c-7K4SCQB7.js";import"./c-WMRJKQ2V.js";import"./c-ZRGEN6QQ.js";import"./c-OH2FPYSY.js";import"./c-FSQXFG5T.js";import"./c-RETTCOWO.js";import"./c-WCG6AKA7.js";import"./c-57XDY6HC.js";import"./c-I2SCCUEW.js";import"./c-VHNSBD2M.js";export{e as ChartView,d as chartFromSlash,a as chartTables,b as insertChartAfterTable,f as refreshCharts,c as tableLabel};
@@ -1 +0,0 @@
1
- import{a as ce,b as Qe,c as ue,e as fe,f as pe,g as nt}from"./c-UOOIF2AL.js";import{a as Ze,b as et,c as de,d as tt}from"./c-LZJPNR2W.js";import{a as A,b as J}from"./c-QTTJYJMA.js";import{b as Ke}from"./c-5VYOWDTI.js";import{b as oe,c as ae,d as x,f as he,g as Ve,h as Xe}from"./c-6Q6RGFBF.js";import{a as q}from"./c-LA2BW7UY.js";import{a as Ge}from"./c-LD6UVV5R.js";import{a as ze,f as We,g as Ye,h as Je}from"./c-PGSBXHUE.js";import{a as se,b as $e,c as P,d as re,e as le,h as je}from"./c-6IJEVE6B.js";import{e as Ue}from"./c-QQFHEODI.js";import{d as Pe}from"./c-IJUK2GPW.js";import{f as $,j as te}from"./c-EDE45NM7.js";import{a as Le}from"./c-BPF2NSPV.js";import{E as Y,F as Ne,H as T,I as Oe,b as D,j as ie,o as W,t as M,z as Be}from"./c-PWJSJEJU.js";import{a as Re,b as qe,c as Me,e as j,g as z,h as ne}from"./c-VG5XIN4T.js";import{m as Ie,n as Te}from"./c-HA6INT6J.js";import{a as He,b as Fe,l as Ce,m as Ae}from"./c-ICMAOOGK.js";function it(s){let e=new WeakMap,t=0,i=r=>e.get(r)||null,n=r=>{let l=e.get(r);return l||(l=`${s}:${++t}`,e.set(r,l)),l};return{idOf:i,ensure:n,adopt:(r,l)=>{r&&typeof l=="string"&&l&&e.set(r,l)},exportMap:(r,l)=>{let o={},a=[],h=[],c=(d,_)=>{let g=l(d);g&&(o[_]=n(g));let E=d.children;a.push(E.length),h.push(d.tagName.toLowerCase());for(let f=0;f<E.length;f++)c(E[f],_===""?String(f):`${_}.${f}`)};return c(r,""),o["~"]=a.join(","),o["^"]=h.join(","),o}}}function st(s,e){let t=new WeakMap;if(!s||!e||typeof e!="object"||Array.isArray(e))return t;let i=e["~"],n=typeof i=="string"?i.split(",").map(Number):null,r=n&&typeof e["^"]=="string"?e["^"].split(","):null,l=d=>Number.isInteger(d)&&d>=0,o=0,a=!1,h=d=>{let _=d;for(;_>0;){let g=n[o++];if(o>n.length||!l(g))return!1;_+=g-1}return!0},c=(d,_)=>{if(a)return;if(n){let f=o++,u=n[f];if(f>=n.length||!l(u)){a=!0;return}let S=!r||r[f]===d.tagName.toLowerCase();if(!S||u!==d.children.length){let w=S&&e[_];typeof w=="string"&&w&&t.set(d,w),h(u)||(a=!0);return}}let g=e[_];typeof g=="string"&&g&&t.set(d,g);let E=d.children;for(let f=0;f<E.length;f++)c(E[f],_===""?String(f):`${_}.${f}`)};return c(s,""),t}function vt(s){return e=>{for(let t of s){let i=t(e);if(typeof i=="string"&&i!=="")return i}return null}}var Bt=vt([s=>s.getAttribute("data-id"),s=>s.getAttribute("id")]);var St=/^blockeditor(\.[0-9]+)?$/,rt=s=>[...s.querySelectorAll('script[merge][clay~="live"]')].filter(e=>St.test(e.getAttribute("merge")));function lt(s,e,t){if(!s.html.includes("data-blockeditor"))return s;let i=u=>W(new DOMParser().parseFromString(u,"text/html")),n=i(s.html),r=n.querySelector("article[data-blockeditor]");if(!r)return s;let l=i(e),o=l.querySelector("article[data-blockeditor]");if(!o)return null;let a=st(n.documentElement,s.identityMap),h=(u,S)=>{let w=n.importNode(S,!0),b=a.get(u);return b&&a.set(w,b),u.replaceWith(w),w},c=h(r,o),d=new Map(rt(n).map(u=>[u.getAttribute("merge"),u]));for(let u of rt(l)){let S=u.getAttribute("merge"),w=d.get(S);w?h(w,u):c.before(n.importNode(u,!0)),d.delete(S)}for(let u of d.values())u.remove();let _=n.querySelector("head > title"),g=l.querySelector("head > title");_&&g?h(_,g):g?n.head.append(n.importNode(g,!0)):_?.remove();let E=n.documentElement,f=t.exportMap(E,u=>{let S=a.get(u);return S?(t.adopt(u,S),u):null});return{...s,html:T(E),identityMap:f}}var Et={"merge-tokens":"tokens","merge-max":"max"};function ot(s,e){if(!e.startsWith("data-")||e==="data-id"||!s?.closest)return null;for(let[t,i]of Object.entries(Et)){let n=s.closest(`[${t}]`);if(n&&n.getAttribute(t).split(/\s+/).includes(e))return i}return null}var m=null,at=null,B=new Map;function V(){return at??=Promise.all([import("./c-PYG2NGWU.js"),import("./c-EJTGYSLN.js")]).then(([s,e])=>{m={...s,beginLineageCapture:e.beginLineageCapture};for(let t of[...B.keys()])B.set(t,s.registerContext(t));return m}),at}var ht=()=>m,I={get size(){return m?m.conflicts.size:0},list(){return m?m.conflicts.list():[]},get(s){return m?m.conflicts.get(s):null},acknowledge(s,e={}){if(m)return m.conflicts.acknowledge(s,e);if(!Array.isArray(s))throw new TypeError("clay.conflicts.acknowledge needs an array of ids");return{removedIds:[],remainingIds:[]}},claim(s,e={}){if(m)return m.conflicts.claim(s,e);if(!e.owner)throw new TypeError("clay.conflicts.claim needs an owner");return{release(){}}},registerContext(s){if(m)return m.conflicts.registerContext(s);if(typeof s!="function")throw new TypeError("clay.conflicts.registerContext needs a resolver function");return B.set(s,null),()=>{let e=B.get(s);B.delete(s),e&&e()}},contextFor(s,e){return m?m.conflicts.contextFor(s,e):null},recoveryOf(s){return m?m.conflicts.recoveryOf(s):null},hasPendingApply(){return m?m.conflicts.hasPendingApply():!1}};var y=null,_e=null;function R(){return _e??=new Promise(s=>setTimeout(s,0)).then(()=>import("./c-PDBNCJCT.js")).then(s=>y=s).catch(s=>{throw _e=null,s}),_e}var ve=null,ge=null;function kt(){return ge??=import("./c-APGHGDZM.js").then(s=>ve=s.presence).catch(s=>{throw ge=null,s}),ge}var ut=te().phase==="entering";$&&!ut&&R().catch(()=>{});$&&V().catch(()=>{});var L=null,ye=null,Q=[];function ft(s){L.presence.update(s),L.editingMarker.update(s)}function xt(){return ye??=Promise.all([import("./c-T3P3AXEW.js"),import("./c-X75G43SZ.js")]).then(([s,e])=>{L={presence:s.presence,editingMarker:e.editingMarker};let t=Q;Q=[];for(let i of t)ft(i);return L}).catch(s=>{throw ye=null,s}),ye}function bt(s){if(L){ft(s);return}Q.push(s),xt().catch(()=>{})}var ct=Object.freeze({bytes:null,etag:null,seq:null}),Dt=()=>({msg:"Not in edit mode",msgType:"skipped",code:null,etag:null}),pt=["[editor-ui]",'[clay~="editor-ui"]',"[save-ignore]","[snapshot-remove]","[no-snapshot]","[no-save]","[save-remove]","[freeze] *","[save-freeze] *",'[clay~="no-save"]','[clay~="no-snapshot"]','[clay~="freeze"] *',Ce,He].join(","),_t='[clay~="freeze"], [freeze], [save-freeze]';function X(s){for(let e of s.querySelectorAll(_t))e.replaceChildren();return z()&&Me(s),s}function dt(s){if(s==null)return s;let e=typeof s=="string"?new DOMParser().parseFromString(s,"text/html"):s;return ie(e),W(e),X(e),e}var It=[Ae,'[clay~="no-watch"]',"[no-watch]","[mutations-ignore]"].join(","),Tt=(s,e,t)=>Ie(s,e,t)||Fe.test(e.toLowerCase()),gt=s=>s.getAttribute("data-id")||s.getAttribute("id")||null;function Lt(s){let e=new Map,t=n=>{if(n.matches(pt))return;let r=gt(n);r&&e.set(r,(e.get(r)||0)+1);let l=n.localName==="template"&&n.content?n.content.children:n.children;for(let o of l)t(o)},i=s.nodeType===9?[s.documentElement]:s.nodeType===11?s.children:[s];for(let n of i)n&&n.nodeType===1&&t(n);return e}var Ht=s=>e=>{let t=gt(e);if(!t)return null;let i=e.getRootNode(),n=s.get(i);return n||s.set(i,n=Lt(i)),n.get(t)===1?t:null},me=s=>!!s&&typeof s=="object"&&!Array.isArray(s);function Ft(s){return typeof s!="string"||s===""?null:new DOMParser().parseFromString(s,"text/html").documentElement?.getAttribute("documentetag")||null}function Ct(s,e){e!=="live"||!s||!y||(y.enableContentEditable(s),y.enableOnClick(s),y.enableAdminInputs(s),y.enableAdminResources(s))}function At(){let{forComparison:s,forDirty:e}=Be({flushUndo:!1});return[s,e]}var Rt=1024*1024;function qt(s,e,t,i,n){let r={sender:t,identityMap:i,...n?{etag:n}:{}};return e.length<Rt?JSON.stringify({[s.snapshotKey]:e,...r}):new Blob([`{${JSON.stringify(s.snapshotKey)}:`,JSON.stringify(e),`,${JSON.stringify(r).slice(1)}`],{type:"application/json"})}var Se=class{constructor(){this.sse=null,this.currentFile=null,this.lastHtml=null,this._diskBase=null,this._diskBaseTicket=0,this._agreeSeq=0,this._saveTicket=0,this._peerBaseTicket=0,this._acceptedSaveTicket=0,this._morphTicket=0,this.clientId=this.generateClientId(),this.resumeId=null,this._savedSnapshot?.abort?.abort(),this._savedSnapshot=null,this._sendInFlight=!1,this._queuedSend=null,this._profile=null,this._profilePromise=null,this._sharedData=!1,this._sharedSync=!1,this._workerFeatures=["live-data"],this._liveData=!1,this._editing=null,this._presenceLease=null,this._presenceQuiesced=!1,this._ready=null,this._startGen=0,this.isPaused=!1,this.isDestroyed=!1,this.debug=!1,this._lane=$?"live":"saved",this._laneChosen=!1,this._snapshotHandler=null,this._hiddenHandler=null,this.lastSeenSeq=0,this._pendingHtml=null,this._pendingSeq=null,this._pendingIdentityMap=null,this._pendingEtag=null,this._pendingBy=null,this._morphInFlight=!1,this._rafHandle=null,this._represented=ct,this._handoff=null,this._handoffHeld=!1,this._pendingExternal=null,this._lastExternalSeq=0,this._saveEpoch=0,this._saveSavedHandler=null,this._saveConflictHandler=null,this._settledHandler=null,this._lastIdentityMap=null,this._applyGen=0,this._holdRetryPeer=null,this._holdRetryExt=null,this._servedFetchId=0,this._startupRetry=null,this._engineRetry=null,this._heldLive=!1,this._heldExt=!1,this.identity=it(this.clientId),this.onConnect=null,this.onDisconnect=null,this.onUpdate=null,this.onError=null,this.onNotification=null}get unresolvedConflicts(){return I.list().filter(e=>e.kind!=="apply-incomplete")}_log(e,t=null){if(!this.debug)return;let i=`[LiveSync ${new Date().toISOString()}]`;t!==null?console.log(i,e,t):console.log(i,e)}generateClientId(){return Math.random().toString(36).slice(2,11)+Date.now().toString(36)}generateResumeId(){try{let e=new Uint8Array(16);return(globalThis.crypto||window.crypto).getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}catch{return Math.random().toString(36).slice(2)+Date.now().toString(36)}}_seedBases(){if(x())return;let e=M({flushUndo:!1});this._setPeerBase(T(e),this.identity.exportMap(e,D),this._ticket()),this._setDiskBase(Y({emitForSync:!1}).forSave,this._ticket())}get lane(){return this._lane}set lane(e){this._lane=e,this._laneChosen=!0}start(e=null,{lane:t,represented:i}={}){if(this.isDestroyed=!1,(this.sse||this._snapshotHandler)&&this.cleanup(),this.currentFile=e||this.detectCurrentFile(),!this.currentFile){console.warn("[LiveSync] No file detected");return}let n=te().mode==="edit"?"live":"saved",r=this.lane==="live";this._lane=t||(this._laneChosen?this._lane:n),this.lastHtml=null,this._lastIdentityMap=null,this._peerBaseTicket=this._ticket(),this._diskBase=null,this._diskBaseTicket=this._ticket(),this._saveTicket=0,this._savedSnapshot?.abort?.abort(),this._savedSnapshot=null,this._applyGen++,this.lastSeenSeq=0,this._lastExternalSeq=0,this._represented=i?Object.freeze({bytes:i.bytes??null,etag:i.etag??null,seq:i.seq??null}):ct,this._acquireEmptySaved=r&&this.lane==="saved"&&this._represented.bytes===null,this._pendingExternal=null,this.resumeId=this.generateResumeId(),this.lane==="live"&&this._seedBases(),this.lane==="live"&&V().catch(()=>{}),console.log(`[LiveSync] Starting for: ${this.currentFile} (lane=${this.lane})`);let l=++this._startGen;if(this.lane==="live"&&!(y&&y.baselineSettled())){let o=this._applyGen,a=this._morphTicket,h=this._saveEpoch,c=this.lastHtml,d=this._diskBaseTicket,_=this._diskBase!==null;this._settledHandler=()=>{if(this._settledHandler=null,!(this.isDestroyed||this._startGen!==l)&&!Pe()&&!x()&&this._saveTicket===0&&this._morphTicket===a){if(c!==null&&this._applyGen===o&&this._saveEpoch===h&&this.lastHtml===c){let g=M({flushUndo:!1});this._setPeerBase(T(g),this.identity.exportMap(g,D),this._ticket())}_&&this._diskBaseTicket===d&&this._setDiskBase(Y({emitForSync:!1}).forSave,this._ticket())}},document.addEventListener("clay:baseline-settled",this._settledHandler,{once:!0})}this._ready=Promise.all([this.lane==="live"?R():null,this._resolveProfile()]).then(()=>{this.isDestroyed||this._startGen!==l||this.connect()}),this.lane==="live"&&(this.listenForSnapshots(),kt().then(o=>this._startPresence(o,l),()=>{}),this._saveSavedHandler=o=>{this._saveEpoch++;let a=this._saveTicket||this._ticket();this._saveTicket=0,a>this._acceptedSaveTicket&&(this._acceptedSaveTicket=a);let h=y?y.getLastSavedBytes():null;h!=null&&this._setDiskBase(h,a),this._relayCommit(o?.detail?.captureId,h)},document.addEventListener("clay:save-saved",this._saveSavedHandler),this._saveConflictHandler=o=>{let a=o.detail&&o.detail.etag;a&&queueMicrotask(()=>{this.isDestroyed||a===se()&&(y?.conflictResolvedBySync(a),this._saveAfterMerge(x(),!1))})},document.addEventListener("clay:save-conflict",this._saveConflictHandler))}cleanup(){if(this.sse&&(this.sse.close(),this.sse=null),de(),Q=[],L&&(L.presence.clear(),L.editingMarker.clear()),this._editing&&(this._editing.stop(),this._editing=null),this._presenceLease){let e=this._presenceLease;this._presenceLease=null,typeof e.stop=="function"?e.stop():e.detach()}this._lastRoster=null,this._snapshotHandler&&(document.removeEventListener("clay:snapshot-ready",this._snapshotHandler),this._snapshotHandler=null),this._saveSavedHandler&&(document.removeEventListener("clay:save-saved",this._saveSavedHandler),this._saveSavedHandler=null),this._saveConflictHandler&&(document.removeEventListener("clay:save-conflict",this._saveConflictHandler),this._saveConflictHandler=null),this._settledHandler&&(document.removeEventListener("clay:baseline-settled",this._settledHandler),this._settledHandler=null),this._hiddenHandler&&(document.removeEventListener("visibilitychange",this._hiddenHandler),document.removeEventListener("clay:workspace-background",this._hiddenHandler),this._hiddenHandler=null),this._queuedSend=null,this._rafHandle!=null&&(this._cancelFrame(this._rafHandle),this._rafHandle=null),this._pendingHtml=null,this._pendingSeq=null,this._pendingIdentityMap=null,this._pendingBy=null,this._pendingExternal=null,this._handoff=null,this._handoffHeld=!1,clearTimeout(this._holdRetryPeer),clearTimeout(this._holdRetryExt),this._holdRetryPeer=null,this._holdRetryExt=null,clearTimeout(this._startupRetry),this._startupRetry=null,clearTimeout(this._engineRetry),this._engineRetry=null,this._servedFetchId++}detectCurrentFile(){let e=window.location.pathname;if(e==="/")return"index.html";e=e.replace(/^\//,"");let t=e.match(/^(.*?\.html(?:clay)?)/);return t?t[1]:e}_resolveProfile(){return this._profilePromise||(this._profilePromise=nt().then(e=>(this._sharedData=e.sharedData,this._sharedSync=e.sharedSync,this._liveData=e.liveData,this._workerFeatures=e.workerFeatures,this._profile=e.profile,this._log(`Wire profile: ${e.profile.name}`),e.profile))),this._profilePromise}_setHeld(e,t,i){let n=e==="live"?"_heldLive":"_heldExt";this[n]!==t&&(this[n]=t,!t&&!this._heldLive&&!this._heldExt&&je({fresh:!0,clearIfMissing:!1}),document.dispatchEvent(new CustomEvent(t?"clay:sync-held":"clay:sync-resumed",{detail:{lane:e,el:i||null}})))}_applyEtagFrame(e){return typeof e.etag!="string"||typeof e.html=="string"?!1:(this._log("Dropping a stamp that arrived with no document: nothing proves this tab holds those bytes"),!0)}connect(){if(this.isDestroyed)return;let t=(this._profile||pe.legacy).streamPath(window.location.href,this.lane,this.resumeId,this.clientId);this._hiddenHandler||(this._hiddenHandler=()=>{this._rafHandle==null||!ce()||(this._cancelFrame(this._rafHandle),this._rafHandle=null,this._scheduleNextFrame())},document.addEventListener("visibilitychange",this._hiddenHandler),document.addEventListener("clay:workspace-background",this._hiddenHandler)),this.sse=new Qe(new URL(t,window.location.origin).href,{shared:this._sharedSync,sharedData:this._sharedData,workerFeatures:this._workerFeatures,documentURL:window.location.href,lane:this.lane,clientId:this.clientId,keepAliveWhenHidden:this.lane!=="live"?!1:this._liveData?!0:"shared",startupCheck:!!Le}),this._acquireEmptySaved&&(this._acquireEmptySaved=!1,this._fetchServedDocument(void 0,{repair:!0})),this.sse.onopen=()=>{console.log("[LiveSync] Connected"),this._editing&&this._editing.reconnected(),ve&&ve.reconnect(),this.onConnect&&this.onConnect()},this.sse.addEventListener("open",()=>et({clientId:this.clientId,lane:this.lane})),this.sse.addEventListener("error",()=>de());for(let i of Ze)this.sse.addEventListener(i,n=>{let r;try{r=JSON.parse(n.data)}catch{return}tt(i,r)});this.sse.addEventListener("cursor",i=>{let n;try{n=JSON.parse(i.data)}catch{return}if(!n||n.resync!==!0&&n.startup!==!0)return;let r=n.resync===!0,l=n.startup===!0&&!r;console.log(r?"[LiveSync] Server could not replay everything; refetching the document":"[LiveSync] Checking the served document against the version this tab was served"),this._fetchServedDocument(typeof n.seq=="number"?n.seq:void 0,{repair:r,startup:l})}),this.sse.addEventListener("presence",i=>{let n;try{n=JSON.parse(i.data)}catch{return}bt(n),this._lastRoster=n,this._editing&&this._editing.roster(n)}),this.sse.onmessage=i=>{let n=JSON.parse(i.data),{seq:r}=n;if(typeof r=="number"&&r<=this.lastSeenSeq){this._log(`Dropping stale message: seq=${r}, lastSeen=${this.lastSeenSeq}`);return}if(typeof r=="number"&&(this.lastSeenSeq=r),n.type==="notification"){if(this._maybeAcceptExternalChange(n))return;this.handleNotification(n);return}if(n.error){console.error("[LiveSync] Server error:",n.error),this.onError&&this.onError(new Error(n.error));return}if(this._applyEtagFrame(n))return;let{html:l,sender:o,identityMap:a}=n;if(o===this.clientId){this._log("Ignoring own message (sender matches clientId)");return}if(typeof l!="string"){console.error("[LiveSync] Received invalid html, ignoring");return}let h=typeof n.etag=="string"&&n.etag?n.etag:null;if(this.lane==="live"&&!h&&$e()){this._log(`Dropping an unstamped live frame on a stamping host (seq=${r})`);return}if(this.lane==="saved"&&l===this._represented.bytes){this._represented=Object.freeze({bytes:l,etag:h||null,seq:r??null}),P(h);return}if(h&&l===this.lastHtml){this._log(`Taking the stamp from a peer save of content already applied (seq=${r})`),P(h),y&&y.isSaveConflicted()&&(y.conflictResolvedBySync(h),this._saveAfterMerge(x(),!1));return}this._log(`Received update from: ${o} (my clientId: ${this.clientId}, seq=${r})`),this.applyUpdate(l,r,a,h,n.by),this.onUpdate&&this.onUpdate({html:l,sender:o,seq:r,identityMap:a,etag:h})},this.sse.onerror=()=>{this.sse.readyState===EventSource.CONNECTING?console.log("[LiveSync] Reconnecting..."):this.sse.readyState===EventSource.CLOSED&&(console.log("[LiveSync] Connection closed"),this.onError&&this.onError(new Error("Connection closed"))),this.onDisconnect&&this.onDisconnect()}}listenForSnapshots(){this._snapshotHandler=e=>{if(!e.detail||e.detail.forSave!==!0)return;this._saveTicket=this._ticket();let{documentElement:t}=e.detail;if(!t)return;this._log("snapshot-ready received, preparing to send");let i=this.identity.exportMap(t,D);this._savedSnapshot?.abort?.abort();let n={html:null,steps:null,copy:null,abort:null,identityMap:i,ticket:this._saveTicket,captureId:e.detail.captureId??null};if(e.detail.sliced){n.copy=Oe(t),n.abort=new AbortController;let{signal:r}=n.abort;Promise.all([import("./c-YYMZWQLR.js"),import("./c-ZWBI4HYK.js")]).then(([{serializeForSyncSteps:l},{runSliced:o}])=>{if(r.aborted||typeof n.html=="string")return;let a=(function*(){let h=yield*l(n.copy);n.html=h,n.steps=null})();return n.steps=a,o(a,{signal:r})}).catch(()=>{})}else n.html=T(t);this._savedSnapshot=n},document.addEventListener("clay:snapshot-ready",this._snapshotHandler)}_enqueueSend(e,t,i=null){if(!this._profile){this._queuedSend={html:e,identityMap:t,etag:i},this._resolveProfile().then(()=>this._flushQueuedSend());return}if(this._sendInFlight){this._queuedSend={html:e,identityMap:t,etag:i};return}this._postUpdate(e,t,i)}_flushQueuedSend(){if(this.isDestroyed||this._sendInFlight)return;let e=this._queuedSend;e&&(this._queuedSend=null,this._postUpdate(e.html,e.identityMap,e.etag))}_relayCommit(e=null,t=null){if(this.isDestroyed)return;let i=se(),n=this._savedSnapshot;if(n&&(n.captureId??null)!==(e??null)){this._log("Skipping send - snapshot belongs to a different capture");return}let r=n;if(this._savedSnapshot=null,r?.copy&&typeof r.html!="string")if(r.abort?.abort(),r.steps)for(let c=r.steps.next();!c.done;c=r.steps.next());else r.html=T(r.copy);if(!r||typeof r.html!="string")return;let l=r;if(typeof t=="string"){try{l=lt(r,t,this.identity)}catch(c){this._log(`Skipping send - page relay failed: ${c&&c.message}`);return}if(!l){this._log("Skipping send - accepted capture has no page article");return}}let o=Mt(e)??t,a=typeof o=="string"?We(o):0;l={...l,html:Pt(Ye(l.html,Math.max(Je(),a)),o)};let h=!i&&l.html===this.lastHtml;if(this._setPeerBase(l.html,l.identityMap,l.ticket),h){this._log("Skipping send - HTML unchanged");return}this._enqueueSend(l.html,l.identityMap,i||null)}_postUpdate(e,t,i=null,n=0){this._log(`Sending update (HTML length: ${e.length})`),this._sendInFlight=!0;let r=!1,l=this._profile||pe.legacy;fetch(new URL(l.relayPath,window.location.origin).href,{method:"POST",headers:{"Content-Type":"application/json",[l.documentHeader]:window.location.href,[ze]:String(1)},body:qt(l,e,this.clientId,t,i)}).then(o=>{o.ok||(console.warn("[LiveSync] Save returned status:",o.status),r=o.status>=500||o.status===408||o.status===429)}).catch(o=>{console.error("[LiveSync] Save failed:",o),this.onError&&this.onError(o),r=!0}).finally(()=>{this._sendInFlight=!1;let o=this._queuedSend;if(this._queuedSend=null,o){this._postUpdate(o.html,o.identityMap,o.etag);return}!r||!i||n>=3||this.isDestroyed||(this._sendInFlight=!0,setTimeout(()=>{if(this._sendInFlight=!1,this.isDestroyed)return;let a=this._queuedSend;this._queuedSend=null,a?this._postUpdate(a.html,a.identityMap,a.etag):this._postUpdate(e,t,i,n+1)},500*2**n))})}_startPresence(e,t){return this.isDestroyed||this._startGen!==t||this._presenceLease?null:e.connect({send:i=>this._postPresence(i)}).then(i=>this.isDestroyed||this._startGen!==t?(typeof i?.stop=="function"?i.stop():i?.detach(),null):(this._presenceLease=i||null,Ue("presence-editing")),()=>!1).then(i=>{if(!(!i||this.isDestroyed||this._startGen!==t||this._editing))return R().then(n=>{this.isDestroyed||this._startGen!==t||this._editing||(this._editing=new n.EditingSender({}),this._presenceQuiesced?this._editing.stop():(this._editing.start(),this._editing.roster(this._lastRoster)))})})}_postPresence(e){let t=new URL("/_/presence",window.location.origin);return t.searchParams.set("client-id",this.clientId),fetch(t.href,{method:"POST",headers:{"Content-Type":"application/json","Document-URL":window.location.href},body:JSON.stringify(e)}).then(i=>i.ok,()=>!1)}_maybeAcceptExternalChange(e){if(this.lane!=="live")return!1;let t=e.data;return t&&t.kind==="external-change"?(typeof t.html=="string"?this._enqueueExternal(t.html,e.seq,t.etag,t.by):this._fetchExternalChange(e.seq),!0):typeof e.msg=="string"&&e.msg.endsWith("changed on disk outside this tab")?(this._fetchExternalChange(e.seq),!0):!1}_enqueueExternal(e,t,i,n){if(typeof t=="number"){if(t<=this._lastExternalSeq){this._log(`Dropping replayed external change: seq=${t}`);return}this._lastExternalSeq=t}this._pendingExternal={html:e,seq:t,saveEpoch:this._saveEpoch,etag:typeof i=="string"&&i?i:null,by:n??null},this._scheduleNextFrame()}_fetchExternalChange(e){if(typeof e=="number"){if(e<=this._lastExternalSeq)return;this._lastExternalSeq=e}this._fetchServedDocument(e)}_fetchServedDocument(e,{attempt:t=0,repair:i=!1,startup:n=!1}={}){if(n&&(this._morphInFlight||this._pendingHtml!=null||this._pendingExternal!=null)){this._retryStartup(t);return}let r=this._saveEpoch,l=this._startGen,o=this.lastSeenSeq,a=this._applyGen,h=++this._servedFetchId;i&&typeof e!="number"&&(e=this._lastExternalSeq),fetch(new URL(window.location.href),{cache:"no-store"}).then(c=>c.ok?c.text():null).then(c=>{if(this.isDestroyed||c==null||this._startGen!==l)return;let d=Ft(c),_=n||i&&!!d;if(_){if(h!==this._servedFetchId){i&&this._retryStartup(t+1,{repair:i,startup:n},typeof e=="number"?Math.max(e,this._lastExternalSeq):e);return}if(r!==this._saveEpoch||o!==this.lastSeenSeq||a!==this._applyGen||this._morphInFlight||this._pendingHtml!=null||this._pendingExternal!=null){this._retryStartup(t+1,{repair:i,startup:n},e);return}if(d){if(d===re()){(i||n)&&this.lane==="saved"&&(this._represented=Object.freeze({bytes:c,etag:d,seq:e??null}));return}}else if(!i)return}else if(typeof e=="number"&&e<this._lastExternalSeq){i&&t<3&&this._fetchServedDocument(this._lastExternalSeq,{attempt:t+1,repair:i,startup:n});return}else if(this._saveEpoch>r){t<3&&(console.log("[LiveSync] Refetching external change: own save landed mid-fetch"),this._fetchServedDocument(e,{attempt:t+1,repair:i,startup:n}));return}this._pendingExternal={html:c,seq:e,saveEpoch:r,etag:d,by:null,fetchOptions:{repair:i,startup:n,attempt:t,versionCheck:_},startGen:l,seenSeq:o,applyGen:a,fetchId:h},this._scheduleNextFrame()}).catch(c=>{this._log("External-change fetch failed",c),typeof e=="number"&&this._lastExternalSeq===e&&(this._lastExternalSeq=e-1)})}_retryStartup(e=0,t={startup:!0},i){this.isDestroyed||e>3||(clearTimeout(this._startupRetry),this._startupRetry=setTimeout(()=>{if(this._startupRetry=null,!this.isDestroyed){if(this._morphInFlight||this._pendingHtml!=null||this._pendingExternal!=null){this._retryStartup(e,t,i);return}this._fetchServedDocument(i,{...t,attempt:e})}},16))}applyUpdate(e,t,i,n,r){this.isDestroyed||(this._pendingHtml=e,this._pendingSeq=t,this._pendingIdentityMap=i,this._pendingEtag=n??null,this._pendingBy=r??null,this._scheduleNextFrame())}prepareHandoff(e={}){return this._handoff?Promise.resolve(this._handoff):this.isDestroyed?Promise.reject(new Error("LiveSync: stopped")):(this._handoffHeld=!0,this._rafHandle!=null&&(this._cancelFrame(this._rafHandle),this._rafHandle=null),import("./c-6LEYVQJK.js").then(({engineHandoff:t})=>t(this,e)).then(t=>this._handoff=t))}_scheduleNextFrame(){this.isDestroyed||this._handoffHeld||this._rafHandle==null&&(this._morphInFlight||(this._rafHandle=this._requestFrame(()=>this._runPending())))}async _runPending(){if(this._rafHandle=null,this.isDestroyed)return;if(!A()){this._morphInFlight=!0;try{await J()}catch(r){this._log("Merge engine failed to load",r),this._engineRetry=setTimeout(()=>this._scheduleNextFrame(),2e3);return}finally{this._morphInFlight=!1}if(this.isDestroyed)return}let e=this._pendingExternal,t=e?.fetchOptions||null,i=!!(t?.startup||t?.versionCheck),n=!1;if(e!=null&&(i&&this._pendingHtml!=null?n=!1:this._pendingHtml==null?n=!0:n=!(typeof e.seq=="number"&&typeof this._pendingSeq=="number"&&this._pendingSeq<e.seq)),n)if(this._pendingExternal=null,typeof e.seq=="number"&&e.seq<this._lastExternalSeq)i&&t?.repair?this._retryStartup((t.attempt||0)+1,t,this._lastExternalSeq):this._log("Dropping superseded external change at drain");else if(i&&e.startGen!==this._startGen)this._log("Dropping superseded startup check at drain");else if(i&&e.fetchId!==this._servedFetchId)t?.repair?this._retryStartup((t.attempt||0)+1,t,this._lastExternalSeq):this._log("Dropping superseded startup check at drain");else if(i&&(e.saveEpoch!==this._saveEpoch||e.seenSeq!==this.lastSeenSeq||e.applyGen!==this._applyGen))this._retryStartup((t.attempt||0)+1,t,e.seq);else if(i&&e.etag!=null&&e.etag===re())this._log("Startup check found the same version: nothing to apply");else if(!i&&e.saveEpoch!==this._saveEpoch)console.log("[LiveSync] Refetching external change: own save landed after queue"),this._fetchServedDocument(e.seq,t||{});else{this._morphInFlight=!0;try{await this._doApplyExternal(e.html,e.seq,e.etag,e.by,t)}catch(r){console.error("[LiveSync] applyExternal failed:",r)}finally{this._morphInFlight=!1}}else{let r=this._pendingHtml,l=this._pendingSeq,o=this._pendingIdentityMap,a=this._pendingEtag,h=this._pendingBy;if(this._pendingHtml=null,this._pendingSeq=null,this._pendingIdentityMap=null,this._pendingEtag=null,this._pendingBy=null,r==null)return;this._morphInFlight=!0;try{await this._doApplyUpdate(r,l,o,a,h)}catch(c){console.error("[LiveSync] applyUpdate failed:",c)}finally{this._morphInFlight=!1}}!this.isDestroyed&&(this._pendingHtml!=null||this._pendingExternal!=null)&&this._scheduleNextFrame()}_ticket(){return++this._agreeSeq}_setDiskBase(e,t){t<=this._diskBaseTicket||(this._diskBase=e,this._diskBaseTicket=t)}_setPeerBase(e,t,i){return i<this._peerBaseTicket?!1:(this._peerBaseTicket=i,this.lastHtml=e,this._lastIdentityMap=t&&typeof t=="object"&&!Array.isArray(t)?t:null,!0)}_requestFrame(e){if(ce()){if(typeof MessageChannel=="function"){let n=new MessageChannel,r=!0;return n.port1.onmessage=()=>{n.port1.close(),r&&e()},n.port2.postMessage(null),{cancel:()=>{r=!1,n.port1.close()}}}let i=setTimeout(e,0);return{cancel:()=>clearTimeout(i)}}if(typeof window<"u"&&typeof window.requestAnimationFrame=="function"){let i=window.requestAnimationFrame(e);return{cancel:()=>window.cancelAnimationFrame?.(i)}}let t=setTimeout(e,16);return{cancel:()=>clearTimeout(t)}}_cancelFrame(e){e?.cancel?.()}async _mergeIncoming(e,t,{base:i,baseIdentityMap:n=null,captureLocal:r,synthetic:l,source:o="peer",seq:a=null,etag:h=null,extra:c={}}){A()||await J();let{beginApply:d,completeApply:_,failApply:g,beginLineageCapture:E}=ht()||await V(),f,u=p=>{f=E(I.list());try{let v=A().HyperMorph.mergeDocument({...p,lineage:f.lineage});return f.returned(),v}catch(v){throw f.invalidate(I.list()),f.finish(I.list()),v}},S=this.identity,w=Te,b=Ht(new WeakMap),N=p=>me(p)?{first:b,map:p,then:b}:b,O=l?p=>b(p)||S.idOf(D(p)||p)||null:b,H=e,we=new Map;if(me(t)){H=new DOMParser().parseFromString(e,"text/html"),ie(H);let p=A().HyperMorph.importMap(H.documentElement,t);for(let v of H.querySelectorAll("[data-id], [id]")){let k=b(v),De=k&&p.get(v);De&&we.set(k,De)}}H=dt(H);let Z={live:document,remote:H,ignore:p=>p.matches(pt),opaque:p=>p.matches(_t)||z()&&qe(p),remoteWins:p=>p.matches(It),ignoreAttribute:(p,v,k)=>Tt(p,v,k)||z()&&Re(k||p,v),attributeMerge:ot,protectFocusedValue:!0,restoreFocus:document.activeElement?.localName!=="clay-editor-ui",keepLiveOnly:o==="peer",scripts:{mergeTags:A().mergeTagRecognizers},hooks:{beforeAttributeUpdated:w},...c},ke=this.lane==="live"&&x(),xe=he(),G,ee=null,C=null;if(i==null)G=u({...Z,base:null,local:{root:X(r()),toLive:D},identity:{local:O,remote:N(t)}});else if(ke){let p=r(),v=p.cloneNode(!0);ee=X(p),C=d({source:o,seq:a,etag:h,root:ee,recoveryRoot:v,domain:o==="disk"?"save":"sync"});try{G=u({...Z,base:dt(i),local:{root:ee,toLive:D},identity:{base:N(n),local:O,remote:N(t)}})}catch(k){throw g(C,k),k}}else{let p=X(r()),v=p.ownerDocument;v.documentElement!==p&&v.replaceChild(p,v.documentElement),G=u({...Z,base:v,local:{root:p,toLive:D},fastPath:!0,identity:{base:O,local:O,remote:N(t)}})}let U=this._ticket();this._morphTicket=U;let F;try{F=await G}catch(p){f.invalidate(I.list());try{C&&g(C,p,{ticket:U})}finally{f.finish(I.list())}throw p}let yt=he().gen!==xe.gen,be;try{f.prepareComplete(F,I.list()),be=C?_(C,F.conflicts,{ticket:U}):[]}finally{f.finish(I.list())}this.lane==="live"&&F.localDiverged?Ve():ke&&!F.localDiverged&&Xe(xe);let mt=new Set(me(t)?Object.values(t):[]);for(let[p,v]of F.identities){let k=mt.has(v)?v:we.get(v);k&&S.adopt(p,k)}return{report:F,ticket:U,typedDuringWait:yt,conflictIds:be}}_saveAfterMerge(e,t){(e||t)&&Ke()&&(y?y.savePageThrottled():Dt())}async _doApplyUpdate(e,t,i,n,r=null){if(ue(e)){await fe();return}this.lane==="live"&&!y&&await R(),this._log("applyUpdate - pausing mutations and morphing"),this.isPaused=!0;let l=window.scrollX,o=window.scrollY;q.pause(),oe();let a=!1,h=!1,c=!1;try{if(this.lane==="live"&&x()&&this.lastHtml===null){console.log("[LiveSync] Holding incoming update: unsaved local edits and no baseline to merge against"),this._setHeld("live",!0,null);let f=this._saveEpoch,u=this.lastSeenSeq;clearTimeout(this._holdRetryPeer),this._holdRetryPeer=setTimeout(()=>{this._holdRetryPeer=null,!(this.isDestroyed||this._pendingHtml!=null)&&this._saveEpoch===f&&this.lastSeenSeq===u&&(this._pendingHtml=e,this._pendingSeq=t,this._pendingIdentityMap=i,this._pendingBy=r,this._scheduleNextFrame())},3e3);return}this._setHeld("live",!1);let{report:d,ticket:_,typedDuringWait:g,conflictIds:E}=await this._mergeIncoming(e,i,{base:this.lastHtml,baseIdentityMap:this._lastIdentityMap,captureLocal:()=>M({flushUndo:!1}),synthetic:!0,source:"peer",seq:t,etag:n});if(a=d.localDiverged,h=g,ne(),window.scrollTo(l,o),this._setPeerBase(e,i,_),this._applyGen++,this._acceptedSaveTicket>_||(typeof n=="string"&&n?(P(n),c=!0):le()),this.lane==="live"&&!a&&!x()){let{forSave:f,forComparison:u,forDirty:S}=Y({emitForSync:!1,flushUndo:!1});y.setLastSavedBaselines(u,S),this._setDiskBase(f,this._ticket())}this.lane==="saved"&&(this._represented=Object.freeze({bytes:e,etag:n||null,seq:t??null})),document.dispatchEvent(new CustomEvent("clay:sync-applied",{detail:{seq:t,source:this.lane==="saved"?"disk":"peer",lane:this.lane,by:r||null,html:e,report:d,unresolved:this.unresolvedConflicts,conflictIds:E}}))}finally{this._log("applyUpdate - morph complete, resuming mutations"),q.resume(),ae(),await new Promise(d=>setTimeout(d,0)),this.isPaused=!1}c&&y?.conflictResolvedBySync(n),this._saveAfterMerge(a,h)}async _doApplyExternal(e,t,i=null,n=null,r=null){if(ue(e)){await fe();return}this.lane==="live"&&!y&&await R();let l=this._diskBase;this._log(`applyExternal - external disk change (seq=${t})`),this.isPaused=!0;let o=window.scrollX,a=window.scrollY;q.pause(),oe();let h=!1,c=!1,d=!1;try{if(this.lane==="live"&&x()&&this._diskBase===null){if(console.log("[LiveSync] Holding external change: unsaved local edits and no baseline to merge against"),this._setHeld("external",!0,null),r?.startup||r?.versionCheck){clearTimeout(this._holdRetryExt),this._holdRetryExt=setTimeout(()=>{if(this._holdRetryExt=null,this.isDestroyed)return;let S=typeof t=="number"?Math.max(t,this._lastExternalSeq):t;this._retryStartup(0,r,S)},3e3);return}let u=this._saveEpoch;clearTimeout(this._holdRetryExt),this._holdRetryExt=setTimeout(()=>{this._holdRetryExt=null,!(this.isDestroyed||this._pendingExternal!=null)&&(this._pendingExternal={html:e,seq:t,saveEpoch:u,etag:i,by:n},this._scheduleNextFrame())},3e3);return}this._setHeld("external",!1);let{report:_,ticket:g,typedDuringWait:E,conflictIds:f}=await this._mergeIncoming(e,null,{base:this._diskBase,captureLocal:()=>Ne().saveClone,synthetic:!1,source:"disk",seq:t,etag:i,extra:{beforeApply:u=>Ct(u.documentElement,this.lane)}});if(h=_.localDiverged,c=E,ne(),this._setDiskBase(e,g),window.scrollTo(o,a),this._acceptedSaveTicket>g||(typeof i=="string"&&i?(P(i),d=!0):le()),this.lane==="live"&&!h&&!x()){y.setLastSavedBaselines(...At()),y.setUnsavedChanges(!1);let u=M({flushUndo:!1});this._setPeerBase(T(u),this.identity.exportMap(u,D),g),this._applyGen++}this.lane==="saved"&&(this._represented=Object.freeze({bytes:e,etag:i||null,seq:t??null})),document.dispatchEvent(new CustomEvent("clay:sync-applied",{detail:{seq:t,source:"disk",etag:typeof i=="string"&&i?i:null,by:n||null,html:e,report:_,conflictIds:f,unresolved:this.unresolvedConflicts}}))}finally{this._log("applyExternal - morph complete, resuming mutations"),q.resume(),ae(),await new Promise(_=>setTimeout(_,0)),this.isPaused=!1}d&&y?.conflictResolvedBySync(i),this._saveAfterMerge(h,c),l!=null&&j(l)===j(e)&&y&&y.schedulePaintHeal(()=>this._diskBase==null?null:j(this._diskBase))}handleNotification({msgType:e,msg:t,action:i,persistent:n,data:r}){this._log(`Notification received: ${e} - ${t}`),e==="data-loss"||(n&&window.toastPersistent?window.toastPersistent(t,e):window.toast?window.toast(t,e):console.log(`[LiveSync] Notification: ${t}`)),document.dispatchEvent(new CustomEvent("clay:notification",{detail:{msgType:e,msg:t,action:i,persistent:n,data:r}})),this.onNotification&&this.onNotification({msgType:e,msg:t,action:i,persistent:n,data:r})}stop(){this.cleanup(),this.isDestroyed=!0,console.log("[LiveSync] Stopped")}editParticipant(){return R().then(e=>e.syncParticipant(this))}},K=null;Ge((s,e)=>{K=typeof s=="string"?{html:s,captureId:e?.captureId??null}:null});var Mt=s=>K&&(K.captureId??null)===(s??null)?K.html:null;function Pt(s,e){if(typeof e!="string"||e===s)return s;let t=i=>new DOMParser().parseFromString(i,"text/html").documentElement;return t(s).isEqualNode(t(e))?e:s}var Ee=new Se;typeof window<"u"&&!ut&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>Ee.start()):Ee.start());var yn=(s,e,t)=>J().then(({morph:i})=>i(s,e,t));var mn=Ee;export{I as a,pt as b,It as c,Se as d,Ee as e,yn as f,mn as g};
@@ -1 +0,0 @@
1
- var c=/^[A-Za-z0-9._-]{1,100}$/,d="visitor-drafts",p="visitor-drafts",l=!1,u=null,i=!1,s=(t,e)=>(t?.get?.(e)||"").split(",").map(r=>r.trim()).includes(p);function m(t){l=s(t,"plugins")&&!s(t,"exclude")}function x(t=document){let e=t.documentElement.getAttribute(d);return e&&c.test(e)?e:null}var a=!1;function h(t){let e=t.querySelector('script[data-rules-name~="api"]');if(!e)return!1;let r=e.getAttribute("data-rules-version"),n=null;if(r!=="1")n=`the api rules tag says data-rules-version="${r??""}" and this version reads version 1`;else try{JSON.parse(e.textContent)}catch{n="the api rules tag does not hold readable JSON"}return n?(a||(a=!0,console.warn(`visitor-drafts: this page keeps no draft (${n})`)),!1):!0}function g(t=document,e=window.location){return l&&(e.protocol==="https:"||e.protocol==="http:")&&x(t)!==null&&h(t)}function v(t){u=t}function D(){return u}var o=null;function S(t){o=t}function T(){if(!o)return!0;try{return o()!==!1}catch{return!1}}function y(t){i=!!t}function A(){return i}var f=null;function F(t){f=t}function b(){try{return!!f?.()}catch{return!0}}export{d as a,p as b,m as c,x as d,g as e,v as f,D as g,S as h,T as i,y as j,A as k,F as l,b as m};
@@ -1 +0,0 @@
1
- import{b as y}from"./c-QTEUO2K6.js";import{a as i,e as s,f as h,g as u,h as m,k as v}from"./c-DIKR7H57.js";import{b as r,c,d as p,e as d,f}from"./c-CUMXGHVD.js";import"./c-QY7F6EN6.js";import"./c-ICMAOOGK.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";function g(){let t=()=>{let o=d()&&c(d());document.dispatchEvent(new CustomEvent("clay:variant-change",{detail:{active:o,shown:o}}))},e=o=>r().some(n=>c(n)===o)?(document.documentElement.setAttribute("look",o),f(o),window.clay?.save?.soon?.(),t(),{ok:!0}):{ok:!1,code:"unknown-variant"};r().length>=2&&(window.clay.variants={list:()=>r().map(o=>({name:c(o),label:p(o),active:o===d()})),get active(){return d()&&c(d())},get shown(){return d()&&c(d())},preview:e,choose:e,keep:()=>Promise.resolve({ok:!1,code:"not-editing"})},document.addEventListener("clay:drafts-restored",()=>{t()}))}var L='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round" aria-hidden="true"><path d="M12 9a3 3 0 1 1 0 6 3 3 0 0 1 0-6M10 3h4l1.5 3 3.5-.5 2 4-2 2.5 2 2.5-2 4-3.5-.5-1.5 3h-4l-1.5-3-3.5.5-2-4 2-2.5-2-2.5 2-4 3.5.5Z"/></svg>',w=()=>window.clay?.blockeditor?.history??window.clay?.undo??null;function S({addItem:t,beforeOpen:e}){let o=null,n=()=>{let a=w();if(!a)return;let l=o??{canUndo:!!a.canUndo,canRedo:!!a.canRedo};t({id:"clay.undo",pair:[{id:"clay.undo.undo",label:"Undo",keys:y("\u2318Z","Ctrl+Z"),disabled:!l.canUndo,run:()=>w()?.undo()},{id:"clay.undo.redo",label:"Redo",keys:y("\u2318\u21E7Z","Ctrl+Shift+Z"),disabled:!l.canRedo,run:()=>w()?.redo()}]})};document.addEventListener("clay:undo-change",a=>{o={canUndo:!!a.detail?.canUndo,canRedo:!!a.detail?.canRedo},n()}),n(),e.push(n)}function R(t=window.location){let e=t.pathname.replace(/\/+$/,"")||"/";return`/_/copy${e==="/"?"":e}`}function N(){if(document.querySelector('clay-editor-ui[data-clay-ui="menu"]'))return;let t=v({sections:[["clay.undo"],null],icon:L,label:"Settings"}),{embedded:e,skin:o,addItem:n,removeItem:a,open:l,close:k,note:b,goo:E,beforeOpen:U}=t;t.mount(e?[i,s,o??u,m]:[i,s,h,u,m]),g(),S({addItem:n,beforeOpen:U}),n({id:"clay.download",label:"Download copy",run:()=>window.clay.visitorDrafts.download()}),n({id:"clay.copy",label:"Make your own copy",href:R()}),window.clay.menu={addItem:n,removeItem:a,open:l,close:k,note:b,embedded:e,button:E},document.dispatchEvent(new CustomEvent("clay:menu-ready"))}export{N as start};
@@ -1 +0,0 @@
1
- import{a as h}from"./c-2YYDMLNZ.js";var p="sap-error",S=/^(show-when|hide-when|option|option-not):/,m=new Set(["id","data-id","class","style","sap","scope","items","item","bind","state","template","cms-template","sap-ignore"]),v=new Set(["value","checked","selected"]);function b(t){return t.hasAttribute("bind")||t.hasAttribute("persist")||!!t.closest("select[bind]")}function g(t){return t.localName==="template"||t.hasAttribute("template")||t.hasAttribute("cms-template")||t.hasAttribute("sap-ignore")}function a(t,e=null){let s=null;for(let r=t;r&&r.nodeType===1;r=r.parentElement){if(g(r))return null;if(r.hasAttribute("sap"))return r;s=r}return e&&s&&!s.isConnected?a(e):null}function A(t,e){let s=t.getAttribute("state");if(!s)return!1;for(let r of s.trim().split(/\s+/))if(r.split("=")[0].split(":")[0]===e)return!0;return!1}function y(t){if(t.hasAttribute("show"))return!0;for(let e of t.attributes)if(S.test(e.name))return!0;return!1}function x(t,e,s=null){return!t||t.nodeType!==1||!e?!1:e===p?!!a(t,s):m.has(e)||v.has(e)&&b(t)?!1:e==="hidden"?y(t)&&!!a(t,s):t.hasAttribute("attr:"+e)&&!A(t,e)&&!!a(t,s)}function f(t){if(!t||t.nodeType!==1||!a(t))return null;let e=null,s=(r,n)=>(e||(e={attrs:[],classes:[],vars:[],text:!1}))[r].push(n);for(let r of t.attributes){let n=r.name;if(n==="text"||n.startsWith("text:"))t.hasAttribute("bind")||((e||(e={attrs:[],classes:[],vars:[],text:!1})).text=!0);else if(n.startsWith("attr:")){let i=n.slice(5);i&&!m.has(i)&&!(v.has(i)&&b(t))&&!A(t,i)&&s("attrs",i)}else n.startsWith("class:")?s("classes",n.slice(6)):n.startsWith("css:")&&s("vars","--"+n.slice(4))}return y(t)&&s("attrs","hidden"),t.hasAttribute(p)&&s("attrs",p),e}function d(t,e){if(!t||t.nodeType!==1&&t.nodeType!==9)return;let s=t.nodeType===1&&t.hasAttribute("sap")?[t]:[...t.querySelectorAll("[sap]")].filter(r=>!r.parentElement||!r.parentElement.closest("[sap]"));for(let r of s)for(let n of[r,...r.querySelectorAll("*")]){let i=f(n);i&&e(n,i)}}function w(t){d(t,(e,s)=>{for(let r of s.attrs)e.hasAttribute(r)&&e.removeAttribute(r);for(let r of s.classes)e.classList.contains(r)&&e.classList.remove(r);!e.getAttribute("class")&&e.hasAttribute("class")&&s.classes.length&&e.removeAttribute("class");for(let r of s.vars)e.style.getPropertyValue(r)!==""&&e.style.removeProperty(r);s.vars.length&&e.hasAttribute("style")&&!e.getAttribute("style").trim()&&e.removeAttribute("style"),s.text&&e.firstChild&&e.replaceChildren()})}var P=(t,e,s=null)=>x(t,e,s),O=t=>!!t&&t.nodeType===1&&!!f(t)?.text,V=t=>w(t);function D(t){let e=[];return d(t,(s,r)=>{e.push(s.localName);for(let n of r.attrs)n!=="sap-error"&&e.push(n+"="+(s.getAttribute(n)??"\0"));for(let n of r.classes)e.push("."+n+"="+s.classList.contains(n));for(let n of r.vars)e.push(n+"="+s.style.getPropertyValue(n));r.text&&e.push("#"+s.textContent)}),e.join("")}function j(t){return D(new DOMParser().parseFromString(t,"text/html"))}function T(t,e,s,r,n){return s(t||"").map(i=>i.trim()).filter(i=>i&&!e.includes(n(i))).sort().join(r)}function E(t,e,s,r){let n=f(t);if(!n)return!1;if(e==="class"){if(!n.classes.length)return!1;let u=o=>T(o,n.classes,l=>l.split(/\s+/)," ",l=>l);return u(s)===u(r)}if(!n.vars.length)return!1;let i=u=>T(u,n.vars,o=>o.split(";"),";",o=>o.split(":")[0].trim());return i(s)===i(r)}function q(t){if(t.__derived!==void 0)return t.__derived;let e=t.element,s=!1;if(e&&e.nodeType===1)if(t.type==="attribute"){let r=t.attribute;s=P(e,r)||(r==="class"||r==="style")&&E(e,r,t.oldValue,t.newValue)}else t.type==="characterData"&&(s=O(e));return t.__derived=s,s}var c=new Set,_=!1;function F(){return c.size>0||h.holdSettle}var C=[];function H(){for(let t of[...c])try{t()}catch(e){console.error("clayjs: a derived repaint failed:",e)}}var L={register(t){return c.add(t),()=>c.delete(t)},mounted(){_=!0;for(let t of C.splice(0))t()}};export{P as a,O as b,V as c,D as d,j as e,q as f,F as g,H as h,L as i};
@@ -1 +0,0 @@
1
- import{a}from"./c-YDW4VCHP.js";import"./c-MFOSMAVM.js";import"./c-LD6UVV5R.js";import"./c-PGSBXHUE.js";import"./c-6IJEVE6B.js";import"./c-QQFHEODI.js";import"./c-IJUK2GPW.js";import"./c-EDE45NM7.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-U4NTUVDZ.js";import"./c-PWJSJEJU.js";import"./c-XQXZAO7N.js";import"./c-S7LK4KUE.js";import"./c-VG5XIN4T.js";import"./c-2YYDMLNZ.js";import"./c-HA6INT6J.js";import"./c-ICMAOOGK.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";export{a as replace};
@@ -1 +0,0 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k,l,m}from"../c-U4NTUVDZ.js";import"../c-VHNSBD2M.js";export{a as DRAFT_ATTR,b as DRAFT_PLUGIN,e as draftEligible,d as draftSlot,k as draftStoreFailed,g as draftTransport,m as draftUnconfirmed,i as flushDraft,c as noteBootParams,h as setDraftFlush,j as setDraftStoreFailed,f as setDraftTransport,l as setDraftUnconfirmed};
@@ -1 +0,0 @@
1
- import{a,b,c}from"../c-HTLYXCUH.js";import"../c-4ASQPRQL.js";import"../c-GQ6F6IDK.js";import"../c-I2SCCUEW.js";import"../c-5VYOWDTI.js";import"../c-6Q6RGFBF.js";import"../c-SKMIR5HQ.js";import"../c-WYFDLITL.js";import"../c-UGHH4MB3.js";import"../c-LA2BW7UY.js";import"../c-MFOSMAVM.js";import"../c-LD6UVV5R.js";import"../c-PGSBXHUE.js";import"../c-6IJEVE6B.js";import"../c-QQFHEODI.js";import"../c-IJUK2GPW.js";import"../c-EDE45NM7.js";import"../c-BPF2NSPV.js";import"../c-P7KNDG34.js";import"../c-CYWLPPUS.js";import"../c-U4NTUVDZ.js";import"../c-PWJSJEJU.js";import"../c-XQXZAO7N.js";import"../c-S7LK4KUE.js";import"../c-VG5XIN4T.js";import"../c-2YYDMLNZ.js";import"../c-HA6INT6J.js";import"../c-ICMAOOGK.js";import"../c-WRBKEJD4.js";import"../c-VHNSBD2M.js";export{c as bytesUnsaved,b as hasUnsavedChanges,a as reloadAfterDiscard};
@@ -1 +0,0 @@
1
- import{g as t,t as n,w as i}from"../c-MFOSMAVM.js";import"../c-LD6UVV5R.js";import"../c-PGSBXHUE.js";import"../c-6IJEVE6B.js";import"../c-QQFHEODI.js";import"../c-IJUK2GPW.js";import"../c-EDE45NM7.js";import"../c-BPF2NSPV.js";import"../c-P7KNDG34.js";import"../c-CYWLPPUS.js";import"../c-U4NTUVDZ.js";import{G as o,r as a,t as e}from"../c-PWJSJEJU.js";import"../c-XQXZAO7N.js";import"../c-S7LK4KUE.js";import"../c-VG5XIN4T.js";import"../c-2YYDMLNZ.js";import"../c-HA6INT6J.js";import{w as r}from"../c-ICMAOOGK.js";import"../c-WRBKEJD4.js";import"../c-VHNSBD2M.js";var s=window.clay=window.clay||{};s.internals={captureSnapshot:e,captureForSave:o,addDocumentTransform:a,region:r,save:{saveHtml:n,replacePageWith:i,isSaveInProgress:t}};var l=s.internals;export{l as default};