graview 0.1.64 → 0.1.65
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/preview/chunk.2P34ML3O.js +111 -0
- package/dist/preview/{chunk.77JI5T4F.js → chunk.2PK335JQ.js} +1 -1
- package/dist/preview/{chunk.YEXFVDRA.js → chunk.2QQ37RCZ.js} +1 -1
- package/dist/preview/{chunk.YIZPW7IK.js → chunk.2TZSLREX.js} +2 -2
- package/dist/preview/chunk.2UW5CRHF.js +1 -0
- package/dist/preview/{chunk.X36BYTEG.js → chunk.2YMO7ZVX.js} +1 -1
- package/dist/preview/chunk.33ULA3CG.js +1 -0
- package/dist/preview/{chunk.WX23K7ZU.js → chunk.35E75QJ7.js} +1 -1
- package/dist/preview/chunk.3CJLAJXP.js +25 -0
- package/dist/preview/chunk.3IJSB5ET.js +1 -0
- package/dist/preview/{chunk.BVIJXL4J.js → chunk.3IZEZPJB.js} +1 -1
- package/dist/preview/chunk.3KO35VN4.js +1 -0
- package/dist/preview/{chunk.UDU545CL.js → chunk.3KUYB5ZT.js} +1 -1
- package/dist/preview/chunk.3RFAUIGT.js +1 -0
- package/dist/preview/{chunk.DN7UCBOA.js → chunk.3WP66LB5.js} +1 -1
- package/dist/preview/{chunk.VZAF3452.js → chunk.44ZHHPPJ.js} +2 -2
- package/dist/preview/chunk.4GJ7F4SP.js +35 -0
- package/dist/preview/{chunk.7ZG77OI3.js → chunk.4IJTPV5X.js} +1 -1
- package/dist/preview/{chunk.HPG6CNKM.js → chunk.4JFBLVXJ.js} +1 -1
- package/dist/preview/{chunk.P6FNJR6E.js → chunk.4O3C2LJF.js} +1 -1
- package/dist/preview/chunk.4PCVQEVI.js +1 -0
- package/dist/preview/{chunk.T4JP6BGP.js → chunk.5FQSYMAE.js} +1 -1
- package/dist/preview/chunk.5M34BJIQ.js +1 -0
- package/dist/preview/chunk.5NCLZ4NZ.js +1 -0
- package/dist/preview/{chunk.5B7NG6WH.js → chunk.5THLLSS4.js} +1 -1
- package/dist/preview/chunk.5YNLFOBJ.js +5 -0
- package/dist/preview/{chunk.2JEN2RCB.js → chunk.64FCAUAJ.js} +1 -1
- package/dist/preview/chunk.6RZHKQP3.js +1 -0
- package/dist/preview/chunk.6YDC6IDA.js +1 -0
- package/dist/preview/{chunk.F6BNFLQM.js → chunk.74B6KQF4.js} +1 -1
- package/dist/preview/chunk.77XQEDT5.js +1 -0
- package/dist/preview/chunk.7E4CSXBT.js +1 -0
- package/dist/preview/chunk.7HPQI5SY.js +1 -0
- package/dist/preview/{chunk.JOM6MFVE.js → chunk.7IGD2K4M.js} +1 -1
- package/dist/preview/{chunk.4U45EY5M.js → chunk.7Q43N5JS.js} +1 -1
- package/dist/preview/{chunk.B6JR7EQO.js → chunk.7VQ3C7F4.js} +1 -1
- package/dist/preview/{chunk.DMENNIHT.js → chunk.A4VA3DU5.js} +1 -1
- package/dist/preview/{chunk.2JDAUKSN.js → chunk.AB4RZSYW.js} +31 -23
- package/dist/preview/chunk.ABSY3UZF.js +1 -0
- package/dist/preview/chunk.ARHAD5IS.js +1 -0
- package/dist/preview/chunk.BOC2EOGB.js +9 -0
- package/dist/preview/chunk.BR6TINGU.js +1 -0
- package/dist/preview/{chunk.4DZOAB4D.js → chunk.BU5PVRX7.js} +1 -1
- package/dist/preview/{chunk.4VRX7FCO.js → chunk.BUQKRXI6.js} +1 -1
- package/dist/preview/{chunk.S7SHWDPR.js → chunk.C437FVD7.js} +1 -1
- package/dist/preview/{chunk.YMXWS4XN.js → chunk.CD6YWH6T.js} +1 -1
- package/dist/preview/chunk.CDEAAWPS.js +1 -0
- package/dist/preview/{chunk.NGRL3QOI.js → chunk.CGQ6KXVK.js} +1 -1
- package/dist/preview/{chunk.YSBTE3PX.js → chunk.CPYBJNHP.js} +1 -1
- package/dist/preview/{chunk.REXU6ARY.js → chunk.CS72MISN.js} +2 -2
- package/dist/preview/chunk.CXJJB3MK.js +1 -0
- package/dist/preview/{chunk.TYIBLD2D.js → chunk.CXLQPE4J.js} +1 -1
- package/dist/preview/{chunk.75JQCTR6.js → chunk.DA4RSHLW.js} +1 -1
- package/dist/preview/{chunk.K5YFUMRS.js → chunk.DICM56FT.js} +1 -1
- package/dist/preview/{chunk.JS2UZYGB.js → chunk.DJMSXXP4.js} +1 -1
- package/dist/preview/{chunk.AJEK3I5X.js → chunk.DJPNVXBQ.js} +1 -1
- package/dist/preview/chunk.DJVHKBEI.js +1 -0
- package/dist/preview/chunk.E5WJSTOV.js +1 -0
- package/dist/preview/{chunk.XIVELWAM.js → chunk.F2TWV4TX.js} +1 -1
- package/dist/preview/chunk.F5VEHAP2.js +1 -0
- package/dist/preview/{chunk.2DH42I7L.js → chunk.FDWRH5P2.js} +1 -1
- package/dist/preview/chunk.FEGSYSA7.js +1 -0
- package/dist/preview/{chunk.2VIS2NAT.js → chunk.FHHVW2WB.js} +1 -1
- package/dist/preview/chunk.FOSY7MZF.js +2 -0
- package/dist/preview/{chunk.P4TAX3HE.js → chunk.FXG5AJF6.js} +1 -1
- package/dist/preview/{chunk.UJNLT3L6.js → chunk.G3Q5IMM3.js} +1 -1
- package/dist/preview/{chunk.APUQIELA.js → chunk.GPCKOYSF.js} +1 -1
- package/dist/preview/{chunk.GH5UBSQI.js → chunk.HJS3LTSR.js} +1 -1
- package/dist/preview/chunk.HJUXC5GM.js +1 -0
- package/dist/preview/chunk.HNMSYQRA.js +1 -0
- package/dist/preview/chunk.HWLRKOI3.js +1 -0
- package/dist/preview/{chunk.77MLXWZV.js → chunk.IFBGYFS4.js} +1 -1
- package/dist/preview/chunk.IHUMKFYH.js +10 -0
- package/dist/preview/{chunk.PVDDSBRG.js → chunk.IJ3YDBWI.js} +1 -1
- package/dist/preview/{chunk.7VAHHEDX.js → chunk.IMKD6QQG.js} +1 -1
- package/dist/preview/{chunk.DUP2CGVH.js → chunk.INTJD5WG.js} +1 -1
- package/dist/preview/chunk.IQ54QTA5.js +1 -0
- package/dist/preview/{chunk.LTOQ22ZJ.js → chunk.IQC3GOXO.js} +1 -1
- package/dist/preview/{chunk.2VYGDY5Z.js → chunk.IR4OW67N.js} +1 -1
- package/dist/preview/{chunk.DJIF7IAQ.js → chunk.ISN2QTVL.js} +1 -1
- package/dist/preview/{chunk.IQGSEAQ2.js → chunk.J24YPQ5I.js} +4 -4
- package/dist/preview/chunk.J545NAMY.js +1 -0
- package/dist/preview/{chunk.TQ2G4AM4.js → chunk.J6KNEI5R.js} +1 -1
- package/dist/preview/chunk.K3JARAWU.js +1 -0
- package/dist/preview/{chunk.E4TXLT25.js → chunk.KHAVEYT7.js} +1 -1
- package/dist/preview/{chunk.D2XLECMP.js → chunk.KIQXTQDU.js} +1 -1
- package/dist/preview/chunk.KROR65KD.js +2 -0
- package/dist/preview/{chunk.KHXRJLLU.js → chunk.KV7GZBJ6.js} +1 -1
- package/dist/preview/{chunk.DLWFULWE.js → chunk.L6FGKJ5H.js} +1 -1
- package/dist/preview/chunk.L7NJLZWV.js +1 -0
- package/dist/preview/{chunk.JHUCKEJS.js → chunk.LGRQDILY.js} +1 -1
- package/dist/preview/{chunk.UDYFGYJP.js → chunk.LKK5YF2H.js} +1 -1
- package/dist/preview/chunk.LON75VHP.js +1 -0
- package/dist/preview/chunk.LQWVJQ5X.js +18 -0
- package/dist/preview/{chunk.XJWKIXPV.js → chunk.LVD3V77M.js} +1 -1
- package/dist/preview/{chunk.ITBG37WJ.js → chunk.LY5CY7GE.js} +1 -1
- package/dist/preview/{chunk.ATHLE33D.js → chunk.M5W2RHC6.js} +1 -1
- package/dist/preview/chunk.M6BTLH24.js +1 -0
- package/dist/preview/chunk.MAGKI4PD.js +1 -0
- package/dist/preview/chunk.MD36ZSM5.js +74 -0
- package/dist/preview/chunk.MFZJVHWP.js +1 -0
- package/dist/preview/{chunk.LDMBJC3B.js → chunk.MH46V556.js} +1 -1
- package/dist/preview/chunk.MHTA4HYB.js +19 -0
- package/dist/preview/chunk.N2FNHRI2.js +1 -0
- package/dist/preview/chunk.N2YM247R.js +1 -0
- package/dist/preview/chunk.N35SJWAM.js +1 -0
- package/dist/preview/chunk.NBVPWLRY.js +3 -0
- package/dist/preview/{chunk.2TCOLAL2.js → chunk.NKYYDFIX.js} +1 -1
- package/dist/preview/{chunk.WPQP54FM.js → chunk.NSO6RUKW.js} +1 -1
- package/dist/preview/{chunk.47N2G7A5.js → chunk.O2W5JTWA.js} +1 -1
- package/dist/preview/chunk.OHMHPTEW.js +1 -0
- package/dist/preview/{chunk.CJHYGRWV.js → chunk.P6TZGR3A.js} +1 -1
- package/dist/preview/{chunk.OXFDB5BB.js → chunk.PTQPS2FJ.js} +1 -1
- package/dist/preview/chunk.PV2I4UPH.js +1 -0
- package/dist/preview/chunk.QFQSSZN7.js +1 -0
- package/dist/preview/{chunk.WFCE7NLK.js → chunk.QO5RXOCS.js} +2 -2
- package/dist/preview/{chunk.2V7QTIAV.js → chunk.QSDBF7VL.js} +1 -1
- package/dist/preview/{chunk.Z26T5E76.js → chunk.R2TSTDS3.js} +1 -1
- package/dist/preview/{chunk.T4TRJDBF.js → chunk.RFVOXX3P.js} +1 -1
- package/dist/preview/chunk.RSS6OHXG.js +1 -0
- package/dist/preview/{chunk.ZA5TDCBC.js → chunk.S2DOVJRL.js} +1 -1
- package/dist/preview/chunk.S3EEY7T3.js +1 -0
- package/dist/preview/chunk.SBCAYTMT.js +1 -0
- package/dist/preview/chunk.SMTGRCMG.js +3 -0
- package/dist/preview/{chunk.7SRSE5IS.js → chunk.SOMRYDDH.js} +1 -1
- package/dist/preview/{chunk.7CLKGKSF.js → chunk.SPCAMQJE.js} +1 -1
- package/dist/preview/{chunk.OW3M4OBN.js → chunk.T3KNLP7C.js} +1 -1
- package/dist/preview/chunk.TBY5IR7C.js +1 -0
- package/dist/preview/chunk.TCZIZ2PU.js +1 -0
- package/dist/preview/{chunk.TMHVYI5R.js → chunk.TUCSUZNO.js} +1 -1
- package/dist/preview/{chunk.2G5WLG3Z.js → chunk.TY74U3EI.js} +1 -1
- package/dist/preview/chunk.U74PTRHJ.js +1 -0
- package/dist/preview/chunk.UAORKZLO.js +1 -0
- package/dist/preview/chunk.UDVTPI2W.js +1 -0
- package/dist/preview/{chunk.S6QZBWCJ.js → chunk.UETLP5KC.js} +1 -1
- package/dist/preview/{chunk.2E62YCMZ.js → chunk.UHI3X2YD.js} +1 -1
- package/dist/preview/chunk.UL62ELNR.js +1 -0
- package/dist/preview/chunk.VRYSZYAD.js +1 -0
- package/dist/preview/{chunk.G5BVZLCM.js → chunk.VUZFLDOX.js} +1 -1
- package/dist/preview/chunk.X2NGFOAF.js +1 -0
- package/dist/preview/chunk.XE762VL2.js +2 -0
- package/dist/preview/{chunk.TA2JTUNX.js → chunk.XSWR5LI4.js} +1 -1
- package/dist/preview/{chunk.HZPRMHSL.js → chunk.XTTESA7X.js} +1 -1
- package/dist/preview/chunk.Y2RZ5B4U.js +1 -0
- package/dist/preview/chunk.Y7QDQ3WF.js +1 -0
- package/dist/preview/{chunk.TUR2DA2M.js → chunk.YKMBXMZE.js} +1 -1
- package/dist/preview/chunk.Z34KASY7.js +1 -0
- package/dist/preview/{chunk.WHX47OJM.js → chunk.ZDUTEM3Z.js} +1 -1
- package/dist/preview/{chunk.DQAMVVE6.js → chunk.ZJFXM3LE.js} +1 -1
- package/dist/preview/{chunk.UN2IAA5R.js → chunk.ZMGKWMID.js} +1 -1
- package/dist/preview/{chunk.R5MLRKAO.js → chunk.ZMWAZACO.js} +1 -1
- package/dist/preview/chunk.ZT5YQSSP.js +21 -0
- package/dist/preview/{chunk.XCLW4GP7.js → chunk.ZTN7BS5O.js} +1 -1
- package/dist/preview/{chunk.4XCYZRZ3.js → chunk.ZYNC73DJ.js} +1 -1
- package/dist/preview/chunk.ZZM75ZTN.js +4 -0
- package/dist/preview/index.html +56 -56
- package/dist/preview/page.js +2 -2
- package/package.json +6 -6
- package/dist/preview/chunk.2D7K2IJQ.js +0 -4
- package/dist/preview/chunk.2HV5FF6O.js +0 -1
- package/dist/preview/chunk.37I45R6V.js +0 -35
- package/dist/preview/chunk.3FKKH2XU.js +0 -74
- package/dist/preview/chunk.3J7XLJP2.js +0 -1
- package/dist/preview/chunk.3OEODIHB.js +0 -1
- package/dist/preview/chunk.3RD4JHVG.js +0 -88
- package/dist/preview/chunk.3RUV4HE4.js +0 -1
- package/dist/preview/chunk.3SAESG6X.js +0 -1
- package/dist/preview/chunk.4HTB6TX2.js +0 -1
- package/dist/preview/chunk.4Q5PCMGZ.js +0 -18
- package/dist/preview/chunk.52MBXPEK.js +0 -1
- package/dist/preview/chunk.5AD2QHWH.js +0 -3
- package/dist/preview/chunk.5HJ2GTKZ.js +0 -1
- package/dist/preview/chunk.5IEZF433.js +0 -2
- package/dist/preview/chunk.5PPCK7QT.js +0 -1
- package/dist/preview/chunk.6NRWLCIZ.js +0 -5
- package/dist/preview/chunk.7AOEZJRM.js +0 -1
- package/dist/preview/chunk.7ZHH7WBN.js +0 -1
- package/dist/preview/chunk.APRWUIE3.js +0 -1
- package/dist/preview/chunk.B2YTHEX5.js +0 -1
- package/dist/preview/chunk.BN42H3C6.js +0 -1
- package/dist/preview/chunk.CC7P435K.js +0 -9
- package/dist/preview/chunk.CM65MCHA.js +0 -1
- package/dist/preview/chunk.DYRULRFX.js +0 -1
- package/dist/preview/chunk.FN34P4IS.js +0 -1
- package/dist/preview/chunk.FUPYIOXZ.js +0 -1
- package/dist/preview/chunk.FXRYMT3U.js +0 -1
- package/dist/preview/chunk.G7YLK4PX.js +0 -1
- package/dist/preview/chunk.GF62K25C.js +0 -1
- package/dist/preview/chunk.GFQPO3NC.js +0 -1
- package/dist/preview/chunk.GHHKRFPD.js +0 -1
- package/dist/preview/chunk.GP5DAA4P.js +0 -3
- package/dist/preview/chunk.HSJEOM3W.js +0 -1
- package/dist/preview/chunk.K2PXP5H6.js +0 -1
- package/dist/preview/chunk.K54ISAXN.js +0 -1
- package/dist/preview/chunk.KMIFSPGQ.js +0 -1
- package/dist/preview/chunk.L4V5VLSM.js +0 -1
- package/dist/preview/chunk.M5VHUIDB.js +0 -1
- package/dist/preview/chunk.N643PVQA.js +0 -1
- package/dist/preview/chunk.NRPBTV6O.js +0 -21
- package/dist/preview/chunk.O7HHNQK4.js +0 -2
- package/dist/preview/chunk.PR74PGLC.js +0 -1
- package/dist/preview/chunk.QROPDEJF.js +0 -1
- package/dist/preview/chunk.QRT6BZR6.js +0 -1
- package/dist/preview/chunk.RDA35HZB.js +0 -2
- package/dist/preview/chunk.SADHOSRC.js +0 -19
- package/dist/preview/chunk.SJHUC4TL.js +0 -1
- package/dist/preview/chunk.SL5FXE3R.js +0 -1
- package/dist/preview/chunk.TOLW64EO.js +0 -1
- package/dist/preview/chunk.TP3PZRHE.js +0 -1
- package/dist/preview/chunk.UD2GGG7L.js +0 -1
- package/dist/preview/chunk.VLX7YWVH.js +0 -25
- package/dist/preview/chunk.VT4YBFZL.js +0 -1
- package/dist/preview/chunk.WMARJ5E3.js +0 -1
- package/dist/preview/chunk.XEG7ZDRG.js +0 -1
- package/dist/preview/chunk.XQ5RTPEF.js +0 -1
- package/dist/preview/chunk.YLOGIJOH.js +0 -1
- package/dist/preview/chunk.Z4XGEV34.js +0 -1
- package/dist/preview/chunk.ZNDVJGTY.js +0 -1
- package/dist/preview/chunk.ZQGLPP7A.js +0 -1
- /package/dist/preview/{chunk.GZHZLJBF.js → chunk.MIE4TJRW.js} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{a as Tr,b as ce,c as qe,d as He,f as Re,g as jr,h as Je,i as qn,j as Vi}from"./chunk.FQLNBIQ5.js";var zt="en-US",Yn=/^\d{4}-\d{2}-\d{2}$/,Fr=/^\d{4}(?:-(?:0[1-9]|1[0-2]))?$/,Lr=/^\d{4}(?:-(?:0[1-9]|1[0-2])(?:-\d{2})?)?$/;function hu(n){if(Yn.test(n))return{from:n,to:n};if(!Fr.test(n))return;if(n.length===4)return{from:`${n}-01-01`,to:`${n}-12-31`};let e=new Date(Date.UTC(+n.slice(0,4),+n.slice(5,7),0)).getUTCDate();return{from:`${n}-01`,to:`${n}-${String(e).padStart(2,"0")}`}}var It=/^\d{4}(-\d\d){2}[T ]\d\d:\d\d(:[\d.]+)?(Z|[+-][\d:]+)?$/,ug=n=>!Number.isNaN(Date.parse(n)),te=(n,e=Date.now())=>{let t=Tt(n);return t?Cr(e,t).day:new Date(e).toISOString().slice(0,10)},Tt=n=>xn(n)??kn,Hn,wn,Jn,kn;function gu(n){Hn=Sn(n.reader),wn=Sn(n.app),Jn=xn(n.readerTimeZone),kn=xn(n.appTimeZone)}function mu(n,e){let t=[Hn,wn,Jn,kn];n.reader!==void 0&&(Hn=Sn(n.reader)),n.app!==void 0&&(wn=Sn(n.app)),n.readerTimeZone!==void 0&&(Jn=xn(n.readerTimeZone)),n.appTimeZone!==void 0&&(kn=xn(n.appTimeZone));try{return e()}finally{[Hn,wn,Jn,kn]=t}}var Bi=n=>Hn??Sn(n)??wn??zt,lg=n=>Sn(n)??wn??zt,jt=n=>Jn??xn(n)??kn,yu=n=>jt(n)??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",bu=/^\s*([+\-−]|\d)/;var Dr=new Map;function xn(n){if(n&&!Dr.has(n)){let e=!1;try{new Intl.DateTimeFormat(zt,{timeZone:n}),e=!bu.test(n)}catch{}Dr.set(n,e)}return n&&Dr.get(n)?n:void 0}var Ye=new Map;function Sn(n){if(n&&!Ye.has(n)){let e=!1;try{e=Intl.DateTimeFormat.supportedLocalesOf(n).length>0}catch{}Ye.set(n,e)}return n&&Ye.get(n)?n:void 0}function Ie(n,e,t,r){let o=`${t=Bi(t)}${r?"#":"@"}${JSON.stringify(e)}`,i=Ye.get(o);return i||Ye.set(o,i=r?new Intl.NumberFormat(t,e):new Intl.DateTimeFormat(t,e)),i.format(n).replace(/ /g," ")}var Xe="UTC",Dt=n=>Date.UTC(+n.slice(0,4),+n.slice(5,7)-1,+n.slice(8,10));function Te(n,e){return Fr.test(n)?n.length===4?n:Hi(n,{},e):Yn.test(n)?Ie(Dt(n),{year:"numeric",month:"short",day:"numeric",timeZone:Xe},e):n}function Cr(n,e){let t=`wall@${e??""}`,r=Ye.get(t);r||Ye.set(t,r=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23",...e?{timeZone:e}:{}}));let o=Object.fromEntries(r.formatToParts(n).map(i=>[i.type,i.value]));return{day:`${o.year}-${o.month}-${o.day}`,minutes:Number(o.hour)%24*60+Number(o.minute)}}function Ui(n,e,t){let r=Date.UTC(+n.slice(0,4),+n.slice(5,7)-1,+n.slice(8,10),0,e),o=i=>{let s=Cr(i,t);return vu(s.day,s.minutes)-Math.floor(i/6e4)*6e4};return r-o(r-o(r))}var vu=(n,e)=>Date.UTC(+n.slice(0,4),+n.slice(5,7)-1,+n.slice(8,10),0,e),Wi=n=>/[Z+-][\d:]*$/.test(n.slice(16));function qi(n,e,t,r,o=!1){if(!It.test(n))return n;let i=Wi(n),s=Date.parse(n.replace(" ","T")+(i?"":"Z"));if(Number.isNaN(s))return n;let a=i?jt(r):Xe;return Ie(s,{...e,hour:"numeric",minute:"2-digit",...i&&o?{timeZoneName:"short"}:{},...a?{timeZone:a}:{}},t)}var Zr=(n,e,t)=>qi(n,{year:"numeric",month:"short",day:"numeric"},e,t,!0),wu=(n,e,t)=>qi(n,{},e,t);function ku(n,e){if(Yn.test(n))return n;if(!It.test(n))return;if(!Wi(n))return n.slice(0,10);let t=Date.parse(n.replace(" ","T"));return Number.isNaN(t)?void 0:Cr(t,jt(e)).day}function $e(n,e,t={maximumFractionDigits:2}){return Number.isFinite(n)?Ie(n,t,e,!0):String(n)}function xu(n,e={},t){return Yn.test(n)?Ie(Dt(n),{weekday:e.weekday??"long",month:"short",day:"numeric",...e.year?{year:"numeric"}:{},timeZone:Xe},t):n}function Su(n,e){return Yn.test(n)?Ie(Dt(n),{month:"short",day:"numeric",timeZone:Xe},e):n}function Hi(n,e={},t){if(!/^\d{4}-\d{2}/.test(n))return n;let r=e.year??!e.short;return Ie(Dt(`${n.slice(0,7)}-01`),{month:e.short?"short":"long",...r?{year:e.short?"2-digit":"numeric"}:{},timeZone:Xe},t)}var Ru=(n,e="short",t)=>Ie(Date.UTC(1970,0,4+n),{weekday:e,timeZone:Xe},t),$u=(n,e)=>Ie(Date.UTC(1970,0,1,0,Math.round(n)),{hour:"numeric",minute:"2-digit",timeZone:Xe},e),Au=/(?<![\w-])(\d{4}-\d{2}-\d{2})(?![\w-]|:)/g;function Gr(n,e){return n.includes("-")?n.replace(Au,t=>Te(t,e)):n}var Qe=n=>n.charAt(0).toUpperCase()+n.slice(1),Ft=n=>/^.\p{Lu}/u.test(n)?n:n.charAt(0).toLowerCase()+n.slice(1),Ji=(n,e="and")=>n.length>1?`${n.slice(0,-1).join(", ")} ${e} ${n.at(-1)}`:n[0]??"";function B(n){let e=n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim().toLowerCase();return Qe(e.replace(/\b[a-z]+\b/g,t=>Yi.has(t)?t.toUpperCase():t.endsWith("s")&&Yi.has(t.slice(0,-1))?`${t.slice(0,-1).toUpperCase()}s`:t))}var Yi=new Set("id url uri api ip ioc cve cvss cwe cpe sku vat iban isbn pdf csv json html css sla kpi roi faq ssn ein vin gps sms crm erp seo utm ui ux ai dns ssl tls http https sql uuid mfa sso cto ceo cfo coo rsvp eta".split(" "));function en(n){if(!Xi(n))return B(n);let e=n.replace(/[_\s]+/g," ").trim();return Qe(e)}var Xi=n=>/[A-Z]/.test(n)&&!/^[a-z][a-zA-Z0-9]*$/.test(n);function gg(n){return Xi(n)?en(n):Ft(B(n))}function Ou(n,e){return{...e,kind:n,edges:e.edges??{}}}function Kr(n,e,t){let r=n?.lifecycle;if(!r)return!0;let o=e[r.field];return r.retired==="date"?typeof o!="string"||o.length===0?!0:o>=(t??te()):!r.retired.includes(o)}function V(n,e){if(n?.label)return n.label(e);let t=e.label;return typeof t=="string"&&t.length>0?t:e.id}function _u(n){return n.title??B(n.name)}function Pu(n,e,t){let r=n.tryDefinition(e);return`${$e(t)} ${t===1?X(r,e):ue(n,e).toLowerCase()}`}function ue(n,e){return n.tryDefinition(e)?.plural??`${B(e).toLowerCase()}s`}function Eu(n,e){return Qe(ue(n,e))}function Mu(n,e){let t=ue(n,e);return`All ${/^[A-Z][a-z]/.test(t)?t.charAt(0).toLowerCase()+t.slice(1):t}`}function Lt(n,e){let t=n?.computed&&Object.hasOwn(n.computed,e)?n.computed[e]:void 0;return n?.display?.labels?.[e]??(typeof t=="object"?t.label:void 0)??(e==="label"?"Name":B(e))}var Nu=/^(u[nt]i|use|usu|uti|ubiq|eu|ewe|one|once)/,zu=/^(hour|honest|hono[ur]r?|heir)/;function Qi(n){let e=B(n).toLowerCase();return zu.test(e)?"an":Nu.test(e)?"a":/^[aeiou]/.test(e)?"an":"a"}function Rn(n){return`${Qi(n)} ${B(n).toLowerCase()}`}function X(n,e){return n?.noun??B(e).toLowerCase()}function Ur(n){let e=Object.values(n).filter(r=>typeof r=="number");return Object.entries(n).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function Wr(n,e="|"){return n.map(t=>Xr(t)).join(e)}function ns(n,e){return typeof e=="bigint"?e.toString():e}var Br=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function ts(n){return new Br(n)}function rs(n){return n==null}function qr(n){let e=n.startsWith("^")?1:0,t=n.endsWith("$")?n.length-1:n.length;return n.slice(e,t)}function os(n,e){let t=n/e,r=Math.round(t),o=4*Number.EPSILON*Math.max(Math.abs(t),1);return Math.abs(t-r)<o?0:t-r}var es=Symbol("evaluating");function is(n,e,t){let r;Object.defineProperty(n,e,{get(){if(r!==es)return r===void 0&&(r=es,r=t()),r},set(o){Object.defineProperty(n,e,{value:o})},configurable:!0})}function Zt(n,e,t){Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}function ss(n){let e=Object.getOwnPropertyDescriptor(n,"shape");return e?.get?e.get.raw:e?.value}function Hr(n){return ss(n._zod.def)??n._zod.def.shape}function as(n,e,t){Object.defineProperty(n,e,{get(){let r=t();return Zt(this,e,r),r},enumerable:!0,configurable:!0})}function ds(n,e,t){e in n?Zt(n,e,t):n[e]=t}function Iu(n,e,t,r){let o=Hr(e);for(let i of t){let s=Object.getOwnPropertyDescriptor(o,i);s.enumerable&&(s.get?as(n,i,()=>{let a=e._zod.def.shape[i];return r?r(a,i):a}):ds(n,i,r?r(s.value,i):s.value))}}function Tu(n,e){for(let t of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,t);r.enumerable&&(r.get?as(n,t,()=>e[t]):ds(n,t,r.value))}}function cs(...n){let e={};for(let t of n){let r=Object.getOwnPropertyDescriptors(t);Object.assign(e,r)}return Object.defineProperties({},e)}var Jr="captureStackTrace"in Error?Error.captureStackTrace:(...n)=>{};function Ct(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Yr(n){if(Ct(n)===!1)return!1;let e=n.constructor;if(e===void 0||typeof e!="function")return!0;let t=e.prototype;return!(Ct(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}var us=new Set(["string","number","symbol"]);function Qn(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $n(n,e,t){let r=new n._zod.constr(e??n._zod.def);return(!e||t?.parent)&&(r._zod.parent=n),r}function D(n){let e=n;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Xr(n){return typeof n=="bigint"?n.toString()+"n":typeof n=="string"?`"${n}"`:`${n}`}function ls(n){return Object.keys(n).filter(e=>n[e]._zod.optin!==void 0&&n[e]._zod.optout==="optional")}var fs={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function ps(n,e){if(!Yr(e))throw new Error("Invalid input to extend: expected a plain object");let t=n._zod.def.checks;if(t&&t.length>0){let o=Hr(n);for(let i of Reflect.ownKeys(e))if(Object.getOwnPropertyDescriptor(o,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return $n(n,cs(n._zod.def,{shape:ju(n,e)}))}function ju(n,e){let t={};return Iu(t,n,Reflect.ownKeys(Hr(n))),Tu(t,e),t}function Ae(n,e=0){if(n.aborted===!0)return!0;for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue!==!0)return!0;return!1}function hs(n,e=0){if(n.aborted===!0)return!0;for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue===!1)return!0;return!1}function De(n,e){return e.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(n),t})}function Xn(n){return typeof n=="string"?n:n?.message}function Qr(n,e,t){var r;for(let o=e;o<n.length;o++)(r=n[o]).schema??(r.schema=t)}function Oe(n,e,t){var r;let o=n.inst?._zod?.traits;o?.has("$ZodType")&&(o.has("$ZodCheck")?(r=n).schema??(r.schema=n.inst):n.schema=n.inst);let i=n.schema!==n.inst?n.schema?._zod.def?.error:void 0,s=n.message?n.message:Xn(n.inst?._zod.def?.error?.(n))??Xn(i?.(n))??Xn(e?.error?.(n))??Xn(t.customError?.(n))??Xn(t.localeError?.(n))??"Invalid input",a={};for(let d of Object.keys(n))d==="inst"||d==="schema"||d==="continue"||d==="input"||d==="__proto__"||(a[d]=n[d]);return a.path??(a.path=[]),a.message=s,e?.reportInput&&(a.input=n.input),a}var Du=/[\uD800-\uDBFF]/;function eo(n){let e=n.length;if(!Du.test(n))return e;let t=e;for(let r=0;r<e-1;r++)(n.charCodeAt(r)&64512)===55296&&(n.charCodeAt(r+1)&64512)===56320&&(t--,r++);return t}function no(n){return Array.isArray(n)?"array":typeof n=="string"?"string":"unknown"}function gs(n){let e=typeof n;switch(e){case"number":return Number.isNaN(n)?"nan":"number";case"object":{if(n===null)return"null";if(Array.isArray(n))return"array";let t=n;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}}return e}function et(...n){let[e,t,r]=n;return typeof e=="string"?{message:e,code:"custom",input:t,inst:r}:{...e}}function ms(n,e){for(let t in e){let r=Object.getOwnPropertyDescriptor(e,t);r.get?Object.defineProperty(n,t,{...r,enumerable:!1}):Fu(n,t,r.value)}}function nn(n,e,t,r=!0){return Object.defineProperty(n,e,{configurable:!0,writable:!0,enumerable:r,value:t}),t}function to(n,e,t){return nn(n,e,t,!1)}function Fu(n,e,t){Object.defineProperty(n,e,{configurable:!0,get(){return this==null?t:nn(this,e,t.bind(this))},set(r){nn(this,e,r)}})}function Lu(n,e){let t=Object.getPrototypeOf(n);return e in t?void 0:t}var Vr,je=!1,Cu={configurable:!0,get(){je=!0}};function Q(n,e,t){let r=Object.getPrototypeOf(n._zod);if(e in r&&Vr!==n._zod){Vr=void 0;return}Vr=n._zod,Object.defineProperty(r,e,{configurable:!0,get(){Object.defineProperty(this,e,Cu);let o=je;je=!1;try{let i=t(this);return je?delete this[e]:Object.defineProperty(this,e,{configurable:!0,writable:!0,value:i}),je=je||o,i}catch(i){throw delete this[e],je=je||o,i}},set(o){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:o})}})}function ys(n,e,t,r){let o=Lu(n,e);o&&Object.defineProperty(o,e,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,e,i),i.value=t(this),Object.defineProperty(this,e,i),i.value},set(i){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:r,value:i})}})}var bs;var ro={value:void 0,enumerable:!1},vs="captureStackTrace"in Error?Error:null;function Zu(n){let e=vs;if(e){let t=e.stackTraceLimit;if(typeof t=="number"){try{e.stackTraceLimit=0}catch{return vs=null,new n}try{return new n}finally{e.stackTraceLimit=t}}}return new n}function E(n,e,t,r){let o={};function i(c){this.def=c,this.constr=p,this.traits=new Set}i.prototype=o;let s=t,a=s&&new WeakSet;function d(c,f){if(c._zod){if(c._zod.traits.has(n))return}else{ro.value=new i(f);try{Object.defineProperty(c,"_zod",ro)}finally{ro.value=void 0}}if(c._zod.traits.add(n),e(c,f),a){let h=Object.getPrototypeOf(c),y=c._zod.constr.prototype,b=h;for(;b&&b!==y;)b=Object.getPrototypeOf(b);let x=b??h;a.has(x)||(a.add(x),ms(x,s))}let g=p.prototype;for(let h in g)Object.prototype.hasOwnProperty.call(g,h)&&(h in c||(c[h]=g[h].bind(c)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:n});function p(c){let f=r?.Parent?Zu(u):this;d(f,c);let g=f._zod.deferred;if(g){for(let y of g)y();f._zod.deferred=void 0}let h=globalThis.__zod_globalConfig?.postProcessor;return h&&h(f),f}return Object.defineProperty(p,"init",{value:d}),Object.defineProperty(p,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(n)}),Object.defineProperty(p,"name",{value:n}),p}var Pe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};(bs=globalThis).__zod_globalConfig??(bs.__zod_globalConfig={});var An=globalThis.__zod_globalConfig;function oe(n){return n&&Object.assign(An,n),An}function Gu(){let n=this._zod;return n.message??(n.message=JSON.stringify(n.def,ns,2)),n.message}function Ku(n){this._zod.message=n}var Vu={get:Gu,set:Ku,enumerable:!0,configurable:!0},io={value:void 0,enumerable:!1},ws=new WeakSet([Object.prototype,Error.prototype]),ks=(n,e)=>{n.name="$ZodError",io.value=e,Object.defineProperty(n,"issues",io),io.value=void 0,Object.defineProperty(n,"message",Vu);let t=Object.getPrototypeOf(n);ws.has(t)||(ws.add(t),Object.defineProperty(t,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}}))},Sg=E("$ZodError",ks),nt=E("$ZodError",ks,void 0,{Parent:Error});var Uu=n=>{let e=(t,r,o,i)=>{let s=o?{...o,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Pe;if(a.issues.length){let d=new(i?.Err??n)(a.issues.map(l=>Oe(l,s,oe())));throw Jr(d,i?.callee??e),d}return a.value};return e},so=Uu(nt),Wu=n=>{let e=async(t,r,o,i)=>{let s=o?{...o,async:!0}:{async:!0},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){let d=new(i?.Err??n)(a.issues.map(l=>Oe(l,s,oe())));throw Jr(d,i?.callee??e),d}return a.value};return e},ao=Wu(nt),qu=n=>(e,t,r)=>{let o=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:t,issues:[]},o);if(i instanceof Promise)throw new Pe;return i.issues.length?xs(n,i.issues,o):{success:!0,data:i.value}},co=qu(nt);function xs(n,e,t){let r;return{success:!1,get error(){return r||(r=new n(e.map(o=>Oe(o,t,oe()))),e=void 0,t=void 0),r},set error(o){r=o,e=void 0,t=void 0}}}var Hu=n=>async(e,t,r)=>{let o=r?{...r,async:!0}:{async:!0},i=e._zod.run({value:t,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?xs(n,i.issues,o):{success:!0,data:i.value}},uo=Hu(nt);var Ss=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Rs=/^https?$/;var $s=/^[\s\S]{0,}$/;var lo=/^-?\d+(?:\.\d+)?$/,As=/^(?:true|false)$/i,Os=/^null$/i;var ie=E("$ZodCheck",(n,e)=>{var t;n._zod??(n._zod={}),n._zod.def=e,(t=n._zod).onattach??(t.onattach=[])});var _s=n=>{let e=n.value;return!rs(e)&&e.length!==void 0},Gt={number:"number",bigint:"bigint",object:"date"},Ps=E("$ZodCheckLessThan",(n,e)=>{ie.init(n,e);let t=Gt[typeof e.value];n._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:Gt[typeof r.value]??t,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),Es=E("$ZodCheckGreaterThan",(n,e)=>{ie.init(n,e);let t=Gt[typeof e.value];n._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:Gt[typeof r.value]??t,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),Ms=E("$ZodCheckMultipleOf",(n,e)=>{ie.init(n,e),n._zod.check=t=>{if(typeof t.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof t.value=="bigint"?e.value!==BigInt(0)&&t.value%e.value===BigInt(0):os(t.value,e.value)===0)||t.issues.push({origin:typeof t.value,code:"not_multiple_of",divisor:e.value,input:t.value,inst:n,continue:!e.abort})}}),Ns=E("$ZodCheckNumberFormat",(n,e)=>{ie.init(n,e),e.format=e.format||"float64";let t=e.format?.includes("int"),r=t?"int":"number",[o,i]=fs[e.format];n._zod.check=s=>{let a=s.value;if(t){if(!Number.isInteger(a)){s.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:a,inst:n});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:r,inclusive:!0,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:r,inclusive:!0,continue:!e.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:n,continue:!e.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:n,continue:!e.abort})}});var zs=E("$ZodCheckMaxLength",(n,e)=>{var t;ie.init(n,e),(t=n._zod.def).when??(t.when=_s),n._zod.check=r=>{let o=r.value,i=o.length;if((typeof o=="string"&&i>e.maximum?eo(o):i)<=e.maximum)return;let a=no(o);r.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:n,continue:!e.abort})}}),Is=E("$ZodCheckMinLength",(n,e)=>{var t;ie.init(n,e),(t=n._zod.def).when??(t.when=_s),n._zod.check=r=>{let o=r.value,i=o.length;if((typeof o=="string"&&i>=e.minimum&&i<e.minimum*2?eo(o):i)>=e.minimum)return;let a=no(o);r.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:n,continue:!e.abort})}});var po=E("$ZodCheckStringFormat",(n,e)=>{var t,r;ie.init(n,e),e.pattern?(t=n._zod).check??(t.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:n,continue:!e.abort})}):(r=n._zod).check??(r.check=()=>{})}),Ts=E("$ZodCheckRegex",(n,e)=>{po.init(n,e),n._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:n,continue:!e.abort})}});var Ds={major:4,minor:6,patch:5};var U=E("$ZodType",(n,e)=>{var t;n??(n={}),n._zod.def=e,n._zod.bag=n._zod.bag||{},n._zod.version=Ds;let r=n._zod.def.checks,o=n._zod.traits.has("$ZodCheck")?[n,...r??[]]:r?.length?[...r]:[];for(let i of o)for(let s of i._zod.onattach)s(n);if(o.length===0)(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{let i=(a,d,l)=>{if(a.memo)return a;let u=Ae(a),p;for(let c of d){if(c._zod.def.when){if(hs(a)||!c._zod.def.when(a))continue}else if(u)continue;let f=a.issues.length,g=c._zod.check(a);if(g instanceof Promise&&l?.async===!1)throw new Pe;if(p||g instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await g,a.issues.length!==f&&(Qr(a.issues,f,n),u||(u=Ae(a,f)))});else{if(a.issues.length===f)continue;Qr(a.issues,f,n),u||(u=Ae(a,f))}}return p?p.then(()=>a):a},s=(a,d,l)=>{if(Ae(a))return a.aborted=!0,a;let u=i(d,o,l);if(u instanceof Promise){if(l.async===!1)throw new Pe;return u.then(p=>n._zod.parse(p,l))}return n._zod.parse(u,l)};n._zod.run=(a,d)=>{if(d.skipChecks)return n._zod.parse(a,d);if(d.direction==="backward"){let u=n._zod.parse({value:a.value,issues:[]},{...d,skipChecks:!0});return u instanceof Promise?u.then(p=>s(p,a,d)):s(u,a,d)}let l=n._zod.parse(a,d);if(l instanceof Promise){if(d.async===!1)throw new Pe;return l.then(u=>i(u,o,d))}return i(l,o,d)}}},{get"~standard"(){return to(this,"~standard",Yu(this))},set"~standard"(n){nn(this,"~standard",n)}}),Ks=(n,e)=>n.issues.length?{issues:n.issues.map(t=>Oe(t,e,oe()))}:{value:n.value};async function Ju(n,e){let t={async:!0};return Ks(await n._zod.run({value:e,issues:[]},t),t)}function Yu(n){return{validate:e=>{let t={async:!1};try{let r=n._zod.run({value:e,issues:[]},t);if(!(r instanceof Promise))return Ks(r,t)}catch{}return Ju(n,e)},vendor:"zod",version:1}}var ho=E("$ZodString",(n,e)=>{U.init(n,e),n._zod.pattern=e.pattern??$s,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=String(t.value)}catch{}return typeof t.value=="string"||t.issues.push({expected:"string",code:"invalid_type",input:t.value,inst:n}),t}}),Bt=E("$ZodStringFormat",(n,e)=>{po.init(n,e),ho.init(n,e)});var Vs=E("$ZodEmail",(n,e)=>{e.pattern??(e.pattern=Ss),Bt.init(n,e)}),Bs=1,Kt=2;function Xu(n){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(n):(new URL(n),!0)}catch{return!1}}function Qu(n,e){return!("normalize"in e)&&!("hostname"in e)&&!("protocol"in e)?Xu(n)||Kt:el(n,e)}function el(n,e){if(!e.normalize&&e.protocol?.source===Rs.source&&!/^https?:\/\//i.test(n))return Bs;try{if(typeof URL<"u"){let t=URL;if(typeof t.parse=="function")return t.parse(n)??Kt}return new URL(n)}catch{return Kt}}var nl=/[\t\n\r]/g;function Fs(n){return n.replace(nl,"")}function tl(n,e){return e.lastIndex=0,e.test(n.hostname)}function rl(n,e){return e.lastIndex=0,e.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)}var Us=E("$ZodURL",(n,e)=>{Bt.init(n,e),n._zod.check=t=>{try{let r=t.value.trim(),o=Qu(r,e);if(o===Bs){t.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:t.value,inst:n,continue:!e.abort});return}if(o===Kt){t.issues.push({code:"invalid_format",format:"url",input:t.value,inst:n,continue:!e.abort});return}if(o===!0){t.value=Fs(r);return}e.hostname&&!tl(o,e.hostname)&&t.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:t.value,inst:n,continue:!e.abort}),e.protocol&&!rl(o,e.protocol)&&t.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:t.value,inst:n,continue:!e.abort}),t.value=e.normalize?o.href:Fs(r);return}catch{t.issues.push({code:"invalid_format",format:"url",input:t.value,inst:n,continue:!e.abort})}}});var go=E("$ZodNumber",(n,e)=>{U.init(n,e),n._zod.pattern=lo,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=Number(t.value)}catch{}let o=t.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return t;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:String(o):void 0;return t.issues.push({expected:"number",code:"invalid_type",input:o,inst:n,...i?{received:i}:{}}),t}}),Ws=E("$ZodNumberFormat",(n,e)=>{Ns.init(n,e),go.init(n,e)}),qs=E("$ZodBoolean",(n,e)=>{U.init(n,e),n._zod.pattern=As,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=!!t.value}catch{}let o=t.value;return typeof o=="boolean"||t.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:n}),t}});var Hs=E("$ZodNull",(n,e)=>{U.init(n,e),n._zod.pattern=Os,n._zod.values=new Set([null]),n._zod.parse=(t,r)=>{let o=t.value;return o===null||t.issues.push({expected:"null",code:"invalid_type",input:o,inst:n}),t}});var Js=E("$ZodUnknown",(n,e)=>{U.init(n,e),n._zod.parse=t=>t}),Ys=E("$ZodNever",(n,e)=>{U.init(n,e),n._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:n}),t)});function Ls(n,e,t){n.issues.length&&e.issues.push(...De(t,n.issues)),e.value[t]=n.value}var Xs=E("$ZodArray",(n,e)=>{U.init(n,e);let t=An.memoizer;t?.attach(n),n._zod.parse=(r,o)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:n}),r;r.value=t?t.alloc(n,r,Array(i.length),o):Array(i.length);let s=[],a=o?.abortEarly;for(let d=0;d<i.length;d++){let l=i[d],u=e.element._zod.run({value:l,issues:[]},o);if(u instanceof Promise)s.push(u.then(p=>Ls(p,r,d)));else if(Ls(u,r,d),a&&u.issues.length!==0&&Ae(u))break}return s.length?Promise.all(s).then(()=>r):r}});function Vt(n,e,t,r,o,i){let s=t in r,a=i==="optional";if(!(!s&&a&&o==="optional")){if(n.issues.length){if(o!==void 0&&a&&!s)return;e.issues.push(...De(t,n.issues))}if(!s&&o===void 0){n.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[t]});return}n.value===void 0?(s||o==="defaulted"&&!a)&&(e.value[t]=void 0):e.value[t]=n.value}}var ol=[];function il(n){let e=Object.keys(n.shape),t=Object.getOwnPropertySymbols(n.shape),r=t.length?t:ol,o=r.length?[...e,...r]:e;for(let s of o)if(!n.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(s)}": expected a Zod schema`);let i=ls(n.shape);return{...n,allKeys:o,symbolKeys:r,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(i)}}function sl(n,e,t,r,o,i,s){let a=[],d=o.keySet,l=o.catchall._zod,u=l.def.type,p=l.optin,c=l.optout,f=0;for(let g in e){if(s&&t.issues.length!==f){if(Ae(t,f))break;f=t.issues.length}if(d.has(g))continue;if(g==="__proto__"){u==="never"&&a.push(g);continue}if(u==="never"){a.push(g);continue}let h=l.run({value:e[g],issues:[]},r);h instanceof Promise?n.push(h.then(y=>Vt(y,t,g,e,p,c))):Vt(h,t,g,e,p,c)}return a.length&&t.issues.push({code:"unrecognized_keys",keys:a,input:e,inst:i,continue:!0}),n.length?Promise.all(n).then(()=>t):t}var Qs=E("$ZodObject",(n,e)=>{U.init(n,e);let t=Object.getOwnPropertyDescriptor(e,"shape"),r=t?.get?t.get.raw:e.shape??{};if(r){let l=()=>{let u={...r};return Object.defineProperty(e,"shape",{value:u}),l.raw=u,u};l.raw=r,Object.defineProperty(e,"shape",{get:l})}let o=ts(()=>il(e));Q(n,"propValues",l=>{let u=l.def.shape,p={};for(let c in u){let f=u[c]._zod;if(f.values){Object.prototype.hasOwnProperty.call(p,c)||Zt(p,c,new Set);for(let g of f.values)p[c].add(g);f.optin!==void 0&&p[c].add(void 0)}}return p});let i=Ct,s=e.catchall,a,d=An.memoizer;d?.attach(n),n._zod.parse=(l,u)=>{a??(a=o.value);let p=l.value;if(!i(p))return l.issues.push({expected:"object",code:"invalid_type",input:p,inst:n}),l;l.value=d?d.alloc(n,l,{},u):{};let c=[],f=a.shape,g=u?.abortEarly,h=l.issues.length;for(let y of a.allKeys){if(g&&l.issues.length!==h){if(Ae(l,h))break;h=l.issues.length}if(y==="__proto__")continue;let b=f[y],x=b._zod.optin,$=b._zod.optout,w=b._zod.run({value:p[y],issues:[]},u);w instanceof Promise?c.push(w.then(O=>Vt(O,l,y,p,x,$))):Vt(w,l,y,p,x,$)}return s?sl(c,p,l,u,o.value,n,g===!0):c.length?Promise.all(c).then(()=>l):l}});function Cs(n,e,t,r){for(let i of n)if(i.issues.length===0)return e.value=i.value,e;let o=n.filter(i=>!Ae(i));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:t,errors:n.map(i=>i.issues.map(s=>Oe(s,r,oe())))}),e)}var ea=E("$ZodUnion",(n,e)=>{U.init(n,e),Q(n,"optin",r=>r.def.options.some(o=>o._zod.optin==="defaulted")?"defaulted":r.def.options.some(o=>o._zod.optin!==void 0)?"optional":void 0),Q(n,"optout",r=>r.def.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Q(n,"values",r=>{if(r.def.options.every(o=>o._zod.values))return new Set(r.def.options.flatMap(o=>Array.from(o._zod.values)))}),Q(n,"pattern",r=>{if(r.def.options.every(o=>o._zod.pattern)){let o=r.def.options.map(i=>i._zod.pattern);return new RegExp(`^(${o.map(i=>qr(i.source)).join("|")})$`)}});let t=e.options.length===1?e.options[0]._zod.run:null;n._zod.parse=(r,o)=>{if(t)return t(r,o);let i=!1,s=[];for(let a of e.options){let d=a._zod.run({value:r.value,issues:[]},o);if(d instanceof Promise)s.push(d),i=!0;else{if(d.issues.length===0)return d;s.push(d)}}return i?Promise.all(s).then(a=>Cs(a,r,n,o)):Cs(s,r,n,o)}});var na=E("$ZodRecord",(n,e)=>{U.init(n,e);let t=An.memoizer;t?.attach(n),n._zod.parse=(r,o)=>{let i=r.value;if(!Yr(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:n}),r;let s=[],a=e.keyType._zod.values;if(a&&!e.partial){r.value=t?t.alloc(n,r,{},o):{};let d=new Set;for(let u of a)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){if(d.add(typeof u=="number"?u.toString():u),u==="__proto__")continue;let p=e.keyType._zod.run({value:u,issues:[]},o);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(p.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(g=>Oe(g,o,oe())),input:u,path:[u],inst:n});continue}let c=p.value;if(c==="__proto__")continue;let f=e.valueType._zod.run({value:i[u],issues:[]},o);f instanceof Promise?s.push(f.then(g=>{g.issues.length&&r.issues.push(...De(u,g.issues)),r.value[c]=g.value})):(f.issues.length&&r.issues.push(...De(u,f.issues)),r.value[c]=f.value)}let l;for(let u in i)if(!d.has(u))if(e.mode==="loose"){if(u==="__proto__")continue;r.value[u]=i[u]}else l=l??[],l.push(u);l&&l.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:n,keys:l,continue:!0})}else{r.value=t?t.alloc(n,r,{},o):{};let d;for(let l of Reflect.ownKeys(i)){if(l==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,l))continue;let u=e.keyType._zod.run({value:l,issues:[]},o);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&lo.test(l)&&u.issues.length){let g=e.keyType._zod.run({value:Number(l),issues:[]},o);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(u=g)}if(u.issues.length){e.mode==="loose"?r.value[l]=i[l]:a?(d=d??[],d.push(l)):r.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(g=>Oe(g,o,oe())),input:l,path:[l],inst:n});continue}let c=u.value;if(c==="__proto__")continue;let f=e.valueType._zod.run({value:i[l],issues:[]},o);f instanceof Promise?s.push(f.then(g=>{g.issues.length&&r.issues.push(...De(l,g.issues)),r.value[c]=g.value})):(f.issues.length&&r.issues.push(...De(l,f.issues)),r.value[c]=f.value)}d&&d.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:n,keys:d,continue:!0})}return s.length?Promise.all(s).then(()=>r):r}});var ta=E("$ZodEnum",(n,e)=>{U.init(n,e);let t=Ur(e.entries),r=new Set(t);n._zod.values=r,Q(n,"pattern",o=>{let i=Ur(o.def.entries).filter(s=>us.has(typeof s));return new RegExp(i.length?`^(${i.map(s=>Qn(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),n._zod.parse=(o,i)=>{let s=o.value;return r.has(s)||o.issues.push({code:"invalid_value",values:t,input:s,inst:n}),o}}),ra=E("$ZodLiteral",(n,e)=>{U.init(n,e);let t=new Set(e.values);n._zod.values=t,Q(n,"pattern",r=>{let o=r.def.values;return new RegExp(o.length?`^(${o.map(i=>typeof i=="string"?Qn(i):i?Qn(i.toString()):String(i)).join("|")})$`:"^[^\\s\\S]$")}),n._zod.parse=(r,o)=>{let i=r.value;return t.has(i)||r.issues.push({code:"invalid_value",values:e.values,input:i,inst:n}),r}});function Zs(n,e){return n.value=e.issues.length?void 0:e.value,n}var oa=E("$ZodOptional",(n,e)=>{U.init(n,e),Q(n,"optin",t=>t.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),n._zod.optout="optional",Q(n,"values",t=>{let r=t.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),Q(n,"pattern",t=>{let r=t.def.innerType._zod.pattern;return r?new RegExp(`^(${qr(r.source)})?$`):void 0}),n._zod.parse=(t,r)=>{if(t.value===void 0){if(e.innerType._zod.optin!=="defaulted")return t;let o=e.innerType._zod.run({value:t.value,issues:[]},r);return o instanceof Promise?o.then(i=>Zs(t,i)):Zs(t,o)}return e.innerType._zod.run(t,r)}});var ia=E("$ZodLazy",(n,e)=>{U.init(n,e),is(n._zod,"innerType",()=>{let t=e;return t._cachedInner||(t._cachedInner=e.getter()),t._cachedInner}),Q(n,"pattern",t=>t.innerType?._zod?.pattern),Q(n,"propValues",t=>t.innerType?._zod?.propValues),Q(n,"optin",t=>t.innerType?._zod?.optin??void 0),Q(n,"optout",t=>t.innerType?._zod?.optout??void 0),n._zod.parse=(t,r)=>n._zod.innerType._zod.run(t,r)}),sa=E("$ZodCustom",(n,e)=>{ie.init(n,e),U.init(n,e),n._zod.parse=(t,r)=>t,n._zod.check=t=>{let r=t.value,o=e.fn(r);if(o instanceof Promise)return o.then(i=>Gs(i,t,r,n));Gs(o,t,r,n)}});function Gs(n,e,t,r){if(!n){let o={code:"custom",input:t,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(et(o))}}var al=()=>{let n={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(i){return n[i]??null}let t={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function o(i,s){return i==="number"&&typeof s=="number"&&!Number.isFinite(s)?String(s):r[i]??i}return i=>{switch(i.code){case"invalid_type":{let s=o(i.expected),a=gs(i.input),d=o(a,i.input);return`Invalid input: expected ${s}, received ${d}`}case"invalid_value":return i.values.length===1?`Invalid input: expected ${Xr(i.values[0])}`:`Invalid option: expected one of ${Wr(i.values,"|")}`;case"too_big":{let s=i.exact?"exactly ":i.inclusive?"<=":"<",a=e(i.origin);return a?`Too big: expected ${i.origin??"value"} to have ${s}${i.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${s}${i.maximum.toString()}`}case"too_small":{let s=i.exact?"exactly ":i.inclusive?">=":">",a=e(i.origin);return a?`Too small: expected ${i.origin} to have ${s}${i.minimum.toString()} ${a.unit}`:`Too small: expected ${i.origin} to be ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${t[s.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${Wr(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return i.options&&Array.isArray(i.options)&&i.options.length>0?`Invalid discriminator value. Expected ${i.options.map(a=>`'${a}'`).join(" | ")}`:i.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function aa(){return{localeError:al()}}var da;var mo=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function ca(){return new mo}(da=globalThis).__zod_globalRegistry??(da.__zod_globalRegistry=ca());var On=globalThis.__zod_globalRegistry;function ua(n){return n.checks&&(n.checks=[...n.checks]),n}function la(n,e){return new n(ua({type:"string",...D(e)}))}function fa(n,e){return new n({type:"string",format:"email",check:"string_format",abort:!1,...D(e)})}function pa(n,e){return new n({type:"string",format:"url",check:"string_format",abort:!1,...D(e)})}function ha(n,e){return new n(ua({type:"number",checks:[],...D(e)}))}function ga(n,e){return new n({type:"number",check:"number_format",abort:!1,format:"safeint",...D(e)})}function ma(n,e){return new n({type:"boolean",...D(e)})}function ya(n,e){return new n({type:"null",...D(e)})}function ba(n){return new n({type:"unknown"})}function va(n,e){return new n({type:"never",...D(e)})}function wa(n,e){return new Ps({check:"less_than",...D(e),value:n,inclusive:!0})}function ka(n,e){return new Es({check:"greater_than",...D(e),value:n,inclusive:!0})}function ll(n,e){return new Ms({check:"multiple_of",...D(e),value:n})}function yo(n,e){return new zs({check:"max_length",...D(e),maximum:n})}function tt(n,e){return new Is({check:"min_length",...D(e),minimum:n})}function rt(n,e){return new Ts({check:"string_format",format:"regex",...D(e),pattern:n})}function xa(n,e,t){return new n({type:"custom",check:"custom",fn:e,...D(t)})}function Sa(n,e){let t=fl(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(et(o,r.value,t._zod.def));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),r.issues.push(et(i))}},n(r.value,r)),e);return t}function fl(n,e){let t=new ie({check:"custom",...D(e)});return t._zod.check=n,t}function Ra(n){let e=new ie({check:"describe"});return e._zod.onattach=[t=>{let r=On.get(t)??{};On.add(t,{...r,description:n})}],e._zod.check=()=>{},e}var ee=E("ZodMiniType",(n,e)=>{if(!n._zod)throw new Error("Uninitialized schema in ZodMiniType.");U.init(n,e),n.def=e,n.type=e.type},{get with(){return this.check},set with(n){nn(this,"with",n)},parse(n,e){return so(this,n,e,{callee:this.parse})},parseAsync(n,e){return ao(this,n,e,{callee:this.parseAsync})},safeParse(n,e){return co(this,n,e)},safeParseAsync(n,e){return uo(this,n,e)},check(...n){let e=this.def;return this.clone({...e,checks:[...e.checks??[],...n.map(t=>typeof t=="function"?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]},{parent:!0})},clone(n,e){return $n(this,n,e)},brand(){return this},register(n,e){return n.add(this,e),this},apply(n,...e){return e.length===0?n(this):n(this,...e)}}),Aa=E("ZodMiniString",(n,e)=>{ho.init(n,e),ee.init(n,e)});function F(n){return la(Aa,n)}var Oa=E("ZodMiniStringFormat",(n,e)=>{Bt.init(n,e),Aa.init(n,e)}),gl=E("ZodMiniEmail",(n,e)=>{Vs.init(n,e),Oa.init(n,e)});function $b(n){return fa(gl,n)}var ml=E("ZodMiniURL",(n,e)=>{Us.init(n,e),Oa.init(n,e)});function Ab(n){return pa(ml,n)}var _a=E("ZodMiniNumber",(n,e)=>{go.init(n,e),ee.init(n,e)});function tn(n){return ha(_a,n)}var yl=E("ZodMiniNumberFormat",(n,e)=>{Ws.init(n,e),_a.init(n,e)});function Ob(n){return ga(yl,n)}var bl=E("ZodMiniBoolean",(n,e)=>{qs.init(n,e),ee.init(n,e)});function _b(n){return ma(bl,n)}var vl=E("ZodMiniNull",(n,e)=>{Hs.init(n,e),ee.init(n,e)});function Pa(n){return ya(vl,n)}var wl=E("ZodMiniUnknown",(n,e)=>{Js.init(n,e),ee.init(n,e)});function ot(){return ba(wl)}var kl=E("ZodMiniNever",(n,e)=>{Ys.init(n,e),ee.init(n,e)});function xl(n){return va(kl,n)}var Sl=E("ZodMiniArray",(n,e)=>{Xs.init(n,e),ee.init(n,e)});function Ea(n,e){return new Sl({type:"array",element:n,...D(e)})}var bo=E("ZodMiniObject",(n,e)=>{Qs.init(n,e),ee.init(n,e),ys(n,"shape",t=>t._zod.def.shape,!1)});function se(n,e){let t={type:"object",shape:n??{},...D(e)};return new bo(t)}function _n(n,e){return new bo({type:"object",shape:n,catchall:xl(),...D(e)})}function Pb(n,e){return new bo({type:"object",shape:n,catchall:ot(),...D(e)})}function Ma(n,e){return ps(n,e)}var Rl=E("ZodMiniUnion",(n,e)=>{ea.init(n,e),ee.init(n,e)});function Na(n,e){return new Rl({type:"union",options:n,...D(e)})}var $a=E("ZodMiniRecord",(n,e)=>{na.init(n,e),ee.init(n,e)});function Eb(n,e,t){return!e||!e._zod?new $a({type:"record",keyType:F(),valueType:n,...D(e)}):new $a({type:"record",keyType:n,valueType:e,...D(t)})}var $l=E("ZodMiniEnum",(n,e)=>{ta.init(n,e),ee.init(n,e),n.options=[...n._zod.values]});function za(n,e){let t=Array.isArray(n)?Object.fromEntries(n.map(r=>[r,r])):n;return new $l({type:"enum",entries:t,...D(e)})}var Al=E("ZodMiniLiteral",(n,e)=>{ra.init(n,e),ee.init(n,e)});function it(n,e){return new Al({type:"literal",values:Array.isArray(n)?n:[n],...D(e)})}var Ol=E("ZodMiniOptional",(n,e)=>{oa.init(n,e),ee.init(n,e)});function W(n){return new Ol({type:"optional",innerType:n})}var _l=E("ZodMiniLazy",(n,e)=>{ia.init(n,e),ee.init(n,e)});function Mb(n){return new _l({type:"lazy",getter:n})}var Pl=E("ZodMiniCustom",(n,e)=>{sa.init(n,e),ee.init(n,e)});function Ut(n,e={}){return xa(Pl,n,e)}function Nb(n,e){return Sa(n,e)}var zb=Ra;oe().localeError||oe(aa());var L=n=>typeof n=="object"&&n!==null?n._zod?.def:void 0,El=n=>{if(typeof n!="object"||n===null||!("_zod"in n))return;let e=On.get(n)?.description;return typeof e=="string"?e:void 0};var Ml=(n,e)=>n?.src?.(e)??e,Wt=n=>typeof n=="string"&&n.length<2049&&/^(?![^/?#]*:|\/\/)(?!(?:.*\/)?\.\.?(?:[/?#]|$))(?!.*%2e)[^\\\s]+$/i.test(n),vo=(n,e=1)=>e>0&&n===void 0||Number.isInteger(n)&&n>=e;function wo(n){let e=n??{};return Wt(e.href)&&typeof e.name=="string"&&/^.{1,255}$/s.test(e.name)&&/^[\w.+-]{1,60}\/[\w.+-]{1,60}$/.test(e.type)&&vo(e.bytes,0)&&vo(e.width)&&vo(e.height)&&(e.caption===void 0||typeof e.caption=="string"&&e.caption.length<501)&&(e.poster===void 0||Wt(e.poster))&&(e.captions===void 0||Wt(e.captions))&&(e.duration===void 0||typeof e.duration=="number"&&Number.isFinite(e.duration)&&e.duration>0)&&(e.at===void 0||Ia(e.at)!==void 0)}function Ia(n){return typeof n=="string"&&n.length<41&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:?\d{2})$/.test(n)&&Number.isFinite(Date.parse(n))?n:void 0}var Ta=n=>n.type.startsWith("image/"),ja=n=>n.type.startsWith("video/");function Nl(n){let e=n.duration===void 0?0:Math.round(n.duration);if(e<1)return"a video";if(e<60)return`a ${e}-second video`;let t=Math.round(e/60);return t<60?`a ${t}-minute video`:`a ${Math.floor(t/60)}-hour${t%60>0?` ${t%60}-minute`:""} video`}var zl=(n,e)=>e==="image"?Ta(n):e==="video"?ja(n):!0,Il=n=>`${n==="image"?"an image":n==="video"?"a video":"a file"} the host stored, at a path on this host`,st=n=>(Array.isArray(n)?n:[n]).filter(wo),Da=Symbol.for("@graview/core:file"),Tl=(n,e)=>(Object.defineProperty(L(n),Da,{value:e,enumerable:!0}),n);function Fa(n){let e=L(n);return e?.[Da]??(e?.innerType?Fa(e.innerType):void 0)}var jl=()=>({href:F(),name:F(),type:F(),bytes:tn(),width:W(tn()),height:W(tn()),caption:W(F()),poster:W(F()),duration:W(tn()),captions:W(F()),at:W(F())});function Iv(n){return Tl(se(jl()).check(Ut(e=>wo(e)&&zl(e,n),Il(n))),n)}var qt=/^(?:https?:\/\/[^\s<>"'`\\]+|@?[A-Za-z0-9][\w.~-]*(?:\/[\w.~-]+)*)$/,Ht=n=>typeof n=="string"&&n.length<501&&qt.test(n);var La=n=>typeof n=="object"&&n!==null?n._zod?.def:void 0,Dl=/^@(?:https?:\/\/[^\s<>"'`\\#?]+|[A-Za-z0-9][\w.~-]*(?:\/[\w.~-]+)*)\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function Ca(n){if(typeof n!="string"||!n.startsWith("@")||!Dl.test(n))return;let e=n.lastIndexOf("/"),t=n.slice(0,e),r=n.slice(e+1),o=/^@https?:\/\//.test(t)||!t.includes("/")?t.slice(1):t;return Ht(o)?{address:o,kind:r}:void 0}var Fl=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*:\S[^\n]{0,199}$/,Ll=n=>`${n.kind}:${n.id}`;function Za(n,e){if(typeof n!="string"||!Fl.test(n))return;let t=n.indexOf(":"),r=n.slice(0,t);return e.kinds.includes(r)?{address:e.address,kind:r,id:n.slice(t+1)}:void 0}function Cl(n,e){return(Array.isArray(n)?n:n==null?[]:[n]).flatMap(r=>{let o=Za(r,e);return o?[o]:[]})}var Ga=Symbol.for("@graview/core:linked"),Fv=(n,e)=>(Object.defineProperty(La(n),Ga,{value:e,enumerable:!0}),n);function at(n){let e=La(n);return e?e[Ga]??at(e.innerType):void 0}function Zl(n){let e=n?.fields?.shape??{},t=new Map;for(let[r,o]of Object.entries(e)){let i=at(o);i&&t.set(r,i)}return t}function Gl(n){if(n.to==="*"||n.to.length===0)return;let e=n.to.map(Ca);if(e.some(r=>!r))return;let t=e[0].address;if(!e.some(r=>r.address!==t))return{address:t,kinds:[...new Set(e.map(r=>r.kind))],cardinality:n.cardinality??"many",...n.description?{description:n.description}:{}}}var Kl=n=>n.to!=="*"&&n.to.some(e=>typeof e=="string"&&e.startsWith("@"));function Lv(n){return Object.fromEntries(Object.entries(n??{}).filter(([,e])=>!Kl(e)))}function Cv(n){let e=new Map;for(let[t,r]of Object.entries(n??{})){let o=Gl(r);o&&e.set(t,o)}return e}var ko=new WeakMap;function Vl(n,e){e?ko.set(n,e):ko.delete(n)}var Ka=n=>ko.get(n);var Jt=["sun","mon","tue","wed","thu","fri","sat"],Bl=["day","week","month","year"],En=n=>`${n}Repeat`,ct=n=>n.endsWith("Repeat")&&n.length>6?n.slice(0,-6):void 0,Ua=/^\d{4}-\d{2}-\d{2}$/,Wa=Symbol.for("@graview/core:repeat");function Yt(n){let e=L(n);return!!e&&(e[Wa]===1||Yt(e.innerType))}var Ul=n=>(Object.defineProperty(L(n),Wa,{value:1,enumerable:!0}),n),xo=(n,e,t)=>n===void 0||Number.isInteger(n)&&n>=e&&n<=t,Va=(n,e)=>n===void 0||Array.isArray(n)&&n.length<=e&&n.every(t=>typeof t=="string"&&Ua.test(t)),Wl=["every","interval","on","until","count","except","continues"],qa=n=>Mn(n)&&Object.keys(n).every(e=>Wl.includes(e))&&xo(n.interval,1,99)&&xo(n.count,1,1e3)&&Va(n.until===void 0?void 0:[n.until],1)&&Va(n.except,500)&&(n.continues===void 0||typeof n.continues=="string"&&n.continues.length<=200)&&(n.on===void 0||Array.isArray(n.on)&&n.on.length>0&&n.on.length<=31&&n.on.every(e=>n.every==="week"?Jt.includes(e):n.every==="month"&&e!==0&&xo(e,-1,31))),Kv=()=>Ul(ot().check(Ut(n=>n===null||qa(n),"how a date repeats, or null"))),dt=n=>Date.UTC(+n.slice(0,4),+n.slice(5,7)-1,+n.slice(8,10)),Ha=n=>new Date(n).toISOString().slice(0,10),So=(n,e)=>Ha(dt(n)+e*864e5),Ba=(n,e,t)=>{let r=new Date(Date.UTC(n,e+1,0)).getUTCDate();return Ha(Date.UTC(n,e,t<0||t>r?r:t))},Mn=n=>typeof n=="object"&&n!==null&&Bl.includes(n.every);function Pn(n,e,t={}){let r=n.slice(0,10),o=n.slice(10),i=[];if(!Ua.test(r))return i;let s=Math.max(1,e.interval??1),a=e.every,d=t.from&&t.from>r?t.from.slice(0,10):r,l=[e.until,t.to?.slice(0,10)].filter(Boolean).sort()[0],u=t.limit??1e3,p=new Set(e.except??[]),c=+r.slice(0,4),f=+r.slice(5,7)-1,g=+r.slice(8,10),h=So(r,-new Date(dt(r)).getUTCDay()),y=(e.on?.length?e.on:[a==="week"?Jt[new Date(dt(r)).getUTCDay()]:g]).map(O=>typeof O=="string"?Jt.indexOf(O):O),b=a==="day"?1:a==="week"?7:0,x=(+d.slice(0,4)-c)*12+(+d.slice(5,7)-1-f),$=e.count?0:Math.max(0,Math.floor((b?(dt(d)-dt(b===7?h:r))/864e5/b:a==="month"?x:x/12)/s)-1),w=0;for(let O=0;O<5e4&&i.length<u;O++,$++){let A=$*s,m=a==="day"?[So(r,A)]:a==="week"?y.map(v=>So(h,A*7+v)):a==="month"?y.map(v=>Ba(c,f+A,v)):[Ba(c+A,f,g)];for(let v of[...new Set(m)].sort())if(!(v<r)&&(l&&v>l||e.count&&w>=e.count||(w++,v>=d&&!p.has(v)&&i.push(v+o),i.length>=u)))return i}return i}function Ja(n,e,t){if(!Mn(e)||typeof n!="string")return n;let r=Pn(n,e,{from:t,limit:1})[0];if(r)return r;let o=e.until||e.count?Pn(n,e):[];return o[o.length-1]??n}function ql(n,e,t){let r=n[e],o=n[En(e)];return typeof r=="string"&&Mn(o)?Ja(r,o,t):r}var Xt=["human","visitor","agent","rule","system"],Hl=new Set(Xt);function Ro(n){return Hl.has(n?.kind)?n.kind:"system"}function ut(n,e){if(n.onBehalfOf){let{onBehalfOf:s,...a}=n;return`${ut(a,e)}, for ${ut(s,e)}`}let t=Ro(n);if(n.id===void 0)return n.name??(t==="agent"?"an agent":t==="visitor"?"a visitor":t);let r=e.graph.getNode(n.id);if(r)return V(e.schema.tryDefinition(r.kind),r);let o=e.seats?.find(s=>s.principal.id===n.id);if(o)return o.label;let i=e.people?.find(s=>s.id===n.id&&(s.kind===void 0||s.kind===n.kind));return i?i.name:n.name?n.name:/(^|:)migration$/.test(n.id)?"the upgrade":n.id.startsWith("form:")?"a visitor via a form":/[:_/]/.test(n.id)?{human:"somebody",visitor:"a visitor",agent:"an agent",rule:"a rule",system:"the system"}[t]:n.id}var ge="$archived",me=n=>n?.[ge]===!0,Hv=(n,e=!1)=>e==="all"||me(n)===e,$o=n=>n===!0||n==="true"?!0:n==="all"?"all":!1,lt="$leftAlone",Qt=new Set([ge,lt]);var Nn="0.1.64";var pe=class extends Error{constructor(t,r){super(r?`${t}
|
|
1
|
+
import{a as Tr,b as ce,c as qe,d as He,f as Re,g as jr,h as Je,i as qn,j as Ki}from"./chunk.FQLNBIQ5.js";var zt="en-US",Yn=/^\d{4}-\d{2}-\d{2}$/,Fr=/^\d{4}(?:-(?:0[1-9]|1[0-2]))?$/,Lr=/^\d{4}(?:-(?:0[1-9]|1[0-2])(?:-\d{2})?)?$/;function hu(n){if(Yn.test(n))return{from:n,to:n};if(!Fr.test(n))return;if(n.length===4)return{from:`${n}-01-01`,to:`${n}-12-31`};let e=new Date(Date.UTC(+n.slice(0,4),+n.slice(5,7),0)).getUTCDate();return{from:`${n}-01`,to:`${n}-${String(e).padStart(2,"0")}`}}var It=/^\d{4}(-\d\d){2}[T ]\d\d:\d\d(:[\d.]+)?(Z|[+-][\d:]+)?$/,ug=n=>!Number.isNaN(Date.parse(n)),te=(n,e=Date.now())=>{let t=Tt(n);return t?Cr(e,t).day:new Date(e).toISOString().slice(0,10)},Tt=n=>xn(n)??kn,Hn,wn,Jn,kn;function gu(n){Hn=Sn(n.reader),wn=Sn(n.app),Jn=xn(n.readerTimeZone),kn=xn(n.appTimeZone)}function mu(n,e){let t=[Hn,wn,Jn,kn];n.reader!==void 0&&(Hn=Sn(n.reader)),n.app!==void 0&&(wn=Sn(n.app)),n.readerTimeZone!==void 0&&(Jn=xn(n.readerTimeZone)),n.appTimeZone!==void 0&&(kn=xn(n.appTimeZone));try{return e()}finally{[Hn,wn,Jn,kn]=t}}var Bi=n=>Hn??Sn(n)??wn??zt,lg=n=>Sn(n)??wn??zt,jt=n=>Jn??xn(n)??kn,yu=n=>jt(n)??Intl.DateTimeFormat().resolvedOptions().timeZone??"UTC",bu=/^\s*([+\-−]|\d)/;var Dr=new Map;function xn(n){if(n&&!Dr.has(n)){let e=!1;try{new Intl.DateTimeFormat(zt,{timeZone:n}),e=!bu.test(n)}catch{}Dr.set(n,e)}return n&&Dr.get(n)?n:void 0}var Ye=new Map;function Sn(n){if(n&&!Ye.has(n)){let e=!1;try{e=Intl.DateTimeFormat.supportedLocalesOf(n).length>0}catch{}Ye.set(n,e)}return n&&Ye.get(n)?n:void 0}function Ie(n,e,t,r){let o=`${t=Bi(t)}${r?"#":"@"}${JSON.stringify(e)}`,i=Ye.get(o);return i||Ye.set(o,i=r?new Intl.NumberFormat(t,e):new Intl.DateTimeFormat(t,e)),i.format(n).replace(/ /g," ")}var Xe="UTC",Dt=n=>Date.UTC(+n.slice(0,4),+n.slice(5,7)-1,+n.slice(8,10));function Te(n,e){return Fr.test(n)?n.length===4?n:Hi(n,{},e):Yn.test(n)?Ie(Dt(n),{year:"numeric",month:"short",day:"numeric",timeZone:Xe},e):n}function Cr(n,e){let t=`wall@${e??""}`,r=Ye.get(t);r||Ye.set(t,r=new Intl.DateTimeFormat("en-US",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hourCycle:"h23",...e?{timeZone:e}:{}}));let o=Object.fromEntries(r.formatToParts(n).map(i=>[i.type,i.value]));return{day:`${o.year}-${o.month}-${o.day}`,minutes:Number(o.hour)%24*60+Number(o.minute)}}function Ui(n,e,t){let r=Date.UTC(+n.slice(0,4),+n.slice(5,7)-1,+n.slice(8,10),0,e),o=i=>{let s=Cr(i,t);return vu(s.day,s.minutes)-Math.floor(i/6e4)*6e4};return r-o(r-o(r))}var vu=(n,e)=>Date.UTC(+n.slice(0,4),+n.slice(5,7)-1,+n.slice(8,10),0,e),Wi=n=>/[Z+-][\d:]*$/.test(n.slice(16));function qi(n,e,t,r,o=!1){if(!It.test(n))return n;let i=Wi(n),s=Date.parse(n.replace(" ","T")+(i?"":"Z"));if(Number.isNaN(s))return n;let a=i?jt(r):Xe;return Ie(s,{...e,hour:"numeric",minute:"2-digit",...i&&o?{timeZoneName:"short"}:{},...a?{timeZone:a}:{}},t)}var Zr=(n,e,t)=>qi(n,{year:"numeric",month:"short",day:"numeric"},e,t,!0),wu=(n,e,t)=>qi(n,{},e,t);function ku(n,e){if(Yn.test(n))return n;if(!It.test(n))return;if(!Wi(n))return n.slice(0,10);let t=Date.parse(n.replace(" ","T"));return Number.isNaN(t)?void 0:Cr(t,jt(e)).day}function $e(n,e,t={maximumFractionDigits:2}){return Number.isFinite(n)?Ie(n,t,e,!0):String(n)}function xu(n,e={},t){return Yn.test(n)?Ie(Dt(n),{weekday:e.weekday??"long",month:"short",day:"numeric",...e.year?{year:"numeric"}:{},timeZone:Xe},t):n}function Su(n,e){return Yn.test(n)?Ie(Dt(n),{month:"short",day:"numeric",timeZone:Xe},e):n}function Hi(n,e={},t){if(!/^\d{4}-\d{2}/.test(n))return n;let r=e.year??!e.short;return Ie(Dt(`${n.slice(0,7)}-01`),{month:e.short?"short":"long",...r?{year:e.short?"2-digit":"numeric"}:{},timeZone:Xe},t)}var Ru=(n,e="short",t)=>Ie(Date.UTC(1970,0,4+n),{weekday:e,timeZone:Xe},t),$u=(n,e)=>Ie(Date.UTC(1970,0,1,0,Math.round(n)),{hour:"numeric",minute:"2-digit",timeZone:Xe},e),Au=/(?<![\w-])(\d{4}-\d{2}-\d{2})(?![\w-]|:)/g;function Gr(n,e){return n.includes("-")?n.replace(Au,t=>Te(t,e)):n}var Qe=n=>n.charAt(0).toUpperCase()+n.slice(1),Ft=n=>/^.\p{Lu}/u.test(n)?n:n.charAt(0).toLowerCase()+n.slice(1),Ji=(n,e="and")=>n.length>1?`${n.slice(0,-1).join(", ")} ${e} ${n.at(-1)}`:n[0]??"";function B(n){let e=n.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim().toLowerCase();return Qe(e.replace(/\b[a-z]+\b/g,t=>Yi.has(t)?t.toUpperCase():t.endsWith("s")&&Yi.has(t.slice(0,-1))?`${t.slice(0,-1).toUpperCase()}s`:t))}var Yi=new Set("id url uri api ip ioc cve cvss cwe cpe sku vat iban isbn pdf csv json html css sla kpi roi faq ssn ein vin gps sms crm erp seo utm ui ux ai dns ssl tls http https sql uuid mfa sso cto ceo cfo coo rsvp eta".split(" "));function en(n){if(!Xi(n))return B(n);let e=n.replace(/[_\s]+/g," ").trim();return Qe(e)}var Xi=n=>/[A-Z]/.test(n)&&!/^[a-z][a-zA-Z0-9]*$/.test(n);function gg(n){return Xi(n)?en(n):Ft(B(n))}function Ou(n,e){return{...e,kind:n,edges:e.edges??{}}}function Vr(n,e,t){let r=n?.lifecycle;if(!r)return!0;let o=e[r.field];return r.retired==="date"?typeof o!="string"||o.length===0?!0:o>=(t??te()):!r.retired.includes(o)}function K(n,e){if(n?.label)return n.label(e);let t=e.label;return typeof t=="string"&&t.length>0?t:e.id}function _u(n){return n.title??B(n.name)}function Pu(n,e,t){let r=n.tryDefinition(e);return`${$e(t)} ${t===1?X(r,e):ue(n,e).toLowerCase()}`}function ue(n,e){return n.tryDefinition(e)?.plural??`${B(e).toLowerCase()}s`}function Eu(n,e){return Qe(ue(n,e))}function Mu(n,e){let t=ue(n,e);return`All ${/^[A-Z][a-z]/.test(t)?t.charAt(0).toLowerCase()+t.slice(1):t}`}function Lt(n,e){let t=n?.computed&&Object.hasOwn(n.computed,e)?n.computed[e]:void 0;return n?.display?.labels?.[e]??(typeof t=="object"?t.label:void 0)??(e==="label"?"Name":B(e))}var Nu=/^(u[nt]i|use|usu|uti|ubiq|eu|ewe|one|once)/,zu=/^(hour|honest|hono[ur]r?|heir)/;function Qi(n){let e=B(n).toLowerCase();return zu.test(e)?"an":Nu.test(e)?"a":/^[aeiou]/.test(e)?"an":"a"}function Rn(n){return`${Qi(n)} ${B(n).toLowerCase()}`}function X(n,e){return n?.noun??B(e).toLowerCase()}function Ur(n){let e=Object.values(n).filter(r=>typeof r=="number");return Object.entries(n).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function Wr(n,e="|"){return n.map(t=>Xr(t)).join(e)}function ns(n,e){return typeof e=="bigint"?e.toString():e}var Br=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function ts(n){return new Br(n)}function rs(n){return n==null}function qr(n){let e=n.startsWith("^")?1:0,t=n.endsWith("$")?n.length-1:n.length;return n.slice(e,t)}function os(n,e){let t=n/e,r=Math.round(t),o=4*Number.EPSILON*Math.max(Math.abs(t),1);return Math.abs(t-r)<o?0:t-r}var es=Symbol("evaluating");function is(n,e,t){let r;Object.defineProperty(n,e,{get(){if(r!==es)return r===void 0&&(r=es,r=t()),r},set(o){Object.defineProperty(n,e,{value:o})},configurable:!0})}function Zt(n,e,t){Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}function ss(n){let e=Object.getOwnPropertyDescriptor(n,"shape");return e?.get?e.get.raw:e?.value}function Hr(n){return ss(n._zod.def)??n._zod.def.shape}function as(n,e,t){Object.defineProperty(n,e,{get(){let r=t();return Zt(this,e,r),r},enumerable:!0,configurable:!0})}function ds(n,e,t){e in n?Zt(n,e,t):n[e]=t}function Iu(n,e,t,r){let o=Hr(e);for(let i of t){let s=Object.getOwnPropertyDescriptor(o,i);s.enumerable&&(s.get?as(n,i,()=>{let a=e._zod.def.shape[i];return r?r(a,i):a}):ds(n,i,r?r(s.value,i):s.value))}}function Tu(n,e){for(let t of Reflect.ownKeys(e)){let r=Object.getOwnPropertyDescriptor(e,t);r.enumerable&&(r.get?as(n,t,()=>e[t]):ds(n,t,r.value))}}function cs(...n){let e={};for(let t of n){let r=Object.getOwnPropertyDescriptors(t);Object.assign(e,r)}return Object.defineProperties({},e)}var Jr="captureStackTrace"in Error?Error.captureStackTrace:(...n)=>{};function Ct(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Yr(n){if(Ct(n)===!1)return!1;let e=n.constructor;if(e===void 0||typeof e!="function")return!0;let t=e.prototype;return!(Ct(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}var us=new Set(["string","number","symbol"]);function Qn(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function $n(n,e,t){let r=new n._zod.constr(e??n._zod.def);return(!e||t?.parent)&&(r._zod.parent=n),r}function D(n){let e=n;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function Xr(n){return typeof n=="bigint"?n.toString()+"n":typeof n=="string"?`"${n}"`:`${n}`}function ls(n){return Object.keys(n).filter(e=>n[e]._zod.optin!==void 0&&n[e]._zod.optout==="optional")}var fs={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function ps(n,e){if(!Yr(e))throw new Error("Invalid input to extend: expected a plain object");let t=n._zod.def.checks;if(t&&t.length>0){let o=Hr(n);for(let i of Reflect.ownKeys(e))if(Object.getOwnPropertyDescriptor(o,i)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return $n(n,cs(n._zod.def,{shape:ju(n,e)}))}function ju(n,e){let t={};return Iu(t,n,Reflect.ownKeys(Hr(n))),Tu(t,e),t}function Ae(n,e=0){if(n.aborted===!0)return!0;for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue!==!0)return!0;return!1}function hs(n,e=0){if(n.aborted===!0)return!0;for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue===!1)return!0;return!1}function De(n,e){return e.map(t=>{var r;return(r=t).path??(r.path=[]),t.path.unshift(n),t})}function Xn(n){return typeof n=="string"?n:n?.message}function Qr(n,e,t){var r;for(let o=e;o<n.length;o++)(r=n[o]).schema??(r.schema=t)}function Oe(n,e,t){var r;let o=n.inst?._zod?.traits;o?.has("$ZodType")&&(o.has("$ZodCheck")?(r=n).schema??(r.schema=n.inst):n.schema=n.inst);let i=n.schema!==n.inst?n.schema?._zod.def?.error:void 0,s=n.message?n.message:Xn(n.inst?._zod.def?.error?.(n))??Xn(i?.(n))??Xn(e?.error?.(n))??Xn(t.customError?.(n))??Xn(t.localeError?.(n))??"Invalid input",a={};for(let d of Object.keys(n))d==="inst"||d==="schema"||d==="continue"||d==="input"||d==="__proto__"||(a[d]=n[d]);return a.path??(a.path=[]),a.message=s,e?.reportInput&&(a.input=n.input),a}var Du=/[\uD800-\uDBFF]/;function eo(n){let e=n.length;if(!Du.test(n))return e;let t=e;for(let r=0;r<e-1;r++)(n.charCodeAt(r)&64512)===55296&&(n.charCodeAt(r+1)&64512)===56320&&(t--,r++);return t}function no(n){return Array.isArray(n)?"array":typeof n=="string"?"string":"unknown"}function gs(n){let e=typeof n;switch(e){case"number":return Number.isNaN(n)?"nan":"number";case"object":{if(n===null)return"null";if(Array.isArray(n))return"array";let t=n;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}}return e}function et(...n){let[e,t,r]=n;return typeof e=="string"?{message:e,code:"custom",input:t,inst:r}:{...e}}function ms(n,e){for(let t in e){let r=Object.getOwnPropertyDescriptor(e,t);r.get?Object.defineProperty(n,t,{...r,enumerable:!1}):Fu(n,t,r.value)}}function nn(n,e,t,r=!0){return Object.defineProperty(n,e,{configurable:!0,writable:!0,enumerable:r,value:t}),t}function to(n,e,t){return nn(n,e,t,!1)}function Fu(n,e,t){Object.defineProperty(n,e,{configurable:!0,get(){return this==null?t:nn(this,e,t.bind(this))},set(r){nn(this,e,r)}})}function Lu(n,e){let t=Object.getPrototypeOf(n);return e in t?void 0:t}var Kr,je=!1,Cu={configurable:!0,get(){je=!0}};function Q(n,e,t){let r=Object.getPrototypeOf(n._zod);if(e in r&&Kr!==n._zod){Kr=void 0;return}Kr=n._zod,Object.defineProperty(r,e,{configurable:!0,get(){Object.defineProperty(this,e,Cu);let o=je;je=!1;try{let i=t(this);return je?delete this[e]:Object.defineProperty(this,e,{configurable:!0,writable:!0,value:i}),je=je||o,i}catch(i){throw delete this[e],je=je||o,i}},set(o){Object.defineProperty(this,e,{configurable:!0,writable:!0,value:o})}})}function ys(n,e,t,r){let o=Lu(n,e);o&&Object.defineProperty(o,e,{configurable:!0,get(){let i={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,e,i),i.value=t(this),Object.defineProperty(this,e,i),i.value},set(i){Object.defineProperty(this,e,{configurable:!0,writable:!0,enumerable:r,value:i})}})}var bs;var ro={value:void 0,enumerable:!1},vs="captureStackTrace"in Error?Error:null;function Zu(n){let e=vs;if(e){let t=e.stackTraceLimit;if(typeof t=="number"){try{e.stackTraceLimit=0}catch{return vs=null,new n}try{return new n}finally{e.stackTraceLimit=t}}}return new n}function E(n,e,t,r){let o={};function i(c){this.def=c,this.constr=p,this.traits=new Set}i.prototype=o;let s=t,a=s&&new WeakSet;function d(c,f){if(c._zod){if(c._zod.traits.has(n))return}else{ro.value=new i(f);try{Object.defineProperty(c,"_zod",ro)}finally{ro.value=void 0}}if(c._zod.traits.add(n),e(c,f),a){let h=Object.getPrototypeOf(c),y=c._zod.constr.prototype,b=h;for(;b&&b!==y;)b=Object.getPrototypeOf(b);let x=b??h;a.has(x)||(a.add(x),ms(x,s))}let g=p.prototype;for(let h in g)Object.prototype.hasOwnProperty.call(g,h)&&(h in c||(c[h]=g[h].bind(c)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:n});function p(c){let f=r?.Parent?Zu(u):this;d(f,c);let g=f._zod.deferred;if(g){for(let y of g)y();f._zod.deferred=void 0}let h=globalThis.__zod_globalConfig?.postProcessor;return h&&h(f),f}return Object.defineProperty(p,"init",{value:d}),Object.defineProperty(p,Symbol.hasInstance,{value:c=>r?.Parent&&c instanceof r.Parent?!0:c?._zod?.traits?.has(n)}),Object.defineProperty(p,"name",{value:n}),p}var Pe=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};(bs=globalThis).__zod_globalConfig??(bs.__zod_globalConfig={});var An=globalThis.__zod_globalConfig;function oe(n){return n&&Object.assign(An,n),An}function Gu(){let n=this._zod;return n.message??(n.message=JSON.stringify(n.def,ns,2)),n.message}function Vu(n){this._zod.message=n}var Ku={get:Gu,set:Vu,enumerable:!0,configurable:!0},io={value:void 0,enumerable:!1},ws=new WeakSet([Object.prototype,Error.prototype]),ks=(n,e)=>{n.name="$ZodError",io.value=e,Object.defineProperty(n,"issues",io),io.value=void 0,Object.defineProperty(n,"message",Ku);let t=Object.getPrototypeOf(n);ws.has(t)||(ws.add(t),Object.defineProperty(t,"toString",{configurable:!0,enumerable:!1,get(){let r=()=>this.message;return Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0}),r},set(r){Object.defineProperty(this,"toString",{value:r,configurable:!0,writable:!0})}}))},Sg=E("$ZodError",ks),nt=E("$ZodError",ks,void 0,{Parent:Error});var Uu=n=>{let e=(t,r,o,i)=>{let s=o?{...o,async:!1}:{async:!1},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new Pe;if(a.issues.length){let d=new(i?.Err??n)(a.issues.map(l=>Oe(l,s,oe())));throw Jr(d,i?.callee??e),d}return a.value};return e},so=Uu(nt),Wu=n=>{let e=async(t,r,o,i)=>{let s=o?{...o,async:!0}:{async:!0},a=t._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){let d=new(i?.Err??n)(a.issues.map(l=>Oe(l,s,oe())));throw Jr(d,i?.callee??e),d}return a.value};return e},ao=Wu(nt),qu=n=>(e,t,r)=>{let o=r?{...r,async:!1}:{async:!1},i=e._zod.run({value:t,issues:[]},o);if(i instanceof Promise)throw new Pe;return i.issues.length?xs(n,i.issues,o):{success:!0,data:i.value}},co=qu(nt);function xs(n,e,t){let r;return{success:!1,get error(){return r||(r=new n(e.map(o=>Oe(o,t,oe()))),e=void 0,t=void 0),r},set error(o){r=o,e=void 0,t=void 0}}}var Hu=n=>async(e,t,r)=>{let o=r?{...r,async:!0}:{async:!0},i=e._zod.run({value:t,issues:[]},o);return i instanceof Promise&&(i=await i),i.issues.length?xs(n,i.issues,o):{success:!0,data:i.value}},uo=Hu(nt);var Ss=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var Rs=/^https?$/;var $s=/^[\s\S]{0,}$/;var lo=/^-?\d+(?:\.\d+)?$/,As=/^(?:true|false)$/i,Os=/^null$/i;var ie=E("$ZodCheck",(n,e)=>{var t;n._zod??(n._zod={}),n._zod.def=e,(t=n._zod).onattach??(t.onattach=[])});var _s=n=>{let e=n.value;return!rs(e)&&e.length!==void 0},Gt={number:"number",bigint:"bigint",object:"date"},Ps=E("$ZodCheckLessThan",(n,e)=>{ie.init(n,e);let t=Gt[typeof e.value];n._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:Gt[typeof r.value]??t,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),Es=E("$ZodCheckGreaterThan",(n,e)=>{ie.init(n,e);let t=Gt[typeof e.value];n._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:Gt[typeof r.value]??t,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),Ms=E("$ZodCheckMultipleOf",(n,e)=>{ie.init(n,e),n._zod.check=t=>{if(typeof t.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof t.value=="bigint"?e.value!==BigInt(0)&&t.value%e.value===BigInt(0):os(t.value,e.value)===0)||t.issues.push({origin:typeof t.value,code:"not_multiple_of",divisor:e.value,input:t.value,inst:n,continue:!e.abort})}}),Ns=E("$ZodCheckNumberFormat",(n,e)=>{ie.init(n,e),e.format=e.format||"float64";let t=e.format?.includes("int"),r=t?"int":"number",[o,i]=fs[e.format];n._zod.check=s=>{let a=s.value;if(t){if(!Number.isInteger(a)){s.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:a,inst:n});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:r,inclusive:!0,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:r,inclusive:!0,continue:!e.abort});return}}a<o&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:n,continue:!e.abort}),a>i&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:i,inclusive:!0,inst:n,continue:!e.abort})}});var zs=E("$ZodCheckMaxLength",(n,e)=>{var t;ie.init(n,e),(t=n._zod.def).when??(t.when=_s),n._zod.check=r=>{let o=r.value,i=o.length;if((typeof o=="string"&&i>e.maximum?eo(o):i)<=e.maximum)return;let a=no(o);r.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:n,continue:!e.abort})}}),Is=E("$ZodCheckMinLength",(n,e)=>{var t;ie.init(n,e),(t=n._zod.def).when??(t.when=_s),n._zod.check=r=>{let o=r.value,i=o.length;if((typeof o=="string"&&i>=e.minimum&&i<e.minimum*2?eo(o):i)>=e.minimum)return;let a=no(o);r.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:n,continue:!e.abort})}});var po=E("$ZodCheckStringFormat",(n,e)=>{var t,r;ie.init(n,e),e.pattern?(t=n._zod).check??(t.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:n,continue:!e.abort})}):(r=n._zod).check??(r.check=()=>{})}),Ts=E("$ZodCheckRegex",(n,e)=>{po.init(n,e),n._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:n,continue:!e.abort})}});var Ds={major:4,minor:6,patch:5};var U=E("$ZodType",(n,e)=>{var t;n??(n={}),n._zod.def=e,n._zod.bag=n._zod.bag||{},n._zod.version=Ds;let r=n._zod.def.checks,o=n._zod.traits.has("$ZodCheck")?[n,...r??[]]:r?.length?[...r]:[];for(let i of o)for(let s of i._zod.onattach)s(n);if(o.length===0)(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{let i=(a,d,l)=>{if(a.memo)return a;let u=Ae(a),p;for(let c of d){if(c._zod.def.when){if(hs(a)||!c._zod.def.when(a))continue}else if(u)continue;let f=a.issues.length,g=c._zod.check(a);if(g instanceof Promise&&l?.async===!1)throw new Pe;if(p||g instanceof Promise)p=(p??Promise.resolve()).then(async()=>{await g,a.issues.length!==f&&(Qr(a.issues,f,n),u||(u=Ae(a,f)))});else{if(a.issues.length===f)continue;Qr(a.issues,f,n),u||(u=Ae(a,f))}}return p?p.then(()=>a):a},s=(a,d,l)=>{if(Ae(a))return a.aborted=!0,a;let u=i(d,o,l);if(u instanceof Promise){if(l.async===!1)throw new Pe;return u.then(p=>n._zod.parse(p,l))}return n._zod.parse(u,l)};n._zod.run=(a,d)=>{if(d.skipChecks)return n._zod.parse(a,d);if(d.direction==="backward"){let u=n._zod.parse({value:a.value,issues:[]},{...d,skipChecks:!0});return u instanceof Promise?u.then(p=>s(p,a,d)):s(u,a,d)}let l=n._zod.parse(a,d);if(l instanceof Promise){if(d.async===!1)throw new Pe;return l.then(u=>i(u,o,d))}return i(l,o,d)}}},{get"~standard"(){return to(this,"~standard",Yu(this))},set"~standard"(n){nn(this,"~standard",n)}}),Vs=(n,e)=>n.issues.length?{issues:n.issues.map(t=>Oe(t,e,oe()))}:{value:n.value};async function Ju(n,e){let t={async:!0};return Vs(await n._zod.run({value:e,issues:[]},t),t)}function Yu(n){return{validate:e=>{let t={async:!1};try{let r=n._zod.run({value:e,issues:[]},t);if(!(r instanceof Promise))return Vs(r,t)}catch{}return Ju(n,e)},vendor:"zod",version:1}}var ho=E("$ZodString",(n,e)=>{U.init(n,e),n._zod.pattern=e.pattern??$s,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=String(t.value)}catch{}return typeof t.value=="string"||t.issues.push({expected:"string",code:"invalid_type",input:t.value,inst:n}),t}}),Bt=E("$ZodStringFormat",(n,e)=>{po.init(n,e),ho.init(n,e)});var Ks=E("$ZodEmail",(n,e)=>{e.pattern??(e.pattern=Ss),Bt.init(n,e)}),Bs=1,Vt=2;function Xu(n){try{return typeof URL<"u"&&typeof URL.canParse=="function"?URL.canParse(n):(new URL(n),!0)}catch{return!1}}function Qu(n,e){return!("normalize"in e)&&!("hostname"in e)&&!("protocol"in e)?Xu(n)||Vt:el(n,e)}function el(n,e){if(!e.normalize&&e.protocol?.source===Rs.source&&!/^https?:\/\//i.test(n))return Bs;try{if(typeof URL<"u"){let t=URL;if(typeof t.parse=="function")return t.parse(n)??Vt}return new URL(n)}catch{return Vt}}var nl=/[\t\n\r]/g;function Fs(n){return n.replace(nl,"")}function tl(n,e){return e.lastIndex=0,e.test(n.hostname)}function rl(n,e){return e.lastIndex=0,e.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)}var Us=E("$ZodURL",(n,e)=>{Bt.init(n,e),n._zod.check=t=>{try{let r=t.value.trim(),o=Qu(r,e);if(o===Bs){t.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:t.value,inst:n,continue:!e.abort});return}if(o===Vt){t.issues.push({code:"invalid_format",format:"url",input:t.value,inst:n,continue:!e.abort});return}if(o===!0){t.value=Fs(r);return}e.hostname&&!tl(o,e.hostname)&&t.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:t.value,inst:n,continue:!e.abort}),e.protocol&&!rl(o,e.protocol)&&t.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:t.value,inst:n,continue:!e.abort}),t.value=e.normalize?o.href:Fs(r);return}catch{t.issues.push({code:"invalid_format",format:"url",input:t.value,inst:n,continue:!e.abort})}}});var go=E("$ZodNumber",(n,e)=>{U.init(n,e),n._zod.pattern=lo,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=Number(t.value)}catch{}let o=t.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return t;let i=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:String(o):void 0;return t.issues.push({expected:"number",code:"invalid_type",input:o,inst:n,...i?{received:i}:{}}),t}}),Ws=E("$ZodNumberFormat",(n,e)=>{Ns.init(n,e),go.init(n,e)}),qs=E("$ZodBoolean",(n,e)=>{U.init(n,e),n._zod.pattern=As,n._zod.parse=(t,r)=>{if(e.coerce)try{t.value=!!t.value}catch{}let o=t.value;return typeof o=="boolean"||t.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:n}),t}});var Hs=E("$ZodNull",(n,e)=>{U.init(n,e),n._zod.pattern=Os,n._zod.values=new Set([null]),n._zod.parse=(t,r)=>{let o=t.value;return o===null||t.issues.push({expected:"null",code:"invalid_type",input:o,inst:n}),t}});var Js=E("$ZodUnknown",(n,e)=>{U.init(n,e),n._zod.parse=t=>t}),Ys=E("$ZodNever",(n,e)=>{U.init(n,e),n._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:n}),t)});function Ls(n,e,t){n.issues.length&&e.issues.push(...De(t,n.issues)),e.value[t]=n.value}var Xs=E("$ZodArray",(n,e)=>{U.init(n,e);let t=An.memoizer;t?.attach(n),n._zod.parse=(r,o)=>{let i=r.value;if(!Array.isArray(i))return r.issues.push({expected:"array",code:"invalid_type",input:i,inst:n}),r;r.value=t?t.alloc(n,r,Array(i.length),o):Array(i.length);let s=[],a=o?.abortEarly;for(let d=0;d<i.length;d++){let l=i[d],u=e.element._zod.run({value:l,issues:[]},o);if(u instanceof Promise)s.push(u.then(p=>Ls(p,r,d)));else if(Ls(u,r,d),a&&u.issues.length!==0&&Ae(u))break}return s.length?Promise.all(s).then(()=>r):r}});function Kt(n,e,t,r,o,i){let s=t in r,a=i==="optional";if(!(!s&&a&&o==="optional")){if(n.issues.length){if(o!==void 0&&a&&!s)return;e.issues.push(...De(t,n.issues))}if(!s&&o===void 0){n.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[t]});return}n.value===void 0?(s||o==="defaulted"&&!a)&&(e.value[t]=void 0):e.value[t]=n.value}}var ol=[];function il(n){let e=Object.keys(n.shape),t=Object.getOwnPropertySymbols(n.shape),r=t.length?t:ol,o=r.length?[...e,...r]:e;for(let s of o)if(!n.shape?.[s]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${String(s)}": expected a Zod schema`);let i=ls(n.shape);return{...n,allKeys:o,symbolKeys:r,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(i)}}function sl(n,e,t,r,o,i,s){let a=[],d=o.keySet,l=o.catchall._zod,u=l.def.type,p=l.optin,c=l.optout,f=0;for(let g in e){if(s&&t.issues.length!==f){if(Ae(t,f))break;f=t.issues.length}if(d.has(g))continue;if(g==="__proto__"){u==="never"&&a.push(g);continue}if(u==="never"){a.push(g);continue}let h=l.run({value:e[g],issues:[]},r);h instanceof Promise?n.push(h.then(y=>Kt(y,t,g,e,p,c))):Kt(h,t,g,e,p,c)}return a.length&&t.issues.push({code:"unrecognized_keys",keys:a,input:e,inst:i,continue:!0}),n.length?Promise.all(n).then(()=>t):t}var Qs=E("$ZodObject",(n,e)=>{U.init(n,e);let t=Object.getOwnPropertyDescriptor(e,"shape"),r=t?.get?t.get.raw:e.shape??{};if(r){let l=()=>{let u={...r};return Object.defineProperty(e,"shape",{value:u}),l.raw=u,u};l.raw=r,Object.defineProperty(e,"shape",{get:l})}let o=ts(()=>il(e));Q(n,"propValues",l=>{let u=l.def.shape,p={};for(let c in u){let f=u[c]._zod;if(f.values){Object.prototype.hasOwnProperty.call(p,c)||Zt(p,c,new Set);for(let g of f.values)p[c].add(g);f.optin!==void 0&&p[c].add(void 0)}}return p});let i=Ct,s=e.catchall,a,d=An.memoizer;d?.attach(n),n._zod.parse=(l,u)=>{a??(a=o.value);let p=l.value;if(!i(p))return l.issues.push({expected:"object",code:"invalid_type",input:p,inst:n}),l;l.value=d?d.alloc(n,l,{},u):{};let c=[],f=a.shape,g=u?.abortEarly,h=l.issues.length;for(let y of a.allKeys){if(g&&l.issues.length!==h){if(Ae(l,h))break;h=l.issues.length}if(y==="__proto__")continue;let b=f[y],x=b._zod.optin,$=b._zod.optout,w=b._zod.run({value:p[y],issues:[]},u);w instanceof Promise?c.push(w.then(O=>Kt(O,l,y,p,x,$))):Kt(w,l,y,p,x,$)}return s?sl(c,p,l,u,o.value,n,g===!0):c.length?Promise.all(c).then(()=>l):l}});function Cs(n,e,t,r){for(let i of n)if(i.issues.length===0)return e.value=i.value,e;let o=n.filter(i=>!Ae(i));return o.length===1?(e.value=o[0].value,o[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:t,errors:n.map(i=>i.issues.map(s=>Oe(s,r,oe())))}),e)}var ea=E("$ZodUnion",(n,e)=>{U.init(n,e),Q(n,"optin",r=>r.def.options.some(o=>o._zod.optin==="defaulted")?"defaulted":r.def.options.some(o=>o._zod.optin!==void 0)?"optional":void 0),Q(n,"optout",r=>r.def.options.some(o=>o._zod.optout==="optional")?"optional":void 0),Q(n,"values",r=>{if(r.def.options.every(o=>o._zod.values))return new Set(r.def.options.flatMap(o=>Array.from(o._zod.values)))}),Q(n,"pattern",r=>{if(r.def.options.every(o=>o._zod.pattern)){let o=r.def.options.map(i=>i._zod.pattern);return new RegExp(`^(${o.map(i=>qr(i.source)).join("|")})$`)}});let t=e.options.length===1?e.options[0]._zod.run:null;n._zod.parse=(r,o)=>{if(t)return t(r,o);let i=!1,s=[];for(let a of e.options){let d=a._zod.run({value:r.value,issues:[]},o);if(d instanceof Promise)s.push(d),i=!0;else{if(d.issues.length===0)return d;s.push(d)}}return i?Promise.all(s).then(a=>Cs(a,r,n,o)):Cs(s,r,n,o)}});var na=E("$ZodRecord",(n,e)=>{U.init(n,e);let t=An.memoizer;t?.attach(n),n._zod.parse=(r,o)=>{let i=r.value;if(!Yr(i))return r.issues.push({expected:"record",code:"invalid_type",input:i,inst:n}),r;let s=[],a=e.keyType._zod.values;if(a&&!e.partial){r.value=t?t.alloc(n,r,{},o):{};let d=new Set;for(let u of a)if(typeof u=="string"||typeof u=="number"||typeof u=="symbol"){if(d.add(typeof u=="number"?u.toString():u),u==="__proto__")continue;let p=e.keyType._zod.run({value:u,issues:[]},o);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(p.issues.length){r.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map(g=>Oe(g,o,oe())),input:u,path:[u],inst:n});continue}let c=p.value;if(c==="__proto__")continue;let f=e.valueType._zod.run({value:i[u],issues:[]},o);f instanceof Promise?s.push(f.then(g=>{g.issues.length&&r.issues.push(...De(u,g.issues)),r.value[c]=g.value})):(f.issues.length&&r.issues.push(...De(u,f.issues)),r.value[c]=f.value)}let l;for(let u in i)if(!d.has(u))if(e.mode==="loose"){if(u==="__proto__")continue;r.value[u]=i[u]}else l=l??[],l.push(u);l&&l.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:n,keys:l,continue:!0})}else{r.value=t?t.alloc(n,r,{},o):{};let d;for(let l of Reflect.ownKeys(i)){if(l==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,l))continue;let u=e.keyType._zod.run({value:l,issues:[]},o);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&lo.test(l)&&u.issues.length){let g=e.keyType._zod.run({value:Number(l),issues:[]},o);if(g instanceof Promise)throw new Error("Async schemas not supported in object keys currently");g.issues.length===0&&(u=g)}if(u.issues.length){e.mode==="loose"?r.value[l]=i[l]:a?(d=d??[],d.push(l)):r.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(g=>Oe(g,o,oe())),input:l,path:[l],inst:n});continue}let c=u.value;if(c==="__proto__")continue;let f=e.valueType._zod.run({value:i[l],issues:[]},o);f instanceof Promise?s.push(f.then(g=>{g.issues.length&&r.issues.push(...De(l,g.issues)),r.value[c]=g.value})):(f.issues.length&&r.issues.push(...De(l,f.issues)),r.value[c]=f.value)}d&&d.length>0&&r.issues.push({code:"unrecognized_keys",input:i,inst:n,keys:d,continue:!0})}return s.length?Promise.all(s).then(()=>r):r}});var ta=E("$ZodEnum",(n,e)=>{U.init(n,e);let t=Ur(e.entries),r=new Set(t);n._zod.values=r,Q(n,"pattern",o=>{let i=Ur(o.def.entries).filter(s=>us.has(typeof s));return new RegExp(i.length?`^(${i.map(s=>Qn(s.toString())).join("|")})$`:"^[^\\s\\S]$")}),n._zod.parse=(o,i)=>{let s=o.value;return r.has(s)||o.issues.push({code:"invalid_value",values:t,input:s,inst:n}),o}}),ra=E("$ZodLiteral",(n,e)=>{U.init(n,e);let t=new Set(e.values);n._zod.values=t,Q(n,"pattern",r=>{let o=r.def.values;return new RegExp(o.length?`^(${o.map(i=>typeof i=="string"?Qn(i):i?Qn(i.toString()):String(i)).join("|")})$`:"^[^\\s\\S]$")}),n._zod.parse=(r,o)=>{let i=r.value;return t.has(i)||r.issues.push({code:"invalid_value",values:e.values,input:i,inst:n}),r}});function Zs(n,e){return n.value=e.issues.length?void 0:e.value,n}var oa=E("$ZodOptional",(n,e)=>{U.init(n,e),Q(n,"optin",t=>t.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),n._zod.optout="optional",Q(n,"values",t=>{let r=t.def.innerType._zod.values;return r?new Set([...r,void 0]):void 0}),Q(n,"pattern",t=>{let r=t.def.innerType._zod.pattern;return r?new RegExp(`^(${qr(r.source)})?$`):void 0}),n._zod.parse=(t,r)=>{if(t.value===void 0){if(e.innerType._zod.optin!=="defaulted")return t;let o=e.innerType._zod.run({value:t.value,issues:[]},r);return o instanceof Promise?o.then(i=>Zs(t,i)):Zs(t,o)}return e.innerType._zod.run(t,r)}});var ia=E("$ZodLazy",(n,e)=>{U.init(n,e),is(n._zod,"innerType",()=>{let t=e;return t._cachedInner||(t._cachedInner=e.getter()),t._cachedInner}),Q(n,"pattern",t=>t.innerType?._zod?.pattern),Q(n,"propValues",t=>t.innerType?._zod?.propValues),Q(n,"optin",t=>t.innerType?._zod?.optin??void 0),Q(n,"optout",t=>t.innerType?._zod?.optout??void 0),n._zod.parse=(t,r)=>n._zod.innerType._zod.run(t,r)}),sa=E("$ZodCustom",(n,e)=>{ie.init(n,e),U.init(n,e),n._zod.parse=(t,r)=>t,n._zod.check=t=>{let r=t.value,o=e.fn(r);if(o instanceof Promise)return o.then(i=>Gs(i,t,r,n));Gs(o,t,r,n)}});function Gs(n,e,t,r){if(!n){let o={code:"custom",input:t,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push(et(o))}}var al=()=>{let n={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(i){return n[i]??null}let t={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},r={nan:"NaN"};function o(i,s){return i==="number"&&typeof s=="number"&&!Number.isFinite(s)?String(s):r[i]??i}return i=>{switch(i.code){case"invalid_type":{let s=o(i.expected),a=gs(i.input),d=o(a,i.input);return`Invalid input: expected ${s}, received ${d}`}case"invalid_value":return i.values.length===1?`Invalid input: expected ${Xr(i.values[0])}`:`Invalid option: expected one of ${Wr(i.values,"|")}`;case"too_big":{let s=i.exact?"exactly ":i.inclusive?"<=":"<",a=e(i.origin);return a?`Too big: expected ${i.origin??"value"} to have ${s}${i.maximum.toString()} ${a.unit??"elements"}`:`Too big: expected ${i.origin??"value"} to be ${s}${i.maximum.toString()}`}case"too_small":{let s=i.exact?"exactly ":i.inclusive?">=":">",a=e(i.origin);return a?`Too small: expected ${i.origin} to have ${s}${i.minimum.toString()} ${a.unit}`:`Too small: expected ${i.origin} to be ${s}${i.minimum.toString()}`}case"invalid_format":{let s=i;return s.format==="starts_with"?`Invalid string: must start with "${s.prefix}"`:s.format==="ends_with"?`Invalid string: must end with "${s.suffix}"`:s.format==="includes"?`Invalid string: must include "${s.includes}"`:s.format==="regex"?`Invalid string: must match pattern ${s.pattern}`:`Invalid ${t[s.format]??i.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${i.divisor}`;case"unrecognized_keys":return`Unrecognized key${i.keys.length>1?"s":""}: ${Wr(i.keys,", ")}`;case"invalid_key":return`Invalid key in ${i.origin}`;case"invalid_union":return i.options&&Array.isArray(i.options)&&i.options.length>0?`Invalid discriminator value. Expected ${i.options.map(a=>`'${a}'`).join(" | ")}`:i.inclusive===!1?"Invalid input: more than one option matched":"Invalid input";case"invalid_element":return`Invalid value in ${i.origin}`;default:return"Invalid input"}}};function aa(){return{localeError:al()}}var da;var mo=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let o={...r,...this._map.get(e)};return Object.keys(o).length?o:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function ca(){return new mo}(da=globalThis).__zod_globalRegistry??(da.__zod_globalRegistry=ca());var On=globalThis.__zod_globalRegistry;function ua(n){return n.checks&&(n.checks=[...n.checks]),n}function la(n,e){return new n(ua({type:"string",...D(e)}))}function fa(n,e){return new n({type:"string",format:"email",check:"string_format",abort:!1,...D(e)})}function pa(n,e){return new n({type:"string",format:"url",check:"string_format",abort:!1,...D(e)})}function ha(n,e){return new n(ua({type:"number",checks:[],...D(e)}))}function ga(n,e){return new n({type:"number",check:"number_format",abort:!1,format:"safeint",...D(e)})}function ma(n,e){return new n({type:"boolean",...D(e)})}function ya(n,e){return new n({type:"null",...D(e)})}function ba(n){return new n({type:"unknown"})}function va(n,e){return new n({type:"never",...D(e)})}function wa(n,e){return new Ps({check:"less_than",...D(e),value:n,inclusive:!0})}function ka(n,e){return new Es({check:"greater_than",...D(e),value:n,inclusive:!0})}function ll(n,e){return new Ms({check:"multiple_of",...D(e),value:n})}function yo(n,e){return new zs({check:"max_length",...D(e),maximum:n})}function tt(n,e){return new Is({check:"min_length",...D(e),minimum:n})}function rt(n,e){return new Ts({check:"string_format",format:"regex",...D(e),pattern:n})}function xa(n,e,t){return new n({type:"custom",check:"custom",fn:e,...D(t)})}function Sa(n,e){let t=fl(r=>(r.addIssue=o=>{if(typeof o=="string")r.issues.push(et(o,r.value,t._zod.def));else{let i=o;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),"input"in i||(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),r.issues.push(et(i))}},n(r.value,r)),e);return t}function fl(n,e){let t=new ie({check:"custom",...D(e)});return t._zod.check=n,t}function Ra(n){let e=new ie({check:"describe"});return e._zod.onattach=[t=>{let r=On.get(t)??{};On.add(t,{...r,description:n})}],e._zod.check=()=>{},e}var ee=E("ZodMiniType",(n,e)=>{if(!n._zod)throw new Error("Uninitialized schema in ZodMiniType.");U.init(n,e),n.def=e,n.type=e.type},{get with(){return this.check},set with(n){nn(this,"with",n)},parse(n,e){return so(this,n,e,{callee:this.parse})},parseAsync(n,e){return ao(this,n,e,{callee:this.parseAsync})},safeParse(n,e){return co(this,n,e)},safeParseAsync(n,e){return uo(this,n,e)},check(...n){let e=this.def;return this.clone({...e,checks:[...e.checks??[],...n.map(t=>typeof t=="function"?{_zod:{check:t,def:{check:"custom"},onattach:[]}}:t)]},{parent:!0})},clone(n,e){return $n(this,n,e)},brand(){return this},register(n,e){return n.add(this,e),this},apply(n,...e){return e.length===0?n(this):n(this,...e)}}),Aa=E("ZodMiniString",(n,e)=>{ho.init(n,e),ee.init(n,e)});function F(n){return la(Aa,n)}var Oa=E("ZodMiniStringFormat",(n,e)=>{Bt.init(n,e),Aa.init(n,e)}),gl=E("ZodMiniEmail",(n,e)=>{Ks.init(n,e),Oa.init(n,e)});function $b(n){return fa(gl,n)}var ml=E("ZodMiniURL",(n,e)=>{Us.init(n,e),Oa.init(n,e)});function Ab(n){return pa(ml,n)}var _a=E("ZodMiniNumber",(n,e)=>{go.init(n,e),ee.init(n,e)});function tn(n){return ha(_a,n)}var yl=E("ZodMiniNumberFormat",(n,e)=>{Ws.init(n,e),_a.init(n,e)});function Ob(n){return ga(yl,n)}var bl=E("ZodMiniBoolean",(n,e)=>{qs.init(n,e),ee.init(n,e)});function _b(n){return ma(bl,n)}var vl=E("ZodMiniNull",(n,e)=>{Hs.init(n,e),ee.init(n,e)});function Pa(n){return ya(vl,n)}var wl=E("ZodMiniUnknown",(n,e)=>{Js.init(n,e),ee.init(n,e)});function ot(){return ba(wl)}var kl=E("ZodMiniNever",(n,e)=>{Ys.init(n,e),ee.init(n,e)});function xl(n){return va(kl,n)}var Sl=E("ZodMiniArray",(n,e)=>{Xs.init(n,e),ee.init(n,e)});function Ea(n,e){return new Sl({type:"array",element:n,...D(e)})}var bo=E("ZodMiniObject",(n,e)=>{Qs.init(n,e),ee.init(n,e),ys(n,"shape",t=>t._zod.def.shape,!1)});function se(n,e){let t={type:"object",shape:n??{},...D(e)};return new bo(t)}function _n(n,e){return new bo({type:"object",shape:n,catchall:xl(),...D(e)})}function Pb(n,e){return new bo({type:"object",shape:n,catchall:ot(),...D(e)})}function Ma(n,e){return ps(n,e)}var Rl=E("ZodMiniUnion",(n,e)=>{ea.init(n,e),ee.init(n,e)});function Na(n,e){return new Rl({type:"union",options:n,...D(e)})}var $a=E("ZodMiniRecord",(n,e)=>{na.init(n,e),ee.init(n,e)});function Eb(n,e,t){return!e||!e._zod?new $a({type:"record",keyType:F(),valueType:n,...D(e)}):new $a({type:"record",keyType:n,valueType:e,...D(t)})}var $l=E("ZodMiniEnum",(n,e)=>{ta.init(n,e),ee.init(n,e),n.options=[...n._zod.values]});function za(n,e){let t=Array.isArray(n)?Object.fromEntries(n.map(r=>[r,r])):n;return new $l({type:"enum",entries:t,...D(e)})}var Al=E("ZodMiniLiteral",(n,e)=>{ra.init(n,e),ee.init(n,e)});function it(n,e){return new Al({type:"literal",values:Array.isArray(n)?n:[n],...D(e)})}var Ol=E("ZodMiniOptional",(n,e)=>{oa.init(n,e),ee.init(n,e)});function W(n){return new Ol({type:"optional",innerType:n})}var _l=E("ZodMiniLazy",(n,e)=>{ia.init(n,e),ee.init(n,e)});function Mb(n){return new _l({type:"lazy",getter:n})}var Pl=E("ZodMiniCustom",(n,e)=>{sa.init(n,e),ee.init(n,e)});function Ut(n,e={}){return xa(Pl,n,e)}function Nb(n,e){return Sa(n,e)}var zb=Ra;oe().localeError||oe(aa());var L=n=>typeof n=="object"&&n!==null?n._zod?.def:void 0,El=n=>{if(typeof n!="object"||n===null||!("_zod"in n))return;let e=On.get(n)?.description;return typeof e=="string"?e:void 0};var Ml=(n,e)=>n?.src?.(e)??e,Wt=n=>typeof n=="string"&&n.length<2049&&/^(?![^/?#]*:|\/\/)(?!(?:.*\/)?\.\.?(?:[/?#]|$))(?!.*%2e)[^\\\s]+$/i.test(n),vo=(n,e=1)=>e>0&&n===void 0||Number.isInteger(n)&&n>=e;function wo(n){let e=n??{};return Wt(e.href)&&typeof e.name=="string"&&/^.{1,255}$/s.test(e.name)&&/^[\w.+-]{1,60}\/[\w.+-]{1,60}$/.test(e.type)&&vo(e.bytes,0)&&vo(e.width)&&vo(e.height)&&(e.caption===void 0||typeof e.caption=="string"&&e.caption.length<501)&&(e.poster===void 0||Wt(e.poster))&&(e.captions===void 0||Wt(e.captions))&&(e.duration===void 0||typeof e.duration=="number"&&Number.isFinite(e.duration)&&e.duration>0)&&(e.at===void 0||Ia(e.at)!==void 0)}function Ia(n){return typeof n=="string"&&n.length<41&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:?\d{2})$/.test(n)&&Number.isFinite(Date.parse(n))?n:void 0}var Ta=n=>n.type.startsWith("image/"),ja=n=>n.type.startsWith("video/");function Nl(n){let e=n.duration===void 0?0:Math.round(n.duration);if(e<1)return"a video";if(e<60)return`a ${e}-second video`;let t=Math.round(e/60);return t<60?`a ${t}-minute video`:`a ${Math.floor(t/60)}-hour${t%60>0?` ${t%60}-minute`:""} video`}var zl=(n,e)=>e==="image"?Ta(n):e==="video"?ja(n):!0,Il=n=>`${n==="image"?"an image":n==="video"?"a video":"a file"} the host stored, at a path on this host`,st=n=>(Array.isArray(n)?n:[n]).filter(wo),Da=Symbol.for("@graview/core:file"),Tl=(n,e)=>(Object.defineProperty(L(n),Da,{value:e,enumerable:!0}),n);function Fa(n){let e=L(n);return e?.[Da]??(e?.innerType?Fa(e.innerType):void 0)}var jl=()=>({href:F(),name:F(),type:F(),bytes:tn(),width:W(tn()),height:W(tn()),caption:W(F()),poster:W(F()),duration:W(tn()),captions:W(F()),at:W(F())});function Iv(n){return Tl(se(jl()).check(Ut(e=>wo(e)&&zl(e,n),Il(n))),n)}var qt=/^(?:https?:\/\/[^\s<>"'`\\]+|@?[A-Za-z0-9][\w.~-]*(?:\/[\w.~-]+)*)$/,Ht=n=>typeof n=="string"&&n.length<501&&qt.test(n);var La=n=>typeof n=="object"&&n!==null?n._zod?.def:void 0,Dl=/^@(?:https?:\/\/[^\s<>"'`\\#?]+|[A-Za-z0-9][\w.~-]*(?:\/[\w.~-]+)*)\/[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;function Ca(n){if(typeof n!="string"||!n.startsWith("@")||!Dl.test(n))return;let e=n.lastIndexOf("/"),t=n.slice(0,e),r=n.slice(e+1),o=/^@https?:\/\//.test(t)||!t.includes("/")?t.slice(1):t;return Ht(o)?{address:o,kind:r}:void 0}var Fl=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*:\S[^\n]{0,199}$/,Ll=n=>`${n.kind}:${n.id}`;function Za(n,e){if(typeof n!="string"||!Fl.test(n))return;let t=n.indexOf(":"),r=n.slice(0,t);return e.kinds.includes(r)?{address:e.address,kind:r,id:n.slice(t+1)}:void 0}function Cl(n,e){return(Array.isArray(n)?n:n==null?[]:[n]).flatMap(r=>{let o=Za(r,e);return o?[o]:[]})}var Ga=Symbol.for("@graview/core:linked"),Fv=(n,e)=>(Object.defineProperty(La(n),Ga,{value:e,enumerable:!0}),n);function at(n){let e=La(n);return e?e[Ga]??at(e.innerType):void 0}function Zl(n){let e=n?.fields?.shape??{},t=new Map;for(let[r,o]of Object.entries(e)){let i=at(o);i&&t.set(r,i)}return t}function Gl(n){if(n.to==="*"||n.to.length===0)return;let e=n.to.map(Ca);if(e.some(r=>!r))return;let t=e[0].address;if(!e.some(r=>r.address!==t))return{address:t,kinds:[...new Set(e.map(r=>r.kind))],cardinality:n.cardinality??"many",...n.description?{description:n.description}:{}}}var Vl=n=>n.to!=="*"&&n.to.some(e=>typeof e=="string"&&e.startsWith("@"));function Lv(n){return Object.fromEntries(Object.entries(n??{}).filter(([,e])=>!Vl(e)))}function Cv(n){let e=new Map;for(let[t,r]of Object.entries(n??{})){let o=Gl(r);o&&e.set(t,o)}return e}var ko=new WeakMap;function Kl(n,e){e?ko.set(n,e):ko.delete(n)}var Va=n=>ko.get(n);var Jt=["sun","mon","tue","wed","thu","fri","sat"],Bl=["day","week","month","year"],En=n=>`${n}Repeat`,ct=n=>n.endsWith("Repeat")&&n.length>6?n.slice(0,-6):void 0,Ua=/^\d{4}-\d{2}-\d{2}$/,Wa=Symbol.for("@graview/core:repeat");function Yt(n){let e=L(n);return!!e&&(e[Wa]===1||Yt(e.innerType))}var Ul=n=>(Object.defineProperty(L(n),Wa,{value:1,enumerable:!0}),n),xo=(n,e,t)=>n===void 0||Number.isInteger(n)&&n>=e&&n<=t,Ka=(n,e)=>n===void 0||Array.isArray(n)&&n.length<=e&&n.every(t=>typeof t=="string"&&Ua.test(t)),Wl=["every","interval","on","until","count","except","continues"],qa=n=>Mn(n)&&Object.keys(n).every(e=>Wl.includes(e))&&xo(n.interval,1,99)&&xo(n.count,1,1e3)&&Ka(n.until===void 0?void 0:[n.until],1)&&Ka(n.except,500)&&(n.continues===void 0||typeof n.continues=="string"&&n.continues.length<=200)&&(n.on===void 0||Array.isArray(n.on)&&n.on.length>0&&n.on.length<=31&&n.on.every(e=>n.every==="week"?Jt.includes(e):n.every==="month"&&e!==0&&xo(e,-1,31))),Vv=()=>Ul(ot().check(Ut(n=>n===null||qa(n),"how a date repeats, or null"))),dt=n=>Date.UTC(+n.slice(0,4),+n.slice(5,7)-1,+n.slice(8,10)),Ha=n=>new Date(n).toISOString().slice(0,10),So=(n,e)=>Ha(dt(n)+e*864e5),Ba=(n,e,t)=>{let r=new Date(Date.UTC(n,e+1,0)).getUTCDate();return Ha(Date.UTC(n,e,t<0||t>r?r:t))},Mn=n=>typeof n=="object"&&n!==null&&Bl.includes(n.every);function Pn(n,e,t={}){let r=n.slice(0,10),o=n.slice(10),i=[];if(!Ua.test(r))return i;let s=Math.max(1,e.interval??1),a=e.every,d=t.from&&t.from>r?t.from.slice(0,10):r,l=[e.until,t.to?.slice(0,10)].filter(Boolean).sort()[0],u=t.limit??1e3,p=new Set(e.except??[]),c=+r.slice(0,4),f=+r.slice(5,7)-1,g=+r.slice(8,10),h=So(r,-new Date(dt(r)).getUTCDay()),y=(e.on?.length?e.on:[a==="week"?Jt[new Date(dt(r)).getUTCDay()]:g]).map(O=>typeof O=="string"?Jt.indexOf(O):O),b=a==="day"?1:a==="week"?7:0,x=(+d.slice(0,4)-c)*12+(+d.slice(5,7)-1-f),$=e.count?0:Math.max(0,Math.floor((b?(dt(d)-dt(b===7?h:r))/864e5/b:a==="month"?x:x/12)/s)-1),w=0;for(let O=0;O<5e4&&i.length<u;O++,$++){let A=$*s,m=a==="day"?[So(r,A)]:a==="week"?y.map(v=>So(h,A*7+v)):a==="month"?y.map(v=>Ba(c,f+A,v)):[Ba(c+A,f,g)];for(let v of[...new Set(m)].sort())if(!(v<r)&&(l&&v>l||e.count&&w>=e.count||(w++,v>=d&&!p.has(v)&&i.push(v+o),i.length>=u)))return i}return i}function Ja(n,e,t){if(!Mn(e)||typeof n!="string")return n;let r=Pn(n,e,{from:t,limit:1})[0];if(r)return r;let o=e.until||e.count?Pn(n,e):[];return o[o.length-1]??n}function ql(n,e,t){let r=n[e],o=n[En(e)];return typeof r=="string"&&Mn(o)?Ja(r,o,t):r}var Xt=["human","visitor","agent","rule","system"],Hl=new Set(Xt);function Ro(n){return Hl.has(n?.kind)?n.kind:"system"}function ut(n,e){if(n.onBehalfOf){let{onBehalfOf:s,...a}=n;return`${ut(a,e)}, for ${ut(s,e)}`}let t=Ro(n);if(n.id===void 0)return n.name??(t==="agent"?"an agent":t==="visitor"?"a visitor":t);let r=e.graph.getNode(n.id);if(r)return K(e.schema.tryDefinition(r.kind),r);let o=e.seats?.find(s=>s.principal.id===n.id);if(o)return o.label;let i=e.people?.find(s=>s.id===n.id&&(s.kind===void 0||s.kind===n.kind));return i?i.name:n.name?n.name:/(^|:)migration$/.test(n.id)?"the upgrade":n.id.startsWith("form:")?"a visitor via a form":/[:_/]/.test(n.id)?{human:"somebody",visitor:"a visitor",agent:"an agent",rule:"a rule",system:"the system"}[t]:n.id}var ge="$archived",me=n=>n?.[ge]===!0,Hv=(n,e=!1)=>e==="all"||me(n)===e,$o=n=>n===!0||n==="true"?!0:n==="all"?"all":!1,lt="$leftAlone",Qt=new Set([ge,lt]);var Nn="0.1.65";var pe=class extends Error{constructor(t,r){super(r?`${t}
|
|
2
2
|
\u2192 ${r}`:t);this.hint=r;this.name="SchemaError"}};function Jl(n,e){let t=n,r=new Map;for(let a of t){if(r.has(a.kind))throw new pe(`Duplicate node kind "${a.kind}"`,"Each kind may be declared once; merge the two defineNode calls.");r.set(a.kind,a)}let o=new Map;for(let a of t)for(let[d,l]of Object.entries(a.edges)){if(l.to!=="*"){for(let p of l.to)if(!r.has(p))throw new pe(`Edge "${d}" on "${a.kind}" points at undeclared kind "${p}"`,`Declared kinds: ${[...r.keys()].join(", ")}`)}let u=o.get(d);u?u.from.push(a.kind):o.set(d,{from:[a.kind],decl:l})}let i=new Map;for(let[a,{from:d,decl:l}]of o){let u=d.map(p=>r.get(p).edges[a].to);i.set(a,{kind:a,from:d,to:u.includes("*")?"*":[...new Set(u.flat())],cardinality:l.cardinality??"many",...l.description===void 0?{}:{description:l.description}})}let s=new Map;for(let a of t)s.set(a.kind,Ma(a.fields,{id:F().check(tt(1)),kind:it(a.kind)}));return{definitions:t,computed:e,kinds:t.map(a=>a.kind),edgeKinds:[...i.keys()],definition(a){let d=r.get(a);if(!d)throw new pe(`Unknown node kind "${String(a)}"`,`Declared kinds: ${[...r.keys()].join(", ")}`);return d},tryDefinition(a){return r.get(a)},edge(a){return i.get(a)},edgeAllowed(a,d,l){let u=r.get(d)?.edges[a];return u?u.to==="*"||u.to.includes(l):!1},parseNode(a){let d=a?.kind;if(typeof d!="string")throw new pe("Node is missing a `kind`");let l=s.get(d);if(!l)throw new pe(`Unknown node kind "${d}"`,`Declared kinds: ${[...r.keys()].join(", ")}`);let u={},p={};for(let[f,g]of Object.entries(a))Qt.has(f)?g===!0&&(p[f]=!0):u[f]=g;let c=l.parse(u);return Object.keys(p).length>0?{...c,...p}:c},__node:void 0}}var fe={snapshot:2,op:3},rn=class extends Error{constructor(t,r,o,i,s){super(s!==void 0?`This ${t} holds a ${s} that @graview ${Nn} does not know: upgrade the framework to read it.`:`This ${t} is in a newer format (${r}${i?`, written by @graview ${i}`:""}) than @graview ${Nn} reads (${o}). `+(t==="snapshot"?"Refold it from the log, or upgrade the framework.":"Upgrade the framework to read it."));this.what=t;this.found=r;this.supported=o;this.writtenBy=i;this.unknown=s;this.name="NewerFormatError"}},Ao=["add-node","remove-node","patch-node","add-edge","remove-edge","splice-text"],Yl=new Set(Ao);function Oo(n){throw new rn("op",fe.op+1,fe.op,void 0,`primitive "${n?.op}"`)}var _o=new Set;function Po(n){for(let e in n){let t=n[e]?.$type;if(t!==void 0&&!_o.has(t))throw new rn("op",fe.op+1,fe.op,void 0,`value type "${t}" in "${e}"`)}}function Eo(n){for(let e of n.primitives)Yl.has(e?.op)||Oo(e)}function I(n){return`${n.kind}\0${n.from}\0${n.to}`}var ft={addedNodes:[],removedNodes:[],changedNodes:[],addedEdges:[],removedEdges:[],touched:[]};function Ya(n){return n.addedNodes.length===0&&n.removedNodes.length===0&&n.changedNodes.length===0&&n.addedEdges.length===0&&n.removedEdges.length===0}function Xl(n,e){let t=new Set([...Object.keys(n),...Object.keys(e)]),r=[];for(let o of t){let i=n[o],s=e[o];JSON.stringify(i)!==JSON.stringify(s)&&r.push(o)}return r.sort()}function Fe(n,e){let t=new Map(n.nodes.map(c=>[c.id,c])),r=new Map(e.nodes.map(c=>[c.id,c])),o=e.nodes.filter(c=>!t.has(c.id)),i=n.nodes.filter(c=>!r.has(c.id)),s=[];for(let c of n.nodes){let f=r.get(c.id);if(!f||f===c)continue;let g=Xl(c,f);g.length>0&&s.push({before:c,after:f,fields:g})}let a=new Map(n.edges.map(c=>[I(c),c])),d=new Map(e.edges.map(c=>[I(c),c])),l=e.edges.filter(c=>!a.has(I(c))),u=n.edges.filter(c=>!d.has(I(c))),p=new Set;for(let c of o)p.add(c.id);for(let c of i)p.add(c.id);for(let c of s)p.add(c.after.id);for(let c of[...l,...u])p.add(c.from),p.add(c.to);return{addedNodes:o,removedNodes:i,changedNodes:s,addedEdges:l,removedEdges:u,touched:[...p].sort()}}function Le(n,e,t){let r=new Set(t.flatMap(i=>i.op==="patch-node"||i.op==="splice-text"?[i.id]:"node"in i?[i.node.id]:[i.edge.from,i.edge.to]));if(r.size===0)return ft;let o=i=>({nodes:i.nodes.filter(s=>r.has(s.id)),edges:i.edges.filter(s=>r.has(s.from)||r.has(s.to))});return Fe(o(n),o(e))}var er={idLength:200,dataLength:4096,sameKindPerPair:1};function Xa({id:n,data:e}){if(n!==void 0&&!(typeof n=="string"&&n.length<=er.idLength&&/^[^\s\p{Cc}]+$/u.test(n)))return`A link's id is 1\u2013${er.idLength} characters with no space`;if(e!==void 0&&!(e&&typeof e=="object"&&!Array.isArray(e)&&JSON.stringify(e).length<=er.dataLength))return`A link's data is a JSON object of at most ${er.dataLength} characters`}function Ql(n){let e=n?.issues;return!Array.isArray(e)||e.length===0?n instanceof Error?n.message:String(n):e.map(t=>{let r=t.path?.length?B(String(t.path.at(-1))):null,o=t.message??"is not what the declaration allows";return r?`${r}: ${o}`:o}).join("; ")}var N=class extends Error{constructor(t,r){super(r?`${t}
|
|
3
|
-
${r}`:t);this.hint=r;this.name="GraphError"}},q=class extends N{constructor(t,r){super(r);this.id=t;this.name="MissingRecordError"}};function nr(n,e){try{n.parseNode(e);return}catch(t){if(t instanceof pe)throw t;let r=t.issues??[];return{fields:new Set(r.flatMap(i=>i.code==="unrecognized_keys"&&i.keys?[...i.keys]:typeof i.path?.[0]=="string"?[i.path[0]]:[""])),error:t}}}var Mo="n\0",No="e\0",H=class n{constructor(e,t={}){this.schema=e;this.validate=t.validate??!0}nodes=new Map;edges=new Map;linkIds=new Map;outIndex=new Map;inIndex=new Map;rank=0;ranks=new Map;lapsed=new Map;reordered=!1;counts=new Map;archived=new Set;listeners=new Set;validate;static from(e,t,r={}){let o=new n(e,r);return o.load(t),o}load(e){let t=this.snapshot();this.restore(e);let r=Fe(t,this.snapshot());return this.emit(r),r}getNode(e){return this.nodes.get(e)}has(e){return this.nodes.has(e)}allNodes(e){return this.reach([...this.nodes.values()],e,this.held)}count(e,t){return t||this.archived.size?this.nodesOfKind(e,t).length:this.counts.get(e)??0}allEdges(e){return this.reach([...this.edges.values()],e,t=>this.archived.has(t.from)||this.archived.has(t.to))}nodesOfKind(e,t){return this.allNodes(t).filter(r=>r.kind===e)}edgesOfKind(e,t){return this.allEdges(t).filter(r=>r.kind===e)}out(e,t,r){return this.reach(this.resolve(this.outIndex.get(e),t,"to"),r,this.held)}in(e,t,r){return this.reach(this.resolve(this.inIndex.get(e),t,"from"),r,this.held)}neighbors(e,t){let r=new Map;for(let o of[...this.out(e,void 0,t),...this.in(e,void 0,t)])r.set(o.id,o);return[...r.values()]}isArchived(e){return this.archived.has(e)}outEdges(e,t){return this.edgesFrom(this.outIndex.get(e),t)}inEdges(e,t){return this.edgesFrom(this.inIndex.get(e),t)}linkById(e){return this.edges.get(this.linkIds.get(e))}snapshot(){return{nodes:[...this.nodes.values()],edges:[...this.edges.values()]}}get size(){return{nodes:this.nodes.size,edges:this.edges.size}}applyPrimitives(e,t={}){let r=this.snapshot();try{for(let i of e)this.applyOne(i,t.restoring===!0,t.inPlace===!0);this.settleOrder()}catch(i){throw this.restore(r),i}let o=Le(r,this.snapshot(),e);return this.emit(o),o}preview(e,t={}){return n.from(this.schema,this.snapshot(),{validate:this.validate}).applyPrimitives(e,t)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}restore(e){let t=new Map([...this.lapsed,...this.ranks]);for(let o of[this.nodes,this.edges,this.linkIds,this.outIndex,this.inIndex,this.ranks,this.lapsed,this.counts,this.archived])o.clear();this.reordered=!1;for(let o of e.nodes)this.insertNode(o,!0);for(let o of e.edges)this.insertEdge(o,!0);let r=[...this.ranks.keys()];if(r.every((o,i)=>t.get(o)>(o[0]===r[i-1]?.[0]?t.get(r[i-1]):0))){for(let[o,i]of t)(this.ranks.has(o)?this.ranks:this.lapsed).set(o,i);for(;this.lapsed.size>4096;)this.lapsed.delete(this.lapsed.keys().next().value)}}tally(e,t){this.counts.set(e,(this.counts.get(e)??0)+t)}place(e,t){let r=t?this.lapsed.get(e):void 0;if(r===void 0){this.ranks.set(e,++this.rank);return}this.ranks.set(e,r),this.lapsed.delete(e),this.reordered=!0}lapse(e){let t=this.ranks.get(e);t!==void 0&&(this.ranks.delete(e),this.lapsed.set(e,t),this.lapsed.size>4096&&this.lapsed.delete(this.lapsed.keys().next().value))}settleOrder(){if(!this.reordered)return;this.reordered=!1;let e=o=>(i,s)=>this.ranks.get(o+i[0])-this.ranks.get(o+s[0]),t=[...this.nodes.entries()].sort(e(Mo));this.nodes.clear();for(let[o,i]of t)this.nodes.set(o,i);let r=[...this.edges.entries()].sort(e(No));this.edges.clear();for(let[o,i]of r)this.edges.set(o,i)}emit(e){if(!(e.addedNodes.length===0&&e.removedNodes.length===0&&e.changedNodes.length===0&&e.addedEdges.length===0&&e.removedEdges.length===0))for(let t of this.listeners)t(e)}applyOne(e,t,r){switch(e.op){case"add-node":Po(e.node),this.insertNode(e.node,t,r);return;case"remove-node":{let o=e.node.id,i=this.nodes.get(o);if(!i)throw new q(o,`Cannot remove missing node "${o}"`);for(let s of[...this.outEdges(o),...this.inEdges(o)])this.deleteEdge(s);this.tally(i.kind,-1),this.archived.delete(o),this.nodes.delete(o),this.lapse(Mo+o),this.outIndex.delete(o),this.inIndex.delete(o);return}case"patch-node":{let o=this.nodes.get(e.id);if(!o)throw new q(e.id,`Cannot patch missing node "${e.id}"`);Po(e.after);let i={...o};for(let[a,d]of Object.entries(e.after))qe(d)?delete i[a]:i[a]=d;let s=t?i:this.checkPatch(o,i,Object.keys(e.after));this.nodes.set(e.id,s),this.archived[me(s)?"add":"delete"](e.id),s.kind!==o.kind&&(this.tally(o.kind,-1),this.tally(s.kind,1));return}case"splice-text":{let o=this.nodes.get(e.id);if(!o)throw new q(e.id,`Cannot splice the text of missing node "${e.id}"`);let i=o[e.field],s;try{typeof i=="string"&&e.field!=="id"&&e.field!=="kind"&&(s=Tr(i,e))}catch{}if(s===void 0)throw new N(`Cannot splice ${e.id}.${e.field}: it does not hold ${JSON.stringify(e.removed)} at ${e.at}`,"A corrupt op: the text it was made against is not the text the log folds to.");let a={...o,[e.field]:s};this.nodes.set(e.id,t?a:this.checkPatch(o,a,[e.field]));return}case"add-edge":this.insertEdge(e.edge,t,r);return;case"remove-edge":{let o=e.edge.id===void 0?e.edge:this.linkById(e.edge.id);if(!o||!this.edges.has(I(o)))throw new q(e.edge.id??I(e.edge),`Cannot remove missing edge ${e.edge.id??I(e.edge)}`);this.deleteEdge(o);return}default:Oo(e)}}check(e){if(!this.validate)return e;try{return this.schema.parseNode(e)}catch(t){throw this.refusal(e,t)}}checkPatch(e,t,r){if(!this.validate)return t;let o=this.schema.tryDefinition(String(t.kind))?.fields?.shape;if(!o)return this.check(t);for(let a of r){if(a==="id"||a==="kind"||Qt.has(a))continue;let d=o[a];if(!d){delete t[a];continue}let l=d.safeParse(t[a]);l.success&&(l.data===void 0?delete t[a]:t[a]=l.data)}let i=nr(this.schema,t);if(i===void 0)return t;let s=nr(this.schema,e)?.fields??new Set;if([...i.fields].some(a=>r.includes(a)||!s.has(a)))throw this.refusal(t,i.error);return t}refusal(e,t){if(t instanceof pe)return t;{let r=e?.id??"?",o=e?.kind??"?",i=this.schema.tryDefinition(o),s=i&&e&&typeof e=="object"?V(i,e):r;return new N(`${s} does not match what ${o} declares`,Ql(t))}}insertNode(e,t,r=!1){if(this.nodes.has(e.id))throw new N(`Duplicate node id "${e.id}"`);this.nodes.set(e.id,t?e:this.check(e)),me(e)&&this.archived.add(e.id),this.tally(e.kind,1),this.place(Mo+e.id,r)}insertEdge(e,t,r=!1){let o=this.nodes.get(e.from),i=this.nodes.get(e.to);if(!o||!i){let a=o?e.to:e.from;throw new q(a,`Edge "${e.kind}" references missing node "${a}"`)}if(this.validate&&!t&&!this.schema.edgeAllowed(e.kind,o.kind,i.kind)){let a=this.schema.edge(e.kind);throw new N(`Edge "${e.kind}" is not declared from ${o.kind} to ${i.kind}`,a?`Declared: ${a.from.join("|")} -> ${a.to==="*"?"*":a.to.join("|")}`:`No edge kind "${e.kind}" is declared in this schema`)}let s=I(e);if(!t&&(e.id!==void 0||e.data!==void 0)){let a=this.edges.get(s),d=Xa(e)??(a&&e.id!==void 0&&a.id!==e.id?`A second "${e.kind}" link between two records is not allowed yet`:(this.linkIds.get(e.id)??s)!==s?`Link id "${e.id}" is already taken`:void 0);if(d)throw new N(d)}this.edges.has(s)||(this.edges.set(s,e),e.id!==void 0&&this.linkIds.set(e.id,s),this.place(No+s,r),this.index(this.outIndex,e.from,s),this.index(this.inIndex,e.to,s))}deleteEdge(e){let t=I(e),r=this.edges.get(t)?.id;r!==void 0&&this.linkIds.delete(r),this.edges.delete(t),this.lapse(No+t),this.outIndex.get(e.from)?.delete(t),this.inIndex.get(e.to)?.delete(t)}index(e,t,r){(e.get(t)??e.set(t,new Set).get(t)).add(r)}edgesFrom(e,t){if(!e)return[];let r=[];for(let o of e){let i=this.edges.get(o);i&&(t===void 0||i.kind===t)&&r.push(i)}return r}resolve(e,t,r){let o=[];for(let i of this.edgesFrom(e,t)){let s=this.nodes.get(i[r]);s&&o.push(s)}return o}held=e=>this.archived.has(e.id);reach(e,t,r){let o=t?.archived??!1;return o==="all"||!o&&!this.archived.size?e:e.filter(i=>r(i)===o)}};var tr=class extends Error{constructor(t,r){super(`No invariant registered under "${t}" (required by node "${r}")`);this.invariant=t;this.nodeId=r;this.name="UnregisteredInvariantError"}};function ef(n,e){return{...e,name:n}}var rr=class extends Error{constructor(e){super(e),this.name="RuleBudgetError"}};function Qa(n,e,t){try{return e().map(r=>r.status?r:{...r,status:"violated"})}catch(r){let o=r instanceof rr,i=r instanceof Error?r.message:String(r),s=n.label??n.name.replace(/-/g," ");return[{invariant:n.name,status:o?"over-budget":"could-not-judge",...t!==void 0?{subjectId:t}:{},label:s,message:`${s} could not be judged: ${i}`,nodeIds:t!==void 0?[t]:[],repairs:[]}]}}function zn(n,e,t={}){let r=t.context??{},o=t.today===void 0?{}:{today:t.today},i=t.onUnregistered??"skip",s=new Set(e.map(c=>c.name)),a=[];for(let c of e)c.scope==="graph"&&a.push(...Qa(c,()=>c.evaluate({graph:n,subject:void 0,context:r,...o}),void 0));let d=e.filter(c=>c.scope!=="graph"),l=new Map;for(let c of d){let f=c.scope.kind,g=l.get(f);g?g.push(c):l.set(f,[c])}for(let c of n.allNodes()){let f=n.schema.tryDefinition(c.kind),g=f?.requiresInvariant?.(c)??null;if(t.subjectFilter&&!t.subjectFilter(c,r))continue;if(g!==null&&!s.has(g)){if(i==="throw")throw new tr(g,c.id);continue}let h=!Kr(f,c,t.today);for(let y of l.get(c.kind)??[]){if(h&&y.judgesPast!==!0)continue;let b=y.scope.match;b&&!b(c)||a.push(...Qa(y,()=>y.evaluate({graph:n,subject:c,context:r,...o}),c.id))}}let u=new Set,p=a.filter(c=>{let f=`${c.message}|${[...c.nodeIds].sort().join(",")}`;return u.has(f)?!1:(u.add(f),!0)}).map(c=>{let f=Gr(c.message);return f===c.message?c:{...c,message:f}});return zo?zo(n,e,p,t.today):p}var zo;function bw(n){zo=n}function nf(n,e){let t=new Set(e);return n.filter(r=>r.nodeIds.some(o=>t.has(o))||r.subjectId!==void 0&&t.has(r.subjectId))}function tf(n){let e=new Set(n.map(r=>r.invariant)).size;if(e===0)return"All rules hold";let t=`${e} ${e===1?"rule":"rules"} broken`;return n.length>e?`${t} in ${n.length} places`:t}var pt=(n,e)=>n==="*"||n.includes(e);function z(n){let e=n.onBehalfOf;if(!e)return n;let t=e.roles??[],r=n.roles===void 0?t:n.roles.filter(o=>t.includes(o));return{...n,...e.id!==void 0?{id:e.id}:{},roles:r}}var Z=n=>n.kind==="system"&&n.onBehalfOf===void 0,ye=(n,e)=>n.roles==="*"||(e.roles??[]).some(t=>n.roles.includes(t));function ed(n){return Ji(n.map(e=>Rn(B(e).toLowerCase())),"or")}function be(n,e,t,r,o,i,s={},a,d,l){if(!n)return{ok:!0};if(Z(e))return{ok:!0};if(e=z(e),o!==void 0){if(be(n,e,t,r,void 0,i).ok)return{ok:!0};let f=!1;if(o.some(b=>be(n,e,b,r,void 0,i).ok)){if(!d||i===void 0||e.id!==void 0&&d()===e.id||!l&&n.grants.some(b=>b.roles!=="*"&&ye(b,e)&&o.some(x=>pt(b.mutations,x))))return{ok:!0};f=!0}let g=f?[t]:[t,...o],h=[...new Set(g.flatMap(b=>Io(n,b,r)))].sort(),y=(f?"only on what you made; ":"")+(h.length===0?o.length===0?"no declared act creates or changes it, so no role can":"no role can":`${ed(h)} can`);return{ok:!1,refusal:{mutation:t,...r===void 0?{}:{kind:r},wouldNeed:h,message:nd(n,g,r,y,s)}}}let u=!1;for(let f of n.grants){if(!ye(f,e)||!pt(f.mutations,t)||f.kinds!==void 0&&f.kinds!=="*"&&(r===void 0||!f.kinds.includes(r))||f.self&&(i===void 0||e.id===void 0||i!==e.id))continue;let g=f.ownEnd?a?.()??[]:[e.id];if(!g.length||g.some(h=>h!==e.id)){u=!0;continue}return{ok:!0}}let p=Io(n,t,r),c=u?"only on your own end of the link":p.length===0?"no role can":`${ed(p)} can`;return{ok:!1,refusal:{mutation:t,...r===void 0?{}:{kind:r},wouldNeed:p,message:nd(n,[t],r,c,s)}}}function nd(n,e,t,r,o){let i=[...new Set(e.flatMap(a=>td(n,a,t)))],s=o.act?.(e[0]);return`Not permitted: ${s?`\u201C${s}\u201D`:e[0]}${t?` on ${Rn(o.noun?.(t)??t)}`:""} \u2014 ${r}.`+(i.length>0?` ${i.join(" ")}`:"")}function td(n,e,t){return[...new Set(rd(n,e,t).flatMap(r=>r.describe||[]))]}var rd=(n,e,t)=>n.grants.filter(r=>pt(r.mutations,e)&&(t===void 0||pt(r.kinds??"*",t)));function Io(n,e,t){let r=rd(n,e,t);return r.some(o=>o.roles==="*")?[]:[...new Set(r.flatMap(o=>o.roles))].sort()}function To(n,e,t){return n?t.filter(r=>{let o=z(e).id;return jo(r).some(i=>be(n,e,r.name,i,void 0,o,void 0,()=>[o??[]].flat()).ok)}):t}var jo=n=>n.subject&&n.subject.kinds!=="*"?n.subject.kinds:[void 0];function Do(n,e,t,r){if(!n||Z(e))return!1;let o=z(e);return n.grants.some(i=>i.propose!==void 0&&ye(i,o)&&pt(i.propose,t)&&(i.kinds===void 0||i.kinds==="*"||r!==void 0&&i.kinds.includes(r)))}var or="type-text",ae={};var de=class extends Error{constructor(t,r="refused"){super(t);this.sentence=t;this.reason=r;this.name="ActRefusal"}};var ir="publish",Fo=n=>n?.mode==="on-publish",Lo=(n,e,t)=>Fo(n)&&!Z(e)&&(t==="published"||!(z(e).roles??[]).some(r=>n.working.includes(r))),J=globalThis[Symbol.for("@graview/core:publishing")]??={};J.input=()=>se({through:W(tn())});var ht=class{constructor(e,t,r){this.present=e;this.timeline=t;this.unversioned=r}nodes=new Map;edges=new Map;touching=new Map;seq=Number.MAX_SAFE_INTEGER;wrote=new Map;begin(e){this.seq=e,this.wrote.clear()}writerOf(e){return t=>{let r=`${e}\0${t}`;return this.wrote.has(r)?this.wrote.get(r):this.timeline?.writers?.writerAt(e,t,this.seq)}}note(e,t){let r=e.op==="add-node"?e.node.id:e.op==="patch-node"||e.op==="splice-text"?e.id:"";if(r===""||this.unversioned?.has(r))return;let o=e.op==="add-node"?Object.keys(e.node):e.op==="splice-text"?[e.field]:Object.keys(e.after);for(let i of o)i!=="id"&&i!=="kind"&&this.wrote.set(`${r}\0${i}`,t(r,i))}node(e){return this.nodes.has(e)?this.nodes.get(e)??void 0:this.present.getNode(e)}setNode(e,t){this.nodes.set(e,t)}setEdge(e,t){let r=I(e);this.edges.set(r,t?e:null);for(let o of[e.from,e.to]){let i=this.touching.get(o);i||this.touching.set(o,i=new Set),i.add(r)}}incident(e){let t=new Map;for(let r of[...this.present.outEdges(e),...this.present.inEdges(e)]){let o=I(r);this.edges.has(o)||t.set(o,r)}for(let r of this.touching.get(e)??[]){let o=this.edges.get(r);o&&t.set(r,o)}return[...t.values()]}undo(e){switch(e.op){case"add-node":this.setNode(e.node.id,null);return;case"remove-node":this.setNode(e.node.id,e.node);return;case"patch-node":{if(this.unversioned?.has(e.id))return;let t=this.node(e.id);if(!t)return;this.setNode(e.id,od(t,e.before));return}case"splice-text":{let t=this.unversioned?.has(e.id)?void 0:this.node(e.id);t&&this.setNode(e.id,jr(t,e,!0));return}case"add-edge":this.setEdge(e.edge,!1);return;case"remove-edge":this.setEdge(e.edge,!0);return}}apply(e){switch(e.op){case"add-node":this.setNode(e.node.id,e.node);return;case"remove-node":for(let t of this.incident(e.node.id))this.setEdge(t,!1);this.setNode(e.node.id,null);return;case"patch-node":{if(this.unversioned?.has(e.id))return;let t=this.node(e.id);if(!t)return;this.setNode(e.id,od(t,e.after));return}case"splice-text":{let t=this.unversioned?.has(e.id)?void 0:this.node(e.id);t&&this.setNode(e.id,jr(t,e));return}case"add-edge":this.setEdge(e.edge,!0);return;case"remove-edge":this.setEdge(e.edge,!1);return}}};function od(n,e){let t={...n};for(let[r,o]of Object.entries(e))qe(o)?delete t[r]:t[r]=o;return t}var rf=n=>n.op==="add-node"||n.op==="remove-node"?n.node.id:n.op==="patch-node"||n.op==="splice-text"?n.id:void 0;function Co(n,e,t,r){let o=u=>{let p=e.node(u);return p?t.served(p,e.writerOf(u))!==void 0:t.sees?.(u)??!1},i=rf(n);if(i===void 0){let u=n.edge,p=t.edgeClean(u)&&o(u.from)&&o(u.to);return e.apply(n),{primitives:p?[n]:[],faithful:!0}}let s=e.node(i),a=s?t.served(s,e.writerOf(i)):void 0;e.apply(n),e.note(n,r);let d=e.node(i),l=d?t.served(d,e.writerOf(i)):void 0;if(!a&&!l)return{primitives:[],faithful:!1};if(!a&&l){let u=e.incident(i).filter(c=>t.edgeClean(c)&&o(c.from===i?c.to:c.from)).map(c=>({op:"add-edge",edge:c})),p=n.op==="add-node"&&l===n.node&&u.length===0;return{primitives:p?[n]:[{op:"add-node",node:l},...u],faithful:p}}if(a&&!l){let u=n.op==="remove-node"&&a===s;return{primitives:u?[n]:[{op:"remove-node",node:a}],faithful:u}}if(n.op==="patch-node"){let u=(c,f)=>g=>g in c==(f!==void 0&&g in f);if(Object.keys(n.after).every(c=>u(a,s)(c)&&u(l,d)(c)))return{primitives:[n],faithful:!0};let p=c=>Object.fromEntries(Object.keys(n.after).map(f=>[f,f in c?c[f]:ce]));return{primitives:[{op:"patch-node",id:i,before:p(a),after:p(l)}],faithful:!1}}if(n.op==="splice-text"){let u=n.field;if(a[u]===s[u]&&l[u]===d[u])return{primitives:[n],faithful:!0};let p=c=>({[u]:u in c?c[u]:ce});return{primitives:[{op:"patch-node",id:i,before:p(a),after:p(l)}],faithful:!1}}return{primitives:[{op:"remove-node",node:a},{op:"add-node",node:l}],faithful:!1}}function id(n,e,t){if(n.length===0)return[];let r=e.log.all(),o=r[0]?.seq??0,i=n.every(c=>r[c.seq-o]?.id===c.id),s=new ht(e.present,e);if(!i)return s.begin(e.log.length??o+r.length),n.map(c=>{let f=z(c.author).id,g=c.primitives.map(h=>Co(h,s,t,()=>f));return{op:c,primitives:g.flatMap(h=>h.primitives),faithful:g.every(h=>h.faithful)}});let a=new Set(n.map(c=>c.seq)),d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let c of a)c<d&&(d=c),c>l&&(l=c);d-=o,l-=o;let u=of(r,d,e.present,t),p=u?new ht(e.present,e,u.unversioned):s;for(let c=r.length-1;c>=d;c--){let f=r[c].primitives;for(let g=f.length-1;g>=0;g--)p.undo(f[g])}return sf(n,r,d,l,a,p,u?.judge??t,e)}function of(n,e,t,r){let{sees:o,names:i}=r;if(!o||!i)return;let s=new Set,a=new Set,d=new Set,l=(p,c)=>{s.has(p)||a.has(p)||(o(p)?i(c)?(a.add(p),d.delete(p)):d.add(p):(s.add(p),d.delete(p)))};for(let p=e;p<n.length;p++)for(let c of n[p].primitives)c.op==="add-node"||c.op==="remove-node"?l(c.node.id,c.node):c.op==="patch-node"?(l(c.id,c.before),l(c.id,c.after)):c.op==="splice-text"&&(l(c.id,{}),s.has(c.id)||(a.add(c.id),d.delete(c.id)));for(let p of d){let c=t.getNode(p);c&&i(c)&&(d.delete(p),a.add(p))}return{unversioned:new Set([...d,...s]),judge:{...r,served:(p,c)=>d.has(p.id)?p:s.has(p.id)?void 0:r.served(p,c)}}}function sf(n,e,t,r,o,i,s,a){let d=new Map;for(let l=t;l<=r;l++){let u=e[l];if(i.begin(u.seq),!o.has(u.seq)){for(let f of u.primitives)i.apply(f);continue}let p=(f,g)=>a.writers?.writerAt(f,g,u.seq+1),c=u.primitives.map(f=>Co(f,i,s,p));d.set(u.seq,{op:u,primitives:c.flatMap(f=>f.primitives),faithful:c.every(f=>f.faithful)})}return n.map(l=>d.get(l.seq))}function Mw(n,e,t,r){let o=new ht(e.present,e);return o.begin(e.log.length??e.log.all().length),n.flatMap(i=>Co(i,o,t,()=>r).primitives)}var ad="A change you cannot see",dd={kind:"system",id:"withheld",name:"Someone"};function In(n){return n.withheld===!0}var gt=Re,cd=(n,e)=>Object.entries(n).some(([t,r])=>t!=="id"&&t!=="kind"&&C(r,e));function ud(n){if(typeof n!="function")return n;let e=n,t=r=>e(r.id)&&!cd(r,e)?r:void 0;return{sees:e,shows:e,served:t,servedWith:t,optional:()=>!1,kindOf:()=>{}}}function C(n,e){if(typeof n=="string")return!e(n);if(n===null||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0;t<n.length;t++)if(C(n[t],e))return!0;return!1}for(let t in n)if(Object.hasOwn(n,t)&&(!e(t)||C(n[t],e)))return!0;return!1}function ld(n,e){let t=r=>!e(r);return n.primitives.some(r=>gt(r).some(t))||[...n.writes,...n.reads].some(t)||n.mutation!==null&&C(n.mutation.args,e)}function af(n,e){if(gt(n).every(e.shows))switch(n.op){case"add-node":{let t=e.served(n.node);return t?t===n.node?n:{op:"add-node",node:t}:void 0}case"remove-node":{let t=n.node;return cd(t,e.sees)?{op:"remove-node",node:Object.fromEntries(Object.entries(t).filter(([r,o])=>r==="id"||r==="kind"||!C(o,e.sees)))}:n}case"patch-node":{let t=e.kindOf(n.id),r={};for(let[i,s]of Object.entries(n.after))if(!C(s,e.sees))r[i]=s;else if(t!==void 0&&e.optional(t,i))r[i]=ce;else return;let o=Object.fromEntries(Object.entries(n.before).filter(([,i])=>!C(i,e.sees)));return{op:"patch-node",id:n.id,before:o,after:r}}case"add-edge":case"remove-edge":return C(n.edge,e.sees)?void 0:n;case"splice-text":return C(n.removed,e.sees)||C(n.inserted,e.sees)?void 0:n}}function Zo(n,e,t){let r=ud(e),o=i=>r.shows(i)&&fd(r,i);return{id:n.id,seq:n.seq,batch:n.batch,author:dd,intent:ad,mutation:null,primitives:t??n.primitives.flatMap(i=>{let s=af(i,r);return s?[s]:[]}),reads:n.reads.filter(o),writes:n.writes.filter(o),at:n.at,...n.undoes!==void 0?{undoes:n.undoes}:{},withheld:!0}}function Tn(n,e){let t=ud(e);if(t.hides?.()===!1)return[...n];let r=t.pin?.()??t;if(r.redact)return r.redact(n);if(r.timeline){let o={served:(i,s)=>r.servedWith(i,s),edgeClean:i=>!C(i,r.sees),sees:r.sees,names:i=>C(i,r.sees)};return id(n,r.timeline,o).map(({op:i,primitives:s,faithful:a})=>(!i.withheld&&a?sd(i,r,s):void 0)??Zo(i,r,s))}return n.map(o=>(!o.withheld&&!ld(o,r.shows)?sd(o,r):void 0)??Zo(o,r))}function sd(n,e,t){let r=n.inverse??n.primitives;if(t&&t.length<n.primitives.length){if(!t.length)return;r=r.filter(h=>gt(h).every(e.shows));let{inverse:f,...g}=n;n={...g,primitives:t}}let o=f=>e.sees(f)&&fd(e,f),i=n.reads.filter(o),s=new Set(n.primitives.flatMap(gt)),a=n.writes.filter(f=>o(f)||e.sees(f)&&s.has(f)),d=i.length===n.reads.length&&a.length===n.writes.length?n:{...n,reads:i,writes:a},l=e.actor!==void 0&&z(n.author).id===e.actor;if(!l&&n.described?.some(f=>!e.sees(f)))return;if(!C(n,e.sees))return d;let u=new Set,p=f=>{if(typeof f=="string")u.add(f);else if(Array.isArray(f))for(let g of f)p(g);else if(f!==null&&typeof f=="object")for(let[g,h]of Object.entries(f))u.add(g),p(h)};t&&p(t);let c=f=>e.sees(f)||u.has(f);if(!C(r,c))return l&&n.mutation&&p(n.mutation.args),C({...d,primitives:[],inverse:[]},l?c:e.sees)?void 0:d}function fd(n,e){return n.timeline===void 0||n.kindOf(e)!==void 0}var on=class extends N{constructor(t){super(t.message);this.check=t;this.name="UndoBlockedError"}get blockedBy(){return this.check.blockedBy}};function mt(n,e){let t=new Set(e),r=n.undoneIds(),o=n.all().filter(h=>t.has(h.batch)&&!r.has(h.id)),i=[...n.epochs()].reverse().find(h=>h.horizon);if(i){let h=new Set(n.all().map(b=>b.batch)),y=e.filter(b=>!h.has(b));if(y.length>0)return{ok:!1,ops:o,blockedBy:[],includeBatches:[],reason:"missing",message:`Cannot undo ${y.map(b=>`batch ${b}`).join(", ")}: it is not after the undo horizon at op ${i.seq}${i.at?` (${i.at})`:""}. What was done before the horizon is archived, and undo does not reach behind it.`}}if(o.length===0)return{ok:!1,ops:o,blockedBy:[],includeBatches:[],reason:"missing",message:e.length===0?"No batch given to undo":`Nothing live to undo in ${e.join(", ")} \u2014 already undone, or never applied`};if(o.some(In))return{ok:!1,ops:o,blockedBy:[],includeBatches:[],reason:"forbidden",message:o.every(In)?"Cannot undo a change you cannot see: only somebody who can see it can take it back.":"Cannot undo this here: part of it is a change you cannot see, and only somebody who can see it can take it back."};if(o.some(h=>h.enabledModules!==void 0))return{ok:!1,ops:o,blockedBy:[],includeBatches:[],message:"Cannot undo turning a module off or on: it is changed by turning the module the other way."};if(o.some(h=>h.sentOut!==void 0))return{ok:!1,ops:o,blockedBy:[],includeBatches:[],message:o.every(h=>h.sentOut===void 0||h.sentOut.refused)?"Nothing to take back: nothing went out.":"Nothing to take back: an invitation already went out. Change the guests here, and the next pass sends that."};let s=i&&o.some(h=>h.publishedThrough!==void 0)?J.undo?.(n,o,i):void 0;if(s)return{ok:!1,ops:o,blockedBy:[],includeBatches:[],message:s};let a=new Set;for(let h of o)for(let y of h.writes)a.add(y);let d=Math.min(...o.map(h=>h.seq)),l=n.epochs().find(h=>h.change!==void 0&&h.seq>d);if(l){let h=o.find(y=>y.seq<l.seq);return{ok:!1,ops:o,blockedBy:[],includeBatches:[],message:`Cannot undo "${h.intent}": ${h.intent===l.change?"it changed the declaration":`it was done before the declaration changed (${l.change})`}, and undo does not reach back across that change.`}}let u=new Map(n.all().map(h=>[h.id,h.seq])),p=o.flatMap(h=>h.primitives),c=[];for(let h of n.all()){if(h.seq<=d||t.has(h.batch)||r.has(h.id)||h.undoes!==void 0&&(u.get(h.undoes)??-1)>d)continue;let y=ae.aside?.(p,h);if(y===!0)continue;let b=[...new Set([...h.reads.filter(x=>a.has(x)),...y??[]])];b.length>0&&c.push({op:h,overlap:b})}if(c.length===0)return{ok:!0,ops:o};let f=c.filter(h=>!In(h.op)).map(h=>`"${h.op.intent}" (op ${h.op.id}, read ${h.overlap.join(", ")})`).join("; ");if(c.some(h=>In(h.op)))return{ok:!1,ops:o,blockedBy:c,includeBatches:[],message:`Cannot undo on its own \u2014 ${f?`a later operation depends on it: ${f}; and `:""}a later change you cannot see depends on it, which only somebody who can see it can take back.`};let g=[...new Set(c.map(h=>h.op.batch))];return{ok:!1,ops:o,blockedBy:c,includeBatches:g,message:`Cannot undo on its own \u2014 a later operation depends on it: ${f}. Include ${g.map(h=>`batch ${h}`).join(", ")} to undo them together.`}}function pd(n,e){return e?Go(e,n).flatMap(t=>[...t.primitives]):[...n].sort((t,r)=>r.seq-t.seq).flatMap(t=>Je(t))}function Go(n,e){return ae.undone?ae.undone(n,e):[...e].sort((t,r)=>r.seq-t.seq).map(t=>({op:t,primitives:Je(t)}))}var sn=class extends Error{refusal;constructor(e){super(e.message),this.name="PermissionDeniedError",this.refusal=e}};function df(n){let e=n instanceof Error?n.message:String(n);if(n instanceof sn){let t=n.refusal.wouldNeed;return{reason:"forbidden",sentence:e,...t.length>0?{wouldNeed:[...t]}:{}}}return n instanceof q?{reason:"missing",sentence:e}:n instanceof de?{reason:n.reason,sentence:n.sentence}:n instanceof on?{reason:n.check.reason??"invalid",sentence:e}:{reason:"invalid",sentence:e}}var ve=class extends N{constructor(t,r){super(`Invalid arguments for mutation "${t}"`,r.map(o=>`${o.path.map(String).join(".")||"(root)"}: ${o.message}`).join("; "));this.mutation=t;this.issues=r;this.name="InvalidArguments"}};var cf=["edit","remove","archive","unarchive","merge","leave-alone","allow-tidying"];var Yw=n=>cf.map(e=>`${e}-${n}`);function gd(n){let e=/^(edit|remove|archive|unarchive|merge|leave-alone|allow-tidying|skip|detach|split)-(.+)$/.exec(n);return e?{act:e[1],kind:e[2]}:void 0}var Ko=["connect","disconnect"],md=n=>n.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),Vo=(n,e,t)=>`${n}-${e}-${md(t)}`;function Xw(n,e){let t=/^(connect|disconnect)-(.+)$/.exec(n);if(t){for(let[r,o]of e)if(t[2].startsWith(`${r}-`)){for(let i of o)if(t[2]===`${r}-${md(i)}`)return{act:t[1],kind:r,relation:i}}}}var Qw=n=>[...n].flatMap(([e,t])=>[...t].flatMap(r=>Ko.map(o=>Vo(o,e,r)))),hd=n=>`${/^[aeiou]/i.test(n)?"an":"a"} ${n}`;function yd(n,e){let t=e.also?` (${e.also})`:"";return{title:`${e.one?`${n==="connect"?"Set":"Clear"} the ${e.to}`:`${n==="connect"?"Link":"Unlink"} ${hd(e.to)}`}${t}`,fromTheOtherEnd:`${n==="connect"?"Link":"Unlink"} ${hd(e.from)}${t}`}}function bd(n,e,t,r){if(t.cardinality!=="one"||t.to==="*"||t.to.length!==1||t.to[0]!==n)return;let o=t.description?.trim().replace(/\.$/,"");return o&&/^the\s+\S/i.test(o)&&!/[.;:!?,()]/.test(o)&&o.split(/\s+/).length<=8?{to:o.replace(/^the\s+/i,"")}:{also:r(e)}}var yt="vote-suggestion",vd="Sign in to vote on this suggestion.";function bt(n){return n?n.shared===!0||n.kind==="visitor"?!0:bt(n.onBehalfOf):!1}function sr(n){if(!n)return;if(n.shared!==!0&&n.kind!=="visitor")return sr(n.onBehalfOf);let e=n.visitorKey??(n.shared===!0?void 0:n.id);return e||void 0}function wd(){return{name:yt,title:"Vote on a suggestion",input:se({suggestion:F(),vote:Na([it("for"),it("against"),Pa()])}),apply(){}}}var ar=globalThis[Symbol.for("@graview/core:voting")]??={};var an=n=>n.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").replace(/-+/g,"-").toLowerCase();function dr(n,e){let t=an(n),r=[...e];if(r.includes(n))return n;let o=r.filter(i=>an(i)===t);return o.length===1?o[0]:void 0}function uf(n,e){let t=Array.from({length:e.length+1},(r,o)=>o);for(let r=1;r<=n.length;r+=1){let o=[r];for(let i=1;i<=e.length;i+=1)o[i]=Math.min(t[i]+1,o[i-1]+1,t[i-1]+(n[r-1]===e[i-1]?0:1));t=o}return t[e.length]}function Bo(n,e){let t=[...e],r=dr(n,t);if(r)return r;let o=an(n);if(o==="")return;let i,s=!1;for(let a of t){let d=uf(o,an(a));d>Math.max(2,Math.floor(Math.max(o.length,a.length)/3))||(!i||d<i.far?(i={act:a,far:d},s=!1):d===i.far&&(s=!0))}return i&&!s?i.act:void 0}var lf=n=>`Op "${n.id}" has seq ${n.seq}, so the log begins at seq ${n.seq}: a log that begins past 0 begins at its undo horizon, and none was given (a checkpoint epoch, or { horizon })`,jn=class n{ops=[];marks=[];start=0;get length(){return this.start+this.ops.length}get horizon(){return this.start}all(){return this.ops}opsFrom(e){return this.ops.slice(Math.max(0,e-this.start))}append(e){if(e.seq!==this.length)throw new Error(this.length===0&&e.seq>0?lf(e):`Op "${e.id}" has seq ${e.seq} but the log is ${this.length} long`);Eo(e),this.ops.push(qn(e))}static from(e,t=[],r={}){let o=new n,i=[...t].reverse().find(d=>d.horizon),s=r.horizon??i?.seq??0;if(!Number.isInteger(s)||s<0)throw new Error(`A log cannot begin at seq ${s}`);if(i&&r.horizon!==void 0&&i.seq!==r.horizon)throw new Error(`A log said to begin at seq ${r.horizon} has its checkpoint at seq ${i.seq}`);let a=e[0];if(a&&s>0&&a.seq!==s)throw new Error(`A log compacted at seq ${s} begins with op "${a.id}" at seq ${a.seq}`);o.start=s;for(let d of e)o.append(d);for(let d of t)o.markEpoch(d);return o}replace(e,t=[],r={}){let o=n.from(e,t,r);this.ops=o.ops,this.marks=o.marks,this.start=o.start}epochs(){return this.marks}horizonEpoch(){for(let e=this.marks.length-1;e>=0;e--)if(this.marks[e].horizon)return this.marks[e]}lastEpoch(){return this.marks.at(-1)}markEpoch(e){if(!Number.isInteger(e.seq)||e.seq<0||e.seq>this.length)throw new Error(`An epoch at seq ${e.seq} starts past the end of a log ${this.length} long`);if(e.seq<this.start)throw new Error(`An epoch at seq ${e.seq} is behind the horizon at seq ${this.start}: it went to the archive with the ops before it`);let t=this.lastEpoch();if(t&&e.seq<t.seq)throw new Error(`An epoch at seq ${e.seq} comes before the last one, at seq ${t.seq}`);this.marks.push(e)}truncate(e){if(!Number.isInteger(e)||e<this.start||e>this.length)throw new Error(`Cannot cut a log ${this.length} long back to ${e}`);let t=this.lastEpoch();if(t&&t.seq>e)throw new Error(`Cannot cut the log back to ${e}: an epoch begins at seq ${t.seq}`);return this.ops.splice(e-this.start)}checkpointAt(e,t,r={}){if(!Number.isInteger(t)||t<this.start||t>this.length)throw new Error(`No checkpoint at seq ${t}: this log holds seqs ${this.start} to ${this.length}`);let o=[...this.marks].reverse().find(a=>a.seq<=t);if(o?.seq===t)return{...o,horizon:!0};let i=this.fold(e,{...r,...o?{from:o}:{},to:t}).snapshot(),s=this.ops[t-1-this.start]?.at??o?.at;return{seq:t,base:i,...o?.version!==void 0?{version:o.version}:{},...s!==void 0?{at:s}:{},horizon:!0}}compact(e){if(!Number.isInteger(e.seq)||e.seq<this.start||e.seq>this.length)throw new Error(`Cannot compact at seq ${e.seq}: this log holds seqs ${this.start} to ${this.length}`);let t=this.ops.slice(0,e.seq-this.start),r=this.marks.filter(o=>o.seq<e.seq);return this.ops=this.ops.slice(e.seq-this.start),this.marks=[{...e,horizon:!0},...this.marks.filter(o=>o.seq>e.seq)],this.start=e.seq,{ops:t,epochs:r}}get(e){return this.ops.find(t=>t.id===e)}live(){let e=this.undoneIds();return this.ops.filter(t=>!e.has(t.id))}undoneIds(){return dn(this.ops)}opsInBatch(e){return this.ops.filter(t=>t.batch===e)}batches(){return Uo(this.ops,this.undoneIds())}fold(e,t={}){let r=t.from?.seq??0;if(r<this.start)throw new Error(t.from?`An epoch at seq ${r} is behind the horizon at seq ${this.start}: fold from the checkpoint`:`A log compacted at seq ${this.start} does not fold from empty: fold from its checkpoint`);let o=t.from?.base??{nodes:[],edges:[]},i=H.from(e,o,t.validate!==void 0?{validate:t.validate}:{}),s=t.to??this.length;for(let a of this.ops.slice(r-this.start,Math.max(0,s-this.start)))ff(i,a);return i}toJSON(){return[...this.ops]}};function ff(n,e){if(e.undoes!==void 0){n.applyPrimitives(e.primitives,{restoring:!0});return}try{n.applyPrimitives(e.primitives)}catch{n.applyPrimitives(e.primitives,{restoring:!0})}}function dn(n){let e=new Map;for(let r of n){if(!r.undoes)continue;let o=e.get(r.undoes);o?o.push(r.id):e.set(r.undoes,[r.id])}let t=new Map;for(let r=n.length-1;r>=0;r--){let o=n[r],i=e.get(o.id)??[];t.set(o.id,!i.some(s=>t.get(s)===!0))}return new Set(n.filter(r=>t.get(r.id)===!1).map(r=>r.id))}function pf(n){let e=[...new Set(n.map(t=>t.intent))];return e.length<=3?e.join("; "):`${e.slice(0,2).join("; ")}; and ${e.length-2} more`}function Uo(n,e){let t=[],r=new Map;for(let o of n){let i=r.get(o.batch);i?i.push(o):(r.set(o.batch,[o]),t.push(o.batch))}return t.map(o=>{let i=r.get(o)??[],s=i[0];return{id:o,author:s.author,intent:s.batchIntent??pf(i),at:s.at,...s.lineage?{lineage:s.lineage}:{},ops:i,undone:i.every(a=>e.has(a.id))}})}function cr(n){return n?.automated===!0&&n.kind!=="human"&&n.kind!=="rule"}var xd=n=>n?.[lt]===!0,hf=(n,e)=>xd(("graph"in n?n.graph:n).getNode(e));function kd(n,e,t){let r=n.tryDefinition(e);return t===void 0?r?.tidying:r?.edges?.[t]?.tidying}var gf=n=>JSON.stringify(n,(e,t)=>t&&typeof t=="object"&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort()):t);var mf=/^(archive|unarchive|remove|leave-alone|allow-tidying)$/;function yf(n,e){let t=an(n.name),r=e?.act(n.name),o=n.args??{},i=r?r.derived:gd(t),{id:s}=o;if(i&&typeof s=="string"){if(mf.test(i.act))return[i.act,s];if(i.act==="merge")return["merge",...[s,o.into].sort()];if(i.relation)return[i.act,i.relation,s,o.to]}let a=r?.subject?.arg??"id",[d,l]=Object.keys(o).filter(u=>u!==a);return r?.connects?.length===1&&d&&!l&&e.has(o[a])&&e.has(o[d])?["connect",r.connects[0],o[a],o[d]]:[t,r?.creates?.length&&typeof s=="string"&&!e.has(s)?{...o,id:0}:o]}var Sd=(n,e)=>`\u2248${gf(n.map(t=>yf(t,e)))}`;function Rd(n,e,t){let r=bf(n,t);return[e,...e.map(o=>[o])].map(o=>r.get(Sd(o,t))).find(Boolean)}function bf(n,e){let t=dn(n),r=new Map(n.map(s=>[s.id,s])),o=new Map,i=new Map;for(let s of n)s.lineage?.suggestion!==void 0&&s.lineage.items&&i.set(s.lineage.suggestion,[...i.get(s.lineage.suggestion)??[],...s.lineage.items]);for(let s of n){let a=s.undoes!==void 0&&!t.has(s.id)&&!s.withheld?r.get(s.undoes):void 0;if(a?.suggests&&a.author.kind===s.author.kind&&a.author.id===s.author.id)continue;let d=a?.suggests?a.suggests.filter((l,u)=>!i.get(a.id)?.includes(u)):a?.mutation&&(a.lineage||s.undoneLineage)?[a.mutation]:[];if(d.length>0)for(let l of[d,...d.map(u=>[u])])o.set(Sd(l,e),s)}return o}function $d(n,e,t,r,o={}){let i=o.declaration!==!1,s=(a,d)=>`${r} may not ${a}: ${d}.`;for(let a of t){let d="edge"in a?a.edge:void 0,l=(d?[d.from,d.to]:["id"in a?a.id:a.node.id]).map(u=>e.getNode(u)??("node"in a?a.node:void 0));for(let u of l){if(!u)continue;if(xd(u))return s(`change \u201C${V(n.tryDefinition(u.kind),u)}\u201D`,"a person said to leave it alone");if(!i)continue;let p=kd(n,u.kind);if(p==="never")return s(`change ${ue(n,u.kind)} on its own`,"the app says they are never tidied");if(d&&p==="no-links")return s(`link or unlink ${ue(n,u.kind)} on its own`,"the app says they are never linked automatically")}if(d&&i&&l[0]&&kd(n,l[0].kind,d.kind)==="never")return s(`${a.op==="add-edge"?"make":"break"} a \u201C${d.kind}\u201D link on its own`,"the app says that relation is never tidied")}}function vf(n,e){if(!e||n.length===0)return null;let t=e.roles,r=o=>t?o.wouldNeed.some(i=>t.includes(i)):o.wouldNeed.length>0;return n.every(({refusal:o})=>r(o))?e:null}var ur={scene:0,overview:10,rail:20,popover:30,dialog:40,toast:50},wf={plots:0,stage:1,tag:2,ties:2,lines:3,tieLabels:4,occupants:6,seatMarks:7,zoom:8,card:10,opened:11},kf={under:0,raised:1,over:2},Wo=n=>`--graview-layer-${n}`,xf=n=>`var(${Wo(n)}, ${ur[n]})`;function Sf(){return Object.keys(ur).map(n=>` ${Wo(n)}: ${ur[n]};`).join(`
|
|
4
|
-
`)}function Rf(n){let e=n.onBehalfOf??n;return{kind:e.kind,...e.id!==void 0?{id:e.id}:{},...e.name!==void 0?{name:e.name}:{},...e.roles!==void 0?{roles:e.roles}:{}}}function Ad(){return`sub_${(globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`).replace(/-/g,"").slice(0,20)}`}function Od(n){return{...n,id:n.id??Ad(),at:n.at??new Date().toISOString()}}function $f(n=[]){let e=[...n],t=new Set,r=()=>{for(let o of t)o()};return{list:o=>o===void 0?e:e.filter(i=>i.who.id===o),add(o){let i=Od(o);return e=[...e.filter(s=>s.id!==i.id),i],r(),i},remove(o){let i=e.length;e=e.filter(a=>a.id!==o);let s=e.length<i;return s&&r(),s},onChange(o){return t.add(o),()=>t.delete(o)}}}var qo=(n,e)=>`${n}\0${e}`,_d=new WeakMap;function Af(n,e){let t=new Map;for(let[o,i]of Object.entries(e??{}))for(let[s,a]of Object.entries(i))t.set(qo(o,s),[{seq:n-1,by:a}]);return{base:n,end:n,read:[],fields:t,written:[],seqOf:new Map,writers:{writerAt:(o,i,s)=>{let a=t.get(qo(o,i));if(!a)return;let d=0,l=a.length;for(;d<l;){let u=d+l>>1;a[u].seq<s?d=u+1:l=u}return d===0?void 0:a[d-1].by}}}}function Of(n){if(n.op==="add-node")return[n.node.id,Object.keys(n.node).filter(e=>e!=="id"&&e!=="kind")];if(n.op==="patch-node")return[n.id,Object.keys(n.after).filter(e=>!qe(n.after[e]))];if(n.op==="splice-text")return[n.id,[n.field]]}function _f(n,e){let t=n.end,r=z(e.author).id,o=e.undoes!==void 0?n.seqOf.get(e.undoes):void 0,i=[];for(let s of e.primitives){let a=Of(s);if(!a)continue;let[d,l]=a;for(let u of l){let p=e.undoes===void 0?r:o!==void 0?n.writers.writerAt(d,u,o):void 0,c=qo(d,u),f=n.fields.get(c);f||n.fields.set(c,f=[]),f.push({seq:t,by:p}),i.push(c)}}n.written.push({seq:t,keys:i}),n.seqOf.set(e.id,t),n.read.push(e),n.end++}function Pf(n,e){for(;n.written.length>0&&n.written.at(-1).seq>=e;){let{keys:t}=n.written.pop();for(let r of t)n.fields.get(r)?.pop()}for(let t of n.read.slice(e-n.base))n.seqOf.delete(t.id);n.read.length=e-n.base,n.end=e}function vt(n){let e=n.all(),t=typeof n.length=="number"?n.length:e.length,r=t-e.length,o=_d.get(n);if(o&&o.base<=r&&r<=o.end){let i=Math.min(o.end,t);for(;i>r&&e[i-1-r]!==o.read[i-1-o.base];)i--;i===r&&r>o.base&&i<o.end?o=void 0:(i<o.end&&Pf(o,i),r>o.base&&(o.read=o.read.slice(r-o.base),o.base=r))}else o=void 0;o||_d.set(n,o=Af(r,r>0?[...n.epochs?.()??[]].reverse().find(i=>i.horizon)?.writers:void 0));for(let i=o.end;i<t;i++)_f(o,e[i-r]);return o.writers}function Pd(n,e,t,r){let o=vt(n),i={};for(let s of t)for(let a in s){if(!Object.hasOwn(s,a)||a==="id"||a==="kind"||!r(s[a]))continue;let d=o.writerAt(s.id,a,e);d!==void 0&&((i[s.id]??={})[a]=d)}return i}var cn={served:new WeakSet},wt=n=>n.fields!==void 0||(n.hide?.length??0)>0,Ed=(n,e,t)=>(n??[]).some(r=>r.kinds.includes(e)&&(r.hide?.includes(t)===!0||r.fields!==void 0&&!r.fields.includes(t))),Md=(n,e,t,r)=>Object.entries(t).some(([o,i])=>typeof i=="string"&&i.trim()!==""&&n.includes(i.trim())&&r(e,o)),Ce=n=>cn.on===!0||cn.served.has(n);var Ho=new WeakMap;function Ef(n,e){let t=new Map(Object.entries(e?.removed??{})),r=new Map(Object.entries(e?.creators??{})),o=n===0||e?.removed!==void 0;return{base:n,end:n,read:[],kinds:t,creators:r,entries:[],records:{kindOf:i=>t.get(i),creatorOf:i=>r.get(i),knowsAll:o}}}function Mf(n,e){let t=n.end;for(let r of e.primitives){if(r.op!=="add-node"&&r.op!=="remove-node")continue;let{id:o,kind:i}=r.node;if(n.kinds.has(o)||(n.kinds.set(o,i),n.entries.push({seq:t,id:o,creator:!1})),r.op!=="add-node"||n.creators.has(o)||e.undoes!==void 0)continue;let s=z(e.author).id;s!==void 0&&(n.creators.set(o,s),n.entries.push({seq:t,id:o,creator:!0}))}n.read.push(e),n.end++}function Nf(n,e){for(;n.entries.length>0&&n.entries.at(-1).seq>=e;){let t=n.entries.pop();(t.creator?n.creators:n.kinds).delete(t.id)}n.read.length=e-n.base,n.end=e}function he(n){let e=n.all(),t=typeof n.length=="number"?n.length:e.length,r=t-e.length,o=Ho.get(n);if(o&&o.base<=r&&r<=o.end){let i=Math.min(o.end,t);for(;i>r&&e[i-1-r]!==o.read[i-1-o.base];)i--;i===r&&r>o.base&&i<o.end?o=void 0:(i<o.end&&Nf(o,i),r>o.base&&(o.read=o.read.slice(r-o.base),o.base=r))}else o=void 0;o||Ho.set(n,o=Ef(r,r>0?zf(n,r):void 0));for(let i=o.end;i<t;i++)Mf(o,e[i-r]);return o.records}function zf(n,e){let t=[...n.epochs?.()??[]].reverse().find(r=>r.horizon);return t?.seq===e?t:void 0}function Nd(n,e,t){he(n);let r=Ho.get(n),o=[new Set,new Set];for(let a=r.entries.length-1;a>=0&&r.entries[a].seq>=e;a--)o[+r.entries[a].creator].add(r.entries[a].id);let i={},s={};for(let[a,d]of r.creators)o[1].has(a)||(i[a]=d);for(let[a,d]of r.kinds)!o[0].has(a)&&!t(a)&&(s[a]=d);return r.records.knowsAll?{creators:i,removed:s}:{creators:i}}function Dn(n,e,t,r,o,i=cn.on===!0){if(!n?.sees?.length||Z(e))return!0;let s=n.sees.filter(a=>a.kinds.includes(t.kind)&&(i||!wt(a)));return s.length===0?!1:(e=z(e),s.some(a=>{if(!ye(a,e))return!1;if(!a.own&&!a.via)return!0;let d=e.id;if(d===void 0)return!1;let l=u=>u.id===d;return a.via?r.out(t.id,a.via).some(l)||r.in(t.id,a.via).some(l):t.id===d||r.out(t.id).some(l)||r.in(t.id).some(l)||o?.creatorOf(t.id)===d}))}var Id=Symbol.for("@graview/core:node-ref"),zd=n=>typeof n=="object"&&n!==null?n[Id]:void 0;function Ze(n="*"){return If(F().check(tt(1)),n)}function If(n,e){let t=Object.freeze(e==="*"?["*"]:[...e]),r=o=>{o&&Object.defineProperty(o,Id,{value:t,enumerable:!0,configurable:!0})};return r(n),r(L(n)),n}function kt(n){if(typeof n!="object"||n===null)return;let e=zd(n);if(e)return e;let t=L(n),r=zd(t);if(r)return r;let o=t?.innerType;return o?kt(o):void 0}function xt(n){let e=n.shape;if(!e)return[];let t=[];for(let[r,o]of Object.entries(e)){let i=kt(o);i&&t.push({name:r,kinds:i,optional:o.safeParse(void 0).success})}return t}var Yo=new Set;function lr(n,e){return Z(e)?Yo:n.modules?.disabledKinds??Yo}function un(n,e){return Z(e)?!1:(n.policy?.sees?.length??0)>0||lr(n,e).size>0}function Fd(n,e){if(!un(n,e))return()=>!0;let t=n.modules?.disabledKinds??Yo,r=n.policy?.sees??[],o=z(e),i=Ce(n),s=u=>!t.has(u)&&(r.length===0||r.some(p=>p.kinds.includes(u)&&ye(p,o)&&!p.own&&!p.via&&(i||!wt(p)))),a=n.schema.kinds.every(s),d=u=>s(u)&&Tf(n.schema,u).every(p=>p.every(c=>c==="*"?a:s(c))),l=a&&n.schema.kinds.every(d);return u=>l||u!==void 0&&d(u)}function St(n,e){return t=>{let r=lr(n,e);if(!n.policy?.sees?.length&&r.size===0)return!0;let o=he(n.log),i=n.graph.getNode(t);if(i)return!r.has(i.kind)&&Dn(n.policy,e,i,n.graph,o,Ce(n));let s=o.kindOf(t)??Ld(n,o,t);return s===void 0?!0:!r.has(s)&&Dn(n.policy,e,{id:t,kind:s},{out:()=>[],in:()=>[]},o,Ce(n))}}function Tf(n,e){let t=n?.tryDefinition?.(e)?.fields?.shape??{};return Object.values(t).flatMap(r=>{let o=kt(r);return o&&r.safeParse?.(void 0).success===!1?[o]:[]})}var jf={out:()=>[],in:()=>[]};function Ld(n,e,t){if(e.knowsAll||cn.served.has(n))return;let r=t.indexOf(":");if(r<=0)return;let o=t.slice(0,r);return n.schema?.tryDefinition(o)?o:void 0}function Df(n,e,t=new Map,r){let o=lr(n,e);if(!n.policy?.sees?.length&&o.size===0)return()=>!0;let i=he(n.log);return s=>{let a=t.get(s);if(a!==void 0)return a;let d,l=n.graph.getNode(s);if(l)d=!o.has(l.kind)&&Dn(n.policy,e,l,n.graph,i,Ce(n));else{let u=i.kindOf(s)??Ld(n,i,s);if(u===void 0)return r?.add(s),!0;d=!o.has(u)&&Dn(n.policy,e,{id:s,kind:u},jf,i,Ce(n))}return t.set(s,d),d}}function Ff(n){let e=new Map;return(t,r)=>{let o=`${t}\0${r}`,i=e.get(o);if(i===void 0){let s=n?.tryDefinition(t)?.fields?.shape,a=s?.[r];i=s!==void 0&&(a===void 0||a.safeParse?.(void 0).success===!0),e.set(o,i)}return i}}function fr(n,e){return Cd(n,e).lens}var Xo=()=>({judged:new Map,shown:new Map});function Cd(n,e){let t=Ff(n.schema),r=Z(e)?void 0:z(e).id,o=()=>n.log.length??n.log.all().length,i=new WeakMap,s=n.graph,a=(u,p,c,f,g)=>{let h=(v,R)=>{if(!u(v.id))return;let S;for(let M in v)if(!(!Object.hasOwn(v,M)||M==="id"||M==="kind"||!C(v[M],u))&&!(r!==void 0&&R(M)===r)){if(!t(v.kind,M))return;(S??=[]).push(M)}if(!S)return v;let k=S.join("\0"),_=i.get(v);if(_?.without===k)return _.node;let P=Object.fromEntries(Object.entries(v).filter(([M])=>!S.includes(M)));return i.set(v,{without:k,node:P}),P},y=v=>{let R=c();return h(v,S=>p().writerAt(v.id,S,R))},b=new WeakMap,x=g?v=>{let R=b.get(v);return R||b.set(v,R={node:y(v)}),R.node}:y,$=v=>{if(!u(v))return!1;let R=s.getNode(v);return R===void 0||x(R)!==void 0},w=g?.shown??new Map,O=g?v=>{let R=w.get(v);return R===void 0&&w.set(v,R=$(v)),R}:$,A=s.outEdges&&s.inEdges?{present:{getNode:v=>s.getNode(v),outEdges:v=>s.outEdges(v),inEdges:v=>s.inEdges(v)},log:n.log,get writers(){return p()}}:void 0,m={sees:u,shows:O,served:x,servedWith:h,optional:t,kindOf:f,...r!==void 0?{actor:r}:{},...A?{timeline:A}:{},hides:()=>un(n,e),pin:g?()=>m:()=>d(Xo())};return cn.lens?.(m,n,e)??m};function d(u){let p,c=o(),f=he(n.log);return a(Df(n,e,u.judged,u.unnamed),()=>p??=vt(n.log),()=>c,g=>s.getNode(g)?.kind??f.kindOf(g),u)}return{lens:a(St(n,e),()=>vt(n.log),o,u=>s.getNode(u)?.kind??he(n.log).kindOf(u)),pinWith:d}}var Td=new WeakMap,jd=new WeakMap,Lf=n=>{let e=new Set;for(let t of n)for(let r of t.primitives)r.op==="add-node"||r.op==="remove-node"?e.add(r.node.id):r.op==="patch-node"||r.op==="splice-text"?e.add(r.id):(e.add(r.edge.from),e.add(r.edge.to));return e};function Zd(n,e){if(!un(n,e))return n.log.all();let t=n.log.all(),r=n.log.length??t.length,o=r-t.length,i=[...lr(n,e)].sort().join("\0"),s=Gd(e),a=Td.get(n.log);a||Td.set(n.log,a=new Map);let d=a.get(s),{pinWith:l}=Cd(n,e),u=jd.get(n.log);u||jd.set(n.log,u=new Set);let p=d!==void 0&&d.horizon===o&&d.off===i&&d.length<=r&&(d.length===o||t[d.length-1-o]===d.last);if(d&&p){if(d.length===r)return d.ops;let g=t.slice(d.length-o),h=l(Xo()),y=!0,b=Lf(g);for(let x of b){let $=d.judgments.judged.get(x),w=d.judgments.shown.get(x);if($!==void 0&&h.sees(x)!==$||w!==void 0&&h.shows(x)!==w){y=!1;break}}if(y){for(let x of b)if(u.has(x)){y=!1;break}}if(y){let x=[...d.ops,...Tn(g,l(d.judgments))],$={horizon:o,off:i,length:r,last:t.at(-1),ops:x,judgments:d.judgments};return a.set(s,$),x}}let c={...Xo(),unnamed:u},f=Tn(t,l(c));return a.set(s,{horizon:o,off:i,length:r,last:t.at(-1),ops:f,judgments:c}),f}function Cf(n,e,t){return(t.subjectId===void 0||!e(t.subjectId)||n.shows(t.subjectId))&&t.nodeIds.every(r=>!e(r)||n.shows(r))&&!C(t,n.sees)}function Qo(n,e){return{all:()=>n,undoneIds:()=>dn(n),epochs:e}}var Dd=new WeakMap;function Gd(n){let e=Z(n)?n:z(n);return`${n.kind}|${e.id??""}|${(e.roles??[]).join(",")}|${n.onBehalfOf?`for:${n.id??""}`:""}`}var Kd=(n,e)=>`${Gd(n)}@${e}`,Jo=(n,e)=>{let t=Reflect.get(n,e,n);return typeof t=="function"?t.bind(n):t},Zf=Symbol.for("@graview/core:seat");function we(n,e,t={}){if(Lo(n.publishing,e,t.as)){if(J.served)return J.served(n,e);throw new Error("Load @graview/core/publishing to serve a reader of an app that publishes.")}return Bd(n,e)}var Gf=()=>J.served!==void 0;function Vd(n){let e=Dd.get(n);return e||Dd.set(n,e=new Map),e}function Bd(n,e){if(!un(n,e))return n;let t=Kd(e,"head"),r=Vd(n),o=r.get(t);if(o)return o;let i=n.graph,s=fr(n,e),a=w=>{let O=S=>S===void 0?void 0:w.served(S),A=S=>O(S)!==void 0,m=S=>A(i.getNode(S));return{served:O,seenNode:A,seenId:m,seenEdge:S=>m(S.from)&&m(S.to)&&!C(S,w.sees),servedAll:S=>S.flatMap(k=>O(k)??[])}},{served:d,seenId:l}=a(s),u=()=>a(s.pin?.()??s),p=(w,O)=>{let A=vt(n.log),m=s.pin?.()??s,v=w.nodes.flatMap(S=>m.servedWith(S,k=>A.writerAt(S.id,k,O))??[]),R=new Set(v.map(S=>S.id));return{nodes:v,edges:w.edges.filter(S=>R.has(S.from)&&R.has(S.to)&&!C(S,m.sees))}},c=w=>{let{removed:O,writers:A,published:m,...v}=w,R=p(w.base,w.seq);if(!w.creators)return{...v,base:R};let S=new Set(R.nodes.map(_=>_.id)),k=Object.fromEntries(Object.entries(w.creators).filter(([_,P])=>S.has(_)&&!C(P,s.sees)));return{...v,base:R,creators:k}},f=w=>w&&c(w),g=()=>Zd(n,e),h=()=>Qo(g(),()=>n.log.epochs()),y=new Proxy(i,{get(w,O){switch(O){case"getNode":return A=>d(w.getNode(A));case"has":return l;case"allNodes":case"nodesOfKind":return(...A)=>u().servedAll(w[O](...A));case"count":return(...A)=>u().servedAll(w.nodesOfKind(...A)).length;case"allEdges":case"edgesOfKind":case"outEdges":case"inEdges":return(...A)=>w[O](...A).filter(u().seenEdge);case"out":case"in":case"neighbors":return(A,...m)=>{let v=u();return v.seenId(A)?v.servedAll(w[O](A,...m)):[]};case"snapshot":return()=>{let A=w.snapshot(),m=u();return{...A,nodes:m.servedAll(A.nodes),edges:A.edges.filter(m.seenEdge)}};case"size":{let A=u();return{nodes:A.servedAll(w.allNodes({archived:"all"})).length,edges:w.allEdges({archived:"all"}).filter(A.seenEdge).length}}default:return Jo(w,O)}}}),b=()=>{let w=g();return Uo(w,dn(w))},x=new Proxy(n.log,{get(w,O){switch(O){case"all":case"toJSON":return()=>[...g()];case"epochs":return()=>w.epochs().map(c);case"lastEpoch":return()=>f(w.lastEpoch());case"horizonEpoch":return()=>f(w.horizonEpoch());case"live":return()=>{let A=g(),m=dn(A);return A.filter(v=>!m.has(v.id))};case"get":return A=>g().find(m=>m.id===A);case"opsInBatch":return A=>g().filter(m=>m.batch===A);case"batches":return b;default:return Jo(w,O)}}}),$=new Proxy(n,{get(w,O){switch(O){case Zf:return{store:w,principal:e};case"graph":return y;case"log":return x;case"snapshot":return y.snapshot;case"batches":return b;case"canUndo":return A=>mt(h(),typeof A=="string"?[A]:A);case"violations":return A=>w.violations(A,y).filter(m=>Cf(s,v=>i.has(v),m));case"findings":return()=>w.findings().filter(A=>(A.id.includes("->")?A.id.split("->").map((v,R)=>R===0?v.slice(v.indexOf(":")+1):v):[A.id]).every(v=>!i.has(v)||l(v))&&!C(A,s.sees));case"wouldChange":return A=>w.wouldChange(A,e);case"preview":return(A,m,v)=>w.preview(A,m,{author:e,...v});case"seenBy":return(A,m)=>we(w,A,m);case"seenFor":return e;case"servedSeq":return w.servedSeq;case"checkpoint":return A=>f(w.checkpoint(A));default:return Jo(w,O)}}});return r.set(t,$),$}J.kit={seatView:Bd,viewsOf:Vd,viewKey:Kd,diff:Fe,reads:Lo};var ei=new Set;function ni(n,e){if(!n||e===void 0)return{enabled:new Set(Object.keys(n??{})),disabledKinds:ei,disabledMutations:ei,disabledInvariants:ei,administered:Ud(n,new Set(Object.keys(n??{})))};let t=new Set,r=a=>{if(!(t.has(a)||!(a in n))){t.add(a);for(let d of n[a]?.requires??[])r(d)}};for(let a of e)r(a);for(let[a,d]of Object.entries(n))d.required&&r(a);let o=new Set,i=new Set,s=new Set;for(let[a,d]of Object.entries(n))if(!t.has(a)){for(let l of d.kinds??[])o.add(l);for(let l of d.mutations??[])i.add(l);for(let l of d.invariants??[])s.add(l)}for(let a of t){let d=n[a];for(let l of d?.kinds??[])o.delete(l);for(let l of d?.mutations??[])i.delete(l);for(let l of d?.invariants??[])s.delete(l)}return{enabled:t,disabledKinds:o,disabledMutations:i,disabledInvariants:s,administered:Ud(n,t)}}function Ud(n,e){let t=new Map;for(let[r,o]of Object.entries(n??{}))e.has(r)&&o.visibility==="admin"&&t.set(r,o);return t}var Wd=new WeakMap;function ri(n){let e=Wd.get(n);if(e)return e;let t=new Map,r=new Map;for(let o of n.definitions){let i=o.derives;i&&(r.set(o.kind,i),t.set(i.from,[...t.get(i.from)??[],[o.kind,i]]))}return Wd.set(n,e={bySource:t,byKind:r}),e}var Fn=n=>ri(n).byKind.size>0;function qd(n,e,t){let r={archived:"all"};return(e.sourceEnd==="to"?n.out(t,e.via,r):n.in(t,e.via,r)).filter(o=>o.kind===e.from)}function Kf(n,e,t,r){let o={archived:"all"};return(t.sourceEnd==="to"?n.in(r,t.via,o):n.out(r,t.via,o)).filter(i=>i.kind===e)}var Hd=(n,e)=>JSON.stringify(n??null)===JSON.stringify(e??null);function ti(n,e){let t={},r={};for(let[o,i]of Object.entries(e)){let s=n[o];Hd(s,i)||(t[o]=s,r[o]=i)}return Object.keys(r).length>0?{op:"patch-node",id:n.id,before:t,after:r}:void 0}function pr(n,e,t,r={}){let{bySource:o,byKind:i}=ri(n);if(i.size===0)return[];let s=[],a=h=>{h&&(e.applyPrimitives([h]),s.push(h))},d=h=>e.getNode(h)?.kind,l=new Map,u=(h,y=!1)=>l.set(h,(l.get(h)??!1)||y),p=new Set(t.flatMap(h=>h.op==="remove-node"?[h.node.id]:[])),c=new Map,f=new Map;for(let h of t)if(h.op==="patch-node"&&i.has(d(h.id)??"")&&f.set(h.id,new Set([...f.get(h.id)??[],...Object.keys(h.after)])),h.op==="add-node"&&o.has(h.node.kind))u(h.node.id);else if(h.op==="patch-node"){let y=d(h.id);y&&o.has(y)&&(u(h.id,ge in h.after),c.set(h.id,new Set([...c.get(h.id)??[],...Object.keys(h.after)])))}else if(h.op==="add-edge"){let y=e.getNode(h.edge.from),b=e.getNode(h.edge.to);for(let[x,$]of[[y,b],[b,y]]){let w=$?i.get($.kind):void 0;x&&w&&w.via===h.edge.kind&&w.from===x.kind&&u(x.id)}}else if(h.op==="remove-edge"&&(p.has(h.edge.from)||p.has(h.edge.to))){let y=p.has(h.edge.from)?h.edge.from:h.edge.to,b=e.getNode(y===h.edge.from?h.edge.to:h.edge.from),x=b?i.get(b.kind):void 0,$=t.find(w=>w.op==="remove-node"&&w.node.id===y)?.node.kind;b&&x&&x.via===h.edge.kind&&x.from===$&&!me(b)&&a(ti(b,{[ge]:!0}))}for(let h of t){if(h.op!=="patch-node")continue;let y=e.getNode(h.id),b=y?i.get(y.kind):void 0;if(!y||!b)continue;let x=Object.keys(h.after).filter(m=>Object.hasOwn(b.back,m));if(x.length===0)continue;let $=qd(e,b,y.id);if($.length!==1)continue;let w=$[0],O={};for(let m of x){let v=b.back[m];if(c.get(w.id)?.has(v))continue;let R=y[m];n.tryDefinition(w.kind)?.fixed?.[v]===void 0&&(r.mayWriteBack&&!r.mayWriteBack(w,v,R)||(O[v]=R))}let A=ti(w,O);A&&(a(A),u(w.id))}let g=new Set;for(let[h,y]of l){if(g.has(h))continue;g.add(h);let b=e.getNode(h);if(b)for(let[x,$]of o.get(b.kind)??[])for(let w of Kf(e,x,$,b.id)){let O={...$.values(e,b,w)};if(!c.has(b.id))for(let m of f.get(w.id)??[])delete O[m];y&&(O[ge]=me(b)?!0:void 0);let A=ti(w,O);A&&(a(A),o.has(x)&&l.set(w.id,y))}}return s}function Jd(n,e,t){let{byKind:r}=ri(n);if(r.size===0)return[];let o=[];for(let i of t){let s=r.get(i.kind);if(!s)continue;let a=qd(e,s,i.id);if(a.length===1)for(let[d,l]of Object.entries(s.values(e,a[0],i))){let u=i[d];Hd(u,l)||o.push({id:i.id,source:a[0].id,field:d,holds:u,follows:l})}}return o}function Yd(n){return n.normalize("NFKD").replace(/\p{M}/gu,"").toLowerCase().trim().replace(/\s+/g," ")}var Rt=class{constructor(e){this.graph=e;for(let t of e.allNodes({archived:"all"}))this.file(t);e.subscribe(t=>this.follow(t))}kinds=new Map;filed=new Map;labelOf(e){return this.filed.get(e)?.label}lookup(e,t){let r=Yd(t);if(r.length===0)return{exact:[],prefix:[]};let o=e.includes("*")?[...this.kinds.values()]:e.flatMap(a=>this.kinds.get(a)??[]),i=[],s=[];for(let a of o)for(let d=oi(a.sorted,r);d<a.sorted.length&&a.sorted[d].startsWith(r);d+=1){let l=[...a.ids.get(a.sorted[d])??[]];s.push(...l),a.sorted[d]===r&&i.push(...l)}return{exact:i,prefix:s}}follow(e){for(let t of e.removedNodes)this.unfile(t.id);for(let t of e.changedNodes)this.unfile(t.after.id),this.file(t.after);for(let t of e.addedNodes)this.file(t)}file(e){let t=V(this.graph.schema.tryDefinition(e.kind),e),r=Yd(t);this.filed.set(e.id,{kind:e.kind,key:r,label:t});let o=this.kinds.get(e.kind);o||this.kinds.set(e.kind,o={ids:new Map,sorted:[]});let i=o.ids.get(r);i?i.add(e.id):(o.ids.set(r,new Set([e.id])),o.sorted.splice(oi(o.sorted,r),0,r))}unfile(e){let t=this.filed.get(e);if(!t)return;this.filed.delete(e);let r=this.kinds.get(t.kind),o=r?.ids.get(t.key);if(!r||!o||(o.delete(e),o.size>0))return;r.ids.delete(t.key);let i=oi(r.sorted,t.key);r.sorted[i]===t.key&&r.sorted.splice(i,1)}};function oi(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>>1;n[o]<e?t=o+1:r=o}return t}function Vf(n,e){return e.includes("*")?"record":e.map(t=>X(n.tryDefinition(t),t)).join(" or ")}function Xd(n,e,t,r){let o=Vf(n,e.kinds);if(r.length===0)return{ok:!1,reason:"none",candidates:r,message:`There is no ${o} called "${t}".`};let i=r.slice(0,10).map(a=>`${a.label} (${a.id})`),s=r.length>i.length?`, and ${r.length-i.length} more`:"";return{ok:!1,reason:"ambiguous",candidates:r,message:`"${t}" names more than one ${o}: ${i.join(", ")}${s}. Pass the id of the one you mean as ${e.name}.`}}function ii(n){if(n===null||typeof n!="object")return JSON.stringify(n)??"null";if(Array.isArray(n))return`[${n.map(r=>r===void 0?"null":ii(r)).join(",")}]`;let e=n;return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${ii(e[r])}`).join(",")}}`}var Qd=(n,e)=>n.key<e.key?-1:n.key>e.key?1:0;function Bf(n){let e=n.nodes.map(r=>({key:r.id,value:r})).sort(Qd),t=n.edges.map(r=>({key:I(r),value:{kind:r.kind,from:r.from,to:r.to,id:r.id,data:r.data}})).sort(Qd);return ii({nodes:e.map(r=>r.value),edges:t.map(r=>r.value)})}function Ln(n){return`sha256:${nc(Bf(n))}`}function ec(n,e,t,r={}){let o=r.validate??!0,i=r.base??{nodes:[],edges:[]},s=Ln(t),a=H.from(n,i,{validate:o});for(let[h,y]of e.entries())try{a.applyPrimitives(y.primitives)}catch(b){let x=e[h-1];return{ok:!1,expected:Ln(a.snapshot()),actual:s,...x?{divergedAfter:x.id}:{},reason:`The log does not fold: op "${y.id}" (${y.intent}) could not be applied. ${b instanceof Error?b.message:String(b)}`}}let d=Ln(a.snapshot());if(d===s)return{ok:!0,hash:s};let l=h=>{let y=H.from(n,i,{validate:o});for(let b=0;b<=h;b++)y.applyPrimitives(e[b].primitives);return Ln(y.snapshot())},u=h=>{try{let y=H.from(n,t,{validate:o});for(let b=e.length-1;b>h;b--)y.applyPrimitives(Je(e[b]));return Ln(y.snapshot())}catch{return}},p=h=>{let y=u(h);return y!==void 0&&y!==l(h)},c=-1,f=e.length-1;for(;c<f;){let h=Math.floor((c+f)/2);p(h)?f=h:c=h+1}let g=f>=0?e[f]:void 0;return{ok:!1,expected:d,actual:s,...g?{divergedAfter:g.id}:{},reason:g?`The graph and the fold of its log part after op "${g.id}" (${g.intent}).`:"The graph and the fold of its log disagree before any op: the base it folds from does not match."}}var Uf=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Wf=new TextEncoder,qf=new Uint32Array(64),Hf=new Uint32Array(8),hr=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function nc(n){let e=Wf.encode(n),t=e.length*8,r=new Uint8Array(e.length+9+63>>6<<6);r.set(e),r[e.length]=128;let o=new DataView(r.buffer);o.setUint32(r.length-8,Math.floor(t/2**32)),o.setUint32(r.length-4,t>>>0);let i=Hf;i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225;let s=qf;for(let d=0;d<r.length;d+=64){for(let b=0;b<16;b++)s[b]=o.getUint32(d+b*4);for(let b=16;b<64;b++){let x=s[b-15],$=s[b-2],w=(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3,O=($>>>17|$<<15)^($>>>19|$<<13)^$>>>10;s[b]=s[b-16]+w+s[b-7]+O>>>0}let l=i[0],u=i[1],p=i[2],c=i[3],f=i[4],g=i[5],h=i[6],y=i[7];for(let b=0;b<64;b++){let x=(f>>>6|f<<26)^(f>>>11|f<<21)^(f>>>25|f<<7),$=f&g^~f&h,w=y+x+$+Uf[b]+s[b]>>>0,O=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),A=l&u^l&p^u&p,m=O+A>>>0;y=h,h=g,g=f,f=c+w>>>0,c=p,p=u,u=l,l=w+m>>>0}i[0]=i[0]+l>>>0,i[1]=i[1]+u>>>0,i[2]=i[2]+p>>>0,i[3]=i[3]+c>>>0,i[4]=i[4]+f>>>0,i[5]=i[5]+g>>>0,i[6]=i[6]+h>>>0,i[7]=i[7]+y>>>0}let a="";for(let d=0;d<8;d++){let l=i[d];a+=hr[l>>>24]+hr[l>>>16&255]+hr[l>>>8&255]+hr[l&255]}return a}var $t=class{constructor(e){this.inner=e}seen=new Set;reads(){return[...this.seen]}markAll(e){for(let t of e)this.seen.add(t.id);return e}markEdges(e){for(let t of e)this.seen.add(t.from),this.seen.add(t.to);return e}getNode(e){return this.seen.add(e),this.inner.getNode(e)}has(e){return this.seen.add(e),this.inner.has(e)}allNodes(e){return this.markAll(this.inner.allNodes(e))}allEdges(e){return this.markEdges(this.inner.allEdges(e))}nodesOfKind(e,t){return this.markAll(this.inner.nodesOfKind(e,t))}edgesOfKind(e,t){return this.markEdges(this.inner.edgesOfKind(e,t))}out(e,t,r){return this.seen.add(e),this.markAll(this.inner.out(e,t,r))}in(e,t,r){return this.seen.add(e),this.markAll(this.inner.in(e,t,r))}neighbors(e,t){return this.seen.add(e),this.markAll(this.inner.neighbors(e,t))}};function Jf(n,e){return{...e,name:n}}function si(n){if(!n.creates?.length)return!1;let e=n.input.shape;return e===void 0||!("id"in e)}function ic(n){let e=n.input,t=e._zod?.def;if(t?.type!=="object"||t.catchall!==void 0||!e.shape)return;let r=Object.keys(e.shape);return si(n)?[...r,"id"]:r}var tc=(n,e,t={})=>{let r=n.filter(s=>t[s]?.length),o=n.filter(s=>!t[s]?.length);return`${[...o.length>0?[`does not take ${o.map(s=>`"${s}"`).join(", ")}`]:[],...r.map(s=>`${s} is set by ${t[s].join(" or ")}`)].join("; ")}; it takes ${e.length>0?e.map(s=>`"${s}"`).join(", "):"nothing"}`};function Yf(n){let e=n?._zod?.def;for(let t=0;e?.innerType&&t<8;t++)e=e.innerType._zod?.def;return e}var Xf=/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;function sc(n,e){let t=n?.shape;if(!t||typeof e!="object"||e===null||Array.isArray(e))return e;let r;for(let[o,i]of Object.entries(e)){if(typeof i!="string"||!Xf.test(i)||Yf(t[o])?.type!=="number")continue;let s=Number(i);Number.isFinite(s)&&(r??={...e},r[o]=s)}return r??e}var ac=n=>typeof n=="string"&&n.length<=200&&/^[^\s\p{Cc}]+$/u.test(n);function Qf(n){if(typeof n!="object"||n===null)return;let e=n.id;if(e!==void 0){if(!ac(e))throw new N("An id is 1\u2013200 characters with no space",`Got ${JSON.stringify(e)}.`);return e}}function ep(n){let{id:e,...t}=n;return t}function rc(n){return n.normalize("NFKD").replace(/\p{M}/gu,"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"")||"item"}function ai(n){let e=2166136261;for(let t=0;t<n.length;t++)e=Math.imul(e^n.charCodeAt(t),16777619);return(e>>>0).toString(36).padStart(7,"0")}function np(n,e){if(e.limited&&e.me===void 0)return oc(n,e.held);let t=e.limited?`${n}.${ai(e.me)}`:n,r=t;for(let o=2;e.seen(r);o++)r=`${t}-${o}`;return e.held(r)?oc(t,e.held):r}function oc(n,e){let t;do t=`${n}-${Math.floor(Math.random()*36**6).toString(36).padStart(6,"0")}`;while(e(t));return t}function Cn(n,e,t,r={}){let o=si(e)?Qf(t):void 0,i=sc(e.input,o===void 0?t:ep(t)),s=ic(e);if(s&&typeof i=="object"&&i!==null&&!Array.isArray(i)){let m=Object.keys(i).filter(v=>!s.includes(v)&&i[v]!==void 0);if(m.length>0)throw new ve(e.name,[{path:[],message:tc(m,s,e.writtenBy)}])}let a=e.clearable&&typeof i=="object"&&i!==null&&!Array.isArray(i)?e.clearable.filter(m=>i[m]===null):[],d=e.input.safeParse(a.length>0?Object.fromEntries(Object.entries(i).filter(([m])=>!a.includes(m))):i);if(d.success)for(let m of a)d.data[m]=null;if(!d.success){let m=Object.keys(e.input.shape??{});throw new ve(e.name,d.error.issues.map(v=>v.code==="unrecognized_keys"&&m.length>0?{...v,message:tc(v.keys,m,e.writtenBy)}:v))}let l=d.data,u=new $t(r.seen??n),p=[],c=new Set,f=r.me===void 0?void 0:`.${ai(r.me)}`,g=m=>!r.seesInFull||r.seesInFull()||f!==void 0&&new RegExp(`\\${f}(-[0-9a-z]+)?$`).test(m),h=m=>u.has(m)||n.has(m)||c.has(m)||r.everHeld?.(m)===!0,y,b=m=>{let v=new Set([...n.outEdges(m),...n.inEdges(m)]);for(let R of v)u.getNode(R.from),u.getNode(R.to),p.push({op:"remove-edge",edge:R});return v},x={graph:u,schema:n.schema,me:r.me,emit(m){p.push(m)},addNode(m){p.push({op:"add-node",node:m})},removeNode(m){let v=u.getNode(m)&&n.getNode(m);if(!v)throw new q(m,`Cannot remove missing node "${m}"`);b(m),p.push({op:"remove-node",node:v})},patchNode(m,v){let R=u.getNode(m)&&n.getNode(m);if(!R)throw new q(m,`Cannot patch missing node "${m}"`);let S={},k={};for(let[_,P]of Object.entries(v)){let M=R[_];JSON.stringify(M)===JSON.stringify(P)&&!r.keepUnchanged?.(P,_,R)||(S[_]=M,k[_]=P)}Object.keys(k).length!==0&&p.push({op:"patch-node",id:m,before:S,after:k})},archiveNode:m=>x.patchNode(m,{[ge]:!0}),unarchiveNode:m=>x.patchNode(m,{[ge]:void 0}),mergeNode(m,v){let R=u.getNode(v)&&n.getNode(v);if(!R)throw new q(v,`Cannot merge into missing node "${v}"`);if(m===v||me(R))throw new N(m===v?"Cannot merge a record into itself":"Cannot merge into an archived record");let S=new Set([...n.outEdges(v),...n.inEdges(v)].map(I));for(let k of b(m)){let _={...k,from:k.from===m?v:k.from,to:k.to===m?v:k.to};_.from!==_.to&&!S.has(I(_))&&(S.add(I(_)),p.push({op:"add-edge",edge:_}))}x.archiveNode(m),y=v},addEdge(m){p.push({op:"add-edge",edge:m})},removeEdge(m){p.push({op:"remove-edge",edge:m.id!==void 0&&n.linkById(m.id)||m})},setSingleSource(m,v,R){n.inEdges(v,m).some(S=>S.from===R)||p.push({op:"add-edge",edge:{kind:m,from:R,to:v}});for(let S of n.inEdges(v,m))u.getNode(S.from),S.from!==R&&p.push({op:"remove-edge",edge:S})},freshId(m,v,R){if(o!==void 0&&!c.has(o)){if(v&&!o.startsWith(`${v}:`)){let ne=o.includes(":")?o.slice(o.indexOf(":")+1):o;throw new N(`Id "${o}" does not say its kind: ask for "${v}:${ne||o}"`,`Every ${v} id starts "${v}:", the ones "${e.name}" mints and the ones a caller asks for alike, so a later call names it as it names the rest.`)}if(!g(o))throw new N(`"${e.name}" makes its own id here`,`Leave id out${f?`, or end it "${f}"`:""}.`);if(h(o))throw new N(`Id "${o}" is already taken`,`"${e.name}" was asked to make a node with that id, and the graph has or had one. Pick another, or leave id out and let the act mint one.`);return c.add(o),o}let S=r.hint;if(o===void 0&&!c.size&&ac(S)&&(!v||S.startsWith(`${v}:`))&&g(S)&&!h(S))return c.add(S),S;v&&r.keeps&&[l,R??{}].some(ne=>Md(m,v,ne,r.keeps))&&(m=v);let k=v?`${v}:${rc(m)}`:rc(m),_=r.seesInFull!==void 0&&!r.seesInFull(v),M=np(k,{seen:ne=>(r.seen?r.seen.has(ne):n.has(ne))||c.has(ne)||!_&&r.everHeld?.(ne)===!0,held:h,limited:_,me:r.me});return c.add(M),M}};if(e.apply(x,l),o!==void 0&&!c.has(o))throw new N(`"${e.name}" did not make a record with id "${o}": it names what it makes itself`);let $=r.check?.(p,e),w=new Set(p.flatMap(Re)),O=new $t(r.seen??n),A=e.describe?.(l,O)??`${e.name}(${Object.entries(l).map(([m,v])=>`${m}=${JSON.stringify(v)}`).join(", ")})`;return{primitives:p,reads:[...new Set([...u.reads(),...O.reads()])],...e.describe?{described:[...O.reads(),...$??[]]}:{},writes:[...w],intent:A,...y!==void 0?{mergedInto:y}:{},...c.size>0?{firstMinted:c.values().next().value}:{}}}function di(n,e,t,r,o,i){if(typeof r!="string"||typeof o!="string")return n.allowedOn===void 0;if(n.allowedOn)return n.allowedOn(t,r);let s=n.subject?.arg??"id",a=n.input.shape??{},d=t.getNode(r)?.[o],l={[s]:r,...o!==s&&o in a&&d!==void 0&&d!==null?{[o]:d}:{}},u=n.input.safeParse?.(l),p=u?.success?u.data:l,c=()=>{},f={graph:t,schema:e,me:i,addNode:c,removeNode:c,patchNode:c,archiveNode:c,unarchiveNode:c,mergeNode:c,addEdge:c,removeEdge:c,setSingleSource:c,freshId:(g,h)=>`${h?`${h}:`:""}${g}`,emit:c};try{n.apply(f,p)}catch(g){let h=g;return!(h?.name==="ActRefusal"&&h.reason!=="invalid")}return!0}var dc=Symbol.for("@graview/core:amount"),Qk=(n,e)=>(Object.defineProperty(L(n),dc,{value:e,enumerable:!0}),n);function ci(n,e=!0){let t=L(n);return t?.[dc]??(e&&t?.innerType?ci(t.innerType):void 0)}function cc(n,e={},t){let r=t===0?Math.round(n):Math.round(n*100)/100,o=Number.isInteger(r),i={maximumFractionDigits:o?0:2,minimumFractionDigits:o?0:2};try{return $e(r,e.locale,e.currency?{style:"currency",currency:e.currency,...i}:i)}catch{return $e(r,e.locale,i)}}function uc(n,{format:e,unit:t,currency:r,locale:o,places:i}){let s=/^[A-Z]{3}$/.test(t??"");return e==="money"||!e&&s?cc(n,{...o?{locale:o}:{},...(s?t:r)?{currency:s?t:r}:{}},i):e==="percent"?$e(n,o,{style:"percent",maximumFractionDigits:0}):$e(n,o)+(t?` ${t}`:"")}var tp=Symbol.for("@graview/core:typed-field");function ui(n){let e=L(n);return e?e[tp]??ui(e.innerType):void 0}var rp=/^[("'“‘]*(?:(?:[a-z]{1,3}\.){2,}|(?:dr|mr|mrs|ms|mx|st|mt|vs|jr|sr|prof|no|fig|approx)\.)$/i;function op(n){for(let e of n.matchAll(/[.!?](?=\s|$)/g)){let t=n.slice(0,e.index+1),r=/\S+$/.exec(t)?.[0]??"";if(!(e[0]==="."&&rp.test(r))&&!(t.split(" ").length<3&&e.index+1<n.length))return t}}function lc(n,e=140){let t=n.replace(/^[#>\s]+|\*\*|`|\](\([^)\s]*\))?|\[/gm,"").replace(/\s+/g," ").trim(),r=op(t);return r&&r.length<=e?r:t.length<=e?t:`${(t.slice(0,e+1).replace(/\s+\S*$/,"")||t.slice(0,e)).replace(/[\s,;:.—-]+$/,"")}\u2026`}function li(n){let e=n.fields.shape;return Object.keys(e).flatMap(t=>{let r=Yt(e[t])?ct(t):void 0;return r&&e[r]?[r]:[]})}var ip=[["skip","Skip this one","Leave one day out of the series; the rest stay as they are.","Skip {} on "],["detach","Change just this one","Make one day of the series a record of its own, to change apart from the rest.","Change {} only on "],["split","Change from here","End the series the day before, and start it again from that day with what changes.","Change {} from "]];function fc(n,e){let t=new Set(e.map(o=>o.name)),r=[];for(let o of n.definitions){let i=li(o);if(i.length===0)continue;let s=o.kind,a=o.fields.shape,d=At(n,e).get(s),l=new Set(o.keptInStep??[]),u=g=>(d?.get(g)?.length??0)>0&&!l.has(g),p=Ge(o).filter(g=>!u(g)),c=Object.fromEntries(Ge(o).filter(u).map(g=>[g,d.get(g)])),f=g=>V(o,g);for(let[g,h,y,b]of ip){let x=`${g}-${s}`;t.has(x)||r.push({name:x,derived:{kind:s,act:g},title:h,description:y,subject:{kinds:[s],arg:"id"},writes:i.map(En),...g==="skip"?{}:{creates:[s],...Object.keys(c).length>0?{writtenBy:c}:{}},input:_n({id:Ze([s]),on:F().check(rt(/^\d{4}-\d{2}-\d{2}$/,"a day, like 2026-10-21")),...i.length>1?{field:W(za(i))}:{},...g==="skip"?{}:Object.fromEntries(p.map($=>[$,W(a[$])]))}),describe:($,w)=>b.replace("{}",f(w.getNode(String($.id))??{id:$.id}))+Te(String($.on)),apply($,w){let O=$.graph.getNode(String(w.id)),A=String(w.field??i[0]),m=O?.[A],v=O?.[En(A)],R=String(w.on);if(typeof m!="string"||!Mn(v))throw new de(`${f(O??{id:w.id})} does not repeat`,"refused");let S=Pn(m,v,{from:R,to:R})[0];if(!S)throw new de(`${f(O)} does not fall on ${Te(R)}`,"refused");let k=String(O.id),_=Object.fromEntries(p.filter(K=>w[K]!==void 0).map(K=>[K,w[K]])),P=En(A),M=K=>{let bn=Object.fromEntries(Object.entries({...O,...K,..._}).filter(([ze,We])=>We!=null&&ze!=="id")),G=$.freshId(f(bn),s,bn);$.addNode({...bn,id:G,kind:s});for(let ze of Object.keys(o.edges??{}))for(let We of $.graph.out(k,ze))$.addEdge({kind:ze,from:G,to:We.id})};if(g!=="split"){$.patchNode(k,{[P]:{...v,except:[...new Set([...v.except??[],R])].sort()}}),g==="detach"&&M({[A]:S,[P]:null});return}if(Object.keys(_).length===0)throw new de(`Nothing to change: give ${f(O)} from ${Te(R)} something new`,"invalid");if(R<=m.slice(0,10))return $.patchNode(k,_);let ne=new Date(Date.parse(`${R}T00:00:00Z`)-864e5).toISOString().slice(0,10),Un=v.count?Pn(m,{...v,except:[]},{to:ne}).length:0,{count:Ne,except:yn,...Wn}=v,re=K=>yn?.some(K)?{except:yn.filter(K)}:{};$.patchNode(k,{[P]:{...Wn,until:ne,...re(K=>K<R),...Ne?{count:Un}:{}}}),M({[A]:S,[P]:{...Wn,...re(K=>K>=R),...Ne?{count:Ne-Un}:{},continues:k}})}})}}return r}function pc(n,e,t,r){if(n==="detach")return!0;if(n!=="split"||typeof e.on!="string")return!1;let o=t?.[String(e.field??r[0])];return typeof o!="string"||e.on>o.slice(0,10)}function hc(n,e){let t=new Set(e.map(a=>a.name)),r=e.filter(a=>!a.derived&&!a.creates?.length),o=(a,d,l,u)=>r.some(p=>{if(!(p[a]??[]).includes(l))return!1;let c=p.subject?.kinds;return c===void 0||c==="*"||c.includes(d)||u.to==="*"||c.some(f=>u.to.includes(f))}),i=[],s=(a,d)=>{let l=a.getNode(String(d));return l?V(n.tryDefinition(l.kind),l):String(d)};for(let a of n.definitions){let d=a.kind,l=Object.entries(a.edges??{}),u=p=>p.to==="*"?"record":p.to.map(c=>X(n.tryDefinition(c),c)).join(" or ");for(let[p,c]of l){let f=u(c),g=c.cardinality==="one",h=l.some(([w,O])=>w!==p&&u(O)===f),y=w=>B(w).toLowerCase(),b=bd(d,p,c,y),x={to:b&&"to"in b?b.to:f,from:X(a,d),one:g,also:b&&"also"in b?b.also:h&&!b?y(p):void 0},$=x.from;for(let w of Ko){let O=Vo(w,d,p);if(t.has(O)||c.acts==="none"||(w==="connect"?o("connects",d,p,c):o("severs",d,p,c)||c.appendOnly))continue;let{title:A,fromTheOtherEnd:m}=yd(w,x),v=c.description?`: ${c.description.replace(/\.$/,"")}`:"";i.push({name:O,derived:{kind:d,act:w,relation:p},title:A,fromTheOtherEnd:m,description:w==="connect"?`Link this ${$} to ${/^[aeiou]/i.test(f)?"an":"a"} ${f}${v}.${g?" It has one, so this replaces the one it has.":""}`:`Take away the link between this ${$} and ${/^[aeiou]/i.test(f)?"an":"a"} ${f}${v}. Undo puts it back.`,subject:{kinds:[d],arg:"id"},...w==="connect"?{connects:[p]}:{severs:[p],destructive:!0},idempotent:!0,input:_n({id:Ze([d]),to:Ze(c.to==="*"?"*":c.to)}),describe:(R,S)=>w==="disconnect"?`Unlink ${s(S,R.id)} from ${s(S,R.to)}`:g?`Set the ${f} of ${s(S,R.id)} to ${s(S,R.to)}`:`Link ${s(S,R.id)} to ${s(S,R.to)}`,apply(R,S){let k=String(S.id),_=String(S.to);for(let M of[k,_])if(!R.graph.getNode(M))throw new de(`there is no record "${M}"`,"invalid");let P=R.graph.out(k,p).some(M=>M.id===_);if(w==="disconnect"){if(!P)throw new de(`${s(R.graph,k)} is not linked to ${s(R.graph,_)}`,"invalid");R.removeEdge({kind:p,from:k,to:_});return}if(g)for(let M of R.graph.out(k,p))M.id!==_&&R.removeEdge({kind:p,from:k,to:M.id});P||R.addEdge({kind:p,from:k,to:_})}})}}}return i}function sp(n){let e=new Set(n.declared),t=[...new Set([...(n.paged??[]).filter(o=>e.has(o)),...n.declared])],r=(n.naming??[]).filter(o=>e.has(o));return[...new Set([...r,...t.filter(n.must),...t])]}var fi=n=>`\xA7${n}\xA7`;function ap(n,e){if(n.label)try{let r={id:fi(e.length),kind:n.kind};e.forEach((s,a)=>r[s]=fi(a));let o=String(n.label(r)),i=e.map((s,a)=>[s,o.indexOf(fi(a))]).filter(([,s])=>s>=0);if(i.length>0)return i.sort((s,a)=>s[1]-a[1]).map(([s])=>s)}catch{}let t=["name","title","label"].find(r=>e.includes(r));return t?[t]:[]}var gc=new WeakMap;function gr(n){let e=gc.get(n);if(e)return e;let t=n.fields.shape??{},r=Object.keys(t),o=n.display?.page,i=sp({declared:r,paged:[...o?.fields??[],...(o?.groups??[]).flatMap(s=>s.fields)],must:s=>t[s]?.safeParse?.(void 0).success===!1&&!Object.hasOwn(n.defaults??{},s),naming:ap(n,r)});return gc.set(n,i),i}function dp(n,e){let t=e.subject?.kinds,r=e.creates?.[0]??e.derived?.kind??(t!==void 0&&t!=="*"&&t.length===1?t[0]:void 0);return r===void 0?void 0:n.tryDefinition(r)}function cp(n,e){let t=Object.keys(e.input?.shape??{}),r=n?dp(n,e):void 0;if(!r)return t;let o=gr(r),i=d=>d!==e.subject?.arg&&o.includes(d),s=t.filter(i).sort((d,l)=>o.indexOf(d)-o.indexOf(l)),a=0;return t.map(d=>i(d)?s[a++]:d)}function pi(n,e,t=r=>r.name){let r=o=>{let i=e.indexOf(t(o));return i<0?e.length:i};return[...n].sort((o,i)=>r(o)-r(i))}function Ge(n){let e=n.fields.shape;return Object.keys(e).filter(t=>!(t in(n.fixed??{})))}function hi(n,e){let t=e.subject;return t?t.kinds==="*"?n.kinds:t.kinds:[]}function gi(n,e){let t=n.subject;if(!t||!n.writes&&n.creates?.length)return[];let r=new Set(Object.keys(e.fields.shape));if(n.writes)return n.writes.filter(s=>r.has(s));let o=n.input.shape??{},i=new Set(xt(n.input).map(s=>s.name));return Object.keys(o).filter(s=>s!==t.arg&&r.has(s)&&!i.has(s))}function At(n,e){let t=new Map,r=(o,i,s)=>{let a=t.get(o)??new Map;a.get(i)?.includes(s)||(a.set(i,[...a.get(i)??[],s]),t.set(o,a))};for(let o of e){for(let i of hi(n,o)){let s=n.tryDefinition(i);if(s)for(let a of gi(o,s))r(i,a,o.name)}for(let[i,s]of Object.entries(o.writesOther??{})){let a=n.tryDefinition(i)?.fields.shape;if(a)for(let d of s)d in a&&r(i,d,o.name)}}return t}function yc(n,e,t){let r=n.tryDefinition(t);if(!r)return[];let o=At(n,e).get(t);return Ge(r).filter(i=>!o?.has(i))}var mr=n=>`edit-${n}`;function yr(n,e,t){let r=n.tryDefinition(t);if(!r)return[];let o=new Set;for(let i of e)i.derived||((i.creates??[]).includes(t)&&o.add(i.name),hi(n,i).includes(t)&&gi(i,r).length>0&&o.add(i.name));return[...o]}function bc(n,e){let t=new Set(e.map(o=>o.name)),r=[];for(let o of n.definitions){let i=o.kind,s=mr(i);if(t.has(s))continue;let a=new Set((o.keptInStep??[]).filter(h=>Ge(o).includes(h))),d=yc(n,e,i),l=pi(Ge(o).filter(h=>d.includes(h)||a.has(h)),gr(o),h=>h);if(l.length===0)continue;let u=At(n,e).get(i),p=Object.fromEntries(Ge(o).flatMap(h=>!l.includes(h)&&u?.get(h)?.length?[[h,u.get(h)]]:[])),c=o.fields.shape,f=X(o,i),g=l.map(h=>Lt(o,h).toLowerCase());r.push({name:s,derived:{kind:i,act:"edit"},idempotent:!0,title:`Change the ${f}`,description:`Change what was set when this ${f} was made: ${g.join(", ")}.`,subject:{kinds:[i],arg:"id"},writes:l,...Object.keys(p).length>0?{writtenBy:p}:{},...l.some(h=>mc(c[h]))?{clearable:l.filter(h=>mc(c[h]))}:{},input:_n({id:Ze([i]),...Object.fromEntries(l.map(h=>[h,W(fp(c[h]))]))}),describe:(h,y)=>up(o,c,l,h,y),apply(h,y){let b={};for(let x of l){let $=y[x];$===null?b[x]=void 0:$!==void 0&&(b[x]=$)}if(Object.keys(b).length===0)throw new de(`Nothing to change \u2014 give at least one of ${g.join(", ")} a value.`,"invalid");h.patchNode(y.id,b)}})}return r}function up(n,e,t,r,o){let i=o.getNode(r.id),s=i?V(n,i):"a record",a=t.filter(d=>r[d]!==void 0).map((d,l)=>{let u=r[d],p=ct(d),c=p!==void 0&&p in e,f=Lt(n,c?p:d);return`the ${f===f.toUpperCase()?f:Ft(f)}${l===0?` of ${s}`:""} to ${c?u?`repeat ${lp(u)}`:"stop repeating":vc(n,e[d],d,u)}`});return a.length===0?`Changed nothing on ${s}`:`Changed ${a.length>1?`${a.slice(0,-1).join(", ")} and ${a.at(-1)}`:a[0]}`}var lp=n=>`every ${(n.interval??1)>1?`${n.interval} ${n.every}s`:n.every}`;function vc(n,e,t,r){if(r===null||r===""||Array.isArray(r)&&r.length===0)return"nothing";let o=n.display?.format?.[t];try{if(o)return String(o(r))}catch{}if(st(r).length>0)return st(r).map(i=>i.name).join(", ");if(at(e))return Array.isArray(r)&&r.length>1?`${r.length} linked records`:"a linked record";if(Array.isArray(r))return r.map(i=>vc(n,e,t,i)).join(", ");if(typeof r=="boolean")return r?"yes":"no";if(typeof r=="number"){let i=ci(e);return i?uc(r,i):ui(e)==="duration"?`${r>=60?`${Math.floor(r/60)} h `:""}${r%60||r<60?`${r%60} min`:""}`.trim():String(r)}if(typeof r!="string")return"a new value";if(Lr.test(r))return Te(r);if(It.test(r))return Zr(r);for(let i=L(e);i;i=L(i.innerType))if(i.type==="enum")return en(r);return`\u201C${lc(r,60)}\u201D`}function mc(n){return n._zod?.def?.type==="optional"}function fp(n){let e=n;for(let t=0;t<4;t++){let r=e._zod?.def;if((r?.type==="default"||r?.type==="prefault")&&r.innerType)e=r.innerType;else break}return e}function br(n,e){return n.filter(t=>!t.derived&&(t.creates??[]).includes(e)).map(t=>t.name)}function vr(n,e,t){if(!t.derived)return;let r=t.derived.act;return r==="edit"||r==="skip"||r==="detach"||r==="split"||r==="connect"||r==="disconnect"?yr(n,e,t.derived.kind):br(e,t.derived.kind)}function pp(n,e){let t=new Set(e.map(o=>o.name)),r=[];for(let o of n.definitions){let i=o.kind,s=X(o,i),a=(l,u)=>{let p=l.getNode(String(u));return p?V(o,p):String(u)},d=Ze([i]);for(let[l,u,p,c]of[["remove","Remove",`Remove the ${s}`,`Take this ${s} out of the graph, with every tie it has. Undo puts it back.`],["archive","Archive",`Archive the ${s}`,`Set this ${s} aside, with its ties and history kept.`],["unarchive","Bring back","Bring it back",`Bring this archived ${s} back.`],["merge","Merge",`Merge into another ${s}`,`The other takes this ${s}'s ties, and this one is archived.`],["leave-alone","Leave alone","Leave this one alone",`Nothing automated changes this ${s}: tidying passes it by until you allow it again.`],["allow-tidying","Allow tidying of","Allow tidying again",`Let tidying change this ${s} again.`]]){let f=`${l}-${i}`,g=l==="leave-alone"||l==="allow-tidying";t.has(f)||!g&&l!=="remove"&&o.archives===!1||g&&o.tidying==="never"||r.push({name:f,derived:{kind:i,act:l},title:p,description:c,subject:{kinds:[i],arg:"id"},...l==="remove"?{destructive:!0}:{},idempotent:!0,input:se(l==="merge"?{id:d,into:d}:{id:d}),describe:(h,y)=>{let b=l==="remove"&&y.getNode(String(h.id)),x=b?new Set(Object.values(b).flatMap(O=>st(O).map(A=>A.href))).size:0,$=l==="merge"&&a(y,h.id)===a(y,h.into),w=O=>$?`${a(y,O)} (${String(O)})`:a(y,O);return`${u} ${w(h.id)}${l==="merge"?` into ${w(h.into)}`:""}${x?` and its ${x} file${x>1?"s":""}`:""}`},apply:g?(h,y)=>h.patchNode(String(y.id),{[lt]:l==="leave-alone"?!0:void 0}):(h,y)=>h[`${l}Node`](y.id,y.into)})}}return r}function mi(n,e){return[...bc(n,e),...pp(n,e),...fc(n,e),...hc(n,e)]}var hp=n=>({$made:n}),wr=n=>typeof n=="object"&&n!==null&&Object.keys(n).join()==="$made"&&Number.isInteger(n.$made)&&n.$made>=0,gp=(n,e)=>Object.fromEntries(Object.entries(n.args??{}).map(([t,r])=>[t,Array.isArray(r)?r.map(e):e(r)])),yi=n=>Object.values(n.args??{}).some(e=>wr(e)||Array.isArray(e)&&e.some(wr)),wc=(n,e,t)=>({...n,args:gp(n,r=>{if(!wr(r))return r;let o=r.$made<t?e[r.$made]:void 0;if(o===void 0)throw new Error(`\u201C${n.name}\u201D names the record call ${r.$made+1} makes, and no call before it made that record.`);return o})});var mp=500,yp=120,bp=50,vp=200,wp=500,kp=200,kc=4e3,xp=["model","suggestion","interaction","actor","run","proposedBy"],bi=n=>typeof n=="string"&&n.length>0&&n.length<=yp,Sp=n=>typeof n=="string"&&n.length<=240&&n.lastIndexOf("#")>0&&n.lastIndexOf("#")<n.length-1,Rp=n=>{let e=JSON.stringify(n);return e===void 0?void 0:JSON.parse(e)};function ln(n){if(n===void 0)return;let e=n&&typeof n=="object"&&!Array.isArray(n)?n:{},t=typeof e.basis=="string"?e.basis.trim():"",r={basis:t},o=t!==""&&t.length<=mp;for(let i of Object.keys(e)){let s=e[i];i==="basis"||s===void 0||(i==="model"&&typeof s=="string"&&(s=s.trim()),i==="confidence"?o&&=typeof s=="number"&&s>=0&&s<=1:xp.includes(i)?o&&=bi(s):i==="evidence"?o&&=Array.isArray(s)&&s.length<=bp&&s.every(bi):i==="read"?o&&=Array.isArray(s)&&s.length<=vp&&s.every(Sp):i==="items"?o&&=Array.isArray(s)&&s.length>0&&s.length<=wp&&s.every(a=>Number.isInteger(a)&&a>=0):i==="voters"?o&&=Array.isArray(s)&&s.length<=kp&&s.every(bi):o&&=i!=="__proto__"&&i!=="constructor"&&i!=="prototype"&&(s=Rp(s))!==void 0,o&&(r[i]=s))}if(!o)throw new N("A lineage is { basis: 1 to 500 characters, confidence?: 0 to 1, model?, suggestion?, interaction?, actor?, run?, proposedBy?: 1 to 120 characters, evidence?: up to 50 ids, read?: up to 200 <id>#<field>, voters?: up to 200 ids, items?: up to 500 places }");if(JSON.stringify(r).length>kc)throw new N(`A lineage is at most ${kc} characters written out.`);return r}var Zn="keep-link";function xc(n){let e=(t,r)=>{let o=t.getNode(r);return o?V(n.tryDefinition(o.kind),o):r};return{name:Zn,title:"Keep this link",input:se({kind:F(),from:F(),to:F()}),describe:(t,r)=>`Keep the link from ${e(r,t.from)} to ${e(r,t.to)}`,apply(t,r){let{kind:o,from:i,to:s}=r;if(!t.graph.getNode(i)||!t.graph.getNode(s)){let d=I({kind:o,from:i,to:s});throw new q(d,`Cannot remove missing edge ${d}`)}let a=t.graph.edgesOfKind(o,{archived:"all"}).find(d=>d.from===i&&d.to===s)??{kind:o,from:i,to:s};t.removeEdge(a),t.addEdge(a)}}}var vi=(n,e)=>[...n].filter(t=>!t.derived&&t.name!==Zn&&typeof e=="string"&&(t.connects?.includes(e)||t.severs?.includes(e))).map(t=>t.name);var Ot="propose-changes",wi=500;function Sc(){return{name:Ot,title:"Propose changes",input:se({calls:Ea(se({name:F(),args:ot()})),intent:W(F())}),apply(){}}}var Rc=["kind-unknown","node-shape","edge-dangling","edge-disallowed","rule-error","rule-budget","derived-out-of-step"];function $c(n,e){let t=nr(n,e);return t&&[...t.fields].filter(Boolean)}function $p(n,e,t){return n.tryDefinition(e)?.fields?.shape?.[t]}function Gn(n,e){try{return V(n.tryDefinition(e.kind),e)}catch{return typeof e.label=="string"?e.label:"A record"}}var Ap=n=>`${n.kind}:${n.from}->${n.to}`,kr=(n,e)=>n<e?-1:n>e?1:0;function Ac(n,e,t={}){let{schema:r}=n,o=[],i=new Map;for(let c of e.nodes)i.has(c.id)||i.set(c.id,c);let s=c=>e.edges.filter(f=>f.from===c||f.to===c),a=c=>({action:"drop",primitives:[...s(c.id).filter(f=>i.has(f.from)&&i.has(f.to)).map(f=>({op:"remove-edge",edge:f})),{op:"remove-node",node:c}]}),d=new Set;for(let c of[...i.values()].sort((f,g)=>kr(f.id,g.id))){if(!r.tryDefinition(c.kind)){d.add(c.id),o.push({code:"kind-unknown",id:c.id,message:`${Gn(r,c)} is a kind of record this app no longer has`,repair:a(c)});continue}let f=$c(r,c);if(f===void 0)continue;let g=Gn(r,c),h=new Map,y=f.length>0;for(let b of f){if(b==="id"||b==="kind"){y=!1;continue}let x=$p(r,c.kind,b),$=x?x.safeParse(void 0):{success:!0,data:void 0},w=r.tryDefinition(c.kind)?.defaults;!$.success&&x&&w&&Object.hasOwn(w,b)&&($=x.safeParse(w[b])),$.success?$.data===void 0?h.set(b,{action:"clear",value:ce}):h.set(b,{action:"coerce",value:$.data}):y=!1}if(y){let b={...c};for(let[x,$]of h)$.value===ce?delete b[x]:b[x]=$.value;$c(r,b)!==void 0&&(y=!1)}if(f.length===0){o.push({code:"node-shape",id:c.id,message:`${g} does not fit what ${c.kind} declares`,repair:a(c)});continue}for(let b of f){let x=h.get(b),$=y&&x?{action:x.action,primitives:[{op:"patch-node",id:c.id,before:{[b]:c[b]===void 0?ce:c[b]},after:{[b]:x.value}}]}:a(c);o.push({code:"node-shape",id:c.id,detail:b,message:`${g}: ${B(b)} does not fit what ${c.kind} declares`,repair:$})}}let l=new Set,u=[];for(let c of[...e.edges].sort((f,g)=>kr(I(f),I(g)))){if(l.has(I(c)))continue;l.add(I(c));let f=Ap(c),g=i.get(c.from),h=i.get(c.to);if(!g||!h){o.push({code:"edge-dangling",id:f,message:"A link points at a record that is not there",repair:{action:"drop",primitives:[{op:"remove-edge",edge:c}]}});continue}u.push(c),!(d.has(g.id)||d.has(h.id))&&(r.edgeAllowed(c.kind,g.kind,h.kind)||o.push({code:"edge-disallowed",id:f,message:`${Gn(r,g)} \u2192 ${Gn(r,h)}: this app does not allow that link between them`,repair:{action:"drop",primitives:[{op:"remove-edge",edge:c}]}}))}let p=n.invariants??[];if(p.length>0){let c=H.from(r,{nodes:[...i.values()],edges:u},{validate:!1}),f=new Set,g;try{g=zn(c,p,t.invariantOptions??{})}catch{g=[{invariant:"rules",status:"could-not-judge",label:"The rules",message:"The rules could not be judged",nodeIds:[],repairs:[]}]}for(let h of g){let y=h.status==="could-not-judge"?"rule-error":h.status==="over-budget"?"rule-budget":void 0;if(!y)continue;let b=h.subjectId??h.invariant,x=`${y}|${b}|${h.invariant}`;f.has(x)||(f.add(x),o.push({code:y,id:b,detail:h.invariant,message:h.message}))}}if(Fn(r)){let c=H.from(r,{nodes:[...i.values()].filter(f=>!d.has(f.id)),edges:u},{validate:!1});for(let f of Jd(r,c,i.values())){let g=i.get(f.id),h=i.get(f.source);o.push({code:"derived-out-of-step",id:f.id,detail:f.field,message:`${Gn(r,g)}: ${B(f.field)} says ${JSON.stringify(f.holds??null)}, and it follows ${Gn(r,h)}, which works it out as ${JSON.stringify(f.follows??null)}`,repair:{action:"coerce",primitives:[{op:"patch-node",id:f.id,before:{[f.field]:f.holds===void 0?ce:f.holds},after:{[f.field]:f.follows===void 0?ce:f.follows}}]}})}}return o.sort((c,f)=>Rc.indexOf(c.code)-Rc.indexOf(f.code)||kr(c.id,f.id)||kr(c.detail??"",f.detail??""))}var _t=()=>globalThis.__graviewWatch;function Oc(n){_t()?.store?.(n)}function xr(n){n!==void 0&&_t()?.learn?.({ids:[n],words:[]})}function _c(n,e){_t()?.refused?.({...n,...e===void 0?{}:{author:e}})}function ki(n,e){let t=_t();if(!t?.refusedInput)return;let r=n.issues.map(o=>`${o.path.map(String).join(".")}: ${o.message}`).join("; ");t.refusedInput({mutation:n.mutation,message:r,...e===void 0?{}:{author:e}})}function Op(n,e){n instanceof ve&&ki(n,e)}function _p(n,e,t){_t()?.seat?.(n,e,t)}function Si(n,e){if(typeof n=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(n))return n;let t=new Date(n).getTime();if(Number.isNaN(t))throw new Error(`Not a day: ${String(n)}`);return te(e,t)}var xi=15*6e4;function Pc(n=Date.now(),e){let t=new Date(n).getTime(),r=Tt(e),o=te(r,t),i=new Date(Date.parse(`${o}T00:00:00Z`));if(i.setUTCDate(i.getUTCDate()+1),!r)return i.getTime()-t;let s=Ui(i.toISOString().slice(0,10),0,r);for(;te(r,s)===o;)s+=xi;for(;te(r,s-xi)!==o;)s-=xi;return s-t}function Pp(n,e){let t,r=()=>{t=setTimeout(()=>{let o=n.tick(new Date);r(),e?.(o)},Pc(Date.now(),n.timeZone)+1e3),t.unref?.()};return r(),()=>clearTimeout(t)}function Ri(n){let e=(n?.published?.length??0)>0;return{framework:Nn,formats:{...fe,snapshot:e?2:1}}}var Sr=class extends N{constructor(e){super(`This is the app as it stood${e.at?` at ${e.at}`:" at the start"}: the past is read, never changed`),this.name="PastError"}},$i="preview",T=(n,e)=>e===void 0?{}:{[n]:e},Ke={kind:"human"},Ec={kind:"system"},zc={kind:"system",id:"modules",name:"Modules"},Mc=n=>n.mutation===null&&n.undoes===void 0;function Ai(n,e){return`${n.invariant}|${n.subjectId??""}|${n.line||e?.has(n.invariant)?n.label:n.message}`}var Ep=new Set(["remove","archive","unarchive","merge"]),Mp={has:()=>!0},Ic=n=>new Set(n.filter(e=>e.shape).map(e=>e.name));function Tc(n,e,t){let r=Ic(n),o=p=>Ai(p,r),i=new Set(e.map(o)),s=new Set(t.map(o)),a=t.filter(p=>!i.has(o(p))),d=e.filter(p=>!s.has(o(p)));if(a.length===0||d.length===0)return{introduces:a,resolves:d};let l=p=>p.subjectId&&Ai(p,Mp),u=d.map(l);return{introduces:a.filter(p=>{let c=l(p)?u.indexOf(l(p)):-1;return c<0||(u[c]=null,!1)}),resolves:d.filter((p,c)=>u[c]!==null)}}var Kn=class extends Error{constructor(t,r){super(`Op "${t.id}" (${t.intent}) could not be applied: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.op=t;this.name="ReceiveError"}},Rr=class extends N{constructor(t,r){let o=Bo(t,r);super(`Unknown mutation "${t}"${o?` \u2014 did you mean "${o}"?`:""}`,`Registered: ${r.join(", ")||"(none)"}`);this.mutation=t;this.name="UnknownMutationError",this.nearest=o}nearest},Nc=n=>new Map(n.map(e=>[e.id,e.batch]));function Np(){let n=globalThis.crypto,e=new Uint8Array(6);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return[...e].map(t=>t.toString(36).padStart(2,"0")).join("")}var Oi=class n{schema;graph;log;mutations=new Map;keeper;typer;voter;proposer;invariants;invariantOptions;policy;publishing;tidying;votes;intelligence;may=new Map;by;declaredModules;startingModules;projected;nextId;now;validate;mintBatch;batchTag;counter=0;opCount=0;quiet=0;rehearsing=!1;suggesting=!1;proposing=!1;ticked;timeZone;past;pastEvery;listeners=new Set;constructor(e){this.pastEvery=Math.max(1,e.pastEvery??64),this.past=e.past,this.schema=e.schema,this.invariants=e.invariants??[],this.invariantOptions=e.invariantOptions??{},this.timeZone=e.timeZone,this.timeZone&&(this.ticked={day:te(this.timeZone),on:te(this.timeZone)}),this.policy=e.policy,this.publishing=e.publishing,this.tidying=e.tidying,this.votes=e.votes,this.by=e.principal??Ke,this.intelligence=e.intelligence??[];for(let i of e.intelligence??[])i.may&&this.may.set(i.name,new Set(i.may));this.declaredModules=e.modules,this.startingModules=e.enabledModules,this.nextId=e.ids??(()=>`op${++this.opCount}`),this.now=e.now??(()=>new Date().toISOString()),this.validate=e.validate??!0;let t=Np();this.batchTag=e.batchIds?void 0:t,this.mintBatch=e.batchIds??(i=>`${i}:${t}:${++this.counter}`);for(let i of e.past?[]:e.mutations??[]){if(this.mutations.has(i.name))throw new N(`Duplicate mutation "${i.name}"`);this.mutations.set(i.name,i)}for(let i of e.past?[]:mi(e.schema,e.mutations??[]))this.mutations.set(i.name,i);!e.past&&!this.mutations.has(Zn)&&(this.keeper=xc(e.schema),this.mutations.set(Zn,this.keeper)),!e.past&&!this.mutations.has(yt)&&(this.voter=wd(),this.mutations.set(yt,this.voter)),!e.past&&!this.mutations.has(Ot)&&(this.proposer=Sc(),this.mutations.set(Ot,this.proposer));let r=T("horizon",e.horizon),o={validate:this.validate};if(e.log){this.log=jn.from(e.log,e.epochs,r);let i=this.log.lastEpoch();this.graph=e.snapshot?H.from(e.schema,e.snapshot,o):this.log.fold(e.schema,{...o,...i?{from:i}:{}})}else this.log=jn.from([],e.epochs??(e.snapshot?[{seq:e.horizon??0,base:e.snapshot}]:[]),r),this.graph=H.from(e.schema,e.snapshot??{nodes:[],edges:[]},o);e.past||(this.countPastTheLog(),Oc(this))}stillNow(){if(this.past)throw new Sr(this.past)}countPastTheLog(){this.countPast(this.log.all())}countPast(e){let t=r=>{let o=/(\d+)$/.exec(r);return o?Number(o[1]):0};for(let r of e)this.counter=Math.max(this.counter,t(r.batch)),this.opCount=Math.max(this.opCount,t(r.id));this.log.horizon>0&&(this.opCount=Math.max(this.opCount,this.log.length))}get servedSeq(){return this.log.length}get publishedSeq(){return J.seq?.(this)}get publisher(){return J.act?.(this,this.mutations)}get modules(){let e=this.log.all(),t=e.at(-1)?.id,r=this.projected;if(r&&r.length===e.length&&r.last===t)return r.projection;let o,i=0;r&&r.length<=e.length&&(r.length===0||e[r.length-1]?.id===r.last)&&(o=r.said,i=r.length);for(let a=e.length-1;a>=i;a--){let d=e[a].enabledModules;if(d!==void 0){o=d;break}}o??=this.log.horizonEpoch()?.enabledModules;let s=r&&o===r.said?r.projection:ni(this.declaredModules,o??this.startingModules);return this.projected={projection:s,length:e.length,last:t,said:o},s}setEnabledModules(e,t={}){this.stillNow();let r=this.modules.enabled,o=ni(this.declaredModules,e).enabled,i=[...r].filter(u=>!o.has(u)),s=[...o].filter(u=>!r.has(u));if(i.length===0&&s.length===0)return;let a=u=>u.map(p=>{let c=this.declaredModules?.[p]?.kinds??[];return c.length>0?c.map(f=>ue(this.schema,f)).join(", "):p}).join(", "),d=[i.length>0?`Turn off ${a(i)}`:"",s.length>0?`turn on ${a(s)}`:""].filter(Boolean).join("; "),l={id:this.nextId(),seq:this.log.length,batch:t.batch??this.mintBatch("batch"),author:zc,intent:Qe(d),mutation:null,primitives:[],reads:[],writes:[],at:this.now(),...T("via",t.via),enabledModules:[...o].sort()};return this.log.append(l),this.notify(ft,[l]),l}mutation(e){let t=this.mutations.get(this.spelled(e))??(e===ir?this.publisher:void 0);if(!t)throw new Rr(e,[...this.mutations.keys()]);if(this.mutationDisabled(t))throw new N(`Mutation "${e}" belongs to a module this workspace has turned off`,`Enabled modules: ${[...this.modules.enabled].join(", ")||"(none)"}`);return t}spelled(e){return e===or&&!this.typer&&ae.typeText&&!this.past&&!this.mutations.has(e)&&this.mutations.set(e,this.typer=ae.typeText(this)),this.mutations.has(e)?e:dr(e,this.mutations.keys())??e}spelledCall(e){let t=this.spelled(e.name);return t===e.name?e:{...e,name:t}}mutationDisabled(e){return this.modules.disabledMutations.has(e.name)?!0:e.derived!==void 0&&this.modules.disabledKinds.has(e.derived.kind)}allMutations(){return[...this.mutations.values(),...this.publisher?[this.publisher]:[]].filter(e=>e!==this.keeper&&e!==this.typer&&e!==this.voter&&e!==this.proposer&&!this.mutationDisabled(e))}viaOf(e,t,r){if(e!==void 0&&e===this.keeper){let o=vi(this.mutations.values(),t?.args.kind);if(o.length>0)return o;let i=[...this.mutations.values()];return[...new Set(i.filter(s=>s.derived?.relation===t?.args.kind).flatMap(s=>vr(this.schema,i,s)??[]))]}if(e!==void 0&&e===this.typer){let o=r===void 0||Z(r)?this.graph:we(this,r).graph,i=s=>!this.mutationDisabled(s)&&di(s,this.schema,o,t?.args.node,t?.args.field,r&&z(r).id);return ae.via(this.schema,[...this.mutations.values()],this.subjectKindOf(t,r),t?.args.field,i)}if(e?.derived)return vr(this.schema,[...this.mutations.values()],e)}moved(e,t){return Tc(this.allInvariants(),e,t)}allInvariants(){return this.invariants.filter(e=>this.invariantEnabled(e))}invariantEnabled(e){if(this.modules.disabledInvariants.has(e.name))return!1;if(e.scope!=="graph"){let t=e.scope.kind;if(this.modules.disabledKinds.has(t))return!1}return!0}writesBack(e){if(this.policy)return(t,r,o)=>{try{return this.permits({name:`edit-${t.kind}`,args:{id:t.id,[r]:o}},e).ok}catch{return!1}}}permits(e,t=Ke){if(e=this.spelledCall(e),this.past)return{ok:!1,refusal:{mutation:e.name,wouldNeed:[],message:"Nothing changes while you look back."}};let r=this.refusesAgent(e,t)??this.namesTurnedOff(e,t);if(r)return{ok:!1,refusal:r};let o=this.mutations.get(e.name)??(e.name===ir?this.publisher:void 0);if(o&&o===this.publisher)return J.verdict(this,t);if(o&&o===this.voter)return bt(t)&&(this.votes?.advisory!=="visitors"||sr(t)===void 0)?{ok:!1,refusal:{mutation:e.name,wouldNeed:[],message:vd}}:{ok:!0};if(o&&o===this.proposer)return this.permitsProposal(e,t);let i=o!==void 0&&o===this.keeper&&vi(this.mutations.values(),e.args.kind).length===0,s=i?e.args.from:o?.subject&&e.args[o.subject.arg],a=this.subjectKindOf(e,t),d=be(this.policy,t,e.name,a,this.viaOf(o,e,t),typeof s=="string"?s:void 0,this.words,()=>{let l=z(t).id,u=this.namedIn(e,!1);try{for(let p of Cn(this.graph,o,e.args,this.sighted(t)).primitives)"edge"in p&&p.edge.from!==l&&p.edge.to!==l&&u.push(p.edge.to)}catch{}return u},o!==void 0&&(o.derived!==void 0||o===this.typer||i)?()=>this.madeBy(o,e,s):void 0,o?.derived!==void 0&&Ep.has(o.derived.act));if(d.ok&&o?.writesLinked&&typeof s=="string"){let l=this.refusesLinked(o,s,t);if(l)return l}return!d.ok||!o?.derived||!this.repeatMakes(o,e,s,t)?d:be(this.policy,t,e.name,a,br([...this.mutations.values()],o.derived.kind),typeof s=="string"?s:void 0,this.words)}mayPropose(e,t=Ke){if(!this.policy||this.past||bt(t))return!1;e=this.spelledCall(e);let r=this.mutations.get(e.name);return!r||r===this.proposer||r===this.voter||this.refusesAgent(e,t)||this.namesTurnedOff(e,t)?!1:!this.permits(e,t).ok&&Do(this.policy,t,e.name,this.subjectKindOf(e,t))}proposal(e,t,r,o){let{calls:i,intent:s}=e.args;if(i.length===0||i.length>wi||i.some(f=>!f.args||typeof f.args!="object"||Array.isArray(f.args)))throw new N(`A proposal holds 1 to ${wi} changes, each an act's name and its arguments.`);let a=z(r).id??r.session;if(a===void 0)throw new N("A proposal is somebody's: sign in to propose a change.");let d=ln({basis:(s??`Proposed by ${r.name??a}`).slice(0,500),proposedBy:a.slice(0,120)}),l=this.rehearsal();l.proposing=!0;let u=l.applying(i,{author:r,lineage:d,...T("via",o)});if(u.ops.length===0)return;let p=[...new Set(u.ops.flatMap(f=>f.described??[]))],c=u.ops.filter(f=>f.mutation!==null&&f.author===r);return{id:this.nextId(),seq:this.log.length,batch:t,author:r,intent:u.ops.map(f=>f.intent).join("; "),...T("batchIntent",s),mutation:null,primitives:[],reads:[],writes:[],...p.length>0?{described:p}:{},at:this.now(),...T("via",o),lineage:d,suggests:i,...T("suggestsSaid",i.length>1&&c.length===i.length?c.map(f=>f.intent):void 0)}}permitsProposal(e,t){let r=i=>({ok:!1,refusal:{mutation:e.name,wouldNeed:[],message:i}});if(bt(t))return r("Sign in to propose a change.");let o=Array.isArray(e.args.calls)?e.args.calls:[];for(let i of o){if(typeof i?.name!="string")continue;let s=this.permits(i,t);if(!(s.ok||this.mayPropose(i,t)))return r(`Not permitted to propose this: ${s.refusal.message.replace(/^Not permitted: /,"")}`)}return{ok:!0}}refusesLinked(e,t,r){let o=Z(r)?this.graph:we(this,r).graph,i=o.getNode(t);if(!i)return;let s=[...this.mutations.values()];for(let a of Object.keys(e.writesLinked??{})){let l=this.schema.tryDefinition(i.kind)?.edges?.[a]!==void 0?o.out(i.id,a):o.in(i.id,a);for(let u of l){let p=mr(u.kind),c=this.mutations.get(p),f=c?this.permits({name:p,args:{[c.subject?.arg??"id"]:u.id}},r):be(this.policy,r,p,u.kind,yr(this.schema,s,u.kind),u.id,this.words);if(f.ok)continue;let g=this.words.act?.(e.name)??e.name,h=(this.labels??=new Rt(this.graph)).labelOf(u.id)??u.id,y=this.words.noun?.(u.kind)??u.kind;return{ok:!1,refusal:{mutation:e.name,kind:i.kind,wouldNeed:f.refusal.wouldNeed,message:`Not permitted: \u201C${g}\u201D would change \u201C${h}\u201D, ${/^[aeiou]/i.test(y)?"an":"a"} ${y} that is not yours to change. ${f.refusal.message}`}}}}}repeatMakes(e,t,r,o){let i=e.derived.act;if(i!=="detach"&&i!=="split")return!1;let s=this.schema.tryDefinition(e.derived.kind);if(!s)return!1;let a=typeof r=="string"?(Z(o)?this.graph:we(this,o).graph).getNode(r):void 0;return pc(i,t.args,a,li(s))}madeBy(e,t,r){let o=he(this.log),i=o.creatorOf(r),s=t.args.into;if(!(e.derived?.act==="merge"&&typeof s=="string"&&o.creatorOf(s)!==i))return i}namedIn(e,t=!0){let r=this.mutations.get(e.name);if(!r)return[];let o=r.subject?.arg;return[...t&&o?[e.args[o]]:[],...xt(r.input).flatMap(s=>s.name===o?[]:[e.args[s.name]])].flat().filter(s=>typeof s=="string")}refuse(e,t,r=!this.rehearsing){throw r&&_c(e,t),new sn(e)}get words(){return{act:e=>this.mutations.get(e)?.title,noun:e=>X(this.schema.tryDefinition(e),e)}}refusesAgent(e,t){if(t.kind!=="agent"||t.id===void 0)return;let r=this.may.get(t.id);if(!r||r.has(e.name))return;let o=s=>`\u201C${this.mutations.get(s)?.title??s}\u201D`,i=[...r].map(o);return{mutation:e.name,message:`${t.id} may not ${o(e.name)} here: it was declared able to ${i.length===0?"do nothing else":i.join(", ")}.`,wouldNeed:[]}}namesTurnedOff(e,t=Ec){let r=this.modules.disabledKinds;if(r.size===0||!Z(t))return;let o=this.mutations.get(e.name);if(!(!o||!this.namedIn(e).some(i=>r.has(this.graph.getNode(i)?.kind))))return{mutation:e.name,message:`\u201C${o.title??e.name}\u201D names a record of a module this workspace has turned off.`,wouldNeed:[]}}sighted(e){let t={me:e&&z(e).id,everHeld:o=>he(this.log).kindOf(o)!==void 0,keeps:(o,i)=>Ed(this.policy?.sees,o,i)};if(e===void 0||!un(this,e))return t;let r=St(this,e);return{...t,seen:we(this,e).graph,keepUnchanged:o=>C(o,r),seesInFull:Fd(this,e)}}collaborative(e,t){return ae.collaborative?.(this.schema,this.graph.getNode(e)?.kind,t)??!1}asSplices(e,t){return ae.asSplices?ae.asSplices(this,e,t):e}missingFor(e,t=Ke){e=this.spelledCall(e);let r=this.mutations.get(e.name),o=new Set(this.namedIn(e));if(!r||o.size===0)return;let i=we(this,t).graph;for(let s of o)if(!i.has(s))return new q(s,`\u201C${r.title??e.name}\u201D names a record that is not there.`)}mayAdminister(e,t=Ke){let r=this.modules.administered.get(e);return r?(r.mutations??[]).some(o=>{let i=this.mutations.get(o);return!!i&&jo(i).some(s=>be(this.policy,t,o,s,this.viaOf(i)).ok)}):!1}seenBy(e,t){return we(this,e,t)}sees(e,t){return this.graph.has(t)&&St(this,e)(t)}labels;resolveRef(e,t,r=Ke){let o=(this.policy?.sees?.length??0)>0,i=c=>!o||this.sees(r,c),s=this.graph.getNode(t);if(this.labels??=new Rt(this.graph),s&&i(t))return{ok:!0,id:t,label:this.labels.labelOf(t)??t,by:"id"};let a=this.labels.lookup(e.kinds,t),d=c=>{let f=c.filter(g=>!this.graph.isArchived(g));return f.length?f:c},l=d(a.exact.filter(i)),u=l.length>0,p=(u?l:d(a.prefix.filter(i))).map(c=>({id:c,kind:this.graph.getNode(c).kind,label:this.labels.labelOf(c)??c})).sort((c,f)=>c.label<f.label?-1:c.label>f.label?1:c.id<f.id?-1:1);return p.length===1?{ok:!0,id:p[0].id,label:p[0].label,by:u?"label":"prefix"}:Xd(this.schema,e,t,p)}kindsKeptFrom(e=Ke){let t=new Set;for(let[o,i]of this.modules.administered)if(!this.mayAdminister(o,e))for(let s of i.kinds??[])t.add(s);let r=this.policy?.sees??[];if(r.length>0&&!Z(e)){let o=new Set(this.permittedMutations(e).flatMap(s=>s.creates??[])),i=Ce(this);for(let s of this.schema.kinds)!r.some(d=>d.kinds.includes(s)&&ye(d,e)&&(!d.own&&!d.via||e.id!==void 0)&&(i||!wt(d)))&&!o.has(s)&&t.add(s)}return t}permittedMutations(e=Ke){let t=this.allMutations(),r=To(this.policy,e,t.filter(s=>!s.derived&&s!==this.publisher)),o=this.publisher&&J.verdict(this,e).ok?[this.publisher]:[],i=t.filter(s=>s.derived!==void 0&&be(this.policy,e,s.name,s.derived.kind,this.viaOf(s),z(e).id).ok);return[...r,...o,...i]}subjectKindOf(e,t=Ec){let o=this.mutations.get(e.name)?.subject;if(!o)return;let i=e.args[o.arg];if(typeof i!="string")return o.kinds!=="*"&&o.kinds.length===1?o.kinds[0]:void 0;if(!(!Z(t)&&!we(this,t).graph.has(i)))return this.graph.getNode(i)?.kind}today(){return this.pinned()??(this.ticked&&this.ticked.on===te(this.timeZone)?this.ticked.day:void 0)??(this.timeZone?te(this.timeZone):void 0)}pinned(){let e=this.invariantOptions.context,t=this.invariantOptions.today??e?.today;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:void 0}judging(e){let t=this.today(),r=Ka(this.graph),o=e??this.invariantOptions.context,i=r&&!(o&&"linked"in o)?{...o,linked:r}:e,s=i??o,a=this.timeZone&&t!==void 0&&e===void 0&&!(s&&"today"in s)?{...s,today:t}:i;return{...this.invariantOptions,...a===void 0?{}:{context:a},...t===void 0?{}:{today:t}}}tick(e=new Date){let t=this.pinned();if(t!==void 0)return{day:t,was:t,appeared:[],cleared:[]};let r=Si(e,this.timeZone),o=te(this.timeZone);this.ticked&&(this.ticked={day:this.ticked.day,on:o});let i=this.today(),s=this.violations();this.ticked={day:r,on:o};let a=this.moved(s,this.violations());if(r!==i&&!this.rehearsing&&this.quiet===0)for(let d of this.listeners)d(ft,[]);return{day:r,...i===void 0?{}:{was:i},appeared:a.introduces,cleared:a.resolves}}reread(){if(!(this.rehearsing||this.quiet>0))for(let e of this.listeners)e(ft,[])}violations(e,t=this.graph){return zn(t,this.allInvariants(),this.judging(e)).map(r=>this.asking(r))}required=new Map;asking(e){if(!e.repairs.some(o=>o.missing===void 0))return e;let t=!1,r=e.repairs.map(o=>{if(o.missing!==void 0)return o;let i=this.requiredOf(o.mutation).filter(s=>o.args?.[s]===void 0);return i.length===0?o:(t=!0,{...o,missing:i})});return t?{...e,repairs:r}:e}requiredOf(e){let t=this.required.get(e);if(t)return t;let r=this.mutations.get(e)?.input?.shape??{},o=Object.entries(r).filter(([,i])=>typeof i?.safeParse=="function"&&!i.safeParse(void 0).success).map(([i])=>i);return this.required.set(e,o),o}wouldChange(e,t){try{return Cn(this.graph,this.mutation(e.name),e.args,this.sighted(t)).primitives.length>0}catch{return!0}}preview(e,t,r={}){e=this.spelledCall(e);let o=this.mutation(e.name),i=Cn(this.graph,o,e.args,this.sighted(r.author)),s=this.asSplices(i.primitives),a=[];if(Fn(this.schema)){let d=H.from(this.schema,this.graph.snapshot());d.applyPrimitives(s),a=pr(this.schema,d,s,{mayWriteBack:this.writesBack(r.author??this.by)})}return this.previewPrimitives([...s,...a],{reads:i.reads,writes:i.writes,intent:i.intent,context:t})}previewAll(e,t={}){let{context:r,...o}=t;return{...this.rehearsal().applying(e,o,r),kept:!1}}rehearsal(){let e=Object.assign(Object.create(n.prototype),this),t=0;Object.assign(e,{graph:H.from(this.schema,this.graph.snapshot(),{validate:this.validate}),log:jn.from(this.log.all(),this.log.epochs(),{horizon:this.log.horizon}),listeners:new Set,labels:void 0,nextId:()=>`${$i}:${++t}`,mintBatch:()=>$i,rehearsing:!0});let r=this.typer&&ae.typeText(e);return Object.assign(e,{typer:r,mutations:r?new Map(this.mutations).set(or,r):new Map(this.mutations)}),e}wouldKeep(e,t,r){try{return this.rehearsal().applying(e,{author:t,lineage:r}),!0}catch{return!1}}previewPrimitives(e,t){let r=this.violations(t.context),o=H.from(this.schema,this.graph.snapshot()),i=o.applyPrimitives(e,{restoring:t.restoring===!0}),s=zn(o,this.allInvariants(),this.judging(t.context));return{diff:i,primitives:e,reads:t.reads,writes:t.writes,intent:t.intent,...this.moved(r,s),violationsAfter:s}}apply(e,t={}){return this.applyAll([e],t)}applyAll(e,t={}){return this.applying(e,t)}applying(e,t,r){let o=e.map(k=>this.spelledCall(k));this.stillNow();let i=t.batch??this.mintBatch("batch"),s=t.author??this.by,a=ln(t.lineage),d=[],l=[],u=new Set,p=new Set,c=[],f=this.violations(r),g=this.graph.snapshot(),h=this.log.length,y=(k,_=s)=>{let P=this.voter!==void 0&&this.mutations.get(k.name)===this.voter,M=this.policy||this.publisher&&k.name===ir||P||this.mutations.get(k.name)===this.proposer?this.permits(k,_):void 0;M&&!M.ok&&!(this.proposing&&this.mayPropose(k,_))&&this.refuse(M.refusal,_.id)},b=(k,_=s)=>{let P=this.refusesAgent(k,_)??this.namesTurnedOff(k,_);P&&this.refuse(P,_.id)},x=o.map(yi);o.forEach((k,_)=>x[_]||y(k)),o.forEach((k,_)=>x[_]||b(k));let $=o.map(k=>({sent:k,as:s,lineage:a,decided:!1}));cr(s)&&this.refuseDeclined(o,s),this.rehearsing||xr(s.id);let O=[],A=[],m=new Map,v=k=>typeof k=="string"?m.get(k)??k:Array.isArray(k)?k.map(v):k;try{for(let k=0;k<$.length;k++){let{sent:_,as:P,lineage:M,decided:ne}=$[k],Un=k<x.length?x[k]:yi(_),{mintedHint:Ne,...yn}=_,Wn=m.size?{...yn,args:Object.fromEntries(Object.entries(yn.args).map(([j,Se])=>[j,v(Se)]))}:yn,re=Un?wc(Wn,O,k):Wn;(Un||ne)&&(y(re,P),b(re,P));let K=this.mutation(re.name);if(K===this.publisher){let j=J.op(this,{id:this.nextId(),at:this.now()},re,i,P,t);d.push(j),c.push(j.intent);continue}if(K===this.voter){if(!ar.op)throw new N("Load @graview/core/tidying to vote on a suggestion.");let j=ar.op(this,{id:this.nextId(),at:this.now()},re,i,P,t);this.log.append(j),d.push(j),c.push(j.intent);let Se=ar.accepting?.(this,j);if(Se&&this.wouldKeep(Se.calls,Se.author,Se.lineage))for(let pu of Se.calls)$.push({sent:pu,as:Se.author,lineage:ln(Se.lineage),decided:!0});continue}if(K===this.proposer){let j=this.proposal(re,i,P,t.via);if(!j)continue;this.log.append(j),d.push(j),c.push(j.intent);continue}let bn=this.missingFor(re,P);if(bn)throw bn;let G;try{G=Cn(this.graph,K,re.args,{...this.sighted(P),hint:Ne})}catch(j){throw j instanceof ve&&!this.rehearsing&&ki(j,P.id),j}if(Ne!==void 0&&G.firstMinted!==void 0&&G.firstMinted!==Ne&&m.set(Ne,G.firstMinted),cr(P)){let j=$d(this.schema,this.graph,G.primitives,this.authorName(P),{declaration:!this.suggesting&&!ne});j&&this.refuse({mutation:re.name,message:j,wouldNeed:[]},P.id)}if(G.primitives.length===0)continue;A[k]=G.firstMinted;let ze=this.asSplices(G.primitives,t.base).map(He);this.graph.applyPrimitives(ze);let We=Fn(this.schema)?pr(this.schema,this.graph,ze,{mayWriteBack:this.writesBack(P)}).map(He):[];O[k]=G.primitives.find(j=>j.op==="add-node")?.node.id;let vn={id:this.nextId(),seq:this.log.length,batch:i,author:P,intent:K.describe!==void 0?G.intent:t.intent??G.intent,...T("batchIntent",t.intent),mutation:re,primitives:[...ze,...We],reads:G.reads,writes:We.length>0?[...new Set([...G.writes,...We.flatMap(Re)])]:G.writes,...K.describe!==void 0&&G.described&&G.described.length>0?{described:G.described}:{},...T("mergedInto",G.mergedInto),at:this.now(),...T("via",t.via),...T("lineage",M)};this.log.append(vn),d.push(vn),l.push(...vn.primitives);for(let j of vn.reads)u.add(j);for(let j of vn.writes)p.add(j);c.push(vn.intent)}}catch(k){throw this.putBack(g,h),k}let R=Le(g,this.graph.snapshot(),l);this.admitted(t,d,l,R,g,h);let S=this.violations(r);return this.notify(R,d),{batch:i,ops:d,...A.length>0?{minted:A}:{},diff:R,primitives:l,reads:[...u],writes:[...p],intent:t.intent??c.join("; "),...this.moved(f,S),violationsAfter:S}}receive(e,t={}){this.stillNow();let r=new Set(this.log.all().map(d=>d.id)),o=e.filter(d=>!r.has(d.id));if(o.length===0)return[];let i=this.graph.snapshot(),s=[];if(!t.applied)for(let d of o)try{this.graph.applyPrimitives(d.primitives,{restoring:d.undoes!==void 0})}catch(l){throw this.graph.load(i),new Kn(d,l)}let a=this.log.length;for(let[d,l]of o.entries()){let u=qn({...l,seq:a+d});this.log.append(u),s.push(u)}return this.countPast(s),this.notify(Le(i,this.graph.snapshot(),o.flatMap(d=>d.primitives)),s),s}append(e,t={}){if(this.stillNow(),e.length===0)return[];let r=new Set(this.log.all().map(a=>a.id)),o,i=e.map((a,d)=>{let l=a.primitives.map(He),u={id:a.id??this.nextId(),seq:this.log.length+d,batch:a.batch??t.batch??(o??=this.mintBatch("batch")),author:a.author,intent:a.intent,...T("batchIntent",a.batchIntent),mutation:a.mutation??null,primitives:l,reads:a.reads??[],writes:a.writes??[...new Set(l.flatMap(Re))],at:a.at??this.now(),...T("undoes",a.undoes),...T("via",a.via),...T("lineage",ln(a.lineage)),...T("described",a.described),...T("sentOut",a.sentOut)};if(r.has(u.id))throw new N(`Op "${u.id}" (${u.intent}) is already in the log`,"A host-made op needs an id of its own; leave `id` out and the store mints one.");return r.add(u.id),u}),s=this.graph.snapshot();for(let a of i)try{this.graph.applyPrimitives(a.primitives,{restoring:a.undoes!==void 0})}catch(d){throw this.graph.load(s),new Kn(a,d)}for(let a of i)this.log.append(a);this.countPast(i);for(let a of i)xr(a.author.id);return this.notify(Le(s,this.graph.snapshot(),i.flatMap(a=>a.primitives)),i),i}applyPrimitives(e,t={}){this.stillNow();let r=t.batch??this.mintBatch("batch"),o=t.author??this.by,i=this.violations(),s=this.graph.snapshot(),a=t.intent??"Apply a change",d=ln(t.lineage),l=this.asSplices(e,t.base).map(He);this.graph.applyPrimitives(l);let u=l;try{Fn(this.schema)&&(u=[...l,...pr(this.schema,this.graph,l,{mayWriteBack:this.writesBack(o)}).map(He)])}catch(g){throw this.putBack(s,this.log.length),g}let p=[];if(u.length>0){let g={id:this.nextId(),seq:this.log.length,batch:r,author:o,intent:a,mutation:null,primitives:u,reads:[],writes:[...new Set(u.flatMap(Re))],at:this.now(),...T("via",t.via),...T("lineage",d)};this.log.append(g),p.push(g),xr(o.id)}let c=this.violations(),f=Le(s,this.graph.snapshot(),u);return this.notify(f,p),{batch:r,ops:p,diff:f,primitives:u,reads:[],writes:p[0]?.writes??[],intent:a,...this.moved(i,c),violationsAfter:c}}findings(){return Ac({schema:this.schema,invariants:this.allInvariants()},this.graph.snapshot(),{invariantOptions:this.invariantOptions})}batches(){return this.log.batches()}canUndo(e){return mt(this.log,typeof e=="string"?[e]:e)}previewUndo(e,t){let r=this.canUndo(e);if(!r.ok)return{ok:!1,check:r};let o=pd(r.ops,this.log.all()),i=new Set;for(let s of r.ops)for(let a of s.writes)i.add(a);return{ok:!0,check:r,...this.previewPrimitives(o,{reads:[...new Set(r.ops.flatMap(s=>[...s.reads]))],writes:[...i],intent:`Undo: ${r.ops.map(s=>s.intent).join("; ")}`,restoring:r.ops.every(Mc),...t===void 0?{}:{context:t}})}}undo(e,t={}){return this.undoing(e,t)}undoing(e,t){this.stillNow();let r=typeof e=="string"?[e]:e,o=t.author??this.by,i=(this.policy?.sees?.length??0)>0&&!Z(o);if(i){let y=mt(Qo(Tn(this.log.all(),fr(this,o)),()=>this.log.epochs()),r);if(!y.ok)throw new on(y)}let s=this.canUndo(r);if(!s.ok)throw new on(i?{ok:!1,ops:[],blockedBy:[],includeBatches:[],message:"Cannot undo on its own \u2014 a later change you cannot see depends on it, which only somebody who can see it can take back."}:s);let a=t.batch??this.mintBatch("undo"),d=ln(t.lineage),l=this.undoRefusal(s.ops,o);l&&this.refuse(l,o.id,!0);let u=this.graph.snapshot(),p=this.violations(),c=[],f=this.log.length;for(let{op:y,primitives:b}of Go(this.log.all(),s.ops)){let x={id:this.nextId(),seq:this.log.length,batch:a,author:o,intent:`Undo: ${y.intent}`,...T("batchIntent",t.intent),mutation:null,primitives:b,reads:y.reads,writes:y.writes,at:this.now(),undoes:y.id,...T("via",t.via),...T("lineage",d),...T("undoneLineage",y.lineage)};this.graph.applyPrimitives(x.primitives,{restoring:Mc(y)}),this.log.append(x),c.push(x)}let g=Le(u,this.graph.snapshot(),c.flatMap(y=>[...y.primitives]));this.admitted(t,c,c.flatMap(y=>[...y.primitives]),g,u,f);let h=this.violations();return this.notify(g,c),{batch:a,ops:c,diff:g,primitives:c.flatMap(y=>[...y.primitives]),reads:[...new Set(c.flatMap(y=>[...y.reads]))],writes:[...new Set(c.flatMap(y=>[...y.writes]))],intent:t.intent??c.map(y=>y.intent).join("; "),...this.moved(p,h),violationsAfter:h}}mayUndo(e,t=this.by){let r=this.canUndo(e);if(!r.ok)return{ok:!1,check:r};let o=this.undoRefusal(r.ops,t);return o?{ok:!1,refusal:o}:{ok:!0}}undoRefusal(e,t){if(this.policy||this.publisher)for(let r of e){let o=this.rootOf(r),i=z(o.author).id;if(o.vote!==void 0){if(o.vote.advisory&&!Z(t)&&sr(t)!==o.vote.voter&&!(this.policy&&this.grantsEveryAct(t)))return{mutation:"undo",wouldNeed:[],message:`Not permitted to undo "${r.intent}": only whoever voted takes their vote back.`};if(this.policy&&!Z(t)&&i!==z(t).id&&!this.grantsEveryAct(t))return{mutation:"undo",wouldNeed:[],message:`Not permitted to undo "${r.intent}": only whoever voted takes their vote back.`};continue}if(!o.mutation){if(o.primitives.length===0)continue;if(this.policy&&!Z(t)&&i!==z(t).id&&!this.grantsEveryAct(t))return{mutation:"undo",wouldNeed:[],message:`Not permitted to undo "${r.intent}": no act made it, so only whoever did may take it back.`};continue}let s=d=>JSON.stringify(d).includes(JSON.stringify(i)),a=i!==void 0&&i!==z(t).id&&!Z(t)&&!s(o.mutation.args)&&s(o.primitives)?{ok:!1,refusal:{mutation:o.mutation.name,wouldNeed:[],message:"it was done as somebody else."}}:this.permits(o.mutation,t);if(!a.ok)return{...a.refusal,message:`Not permitted to undo "${r.intent}": ${a.refusal.message}`}}}rootOf(e){let t=e;for(let r=t.undoes===void 0?void 0:this.log.get(t.undoes);r!==void 0;r=t.undoes===void 0?void 0:this.log.get(t.undoes))t=r;return t}grantsEveryAct(e){let t=z(e);return(this.policy?.grants??[]).some(r=>ye(r,t)&&r.mutations==="*"&&(r.kinds===void 0||r.kinds==="*")&&!r.self&&!r.ownEnd)}authorName(e){return ut(e,{graph:this.graph,schema:this.schema})}actMeanings(){return{act:e=>this.mutations.get(this.spelled(e)),has:e=>this.graph.has(e)}}refuseDeclined(e,t){let r=Rd(this.log.all(),e,this.actMeanings());r&&this.refuse({mutation:e[0].name,message:`${this.authorName(t)} may not make this again: a person declined it on ${r.at.slice(0,10)}.`,wouldNeed:[]},t.id)}putBack(e,t){this.graph.load(e),this.log.length>t&&this.log.truncate(t)}admitted(e,t,r,o,i,s){if(!e.admit||t.length===0)return;let a=this.graph.size;try{e.admit({ops:t,primitives:r,added:{nodes:o.addedNodes.length,edges:o.addedEdges.length},removed:{nodes:o.removedNodes.length,edges:o.removedEdges.length},changed:{nodes:o.changedNodes.length},nodesAfter:a.nodes,edgesAfter:a.edges})}catch(d){throw this.putBack(i,s),d}}redo(e,t={}){return this.undo(e,t)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(e,t){if(!(this.quiet>0)&&!(t.length===0&&Ya(e)))for(let r of this.listeners)r(e,t)}rebase(e){this.stillNow();let t=new Set([...e.pending,...e.drop??[]]),r=this.log.all(),o=r.findIndex(h=>t.has(h.batch)),i=r.slice(o<0?r.length:o),s=this.log.horizon+(o<0?r.length:o),a=i.find(h=>!t.has(h.batch));if(a)throw new N(`Cannot rebase: op "${a.id}" (${a.intent}) comes after a pending batch and is neither pending nor dropped`,"While anything is pending, land the server's ops through rebase, so the log stays confirmed ops then pending ones.");let d=this.log.lastEpoch();if(d&&d.seq>s)throw new N(`Cannot rebase across an epoch: one begins at seq ${d.seq}, after pending op "${i[0].id}"`);let l=this.graph.snapshot(),u=[],p=[],c=[];this.quiet++;try{for(let x of[...i].reverse())this.graph.applyPrimitives(Je(x),{restoring:!0,inPlace:!0});this.log.truncate(s);let h=new Set(this.log.all().map(x=>x.id));for(let x of e.confirmed){if(h.has(x.id))continue;try{this.graph.applyPrimitives(x.primitives,{restoring:x.undoes!==void 0})}catch(w){throw new Kn(x,w)}let $=qn({...x,seq:this.log.length});this.log.append($),h.add(x.id),u.push($)}this.countPast(u);let y=ae.carried?.(i,u,e.pending),b=Nc(i);for(let x of e.pending){let $=i.filter(w=>w.batch===x);if($.length!==0)try{p.push(...this.replay(x,$,y?.get(x),b))}catch(w){c.push({batch:x,error:w})}}}catch(h){this.log.truncate(s);for(let y of i)this.log.append(y);throw this.graph.load(l),h}finally{this.quiet--}let f=Fe(l,this.graph.snapshot()),g=[...u,...p];return this.notify(f,g),{diff:f,confirmed:u,pending:p,refused:c}}adopt(e){this.stillNow();let t=new Set(e.drop??[]),r=(e.pending??[]).filter(f=>!t.has(f)),o=this.log.all(),i=this.graph.snapshot(),s={ops:[...o],epochs:[...this.log.epochs()],horizon:this.log.horizon},a=new Set(o.map(f=>f.id)),d=new Map(r.map(f=>[f,o.filter(g=>g.batch===f)]));if(e.log.length>0)this.log.replace(e.log,e.epochs,T("horizon",e.horizon));else{let f=e.horizon??0;this.log.replace([],e.epochs??[{seq:f,base:e.snapshot}],{horizon:f})}let l=[],u=[];this.quiet++;try{this.graph.load(e.snapshot),this.projected=void 0,this.countPastTheLog();for(let f of r){let g=d.get(f)??[];if(g.length!==0)try{l.push(...this.replay(f,g,void 0,Nc(o)))}catch(h){u.push({batch:f,error:h})}}}catch(f){throw this.log.replace(s.ops,s.epochs,{horizon:s.horizon}),this.graph.load(i),this.projected=void 0,f}finally{this.quiet--}let p=this.log.all().filter(f=>!a.has(f.id)&&!l.includes(f)),c=Fe(i,this.graph.snapshot());return this.notify(c,[...p,...l]),{diff:c,adopted:p,pending:l,refused:u}}replay(e,t,r,o=new Map){let i=t[0],s={author:i.author,batch:e,...T("intent",i.batchIntent),...T("via",i.via),...T("lineage",i.lineage)};if(i.undoes!==void 0){let a=t.map(l=>this.log.get(l.undoes??"")?.batch??o.get(l.undoes??"")),d=t.find((l,u)=>a[u]===void 0||!this.log.all().some(p=>p.batch===a[u]));if(d)throw new N(`What "${d.intent}" took back is no longer in the log`);return this.undoing([...new Set(a)],s).ops}return r?this.applying(r,s).ops:t.every(a=>a.mutation!==null)?this.applying(t.map(a=>a.mutation),s).ops:this.append(t.map(({seq:a,...d})=>d))}snapshot(){return this.graph.snapshot()}verify(){let e=this.log.lastEpoch();return ec(this.schema,this.log.opsFrom(e?.seq??0),this.graph.snapshot(),{validate:this.validate,...e?{base:e.base}:{}})}checkpoint(e={}){let t=this.log.all(),r;if(e.seq!==void 0)r=e.seq;else{let u=this.log.length-(e.keepOps??1e3),c=Date.parse(e.now??this.now())-(e.keepDays??90)*864e5,f=t.find(h=>Date.parse(h.at)>c),g=f?f.seq:this.log.length;r=Math.min(u,g)}let o=Fo(this.publishing)&&this.publishedSeq===void 0?[0]:[],i=[...e.pins??[],...o].filter(u=>Number.isInteger(u));i.length>0&&(r=Math.min(r,...i));let s=e.format??fe.snapshot;if(!Number.isInteger(s)||s<1||s>fe.snapshot)throw new RangeError(`Cannot write a checkpoint in snapshot format ${String(s)}: this build writes formats 1 to ${fe.snapshot}.`);let a=u=>{let p=Math.min(Math.max(u,this.log.horizon),this.log.length);for(;p>this.log.horizon&&p<this.log.length&&t[p-this.log.horizon].batch===t[p-1-this.log.horizon].batch;)p--;return p};if(r=a(r),r<=this.log.horizon)return;let d=this.verify();if(!d.ok)throw new N(`Cannot compact a store that does not verify: ${d.reason}`);let l=this.checkpointWithPublished(r);for(;Ri(l).formats.snapshot>s;){if(r=a(Math.min(...l.published.map(u=>u.seq))),r<=this.log.horizon)return;l=this.checkpointWithPublished(r)}return l}checkpointWithPublished(e){let t=this.log.horizonEpoch()?.published??[],r=(J.behind?.(this,e)??[]).flatMap(o=>o>=this.log.horizon?[this.epochAt(o)]:t.filter(i=>i.seq===o));return{...this.epochAt(e),...r.length>0&&{published:r}}}epochAt(e){let t=this.log.all(),{creators:r,removed:o,writers:i,published:s,...a}=this.log.checkpointAt(this.schema,e,{validate:this.validate}),d=new Set(a.base.nodes.map(g=>g.id)),{creators:l,removed:u}=Nd(this.log,e,g=>d.has(g)),p=he(this.log),c=Pd(this.log,e,a.base.nodes,g=>C(g,h=>!d.has(h)&&p.kindOf(h)===void 0)),f=g=>g&&Object.keys(g).length>0;return{...a,...f(l)&&{creators:l},...u&&{removed:u},...f(c)&&{writers:c},...T("enabledModules",t.slice(0,e-this.log.horizon).reverse().find(g=>g.enabledModules)?.enabledModules??this.log.horizonEpoch()?.enabledModules),...T("publishedThrough",J.seq?.(this,e))}}compact(e){return this.stillNow(),this.log.compact(e)}};var zp=n=>`lens:${n}`,Ip={hidden:[],removed:[],may:{views:!1,lenses:!1}};function Tp(n,e,t){return n.name!==void 0&&e.may.views?"view":n.declared&&e.may.lenses&&t.lens?"lens":null}var jc=["full","summary","glyph"],Pt="view:",Pi=(n,e)=>n.as===e.as&&(n.over??[n.kind]).includes(e.kind),jp=n=>n.filter((e,t)=>!n.slice(0,t).some(r=>Pi(r,e))),Dp=n=>n.filter(e=>!e.hidden);function Ee(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Et(n,e){return`/${Ee(n.tryDefinition(e)?.plural??`${e}s`)}`}function Fp(n,e,t){return`${Et(n,e)}/${encodeURIComponent(t)}`}function Lp(n,e){return`/places/${encodeURIComponent(n)}${e?`?of=${encodeURIComponent(e)}`:""}`}function Dc(n,e){return e.some(t=>t.as===n.as&&!Pi(n,t))}function Cp(n,e,t){return Dc(n,e)?`${n.title} \xB7 ${(t.tryDefinition(n.kind)?.plural??`${n.kind}s`).toLowerCase()}`:n.title}var fn=(n,e,t="")=>`${n}|${e.cardinality}|${e.fidelity}|${t}`;function _i(n){switch(n){case"full":return["full","summary","glyph"];case"summary":return["summary","full","glyph"];case"glyph":return["glyph","summary","full"]}}function Zp(n){let e=new Map,t=[],r=[],o,i=[],s={arrange(a){return a!==void 0&&(o=a),s},arrangement:()=>o,home(a,d){return a!==void 0&&i.push({view:a,...d?.name!==void 0?{name:d.name}:{}}),s},homeView:()=>i.at(-1)?.view,homes:()=>i,register(a,d,l,u){let p={...u?.over?.[1]?{over:u.over}:{},...u?.hidden?{hidden:!0}:{},...u?.name?{name:u.name}:{},...u?.declared?{declared:!0}:{}},c={kind:a,cardinality:d.cardinality,fidelity:d.fidelity,view:l,...u?.title?{title:u.title}:{},...u?.across?{across:u.across}:{},...u?.beside?{beside:!0}:{},...p};if(r.push(c),!u?.beside&&!p.hidden&&e.set(fn(a,d),c),u?.title){let f=Ee(u.title);e.set(fn(a,d,f),c),d.cardinality==="many"&&!t.some(g=>g.kind===a&&g.as===f)&&t.push({kind:a,title:u.title,as:f,...u.across?{across:u.across}:{},...p,...u.lens?{lens:u.lens}:{},...u.reads?.length?{reads:u.reads}:{}})}return s},places:()=>t,forget(a,d){for(let u of jc)e.delete(fn(a,{cardinality:"many",fidelity:u},d));let l=t.findIndex(u=>u.kind===a&&u.as===d);return l>=0&&t.splice(l,1),s},lookup(a,d){return e.get(fn(a,d))?.view},resolve(a,d,l){if(l)for(let u of _i(d.fidelity)){let p=e.get(fn(a,{cardinality:d.cardinality,fidelity:u},l));if(p)return p}for(let u of _i(d.fidelity)){let p=e.get(fn(a,{cardinality:d.cardinality,fidelity:u}));if(p)return p}if(d.cardinality==="one")for(let u of _i(d.fidelity)){let p=e.get(fn(a,{cardinality:"many",fidelity:u}));if(p)return p}},registrations:()=>r,all(){return[...e.values()]},kindsWithViews(){return[...new Set([...e.values()].map(a=>a.kind))]}};return s}var Gp=["day","week","month","year","decade"];function Fc(n){let e={};n.q&&n.q.trim().length>0&&(e.query=n.q);let t=$o(n.archived);if(t&&(e.archived=t),n.sort){let[r,o]=n.sort.split(":");r&&(e.sort={by:r,direction:o==="desc"?"desc":"asc"})}if(n.filter){let r=[];for(let o of n.filter.split(",")){let i=o.indexOf(":");i<=0||r.push({key:o.slice(0,i),value:o.slice(i+1)})}r.length>0&&(e.filter=r)}if(n.group){let[r,o]=n.group.split(":");r&&(e.group={by:r,...Gp.includes(o)?{bucket:o}:{}})}return e}function Ei(n){if(typeof n=="string"&&n.length>0)return{by:n,direction:"asc"};if(typeof n!="object"||n===null)return;let{by:e,direction:t}=n;if(!(typeof e!="string"||e.length===0))return{by:e,direction:t==="desc"?"desc":"asc"}}function $r(n,e,t){let r=Ei(n);if(!r)return'an order is a field, like "released", or { "by": "released", "direction": "asc" | "desc" }';let o=typeof n=="object"&&n!==null?n.direction:void 0;if(o!==void 0&&o!=="asc"&&o!=="desc")return`an order runs "asc" or "desc", not "${String(o)}"`;if(r.by!=="label"&&!e.includes(r.by))return`${t} has no field "${r.by}" to order by (it has ${e.length>0?e.map(i=>`"${i}"`).join(", "):"none"}, and "label", its name)`}function Kp(n,e,t){let r=Ei(e);if(!r)return n;let o=r.direction==="desc"?-1:1;return n.map((i,s)=>({item:i,at:s,value:t(i,r.by)})).sort((i,s)=>{let a=(i.value===void 0||i.value===null||i.value===""?1:0)-(s.value===void 0||s.value===null||s.value===""?1:0);if(a!==0)return a;if(i.value===s.value||i.value===void 0||i.value===null)return i.at-s.at;let d=typeof i.value=="number"&&typeof s.value=="number"?i.value-s.value:String(i.value).localeCompare(String(s.value),void 0,{numeric:!0});return d===0?i.at-s.at:d*o}).map(i=>i.item)}var Mt={timeline:{binds:"fields",requiredRoles:["start","end"],options:["columns","extent","tick","minWindow","arranging"]},calendar:{binds:"fields",requiredRoles:["start"],options:["today","range","weekStartsOn","perCell","horizon","arranging","search","filters"]},coverage:{binds:"entities",requiredRoles:["rows","columns","link"],options:["rowRef","rowGroup","groupOrder","requiredGroups","requiredVia","badge","columnGroup","sort","columnSort","search","filters"]},board:{binds:"entities",requiredRoles:["slots","x","y","fill"],options:["fillFrom","slotCode","zones","aspect","emptyLabel","pickTarget","arranging","arrange"]},plan:{binds:"entities",requiredRoles:["regions","outline"],options:["hues","aspect","undrawnLabel","strayLabel","draw","place","help"]},reach:{binds:"nothing",requiredRoles:[],options:[]},blocks:{binds:"nothing",requiredRoles:[],options:["blocks"]},columns:{binds:"fields",requiredRoles:["column"],options:["sort","search","filters","move","collapsed","cap","hidden"]}},Vp=["start","end"],Bp=20,Zc=Object.keys(Mt),Up=(n,e,t,r=Mt[n].options)=>({message:`The ${n} lens takes no option "${e}", so "${t}" ignores it.`,fix:r.length?`Use one of: ${r.join(", ")}.`:`The ${n} lens takes no options; drop it.`}),Gc=n=>Object.hasOwn(Mt,n);function Mi(n,e,t){let r=n[e],o=Array.isArray(r)?r.filter(i=>typeof i=="string"&&t(i)):[];o.length>0?n[e]=o:delete n[e]}var Vn=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function Wp(n,e,t){let r=n.tryDefinition(e)?.fields.shape,o=L(r?.[t]);for(;o&&(o.type==="optional"||o.type==="default"||o.type==="nullable"||o.type==="prefault");)o=L(o.innerType);return o?.type==="number"}var Lc=(n,e="start",t="end")=>`A timeline lays out spans by number \u2014 minutes of a day, 0 to 1440 \u2014 across columns: "bindings": { "${n}": { "start": "<a number field>", "end": "<a number field>", "column": "<a choice field, like a weekday>" } }, or "options": { "columns": ["mon", "tue", \u2026] }. For spans of dates, draw a calendar: "lens": "calendar", "bindings": { "${n}": { "start": "${e}", "end": "${t}" } }, "options": { "range": "month" }.`;function Cc(n,e,t){let r=n.tryDefinition(e)?.fields.shape,o=L(r?.[t]);for(;o&&(o.type==="optional"||o.type==="default"||o.type==="nullable"||o.type==="prefault");)o=L(o.innerType);return o?.type!=="enum"?[]:(o.entries?Object.values(o.entries):o.values??[]).filter(s=>typeof s=="string")}function qp(n){let e=[],t=[],r=[],o=new Set(n.schema.kinds),i=new Set;for(let d of o)for(let l of Object.keys(n.schema.tryDefinition(d)?.edges??{}))i.add(l);let s=d=>Object.keys(n.schema.tryDefinition(d)?.fields.shape??{}),a=new Map;return(n.lenses??[]).forEach((d,l)=>{let u=`lenses.${l}`,p=typeof d.title=="string"&&d.title.trim().length>0?d.title.trim():void 0,c=(m,v)=>{t.push({index:l,name:d.name,...p?{title:p}:{},why:m}),v&&r.push({severity:"warning",...v})};if(!Gc(d.name)){p?c(`"${d.name}" is not a lens this framework draws`,{code:"lens-not-shipped",path:`${u}.name`,message:`"${p}" names the lens "${d.name}", which the framework does not ship, so nothing draws it.`,fix:`Name one of ${Zc.join(", ")} \u2014 or register the view yourself and drop the title.`}):c("it is a lens this app wrote, drawn by the app's own views");return}if(!p)return c("it has no title, so it is bindings the checker holds and no place");let f=Mt[d.name],g=Vn(d.options)?d.options:{};if(d.options!==void 0&&!Vn(d.options))return c("its options are not an object",{code:"lens-options-not-an-object",path:`${u}.options`,message:`"${p}" has options that are not an object.`,fix:'Write them as { "<option>": <value> }, or drop them.'});for(let m of Object.keys(g))f.options.includes(m)||r.push({severity:"warning",code:"lens-option-unknown",path:`${u}.options.${m}`,...Up(d.name,m,p,f.options)});let h={};for(let m of f.options)g[m]!==void 0&&(h[m]=g[m]);d.arrangedBy&&(h.arrangedBy=Fc(d.arrangedBy));let y=Vn(d.bindings)?d.bindings:{},b=[],x,$=(m,v,R)=>c(v,{code:"lens-cannot-draw",path:m,message:`"${p}" cannot draw: ${v}.`,fix:R});if(f.binds==="fields"){let m=Object.keys(y).filter(R=>Vn(y[R])),v=m.filter(R=>!o.has(R));if(m.length===0)return $(`${u}.bindings`,"it binds no kind",`Bind a kind's fields: "bindings": { "<kind>": { ${f.requiredRoles.map(R=>`"${R}": "<field>"`).join(", ")} } }.`);if(v.length>0)return;if(h.bindings=y,b=m,d.name==="timeline"){for(let S of m){let k=y[S];for(let _ of Vp){let P=k[_];if(!(typeof P!="string"||!s(S).includes(P))&&!Wp(n.schema,S,P))return $(`${u}.bindings.${S}.${_}`,`its ${_} "${P}" is not a number, and a timeline's axis is`,Lc(S,String(k.start??"start"),String(k.end??"end")))}}let R=g.columns;if(Array.isArray(R))h.columns=R.map(S=>typeof S=="string"?{id:S,label:S}:S);else{let S=m.flatMap(_=>{let P=y[_],M=typeof P.column=="string"?P.column:typeof P.columns=="string"?P.columns:void 0;return M?Cc(n.schema,_,M):[]}),k=[...new Set(S)];if(k.length===0)return $(`${u}.options.columns`,"it has no columns \u2014 no option names them and no `column` role is bound to a field of set values",Lc(m[0]));h.columns=k.map(_=>({id:_,label:_.toUpperCase()}))}h.extent===void 0&&(h.extent=1440)}if(d.name==="columns"){if(h.sort!==void 0){let S=m.map(k=>$r(h.sort,s(k),k)).find(Boolean);S&&(r.push({severity:"warning",code:"lens-sort",path:`${u}.options.sort`,message:`"${p}" cannot order its cards: ${S}.`,fix:'Write { "by": "<a field>", "direction": "asc" }, or drop it.'}),delete h.sort)}let R=new Set;for(let S of m){let k=y[S].column;if(typeof k!="string"||!s(S).includes(k))return;let _=Cc(n.schema,S,k);if(_.length===0)return $(`${u}.bindings.${S}.column`,`its column field "${k}" is not a choice`,`Bind "column" to a choice field of ${S}, like a status.`);for(let P of _)R.add(P)}typeof h.move!="boolean"&&delete h.move,Number.isInteger(h.cap)&&h.cap>=1&&h.cap<=500||delete h.cap;for(let S of["collapsed","hidden"])Mi(h,S,k=>R.has(k))}if(d.name==="calendar"&&h.today!==void 0&&!(typeof h.today=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(h.today)))return $(`${u}.options.today`,"its today is not a date",'Write it as "YYYY-MM-DD", or leave it out and the calendar opens on the day it is drawn.');if(d.name==="calendar"&&h.horizon!==void 0){let R=h.horizon,S=P=>P===void 0||Number.isInteger(P)&&P>=1&&P<=9999,k=typeof R=="number"?{years:R,title:"Years"}:R;Vn(k)&&Number.isInteger(k.years)&&k.years>=1&&k.years<=200&&typeof k.title=="string"&&k.title.trim().length>0&&S(k.from)&&S(k.to)&&Object.keys(k).every(P=>["years","title","from","to"].includes(P))&&!(typeof k.from=="number"&&typeof k.to=="number"&&k.to<k.from)?h.horizon=k:(delete h.horizon,r.push({severity:"warning",code:"lens-horizon",path:`${u}.options.horizon`,message:`"${p}" has a horizon that is not a span of years, so it offers no span of years.`,fix:'Write { "years": 30, "title": "The career" } \u2014 "from" and "to" (years, like 1962 and 2023) only to pin its ends, which otherwise reach the first and last of its records.'}))}if(d.name==="calendar"&&h.range!==void 0&&!["day","week","month","quarter","year","years","agenda"].includes(h.range))return $(`${u}.options.range`,`its range "${String(h.range)}" is not one a calendar opens at`,"Use one of: day, week, month, quarter, year, agenda.")}else if(f.binds==="entities"){let m=S=>{let k=y[S];if(Vn(k)){if(typeof k.kind=="string")return k.kind;if(typeof k.edge=="string")return k.edge;if(Array.isArray(k.path))return{path:k.path};if(typeof k.field=="string")return k.field}};for(let S of f.requiredRoles)if(m(S)===void 0)return;let v=d.name==="coverage"?"rows":d.name==="board"?"slots":"regions",R=m(v);if(!o.has(R))return;if(d.name==="coverage"){let S=m("columns");if(!o.has(S))return;let k=m("link");if(typeof k=="string"&&!i.has(k))return;Object.assign(h,{rows:R,columns:S,link:k}),S!==R&&(x=S);for(let[_,P]of[["sort",R],["columnSort",S]]){if(h[_]===void 0)continue;let M=$r(h[_],s(P),P);M&&(r.push({severity:"warning",code:"lens-sort",path:`${u}.options.${_}`,message:`"${p}" cannot order its ${_==="sort"?"rows":"columns"}: ${M}.`,fix:`Write { "by": "<a field of ${P}>", "direction": "asc" }, or drop it.`}),delete h[_])}}else if(d.name==="board"){Object.assign(h,{slots:R,x:m("x"),y:m("y"),fill:m("fill")});for(let S of["x","y"])if(!s(R).includes(h[S]))return}else{Object.assign(h,{regions:R,outline:m("outline")});for(let S of["markers","at","within","nests","regionKind","markerKind"]){let k=m(S);typeof k=="string"&&(h[S]=k)}}b=[R]}else if(d.name==="blocks"){if(!d.on)return $(`${u}.on`,"it does not say which kind it stands on",'Say "on": "<the kind it is a place of>".');if(!Array.isArray(h.blocks)||h.blocks.length===0)return $(`${u}.options.blocks`,"it has no blocks to draw",`Say "options": { "blocks": [{ "headline": "\u2026" }, { "list": "all('<kind>')", "as": "card" }] }.`)}else{let m=["user","person","member"].find(v=>o.has(v));if(!d.on&&!m)return $(`${u}.on`,"it does not say which kind it stands on",'Say "on": "<the kind whose records are the people>".');b=m?[m]:[]}if(d.on!==void 0){if(typeof d.on!="string"||!o.has(d.on))return $(`${u}.on`,`it stands on "${String(d.on)}", which is not a kind`,`Use one of: ${[...o].join(", ")}.`);if(b=[d.on],d.name==="coverage"){let m=[h.rows,h.columns].find(v=>v!==d.on);x=typeof m=="string"?m:void 0}}let w=typeof h.rows=="string"?h.rows:b[0];if(w!==void 0){let m=["label",...s(w)],v=new Set(["is",...m,...Object.keys(n.schema.tryDefinition(w)?.edges??{})]);Mi(h,"search",R=>m.includes(R)),Mi(h,"filters",R=>v.has(R.split(".")[0]))}let O=Ee(p);if(O.length===0)return $(`${u}.title`,"its title has no letters or digits to make an address of","Give it a title a person would say.");for(let m of b){let v=`${m}|${O}`;if(a.has(v))return c(`another lens on ${m} is already called "${p}"`,{code:"lens-title-taken",path:`${u}.title`,message:`"${p}" is the title of lenses.${a.get(v)} too, on the same kind, so one address would name two pictures.`,fix:"Give each its own title."})}for(let m of b)a.set(`${m}|${O}`,l);let A=d.create;A!==void 0&&typeof A!="boolean"&&r.push({severity:"warning",code:"lens-create",path:`${u}.create`,message:`"${p}" says create ${JSON.stringify(A)}, which is neither true nor false, so its page keeps the forms that begin its kind.`,fix:'Say "create": false to leave them off, or drop it.'}),e.push({index:l,lens:d.name,title:p,as:O,kinds:b,...x?{across:x}:{},options:h,...d.hidden===!0?{hidden:!0}:{},...A===!1?{create:!1}:{}})}),{drawn:e,undrawn:t,findings:r}}var Hp=6;function Jp(n,e,t=[]){let r=n.kinds,o=s=>Object.values(n.tryDefinition(s)?.edges??{}).map(a=>(a.to==="*"?r:a.to).filter(d=>d!==s)),i=new Set(r.flatMap(s=>o(s).flat()));return new Set([...e?.hide??[],...t,...r.filter(s=>!i.has(s)&&o(s).length>0&&o(s).every(a=>a.length>=2))])}function Yp(n,e,t){if(!n?.primary)return;let r=new Set(n.primary.map(Ee));return{kinds:new Set(e.kinds.filter(o=>r.has(Ee(o))||r.has(Et(e,o).slice(1)))),places:new Set(t.filter(o=>r.has(o.as)||r.has(Ee(o.title))||o.name!==void 0&&n.primary.includes(Pt+o.name)).map(o=>`${o.kind}|${o.as}`))}}var Xp="home",Kc="overview",Qp=`/places/${Kc}`;function eh(n){let e=n?.scene?.trim();return e||"Scene"}function nh(n){let e=n?.pages?.trim();return e||"Pages"}function th(n,e){if(!e||e.length===0)return n;let t=e.filter(r=>n.includes(r));return[...new Set(t),...n.filter(r=>!t.includes(r))]}function Vc(n){return n.startsWith(Pt)&&n.slice(Pt.length).trim()||void 0}function rh(n,e,t){let r=[],o=new Set;for(let i of e??[]){let s=Vc(i),a=s===void 0?void 0:t.find(d=>d.name===s&&n.includes(d.kind));a?r.some(d=>d.view===a)||r.push({kind:a.kind,view:a}):s===void 0&&n.includes(i)&&!o.has(i)&&(o.add(i),r.push({kind:i}))}for(let i of n)o.has(i)||r.push({kind:i});return r}function oh(n,e,t){if(n===void 0)return;let r=n.trim();if(r==="")return;if(r.toLowerCase()==="home"||r==="/")return{to:"home"};let o=Ee(r),i=t.find(d=>d.title===r||Pt+d.name===r)??t.find(d=>d.as===o);if(i)return{to:"place",place:i};let s=e.kinds,a=s.find(d=>d===r)??s.find(d=>Et(e,d).slice(1)===o);return a?{to:"kind",kind:a}:void 0}function Ni(n){let e=(n??"").replace(/\/+$/,"");return e===""?"":e.startsWith("/")?e:`/${e}`}function ih(n,e={}){let t=typeof n=="string"?n:n.address,r=Ni(e.basePath),o=t.startsWith("/")?t:`/${t}`;return r===""?o:o==="/"?r:o.startsWith("/?")||o.startsWith("/#")?`${r}${o.slice(1)}`:`${r}${o}`}function sh(n,e){let t=Ni(e);if(t==="")return n.startsWith("/")?n:`/${n}`;if(!n.toLowerCase().startsWith(t.toLowerCase()))return null;let r=n.slice(t.length);return r===""||r==="/"?"/":r.startsWith("/")?r:null}var Ar=2500,ah=Ar*4;function dh(n){let e=n.name??"";return e&&n.onBehalfOfName?`${e}, for ${n.onBehalfOfName}`:e}function zi(n,e,t=Ar){return n.held==="socket"?!0:n.until!==void 0?e<Date.parse(n.until):e-Date.parse(n.at)<t}var f0=new Set(Xt);function ch(n){return`${n.kind}:${n.id??""}:${n.session??""}`}function uh(n,e,t,r=Ar,o){let i=new Map;for(let[s,a]of n)zi(a,t,r)&&i.set(s,a);for(let s of e){if(!zi(s,t,r)){i.delete(s.participant);continue}let a=i.get(s.participant);(!a||Date.parse(a.at)<=Date.parse(s.at))&&i.set(s.participant,s)}return o!==void 0&&i.delete(o),i}function lh(n,e){return!n||!e?n===e:n.participant===e.participant&&n.kind===e.kind&&n.name===e.name&&n.onBehalfOf===e.onBehalfOf&&n.onBehalfOfName===e.onBehalfOfName&&n.until===e.until&&n.held===e.held&&n.hue===e.hue&&n.stop===e.stop&&(n.over??null)===(e.over??null)&&(n.robot?.at??null)===(e.robot?.at??null)&&(n.robot?.mode??null)===(e.robot?.mode??null)&&JSON.stringify(n.caret)===JSON.stringify(e.caret)}var Bc=Symbol.for("@graview/core:app-link"),fh=n=>(Object.defineProperty(L(n),Bc,{value:1,enumerable:!0}),n);function Uc(n){let e=L(n);return!!e&&(e[Bc]===1||Uc(e.innerType))}var m0=()=>fh(F().check(yo(500),rt(qt,"another app's address")));var Or=(n,e)=>`${e.kind}\0${e.id??""}\0${n.address}\0${n.kind}\0${n.id}`;function ph(n,e,t=()=>{}){let r=new Map,o=new Map,i=s=>{let a=Or(s,e),d=r.get(a);return d||(d=Promise.resolve().then(()=>n.resolve(s,e)).then(l=>hh(l)?l:null,()=>null).then(l=>(r.get(a)===d&&(o.set(a,l),t(s)),l)),r.set(a,d)),d};return{read(s){let a=Or(s,e);if(o.has(a)){let d=o.get(a);return d===null?{unread:!0}:"denied"in d?{denied:!0}:{record:d}}return i(s),{unread:!0}},ask:i,answered:s=>o.get(Or(s,e)),forget(s){if(!s){r.clear(),o.clear();return}let a=Or(s,e);r.delete(a),o.delete(a)}}}function hh(n){if(n===null)return!0;if(typeof n!="object"||n===void 0)return!1;if(n.denied===!0)return!0;let e=n;return typeof e.label=="string"&&typeof e.id=="string"&&typeof e.kind=="string"&&typeof e.fields=="object"&&e.fields!==null}var gh=1;var _r=(n,e)=>`${n}\0${e}`;function Ti(n){return n.op==="add-node"?Object.keys(n.node).filter(e=>e!=="id"&&e!=="kind").map(e=>[n.node.id,e]):n.op==="patch-node"?Object.keys(n.after).map(e=>[n.id,e]):n.op==="splice-text"?[[n.id,n.field]]:[]}var Ii=class n{revs=new Map;floor;constructor(e=0){this.floor=Math.max(0,Math.floor(e))-1}static of(e,t={}){let r=new n(t.horizon);return r.note(e),r}note(e){for(let t of e)for(let r of t.primitives)for(let[o,i]of Ti(r)){let s=_r(o,i);(this.revs.get(s)??this.floor)<t.seq&&this.revs.set(s,t.seq)}}of(e,t){return this.revs.get(_r(e,t))??this.floor}baseFor(e,t=new Set,r){let o=new Set,i=new Map;for(let s of e)for(let a of s.primitives)if(a.op==="add-node"&&o.add(a.node.id),!(a.op!=="patch-node"||o.has(a.id)||t.has(a.id)))for(let d of Object.keys(a.after)){let l=_r(a.id,d);t.has(l)||i.has(l)||r?.(a.id,d)||i.set(l,{node:a.id,field:d,rev:this.of(a.id,d)})}return[...i.values()]}stale(e){return e.filter(t=>this.of(t.node,t.field)>t.rev)}};function mh(n){let e=new Set;for(let t of n)for(let r of t.primitives){r.op==="add-node"&&e.add(r.node.id);for(let[o,i]of Ti(r))e.add(_r(o,i))}return e}var x0=Symbol.for("@graview/core:collaborative"),S0=n=>typeof n=="object"&&n!==null?n._zod?.def:void 0;var yh=/^#([0-9a-f]{3,8})$/i,bh=/(rgba?|hsla?)\(([^)]+)\)/gi;function vh(n){let e=yh.exec(n.trim());if(!e)return null;let t=e[1];if((t.length===3||t.length===4)&&(t=[...t].map(i=>i+i).join("")),t.length!==6&&t.length!==8)return null;let r=Number.parseInt(t.slice(0,6),16),o=t.length===8?Number.parseInt(t.slice(6,8),16)/255:1;return{r:r>>16&255,g:r>>8&255,b:r&255,a:o}}function wh(n){let e=n.slice(0,n.indexOf("(")).toLowerCase(),r=n.slice(n.indexOf("(")+1,n.lastIndexOf(")")).split(/[,\s/]+/).filter(Boolean).map(d=>d.endsWith("%")?Number.parseFloat(d)/100:Number.parseFloat(d));if(r.some(Number.isNaN))return null;if(e.startsWith("rgb")){let[d,l,u,p]=r;return d===void 0||l===void 0||u===void 0?null:{r:d,g:l,b:u,a:p??1}}let[o,i,s,a]=r;return o===void 0||i===void 0||s===void 0?null:{...qc(o,i>1?i/100:i,s>1?s/100:s),a:a??1}}function pn(n){let e=n.r/255,t=n.g/255,r=n.b/255,o=Math.max(e,t,r),i=Math.min(e,t,r),s=(o+i)/2;if(o===i)return{h:0,s:0,l:s};let a=o-i,d=a/(1-Math.abs(2*s-1));return{h:((o===e?60*((t-r)/a%6):o===t?60*((r-e)/a+2):60*((e-t)/a+4))+360)%360,s:d,l:s}}function Me(n,e,t){return{...qc(n,e,t),a:1}}function qc(n,e,t){let r=(1-Math.abs(2*t-1))*e,o=(n%360+360)%360/60,i=r*(1-Math.abs(o%2-1)),[s,a,d]=o<1?[r,i,0]:o<2?[i,r,0]:o<3?[0,r,i]:o<4?[0,i,r]:o<5?[i,0,r]:[r,0,i],l=t-r/2;return{r:Math.round((s+l)*255),g:Math.round((a+l)*255),b:Math.round((d+l)*255)}}function Y(n){let e=[];for(let t of n.matchAll(bh)){let r=wh(t[0]);r&&e.push(r)}for(let t of n.matchAll(/#[0-9a-fA-F]{3,8}\b/g)){let r=vh(t[0]);r&&e.push(r)}return e}function hn(n,e){let t=n.a+e.a*(1-n.a);if(t===0)return{r:0,g:0,b:0,a:0};let r=(o,i)=>(o*n.a+i*e.a*(1-n.a))/t;return{r:r(n.r,e.r),g:r(n.g,e.g),b:r(n.b,e.b),a:t}}function ji(n){let e=n/255;return e<=.03928?e/12.92:((e+.055)/1.055)**2.4}function Wc(n){return .2126*ji(n.r)+.7152*ji(n.g)+.0722*ji(n.b)}function ke(n,e){let[t,r]=[Wc(n),Wc(e)].sort((o,i)=>i-o);return(t+.05)/(r+.05)}function Pr(n){return ke({r:255,g:255,b:255,a:1},n)>ke({r:0,g:0,b:0,a:1},n)}var Er=(n,e)=>`rgba(${Math.round(n.r)}, ${Math.round(n.g)}, ${Math.round(n.b)}, ${e})`,Hc={r:0,g:0,b:0,a:1},Mr={r:255,g:255,b:255,a:1};function Nr(n){let e=Y(n.accent)[0];if(!e)return{ok:!1,missing:["accent"],why:`"${n.accent}" is not a color this can read. Use a hex, rgb() or hsl() value.`};let t={},r=new Set,o=[],i=pn(e);for(let s of["dark","light"]){let a=n.base[s],d=Y(a.ground)[0]??(s==="dark"?Hc:Mr),l=hn(Y(a.panel)[0]??Mr,d),u=Sh(i,[l,d],s,4.5);u?Math.abs(u.l-i.l)>xh&&(r.add(`accent (${s})`),o.push(`reaching 4.5:1 on the ${s} panel would move the accent's lightness by ${Math.round(Math.abs(u.l-i.l)*100)} points, which is far enough that it stops being the same color \u2014 supply one for ${s}`)):(r.add(`accent (${s})`),o.push(`no lightness of this hue clears 4.5:1 as text on the ${s} panel, so ${s} needs an accent of its own`));let p=u??i,c=Me(p.h,p.s,p.l),f=n.accentInk?.[s]??(ke(Mr,c)>=ke(Hc,c)?"#ffffff":"#000000"),g=ke(Y(f)[0]??Mr,c);g+.005<4.5&&(r.add(`accentInk (${s})`),o.push(`neither black nor white clears 4.5:1 on the accent (best ${g.toFixed(2)}:1), so text on a filled button has to be given`)),t[s]={...a,accent:Er(c,1),accentDim:Er(c,s==="dark"?.35:.22),accentInk:f,glow:Er(c,s==="dark"?.28:.1),edgeBright:Er(c,Di(c,l,s==="dark"?.55:.42,3)),...n.warn?.[s]?{warn:n.warn[s]}:{}};let h=Y(t[s].warn)[0];h&&kh(pn(h).h,p.h)<25&&(r.add(`warn (${s})`),o.push(`the warning color shares the accent's hue in ${s}, so "something is broken" looks like "this is selected"`))}return r.size>0?{ok:!1,missing:[...r].sort(),why:o.join("; ")}:{ok:!0,schemes:t}}function Di(n,e,t,r){for(let o=Math.round(t*100);o<=100;o++){let i=o/100;if(ke(hn({...n,a:i},e),e)>=r)return i}return 1}function kh(n,e){let t=Math.abs(n-e)%360;return t>180?360-t:t}var xh=.3;function Sh(n,e,t,r){let o=t==="dark";for(let i=0;i<=100;i++){let s=o?n.l+i/100:n.l-i/100,a=o?n.l-i/100:n.l+i/100;for(let d of[s,a])if(!(d<0||d>1)&&e.every(l=>ke(Me(n.h,n.s,d),l)>=r))return{...n,l:d}}return null}function Rh(n,e){let t=e?.[n];if(t!==void 0)return(t%360+360)%360;let r=2166136261;for(let o=0;o<n.length;o++)r^=n.charCodeAt(o),r=Math.imul(r,16777619);return(r>>>0)%360}var gn=Object.freeze({navy:"#001769",turquoise:"#00e5b9",paper:"#f7f7f2",ink:"#18213a",muted:"#586174"}),Fi="Montserrat",Li=Object.freeze({display:550,body:450,label:600}),Ci=Object.freeze({display:600,body:400,label:600}),$h="-0.025em",Ah=Object.freeze({minWidth:140,clearSpace:.5,microMax:24,regularMin:32,microBelow:28});var Jc={ground:"#0a0f1f",groundDeep:"#060914",wash:"none",panel:"rgba(19, 27, 52, 0.96)",panelMuted:"rgba(14, 21, 42, 0.94)",panelWarning:"rgba(48, 33, 18, 0.95)",edge:"rgba(164, 178, 222, 0.18)",edgeBright:"rgba(154, 171, 255, 0.6)",ink:"#eef0f6",inkMuted:"#aab2c6",inkFaint:"#97a0b6",accent:"#9aabff",accentDim:"rgba(154, 171, 255, 0.32)",accentInk:gn.navy,warn:"#f0a868",good:"#8fdcaa",bad:"#ffa3a3",glow:"rgba(154, 171, 255, 0.18)",bar:"rgba(10, 15, 31, 0.96)",float:"rgba(16, 23, 45, 0.98)",liftLow:"0 14px 36px -22px #000",liftHigh:"0 28px 64px -30px #000",tintAlpha:.2,tintLightness:52,gridAlpha:.35},Yc={ground:gn.paper,groundDeep:"#efefe8",wash:"none",panel:"#ffffff",panelMuted:"#fafaf6",panelWarning:"#fdf4ea",edge:"rgba(24, 33, 58, 0.12)",edgeBright:"rgba(0, 23, 105, 0.6)",ink:gn.ink,inkMuted:gn.muted,inkFaint:"#626b7d",accent:gn.navy,accentDim:"rgba(0, 23, 105, 0.16)",accentInk:"#ffffff",warn:"#9a5312",good:"#1b6436",bad:"#a1232d",glow:"rgba(0, 23, 105, 0.08)",bar:"rgba(255, 255, 255, 0.96)",float:"#ffffff",liftLow:"0 1px 2px rgba(24,33,58,0.06), 0 8px 24px -12px rgba(24,33,58,0.16)",liftHigh:"0 2px 6px rgba(24,33,58,0.08), 0 24px 56px -24px rgba(24,33,58,0.26)",tintAlpha:.16,tintLightness:46,gridAlpha:.5},Ve={dark:Jc,light:Yc};var Be=Object.freeze({radius:8,density:1,radiusSmall:.72,radiusSmallFloor:2,pad:15,padSmall:10,gap:7}),mn=Object.freeze({body:`"${Fi}", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif`,mono:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace'});function Oh(n){let e=n?.shape?.radius??Be.radius,t=n?.shape?.density??Be.density;return Object.freeze({radius:e,radiusSmall:Math.max(Be.radiusSmallFloor,Math.round(e*Be.radiusSmall)),pad:Math.round(Be.pad*t),padSmall:Math.round(Be.padSmall*t),gap:Math.round(Be.gap*t)})}function _h(n){let e=n?.typography?.body??mn.body,t=n?.typography?.display??e,o=e===mn.body&&t===mn.body?Li:Ci,i=n?.typography?.weights;return Object.freeze({body:e,display:t,mono:n?.typography?.mono??mn.mono,weights:Object.freeze({display:i?.display??o.display,body:i?.body??o.body,label:i?.label??o.label})})}var z0=Object.freeze({light:Object.freeze({roof:Object.freeze({saturation:48,lightness:82}),right:Object.freeze({saturation:40,lightness:66}),left:Object.freeze({saturation:34,lightness:55}),roofEdge:"rgba(255,255,255,0.75)",plot:Object.freeze({saturation:45,lightness:58,alpha:.12}),plotEdge:Object.freeze({saturation:40,lightness:48,alpha:.55})}),dark:Object.freeze({roof:Object.freeze({saturation:42,lightness:32}),right:Object.freeze({saturation:40,lightness:21}),left:Object.freeze({saturation:38,lightness:13}),roofEdge:"rgba(255,255,255,0.14)",plot:Object.freeze({saturation:45,lightness:48,alpha:.2}),plotEdge:Object.freeze({saturation:40,lightness:62,alpha:.55})})});var Ph=64*1024;function Qc(n){return/^\s*(<\?xml[^>]*>\s*)?(<!--[\s\S]*?-->\s*)*(<!DOCTYPE svg[^>]*>\s*)?<svg[\s>/]/i.test(n)}var eu="http://www.w3.org/2000/svg",Eh=["http://www.w3.org/1999/xhtml","http://www.w3.org/1998/Math/MathML",eu],Mh=new Set("svg g defs symbol use title desc path rect circle ellipse line polyline polygon text tspan textPath linearGradient radialGradient stop pattern clipPath mask marker image filter feBlend feColorMatrix feComponentTransfer feComposite feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feMerge feMergeNode feMorphology feOffset feTile feTurbulence".split(" ")),Nh=new Set(["title","desc"]),Nt="it embeds a page or media",zh={script:"it has a script in it",foreignobject:"it embeds HTML (foreignObject)",iframe:Nt,embed:Nt,object:Nt,audio:Nt,video:Nt,style:"it has a style sheet in it; a mark is styled by its attributes",a:"it links to something (an <a> element)"},Ih={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function Th(n){let e=!1,t=n.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z][a-z0-9]*);?/gi,(r,o)=>{if(o[0]==="#"){let s=o[1]==="x"||o[1]==="X"?parseInt(o.slice(2),16):parseInt(o.slice(1),10);return s>0&&s<=1114111?String.fromCodePoint(s):"\uFFFD"}let i=Ih[o.toLowerCase()];return i===void 0&&(e=!0),i??""});return e?null:t}function jh(n){if(/\\|@|expression\s*\(|(?:image-set|cross-fade|image|element|src)\s*\(/i.test(n))return!1;for(let[,e]of n.matchAll(/url\s*\(\s*["']?\s*([^)]*)/gi))if(!e.startsWith("#"))return!1;return!0}function Dh(n,e,t){let r=Th(t);if(r===null)return"it declares XML entities";let o=(e.includes(":")?e.slice(e.indexOf(":")+1):e).toLowerCase();if(o.startsWith("on"))return"it has an event handler (an on\u2026 attribute)";if(e==="xml:base")return"it loads or links to something outside itself";if(e==="xmlns")return r===eu?null:"it changes what its elements are (another xmlns)";if(e.startsWith("xmlns:"))return Eh.includes(r)?"it changes what its elements are (another xmlns)":null;if(o==="href"||o==="src"){let i=r.replace(/[\u0000- ]+/g,"");return i.startsWith("#")||n==="image"&&/^data:image\/(png|jpe?g|gif|webp|avif);/i.test(i)?null:"it loads or links to something outside itself"}return jh(r)?null:o==="style"?"its style loads something outside itself":"it loads or links to something outside itself"}var Xc=/^\s+([A-Za-z_][A-Za-z0-9_.:-]*)\s*=\s*(?:"([^"<]*)"|'([^'<]*)')/;function nu(n){if(/<!ENTITY/i.test(n))return"it declares XML entities";if(/<!\[CDATA\[/i.test(n))return"it has a CDATA section, which the page and the picture read differently";let e=[],t=!1,r=/^\s*(<\?xml\s[^?<>]*\?>)?/.exec(n)[0].length;for(;r<n.length;){let o=n.slice(r),i=/^[^<]+/.exec(o);if(i){if(e.length===0&&i[0].trim()!=="")return"it is not one SVG: there is text outside it";r+=i[0].length;continue}if(o.startsWith("<!--")){let f=o.indexOf("-->",4);if(f<0)return"it has a comment that never ends";let g=o.slice(4,f);if(/^-?>/.test(g)||g.includes("--")||g.includes("<!")||g.endsWith("-"))return"it has a comment the page and the picture read differently";r+=f+3;continue}if(/^<!DOCTYPE/i.test(o)){let f=/^<!DOCTYPE\s+svg\b[^<>[\]]*>/i.exec(o);if(!f||e.length>0||t)return"it declares XML entities";r+=f[0].length;continue}let s=/^<\/([A-Za-z][A-Za-z0-9_.:-]*)\s*>/.exec(o);if(s){if(e.pop()!==s[1])return`it is not one SVG: </${s[1]}> closes what is not open`;e.length===0&&(t=!0),r+=s[0].length;continue}let a=/^<([A-Za-z][A-Za-z0-9_.:-]*)/.exec(o);if(!a)return"it is not one SVG: it has markup a picture cannot hold";let d=a[1],l=zh[d.toLowerCase()];if(l)return l;if(t)return`it is not one SVG: <${d}> comes after it ends`;if(e.length===0&&d!=="svg")return"it is not one SVG";if(d.includes(":"))return`it has an element of another kind (<${d}>)`;if(!Mh.has(d))return`it has a <${d}> element, which a picture does not need`;let u=e[e.length-1];if(u&&Nh.has(u))return`it has an element inside a <${u}>, which the page reads as HTML`;let p=a[0].length;for(let f=Xc.exec(o.slice(p));f;f=Xc.exec(o.slice(p))){let g=Dh(d,f[1],f[2]??f[3]??"");if(g)return g;p+=f[0].length}let c=/^\s*(\/?)>/.exec(o.slice(p));if(!c)return/(?:^|[\s/"'])on[a-z]+\s*=/i.test(o.slice(p,p+400))?"it has an event handler (an on\u2026 attribute)":`it is not one SVG: <${d}>'s attributes are not each quoted and apart`;c[1]!=="/"?e.push(d):e.length===0&&(t=!0),r+=p+c[0].length}return e.length>0?`it is not one SVG: <${e[e.length-1]}> is never closed`:t?null:"it is not one SVG"}function tu(n){if(n){if(!Qc(n)){if(/^\s*</.test(n))return;let e=/^\s*([a-z][a-z0-9+.-]*):/i.exec(n)?.[1]?.toLowerCase();return e===void 0||e==="http"||e==="https"||e==="data"&&/^\s*data:image\//i.test(n)?n:void 0}return nu(n)===null?`data:image/svg+xml,${encodeURIComponent(n.trim())}`:void 0}}var zr;function Fh(){if(zr===void 0)try{zr=new RegExp("^\\p{RGI_Emoji}$","v")}catch{zr=null}return zr}function Lh(n){return/\p{Extended_Pictographic}|\p{Regional_Indicator}|⃣/u.test(n)}function Zi(n){if(typeof n!="string"||n.trim()==="")return"it is empty; give one emoji, like \u{1F3E1}";let e=[...new Intl.Segmenter("en",{granularity:"grapheme"}).segment(n)].map(o=>o.segment),t=e.filter(Lh).length;if(t===0)return"it is not an emoji; give one emoji, like \u{1F3E1}";if(e.length>1)return t===e.length?`it is ${e.length} emoji, and a mark is one`:"it has other characters beside the emoji; give the emoji alone";let r=Fh();return r&&!r.test(n)?"it is not one of the standard emoji every emoji set draws":null}function Gi(n){return typeof n=="object"&&n!==null&&typeof n.emoji=="string"?n.emoji:void 0}function ru(n){return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text x="50" y="50" dy=".35em" font-size="88" text-anchor="middle">${n}</text></svg>`}function Ch(n){let e=n?.favicon;if(typeof e=="object"&&e!==null){let t=Gi(e);return t!==void 0&&Zi(t)===null?`data:image/svg+xml,${encodeURIComponent(ru(t))}`:void 0}return tu(e)}function Zh(n){let e=n?.logo;return typeof e=="string"?e===""?void 0:{light:e}:e&&typeof e.light=="string"&&e.light!==""?e:void 0}function Gh(n,e){if(e==="dark")return"dark";let t=n?.schemes?.light?.ground,r=t?Y(t)[0]:void 0;return r&&Pr(r)?"dark":"light"}function Kh(n){if(n?.logo)return;let e=Gi(n?.favicon);return e!==void 0&&Zi(e)===null?e:void 0}var ou="/graview/assets/";function Vh(n,e){return n&&e!==void 0&&e.startsWith(ou)?n(e):e}var iu={"system-sans":'ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif',"system-serif":'ui-serif, "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, Cambria, "Times New Roman", serif',"system-mono":mn.mono},Bh=["serif","sans-serif","monospace","cursive","fantasy","system-ui","math","emoji","-apple-system","BlinkMacSystemFont"],su=["Georgia","Times New Roman","Times","Iowan Old Style","Palatino","Palatino Linotype","Charter","Cambria","Baskerville","Optima","Helvetica","Helvetica Neue","Arial","Verdana","Segoe UI","Roboto","Avenir","Avenir Next","Gill Sans","Menlo","Monaco","Consolas","SF Mono","SFMono-Regular","Courier New"];var Uh=n=>new Set(n.map(e=>e.toLowerCase()));function Wh(n){return Uh([...Bh,...su]).has(n.toLowerCase())||n.toLowerCase().startsWith("ui-")}function qh(n){return iu[n]??n}function F0(n){if(/url\(|@import|[;{}<>\\]|\/\*|[\u0000-\u001f\u007f]/i.test(n))return"it is not a list of font names; a document names a face, never where one comes from";for(let e of n.split(",")){let t=e.trim();if(!(/^"[^"']*"$/.test(t)||/^'[^"']*'$/.test(t))&&/["']/.test(t))return`${t} is not quoted in one pair; write a face as Georgia or "Times New Roman"`}return null}var au={r:255,g:255,b:255,a:1},Hh={r:0,g:0,b:0,a:1},Bn=n=>`#${[n.r,n.g,n.b].map(e=>Math.round(Math.max(0,Math.min(255,e))).toString(16).padStart(2,"0")).join("")}`,Ue=(n,e)=>`rgba(${Math.round(n.r)}, ${Math.round(n.g)}, ${Math.round(n.b)}, ${e})`,Ki=(n,e,t)=>({r:n.r+(e.r-n.r)*t,g:n.g+(e.g-n.g)*t,b:n.b+(e.b-n.b)*t,a:1});function Jh(n){return typeof n=="string"?{light:n}:{...n.light?{light:n.light}:{},...n.dark?{dark:n.dark}:{}}}function Yh(n){let e=Y(n)[0];if(!e)return;let{h:t,s:r}=pn(e);return Bn(Me(t,Math.min(r,.45),.08))}function cu(n,e){let t=Y(n.edgeBright)[0];return Ue(t,Di({...t,a:1},e,t.a,3))}function Xh(n,e,t){let{h:r,s:o}=pn(t),i=Ki(t,au,.8);return{...n,ground:e,groundDeep:Bn(Ki(t,Hh,.04)),panel:Bn(i),panelMuted:Bn(Ki(t,au,.55)),edge:Ue(Me(r,Math.min(o,.5),.14),.14),edgeBright:cu(n,i),bar:Ue(i,.96),float:Bn(i)}}function du(n,e,t){let{h:r,s:o,l:i}=pn(t),s=a=>Me(r,o,Math.min(1,i+a));return{...n,ground:e,groundDeep:Bn(Me(r,o,i*.6)),panel:Ue(s(.07),.96),panelMuted:Ue(s(.035),.94),edge:Ue(Me(r,Math.min(o,.45),.75),.18),edgeBright:cu(n,hn({...s(.07),a:.96},t)),bar:Ue(t,.96),float:Ue(s(.05),.98)}}function uu(n){if(n===void 0)return Ve;let e=Jh(n),t=e.dark??(e.light?Yh(e.light):void 0),r=e.light?Y(e.light)[0]:void 0,o=t?Y(t)[0]:void 0;return{light:r?Pr(r)?du(Ve.dark,e.light,r):Xh(Ve.light,e.light,r):Ve.light,dark:o?du(Ve.dark,t,o):Ve.dark}}var Qh=[["ink","ink",["ground","panel","panelMuted","panelWarning","float","bar"],4.5],["inkMuted","muted ink",["ground","panel","panelMuted","float","bar"],4.5],["inkFaint","faint ink",["panel","panelMuted","float"],4.5],["accent","the accent",["ground","panel","float"],4.5],["warn","the warning color",["panel","panelWarning","float"],4.5],["good","the good status",["ground","panel"],4.5],["bad","the bad status",["ground","panel"],4.5],["edgeBright","the lit edge",["panel"],3]],eg={panel:"a card",panelMuted:"a receded card",panelWarning:"a flagged card",float:"a floating sheet",bar:"the bar"};function K0(n,e){for(let t of["light","dark"]){let r={...n[t],...t==="light"&&e?{accent:e}:{}},o=Y(r.ground)[0];for(let[i,s,a,d]of Qh)for(let l of a){let u=l==="ground"?[o]:Y(String(r[l])).map(p=>hn(p,o));for(let p of u){let c=hn(Y(String(r[i]))[0],p),f=ke(c,p);if(f<d)return{scheme:t,what:s,text:c,ground:o,...l==="ground"?{}:{card:p,surface:eg[l]},ratio:f,requires:d}}}}return null}function W0(n,e){let t=uu(e),r=Nr({accent:n,base:t});return r.ok||!r.missing.every(o=>o.startsWith("warn"))?r:Nr({accent:n,base:t,warn:{light:t.light.bad,dark:t.dark.bad}})}function ng(n,e,t){if(t.rows===0)return;let r=ue(n,e.rows).toLowerCase(),o=ue(n,e.columns).toLowerCase(),i=e.rows===e.columns,s=i?`link ${r} to each other`:`link ${r} to ${o}`;if(t.columns===0)return`No ${o} yet: ${s}.`;if(t.cells>0||typeof e.link=="object"&&e.link!==null)return;let a=X(n.tryDefinition(e.rows),e.rows);return i?`No ${a} is linked to another yet: ${s}.`:`No ${a} is linked to ${Rn(X(n.tryDefinition(e.columns),e.columns))} yet: ${s}.`}function tg(n,e){let t=o=>o?._zod?.def,r={};for(let o of new Set(e)){let i=n.tryDefinition(o),s=i?.fields?.shape??{};for(let[a,d]of Object.entries(s)){let l=t(d);for(let p=0;p<6&&l?.innerType!==void 0&&l.type!=="enum";p++)l=t(l.innerType);if(l?.type==="array"&&(l=t(l.element)),l?.type!=="enum"||!l.entries)continue;let u=i?.display?.format?.[a];(r[o]??={})[a]=Object.fromEntries(Object.values(l.entries).map(p=>[String(p),u?u(p):en(String(p))]))}}return r}var xe={connectors:{all:{route:"curve",visible:!0},byEdge:{}},captions:{visible:!0},grid:{visible:!0,size:64},lattice:{visible:!0,size:46},tags:{visible:!0},emphasis:{rest:.34,dim:.12},marks:{flag:"\u26A0"}};function rg(n){return n?{connectors:{all:{...xe.connectors.all,...n.connectors?.all??{}},byEdge:{...xe.connectors.byEdge,...n.connectors?.byEdge??{}}},captions:{...xe.captions,...n.captions??{}},grid:{...xe.grid,...n.grid??{}},lattice:{...xe.lattice,...n.lattice??{}},tags:{...xe.tags,...n.tags??{}},emphasis:{...xe.emphasis,...n.emphasis??{}},marks:{...xe.marks,...n.marks??{}}}:xe}function og(n,e){return{...n.connectors.all,...n.connectors.byEdge[e]??{}}}function ig(n){return[` --graview-kit-grid: ${n.grid.visible?1:0};`,` --graview-kit-grid-size: ${n.grid.size}px;`,` --graview-kit-lattice: ${n.lattice.visible?1:0};`,` --graview-kit-lattice-size: ${n.lattice.size}px;`,` --graview-kit-tags: ${n.tags.visible?"inline-flex":"none"};`,` --graview-kit-captions: ${n.captions.visible?"block":"none"};`,` --graview-kit-rest: ${n.emphasis.rest};`,` --graview-kit-dim: ${n.emphasis.dim};`,` --graview-kit-flag: "${n.marks.flag.replace(/"/g,"'")}";`].join(`
|
|
5
|
-
`)}var lu=n=>n?.kind==="visitor"||n?.onBehalfOf?.kind==="visitor",Ir=new WeakMap;function sg(n,e){e?Ir.set(n,e):Ir.delete(n)}function ag(n,e,t){if(!n||lu(t))return;let r=Ir.get(n)??Ir.get(
|
|
3
|
+
${r}`:t);this.hint=r;this.name="GraphError"}},q=class extends N{constructor(t,r){super(r);this.id=t;this.name="MissingRecordError"}};function nr(n,e){try{n.parseNode(e);return}catch(t){if(t instanceof pe)throw t;let r=t.issues??[];return{fields:new Set(r.flatMap(i=>i.code==="unrecognized_keys"&&i.keys?[...i.keys]:typeof i.path?.[0]=="string"?[i.path[0]]:[""])),error:t}}}var Mo="n\0",No="e\0",H=class n{constructor(e,t={}){this.schema=e;this.validate=t.validate??!0}nodes=new Map;edges=new Map;linkIds=new Map;outIndex=new Map;inIndex=new Map;rank=0;ranks=new Map;lapsed=new Map;reordered=!1;counts=new Map;archived=new Set;listeners=new Set;validate;static from(e,t,r={}){let o=new n(e,r);return o.load(t),o}load(e){let t=this.snapshot();this.restore(e);let r=Fe(t,this.snapshot());return this.emit(r),r}getNode(e){return this.nodes.get(e)}has(e){return this.nodes.has(e)}allNodes(e){return this.reach([...this.nodes.values()],e,this.held)}count(e,t){return t||this.archived.size?this.nodesOfKind(e,t).length:this.counts.get(e)??0}allEdges(e){return this.reach([...this.edges.values()],e,t=>this.archived.has(t.from)||this.archived.has(t.to))}nodesOfKind(e,t){return this.allNodes(t).filter(r=>r.kind===e)}edgesOfKind(e,t){return this.allEdges(t).filter(r=>r.kind===e)}out(e,t,r){return this.reach(this.resolve(this.outIndex.get(e),t,"to"),r,this.held)}in(e,t,r){return this.reach(this.resolve(this.inIndex.get(e),t,"from"),r,this.held)}neighbors(e,t){let r=new Map;for(let o of[...this.out(e,void 0,t),...this.in(e,void 0,t)])r.set(o.id,o);return[...r.values()]}isArchived(e){return this.archived.has(e)}outEdges(e,t){return this.edgesFrom(this.outIndex.get(e),t)}inEdges(e,t){return this.edgesFrom(this.inIndex.get(e),t)}linkById(e){return this.edges.get(this.linkIds.get(e))}snapshot(){return{nodes:[...this.nodes.values()],edges:[...this.edges.values()]}}get size(){return{nodes:this.nodes.size,edges:this.edges.size}}applyPrimitives(e,t={}){let r=this.snapshot();try{for(let i of e)this.applyOne(i,t.restoring===!0,t.inPlace===!0);this.settleOrder()}catch(i){throw this.restore(r),i}let o=Le(r,this.snapshot(),e);return this.emit(o),o}preview(e,t={}){return n.from(this.schema,this.snapshot(),{validate:this.validate}).applyPrimitives(e,t)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}restore(e){let t=new Map([...this.lapsed,...this.ranks]);for(let o of[this.nodes,this.edges,this.linkIds,this.outIndex,this.inIndex,this.ranks,this.lapsed,this.counts,this.archived])o.clear();this.reordered=!1;for(let o of e.nodes)this.insertNode(o,!0);for(let o of e.edges)this.insertEdge(o,!0);let r=[...this.ranks.keys()];if(r.every((o,i)=>t.get(o)>(o[0]===r[i-1]?.[0]?t.get(r[i-1]):0))){for(let[o,i]of t)(this.ranks.has(o)?this.ranks:this.lapsed).set(o,i);for(;this.lapsed.size>4096;)this.lapsed.delete(this.lapsed.keys().next().value)}}tally(e,t){this.counts.set(e,(this.counts.get(e)??0)+t)}place(e,t){let r=t?this.lapsed.get(e):void 0;if(r===void 0){this.ranks.set(e,++this.rank);return}this.ranks.set(e,r),this.lapsed.delete(e),this.reordered=!0}lapse(e){let t=this.ranks.get(e);t!==void 0&&(this.ranks.delete(e),this.lapsed.set(e,t),this.lapsed.size>4096&&this.lapsed.delete(this.lapsed.keys().next().value))}settleOrder(){if(!this.reordered)return;this.reordered=!1;let e=o=>(i,s)=>this.ranks.get(o+i[0])-this.ranks.get(o+s[0]),t=[...this.nodes.entries()].sort(e(Mo));this.nodes.clear();for(let[o,i]of t)this.nodes.set(o,i);let r=[...this.edges.entries()].sort(e(No));this.edges.clear();for(let[o,i]of r)this.edges.set(o,i)}emit(e){if(!(e.addedNodes.length===0&&e.removedNodes.length===0&&e.changedNodes.length===0&&e.addedEdges.length===0&&e.removedEdges.length===0))for(let t of this.listeners)t(e)}applyOne(e,t,r){switch(e.op){case"add-node":Po(e.node),this.insertNode(e.node,t,r);return;case"remove-node":{let o=e.node.id,i=this.nodes.get(o);if(!i)throw new q(o,`Cannot remove missing node "${o}"`);for(let s of[...this.outEdges(o),...this.inEdges(o)])this.deleteEdge(s);this.tally(i.kind,-1),this.archived.delete(o),this.nodes.delete(o),this.lapse(Mo+o),this.outIndex.delete(o),this.inIndex.delete(o);return}case"patch-node":{let o=this.nodes.get(e.id);if(!o)throw new q(e.id,`Cannot patch missing node "${e.id}"`);Po(e.after);let i={...o};for(let[a,d]of Object.entries(e.after))qe(d)?delete i[a]:i[a]=d;let s=t?i:this.checkPatch(o,i,Object.keys(e.after));this.nodes.set(e.id,s),this.archived[me(s)?"add":"delete"](e.id),s.kind!==o.kind&&(this.tally(o.kind,-1),this.tally(s.kind,1));return}case"splice-text":{let o=this.nodes.get(e.id);if(!o)throw new q(e.id,`Cannot splice the text of missing node "${e.id}"`);let i=o[e.field],s;try{typeof i=="string"&&e.field!=="id"&&e.field!=="kind"&&(s=Tr(i,e))}catch{}if(s===void 0)throw new N(`Cannot splice ${e.id}.${e.field}: it does not hold ${JSON.stringify(e.removed)} at ${e.at}`,"A corrupt op: the text it was made against is not the text the log folds to.");let a={...o,[e.field]:s};this.nodes.set(e.id,t?a:this.checkPatch(o,a,[e.field]));return}case"add-edge":this.insertEdge(e.edge,t,r);return;case"remove-edge":{let o=e.edge.id===void 0?e.edge:this.linkById(e.edge.id);if(!o||!this.edges.has(I(o)))throw new q(e.edge.id??I(e.edge),`Cannot remove missing edge ${e.edge.id??I(e.edge)}`);this.deleteEdge(o);return}default:Oo(e)}}check(e){if(!this.validate)return e;try{return this.schema.parseNode(e)}catch(t){throw this.refusal(e,t)}}checkPatch(e,t,r){if(!this.validate)return t;let o=this.schema.tryDefinition(String(t.kind))?.fields?.shape;if(!o)return this.check(t);for(let a of r){if(a==="id"||a==="kind"||Qt.has(a))continue;let d=o[a];if(!d){delete t[a];continue}let l=d.safeParse(t[a]);l.success&&(l.data===void 0?delete t[a]:t[a]=l.data)}let i=nr(this.schema,t);if(i===void 0)return t;let s=nr(this.schema,e)?.fields??new Set;if([...i.fields].some(a=>r.includes(a)||!s.has(a)))throw this.refusal(t,i.error);return t}refusal(e,t){if(t instanceof pe)return t;{let r=e?.id??"?",o=e?.kind??"?",i=this.schema.tryDefinition(o),s=i&&e&&typeof e=="object"?K(i,e):r;return new N(`${s} does not match what ${o} declares`,Ql(t))}}insertNode(e,t,r=!1){if(this.nodes.has(e.id))throw new N(`Duplicate node id "${e.id}"`);this.nodes.set(e.id,t?e:this.check(e)),me(e)&&this.archived.add(e.id),this.tally(e.kind,1),this.place(Mo+e.id,r)}insertEdge(e,t,r=!1){let o=this.nodes.get(e.from),i=this.nodes.get(e.to);if(!o||!i){let a=o?e.to:e.from;throw new q(a,`Edge "${e.kind}" references missing node "${a}"`)}if(this.validate&&!t&&!this.schema.edgeAllowed(e.kind,o.kind,i.kind)){let a=this.schema.edge(e.kind);throw new N(`Edge "${e.kind}" is not declared from ${o.kind} to ${i.kind}`,a?`Declared: ${a.from.join("|")} -> ${a.to==="*"?"*":a.to.join("|")}`:`No edge kind "${e.kind}" is declared in this schema`)}let s=I(e);if(!t&&(e.id!==void 0||e.data!==void 0)){let a=this.edges.get(s),d=Xa(e)??(a&&e.id!==void 0&&a.id!==e.id?`A second "${e.kind}" link between two records is not allowed yet`:(this.linkIds.get(e.id)??s)!==s?`Link id "${e.id}" is already taken`:void 0);if(d)throw new N(d)}this.edges.has(s)||(this.edges.set(s,e),e.id!==void 0&&this.linkIds.set(e.id,s),this.place(No+s,r),this.index(this.outIndex,e.from,s),this.index(this.inIndex,e.to,s))}deleteEdge(e){let t=I(e),r=this.edges.get(t)?.id;r!==void 0&&this.linkIds.delete(r),this.edges.delete(t),this.lapse(No+t),this.outIndex.get(e.from)?.delete(t),this.inIndex.get(e.to)?.delete(t)}index(e,t,r){(e.get(t)??e.set(t,new Set).get(t)).add(r)}edgesFrom(e,t){if(!e)return[];let r=[];for(let o of e){let i=this.edges.get(o);i&&(t===void 0||i.kind===t)&&r.push(i)}return r}resolve(e,t,r){let o=[];for(let i of this.edgesFrom(e,t)){let s=this.nodes.get(i[r]);s&&o.push(s)}return o}held=e=>this.archived.has(e.id);reach(e,t,r){let o=t?.archived??!1;return o==="all"||!o&&!this.archived.size?e:e.filter(i=>r(i)===o)}};var tr=class extends Error{constructor(t,r){super(`No invariant registered under "${t}" (required by node "${r}")`);this.invariant=t;this.nodeId=r;this.name="UnregisteredInvariantError"}};function ef(n,e){return{...e,name:n}}var rr=class extends Error{constructor(e){super(e),this.name="RuleBudgetError"}};function Qa(n,e,t){try{return e().map(r=>r.status?r:{...r,status:"violated"})}catch(r){let o=r instanceof rr,i=r instanceof Error?r.message:String(r),s=n.label??n.name.replace(/-/g," ");return[{invariant:n.name,status:o?"over-budget":"could-not-judge",...t!==void 0?{subjectId:t}:{},label:s,message:`${s} could not be judged: ${i}`,nodeIds:t!==void 0?[t]:[],repairs:[]}]}}function zn(n,e,t={}){let r=t.context??{},o=t.today===void 0?{}:{today:t.today},i=t.onUnregistered??"skip",s=new Set(e.map(c=>c.name)),a=[];for(let c of e)c.scope==="graph"&&a.push(...Qa(c,()=>c.evaluate({graph:n,subject:void 0,context:r,...o}),void 0));let d=e.filter(c=>c.scope!=="graph"),l=new Map;for(let c of d){let f=c.scope.kind,g=l.get(f);g?g.push(c):l.set(f,[c])}for(let c of n.allNodes()){let f=n.schema.tryDefinition(c.kind),g=f?.requiresInvariant?.(c)??null;if(t.subjectFilter&&!t.subjectFilter(c,r))continue;if(g!==null&&!s.has(g)){if(i==="throw")throw new tr(g,c.id);continue}let h=!Vr(f,c,t.today);for(let y of l.get(c.kind)??[]){if(h&&y.judgesPast!==!0)continue;let b=y.scope.match;b&&!b(c)||a.push(...Qa(y,()=>y.evaluate({graph:n,subject:c,context:r,...o}),c.id))}}let u=new Set,p=a.filter(c=>{let f=`${c.message}|${[...c.nodeIds].sort().join(",")}`;return u.has(f)?!1:(u.add(f),!0)}).map(c=>{let f=Gr(c.message);return f===c.message?c:{...c,message:f}});return zo?zo(n,e,p,t.today):p}var zo;function bw(n){zo=n}function nf(n,e){let t=new Set(e);return n.filter(r=>r.nodeIds.some(o=>t.has(o))||r.subjectId!==void 0&&t.has(r.subjectId))}function tf(n){let e=new Set(n.map(r=>r.invariant)).size;if(e===0)return"All rules hold";let t=`${e} ${e===1?"rule":"rules"} broken`;return n.length>e?`${t} in ${n.length} places`:t}var pt=(n,e)=>n==="*"||n.includes(e);function z(n){let e=n.onBehalfOf;if(!e)return n;let t=e.roles??[],r=n.roles===void 0?t:n.roles.filter(o=>t.includes(o));return{...n,...e.id!==void 0?{id:e.id}:{},roles:r}}var Z=n=>n.kind==="system"&&n.onBehalfOf===void 0,ye=(n,e)=>n.roles==="*"||(e.roles??[]).some(t=>n.roles.includes(t));function ed(n){return Ji(n.map(e=>Rn(B(e).toLowerCase())),"or")}function be(n,e,t,r,o,i,s={},a,d,l){if(!n)return{ok:!0};if(Z(e))return{ok:!0};if(e=z(e),o!==void 0){if(be(n,e,t,r,void 0,i).ok)return{ok:!0};let f=!1;if(o.some(b=>be(n,e,b,r,void 0,i).ok)){if(!d||i===void 0||e.id!==void 0&&d()===e.id||!l&&n.grants.some(b=>b.roles!=="*"&&ye(b,e)&&o.some(x=>pt(b.mutations,x))))return{ok:!0};f=!0}let g=f?[t]:[t,...o],h=[...new Set(g.flatMap(b=>Io(n,b,r)))].sort(),y=(f?"only on what you made; ":"")+(h.length===0?o.length===0?"no declared act creates or changes it, so no role can":"no role can":`${ed(h)} can`);return{ok:!1,refusal:{mutation:t,...r===void 0?{}:{kind:r},wouldNeed:h,message:nd(n,g,r,y,s)}}}let u=!1;for(let f of n.grants){if(!ye(f,e)||!pt(f.mutations,t)||f.kinds!==void 0&&f.kinds!=="*"&&(r===void 0||!f.kinds.includes(r))||f.self&&(i===void 0||e.id===void 0||i!==e.id))continue;let g=f.ownEnd?a?.()??[]:[e.id];if(!g.length||g.some(h=>h!==e.id)){u=!0;continue}return{ok:!0}}let p=Io(n,t,r),c=u?"only on your own end of the link":p.length===0?"no role can":`${ed(p)} can`;return{ok:!1,refusal:{mutation:t,...r===void 0?{}:{kind:r},wouldNeed:p,message:nd(n,[t],r,c,s)}}}function nd(n,e,t,r,o){let i=[...new Set(e.flatMap(a=>td(n,a,t)))],s=o.act?.(e[0]);return`Not permitted: ${s?`\u201C${s}\u201D`:e[0]}${t?` on ${Rn(o.noun?.(t)??t)}`:""} \u2014 ${r}.`+(i.length>0?` ${i.join(" ")}`:"")}function td(n,e,t){return[...new Set(rd(n,e,t).flatMap(r=>r.describe||[]))]}var rd=(n,e,t)=>n.grants.filter(r=>pt(r.mutations,e)&&(t===void 0||pt(r.kinds??"*",t)));function Io(n,e,t){let r=rd(n,e,t);return r.some(o=>o.roles==="*")?[]:[...new Set(r.flatMap(o=>o.roles))].sort()}function To(n,e,t){return n?t.filter(r=>{let o=z(e).id;return jo(r).some(i=>be(n,e,r.name,i,void 0,o,void 0,()=>[o??[]].flat()).ok)}):t}var jo=n=>n.subject&&n.subject.kinds!=="*"?n.subject.kinds:[void 0];function Do(n,e,t,r){if(!n||Z(e))return!1;let o=z(e);return n.grants.some(i=>i.propose!==void 0&&ye(i,o)&&pt(i.propose,t)&&(i.kinds===void 0||i.kinds==="*"||r!==void 0&&i.kinds.includes(r)))}var or="type-text",ae={};var de=class extends Error{constructor(t,r="refused"){super(t);this.sentence=t;this.reason=r;this.name="ActRefusal"}};var ir="publish",Fo=n=>n?.mode==="on-publish",Lo=(n,e,t)=>Fo(n)&&!Z(e)&&(t==="published"||!(z(e).roles??[]).some(r=>n.working.includes(r))),J=globalThis[Symbol.for("@graview/core:publishing")]??={};J.input=()=>se({through:W(tn())});var ht=class{constructor(e,t,r){this.present=e;this.timeline=t;this.unversioned=r}nodes=new Map;edges=new Map;touching=new Map;seq=Number.MAX_SAFE_INTEGER;wrote=new Map;begin(e){this.seq=e,this.wrote.clear()}writerOf(e){return t=>{let r=`${e}\0${t}`;return this.wrote.has(r)?this.wrote.get(r):this.timeline?.writers?.writerAt(e,t,this.seq)}}note(e,t){let r=e.op==="add-node"?e.node.id:e.op==="patch-node"||e.op==="splice-text"?e.id:"";if(r===""||this.unversioned?.has(r))return;let o=e.op==="add-node"?Object.keys(e.node):e.op==="splice-text"?[e.field]:Object.keys(e.after);for(let i of o)i!=="id"&&i!=="kind"&&this.wrote.set(`${r}\0${i}`,t(r,i))}node(e){return this.nodes.has(e)?this.nodes.get(e)??void 0:this.present.getNode(e)}setNode(e,t){this.nodes.set(e,t)}setEdge(e,t){let r=I(e);this.edges.set(r,t?e:null);for(let o of[e.from,e.to]){let i=this.touching.get(o);i||this.touching.set(o,i=new Set),i.add(r)}}incident(e){let t=new Map;for(let r of[...this.present.outEdges(e),...this.present.inEdges(e)]){let o=I(r);this.edges.has(o)||t.set(o,r)}for(let r of this.touching.get(e)??[]){let o=this.edges.get(r);o&&t.set(r,o)}return[...t.values()]}undo(e){switch(e.op){case"add-node":this.setNode(e.node.id,null);return;case"remove-node":this.setNode(e.node.id,e.node);return;case"patch-node":{if(this.unversioned?.has(e.id))return;let t=this.node(e.id);if(!t)return;this.setNode(e.id,od(t,e.before));return}case"splice-text":{let t=this.unversioned?.has(e.id)?void 0:this.node(e.id);t&&this.setNode(e.id,jr(t,e,!0));return}case"add-edge":this.setEdge(e.edge,!1);return;case"remove-edge":this.setEdge(e.edge,!0);return}}apply(e){switch(e.op){case"add-node":this.setNode(e.node.id,e.node);return;case"remove-node":for(let t of this.incident(e.node.id))this.setEdge(t,!1);this.setNode(e.node.id,null);return;case"patch-node":{if(this.unversioned?.has(e.id))return;let t=this.node(e.id);if(!t)return;this.setNode(e.id,od(t,e.after));return}case"splice-text":{let t=this.unversioned?.has(e.id)?void 0:this.node(e.id);t&&this.setNode(e.id,jr(t,e));return}case"add-edge":this.setEdge(e.edge,!0);return;case"remove-edge":this.setEdge(e.edge,!1);return}}};function od(n,e){let t={...n};for(let[r,o]of Object.entries(e))qe(o)?delete t[r]:t[r]=o;return t}var rf=n=>n.op==="add-node"||n.op==="remove-node"?n.node.id:n.op==="patch-node"||n.op==="splice-text"?n.id:void 0;function Co(n,e,t,r){let o=u=>{let p=e.node(u);return p?t.served(p,e.writerOf(u))!==void 0:t.sees?.(u)??!1},i=rf(n);if(i===void 0){let u=n.edge,p=t.edgeClean(u)&&o(u.from)&&o(u.to);return e.apply(n),{primitives:p?[n]:[],faithful:!0}}let s=e.node(i),a=s?t.served(s,e.writerOf(i)):void 0;e.apply(n),e.note(n,r);let d=e.node(i),l=d?t.served(d,e.writerOf(i)):void 0;if(!a&&!l)return{primitives:[],faithful:!1};if(!a&&l){let u=e.incident(i).filter(c=>t.edgeClean(c)&&o(c.from===i?c.to:c.from)).map(c=>({op:"add-edge",edge:c})),p=n.op==="add-node"&&l===n.node&&u.length===0;return{primitives:p?[n]:[{op:"add-node",node:l},...u],faithful:p}}if(a&&!l){let u=n.op==="remove-node"&&a===s;return{primitives:u?[n]:[{op:"remove-node",node:a}],faithful:u}}if(n.op==="patch-node"){let u=(c,f)=>g=>g in c==(f!==void 0&&g in f);if(Object.keys(n.after).every(c=>u(a,s)(c)&&u(l,d)(c)))return{primitives:[n],faithful:!0};let p=c=>Object.fromEntries(Object.keys(n.after).map(f=>[f,f in c?c[f]:ce]));return{primitives:[{op:"patch-node",id:i,before:p(a),after:p(l)}],faithful:!1}}if(n.op==="splice-text"){let u=n.field;if(a[u]===s[u]&&l[u]===d[u])return{primitives:[n],faithful:!0};let p=c=>({[u]:u in c?c[u]:ce});return{primitives:[{op:"patch-node",id:i,before:p(a),after:p(l)}],faithful:!1}}return{primitives:[{op:"remove-node",node:a},{op:"add-node",node:l}],faithful:!1}}function id(n,e,t){if(n.length===0)return[];let r=e.log.all(),o=r[0]?.seq??0,i=n.every(c=>r[c.seq-o]?.id===c.id),s=new ht(e.present,e);if(!i)return s.begin(e.log.length??o+r.length),n.map(c=>{let f=z(c.author).id,g=c.primitives.map(h=>Co(h,s,t,()=>f));return{op:c,primitives:g.flatMap(h=>h.primitives),faithful:g.every(h=>h.faithful)}});let a=new Set(n.map(c=>c.seq)),d=Number.POSITIVE_INFINITY,l=Number.NEGATIVE_INFINITY;for(let c of a)c<d&&(d=c),c>l&&(l=c);d-=o,l-=o;let u=of(r,d,e.present,t),p=u?new ht(e.present,e,u.unversioned):s;for(let c=r.length-1;c>=d;c--){let f=r[c].primitives;for(let g=f.length-1;g>=0;g--)p.undo(f[g])}return sf(n,r,d,l,a,p,u?.judge??t,e)}function of(n,e,t,r){let{sees:o,names:i}=r;if(!o||!i)return;let s=new Set,a=new Set,d=new Set,l=(p,c)=>{s.has(p)||a.has(p)||(o(p)?i(c)?(a.add(p),d.delete(p)):d.add(p):(s.add(p),d.delete(p)))};for(let p=e;p<n.length;p++)for(let c of n[p].primitives)c.op==="add-node"||c.op==="remove-node"?l(c.node.id,c.node):c.op==="patch-node"?(l(c.id,c.before),l(c.id,c.after)):c.op==="splice-text"&&(l(c.id,{}),s.has(c.id)||(a.add(c.id),d.delete(c.id)));for(let p of d){let c=t.getNode(p);c&&i(c)&&(d.delete(p),a.add(p))}return{unversioned:new Set([...d,...s]),judge:{...r,served:(p,c)=>d.has(p.id)?p:s.has(p.id)?void 0:r.served(p,c)}}}function sf(n,e,t,r,o,i,s,a){let d=new Map;for(let l=t;l<=r;l++){let u=e[l];if(i.begin(u.seq),!o.has(u.seq)){for(let f of u.primitives)i.apply(f);continue}let p=(f,g)=>a.writers?.writerAt(f,g,u.seq+1),c=u.primitives.map(f=>Co(f,i,s,p));d.set(u.seq,{op:u,primitives:c.flatMap(f=>f.primitives),faithful:c.every(f=>f.faithful)})}return n.map(l=>d.get(l.seq))}function Mw(n,e,t,r){let o=new ht(e.present,e);return o.begin(e.log.length??e.log.all().length),n.flatMap(i=>Co(i,o,t,()=>r).primitives)}var ad="A change you cannot see",dd={kind:"system",id:"withheld",name:"Someone"};function In(n){return n.withheld===!0}var gt=Re,cd=(n,e)=>Object.entries(n).some(([t,r])=>t!=="id"&&t!=="kind"&&C(r,e));function ud(n){if(typeof n!="function")return n;let e=n,t=r=>e(r.id)&&!cd(r,e)?r:void 0;return{sees:e,shows:e,served:t,servedWith:t,optional:()=>!1,kindOf:()=>{}}}function C(n,e){if(typeof n=="string")return!e(n);if(n===null||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0;t<n.length;t++)if(C(n[t],e))return!0;return!1}for(let t in n)if(Object.hasOwn(n,t)&&(!e(t)||C(n[t],e)))return!0;return!1}function ld(n,e){let t=r=>!e(r);return n.primitives.some(r=>gt(r).some(t))||[...n.writes,...n.reads].some(t)||n.mutation!==null&&C(n.mutation.args,e)}function af(n,e){if(gt(n).every(e.shows))switch(n.op){case"add-node":{let t=e.served(n.node);return t?t===n.node?n:{op:"add-node",node:t}:void 0}case"remove-node":{let t=n.node;return cd(t,e.sees)?{op:"remove-node",node:Object.fromEntries(Object.entries(t).filter(([r,o])=>r==="id"||r==="kind"||!C(o,e.sees)))}:n}case"patch-node":{let t=e.kindOf(n.id),r={};for(let[i,s]of Object.entries(n.after))if(!C(s,e.sees))r[i]=s;else if(t!==void 0&&e.optional(t,i))r[i]=ce;else return;let o=Object.fromEntries(Object.entries(n.before).filter(([,i])=>!C(i,e.sees)));return{op:"patch-node",id:n.id,before:o,after:r}}case"add-edge":case"remove-edge":return C(n.edge,e.sees)?void 0:n;case"splice-text":return C(n.removed,e.sees)||C(n.inserted,e.sees)?void 0:n}}function Zo(n,e,t){let r=ud(e),o=i=>r.shows(i)&&fd(r,i);return{id:n.id,seq:n.seq,batch:n.batch,author:dd,intent:ad,mutation:null,primitives:t??n.primitives.flatMap(i=>{let s=af(i,r);return s?[s]:[]}),reads:n.reads.filter(o),writes:n.writes.filter(o),at:n.at,...n.undoes!==void 0?{undoes:n.undoes}:{},withheld:!0}}function Tn(n,e){let t=ud(e);if(t.hides?.()===!1)return[...n];let r=t.pin?.()??t;if(r.redact)return r.redact(n);if(r.timeline){let o={served:(i,s)=>r.servedWith(i,s),edgeClean:i=>!C(i,r.sees),sees:r.sees,names:i=>C(i,r.sees)};return id(n,r.timeline,o).map(({op:i,primitives:s,faithful:a})=>(!i.withheld&&a?sd(i,r,s):void 0)??Zo(i,r,s))}return n.map(o=>(!o.withheld&&!ld(o,r.shows)?sd(o,r):void 0)??Zo(o,r))}function sd(n,e,t){let r=n.inverse??n.primitives;if(t&&t.length<n.primitives.length){if(!t.length)return;r=r.filter(h=>gt(h).every(e.shows));let{inverse:f,...g}=n;n={...g,primitives:t}}let o=f=>e.sees(f)&&fd(e,f),i=n.reads.filter(o),s=new Set(n.primitives.flatMap(gt)),a=n.writes.filter(f=>o(f)||e.sees(f)&&s.has(f)),d=i.length===n.reads.length&&a.length===n.writes.length?n:{...n,reads:i,writes:a},l=e.actor!==void 0&&z(n.author).id===e.actor;if(!l&&n.described?.some(f=>!e.sees(f)))return;if(!C(n,e.sees))return d;let u=new Set,p=f=>{if(typeof f=="string")u.add(f);else if(Array.isArray(f))for(let g of f)p(g);else if(f!==null&&typeof f=="object")for(let[g,h]of Object.entries(f))u.add(g),p(h)};t&&p(t);let c=f=>e.sees(f)||u.has(f);if(!C(r,c))return l&&n.mutation&&p(n.mutation.args),C({...d,primitives:[],inverse:[]},l?c:e.sees)?void 0:d}function fd(n,e){return n.timeline===void 0||n.kindOf(e)!==void 0}var on=class extends N{constructor(t){super(t.message);this.check=t;this.name="UndoBlockedError"}get blockedBy(){return this.check.blockedBy}};function mt(n,e){let t=new Set(e),r=n.undoneIds(),o=n.all().filter(h=>t.has(h.batch)&&!r.has(h.id)),i=[...n.epochs()].reverse().find(h=>h.horizon);if(i){let h=new Set(n.all().map(b=>b.batch)),y=e.filter(b=>!h.has(b));if(y.length>0)return{ok:!1,ops:o,blockedBy:[],includeBatches:[],reason:"missing",message:`Cannot undo ${y.map(b=>`batch ${b}`).join(", ")}: it is not after the undo horizon at op ${i.seq}${i.at?` (${i.at})`:""}. What was done before the horizon is archived, and undo does not reach behind it.`}}if(o.length===0)return{ok:!1,ops:o,blockedBy:[],includeBatches:[],reason:"missing",message:e.length===0?"No batch given to undo":`Nothing live to undo in ${e.join(", ")} \u2014 already undone, or never applied`};if(o.some(In))return{ok:!1,ops:o,blockedBy:[],includeBatches:[],reason:"forbidden",message:o.every(In)?"Cannot undo a change you cannot see: only somebody who can see it can take it back.":"Cannot undo this here: part of it is a change you cannot see, and only somebody who can see it can take it back."};if(o.some(h=>h.enabledModules!==void 0))return{ok:!1,ops:o,blockedBy:[],includeBatches:[],message:"Cannot undo turning a module off or on: it is changed by turning the module the other way."};if(o.some(h=>h.sentOut!==void 0))return{ok:!1,ops:o,blockedBy:[],includeBatches:[],message:o.every(h=>h.sentOut===void 0||h.sentOut.refused)?"Nothing to take back: nothing went out.":"Nothing to take back: an invitation already went out. Change the guests here, and the next pass sends that."};let s=i&&o.some(h=>h.publishedThrough!==void 0)?J.undo?.(n,o,i):void 0;if(s)return{ok:!1,ops:o,blockedBy:[],includeBatches:[],message:s};let a=new Set;for(let h of o)for(let y of h.writes)a.add(y);let d=Math.min(...o.map(h=>h.seq)),l=n.epochs().find(h=>h.change!==void 0&&h.seq>d);if(l){let h=o.find(y=>y.seq<l.seq);return{ok:!1,ops:o,blockedBy:[],includeBatches:[],message:`Cannot undo "${h.intent}": ${h.intent===l.change?"it changed the declaration":`it was done before the declaration changed (${l.change})`}, and undo does not reach back across that change.`}}let u=new Map(n.all().map(h=>[h.id,h.seq])),p=o.flatMap(h=>h.primitives),c=[];for(let h of n.all()){if(h.seq<=d||t.has(h.batch)||r.has(h.id)||h.undoes!==void 0&&(u.get(h.undoes)??-1)>d)continue;let y=ae.aside?.(p,h);if(y===!0)continue;let b=[...new Set([...h.reads.filter(x=>a.has(x)),...y??[]])];b.length>0&&c.push({op:h,overlap:b})}if(c.length===0)return{ok:!0,ops:o};let f=c.filter(h=>!In(h.op)).map(h=>`"${h.op.intent}" (op ${h.op.id}, read ${h.overlap.join(", ")})`).join("; ");if(c.some(h=>In(h.op)))return{ok:!1,ops:o,blockedBy:c,includeBatches:[],message:`Cannot undo on its own \u2014 ${f?`a later operation depends on it: ${f}; and `:""}a later change you cannot see depends on it, which only somebody who can see it can take back.`};let g=[...new Set(c.map(h=>h.op.batch))];return{ok:!1,ops:o,blockedBy:c,includeBatches:g,message:`Cannot undo on its own \u2014 a later operation depends on it: ${f}. Include ${g.map(h=>`batch ${h}`).join(", ")} to undo them together.`}}function pd(n,e){return e?Go(e,n).flatMap(t=>[...t.primitives]):[...n].sort((t,r)=>r.seq-t.seq).flatMap(t=>Je(t))}function Go(n,e){return ae.undone?ae.undone(n,e):[...e].sort((t,r)=>r.seq-t.seq).map(t=>({op:t,primitives:Je(t)}))}var sn=class extends Error{refusal;constructor(e){super(e.message),this.name="PermissionDeniedError",this.refusal=e}};function df(n){let e=n instanceof Error?n.message:String(n);if(n instanceof sn){let t=n.refusal.wouldNeed;return{reason:"forbidden",sentence:e,...t.length>0?{wouldNeed:[...t]}:{}}}return n instanceof q?{reason:"missing",sentence:e}:n instanceof de?{reason:n.reason,sentence:n.sentence}:n instanceof on?{reason:n.check.reason??"invalid",sentence:e}:{reason:"invalid",sentence:e}}var ve=class extends N{constructor(t,r){super(`Invalid arguments for mutation "${t}"`,r.map(o=>`${o.path.map(String).join(".")||"(root)"}: ${o.message}`).join("; "));this.mutation=t;this.issues=r;this.name="InvalidArguments"}};var cf=["edit","remove","archive","unarchive","merge","leave-alone","allow-tidying"];var Yw=n=>cf.map(e=>`${e}-${n}`);function gd(n){let e=/^(edit|remove|archive|unarchive|merge|leave-alone|allow-tidying|skip|detach|split)-(.+)$/.exec(n);return e?{act:e[1],kind:e[2]}:void 0}var Vo=["connect","disconnect"],md=n=>n.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`),Ko=(n,e,t)=>`${n}-${e}-${md(t)}`;function Xw(n,e){let t=/^(connect|disconnect)-(.+)$/.exec(n);if(t){for(let[r,o]of e)if(t[2].startsWith(`${r}-`)){for(let i of o)if(t[2]===`${r}-${md(i)}`)return{act:t[1],kind:r,relation:i}}}}var Qw=n=>[...n].flatMap(([e,t])=>[...t].flatMap(r=>Vo.map(o=>Ko(o,e,r)))),hd=n=>`${/^[aeiou]/i.test(n)?"an":"a"} ${n}`;function yd(n,e){let t=e.also?` (${e.also})`:"";return{title:`${e.one?`${n==="connect"?"Set":"Clear"} the ${e.to}`:`${n==="connect"?"Link":"Unlink"} ${hd(e.to)}`}${t}`,fromTheOtherEnd:`${n==="connect"?"Link":"Unlink"} ${hd(e.from)}${t}`}}function bd(n,e,t,r){if(t.cardinality!=="one"||t.to==="*"||t.to.length!==1||t.to[0]!==n)return;let o=t.description?.trim().replace(/\.$/,"");return o&&/^the\s+\S/i.test(o)&&!/[.;:!?,()]/.test(o)&&o.split(/\s+/).length<=8?{to:o.replace(/^the\s+/i,"")}:{also:r(e)}}var yt="vote-suggestion",vd="Sign in to vote on this suggestion.";function bt(n){return n?n.shared===!0||n.kind==="visitor"?!0:bt(n.onBehalfOf):!1}function sr(n){if(!n)return;if(n.shared!==!0&&n.kind!=="visitor")return sr(n.onBehalfOf);let e=n.visitorKey??(n.shared===!0?void 0:n.id);return e||void 0}function wd(){return{name:yt,title:"Vote on a suggestion",input:se({suggestion:F(),vote:Na([it("for"),it("against"),Pa()])}),apply(){}}}var ar=globalThis[Symbol.for("@graview/core:voting")]??={};var an=n=>n.trim().replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").replace(/-+/g,"-").toLowerCase();function dr(n,e){let t=an(n),r=[...e];if(r.includes(n))return n;let o=r.filter(i=>an(i)===t);return o.length===1?o[0]:void 0}function uf(n,e){let t=Array.from({length:e.length+1},(r,o)=>o);for(let r=1;r<=n.length;r+=1){let o=[r];for(let i=1;i<=e.length;i+=1)o[i]=Math.min(t[i]+1,o[i-1]+1,t[i-1]+(n[r-1]===e[i-1]?0:1));t=o}return t[e.length]}function Bo(n,e){let t=[...e],r=dr(n,t);if(r)return r;let o=an(n);if(o==="")return;let i,s=!1;for(let a of t){let d=uf(o,an(a));d>Math.max(2,Math.floor(Math.max(o.length,a.length)/3))||(!i||d<i.far?(i={act:a,far:d},s=!1):d===i.far&&(s=!0))}return i&&!s?i.act:void 0}var lf=n=>`Op "${n.id}" has seq ${n.seq}, so the log begins at seq ${n.seq}: a log that begins past 0 begins at its undo horizon, and none was given (a checkpoint epoch, or { horizon })`,jn=class n{ops=[];marks=[];start=0;get length(){return this.start+this.ops.length}get horizon(){return this.start}all(){return this.ops}opsFrom(e){return this.ops.slice(Math.max(0,e-this.start))}append(e){if(e.seq!==this.length)throw new Error(this.length===0&&e.seq>0?lf(e):`Op "${e.id}" has seq ${e.seq} but the log is ${this.length} long`);Eo(e),this.ops.push(qn(e))}static from(e,t=[],r={}){let o=new n,i=[...t].reverse().find(d=>d.horizon),s=r.horizon??i?.seq??0;if(!Number.isInteger(s)||s<0)throw new Error(`A log cannot begin at seq ${s}`);if(i&&r.horizon!==void 0&&i.seq!==r.horizon)throw new Error(`A log said to begin at seq ${r.horizon} has its checkpoint at seq ${i.seq}`);let a=e[0];if(a&&s>0&&a.seq!==s)throw new Error(`A log compacted at seq ${s} begins with op "${a.id}" at seq ${a.seq}`);o.start=s;for(let d of e)o.append(d);for(let d of t)o.markEpoch(d);return o}replace(e,t=[],r={}){let o=n.from(e,t,r);this.ops=o.ops,this.marks=o.marks,this.start=o.start}epochs(){return this.marks}horizonEpoch(){for(let e=this.marks.length-1;e>=0;e--)if(this.marks[e].horizon)return this.marks[e]}lastEpoch(){return this.marks.at(-1)}markEpoch(e){if(!Number.isInteger(e.seq)||e.seq<0||e.seq>this.length)throw new Error(`An epoch at seq ${e.seq} starts past the end of a log ${this.length} long`);if(e.seq<this.start)throw new Error(`An epoch at seq ${e.seq} is behind the horizon at seq ${this.start}: it went to the archive with the ops before it`);let t=this.lastEpoch();if(t&&e.seq<t.seq)throw new Error(`An epoch at seq ${e.seq} comes before the last one, at seq ${t.seq}`);this.marks.push(e)}truncate(e){if(!Number.isInteger(e)||e<this.start||e>this.length)throw new Error(`Cannot cut a log ${this.length} long back to ${e}`);let t=this.lastEpoch();if(t&&t.seq>e)throw new Error(`Cannot cut the log back to ${e}: an epoch begins at seq ${t.seq}`);return this.ops.splice(e-this.start)}checkpointAt(e,t,r={}){if(!Number.isInteger(t)||t<this.start||t>this.length)throw new Error(`No checkpoint at seq ${t}: this log holds seqs ${this.start} to ${this.length}`);let o=[...this.marks].reverse().find(a=>a.seq<=t);if(o?.seq===t)return{...o,horizon:!0};let i=this.fold(e,{...r,...o?{from:o}:{},to:t}).snapshot(),s=this.ops[t-1-this.start]?.at??o?.at;return{seq:t,base:i,...o?.version!==void 0?{version:o.version}:{},...s!==void 0?{at:s}:{},horizon:!0}}compact(e){if(!Number.isInteger(e.seq)||e.seq<this.start||e.seq>this.length)throw new Error(`Cannot compact at seq ${e.seq}: this log holds seqs ${this.start} to ${this.length}`);let t=this.ops.slice(0,e.seq-this.start),r=this.marks.filter(o=>o.seq<e.seq);return this.ops=this.ops.slice(e.seq-this.start),this.marks=[{...e,horizon:!0},...this.marks.filter(o=>o.seq>e.seq)],this.start=e.seq,{ops:t,epochs:r}}get(e){return this.ops.find(t=>t.id===e)}live(){let e=this.undoneIds();return this.ops.filter(t=>!e.has(t.id))}undoneIds(){return dn(this.ops)}opsInBatch(e){return this.ops.filter(t=>t.batch===e)}batches(){return Uo(this.ops,this.undoneIds())}fold(e,t={}){let r=t.from?.seq??0;if(r<this.start)throw new Error(t.from?`An epoch at seq ${r} is behind the horizon at seq ${this.start}: fold from the checkpoint`:`A log compacted at seq ${this.start} does not fold from empty: fold from its checkpoint`);let o=t.from?.base??{nodes:[],edges:[]},i=H.from(e,o,t.validate!==void 0?{validate:t.validate}:{}),s=t.to??this.length;for(let a of this.ops.slice(r-this.start,Math.max(0,s-this.start)))ff(i,a);return i}toJSON(){return[...this.ops]}};function ff(n,e){if(e.undoes!==void 0){n.applyPrimitives(e.primitives,{restoring:!0});return}try{n.applyPrimitives(e.primitives)}catch{n.applyPrimitives(e.primitives,{restoring:!0})}}function dn(n){let e=new Map;for(let r of n){if(!r.undoes)continue;let o=e.get(r.undoes);o?o.push(r.id):e.set(r.undoes,[r.id])}let t=new Map;for(let r=n.length-1;r>=0;r--){let o=n[r],i=e.get(o.id)??[];t.set(o.id,!i.some(s=>t.get(s)===!0))}return new Set(n.filter(r=>t.get(r.id)===!1).map(r=>r.id))}function pf(n){let e=[...new Set(n.map(t=>t.intent))];return e.length<=3?e.join("; "):`${e.slice(0,2).join("; ")}; and ${e.length-2} more`}function Uo(n,e){let t=[],r=new Map;for(let o of n){let i=r.get(o.batch);i?i.push(o):(r.set(o.batch,[o]),t.push(o.batch))}return t.map(o=>{let i=r.get(o)??[],s=i[0];return{id:o,author:s.author,intent:s.batchIntent??pf(i),at:s.at,...s.lineage?{lineage:s.lineage}:{},ops:i,undone:i.every(a=>e.has(a.id))}})}function cr(n){return n?.automated===!0&&n.kind!=="human"&&n.kind!=="rule"}var xd=n=>n?.[lt]===!0,hf=(n,e)=>xd(("graph"in n?n.graph:n).getNode(e));function kd(n,e,t){let r=n.tryDefinition(e);return t===void 0?r?.tidying:r?.edges?.[t]?.tidying}var gf=n=>JSON.stringify(n,(e,t)=>t&&typeof t=="object"&&!Array.isArray(t)?Object.fromEntries(Object.entries(t).sort()):t);var mf=/^(archive|unarchive|remove|leave-alone|allow-tidying)$/;function yf(n,e){let t=an(n.name),r=e?.act(n.name),o=n.args??{},i=r?r.derived:gd(t),{id:s}=o;if(i&&typeof s=="string"){if(mf.test(i.act))return[i.act,s];if(i.act==="merge")return["merge",...[s,o.into].sort()];if(i.relation)return[i.act,i.relation,s,o.to]}let a=r?.subject?.arg??"id",[d,l]=Object.keys(o).filter(u=>u!==a);return r?.connects?.length===1&&d&&!l&&e.has(o[a])&&e.has(o[d])?["connect",r.connects[0],o[a],o[d]]:[t,r?.creates?.length&&typeof s=="string"&&!e.has(s)?{...o,id:0}:o]}var Sd=(n,e)=>`\u2248${gf(n.map(t=>yf(t,e)))}`;function Rd(n,e,t){let r=bf(n,t);return[e,...e.map(o=>[o])].map(o=>r.get(Sd(o,t))).find(Boolean)}function bf(n,e){let t=dn(n),r=new Map(n.map(s=>[s.id,s])),o=new Map,i=new Map;for(let s of n)s.lineage?.suggestion!==void 0&&s.lineage.items&&i.set(s.lineage.suggestion,[...i.get(s.lineage.suggestion)??[],...s.lineage.items]);for(let s of n){let a=s.undoes!==void 0&&!t.has(s.id)&&!s.withheld?r.get(s.undoes):void 0;if(a?.suggests&&a.author.kind===s.author.kind&&a.author.id===s.author.id)continue;let d=a?.suggests?a.suggests.filter((l,u)=>!i.get(a.id)?.includes(u)):a?.mutation&&(a.lineage||s.undoneLineage)?[a.mutation]:[];if(d.length>0)for(let l of[d,...d.map(u=>[u])])o.set(Sd(l,e),s)}return o}function $d(n,e,t,r,o={}){let i=o.declaration!==!1,s=(a,d)=>`${r} may not ${a}: ${d}.`;for(let a of t){let d="edge"in a?a.edge:void 0,l=(d?[d.from,d.to]:["id"in a?a.id:a.node.id]).map(u=>e.getNode(u)??("node"in a?a.node:void 0));for(let u of l){if(!u)continue;if(xd(u))return s(`change \u201C${K(n.tryDefinition(u.kind),u)}\u201D`,"a person said to leave it alone");if(!i)continue;let p=kd(n,u.kind);if(p==="never")return s(`change ${ue(n,u.kind)} on its own`,"the app says they are never tidied");if(d&&p==="no-links")return s(`link or unlink ${ue(n,u.kind)} on its own`,"the app says they are never linked automatically")}if(d&&i&&l[0]&&kd(n,l[0].kind,d.kind)==="never")return s(`${a.op==="add-edge"?"make":"break"} a \u201C${d.kind}\u201D link on its own`,"the app says that relation is never tidied")}}function vf(n,e){if(!e||n.length===0)return null;let t=e.roles,r=o=>t?o.wouldNeed.some(i=>t.includes(i)):o.wouldNeed.length>0;return n.every(({refusal:o})=>r(o))?e:null}var ur={scene:0,overview:10,rail:20,popover:30,dialog:40,toast:50},wf={plots:0,stage:1,tag:2,ties:2,lines:3,tieLabels:4,occupants:6,seatMarks:7,zoom:8,card:10,opened:11},kf={under:0,raised:1,over:2},Wo=n=>`--graview-layer-${n}`,xf=n=>`var(${Wo(n)}, ${ur[n]})`;function Sf(){return Object.keys(ur).map(n=>` ${Wo(n)}: ${ur[n]};`).join(`
|
|
4
|
+
`)}function Rf(n){let e=n.onBehalfOf??n;return{kind:e.kind,...e.id!==void 0?{id:e.id}:{},...e.name!==void 0?{name:e.name}:{},...e.roles!==void 0?{roles:e.roles}:{}}}function Ad(){return`sub_${(globalThis.crypto?.randomUUID?.()??`${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`).replace(/-/g,"").slice(0,20)}`}function Od(n){return{...n,id:n.id??Ad(),at:n.at??new Date().toISOString()}}function $f(n=[]){let e=[...n],t=new Set,r=()=>{for(let o of t)o()};return{list:o=>o===void 0?e:e.filter(i=>i.who.id===o),add(o){let i=Od(o);return e=[...e.filter(s=>s.id!==i.id),i],r(),i},remove(o){let i=e.length;e=e.filter(a=>a.id!==o);let s=e.length<i;return s&&r(),s},onChange(o){return t.add(o),()=>t.delete(o)}}}var qo=(n,e)=>`${n}\0${e}`,_d=new WeakMap;function Af(n,e){let t=new Map;for(let[o,i]of Object.entries(e??{}))for(let[s,a]of Object.entries(i))t.set(qo(o,s),[{seq:n-1,by:a}]);return{base:n,end:n,read:[],fields:t,written:[],seqOf:new Map,writers:{writerAt:(o,i,s)=>{let a=t.get(qo(o,i));if(!a)return;let d=0,l=a.length;for(;d<l;){let u=d+l>>1;a[u].seq<s?d=u+1:l=u}return d===0?void 0:a[d-1].by}}}}function Of(n){if(n.op==="add-node")return[n.node.id,Object.keys(n.node).filter(e=>e!=="id"&&e!=="kind")];if(n.op==="patch-node")return[n.id,Object.keys(n.after).filter(e=>!qe(n.after[e]))];if(n.op==="splice-text")return[n.id,[n.field]]}function _f(n,e){let t=n.end,r=z(e.author).id,o=e.undoes!==void 0?n.seqOf.get(e.undoes):void 0,i=[];for(let s of e.primitives){let a=Of(s);if(!a)continue;let[d,l]=a;for(let u of l){let p=e.undoes===void 0?r:o!==void 0?n.writers.writerAt(d,u,o):void 0,c=qo(d,u),f=n.fields.get(c);f||n.fields.set(c,f=[]),f.push({seq:t,by:p}),i.push(c)}}n.written.push({seq:t,keys:i}),n.seqOf.set(e.id,t),n.read.push(e),n.end++}function Pf(n,e){for(;n.written.length>0&&n.written.at(-1).seq>=e;){let{keys:t}=n.written.pop();for(let r of t)n.fields.get(r)?.pop()}for(let t of n.read.slice(e-n.base))n.seqOf.delete(t.id);n.read.length=e-n.base,n.end=e}function vt(n){let e=n.all(),t=typeof n.length=="number"?n.length:e.length,r=t-e.length,o=_d.get(n);if(o&&o.base<=r&&r<=o.end){let i=Math.min(o.end,t);for(;i>r&&e[i-1-r]!==o.read[i-1-o.base];)i--;i===r&&r>o.base&&i<o.end?o=void 0:(i<o.end&&Pf(o,i),r>o.base&&(o.read=o.read.slice(r-o.base),o.base=r))}else o=void 0;o||_d.set(n,o=Af(r,r>0?[...n.epochs?.()??[]].reverse().find(i=>i.horizon)?.writers:void 0));for(let i=o.end;i<t;i++)_f(o,e[i-r]);return o.writers}function Pd(n,e,t,r){let o=vt(n),i={};for(let s of t)for(let a in s){if(!Object.hasOwn(s,a)||a==="id"||a==="kind"||!r(s[a]))continue;let d=o.writerAt(s.id,a,e);d!==void 0&&((i[s.id]??={})[a]=d)}return i}var cn={served:new WeakSet},wt=n=>n.fields!==void 0||(n.hide?.length??0)>0,Ed=(n,e,t)=>(n??[]).some(r=>r.kinds.includes(e)&&(r.hide?.includes(t)===!0||r.fields!==void 0&&!r.fields.includes(t))),Md=(n,e,t,r)=>Object.entries(t).some(([o,i])=>typeof i=="string"&&i.trim()!==""&&n.includes(i.trim())&&r(e,o)),Ce=n=>cn.on===!0||cn.served.has(n);var Ho=new WeakMap;function Ef(n,e){let t=new Map(Object.entries(e?.removed??{})),r=new Map(Object.entries(e?.creators??{})),o=n===0||e?.removed!==void 0;return{base:n,end:n,read:[],kinds:t,creators:r,entries:[],records:{kindOf:i=>t.get(i),creatorOf:i=>r.get(i),knowsAll:o}}}function Mf(n,e){let t=n.end;for(let r of e.primitives){if(r.op!=="add-node"&&r.op!=="remove-node")continue;let{id:o,kind:i}=r.node;if(n.kinds.has(o)||(n.kinds.set(o,i),n.entries.push({seq:t,id:o,creator:!1})),r.op!=="add-node"||n.creators.has(o)||e.undoes!==void 0)continue;let s=z(e.author).id;s!==void 0&&(n.creators.set(o,s),n.entries.push({seq:t,id:o,creator:!0}))}n.read.push(e),n.end++}function Nf(n,e){for(;n.entries.length>0&&n.entries.at(-1).seq>=e;){let t=n.entries.pop();(t.creator?n.creators:n.kinds).delete(t.id)}n.read.length=e-n.base,n.end=e}function he(n){let e=n.all(),t=typeof n.length=="number"?n.length:e.length,r=t-e.length,o=Ho.get(n);if(o&&o.base<=r&&r<=o.end){let i=Math.min(o.end,t);for(;i>r&&e[i-1-r]!==o.read[i-1-o.base];)i--;i===r&&r>o.base&&i<o.end?o=void 0:(i<o.end&&Nf(o,i),r>o.base&&(o.read=o.read.slice(r-o.base),o.base=r))}else o=void 0;o||Ho.set(n,o=Ef(r,r>0?zf(n,r):void 0));for(let i=o.end;i<t;i++)Mf(o,e[i-r]);return o.records}function zf(n,e){let t=[...n.epochs?.()??[]].reverse().find(r=>r.horizon);return t?.seq===e?t:void 0}function Nd(n,e,t){he(n);let r=Ho.get(n),o=[new Set,new Set];for(let a=r.entries.length-1;a>=0&&r.entries[a].seq>=e;a--)o[+r.entries[a].creator].add(r.entries[a].id);let i={},s={};for(let[a,d]of r.creators)o[1].has(a)||(i[a]=d);for(let[a,d]of r.kinds)!o[0].has(a)&&!t(a)&&(s[a]=d);return r.records.knowsAll?{creators:i,removed:s}:{creators:i}}function Dn(n,e,t,r,o,i=cn.on===!0){if(!n?.sees?.length||Z(e))return!0;let s=n.sees.filter(a=>a.kinds.includes(t.kind)&&(i||!wt(a)));return s.length===0?!1:(e=z(e),s.some(a=>{if(!ye(a,e))return!1;if(!a.own&&!a.via)return!0;let d=e.id;if(d===void 0)return!1;let l=u=>u.id===d;return a.via?r.out(t.id,a.via).some(l)||r.in(t.id,a.via).some(l):t.id===d||r.out(t.id).some(l)||r.in(t.id).some(l)||o?.creatorOf(t.id)===d}))}var Id=Symbol.for("@graview/core:node-ref"),zd=n=>typeof n=="object"&&n!==null?n[Id]:void 0;function Ze(n="*"){return If(F().check(tt(1)),n)}function If(n,e){let t=Object.freeze(e==="*"?["*"]:[...e]),r=o=>{o&&Object.defineProperty(o,Id,{value:t,enumerable:!0,configurable:!0})};return r(n),r(L(n)),n}function kt(n){if(typeof n!="object"||n===null)return;let e=zd(n);if(e)return e;let t=L(n),r=zd(t);if(r)return r;let o=t?.innerType;return o?kt(o):void 0}function xt(n){let e=n.shape;if(!e)return[];let t=[];for(let[r,o]of Object.entries(e)){let i=kt(o);i&&t.push({name:r,kinds:i,optional:o.safeParse(void 0).success})}return t}var Yo=new Set;function lr(n,e){return Z(e)?Yo:n.modules?.disabledKinds??Yo}function un(n,e){return Z(e)?!1:(n.policy?.sees?.length??0)>0||lr(n,e).size>0}function Fd(n,e){if(!un(n,e))return()=>!0;let t=n.modules?.disabledKinds??Yo,r=n.policy?.sees??[],o=z(e),i=Ce(n),s=u=>!t.has(u)&&(r.length===0||r.some(p=>p.kinds.includes(u)&&ye(p,o)&&!p.own&&!p.via&&(i||!wt(p)))),a=n.schema.kinds.every(s),d=u=>s(u)&&Tf(n.schema,u).every(p=>p.every(c=>c==="*"?a:s(c))),l=a&&n.schema.kinds.every(d);return u=>l||u!==void 0&&d(u)}function St(n,e){return t=>{let r=lr(n,e);if(!n.policy?.sees?.length&&r.size===0)return!0;let o=he(n.log),i=n.graph.getNode(t);if(i)return!r.has(i.kind)&&Dn(n.policy,e,i,n.graph,o,Ce(n));let s=o.kindOf(t)??Ld(n,o,t);return s===void 0?!0:!r.has(s)&&Dn(n.policy,e,{id:t,kind:s},{out:()=>[],in:()=>[]},o,Ce(n))}}function Tf(n,e){let t=n?.tryDefinition?.(e)?.fields?.shape??{};return Object.values(t).flatMap(r=>{let o=kt(r);return o&&r.safeParse?.(void 0).success===!1?[o]:[]})}var jf={out:()=>[],in:()=>[]};function Ld(n,e,t){if(e.knowsAll||cn.served.has(n))return;let r=t.indexOf(":");if(r<=0)return;let o=t.slice(0,r);return n.schema?.tryDefinition(o)?o:void 0}function Df(n,e,t=new Map,r){let o=lr(n,e);if(!n.policy?.sees?.length&&o.size===0)return()=>!0;let i=he(n.log);return s=>{let a=t.get(s);if(a!==void 0)return a;let d,l=n.graph.getNode(s);if(l)d=!o.has(l.kind)&&Dn(n.policy,e,l,n.graph,i,Ce(n));else{let u=i.kindOf(s)??Ld(n,i,s);if(u===void 0)return r?.add(s),!0;d=!o.has(u)&&Dn(n.policy,e,{id:s,kind:u},jf,i,Ce(n))}return t.set(s,d),d}}function Ff(n){let e=new Map;return(t,r)=>{let o=`${t}\0${r}`,i=e.get(o);if(i===void 0){let s=n?.tryDefinition(t)?.fields?.shape,a=s?.[r];i=s!==void 0&&(a===void 0||a.safeParse?.(void 0).success===!0),e.set(o,i)}return i}}function fr(n,e){return Cd(n,e).lens}var Xo=()=>({judged:new Map,shown:new Map});function Cd(n,e){let t=Ff(n.schema),r=Z(e)?void 0:z(e).id,o=()=>n.log.length??n.log.all().length,i=new WeakMap,s=n.graph,a=(u,p,c,f,g)=>{let h=(v,R)=>{if(!u(v.id))return;let S;for(let M in v)if(!(!Object.hasOwn(v,M)||M==="id"||M==="kind"||!C(v[M],u))&&!(r!==void 0&&R(M)===r)){if(!t(v.kind,M))return;(S??=[]).push(M)}if(!S)return v;let k=S.join("\0"),_=i.get(v);if(_?.without===k)return _.node;let P=Object.fromEntries(Object.entries(v).filter(([M])=>!S.includes(M)));return i.set(v,{without:k,node:P}),P},y=v=>{let R=c();return h(v,S=>p().writerAt(v.id,S,R))},b=new WeakMap,x=g?v=>{let R=b.get(v);return R||b.set(v,R={node:y(v)}),R.node}:y,$=v=>{if(!u(v))return!1;let R=s.getNode(v);return R===void 0||x(R)!==void 0},w=g?.shown??new Map,O=g?v=>{let R=w.get(v);return R===void 0&&w.set(v,R=$(v)),R}:$,A=s.outEdges&&s.inEdges?{present:{getNode:v=>s.getNode(v),outEdges:v=>s.outEdges(v),inEdges:v=>s.inEdges(v)},log:n.log,get writers(){return p()}}:void 0,m={sees:u,shows:O,served:x,servedWith:h,optional:t,kindOf:f,...r!==void 0?{actor:r}:{},...A?{timeline:A}:{},hides:()=>un(n,e),pin:g?()=>m:()=>d(Xo())};return cn.lens?.(m,n,e)??m};function d(u){let p,c=o(),f=he(n.log);return a(Df(n,e,u.judged,u.unnamed),()=>p??=vt(n.log),()=>c,g=>s.getNode(g)?.kind??f.kindOf(g),u)}return{lens:a(St(n,e),()=>vt(n.log),o,u=>s.getNode(u)?.kind??he(n.log).kindOf(u)),pinWith:d}}var Td=new WeakMap,jd=new WeakMap,Lf=n=>{let e=new Set;for(let t of n)for(let r of t.primitives)r.op==="add-node"||r.op==="remove-node"?e.add(r.node.id):r.op==="patch-node"||r.op==="splice-text"?e.add(r.id):(e.add(r.edge.from),e.add(r.edge.to));return e};function Zd(n,e){if(!un(n,e))return n.log.all();let t=n.log.all(),r=n.log.length??t.length,o=r-t.length,i=[...lr(n,e)].sort().join("\0"),s=Gd(e),a=Td.get(n.log);a||Td.set(n.log,a=new Map);let d=a.get(s),{pinWith:l}=Cd(n,e),u=jd.get(n.log);u||jd.set(n.log,u=new Set);let p=d!==void 0&&d.horizon===o&&d.off===i&&d.length<=r&&(d.length===o||t[d.length-1-o]===d.last);if(d&&p){if(d.length===r)return d.ops;let g=t.slice(d.length-o),h=l(Xo()),y=!0,b=Lf(g);for(let x of b){let $=d.judgments.judged.get(x),w=d.judgments.shown.get(x);if($!==void 0&&h.sees(x)!==$||w!==void 0&&h.shows(x)!==w){y=!1;break}}if(y){for(let x of b)if(u.has(x)){y=!1;break}}if(y){let x=[...d.ops,...Tn(g,l(d.judgments))],$={horizon:o,off:i,length:r,last:t.at(-1),ops:x,judgments:d.judgments};return a.set(s,$),x}}let c={...Xo(),unnamed:u},f=Tn(t,l(c));return a.set(s,{horizon:o,off:i,length:r,last:t.at(-1),ops:f,judgments:c}),f}function Cf(n,e,t){return(t.subjectId===void 0||!e(t.subjectId)||n.shows(t.subjectId))&&t.nodeIds.every(r=>!e(r)||n.shows(r))&&!C(t,n.sees)}function Qo(n,e){return{all:()=>n,undoneIds:()=>dn(n),epochs:e}}var Dd=new WeakMap;function Gd(n){let e=Z(n)?n:z(n);return`${n.kind}|${e.id??""}|${(e.roles??[]).join(",")}|${n.onBehalfOf?`for:${n.id??""}`:""}`}var Vd=(n,e)=>`${Gd(n)}@${e}`,Jo=(n,e)=>{let t=Reflect.get(n,e,n);return typeof t=="function"?t.bind(n):t},Zf=Symbol.for("@graview/core:seat");function we(n,e,t={}){if(Lo(n.publishing,e,t.as)){if(J.served)return J.served(n,e);throw new Error("Load @graview/core/publishing to serve a reader of an app that publishes.")}return Bd(n,e)}var Gf=()=>J.served!==void 0;function Kd(n){let e=Dd.get(n);return e||Dd.set(n,e=new Map),e}function Bd(n,e){if(!un(n,e))return n;let t=Vd(e,"head"),r=Kd(n),o=r.get(t);if(o)return o;let i=n.graph,s=fr(n,e),a=w=>{let O=S=>S===void 0?void 0:w.served(S),A=S=>O(S)!==void 0,m=S=>A(i.getNode(S));return{served:O,seenNode:A,seenId:m,seenEdge:S=>m(S.from)&&m(S.to)&&!C(S,w.sees),servedAll:S=>S.flatMap(k=>O(k)??[])}},{served:d,seenId:l}=a(s),u=()=>a(s.pin?.()??s),p=(w,O)=>{let A=vt(n.log),m=s.pin?.()??s,v=w.nodes.flatMap(S=>m.servedWith(S,k=>A.writerAt(S.id,k,O))??[]),R=new Set(v.map(S=>S.id));return{nodes:v,edges:w.edges.filter(S=>R.has(S.from)&&R.has(S.to)&&!C(S,m.sees))}},c=w=>{let{removed:O,writers:A,published:m,...v}=w,R=p(w.base,w.seq);if(!w.creators)return{...v,base:R};let S=new Set(R.nodes.map(_=>_.id)),k=Object.fromEntries(Object.entries(w.creators).filter(([_,P])=>S.has(_)&&!C(P,s.sees)));return{...v,base:R,creators:k}},f=w=>w&&c(w),g=()=>Zd(n,e),h=()=>Qo(g(),()=>n.log.epochs()),y=new Proxy(i,{get(w,O){switch(O){case"getNode":return A=>d(w.getNode(A));case"has":return l;case"allNodes":case"nodesOfKind":return(...A)=>u().servedAll(w[O](...A));case"count":return(...A)=>u().servedAll(w.nodesOfKind(...A)).length;case"allEdges":case"edgesOfKind":case"outEdges":case"inEdges":return(...A)=>w[O](...A).filter(u().seenEdge);case"out":case"in":case"neighbors":return(A,...m)=>{let v=u();return v.seenId(A)?v.servedAll(w[O](A,...m)):[]};case"snapshot":return()=>{let A=w.snapshot(),m=u();return{...A,nodes:m.servedAll(A.nodes),edges:A.edges.filter(m.seenEdge)}};case"size":{let A=u();return{nodes:A.servedAll(w.allNodes({archived:"all"})).length,edges:w.allEdges({archived:"all"}).filter(A.seenEdge).length}}default:return Jo(w,O)}}}),b=()=>{let w=g();return Uo(w,dn(w))},x=new Proxy(n.log,{get(w,O){switch(O){case"all":case"toJSON":return()=>[...g()];case"epochs":return()=>w.epochs().map(c);case"lastEpoch":return()=>f(w.lastEpoch());case"horizonEpoch":return()=>f(w.horizonEpoch());case"live":return()=>{let A=g(),m=dn(A);return A.filter(v=>!m.has(v.id))};case"get":return A=>g().find(m=>m.id===A);case"opsInBatch":return A=>g().filter(m=>m.batch===A);case"batches":return b;default:return Jo(w,O)}}}),$=new Proxy(n,{get(w,O){switch(O){case Zf:return{store:w,principal:e};case"graph":return y;case"log":return x;case"snapshot":return y.snapshot;case"batches":return b;case"canUndo":return A=>mt(h(),typeof A=="string"?[A]:A);case"violations":return A=>w.violations(A,y).filter(m=>Cf(s,v=>i.has(v),m));case"findings":return()=>w.findings().filter(A=>(A.id.includes("->")?A.id.split("->").map((v,R)=>R===0?v.slice(v.indexOf(":")+1):v):[A.id]).every(v=>!i.has(v)||l(v))&&!C(A,s.sees));case"wouldChange":return A=>w.wouldChange(A,e);case"preview":return(A,m,v)=>w.preview(A,m,{author:e,...v});case"seenBy":return(A,m)=>we(w,A,m);case"seenFor":return e;case"servedSeq":return w.servedSeq;case"checkpoint":return A=>f(w.checkpoint(A));default:return Jo(w,O)}}});return r.set(t,$),$}J.kit={seatView:Bd,viewsOf:Kd,viewKey:Vd,diff:Fe,reads:Lo};var ei=new Set;function ni(n,e){if(!n||e===void 0)return{enabled:new Set(Object.keys(n??{})),disabledKinds:ei,disabledMutations:ei,disabledInvariants:ei,administered:Ud(n,new Set(Object.keys(n??{})))};let t=new Set,r=a=>{if(!(t.has(a)||!(a in n))){t.add(a);for(let d of n[a]?.requires??[])r(d)}};for(let a of e)r(a);for(let[a,d]of Object.entries(n))d.required&&r(a);let o=new Set,i=new Set,s=new Set;for(let[a,d]of Object.entries(n))if(!t.has(a)){for(let l of d.kinds??[])o.add(l);for(let l of d.mutations??[])i.add(l);for(let l of d.invariants??[])s.add(l)}for(let a of t){let d=n[a];for(let l of d?.kinds??[])o.delete(l);for(let l of d?.mutations??[])i.delete(l);for(let l of d?.invariants??[])s.delete(l)}return{enabled:t,disabledKinds:o,disabledMutations:i,disabledInvariants:s,administered:Ud(n,t)}}function Ud(n,e){let t=new Map;for(let[r,o]of Object.entries(n??{}))e.has(r)&&o.visibility==="admin"&&t.set(r,o);return t}var Wd=new WeakMap;function ri(n){let e=Wd.get(n);if(e)return e;let t=new Map,r=new Map;for(let o of n.definitions){let i=o.derives;i&&(r.set(o.kind,i),t.set(i.from,[...t.get(i.from)??[],[o.kind,i]]))}return Wd.set(n,e={bySource:t,byKind:r}),e}var Fn=n=>ri(n).byKind.size>0;function qd(n,e,t){let r={archived:"all"};return(e.sourceEnd==="to"?n.out(t,e.via,r):n.in(t,e.via,r)).filter(o=>o.kind===e.from)}function Vf(n,e,t,r){let o={archived:"all"};return(t.sourceEnd==="to"?n.in(r,t.via,o):n.out(r,t.via,o)).filter(i=>i.kind===e)}var Hd=(n,e)=>JSON.stringify(n??null)===JSON.stringify(e??null);function ti(n,e){let t={},r={};for(let[o,i]of Object.entries(e)){let s=n[o];Hd(s,i)||(t[o]=s,r[o]=i)}return Object.keys(r).length>0?{op:"patch-node",id:n.id,before:t,after:r}:void 0}function pr(n,e,t,r={}){let{bySource:o,byKind:i}=ri(n);if(i.size===0)return[];let s=[],a=h=>{h&&(e.applyPrimitives([h]),s.push(h))},d=h=>e.getNode(h)?.kind,l=new Map,u=(h,y=!1)=>l.set(h,(l.get(h)??!1)||y),p=new Set(t.flatMap(h=>h.op==="remove-node"?[h.node.id]:[])),c=new Map,f=new Map;for(let h of t)if(h.op==="patch-node"&&i.has(d(h.id)??"")&&f.set(h.id,new Set([...f.get(h.id)??[],...Object.keys(h.after)])),h.op==="add-node"&&o.has(h.node.kind))u(h.node.id);else if(h.op==="patch-node"){let y=d(h.id);y&&o.has(y)&&(u(h.id,ge in h.after),c.set(h.id,new Set([...c.get(h.id)??[],...Object.keys(h.after)])))}else if(h.op==="add-edge"){let y=e.getNode(h.edge.from),b=e.getNode(h.edge.to);for(let[x,$]of[[y,b],[b,y]]){let w=$?i.get($.kind):void 0;x&&w&&w.via===h.edge.kind&&w.from===x.kind&&u(x.id)}}else if(h.op==="remove-edge"&&(p.has(h.edge.from)||p.has(h.edge.to))){let y=p.has(h.edge.from)?h.edge.from:h.edge.to,b=e.getNode(y===h.edge.from?h.edge.to:h.edge.from),x=b?i.get(b.kind):void 0,$=t.find(w=>w.op==="remove-node"&&w.node.id===y)?.node.kind;b&&x&&x.via===h.edge.kind&&x.from===$&&!me(b)&&a(ti(b,{[ge]:!0}))}for(let h of t){if(h.op!=="patch-node")continue;let y=e.getNode(h.id),b=y?i.get(y.kind):void 0;if(!y||!b)continue;let x=Object.keys(h.after).filter(m=>Object.hasOwn(b.back,m));if(x.length===0)continue;let $=qd(e,b,y.id);if($.length!==1)continue;let w=$[0],O={};for(let m of x){let v=b.back[m];if(c.get(w.id)?.has(v))continue;let R=y[m];n.tryDefinition(w.kind)?.fixed?.[v]===void 0&&(r.mayWriteBack&&!r.mayWriteBack(w,v,R)||(O[v]=R))}let A=ti(w,O);A&&(a(A),u(w.id))}let g=new Set;for(let[h,y]of l){if(g.has(h))continue;g.add(h);let b=e.getNode(h);if(b)for(let[x,$]of o.get(b.kind)??[])for(let w of Vf(e,x,$,b.id)){let O={...$.values(e,b,w)};if(!c.has(b.id))for(let m of f.get(w.id)??[])delete O[m];y&&(O[ge]=me(b)?!0:void 0);let A=ti(w,O);A&&(a(A),o.has(x)&&l.set(w.id,y))}}return s}function Jd(n,e,t){let{byKind:r}=ri(n);if(r.size===0)return[];let o=[];for(let i of t){let s=r.get(i.kind);if(!s)continue;let a=qd(e,s,i.id);if(a.length===1)for(let[d,l]of Object.entries(s.values(e,a[0],i))){let u=i[d];Hd(u,l)||o.push({id:i.id,source:a[0].id,field:d,holds:u,follows:l})}}return o}function Yd(n){return n.normalize("NFKD").replace(/\p{M}/gu,"").toLowerCase().trim().replace(/\s+/g," ")}var Rt=class{constructor(e){this.graph=e;for(let t of e.allNodes({archived:"all"}))this.file(t);e.subscribe(t=>this.follow(t))}kinds=new Map;filed=new Map;labelOf(e){return this.filed.get(e)?.label}lookup(e,t){let r=Yd(t);if(r.length===0)return{exact:[],prefix:[]};let o=e.includes("*")?[...this.kinds.values()]:e.flatMap(a=>this.kinds.get(a)??[]),i=[],s=[];for(let a of o)for(let d=oi(a.sorted,r);d<a.sorted.length&&a.sorted[d].startsWith(r);d+=1){let l=[...a.ids.get(a.sorted[d])??[]];s.push(...l),a.sorted[d]===r&&i.push(...l)}return{exact:i,prefix:s}}follow(e){for(let t of e.removedNodes)this.unfile(t.id);for(let t of e.changedNodes)this.unfile(t.after.id),this.file(t.after);for(let t of e.addedNodes)this.file(t)}file(e){let t=K(this.graph.schema.tryDefinition(e.kind),e),r=Yd(t);this.filed.set(e.id,{kind:e.kind,key:r,label:t});let o=this.kinds.get(e.kind);o||this.kinds.set(e.kind,o={ids:new Map,sorted:[]});let i=o.ids.get(r);i?i.add(e.id):(o.ids.set(r,new Set([e.id])),o.sorted.splice(oi(o.sorted,r),0,r))}unfile(e){let t=this.filed.get(e);if(!t)return;this.filed.delete(e);let r=this.kinds.get(t.kind),o=r?.ids.get(t.key);if(!r||!o||(o.delete(e),o.size>0))return;r.ids.delete(t.key);let i=oi(r.sorted,t.key);r.sorted[i]===t.key&&r.sorted.splice(i,1)}};function oi(n,e){let t=0,r=n.length;for(;t<r;){let o=t+r>>>1;n[o]<e?t=o+1:r=o}return t}function Kf(n,e){return e.includes("*")?"record":e.map(t=>X(n.tryDefinition(t),t)).join(" or ")}function Xd(n,e,t,r){let o=Kf(n,e.kinds);if(r.length===0)return{ok:!1,reason:"none",candidates:r,message:`There is no ${o} called "${t}".`};let i=r.slice(0,10).map(a=>`${a.label} (${a.id})`),s=r.length>i.length?`, and ${r.length-i.length} more`:"";return{ok:!1,reason:"ambiguous",candidates:r,message:`"${t}" names more than one ${o}: ${i.join(", ")}${s}. Pass the id of the one you mean as ${e.name}.`}}function ii(n){if(n===null||typeof n!="object")return JSON.stringify(n)??"null";if(Array.isArray(n))return`[${n.map(r=>r===void 0?"null":ii(r)).join(",")}]`;let e=n;return`{${Object.keys(e).filter(r=>e[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${ii(e[r])}`).join(",")}}`}var Qd=(n,e)=>n.key<e.key?-1:n.key>e.key?1:0;function Bf(n){let e=n.nodes.map(r=>({key:r.id,value:r})).sort(Qd),t=n.edges.map(r=>({key:I(r),value:{kind:r.kind,from:r.from,to:r.to,id:r.id,data:r.data}})).sort(Qd);return ii({nodes:e.map(r=>r.value),edges:t.map(r=>r.value)})}function Ln(n){return`sha256:${nc(Bf(n))}`}function ec(n,e,t,r={}){let o=r.validate??!0,i=r.base??{nodes:[],edges:[]},s=Ln(t),a=H.from(n,i,{validate:o});for(let[h,y]of e.entries())try{a.applyPrimitives(y.primitives)}catch(b){let x=e[h-1];return{ok:!1,expected:Ln(a.snapshot()),actual:s,...x?{divergedAfter:x.id}:{},reason:`The log does not fold: op "${y.id}" (${y.intent}) could not be applied. ${b instanceof Error?b.message:String(b)}`}}let d=Ln(a.snapshot());if(d===s)return{ok:!0,hash:s};let l=h=>{let y=H.from(n,i,{validate:o});for(let b=0;b<=h;b++)y.applyPrimitives(e[b].primitives);return Ln(y.snapshot())},u=h=>{try{let y=H.from(n,t,{validate:o});for(let b=e.length-1;b>h;b--)y.applyPrimitives(Je(e[b]));return Ln(y.snapshot())}catch{return}},p=h=>{let y=u(h);return y!==void 0&&y!==l(h)},c=-1,f=e.length-1;for(;c<f;){let h=Math.floor((c+f)/2);p(h)?f=h:c=h+1}let g=f>=0?e[f]:void 0;return{ok:!1,expected:d,actual:s,...g?{divergedAfter:g.id}:{},reason:g?`The graph and the fold of its log part after op "${g.id}" (${g.intent}).`:"The graph and the fold of its log disagree before any op: the base it folds from does not match."}}var Uf=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Wf=new TextEncoder,qf=new Uint32Array(64),Hf=new Uint32Array(8),hr=Array.from({length:256},(n,e)=>e.toString(16).padStart(2,"0"));function nc(n){let e=Wf.encode(n),t=e.length*8,r=new Uint8Array(e.length+9+63>>6<<6);r.set(e),r[e.length]=128;let o=new DataView(r.buffer);o.setUint32(r.length-8,Math.floor(t/2**32)),o.setUint32(r.length-4,t>>>0);let i=Hf;i[0]=1779033703,i[1]=3144134277,i[2]=1013904242,i[3]=2773480762,i[4]=1359893119,i[5]=2600822924,i[6]=528734635,i[7]=1541459225;let s=qf;for(let d=0;d<r.length;d+=64){for(let b=0;b<16;b++)s[b]=o.getUint32(d+b*4);for(let b=16;b<64;b++){let x=s[b-15],$=s[b-2],w=(x>>>7|x<<25)^(x>>>18|x<<14)^x>>>3,O=($>>>17|$<<15)^($>>>19|$<<13)^$>>>10;s[b]=s[b-16]+w+s[b-7]+O>>>0}let l=i[0],u=i[1],p=i[2],c=i[3],f=i[4],g=i[5],h=i[6],y=i[7];for(let b=0;b<64;b++){let x=(f>>>6|f<<26)^(f>>>11|f<<21)^(f>>>25|f<<7),$=f&g^~f&h,w=y+x+$+Uf[b]+s[b]>>>0,O=(l>>>2|l<<30)^(l>>>13|l<<19)^(l>>>22|l<<10),A=l&u^l&p^u&p,m=O+A>>>0;y=h,h=g,g=f,f=c+w>>>0,c=p,p=u,u=l,l=w+m>>>0}i[0]=i[0]+l>>>0,i[1]=i[1]+u>>>0,i[2]=i[2]+p>>>0,i[3]=i[3]+c>>>0,i[4]=i[4]+f>>>0,i[5]=i[5]+g>>>0,i[6]=i[6]+h>>>0,i[7]=i[7]+y>>>0}let a="";for(let d=0;d<8;d++){let l=i[d];a+=hr[l>>>24]+hr[l>>>16&255]+hr[l>>>8&255]+hr[l&255]}return a}var $t=class{constructor(e){this.inner=e}seen=new Set;reads(){return[...this.seen]}markAll(e){for(let t of e)this.seen.add(t.id);return e}markEdges(e){for(let t of e)this.seen.add(t.from),this.seen.add(t.to);return e}getNode(e){return this.seen.add(e),this.inner.getNode(e)}has(e){return this.seen.add(e),this.inner.has(e)}allNodes(e){return this.markAll(this.inner.allNodes(e))}allEdges(e){return this.markEdges(this.inner.allEdges(e))}nodesOfKind(e,t){return this.markAll(this.inner.nodesOfKind(e,t))}edgesOfKind(e,t){return this.markEdges(this.inner.edgesOfKind(e,t))}out(e,t,r){return this.seen.add(e),this.markAll(this.inner.out(e,t,r))}in(e,t,r){return this.seen.add(e),this.markAll(this.inner.in(e,t,r))}neighbors(e,t){return this.seen.add(e),this.markAll(this.inner.neighbors(e,t))}};function Jf(n,e){return{...e,name:n}}function si(n){if(!n.creates?.length)return!1;let e=n.input.shape;return e===void 0||!("id"in e)}function ic(n){let e=n.input,t=e._zod?.def;if(t?.type!=="object"||t.catchall!==void 0||!e.shape)return;let r=Object.keys(e.shape);return si(n)?[...r,"id"]:r}var tc=(n,e,t={})=>{let r=n.filter(s=>t[s]?.length),o=n.filter(s=>!t[s]?.length);return`${[...o.length>0?[`does not take ${o.map(s=>`"${s}"`).join(", ")}`]:[],...r.map(s=>`${s} is set by ${t[s].join(" or ")}`)].join("; ")}; it takes ${e.length>0?e.map(s=>`"${s}"`).join(", "):"nothing"}`};function Yf(n){let e=n?._zod?.def;for(let t=0;e?.innerType&&t<8;t++)e=e.innerType._zod?.def;return e}var Xf=/^-?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;function sc(n,e){let t=n?.shape;if(!t||typeof e!="object"||e===null||Array.isArray(e))return e;let r;for(let[o,i]of Object.entries(e)){if(typeof i!="string"||!Xf.test(i)||Yf(t[o])?.type!=="number")continue;let s=Number(i);Number.isFinite(s)&&(r??={...e},r[o]=s)}return r??e}var ac=n=>typeof n=="string"&&n.length<=200&&/^[^\s\p{Cc}]+$/u.test(n);function Qf(n){if(typeof n!="object"||n===null)return;let e=n.id;if(e!==void 0){if(!ac(e))throw new N("An id is 1\u2013200 characters with no space",`Got ${JSON.stringify(e)}.`);return e}}function ep(n){let{id:e,...t}=n;return t}function rc(n){return n.normalize("NFKD").replace(/\p{M}/gu,"").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"")||"item"}function ai(n){let e=2166136261;for(let t=0;t<n.length;t++)e=Math.imul(e^n.charCodeAt(t),16777619);return(e>>>0).toString(36).padStart(7,"0")}function np(n,e){if(e.limited&&e.me===void 0)return oc(n,e.held);let t=e.limited?`${n}.${ai(e.me)}`:n,r=t;for(let o=2;e.seen(r);o++)r=`${t}-${o}`;return e.held(r)?oc(t,e.held):r}function oc(n,e){let t;do t=`${n}-${Math.floor(Math.random()*36**6).toString(36).padStart(6,"0")}`;while(e(t));return t}function Cn(n,e,t,r={}){let o=si(e)?Qf(t):void 0,i=sc(e.input,o===void 0?t:ep(t)),s=ic(e);if(s&&typeof i=="object"&&i!==null&&!Array.isArray(i)){let m=Object.keys(i).filter(v=>!s.includes(v)&&i[v]!==void 0);if(m.length>0)throw new ve(e.name,[{path:[],message:tc(m,s,e.writtenBy)}])}let a=e.clearable&&typeof i=="object"&&i!==null&&!Array.isArray(i)?e.clearable.filter(m=>i[m]===null):[],d=e.input.safeParse(a.length>0?Object.fromEntries(Object.entries(i).filter(([m])=>!a.includes(m))):i);if(d.success)for(let m of a)d.data[m]=null;if(!d.success){let m=Object.keys(e.input.shape??{});throw new ve(e.name,d.error.issues.map(v=>v.code==="unrecognized_keys"&&m.length>0?{...v,message:tc(v.keys,m,e.writtenBy)}:v))}let l=d.data,u=new $t(r.seen??n),p=[],c=new Set,f=r.me===void 0?void 0:`.${ai(r.me)}`,g=m=>!r.seesInFull||r.seesInFull()||f!==void 0&&new RegExp(`\\${f}(-[0-9a-z]+)?$`).test(m),h=m=>u.has(m)||n.has(m)||c.has(m)||r.everHeld?.(m)===!0,y,b=m=>{let v=new Set([...n.outEdges(m),...n.inEdges(m)]);for(let R of v)u.getNode(R.from),u.getNode(R.to),p.push({op:"remove-edge",edge:R});return v},x={graph:u,schema:n.schema,me:r.me,emit(m){p.push(m)},addNode(m){p.push({op:"add-node",node:m})},removeNode(m){let v=u.getNode(m)&&n.getNode(m);if(!v)throw new q(m,`Cannot remove missing node "${m}"`);b(m),p.push({op:"remove-node",node:v})},patchNode(m,v){let R=u.getNode(m)&&n.getNode(m);if(!R)throw new q(m,`Cannot patch missing node "${m}"`);let S={},k={};for(let[_,P]of Object.entries(v)){let M=R[_];JSON.stringify(M)===JSON.stringify(P)&&!r.keepUnchanged?.(P,_,R)||(S[_]=M,k[_]=P)}Object.keys(k).length!==0&&p.push({op:"patch-node",id:m,before:S,after:k})},archiveNode:m=>x.patchNode(m,{[ge]:!0}),unarchiveNode:m=>x.patchNode(m,{[ge]:void 0}),mergeNode(m,v){let R=u.getNode(v)&&n.getNode(v);if(!R)throw new q(v,`Cannot merge into missing node "${v}"`);if(m===v||me(R))throw new N(m===v?"Cannot merge a record into itself":"Cannot merge into an archived record");let S=new Set([...n.outEdges(v),...n.inEdges(v)].map(I));for(let k of b(m)){let _={...k,from:k.from===m?v:k.from,to:k.to===m?v:k.to};_.from!==_.to&&!S.has(I(_))&&(S.add(I(_)),p.push({op:"add-edge",edge:_}))}x.archiveNode(m),y=v},addEdge(m){p.push({op:"add-edge",edge:m})},removeEdge(m){p.push({op:"remove-edge",edge:m.id!==void 0&&n.linkById(m.id)||m})},setSingleSource(m,v,R){n.inEdges(v,m).some(S=>S.from===R)||p.push({op:"add-edge",edge:{kind:m,from:R,to:v}});for(let S of n.inEdges(v,m))u.getNode(S.from),S.from!==R&&p.push({op:"remove-edge",edge:S})},freshId(m,v,R){if(o!==void 0&&!c.has(o)){if(v&&!o.startsWith(`${v}:`)){let ne=o.includes(":")?o.slice(o.indexOf(":")+1):o;throw new N(`Id "${o}" does not say its kind: ask for "${v}:${ne||o}"`,`Every ${v} id starts "${v}:", the ones "${e.name}" mints and the ones a caller asks for alike, so a later call names it as it names the rest.`)}if(!g(o))throw new N(`"${e.name}" makes its own id here`,`Leave id out${f?`, or end it "${f}"`:""}.`);if(h(o))throw new N(`Id "${o}" is already taken`,`"${e.name}" was asked to make a node with that id, and the graph has or had one. Pick another, or leave id out and let the act mint one.`);return c.add(o),o}let S=r.hint;if(o===void 0&&!c.size&&ac(S)&&(!v||S.startsWith(`${v}:`))&&g(S)&&!h(S))return c.add(S),S;v&&r.keeps&&[l,R??{}].some(ne=>Md(m,v,ne,r.keeps))&&(m=v);let k=v?`${v}:${rc(m)}`:rc(m),_=r.seesInFull!==void 0&&!r.seesInFull(v),M=np(k,{seen:ne=>(r.seen?r.seen.has(ne):n.has(ne))||c.has(ne)||!_&&r.everHeld?.(ne)===!0,held:h,limited:_,me:r.me});return c.add(M),M}};if(e.apply(x,l),o!==void 0&&!c.has(o))throw new N(`"${e.name}" did not make a record with id "${o}": it names what it makes itself`);let $=r.check?.(p,e),w=new Set(p.flatMap(Re)),O=new $t(r.seen??n),A=e.describe?.(l,O)??`${e.name}(${Object.entries(l).map(([m,v])=>`${m}=${JSON.stringify(v)}`).join(", ")})`;return{primitives:p,reads:[...new Set([...u.reads(),...O.reads()])],...e.describe?{described:[...O.reads(),...$??[]]}:{},writes:[...w],intent:A,...y!==void 0?{mergedInto:y}:{},...c.size>0?{firstMinted:c.values().next().value}:{}}}function di(n,e,t,r,o,i){if(typeof r!="string"||typeof o!="string")return n.allowedOn===void 0;if(n.allowedOn)return n.allowedOn(t,r);let s=n.subject?.arg??"id",a=n.input.shape??{},d=t.getNode(r)?.[o],l={[s]:r,...o!==s&&o in a&&d!==void 0&&d!==null?{[o]:d}:{}},u=n.input.safeParse?.(l),p=u?.success?u.data:l,c=()=>{},f={graph:t,schema:e,me:i,addNode:c,removeNode:c,patchNode:c,archiveNode:c,unarchiveNode:c,mergeNode:c,addEdge:c,removeEdge:c,setSingleSource:c,freshId:(g,h)=>`${h?`${h}:`:""}${g}`,emit:c};try{n.apply(f,p)}catch(g){let h=g;return!(h?.name==="ActRefusal"&&h.reason!=="invalid")}return!0}var dc=Symbol.for("@graview/core:amount"),Qk=(n,e)=>(Object.defineProperty(L(n),dc,{value:e,enumerable:!0}),n);function ci(n,e=!0){let t=L(n);return t?.[dc]??(e&&t?.innerType?ci(t.innerType):void 0)}function cc(n,e={},t){let r=t===0?Math.round(n):Math.round(n*100)/100,o=Number.isInteger(r),i={maximumFractionDigits:o?0:2,minimumFractionDigits:o?0:2};try{return $e(r,e.locale,e.currency?{style:"currency",currency:e.currency,...i}:i)}catch{return $e(r,e.locale,i)}}function uc(n,{format:e,unit:t,currency:r,locale:o,places:i}){let s=/^[A-Z]{3}$/.test(t??"");return e==="money"||!e&&s?cc(n,{...o?{locale:o}:{},...(s?t:r)?{currency:s?t:r}:{}},i):e==="percent"?$e(n,o,{style:"percent",maximumFractionDigits:0}):$e(n,o)+(t?` ${t}`:"")}var tp=Symbol.for("@graview/core:typed-field");function ui(n){let e=L(n);return e?e[tp]??ui(e.innerType):void 0}var rp=/^[("'“‘]*(?:(?:[a-z]{1,3}\.){2,}|(?:dr|mr|mrs|ms|mx|st|mt|vs|jr|sr|prof|no|fig|approx)\.)$/i;function op(n){for(let e of n.matchAll(/[.!?](?=\s|$)/g)){let t=n.slice(0,e.index+1),r=/\S+$/.exec(t)?.[0]??"";if(!(e[0]==="."&&rp.test(r))&&!(t.split(" ").length<3&&e.index+1<n.length))return t}}function lc(n,e=140){let t=n.replace(/^[#>\s]+|\*\*|`|\](\([^)\s]*\))?|\[/gm,"").replace(/\s+/g," ").trim(),r=op(t);return r&&r.length<=e?r:t.length<=e?t:`${(t.slice(0,e+1).replace(/\s+\S*$/,"")||t.slice(0,e)).replace(/[\s,;:.—-]+$/,"")}\u2026`}function li(n){let e=n.fields.shape;return Object.keys(e).flatMap(t=>{let r=Yt(e[t])?ct(t):void 0;return r&&e[r]?[r]:[]})}var ip=[["skip","Skip this one","Leave one day out of the series; the rest stay as they are.","Skip {} on "],["detach","Change just this one","Make one day of the series a record of its own, to change apart from the rest.","Change {} only on "],["split","Change from here","End the series the day before, and start it again from that day with what changes.","Change {} from "]];function fc(n,e){let t=new Set(e.map(o=>o.name)),r=[];for(let o of n.definitions){let i=li(o);if(i.length===0)continue;let s=o.kind,a=o.fields.shape,d=At(n,e).get(s),l=new Set(o.keptInStep??[]),u=g=>(d?.get(g)?.length??0)>0&&!l.has(g),p=Ge(o).filter(g=>!u(g)),c=Object.fromEntries(Ge(o).filter(u).map(g=>[g,d.get(g)])),f=g=>K(o,g);for(let[g,h,y,b]of ip){let x=`${g}-${s}`;t.has(x)||r.push({name:x,derived:{kind:s,act:g},title:h,description:y,subject:{kinds:[s],arg:"id"},writes:i.map(En),...g==="skip"?{}:{creates:[s],...Object.keys(c).length>0?{writtenBy:c}:{}},input:_n({id:Ze([s]),on:F().check(rt(/^\d{4}-\d{2}-\d{2}$/,"a day, like 2026-10-21")),...i.length>1?{field:W(za(i))}:{},...g==="skip"?{}:Object.fromEntries(p.map($=>[$,W(a[$])]))}),describe:($,w)=>b.replace("{}",f(w.getNode(String($.id))??{id:$.id}))+Te(String($.on)),apply($,w){let O=$.graph.getNode(String(w.id)),A=String(w.field??i[0]),m=O?.[A],v=O?.[En(A)],R=String(w.on);if(typeof m!="string"||!Mn(v))throw new de(`${f(O??{id:w.id})} does not repeat`,"refused");let S=Pn(m,v,{from:R,to:R})[0];if(!S)throw new de(`${f(O)} does not fall on ${Te(R)}`,"refused");let k=String(O.id),_=Object.fromEntries(p.filter(V=>w[V]!==void 0).map(V=>[V,w[V]])),P=En(A),M=V=>{let bn=Object.fromEntries(Object.entries({...O,...V,..._}).filter(([ze,We])=>We!=null&&ze!=="id")),G=$.freshId(f(bn),s,bn);$.addNode({...bn,id:G,kind:s});for(let ze of Object.keys(o.edges??{}))for(let We of $.graph.out(k,ze))$.addEdge({kind:ze,from:G,to:We.id})};if(g!=="split"){$.patchNode(k,{[P]:{...v,except:[...new Set([...v.except??[],R])].sort()}}),g==="detach"&&M({[A]:S,[P]:null});return}if(Object.keys(_).length===0)throw new de(`Nothing to change: give ${f(O)} from ${Te(R)} something new`,"invalid");if(R<=m.slice(0,10))return $.patchNode(k,_);let ne=new Date(Date.parse(`${R}T00:00:00Z`)-864e5).toISOString().slice(0,10),Un=v.count?Pn(m,{...v,except:[]},{to:ne}).length:0,{count:Ne,except:yn,...Wn}=v,re=V=>yn?.some(V)?{except:yn.filter(V)}:{};$.patchNode(k,{[P]:{...Wn,until:ne,...re(V=>V<R),...Ne?{count:Un}:{}}}),M({[A]:S,[P]:{...Wn,...re(V=>V>=R),...Ne?{count:Ne-Un}:{},continues:k}})}})}}return r}function pc(n,e,t,r){if(n==="detach")return!0;if(n!=="split"||typeof e.on!="string")return!1;let o=t?.[String(e.field??r[0])];return typeof o!="string"||e.on>o.slice(0,10)}function hc(n,e){let t=new Set(e.map(a=>a.name)),r=e.filter(a=>!a.derived&&!a.creates?.length),o=(a,d,l,u)=>r.some(p=>{if(!(p[a]??[]).includes(l))return!1;let c=p.subject?.kinds;return c===void 0||c==="*"||c.includes(d)||u.to==="*"||c.some(f=>u.to.includes(f))}),i=[],s=(a,d)=>{let l=a.getNode(String(d));return l?K(n.tryDefinition(l.kind),l):String(d)};for(let a of n.definitions){let d=a.kind,l=Object.entries(a.edges??{}),u=p=>p.to==="*"?"record":p.to.map(c=>X(n.tryDefinition(c),c)).join(" or ");for(let[p,c]of l){let f=u(c),g=c.cardinality==="one",h=l.some(([w,O])=>w!==p&&u(O)===f),y=w=>B(w).toLowerCase(),b=bd(d,p,c,y),x={to:b&&"to"in b?b.to:f,from:X(a,d),one:g,also:b&&"also"in b?b.also:h&&!b?y(p):void 0},$=x.from;for(let w of Vo){let O=Ko(w,d,p);if(t.has(O)||c.acts==="none"||(w==="connect"?o("connects",d,p,c):o("severs",d,p,c)||c.appendOnly))continue;let{title:A,fromTheOtherEnd:m}=yd(w,x),v=c.description?`: ${c.description.replace(/\.$/,"")}`:"";i.push({name:O,derived:{kind:d,act:w,relation:p},title:A,fromTheOtherEnd:m,description:w==="connect"?`Link this ${$} to ${/^[aeiou]/i.test(f)?"an":"a"} ${f}${v}.${g?" It has one, so this replaces the one it has.":""}`:`Take away the link between this ${$} and ${/^[aeiou]/i.test(f)?"an":"a"} ${f}${v}. Undo puts it back.`,subject:{kinds:[d],arg:"id"},...w==="connect"?{connects:[p]}:{severs:[p],destructive:!0},idempotent:!0,input:_n({id:Ze([d]),to:Ze(c.to==="*"?"*":c.to)}),describe:(R,S)=>w==="disconnect"?`Unlink ${s(S,R.id)} from ${s(S,R.to)}`:g?`Set the ${f} of ${s(S,R.id)} to ${s(S,R.to)}`:`Link ${s(S,R.id)} to ${s(S,R.to)}`,apply(R,S){let k=String(S.id),_=String(S.to);for(let M of[k,_])if(!R.graph.getNode(M))throw new de(`there is no record "${M}"`,"invalid");let P=R.graph.out(k,p).some(M=>M.id===_);if(w==="disconnect"){if(!P)throw new de(`${s(R.graph,k)} is not linked to ${s(R.graph,_)}`,"invalid");R.removeEdge({kind:p,from:k,to:_});return}if(g)for(let M of R.graph.out(k,p))M.id!==_&&R.removeEdge({kind:p,from:k,to:M.id});P||R.addEdge({kind:p,from:k,to:_})}})}}}return i}function sp(n){let e=new Set(n.declared),t=[...new Set([...(n.paged??[]).filter(o=>e.has(o)),...n.declared])],r=(n.naming??[]).filter(o=>e.has(o));return[...new Set([...r,...t.filter(n.must),...t])]}var fi=n=>`\xA7${n}\xA7`;function ap(n,e){if(n.label)try{let r={id:fi(e.length),kind:n.kind};e.forEach((s,a)=>r[s]=fi(a));let o=String(n.label(r)),i=e.map((s,a)=>[s,o.indexOf(fi(a))]).filter(([,s])=>s>=0);if(i.length>0)return i.sort((s,a)=>s[1]-a[1]).map(([s])=>s)}catch{}let t=["name","title","label"].find(r=>e.includes(r));return t?[t]:[]}var gc=new WeakMap;function gr(n){let e=gc.get(n);if(e)return e;let t=n.fields.shape??{},r=Object.keys(t),o=n.display?.page,i=sp({declared:r,paged:[...o?.fields??[],...(o?.groups??[]).flatMap(s=>s.fields)],must:s=>t[s]?.safeParse?.(void 0).success===!1&&!Object.hasOwn(n.defaults??{},s),naming:ap(n,r)});return gc.set(n,i),i}function dp(n,e){let t=e.subject?.kinds,r=e.creates?.[0]??e.derived?.kind??(t!==void 0&&t!=="*"&&t.length===1?t[0]:void 0);return r===void 0?void 0:n.tryDefinition(r)}function cp(n,e){let t=Object.keys(e.input?.shape??{}),r=n?dp(n,e):void 0;if(!r)return t;let o=gr(r),i=d=>d!==e.subject?.arg&&o.includes(d),s=t.filter(i).sort((d,l)=>o.indexOf(d)-o.indexOf(l)),a=0;return t.map(d=>i(d)?s[a++]:d)}function pi(n,e,t=r=>r.name){let r=o=>{let i=e.indexOf(t(o));return i<0?e.length:i};return[...n].sort((o,i)=>r(o)-r(i))}function Ge(n){let e=n.fields.shape;return Object.keys(e).filter(t=>!(t in(n.fixed??{})))}function hi(n,e){let t=e.subject;return t?t.kinds==="*"?n.kinds:t.kinds:[]}function gi(n,e){let t=n.subject;if(!t||!n.writes&&n.creates?.length)return[];let r=new Set(Object.keys(e.fields.shape));if(n.writes)return n.writes.filter(s=>r.has(s));let o=n.input.shape??{},i=new Set(xt(n.input).map(s=>s.name));return Object.keys(o).filter(s=>s!==t.arg&&r.has(s)&&!i.has(s))}function At(n,e){let t=new Map,r=(o,i,s)=>{let a=t.get(o)??new Map;a.get(i)?.includes(s)||(a.set(i,[...a.get(i)??[],s]),t.set(o,a))};for(let o of e){for(let i of hi(n,o)){let s=n.tryDefinition(i);if(s)for(let a of gi(o,s))r(i,a,o.name)}for(let[i,s]of Object.entries(o.writesOther??{})){let a=n.tryDefinition(i)?.fields.shape;if(a)for(let d of s)d in a&&r(i,d,o.name)}}return t}function yc(n,e,t){let r=n.tryDefinition(t);if(!r)return[];let o=At(n,e).get(t);return Ge(r).filter(i=>!o?.has(i))}var mr=n=>`edit-${n}`;function yr(n,e,t){let r=n.tryDefinition(t);if(!r)return[];let o=new Set;for(let i of e)i.derived||((i.creates??[]).includes(t)&&o.add(i.name),hi(n,i).includes(t)&&gi(i,r).length>0&&o.add(i.name));return[...o]}function bc(n,e){let t=new Set(e.map(o=>o.name)),r=[];for(let o of n.definitions){let i=o.kind,s=mr(i);if(t.has(s))continue;let a=new Set((o.keptInStep??[]).filter(h=>Ge(o).includes(h))),d=yc(n,e,i),l=pi(Ge(o).filter(h=>d.includes(h)||a.has(h)),gr(o),h=>h);if(l.length===0)continue;let u=At(n,e).get(i),p=Object.fromEntries(Ge(o).flatMap(h=>!l.includes(h)&&u?.get(h)?.length?[[h,u.get(h)]]:[])),c=o.fields.shape,f=X(o,i),g=l.map(h=>Lt(o,h).toLowerCase());r.push({name:s,derived:{kind:i,act:"edit"},idempotent:!0,title:`Change the ${f}`,description:`Change what was set when this ${f} was made: ${g.join(", ")}.`,subject:{kinds:[i],arg:"id"},writes:l,...Object.keys(p).length>0?{writtenBy:p}:{},...l.some(h=>mc(c[h]))?{clearable:l.filter(h=>mc(c[h]))}:{},input:_n({id:Ze([i]),...Object.fromEntries(l.map(h=>[h,W(fp(c[h]))]))}),describe:(h,y)=>up(o,c,l,h,y),apply(h,y){let b={};for(let x of l){let $=y[x];$===null?b[x]=void 0:$!==void 0&&(b[x]=$)}if(Object.keys(b).length===0)throw new de(`Nothing to change \u2014 give at least one of ${g.join(", ")} a value.`,"invalid");h.patchNode(y.id,b)}})}return r}function up(n,e,t,r,o){let i=o.getNode(r.id),s=i?K(n,i):"a record",a=t.filter(d=>r[d]!==void 0).map((d,l)=>{let u=r[d],p=ct(d),c=p!==void 0&&p in e,f=Lt(n,c?p:d);return`the ${f===f.toUpperCase()?f:Ft(f)}${l===0?` of ${s}`:""} to ${c?u?`repeat ${lp(u)}`:"stop repeating":vc(n,e[d],d,u)}`});return a.length===0?`Changed nothing on ${s}`:`Changed ${a.length>1?`${a.slice(0,-1).join(", ")} and ${a.at(-1)}`:a[0]}`}var lp=n=>`every ${(n.interval??1)>1?`${n.interval} ${n.every}s`:n.every}`;function vc(n,e,t,r){if(r===null||r===""||Array.isArray(r)&&r.length===0)return"nothing";let o=n.display?.format?.[t];try{if(o)return String(o(r))}catch{}if(st(r).length>0)return st(r).map(i=>i.name).join(", ");if(at(e))return Array.isArray(r)&&r.length>1?`${r.length} linked records`:"a linked record";if(Array.isArray(r))return r.map(i=>vc(n,e,t,i)).join(", ");if(typeof r=="boolean")return r?"yes":"no";if(typeof r=="number"){let i=ci(e);return i?uc(r,i):ui(e)==="duration"?`${r>=60?`${Math.floor(r/60)} h `:""}${r%60||r<60?`${r%60} min`:""}`.trim():String(r)}if(typeof r!="string")return"a new value";if(Lr.test(r))return Te(r);if(It.test(r))return Zr(r);for(let i=L(e);i;i=L(i.innerType))if(i.type==="enum")return en(r);return`\u201C${lc(r,60)}\u201D`}function mc(n){return n._zod?.def?.type==="optional"}function fp(n){let e=n;for(let t=0;t<4;t++){let r=e._zod?.def;if((r?.type==="default"||r?.type==="prefault")&&r.innerType)e=r.innerType;else break}return e}function br(n,e){return n.filter(t=>!t.derived&&(t.creates??[]).includes(e)).map(t=>t.name)}function vr(n,e,t){if(!t.derived)return;let r=t.derived.act;return r==="edit"||r==="skip"||r==="detach"||r==="split"||r==="connect"||r==="disconnect"?yr(n,e,t.derived.kind):br(e,t.derived.kind)}function pp(n,e){let t=new Set(e.map(o=>o.name)),r=[];for(let o of n.definitions){let i=o.kind,s=X(o,i),a=(l,u)=>{let p=l.getNode(String(u));return p?K(o,p):String(u)},d=Ze([i]);for(let[l,u,p,c]of[["remove","Remove",`Remove the ${s}`,`Take this ${s} out of the graph, with every tie it has. Undo puts it back.`],["archive","Archive",`Archive the ${s}`,`Set this ${s} aside, with its ties and history kept.`],["unarchive","Bring back","Bring it back",`Bring this archived ${s} back.`],["merge","Merge",`Merge into another ${s}`,`The other takes this ${s}'s ties, and this one is archived.`],["leave-alone","Leave alone","Leave this one alone",`Nothing automated changes this ${s}: tidying passes it by until you allow it again.`],["allow-tidying","Allow tidying of","Allow tidying again",`Let tidying change this ${s} again.`]]){let f=`${l}-${i}`,g=l==="leave-alone"||l==="allow-tidying";t.has(f)||!g&&l!=="remove"&&o.archives===!1||g&&o.tidying==="never"||r.push({name:f,derived:{kind:i,act:l},title:p,description:c,subject:{kinds:[i],arg:"id"},...l==="remove"?{destructive:!0}:{},idempotent:!0,input:se(l==="merge"?{id:d,into:d}:{id:d}),describe:(h,y)=>{let b=l==="remove"&&y.getNode(String(h.id)),x=b?new Set(Object.values(b).flatMap(O=>st(O).map(A=>A.href))).size:0,$=l==="merge"&&a(y,h.id)===a(y,h.into),w=O=>$?`${a(y,O)} (${String(O)})`:a(y,O);return`${u} ${w(h.id)}${l==="merge"?` into ${w(h.into)}`:""}${x?` and its ${x} file${x>1?"s":""}`:""}`},apply:g?(h,y)=>h.patchNode(String(y.id),{[lt]:l==="leave-alone"?!0:void 0}):(h,y)=>h[`${l}Node`](y.id,y.into)})}}return r}function mi(n,e){return[...bc(n,e),...pp(n,e),...fc(n,e),...hc(n,e)]}var hp=n=>({$made:n}),wr=n=>typeof n=="object"&&n!==null&&Object.keys(n).join()==="$made"&&Number.isInteger(n.$made)&&n.$made>=0,gp=(n,e)=>Object.fromEntries(Object.entries(n.args??{}).map(([t,r])=>[t,Array.isArray(r)?r.map(e):e(r)])),yi=n=>Object.values(n.args??{}).some(e=>wr(e)||Array.isArray(e)&&e.some(wr)),wc=(n,e,t)=>({...n,args:gp(n,r=>{if(!wr(r))return r;let o=r.$made<t?e[r.$made]:void 0;if(o===void 0)throw new Error(`\u201C${n.name}\u201D names the record call ${r.$made+1} makes, and no call before it made that record.`);return o})});var mp=500,yp=120,bp=50,vp=200,wp=500,kp=200,kc=4e3,xp=["model","suggestion","interaction","actor","run","proposedBy"],bi=n=>typeof n=="string"&&n.length>0&&n.length<=yp,Sp=n=>typeof n=="string"&&n.length<=240&&n.lastIndexOf("#")>0&&n.lastIndexOf("#")<n.length-1,Rp=n=>{let e=JSON.stringify(n);return e===void 0?void 0:JSON.parse(e)};function ln(n){if(n===void 0)return;let e=n&&typeof n=="object"&&!Array.isArray(n)?n:{},t=typeof e.basis=="string"?e.basis.trim():"",r={basis:t},o=t!==""&&t.length<=mp;for(let i of Object.keys(e)){let s=e[i];i==="basis"||s===void 0||(i==="model"&&typeof s=="string"&&(s=s.trim()),i==="confidence"?o&&=typeof s=="number"&&s>=0&&s<=1:xp.includes(i)?o&&=bi(s):i==="evidence"?o&&=Array.isArray(s)&&s.length<=bp&&s.every(bi):i==="read"?o&&=Array.isArray(s)&&s.length<=vp&&s.every(Sp):i==="items"?o&&=Array.isArray(s)&&s.length>0&&s.length<=wp&&s.every(a=>Number.isInteger(a)&&a>=0):i==="voters"?o&&=Array.isArray(s)&&s.length<=kp&&s.every(bi):o&&=i!=="__proto__"&&i!=="constructor"&&i!=="prototype"&&(s=Rp(s))!==void 0,o&&(r[i]=s))}if(!o)throw new N("A lineage is { basis: 1 to 500 characters, confidence?: 0 to 1, model?, suggestion?, interaction?, actor?, run?, proposedBy?: 1 to 120 characters, evidence?: up to 50 ids, read?: up to 200 <id>#<field>, voters?: up to 200 ids, items?: up to 500 places }");if(JSON.stringify(r).length>kc)throw new N(`A lineage is at most ${kc} characters written out.`);return r}var Zn="keep-link";function xc(n){let e=(t,r)=>{let o=t.getNode(r);return o?K(n.tryDefinition(o.kind),o):r};return{name:Zn,title:"Keep this link",input:se({kind:F(),from:F(),to:F()}),describe:(t,r)=>`Keep the link from ${e(r,t.from)} to ${e(r,t.to)}`,apply(t,r){let{kind:o,from:i,to:s}=r;if(!t.graph.getNode(i)||!t.graph.getNode(s)){let d=I({kind:o,from:i,to:s});throw new q(d,`Cannot remove missing edge ${d}`)}let a=t.graph.edgesOfKind(o,{archived:"all"}).find(d=>d.from===i&&d.to===s)??{kind:o,from:i,to:s};t.removeEdge(a),t.addEdge(a)}}}var vi=(n,e)=>[...n].filter(t=>!t.derived&&t.name!==Zn&&typeof e=="string"&&(t.connects?.includes(e)||t.severs?.includes(e))).map(t=>t.name);var Ot="propose-changes",wi=500;function Sc(){return{name:Ot,title:"Propose changes",input:se({calls:Ea(se({name:F(),args:ot()})),intent:W(F())}),apply(){}}}var Rc=["kind-unknown","node-shape","edge-dangling","edge-disallowed","rule-error","rule-budget","derived-out-of-step"];function $c(n,e){let t=nr(n,e);return t&&[...t.fields].filter(Boolean)}function $p(n,e,t){return n.tryDefinition(e)?.fields?.shape?.[t]}function Gn(n,e){try{return K(n.tryDefinition(e.kind),e)}catch{return typeof e.label=="string"?e.label:"A record"}}var Ap=n=>`${n.kind}:${n.from}->${n.to}`,kr=(n,e)=>n<e?-1:n>e?1:0;function Ac(n,e,t={}){let{schema:r}=n,o=[],i=new Map;for(let c of e.nodes)i.has(c.id)||i.set(c.id,c);let s=c=>e.edges.filter(f=>f.from===c||f.to===c),a=c=>({action:"drop",primitives:[...s(c.id).filter(f=>i.has(f.from)&&i.has(f.to)).map(f=>({op:"remove-edge",edge:f})),{op:"remove-node",node:c}]}),d=new Set;for(let c of[...i.values()].sort((f,g)=>kr(f.id,g.id))){if(!r.tryDefinition(c.kind)){d.add(c.id),o.push({code:"kind-unknown",id:c.id,message:`${Gn(r,c)} is a kind of record this app no longer has`,repair:a(c)});continue}let f=$c(r,c);if(f===void 0)continue;let g=Gn(r,c),h=new Map,y=f.length>0;for(let b of f){if(b==="id"||b==="kind"){y=!1;continue}let x=$p(r,c.kind,b),$=x?x.safeParse(void 0):{success:!0,data:void 0},w=r.tryDefinition(c.kind)?.defaults;!$.success&&x&&w&&Object.hasOwn(w,b)&&($=x.safeParse(w[b])),$.success?$.data===void 0?h.set(b,{action:"clear",value:ce}):h.set(b,{action:"coerce",value:$.data}):y=!1}if(y){let b={...c};for(let[x,$]of h)$.value===ce?delete b[x]:b[x]=$.value;$c(r,b)!==void 0&&(y=!1)}if(f.length===0){o.push({code:"node-shape",id:c.id,message:`${g} does not fit what ${c.kind} declares`,repair:a(c)});continue}for(let b of f){let x=h.get(b),$=y&&x?{action:x.action,primitives:[{op:"patch-node",id:c.id,before:{[b]:c[b]===void 0?ce:c[b]},after:{[b]:x.value}}]}:a(c);o.push({code:"node-shape",id:c.id,detail:b,message:`${g}: ${B(b)} does not fit what ${c.kind} declares`,repair:$})}}let l=new Set,u=[];for(let c of[...e.edges].sort((f,g)=>kr(I(f),I(g)))){if(l.has(I(c)))continue;l.add(I(c));let f=Ap(c),g=i.get(c.from),h=i.get(c.to);if(!g||!h){o.push({code:"edge-dangling",id:f,message:"A link points at a record that is not there",repair:{action:"drop",primitives:[{op:"remove-edge",edge:c}]}});continue}u.push(c),!(d.has(g.id)||d.has(h.id))&&(r.edgeAllowed(c.kind,g.kind,h.kind)||o.push({code:"edge-disallowed",id:f,message:`${Gn(r,g)} \u2192 ${Gn(r,h)}: this app does not allow that link between them`,repair:{action:"drop",primitives:[{op:"remove-edge",edge:c}]}}))}let p=n.invariants??[];if(p.length>0){let c=H.from(r,{nodes:[...i.values()],edges:u},{validate:!1}),f=new Set,g;try{g=zn(c,p,t.invariantOptions??{})}catch{g=[{invariant:"rules",status:"could-not-judge",label:"The rules",message:"The rules could not be judged",nodeIds:[],repairs:[]}]}for(let h of g){let y=h.status==="could-not-judge"?"rule-error":h.status==="over-budget"?"rule-budget":void 0;if(!y)continue;let b=h.subjectId??h.invariant,x=`${y}|${b}|${h.invariant}`;f.has(x)||(f.add(x),o.push({code:y,id:b,detail:h.invariant,message:h.message}))}}if(Fn(r)){let c=H.from(r,{nodes:[...i.values()].filter(f=>!d.has(f.id)),edges:u},{validate:!1});for(let f of Jd(r,c,i.values())){let g=i.get(f.id),h=i.get(f.source);o.push({code:"derived-out-of-step",id:f.id,detail:f.field,message:`${Gn(r,g)}: ${B(f.field)} says ${JSON.stringify(f.holds??null)}, and it follows ${Gn(r,h)}, which works it out as ${JSON.stringify(f.follows??null)}`,repair:{action:"coerce",primitives:[{op:"patch-node",id:f.id,before:{[f.field]:f.holds===void 0?ce:f.holds},after:{[f.field]:f.follows===void 0?ce:f.follows}}]}})}}return o.sort((c,f)=>Rc.indexOf(c.code)-Rc.indexOf(f.code)||kr(c.id,f.id)||kr(c.detail??"",f.detail??""))}var _t=()=>globalThis.__graviewWatch;function Oc(n){_t()?.store?.(n)}function xr(n){n!==void 0&&_t()?.learn?.({ids:[n],words:[]})}function _c(n,e){_t()?.refused?.({...n,...e===void 0?{}:{author:e}})}function ki(n,e){let t=_t();if(!t?.refusedInput)return;let r=n.issues.map(o=>`${o.path.map(String).join(".")}: ${o.message}`).join("; ");t.refusedInput({mutation:n.mutation,message:r,...e===void 0?{}:{author:e}})}function Op(n,e){n instanceof ve&&ki(n,e)}function _p(n,e,t){_t()?.seat?.(n,e,t)}function Si(n,e){if(typeof n=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(n))return n;let t=new Date(n).getTime();if(Number.isNaN(t))throw new Error(`Not a day: ${String(n)}`);return te(e,t)}var xi=15*6e4;function Pc(n=Date.now(),e){let t=new Date(n).getTime(),r=Tt(e),o=te(r,t),i=new Date(Date.parse(`${o}T00:00:00Z`));if(i.setUTCDate(i.getUTCDate()+1),!r)return i.getTime()-t;let s=Ui(i.toISOString().slice(0,10),0,r);for(;te(r,s)===o;)s+=xi;for(;te(r,s-xi)!==o;)s-=xi;return s-t}function Pp(n,e){let t,r=()=>{t=setTimeout(()=>{let o=n.tick(new Date);r(),e?.(o)},Pc(Date.now(),n.timeZone)+1e3),t.unref?.()};return r(),()=>clearTimeout(t)}function Ri(n){let e=(n?.published?.length??0)>0;return{framework:Nn,formats:{...fe,snapshot:e?2:1}}}var Sr=class extends N{constructor(e){super(`This is the app as it stood${e.at?` at ${e.at}`:" at the start"}: the past is read, never changed`),this.name="PastError"}},$i="preview",T=(n,e)=>e===void 0?{}:{[n]:e},Ve={kind:"human"},Ec={kind:"system"},zc={kind:"system",id:"modules",name:"Modules"},Mc=n=>n.mutation===null&&n.undoes===void 0;function Ai(n,e){return`${n.invariant}|${n.subjectId??""}|${n.line||e?.has(n.invariant)?n.label:n.message}`}var Ep=new Set(["remove","archive","unarchive","merge"]),Mp={has:()=>!0},Ic=n=>new Set(n.filter(e=>e.shape).map(e=>e.name));function Tc(n,e,t){let r=Ic(n),o=p=>Ai(p,r),i=new Set(e.map(o)),s=new Set(t.map(o)),a=t.filter(p=>!i.has(o(p))),d=e.filter(p=>!s.has(o(p)));if(a.length===0||d.length===0)return{introduces:a,resolves:d};let l=p=>p.subjectId&&Ai(p,Mp),u=d.map(l);return{introduces:a.filter(p=>{let c=l(p)?u.indexOf(l(p)):-1;return c<0||(u[c]=null,!1)}),resolves:d.filter((p,c)=>u[c]!==null)}}var Vn=class extends Error{constructor(t,r){super(`Op "${t.id}" (${t.intent}) could not be applied: ${r instanceof Error?r.message:String(r)}`,{cause:r});this.op=t;this.name="ReceiveError"}},Rr=class extends N{constructor(t,r){let o=Bo(t,r);super(`Unknown mutation "${t}"${o?` \u2014 did you mean "${o}"?`:""}`,`Registered: ${r.join(", ")||"(none)"}`);this.mutation=t;this.name="UnknownMutationError",this.nearest=o}nearest},Nc=n=>new Map(n.map(e=>[e.id,e.batch]));function Np(){let n=globalThis.crypto,e=new Uint8Array(6);if(n?.getRandomValues)n.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return[...e].map(t=>t.toString(36).padStart(2,"0")).join("")}var Oi=class n{schema;graph;log;mutations=new Map;keeper;typer;voter;proposer;invariants;invariantOptions;policy;publishing;tidying;votes;intelligence;may=new Map;by;declaredModules;startingModules;projected;nextId;now;validate;mintBatch;batchTag;counter=0;opCount=0;quiet=0;rehearsing=!1;suggesting=!1;proposing=!1;ticked;timeZone;past;pastEvery;listeners=new Set;constructor(e){this.pastEvery=Math.max(1,e.pastEvery??64),this.past=e.past,this.schema=e.schema,this.invariants=e.invariants??[],this.invariantOptions=e.invariantOptions??{},this.timeZone=e.timeZone,this.timeZone&&(this.ticked={day:te(this.timeZone),on:te(this.timeZone)}),this.policy=e.policy,this.publishing=e.publishing,this.tidying=e.tidying,this.votes=e.votes,this.by=e.principal??Ve,this.intelligence=e.intelligence??[];for(let i of e.intelligence??[])i.may&&this.may.set(i.name,new Set(i.may));this.declaredModules=e.modules,this.startingModules=e.enabledModules,this.nextId=e.ids??(()=>`op${++this.opCount}`),this.now=e.now??(()=>new Date().toISOString()),this.validate=e.validate??!0;let t=Np();this.batchTag=e.batchIds?void 0:t,this.mintBatch=e.batchIds??(i=>`${i}:${t}:${++this.counter}`);for(let i of e.past?[]:e.mutations??[]){if(this.mutations.has(i.name))throw new N(`Duplicate mutation "${i.name}"`);this.mutations.set(i.name,i)}for(let i of e.past?[]:mi(e.schema,e.mutations??[]))this.mutations.set(i.name,i);!e.past&&!this.mutations.has(Zn)&&(this.keeper=xc(e.schema),this.mutations.set(Zn,this.keeper)),!e.past&&!this.mutations.has(yt)&&(this.voter=wd(),this.mutations.set(yt,this.voter)),!e.past&&!this.mutations.has(Ot)&&(this.proposer=Sc(),this.mutations.set(Ot,this.proposer));let r=T("horizon",e.horizon),o={validate:this.validate};if(e.log){this.log=jn.from(e.log,e.epochs,r);let i=this.log.lastEpoch();this.graph=e.snapshot?H.from(e.schema,e.snapshot,o):this.log.fold(e.schema,{...o,...i?{from:i}:{}})}else this.log=jn.from([],e.epochs??(e.snapshot?[{seq:e.horizon??0,base:e.snapshot}]:[]),r),this.graph=H.from(e.schema,e.snapshot??{nodes:[],edges:[]},o);e.past||(this.countPastTheLog(),Oc(this))}stillNow(){if(this.past)throw new Sr(this.past)}countPastTheLog(){this.countPast(this.log.all())}countPast(e){let t=r=>{let o=/(\d+)$/.exec(r);return o?Number(o[1]):0};for(let r of e)this.counter=Math.max(this.counter,t(r.batch)),this.opCount=Math.max(this.opCount,t(r.id));this.log.horizon>0&&(this.opCount=Math.max(this.opCount,this.log.length))}get servedSeq(){return this.log.length}get publishedSeq(){return J.seq?.(this)}get publisher(){return J.act?.(this,this.mutations)}get modules(){let e=this.log.all(),t=e.at(-1)?.id,r=this.projected;if(r&&r.length===e.length&&r.last===t)return r.projection;let o,i=0;r&&r.length<=e.length&&(r.length===0||e[r.length-1]?.id===r.last)&&(o=r.said,i=r.length);for(let a=e.length-1;a>=i;a--){let d=e[a].enabledModules;if(d!==void 0){o=d;break}}o??=this.log.horizonEpoch()?.enabledModules;let s=r&&o===r.said?r.projection:ni(this.declaredModules,o??this.startingModules);return this.projected={projection:s,length:e.length,last:t,said:o},s}setEnabledModules(e,t={}){this.stillNow();let r=this.modules.enabled,o=ni(this.declaredModules,e).enabled,i=[...r].filter(u=>!o.has(u)),s=[...o].filter(u=>!r.has(u));if(i.length===0&&s.length===0)return;let a=u=>u.map(p=>{let c=this.declaredModules?.[p]?.kinds??[];return c.length>0?c.map(f=>ue(this.schema,f)).join(", "):p}).join(", "),d=[i.length>0?`Turn off ${a(i)}`:"",s.length>0?`turn on ${a(s)}`:""].filter(Boolean).join("; "),l={id:this.nextId(),seq:this.log.length,batch:t.batch??this.mintBatch("batch"),author:zc,intent:Qe(d),mutation:null,primitives:[],reads:[],writes:[],at:this.now(),...T("via",t.via),enabledModules:[...o].sort()};return this.log.append(l),this.notify(ft,[l]),l}mutation(e){let t=this.mutations.get(this.spelled(e))??(e===ir?this.publisher:void 0);if(!t)throw new Rr(e,[...this.mutations.keys()]);if(this.mutationDisabled(t))throw new N(`Mutation "${e}" belongs to a module this workspace has turned off`,`Enabled modules: ${[...this.modules.enabled].join(", ")||"(none)"}`);return t}spelled(e){return e===or&&!this.typer&&ae.typeText&&!this.past&&!this.mutations.has(e)&&this.mutations.set(e,this.typer=ae.typeText(this)),this.mutations.has(e)?e:dr(e,this.mutations.keys())??e}spelledCall(e){let t=this.spelled(e.name);return t===e.name?e:{...e,name:t}}mutationDisabled(e){return this.modules.disabledMutations.has(e.name)?!0:e.derived!==void 0&&this.modules.disabledKinds.has(e.derived.kind)}allMutations(){return[...this.mutations.values(),...this.publisher?[this.publisher]:[]].filter(e=>e!==this.keeper&&e!==this.typer&&e!==this.voter&&e!==this.proposer&&!this.mutationDisabled(e))}viaOf(e,t,r){if(e!==void 0&&e===this.keeper){let o=vi(this.mutations.values(),t?.args.kind);if(o.length>0)return o;let i=[...this.mutations.values()];return[...new Set(i.filter(s=>s.derived?.relation===t?.args.kind).flatMap(s=>vr(this.schema,i,s)??[]))]}if(e!==void 0&&e===this.typer){let o=r===void 0||Z(r)?this.graph:we(this,r).graph,i=s=>!this.mutationDisabled(s)&&di(s,this.schema,o,t?.args.node,t?.args.field,r&&z(r).id);return ae.via(this.schema,[...this.mutations.values()],this.subjectKindOf(t,r),t?.args.field,i)}if(e?.derived)return vr(this.schema,[...this.mutations.values()],e)}moved(e,t){return Tc(this.allInvariants(),e,t)}allInvariants(){return this.invariants.filter(e=>this.invariantEnabled(e))}invariantEnabled(e){if(this.modules.disabledInvariants.has(e.name))return!1;if(e.scope!=="graph"){let t=e.scope.kind;if(this.modules.disabledKinds.has(t))return!1}return!0}writesBack(e){if(this.policy)return(t,r,o)=>{try{return this.permits({name:`edit-${t.kind}`,args:{id:t.id,[r]:o}},e).ok}catch{return!1}}}permits(e,t=Ve){if(e=this.spelledCall(e),this.past)return{ok:!1,refusal:{mutation:e.name,wouldNeed:[],message:"Nothing changes while you look back."}};let r=this.refusesAgent(e,t)??this.namesTurnedOff(e,t);if(r)return{ok:!1,refusal:r};let o=this.mutations.get(e.name)??(e.name===ir?this.publisher:void 0);if(o&&o===this.publisher)return J.verdict(this,t);if(o&&o===this.voter)return bt(t)&&(this.votes?.advisory!=="visitors"||sr(t)===void 0)?{ok:!1,refusal:{mutation:e.name,wouldNeed:[],message:vd}}:{ok:!0};if(o&&o===this.proposer)return this.permitsProposal(e,t);let i=o!==void 0&&o===this.keeper&&vi(this.mutations.values(),e.args.kind).length===0,s=i?e.args.from:o?.subject&&e.args[o.subject.arg],a=this.subjectKindOf(e,t),d=be(this.policy,t,e.name,a,this.viaOf(o,e,t),typeof s=="string"?s:void 0,this.words,()=>{let l=z(t).id,u=this.namedIn(e,!1);try{for(let p of Cn(this.graph,o,e.args,this.sighted(t)).primitives)"edge"in p&&p.edge.from!==l&&p.edge.to!==l&&u.push(p.edge.to)}catch{}return u},o!==void 0&&(o.derived!==void 0||o===this.typer||i)?()=>this.madeBy(o,e,s):void 0,o?.derived!==void 0&&Ep.has(o.derived.act));if(d.ok&&o?.writesLinked&&typeof s=="string"){let l=this.refusesLinked(o,s,t);if(l)return l}return!d.ok||!o?.derived||!this.repeatMakes(o,e,s,t)?d:be(this.policy,t,e.name,a,br([...this.mutations.values()],o.derived.kind),typeof s=="string"?s:void 0,this.words)}mayPropose(e,t=Ve){if(!this.policy||this.past||bt(t))return!1;e=this.spelledCall(e);let r=this.mutations.get(e.name);return!r||r===this.proposer||r===this.voter||this.refusesAgent(e,t)||this.namesTurnedOff(e,t)?!1:!this.permits(e,t).ok&&Do(this.policy,t,e.name,this.subjectKindOf(e,t))}proposal(e,t,r,o){let{calls:i,intent:s}=e.args;if(i.length===0||i.length>wi||i.some(f=>!f.args||typeof f.args!="object"||Array.isArray(f.args)))throw new N(`A proposal holds 1 to ${wi} changes, each an act's name and its arguments.`);let a=z(r).id??r.session;if(a===void 0)throw new N("A proposal is somebody's: sign in to propose a change.");let d=ln({basis:(s??`Proposed by ${r.name??a}`).slice(0,500),proposedBy:a.slice(0,120)}),l=this.rehearsal();l.proposing=!0;let u=l.applying(i,{author:r,lineage:d,...T("via",o)});if(u.ops.length===0)return;let p=[...new Set(u.ops.flatMap(f=>f.described??[]))],c=u.ops.filter(f=>f.mutation!==null&&f.author===r);return{id:this.nextId(),seq:this.log.length,batch:t,author:r,intent:u.ops.map(f=>f.intent).join("; "),...T("batchIntent",s),mutation:null,primitives:[],reads:[],writes:[],...p.length>0?{described:p}:{},at:this.now(),...T("via",o),lineage:d,suggests:i,...T("suggestsSaid",i.length>1&&c.length===i.length?c.map(f=>f.intent):void 0)}}permitsProposal(e,t){let r=i=>({ok:!1,refusal:{mutation:e.name,wouldNeed:[],message:i}});if(bt(t))return r("Sign in to propose a change.");let o=Array.isArray(e.args.calls)?e.args.calls:[];for(let i of o){if(typeof i?.name!="string")continue;let s=this.permits(i,t);if(!(s.ok||this.mayPropose(i,t)))return r(`Not permitted to propose this: ${s.refusal.message.replace(/^Not permitted: /,"")}`)}return{ok:!0}}refusesLinked(e,t,r){let o=Z(r)?this.graph:we(this,r).graph,i=o.getNode(t);if(!i)return;let s=[...this.mutations.values()];for(let a of Object.keys(e.writesLinked??{})){let l=this.schema.tryDefinition(i.kind)?.edges?.[a]!==void 0?o.out(i.id,a):o.in(i.id,a);for(let u of l){let p=mr(u.kind),c=this.mutations.get(p),f=c?this.permits({name:p,args:{[c.subject?.arg??"id"]:u.id}},r):be(this.policy,r,p,u.kind,yr(this.schema,s,u.kind),u.id,this.words);if(f.ok)continue;let g=this.words.act?.(e.name)??e.name,h=(this.labels??=new Rt(this.graph)).labelOf(u.id)??u.id,y=this.words.noun?.(u.kind)??u.kind;return{ok:!1,refusal:{mutation:e.name,kind:i.kind,wouldNeed:f.refusal.wouldNeed,message:`Not permitted: \u201C${g}\u201D would change \u201C${h}\u201D, ${/^[aeiou]/i.test(y)?"an":"a"} ${y} that is not yours to change. ${f.refusal.message}`}}}}}repeatMakes(e,t,r,o){let i=e.derived.act;if(i!=="detach"&&i!=="split")return!1;let s=this.schema.tryDefinition(e.derived.kind);if(!s)return!1;let a=typeof r=="string"?(Z(o)?this.graph:we(this,o).graph).getNode(r):void 0;return pc(i,t.args,a,li(s))}madeBy(e,t,r){let o=he(this.log),i=o.creatorOf(r),s=t.args.into;if(!(e.derived?.act==="merge"&&typeof s=="string"&&o.creatorOf(s)!==i))return i}namedIn(e,t=!0){let r=this.mutations.get(e.name);if(!r)return[];let o=r.subject?.arg;return[...t&&o?[e.args[o]]:[],...xt(r.input).flatMap(s=>s.name===o?[]:[e.args[s.name]])].flat().filter(s=>typeof s=="string")}refuse(e,t,r=!this.rehearsing){throw r&&_c(e,t),new sn(e)}get words(){return{act:e=>this.mutations.get(e)?.title,noun:e=>X(this.schema.tryDefinition(e),e)}}refusesAgent(e,t){if(t.kind!=="agent"||t.id===void 0)return;let r=this.may.get(t.id);if(!r||r.has(e.name))return;let o=s=>`\u201C${this.mutations.get(s)?.title??s}\u201D`,i=[...r].map(o);return{mutation:e.name,message:`${t.id} may not ${o(e.name)} here: it was declared able to ${i.length===0?"do nothing else":i.join(", ")}.`,wouldNeed:[]}}namesTurnedOff(e,t=Ec){let r=this.modules.disabledKinds;if(r.size===0||!Z(t))return;let o=this.mutations.get(e.name);if(!(!o||!this.namedIn(e).some(i=>r.has(this.graph.getNode(i)?.kind))))return{mutation:e.name,message:`\u201C${o.title??e.name}\u201D names a record of a module this workspace has turned off.`,wouldNeed:[]}}sighted(e){let t={me:e&&z(e).id,everHeld:o=>he(this.log).kindOf(o)!==void 0,keeps:(o,i)=>Ed(this.policy?.sees,o,i)};if(e===void 0||!un(this,e))return t;let r=St(this,e);return{...t,seen:we(this,e).graph,keepUnchanged:o=>C(o,r),seesInFull:Fd(this,e)}}collaborative(e,t){return ae.collaborative?.(this.schema,this.graph.getNode(e)?.kind,t)??!1}asSplices(e,t){return ae.asSplices?ae.asSplices(this,e,t):e}missingFor(e,t=Ve){e=this.spelledCall(e);let r=this.mutations.get(e.name),o=new Set(this.namedIn(e));if(!r||o.size===0)return;let i=we(this,t).graph;for(let s of o)if(!i.has(s))return new q(s,`\u201C${r.title??e.name}\u201D names a record that is not there.`)}mayAdminister(e,t=Ve){let r=this.modules.administered.get(e);return r?(r.mutations??[]).some(o=>{let i=this.mutations.get(o);return!!i&&jo(i).some(s=>be(this.policy,t,o,s,this.viaOf(i)).ok)}):!1}seenBy(e,t){return we(this,e,t)}sees(e,t){return this.graph.has(t)&&St(this,e)(t)}labels;resolveRef(e,t,r=Ve){let o=(this.policy?.sees?.length??0)>0,i=c=>!o||this.sees(r,c),s=this.graph.getNode(t);if(this.labels??=new Rt(this.graph),s&&i(t))return{ok:!0,id:t,label:this.labels.labelOf(t)??t,by:"id"};let a=this.labels.lookup(e.kinds,t),d=c=>{let f=c.filter(g=>!this.graph.isArchived(g));return f.length?f:c},l=d(a.exact.filter(i)),u=l.length>0,p=(u?l:d(a.prefix.filter(i))).map(c=>({id:c,kind:this.graph.getNode(c).kind,label:this.labels.labelOf(c)??c})).sort((c,f)=>c.label<f.label?-1:c.label>f.label?1:c.id<f.id?-1:1);return p.length===1?{ok:!0,id:p[0].id,label:p[0].label,by:u?"label":"prefix"}:Xd(this.schema,e,t,p)}kindsKeptFrom(e=Ve){let t=new Set;for(let[o,i]of this.modules.administered)if(!this.mayAdminister(o,e))for(let s of i.kinds??[])t.add(s);let r=this.policy?.sees??[];if(r.length>0&&!Z(e)){let o=new Set(this.permittedMutations(e).flatMap(s=>s.creates??[])),i=Ce(this);for(let s of this.schema.kinds)!r.some(d=>d.kinds.includes(s)&&ye(d,e)&&(!d.own&&!d.via||e.id!==void 0)&&(i||!wt(d)))&&!o.has(s)&&t.add(s)}return t}permittedMutations(e=Ve){let t=this.allMutations(),r=To(this.policy,e,t.filter(s=>!s.derived&&s!==this.publisher)),o=this.publisher&&J.verdict(this,e).ok?[this.publisher]:[],i=t.filter(s=>s.derived!==void 0&&be(this.policy,e,s.name,s.derived.kind,this.viaOf(s),z(e).id).ok);return[...r,...o,...i]}subjectKindOf(e,t=Ec){let o=this.mutations.get(e.name)?.subject;if(!o)return;let i=e.args[o.arg];if(typeof i!="string")return o.kinds!=="*"&&o.kinds.length===1?o.kinds[0]:void 0;if(!(!Z(t)&&!we(this,t).graph.has(i)))return this.graph.getNode(i)?.kind}today(){return this.pinned()??(this.ticked&&this.ticked.on===te(this.timeZone)?this.ticked.day:void 0)??(this.timeZone?te(this.timeZone):void 0)}pinned(){let e=this.invariantOptions.context,t=this.invariantOptions.today??e?.today;return typeof t=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(t)?t:void 0}judging(e){let t=this.today(),r=Va(this.graph),o=e??this.invariantOptions.context,i=r&&!(o&&"linked"in o)?{...o,linked:r}:e,s=i??o,a=this.timeZone&&t!==void 0&&e===void 0&&!(s&&"today"in s)?{...s,today:t}:i;return{...this.invariantOptions,...a===void 0?{}:{context:a},...t===void 0?{}:{today:t}}}tick(e=new Date){let t=this.pinned();if(t!==void 0)return{day:t,was:t,appeared:[],cleared:[]};let r=Si(e,this.timeZone),o=te(this.timeZone);this.ticked&&(this.ticked={day:this.ticked.day,on:o});let i=this.today(),s=this.violations();this.ticked={day:r,on:o};let a=this.moved(s,this.violations());if(r!==i&&!this.rehearsing&&this.quiet===0)for(let d of this.listeners)d(ft,[]);return{day:r,...i===void 0?{}:{was:i},appeared:a.introduces,cleared:a.resolves}}reread(){if(!(this.rehearsing||this.quiet>0))for(let e of this.listeners)e(ft,[])}violations(e,t=this.graph){return zn(t,this.allInvariants(),this.judging(e)).map(r=>this.asking(r))}required=new Map;asking(e){if(!e.repairs.some(o=>o.missing===void 0))return e;let t=!1,r=e.repairs.map(o=>{if(o.missing!==void 0)return o;let i=this.requiredOf(o.mutation).filter(s=>o.args?.[s]===void 0);return i.length===0?o:(t=!0,{...o,missing:i})});return t?{...e,repairs:r}:e}requiredOf(e){let t=this.required.get(e);if(t)return t;let r=this.mutations.get(e)?.input?.shape??{},o=Object.entries(r).filter(([,i])=>typeof i?.safeParse=="function"&&!i.safeParse(void 0).success).map(([i])=>i);return this.required.set(e,o),o}wouldChange(e,t){try{return Cn(this.graph,this.mutation(e.name),e.args,this.sighted(t)).primitives.length>0}catch{return!0}}preview(e,t,r={}){e=this.spelledCall(e);let o=this.mutation(e.name),i=Cn(this.graph,o,e.args,this.sighted(r.author)),s=this.asSplices(i.primitives),a=[];if(Fn(this.schema)){let d=H.from(this.schema,this.graph.snapshot());d.applyPrimitives(s),a=pr(this.schema,d,s,{mayWriteBack:this.writesBack(r.author??this.by)})}return this.previewPrimitives([...s,...a],{reads:i.reads,writes:i.writes,intent:i.intent,context:t})}previewAll(e,t={}){let{context:r,...o}=t;return{...this.rehearsal().applying(e,o,r),kept:!1}}rehearsal(){let e=Object.assign(Object.create(n.prototype),this),t=0;Object.assign(e,{graph:H.from(this.schema,this.graph.snapshot(),{validate:this.validate}),log:jn.from(this.log.all(),this.log.epochs(),{horizon:this.log.horizon}),listeners:new Set,labels:void 0,nextId:()=>`${$i}:${++t}`,mintBatch:()=>$i,rehearsing:!0});let r=this.typer&&ae.typeText(e);return Object.assign(e,{typer:r,mutations:r?new Map(this.mutations).set(or,r):new Map(this.mutations)}),e}wouldKeep(e,t,r){try{return this.rehearsal().applying(e,{author:t,lineage:r}),!0}catch{return!1}}previewPrimitives(e,t){let r=this.violations(t.context),o=H.from(this.schema,this.graph.snapshot()),i=o.applyPrimitives(e,{restoring:t.restoring===!0}),s=zn(o,this.allInvariants(),this.judging(t.context));return{diff:i,primitives:e,reads:t.reads,writes:t.writes,intent:t.intent,...this.moved(r,s),violationsAfter:s}}apply(e,t={}){return this.applyAll([e],t)}applyAll(e,t={}){return this.applying(e,t)}applying(e,t,r){let o=e.map(k=>this.spelledCall(k));this.stillNow();let i=t.batch??this.mintBatch("batch"),s=t.author??this.by,a=ln(t.lineage),d=[],l=[],u=new Set,p=new Set,c=[],f=this.violations(r),g=this.graph.snapshot(),h=this.log.length,y=(k,_=s)=>{let P=this.voter!==void 0&&this.mutations.get(k.name)===this.voter,M=this.policy||this.publisher&&k.name===ir||P||this.mutations.get(k.name)===this.proposer?this.permits(k,_):void 0;M&&!M.ok&&!(this.proposing&&this.mayPropose(k,_))&&this.refuse(M.refusal,_.id)},b=(k,_=s)=>{let P=this.refusesAgent(k,_)??this.namesTurnedOff(k,_);P&&this.refuse(P,_.id)},x=o.map(yi);o.forEach((k,_)=>x[_]||y(k)),o.forEach((k,_)=>x[_]||b(k));let $=o.map(k=>({sent:k,as:s,lineage:a,decided:!1}));cr(s)&&this.refuseDeclined(o,s),this.rehearsing||xr(s.id);let O=[],A=[],m=new Map,v=k=>typeof k=="string"?m.get(k)??k:Array.isArray(k)?k.map(v):k;try{for(let k=0;k<$.length;k++){let{sent:_,as:P,lineage:M,decided:ne}=$[k],Un=k<x.length?x[k]:yi(_),{mintedHint:Ne,...yn}=_,Wn=m.size?{...yn,args:Object.fromEntries(Object.entries(yn.args).map(([j,Se])=>[j,v(Se)]))}:yn,re=Un?wc(Wn,O,k):Wn;(Un||ne)&&(y(re,P),b(re,P));let V=this.mutation(re.name);if(V===this.publisher){let j=J.op(this,{id:this.nextId(),at:this.now()},re,i,P,t);d.push(j),c.push(j.intent);continue}if(V===this.voter){if(!ar.op)throw new N("Load @graview/core/tidying to vote on a suggestion.");let j=ar.op(this,{id:this.nextId(),at:this.now()},re,i,P,t);this.log.append(j),d.push(j),c.push(j.intent);let Se=ar.accepting?.(this,j);if(Se&&this.wouldKeep(Se.calls,Se.author,Se.lineage))for(let pu of Se.calls)$.push({sent:pu,as:Se.author,lineage:ln(Se.lineage),decided:!0});continue}if(V===this.proposer){let j=this.proposal(re,i,P,t.via);if(!j)continue;this.log.append(j),d.push(j),c.push(j.intent);continue}let bn=this.missingFor(re,P);if(bn)throw bn;let G;try{G=Cn(this.graph,V,re.args,{...this.sighted(P),hint:Ne})}catch(j){throw j instanceof ve&&!this.rehearsing&&ki(j,P.id),j}if(Ne!==void 0&&G.firstMinted!==void 0&&G.firstMinted!==Ne&&m.set(Ne,G.firstMinted),cr(P)){let j=$d(this.schema,this.graph,G.primitives,this.authorName(P),{declaration:!this.suggesting&&!ne});j&&this.refuse({mutation:re.name,message:j,wouldNeed:[]},P.id)}if(G.primitives.length===0)continue;A[k]=G.firstMinted;let ze=this.asSplices(G.primitives,t.base).map(He);this.graph.applyPrimitives(ze);let We=Fn(this.schema)?pr(this.schema,this.graph,ze,{mayWriteBack:this.writesBack(P)}).map(He):[];O[k]=G.primitives.find(j=>j.op==="add-node")?.node.id;let vn={id:this.nextId(),seq:this.log.length,batch:i,author:P,intent:V.describe!==void 0?G.intent:t.intent??G.intent,...T("batchIntent",t.intent),mutation:re,primitives:[...ze,...We],reads:G.reads,writes:We.length>0?[...new Set([...G.writes,...We.flatMap(Re)])]:G.writes,...V.describe!==void 0&&G.described&&G.described.length>0?{described:G.described}:{},...T("mergedInto",G.mergedInto),at:this.now(),...T("via",t.via),...T("lineage",M)};this.log.append(vn),d.push(vn),l.push(...vn.primitives);for(let j of vn.reads)u.add(j);for(let j of vn.writes)p.add(j);c.push(vn.intent)}}catch(k){throw this.putBack(g,h),k}let R=Le(g,this.graph.snapshot(),l);this.admitted(t,d,l,R,g,h);let S=this.violations(r);return this.notify(R,d),{batch:i,ops:d,...A.length>0?{minted:A}:{},diff:R,primitives:l,reads:[...u],writes:[...p],intent:t.intent??c.join("; "),...this.moved(f,S),violationsAfter:S}}receive(e,t={}){this.stillNow();let r=new Set(this.log.all().map(d=>d.id)),o=e.filter(d=>!r.has(d.id));if(o.length===0)return[];let i=this.graph.snapshot(),s=[];if(!t.applied)for(let d of o)try{this.graph.applyPrimitives(d.primitives,{restoring:d.undoes!==void 0})}catch(l){throw this.graph.load(i),new Vn(d,l)}let a=this.log.length;for(let[d,l]of o.entries()){let u=qn({...l,seq:a+d});this.log.append(u),s.push(u)}return this.countPast(s),this.notify(Le(i,this.graph.snapshot(),o.flatMap(d=>d.primitives)),s),s}append(e,t={}){if(this.stillNow(),e.length===0)return[];let r=new Set(this.log.all().map(a=>a.id)),o,i=e.map((a,d)=>{let l=a.primitives.map(He),u={id:a.id??this.nextId(),seq:this.log.length+d,batch:a.batch??t.batch??(o??=this.mintBatch("batch")),author:a.author,intent:a.intent,...T("batchIntent",a.batchIntent),mutation:a.mutation??null,primitives:l,reads:a.reads??[],writes:a.writes??[...new Set(l.flatMap(Re))],at:a.at??this.now(),...T("undoes",a.undoes),...T("via",a.via),...T("lineage",ln(a.lineage)),...T("described",a.described),...T("sentOut",a.sentOut)};if(r.has(u.id))throw new N(`Op "${u.id}" (${u.intent}) is already in the log`,"A host-made op needs an id of its own; leave `id` out and the store mints one.");return r.add(u.id),u}),s=this.graph.snapshot();for(let a of i)try{this.graph.applyPrimitives(a.primitives,{restoring:a.undoes!==void 0})}catch(d){throw this.graph.load(s),new Vn(a,d)}for(let a of i)this.log.append(a);this.countPast(i);for(let a of i)xr(a.author.id);return this.notify(Le(s,this.graph.snapshot(),i.flatMap(a=>a.primitives)),i),i}applyPrimitives(e,t={}){this.stillNow();let r=t.batch??this.mintBatch("batch"),o=t.author??this.by,i=this.violations(),s=this.graph.snapshot(),a=t.intent??"Apply a change",d=ln(t.lineage),l=this.asSplices(e,t.base).map(He);this.graph.applyPrimitives(l);let u=l;try{Fn(this.schema)&&(u=[...l,...pr(this.schema,this.graph,l,{mayWriteBack:this.writesBack(o)}).map(He)])}catch(g){throw this.putBack(s,this.log.length),g}let p=[];if(u.length>0){let g={id:this.nextId(),seq:this.log.length,batch:r,author:o,intent:a,mutation:null,primitives:u,reads:[],writes:[...new Set(u.flatMap(Re))],at:this.now(),...T("via",t.via),...T("lineage",d)};this.log.append(g),p.push(g),xr(o.id)}let c=this.violations(),f=Le(s,this.graph.snapshot(),u);return this.notify(f,p),{batch:r,ops:p,diff:f,primitives:u,reads:[],writes:p[0]?.writes??[],intent:a,...this.moved(i,c),violationsAfter:c}}findings(){return Ac({schema:this.schema,invariants:this.allInvariants()},this.graph.snapshot(),{invariantOptions:this.invariantOptions})}batches(){return this.log.batches()}canUndo(e){return mt(this.log,typeof e=="string"?[e]:e)}previewUndo(e,t){let r=this.canUndo(e);if(!r.ok)return{ok:!1,check:r};let o=pd(r.ops,this.log.all()),i=new Set;for(let s of r.ops)for(let a of s.writes)i.add(a);return{ok:!0,check:r,...this.previewPrimitives(o,{reads:[...new Set(r.ops.flatMap(s=>[...s.reads]))],writes:[...i],intent:`Undo: ${r.ops.map(s=>s.intent).join("; ")}`,restoring:r.ops.every(Mc),...t===void 0?{}:{context:t}})}}undo(e,t={}){return this.undoing(e,t)}undoing(e,t){this.stillNow();let r=typeof e=="string"?[e]:e,o=t.author??this.by,i=(this.policy?.sees?.length??0)>0&&!Z(o);if(i){let y=mt(Qo(Tn(this.log.all(),fr(this,o)),()=>this.log.epochs()),r);if(!y.ok)throw new on(y)}let s=this.canUndo(r);if(!s.ok)throw new on(i?{ok:!1,ops:[],blockedBy:[],includeBatches:[],message:"Cannot undo on its own \u2014 a later change you cannot see depends on it, which only somebody who can see it can take back."}:s);let a=t.batch??this.mintBatch("undo"),d=ln(t.lineage),l=this.undoRefusal(s.ops,o);l&&this.refuse(l,o.id,!0);let u=this.graph.snapshot(),p=this.violations(),c=[],f=this.log.length;for(let{op:y,primitives:b}of Go(this.log.all(),s.ops)){let x={id:this.nextId(),seq:this.log.length,batch:a,author:o,intent:`Undo: ${y.intent}`,...T("batchIntent",t.intent),mutation:null,primitives:b,reads:y.reads,writes:y.writes,at:this.now(),undoes:y.id,...T("via",t.via),...T("lineage",d),...T("undoneLineage",y.lineage)};this.graph.applyPrimitives(x.primitives,{restoring:Mc(y)}),this.log.append(x),c.push(x)}let g=Le(u,this.graph.snapshot(),c.flatMap(y=>[...y.primitives]));this.admitted(t,c,c.flatMap(y=>[...y.primitives]),g,u,f);let h=this.violations();return this.notify(g,c),{batch:a,ops:c,diff:g,primitives:c.flatMap(y=>[...y.primitives]),reads:[...new Set(c.flatMap(y=>[...y.reads]))],writes:[...new Set(c.flatMap(y=>[...y.writes]))],intent:t.intent??c.map(y=>y.intent).join("; "),...this.moved(p,h),violationsAfter:h}}mayUndo(e,t=this.by){let r=this.canUndo(e);if(!r.ok)return{ok:!1,check:r};let o=this.undoRefusal(r.ops,t);return o?{ok:!1,refusal:o}:{ok:!0}}undoRefusal(e,t){if(this.policy||this.publisher)for(let r of e){let o=this.rootOf(r),i=z(o.author).id;if(o.vote!==void 0){if(o.vote.advisory&&!Z(t)&&sr(t)!==o.vote.voter&&!(this.policy&&this.grantsEveryAct(t)))return{mutation:"undo",wouldNeed:[],message:`Not permitted to undo "${r.intent}": only whoever voted takes their vote back.`};if(this.policy&&!Z(t)&&i!==z(t).id&&!this.grantsEveryAct(t))return{mutation:"undo",wouldNeed:[],message:`Not permitted to undo "${r.intent}": only whoever voted takes their vote back.`};continue}if(!o.mutation){if(o.primitives.length===0)continue;if(this.policy&&!Z(t)&&i!==z(t).id&&!this.grantsEveryAct(t))return{mutation:"undo",wouldNeed:[],message:`Not permitted to undo "${r.intent}": no act made it, so only whoever did may take it back.`};continue}let s=d=>JSON.stringify(d).includes(JSON.stringify(i)),a=i!==void 0&&i!==z(t).id&&!Z(t)&&!s(o.mutation.args)&&s(o.primitives)?{ok:!1,refusal:{mutation:o.mutation.name,wouldNeed:[],message:"it was done as somebody else."}}:this.permits(o.mutation,t);if(!a.ok)return{...a.refusal,message:`Not permitted to undo "${r.intent}": ${a.refusal.message}`}}}rootOf(e){let t=e;for(let r=t.undoes===void 0?void 0:this.log.get(t.undoes);r!==void 0;r=t.undoes===void 0?void 0:this.log.get(t.undoes))t=r;return t}grantsEveryAct(e){let t=z(e);return(this.policy?.grants??[]).some(r=>ye(r,t)&&r.mutations==="*"&&(r.kinds===void 0||r.kinds==="*")&&!r.self&&!r.ownEnd)}authorName(e){return ut(e,{graph:this.graph,schema:this.schema})}actMeanings(){return{act:e=>this.mutations.get(this.spelled(e)),has:e=>this.graph.has(e)}}refuseDeclined(e,t){let r=Rd(this.log.all(),e,this.actMeanings());r&&this.refuse({mutation:e[0].name,message:`${this.authorName(t)} may not make this again: a person declined it on ${r.at.slice(0,10)}.`,wouldNeed:[]},t.id)}putBack(e,t){this.graph.load(e),this.log.length>t&&this.log.truncate(t)}admitted(e,t,r,o,i,s){if(!e.admit||t.length===0)return;let a=this.graph.size;try{e.admit({ops:t,primitives:r,added:{nodes:o.addedNodes.length,edges:o.addedEdges.length},removed:{nodes:o.removedNodes.length,edges:o.removedEdges.length},changed:{nodes:o.changedNodes.length},nodesAfter:a.nodes,edgesAfter:a.edges})}catch(d){throw this.putBack(i,s),d}}redo(e,t={}){return this.undo(e,t)}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(e,t){if(!(this.quiet>0)&&!(t.length===0&&Ya(e)))for(let r of this.listeners)r(e,t)}rebase(e){this.stillNow();let t=new Set([...e.pending,...e.drop??[]]),r=this.log.all(),o=r.findIndex(h=>t.has(h.batch)),i=r.slice(o<0?r.length:o),s=this.log.horizon+(o<0?r.length:o),a=i.find(h=>!t.has(h.batch));if(a)throw new N(`Cannot rebase: op "${a.id}" (${a.intent}) comes after a pending batch and is neither pending nor dropped`,"While anything is pending, land the server's ops through rebase, so the log stays confirmed ops then pending ones.");let d=this.log.lastEpoch();if(d&&d.seq>s)throw new N(`Cannot rebase across an epoch: one begins at seq ${d.seq}, after pending op "${i[0].id}"`);let l=this.graph.snapshot(),u=[],p=[],c=[];this.quiet++;try{for(let x of[...i].reverse())this.graph.applyPrimitives(Je(x),{restoring:!0,inPlace:!0});this.log.truncate(s);let h=new Set(this.log.all().map(x=>x.id));for(let x of e.confirmed){if(h.has(x.id))continue;try{this.graph.applyPrimitives(x.primitives,{restoring:x.undoes!==void 0})}catch(w){throw new Vn(x,w)}let $=qn({...x,seq:this.log.length});this.log.append($),h.add(x.id),u.push($)}this.countPast(u);let y=ae.carried?.(i,u,e.pending),b=Nc(i);for(let x of e.pending){let $=i.filter(w=>w.batch===x);if($.length!==0)try{p.push(...this.replay(x,$,y?.get(x),b))}catch(w){c.push({batch:x,error:w})}}}catch(h){this.log.truncate(s);for(let y of i)this.log.append(y);throw this.graph.load(l),h}finally{this.quiet--}let f=Fe(l,this.graph.snapshot()),g=[...u,...p];return this.notify(f,g),{diff:f,confirmed:u,pending:p,refused:c}}adopt(e){this.stillNow();let t=new Set(e.drop??[]),r=(e.pending??[]).filter(f=>!t.has(f)),o=this.log.all(),i=this.graph.snapshot(),s={ops:[...o],epochs:[...this.log.epochs()],horizon:this.log.horizon},a=new Set(o.map(f=>f.id)),d=new Map(r.map(f=>[f,o.filter(g=>g.batch===f)]));if(e.log.length>0)this.log.replace(e.log,e.epochs,T("horizon",e.horizon));else{let f=e.horizon??0;this.log.replace([],e.epochs??[{seq:f,base:e.snapshot}],{horizon:f})}let l=[],u=[];this.quiet++;try{this.graph.load(e.snapshot),this.projected=void 0,this.countPastTheLog();for(let f of r){let g=d.get(f)??[];if(g.length!==0)try{l.push(...this.replay(f,g,void 0,Nc(o)))}catch(h){u.push({batch:f,error:h})}}}catch(f){throw this.log.replace(s.ops,s.epochs,{horizon:s.horizon}),this.graph.load(i),this.projected=void 0,f}finally{this.quiet--}let p=this.log.all().filter(f=>!a.has(f.id)&&!l.includes(f)),c=Fe(i,this.graph.snapshot());return this.notify(c,[...p,...l]),{diff:c,adopted:p,pending:l,refused:u}}replay(e,t,r,o=new Map){let i=t[0],s={author:i.author,batch:e,...T("intent",i.batchIntent),...T("via",i.via),...T("lineage",i.lineage)};if(i.undoes!==void 0){let a=t.map(l=>this.log.get(l.undoes??"")?.batch??o.get(l.undoes??"")),d=t.find((l,u)=>a[u]===void 0||!this.log.all().some(p=>p.batch===a[u]));if(d)throw new N(`What "${d.intent}" took back is no longer in the log`);return this.undoing([...new Set(a)],s).ops}return r?this.applying(r,s).ops:t.every(a=>a.mutation!==null)?this.applying(t.map(a=>a.mutation),s).ops:this.append(t.map(({seq:a,...d})=>d))}snapshot(){return this.graph.snapshot()}verify(){let e=this.log.lastEpoch();return ec(this.schema,this.log.opsFrom(e?.seq??0),this.graph.snapshot(),{validate:this.validate,...e?{base:e.base}:{}})}checkpoint(e={}){let t=this.log.all(),r;if(e.seq!==void 0)r=e.seq;else{let u=this.log.length-(e.keepOps??1e3),c=Date.parse(e.now??this.now())-(e.keepDays??90)*864e5,f=t.find(h=>Date.parse(h.at)>c),g=f?f.seq:this.log.length;r=Math.min(u,g)}let o=Fo(this.publishing)&&this.publishedSeq===void 0?[0]:[],i=[...e.pins??[],...o].filter(u=>Number.isInteger(u));i.length>0&&(r=Math.min(r,...i));let s=e.format??fe.snapshot;if(!Number.isInteger(s)||s<1||s>fe.snapshot)throw new RangeError(`Cannot write a checkpoint in snapshot format ${String(s)}: this build writes formats 1 to ${fe.snapshot}.`);let a=u=>{let p=Math.min(Math.max(u,this.log.horizon),this.log.length);for(;p>this.log.horizon&&p<this.log.length&&t[p-this.log.horizon].batch===t[p-1-this.log.horizon].batch;)p--;return p};if(r=a(r),r<=this.log.horizon)return;let d=this.verify();if(!d.ok)throw new N(`Cannot compact a store that does not verify: ${d.reason}`);let l=this.checkpointWithPublished(r);for(;Ri(l).formats.snapshot>s;){if(r=a(Math.min(...l.published.map(u=>u.seq))),r<=this.log.horizon)return;l=this.checkpointWithPublished(r)}return l}checkpointWithPublished(e){let t=this.log.horizonEpoch()?.published??[],r=(J.behind?.(this,e)??[]).flatMap(o=>o>=this.log.horizon?[this.epochAt(o)]:t.filter(i=>i.seq===o));return{...this.epochAt(e),...r.length>0&&{published:r}}}epochAt(e){let t=this.log.all(),{creators:r,removed:o,writers:i,published:s,...a}=this.log.checkpointAt(this.schema,e,{validate:this.validate}),d=new Set(a.base.nodes.map(g=>g.id)),{creators:l,removed:u}=Nd(this.log,e,g=>d.has(g)),p=he(this.log),c=Pd(this.log,e,a.base.nodes,g=>C(g,h=>!d.has(h)&&p.kindOf(h)===void 0)),f=g=>g&&Object.keys(g).length>0;return{...a,...f(l)&&{creators:l},...u&&{removed:u},...f(c)&&{writers:c},...T("enabledModules",t.slice(0,e-this.log.horizon).reverse().find(g=>g.enabledModules)?.enabledModules??this.log.horizonEpoch()?.enabledModules),...T("publishedThrough",J.seq?.(this,e))}}compact(e){return this.stillNow(),this.log.compact(e)}};var zp=n=>`lens:${n}`,Ip={hidden:[],removed:[],may:{views:!1,lenses:!1}};function Tp(n,e,t){return n.name!==void 0&&e.may.views?"view":n.declared&&e.may.lenses&&t.lens?"lens":null}var jc=["full","summary","glyph"],Pt="view:",Pi=(n,e)=>n.as===e.as&&(n.over??[n.kind]).includes(e.kind),jp=n=>n.filter((e,t)=>!n.slice(0,t).some(r=>Pi(r,e))),Dp=n=>n.filter(e=>!e.hidden);function Ee(n){return n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Et(n,e){return`/${Ee(n.tryDefinition(e)?.plural??`${e}s`)}`}function Fp(n,e,t){return`${Et(n,e)}/${encodeURIComponent(t)}`}function Lp(n,e){return`/places/${encodeURIComponent(n)}${e?`?of=${encodeURIComponent(e)}`:""}`}function Dc(n,e){return e.some(t=>t.as===n.as&&!Pi(n,t))}function Cp(n,e,t){return Dc(n,e)?`${n.title} \xB7 ${(t.tryDefinition(n.kind)?.plural??`${n.kind}s`).toLowerCase()}`:n.title}var fn=(n,e,t="")=>`${n}|${e.cardinality}|${e.fidelity}|${t}`;function _i(n){switch(n){case"full":return["full","summary","glyph"];case"summary":return["summary","full","glyph"];case"glyph":return["glyph","summary","full"]}}function Zp(n){let e=new Map,t=[],r=[],o,i=[],s={arrange(a){return a!==void 0&&(o=a),s},arrangement:()=>o,home(a,d){return a!==void 0&&i.push({view:a,...d?.name!==void 0?{name:d.name}:{}}),s},homeView:()=>i.at(-1)?.view,homes:()=>i,register(a,d,l,u){let p={...u?.over?.[1]?{over:u.over}:{},...u?.hidden?{hidden:!0}:{},...u?.name?{name:u.name}:{},...u?.declared?{declared:!0}:{}},c={kind:a,cardinality:d.cardinality,fidelity:d.fidelity,view:l,...u?.title?{title:u.title}:{},...u?.across?{across:u.across}:{},...u?.beside?{beside:!0}:{},...p};if(r.push(c),!u?.beside&&!p.hidden&&e.set(fn(a,d),c),u?.title){let f=Ee(u.title);e.set(fn(a,d,f),c),d.cardinality==="many"&&!t.some(g=>g.kind===a&&g.as===f)&&t.push({kind:a,title:u.title,as:f,...u.across?{across:u.across}:{},...p,...u.lens?{lens:u.lens}:{},...u.reads?.length?{reads:u.reads}:{}})}return s},places:()=>t,forget(a,d){for(let u of jc)e.delete(fn(a,{cardinality:"many",fidelity:u},d));let l=t.findIndex(u=>u.kind===a&&u.as===d);return l>=0&&t.splice(l,1),s},lookup(a,d){return e.get(fn(a,d))?.view},resolve(a,d,l){if(l)for(let u of _i(d.fidelity)){let p=e.get(fn(a,{cardinality:d.cardinality,fidelity:u},l));if(p)return p}for(let u of _i(d.fidelity)){let p=e.get(fn(a,{cardinality:d.cardinality,fidelity:u}));if(p)return p}if(d.cardinality==="one")for(let u of _i(d.fidelity)){let p=e.get(fn(a,{cardinality:"many",fidelity:u}));if(p)return p}},registrations:()=>r,all(){return[...e.values()]},kindsWithViews(){return[...new Set([...e.values()].map(a=>a.kind))]}};return s}var Gp=["day","week","month","year","decade"];function Fc(n){let e={};n.q&&n.q.trim().length>0&&(e.query=n.q);let t=$o(n.archived);if(t&&(e.archived=t),n.sort){let[r,o]=n.sort.split(":");r&&(e.sort={by:r,direction:o==="desc"?"desc":"asc"})}if(n.filter){let r=[];for(let o of n.filter.split(",")){let i=o.indexOf(":");i<=0||r.push({key:o.slice(0,i),value:o.slice(i+1)})}r.length>0&&(e.filter=r)}if(n.group){let[r,o]=n.group.split(":");r&&(e.group={by:r,...Gp.includes(o)?{bucket:o}:{}})}return e}function Ei(n){if(typeof n=="string"&&n.length>0)return{by:n,direction:"asc"};if(typeof n!="object"||n===null)return;let{by:e,direction:t}=n;if(!(typeof e!="string"||e.length===0))return{by:e,direction:t==="desc"?"desc":"asc"}}function $r(n,e,t){let r=Ei(n);if(!r)return'an order is a field, like "released", or { "by": "released", "direction": "asc" | "desc" }';let o=typeof n=="object"&&n!==null?n.direction:void 0;if(o!==void 0&&o!=="asc"&&o!=="desc")return`an order runs "asc" or "desc", not "${String(o)}"`;if(r.by!=="label"&&!e.includes(r.by))return`${t} has no field "${r.by}" to order by (it has ${e.length>0?e.map(i=>`"${i}"`).join(", "):"none"}, and "label", its name)`}function Vp(n,e,t){let r=Ei(e);if(!r)return n;let o=r.direction==="desc"?-1:1;return n.map((i,s)=>({item:i,at:s,value:t(i,r.by)})).sort((i,s)=>{let a=(i.value===void 0||i.value===null||i.value===""?1:0)-(s.value===void 0||s.value===null||s.value===""?1:0);if(a!==0)return a;if(i.value===s.value||i.value===void 0||i.value===null)return i.at-s.at;let d=typeof i.value=="number"&&typeof s.value=="number"?i.value-s.value:String(i.value).localeCompare(String(s.value),void 0,{numeric:!0});return d===0?i.at-s.at:d*o}).map(i=>i.item)}var Mt={timeline:{binds:"fields",requiredRoles:["start","end"],options:["columns","extent","tick","minWindow","arranging"]},calendar:{binds:"fields",requiredRoles:["start"],options:["today","range","weekStartsOn","perCell","horizon","arranging","search","filters"]},coverage:{binds:"entities",requiredRoles:["rows","columns","link"],options:["rowRef","rowGroup","groupOrder","requiredGroups","requiredVia","badge","columnGroup","sort","columnSort","search","filters"]},board:{binds:"entities",requiredRoles:["slots","x","y","fill"],options:["fillFrom","slotCode","zones","aspect","emptyLabel","pickTarget","arranging","arrange"]},plan:{binds:"entities",requiredRoles:["regions","outline"],options:["hues","aspect","undrawnLabel","strayLabel","draw","place","help"]},reach:{binds:"nothing",requiredRoles:[],options:[]},blocks:{binds:"nothing",requiredRoles:[],options:["blocks"]},columns:{binds:"fields",requiredRoles:["column"],options:["sort","search","filters","move","collapsed","cap","hidden"]}},Kp=["start","end"],Bp=20,Zc=Object.keys(Mt),Up=(n,e,t,r=Mt[n].options)=>({message:`The ${n} lens takes no option "${e}", so "${t}" ignores it.`,fix:r.length?`Use one of: ${r.join(", ")}.`:`The ${n} lens takes no options; drop it.`}),Gc=n=>Object.hasOwn(Mt,n);function Mi(n,e,t){let r=n[e],o=Array.isArray(r)?r.filter(i=>typeof i=="string"&&t(i)):[];o.length>0?n[e]=o:delete n[e]}var Kn=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function Wp(n,e,t){let r=n.tryDefinition(e)?.fields.shape,o=L(r?.[t]);for(;o&&(o.type==="optional"||o.type==="default"||o.type==="nullable"||o.type==="prefault");)o=L(o.innerType);return o?.type==="number"}var Lc=(n,e="start",t="end")=>`A timeline lays out spans by number \u2014 minutes of a day, 0 to 1440 \u2014 across columns: "bindings": { "${n}": { "start": "<a number field>", "end": "<a number field>", "column": "<a choice field, like a weekday>" } }, or "options": { "columns": ["mon", "tue", \u2026] }. For spans of dates, draw a calendar: "lens": "calendar", "bindings": { "${n}": { "start": "${e}", "end": "${t}" } }, "options": { "range": "month" }.`;function Cc(n,e,t){let r=n.tryDefinition(e)?.fields.shape,o=L(r?.[t]);for(;o&&(o.type==="optional"||o.type==="default"||o.type==="nullable"||o.type==="prefault");)o=L(o.innerType);return o?.type!=="enum"?[]:(o.entries?Object.values(o.entries):o.values??[]).filter(s=>typeof s=="string")}function qp(n){let e=[],t=[],r=[],o=new Set(n.schema.kinds),i=new Set;for(let d of o)for(let l of Object.keys(n.schema.tryDefinition(d)?.edges??{}))i.add(l);let s=d=>Object.keys(n.schema.tryDefinition(d)?.fields.shape??{}),a=new Map;return(n.lenses??[]).forEach((d,l)=>{let u=`lenses.${l}`,p=typeof d.title=="string"&&d.title.trim().length>0?d.title.trim():void 0,c=(m,v)=>{t.push({index:l,name:d.name,...p?{title:p}:{},why:m}),v&&r.push({severity:"warning",...v})};if(!Gc(d.name)){p?c(`"${d.name}" is not a lens this framework draws`,{code:"lens-not-shipped",path:`${u}.name`,message:`"${p}" names the lens "${d.name}", which the framework does not ship, so nothing draws it.`,fix:`Name one of ${Zc.join(", ")} \u2014 or register the view yourself and drop the title.`}):c("it is a lens this app wrote, drawn by the app's own views");return}if(!p)return c("it has no title, so it is bindings the checker holds and no place");let f=Mt[d.name],g=Kn(d.options)?d.options:{};if(d.options!==void 0&&!Kn(d.options))return c("its options are not an object",{code:"lens-options-not-an-object",path:`${u}.options`,message:`"${p}" has options that are not an object.`,fix:'Write them as { "<option>": <value> }, or drop them.'});for(let m of Object.keys(g))f.options.includes(m)||r.push({severity:"warning",code:"lens-option-unknown",path:`${u}.options.${m}`,...Up(d.name,m,p,f.options)});let h={};for(let m of f.options)g[m]!==void 0&&(h[m]=g[m]);d.arrangedBy&&(h.arrangedBy=Fc(d.arrangedBy));let y=Kn(d.bindings)?d.bindings:{},b=[],x,$=(m,v,R)=>c(v,{code:"lens-cannot-draw",path:m,message:`"${p}" cannot draw: ${v}.`,fix:R});if(f.binds==="fields"){let m=Object.keys(y).filter(R=>Kn(y[R])),v=m.filter(R=>!o.has(R));if(m.length===0)return $(`${u}.bindings`,"it binds no kind",`Bind a kind's fields: "bindings": { "<kind>": { ${f.requiredRoles.map(R=>`"${R}": "<field>"`).join(", ")} } }.`);if(v.length>0)return;if(h.bindings=y,b=m,d.name==="timeline"){for(let S of m){let k=y[S];for(let _ of Kp){let P=k[_];if(!(typeof P!="string"||!s(S).includes(P))&&!Wp(n.schema,S,P))return $(`${u}.bindings.${S}.${_}`,`its ${_} "${P}" is not a number, and a timeline's axis is`,Lc(S,String(k.start??"start"),String(k.end??"end")))}}let R=g.columns;if(Array.isArray(R))h.columns=R.map(S=>typeof S=="string"?{id:S,label:S}:S);else{let S=m.flatMap(_=>{let P=y[_],M=typeof P.column=="string"?P.column:typeof P.columns=="string"?P.columns:void 0;return M?Cc(n.schema,_,M):[]}),k=[...new Set(S)];if(k.length===0)return $(`${u}.options.columns`,"it has no columns \u2014 no option names them and no `column` role is bound to a field of set values",Lc(m[0]));h.columns=k.map(_=>({id:_,label:_.toUpperCase()}))}h.extent===void 0&&(h.extent=1440)}if(d.name==="columns"){if(h.sort!==void 0){let S=m.map(k=>$r(h.sort,s(k),k)).find(Boolean);S&&(r.push({severity:"warning",code:"lens-sort",path:`${u}.options.sort`,message:`"${p}" cannot order its cards: ${S}.`,fix:'Write { "by": "<a field>", "direction": "asc" }, or drop it.'}),delete h.sort)}let R=new Set;for(let S of m){let k=y[S].column;if(typeof k!="string"||!s(S).includes(k))return;let _=Cc(n.schema,S,k);if(_.length===0)return $(`${u}.bindings.${S}.column`,`its column field "${k}" is not a choice`,`Bind "column" to a choice field of ${S}, like a status.`);for(let P of _)R.add(P)}typeof h.move!="boolean"&&delete h.move,Number.isInteger(h.cap)&&h.cap>=1&&h.cap<=500||delete h.cap;for(let S of["collapsed","hidden"])Mi(h,S,k=>R.has(k))}if(d.name==="calendar"&&h.today!==void 0&&!(typeof h.today=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(h.today)))return $(`${u}.options.today`,"its today is not a date",'Write it as "YYYY-MM-DD", or leave it out and the calendar opens on the day it is drawn.');if(d.name==="calendar"&&h.horizon!==void 0){let R=h.horizon,S=P=>P===void 0||Number.isInteger(P)&&P>=1&&P<=9999,k=typeof R=="number"?{years:R,title:"Years"}:R;Kn(k)&&Number.isInteger(k.years)&&k.years>=1&&k.years<=200&&typeof k.title=="string"&&k.title.trim().length>0&&S(k.from)&&S(k.to)&&Object.keys(k).every(P=>["years","title","from","to"].includes(P))&&!(typeof k.from=="number"&&typeof k.to=="number"&&k.to<k.from)?h.horizon=k:(delete h.horizon,r.push({severity:"warning",code:"lens-horizon",path:`${u}.options.horizon`,message:`"${p}" has a horizon that is not a span of years, so it offers no span of years.`,fix:'Write { "years": 30, "title": "The career" } \u2014 "from" and "to" (years, like 1962 and 2023) only to pin its ends, which otherwise reach the first and last of its records.'}))}if(d.name==="calendar"&&h.range!==void 0&&!["day","week","month","quarter","year","years","agenda"].includes(h.range))return $(`${u}.options.range`,`its range "${String(h.range)}" is not one a calendar opens at`,"Use one of: day, week, month, quarter, year, agenda.")}else if(f.binds==="entities"){let m=S=>{let k=y[S];if(Kn(k)){if(typeof k.kind=="string")return k.kind;if(typeof k.edge=="string")return k.edge;if(Array.isArray(k.path))return{path:k.path};if(typeof k.field=="string")return k.field}};for(let S of f.requiredRoles)if(m(S)===void 0)return;let v=d.name==="coverage"?"rows":d.name==="board"?"slots":"regions",R=m(v);if(!o.has(R))return;if(d.name==="coverage"){let S=m("columns");if(!o.has(S))return;let k=m("link");if(typeof k=="string"&&!i.has(k))return;Object.assign(h,{rows:R,columns:S,link:k}),S!==R&&(x=S);for(let[_,P]of[["sort",R],["columnSort",S]]){if(h[_]===void 0)continue;let M=$r(h[_],s(P),P);M&&(r.push({severity:"warning",code:"lens-sort",path:`${u}.options.${_}`,message:`"${p}" cannot order its ${_==="sort"?"rows":"columns"}: ${M}.`,fix:`Write { "by": "<a field of ${P}>", "direction": "asc" }, or drop it.`}),delete h[_])}}else if(d.name==="board"){Object.assign(h,{slots:R,x:m("x"),y:m("y"),fill:m("fill")});for(let S of["x","y"])if(!s(R).includes(h[S]))return}else{Object.assign(h,{regions:R,outline:m("outline")});for(let S of["markers","at","within","nests","regionKind","markerKind"]){let k=m(S);typeof k=="string"&&(h[S]=k)}}b=[R]}else if(d.name==="blocks"){if(!d.on)return $(`${u}.on`,"it does not say which kind it stands on",'Say "on": "<the kind it is a place of>".');if(!Array.isArray(h.blocks)||h.blocks.length===0)return $(`${u}.options.blocks`,"it has no blocks to draw",`Say "options": { "blocks": [{ "headline": "\u2026" }, { "list": "all('<kind>')", "as": "card" }] }.`)}else{let m=["user","person","member"].find(v=>o.has(v));if(!d.on&&!m)return $(`${u}.on`,"it does not say which kind it stands on",'Say "on": "<the kind whose records are the people>".');b=m?[m]:[]}if(d.on!==void 0){if(typeof d.on!="string"||!o.has(d.on))return $(`${u}.on`,`it stands on "${String(d.on)}", which is not a kind`,`Use one of: ${[...o].join(", ")}.`);if(b=[d.on],d.name==="coverage"){let m=[h.rows,h.columns].find(v=>v!==d.on);x=typeof m=="string"?m:void 0}}let w=typeof h.rows=="string"?h.rows:b[0];if(w!==void 0){let m=["label",...s(w)],v=new Set(["is",...m,...Object.keys(n.schema.tryDefinition(w)?.edges??{})]);Mi(h,"search",R=>m.includes(R)),Mi(h,"filters",R=>v.has(R.split(".")[0]))}let O=Ee(p);if(O.length===0)return $(`${u}.title`,"its title has no letters or digits to make an address of","Give it a title a person would say.");for(let m of b){let v=`${m}|${O}`;if(a.has(v))return c(`another lens on ${m} is already called "${p}"`,{code:"lens-title-taken",path:`${u}.title`,message:`"${p}" is the title of lenses.${a.get(v)} too, on the same kind, so one address would name two pictures.`,fix:"Give each its own title."})}for(let m of b)a.set(`${m}|${O}`,l);let A=d.create;A!==void 0&&typeof A!="boolean"&&r.push({severity:"warning",code:"lens-create",path:`${u}.create`,message:`"${p}" says create ${JSON.stringify(A)}, which is neither true nor false, so its page keeps the forms that begin its kind.`,fix:'Say "create": false to leave them off, or drop it.'}),e.push({index:l,lens:d.name,title:p,as:O,kinds:b,...x?{across:x}:{},options:h,...d.hidden===!0?{hidden:!0}:{},...A===!1?{create:!1}:{}})}),{drawn:e,undrawn:t,findings:r}}var Hp=6;function Jp(n,e,t=[]){let r=n.kinds,o=s=>Object.values(n.tryDefinition(s)?.edges??{}).map(a=>(a.to==="*"?r:a.to).filter(d=>d!==s)),i=new Set(r.flatMap(s=>o(s).flat()));return new Set([...e?.hide??[],...t,...r.filter(s=>!i.has(s)&&o(s).length>0&&o(s).every(a=>a.length>=2))])}function Yp(n,e,t){if(!n?.primary)return;let r=new Set(n.primary.map(Ee));return{kinds:new Set(e.kinds.filter(o=>r.has(Ee(o))||r.has(Et(e,o).slice(1)))),places:new Set(t.filter(o=>r.has(o.as)||r.has(Ee(o.title))||o.name!==void 0&&n.primary.includes(Pt+o.name)).map(o=>`${o.kind}|${o.as}`))}}var Xp="home",Vc="overview",Qp=`/places/${Vc}`;function eh(n){let e=n?.scene?.trim();return e||"Scene"}function nh(n){let e=n?.pages?.trim();return e||"Pages"}function th(n,e){if(!e||e.length===0)return n;let t=e.filter(r=>n.includes(r));return[...new Set(t),...n.filter(r=>!t.includes(r))]}function Kc(n){return n.startsWith(Pt)&&n.slice(Pt.length).trim()||void 0}function rh(n,e,t){let r=[],o=new Set;for(let i of e??[]){let s=Kc(i),a=s===void 0?void 0:t.find(d=>d.name===s&&n.includes(d.kind));a?r.some(d=>d.view===a)||r.push({kind:a.kind,view:a}):s===void 0&&n.includes(i)&&!o.has(i)&&(o.add(i),r.push({kind:i}))}for(let i of n)o.has(i)||r.push({kind:i});return r}function oh(n,e,t){if(n===void 0)return;let r=n.trim();if(r==="")return;if(r.toLowerCase()==="home"||r==="/")return{to:"home"};let o=Ee(r),i=t.find(d=>d.title===r||Pt+d.name===r)??t.find(d=>d.as===o);if(i)return{to:"place",place:i};let s=e.kinds,a=s.find(d=>d===r)??s.find(d=>Et(e,d).slice(1)===o);return a?{to:"kind",kind:a}:void 0}function Ni(n){let e=(n??"").replace(/\/+$/,"");return e===""?"":e.startsWith("/")?e:`/${e}`}function ih(n,e={}){let t=typeof n=="string"?n:n.address,r=Ni(e.basePath),o=t.startsWith("/")?t:`/${t}`;return r===""?o:o==="/"?r:o.startsWith("/?")||o.startsWith("/#")?`${r}${o.slice(1)}`:`${r}${o}`}function sh(n,e){let t=Ni(e);if(t==="")return n.startsWith("/")?n:`/${n}`;if(!n.toLowerCase().startsWith(t.toLowerCase()))return null;let r=n.slice(t.length);return r===""||r==="/"?"/":r.startsWith("/")?r:null}var Ar=2500,ah=Ar*4;function dh(n){let e=n.name??"";return e&&n.onBehalfOfName?`${e}, for ${n.onBehalfOfName}`:e}function zi(n,e,t=Ar){return n.held==="socket"?!0:n.until!==void 0?e<Date.parse(n.until):e-Date.parse(n.at)<t}var f0=new Set(Xt);function ch(n){return`${n.kind}:${n.id??""}:${n.session??""}`}function uh(n,e,t,r=Ar,o){let i=new Map;for(let[s,a]of n)zi(a,t,r)&&i.set(s,a);for(let s of e){if(!zi(s,t,r)){i.delete(s.participant);continue}let a=i.get(s.participant);(!a||Date.parse(a.at)<=Date.parse(s.at))&&i.set(s.participant,s)}return o!==void 0&&i.delete(o),i}function lh(n,e){return!n||!e?n===e:n.participant===e.participant&&n.kind===e.kind&&n.name===e.name&&n.onBehalfOf===e.onBehalfOf&&n.onBehalfOfName===e.onBehalfOfName&&n.until===e.until&&n.held===e.held&&n.hue===e.hue&&n.stop===e.stop&&(n.over??null)===(e.over??null)&&(n.robot?.at??null)===(e.robot?.at??null)&&(n.robot?.mode??null)===(e.robot?.mode??null)&&JSON.stringify(n.caret)===JSON.stringify(e.caret)}var Bc=Symbol.for("@graview/core:app-link"),fh=n=>(Object.defineProperty(L(n),Bc,{value:1,enumerable:!0}),n);function Uc(n){let e=L(n);return!!e&&(e[Bc]===1||Uc(e.innerType))}var m0=()=>fh(F().check(yo(500),rt(qt,"another app's address")));var Or=(n,e)=>`${e.kind}\0${e.id??""}\0${n.address}\0${n.kind}\0${n.id}`;function ph(n,e,t=()=>{}){let r=new Map,o=new Map,i=s=>{let a=Or(s,e),d=r.get(a);return d||(d=Promise.resolve().then(()=>n.resolve(s,e)).then(l=>hh(l)?l:null,()=>null).then(l=>(r.get(a)===d&&(o.set(a,l),t(s)),l)),r.set(a,d)),d};return{read(s){let a=Or(s,e);if(o.has(a)){let d=o.get(a);return d===null?{unread:!0}:"denied"in d?{denied:!0}:{record:d}}return i(s),{unread:!0}},ask:i,answered:s=>o.get(Or(s,e)),forget(s){if(!s){r.clear(),o.clear();return}let a=Or(s,e);r.delete(a),o.delete(a)}}}function hh(n){if(n===null)return!0;if(typeof n!="object"||n===void 0)return!1;if(n.denied===!0)return!0;let e=n;return typeof e.label=="string"&&typeof e.id=="string"&&typeof e.kind=="string"&&typeof e.fields=="object"&&e.fields!==null}var gh=1;var _r=(n,e)=>`${n}\0${e}`;function Ti(n){return n.op==="add-node"?Object.keys(n.node).filter(e=>e!=="id"&&e!=="kind").map(e=>[n.node.id,e]):n.op==="patch-node"?Object.keys(n.after).map(e=>[n.id,e]):n.op==="splice-text"?[[n.id,n.field]]:[]}var Ii=class n{revs=new Map;floor;constructor(e=0){this.floor=Math.max(0,Math.floor(e))-1}static of(e,t={}){let r=new n(t.horizon);return r.note(e),r}note(e){for(let t of e)for(let r of t.primitives)for(let[o,i]of Ti(r)){let s=_r(o,i);(this.revs.get(s)??this.floor)<t.seq&&this.revs.set(s,t.seq)}}of(e,t){return this.revs.get(_r(e,t))??this.floor}baseFor(e,t=new Set,r){let o=new Set,i=new Map;for(let s of e)for(let a of s.primitives)if(a.op==="add-node"&&o.add(a.node.id),!(a.op!=="patch-node"||o.has(a.id)||t.has(a.id)))for(let d of Object.keys(a.after)){let l=_r(a.id,d);t.has(l)||i.has(l)||r?.(a.id,d)||i.set(l,{node:a.id,field:d,rev:this.of(a.id,d)})}return[...i.values()]}stale(e){return e.filter(t=>this.of(t.node,t.field)>t.rev)}};function mh(n){let e=new Set;for(let t of n)for(let r of t.primitives){r.op==="add-node"&&e.add(r.node.id);for(let[o,i]of Ti(r))e.add(_r(o,i))}return e}var x0=Symbol.for("@graview/core:collaborative"),S0=n=>typeof n=="object"&&n!==null?n._zod?.def:void 0;var yh=/^#([0-9a-f]{3,8})$/i,bh=/(rgba?|hsla?)\(([^)]+)\)/gi;function vh(n){let e=yh.exec(n.trim());if(!e)return null;let t=e[1];if((t.length===3||t.length===4)&&(t=[...t].map(i=>i+i).join("")),t.length!==6&&t.length!==8)return null;let r=Number.parseInt(t.slice(0,6),16),o=t.length===8?Number.parseInt(t.slice(6,8),16)/255:1;return{r:r>>16&255,g:r>>8&255,b:r&255,a:o}}function wh(n){let e=n.slice(0,n.indexOf("(")).toLowerCase(),r=n.slice(n.indexOf("(")+1,n.lastIndexOf(")")).split(/[,\s/]+/).filter(Boolean).map(d=>d.endsWith("%")?Number.parseFloat(d)/100:Number.parseFloat(d));if(r.some(Number.isNaN))return null;if(e.startsWith("rgb")){let[d,l,u,p]=r;return d===void 0||l===void 0||u===void 0?null:{r:d,g:l,b:u,a:p??1}}let[o,i,s,a]=r;return o===void 0||i===void 0||s===void 0?null:{...qc(o,i>1?i/100:i,s>1?s/100:s),a:a??1}}function pn(n){let e=n.r/255,t=n.g/255,r=n.b/255,o=Math.max(e,t,r),i=Math.min(e,t,r),s=(o+i)/2;if(o===i)return{h:0,s:0,l:s};let a=o-i,d=a/(1-Math.abs(2*s-1));return{h:((o===e?60*((t-r)/a%6):o===t?60*((r-e)/a+2):60*((e-t)/a+4))+360)%360,s:d,l:s}}function Me(n,e,t){return{...qc(n,e,t),a:1}}function qc(n,e,t){let r=(1-Math.abs(2*t-1))*e,o=(n%360+360)%360/60,i=r*(1-Math.abs(o%2-1)),[s,a,d]=o<1?[r,i,0]:o<2?[i,r,0]:o<3?[0,r,i]:o<4?[0,i,r]:o<5?[i,0,r]:[r,0,i],l=t-r/2;return{r:Math.round((s+l)*255),g:Math.round((a+l)*255),b:Math.round((d+l)*255)}}function Y(n){let e=[];for(let t of n.matchAll(bh)){let r=wh(t[0]);r&&e.push(r)}for(let t of n.matchAll(/#[0-9a-fA-F]{3,8}\b/g)){let r=vh(t[0]);r&&e.push(r)}return e}function hn(n,e){let t=n.a+e.a*(1-n.a);if(t===0)return{r:0,g:0,b:0,a:0};let r=(o,i)=>(o*n.a+i*e.a*(1-n.a))/t;return{r:r(n.r,e.r),g:r(n.g,e.g),b:r(n.b,e.b),a:t}}function ji(n){let e=n/255;return e<=.03928?e/12.92:((e+.055)/1.055)**2.4}function Wc(n){return .2126*ji(n.r)+.7152*ji(n.g)+.0722*ji(n.b)}function ke(n,e){let[t,r]=[Wc(n),Wc(e)].sort((o,i)=>i-o);return(t+.05)/(r+.05)}function Pr(n){return ke({r:255,g:255,b:255,a:1},n)>ke({r:0,g:0,b:0,a:1},n)}var Er=(n,e)=>`rgba(${Math.round(n.r)}, ${Math.round(n.g)}, ${Math.round(n.b)}, ${e})`,Hc={r:0,g:0,b:0,a:1},Mr={r:255,g:255,b:255,a:1};function Nr(n){let e=Y(n.accent)[0];if(!e)return{ok:!1,missing:["accent"],why:`"${n.accent}" is not a color this can read. Use a hex, rgb() or hsl() value.`};let t={},r=new Set,o=[],i=pn(e);for(let s of["dark","light"]){let a=n.base[s],d=Y(a.ground)[0]??(s==="dark"?Hc:Mr),l=hn(Y(a.panel)[0]??Mr,d),u=Sh(i,[l,d],s,4.5);u?Math.abs(u.l-i.l)>xh&&(r.add(`accent (${s})`),o.push(`reaching 4.5:1 on the ${s} panel would move the accent's lightness by ${Math.round(Math.abs(u.l-i.l)*100)} points, which is far enough that it stops being the same color \u2014 supply one for ${s}`)):(r.add(`accent (${s})`),o.push(`no lightness of this hue clears 4.5:1 as text on the ${s} panel, so ${s} needs an accent of its own`));let p=u??i,c=Me(p.h,p.s,p.l),f=n.accentInk?.[s]??(ke(Mr,c)>=ke(Hc,c)?"#ffffff":"#000000"),g=ke(Y(f)[0]??Mr,c);g+.005<4.5&&(r.add(`accentInk (${s})`),o.push(`neither black nor white clears 4.5:1 on the accent (best ${g.toFixed(2)}:1), so text on a filled button has to be given`)),t[s]={...a,accent:Er(c,1),accentDim:Er(c,s==="dark"?.35:.22),accentInk:f,glow:Er(c,s==="dark"?.28:.1),edgeBright:Er(c,Di(c,l,s==="dark"?.55:.42,3)),...n.warn?.[s]?{warn:n.warn[s]}:{}};let h=Y(t[s].warn)[0];h&&kh(pn(h).h,p.h)<25&&(r.add(`warn (${s})`),o.push(`the warning color shares the accent's hue in ${s}, so "something is broken" looks like "this is selected"`))}return r.size>0?{ok:!1,missing:[...r].sort(),why:o.join("; ")}:{ok:!0,schemes:t}}function Di(n,e,t,r){for(let o=Math.round(t*100);o<=100;o++){let i=o/100;if(ke(hn({...n,a:i},e),e)>=r)return i}return 1}function kh(n,e){let t=Math.abs(n-e)%360;return t>180?360-t:t}var xh=.3;function Sh(n,e,t,r){let o=t==="dark";for(let i=0;i<=100;i++){let s=o?n.l+i/100:n.l-i/100,a=o?n.l-i/100:n.l+i/100;for(let d of[s,a])if(!(d<0||d>1)&&e.every(l=>ke(Me(n.h,n.s,d),l)>=r))return{...n,l:d}}return null}function Rh(n,e){let t=e?.[n];if(t!==void 0)return(t%360+360)%360;let r=2166136261;for(let o=0;o<n.length;o++)r^=n.charCodeAt(o),r=Math.imul(r,16777619);return(r>>>0)%360}var gn=Object.freeze({navy:"#001769",turquoise:"#00e5b9",paper:"#f7f7f2",ink:"#18213a",muted:"#586174"}),Fi="Montserrat",Li=Object.freeze({display:550,body:450,label:600}),Ci=Object.freeze({display:600,body:400,label:600}),$h="-0.025em",Ah=Object.freeze({minWidth:140,clearSpace:.5,microMax:24,regularMin:32,microBelow:28});var Jc={ground:"#0a0f1f",groundDeep:"#060914",wash:"none",panel:"rgba(19, 27, 52, 0.96)",panelMuted:"rgba(14, 21, 42, 0.94)",panelWarning:"rgba(48, 33, 18, 0.95)",edge:"rgba(164, 178, 222, 0.18)",edgeBright:"rgba(154, 171, 255, 0.6)",ink:"#eef0f6",inkMuted:"#aab2c6",inkFaint:"#97a0b6",accent:"#9aabff",accentDim:"rgba(154, 171, 255, 0.32)",accentInk:gn.navy,warn:"#f0a868",good:"#8fdcaa",bad:"#ffa3a3",glow:"rgba(154, 171, 255, 0.18)",bar:"rgba(10, 15, 31, 0.96)",float:"rgba(16, 23, 45, 0.98)",liftLow:"0 14px 36px -22px #000",liftHigh:"0 28px 64px -30px #000",tintAlpha:.2,tintLightness:52,gridAlpha:.35},Yc={ground:gn.paper,groundDeep:"#efefe8",wash:"none",panel:"#ffffff",panelMuted:"#fafaf6",panelWarning:"#fdf4ea",edge:"rgba(24, 33, 58, 0.12)",edgeBright:"rgba(0, 23, 105, 0.6)",ink:gn.ink,inkMuted:gn.muted,inkFaint:"#626b7d",accent:gn.navy,accentDim:"rgba(0, 23, 105, 0.16)",accentInk:"#ffffff",warn:"#9a5312",good:"#1b6436",bad:"#a1232d",glow:"rgba(0, 23, 105, 0.08)",bar:"rgba(255, 255, 255, 0.96)",float:"#ffffff",liftLow:"0 1px 2px rgba(24,33,58,0.06), 0 8px 24px -12px rgba(24,33,58,0.16)",liftHigh:"0 2px 6px rgba(24,33,58,0.08), 0 24px 56px -24px rgba(24,33,58,0.26)",tintAlpha:.16,tintLightness:46,gridAlpha:.5},Ke={dark:Jc,light:Yc};var Be=Object.freeze({radius:8,density:1,radiusSmall:.72,radiusSmallFloor:2,pad:15,padSmall:10,gap:7}),mn=Object.freeze({body:`"${Fi}", ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif`,mono:'ui-monospace, SFMono-Regular, "SF Mono", Menlo, monospace'});function Oh(n){let e=n?.shape?.radius??Be.radius,t=n?.shape?.density??Be.density;return Object.freeze({radius:e,radiusSmall:Math.max(Be.radiusSmallFloor,Math.round(e*Be.radiusSmall)),pad:Math.round(Be.pad*t),padSmall:Math.round(Be.padSmall*t),gap:Math.round(Be.gap*t)})}function _h(n){let e=n?.typography?.body??mn.body,t=n?.typography?.display??e,o=e===mn.body&&t===mn.body?Li:Ci,i=n?.typography?.weights;return Object.freeze({body:e,display:t,mono:n?.typography?.mono??mn.mono,weights:Object.freeze({display:i?.display??o.display,body:i?.body??o.body,label:i?.label??o.label})})}var z0=Object.freeze({light:Object.freeze({roof:Object.freeze({saturation:48,lightness:82}),right:Object.freeze({saturation:40,lightness:66}),left:Object.freeze({saturation:34,lightness:55}),roofEdge:"rgba(255,255,255,0.75)",plot:Object.freeze({saturation:45,lightness:58,alpha:.12}),plotEdge:Object.freeze({saturation:40,lightness:48,alpha:.55})}),dark:Object.freeze({roof:Object.freeze({saturation:42,lightness:32}),right:Object.freeze({saturation:40,lightness:21}),left:Object.freeze({saturation:38,lightness:13}),roofEdge:"rgba(255,255,255,0.14)",plot:Object.freeze({saturation:45,lightness:48,alpha:.2}),plotEdge:Object.freeze({saturation:40,lightness:62,alpha:.55})})});var Ph=64*1024;function Qc(n){return/^\s*(<\?xml[^>]*>\s*)?(<!--[\s\S]*?-->\s*)*(<!DOCTYPE svg[^>]*>\s*)?<svg[\s>/]/i.test(n)}var eu="http://www.w3.org/2000/svg",Eh=["http://www.w3.org/1999/xhtml","http://www.w3.org/1998/Math/MathML",eu],Mh=new Set("svg g defs symbol use title desc path rect circle ellipse line polyline polygon text tspan textPath linearGradient radialGradient stop pattern clipPath mask marker image filter feBlend feColorMatrix feComponentTransfer feComposite feDropShadow feFlood feFuncA feFuncB feFuncG feFuncR feGaussianBlur feMerge feMergeNode feMorphology feOffset feTile feTurbulence".split(" ")),Nh=new Set(["title","desc"]),Nt="it embeds a page or media",zh={script:"it has a script in it",foreignobject:"it embeds HTML (foreignObject)",iframe:Nt,embed:Nt,object:Nt,audio:Nt,video:Nt,style:"it has a style sheet in it; a mark is styled by its attributes",a:"it links to something (an <a> element)"},Ih={amp:"&",lt:"<",gt:">",quot:'"',apos:"'"};function Th(n){let e=!1,t=n.replace(/&(#x[0-9a-f]+|#[0-9]+|[a-z][a-z0-9]*);?/gi,(r,o)=>{if(o[0]==="#"){let s=o[1]==="x"||o[1]==="X"?parseInt(o.slice(2),16):parseInt(o.slice(1),10);return s>0&&s<=1114111?String.fromCodePoint(s):"\uFFFD"}let i=Ih[o.toLowerCase()];return i===void 0&&(e=!0),i??""});return e?null:t}function jh(n){if(/\\|@|expression\s*\(|(?:image-set|cross-fade|image|element|src)\s*\(/i.test(n))return!1;for(let[,e]of n.matchAll(/url\s*\(\s*["']?\s*([^)]*)/gi))if(!e.startsWith("#"))return!1;return!0}function Dh(n,e,t){let r=Th(t);if(r===null)return"it declares XML entities";let o=(e.includes(":")?e.slice(e.indexOf(":")+1):e).toLowerCase();if(o.startsWith("on"))return"it has an event handler (an on\u2026 attribute)";if(e==="xml:base")return"it loads or links to something outside itself";if(e==="xmlns")return r===eu?null:"it changes what its elements are (another xmlns)";if(e.startsWith("xmlns:"))return Eh.includes(r)?"it changes what its elements are (another xmlns)":null;if(o==="href"||o==="src"){let i=r.replace(/[\u0000- ]+/g,"");return i.startsWith("#")||n==="image"&&/^data:image\/(png|jpe?g|gif|webp|avif);/i.test(i)?null:"it loads or links to something outside itself"}return jh(r)?null:o==="style"?"its style loads something outside itself":"it loads or links to something outside itself"}var Xc=/^\s+([A-Za-z_][A-Za-z0-9_.:-]*)\s*=\s*(?:"([^"<]*)"|'([^'<]*)')/;function nu(n){if(/<!ENTITY/i.test(n))return"it declares XML entities";if(/<!\[CDATA\[/i.test(n))return"it has a CDATA section, which the page and the picture read differently";let e=[],t=!1,r=/^\s*(<\?xml\s[^?<>]*\?>)?/.exec(n)[0].length;for(;r<n.length;){let o=n.slice(r),i=/^[^<]+/.exec(o);if(i){if(e.length===0&&i[0].trim()!=="")return"it is not one SVG: there is text outside it";r+=i[0].length;continue}if(o.startsWith("<!--")){let f=o.indexOf("-->",4);if(f<0)return"it has a comment that never ends";let g=o.slice(4,f);if(/^-?>/.test(g)||g.includes("--")||g.includes("<!")||g.endsWith("-"))return"it has a comment the page and the picture read differently";r+=f+3;continue}if(/^<!DOCTYPE/i.test(o)){let f=/^<!DOCTYPE\s+svg\b[^<>[\]]*>/i.exec(o);if(!f||e.length>0||t)return"it declares XML entities";r+=f[0].length;continue}let s=/^<\/([A-Za-z][A-Za-z0-9_.:-]*)\s*>/.exec(o);if(s){if(e.pop()!==s[1])return`it is not one SVG: </${s[1]}> closes what is not open`;e.length===0&&(t=!0),r+=s[0].length;continue}let a=/^<([A-Za-z][A-Za-z0-9_.:-]*)/.exec(o);if(!a)return"it is not one SVG: it has markup a picture cannot hold";let d=a[1],l=zh[d.toLowerCase()];if(l)return l;if(t)return`it is not one SVG: <${d}> comes after it ends`;if(e.length===0&&d!=="svg")return"it is not one SVG";if(d.includes(":"))return`it has an element of another kind (<${d}>)`;if(!Mh.has(d))return`it has a <${d}> element, which a picture does not need`;let u=e[e.length-1];if(u&&Nh.has(u))return`it has an element inside a <${u}>, which the page reads as HTML`;let p=a[0].length;for(let f=Xc.exec(o.slice(p));f;f=Xc.exec(o.slice(p))){let g=Dh(d,f[1],f[2]??f[3]??"");if(g)return g;p+=f[0].length}let c=/^\s*(\/?)>/.exec(o.slice(p));if(!c)return/(?:^|[\s/"'])on[a-z]+\s*=/i.test(o.slice(p,p+400))?"it has an event handler (an on\u2026 attribute)":`it is not one SVG: <${d}>'s attributes are not each quoted and apart`;c[1]!=="/"?e.push(d):e.length===0&&(t=!0),r+=p+c[0].length}return e.length>0?`it is not one SVG: <${e[e.length-1]}> is never closed`:t?null:"it is not one SVG"}function tu(n){if(n){if(!Qc(n)){if(/^\s*</.test(n))return;let e=/^\s*([a-z][a-z0-9+.-]*):/i.exec(n)?.[1]?.toLowerCase();return e===void 0||e==="http"||e==="https"||e==="data"&&/^\s*data:image\//i.test(n)?n:void 0}return nu(n)===null?`data:image/svg+xml,${encodeURIComponent(n.trim())}`:void 0}}var zr;function Fh(){if(zr===void 0)try{zr=new RegExp("^\\p{RGI_Emoji}$","v")}catch{zr=null}return zr}function Lh(n){return/\p{Extended_Pictographic}|\p{Regional_Indicator}|⃣/u.test(n)}function Zi(n){if(typeof n!="string"||n.trim()==="")return"it is empty; give one emoji, like \u{1F3E1}";let e=[...new Intl.Segmenter("en",{granularity:"grapheme"}).segment(n)].map(o=>o.segment),t=e.filter(Lh).length;if(t===0)return"it is not an emoji; give one emoji, like \u{1F3E1}";if(e.length>1)return t===e.length?`it is ${e.length} emoji, and a mark is one`:"it has other characters beside the emoji; give the emoji alone";let r=Fh();return r&&!r.test(n)?"it is not one of the standard emoji every emoji set draws":null}function Gi(n){return typeof n=="object"&&n!==null&&typeof n.emoji=="string"?n.emoji:void 0}function ru(n){return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><text x="50" y="50" dy=".35em" font-size="88" text-anchor="middle">${n}</text></svg>`}function Ch(n){let e=n?.favicon;if(typeof e=="object"&&e!==null){let t=Gi(e);return t!==void 0&&Zi(t)===null?`data:image/svg+xml,${encodeURIComponent(ru(t))}`:void 0}return tu(e)}function Zh(n){let e=n?.logo;return typeof e=="string"?e===""?void 0:{light:e}:e&&typeof e.light=="string"&&e.light!==""?e:void 0}function Gh(n,e){if(e==="dark")return"dark";let t=n?.schemes?.light?.ground,r=t?Y(t)[0]:void 0;return r&&Pr(r)?"dark":"light"}function Vh(n){if(n?.logo)return;let e=Gi(n?.favicon);return e!==void 0&&Zi(e)===null?e:void 0}var ou="/graview/assets/";function Kh(n,e){return n&&e!==void 0&&e.startsWith(ou)?n(e):e}var iu={"system-sans":'ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif',"system-serif":'ui-serif, "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, Cambria, "Times New Roman", serif',"system-mono":mn.mono},Bh=["serif","sans-serif","monospace","cursive","fantasy","system-ui","math","emoji","-apple-system","BlinkMacSystemFont"],su=["Georgia","Times New Roman","Times","Iowan Old Style","Palatino","Palatino Linotype","Charter","Cambria","Baskerville","Optima","Helvetica","Helvetica Neue","Arial","Verdana","Segoe UI","Roboto","Avenir","Avenir Next","Gill Sans","Menlo","Monaco","Consolas","SF Mono","SFMono-Regular","Courier New"];var Uh=n=>new Set(n.map(e=>e.toLowerCase()));function Wh(n){return Uh([...Bh,...su]).has(n.toLowerCase())||n.toLowerCase().startsWith("ui-")}function qh(n){return iu[n]??n}function F0(n){if(/url\(|@import|[;{}<>\\]|\/\*|[\u0000-\u001f\u007f]/i.test(n))return"it is not a list of font names; a document names a face, never where one comes from";for(let e of n.split(",")){let t=e.trim();if(!(/^"[^"']*"$/.test(t)||/^'[^"']*'$/.test(t))&&/["']/.test(t))return`${t} is not quoted in one pair; write a face as Georgia or "Times New Roman"`}return null}var au={r:255,g:255,b:255,a:1},Hh={r:0,g:0,b:0,a:1},Bn=n=>`#${[n.r,n.g,n.b].map(e=>Math.round(Math.max(0,Math.min(255,e))).toString(16).padStart(2,"0")).join("")}`,Ue=(n,e)=>`rgba(${Math.round(n.r)}, ${Math.round(n.g)}, ${Math.round(n.b)}, ${e})`,Vi=(n,e,t)=>({r:n.r+(e.r-n.r)*t,g:n.g+(e.g-n.g)*t,b:n.b+(e.b-n.b)*t,a:1});function Jh(n){return typeof n=="string"?{light:n}:{...n.light?{light:n.light}:{},...n.dark?{dark:n.dark}:{}}}function Yh(n){let e=Y(n)[0];if(!e)return;let{h:t,s:r}=pn(e);return Bn(Me(t,Math.min(r,.45),.08))}function cu(n,e){let t=Y(n.edgeBright)[0];return Ue(t,Di({...t,a:1},e,t.a,3))}function Xh(n,e,t){let{h:r,s:o}=pn(t),i=Vi(t,au,.8);return{...n,ground:e,groundDeep:Bn(Vi(t,Hh,.04)),panel:Bn(i),panelMuted:Bn(Vi(t,au,.55)),edge:Ue(Me(r,Math.min(o,.5),.14),.14),edgeBright:cu(n,i),bar:Ue(i,.96),float:Bn(i)}}function du(n,e,t){let{h:r,s:o,l:i}=pn(t),s=a=>Me(r,o,Math.min(1,i+a));return{...n,ground:e,groundDeep:Bn(Me(r,o,i*.6)),panel:Ue(s(.07),.96),panelMuted:Ue(s(.035),.94),edge:Ue(Me(r,Math.min(o,.45),.75),.18),edgeBright:cu(n,hn({...s(.07),a:.96},t)),bar:Ue(t,.96),float:Ue(s(.05),.98)}}function uu(n){if(n===void 0)return Ke;let e=Jh(n),t=e.dark??(e.light?Yh(e.light):void 0),r=e.light?Y(e.light)[0]:void 0,o=t?Y(t)[0]:void 0;return{light:r?Pr(r)?du(Ke.dark,e.light,r):Xh(Ke.light,e.light,r):Ke.light,dark:o?du(Ke.dark,t,o):Ke.dark}}var Qh=[["ink","ink",["ground","panel","panelMuted","panelWarning","float","bar"],4.5],["inkMuted","muted ink",["ground","panel","panelMuted","float","bar"],4.5],["inkFaint","faint ink",["panel","panelMuted","float"],4.5],["accent","the accent",["ground","panel","float"],4.5],["warn","the warning color",["panel","panelWarning","float"],4.5],["good","the good status",["ground","panel"],4.5],["bad","the bad status",["ground","panel"],4.5],["edgeBright","the lit edge",["panel"],3]],eg={panel:"a card",panelMuted:"a receded card",panelWarning:"a flagged card",float:"a floating sheet",bar:"the bar"};function V0(n,e){for(let t of["light","dark"]){let r={...n[t],...t==="light"&&e?{accent:e}:{}},o=Y(r.ground)[0];for(let[i,s,a,d]of Qh)for(let l of a){let u=l==="ground"?[o]:Y(String(r[l])).map(p=>hn(p,o));for(let p of u){let c=hn(Y(String(r[i]))[0],p),f=ke(c,p);if(f<d)return{scheme:t,what:s,text:c,ground:o,...l==="ground"?{}:{card:p,surface:eg[l]},ratio:f,requires:d}}}}return null}function W0(n,e){let t=uu(e),r=Nr({accent:n,base:t});return r.ok||!r.missing.every(o=>o.startsWith("warn"))?r:Nr({accent:n,base:t,warn:{light:t.light.bad,dark:t.dark.bad}})}function ng(n,e,t){if(t.rows===0)return;let r=ue(n,e.rows).toLowerCase(),o=ue(n,e.columns).toLowerCase(),i=e.rows===e.columns,s=i?`link ${r} to each other`:`link ${r} to ${o}`;if(t.columns===0)return`No ${o} yet: ${s}.`;if(t.cells>0||typeof e.link=="object"&&e.link!==null)return;let a=X(n.tryDefinition(e.rows),e.rows);return i?`No ${a} is linked to another yet: ${s}.`:`No ${a} is linked to ${Rn(X(n.tryDefinition(e.columns),e.columns))} yet: ${s}.`}function tg(n,e){let t=o=>o?._zod?.def,r={};for(let o of new Set(e)){let i=n.tryDefinition(o),s=i?.fields?.shape??{};for(let[a,d]of Object.entries(s)){let l=t(d);for(let p=0;p<6&&l?.innerType!==void 0&&l.type!=="enum";p++)l=t(l.innerType);if(l?.type==="array"&&(l=t(l.element)),l?.type!=="enum"||!l.entries)continue;let u=i?.display?.format?.[a];(r[o]??={})[a]=Object.fromEntries(Object.values(l.entries).map(p=>[String(p),u?u(p):en(String(p))]))}}return r}var xe={connectors:{all:{route:"curve",visible:!0},byEdge:{}},captions:{visible:!0},grid:{visible:!0,size:64},lattice:{visible:!0,size:46},tags:{visible:!0},emphasis:{rest:.34,dim:.12},marks:{flag:"\u26A0"}};function rg(n){return n?{connectors:{all:{...xe.connectors.all,...n.connectors?.all??{}},byEdge:{...xe.connectors.byEdge,...n.connectors?.byEdge??{}}},captions:{...xe.captions,...n.captions??{}},grid:{...xe.grid,...n.grid??{}},lattice:{...xe.lattice,...n.lattice??{}},tags:{...xe.tags,...n.tags??{}},emphasis:{...xe.emphasis,...n.emphasis??{}},marks:{...xe.marks,...n.marks??{}}}:xe}function og(n,e){return{...n.connectors.all,...n.connectors.byEdge[e]??{}}}function ig(n){return[` --graview-kit-grid: ${n.grid.visible?1:0};`,` --graview-kit-grid-size: ${n.grid.size}px;`,` --graview-kit-lattice: ${n.lattice.visible?1:0};`,` --graview-kit-lattice-size: ${n.lattice.size}px;`,` --graview-kit-tags: ${n.tags.visible?"inline-flex":"none"};`,` --graview-kit-captions: ${n.captions.visible?"block":"none"};`,` --graview-kit-rest: ${n.emphasis.rest};`,` --graview-kit-dim: ${n.emphasis.dim};`,` --graview-kit-flag: "${n.marks.flag.replace(/"/g,"'")}";`].join(`
|
|
5
|
+
`)}var lu=n=>n?.kind==="visitor"||n?.onBehalfOf?.kind==="visitor",Ir=new WeakMap;function sg(n,e){e?Ir.set(n,e):Ir.delete(n)}function ag(n,e,t){if(!n||lu(t))return;let r=Ir.get(n)??Ir.get(Ki(n)?.store??{});if(r)try{r(e,t)}catch{}}function dg(n,e,t){let r=new Set([e]);for(let[o,i]of t.entries()){let s=n.edge(i);if(!s)return{ok:!1,at:o};let a=s.from,d=s.to==="*"?n.kinds:s.to,l=new Set;for(let u of r){if(a.includes(u))for(let p of d)l.add(p);if(s.to==="*"||d.includes(u))for(let p of a)l.add(p)}if(l.size===0)return{ok:!1,at:o};r=l}return{ok:!0,reached:r}}var fu="graview:fresh";function cg(n,e){let t=new URL(n),r="1";try{let o=Array.from(crypto.getRandomValues(new Uint8Array(16)),i=>i.toString(16).padStart(2,"0")).join("");(e??globalThis.sessionStorage).setItem(fu,o),r=o}catch{}return t.searchParams.set("fresh",r),t.toString()}export{On as a,wa as b,ka as c,ll as d,yo as e,tt as f,rt as g,F as h,$b as i,Ab as j,tn as k,Ob as l,_b as m,Pa as n,ot as o,Ea as p,se as q,_n as r,Pb as s,Na as t,Eb as u,za as v,it as w,W as x,Mb as y,Ut as z,Nb as A,zb as B,L as C,El as D,zt as E,Yn as F,Fr as G,Lr as H,hu as I,It as J,ug as K,te as L,Tt as M,gu as N,mu as O,Bi as P,lg as Q,jt as R,yu as S,Te as T,Cr as U,Ui as V,Zr as W,wu as X,ku as Y,$e as Z,xu as _,Su as $,Hi as aa,Ru as ba,$u as ca,Qe as da,Ft as ea,Ji as fa,B as ga,en as ha,gg as ia,Ou as ja,Vr as ka,K as la,_u as ma,Pu as na,ue as oa,Eu as pa,Mu as qa,Lt as ra,Rn as sa,X as ta,Ml as ua,Wt as va,wo as wa,Ia as xa,Ta as ya,ja as za,Nl as Aa,st as Ba,Fa as Ca,Iv as Da,Ht as Ea,Uc as Fa,m0 as Ga,Dl as Ha,Ll as Ia,Za as Ja,Cl as Ka,Fv as La,at as Ma,Zl as Na,Vl as Oa,Lv as Pa,Cv as Qa,Kl as Ra,Va as Sa,ph as Ta,Jt as Ua,Bl as Va,En as Wa,ct as Xa,Yt as Ya,Vv as Za,Mn as _a,Pn as $a,Ja as ab,ql as bb,Ro as cb,ut as db,ge as eb,me as fb,Hv as gb,$o as hb,Qt as ib,Jl as jb,Nn as kb,fe as lb,I as mb,ft as nb,N as ob,q as pb,H as qb,ef as rb,rr as sb,bw as tb,nf as ub,tf as vb,gh as wb,z as xb,Z as yb,ye as zb,be as Ab,To as Bb,jo as Cb,Do as Db,or as Eb,ae as Fb,Mw as Gb,ad as Hb,In as Ib,C as Jb,Tn as Kb,sn as Lb,de as Mb,df as Nb,ve as Ob,cn as Pb,wt as Qb,Ed as Rb,Md as Sb,he as Tb,Jf as Ub,si as Vb,ic as Wb,Cn as Xb,di as Yb,Qk as Zb,ci as _b,cc as $b,uc as ac,ui as bc,Ze as cc,kt as dc,xt as ec,op as fc,lc as gc,Yw as hc,gd as ic,Xw as jc,Qw as kc,sp as lc,cp as mc,pi as nc,hi as oc,gi as pc,At as qc,bc as rc,vr as sc,hp as tc,wr as uc,dn as vc,Ii as wc,mh as xc,kp as yc,ln as zc,Zn as Ac,Ot as Bc,yt as Cc,bt as Dc,sr as Ec,ar as Fc,x0 as Gc,S0 as Hc,dr as Ic,Bo as Jc,cr as Kc,xd as Lc,hf as Mc,Sd as Nc,vf as Oc,Y as Pc,Rh as Qc,Fi as Rc,$h as Sc,Ke as Tc,mn as Uc,Oh as Vc,_h as Wc,Qc as Xc,nu as Yc,tu as Zc,Ch as _c,Zh as $c,Gh as ad,Vh as bd,Kh as cd,Wh as dd,qh as ed,F0 as fd,uu as gd,V0 as hd,W0 as id,Ei as jd,Vp as kd,ng as ld,tg as md,rg as nd,og as od,ig as pd,wf as qd,kf as rd,xf as sd,Sf as td,vt as ud,un as vd,St as wd,fr as xd,we as yd,Gf as zd,Rf as Ad,$f as Bd,lu as Cd,sg as Dd,ag as Ed,dg as Fd,Op as Gd,_p as Hd,nc as Id,Pp as Jd,Tc as Kd,Vn as Ld,Oi as Md,zp as Nd,Ip as Od,Tp as Pd,jc as Qd,Pi as Rd,jp as Sd,Dp as Td,Ee as Ud,Et as Vd,Fp as Wd,Lp as Xd,Dc as Yd,Cp as Zd,Zp as _d,Fc as $d,Mt as ae,Bp as be,Zc as ce,Gc as de,qp as ee,Hp as fe,Jp as ge,Yp as he,Xp as ie,Vc as je,Qp as ke,eh as le,nh as me,th as ne,rh as oe,oh as pe,Ni as qe,ih as re,sh as se,ah as te,dh as ue,ch as ve,uh as we,lh as xe,cg as ye};
|