@panphora/clayjs 1.26.1 → 1.26.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/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 +4 -3
  11. package/dist/m/{c-EQ5NBOGA.js → c-26W3BMWK.js} +1 -1
  12. package/dist/m/{c-AQVQKFKB.js → c-3JQY5MB2.js} +1 -1
  13. package/dist/m/{c-MKAUC6DB.js → c-3KG4SDZ5.js} +1 -1
  14. package/dist/m/{c-HYNM5U6B.js → c-5CJCIAFK.js} +1 -1
  15. package/dist/m/{c-O3DPFZCE.js → c-6266A3CU.js} +1 -1
  16. package/dist/m/{c-WOJ2RTV4.js → c-627JDXWT.js} +1 -1
  17. package/dist/m/{c-MMEVDN6D.js → c-7PZS45FY.js} +1 -1
  18. package/dist/m/{c-NYJ577NL.js → c-7RJCYD4F.js} +1 -1
  19. package/dist/m/{c-EHAR4RJJ.js → c-CKG4NF7J.js} +2 -2
  20. package/dist/m/{c-EXZOA6XY.js → c-E37MV4WS.js} +1 -1
  21. package/dist/m/{c-N4GEJMXW.js → c-EFXPKDJP.js} +1 -1
  22. package/dist/m/{c-ZPI7M5U5.js → c-G426P2SE.js} +1 -1
  23. package/dist/m/{c-BJ2RRQBQ.js → c-GXOUAT7E.js} +1 -1
  24. package/dist/m/{c-VU4WEWPH.js → c-H25R2UF3.js} +1 -1
  25. package/dist/m/{c-VO6RSFCO.js → c-HBSBQBD7.js} +1 -1
  26. package/dist/m/{c-CL5LSATX.js → c-I4ZVJZC7.js} +1 -1
  27. package/dist/m/{c-67TBU56I.js → c-I62KCFMW.js} +1 -1
  28. package/dist/m/{c-Y3MPVURA.js → c-IJ4VUYDN.js} +1 -1
  29. package/dist/m/{c-FC5RUFPR.js → c-IOJOJTPL.js} +1 -1
  30. package/dist/m/{c-HXGNH6GY.js → c-IPCSVZAB.js} +1 -1
  31. package/dist/m/c-JEWSJHMK.js +1 -0
  32. package/dist/m/{c-3F3AADKG.js → c-JOA4OJGK.js} +1 -1
  33. package/dist/m/{c-GFASNR55.js → c-JUSHNY3I.js} +1 -1
  34. package/dist/m/{c-7RHOMAMR.js → c-K5HRHUTK.js} +1 -1
  35. package/dist/m/{c-H3M6UDNV.js → c-KFXW6SZO.js} +1 -1
  36. package/dist/m/{c-EAV7A6BT.js → c-MB5FZ2PD.js} +1 -1
  37. package/dist/m/{c-2EPHRF47.js → c-MIQYK2VM.js} +1 -1
  38. package/dist/m/{c-ARO6CPMA.js → c-O3BSWMVD.js} +1 -1
  39. package/dist/m/{c-U35T5NAY.js → c-O54PVIAQ.js} +1 -1
  40. package/dist/m/{c-H4M2T4A6.js → c-OEEJRV2M.js} +1 -1
  41. package/dist/m/{c-KU3PX7LL.js → c-OSGTRM4C.js} +1 -1
  42. package/dist/m/{c-YZGWSCMT.js → c-QLGTY326.js} +1 -1
  43. package/dist/m/{c-WOWGGNCJ.js → c-RC37IFYT.js} +1 -1
  44. package/dist/m/{c-SMLAJASY.js → c-RHYX6KUH.js} +1 -1
  45. package/dist/m/{c-RGFPLQGV.js → c-SMCZC3V6.js} +1 -1
  46. package/dist/m/{c-P73XPAOA.js → c-T6RRRHX7.js} +1 -1
  47. package/dist/m/{c-3S5TNRZA.js → c-USO6XV23.js} +1 -1
  48. package/dist/m/{c-ZFAPQQIB.js → c-VPUSMVKE.js} +1 -1
  49. package/dist/m/{c-YYIN4NAF.js → c-VXJJ7BJL.js} +1 -1
  50. package/dist/m/{c-EEWPNUM2.js → c-W3DMFFGK.js} +1 -1
  51. package/dist/m/{c-755ZOHOM.js → c-W5HY5JHM.js} +1 -1
  52. package/dist/m/{c-C5UGNOC2.js → c-WJVW76R6.js} +1 -1
  53. package/dist/m/{c-Q2CB57UG.js → c-X3WLDGBX.js} +1 -1
  54. package/dist/m/{c-SRW5OBCF.js → c-XLVZN7DT.js} +1 -1
  55. package/dist/m/{c-3WX5FABT.js → c-YIFBOWQE.js} +1 -1
  56. package/dist/m/{c-34J5HC7N.js → c-YJS2V3MX.js} +1 -1
  57. package/dist/m/core/{admin-attrs-43JBA6JB.js → admin-attrs-H26XE2AE.js} +1 -1
  58. package/dist/m/core/{autosave-HD7Y7UNV.js → autosave-U5UIKPM3.js} +1 -1
  59. package/dist/m/core/{conflict-notice-UNDOD4BL.js → conflict-notice-HTF6CECH.js} +1 -1
  60. package/dist/m/core/{host-permission-5BYP24GC.js → host-permission-JHMPKRPO.js} +1 -1
  61. package/dist/m/core/{is-edit-mode-73OXKK5H.js → is-edit-mode-QBJUFMVF.js} +1 -1
  62. package/dist/m/core/{persist-MX3VYVBN.js → persist-TRXZPS6T.js} +1 -1
  63. package/dist/m/core/{recovery-VZF7RJZF.js → recovery-YJS7CI66.js} +1 -1
  64. package/dist/m/core/{save-JZ7R4ET2.js → save-KY3ZMPU4.js} +1 -1
  65. package/dist/m/core/{save-core-I4N6S4ED.js → save-core-LBW6DNJ6.js} +1 -1
  66. package/dist/m/core/{site-edits-C22O53GS.js → site-edits-M44KWAQN.js} +1 -1
  67. package/dist/m/core/{unsaved-warning-BP6ZY3PG.js → unsaved-warning-2X7NJNHZ.js} +1 -1
  68. package/dist/m/internals/{index-3LAVREAU.js → index-CDXUFQZK.js} +1 -1
  69. package/dist/m/{loader-RHUGUKXI.js → loader-CRCEH7TD.js} +1 -1
  70. package/dist/m/manifest-6D031725.js +1 -0
  71. package/dist/m/{manifest-edit-93AA79D7.js → manifest-edit-A75598BC.js} +1 -1
  72. package/dist/m/manifest.json +584 -584
  73. package/dist/m/plugins/{ai-edit-WDV2GLDU.js → ai-edit-T2SM7TRD.js} +1 -1
  74. package/dist/m/plugins/{demo-LMCMBILC.js → demo-57MJ3GOO.js} +1 -1
  75. package/dist/m/plugins/{indicator-OLPZ4WFI.js → indicator-D5PZJGVS.js} +1 -1
  76. package/dist/m/plugins/{live-DF5YS5AH.js → live-J52JO243.js} +1 -1
  77. package/dist/m/plugins/{menu-ESEFQARM.js → menu-KCCEDUMJ.js} +1 -1
  78. package/dist/m/plugins/{page-GZSU77JS.js → page-F7JG3JZX.js} +2 -2
  79. package/dist/m/plugins/{page-view-7MM3FEAR.js → page-view-QPRXXAT3.js} +1 -1
  80. package/dist/m/plugins/{people-EBWE337I.js → people-FEMXINJK.js} +1 -1
  81. package/dist/m/plugins/{richclay-MXH2GFAZ.js → richclay-XL64ZGOZ.js} +2 -2
  82. package/dist/m/plugins/{sortable-BAG3MSWS.js → sortable-HE7Q4KKP.js} +1 -1
  83. package/dist/m/plugins/{source-OYHDXKTB.js → source-5RTLTD75.js} +1 -1
  84. package/dist/m/plugins/{undo-KLHAGV75.js → undo-5MFW3OD5.js} +1 -1
  85. package/dist/m/plugins/{upgrade-SZQJYEQQ.js → upgrade-ORK24FK6.js} +1 -1
  86. package/dist/m/plugins/{upload-NZET3DNQ.js → upload-YMBDWTLR.js} +1 -1
  87. package/dist/m/plugins/{visitor-drafts-ZE6PCAFP.js → visitor-drafts-DCVGLCBX.js} +2 -2
  88. package/dist/m/plugins/{visitor-drafts-owner-TLECTYWS.js → visitor-drafts-owner-QLF6IALP.js} +1 -1
  89. package/dist/m/plugins/{visitor-menu-5XY57JQA.js → visitor-menu-VNWJZ6PV.js} +1 -1
  90. package/dist/m/plugins/{wire-S5ATC4QI.js → wire-I3TDGBGZ.js} +1 -1
  91. package/dist/m/{reader-core-AHOAP5DH.js → reader-core-7JOVUCEQ.js} +2 -2
  92. package/dist/m/sync/{live-sync-RZQSDMZW.js → live-sync-2UYQQSD7.js} +1 -1
  93. package/dist/offline-manifest.json +377 -377
  94. package/package.json +1 -1
  95. package/src/core/mode-receipt.js +7 -5
  96. package/dist/m/c-C7SUMNMI.js +0 -1
  97. package/dist/m/manifest-D70FE013.js +0 -1
  98. /package/dist/m/plugins/{richclay-MXH2GFAZ.js.LEGAL.txt → richclay-XL64ZGOZ.js.LEGAL.txt} +0 -0
@@ -1 +1 @@
1
- import{a as ce,b as Qe,c as ue,e as fe,f as pe,g as nt}from"./c-ARO6CPMA.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-FILLTJA7.js";import{b as Ke}from"./c-5VYOWDTI.js";import{b as oe,c as ae,d as b,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-UW6MMZ4V.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 k=S&&e[_];typeof k=="string"&&k&&t.set(d,k),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 Ot=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 k=n.importNode(S,!0),x=a.get(u);return x&&a.set(k,x),u.replaceWith(k),k},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"),k=d.get(S);k?h(k,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-O3DPFZCE.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-HYNM5U6B.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 bt(){return ye??=Promise.all([import("./c-WOWGGNCJ.js"),import("./c-EEWPNUM2.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 xt(s){if(L){pt(s);return}Q.push(s),bt().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="[data-richclay], [richclay], [editable], [clay-editable]";function Lt(){let s=Array.from(document.querySelectorAll(Tt),e=>[e,e.innerHTML]);return()=>{for(let[e,t]of s)e.isConnected&&e.innerHTML!==t&&e.dispatchEvent(new CustomEvent("clay:external-write"))}}var Ht=(s,e,t)=>Ie(s,e,t)||Fe.test(e.toLowerCase()),yt=s=>s.getAttribute("data-id")||s.getAttribute("id")||null;function Ft(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 Ct=s=>e=>{let t=yt(e);if(!t)return null;let i=e.getRootNode(),n=s.get(i);return n||s.set(i,n=Ft(i)),n.get(t)===1?t:null},me=s=>!!s&&typeof s=="object"&&!Array.isArray(s);function At(s){return typeof s!="string"||s===""?null:new DOMParser().parseFromString(s,"text/html").documentElement?.getAttribute("documentetag")||null}function Rt(s,e){e!=="live"||!s||!y||(y.enableContentEditable(s),y.enableOnClick(s),y.enableAdminInputs(s),y.enableAdminResources(s))}function qt(){let{forComparison:s,forDirty:e}=Be({flushUndo:!1});return[s,e]}var Mt=1024*1024;function Pt(s,e,t,i,n){let r={sender:t,identityMap:i,...n?{etag:n}:{}};return e.length<Mt?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(b())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()&&!b()&&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(b(),!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}xt(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(b(),!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-L6KVXPBO.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=Bt(e)??t,a=typeof o=="string"?We(o):0;l={...l,html:Nt(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:Pt(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=At(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-NYJ577NL.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());let v=Lt();try{let w=A().HyperMorph.mergeDocument({...p,lineage:f.lineage});return f.returned(),w}catch(w){throw f.invalidate(I.list()),f.finish(I.list()),w}finally{v()}},S=this.identity,k=Te,x=Ct(new WeakMap),N=p=>me(p)?{first:x,map:p,then:x}:x,O=l?p=>x(p)||S.idOf(D(p)||p)||null:x,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 w=x(v),De=w&&p.get(v);De&&we.set(w,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,w)=>Ht(p,v,w)||z()&&Re(w||p,v),attributeMerge:ot,protectFocusedValue:!0,restoreFocus:document.activeElement?.localName!=="clay-editor-ui",keepLiveOnly:o==="peer",scripts:{mergeTags:A().mergeTagRecognizers},hooks:{beforeAttributeUpdated:k},...c},ke=this.lane==="live"&&b(),be=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(w){throw g(C,w),w}}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!==be.gen,xe;try{f.prepareComplete(F,I.list()),xe=C?_(C,F.conflicts,{ticket:U}):[]}finally{f.finish(I.list())}this.lane==="live"&&F.localDiverged?Ve():ke&&!F.localDiverged&&Xe(be);let vt=new Set(me(t)?Object.values(t):[]);for(let[p,v]of F.identities){let w=vt.has(v)?v:we.get(v);w&&S.adopt(p,w)}return{report:F,ticket:U,typedDuringWait:mt,conflictIds:xe}}_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"&&b()&&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&&!b()){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"&&b()&&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=>Rt(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&&!b()){y.setLastSavedBaselines(...qt()),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 Bt=s=>K&&(K.captureId??null)===(s??null)?K.html:null;function Nt(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 vn=(s,e,t)=>J().then(({morph:i})=>i(s,e,t));var Sn=Ee;export{I as a,_t as b,It as c,Se as d,Ee as e,vn as f,Sn as g};
1
+ import{a as ce,b as Qe,c as ue,e as fe,f as pe,g as nt}from"./c-O3BSWMVD.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-FILLTJA7.js";import{b as Ke}from"./c-5VYOWDTI.js";import{b as oe,c as ae,d as b,f as he,g as Ve,h as Xe}from"./c-T6RRRHX7.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-OSGTRM4C.js";import{e as Ue}from"./c-26W3BMWK.js";import{d as Pe}from"./c-IJUK2GPW.js";import{f as $,j as te}from"./c-JEWSJHMK.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-UW6MMZ4V.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 k=S&&e[_];typeof k=="string"&&k&&t.set(d,k),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 Ot=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 k=n.importNode(S,!0),x=a.get(u);return x&&a.set(k,x),u.replaceWith(k),k},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"),k=d.get(S);k?h(k,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-6266A3CU.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-5CJCIAFK.js")).then(s=>y=s).catch(s=>{throw _e=null,s}),_e}var ve=null,ge=null;function kt(){return ge??=import("./c-RHYX6KUH.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 bt(){return ye??=Promise.all([import("./c-RC37IFYT.js"),import("./c-W3DMFFGK.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 xt(s){if(L){pt(s);return}Q.push(s),bt().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="[data-richclay], [richclay], [editable], [clay-editable]";function Lt(){let s=Array.from(document.querySelectorAll(Tt),e=>[e,e.innerHTML]);return()=>{for(let[e,t]of s)e.isConnected&&e.innerHTML!==t&&e.dispatchEvent(new CustomEvent("clay:external-write"))}}var Ht=(s,e,t)=>Ie(s,e,t)||Fe.test(e.toLowerCase()),yt=s=>s.getAttribute("data-id")||s.getAttribute("id")||null;function Ft(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 Ct=s=>e=>{let t=yt(e);if(!t)return null;let i=e.getRootNode(),n=s.get(i);return n||s.set(i,n=Ft(i)),n.get(t)===1?t:null},me=s=>!!s&&typeof s=="object"&&!Array.isArray(s);function At(s){return typeof s!="string"||s===""?null:new DOMParser().parseFromString(s,"text/html").documentElement?.getAttribute("documentetag")||null}function Rt(s,e){e!=="live"||!s||!y||(y.enableContentEditable(s),y.enableOnClick(s),y.enableAdminInputs(s),y.enableAdminResources(s))}function qt(){let{forComparison:s,forDirty:e}=Be({flushUndo:!1});return[s,e]}var Mt=1024*1024;function Pt(s,e,t,i,n){let r={sender:t,identityMap:i,...n?{etag:n}:{}};return e.length<Mt?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(b())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()&&!b()&&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(b(),!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}xt(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(b(),!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-L6KVXPBO.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=Bt(e)??t,a=typeof o=="string"?We(o):0;l={...l,html:Nt(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:Pt(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=At(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-7RJCYD4F.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());let v=Lt();try{let w=A().HyperMorph.mergeDocument({...p,lineage:f.lineage});return f.returned(),w}catch(w){throw f.invalidate(I.list()),f.finish(I.list()),w}finally{v()}},S=this.identity,k=Te,x=Ct(new WeakMap),N=p=>me(p)?{first:x,map:p,then:x}:x,O=l?p=>x(p)||S.idOf(D(p)||p)||null:x,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 w=x(v),De=w&&p.get(v);De&&we.set(w,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,w)=>Ht(p,v,w)||z()&&Re(w||p,v),attributeMerge:ot,protectFocusedValue:!0,restoreFocus:document.activeElement?.localName!=="clay-editor-ui",keepLiveOnly:o==="peer",scripts:{mergeTags:A().mergeTagRecognizers},hooks:{beforeAttributeUpdated:k},...c},ke=this.lane==="live"&&b(),be=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(w){throw g(C,w),w}}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!==be.gen,xe;try{f.prepareComplete(F,I.list()),xe=C?_(C,F.conflicts,{ticket:U}):[]}finally{f.finish(I.list())}this.lane==="live"&&F.localDiverged?Ve():ke&&!F.localDiverged&&Xe(be);let vt=new Set(me(t)?Object.values(t):[]);for(let[p,v]of F.identities){let w=vt.has(v)?v:we.get(v);w&&S.adopt(p,w)}return{report:F,ticket:U,typedDuringWait:mt,conflictIds:xe}}_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"&&b()&&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&&!b()){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"&&b()&&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=>Rt(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&&!b()){y.setLastSavedBaselines(...qt()),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 Bt=s=>K&&(K.captureId??null)===(s??null)?K.html:null;function Nt(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 vn=(s,e,t)=>J().then(({morph:i})=>i(s,e,t));var Sn=Ee;export{I as a,_t as b,It as c,Se as d,Ee as e,vn as f,Sn as g};
@@ -1,4 +1,4 @@
1
- import{a as _t,b as Dt,c as jt,d as Ue,e as je,f as oo,g as Ft,h as ro,i as so,j as Lt,l as Nt}from"./c-DEYHCYJB.js";import{a as $t,b as no,c as Qo,f as Zo}from"./c-LETPPG2F.js";import{a as er}from"./c-6BGJAJ67.js";import{a as Zn,b as eo,e as to,f as pt,g as Pt}from"./c-MMV5JULA.js";import{a as Xo}from"./c-MVVEIJUU.js";import{b as Vo,c as qo}from"./c-OBMZASYQ.js";import"./c-IW6GGOU2.js";import"./c-HAWFNBYG.js";import{a as De,b as Un,p as Gn,q as Xn,s as Wo,v as Uo,w as Go}from"./c-WHMZCRQD.js";import{A as Nn,B as Bn,D as Te,E as zn,F as We,G as ft,H as Kn,I as Jn,J as qe,K as ut,L as Ae,M as dt,N as Hn,O as Yt,P as Vn,Q as Wn,R as mt,S as qn,T as de,a as Ve,b as _e,c as An,d as Yn,e as Rn,g as Pn,k as $n,n as Ho,q as _n,r as Dn,s as jn,t as Fn,u as Ct,w as Tt,y as At,z as Ln}from"./c-LAKBBJOU.js";import{a as be,b as On,d as Ye,e as Ke,g as Me,h as Je,i as xe,j as ne,k as En,l as He,m as ct,n as ye,o as Mn,p as In,q as Ce,r as Re,u as Cn,v as Tn,w as at}from"./c-EIUKME3W.js";import"./c-DZT6W2NG.js";import"./c-SYOA4T7V.js";import"./c-ND3W7D5U.js";import{A as we,B as Be,C as Ee,d as xt,e as Le,f as un,i as dn,j as mn,l as st,m as it,n as St,q as Ot,r as Ne,s as ge,t as pn,w as Et,x as hn,y as $e,z as me}from"./c-WHQUZM2V.js";import{g as Qn,p as Rt}from"./c-3XGLJAS7.js";import{E as Mt,H as It,I as wn,d as ue,fa as ze,g as kn,i as yn,ia as xn,ja as Sn,na as lt,w as vn}from"./c-OH2FPYSY.js";import{b as nn}from"./c-QY7F6EN6.js";import"./c-FSQXFG5T.js";import{b as pe,c as gn,e as bn}from"./c-RETTCOWO.js";import{a as on,b as rn,d as vt}from"./c-JC4RZW4E.js";import{a as an}from"./c-TCCA5BZN.js";import"./c-3LDGIBMN.js";import{c as fn}from"./c-57XDY6HC.js";import"./c-OZVK3TFI.js";import{a as cn,b as wt}from"./c-FILLTJA7.js";import"./c-QCDVDZIR.js";import{e as sn,f as ln}from"./c-FC5RUFPR.js";import"./c-4ASQPRQL.js";import"./c-GQ6F6IDK.js";import"./c-I2SCCUEW.js";import"./c-5VYOWDTI.js";import"./c-P73XPAOA.js";import"./c-ZPI7M5U5.js";import"./c-WYFDLITL.js";import"./c-UGHH4MB3.js";import"./c-MZCOGNZL.js";import"./c-EHAR4RJJ.js";import"./c-LD6UVV5R.js";import"./c-PGSBXHUE.js";import"./c-KU3PX7LL.js";import"./c-EQ5NBOGA.js";import"./c-IJUK2GPW.js";import"./c-C7SUMNMI.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-U4TWEIKZ.js";import"./c-UW6MMZ4V.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";var Bt=new Set(["paragraph","heading","list_item","callout","quote","code_block","toggle"]),Ge=(e,o)=>ze(e)===ze(o);function zt(e,o){let t=o.createElement("article");return t.setAttribute("data-blockeditor",""),t.innerHTML=Sn([{id:e.id,t:"paragraph",c:e.c??"",...e.m?{m:e.m}:{}}],{clean:xn(o)}),t}function tr(e,o){let t=new Map(e.map((c,i)=>[c.id,i])),r=new Set(o.map(c=>c.id)),n=new Map,s=0;return o.map(c=>{let i=t.get(c.id);if(i!==void 0)return s=i+1,c;let a={c:c.c??"",m:c.m??null};for(let p=s;p<e.length;p++){let w=e[p];if(!(r.has(w.id)||w.t!==c.t||!Ge({c:w.c??"",m:w.m??null},a)))return r.add(w.id),s=p+1,n.set(c.id,w.id),{...c,id:w.id}}return c}).map(c=>n.has(c.parent)?{...c,parent:n.get(c.parent)}:c)}function Kt(e,o,t,{doc:r,merge3:n,mergeJson:s}){let l=[],c=tr(e,t),i=new Map(e.map(u=>[u.id,u])),a=new Map(o.map(u=>[u.id,u])),p=new Map(c.map(u=>[u.id,u])),w=o.map(u=>({...u})),x=c.map(u=>({...u})),h=new Map(w.map(u=>[u.id,u])),y=new Map(x.map(u=>[u.id,u]));for(let[u,C]of i){let f=a.get(u),k=p.get(u);if(!f||!k||!Bt.has(C.t)||!Bt.has(f.t)||!Bt.has(k.t))continue;let A={c:C.c??"",m:C.m??null},D={c:f.c??"",m:f.m??null},W={c:k.c??"",m:k.m??null};if(Ge(D,A)||Ge(W,A)||Ge(D,W))continue;if(C.t==="code_block"){for(let $ of[h.get(u),y.get(u)])$.c=k.c??"",k.m?$.m=k.m:delete $.m;l.push({id:u,kind:"text",local:f.c??"",remote:k.c??""});continue}let j=n(zt(C,r),zt(f,r),zt(k,r));for(let $ of j.conflicts)l.push({id:u,kind:"text",local:$.local?.textContent??null,remote:$.remote?.textContent??null});let[X]=lt(j.root,{seed:"",known:new Map});for(let $ of[h.get(u),y.get(u)])$.c=X.c,X.m?$.m=X.m:delete $.m}let v=o.map(u=>u.id);for(let[u,C]of i){let f=h.get(u);if(!f||p.has(u)||Ge(a.get(u),C))continue;let k=v.indexOf(u)-1;for(;k>=0&&!y.has(v[k]);)k--;let A=k<0?0:x.findIndex(D=>D.id===v[k])+1;x.splice(A,0,{...f}),y.set(u,x[A]),l.push({id:u,kind:"kept-edit"})}let _=s(e,w,x,{onConflict:u=>l.push({kind:"field",path:u.path,local:u.local,remote:u.remote,resolved:u.resolved})}),N=new Set(_.map(u=>u.id)),m=u=>(a.get(u)??i.get(u)??p.get(u))?.parent??null,O=_.map(u=>{let C=u.parent??null;for(;C&&!N.has(C);)C=m(C);return C===(u.parent??null)?u:{...u,parent:C}}),Y=new Map(O.map(u=>[u.id,u.parent??null])),I=u=>{let C=new Set([u]);for(let f=Y.get(u);f;f=Y.get(f)){if(C.has(f))return!0;C.add(f)}return!1};for(let u of O)if(I(u.id)){for(let C of[a.get(u.id)?.parent,i.get(u.id)?.parent,null])if(Y.set(u.id,C&&N.has(C)?C:null),!I(u.id))break}return{items:O.map(u=>(u.parent??null)===Y.get(u.id)?u:{...u,parent:Y.get(u.id)}),conflicts:l}}var nr=e=>{try{return an(e)}catch{return null}},Fe={ok:!0,outcome:"unchanged"},Xe={ok:!1,outcome:"disposed",reason:"adoption-disposed"},Qe={ok:!1,outcome:"refused",reason:"adoption-refused"},or={ok:!1,outcome:"refused",reason:"adoption-timeout"},rr={ok:!1,outcome:"error",reason:"adoption-error"},sr={ok:!0,outcome:"writer-adopts"},io=e=>({ok:!0,outcome:"adopted",counts:e}),lo=1e4;function ir(e){let o=e.querySelector($t);return o?{article:o.cloneNode(!0),tags:no(e).map(t=>nr(t.textContent))}:null}function co(e){return new Promise(o=>{if(!e.composing)return o();e.dom.addEventListener("compositionend",()=>setTimeout(()=>o(co(e)),0),{once:!0})})}function lr({view:e,source:o=null,ready:t=Promise.resolve(),isAdopter:r=()=>!0,idle:n=()=>co(e),requestCheckpoint:s=()=>{},notice:l=()=>{},snapshot:c=()=>null,mergeTagless:i=!1,seeded:a=!1,writerReady:p=()=>Promise.resolve(),adopted:w=()=>{},hold:x=sn,release:h=ln,holdMs:y=lo,doc:v=document}){let _=o?o.article.innerHTML:null,N=o?o.article:null,m=new Map,O=$=>{let R=$.getAttribute("data-rev");if(!R)return;let K=m.get(R)??[];m.delete(R),m.set(R,K),K.push($),K.length>10&&K.shift(),m.size>20&&m.delete(m.keys().next().value)};N&&O(N);let Y=Promise.resolve(),I=!1,E,u=new Promise($=>E=$);async function C(){let $,R=new Promise(K=>{$=setTimeout(()=>K("timeout"),y)});try{return await Promise.race([Promise.resolve(t).then(()=>n()).then(()=>"ready"),u.then(()=>"disposed"),R])}finally{clearTimeout($)}}function f($,R,K,L){let{HyperMorph:M}=cn(),q=Kt(K,R,L,{doc:v,merge3:M.merge3,mergeJson:M.mergeJson}),Q=q.conflicts.filter(J=>J.kind==="text"||J.kind==="field"),b=Q.length?c():null,d=eo($,q.items,R),S=d&&to(e.state,d);if(!S)return null;e.dispatch(S),e.dispatch(bn.closeHistory(e.state.tr));let F={edited:d.edited.size,created:d.created.size,deleted:d.deleted.length,moved:d.reordered},{displaced:B}=S.getMeta(Zn);return Object.keys(B).length&&(F.displaced=B),Q.length&&(F.conflicts=Q),b&&(F.copy=b),F}async function k($){if(i&&!$.tags.length)return A($);let R=Pt($.article,$.tags);if(R.kind==="unbased"&&console.warn("page: the article and its data changed together; kept the data"),R.kind!=="adopt")return Fe;if(!r())return sr;x();try{if(await wt(),I)return Xe;if(!r())return Qe;let K=await C();if(K==="timeout"&&console.warn("page: gave up waiting for the editor; the hand edit was not adopted"),K==="disposed"||I)return Xe;if(K!=="ready")return or;if(!r())return Qe;let L=Mt(e.state.doc),M=f(L,pt(L,v),R.baseItems,R.parsed);return M?(w(R.A),io(M)):Fe}finally{h()}}async function A($){let R=$.article.getAttribute("data-rev"),K=R&&m.get(R)||[],L=K.at(-1)??N;if(K.slice(0,-1).some(M=>M.innerHTML===$.article.innerHTML)||(O($.article),N=$.article,!L)||L.outerHTML===$.article.outerHTML)return Fe;x();try{if(await wt(),I)return Xe;if(!r())return Qe;if(await p(),I)return Xe;if(!r())return Qe;if(await C()==="disposed"||I)return Xe;if(!r())return Qe;let q=Mt(e.state.doc),Q=pt(q,v),b=new Map(Q.map(F=>[F.id,F])),d=F=>lt(F,{seed:F.getAttribute("data-rev")??"",known:b}),S=f(q,Q,d(L),d($.article));return S?io(S):Fe}finally{h()}}async function D($){try{return await k($)}catch(R){return console.error("page: adoption failed",R),rr}}let W=null;function j($,R=!1){return Y=Y.then(()=>D($)).then(K=>(R&&(W=K),!K.ok||K.outcome!=="adopted"||(s(),l(K.counts),v.dispatchEvent(new CustomEvent("clay:blockeditor-adopted",{detail:K.counts}))),K)),Y}function X($){let R=$.detail?.html;if(I||typeof R!="string")return;let K=ir(new DOMParser().parseFromString(R,"text/html"));!K||K.article.innerHTML===_||(_=K.article.innerHTML,j(K))}return v.addEventListener("clay:sync-applied",X),o&&!a&&j(o,!0),{idle:async()=>(await Y,W),saved($){if(!i||typeof $!="string")return;let R=new DOMParser().parseFromString($,"text/html").querySelector($t);R&&(O(R),N=R)},dispose(){I=!0,E(),v.removeEventListener("clay:sync-applied",X)}}}var ao='["text-delete",',fo=(e,o)=>o instanceof hn&&o._item&&o._item.parent===e.attrs&&typeof o._item.parentSub=="string"?o._item.parentSub:null,uo=e=>e==="t"||e==="parent",Jt=e=>e.content instanceof me&&e.content.embed.b!==void 0,cr=e=>e.content instanceof Be||e.content instanceof we||e.content instanceof me&&e.content.embed.b===void 0,po=e=>{let o=new Map;for(let t of e.stops)(o.get(t.client)??o.set(t.client,[]).get(t.client)).push(t);return o},ho=(e,o)=>{let t=o.get(e.id.client);if(!t)return!1;let r=e.id.clock,n=r+e.length;return t.some(s=>s.clock<n&&r<s.clock+s.len)},ar=(e,o)=>{for(let t=e.left;t;t=t.left){if(t.deleted){if(ho(t,o))return null;continue}if(Jt(t))return t}return null};function go(e,o,t){let r=po(t),n=new Set,s=new Set,l=o.changed.get(e.tableFields)??new Set;for(let[h,y]of o.changed){if(h===e.flow)continue;if(h===e.attrs){if(!o.local)return null;for(let _ of y){let N=e.attrs.get(_);if(!(N instanceof $e)||N._item.left||N._item.id.clock<(o.beforeState.get(N._item.id.client)??0))return null;s.add(_)}if(s.size>1)return null;continue}if(h===e.tableFields){for(let _ of y){let N=e.tableFields.has(_)?Dn(_,e.tableFields.get(_)):null;if(N===null)return null;n.add(N)}continue}let v=fo(e,h);if(v!==null){for(let _ of y)if(uo(_))return null;n.add(v);continue}if(h!==e.gone)return null;for(let _ of y)if(typeof _!="string"||!_.startsWith(ao))return null}let c=e.ydoc.store,i=null,a=null,p=!1,w=h=>{if(!(h instanceof Ee))return!1;if(h.parent===e.gone)return typeof h.parentSub=="string"&&h.parentSub.startsWith(ao);if(h.parent===e.tableFields)return l.has(h.parentSub);if(h.parent===e.attrs)return s.has(h.parentSub);if(h.parent!==e.flow){let v=fo(e,h.parent);return v!==null&&(s.has(v)||n.has(v)&&!uo(h.parentSub))}if(Jt(h)){if(h.deleted||!s.has(h.content.embed.b))return!1;a=h}else if(!cr(h))return!1;let y=ar(h,r);return!y||i&&y!==i?!1:(i=y,h.content instanceof we&&(p=!0),!0)};for(let[h,y]of o.afterState)for(let v=o.beforeState.get(h)??0;v<y;){let _=ge(c,{client:h,clock:v});if(!w(_))return null;v=_.id.clock+_.length}let x=!1;for(let[h,y]of o.deleteSet.clients)for(let{clock:v,len:_}of y)for(let N=v;N<v+_;){let m=ge(c,{client:h,clock:N});if(!w(m))return null;x=!0,N=m.id.clock+m.length}return s.size&&!a?null:i||n.size?{marker:i,split:a,deleted:x,formats:p,fields:n,remote:!o.local}:null}var fr=e=>{for(let o in e)return{...e};return null};function bo(e,o,t,r=null){let n=r?.formats??!0,s=r?.split??null,l=o.visible,c=-1,i=0;for(let f=0;f<l.length;f++){let k=l[f];if(k.brk&&k.brk.client===t.id.client&&k.brk.clock===t.id.clock){c=f;break}i+=k.len}if(c<0)return null;let a=l[c];if(a.implicit||a.atom||a.opaque||a.recovered||a.hide)return null;let p=a.runs.findIndex(f=>f.hole!==void 0);if(p>=0&&n||a.items&&o.copies.has(a.baseId))return null;let w=po(o),x={...a.fmtIn??{}},h=null,y={...a,runs:[],len:1};a.items&&(y.items=[]);let v=y,_=!1,N=je(o.holes,i),m=N+1;for(let f=t.right;f;f=f.right){if(f.deleted){if(ho(f,w))return null;continue}if(Jt(f)&&(f!==s||v!==y)){_=!0;break}let k=m;f.countable&&(m+=f.length);let A=f.content;if(f===s){let D=A.embed.b,W=e.attrs.get(D)?.get("t")||"paragraph";if(!Object.hasOwn(ue.nodes,W)||!ue.nodes[W].isTextblock)return null;let j=fr(x);y.fmtOut=j,v={kind:"b",id:D,baseId:D,brk:{client:f.id.client,clock:f.id.clock},implicit:!1,runs:[],len:1,atom:!1,items:null,fmtIn:j,fmtOut:null,t:W,opaque:!1},h=null;continue}if(A instanceof we){A.value===null?delete x[A.key]:x[A.key]=A.value,h=null;continue}if(A instanceof me){v.runs.push({br:!0}),v.items&&v.items.push({at:k,id:ne(f.id),client:f.id.client,clock:f.id.clock,length:f.length,kind:"br",text:null,blockId:null,raw:{...x}}),v.len+=1;continue}if(A instanceof Be){if(!h){let D=Tn(x,v.t);h={marks:D,mk:Cn(D)}}v.runs.push({text:A.str,marks:h.marks,mk:h.mk}),v.items&&v.items.push({at:k,id:ne(f.id),client:f.id.client,clock:f.id.clock,length:f.length,kind:"text",text:A.str,blockId:null,raw:{...x}}),v.len+=A.str.length}else if(f.countable)return null}let O=a.len;if(p<0){if(!xe(x,a.fmtOut??{}))return null}else{if(!_||v.t!==a.t)return null;O=1;for(let f=0;f<p;f++)O+=a.runs[f].br?1:a.runs[f].text.length}let Y=v===y?[y]:[y,v],I=Y.reduce((f,k)=>f+k.len,0)-O,E=N+O,u=f=>f.at>=E?{...f,at:f.at+I}:f;v.fmtOut=a.fmtOut,p>=0&&(v.runs=v.runs.concat(a.runs.slice(p)),v.len+=a.len-O,v.items&&(v.items=v.items.concat(a.items.filter(f=>f.at>=E).map(u))));let C={...o,visible:l.slice(),tokens:o.tokens+I};if(C.visible.splice(c,1,...Y),I){let f=i+O;C.holes=o.holes.map(k=>k.at>=f?{at:k.at+I,len:k.len}:k),C.hidden=o.hidden.map(k=>k.at>=E?{...k,at:k.at+I,items:k.items.map(u)}:k);for(let k=c+Y.length;k<C.visible.length;k+=1){let A=C.visible[k];A.items?.length&&(C.visible[k]={...A,items:A.items.map(u)})}}return C}var ur=e=>e.br?`
1
+ import{a as _t,b as Dt,c as jt,d as Ue,e as je,f as oo,g as Ft,h as ro,i as so,j as Lt,l as Nt}from"./c-DEYHCYJB.js";import{a as $t,b as no,c as Qo,f as Zo}from"./c-LETPPG2F.js";import{a as er}from"./c-6BGJAJ67.js";import{a as Zn,b as eo,e as to,f as pt,g as Pt}from"./c-MMV5JULA.js";import{a as Xo}from"./c-MVVEIJUU.js";import{b as Vo,c as qo}from"./c-OBMZASYQ.js";import"./c-IW6GGOU2.js";import"./c-HAWFNBYG.js";import{a as De,b as Un,p as Gn,q as Xn,s as Wo,v as Uo,w as Go}from"./c-WHMZCRQD.js";import{A as Nn,B as Bn,D as Te,E as zn,F as We,G as ft,H as Kn,I as Jn,J as qe,K as ut,L as Ae,M as dt,N as Hn,O as Yt,P as Vn,Q as Wn,R as mt,S as qn,T as de,a as Ve,b as _e,c as An,d as Yn,e as Rn,g as Pn,k as $n,n as Ho,q as _n,r as Dn,s as jn,t as Fn,u as Ct,w as Tt,y as At,z as Ln}from"./c-LAKBBJOU.js";import{a as be,b as On,d as Ye,e as Ke,g as Me,h as Je,i as xe,j as ne,k as En,l as He,m as ct,n as ye,o as Mn,p as In,q as Ce,r as Re,u as Cn,v as Tn,w as at}from"./c-EIUKME3W.js";import"./c-DZT6W2NG.js";import"./c-SYOA4T7V.js";import"./c-ND3W7D5U.js";import{A as we,B as Be,C as Ee,d as xt,e as Le,f as un,i as dn,j as mn,l as st,m as it,n as St,q as Ot,r as Ne,s as ge,t as pn,w as Et,x as hn,y as $e,z as me}from"./c-WHQUZM2V.js";import{g as Qn,p as Rt}from"./c-3XGLJAS7.js";import{E as Mt,H as It,I as wn,d as ue,fa as ze,g as kn,i as yn,ia as xn,ja as Sn,na as lt,w as vn}from"./c-OH2FPYSY.js";import{b as nn}from"./c-QY7F6EN6.js";import"./c-FSQXFG5T.js";import{b as pe,c as gn,e as bn}from"./c-RETTCOWO.js";import{a as on,b as rn,d as vt}from"./c-JC4RZW4E.js";import{a as an}from"./c-TCCA5BZN.js";import"./c-3LDGIBMN.js";import{c as fn}from"./c-57XDY6HC.js";import"./c-OZVK3TFI.js";import{a as cn,b as wt}from"./c-FILLTJA7.js";import"./c-QCDVDZIR.js";import{e as sn,f as ln}from"./c-IOJOJTPL.js";import"./c-4ASQPRQL.js";import"./c-GQ6F6IDK.js";import"./c-I2SCCUEW.js";import"./c-5VYOWDTI.js";import"./c-T6RRRHX7.js";import"./c-G426P2SE.js";import"./c-WYFDLITL.js";import"./c-UGHH4MB3.js";import"./c-MZCOGNZL.js";import"./c-CKG4NF7J.js";import"./c-LD6UVV5R.js";import"./c-PGSBXHUE.js";import"./c-OSGTRM4C.js";import"./c-26W3BMWK.js";import"./c-IJUK2GPW.js";import"./c-JEWSJHMK.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-U4TWEIKZ.js";import"./c-UW6MMZ4V.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";var Bt=new Set(["paragraph","heading","list_item","callout","quote","code_block","toggle"]),Ge=(e,o)=>ze(e)===ze(o);function zt(e,o){let t=o.createElement("article");return t.setAttribute("data-blockeditor",""),t.innerHTML=Sn([{id:e.id,t:"paragraph",c:e.c??"",...e.m?{m:e.m}:{}}],{clean:xn(o)}),t}function tr(e,o){let t=new Map(e.map((c,i)=>[c.id,i])),r=new Set(o.map(c=>c.id)),n=new Map,s=0;return o.map(c=>{let i=t.get(c.id);if(i!==void 0)return s=i+1,c;let a={c:c.c??"",m:c.m??null};for(let p=s;p<e.length;p++){let w=e[p];if(!(r.has(w.id)||w.t!==c.t||!Ge({c:w.c??"",m:w.m??null},a)))return r.add(w.id),s=p+1,n.set(c.id,w.id),{...c,id:w.id}}return c}).map(c=>n.has(c.parent)?{...c,parent:n.get(c.parent)}:c)}function Kt(e,o,t,{doc:r,merge3:n,mergeJson:s}){let l=[],c=tr(e,t),i=new Map(e.map(u=>[u.id,u])),a=new Map(o.map(u=>[u.id,u])),p=new Map(c.map(u=>[u.id,u])),w=o.map(u=>({...u})),x=c.map(u=>({...u})),h=new Map(w.map(u=>[u.id,u])),y=new Map(x.map(u=>[u.id,u]));for(let[u,C]of i){let f=a.get(u),k=p.get(u);if(!f||!k||!Bt.has(C.t)||!Bt.has(f.t)||!Bt.has(k.t))continue;let A={c:C.c??"",m:C.m??null},D={c:f.c??"",m:f.m??null},W={c:k.c??"",m:k.m??null};if(Ge(D,A)||Ge(W,A)||Ge(D,W))continue;if(C.t==="code_block"){for(let $ of[h.get(u),y.get(u)])$.c=k.c??"",k.m?$.m=k.m:delete $.m;l.push({id:u,kind:"text",local:f.c??"",remote:k.c??""});continue}let j=n(zt(C,r),zt(f,r),zt(k,r));for(let $ of j.conflicts)l.push({id:u,kind:"text",local:$.local?.textContent??null,remote:$.remote?.textContent??null});let[X]=lt(j.root,{seed:"",known:new Map});for(let $ of[h.get(u),y.get(u)])$.c=X.c,X.m?$.m=X.m:delete $.m}let v=o.map(u=>u.id);for(let[u,C]of i){let f=h.get(u);if(!f||p.has(u)||Ge(a.get(u),C))continue;let k=v.indexOf(u)-1;for(;k>=0&&!y.has(v[k]);)k--;let A=k<0?0:x.findIndex(D=>D.id===v[k])+1;x.splice(A,0,{...f}),y.set(u,x[A]),l.push({id:u,kind:"kept-edit"})}let _=s(e,w,x,{onConflict:u=>l.push({kind:"field",path:u.path,local:u.local,remote:u.remote,resolved:u.resolved})}),N=new Set(_.map(u=>u.id)),m=u=>(a.get(u)??i.get(u)??p.get(u))?.parent??null,O=_.map(u=>{let C=u.parent??null;for(;C&&!N.has(C);)C=m(C);return C===(u.parent??null)?u:{...u,parent:C}}),Y=new Map(O.map(u=>[u.id,u.parent??null])),I=u=>{let C=new Set([u]);for(let f=Y.get(u);f;f=Y.get(f)){if(C.has(f))return!0;C.add(f)}return!1};for(let u of O)if(I(u.id)){for(let C of[a.get(u.id)?.parent,i.get(u.id)?.parent,null])if(Y.set(u.id,C&&N.has(C)?C:null),!I(u.id))break}return{items:O.map(u=>(u.parent??null)===Y.get(u.id)?u:{...u,parent:Y.get(u.id)}),conflicts:l}}var nr=e=>{try{return an(e)}catch{return null}},Fe={ok:!0,outcome:"unchanged"},Xe={ok:!1,outcome:"disposed",reason:"adoption-disposed"},Qe={ok:!1,outcome:"refused",reason:"adoption-refused"},or={ok:!1,outcome:"refused",reason:"adoption-timeout"},rr={ok:!1,outcome:"error",reason:"adoption-error"},sr={ok:!0,outcome:"writer-adopts"},io=e=>({ok:!0,outcome:"adopted",counts:e}),lo=1e4;function ir(e){let o=e.querySelector($t);return o?{article:o.cloneNode(!0),tags:no(e).map(t=>nr(t.textContent))}:null}function co(e){return new Promise(o=>{if(!e.composing)return o();e.dom.addEventListener("compositionend",()=>setTimeout(()=>o(co(e)),0),{once:!0})})}function lr({view:e,source:o=null,ready:t=Promise.resolve(),isAdopter:r=()=>!0,idle:n=()=>co(e),requestCheckpoint:s=()=>{},notice:l=()=>{},snapshot:c=()=>null,mergeTagless:i=!1,seeded:a=!1,writerReady:p=()=>Promise.resolve(),adopted:w=()=>{},hold:x=sn,release:h=ln,holdMs:y=lo,doc:v=document}){let _=o?o.article.innerHTML:null,N=o?o.article:null,m=new Map,O=$=>{let R=$.getAttribute("data-rev");if(!R)return;let K=m.get(R)??[];m.delete(R),m.set(R,K),K.push($),K.length>10&&K.shift(),m.size>20&&m.delete(m.keys().next().value)};N&&O(N);let Y=Promise.resolve(),I=!1,E,u=new Promise($=>E=$);async function C(){let $,R=new Promise(K=>{$=setTimeout(()=>K("timeout"),y)});try{return await Promise.race([Promise.resolve(t).then(()=>n()).then(()=>"ready"),u.then(()=>"disposed"),R])}finally{clearTimeout($)}}function f($,R,K,L){let{HyperMorph:M}=cn(),q=Kt(K,R,L,{doc:v,merge3:M.merge3,mergeJson:M.mergeJson}),Q=q.conflicts.filter(J=>J.kind==="text"||J.kind==="field"),b=Q.length?c():null,d=eo($,q.items,R),S=d&&to(e.state,d);if(!S)return null;e.dispatch(S),e.dispatch(bn.closeHistory(e.state.tr));let F={edited:d.edited.size,created:d.created.size,deleted:d.deleted.length,moved:d.reordered},{displaced:B}=S.getMeta(Zn);return Object.keys(B).length&&(F.displaced=B),Q.length&&(F.conflicts=Q),b&&(F.copy=b),F}async function k($){if(i&&!$.tags.length)return A($);let R=Pt($.article,$.tags);if(R.kind==="unbased"&&console.warn("page: the article and its data changed together; kept the data"),R.kind!=="adopt")return Fe;if(!r())return sr;x();try{if(await wt(),I)return Xe;if(!r())return Qe;let K=await C();if(K==="timeout"&&console.warn("page: gave up waiting for the editor; the hand edit was not adopted"),K==="disposed"||I)return Xe;if(K!=="ready")return or;if(!r())return Qe;let L=Mt(e.state.doc),M=f(L,pt(L,v),R.baseItems,R.parsed);return M?(w(R.A),io(M)):Fe}finally{h()}}async function A($){let R=$.article.getAttribute("data-rev"),K=R&&m.get(R)||[],L=K.at(-1)??N;if(K.slice(0,-1).some(M=>M.innerHTML===$.article.innerHTML)||(O($.article),N=$.article,!L)||L.outerHTML===$.article.outerHTML)return Fe;x();try{if(await wt(),I)return Xe;if(!r())return Qe;if(await p(),I)return Xe;if(!r())return Qe;if(await C()==="disposed"||I)return Xe;if(!r())return Qe;let q=Mt(e.state.doc),Q=pt(q,v),b=new Map(Q.map(F=>[F.id,F])),d=F=>lt(F,{seed:F.getAttribute("data-rev")??"",known:b}),S=f(q,Q,d(L),d($.article));return S?io(S):Fe}finally{h()}}async function D($){try{return await k($)}catch(R){return console.error("page: adoption failed",R),rr}}let W=null;function j($,R=!1){return Y=Y.then(()=>D($)).then(K=>(R&&(W=K),!K.ok||K.outcome!=="adopted"||(s(),l(K.counts),v.dispatchEvent(new CustomEvent("clay:blockeditor-adopted",{detail:K.counts}))),K)),Y}function X($){let R=$.detail?.html;if(I||typeof R!="string")return;let K=ir(new DOMParser().parseFromString(R,"text/html"));!K||K.article.innerHTML===_||(_=K.article.innerHTML,j(K))}return v.addEventListener("clay:sync-applied",X),o&&!a&&j(o,!0),{idle:async()=>(await Y,W),saved($){if(!i||typeof $!="string")return;let R=new DOMParser().parseFromString($,"text/html").querySelector($t);R&&(O(R),N=R)},dispose(){I=!0,E(),v.removeEventListener("clay:sync-applied",X)}}}var ao='["text-delete",',fo=(e,o)=>o instanceof hn&&o._item&&o._item.parent===e.attrs&&typeof o._item.parentSub=="string"?o._item.parentSub:null,uo=e=>e==="t"||e==="parent",Jt=e=>e.content instanceof me&&e.content.embed.b!==void 0,cr=e=>e.content instanceof Be||e.content instanceof we||e.content instanceof me&&e.content.embed.b===void 0,po=e=>{let o=new Map;for(let t of e.stops)(o.get(t.client)??o.set(t.client,[]).get(t.client)).push(t);return o},ho=(e,o)=>{let t=o.get(e.id.client);if(!t)return!1;let r=e.id.clock,n=r+e.length;return t.some(s=>s.clock<n&&r<s.clock+s.len)},ar=(e,o)=>{for(let t=e.left;t;t=t.left){if(t.deleted){if(ho(t,o))return null;continue}if(Jt(t))return t}return null};function go(e,o,t){let r=po(t),n=new Set,s=new Set,l=o.changed.get(e.tableFields)??new Set;for(let[h,y]of o.changed){if(h===e.flow)continue;if(h===e.attrs){if(!o.local)return null;for(let _ of y){let N=e.attrs.get(_);if(!(N instanceof $e)||N._item.left||N._item.id.clock<(o.beforeState.get(N._item.id.client)??0))return null;s.add(_)}if(s.size>1)return null;continue}if(h===e.tableFields){for(let _ of y){let N=e.tableFields.has(_)?Dn(_,e.tableFields.get(_)):null;if(N===null)return null;n.add(N)}continue}let v=fo(e,h);if(v!==null){for(let _ of y)if(uo(_))return null;n.add(v);continue}if(h!==e.gone)return null;for(let _ of y)if(typeof _!="string"||!_.startsWith(ao))return null}let c=e.ydoc.store,i=null,a=null,p=!1,w=h=>{if(!(h instanceof Ee))return!1;if(h.parent===e.gone)return typeof h.parentSub=="string"&&h.parentSub.startsWith(ao);if(h.parent===e.tableFields)return l.has(h.parentSub);if(h.parent===e.attrs)return s.has(h.parentSub);if(h.parent!==e.flow){let v=fo(e,h.parent);return v!==null&&(s.has(v)||n.has(v)&&!uo(h.parentSub))}if(Jt(h)){if(h.deleted||!s.has(h.content.embed.b))return!1;a=h}else if(!cr(h))return!1;let y=ar(h,r);return!y||i&&y!==i?!1:(i=y,h.content instanceof we&&(p=!0),!0)};for(let[h,y]of o.afterState)for(let v=o.beforeState.get(h)??0;v<y;){let _=ge(c,{client:h,clock:v});if(!w(_))return null;v=_.id.clock+_.length}let x=!1;for(let[h,y]of o.deleteSet.clients)for(let{clock:v,len:_}of y)for(let N=v;N<v+_;){let m=ge(c,{client:h,clock:N});if(!w(m))return null;x=!0,N=m.id.clock+m.length}return s.size&&!a?null:i||n.size?{marker:i,split:a,deleted:x,formats:p,fields:n,remote:!o.local}:null}var fr=e=>{for(let o in e)return{...e};return null};function bo(e,o,t,r=null){let n=r?.formats??!0,s=r?.split??null,l=o.visible,c=-1,i=0;for(let f=0;f<l.length;f++){let k=l[f];if(k.brk&&k.brk.client===t.id.client&&k.brk.clock===t.id.clock){c=f;break}i+=k.len}if(c<0)return null;let a=l[c];if(a.implicit||a.atom||a.opaque||a.recovered||a.hide)return null;let p=a.runs.findIndex(f=>f.hole!==void 0);if(p>=0&&n||a.items&&o.copies.has(a.baseId))return null;let w=po(o),x={...a.fmtIn??{}},h=null,y={...a,runs:[],len:1};a.items&&(y.items=[]);let v=y,_=!1,N=je(o.holes,i),m=N+1;for(let f=t.right;f;f=f.right){if(f.deleted){if(ho(f,w))return null;continue}if(Jt(f)&&(f!==s||v!==y)){_=!0;break}let k=m;f.countable&&(m+=f.length);let A=f.content;if(f===s){let D=A.embed.b,W=e.attrs.get(D)?.get("t")||"paragraph";if(!Object.hasOwn(ue.nodes,W)||!ue.nodes[W].isTextblock)return null;let j=fr(x);y.fmtOut=j,v={kind:"b",id:D,baseId:D,brk:{client:f.id.client,clock:f.id.clock},implicit:!1,runs:[],len:1,atom:!1,items:null,fmtIn:j,fmtOut:null,t:W,opaque:!1},h=null;continue}if(A instanceof we){A.value===null?delete x[A.key]:x[A.key]=A.value,h=null;continue}if(A instanceof me){v.runs.push({br:!0}),v.items&&v.items.push({at:k,id:ne(f.id),client:f.id.client,clock:f.id.clock,length:f.length,kind:"br",text:null,blockId:null,raw:{...x}}),v.len+=1;continue}if(A instanceof Be){if(!h){let D=Tn(x,v.t);h={marks:D,mk:Cn(D)}}v.runs.push({text:A.str,marks:h.marks,mk:h.mk}),v.items&&v.items.push({at:k,id:ne(f.id),client:f.id.client,clock:f.id.clock,length:f.length,kind:"text",text:A.str,blockId:null,raw:{...x}}),v.len+=A.str.length}else if(f.countable)return null}let O=a.len;if(p<0){if(!xe(x,a.fmtOut??{}))return null}else{if(!_||v.t!==a.t)return null;O=1;for(let f=0;f<p;f++)O+=a.runs[f].br?1:a.runs[f].text.length}let Y=v===y?[y]:[y,v],I=Y.reduce((f,k)=>f+k.len,0)-O,E=N+O,u=f=>f.at>=E?{...f,at:f.at+I}:f;v.fmtOut=a.fmtOut,p>=0&&(v.runs=v.runs.concat(a.runs.slice(p)),v.len+=a.len-O,v.items&&(v.items=v.items.concat(a.items.filter(f=>f.at>=E).map(u))));let C={...o,visible:l.slice(),tokens:o.tokens+I};if(C.visible.splice(c,1,...Y),I){let f=i+O;C.holes=o.holes.map(k=>k.at>=f?{at:k.at+I,len:k.len}:k),C.hidden=o.hidden.map(k=>k.at>=E?{...k,at:k.at+I,items:k.items.map(u)}:k);for(let k=c+Y.length;k<C.visible.length;k+=1){let A=C.visible[k];A.items?.length&&(C.visible[k]={...A,items:A.items.map(u)})}}return C}var ur=e=>e.br?`
2
2
  `:e.hole!==void 0?{hole:e.hole}:{text:e.text,mk:e.mk},dr=e=>{let o=[];for(let t of e.map(ur)){let r=o[o.length-1];r&&typeof r=="object"&&typeof t=="object"&&r.text!==void 0&&t.text!==void 0&&r.mk===t.mk?o[o.length-1]={text:r.text+t.text,mk:t.mk}:o.push(t)}return o},mo=(e,o)=>{let t=ge(e.ydoc.store,{client:o.client,clock:o.clock});return{client:t.id.client,clock:t.id.clock,len:t.length}},et=(e,o)=>dt({...o,copies:[...o.copies],fences:o.fences.map(t=>mo(e,t)),stops:o.stops.map(t=>mo(e,t)),visible:o.visible.map(t=>({...t,runs:dr(t.runs)}))});var ko=e=>e===!0?{}:e,yo=(e,o)=>xe(ko(e),ko(o));function xo(e,o,t,r){let n=e.attrs.get(o);n||(n=new $e,e.attrs.set(o,n));let s=ue.nodes[t];if(!s){n.get("t")!==t&&n.set("t",t);for(let[a,p]of Object.entries(r??{}))a==="t"||a==="pos"||xe(n.has(a)?n.get(a):void 0,p)||n.set(a,p);return}let l=t==="table"&&n.get("t")==="table"&&!Yt(o),c=t==="board"&&!Yt(o),i=l?jn(e.tableFields,o,Fn(e,o)):c?Tt(e.boardFields,o):null;n.get("t")!==t&&n.set("t",t);for(let a of Me(s)){if(l&&(a==="rows"||a==="cols")||c&&(a==="columns"||a==="cards"))continue;let p=n.has(a)?n.get(a):Je(s,a);xe(p,r[a])||n.set(a,r[a])}l&&Ct(e,o,i,r),c&&At(e,o,i,r)}function vo(e,o){let t=new Map,r=o;for(let n=e.flow._start;n&&r>0;n=n.right){if(n.deleted)continue;let s=n.content;s instanceof we?s.value===null?t.delete(s.key):t.set(s.key,s.value):n.countable&&(r-=n.length)}return t}function mr(e){let o=new Set;for(let[r,n]of e)Re(r)&&n&&o.add(r.split("!")[0]);let t=[];for(let[r,n]of e)!Re(r)&&n!==null&&n!==void 0&&!o.has(r)&&ue.marks[Ce(r)]&&t.push([r,n]);return t}function So(e){let o=new Set;for(let[r,n]of e)Re(r)&&n&&o.add(r.split("!")[0]);let t=[];for(let[r,n]of e)!Re(r)&&n!==null&&n!==void 0&&!o.has(r)&&!ue.marks[Ce(r)]&&t.push([r,n]);return t}function Oo(e,o={}){let t={},r=!1;for(let[n,s]of e)(Re(n)||ue.marks[Ce(n)])&&(t[n]=s);for(let[n,s]of So(e))r=!0,o[Ce(n)]!==void 0&&(t[n]=s);return{attrs:t,opaque:r}}function pr(e,o,t){let r=ye(e),n={},s=mr(o),l=new Set;for(let[i,a]of s){let p=Ce(i),w=t[p];w!==void 0&&yo(w,a)?l.add(p):n[`${i}!${r}`]=!0}for(let[i,a]of So(o)){let p=Ce(i);t[p]!==void 0&&yo(t[p],a)&&l.add(p)}for(let[i,a]of Object.entries(t))l.has(i)||(n[`${i}~${ye(e)}`]=a);let c=Oo(o,t);if(!(!Object.keys(n).length&&!c.opaque))return{...c.attrs,...n}}var Ht=2e3;function hr(e){let o=[],t=[],r=0;for(let n=0;n<e.length;n++)if(t.push(e[n]),r+=1,r>=Ht&&n+1<e.length){let s=e[n];if(s.k==="c"&&He(s.ch.charCodeAt(0)))continue;o.push(t),t=[],r=0}return t.length&&o.push(t),o}function ht(e,o,t,r=s=>s(),n=null){let s=o;for(let l of hr(t))r(()=>{s+=br(e,s,l,n)});return s-o}var gr=(e,o,t)=>{if(!t||!t.length)return null;let r=o,n=e.flow._start;for(;n&&r>0;){if(!n.deleted&&n.countable){if(r<n.length)return null;r-=n.length}n=n.right}for(;n&&(n.deleted||!n.countable);n=n.right)if(n.deleted&&t.some(s=>s.client===n.id.client&&s.clock>=n.id.clock&&s.clock<n.id.clock+n.length))return n;return null},Ie=(e,o,t,r)=>{let n=gr(e,o,t);if(!n)return r();n.deleted=!1;try{return r()}finally{n.deleted=!0,e.flow._searchMarker&&(e.flow._searchMarker.length=0)}};function br(e,o,t,r=null){let n=o,s="",l=null,c=null,i=()=>{if(!s)return;let p=pr(e,vo(e,n),c??{});Ie(e,n,r,()=>e.flow.insert(n,s,p)),n+=s.length,s=""},a=p=>{let w=Oo(vo(e,n)).attrs;Ie(e,n,r,()=>e.flow.insertEmbed(n,p,w)),n+=1};for(let p of t)p.k==="c"?(l!==null&&p.mk!==l&&i(),l=p.mk,c=p.ma,s+=p.ch):p.k==="h"?(i(),l=null,a({br:1})):(i(),l=null,a({b:p.id}),xo(e,p.id,p.t,p.attrs));return i(),n-o}var kr=(e,o,t,r)=>{let n=0;for(let s=e.flow._start;s&&n<r;s=s.right){if(s.deleted||!s.countable)continue;let l=n;if(n+=s.length,n<=t||s.content instanceof me&&s.content.embed?.b!==void 0)continue;let c=Math.max(0,t-l),i=Math.min(s.length,r-l);i<=c||e.gone.set(Jn(s.id.client,s.id.clock+c,o.operationId),{length:i-c,actor:e.ydoc.clientID,sv:o.sv})}};function wo(e,o,t,r=null){for(let n=t.length-1;n>=0;n--){let[s,l]=t[n];if(l<=s)continue;let c=o.physicalRanges(s,l);for(let i=c.length-1;i>=0;i--){let[a,p]=c[i];p<=a||(r&&kr(e,r,a,p),e.flow.delete(a,p-a))}}}function yr(e,o,t){let r=!1;for(let n=e.flow._start;n;n=n.right){let s=ne(n.id);if(s===o){r=!0;continue}if(!r)continue;let l=n.content instanceof me?n.content.embed:null;if(l&&l.b!==void 0&&l.b!==t)return s}return null}function Vt(e,o,t,r,n=null){let{pd:s,map:l,bt:c}=e,i=f=>n===null||n[f],a=0;for(;a<t.length&&a<r.length&&Ue(t[a],r[a])&&i(a);)a++;let p=0;for(;p<t.length-a&&p<r.length-a&&Ue(t[t.length-1-p],r[r.length-1-p])&&i(t.length-1-p);)p++;let w=f=>f&&f.k==="c"?f.ch.charCodeAt(0):-1;a>0&&He(w(t[a-1]))&&(ct(w(t[a]))||ct(w(r[a])))&&a--,p>0&&ct(w(t[t.length-p]))&&(He(w(t[t.length-p-1]))||He(w(r[r.length-p-1])))&&p--;let x=t.slice(a,t.length-p),h=r.slice(a,r.length-p),y=o+a,v=y+x.length,_=x.filter(f=>f.k==="b").map(f=>f.id).join(",");if(!(x.some(f=>f.k==="b")&&_===h.filter(f=>f.k==="b").map(f=>f.id).join(","))){let f=Ve(s.origins);try{for(let j of x){if(j.k!=="b"||!j.brk)continue;let X=f.resolve(j.brk);f.boundaryOf(X)||e.tx(()=>f.recordBoundary(X,{blockId:j.id,kind:"removed"}))}}finally{f.dispose()}let k=new Set;x.forEach((j,X)=>{if(j.k!=="b"||!j.brk)return;let $=y+X,R=$+1;for(;R<c.length&&c[R].k!=="b";)R++;let K=R<=v&&R!==$+1,L=R<c.length?c[R].brk:null;K&&(e.tx(()=>s.gone.set(We(ne(j.brk),e.operationId),{blockId:j.id,end:L?ne(L):null,sv:e.sv})),k.add($))});let A=[],D=y;for(let j=y;j<v;j++)k.has(j)&&(j>D&&A.push([D,j]),D=j+1);v>D&&A.push([D,v]),e.tx(()=>wo(s,l,A,x.some(j=>j.k==="b")?null:e));let W=new Set(h.filter(j=>j.k==="b").map(j=>j.id));for(let j of x)if(!(j.k!=="b"||!j.brk||W.has(j.id)))for(let X of e.copies.get(j.id)??[]){let $=We(X,e.operationId);s.gone.has($)||e.tx(()=>s.gone.set($,{blockId:j.id,end:yr(s,X,j.id),sv:e.sv}))}h.length&&ht(s,l.toPhysical(y,"before"),h,e.tx,e.fences);return}let m=[],O=[],Y=[],I=y,E=0,u=0;for(;E<x.length||u<h.length;){let f=E;for(;f<x.length&&x[f].k!=="b";)f++;let k=u;for(;k<h.length&&h[k].k!=="b";)k++;let A=x.slice(E,f),D=h.slice(u,k);if(A.length&&m.push([I,I+A.length]),D.length&&O.push({at:I,toks:D}),I+=A.length,f<x.length&&(Y.push([x[f],h[k]]),I+=1),E=f+(f<x.length?1:0),u=k+(k<h.length?1:0),f>=x.length&&k>=h.length)break}let C=[...m.map(f=>({at:f[0],d:f})),...O.map(f=>({at:f.at,i:f}))].sort((f,k)=>k.at-f.at||(f.d?-1:1));for(let f of C)f.d?e.tx(()=>wo(s,l,[f.d],e)):ht(s,l.toPhysical(f.at,"before"),f.i.toks,e.tx,e.fences);for(let[f,k]of Y)e.tx(()=>{if(!ue.nodes[k.t])return;let A=e.recovered.get(f.id);if(A){f.t!==k.t&&s.gone.set(qe(A,"t"),k.t);for(let j of Me(ue.nodes[k.t]))xe(f.attrs[j],k.attrs[j])||s.gone.set(qe(A,j),k.attrs[j]);return}let D=f.id,W=s.attrs.get(D);if(W){let j=f.t==="table"&&k.t==="table"&&W.get("t")==="table",X=k.t==="board",$=X?f.t==="board"&&W.get("t")==="board"?f.attrs:Tt(s.boardFields,D):null;f.t!==k.t&&W.set("t",k.t);for(let R of Me(ue.nodes[k.t])){if(j&&(R==="rows"||R==="cols")||X&&(R==="columns"||R==="cards"))continue;let K=W.has(R)?W.get(R):Je(ue.nodes[k.t],R);xe(K,k.attrs[R])||W.set(R,k.attrs[R])}j&&Ct(s,D,f.attrs,k.attrs),X&&At(s,D,$,k.attrs)}else xo(s,D,k.t,k.attrs)})}function Wt(e,o,t,r,n,s){let{pd:l,map:c}=e,i=`${r}~${ye(l)}`,a=ye(l),p=o;for(;p<t;){if(s[p].k!=="c"){p++;continue}let w=p;for(;w<t&&s[w].k==="c";)w++;let x=c.physicalRanges(p,w);if(n!==null)for(let[h,y]of x)l.flow.format(h,y-h,{[i]:n});else{let h=0;for(let y of l.flow.toDelta()){let v=typeof y.insert=="string"?y.insert.length:1;for(let[_,N]of x){if(h>=N)break;let m=Math.max(h,_),O=Math.min(h+v,N);if(O>m&&y.attributes){let Y={};for(let[I,E]of Object.entries(y.attributes))Ce(I)===r&&!Re(I)&&E!==null&&(Y[`${I}!${a}`]=!0);Object.keys(Y).length&&l.flow.format(m,O-m,Y)}}h+=v}}p=w}}var{AddMarkStep:Eo,RemoveMarkStep:vr,AttrStep:wr,ReplaceStep:xr,Mapping:gt}=gn,Mo=(e,o,t)=>{let r=e.resolve(o),n=e.resolve(t);return[r.depth&&r.node(1).type.name==="table"?r.before(1):o,n.depth&&n.node(1).type.name==="table"?n.after(1):t]},Sr=(e,o,t)=>{let r=!1;return e.nodesBetween(o,t,n=>(n.type.name==="table"&&(r=!0),!r&&n.type.name!=="table")),r};function Io(e,o,t,r,n=null,s=!0,l=null,{join:c=!1,open:i=!1}={}){let a=()=>{if(l){let d=l;l=null,d()}},p=[],w=[],x=[];for(let d of o)d.steps.forEach((S,F)=>{p.push(S),w.push(d.docs[F]),x.push(S.getMap())});if(!p.length)return;let h=new gt(x),y=[...st(it(e.ydoc)).entries()].sort((d,S)=>d[0]-S[0]),v=ye(e),_=w[0],N=o[o.length-1].doc,m=t.visible.length===0&&_.childCount===1&&_.firstChild.type.name==="paragraph"?[{id:_.firstChild.attrs.id,implicit:!0,t:"paragraph",len:0}]:t.visible,O=new Map,Y=[];{let d=0;m.forEach(S=>{S.implicit&&Y.push({tok:d,id:S.id,t:S.t}),d+=S.len})}Y.sort((d,S)=>S.tok-d.tok);for(let d of Y)d.alias=Mn(e),O.set(d.id,d.alias);let I=O.size?t.holes.map(d=>({at:d.at+Y.filter(S=>S.tok<d.at).length,len:d.len})):t.holes,E=Ft(t.tokens+O.size,I,e.flow.length+O.size),u=[],C=[];p.forEach((d,S)=>{let F=d instanceof Eo||d instanceof vr;if(F&&!Sr(w[S],d.from,d.to)){C.push({i:S,step:d});return}let B=new gt(x.slice(0,S)).invert(),J=new gt(x.slice(S+1)),U=[];d instanceof wr?U.push([d.pos,d.pos+1,d.pos,d.pos+1]):F?U.push([d.from,d.to,d.from,d.to]):d.getMap().forEach((P,oe,ee,te)=>U.push([P,oe,ee,te]));for(let[P,oe,ee,te]of U){let[Z,ie]=Mo(_,B.map(P,-1),B.map(oe,1)),[re,ot]=Mo(N,J.map(ee,-1),J.map(te,1));u.push({oa:Z,ob:ie,na:re,nb:ot})}}),u.sort((d,S)=>d.oa-S.oa||d.na-S.na);let f=[];for(let d of u){let S=f[f.length-1];S&&(d.oa<=S.ob||d.na<=S.nb)?(S.ob=Math.max(S.ob,d.ob),S.nb=Math.max(S.nb,d.nb)):f.push({...d})}let k=!Y.length&&!C.length&&p.every(d=>d instanceof xr)&&o.every(wn),A=k?null:Dt(_,O,m),D=k?null:Dt(N,O,m),W=k?[]:_t(_,O,m),j=k?[]:_t(N,O,m),X=k?f.map(d=>({r:d,old:jt(_,d.oa,d.ob),next:jt(N,d.na,d.nb)})):null,$=k?X.reduce((d,S)=>d+S.next.end-S.next.start,0):f.reduce((d,S)=>d+(D[S.nb]-D[S.na]),0),R=$>Ht,K=R?d=>e.ydoc.transact(S=>{S.meta.set(Ke,s),a(),d()},be):d=>d(),L={pd:e,map:E,bt:W,tx:K,copies:t.copies,fences:t.fences,sv:y,operationId:v,recovered:new Map(t.visible.filter(d=>d.recovered).map(d=>[d.id,d.sourceKey]))},M=d=>d.filter(S=>S.k==="b").map(S=>`${S.id}|${S.t}|${JSON.stringify(S.attrs)}`).join(`
3
3
  `),q=!k&&(C.length>0||M(W)!==M(j)),Q=()=>{for(let F of Y)ht(e,je(t.holes,F.tok),[{k:"b",id:F.alias,t:F.t,attrs:Object.fromEntries(Me(ue.nodes[F.t]).map(B=>[B,Je(ue.nodes[F.t],B)]))}],K);for(let F=f.length-1;F>=0;F--)if(k){let{r:B,old:J,next:U}=X[F],P=J.tokens.map((oe,ee)=>{let te=h.mapResult(B.oa+ee,1),Z=h.mapResult(B.oa+ee+1,-1),ie=te.pos-B.na;return!te.deleted&&!Z.deleted&&Z.pos===te.pos+1&&ie>=0&&ie<U.tokens.length&&Ue(oe,U.tokens[ie])});Vt(L,J.start,J.tokens,U.tokens,P)}else{let B=f[F],J=A[B.oa],U=A[B.ob];Vt(L,J,W.slice(J,U),j.slice(D[B.na],D[B.nb]))}let d=C.length?de(e):null,S=d?{...L,map:Ft(d.tokens,d.holes,e.flow.length)}:null;for(let{i:F,step:B}of C){let J=new gt(x.slice(F+1)),U=D[J.map(B.from,1)],P=D[J.map(B.to,-1)];if(P<=U)continue;let oe=B.mark.type.name,ee=B instanceof Eo?B.mark.attrs&&Object.keys(B.mark.attrs).length?{...B.mark.attrs}:!0:null;if(kn(B.mark)){if(ee===null)continue;let te=yn(B.mark.attrs.entries);K(()=>{for(let[Z,ie]of Object.entries(te))Wt(S,U,P,Z,ie,j)});continue}K(()=>Wt(S,U,P,oe,ee,j))}};c||n?.stopCapturing();let b=n?.captureTimeout;n&&(n.captureTimeout=1/0);try{R?Q():e.ydoc.transact(d=>{d.meta.set(Ke,s),a(),Q()},be)}finally{n&&(n.captureTimeout=b),i||n?.stopCapturing()}r.groups++,r.lastGroup={chunked:R,structural:q,regional:k,span:$}}var ve=e=>({status:"refused",code:e}),kt=e=>{if(!e)return"";let o=[];for(let t of Object.keys(e).sort())o.push(`${t}=${JSON.stringify(e[t])}`);return o.join(`
4
4
  `)},Or=(e,o,t)=>{let r=t?t.state.doc:null,s=r&&r.childCount===o.visible.length&&o.visible.every((c,i)=>r.child(i).attrs.id===c.id)?r:De(e,o),l=[];return s.forEach(c=>{c.attrs.id===null||c.attrs.id===void 0||l.push({id:c.attrs.id,parent:c.attrs.parent??null,t:c.type.name})}),l},Er=(e,o)=>{let t=[],r=e.get(o)?.parent??null,n=0;for(;r!=null&&n++<=e.size;)t.push(r),r=e.get(r)?.parent??null;return t},Ro=(e,o,t)=>Er(e,t).includes(o),qt=(e,o,t)=>o===t||Ro(e,t,o),Ut=(e,o,t,r,n)=>{if(o?.recovered){let l=qe(o.sourceKey,r);(e.gone.has(l)?e.gone.get(l):o.fields?.[r]??null)!==n&&e.gone.set(l,n);return}let s=e.attrs.get(t);s||(s=new $e,e.attrs.set(t,s)),s.get(r)!==n&&s.set(r,n)},bt=(e,o,t,r)=>Ut(e,o,t,"parent",r),Mr=8,Co={indent:(e,o)=>o.t==="list_item"&&Number.isInteger(e)&&e>=0&&e<=Mr,open:(e,o)=>o.t==="toggle"&&typeof e=="boolean",parent:(e,o,t)=>e===null||typeof e=="string"&&t.get(e)?.t==="toggle"&&!qt(t,e,o.id)},Ir=(e,o)=>{if(e?.attrs===void 0)return[];if(!e.attrs||typeof e.attrs!="object"||Array.isArray(e.attrs))return null;let t=[];for(let[r,n]of Object.entries(e.attrs)){let s=o.get(r);if(!s||!n||typeof n!="object"||Array.isArray(n))return null;for(let[l,c]of Object.entries(n)){if(!Co[l]||!Co[l](c,s,o))return null;t.push({id:r,field:l,value:c})}}return t},Cr=(e,o)=>{let t=_e(e.flow,0,e.flow.length),r=[],n=0;for(let s of e.flow.toDelta()){let l=s.attributes;if(typeof s.insert=="string")for(let c=0;c<s.insert.length;c++)r.push({ch:s.insert[c],attrs:l,source:o.resolve(t[n++])});else r.push({embed:s.insert,attrs:l,source:o.resolve(t[n++])})}if(n!==t.length)throw new Error(`The flow delta has ${n} units but the document has ${t.length}`);return r},Tr=(e,o,t)=>{let r=new Map;for(let s of o.visible)t.has(s.id)&&s.brk&&r.set(Te(s.brk),s.id);for(let s of t)for(let l of o.copies.get(s)??[])r.set(l,s);let n=[];for(let s=e.flow._start;s;s=s.right){if(s.deleted||!(s.content instanceof me))continue;let l=s.content.embed?.b;if(l===void 0||r.get(Te(s.id))!==l)continue;let c=null;for(let i=s.right;i;i=i.right){if(i.deleted||!(i.content instanceof me))continue;let a=i.content.embed?.b;if(!(a===void 0||a===l)){c=Te(i.id);break}}n.push({key:Te(s.id),blockId:l,end:c})}return n};function Gt({pd:e,view:o,um:t,origins:r,render:n,walked:s=null},l={}){let c=Array.isArray(l?.ids)?[...new Set(l.ids)]:[],i=l?.afterId===void 0?null:l.afterId,a=l?.parent!==void 0,p=s??de(e,r),w=new Set(p.visible.filter(b=>b.opaque).map(b=>b.id)),x=Or(e,p,o),h=new Map(x.map(b=>[b.id,b])),y=x.map(b=>b.id);if(!c.length)return ve("missing-source");for(let b of c)if(!h.has(b))return ve("missing-source");let v=Ir(l,h);if(!v)return ve("invalid-attrs");let _=v.filter(b=>b.field==="parent"),N=new Set(c.filter(b=>!c.some(d=>d!==b&&Ro(h,d,b)))),m=x.filter(b=>c.some(d=>qt(h,b.id,d))),O=new Set(m.map(b=>b.id));if(m.some(b=>w.has(b.id))||v.some(b=>w.has(b.id)))return ve("unsupported-format");let Y=new Map(p.visible.map(b=>[b.id,b]));for(let b of m){let d=Y.get(b.id);if(!d||d.implicit||!d.brk)return ve("missing-source")}let I;if(a)I=l.parent??null;else{let b=new Set(m.filter(d=>N.has(d.id)).map(d=>d.parent));if(b.size!==1)return ve("invalid-parent");I=[...b][0]}if(a&&I!==null){let b=h.get(I);if(!b||b.t!=="toggle")return ve("invalid-parent");if(O.has(I))return ve("cycle")}if(i!==null){if(typeof i!="string"||!h.has(i))return ve("missing-destination");if(O.has(i))return ve("cycle");if(h.get(i).parent!==I)return ve("missing-destination")}let E=x.filter(b=>!O.has(b.id)),u=0;if(i===null){if(I!==null){let b=E.findIndex(S=>S.parent===I),d=E.findIndex(S=>S.id===I);u=b>=0?b:d<0?0:d+1}}else for(u=E.findIndex(b=>b.id===i)+1;u<E.length&&qt(h,E[u].id,i);)u++;let C=[...E.slice(0,u),...m,...E.slice(u)],f=C.length===y.length&&C.every((b,d)=>b.id===y[d]),k=m.filter(b=>N.has(b.id)&&b.parent!==I),A=m.map(b=>b.id);if(f&&!k.length&&!v.length)return{status:"unchanged"};let D=(()=>{let b=o?.state.selection;if(!(b instanceof pe.TextSelection))return null;let d=B=>{let J=o.state.doc.resolve(B);return J.depth?{id:J.node(1).attrs.id,offset:J.parentOffset}:null},S=d(b.anchor),F=d(b.head);return S&&F&&(O.has(S.id)||O.has(F.id))?{anchor:S,head:F}:null})(),W=()=>{if(!D||!o)return;let b=({id:F,offset:B})=>{let J=null;return o.state.doc.forEach((U,P)=>{J===null&&U.attrs.id===F&&(J=P+1+Math.min(B,U.content.size))}),J},d=b(D.anchor),S=b(D.head);d!==null&&S!==null&&o.dispatch(o.state.tr.setSelection(pe.TextSelection.create(o.state.doc,d,S)).setMeta(Ye,!0).setMeta("addToHistory",!1))};if(f)return t?.stopCapturing(),e.ydoc.transact(()=>{if(_.length)for(let b of _)bt(e,Y.get(b.id),b.id,b.value);else for(let b of k)bt(e,Y.get(b.id),b.id,I);for(let b of v)b.field!=="parent"&&Ut(e,Y.get(b.id),b.id,b.field,b.value)},be),t?.stopCapturing(),n(),W(),{status:"moved",ids:A};let j=[...st(it(e.ydoc)).entries()].sort((b,d)=>b[0]-d[0]),X=ye(e),$=Cr(e,r),R=at(p,e.flow.length),K=[],L=0;for(let b of p.visible){if(O.has(b.id)){let d=[];for(let[S,F]of R.physicalRanges(L,L+b.len))for(let B=S;B<F;B++)d.push($[B]);K.push({seg:b,units:d})}L+=b.len}for(let b=0;b<K.length;b++){let d=K[b];if(d.seg.id!==A[b])throw new Error(`Captured ${d.seg.id} where ${A[b]} was expected`);if(!d.units.length||d.units[0].embed===void 0||d.units[0].embed.b!==d.seg.id)throw new Error(`The selected block ${d.seg.id} has no physical marker to copy`)}let M=Tr(e,p,O),q=Ae(e.gone),Q=new Map;for(let b of m){let d=Y.get(b.id);if(!d.recovered)continue;let S=p.removals.filter(J=>J.sourceKey===d.sourceKey),F=Vn(d.sourceKey,S,q),B=q.restores.find(J=>J.key===F?.key)?.baseline??{type:d.t,attrs:d.fields??{}};Q.set(d.sourceKey,{covers:S.map(J=>J.key),baseline:JSON.parse(JSON.stringify(B))})}if(!M.length)throw new Error("The selected blocks have no live physical markers to retire");return t?.stopCapturing(),e.ydoc.transact(()=>{for(let P of M)e.gone.set(We(P.key,X),{blockId:P.blockId,end:P.end,sv:j});let b=de(e,r),d=at(b,e.flow.length),S=b.visible.map(P=>P.id),F=0;if(u>0){let P=S.indexOf(E[u-1].id);F=P<0?0:P+1}let B=0;for(let P=0;P<F;P++)B+=b.visible[P].len;let J=d.toPhysical(B,"before"),U=[];for(let P of K){let oe=J,ee=null,te=null,Z=()=>{ee!==null&&(Ie(e,J,b.fences,()=>e.flow.insert(J,ee,te??void 0)),J+=ee.length,ee=null)};for(let re of P.units)re.ch!==void 0?(ee!==null&&kt(re.attrs)!==kt(te)&&Z(),ee===null&&(ee="",te=re.attrs),ee+=re.ch):(Z(),Ie(e,J,b.fences,()=>e.flow.insertEmbed(J,re.embed,re.attrs)),J+=1);Z();let ie=_e(e.flow,oe,J);if(ie.length!==P.units.length)throw new Error(`Copied ${P.seg.id} as ${ie.length} units instead of ${P.units.length}`);for(let re=1;re<P.units.length;re++)U.push({dest:ie[re],source:P.units[re].source});r.recordBoundary(ie[0],P.seg.recovered?{blockId:P.seg.id,kind:"copy",recoveryOf:P.seg.sourceKey}:{blockId:P.seg.id,kind:"copy"}),P.seg.recovered&&e.gone.set(ft(P.seg.sourceKey,X),Q.get(P.seg.sourceKey)),e.gone.set(Kn(Te(ie[0])),!0)}if(U.length&&r.recordSpans(U),_.length)for(let P of _)bt(e,Y.get(P.id),P.id,P.value);else for(let P of k)bt(e,Y.get(P.id),P.id,I);for(let P of v)P.field!=="parent"&&Ut(e,Y.get(P.id),P.id,P.field,P.value)},be),t?.stopCapturing(),n(),W(),{status:"moved",ids:A}}var Po="blockeditor-move-carry",To=`["${Nn}",`,Ar=`["${Ln}",`,Yr=`["${Bn}",`,$o=(e,o)=>{let t=ut(o);if(!t)return null;let r=null;try{r=ge(e.ydoc.store,t)}catch{return null}return r instanceof Ee&&!r.deleted&&r.parent===e.flow?r:null},Rr=(e,o,t,r,n)=>{let s=0,l=null;for(let a of t.visible){if(a.id===n){l=a;break}s+=a.len}if(!l||l.implicit||l.atom||l.opaque||!l.brk)return null;let c=new Map,i=null;for(let[a,p]of r.physicalRanges(s,s+l.len)){let w=_e(e.flow,a,p);for(let x=0;x<w.length;x++)i===null?i=a:c.set(ne(o.resolve(w[x])),a+x)}return i===null?null:{head:i,places:c}},Pr=(e,o)=>{let t=new Map;for(let r=e.flow._start;r&&r!==o;r=r.right)r.deleted||!(r.content instanceof we)||(r.content.value===null?t.delete(r.content.key):t.set(r.content.key,r.content.value));return t},tt=e=>{let o=un();for(let{client:t,clock:r,len:n}of e)(o.clients.get(t)??o.clients.set(t,[]).get(t)).push({clock:r,len:n});return o},yt=e=>e.content instanceof me&&e.content.embed?.b!==void 0,$r=(e,o,t)=>{let r=[],n=t,s=null;for(;;){let l=o.get(n);if(l!==void 0){s=l;break}r.push(n);let c=null;if(n.origin)try{c=ge(e.ydoc.store,n.origin)}catch{c=null}if(!(c instanceof Ee))break;if(yt(c)){s=c;break}n=c}for(let l of r)o.set(l,s);return s};function _r({pd:e,origins:o,walked:t,placed:r},n,s,l=null,c=!1){let i=t.hidden.filter(m=>n.has(m.key));if(!i.length)return!1;let a=e.ydoc.clientID,p=l!==null||c?Ae(e.gone).textDeletes.filter(m=>m.actor!==a):[],w=new Map,x=new Set,h=[],y=new Map,v=null,_=null;for(let m of i){let O=n.get(m.key),{left:Y,past:I}=O,E=$o(e,m.sourceKey);if(!E)continue;let u=new Map(m.items.map(M=>[M.id,M])),C=[];for(let M=E.right;M&&!(M.countable&&!M.deleted&&!u.has(ne(M.id)));M=M.right)C.push(M);let f=new Set(O.copy?C.filter(M=>!M.deleted&&M.countable&&!yt(M)&&!Y.has(`${ne(M.id)}+${M.length}`)&&$r(e,s,M)===E):[]),k=p.filter(M=>C.some(q=>q.deleted&&q.countable&&q.id.client===M.client&&M.clock<q.id.clock+q.length&&q.id.clock<M.clock+M.length));if(!f.size&&!k.length)continue;let A=O.seen??new Map(m.sv),D=(M,q)=>q>=(A.get(M)??0),W=f.size?Pr(e,E):null,j=null,X=[],$=new Map;for(let M of C){if(!M.countable){W&&M.content instanceof we&&(!M.deleted||xt(I,M.id))&&(M.content.value===null?W.delete(M.content.key):W.set(M.content.key,M.content.value),j=null);continue}let q=M.deleted?null:u.get(ne(M.id)),Q=f.has(M);for(let b=0;b<M.length;b++){let d={client:M.id.client,clock:M.id.clock+b},S=o.resolve(d),F=ne(S);M.deleted&&k.length&&An(k,a,d)?!$.has(F)&&(!O.alive||D(d.client,d.clock)||O.alive.has(ne(d)))&&$.set(F,!1):$.set(F,!0),X.push({it:M,item:q,offset:b,id:d,source:S,key:F,attrs:Q?j??=Object.fromEntries(W):null})}}_??=at(t,e.flow.length);let R=Rr(e,o,t,_,m.blockId);if(!R){for(let M of f)Y.add(`${ne(M.id)}+${M.length}`);continue}if(k.length)for(let[M,q]of R.places)$.get(M)===!1&&!w.has(q)&&w.set(q,null);let K=new Map,L=R.head+1;for(let M of X){let{it:q,item:Q,offset:b,id:d,source:S}=M;if(M.attrs){if(!x.has(ne(d))&&!(v??=Wn(e.flow,t,o))(S.client,S.clock)){x.add(ne(d)),w.set(Q.at+b,O),O.step&&!y.has(O)&&y.set(O,{deleted:[],inserted:[]}),(K.get(L)??K.set(L,[]).get(L)).push(Q.kind==="text"?{ch:q.content.str[b],attrs:M.attrs,source:S}:{embed:q.content.embed,attrs:M.attrs,source:S});continue}Y.add(`${ne(q.id)}+${q.length}`)}let F=R.places.get(M.key);F!==void 0&&(L=F+1)}for(let[M,q]of K)h.push({at:M,units:q,owner:O})}if(!w.size&&!h.length)return!1;let N=[...[...w].map(([m,O])=>({at:m,owner:O})),...h].sort((m,O)=>O.at-m.at||(m.units?1:0)-(O.units?1:0));e.ydoc.transact(m=>{let O=null,Y=()=>{if(!O)return;let I=y.get(O.owner),E=I?new Map([...m.deleteSet.clients].map(([u,C])=>[u,C.length])):null;if(e.flow.delete(O.from,O.to-O.from),I)for(let[u,C]of m.deleteSet.clients)for(let{clock:f,len:k}of C.slice(E.get(u)??0)){let A=ge(e.ydoc.store,{client:u,clock:f});A instanceof Ee&&(A.keep=!0),I.deleted.push({client:u,clock:f,len:k})}O=null};for(let I of N){if(!I.units){O&&I.at===O.from-1&&I.owner===O.owner?O.from=I.at:(Y(),O={from:I.at,to:I.at+1,owner:I.owner});continue}Y();let E=Ne(e.ydoc.store,a),u=I.at,C="",f=null,k=()=>{if(!C)return;let D=C;Ie(e,u,t.fences,()=>e.flow.insert(u,D,{...f})),u+=D.length,C=""};for(let D of I.units){if(D.ch===void 0){k(),Ie(e,u,t.fences,()=>e.flow.insertEmbed(u,{...D.embed},{...D.attrs})),u+=1;continue}C&&kt(D.attrs)!==kt(f)&&k(),f=D.attrs,C+=D.ch}k(),y.get(I.owner)?.inserted.push({client:a,clock:E,len:Ne(e.ydoc.store,a)-E});let A=_e(e.flow,I.at,u);if(A.length!==I.units.length)throw new Error(`Carried ${A.length} units instead of ${I.units.length}`);o.recordSpans(A.map((D,W)=>({dest:D,source:I.units[W].source}))),r.push({ids:A,step:I.owner.step})}Y()},Po);for(let[{step:m},O]of y)m.deletions=Le([m.deletions,tt(O.deleted)]),m.insertions=Le([m.insertions,tt(O.inserted)]);return!0}var Ao=(e,o,t)=>{for(let[r,n]of o.clients)for(let{clock:s,len:l}of n)for(let c=s;c<s+l;){let i=null;try{i=ge(e.ydoc.store,{client:r,clock:c})}catch{break}let a=Math.min(s+l,i.id.clock+i.length);if(i instanceof Ee&&i.parent===e.flow&&i.countable)for(let p=c;p<a;p++)t(i,{client:r,clock:p});c=a}},Dr=(e,o)=>e.some(t=>t.client===o.client&&o.clock>=t.clock&&o.clock<t.clock+t.length),_o=(e,o)=>{try{return ge(e.ydoc.store,o).deleted}catch{return!0}},jr=(e,o,t)=>{let r=[];if(Ao(e,t.insertions,(i,a)=>{i.deleted&&r.push(a)}),!r.length)return;let n=Ae(e.gone).textDeletes,s=new Map;for(let i of r){let a=o.resolve(i),p=s.get(ne(a))??s.set(ne(a),{source:a,follow:!1,redo:[]}).get(ne(a));!p.follow&&!Dr(n,i)&&_o(e,a)&&(p.follow=!0)}Ao(e,t.deletions,(i,a)=>s.get(ne(o.resolve(a)))?.redo.push(a));let l=new Map;for(let i of s.values())!i.follow&&!i.redo.length||(i.lives=[],(l.get(i.source.client)??l.set(i.source.client,[]).get(i.source.client)).push(i));if(!l.size)return;for(let i=e.flow._start;i;i=i.right){if(i.deleted||!i.countable)continue;let a=i.id.clock;for(let p of o.resolveRange(i.id.client,i.id.clock,i.length)){for(let w of l.get(p.client)??[]){let x=w.source.clock-p.clock;x>=0&&x<p.length&&w.lives.push({client:i.id.client,clock:a+x,len:1})}a+=p.length}}let c=[];for(let i of l.values())for(let a of i)if(a.follow&&c.push(...a.lives),!a.lives.length)for(let p of a.redo)c.push({client:p.client,clock:p.clock,len:1});c.length&&(t.insertions=Le([t.insertions,tt(c)]))},Yo=(e,o)=>o!==null&&e.id.client===o.client&&o.clock>=e.id.clock&&o.clock<e.id.clock+e.length,Fr=(e,o)=>{let t;try{t=ge(e.ydoc.store,o[0])}catch{return null}if(t.id.clock!==o[0].clock||!t.origin)return null;let r=[t],n=null;for(let s=t.left;s&&!Yo(s,t.origin);s=s.left)yt(s)&&s.id.client!==e.ydoc.clientID&&!r.some(l=>Yo(l,s.rightOrigin))&&(n=s),r.push(s);return n},Lr=(e,o,t,r)=>{let n=[],s=[];for(let c of r){let i=c.ids.filter(p=>!_o(e,p));if(!i.length)continue;let a=Fr(e,c.ids);a?s.push({group:c,edge:a,live:new Set(i.map(ne))}):n.push(c)}if(!s.length)return r;let l=e.ydoc.clientID;return e.ydoc.transact(()=>{for(let{group:c,edge:i,live:a}of s){let p=new Map,w=[],x=0;for(let m=e.flow._start;m;m=m.right){if(m.content instanceof we){m.deleted||(m.content.value===null?p.delete(m.content.key):p.set(m.content.key,m.content.value));continue}if(!(m.deleted||!m.countable)){for(let O=0;O<m.length;O++){let Y={client:m.id.client,clock:m.id.clock+O};a.has(ne(Y))&&w.push({at:x+O,ch:m.content instanceof Be?m.content.str[O]:void 0,embed:m.content.embed,attrs:Object.fromEntries(p),source:o.resolve(Y)})}x+=m.length}}for(let m=w.length-1;m>=0;m--)e.flow.delete(w[m].at,1);let h=0;for(let m=e.flow._start;m&&m!==i;m=m.right)!m.deleted&&m.countable&&(h+=m.length);let y=h,v=Ne(e.ydoc.store,l),_=[...t.fences,i.id];for(let m of w)m.ch===void 0?Ie(e,h,_,()=>e.flow.insertEmbed(h,{...m.embed},{...m.attrs})):Ie(e,h,_,()=>e.flow.insert(h,m.ch,{...m.attrs})),h+=1;let N=_e(e.flow,y,h);if(N.length!==w.length)throw new Error(`Moved ${N.length} carried units instead of ${w.length}`);o.recordSpans(N.map((m,O)=>({dest:m,source:w[O].source}))),c.step&&(c.step.insertions=Le([c.step.insertions,tt([{client:l,clock:v,len:Ne(e.ydoc.store,l)-v}])])),n.push({ids:N,step:c.step})}},Po),n},Nr=(e,o)=>{let t=e.ydoc.store;for(let[r,n]of o.insertions.clients)for(let{clock:s,len:l}of n)for(let c=s;c<s+l;){let i;try{i=ge(t,{client:r,clock:c})}catch{break}let a=i;for(;a instanceof Ee&&a.redone;)try{a=ge(t,a.redone)}catch{break}if(a instanceof Ee&&!a.deleted)return!0;c=i.id.clock+i.length}for(let[r,n]of o.deletions.clients)for(let{clock:s}of n)if(!xt(o.insertions,{client:r,clock:s}))return!0;return!1},Br=(e,o)=>{let t=new Set;for(let r=$o(e,o)?.right??null;r;r=r.right)if(!(!r.countable||r.deleted)){if(yt(r))break;for(let n=0;n<r.length;n++)t.add(ne({client:r.id.client,clock:r.id.clock+n}))}return t};function Do({pd:e,origins:o,um:t,walked:r}){let n=new Map,s=new Map,l=new WeakMap,c=null,i=[],a=(p=null,w=!1)=>n.size>0&&_r({pd:e,origins:o,walked:r(),placed:i},n,l,p,w);return{note(p){let w=[...p.changed.get(e.gone)??[]].filter(y=>typeof y=="string");if(!w.some(y=>y.startsWith(To)))return;let x=new Set,h=tt([...p.deleteSet.clients].flatMap(([y,v])=>v.map(({clock:_,len:N})=>({client:y,clock:_,len:N}))));for(let y of w){let v=y.startsWith(To);if(!(!v&&!y.startsWith(Ar))){if(e.gone.has(y)===v){n.delete(y),v||s.set(y,{seen:p.afterState,alive:Br(e,JSON.parse(y)[1])});continue}x.add(y),n.set(y,{copy:v,left:new Set,past:h,seen:null,alive:null,step:null,...v?null:s.get(y)})}}x.size&&(c=x)},replay(p){let w=p==="undo"?t.undoStack:t.redoStack;for(let v=w.length-1;v>=0&&(jr(e,o,w[v]),!Nr(e,w[v]));v--);let x=p==="undo"?t.redoStack:t.undoStack,h=x.length;if(c=null,t[p]()===null)return!1;let y=c;if(c=null,y&&x.length>h)for(let v of y)n.get(v).step=x[x.length-1];return a(y),!0},received(p){if(!n.size&&!i.length)return;let w=!1,x=!1;for(let h of p)if(!h.local){w=!0;for(let y of h.changed.get(e.gone)??[])typeof y=="string"&&y.startsWith(Yr)&&(x=!0)}w&&(a(null,x),i.length&&(i=Lr(e,o,r(),i)))}}}var Xt=e=>{let o=[];return e.forEach(t=>o.push([t.type.name,JSON.stringify(Object.fromEntries(Me(t.type).map(r=>[r,t.attrs[r]]))),t.isTextblock||t.type.name==="table"?JSON.stringify(t.content.toJSON()):null])),JSON.stringify(o)};function zr(e,o){if(e.childCount!==o.childCount)return!1;for(let t=0;t<e.childCount;t++){let r=e.child(t),n=o.child(t);if(r!==n&&(r.type!==n.type||Me(r.type).some(s=>!xe(r.attrs[s],n.attrs[s]))||(r.isTextblock||r.type.name==="table")&&!r.content.eq(n.content)))return!1}return!0}var Kr=e=>{let o=[];return e.forEach((t,r)=>{t.type.name==="opaque_block"&&o.push([r,r+t.nodeSize])}),o},Jr=(e,o)=>{let t=typeof e.from=="number"?e.from:typeof e.pos=="number"?e.pos:null;if(t===null)return!1;let r=typeof e.to=="number"?e.to:t+1;return o.some(([n,s])=>t<s&&r>n)},nt=(e,o)=>{let t=e.resolve(o);return t.depth&&t.node(1).type.name==="table"?[t.before(1),t.after(1)]:null};function jo(e,o){let t=e.content.findDiffStart(o.content);if(t===null)return null;let{a:r,b:n}=e.content.findDiffEnd(o.content),s=t-Math.min(r,n);s>0&&(r+=s,n+=s);let l=(c,i)=>{let a=c.resolve(t);return a.parent.isTextblock&&a.sameParent(c.resolve(i))};return(nt(e,t)||nt(e,r))&&!(l(e,r)&&l(o,n))?(t=nt(e,t)?.[0]??t,r=nt(e,r)?.[1]??r,n=nt(o,n)?.[1]??n,{start:t,endA:r,endB:n,tables:!0}):{start:t,endA:r,endB:n}}function Qt(e,o=null){let t=new Map;o?.forEach(i=>{i.attrs.id&&t.set(i.attrs.id,i)});let r=[];e.forEach(i=>r.push(i));let n=r.map(i=>({id:i.attrs.id,pos:t.get(i.attrs.id)?.attrs.pos??i.attrs.pos})),s=It(n,"b"),l=!1,c=r.map((i,a)=>{let p=s[a]?.pos??n[a].pos,w=i.content;if(i.type.name==="table"){let y=[];i.forEach(m=>y.push(m));let v=y.map(m=>({id:m.attrs.id,pos:m.attrs.pos})),_=It(v,"r"),N=y.map((m,O)=>{let Y=_[O]?.pos??v[O].pos;return Y===m.attrs.pos?m:m.type.create({...m.attrs,pos:Y},m.content,m.marks)});N.some((m,O)=>m!==y[O])&&(w=N)}if(p===i.attrs.pos&&w===i.content)return i;l=!0;let x={...i.attrs,pos:p},h=t.get(i.attrs.id);return h&&w===i.content&&h.hasMarkup(i.type,x,i.marks)&&h.content.eq(w)?h:i.type.create(x,w,i.marks)});return l?e.type.create(e.attrs,c):e}var Fo=e=>{let o=new Set,t=null;for(let r=0;r<e.childCount;r++){let{id:n,pos:s}=e.child(r).attrs;if(!n||o.has(n)||!vn(s)||t!==null&&t>=s)return!1;o.add(n),t=s}return!0},Hr=(e,o)=>{for(let t in e.attrs)if(t!=="pos"&&e.attrs[t]!==o.attrs[t])return!1;return!0};function Vr(e,o){if(e.childCount!==o.childCount||!Fo(e))return!1;for(let t=0;t<e.childCount;t++){let r=e.child(t),n=o.child(t);if(r===n)continue;if(!(r.type===n.type&&r.marks===n.marks&&Hr(r,n))&&!r.hasMarkup(n.type,{...n.attrs,pos:r.attrs.pos},n.marks)||!r.content.eq(n.content)||r.type.name==="table"&&!Fo(r))return!1}return!0}var No=e=>{if(e&&typeof e=="object"){for(let o of Object.keys(e))No(e[o]);Object.freeze(e)}return e},Lo=e=>No(JSON.parse(JSON.stringify(e))),Wr=(e,o)=>{let t=En(o),r=0;for(let n=e.flow._start;n;n=n.right){if(n.id.client===t.client&&n.id.clock===t.clock)return n.deleted?r:r+n.length;!n.deleted&&n.countable&&(r+=n.length)}return r},qr=(e,o)=>{let t=null;for(let r=e.flow._start;r;r=r.right)r.id.client!==e.ydoc.clientID||!(r.content instanceof me)||r.content.embed?.b!==o||(!t||r.id.clock>t.clock)&&(t=r.id);return t};function Bo({pd:e,onNotice:o=()=>{},ownedTokens:t=[],authorToken:r=null,stats:n={groups:0,mismatch:0,renders:0,first:null},captureTimeout:s=500}){let l=null,c=null,i=0,a=-1,p=null,w=0,x=new WeakMap,h=Ve(e.origins);c=de(e,h);let y=new pn([e.flow,e.attrs,e.gone,e.tableFields,e.boardFields],{trackedOrigins:new Set([be]),captureTimeout:s,captureTransaction:g=>g.meta.get(Ke)!==!1,deleteFilter:g=>{if(g.parent!==e.flow||!(g.content instanceof me))return!0;let T=h.resolve(g.id);return T.client!==g.id.client||T.clock!==g.id.clock||h.boundaryOf(g.id)?.kind!=="copy"}}),v=Yn(e,y,h,g=>Ae(g).textDeletes),_=new Set,N=new Set(r?[...t,r]:t),m=r?()=>{let g=zn(e.ydoc.clientID);e.origins.get(g)!==r&&e.origins.set(g,r)}:null,O=new Set,Y=new Set,I=0,E=null,u=null,C=g=>{let T=new Set;for(let H of g.blocks)for(let G of H.runs){if(!G.displaced)continue;let V=ut(G.source)?.client===e.ydoc.clientID;G.author&&(V||N.has(G.author))?T.add(G.author):V&&T.add(null)}if(!T.size)return null;let z=[...T].filter(Boolean).sort();return{kind:"recovered-change",source:g.source,revision:g.revision,blockId:g.blockId,author:z[0]??null,authors:z}},f=g=>{let T=g.list.filter(H=>H.recoverable).map(H=>Lo(H)),z=Lo(T.map(H=>C(H)).filter(H=>H&&!O.has(`${H.source}\0${H.revision}`)));return Object.freeze({recoverable:Object.freeze(T),notices:Object.freeze(z)})},k=(g,T)=>{if(JSON.stringify(f(mt(e,{index:h,walked:T})))===JSON.stringify(g)){n.provedRecoveries=(n.provedRecoveries??0)+1;return}throw n.walkMismatch=(n.walkMismatch??0)+1,new Error("Recovery snapshot built from the displacing sources diverged from a full reduction")},A=()=>{if(E&&E.version===I)return E.snapshot;let g=a===i?c:void 0,T=f(qn(e,{index:h,walked:g}));return n.proveWalks&&k(T,g),E={version:I,snapshot:T},T},D=g=>dt({recoverable:g.recoverable.map(T=>[T.source,T.revision]),notices:g.notices}),W=()=>{I++;let g=A();for(let z of g.notices){let H=`${z.source}\0${z.revision}`;_.has(H)||(_.add(H),o(z))}if(!Y.size){u=null;return}let T=D(g);if(T!==u){u=T;for(let z of[...Y])z(g)}},j=g=>{c=g,a=i,p=null,w=0},X=()=>a===i?c:null,$=g=>{let T=et(e,g),z=et(e,de(e));if(T===z){n.provedWalks=(n.provedWalks??0)+1;return}throw n.walkMismatch=(n.walkMismatch??0)+1,new Error(`Incremental walk diverged from the full walk:
@@ -1 +1 @@
1
- import{a as _,d as v}from"./c-WN3MXOLT.js";import{b as c}from"./c-RVMWGXEJ.js";import{b as u,c as s}from"./c-NUHP2XDB.js";import{e as b}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 d="#FFFCF6",l=["all:initial","color-scheme:inherit","direction:ltr","unicode-bidi:isolate"],y=18,h=3,p=null,f=null;function C(){return f??=Promise.all([import("./c-33SS5A4Y.js"),import("./c-46LJAZZJ.js")]).then(([i,e])=>p={RUNTIME_ONLY:i.RUNTIME_ONLY,CHIP_FONT:`600 11px/16px ${e.FONT_MONO}`}).catch(i=>{throw f=null,i}),f}var $=()=>C().then(()=>!0,()=>!1);function a(i){return i.setAttribute("clay",p.RUNTIME_ONLY),i}function A(i){let e=i&&Array.isArray(i.people)?i.people:[],o=[];for(let t of e){if(!t||t.you===!0||typeof t.id!="string"||!t.id||typeof t.editing!="string"||!_.test(t.editing))continue;let n=typeof t.name=="string"&&t.name.trim()?t.name.trim():"Someone";o.push({id:t.id,name:n,path:t.editing})}return o}var m=class{constructor(){this.editors=[],this.root=null,this._gate=null,this._frame=0,this._following=!1,this._onMove=()=>this.schedule()}supported(){return this._gate||(this._gate=b("presence").then(e=>e===!0,()=>!1)),this._gate}async update(e){this.editors=A(e),await this.supported()&&await this.render()}clear(){this.editors=[],this.follow(!1),this._frame&&cancelAnimationFrame(this._frame),this._frame=0,this.root&&this.root.remove(),this.root=null}schedule(){this._frame||(this._frame=requestAnimationFrame(()=>{this._frame=0,this.render()}))}render(){return p?(this.paint(),Promise.resolve()):$().then(e=>{e&&this.paint()})}paint(){let e=new Map;for(let t of this.editors){let n=v(t.path);n&&(e.has(n)||e.set(n,[]),e.get(n).push(t))}let o=[];for(let[t,n]of e){let r=this.box(t,n);r&&o.push(r)}if(!o.length){this.root&&(this.root.textContent="",u(this.root,"display","none")),this.follow(this.editors.length>0);return}this.build()&&(this.root.textContent="",this.root.append(...o),u(this.root,"display","block"),this.follow(!0))}box(e,o){let t=e.getBoundingClientRect();if(!(t.width||t.height))return null;let n=c(o[0].id),r=a(s("div",[...l,"position:fixed","box-sizing:border-box","pointer-events:none",`top:${Math.round(t.top-h)}px`,`left:${Math.round(t.left-h)}px`,`width:${Math.round(t.width+h*2)}px`,`height:${Math.round(t.height+h*2)}px`,`border:2px solid ${n}`,`box-shadow:0 0 0 1px ${d}, inset 0 0 0 1px ${d}`]));r.setAttribute("data-clay-editing-marker","");let M=t.top-h>=y+2,x=a(s("div",[...l,"position:absolute","left:-2px",M?"bottom:100%":"top:100%","display:flex","gap:2px","pointer-events:none"]));for(let g of o){let w=a(s("span",[...l,"box-sizing:border-box",`height:${y}px`,"padding:1px 6px",`font:${p.CHIP_FONT}`,"letter-spacing:.02em","white-space:nowrap","max-width:180px","overflow:hidden","text-overflow:ellipsis",`background-color:${c(g.id)}`,`color:${d}`,`box-shadow:0 0 0 1px ${d}`],g.name));w.setAttribute("data-clay-editing-chip",""),x.appendChild(w)}return r.appendChild(x),r}build(){return this.root&&this.root.isConnected?!0:typeof document>"u"||!document.body?!1:(this.root=a(s("div",[...l,"position:fixed","top:0","left:0","width:0","height:0","overflow:visible","z-index:2147482999","pointer-events:none","display:none"])),this.root.setAttribute("data-clay-editing",""),document.body.appendChild(this.root),!0)}follow(e){if(typeof window>"u"||!!e===this._following)return;this._following=!!e;let o=e?"addEventListener":"removeEventListener";window[o]("scroll",this._onMove,{capture:!0,passive:!0}),window[o]("resize",this._onMove,{passive:!0}),document[o]("input",this._onMove),document[o]("clay:sync-applied",this._onMove)}},N=new m;var O=N;export{m as EditingMarker,O as default,N as editingMarker};
1
+ import{a as _,d as v}from"./c-WN3MXOLT.js";import{b as c}from"./c-RVMWGXEJ.js";import{b as u,c as s}from"./c-NUHP2XDB.js";import{e as b}from"./c-26W3BMWK.js";import"./c-JEWSJHMK.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 d="#FFFCF6",l=["all:initial","color-scheme:inherit","direction:ltr","unicode-bidi:isolate"],y=18,h=3,p=null,f=null;function C(){return f??=Promise.all([import("./c-33SS5A4Y.js"),import("./c-46LJAZZJ.js")]).then(([i,e])=>p={RUNTIME_ONLY:i.RUNTIME_ONLY,CHIP_FONT:`600 11px/16px ${e.FONT_MONO}`}).catch(i=>{throw f=null,i}),f}var $=()=>C().then(()=>!0,()=>!1);function a(i){return i.setAttribute("clay",p.RUNTIME_ONLY),i}function A(i){let e=i&&Array.isArray(i.people)?i.people:[],o=[];for(let t of e){if(!t||t.you===!0||typeof t.id!="string"||!t.id||typeof t.editing!="string"||!_.test(t.editing))continue;let n=typeof t.name=="string"&&t.name.trim()?t.name.trim():"Someone";o.push({id:t.id,name:n,path:t.editing})}return o}var m=class{constructor(){this.editors=[],this.root=null,this._gate=null,this._frame=0,this._following=!1,this._onMove=()=>this.schedule()}supported(){return this._gate||(this._gate=b("presence").then(e=>e===!0,()=>!1)),this._gate}async update(e){this.editors=A(e),await this.supported()&&await this.render()}clear(){this.editors=[],this.follow(!1),this._frame&&cancelAnimationFrame(this._frame),this._frame=0,this.root&&this.root.remove(),this.root=null}schedule(){this._frame||(this._frame=requestAnimationFrame(()=>{this._frame=0,this.render()}))}render(){return p?(this.paint(),Promise.resolve()):$().then(e=>{e&&this.paint()})}paint(){let e=new Map;for(let t of this.editors){let n=v(t.path);n&&(e.has(n)||e.set(n,[]),e.get(n).push(t))}let o=[];for(let[t,n]of e){let r=this.box(t,n);r&&o.push(r)}if(!o.length){this.root&&(this.root.textContent="",u(this.root,"display","none")),this.follow(this.editors.length>0);return}this.build()&&(this.root.textContent="",this.root.append(...o),u(this.root,"display","block"),this.follow(!0))}box(e,o){let t=e.getBoundingClientRect();if(!(t.width||t.height))return null;let n=c(o[0].id),r=a(s("div",[...l,"position:fixed","box-sizing:border-box","pointer-events:none",`top:${Math.round(t.top-h)}px`,`left:${Math.round(t.left-h)}px`,`width:${Math.round(t.width+h*2)}px`,`height:${Math.round(t.height+h*2)}px`,`border:2px solid ${n}`,`box-shadow:0 0 0 1px ${d}, inset 0 0 0 1px ${d}`]));r.setAttribute("data-clay-editing-marker","");let M=t.top-h>=y+2,x=a(s("div",[...l,"position:absolute","left:-2px",M?"bottom:100%":"top:100%","display:flex","gap:2px","pointer-events:none"]));for(let g of o){let w=a(s("span",[...l,"box-sizing:border-box",`height:${y}px`,"padding:1px 6px",`font:${p.CHIP_FONT}`,"letter-spacing:.02em","white-space:nowrap","max-width:180px","overflow:hidden","text-overflow:ellipsis",`background-color:${c(g.id)}`,`color:${d}`,`box-shadow:0 0 0 1px ${d}`],g.name));w.setAttribute("data-clay-editing-chip",""),x.appendChild(w)}return r.appendChild(x),r}build(){return this.root&&this.root.isConnected?!0:typeof document>"u"||!document.body?!1:(this.root=a(s("div",[...l,"position:fixed","top:0","left:0","width:0","height:0","overflow:visible","z-index:2147482999","pointer-events:none","display:none"])),this.root.setAttribute("data-clay-editing",""),document.body.appendChild(this.root),!0)}follow(e){if(typeof window>"u"||!!e===this._following)return;this._following=!!e;let o=e?"addEventListener":"removeEventListener";window[o]("scroll",this._onMove,{capture:!0,passive:!0}),window[o]("resize",this._onMove,{passive:!0}),document[o]("input",this._onMove),document[o]("clay:sync-applied",this._onMove)}},N=new m;var O=N;export{m as EditingMarker,O as default,N as editingMarker};
@@ -1 +1 @@
1
- import{n as g,s as k}from"./c-EHAR4RJJ.js";import{a as u,b as r,c as d,h as p}from"./c-KU3PX7LL.js";var v=3e4;function a(){return{ok:!1,code:"failed"}}async function x(n,{etag:o}={}){if(typeof n!="string"||n==="")return a();let m=o!==void 0,y=typeof o=="string"&&o?o:null;if(r()||await p(),!r())return{ok:!1,code:"unsupported"};let s=m?y:u();if(!s)return{ok:!1,code:"conflict"};let i=new AbortController,S=setTimeout(()=>i.abort(),v);try{let{url:c,options:b}=k(n,!0,i.signal,g(),s,!1,null,!1),t=await fetch(c,b),f=await t.text(),e={};if(f)try{e=JSON.parse(f)}catch{e={}}if(!t.ok)return t.status===412?{ok:!1,code:"conflict"}:t.status===401||t.status===403?{ok:!1,code:"forbidden"}:a();let l=typeof e.etag=="string"&&e.etag?e.etag:null;return d(l),{ok:!0,etag:l}}catch{return a()}finally{clearTimeout(S)}}export{x as a};
1
+ import{n as g,s as k}from"./c-CKG4NF7J.js";import{a as u,b as r,c as d,h as p}from"./c-OSGTRM4C.js";var v=3e4;function a(){return{ok:!1,code:"failed"}}async function x(n,{etag:o}={}){if(typeof n!="string"||n==="")return a();let m=o!==void 0,y=typeof o=="string"&&o?o:null;if(r()||await p(),!r())return{ok:!1,code:"unsupported"};let s=m?y:u();if(!s)return{ok:!1,code:"conflict"};let i=new AbortController,S=setTimeout(()=>i.abort(),v);try{let{url:c,options:b}=k(n,!0,i.signal,g(),s,!1,null,!1),t=await fetch(c,b),f=await t.text(),e={};if(f)try{e=JSON.parse(f)}catch{e={}}if(!t.ok)return t.status===412?{ok:!1,code:"conflict"}:t.status===401||t.status===403?{ok:!1,code:"forbidden"}:a();let l=typeof e.etag=="string"&&e.etag?e.etag:null;return d(l),{ok:!0,etag:l}}catch{return a()}finally{clearTimeout(S)}}export{x as a};
@@ -1 +1 @@
1
- import{d as A,e as I}from"./c-EQ5NBOGA.js";import{f as b,j as T}from"./c-C7SUMNMI.js";import{c as M}from"./c-BPF2NSPV.js";var B=15e3,P=12e4,K=15e3,V=4e3,W=5e3,U=50,y=new Set(["sent","acked"]),R=new Set(["done","error","cancelled"]),j="wire",a=new Map,k=new Set,f=null,g=null,D=0,h=null;function Q(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`page-${Date.now()}-${Math.random().toString(16).slice(2)}`}function H(e){return new URL(e,window.location.origin).href}function N(){let e=M();return typeof e=="string"&&e!==""?e:null}function w(e){return{id:e.id,type:e.type,state:e.state,helper:e.helper,text:e.text,result:e.result,error:e.error,errorCode:e.errorCode,errorDetails:e.errorDetails,errorSource:e.errorSource,startedAt:e.startedAt}}function m(e,t){let n=w(e);for(let r of k)try{r(n,t||null)}catch(s){console.error("clay.wire: a listener threw",s)}document.dispatchEvent(new CustomEvent("clay:wire-state",{detail:n}))}function Y(e,t){e.state!==t&&(e.state=t,m(e))}function v(e,t,n,{cancelFirst:r=!1,errorCode:s=null}={}){clearTimeout(e.timer),e.timer=setTimeout(()=>{e.timer=null,r&&z(e),l(e,"error",n,{errorCode:s,errorSource:"client"})},t)}function q(e){clearTimeout(e.timer),e.timer=null}function Z(){if(!(a.size<=U))for(let[e,t]of a){if(a.size<=U)break;!y.has(t.state)&&t.state!=="landing"&&a.delete(e)}}function ee(){if(g)return g;let e=N(),t=`/_/wire/subscribe?page-url=${encodeURIComponent(window.location.href)}`+(e?`&token=${encodeURIComponent(e)}`:"");return f=new EventSource(H(t)),f.onmessage=n=>{let r;try{r=JSON.parse(n.data)}catch{return}te(r)},f.onerror=()=>{},g=new Promise(n=>{let r=!1,s=()=>{r||(r=!0,n())};f.onopen=s,setTimeout(s,2e3)}),g}function L(){for(let e of a.values())if(y.has(e.state))return;f&&(f.close(),f=null,g=null)}function te(e){if(!e||typeof e.id!="string")return;let t=a.get(e.id);if(!(!t||!y.has(t.state)))switch(e.type){case"wire/ack":e.payload?.mode==="jsonl"&&Number.isFinite(e.payload.budgetMs)&&e.payload.budgetMs>0?(t.structured=!0,v(t,e.payload.budgetMs+K,"the helper did not finish within its execution budget",{cancelFirst:!0,errorCode:"helper_timeout"})):v(t,P,"the agent stopped responding"),Y(t,"acked");break;case"wire/status":t.structured||v(t,P,"the agent stopped responding"),t.text=typeof e.text=="string"?e.text:"",t.state="acked",ne(t,e),m(t,e);break;case"wire/done":t.result=Object.prototype.hasOwnProperty.call(e,"payload")?e.payload:null,t.document==="edit"?ie(t):l(t,"done",null);break;case"wire/error":re(t,e);break;default:break}}function ne(e,t){if(!e.onStatus||typeof t.text!="string")return;let n={text:t.text};t.payload&&typeof t.payload=="object"&&Object.prototype.hasOwnProperty.call(t.payload,"progress")&&(n.progress=t.payload.progress);try{e.onStatus(n)}catch(r){console.error("clay.wire: an onStatus listener threw",r)}}function re(e,t){let n=t.payload,r=n&&typeof n=="object"&&!Array.isArray(n)&&(n.source==="application"||n.source==="host")&&typeof n.code=="string"&&n.code,s=typeof t.text=="string"&&t.text?t.text:"the handler reported an error";if(!r){l(e,"error",s);return}let i=n.source==="host"&&n.code==="helper_cancelled"?"cancelled":"error";l(e,i,s,{errorCode:n.code,errorDetails:Object.prototype.hasOwnProperty.call(n,"details")?n.details:null,errorSource:n.source})}function oe(){h||(h=e=>{if(e.detail?.source!=="peer"){for(let t of a.values())if(t.state==="landing"){l(t,"done",null);return}}},document.addEventListener("clay:sync-applied",h))}function se(){D>0||!h||(document.removeEventListener("clay:sync-applied",h),h=null)}function ie(e){R.has(e.state)||e.state==="landing"||(q(e),e.state="landing",D++,oe(),e.landingTimer=setTimeout(()=>{l(e,"done",null)},V),m(e),L())}function l(e,t,n,r={}){if(R.has(e.state))return;let s=e.state==="landing";if(q(e),clearTimeout(e.landingTimer),e.landingTimer=null,e.abort?.abort(),s&&(D--,se()),e.error=n,Object.prototype.hasOwnProperty.call(r,"errorCode")&&(e.errorCode=r.errorCode),Object.prototype.hasOwnProperty.call(r,"errorDetails")&&(e.errorDetails=r.errorDetails),Object.prototype.hasOwnProperty.call(r,"errorSource")&&(e.errorSource=r.errorSource),e.state=t,e.signal&&e.signalHandler&&(e.signal.removeEventListener("abort",e.signalHandler),e.signalHandler=null),ue(e),m(e),L(),Z(),e.settle){let i=e.settle;e.settle=null,i(w(e))}}var C=0,$=null,E=null;function ae(){return E||(E=import("./core/save-JZ7R4ET2.js")),E}async function le(e){if(!b||e.holdsSave)return;let t=await ae();e.state==="sent"&&($=t,e.holdsSave=!0,!(C++>0)&&t.suspendAutosave())}function ue(e){e.holdsSave&&(e.holdsSave=!1,!(--C>0)&&(C=0,$?.resumeAutosave()))}var c=null,de=()=>!c||c.admitted,ce=(e,t,n)=>Object.assign(new Error(`clay.wire: ${e}`),{code:t,pending:n});function O(e){return e.document!=="edit"||e.generation===T().generation&&de()?!0:(l(e,"error","the page changed mode before this request went out",{errorCode:"stale-document",errorSource:"client"}),!1)}function _e(){return{id:"clay:wire",order:900,prepare(e={}){let t={admitted:e.initial===!0};return c=t,{enable(){c===t&&(t.admitted=!0)},quiesce(){if(c!==t)return;t.admitted=!1;let n=[...a.values()].filter(r=>r.document==="edit"&&(r.holdsSave||y.has(r.state))).map(r=>r.id);if(n.length)throw ce("a request on this page has not settled","pending-input",n)},resume(){c===t&&(t.admitted=!0)},dispose(){c===t&&(c=null)}}}}}function fe(e,t){return new Promise(n=>{let r=!1,s=()=>{r||(r=!0,document.removeEventListener(e,s),n())};document.addEventListener(e,s),setTimeout(s,t)})}async function pe(){if(!b)return;let e=window.clay;if(!e||typeof e.save!="function")return;let{isSaveInProgress:t}=await import("./core/save-core-I4N6S4ED.js"),{savesHeld:n,saveHoldReason:r}=await import("./core/save-JZ7R4ET2.js");if(n())throw new Error(r());let s=Date.now()+W;for(let i=0;i<3;i++){t()&&await fe("clay:save-saved",Math.max(0,s-Date.now()));let u=await e.save();if(u?.ok||u?.msgType==="skipped"&&!t())return;if(u?.msgType==="error"||u?.msgType==="unknown")throw new Error(`could not save this page first: ${u.msg||u.msgType}`);if(Date.now()>=s)break}throw new Error("could not save this page before sending")}async function F(e,t){let n={"Content-Type":"application/json","Page-URL":window.location.href},r=N();r&&(n["Save-Token"]=r);let s=await fetch(H("/_/wire/send"),{method:"POST",headers:n,body:JSON.stringify(e),signal:t}),i=null;try{i=await s.json()}catch{i=null}return{ok:s.ok,status:s.status,reply:i}}function he(e,t={}){let n=typeof t.id=="string"&&t.id?t.id:Q(),r=typeof t.type=="string"&&t.type?t.type:"wire/request",s=Object.prototype.hasOwnProperty.call(t,"helper"),i=s&&typeof t.helper=="string"&&t.helper?t.helper:null,u=t.document===void 0?i?"none":"edit":t.document;if(s&&!i)return _(n,r,null,"helper must be a nonempty string","invalid_helper");if(u!=="edit"&&u!=="none")return _(n,r,i,'document must be "edit" or "none"',"invalid_document");if(a.has(n))return _(n,r,i,"a request with this id is already on the wire","duplicate_request");let o={id:n,type:r,state:"sent",helper:i,document:u,structured:!1,onStatus:typeof t.onStatus=="function"?t.onStatus:null,text:"",result:null,error:null,errorCode:null,errorDetails:null,errorSource:null,startedAt:Date.now(),timer:null,landingTimer:null,abort:typeof AbortController=="function"?new AbortController:null,holdsSave:!1,generation:T().generation,settle:null,signal:t.signal&&typeof t.signal.addEventListener=="function"?t.signal:null,signalHandler:null};return o.done=new Promise(d=>{o.settle=d}),a.set(n,o),m(o),o.signal&&(o.signalHandler=()=>x(n),o.signal.addEventListener("abort",o.signalHandler,{once:!0}),o.signal.aborted&&o.signalHandler()),(async()=>{if(o.state!=="sent")return;if(o.helper){let X=await I(j);if(o.state!=="sent")return;if(!X){l(o,"error","this host does not support named wire helpers",{errorCode:"helper_protocol_unsupported",errorSource:"client"});return}}if(!O(o)||o.document==="edit"&&(await le(o),o.state!=="sent"||!O(o)||(await pe(),o.state!=="sent")||!O(o)))return;if(await ee(),o.state!=="sent"){L();return}v(o,B,"the agent never answered",o.helper?{cancelFirst:!0,errorCode:"ack_timeout"}:void 0);let d={type:o.type,id:o.id,text:t.text,payload:e};o.helper&&(d.helper=o.helper),(o.helper||t.document!==void 0)&&(d.document=o.document);let{ok:G,status:J,reply:S}=await F(d,o.abort?.signal);if(o.state!=="sent")return;if(!G){l(o,"error",`the wire refused this request (${J})`);return}let p=S&&S.refused;if(p&&typeof p.code=="string"&&p.code){l(o,"error",p.message||"the handler refused this request",{errorCode:p.code,errorSource:p.source==="application"?"application":"host",errorDetails:null});return}(!S||S.delivered===0)&&l(o,"error",o.helper?`The local program "${o.helper}" is not connected to this file.`:"No program is connected to this file.")})().catch(d=>{l(o,"error",d&&d.message?d.message:String(d))}),{id:n,get state(){return o.state},done:o.done,cancel:()=>x(n)}}function _(e,t,n,r,s){let i={id:e,type:t,state:"error",helper:n,text:"",result:null,error:r,errorCode:s,errorDetails:null,errorSource:"client",startedAt:Date.now()};return{id:e,get state(){return i.state},done:Promise.resolve(w(i)),cancel:()=>!1}}function x(e){let t=a.get(e);return!t||!y.has(t.state)?!1:(z(t),l(t,"cancelled",null),!0)}function z(e){F({type:"wire/cancel",id:e.id}).catch(()=>{})}function ye(e){let t=a.get(e);return t?w(t):void 0}function ge(){return[...a.values()].map(w)}function we(){for(let e of a.values())if(y.has(e.state))return!0;return!1}function me(e){return typeof e!="function"?()=>{}:(k.add(e),()=>k.delete(e))}async function Se(){let e=await A({fresh:!0});if(!e.extensions.includes(j))return[];let t=e.document?.helpers;return Array.isArray(t)?t.filter(n=>n&&typeof n.name=="string"&&["ready","denied","unavailable"].includes(n.state)).map(({name:n,state:r})=>({name:n,state:r})):[]}var ve={send:he,cancel:x,get:ye,list:ge,isBusy:we,on:me,helpers:Se},ke=ve;export{_e as a,ve as b,ke as c};
1
+ import{d as A,e as I}from"./c-26W3BMWK.js";import{f as b,j as T}from"./c-JEWSJHMK.js";import{c as M}from"./c-BPF2NSPV.js";var B=15e3,P=12e4,K=15e3,V=4e3,W=5e3,U=50,y=new Set(["sent","acked"]),R=new Set(["done","error","cancelled"]),j="wire",a=new Map,k=new Set,f=null,g=null,D=0,h=null;function Q(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`page-${Date.now()}-${Math.random().toString(16).slice(2)}`}function H(e){return new URL(e,window.location.origin).href}function N(){let e=M();return typeof e=="string"&&e!==""?e:null}function w(e){return{id:e.id,type:e.type,state:e.state,helper:e.helper,text:e.text,result:e.result,error:e.error,errorCode:e.errorCode,errorDetails:e.errorDetails,errorSource:e.errorSource,startedAt:e.startedAt}}function m(e,t){let n=w(e);for(let r of k)try{r(n,t||null)}catch(s){console.error("clay.wire: a listener threw",s)}document.dispatchEvent(new CustomEvent("clay:wire-state",{detail:n}))}function Y(e,t){e.state!==t&&(e.state=t,m(e))}function v(e,t,n,{cancelFirst:r=!1,errorCode:s=null}={}){clearTimeout(e.timer),e.timer=setTimeout(()=>{e.timer=null,r&&z(e),l(e,"error",n,{errorCode:s,errorSource:"client"})},t)}function q(e){clearTimeout(e.timer),e.timer=null}function Z(){if(!(a.size<=U))for(let[e,t]of a){if(a.size<=U)break;!y.has(t.state)&&t.state!=="landing"&&a.delete(e)}}function ee(){if(g)return g;let e=N(),t=`/_/wire/subscribe?page-url=${encodeURIComponent(window.location.href)}`+(e?`&token=${encodeURIComponent(e)}`:"");return f=new EventSource(H(t)),f.onmessage=n=>{let r;try{r=JSON.parse(n.data)}catch{return}te(r)},f.onerror=()=>{},g=new Promise(n=>{let r=!1,s=()=>{r||(r=!0,n())};f.onopen=s,setTimeout(s,2e3)}),g}function L(){for(let e of a.values())if(y.has(e.state))return;f&&(f.close(),f=null,g=null)}function te(e){if(!e||typeof e.id!="string")return;let t=a.get(e.id);if(!(!t||!y.has(t.state)))switch(e.type){case"wire/ack":e.payload?.mode==="jsonl"&&Number.isFinite(e.payload.budgetMs)&&e.payload.budgetMs>0?(t.structured=!0,v(t,e.payload.budgetMs+K,"the helper did not finish within its execution budget",{cancelFirst:!0,errorCode:"helper_timeout"})):v(t,P,"the agent stopped responding"),Y(t,"acked");break;case"wire/status":t.structured||v(t,P,"the agent stopped responding"),t.text=typeof e.text=="string"?e.text:"",t.state="acked",ne(t,e),m(t,e);break;case"wire/done":t.result=Object.prototype.hasOwnProperty.call(e,"payload")?e.payload:null,t.document==="edit"?ie(t):l(t,"done",null);break;case"wire/error":re(t,e);break;default:break}}function ne(e,t){if(!e.onStatus||typeof t.text!="string")return;let n={text:t.text};t.payload&&typeof t.payload=="object"&&Object.prototype.hasOwnProperty.call(t.payload,"progress")&&(n.progress=t.payload.progress);try{e.onStatus(n)}catch(r){console.error("clay.wire: an onStatus listener threw",r)}}function re(e,t){let n=t.payload,r=n&&typeof n=="object"&&!Array.isArray(n)&&(n.source==="application"||n.source==="host")&&typeof n.code=="string"&&n.code,s=typeof t.text=="string"&&t.text?t.text:"the handler reported an error";if(!r){l(e,"error",s);return}let i=n.source==="host"&&n.code==="helper_cancelled"?"cancelled":"error";l(e,i,s,{errorCode:n.code,errorDetails:Object.prototype.hasOwnProperty.call(n,"details")?n.details:null,errorSource:n.source})}function oe(){h||(h=e=>{if(e.detail?.source!=="peer"){for(let t of a.values())if(t.state==="landing"){l(t,"done",null);return}}},document.addEventListener("clay:sync-applied",h))}function se(){D>0||!h||(document.removeEventListener("clay:sync-applied",h),h=null)}function ie(e){R.has(e.state)||e.state==="landing"||(q(e),e.state="landing",D++,oe(),e.landingTimer=setTimeout(()=>{l(e,"done",null)},V),m(e),L())}function l(e,t,n,r={}){if(R.has(e.state))return;let s=e.state==="landing";if(q(e),clearTimeout(e.landingTimer),e.landingTimer=null,e.abort?.abort(),s&&(D--,se()),e.error=n,Object.prototype.hasOwnProperty.call(r,"errorCode")&&(e.errorCode=r.errorCode),Object.prototype.hasOwnProperty.call(r,"errorDetails")&&(e.errorDetails=r.errorDetails),Object.prototype.hasOwnProperty.call(r,"errorSource")&&(e.errorSource=r.errorSource),e.state=t,e.signal&&e.signalHandler&&(e.signal.removeEventListener("abort",e.signalHandler),e.signalHandler=null),ue(e),m(e),L(),Z(),e.settle){let i=e.settle;e.settle=null,i(w(e))}}var C=0,$=null,E=null;function ae(){return E||(E=import("./core/save-KY3ZMPU4.js")),E}async function le(e){if(!b||e.holdsSave)return;let t=await ae();e.state==="sent"&&($=t,e.holdsSave=!0,!(C++>0)&&t.suspendAutosave())}function ue(e){e.holdsSave&&(e.holdsSave=!1,!(--C>0)&&(C=0,$?.resumeAutosave()))}var c=null,de=()=>!c||c.admitted,ce=(e,t,n)=>Object.assign(new Error(`clay.wire: ${e}`),{code:t,pending:n});function O(e){return e.document!=="edit"||e.generation===T().generation&&de()?!0:(l(e,"error","the page changed mode before this request went out",{errorCode:"stale-document",errorSource:"client"}),!1)}function _e(){return{id:"clay:wire",order:900,prepare(e={}){let t={admitted:e.initial===!0};return c=t,{enable(){c===t&&(t.admitted=!0)},quiesce(){if(c!==t)return;t.admitted=!1;let n=[...a.values()].filter(r=>r.document==="edit"&&(r.holdsSave||y.has(r.state))).map(r=>r.id);if(n.length)throw ce("a request on this page has not settled","pending-input",n)},resume(){c===t&&(t.admitted=!0)},dispose(){c===t&&(c=null)}}}}}function fe(e,t){return new Promise(n=>{let r=!1,s=()=>{r||(r=!0,document.removeEventListener(e,s),n())};document.addEventListener(e,s),setTimeout(s,t)})}async function pe(){if(!b)return;let e=window.clay;if(!e||typeof e.save!="function")return;let{isSaveInProgress:t}=await import("./core/save-core-LBW6DNJ6.js"),{savesHeld:n,saveHoldReason:r}=await import("./core/save-KY3ZMPU4.js");if(n())throw new Error(r());let s=Date.now()+W;for(let i=0;i<3;i++){t()&&await fe("clay:save-saved",Math.max(0,s-Date.now()));let u=await e.save();if(u?.ok||u?.msgType==="skipped"&&!t())return;if(u?.msgType==="error"||u?.msgType==="unknown")throw new Error(`could not save this page first: ${u.msg||u.msgType}`);if(Date.now()>=s)break}throw new Error("could not save this page before sending")}async function F(e,t){let n={"Content-Type":"application/json","Page-URL":window.location.href},r=N();r&&(n["Save-Token"]=r);let s=await fetch(H("/_/wire/send"),{method:"POST",headers:n,body:JSON.stringify(e),signal:t}),i=null;try{i=await s.json()}catch{i=null}return{ok:s.ok,status:s.status,reply:i}}function he(e,t={}){let n=typeof t.id=="string"&&t.id?t.id:Q(),r=typeof t.type=="string"&&t.type?t.type:"wire/request",s=Object.prototype.hasOwnProperty.call(t,"helper"),i=s&&typeof t.helper=="string"&&t.helper?t.helper:null,u=t.document===void 0?i?"none":"edit":t.document;if(s&&!i)return _(n,r,null,"helper must be a nonempty string","invalid_helper");if(u!=="edit"&&u!=="none")return _(n,r,i,'document must be "edit" or "none"',"invalid_document");if(a.has(n))return _(n,r,i,"a request with this id is already on the wire","duplicate_request");let o={id:n,type:r,state:"sent",helper:i,document:u,structured:!1,onStatus:typeof t.onStatus=="function"?t.onStatus:null,text:"",result:null,error:null,errorCode:null,errorDetails:null,errorSource:null,startedAt:Date.now(),timer:null,landingTimer:null,abort:typeof AbortController=="function"?new AbortController:null,holdsSave:!1,generation:T().generation,settle:null,signal:t.signal&&typeof t.signal.addEventListener=="function"?t.signal:null,signalHandler:null};return o.done=new Promise(d=>{o.settle=d}),a.set(n,o),m(o),o.signal&&(o.signalHandler=()=>x(n),o.signal.addEventListener("abort",o.signalHandler,{once:!0}),o.signal.aborted&&o.signalHandler()),(async()=>{if(o.state!=="sent")return;if(o.helper){let X=await I(j);if(o.state!=="sent")return;if(!X){l(o,"error","this host does not support named wire helpers",{errorCode:"helper_protocol_unsupported",errorSource:"client"});return}}if(!O(o)||o.document==="edit"&&(await le(o),o.state!=="sent"||!O(o)||(await pe(),o.state!=="sent")||!O(o)))return;if(await ee(),o.state!=="sent"){L();return}v(o,B,"the agent never answered",o.helper?{cancelFirst:!0,errorCode:"ack_timeout"}:void 0);let d={type:o.type,id:o.id,text:t.text,payload:e};o.helper&&(d.helper=o.helper),(o.helper||t.document!==void 0)&&(d.document=o.document);let{ok:G,status:J,reply:S}=await F(d,o.abort?.signal);if(o.state!=="sent")return;if(!G){l(o,"error",`the wire refused this request (${J})`);return}let p=S&&S.refused;if(p&&typeof p.code=="string"&&p.code){l(o,"error",p.message||"the handler refused this request",{errorCode:p.code,errorSource:p.source==="application"?"application":"host",errorDetails:null});return}(!S||S.delivered===0)&&l(o,"error",o.helper?`The local program "${o.helper}" is not connected to this file.`:"No program is connected to this file.")})().catch(d=>{l(o,"error",d&&d.message?d.message:String(d))}),{id:n,get state(){return o.state},done:o.done,cancel:()=>x(n)}}function _(e,t,n,r,s){let i={id:e,type:t,state:"error",helper:n,text:"",result:null,error:r,errorCode:s,errorDetails:null,errorSource:"client",startedAt:Date.now()};return{id:e,get state(){return i.state},done:Promise.resolve(w(i)),cancel:()=>!1}}function x(e){let t=a.get(e);return!t||!y.has(t.state)?!1:(z(t),l(t,"cancelled",null),!0)}function z(e){F({type:"wire/cancel",id:e.id}).catch(()=>{})}function ye(e){let t=a.get(e);return t?w(t):void 0}function ge(){return[...a.values()].map(w)}function we(){for(let e of a.values())if(y.has(e.state))return!0;return!1}function me(e){return typeof e!="function"?()=>{}:(k.add(e),()=>k.delete(e))}async function Se(){let e=await A({fresh:!0});if(!e.extensions.includes(j))return[];let t=e.document?.helpers;return Array.isArray(t)?t.filter(n=>n&&typeof n.name=="string"&&["ready","denied","unavailable"].includes(n.state)).map(({name:n,state:r})=>({name:n,state:r})):[]}var ve={send:he,cancel:x,get:ye,list:ge,isBusy:we,on:me,helpers:Se},ke=ve;export{_e as a,ve as b,ke as c};
@@ -1 +1 @@
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
+ import{a,b,c,d,e,f,g,h,i,j,k}from"./c-26W3BMWK.js";import"./c-JEWSJHMK.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,4 +1,4 @@
1
- import{a as Tt,c as Rt,d as Pt,e as $t,f as be,g as Ct}from"./c-JKZJIUIP.js";import{a as ee}from"./c-TCCA5BZN.js";import{a as T,b as Fe,c as Ye,d as Be,e as ke,f as Mt,g as ze,h as Lt,i as G,j as Ae,k as R,l as _t,m as qt,n as Ve,o as ue}from"./c-3LDGIBMN.js";import{d as jt}from"./c-57XDY6HC.js";import{e as Ot}from"./c-LZJPNR2W.js";import{F as Je,K as Ue,g as Et,r as Ie}from"./c-FC5RUFPR.js";import{a as We}from"./c-I2SCCUEW.js";import{f as De,g as He,k as kt,l as At,m as St,y as xt}from"./c-EHAR4RJJ.js";import{a as vt}from"./c-LD6UVV5R.js";import{a as Ne}from"./c-PGSBXHUE.js";import{a as je,c as bt}from"./c-KU3PX7LL.js";import{e as we,k as wt}from"./c-EQ5NBOGA.js";import{b as mt,f as Z}from"./c-C7SUMNMI.js";import{f as gt,k as yt}from"./c-UW6MMZ4V.js";var gn=new Set(["push","pop","shift","unshift","splice","sort","reverse","fill","copyWithin"]),yn=/^(0|[1-9]\d*)$/,U=e=>e!==null&&typeof e=="object",te=e=>Array.isArray(e)?"a list":"an object";function J(e,t){let r=e;for(let o of t){if(!U(r))return;Array.isArray(r)?r=r[Number(o)]:r=Object.prototype.hasOwnProperty.call(r,o)?r[o]:void 0}return r}var Se=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),vn=(e,t)=>R(e)===R(t);function Nt(e,t){let r=[];try{for(let o of t){let n=Mt(e,o);n&&(r.push(n),e=n.root)}return r}catch{return Ke(r),null}}function Ke(e){let t;for(let r=e.length-1;r>=0;r--)t=ze(e[r]);return t}function wn(e,t,r){let o=[];for(let n of e){if(n.at===null||Array.isArray(n.at))return null;let s=o.find(a=>a.path.length===n.path.length&&G(a.path,n.path));if(s){if(s.removed&&n.kind!=="remove")return null;n.kind==="remove"&&(s.removed=!0);continue}if(o.some(a=>G(a.path,n.path)))return null;o.push({path:n.path,at:n.at,key:n.key,had:n.kind!=="add",old:n.old,removed:n.kind==="remove"})}for(let n of o){if(n.has=Se(n.at,n.key),n.had&&n.has&&n.removed||(n.into=J(r,n.path.slice(0,-1)),!U(n.into)||Array.isArray(n.into)||Se(n.into,n.key)!==n.had))return null;let s=n.path.slice(0,-1);for(let a of t){let i=a.op.path;if(G(n.path,i)||a.op.op==="del"&&i.length<=n.path.length&&G(i.slice(0,-1),n.path)&&Array.isArray(J(r,i.slice(0,-1))))return null;if(!n.had&&n.has&&i.length>s.length&&G(s,i)){let c=i[s.length];if(i.length===s.length+1&&a.op.op==="del"||!Se(n.at,String(c)))return null}}}return o}function bn(e,t){if(t.op==="set"){let r=J(e,t.path);if(U(r)&&U(t.value)&&Array.isArray(r)===Array.isArray(t.value)){Ae(r,T(t.value));return}}Be(e,t)}function Ge({name:e,value:t,ephemeral:r=!1}){if(!U(t))throw new TypeError(`clay.live("${e}"): the tag must hold a JSON object or list`);let o=T(t),n=null,s=T(t),a=!0,i=[],c=1,d=null,h="file",w=new Set,A=new Set,b=new Set,x=new Set,E=new Set,v=new WeakMap;function O(l,u){let f={source:l,ops:u};for(let g of[...w])try{g(f)}catch(S){console.error(`clay.live("${e}"): a change listener threw`,S)}}function I(){let l=T(o),u=[];for(let f of i)try{Ye(l,f.op),l=Be(l,f.op),u.push(f)}catch{}i=u,Ae(s,l),a=!0}function N(l){for(let u of[...b])try{u(l)}catch(f){console.error(`clay.live("${e}"): a rebase listener threw`,f)}}function se(l,{source:u="remote",confirmed:f=0,through:g,drop:S,dropIds:$,frame:K=null,room:L=null,cause:ce=null}={}){if(!U(l)||te(l)!==te(s))return console.warn(`clay.live("${e}"): ignored an incoming value that is not ${te(s)}`),!1;L&&(n=L);let me=T(s),ge=o;if(o=T(l),S)i=i.filter(_=>_.id<S[0]||_.id>S[1]);else if($){let _=new Set($);i=i.filter(ye=>!_.has(ye.id))}else i=g===void 0?i.slice(f):i.filter(_=>_.id>g);return I(),N({source:u,frame:K,room:L,cause:ce,prev:ge,before:_=>J(ge,_),next:o}),_t(me,s)||O(u,null),!0}function ie(l){let u=T(o);for(let f=l.length-1;f>=0;f--){let g=l[f];ze({...g,at:J(u,g.path.slice(0,-1))})}return u}function ae(l){for(let u of[...A])try{u(l)}catch(f){console.error(`clay.live("${e}"): a transport threw`,f)}O("local",l)}function C(l){let u=l.map(Fe);for(let f of u)if(f.path.length===0&&te(f.value)!==te(s))throw new TypeError(`clay.live("${e}"): the whole value must stay ${te(s)}`);u.length===1?Ye(s,u[0]):ke(T(s),u);for(let f of u)bn(s,f);i.push(...u.map(f=>({id:c++,op:f}))),d?d.push(...u):ae(u)}function B(l,u){let f=v.get(l);f||v.set(l,f=new Map);let g=JSON.stringify(u),S=f.get(g);return S||(S=new Proxy(l,Ce(u)),f.set(g,S)),S}function Ce(l){return{get(u,f){if(Array.isArray(u)&&gn.has(f))return(...S)=>{let $=T(u),K=Array.prototype[f].apply($,S);return C([{op:"set",path:l,value:$}]),K===$?B(u,l):K};let g=u[f];return typeof f=="symbol"||!U(g)||!Object.prototype.hasOwnProperty.call(u,f)?g:B(g,[...l,Array.isArray(u)?Number(f):f])},set(u,f,g){if(typeof f=="symbol")throw new TypeError(`clay.live("${e}"): symbol keys are not JSON`);if(Array.isArray(u)){if(f==="length"){let S=T(u);return S.length=g,C([{op:"set",path:l,value:S}]),!0}if(!yn.test(f))throw new TypeError(`clay.live("${e}"): "${f}" is not a list index`);return C([{op:"set",path:[...l,Number(f)],value:g}]),!0}return C([{op:"set",path:[...l,f],value:g}]),!0},deleteProperty(u,f){if(typeof f=="symbol")return!0;if(Array.isArray(u))throw new TypeError(`clay.live("${e}"): remove a list item with splice`);return C([{op:"del",path:[...l,f]}]),!0},defineProperty(){throw new TypeError(`clay.live("${e}"): assign values instead of defining properties`)},setPrototypeOf(){return!1},preventExtensions(){return!1}}}let le=B(s,[]),Q,Me=new Promise(l=>{Q=l}),y=Object.freeze({name:e,ephemeral:r,ready:Me,get data(){return le},get status(){return{mode:h}},set(l,u){C([{op:"set",path:l,value:u}])},delete(l){C([{op:"del",path:l}])},add(l,u=1){C([{op:"add",path:l,n:u}])},update(l){if(typeof l!="function")throw new TypeError(`clay.live("${e}"): update() takes a function`);if(d)return l(le);d=[];let u=i.length,f=c,g;try{if(g=l(le),g&&typeof g.then=="function")throw new TypeError(`clay.live("${e}"): update() runs synchronously; do async work before calling it`)}catch($){throw d=null,i.length=u,c=f,I(),$}let S=Lt(d);return d=null,i.length=u,c=f,i.push(...S.map($=>({id:c++,op:$}))),S.length&&ae(S),g},on(l,u){if(l!=="change")throw new TypeError(`clay.live("${e}"): the only event is "change"`);if(typeof u!="function")throw new TypeError(`clay.live("${e}"): on() takes a function`);return w.add(u),()=>w.delete(u)},off(l,u){w.delete(u)},toJSON(){return T(s)}});return Q(y),{handle:y,name:e,ephemeral:r,get value(){return s},get authoritative(){return o},get room(){return n},get pending(){return i.map(l=>l.op)},pendingEntries(){return i.map(l=>({id:l.id,op:l.op}))},get mark(){return c-1},setMode(l){h=l,l!=="fast"&&(n=null)},onLocal(l){return A.add(l),()=>A.delete(l)},confirm(l){let u=i.filter(f=>f.id<=l);if(u.length){try{o=ke(T(o),u.map(f=>f.op))}catch{o=T(s),a=!1}i=i.filter(f=>f.id>l);for(let f of[...x])try{f({through:l})}catch(g){console.error(`clay.live("${e}"): a confirmation listener threw`,g)}}},onConfirm(l){return x.add(l),()=>x.delete(l)},rebase:se,checkOps(l){let u;try{u=l.map(Fe)}catch{return null}let f=Nt(o,u);return f?(Ke(f),u):null},rebaseOps(l,{source:u="remote",confirmed:f=0,through:g,frame:S=null,room:$=null,cause:K=null}={}){let L=Nt(o,l);if(!L)return!1;let ce=g===void 0?i.slice(f):i.filter(k=>k.id>g),me=i.length-ce.length,ge=L.some(k=>k.at===null),_=a&&!ge&&me===l.length&&l.every((k,D)=>vn(k,i[D].op)),ye=a&&!_&&me===0?wn(L,ce,s):null;if(!_&&!ye)return Ke(L),se(ke(T(o),l),{source:u,confirmed:f,through:g,frame:S,room:$,cause:K});i=ce;let Le=!1;for(let k of ye??[]){let D=k.into;if(k.has){let ht=k.at[k.key];(!k.had||R(k.old)!==R(ht))&&(Le=!0);let qe=k.had?D[k.key]:void 0,ve=T(ht),mn=U(qe)&&U(ve)&&Array.isArray(qe)===Array.isArray(ve);Object.defineProperty(D,k.key,{value:mn?Ae(qe,ve):ve,enumerable:!0,writable:!0,configurable:!0})}else k.had&&(Le=!0,delete D[k.key])}let dn=null,_e=()=>dn??=ie(L),pn=L.some(k=>Array.isArray(k.at)&&k.kind!=="put"),hn=k=>{if(pn)return J(_e(),k);for(let D of L)if(G(D.path,k))return D.path.length>k.length?J(_e(),k):J(D.old,k.slice(D.path.length));return J(o,k)};return $&&(n=$),N({source:u,frame:S,room:$,cause:K,get prev(){return _e()},before:hn,next:o}),Le&&O(u,null),!0},onRebase(l){return b.add(l),()=>b.delete(l)},onDelivery(l){return E.add(l),()=>E.delete(l)},deliver(l){for(let u of[...E])try{u(l)}catch(f){console.error(`clay.live("${e}"): a delivery listener threw`,f)}}}}function Dt({needsSave:e,blocked:t,save:r,saveNow:o,now:n=()=>Date.now(),setTimer:s=setTimeout,clearTimer:a=clearTimeout}){let i=null,c=null,d=!1,h=!1,w=0;function A(v){let O=v&&!v.ok&&v.msgType==="skipped";return w=v?.ok||O?0:n()+8e3,O?1e3:8e3}function b(v){i=v,c!==null&&a(c),c=s(E,Math.max(0,v-n()))}function x(){c!==null&&a(c),c=null,i=null}async function E(){if(c=null,i=null,!e())return;if(t()){b(n()+1e3);return}d=!0;let v=null;try{v=await r()}catch{v=null}finally{d=!1}let O=A(v);e()&&b(n()+O)}return{changed(){i===null&&!d&&b(n()+8e3)},flush(){d||!e()||t()||(x(),d=!0,h=!0,Promise.resolve().then(o).catch(()=>null).then(v=>{d=!1,h=!1;let O=A(v);e()&&b(n()+O)}))},soon(){if(d)return;let v=Math.max(n(),w);(i===null||v<i)&&b(v)},within(v){if(d)return;let O=Math.max(n()+v,w);(i===null||O<i)&&b(O)},get flushing(){return h},get deadline(){return i}}}var ne=[0,1e4,3e4],kn=6e3,An=2;async function Sn(e){let t=globalThis.crypto&&globalThis.crypto.subtle;if(!t)return null;try{let r=new TextEncoder().encode(String(e)),o=await t.digest("SHA-256",r),n=new Uint8Array(o),s="";for(let a=0;a<n.length;a+=1)s+=n[a].toString(16).padStart(2,"0");return s}catch{return null}}function xn(e){let t=[];for(let r of e||[]){let o=r&&r.saveId;if(typeof o=="string"&&o&&!t.includes(o)&&t.push(o),t.length>=An)break}return t}function En(e,t,r){return!!(e&&typeof e=="object"&&e.saveId===t&&e.requestHash===r&&e.status==="applied")}function Ht({query:e,digest:t=Sn,now:r=()=>Date.now(),setTimer:o=setTimeout,clearTimer:n=clearTimeout}={}){function s({captureId:a,html:i,attempts:c,initialOutcome:d,startedAt:h,onApplied:w,onUnknown:A}){let b=h+45e3,x=xn(c),E=new Set,v=new Set,O=i,I=null,N=!1;function se(y,l){try{typeof y=="function"&&y(l)}catch(u){console.error("clayjs: save-history callback failed:",u)}}function ie(){N=!0,O=null;for(let y of E)n(y);E.clear();for(let y of v)y.abort();v.clear()}function ae(y,l){N||(ie(),se(w,{captureId:a,saveId:y,requestHash:l}))}function C(y){N||(ie(),se(A,{captureId:a,reason:y}))}function B(y,l){let u=null;return u=o(()=>{u!==null&&E.delete(u),y()},Math.max(0,l)),E.add(u),u}function Ce(y){y!==null&&(n(y),E.delete(y))}async function le(y){if(N)return;let l=b-r();if(l<=0)return;let u=new AbortController;v.add(u);let f=B(()=>u.abort(),Math.min(kn,l)),g=null;try{g=await e({saveId:y,requestHash:I,signal:u.signal})}catch{g=null}finally{Ce(f),v.delete(u)}N||En(g,y,I)&&ae(y,I)}function Q(){if(!N&&!(r()>=b))for(let y of x)le(y)}async function Me(){let y=null;try{y=await t(O)}catch{y=null}if(O=null,N)return;if(typeof y!="string"||!y){C("unavailable");return}if(I=y,d&&typeof d=="object"&&d.status==="applied"&&d.requestHash===I&&x.includes(d.saveId)){ae(d.saveId,I);return}let l=r()-h;if(l>=45e3){C("expired");return}let u=-1;for(let f=0;f<ne.length;f+=1)ne[f]<=l&&(u=f);if(u<0){for(let f=0;f<ne.length;f+=1)B(Q,h+ne[f]-r());return}Q();for(let f=u+1;f<ne.length;f+=1)B(Q,h+ne[f]-r())}return B(()=>C("expired"),b-r()),Me(),{cancel(){ie()}}}return{start:s}}var On="/_/sync/data";function It(){return new URL(On,window.location.origin)}async function Tn(e,t){let r=It();r.searchParams.set("client-id",e);try{let o=await fetch(r.href,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","Document-URL":window.location.href,[Ne]:String(1)},body:JSON.stringify(t)}),n=null;try{n=await o.json()}catch{}let s=Number(o.headers?.get?.("Retry-After"))||0;return{status:o.status,body:n,retryAfter:s}}catch{return{status:0,body:null,retryAfter:0}}}async function Rn(e,t=null,{signal:r}={}){let o=It();e&&o.searchParams.set("client-id",e),t&&typeof t.epoch=="string"&&Number.isInteger(t.seq)&&o.searchParams.set("since",`${t.epoch}:${t.seq}`),o.searchParams.set("compaction","1");try{let n=await fetch(o.href,{credentials:"same-origin",cache:"no-store",headers:{"Document-URL":window.location.href,[Ne]:String(1)},signal:r});if(!n.ok){let a=null;try{a=await n.json()}catch{}return{status:n.status,code:a?.code??null,retryAfter:Number(n.headers?.get?.("Retry-After"))||0}}let s=await n.json();return s&&typeof s.epoch=="string"&&s.conn===null?null:s}catch{return null}}function Jt(){return{start(e){return Ot({open(t){t.lane==="live"&&e.open(t)},close:()=>e.close(),event(t,r){t==="data"?e.frame(r):t==="data-state"?e.state(r):t==="data-writer"&&e.writer(r)}})},send:Tn,fetchState:Rn}}var $n=()=>Promise.all([import("./c-IXO7EI2Q.js"),import("./c-BCS3AZQZ.js")]).then(([e,t])=>({createFastLane:e.createFastLane,localTransport:t.localTransport,localLaneSupported:t.localLaneSupported})),Cn=/^[A-Za-z0-9_.:-]{1,64}$/,m=new Map,Gt="save_"+[...crypto.getRandomValues(new Uint32Array(4))].map(e=>e.toString(16).padStart(8,"0")).join(""),Qe=0,Mn=0,Ln=45e3;function rt(e){let t=ue(e.getAttribute("live-at"));if(!t||t.hash!==Zn(e.textContent))return null;let r=e.getAttribute("live-by"),o=r===null?null:be(r);return r!==null&&!o?null:o&&o.v!==2?{disk:!0}:{epoch:t.epoch,seq:t.seq,frames:Pt(o),ancestors:$t(o)}}function _n(e,t){let r=e.leftAt;if(!r||r.disk)return null;let o=p?.pendingFrames(e.store.name,r,{reserve:t})??{frames:[],complete:!0};if(!o.complete)return null;let n=Tt(r.frames??[],o.frames),s=r.ancestors??[],a=R(e.store.value),i=JSON.stringify([r.epoch,r.seq,n,s,e.store.mark,a]);if(e.capture?.key===i)return e.capture.value;let c={v:2,frames:n,ancestors:s,capture:[Gt,Qe+1]},d=Ct(c),h=d?{at:Ve(r.epoch,r.seq,a),by:d}:null;return e.capture={key:i,value:h},h}var V=new Map,F=null,q=null,H=null,qn=Ht({query:e=>wt?.(e)??null}),j=new Map;function Xt(e){if(!e.captureOps.size)return;let t=new Set(e.store.pendingEntries().map(r=>r.id));for(let[r,o]of e.captureOps)o.ids=o.ids.filter(n=>t.has(n)),o.ids.length||e.captureOps.delete(r);[...e.captureOps.values()].some(r=>r.ended)||pe(e)}var Qt=(e,t)=>F===null||!He()?!1:V.get(F)?.get(e)?.key===t;function fe(e){let t=m.get(e);if(!t||!t.captureOps.size)return[];let r=new Set(t.store.pendingEntries().map(n=>n.id)),o=new Set;for(let[n,s]of t.captureOps)if(!(!s.ended&&!Qt(e,n)))for(let a of s.ids)r.has(a)&&o.add(a);return[...o]}function ot(e){for(let[t,r]of e.captureOps)if(r.ended)return[t,r];return null}We({id:"live:held",isPending:()=>[...m.values()].some(e=>ot(e))});var Ut=e=>[...e.captureOps].some(([t,r])=>!r.ended&&Qt(e.store.name,t));function jn({op:e,path:t,n:r,value:o}){let n=t.length?t.join("."):"the whole value",s=e==="add"?`${n} + ${r}`:e==="del"?`${n} removed`:`${n} = ${JSON.stringify(o)}`;return s.length>60?`${s.slice(0,57)}...`:s}function st(e){clearTimeout(e.timer),e.timer=setTimeout(()=>{e.timer=null,re(e)},Ln)}function pe(e){clearTimeout(e.timer),e.timer=null}function re(e,{read:t=!0}={}){let r=e.store.name,o=fe(r);if(pe(e),e.withheld=!1,e.reading=!1,tn(e),o.length){let n=e.store.pendingEntries().filter(c=>o.includes(c.id)).map(c=>c.op);e.store.handle.status.mode==="file"&&(e.leftAt=null),e.store.rebase(e.store.authoritative,{source:"state",dropIds:o});let s=n.slice(0,5).map(jn).join("; "),a=n.length>5?` and ${n.length-5} more`:"",i=`A save of "${r}" ended without an answer, so ${n.length===1?"this edit was":"these edits were"} not sent again: ${s}${a}. Check the value, and redo ${n.length===1?"it":"any"} if missing.`;console.warn(`clay.live("${r}"): ${i}`,n),document.dispatchEvent(new CustomEvent("clay:live-notice",{detail:{name:r,code:"save-uncertain",ops:n,message:i}}))}t&&p?.release(r,{read:p.roomBound(r)})}function de(e){Xt(e);let t=e.store.name;if(e.recovery&&!Dn(e)&&tn(e),!(!e.withheld||e.reading||fe(t).length)){if(!p?.roomBound(t)){e.withheld=!1,pe(e);return}e.reading=!0,st(e),p.release(t,{read:!0})}}function Nn(e){let t=m.get(e);t&&(it(t),!(!t.withheld&&!t.reading)&&(t.withheld=!1,t.reading=!1,[...t.captureOps.values()].some(r=>r.ended)||pe(t)))}function Zt(){for(let e of m.values())if(e.recovery||e.historicalRefreshPending)return!0;return!1}function Dn(e){let t=new Set(e.store.pendingEntries().map(o=>o.id));return e.recovery.targets.find(({name:o})=>o===e.store.name)?.ids.some(o=>t.has(o))??!1}function Hn(e){if(!H||H.captureId!==e||typeof H.html!="string")return null;let t=[];for(let[r,o]of H.qualified)!m.get(r)||!o.length||t.push({name:r,ids:[...o],saved:H.saved.get(r)});return t.length?{captureId:e,html:H.html,targets:t}:null}function Ee(){H&&(H.html=null)}function Wn(e,t){en(e);let r=e.store.name;e.refreshTimer=setTimeout(()=>{if(e.refreshTimer=null,!e.historicalRefreshPending)return;let o=`The save of "${r}" that ended without an answer did happen, but the value the file holds now must load before newer edits can be saved.`;console.warn(`clay.live("${r}"): ${o}`),document.dispatchEvent(new CustomEvent("clay:live-notice",{detail:{name:r,code:"save-history-refresh-required",message:o}}))},Math.max(0,t-Date.now()))}function it(e){e.historicalRefreshPending&&(e.historicalRefreshPending=!1,en(e))}function en(e){e.refreshTimer!==null&&(clearTimeout(e.refreshTimer),e.refreshTimer=null)}function tn(e){let t=e.recovery;t&&(e.recovery=null,!t.targets.some(r=>m.get(r.name)?.recovery===t)&&(j.delete(t.captureId),t.run?.cancel()))}function nn(e){if(e==null)return;let t=j.get(e);if(t){j.delete(e);for(let r of t.targets){let o=m.get(r.name);o&&o.recovery===t&&(o.recovery=null)}t.run?.cancel()}}function In(e,{result:t,attempts:r,startedAt:o}){let{captureId:n,html:s}=e,a={captureId:n,deadline:o+45e3,targets:e.targets,run:null};j.set(n,a);for(let i of e.targets){let c=m.get(i.name);pe(c),c.recovery=a}we("save-history").then(i=>{if(j.get(n)===a){if(e.html=null,!i)return Ft(n);a.run=qn.start({captureId:n,html:s,attempts:r,initialOutcome:t?.saveOutcome??null,startedAt:o,onApplied:({saveId:c,requestHash:d})=>Jn(n,c,d),onUnknown:({reason:c})=>Un(n,c)})}},()=>{e.html=null,Ft(n)})}function Jn(e,t,r){let o=j.get(e);if(o){j.delete(e);for(let n of o.targets){let s=m.get(n.name);if(!s||s.recovery!==o)continue;s.recovery=null,s.historicalRefreshPending=!0;let a=new Set(s.store.pendingEntries().map(c=>c.id)),i=n.ids.filter(c=>a.has(c));if(s.store.rebase(JSON.parse(n.saved),{source:"state",dropIds:i}),!p){it(s);continue}p.release(s.store.name,{read:!0}),Wn(s,o.deadline)}}}function Ft(e){let t=j.get(e);if(t){j.delete(e);for(let r of t.targets){let o=m.get(r.name);if(!(!o||o.recovery!==t)){if(o.recovery=null,!p?.roomBound(o.store.name)){re(o,{read:!1});continue}o.withheld=!0,o.reading=!0,st(o),p.release(o.store.name,{read:!0})}}}}function Un(e,t){let r=j.get(e);if(r){j.delete(e);for(let o of r.targets){let n=m.get(o.name);!n||n.recovery!==r||(n.recovery=null,re(n))}}}function Fn(e,t,r){let o=e.captureOps.get(t),n=e.store.name;if(!o){e.store.handle.status.mode==="file"&&(e.leftAt=null);return}if(o.ended=!0,r?.has(n)){e.withheld=!0,e.reading=!0;return}if(!p?.roomBound(n)){re(e,{read:!1});return}e.withheld=!0,e.reading=!0,st(e),p.release(n,{read:!0})}function Ze(e){if(Array.isArray(e))return e.map(Ze);if(e===null||typeof e!="object")return e;let t={};for(let r of Object.keys(e).sort())t[r]=Ze(e[r]);return t}function at(e){try{return JSON.stringify(Ze(ee(e)))}catch{return null}}var P=null,he=()=>!P||P.admitted;function Yn(){if(!Z||!he())return!1;for(let e of m.values())if(!e.store.ephemeral){if(e.store.handle.status.mode==="fast"){if(p?.isWriter()&&e.landed<e.last)return!0}else if(e.store.pending.length>0)return!0}return!1}var et=new Set;function rn(){for(let e of[...et])e()}var M=Dt({needsSave:Yn,blocked:()=>!he()||!Ue()||Ie()||Et()||Zt(),save:()=>Je().finally(rn),saveNow:()=>De(!0,()=>Je())}),p=null,tt=!1,xe=0,Oe=null,lt=!1,W=null,ct=!1;function Re(){return[...m.values()].filter(e=>!e.store.ephemeral)}function on(){if(!P||P.admitted||!p||p.status.stopped)return!1;for(let e of Re())if(e.store.handle.status.mode==="fast"&&e.store.pending.length>0)return!0;return!1}async function sn({timeoutMs:e=5e3}={}){let t=Date.now()+e,r=()=>{for(let o of Re())o.store.handle.status.mode==="fast"&&o.store.pending.length>0&&p?.release(o.store.name)};for(r();on();){if(Date.now()>=t)return{ok:!1,code:"timeout"};await new Promise(o=>setTimeout(o,5)),r()}return{ok:!0}}We({id:"live:writer",isPending:on,flush:sn});function Bn(){for(let e of m.values()){e.framesSince=!1;let t=e.store.pendingEntries().map(r=>r.id);t.length&&e.store.rebase(e.store.authoritative,{source:"state",dropIds:t})}}function zn(){let e=p;p=null,tt=!1,xe++,Oe=null,W=null,lt=!1,Te=null,ut=null,X=null,z=null,e?.stop()}function $r(){return{id:"clay:live",order:200,prepare(e={}){if(e.initial===!0)return P||(P={admitted:!0}),Bt(P,{adopted:!0});an();let t={admitted:!1,wantsLane:!0};return P=t,Bn(),Pe(),Bt(t)}}}function Yt(){for(let e of Re())e.store.pending.length>0&&p?.release(e.store.name)}function Bt(e,{adopted:t=!1}={}){return{enable(){t||P!==e||(e.admitted=!0,Pe(),Yt())},quiesce(){if(P===e)return e.admitted=!1,sn()},resume(){P===e&&(e.admitted=!0,Yt())},dispose(){P===e&&(P=null,zn())}}}var Te=null,ut=null,X=null,z=null;function an(){Te=new Promise(e=>{X=e}),ut=new Promise(e=>{z=e})}function ft(){return Te||an(),{laneReady:Te,writerReady:ut}}function Cr(){return ft().laneReady}function Mr(){return ft().writerReady}function zt(){for(let e of m.values())if(!e.store.ephemeral&&e.store.handle.status.mode==="fast"&&e.landed===-1){M.soon();return}M.changed()}function Xe(e,t){e.store.rebase(e.store.authoritative,{source:"state",through:t})}function dt(e,t,r=null){if(e)for(let[o,n]of e){let s=m.get(o);!s||n.mode!=="file"||(t||n.maybeLanded?Fn(s,n.key,r):(s.captureOps.delete(n.key),de(s)),s.store.handle.status.mode==="fast"&&p?.release(o))}}function oe(e){let t=V.get(e);return V.delete(e),F===e&&(F=null),q===e&&(q=null),t}function ln(e,t=null){let r=t??F??q;r!==null&&dt(oe(r),e)}function Vn(e,t){if(e?.code==="draft-storage"||e?.code==="draft-not-ready")return!1;let r=e?.code,o=r==="blockeditor-converting"||r==="blockeditor-capacity";return r==="save-already-applied"||e?.hadTimeout===!0||t!==!1&&!o&&!(e?.status>=400&&e?.status<500)}function Vt(e){return{transport:e,entries:m,onWriter:()=>{M.changed(),p&&p.status.writer!==null&&z?.(p)},onApplied:zt,onLanded:()=>{zt(),rn()},onCheckpoint:()=>M.soon(),onLeave:(t,r)=>{let o=m.get(t);o?.store.handle.status.mode==="fast"&&(o.leftAt={...r,frames:[],ancestors:[]})},held:t=>fe(t).length>0,heldIds:fe,hold:t=>{let r=m.get(t);return r?r.recovery?!0:Ut(r)?(r.withheld=!0,!0):(re(r,{read:!1}),!1):!1},taken:Nn,onStop:()=>{for(let t of m.values())it(t),!t.recovery&&(Ut(t)||re(t,{read:!1}))}}}function Kn(){let e=new Map;for(let[t,r]of Y(document,{warn:!1})){let o=m.get(t);if(o){e.set(t,{value:o.store.authoritative,ephemeral:o.store.ephemeral});continue}try{let n=ee(r.element.textContent);n!==null&&typeof n=="object"&&e.set(t,{value:n,ephemeral:r.ephemeral})}catch{}}for(let[t,r]of m)r.staged||e.set(t,{value:r.store.authoritative,ephemeral:r.store.ephemeral});return e}function Pe(){if(ft(),tt||!(P?P.admitted||P.wantsLane:Z))return;if(tt=!0,mt){X?.(null),z?.(null);return}let e=++xe;we("live-data").then(async t=>{let r=t&&await we("live-provenance");if(e!==xe)return;Oe=t,lt=r;let o=await $n().catch(()=>null);if(e===xe){if(!o){X?.(null),z?.(null);return}if(t)p=o.createFastLane(Vt(Jt()));else if(o.localLaneSupported())W=o.localTransport({seed:Kn,rooms:!0,floor:document.querySelector('meta[name="clay-blockeditor-format"]')?.getAttribute("content")}),p=o.createFastLane(Vt(W));else{X?.(null),z?.(null);return}for(let n of Y(document,{warn:!1}).keys())if(!m.has(n))try{un(n)}catch{}for(let[n,s]of m)s.historicalRefreshPending&&p.release(n,{read:!0});p.start(),X?.(p),p.status.writer!==null&&z?.(p)}}).catch(()=>{X?.(null),z?.(null)})}function Gn(e){let t=(e||"").split(";")[0].trim().toLowerCase();return t==="application/json"||t.endsWith("+json")}function Y(e=document,{warn:t=!0}={}){let r=new Map,o=new Set;for(let n of e.querySelectorAll('script[merge][clay~="live"]')){if(n.hasAttribute("src")||!Gn(n.getAttribute("type")))continue;let s=n.getAttribute("merge");if(Cn.test(s)){if(r.has(s)){o.add(s);continue}r.set(s,{name:s,ephemeral:n.getAttribute("clay").split(/\s+/).includes("ephemeral"),element:n})}}for(let n of o)t&&console.warn(`clay.live: more than one live tag is named "${n}", so none of them is live`),r.delete(n);return r}function $e(e){return new DOMParser().parseFromString(e,"text/html")}function Xn(e){let t=e.store.handle.status.mode==="fast",r=t?e.store.authoritative:e.store.value,o=t&&/^blockeditor(\.[0-9]+)?$/.test(e.store.name)?jt(r):r;return e.layout==="lines"?Qn(o):e.layout==="pretty"?JSON.stringify(o,null,2).replace(/</g,"\\u003c"):R(o)}var Kt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Qn(e){return Kt(e)?`{${Object.entries(e).map(([r,o])=>!Kt(o)||!Object.keys(o).length?`${R(r)}:${R(o)}`:`${R(r)}:{
1
+ import{a as Tt,c as Rt,d as Pt,e as $t,f as be,g as Ct}from"./c-JKZJIUIP.js";import{a as ee}from"./c-TCCA5BZN.js";import{a as T,b as Fe,c as Ye,d as Be,e as ke,f as Mt,g as ze,h as Lt,i as G,j as Ae,k as R,l as _t,m as qt,n as Ve,o as ue}from"./c-3LDGIBMN.js";import{d as jt}from"./c-57XDY6HC.js";import{e as Ot}from"./c-LZJPNR2W.js";import{F as Je,K as Ue,g as Et,r as Ie}from"./c-IOJOJTPL.js";import{a as We}from"./c-I2SCCUEW.js";import{f as De,g as He,k as kt,l as At,m as St,y as xt}from"./c-CKG4NF7J.js";import{a as vt}from"./c-LD6UVV5R.js";import{a as Ne}from"./c-PGSBXHUE.js";import{a as je,c as bt}from"./c-OSGTRM4C.js";import{e as we,k as wt}from"./c-26W3BMWK.js";import{b as mt,f as Z}from"./c-JEWSJHMK.js";import{f as gt,k as yt}from"./c-UW6MMZ4V.js";var gn=new Set(["push","pop","shift","unshift","splice","sort","reverse","fill","copyWithin"]),yn=/^(0|[1-9]\d*)$/,U=e=>e!==null&&typeof e=="object",te=e=>Array.isArray(e)?"a list":"an object";function J(e,t){let r=e;for(let o of t){if(!U(r))return;Array.isArray(r)?r=r[Number(o)]:r=Object.prototype.hasOwnProperty.call(r,o)?r[o]:void 0}return r}var Se=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),vn=(e,t)=>R(e)===R(t);function Nt(e,t){let r=[];try{for(let o of t){let n=Mt(e,o);n&&(r.push(n),e=n.root)}return r}catch{return Ke(r),null}}function Ke(e){let t;for(let r=e.length-1;r>=0;r--)t=ze(e[r]);return t}function wn(e,t,r){let o=[];for(let n of e){if(n.at===null||Array.isArray(n.at))return null;let s=o.find(a=>a.path.length===n.path.length&&G(a.path,n.path));if(s){if(s.removed&&n.kind!=="remove")return null;n.kind==="remove"&&(s.removed=!0);continue}if(o.some(a=>G(a.path,n.path)))return null;o.push({path:n.path,at:n.at,key:n.key,had:n.kind!=="add",old:n.old,removed:n.kind==="remove"})}for(let n of o){if(n.has=Se(n.at,n.key),n.had&&n.has&&n.removed||(n.into=J(r,n.path.slice(0,-1)),!U(n.into)||Array.isArray(n.into)||Se(n.into,n.key)!==n.had))return null;let s=n.path.slice(0,-1);for(let a of t){let i=a.op.path;if(G(n.path,i)||a.op.op==="del"&&i.length<=n.path.length&&G(i.slice(0,-1),n.path)&&Array.isArray(J(r,i.slice(0,-1))))return null;if(!n.had&&n.has&&i.length>s.length&&G(s,i)){let c=i[s.length];if(i.length===s.length+1&&a.op.op==="del"||!Se(n.at,String(c)))return null}}}return o}function bn(e,t){if(t.op==="set"){let r=J(e,t.path);if(U(r)&&U(t.value)&&Array.isArray(r)===Array.isArray(t.value)){Ae(r,T(t.value));return}}Be(e,t)}function Ge({name:e,value:t,ephemeral:r=!1}){if(!U(t))throw new TypeError(`clay.live("${e}"): the tag must hold a JSON object or list`);let o=T(t),n=null,s=T(t),a=!0,i=[],c=1,d=null,h="file",w=new Set,A=new Set,b=new Set,x=new Set,E=new Set,v=new WeakMap;function O(l,u){let f={source:l,ops:u};for(let g of[...w])try{g(f)}catch(S){console.error(`clay.live("${e}"): a change listener threw`,S)}}function I(){let l=T(o),u=[];for(let f of i)try{Ye(l,f.op),l=Be(l,f.op),u.push(f)}catch{}i=u,Ae(s,l),a=!0}function N(l){for(let u of[...b])try{u(l)}catch(f){console.error(`clay.live("${e}"): a rebase listener threw`,f)}}function se(l,{source:u="remote",confirmed:f=0,through:g,drop:S,dropIds:$,frame:K=null,room:L=null,cause:ce=null}={}){if(!U(l)||te(l)!==te(s))return console.warn(`clay.live("${e}"): ignored an incoming value that is not ${te(s)}`),!1;L&&(n=L);let me=T(s),ge=o;if(o=T(l),S)i=i.filter(_=>_.id<S[0]||_.id>S[1]);else if($){let _=new Set($);i=i.filter(ye=>!_.has(ye.id))}else i=g===void 0?i.slice(f):i.filter(_=>_.id>g);return I(),N({source:u,frame:K,room:L,cause:ce,prev:ge,before:_=>J(ge,_),next:o}),_t(me,s)||O(u,null),!0}function ie(l){let u=T(o);for(let f=l.length-1;f>=0;f--){let g=l[f];ze({...g,at:J(u,g.path.slice(0,-1))})}return u}function ae(l){for(let u of[...A])try{u(l)}catch(f){console.error(`clay.live("${e}"): a transport threw`,f)}O("local",l)}function C(l){let u=l.map(Fe);for(let f of u)if(f.path.length===0&&te(f.value)!==te(s))throw new TypeError(`clay.live("${e}"): the whole value must stay ${te(s)}`);u.length===1?Ye(s,u[0]):ke(T(s),u);for(let f of u)bn(s,f);i.push(...u.map(f=>({id:c++,op:f}))),d?d.push(...u):ae(u)}function B(l,u){let f=v.get(l);f||v.set(l,f=new Map);let g=JSON.stringify(u),S=f.get(g);return S||(S=new Proxy(l,Ce(u)),f.set(g,S)),S}function Ce(l){return{get(u,f){if(Array.isArray(u)&&gn.has(f))return(...S)=>{let $=T(u),K=Array.prototype[f].apply($,S);return C([{op:"set",path:l,value:$}]),K===$?B(u,l):K};let g=u[f];return typeof f=="symbol"||!U(g)||!Object.prototype.hasOwnProperty.call(u,f)?g:B(g,[...l,Array.isArray(u)?Number(f):f])},set(u,f,g){if(typeof f=="symbol")throw new TypeError(`clay.live("${e}"): symbol keys are not JSON`);if(Array.isArray(u)){if(f==="length"){let S=T(u);return S.length=g,C([{op:"set",path:l,value:S}]),!0}if(!yn.test(f))throw new TypeError(`clay.live("${e}"): "${f}" is not a list index`);return C([{op:"set",path:[...l,Number(f)],value:g}]),!0}return C([{op:"set",path:[...l,f],value:g}]),!0},deleteProperty(u,f){if(typeof f=="symbol")return!0;if(Array.isArray(u))throw new TypeError(`clay.live("${e}"): remove a list item with splice`);return C([{op:"del",path:[...l,f]}]),!0},defineProperty(){throw new TypeError(`clay.live("${e}"): assign values instead of defining properties`)},setPrototypeOf(){return!1},preventExtensions(){return!1}}}let le=B(s,[]),Q,Me=new Promise(l=>{Q=l}),y=Object.freeze({name:e,ephemeral:r,ready:Me,get data(){return le},get status(){return{mode:h}},set(l,u){C([{op:"set",path:l,value:u}])},delete(l){C([{op:"del",path:l}])},add(l,u=1){C([{op:"add",path:l,n:u}])},update(l){if(typeof l!="function")throw new TypeError(`clay.live("${e}"): update() takes a function`);if(d)return l(le);d=[];let u=i.length,f=c,g;try{if(g=l(le),g&&typeof g.then=="function")throw new TypeError(`clay.live("${e}"): update() runs synchronously; do async work before calling it`)}catch($){throw d=null,i.length=u,c=f,I(),$}let S=Lt(d);return d=null,i.length=u,c=f,i.push(...S.map($=>({id:c++,op:$}))),S.length&&ae(S),g},on(l,u){if(l!=="change")throw new TypeError(`clay.live("${e}"): the only event is "change"`);if(typeof u!="function")throw new TypeError(`clay.live("${e}"): on() takes a function`);return w.add(u),()=>w.delete(u)},off(l,u){w.delete(u)},toJSON(){return T(s)}});return Q(y),{handle:y,name:e,ephemeral:r,get value(){return s},get authoritative(){return o},get room(){return n},get pending(){return i.map(l=>l.op)},pendingEntries(){return i.map(l=>({id:l.id,op:l.op}))},get mark(){return c-1},setMode(l){h=l,l!=="fast"&&(n=null)},onLocal(l){return A.add(l),()=>A.delete(l)},confirm(l){let u=i.filter(f=>f.id<=l);if(u.length){try{o=ke(T(o),u.map(f=>f.op))}catch{o=T(s),a=!1}i=i.filter(f=>f.id>l);for(let f of[...x])try{f({through:l})}catch(g){console.error(`clay.live("${e}"): a confirmation listener threw`,g)}}},onConfirm(l){return x.add(l),()=>x.delete(l)},rebase:se,checkOps(l){let u;try{u=l.map(Fe)}catch{return null}let f=Nt(o,u);return f?(Ke(f),u):null},rebaseOps(l,{source:u="remote",confirmed:f=0,through:g,frame:S=null,room:$=null,cause:K=null}={}){let L=Nt(o,l);if(!L)return!1;let ce=g===void 0?i.slice(f):i.filter(k=>k.id>g),me=i.length-ce.length,ge=L.some(k=>k.at===null),_=a&&!ge&&me===l.length&&l.every((k,D)=>vn(k,i[D].op)),ye=a&&!_&&me===0?wn(L,ce,s):null;if(!_&&!ye)return Ke(L),se(ke(T(o),l),{source:u,confirmed:f,through:g,frame:S,room:$,cause:K});i=ce;let Le=!1;for(let k of ye??[]){let D=k.into;if(k.has){let ht=k.at[k.key];(!k.had||R(k.old)!==R(ht))&&(Le=!0);let qe=k.had?D[k.key]:void 0,ve=T(ht),mn=U(qe)&&U(ve)&&Array.isArray(qe)===Array.isArray(ve);Object.defineProperty(D,k.key,{value:mn?Ae(qe,ve):ve,enumerable:!0,writable:!0,configurable:!0})}else k.had&&(Le=!0,delete D[k.key])}let dn=null,_e=()=>dn??=ie(L),pn=L.some(k=>Array.isArray(k.at)&&k.kind!=="put"),hn=k=>{if(pn)return J(_e(),k);for(let D of L)if(G(D.path,k))return D.path.length>k.length?J(_e(),k):J(D.old,k.slice(D.path.length));return J(o,k)};return $&&(n=$),N({source:u,frame:S,room:$,cause:K,get prev(){return _e()},before:hn,next:o}),Le&&O(u,null),!0},onRebase(l){return b.add(l),()=>b.delete(l)},onDelivery(l){return E.add(l),()=>E.delete(l)},deliver(l){for(let u of[...E])try{u(l)}catch(f){console.error(`clay.live("${e}"): a delivery listener threw`,f)}}}}function Dt({needsSave:e,blocked:t,save:r,saveNow:o,now:n=()=>Date.now(),setTimer:s=setTimeout,clearTimer:a=clearTimeout}){let i=null,c=null,d=!1,h=!1,w=0;function A(v){let O=v&&!v.ok&&v.msgType==="skipped";return w=v?.ok||O?0:n()+8e3,O?1e3:8e3}function b(v){i=v,c!==null&&a(c),c=s(E,Math.max(0,v-n()))}function x(){c!==null&&a(c),c=null,i=null}async function E(){if(c=null,i=null,!e())return;if(t()){b(n()+1e3);return}d=!0;let v=null;try{v=await r()}catch{v=null}finally{d=!1}let O=A(v);e()&&b(n()+O)}return{changed(){i===null&&!d&&b(n()+8e3)},flush(){d||!e()||t()||(x(),d=!0,h=!0,Promise.resolve().then(o).catch(()=>null).then(v=>{d=!1,h=!1;let O=A(v);e()&&b(n()+O)}))},soon(){if(d)return;let v=Math.max(n(),w);(i===null||v<i)&&b(v)},within(v){if(d)return;let O=Math.max(n()+v,w);(i===null||O<i)&&b(O)},get flushing(){return h},get deadline(){return i}}}var ne=[0,1e4,3e4],kn=6e3,An=2;async function Sn(e){let t=globalThis.crypto&&globalThis.crypto.subtle;if(!t)return null;try{let r=new TextEncoder().encode(String(e)),o=await t.digest("SHA-256",r),n=new Uint8Array(o),s="";for(let a=0;a<n.length;a+=1)s+=n[a].toString(16).padStart(2,"0");return s}catch{return null}}function xn(e){let t=[];for(let r of e||[]){let o=r&&r.saveId;if(typeof o=="string"&&o&&!t.includes(o)&&t.push(o),t.length>=An)break}return t}function En(e,t,r){return!!(e&&typeof e=="object"&&e.saveId===t&&e.requestHash===r&&e.status==="applied")}function Ht({query:e,digest:t=Sn,now:r=()=>Date.now(),setTimer:o=setTimeout,clearTimer:n=clearTimeout}={}){function s({captureId:a,html:i,attempts:c,initialOutcome:d,startedAt:h,onApplied:w,onUnknown:A}){let b=h+45e3,x=xn(c),E=new Set,v=new Set,O=i,I=null,N=!1;function se(y,l){try{typeof y=="function"&&y(l)}catch(u){console.error("clayjs: save-history callback failed:",u)}}function ie(){N=!0,O=null;for(let y of E)n(y);E.clear();for(let y of v)y.abort();v.clear()}function ae(y,l){N||(ie(),se(w,{captureId:a,saveId:y,requestHash:l}))}function C(y){N||(ie(),se(A,{captureId:a,reason:y}))}function B(y,l){let u=null;return u=o(()=>{u!==null&&E.delete(u),y()},Math.max(0,l)),E.add(u),u}function Ce(y){y!==null&&(n(y),E.delete(y))}async function le(y){if(N)return;let l=b-r();if(l<=0)return;let u=new AbortController;v.add(u);let f=B(()=>u.abort(),Math.min(kn,l)),g=null;try{g=await e({saveId:y,requestHash:I,signal:u.signal})}catch{g=null}finally{Ce(f),v.delete(u)}N||En(g,y,I)&&ae(y,I)}function Q(){if(!N&&!(r()>=b))for(let y of x)le(y)}async function Me(){let y=null;try{y=await t(O)}catch{y=null}if(O=null,N)return;if(typeof y!="string"||!y){C("unavailable");return}if(I=y,d&&typeof d=="object"&&d.status==="applied"&&d.requestHash===I&&x.includes(d.saveId)){ae(d.saveId,I);return}let l=r()-h;if(l>=45e3){C("expired");return}let u=-1;for(let f=0;f<ne.length;f+=1)ne[f]<=l&&(u=f);if(u<0){for(let f=0;f<ne.length;f+=1)B(Q,h+ne[f]-r());return}Q();for(let f=u+1;f<ne.length;f+=1)B(Q,h+ne[f]-r())}return B(()=>C("expired"),b-r()),Me(),{cancel(){ie()}}}return{start:s}}var On="/_/sync/data";function It(){return new URL(On,window.location.origin)}async function Tn(e,t){let r=It();r.searchParams.set("client-id",e);try{let o=await fetch(r.href,{method:"POST",credentials:"same-origin",headers:{"Content-Type":"application/json","Document-URL":window.location.href,[Ne]:String(1)},body:JSON.stringify(t)}),n=null;try{n=await o.json()}catch{}let s=Number(o.headers?.get?.("Retry-After"))||0;return{status:o.status,body:n,retryAfter:s}}catch{return{status:0,body:null,retryAfter:0}}}async function Rn(e,t=null,{signal:r}={}){let o=It();e&&o.searchParams.set("client-id",e),t&&typeof t.epoch=="string"&&Number.isInteger(t.seq)&&o.searchParams.set("since",`${t.epoch}:${t.seq}`),o.searchParams.set("compaction","1");try{let n=await fetch(o.href,{credentials:"same-origin",cache:"no-store",headers:{"Document-URL":window.location.href,[Ne]:String(1)},signal:r});if(!n.ok){let a=null;try{a=await n.json()}catch{}return{status:n.status,code:a?.code??null,retryAfter:Number(n.headers?.get?.("Retry-After"))||0}}let s=await n.json();return s&&typeof s.epoch=="string"&&s.conn===null?null:s}catch{return null}}function Jt(){return{start(e){return Ot({open(t){t.lane==="live"&&e.open(t)},close:()=>e.close(),event(t,r){t==="data"?e.frame(r):t==="data-state"?e.state(r):t==="data-writer"&&e.writer(r)}})},send:Tn,fetchState:Rn}}var $n=()=>Promise.all([import("./c-IXO7EI2Q.js"),import("./c-BCS3AZQZ.js")]).then(([e,t])=>({createFastLane:e.createFastLane,localTransport:t.localTransport,localLaneSupported:t.localLaneSupported})),Cn=/^[A-Za-z0-9_.:-]{1,64}$/,m=new Map,Gt="save_"+[...crypto.getRandomValues(new Uint32Array(4))].map(e=>e.toString(16).padStart(8,"0")).join(""),Qe=0,Mn=0,Ln=45e3;function rt(e){let t=ue(e.getAttribute("live-at"));if(!t||t.hash!==Zn(e.textContent))return null;let r=e.getAttribute("live-by"),o=r===null?null:be(r);return r!==null&&!o?null:o&&o.v!==2?{disk:!0}:{epoch:t.epoch,seq:t.seq,frames:Pt(o),ancestors:$t(o)}}function _n(e,t){let r=e.leftAt;if(!r||r.disk)return null;let o=p?.pendingFrames(e.store.name,r,{reserve:t})??{frames:[],complete:!0};if(!o.complete)return null;let n=Tt(r.frames??[],o.frames),s=r.ancestors??[],a=R(e.store.value),i=JSON.stringify([r.epoch,r.seq,n,s,e.store.mark,a]);if(e.capture?.key===i)return e.capture.value;let c={v:2,frames:n,ancestors:s,capture:[Gt,Qe+1]},d=Ct(c),h=d?{at:Ve(r.epoch,r.seq,a),by:d}:null;return e.capture={key:i,value:h},h}var V=new Map,F=null,q=null,H=null,qn=Ht({query:e=>wt?.(e)??null}),j=new Map;function Xt(e){if(!e.captureOps.size)return;let t=new Set(e.store.pendingEntries().map(r=>r.id));for(let[r,o]of e.captureOps)o.ids=o.ids.filter(n=>t.has(n)),o.ids.length||e.captureOps.delete(r);[...e.captureOps.values()].some(r=>r.ended)||pe(e)}var Qt=(e,t)=>F===null||!He()?!1:V.get(F)?.get(e)?.key===t;function fe(e){let t=m.get(e);if(!t||!t.captureOps.size)return[];let r=new Set(t.store.pendingEntries().map(n=>n.id)),o=new Set;for(let[n,s]of t.captureOps)if(!(!s.ended&&!Qt(e,n)))for(let a of s.ids)r.has(a)&&o.add(a);return[...o]}function ot(e){for(let[t,r]of e.captureOps)if(r.ended)return[t,r];return null}We({id:"live:held",isPending:()=>[...m.values()].some(e=>ot(e))});var Ut=e=>[...e.captureOps].some(([t,r])=>!r.ended&&Qt(e.store.name,t));function jn({op:e,path:t,n:r,value:o}){let n=t.length?t.join("."):"the whole value",s=e==="add"?`${n} + ${r}`:e==="del"?`${n} removed`:`${n} = ${JSON.stringify(o)}`;return s.length>60?`${s.slice(0,57)}...`:s}function st(e){clearTimeout(e.timer),e.timer=setTimeout(()=>{e.timer=null,re(e)},Ln)}function pe(e){clearTimeout(e.timer),e.timer=null}function re(e,{read:t=!0}={}){let r=e.store.name,o=fe(r);if(pe(e),e.withheld=!1,e.reading=!1,tn(e),o.length){let n=e.store.pendingEntries().filter(c=>o.includes(c.id)).map(c=>c.op);e.store.handle.status.mode==="file"&&(e.leftAt=null),e.store.rebase(e.store.authoritative,{source:"state",dropIds:o});let s=n.slice(0,5).map(jn).join("; "),a=n.length>5?` and ${n.length-5} more`:"",i=`A save of "${r}" ended without an answer, so ${n.length===1?"this edit was":"these edits were"} not sent again: ${s}${a}. Check the value, and redo ${n.length===1?"it":"any"} if missing.`;console.warn(`clay.live("${r}"): ${i}`,n),document.dispatchEvent(new CustomEvent("clay:live-notice",{detail:{name:r,code:"save-uncertain",ops:n,message:i}}))}t&&p?.release(r,{read:p.roomBound(r)})}function de(e){Xt(e);let t=e.store.name;if(e.recovery&&!Dn(e)&&tn(e),!(!e.withheld||e.reading||fe(t).length)){if(!p?.roomBound(t)){e.withheld=!1,pe(e);return}e.reading=!0,st(e),p.release(t,{read:!0})}}function Nn(e){let t=m.get(e);t&&(it(t),!(!t.withheld&&!t.reading)&&(t.withheld=!1,t.reading=!1,[...t.captureOps.values()].some(r=>r.ended)||pe(t)))}function Zt(){for(let e of m.values())if(e.recovery||e.historicalRefreshPending)return!0;return!1}function Dn(e){let t=new Set(e.store.pendingEntries().map(o=>o.id));return e.recovery.targets.find(({name:o})=>o===e.store.name)?.ids.some(o=>t.has(o))??!1}function Hn(e){if(!H||H.captureId!==e||typeof H.html!="string")return null;let t=[];for(let[r,o]of H.qualified)!m.get(r)||!o.length||t.push({name:r,ids:[...o],saved:H.saved.get(r)});return t.length?{captureId:e,html:H.html,targets:t}:null}function Ee(){H&&(H.html=null)}function Wn(e,t){en(e);let r=e.store.name;e.refreshTimer=setTimeout(()=>{if(e.refreshTimer=null,!e.historicalRefreshPending)return;let o=`The save of "${r}" that ended without an answer did happen, but the value the file holds now must load before newer edits can be saved.`;console.warn(`clay.live("${r}"): ${o}`),document.dispatchEvent(new CustomEvent("clay:live-notice",{detail:{name:r,code:"save-history-refresh-required",message:o}}))},Math.max(0,t-Date.now()))}function it(e){e.historicalRefreshPending&&(e.historicalRefreshPending=!1,en(e))}function en(e){e.refreshTimer!==null&&(clearTimeout(e.refreshTimer),e.refreshTimer=null)}function tn(e){let t=e.recovery;t&&(e.recovery=null,!t.targets.some(r=>m.get(r.name)?.recovery===t)&&(j.delete(t.captureId),t.run?.cancel()))}function nn(e){if(e==null)return;let t=j.get(e);if(t){j.delete(e);for(let r of t.targets){let o=m.get(r.name);o&&o.recovery===t&&(o.recovery=null)}t.run?.cancel()}}function In(e,{result:t,attempts:r,startedAt:o}){let{captureId:n,html:s}=e,a={captureId:n,deadline:o+45e3,targets:e.targets,run:null};j.set(n,a);for(let i of e.targets){let c=m.get(i.name);pe(c),c.recovery=a}we("save-history").then(i=>{if(j.get(n)===a){if(e.html=null,!i)return Ft(n);a.run=qn.start({captureId:n,html:s,attempts:r,initialOutcome:t?.saveOutcome??null,startedAt:o,onApplied:({saveId:c,requestHash:d})=>Jn(n,c,d),onUnknown:({reason:c})=>Un(n,c)})}},()=>{e.html=null,Ft(n)})}function Jn(e,t,r){let o=j.get(e);if(o){j.delete(e);for(let n of o.targets){let s=m.get(n.name);if(!s||s.recovery!==o)continue;s.recovery=null,s.historicalRefreshPending=!0;let a=new Set(s.store.pendingEntries().map(c=>c.id)),i=n.ids.filter(c=>a.has(c));if(s.store.rebase(JSON.parse(n.saved),{source:"state",dropIds:i}),!p){it(s);continue}p.release(s.store.name,{read:!0}),Wn(s,o.deadline)}}}function Ft(e){let t=j.get(e);if(t){j.delete(e);for(let r of t.targets){let o=m.get(r.name);if(!(!o||o.recovery!==t)){if(o.recovery=null,!p?.roomBound(o.store.name)){re(o,{read:!1});continue}o.withheld=!0,o.reading=!0,st(o),p.release(o.store.name,{read:!0})}}}}function Un(e,t){let r=j.get(e);if(r){j.delete(e);for(let o of r.targets){let n=m.get(o.name);!n||n.recovery!==r||(n.recovery=null,re(n))}}}function Fn(e,t,r){let o=e.captureOps.get(t),n=e.store.name;if(!o){e.store.handle.status.mode==="file"&&(e.leftAt=null);return}if(o.ended=!0,r?.has(n)){e.withheld=!0,e.reading=!0;return}if(!p?.roomBound(n)){re(e,{read:!1});return}e.withheld=!0,e.reading=!0,st(e),p.release(n,{read:!0})}function Ze(e){if(Array.isArray(e))return e.map(Ze);if(e===null||typeof e!="object")return e;let t={};for(let r of Object.keys(e).sort())t[r]=Ze(e[r]);return t}function at(e){try{return JSON.stringify(Ze(ee(e)))}catch{return null}}var P=null,he=()=>!P||P.admitted;function Yn(){if(!Z||!he())return!1;for(let e of m.values())if(!e.store.ephemeral){if(e.store.handle.status.mode==="fast"){if(p?.isWriter()&&e.landed<e.last)return!0}else if(e.store.pending.length>0)return!0}return!1}var et=new Set;function rn(){for(let e of[...et])e()}var M=Dt({needsSave:Yn,blocked:()=>!he()||!Ue()||Ie()||Et()||Zt(),save:()=>Je().finally(rn),saveNow:()=>De(!0,()=>Je())}),p=null,tt=!1,xe=0,Oe=null,lt=!1,W=null,ct=!1;function Re(){return[...m.values()].filter(e=>!e.store.ephemeral)}function on(){if(!P||P.admitted||!p||p.status.stopped)return!1;for(let e of Re())if(e.store.handle.status.mode==="fast"&&e.store.pending.length>0)return!0;return!1}async function sn({timeoutMs:e=5e3}={}){let t=Date.now()+e,r=()=>{for(let o of Re())o.store.handle.status.mode==="fast"&&o.store.pending.length>0&&p?.release(o.store.name)};for(r();on();){if(Date.now()>=t)return{ok:!1,code:"timeout"};await new Promise(o=>setTimeout(o,5)),r()}return{ok:!0}}We({id:"live:writer",isPending:on,flush:sn});function Bn(){for(let e of m.values()){e.framesSince=!1;let t=e.store.pendingEntries().map(r=>r.id);t.length&&e.store.rebase(e.store.authoritative,{source:"state",dropIds:t})}}function zn(){let e=p;p=null,tt=!1,xe++,Oe=null,W=null,lt=!1,Te=null,ut=null,X=null,z=null,e?.stop()}function $r(){return{id:"clay:live",order:200,prepare(e={}){if(e.initial===!0)return P||(P={admitted:!0}),Bt(P,{adopted:!0});an();let t={admitted:!1,wantsLane:!0};return P=t,Bn(),Pe(),Bt(t)}}}function Yt(){for(let e of Re())e.store.pending.length>0&&p?.release(e.store.name)}function Bt(e,{adopted:t=!1}={}){return{enable(){t||P!==e||(e.admitted=!0,Pe(),Yt())},quiesce(){if(P===e)return e.admitted=!1,sn()},resume(){P===e&&(e.admitted=!0,Yt())},dispose(){P===e&&(P=null,zn())}}}var Te=null,ut=null,X=null,z=null;function an(){Te=new Promise(e=>{X=e}),ut=new Promise(e=>{z=e})}function ft(){return Te||an(),{laneReady:Te,writerReady:ut}}function Cr(){return ft().laneReady}function Mr(){return ft().writerReady}function zt(){for(let e of m.values())if(!e.store.ephemeral&&e.store.handle.status.mode==="fast"&&e.landed===-1){M.soon();return}M.changed()}function Xe(e,t){e.store.rebase(e.store.authoritative,{source:"state",through:t})}function dt(e,t,r=null){if(e)for(let[o,n]of e){let s=m.get(o);!s||n.mode!=="file"||(t||n.maybeLanded?Fn(s,n.key,r):(s.captureOps.delete(n.key),de(s)),s.store.handle.status.mode==="fast"&&p?.release(o))}}function oe(e){let t=V.get(e);return V.delete(e),F===e&&(F=null),q===e&&(q=null),t}function ln(e,t=null){let r=t??F??q;r!==null&&dt(oe(r),e)}function Vn(e,t){if(e?.code==="draft-storage"||e?.code==="draft-not-ready")return!1;let r=e?.code,o=r==="blockeditor-converting"||r==="blockeditor-capacity";return r==="save-already-applied"||e?.hadTimeout===!0||t!==!1&&!o&&!(e?.status>=400&&e?.status<500)}function Vt(e){return{transport:e,entries:m,onWriter:()=>{M.changed(),p&&p.status.writer!==null&&z?.(p)},onApplied:zt,onLanded:()=>{zt(),rn()},onCheckpoint:()=>M.soon(),onLeave:(t,r)=>{let o=m.get(t);o?.store.handle.status.mode==="fast"&&(o.leftAt={...r,frames:[],ancestors:[]})},held:t=>fe(t).length>0,heldIds:fe,hold:t=>{let r=m.get(t);return r?r.recovery?!0:Ut(r)?(r.withheld=!0,!0):(re(r,{read:!1}),!1):!1},taken:Nn,onStop:()=>{for(let t of m.values())it(t),!t.recovery&&(Ut(t)||re(t,{read:!1}))}}}function Kn(){let e=new Map;for(let[t,r]of Y(document,{warn:!1})){let o=m.get(t);if(o){e.set(t,{value:o.store.authoritative,ephemeral:o.store.ephemeral});continue}try{let n=ee(r.element.textContent);n!==null&&typeof n=="object"&&e.set(t,{value:n,ephemeral:r.ephemeral})}catch{}}for(let[t,r]of m)r.staged||e.set(t,{value:r.store.authoritative,ephemeral:r.store.ephemeral});return e}function Pe(){if(ft(),tt||!(P?P.admitted||P.wantsLane:Z))return;if(tt=!0,mt){X?.(null),z?.(null);return}let e=++xe;we("live-data").then(async t=>{let r=t&&await we("live-provenance");if(e!==xe)return;Oe=t,lt=r;let o=await $n().catch(()=>null);if(e===xe){if(!o){X?.(null),z?.(null);return}if(t)p=o.createFastLane(Vt(Jt()));else if(o.localLaneSupported())W=o.localTransport({seed:Kn,rooms:!0,floor:document.querySelector('meta[name="clay-blockeditor-format"]')?.getAttribute("content")}),p=o.createFastLane(Vt(W));else{X?.(null),z?.(null);return}for(let n of Y(document,{warn:!1}).keys())if(!m.has(n))try{un(n)}catch{}for(let[n,s]of m)s.historicalRefreshPending&&p.release(n,{read:!0});p.start(),X?.(p),p.status.writer!==null&&z?.(p)}}).catch(()=>{X?.(null),z?.(null)})}function Gn(e){let t=(e||"").split(";")[0].trim().toLowerCase();return t==="application/json"||t.endsWith("+json")}function Y(e=document,{warn:t=!0}={}){let r=new Map,o=new Set;for(let n of e.querySelectorAll('script[merge][clay~="live"]')){if(n.hasAttribute("src")||!Gn(n.getAttribute("type")))continue;let s=n.getAttribute("merge");if(Cn.test(s)){if(r.has(s)){o.add(s);continue}r.set(s,{name:s,ephemeral:n.getAttribute("clay").split(/\s+/).includes("ephemeral"),element:n})}}for(let n of o)t&&console.warn(`clay.live: more than one live tag is named "${n}", so none of them is live`),r.delete(n);return r}function $e(e){return new DOMParser().parseFromString(e,"text/html")}function Xn(e){let t=e.store.handle.status.mode==="fast",r=t?e.store.authoritative:e.store.value,o=t&&/^blockeditor(\.[0-9]+)?$/.test(e.store.name)?jt(r):r;return e.layout==="lines"?Qn(o):e.layout==="pretty"?JSON.stringify(o,null,2).replace(/</g,"\\u003c"):R(o)}var Kt=e=>e!==null&&typeof e=="object"&&!Array.isArray(e);function Qn(e){return Kt(e)?`{${Object.entries(e).map(([r,o])=>!Kt(o)||!Object.keys(o).length?`${R(r)}:${R(o)}`:`${R(r)}:{
2
2
  ${Object.entries(o).map(([n,s])=>`${R(n)}:${R(s)}`).join(`,
3
3
  `)}
4
4
  }`).join(`,