@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
@@ -1 +1 @@
1
- import{a as $}from"./c-XQXZAO7N.js";import{e as Y}from"./c-S7LK4KUE.js";import{c as z}from"./c-VG5XIN4T.js";import{b as H,i as I,o as F}from"./c-HA6INT6J.js";import{c as D,h as A,j as T,k as _,n as C,o as L}from"./c-ICMAOOGK.js";var K=[],f=[],g=new WeakMap,w=null,U=null,b=0;function de(){return b}function G(e){return g.get(e)||null}var M=new WeakMap,v=null;function he(){return v}function me(e){v&&e&&(v.artifact=e)}var R=null,x=new Map;function ye(e){R=e}function ve(e){return e==null?null:x.get(e)??null}function Se(e){return e&&M.get(e)||null}function X(e){e&&(M.delete(e),x.delete(e.captureId))}function J(e){let t=o=>{if(o.hasAttribute("onbeforesave")||o.hasAttribute("onbeforesnapshot"))return!0;let r=o.localName==="template"&&o.content?o.content:o;for(let n of r.children)if(t(n))return!0;return!1};return e.nodeType===1?t(e):!1}function a(e){for(let t of e.querySelectorAll(L))t.remove()}function m(e,t){for(let o of e.querySelectorAll(`[${t}]`))if(a(e),!(o!==e&&!e.contains(o)))try{new Function(o.getAttribute(t)).call(o)}catch(r){console.error(`[${t}] handler failed:`,r)}}var O=null;function Ce(e){O=e}function xe(e){return O?.(e),e}function Ae(e){K.push(e)}function Te(e,{steps:t=null}={}){w=e,U=t}var j="http://www.w3.org/1999/xhtml";function P(e){let t=B(e);if(!t.length)return"<!DOCTYPE html>"+e.outerHTML;let o=V(t),r;try{r="<!DOCTYPE html>"+e.outerHTML}finally{for(let[n,c]of t)n.replaceChildren(...c)}for(let[n,c]of o)r=r.split(n).join(c);return r}function B(e){let t=[],o=r=>{for(let n of r.childNodes)if(n.nodeType===1){if(n.localName==="noscript"&&n.namespaceURI===j){let c=Array.from(n.childNodes);c.length&&c.every(l=>l.nodeType===3)&&t.push([n,c]);continue}o(n.localName==="template"&&n.content?n.content:n)}};return o(e),t}function ge(e){let t=[],o=r=>{for(let n of r.childNodes)if(n.nodeType===1){if(n.localName==="noscript"&&n.namespaceURI===j){n.firstChild&&t.push(n);continue}o(n.localName==="template"&&n.content?n.content:n)}};o(e.documentElement??e);for(let r of t)r.replaceChildren(r.ownerDocument.createTextNode(r.innerHTML));return e}function V(e){let t=Math.random().toString(36).slice(2);return e.map(([o,r],n)=>{let c=`\uE000clay-noscript-${t}-${n}\uE000`;return o.replaceChildren(o.ownerDocument.createTextNode(c)),[c,r.map(l=>l.data).join("")]})}function W(e,t){let o=v;v=e;try{return t()}finally{v=o}}function N(e,t=null){if(t&&R){let r=null;try{r=R(e)}catch{}r&&x.set(t.captureId,r)}let o=P(e);if(!w)return o;try{return W(t,()=>w(e,o))}catch(r){return console.error("clayjs: save renderer failed, sending the full serialization",r),o}}function we(e){f.push(e)}function h(e,t=!0){let o=window.__preventOnclone;window.__preventOnclone=!0;try{return e.cloneNode(t)}finally{window.__preventOnclone=o}}function k(e,t){let o=g.get(e);o&&g.set(t,o);let r=e.children,n=t.children;for(let c=0;c<r.length;c++)k(r[c],n[c])}function p({flushUndo:e=!0,authored:t=!0,forSave:o=!1,requestRefresh:r=!1,context:n=null}={}){e&&typeof window<"u"&&window.clay?.undo?.flush&&window.clay.undo.flush();let l=$(document.documentElement,{capability:"snapshot",provenance:g}).root;for(let u of K)a(l),u(l,{original:G,forSave:o,requestRefresh:r});return Y(l),O?.(l),a(l),n&&(n.authoredHandlers=J(l)),t&&m(l,"onbeforesnapshot"),a(l),D(l),F(l),H(l),l}function E(e,{authored:t=!0}={}){a(e),t&&m(e,"onbeforesave");for(let o of f)a(e),o(e);a(e);for(let o of e.querySelectorAll(A))o.remove();return q(e),e}function q(e){for(let t of e.querySelectorAll("[sap-error]"))t.removeAttribute("sap-error")}function Q({flushUndo:e=!0,authored:t=!0}={}){return E(p({flushUndo:e,authored:t}),{authored:t})}var Z=["style","class"];function ee(e){z(e);for(let t of Z){e.getAttribute(t)===""&&e.removeAttribute(t);for(let o of e.querySelectorAll(`[${t}=""]`))o.removeAttribute(t)}}function S(e){return ee(e),"<!DOCTYPE html>"+e.outerHTML}function Re({flushUndo:e=!0}={}){let t=p({flushUndo:e});m(t,"onbeforesave");for(let o of t.querySelectorAll(T))o.remove();for(let o of f)a(t),o(t);return a(t),S(t)}function ke({flushUndo:e=!0}={}){let t=p({flushUndo:e});m(t,"onbeforesave");for(let o of t.querySelectorAll(C))o.remove();for(let o of f)a(t),o(t);return a(t),S(t)}function Ee({flushUndo:e=!0}={}){let t=p({flushUndo:e});m(t,"onbeforesave");let o=t.querySelector(_)?h(t):null;o&&k(t,o);for(let c of t.querySelectorAll(T))c.remove();for(let c of f)a(t),c(t);a(t);let r=S(t),n=r;if(o){for(let c of o.querySelectorAll(C))c.remove();for(let c of f)a(o),c(o);a(o),n=S(o)}return{forComparison:r,forDirty:n}}function te({emitForSync:e=!0,flushUndo:t=!0,requestRefresh:o=!1,forRequest:r=!1,pageFormatMarker:n=null,sliced:c=!1}={}){if(!Number.isSafeInteger(b+1))throw new Error("Save capture identity exhausted");let l=++b,u=r?{captureId:l,authoredHandlers:!1,artifact:null}:null,s=p({flushUndo:t,forSave:e,requestRefresh:o,context:u});e&&document.dispatchEvent(new CustomEvent("clay:snapshot-ready",{detail:{documentElement:s,forSave:!0,captureId:l,sliced:c}})),m(s,"onbeforesave");let y=h(s);k(s,y);let d=s.querySelector(_)?h(s):null;d&&k(s,d);for(let i of f)a(s),i(s);a(s);for(let i of s.querySelectorAll(A))i.remove();q(s);for(let i of y.querySelectorAll(T))i.remove();for(let i of f)a(y),i(y);if(a(y),d){for(let i of d.querySelectorAll(C))i.remove();for(let i of f)a(d),i(d);a(d)}return{captureId:l,context:u,pageFormatMarker:n,clone:s,compareClone:y,dirtyClone:d,renderer:w,rendererSteps:U,pageStateReader:R,result:null}}function oe(e){if(!e.context||!e.pageStateReader)return;let t=null;try{t=e.pageStateReader(e.clone)}catch{}t&&x.set(e.captureId,t)}function re(e,{forSave:t,forComparison:o,forDirty:r}){let n={forSave:t,forComparison:o,forDirty:r,captureId:e.captureId};return e.context&&e.context.artifact&&M.set(n,e.context.artifact),e.result=n,n}function ne(e){X(e.result),x.delete(e.captureId),e.context&&(e.context.artifact=null),e.clone=e.compareClone=e.dirtyClone=null,e.result=null}function _e(e={}){let t=te(e);try{oe(t);let o=P(t.clone),r=t.compareClone?S(t.compareClone):null,n=t.dirtyClone?S(t.dirtyClone):r,c=t.renderer?W(t.context,()=>t.renderer(t.clone,o)):o;return re(t,{forSave:c,forComparison:r,forDirty:n})}catch(o){throw ne(t),o}}function be(){let e=p({flushUndo:!1});m(e,"onbeforesave");let t=h(e),o=new WeakMap;(function r(n,c){o.set(n,c);let l=n.children,u=c.children;for(let s=0;s<l.length;s++)r(l[s],u[s])})(t,e);for(let r of f)a(e),r(e);a(e);for(let r of e.querySelectorAll(A))r.remove();q(e);for(let r of t.querySelectorAll(C))r.remove();for(let r of f)a(t),r(t);return a(t),{saveClone:e,compareClone:t,pairMap:o}}function ce({emitForSync:e=!0}={}){let t=p();return e&&document.dispatchEvent(new CustomEvent("clay:snapshot-ready",{detail:{documentElement:t}})),N(E(t))}function Me(e){let t=h(e,!1);for(let u of I)t.removeAttribute(u);let o=t.outerHTML,r=`</${t.localName}>`,n=B(e),c=n.length?V(n):[],l;try{l=e.innerHTML}finally{for(let[u,s]of n)u.replaceChildren(...s)}for(let[u,s]of c)l=l.split(u).join(s);return"<!DOCTYPE html>"+o.slice(0,o.length-r.length)+l+r}function Oe(e){return h(e)}function Pe(){return p().querySelector("body").innerHTML}function Ne({transform:e=null,flushUndo:t=!0}={}){if(!e&&t)return ce({emitForSync:!1});let o=p({flushUndo:t});if(e){let r=e(o);if(r&&typeof r.then=="function")throw new TypeError("getHTML: the transform must be synchronous")}return N(E(o))}function qe(e,{prepared:t=!1}={}){let o=h(e);return P(t?o:E(o,{authored:!1}))}function He(){return N(Q({flushUndo:!1,authored:!1}))}export{de as a,G as b,he as c,me as d,ye as e,ve as f,Se as g,X as h,Ce as i,xe as j,Ae as k,Te as l,P as m,B as n,ge as o,V as p,W as q,we as r,h as s,p as t,Q as u,ee as v,S as w,Re as x,ke as y,Ee as z,te as A,oe as B,re as C,ne as D,_e as E,be as F,ce as G,Me as H,Oe as I,Pe as J,Ne as K,qe as L,He as M};
1
+ import{a as $}from"./c-XQXZAO7N.js";import{e as Y}from"./c-S7LK4KUE.js";import{c as z}from"./c-MOP5KBWZ.js";import{b as H,i as I,o as F}from"./c-HA6INT6J.js";import{c as D,h as A,j as T,k as _,n as C,o as L}from"./c-ICMAOOGK.js";var K=[],f=[],g=new WeakMap,w=null,U=null,b=0;function de(){return b}function G(e){return g.get(e)||null}var M=new WeakMap,v=null;function he(){return v}function me(e){v&&e&&(v.artifact=e)}var R=null,x=new Map;function ye(e){R=e}function ve(e){return e==null?null:x.get(e)??null}function Se(e){return e&&M.get(e)||null}function X(e){e&&(M.delete(e),x.delete(e.captureId))}function J(e){let t=o=>{if(o.hasAttribute("onbeforesave")||o.hasAttribute("onbeforesnapshot"))return!0;let r=o.localName==="template"&&o.content?o.content:o;for(let n of r.children)if(t(n))return!0;return!1};return e.nodeType===1?t(e):!1}function a(e){for(let t of e.querySelectorAll(L))t.remove()}function m(e,t){for(let o of e.querySelectorAll(`[${t}]`))if(a(e),!(o!==e&&!e.contains(o)))try{new Function(o.getAttribute(t)).call(o)}catch(r){console.error(`[${t}] handler failed:`,r)}}var O=null;function Ce(e){O=e}function xe(e){return O?.(e),e}function Ae(e){K.push(e)}function Te(e,{steps:t=null}={}){w=e,U=t}var j="http://www.w3.org/1999/xhtml";function P(e){let t=B(e);if(!t.length)return"<!DOCTYPE html>"+e.outerHTML;let o=V(t),r;try{r="<!DOCTYPE html>"+e.outerHTML}finally{for(let[n,c]of t)n.replaceChildren(...c)}for(let[n,c]of o)r=r.split(n).join(c);return r}function B(e){let t=[],o=r=>{for(let n of r.childNodes)if(n.nodeType===1){if(n.localName==="noscript"&&n.namespaceURI===j){let c=Array.from(n.childNodes);c.length&&c.every(l=>l.nodeType===3)&&t.push([n,c]);continue}o(n.localName==="template"&&n.content?n.content:n)}};return o(e),t}function ge(e){let t=[],o=r=>{for(let n of r.childNodes)if(n.nodeType===1){if(n.localName==="noscript"&&n.namespaceURI===j){n.firstChild&&t.push(n);continue}o(n.localName==="template"&&n.content?n.content:n)}};o(e.documentElement??e);for(let r of t)r.replaceChildren(r.ownerDocument.createTextNode(r.innerHTML));return e}function V(e){let t=Math.random().toString(36).slice(2);return e.map(([o,r],n)=>{let c=`\uE000clay-noscript-${t}-${n}\uE000`;return o.replaceChildren(o.ownerDocument.createTextNode(c)),[c,r.map(l=>l.data).join("")]})}function W(e,t){let o=v;v=e;try{return t()}finally{v=o}}function N(e,t=null){if(t&&R){let r=null;try{r=R(e)}catch{}r&&x.set(t.captureId,r)}let o=P(e);if(!w)return o;try{return W(t,()=>w(e,o))}catch(r){return console.error("clayjs: save renderer failed, sending the full serialization",r),o}}function we(e){f.push(e)}function h(e,t=!0){let o=window.__preventOnclone;window.__preventOnclone=!0;try{return e.cloneNode(t)}finally{window.__preventOnclone=o}}function k(e,t){let o=g.get(e);o&&g.set(t,o);let r=e.children,n=t.children;for(let c=0;c<r.length;c++)k(r[c],n[c])}function p({flushUndo:e=!0,authored:t=!0,forSave:o=!1,requestRefresh:r=!1,context:n=null}={}){e&&typeof window<"u"&&window.clay?.undo?.flush&&window.clay.undo.flush();let l=$(document.documentElement,{capability:"snapshot",provenance:g}).root;for(let u of K)a(l),u(l,{original:G,forSave:o,requestRefresh:r});return Y(l),O?.(l),a(l),n&&(n.authoredHandlers=J(l)),t&&m(l,"onbeforesnapshot"),a(l),D(l),F(l),H(l),l}function E(e,{authored:t=!0}={}){a(e),t&&m(e,"onbeforesave");for(let o of f)a(e),o(e);a(e);for(let o of e.querySelectorAll(A))o.remove();return q(e),e}function q(e){for(let t of e.querySelectorAll("[sap-error]"))t.removeAttribute("sap-error")}function Q({flushUndo:e=!0,authored:t=!0}={}){return E(p({flushUndo:e,authored:t}),{authored:t})}var Z=["style","class"];function ee(e){z(e);for(let t of Z){e.getAttribute(t)===""&&e.removeAttribute(t);for(let o of e.querySelectorAll(`[${t}=""]`))o.removeAttribute(t)}}function S(e){return ee(e),"<!DOCTYPE html>"+e.outerHTML}function Re({flushUndo:e=!0}={}){let t=p({flushUndo:e});m(t,"onbeforesave");for(let o of t.querySelectorAll(T))o.remove();for(let o of f)a(t),o(t);return a(t),S(t)}function ke({flushUndo:e=!0}={}){let t=p({flushUndo:e});m(t,"onbeforesave");for(let o of t.querySelectorAll(C))o.remove();for(let o of f)a(t),o(t);return a(t),S(t)}function Ee({flushUndo:e=!0}={}){let t=p({flushUndo:e});m(t,"onbeforesave");let o=t.querySelector(_)?h(t):null;o&&k(t,o);for(let c of t.querySelectorAll(T))c.remove();for(let c of f)a(t),c(t);a(t);let r=S(t),n=r;if(o){for(let c of o.querySelectorAll(C))c.remove();for(let c of f)a(o),c(o);a(o),n=S(o)}return{forComparison:r,forDirty:n}}function te({emitForSync:e=!0,flushUndo:t=!0,requestRefresh:o=!1,forRequest:r=!1,pageFormatMarker:n=null,sliced:c=!1}={}){if(!Number.isSafeInteger(b+1))throw new Error("Save capture identity exhausted");let l=++b,u=r?{captureId:l,authoredHandlers:!1,artifact:null}:null,s=p({flushUndo:t,forSave:e,requestRefresh:o,context:u});e&&document.dispatchEvent(new CustomEvent("clay:snapshot-ready",{detail:{documentElement:s,forSave:!0,captureId:l,sliced:c}})),m(s,"onbeforesave");let y=h(s);k(s,y);let d=s.querySelector(_)?h(s):null;d&&k(s,d);for(let i of f)a(s),i(s);a(s);for(let i of s.querySelectorAll(A))i.remove();q(s);for(let i of y.querySelectorAll(T))i.remove();for(let i of f)a(y),i(y);if(a(y),d){for(let i of d.querySelectorAll(C))i.remove();for(let i of f)a(d),i(d);a(d)}return{captureId:l,context:u,pageFormatMarker:n,clone:s,compareClone:y,dirtyClone:d,renderer:w,rendererSteps:U,pageStateReader:R,result:null}}function oe(e){if(!e.context||!e.pageStateReader)return;let t=null;try{t=e.pageStateReader(e.clone)}catch{}t&&x.set(e.captureId,t)}function re(e,{forSave:t,forComparison:o,forDirty:r}){let n={forSave:t,forComparison:o,forDirty:r,captureId:e.captureId};return e.context&&e.context.artifact&&M.set(n,e.context.artifact),e.result=n,n}function ne(e){X(e.result),x.delete(e.captureId),e.context&&(e.context.artifact=null),e.clone=e.compareClone=e.dirtyClone=null,e.result=null}function _e(e={}){let t=te(e);try{oe(t);let o=P(t.clone),r=t.compareClone?S(t.compareClone):null,n=t.dirtyClone?S(t.dirtyClone):r,c=t.renderer?W(t.context,()=>t.renderer(t.clone,o)):o;return re(t,{forSave:c,forComparison:r,forDirty:n})}catch(o){throw ne(t),o}}function be(){let e=p({flushUndo:!1});m(e,"onbeforesave");let t=h(e),o=new WeakMap;(function r(n,c){o.set(n,c);let l=n.children,u=c.children;for(let s=0;s<l.length;s++)r(l[s],u[s])})(t,e);for(let r of f)a(e),r(e);a(e);for(let r of e.querySelectorAll(A))r.remove();q(e);for(let r of t.querySelectorAll(C))r.remove();for(let r of f)a(t),r(t);return a(t),{saveClone:e,compareClone:t,pairMap:o}}function ce({emitForSync:e=!0}={}){let t=p();return e&&document.dispatchEvent(new CustomEvent("clay:snapshot-ready",{detail:{documentElement:t}})),N(E(t))}function Me(e){let t=h(e,!1);for(let u of I)t.removeAttribute(u);let o=t.outerHTML,r=`</${t.localName}>`,n=B(e),c=n.length?V(n):[],l;try{l=e.innerHTML}finally{for(let[u,s]of n)u.replaceChildren(...s)}for(let[u,s]of c)l=l.split(u).join(s);return"<!DOCTYPE html>"+o.slice(0,o.length-r.length)+l+r}function Oe(e){return h(e)}function Pe(){return p().querySelector("body").innerHTML}function Ne({transform:e=null,flushUndo:t=!0}={}){if(!e&&t)return ce({emitForSync:!1});let o=p({flushUndo:t});if(e){let r=e(o);if(r&&typeof r.then=="function")throw new TypeError("getHTML: the transform must be synchronous")}return N(E(o))}function qe(e,{prepared:t=!1}={}){let o=h(e);return P(t?o:E(o,{authored:!1}))}function He(){return N(Q({flushUndo:!1,authored:!1}))}export{de as a,G as b,he as c,me as d,ye as e,ve as f,Se as g,X as h,Ce as i,xe as j,Ae as k,Te as l,P as m,B as n,ge as o,V as p,W as q,we as r,h as s,p as t,Q as u,ee as v,S as w,Re as x,ke as y,Ee as z,te as A,oe as B,re as C,ne as D,_e as E,be as F,ce as G,Me as H,Oe as I,Pe as J,Ne as K,qe as L,He as M};
@@ -1,3 +1,3 @@
1
- import{a as me,b as pe,c as he}from"./c-SIM7Z3U7.js";import{a as de,b as fe}from"./c-OYW5MFPZ.js";import{a as F,b as U,c as ue}from"./c-H3FNLBHN.js";import{C as X,E as le,h as z,l as ce,m as Y}from"./c-ZRGEN6QQ.js";import{A as se,d as N,x as oe}from"./c-OH2FPYSY.js";import"./c-VPXCXBDT.js";import{b as $,c as ae,d as R}from"./c-Z6MROEQ4.js";import{b as ie}from"./c-Q26XHBLQ.js";import{a as H,b as V}from"./c-RETTCOWO.js";import{a as re}from"./c-3LDGIBMN.js";import"./c-VHNSBD2M.js";var ge=16384,we=i=>new TextEncoder().encode(JSON.stringify(i)).length,G=class extends Error{constructor(n,t=n){super(t),this.name="ToolRequestError",this.code=n}};function Oe(i){let n=re(i);for(Array.isArray(n.tables)||(n.tables=[]),Array.isArray(n.outline)||(n.outline=[]);we(n)>ge;){let t=[...n.tables].reverse().find(r=>Array.isArray(r.rows)&&r.rows.length);if(t)t.rows.pop();else if(n.outline.length)n.outline.pop();else break}if(we(n)>ge)throw new G("context-too-large");return n}var Me=()=>globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function ve({transport:i,newId:n=Me}){let t=null,r=s=>{!s||s.discarded||s.done||(s.discarded=!0,t===s&&(t=null),i.cancel(s.requestId),s.resolve({requestId:s.requestId,code:"discarded",message:"Candidate discarded"}))};return{request(s,a,v=null,h=null){let o=Oe(a);t&&r(t);let m=n(),l={requestId:m,discarded:!1,done:!1};l.promise=new Promise(u=>{l.resolve=u}),t=l;let e={protocol:"blockeditor-tool/1",requestId:m,prompt:s,context:o,target:v,current:h};l.request=e;let f=u=>{if(!(l.discarded||l.done||u?.requestId!==m))if(l.done=!0,t===l&&(t=null),u?.artifact!==void 0){let g=F(u.artifact),d=U(u.state),p=g.ok?d.ok?null:d:g;l.resolve(p?{requestId:m,code:p.code,message:p.code}:u)}else l.resolve(typeof u?.code=="string"?u:{requestId:m,code:"invalid-result",message:"invalid-result"})};try{let u=g=>f({requestId:m,code:typeof g?.code=="string"?g.code:"transport-error",message:String(g?.message??g)});Promise.resolve(i.request(e)).then(f,u)}catch(u){f({requestId:m,code:typeof u?.code=="string"?u.code:"transport-error",message:String(u?.message??u)})}return l},discard:r,async wait(s,{signal:a}={}){if(a?.aborted)throw new DOMException("Aborted","AbortError");let v,h=await(a?Promise.race([s.promise,new Promise((o,m)=>{v=()=>m(new DOMException("Aborted","AbortError")),a.addEventListener("abort",v,{once:!0})})]).finally(()=>a.removeEventListener("abort",v)):s.promise);if(h?.code)throw new G(h.code,h.message);return h}}}var J=class extends Error{constructor(n){super(n),this.name="ToolTransportError",this.code=n}};function ye({getWire:i=()=>globalThis.window?.clay?.wire??null}={}){let n=new Map;return{request(t,{onStatus:r=null}={}){let s=i();if(!s||typeof s.send!="function")return Promise.reject(new J("no-wire"));let a=t?.requestId,v;try{v=s.send(t,{helper:"blockeditor-tool",document:"none",id:a,onStatus:r})}catch{return Promise.reject(new J("no-wire"))}return n.set(a,v),Promise.resolve(v.done).then(h=>{if(n.get(a)===v&&n.delete(a),h?.state==="done"){let o=h.result??{};return{requestId:typeof o.requestId=="string"?o.requestId:a,artifact:o.artifact,state:o.state,model:o.model}}return{requestId:a,code:h?.errorCode||(h?.state==="cancelled"?"cancelled":"transport-error"),message:h?.error||"the helper reported an error"}},()=>({requestId:a,code:"transport-error",message:"the helper reported an error"}))},cancel(t){let r=n.get(t);n.delete(t),r?.cancel?.()}}}var{Selection:Be}=V,W="This page is not open for editing any more.",Ie="AI tool making isn't available on this page right now.",Te="This document can't save tool data.",K="The place for this tool moved. Close this and run /ai where you want the tool.",be="This tool changed while you were revising, so nothing was replaced. Ask again.",Q="AI did not make a usable tool. Try again.",Ne="The tool data from AI is too large or not usable. Try again.",xe="This tool's data changed while AI was working, so it was not replaced. Ask again to include the latest data.",Ae="The tool could not be saved, so it was not added. Try again.",Re="Your tool is in the document, but saving failed. It will be saved with your next edit.";function _(i,n){let t=null;return i.forEach((r,s,a)=>{r.attrs.id===n&&(t={node:r,at:s,index:a})}),t}function Pe(i,n){let t=i.selection.$head,r=Math.min(Math.max(t.index(0),0),i.doc.childCount-1);return{hostId:i.doc.child(r)?.attrs.id??null,slashText:n?i.doc.textBetween(n.from,n.to):null,slashOffset:n&&t.depth?n.from-t.before(1)-1:null}}function Z(i,n){let t=n?.hostId?_(i.doc,n.hostId):null;if(!t)return null;let r=i.doc.maybeChild(t.index+1),s=t.node.isTextblock&&(t.node.content.size===0||t.node.textContent===n.slashText);return{...t,replace:s,pos:s?t.node.attrs.pos:oe(t.node.attrs.pos,r?.attrs.pos??null),insertAt:s?t.at:t.at+t.node.nodeSize}}function _e(i,n,t){let r=i.state,s=Z(r,t);if(!s)return!1;let{node:a,at:v,insertAt:h,replace:o}=s,m=N.nodes.tool.create({id:n.id,pos:s.pos,parent:a.attrs.parent??null,artifact:n.artifact,rev:n.rev,state:n.state}),l=r.tr;if(!o&&t?.hostId===a.attrs.id&&t.slashText&&t.slashOffset>=0){let f=v+1+t.slashOffset,u=f+t.slashText.length;u<=v+a.nodeSize-1&&r.doc.textBetween(f,u)===t.slashText&&l.delete(f,u)}let e=l.mapping.map(h);return l.replaceWith(e,o?l.mapping.map(v+a.nodeSize):e,m),l.setSelection(Be.near(l.doc.resolve(Math.min(e+m.nodeSize,l.doc.content.size)))),i.dispatch(X(l).scrollIntoView()),!0}var Se=()=>({x:0,y:0,left:0,top:0,right:0,bottom:0,width:0,height:0});function Ee({getView:i,store:n=()=>null,acceptState:t=()=>globalThis.clay?.save?.flush?.(),newId:r=se,transport:s=ye()}={}){let a=()=>{let e=i();return e&&!e.isDestroyed?e:null},v=()=>typeof n=="function"?n():n,h=(e,f)=>{let u=v()?.data?.[e]?.[f];return u===void 0?{}:u},o=new Map,m=e=>Array.isArray(e)?`[${e.map(m).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(u=>`${JSON.stringify(u)}:${m(e[u])}`).join(",")}}`:JSON.stringify(e)??"null";function l(e=null,f=null){let u=a(),g=e||!u?null:Pe(u.state,f),d=null,p=ve({transport:{request:c=>s.request(c,{onStatus:T=>d?.(T)}),cancel:c=>s.cancel(c)}}),b=null,w=null,y=null,M=!1,k=null,O=null,C=()=>{y?.host?.dispose(),y=null},L=()=>{let c=a();return c&&e?ie.get(c)?.get(e)??null:null},j=()=>L()?.suspend(),B=()=>L()?.resume(),q=c=>{M=!1;let T=a();return C(),T&&R(T),B(),{status:"failed",message:c}},ne={aiTarget:!0,label:e?"This tool":"New tool",ref:e?[e]:[],placeholder:e?"What should change?":"Describe the tool",get isConnected(){let c=a();return c?e?!!_(c.state.doc,e):!0:!1},getBoundingClientRect(){let c=a();if(!c)return Se();if(y)return y.dom.getBoundingClientRect();let T=e??g?.hostId,A=T?_(c.state.doc,T):null,E=A?c.nodeDOM(A.at):null;return E&&typeof E.getBoundingClientRect=="function"?E.getBoundingClientRect():Se()},async start(c){w=null,M=!1;let T=a();if(!T)return{status:"refused",code:"gone",message:W};if(!globalThis.window?.clay?.wire)return{status:"refused",code:"no-wire",message:Ie};let A=null,E=null;if(e){let x=_(T.state.doc,e);if(x?.node.type!==N.nodes.tool)return{status:"refused",code:"gone",message:W};k=x.node.attrs.rev,A={toolId:e,rev:k},j(),E={artifact:x.node.attrs.artifact,state:h(e,k)},O=m(E.state)}return b=p.request(c,fe(T.state.doc,T.dom.ownerDocument.title),A,E),{status:"ok",id:b.requestId,send:(x={})=>(d=typeof x.onStatus=="function"?x.onStatus:null,{done:p.wait(b).then(S=>(w={id:e,rev:null,artifact:S.artifact,state:S.state},{state:"done",result:S}),S=>(B(),{state:"error",error:S?.message||S?.code||"the helper reported an error",code:S?.code??null})),cancel:()=>{B(),p.discard(b)}})}},async propose(c){let T=a();if(!T||!c)return{status:"refused",message:W};if(!F(c.artifact).ok)return{status:"refused",message:Q};if(!U(c.state).ok)return{status:"refused",message:Ne};w={id:e,rev:null,artifact:c.artifact,state:c.state};let x=De(T);return x.status!=="ready"&&(w=null),x},async keep(){if(!w||M)return q(be);let c=a();if(!c)return q(W);let T=v();if(!T)return q(Te);let A=()=>e&&O!==null&&m(h(e,k))!==O;if(A())return q(xe);M=!0;let E=w.id??r("b"),x=r("rev"),I={...w,id:E,rev:x};try{await T.set([E,x],I.state)}catch(D){return q(D?.message??Te)}let S=null;try{S=await t()}catch{return q(Ae)}if(S?.ok!==!0&&!["saved","clean"].includes(S?.state))return q(S?.msg??S?.message??Ae);if(e){let D=_(c.state.doc,e);if(D?.node.type!==N.nodes.tool||D.node.attrs.rev!==k)return q(be)}else if(!Z(c.state,g))return q(K);if(A())return q(xe);if(C(),R(c),e){let D=_(c.state.doc,e);c.dispatch(X(c.state.tr.setNodeMarkup(D.at,null,{...D.node.attrs,artifact:I.artifact,rev:I.rev})))}else if(!_e(c,I,g))return q(K);let P=!1;for(let D=0;D<2&&!P;D++)try{P=(await t())?.ok!==!1}catch{P=!1}return P?(o.delete(e??"new"),{status:"kept"}):{status:"failed",message:Re}},discard(){C();let c=a();c&&R(c),p.discard(b),B(),o.delete(e??"new")}};function De(c){C();let T=ue({mode:"view",tables:()=>de(c.state.doc).map(({id:I,cols:S,rows:P})=>({id:I,cols:S,rows:P}))}),A=c.dom.ownerDocument.createElement("div");A.className="blockeditor-ai-preview";let E=null;try{E=T.mount(A,{id:"preview",rev:"preview",artifact:w.artifact,seed:w.state})}catch{return T.dispose(),{status:"refused",message:Q}}if(E.failed)return T.dispose(),{status:"refused",message:Q};if(y={host:T,dom:A},e)return $(c,{ids:[e],dom:A}),{status:"ready"};let x=Z(c.state,g);return x?(x.replace?$(c,{ids:[x.node.attrs.id],dom:A}):ae(c,{at:x.insertAt,dom:A}),{status:"ready"}):(C(),{status:"refused",message:K})}return e&&o.set(e,ne),ne}return{newTool(e=null){return l(null,e)},reviseTool(e){let f=o.get(e);return f?.isConnected?f:(o.delete(e),l(e))}}}var{TextSelection:$e}=V,ze="ai-edit",Le="page area",je="This section is too large for AI editing. Select a smaller part.",Ce="Someone changed this area while AI was working, so nothing was changed.",Ve="This page is not open for editing any more.",Fe="AI editing isn't available on this page right now.",Ue=0;function te(i,n){let t=null;return i.forEach((r,s)=>{r.attrs?.id===n&&(t={node:r,at:s})}),t}var qe=(i,n)=>te(i,n)?.node?.type===N.nodes.tool,ee=(i,n,t)=>i.slice(n,t+1).map(r=>r.node.attrs.id).filter(Boolean),Ge=()=>globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,ke=()=>({x:0,y:0,left:0,top:0,right:0,bottom:0,width:0,height:0});function Je(i){if(!i.length)return ke();let n=Math.min(...i.map(a=>a.left)),t=Math.min(...i.map(a=>a.top)),r=Math.max(...i.map(a=>a.right)),s=Math.max(...i.map(a=>a.bottom));return{x:n,y:t,left:n,top:t,right:r,bottom:s,width:r-n,height:s-t}}function We(i,n,t){let r=i.selection;if(!(r instanceof $e)||r.empty)return null;let[s,a]=ce(i.doc,r,n);if(s!==a||t.lo!==s||t.hi!==s)return null;let v=n[s];if(r.from<v.at||r.to>v.end)return null;let h=i.doc.textBetween(r.from,r.to," ");if(!h.trim())return null;let o=i.doc.textBetween(v.at+1,r.from," ").length;return{text:h,start:o,end:o+h.length}}function Tt({getView:i,store:n=()=>null,acceptState:t}={}){let r=()=>{let o=i();return o&&!o.isDestroyed?o:null},s=new Map,a=Ee({getView:r,store:n,acceptState:t}),v=o=>a.reviseTool(o);function h(o,{quote:m=null,label:l=null}={}){for(let[d,p]of s)p.isConnected||s.delete(d);let e=s.get(o.join(","));if(e)return e.quote=m??void 0,e;let f=null,u=null,g={aiTarget:!0,label:l??(o.length===1?"This block":`${o.length} blocks`),ref:[...o],get isConnected(){let d=r();return!!d&&o.some(p=>te(d.state.doc,p))},getBoundingClientRect(){let d=r();if(!d)return ke();let p=d.dom.querySelector(".blockeditor-ai-preview");if(p)return p.getBoundingClientRect();let w=[g.ref[0],g.ref[g.ref.length-1]].map(y=>te(d.state.doc,y)).map(y=>y?d.nodeDOM(y.at):null).filter(y=>y&&typeof y.getBoundingClientRect=="function").map(y=>y.getBoundingClientRect());return Je(w)},async start(d,p){let b=r();if(!b)return{status:"refused",code:"gone",message:Ve};let w=window.clay?.wire;if(!w)return{status:"refused",code:"no-wire",message:Fe};let{captureArea:y,AREA_GUIDE:M}=await import("./c-47IBJGPQ.js"),k=y(b.state.doc,g.ref);if(f=null,u=null,k.status!=="ok")return{status:"refused",code:k.code,message:k.message};let O=p??g.quote,C={id:"req-"+Date.now().toString(36)+"-"+ ++Ue,editId:Le,tag:"div",elementHTML:k.capture.html,comment:d+`
1
+ import{a as me,b as pe,c as he}from"./c-SIM7Z3U7.js";import{a as de,b as fe}from"./c-OYW5MFPZ.js";import{a as F,b as U,c as ue}from"./c-H3FNLBHN.js";import{C as X,E as le,h as z,l as ce,m as Y}from"./c-AI3H6ETU.js";import{A as se,d as N,x as oe}from"./c-OH2FPYSY.js";import"./c-VPXCXBDT.js";import{b as $,c as ae,d as R}from"./c-Z6MROEQ4.js";import{b as ie}from"./c-Q26XHBLQ.js";import{a as H,b as V}from"./c-RETTCOWO.js";import{a as re}from"./c-3LDGIBMN.js";import"./c-VHNSBD2M.js";var ge=16384,we=i=>new TextEncoder().encode(JSON.stringify(i)).length,G=class extends Error{constructor(n,t=n){super(t),this.name="ToolRequestError",this.code=n}};function Oe(i){let n=re(i);for(Array.isArray(n.tables)||(n.tables=[]),Array.isArray(n.outline)||(n.outline=[]);we(n)>ge;){let t=[...n.tables].reverse().find(r=>Array.isArray(r.rows)&&r.rows.length);if(t)t.rows.pop();else if(n.outline.length)n.outline.pop();else break}if(we(n)>ge)throw new G("context-too-large");return n}var Me=()=>globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;function ve({transport:i,newId:n=Me}){let t=null,r=s=>{!s||s.discarded||s.done||(s.discarded=!0,t===s&&(t=null),i.cancel(s.requestId),s.resolve({requestId:s.requestId,code:"discarded",message:"Candidate discarded"}))};return{request(s,a,v=null,h=null){let o=Oe(a);t&&r(t);let m=n(),l={requestId:m,discarded:!1,done:!1};l.promise=new Promise(u=>{l.resolve=u}),t=l;let e={protocol:"blockeditor-tool/1",requestId:m,prompt:s,context:o,target:v,current:h};l.request=e;let f=u=>{if(!(l.discarded||l.done||u?.requestId!==m))if(l.done=!0,t===l&&(t=null),u?.artifact!==void 0){let g=F(u.artifact),d=U(u.state),p=g.ok?d.ok?null:d:g;l.resolve(p?{requestId:m,code:p.code,message:p.code}:u)}else l.resolve(typeof u?.code=="string"?u:{requestId:m,code:"invalid-result",message:"invalid-result"})};try{let u=g=>f({requestId:m,code:typeof g?.code=="string"?g.code:"transport-error",message:String(g?.message??g)});Promise.resolve(i.request(e)).then(f,u)}catch(u){f({requestId:m,code:typeof u?.code=="string"?u.code:"transport-error",message:String(u?.message??u)})}return l},discard:r,async wait(s,{signal:a}={}){if(a?.aborted)throw new DOMException("Aborted","AbortError");let v,h=await(a?Promise.race([s.promise,new Promise((o,m)=>{v=()=>m(new DOMException("Aborted","AbortError")),a.addEventListener("abort",v,{once:!0})})]).finally(()=>a.removeEventListener("abort",v)):s.promise);if(h?.code)throw new G(h.code,h.message);return h}}}var J=class extends Error{constructor(n){super(n),this.name="ToolTransportError",this.code=n}};function ye({getWire:i=()=>globalThis.window?.clay?.wire??null}={}){let n=new Map;return{request(t,{onStatus:r=null}={}){let s=i();if(!s||typeof s.send!="function")return Promise.reject(new J("no-wire"));let a=t?.requestId,v;try{v=s.send(t,{helper:"blockeditor-tool",document:"none",id:a,onStatus:r})}catch{return Promise.reject(new J("no-wire"))}return n.set(a,v),Promise.resolve(v.done).then(h=>{if(n.get(a)===v&&n.delete(a),h?.state==="done"){let o=h.result??{};return{requestId:typeof o.requestId=="string"?o.requestId:a,artifact:o.artifact,state:o.state,model:o.model}}return{requestId:a,code:h?.errorCode||(h?.state==="cancelled"?"cancelled":"transport-error"),message:h?.error||"the helper reported an error"}},()=>({requestId:a,code:"transport-error",message:"the helper reported an error"}))},cancel(t){let r=n.get(t);n.delete(t),r?.cancel?.()}}}var{Selection:Be}=V,W="This page is not open for editing any more.",Ie="AI tool making isn't available on this page right now.",Te="This document can't save tool data.",K="The place for this tool moved. Close this and run /ai where you want the tool.",be="This tool changed while you were revising, so nothing was replaced. Ask again.",Q="AI did not make a usable tool. Try again.",Ne="The tool data from AI is too large or not usable. Try again.",xe="This tool's data changed while AI was working, so it was not replaced. Ask again to include the latest data.",Ae="The tool could not be saved, so it was not added. Try again.",Re="Your tool is in the document, but saving failed. It will be saved with your next edit.";function _(i,n){let t=null;return i.forEach((r,s,a)=>{r.attrs.id===n&&(t={node:r,at:s,index:a})}),t}function Pe(i,n){let t=i.selection.$head,r=Math.min(Math.max(t.index(0),0),i.doc.childCount-1);return{hostId:i.doc.child(r)?.attrs.id??null,slashText:n?i.doc.textBetween(n.from,n.to):null,slashOffset:n&&t.depth?n.from-t.before(1)-1:null}}function Z(i,n){let t=n?.hostId?_(i.doc,n.hostId):null;if(!t)return null;let r=i.doc.maybeChild(t.index+1),s=t.node.isTextblock&&(t.node.content.size===0||t.node.textContent===n.slashText);return{...t,replace:s,pos:s?t.node.attrs.pos:oe(t.node.attrs.pos,r?.attrs.pos??null),insertAt:s?t.at:t.at+t.node.nodeSize}}function _e(i,n,t){let r=i.state,s=Z(r,t);if(!s)return!1;let{node:a,at:v,insertAt:h,replace:o}=s,m=N.nodes.tool.create({id:n.id,pos:s.pos,parent:a.attrs.parent??null,artifact:n.artifact,rev:n.rev,state:n.state}),l=r.tr;if(!o&&t?.hostId===a.attrs.id&&t.slashText&&t.slashOffset>=0){let f=v+1+t.slashOffset,u=f+t.slashText.length;u<=v+a.nodeSize-1&&r.doc.textBetween(f,u)===t.slashText&&l.delete(f,u)}let e=l.mapping.map(h);return l.replaceWith(e,o?l.mapping.map(v+a.nodeSize):e,m),l.setSelection(Be.near(l.doc.resolve(Math.min(e+m.nodeSize,l.doc.content.size)))),i.dispatch(X(l).scrollIntoView()),!0}var Se=()=>({x:0,y:0,left:0,top:0,right:0,bottom:0,width:0,height:0});function Ee({getView:i,store:n=()=>null,acceptState:t=()=>globalThis.clay?.save?.flush?.(),newId:r=se,transport:s=ye()}={}){let a=()=>{let e=i();return e&&!e.isDestroyed?e:null},v=()=>typeof n=="function"?n():n,h=(e,f)=>{let u=v()?.data?.[e]?.[f];return u===void 0?{}:u},o=new Map,m=e=>Array.isArray(e)?`[${e.map(m).join(",")}]`:e&&typeof e=="object"?`{${Object.keys(e).sort().map(u=>`${JSON.stringify(u)}:${m(e[u])}`).join(",")}}`:JSON.stringify(e)??"null";function l(e=null,f=null){let u=a(),g=e||!u?null:Pe(u.state,f),d=null,p=ve({transport:{request:c=>s.request(c,{onStatus:T=>d?.(T)}),cancel:c=>s.cancel(c)}}),b=null,w=null,y=null,M=!1,k=null,O=null,C=()=>{y?.host?.dispose(),y=null},L=()=>{let c=a();return c&&e?ie.get(c)?.get(e)??null:null},j=()=>L()?.suspend(),B=()=>L()?.resume(),q=c=>{M=!1;let T=a();return C(),T&&R(T),B(),{status:"failed",message:c}},ne={aiTarget:!0,label:e?"This tool":"New tool",ref:e?[e]:[],placeholder:e?"What should change?":"Describe the tool",get isConnected(){let c=a();return c?e?!!_(c.state.doc,e):!0:!1},getBoundingClientRect(){let c=a();if(!c)return Se();if(y)return y.dom.getBoundingClientRect();let T=e??g?.hostId,A=T?_(c.state.doc,T):null,E=A?c.nodeDOM(A.at):null;return E&&typeof E.getBoundingClientRect=="function"?E.getBoundingClientRect():Se()},async start(c){w=null,M=!1;let T=a();if(!T)return{status:"refused",code:"gone",message:W};if(!globalThis.window?.clay?.wire)return{status:"refused",code:"no-wire",message:Ie};let A=null,E=null;if(e){let x=_(T.state.doc,e);if(x?.node.type!==N.nodes.tool)return{status:"refused",code:"gone",message:W};k=x.node.attrs.rev,A={toolId:e,rev:k},j(),E={artifact:x.node.attrs.artifact,state:h(e,k)},O=m(E.state)}return b=p.request(c,fe(T.state.doc,T.dom.ownerDocument.title),A,E),{status:"ok",id:b.requestId,send:(x={})=>(d=typeof x.onStatus=="function"?x.onStatus:null,{done:p.wait(b).then(S=>(w={id:e,rev:null,artifact:S.artifact,state:S.state},{state:"done",result:S}),S=>(B(),{state:"error",error:S?.message||S?.code||"the helper reported an error",code:S?.code??null})),cancel:()=>{B(),p.discard(b)}})}},async propose(c){let T=a();if(!T||!c)return{status:"refused",message:W};if(!F(c.artifact).ok)return{status:"refused",message:Q};if(!U(c.state).ok)return{status:"refused",message:Ne};w={id:e,rev:null,artifact:c.artifact,state:c.state};let x=De(T);return x.status!=="ready"&&(w=null),x},async keep(){if(!w||M)return q(be);let c=a();if(!c)return q(W);let T=v();if(!T)return q(Te);let A=()=>e&&O!==null&&m(h(e,k))!==O;if(A())return q(xe);M=!0;let E=w.id??r("b"),x=r("rev"),I={...w,id:E,rev:x};try{await T.set([E,x],I.state)}catch(D){return q(D?.message??Te)}let S=null;try{S=await t()}catch{return q(Ae)}if(S?.ok!==!0&&!["saved","clean"].includes(S?.state))return q(S?.msg??S?.message??Ae);if(e){let D=_(c.state.doc,e);if(D?.node.type!==N.nodes.tool||D.node.attrs.rev!==k)return q(be)}else if(!Z(c.state,g))return q(K);if(A())return q(xe);if(C(),R(c),e){let D=_(c.state.doc,e);c.dispatch(X(c.state.tr.setNodeMarkup(D.at,null,{...D.node.attrs,artifact:I.artifact,rev:I.rev})))}else if(!_e(c,I,g))return q(K);let P=!1;for(let D=0;D<2&&!P;D++)try{P=(await t())?.ok!==!1}catch{P=!1}return P?(o.delete(e??"new"),{status:"kept"}):{status:"failed",message:Re}},discard(){C();let c=a();c&&R(c),p.discard(b),B(),o.delete(e??"new")}};function De(c){C();let T=ue({mode:"view",tables:()=>de(c.state.doc).map(({id:I,cols:S,rows:P})=>({id:I,cols:S,rows:P}))}),A=c.dom.ownerDocument.createElement("div");A.className="blockeditor-ai-preview";let E=null;try{E=T.mount(A,{id:"preview",rev:"preview",artifact:w.artifact,seed:w.state})}catch{return T.dispose(),{status:"refused",message:Q}}if(E.failed)return T.dispose(),{status:"refused",message:Q};if(y={host:T,dom:A},e)return $(c,{ids:[e],dom:A}),{status:"ready"};let x=Z(c.state,g);return x?(x.replace?$(c,{ids:[x.node.attrs.id],dom:A}):ae(c,{at:x.insertAt,dom:A}),{status:"ready"}):(C(),{status:"refused",message:K})}return e&&o.set(e,ne),ne}return{newTool(e=null){return l(null,e)},reviseTool(e){let f=o.get(e);return f?.isConnected?f:(o.delete(e),l(e))}}}var{TextSelection:$e}=V,ze="ai-edit",Le="page area",je="This section is too large for AI editing. Select a smaller part.",Ce="Someone changed this area while AI was working, so nothing was changed.",Ve="This page is not open for editing any more.",Fe="AI editing isn't available on this page right now.",Ue=0;function te(i,n){let t=null;return i.forEach((r,s)=>{r.attrs?.id===n&&(t={node:r,at:s})}),t}var qe=(i,n)=>te(i,n)?.node?.type===N.nodes.tool,ee=(i,n,t)=>i.slice(n,t+1).map(r=>r.node.attrs.id).filter(Boolean),Ge=()=>globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,ke=()=>({x:0,y:0,left:0,top:0,right:0,bottom:0,width:0,height:0});function Je(i){if(!i.length)return ke();let n=Math.min(...i.map(a=>a.left)),t=Math.min(...i.map(a=>a.top)),r=Math.max(...i.map(a=>a.right)),s=Math.max(...i.map(a=>a.bottom));return{x:n,y:t,left:n,top:t,right:r,bottom:s,width:r-n,height:s-t}}function We(i,n,t){let r=i.selection;if(!(r instanceof $e)||r.empty)return null;let[s,a]=ce(i.doc,r,n);if(s!==a||t.lo!==s||t.hi!==s)return null;let v=n[s];if(r.from<v.at||r.to>v.end)return null;let h=i.doc.textBetween(r.from,r.to," ");if(!h.trim())return null;let o=i.doc.textBetween(v.at+1,r.from," ").length;return{text:h,start:o,end:o+h.length}}function Tt({getView:i,store:n=()=>null,acceptState:t}={}){let r=()=>{let o=i();return o&&!o.isDestroyed?o:null},s=new Map,a=Ee({getView:r,store:n,acceptState:t}),v=o=>a.reviseTool(o);function h(o,{quote:m=null,label:l=null}={}){for(let[d,p]of s)p.isConnected||s.delete(d);let e=s.get(o.join(","));if(e)return e.quote=m??void 0,e;let f=null,u=null,g={aiTarget:!0,label:l??(o.length===1?"This block":`${o.length} blocks`),ref:[...o],get isConnected(){let d=r();return!!d&&o.some(p=>te(d.state.doc,p))},getBoundingClientRect(){let d=r();if(!d)return ke();let p=d.dom.querySelector(".blockeditor-ai-preview");if(p)return p.getBoundingClientRect();let w=[g.ref[0],g.ref[g.ref.length-1]].map(y=>te(d.state.doc,y)).map(y=>y?d.nodeDOM(y.at):null).filter(y=>y&&typeof y.getBoundingClientRect=="function").map(y=>y.getBoundingClientRect());return Je(w)},async start(d,p){let b=r();if(!b)return{status:"refused",code:"gone",message:Ve};let w=window.clay?.wire;if(!w)return{status:"refused",code:"no-wire",message:Fe};let{captureArea:y,AREA_GUIDE:M}=await import("./c-SFZRY6RT.js"),k=y(b.state.doc,g.ref);if(f=null,u=null,k.status!=="ok")return{status:"refused",code:k.code,message:k.message};let O=p??g.quote,C={id:"req-"+Date.now().toString(36)+"-"+ ++Ue,editId:Le,tag:"div",elementHTML:k.capture.html,comment:d+`
2
2
 
3
- `+M,contextRefs:pe(d)};return O&&(C.quote=O.text,Number.isInteger(O.start)&&(C.selection={start:O.start,end:O.end})),he(d)&&(C.page=!0),new Blob([JSON.stringify(C)]).size>921600?{status:"refused",code:"too-large",message:je}:(f=k.capture,{status:"ok",id:C.id,send:(L={})=>{let j=!0,B=null;return{done:(async()=>(C.page&&await window.clay?.save?.(),j?(B=w.send(C,{helper:ze,onStatus:L.onStatus}),B.done):{state:"cancelled"}))(),cancel(){j=!1,B?.cancel()}}}})},async propose(d){let p=r();if(!p||!f)return{status:"refused",message:"This area is no longer open for AI editing."};let{proposeArea:b}=await import("./c-47IBJGPQ.js"),w=b(p.state,f,d?.html??"",{seed:Ge()});if(w.status!=="ready")return{status:"refused",message:w.message};u=w;let y=p.dom.ownerDocument.createElement("div");y.className="blockeditor-ai-preview";let M=H.DOMSerializer.fromSchema(N);return y.appendChild(M.serializeFragment(H.Fragment.from(w.nodes),{document:p.dom.ownerDocument})),$(p,{ids:f.ids,dom:y}),{status:"ready"}},async keep(){let d=r();if(!d||!f||!u)return{status:"failed",message:Ce};let{keepAreaTransaction:p}=await import("./c-47IBJGPQ.js"),b=p(d.state,f,u);if(R(d),b.status!=="ok")return{status:"failed",message:Ce};d.dispatch(b.tr),d.dom.isConnected&&d.focus();try{await window.clay?.save?.flush?.()}catch{return{status:"failed",message:"Your change is in the document, but saving failed. It will be saved with your next edit."}}return{status:"kept"}},discard(){let d=r();d&&(R(d),d.dom.isConnected&&d.focus())}};return g.quote=m??void 0,s.set(o.join(","),g),g}return{active:()=>!!r(),targetFromSelection(){let o=r();if(!o)return null;let m=z(o.state.doc);if(!m.length)return null;let l=le(o.state,m),e=ee(m,l.lo,l.hi);return e.length?e.length===1&&qe(o.state.doc,e[0])?v(e[0]):h(e,{quote:We(o.state,m,l)}):null},targetAt(o,m){let l=r();if(!l)return null;let e=l.posAtCoords({left:o,top:m});if(!e)return null;let f=z(l.state.doc);if(!f.length)return null;let u=e.inside>=0?e.inside:e.pos,g=f.findIndex(y=>y.node.type===N.nodes.tool&&y.end===u),d=g>=0?g:Math.min(Math.max(l.state.doc.resolve(u).index(0),0),f.length-1),{lo:p,hi:b}=Y(f,d,d),w=ee(f,p,b);return w.length?w.length===1&&qe(l.state.doc,w[0])?v(w[0]):h(w):null},between(o,m){let l=r();if(!l)return null;let e=z(l.state.doc),f=[...o?.ref??[],...m?.ref??[]].map(p=>e.findIndex(b=>b.node.attrs.id===p)).filter(p=>p>=0);if(!f.length)return null;let{lo:u,hi:g}=Y(e,Math.min(...f),Math.max(...f)),d=ee(e,u,g);return d.length?h(d):null},wholePage(){let o=r(),m=o?z(o.state.doc).map(l=>l.node.attrs.id).filter(Boolean):[];return h(m,{label:"This page"})},newTool(o){return a.newTool(o??null)},reviseTool(o){return a.reviseTool(o)}}}export{Tt as createPageAi};
3
+ `+M,contextRefs:pe(d)};return O&&(C.quote=O.text,Number.isInteger(O.start)&&(C.selection={start:O.start,end:O.end})),he(d)&&(C.page=!0),new Blob([JSON.stringify(C)]).size>921600?{status:"refused",code:"too-large",message:je}:(f=k.capture,{status:"ok",id:C.id,send:(L={})=>{let j=!0,B=null;return{done:(async()=>(C.page&&await window.clay?.save?.(),j?(B=w.send(C,{helper:ze,onStatus:L.onStatus}),B.done):{state:"cancelled"}))(),cancel(){j=!1,B?.cancel()}}}})},async propose(d){let p=r();if(!p||!f)return{status:"refused",message:"This area is no longer open for AI editing."};let{proposeArea:b}=await import("./c-SFZRY6RT.js"),w=b(p.state,f,d?.html??"",{seed:Ge()});if(w.status!=="ready")return{status:"refused",message:w.message};u=w;let y=p.dom.ownerDocument.createElement("div");y.className="blockeditor-ai-preview";let M=H.DOMSerializer.fromSchema(N);return y.appendChild(M.serializeFragment(H.Fragment.from(w.nodes),{document:p.dom.ownerDocument})),$(p,{ids:f.ids,dom:y}),{status:"ready"}},async keep(){let d=r();if(!d||!f||!u)return{status:"failed",message:Ce};let{keepAreaTransaction:p}=await import("./c-SFZRY6RT.js"),b=p(d.state,f,u);if(R(d),b.status!=="ok")return{status:"failed",message:Ce};d.dispatch(b.tr),d.dom.isConnected&&d.focus();try{await window.clay?.save?.flush?.()}catch{return{status:"failed",message:"Your change is in the document, but saving failed. It will be saved with your next edit."}}return{status:"kept"}},discard(){let d=r();d&&(R(d),d.dom.isConnected&&d.focus())}};return g.quote=m??void 0,s.set(o.join(","),g),g}return{active:()=>!!r(),targetFromSelection(){let o=r();if(!o)return null;let m=z(o.state.doc);if(!m.length)return null;let l=le(o.state,m),e=ee(m,l.lo,l.hi);return e.length?e.length===1&&qe(o.state.doc,e[0])?v(e[0]):h(e,{quote:We(o.state,m,l)}):null},targetAt(o,m){let l=r();if(!l)return null;let e=l.posAtCoords({left:o,top:m});if(!e)return null;let f=z(l.state.doc);if(!f.length)return null;let u=e.inside>=0?e.inside:e.pos,g=f.findIndex(y=>y.node.type===N.nodes.tool&&y.end===u),d=g>=0?g:Math.min(Math.max(l.state.doc.resolve(u).index(0),0),f.length-1),{lo:p,hi:b}=Y(f,d,d),w=ee(f,p,b);return w.length?w.length===1&&qe(l.state.doc,w[0])?v(w[0]):h(w):null},between(o,m){let l=r();if(!l)return null;let e=z(l.state.doc),f=[...o?.ref??[],...m?.ref??[]].map(p=>e.findIndex(b=>b.node.attrs.id===p)).filter(p=>p>=0);if(!f.length)return null;let{lo:u,hi:g}=Y(e,Math.min(...f),Math.max(...f)),d=ee(e,u,g);return d.length?h(d):null},wholePage(){let o=r(),m=o?z(o.state.doc).map(l=>l.node.attrs.id).filter(Boolean):[];return h(m,{label:"This page"})},newTool(o){return a.newTool(o??null)},reviseTool(o){return a.reviseTool(o)}}}export{Tt as createPageAi};
@@ -1 +1 @@
1
- import{a,b,c,d,e,f,g,h,i,j,k}from"./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-WRBKEJD4.js";import"./c-VHNSBD2M.js";export{i as hostActions,d as hostMeta,c as hostMetaOrder,a as hostMetaOutcome,b as hostMetaPath,f as hostPageFormat,g as hostPageStateHref,e as hostSupports,h as hostVersions,k as querySaveOutcome,j as resetHostMeta};
1
+ import{a,b,c,d,e,f,g,h,i,j,k}from"./c-EQ5NBOGA.js";import"./c-C7SUMNMI.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-U4TWEIKZ.js";import"./c-HA6INT6J.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";export{i as hostActions,d as hostMeta,c as hostMetaOrder,a as hostMetaOutcome,b as hostMetaPath,f as hostPageFormat,g as hostPageStateHref,e as hostSupports,h as hostVersions,k as querySaveOutcome,j as resetHostMeta};
@@ -1 +1 @@
1
- import{a as d}from"./c-LA2BW7UY.js";import{b as A,k as c}from"./c-HA6INT6J.js";import{i as s}from"./c-ICMAOOGK.js";import{a as v}from"./c-VHNSBD2M.js";var O={};v(O,{CONTROLLED_SELECTOR:()=>m,authoredAttr:()=>b,canonicalContentEditable:()=>x,canonicalContentEditableValue:()=>E,captureAll:()=>h,captureAuthored:()=>u,captureFrozen:()=>p,frozenOriginal:()=>L,restoreAuthoredOrder:()=>T});var m="[editmode\\:contenteditable], [editmode\\:onclick], [viewmode\\:disabled], [viewmode\\:readonly]",l=new WeakMap,f=new WeakMap;function u(e){let t=l.get(e);if(!t){let r=e.getAttributeNames(),n={};for(let i of r)n[i]=e.getAttribute(i);t={order:r,values:n},l.set(e,t)}return t}function b(e,t){if(!e)return null;let{values:r}=u(e);return t in r?r[t]:null}function T(e,t=e){let r=l.get(t);if(!r)return;let n=e.getAttributeNames(),i=[...r.order.filter(o=>n.includes(o)),...n.filter(o=>!r.order.includes(o))];if(i.every((o,a)=>o===n[a]))return;let g=i.map(o=>[o,e.getAttribute(o)]);for(let o of n)e.removeAttribute(o);for(let[o,a]of g)e.setAttribute(o,a)}function E(e){return e.getAttribute("contenteditable")??e.getAttribute("inert-contenteditable")??b(e,"inert-contenteditable")??b(e,"contenteditable")??"true"}function x(e){e.setAttribute("inert-contenteditable",E(e)),e.removeAttribute("contenteditable")}function y(e){let t=e.innerHTML;if(!e.querySelector(`[${c}]`)&&!t.includes("ephemeral")&&!t.includes("<dialog"))return t;let r=e.cloneNode(!0);for(let n of r.querySelectorAll(`[${c}]`))n.removeAttribute(c);for(let n of r.children)A(n);return r.innerHTML}function p(e){f.has(e)||f.set(e,y(e))}function L(e){return f.get(e)}function h(){for(let e of document.querySelectorAll(m))u(e);for(let e of document.querySelectorAll(s))p(e)}h();d.onAddElement({selectorFilter:m,require:"observed",pausable:!1,debounce:0},e=>{e.forEach(({element:t})=>u(t))});d.onAddElement({selectorFilter:s,require:"observed",pausable:!1,debounce:0},e=>{e.forEach(({element:t})=>p(t))});export{u as a,b,T as c,x as d,L as e,h as f,O as g};
1
+ import{a as d}from"./c-MZCOGNZL.js";import{b as A,k as c}from"./c-HA6INT6J.js";import{i as s}from"./c-ICMAOOGK.js";import{a as v}from"./c-VHNSBD2M.js";var O={};v(O,{CONTROLLED_SELECTOR:()=>m,authoredAttr:()=>b,canonicalContentEditable:()=>x,canonicalContentEditableValue:()=>E,captureAll:()=>h,captureAuthored:()=>u,captureFrozen:()=>p,frozenOriginal:()=>L,restoreAuthoredOrder:()=>T});var m="[editmode\\:contenteditable], [editmode\\:onclick], [viewmode\\:disabled], [viewmode\\:readonly]",l=new WeakMap,f=new WeakMap;function u(e){let t=l.get(e);if(!t){let r=e.getAttributeNames(),n={};for(let i of r)n[i]=e.getAttribute(i);t={order:r,values:n},l.set(e,t)}return t}function b(e,t){if(!e)return null;let{values:r}=u(e);return t in r?r[t]:null}function T(e,t=e){let r=l.get(t);if(!r)return;let n=e.getAttributeNames(),i=[...r.order.filter(o=>n.includes(o)),...n.filter(o=>!r.order.includes(o))];if(i.every((o,a)=>o===n[a]))return;let g=i.map(o=>[o,e.getAttribute(o)]);for(let o of n)e.removeAttribute(o);for(let[o,a]of g)e.setAttribute(o,a)}function E(e){return e.getAttribute("contenteditable")??e.getAttribute("inert-contenteditable")??b(e,"inert-contenteditable")??b(e,"contenteditable")??"true"}function x(e){e.setAttribute("inert-contenteditable",E(e)),e.removeAttribute("contenteditable")}function y(e){let t=e.innerHTML;if(!e.querySelector(`[${c}]`)&&!t.includes("ephemeral")&&!t.includes("<dialog"))return t;let r=e.cloneNode(!0);for(let n of r.querySelectorAll(`[${c}]`))n.removeAttribute(c);for(let n of r.children)A(n);return r.innerHTML}function p(e){f.has(e)||f.set(e,y(e))}function L(e){return f.get(e)}function h(){for(let e of document.querySelectorAll(m))u(e);for(let e of document.querySelectorAll(s))p(e)}h();d.onAddElement({selectorFilter:m,require:"observed",pausable:!1,debounce:0},e=>{e.forEach(({element:t})=>u(t))});d.onAddElement({selectorFilter:s,require:"observed",pausable:!1,debounce:0},e=>{e.forEach(({element:t})=>p(t))});export{u as a,b,T as c,x as d,L as e,h as f,O as g};
@@ -1 +1 @@
1
- import{d as m}from"./c-QQFHEODI.js";import{f as l}from"./c-EDE45NM7.js";var _=window.__clayWorkspaceBackground===!0;document.addEventListener("clay:workspace-background",()=>{_=!0});document.addEventListener("clay:workspace-foreground",()=>{_=!1});var c=()=>document.hidden||_,y=class extends EventTarget{constructor(e,{shared:s=!1,sharedData:i=!1,documentURL:n,lane:o,clientId:h,startupCheck:t=!1,keepAliveWhenHidden:a=!1,workerFeatures:d=["live-data"]}={}){super(),this.url=e,this.readyState=0,this.onopen=null,this.onmessage=null,this.onerror=null,this._shared=s&&typeof SharedWorker=="function"&&(!i||o==="live"),this._sharedData=i,this._documentURL=n,this._lane=o,this._clientId=h,this._keepAliveWhenHidden=a,this._workerFeatures=d,this._since=0,this._closed=!1,this._suspended=!1,this._repair=!1,this._startup=t,this._worker=null,this._source=null,this._visibility=()=>{clearTimeout(this._hiddenTimer),c()?(this._worker&&this._postWorker(this._worker,"hidden"),this._keepHidden()||(this._hiddenTimer=setTimeout(()=>this._suspend(),5e3))):this._suspended?this._resume():this._worker&&this._postWorker(this._worker,"visible")},this._pagehide=()=>this._suspend(!0),this._pageshow=()=>{(!c()||this._keepHidden())&&this._resume()},document.addEventListener("visibilitychange",this._visibility),document.addEventListener("clay:workspace-background",this._visibility),document.addEventListener("clay:workspace-foreground",this._visibility),window.addEventListener("pagehide",this._pagehide),window.addEventListener("pageshow",this._pageshow),this._open(),c()&&this._visibility()}_emit(e,s){if(this._closed)return;let i=s===void 0?new Event(e):new MessageEvent(e,{data:s});this.dispatchEvent(i),this[`on${e}`]?.(i)}_postWorker(e,s,i={}){e.port.postMessage({v:this._sharedData?2:1,type:s,...i})}_open(){if(!(this._closed||this._suspended)){if(this.readyState=0,!this._shared)return this._openDirect();try{let e=new SharedWorker(new URL(this._sharedData?"/_/sync/data-worker.js":"/_/sync/worker.js",window.location.origin).href,this._sharedData?"clay-sync-data":"clay-sync");this._worker=e;let s=Date.now(),i=!1;e.onerror=()=>{this._worker===e&&(this._shared=!1,this._repair=!0,this._reopen(),c()&&this._visibility())},this._startTimer=setTimeout(e.onerror,5e3),e.port.onmessage=({data:t})=>{if(!(this._worker!==e||t?.v!==(this._sharedData?2:1))){if(this._sharedData){if(t.type==="unsupported"||t.type==="capacity"){e.onerror();return}if(t.type==="gone"){this.readyState=2,this._emit("error"),this.close();return}if(!i){if(t.type!=="hello")return;if(!Array.isArray(t.features)||!this._workerFeatures.every(a=>t.features.includes(a))){e.onerror();return}i=!0,clearTimeout(this._startTimer),s=Date.now();return}if(t.type==="hello")return}if(s=Date.now(),!this._sharedData&&["status","pong","cursor","frame","gone"].includes(t.type)&&clearTimeout(this._startTimer),t.type==="status")t.state==="open"?(!this._sharedData||this.readyState!==1)&&(this.readyState=1,this._emit("open")):t.state==="connecting"&&(this.readyState=0,this._emit("error"));else if(t.type==="cursor"){clearTimeout(this._startTimer),Number.isSafeInteger(t.seq)&&(this._since=Math.max(this._since,t.seq));let a=t.resync===!0||this._repair,d=this._startup;this._repair=!1,this._startup=!1,this._emit("cursor",JSON.stringify({...t,resync:a,startup:d}))}else if(t.type==="frame"&&typeof t.data=="string")this._remember(t.data),this._emit("message",t.data);else if(this._sharedData&&t.type==="event"&&["data","data-state","data-writer","presence"].includes(t.event)&&t.data!==null&&typeof t.data=="object"&&!Array.isArray(t.data))try{this._emit(t.event,JSON.stringify(t.data))}catch{}else t.type==="gone"&&(this.readyState=2,this._emit("error"),this.close())}},e.port.start(),this._postWorker(e,c()?"hidden":"visible");let n={document:this._documentURL,lane:this._lane,since:this._since};this._sharedData&&this._lane==="live"&&(n.clientId=this._clientId),this._postWorker(e,"subscribe",n);let o=0,h=Date.now();this._pingTimer=setInterval(()=>{if(this._worker!==e)return;let t=Date.now(),a=t-h>15e3*6;if(h=t,s>=o&&(o=0),a||o&&t-o>=15e3*3){this._repair=!0,this._reopen();return}o||(o=t),this._postWorker(e,"ping")},15e3)}catch{this._shared=!1,this._reopen(),c()&&this._visibility()}}}_openDirect(){let e=new EventSource(this.url);this._source=e;let s=!1,i=!1;e.onopen=()=>{if(this._source===e&&(s&&!i&&(this._repair=!0),s=!0,this.readyState=1,this._emit("open"),this._repair||this._startup)){let n=this._repair,o=this._startup;this._repair=!1,this._startup=!1,this._emit("cursor",JSON.stringify({resync:n,startup:o}))}},e.onerror=()=>{this._source===e&&(this.readyState=e.readyState,this._emit("error"))},e.onmessage=n=>{this._source===e&&(this._remember(n.data),this._emit("message",n.data))};for(let n of["cursor","presence","data","data-state","data-writer"])e.addEventListener(n,o=>{this._source===e&&(n==="cursor"&&(i=!0),this._emit(n,o.data))})}_remember(e){try{let{seq:s}=JSON.parse(e);Number.isSafeInteger(s)&&(this._since=Math.max(this._since,s))}catch{}}_disconnect(){if(clearTimeout(this._startTimer),clearInterval(this._pingTimer),this._worker){let e=this._worker;this._worker=null,e.onerror=null,e.port.onmessage=null;try{this._postWorker(e,"unsubscribe")}catch{}e.port.close()}this._source&&(this._source.close(),this._source=null)}_keepHidden(){return this._keepAliveWhenHidden===!0||this._keepAliveWhenHidden==="shared"&&this._shared}_reopen(){let e=(this._sharedData||this._keepAliveWhenHidden===!0)&&this.readyState===1;this.readyState=0,e&&this._emit("error"),this._disconnect(),this._open()}_suspend(e=!1){clearTimeout(this._hiddenTimer),!(this._closed||this._suspended)&&(this._suspended=!0,this._repair=!0,this.readyState=0,e&&this._keepAliveWhenHidden===!0&&this._emit("error"),this._disconnect())}_resume(){clearTimeout(this._hiddenTimer),!(this._closed||!this._suspended)&&(this._suspended=!1,this._open())}close(){this._closed=!0,this.readyState=2,clearTimeout(this._hiddenTimer),this._disconnect(),document.removeEventListener("visibilitychange",this._visibility),document.removeEventListener("clay:workspace-background",this._visibility),document.removeEventListener("clay:workspace-foreground",this._visibility),window.removeEventListener("pagehide",this._pagehide),window.removeEventListener("pageshow",this._pageshow)}};var v="This document was upgraded.",u=!1;function p(r,e){let s=r.querySelector(`meta[name="${e}"]`),i=s?s.getAttribute("content"):null;return i&&i.trim()?i.trim():null}function g(r=document){return p(r,"hyper-version")}function k(r){return typeof r!="string"||!r.includes("hyper-version")?null:p(new DOMParser().parseFromString(r,"text/html"),"hyper-version")}function w(r){let e=g();return!!e&&!!r&&r!==e}function S(r){return u?!0:w(k(r))}function D(r){return u?!0:!r||typeof r.querySelector!="function"?!1:w(p(r,"hyper-version"))}function b(){if(u)return Promise.resolve();u=!0;let r=l?import("./core/save-6HT2LABE.js").then(i=>i.holdAllSaves(v),()=>{}):Promise.resolve(),e=new CustomEvent("clay:document-upgraded",{detail:{message:v}}),s=l?Promise.resolve():import("./c-42ZNV7LI.js").then(i=>i.start(e),()=>{});return document.dispatchEvent(e),Promise.all([r,s]).then(()=>{})}var f={spec:{name:"spec",relayPath:"/_/sync",documentHeader:"Document-URL",snapshotKey:"snapshot",streamPath:(r,e,s,i)=>`/_/sync?document-url=${encodeURIComponent(r)}&lane=${e}&resume-id=${s}&client-id=${encodeURIComponent(i)}`},legacy:{name:"legacy",relayPath:"/_/live-sync/save",documentHeader:"Page-URL",snapshotKey:"html",streamPath:(r,e,s,i)=>`/_/live-sync/stream?page-url=${encodeURIComponent(r)}&lane=${e}&resume-id=${s}&client-id=${encodeURIComponent(i)}`}};function A(){return m().then(r=>{let e=r?.extensions||[],s=e.includes("sync"),i=e.includes("live-data"),n=e.includes("presence"),o=s&&i&&e.includes("sync-worker-data"),h=s&&(o||e.includes("sync-worker")&&!i&&!n);return{profile:s?f.spec:f.legacy,sharedSync:h,sharedData:o,liveData:i,workerFeatures:n?["live-data","presence"]:["live-data"]}}).catch(()=>({profile:f.legacy,sharedSync:!1,sharedData:!1,liveData:!1,workerFeatures:["live-data"]}))}export{c as a,y as b,S as c,D as d,b as e,f,A as g};
1
+ import{d as m}from"./c-EQ5NBOGA.js";import{f as l}from"./c-C7SUMNMI.js";var _=window.__clayWorkspaceBackground===!0;document.addEventListener("clay:workspace-background",()=>{_=!0});document.addEventListener("clay:workspace-foreground",()=>{_=!1});var c=()=>document.hidden||_,y=class extends EventTarget{constructor(e,{shared:s=!1,sharedData:r=!1,documentURL:n,lane:o,clientId:h,startupCheck:t=!1,keepAliveWhenHidden:a=!1,workerFeatures:d=["live-data"]}={}){super(),this.url=e,this.readyState=0,this.onopen=null,this.onmessage=null,this.onerror=null,this._shared=s&&typeof SharedWorker=="function"&&(!r||o==="live"),this._sharedData=r,this._documentURL=n,this._lane=o,this._clientId=h,this._keepAliveWhenHidden=a,this._workerFeatures=d,this._since=0,this._closed=!1,this._suspended=!1,this._repair=!1,this._startup=t,this._worker=null,this._source=null,this._visibility=()=>{clearTimeout(this._hiddenTimer),c()?(this._worker&&this._postWorker(this._worker,"hidden"),this._keepHidden()||(this._hiddenTimer=setTimeout(()=>this._suspend(),5e3))):this._suspended?this._resume():this._worker&&this._postWorker(this._worker,"visible")},this._pagehide=()=>this._suspend(!0),this._pageshow=()=>{(!c()||this._keepHidden())&&this._resume()},document.addEventListener("visibilitychange",this._visibility),document.addEventListener("clay:workspace-background",this._visibility),document.addEventListener("clay:workspace-foreground",this._visibility),window.addEventListener("pagehide",this._pagehide),window.addEventListener("pageshow",this._pageshow),this._open(),c()&&this._visibility()}_emit(e,s){if(this._closed)return;let r=s===void 0?new Event(e):new MessageEvent(e,{data:s});this.dispatchEvent(r),this[`on${e}`]?.(r)}_postWorker(e,s,r={}){e.port.postMessage({v:this._sharedData?2:1,type:s,...r})}_open(){if(!(this._closed||this._suspended)){if(this.readyState=0,!this._shared)return this._openDirect();try{let e=new SharedWorker(new URL(this._sharedData?"/_/sync/data-worker.js":"/_/sync/worker.js",window.location.origin).href,this._sharedData?"clay-sync-data":"clay-sync");this._worker=e;let s=Date.now(),r=!1;e.onerror=()=>{this._worker===e&&(this._shared=!1,this._repair=!0,this._reopen(),c()&&this._visibility())},this._startTimer=setTimeout(e.onerror,5e3),e.port.onmessage=({data:t})=>{if(!(this._worker!==e||t?.v!==(this._sharedData?2:1))){if(this._sharedData){if(t.type==="unsupported"||t.type==="capacity"){e.onerror();return}if(t.type==="gone"){this.readyState=2,this._emit("error"),this.close();return}if(!r){if(t.type!=="hello")return;if(!Array.isArray(t.features)||!this._workerFeatures.every(a=>t.features.includes(a))){e.onerror();return}r=!0,clearTimeout(this._startTimer),s=Date.now();return}if(t.type==="hello")return}if(s=Date.now(),!this._sharedData&&["status","pong","cursor","frame","gone"].includes(t.type)&&clearTimeout(this._startTimer),t.type==="status")t.state==="open"?(!this._sharedData||this.readyState!==1)&&(this.readyState=1,this._emit("open")):t.state==="connecting"&&(this.readyState=0,this._emit("error"));else if(t.type==="cursor"){clearTimeout(this._startTimer),Number.isSafeInteger(t.seq)&&(this._since=Math.max(this._since,t.seq));let a=t.resync===!0||this._repair,d=this._startup;this._repair=!1,this._startup=!1,this._emit("cursor",JSON.stringify({...t,resync:a,startup:d}))}else if(t.type==="frame"&&typeof t.data=="string")this._remember(t.data),this._emit("message",t.data);else if(this._sharedData&&t.type==="event"&&["data","data-state","data-writer","presence"].includes(t.event)&&t.data!==null&&typeof t.data=="object"&&!Array.isArray(t.data))try{this._emit(t.event,JSON.stringify(t.data))}catch{}else t.type==="gone"&&(this.readyState=2,this._emit("error"),this.close())}},e.port.start(),this._postWorker(e,c()?"hidden":"visible");let n={document:this._documentURL,lane:this._lane,since:this._since};this._sharedData&&this._lane==="live"&&(n.clientId=this._clientId),this._postWorker(e,"subscribe",n);let o=0,h=Date.now();this._pingTimer=setInterval(()=>{if(this._worker!==e)return;let t=Date.now(),a=t-h>15e3*6;if(h=t,s>=o&&(o=0),a||o&&t-o>=15e3*3){this._repair=!0,this._reopen();return}o||(o=t),this._postWorker(e,"ping")},15e3)}catch{this._shared=!1,this._reopen(),c()&&this._visibility()}}}_openDirect(){let e=new EventSource(this.url);this._source=e;let s=!1,r=!1;e.onopen=()=>{if(this._source===e&&(s&&!r&&(this._repair=!0),s=!0,this.readyState=1,this._emit("open"),this._repair||this._startup)){let n=this._repair,o=this._startup;this._repair=!1,this._startup=!1,this._emit("cursor",JSON.stringify({resync:n,startup:o}))}},e.onerror=()=>{this._source===e&&(this.readyState=e.readyState,this._emit("error"))},e.onmessage=n=>{this._source===e&&(this._remember(n.data),this._emit("message",n.data))};for(let n of["cursor","presence","data","data-state","data-writer"])e.addEventListener(n,o=>{this._source===e&&(n==="cursor"&&(r=!0),this._emit(n,o.data))})}_remember(e){try{let{seq:s}=JSON.parse(e);Number.isSafeInteger(s)&&(this._since=Math.max(this._since,s))}catch{}}_disconnect(){if(clearTimeout(this._startTimer),clearInterval(this._pingTimer),this._worker){let e=this._worker;this._worker=null,e.onerror=null,e.port.onmessage=null;try{this._postWorker(e,"unsubscribe")}catch{}e.port.close()}this._source&&(this._source.close(),this._source=null)}_keepHidden(){return this._keepAliveWhenHidden===!0||this._keepAliveWhenHidden==="shared"&&this._shared}_reopen(){let e=(this._sharedData||this._keepAliveWhenHidden===!0)&&this.readyState===1;this.readyState=0,e&&this._emit("error"),this._disconnect(),this._open()}_suspend(e=!1){clearTimeout(this._hiddenTimer),!(this._closed||this._suspended)&&(this._suspended=!0,this._repair=!0,this.readyState=0,e&&this._keepAliveWhenHidden===!0&&this._emit("error"),this._disconnect())}_resume(){clearTimeout(this._hiddenTimer),!(this._closed||!this._suspended)&&(this._suspended=!1,this._open())}close(){this._closed=!0,this.readyState=2,clearTimeout(this._hiddenTimer),this._disconnect(),document.removeEventListener("visibilitychange",this._visibility),document.removeEventListener("clay:workspace-background",this._visibility),document.removeEventListener("clay:workspace-foreground",this._visibility),window.removeEventListener("pagehide",this._pagehide),window.removeEventListener("pageshow",this._pageshow)}};var v="This document was upgraded.",u=!1;function p(i,e){let s=i.querySelector(`meta[name="${e}"]`),r=s?s.getAttribute("content"):null;return r&&r.trim()?r.trim():null}function k(i=document){return p(i,"hyper-version")}function T(i){return typeof i!="string"||!i.includes("hyper-version")?null:p(new DOMParser().parseFromString(i,"text/html"),"hyper-version")}function w(i){let e=k();return!!e&&!!i&&i!==e}function D(i){return u?!0:w(T(i))}function b(i){return u?!0:!i||typeof i.querySelector!="function"?!1:w(p(i,"hyper-version"))}function L(){if(u)return Promise.resolve();u=!0;let i=l?import("./core/save-K6Q47J2X.js").then(r=>r.holdAllSaves(v),()=>{}):Promise.resolve(),e=new CustomEvent("clay:document-upgraded",{detail:{message:v}}),s=l?Promise.resolve():import("./c-K4M76VPM.js").then(r=>r.start(e),()=>{});return document.dispatchEvent(e),Promise.all([i,s]).then(()=>{})}var g=i=>i==null?"":`&blockeditor-format=${i}`,f={spec:{name:"spec",relayPath:"/_/sync",documentHeader:"Document-URL",snapshotKey:"snapshot",streamPath:(i,e,s,r,n)=>`/_/sync?document-url=${encodeURIComponent(i)}&lane=${e}&resume-id=${s}&client-id=${encodeURIComponent(r)}${g(n)}`},legacy:{name:"legacy",relayPath:"/_/live-sync/save",documentHeader:"Page-URL",snapshotKey:"html",streamPath:(i,e,s,r,n)=>`/_/live-sync/stream?page-url=${encodeURIComponent(i)}&lane=${e}&resume-id=${s}&client-id=${encodeURIComponent(r)}${g(n)}`}};function R(){return m().then(i=>{let e=i?.extensions||[],s=e.includes("sync"),r=e.includes("live-data"),n=e.includes("presence"),o=s&&r&&e.includes("sync-worker-data"),h=s&&(o||e.includes("sync-worker")&&!r&&!n);return{profile:s?f.spec:f.legacy,sharedSync:h,sharedData:o,liveData:r,workerFeatures:n?["live-data","presence"]:["live-data"]}}).catch(()=>({profile:f.legacy,sharedSync:!1,sharedData:!1,liveData:!1,workerFeatures:["live-data"]}))}export{c as a,y as b,D as c,b as d,L as e,f,R as g};
@@ -0,0 +1 @@
1
+ import{a as ce,b as Qe,c as ue,e as fe,f as pe,g as nt}from"./c-QDVG4NAZ.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-P73XPAOA.js";import{a as q}from"./c-MZCOGNZL.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-KU3PX7LL.js";import{e as Ue}from"./c-EQ5NBOGA.js";import{d as Pe}from"./c-IJUK2GPW.js";import{f as $,j as te}from"./c-C7SUMNMI.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-PNZIJFG7.js";import{a as Re,b as qe,c as Me,e as j,g as z,h as ne}from"./c-MOP5KBWZ.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 St(s){return e=>{for(let t of s){let i=t(e);if(typeof i=="string"&&i!=="")return i}return null}}var Bt=St([s=>s.getAttribute("data-id"),s=>s.getAttribute("id")]);var Et=/^blockeditor(\.[0-9]+)?$/,rt=s=>[...s.querySelectorAll('script[merge][clay~="live"]')].filter(e=>Et.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 wt={"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(wt)){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-YFO6ZJLQ.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-U7F66I64.js")).then(s=>y=s).catch(s=>{throw _e=null,s}),_e}var ve=null,ge=null;function kt(){return ge??=import("./c-SMLAJASY.js").then(s=>ve=s.presence).catch(s=>{throw ge=null,s}),ge}var ft=te().phase==="entering";$&&!ft&&R().catch(()=>{});$&&V().catch(()=>{});var L=null,ye=null,Q=[];function pt(s){L.presence.update(s),L.editingMarker.update(s)}function xt(){return ye??=Promise.all([import("./c-ZJG6C2WL.js"),import("./c-O2QZDVZ2.js")]).then(([s,e])=>{L={presence:s.presence,editingMarker:e.editingMarker};let t=Q;Q=[];for(let i of t)pt(i);return L}).catch(s=>{throw ye=null,s}),ye}function bt(s){if(L){pt(s);return}Q.push(s),xt().catch(()=>{})}var dt=Object.freeze({bytes:null,etag:null,seq:null}),Dt=()=>({msg:"Not in edit mode",msgType:"skipped",code:null,etag:null}),_t=["[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(","),gt='[clay~="freeze"], [freeze], [save-freeze]';function X(s){for(let e of s.querySelectorAll(gt))e.replaceChildren();return z()&&Me(s),s}function ut(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()),yt=s=>s.getAttribute("data-id")||s.getAttribute("id")||null;function Lt(s){let e=new Map,t=n=>{if(n.matches(_t))return;let r=yt(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=yt(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=dt,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}):dt,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,1);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-Z2OZFX3N.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-D62HRSZK.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=ut(H);let Z={live:document,remote:H,ignore:p=>p.matches(_t),opaque:p=>p.matches(gt)||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:ut(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 mt=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 vt=new Set(me(t)?Object.values(t):[]);for(let[p,v]of F.identities){let k=vt.has(v)?v:we.get(v);k&&S.adopt(p,k)}return{report:F,ticket:U,typedDuringWait:mt,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"&&!ft&&(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,_t as b,It as c,Se as d,Ee as e,yn as f,mn as g};
@@ -1,4 +1,4 @@
1
- import{A as k,B as P,C as g,D as T,E as y,F as A,G as E,H as z,I as x,J as O,K as tt,L as et,M as ot,N as B,O as D,R as it,S as K,c as M,d as L,e as f,n as J,s as $,w as v,x as Q,z as Z}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 as Y,d as N}from"./c-ZRGEN6QQ.js";import{N as G,d as V,z as X}from"./c-OH2FPYSY.js";import"./c-FSQXFG5T.js";import"./c-RETTCOWO.js";import"./c-WCG6AKA7.js";import"./c-57XDY6HC.js";import{a as j}from"./c-I2SCCUEW.js";import"./c-VHNSBD2M.js";var nt=`
1
+ import{A as k,B as P,C as g,D as T,E as y,F as A,G as E,H as z,I as x,J as O,K as tt,L as et,M as ot,N as B,O as D,R as it,S as K,c as M,d as L,e as f,n as J,s as $,w as v,x as Q,z as Z}from"./c-JWW6BHWD.js";import"./c-GO635CRU.js";import"./c-V2V5FKXX.js";import"./c-DT7E76Z2.js";import"./c-C6YZNU6E.js";import"./c-7K4SCQB7.js";import"./c-WMRJKQ2V.js";import{C as Y,d as N}from"./c-AI3H6ETU.js";import{N as G,d as V,z as X}from"./c-OH2FPYSY.js";import"./c-FSQXFG5T.js";import"./c-RETTCOWO.js";import"./c-WCG6AKA7.js";import"./c-57XDY6HC.js";import{a as j}from"./c-I2SCCUEW.js";import"./c-VHNSBD2M.js";var nt=`
2
2
  .blockeditor-editor .blockeditor-table { position: relative; }
3
3
  .blockeditor-table td { position: relative; }
4
4
  .blockeditor-table th { position: relative; }
@@ -0,0 +1,2 @@
1
+ import{a as g}from"./c-CITLTVQ4.js";import{a as F,b as i}from"./c-UOUUI265.js";import{d as P}from"./c-QHWJ5ZIJ.js";import"./c-HKSLOVU4.js";import"./c-RHMPKZZ7.js";import"./c-ESK4S67I.js";import{g as C,j as s,n as m,q as c}from"./c-MR75YPRT.js";import"./c-4JZDZFF6.js";import{c as $}from"./c-5RZNFTWD.js";import"./c-PKCCHJ5X.js";import"./c-46XYM55L.js";import"./c-NUHP2XDB.js";import"./c-VHNSBD2M.js";function U(a,v){let u=0,e=async()=>{let l=++u;try{let n=await v(),d=n?await n.list():[];if(l!==u)return;if(!d.length)return a.removeItem("clay.earlier-drafts");a.addItem({id:"clay.earlier-drafts",label:g.label,run:()=>I(n,{refresh:e,anchor:a.goo}).catch(()=>a.note("The drafts could not be opened. Try again."))})}catch{l===u&&a.removeItem("clay.earlier-drafts")}};return a.beforeOpen.push(e),e(),e}async function I(a,{refresh:v=()=>{},anchor:u=document.activeElement}={}){let e=P(),l=s("div",["display:flex","flex-direction:column","gap:16px"],{theme:e,parts:["dialog.content"]});l.dataset.draftCopies="",l.append(m("p",["display:block","margin:0"],g.intro,{theme:e}));let n=m("p",["display:block","margin:0"],"",{theme:e});n.setAttribute("role","status");let d=s("ol",["display:flex","flex-direction:column","gap:16px","padding:0","margin:0","list-style:none"],{theme:e});l.append(n,d);let A=!1;async function T(){let S=await a.list();d.replaceChildren(),S.length||(n.textContent="No earlier drafts are kept.");for(let r of S){let h=s("li",["display:flex","flex-direction:column","gap:8px"],{theme:e});h.dataset.draftMark=r.mark;let D=new Date(r.savedAt),k=Number.isNaN(D.getTime())?"Time unavailable":D.toLocaleString(),q=m("time",["display:block",`font-family:${$}`],k,{theme:e});r.savedAt&&(q.dateTime=r.savedAt),h.append(q,m("p",["display:block","margin:0"],`${r.fields} saved ${r.fields===1?"field":"fields"}`,{theme:e,role:"mutedText"}));let E=s("div",["display:flex","flex-wrap:wrap","gap:8px"],{theme:e}),f=s("div",["display:block"],{theme:e});c(f,!1);let b=s("div",["display:flex","flex-wrap:wrap","gap:8px","align-items:center"],{theme:e});c(b,!1);let y=(o,w,p={})=>{let t=C(o,{small:!0,theme:e,...p,onClick:async()=>{if(!A){A=!0,t.setDisabled(!0),n.textContent="";try{await w(t)}catch(H){n.textContent=H.message||"That did not work. Try again."}finally{A=!1,t.setDisabled(!1)}}}});return t.setAttribute("aria-label",`${o}: ${k}`),t},x=y("Preview",()=>{if(!f.hidden){c(f,!1),x.setAttribute("aria-expanded","false");return}let o=new DOMParser().parseFromString(a.html(r.copy),"text/html");for(let t of o.querySelectorAll('script, meta[http-equiv="refresh" i]'))t.remove();for(let t of o.querySelectorAll("input, textarea, select, button"))t.disabled=!0;for(let t of o.querySelectorAll("[contenteditable]"))t.removeAttribute("contenteditable");for(let t of o.querySelectorAll("a, area"))t.removeAttribute("href"),t.removeAttributeNS("http://www.w3.org/1999/xlink","href"),t.removeAttribute("xlink:href");let w=o.createElement("meta");w.httpEquiv="Content-Security-Policy",w.content="default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:; form-action 'none'",o.head.prepend(w);let p=s("iframe",["display:block","width:100%","height:45vh","border:0"],{theme:e});p.title=`Draft preview: ${k}`,p.setAttribute("sandbox",""),p.srcdoc=`<!DOCTYPE html>
2
+ `+o.documentElement.outerHTML,f.replaceChildren(p),c(f,!0),x.setAttribute("aria-expanded","true")});x.setAttribute("aria-expanded","false");let N=y("Restore",async()=>{await a.restore(r.mark),n.textContent="Draft restored. Reloading the page.",await v()}),R=y("Download",()=>a.download(r.copy));for(let o of[x,N,R])o.setDisabled(!r.available);let O=y("Remove",()=>{c(b,!0,"flex"),M.focus()}),M=C("Keep draft",{small:!0,theme:e,onClick:()=>{c(b,!1),O.focus()}});b.append(m("p",["margin:0"],"Remove this saved draft?",{theme:e}),M,y("Remove draft",async()=>{await a.remove(r.mark),await T(),await v(),d.querySelector("button")?.focus()},{variant:"danger"})),E.append(x,N,R,O),h.append(E,b,f),d.append(h)}}return await T(),i.title=g.label,i.html=l,i.width="720px",i[F]=e,i.closeHtml="x",i.no="Close",i.onNo(()=>u?.focus()),i.open(),l}export{U as attachRecoveryMenu,I as openRecovery};
@@ -1 +1 @@
1
- import{e as k}from"./c-N326R2JD.js";import{a as w}from"./c-I2SCCUEW.js";import{f as v}from"./c-EDE45NM7.js";var j=new Set(["accepted","reverted","reconciled"]),T=Math.random().toString(36).slice(2,8),z=0,l=new Map,f=new Map,p=new Set,h=new Set,x=null,O=20,y=null,b=null,u=[];function E(){b??=import("./c-LUXAB2XI.js").then(e=>{for(y=e;u.length;)y.keep(u.shift())},e=>{b=null,console.error("clayjs: the conflict recovery module could not be downloaded; conflicts stay in this tab only",e)})}v&&E();function S(e=""){return`${T}:${e}${++z}`}function m(){return x||=w({id:"live-sync-conflicts",isPending:()=>l.size>0||p.size>0}),x}function g(e){m().changed(),document.dispatchEvent(new CustomEvent("clay:sync-conflicts-changed",{detail:{open:[...l.keys()],added:[],removedIds:[],updatedIds:[],...e}}))}function $(e){let t=e.recovery;return t?t.applied===!1&&t.unavailable==="hook-veto"?!1:t.localLost!==!1:!0}var C=["kind","id","label","field"];function I(e){if(!e||typeof e!="object")return null;let t={};for(let n of C){let o=e[n];typeof o=="string"&&o?t[n]=o:typeof o=="number"&&Number.isFinite(o)&&(t[n]=String(o))}return Object.keys(t).length?t:null}function F(e){let t=I(e);return t?(typeof e.open=="function"&&(t.open=e.open),t):null}function A(e,t){for(let n of[...h].reverse()){let o;try{o=n(e,t)}catch(r){console.error("clayjs: a conflict context resolver threw; the conflict stays generic",r);continue}let c=F(o);if(c)return c}return null}function L(e){if(typeof e!="function")throw new TypeError("clay.conflicts.registerContext needs a resolver function");return h.add(e),()=>h.delete(e)}function B(e,t){let n=S(),o=Object.assign(t[0],{id:n,applyId:e.id,source:e.source,ticket:e.ticket,rawReports:t,claimedBy:null});return o.context=A(o,e),l.set(n,o),e.ids.add(n),n}function D({source:e,seq:t=null,etag:n=null,domain:o,root:c,recoveryRoot:r=null}){let i=S("a");return f.set(i,{id:i,source:e,seq:t,etag:n,ticket:0,domain:o,root:c,recoveryRoot:r,ids:new Set}),p.add(i),m().changed(),i}function N(e){if(!e.every(n=>n.kind==="structure"&&n.detail==="insert-collision"&&n.recovery?.applied===!0&&!n.recovery.unavailable&&n.recovery.structure?.localAction==="inserted"&&n.recovery.structure.fragmentKind==="element"))return null;let t=e[0].recovery.subject;return t?.local?.length!==1||t.merged?.length!==1||t.live?.length!==1?null:{local:t.local[0],merged:t.merged[0],live:t.live[0]}}function P(e){let t=new Map(e.map(r=>[r,N(r)])),n=(r,i)=>r.length<i.length&&r.every((s,d)=>s===i[d]),o=(r,i)=>i.reduce((s,d)=>d==="content"?s?.content:s?.childNodes[d],r),c=new Map;for(let r of e){let i=t.get(r),s=r;if(i)for(let d of e){let a=t.get(d);a&&a.local.length<t.get(s).local.length&&n(a.local,i.local)&&n(a.merged,i.merged)&&(a.live.contains(i.live)||o(a.live,i.merged.slice(a.merged.length))===i.live)&&(s=d)}c.has(s)||c.set(s,[...s]),r!==s&&c.get(s).push(...r)}return[...c.values()]}function M(e,t){let n=t.map(c=>l.get(c)).filter(Boolean);if(!n.length)return;let o={apply:e,records:n.map(c=>({rec:c,context:I(c.context)}))};if(y)return y.keep(o);u.push(o),u.length>O&&u.shift(),E()}function Q(e,t,{ticket:n}){let o=f.get(e);if(!o)return[];o.ticket=n;let c=new Map;for(let i of t){if(!$(i))continue;let s=i.recovery?.key??Symbol();c.has(s)||c.set(s,[]),c.get(s).push(i)}let r=P([...c.values()]).map(i=>B(o,i));return r.length&&M(o,r),p.delete(e),r.length||f.delete(e),r.length?g({added:r.map(i=>l.get(i))}):m().changed(),r}function X(e,t,{ticket:n=0}={}){let o=f.get(e);if(!o)return[];o.ticket=n,p.delete(e);let c=B(o,[{kind:"apply-incomplete",detail:null,error:String(t)}]);return l.get(c).rawReports=[],M(o,[c]),g({added:[l.get(c)]}),[c]}var q={get size(){return l.size},list(){return[...l.values()]},get(e){return l.get(e)||null},acknowledge(e,{reason:t}={}){if(!Array.isArray(e))throw new TypeError("clay.conflicts.acknowledge needs an array of ids");if(!j.has(t))throw new TypeError(`clay.conflicts.acknowledge: unknown reason "${t}"`);let n=[];for(let o of e){let c=l.get(o);if(!c)continue;k(c),l.delete(o),n.push(o);let r=f.get(c.applyId);r&&(r.ids.delete(o),r.ids.size||f.delete(c.applyId))}return n.length&&(g({removedIds:n,reason:t}),import("./c-LUXAB2XI.js").then(o=>o.dismiss(n),()=>{})),{removedIds:n,remainingIds:[...l.keys()]}},claim(e,{owner:t}){if(!t)throw new TypeError("clay.conflicts.claim needs an owner");for(let c of e){let r=l.get(c);if(r&&r.claimedBy&&r.claimedBy!==t)throw new Error(`conflict ${c} is already claimed by ${r.claimedBy}`)}let n=[];for(let c of e){let r=l.get(c);r&&!r.claimedBy&&(r.claimedBy=t,n.push(c))}n.length&&g({updatedIds:n,reason:"claimed"});let o=!1;return{release(){if(o)return;o=!0;let c=n.filter(r=>l.get(r)?.claimedBy===t);for(let r of c)l.get(r).claimedBy=null;c.length&&g({updatedIds:c,reason:"released"})}}},registerContext:L,contextFor:A,recoveryOf(e){let t=l.get(e);return t&&f.get(t.applyId)||null},hasPendingApply(){return p.size>0}};export{E as a,L as b,D as c,Q as d,X as e,q as f};
1
+ import{e as k}from"./c-N326R2JD.js";import{a as w}from"./c-I2SCCUEW.js";import{f as v}from"./c-C7SUMNMI.js";var j=new Set(["accepted","reverted","reconciled"]),T=Math.random().toString(36).slice(2,8),z=0,l=new Map,f=new Map,p=new Set,h=new Set,x=null,O=20,y=null,b=null,u=[];function E(){b??=import("./c-ORLPQFNU.js").then(e=>{for(y=e;u.length;)y.keep(u.shift())},e=>{b=null,console.error("clayjs: the conflict recovery module could not be downloaded; conflicts stay in this tab only",e)})}v&&E();function S(e=""){return`${T}:${e}${++z}`}function m(){return x||=w({id:"live-sync-conflicts",isPending:()=>l.size>0||p.size>0}),x}function g(e){m().changed(),document.dispatchEvent(new CustomEvent("clay:sync-conflicts-changed",{detail:{open:[...l.keys()],added:[],removedIds:[],updatedIds:[],...e}}))}function $(e){let t=e.recovery;return t?t.applied===!1&&t.unavailable==="hook-veto"?!1:t.localLost!==!1:!0}var C=["kind","id","label","field"];function I(e){if(!e||typeof e!="object")return null;let t={};for(let n of C){let o=e[n];typeof o=="string"&&o?t[n]=o:typeof o=="number"&&Number.isFinite(o)&&(t[n]=String(o))}return Object.keys(t).length?t:null}function F(e){let t=I(e);return t?(typeof e.open=="function"&&(t.open=e.open),t):null}function A(e,t){for(let n of[...h].reverse()){let o;try{o=n(e,t)}catch(r){console.error("clayjs: a conflict context resolver threw; the conflict stays generic",r);continue}let c=F(o);if(c)return c}return null}function L(e){if(typeof e!="function")throw new TypeError("clay.conflicts.registerContext needs a resolver function");return h.add(e),()=>h.delete(e)}function B(e,t){let n=S(),o=Object.assign(t[0],{id:n,applyId:e.id,source:e.source,ticket:e.ticket,rawReports:t,claimedBy:null});return o.context=A(o,e),l.set(n,o),e.ids.add(n),n}function D({source:e,seq:t=null,etag:n=null,domain:o,root:c,recoveryRoot:r=null}){let i=S("a");return f.set(i,{id:i,source:e,seq:t,etag:n,ticket:0,domain:o,root:c,recoveryRoot:r,ids:new Set}),p.add(i),m().changed(),i}function N(e){if(!e.every(n=>n.kind==="structure"&&n.detail==="insert-collision"&&n.recovery?.applied===!0&&!n.recovery.unavailable&&n.recovery.structure?.localAction==="inserted"&&n.recovery.structure.fragmentKind==="element"))return null;let t=e[0].recovery.subject;return t?.local?.length!==1||t.merged?.length!==1||t.live?.length!==1?null:{local:t.local[0],merged:t.merged[0],live:t.live[0]}}function P(e){let t=new Map(e.map(r=>[r,N(r)])),n=(r,i)=>r.length<i.length&&r.every((s,d)=>s===i[d]),o=(r,i)=>i.reduce((s,d)=>d==="content"?s?.content:s?.childNodes[d],r),c=new Map;for(let r of e){let i=t.get(r),s=r;if(i)for(let d of e){let a=t.get(d);a&&a.local.length<t.get(s).local.length&&n(a.local,i.local)&&n(a.merged,i.merged)&&(a.live.contains(i.live)||o(a.live,i.merged.slice(a.merged.length))===i.live)&&(s=d)}c.has(s)||c.set(s,[...s]),r!==s&&c.get(s).push(...r)}return[...c.values()]}function M(e,t){let n=t.map(c=>l.get(c)).filter(Boolean);if(!n.length)return;let o={apply:e,records:n.map(c=>({rec:c,context:I(c.context)}))};if(y)return y.keep(o);u.push(o),u.length>O&&u.shift(),E()}function Q(e,t,{ticket:n}){let o=f.get(e);if(!o)return[];o.ticket=n;let c=new Map;for(let i of t){if(!$(i))continue;let s=i.recovery?.key??Symbol();c.has(s)||c.set(s,[]),c.get(s).push(i)}let r=P([...c.values()]).map(i=>B(o,i));return r.length&&M(o,r),p.delete(e),r.length||f.delete(e),r.length?g({added:r.map(i=>l.get(i))}):m().changed(),r}function X(e,t,{ticket:n=0}={}){let o=f.get(e);if(!o)return[];o.ticket=n,p.delete(e);let c=B(o,[{kind:"apply-incomplete",detail:null,error:String(t)}]);return l.get(c).rawReports=[],M(o,[c]),g({added:[l.get(c)]}),[c]}var q={get size(){return l.size},list(){return[...l.values()]},get(e){return l.get(e)||null},acknowledge(e,{reason:t}={}){if(!Array.isArray(e))throw new TypeError("clay.conflicts.acknowledge needs an array of ids");if(!j.has(t))throw new TypeError(`clay.conflicts.acknowledge: unknown reason "${t}"`);let n=[];for(let o of e){let c=l.get(o);if(!c)continue;k(c),l.delete(o),n.push(o);let r=f.get(c.applyId);r&&(r.ids.delete(o),r.ids.size||f.delete(c.applyId))}return n.length&&(g({removedIds:n,reason:t}),import("./c-ORLPQFNU.js").then(o=>o.dismiss(n),()=>{})),{removedIds:n,remainingIds:[...l.keys()]}},claim(e,{owner:t}){if(!t)throw new TypeError("clay.conflicts.claim needs an owner");for(let c of e){let r=l.get(c);if(r&&r.claimedBy&&r.claimedBy!==t)throw new Error(`conflict ${c} is already claimed by ${r.claimedBy}`)}let n=[];for(let c of e){let r=l.get(c);r&&!r.claimedBy&&(r.claimedBy=t,n.push(c))}n.length&&g({updatedIds:n,reason:"claimed"});let o=!1;return{release(){if(o)return;o=!0;let c=n.filter(r=>l.get(r)?.claimedBy===t);for(let r of c)l.get(r).claimedBy=null;c.length&&g({updatedIds:c,reason:"released"})}}},registerContext:L,contextFor:A,recoveryOf(e){let t=l.get(e);return t&&f.get(t.applyId)||null},hasPendingApply(){return p.size>0}};export{E as a,L as b,D as c,Q as d,X as e,q as f};
@@ -1 +1 @@
1
- import{d as v,e as m}from"./c-A4L7APIU.js";import"./c-NEQRFC4O.js";import"./c-IW6GGOU2.js";import"./c-HAWFNBYG.js";import{e as h,f as p,g,h as k}from"./c-GO635CRU.js";import"./c-V2V5FKXX.js";import"./c-7K4SCQB7.js";import"./c-WMRJKQ2V.js";import"./c-OH2FPYSY.js";import"./c-RETTCOWO.js";import"./c-TCCA5BZN.js";import"./c-57XDY6HC.js";import"./c-YK2L436K.js";import"./c-TWCXBWS3.js";import"./c-LA2BW7UY.js";import"./c-IJUK2GPW.js";import{c as b}from"./c-BPF2NSPV.js";import{e as T}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"./c-ICMAOOGK.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";T(v);var x=1,y=class extends Error{constructor(o,n){super(n),this.name="PageCheckpointError",this.code=o}},w=(e,o)=>{throw new y(e,o)},t=(e,o)=>({ok:!1,code:e,message:o}),A=/^[0-9a-f]{64}$/,j=/^[0-9a-f]{32}$/,E=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function I(e){return{v:e.v,g:e.g,y:{...e.y??{}}}}function H(e){let o;try{o=JSON.parse(e)}catch{w("invalid-state","The page state is not JSON")}return(!E(o)||o.v!==1)&&w("invalid-state","Expected a version 1 Yjs page value"),{state:I(o),bytes:p(o)}}var S=e=>e==null?"":String(e);async function N({href:e,etag:o,fetch:n=globalThis.fetch,signal:i=null}={}){if(typeof o!="string"||!o)return t("missing-etag","A conditional read needs the accepted ETag");if(typeof e!="string"||!e)return t("no-blockeditor-state","This host names no blockeditor-state resource");if(typeof n!="function")return t("unavailable","This tab cannot read the page state");let s=globalThis.location?.href??"http://localhost/",d;try{d=new URL(e,s).href}catch{return t("no-blockeditor-state","The blockeditor-state resource is not a URL")}let c=b(),a;try{a=await n(d,{method:"GET",credentials:c?"omit":"same-origin",headers:{"If-Match":o,"Document-URL":globalThis.location?.href??s},cache:"no-store",redirect:"manual",signal:i})}catch{return t("unavailable","The blockeditor-state request did not complete")}if(!a||typeof a.status!="number")return t("unavailable","The blockeditor-state request did not answer");if(a.status===412)return t("etag-mismatch","Another version of this document is stored");if(a.status===428)return t("etag-required","The host needs a condition this read cannot send");if(a.status===404)return t("no-blockeditor-state","This host keeps no page state");if(!a.ok)return t("unavailable",`The host answered ${a.status}`);let r;try{r=JSON.parse(await a.text())}catch{return t("invalid-state","The blockeditor-state answer is not JSON")}return!E(r)||r.version!==x?t("unsupported-version","Unknown blockeditor-state version"):typeof r.tag!="string"||!r.tag?t("invalid-state","The blockeditor-state answer carries no page tag"):typeof r.stateHash!="string"||!A.test(r.stateHash)?t("invalid-state","The blockeditor-state answer carries no state digest"):typeof r.generation!="string"||!j.test(r.generation)?t("invalid-state","The blockeditor-state answer carries no generation"):typeof r.etag!="string"||!r.etag?t("invalid-state","The blockeditor-state answer carries no ETag"):Object.hasOwn(r,"documentId")?{ok:!0,version:r.version,documentId:r.documentId,generation:r.generation,etag:r.etag,stateHash:r.stateHash,tag:r.tag}:t("invalid-state","The blockeditor-state answer carries no document identity")}async function _(e,{accepted:o,article:n,etag:i}={}){if(!e||e.ok!==!0)return t(e?.code??"unavailable",e?.message??"The page state was not read");let s=o?.authority;if(!(s?.scope==="path"&&e.documentId==null)&&S(e.documentId)!==S(s?.documentId))return t("foreign-document","The page state belongs to another document");if(typeof o?.lineage?.generation!="string"||e.generation!==o.lineage.generation)return t("foreign-generation","The page state belongs to another generation");if(e.etag!==i)return t("etag-mismatch","The page state belongs to another version of this document");let c,a;try{({state:a,bytes:c}=H(e.tag))}catch(u){return t(u?.code??"invalid-state",u?.message??"The page state does not decode")}if(await h(c)!==e.stateHash)return t("state-digest-mismatch","The page state is not the one the host hashed");if(typeof n!="string")return t("missing-article","A proof names the final outgoing article");let r;try{r=m(a)}catch(u){return t("invalid-state",u?.message??"The page state does not project")}return r!==n?t("article-mismatch","The page state does not project to the accepted article"):{ok:!0,state:a,receipt:{file:e.etag,blockeditorState:e.stateHash}}}async function O(e,o){let n=(o||[]).map(({id:i,revision:s})=>({id:i,revision:s}));try{return{ok:!0,proof:e,covered:await k(e,n)}}catch(i){return t(i?.code??"invalid-proof",i?.message??"The proof does not validate")}}async function R({capture:e,records:o=[],accepted:n,article:i,state:s=null,etag:d=null}={}){if(!s)return t("no-capture-state","No page state was pinned to this capture");if(typeof d!="string"||!d)return t("missing-etag","An accepted save with no ETag proves no stored pair");if(typeof i!="string")return t("missing-article","The accepted bytes hold no article");let c,a;try{c=m(s),a=p(s)}catch(u){return t(u?.code??"invalid-state",u?.message??"The pinned page state does not decode")}if(c!==i)return t("article-mismatch","The pinned page state does not project to the accepted article");let r;try{r=await g({capture:e,records:o,accepted:n,article:i,state:s,receipt:{file:d,blockeditorState:await h(a)}})}catch(u){return t(u?.code??"invalid-proof",u?.message??"The proof could not be built")}return O(r,o)}async function B({read:e,capture:o,records:n=[],accepted:i,article:s,etag:d=null}={}){let c=await _(e,{accepted:i,article:s,etag:d});if(!c.ok)return c;let a;try{a=await g({capture:o,records:n,accepted:i,article:s,state:c.state,receipt:c.receipt})}catch(r){return t(r?.code??"invalid-proof",r?.message??"The proof could not be built")}return O(a,n)}async function G({channel:e,records:o=[],capture:n,accepted:i,article:s,state:d=null,etag:c=null,href:a=null,read:r=N,fetch:u}={}){if(!e||typeof e.checkpoint!="function")return{ok:!1,code:"no-channel",retired:[],proof:null};let l=await R({capture:n,records:o,accepted:i,article:s,state:d,etag:c});if(!l.ok){let P=await r({href:a,etag:c,fetch:u});l=await B({read:P,capture:n,records:o,accepted:i,article:s,etag:c})}if(!l.ok)return{ok:!1,code:l.code,retired:[],proof:null};let f=await e.checkpoint({records:l.covered,proof:l.proof});return!f||f.ok!==!0?{ok:!1,code:f?.code??"checkpoint-failed",retired:[],proof:l.proof}:{ok:!0,retired:f.retired??[],proof:l.proof}}export{x as PAGE_STATE_VERSION,y as PageCheckpointError,R as captureProof,G as checkpointAccepted,N as readPageState,B as refetchedProof,_ as verifyPageState};
1
+ import{d as v,e as m}from"./c-4AE2A2LK.js";import"./c-NEQRFC4O.js";import"./c-IW6GGOU2.js";import"./c-HAWFNBYG.js";import{e as h,f as p,g,h as k}from"./c-GO635CRU.js";import"./c-V2V5FKXX.js";import"./c-7K4SCQB7.js";import"./c-WMRJKQ2V.js";import"./c-OH2FPYSY.js";import"./c-RETTCOWO.js";import"./c-TCCA5BZN.js";import"./c-57XDY6HC.js";import"./c-MV7TEUTD.js";import"./c-QCDVDZIR.js";import"./c-MZCOGNZL.js";import"./c-IJUK2GPW.js";import{c as b}from"./c-BPF2NSPV.js";import{e as T}from"./c-PNZIJFG7.js";import"./c-XQXZAO7N.js";import"./c-S7LK4KUE.js";import"./c-MOP5KBWZ.js";import"./c-2YYDMLNZ.js";import"./c-HA6INT6J.js";import"./c-ICMAOOGK.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";T(v);var x=1,y=class extends Error{constructor(o,n){super(n),this.name="PageCheckpointError",this.code=o}},w=(e,o)=>{throw new y(e,o)},t=(e,o)=>({ok:!1,code:e,message:o}),A=/^[0-9a-f]{64}$/,j=/^[0-9a-f]{32}$/,E=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function I(e){return{v:e.v,g:e.g,y:{...e.y??{}}}}function H(e){let o;try{o=JSON.parse(e)}catch{w("invalid-state","The page state is not JSON")}return(!E(o)||o.v!==1)&&w("invalid-state","Expected a version 1 Yjs page value"),{state:I(o),bytes:p(o)}}var S=e=>e==null?"":String(e);async function N({href:e,etag:o,fetch:n=globalThis.fetch,signal:i=null}={}){if(typeof o!="string"||!o)return t("missing-etag","A conditional read needs the accepted ETag");if(typeof e!="string"||!e)return t("no-blockeditor-state","This host names no blockeditor-state resource");if(typeof n!="function")return t("unavailable","This tab cannot read the page state");let s=globalThis.location?.href??"http://localhost/",d;try{d=new URL(e,s).href}catch{return t("no-blockeditor-state","The blockeditor-state resource is not a URL")}let c=b(),a;try{a=await n(d,{method:"GET",credentials:c?"omit":"same-origin",headers:{"If-Match":o,"Document-URL":globalThis.location?.href??s},cache:"no-store",redirect:"manual",signal:i})}catch{return t("unavailable","The blockeditor-state request did not complete")}if(!a||typeof a.status!="number")return t("unavailable","The blockeditor-state request did not answer");if(a.status===412)return t("etag-mismatch","Another version of this document is stored");if(a.status===428)return t("etag-required","The host needs a condition this read cannot send");if(a.status===404)return t("no-blockeditor-state","This host keeps no page state");if(!a.ok)return t("unavailable",`The host answered ${a.status}`);let r;try{r=JSON.parse(await a.text())}catch{return t("invalid-state","The blockeditor-state answer is not JSON")}return!E(r)||r.version!==x?t("unsupported-version","Unknown blockeditor-state version"):typeof r.tag!="string"||!r.tag?t("invalid-state","The blockeditor-state answer carries no page tag"):typeof r.stateHash!="string"||!A.test(r.stateHash)?t("invalid-state","The blockeditor-state answer carries no state digest"):typeof r.generation!="string"||!j.test(r.generation)?t("invalid-state","The blockeditor-state answer carries no generation"):typeof r.etag!="string"||!r.etag?t("invalid-state","The blockeditor-state answer carries no ETag"):Object.hasOwn(r,"documentId")?{ok:!0,version:r.version,documentId:r.documentId,generation:r.generation,etag:r.etag,stateHash:r.stateHash,tag:r.tag}:t("invalid-state","The blockeditor-state answer carries no document identity")}async function _(e,{accepted:o,article:n,etag:i}={}){if(!e||e.ok!==!0)return t(e?.code??"unavailable",e?.message??"The page state was not read");let s=o?.authority;if(!(s?.scope==="path"&&e.documentId==null)&&S(e.documentId)!==S(s?.documentId))return t("foreign-document","The page state belongs to another document");if(typeof o?.lineage?.generation!="string"||e.generation!==o.lineage.generation)return t("foreign-generation","The page state belongs to another generation");if(e.etag!==i)return t("etag-mismatch","The page state belongs to another version of this document");let c,a;try{({state:a,bytes:c}=H(e.tag))}catch(u){return t(u?.code??"invalid-state",u?.message??"The page state does not decode")}if(await h(c)!==e.stateHash)return t("state-digest-mismatch","The page state is not the one the host hashed");if(typeof n!="string")return t("missing-article","A proof names the final outgoing article");let r;try{r=m(a)}catch(u){return t("invalid-state",u?.message??"The page state does not project")}return r!==n?t("article-mismatch","The page state does not project to the accepted article"):{ok:!0,state:a,receipt:{file:e.etag,blockeditorState:e.stateHash}}}async function O(e,o){let n=(o||[]).map(({id:i,revision:s})=>({id:i,revision:s}));try{return{ok:!0,proof:e,covered:await k(e,n)}}catch(i){return t(i?.code??"invalid-proof",i?.message??"The proof does not validate")}}async function R({capture:e,records:o=[],accepted:n,article:i,state:s=null,etag:d=null}={}){if(!s)return t("no-capture-state","No page state was pinned to this capture");if(typeof d!="string"||!d)return t("missing-etag","An accepted save with no ETag proves no stored pair");if(typeof i!="string")return t("missing-article","The accepted bytes hold no article");let c,a;try{c=m(s),a=p(s)}catch(u){return t(u?.code??"invalid-state",u?.message??"The pinned page state does not decode")}if(c!==i)return t("article-mismatch","The pinned page state does not project to the accepted article");let r;try{r=await g({capture:e,records:o,accepted:n,article:i,state:s,receipt:{file:d,blockeditorState:await h(a)}})}catch(u){return t(u?.code??"invalid-proof",u?.message??"The proof could not be built")}return O(r,o)}async function B({read:e,capture:o,records:n=[],accepted:i,article:s,etag:d=null}={}){let c=await _(e,{accepted:i,article:s,etag:d});if(!c.ok)return c;let a;try{a=await g({capture:o,records:n,accepted:i,article:s,state:c.state,receipt:c.receipt})}catch(r){return t(r?.code??"invalid-proof",r?.message??"The proof could not be built")}return O(a,n)}async function G({channel:e,records:o=[],capture:n,accepted:i,article:s,state:d=null,etag:c=null,href:a=null,read:r=N,fetch:u}={}){if(!e||typeof e.checkpoint!="function")return{ok:!1,code:"no-channel",retired:[],proof:null};let l=await R({capture:n,records:o,accepted:i,article:s,state:d,etag:c});if(!l.ok){let P=await r({href:a,etag:c,fetch:u});l=await B({read:P,capture:n,records:o,accepted:i,article:s,etag:c})}if(!l.ok)return{ok:!1,code:l.code,retired:[],proof:null};let f=await e.checkpoint({records:l.covered,proof:l.proof});return!f||f.ok!==!0?{ok:!1,code:f?.code??"checkpoint-failed",retired:[],proof:l.proof}:{ok:!0,retired:f.retired??[],proof:l.proof}}export{x as PAGE_STATE_VERSION,y as PageCheckpointError,R as captureProof,G as checkpointAccepted,N as readPageState,B as refetchedProof,_ as verifyPageState};
@@ -1,4 +1,4 @@
1
- import{b as Ge}from"./c-HAWFNBYG.js";import{a as Xe,d as ce}from"./c-X6MOYATI.js";import{j as Je}from"./c-DIKR7H57.js";import{a as Ye}from"./c-AQLFEATB.js";import{a as Qe}from"./c-AQYCG7QW.js";import{b as qe}from"./c-QY7F6EN6.js";import{b as Ve,d as We}from"./c-WCG6AKA7.js";import{c as Ke}from"./c-PKCCHJ5X.js";import{a as $e}from"./c-I2SCCUEW.js";import{d as je}from"./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";var At=/^[a-z][a-z0-9+.-]*:/i,Lt=["noindex","nofollow"],St=["ogTitle","ogDescription","ogImage","ogImageAlt","siteName"],m=e=>e==null?"":String(e),I=e=>m(e).trim()!=="",T=e=>e.head||e.querySelector("head"),O=(e,t,n)=>Array.from(T(e).querySelectorAll("meta")).filter(i=>m(i.getAttribute(t)).trim().toLowerCase()===n),de=(e,t)=>Array.from(T(e).querySelectorAll("link")).filter(n=>m(n.getAttribute("rel")).trim().toLowerCase().split(/\s+/).includes(t)),pe=e=>Array.from(T(e).querySelectorAll("title")),fe=e=>O(e,"name","robots"),w=e=>e.remove();function G(e,t,n){let i=e.createElement("meta");return i.setAttribute(t,n),T(e).appendChild(i),i}function Ct(e,t){let n=e.createElement("link");return n.setAttribute("rel",t),T(e).appendChild(n),n}function ue(e,t,n,i){(O(e,t,n)[0]||G(e,t,n)).setAttribute("content",i)}function C(e,t,{trim:n=!1}={}){let i=c=>O(c,e,t);return{find:i,read(c){let d=i(c)[0];return d?m(d.getAttribute("content")):""},write(c,d){let f=i(c),p=m(d);if(!I(p)){f.forEach(w);return}(f[0]||G(c,e,t)).setAttribute("content",n?p.trim():p),f.slice(1).forEach(w)}}}var et=e=>m(e.getAttribute("content")).split(",").map(t=>t.trim()).filter(Boolean);function It(e,t){let n=fe(e),i=(n[0]?et(n[0]):[]).filter(p=>!Lt.includes(p.toLowerCase())),c=[];t.index===!1&&c.push("noindex"),t.follow===!1&&c.push("nofollow");let d=c.concat(i);if(!d.length){n.forEach(w);return}(n[0]||G(e,"name","robots")).setAttribute("content",d.join(", ")),n.slice(1).forEach(w)}function Ze(e){let t=e==="noindex"?"index":"follow",n=t==="index"?"follow":"index";return{find:fe,read(i){let c=fe(i)[0];return c?!et(c).some(d=>d.toLowerCase()===e):!0},write(i,c){let d={index:!0,follow:!0};d[t]=!!c,d[n]=x[n].read(i),It(i,d)}}}var Ot={find:pe,read(e){let t=pe(e)[0];return t?m(t.textContent):""},write(e,t){let n=pe(e),i=m(t);if(!I(i)){n.forEach(w);return}let c=n[0]||e.createElement("title");n.length||T(e).appendChild(c),c.textContent=i,n.slice(1).forEach(w)}},Ut={find(e){let t=e.documentElement;return t&&t.hasAttribute("lang")?[t]:[]},read(e){let t=e.documentElement;return t&&t.hasAttribute("lang")?m(t.getAttribute("lang")):""},write(e,t){let n=e.documentElement;if(!n)return;let i=m(t);if(!I(i)){n.removeAttribute("lang");return}n.setAttribute("lang",i.trim())}},zt={find:e=>de(e,"canonical"),read(e){let t=de(e,"canonical")[0];return t?m(t.getAttribute("href")):""},write(e,t){let n=de(e,"canonical"),i=m(t);if(!I(i)){n.forEach(w);return}(n[0]||Ct(e,"canonical")).setAttribute("href",i.trim()),n.slice(1).forEach(w)}},Y="clay-seo-title-mode",Tt={find:e=>O(e,"name",Y),read(e){return O(e,"name",Y).some(n=>m(n.getAttribute("content")).trim().toLowerCase()==="custom")?"custom":"derived"},write(e,t){let n=O(e,"name",Y);if(m(t).trim().toLowerCase()!=="custom"){n.forEach(w);return}(n[0]||G(e,"name",Y)).setAttribute("content","custom"),n.slice(1).forEach(w)}},x={title:Ot,description:C("name","description"),lang:Ut,canonical:zt,index:Ze("noindex"),follow:Ze("nofollow"),ogTitle:C("property","og:title"),ogDescription:C("property","og:description"),ogImage:C("property","og:image",{trim:!0}),ogImageAlt:C("property","og:image:alt"),siteName:C("property","og:site_name"),twitterSite:C("name","twitter:site"),titleMode:Tt},tt=Object.fromEntries(Object.keys(x).map(e=>[e,{read:x[e].read,write:x[e].write}]));function ot(e){let t=e.hostname.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"}function me(e){try{return new URL(e)}catch{return null}}function ge(e){return e.protocol==="http:"||e.protocol==="https:"}function nt(e){let t=e.location&&e.location.href||e.URL||e.baseURI||"",n=me(t);return!n||!ge(n)||ot(n)?"":n.origin+n.pathname}function it(e){let t=m(e).trim();if(!t)return"";let n=me(t);return!n||!ge(n)?"Enter a full http: or https: address.":ot(n)?"A localhost address cannot be a canonical URL.":""}function Mt(e,t){let n=m(e).trim();if(!n)return"";if(At.test(n)){let i=me(n);return!i||!ge(i)?"Use an http: or https: image address.":""}if(t)try{new URL(n,t)}catch{return"Use an http: or https: image address."}return""}function rt(e,t){let n=("canonical"in t?m(t.canonical).trim():x.canonical.read(e)).trim();return n&&!it(n)?n:""}function Rt(e,t){let n=St.some(d=>d in t&&I(t[d])),i="canonical"in t&&I(t.canonical);if(!n&&!i&&!("ogImage"in t))return;if(n||i){O(e,"property","og:type").length||ue(e,"property","og:type","website");let d=rt(e,t)||nt(e);d&&ue(e,"property","og:url",d)}let c="ogImage"in t?t.ogImage:x.ogImage.read(e);ue(e,"name","twitter:card",I(c)?"summary_large_image":"summary")}function B(e){let t={},n={};for(let i of Object.keys(x)){let c=x[i];t[i]=c.read(e),n[i]=c.find(e).length>0}return{values:t,present:n}}function X(e,t){let n=t||{},i=Object.keys(x).filter(p=>p in n),c={};if(i.includes("canonical")){let p=it(n.canonical);p&&(c.canonical=p)}if(i.includes("ogImage")){let p=rt(e,n)||nt(e),b=Mt(n.ogImage,p);b&&(c.ogImage=b)}if(Object.keys(c).length)return{normalized:[],errors:c};let d=[],f=new Set;for(let p of i){let b=x[p].find;b(e).length>1&&!f.has(b)&&(f.add(b),d.push(p))}for(let p of i)x[p].write(e,n[p]);return Rt(e,n),{normalized:d,errors:{}}}var at="reopen-seo",Ht="SEO and social sharing",Pt="SEO settings",lt="SEO settings applied",mt=/^[a-z][a-z0-9+.-]*:/i,Nt="This site is hidden from search engines in your account settings, so this page stays hidden whatever you choose here.",Bt="Uploaded images are public to anyone with the link.",Dt="Paste the address of an image on the web.",_t={title:{label:"Title",kind:"text",full:!0,count:60},description:{label:"Description",kind:"textarea",full:!0,count:160},ogTitle:{label:"Preview title",note:"Open Graph",kind:"text"},ogDescription:{label:"Preview description",note:"Open Graph",kind:"textarea",short:!0},ogImage:{label:"Preview image",note:"Open Graph",kind:"text",full:!0},canonical:{label:"Canonical URL",kind:"text"},lang:{label:"Language",kind:"text"},ogImageAlt:{label:"Image alt text",kind:"text"},siteName:{label:"Site name",kind:"text"},twitterSite:{label:"Social handle",kind:"text",placeholder:"@yourname"},index:{label:"Show in search results",kind:"checkbox"},follow:{label:"Let search engines follow links",kind:"checkbox"}},Ft=["title","description","ogTitle","ogDescription","ogImage"],jt=["canonical","lang","ogImageAlt","siteName","twitterSite"],Kt=["index","follow"],st=`.clay-seo { box-sizing: border-box; width: 100%; border-bottom: 1px solid var(--bevel-line-3); background: var(--bevel-surface); box-shadow: var(--clay-sheet-shadow); font-size: 13px; line-height: 1.45; container-type: inline-size; animation: clay-seo-in .2s ease-out; position: relative; z-index: 2147482001; grid-column: 1 / -1; flex: 0 0 100%; max-height: 85vh; max-height: 85dvh; overflow-y: auto; overscroll-behavior: contain; }
1
+ import{b as Ge}from"./c-HAWFNBYG.js";import{a as Xe,d as ce}from"./c-X6MOYATI.js";import{j as Je}from"./c-DIKR7H57.js";import{a as Ye}from"./c-AQLFEATB.js";import{a as Qe}from"./c-AQYCG7QW.js";import{b as qe}from"./c-QY7F6EN6.js";import{b as Ve,d as We}from"./c-WCG6AKA7.js";import{c as Ke}from"./c-PKCCHJ5X.js";import{a as $e}from"./c-I2SCCUEW.js";import{d as je}from"./c-EQ5NBOGA.js";import"./c-C7SUMNMI.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-U4TWEIKZ.js";import"./c-HA6INT6J.js";import"./c-ICMAOOGK.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";var At=/^[a-z][a-z0-9+.-]*:/i,Lt=["noindex","nofollow"],St=["ogTitle","ogDescription","ogImage","ogImageAlt","siteName"],m=e=>e==null?"":String(e),I=e=>m(e).trim()!=="",T=e=>e.head||e.querySelector("head"),O=(e,t,n)=>Array.from(T(e).querySelectorAll("meta")).filter(i=>m(i.getAttribute(t)).trim().toLowerCase()===n),de=(e,t)=>Array.from(T(e).querySelectorAll("link")).filter(n=>m(n.getAttribute("rel")).trim().toLowerCase().split(/\s+/).includes(t)),pe=e=>Array.from(T(e).querySelectorAll("title")),fe=e=>O(e,"name","robots"),w=e=>e.remove();function G(e,t,n){let i=e.createElement("meta");return i.setAttribute(t,n),T(e).appendChild(i),i}function Ct(e,t){let n=e.createElement("link");return n.setAttribute("rel",t),T(e).appendChild(n),n}function ue(e,t,n,i){(O(e,t,n)[0]||G(e,t,n)).setAttribute("content",i)}function C(e,t,{trim:n=!1}={}){let i=c=>O(c,e,t);return{find:i,read(c){let d=i(c)[0];return d?m(d.getAttribute("content")):""},write(c,d){let f=i(c),p=m(d);if(!I(p)){f.forEach(w);return}(f[0]||G(c,e,t)).setAttribute("content",n?p.trim():p),f.slice(1).forEach(w)}}}var et=e=>m(e.getAttribute("content")).split(",").map(t=>t.trim()).filter(Boolean);function It(e,t){let n=fe(e),i=(n[0]?et(n[0]):[]).filter(p=>!Lt.includes(p.toLowerCase())),c=[];t.index===!1&&c.push("noindex"),t.follow===!1&&c.push("nofollow");let d=c.concat(i);if(!d.length){n.forEach(w);return}(n[0]||G(e,"name","robots")).setAttribute("content",d.join(", ")),n.slice(1).forEach(w)}function Ze(e){let t=e==="noindex"?"index":"follow",n=t==="index"?"follow":"index";return{find:fe,read(i){let c=fe(i)[0];return c?!et(c).some(d=>d.toLowerCase()===e):!0},write(i,c){let d={index:!0,follow:!0};d[t]=!!c,d[n]=x[n].read(i),It(i,d)}}}var Ot={find:pe,read(e){let t=pe(e)[0];return t?m(t.textContent):""},write(e,t){let n=pe(e),i=m(t);if(!I(i)){n.forEach(w);return}let c=n[0]||e.createElement("title");n.length||T(e).appendChild(c),c.textContent=i,n.slice(1).forEach(w)}},Ut={find(e){let t=e.documentElement;return t&&t.hasAttribute("lang")?[t]:[]},read(e){let t=e.documentElement;return t&&t.hasAttribute("lang")?m(t.getAttribute("lang")):""},write(e,t){let n=e.documentElement;if(!n)return;let i=m(t);if(!I(i)){n.removeAttribute("lang");return}n.setAttribute("lang",i.trim())}},zt={find:e=>de(e,"canonical"),read(e){let t=de(e,"canonical")[0];return t?m(t.getAttribute("href")):""},write(e,t){let n=de(e,"canonical"),i=m(t);if(!I(i)){n.forEach(w);return}(n[0]||Ct(e,"canonical")).setAttribute("href",i.trim()),n.slice(1).forEach(w)}},Y="clay-seo-title-mode",Tt={find:e=>O(e,"name",Y),read(e){return O(e,"name",Y).some(n=>m(n.getAttribute("content")).trim().toLowerCase()==="custom")?"custom":"derived"},write(e,t){let n=O(e,"name",Y);if(m(t).trim().toLowerCase()!=="custom"){n.forEach(w);return}(n[0]||G(e,"name",Y)).setAttribute("content","custom"),n.slice(1).forEach(w)}},x={title:Ot,description:C("name","description"),lang:Ut,canonical:zt,index:Ze("noindex"),follow:Ze("nofollow"),ogTitle:C("property","og:title"),ogDescription:C("property","og:description"),ogImage:C("property","og:image",{trim:!0}),ogImageAlt:C("property","og:image:alt"),siteName:C("property","og:site_name"),twitterSite:C("name","twitter:site"),titleMode:Tt},tt=Object.fromEntries(Object.keys(x).map(e=>[e,{read:x[e].read,write:x[e].write}]));function ot(e){let t=e.hostname.toLowerCase();return t==="localhost"||t.endsWith(".localhost")||t==="127.0.0.1"}function me(e){try{return new URL(e)}catch{return null}}function ge(e){return e.protocol==="http:"||e.protocol==="https:"}function nt(e){let t=e.location&&e.location.href||e.URL||e.baseURI||"",n=me(t);return!n||!ge(n)||ot(n)?"":n.origin+n.pathname}function it(e){let t=m(e).trim();if(!t)return"";let n=me(t);return!n||!ge(n)?"Enter a full http: or https: address.":ot(n)?"A localhost address cannot be a canonical URL.":""}function Mt(e,t){let n=m(e).trim();if(!n)return"";if(At.test(n)){let i=me(n);return!i||!ge(i)?"Use an http: or https: image address.":""}if(t)try{new URL(n,t)}catch{return"Use an http: or https: image address."}return""}function rt(e,t){let n=("canonical"in t?m(t.canonical).trim():x.canonical.read(e)).trim();return n&&!it(n)?n:""}function Rt(e,t){let n=St.some(d=>d in t&&I(t[d])),i="canonical"in t&&I(t.canonical);if(!n&&!i&&!("ogImage"in t))return;if(n||i){O(e,"property","og:type").length||ue(e,"property","og:type","website");let d=rt(e,t)||nt(e);d&&ue(e,"property","og:url",d)}let c="ogImage"in t?t.ogImage:x.ogImage.read(e);ue(e,"name","twitter:card",I(c)?"summary_large_image":"summary")}function B(e){let t={},n={};for(let i of Object.keys(x)){let c=x[i];t[i]=c.read(e),n[i]=c.find(e).length>0}return{values:t,present:n}}function X(e,t){let n=t||{},i=Object.keys(x).filter(p=>p in n),c={};if(i.includes("canonical")){let p=it(n.canonical);p&&(c.canonical=p)}if(i.includes("ogImage")){let p=rt(e,n)||nt(e),b=Mt(n.ogImage,p);b&&(c.ogImage=b)}if(Object.keys(c).length)return{normalized:[],errors:c};let d=[],f=new Set;for(let p of i){let b=x[p].find;b(e).length>1&&!f.has(b)&&(f.add(b),d.push(p))}for(let p of i)x[p].write(e,n[p]);return Rt(e,n),{normalized:d,errors:{}}}var at="reopen-seo",Ht="SEO and social sharing",Pt="SEO settings",lt="SEO settings applied",mt=/^[a-z][a-z0-9+.-]*:/i,Nt="This site is hidden from search engines in your account settings, so this page stays hidden whatever you choose here.",Bt="Uploaded images are public to anyone with the link.",Dt="Paste the address of an image on the web.",_t={title:{label:"Title",kind:"text",full:!0,count:60},description:{label:"Description",kind:"textarea",full:!0,count:160},ogTitle:{label:"Preview title",note:"Open Graph",kind:"text"},ogDescription:{label:"Preview description",note:"Open Graph",kind:"textarea",short:!0},ogImage:{label:"Preview image",note:"Open Graph",kind:"text",full:!0},canonical:{label:"Canonical URL",kind:"text"},lang:{label:"Language",kind:"text"},ogImageAlt:{label:"Image alt text",kind:"text"},siteName:{label:"Site name",kind:"text"},twitterSite:{label:"Social handle",kind:"text",placeholder:"@yourname"},index:{label:"Show in search results",kind:"checkbox"},follow:{label:"Let search engines follow links",kind:"checkbox"}},Ft=["title","description","ogTitle","ogDescription","ogImage"],jt=["canonical","lang","ogImageAlt","siteName","twitterSite"],Kt=["index","follow"],st=`.clay-seo { box-sizing: border-box; width: 100%; border-bottom: 1px solid var(--bevel-line-3); background: var(--bevel-surface); box-shadow: var(--clay-sheet-shadow); font-size: 13px; line-height: 1.45; container-type: inline-size; animation: clay-seo-in .2s ease-out; position: relative; z-index: 2147482001; grid-column: 1 / -1; flex: 0 0 100%; max-height: 85vh; max-height: 85dvh; overflow-y: auto; overscroll-behavior: contain; }
2
2
  @keyframes clay-seo-in { from { margin-top: -40px; opacity: 0; } to { margin-top: 0; opacity: 1; } }
3
3
  .clay-seo-inner { max-width: 1120px; margin: 0 auto; padding: 14px 20px 18px; }
4
4
  .clay-seo-bar { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-bottom: 10px; margin-bottom: 12px; border-bottom: 1px solid var(--bevel-line-2); }
@@ -1 +1 @@
1
- import{b as E,d as A,e as M,f as I}from"./c-LS7IVQVW.js";import"./c-NEQRFC4O.js";import"./c-GO635CRU.js";import"./c-V2V5FKXX.js";import"./c-7K4SCQB7.js";import"./c-WMRJKQ2V.js";import{C as B}from"./c-ZRGEN6QQ.js";import{E as m,fa as S,ia as L,ja as O,la as Y,ma as x}from"./c-OH2FPYSY.js";import"./c-RETTCOWO.js";import"./c-57XDY6HC.js";import"./c-VHNSBD2M.js";var Q="This element holds blocks from a document editor. Reply with the same outer div. Inside it use p, h1, h2, h3, ul, ol, li, blockquote, pre with code, details with summary, hr, table with thead, tbody, tr, th, td, and the inline tags strong, em, s, u, code, a. You may also keep any tag already in the element. Keep each data-id on the block it belongs to, and give a new block no data-id. An hr with data-clay-keep stands for something you cannot see: keep it where it belongs unless the request says to remove it. Keep each checkbox on a list item unless the request says to remove it. No classes, no style attributes, no scripts.",U=new Set(["image","file","chart","board","toc","tool","preserved"]),$=new Set(["paragraph","heading","list_item","quote","callout","code_block","toggle","divider","table"]),p=(r,t)=>({status:"refused",code:r,message:t}),H=({id:r,parent:t,...i})=>({...i,parent:t??null}),F=(r,t)=>S(H(r))===S(H(t)),K=()=>globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,P=["owner","due","pageIcon","pageCoverSrc","pageCoverAlt","pageCoverX","pageCoverY"],G=(r,t)=>{let i={...t};for(let d of P)(i[d]===void 0||i[d]===null)&&r[d]!==void 0&&(i[d]=r[d]);return i},V=(r,t)=>{let i=new Set(r.cols.map(o=>o.id).filter(Boolean)),d=r.cols.map((o,l)=>{if(o.id)return o;let n=t.cols[l];return!n?.id||i.has(n.id)?o:(i.add(n.id),{...o,id:n.id})}).map(o=>{let l=o.id?t.cols.find(h=>h.id===o.id):null;if(!l)return o;let n={...o};return n.kind===void 0&&l.kind!==void 0&&(n.kind=l.kind),n.width===void 0&&l.width!==void 0&&(n.width=l.width),n});return{...r,cols:d}};function Z(r,t,{dom:i=document}={}){let d=m(r);if(t.some(s=>d[s]?.t==="opaque_block"))return p("opaque","This area holds a block this editor cannot rewrite.");let o=I(A(d),i),l=new Set(t),n=o.filter(s=>l.has(s.id));if(n.length!==t.length)return p("not-found","Some of these blocks are no longer in the document.");let h=new Map,a=new Map,g=n.map(s=>{let w=d[s.id]?.t??s.t;return U.has(w)?(h.set(s.id,s),a.set(s.id,w),{id:s.id,t:"divider",parent:s.parent}):s});if(n.every(s=>h.has(s.id)))return p("no-text","This area holds nothing that can be rewritten.");let b=i.createElement("template");b.innerHTML=O(g,{clean:L(i)});for(let s of b.content.querySelectorAll("hr[data-id]")){let w=s.getAttribute("data-id");h.has(w)&&s.setAttribute("data-clay-keep",a.get(w))}let f=o.indexOf(n[0]),y=o.indexOf(n[n.length-1]);return y-f+1!==n.length?p("not-found","These blocks are not next to each other."):{status:"ok",capture:{ids:n.map(s=>s.id),blocks:d,baseItems:o,before:o.slice(0,f),span:n,after:o.slice(y+1),parent:n[0].parent??null,held:h,html:`<div data-clay-area>${b.innerHTML}</div>`}}}function N(r,t,i=document){let d=I(A(m(r)),i),o=new Map(d.map(a=>[a.id,a])),l=t.span.filter(a=>!o.has(a.id)||!F(a,o.get(a.id))).map(a=>a.id);if(l.length)return l;let n=d.findIndex(a=>a.id===t.ids[0]);return t.ids.every((a,g)=>d[n+g]?.id===a)?[]:[...t.ids]}function ee(r,t,i,{seed:d="",dom:o=document}={}){if(N(r.doc,t,o).length)return p("stale","These blocks changed while AI was working, so nothing was changed.");let n=o.createElement("template");n.innerHTML=i??"";let h=[...n.content.children],a=h.length===1?h[0]:null,g=a&&a.tagName==="DIV"&&(a.hasAttribute("data-clay-area")||!a.hasAttribute("data-id"))?a:null,b=o.createElement("article");b.append(...g?g.childNodes:n.content.childNodes);let f=Y(b);if(!f.length)return p("empty","AI did not write any blocks. Try again.");let y=new Set(t.ids);if(f=f.map(e=>e.id&&!y.has(e.id)?{...e,id:null}:e),f.some(e=>!(e.id&&t.held.has(e.id))&&!$.has(e.t)))return p("active","AI used formatting this editor cannot put in a document. Try again.");let s=new Map(t.span.map(e=>[e.id,e])),w=new Set(f.map(e=>e.id).filter(Boolean)),v=0,q=f.map(e=>{if(e.id){let R=t.ids.indexOf(e.id);return R>=0&&(v=R+1),e}let c=t.ids[v],D=c?s.get(c):null;return!c||w.has(c)||!D||D.t!==e.t?e:(w.add(c),v++,{...e,id:c})}).map(e=>{let c=e.id?s.get(e.id):null;return c?.t==="table"&&e.t==="table"&&Array.isArray(e.cols)&&Array.isArray(c.cols)?V(e,c):e}),k=new Set(t.baseItems.filter(e=>!s.has(e.id)).map(e=>e.id)),u=x(q,{seed:d,known:s,taken:k});for(let e=0;e<4&&u.some(c=>k.has(c.id));e++)u=x(q,{seed:K(),known:s,taken:k});if(u.some(e=>k.has(e.id)))return p("active","The new blocks from AI could not be added to the document. Try again.");u=u.map(e=>e.id&&t.held.has(e.id)?{...t.held.get(e.id)}:e),u=u.map(e=>{let c=e.id?s.get(e.id):null;return c&&c.t===e.t?G(c,e):e}),t.parent!==null&&(u=u.map(e=>e.parent?e:{...e,parent:t.parent}));let T=E(t.blocks,[...t.before,...u,...t.after],t.baseItems);if(!T)return p("no-change","AI did not change anything.");let C=M(r,T);if(!C)return p("no-change","AI did not change anything.");let _=new Map;return C.doc.forEach(e=>_.set(e.attrs.id,e)),{status:"ready",plan:T,reply:u,nodes:u.map(e=>_.get(e.id)).filter(Boolean)}}function te(r,t,i,d=document){let o=N(r.doc,t,d);if(o.length)return{status:"stale",ids:o};let l=A(m(r.doc)),n=I(l,d),h=n.findIndex(f=>f.id===t.ids[0]);if(h<0)return{status:"stale",ids:[...t.ids]};let a=h+t.ids.length-1,g=E(l,[...n.slice(0,h),...i.reply,...n.slice(a+1)],n);if(!g)return{status:"stale",ids:[]};let b=M(r,g);return b?{status:"ok",tr:B(b)}:{status:"stale",ids:[]}}export{Q as AREA_GUIDE,Z as captureArea,te as keepAreaTransaction,ee as proposeArea,N as staleIds};
1
+ import{b as E,d as A,e as M,f as I}from"./c-LS7IVQVW.js";import"./c-NEQRFC4O.js";import"./c-GO635CRU.js";import"./c-V2V5FKXX.js";import"./c-7K4SCQB7.js";import"./c-WMRJKQ2V.js";import{C as B}from"./c-AI3H6ETU.js";import{E as m,fa as S,ia as L,ja as O,la as Y,ma as x}from"./c-OH2FPYSY.js";import"./c-RETTCOWO.js";import"./c-57XDY6HC.js";import"./c-VHNSBD2M.js";var Q="This element holds blocks from a document editor. Reply with the same outer div. Inside it use p, h1, h2, h3, ul, ol, li, blockquote, pre with code, details with summary, hr, table with thead, tbody, tr, th, td, and the inline tags strong, em, s, u, code, a. You may also keep any tag already in the element. Keep each data-id on the block it belongs to, and give a new block no data-id. An hr with data-clay-keep stands for something you cannot see: keep it where it belongs unless the request says to remove it. Keep each checkbox on a list item unless the request says to remove it. No classes, no style attributes, no scripts.",U=new Set(["image","file","chart","board","toc","tool","preserved"]),$=new Set(["paragraph","heading","list_item","quote","callout","code_block","toggle","divider","table"]),p=(r,t)=>({status:"refused",code:r,message:t}),H=({id:r,parent:t,...i})=>({...i,parent:t??null}),F=(r,t)=>S(H(r))===S(H(t)),K=()=>globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`,P=["owner","due","pageIcon","pageCoverSrc","pageCoverAlt","pageCoverX","pageCoverY"],G=(r,t)=>{let i={...t};for(let d of P)(i[d]===void 0||i[d]===null)&&r[d]!==void 0&&(i[d]=r[d]);return i},V=(r,t)=>{let i=new Set(r.cols.map(o=>o.id).filter(Boolean)),d=r.cols.map((o,l)=>{if(o.id)return o;let n=t.cols[l];return!n?.id||i.has(n.id)?o:(i.add(n.id),{...o,id:n.id})}).map(o=>{let l=o.id?t.cols.find(h=>h.id===o.id):null;if(!l)return o;let n={...o};return n.kind===void 0&&l.kind!==void 0&&(n.kind=l.kind),n.width===void 0&&l.width!==void 0&&(n.width=l.width),n});return{...r,cols:d}};function Z(r,t,{dom:i=document}={}){let d=m(r);if(t.some(s=>d[s]?.t==="opaque_block"))return p("opaque","This area holds a block this editor cannot rewrite.");let o=I(A(d),i),l=new Set(t),n=o.filter(s=>l.has(s.id));if(n.length!==t.length)return p("not-found","Some of these blocks are no longer in the document.");let h=new Map,a=new Map,g=n.map(s=>{let w=d[s.id]?.t??s.t;return U.has(w)?(h.set(s.id,s),a.set(s.id,w),{id:s.id,t:"divider",parent:s.parent}):s});if(n.every(s=>h.has(s.id)))return p("no-text","This area holds nothing that can be rewritten.");let b=i.createElement("template");b.innerHTML=O(g,{clean:L(i)});for(let s of b.content.querySelectorAll("hr[data-id]")){let w=s.getAttribute("data-id");h.has(w)&&s.setAttribute("data-clay-keep",a.get(w))}let f=o.indexOf(n[0]),y=o.indexOf(n[n.length-1]);return y-f+1!==n.length?p("not-found","These blocks are not next to each other."):{status:"ok",capture:{ids:n.map(s=>s.id),blocks:d,baseItems:o,before:o.slice(0,f),span:n,after:o.slice(y+1),parent:n[0].parent??null,held:h,html:`<div data-clay-area>${b.innerHTML}</div>`}}}function N(r,t,i=document){let d=I(A(m(r)),i),o=new Map(d.map(a=>[a.id,a])),l=t.span.filter(a=>!o.has(a.id)||!F(a,o.get(a.id))).map(a=>a.id);if(l.length)return l;let n=d.findIndex(a=>a.id===t.ids[0]);return t.ids.every((a,g)=>d[n+g]?.id===a)?[]:[...t.ids]}function ee(r,t,i,{seed:d="",dom:o=document}={}){if(N(r.doc,t,o).length)return p("stale","These blocks changed while AI was working, so nothing was changed.");let n=o.createElement("template");n.innerHTML=i??"";let h=[...n.content.children],a=h.length===1?h[0]:null,g=a&&a.tagName==="DIV"&&(a.hasAttribute("data-clay-area")||!a.hasAttribute("data-id"))?a:null,b=o.createElement("article");b.append(...g?g.childNodes:n.content.childNodes);let f=Y(b);if(!f.length)return p("empty","AI did not write any blocks. Try again.");let y=new Set(t.ids);if(f=f.map(e=>e.id&&!y.has(e.id)?{...e,id:null}:e),f.some(e=>!(e.id&&t.held.has(e.id))&&!$.has(e.t)))return p("active","AI used formatting this editor cannot put in a document. Try again.");let s=new Map(t.span.map(e=>[e.id,e])),w=new Set(f.map(e=>e.id).filter(Boolean)),v=0,q=f.map(e=>{if(e.id){let R=t.ids.indexOf(e.id);return R>=0&&(v=R+1),e}let c=t.ids[v],D=c?s.get(c):null;return!c||w.has(c)||!D||D.t!==e.t?e:(w.add(c),v++,{...e,id:c})}).map(e=>{let c=e.id?s.get(e.id):null;return c?.t==="table"&&e.t==="table"&&Array.isArray(e.cols)&&Array.isArray(c.cols)?V(e,c):e}),k=new Set(t.baseItems.filter(e=>!s.has(e.id)).map(e=>e.id)),u=x(q,{seed:d,known:s,taken:k});for(let e=0;e<4&&u.some(c=>k.has(c.id));e++)u=x(q,{seed:K(),known:s,taken:k});if(u.some(e=>k.has(e.id)))return p("active","The new blocks from AI could not be added to the document. Try again.");u=u.map(e=>e.id&&t.held.has(e.id)?{...t.held.get(e.id)}:e),u=u.map(e=>{let c=e.id?s.get(e.id):null;return c&&c.t===e.t?G(c,e):e}),t.parent!==null&&(u=u.map(e=>e.parent?e:{...e,parent:t.parent}));let T=E(t.blocks,[...t.before,...u,...t.after],t.baseItems);if(!T)return p("no-change","AI did not change anything.");let C=M(r,T);if(!C)return p("no-change","AI did not change anything.");let _=new Map;return C.doc.forEach(e=>_.set(e.attrs.id,e)),{status:"ready",plan:T,reply:u,nodes:u.map(e=>_.get(e.id)).filter(Boolean)}}function te(r,t,i,d=document){let o=N(r.doc,t,d);if(o.length)return{status:"stale",ids:o};let l=A(m(r.doc)),n=I(l,d),h=n.findIndex(f=>f.id===t.ids[0]);if(h<0)return{status:"stale",ids:[...t.ids]};let a=h+t.ids.length-1,g=E(l,[...n.slice(0,h),...i.reply,...n.slice(a+1)],n);if(!g)return{status:"stale",ids:[]};let b=M(r,g);return b?{status:"ok",tr:B(b)}:{status:"stale",ids:[]}}export{Q as AREA_GUIDE,Z as captureArea,te as keepAreaTransaction,ee as proposeArea,N as staleIds};
@@ -1 +1 @@
1
- import{a as ce}from"./c-7WZSUTYP.js";import{i as ne,j as re}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 as se}from"./c-ZRGEN6QQ.js";import{A as N,F as ee,a as U,b as G,d as K,ea as te,ia as oe,o as Q,r as J,y as D,z as Z}from"./c-OH2FPYSY.js";import"./c-FSQXFG5T.js";import{b as Y}from"./c-RETTCOWO.js";import"./c-WCG6AKA7.js";import"./c-57XDY6HC.js";import{a as W}from"./c-I2SCCUEW.js";import"./c-PGSBXHUE.js";import"./c-VHNSBD2M.js";var ge="iframe, frame, frameset, object, embed, applet, meta, base, link, form, style, animate, set, animateMotion, animateTransform, portal",ye=/^(srcdoc|data|formaction|codebase|archive|ping|background|poster|lowsrc|dynsrc)$/i,we=/^\s*(javascript|vbscript|data):/i;function xe(o){let l=document.createElement("template");l.innerHTML=o;for(let c of l.content.querySelectorAll(ge))c.remove();for(let c of l.content.querySelectorAll("*"))for(let{name:i,value:h}of[...c.attributes])(ye.test(i)||we.test(h.replace(/[\u0000-\u0020]/g,"")))&&c.removeAttribute(i);return l.innerHTML}var F=2*1024*1024,ae=32,le=1e4,P=class extends Error{constructor(l,c){super(c),this.name="MarkdownImportError",this.code=l}},de="\uFFFC",pe={type:"hard_break"},ue=new Set(["paragraph","heading","list","blockquote","code","table","hr","html","def","space"]),Me=new TextEncoder,ie=K.marks,fe=o=>o.slice().sort((l,c)=>l.type.rank-c.type.rank);function j(o,l,c){return o.some(i=>i.type===ie[l])?o:fe([...o,ie[l].create(c)])}function Se(o,{images:l=!0,refused:c=[],unsupported:i=[]}={}){let h=[],k="",z=[],S=()=>{k&&h.push({c:k,m:z}),k="",z=[]},O=(A,b)=>{let d=String(A??"");if(!d)return;let C=Q(fe(b));k+=d;for(let g=0;g<d.length;g++)z.push(C)},$=A=>{k+=de,z.push("@"+JSON.stringify(A))},E=(A,b)=>{for(let d of A??[]){let C=d?.type;if(typeof C!="string")throw new P("malformed-input","A Markdown token has no type.");switch(C){case"text":Array.isArray(d.tokens)?E(d.tokens.filter(g=>typeof g?.type=="string"&&!ue.has(g.type)),b):O(d.text,b);break;case"escape":O(d.text,b);break;case"strong":E(d.tokens,j(b,"strong"));break;case"em":E(d.tokens,j(b,"em"));break;case"del":case"strike":E(d.tokens,j(b,"strike"));break;case"codespan":O(d.text,j(b,"code"));break;case"br":$(pe);break;case"link":{let g=U(d.href);g?E(d.tokens,j(b,"link",{href:g})):(c.push({type:"link",href:String(d.href??"")}),E(d.tokens,b));break}case"image":{let g={src:String(d.href??""),alt:String(d.text??""),title:d.title??""};if(!l){O(g.alt,b);break}S(),h.push({image:g});break}case"html":O(d.text??d.raw,b);break;case"checkbox":break;default:i.push({type:C,text:String(d.raw??d.text??"")}),O(d.raw??d.text,b);break}}};return E(o,[]),S(),{parts:h}}function me(o){if(!Array.isArray(o))throw new P("malformed-input","Markdown import needs the lexer's token list.");let l=0;for(let e of o){if(!e||typeof e!="object"||typeof e.type!="string")throw new P("malformed-input","A Markdown token has no type.");l+=Me.encode(String(e.raw??"")).length}if(l>F)throw new P("input-too-large",`Markdown import is limited to ${F} bytes; this file is ${l}.`);let c=[],i=[],h=[],k=new Set,z=e=>{let t=N(e);for(;k.has(t);)t=N(e);return k.add(t),t},S=e=>{if(c.length+1>le)throw new P("too-many-blocks",`Markdown import is limited to ${le} blocks.`);c.push(e)},O=e=>{let t=e.depth+1;if(t>ae)throw new P("nesting-too-deep",`Markdown import is limited to ${ae} levels of nesting.`);return t},$=(e,t,{c:n,m:u})=>{let r={t:e,...t,c:n};return u.some(Boolean)&&(r.m=J(u)),r},E=e=>{let t=G(e.src);return t?{t:"image",src:t,...e.alt?{alt:e.alt}:{},...e.title?{caption:e.title}:{}}:(h.push({type:"image",href:e.src}),e.alt?$("paragraph",{},{c:e.alt,m:[]}):null)},A=(e,t,n)=>{for(let u of n.parts){if(!u.image){S($(e,t,u));continue}let r=E(u.image);r&&S(r)}},b=(e,t)=>A(t.quote?"quote":"paragraph",{},e),d=(e,t={})=>Se(e,{refused:h,unsupported:i,...t}),C=e=>{let t=String(e.raw??e.text??"");i.push({type:e.type,text:t}),S({t:"code_block",lang:"markdown",c:t})},g=(e,t)=>{for(let n of e??[]){let u=n?.type;if(typeof u!="string")throw new P("malformed-input","A Markdown token has no type.");switch(u){case"space":break;case"heading":{let r=Math.min(6,Math.max(1,Number.parseInt(n.depth,10)||1));A("heading",r===2?{}:{level:r},d(n.tokens,{images:!1}));break}case"paragraph":case"text":b(d(n.tokens??[n]),t);break;case"hr":S({t:"divider"});break;case"code":S({t:"code_block",...n.lang?{lang:String(n.lang)}:{},c:String(n.text??"")});break;case"html":{let r=String(n.text??n.raw??"");i.push({type:"HTML block cleaned",text:r}),S({t:"preserved",html:xe(oe(document).fallback(r))});break}case"blockquote":{let r=O(t);g(n.tokens,{...t,depth:r,quote:!0});break}case"list":{let r=O(t),s=t.indent??0,f=n.ordered?"ordered":"bullet";for(let a of n.items??[]){let m={c:"",m:[]},p=[];for(let y of a?.tokens??[]){let M=y?.type;if(!(M==="checkbox"||M==="space"))if(M==="text"||M==="paragraph"){m.c&&(m={c:m.c+de,m:[...m.m,"@"+JSON.stringify(pe)]});let v=M==="paragraph"?y.tokens??[]:[y];for(let x of d(v,{images:!1}).parts)m={c:m.c+x.c,m:[...m.m,...x.m]};p.push(...(y.tokens??[]).filter(x=>typeof x?.type=="string"&&ue.has(x.type)&&x.type!=="space"))}else p.push(y)}let w=a?.task?"check":f,B={...w==="bullet"?{}:{kind:w},...s?{indent:s}:{},...a?.task&&a.checked?{checked:!0}:{}};S($("list_item",B,m)),p.length&&g(p,{...t,depth:r,indent:s+1,quote:!1})}break}case"table":{let r=n.header??[];if(!r.length){C(n);break}let s=y=>d(y,{images:!1}).parts[0]??{c:"",m:[]},f=r.map(()=>z("c")),a=D(null,null,r.length),m=Object.fromEntries(f.map((y,M)=>[y,{pos:a[M],name:s(r[M]?.tokens).c}])),p=n.rows?.length?n.rows:[[]],w=D(null,null,p.length),B=p.map(y=>Object.fromEntries(f.map((M,v)=>{let x=s(y?.[v]?.tokens);return[M,x.m.some(Boolean)?{c:x.c,m:J(x.m)}:x.c]})));S({t:"table",cols:m,rows:Object.fromEntries(B.map((y,M)=>[z("r"),{pos:w[M],cells:y}]))});break}default:C(n);break}}};g(o,{depth:0,indent:0,quote:!1});let _=D(null,null,c.length),R={};return c.forEach((e,t)=>{R[z("b")]={...e,pos:_[t]}}),{blocks:R,unsupported:i,refused:h}}var Ee="markdown-import-preview",Te=new TextEncoder,Ae=o=>{let l=String(o??"").replace(/\s+/g," ").trim();return l.length>60?`${l.slice(0,60)}\u2026`:l},Oe=o=>typeof o.text=="function"?o.text():new Promise((l,c)=>{let i=new FileReader;i.onload=()=>l(i.result),i.onerror=()=>c(i.error),i.readAsText(o)}),ze=()=>globalThis.clay?.assets?.load?.("marked")??import("./c-XN6MBKI6.js"),$e=(o,l)=>{let c=-1;return o.forEach((i,h,k)=>{c<0&&i.attrs.id===l&&(c=k)}),c};function Ce(o){let l=o.selection.$from;if(l.depth>=1)return{node:l.node(1),at:l.before(1),textblock:l.parent.isTextblock};let c=Math.min(l.index(0),Math.max(0,o.doc.childCount-1)),i=0;for(let h=0;h<c;h++)i+=o.doc.child(h).nodeSize;return{node:o.doc.child(c),at:i,textblock:!1}}function ve(o){let{node:l,at:c,textblock:i}=Ce(o),h=o.selection,k=i?Math.max(0,h.from-c-1):0;return{id:l.attrs.id,textblock:i,size:l.isTextblock?l.content.size:0,fromOff:k,toOff:i?Math.max(k,h.to-c-1):0}}var Pe=o=>{try{return ce(te(o))>0}catch{return!0}},Be=o=>o?.code==="blockeditor-format-upgrade-required"?"This document needs a newer page format before Markdown can be added. The preview stays open.":o?.code==="blockeditor-format-unsupported"?"This host cannot record the newer page format this file needs. The preview stays open.":o?.code==="stale-target"?"The place this import was started from changed. The preview stays open.":o?.code==="empty-import"?"This file holds nothing that can be inserted.":"The Markdown could not be inserted. The preview stays open.";function Ue({view:o=null,load:l=ze}={}){if(!o)return{run:()=>Promise.resolve({ok:!1,code:"not-editing"}),dispose(){}};let c=o.dom.ownerDocument,i=null,h=null,k=!1,z=W({id:Ee,isPending:()=>i!==null}),S=()=>h??=Promise.resolve().then(l).catch(e=>{throw h=null,e});function O(){try{let e=o.dom.parentElement?.getBoundingClientRect?.()??{left:0,top:0},t=o.coordsAtPos(Math.min(o.state.selection.from,o.state.doc.content.size));return{x:Math.max(8,t.left-e.left),y:t.bottom+6-e.top}}catch{return null}}function $(){let e=i;if(!e)return!1;i=null;for(let[t,n,u,r]of e.listen)t.removeEventListener(n,u,r);return e.panel.remove(),!0}function E(){return $()?(o.focus?.(),{ok:!0,cancelled:!0}):{ok:!1,code:"cancelled"}}function A(e){let t=[],n=(a,m)=>{let p=c.createElement("div");return p.className=a,p.textContent=m,p};if(t.push(n("blockeditor-menu-title",e.error?"Couldn't read that Markdown":`Import ${e.name}`)),!e.error){let a=[`${e.count} block${e.count===1?"":"s"}`];e.unsupported.length&&a.push(`${e.unsupported.length} kept as written`),e.refused.length&&a.push(`${e.refused.length} address${e.refused.length===1?"":"es"} left out`),t.push(n("blockeditor-menu-title blockeditor-import-summary",a.join(" \xB7 ")))}let u=(a,m)=>{let p=c.createElement("div");return p.className=a,p.replaceChildren(...m.map(w=>n("blockeditor-import-row",w))),p};e.unsupported.length&&t.push(u("blockeditor-import-unsupported",e.unsupported.map(a=>`${a.type}: ${Ae(a.text)}`))),e.refused.length&&t.push(u("blockeditor-import-refused",e.refused.map(a=>`${a.type}: ${a.href}`)));let r=e.error??e.notice??null;if(r){let a=c.createElement("p");a.className="blockeditor-import-error",a.setAttribute("role","alert"),a.textContent=r,t.push(a)}let s=(a,m)=>{let p=c.createElement("button");return p.type="button",p.className="blockeditor-menu-item",p.dataset.import=a,p.textContent=m,p.addEventListener("mousedown",w=>w.preventDefault()),p.addEventListener("click",()=>a==="insert"?d():E()),p},f=s("insert","Insert at the selection");f.disabled=!!e.error,t.push(f,s("cancel","Cancel")),e.panel.replaceChildren(...t)}function b(e,t){let n=o.state,u=n.doc,r=$e(u,e.id);if(r<0)return{ok:!1,code:"stale-target"};let s=u.child(r);if(e.textblock?!s.isTextblock||s.content.size!==e.size:s.isTextblock)return{ok:!1,code:"stale-target"};let f=Z(t).map(T=>ee(K,T,{...t[T],pos:null,parent:null}));if(!f.length)return{ok:!1,code:"empty-import"};let a=0;for(let T=0;T<r;T++)a+=u.child(T).nodeSize;let m=u.maybeChild(r+1),p=s.type.name==="toggle",w=e.textblock&&!p&&s.content.size>0,B=w||e.textblock&&!p&&s.content.size===0,y=w?Math.min(e.fromOff,s.content.size):0,M=w?Math.min(Math.max(y,e.toOff),s.content.size):0,v=w&&y>0?s.type.create({...s.attrs},s.content.cut(0,y)):null,x=w?s.content.cut(M):null,I=x&&x.size?s.type.create({...s.attrs,id:N(),pos:null},x):null,he=w&&!v?r>0?u.child(r-1).attrs.pos:null:s.attrs.pos,V=D(he,m?.attrs.pos??null,f.length+(I?1:0)),ke=p?s.attrs.id:s.attrs.parent??null,L=f.map((T,be)=>T.type.create({...T.attrs,pos:V[be],parent:ke},T.content,T.marks)),H=I?I.type.create({...I.attrs,pos:V[f.length]},I.content,I.marks):null,q=n.tr;B?q.replaceWith(a,a+s.nodeSize,[...v?[v]:[],...L,...H?[H]:[]]):q.insert(a+s.nodeSize,L),p&&!s.attrs.open&&L.length>0&&q.setNodeMarkup(a,null,{...s.attrs,open:!0});let X=a+(B?v?v.nodeSize:0:s.nodeSize);for(let T of L)X+=T.nodeSize;return q.setSelection(Y.TextSelection.near(q.doc.resolve(H?X:Math.max(0,X-1)),H?1:-1)),o.dispatch(se(q).scrollIntoView()),o.focus?.(),{ok:!0,blocks:L.length}}async function d(){let e=i;if(!e||e.error)return e?{ok:!1,code:"no-import"}:{ok:!1,code:"not-editing"};e.notice&&(e.notice=null,A(e));let t=()=>b(e.target,e.blocks),n=e.floor?await ne(o,t):t();return n?.ok?($(),n):(i===e&&(e.notice=Be(n),A(e)),n??{ok:!1,code:"import-failed"})}function C(e){!i||re(e,o)||(e.key==="Escape"?(e.preventDefault(),e.stopPropagation(),E()):e.key==="Enter"&&!e.target?.closest?.("[data-import]")&&(e.preventDefault(),e.stopPropagation(),d()))}function g(){return new Promise(e=>{let t=c.createElement("input");t.type="file",t.accept=".md,.markdown,text/markdown,text/plain",t.hidden=!0,t.className="blockeditor-markdown-input";let n=u=>{t.remove(),e(u)};t.addEventListener("change",()=>n(t.files?.[0]??null)),t.addEventListener("cancel",()=>n(null)),(o.dom.parentElement??c.body).appendChild(t),t.click()})}async function _(e,t=null){e.error=t;let n=c.createElement("div");n.className="blockeditor-menu blockeditor-import-preview",n.setAttribute("role","dialog"),n.setAttribute("aria-label","Import Markdown"),e.panel=n,i=e;let u=(f,a,m,p)=>{f.addEventListener(a,m,p),e.listen.push([f,a,m,p])};u(c,"keydown",f=>C(f),!0),u(c,"mousedown",f=>{e.panel.contains(f.target)||E()},!0),(o.dom.parentElement??c.body).appendChild(n),A(e);let r=O();r&&(n.style.setProperty("--blockeditor-pop-x",`${r.x}px`),n.style.setProperty("--blockeditor-pop-y",`${r.y}px`));let s=n.querySelector('[data-import="insert"]');return s&&!s.disabled&&s.focus?.(),{ok:!0,preview:!0}}async function R(e={}){if(k||o.isDestroyed)return{ok:!1,code:"not-editing"};$();let t=ve(o.state),n=e?.file??await g();if(!n)return{ok:!1,code:"cancelled"};if(typeof n.size=="number"&&n.size>F)return{ok:!1,code:"input-too-large"};let u;try{u=await Oe(n)}catch(f){return{ok:!1,code:"unreadable",error:f}}if(k||o.isDestroyed)return{ok:!1,code:"not-editing"};if(Te.encode(u).length>F)return{ok:!1,code:"input-too-large"};let r={target:t,name:String(n.name??"Markdown"),blocks:{},count:0,unsupported:[],refused:[],floor:0,panel:null,error:null,notice:null,listen:[]},s;try{let f=await S();s=me(new f.Marked().lexer(u))}catch(f){return k||o.isDestroyed?{ok:!1,code:"not-editing"}:_(r,String(f?.message??"The Markdown could not be read."))}return k||o.isDestroyed?{ok:!1,code:"not-editing"}:(r.blocks=s.blocks,r.count=Object.keys(s.blocks).length,r.unsupported=s.unsupported,r.refused=s.refused,r.floor=Pe(s.blocks)?1:0,_(r))}return{async run(e){return R(e)},dispose(){k=!0,$(),z.dispose()}}}export{Ue as createFeature};
1
+ import{a as ce}from"./c-7WZSUTYP.js";import{i as ne,j as re}from"./c-JWW6BHWD.js";import"./c-GO635CRU.js";import"./c-V2V5FKXX.js";import"./c-DT7E76Z2.js";import"./c-C6YZNU6E.js";import"./c-7K4SCQB7.js";import"./c-WMRJKQ2V.js";import{C as se}from"./c-AI3H6ETU.js";import{A as N,F as ee,a as U,b as G,d as K,ea as te,ia as oe,o as Q,r as J,y as D,z as Z}from"./c-OH2FPYSY.js";import"./c-FSQXFG5T.js";import{b as Y}from"./c-RETTCOWO.js";import"./c-WCG6AKA7.js";import"./c-57XDY6HC.js";import{a as W}from"./c-I2SCCUEW.js";import"./c-PGSBXHUE.js";import"./c-VHNSBD2M.js";var ge="iframe, frame, frameset, object, embed, applet, meta, base, link, form, style, animate, set, animateMotion, animateTransform, portal",ye=/^(srcdoc|data|formaction|codebase|archive|ping|background|poster|lowsrc|dynsrc)$/i,we=/^\s*(javascript|vbscript|data):/i;function xe(o){let l=document.createElement("template");l.innerHTML=o;for(let c of l.content.querySelectorAll(ge))c.remove();for(let c of l.content.querySelectorAll("*"))for(let{name:i,value:h}of[...c.attributes])(ye.test(i)||we.test(h.replace(/[\u0000-\u0020]/g,"")))&&c.removeAttribute(i);return l.innerHTML}var F=2*1024*1024,ae=32,le=1e4,P=class extends Error{constructor(l,c){super(c),this.name="MarkdownImportError",this.code=l}},de="\uFFFC",pe={type:"hard_break"},ue=new Set(["paragraph","heading","list","blockquote","code","table","hr","html","def","space"]),Me=new TextEncoder,ie=K.marks,fe=o=>o.slice().sort((l,c)=>l.type.rank-c.type.rank);function j(o,l,c){return o.some(i=>i.type===ie[l])?o:fe([...o,ie[l].create(c)])}function Se(o,{images:l=!0,refused:c=[],unsupported:i=[]}={}){let h=[],k="",z=[],S=()=>{k&&h.push({c:k,m:z}),k="",z=[]},O=(A,b)=>{let d=String(A??"");if(!d)return;let C=Q(fe(b));k+=d;for(let g=0;g<d.length;g++)z.push(C)},$=A=>{k+=de,z.push("@"+JSON.stringify(A))},E=(A,b)=>{for(let d of A??[]){let C=d?.type;if(typeof C!="string")throw new P("malformed-input","A Markdown token has no type.");switch(C){case"text":Array.isArray(d.tokens)?E(d.tokens.filter(g=>typeof g?.type=="string"&&!ue.has(g.type)),b):O(d.text,b);break;case"escape":O(d.text,b);break;case"strong":E(d.tokens,j(b,"strong"));break;case"em":E(d.tokens,j(b,"em"));break;case"del":case"strike":E(d.tokens,j(b,"strike"));break;case"codespan":O(d.text,j(b,"code"));break;case"br":$(pe);break;case"link":{let g=U(d.href);g?E(d.tokens,j(b,"link",{href:g})):(c.push({type:"link",href:String(d.href??"")}),E(d.tokens,b));break}case"image":{let g={src:String(d.href??""),alt:String(d.text??""),title:d.title??""};if(!l){O(g.alt,b);break}S(),h.push({image:g});break}case"html":O(d.text??d.raw,b);break;case"checkbox":break;default:i.push({type:C,text:String(d.raw??d.text??"")}),O(d.raw??d.text,b);break}}};return E(o,[]),S(),{parts:h}}function me(o){if(!Array.isArray(o))throw new P("malformed-input","Markdown import needs the lexer's token list.");let l=0;for(let e of o){if(!e||typeof e!="object"||typeof e.type!="string")throw new P("malformed-input","A Markdown token has no type.");l+=Me.encode(String(e.raw??"")).length}if(l>F)throw new P("input-too-large",`Markdown import is limited to ${F} bytes; this file is ${l}.`);let c=[],i=[],h=[],k=new Set,z=e=>{let t=N(e);for(;k.has(t);)t=N(e);return k.add(t),t},S=e=>{if(c.length+1>le)throw new P("too-many-blocks",`Markdown import is limited to ${le} blocks.`);c.push(e)},O=e=>{let t=e.depth+1;if(t>ae)throw new P("nesting-too-deep",`Markdown import is limited to ${ae} levels of nesting.`);return t},$=(e,t,{c:n,m:u})=>{let r={t:e,...t,c:n};return u.some(Boolean)&&(r.m=J(u)),r},E=e=>{let t=G(e.src);return t?{t:"image",src:t,...e.alt?{alt:e.alt}:{},...e.title?{caption:e.title}:{}}:(h.push({type:"image",href:e.src}),e.alt?$("paragraph",{},{c:e.alt,m:[]}):null)},A=(e,t,n)=>{for(let u of n.parts){if(!u.image){S($(e,t,u));continue}let r=E(u.image);r&&S(r)}},b=(e,t)=>A(t.quote?"quote":"paragraph",{},e),d=(e,t={})=>Se(e,{refused:h,unsupported:i,...t}),C=e=>{let t=String(e.raw??e.text??"");i.push({type:e.type,text:t}),S({t:"code_block",lang:"markdown",c:t})},g=(e,t)=>{for(let n of e??[]){let u=n?.type;if(typeof u!="string")throw new P("malformed-input","A Markdown token has no type.");switch(u){case"space":break;case"heading":{let r=Math.min(6,Math.max(1,Number.parseInt(n.depth,10)||1));A("heading",r===2?{}:{level:r},d(n.tokens,{images:!1}));break}case"paragraph":case"text":b(d(n.tokens??[n]),t);break;case"hr":S({t:"divider"});break;case"code":S({t:"code_block",...n.lang?{lang:String(n.lang)}:{},c:String(n.text??"")});break;case"html":{let r=String(n.text??n.raw??"");i.push({type:"HTML block cleaned",text:r}),S({t:"preserved",html:xe(oe(document).fallback(r))});break}case"blockquote":{let r=O(t);g(n.tokens,{...t,depth:r,quote:!0});break}case"list":{let r=O(t),s=t.indent??0,f=n.ordered?"ordered":"bullet";for(let a of n.items??[]){let m={c:"",m:[]},p=[];for(let y of a?.tokens??[]){let M=y?.type;if(!(M==="checkbox"||M==="space"))if(M==="text"||M==="paragraph"){m.c&&(m={c:m.c+de,m:[...m.m,"@"+JSON.stringify(pe)]});let v=M==="paragraph"?y.tokens??[]:[y];for(let x of d(v,{images:!1}).parts)m={c:m.c+x.c,m:[...m.m,...x.m]};p.push(...(y.tokens??[]).filter(x=>typeof x?.type=="string"&&ue.has(x.type)&&x.type!=="space"))}else p.push(y)}let w=a?.task?"check":f,B={...w==="bullet"?{}:{kind:w},...s?{indent:s}:{},...a?.task&&a.checked?{checked:!0}:{}};S($("list_item",B,m)),p.length&&g(p,{...t,depth:r,indent:s+1,quote:!1})}break}case"table":{let r=n.header??[];if(!r.length){C(n);break}let s=y=>d(y,{images:!1}).parts[0]??{c:"",m:[]},f=r.map(()=>z("c")),a=D(null,null,r.length),m=Object.fromEntries(f.map((y,M)=>[y,{pos:a[M],name:s(r[M]?.tokens).c}])),p=n.rows?.length?n.rows:[[]],w=D(null,null,p.length),B=p.map(y=>Object.fromEntries(f.map((M,v)=>{let x=s(y?.[v]?.tokens);return[M,x.m.some(Boolean)?{c:x.c,m:J(x.m)}:x.c]})));S({t:"table",cols:m,rows:Object.fromEntries(B.map((y,M)=>[z("r"),{pos:w[M],cells:y}]))});break}default:C(n);break}}};g(o,{depth:0,indent:0,quote:!1});let _=D(null,null,c.length),R={};return c.forEach((e,t)=>{R[z("b")]={...e,pos:_[t]}}),{blocks:R,unsupported:i,refused:h}}var Ee="markdown-import-preview",Te=new TextEncoder,Ae=o=>{let l=String(o??"").replace(/\s+/g," ").trim();return l.length>60?`${l.slice(0,60)}\u2026`:l},Oe=o=>typeof o.text=="function"?o.text():new Promise((l,c)=>{let i=new FileReader;i.onload=()=>l(i.result),i.onerror=()=>c(i.error),i.readAsText(o)}),ze=()=>globalThis.clay?.assets?.load?.("marked")??import("./c-XN6MBKI6.js"),$e=(o,l)=>{let c=-1;return o.forEach((i,h,k)=>{c<0&&i.attrs.id===l&&(c=k)}),c};function Ce(o){let l=o.selection.$from;if(l.depth>=1)return{node:l.node(1),at:l.before(1),textblock:l.parent.isTextblock};let c=Math.min(l.index(0),Math.max(0,o.doc.childCount-1)),i=0;for(let h=0;h<c;h++)i+=o.doc.child(h).nodeSize;return{node:o.doc.child(c),at:i,textblock:!1}}function ve(o){let{node:l,at:c,textblock:i}=Ce(o),h=o.selection,k=i?Math.max(0,h.from-c-1):0;return{id:l.attrs.id,textblock:i,size:l.isTextblock?l.content.size:0,fromOff:k,toOff:i?Math.max(k,h.to-c-1):0}}var Pe=o=>{try{return ce(te(o))>0}catch{return!0}},Be=o=>o?.code==="blockeditor-format-upgrade-required"?"This document needs a newer page format before Markdown can be added. The preview stays open.":o?.code==="blockeditor-format-unsupported"?"This host cannot record the newer page format this file needs. The preview stays open.":o?.code==="stale-target"?"The place this import was started from changed. The preview stays open.":o?.code==="empty-import"?"This file holds nothing that can be inserted.":"The Markdown could not be inserted. The preview stays open.";function Ue({view:o=null,load:l=ze}={}){if(!o)return{run:()=>Promise.resolve({ok:!1,code:"not-editing"}),dispose(){}};let c=o.dom.ownerDocument,i=null,h=null,k=!1,z=W({id:Ee,isPending:()=>i!==null}),S=()=>h??=Promise.resolve().then(l).catch(e=>{throw h=null,e});function O(){try{let e=o.dom.parentElement?.getBoundingClientRect?.()??{left:0,top:0},t=o.coordsAtPos(Math.min(o.state.selection.from,o.state.doc.content.size));return{x:Math.max(8,t.left-e.left),y:t.bottom+6-e.top}}catch{return null}}function $(){let e=i;if(!e)return!1;i=null;for(let[t,n,u,r]of e.listen)t.removeEventListener(n,u,r);return e.panel.remove(),!0}function E(){return $()?(o.focus?.(),{ok:!0,cancelled:!0}):{ok:!1,code:"cancelled"}}function A(e){let t=[],n=(a,m)=>{let p=c.createElement("div");return p.className=a,p.textContent=m,p};if(t.push(n("blockeditor-menu-title",e.error?"Couldn't read that Markdown":`Import ${e.name}`)),!e.error){let a=[`${e.count} block${e.count===1?"":"s"}`];e.unsupported.length&&a.push(`${e.unsupported.length} kept as written`),e.refused.length&&a.push(`${e.refused.length} address${e.refused.length===1?"":"es"} left out`),t.push(n("blockeditor-menu-title blockeditor-import-summary",a.join(" \xB7 ")))}let u=(a,m)=>{let p=c.createElement("div");return p.className=a,p.replaceChildren(...m.map(w=>n("blockeditor-import-row",w))),p};e.unsupported.length&&t.push(u("blockeditor-import-unsupported",e.unsupported.map(a=>`${a.type}: ${Ae(a.text)}`))),e.refused.length&&t.push(u("blockeditor-import-refused",e.refused.map(a=>`${a.type}: ${a.href}`)));let r=e.error??e.notice??null;if(r){let a=c.createElement("p");a.className="blockeditor-import-error",a.setAttribute("role","alert"),a.textContent=r,t.push(a)}let s=(a,m)=>{let p=c.createElement("button");return p.type="button",p.className="blockeditor-menu-item",p.dataset.import=a,p.textContent=m,p.addEventListener("mousedown",w=>w.preventDefault()),p.addEventListener("click",()=>a==="insert"?d():E()),p},f=s("insert","Insert at the selection");f.disabled=!!e.error,t.push(f,s("cancel","Cancel")),e.panel.replaceChildren(...t)}function b(e,t){let n=o.state,u=n.doc,r=$e(u,e.id);if(r<0)return{ok:!1,code:"stale-target"};let s=u.child(r);if(e.textblock?!s.isTextblock||s.content.size!==e.size:s.isTextblock)return{ok:!1,code:"stale-target"};let f=Z(t).map(T=>ee(K,T,{...t[T],pos:null,parent:null}));if(!f.length)return{ok:!1,code:"empty-import"};let a=0;for(let T=0;T<r;T++)a+=u.child(T).nodeSize;let m=u.maybeChild(r+1),p=s.type.name==="toggle",w=e.textblock&&!p&&s.content.size>0,B=w||e.textblock&&!p&&s.content.size===0,y=w?Math.min(e.fromOff,s.content.size):0,M=w?Math.min(Math.max(y,e.toOff),s.content.size):0,v=w&&y>0?s.type.create({...s.attrs},s.content.cut(0,y)):null,x=w?s.content.cut(M):null,I=x&&x.size?s.type.create({...s.attrs,id:N(),pos:null},x):null,he=w&&!v?r>0?u.child(r-1).attrs.pos:null:s.attrs.pos,V=D(he,m?.attrs.pos??null,f.length+(I?1:0)),ke=p?s.attrs.id:s.attrs.parent??null,L=f.map((T,be)=>T.type.create({...T.attrs,pos:V[be],parent:ke},T.content,T.marks)),H=I?I.type.create({...I.attrs,pos:V[f.length]},I.content,I.marks):null,q=n.tr;B?q.replaceWith(a,a+s.nodeSize,[...v?[v]:[],...L,...H?[H]:[]]):q.insert(a+s.nodeSize,L),p&&!s.attrs.open&&L.length>0&&q.setNodeMarkup(a,null,{...s.attrs,open:!0});let X=a+(B?v?v.nodeSize:0:s.nodeSize);for(let T of L)X+=T.nodeSize;return q.setSelection(Y.TextSelection.near(q.doc.resolve(H?X:Math.max(0,X-1)),H?1:-1)),o.dispatch(se(q).scrollIntoView()),o.focus?.(),{ok:!0,blocks:L.length}}async function d(){let e=i;if(!e||e.error)return e?{ok:!1,code:"no-import"}:{ok:!1,code:"not-editing"};e.notice&&(e.notice=null,A(e));let t=()=>b(e.target,e.blocks),n=e.floor?await ne(o,t):t();return n?.ok?($(),n):(i===e&&(e.notice=Be(n),A(e)),n??{ok:!1,code:"import-failed"})}function C(e){!i||re(e,o)||(e.key==="Escape"?(e.preventDefault(),e.stopPropagation(),E()):e.key==="Enter"&&!e.target?.closest?.("[data-import]")&&(e.preventDefault(),e.stopPropagation(),d()))}function g(){return new Promise(e=>{let t=c.createElement("input");t.type="file",t.accept=".md,.markdown,text/markdown,text/plain",t.hidden=!0,t.className="blockeditor-markdown-input";let n=u=>{t.remove(),e(u)};t.addEventListener("change",()=>n(t.files?.[0]??null)),t.addEventListener("cancel",()=>n(null)),(o.dom.parentElement??c.body).appendChild(t),t.click()})}async function _(e,t=null){e.error=t;let n=c.createElement("div");n.className="blockeditor-menu blockeditor-import-preview",n.setAttribute("role","dialog"),n.setAttribute("aria-label","Import Markdown"),e.panel=n,i=e;let u=(f,a,m,p)=>{f.addEventListener(a,m,p),e.listen.push([f,a,m,p])};u(c,"keydown",f=>C(f),!0),u(c,"mousedown",f=>{e.panel.contains(f.target)||E()},!0),(o.dom.parentElement??c.body).appendChild(n),A(e);let r=O();r&&(n.style.setProperty("--blockeditor-pop-x",`${r.x}px`),n.style.setProperty("--blockeditor-pop-y",`${r.y}px`));let s=n.querySelector('[data-import="insert"]');return s&&!s.disabled&&s.focus?.(),{ok:!0,preview:!0}}async function R(e={}){if(k||o.isDestroyed)return{ok:!1,code:"not-editing"};$();let t=ve(o.state),n=e?.file??await g();if(!n)return{ok:!1,code:"cancelled"};if(typeof n.size=="number"&&n.size>F)return{ok:!1,code:"input-too-large"};let u;try{u=await Oe(n)}catch(f){return{ok:!1,code:"unreadable",error:f}}if(k||o.isDestroyed)return{ok:!1,code:"not-editing"};if(Te.encode(u).length>F)return{ok:!1,code:"input-too-large"};let r={target:t,name:String(n.name??"Markdown"),blocks:{},count:0,unsupported:[],refused:[],floor:0,panel:null,error:null,notice:null,listen:[]},s;try{let f=await S();s=me(new f.Marked().lexer(u))}catch(f){return k||o.isDestroyed?{ok:!1,code:"not-editing"}:_(r,String(f?.message??"The Markdown could not be read."))}return k||o.isDestroyed?{ok:!1,code:"not-editing"}:(r.blocks=s.blocks,r.count=Object.keys(s.blocks).length,r.unsupported=s.unsupported,r.refused=s.refused,r.floor=Pe(s.blocks)?1:0,_(r))}return{async run(e){return R(e)},dispose(){k=!0,$(),z.dispose()}}}export{Ue as createFeature};
@@ -0,0 +1 @@
1
+ import{e as a,f as b,g as c}from"./c-VO6RSFCO.js";import"./c-WN3MXOLT.js";import"./c-EQ5NBOGA.js";import"./c-C7SUMNMI.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-U4TWEIKZ.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};