@panphora/clayjs 1.19.0 → 1.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/all.js +1 -1
- package/dist/clay-dom.js +1 -1
- package/dist/clay-events.js +1 -1
- package/dist/clay-internals.js +1 -1
- package/dist/clay-options.js +1 -1
- package/dist/clay-router.js +1 -1
- package/dist/clay-ui.js +1 -1
- package/dist/clay-utils.js +1 -1
- package/dist/clay.js +1 -1
- package/dist/clay.standalone.js +8349 -8125
- package/dist/m/attrs/{refetch-on-save-ZUE7PSCI.js → refetch-on-save-DPGJJMGN.js} +1 -1
- package/dist/m/attrs/save-freeze-MTFVVYV5.js +1 -0
- package/dist/m/{c-DHUCEMXE.js → c-2VB555FG.js} +1 -1
- package/dist/m/{c-KGHVFRR3.js → c-3AXJDL2P.js} +1 -1
- package/dist/m/{c-FOOE4GML.js → c-3GJ4XARY.js} +1 -1
- package/dist/m/c-3TWCKFOP.js +1 -0
- package/dist/m/{c-LPCZOYTX.js → c-3YH6JSIL.js} +1 -1
- package/dist/m/{c-AIWN4QN4.js → c-44B5ODN7.js} +2 -2
- package/dist/m/{c-WQWIRWO3.js → c-5FEU5MMY.js} +1 -1
- package/dist/m/{c-S2U6NJU4.js → c-62HZW5DH.js} +1 -1
- package/dist/m/{c-ZGDYHKG3.js → c-67ILSNPR.js} +1 -1
- package/dist/m/c-67LGZ52V.js +20 -0
- package/dist/m/{c-ZRUQ5FSU.js → c-7SXYQCN4.js} +1 -1
- package/dist/m/{c-LACAAQFB.js → c-AL4RBJF2.js} +1 -1
- package/dist/m/{c-L42OLXWM.js → c-ANNFZFLN.js} +1 -1
- package/dist/m/{c-QO4HNGCQ.js → c-B4VYNXTQ.js} +1 -1
- package/dist/m/{c-7PRJCA3E.js → c-BJPZCWAV.js} +1 -1
- package/dist/m/{c-V52FE5FI.js → c-BTLFLLML.js} +1 -1
- package/dist/m/c-C4IIQZGJ.js +1 -0
- package/dist/m/{c-5T6NZHNM.js → c-CAWNFER6.js} +1 -1
- package/dist/m/c-CSNE5EIF.js +1 -0
- package/dist/m/{c-DVYGFTSK.js → c-DDDOKPI6.js} +2 -2
- package/dist/m/{c-2RARVIAK.js → c-DHXPDLW6.js} +1 -1
- package/dist/m/{c-WCXLG3MV.js → c-E4IBSAQM.js} +1 -1
- package/dist/m/{c-IVTRVENZ.js → c-EDSPKYMA.js} +1 -1
- package/dist/m/{c-2Y4DOHSY.js → c-EFD6QNTE.js} +1 -1
- package/dist/m/{c-7MG5RU63.js → c-EGTIAL6P.js} +1 -1
- package/dist/m/{c-FCNAO2MI.js → c-EOCKLMKX.js} +1 -1
- package/dist/m/{c-UXFUJEZO.js → c-EOCZ2YVL.js} +1 -1
- package/dist/m/{c-K72SY2TL.js → c-EZ7B5AZT.js} +1 -1
- package/dist/m/{c-UPD33ZPE.js → c-FDAXZ2PM.js} +1 -1
- package/dist/m/{c-P3CK66NT.js → c-FNVQAACK.js} +1 -1
- package/dist/m/c-FSWRGBVQ.js +1 -0
- package/dist/m/c-FTWGYI5E.js +1 -0
- package/dist/m/{c-WKNRJX3C.js → c-GKEATME6.js} +1 -1
- package/dist/m/{c-QINHDETP.js → c-GPGYKER7.js} +1 -1
- package/dist/m/{c-FWKHM4E7.js → c-GSRLXYWL.js} +1 -1
- package/dist/m/{c-B7J4K2AE.js → c-GVPNDIKJ.js} +2 -2
- package/dist/m/{c-D3E4WJ4M.js → c-HDWZEJHM.js} +49 -32
- package/dist/m/{c-FTQKI7SP.js → c-I2IFKJX2.js} +1 -1
- package/dist/m/c-ICMAOOGK.js +1 -0
- package/dist/m/{c-HUISJXHF.js → c-J3BXFTZS.js} +1 -1
- package/dist/m/{c-BIJALSRD.js → c-JDZDF2QM.js} +1 -1
- package/dist/m/{c-UDHIVLYH.js → c-JH5FF4NL.js} +1 -1
- package/dist/m/{c-OYRZ7XG2.js → c-JHJR5BQX.js} +1 -1
- package/dist/m/{c-V44KWI2L.js → c-JOH753EJ.js} +2 -2
- package/dist/m/{c-P3OFYUMA.js → c-JUE7B4OX.js} +1 -1
- package/dist/m/c-K76AUL4I.js +7 -0
- package/dist/m/{c-ZWIOJGMT.js → c-LA2BW7UY.js} +1 -1
- package/dist/m/{c-ICJYHABF.js → c-LDUNOR57.js} +1 -1
- package/dist/m/{c-XSZKP646.js → c-LIBE4HPD.js} +1 -1
- package/dist/m/c-LPUJXRXW.js +1 -0
- package/dist/m/{c-JK3PHE7J.js → c-LQU7TXIH.js} +1 -1
- package/dist/m/{c-5ZQV7KC4.js → c-LV5MABYD.js} +1 -1
- package/dist/m/{c-GWNC3UGL.js → c-M4FSPNQ2.js} +1 -1
- package/dist/m/{c-2KIEGNC4.js → c-MEWUGR4D.js} +1 -1
- package/dist/m/c-MIL4B2JQ.js +1 -0
- package/dist/m/{c-IVMD3FEM.js → c-N7Y52HJH.js} +1 -1
- package/dist/m/{c-O4JMKN6U.js → c-NFR673TL.js} +2 -2
- package/dist/m/{c-ZKNBMNN3.js → c-NLZ5AN4L.js} +1 -1
- package/dist/m/{c-RRZJWFLE.js → c-OABVRYOT.js} +1 -1
- package/dist/m/c-PIVIYLTY.js +1 -0
- package/dist/m/{c-L7JL5TL3.js → c-QY7F6EN6.js} +1 -1
- package/dist/m/{c-UY4QX42B.js → c-RG6XUZFA.js} +1 -1
- package/dist/m/c-RHMPKZZ7.js +1 -0
- package/dist/m/{c-TJAXGIRV.js → c-RQRMPZXD.js} +1 -1
- package/dist/m/{c-GY422N3Q.js → c-RS77ODLY.js} +1 -1
- package/dist/m/{c-BAUBNYXK.js → c-RT3C74GY.js} +1 -1
- package/dist/m/{c-CAS3NND4.js → c-S5IEIZCN.js} +1 -1
- package/dist/m/{c-HXPHZN7Q.js → c-SBSMJIPC.js} +1 -1
- package/dist/m/c-SFKI6OLM.js +2 -0
- package/dist/m/{c-4FJTBE6I.js → c-SJPD46ZO.js} +4 -4
- package/dist/m/{c-JCP3XDSJ.js → c-SO63UGPQ.js} +1 -1
- package/dist/m/{c-PLP4JKFC.js → c-TUGVINJR.js} +1 -1
- package/dist/m/{c-Q26MME6N.js → c-TWCXBWS3.js} +1 -1
- package/dist/m/{c-GNDL3TKB.js → c-U5X57T4L.js} +1 -1
- package/dist/m/{c-ZS4US2XV.js → c-UXEVJ63W.js} +1 -1
- package/dist/m/{c-KJJPV77R.js → c-V2J5C5MT.js} +1 -1
- package/dist/m/{c-7PYNAULW.js → c-VBLFAQD2.js} +1 -1
- package/dist/m/{c-ERQSNR6K.js → c-VQCEOGKH.js} +2 -2
- package/dist/m/{c-YVZ2L7CE.js → c-VSPAFOKU.js} +1 -1
- package/dist/m/{c-L6FLIUXP.js → c-VY6XRBOW.js} +1 -1
- package/dist/m/{c-2KL3BD52.js → c-W23KVGUO.js} +1 -1
- package/dist/m/{c-AXGY2WTB.js → c-W3K23S72.js} +1 -1
- package/dist/m/c-WFMRX5RZ.js +1 -0
- package/dist/m/{c-BWFVSBDF.js → c-WN3MXOLT.js} +1 -1
- package/dist/m/{c-MIKZEG5I.js → c-XD5MOROJ.js} +1 -1
- package/dist/m/{c-CQQDL6O4.js → c-XQSXKIKM.js} +1 -1
- package/dist/m/{c-I4MQHOEY.js → c-Y33LUUIQ.js} +1 -1
- package/dist/m/{c-JDARJDOT.js → c-YQUJ74R3.js} +1 -1
- package/dist/m/{c-F6G2OGYG.js → c-YSB6JKV2.js} +2 -2
- package/dist/m/{c-BHZYSHW4.js → c-ZJLU56DV.js} +1 -1
- package/dist/m/{c-DKLS74XB.js → c-ZQXNHZZT.js} +2 -2
- package/dist/m/{c-TNEM3RNM.js → c-ZSCBEB7I.js} +1 -1
- package/dist/m/core/{admin-attrs-YY7T5FGU.js → admin-attrs-ZG7R5V3E.js} +1 -1
- package/dist/m/core/{autosave-RVJPYLRT.js → autosave-VPORYJSE.js} +1 -1
- package/dist/m/core/{conflict-notice-2WGT52LH.js → conflict-notice-JMAZLVRX.js} +1 -1
- package/dist/m/core/{persist-UKXV5KLA.js → persist-3OPWJKZS.js} +1 -1
- package/dist/m/core/{recovery-ZOUOJVIX.js → recovery-DRFZRJED.js} +1 -1
- package/dist/m/core/{save-A5JXV6ME.js → save-AOJBDSOK.js} +1 -1
- package/dist/m/core/{save-core-MKRPSEEO.js → save-core-IOCMXO5L.js} +1 -1
- package/dist/m/core/{snapshot-NU3YM6GR.js → snapshot-O7II2AGG.js} +1 -1
- package/dist/m/core/unsaved-warning-U5VUJFOE.js +1 -0
- package/dist/m/events/{index-RN2JNGBV.js → index-B6TGDYMG.js} +1 -1
- package/dist/m/internals/{index-TGLQINN3.js → index-HDRANDWE.js} +1 -1
- package/dist/m/lib/{cache-bust-MUMFXZK6.js → cache-bust-NH7VBWHO.js} +1 -1
- package/dist/m/lib/{region-policy-SB2AWVG5.js → region-policy-KWBPROWF.js} +1 -1
- package/dist/m/{loader-34YPFKOH.js → loader-ZVPK4ZN3.js} +1 -1
- package/dist/m/manifest-5498AFD3.js +1 -0
- package/dist/m/manifest-edit-62A5A00F.js +1 -0
- package/dist/m/manifest.json +1215 -1171
- package/dist/m/options/{options-EJMS3K24.js → options-55LQHSJ4.js} +1 -1
- package/dist/m/page/{editor-WRQGHDSG.js → editor-EY2WAAGB.js} +2 -2
- package/dist/m/plugins/{ai-edit-X2L2KIEP.js → ai-edit-J5VLSW5I.js} +1 -1
- package/dist/m/plugins/{demo-OYO5GCAO.js → demo-42BSYQ7T.js} +1 -1
- package/dist/m/plugins/{derive-FRE5JJQE.js → derive-QVI3LI3A.js} +1 -1
- package/dist/m/plugins/{live-7C36XEI2.js → live-5EZN2EYP.js} +1 -1
- package/dist/m/plugins/menu-DM2JHPSR.js +1 -0
- package/dist/m/plugins/{page-BSW6MGDO.js → page-LVW5DWA4.js} +2 -2
- package/dist/m/plugins/{page-view-WFZVTPQK.js → page-view-5KQ76IJB.js} +1 -1
- package/dist/m/plugins/{sortable-4S6SQC3D.js → sortable-WJZZBM7R.js} +1 -1
- package/dist/m/plugins/{source-TJXOIOYY.js → source-CCEUM3OR.js} +1 -1
- package/dist/m/plugins/{undo-NLPGCJQY.js → undo-3JEYK5QY.js} +1 -1
- package/dist/m/plugins/{upgrade-HSUNDNJD.js → upgrade-NW556WJD.js} +1 -1
- package/dist/m/plugins/{upload-NHGJXZK2.js → upload-TTCQRIM5.js} +1 -1
- package/dist/m/plugins/{visitor-drafts-BW43DGY3.js → visitor-drafts-2AWNT23K.js} +2 -2
- package/dist/m/plugins/{visitor-drafts-owner-7ODQG7JX.js → visitor-drafts-owner-MZP45XSG.js} +1 -1
- package/dist/m/plugins/{wire-6OSIL3I7.js → wire-VRYPY6EJ.js} +1 -1
- package/dist/m/{reader-core-PLZYLYLT.js → reader-core-2GXY7SHY.js} +2 -2
- package/dist/m/sync/{live-sync-UXNI6ZF6.js → live-sync-SKPMFYOO.js} +1 -1
- package/dist/m/ui/{index-IVWN2QC4.js → index-QNIPDHXQ.js} +1 -1
- package/dist/m/vendor/{sap-core.vendor-RN4ZVY4X.js → sap-core.vendor-OA5SKL7Q.js} +1 -1
- package/dist/offline-manifest.json +650 -626
- package/docs/guide.md +38 -14
- package/entries/sap.js +1 -1
- package/package.json +3 -2
- package/src/core/conflict-download.js +8 -7
- package/src/core/conflict-notice-ui.js +4 -4
- package/src/core/copy-content.js +103 -0
- package/src/core/download.js +14 -2
- package/src/core/save-size-notice.js +2 -2
- package/src/core/upgrade-run.js +5 -1
- package/src/lib/region-policy.js +1 -1
- package/src/page/features/export-html.js +4 -4
- package/src/page/features/export-markdown.js +2 -2
- package/src/page/recovery-ui.js +2 -2
- package/src/page/save-states.js +4 -4
- package/src/plugins/menu/actions.js +1 -1
- package/src/plugins/menu/style.js +59 -31
- package/src/plugins/menu.js +131 -28
- package/src/plugins/page.js +4 -4
- package/src/plugins/visitor-drafts/prompt.js +12 -12
- package/src/plugins/wire.js +3 -1
- package/src/vendor/sap-core.vendor.js +1 -1
- package/dist/m/attrs/save-freeze-LWGF6XUN.js +0 -1
- package/dist/m/c-DCFSEJZG.js +0 -1
- package/dist/m/c-EXEDYU4H.js +0 -1
- package/dist/m/c-GRXHHFPO.js +0 -1
- package/dist/m/c-HT2DKBV2.js +0 -1
- package/dist/m/c-MCOOHCSG.js +0 -1
- package/dist/m/c-MMXKAX2W.js +0 -1
- package/dist/m/c-VE7RKNKZ.js +0 -7
- package/dist/m/c-VR2BJ4AN.js +0 -1
- package/dist/m/c-WGW764WX.js +0 -1
- package/dist/m/c-WNTYKCDG.js +0 -1
- package/dist/m/c-YBSS55KU.js +0 -20
- package/dist/m/core/unsaved-warning-4ZPEV7BF.js +0 -1
- package/dist/m/manifest-0D166F4F.js +0 -1
- package/dist/m/manifest-edit-3877153E.js +0 -1
- package/dist/m/plugins/menu-MFC4DI5E.js +0 -1
- /package/dist/m/{c-QTTJYJMA.js → c-FILLTJA7.js} +0 -0
- /package/dist/m/{c-5JLFROUB.js → c-X5LNHET5.js} +0 -0
- /package/dist/m/plugins/{people-JCHVPF7P.js → people-C7TVBBMR.js} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as Xe,b as ce,d as de,e as ue,f as et}from"./c-2RARVIAK.js";import{a as Ke,b as Qe,c as he,d as Ze}from"./c-LZJPNR2W.js";import{a as R,b as Y}from"./c-QTTJYJMA.js";import{b as Ve}from"./c-5VYOWDTI.js";import{b as le,c as oe,d as x,f as ae,g as Ye,h as Je}from"./c-FWKHM4E7.js";import{a as q}from"./c-ZWIOJGMT.js";import{a as Ne}from"./c-ATKAOH23.js";import{a as $e,f as je,g as ze,h as We}from"./c-EK63G3CG.js";import{a as ie,b as Ge,c as M,d as se,e as re,h as Ue}from"./c-NQJRVJ56.js";import{e as Oe}from"./c-XGH4GS2T.js";import{d as qe}from"./c-IJUK2GPW.js";import{f as $,j as ee}from"./c-3O7OBDCM.js";import{a as Ie}from"./c-BPF2NSPV.js";import{D as W,E as Me,G as T,H as Be,b as D,j as ne,s as P,y as Pe}from"./c-7MG5RU63.js";import{a as Fe,b as Re,c as He,e as j,g as z,h as te}from"./c-VG5XIN4T.js";import{m as be,n as De}from"./c-HA6INT6J.js";import{a as Te,b as Le,l as Ce,m as Ae}from"./c-DCFSEJZG.js";function tt(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 nt(s,e){let t=new WeakMap;if(!s||!e||typeof e!="object"||Array.isArray(e))return t;let i=e["~"],n=typeof i=="string"?i.split(",").map(Number):null,r=n&&typeof e["^"]=="string"?e["^"].split(","):null,l=d=>Number.isInteger(d)&&d>=0,o=0,a=!1,h=d=>{let _=d;for(;_>0;){let g=n[o++];if(o>n.length||!l(g))return!1;_+=g-1}return!0},c=(d,_)=>{if(a)return;if(n){let f=o++,u=n[f];if(f>=n.length||!l(u)){a=!0;return}let S=!r||r[f]===d.tagName.toLowerCase();if(!S||u!==d.children.length){let w=S&&e[_];typeof w=="string"&&w&&t.set(d,w),h(u)||(a=!0);return}}let g=e[_];typeof g=="string"&&g&&t.set(d,g);let E=d.children;for(let f=0;f<E.length;f++)c(E[f],_===""?String(f):`${_}.${f}`)};return c(s,""),t}function yt(s){return e=>{for(let t of s){let i=t(e);if(typeof i=="string"&&i!=="")return i}return null}}var Pt=yt([s=>s.getAttribute("data-id"),s=>s.getAttribute("id")]);var mt=/^page(\.[0-9]+)?$/,it=s=>[...s.querySelectorAll('script[merge][clay~="live"]')].filter(e=>mt.test(e.getAttribute("merge")));function st(s,e,t){if(!s.html.includes("data-page"))return s;let i=u=>new DOMParser().parseFromString(u,"text/html"),n=i(s.html),r=n.querySelector("article[data-page]");if(!r)return s;let l=i(e),o=l.querySelector("article[data-page]");if(!o)return null;let a=nt(n.documentElement,s.identityMap),h=(u,S)=>{let w=n.importNode(S,!0),b=a.get(u);return b&&a.set(w,b),u.replaceWith(w),w},c=h(r,o),d=new Map(it(n).map(u=>[u.getAttribute("merge"),u]));for(let u of it(l)){let S=u.getAttribute("merge"),w=d.get(S);w?h(w,u):c.before(n.importNode(u,!0)),d.delete(S)}for(let u of d.values())u.remove();let _=n.querySelector("head > title"),g=l.querySelector("head > title");_&&g?h(_,g):g?n.head.append(n.importNode(g,!0)):_?.remove();let E=n.documentElement,f=t.exportMap(E,u=>{let S=a.get(u);return S?(t.adopt(u,S),u):null});return{...s,html:T(E),identityMap:f}}var vt={"merge-tokens":"tokens","merge-max":"max"};function rt(s,e){if(!e.startsWith("data-")||e==="data-id"||!s?.closest)return null;for(let[t,i]of Object.entries(vt)){let n=s.closest(`[${t}]`);if(n&&n.getAttribute(t).split(/\s+/).includes(e))return i}return null}var m=null,lt=null,B=new Map;function J(){return lt??=Promise.all([import("./c-5T6NZHNM.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}),lt}var ot=()=>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,fe=null;function H(){return fe??=new Promise(s=>setTimeout(s,0)).then(()=>import("./c-P3CK66NT.js")).then(s=>y=s).catch(s=>{throw fe=null,s}),fe}var ye=null,pe=null;function Et(){return pe??=import("./c-VR2BJ4AN.js").then(s=>ye=s.presence).catch(s=>{throw pe=null,s}),pe}var ct=ee().phase==="entering";$&&!ct&&H().catch(()=>{});$&&J().catch(()=>{});var L=null,_e=null,K=[];function dt(s){L.presence.update(s),L.editingMarker.update(s)}function wt(){return _e??=Promise.all([import("./c-BHZYSHW4.js"),import("./c-P3OFYUMA.js")]).then(([s,e])=>{L={presence:s.presence,editingMarker:e.editingMarker};let t=K;K=[];for(let i of t)dt(i);return L}).catch(s=>{throw _e=null,s}),_e}function kt(s){if(L){dt(s);return}K.push(s),wt().catch(()=>{})}var at=Object.freeze({bytes:null,etag:null,seq:null}),xt=()=>({msg:"Not in edit mode",msgType:"skipped",code:null,etag:null}),ut=["[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,Te].join(","),ft='[clay~="freeze"], [freeze], [save-freeze]';function V(s){for(let e of s.querySelectorAll(ft))e.replaceChildren();return z()&&He(s),s}function ht(s){if(s==null)return s;let e=typeof s=="string"?new DOMParser().parseFromString(s,"text/html"):s;return ne(e),V(e),e}var bt=[Ae,'[clay~="no-watch"]',"[no-watch]","[mutations-ignore]"].join(","),Dt=(s,e,t)=>be(s,e,t)||Le.test(e.toLowerCase()),pt=s=>s.getAttribute("data-id")||s.getAttribute("id")||null;function It(s){let e=new Map,t=n=>{if(n.matches(ut))return;let r=pt(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 Tt=s=>e=>{let t=pt(e);if(!t)return null;let i=e.getRootNode(),n=s.get(i);return n||s.set(i,n=It(i)),n.get(t)===1?t:null},ge=s=>!!s&&typeof s=="object"&&!Array.isArray(s);function Lt(s){return typeof s!="string"||s===""?null:new DOMParser().parseFromString(s,"text/html").documentElement?.getAttribute("documentetag")||null}function Ct(s,e){e!=="live"||!s||!y||(y.enableContentEditable(s),y.enableOnClick(s),y.enableAdminInputs(s),y.enableAdminResources(s))}function At(){let{forComparison:s,forDirty:e}=Pe({flushUndo:!1});return[s,e]}var Ft=1024*1024;function Rt(s,e,t,i,n){let r={sender:t,identityMap:i,...n?{etag:n}:{}};return e.length<Ft?JSON.stringify({[s.snapshotKey]:e,...r}):new Blob([`{${JSON.stringify(s.snapshotKey)}:`,JSON.stringify(e),`,${JSON.stringify(r).slice(1)}`],{type:"application/json"})}var me=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._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.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=at,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=tt(this.clientId),this.onConnect=null,this.onDisconnect=null,this.onUpdate=null,this.onError=null,this.onNotification=null}get unresolvedConflicts(){return I.list().filter(e=>e.kind!=="apply-incomplete")}_log(e,t=null){if(!this.debug)return;let i=`[LiveSync ${new Date().toISOString()}]`;t!==null?console.log(i,e,t):console.log(i,e)}generateClientId(){return Math.random().toString(36).slice(2,11)+Date.now().toString(36)}generateResumeId(){try{let e=new Uint8Array(16);return(globalThis.crypto||window.crypto).getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}catch{return Math.random().toString(36).slice(2)+Date.now().toString(36)}}_seedBases(){if(x())return;let e=P({flushUndo:!1});this._setPeerBase(T(e),this.identity.exportMap(e,D),this._ticket()),this._setDiskBase(W({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=ee().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}):at,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"&&J().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)&&!qe()&&!x()&&this._saveTicket===0&&this._morphTicket===a){if(c!==null&&this._applyGen===o&&this._saveEpoch===h&&this.lastHtml===c){let g=P({flushUndo:!1});this._setPeerBase(T(g),this.identity.exportMap(g,D),this._ticket())}_&&this._diskBaseTicket===d&&this._setDiskBase(W({emitForSync:!1}).forSave,this._ticket())}},document.addEventListener("clay:baseline-settled",this._settledHandler,{once:!0})}this._ready=Promise.all([this.lane==="live"?H():null,this._resolveProfile()]).then(()=>{this.isDestroyed||this._startGen!==l||this.connect()}),this.lane==="live"&&(this.listenForSnapshots(),Et().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===ie()&&(y?.conflictResolvedBySync(a),this._saveAfterMerge(x(),!1))})},document.addEventListener("clay:save-conflict",this._saveConflictHandler))}cleanup(){if(this.sse&&(this.sse.close(),this.sse=null),he(),K=[],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._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=et().then(e=>(this._sharedData=e.sharedData,this._sharedSync=e.sharedSync,this._liveData=e.liveData,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&&Ue({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||ue.legacy).streamPath(window.location.href,this.lane,this.resumeId,this.clientId);this.sse=new Xe(new URL(t,window.location.origin).href,{shared:this._sharedSync,sharedData:this._sharedData,documentURL:window.location.href,lane:this.lane,clientId:this.clientId,keepAliveWhenHidden:this._liveData&&this.lane==="live",startupCheck:!!Ie}),this._acquireEmptySaved&&(this._acquireEmptySaved=!1,this._fetchServedDocument(void 0,{repair:!0})),this.sse.onopen=()=>{console.log("[LiveSync] Connected"),this._editing&&this._editing.reconnected(),ye&&ye.reconnect(),this.onConnect&&this.onConnect()},this.sse.addEventListener("open",()=>Qe({clientId:this.clientId,lane:this.lane})),this.sse.addEventListener("error",()=>he());for(let i of Ke)this.sse.addEventListener(i,n=>{let r;try{r=JSON.parse(n.data)}catch{return}Ze(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}kt(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&&Ge()){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}),M(h);return}if(h&&l===this.lastHtml){this._log(`Taking the stamp from a peer save of content already applied (seq=${r})`),M(h),y&&y.isSaveConflicted()&&(y.conflictResolvedBySync(h),this._saveAfterMerge(x(),!1));return}this._log(`Received update from: ${o} (my clientId: ${this.clientId}, seq=${r})`),this.applyUpdate(l,r,a,h,n.by),this.onUpdate&&this.onUpdate({html:l,sender:o,seq:r,identityMap:a,etag:h})},this.sse.onerror=()=>{this.sse.readyState===EventSource.CONNECTING?console.log("[LiveSync] Reconnecting..."):this.sse.readyState===EventSource.CLOSED&&(console.log("[LiveSync] Connection closed"),this.onError&&this.onError(new Error("Connection closed"))),this.onDisconnect&&this.onDisconnect()}}listenForSnapshots(){this._snapshotHandler=e=>{if(!e.detail||e.detail.forSave!==!0)return;this._saveTicket=this._ticket();let{documentElement:t}=e.detail;if(!t)return;this._log("snapshot-ready received, preparing to send");let i=this.identity.exportMap(t,D);this._savedSnapshot?.abort?.abort();let n={html:null,steps:null,copy:null,abort:null,identityMap:i,ticket:this._saveTicket,captureId:e.detail.captureId??null};if(e.detail.sliced){n.copy=Be(t),n.abort=new AbortController;let{signal:r}=n.abort;Promise.all([import("./c-2KIEGNC4.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=ie(),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=st(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=Ht(e)??t,a=typeof o=="string"?je(o):0;l={...l,html:qt(ze(l.html,Math.max(We(),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||ue.legacy;fetch(new URL(l.relayPath,window.location.origin).href,{method:"POST",headers:{"Content-Type":"application/json",[l.documentHeader]:window.location.href,[$e]:String(1)},body:Rt(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,Oe("presence-editing")),()=>!1).then(i=>{if(!(!i||this.isDestroyed||this._startGen!==t||this._editing))return H().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=Lt(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===se()){(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-I4MQHOEY.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(!R()){this._morphInFlight=!0;try{await Y()}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===se())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){return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(e):setTimeout(e,16)}_cancelFrame(e){if(typeof window<"u"&&typeof window.cancelAnimationFrame=="function"){window.cancelAnimationFrame(e);return}clearTimeout(e)}async _mergeIncoming(e,t,{base:i,baseIdentityMap:n=null,captureLocal:r,synthetic:l,source:o="peer",seq:a=null,etag:h=null,extra:c={}}){R()||await Y();let{beginApply:d,completeApply:_,failApply:g,beginLineageCapture:E}=ot()||await J(),f,u=p=>{f=E(I.list());try{let v=R().HyperMorph.mergeDocument({...p,lineage:f.lineage});return f.returned(),v}catch(v){throw f.invalidate(I.list()),f.finish(I.list()),v}},S=this.identity,w=De,b=Tt(new WeakMap),N=p=>ge(p)?{first:b,map:p,then:b}:b,O=l?p=>b(p)||S.idOf(D(p)||p)||null:b,C=e,Se=new Map;if(ge(t)){C=new DOMParser().parseFromString(e,"text/html"),ne(C);let p=R().HyperMorph.importMap(C.documentElement,t);for(let v of C.querySelectorAll("[data-id], [id]")){let k=b(v),xe=k&&p.get(v);xe&&Se.set(k,xe)}}C=ht(C);let Q={live:document,remote:C,ignore:p=>p.matches(ut),opaque:p=>p.matches(ft)||z()&&Re(p),remoteWins:p=>p.matches(bt),ignoreAttribute:(p,v,k)=>Dt(p,v,k)||z()&&Fe(k||p,v),attributeMerge:rt,protectFocusedValue:!0,restoreFocus:document.activeElement?.localName!=="clay-editor-ui",keepLiveOnly:o==="peer",scripts:{mergeTags:R().mergeTagRecognizers},hooks:{beforeAttributeUpdated:w},...c},Ee=this.lane==="live"&&x(),we=ae(),G,Z=null,F=null;if(i==null)G=u({...Q,base:null,local:{root:V(r()),toLive:D},identity:{local:O,remote:N(t)}});else if(Ee){let p=r(),v=p.cloneNode(!0);Z=V(p),F=d({source:o,seq:a,etag:h,root:Z,recoveryRoot:v,domain:o==="disk"?"save":"sync"});try{G=u({...Q,base:ht(i),local:{root:Z,toLive:D},identity:{base:N(n),local:O,remote:N(t)}})}catch(k){throw g(F,k),k}}else{let p=V(r()),v=p.ownerDocument;v.documentElement!==p&&v.replaceChild(p,v.documentElement),G=u({...Q,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 A;try{A=await G}catch(p){f.invalidate(I.list());try{F&&g(F,p,{ticket:U})}finally{f.finish(I.list())}throw p}let _t=ae().gen!==we.gen,ke;try{f.prepareComplete(A,I.list()),ke=F?_(F,A.conflicts,{ticket:U}):[]}finally{f.finish(I.list())}this.lane==="live"&&A.localDiverged?Ye():Ee&&!A.localDiverged&&Je(we);let gt=new Set(ge(t)?Object.values(t):[]);for(let[p,v]of A.identities){let k=gt.has(v)?v:Se.get(v);k&&S.adopt(p,k)}return{report:A,ticket:U,typedDuringWait:_t,conflictIds:ke}}_saveAfterMerge(e,t){(e||t)&&Ve()&&(y?y.savePageThrottled():xt())}async _doApplyUpdate(e,t,i,n,r=null){if(ce(e)){await de();return}this.lane==="live"&&!y&&await H(),this._log("applyUpdate - pausing mutations and morphing"),this.isPaused=!0;let l=window.scrollX,o=window.scrollY;q.pause(),le();let a=!1,h=!1,c=!1;try{if(this.lane==="live"&&x()&&this.lastHtml===null){console.log("[LiveSync] Holding incoming update: unsaved local edits and no baseline to merge against"),this._setHeld("live",!0,null);let f=this._saveEpoch,u=this.lastSeenSeq;clearTimeout(this._holdRetryPeer),this._holdRetryPeer=setTimeout(()=>{this._holdRetryPeer=null,!(this.isDestroyed||this._pendingHtml!=null)&&this._saveEpoch===f&&this.lastSeenSeq===u&&(this._pendingHtml=e,this._pendingSeq=t,this._pendingIdentityMap=i,this._pendingBy=r,this._scheduleNextFrame())},3e3);return}this._setHeld("live",!1);let{report:d,ticket:_,typedDuringWait:g,conflictIds:E}=await this._mergeIncoming(e,i,{base:this.lastHtml,baseIdentityMap:this._lastIdentityMap,captureLocal:()=>P({flushUndo:!1}),synthetic:!0,source:"peer",seq:t,etag:n});if(a=d.localDiverged,h=g,te(),window.scrollTo(l,o),this._setPeerBase(e,i,_),this._applyGen++,this._acceptedSaveTicket>_||(typeof n=="string"&&n?(M(n),c=!0):re()),this.lane==="live"&&!a&&!x()){let{forSave:f,forComparison:u,forDirty:S}=W({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(),oe(),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(ce(e)){await de();return}this.lane==="live"&&!y&&await H();let l=this._diskBase;this._log(`applyExternal - external disk change (seq=${t})`),this.isPaused=!0;let o=window.scrollX,a=window.scrollY;q.pause(),le();let h=!1,c=!1,d=!1;try{if(this.lane==="live"&&x()&&this._diskBase===null){if(console.log("[LiveSync] Holding external change: unsaved local edits and no baseline to merge against"),this._setHeld("external",!0,null),r?.startup||r?.versionCheck){clearTimeout(this._holdRetryExt),this._holdRetryExt=setTimeout(()=>{if(this._holdRetryExt=null,this.isDestroyed)return;let S=typeof t=="number"?Math.max(t,this._lastExternalSeq):t;this._retryStartup(0,r,S)},3e3);return}let u=this._saveEpoch;clearTimeout(this._holdRetryExt),this._holdRetryExt=setTimeout(()=>{this._holdRetryExt=null,!(this.isDestroyed||this._pendingExternal!=null)&&(this._pendingExternal={html:e,seq:t,saveEpoch:u,etag:i,by:n},this._scheduleNextFrame())},3e3);return}this._setHeld("external",!1);let{report:_,ticket:g,typedDuringWait:E,conflictIds:f}=await this._mergeIncoming(e,null,{base:this._diskBase,captureLocal:()=>Me().saveClone,synthetic:!1,source:"disk",seq:t,etag:i,extra:{beforeApply:u=>Ct(u.documentElement,this.lane)}});if(h=_.localDiverged,c=E,te(),this._setDiskBase(e,g),window.scrollTo(o,a),this._acceptedSaveTicket>g||(typeof i=="string"&&i?(M(i),d=!0):re()),this.lane==="live"&&!h&&!x()){y.setLastSavedBaselines(...At()),y.setUnsavedChanges(!1);let u=P({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(),oe(),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 H().then(e=>e.syncParticipant(this))}},X=null;Ne((s,e)=>{X=typeof s=="string"?{html:s,captureId:e?.captureId??null}:null});var Ht=s=>X&&(X.captureId??null)===(s??null)?X.html:null;function qt(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 ve=new me;typeof window<"u"&&!ct&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>ve.start()):ve.start());var _n=(s,e,t)=>Y().then(({morph:i})=>i(s,e,t));var gn=ve;export{I as a,ut as b,bt as c,me as d,ve as e,_n as f,gn as g};
|
|
1
|
+
import{a as Xe,b as ce,d as de,e as ue,f as et}from"./c-DHXPDLW6.js";import{a as Ke,b as Qe,c as he,d as Ze}from"./c-LZJPNR2W.js";import{a as R,b as Y}from"./c-FILLTJA7.js";import{b as Ve}from"./c-5VYOWDTI.js";import{b as le,c as oe,d as x,f as ae,g as Ye,h as Je}from"./c-GSRLXYWL.js";import{a as q}from"./c-LA2BW7UY.js";import{a as Ne}from"./c-ATKAOH23.js";import{a as $e,f as je,g as ze,h as We}from"./c-EK63G3CG.js";import{a as ie,b as Ge,c as M,d as se,e as re,h as Ue}from"./c-NQJRVJ56.js";import{e as Oe}from"./c-XGH4GS2T.js";import{d as qe}from"./c-IJUK2GPW.js";import{f as $,j as ee}from"./c-3O7OBDCM.js";import{a as Ie}from"./c-BPF2NSPV.js";import{D as W,E as Me,G as T,H as Be,b as D,j as ne,s as P,y as Pe}from"./c-EGTIAL6P.js";import{a as Fe,b as Re,c as He,e as j,g as z,h as te}from"./c-VG5XIN4T.js";import{m as be,n as De}from"./c-HA6INT6J.js";import{a as Te,b as Le,l as Ce,m as Ae}from"./c-ICMAOOGK.js";function tt(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 nt(s,e){let t=new WeakMap;if(!s||!e||typeof e!="object"||Array.isArray(e))return t;let i=e["~"],n=typeof i=="string"?i.split(",").map(Number):null,r=n&&typeof e["^"]=="string"?e["^"].split(","):null,l=d=>Number.isInteger(d)&&d>=0,o=0,a=!1,h=d=>{let _=d;for(;_>0;){let g=n[o++];if(o>n.length||!l(g))return!1;_+=g-1}return!0},c=(d,_)=>{if(a)return;if(n){let f=o++,u=n[f];if(f>=n.length||!l(u)){a=!0;return}let S=!r||r[f]===d.tagName.toLowerCase();if(!S||u!==d.children.length){let w=S&&e[_];typeof w=="string"&&w&&t.set(d,w),h(u)||(a=!0);return}}let g=e[_];typeof g=="string"&&g&&t.set(d,g);let E=d.children;for(let f=0;f<E.length;f++)c(E[f],_===""?String(f):`${_}.${f}`)};return c(s,""),t}function yt(s){return e=>{for(let t of s){let i=t(e);if(typeof i=="string"&&i!=="")return i}return null}}var Pt=yt([s=>s.getAttribute("data-id"),s=>s.getAttribute("id")]);var mt=/^page(\.[0-9]+)?$/,it=s=>[...s.querySelectorAll('script[merge][clay~="live"]')].filter(e=>mt.test(e.getAttribute("merge")));function st(s,e,t){if(!s.html.includes("data-page"))return s;let i=u=>new DOMParser().parseFromString(u,"text/html"),n=i(s.html),r=n.querySelector("article[data-page]");if(!r)return s;let l=i(e),o=l.querySelector("article[data-page]");if(!o)return null;let a=nt(n.documentElement,s.identityMap),h=(u,S)=>{let w=n.importNode(S,!0),b=a.get(u);return b&&a.set(w,b),u.replaceWith(w),w},c=h(r,o),d=new Map(it(n).map(u=>[u.getAttribute("merge"),u]));for(let u of it(l)){let S=u.getAttribute("merge"),w=d.get(S);w?h(w,u):c.before(n.importNode(u,!0)),d.delete(S)}for(let u of d.values())u.remove();let _=n.querySelector("head > title"),g=l.querySelector("head > title");_&&g?h(_,g):g?n.head.append(n.importNode(g,!0)):_?.remove();let E=n.documentElement,f=t.exportMap(E,u=>{let S=a.get(u);return S?(t.adopt(u,S),u):null});return{...s,html:T(E),identityMap:f}}var vt={"merge-tokens":"tokens","merge-max":"max"};function rt(s,e){if(!e.startsWith("data-")||e==="data-id"||!s?.closest)return null;for(let[t,i]of Object.entries(vt)){let n=s.closest(`[${t}]`);if(n&&n.getAttribute(t).split(/\s+/).includes(e))return i}return null}var m=null,lt=null,B=new Map;function J(){return lt??=Promise.all([import("./c-CAWNFER6.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}),lt}var ot=()=>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,fe=null;function H(){return fe??=new Promise(s=>setTimeout(s,0)).then(()=>import("./c-FNVQAACK.js")).then(s=>y=s).catch(s=>{throw fe=null,s}),fe}var ye=null,pe=null;function Et(){return pe??=import("./c-FTWGYI5E.js").then(s=>ye=s.presence).catch(s=>{throw pe=null,s}),pe}var ct=ee().phase==="entering";$&&!ct&&H().catch(()=>{});$&&J().catch(()=>{});var L=null,_e=null,K=[];function dt(s){L.presence.update(s),L.editingMarker.update(s)}function wt(){return _e??=Promise.all([import("./c-ZJLU56DV.js"),import("./c-JUE7B4OX.js")]).then(([s,e])=>{L={presence:s.presence,editingMarker:e.editingMarker};let t=K;K=[];for(let i of t)dt(i);return L}).catch(s=>{throw _e=null,s}),_e}function kt(s){if(L){dt(s);return}K.push(s),wt().catch(()=>{})}var at=Object.freeze({bytes:null,etag:null,seq:null}),xt=()=>({msg:"Not in edit mode",msgType:"skipped",code:null,etag:null}),ut=["[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,Te].join(","),ft='[clay~="freeze"], [freeze], [save-freeze]';function V(s){for(let e of s.querySelectorAll(ft))e.replaceChildren();return z()&&He(s),s}function ht(s){if(s==null)return s;let e=typeof s=="string"?new DOMParser().parseFromString(s,"text/html"):s;return ne(e),V(e),e}var bt=[Ae,'[clay~="no-watch"]',"[no-watch]","[mutations-ignore]"].join(","),Dt=(s,e,t)=>be(s,e,t)||Le.test(e.toLowerCase()),pt=s=>s.getAttribute("data-id")||s.getAttribute("id")||null;function It(s){let e=new Map,t=n=>{if(n.matches(ut))return;let r=pt(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 Tt=s=>e=>{let t=pt(e);if(!t)return null;let i=e.getRootNode(),n=s.get(i);return n||s.set(i,n=It(i)),n.get(t)===1?t:null},ge=s=>!!s&&typeof s=="object"&&!Array.isArray(s);function Lt(s){return typeof s!="string"||s===""?null:new DOMParser().parseFromString(s,"text/html").documentElement?.getAttribute("documentetag")||null}function Ct(s,e){e!=="live"||!s||!y||(y.enableContentEditable(s),y.enableOnClick(s),y.enableAdminInputs(s),y.enableAdminResources(s))}function At(){let{forComparison:s,forDirty:e}=Pe({flushUndo:!1});return[s,e]}var Ft=1024*1024;function Rt(s,e,t,i,n){let r={sender:t,identityMap:i,...n?{etag:n}:{}};return e.length<Ft?JSON.stringify({[s.snapshotKey]:e,...r}):new Blob([`{${JSON.stringify(s.snapshotKey)}:`,JSON.stringify(e),`,${JSON.stringify(r).slice(1)}`],{type:"application/json"})}var me=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._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.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=at,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=tt(this.clientId),this.onConnect=null,this.onDisconnect=null,this.onUpdate=null,this.onError=null,this.onNotification=null}get unresolvedConflicts(){return I.list().filter(e=>e.kind!=="apply-incomplete")}_log(e,t=null){if(!this.debug)return;let i=`[LiveSync ${new Date().toISOString()}]`;t!==null?console.log(i,e,t):console.log(i,e)}generateClientId(){return Math.random().toString(36).slice(2,11)+Date.now().toString(36)}generateResumeId(){try{let e=new Uint8Array(16);return(globalThis.crypto||window.crypto).getRandomValues(e),Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}catch{return Math.random().toString(36).slice(2)+Date.now().toString(36)}}_seedBases(){if(x())return;let e=P({flushUndo:!1});this._setPeerBase(T(e),this.identity.exportMap(e,D),this._ticket()),this._setDiskBase(W({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=ee().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}):at,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"&&J().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)&&!qe()&&!x()&&this._saveTicket===0&&this._morphTicket===a){if(c!==null&&this._applyGen===o&&this._saveEpoch===h&&this.lastHtml===c){let g=P({flushUndo:!1});this._setPeerBase(T(g),this.identity.exportMap(g,D),this._ticket())}_&&this._diskBaseTicket===d&&this._setDiskBase(W({emitForSync:!1}).forSave,this._ticket())}},document.addEventListener("clay:baseline-settled",this._settledHandler,{once:!0})}this._ready=Promise.all([this.lane==="live"?H():null,this._resolveProfile()]).then(()=>{this.isDestroyed||this._startGen!==l||this.connect()}),this.lane==="live"&&(this.listenForSnapshots(),Et().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===ie()&&(y?.conflictResolvedBySync(a),this._saveAfterMerge(x(),!1))})},document.addEventListener("clay:save-conflict",this._saveConflictHandler))}cleanup(){if(this.sse&&(this.sse.close(),this.sse=null),he(),K=[],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._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=et().then(e=>(this._sharedData=e.sharedData,this._sharedSync=e.sharedSync,this._liveData=e.liveData,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&&Ue({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||ue.legacy).streamPath(window.location.href,this.lane,this.resumeId,this.clientId);this.sse=new Xe(new URL(t,window.location.origin).href,{shared:this._sharedSync,sharedData:this._sharedData,documentURL:window.location.href,lane:this.lane,clientId:this.clientId,keepAliveWhenHidden:this._liveData&&this.lane==="live",startupCheck:!!Ie}),this._acquireEmptySaved&&(this._acquireEmptySaved=!1,this._fetchServedDocument(void 0,{repair:!0})),this.sse.onopen=()=>{console.log("[LiveSync] Connected"),this._editing&&this._editing.reconnected(),ye&&ye.reconnect(),this.onConnect&&this.onConnect()},this.sse.addEventListener("open",()=>Qe({clientId:this.clientId,lane:this.lane})),this.sse.addEventListener("error",()=>he());for(let i of Ke)this.sse.addEventListener(i,n=>{let r;try{r=JSON.parse(n.data)}catch{return}Ze(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}kt(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&&Ge()){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}),M(h);return}if(h&&l===this.lastHtml){this._log(`Taking the stamp from a peer save of content already applied (seq=${r})`),M(h),y&&y.isSaveConflicted()&&(y.conflictResolvedBySync(h),this._saveAfterMerge(x(),!1));return}this._log(`Received update from: ${o} (my clientId: ${this.clientId}, seq=${r})`),this.applyUpdate(l,r,a,h,n.by),this.onUpdate&&this.onUpdate({html:l,sender:o,seq:r,identityMap:a,etag:h})},this.sse.onerror=()=>{this.sse.readyState===EventSource.CONNECTING?console.log("[LiveSync] Reconnecting..."):this.sse.readyState===EventSource.CLOSED&&(console.log("[LiveSync] Connection closed"),this.onError&&this.onError(new Error("Connection closed"))),this.onDisconnect&&this.onDisconnect()}}listenForSnapshots(){this._snapshotHandler=e=>{if(!e.detail||e.detail.forSave!==!0)return;this._saveTicket=this._ticket();let{documentElement:t}=e.detail;if(!t)return;this._log("snapshot-ready received, preparing to send");let i=this.identity.exportMap(t,D);this._savedSnapshot?.abort?.abort();let n={html:null,steps:null,copy:null,abort:null,identityMap:i,ticket:this._saveTicket,captureId:e.detail.captureId??null};if(e.detail.sliced){n.copy=Be(t),n.abort=new AbortController;let{signal:r}=n.abort;Promise.all([import("./c-MEWUGR4D.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=ie(),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=st(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=Ht(e)??t,a=typeof o=="string"?je(o):0;l={...l,html:qt(ze(l.html,Math.max(We(),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||ue.legacy;fetch(new URL(l.relayPath,window.location.origin).href,{method:"POST",headers:{"Content-Type":"application/json",[l.documentHeader]:window.location.href,[$e]:String(1)},body:Rt(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,Oe("presence-editing")),()=>!1).then(i=>{if(!(!i||this.isDestroyed||this._startGen!==t||this._editing))return H().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=Lt(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===se()){(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-Y33LUUIQ.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(!R()){this._morphInFlight=!0;try{await Y()}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===se())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){return typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(e):setTimeout(e,16)}_cancelFrame(e){if(typeof window<"u"&&typeof window.cancelAnimationFrame=="function"){window.cancelAnimationFrame(e);return}clearTimeout(e)}async _mergeIncoming(e,t,{base:i,baseIdentityMap:n=null,captureLocal:r,synthetic:l,source:o="peer",seq:a=null,etag:h=null,extra:c={}}){R()||await Y();let{beginApply:d,completeApply:_,failApply:g,beginLineageCapture:E}=ot()||await J(),f,u=p=>{f=E(I.list());try{let v=R().HyperMorph.mergeDocument({...p,lineage:f.lineage});return f.returned(),v}catch(v){throw f.invalidate(I.list()),f.finish(I.list()),v}},S=this.identity,w=De,b=Tt(new WeakMap),N=p=>ge(p)?{first:b,map:p,then:b}:b,O=l?p=>b(p)||S.idOf(D(p)||p)||null:b,C=e,Se=new Map;if(ge(t)){C=new DOMParser().parseFromString(e,"text/html"),ne(C);let p=R().HyperMorph.importMap(C.documentElement,t);for(let v of C.querySelectorAll("[data-id], [id]")){let k=b(v),xe=k&&p.get(v);xe&&Se.set(k,xe)}}C=ht(C);let Q={live:document,remote:C,ignore:p=>p.matches(ut),opaque:p=>p.matches(ft)||z()&&Re(p),remoteWins:p=>p.matches(bt),ignoreAttribute:(p,v,k)=>Dt(p,v,k)||z()&&Fe(k||p,v),attributeMerge:rt,protectFocusedValue:!0,restoreFocus:document.activeElement?.localName!=="clay-editor-ui",keepLiveOnly:o==="peer",scripts:{mergeTags:R().mergeTagRecognizers},hooks:{beforeAttributeUpdated:w},...c},Ee=this.lane==="live"&&x(),we=ae(),G,Z=null,F=null;if(i==null)G=u({...Q,base:null,local:{root:V(r()),toLive:D},identity:{local:O,remote:N(t)}});else if(Ee){let p=r(),v=p.cloneNode(!0);Z=V(p),F=d({source:o,seq:a,etag:h,root:Z,recoveryRoot:v,domain:o==="disk"?"save":"sync"});try{G=u({...Q,base:ht(i),local:{root:Z,toLive:D},identity:{base:N(n),local:O,remote:N(t)}})}catch(k){throw g(F,k),k}}else{let p=V(r()),v=p.ownerDocument;v.documentElement!==p&&v.replaceChild(p,v.documentElement),G=u({...Q,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 A;try{A=await G}catch(p){f.invalidate(I.list());try{F&&g(F,p,{ticket:U})}finally{f.finish(I.list())}throw p}let _t=ae().gen!==we.gen,ke;try{f.prepareComplete(A,I.list()),ke=F?_(F,A.conflicts,{ticket:U}):[]}finally{f.finish(I.list())}this.lane==="live"&&A.localDiverged?Ye():Ee&&!A.localDiverged&&Je(we);let gt=new Set(ge(t)?Object.values(t):[]);for(let[p,v]of A.identities){let k=gt.has(v)?v:Se.get(v);k&&S.adopt(p,k)}return{report:A,ticket:U,typedDuringWait:_t,conflictIds:ke}}_saveAfterMerge(e,t){(e||t)&&Ve()&&(y?y.savePageThrottled():xt())}async _doApplyUpdate(e,t,i,n,r=null){if(ce(e)){await de();return}this.lane==="live"&&!y&&await H(),this._log("applyUpdate - pausing mutations and morphing"),this.isPaused=!0;let l=window.scrollX,o=window.scrollY;q.pause(),le();let a=!1,h=!1,c=!1;try{if(this.lane==="live"&&x()&&this.lastHtml===null){console.log("[LiveSync] Holding incoming update: unsaved local edits and no baseline to merge against"),this._setHeld("live",!0,null);let f=this._saveEpoch,u=this.lastSeenSeq;clearTimeout(this._holdRetryPeer),this._holdRetryPeer=setTimeout(()=>{this._holdRetryPeer=null,!(this.isDestroyed||this._pendingHtml!=null)&&this._saveEpoch===f&&this.lastSeenSeq===u&&(this._pendingHtml=e,this._pendingSeq=t,this._pendingIdentityMap=i,this._pendingBy=r,this._scheduleNextFrame())},3e3);return}this._setHeld("live",!1);let{report:d,ticket:_,typedDuringWait:g,conflictIds:E}=await this._mergeIncoming(e,i,{base:this.lastHtml,baseIdentityMap:this._lastIdentityMap,captureLocal:()=>P({flushUndo:!1}),synthetic:!0,source:"peer",seq:t,etag:n});if(a=d.localDiverged,h=g,te(),window.scrollTo(l,o),this._setPeerBase(e,i,_),this._applyGen++,this._acceptedSaveTicket>_||(typeof n=="string"&&n?(M(n),c=!0):re()),this.lane==="live"&&!a&&!x()){let{forSave:f,forComparison:u,forDirty:S}=W({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(),oe(),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(ce(e)){await de();return}this.lane==="live"&&!y&&await H();let l=this._diskBase;this._log(`applyExternal - external disk change (seq=${t})`),this.isPaused=!0;let o=window.scrollX,a=window.scrollY;q.pause(),le();let h=!1,c=!1,d=!1;try{if(this.lane==="live"&&x()&&this._diskBase===null){if(console.log("[LiveSync] Holding external change: unsaved local edits and no baseline to merge against"),this._setHeld("external",!0,null),r?.startup||r?.versionCheck){clearTimeout(this._holdRetryExt),this._holdRetryExt=setTimeout(()=>{if(this._holdRetryExt=null,this.isDestroyed)return;let S=typeof t=="number"?Math.max(t,this._lastExternalSeq):t;this._retryStartup(0,r,S)},3e3);return}let u=this._saveEpoch;clearTimeout(this._holdRetryExt),this._holdRetryExt=setTimeout(()=>{this._holdRetryExt=null,!(this.isDestroyed||this._pendingExternal!=null)&&(this._pendingExternal={html:e,seq:t,saveEpoch:u,etag:i,by:n},this._scheduleNextFrame())},3e3);return}this._setHeld("external",!1);let{report:_,ticket:g,typedDuringWait:E,conflictIds:f}=await this._mergeIncoming(e,null,{base:this._diskBase,captureLocal:()=>Me().saveClone,synthetic:!1,source:"disk",seq:t,etag:i,extra:{beforeApply:u=>Ct(u.documentElement,this.lane)}});if(h=_.localDiverged,c=E,te(),this._setDiskBase(e,g),window.scrollTo(o,a),this._acceptedSaveTicket>g||(typeof i=="string"&&i?(M(i),d=!0):re()),this.lane==="live"&&!h&&!x()){y.setLastSavedBaselines(...At()),y.setUnsavedChanges(!1);let u=P({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(),oe(),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 H().then(e=>e.syncParticipant(this))}},X=null;Ne((s,e)=>{X=typeof s=="string"?{html:s,captureId:e?.captureId??null}:null});var Ht=s=>X&&(X.captureId??null)===(s??null)?X.html:null;function qt(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 ve=new me;typeof window<"u"&&!ct&&(document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>ve.start()):ve.start());var _n=(s,e,t)=>Y().then(({morph:i})=>i(s,e,t));var gn=ve;export{I as a,ut as b,bt as c,me as d,ve as e,_n as f,gn as g};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{b as x}from"./c-
|
|
1
|
+
import{b as x}from"./c-QY7F6EN6.js";import{a as w}from"./c-5B4YBZXC.js";import"./c-I2SCCUEW.js";import"./c-XGH4GS2T.js";import"./c-3O7OBDCM.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-N7JPUPGC.js";import"./c-HA6INT6J.js";import"./c-ICMAOOGK.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";var S=`.clay-upload {
|
|
2
2
|
display: flex;
|
|
3
3
|
flex-wrap: wrap;
|
|
4
4
|
align-items: center;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b}from"./c-
|
|
1
|
+
import{a,b}from"./c-QY7F6EN6.js";import"./c-ICMAOOGK.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";export{a as HOST_CSS,b as mountEditorUI};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as b,e as m}from"./c-
|
|
1
|
+
import{d as b,e as m}from"./c-FDAXZ2PM.js";import"./c-L3F5ZLIV.js";import"./c-IW6GGOU2.js";import"./c-HAWFNBYG.js";import{e as h,f as d,g as l,h as w}from"./c-EXKHPOVC.js";import"./c-L5VFATT6.js";import"./c-7K4SCQB7.js";import"./c-WMRJKQ2V.js";import"./c-QIXT3Q7C.js";import"./c-TCCA5BZN.js";import"./c-57XDY6HC.js";import"./c-JHJR5BQX.js";import"./c-TWCXBWS3.js";import"./c-LA2BW7UY.js";import"./c-IJUK2GPW.js";import{c as T}from"./c-BPF2NSPV.js";import{e as v}from"./c-EGTIAL6P.js";import"./c-XQXZAO7N.js";import"./c-S7LK4KUE.js";import"./c-VG5XIN4T.js";import"./c-2YYDMLNZ.js";import"./c-HA6INT6J.js";import"./c-ICMAOOGK.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";v(b);var x=1,y=class extends Error{constructor(a,n){super(n),this.name="PageCheckpointError",this.code=a}},k=(e,a)=>{throw new y(e,a)},t=(e,a)=>({ok:!1,code:e,message:a}),A=/^[0-9a-f]{64}$/,j=/^[0-9a-f]{32}$/,E=e=>!!e&&typeof e=="object"&&!Array.isArray(e);function I(e){return{v:e.v,g:e.g,y:{...e.y??{}}}}function H(e){let a;try{a=JSON.parse(e)}catch{k("invalid-state","The page state is not JSON")}return(!E(a)||a.v!==1)&&k("invalid-state","Expected a version 1 Yjs page value"),{state:I(a),bytes:d(a)}}var S=e=>e==null?"":String(e);async function N({href:e,etag:a,fetch:n=globalThis.fetch,signal:s=null}={}){if(typeof a!="string"||!a)return t("missing-etag","A conditional read needs the accepted ETag");if(typeof e!="string"||!e)return t("no-page-state","This host names no page-state resource");if(typeof n!="function")return t("unavailable","This tab cannot read the page state");let i=globalThis.location?.href??"http://localhost/",p;try{p=new URL(e,i).href}catch{return t("no-page-state","The page-state resource is not a URL")}let c=T(),o;try{o=await n(p,{method:"GET",credentials:c?"omit":"same-origin",headers:{"If-Match":a,"Document-URL":globalThis.location?.href??i},cache:"no-store",redirect:"manual",signal:s})}catch{return t("unavailable","The page-state request did not complete")}if(!o||typeof o.status!="number")return t("unavailable","The page-state request did not answer");if(o.status===412)return t("etag-mismatch","Another version of this document is stored");if(o.status===428)return t("etag-required","The host needs a condition this read cannot send");if(o.status===404)return t("no-page-state","This host keeps no page state");if(!o.ok)return t("unavailable",`The host answered ${o.status}`);let r;try{r=JSON.parse(await o.text())}catch{return t("invalid-state","The page-state answer is not JSON")}return!E(r)||r.version!==x?t("unsupported-version","Unknown page-state version"):typeof r.tag!="string"||!r.tag?t("invalid-state","The page-state answer carries no page tag"):typeof r.stateHash!="string"||!A.test(r.stateHash)?t("invalid-state","The page-state answer carries no state digest"):typeof r.generation!="string"||!j.test(r.generation)?t("invalid-state","The page-state answer carries no generation"):typeof r.etag!="string"||!r.etag?t("invalid-state","The page-state answer carries no ETag"):Object.hasOwn(r,"documentId")?{ok:!0,version:r.version,documentId:r.documentId,generation:r.generation,etag:r.etag,stateHash:r.stateHash,tag:r.tag}:t("invalid-state","The page-state answer carries no document identity")}async function _(e,{accepted:a,article:n,etag:s}={}){if(!e||e.ok!==!0)return t(e?.code??"unavailable",e?.message??"The page state was not read");let i=a?.authority;if(!(i?.scope==="path"&&e.documentId==null)&&S(e.documentId)!==S(i?.documentId))return t("foreign-document","The page state belongs to another document");if(typeof a?.lineage?.generation!="string"||e.generation!==a.lineage.generation)return t("foreign-generation","The page state belongs to another generation");if(e.etag!==s)return t("etag-mismatch","The page state belongs to another version of this document");let c,o;try{({state:o,bytes:c}=H(e.tag))}catch(u){return t(u?.code??"invalid-state",u?.message??"The page state does not decode")}if(await h(c)!==e.stateHash)return t("state-digest-mismatch","The page state is not the one the host hashed");if(typeof n!="string")return t("missing-article","A proof names the final outgoing article");let r;try{r=m(o)}catch(u){return t("invalid-state",u?.message??"The page state does not project")}return r!==n?t("article-mismatch","The page state does not project to the accepted article"):{ok:!0,state:o,receipt:{file:e.etag,pageState:e.stateHash}}}async function O(e,a){let n=(a||[]).map(({id:s,revision:i})=>({id:s,revision:i}));try{return{ok:!0,proof:e,covered:await w(e,n)}}catch(s){return t(s?.code??"invalid-proof",s?.message??"The proof does not validate")}}async function R({capture:e,records:a=[],accepted:n,article:s,state:i=null,etag:p=null}={}){if(!i)return t("no-capture-state","No page state was pinned to this capture");if(typeof p!="string"||!p)return t("missing-etag","An accepted save with no ETag proves no stored pair");if(typeof s!="string")return t("missing-article","The accepted bytes hold no article");let c,o;try{c=m(i),o=d(i)}catch(u){return t(u?.code??"invalid-state",u?.message??"The pinned page state does not decode")}if(c!==s)return t("article-mismatch","The pinned page state does not project to the accepted article");let r;try{r=await l({capture:e,records:a,accepted:n,article:s,state:i,receipt:{file:p,pageState:await h(o)}})}catch(u){return t(u?.code??"invalid-proof",u?.message??"The proof could not be built")}return O(r,a)}async function B({read:e,capture:a,records:n=[],accepted:s,article:i,etag:p=null}={}){let c=await _(e,{accepted:s,article:i,etag:p});if(!c.ok)return c;let o;try{o=await l({capture:a,records:n,accepted:s,article:i,state:c.state,receipt:c.receipt})}catch(r){return t(r?.code??"invalid-proof",r?.message??"The proof could not be built")}return O(o,n)}async function G({channel:e,records:a=[],capture:n,accepted:s,article:i,state:p=null,etag:c=null,href:o=null,read:r=N,fetch:u}={}){if(!e||typeof e.checkpoint!="function")return{ok:!1,code:"no-channel",retired:[],proof:null};let f=await R({capture:n,records:a,accepted:s,article:i,state:p,etag:c});if(!f.ok){let P=await r({href:o,etag:c,fetch:u});f=await B({read:P,capture:n,records:a,accepted:s,article:i,etag:c})}if(!f.ok)return{ok:!1,code:f.code,retired:[],proof:null};let g=await e.checkpoint({records:f.covered,proof:f.proof});return!g||g.ok!==!0?{ok:!1,code:g?.code??"checkpoint-failed",retired:[],proof:f.proof}:{ok:!0,retired:g.retired??[],proof:f.proof}}export{x as PAGE_STATE_VERSION,y as PageCheckpointError,R as captureProof,G as checkpointAccepted,N as readPageState,B as refetchedProof,_ as verifyPageState};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as X,f as G,h as J,i as Q,j as P,k as U}from"./c-QIKT6SKM.js";import{a as C,f as L}from"./c-
|
|
1
|
+
import{e as X,f as G,h as J,i as Q,j as P,k as U}from"./c-QIKT6SKM.js";import{a as C,f as L}from"./c-RQRMPZXD.js";import"./c-WN3MXOLT.js";import"./c-L5VFATT6.js";import{a as O,b as N,k as z,l as K,m as j,n as V,v as T}from"./c-WMRJKQ2V.js";import{o as w}from"./c-44B5ODN7.js";import{b as k,d as H}from"./c-QIXT3Q7C.js";import{b as W}from"./c-RS77ODLY.js";import"./c-7SWMYKAI.js";import"./c-UGHH4MB3.js";import"./c-LA2BW7UY.js";import{d as q}from"./c-XGH4GS2T.js";import"./c-IJUK2GPW.js";import"./c-3O7OBDCM.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-N7JPUPGC.js";import"./c-VG5XIN4T.js";import"./c-2YYDMLNZ.js";import"./c-HA6INT6J.js";import"./c-ICMAOOGK.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";var ie=128,D=r=>r.depth?r.node(1).attrs.id:null,Z=r=>!!r.depth&&r.node(1).type.name==="table",ce=(r,t,n,e,o)=>O(K(z(r.flow,J(t,n.holes,e,n.visible),o)));function te({pd:r,w:t,doc:n},e){if(!r||!t||!n||!e)return null;if(e instanceof k.TextSelection){let o=e.$anchor,s=e.$head;if(Z(o)||Z(s)){let c=P(n,o.pos),u=P(n,s.pos);return!c||!u||c.table!==u.table||c.row!==u.row||c.col!==u.col?null:{kind:"cell",block:c.table,row:c.row,col:c.col}}let a=Math.min(e.from,e.to),l=c=>{let u=D(c);return u===null?null:{block:u,rel:ce(r,n,t,c.pos,e.empty||c.pos===a?0:-1)}},i=l(o),d=l(s);return i&&d?{kind:"text",anchor:i,head:d}:null}if(e instanceof w||e instanceof k.NodeSelection){let o=[];if(e instanceof w){let{lo:s,hi:a}=e.span();n.forEach((l,i,d)=>{d>=s&&d<=a&&o.push(l.attrs.id)})}else{let s=n.nodeAt(e.from);s&&o.push(s.attrs.id)}if(!o.length)return null;if(o.length>ie){let s=D(e.$from);return s?{kind:"blocks",ids:[s]}:null}return{kind:"blocks",ids:o}}return null}var ue=(r,t)=>{if(!t||typeof t!="object"||typeof t.block!="string"||!t.block||typeof t.rel!="string"||!t.rel)return null;let n;try{n=j(N(t.rel))}catch{return null}let e;try{e=V(n,r.ydoc)}catch{return null}return!e||e.type!==r.flow?null:e.index},fe=(r,t)=>{let n=0;for(let e=r.flow._start;e;e=e.right){let o=n+e.length;if(t<o)return!e.deleted;n=o}return!1},pe=(r,t)=>{for(let n=r.flow._start;n;n=n.right)if(!n.deleted&&n.content instanceof T&&n.content.embed?.b===t)return!0;return!1},de=(r,t)=>{let n=0,e=null,o=0;for(let s=r.flow._start;s;s=s.right)if(s.content instanceof T&&s.content.embed?.b!==void 0&&(e=s.content.embed.b,o=n+s.length),n+=s.length,n>t&&e!==null)return{id:e,offset:t-o};return e===null?null:{id:e,offset:t-o}},me=(r,t,n)=>{let e=null;return r.forEach((o,s)=>{e===null&&o.attrs.id===t&&o.isTextblock&&(e=s+1+Math.min(Math.max(n,0),o.content.size))}),e},ee=({pd:r,w:t,doc:n},e)=>{let o=ue(r,e);if(o===null)return null;let s=Q(n,t.holes,t.tokens,o,t.visible);if(D(n.resolve(s))===e.block)return s;let a=de(r,o);if(a&&a.id===e.block){let l=me(n,e.block,a.offset);if(l!==null)return l}return pe(r,e.block)||!fe(r,o)||t.holes.some(l=>o>=G(t.holes,l.at)&&o<X(t.holes,l.at))?null:n.resolve(s).parent.inlineContent?s:null};function ne({pd:r,w:t,doc:n},e){if(!r||!t||!n||!e||typeof e!="object")return null;if(e.kind==="text"){let o=ee({pd:r,w:t,doc:n},e.anchor),s=ee({pd:r,w:t,doc:n},e.head);return o===null||s===null?null:{kind:"text",from:Math.min(o,s),to:Math.max(o,s)}}if(e.kind==="cell"){let o=U(n,{table:e.block,row:e.row,col:e.col,offset:0});return o?{kind:"cell",from:o.from,to:o.to,block:o.block,row:o.row,col:o.col}:null}if(e.kind==="blocks"){let o=[],s=[];for(let a of Array.isArray(e.ids)?e.ids:[])n.forEach((l,i)=>{l.attrs.id!==a||o.includes(a)||(o.push(a),s.push({from:i,to:i+l.nodeSize}))});return s.length?{kind:"blocks",ids:o,ranges:s}:null}return null}var{Plugin:ge,PluginKey:he}=k,{Decoration:b,DecorationSet:x}=H,y=new he("page-awareness"),oe="page-awareness-style",be=`
|
|
2
2
|
.page-remote-selection { background-color: color-mix(in srgb, var(--page-remote-color, currentColor) 22%, transparent); }
|
|
3
3
|
.page-remote-caret { position: relative; display: inline-block; width: 0; height: 1.1em; vertical-align: text-bottom; }
|
|
4
4
|
.page-remote-caret::before { content: ""; position: absolute; inset-inline-start: -1px; top: 0; bottom: 0; width: 2px; background: var(--page-remote-color, currentColor); }
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./c-SFKI6OLM.js";import"./c-Q3XOWZEV.js";import"./c-VHNSBD2M.js";export{a as stripCopyContent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c,d,e,f}from"./c-
|
|
1
|
+
import{a,b,c,d,e,f}from"./c-LV5MABYD.js";import"./c-N326R2JD.js";import"./c-I2SCCUEW.js";import"./c-3O7OBDCM.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-N7JPUPGC.js";import"./c-HA6INT6J.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";export{c as beginApply,d as completeApply,f as conflicts,e as failApply,a as loadEdit,b as registerContext};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as m}from"./c-PZ4XEPUP.js";import{a as c}from"./c-SFKI6OLM.js";import{a as p,b as y}from"./c-RHMPKZZ7.js";import{K as f,L as d}from"./c-EGTIAL6P.js";function g(e=new Date){let t=r=>String(r).padStart(2,"0");return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}-${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`}function h(e,t){let n=`<script type="application/json" id="clay-lost-edits" clay="no-save">${JSON.stringify(t).replace(/</g,"\\u003c")}<\/script>`,s=e.lastIndexOf("</body>");return s>=0?e.slice(0,s)+n+e.slice(s):e+n}function j(e,{refused:t=!1}={}){let r=window.clay?.conflicts||null,n=[],s=new Set;for(let o of e){let a=r?.recoveryOf(o.id);a&&!s.has(a.id)&&(s.add(a.id),n.push(a))}n.sort((o,a)=>(o.ticket||0)-(a.ticket||0));let u=o=>c(f(o.recoveryRoot??o.root,{prepared:o.domain==="save"})),i,l;t||!n.length?(i=c(d()),l=n):(i=u(n[n.length-1]),l=n.slice(0,-1));let w=e.map(o=>{if(o.kind==="apply-incomplete")return{id:o.id,kind:"apply-incomplete",name:"Sync update that did not finish",error:o.error??null};let{id:a,name:$,kind:S,yours:O,now:b,sentence:k}=m(o);return{id:a,name:$,kind:S,yours:O,now:b,sentence:k}}),v={format:"clay-lost-edits",version:1,savedAt:new Date().toISOString(),page:location.href,refused:!!t,edits:w,earlierPages:l.map(o=>({applyId:o.id,source:o.source,html:u(o)}))};return{html:h(i,v),name:`${p()}-${t?"my-version":"my-copy"}-${g()}.html`}}async function I({html:e=null,edits:t=[]}={}){try{let r=c(typeof e=="string"?e:d()),n={format:"clay-lost-edits",version:1,savedAt:new Date().toISOString(),page:location.href,refused:!1,edits:Array.isArray(t)?t:[],earlierPages:[]};return await y({html:h(r,n),name:`${p()}-my-copy-${g()}.html`})}catch(r){return console.error("clayjs: could not build the download",r),!1}}async function C(e,{refused:t=!1}={}){try{let{html:r,name:n}=j(e,{refused:t});return await y({html:r,name:n})}catch(r){return console.error("clayjs: could not build the download",r),!1}}export{I as a,C as b};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as G}from"./c-CAS3NND4.js";import{b as J}from"./c-3G2DGZUP.js";import{o as z,p as _}from"./c-B7J4K2AE.js";import"./c-ATKAOH23.js";import"./c-EK63G3CG.js";import{a as F}from"./c-NQJRVJ56.js";import"./c-XGH4GS2T.js";import"./c-IJUK2GPW.js";import"./c-3O7OBDCM.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-N7JPUPGC.js";import"./c-7MG5RU63.js";import"./c-XQXZAO7N.js";import"./c-S7LK4KUE.js";import"./c-VG5XIN4T.js";import"./c-2YYDMLNZ.js";import"./c-HA6INT6J.js";import"./c-DCFSEJZG.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";var Le=Object.defineProperty,je=(e,t)=>{for(var r in t)Le(e,r,{get:t[r],enumerable:!0})},Ce=["textContent","innerText","innerHTML","outerHTML","value","checked","selected","disabled","readOnly","type","tagName","nodeName","nodeType","nodeValue","childElementCount","id","className","classList","baseURI","offsetWidth","offsetHeight","clientWidth","clientHeight","scrollWidth","scrollHeight","dataset","currentSrc","duration","paused","title","documentURI","contentType"],Me=new Set(Ce),Ue=new Set(["textContent","innerText","innerHTML","value","checked","selected","disabled","readOnly","type","id","className","title"]),Ie=new Set(["tagName","nodeName","nodeType","nodeValue","childElementCount","classList","baseURI","documentURI","contentType","offsetWidth","offsetHeight","clientWidth","clientHeight","scrollWidth","scrollHeight","currentSrc","duration","paused","dataset"]),Y=new Set(["checked","selected","disabled","readOnly","paused"]);function Pe(e,t){return t==null?Y.has(e)?!1:"":Y.has(e)?t==="false"?!1:!!t:t}var De={};je(De,{EmptyListInsert:()=>R,MAX_RULE_DEPTH:()=>C,MaxRuleDepthExceeded:()=>V,NoRulesTag:()=>We,RuleTargetReadOnly:()=>fe,RulesParseError:()=>se,ShapeMismatch:()=>ce,UnknownRulesVersion:()=>ue,WriteNotRoundTripped:()=>He,WriteRefused:()=>Be,WriteRejected:()=>Ve});var se=class extends Error{constructor(e,t){super(e),this.name="RulesParseError",this.cause=t}},ue=class extends Error{constructor(e){super(`unknown rules version: ${e}. Library supports "1".`),this.name="UnknownRulesVersion",this.version=e}},C=20,V=class extends Error{constructor(e){super(`rule depth exceeded ${C} at path: ${e.join(".")}`),this.name="MaxRuleDepthExceeded",this.path=e}},ce=class extends Error{constructor(e){super(`shape mismatch: ${e.length} field(s) failed validation`),this.name="ShapeMismatch",this.mismatches=e}},R=class extends Error{constructor(e,t){super(t?`cannot add items to empty list at "${e.join(".")}" \u2014 ${t}`:`cannot add items to empty list at "${e.join(".")}" \u2014 no sibling to clone as template. Seed the list with a hidden item first.`),this.name="EmptyListInsert",this.path=e}},fe=class extends Error{constructor(e){super(`cannot write to read-only DOM property "${e}"`),this.name="RuleTargetReadOnly",this.target=e}},Be=class extends Error{constructor(e){super(`write refused: ${e.length} write(s) broke the content-only policy`),this.name="WriteRefused",this.refusals=e}};function qe(e){return e.reduce((t,r)=>typeof r=="number"?`${t}[${r}]`:t?`${t}.${r}`:String(r),"")||"(root)"}var He=class extends Error{constructor(e){super(`write did not round-trip at "${qe(e)}"`),this.name="WriteNotRoundTripped",this.path=e}},We=class extends Error{constructor(e){super(`no <script data-rules-name~="${e}"> rules tag in this document`),this.name="NoRulesTag",this.token=e}},Ve=class extends Error{constructor(e,t){super(`write rejected: ${e.length} unknown key(s), ${t.length} rule(s) with no matching element`),this.name="WriteRejected",this.unknownKeys=e,this.unmatched=t}};function de(e){let t=0,r=null,l=-1;for(let n=0;n<e.length;n++){let o=e[n];o==="\\"?n++:r?o===r&&(r=null):o==='"'||o==="'"?r=o:o==="["||o==="("?t++:o==="]"||o===")"?t>0&&t--:o==="@"&&t===0&&(l=n)}return l}function pe(e){let t=0,r=null,l=-1,n=!1;for(let o=0;o<e.length;o++){let i=e[o];i==="\\"?o++:r?i===r&&(r=null):i==='"'||i==="'"?r=i:i==="["||i==="("?t++:i==="]"||i===")"?t>0&&t--:t===0&&i===">"?l=o:t===0&&i===","&&(n=!0)}return n||l===-1||!Fe(e,l+1)?null:e.slice(0,l).trim()||null}function Fe(e,t){let r=t,l=e.replace(/\s+$/,"").length;for(;r<l&&/\s/.test(e[r]);)r++;let n=0,o=null;for(;r<l;r++){let i=e[r];if(i==="\\")r++;else if(o)i===o&&(o=null);else if(i==='"'||i==="'")o=i;else if(i==="["||i==="(")n++;else if(i==="]"||i===")")n>0&&n--;else if(n===0&&(i==="+"||i==="~"||/\s/.test(i)))return!1}return!0}var ze=/^--[A-Za-z0-9_-]+$/;function he(e){return typeof e=="string"&&ze.test(e)}function me(e){let t=[],r=[],l=null,n=0;for(let o=0;o<e.length;o++){let i=e[o];if(l){i==="\\"?o++:i===l&&(l=null);continue}if(i==="/"&&e[o+1]==="*"){let a=e.indexOf("*/",o+2);o=a===-1?e.length:a+1;continue}i==='"'||i==="'"?l=i:i==="("?r.push(")"):i==="["?r.push("]"):i==="{"?r.push("}"):(i===")"||i==="]"||i==="}")&&r[r.length-1]===i?r.pop():i===";"&&r.length===0&&(t.push(e.slice(n,o)),n=o+1)}return t.push(e.slice(n)),t}function _e(e){let t="",r=null;for(let l=0;l<e.length;l++){let n=e[l];if(r){t+=n,n==="\\"&&l+1<e.length?t+=e[++l]:n===r&&(r=null);continue}if(n==="/"&&e[l+1]==="*"){let o=e.indexOf("*/",l+2);l=o===-1?e.length:o+1,t+=" ";continue}(n==='"'||n==="'")&&(r=n),t+=n}return t}function ye(e){e=_e(e);let t=e.indexOf(":");if(t===-1)return null;let r=e.slice(0,t).trim(),l=e.slice(t+1).trim(),n=/!\s*important\s*$/i.exec(l);return n&&(l=l.slice(0,n.index).trim()),{name:r,value:l,important:!!n}}function ge(e,t){if(e==null)return null;let r=null;for(let l of me(String(e))){let n=ye(l);!n||n.name!==t||(!r||n.important||!r.important)&&(r=n)}return r?r.value:null}function Je(e,t,r){let l=e==null?"":String(e),n=r==null||r==="",o=me(l),i=o.map(ye),a=i.some(f=>f&&f.name===t&&f.important),s=[],u=!1;o.forEach((f,d)=>{let h=i[d];if(!h||h.name!==t){s.push(f);return}if(n||u)return;let m=/^\s*/.exec(f)[0];s.push(`${m}${t}: ${r}${a?" !important":""}`),u=!0});let c=s.join(";");if(!n&&!u){let f=c.trimEnd();c=f===""?`${t}: ${r}`:`${f}${f.endsWith(";")?" ":"; "}${t}: ${r}`}return c.trim()===""?null:c}function Ge(e,t,r,l){let n=e.attr(t,"style");if((ge(n,r)??"")===l)return;let o=Je(n,r,l);o==null?e.removeAttr(t,"style"):e.attr(t,"style",o)}function we(e,t,r,l={}){if(Object.prototype.hasOwnProperty.call(l,"exclude")&&e.semanticExclude===!1)throw new Error("This adapter does not support semantic exclude queries; omit exclude or use the DOM adapter.");return P(e,t,r,{depth:0,path:[]},l)}function P(e,t,r,l,n){if(l.depth>C)throw new V(l.path);if(typeof r=="string")return Ye(e,t,r,l,n);if(Array.isArray(r)){let[o,i]=r,a=e.find(t,o,n);return ve(n,l,a),a.map((s,u)=>P(e,s,i,{depth:l.depth+1,path:[...l.path,u]},n))}if(typeof r=="object"&&r!==null){let o={};for(let[i,a]of Object.entries(r))o[i]=P(e,t,a,{depth:l.depth+1,path:[...l.path,i]},n);return o}return null}function Ye(e,t,r,l,n){if(r.endsWith("[]")){let a=r.slice(0,-2),s=e.find(t,a,n);return ve(n,l,s),s.map(u=>e.text(u))}if(r.startsWith("@"))return X(e,t,r.slice(1));let o=de(r);if(o!==-1){let a=r.slice(0,o),s=r.slice(o+1),u=a?e.find(t,a,n):[t];return u.length===0?null:X(e,u[0],s)}if(r===".")return e.text(t);let i=e.find(t,r,n);return i.length===0?null:e.text(i[0])}function ve(e,t,r){if(typeof e.onRowsRead=="function")try{e.onRowsRead(t.path.slice(),r)}catch(l){console.warn(`[hyper-html-api] onRowsRead threw at "${t.path.join(".")||"(root)"}"`,l)}}function X(e,t,r){if(he(r))return ge(e.attr(t,"style"),r);if(Me.has(r)){let n=e.prop(t,r);return n==null?null:String(n)}return e.attr(t,r)??null}function Xe(e,t,r,l){let n=e.length,o=t.length,i=new Array(n).fill(-1);if(l){let p=new Set;for(let y=0;y<n;y++){let g=l[y];!(g>=0&&g<o)||p.has(g)||(i[y]=g,p.add(g))}}if(n===0||o===0)return i;let a=e.map(p=>K(p,r)),s=t.map(p=>K(p,r)),u=new Array(o).fill(!1);for(let p of i)p>=0&&(u[p]=!0);let c=new Map;s.forEach((p,y)=>{u[y]||c.set(p,c.has(p)?-1:y)});let f=new Map;a.forEach((p,y)=>{i[y]>=0||f.set(p,(f.get(p)||0)+1)}),a.forEach((p,y)=>{if(i[y]>=0||f.get(p)!==1)return;let g=c.get(p);g===void 0||g===-1||u[g]||(i[y]=g,u[g]=!0)});let d=[];for(let p=0;p<n;p++)i[p]<0&&d.push(p);let h=[];for(let p=0;p<o;p++)u[p]||h.push(p);if(d.length===0||h.length===0)return i;let m=n*o+1,w=Ke(e,t,r),v=(p,y)=>w(p,y)*m+Math.abs(p-y);for(let[p,y]of Ze(d,h,v))i[p]=y;return i}var be=e=>typeof e=="object"&&e!==null;function K(e,t){if(!be(t))return e==null?" null":String(e);let r=Object.keys(t);return JSON.stringify(r.map(l=>{let n=JSON.stringify(e?.[l]);return n===void 0?" undef":n}))}function Ke(e,t,r){if(!be(r))return(a,s)=>e[a]===t[s]?0:1;let l=Object.keys(r),n=a=>l.map(s=>JSON.stringify(a?.[s])),o=e.map(n),i=t.map(n);return(a,s)=>{let u=o[a],c=i[s],f=0;for(let d=0;d<l.length;d++)u[d]!==c[d]&&f++;return f}}function Ze(e,t,r){return e.length<=t.length?Z(e,t,r,!1):Z(t,e,(l,n)=>r(n,l),!0)}function Z(e,t,r,l){let n=e.length,o=t.length,i=[];for(let f=0;f<=n;f++)i.push(new Float64Array(o+1).fill(1/0));let a=[];for(let f=0;f<=n;f++)a.push(new Uint8Array(o+1));for(let f=0;f<=o;f++)i[n][f]=0;for(let f=n-1;f>=0;f--)for(let d=o-1;d>=0;d--){let h=r(e[f],t[d])+i[f+1][d+1],m=i[f][d+1];h<=m?(i[f][d]=h,a[f][d]=1):i[f][d]=m}let s=[],u=0,c=0;for(;u<n&&c<o;)a[u][c]&&(s.push(l?[t[c],e[u]]:[e[u],t[c]]),u++),c++;return s}function xe(e,t,r,l,n,o,i,a={}){let s=e.find(t,r,a);if(n.length===0){s.forEach(b=>e.remove(b)),D(a,"onRowsApplied",o.path,[]);return}let u=n.length>s.length,c=s[0]||null;if(u&&!c&&(c=rt(e,t,r,a),!c))throw new R(o.path);let f=s.map(b=>tt(e,b,l,a)),d=null;if(u&&c){d=e.clone(c),a.templateAttr&&e.removeAttr(d,a.templateAttr);let b=e.stripIds(d);b>0&&console.warn(`[hyper-html-api] stripped ${b} id attribute(s) from cloned template at "${o.path.join(".")||"(root)"}"`)}let h=Xe(n,f,l,Qe(e,s,n,o,a)),m=s.length>0?e.parent(s[0]):it(e,t,r,c,o,a),w=s.length>0?Ae(e,m,s[0]):0,v=ut(e,s),p=new Set,y=[],g=n.map((b,E)=>{let N=h[E];if(N>=0)return p.add(N),y.push(!1),s[N];y.push(!0);let T=e.clone(d);return e.stripIds(T),T});s.forEach((b,E)=>{p.has(E)||e.remove(b)}),v?st(e,m,w,g,y):ct(e,g,y,m,w),et(e,g,l,n,o,i,a),D(a,"onRowsApplied",o.path,g)}function D(e,t,r,l){if(typeof e[t]=="function")try{return e[t](r.slice(),l)}catch(n){console.warn(`[hyper-html-api] ${t} threw at "${r.join(".")||"(root)"}"`,n);return}}function Qe(e,t,r,l,n){let o=D(n,"identifyRows",l.path,r);if(!Array.isArray(o))return null;let i=new Array(r.length).fill(-1),a=new Set,s=new Map(t.map((u,c)=>[e.identity(u),c]));for(let u=0;u<r.length;u++){if(!o[u])continue;let c=s.get(e.identity(o[u]));c===void 0||a.has(c)||(i[u]=c,a.add(c))}return i}function et(e,t,r,l,n,o,i){t.forEach((a,s)=>{if(r===null){let u=l[s],c=u==null?"":String(u);e.text(a)!==c&&e.text(a,c)}else{let u=o(e,a,r,l[s],{depth:n.depth+1,path:[...n.path,s]},i);u&&u!==a&&(t[s]=u)}})}function tt(e,t,r,l){return r===null?e.text(t):we(e,t,r,l.onRowsRead?{...l,onRowsRead:void 0}:l)}function Ae(e,t,r){let l=e.children(t);for(let n=0;n<l.length;n++)if(e.sameNode(l[n],r))return n;return-1}function rt(e,t,r,l){if(!l.templateAttr)return null;let n=/^\s*:scope\s*>\s*/.test(r),o=new RegExp(":not\\(\\["+l.templateAttr.replace(/[.*+?^${}()|[\]\\-]/g,"\\$&")+"\\]\\)","g"),i=r.replace(/^\s*:scope\s*>\s*/,"").replace(o,""),a=n?nt(i):0,s=pe(i),u=t;for(;u;){let c=e.find(u,i,{includeRulesTag:!1,templateAttr:null});for(let f of c)if(e.attr(f,l.templateAttr)!=null&&!(n&&!ot(e,t,f,a))&&!(s&&!e.matches(e.parent(f),s)))return f;u=e.parent(u)}return null}function nt(e){let t=0,r=null,l=1;for(let n=0;n<e.length;n++){let o=e[n];if(o==="\\")n++;else if(r)o===r&&(r=null);else if(o==='"'||o==="'")r=o;else if(o==="["||o==="(")t++;else if(o==="]"||o===")")t>0&&t--;else if(t===0&&o===">")l++;else{if(t===0&&(o==="+"||o==="~"))return null;if(t===0&&/\s/.test(o)){if(!lt(e,n))return null;for(;n+1<e.length&&/\s/.test(e[n+1]);)n++}}}return l}function lt(e,t){let r=t;for(;r<e.length&&/\s/.test(e[r]);)r++;let l=t>0?e[t-1]:"",n=r<e.length?e[r]:"";return Q(l)||Q(n)}function Q(e){return e===">"||e==="+"||e==="~"}function ot(e,t,r,l){if(l===null)return!0;let n=r;for(let s=0;s<l;s++)if(n=e.parent(n),!n)return!1;let o=e.prop(t,"tagName");if(!o)return!0;let i=e.prop(n,"tagName");if(!i||String(i).toLowerCase()!==String(o).toLowerCase())return!1;let a=new Set(ee(e,n));return ee(e,t).every(s=>a.has(s))}function ee(e,t){let r=e.attr(t,"class");return r?String(r).split(/\s+/).filter(Boolean):[]}function it(e,t,r,l,n,o){let i=e.parent(l);if(i&&at(e,t,i)&&!re(e,i,o))return i;let a=pe(r);if(!a)throw new R(n.path,`the list selector "${r}" names no container to hold the new rows \u2014 write it as "container > row" (for example "ol.comments > li") so the cloned row lands in the list`);let s=(a===":scope"?e.prop(t,"tagName")?[t]:[]:e.find(t,a,o)).filter(u=>!re(e,u,o));if(s.length===0)throw new R(n.path,`no container matching "${a}" inside this context to hold the new rows`);if(s.length>1)throw new R(n.path,`"${a}" matches ${s.length} containers inside this context, so the new rows have no single destination`);return s[0]}function at(e,t,r){let l=r;for(;l;){if(e.sameNode(l,t))return!0;l=e.parent(l)}return e.parent(t)?!1:e.find(t,"*",{includeRulesTag:!0,templateAttr:null}).some(n=>e.sameNode(n,r))}var te=["no-data","editor-ui"];function re(e,t,r){let l=t;for(;l;){if(r.templateAttr&&e.attr(l,r.templateAttr)!=null||te.some(o=>e.attr(l,o)!=null))return!0;let n=e.attr(l,"clay");if(n&&n.split(/\s+/).some(o=>te.includes(o)))return!0;l=e.parent(l)}return!1}function st(e,t,r,l,n){let o=e.children(t),i=o.map(s=>e.identity(s)),a=!1;l.forEach((s,u)=>{let c=e.identity(s),f=r+u;if(i[f]===c)return;if(!n[u]){let h=i.indexOf(c);h!==-1&&(i.splice(h,1),o.splice(h,1))}let d=Math.min(f,o.length);d<o.length?e.insertBefore(o[d],s):o.length?a?e.insertAfter(o[o.length-1],s):(e.insertAt(t,s,f),a=!0):e.insertAt(t,s,0),i.splice(d,0,c),o.splice(d,0,s)})}function ut(e,t){if(t.length<=1)return!0;let r=e.parent(t[0]);if(!r)return!1;let l=new Map(e.children(r).map((o,i)=>[e.identity(o),i])),n=[];for(let o of t){let i=l.get(e.identity(o));if(i===void 0)return!1;n.push(i)}return n.sort((o,i)=>o-i),n[n.length-1]-n[0]===n.length-1}function ct(e,t,r,l,n){let o=null,i=n;for(let a=0;a<t.length;a++){if(!r[a]){o=t[a];continue}let s=o?e.parent(o):l;if(!s)continue;let u=o?Ae(e,s,o)+1:i++;e.insertAt(s,t[a],u),o=t[a]}}function ft(e,t,r,l,n={}){if(Object.prototype.hasOwnProperty.call(n,"exclude")&&e.semanticExclude===!1)throw new Error("This adapter does not support semantic exclude queries; omit exclude or use the DOM adapter.");let o=[];if(B(r,l,[],o),o.length)throw new ce(o);j(e,t,r,l,{depth:0,path:[]},n)}function j(e,t,r,l,n,o={}){if(n.depth>C)throw new V(n.path);if(l===void 0)return t;if(typeof r=="string")return dt(e,t,r,l,n,o);if(Array.isArray(r)){let[i,a]=r;return xe(e,t,i,a,l,n,j,o),t}if(typeof r=="object"&&r!==null){for(let[i,a]of Object.entries(r)){let s=j(e,t,a,l==null?l:l[i],{depth:n.depth+1,path:[...n.path,i]},o);s&&s!==t&&(t=s)}return t}return t}function dt(e,t,r,l,n,o){if(r.endsWith("[]")){let s=r.slice(0,-2);return xe(e,t,s,null,l,n,j,o),t}if(r.startsWith("@"))return le(e,t,r.slice(1),l);let i=de(r);if(i!==-1){let s=r.slice(0,i),u=r.slice(i+1),c=s?e.find(t,s,o):[t];return c.length===0||le(e,c[0],u,l),t}if(r===".")return ne(e,t,l),t;let a=e.find(t,r,o);return a.length===0||ne(e,a[0],l),t}function ne(e,t,r){let l=r==null?"":String(r);e.text(t)!==l&&e.text(t,l)}function pt(e,t,r,l){if(e.styleVar){e.styleVar(t,r,l);return}Ge(e,t,r,l)}function le(e,t,r,l){if(he(r))return pt(e,t,r,l==null?"":String(l).trim()),t;if(Ie.has(r)){let n=e.prop(t,r);if(n===l||n!=null&&l!=null&&String(n)===String(l))return t;throw new fe(r)}if(r==="outerHTML"){let n=l==null?"":String(l);return e.replaceWith(t,n)}if(Ue.has(r)){let n=Pe(r,l);return e.prop(t,r)!==n&&e.prop(t,r,n),t}if(l==null)e.attr(t,r)!=null&&e.removeAttr(t,r);else{let n=String(l);e.attr(t,r)!==n&&e.attr(t,r,n)}return t}function B(e,t,r,l){if(t!==void 0){if(typeof e=="string"){if(e.endsWith("[]")){Array.isArray(t)?t.forEach((n,o)=>{typeof n=="object"&&n!==null&&l.push({path:S([...r,o]),expected:"scalar",got:k(n)})}):l.push({path:S(r),expected:"array",got:k(t)});return}t!==null&&typeof t=="object"&&l.push({path:S(r),expected:"scalar",got:k(t)});return}if(Array.isArray(e)){if(!Array.isArray(t)){l.push({path:S(r),expected:"array",got:k(t)});return}let n=e[1];t.forEach((o,i)=>B(n,o,[...r,i],l));return}if(typeof e=="object"&&e!==null){if(t===null||Array.isArray(t)||typeof t!="object"){l.push({path:S(r),expected:"object",got:k(t)});return}for(let[n,o]of Object.entries(e))B(o,t[n],[...r,n],l)}}}function k(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function S(e){return e.join(".")}function ht(e){try{return JSON.parse(e)}catch{}let t={BRACE_OPEN:"{",BRACE_CLOSE:"}",BRACKET_OPEN:"[",BRACKET_CLOSE:"]",COLON:":",COMMA:",",STRING:"STRING",SELECTOR:"SELECTOR",IDENTIFIER:"IDENTIFIER",NUMBER:"NUMBER",BOOLEAN:"BOOLEAN"};function r(n){let o=[],i=0;for(;i<n.length;){let a=n[i];if(/\s/.test(a)){i++;continue}if("{}".includes(a)){o.push({type:a,value:a}),i++;continue}if(a==="["){let f=!1,d=i+1;for(;d<n.length&&/\s/.test(n[d]);)d++;if(d<n.length&&/[a-zA-Z_]/.test(n[d])&&(f=!0),!f){o.push({type:a,value:a}),i++;continue}}if(a==="]"){o.push({type:a,value:a}),i++;continue}if(a===":"){o.push({type:t.COLON,value:a}),i++;continue}if(a===","){o.push({type:t.COMMA,value:a}),i++;continue}if(a==='"'||a==="'"){let f=a,d=i+1;for(;d<n.length&&n[d]!==f;)n[d]==="\\"&&d++,d++;o.push({type:t.STRING,value:n.substring(i+1,d),quoted:!0,sourceQuote:f}),i=d+1;continue}let s=i,u;for(;s<n.length&&!/[{},]/.test(n[s]);)if(n[s]===":"){let f=[":first",":last",":nth-child",":nth-of-type",":first-child",":last-child",":first-of-type",":last-of-type",":only-child",":only-of-type",":hover",":focus",":active",":visited",":disabled",":enabled",":checked",":empty",":root",":target",":not",":before",":after",":nth-last-child",":nth-last-of-type"],d=!1;for(let h of f){let m=h.substring(1);if(n.substring(s+1,s+1+m.length)===m){d=!0,s+=m.length;break}}if(!d)break}else if(n[s]==="["){for(s++;s<n.length&&n[s]!=="]";){if(n[s]==='"'||n[s]==="'"){let f=n[s];for(s++;s<n.length&&n[s]!==f;)n[s]==="\\"&&s++,s++}s++}s<n.length&&n[s]==="]"&&s++}else s++;u=n.substring(i,s);let c=t.IDENTIFIER;/^-?\d+(\.\d+)?$/.test(u)?c=t.NUMBER:u==="true"||u==="false"||u==="null"?c=t.BOOLEAN:/^[.#@\[]|[.#@\[]| /.test(u)&&(c=t.SELECTOR),o.push({type:c,value:u,quoted:!1}),i=s}return o}function l(n){let o="";for(let i=0;i<n.length;i++){let a=n[i];if("{}".includes(a.type)||"[]".includes(a.type)){o+=a.value;continue}if(a.type===t.COLON){o+=a.value;continue}if(a.type===t.COMMA){let s=n[i+1];if(s&&(s.type==="}"||s.type==="]"))continue;o+=a.value;continue}if(a.type===t.STRING&&a.quoted){let s=a.value;a.sourceQuote==="'"&&(s=s.replace(/\\'/g,"'"),s=s.replace(/(\\*)"/g,(u,c)=>c.length%2===0?c+'\\"':u)),o+=`"${s}"`;continue}if(a.type===t.NUMBER||a.type===t.BOOLEAN){o+=a.value;continue}if(a.type===t.SELECTOR||a.type===t.IDENTIFIER){o+=`"${a.value}"`;continue}o+=`"${a.value}"`}return o}try{let n=r(e),o=l(n);return JSON.parse(o)}catch(n){throw new se("Invalid extraction rules syntax: "+n.message,n)}}var mt="1";var or=Object.freeze({data:Object.freeze({tokens:["no-data"],bundles:["editor-ui"]}),save:Object.freeze({tokens:["no-save"],bundles:["editor-ui"]}),snapshot:Object.freeze({tokens:["no-snapshot"],bundles:["editor-ui"]}),watch:Object.freeze({tokens:["no-watch"],bundles:["editor-ui"]}),undo:Object.freeze({tokens:["no-undo"],bundles:["editor-ui"]}),history:Object.freeze({tokens:[],bundles:["editor-ui"]})}),ir=Object.freeze({"editor-ui":Object.freeze(["no-data","no-save","no-snapshot","no-watch","no-undo"])}),yt=Object.freeze(["no-save","no-snapshot","no-trigger-autosave","no-dirty","no-watch","no-undo","no-data","freeze","editor-ui","live"]);var ar=Object.freeze({refusedRuleForms:["innerHTML","outerHTML"],refusedTargets:["script","style","template","noscript","iframe","object","embed","xmp","plaintext","noembed","noframes","meta","link","base","animate","set","animatemotion","animatetransform"],refusedAttributes:["style","srcdoc","is","http-equiv","sandbox","allow","nonce","integrity","charset","htmlclaytoken","htmlclayid","data-rules-name","data-rules-version","clay","contenteditable",...yt],refusedAttributePrefixes:["on"],urlAttributes:["href","src","srcset","action","formaction","poster","cite","data","ping","background","longdesc","usemap","xlink:href","manifest","codebase","icon"],refusedSchemes:["javascript","vbscript","data"],customPropertyValues:Object.freeze({maxLength:200,refusedCharacters:[";","{","}","<",">","\\"],refusedFunctions:["url","src","image","image-set","-webkit-image-set","cross-fade","element","expression","paint"]})});function gt(e){return e&&e.nodeType===1&&e.tagName==="SCRIPT"&&e.hasAttribute&&e.hasAttribute("data-rules-name")}function wt(e){return e?(e.nodeType===9||e.nodeType,e):null}function oe(e,t,r){!e||e.nodeType!==1||(t==="value"&&e.tagName==="INPUT"?e.value=r===null?"":r:t==="checked"&&e.tagName==="INPUT"?e.checked=r!==null:t==="selected"&&e.tagName==="OPTION"&&(e.selected=r!==null))}function vt(e,t){e&&e.tagName==="TEXTAREA"&&(e.value=t)}function bt(e){if(!e||e.nodeType!==1)return;let t=[e,...e.querySelectorAll?e.querySelectorAll("textarea, input, option"):[]];for(let r of t)if(r.tagName==="TEXTAREA")r.value=r.defaultValue;else if(r.tagName==="INPUT"){let l=r.type;l!=="file"&&l!=="checkbox"&&l!=="radio"&&(r.value=r.defaultValue),r.checked=r.defaultChecked}else r.tagName==="OPTION"&&(r.selected=r.defaultSelected)}var xt={semanticExclude:!0,find(e,t,r={}){let l=wt(e);if(!l||!l.querySelectorAll)return[];let n=Array.from(l.querySelectorAll(t));r.includeRulesTag||(n=n.filter(a=>!gt(a)));let o=[];r.skip&&o.push(r.skip);let i=r.templateAttr===null?null:r.templateAttr||"cms-template";if(i&&o.push("["+i+"]"),o.length){let a=o.join(", ");n=n.filter(s=>!s.closest||!s.closest(a))}return n},parent(e){return e?e.parentElement:null},children(e){return e?Array.from(e.children):[]},matches(e,t){return!!(e&&e.matches)&&e.matches(t)},text(e,t){if(t===void 0)return(e.textContent||"").trim();e.textContent=t,vt(e,t)},attr(e,t,r){if(r===void 0)return e.hasAttribute&&e.hasAttribute(t)?e.getAttribute(t):null;e.setAttribute(t,r),oe(e,t,r)},removeAttr(e,t){e&&e.removeAttribute&&e.removeAttribute(t),oe(e,t,null)},prop(e,t,r){if(r===void 0){let l=e?e[t]:void 0;return l!==void 0?l:null}e[t]=r},clone(e){let t=e.cloneNode(!0);return bt(t),t},insertAt(e,t,r){let l=e.children[r]||null;e.insertBefore(t,l)},insertBefore(e,t){e.parentNode.insertBefore(t,e)},insertAfter(e,t){e.parentNode.insertBefore(t,e.nextSibling)},identity(e){return e||null},remove(e){e&&e.parentNode&&e.parentNode.removeChild(e)},replaceWith(e,t){if(!e||!e.parentNode)throw new Error("dom.replaceWith: node has no parent");let r=e.ownerDocument.createElement("template");r.innerHTML=t;let l=r.content.firstElementChild;if(!l)throw new Error("dom.replaceWith: html did not parse to an element");return e.parentNode.replaceChild(l,e),l},stripIds(e){let t=0;return e.id&&(e.removeAttribute("id"),t++),(e.querySelectorAll?e.querySelectorAll("[id]"):[]).forEach(r=>{r.removeAttribute("id"),t++}),t},sameNode(e,t){return e===t}};var L=xt;var At="hha:upgrade-check:";function x(e,t){let r=e.querySelector(`meta[name="${t}"]`),l=r?r.getAttribute("content"):null;return l&&l.trim()?l.trim():null}function ie(e){if(typeof e!="string")return null;let t=e.trim().replace(/^v/,"");return/^\d+(\.\d+)*$/.test(t)?t.split(".").map(Number):null}function Tt(e,t){let r=ie(e),l=ie(t);if(!r||!l)return!1;let n=Math.max(r.length,l.length);for(let o=0;o<n;o++){let i=r[o]||0,a=l[o]||0;if(i!==a)return i>a}return!1}function Ot(e){try{let t=globalThis.localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function Et(e,t){try{globalThis.localStorage.setItem(e,JSON.stringify(t))}catch{}}async function Nt({force:e=!1,doc:t,loc:r,fetchFn:l,now:n,ttlMs:o=864e5}={}){if(t=t||(typeof document<"u"?document:null),r=r||(typeof location<"u"?location:null),l=l||(d=>fetch(d)),n=n??Date.now(),!t)return null;let i=x(t,"hyper-source");if(!i)return null;let a=x(t,"hyper-version"),s;try{s=new URL(i,r?r.href:void 0)}catch{return null}if(r&&s.origin===r.origin&&s.pathname===r.pathname)return null;let u=`${At}${s.href}:${a||"none"}`,c,f=e?null:Ot(u);if(f&&typeof f.checkedAt=="number"&&n-f.checkedAt<o)c=f.sourceVersion;else{try{let d=await l(s.href);if(!d.ok)throw new Error(`HTTP ${d.status}`);let h=await d.text(),m=new DOMParser().parseFromString(h,"text/html");c=x(m,"hyper-version")}catch{c=null}Et(u,{checkedAt:n,sourceVersion:c})}return c?{available:Tt(c,a||"0.0.0"),currentVersion:a,sourceVersion:c,sourceUrl:s.href}:null}var kt="script[data-rules-name]";function St(e){return typeof e=="string"?e.trim().replace(/\s+/g," "):""}function Te(e,t){let r=e.find(t,kt,{includeRulesTag:!0}),l=new Set,n=[];for(let o of r){let i=St(e.attr(o,"data-rules-name"));if(!i)continue;if(l.has(i)){console.warn(`hyper-html-api: duplicate rules tag name "${i}"; using the first.`);continue}let a=e.attr(o,"data-rules-version");if(a!==mt)throw new ue(a);l.add(i),n.push({name:i,rules:ht(e.text(o))})}return n}function Oe(e,t){let r={};for(let{name:l,rules:n}of Te(e,t))r[l]=we(e,t,n);return r}function Rt(e){let t=e||document,r=t.nodeType===9?t:t.ownerDocument||t;return{dataByName:Oe(L,t),version:x(r,"hyper-version")}}var ae=class extends Error{constructor(e,t){super(`could not fetch upgrade source: ${e}`),this.name="UpgradeSourceUnreachable",this.sourceUrl=e,this.cause=t}},$t=class extends Error{constructor(e){super(`upgrade source has no rules tags; refusing to drop all existing data: ${e}`),this.name="UpgradeSourceHasNoRules",this.sourceUrl=e}},q=class extends Error{constructor(e,t){super(e),this.name="UpgradeTransformInvalid",this.cause=t}},Lt=class extends Error{constructor(e){super(`found ${e} script[type="text/hyper-upgrade"] tags; only one is allowed per document.`),this.name="UpgradeMultipleTransforms",this.count=e}},jt="text/hyper-upgrade";function Ct(e,t){let r=e.find(t,`script[type="${jt}"]`);if(r.length===0)return null;if(r.length>1)throw new Lt(r.length);return e.text(r[0])||null}var Mt=new Function("url","return import(url)");async function Ut(e){let t=new Blob([e],{type:"text/javascript"}),r=URL.createObjectURL(t),l;try{l=await Mt(r)}catch(n){throw new q(`transform failed to load: ${n&&n.message?n.message:n}`,n)}finally{URL.revokeObjectURL(r)}if(typeof l.default!="function")throw new q("transform must `export default` a function");return l.default}function Ee(e,t){let r={carriedOver:0,discarded:0,listItems:0},l=H(t,e,r);return W(t,e,r),{data:l,summary:r}}function H(e,t,r){if(typeof e=="string")return e.endsWith("[]")?Array.isArray(t)?(r.listItems+=t.length,r.carriedOver+=t.length,t):void 0:t==null||typeof t=="object"?void 0:(r.carriedOver++,t);if(Array.isArray(e)){let[,l]=e;return Array.isArray(t)?(r.listItems+=t.length,t.map(n=>H(l,n,r))):void 0}if(typeof e=="object"&&e!==null){let l={};for(let[n,o]of Object.entries(e)){let i=H(o,t?.[n],r);i!==void 0&&(l[n]=i)}return l}}function W(e,t,r){if(t!=null){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(typeof t!="object"||Array.isArray(t))return;let l=new Set(Object.keys(e));for(let n of Object.keys(t))l.has(n)?W(e[n],t[n],r):r.discarded+=$(t[n]);return}if(Array.isArray(e)&&Array.isArray(t)){let l=e[1];t.forEach(n=>W(l,n,r));return}typeof e=="string"&&!e.endsWith("[]")&&typeof t=="object"&&t!==null&&(r.discarded+=$(t))}}function $(e){return e==null?0:Array.isArray(e)?e.reduce((t,r)=>t+$(r),0):typeof e=="object"?Object.values(e).reduce((t,r)=>t+$(r),0):1}function It(e,t,r){let l=Te(e,t),n={carriedOver:0,discarded:0,listItems:0},o={},i=new Set;for(let{name:a,rules:s}of l){if(i.add(a),!Object.prototype.hasOwnProperty.call(r,a)){o[a]={carriedOver:0,discarded:0,listItems:0};continue}let{data:u,summary:c}=Ee(r[a],s);ft(e,t,s,u),o[a]=c,n.carriedOver+=c.carriedOver,n.discarded+=c.discarded,n.listItems+=c.listItems}for(let a of Object.keys(r))i.has(a)||(n.discarded+=$(r[a]));return{totals:n,byName:o,rulesTagCount:l.length}}async function Pt({sourceUrl:e,dataByName:t,fromVersion:r,doc:l,loc:n,fetchFn:o}={}){if(l=l||(typeof document<"u"?document:null),n=n||(typeof location<"u"?location:null),o=o||(p=>fetch(p)),!l)throw new Error("upgrade.run requires a document context");if(e=e||x(l,"hyper-source"),!e)throw new Error("upgrade.run: no sourceUrl given and no hyper-source meta tag found");let i=new URL(e,n?n.href:void 0);r=r!==void 0?r:x(l,"hyper-version"),t=t||Oe(L,l);let a;try{a=await o(i.href)}catch(p){throw new ae(i.href,p)}if(!a.ok)throw new ae(i.href,new Error(`HTTP ${a.status}`));let s=await a.text(),u=new DOMParser().parseFromString(s,"text/html"),c=x(u,"hyper-version"),f=t,d=!1,h=Ct(L,u);if(h){let p=await(await Ut(h))(f,{fromVersion:r,toVersion:c});if(!p||typeof p!="object"||Array.isArray(p))throw new q("transform must return a plain object map of { rulesName: data }");f=p,d=!0}let{totals:m,byName:w,rulesTagCount:v}=It(L,u,f);if(v===0&&Object.keys(f).length>0)throw new $t(i.href);return{html:Bt(u),fromVersion:r,toVersion:c,summary:{transformApplied:d,totals:m,byName:w}}}function Dt(e){for(let t of e.querySelectorAll("input")){let r=(t.getAttribute("type")||"").toLowerCase();r!=="file"&&(r==="checkbox"||r==="radio"?t.checked!==t.hasAttribute("checked")&&t.toggleAttribute("checked",t.checked):t.value!==(t.getAttribute("value")??"")&&t.setAttribute("value",t.value))}for(let t of e.querySelectorAll("textarea"))t.value!==t.textContent&&(t.textContent=t.value);for(let t of e.querySelectorAll("select")){let r=[...t.options];if(!t.multiple){let l=r.findIndex(n=>n.hasAttribute("selected"));if(t.selectedIndex===l||l===-1&&t.selectedIndex<=0)continue}for(let l of r)l.selected!==l.hasAttribute("selected")&&l.toggleAttribute("selected",l.selected)}}function Bt(e){return Dt(e),`<!DOCTYPE ${e.doctype&&e.doctype.name?e.doctype.name:"html"}>
|
|
1
|
+
import{a as G}from"./c-S5IEIZCN.js";import{b as J}from"./c-3G2DGZUP.js";import{o as z,p as _}from"./c-GVPNDIKJ.js";import"./c-ATKAOH23.js";import"./c-EK63G3CG.js";import{a as F}from"./c-NQJRVJ56.js";import"./c-XGH4GS2T.js";import"./c-IJUK2GPW.js";import"./c-3O7OBDCM.js";import"./c-BPF2NSPV.js";import"./c-P7KNDG34.js";import"./c-CYWLPPUS.js";import"./c-N7JPUPGC.js";import"./c-EGTIAL6P.js";import"./c-XQXZAO7N.js";import"./c-S7LK4KUE.js";import"./c-VG5XIN4T.js";import"./c-2YYDMLNZ.js";import"./c-HA6INT6J.js";import"./c-ICMAOOGK.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";var Ce=Object.defineProperty,Le=(e,t)=>{for(var r in t)Ce(e,r,{get:t[r],enumerable:!0})},je=["textContent","innerText","innerHTML","outerHTML","value","checked","selected","disabled","readOnly","type","tagName","nodeName","nodeType","nodeValue","childElementCount","id","className","classList","baseURI","offsetWidth","offsetHeight","clientWidth","clientHeight","scrollWidth","scrollHeight","dataset","currentSrc","duration","paused","title","documentURI","contentType"],Me=new Set(je),Ue=new Set(["textContent","innerText","innerHTML","value","checked","selected","disabled","readOnly","type","id","className","title"]),Ie=new Set(["tagName","nodeName","nodeType","nodeValue","childElementCount","classList","baseURI","documentURI","contentType","offsetWidth","offsetHeight","clientWidth","clientHeight","scrollWidth","scrollHeight","currentSrc","duration","paused","dataset"]),Y=new Set(["checked","selected","disabled","readOnly","paused"]);function Pe(e,t){return t==null?Y.has(e)?!1:"":Y.has(e)?t==="false"?!1:!!t:t}var De={};Le(De,{EmptyListInsert:()=>R,MAX_RULE_DEPTH:()=>j,MaxRuleDepthExceeded:()=>V,NoRulesTag:()=>We,RuleTargetReadOnly:()=>fe,RulesParseError:()=>se,ShapeMismatch:()=>ce,UnknownRulesVersion:()=>ue,WriteNotRoundTripped:()=>He,WriteRefused:()=>Be,WriteRejected:()=>Ve});var se=class extends Error{constructor(e,t){super(e),this.name="RulesParseError",this.cause=t}},ue=class extends Error{constructor(e){super(`unknown rules version: ${e}. Library supports "1".`),this.name="UnknownRulesVersion",this.version=e}},j=20,V=class extends Error{constructor(e){super(`rule depth exceeded ${j} at path: ${e.join(".")}`),this.name="MaxRuleDepthExceeded",this.path=e}},ce=class extends Error{constructor(e){super(`shape mismatch: ${e.length} field(s) failed validation`),this.name="ShapeMismatch",this.mismatches=e}},R=class extends Error{constructor(e,t){super(t?`cannot add items to empty list at "${e.join(".")}" \u2014 ${t}`:`cannot add items to empty list at "${e.join(".")}" \u2014 no sibling to clone as template. Seed the list with a hidden item first.`),this.name="EmptyListInsert",this.path=e}},fe=class extends Error{constructor(e){super(`cannot write to read-only DOM property "${e}"`),this.name="RuleTargetReadOnly",this.target=e}},Be=class extends Error{constructor(e){super(`write refused: ${e.length} write(s) broke the content-only policy`),this.name="WriteRefused",this.refusals=e}};function qe(e){return e.reduce((t,r)=>typeof r=="number"?`${t}[${r}]`:t?`${t}.${r}`:String(r),"")||"(root)"}var He=class extends Error{constructor(e){super(`write did not round-trip at "${qe(e)}"`),this.name="WriteNotRoundTripped",this.path=e}},We=class extends Error{constructor(e){super(`no <script data-rules-name~="${e}"> rules tag in this document`),this.name="NoRulesTag",this.token=e}},Ve=class extends Error{constructor(e,t){super(`write rejected: ${e.length} unknown key(s), ${t.length} rule(s) with no matching element`),this.name="WriteRejected",this.unknownKeys=e,this.unmatched=t}};function de(e){let t=0,r=null,l=-1;for(let n=0;n<e.length;n++){let o=e[n];o==="\\"?n++:r?o===r&&(r=null):o==='"'||o==="'"?r=o:o==="["||o==="("?t++:o==="]"||o===")"?t>0&&t--:o==="@"&&t===0&&(l=n)}return l}function pe(e){let t=0,r=null,l=-1,n=!1;for(let o=0;o<e.length;o++){let i=e[o];i==="\\"?o++:r?i===r&&(r=null):i==='"'||i==="'"?r=i:i==="["||i==="("?t++:i==="]"||i===")"?t>0&&t--:t===0&&i===">"?l=o:t===0&&i===","&&(n=!0)}return n||l===-1||!Fe(e,l+1)?null:e.slice(0,l).trim()||null}function Fe(e,t){let r=t,l=e.replace(/\s+$/,"").length;for(;r<l&&/\s/.test(e[r]);)r++;let n=0,o=null;for(;r<l;r++){let i=e[r];if(i==="\\")r++;else if(o)i===o&&(o=null);else if(i==='"'||i==="'")o=i;else if(i==="["||i==="(")n++;else if(i==="]"||i===")")n>0&&n--;else if(n===0&&(i==="+"||i==="~"||/\s/.test(i)))return!1}return!0}var ze=/^--[A-Za-z0-9_-]+$/;function he(e){return typeof e=="string"&&ze.test(e)}function me(e){let t=[],r=[],l=null,n=0;for(let o=0;o<e.length;o++){let i=e[o];if(l){i==="\\"?o++:i===l&&(l=null);continue}if(i==="/"&&e[o+1]==="*"){let a=e.indexOf("*/",o+2);o=a===-1?e.length:a+1;continue}i==='"'||i==="'"?l=i:i==="("?r.push(")"):i==="["?r.push("]"):i==="{"?r.push("}"):(i===")"||i==="]"||i==="}")&&r[r.length-1]===i?r.pop():i===";"&&r.length===0&&(t.push(e.slice(n,o)),n=o+1)}return t.push(e.slice(n)),t}function _e(e){let t="",r=null;for(let l=0;l<e.length;l++){let n=e[l];if(r){t+=n,n==="\\"&&l+1<e.length?t+=e[++l]:n===r&&(r=null);continue}if(n==="/"&&e[l+1]==="*"){let o=e.indexOf("*/",l+2);l=o===-1?e.length:o+1,t+=" ";continue}(n==='"'||n==="'")&&(r=n),t+=n}return t}function ye(e){e=_e(e);let t=e.indexOf(":");if(t===-1)return null;let r=e.slice(0,t).trim(),l=e.slice(t+1).trim(),n=/!\s*important\s*$/i.exec(l);return n&&(l=l.slice(0,n.index).trim()),{name:r,value:l,important:!!n}}function ge(e,t){if(e==null)return null;let r=null;for(let l of me(String(e))){let n=ye(l);!n||n.name!==t||(!r||n.important||!r.important)&&(r=n)}return r?r.value:null}function Je(e,t,r){let l=e==null?"":String(e),n=r==null||r==="",o=me(l),i=o.map(ye),a=i.some(f=>f&&f.name===t&&f.important),s=[],u=!1;o.forEach((f,d)=>{let h=i[d];if(!h||h.name!==t){s.push(f);return}if(n||u)return;let m=/^\s*/.exec(f)[0];s.push(`${m}${t}: ${r}${a?" !important":""}`),u=!0});let c=s.join(";");if(!n&&!u){let f=c.trimEnd();c=f===""?`${t}: ${r}`:`${f}${f.endsWith(";")?" ":"; "}${t}: ${r}`}return c.trim()===""?null:c}function Ge(e,t,r,l){let n=e.attr(t,"style");if((ge(n,r)??"")===l)return;let o=Je(n,r,l);o==null?e.removeAttr(t,"style"):e.attr(t,"style",o)}function we(e,t,r,l={}){if(Object.prototype.hasOwnProperty.call(l,"exclude")&&e.semanticExclude===!1)throw new Error("This adapter does not support semantic exclude queries; omit exclude or use the DOM adapter.");return P(e,t,r,{depth:0,path:[]},l)}function P(e,t,r,l,n){if(l.depth>j)throw new V(l.path);if(typeof r=="string")return Ye(e,t,r,l,n);if(Array.isArray(r)){let[o,i]=r,a=e.find(t,o,n);return ve(n,l,a),a.map((s,u)=>P(e,s,i,{depth:l.depth+1,path:[...l.path,u]},n))}if(typeof r=="object"&&r!==null){let o={};for(let[i,a]of Object.entries(r))o[i]=P(e,t,a,{depth:l.depth+1,path:[...l.path,i]},n);return o}return null}function Ye(e,t,r,l,n){if(r.endsWith("[]")){let a=r.slice(0,-2),s=e.find(t,a,n);return ve(n,l,s),s.map(u=>e.text(u))}if(r.startsWith("@"))return X(e,t,r.slice(1));let o=de(r);if(o!==-1){let a=r.slice(0,o),s=r.slice(o+1),u=a?e.find(t,a,n):[t];return u.length===0?null:X(e,u[0],s)}if(r===".")return e.text(t);let i=e.find(t,r,n);return i.length===0?null:e.text(i[0])}function ve(e,t,r){if(typeof e.onRowsRead=="function")try{e.onRowsRead(t.path.slice(),r)}catch(l){console.warn(`[hyper-html-api] onRowsRead threw at "${t.path.join(".")||"(root)"}"`,l)}}function X(e,t,r){if(he(r))return ge(e.attr(t,"style"),r);if(Me.has(r)){let n=e.prop(t,r);return n==null?null:String(n)}return e.attr(t,r)??null}function Xe(e,t,r,l){let n=e.length,o=t.length,i=new Array(n).fill(-1);if(l){let p=new Set;for(let y=0;y<n;y++){let g=l[y];!(g>=0&&g<o)||p.has(g)||(i[y]=g,p.add(g))}}if(n===0||o===0)return i;let a=e.map(p=>K(p,r)),s=t.map(p=>K(p,r)),u=new Array(o).fill(!1);for(let p of i)p>=0&&(u[p]=!0);let c=new Map;s.forEach((p,y)=>{u[y]||c.set(p,c.has(p)?-1:y)});let f=new Map;a.forEach((p,y)=>{i[y]>=0||f.set(p,(f.get(p)||0)+1)}),a.forEach((p,y)=>{if(i[y]>=0||f.get(p)!==1)return;let g=c.get(p);g===void 0||g===-1||u[g]||(i[y]=g,u[g]=!0)});let d=[];for(let p=0;p<n;p++)i[p]<0&&d.push(p);let h=[];for(let p=0;p<o;p++)u[p]||h.push(p);if(d.length===0||h.length===0)return i;let m=n*o+1,w=Ke(e,t,r),v=(p,y)=>w(p,y)*m+Math.abs(p-y);for(let[p,y]of Ze(d,h,v))i[p]=y;return i}var be=e=>typeof e=="object"&&e!==null;function K(e,t){if(!be(t))return e==null?" null":String(e);let r=Object.keys(t);return JSON.stringify(r.map(l=>{let n=JSON.stringify(e?.[l]);return n===void 0?" undef":n}))}function Ke(e,t,r){if(!be(r))return(a,s)=>e[a]===t[s]?0:1;let l=Object.keys(r),n=a=>l.map(s=>JSON.stringify(a?.[s])),o=e.map(n),i=t.map(n);return(a,s)=>{let u=o[a],c=i[s],f=0;for(let d=0;d<l.length;d++)u[d]!==c[d]&&f++;return f}}function Ze(e,t,r){return e.length<=t.length?Z(e,t,r,!1):Z(t,e,(l,n)=>r(n,l),!0)}function Z(e,t,r,l){let n=e.length,o=t.length,i=[];for(let f=0;f<=n;f++)i.push(new Float64Array(o+1).fill(1/0));let a=[];for(let f=0;f<=n;f++)a.push(new Uint8Array(o+1));for(let f=0;f<=o;f++)i[n][f]=0;for(let f=n-1;f>=0;f--)for(let d=o-1;d>=0;d--){let h=r(e[f],t[d])+i[f+1][d+1],m=i[f][d+1];h<=m?(i[f][d]=h,a[f][d]=1):i[f][d]=m}let s=[],u=0,c=0;for(;u<n&&c<o;)a[u][c]&&(s.push(l?[t[c],e[u]]:[e[u],t[c]]),u++),c++;return s}function xe(e,t,r,l,n,o,i,a={}){let s=e.find(t,r,a);if(n.length===0){s.forEach(b=>e.remove(b)),D(a,"onRowsApplied",o.path,[]);return}let u=n.length>s.length,c=s[0]||null;if(u&&!c&&(c=rt(e,t,r,a),!c))throw new R(o.path);let f=s.map(b=>tt(e,b,l,a)),d=null;if(u&&c){d=e.clone(c),a.templateAttr&&e.removeAttr(d,a.templateAttr);let b=e.stripIds(d);b>0&&console.warn(`[hyper-html-api] stripped ${b} id attribute(s) from cloned template at "${o.path.join(".")||"(root)"}"`)}let h=Xe(n,f,l,Qe(e,s,n,o,a)),m=s.length>0?e.parent(s[0]):it(e,t,r,c,o,a),w=s.length>0?Ae(e,m,s[0]):0,v=ut(e,s),p=new Set,y=[],g=n.map((b,E)=>{let N=h[E];if(N>=0)return p.add(N),y.push(!1),s[N];y.push(!0);let T=e.clone(d);return e.stripIds(T),T});s.forEach((b,E)=>{p.has(E)||e.remove(b)}),v?st(e,m,w,g,y):ct(e,g,y,m,w),et(e,g,l,n,o,i,a),D(a,"onRowsApplied",o.path,g)}function D(e,t,r,l){if(typeof e[t]=="function")try{return e[t](r.slice(),l)}catch(n){console.warn(`[hyper-html-api] ${t} threw at "${r.join(".")||"(root)"}"`,n);return}}function Qe(e,t,r,l,n){let o=D(n,"identifyRows",l.path,r);if(!Array.isArray(o))return null;let i=new Array(r.length).fill(-1),a=new Set,s=new Map(t.map((u,c)=>[e.identity(u),c]));for(let u=0;u<r.length;u++){if(!o[u])continue;let c=s.get(e.identity(o[u]));c===void 0||a.has(c)||(i[u]=c,a.add(c))}return i}function et(e,t,r,l,n,o,i){t.forEach((a,s)=>{if(r===null){let u=l[s],c=u==null?"":String(u);e.text(a)!==c&&e.text(a,c)}else{let u=o(e,a,r,l[s],{depth:n.depth+1,path:[...n.path,s]},i);u&&u!==a&&(t[s]=u)}})}function tt(e,t,r,l){return r===null?e.text(t):we(e,t,r,l.onRowsRead?{...l,onRowsRead:void 0}:l)}function Ae(e,t,r){let l=e.children(t);for(let n=0;n<l.length;n++)if(e.sameNode(l[n],r))return n;return-1}function rt(e,t,r,l){if(!l.templateAttr)return null;let n=/^\s*:scope\s*>\s*/.test(r),o=new RegExp(":not\\(\\["+l.templateAttr.replace(/[.*+?^${}()|[\]\\-]/g,"\\$&")+"\\]\\)","g"),i=r.replace(/^\s*:scope\s*>\s*/,"").replace(o,""),a=n?nt(i):0,s=pe(i),u=t;for(;u;){let c=e.find(u,i,{includeRulesTag:!1,templateAttr:null});for(let f of c)if(e.attr(f,l.templateAttr)!=null&&!(n&&!ot(e,t,f,a))&&!(s&&!e.matches(e.parent(f),s)))return f;u=e.parent(u)}return null}function nt(e){let t=0,r=null,l=1;for(let n=0;n<e.length;n++){let o=e[n];if(o==="\\")n++;else if(r)o===r&&(r=null);else if(o==='"'||o==="'")r=o;else if(o==="["||o==="(")t++;else if(o==="]"||o===")")t>0&&t--;else if(t===0&&o===">")l++;else{if(t===0&&(o==="+"||o==="~"))return null;if(t===0&&/\s/.test(o)){if(!lt(e,n))return null;for(;n+1<e.length&&/\s/.test(e[n+1]);)n++}}}return l}function lt(e,t){let r=t;for(;r<e.length&&/\s/.test(e[r]);)r++;let l=t>0?e[t-1]:"",n=r<e.length?e[r]:"";return Q(l)||Q(n)}function Q(e){return e===">"||e==="+"||e==="~"}function ot(e,t,r,l){if(l===null)return!0;let n=r;for(let s=0;s<l;s++)if(n=e.parent(n),!n)return!1;let o=e.prop(t,"tagName");if(!o)return!0;let i=e.prop(n,"tagName");if(!i||String(i).toLowerCase()!==String(o).toLowerCase())return!1;let a=new Set(ee(e,n));return ee(e,t).every(s=>a.has(s))}function ee(e,t){let r=e.attr(t,"class");return r?String(r).split(/\s+/).filter(Boolean):[]}function it(e,t,r,l,n,o){let i=e.parent(l);if(i&&at(e,t,i)&&!re(e,i,o))return i;let a=pe(r);if(!a)throw new R(n.path,`the list selector "${r}" names no container to hold the new rows \u2014 write it as "container > row" (for example "ol.comments > li") so the cloned row lands in the list`);let s=(a===":scope"?e.prop(t,"tagName")?[t]:[]:e.find(t,a,o)).filter(u=>!re(e,u,o));if(s.length===0)throw new R(n.path,`no container matching "${a}" inside this context to hold the new rows`);if(s.length>1)throw new R(n.path,`"${a}" matches ${s.length} containers inside this context, so the new rows have no single destination`);return s[0]}function at(e,t,r){let l=r;for(;l;){if(e.sameNode(l,t))return!0;l=e.parent(l)}return e.parent(t)?!1:e.find(t,"*",{includeRulesTag:!0,templateAttr:null}).some(n=>e.sameNode(n,r))}var te=["no-data","editor-ui"];function re(e,t,r){let l=t;for(;l;){if(r.templateAttr&&e.attr(l,r.templateAttr)!=null||te.some(o=>e.attr(l,o)!=null))return!0;let n=e.attr(l,"clay");if(n&&n.split(/\s+/).some(o=>te.includes(o)))return!0;l=e.parent(l)}return!1}function st(e,t,r,l,n){let o=e.children(t),i=o.map(s=>e.identity(s)),a=!1;l.forEach((s,u)=>{let c=e.identity(s),f=r+u;if(i[f]===c)return;if(!n[u]){let h=i.indexOf(c);h!==-1&&(i.splice(h,1),o.splice(h,1))}let d=Math.min(f,o.length);d<o.length?e.insertBefore(o[d],s):o.length?a?e.insertAfter(o[o.length-1],s):(e.insertAt(t,s,f),a=!0):e.insertAt(t,s,0),i.splice(d,0,c),o.splice(d,0,s)})}function ut(e,t){if(t.length<=1)return!0;let r=e.parent(t[0]);if(!r)return!1;let l=new Map(e.children(r).map((o,i)=>[e.identity(o),i])),n=[];for(let o of t){let i=l.get(e.identity(o));if(i===void 0)return!1;n.push(i)}return n.sort((o,i)=>o-i),n[n.length-1]-n[0]===n.length-1}function ct(e,t,r,l,n){let o=null,i=n;for(let a=0;a<t.length;a++){if(!r[a]){o=t[a];continue}let s=o?e.parent(o):l;if(!s)continue;let u=o?Ae(e,s,o)+1:i++;e.insertAt(s,t[a],u),o=t[a]}}function ft(e,t,r,l,n={}){if(Object.prototype.hasOwnProperty.call(n,"exclude")&&e.semanticExclude===!1)throw new Error("This adapter does not support semantic exclude queries; omit exclude or use the DOM adapter.");let o=[];if(B(r,l,[],o),o.length)throw new ce(o);L(e,t,r,l,{depth:0,path:[]},n)}function L(e,t,r,l,n,o={}){if(n.depth>j)throw new V(n.path);if(l===void 0)return t;if(typeof r=="string")return dt(e,t,r,l,n,o);if(Array.isArray(r)){let[i,a]=r;return xe(e,t,i,a,l,n,L,o),t}if(typeof r=="object"&&r!==null){for(let[i,a]of Object.entries(r)){let s=L(e,t,a,l==null?l:l[i],{depth:n.depth+1,path:[...n.path,i]},o);s&&s!==t&&(t=s)}return t}return t}function dt(e,t,r,l,n,o){if(r.endsWith("[]")){let s=r.slice(0,-2);return xe(e,t,s,null,l,n,L,o),t}if(r.startsWith("@"))return le(e,t,r.slice(1),l);let i=de(r);if(i!==-1){let s=r.slice(0,i),u=r.slice(i+1),c=s?e.find(t,s,o):[t];return c.length===0||le(e,c[0],u,l),t}if(r===".")return ne(e,t,l),t;let a=e.find(t,r,o);return a.length===0||ne(e,a[0],l),t}function ne(e,t,r){let l=r==null?"":String(r);e.text(t)!==l&&e.text(t,l)}function pt(e,t,r,l){if(e.styleVar){e.styleVar(t,r,l);return}Ge(e,t,r,l)}function le(e,t,r,l){if(he(r))return pt(e,t,r,l==null?"":String(l).trim()),t;if(Ie.has(r)){let n=e.prop(t,r);if(n===l||n!=null&&l!=null&&String(n)===String(l))return t;throw new fe(r)}if(r==="outerHTML"){let n=l==null?"":String(l);return e.replaceWith(t,n)}if(Ue.has(r)){let n=Pe(r,l);return e.prop(t,r)!==n&&e.prop(t,r,n),t}if(l==null)e.attr(t,r)!=null&&e.removeAttr(t,r);else{let n=String(l);e.attr(t,r)!==n&&e.attr(t,r,n)}return t}function B(e,t,r,l){if(t!==void 0){if(typeof e=="string"){if(e.endsWith("[]")){Array.isArray(t)?t.forEach((n,o)=>{typeof n=="object"&&n!==null&&l.push({path:S([...r,o]),expected:"scalar",got:k(n)})}):l.push({path:S(r),expected:"array",got:k(t)});return}t!==null&&typeof t=="object"&&l.push({path:S(r),expected:"scalar",got:k(t)});return}if(Array.isArray(e)){if(!Array.isArray(t)){l.push({path:S(r),expected:"array",got:k(t)});return}let n=e[1];t.forEach((o,i)=>B(n,o,[...r,i],l));return}if(typeof e=="object"&&e!==null){if(t===null||Array.isArray(t)||typeof t!="object"){l.push({path:S(r),expected:"object",got:k(t)});return}for(let[n,o]of Object.entries(e))B(o,t[n],[...r,n],l)}}}function k(e){return e===null?"null":Array.isArray(e)?"array":typeof e}function S(e){return e.join(".")}function ht(e){try{return JSON.parse(e)}catch{}let t={BRACE_OPEN:"{",BRACE_CLOSE:"}",BRACKET_OPEN:"[",BRACKET_CLOSE:"]",COLON:":",COMMA:",",STRING:"STRING",SELECTOR:"SELECTOR",IDENTIFIER:"IDENTIFIER",NUMBER:"NUMBER",BOOLEAN:"BOOLEAN"};function r(n){let o=[],i=0;for(;i<n.length;){let a=n[i];if(/\s/.test(a)){i++;continue}if("{}".includes(a)){o.push({type:a,value:a}),i++;continue}if(a==="["){let f=!1,d=i+1;for(;d<n.length&&/\s/.test(n[d]);)d++;if(d<n.length&&/[a-zA-Z_]/.test(n[d])&&(f=!0),!f){o.push({type:a,value:a}),i++;continue}}if(a==="]"){o.push({type:a,value:a}),i++;continue}if(a===":"){o.push({type:t.COLON,value:a}),i++;continue}if(a===","){o.push({type:t.COMMA,value:a}),i++;continue}if(a==='"'||a==="'"){let f=a,d=i+1;for(;d<n.length&&n[d]!==f;)n[d]==="\\"&&d++,d++;o.push({type:t.STRING,value:n.substring(i+1,d),quoted:!0,sourceQuote:f}),i=d+1;continue}let s=i,u;for(;s<n.length&&!/[{},]/.test(n[s]);)if(n[s]===":"){let f=[":first",":last",":nth-child",":nth-of-type",":first-child",":last-child",":first-of-type",":last-of-type",":only-child",":only-of-type",":hover",":focus",":active",":visited",":disabled",":enabled",":checked",":empty",":root",":target",":not",":before",":after",":nth-last-child",":nth-last-of-type"],d=!1;for(let h of f){let m=h.substring(1);if(n.substring(s+1,s+1+m.length)===m){d=!0,s+=m.length;break}}if(!d)break}else if(n[s]==="["){for(s++;s<n.length&&n[s]!=="]";){if(n[s]==='"'||n[s]==="'"){let f=n[s];for(s++;s<n.length&&n[s]!==f;)n[s]==="\\"&&s++,s++}s++}s<n.length&&n[s]==="]"&&s++}else s++;u=n.substring(i,s);let c=t.IDENTIFIER;/^-?\d+(\.\d+)?$/.test(u)?c=t.NUMBER:u==="true"||u==="false"||u==="null"?c=t.BOOLEAN:/^[.#@\[]|[.#@\[]| /.test(u)&&(c=t.SELECTOR),o.push({type:c,value:u,quoted:!1}),i=s}return o}function l(n){let o="";for(let i=0;i<n.length;i++){let a=n[i];if("{}".includes(a.type)||"[]".includes(a.type)){o+=a.value;continue}if(a.type===t.COLON){o+=a.value;continue}if(a.type===t.COMMA){let s=n[i+1];if(s&&(s.type==="}"||s.type==="]"))continue;o+=a.value;continue}if(a.type===t.STRING&&a.quoted){let s=a.value;a.sourceQuote==="'"&&(s=s.replace(/\\'/g,"'"),s=s.replace(/(\\*)"/g,(u,c)=>c.length%2===0?c+'\\"':u)),o+=`"${s}"`;continue}if(a.type===t.NUMBER||a.type===t.BOOLEAN){o+=a.value;continue}if(a.type===t.SELECTOR||a.type===t.IDENTIFIER){o+=`"${a.value}"`;continue}o+=`"${a.value}"`}return o}try{let n=r(e),o=l(n);return JSON.parse(o)}catch(n){throw new se("Invalid extraction rules syntax: "+n.message,n)}}var mt="1";var or=Object.freeze({data:Object.freeze({tokens:["no-data"],bundles:["editor-ui"]}),save:Object.freeze({tokens:["no-save"],bundles:["editor-ui"]}),snapshot:Object.freeze({tokens:["no-snapshot"],bundles:["editor-ui"]}),watch:Object.freeze({tokens:["no-watch"],bundles:["editor-ui"]}),undo:Object.freeze({tokens:["no-undo"],bundles:["editor-ui"]}),history:Object.freeze({tokens:[],bundles:["editor-ui"]})}),ir=Object.freeze({"editor-ui":Object.freeze(["no-data","no-save","no-snapshot","no-watch","no-undo"])}),yt=Object.freeze(["no-save","no-snapshot","no-trigger-autosave","no-dirty","no-watch","no-undo","no-data","freeze","editor-ui","live"]);var ar=Object.freeze({refusedRuleForms:["innerHTML","outerHTML"],refusedTargets:["script","style","template","noscript","iframe","object","embed","xmp","plaintext","noembed","noframes","meta","link","base","animate","set","animatemotion","animatetransform"],refusedAttributes:["style","srcdoc","is","http-equiv","sandbox","allow","nonce","integrity","charset","htmlclaytoken","htmlclayid","data-rules-name","data-rules-version","clay","contenteditable",...yt],refusedAttributePrefixes:["on"],urlAttributes:["href","src","srcset","action","formaction","poster","cite","data","ping","background","longdesc","usemap","xlink:href","manifest","codebase","icon"],refusedSchemes:["javascript","vbscript","data"],customPropertyValues:Object.freeze({maxLength:200,refusedCharacters:[";","{","}","<",">","\\"],refusedFunctions:["url","src","image","image-set","-webkit-image-set","cross-fade","element","expression","paint"]})});function gt(e){return e&&e.nodeType===1&&e.tagName==="SCRIPT"&&e.hasAttribute&&e.hasAttribute("data-rules-name")}function wt(e){return e?(e.nodeType===9||e.nodeType,e):null}function oe(e,t,r){!e||e.nodeType!==1||(t==="value"&&e.tagName==="INPUT"?e.value=r===null?"":r:t==="checked"&&e.tagName==="INPUT"?e.checked=r!==null:t==="selected"&&e.tagName==="OPTION"&&(e.selected=r!==null))}function vt(e,t){e&&e.tagName==="TEXTAREA"&&(e.value=t)}function bt(e){if(!e||e.nodeType!==1)return;let t=[e,...e.querySelectorAll?e.querySelectorAll("textarea, input, option"):[]];for(let r of t)if(r.tagName==="TEXTAREA")r.value=r.defaultValue;else if(r.tagName==="INPUT"){let l=r.type;l!=="file"&&l!=="checkbox"&&l!=="radio"&&(r.value=r.defaultValue),r.checked=r.defaultChecked}else r.tagName==="OPTION"&&(r.selected=r.defaultSelected)}var xt={semanticExclude:!0,find(e,t,r={}){let l=wt(e);if(!l||!l.querySelectorAll)return[];let n=Array.from(l.querySelectorAll(t));r.includeRulesTag||(n=n.filter(a=>!gt(a)));let o=[];r.skip&&o.push(r.skip);let i=r.templateAttr===null?null:r.templateAttr||"cms-template";if(i&&o.push("["+i+"]"),o.length){let a=o.join(", ");n=n.filter(s=>!s.closest||!s.closest(a))}return n},parent(e){return e?e.parentElement:null},children(e){return e?Array.from(e.children):[]},matches(e,t){return!!(e&&e.matches)&&e.matches(t)},text(e,t){if(t===void 0)return(e.textContent||"").trim();e.textContent=t,vt(e,t)},attr(e,t,r){if(r===void 0)return e.hasAttribute&&e.hasAttribute(t)?e.getAttribute(t):null;e.setAttribute(t,r),oe(e,t,r)},removeAttr(e,t){e&&e.removeAttribute&&e.removeAttribute(t),oe(e,t,null)},prop(e,t,r){if(r===void 0){let l=e?e[t]:void 0;return l!==void 0?l:null}e[t]=r},clone(e){let t=e.cloneNode(!0);return bt(t),t},insertAt(e,t,r){let l=e.children[r]||null;e.insertBefore(t,l)},insertBefore(e,t){e.parentNode.insertBefore(t,e)},insertAfter(e,t){e.parentNode.insertBefore(t,e.nextSibling)},identity(e){return e||null},remove(e){e&&e.parentNode&&e.parentNode.removeChild(e)},replaceWith(e,t){if(!e||!e.parentNode)throw new Error("dom.replaceWith: node has no parent");let r=e.ownerDocument.createElement("template");r.innerHTML=t;let l=r.content.firstElementChild;if(!l)throw new Error("dom.replaceWith: html did not parse to an element");return e.parentNode.replaceChild(l,e),l},stripIds(e){let t=0;return e.id&&(e.removeAttribute("id"),t++),(e.querySelectorAll?e.querySelectorAll("[id]"):[]).forEach(r=>{r.removeAttribute("id"),t++}),t},sameNode(e,t){return e===t}};var C=xt;var At="hha:upgrade-check:";function x(e,t){let r=e.querySelector(`meta[name="${t}"]`),l=r?r.getAttribute("content"):null;return l&&l.trim()?l.trim():null}function ie(e){if(typeof e!="string")return null;let t=e.trim().replace(/^v/,"");return/^\d+(\.\d+)*$/.test(t)?t.split(".").map(Number):null}function Tt(e,t){let r=ie(e),l=ie(t);if(!r||!l)return!1;let n=Math.max(r.length,l.length);for(let o=0;o<n;o++){let i=r[o]||0,a=l[o]||0;if(i!==a)return i>a}return!1}function Ot(e){try{let t=globalThis.localStorage.getItem(e);return t?JSON.parse(t):null}catch{return null}}function Et(e,t){try{globalThis.localStorage.setItem(e,JSON.stringify(t))}catch{}}async function Nt({force:e=!1,doc:t,loc:r,fetchFn:l,now:n,ttlMs:o=864e5}={}){if(t=t||(typeof document<"u"?document:null),r=r||(typeof location<"u"?location:null),l=l||(d=>fetch(d)),n=n??Date.now(),!t)return null;let i=x(t,"hyper-source");if(!i)return null;let a=x(t,"hyper-version"),s;try{s=new URL(i,r?r.href:void 0)}catch{return null}if(r&&s.origin===r.origin&&s.pathname===r.pathname)return null;let u=`${At}${s.href}:${a||"none"}`,c,f=e?null:Ot(u);if(f&&typeof f.checkedAt=="number"&&n-f.checkedAt<o)c=f.sourceVersion;else{try{let d=await l(s.href);if(!d.ok)throw new Error(`HTTP ${d.status}`);let h=await d.text(),m=new DOMParser().parseFromString(h,"text/html");c=x(m,"hyper-version")}catch{c=null}Et(u,{checkedAt:n,sourceVersion:c})}return c?{available:Tt(c,a||"0.0.0"),currentVersion:a,sourceVersion:c,sourceUrl:s.href}:null}var kt="script[data-rules-name]";function St(e){return typeof e=="string"?e.trim().replace(/\s+/g," "):""}function Te(e,t){let r=e.find(t,kt,{includeRulesTag:!0}),l=new Set,n=[];for(let o of r){let i=St(e.attr(o,"data-rules-name"));if(!i)continue;if(l.has(i)){console.warn(`hyper-html-api: duplicate rules tag name "${i}"; using the first.`);continue}let a=e.attr(o,"data-rules-version");if(a!==mt)throw new ue(a);l.add(i),n.push({name:i,rules:ht(e.text(o))})}return n}function Oe(e,t){let r={};for(let{name:l,rules:n}of Te(e,t))r[l]=we(e,t,n);return r}function Rt(e){let t=e||document,r=t.nodeType===9?t:t.ownerDocument||t;return{dataByName:Oe(C,t),version:x(r,"hyper-version")}}var ae=class extends Error{constructor(e,t){super(`could not fetch upgrade source: ${e}`),this.name="UpgradeSourceUnreachable",this.sourceUrl=e,this.cause=t}},$t=class extends Error{constructor(e){super(`upgrade source has no rules tags; refusing to drop all existing data: ${e}`),this.name="UpgradeSourceHasNoRules",this.sourceUrl=e}},q=class extends Error{constructor(e,t){super(e),this.name="UpgradeTransformInvalid",this.cause=t}},Ct=class extends Error{constructor(e){super(`found ${e} script[type="text/hyper-upgrade"] tags; only one is allowed per document.`),this.name="UpgradeMultipleTransforms",this.count=e}},Lt="text/hyper-upgrade";function jt(e,t){let r=e.find(t,`script[type="${Lt}"]`);if(r.length===0)return null;if(r.length>1)throw new Ct(r.length);return e.text(r[0])||null}var Mt=new Function("url","return import(url)");async function Ut(e){let t=new Blob([e],{type:"text/javascript"}),r=URL.createObjectURL(t),l;try{l=await Mt(r)}catch(n){throw new q(`transform failed to load: ${n&&n.message?n.message:n}`,n)}finally{URL.revokeObjectURL(r)}if(typeof l.default!="function")throw new q("transform must `export default` a function");return l.default}function Ee(e,t){let r={carriedOver:0,discarded:0,listItems:0},l=H(t,e,r);return W(t,e,r),{data:l,summary:r}}function H(e,t,r){if(typeof e=="string")return e.endsWith("[]")?Array.isArray(t)?(r.listItems+=t.length,r.carriedOver+=t.length,t):void 0:t==null||typeof t=="object"?void 0:(r.carriedOver++,t);if(Array.isArray(e)){let[,l]=e;return Array.isArray(t)?(r.listItems+=t.length,t.map(n=>H(l,n,r))):void 0}if(typeof e=="object"&&e!==null){let l={};for(let[n,o]of Object.entries(e)){let i=H(o,t?.[n],r);i!==void 0&&(l[n]=i)}return l}}function W(e,t,r){if(t!=null){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(typeof t!="object"||Array.isArray(t))return;let l=new Set(Object.keys(e));for(let n of Object.keys(t))l.has(n)?W(e[n],t[n],r):r.discarded+=$(t[n]);return}if(Array.isArray(e)&&Array.isArray(t)){let l=e[1];t.forEach(n=>W(l,n,r));return}typeof e=="string"&&!e.endsWith("[]")&&typeof t=="object"&&t!==null&&(r.discarded+=$(t))}}function $(e){return e==null?0:Array.isArray(e)?e.reduce((t,r)=>t+$(r),0):typeof e=="object"?Object.values(e).reduce((t,r)=>t+$(r),0):1}function It(e,t,r){let l=Te(e,t),n={carriedOver:0,discarded:0,listItems:0},o={},i=new Set;for(let{name:a,rules:s}of l){if(i.add(a),!Object.prototype.hasOwnProperty.call(r,a)){o[a]={carriedOver:0,discarded:0,listItems:0};continue}let{data:u,summary:c}=Ee(r[a],s);ft(e,t,s,u),o[a]=c,n.carriedOver+=c.carriedOver,n.discarded+=c.discarded,n.listItems+=c.listItems}for(let a of Object.keys(r))i.has(a)||(n.discarded+=$(r[a]));return{totals:n,byName:o,rulesTagCount:l.length}}async function Pt({sourceUrl:e,dataByName:t,fromVersion:r,doc:l,loc:n,fetchFn:o}={}){if(l=l||(typeof document<"u"?document:null),n=n||(typeof location<"u"?location:null),o=o||(p=>fetch(p)),!l)throw new Error("upgrade.run requires a document context");if(e=e||x(l,"hyper-source"),!e)throw new Error("upgrade.run: no sourceUrl given and no hyper-source meta tag found");let i=new URL(e,n?n.href:void 0);r=r!==void 0?r:x(l,"hyper-version"),t=t||Oe(C,l);let a;try{a=await o(i.href)}catch(p){throw new ae(i.href,p)}if(!a.ok)throw new ae(i.href,new Error(`HTTP ${a.status}`));let s=await a.text(),u=new DOMParser().parseFromString(s,"text/html"),c=x(u,"hyper-version"),f=t,d=!1,h=jt(C,u);if(h){let p=await(await Ut(h))(f,{fromVersion:r,toVersion:c});if(!p||typeof p!="object"||Array.isArray(p))throw new q("transform must return a plain object map of { rulesName: data }");f=p,d=!0}let{totals:m,byName:w,rulesTagCount:v}=It(C,u,f);if(v===0&&Object.keys(f).length>0)throw new $t(i.href);return{html:Bt(u),fromVersion:r,toVersion:c,summary:{transformApplied:d,totals:m,byName:w}}}function Dt(e){for(let t of e.querySelectorAll("input")){let r=(t.getAttribute("type")||"").toLowerCase();r!=="file"&&(r==="checkbox"||r==="radio"?t.checked!==t.hasAttribute("checked")&&t.toggleAttribute("checked",t.checked):t.value!==(t.getAttribute("value")??"")&&t.setAttribute("value",t.value))}for(let t of e.querySelectorAll("textarea"))t.value!==t.textContent&&(t.textContent=t.value);for(let t of e.querySelectorAll("select")){let r=[...t.options];if(!t.multiple){let l=r.findIndex(n=>n.hasAttribute("selected"));if(t.selectedIndex===l||l===-1&&t.selectedIndex<=0)continue}for(let l of r)l.selected!==l.hasAttribute("selected")&&l.toggleAttribute("selected",l.selected)}}function Bt(e){return Dt(e),`<!DOCTYPE ${e.doctype&&e.doctype.name?e.doctype.name:"html"}>
|
|
2
2
|
`+e.documentElement.outerHTML}var M={checkForUpdate:Nt,run:Pt,extractAll:Rt,shapeMatch:Ee};var A="The new version could not be downloaded. Nothing was changed.",U="The upgrade could not be saved. Nothing was changed.",Se="This document changed somewhere else. Reload and try again.",qt="Something else is changing this document. Nothing was changed.",Ht="This document does not say which parts are its data, so it cannot be upgraded safely. Nothing was changed.",Wt="The new version has no place for this page's content. Nothing was changed.";async function Vt(e){let t=globalThis.crypto&&globalThis.crypto.subtle;if(!t)return null;let r=await t.digest("SHA-256",e);return[...new Uint8Array(r)].map(l=>l.toString(16).padStart(2,"0")).join("")}async function Ne(e,t){try{let r=await e(t,{credentials:"omit"});return!r||!r.ok?null:r}catch{return null}}function Ft(e,t,r){if(e&&typeof e.latestUrl=="string"&&e.latestUrl)return e.latestUrl;let l=x(t,"hyper-source");if(!l)return null;try{let n=new URL(l,r?r.href:void 0);return n.pathname=n.pathname.replace(/\.html$/,".json"),n.href}catch{return null}}function zt(e){let t=x(e,"clay-template");if(!t)return null;let[r,l]=t.split(/\s+/);return r&&l?{id:r,variant:l}:null}function I(e,t="",r=[]){if(Array.isArray(e)){for(let l of e)I(l,`${t}[]`,r);return r}if(e&&typeof e=="object"){for(let[l,n]of Object.entries(e))I(n,t?`${t}.${l}`:l,r);return r}return e!=null&&r.push({path:t,value:e}),r}function _t(e,t){let r=[e];for(let l of String(t).split(".")){let n=l.endsWith("[]"),o=n?l.slice(0,-2):l,i=[];for(let a of r){let s=o?a?.[o]:a;n?Array.isArray(s)&&i.push(...s):i.push(s)}r=i}return r}function Jt(e,t,r={}){let l=new Map;for(let{path:o,value:i}of I(t)){let a=`${o}\0${String(i)}`;l.set(a,(l.get(a)||0)+1)}let n=[];for(let{path:o,value:i}of I(e)){let a=`${o}\0${String(i)}`;if(l.get(a)>0){l.set(a,l.get(a)-1);continue}let s=r[o];typeof s=="string"&&_t(t,s).some(u=>u===i)||n.push({path:o,value:i})}return n}async function Gt(e){let t=new Blob([e],{type:"text/javascript"}),r=URL.createObjectURL(t);try{return await new Function("url","return import(url)")(r)}finally{URL.revokeObjectURL(r)}}async function Yt(e){let r=new DOMParser().parseFromString(e,"text/html").querySelector('script[type="text/hyper-upgrade"]');if(!r)return{};let l=await Gt(r.textContent||"");return l&&l.renames&&typeof l.renames=="object"?l.renames:{}}var ke='script[clay~="live"][merge]';function Xt(e,t,r){let l=t.querySelector("article[data-page]");if(!l)return null;l.replaceWith(t.importNode(r,!0));for(let o of e.querySelectorAll(ke)){let i=o.getAttribute("merge");if(i!=="page"&&!i.startsWith("page."))continue;let a=t.importNode(o,!0),s=[...t.querySelectorAll(ke)].find(u=>u.getAttribute("merge")===i);s?s.replaceWith(a):t.querySelector("article[data-page]").after(a)}return(t.doctype?`<!DOCTYPE ${t.doctype.name}>
|
|
3
|
-
`:"")+t.documentElement.outerHTML}async function Re(e,{doc:t=document,loc:r=location,fetchFn:l=(n,o)=>fetch(n,o)}={}){if((typeof window<"u"&&window.clay||{}).isDraftMode)return{ok:!1,code:"draft"};if(!e||typeof e.version!="string")return{ok:!1,code:"unavailable",message:A};let o=Ft(e,t,r);if(!o)return{ok:!1,code:"unavailable",message:A};let i=await Ne(l,o);if(!i)return{ok:!1,code:"unavailable",message:A};let a;try{a=await i.json()}catch{return{ok:!1,code:"unavailable",message:A}}if(!a||typeof a!="object")return{ok:!1,code:"unavailable",message:A};let s=zt(t);if(!s||a.id!==s.id||a.variant!==s.variant)return{ok:!1,code:"template",message:"This upgrade is for a different document."};let u=x(t,"hyper-version");if(!u||typeof a.version!="string"||!J(a.version,u))return{ok:!1,code:"not-newer",message:"There is no newer version to install."};if(typeof a.html!="string"||!a.html)return{ok:!1,code:"unavailable",message:A};let c;try{c=new URL(a.html,o).href}catch{return{ok:!1,code:"unavailable",message:A}}if(!/^https:\/\/hyperclay\.com\/templates\//.test(c))return{ok:!1,code:"source",message:"This upgrade is not from the template host."};let f=await Ne(l,c);if(!f)return{ok:!1,code:"unavailable",message:A};let d;try{d=await f.text()}catch{return{ok:!1,code:"unavailable",message:A}}let h=await Vt(new TextEncoder().encode(d));if(!h||h!==String(a.sha256||"").toLowerCase())return{ok:!1,code:"unavailable",message:A};let m,w;try{w=await Yt(d),m=await M.run({sourceUrl:c,doc:t,loc:r,fromVersion:u,fetchFn:async()=>({ok:!0,status:200,text:async()=>d})})}catch(T){return{ok:!1,code:"transform",message:T&&T.message?T.message:A}}let v=new DOMParser().parseFromString(m.html,"text/html"),p=M.extractAll(t).dataByName,y=t.querySelector("article[data-page]");if(!y&&!Object.keys(p||{}).length)return{ok:!1,code:"undeclared",message:Ht};let g=m.html;if(y){let T=Xt(t,v,y);if(!T)return{ok:!1,code:"lost",lost:[],discarded:0,message:Wt};g=T}let b=M.extractAll(v).dataByName,E=Jt(p,b,w),N=m.summary&&m.summary.totals&&m.summary.totals.discarded||0;return E.length||N>0?{ok:!1,code:"lost",lost:E,discarded:N,message:Kt(E,N)}:{ok:!0,html:g,version:m.toVersion||a.version}}function Kt(e,t){let r=e.slice(0,5).map(({path:n})=>n),l=e.length>r.length?` and ${e.length-r.length} more`:"";return r.length?`This upgrade would lose data: ${r.join(", ")}${l}. Nothing was changed.`:`This upgrade would lose ${t} value${t===1?"":"s"}. Nothing was changed.`}function Zt(e){let t=e&&e.state;if(t==="conflict")return{ok:!1,code:"conflict",message:Se};let r=e&&e.message?e.message:"The document could not be saved.";return{ok:!1,code:"flush",state:t||"failed",message:r}}async function $e(e,{doc:t=document,loc:r=location,fetchFn:l=(s,u)=>fetch(s,u),clay:n=typeof window<"u"?window.clay:null,reload:o=()=>window.location.reload(),replace:i=null,etag:a}={}){if((n||{}).isDraftMode)return{ok:!1,code:"draft"};let u=z("upgrade");if(!u)return{ok:!1,code:"busy",message:qt};try{return await Qt(e,{doc:t,loc:r,fetchFn:l,clay:n,reload:o,replace:i,etag:a})}finally{_(u)}}async function Qt(e,{doc:t,loc:r,fetchFn:l,clay:n,reload:o,replace:i,etag:a}){let s=n||{};if(s.isEditMode&&s.save&&typeof s.save.flush=="function"){let h;try{h=await s.save.flush()}catch(m){return Zt(m)}if(h&&typeof h.state=="string"&&h.state!=="saved"&&h.state!=="clean"&&h.state!=="view")return{ok:!1,code:"flush",state:h.state,message:"This document has changes that could not be saved. Nothing was changed."}}let u=t;if(s.isEditMode&&typeof s.getHTML=="function")try{u=new DOMParser().parseFromString(await s.getHTML(),"text/html")}catch{return{ok:!1,code:"failed",message:U}}let c=await Re(e,{doc:u,loc:r,fetchFn:l});if(!c.ok)return c;let f=typeof i=="function"?i:s.save&&typeof s.save.replace=="function"?s.save.replace:G,d;try{d=await f(c.html,{etag:a!==void 0?a:F()})}catch{return{ok:!1,code:"failed",message:U}}if(!d||!d.ok){let h=d&&d.code?d.code:"failed";return h==="conflict"?{ok:!1,code:h,message:Se}:h==="forbidden"?{ok:!1,code:h,message:"You are not allowed to save this document."}:h==="unsupported"?{ok:!1,code:h,message:"This host cannot save the upgrade."}:{ok:!1,code:h,message:U}}return o(),{ok:!0,html:c.html,version:c.version,etag:d.etag}}function O(e,t,r={}){let l=e.createElement(t);l.setAttribute("clay","editor-ui");for(let[n,o]of Object.entries(r))n==="style"?l.setAttribute("style",o):n==="text"?l.textContent=o:l.setAttribute(n,o);return l}function er(e){let r=(e&&e.pathname?e.pathname:"/").split("/").filter(Boolean).pop()||"page.html";try{r=decodeURIComponent(r)}catch{}return/\.html?$/i.test(r)?r:`${r}.html`}async function tr(e,{loc:t=location,fetchFn:r=(l,n)=>fetch(l,n)}={}){if(typeof e.getHTML=="function")return e.getHTML();let l=await r(t.href,{cache:"no-store",credentials:"same-origin"});if(!l.ok)throw new Error(`copy fetch ${l.status}`);return l.text()}async function rr({clay:e,doc:t=document,loc:r=location,fetchFn:l}={}){if(typeof URL>"u"||typeof URL.createObjectURL!="function")return!1;try{let n=await tr(e,{loc:r,fetchFn:l})
|
|
3
|
+
`:"")+t.documentElement.outerHTML}async function Re(e,{doc:t=document,loc:r=location,fetchFn:l=(n,o)=>fetch(n,o)}={}){if((typeof window<"u"&&window.clay||{}).isDraftMode)return{ok:!1,code:"draft"};if(!e||typeof e.version!="string")return{ok:!1,code:"unavailable",message:A};let o=Ft(e,t,r);if(!o)return{ok:!1,code:"unavailable",message:A};let i=await Ne(l,o);if(!i)return{ok:!1,code:"unavailable",message:A};let a;try{a=await i.json()}catch{return{ok:!1,code:"unavailable",message:A}}if(!a||typeof a!="object")return{ok:!1,code:"unavailable",message:A};let s=zt(t);if(!s||a.id!==s.id||a.variant!==s.variant)return{ok:!1,code:"template",message:"This upgrade is for a different document."};let u=x(t,"hyper-version");if(!u||typeof a.version!="string"||!J(a.version,u))return{ok:!1,code:"not-newer",message:"There is no newer version to install."};if(typeof a.html!="string"||!a.html)return{ok:!1,code:"unavailable",message:A};let c;try{c=new URL(a.html,o).href}catch{return{ok:!1,code:"unavailable",message:A}}if(!/^https:\/\/hyperclay\.com\/templates\//.test(c))return{ok:!1,code:"source",message:"This upgrade is not from the template host."};let f=await Ne(l,c);if(!f)return{ok:!1,code:"unavailable",message:A};let d;try{d=await f.text()}catch{return{ok:!1,code:"unavailable",message:A}}let h=await Vt(new TextEncoder().encode(d));if(!h||h!==String(a.sha256||"").toLowerCase())return{ok:!1,code:"unavailable",message:A};let m,w;try{w=await Yt(d),m=await M.run({sourceUrl:c,doc:t,loc:r,fromVersion:u,fetchFn:async()=>({ok:!0,status:200,text:async()=>d})})}catch(T){return{ok:!1,code:"transform",message:T&&T.message?T.message:A}}let v=new DOMParser().parseFromString(m.html,"text/html"),p=M.extractAll(t).dataByName,y=t.querySelector("article[data-page]");if(!y&&!Object.keys(p||{}).length)return{ok:!1,code:"undeclared",message:Ht};let g=m.html;if(y){let T=Xt(t,v,y);if(!T)return{ok:!1,code:"lost",lost:[],discarded:0,message:Wt};g=T}let b=M.extractAll(v).dataByName,E=Jt(p,b,w),N=m.summary&&m.summary.totals&&m.summary.totals.discarded||0;return E.length||N>0?{ok:!1,code:"lost",lost:E,discarded:N,message:Kt(E,N)}:{ok:!0,html:g,version:m.toVersion||a.version}}function Kt(e,t){let r=e.slice(0,5).map(({path:n})=>n),l=e.length>r.length?` and ${e.length-r.length} more`:"";return r.length?`This upgrade would lose data: ${r.join(", ")}${l}. Nothing was changed.`:`This upgrade would lose ${t} value${t===1?"":"s"}. Nothing was changed.`}function Zt(e){let t=e&&e.state;if(t==="conflict")return{ok:!1,code:"conflict",message:Se};let r=e&&e.message?e.message:"The document could not be saved.";return{ok:!1,code:"flush",state:t||"failed",message:r}}async function $e(e,{doc:t=document,loc:r=location,fetchFn:l=(s,u)=>fetch(s,u),clay:n=typeof window<"u"?window.clay:null,reload:o=()=>window.location.reload(),replace:i=null,etag:a}={}){if((n||{}).isDraftMode)return{ok:!1,code:"draft"};let u=z("upgrade");if(!u)return{ok:!1,code:"busy",message:qt};try{return await Qt(e,{doc:t,loc:r,fetchFn:l,clay:n,reload:o,replace:i,etag:a})}finally{_(u)}}async function Qt(e,{doc:t,loc:r,fetchFn:l,clay:n,reload:o,replace:i,etag:a}){let s=n||{};if(s.isEditMode&&s.save&&typeof s.save.flush=="function"){let h;try{h=await s.save.flush()}catch(m){return Zt(m)}if(h&&typeof h.state=="string"&&h.state!=="saved"&&h.state!=="clean"&&h.state!=="view")return{ok:!1,code:"flush",state:h.state,message:"This document has changes that could not be saved. Nothing was changed."}}let u=t;if(s.isEditMode&&typeof s.getHTML=="function")try{u=new DOMParser().parseFromString(await s.getHTML(),"text/html")}catch{return{ok:!1,code:"failed",message:U}}let c=await Re(e,{doc:u,loc:r,fetchFn:l});if(!c.ok)return c;let f=typeof i=="function"?i:s.save&&typeof s.save.replace=="function"?s.save.replace:G,d;try{d=await f(c.html,{etag:a!==void 0?a:F()})}catch{return{ok:!1,code:"failed",message:U}}if(!d||!d.ok){let h=d&&d.code?d.code:"failed";return h==="conflict"?{ok:!1,code:h,message:Se}:h==="forbidden"?{ok:!1,code:h,message:"You are not allowed to save this document."}:h==="unsupported"?{ok:!1,code:h,message:"This host cannot save the upgrade."}:{ok:!1,code:h,message:U}}return o(),{ok:!0,html:c.html,version:c.version,etag:d.etag}}function O(e,t,r={}){let l=e.createElement(t);l.setAttribute("clay","editor-ui");for(let[n,o]of Object.entries(r))n==="style"?l.setAttribute("style",o):n==="text"?l.textContent=o:l.setAttribute(n,o);return l}function er(e){let r=(e&&e.pathname?e.pathname:"/").split("/").filter(Boolean).pop()||"page.html";try{r=decodeURIComponent(r)}catch{}return/\.html?$/i.test(r)?r:`${r}.html`}async function tr(e,{loc:t=location,fetchFn:r=(l,n)=>fetch(l,n)}={}){if(typeof e.getHTML=="function")return e.getHTML();let l=await r(t.href,{cache:"no-store",credentials:"same-origin"});if(!l.ok)throw new Error(`copy fetch ${l.status}`);return l.text()}async function rr({clay:e,doc:t=document,loc:r=location,fetchFn:l}={}){if(typeof URL>"u"||typeof URL.createObjectURL!="function")return!1;try{let n=await tr(e,{loc:r,fetchFn:l});if(typeof n=="string"&&/clay|data-paid-only/i.test(n)){let{stripCopyContent:a}=await import("./c-C4IIQZGJ.js");n=a(n)}let o=URL.createObjectURL(new Blob([n],{type:"text/html"})),i=t.createElement("a");return i.setAttribute("clay","editor-ui"),i.href=o,i.download=er(r),i.style.setProperty("display","none","important"),t.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(o),4e4),!0}catch{return!1}}async function nr(e){let t=e&&e.host;if(!t||!t.versions)return!1;try{return await t.versions===!0}catch{return!1}}async function lr(e,t={}){let r=t.doc||document,l=t.clay||(typeof window<"u"?window.clay:null)||{};if(l.isDraftMode||!e||typeof e.version!="string")return null;let n=await nr(l),o=O(r,"div",{role:"dialog","aria-modal":"true","data-clay-upgrade":"",style:"position:fixed;inset:0;z-index:2147483000;display:flex;align-items:center;justify-content:center;padding:16px;background:rgba(15,17,21,.42);font-family:system-ui,-apple-system,'Segoe UI',sans-serif;"}),i=O(r,"div",{style:"width:min(460px,100%);padding:20px;border-radius:14px;background:var(--clay-ui-bg,#fff);color:var(--clay-ui-fg,#1f2328);box-shadow:0 18px 48px -16px rgba(0,0,0,.55);font-size:14px;line-height:1.5;"}),a=O(r,"h2",{text:`Upgrade to version ${e.version}`,style:"margin:0 0 8px;font-size:16px;"}),s=O(r,"p",{text:`Your data moves into version ${e.version}. The page's layout and code are replaced; your current version stays in this document's history.`,style:"margin:0 0 16px;"}),u=O(r,"p",{role:"status",style:"margin:0 0 12px;min-height:1.5em;"}),c=O(r,"div",{style:"display:flex;flex-wrap:wrap;gap:8px;justify-content:flex-end;"}),f="padding:7px 12px;border-radius:8px;border:1px solid rgba(23,28,36,.2);background:transparent;color:inherit;font:inherit;cursor:pointer;",d=O(r,"button",{type:"button",text:"Cancel",style:f}),h=n?null:O(r,"button",{type:"button",text:"Download a copy first",style:f}),m=O(r,"button",{type:"button",text:"Upgrade",style:`${f}border-color:transparent;background:#2f6fed;color:#fff;font-weight:600;`});n||(m.disabled=!0),h&&c.append(h),c.append(d,m),i.append(a,s,u,c),o.append(i),r.body.appendChild(o);let w=!1,v=()=>{w||(w=!0,o.remove())};h&&h.addEventListener("click",async()=>{await rr({clay:l,doc:r,loc:t.loc,fetchFn:t.fetchFn})?(m.disabled=!1,u.textContent="Your copy was downloaded."):u.textContent="The copy could not be downloaded. Nothing was changed."}),d.addEventListener("click",v);let p,y=new Promise(g=>{p=g});return m.addEventListener("click",async()=>{m.disabled=!0,h&&(h.disabled=!0),u.textContent=`Upgrading to version ${e.version}\u2026`;let g=await $e(e,t);if(g.ok){v(),p(g);return}u.textContent=g.message||U,m.disabled=!1,h&&(h.disabled=!1),p(g)}),{root:o,title:a,body:s,status:u,cancel:d,download:h,upgrade:m,close:v,done:y}}export{$e as apply,Re as prepare,lr as start};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as p}from"./c-XGH4GS2T.js";import{f as u}from"./c-3O7OBDCM.js";var d=window.__clayWorkspaceBackground===!0;document.addEventListener("clay:workspace-background",()=>{d=!0});document.addEventListener("clay:workspace-foreground",()=>{d=!1});var a=()=>document.hidden||d,m=class extends EventTarget{constructor(e,{shared:t=!1,sharedData:i=!1,documentURL:n,lane:s,clientId:o,startupCheck:c=!1,keepAliveWhenHidden:v=!1}={}){super(),this.url=e,this.readyState=0,this.onopen=null,this.onmessage=null,this.onerror=null,this._shared=t&&typeof SharedWorker=="function",this._sharedData=i,this._documentURL=n,this._lane=s,this._clientId=o,this._keepAliveWhenHidden=v,this._since=0,this._closed=!1,this._suspended=!1,this._repair=!1,this._startup=c,this._worker=null,this._source=null,this._visibility=()=>{clearTimeout(this._hiddenTimer),a()?(this._worker&&this._postWorker(this._worker,"hidden"),this._keepAliveWhenHidden||(this._hiddenTimer=setTimeout(()=>this._suspend(),5e3))):this._suspended?this._resume():this._worker&&this._postWorker(this._worker,"visible")},this._pagehide=()=>this._suspend(!0),this._pageshow=()=>{(!a()||this._keepAliveWhenHidden)&&this._resume()},document.addEventListener("visibilitychange",this._visibility),document.addEventListener("clay:workspace-background",this._visibility),document.addEventListener("clay:workspace-foreground",this._visibility),window.addEventListener("pagehide",this._pagehide),window.addEventListener("pageshow",this._pageshow),this._open(),a()&&this._visibility()}_emit(e,t){if(this._closed)return;let i=t===void 0?new Event(e):new MessageEvent(e,{data:t});this.dispatchEvent(i),this[`on${e}`]?.(i)}_postWorker(e,t,i={}){e.port.postMessage({v:this._sharedData?2:1,type:t,...i})}_open(){if(!(this._closed||this._suspended)){if(this.readyState=0,!this._shared)return this._openDirect();try{let e=new SharedWorker(new URL(this._sharedData?"/_/sync/data-worker.js":"/_/sync/worker.js",window.location.origin).href,this._sharedData?"clay-sync-data":"clay-sync");this._worker=e;let t=Date.now(),i=!1;e.onerror=()=>{this._worker===e&&(this._shared=!1,this._repair=!0,this._reopen())},this._startTimer=setTimeout(e.onerror,5e3),e.port.onmessage=({data:s})=>{if(!(this._worker!==e||s?.v!==(this._sharedData?2:1))){if(this._sharedData){if(s.type==="unsupported"){e.onerror();return}if(s.type==="gone"){this.readyState=2,this._emit("error"),this.close();return}if(!i){if(s.type!=="hello")return;if(!Array.isArray(s.features)||!s.features.includes("live-data")){e.onerror();return}i=!0,clearTimeout(this._startTimer),t=Date.now();return}if(s.type==="hello")return}if(t=Date.now(),!this._sharedData&&["status","pong","cursor","frame","gone"].includes(s.type)&&clearTimeout(this._startTimer),s.type==="status")s.state==="open"?(!this._sharedData||this.readyState!==1)&&(this.readyState=1,this._emit("open")):s.state==="connecting"&&(this.readyState=0,this._emit("error"));else if(s.type==="cursor"){clearTimeout(this._startTimer),Number.isSafeInteger(s.seq)&&(this._since=Math.max(this._since,s.seq));let o=s.resync===!0||this._repair,c=this._startup;this._repair=!1,this._startup=!1,this._emit("cursor",JSON.stringify({...s,resync:o,startup:c}))}else if(s.type==="frame"&&typeof s.data=="string")this._remember(s.data),this._emit("message",s.data);else if(this._sharedData&&s.type==="event"&&["data","data-state","data-writer"].includes(s.event)&&s.data!==null&&typeof s.data=="object"&&!Array.isArray(s.data))try{this._emit(s.event,JSON.stringify(s.data))}catch{}else s.type==="gone"&&(this.readyState=2,this._emit("error"),this.close())}},e.port.start(),this._postWorker(e,a()?"hidden":"visible");let n={document:this._documentURL,lane:this._lane,since:this._since};this._sharedData&&this._lane==="live"&&(n.clientId=this._clientId),this._postWorker(e,"subscribe",n),this._pingTimer=setInterval(()=>{this._worker===e&&(Date.now()-t>15e3*3?(this._repair=!0,this._reopen()):this._postWorker(e,"ping"))},15e3)}catch{this._shared=!1,this._reopen()}}}_openDirect(){let e=new EventSource(this.url);this._source=e,e.onopen=()=>{if(this._source===e&&(this.readyState=1,this._emit("open"),this._repair||this._startup)){let t=this._repair,i=this._startup;this._repair=!1,this._startup=!1,this._emit("cursor",JSON.stringify({resync:t,startup:i}))}},e.onerror=()=>{this._source===e&&(this.readyState=e.readyState,this._emit("error"))},e.onmessage=t=>{this._source===e&&(this._remember(t.data),this._emit("message",t.data))};for(let t of["cursor","presence","data","data-state","data-writer"])e.addEventListener(t,i=>{this._source===e&&this._emit(t,i.data)})}_remember(e){try{let{seq:t}=JSON.parse(e);Number.isSafeInteger(t)&&(this._since=Math.max(this._since,t))}catch{}}_disconnect(){if(clearTimeout(this._startTimer),clearInterval(this._pingTimer),this._worker){let e=this._worker;this._worker=null,e.onerror=null,e.port.onmessage=null;try{this._postWorker(e,"unsubscribe")}catch{}e.port.close()}this._source&&(this._source.close(),this._source=null)}_reopen(){let e=(this._sharedData||this._keepAliveWhenHidden)&&this.readyState===1;this.readyState=0,e&&this._emit("error"),this._disconnect(),this._open()}_suspend(e=!1){clearTimeout(this._hiddenTimer),!(this._closed||this._suspended)&&(this._suspended=!0,this._repair=!0,this.readyState=0,e&&this._keepAliveWhenHidden&&this._emit("error"),this._disconnect())}_resume(){clearTimeout(this._hiddenTimer),!(this._closed||!this._suspended)&&(this._suspended=!1,this._open())}close(){this._closed=!0,this.readyState=2,clearTimeout(this._hiddenTimer),this._disconnect(),document.removeEventListener("visibilitychange",this._visibility),document.removeEventListener("clay:workspace-background",this._visibility),document.removeEventListener("clay:workspace-foreground",this._visibility),window.removeEventListener("pagehide",this._pagehide),window.removeEventListener("pageshow",this._pageshow)}};var f="This document was upgraded.",h=!1;function l(r,e){let t=r.querySelector(`meta[name="${e}"]`),i=t?t.getAttribute("content"):null;return i&&i.trim()?i.trim():null}function g(r=document){return l(r,"hyper-version")}function w(r){return typeof r!="string"||!r.includes("hyper-version")?null:l(new DOMParser().parseFromString(r,"text/html"),"hyper-version")}function y(r){let e=g();return!!e&&!!r&&r!==e}function T(r){return h?!0:y(w(r))}function D(r){return h?!0:!r||typeof r.querySelector!="function"?!1:y(l(r,"hyper-version"))}function S(){if(h)return Promise.resolve();h=!0;let r=u?import("./core/save-
|
|
1
|
+
import{d as p}from"./c-XGH4GS2T.js";import{f as u}from"./c-3O7OBDCM.js";var d=window.__clayWorkspaceBackground===!0;document.addEventListener("clay:workspace-background",()=>{d=!0});document.addEventListener("clay:workspace-foreground",()=>{d=!1});var a=()=>document.hidden||d,m=class extends EventTarget{constructor(e,{shared:t=!1,sharedData:i=!1,documentURL:n,lane:s,clientId:o,startupCheck:c=!1,keepAliveWhenHidden:v=!1}={}){super(),this.url=e,this.readyState=0,this.onopen=null,this.onmessage=null,this.onerror=null,this._shared=t&&typeof SharedWorker=="function",this._sharedData=i,this._documentURL=n,this._lane=s,this._clientId=o,this._keepAliveWhenHidden=v,this._since=0,this._closed=!1,this._suspended=!1,this._repair=!1,this._startup=c,this._worker=null,this._source=null,this._visibility=()=>{clearTimeout(this._hiddenTimer),a()?(this._worker&&this._postWorker(this._worker,"hidden"),this._keepAliveWhenHidden||(this._hiddenTimer=setTimeout(()=>this._suspend(),5e3))):this._suspended?this._resume():this._worker&&this._postWorker(this._worker,"visible")},this._pagehide=()=>this._suspend(!0),this._pageshow=()=>{(!a()||this._keepAliveWhenHidden)&&this._resume()},document.addEventListener("visibilitychange",this._visibility),document.addEventListener("clay:workspace-background",this._visibility),document.addEventListener("clay:workspace-foreground",this._visibility),window.addEventListener("pagehide",this._pagehide),window.addEventListener("pageshow",this._pageshow),this._open(),a()&&this._visibility()}_emit(e,t){if(this._closed)return;let i=t===void 0?new Event(e):new MessageEvent(e,{data:t});this.dispatchEvent(i),this[`on${e}`]?.(i)}_postWorker(e,t,i={}){e.port.postMessage({v:this._sharedData?2:1,type:t,...i})}_open(){if(!(this._closed||this._suspended)){if(this.readyState=0,!this._shared)return this._openDirect();try{let e=new SharedWorker(new URL(this._sharedData?"/_/sync/data-worker.js":"/_/sync/worker.js",window.location.origin).href,this._sharedData?"clay-sync-data":"clay-sync");this._worker=e;let t=Date.now(),i=!1;e.onerror=()=>{this._worker===e&&(this._shared=!1,this._repair=!0,this._reopen())},this._startTimer=setTimeout(e.onerror,5e3),e.port.onmessage=({data:s})=>{if(!(this._worker!==e||s?.v!==(this._sharedData?2:1))){if(this._sharedData){if(s.type==="unsupported"){e.onerror();return}if(s.type==="gone"){this.readyState=2,this._emit("error"),this.close();return}if(!i){if(s.type!=="hello")return;if(!Array.isArray(s.features)||!s.features.includes("live-data")){e.onerror();return}i=!0,clearTimeout(this._startTimer),t=Date.now();return}if(s.type==="hello")return}if(t=Date.now(),!this._sharedData&&["status","pong","cursor","frame","gone"].includes(s.type)&&clearTimeout(this._startTimer),s.type==="status")s.state==="open"?(!this._sharedData||this.readyState!==1)&&(this.readyState=1,this._emit("open")):s.state==="connecting"&&(this.readyState=0,this._emit("error"));else if(s.type==="cursor"){clearTimeout(this._startTimer),Number.isSafeInteger(s.seq)&&(this._since=Math.max(this._since,s.seq));let o=s.resync===!0||this._repair,c=this._startup;this._repair=!1,this._startup=!1,this._emit("cursor",JSON.stringify({...s,resync:o,startup:c}))}else if(s.type==="frame"&&typeof s.data=="string")this._remember(s.data),this._emit("message",s.data);else if(this._sharedData&&s.type==="event"&&["data","data-state","data-writer"].includes(s.event)&&s.data!==null&&typeof s.data=="object"&&!Array.isArray(s.data))try{this._emit(s.event,JSON.stringify(s.data))}catch{}else s.type==="gone"&&(this.readyState=2,this._emit("error"),this.close())}},e.port.start(),this._postWorker(e,a()?"hidden":"visible");let n={document:this._documentURL,lane:this._lane,since:this._since};this._sharedData&&this._lane==="live"&&(n.clientId=this._clientId),this._postWorker(e,"subscribe",n),this._pingTimer=setInterval(()=>{this._worker===e&&(Date.now()-t>15e3*3?(this._repair=!0,this._reopen()):this._postWorker(e,"ping"))},15e3)}catch{this._shared=!1,this._reopen()}}}_openDirect(){let e=new EventSource(this.url);this._source=e,e.onopen=()=>{if(this._source===e&&(this.readyState=1,this._emit("open"),this._repair||this._startup)){let t=this._repair,i=this._startup;this._repair=!1,this._startup=!1,this._emit("cursor",JSON.stringify({resync:t,startup:i}))}},e.onerror=()=>{this._source===e&&(this.readyState=e.readyState,this._emit("error"))},e.onmessage=t=>{this._source===e&&(this._remember(t.data),this._emit("message",t.data))};for(let t of["cursor","presence","data","data-state","data-writer"])e.addEventListener(t,i=>{this._source===e&&this._emit(t,i.data)})}_remember(e){try{let{seq:t}=JSON.parse(e);Number.isSafeInteger(t)&&(this._since=Math.max(this._since,t))}catch{}}_disconnect(){if(clearTimeout(this._startTimer),clearInterval(this._pingTimer),this._worker){let e=this._worker;this._worker=null,e.onerror=null,e.port.onmessage=null;try{this._postWorker(e,"unsubscribe")}catch{}e.port.close()}this._source&&(this._source.close(),this._source=null)}_reopen(){let e=(this._sharedData||this._keepAliveWhenHidden)&&this.readyState===1;this.readyState=0,e&&this._emit("error"),this._disconnect(),this._open()}_suspend(e=!1){clearTimeout(this._hiddenTimer),!(this._closed||this._suspended)&&(this._suspended=!0,this._repair=!0,this.readyState=0,e&&this._keepAliveWhenHidden&&this._emit("error"),this._disconnect())}_resume(){clearTimeout(this._hiddenTimer),!(this._closed||!this._suspended)&&(this._suspended=!1,this._open())}close(){this._closed=!0,this.readyState=2,clearTimeout(this._hiddenTimer),this._disconnect(),document.removeEventListener("visibilitychange",this._visibility),document.removeEventListener("clay:workspace-background",this._visibility),document.removeEventListener("clay:workspace-foreground",this._visibility),window.removeEventListener("pagehide",this._pagehide),window.removeEventListener("pageshow",this._pageshow)}};var f="This document was upgraded.",h=!1;function l(r,e){let t=r.querySelector(`meta[name="${e}"]`),i=t?t.getAttribute("content"):null;return i&&i.trim()?i.trim():null}function g(r=document){return l(r,"hyper-version")}function w(r){return typeof r!="string"||!r.includes("hyper-version")?null:l(new DOMParser().parseFromString(r,"text/html"),"hyper-version")}function y(r){let e=g();return!!e&&!!r&&r!==e}function T(r){return h?!0:y(w(r))}function D(r){return h?!0:!r||typeof r.querySelector!="function"?!1:y(l(r,"hyper-version"))}function S(){if(h)return Promise.resolve();h=!0;let r=u?import("./core/save-AOJBDSOK.js").then(i=>i.holdAllSaves(f),()=>{}):Promise.resolve(),e=new CustomEvent("clay:document-upgraded",{detail:{message:f}}),t=u?Promise.resolve():import("./c-K76AUL4I.js").then(i=>i.start(e),()=>{});return document.dispatchEvent(e),Promise.all([r,t]).then(()=>{})}var _={spec:{name:"spec",relayPath:"/_/sync",documentHeader:"Document-URL",snapshotKey:"snapshot",streamPath:(r,e,t,i)=>`/_/sync?document-url=${encodeURIComponent(r)}&lane=${e}&resume-id=${t}&client-id=${encodeURIComponent(i)}`},legacy:{name:"legacy",relayPath:"/_/live-sync/save",documentHeader:"Page-URL",snapshotKey:"html",streamPath:(r,e,t,i)=>`/_/live-sync/stream?page-url=${encodeURIComponent(r)}&lane=${e}&resume-id=${t}&client-id=${encodeURIComponent(i)}`}};function I(){return p().then(r=>{let e=r?.extensions||[],t=e.includes("sync"),i=e.includes("live-data"),n=e.includes("presence"),s=t&&i&&e.includes("sync-worker-data")&&!n,o=t&&!n&&(s||e.includes("sync-worker")&&!i);return{profile:t?_.spec:_.legacy,sharedSync:o,sharedData:s,liveData:i}}).catch(()=>({profile:_.legacy,sharedSync:!1,sharedData:!1,liveData:!1}))}export{m as a,T as b,D as c,S as d,_ as e,I as f};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var o=null,n=()=>o??=import("./c-
|
|
1
|
+
var o=null,n=()=>o??=import("./c-MIL4B2JQ.js"),s=t=>(...i)=>{n().then(e=>(t?e[t]:e.default)(...i))},l=s(null),r=s("toastPersistent"),a=(...t)=>{o&&s("dismissPersistent")(...t)};export{l as a,r as b,a as c};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as a}from"./c-PZ4XEPUP.js";import{K as u}from"./c-
|
|
1
|
+
import{b as a}from"./c-PZ4XEPUP.js";import{K as u}from"./c-EGTIAL6P.js";import"./c-XQXZAO7N.js";import"./c-S7LK4KUE.js";import"./c-VG5XIN4T.js";import"./c-2YYDMLNZ.js";import{i as s}from"./c-HA6INT6J.js";import"./c-ICMAOOGK.js";import"./c-WRBKEJD4.js";import"./c-VHNSBD2M.js";var d=20,i=null,l=!1,c=[];function h(){i||l||(l=!0,import("./c-OIDRZKAF.js").then(e=>{i=e,l=!1,f()},e=>{l=!1,console.error("clayjs: the conflict recovery module could not be downloaded; conflicts stay in this tab only",e)}))}function f(){if(!i){h();return}for(;c.length;){let e=c.shift();try{i.recordConflicts(e)}catch(o){console.error("clayjs: the conflict could not be stored for a later reload; it is still here",o)}}}function m(e,o){let t=null;try{t=a(e)}catch{}let n=r=>r?(r.cutBefore?"\u2026":"")+r.before+r.hit+r.after+(r.cutAfter?"\u2026":""):"";return{id:String(e.id),kind:String(e.kind??""),key:e.recovery?.key==null?"":String(e.recovery.key),name:t?.name?String(t.name):"",sentence:t?.sentence?String(t.sentence):"",yours:n(t?.yours),now:n(t?.now),context:o}}function y(e){try{let t=(e.recoveryRoot??e.root)?.cloneNode?.(!0);if(!t)return null;for(let n of s)t.removeAttribute(n);return u(t,{prepared:e.domain==="save"})}catch(o){return console.error("clayjs: the conflict recovery page could not be serialized; the conflict text is still stored",o),null}}function k({apply:e,records:o}){try{c.push({apply:{id:e.id,source:e.source,domain:e.domain,seq:e.seq,etag:e.etag,ticket:e.ticket},root:y(e),conflicts:o.map(({rec:t,context:n})=>m(t,n))}),c.length>d&&c.shift(),f()}catch(t){console.error("clayjs: the conflict could not be stored for a later reload; it is still here",t)}}function A(e){import("./c-OIDRZKAF.js").then(o=>o.dismissConflicts(e),()=>{}).catch(()=>{})}export{A as dismiss,k as keep};
|