1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,940392,623032,e=>{"use strict";var t=e.i(95187);let r=(0,t.createServerReference)("406205dfd4271a65672b289a37e714d5244c290908",t.callServer,void 0,t.findSourceMapURL,"getPollData");e.s(["getPollData",0,r],940392),e.s(["getPublicationMetadataFromLeafletData",0,function(e){if(!e)return null;let t=e.leaflets_in_publications?.[0],r=e.leaflets_to_documents?.[0],n=e.publications?.[0];if(!t||!r||!n){for(let i of e.permission_token_rights[0].entity_sets?.permission_tokens||[])if(!t&&i.leaflets_in_publications?.length&&(t=i.leaflets_in_publications[0]),!r&&i.leaflets_to_documents?.length&&(r=i.leaflets_to_documents[0]),!n&&i.publications?.length&&(n=i.publications[0]),t&&r&&n)break}return t||(r?{...r,publications:null,doc:r.document}:n?{title:n.name||"",description:"",leaflet:e.id,doc:null,publications:n,documents:null,isPublicationDraft:!0}:null)}],623032)},868341,239337,710549,e=>{"use strict";var t=e.i(95187);let r=(0,t.createServerReference)("7ff563ec41b9b369fc3de51e4c8b3d772a8076bf5d",t.callServer,void 0,t.findSourceMapURL,"getIdentityData");e.s(["getIdentityData",0,r],868341);let n=(0,t.createServerReference)("7f86c87d487dc08716b663daa0db32604c535a27fb",t.callServer,void 0,t.findSourceMapURL,"getViewerIdentity");e.s(["getViewerIdentity",0,n],239337);let i=(0,t.createServerReference)("00e7cbfe8f47df59f7ef148e4cf8c63acc211af71a",t.callServer,void 0,t.findSourceMapURL,"getCurrentSessionToken");e.s(["getCurrentSessionToken",0,i],710549)},398920,e=>{"use strict";var t=e.i(843476),r=e.i(500932),n=e.i(935593),i=e.i(271645),a=e.i(283599),s=e.i(606368),o=e.i(314192);let l=(0,i.createContext)({name:"",did:""});function u(){let e,t,s=(0,r.c)(6),{name:o,did:u}=(0,i.useContext)(l),c=`publication-data-${u}-${o}`;s[0]!==u||s[1]!==o?(e=async()=>(await (0,n.callRPC)("get_publication_data",{publication_name:o,did:u}))?.result,s[0]=u,s[1]=o,s[2]=e):e=s[2];let{data:h,mutate:d}=(0,a.default)(c,e);return s[3]!==h||s[4]!==d?(t={data:h,mutate:d},s[3]=h,s[4]=d,s[5]=t):t=s[5],t}e.s(["PublicationSWRDataProvider",0,function(e){let n,i,s,o,u=(0,r.c)(12),c=`publication-data-${e.publication_did}-${e.publication_rkey}`;return u[0]!==e.publication_did||u[1]!==e.publication_rkey?(n={name:e.publication_rkey,did:e.publication_did},u[0]=e.publication_did,u[1]=e.publication_rkey,u[2]=n):n=u[2],u[3]!==c||u[4]!==e.publication_data?(i={fallback:{[c]:e.publication_data}},u[3]=c,u[4]=e.publication_data,u[5]=i):i=u[5],u[6]!==e.children||u[7]!==i?(s=(0,t.jsx)(a.SWRConfig,{value:i,children:e.children}),u[6]=e.children,u[7]=i,u[8]=s):s=u[8],u[9]!==n||u[10]!==s?(o=(0,t.jsx)(l,{value:n,children:s}),u[9]=n,u[10]=s,u[11]=o):o=u[11],o},"mutatePublicationData",0,function(e,t){e(e=>e?(0,s.produce)(e,t):e,{revalidate:!1})},"useNormalizedPublicationRecord",0,function(){let e,t=(0,r.c)(2),{data:n}=u();n?.publication?.record;let i=n?.publication?.record;return t[0]!==i?(e=(0,o.normalizePublicationRecord)(i),t[0]=i,t[1]=e):e=t[1],e},"usePublicationData",0,u])},935593,e=>{"use strict";let t=async(e,t)=>(await fetch(`/api/rpc/${e}`,{body:JSON.stringify(t),method:"POST",headers:{"Content-type":"application/json"}})).json();e.s(["callRPC",0,t],935593)},806398,622616,370682,e=>{"use strict";var t=e.i(843476),r=e.i(500932),n=e.i(868341),i=e.i(239337),a=e.i(710549),s=e.i(271645),o=e.i(283599),l=e.i(72545),u=e.i(271235),c=e.i(738954),h=e.i(606368);let d="leaflet-saved-accounts";function p(){try{let e=window.localStorage.getItem(d);if(!e)return[];let t=JSON.parse(e);if(!Array.isArray(t))return[];return t.filter(e=>!!e&&"string"==typeof e.token&&"string"==typeof e.identity)}catch{return[]}}function f(e){try{window.localStorage.setItem(d,JSON.stringify(e.slice(0,12)))}catch{}}function m(e){f([e,...p().filter(t=>t.identity!==e.identity)])}function g(){(0,l.mutate)("saved-accounts")}async function y(e,t){try{let r=await fetch("/api/auth/switch-account",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:e.token,logoutCurrent:!!t?.logoutCurrent})});if(!r.ok)return!1;let n=await r.json();return!0===n.ok}catch{return!1}}function b(){return p()}e.s(["mutateSavedAccounts",0,g,"readSavedAccountEntries",0,p,"removeSavedAccountEntry",0,function(e){f(p().filter(t=>t.identity!==e))}
1,"switchToSavedAccount",0,y,"upsertSavedAccountEntry",0,m,"useSavedAccounts",0,function(){let e,t=(0,r.c)(1);return t[0]===Symbol.for("react.memo_cache_sentinel")?(e={fallbackData:p()},t[0]=e):e=t[0],(0,o.default)("saved-accounts",b,e)}],622616);var w=e.i(255512);let v="leaflet-identity-change";function _(e){let t=(0,s.useRef)(e);t.current=e,(0,s.useEffect)(()=>{if("u"<typeof BroadcastChannel)return;let e=new BroadcastChannel(v);return e.onmessage=e=>{let r=e.data?.identity;t.current("string"==typeof r?r:null)},()=>e.close()},[])}function k(e){let t,n=(0,r.c)(2);n[0]!==e?(t=t=>{(null===t||t!==e)&&window.location.reload()},n[0]=e,n[1]=t):t=n[1],_(t)}e.s(["broadcastIdentityChange",0,function(e){if("u"<typeof BroadcastChannel)return;let t=new BroadcastChannel(v);t.postMessage({identity:e}),t.close()},"useIdentityChangeListener",0,_,"useReloadOnIdentityChange",0,k],370682);let S="viewer-identity",I=(0,s.createContext)({identity:null,mutate:()=>{},identityPending:!1}),x=s.useLayoutEffect;function D(){}function E(){return(0,n.getIdentityData)()}function N(){return(0,n.getIdentityData)()}function $(){return(0,i.getViewerIdentity)()}e.s(["ClientIdentityProvider",0,function(e){let n,i,a,l,u,c,h,d=(0,r.c)(13);d[0]===Symbol.for("react.memo_cache_sentinel")?(n={revalidateOnFocus:!1,revalidateOnReconnect:!1,revalidateIfStale:!1,revalidateOnMount:!1},d[0]=n):n=d[0];let{data:p,mutate:f,isValidating:m}=(0,o.default)("identity",N,n),[g,y]=(0,s.useState)(!1);d[1]===Symbol.for("react.memo_cache_sentinel")?(i=()=>{(0,w.hasSessionMarker)()&&y(!0)},a=[],d[1]=i,d[2]=a):(i=d[1],a=d[2]),x(i,a),d[3]!==f?(l=()=>{(0,w.hasSessionMarker)()&&f().finally(()=>y(!1))},d[3]=f,d[4]=l):l=d[4],d[5]===Symbol.for("react.memo_cache_sentinel")?(u=[],d[5]=u):u=
1d[5],(0,s.useEffect)(l,u),k(p?.id??null);let b=p??null,v=!p&&(g||m);return d[6]!==f||d[7]!==b||d[8]!==v?(c={identity:b,mutate:f,identityPending:v},d[6]=f,d[7]=b,d[8]=v,d[9]=c):c=d[9],d[10]!==e.children||d[11]!==c?(h=(0,t.jsx)(I.Provider,{value:c,children:e.children}),d[10]=e.children,d[11]=c,d[12]=h):h=d[12],h},"IdentityContext",0,I,"IdentityContextProvider",0,function(e){let n,i,l,u,h,d,p,f,y,b=(0,r.c)(22),w=e.identityPromise?(0,s.use)(e.identityPromise):e.initialValue??null;b[0]!==w?(n={fallbackData:w,revalidateOnFocus:!1,revalidateOnReconnect:!1,revalidateIfStale:!1,revalidateOnMount:!1},b[0]=w,b[1]=n):n=b[1];let{data:v,mutate:_}=(0,o.default)("identity",E,n);b[2]!==w||b[3]!==_?(i=()=>{_(e=>e&&w&&e.fetched_at>w.fetched_at?e:w,{revalidate:!1})},b[2]=w,b[3]=_,b[4]=i):i=b[4],b[5]!==w?(l=[w],b[5]=w,b[6]=l):l=b[6],(0,s.useEffect)(i,l),b[7]!==v?(u=()=>{if(!v?.id)return;let e=v.id,t={email:v.email,did:v.atp_did,handle:v.bsky_profiles?.record.handle??null,displayName:v.bsky_profiles?.record.displayName??null,avatar:v.bsky_profiles?.record.avatar??null};(0,a.getCurrentSessionToken)().then(r=>{r?.identity===e&&(m({token:r.token,identity:e,...t}),g())}).catch(D)},b[7]=v,b[8]=u):u=b[8];let S=v?.id;b[9]!==S?(h=[S],b[9]=S,b[10]=h):h=b[10],(0,s.useEffect)(u,h),k(v?.id??null),b[11]!==v||b[12]!==_?(d=()=>{if(!v?.atp_did)return;let e=(0,c.supabaseBrowserClient)().channel(`identity.atp_did:${v.atp_did}`);return e.on("broadcast",{event:"notification"},()=>{_()}),e.subscribe(),()=>{e.unsubscribe()}},b[11]=v,b[12]=_,b[13]=d):d=b[13];let x=v?.atp_did;return b[14]!==x?(p=[x],b[14]=x,b[15]=p):p=b[15],(0,s.useEffect)(d,p),b[16]!==v||b[17]!==_?(f={identity:v,mutate:_,identityPending:!1},b[16]=v,b[17]=_,b[18]=f):f=b[18],b[19]!==e.children||b[20]!==f?(y=(0,t.jsx)(I.Provider,{value:f,children:e.children}),b[19]=e.children,b[20]=f,b[21]=y):y=b[21],y},"VIEWER_IDENTITY_KEY",0,S,"ViewerIdentityProvider",0,function(e){let n,i,a,l,c,h,d,p,f,m=(0,r.c)(18),{cache:g}=(0,u.useSWRConfig)();m[0]!==g?(n=g.get("identity")?.data??null,m[0]=g,m[1]=n):n=m[1];let y=n;m[2]!==y?(i={fallbackData:y,revalidateOnFocus:!1,revalidateOnReconnect:!1,revalidateIfStale:!1,revalidateOnMount:!1},m[2]=y,m[3]=i):i=m[3];let{data:b,mutate:v,isValidating:k}=(0,o.default)(S,$,i),[D,E]=(0,s.useState)(!1);m[4]===Symbol.for("react.memo_cache_sentinel")?(a=()=>{(0,w.hasSessionMarker)()&&E(!0)},l=[],m[4]=a,m[5]=l):(a=m[4],l=m[5]),x(a,l),m[6]!==v?(c=()=>{(0,w.hasSessionMarker)()&&v().finally(()=>E(!1))},m[6]=v,m[7]=c):c=m[7],m[8]===Symbol.for("react.memo_cache_sentinel")?(h=[],m[8]=h):h=m[8],(0,s.useEffect)(c,h),m[9]!==v?(d=()=>{v()},m[9]=v,m[10]=d):d=m[10],_(d);let N=b??null,C=!b&&(D||k);return m[11]!==v||m[12]!==N||m[13]!==C?(p={identity:N,mutate:v,identityPending:C},m[11]=v,m[12]=N,m[13]=C,m[14]=p):p=m[14],m[15]!==e.children||m[16]!==p?(f=(0,t.jsx)(I.Provider,{value:p,children:e.children}),m[15]=e.children,m[16]=p,m[17]=f):f=m[17],f},"clearIdentityData",0,function(){(0,l.mutate)("identity",null,{revalidate:!1}),(0,l.mutate)(S,null,{revalidate:!1})},"mutateIdentityData",0,function(e,t){e(e=>e?(0,h.produce)(e,t):e,{revalidate:!1})},"refreshIdentityData",0,function(){(0,l.mutate)("identity"),(0,l.mutate)(S)},"updateIdentityData",0,function(e){let t=t=>t?(0,h.produce)(t,t=>{e(t),t.fetched_at=Date.now()}):t;(0,l.mutate)("identity",t,{revalidate:!0}),(0,l.mutate)(S,t,{revalidate:!0})},"useIdentityData",0,()=>(0,s.useContext)(I)],806398)},876082,e=>{"use strict";var t=e.i(843476),r=e.i(500932),n=e.i(283599),i=e.i(467592),a=e.i(935593),s=e.i(940392),o=e.i(271645),l=e.i(623032),u=e.i(250209),c=e.i(620196),h=e.i(314192);let d=(0,o.createContext)(null);function p(e){return e.entity_set}let f=()=>{let e,t=(0,r.c)(5),{permission_token:s}=(0,i.useReplicache)(),l=(0,o.useContext)(d);t[0]!==s.id?(e=async()=>s.id?(await (0,a.callRPC)("get_leaflet_data",{token_id:s.id}))?.result.data:void 0,t[0]=s.id,t[1]=e):e=t[1];let u=(0,n.default)(l?null:`${s.id}-leaflet_data`,e);if(l){let e;return t[2]!==u.mutate||t[3]!==l?(e={data:l,mutate:u.mutate},t[2]=u.mutate,t[3]=l,t[4]=e):e=t[4],e}return u};function m(e){return!!e.document}function g(e){return e.doc}e.s(["PageSWRDataProvider",0,function(e){return(0,t.jsx)(n.SWRConfig,{value:{fallback:{poll_data:e.poll_data,[`${e.leaflet_id}-leaflet_data`]:e.leaflet_data.data}},children:e.children})},"StaticLeafletDataContext",0,d,"useLeafletDomains",0,function(){let e,t=(0,r.c)(3),{data:n,mutate:i}=f(),a=n?.custom_domain_routes;return t[0]!==i||t[1]!==a?(e={data:a,mutate:i},t[0]=i,t[1]=a,t[2]=e):e=t[2],e},"useLeafletPublicationData",0,function(){let{data:e,mutate:t}=f(),r=(0,l.getPublicationMetadataFromLeafletData)(e),n=(0,o.useMemo)(()=>(0,h.normalizePublicationRecord)(r?.publications?.record),[r?.publications?.record]),i=(0,o.useMemo)(()=>(0,h.normalizeDocumentRecord)(r?.documents?.data),[r?.documents?.data]);return{data:r||null,normalizedPublication:n,normalizedDocument:i,mutate:t}},"useLeafletPublicationPage",0,function(){let{data:e}=f();return e?.publications?.[0]??null},"useLeafletPublicationStatus",0,function(){let e,t,n,i,a,s=(0,r.c)(14),l=(0,o.useContext)(d);if(!l)return null;if(s[0]!==l.leaflets_in_publications||s[1]!==l.leaflets_to_documents){n=l.leaflets_in_publications?.find(g),i=l.leaflets_to_documents?.find(m),e=n?.doc??i?.document;let r=n?.documents??i?.documents;if(e&&r){let i=(0,h.normalizeDocumentRecord)(r.data,e);i&&(t=(0,u.getDocumentURL)(i,e,n?.publications??void 0))}if(!t&&e){let r=new c.AtUri(e);t=`/p/${r.host}/${r.rkey}`}s[0]=l.leaflets_in_publications,s[1]=l.leaflets_to_documents,s[2]=e,s[3]=t,s[4]=n,s[5]=i}else e=s[2],t=s[3],n=s[4],i=s[5];let p=l.leaflets_in_publications?.[0]?.publication??void 0,f=n?.publication??l.leaflets_in_publications?.[0]?.publication??void 0,y=!!(n||i),b=n?.documents?.indexed_at??i?.documents?.indexed_at;return s[6]!==l||s[7]!==e||s[8]!==t||s[9]!==p||s[10]!==f||s[11]!==y||s[12]!==b?(a={token:l,leafletId:l.root_entity,shareLink:l.id,draftInPublication:p,publicationUri:f,isPublished:y,publishedAt:b,documentUri:e,postShareLink:t},s[6]=l,s[7]=e,s[8]=t,s[9]=p,s[10]=f,s[11]=y,s[12]=b,s[13]=a):a=s[13],a},"usePollData",0,function(){let e,t=(0,r.c)(2),{permission_token:a}=(0,i.useReplicache)();return t[0]!==a.permission_token_rights?(e=()=>(0,s.getPollData)(a.permission_token_rights.map(p)),t[0]=a.permission_token_rights,t[1]=e):e=t[1],(0,n.default)("poll_data",e)}])},850952,797506,e=>{"use strict";
1e.s(["PublicationBackgroundProvider",()=>g,"PublicationThemeProvider",()=>y,"PublicationThemeProviderDashboard",()=>m,"PublicationThemeWrapper",()=>b,"WithPublicationTheme",()=>w,"useLocalPubTheme",()=>_,"usePubTheme",()=>v],850952);var t=e.i(843476),r=e.i(500932),n=e.i(271645),i=e.i(768928),a=e.i(467592),s=e.i(629683),o=e.i(970827),l=e.i(593302),u=e.i(615405),c=e.i(398920),h=e.i(124670);let d={backgroundColor:"#FDFCFA",pageBackground:"#FDFCFA",primary:"#272727",accentText:"#FFFFFF",accentBackground:"#57822B"};e.s(["PubThemeDefaults",0,d],797506);let p=(e,t)=>(0,n.useMemo)(()=>{let r=e?.[t];return f(r)?"pub.leaflet.theme.color#rgba"===r.$type?(0,i.parseColor)(`rgba(${r.r}, ${r.g}, ${r.b}, ${r.a/100})`):(0,i.parseColor)(`rgb(${r.r}, ${r.g}, ${r.b})`):(0,i.parseColor)(d[t])},[e?.[t]]),f=e=>e?.$type==="pub.leaflet.theme.color#rgb"||e?.$type==="pub.leaflet.theme.color#rgba";function m(e){let n,i,a,s=(0,r.c)(10),{data:o}=(0,c.usePublicationData)();s[0]!==o?(n=o||{},s[0]=o,s[1]=n):n=s[1];let{publication:l}=n,u=(0,c.useNormalizedPublicationRecord)(),h=l?.identity_did||"",d=l?.i
1dentity_did||"";return s[2]!==u||s[3]!==e.children||s[4]!==d?(i=(0,t.jsx)(g,{record:u,pub_creator:d,children:e.children}),s[2]=u,s[3]=e.children,s[4]=d,s[5]=i):i=s[5],s[6]!==u||s[7]!==h||s[8]!==i?(a=(0,t.jsx)(y,{pub_creator:h,record:u,children:i}),s[6]=u,s[7]=h,s[8]=i,s[9]=a):a=s[9],a}function g(e){let n,i,a=(0,r.c)(8),s=void 0!==e.localBgImage?e.localBgImage:e.record?.theme?.backgroundImage?.image?.ref?(0,h.blobRefToSrc)(e.record?.theme?.backgroundImage?.image?.ref,e.pub_creator):null,o=void 0!==e.localBgImageRepeat?!!e.localBgImageRepeat:e.record?.theme?.backgroundImage?.repeat,l=(void 0!==e.localBgImageRepeat?e.localBgImageRepeat:e.record?.theme?.backgroundImage?.width)||500,u=`PubBackgroundWrapper w-full bg-bg-leaflet text-primary h-full flex flex-col bg-cover bg-center bg-no-repeat items-stretch ${e.className}`,c=s?`url(${s})`:void 0,d=o?"repeat":"no-repeat",p=`${o?`${l}px`:"cover"}`;return a[0]!==c||a[1]!==d||a[2]!==p?(n={backgroundImage:c,backgroundRepeat:d,backgroundSize:p},a[0]=c,a[1]=d,a[2]=p,a[3]=n):n=a[3],a[4]!==e.children||a[5]!==u||a[6]!==n?(i=(0,t.jsx)("div",{className:u,style:n,children:e.children}),a[4]=e.children,a[5]=u,a[6]=n,a[7]=i):i=a[7],i}function y(e){let n,i,a=(0,r.c)(8),s=v(e.record,e.isStandalone),l=!s.showPageBackground,u=!!e.record?.theme?.backgroundImage?.image?.ref;return a[0]!==u||a[1]!==e.children||a[2]!==e.local||a[3]!==s?(n=(0,t.jsx)(o.BaseThemeProvider,{local:e.local,...s,hasBackgroundImage:u,children:e.children}),a[0]=u,a[1]=e.children,a[2]=e.local,a[3]=s,a[4]=n):n=a[4],a[5]!==l||a[6]!==n?(i=(0,t.jsx)(o.CardBorderHiddenContext.Provider,{value:l,children:n}),a[5]=l,a[6]=n,a[7]=i):i=a[7],i}function b(e){let n,i,a=(0,r.c)(8),s=!e.pubRecord,l=v(e.pubRecord?.theme||e.pubRecord?.basicTheme?e.pubRecord:e.postRecord,s);if(!1===e.enabled){let r;return a[0]!==e.children?(r=(0,t.jsx)(t.Fragment,{children:e.children}),a[0]=e.children,a[1]=r):r=a[1],r}let u=!l.showPageBackground;return a[2]!==e.children||a[3]!==l?(n=(0,t.jsx)(o.BaseThemeProvider,{local:!0,...l,children:e.children}),a[2]=e.children,a[3]=l,a[4]=n):n=a[4],a[5]!==u||a[6]!==n?(i=(0,t.jsx)(o.CardBorderHiddenContext.Provider,{value:u,children:n}),a[5]=u,a[6]=n,a[7]=i):i=a[7],i}function w(e){let n,i,a=(0,r.c)(10),{record:s,uri:o,enabled:u,children:c}=e;if(!u||!s||!o||!s.theme&&!s.basicTheme){let e;return a[0]!==c?(e=(0,t.jsx)(t.Fragment,{children:c}),a[0]=c,a[1]=e):e=a[1],e}try{let e;a[2]!==o?(e=new l.AtUri(o),a[2]=o,a[3]=e):e=a[3],n=e.host}catch{let e;return a[4]!==c?(e=(0,t.jsx)(t.Fragment,{children:c}),a[4]=c,a[5]=e):e=a[5],e}return a[6]!==c||a[7]!==n||a[8]!==s?(i=(0,t.jsx)(y,{local:!0,record:s,pub_creator:n,children:c}),a[6]=c,a[7]=n,a[8]=s,a[9]=i):i=a[9],i}let v=(e,t)=>{let n,o,l,c=(0,r.c)(16);c[0]!==e?(o=(0,u.resolvePublicationTheme)(e),c[0]=e,c[1]=o):o=c[1];
1let h=p(n=o,"backgroundColor"),d=p(n,"pageBackground");if(t&&!n?.pageBackground){let e;c[2]===Symbol.for("react.memo_cache_sentinel")?(e=(0,i.parseColor)("#FFFFFF"),c[2]=e):e=c[2],d=e}else n&&!n.pageBackground&&(d=h);let f=t?n?.showPageBackground!==!1:!!n?.showPageBackground,m=n?.pageWidth,g=p(n,"primary"),y=p(n,"accentBackground"),b=p(n,"accentText"),w=(0,a.useEntity)(null,"theme/highlight-1")?.data.value,v=(0,s.useColorAttribute)(null,"theme/highlight-2"),_=(0,s.useColorAttribute)(null,"theme/highlight-3"),k=n?.headingFont,S=n?.bodyFont;return c[3]!==y||c[4]!==b||c[5]!==h||c[6]!==d||c[7]!==S||c[8]!==k||c[9]!==w||c[10]!==v||c[11]!==_||c[12]!==m||c[13]!==g||c[14]!==f?(l={bgLeaflet:h,bgPage:d,primary:g,accent1:y,accent2:b,highlight1:w,highlight2:v,highlight3:_,showPageBackground:f,pageWidth:m,headingFontId:k,bodyFontId:S},c[3]=y,c[4]=b,c[5]=h,c[6]=d,c[7]=S,c[8]=k,c[9]=w,c[10]=v,c[11]=_,c[12]=m,c[13]=g,c[14]=f,c[15]=l):l=c[15],l},_=(e,t)=>{let i,a,s,o,l,u,c,h=(0,r.c)(13);h[0]!==e?(i={theme:e},h[0]=e,h[1]=i):i=h[1];let d=v(i);h[2]===Symbol.for("react.memo_cache_sentinel")?(a={},h[2]=a):a=h[2];let[p,f]=(0,n.useState)(a);h[3]!==p||h[4]!==d||h[5]!==t?(o={...d,...p,showPageBackground:t},h[3]=p,h[4]=d,h[5]=t,h[6]=o):o=h[6];let m=o;h[7]!==m?(l={...m},h[7]=m,h[8]=l):l=h[8],s=l,h[9]===Symbol.for("react.memo_cache_sentinel")?(u=()=>f({}),h[9]=u):u=h[9];let g=Object.keys(p).length>0;return h[10]!==s||h[11]!==g?(c={theme:s,setTheme:f,resetChanges:u,changes:g},h[10]=s,h[11]=g,h[12]=c):c=h[12],c}},970827,88046,e=>{"use strict";e.s(["BaseThemeProvider",()=>I,"CardBorderHiddenContext",()=>b,"CardThemeProvider",()=>E,"LeafletThemeProvider",()=>S,"NestedCardThemeProvider",()=>
1D,"ThemeBackgroundProvider",()=>N,"ThemeProvider",()=>k,"useCardBorderHiddenContext",()=>w],970827);var t=e.i(843476),r=e.i(500932),n=e.i(271645),i=e.i(629683),a=e.i(768928),s=e.i(467592),o=e.i(876082),l=e.i(850952),u=e.i(269548);let c={quattro:{id:"quattro",displayName:"iA Writer Quattro",fontFamily:"iA Writer Quattro V",baseSize:16,type:"system",fallback:["system-ui","sans-serif"]},lora:{id:"lora",displayName:"Lora",fontFamily:"Lora",baseSize:17,type:"google",googleFontsFamily:"Lora:ital,wght@0,400..700;1,400..700",fallback:["Georgia","serif"]},"atkinson-hyperlegible":{id:"atkinson-hyperlegible",displayName:"Atkinson Hyperlegible",fontFamily:"Atkinson Hyperlegible Next",baseSize:18,type:"google",googleFontsFamily:"Atkinson+Hyperlegible+Next:ital,wght@0,200..800;1,200..800",fallback:["system-ui","sans-serif"]},"sometype-mono":{id:"sometype-mono",displayName:"Sometype Mono",fontFamily:"Sometype Mono",baseSize:17,type:"google",googleFontsFamily:"Sometype+Mono:ital,wght@0,400;0,700;1,400;1,700",fallback:["monospace"]},montserrat:{id:"montserrat",displayName:"Montserrat",fontFamily:"Montserrat",baseSize:17,type:"google",googleFontsFamily:"Montserrat:ital,wght@0,400;0,700;1,400;1,700",fallback:["system-ui","sans-serif"]},"source-sans":{id:"source-sans",displayName:"Source Sans 3",fontFamily:"Source Sans 3",baseSize:18,type:"google",googleFontsFamily:"Source+Sans+3:ital,wght@0,400;0,700;1,400;1,700",fallback:["system-ui","sans-serif"]}},h="quattro";function d(e){return e.startsWith("custom:")}function p(e){if(!e)return c[h];if(d(e)){let t=function(e){if(!d(e))return null;let t=e.slice(7).split(":");return t.length<2?null:{fontName:t[0],googleFontsFamily:t.slice(1).join(":")}}(e);if(t)return{id:e,displayName:t.fontName,fontFamily:t.fontName,type:"google",googleFontsFamily:function(e){let[t,r]=e.split(/:(.+)/);if(!t||r&&r.includes("ital"))return e;if(r){let e=r.match(/wght@(.+)/);if(e){let r=e[1];if(r.includes(".."))return`${t}:ital,wght@0,${r};1,${r}`;let n=r.split(";").map(e=>`0,${e}`),i=r.split(";").map(e=>`1,${e}`);return`${t}:ital,wght@${[...n,...i].join(";")}`}}return`${t}:ital,wght@0,400;0,700;1,400;1,700`}(t.googleFontsFamily),fallback:["system-ui","sans-serif"]}}return c[e]||c[h]}function f(e){return"google"!==e.type?null:`https://fonts.googleapis.com/css2?family=${e.googleFontsFamily}&display=swap`}function m(e){return e.baseSize??16}function g(e){return"google"!==e.type?null:`${e.fontFamily} Fallback`}function y(e){let t=e.fontFamily.includes(" ")?`'${e.fontFamily}'`:e.fontFamily,r=g(e);return[t,...r?[`'${r}'`]:[],...e.fallback].join(", ")}e.s(["createCustomFontId",0,function(e,t){return`custom:${e}:${t}`},"defaultFontId",0,h,"fonts",0,c,"getFontBaseSize",0,m,"getFontConfig",0,p,"getFontFamilyValue",0,y,"getGoogleFontsUrl",0,f,"getMetricFallbackName",0,g,"isCustomFontId",0,d,"parseGoogleFontInput",0,function(e){let t=e.trim();if(!t)return null;try{let e=new URL(t).searchParams.get("family");if(e)return{fontName:e.split(":")[0].replace(/\+/g," "),googleFontsFamily:e}}catch{}return t.includes(":")||t.includes("@")?{fontName:t.split(":")[0].replace(/\+/g," "),googleFontsFamily:t.includes("+")?t:t.replace(/ /g,"+")}:{fontName:t.replace(/\+/g," "),googleFontsFamily:`${t.replace(/ /g,"+")}:ital,wght@0,400;0,700;1,400;1,700`}}],88046);let b=(0,n.createContext)(!1);function w(){return(0,n.useContext)(b)}let v=(0,n.createContext)(!1);function _(e,t,r){e?.style.setProperty(t,(0,i.colorToString)(r,"rgb"))}function k(e){let n,i=(0,r.c)(6),{data:a,normalizedPublication:s}=(0,o.useLeafletPublicationData)();if(!a||!a.publications){let r;return i[0]!==e?(r=(0,t.jsx)(S,{...e}),i[0]=e,i[1]=r):r=i[1],r}let u=a.publications?.identity_did;return i[2]!==s||i[3]!==e||i[4]!==u?(n=(0,t.jsx)(l.PublicationThemeProvider,{...e,record:s,pub_creator:u}),i[2]=s,i[3]=e,i[4]=u,i[5]=n):n=i[5],n}function S(e){let n,a,o,l=(0,r.c)(22),u=(0,i.useColorAttribute)(e.entityID,"theme/page-background"),c=(0,i.useColorAttribute)(e.entityID,"theme/card-background"),h=(0,s.useEntity)(e.entityID,"theme/card-border-hidden")?.data.value,d=!h,p=!!(0,s.useEntity)(e.entityID,"theme/background-image"),f=(0,i.useColorAttribute)(e.entityID,"theme/primary"),m=(0,s.useEntity)(e.entityID,"theme/highlight-1"),g=(0,i.useColorAttribute)(e.entityID,"theme/highlight-2"),y=(0,i.useColorAttribute)(e.entityID,"theme/highlight-3"),w=(0,i.useColorAttribute)(e.entityID,"theme/accent-background"),_=(0,i.useColorAttribute)(e.entityID,"theme/accent-text"),k=(0,s.useEntity)(e.entityID,"theme/page-width"),S=(0,s.useEntity)(e.entityID,"theme/heading-font")?.data.value??e.initialHeadingFontId,x=(0,s.useEntity)(e.entityID,"theme/body-font")?.data.value??e.initialBodyFontId,D=!!h,E=m?.data.value,N=k?.data.value;return l[0]!==w||l[1]!==_||l[2]!==u||l[3]!==c||l[4]!==x||l[5]!==p||l[6]!==S||l[7]!==g||l[8]!==y||l[9]!==f||l[10]!==e.children||l[11]!==e.local||l[12]!==d||l[13]!==E||l[14]!==N?(n=(0,t.jsx)(I,{local:e.local,bgLeaflet:u,bgPage:c,primary:f,highlight2:g,highlight3:y,highlight1:E,accent1:w,accent2:_,showPageBackgroun
1d:d,pageWidth:N,hasBackgroundImage:p,headingFontId:S,bodyFontId:x,children:e.children}),l[0]=w,l[1]=_,l[2]=u,l[3]=c,l[4]=x,l[5]=p,l[6]=S,l[7]=g,l[8]=y,l[9]=f,l[10]=e.children,l[11]=e.local,l[12]=d,l[13]=E,l[14]=N,l[15]=n):n=l[15],l[16]!==p||l[17]!==n?(a=(0,t.jsx)(v.Provider,{value:p,children:n}),l[16]=p,l[17]=n,l[18]=a):a=l[18],l[19]!==D||l[20]!==a?(o=(0,t.jsx)(b.Provider,{value:D,children:a}),l[19]=D,l[20]=a,l[21]=o):o=l[21],o}let I=e=>{let s,o,l,c,d,g,b,w,v,k,S,I,x=(0,r.c)(45),{local:D,bgLeaflet:E,bgPage:N,primary:C,accent1:T,accent2:P,highlight1:R,highlight2:O,highlight3:A,showPageBackground:j,pageWidth:M,hasBackgroundImage:z,headingFontId:F,bodyFontId:U,className:L,children:H}=e,B=j||z?N:E,V=(0,i.colorToString)(j?B:E,"rgb"),q=(0,i.colorToString)(C,"rgb"),G=[T,P].sort((e,t)=>(0,u.compareColors)((0,i.colorToString)(t,"rgb"),V).distance-(0,u.compareColors)((0,i.colorToString)(e,"rgb"),V).distance),K=(0,u.compareColors)((0,i.colorToString)(G[0],"rgb"),q),J=(0,u.compareColors)((0,i.colorToString)(G[1],"rgb"),V);s=K.distance<.15&&K.chromaDiff<.05&&J.distance>.31?G[1]:G[0];let W=(0,u.compareColors)((0,i.colorToString)(s,"rgb"),q),Z=W.distance<.45&&W.chromaDiff<.05,Q=!U||U===h,Y=!F||F===h,X=p(F),ee=p(U),et=Y?Q?void 0:"var(--font-quattro)":y(X),er=Q?Y?void 0:"var(--font-quattro)":y(ee),en=Q?void 0:m(ee),ei=f(X),ea=f(ee);x[0]!==ee||x[1]!==ea||x[2]!==X||x[3]!==ei?(o=[ei,ea,X.fontFamily,ee.fontFamily],x[0]=ee,x[1]=ea,x[2]=X,x[3]=ei,x[4]=o):o=x[4],(0,n.useEffect)(()=>{let e=$;e(ei,X.fontFamily),e(ea,ee.fontFamily)},o),(0,n.useEffect)(()=>{if(D)return;let e=document.querySelector(":root");if(e){if(_(e,"--bg-leaflet",E),_(e,"--bg-page",B),document.body.style.backgroundColor=`rgb(${(0,i.colorToString)(E,"rgb")})`,document.querySelector('meta[name="theme-color"]')?.setAttribute("content",`rgb(${(0,i.colorToString)(E,"rgb")})`),e?.style.setProperty("--bg-page-alpha",B.getChannelValue("alpha").toString()),_(e,"--primary",C),_(e,"--highlight-2",O),_(e,"--highlight-3",A),R){let t=(0,a.parseColor)(`hsba(${R})`);e?.style.setProperty("--highlight-1",`rgb(${(0,i.colorToString)(t,"rgb")})`)}else e?.style.setProperty("--highlight-1","color-mix(in oklab, rgb(var(--accent-contrast)), rgb(var(--bg-page)) 75%)");for(let[t,r]of(_(e,"--accent-1",T),_(e,"--accent-2",P),e?.style.setProperty("--accent-contrast",(0,i.colorToString)(s,"rgb")),e?.style.setProperty("--accent-1-is-contrast",s===T?"1":"0"),e?.style.setProperty("--accent-contrast-similar-to-text",Z?"1":"0"),e?.style.setProperty("--link-underline",Z?"underline":"none"),e?.style.setProperty("--page-width-setting",(M||624).toString()),[["--theme-heading-font",et],["--theme-font",er]]))r?e?.style.setProperty(t,r):e?.style.removeProperty(t)}},[D,et,er,E,B,C,R,O,A,T,P,s,Z,M]);let es=`leafletWrapper w-full text-primary h-full min-h-fit flex flex-col bg-center items-stretch ${L||""}`;x[5]!==E?(l=(0,i.colorToString)(E,"rgb"),x[5]=E,x[6]=l):l=x[6],x[7]!==B?(c=(0,i.colorToString)(B,"rgb"),x[7]=B,x[8]=c):c=x[8],x[9]!==B?(d=B.getChannelValue("alpha"),x[9]=B,x[10]=d):d=x[10],x[11]!==C?(g=(0,i.colorToString)(C,"rgb"),x[11]=C,x[12]=g):g=x[12],x[13]!==T?(b=(0,i.colorToString)(T,"rgb"),x[13]=T,x[14]=b):b=x[14],x[15]!==P?(w=(0,i.colorToString)(P,"rgb"),x[15]=P,x[16]=w):w=x[16];let eo=(0,i.colorToString)(s,"rgb"),el=+(s===T),eu=+!!Z,ec=Z?"underline":"none",eh=R?`rgb(${(0,i.colorToString)((0,a.parseColor)(`hsba(${R})`),"rgb")})`:"color-mix(in oklab, rgb(var(--accent-contrast)), rgb(var(--bg-page)) 75%)";x[17]!==O?(v=(0,i.colorToString)(O,"rgb"),x[17]=O,x[18]=v):v=x[18],x[19]!==A?(k=(0,i.colorToString)(A,"rgb"),x[19]=A,x[20]=k):k=x[20];let ed=M||624,ep=M||624,ef=`min(${M||624}px, calc(var(--leaflet-layout-width, 100vw) - 12px))`,em=en?`${en}px`:void 0;x[21]!==er||x[22]!==et||x[23]!==el||x[24]!==eu||x[25]!==ec||x[26]!==eh||x[27]!==v||x[28]!==k||x[29]!==ed||x[30]!==ep||x[31]!==ef||x[32]!==em||x[33]!==l||x[34]!==c||x[35]!==d||x[36]!==g||x[37]!==b||x[38]!==w||x[39]!==eo?(S={"--bg-leaflet":l,"--bg-page":c,"--bg-page-alpha":d,"--primary":g,"--accent-1":b,"--accent-2":w,"--accent-contrast":eo,"--accent-1-is-contrast":el,"--accent-contrast-similar-to-text":eu,"--link-underline":ec,"--highlight-1":eh,"--highlight-2":v,"--highlight-3":k,"--page-width-setting":ed,"--page-width-unitless":ep,"--page-width-units":ef,"--theme-heading-font":et,"--theme-font":er,"--theme-font-base-size":em},x[21]=er,x[22]=et,x[23]=el,x[24]=eu,x[25]=ec,x[26]=eh,x[27]=v,x[28]=k,x[29]=ed,x[30]=ep,x[31]=ef,x[32]=em,x[33]=l,x[34]=c,x[35]=d,x[36]=g,x[37]=b,x[38]=w,x[39]=eo,x[40]=S):S=x[40];let eg=S;
1return x[41]!==H||x[42]!==es||x[43]!==eg?(I=(0,t.jsxs)("div",{className:es,style:eg,children:[" ",H," "]}),x[41]=H,x[42]=es,x[43]=eg,x[44]=I):I=x[44],I},x=(0,n.createContext)(null);function D(e){let i,a=(0,r.c)(3),s=(0,n.useContext)(x);return s?(a[0]!==s||a[1]!==e.children?(i=(0,t.jsx)(E,{entityID:s,children:e.children}),a[0]=s,a[1]=e.children,a[2]=i):i=a[2],i):e.children}function E(e){let n,a,s,o,l,c,h,d,p,f,m,g,y=(0,r.c)(35),b=(0,i.useColorAttributeNullable)(e.entityID,"theme/card-background"),w=(0,i.useColorAttributeNullable)(e.entityID,"theme/primary"),v=(0,i.useColorAttributeNullable)(e.entityID,"theme/accent-background"),_=(0,i.useColorAttributeNullable)(e.entityID,"theme/accent-text");if(y[0]!==v||y[1]!==_||y[2]!==b||y[3]!==e.entityID){let t=b&&v&&_?[v,_].sort((e,t)=>{let r=(0,i.colorToString)(b,"rgb");return(0,u.compareColors)((0,i.colorToString)(t,"rgb"),r).distance-(0,u.compareColors)((0,i.colorToString)(e,"rgb"),r).distance})[0]:null;n=x.Provider,c=e.entityID,l="contents text-primary",y[10]!==v?(a=v?(0,i.colorToString)(v,"rgb"):void 0,y[10]=v,y[11]=a):a=y[11],y[12]!==_?(s=_?(0,i.colorToString)(_,"rgb"):void 0,y[12]=_,y[13]=s):s=y[13],o=t?(0,i.colorToString)(t,"rgb"):void 0,y[0]=v,y[1]=_,y[2]=b,y[3]=e.entityID,y[4]=n,y[5]=a,y[6]=s,y[7]=o,y[8]=l,y[9]=c}else n=y[4],a=y[5],s=y[6],o=y[7],l=y[8],c=y[9];y[14]!==b?(h=b?(0,i.colorToString)(b,"rgb"):void 0,y[14]=b,y[15]=h):h=y[15],y[16]!==b?(d=b?b.getChannelValue("alpha"):void 0,y[16]=b,y[17]=d):d=y[17],y[18]!==w?(p=w?(0,i.colorToString)(w,"rgb"):void 0,y[18]=w,y[19]=p):p=y[19],y[20]!==a||y[21]!==s||y[22]!==o||y[23]!==h||y[24]!==d||y[25]!==p?(f={"--accent-1":a,"--accent-2":s,"--accent-contrast":o,"--bg-page":h,"--bg-page-alpha":d,"--primary":p},y[20]=a,y[21]=s,y[22]=o,y[23]=h,y[24]=d,y[25]=p,y[26]=f):f=y[26];let k=f;return y[27]!==e.children||y[28]!==l||y[29]!==k?(m=(0,t.jsx)("div",{className:l,style:k,children:e.children}),y[27]=e.children,y[28]=l,y[29]=k,y[30]=m):m=y[30],y[31]!==n||y[32]!==m||y[33]!==c?(g=(0,t.jsx)(n,{value:c,children:m}),y[31]=n,y[32]=m,y[33]=c,y[34]=g):g=y[34],g}let N=e=>{let n,i,a=(0,r.c)(11),{data:u,normalizedPublication:c}=(0,o.useLeafletPublicationData)(),h=(0,s.useEntity)(e.entityID,"theme/background-image"),d=(0,s.useEntity)(e.entityID,"theme/background-image-repeat");if(u?.publications){let r,n=u?.publications.identity_did||"";return a[0]!==c||a[1]!==e.children||a[2]!==n?(r=(0,t.jsx)(l.PublicationBackgroundProvider,{pub_creator:n,record:c,children:e.children}),a[0]=c,a[1]=e.children,a[2]=n,a[3]=r):r=a[3],r}let p=h?`url(${h?.data.src}), url(${h?.data.fallback})`:void 0,f=d?"repeat":"no-repeat",m=d?d?.data.value:"cover";a[4]!==p||a[5]!==f||a[6]!==m?(n={backgroundImage:p,backgroundPosition:"center",backgroundRepeat:f,backgroundSize:m},a[4]=p,a[5]=f,a[6]=m,a[7]=n):n=a[7];let g=n;return a[8]!==e.children||a[9]!==g?(i=(0,t.jsx)("div",{className:"LeafletBackgroundWrapper w-full bg-bg-leaflet text-primary h-full flex flex-col bg-cover bg-center bg-no-repeat items-stretch",style:g,children:e.children}),a[8]=e.children,a[9]=g,a[10]=i):i=a[10],i};function $(e,t){if(!e||document.querySelector(`link[href="${e}"]`)||document.querySelector(`style[data-google-fonts="${e}"]`))return;if(!document.querySelector('link[href="https://fonts.googleapis.com"]')){let e=document.createElement("link");e.rel="preconnect",e.href="https://fonts.googleapis.com",document.head.appendChild(e);let t=document.createElement("link");t.rel="preconnect",t.href="https://fonts.gstatic.com",t.crossOrigin="anonymous",document.head.appendChild(t)}let r=document.createElement("link");r.rel="stylesheet",r.href=e,document.head.appendChild(r),document.fonts?.load&&document.fonts.load(`1em "${t}"`)}},629683,368919,432433,551701,237598,768928,269548,e=>{"use strict";let t;var r,n=e.i(500932),i={};function a(e,t=-1/0,r=1/0){return Math.min(Math.max(e,t),r)}function s(e,t){let r=e,n=t.toString(),i=n.indexOf("."),a=i>=0?n.length-i:0;if(a>0){let e=Math.pow(10,a);r=Math.round(r*e)/e}return r}function o(e,t,r=10){let n=Math.pow(r,t);return Math.round(e*n)/n}i={"ar-AE":{alpha:"Ø£ÙÙØ§",black:"Ø£Ø³ÙØ¯",blue:"أزرÙ","blue purple":"Ø£Ø±Ø¬ÙØ§ÙÙ Ù
زرÙ",brightness:"Ø§ÙØ³Ø·Ùع",brown:"بÙÙ","brown yellow":"Ø£ØµÙØ± بÙÙ",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"سÙ
اÙÙ","cyan blue":"أزر٠سÙ
اÙÙ",dark:"داÙÙ",gray:"رÙ
ادÙ",grayish:"Ù
ائ٠ÙÙØ±Ù
ادÙ",green:"أخضر","green cyan":"سÙ
اÙÙ Ù
خضر",hue:"درجة اÙÙÙÙ",light:"ÙØ§ØªØ",lightness:"Ø§ÙØ¥Ø¶Ø§Ø¡Ø©",magenta:"Ø£Ø±Ø¬ÙØ§ÙÙ","magenta pink":"Ø£Ø±Ø¬ÙØ§ÙÙ ÙØ±Ø¯Ù",orange:"Ø¨Ø±ØªÙØ§ÙÙ","orange yellow":"Ø£ØµÙØ± Ø¨Ø±ØªÙØ§ÙÙ",pale:"Ø¨Ø§ÙØª",pink:"ÙØ±Ø¯Ù","pink red":"Ø£ØÙ
ر ÙØ±Ø¯Ù",purple:"Ø£Ø±Ø¬ÙØ§ÙÙ","purple magenta":"بÙÙØ³Ø¬Ù",red:"Ø£ØÙ
ر","red orange":"Ø¨Ø±ØªÙØ§ÙÙ Ù
ØÙ
ر",saturation:"Ø§ÙØªØ´Ø¨Ø¹",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} \u{634}\u{641}\u{627}\u{641}`,"very dark":"داÙÙ Ø¬Ø¯ÙØ§","very light":"ÙØ§ØªØ Ø¬Ø¯ÙØ§",vibrant:"ساطع",white:"Ø£Ø¨ÙØ¶",yellow:"Ø£ØµÙØ±","yellow green":"أخضر Ù
ØµÙØ±"},"bg-BG":{alpha:"ÐлÑа",black:"ÑеÑно",blue:"СинÑо","blue purple":"ÑинÑо лилаво",brightness:"ЯÑкоÑÑ",brown:"каÑÑво","brown yellow":"каÑÑво жÑлÑо",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"Ñиан","cyan blue":"Ñиан ÑинÑо",dark:"ÑÑмно",gray:"Ñиво",grayish:"Ñивкав",green:"Ðелено","green cyan":"зелен Ñиан",hue:"ÐÑÑенÑк",light:"ÑвеÑло",lightness:"ÐекоÑа",magenta:"магенÑа","magenta pink":"магенÑа Ñозово",orange:"оÑанжево","orange yellow":"оÑанжево жÑлÑо",pale:"бледо",pink:"Ñозово","pink red":"Ñозово ÑеÑвено",purple:"лилаво","purple magenta":"лилаво магенÑа",red:"ЧеÑвено","red orange":"ÑеÑвен поÑÑокал",saturation:"ÐаÑиÑеноÑÑ",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} \u{43F}\u{440}\u{43E}\u{437}\u{440}\u{430}\u{447}\u{435}\u{43D}`,"very dark":"много ÑÑмно","very light":"много ÑвеÑло",vibrant:" ÑÑко",white:"бÑло",yellow:"жÑлÑо","yellow green":"жÑлÑо зелен"},"cs-CZ":{alpha:"Alfa",black:"Äerná",blue:"Modrá","blue purple":"modrofialová",brightness:"Jas",brown:"hnÄdá","brown yellow":"hnÄdožlutá",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"tyrkysová","cyan blue":"tyrkysovomodrá",dark:"tmavá",gray:"Å¡edá",grayish:"naÅ¡edlá",green:"Zelená","green cyan":"zelenotyrkysová",hue:"OdstÃn",light:"svÄtlá",lightness:"SvÄtlost",magenta:"purpurová","magenta pink":"purpurovÄ růžová",orange:"oranžová","orange yellow":"oranžovožlutá",pale:"bledá",pink:"růžová","pink red":"růžovoÄervená",purple:"fialová","purple magenta":"fialovÄ purpurová",red:"Äervená","red orange":"Äervenooranžová",saturation:"Sytost",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTrans
1parent} pr\u{16F}hledn\xe9`,"very dark":"velmi tmavá","very light":"velmi svÄtlá",vibrant:"záÅivá",white:"bÃlá",yellow:"žlutá","yellow green":"žlutozelená"},"da-DK":{alpha:"Alfa",black:"sort",blue:"BlÃ¥","blue purple":"blÃ¥lilla",brightness:"Lysstyrke",brown:"brun","brown yellow":"brungul",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"cyan","cyan blue":"cyan blÃ¥",dark:"mørk",gray:"grÃ¥",grayish:"grÃ¥lig",green:"Grøn","green cyan":"grøn cyan",hue:"Tone",light:"lys",lightness:"Lyshed",magenta:"magenta","magenta pink":"magenta pink",orange:"orange","orange yellow":"orangegul",pale:"bleg",pink:"lyserød","pink red":"lyserødlig rød",purple:"lilla","purple magenta":"lilla magenta",red:"Rød","red orange":"rødorange",saturation:"Farvemætning",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTransparent} gennemsigtig`,"very dark":"meget mørk","very light":"meget lys",vibrant:"klar",white:"hvid",yellow:"gul","yellow green":"gulgrøn"},"de-DE":{alpha:"Alpha",black:"Schwarz",blue:"Blau","blue purple":"Blaulila",brightness:"Helligkeit",brown:"Braun","brown yellow":"Braungelb",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"Cyan","cyan blue":"Cyanblau",dark:"dunkles",gray:"Grau",grayish:"gräuliches",green:"Grün","green cyan":"Grüncyan",hue:"Farbton",light:"helles",lightness:"Leuchtkraft",magenta:"Magenta","magenta pink":"Magentarosa",orange:"Orange","orange yellow":"Orangegelb",pale:"blasses",pink:"Rosa","pink red":"Rosarot",purple:"Lila","purple magenta":"Lilamagenta",red:"Rot","red orange":"Rotorange",saturation:"Sättigung",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, zu ${e.percentTransparent} transparent`,"very dark":"sehr dunkles","very light":"sehr helles",vibrant:"lebhaftes",white:"WeiÃ",yellow:"Gelb","yellow green":"Gelbgrün"},"el-GR":{alpha:"ÎλÏα",black:"μαÏÏο",blue:"ÎÏλε","blue purple":"μÏλε μÏβ",brightness:"ΦÏÏεινÏÏηÏα",brown:"καÏÎ","brown yellow":"καÏΠκίÏÏινο",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"κÏ
ανÏ","cyan blue":"κÏ
Î±Î½Ï Î¼Ïλε",dark:"ÏκοÏÏο",gray:"γκÏι",grayish:"γκÏιζÏÏÏ",green:"Î ÏάÏινο","green cyan":"ÏÏάÏινο κÏ
ανÏ",hue:"ΤÏνοÏ",light:"ανοιÏÏÏ",lightness:"ΦÏÏεινÏÏηÏα",magenta:"μαÏζÎνÏα","magenta pink":"μαÏζÎνÏα Ïοζ",orange:"ÏοÏÏοκαλί","orange yellow":"ÏοÏÏοκαλί κίÏÏινο",pale:"ανοιÏÏÏ",pink:"Ïοζ","pink red":"Ïοζ κÏκκινο",purple:"μÏβ","purple magenta":"μÏβ μαÏζÎνÏα",red:"ÎÏκκινο","red orange":"κÏκκινο ÏοÏÏοκαλί",saturation:"ÎοÏεÏμÏÏ",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} \u{3B4}\u{3B9}\u{3B1}\u{3C6}\u{3B1}\u{3BD}\u{3AD}\u{3C2}`,"very dark":"ÏÎ¿Î»Ï ÏκοÏÏο","very light":"ÏÎ¿Î»Ï Î±Î½Î¿Î¹ÏÏÏ",vibrant:"ÎνÏονο",white:"λεÏ
κÏ",yellow:"κίÏÏινο","yellow green":"κίÏÏινο ÏÏάÏινο"},"en-US":{hue:"Hue",saturation:"Saturation",lightness:"Lightness",brightness:"Brightness",red:"Red",green:"Green",blue:"Blue",alpha:"Alpha",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTransparent} transparent`,"very dark":"very dark",dark:"dark",light:"light","very light":"very light",pale:"pale",grayish:"grayish",vibrant:"vibrant",black:"black",white:"white",gray:"gray",pink:"pink","pink red":"pink red","red orange":"red orange",brown:"brown",orange:"orange","orange yellow":"orange yellow","brown yellow":"brown yellow",yellow:"yellow","yellow green":"yellow green","green cyan":"green cyan",cyan:"cyan","cyan blue":"cyan blue","blue purple":"blue purple",purple:"purple","purple magenta":"purple magenta",magenta:"magenta","magenta pink":"magenta pink"},"es-ES":{alpha:"Alpha",black:"negro",blue:"Azul","blue purple":"púrpura azulado",brightness:"Brillo",brown:"marrón","brown yellow":"amarillo amarronado",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"cian","cyan blue":"azul cian",dark:"oscuro",gray:"gris",grayish:"grisáceo",green:"Verde","green cyan":"cian verdoso",hue:"Tono",light:"claro",lightness:"Luminosidad",magenta:"magenta","magenta pink":"rosa magenta",orange:"naranja","orange yellow":"amarillo anaranjado",pale:"pálido",pink:"rosa","pink red":"rojo rosado",purple:"morado","purple magenta":"magenta violáceo",red:"Rojo","red orange":"naranja rojizo",saturation:"Saturación",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} transparente`,"very dark":"muy oscuro","very light":"muy claro",vibrant:"intenso",white:"blanco",yellow:"amarillo","yellow green":"verde amarillento"},"et-EE":{alpha:"Alfa",black:"must",blue:"Sinine","blue purple":"sinakaslilla",brightness:"Heledus",brown:"pruun","brown yellow":"pruunikaskollane",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"tsüaan","cyan blue":"tsüaansinine",dark:"tume",gray:"hall",grayish:"hallikas",green:"Roheline","green cyan":"tsüaanroheline",hue:"Värv",light:"valgus",lightness:"Valgus",magenta:"magentapunane","magenta pink":"magentaroosa",orange:"oranž","orange yellow":"oranžikaskollane",pale:"kahvatu",pink:"roosa","pink red":"vaarikapunane",purple:"lilla","purple magenta":"purpurne magenta",red:"Punane","red orange":"punakasoranž",saturation:"Küllastus",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTransparent} l\xe4bipaistev`,"very dark":"väga tume","very light":"väga hele",vibrant:"ere",white:"valge",yellow:"kollane","yellow green":"kollakasroheline"},"fi-FI":{alpha:"Alpha",black:"musta",blue:"Sininen","blue purple":"sinivioletti",brightness:"Kirkkaus",brown:"ruskea","brown yellow":"ruskeankeltainen",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"syaani","cyan blue":"syaaninsininen",dark:"tumma",gray:"harmaa",grayish:"harmahtava",green:"Vihreä","green cyan":"vihreänsyaani",hue:"Sävy",light:"vaalea",lightness:"Valomäärä",magenta:"magenta","magenta pink":"magentapinkki",orange:"oranssi","orange yellow":"oranssinkeltainen",pale:"vaalea",pink:"pinkki","pink red":"vaaleanpunainen",purple:"violetti","purple magenta":"violettimagenta",red:"Punainen","red orange":"punaoranssi",saturation:"Värikylläisyys",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} l\xe4pin\xe4kyv\xe4`,"very dark":"hyvin tumma","very light":"erittäin vaalea",vibrant:"eloisa",white:"valkea",yellow:"keltainen","yellow green":"keltavihreä"},"fr-FR":{alpha:"Alpha",black:"Noir",blue:"Bleu","blue purple":"Violet bleu",brightness:"Luminosité",brown:"Brun","brown yellow":"Jaune brun",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"Cyan","cyan blue":"Bleu cyan",dark:"Sombre",gray:"Gris",grayish:"Grisâtre",green:"Vert","green cyan":"Cyan vert",hue:"Teinte",light:"Clair",lightness:"Luminosité",magenta:"Magenta","magenta pink":"Rose magenta",orange:"Orange","orange yellow":"Jaune orangé",pale:"Pâle",pink:"Rose","pink red":"Rouge rosé",purple:"Violet","purple magenta":"Magenta violet",red:"Rouge","red orange":"Orange rouge",saturation:"Saturation",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTransparent} transparent`,"very dark":"Très sombre","very light":"Très clair",vibrant:"Vif",white:"Blanc",yellow:"Jaune","yellow green":"Vert jaune"},"he-IL":{alpha:"××פ×",black:"ש××ר",blue:"××××","blue purple":"×××× ×¡×××",brightness:"×××ר×ת",brown:"×××","brown yellow":"××× ×¦×××",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"××רק××","cyan blue":"×××× ×¦×××",dark:"×××",gray:"×פ×ר",grayish:"×פרפר",green:"×ר××§","green cyan":"צ××× ×ר××§",hue:"××××",light:"××ר",lightness:"×××ת ××ר",magenta:"××'× ××","magenta pink":"×ר×× ××'× ××",orange:"×ת××","orange yellow":"×ת×× ×¦×××",pale:"××××ר",pink:"×ר××","pink red":"×ר×× ××××",purple:"ס×××","purple magenta":"××'× ×× ×¡×××",red:"××××","red orange":"×ת×× ××××",saturation:"ר××××",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} \u{5E9}\u{5E7}\u{5D5}\u{5E3}`,"very dark":"××× ××××","very light":"×××ר ××××",vibrant:"ת×סס",white:"×××",yellow:"צ×××","yellow green":"צ××× ×ר××§"},"hr-HR":{alpha:"Alfa",black:"crno",blue:"Plava","blue purple":"plavo ljubiÄasta",brightness:"Svjetlina",brown:"smeÄa","brown yellow":"smeÄe žuta",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"cijan","cyan blue":"cijan plava",dark:"tamno",gray:"siva",grayish:"sivkasto",green:"Zelena","green cyan":"zelena cijan",hue:"Nijansa",light:"svjetlo",lightness:"Osvijetljenost",magenta:"magenta","magenta pink":"magentno ružiÄasta",orange:"naranÄasta","orange yellow":"naranÄasto žuta",pale:"blijeda",pink:"ružiÄasta","pink red":"ružiÄasto crvena",purple:"ljubiÄasta","purple magenta":"ljubiÄasta magenta",red:"Crvena","red orange":"crveno naranÄasta",saturation:"ZasiÄenost",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTransparent} prozirnosti`,"very dark":"jako tamna","very light":"vrlo svijetlo",vibrant:"vibrantna",white:"bijela",yellow:"žuto","yellow green":"žuto zelena"},"hu-HU":{alpha:"Alfa",black:"fekete",blue:"Kék","blue purple":"kék lila",brightness:"Fényesség",brown:"barna","brown yellow":"barna sárga",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"ciánkék","cyan blue":"ciánkék",dark:"sötét",gray:"szürke",grayish:"szürkés",green:"Zöld","green cyan":"zöld ciánkék",hue:"SzÃnárnyalat",light:"világos",lightness:"Világosság",magenta:"bÃbor","magenta pink":"bÃbor rózsaszÃn",orange:"narancs","orange yellow":"narancssárga",pale:"halvány",pink:"rózsaszÃn","pink red":"rózsaszÃn piros",purple:"lila","purple magenta":"lila bÃbor",red:"Piros","red orange":"piros narancs",saturation:"TelÃtettség",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} \xe1tl\xe1tsz\xf3`,"very dark":"nagyon sötét","very light":"nagyon világos",vibrant:"élénk",white:"fehér",yellow:"sárga","yellow green":"sárga zöld"},"it-IT":{alpha:"Alfa",black:"nero",blue:"Blu","blue purple":"blu viola",brightness:"Luminosità ",brown:"marrone","brown yellow":"giallo bruno",colorName:e=>`${e.hue} ${e.chroma} ${e.lightness}`,cyan:"ciano","cyan blue":"blu ciano",dark:"scuro",gray:"grigio",grayish:"grigiastro",green:"Verde","green cyan":"verde ciano",hue:"Tonalità ",light:"chiaro",lightness:"Luminosità ",magenta:"magenta","magenta pink":"rosa magenta",orange:"arancio","orange yellow":"giallo arancio",pale:"tenue",pink:"rosa","pink red":"rosa rosso",purple:"viola","purple magenta":"viola magenta",red:"Rosso","red orange":"rosso arancio",saturation:"Saturazione",transparentColorName:e=>`${e.hue} ${e.chroma} ${e.lightness}, trasparenza ${e.percentTransparent}`,"very dark":"molto scuro","very light":"molto chiaro",vibrant:"vivace",white:"bianco",yellow:"giallo","yellow green":"giallo verde"},"ja-JP":{alpha:"ã¢ã«ãã¡",black:"ãã©ãã¯",blue:"é","blue purple":"ãã«ã¼ãã¼ãã«",brightness:"æãã",brown:"ãã©ã¦ã³","brown yellow":"ãã©ã¦ã³ã¤ã¨ãã¼",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"ã·ã¢ã³","cyan blue":"ã·ã¢ã³ãã«ã¼",dark:"ãã¼ã¯",gray:"ã°ã¬ã¼",grayish:"ã°ã¬ã¤ãã·ã¥",green:"ç·","green cyan":"ã°ãªã¼ã³ã·ã¢ã³",hue:"è²ç¸",light:"ã©ã¤ã",lightness:"æåº¦",magenta:"ãã¼ã³ã¿","magenta pink":"ãã¼ã³ã¿ãã³ã¯",orange:"ãªã¬ã³ã¸","orange yellow":"ãªã¬ã³ã¸ã¤ã¨ãã¼",pale:"ãã¼ã«",pink:"ãã³ã¯","pink red":"ãã³ã¯ã¬ãã",purple:"ãã¼ãã«","purple magenta":"ãã¼ãã«ãã¼ã³ã¿",red:"赤","red orange":"ã¬ãããªã¬ã³ã¸",saturation:"彩度",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} \u{900F}\u{660E}`,"very dark":"æãæã","very light":"ããªã¼ã©ã¤ã",vibrant:"é®®ãã",white:"ãã¯ã¤ã",yellow:"ã¤ã¨ãã¼","yellow green":"ã¤ã¨ãã¼ã°ãªã¼ã³"},"ko-KR":{alpha:"ìí",black:"ê²ìì",blue:"íë","blue purple":"ì²ìì",brightness:"ëª
ë",brown:"ê°ì","brown yellow":"í©ê°ì",colorName:e=>`${e.lightness}, ${e.chroma}, ${e.hue}`,cyan:"ì²ë¡ì","cyan blue":"ì²ë¡ì",dark:"ë¤í¬",gray:"íì",grayish:"íê°ì",green:"ì´ë¡","green cyan":"ì²ë¡ì",hue:"ìì¡°",light:"ë¼ì´í¸",lightness:"ë°ê¸°",magenta:"ìíì","magenta pink":"ë§ì í íí¬",orange:"주í©ì","orange yellow":"ë¶ê·¸ì¤ë¦í ë
¸ë",pale:"íì",pink:"ë¶íì","pink red":"íí¬ ë ë",purple:"ì주ì","purple magenta":"ë³´ë¼ë¹ ìíì",red:"빨ê°","red orange":"ë¶ì 주í©ì",saturation:"ì±ë",transparentColorName:e=>`${e.lightness}, ${e.chroma}, ${e.hue}, ${e.percentTransparent} \u{D22C}\u{BA85}\u{B3C4}`,"very dark":"ë§¤ì° ì´ëì´","very light":"ë§¤ì° ì°í¨",vibrant:"ê°ë ¬í",white:"í°ì",yellow:"ë
¸ëì","yellow green":"ì°ëì"},"lt-LT":{alpha:"Alfa",black:"juoda",blue:"MÄlyna","blue purple":"melsvai violetinÄ",brightness:"RyÅ¡kumas",brown:"ruda","brown yellow":"rusvai geltona",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"žalsvai mÄlyna","cyan blue":"žalsvai mÄlyna",dark:"tamsi",gray:"pilka",grayish:"pilkÅ¡va",green:"Žalia","green cyan":"žalsvai mÄlyna",hue:"Atspalvis",light:"Å¡viesi",lightness:"Å viesumas",magenta:"rausvai raudona","magenta pink":"purpurinÄ",orange:"oranžinÄ","orange yellow":"oranžinio atspalvio geltona",pale:"blyÅ¡ki",pink:"rožinÄ","pink red":"rožinÄ raudona",purple:"violetinÄ","purple magenta":"purpurinÄ rausvai raudona",red:"Raudona","red orange":"rausvai oranžinÄ",saturation:"Ä®sotinimas",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} skaidri`,"very dark":"labai tamsi","very light":"labai Å¡viesi",vibrant:"ryÅ¡ki",white:"balta",yellow:"geltona","yellow green":"gelsvai žalia"},"lv-LV":{alpha:"Alfa",black:"melns",blue:"Zila","blue purple":"zili violets",brightness:"Spilgtums",brown:"brÅ«ns","brown yellow":"brÅ«ni dzeltens",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"ciÄns","cyan blue":"ciÄna zils",dark:"tumÅ¡s",gray:"pelÄks",grayish:"pelÄcÄ«gs",green:"Zaļa","green cyan":"zaļš ciÄns",hue:"NokrÄsa",light:"gaiÅ¡s",lightness:"GaiÅ¡ums",magenta:"fuksiju","magenta pink":"fuksiju rozÄ",orange:"oranžs","orange yellow":"oranži dzeltens",pale:"bÄls",pink:"rozÄ","pink red":"rozÄ«gi sarkans",purple:"violets","purple magenta":"violets fuksiju",red:"Sarkana","red orange":"sarkanÄ«gi oranžs",saturation:"PiesÄtinÄjums",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTransparent} caursp\u{12B}d\u{12B}gs`,"very dark":"ļoti tumÅ¡s","very light":"ļoti gaiÅ¡s",vibrant:"koÅ¡s",white:"balts",yellow:"dzeltens","yellow green":"dzelteni zaļš"},"nb-NO":{alpha:"Alfa",black:"svart",blue:"BlÃ¥","blue purple":"blÃ¥lilla",brightness:"Lysstyrke",brown:"brun","brown yellow":"brungul",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"cyan","cyan blue":"cyanblÃ¥",dark:"mørk",gray:"grÃ¥",grayish:"grÃ¥aktig",green:"Grønn","green cyan":"grønncyan",hue:"Fargetone",light:"lys",lightness:"Lyshet",magenta:"magenta","magenta pink":"magentarosa",orange:"oransje","orange yellow":"oransjegul",pale:"blek",pink:"rosa","pink red":"rosarød",purple:"lilla","purple magenta":"lillamagenta",red:"Rød","red orange":"rødoransje",saturation:"Metning",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} gjennomsiktig`,"very dark":"svært mørk","very light":"svært lys",vibrant:"levende",white:"hvit",yellow:"gul","yellow green":"gulgrønn"},"nl-NL":{alpha:"Alfa",black:"zwart",blue:"Blauw","blue purple":"paarsblauw",brightness:"Helderheid",brown:"bruin","brown yellow":"bruingeel",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"cyaan","cyan blue":"cyaanblauw",dark:"donker",gray:"grijs",grayish:"grijsachtig",green:"Groen","green cyan":"cyaangroen",hue:"Kleurtoon",light:"licht",lightness:"Lichtsterkte",magenta:"magenta","magenta pink":"magentaroze",orange:"oranje","orange yellow":"oranjegeel",pale:"bleek",pink:"roze","pink red":"rozerood",purple:"paars","purple magenta":"magentapaars",red:"Rood","red orange":"roodoranje",saturation:"Verzadiging",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTransparent} transparant`,"very dark":"heel donker","very light":"heel licht",vibrant:"levendig",white:"wit",yellow:"geel","yellow green":"geelgroen"},"pl-PL":{alpha:"Alfa",black:"czarny",blue:"Niebieski","blue purple":"niebiesko-fioletowy",brightness:"JasnoÅÄ",brown:"brÄ
zowy","brown yellow":"brÄ
zowo-żóÅty",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"cyjanowy","cyan blue":"cyjanowo-niebieski",dark:"ciemny",gray:"szary",grayish:"szarawy",green:"Zielony","green cyan":"zielono-cyjanowy",hue:"OdcieÅ",light:"jasny",lightness:"JaskrawoÅÄ",magenta:"purpurowy","magenta pink":"purpurowo-różowy",orange:"pomaraÅczowy","orange yellow":"pomaraÅczowo-żóÅty",pale:"blady",pink:"różowy","pink red":"różowo-czerwony",purple:"fioletowy","purple magenta":"fioletowo-purpurowy",red:"Czerwony","red orange":"czerwono-pomaraÅczowy",saturation:"Nasycenie",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} przezroczysto\u{15B}ci`,"very dark":"bardzo ciemny","very light":"bardzo jasny",vibrant:"intensywny",white:"biaÅy",yellow:"żóÅty","yellow green":"żóÅto-zielony"},"pt-BR":{alpha:"Alfa",black:"preto",blue:"Azul","blue purple":"roxo azulado",brightness:"Brilho",brown:"marrom","brown yellow":"marrom amarelado",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"ciano","cyan blue":"azul-ciano",dark:"escuro",gray:"cinza",grayish:"acinzentado",green:"Verde","green cyan":"verde-ciano",hue:"Matiz",light:"claro",lightness:"Luminosidade",magenta:"magenta","magenta pink":"rosa-magenta",orange:"laranja","orange yellow":"amarelo alaranjado",pale:"pálido",pink:"rosa","pink red":"rosa avermelhado",purple:"roxo","purple magenta":"roxo-magenta",red:"Vermelho","red orange":"laranja avermelhado",saturation:"Saturação",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTransparent} transparente`,"very dark":"muito escuro","very light":"muito claro",vibrant:"vibrante",white:"branco",yellow:"amarelo","yellow green":"verde amarelado"},"pt-PT":{alpha:"Alfa",black:"preto",blue:"Azul","blue purple":"azul-púrpura",brightness:"Luminosidade",brown:"castanho","brown yellow":"amarelo-castanho",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"ciano","cyan blue":"azul-ciano",dark:"escuro",gray:"cinzento",grayish:"acinzentado",green:"Verde","green cyan":"verde-ciano",hue:"Tonalidade",light:"claro",lightness:"Claridade",magenta:"magenta","magenta pink":"rosa-magenta",orange:"laranja","orange yellow":"amarelo-laranja",pale:"pálido",pink:"cor-de-rosa","pink red":"vermelho-rosa",purple:"púrpura","purple magenta":"púrpura-magenta",red:"Vermelho","red orange":"laranja-vermelho",saturation:"Saturação",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} transparente`,"very dark":"muito escuro","very light":"muito claro",vibrant:"vibrante",white:"branco",yellow:"amarelo","yellow green":"verde-amarelo"},"ro-RO":{alpha:"Alfa",black:"negru",blue:"Albastru","blue purple":"albastru-violet",brightness:"Luminozitate",brown:"maro","brown yellow":"galben maro",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"bleu","cyan blue":"albastru-bleu",dark:"închis",gray:"gri",grayish:"cenuÈiu",green:"Verde","green cyan":"verde bleu",hue:"NuanÈÄ",light:"deschis",lightness:"Luminozitate",magenta:"fucsia","magenta pink":"roz-fucsia",orange:"portocaliu","orange yellow":"galben-portocaliu",pale:"pal",pink:"roz","pink red":"roz-roÈu",purple:"violet","purple magenta":"violet-fucsia",red:"RoÈu","red orange":"portocaliu-roÈu",saturation:"SaturaÈie",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTransparent} transparent`,"very dark":"foarte închis","very light":"foarte deschis",vibrant:"plin de viaÈÄ",white:"alb",yellow:"galben","yellow green":"galben-verde"},"ru-RU":{alpha:"ÐлÑÑа",black:"ÑеÑнÑй",blue:"Синий","blue purple":"Ñине-ÑиолеÑовÑй",brightness:"ЯÑкоÑÑÑ",brown:"коÑиÑневÑй","brown yellow":"коÑиÑнево-желÑÑй",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"голÑбой","cyan blue":"ÑÐ²ÐµÑ Ð¼Ð¾ÑÑкой волнÑ",dark:"ÑемнÑй",gray:"ÑеÑÑй",grayish:"ÑеÑоваÑÑй",green:"ÐеленÑй","green cyan":"Ñине-зеленÑй",hue:"ÐÑÑенок",light:"ÑвеÑлÑй",lightness:"ÐÑвеÑенноÑÑÑ",magenta:"пÑÑпÑÑнÑй","magenta pink":"пÑÑпÑÑно-ÑозовÑй",orange:"оÑанжевÑй","orange yellow":"оÑанжево-желÑÑй",pale:"бледнÑй",pink:"ÑозовÑй","pink red":"Ñозово-кÑаÑнÑй",purple:"ÑиолеÑовÑй","purple magenta":"ÑиолеÑово-пÑÑпÑÑнÑй",red:"ÐÑаÑнÑй","red orange":"кÑаÑно-оÑанжевÑй",saturation:"ÐаÑÑÑенноÑÑÑ",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, \u{43F}\u{440}\u{43E}\u{437}\u{440}\u{430}\u{447}\u{43D}\u{44B}\u{439} \u{43D}\u{430}
1 ${e.percentTransparent}`,"very dark":"оÑÐµÐ½Ñ ÑемнÑй","very light":"оÑÐµÐ½Ñ ÑвеÑлÑй",vibrant:"ÑÑкий",white:"белÑй",yellow:"желÑÑй","yellow green":"желÑо-зеленÑй"},"sk-SK":{alpha:"Alfa",black:"Äierna",blue:"Modrá","blue purple":"modrofialová",brightness:"Jas",brown:"hnedá","brown yellow":"hnedožltá",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"azúrová","cyan blue":"azúrová modrá",dark:"tmavá",gray:"sivá",grayish:"sivastá",green:"Zelená","green cyan":"zelená azúrová",hue:"OdtieÅ",light:"svetlá",lightness:"SvetlosÅ¥",magenta:"purpurová","magenta pink":"ružová purpurová",orange:"oranžová","orange yellow":"oranžovožltá",pale:"bledá",pink:"ružová","pink red":"ružovoÄervená",purple:"fialová","purple magenta":"fialová purpurová",red:"Äervená","red orange":"Äervenooranžová",saturation:"SýtosÅ¥",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTransparent} prieh\u{13E}adn\xe1`,"very dark":"veľmi tmavá","very light":"veľmi svetlá",vibrant:"energická",white:"biela",yellow:"žltá","yellow green":"žltozelená"},"sl-SI":{alpha:"Alfa",black:"Ärna",blue:"Modra","blue purple":"modro vijoliÄna",brightness:"Svetlost",brown:"rjava","brown yellow":"rjavo rumena",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"cian","cyan blue":"cian modra",dark:"temna",gray:"siva",grayish:"sivkasta",green:"Zelena","green cyan":"zelena cian",hue:"Barva",light:"svetla",lightness:"Lahkost",magenta:"Å¡krlatna","magenta pink":"Å¡krlatno roza",orange:"oranžna","orange yellow":"oranžno rumena",pale:"bleda",pink:"roza","pink red":"roza rdeÄa",purple:"vijoliÄna","purple magenta":"vijoliÄno Å¡krlatna",red:"RdeÄa","red orange":"rdeÄe oranžna",saturation:"NasiÄenost",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} prozorna`,"very dark":"zelo temna","very light":"zelo svetla",vibrant:"živahna",white:"bela",yellow:"rumena","yellow green":"rumeno zelena"},"sr-SP":{alpha:"Alfa",black:"crno",blue:"Plava","blue purple":"plavoljubiÄasta",brightness:"Osvetljenost",brown:"smeÄa","brown yellow":"smeÄežuta",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"cijan","cyan blue":"cijan plava",dark:"tamno",gray:"siva",grayish:"sivkasta",green:"Zelena","green cyan":"zeleno cijan",hue:"Nijansa",light:"svetla",lightness:"Osvetljenje",magenta:"purpurnocrvena","magenta pink":"magenta ružiÄasta",orange:"narandžasta","orange yellow":"narandžastožuta",pale:"bledo",pink:"ružiÄasta","pink red":"ružiÄastocrvena",purple:"ljubiÄasta","purple magenta":"ljubiÄasta magenta",red:"Crvena","red orange":"crvenonarandžasta",saturation:"ZasiÄenje",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTransparent} prozirna`,"very dark":"veoma tamno","very light":"vrlo svetlo",vibrant:"živopisna",white:"bela",yellow:"žuto","yellow green":"žutozelena"},"sv-SE":{alpha:"Alfa",black:"svart",blue:"BlÃ¥tt","blue purple":"blÃ¥lila",brightness:"Ljusstyrka",brown:"brun","brown yellow":"brungul",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"cyan","cyan blue":"cyanblÃ¥",dark:"mörk",gray:"grÃ¥",grayish:"grÃ¥aktig",green:"Grönt","green cyan":"grön cyan",hue:"Nyans",light:"ljus",lightness:"Ljushet",magenta:"magenta","magenta pink":"magentarosa",orange:"orange","orange yellow":"orangegul",pale:"blek",pink:"rosa","pink red":"rosaröd",purple:"lila","purple magenta":"lila magenta",red:"Rött","red orange":"rödorange",saturation:"Mättnad",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} genomskinlig`,"very dark":"mycket mörk","very light":"mycket ljus",vibrant:"livfull",white:"vit",yellow:"gul","yellow green":"gulgrön"},"tr-TR":{alpha:"Alfa",black:"siyah",blue:"Mavi","blue purple":"mavi mor",brightness:"Parlaklık",brown:"kahverengi","brown yellow":"kahverengi sarı",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"camgöbeÄi","cyan blue":"camgöbeÄi mavi",dark:"koyu",gray:"gri",grayish:"grimsi",green:"YeÅil","green cyan":"yeÅil camgöbeÄi",hue:"Ton",light:"açık",lightness:"Canlılık",magenta:"eflatun","magenta pink":"eflatun pembe",orange:"turuncu","orange yellow":"turuncu sarı",pale:"solgun",pink:"pembe","pink red":"pembe kırmızı",purple:"mor","purple magenta":"mor eflatun",red:"Kırmızı","red orange":"kırmızı portakal",saturation:"Doygunluk",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTransparent} saydam`,"very dark":"çok koyu","very light":"çok açık",vibrant:"canlı",white:"beyaz",yellow:"sarı","yellow green":"sarı yeÅil"},"uk-UA":{alpha:"ÐлÑÑа",black:"ÑоÑний",blue:"СинÑй","blue purple":"ÑинÑо-ÑÑолеÑовий",brightness:"ЯÑкÑавÑÑÑÑ",brown:"коÑиÑневий","brown yellow":"коÑиÑнево-жовÑий",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"блакиÑний","cyan blue":"ÑинÑо-блакиÑний",dark:"Ñемний",gray:"ÑÑÑий",grayish:"ÑÑÑÑваÑий",green:"Ðелений","green cyan":"зелено-блакиÑний",hue:"Тон",light:"ÑвÑÑлий",lightness:"ÐÑвÑÑленÑÑÑÑ",magenta:"пÑÑпÑÑовий","magenta pink":"пÑÑпÑÑово-Ñожевий",orange:"помаÑанÑевий","orange yellow":"помаÑанÑево-жовÑий",pale:"блÑдий",pink:"Ñожевий","pink red":"Ñожево-ÑеÑвоний",purple:"ÑÑолеÑовий","purple magenta":"ÑÑолеÑово-пÑÑпÑÑовий",red:"ЧеÑвоний","red orange":"ÑеÑвоно-помаÑанÑевий",saturation:"ÐаÑиÑенÑÑÑÑ",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, \u{43F}\u{440}\u{43E}\u{437}\u{43E}\u{440}\u{438}\u{439} \u{43D}\u{430}
1 ${e.percentTransparent}`,"very dark":"дÑже Ñемний","very light":"дÑже ÑвÑÑлий",vibrant:"ÑÑкÑавий",white:"бÑлий",yellow:"жовÑий","yellow green":"жовÑо-зелений"},"zh-CN":{alpha:"Alpha",black:"é»è²",blue:"èè²","blue purple":"èç´«è²",brightness:"亮度",brown:"æ£è²ç","brown yellow":"æ£é»è²",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"è绿è²","cyan blue":"éèè²",dark:"æ·±è²",gray:"ç°è²",grayish:"æµ
ç°è²ç",green:"绿è²","green cyan":"绿éè²",hue:"è²ç¸",light:"æµ
è²",lightness:"æäº®åº¦",magenta:"紫红è²","magenta pink":"ç´«ç²è²",orange:"æ©è²","orange yellow":"æ©é»è²",pale:"èç½ç",pink:"ç²è²","pink red":"ç²çº¢è²",purple:"ç´«è²","purple magenta":"ç´«æ´çº¢è²",red:"红è²","red orange":"红æ©è²",saturation:"饱å度",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}, ${e.percentTransparent} \u{900F}\u{660E}`,"very dark":"徿","very light":"徿µ
",vibrant:"çæºåå",white:"ç½è²",yellow:"é»è²","yellow green":"é»è²/绿è²"},"zh-TW":{alpha:"Alpha",black:"é»",blue:"èè²","blue purple":"èç´«",brightness:"亮度",brown:"æ£","brown yellow":"æ£é»",colorName:e=>`${e.lightness} ${e.chroma} ${e.hue}`,cyan:"é","cyan blue":"éè",dark:"æ",gray:"ç°",grayish:"åç°",green:"ç¶ è²","green cyan":"éç¶ ",hue:"è²ç¸",light:"æ·º",lightness:"æäº®",magenta:"æ´ç´
","magenta pink":"æ·ºæ´ç´
",orange:"æ©","orange yellow":"æ©é»",pale:"æ·¡",pink:"ç²ç´
","pink red":"ç²ç´
",purple:"ç´«","purple magenta":"ç´«æ´ç´
",red:"ç´
è²","red orange":"æ©ç´
",saturation:"飽å度",transparentColorName:e=>`${e.lightness} ${e.chroma} ${e.hue}
1, ${e.percentTransparent} \u{900F}\u{660E}`,"very dark":"徿","very light":"徿·º",vibrant:"é®®è±",white:"ç½",yellow:"é»","yellow green":"é»ç¶ "}},e.s(["clamp",0,a,"snapValueToStep",0,function(e,t,r,n){t=Number(t),r=Number(r);let i=(e-(isNaN(t)?0:t))%n,a=s(2*Math.abs(i)>=n?e+Math.sign(i)*(n-Math.abs(i)):e-i,n);return isNaN(t)?!isNaN(r)&&a>r&&(a=Math.floor(s(r/n,n))*n):a<t?a=t:!isNaN(r)&&a>r&&(a=t+Math.floor(s((r-t)/n,n))*n),a=s(a,n)},"toFixedNumber",0,o],368919);let l=Symbol.for("react-aria.i18n.locale"),u=Symbol.for("react-aria.i18n.strings");class c{getStringForLocale(e,t){let r=this.getStringsForLocale(t)[e];if(!r)throw Error(`Could not find intl message ${e} in ${t} locale`);return r}getStringsForLocale(e){let t=this.strings[e];return t||(t=function(e,t,r="en-US"){var n;if(t[e])return t[e];let i=(n=e,Intl.Locale?new Intl.Locale(n).language:n.split("-")[0]);if(t[i])return t[i];for(let e in t)if(e.startsWith(i+"-"))return t[e];return t[r]}(e,this.strings,this.defaultLocale),this.strings[e]=t),t}static getGlobalDictionaryForPackage(e){if("u"<typeof window)return null;let r=window[l];if(void 0===t){let e=window[u];if(!e)return null;for(let n in t={},e)t[n]=new c({[r]:e[n]},r)}let n=null==t?void 0:t[e];if(!n)throw Error(`Strings for package "${e}" were not included by LocalizedStringProvider. Please add it to the list passed to createLocalizedStringDictionary.`);return n}constructor(e,t="en-US"){this.strings=Object.fromEntries(Object.entries(e).filter(([,e])=>e)),this.defaultLocale=t}}e.s(["LocalizedStringDictionary",0,c],432433);let h=new Map,d=new Map;class p{format(e,t){let r=this.strings.getStringForLocale(e,this.locale);return"function"==typeof r?r(t,this):r}plural(e,t,r="cardinal"){let n=t["="+e];if(n)return"function"==typeof n?n():n;let i=this.locale+":"+r,a=h.get(i);return a||(a=new Intl.PluralRules(this.locale,{type:r}),h.set(i,a)),"function"==typeof(n=t[a.select(e)]||t.other)?n():n}number(e){let t=d.get(this.locale);return t||(t=new Intl.NumberFormat(this.locale),d.set(this.locale,t)),t.format(e)}select(e,t){let r=e[t]||e.other;return"function"==typeof r?r():r}constructor(e,t){this.locale=e,this.strings=t}}e.s(["LocalizedStringFormatter",0,p],551701);let f=new Map,m=!1;try{m="exceptZero"===new Intl.NumberFormat("de-DE",{signDisplay:"exceptZero"}).resolvedOptions().signDisplay}catch{}let g=!1;try{g="unit"===new Intl.NumberFormat("de-DE",{style:"unit",unit:"degree"}).resolvedOptions().style}catch{}let y={degree:{narrow:{default:"°","ja-JP":" 度","zh-TW":"度","sl-SI":" °"}}};class b{format(e){let t="";if(t=m||null==this.options.signDisplay?this.numberFormatter.format(e):function(e,t,r){if("auto"===t)return e.format(r);{if("never"===t)return e.format(Math.abs(r));let n=!1;if("always"===t?n=r>0||Object.is(r,0):"exceptZero"===t&&(Object.is(r,-0)||Object.is(r,0)?r=Math.abs(r):n=r>0),!n)return e.format(r);{let t=e.format(-r),n=e.format(r),i=t.replace(n,"").replace(/\u200e|\u061C/,"");return 1!=[...i].length&&console.warn("@react-aria/i18n polyfill for NumberFormat signDisplay: Unsupported case"),t.replace(n,"!!!").replace(i,"+").replace("!!!",n)}}}(this.numberFormatter,this.options.signDisplay,e),"unit"===this.options.style&&!g){var r;let{unit:e,unitDisplay:n="short",locale:i}=this.resolvedOptions();if(!e)return t;let a=null==(r=y[e])?void 0:r[n];t+=a[i]||a.default}return t}formatToParts(e){return this.numberFormatter.formatToParts(e)}formatRange(e,t){if("function"==typeof this.numberFormatter.formatRange)return this.numberFormatter.formatRange(e,t);if(t<e)throw RangeError("End date must be >= start date");return`${this.format(e)} \u{2013} ${this.format(t)}`}formatRangeToParts(e,t){if("function"==typeof this.numberFormatter.formatRangeToParts)return this.numberFormatter.formatRangeToParts(e,t);if(t<e)throw RangeError("End date must be >= start date");let r=this.numberFormatter.formatToParts(e),n=this.numberFormatter.formatToParts(t);return[...r.map(e=>({...e,source:"startRange"})),{type:"literal",value:" â ",source:"shared"},...n.map(e=>({...e,source:"endRange"}))]}resolvedOptions(){let e=this.numberFormatter.resolvedOptions();return m||null==this.options.signDisplay||(e={...e,signDisplay:this.options.signDisplay}),g||"unit"!==this.options.style||(e={...e,style:"unit",unit:this.options.unit,unitDisplay:this.options.unitDisplay}),e}constructor(e,t={}){this.numberFormatter=function(e,t={}){let{numberingSystem:r}=t;if(r&&e.includes("-nu-")&&(e.includes("-u-")||(e+="-u-"),e+=`-nu-${r}`),"unit"===t.style&&!g){var n;let{unit:e,unitDisplay:r="short"}=t;if(!e)throw Error('unit option must be provided with style: "unit"');if(!(null==(n=y[e])?void 0:n[r]))throw Error(`Unsupported unit ${e} with unitDisplay = ${r}`);t={...t,style:"decimal"}}let i=e+(t?Object.entries(t).sort((e,t)=>
1e[0]<t[0]?-1:1).join():"");if(f.has(i))return f.get(i);let a=new Intl.NumberFormat(e,t);return f.set(i,a),a}(e,t),this.options=t}}e.s(["NumberFormatter",0,b],237598);let w=new c((r=i)&&r.__esModule?r.default:r);function v(e){let t=I.parse(e)||D.parse(e)||N.parse(e);if(t)return t;throw Error("Invalid color value: "+e)}function _(e){return 360===e?e:(e%360+360)%360}let k=[[0,"pink"],[15,"red"],[48,"orange"],[94,"yellow"],[135,"green"],[175,"cyan"],[264,"blue"],[284,"purple"],[320,"magenta"],[349,"pink"]];class S{toHexInt(){return this.toFormat("rgb").toHexInt()}getChannelValue(e){if(e in this)return this[e];throw Error("Unsupported color channel: "+e)}withChannelValue(e,t){if(e in this){let r=this.clone();return r[e]=t,r}throw Error("Unsupported color channel: "+e)}getChannelName(e,t){return(c.getGlobalDictionaryForPackage("@react-stately/color")||w).getStringForLocale(e,t)}getColorSpaceAxes(e){let{xChannel:t,yChannel:r}=e,n=t||this.getColorChannels().find(e=>e!==r),i=r||this.getColorChannels().find(e=>e!==n),a=this.getColorChannels().find(e=>e!==n&&e!==i);return{xChannel:n,yChannel:i,zChannel:a}}getColorName(e){let t,[r,n,i]=$(this),a=c.getGlobalDictionaryForPackage("@react-stately/color")||w;if(r>.999)return a.getStringForLocale("white",e);if(r<.001)return a.getStringForLocale("black",e);[t,r]=this.getOklchHue(r,n,i,e);let s="",o="";n<=.1&&n>=.001?o=r>=.7?"pale":"grayish":n>=.15&&(o="vibrant"),r<.3?s="very dark":r<.55?s="dark":r<.7||(s=r<.85?"light":"very light"),o&&(o=a.getStringForLocale(o,e)),s&&(s=a.getStringForLocale(s,e));let l=this.getChannelValue("alpha"),u=new p(e,a);if(!(l<1))return u.format("colorName",{lightness:s,chroma:o,hue:t}).replace(/\s+/g," ").trim();{let r=new b(e,{style:"percent"}).format(1-l);return u.format("transparentColorName",{lightness:s,chroma:o,hue:t,percentTrans
1parent:r}).replace(/\s+/g," ").trim()}}getOklchHue(e,t,r,n){let i=c.getGlobalDictionaryForPackage("@react-stately/color")||w;if(t<.001)return[i.getStringForLocale("gray",n),e];for(let t=0;t<k.length;t++){let[a,s]=k[t],[o,l]=k[t+1]||[360,"pink"];if(r>=a&&r<o)return"orange"===s&&(e<.68?s="brown":e=e-.68+.55),r>a+(o-a)/2&&s!==l?s=`${s} ${l}`:"yellow"===s&&e<.85&&(s="yellow green"),[i.getStringForLocale(s,n).toLocaleLowerCase(n),e]}throw Error("Unexpected hue")}getHueName(e){let[t,r,n]=$(this),[i]=this.getOklchHue(t,r,n,e);return i}}class I extends S{static parse(e){var t;let r=[];if(/^#[\da-f]+$/i.test(e)&&[4,5,7,9].includes(e.length)){let t=(e.length<6?e.replace(/[^#]/gi,"$&$&"):e).slice(1).split("");for(;t.length>0;)r.push(parseInt(t.splice(0,2).join(""),16));r[3]=void 0!==r[3]?r[3]/255:void 0}let n=e.match(/^rgba?\((.*)\)$/);if((null==n?void 0:n[1])&&(r=(r=n[1].split(",").map(e=>Number(e.trim()))).map((e,t)=>a(null!=e?e:0,0,t<3?255:1))),void 0!==r[0]&&void 0!==r[1]&&void 0!==r[2])return r.length<3?void 0:new I(r[0],r[1],r[2],null!=(t=r[3])?t:1)}toString(e="css"){switch(e){case"hex":return"#"+(this.red.toString(16).padStart(2,"0")+this.green.toString(16).padStart(2,"0")+this.blue.toString(16).padStart(2,"0")).toUpperCase();case"hexa":return"#"+(this.red.toString(16).padStart(2,"0")+this.green.toString(16).padStart(2,"0")+this.blue.toString(16).padStart(2,"0")+Math.round(255*this.alpha).toString(16).padStart(2,"0")).toUpperCase();case"rgb":return`rgb(${this.red}, ${this.green}, ${this.blue})`;case"css":case"rgba":return`rgba(${this.red}, ${this.green}, ${this.blue}, ${this.alpha})`;default:return this.toFormat(e).toString(e)}}toFormat(e){switch(e){case"hex":case"hexa":case"rgb":case"rgba":return this;case"hsb":case"hsba":return this.toHSB();case"hsl":case"hsla":return this.toHSL();default:throw Error("Unsupported color conversion: rgb -> "+e)}}toHexInt(){return this.red<<16|this.green<<8|this.blue}toHSB(){let e=this.red/255,t=this.green/255,r=this.blue/255,n=Math.min(e,t,r),i=Math.max(e,t,r),a=i-n,s=0;if(0!==a){switch(i){case e:s=(t-r)/a+6*(t<r);break;case t:s=(r-e)/a+2;break;case r:s=(e-t)/a+4}s/=6}return new D(o(360*s,2),o(100*(0===i?0:a/i),2),o(100*i,2),this.alpha)}toHSL(){let e,t,r=this.red/255,n=this.green/255,i=this.blue/255,a=Math.min(r,n,i),s=Math.max(r,n,i),l=(s+a)/2,u=s-a;if(0===u)e=t=0;else{switch(t=u/(l<.5?s+a:2-s-a),s){case r:e=(n-i)/u+6*(n<i);break;case n:e=(i-r)/u+2;break;default:e=(r-n)/u+4}e/=6}return new N(o(360*e,2),o(100*t,2),o(100*l,2),this.alpha)}clone(){return new I(this.red,this.green,this.blue,this.alpha)}getChannelRange(e){switch(e){case"red":case"green":case"blue":return{minValue:0,maxValue:255,step:1,pageSize:17};case"alpha":return{minValue:0,maxValue:1,step:.01,pageSize:.1};default:throw Error("Unknown color channel: "+e)}}getChannelFormatOptions(e){switch(e){case"red":case"green":case"blue":return{style:"decimal"};case"alpha":return{style:"percent"};default:throw Error("Unknown color channel: "+e)}}formatChannelValue(e,t){let r=this.getChannelFormatOptions(e),n=this.getChannelValue(e);return new b(t,r).format(n)}getColorSpace(){return"rgb"}getColorChannels(){return I.colorChannels}constructor(e,t,r,n){super(),this.red=e,this.green=t,this.blue=r,this.alpha=n}}I.colorChannels=["red","green","blue"];let x=/hsb\(([-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d+(?:.\d+)?%)\)|hsba\(([-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d(.\d+)?)\)/;class D extends S{static parse(e){let t;if(t=e.match(x)){var r;let[e,n,i,s]=(null!=(r=t[1])?r:t[2]).split(",").map(e=>Number(e.trim().replace("%","")));return new D(_(e),a(n,0,100),a(i,0,100),a(null!=s?s:1,0,1))}}toString(e="css"){switch(e){case"css":return this.toHSL().toString("css");case"hex":return this.toRGB().toString("hex");case"hexa":return this.toRGB().toString("hexa");case"hsb":return`hsb(${this.hue}, ${o(this.saturation,2)}%, ${o(this.brightness,2)}%)`;case"hsba":return`hsba(${this.hue}, ${o(this.saturation,2)}%, ${o(this.brightness,2)}%, ${this.alpha})`;default:return this.toFormat(e).toString(e)}}toFormat(e){switch(e){case"hsb":case"hsba":return this;case"hsl":case"hsla":return this.toHSL();case"rgb":case"rgba":return this.toRGB();default:throw Error("Unsupported color conversion: hsb -> "+e)}}toHSL(){let e=this.saturation/100,t=this.brightness/100,r=t*(1-e/2);return e=0===r||1===r?0:(t-r)/Math.min(r,1-r),new N(o(this.hue,2),o(100*e,2),o(100*r,2),this.alpha)}toRGB(){let e=this.hue,t=this.saturation/100,r=this.brightness/100,n=(n,i=(n+e/60)%6)=>r-t*r*Math.max(Math.min(i,4-i,1),0);return new I(Math.round(255*n(5)),Math.round(255*n(3)),Math.round(255*n(1)),this.alpha)}clone(){return new D(this.hue,this.saturation,this.brightness,this.alpha)}getChannelRange(e){switch(e){case"hue":return{minValue:0,maxValue:360,step:1,pageSize:15};case"saturation":case"brightness":return{minValue:0,maxValue:100,step:1,pageSize:10};
1case"alpha":return{minValue:0,maxValue:1,step:.01,pageSize:.1};default:throw Error("Unknown color channel: "+e)}}getChannelFormatOptions(e){switch(e){case"hue":return{style:"unit",unit:"degree",unitDisplay:"narrow"};case"saturation":case"brightness":case"alpha":return{style:"percent"};default:throw Error("Unknown color channel: "+e)}}formatChannelValue(e,t){let r=this.getChannelFormatOptions(e),n=this.getChannelValue(e);return("saturation"===e||"brightness"===e)&&(n/=100),new b(t,r).format(n)}getColorSpace(){return"hsb"}getColorChannels(){return D.colorChannels}constructor(e,t,r,n){super(),this.hue=e,this.saturation=t,this.brightness=r,this.alpha=n}}D.colorChannels=["hue","saturation","brightness"];let E=/hsl\(([-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d+(?:.\d+)?%)\)|hsla\(([-+]?\d+(?:.\d+)?\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d+(?:.\d+)?%\s*,\s*[-+]?\d(.\d+)?)\)/;class N extends S{static parse(e){let t;if(t=e.match(E)){var r;let[e,n,i,s]=(null!=(r=t[1])?r:t[2]).split(",").map(e=>Number(e.trim().replace("%","")));return new N(_(e),a(n,0,100),a(i,0,100),a(null!=s?s:1,0,1))}}toString(e="css"){switch(e){case"hex":return this.toRGB().toString("hex");case"hexa":return this.toRGB().toString("hexa");case"hsl":return`hsl(${this.hue}, ${o(this.saturation,2)}%, ${o(this.lightness,2)}%)`;case"css":case"hsla":return`hsla(${this.hue}, ${o(this.saturation,2)}%, ${o(this.lightness,2)}%, ${this.alpha})`;default:return this.toFormat(e).toString(e)}}toFormat(e){switch(e){case"hsl":case"hsla":return this;case"hsb":case"hsba":return this.toHSB();case"rgb":case"rgba":return this.toRGB();default:throw Error("Unsupported color conversion: hsl -> "+e)}}toHSB(){let e=this.saturation/100,t=this.lightness/100,r=t+e*Math.min(t,1-t);return e=0===r?0:2*(1-t/r),new D(o(this.hue,2),o(100*e,2),o(100*r,2),this.alpha)}toRGB(){let e=this.hue,t=this.saturation/100,r=this.lightness/100,n=t*Math.min(r,1-r),i=(t,i=(t+e/30)%12)=>r-n*Math.max(Math.min(i-3,9-i,1),-1);return new I(Math.round(255*i(0)),Math.round(255*i(8)),Math.round(255*i(4)),this.alpha)}clone(){return new N(this.hue,this.saturation,this.lightness,this.alpha)}getChannelRange(e){switch(e){case"hue":return{minValue:0,maxValue:360,step:1,pageSize:15};case"saturation":case"lightness":return{minValue:0,maxValue:100,step:1,pageSize:10};case"alpha":return{minValue:0,maxValue:1,step:.01,pageSize:.1};default:throw Error("Unknown color channel: "+e)}}getChannelFormatOptions(e){switch(e){case"hue":return{style:"unit",unit:"degree",unitDisplay:"narrow"};case"saturation":case"lightness":case"alpha":return{style:"percent"};default:throw Error("Unknown color channel: "+e)}}formatChannelValue(e,t){let r=this.getChannelFormatOptions(e),n=this.getChannelValue(e);return("saturation"===e||"lightness"===e)&&(n/=100),new b(t,r).format(n)}getColorSpace(){return"hsl"}getColorChannels(){return N.colorChannels}constructor(e,t,r,n){super(),this.hue=e,this.saturation=t,this.lightness=r,this.alpha=n}}function $(e){var t,r,n,i,a,s,o;let l=e.toFormat("rgb"),u=l.getChannelValue("red")/255,c=l.getChannelValue("green")/255,h=l.getChannelValue("blue")/255;[u,c,h]=(t=u,r=c,n=h,[C(t),C(r),C(n)]);let[d,p,f]=T([506752/1228815,87881/245763,12673/70218,87098/409605,175762/245763,12673/175545,7918/409605,87881/737289,1001167/1053270],u,c,h),[m,g,y]=function(e,t,r){let[n,i,a]=T([.819022437996703,.3619062600528904,-.1288737815209879,.0329836539323885,.9292868615863434,.0361446663506424,.0481771893596242,.2642395317527308,.6335478284694309],e,t,r);return T([.210454268309314,.7936177747023054,-.0040720430116193,1.9779985324311684,-2.42859224204858,.450593709617411,.0259040424655478,.7827717124575296,-.8086757549230774],Math.cbrt(n),Math.cbrt(i),Math.cbrt(a))}(d,p,f);return i=m,a=g,o=180*Math.atan2(s=y,a)/Math.PI,[i,Math.sqrt(a**2+s**2),o>=0?o:o+360]}function C(e){let t=Math.abs(e);return t<=.04045?e/12.92:(e<0?-1:1)*Math.pow((t+.055)/1.055,2.4)}function T(e,t,r,n){return[e[0]*t+e[1]*r+e[2]*n,e[3]*t+e[4]*r+e[5]*n,e[6]*t+e[7]*r+e[8]*n]}N.colorChannels=["hue","saturation","lightness"],e.s(["normalizeColor",0,function(e){return"string"==typeof e?v(e):e},"parseColor",0,v],768928);var P=e.i(467592);function R(e){return"string"===O(e)}function O(e){return(Object.prototype.toString.call(e).match(/^\[object\s+(.*?)\]$/)[1]||"").toLowerCase()}function A(e){return Number.isNaN(e)||e instanceof Number&&e?.none}let j={deg:1,grad:.9,rad:180/Math.PI,turn:360};function M(e,t,r){return isNaN(e)?t:isNaN(t)?e:e+(t-e)*r}function z(e,t,r){var n;return M(t[0],t[1],(n=e[0],(r-n)/(e[1]-n)))}function F(e,t){return Math.sign(e)===Math.sign(t)?e:-e}function U(e,t){return F(Math.abs(e)**t,e)}let L=new class{add(e,t,r){if("string"!=typeof arguments[0]){for(var e in arguments[0])this.add(e,arguments[0][e],arguments[1]);return}
1(Array.isArray(e)?e:[e]).forEach(function(e){this[e]=this[e]||[],t&&this[e][r?"unshift":"push"](t)},this)}run(e,t){this[e]=this[e]||[],this[e].forEach(function(e){e.call(t&&t.context?t.context:t,t)})}};function H(e,t){let r=e.length;Array.isArray(e[0])||(e=[e]),Array.isArray(t[0])||(t=t.map(e=>[e]));let n=t[0].length,i=t[0].map((e,r)=>t.map(e=>e[r])),a=e.map(e=>i.map(t=>{let r=0;if(!Array.isArray(e)){for(let n of t)r+=e*n;return r}for(let n=0;n<e.length;n++)r+=e[n]*(t[n]||0);return r}));return(1===r&&(a=a[0]),1===n)?a.map(e=>e[0]):a}let B={D50:[.3457/.3585,1,.8251046025104602],D65:[.3127/.329,1,1.0890577507598784]};function V(e){return Array.isArray(e)?e:B[e]}function q(e,t,r,n={}){if(e=V(e),t=V(t),!e||!t)throw TypeError(`Missing white point to convert ${!e?"from":""}${!e&&!t?"/":""}${!t?"to":""}`);if(e===t)return r;let i={W1:e,W2:t,XYZ:r,options:n};if(L.run("chromatic-adaptation-start",i),i.M||(i.W1===B.D65&&i.W2===B.D50?i.M=[[1.0479297925449969,.022946870601609652,-.05019226628920524],[.02962780877005599,.9904344267538799,-.017073799063418826],[-.009243040646204504,.015055191490298152,.7518742814281371]]:i.W1===B.D50&&i.W2===B.D65&&(i.M=[[.955473421488075,-.02309845494876471,.06325924320057072],[-.0283697093338637,1.0099953980813041,.021041441191917323],[.012314014864481998,-.020507649298898964,1.330365926242124]])),L.run("chromatic-adaptation-end",i),i.M)return H(i.M,i.XYZ);throw TypeError("Only Bradford CAT with white points D50 and D65 supported for now.")}function G(e){if(Array.isArray(e))return e.map(G);if(!e)throw TypeError("Empty color reference");R(e)&&(e=Y(e));let t=e.space||e.spaceId;return t instanceof K||(e.space=K.get(t)),void 0===e.alpha&&(e.alpha=1),e}class K{constructor(e){this.id=e.id,this.name=e.name,this.base=e.base?K.get(e.base):null,this.aliases=e.aliases,this.base&&(this.fromBase=e.fromBase,this.toBase=e.toBase);let t=e.coords??this.base.coords;for(let e in t)"name"in t[e]||(t[e].name=e);this.coords=t;let r=e.white??this.base.white??"D65";for(let t in this.white=V(r),this.formats=e.formats??{},this.formats){let e=this.formats[t];e.type||="function",e.name||=t}this.formats.color?.id||(this.formats.color={...this.formats.color??{},id:e.cssId||this.id}),e.gamutSpace?this.gamutSpace="self"===e.gamutSpace?this:K.get(e.gamutSpace):this.isPolar?this.gamutSpace=this.base:this.gamutSpace=this,this.gamutSpace.isUnbounded&&(this.inGamut=(e,t)=>!0),this.referred=e.referred,Object.defineProperty(this,"path",{value:(function(e){let t=[e];for(let r=e;r=r.base;)t.push(r);return t})(this).reverse(),writable:!1,enumerable:!0,configurable:!0}),L.run("colorspace-init-end",this)}inGamut(e,{epsilon:t=75e-6}={}){if(!this.equals(this.gamutSpace))return e=this.to(this.gamutSpace,e),this.gamutSpace.inGamut(e,{epsilon:t});let r=Object.values(this.coords);return e.every((e,n)=>{let i=r[n];if("angle"!==i.type&&i.range){if(Number.isNaN(e))return!0;let[r,n]=i.range;return(void 0===r||e>=r-t)&&(void 0===n||e<=n+t)}return!0})}get isUnbounded(){return Object.values(this.coords).every(e=>!("range"in e))}get cssId(){return this.formats?.color?.id||this.id}get isPolar(){for(let e in this.coords)if("angle"===this.coords[e].type)return!0;return!1}getFormat(e){let t;return"object"==typeof e?e=J(e,this):(t="default"===e?Object.values(this.formats)[0]:this.formats[e])?t=J(t,this):null}equals(e){return!!e&&(this===e||this.id===e||this.id===e.id)}to(e,t){let r,n;if(1==arguments.length){let r=G(e);[e,t]=[r.space,r.coords]}if(e=K.get(e),this.equals(e))return t;t=t.map(e=>Number.isNaN(e)?0:e);let i=this.path,a=e.path;for(let e=0;e<i.length;e++)if(i[e].equals(a[e]))r=i[e],n=e;else break;if(!r)throw Error(`Cannot convert between color spaces ${this} and ${e}: no connection space was found`);for(let e=i.length-1;e>n;e--)t=i[e].toBase(t);for(let e=n+1;e<a.length;e++)t=a[e].fromBase(t);return t}from(e,t){if(1==arguments.length){let r=G(e);[e,t]=[r.space,r.coords]}return(e=K.get(e)).to(this,t)}toString(){return`${this.name} (${this.id})`}getMinCoords(){let e=[];for(let t in this.coords){let r=this.coords[t],n=r.range||r.refRange;e.push(n?.min??0)}return e}static registry={};static get all(){return[...new Set(Object.values(K.registry))]}static register(e,t){if(1==arguments.length&&(t=arguments[0],e=t.id),t=this.get(t),this.registry[e]&&this.registry[e]!==t)throw Error(`Duplicate color space registration: '${e}'`);if(this.registry[e]=t,1==arguments.length&&t.aliases)for(let e of t.aliases)this.register(e,t);return t}static get(e,...t){if(!e||e instanceof K)return e;if("string"===O(e)){let t=K.registry[e.toLowerCase()];if(!t)throw TypeError(`No color space found with id = "${e}"`);return t}if(t.length)return K.get(...t);throw TypeError(`${e} is not a valid color space`)}
1static resolveCoord(e,t){let r,n,i=O(e);if("string"===i?e.includes(".")?[r,n]=e.split("."):[r,n]=[,e]:Array.isArray(e)?[r,n]=e:(r=e.space,n=e.coordId),(r=K.get(r))||(r=t),!r)throw TypeError(`Cannot resolve coordinate reference ${e}: No color space specified and relative references are not allowed here`);if("number"===(i=O(n))||"string"===i&&n>=0){let e=Object.entries(r.coords)[n];if(e)return{space:r,id:e[0],index:n,...e[1]}}r=K.get(r);let a=n.toLowerCase(),s=0;for(let e in r.coords){let t=r.coords[e];if(e.toLowerCase()===a||t.name?.toLowerCase()===a)return{space:r,id:e,index:s,...t};s++}throw TypeError(`No "${n}" coordinate found in ${r.name}. Its coordinates are: ${Object.keys(r.coords).join(", ")}`)}static DEFAULT_FORMAT={type:"functions",name:"color"}}function J(e,{coords:t}={}){if(e.coords&&!e.coordGrammar){e.type||="function",e.name||="color",e.coordGrammar=e.coords.map(e=>e.split("|").map(e=>{let t=(e=e.trim()).match(/^(<[a-z]+>)\[(-?[.\d]+),\s*(-?[.\d]+)\]?$/);if(t){let e=new String(t[1]);return e.range=[+t[2],+t[3]],e}return e}));let r=Object.entries(t).map(([t,r],n)=>{let i=e.coordGrammar[n][0],a=r.range||r.refRange,s=i.range,o="";return"<percentage>"==i?(s=[0,100],o="%"):"<angle>"==i&&(o="deg"),{fromRange:a,toRange:s,suffix:o}});e.serializeCoords=(e,t)=>e.map((e,n)=>{let{fromRange:i,toRange:a,suffix:s}=r[n];return i&&a&&(e=z(i,a,e)),e=function(e,{precision:t,unit:r}){return A(e)?"none":function(e,t){if(0===e)return 0;let r=~~e,n=0;r&&t&&(n=~~Math.log10(Math.abs(r))+1);let i=10**(t-n);return Math.floor(e*i+.5)/i}(e,t)+(r??"")}(e,{precision:t,unit:s})})}return e}let W={gamut_mapping:"css",precision:5,deltaE:"76",verbose:globalThis?.process?.env?.NODE_ENV?.toLowerCase()!=="test",warn:function(e){this.verbose&&globalThis?.console?.warn?.(e)}},Z=new Set(["<number>","<percentage>","<angle>"]);function Q(e,t,r,n){return Object.entries(e.coords).map(([e,i],a)=>{let s,o=t.coordGrammar[a],l=n[a],u=l?.type;if(!(s=l.none?o.find(e=>Z.has(e)):o.find(e=>e==u))){let t=i.name||e;throw TypeError(`${u??l.raw} not allowed for ${t} in ${r}()`)}let c=s.range;"<percentage>"===u&&(c||=[0,1]);let h=i.range||i.refRange;return c&&h&&(n[a]=z(c,h,n[a])),s})}function Y(e,{meta:t}={}){let r={str:String(e)?.trim()};if(L.run("parse-start",r),r.color)return r.color;if(r.parsed=function(e){if(!e)return;e=e.trim();let t=/^-?[\d.]+$/,r=/%|deg|g?rad|turn$/,n=e.match(/^([a-z]+)\((.+?)\)$/i);if(n){let e=[];return n[2].replace(/\/?\s*(none|[-\w.]+(?:%|deg|g?rad|turn)?)/g,(n,i)=>{let a=i.match(r),s=i;if(a){let e=a[0],t=s.slice(0,-e.length);"%"===e?(s=new Number(t/100)).type="<percentage>":((s=new Number(t*j[e])).type="<angle>",s.unit=e)}else t.test(s)?(s=new Number(s)).type="<number>":"none"===s&&((s=new Number(NaN)).none=!0);n.startsWith("/")&&((s=s instanceof Number?s:new Number(s)).alpha=!0),"object"==typeof s&&s instanceof Number&&(s.raw=i),e.push(s)}),{name:n[1].toLowerCase(),rawName:n[1],rawArgs:n[2],args:e}}}(r.str),r.parsed){let e=r.parsed.name;if("color"===e){let e=r.parsed.args.shift(),n=e.startsWith("--")?e.substring(2):`--${e}`,i=[e,n],a=r.parsed.rawArgs.indexOf("/")>0?r.parsed.args.pop():1;for(let n of K.all){let s=n.getFormat("color");if(s&&(i.includes(s.id)||s.ids?.filter(e=>i.includes(e)).length)){let i,o=Object.keys(n.coords).map((e,t)=>r.parsed.args[t]||0);return s.coordGrammar&&(i=Q(n,s,"color",o)),t&&Object.assign(t,{formatId:"color",types:i}),s.id.startsWith("--")&&!e.startsWith("--")&&W.warn(`${n.name} is a non-standard space and not currently supported in the CSS spec. Use prefixed color(${s.id}) instead of color(${e}).`),e.startsWith("--")&&!s.id.startsWith("--")&&W.warn(`${n.name} is a standard space and supported in the CSS spec. Use color(${s.id}) instead of prefixed color(${e}).`),{spaceId:n.id,coords:o,alpha:a}}}let s="",o=e in K.registry?e:n;if(o in K.registry){let e=K.registry[o].formats?.color?.id;e&&(s=`Did you mean color(${e})?`)}throw TypeError(`Cannot parse color(${e}). `+(s||"Missing a plugin?"))}for(let i of K.all){let a=i.getFormat(e);if(a&&"function"===a.type){var n;let s,o=1;
1(a.lastAlpha||(n=r.parsed.args)[n.length-1].alpha)&&(o=r.parsed.args.pop());let l=r.parsed.args;return a.coordGrammar&&(s=Q(i,a,e,l)),t&&Object.assign(t,{formatId:a.name,types:s}),{spaceId:i.id,coords:l,alpha:o}}}}else for(let e of K.all)for(let n in e.formats){let i=e.formats[n];if("custom"!==i.type||i.test&&!i.test(r.str))continue;let a=i.parse(r.str);if(a)return a.alpha??=1,t&&(t.formatId=n),a}throw TypeError(`Could not parse ${e} as a color. Missing a plugin?`)}let X=new K({id:"xyz-d65",name:"XYZ D65",coords:{x:{name:"X"},y:{name:"Y"},z:{name:"Z"}},white:"D65",formats:{color:{ids:["xyz-d65","xyz"]}},aliases:["xyz"]});class ee extends K{constructor(e){e.coords||(e.coords={r:{range:[0,1],name:"Red"},g:{range:[0,1],name:"Green"},b:{range:[0,1],name:"Blue"}}),e.base||(e.base=X),e.toXYZ_M&&e.fromXYZ_M&&(e.toBase??=t=>{let r=H(e.toXYZ_M,t);return this.white!==this.base.white&&(r=q(this.white,this.base.white,r)),r},e.fromBase??=t=>(t=q(this.base.white,this.white,t),H(e.fromXYZ_M,t))),e.referred??="display",super(e)}}let et=new ee({id:"srgb-linear",name:"Linear sRGB",white:"D65",toXYZ_M:[[.41239079926595934,.357584339383878,.1804807884018343],[.21263900587151027,.715168678767756,.07219231536073371],[.01933081871559182,.11919477979462598,.9505321522496607]],fromXYZ_M:[[3.2409699419045226,-1.537383177570094,-.4986107602930034],[-.9692436362808796,1.8759675015077202,.04155505740717559],[.05563007969699366,-.20397695888897652,1.0569715142428786]]}),er={aliceblue:[240/255,248/255,1],antiquewhite:[250/255,235/255,215/255],aqua:[0,1,1],aquamarine:[127/255,1,212/255],azure:[240/255,1,1],beige:[245/255,245/255,220/255],bisque:[1,228/255,196/255],black:[0,0,0],blanchedalmond:[1,235/255,205/255],blue:[0,0,1],blueviolet:[138/255,43/255,226/255],brown:[165/255,42/255,42/255],burlywood:[222/255,184/255,135/255],cadetblue:[95/255,158/255,160/255],chartreuse:[127/255,1,0],chocolate:[210/255,105/255,30/255],coral:[1,127/255,80/255],cornflowerblue:[100/255,149/255,237/255],cornsilk:[1,248/255,220/255],crimson:[220/255,20/255,60/255],cyan:[0,1,1],darkblue:[0,0,139/255],darkcyan:[0,139/255,139/255],darkgoldenrod:[184/255,134/255,11/255],darkgray:[169/255,169/255,169/255],darkgreen:[0,100/255,0],darkgrey:[169/255,169/255,169/255],darkkhaki:[189/255,183/255,107/255],darkmagenta:[139/255,0,139/255],darkolivegreen:[85/255,107/255,47/255],darkorange:[1,140/255,0],darkorchid:[.6,50/255,.8],darkred:[139/255,0,0],darksalmon:[233/255,150/255,122/255],darkseagreen:[143/255,188/255,143/255],darkslateblue:[72/255,61/255,139/255],darkslategray:[47/255,79/255,79/255],darkslategrey:[47/255,79/255,79/255],darkturquoise:[0,206/255,209/255],darkviolet:[148/255,0,211/255],deeppink:[1,20/255,147/255],deepskyblue:[0,191/255,1],dimgray:[105/255,105/255,105/255],dimgrey:[105/255,105/255,105/255],dodgerblue:[30/255,144/255,1],firebrick:[178/255,34/255,34/255],floralwhite:[1,250/255,240/255],forestgreen:[34/255,139/255,34/255],fuchsia:[1,0,1],gainsboro:[220/255,220/255,220/255],ghostwhite:[248/255,248/255,1],gold:[1,215/255,0],goldenrod:[218/255,165/255,32/255],gray:[128/255,128/255,128/255],green:[0,128/255,0],greenyellow:[173/255,1,47/255],grey:[128/255,128/255,128/255],honeydew:[240/255,1,240/255],hotpink:[1,105/255,180/255],indianred:[205/255,92/255,92/255],indigo:[75/255,0,130/255],ivory:[1,1,240/255],khaki:[240/255,230/255,140/255],lavender:[230/255,230/255,250/255],lavenderblush:[1,240/255,245/255],lawngreen:[124/255,252/255,0],lemonchiffon:[1,250/255,205/255],lightblue:[173/255,216/255,230/255],lightcoral:[240/255,128/255,128/255],lightcyan:[224/255,1,1],lightgoldenrodyellow:[250/255,250/255,210/255],lightgray:[211/255,211/255,211/255],lightgreen:[144/255,238/255,144/255],lightgrey:[211/255,211/255,211/255],lightpink:[1,182/255,193/255],lightsalmon:[1,160/255,122/255],lightseagreen:[32/255,178/255,170/255],lightskyblue:[135/255,206/255,250/255],lightslategray:[119/255,136/255,.6],lightslategrey:[119/255,136/255,.6],lightsteelblue:[176/255,196/255,222/255],lightyellow:[1,1,224/255],lime:[0,1,0],limegreen:[50/255,205/255,50/255],linen:[250/255,240/255,230/255],magenta:[1,0,1],maroon:[128/255,0,0],mediumaquamarine:[.4,205/255,170/255],mediumblue:[0,0,205/255],mediumorchid:[186/255,85/255,211/255],mediumpurple:[147/255,112/255,219/255],mediumseagreen:[60/255,179/255,113/255],mediumslateblue:[123/255,104/255,238/255],mediumspringgreen:[0,250/255,154/255],mediumturquoise:[72/255,209/255,.8],mediumvioletred:[199/255,21/255,133/255],midnightblue:[25/255,25/255,112/255],mintcream:[245/255,1,250/255],mistyrose:[1,228/255,225/255],moccasin:[1,228/255,181/255],navajowhite:[1,222/255,173/255],navy:[0,0,128/255],oldlace:[253/255,245/255,230/255],olive:[128/255,128/255,0],olivedrab:[107/255,142/255,35/255],orange:[1,165/255,0],orangered:[1,69/255,0],orchid:[218/255,112/255,214/255],palegoldenrod:[238/255,232/255,170/255],palegreen:[152/255,251/255,152/255],paleturquoise:[175/255,238/255,238/255],palevioletred:[219/255,112/255,147/255],papayawhip:[1,239/255,213/255],peachpuff:[1,218/255,185/255],peru:[205/255,133/255,63/255],pink:[1,192/255,203/255],plum:[221/255,160/255,221/255],powderblue:[176/255,224/255,230/255],purple:[128/255,0,128/255],rebeccapurple:[.4,.2,.6],red:[1,0,0],rosybrown:[188/255,143/255,143/255],royalblue:[65/255,105/255,225/255],saddlebrown:[139/255,69/255,19/255],salmon:[250/255,128/255,114/255],sandybrown:[244/255,164/255,96/255],seagreen:[46/255,139/255,87/255],seashell:[1,245/255,238/255],sienna:[160/255,82/255,45/255],silver:[192/255,192/255,192/255],skyblue:[135/255,206/255,235/255],slateblue:[106/255,90/255,205/255],slategray:[112/255,128/255,144/255],slategrey:[112/255,128/255,144/255],snow:[1,250/255,250/255],springgreen:[0,1,127/255],steelblue:[70/255,130/255,180/255],tan:[210/255,180/255,140/255],teal:[0,128/255,128/255],thistle:[216/255,191/255,216/255],tomato:[1,99/255,71/255],turquoise:[64/255,224/255,208/255],violet:[238/255,130/255,238/255],wheat:[245/255,222/255,179/255],white:[1,1,1],whitesmoke:[245/255,245/255,245/255],yellow:[1,1,0],yellowgreen:[154/255,205/255,50/255]},en=[,,,].fill("<percentage> | <number>[0, 255]"),ei=[,,,].fill("<number>[0, 255]"),ea=new ee({id:"srgb",name:"sRGB",base:et,fromBase:e=>e.map(e=>{let t=e<0?-1:1,r=e*t;return r>.0031308?t*(1.055*r**(1/2.4)-.055):12.92*e}),toBase:e=>e.map(e=>{let t=e<0?-1:1,r=e*t;return r<=.04045?e/12.92:t*((r+.055)/1.055)**2.4}),formats:{rgb:{coords:en},rgb_number:{name:"rgb",commas:!0,coords:ei,noAlpha:!0},color:{},rgba:{coords:en,commas:!0,lastAlpha:!0},rgba_number:{name:"rgba",commas:!0,coords:ei},hex:{type:"custom",toGamut:!0,test:e=>/^#([a-f0-9]{3,4}){1,2}$/i.test(e),parse(e){e.length<=5&&(e=e.replace(/[a-f0-9]/gi,"$&$&"));let t=[];return e.replace(/[a-f0-9]{2}/gi,e=>{t.push(parseInt(e,16)/255)}),{spaceId:"srgb",coords:t.slice(0,3),alpha:t.slice(3)[0]}},serialize:(e,t,{collapse:r=!0}={})=>{t<1&&e.push(t),e=e.map(e=>Math.round(255*e));let n=r&&e.every(e=>e%17==0);return"#"+e.map(e=>n?(e/17).toString(16):e.toString(16).padStart(2,"0")).join("")}},keyword:{type:"custom",test:e=>/^[a-z]+$/i.test(e),parse(e){e=e.toLowerCase();let t={spaceId:"srgb",coords:null,alpha:1};if("transparent"===e?(t.coords=er.black,t.alpha=0):t.coords=er[e],t.coords)return t}}}});function es(e,t,r="lab"){let n=(r=K.get(r)).from(e),i=r.from(t);return Math.sqrt(n.reduce((e,t,r)=>{let n=i[r];return isNaN(t)||isNaN(n)?e:e+(n-t)**2},0))}let eo=[[.819022437996703,.3619062600528904,-.1288737815209879],[.0329836539323885,.9292868615863434,.0361446663506424],[.0481771893596242,.2642395317527308,.63354782846943
109]],el=[[1.2268798758459243,-.5578149944602171,.2813910456659647],[-.0405757452148008,1.112286803280317,-.0717110580655164],[-.0763729366746601,-.4214933324022432,1.5869240198367816]],eu=[[.210454268309314,.7936177747023054,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],ec=[[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,-.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]],eh=new K({id:"oklab",name:"Oklab",coords:{l:{refRange:[0,1],name:"Lightness"},a:{refRange:[-.4,.4]},b:{refRange:[-.4,.4]}},white:"D65",base:X,fromBase(e){let t=H(eo,e).map(e=>Math.cbrt(e));return H(eu,t)},toBase(e){let t=H(ec,e).map(e=>e**3);return H(el,t)},formats:{oklab:{coords:["<percentage> | <number>","<number> | <percentage>[-1,1]","<number> | <percentage>[-1,1]"]}}}),ed=new K({id:"xyz-d50",name:"XYZ D50",white:"D50",base:X,fromBase:e=>q(X.white,"D50",e),toBase:e=>q("D50",X.white,e)}),ep=216/24389,ef=24/116,em=24389/27,eg=B.D50,ey=new K({id:"lab",name:"Lab",coords:{l:{refRange:[0,100],name:"Lightness"},a:{refRange:[-125,125]},b:{refRange:[-125,125]}},white:eg,base:ed,fromBase(e){let t=e.map((e,t)=>e/eg[t]).map(e=>e>ep?Math.cbrt(e):(em*e+16)/116);return[116*t[1]-16,500*(t[0]-t[1]),200*(t[1]-t[2])]},toBase(e){let t=[];return t[1]=(e[0]+16)/116,t[0]=e[1]/500+t[1],t[2]=t[1]-e[2]/200,[t[0]>ef?Math.pow(t[0],3):(116*t[0]-16)/em,e[0]>8?Math.pow((e[0]+16)/116,3):e[0]/em,t[2]>ef?Math.pow(t[2],3):(116*t[2]-16)/em].map((e,t)=>e*eg[t])},formats:{lab:{coords:["<number> | <percentage>","<number> | <percentage>[-1,1]","<number> | <percentage>[-1,1]"]}}});function eb(e){return(e%360+360)%360}let ew=new K({id:"lch",name:"LCH",coords:{l:{refRange:[0,100],name:"Lightness"},c:{refRange:[0,150],name:"Chroma"},h:{refRange:[0,360],type:"angle",name:"Hue"}},base:ey,fromBase(e){let t,[r,n,i]=e;return t=.02>Math.abs(n)&&.02>Math.abs(i)?NaN:180*Math.atan2(i,n)/Math.PI,[r,Math.sqrt(n**2+i**2),eb(t)]},toBase(e){let[t,r,n]=e;return r<0&&(r=0),isNaN(n)&&(n=0),[t,r*Math.cos(n*Math.PI/180),r*Math.sin(n*Math.PI/180)]},formats:{lch:{coords:["<number> | <percentage>","<number> | <percentage>","<number> | <angle>"]}}}),ev=Math.PI,e_=180/ev,ek=ev/180;function eS(e){let t=e*e;return t*t*t*e}function eI(e,t,{kL:r=1,kC:n=1,kH:i=1}={}){let a,s;[e,t]=G([e,t]);let[o,l,u]=ey.from(e),c=ew.from(ey,[o,l,u])[1],[h,d,p]=ey.from(t),f=ew.from(ey,[h,d,p])[1];c<0&&(c=0),f<0&&(f=0);let m=eS((c+f)/2),g=.5*(1-Math.sqrt(m/(m+0x16bcc41e9))),y=(1+g)*l,b=(1+g)*d,w=Math.sqrt(y**2+u**2),v=Math.sqrt(b**2+p**2),_=0===y&&0===u?0:Math.atan2(u,y),k=0===b&&0===p?0:Math.atan2(p,b);_<0&&(_+=2*ev),k<0&&(k+=2*ev),_*=e_;let S=h-o,I=v-w,x=(k*=e_)-_,D=_+k,E=Math.abs(x);w*v==0?a=0:E<=180?a=x:x>180?a=x-360:x<-180?a=x+360:W.warn("the unthinkable has happened");let N=2*Math.sqrt(v*w)*Math.sin(a*ek/2),$=(o+h)/2,C=(w+v)/2,T=eS(C),P=($-50)**2,R=1+.015*P/Math.sqrt(20+P),O=1+.045*C,A=1+.015*C*(1-.17*Math.cos(((s=w*v==0?D:E<=180?D/2:D<360?(D+360)/2:(D-360)/2)-30)*ek)+.24*Math.cos(2*s*ek)+.32*Math.cos((3*s+6)*ek)-.2*Math.cos((4*s-63)*ek)),j=(S/(r*R))**2;return Math.sqrt(j+=(I/(n*O))**2+(N/(i*A))**2+I/(n*O)*(-1*Math.sin(2*(30*Math.exp(-1*((s-275)/25)**2))*ek)*(2*Math.sqrt(T/(T+0x16bcc41e9))))*(N/(i*A)))}function ex(e,t){[e,t]=G([e,t]);let[r,n,i]=eh.from(e),[a,s,o]=eh.from(t);return Math.sqrt((r-a)**2+(n-s)**2+(i-o)**2)}function eD(e,t,{epsilon:r=75e-6}={}){e=G(e),t||(t=e.space),t=K.get(t);let n=e.coords;return t!==e.space&&(n=t.from(e)),t.inGamut(n,{epsilon:r})}function eE(e,t){return(e=G(e),!t||e.space.equals(t))?e.coords.slice():(t=K.get(t)).from(e)}function eN(e,t){e=G(e);let{space:r,index:n}=K.resolveCoord(t,e.space);return eE(e,r)[n]}function e$(e,t,r){return e=G(e),t=K.get(t),e.coords=t.to(e.space,r),e}function eC(e,t,r){if(e=G(e),2==arguments.length&&"object"===O(arguments[1])){let t=arguments[1];for(let r in t)eC(e,r,t[r])}else{"function"==typeof r&&(r=r(eN(e,t)));let{space:n,index:i}=K.resolveCoord(t,e.space),a=eE(e,n);a[i]=r,e$(e,n,a)}return e}function eT(e){return{space:e.space,coords:e.coords.slice(),alpha:e.alpha}}e$.returns="color",eC.returns="color";let eP=Math.PI/180,eR=new K({id:"xyz-abs-d65",cssId:"--xyz-abs-d65",name:"Absolute XYZ D65",coords:{x:{refRange:[0,9504.7],name:"Xa"},y:{refRange:[0,1e4],name:"Ya"},z:{refRange:[0,10888.3],name:"Za"}},base:X,fromBase:e=>e.map(e=>Math.max(203*e,0)),toBase:e=>e.map(e=>Math.max(e/203,0))}),eO=2610/16384,eA=16384/2610,ej=1.7*2523/32,eM=32/(1.7*2523),ez=[[.41478972,.579999,.014648],[-.20151,1.120649,.0531008],[-.0166008,.2648,.6684799]],eF=[[1.9242264357876067,-1.0047923125953657,.037651404030618],[.35031676209499907,.7264811939316552,-.06538442294808501],[-.09098281098284752,-.3127282905230739,1.5227665613052603]],eU=[[.5,.5,0],[3.524,-4.066708,.542708],[.199076,1.096799,-1.295875]],eL=[[1,.1386050432715393,.05804731615611886],[.9999999999999999,-.1386050432715393,-.05804731615611886],[.9999999999999998,-.09601924202631895,-.8118918960560388]],eH=new K({id:"jzazbz",name:"Jzazbz",coords:{jz:{refRange:[0,1],name:"Jz"},az:{refRange:[-.5,.5]},bz:{refRange:[-.5,.5]}},base:eR,fromBase(e){let[t,r,n]=e,i=H(ez,[1.15*t-(1.15-1)*n,.66*r-(.66-1)*t,n]).map(function(e){return((.8359375+18.8515625*(e/1e4)**eO)/(1+18.6875*(e/1e4)**eO))**ej}),[a,s,o]=H(eU,i);return[.43999999999999995*a/(1+-.56*a)-16295499532821565e-27,s,o]},toBase(e){let[t,r,n]=e,i=H(eL,[(t+16295499532821565e-27)/(.43999999999999995- -.56*(t+16295499532821565e-27)),r,n]).map(function(e){return 1e4*((.8359375-e**eM)/(18.6875*e**eM-18.8515625))**eA}),[a,s,o]=H(eF,i),l=(a+(1.15-1)*o)/1.15;return[l,(s+(.66-1)*l)/.66,o]},formats:{color:{coords:["<number> | <percentage>","<number> | <percentage>[-1,1]","<number> | <percentage>[-1,1]"]}}}),eB=new K({id:"jzczhz",name:"JzCzHz",coords:{jz:{refRange:[0,1],name:"Jz"},cz:{refRange:[0,1],name:"Chroma"},hz:{refRange:[0,360],type:"angle",name:"Hue"}},base:eH,fromBase(e){let t,[r,n,i]=e;return t=2e-4>Math.abs(n)&&2e-4>Math.abs(i)?NaN:180*Math.atan2(i,n)/Math.PI,[r,Math.sqrt(n**2+i**2),eb(t)]},toBase:e=>[e[0],e[1]*Math.cos(e[2]*Math.PI/180),e[1]*Math.sin(e[2]*Math.PI/180)]}),eV=2413/128,eq=2610/16384,eG=2523/32,eK=16384/2610,eJ=32/2523,eW=[[.3592832590121217,.6976051147779502,-.035891593232029],[-.1920808463704993,1.100476797037432,.0753748658519118],[.0070797844607479,.0748396662186362,.8433265453898765]],eZ=[[.5,.5,0],[6610/4096,-13613/4096,7003/4096],[17933/4096,-17390/4096,-543/4096]],eQ=[[.9999999999999998,.0086090370379328,.111029625003026],[.9999999999999998,-.0086090370379328,-.1110296250030259],[.9999999999999998,.5600313357106791,-.3206271749873188]],eY=[[2.0701522183894223,-1.3263473389671563,.2066510476294053],[.3647385209748072,.6805660249472273,-.0453045459220347],[-.0497472075358123,-.0492609666966131,1.1880659249923042]],eX=new K({id:"ictcp",name:"ICTCP",coords:{i:{refRange:[0,1],name:"I"},ct:{refRange:[-.5,.5],name:"CT"},cp:{refRange:[-.5,.5],name:"CP"}},base:eR,fromBase:e=>{var t;return t=H(eW,e),H(eZ,t.map(function(e){return((.8359375+eV*(e/1e4)**eq)/(1+18.6875*(e/1e4)**eq))**eG}))},toBase:e=>H(eY,H(eQ,e).map(function(e){let t=Math.max(e**eJ-.8359375,0);return 1e4*(t/(eV-18.6875*e**eJ))**eK}))}),e0=B.D65,e1=2*Math.PI,e2=[[.401288,.650173,-.051461],[-.250268,1.204414,.045854],[-.002079,.048952,.953127]],e5=[[1.8620678550872327,-1.0112546305316843,.14918677544445175],[.38752654323613717,.6214474419314753,-.008973985167612518],[-.015841498849333856,-.03412293802851557,1.0499644368778496]],e3=[[460,451,288],[460,-891,-261],[460,-220,-6300]],e4={dark:[.8,.525,.8],dim:[.9,.59,.9],average:[1,.69,1]},e6=[20.14,90,164.25,237.53,380.14],e9=[.8,.7,1,1.2,.8],e8=[0,100,200,300,400],e7=180/Math.PI,te=Math.PI/180;function tt(e,t){return e.map(e=>{let r=U(t*Math.abs(e)*.01,.42);return 400*F(r,e)/(r+27.13)})}function tr(e,t,r,n,i){let a={};a.discounting=i,a.refWhite=e,a.surround=n;let s=e.map(e=>100*e);a.la=t,a.yb=r;let o=s[1],l=H(e2,s),u=(n=e4[a.surround])[0];a.c=n[1],a.nc=n[2];let c=(1/(5*a.la+1))**4;a.fl=c*a.la+.1*(1-c)*(1-c)*Math.cbrt(5*a.la),a.flRoot=a.fl**.25,a.n=a.yb/o,a.z=1.48+Math.sqrt(a.n),a.nbb=.725*a.n**-.2,a.ncb=a.nbb;let h=i?1:Math.max(Math.min(u*(1-1/3.6*Math.exp((-a.la-42)/92)),1),0);a.dRgb=l.map(e=>M(1,o/e,h)),a.dRgbInv=a.dRgb.map(e=>1/e);let d=tt(l.map((e,t)=>e*a.dRgb[t]),a.fl);return a.aW=a.nbb*(2*d[0]+d[1]+.05*d[2]),a}let tn=tr(e0,64/Math.PI*.2,20,"average",!1);function ti(e,t){var r,n;let i;if(!(void 0!==e.J^void 0!==e.Q))throw Error("Conversion requires one and only one: 'J' or 'Q'");if(!(void 0!==e.C^void 0!==e.M^void 0!==e.s))throw Error("Conversion requires one and only one: 'C', 'M' or 's'");if(!(void 0!==e.h^void 0!==e.H))throw Error("Conversion requires one and only one: 'h' or 'H'");if(0===e.J||0===e.Q)return[0,0,0];let a=0,s=Math.cos(a=void 0!==e.h?eb(e.h)*te:function(e){let t=(e%400+400)%400,r=Math.floor(.01*t);t%=100;let[n,i]=e6.slice(r,r+2),[a,s]=e9.slice(r,r+2);return eb((t*(s*n-a*i)-100*n*s)/(t*(s-a)-100*s))}(e.H)*te),o=Math.sin(a),l=0;void 0!==e.J?l=.1*U(e.J,.5):void 0!==e.Q&&(l=.25*t.c*e.Q/((t.aW+4)*t.flRoot));let u=0;void 0!==e.C?u=e.C/l:void 0!==e.M?u=e.M/t.flRoot/l:void 0!==e.s&&(u=4e-4*e.s**2*(t.aW
1+4)/t.c);let c=U(u*Math.pow(1.64-Math.pow(.29,t.n),-.73),10/9),h=.25*(Math.cos(a+2)+3.8),d=t.aW*U(l,2/t.c/t.z),p=5e4/13*t.nc*t.ncb*h,f=d/t.nbb,m=23*(f+.305)*(0==(r=23*p+c*(11*s+108*o))?0:c/r),g=(n=H(e3,[f,m*s,m*o]).map(e=>e/1403),i=100/t.fl*2588.068098016295,n.map(e=>{let t=Math.abs(e);return F(i*U(t/(400-t),2.380952380952381),e)}));return H(e5,g.map((e,r)=>e*t.dRgbInv[r])).map(e=>e/100)}function ta(e,t){var r,n;let i=tt(H(e2,e.map(e=>100*e)).map((e,r)=>e*t.dRgb[r]),t.fl),a=i[0]+(-12*i[1]+i[2])/11,s=(i[0]+i[1]-2*i[2])/9,o=(Math.atan2(s,a)%e1+e1)%e1,l=.25*(Math.cos(o+2)+3.8),u=U(5e4/13*t.nc*t.ncb*(r=l*Math.sqrt(a**2+s**2),0===(n=i[0]+i[1]+1.05*i[2]+.305)?0:r/n),.9)*Math.pow(1.64-Math.pow(.29,t.n),.73),c=U(t.nbb*(2*i[0]+i[1]+.05*i[2])/t.aW,.5*t.c*t.z),h=100*U(c,2),d=4/t.c*c*(t.aW+4)*t.flRoot,p=u*c,f=p*t.flRoot,m=eb(o*e7),g=function(e){let t=eb(e);t<=e6[0]&&(t+=360);let r=function(e,t,r=0,n=e.length){for(;r<n;){let i=r+n>>1;e[i]<t?r=i+1:n=i}return r}(e6,t)-1,[n,i]=e6.slice(r,r+2),[a,s]=e9.slice(r,r+2),o=e8[r],l=(t-n)/a;return o+100*l/(l+(i-t)/s)}(m);return{J:h,C:p,h:m,s:50*U(t.c*u/(t.aW+4),.5),Q:d,M:f,H:g}}new K({id:"cam16-jmh",cssId:"--cam16-jmh",name:"CAM16-JMh",coords:{j:{refRange:[0,100],name:"J"},m:{refRange:[0,105],name:"Colorfulness"},h:{refRange:[0,360],type:"angle",name:"Hue"}},base:X,fromBase(e){let t=ta(e,tn);return[t.J,t.M,t.h]},toBase:e=>ti({J:e[0],M:e[1],h:e[2]},tn)});let ts=B.D65,to=216/24389,tl=24389/27;function tu(e){return e>8?Math.pow((e+16)/116,3):e/tl}let tc=tr(ts,200/Math.PI*tu(50),100*tu(50),"average",!1),th=new K({id:"hct",name:"HCT",coords:{h:{refRange:[0,360],type:"angle",name:"Hue"},c:{refRange:[0,145],name:"Colorfulness"},t:{refRange:[0,100],name:"Tone"}},base:X,fromBase:e=>(function(e){var t;let r=116*((t=e[1])>to?Math.cbrt(t):(tl*t+16)/116)-16;if(0===r)return[0,0,0];let n=ta(e,tc);return[eb(n.h),n.C,r]})(e),toBase:e=>(function(e,t){let[r,n,i]=e,a=[],s=0;if(0===i)return[0,0,0];let o=tu(i);s=i>0?.00379058511492914*i**2+.608983189401032*i+.9155088574762233:9514440756550361e-21*i**2+.08693057439788597*i-21.928975842194614;let l=0,u=1/0;for(;l<=15;){let e=Math.abs((a=ti({J:s,C:n,h:r},t))[1]-o);if(e<u){if(e<=2e-12)return a;u=e}s-=(a[1]-o)*s/(2*a[1]),l+=1}return ti({J:s,C:n,h:r},t)})(e,tc),formats:{color:{id:"--hct",coords:["<number> | <angle>","<percentage> | <number>","<percentage> | <number>"]}}}),td=Math.PI/180;function tp(e){e[1]<0&&(e=th.fromBase(th.toBase(e)));let t=Math.log(Math.max(1+.0228*e[1]*tc.flRoot,1))/.0228,r=e[0]*td,n=t*Math.cos(r),i=t*Math.sin(r);return[e[2],n,i]}let tf={deltaE76:function(e,t){return es(e,t,"lab")},deltaECMC:function(e,t,{l:r=2,c:n=1}={}){[e,t]=G([e,t]);let[i,a,s]=ey.from(e),[,o,l]=ew.from(ey,[i,a,s]),[u,c,h]=ey.from(t),d=ew.from(ey,[u,c,h])[1];o<0&&(o=0),d<0&&(d=0);let p=i-u,f=o-d,m=a-c,g=s-h,y=.511;i>=16&&(y=.040975*i/(1+.01765*i));let b=.0638*o/(1+.0131*o)+.638;Number.isNaN(l)&&(l=0);let w=Math.pow(o,4),v=Math.sqrt(w/(w+1900)),_=b*(v*(l>=164&&l<=345?.56+Math.abs(.2*Math.cos((l+168)*eP)):.36+Math.abs(.4*Math.cos((l+35)*eP)))+1-v),k=(p/(r*y))**2;return Math.sqrt(k+=(f/(n*b))**2+(m**2+g**2-f**2)/_**2)},deltaE2000:eI,deltaEJz:function(e,t){[e,t]=G([e,t]);let[r,n,i]=eB.from(e),[a,s,o]=eB.from(t);Number.isNaN(i)&&Number.isNaN(o)?(i=0,o=0):Number.isNaN(i)?i=o:Number.isNaN(o)&&(o=i);let l=2*Math.sqrt(n*s)*Math.sin((i-o)/2*(Math.PI/180));return Math.sqrt((r-a)**2+(n-s)**2+l**2)},deltaEITP:function(e,t){[e,t]=G([e,t]);let[r,n,i]=eX.from(e),[a,s,o]=eX.from(t);return 720*Math.sqrt((r-a)**2+.25*(n-s)**2+(i-o)**2)},deltaEOK:ex,deltaEHCT:function(e,t){[e,t]=G([e,t]);let[r,n,i]=tp(th.from(e)),[a,s,o]=tp(th.from(t));return Math.sqrt((r-a)**2+(n-s)**2+(i-o)**2)}},tm={hct:{method:"hct.c",jnd:2,deltaEMethod:"hct",blackWhiteClamp:{}},"hct-tonal":{method:"hct.c",jnd:0,deltaEMethod:"hct",blackWhiteClamp:{channel:"hct.t",min:0,max:100}}};function tg(e,{method:t=W.gamut_mapping,space:r,deltaEMethod:n="",jnd:i=2,blackWhiteClamp:a={}}={}){let s;if(e=G(e),R(arguments[1])?r=arguments[1]:r||(r=e.space),eD(e,r=K.get(r),{epsilon:0}))return e;if("css"===t)s=function(e,{space:t}={}){e=G(e),t||(t=e.space),t=K.get(t);let r=K.get("oklch");if(t.isUnbounded)return tw(e,t);let n=tw(e,r),i=n.coords[0];if(i>=1){let r=tw(ty,t);return r.alpha=e.alpha,tw(r,t)}if(i<=0){let r=tw(tb,t);return r.alpha=e.alpha,tw(r,t)}if(eD(n,t,{epsilon:0}))return tw(n,t);function a(e){let r=tw(e,t),n=Object.values(t.coords);
1return r.coords=r.coords.map((e,t)=>{if("range"in n[t]){let[r,i]=n[t].range;return Math.max(Math.min(i,e),r)}return e}),r}let s=0,o=n.coords[1],l=!0,u=eT(n),c=a(u),h=ex(c,u);if(h<.02)return c;for(;o-s>1e-4;){let e=(s+o)/2;if(u.coords[1]=e,l&&eD(u,t,{epsilon:0}))s=e;else if((h=ex(c=a(u),u))<.02)if(.02-h<1e-4)break;else l=!1,s=e;else o=e}return c}(e,{space:r});else{if("clip"===t||eD(e,r))s=tw(e,r);else{Object.prototype.hasOwnProperty.call(tm,t)&&({method:t,jnd:i,deltaEMethod:n,blackWhiteClamp:a}=tm[t]);let l=eI;if(""!==n){for(let e in tf)if("deltae"+n.toLowerCase()===e.toLowerCase()){l=tf[e];break}}let u=tg(tw(e,r),{method:"clip",space:r});if(l(e,u)>i){var o;let n;if(3===Object.keys(a).length){let t=K.resolveCoord(a.channel),r=eN(tw(e,t.space),t.id);if(A(r)&&(r=0),r>=a.max)return tw({space:"xyz-d65",coords:B.D65},e.space);if(r<=a.min)return tw({space:"xyz-d65",coords:[0,0,0]},e.space)}let u=K.resolveCoord(t),c=u.space,h=u.id,d=tw(e,c);d.coords.forEach((e,t)=>{A(e)&&(d.coords[t]=0)});let p=(u.range||u.refRange)[0],f=(n=(o=i)?Math.floor(Math.log10(Math.abs(o))):0,Math.max(parseFloat(`1e${n-2}`),1e-6)),m=p,g=eN(d,h);for(;g-m>f;){let e=eT(d);l(d,e=tg(e,{space:r,method:"clip"}))-i<f?m=eN(d,h):g=eN(d,h),eC(d,h,(m+g)/2)}s=tw(d,r)}else s=u}if("clip"===t||!eD(s,r,{epsilon:0})){let e=Object.values(r.coords).map(e=>e.range||[]);s.coords=s.coords.map((t,r)=>{let[n,i]=e[r];return void 0!==n&&(t=Math.max(n,t)),void 0!==i&&(t=Math.min(t,i)),t})}}return r!==e.space&&(s=tw(s,e.space)),e.coords=s.coords,e}tg.returns="color";let ty={space:eh,coords:[1,0,0]},tb={space:eh,coords:[0,0,0]};function tw(e,t,{inGamut:r}={}){e=G(e);let n=(t=K.get(t)).from(e),i={space:t,coords:n,alpha:e.alpha};return r&&(i=tg(i,!0===r?void 0:r)),i}tw.returns="color";let tv={"theme/page-background":"#FDFCFA","theme/card-background":"#FFFFFF","theme/primary":"#272727","theme/highlight-1":"#FFFFFF","theme/highlight-2":"#EDD280","theme/highlight-3":"#FFCDC3","theme/accent-text":"#FFFFFF","theme/accent-background":"#57822B","theme/accent-contrast":"#57822B"};e.s(["ThemeDefaults",0,tv,"compareColors",0,function(e,t){K.register(ea),K.register(eh);let r=Y(`rgb(${e})`),n=Y(`rgb(${t})`),[,i,a]=tw(r,"oklab").coords,[,s,o]=tw(n,"oklab").coords;return{distance:es(r,n,"oklab"),chromaDiff:Math.sqrt((i-s)**2+(a-o)**2)}}],269548),e.s(["colorToString",0,function(e,t){return e.toString(t).slice(t.length+1,-1)},"useColorAttribute",0,function(e,t){let r,i=(0,n.c)(2),{rootEntity:a}=(0,P.useReplicache)(),s=(0,P.useEntity)(e,t),o=(0,P.useEntity)(s?null:a,t),l=s||o,u=l?`hsba(${l.data.value})`:tv[t];return i[0]!==u?(r=v(u),i[0]=u,i[1]=r):r=i[1],r},"useColorAttributeNullable",0,function(e,t){let r,i=(0,n.c)(2),a=(0,P.useEntity)(e,t);return i[0]!==a?(r=a?v(`hsba(${a.data.value})`):null,i[0]=a,i[1]=r):r=i[1],r}],629683)},490223,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.DisallowedDomainError=r.UnsupportedDomainError=r.ReservedHandleError=r.InvalidHandleError=r.isValidTld=r.isValidHandle=r.normalizeAndEnsureValidHandle=r.normalizeHandle=r.ensureValidHandleRegex=r.ensureValidHandle=r.DISALLOWED_TLDS=r.INVALID_HANDLE=void 0,r.INVALID_HANDLE="handle.invalid",r.DISALLOWED_TLDS=[".local",".arpa",".invalid",".localhost",".internal",".example",".alt",".onion"],r.ensureValidHandle=e=>{if(!/^[a-zA-Z0-9.-]*$/.test(e))throw new n("Disallowed characters in handle (ASCII letters, digits, dashes, periods only)");if(e.length>253)throw new n("Handle is too long (253 chars max)");let t=e.split(".");if(t.length<2)throw new n("Handle domain needs at least two parts");for(let e=0;e<t.length;e++){let r=t[e];if(r.length<1)throw new n("Handle parts can not be empty");if(r.length>63)throw new n("Handle part too long (max 63 chars)");if(r.endsWith("-")||r.startsWith("-"))throw new n("Handle parts can not start or end with hyphens");if(e+1===t.length&&!/^[a-zA-Z]/.test(r))throw new n("Handle final component (TLD) must start with ASCII letter")}},r.ensureValidHandleRegex=e=>{if(!/^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/.test(e))throw new n("Handle didn't validate via regex");if(e.length>253)throw new n("Handle is too long (253 chars max)")},r.normalizeHandle=e=>e.toLowerCase(),r.normalizeAndEnsureValidHandle=e=>{let t=(0,r.normalizeHandle)(e);return(0,r.ensureValidHandle)(t),t},r.isValidHandle=e=>{try{(0,r.ensureValidHandle)(e)}catch(e){if(e instanceof n)return!1;throw e}return!0},r.isValidTld=e=>!r.DISALLOWED_TLDS.some(t=>e.endsWith(t));
1class n extends Error{}r.InvalidHandleError=n,r.ReservedHandleError=class extends Error{},r.UnsupportedDomainError=class extends Error{},r.DisallowedDomainError=class extends Error{}},722034,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.InvalidDidError=r.ensureValidDidRegex=r.ensureValidDid=void 0,r.ensureValidDid=e=>{if(!e.startsWith("did:"))throw new n('DID requires "did:" prefix');if(!/^[a-zA-Z0-9._:%-]*$/.test(e))throw new n("Disallowed characters in DID (ASCII letters, digits, and a couple other characters only)");let{length:t,1:r}=e.split(":");if(t<3)throw new n("DID requires prefix, method, and method-specific content");if(!/^[a-z]+$/.test(r))throw new n("DID method must be lower-case letters");if(e.endsWith(":")||e.endsWith("%"))throw new n('DID can not end with ":" or "%"');if(e.length>2048)throw new n("DID is too long (2048 chars max)")},r.ensureValidDidRegex=e=>{if(!/^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$/.test(e))throw new n("DID didn't validate via regex");if(e.length>2048)throw new n("DID is too long (2048 chars max)")};class n extends Error{}r.InvalidDidError=n},644351,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.InvalidNsidError=r.ensureValidNsidRegex=r.ensureValidNsid=r.NSID=void 0;class n{static parse(e){return new n(e)}static create(e,t){return new n([...e.split(".").reverse(),t].join("."))}static isValid(e){try{return n.parse(e),!0}catch(e){return!1}}constructor(e){Object.defineProperty(this,"segments",{enumerable:!0,configurable:!0,writable:!0,value:[]}),(0,r.ensureValidNsid)(e),this.segments=e.split(".")}get authority(){return this.segments.slice(0,this.segments.length-1).reverse().join(".")}get name(){return this.segments.at(this.segments.length-1)}toString(){return this.segments.join(".")}}r.NSID=n,r.ensureValidNsid=e=>{if(!/^[a-zA-Z0-9.-]*$/.test(e))throw new i("Disallowed characters in NSID (ASCII letters, digits, dashes, periods only)");if(e.length>317)throw new i("NSID is too long (317 chars max)");let t=e.split(".");if(t.length<3)throw new i("NSID needs at least three parts");for(let e=0;e<t.length;e++){let r=t[e];if(r.length<1)throw new i("NSID parts can not be empty");if(r.length>63)throw new i("NSID part too long (max 63 chars)");if(r.endsWith("-")||r.startsWith("-"))throw new i("NSID parts can not start or end with hyphen");if(/^[0-9]/.test(r)&&0===e)throw new i("NSID first part may not start with a digit");if(!/^[a-zA-Z]+$/.test(r)&&e+1===t.length)throw new i("NSID name part must be only letters")}},r.ensureValidNsidRegex=e=>{if(!/^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\.[a-zA-Z]([a-zA-Z]{0,61}[a-zA-Z])?)$/.test(e))throw new i("NSID didn't validate via regex");if(e.length>317)throw new i("NSID is too long (317 chars max)")};class i extends Error{}r.InvalidNsidError=i},819322,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.ensureValidAtUriRegex=r.ensureValidAtUri=void 0;let n=e.r(722034),i=e.r(490223),a=e.r(644351);r.ensureValidAtUri=e=>{let t=e.split("#");if(t.length>2)throw Error('ATURI can have at most one "#", separating fragment out');let r=t[1]||null;if(e=t[0],!/^[a-zA-Z0-9._~:@!$&')(*+,;=%/-]*$/.test(e))throw Error("Disallowed characters in ATURI (ASCII)");let s=e.split("/");if(s.length>=3&&("at:"!==s[0]||0!==s[1].length))throw Error('ATURI must start with "at://"');if(s.length<3)throw Error("ATURI requires at least method and authority sections");try{s[2].startsWith("did:")?(0,n.ensureValidDid)(s[2]):(0,i.ensureValidHandle)(s[2])}catch{throw Error("ATURI authority must be a valid handle or DID")}if(s.length>=4){if(0===s[3].length)throw Error("ATURI can not have a slash after authority without a path segment");try{(0,a.ensureValidNsid)(s[3])}catch{throw Error("ATURI requires first path segment (if supplied) to be valid NSID")}}if(s.length>=5&&0===s[4].length)throw Error("ATURI can not have a slash after collection, unless record key is provided");if(s.length>=6)throw Error("ATURI path can have at most two parts, and no trailing slash");if(t.length>=2&&null==r)throw Error("ATURI fragment must be non-empty and start with slash");if(null!=r){if(0===r.length||"/"!==r[0])throw Error("ATURI fragment must be non-empty and start with slash");if(!/^\/[a-zA-Z0-9._~:@!$&')(*+,;=%[\]/-]*$/.test(r))throw Error("Disallowed characters in ATURI fragment (ASCII)")}if(e.length>8192)throw Error("ATURI is far too long")},r.ensureValidAtUriRegex=e=>{let t=e.match(/^at:\/\/(?<authority>[a-zA-Z0-9._:%-]+)(\/(?<collection>[a-zA-Z0-9-.]+)(\/(?<rkey>
1[a-zA-Z0-9._~:@!$&%')(*+,;=-]+))?)?(#(?<fragment>\/[a-zA-Z0-9._~:@!$&%')(*+,;=\-[\]/\\]*))?$/);if(!t||!t.groups)throw Error("ATURI didn't validate via regex");let r=t.groups;try{(0,i.ensureValidHandleRegex)(r.authority)}catch{try{(0,n.ensureValidDidRegex)(r.authority)}catch{throw Error("ATURI authority must be a valid handle or DID")}}if(r.collection)try{(0,a.ensureValidNsidRegex)(r.collection)}catch{throw Error("ATURI collection path segment must be a valid NSID")}if(e.length>8192)throw Error("ATURI is far too long")}},152725,(e,t,r)=>{"use strict";var n=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=e.e&&e.e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),r.AtUri=r.ATP_URI_REGEX=void 0,i(e.r(819322),r),r.ATP_URI_REGEX=/^(at:\/\/)?((?:did:[a-z0-9:%-]+)|(?:[a-z0-9][a-z0-9.:-]*))(\/[^?#\s]*)?(\?[^#\s]+)?(#[^\s]+)?$/i;let a=/^(\/[^?#\s]*)?(\?[^#\s]+)?(#[^\s]+)?$/i;function s(e){let t=r.ATP_URI_REGEX.exec(e);if(t)return{hash:t[5]||"",host:t[2]||"",pathname:t[3]||"",searchParams:new URLSearchParams(t[4]||"")}}r.AtUri=class e{constructor(e,t){let r;if(Object.defineProperty(this,"hash",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"host",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"pathname",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"searchParams",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),t){if(!(r=s(t)))throw Error(`Invalid at uri: ${t}`);const n=function(e){let t=a.exec(e);if(t)return{hash:t[3]||"",pathname:t[1]||"",searchParams:new URLSearchParams(t[2]||"")}}(e);if(!n)throw Error(`Invalid path: ${e}`);Object.assign(r,n)}else if(!(r=s(e)))throw Error(`Invalid at uri: ${e}`);this.hash=r.hash,this.host=r.host,this.pathname=r.pathname,this.searchParams=r.searchParams}static make(t,r,n){let i=t;return r&&(i+="/"+r),n&&(i+="/"+n),new e(i)}get protocol(){return"at:"}get origin(){return`at://${this.host}`}get hostname(){return this.host}set hostname(e){this.host=e}get search(){return this.searchParams.toString()}set search(e){this.searchParams=new URLSearchParams(e)}get collection(){return this.pathname.split("/").filter(Boolean)[0]||""}set collection(e){let t=this.pathname.split("/").filter(Boolean);t[0]=e,this.pathname=t.join("/")}get rkey(){return this.pathname.split("/").filter(Boolean)[1]||""}set rkey(e){let t=this.pathname.split("/").filter(Boolean);t[0]||(t[0]="undefined"),t[1]=e,this.pathname=t.join("/")}get href(){return this.toString()}toString(){let e=this.pathname||"/";e.startsWith("/")||(e=`/${e}`);let t=this.searchParams.toString();t&&!t.startsWith("?")&&(t=`?${t}`);let r=this.hash;return r&&!r.startsWith("#")&&(r=`#${r}`),`at://${this.host}${e}${t}${r}`}}},892314,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.InvalidTidError=r.isValidTid=r.ensureValidTid=void 0;let n=/^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$/;r.ensureValidTid=e=>{if(13!==e.length)throw new i("TID must be 13 characters");if(!n.test(e))throw new i("TID syntax not valid (regex)")},r.isValidTid=e=>13===e.length&&n.test(e);class i extends Error{}r.InvalidTidError=i},576239,(e,t,r)=>{"use strict";Object.defineProperty(r,"__esModule",{value:!0}),r.InvalidRecordKeyError=r.isValidRecordKey=r.ensureValidRecordKey=void 0,r.ensureValidRecordKey=e=>{if(e.length>512||e.length<1)throw new n("record key must be 1 to 512 characters");if(!/^[a-zA-Z0-9_~.:-]{1,512}$/.test(e))throw new n("record key syntax not valid (regex)");if("."===e||".."===e)throw new n('record key can not be "." or ".."')},r.isValidRecordKey=e=>{try{(0,r.ensureValidRecordKey)(e)}catch(e){if(e instanceof n)return!1;throw e}return!0};class n extends Error{}r.InvalidRecordKeyError=n},181305,(e,t,r)=>{"use strict";
1Object.defineProperty(r,"__esModule",{value:!0}),r.InvalidDatetimeError=r.normalizeDatetimeAlways=r.normalizeDatetime=r.isValidDatetime=r.ensureValidDatetime=void 0,r.ensureValidDatetime=e=>{let t=new Date(e);if(isNaN(t.getTime()))throw new n("datetime did not parse as ISO 8601");if(t.toISOString().startsWith("-"))throw new n("datetime normalized to a negative time");if(!/^[0-9]{4}-[01][0-9]-[0-3][0-9]T[0-2][0-9]:[0-6][0-9]:[0-6][0-9](.[0-9]{1,20})?(Z|([+-][0-2][0-9]:[0-5][0-9]))$/.test(e))throw new n("datetime didn't validate via regex");if(e.length>64)throw new n("datetime is too long (64 chars max)");if(e.endsWith("-00:00"))throw new n('datetime can not use "-00:00" for UTC timezone');if(e.startsWith("000"))throw new n("datetime so close to year zero not allowed")},r.isValidDatetime=e=>{try{(0,r.ensureValidDatetime)(e)}catch(e){if(e instanceof n)return!1;throw e}return!0},r.normalizeDatetime=e=>{if((0,r.isValidDatetime)(e)){let t=new Date(e).toISOString();if((0,r.isValidDatetime)(t))return t}if(!/.*(([+-]\d\d:?\d\d)|[a-zA-Z])$/.test(e)){let t=new Date(e+"Z");if(!isNaN(t.getTime())){let e=t.toISOString();if((0,r.isValidDatetime)(e))return e}}let t=new Date(e);if(isNaN(t.getTime()))throw new n("datetime did not parse as any timestamp format");let i=t.toISOString();if((0,r.isValidDatetime)(i))return i;throw new n("datetime normalized to invalid timestamp string")},r.normalizeDatetimeAlways=e=>{try{return(0,r.normalizeDatetime)(e)}catch(e){if(e instanceof n)return new Date(0).toISOString();throw e}};class n extends Error{}r.InvalidDatetimeError=n},620196,(e,t,r)=>{"use strict";var n=e.e&&e.e.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=e.e&&e.e.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(r,"__esModule",{value:!0}),i(e.r(490223),r),i(e.r(722034),r),i(e.r(644351),r),i(e.r(152725),r),i(e.r(892314),r),i(e.r(576239),r),i(e.r(181305),r)},734582,(e,t,r)=>{"use strict";r.byteLength=function(e){var t=u(e),r=t[0],n=t[1];return(r+n)*3/4-n},r.toByteArray=function(e){var t,r,n=u(e),s=n[0],o=n[1],l=new a((s+o)*3/4-o),c=0,h=o>0?s-4:s;for(r=0;r<h;r+=4)t=i[e.charCodeAt(r)]<<18|i[e.charCodeAt(r+1)]<<12|i[e.charCodeAt(r+2)]<<6|i[e.charCodeAt(r+3)],l[c++]=t>>16&255,l[c++]=t>>8&255,l[c++]=255&t;return 2===o&&(t=i[e.charCodeAt(r)]<<2|i[e.charCodeAt(r+1)]>>4,l[c++]=255&t),1===o&&(t=i[e.charCodeAt(r)]<<10|i[e.charCodeAt(r+1)]<<4|i[e.charCodeAt(r+2)]>>2,l[c++]=t>>8&255,l[c++]=255&t),l},r.fromByteArray=function(e){for(var t,r=e.length,i=r%3,a=[],s=0,o=r-i;s<o;s+=16383)a.push(function(e,t,r){for(var i,a=[],s=t;s<r;s+=3)i=(e[s]<<16&0xff0000)+(e[s+1]<<8&65280)+(255&e[s+2]),a.push(n[i>>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return a.join("")}(e,s,s+16383>o?o:s+16383));return 1===i?a.push(n[(t=e[r-1])>>2]+n[t<<4&63]+"=="):2===i&&a.push(n[(t=(e[r-2]<<8)+e[r-1])>>10]+n[t>>4&63]+n[t<<2&63]+"="),a.join("")};for(var n=[],i=[],a="u">typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,l=s.length;o<l;++o)n[o]=s[o],i[s.charCodeAt(o)]=o;function u(e){var t=e.length;if(t%4>0)throw Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");-1===r&&(r=t);var n=r===t?0:4-r%4;return[r,n]}i[45]=62,i[95]=63},462819,(e,t,r)=>{"use strict";r.parse=function(e,t){if("string"!=typeof e)throw TypeError("argument str must be a string");for(var r={},n=(t||{}).decode||a,i=0;i<e.length;){var s=e.indexOf("=",i);if(-1===s)break;var o=e.indexOf(";",i);if(-1===o)o=e.length;else if(o<s){i=e.lastIndexOf(";",s-1)+1;continue}var l=e.slice(i,s).trim();if(void 0===r[l]){var u=e.slice(s+1,o).trim();34===u.charCodeAt(0)&&(u=u.slice(1,-1)),r[l]=function(e,t){try{return t(e)}catch(t){return e}}(u,n)}i=o+1}return r},r.serialize=function(e,t,r){var a=r||{},o=a.encode||s;if("function"!=typeof o)throw TypeError("option encode is invali
1d");if(!i.test(e))throw TypeError("argument name is invalid");var l=o(t);if(l&&!i.test(l))throw TypeError("argument val is invalid");var u=e+"="+l;if(null!=a.maxAge){var c=a.maxAge-0;if(isNaN(c)||!isFinite(c))throw TypeError("option maxAge is invalid");u+="; Max-Age="+Math.floor(c)}if(a.domain){if(!i.test(a.domain))throw TypeError("option domain is invalid");u+="; Domain="+a.domain}if(a.path){if(!i.test(a.path))throw TypeError("option path is invalid");u+="; Path="+a.path}if(a.expires){var h,d=a.expires;if(h=d,"[object Date]"!==n.call(h)&&!(h instanceof Date)||isNaN(d.valueOf()))throw TypeError("option expires is invalid");u+="; Expires="+d.toUTCString()}if(a.httpOnly&&(u+="; HttpOnly"),a.secure&&(u+="; Secure"),a.priority)switch("string"==typeof a.priority?a.priority.toLowerCase():a.priority){case"low":u+="; Priority=Low";break;case"medium":u+="; Priority=Medium";break;case"high":u+="; Priority=High";break;default:throw TypeError("option priority is invalid")}if(a.sameSite)switch("string"==typeof a.sameSite?a.sameSite.toLowerCase():a.sameSite){case!0:case"strict":u+="; SameSite=Strict";break;case"lax":u+="; SameSite=Lax";break;case"none":u+="; SameSite=None";break;default:throw TypeError("option sameSite is invalid")}return u};var n=Object.prototype.toString,i=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
1function a(e){return -1!==e.indexOf("%")?decodeURIComponent(e):e}function s(e){return encodeURIComponent(e)}},738954,e=>{"use strict";class t extends Error{constructor(e,t="FunctionsError",r){super(e),this.name=t,this.context=r}}class r extends t{constructor(e){super("Failed to send a request to the Edge Function","FunctionsFetchError",e)}}class n extends t{constructor(e){super("Relay Error invoking the Edge Function","FunctionsRelayError",e)}}class i extends t{constructor(e){super("Edge Function returned a non-2xx status code","FunctionsHttpError",e)}}(s=o||(o={})).Any="any",s.ApNortheast1="ap-northeast-1",s.ApNortheast2="ap-northeast-2",s.ApSouth1="ap-south-1",s.ApSoutheast1="ap-southeast-1",s.ApSoutheast2="ap-southeast-2",s.CaCentral1="ca-central-1",s.EuCentral1="eu-central-1",s.EuWest1="eu-west-1",s.EuWest2="eu-west-2",s.EuWest3="eu-west-3",s.SaEast1="sa-east-1",s.UsEast1="us-east-1",s.UsWest1="us-west-1",s.UsWest2="us-west-2";class a{constructor(t,{headers:r={},customFetch:n,region:i=o.Any}={}){this.url=t,this.headers=r,this.region=i,this.fetch=(t=>{let r;return r=t||("u"<typeof fetch?(...t)=>e.A(611737).then(({default:e})=>e(...t)):fetch),(...e)=>r(...e)})(n)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e,t={}){var a,s,o,l,u;return s=this,o=void 0,l=void 0,u=function*(){try{let s,{headers:o,method:l,body:u}=t,c={},{region:h}=t;h||(h=this.region),h&&"any"!==h&&(c["x-region"]=h),u&&(o&&!Object.prototype.hasOwnProperty.call(o,"Content-Type")||!o)&&("u">typeof Blob&&u instanceof Blob||u instanceof ArrayBuffer?(c["Content-Type"]="application/octet-stream",s=u):"string"==typeof u?(c["Content-Type"]="text/plain",s=u):"u">typeof FormData&&u instanceof FormData?s=u:(c["Content-Type"]="application/json",s=JSON.stringify(u)));let d=yield this.fetch(`${this.url}/${e}`,{method:l||"POST",headers:Object.assign(Object.assign(Object.assign({},c),this.headers),o),body:s}).catch(e=>{throw new r(e)}),p=d.headers.get("x-relay-error");if(p&&"true"===p)throw new n(d);if(!d.ok)throw new i(d);let f=(null!=(a=d.headers.get("Content-Type"))?a:"text/plain").split(";")[0].trim();return{data:"application/json"===f?yield d.json():"application/octet-stream"===f?yield d.blob():"text/event-stream"===f?d:"multipart/form-data"===f?yield d.formData():yield d.text(),error:null}}catch(e){return{data:null,error:e}}},new(l||(l=Promise))(function(e,t){function r(e){try{i(u.next(e))}catch(e){t(e)}}function n(e){try{i(u.throw(e))}catch(e){t(e)}}function i(t){var i;t.done?e(t.value):((i=t.value)instanceof l?i:new l(function(e){e(i)})).then(r,n)}i((u=u.apply(s,o||[])).next())})}}var s,o,l,u,c,h,d,p,f,m,g,y,b,w,v,_,k,S,I,x,D,E,N=e.i(906085);class $ extends Error{constructor(e){super(e.message),this.name="PostgrestError",this.details=e.details,this.hint=e.hint,this.co
1de=e.code}}class C{constructor(e){this.shouldThrowOnError=!1,this.method=e.method,this.url=e.url,this.headers=e.headers,this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle,e.fetch?this.fetch=e.fetch:"u"<typeof fetch?this.fetch=N.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}then(e,t){void 0===this.schema||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),"GET"!==this.method&&"HEAD"!==this.method&&(this.headers["Content-Type"]="application/json");let r=(0,this.fetch)(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async e=>{var t,r,n;let i=null,a=null,s=null,o=e.status,l=e.statusText;if(e.ok){if("HEAD"!==this.method){let t=await e.text();""===t||(a="text/csv"===this.headers.Accept||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?t:JSON.parse(t))}let n=null==(t=this.headers.Prefer)?void 0:t.match(/count=(exact|planned|estimated)/),u=null==(r=e.headers.get("content-range"))?void 0:r.split("/");n&&u&&u.length>1&&(s=parseInt(u[1])),this.isMaybeSingle&&"GET"===this.method&&Array.isArray(a)&&(a.length>1?(i={code:"PGRST116",details:`Results contain ${a.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},a=null,s=null,o=406,l="Not Acceptable"):a=1===a.length?a[0]:null)}else{let t=await e.text();try{i=JSON.parse(t),Array.isArray(i)&&404===e.status&&(a=[],i=null,o=200,l="OK")}catch(r){404===e.status&&""===t?(o=204,l="No Content"):i={message:t}}if(i&&this.isMaybeSingle&&(null==(n=null==i?void 0:i.details)?void 0:n.includes("0 rows"))&&(i=null,o=200,l="OK"),i&&this.shouldThrowOnError)throw new $(i)}return{error:i,data:a,count:s,status:o,statusText:l}});return this.shouldThrowOnError||(r=r.catch(e=>{var t,r,n;return{error:{message:`${null!=(t=null==e?void 0:e.name)?t:"FetchError"}: ${null==e?void 0:e.message}`,details:`${null!=(r=null==e?void 0:e.stack)?r:""}`,hint:"",code:`${null!=(n=null==e?void 0:e.code)?n:""}`},data:null,count:null,status:0,statusText:""}})),r.then(e,t)}}class T extends C{select(e){let t=!1,r=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!t?"":('"'===e&&(t=!t),e)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(e,{ascending:t=!0,nullsFirst:r,foreignTable:n,referencedTable:i=n}={}){let a=i?`${i}.order`:"order",s=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${s?`${s},`:""}${e}.${t?"asc":"desc"}${void 0===r?"":r?".nullsfirst":".nullslast"}`),this}limit(e,{foreignTable:t,referencedTable:r=t}={}){let n=void 0===r?"limit":`${r}.limit`;return this.url.searchParams.set(n,`${e}`),this}range(e,t,{foreignTable:r,referencedTable:n=r}={}){let i=void 0===n?"offset":`${n}.offset`,a=void 0===n?"limit":`${n}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(a,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return"GET"===this.method?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:e=!1,verbose:t=!1,settings:r=!1,buffers:n=!1,wal:i=!1,format:a="text"}={}){var s;let o=[e?"analyze":null,t?"verbose":null,r?"settings":null,n?"buffers":null,i?"wal":null].filter(Boolean).join("|"),l=null!=(s=this.headers.Accept)?s:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${a}; for="${l}"; options=${o};`,this}rollback(){var e;return(null!=(e=this.headers.Prefer)?e:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}}class P extends T{eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(",")}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(",")}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(",")}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(",")}}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}in(e,t){let r=Array.from(new Set(t)).map(e=>"string"==typeof e&&RegExp("[,()]").test(e)?`"${e}"`:`${e}`).join(",");return this.url.searchParams.append(e,`in.(${r})`),this}contains(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(",")}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return"string"==typeof t?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(",")}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return"string"==typeof t?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(",")}}`),this}textSearch(e,t,{config:r,type:n}={}){let i="";"plain"===n?i="pl":"phrase"===n?i="ph":"websearch"===n&&(i="w");let a=void 0===r?"":`(${r})`;return this.url.searchParams.append(e,`${i}fts${a}.${t}`),this}match(e){return Object.entries(e).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,r){return this.url.searchParams.append(e,`not.${t}.${r}`),this}or(e,{foreignTable:t,referencedTable:r=t}={}){let n=r?`${r}.or`:"or";return this.url.searchParams.append(n,`(${e})`),this}filter(e,t,r){return this.url.searchParams.append(e,`${t}.${r}`),this}}class R{constructor(e,{headers:t={},schema:r,fetch:n}){this.url=e,this.headers=t,this.schema=r,this.fetch=n}
1select(e,{head:t=!1,count:r}={}){let n=!1,i=(null!=e?e:"*").split("").map(e=>/\s/.test(e)&&!n?"":('"'===e&&(n=!n),e)).join("");return this.url.searchParams.set("select",i),r&&(this.headers.Prefer=`count=${r}`),new P({method:t?"HEAD":"GET",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(e,{count:t,defaultToNull:r=!0}={}){let n=[];if(this.headers.Prefer&&n.push(this.headers.Prefer),t&&n.push(`count=${t}`),r||n.push("missing=default"),this.headers.Prefer=n.join(","),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);this.url.searchParams.set("columns",e.join(","))}}return new P({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}upsert(e,{onConflict:t,ignoreDuplicates:r=!1,count:n,defaultToNull:i=!0}={}){let a=[`resolution=${r?"ignore":"merge"}-duplicates`];if(void 0!==t&&this.url.searchParams.set("on_conflict",t),this.headers.Prefer&&a.push(this.headers.Prefer),n&&a.push(`count=${n}`),i||a.push("missing=default"),this.headers.Prefer=a.join(","),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);this.url.searchParams.set("columns",e.join(","))}}return new P({method:"POST",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}update(e,{count:t}={}){let r=[];return this.headers.Prefer&&r.push(this.headers.Prefer),t&&r.push(`count=${t}`),this.headers.Prefer=r.join(","),new P({method:"PATCH",url:this.url,headers:this.headers,schema:this.schema,body:e,fetch:this.fetch,allowEmpty:!1})}delete({count:e}={}){let t=[];return e&&t.push(`count=${e}`),this.headers.Prefer&&t.unshift(this.headers.Prefer),this.headers.Prefer=t.join(","),new P({method:"DELETE",url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}}let O={"X-Client-Info":"postgrest-js/1.15.2"};class A{constructor(e,{headers:t={},schema:r,fetch:n}={}){this.url=e,this.headers=Object.assign(Object.assign({},O),t),this.schemaName=r,this.fetch=n}from(e){return new R(new URL(`${this.url}/${e}`),{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(e){return new A(this.url,{headers:this.headers,schema:e,fetch:this.fetch})}rpc(e,t={},{head:r=!1,get:n=!1,count:i}={}){let a,s,o=new URL(`${this.url}/rpc/${e}`);r||n?(a=r?"HEAD":"GET",Object.entries(t).filter(([e,t])=>void 0!==t).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(",")}}`:`${t}`]).forEach(([e,t])=>{o.searchParams.append(e,t)})):(a="POST",s=t);let l=Object.assign({},this.headers);return i&&(l.Prefer=`count=${i}`),new P({method:a,url:o,headers:l,schema:this.schemaName,body:s,fetch:this.fetch,allowEmpty:!1})}}let j={"X-Client-Info":"realtime-js/2.9.5"};(w=l||(l={}))[w.connecting=0]="connecting",w[w.open=1]="open",w[w.closing=2]="closing",w[w.closed=3]="closed",(v=u||(u={})).closed="closed",v.errored="errored",v.joined="joined",v.joining="joining",v.leaving="leaving",(_=c||(c={})).close="phx_close",_.error="phx_error",_.join="phx_join",_.reply="phx_reply",_.leave="phx_leave",_.access_token="access_token",(h||(h={})).websocket="websocket",(k=d||(d={})).Connecting="connecting",k.Open="open",k.Closing="closing",k.Closed="closed";class M{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0,this.callback=e,this.timerCalc=t}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}class z{constructor(){this.HEADER_LENGTH=1}decode(e,t){return e.constructor===ArrayBuffer?t(this._binaryDecode(e)):"string"==typeof e?t(JSON.parse(e)):t({})}_binaryDecode(e){let t=new DataView(e),r=new TextDecoder;return this._decodeBroadcast(e,t,r)}_decodeBroadcast(e,t,r){let n=t.getUint8(1),i=t.getUint8(2),a=this.HEADER_LENGTH+2,s=r.decode(e.slice(a,a+n));a+=n;let o=r.decode(e.slice(a,a+i));return a+=i,{ref:null,topic:s,event:o,payload:JSON.parse(r.decode(e.slice(a,e.byteLength)))}}}class F{constructor(e,t,r={},n=1e4){this.channel=e,this.event=t,this.payload=r,this.timeout=n,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHo
1oks=[],this.refEvent=null}resend(e){this.timeout=e,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(e){this.payload=Object.assign(Object.assign({},this.payload),e)}receive(e,t){var r;return this._hasReceived(e)&&t(null==(r=this.receivedResp)?void 0:r.response),this.recHooks.push({status:e,callback:t}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);let e=e=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=e,this._matchReceive(e)};this.channel._on(this.refEvent,{},e),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(e,t){this.refEvent&&this.channel._trigger(this.refEvent,{status:e,response:t})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:e,response:t}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}_hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}}(S=p||(p={})).SYNC="sync",S.JOIN="join",S.LEAVE="leave";class U{constructor(e,t){this.channel=e,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(null==t?void 0:t.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},e=>{let{onJoin:t,onLeave:r,onSync:n}=this.caller;this.joinRef=this.channel._joinRef(),this.state=U.syncState(this.state,e,t,r),this.pendingDiffs.forEach(e=>{this.state=U.syncDiff(this.state,e,t,r)}),this.pendingDiffs=[],n()}),this.channel._on(r.diff,{},e=>{let{onJoin:t,onLeave:r,onSync:n}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(e):(this.state=U.syncDiff(this.state,e,t,r),n())}),this.onJoin((e,t,r)=>{this.channel._trigger("presence",{event:"join",key:e,currentPresences:t,newPresences:r})}),this.onLeave((e,t,r)=>{this.channel._trigger("presence",{event:"leave",key:e,currentPresences:t,leftPresences:r})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(e,t,r,n){let i=this.cloneDeep(e),a=this.transformState(t),s={},o={};return this.map(i,(e,t)=>{a[e]||(o[e]=t)}),this.map(a,(e,t)=>{let r=i[e];if(r){let n=t.map(e=>e.presence_ref),i=r.map(e=>e.presence_ref),a=t.filter(e=>0>i.indexOf(e.presence_ref)),l=r.filter(e=>0>n.indexOf(e.presence_ref));a.length>0&&(s[e]=a),l.length>0&&(o[e]=l)}else s[e]=t}),this.syncDiff(i,{joins:s,leaves:o},r,n)}static syncDiff(e,t,r,n){let{joins:i,leaves:a}={joins:this.transformState(t.joins),leaves:this.transformState(t.leaves)};return r||(r=()=>{}),n||(n=()=>{}),this.map(i,(t,n)=>{var i;let a=null!=(i=e[t])?i:[];if(e[t]=this.cloneDeep(n),a.length>0){let r=e[t].map(e=>e.presence_ref),n=a.filter(e=>0>r.indexOf(e.presence_ref));e[t].unshift(...n)}r(t,a,n)}),this.map(a,(t,r)=>{let i=e[t];if(!i)return;let a=r.map(e=>e.presence_ref);i=i.filter(e=>0>a.indexOf(e.presence_ref)),e[t]=i,n(t,i,r),0===i.length&&delete e[t]}),e}static map(e,t){return Object.getOwnPropertyNames(e).map(r=>t(r,e[r]))}static transformState(e){return Object.getOwnPropertyNames(e=this.cloneDeep(e)).reduce((t,r)=>{let n=e[r];return"metas"in n?t[r]=n.metas.map(e=>(e.presence_ref=e.phx_ref,delete e.phx_ref,delete e.phx_ref_prev,e)):t[r]=n,t},{})}static cloneDeep(e){return JSON.parse(JSON.stringify(e))}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}(I=f||(f={})).abstime="abstime",I.bool="bool",I.date="date",I.daterange="daterange",I.float4="float4",I.float8="float8",I.int2="int2",I.int4="int4",I.int4range="int4range",I.int8="int8",I.int8range="int8range",I.json="json",I.jsonb="jsonb",I.money="money",I.numeric="numeric",I.oid="oid",I.reltime="reltime",I.text="text",I.time="time",I.timestamp="timestamp",I.timestamptz="timestamptz",I.timetz="timetz",I.tsrange="tsrange",I.tstzrange="tstzrange";let L=(e,t,r={})=>{var n;let i=null!=(n=r.skipTypes)?n:[];return Object.keys(t).reduce((r,n)=>(r[n]=H(n,e,t,i),r),{})},H=(e,t,r,n)=>{let i=t.find(t=>t.name===e),a=null==i?void 0:i.type,s=r[e];return a&&!n.includes(a)?B(a,s):V(s)},B=(e,t)=>{if("_"===e.charAt(0))return J(t,e.slice(1,e.length));switch(e){case f.bool:return q(t);case f.float4:case f.float8:case f.int2:case f.int4:case f.int8:case f.numeric:case f.oid:return G(t);case f.json:case f.jsonb:return K(t);case f.timestamp:return W(t);case f.abstime:case f.date:case f.daterange:case f.int4range:case f.int8range:case f.money:case f.reltime:case f.text:case f.time:case f.timestamptz:case f.timetz:case f.tsrange:case f.tstzrange:default:return V(t)}},V=e=>e,q=e=>{switch(e){case"t":return!0;case"f":return!1;default:return e}},G=e=>{if("string"==typeof e){let t=parseFloat(e);
1if(!Number.isNaN(t))return t}return e},K=e=>{if("string"==typeof e)try{return JSON.parse(e)}catch(e){console.log(`JSON parse error: ${e}`)}return e},J=(e,t)=>{if("string"!=typeof e)return e;let r=e.length-1,n=e[r];if("{"===e[0]&&"}"===n){let n,i=e.slice(1,r);try{n=JSON.parse("["+i+"]")}catch(e){n=i?i.split(","):[]}return n.map(e=>B(t,e))}return e},W=e=>"string"==typeof e?e.replace(" ","T"):e;(x=m||(m={})).ALL="*",x.INSERT="INSERT",x.UPDATE="UPDATE",x.DELETE="DELETE",(D=g||(g={})).BROADCAST="broadcast",D.PRESENCE="presence",D.POSTGRES_CHANGES="postgres_changes",(E=y||(y={})).SUBSCRIBED="SUBSCRIBED",E.TIMED_OUT="TIMED_OUT",E.CLOSED="CLOSED",E.CHANNEL_ERROR="CHANNEL_ERROR";class Z{constructor(e,t={config:{}},r){this.topic=e,this.params=t,this.socket=r,this.bindings={},this.state=u.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=e.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""}},t.config),this.timeout=this.socket.timeout,this.joinPush=new F(this,c.join,this.params,this.timeout),this.rejoinTimer=new M(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=u.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this._onClose(()=>{this.rejoinTimer.reset(),this.socket.log("channel",`close ${this.topic} ${this._joinRef()}`),this.state=u.closed,this.socket._remove(this)}),this._onError(e=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,e),this.state=u.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=u.errored,this.rejoinTimer.scheduleTimeout())}),this._on(c.reply,{},(e,t)=>{this._trigger(this._replyEventName(t),e)}),this.presence=new U(this),this.broadcastEndpointURL=this._broadcastEndpointURL()}subscribe(e,t=this.timeout){var r,n;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{let{config:{broadcast:i,presence:a}}=this.params;this._onError(t=>e&&e("CHANNEL_ERROR",t)),this._onClose(()=>e&&e("CLOSED"));let s={},o={broadcast:i,presence:a,postgres_changes:null!=(n=null==(r=this.bindings.postgres_changes)?void 0:r.map(e=>e.filter))?n:[]};this.socket.accessToken&&(s.access_token=this.socket.accessToken),this.updateJoinPayload(Object.assign({config:o},s)),this.joinedOnce=!0,this._rejoin(t),this.joinPush.receive("ok",({postgres_changes:t})=>{var r;if(this.socket.accessToken&&this.socket.setAuth(this.socket.accessToken),void 0===t){e&&e("SUBSCRIBED");return}{let n=this.bindings.postgres_changes,i=null!=(r=null==n?void 0:n.length)?r:0,a=[];for(let r=0;r<i;r++){let i=n[r],{filter:{event:s,schema:o,table:l,filter:u}}=i,c=t&&t[r];if(c&&c.event===s&&c.schema===o&&c.table===l&&c.filter===u)a.push(Object.assign(Object.assign({},i),{id:c.id}));else{this.unsubscribe(),e&&e("CHANNEL_ERROR",Error("mismatch between server and client bindings for postgres changes"));return}}this.bindings.postgres_changes=a,e&&e("SUBSCRIBED");return}}).receive("error",t=>{e&&e("CHANNEL_ERROR",Error(JSON.stringify(Object.values(t).join(", ")||"error")))}).receive("timeout",()=>{e&&e("TIMED_OUT")})}return this}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:"presence",event:"track",payload:e},t.timeout||this.timeout)}async untrack(e={}){return await this.send({type:"presence",event:"untrack"},e)}on(e,t,r){return this._on(e,t,r)}async send(e,t={}){var r,n;if(this._canPush()||"broadcast"!==e.type)return new Promise(r=>{var n,i,a;let s=this._push(e.type,e,t.timeout||this.timeout);"broadcast"!==e.type||(null==(a=null==(i=null==(n=this.params)?void 0:n.config)?void 0:i.broadcast)?void 0:a.ack)||r("ok"),s.receive("ok",()=>r("ok")),s.receive("error",()=>r("error")),s.receive("timeout",()=>r("timed out"))});{let{event:i,payload:a}=e,s={method:"POST",headers:{apikey:null!=(r=this.socket.apiKey)?r:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:a}]})};try{if((await this._fetchWithTimeout(this.broadcastEndpointURL,s,null!=(n=t.timeout)?n:this.timeout)).ok)return"ok";return"error"}catch(e){if("AbortError"===e.name)return"timed out";return"error"}}}updateJoinPayload(e){this.joinPush.updatePayload(e)}unsubscribe(e=this.timeout){this.state=u.leaving;let t=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(c.close,"leave",this._joinRef())};return this.rejoinTimer.reset(),this.joinPush.destroy(),new Promise(r=>{let n=new F(this,c.leave,{},e);n.receive("ok",()=>{t(),r("ok")}).receive("timeout",()=>{t(),r("timed out")}).receive("error",()=>{r("error")}),n.send(),this._canPush()||n.trigger("ok",{})})}_broadcastEndpointURL(){let e=this.socket.endPoint;
1return(e=(e=e.replace(/^ws/i,"http")).replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,"")).replace(/\/+$/,"")+"/api/broadcast"}async _fetchWithTimeout(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(),r),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:n.signal}));return clearTimeout(i),a}_push(e,t,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${e}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let n=new F(this,e,t,r);return this._canPush()?n.send():(n.startTimeout(),this.pushBuffer.push(n)),n}_onMessage(e,t,r){return t}_isMember(e){return this.topic===e}_joinRef(){return this.joinPush.ref}_trigger(e,t,r){var n,i;let a=e.toLocaleLowerCase(),{close:s,error:o,leave:l,join:u}=c;if(r&&[s,o,l,u].indexOf(a)>=0&&r!==this._joinRef())return;let h=this._onMessage(a,t,r);if(t&&!h)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(a)?null==(n=this.bindings.postgres_changes)||n.filter(e=>{var t,r,n;return(null==(t=e.filter)?void 0:t.event)==="*"||(null==(n=null==(r=e.filter)?void 0:r.event)?void 0:n.toLocaleLowerCase())===a}).map(e=>e.callback(h,r)):null==(i=this.bindings[a])||i.filter(e=>{var r,n,i,s,o,l;if(!["broadcast","presence","postgres_changes"].includes(a))return e.type.toLocaleLowerCase()===a;if("id"in e){let a=e.id,s=null==(r=e.filter)?void 0:r.event;return a&&(null==(n=t.ids)?void 0:n.includes(a))&&("*"===s||(null==s?void 0:s.toLocaleLowerCase())===(null==(i=t.data)?void 0:i.type.toLocaleLowerCase()))}{let r=null==(o=null==(s=null==e?void 0:e.filter)?void 0:s.event)?void 0:o.toLocaleLowerCase();return"*"===r||r===(null==(l=null==t?void 0:t.event)?void 0:l.toLocaleLowerCase())}}).map(e=>{if("object"==typeof h&&"ids"in h){let e=h.data,{schema:t,table:r,commit_timestamp:n,type:i,errors:a}=e;h=Object.assign(Object.assign({},{schema:t,table:r,commit_timestamp:n,eventType:i,new:{},old:{},errors:a}),this._getPayloadRecords(e))}e.callback(h,r)})}_isClosed(){return this.state===u.closed}_isJoined(){return this.state===u.joined}_isJoining(){return this.state===u.joining}_isLeaving(){return this.state===u.leaving}_replyEventName(e){return`chan_reply_${e}`}_on(e,t,r){let n=e.toLocaleLowerCase(),i={type:n,filter:t,callback:r};return this.bindings[n]?this.bindings[n].push(i):this.bindings[n]=[i],this}_off(e,t){let r=e.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(e=>{var n;return!((null==(n=e.type)?void 0:n.toLocaleLowerCase())===r&&Z.isEqual(e.filter,t))}),this}static isEqual(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let r in e)if(e[r]!==t[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(e){this._on(c.close,{},e)}_onError(e){this._on(c.error,{},t=>e(t))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(e=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=u.joining,this.joinPush.resend(e))}_getPayloadRecords(e){let t={new:{},old:{}};return("INSERT"===e.type||"UPDATE"===e.type)&&(t.new=L(e.columns,e.record)),("UPDATE"===e.type||"DELETE"===e.type)&&(t.old=L(e.columns,e.old_record)),t}}let Q=()=>{},Y="u">typeof WebSocket;class X{constructor(t,r){var n;this.accessToken=null,this.apiKey=null,this.channels=[],this.endPoint="",this.headers=j,this.params={},this.timeout=1e4,this.heartbeatIntervalMs=3e4,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.ref=0,this.logger=Q,this.conn=null,this.sendBuffer=[],this.serializer=new z,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this._resolveFetch=t=>{let r;return r=t||("u"<typeof fetch?(...t)=>e.A(611737).then(({default:e})=>e(...t)):fetch),(...e)=>r(...e)},this.endPoint=`${t}/${h.websocket}`,(null==r?void 0:r.transport)?this.transport=r.transport:this.transport=null,(null==r?void 0:r.params)&&(this.params=r.params),(null==r?void 0:r.headers)&&(this.headers=Object.assign(Object.assign({},this.headers),r.headers)),(null==r?void 0:r.timeout)&&(this.timeout=r.timeout),(null==r?void 0:r.logger)&&(this.logger=r.logger),(null==r?void 0:r.heartbeatIntervalMs)&&(this.heartbeatIntervalMs=r.heartbeatIntervalMs);const i=null==(n=null==r?void 0:r.params)?void 0:n.apikey;i&&(this.accessToken=i,this.apiKey=i),this.reconnectAfterMs=(null==r?void 0:r.reconnectAfterMs)?r.reconnectAfterMs:e=>[1e3,2e3,5e3,1e4][e-1]||1e4,this.encode=(null==r?void 0:r.encode)?r.encode:(e,t)=>t(JSON.stringify(e)),this.decode=(null==r?void 0:r.decode)?r.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new M(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(null==r?void 0:r.fetch)}connect(){if(!this.conn){if(this.transport){this.conn=new this.transport(this._endPointURL(),void 0,{headers:this.headers});return}if(Y){this.conn=new WebSocket(this._endPointURL()),this.setupConnection();return}this.conn=new ee(this._endPointURL(),void 0,{close:()=>{this.conn=null}}),e.A(456555).then(({default:e})=>{this.conn=new e(this._endPointURL(),void 0,{headers:this.headers}),this.setupConnection()})}}
1disconnect(e,t){this.conn&&(this.conn.onclose=function(){},e?this.conn.close(e,null!=t?t:""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset())}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return 0===this.channels.length&&this.disconnect(),t}async removeAllChannels(){let e=await Promise.all(this.channels.map(e=>e.unsubscribe()));return this.disconnect(),e}log(e,t,r){this.logger(e,t,r)}connectionState(){switch(this.conn&&this.conn.readyState){case l.connecting:return d.Connecting;case l.open:return d.Open;case l.closing:return d.Closing;default:return d.Closed}}isConnected(){return this.connectionState()===d.Open}channel(e,t={config:{}}){let r=new Z(`realtime:${e}`,t,this);return this.channels.push(r),r}push(e){let{topic:t,event:r,payload:n,ref:i}=e,a=()=>{this.encode(e,e=>{var t;null==(t=this.conn)||t.send(e)})};this.log("push",`${t} ${r} (${i})`,n),this.isConnected()?a():this.sendBuffer.push(a)}setAuth(e){this.accessToken=e,this.channels.forEach(t=>{e&&t.updateJoinPayload({access_token:e}),t.joinedOnce&&t._isJoined()&&t._push(c.access_token,{access_token:e})})}_makeRef(){let e=this.ref+1;return e===this.ref?this.ref=0:this.ref=e,this.ref.toString()}_leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t._isJoined()||t._isJoining()));t&&(this.log("transport",`leaving duplicate topic "${e}"`),t.unsubscribe())}_remove(e){this.channels=this.channels.filter(t=>t._joinRef()!==e._joinRef())}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=e=>this._onConnError(e),this.conn.onmessage=e=>this._onConnMessage(e),this.conn.onclose=e=>this._onConnClose(e))}_endPointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:"1.0.0"}))}_onConnMessage(e){this.decode(e.data,e=>{let{topic:t,event:r,payload:n,ref:i}=e;(i&&i===this.pendingHeartbeatRef||r===(null==n?void 0:n.type))&&(this.pendingHeartbeatRef=null),this.log("receive",`${n.status||""} ${t} ${r} ${i&&"("+i+")"||""}`,n),this.channels.filter(e=>e._isMember(t)).forEach(e=>e._trigger(r,n,i)),this.stateChangeCallbacks.message.forEach(t=>t(e))})}_onConnOpen(){this.log("transport",`connected to ${this._endPointURL()}`),this._flushSendBuffer(),this.reconnectTimer.reset(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this._sendHeartbeat(),this.heartbeatIntervalMs),this.stateChangeCallbacks.open.forEach(e=>e())}_onConnClose(e){this.log("transport","close",e),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(t=>t(e))}_onConnError(e){this.log("transport",e.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(t=>t(e))}_triggerChanError(){this.channels.forEach(e=>e._trigger(c.error))}_appendParams(e,t){if(0===Object.keys(t).length)return e;let r=e.match(/\?/)?"&":"?",n=new URLSearchParams(t);return`${e}${r}${n}`}_flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}_sendHeartbeat(){var e;if(this.isConnected()){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),null==(e=this.conn)||e.close(1e3,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.setAuth(this.accessToken)}}}class ee{constructor(e,t,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=l.connecting,this.send=()=>{},this.url=null,this.url=e,this.close=r.close}}class et extends Error{constructor(e){super(e),this.__isStorageError=!0,this.name="StorageError"}}function er(e){return"object"==typeof e&&null!==e&&"__isStorageError"in e}class en extends et{constructor(e,t){super(e),this.name="StorageApiError",this.status=t}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class ei extends et{constructor(e,t){super(e),this.name="StorageUnknownError",this.originalError=t}}let ea=t=>{let r;return r=t||("u"<typeof fetch?(...t)=>e.A(611737).then(({default:e})=>e(...t)):fetch),(...e)=>r(...e)};var es=function(e,t,r,n){return new(r||(r=Promise))(function(i,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(s,o)}l((n=n.apply(e,t||[])).next())})};let eo=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e);function el(t,r,n,i,a,s){return es(this,void 0,void 0,function*(){return new Promise((o,l)=>{let u;t(n,(u={method:r,headers:(null==i?void 0:i.headers)||{}},"GET"===r?u:(u.headers=Object.assign({"Content-Type":"application/json"},null==i?void 0:i.headers),u.body=JSON.stringify(s),Object.assign(Object.assign({},u),a)))).then(e=>{if(!e.ok)throw e;return(null==i?void 0:i.noResolveJson)?e:e.json()}).then(e=>o(e)).catch(t=>es(void 0,void 0,void 0,function*(){var r,n,i,a;t instanceof(yield(r=void 0,n=void 0,i=void 0,a=function*(){return"u"<typeof Response?(yield e.A(611737)).Response:Response}
1,new(i||(i=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):((r=t.value)instanceof i?r:new i(function(e){e(r)})).then(s,o)}l((a=a.apply(r,n||[])).next())})))?t.json().then(e=>{l(new en(eo(e),t.status||500))}).catch(e=>{l(new ei(eo(e),e))}):l(new ei(eo(t),t))}))})})}function eu(e,t,r,n){return es(this,void 0,void 0,function*(){return el(e,"GET",t,r,n)})}function ec(e,t,r,n,i){return es(this,void 0,void 0,function*(){return el(e,"POST",t,n,i,r)})}function eh(e,t,r,n,i){return es(this,void 0,void 0,function*(){return el(e,"DELETE",t,n,i,r)})}var ed=function(e,t,r,n){return new(r||(r=Promise))(function(i,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(s,o)}l((n=n.apply(e,t||[])).next())})};let ep={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},ef={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class em{constructor(e,t={},r,n){this.url=e,this.headers=t,this.bucketId=r,this.fetch=ea(n)}uploadOrUpdate(e,t,r,n){return ed(this,void 0,void 0,function*(){try{let i,a=Object.assign(Object.assign({},ef),n),s=Object.assign(Object.assign({},this.headers),"POST"===e&&{"x-upsert":String(a.upsert)});"u">typeof Blob&&r instanceof Blob?((i=new FormData).append("cacheControl",a.cacheControl),i.append("",r)):"u">typeof FormData&&r instanceof FormData?(i=r).append("cacheControl",a.cacheControl):(i=r,s["cache-control"]=`max-age=${a.cacheControl}`,s["content-type"]=a.contentType);let o=this._removeEmptyFolders(t),l=this._getFinalPath(o),u=yield this.fetch(`${this.url}/object/${l}`,Object.assign({method:e,body:i,headers:s},(null==a?void 0:a.duplex)?{duplex:a.duplex}:{})),c=yield u.json();if(u.ok)return{data:{path:o,id:c.Id,fullPath:c.Key},error:null};return{data:null,error:c}}catch(e){if(er(e))return{data:null,error:e};throw e}})}upload(e,t,r){return ed(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",e,t,r)})}uploadToSignedUrl(e,t,r,n){return ed(this,void 0,void 0,function*(){let i=this._removeEmptyFolders(e),a=this._getFinalPath(i),s=new URL(this.url+`/object/upload/sign/${a}`);s.searchParams.set("token",t);try{let e,t=Object.assign({upsert:ef.upsert},n),a=Object.assign(Object.assign({},this.headers),{"x-upsert":String(t.upsert)});"u">typeof Blob&&r instanceof Blob?((e=new FormData).append("cacheControl",t.cacheControl),e.append("",r)):"u">typeof FormData&&r instanceof FormData?(e=r).append("cacheControl",t.cacheControl):(e=r,a["cache-control"]=`max-age=${t.cacheControl}`,a["content-type"]=t.contentType);let o=yield this.fetch(s.toString(),{method:"PUT",body:e,headers:a}),l=yield o.json();if(o.ok)return{data:{path:i,fullPath:l.Key},error:null};return{data:null,error:l}}catch(e){if(er(e))return{data:null,error:e};throw e}})}createSignedUploadUrl(e){return ed(this,void 0,void 0,function*(){try{let t=this._getFinalPath(e),r=yield ec(this.fetch,`${this.url}/object/upload/sign/${t}`,{},{headers:this.headers}),n=new URL(this.url+r.url),i=n.searchParams.get("token");if(!i)throw new et("No token returned by API");return{data:{signedUrl:n.toString(),path:e,token:i},error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}update(e,t,r){return ed(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",e,t,r)})}move(e,t){return ed(this,void 0,void 0,function*(){try{return{data:yield ec(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers}),error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}copy(e,t){return ed(this,void 0,void 0,function*(){try{return{data:{path:(yield ec(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:e,destinationKey:t},{headers:this.headers})).Key},error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}createSignedUrl(e,t,r){return ed(this,void 0,void 0,function*(){try{let n=this._getFinalPath(e),i=yield ec(this.fetch,`${this.url}/object/sign/${n}
1`,Object.assign({expiresIn:t},(null==r?void 0:r.transform)?{transform:r.transform}:{}),{headers:this.headers}),a=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:i={signedUrl:encodeURI(`${this.url}${i.signedURL}${a}`)},error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}createSignedUrls(e,t,r){return ed(this,void 0,void 0,function*(){try{let n=yield ec(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:t,paths:e},{headers:this.headers}),i=(null==r?void 0:r.download)?`&download=${!0===r.download?"":r.download}`:"";return{data:n.map(e=>Object.assign(Object.assign({},e),{signedUrl:e.signedURL?encodeURI(`${this.url}${e.signedURL}${i}`):null})),error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}download(e,t){return ed(this,void 0,void 0,function*(){let r=void 0!==(null==t?void 0:t.transform),n=this.transformOptsToQueryString((null==t?void 0:t.transform)||{}),i=n?`?${n}`:"";try{let t=this._getFinalPath(e),n=yield eu(this.fetch,`${this.url}/${r?"render/image/authenticated":"object"}/${t}${i}`,{headers:this.headers,noResolveJson:!0});return{data:yield n.blob(),error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}getPublicUrl(e,t){let r=this._getFinalPath(e),n=[],i=(null==t?void 0:t.download)?`download=${!0===t.download?"":t.download}`:"";""!==i&&n.push(i);let a=void 0!==(null==t?void 0:t.transform),s=this.transformOptsToQueryString((null==t?void 0:t.transform)||{});""!==s&&n.push(s);let o=n.join("&");return""!==o&&(o=`?${o}`),{data:{publicUrl:encodeURI(`${this.url}/${a?"render/image":"object"}/public/${r}${o}`)}}}remove(e){return ed(this,void 0,void 0,function*(){try{return{data:yield eh(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:e},{headers:this.headers}),error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}list(e,t,r){return ed(this,void 0,void 0,function*(){try{let n=Object.assign(Object.assign(Object.assign({},ep),t),{prefix:e||""});return{data:yield ec(this.fetch,`${this.url}/object/list/${this.bucketId}`,n,{headers:this.headers},r),error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}_getFinalPath(e){return`${this.bucketId}/${e}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(e){let t=[];return e.width&&t.push(`width=${e.width}`),e.height&&t.push(`height=${e.height}`),e.resize&&t.push(`resize=${e.resize}`),e.format&&t.push(`format=${e.format}`),e.quality&&t.push(`quality=${e.quality}`),t.join("&")}}let eg={"X-Client-Info":"storage-js/2.5.5"};var ey=function(e,t,r,n){return new(r||(r=Promise))(function(i,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?i(e.value):((t=e.value)instanceof r?t:new r(function(e){e(t)})).then(s,o)}l((n=n.apply(e,t||[])).next())})};class eb{constructor(e,t={},r){this.url=e,this.headers=Object.assign(Object.assign({},eg),t),this.fetch=ea(r)}listBuckets(){return ey(this,void 0,void 0,function*(){try{return{data:yield eu(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}getBucket(e){return ey(this,void 0,void 0,function*(){try{return{data:yield eu(this.fetch,`${this.url}/bucket/${e}`,{headers:this.headers}),error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}createBucket(e,t={public:!1}){return ey(this,void 0,void 0,function*(){try{return{data:yield ec(this.fetch,`${this.url}/bucket`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}updateBucket(e,t){return ey(this,void 0,void 0,function*(){try{return{data:yield function(e,t,r,n){return es(this,void 0,void 0,function*(){return el(e,"PUT",t,n,void 0,r)})}(this.fetch,`${this.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes},{headers:this.headers}),error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}emptyBucket(e){return ey(this,void 0,void 0,function*(){try{return{data:yield ec(this.fetch,`${this.url}/bucket/${e}/empty`,{},{headers:this.headers}),error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}deleteBucket(e){return ey(this,void 0,void 0,function*(){try{return{data:yield eh(this.fetch,`${this.url}/bucket/${e}`,{},{headers:this.headers}),error:null}}catch(e){if(er(e))return{data:null,error:e};throw e}})}}class ew extends eb{constructor(e,t={},r){super(e,t,r)}from(e){return new em(this.url,this.headers,e,this.fetch)}}let ev="";ev="u">typeof Deno?"deno":"u">typeof document?"web":"u">typeof navigator&&"ReactNative"===navigator.product?"react-native":"node";let e_={headers:{"X-Client-Info":`supabase-js-${ev}/2.43.4`}},ek={schema:"public"},eS={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},eI={},ex="2.64.2",eD={"X-Client-Info":`gotrue-js/${ex}`},eE="X-Supabase-Api-Version",eN={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},e$={tested:!1,writable:!1},eC=()=>
1{if(!("u">typeof document))return!1;try{if("object"!=typeof globalThis.localStorage)return!1}catch(e){return!1}if(e$.tested)return e$.writable;let e=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(e,e),globalThis.localStorage.removeItem(e),e$.tested=!0,e$.writable=!0}catch(e){e$.tested=!0,e$.writable=!1}return e$.writable};function eT(e){let t={},r=new URL(e);if(r.hash&&"#"===r.hash[0])try{new URLSearchParams(r.hash.substring(1)).forEach((e,r)=>{t[r]=e})}catch(e){}return r.searchParams.forEach((e,r)=>{t[r]=e}),t}let eP=t=>{let r;return r=t||("u"<typeof fetch?(...t)=>e.A(611737).then(({default:e})=>e(...t)):fetch),(...e)=>r(...e)},eR=async(e,t,r)=>{await e.setItem(t,JSON.stringify(r))},eO=async(e,t)=>{let r=await e.getItem(t);if(!r)return null;try{return JSON.parse(r)}catch(e){return r}},eA=async(e,t)=>{await e.removeItem(t)};class ej{constructor(){this.promise=new ej.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}}function eM(e){let t=e.split(".");if(3!==t.length)throw Error("JWT is not valid: not a JWT structure");if(!/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}=?$|[a-z0-9_-]{2}(==)?$)$/i.test(t[1]))throw Error("JWT is not valid: payload is not in base64url format");return JSON.parse(function(e){let t,r,n,i,a,s,o,l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",u="",c=0;for(e=e.replace("-","+").replace("_","/");c<e.length;)i=l.indexOf(e.charAt(c++)),a=l.indexOf(e.charAt(c++)),s=l.indexOf(e.charAt(c++)),o=l.indexOf(e.charAt(c++)),t=i<<2|a>>4,r=(15&a)<<4|s>>2,n=(3&s)<<6|o,u+=String.fromCharCode(t),64!=s&&0!=r&&(u+=String.fromCharCode(r)),64!=o&&0!=n&&(u+=String.fromCharCode(n));return u}(t[1]))}async function ez(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function eF(e){return("0"+e.toString(16)).substr(-2)}async function eU(e){let t=new TextEncoder().encode(e);return Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",t))).map(e=>String.fromCharCode(e)).join("")}async function eL(e){return"u">typeof crypto&&void 0!==crypto.subtle&&"u">typeof TextEncoder?btoa(await eU(e)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,""):(console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),e)}async function eH(e,t,r=!1){let n=function(){let e=new Uint32Array(56);if("u"<typeof crypto){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",t=e.length,r="";for(let n=0;n<56;n++)r+=e.charAt(Math.floor(Math.random()*t));return r}return crypto.getRandomValues(e),Array.from(e,eF).join("")}(),i=n;r&&(i+="/PASSWORD_RECOVERY"),await eR(e,`${t}-code-verifier`,i);let a=await eL(n),s=n===a?"plain":"s256";return[a,s]}ej.promiseConstructor=Promise;let eB=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;class eV extends Error{constructor(e,t,r){super(e),this.__isAuthError=!0,this.name="AuthError",this.status=t,this.code=r}}function eq(e){return"object"==typeof e&&null!==e&&"__isAuthError"in e}class eG extends eV{constructor(e,t,r){super(e,t,r),this.name="AuthApiError",this.status=t,this.code=r}}class eK extends eV{constructor(e,t){super(e),this.name="AuthUnknownError",this.originalError=t}}class eJ extends eV{constructor(e,t,r,n){super(e,r,n),this.name=t,this.status=r}}class eW extends eJ{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}class eZ extends eJ{constructor(){super("Auth session or user missing","AuthInvalidToken
1ResponseError",500,void 0)}}class eQ extends eJ{constructor(e){super(e,"AuthInvalidCredentialsError",400,void 0)}}class eY extends eJ{constructor(e,t=null){super(e,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class eX extends eJ{constructor(e,t=null){super(e,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=t}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class e0 extends eJ{constructor(e,t){super(e,"AuthRetryableFetchError",t,void 0)}}function e1(e){return eq(e)&&"AuthRetryableFetchError"===e.name}class e2 extends eJ{constructor(e,t,r){super(e,"AuthWeakPasswordError",t,"weak_password"),this.reasons=r}}var e5=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)0>t.indexOf(n[i])&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r};let e3=e=>e.msg||e.message||e.error_description||e.error||JSON.stringify(e),e4=[502,503,504];async function e6(e){var t;let r,n;if(!("object"==typeof e&&null!==e&&"status"in e&&"ok"in e&&"json"in e&&"function"==typeof e.json))throw new e0(e3(e),0);if(e4.includes(e.status))throw new e0(e3(e),e.status);try{r=await e.json()}catch(e){throw new eK(e3(e),e)}let i=function(e){let t=e.headers.get(eE);if(!t||!t.match(eB))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch(e){return null}}(e);if(i&&i.getTime()>=eN["2024-01-01"].timestamp&&"object"==typeof r&&r&&"string"==typeof r.code?n=r.code:"object"==typeof r&&r&&"string"==typeof r.error_code&&(n=r.error_code),n){if("weak_password"===n)throw new e2(e3(r),e.status,(null==(t=r.weak_password)?void 0:t.reasons)||[])}else if("object"==typeof r&&r&&"object"==typeof r.weak_password&&r.weak_password&&Array.isArray(r.weak_password.reasons)&&r.weak_password.reasons.length&&r.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0))throw new e2(e3(r),e.status,r.weak_password.reasons);throw new eG(e3(r),e.status||500,n)}async function e9(e,t,r,n){var i;let a=Object.assign({},null==n?void 0:n.headers);a[eE]||(a[eE]=eN["2024-01-01"].name),(null==n?void 0:n.jwt)&&(a.Authorization=`Bearer ${n.jwt}`);let s=null!=(i=null==n?void 0:n.query)?i:{};(null==n?void 0:n.redirectTo)&&(s.redirect_to=n.redirectTo);let o=Object.keys(s).length?"?"+new URLSearchParams(s).toString():"",l=await e8(e,t,r+o,{headers:a,noResolveJson:null==n?void 0:n.noResolveJson},{},null==n?void 0:n.body);return(null==n?void 0:n.xform)?null==n?void 0:n.xform(l):{data:Object.assign({},l),error:null}}async function e8(e,t,r,n,i,a){let s,o,l=(o={method:t,headers:(null==n?void 0:n.headers)||{}},"GET"===t?o:(o.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},null==n?void 0:n.headers),o.body=JSON.stringify(a),Object.assign(Object.assign({},o),i)));try{s=await e(r,Object.assign({},l))}catch(e){throw console.error(e),new e0(e3(e),0)}if(s.ok||await e6(s),null==n?void 0:n.noResolveJson)return s;try{return await s.json()}catch(e){await e6(e)}}function e7(e){var t,r,n;let i=null;(n=e).access_token&&n.refresh_token&&n.expires_in&&(i=Object.assign({},e),e.expires_at||(i.expires_at=(r=e.expires_in,Math.round(Date.now()/1e3)+r)));return{data:{session:i,user:null!=(t=e.user)?t:e},error:null}}function te(e){let t=e7(e);return!t.error&&e.weak_password&&"object"==typeof e.weak_password&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&"string"==typeof e.weak_password.message&&e.weak_password.reasons.reduce((e,t)=>e&&"string"==typeof t,!0)&&(t.data.weak_password=e.weak_password),t}function tt(e){var t;return{data:{user:null!=(t=e.user)?t:e},error:null}}function tr(e){return{data:e,error:null}}function tn(e){let{action_link:t,email_otp:r,hashed_token:n,redirect_to:i,verification_type:a}=e;return{data:{properties:{action_link:t,email_otp:r,hashed_token:n,redirect_to:i,verification_type:a},user:Object.assign({},e5(e,["action_link","email_otp","hashed_token","redirect_to","verification_type"]))},error:null}}function ti(e){return e}var ta=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)0>t.indexOf(n[i])&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r};class ts{constructor({url:e="",headers:t={},fetch:r}){this.url=e,this.headers=t,this.fetch=eP(r),this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)}}async signOut(e,t="global"){try{return await e9(this.fetch,"POST",`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if(eq(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await e9(this.fetch,"POST",`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:tt})}catch(e){if(eq(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:t}=e,r=ta(e,["options"]),n=Object.assign(Object.assign({},r),t);return"newEmail"in r&&(n.new_email=null==r?void 0:r.newEmail,delete n.newEmail),await e9(this.fetch,"POST",`${this.url}/admin/generate_link`,{body:n,headers:this.headers,xform:tn,redirectTo:null==t?void 0:t.redirectTo})}catch(e){if(eq(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await e9(this.fetch,"POST",`${this.url}/admin/users`,{body:e,headers:this.headers,xform:tt})}catch(e){if(eq(e))return{data:{user:null},error:e};throw e}}async listUsers(e){var t,r,n,i,a,s,o;try{let l={nextPage:null,lastPage:0,total:0},u=await e9(this.fetch,"GET",`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:null!=(r=null==(t=null==e?void 0:e.page)?void 0:t.toString())?r:"",per_page:null!=(i=null==(n=null==e?void 0:e.perPage)?void 0:n.toString())?i:""},xform:ti});if(u.error)throw u.error;let c=await u.json(),h=null!=(a=u.headers.get("x-total-count"))?a:0,d=null!=(o=null==(s=u.headers.get("link"))?void 0:s.split(","))?o:[];return d.length>
10&&(d.forEach(e=>{let t=parseInt(e.split(";")[0].split("=")[1].substring(0,1)),r=JSON.parse(e.split(";")[1].split("=")[1]);l[`${r}Page`]=t}),l.total=parseInt(h)),{data:Object.assign(Object.assign({},c),l),error:null}}catch(e){if(eq(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){try{return await e9(this.fetch,"GET",`${this.url}/admin/users/${e}`,{headers:this.headers,xform:tt})}catch(e){if(eq(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){try{return await e9(this.fetch,"PUT",`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:tt})}catch(e){if(eq(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){try{return await e9(this.fetch,"DELETE",`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:tt})}catch(e){if(eq(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){try{let{data:t,error:r}=await e9(this.fetch,"GET",`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if(eq(e))return{data:null,error:e};throw e}}async _deleteFactor(e){try{return{data:await e9(this.fetch,"DELETE",`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if(eq(e))return{data:null,error:e};throw e}}}let to={getItem:e=>eC()?globalThis.localStorage.getItem(e):null,setItem:(e,t)=>{eC()&&globalThis.localStorage.setItem(e,t)},removeItem:e=>{eC()&&globalThis.localStorage.removeItem(e)}};function tl(e={}){return{getItem:t=>e[t]||null,setItem:(t,r)=>{e[t]=r},removeItem:t=>{delete e[t]}}}let tu={debug:!!(globalThis&&eC()&&globalThis.localStorage&&"true"===globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"))};class tc extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}}class th extends tc{}async function td(e,t,r){tu.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",e,t);let n=new globalThis.AbortController;return t>0&&setTimeout(()=>{n.abort(),tu.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",e)},t),await globalThis.navigator.locks.request(e,0===t?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:n.signal},async n=>{if(n){tu.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",e,n.name);try{return await r()}finally{tu.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",e,n.name)}}if(0===t)throw tu.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",e),new th(`Acquiring an exclusive Navigator LockManager lock "${e}" immediately failed`);if(tu.debug)try{let e=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(e,null," "))}catch(e){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",e)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await r()})}if("object"!=typeof globalThis)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch(e){"u">typeof self&&(self.globalThis=self)}let tp={url:"http://localhost:9999",storageKey:"supabase.auth.token",autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:eD,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function tf(e,t,r){return await r()}class tm{constructor(e){var t,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=tm.nextInstanceID,tm.nextInstanceID+=1,this.instanceID>0&&"u">typeof document&&console.warn("Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.");const n=Object.assign(Object.assign({},tp),e);if(this.logDebugMessages=!!n.debug,"function"==typeof n.debug&&(this.logger=n.debug),this.persistSession=n.persistSession,this.storageKey=n.storageKey,this.autoRefreshToken=n.autoRefreshToken,this.admin=new ts({url:n.url,headers:n.headers,fetch:n.fetch}),this.url=n.url,this.headers=n.headers,this.fetch=eP(n.fetch),this.lock=n.lock||tf,this.detectSessionInUrl=n.detectSessionInUrl,this.flowType=n.flowType,this.hasCustomAuthorizationHeader=n.hasCustomAuthorizationHeader,n.lock?this.lock=n.lock:"u">typeof document&&(null==(t=null==globalThis?void 0:globalThis.navigator)?void 0:t.locks)?this.lock=td:this.lock=tf,this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this)},this.persistSession?n.storage?this.storage=n.storage:eC()?this.storage=to:(this.memoryStorage={},this.storage=tl(this.memoryStorage)):(this.memoryStorage={},this.storage=tl(this.memoryStorage)),"u">typeof document&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",e)}null==(r=this.broadcastChannel)||r.addEventListener("message",async e=>{this._debug("received broadcast notification from other tab or client",e),await this._notifyAllSubscribers(e.data.event,e.data.session,!1)})}this.initialize()}_debug(...e){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${ex}) ${new Date().toISOString()}`,...e),this}async initialize(){return this.initializePromise||(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))()),await this.initializePromise}async _initialize(){try{let e="u">typeof document&&await this._isPKCEFlow();if(this._debug("#_initialize()","begin","is PKCE flow",e),e||this.detectSessionInUrl&&this._isImplicitGrantFlow()){let{data:t,error:r}=await this._getSessionFromURL(e);if(r){if(this._debug("#_initialize()","error detecting session from URL",r),(null==r?void 0:r.message)==="Identity is already linked"||(null==r?void 0:r.message)==="Identity is already linked to another user")return{error:r};return await this._removeSession(),{error:r}}let{session:n,redirectType:i}=t;return this._debug("#_initialize()","detected session in URL",n,"redirect type",i),await this._saveSession(n),setTimeout(async()=>{"recovery"===i?await this._notifyAllSubscribers("PASSWORD_RECOVERY",n):await this._notifyAllSubscribers("SIGNED_IN",n)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){if(eq(e))return{error:e};return{error:new eK("Unexpected error during initialization",e)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(e){var t,r,n;try{await this._removeSession();let{data:i,error:a}=await e9(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:null!=(r=null==(t=null==e?void 0:e.options)?void 0:t.data)?r:{},gotrue_meta_security:{captcha_token:null==(n=null==e?void 0:e.options)?void 0:n.captchaToken}},xform:e7});if(a||!i)return{data:{user:null,session:null},error:a};let s=i.session,o=i.user;return i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",s)),{data:{user:o,session:s},error:null}}catch(e){if(eq(e))return{data:{user:null,session:null},error:e};throw e}}async signUp(e){var t,r,n;try{let i;if(await this._removeSession(),"email"in e){let{email:r,password:n,options:a}=e,s=null,o=null;"pkce"===this.flowType&&([s,o]=await eH(this.storage,this.storageKey)),i=await e9(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:null==a?void 0:a.emailRedirectTo,body:{email:r,password:n,data:null!=(t=null==a?void 0:a.data)?t:{},gotrue_meta_security:{captcha_token:null==a?void 0:a.captchaToken},code_challenge:s,code_challenge_method:o},xform:e7})}else if("phone"in e){let{phone:t,password:a,options:s}=e;i=await e9(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:a,data:null!=(r=null==s?void 0:s.data)?r:{},channel:null!=(n=null==s?void 0:s.channel)?n:"sms",gotrue_meta_security:{captcha_token:null==s?void 0:s.captchaToken}},xform:e7})}else throw new eQ("You must provide either an email or phone number and a password");let{data:a,error:s}=i;if(s||!a)return{data:{user:null,session:null},error:s};let o=a.session,l=a.user;return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers("SIGNED_IN",o)),{data:{user:l,session:o},error:null}}catch(e){if(eq(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithPassword(e){try{let t;if(await this._removeSession(),"email"in e){let{email:r,password:n,options:i}=e;t=await e9(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:r,password:n,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:te})}else if("phone"in e){let{phone:r,password:n,options:i}=e;t=await e9(this.fetch,"POST",`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:r,password:n,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},xform:te})}else throw new eQ("You must provide either an email or phone number and a password");let{data:r,error:n}=t;if(n)return{data:{user:null,session:null},error:n};if(!r||!r.session||!r.user)return{data:{user:null,session:null},error:new eZ};return r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:n}}catch(e){if(eq(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOAuth(e){var t,r,n,i;return await this._removeSession(),await this._handleProviderSignIn(e.provider,{redirectTo:null==(t=e.options)?void 0:t.redirectTo,scopes:null==(r=e.options)?void 0:r.scopes,queryParams:null==(n=e.options)?void 0:n.queryParams,skipBrowserRedirect:null==(i=e.options)?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(e){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(e))}async _exchangeCodeForSession(e){let t=await eO(this.storage,`${this.storageKey}-code-verifier`),[r,n]=(null!=t?t:"").split("/"),{data:i,error:a}=await e9(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:r},xform:e7});return(await eA(this.storage,`${this.storageKey}-code-verifier`),a)?{data:{user:null,session:null,redirectType:null},error:a}:i&&i.session&&i.user?(i.session&&(await this._saveSession(i.session),await this._notifyAllSubscribers("SIGNED_IN",i.session)),{data:Object.assign(Object.assign({},i),{redirectType:null!=n?n:null}),error:a}):{data:{user:null,session:null,redirectType:null},error:new eZ}}async signInWithIdToken(e){await this._removeSession();try{let{options:t,provider:r,token:n,access_token:i,nonce:a}=e,{data:s,error:o}=await e9(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:n,access_token:i,nonce:a,gotrue_meta_security:{captcha_token:null==t?void 0:t.captchaToken}},xform:e7});if(o)return{data:{user:null,session:null},error:o};if(!s||!s.session||!s.user)return{data:{user:null,session:null},error:new eZ};return s.session&&(await this._saveSession(s.session),await this._notifyAllSubscribers("SIGNED_IN",s.session)),{data:s,error:o}}catch(e){if(eq(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithOtp(e){var t,r,n,i,a;try{if(await this._removeSession(),"email"in e){let{email:n,options:i}=e,a=null,s=null;"pkce"===this.flowType&&([a,s]=await eH(this.storage,this.storageKey));let{error:o}=await e9(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:n,data:null!=(t=null==i?void 0:i.data)?t:{},create_user:null==(r=null==i?void 0:i.shouldCreateUser)||r,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken},code_challenge:a,code_challenge_method:s},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:o}}if("phone"in e){let{phone:t,options:r}=e,{data:s,error:o}=await e9(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:null!=(n=null==r?void 0:r.data)?n:{},create_user:null==(i=null==r?void 0:r.shouldCreateUser)||i,gotrue_meta_security:{captcha_token:null==r?void 0:r.captchaToken},channel:null!=(a=null==r?void 0:r.channel)?a:"sms"}});return{data:{user:null,session:null,messageId:null==s?void 0:s.message_id},error:o}}throw new eQ("You must provide either an email or phone number.")}catch(e){if(eq(e))return{data:{user:null,session:null},error:e};throw e}}async verifyOtp(e){var t,r;try{let n,i;"email_change"!==e.type&&"phone_change"!==e.type&&await this._removeSession(),"options"in e&&(n=null==(t=e.options)?void 0:t.redirectTo,i=null==(r=e.options)?void 0:r.captchaToken);let{data:a,error:s}=await e9(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:i}}),redirectTo:n,xform:e7});if(s)throw s;if(!a)throw Error("An error occurred on token verification.");let o=a.session,l=a.user;return(null==o?void 0:o.access_token)&&(await this._saveSession(o),await this._notifyAllSubscribers("recovery"==e.type?"PASSWORD_RECOVERY":"SIGNED_IN",o)),{data:{user:l,session:o},error:null}}catch(e){if(eq(e))return{data:{user:null,session:null},error:e};throw e}}async signInWithSSO(e){var t,r,n;try{await this._removeSession();let i=null,a=null;return"pkce"===this.flowType&&([i,a]=await eH(this.storage,this.storageKey)),await e9(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in e?{provider_id:e.providerId}:null),"domain"in e?{domain:e.domain}:null),{redirect_to:null!=(r=null==(t=e.options)?void 0:t.redirectTo)?r:void 0}),(null==(n=null==e?void 0:e.options)?void 0:n.captchaToken)?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:a}),headers:this.headers,xform:tr})}catch(e){if(eq(e))return{data:null,error:e};throw e}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:r}=e;if(r)throw r;if(!t)throw new eW;let{error:n}=await e9(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return{data:{user:null,session:null},error:n}})}catch(e){if(eq(e))return{data:{user:null,session:null},error:e};throw e}}async resend(e){try{"email_change"!=e.type&&"phone_change"!=e.type&&await this._removeSession();let t=`${this.url}/resend`;if("email"in e){let{email:r,type:n,options:i}=e,{error:a}=await e9(this.fetch,"POST",t,{headers:this.headers,body:{email:r,type:n,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}},redirectTo:null==i?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:a}}if("phone"in e){let{phone:r,type:n,options:i}=e,{data:a,error:s}=await e9(this.fetch,"POST",t,{headers:this.headers,body:{phone:r,type:n,gotrue_meta_security:{captcha_token:null==i?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:null==a?void 0:a.message_id},error:s}}throw new eQ("You must provide either an email or phone number and a type")}catch(e){if(eq(e))return{data:{user:null,session:null},error:e};throw e}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug("#_a
1cquireLock","begin",e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),r=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await r}catch(e){}})()),r}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch(e){}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(e){this._debug("#_useSession","begin");try{let t=await this.__loadSession();return await e(t)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",Error().stack);try{let e=null,t=await eO(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",t),null!==t&&(this._isValidSession(t)?e=t:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!e)return{data:{session:null},error:null};let r=!!e.expires_at&&e.expires_at<=Date.now()/1e3;if(this._debug("#__loadSession()",`session has${r?"":" not"} expired`,"expires_at",e.expires_at),!r){if(this.storage.isServer){let t=this.suppressGetSessionWarning;e=new Proxy(e,{get:(e,r,n)=>(t||"user"!==r||console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and many not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),Reflect.get(e,r,n))})}return{data:{session:e},error:null}}let{session:n,error:i}=await this._callRefreshToken(e.refresh_token);if(i)return{data:{session:null},error:i};return{data:{session:n},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(e){return e?await this._getUser(e):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(e){try{if(e)return await e9(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:e,xform:tt});return await this._useSession(async e=>{var t,r,n;let{data:i,error:a}=e;if(a)throw a;return(null==(t=i.session)?void 0:t.access_token)||this.hasCustomAuthorizationHeader?await e9(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:null!=(n=null==(r=i.session)?void 0:r.access_token)?n:void 0,xform:tt}):{data:{user:null},error:new eW}})}catch(e){if(eq(e))return{data:{user:null},error:e};throw e}}async updateUser(e,t={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){try{return await this._useSession(async r=>{let{data:n,error:i}=r;if(i)throw i;if(!n.session)throw new eW;let a=n.session,s=null,o=null;"pkce"===this.flowType&&null!=e.email&&([s,o]=await eH(this.storage,this.storageKey));let{data:l,error:u}=await e9(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:null==t?void 0:t.emailRedirectTo,body:Object.assign(Object.assign({},e),{code_challenge:s,code_challenge_method:o}),jwt:a.access_token,xform:tt});if(u)throw u;return a.user=l.user,await this._saveSession(a),await this._notifyAllSubscribers("USER_UPDATED",a),{data:{user:a.user},error:null}})}catch(e){if(eq(e))return{data:{user:null},error:e};throw e}}_decodeJWT(e){return eM(e)}async setSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new eW;let t=Date.now()/1e3,r=t,n=!0,i=null,a=eM(e.access_token);if(a.exp&&(n=(r=a.exp)<=t),n){let{session:t,error:r}=await this._callRefreshToken(e.refresh_token);if(r)return{data:{user:null,session:null},error:r};
1if(!t)return{data:{user:null,session:null},error:null};i=t}else{let{data:n,error:a}=await this._getUser(e.access_token);if(a)throw a;i={access_token:e.access_token,refresh_token:e.refresh_token,user:n.user,token_type:"bearer",expires_in:r-t,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(e){if(eq(e))return{data:{session:null,user:null},error:e};throw e}}async refreshSession(e){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{var r;if(!e){let{data:n,error:i}=t;if(i)throw i;e=null!=(r=n.session)?r:void 0}if(!(null==e?void 0:e.refresh_token))throw new eW;let{session:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?{data:{user:null,session:null},error:i}:n?{data:{user:n.user,session:n},error:null}:{data:{user:null,session:null},error:null}})}catch(e){if(eq(e))return{data:{user:null,session:null},error:e};throw e}}async _getSessionFromURL(e){try{if(!("u">typeof document))throw new eY("No browser detected.");if("implicit"!==this.flowType||this._isImplicitGrantFlow()){if("pkce"==this.flowType&&!e)throw new eX("Not a valid PKCE flow url.")}else throw new eY("Not a valid implicit grant flow url.");let t=eT(window.location.href);if(e){if(!t.code)throw new eX("No code detected.");let{data:e,error:r}=await this._exchangeCodeForSession(t.code);if(r)throw r;let n=new URL(window.location.href);return n.searchParams.delete("code"),window.history.replaceState(window.history.state,"",n.toString()),{data:{session:e.session,redirectType:null},error:null}}if(t.error||t.error_description||t.error_code)throw new eY(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});let{provider_token:r,provider_refresh_token:n,access_token:i,refresh_token:a,expires_in:s,expires_at:o,token_type:l}=t;if(!i||!s||!a||!l)throw new eY("No session defined in URL");let u=Math.round(Date.now()/1e3),c=parseInt(s),h=u+c;o&&(h=parseInt(o));let d=h-u;1e3*d<=3e4&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${d}s, should have been closer to ${c}s`);let p=h-c;u-p>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",p,h,u):u-p<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clok for skew",p,h,u);let{data:f,error:m}=await this._getUser(i);if(m)throw m;let g={provider_token:r,provider_refresh_token:n,access_token:i,expires_in:c,expires_at:h,refresh_token:a,token_type:l,user:f.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:g,redirectType:t.type},error:null}}catch(e){if(eq(e))return{data:{session:null,redirectType:null},error:e};throw e}}_isImplicitGrantFlow(){let e=eT(window.location.href);return!!("u">typeof document&&(e.access_token||e.error_description))}async _isPKCEFlow(){let e=eT(window.location.href),t=await eO(this.storage,`${this.storageKey}-code-verifier`);return!!(e.code&&t)}async signOut(e={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:"global"}){return await this._useSession(async t=>{var r;let{data:n,error:i}=t;if(i)return{error:i};let a=null==(r=n.session)?void 0:r.access_token;if(a){let{error:t}=await this.admin.signOut(a,e);if(t&&!(eq(t)&&"AuthApiError"===t.name&&(404===t.status||401===t.status||403===t.status)))return{error:t}}return"others"!==e&&(await this._removeSession(),await eA(this.storage,`${this.storageKey}-code-verifier`),await this._notifyAllSubscribers("SIGNED_OUT",null)),{error:null}})}onAuthStateChange(e){let t="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){let t=16*Math.random()|0;return("x"==e?t:3&t|8).toString(16)}),r={id:t,callback:e,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",t),this.stateChangeEmitters.delete(t)}};return this._debug("#onAuthStateChange()","registered callback with id",t),this.stateChangeEmitters.set(t,r),(async()=>{await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:r}}}async _emitInitialSession(e){return await this._useSession(async t=>{var r,n;try{let{data:{session:n},error:i}=t;if(i)throw i;await (null==(r=this.stateChangeEmitters.get(e))?void 0:r.callback("INITIAL_SESSION",n)),this._debug("INITIAL_SESSION","callback id",e,"session",n)}catch(t){await (null==(n=this.stateChangeEmitters.get(e))?void 0:n.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",e,"error",t),console.error(t)}})}async resetPasswordForEmail(e,t={}){let r=null,n=null;"pkce"===this.flowType&&([r,n]=await eH(this.storage,this.storageKey,!0));try{return await e9(this.fetch,"POST",`${this.url}/recover`,{body:{email:e,code_challenge:r,code_challenge_method:n,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:t.redirectTo})}catch(e){if(eq(e))return{data:null,error:e};throw e}}async getUserIdentities(){var e;try{let{data:t,error:r}=await this.getUser();if(r)throw r;return{data:{identities:null!=(e=t.user.identities)?e:[]},error:null}}catch(e){if(eq(e))return{data:null,error:e};throw e}}async linkIdentity(e){var t;try{let{data:r,error:n}=await this._useSession(async t=>{var r,n,i,a,s;let{data:o,error:l}=t;if(l)throw l;let u=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:null==(r=e.options)?void 0:r.redirectTo,scopes:null==(n=e.options)?void 0:n.scopes,queryParams:null==(i=e.options)?void 0:i.queryParams,skipBrowserRedirect:!0});return await e9(this.fetch,"GET",u,{headers:this.headers,jwt:null!=(s=null==(a=o.session)?void 0:a.access_token)?s:void 0})});if(n)throw n;return!("u">typeof document)||(null==(t=e.options)?void 0:t.skipBrowserRedirect)||window.location.assign(null==r?void 0:r.url),{data:{provider:e.provider,url:null==r?void 0:r.url},error:null}}catch(t){if(eq(t))return{data:{provider:e.provider,url:null},error:t};throw t}}async unlinkIdentity(e){try{return await this._useSession(async t=>{var r,n;let{data:i,error:a}=t;if(a)throw a;
1return await e9(this.fetch,"DELETE",`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:null!=(n=null==(r=i.session)?void 0:r.access_token)?n:void 0})})}catch(e){if(eq(e))return{data:null,error:e};throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken(${e.substring(0,5)}...)`;this._debug(t,"begin");try{var r,n;let i=Date.now();return await (r=async r=>(r>0&&await ez(200*Math.pow(2,r-1)),this._debug(t,"refreshing attempt",r),await e9(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:e7})),n=(e,t)=>{let r=200*Math.pow(2,e);return t&&e1(t)&&Date.now()+r-i<3e4},new Promise((e,t)=>{(async()=>{for(let i=0;i<1/0;i++)try{let t=await r(i);if(!n(i,null))return void e(t)}catch(e){if(!n(i,e))return void t(e)}})()}))}catch(e){if(this._debug(t,"error",e),eq(e))return{data:{session:null,user:null},error:e};throw e}finally{this._debug(t,"end")}}_isValidSession(e){return"object"==typeof e&&null!==e&&"access_token"in e&&"refresh_token"in e&&"expires_at"in e}async _handleProviderSignIn(e,t){let r=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug("#_handleProviderSignIn()","provider",e,"options",t,"url",r),"u">typeof document&&!t.skipBrowserRedirect&&window.location.assign(r),{data:{provider:e,url:r},error:null}}async _recoverAndRefresh(){var e;let t="#_recoverAndRefresh()";this._debug(t,"begin");try{let r=await eO(this.storage,this.storageKey);if(this._debug(t,"session from storage",r),!this._isValidSession(r)){this._debug(t,"session is not valid"),null!==r&&await this._removeSession();return}let n=Math.round(Date.now()/1e3),i=(null!=(e=r.expires_at)?e:1/0)<n+10;if(this._debug(t,`session has${i?"":" not"} expired with margin of 10s`),i){if(this.autoRefreshToken&&r.refresh_token){let{error:e}=await this._callRefreshToken(r.refresh_token);e&&(console.error(e),e1(e)||(this._debug(t,"refresh failed with a non-retryable error, removing the session",e),await this._removeSession()))}}else await this._notifyAllSubscribers("SIGNED_IN",r)}catch(e){this._debug(t,"error",e),console.error(e);return}finally{this._debug(t,"end")}}async _callRefreshToken(e){var t,r;if(!e)throw new eW;if(this.refreshingDeferred)return this.refreshingDeferred.promise;let n=`#_callRefreshToken(${e.substring(0,5)}...)`;this._debug(n,"begin");try{this.refreshingDeferred=new ej;let{data:t,error:r}=await this._refreshAccessToken(e);if(r)throw r;if(!t.session)throw new eW;await this._saveSession(t.session),await this._notifyAllSubscribers("TOKEN_REFRESHED",t.session);let n={session:t.session,error:null};return this.refreshingDeferred.resolve(n),n}catch(e){if(this._debug(n,"error",e),eq(e)){let r={session:null,error:e};return e1(e)||(await this._removeSession(),await this._notifyAllSubscribers("SIGNED_OUT",null)),null==(t=this.refreshingDeferred)||t.resolve(r),r}throw null==(r=this.refreshingDeferred)||r.reject(e),e}finally{this.refreshingDeferred=null,this._debug(n,"end")}}async _notifyAllSubscribers(e,t,r=!0){let n=`#_notifyAllSubscribers(${e})`;this._debug(n,"begin",t,`broadcast = ${r}`);try{this.broadcastChannel&&r&&this.broadcastChannel.postMessage({event:e,session:t});let n=[],i=Array.from(this.stateChangeEmitters.values()).map(async r=>{try{await r.callback(e,t)}catch(e){n.push(e)}});if(await Promise.all(i),n.length>0){for(let e=0;e<n.length;e+=1)console.error(n[e]);throw n[0]}}finally{this._debug(n,"end")}}async _saveSession(e){this._debug("#_saveSession()",e),this.suppressGetSessionWarning=!0,await eR(this.storage,this.storageKey,e)}async _removeSession(){this._debug("#_removeSession()"),await eA(this.storage,this.storageKey)}_removeVisibilityChangedCallback(){this._debug("#_removeVisibilityChangedCallback()");let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&"u">typeof document&&(null==window?void 0:window.removeEventListener)&&window.removeEventListener("visibilitychange",e)}catch(e){console.error("removing visibilitychange callback failed",e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug("#_startAutoRefresh()");let e=setInterval(()=>this._autoRefreshTokenTick(),3e4);this.autoRefreshTicker=e,e&&"object"==typeof e&&"function"==typeof e.unref?e.unref():"u">typeof Deno&&"function"==typeof Deno.unrefTimer&&Deno.unrefTimer(e),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at)return void this._debug("#_autoRefreshTokenTick()","no session");let n=Math.floor((1e3*r.expires_at-e)/3e4);this._debug("#_autoRefreshTokenTick()",`access token expires in ${n} ticks, a tick lasts 30000ms, refresh threshold is 3 ticks`),n<=3&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error("Auto refresh tick failed with error. This is likely a transient error.",e)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(e){if(e.isAcquireTimeout||e instanceof tc)this._debug("auto refresh token tick lock not available");else throw e}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!("u">typeof document)||!(null==window?void 0:window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),null==window||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error("_handleVisibilityChange",e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;this._debug(t,"visibilityState",document.visibilityState),"visible"===document.visibilityState?(this.autoRefreshToken&&this._startAutoRefresh(),e||(
1await this.initializePromise,await this._acquireLock(-1,async()=>{"visible"!==document.visibilityState?this._debug(t,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting"):await this._recoverAndRefresh()}))):"hidden"===document.visibilityState&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,r){let n=[`provider=${encodeURIComponent(t)}`];if((null==r?void 0:r.redirectTo)&&n.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),(null==r?void 0:r.scopes)&&n.push(`scopes=${encodeURIComponent(r.scopes)}`),"pkce"===this.flowType){let[e,t]=await eH(this.storage,this.storageKey),r=new URLSearchParams({code_challenge:`${encodeURIComponent(e)}`,code_challenge_method:`${encodeURIComponent(t)}`});n.push(r.toString())}if(null==r?void 0:r.queryParams){let e=new URLSearchParams(r.queryParams);n.push(e.toString())}return(null==r?void 0:r.skipBrowserRedirect)&&n.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${e}?${n.join("&")}`}async _unenroll(e){try{return await this._useSession(async t=>{var r;let{data:n,error:i}=t;return i?{data:null,error:i}:await e9(this.fetch,"DELETE",`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:null==(r=null==n?void 0:n.session)?void 0:r.access_token})})}catch(e){if(eq(e))return{data:null,error:e};throw e}}async _enroll(e){try{return await this._useSession(async t=>{var r,n;let{data:i,error:a}=t;if(a)return{data:null,error:a};let{data:s,error:o}=await e9(this.fetch,"POST",`${this.url}/factors`,{body:{friendly_name:e.friendlyName,factor_type:e.factorType,issuer:e.issuer},headers:this.headers,jwt:null==(r=null==i?void 0:i.session)?void 0:r.access_token});return o?{data:null,error:o}:((null==(n=null==s?void 0:s.totp)?void 0:n.qr_code)&&(s.totp.qr_code=`data:image/svg+xml;utf-8,${s.totp.qr_code}`),{data:s,error:null})})}catch(e){if(eq(e))return{data:null,error:e};throw e}}async _verify(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:n,error:i}=t;if(i)return{data:null,error:i};let{data:a,error:s}=await e9(this.fetch,"POST",`${this.url}/factors/${e.factorId}/verify`,{body:{code:e.code,challenge_id:e.challengeId},headers:this.headers,jwt:null==(r=null==n?void 0:n.session)?void 0:r.access_token});return s?{data:null,error:s}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+a.expires_in},a)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",a),{data:a,error:s})})}catch(e){if(eq(e))return{data:null,error:e};throw e}})}async _challenge(e){return this._acquireLock(-1,async()=>{try{return await this._useSession(async t=>{var r;let{data:n,error:i}=t;return i?{data:null,error:i}:await e9(this.fetch,"POST",`${this.url}/factors/${e.factorId}/challenge`,{headers:this.headers,jwt:null==(r=null==n?void 0:n.session)?void 0:r.access_token})})}catch(e){if(eq(e))return{data:null,error:e};throw e}})}async _challengeAndVerify(e){let{data:t,error:r}=await this._challenge({factorId:e.factorId});return r?{data:null,error:r}:await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let r=(null==e?void 0:e.factors)||[],n=r.filter(e=>"totp"===e.factor_type&&"verified"===e.status);return{data:{all:r,totp:n},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async e=>{var t,r;let{data:{session:n},error:i}=e;if(i)return{data:null,error:i};if(!n)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let a=this._decodeJWT(n.access_token),s=null;a.aal&&(s=a.aal);let o=s;return(null!=(r=null==(t=n.user.factors)?void 0:t.filter(e=>"verified"===e.status))?r:[]).length>0&&(o="aal2"),{data:{currentLevel:s,nextLevel:o,currentAuthenticationMethods:a.amr||[]},error:null}}))}}tm.nextInstanceID=0;let tg=tm;class ty extends tg{constructor(e){super(e)}}class tb{constructor(e,t,r){var n,i,a;if(this.supabaseUrl=e,this.supabaseKey=t,!e)throw Error("supabaseUrl is required.");
1if(!t)throw Error("supabaseKey is required.");const s=function(e){return e.replace(/\/$/,"")}(e);this.realtimeUrl=`${s}/realtime/v1`.replace(/^http/i,"ws"),this.authUrl=`${s}/auth/v1`,this.storageUrl=`${s}/storage/v1`,this.functionsUrl=`${s}/functions/v1`;const o=`sb-${new URL(this.authUrl).hostname.split(".")[0]}-auth-token`,l=function(e,t){let{db:r,auth:n,realtime:i,global:a}=e,{db:s,auth:o,realtime:l,global:u}=t;return{db:Object.assign(Object.assign({},s),r),auth:Object.assign(Object.assign({},o),n),realtime:Object.assign(Object.assign({},l),i),global:Object.assign(Object.assign({},u),a)}}(null!=r?r:{},{db:ek,realtime:eI,auth:Object.assign(Object.assign({},eS),{storageKey:o}),global:e_});this.storageKey=null!=(n=l.auth.storageKey)?n:"",this.headers=null!=(i=l.global.headers)?i:{},this.auth=this._initSupabaseAuthClient(null!=(a=l.auth)?a:{},this.headers,l.global.fetch),this.fetch=((e,t,r)=>{let n,i=(n=r||("u"<typeof fetch?N.default:fetch),(...e)=>n(...e)),a="u"<typeof Headers?N.Headers:Headers;return(r,n)=>{var s,o,l,u;return s=void 0,o=void 0,l=void 0,u=function*(){var s;let o=null!=(s=yield t())?s:e,l=new a(null==n?void 0:n.headers);return l.has("apikey")||l.set("apikey",e),l.has("Authorization")||l.set("Authorization",`Bearer ${o}`),i(r,Object.assign(Object.assign({},n),{headers:l}))},new(l||(l=Promise))(function(e,t){function r(e){try{i(u.next(e))}catch(e){t(e)}}function n(e){try{i(u.throw(e))}catch(e){t(e)}}function i(t){var i;t.done?e(t.value):((i=t.value)instanceof l?i:new l(function(e){e(i)})).then(r,n)}i((u=u.apply(s,o||[])).next())})}})(t,this._getAccessToken.bind(this),l.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers},l.realtime)),this.rest=new A(`${s}/rest/v1`,{headers:this.headers,schema:l.db.schema,fetch:this.fetch}),this._listenForAuthEvents()}get functions(){return new a(this.functionsUrl,{headers:this.headers,customFetch:this.fetch})}get storage(){return new ew(this.storageUrl,this.headers,this.fetch)}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}rpc(e,t={},r={}){return this.rest.rpc(e,t,r)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var e,t,r,n,i,a;return r=this,n=void 0,i=void 0,a=function*(){let{data:r}=yield this.auth.getSession();return null!=(t=null==(e=r.session)?void 0:e.access_token)?t:null},new(i||(i=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):((r=t.value)instanceof i?r:new i(function(e){e(r)})).then(s,o)}l((a=a.apply(r,n||[])).next())})}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,storageKey:i,flowType:a,debug:s},o,l){var u;let c={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new ty({url:this.authUrl,headers:Object.assign(Object.assign({},c),o),storageKey:i,autoRefreshToken:e,persistSession:t,detectSessionInUrl:r,storage:n,flowType:a,debug:s,fetch:l,hasCustomAuthorizationHeader:((u="Authorization"in this.headers,true),u)})}_initRealtimeClient(e){return new X(this.realtimeUrl,Object.assign(Object.assign({},e),{params:Object.assign({apikey:this.supabaseKey},null==e?void 0:e.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,"CLIENT",null==t?void 0:t.access_token)})}_handleTokenChanged(e,t,r){("TOKEN_REFRESHED"===e||"SIGNED_IN"===e)&&this.changedAccessToken!==r?(this.realtime.setAuth(null!=r?r:null),this.changedAccessToken=r):"SIGNED_OUT"===e&&(this.realtime.setAuth(this.supabaseKey),"STORAGE"==t&&this.auth.signOut(),this.changedAccessToken=void 0)}}let tw=(e,t,r)=>new tb(e,t,r);function tv(e){return null!=e&&"object"==typeof e&&!0===e["@@functional/placeholder"]}function t_(e){return function t(r){return 0==arguments.length||tv(r)?t:e.apply(this,arguments)}}function tk(e){return function t(r,n){switch(arguments.length){case 0:return t;case 1:return tv(r)?t:t_(function(t){return e(r,t)});default:return tv(r)&&tv(n)?t:tv(r)?t_(function(t){return e(t,n)}):tv(n)?t_(function(t){return e(r,t)}):e(r,n)}}}function tS(e){return function t(r,n,i){switch(arguments.length){case 0:return t;case 1:return tv(r)?t:tk(function(t,n){return e(r,t,n)});case 2:return tv(r)&&tv(n)?t:tv(r)?tk(function(t,r){return e(t,n,r)}):tv(n)?tk(function(t,n){return e(r,t,n)}):t_(function(t){return e(r,n,t)});default:return tv(r)&&tv(n)&&tv(i)?t:tv(r)&&tv(n)?tk(function(t,r){return e(t,r,i)}):tv(r)&&tv(i)?tk(function(t,r){return e(t,n,r)}):tv(n)&&tv(i)?tk(function(t,n){return e(r,t,n)}):tv(r)?t_(function(t){return e(t,n,i)}):tv(n)?t_(function(t){return e(r,t,i)}):tv(i)?t_(function(t){return e(r,n,t)}):e(r,n,i)}}}function tI(e){return"[object Object]"===Object.prototype.toString.call(e)}function tx(e,t){return Object.prototype.hasOwnProperty.call(t,e)}var tD=tS(function(e,t,r){var n,i={};for(n in r=r||{},t=t||{})tx(n,t)&&(i[n]=tx(n,r)?e(n,t[n],r[n]):t[n]);for(n in r)tx(n,r)&&!tx(n,i)&&(i[n]=r[n]);return i}),tE=tS(function e(t,r,n){return tD(function(r,n,i){return tI(n)&&tI(i)?e(t,n,i):t(r,n,i)},r,n)}),tN=tk(function(e,t){return tE(function(e,t,r){return r},e,t)}),t$=e.i(462819);function tC(){return"u">typeof window&&void 0!==window.document}var tT={path:"/",sameSite:"lax",httpOnly:!1,maxAge:31536e6};async function tP(e,t){let r=await t(e);if(r)return r;let n=[];for(let r=0;;r++){let i=`${e}.${r}`,a=await t(i);if(!a)break;n.push(a)}if(n.length>0)return n.join("")}async function tR(e,t,r){if(await t(e))return void await r(e);for(let n=0;;n++){let i=`${e}.${n}`;if(!await t(i))break;await r(i)}}e.s(["supabaseBrowserClient",0,function(){return function(e,t){let r,n;if(!e||!t)throw Error(`Your project's URL and Key are required to create a Supabase client! 2 3Check your Supabase project's API settings to find these values 4 5https://supabase.com/dashboard/project/_/settings/api`);let i={};(null==r?void 0:r.name)&&(n.auth={...n.auth,storageKey:r.name});let a=tN({global:{headers:{"X-Client-Info":"supabase-ssr/0.3.0"}},auth:{flowType:"pkce",autoRefreshToken:tC(),detectSessionInUrl:tC(),persistSession:!0,storage:{isServer:!1,getItem:async e=>await tP(e,async e=>"function"==typeof i.get?await i.get(e):tC()?(0,t$.parse)(document.cookie)[e]:void 0),setItem:async(e,t)=>{let n=await function(e,t){let r=(void 0)??3180,n=encodeURIComponent(t);if(n.length<=r)return[{name:e,value:t}];let i=[];for(;n.length>0;){let e=n.slice(0,r),t=e.lastIndexOf("%");t>r-3&&(e=e.slice(0,t));let a="";for(;e.length>0;)try{a=decodeURIComponent(e);break}catch(t){if(t instanceof URIError&&"%"===e.at(-3)&&e.length>3)e=e.slice(0,e.length-3);else throw t}i.push(a),n=n.slice(e.length)}return i.map((t,r)=>({name:`${e}.${r}`,value:t}))}(e,t);await Promise.all(n.map(async e=>{"function"==typeof i.set?await i.set(e.name,e.value,{...tT,...r,maxAge:tT.maxAge}):tC()&&(document.cookie=(0,t$.serialize)(e.name,e.value,{...tT,...r,maxAge:tT.maxAge}))}))},removeItem:async e=>{"function"==typeof i.remove&&"function"!=typeof i.get?console.log("Removing chunked cookie without a `get` method is not supported.\n\n When you call the `createBrowserClient` function from the `@supabase/ssr` package, make sure you declare both a `get` and `remove` method on the `cookies` object.\n\nhttps://supabase.com/docs/guides/auth/server-side/creating-a-client"):await tR(e,async e=>"function"==typeof i.get?await i.get(e):tC()?(0,t$.parse)(document.cookie)[e]:void 0,async e=>{"function"==typeof i.remove?await i.remove(e,{...tT,...r,maxAge:0}
5):tC()&&(document.cookie=(0,t$.serialize)(e,"",{...tT,...r,maxAge:0}))})}}}},n);1;{let r=tC();if(r&&b)return b;let n=tw(e,t,a);return r&&(b=n),n}}("https://bdefzwcumgzjwllsnaej.supabase.co","eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImJkZWZ6d2N1bWd6andsbHNuYWVqIiwicm9sZSI6ImFub24iLCJpYXQiOjE3MTU3MjcwMDAsImV4cCI6MjAzMTMwMzAwMH0.8F7O5jLCRPOrWYRIqf6B0-Tl2JAt_sGSPH_9rhfujgM")}],738954)},72545,e=>{"use strict";var t=e.i(883300);e.s(["mutate",()=>t.j])},283599,883300,646192,271235,84770,91696,947671,541281,538912,696996,233391,606368,e=>{"use strict";var t,r=e.i(271645),n=e.i(802239);e.s(["ERROR_REVALIDATE_EVENT",0,3,"FOCUS_EVENT",0,0,"MUTATE_EVENT",0,2,"RECONNECT_EVENT",0,1],211671);var i=Object.prototype.hasOwnProperty;let a=new WeakMap,s=()=>{},o=s(),l=Object,u=e=>e===o,c=e=>"function"==typeof e,h=(e,t)=>({...e,...t}),d=e=>c(e.then),p={},f={},m="undefined",g=typeof window!=m,y=typeof document!=m,b=g&&"Deno"in window,w=(e,t)=>{let r=a.get(e);return[()=>!u(t)&&e.get(t)||p,n=>{if(!u(t)){let i=e.get(t);t in f||(f[t]=i),r[5](t,h(i,n),i||p)}},r[6],()=>!u(t)&&t in f?f[t]:!u(t)&&e.get(t)||p]},v=!0,[_,k]=g&&window.addEventListener?[window.addEventListener.bind(window),window.removeEventListener.bind(window)]:[s,s],S={initFocus:e=>(y&&document.addEventListener("visibilitychange",e),_("focus",e),()=>{y&&document.removeEventListener("visibilitychange",e),k("focus",e)}),initReconnect:e=>{let t=()=>{v=!0,e()},r=()=>{v=!1};return _("online",t),_("offline",r),()=>{k("online",t),k("offline",r)}}},I=!r.default.useId,x=!g||b,D=e=>g&&typeof window.requestAnimationFrame!=m?window.requestAnimationFrame(e):setTimeout(e,1),E=x?r.useEffect:r.useLayoutEffect,N="u">typeof navigator&&navigator.connection,$=!x&&N&&(["slow-2g","2g"].includes(N.effectiveType)||N.saveData),C=new WeakMap,T=(e,t)=>l.prototype.toString.call(e)===`[object ${t}]`,P=0,R=e=>{let t,r,n=typeof e,i=T(e,"Date"),a=T(e,"RegExp"),s=T(e,"Object");if(l(e)!==e||i||a)t=i?e.toJSON():"symbol"==n?e.toString():"string"==n?JSON.stringify(e):""+e;else{if(t=C.get(e))return t;if(t=++P+"~",C.set(e,t),Array.isArray(e)){for(r=0,t="@";r<e.length;r++)t+=R(e[r])+",";C.set(e,t)}if(s){t="#";let n=l.keys(e).sort();for(;!u(r=n.pop());)u(e[r])||(t+=r+":"+R(e[r])+",");C.set(e,t)}}return t},O=e=>{if(c(e))try{e=e()}catch(t){e=""}let t=e;return[e="string"==typeof e?e:(Array.isArray(e)?e.length:e)?R(e):"",t]},A=0,j=()=>++A;async function M(...e){let[t,r,n,i]=e,s=h({populateCache:!0,throwOnError:!0},"boolean"==typeof i?{revalidate:i}:i||{}),l=s.populateCache,p=s.rollbackOnError,f=s.optimisticData,m=s.throwOnError;if(c(r)){let e=[];for(let n of t.keys())!/^\$(inf|sub)\$/.test(n)&&r(t.get(n)._k)&&e.push(n);return Promise.all(e.map(g))}return g(r);async function g(r){let i,[h]=O(r);if(!h)return;let[g,y]=w(t,h),[b,v,_,k]=a.get(t),S=()=>{let e=b[h];return(c(s.revalidate)?s.revalidate(g().data,r):!1!==s.revalidate)&&(delete _[h],delete k[h],e&&e[0])?e[0](2).then(()=>g().data):g().data};if(e.length<3)return S();let I=n,x=j();v[h]=[x,0];let D=!u(f),E=g(),N=E.data,$=E._c,C=u($)?N:$;if(D&&y({data:f=c(f)?f(C,N):f,_c:C}),c(I))try{I=I(C)}catch(e){i=e}if(I&&d(I)){let e;if(I=await I.catch(e=>{i=e}),x!==v[h][0]){if(i)throw i;return I}i&&D&&(e=i,"function"==typeof p?p(e):!1!==p)&&(l=!0,y({data:C,_c:o}))}if(l&&!i&&(c(l)?y({data:l(I,C),error:o,_c:o}):y({data:I,error:o,_c:o})),v[h][1]=j(),Promise.resolve(S()).then(()=>{y({_c:o})}),i){if(m)throw i;return}return I}}let z=(e,t)=>{for(let r in e)e[r][0]&&e[r][0](t)},F=(e,t)=>{if(!a.has(e)){let r=h(S,t),n=Object.create(null),i=M.bind(o,e),l=s,u=Object.create(null),c=(e,t)=>{let r=u[e]||[];return u[e]=r,r.push(t),()=>r.splice(r.indexOf(t),1)},d=(t,r,n)=>{e.set(t,r);let i=u[t];if(i)for(let e of i)e(r,n)},p=()=>{if(!a.has(e)&&(a.set(e,[n,Object.create(null),Object.create(null),Object.create(null),i,d,c]),!x)){let t=r.initFocus(setTimeout.bind(o,z.bind(o,n,0))),i=r.initReconnect(setTimeout.bind(o,z.bind(o,n,1)));l=()=>{t&&t(),i&&i(),a.delete(e)}}};return p(),[e,i,p,l]}return[e,a.get(e)[4]]},[U,L]=F(new Map),H=h({onLoadingSlow:s,onSuccess:s,onError:s,onErrorRetry:(e,t,r,n,i)=>{let a=r.errorRetryCount,s=i.retryCount,o=~~((Math.random()+.5)*(1<<(s<8?s:8)))*r.errorRetryInterval;(u(a)||!(s>a))&&setTimeout(n,o,i)},onDiscarded:s,revalidateOnFocus:!0,revalidateOnReconnect:!0,revalidateIfStale:!0,shouldRetryOnError:!0,errorRetryInterval:$?1e4:5e3,focusThrottleInterval:5e3,dedupingInterval:2e3,loadingTimeout:$?5e3:3e3,compare:function e(t,r){var n,a;if(t===r)return!0;
5if(t&&r&&(n=t.constructor)===r.constructor){if(n===Date)return t.getTime()===r.getTime();if(n===RegExp)return t.toString()===r.toString();if(n===Array){if((a=t.length)===r.length)for(;a--&&e(t[a],r[a]););return -1===a}if(!n||"object"==typeof t){for(n in a=0,t)if(i.call(t,n)&&++a&&!i.call(r,n)||!(n in r)||!e(t[n],r[n]))return!1;return Object.keys(r).length===a}}return t!=t&&r!=r},isPaused:()=>!1,cache:U,mutate:L,fallback:{}},{isOnline:()=>v,isVisible:()=>{let e=y&&document.visibilityState;return u(e)||"hidden"!==e}}),B=(e,t)=>{let r=h(e,t);if(t){let{use:n,fallback:i}=e,{use:a,fallback:s}=t;n&&a&&(r.use=n.concat(a)),i&&s&&(r.fallback=h(i,s))}return r},V=(0,r.createContext)({}),q=e=>{let{value:t}=e,n=(0,r.useContext)(V),i=c(t),a=(0,r.useMemo)(()=>i?t(n):t,[i,n,t]),s=(0,r.useMemo)(()=>i?a:B(n,a),[i,n,a]),l=a&&a.provider,u=(0,r.useRef)(o);l&&!u.current&&(u.current=F(l(s.cache||U),a));let d=u.current;return d&&(s.cache=d[0],s.mutate=d[1]),E(()=>{if(d)return d[2]&&d[2](),d[3]},[]),(0,r.createElement)(V.Provider,h(e,{value:s}))};e.s(["B",0,d,"I",0,I,"O",0,l,"S",0,V,"U",0,o,"a",0,c,"b",0,a,"c",0,U,"d",0,H,"e",0,u,"f",0,B,"g",0,q,"i",0,g,"j",0,L,"m",0,h,"n",0,M,"o",0,j,"r",0,x,"s",0,O,"t",0,D,"u",0,E,"z",0,w],883300);var G=e.i(211671);let K="$inf$";e.s(["INFINITE_PREFIX",0,K],646192);let J=g&&window.__SWR_DEVTOOLS_USE__,W=J?window.__SWR_DEVTOOLS_USE__:[],Z=e=>c(e[1])?[e[0],e[1],e[2]||{}]:[e[0],null,(null===e[1]?e[2]:e[1])||{}],Q=()=>h(H,(0,r.useContext)(V)),Y=W.concat(e=>(t,r,n)=>{let i=r&&((...e)=>{let[n]=O(t),[,,,i]=a.get(U);if(n.startsWith(K))return r(...e);let s=i[n];return u(s)?r(...e):(delete i[n],s)});return e(t,i,n)}),X=e=>function(...t){let r=Q(),[n,i,a]=Z(t),s=B(r,a),o=e,{use:l}=s,u=(l||[]).concat(Y);for(let e=u.length;e--;)o=u[e](o);return o(n,i||s.fetcher||null,s)},ee=(e,t,r)=>{let n=t[e]||(t[e]=[]);return n.push(r),()=>{let e=n.indexOf(r);e>=0&&(n[e]=n[n.length-1],n.pop())}};J&&(window.__SWR_DEVTOOLS_REACT__=r.default),e.s(["preload",0,(e,t)=>{let[r,n]=O(e),[,,,i]=a.get(U);if(i[r])return i[r];let s=t(n);return i[r]=s,s},"subscribeCallback",0,ee,"useSWRConfig",0,Q,"withArgs",0,X,"withMiddleware",0,(e,t)=>(...r)=>{let[n,i,a]=Z(r),s=(a.use||[]).concat(t);return e(n,i,{...a,use:s})}],271235),e.s(["SWRGlobalState",0,a],84770),e.s(["serialize",0,O],91696),e.s(["createCacheHelper",0,w],947671),e.s(["isUndefined",0,u],541281),e.s(["UNDEFINED",0,o],538912),e.s(["isFunction",0,c],696996);e.s(["useIsomorphicLayoutEffect",0,E],233391);let et=()=>{},er=et(),en=Object,ei=e=>e===er,ea=new WeakMap,es=(e,t)=>en.prototype.toString.call(e)===`[object ${t}]`,eo=0,el=e=>{let t,r,n=typeof e,i=es(e,"Date"),a=es(e,"RegExp"),s=es(e,"Object");if(en(e)!==e||i||a)t=i?e.toJSON():"symbol"==n?e.toString():"string"==n?JSON.stringify(e):""+e;else{if(t=ea.get(e))return t;if(t=++eo+"~",ea.set(e,t),Array.isArray(e)){for(r=0,t="@";r<e.length;r++)t+=el(e[r])+",";ea.set(e,t)}if(s){t="#";let n=en.keys(e).sort();for(;!ei(r=n.pop());)ei(e[r])||(t+=r+":"+el(e[r])+",");ea.set(e,t)}}return t},eu=r.default.use||(e=>{switch(e.status){case"pending":throw e;case"fulfilled":return e.value;case"rejected":throw e.reason;default:throw e.status="pending",e.then(t=>{e.status="fulfilled",e.value=t},t=>{e.status="rejected",e.reason=t}),e}}),ec={dedupe:!0},eh=l.defineProperty(q,"defaultValue",{value:H}),ed=X((e,t,i)=>{let{cache:s,compare:l,suspense:p,fallbackData:f,revalidateOnMount:m,revalidateIfStale:g,refreshInterval:y,refreshWhenHidden:b,refreshWhenOffline:v,keepPreviousData:_}=i,[k,S,N,$]=a.get(s),[C,T]=O(e),P=(0,r.useRef)(!1),R=(0,r.useRef)(!1),A=(0,r.useRef)(C),z=(0,r.useRef)(t),F=(0,r.useRef)(i),U=()=>F.current.isVisible()&&F.current.isOnline(),[L,H,B,V]=w(s,C),q=(0,r.useRef)({}).current,K=u(f)?u(i.fallback)?o:i.fallback[C]:f,J=(e,t)=>{for(let r in q)if("data"===r){if(!l(e[r],t[r])&&(!u(e[r])||!l(ei,t[r])))return!1}else if(t[r]!==e[r])return!1;return!0},W=(0,r.useMemo)(()=>{let e=!!C&&!!t&&(u(m)?!F.current.isPaused()&&!p&&!1!==g:m),r=t=>{let r=h(t);return(delete r._k,e)?{isValidating:!0,isLoading:!0,...r}:r},n=L(),i=V(),a=r(n),s=n===i?a:r(i),o=a;return[()=>{let e=r(L());return J(e,o)?(o.data=e.data,o.isLoading=e.isLoading,o.isValidating=e.isValidating,o.error=e.error,o):(o=e,e)},()=>s]}
5,[s,C]),Z=(0,n.useSyncExternalStore)((0,r.useCallback)(e=>B(C,(t,r)=>{J(r,t)||e()}),[s,C]),W[0],W[1]),Q=!P.current,Y=k[C]&&k[C].length>0,X=Z.data,et=u(X)?K&&d(K)?eu(K):K:X,er=Z.error,en=(0,r.useRef)(et),ei=_?u(X)?u(en.current)?et:en.current:X:et,ea=(!Y||!!u(er))&&(Q&&!u(m)?m:!F.current.isPaused()&&(p?!u(et)&&g:u(et)||g)),es=!!(C&&t&&Q&&ea),eo=u(Z.isValidating)?es:Z.isValidating,el=u(Z.isLoading)?es:Z.isLoading,eh=(0,r.useCallback)(async e=>{let t,r,n=z.current;if(!C||!n||R.current||F.current.isPaused())return!1;let a=!0,s=e||{},h=!N[C]||!s.dedupe,d=()=>I?!R.current&&C===A.current&&P.current:C===A.current,p={isValidating:!1,isLoading:!1},f=()=>{H(p)},m=()=>{let e=N[C];e&&e[1]===r&&delete N[C]},g={isValidating:!0};u(L().data)&&(g.isLoading=!0);try{if(h&&(H(g),i.loadingTimeout&&u(L().data)&&setTimeout(()=>{a&&d()&&F.current.onLoadingSlow(C,i)},i.loadingTimeout),N[C]=[n(T),j()]),[t,r]=N[C],t=await t,h&&setTimeout(m,i.dedupingInterval),!N[C]||N[C][1]!==r)return h&&d()&&F.current.onDiscarded(C),!1;p.error=o;let e=S[C];if(!u(e)&&(r<=e[0]||r<=e[1]||0===e[1]))return f(),h&&d()&&F.current.onDiscarded(C),!1;let s=L().data;p.data=l(s,t)?s:t,h&&d()&&F.current.onSuccess(t,C,i)}catch(r){m();let e=F.current,{shouldRetryOnError:t}=e;!e.isPaused()&&(p.error=r,h&&d()&&(e.onError(r,C,e),(!0===t||c(t)&&t(r))&&(!F.current.revalidateOnFocus||!F.current.revalidateOnReconnect||U())&&e.onErrorRetry(r,C,e,e=>{let t=k[C];t&&t[0]&&t[0](G.ERROR_REVALIDATE_EVENT,e)},{retryCount:(s.retryCount||0)+1,dedupe:!0})))}return a=!1,f(),!0},[C,s]),ed=(0,r.useCallback)((...e)=>M(s,A.current,...e),[]);if(E(()=>{z.current=t,F.current=i,u(X)||(en.current=X)}),E(()=>{if(!C)return;let e=eh.bind(o,ec),t=0;F.current.revalidateOnFocus&&(t=Date.now()+F.current.focusThrottleInterval);let r=ee(C,k,(r,n={})=>{if(r==G.FOCUS_EVENT){let r=Date.now();F.current.revalidateOnFocus&&r>t&&U()&&(t=r+F.current.focusThrottleInterval,e())}else if(r==G.RECONNECT_EVENT)F.current.revalidateOnReconnect&&U()&&e();else if(r==G.MUTATE_EVENT)return eh();else if(r==G.ERROR_REVALIDATE_EVENT)return eh(n)});return R.current=!1,A.current=C,P.current=!0,H({_k:T}),ea&&(u(et)||x?e():D(e)),()=>{R.current=!0,r()}},[C]),E(()=>{let e;function t(){let t=c(y)?y(L().data):y;t&&-1!==e&&(e=setTimeout(r,t))}function r(){!L().error&&(b||F.current.isVisible())&&(v||F.current.isOnline())?eh(ec).then(t):t()}return t(),()=>{e&&(clearTimeout(e),e=-1)}},[y,b,v,C]),(0,r.useDebugValue)(ei),p&&u(et)&&C){if(!I&&x)throw Error("Fallback data is required when using Suspense in SSR.");z.current=t,F.current=i,R.current=!1;let e=$[C];if(u(e)||eu(ed(e)),u(er)){let e=eh(ec);u(ei)||(e.status="fulfilled",e.value=!0),eu(e)}else throw er}return{mutate:ed,get data(){return q.data=!0,ei},get error(){return q.error=!0,er},get isValidating(){return q.isValidating=!0,eo},get isLoading(){return q.isLoading=!0,el}}});e.s(["SWRConfig",0,eh,"default",0,ed,"unstable_serialize",0,e=>(e=>{if("function"==typeof e)try{e=e()}catch(t){e=""}let t=e;return[e="string"==typeof e?e:(Array.isArray(e)?e.length:e)?el(e):"",t]})(e)[0]],283599);var ep=Symbol.for("immer-nothing"),ef=Symbol.for("immer-draftable"),em=Symbol.for("immer-state");function eg(e){throw Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var ey=Object.getPrototypeOf;function eb(e){return!!e&&!!e[em]}function ew(e){return!!e&&(ek(e)||Array.isArray(e)||!!e[ef]||!!e.constructor?.[ef]||eE(e)||eN(e))}var ev=Object.prototype.constructor.toString(),e_=new WeakMap;function ek(e){if(!e||"object"!=typeof e)return!1;let t=Object.getPrototypeOf(e);if(null===t||t===Object.prototype)return!0;let r=Object.hasOwnProperty.call(t,"constructor")&&t.constructor;if(r===Object)return!0;if("function"!=typeof r)return!1;let n=e_.get(r);return void 0===n&&(n=Function.toString.call(r),e_.set(r,n)),n===ev}function eS(e,t,r=!0){0===eI(e)?(r?Reflect.ownKeys(e):Object.keys(e)).forEach(r=>{t(r,e[r],e)}):e.forEach((r,n)=>t(n,r,e))}function eI(e){let t=e[em];return t?t.type_:Array.isArray(e)?1:eE(e)?2:3*!!eN(e)}function ex(e,t){return 2===eI(e)?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function eD(e,t,r){let n=eI(e);2===n?e.set(t,r):3===n?e.add(r):e[t]=r}function eE(e){return e instanceof Map}function eN(e){return e instanceof Set}function e$(e){return e.copy_||e.base_}function eC(e,t){if(eE(e))return new Map(e);if(eN(e))return new Set(e);if(Array.isArray(e))return Array.prototype.slice.call(e);let r=ek(e);if(!0!==t&&("class_only"!==t||r)){let t=ey(e);return null!==t&&r?{...e}:Object.assign(Object.create(t),e)}{let t=Object.getOwnPropertyDescriptors(e);delete t[em];let r=Reflect.ownKeys(t);for(let n=0;n<r.length;n++){let i=r[n],a=t[i];!1===a.writable&&(a.writable=!0,a.configurable=!0),(a.get||a.set)&&(t[i]={configurable:!0,writable:!0,enumerable:a.enumerable,value:e[i]})}return Object.create(ey(e),t)}}function eT(e,t=!1){return eR(e)||eb(e)||!ew(e)||(eI(e)>
51&&Object.defineProperties(e,{set:eP,add:eP,clear:eP,delete:eP}),Object.freeze(e),t&&Object.values(e).forEach(e=>eT(e,!0))),e}var eP={value:function(){eg(2)}};function eR(e){return null===e||"object"!=typeof e||Object.isFrozen(e)}var eO={};function eA(e){let t=eO[e];return t||eg(0),t}function ej(e,t){t&&(eA("Patches"),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function eM(e){ez(e),e.drafts_.forEach(eU),e.drafts_=null}function ez(e){e===t&&(t=e.parent_)}function eF(e){return t={drafts_:[],parent_:t,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function eU(e){let t=e[em];0===t.type_||1===t.type_?t.revoke_():t.revoked_=!0}function eL(e,t){t.unfinalizedDrafts_=t.drafts_.length;let r=t.drafts_[0];return void 0!==e&&e!==r?(r[em].modified_&&(eM(t),eg(4)),ew(e)&&(e=eH(t,e),t.parent_||eV(t,e)),t.patches_&&eA("Patches").generateReplacementPatches_(r[em].base_,e,t.patches_,t.inversePatches_)):e=eH(t,r,[]),eM(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e!==ep?e:void 0}function eH(e,t,r){if(eR(t))return t;let n=e.immer_.shouldUseStrictIteration(),i=t[em];if(!i)return eS(t,(n,a)=>eB(e,i,t,n,a,r),n),t;if(i.scope_!==e)return t;if(!i.modified_)return eV(e,i.base_,!0),i.base_;if(!i.finalized_){i.finalized_=!0,i.scope_.unfinalizedDrafts_--;let t=i.copy_,a=t,s=!1;3===i.type_&&(a=new Set(t),t.clear(),s=!0),eS(a,(n,a)=>eB(e,i,t,n,a,r,s),n),eV(e,t,!1),r&&e.patches_&&eA("Patches").generatePatches_(i,r,e.patches_,e.inversePatches_)}return i.copy_}function eB(e,t,r,n,i,a,s){if(null==i||"object"!=typeof i&&!s)return;let o=eR(i);if(!o||s){if(eb(i)){let s=eH(e,i,a&&t&&3!==t.type_&&!ex(t.assigned_,n)?a.concat(n):void 0);if(eD(r,n,s),!eb(s))return;e.canAutoFreeze_=!1}else s&&r.add(i);if(ew(i)&&!o){if(!e.immer_.autoFreeze_&&e.unfinalizedDrafts_<1||t&&t.base_&&t.base_[n]===i&&o)return;eH(e,i),(!t||!t.scope_.parent_)&&"symbol"!=typeof n&&(eE(r)?r.has(n):Object.prototype.propertyIsEnumerable.call(r,n))&&eV(e,i)}}}function eV(e,t,r=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&eT(t,r)}var eq={get(e,t){if(t===em)return e;let r=e$(e);if(!ex(r,t)){var n;let i;return n=e,(i=eJ(r,t))?"value"in i?i.value:i.get?.call(n.draft_):void 0}let i=r[t];return e.finalized_||!ew(i)?i:i===eK(e.base_,t)?(eZ(e),e.copy_[t]=eQ(i,e)):i},has:(e,t)=>t in e$(e),ownKeys:e=>Reflect.ownKeys(e$(e)),set(e,t,r){let n=eJ(e$(e),t);if(n?.set)return n.set.call(e.draft_,r),!0;if(!e.modified_){let n=eK(e$(e),t),i=n?.[em];if(i&&i.base_===r)return e.copy_[t]=r,e.assigned_[t]=!1,!0;if((r===n?0!==r||1/r==1/n:r!=r&&n!=n)&&(void 0!==r||ex(e.base_,t)))return!0;eZ(e),eW(e)}return!!(e.copy_[t]===r&&(void 0!==r||t in e.copy_)||Number.isNaN(r)&&Number.isNaN(e.copy_[t]))||(e.copy_[t]=r,e.assigned_[t]=!0,!0)},deleteProperty:(e,t)=>(void 0!==eK(e.base_,t)||t in e.base_?(e.assigned_[t]=!1,eZ(e),eW(e)):delete e.assigned_[t],e.copy_&&delete e.copy_[t],!0),getOwnPropertyDescriptor(e,t){let r=e$(e),n=Reflect.getOwnPropertyDescriptor(r,t);return n?{writable:!0,configurable:1!==e.type_||"length"!==t,enumerable:n.enumerable,value:r[t]}:n},defineProperty(){eg(11)},getPrototypeOf:e=>ey(e.base_),setPrototypeOf(){eg(12)}},eG={};function eK(e,t){let r=e[em];return(r?e$(r):e)[t]}function eJ(e,t){if(!(t in e))return;let r=ey(e);for(;r;){let e=Object.getOwnPropertyDescriptor(r,t);if(e)return e;r=ey(r)}}function eW(e){!e.modified_&&(e.modified_=!0,e.parent_&&eW(e.parent_))}function eZ(e){e.copy_||(e.copy_=eC(e.base_,e.scope_.immer_.useStrictShallowCopy_))}function eQ(e,r){let n=eE(e)?eA("MapSet").proxyMap_(e,r):eN(e)?eA("MapSet").proxySet_(e,r):function(e,r){let n=Array.isArray(e),i={type_:+!!n,scope_:r?r.scope_:t,modified_:!1,finalized_:!1,assigned_:{},parent_:r,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1},a=i,s=eq;n&&(a=[i],s=eG);let{revoke:o,proxy:l}=Proxy.revocable(a,s);return i.draft_=l,i.revoke_=o,l}(e,r);return(r?r.scope_:t).drafts_.push(n),n}eS(eq,(e,t)=>{eG[e]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}}),eG.deleteProperty=function(e,t){return eG.set.call(this,e,t,void 0)},eG.set=function(e,t,r){return eq.set.call(this,e[0],t,r,e[0])};var eY=new class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!0,this.produce=(e,t,r)=>{let n;if("function"==typeof e&&"function"!=typeof t){let r=t;t=e;let n=this;return function(e=r,...i){return n.produce(e,e=>t.call(this,e,...i))}}if("function"!=typeof t&&eg(6),void 0!==r&&"function"!=typeof r&&eg(7),ew(e)){let i=eF(this),a=eQ(e,void 0),s=!0;try{n=t(a),s=!1}finally{s?eM(i):ez(i)}return ej(i,r),eL(n,i)}if(e&&"object"==typeof e)eg(1);else{if(void 0===(n=t(e))&&(n=e),n===ep&&(n=void 0),this.autoFreeze_&&eT(n,!0),r){let t=[],i=[];eA("Patches").generateReplacementPatches_(e,n,t,i),r(t,i)}return n}},this.produceWithPatches=(e,t)=>{let r,n;return"function"==typeof e?(t,...r)=>this.produceWithPatches(t,t=>e(t,...r)):[this.produce(e,t,(e,t)=>{r=e,n=t}),r,n]},"boolean"==typeof e?.autoFreeze&&this.setAutoFreeze(e.autoFreeze),"boolean"==typeof e?.useStrictShallowCopy&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),"boolean"==typeof e?.useStrictIteration&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){var t;ew(e)||eg(8),eb(e)&&(eb(t=e)||eg(10),e=function e(t){let r;if(!ew(t)||eR(t))return t;let n=t[em],i=!0;if(n){if(!n.modified_)return n.base_;n.finalized_=!0,r=eC(t,n.scope_.immer_.useStrictShallowCopy_),i=n.scope_.immer_.shouldUseStrictIteration()}else r=eC(t,!0);return eS(r,(t,n)=>{eD(r,t,e(n))},i),n&&(n.finalized_=!1),r}(t));let r=eF(this),n=eQ(e,void 0);return n[em].isManual_=!0,ez(r),n}finishDraft(e,t){let r=e&&e[em];r&&r.isManual_||eg(9);let{scope_:n}=r;return ej(n,t),eL(void 0,n)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let r;for(r=t.length-1;r>=0;r--){let n=t[r];
5if(0===n.path.length&&"replace"===n.op){e=n.value;break}}r>-1&&(t=t.slice(r+1));let n=eA("Patches").applyPatches_;return eb(e)?n(e,t):this.produce(e,e=>n(e,t))}}().produce;e.s(["castDraft",0,function(e){return e},"produce",0,eY],606368)},755838,(e,t,r)=>{"use strict";var n=e.r(271645),i="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},a=n.useState,s=n.useEffect,o=n.useLayoutEffect,l=n.useDebugValue;function u(e){var t=e.getSnapshot;e=e.value;try{var r=t();return!i(e,r)}catch(e){return!0}}var c="u"<typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(e,t){var r=t(),n=a({inst:{value:r,getSnapshot:t}}),i=n[0].inst,c=n[1];return o(function(){i.value=r,i.getSnapshot=t,u(i)&&c({inst:i})},[e,r,t]),s(function(){return u(i)&&c({inst:i}),e(function(){u(i)&&c({inst:i})})},[e]),l(r),r};r.useSyncExternalStore=void 0!==n.useSyncExternalStore?n.useSyncExternalStore:c},802239,(e,t,r)=>{"use strict";e.i(247167),t.exports=e.r(755838)},467592,789606,478802,929495,110383,854799,370257,840124,870370,868679,64572,581869,417223,442957,867854,e=>{"use strict";let t,r,n,i;var a,s,o,l=e.i(843476),u=e.i(500932),c=e.i(271645);let h=!1,d=[];function p(){let e=d;for(let t of(d=[],h=!1,e))t()}function f(e,t,r){let n,i,a,s,o=(0,u.c)(11);o[0]!==r?(n=void 0===r?{}:r,o[0]=r,o[1]=n):n=o[1];let{default:l,dependencies:f,isEqual:m}=n;o[2]!==f?(i=void 0===f?[]:f,o[2]=f,o[3]=i):i=o[3];let g=i,[y,b]=(0,c.useState)(void 0);return(o[4]!==m||o[5]!==t||o[6]!==e?(a=()=>{if(!e)return;let r=e.subscribe(t,{onData:e=>{d.push(()=>b(e)),h||(Promise.resolve().then(p),h=!0)},isEqual:m});return()=>{r(),b(void 0)}},o[4]=m,o[5]=t,o[6]=e,o[7]=a):a=o[7],o[8]!==g||o[9]!==e?(s=[e,...g],o[8]=g,o[9]=e,o[10]=s):s=o[10],(0,c.useEffect)(a,s),void 0===y)?l:y}e.s(["useSubscribe",0,f],789606);class m{#e;constructor(e){this.#e=e}log(e,t,...r){for(let n of this.#e)n.log(e,t,...r)}async flush(){await Promise.all(this.#e.map(e=>e.flush?.()))}}class g{debug=void 0;info=void 0;warn=void 0;error=void 0;flush;constructor(e,t="info",r){const n=t=>(...n)=>e.log(t,r,...n);switch(t){case"debug":this.debug=n("debug");case"info":this.info=n("info");case"warn":this.warn=n("warn");case"error":this.error=n("error")}this.flush=()=>e.flush?.()??Promise.resolve()}}let y={log(e,t,...r){console[e](...function(e){let t=[];for(let[r,n]of Object.entries(e??{})){let e=void 0===n?r:`${r}=${n}`;t.push(e)}return t}(t),...r.map(w))}};class b extends g{#t;#r;#n;constructor(e="info",t,r=y){super(r,e,t),this.#r=e,this.#t=r,this.#n=t}withContext(e,t){let r={...this.#n,[e]:t};return new b(this.#r,r,this.#t)}}function w(e){switch(typeof e){case"string":case"number":case"boolean":case"undefined":case"symbol":case"bigint":return e;case"object":if(null===e)return null}return JSON.stringify(e,v)}function v(e,t){return t instanceof Error?{name:t.name,message:t.message,stack:t.stack,..."cause"in t?{cause:t.cause}:null}:t}function _(){let e,t;return{promise:new Promise((r,n)=>{e=r,t=n}),resolve:e,reject:t}}class k{_lockP=null;async lock(){let e=this._lockP,{promise:t,resolve:r}=_();return this._lockP=t,await e,r}withLock(e){return I(this.lock(),e)}}class S{_lock=new k;_writeP=null;_readP=[];read(){return this._lock.withLock(async()=>{await this._writeP;let{promise:e,resolve:t}=_();return this._readP.push(e),t})}withRead(e){return I(this.read(),e)}async write(){return await this._lock.withLock(async()=>{await this._writeP,await Promise.all(this._readP);let{promise:e,resolve:t}=_();return this._writeP=e,this._readP=[],t})}withWrite(e){return I(this.write(),e)}}async function I(e,t){let r=await e;try{return await t()}finally{r()}}function x(e,t){return e?{ok:!1,code:"join",left:e,right:t}:t}function D(e,t){return{ok:!1,code:"prepend",key:e,tree:t}}function E(e,t=[],r=[]){for(;;)if("join"===e.code)E(e.left,t.slice(),r),e=e.right;else{if("prepend"!==e.code)return"custom_error"===e.code&&"object"==typeof e.error&&void 0!==e.error.path&&t.push(...e.error.path),r.push(function(e,t){let r=e.code;
5switch(r){case"invalid_type":case"invalid_literal":return{code:r,path:t,expected:e.expected};case"missing_value":return{code:r,path:t};case"invalid_length":return{code:r,path:t,minLength:e.minLength,maxLength:e.maxLength};case"unrecognized_keys":return{code:r,path:t,keys:e.keys};case"invalid_union":return{code:r,path:t,tree:e.tree};default:return{code:r,path:t,error:e.error}}}(e,t)),r;t.push(e.key),e=e.tree}}function N(e,t){return 0===e.length?"nothing":1===e.length?e[0]:`${e.slice(0,-1).join(", ")} ${t} ${e[e.length-1]}`}function $(e){return"bigint"==typeof e?`${e}n`:JSON.stringify(e)}function C(e){let t="",r=0;for(;;)if("join"===e.code)r+=function e(t){let r=0;for(;;)if("join"===t.code)r+=e(t.left),t=t.right;else{if("prepend"!==t.code)return r+1;t=t.tree}}(e.right),e=e.left;else if("prepend"===e.code)t+="."+e.key,e=e.tree;else break;let n="validation failed";if("invalid_type"===e.code)n=`expected ${N(e.expected,"or")}`;else if("invalid_literal"===e.code)n=`expected ${N(e.expected.map($),"or")}`;else if("missing_value"===e.code)n="missing value";else if("unrecognized_keys"===e.code){let t=e.keys;n=`unrecognized ${1===t.length?"key":"keys"} ${N(t.map($),"and")}`}else if("invalid_length"===e.code){let t=e.minLength,r=e.maxLength;n="expected an array with ",t>0?r===t?n+=`${t}`:r<1/0?n+=`between ${t} and ${r}`:n+=`at least ${t}`:n+=`at most ${r}`,n+=" item(s)"}else if("custom_error"===e.code){let r=e.error;"string"==typeof r?n=r:void 0!==r&&(void 0!==r.message&&(n=r.message),void 0!==r.path&&(t+="."+r.path.join(".")))}let i=`${e.code} at .${t.slice(1)} (${n})`;return 1===r?i+=" (+ 1 other issue)":r>1&&(i+=` (+ ${r} other issues)`),i}class T extends Error{constructor(e){super(C(e)),this.issueTree=e,Object.setPrototypeOf(this,new.target.prototype),this.name=new.target.name,this._issues=void 0}get issues(){return void 0===this._issues&&(this._issues=E(this.issueTree)),this._issues}}class P{constructor(e){this.issueTree=e,this.ok=!1,this._issues=void 0,this._message=void 0}get issues(){return void 0===this._issues&&(this._issues=E(this.issueTree)),this._issues}get message(){return void 0===this._message&&(this._message=C(this.issueTree)),this._message}throw(){throw new T(this.issueTree)}}function R(e){return{ok:!0,value:e}}function O(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}class A{optional(){return new z(this)}default(e){let t=R(e);return new W(this.optional(),e=>void 0===e?t:void 0)}assert(e,t){let r={ok:!1,code:"custom_error",error:t};return new W(this,(t,n)=>e(t,n)?void 0:r)}map(e){return new W(this,(t,r)=>({ok:!0,value:e(t,r)}))}chain(e){return new W(this,(t,r)=>{let n=e(t,r);return n.ok?n:n.issueTree})}}class j extends A{nullable(){return new M(this)}toTerminals(e){e(this)}try(e,t){let r=1;(null==t?void 0:t.mode)==="passthrough"?r=0:(null==t?void 0:t.mode)==="strip"&&(r=2);let n=this.func(e,r);return void 0===n?{ok:!0,value:e}:n.ok?{ok:!0,value:n.value}:new P(n)}parse(e,t){let r=1;(null==t?void 0:t.mode)==="passthrough"?r=0:(null==t?void 0:t.mode)==="strip"&&(r=2);let n=this.func(e,r);if(void 0===n)return e;if(n.ok)return n.value;throw new T(n)}}class M extends j{constructor(e){super(),this.type=e,this.name="nullable"}func(e,t){return null===e?void 0:this.type.func(e,t)}toTerminals(e){e(er),this.type.toTerminals(e)}nullable(){return this}}class z extends A{constructor(e){super(),this.type=e,this.name="optional"}func(e,t){return void 0===e||4&t?void 0:this.type.func(e,t)}toTerminals(e){e(this),e(et),this.type.toTerminals(e)}optional(){return this}}function F(e,t){return"number"==typeof e?t<32?e>>>t&1:0:e[t>>5]>>>t%32&1}class U extends j{constructor(e,t,r){super(),this.shape=e,this.restType=t,this.checks=r,this.name="object"}check(e,t){var r;return new U(this.shape,this.restType,[...null!=(r=this.checks)?r:[],{func:e,issue:{ok:!1,code:"custom_error",error:t}}])}func(e,t){let r=this._func;return void 0===r&&(r=function(e,t,r){let n=[],i=[];for(let t in e){let r=!1;e[t].toTerminals(e=>{r||(r="optional"===e.name)}),r?i.push(t):n.push(t)}let a=[...n,...i],s=a.length,o={ok:!1,code:"invalid_type",expected:["object"]};if(0===s&&(null==t?void 0:t.name)==="unknown")return function(e,t){if(!O(e))return o;if(void 0!==r){for(let t=0;t<r.length;t++)if(!r[t].func(e))return r[t].issue}};let l=a.map(t=>e[t]),u=n.length,c=Object.create(null);a.forEach((e,t)=>{c[e]=~t});let h=n.map(e=>
5D(e,{ok:!1,code:"missing_value"}));function d(e,t,r){"__proto__"===t?Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}):e[t]=r}return function(e,n){let i,p;if(!O(e))return o;let f=!1,m=e,g=0,y=0;if(1&n||2&n||void 0!==t)for(let r in e){let o,u=e[r],h=~c[r];if(h>=0)y++,g=function e(t,r){if("number"!=typeof t){let e=r>>5;for(let r=t.length;r<=e;r++)t.push(0);return t[e]|=1<<r%32,t}return r<32?t|1<<r:e([t,0],r)}(g,h),o=l[h].func(u,n);else if(void 0!==t)o=t.func(u,n);else{if(1&n)void 0===p?p=[r]:p.push(r);else if(2&n&&void 0===i&&!f){m={},f=!0;for(let t=0;t<s;t++)if(F(g,t)){let r=a[t];d(m,r,e[r])}}continue}if(void 0===o)f&&void 0===i&&d(m,r,u);else if(o.ok){if(void 0===i){if(!f)if(m={},f=!0,void 0===t){for(let t=0;t<s;t++)if(t!==h&&F(g,t)){let r=a[t];d(m,r,e[r])}}else for(let t in e)d(m,t,e[t]);d(m,r,o.value)}}else i=x(i,D(r,o))}if(y<s)for(let r=0;r<s;r++){if(F(g,r))continue;let o=a[r],c=e[o],p=-5&n;if(void 0===c&&!(o in e)){if(r<u){i=x(i,h[r]);continue}p|=4}let y=l[r].func(c,p);if(void 0===y)f&&void 0===i&&!(4&p)&&d(m,o,c);else if(y.ok){if(void 0===i){if(!f)if(m={},f=!0,void 0===t){for(let t=0;t<s;t++)if(t<r||F(g,t)){let r=a[t];d(m,r,e[r])}}else{for(let t in e)d(m,t,e[t]);for(let t=0;t<r;t++)if(!F(g,t)){let r=a[t];d(m,r,e[r])}}d(m,o,y.value)}}else i=x(i,D(o,y))}
5if(void 0!==p&&(i=x(i,{ok:!1,code:"unrecognized_keys",keys:p})),void 0===i&&void 0!==r){for(let e=0;e<r.length;e++)if(!r[e].func(m))return r[e].issue}return void 0===i&&f?{ok:!0,value:m}:i}}(this.shape,this.restType,this.checks),this._func=r),r(e,t)}rest(e){return new U(this.shape,e)}extend(e){return new U(Object.assign(Object.assign({},this.shape),e),this.restType)}pick(...e){let t={};return e.forEach(e=>{t[e]=this.shape[e]}),new U(t,void 0)}omit(...e){let t=Object.assign({},this.shape);return e.forEach(e=>{delete t[e]}),new U(t,this.restType)}partial(){var e;let t={};return Object.keys(this.shape).forEach(e=>{t[e]=this.shape[e].optional()}),new U(t,null==(e=this.restType)?void 0:e.optional())}}class L extends j{constructor(e,t){super(),this.head=e,this.name="array",this.rest=null!=t?t:Y(),this.minLength=this.head.length,this.maxLength=t?1/0:this.minLength,this.invalidType={ok:!1,code:"invalid_type",expected:["array"]},this.invalidLength={ok:!1,code:"invalid_length",minLength:this.minLength,maxLength:this.maxLength}}func(e,t){let r;if(!Array.isArray(e))return this.invalidType;let n=e.length,i=this.minLength,a=this.maxLength;if(n<i||n>a)return this.invalidLength;let s=e;for(let n=0;n<e.length;n++){let a=(n<i?this.head[n]:this.rest).func(e[n],t);void 0!==a&&(a.ok?(s===e&&(s=e.slice()),s[n]=a.value):r=x(r,D(n,a)))}return r||(e===s?void 0:{ok:!0,value:s})}}function H(e){let t=typeof e;return"object"!==t?t:null===e?"null":Array.isArray(e)?"array":t}function B(e){return Array.from(new Set(e))}function V(e){let t=new Map,r=new Map,n=new Map,i=[],a=[],s=[];e.forEach(({root:e,terminal:o})=>{var l;if(t.set(e,null!=(l=t.get(e))?l:t.size),"never"===o.name);else if("optional"===o.name)a.push(e);else if("unknown"===o.name)i.push(e);else if("literal"===o.name){let t=r.get(o.value)||[];t.push(e),r.set(o.value,t),s.push(H(o.value))}else{let t=n.get(o.name)||[];t.push(e),n.set(o.name,t),s.push(o.name)}}),r.forEach((e,t)=>{let i=n.get(H(t));i&&(i.push(...e),r.delete(t))});let o=(e,r)=>{var n,i;return(null!=(n=t.get(e))?n:0)-(null!=(i=t.get(r))?i:0)};return n.forEach((e,t)=>n.set(t,B(e.concat(i).sort(o)))),r.forEach((e,t)=>r.set(t,B(e.concat(i)).sort(o))),{types:n,literals:r,unknowns:B(i).sort(o),optionals:B(a).sort(o),expectedTypes:B(s)}}class q extends j{constructor(e){super(),this.options=e,this.name="union"}toTerminals(e){this.options.forEach(t=>t.toTerminals(e))}func(e,t){let r=this._func;if(void 0===r){let e=[];this.options.forEach(t=>t.toTerminals(r=>{e.push({root:t,terminal:r})}));let t=function(e){let{expectedTypes:t,literals:r,types:n,unknowns:i,optionals:a}=V(e),s=0===n.size&&0===i.length?{ok:!1,code:"invalid_literal",expected:Array.from(r.keys())}:{ok:!1,code:"invalid_type",expected:t},o=r.size>0?r:void 0,l=n.size>0?{}:void 0;for(let[e,t]of n)l[e]=t;return function(e,t){var r,n;let u;if(!(u=4&t?a:null!=(n=null!=(r=null==l?void 0:l[H(e)])?r:null==o?void 0:o.get(e))?n:i))return s;let c=0,h=s;for(let r=0;r<u.length;r++){let n=u[r].func(e,t);if(void 0===n||n.ok)return n;h=c>0?x(h,n):n,c++}return c>1?{ok:!1,code:"invalid_union",tree:h}:h}}(e),n=function(e){var t;let r,n;if(e.some(({terminal:e})=>"unknown"===e.name))return;let i=e.filter(e=>"object"===e.terminal.name);if(!(i.length<2))for(let e of(t=i.map(({terminal:e})=>e.shape),r=new Map,t.forEach(e=>{for(let t in e)r.set(t,(r.get(t)||0)+1)}),n=[],r.forEach((e,r)=>{e===t.length&&n.push(r)}),n)){let t=function(e,t){let r=[];for(let{root:n,terminal:i}of e)i.shape[t].toTerminals(e=>r.push({root:n,terminal:e}));let{types:n,literals:i,optionals:a,unknowns:s,expectedTypes:o}=V(r);if(s.length>0||a.length>1)return;for(let e of i.values())if(e.length>1)return;for(let e of n.values())if(e.length>1)return;let l=D(t,{ok:!1,code:"missing_value"}),u=D(t,0===n.size?{ok:!1,code:"invalid_literal",expected:Array.from(i.keys())}:{ok:!1,code:"invalid_type",expected:o}),c=i.size>0?new Map:void 0;for(let[e,t]of i)c.set(e,t[0]);let h=n.size>0?{}:void 0;for(let[e,t]of n)h[e]=t[0];return function(e,r){var n;let i=e[t];if(void 0===i&&!(t in e))return a.length>0?a[0].func(e,r):l;let s=null!=(n=null==h?void 0:h[H(i)])?n:null==c?void 0:c.get(i);return s?s.func(e,r):u}}(i,e);if(t)return t}}(e);r=n?function(e,r){return O(e)?n(e,r):t(e,r)}:t,this._func=r}return r(e,t)}}let G=Object.freeze({mode:"strict"}),K=Object.freeze({mode:"strip"}),J=Object.freeze({mode:"passthrough"});class W extends j{constructor(e,t){super(),this.transformed=e,this.transform=t,this.name="transform",this.undef=R(void 0),this.transformChain=void 0,this.transformRoot=void 0}func(e,t){let r,n=this.transformChain;if(!n){n=[];let e=this;for(;e instanceof W;)n.push(e.transform),e=e.transformed;n.reverse(),this.transformChain=n,this.transformRoot=e}let i=this.transformRoot.func(e,t);if(void 0!==i&&!i.ok)return i;void 0!==i?r=i.value:4&t?(r=void 0,i=this.undef):r=e;let a=1&t?G:2&t?K:J;for(let e=0;e<n.length;e++){let t=n[e](r,a);if(void 0!==t){if(!t.ok)return t;r=t.value,i=t}}return i}toTerminals(e){this.transformed.toTerminals(e)}}class Z extends j{constructor(e){super(),this.definer=e,this.name="lazy",this.recursing=!1}
5func(e,t){return this.type||(this.type=this.definer()),this.type.func(e,t)}toTerminals(e){if(!this.recursing)try{this.recursing=!0,this.type||(this.type=this.definer()),this.type.toTerminals(e)}finally{this.recursing=!1}}}let Q=new class extends j{constructor(){super(...arguments),this.name="never",this.issue={ok:!1,code:"invalid_type",expected:[]}}func(e,t){return this.issue}};function Y(){return Q}let X=new class extends j{constructor(){super(...arguments),this.name="unknown"}func(e,t){}};function ee(){return X}let et=new class extends j{constructor(){super(...arguments),this.name="undefined",this.issue={ok:!1,code:"invalid_type",expected:["undefined"]}}func(e,t){return void 0===e?void 0:this.issue}},er=new class extends j{constructor(){super(...arguments),this.name="null",this.issue={ok:!1,code:"invalid_type",expected:["null"]}}func(e,t){return null===e?void 0:this.issue}},en=new class extends j{constructor(){super(...arguments),this.name="number",this.issue={ok:!1,code:"invalid_type",expected:["number"]}}func(e,t){return"number"==typeof e?void 0:this.issue}},ei=new class extends j{constructor(){super(...arguments),this.name="bigint",this.issue={ok:!1,code:"invalid_type",expected:["bigint"]}}func(e,t){return"bigint"==typeof e?void 0:this.issue}},ea=new class extends j{constructor(){super(...arguments),this.name="string",this.issue={ok:!1,code:"invalid_type",expected:["string"]}}func(e,t){return"string"==typeof e?void 0:this.issue}},es=new class extends j{constructor(){super(...arguments),this.name="boolean",this.issue={ok:!1,code:"invalid_type",expected:["boolean"]}}func(e,t){return"boolean"==typeof e?void 0:this.issue}};class eo extends j{constructor(e){super(),this.value=e,this.name="literal",this.issue={ok:!1,code:"invalid_literal",expected:[e]}}func(e,t){return e===this.value?void 0:this.issue}}e.s(["ValitaError",0,T,"array",0,function(e){return new L([],e)},"bigint",0,function(){return ei},"boolean",0,function(){return es},"err",0,function(e){return new P({ok:!1,code:"custom_error",error:e})},"lazy",0,function(e){return new Z(e)},"literal",0,function(e){return new eo(e)},"never",0,Y,"null",0,function(){return er},"number",0,function(){return en},"object",0,function(e){return new U(e,void 0)},"ok",0,R,"record",0,function(e){return new U({},null!=e?e:ee())},"string",0,function(){return ea},"tuple",0,function(e){return new L(e)},"undefined",0,function(){return et},"union",0,function(...e){return new q(e)},"unknown",0,ee],390332);var el=e.i(390332),eu=Object.defineProperty,ec=Object.getOwnPropertyDescriptor,eh=Object.getOwnPropertyNames,ed=Object.prototype.hasOwnProperty,ep=class extends Error{name="AbortError"};function ef(e,t="Assertion failed"){if(!e)throw Error(t)}function em(e){ey(e,"string")}function eg(e){ey(e,"number")}function ey(e,t){typeof e!==t&&ev(e,t)}function eb(e){null===e&&ev(e,"object"),ey(e,"object")}function ew(e){Array.isArray(e)||ev(e,"array")}function ev(e,t){let r;throw Error((r="Invalid type: ",null==e?r+=e:r+=`${typeof e} \`${e}\``,r+`, expected ${t}`))}function e_(e,t="Expected non undefined value"){if(void 0===e)throw Error(t)}function ek(e){throw Error("Unreachable")}function eS(){return"u">typeof document?document:void 0}var eI=class{#i;#a;#s=0;visibilityState;#o=new Set;constructor(e,t,r){this.#i=e,this.#a=t,this.visibilityState=e.visibilityState,this.#i.addEventListener("visibilitychange",this.#l,{signal:r})}#l=()=>{"visible"===this.#i.visibilityState?(clearTimeout(this.#s),this.#u("visible")):this.#s=setTimeout(()=>{this.#u("hidden")},this.#a)};#u(e){if(e!==this.visibilityState)for(let t of(this.visibilityState=e,this.#o)){let{resolve:r,state:n}=t;n===e&&(r(),this.#o.delete(t))}}waitForVisible(){return this.#c("visible")}waitForHidden(){return this.#c("hidden")}#c(e){if(this.visibilityState===e)return Promise.resolve();let{promise:t,resolve:r}=_();return this.#o.add({resolve:r,state:e}),t}},ex=Promise.resolve(),eD=new Promise(()=>{}),eE=class{visibilityState="visible";waitForVisible(){return ex}waitForHidden(){return eD}},eN=class{rep;invokeSend;maxConnections=1;constructor(e,t){this.rep=e,this.invokeSend=t}get maxDelayMs(){return this.rep.requestOptions.maxDelayMs}get minDelayMs(){return this.rep.requestOptions.minDelayMs}},e$=class extends eN{debounceDelay=0;get watchdogTimer(){return this.rep.pullInterval}},eC=class extends eN{get debounceDelay(){return this.rep.pushDelay}watchdogTimer=null},eT=Promise.resolve();function eP(e,t){return 0===e?eT:new Promise((r,n)=>{let i;t&&(i=()=>{clearTimeout(a),n(new ep("Aborted"))},t.addEventListener("abort",i,{once:!0}));let a=setTimeout(()=>{r(),t?.removeEventListener("abort",i)},e)})}new Promise(()=>{});var eR=class{#i=_();#a=_();#s=_();#o;#l=!1;#u=0;#c;#h;constructor(e,t,r){this.#c=e,this.#o=t,this.#h=r,this.run()}close(){this.#l=!0,this.#u>0&&this.#s.resolve({error:eO()})}async send(e){if(this.#l)return{error:eO()};this.#u++,this.#c.debug?.("send",e),e?this.#a.resolve():await this.#h?.waitForVisible(),this.#i.resolve();let t=await this.#s.promise;return this.#u--,t}async run(){let e=[],t=_(),r,n=0,i=this.#o,{debug:a}=this.#c,s=0;a?.("Starting connection loop");let o=e=>Promise.race([this.#a.promise,eP(e)]);for(;!this.#l;){a?.(eA(e)?"Last request failed. Trying again":"Waiting for a send");let l=[this.#i.promise],u=i.watchdogTimer;if(null!==u&&l.push(eP(u)),await Promise.race(l),this.#l||(a?.("Waiting for debounce"),await o(i.debounceDelay),this.#l))break;if(a?.("debounced"),this.#i=_(),n>=i.maxConnections){if(a?.("Too many request in flight. Waiting until one finishes..."),await this.#d(),this.#l)break;a?.("...finished")}n>0||eA(e)?(s=function(e,t,r){let{length:n}=r;if(0===n)return e;let{ok:i}=r[r.length-1],{maxConnections:a,minDelayMs:s}=t;if(!i)return 0===e?s:2*e;if(n>1){let e=r[r.length-2];for(;r.length>9;)r.shift();if(i&&!e.ok)return s}return function(e){e.sort();let{length:t}=e,r=t>>1;return t%2==1?e[r]:(e[r-1]+e[r])/2}(r.filter(({ok:e})=>e).map(({duration:e})=>e))/a|0}(s,i,e),a?.(eA(e)?"Last connection errored. Sleeping for":"More than one outstanding connection ("+n+"). Sleeping for",s,"ms")):s=0;let c=Math.min(i.maxDelayMs,Math.max(i.minDelayMs,s));if(void 0!==r){let e=Date.now()-r;if(c>e&&(await Promise.race([o(c-e),t.promise]),this.#l))break}n++,(async()=>{var s;let o=Date.now(),l,u;try{r=o,a?.("Sending request"),this.#a=_(),l=await i.invokeSend(),a?.("Send returned",l)}catch(e){a?.("Send failed",e),u=e,l=!1}if(this.#l)return a?.("Closed after invokeSend");a?.("Request done",{duration:Date.now()-o,ok:l}),e.push({duration:Date.now()-o,ok:l}),(s=e).length>1&&!s[s.length-2].ok&&s[s.length-1].ok&&(t.resolve(),t=_()),n--,this.#p();let c=this.#s;this.#s=_(),u?c.resolve({error:u}):c.resolve(void 0),l||this.#i.resolve()})()}}#f=void 0;#p(){if(this.#f){let e=this.#f;this.#f=void 0,e()}}#d(){let{promise:e,resolve:t}=_();return this.#f=t,e}};function eO(){return Error("Closed")}function eA(e){return e.length>0&&!e[e.length-1].ok}var ej=Object.prototype.hasOwnProperty,eM=Object.hasOwn||((e,t)=>ej.call(e,t));function ez(e,t){if(e===t)return!0;
5if(typeof e!=typeof t)return!1;switch(typeof e){case"boolean":case"number":case"string":return!1}if(Array.isArray(e)){if(!Array.isArray(t)||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!ez(e[r],t[r]))return!1;return!0}if(null===e||null===t||Array.isArray(t))return!1;let r=0;for(let n in e)if(eM(e,n)){if(!ez(e[n],t[n]))return!1;r++}let n=0;for(let e in t)eM(t,e)&&n++;return r===n}function eF(e){}function eU(e){for(let t in e)if(eM(e,t)){let r=e[t];void 0!==r&&eF(r)}}function eL(e,t){var r,n;if(e===t)return 0;if(null===e)return -1;if(null===t)return 1;let i=eH(e),a=eH(t);return"string"==typeof i||"string"==typeof a?(r=String(i))===(n=String(a))?0:r<n?-1:1:i-a}function eH(e){return"string"==typeof e||"number"==typeof e?e:e.order}function eB(e){if(null!==e&&"string"!=typeof e&&"number"!=typeof e&&(eb(e),eU(e),"string"!=typeof e.order&&"number"!=typeof e.order))throw Error("Invalid cookie")}function*eV(...e){for(let t of e)yield*t}var eq=Promise.resolve(!0),eG=Promise.resolve(!1),eK=(Promise.resolve(void 0),Promise.resolve());function eJ(e){switch(typeof e){case"string":return 5+e.length;case"number":var t;return(t=e)===(0|t)?e<=-0x40000000||e>=0x40000000-1?6:5:9;case"boolean":return 1;case"object":if(null===e)return 1;if(Array.isArray(e)){let t=6;for(let r of e)t+=eJ(r);return t}{let t=6;for(let r in e)if(eM(e,r)){let n=e[r];void 0!==n&&(t+=eJ(r)+eJ(n))}return t}}throw Error(`Invalid value. type: ${typeof e}, value: ${e}`)}function eW(e,t){return 11+eJ(e)+eJ(t)}new WeakSet;function eZ(e){}function eQ(e){if(void 0!==e)return e}function eY(e){if(Array.isArray(e)){e.sort();for(let t=1;t<e.length;t++)ef(e[t-1]!==e[t],"Refs must not have duplicates");return e}let t=[...e];return t.sort(),t}var eX=class{hash;data;meta;constructor(e,t,r){ef(!r.includes(e),"Chunk cannot reference itself"),eZ(t),this.hash=e,this.data=t,this.meta=r}};function e0(e){if(!Array.isArray(e))throw Error("Refs must be an array");if(e.length>0){em(e[0]);for(let t=1;t<e.length;t++)em(e[t])}}function e1(){throw Error("unexpected call to compute chunk hash")}function e2(){let e=Math.floor(0xffffffff*Math.random());return BigInt(Math.floor(0xffffffff*Math.random()))<<32n|BigInt(e)}var e5={},e3={assert:()=>tt,is:()=>te,parse:()=>e7,readonly:()=>tn,readonlyArray:()=>ta,readonlyObject:()=>ti,readonlyRecord:()=>ts,test:()=>tr};for(var e4 in e3)eu(e5,e4,{get:e3[e4],enumerable:!0});function e6(e){switch(typeof e){case"string":case"number":case"boolean":return JSON.stringify(e);case"undefined":return"undefined";case"bigint":return e.toString()+"n";default:return null===e?"null":Array.isArray(e)?"array":typeof e}}function e9(e,t){if(!t?.length)return e6(e);let r=e;for(let e of t)r=r[e];return e6(r)}function e8(e,t,r=e=>String(e)){if(1===t.length)return r(t[0]);let n=`${r(t[t.length-2])} ${e} ${r(t[t.length-1])}`;return 2===t.length?n:`${t.slice(0,-2).map(r).join(", ")}, ${n}`}function e7(e,t,r){let n=tr(e,t,r);if(!n.ok)throw TypeError(n.error);return n.value}function te(e,t,r){return tr(e,t,r).ok}function tt(e,t,r){e7(e,t,r)}function tr(e,t,r){let n=t.try(e,r?{mode:r}:void 0);return n.ok?n:{ok:!1,error:function(e,t){let r=e.issues[0],{path:n}=r,i=n?.length?` at ${n.join(".")}`:"";switch(r.code){case"invalid_type":return`Expected ${e8("or",r.expected)}${i}. Got ${e9(t,n)}`;case"missing_value":{let e=n&&n.length>1?` at ${n.slice(0,-1).join(".")}`:"";return r.path?.length?`Missing property ${r.path.at(-1)}${e}`:`TODO Unknown missing property${e}`}case"invalid_literal":return`Expected literal value ${e8("or",r.expected,e6)}${i} Got ${e9(t,n)}`;case"invalid_length":return`Expected array with length ${r.minLength===r.maxLength?r.minLength:`between ${r.minLength} and ${r.maxLength}`}${i}. Got array with length ${t.length}`;case"unrecognized_keys":return 1===r.keys.length?`Unexpected property ${r.keys[0]}${i}`:`Unexpected properties ${e8("and",r.keys)}${i}`;case"invalid_union":return`Invalid union value${i}`;case"custom_error":{let{error:e}=r;return`${e?"string"==typeof e?e:e.message??"unknown":"unknown"}${i}. Got ${e9(t,n)}`}}}(n,e)}}function tn(e){return e}function ti(e){return el.object(e)}function ta(e){return el.array(e)}function ts(e){return el.record(e)}((e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of eh(t))ed.call(e,i)||i===r||eu(e,i,{get:()=>t[i],enumerable:!(n=ec(t,i))||n.enumerable});return})(e5,el,"default");var to=/^[0-9a-v-]+$/,tl="0".repeat(22),tu=(n="",i=0,()=>{n||(n=tc(e2(),12));
5let e=tc(i++,10);return n+e});function tc(e,t){return e.toString(32).slice(-t).padStart(t,"0")}function th(e){e7(e,td,void 0)}var td=e5.string().assert(function(e){return"string"==typeof e&&to.test(e)},"Invalid hash");function tp(e,t,r){return new tf(e,t,r).compute()}var tf=class{#i;#a;#s;#o;#l;#u;#c;#h;constructor(e,t,r){let n=[],i=[];for(let t of e)t.old!==t.new&&(t.old&&i.push(t.old),t.new&&n.push(t.new));this.#i=n,this.#a=i,this.#s=t,this.#o=r,this.#u=new Map,this.#c=new Map,this.#h=void 0!==r.areRefsCounted,this.#l=this.#h?new Set:null}async compute(){for(let e of this.#i)await this.#f(e,1);if(await Promise.all(Array.from(this.#s.values(),e=>this.#d(e))),this.#h){let e;ef(this.#o.areRefsCounted),ef(this.#l);do for(let t of(e=!1,this.#s.values()))if(!this.#o.areRefsCounted(t)&&!this.#l.has(t)&&0!==this.#u.get(t)){await this.#p(t,1),e=!0;break}while(e)}for(let e of this.#a)await this.#f(e,-1);return this.#u}async #f(e,t){await this.#d(e),this.#m(e,t)&&await this.#p(e,t)}async #p(e,t){if(e===tl)return;let r=await this.#o.getRefs(e);if(void 0!==r){this.#l?.add(e);let n=r.map(e=>this.#f(e,t));await Promise.all(n)}}#d(e){let t=this.#c.get(e);return void 0===t&&(t=(async()=>{let t=await this.#o.getRefCount(e)||0;return this.#u.set(e,t),t})(),this.#c.set(e,t)),t}#m(e,t){let r=this.#u.get(e);return eg(r),this.#u.set(e,r+t),0===r&&1===t||1===r&&-1===t}},tm=class extends Error{name="ChunkNotFoundError";hash;constructor(e){super(`Chunk not found ${e}`),this.hash=e}};async function tg(e,t){let r=await e.getChunk(t);if(r)return r;throw new tm(t)}async function ty(e,t){let r=await t.getHead(e);return ef(r,`Missing head ${e}`),r}var tb=class{#i=new S;#a=new Map;#s;#o;#l;t=new Map;n;h=new Map;m=new Map;constructor(e,t,r,n,i=eJ){this.n=new t_(t,i,this.h,this.m),this.#s=e,this.#o=r,this.#l=n}async read(){let e=await this.#i.read();return new tw(this.#a,this.t,this.n,this.#s,e,this.#l)}async write(){let e=await this.#i.write();return new tv(this.#a,this.t,this.n,this.#s,this.h,this.m,e,this.#o,this.#l)}close(){return eK}isCached(e){return void 0!==this.n.getWithoutUpdatingLRU(e)}withSuspendedSourceCacheEvictsAndDeletes(e){return this.n.withSuspendedEvictsAndDeletes(e)}},tw=class{a;t;n;f;#i=void 0;#a;#s=!1;assertValidHash;constructor(e,t,r,n,i,a){this.a=e,this.t=t,this.n=r,this.f=n,this.#a=i,this.assertValidHash=a}isMemOnlyChunkHash(e){return this.t.has(e)}async hasChunk(e){return await this.getChunk(e)!==void 0}async getChunk(e){let t=this.t.get(e);if(void 0!==t)return t;let r=this.n.get(e);return void 0===r&&void 0!==(r=await (await this.y()).getChunk(e))&&this.n.put(r),r}mustGetChunk(e){return tg(this,e)}getHead(e){return Promise.resolve(this.a.get(e))}release(){this.#s||(this.#a(),this.#i?.then(e=>e.release()).catch(e=>{}),this.#s=!0)}get closed(){return this.#s}y(){return this.#i||(this.#i=this.f.read()),this.#i}},tv=class extends tw{#i;#a;#s;i=new Map;o=new Map;s=new Map;#o=new Set;constructor(e,t,r,n,i,a,s,o,l){super(e,t,r,n,s,l),this.#i=i,this.#a=a,this.#s=o}createChunk=(e,t)=>{let r=new eX((0,this.#s)(),e,t);return this.#o.add(r.hash),r};putChunk(e,t){let{hash:r,meta:n}=e;if(this.assertValidHash(r),n.length>0)for(let e of n)this.assertValidHash(e);return this.#o.has(r)||this.isMemOnlyChunkHash(r)?this.o.set(r,e):this.s.set(r,{chunk:e,size:t??-1}),eK}async setHead(e,t){await this.#l(e,t)}async removeHead(e){await this.#l(e,void 0)}async #l(e,t){let r=await this.getHead(e),n=this.i.get(e);void 0===n?this.i.set(e,{new:t,old:r}):n.new=t}isMemOnlyChunkHash(e){return this.o.has(e)||super.isMemOnlyChunkHash(e)}async getChunk(e){let t=this.o.get(e);if(void 0!==t)return t;let r=this.t.get(e);if(void 0!==r)return r;let n=this.s.get(e);if(void 0!==n)return n.chunk;let i=this.n.get(e);return void 0===i&&void 0!==(i=await (await this.y()).getChunk(e))&&this.s.set(i.hash,{chunk:i,size:-1}),i}getHead(e){let t=this.i.get(e);return t?Promise.resolve(t.new):super.getHead(e)}async commit(){let e=new Set(eV(this.o.keys(),this.s.keys())),t=await tp(this.i.values(),e,this);for(let[e,r]of t)if(this.isMemOnlyChunkHash(e)){if(0===r)this.#i.delete(e),this.t.delete(e),this.#a.delete(e);else{this.#i.set(e,r);let t=this.o.get(e);t&&(this.#a.set(e,t.meta),this.t.set(e,t))}t.delete(e)}for(let[e,r]of(this.n.updateForCommit(this.s,t),this.i))r.new?this.a.set(e,r.new):this.a.delete(e);this.o.clear(),this.s.clear(),this.i.clear(),this.release()}getRefCount(e){return this.#i.get(e)}
5getRefs(e){let t=this.o.get(e);if(t)return t.meta;let r=this.t.get(e);if(r)return r.meta;let n=this.s.get(e);return void 0!==n?n.chunk.meta:this.#a.get(e)}areRefsCounted(e){return this.#a.has(e)}chunksPersisted(e){let t=[];for(let r of e){let e=this.t.get(r);e&&(this.t.delete(r),t.push(e))}this.n.persisted(t)}},t_=class{#i;#a;#s;#o;#l=0;#u=!1;#c=[];cacheEntries=new Map;constructor(e,t,r,n){this.#i=e,this.#a=t,this.#s=r,this.#o=n}get(e){let t=this.cacheEntries.get(e);return t&&(this.cacheEntries.delete(e),this.cacheEntries.set(e,t)),t?.chunk}getWithoutUpdatingLRU(e){return this.cacheEntries.get(e)?.chunk}put(e){let{hash:t}=e,r=this.cacheEntries.get(t);if(r){this.cacheEntries.delete(t),this.cacheEntries.set(t,r);return}let n=this.#s.get(t);if(!(void 0===n||n<1)&&this.#f(e)){if(!this.#o.has(t)){for(let t of e.meta)this.#s.set(t,(this.#s.get(t)||0)+1);this.#o.set(t,e.meta)}this.#h()}}#h(){if(!this.#u)for(let e of this.cacheEntries.values()){if(this.#l<=this.#i)break;this.#p(e)}}#f(e,t){let r=t??this.#a(e);return!(r>this.#i)&&(this.#l+=r,this.cacheEntries.set(e.hash,{chunk:e,size:r}),!0)}#p(e){let{hash:t}=e.chunk;this.#l-=e.size,this.cacheEntries.delete(t)}#d(e){this.#s.delete(e),this.#o.delete(e);let t=this.cacheEntries.get(e);t&&(this.#l-=t.size,this.cacheEntries.delete(e))}updateForCommit(e,t){for(let[r,n]of t)if(0===n)this.#u?(this.#s.set(r,0),this.#c.push(r)):this.#d(r);else{this.#s.set(r,n);let t=e.get(r);if(t){let{chunk:e,size:n}=t,i=this.cacheEntries.get(r);i?(this.cacheEntries.delete(r),this.cacheEntries.set(r,i)):(this.#f(e,-1!==n?n:void 0),this.#o.set(r,e.meta))}}this.#h()}persisted(e){for(let t of e)this.#f(t);this.#h()}async withSuspendedEvictsAndDeletes(e){this.#u=!0;try{return await e()}finally{for(let e of(this.#u=!1,this.#c))0===this.#s.get(e)&&this.#d(e);this.#h()}}};function tk(e){return`c/${e}/d`}function tS(e){return`c/${e}/m`}function tI(e){return`c/${e}/r`}var tx=class{#i;#a;#s;constructor(e,t,r){this.#i=e,this.#a=t,this.#s=r}async read(){return new tD(await this.#i.read(),this.#s)}async write(){return new tE(await this.#i.write(),this.#a,this.#s)}close(){return this.#i.close()}},tD=class{e;assertValidHash;constructor(e,t){this.e=e,this.assertValidHash=t}hasChunk(e){return this.e.has(tk(e))}async getChunk(e){let t=await this.e.get(tk(e));if(void 0===t)return;let r=await this.e.get(tS(e)),n;return void 0!==r?(e0(r),n=r):n=[],new eX(e,t,n)}mustGetChunk(e){return tg(this,e)}async getHead(e){let t=await this.e.get(`h/${e}`);if(void 0!==t)return th(t),t}release(){this.e.release()}get closed(){return this.e.closed}},tE=class extends tD{#i;#a=new Set;#s=new Map;constructor(e,t,r){super(e,r),this.#i=t}createChunk=(e,t)=>new eX((0,this.#i)(),e,t);get kvWrite(){return this.e}async putChunk(e){let{hash:t,data:r,meta:n}=e;this.assertValidHash(t);let i=tk(t),a=this.e.put(i,r),s;if(n.length>0){for(let e of n)this.assertValidHash(e);s=this.e.put(tS(t),n)}this.#a.add(t),await a,await s}setHead(e,t){return this.#o(e,t)}removeHead(e){return this.#o(e,void 0)}async #o(e,t){let r=await this.getHead(e),n=`h/${e}`,i;i=void 0===t?this.e.del(n):this.e.put(n,t);let a=this.#s.get(e);void 0===a?this.#s.set(e,{new:t,old:r}):a.new=t,await i}async commit(){let e=await tp(this.#s.values(),this.#a,this);await this.#l(e),await this.e.commit()}async getRefCount(e){let t=await this.e.get(tI(e));if(void 0!==t){if(eg(t),t<0||t>65535||t!==(0|t))throw Error(`Invalid ref count ${t}. We expect the value to be a Uint16`);return t}}async getRefs(e){let t=await this.e.get(tS(e));return void 0===t?[]:(e0(t),t)}async #l(e){let t=[];for(let[r,n]of e)if(0===n)t.push(this.#u(r));else{let e=tI(r);t.push(this.e.put(e,n))}await Promise.all(t)}async #u(e){await Promise.all([this.e.del(tk(e)),this.e.del(tS(e)),this.e.del(tI(e))]),this.#a.delete(e)}release(){this.e.release()}},tN="main";function t$(e){return tq(e.meta)}function tC(e){return 5===e.meta.type||3===e.meta.type}var tT=class{chunk;constructor(e){this.chunk=e}get meta(){return this.chunk.data.meta}get valueHash(){return this.chunk.data.valueHash}getMutationID(e,t){return tP(e,t,this.meta)}async getNextMutationID(e,t){return await this.getMutationID(e,t)+1}get indexes(){return this.chunk.data.indexes}};async function tP(e,t,r){switch(r.type){case 1:case 3:return r.lastMutationID;case 5:return r.lastMutationIDs[e]??0;case 2:return r.mutationID;case 4:{if(r.clientID===e)return r.mutationID;let{basisHash:n}=r,i=await tB(n,t);return tP(e,t,i.meta)}default:ek(r)}}async function tR(e,t){return(await tH(e,t)).filter(e=>{var t;return t$(t=e)||tG(t.meta)})}async function tO(e,t){return(await tH(e,t)).filter(e=>t$(e))}async function tA(e,t,r){let n=[],i=new Map(Object.entries(t));for(;!tC(e)&&i.size>0;){if(t$(e)){let{meta:t}=e,r=i.get(t.clientID);void 0!==r&&(t.mutationID<=r?i.delete(t.clientID):n.push(e))}let{basisHash:t}=e.meta;if(null===t)throw Error(`Commit ${e.chunk.hash} has no basis`);e=await tB(t,r)}return n}async function tj(e,t){let r=await t.getHead(e);return ef(r,`Missing head ${e}`),tz(r,t)}async function tM(e,t){return(await tz(e,t)).chunk.hash}async function tz(e,t){return tF(await tB(e,t),t)}async function tF(e,t){for(;!tC(e);){let{meta:r}=e;if(tq(r))e=await tB(r.baseSnapshotHash,t);else{let{basisHash:n}=r;if(null===n)throw Error(`Commit ${e.chunk.hash} has no basis`);e=await tB(n,t)}}return e}function tU(e,t){let r=e.meta;return 5===r.type?[r.lastMutationIDs[t]??0,r.cookieJSON]:[r.lastMutationID,r.cookieJSON]}function tL(e,t){return eL(e.meta.cookieJSON,t.meta.cookieJSON)}async function tH(e,t){let r=await tB(e,t),n=[];for(;!tC(r);){let{meta:e}=r,{basisHash:i}=e;if(null===i)throw Error(`Commit ${r.chunk.hash} has no basis`);n.push(r),r=await tB(i,t)}return n.push(r),n}async function tB(e,t){var r;return function(e){let{data:t}=e,r=new Set;for(let e of t.indexes){let{name:t}=e.definition;if(r.has(t))throw Error(`Duplicate index ${t}`);r.add(t)}}(r=await t.mustGetChunk(e)),new tT(r)}async function tV(e,t){return tB(await ty(e,t),t)}function tq(e){return 4===e.type}function tG(e){return 2===e.type}function tK(e){var t;null!==(t=e).basisHash&&th(t.basisHash),eF(t.cookieJSON),function(e){for(let t of(eb(e),Object.values(e)))eg(t)}(e.lastMutationIDs)}function tJ(e){tK(e.meta)}function tW(e,t,r,n,i){return tY({type:5,basisHash:e,lastMutationIDs:t,cookieJSON:r},n,i)}function tZ(e,t){return new tT(e(t,tQ(t)))}function tQ(e){let t=new Set;t.add(e.valueHash);let{meta:r}=e;switch(r.type){case 1:case 2:case 4:r.basisHash&&t.add(r.basisHash);break;case 3:case 5:break;default:ek(r)}for(let r of e.indexes)t.add(r.valueHash);return eY(t)}function tY(e,t,r){return{meta:e,valueHash:t,indexes:r}}function tX(e,t){let r=e.length,n=t.length,i=Math.min(r,n);for(let r=0;r<i;){let n=e.codePointAt(r),i=t.codePointAt(r);if(n!==i){if(n<128&&i<128)return n-i;let e=t5(n,t1),t=t5(i,t2);return function(e,t,r,n){let i=Math.min(t,n);for(let t=0;t<i;t++){let n=e[t],i=r[t];if(n!==i)return n-i}return t-n}(t1,e,t2,t)}r+=n>65535?2:1}return r-n}var t0=()=>Array.from({length:4},()=>0),t1=t0(),t2=t0();function t5(e,t){let r,n;if(e<128)return t[0]=e,1;if(e<=2047)r=1,n=192;else if(e<=65535)r=2,n=224;else if(e<=1114111)r=3,n=240;else throw Error("Invalid code point");t[0]=(e>>6*r)+n;let i=1;for(;r>0;r--){let n=e>>6*(r-1);t[i++]=128|63&n}return i}function t3(e,t){let r=0;for(;r<e;){let n=r+(e-r>>1),i=t(n);if(0===i)return n;i>0?r=n+1:e=n}return r}function t4(e){if(e!==(0|e)||e<4||e>7)throw Error(`Unsupported format version: ${e}`);return e}function t6(e,t,r){return[e,r>=7?t:t.map(e=>e.slice(0,2))]}async function t9(e,t,r,n){let i=await r.getNode(t);if(n!==r.rootHash)return t9(e,r.rootHash,r,r.rootHash);if(ro(i))return i;let{entries:a}=i,s=t8(e,a);return s===a.length&&s--,t9(e,a[s][1],r,n)}function t8(e,t){return t3(t.length,r=>tX(e,t[r][0]))}function t7(e,t,r){return e!==t.length&&t[e][0]===r}function re(e,t,r){if(t>=7)return e;ew(e),eZ(e),ef(e.length>=2);let[n,i]=e;eg(n),ew(i);let a=n>0?em:eF;if(t>=7){for(let e of i){var s,o;s=e,o=a,ew(s),ef(s.length>=3),em(s[0]),o(s[1]),eg(s[2])}return e}return[n,i.map(e=>{var t,n,i;let s;return t=e,n=a,i=r,ew(t),ef(t.length>=2),em(t[0]),n(t[1]),s=i(t[0],t[1]),[t[0],t[1],s]})]}var rt=class{entries;hash;isMutable;#i=-1;constructor(e,t,r){this.entries=e,this.hash=t,this.isMutable=r}maxKey(){return this.entries[this.entries.length-1][0]}getChildNodeSize(e){if(-1!==this.#i)return this.#i;let t=e.chunkHeaderSize;
5for(let e of this.entries)t+=e[2];return this.#i=t}c(e){this.#i=-1,e.updateNode(this)}};function rr(e,t){return t6(e.level,e.entries,t)}var rn=class extends rt{level=0;set(e,t,r,n){let i,a=t8(e,this.entries);return i=+!!t7(a,this.entries,e),Promise.resolve(this.#i(n,a,i,[e,t,r]))}#i(e,t,r,...n){if(this.isMutable)return this.entries.splice(t,r,...n),this.c(e),this;let i=ri(this.entries,t,r,...n);return e.newDataNodeImpl(i)}del(e,t){let r=t8(e,this.entries);return t7(r,this.entries,e)?Promise.resolve(this.#i(t,r,1)):Promise.resolve(this)}async *keys(e){for(let e of this.entries)yield e[0]}async *entriesIter(e){for(let e of this.entries)yield e}};function ri(e,t,r,...n){let i=e.slice(0,t);for(let e=0;e<n.length;e++)i.push(n[e]);for(let n=t+r;n<e.length;n++)i.push(e[n]);return i}var ra=class e extends rt{level;constructor(e,t,r,n){super(e,t,n),this.level=r}async set(e,t,r,n){let i=t8(e,this.entries);i===this.entries.length&&i--;let a=this.entries[i][1],s=await (await n.getNode(a)).set(e,t,r,n),o=s.getChildNodeSize(n);if(o>n.maxSize||o<n.minSize)return this.#i(n,i,s);let l=rh(s,n.getEntrySize);return this.#a(n,i,l)}async #i(e,t,r){let n=this.level-1,i=this.entries,a,s,o;if(t>0){let n=i[t-1][1];a=eV((await e.getNode(n)).entries,r.entries),s=t-1,o=2}else if(t<i.length-1){let n=i[t+1][1],l=await e.getNode(n);a=eV(r.entries,l.entries),s=t,o=2}else a=r.entries,s=t,o=1;let l=rl(a,e=>e[2],e.minSize-e.chunkHeaderSize,e.maxSize-e.chunkHeaderSize),u=[];for(let t of l){let r=rh(e.newNodeImpl(t,n),e.getEntrySize);u.push(r)}if(this.isMutable)return this.entries.splice(s,o,...u),this.c(e),this;let c=ri(i,s,o,...u);return e.newInternalNodeImpl(c,this.level)}#a(e,t,r){if(this.isMutable)return this.entries.splice(t,1,r),this.c(e),this;let n=ri(this.entries,t,1,r);return e.newInternalNodeImpl(n,this.level)}async del(e,t){let r=t8(e,this.entries);if(r===this.entries.length)return this;let n=this.entries[r][1],i=await t.getNode(n),a=i.hash,s=await i.del(e,t);if(s.hash===a)return this;if(0===s.entries.length){let e=ri(this.entries,r,1);return t.newInternalNodeImpl(e,this.level)}if(0===r&&1===this.entries.length)return s;if(s.getChildNodeSize(t)>t.minSize){let e=rh(s,t.getEntrySize);return this.#a(t,r,e)}return this.#i(t,r,s)}async *keys(e){for(let t of this.entries)yield*(await e.getNode(t[1])).keys(e)}async *entriesIter(e){for(let t of this.entries)yield*(await e.getNode(t[1])).entriesIter(e)}getChildren(e,t,r){let n=[];for(let i=e;i<t&&i<this.entries.length;i++)n.push(r.getNode(this.entries[i][1]));return Promise.all(n)}async getCompositeChildren(t,r,n){let{level:i}=this;if(0===r)return new e([],tu(),i-1,!0);let a=await this.getChildren(t,t+r,n);if(i>1){let t=[];for(let e of a)t.push(...e.entries);return new e(t,tu(),i-1,!0)}ef(1===i);let s=[];for(let e of a)s.push(...e.entries);return new rn(s,tu(),!0)}};function rs(e,t,r,n){return 0===r?new rn(e,t,n):new ra(e,t,r,n)}function ro(e){return 0===e.level}function rl(e,t,r,n){let i=[],a=[],s=0,o=[];for(let l of e){let e=t(l);e>=n?(o.length>0&&(i.push(o),a.push(s)),i.push([l]),a.push(e),s=0,o=[]):s+e>=r?(o.push(l),i.push(o),a.push(s+e),s=0,o=[]):(s+=e,o.push(l))}return s>0&&(a.length>0&&s+a[a.length-1]<=n?i[i.length-1].push(...o):i.push(o)),i}var ru=t6(0,[],7),rc=new rn([],tl,!1);function rh(e,t){let r=e.maxKey(),n=e.hash,i=t(r,n);return[r,n,i]}var rd=class{p=new Map;l;u;rootHash;getEntrySize;chunkHeaderSize;constructor(e,t,r=tl,n=eW,i=11){this.l=e,this.u=t,this.rootHash=r,this.getEntrySize=n,this.chunkHeaderSize=i}async getNode(e){if(e===tl)return rc;let t=this.p.get(e);if(t)return t;let r=re((await this.l.mustGetChunk(e)).data,this.u,this.getEntrySize),n=rs(r[1],e,r[0],!1);return this.p.set(e,n),n}async get(e){let t=await t9(e,this.rootHash,this,this.rootHash),r=t8(e,t.entries);if(t7(r,t.entries,e))return t.entries[r][1]}async has(e){let t=await t9(e,this.rootHash,this,this.rootHash);return t7(t8(e,t.entries),t.entries,e)}async isEmpty(){let{rootHash:e}=this,t=await this.getNode(this.rootHash);return this.rootHash!==e?this.isEmpty():0===t.entries.length}scan(e){return rf(this.rootHash,()=>this.rootHash,this.rootHash,e,async e=>{let t=await this.getNode(e);return t?[t.level,t.isMutable?t.entries.slice():t.entries]:re((await this.l.mustGetChunk(e)).data,this.u,this.getEntrySize)})}async *keys(){yield*(await this.getNode(this.rootHash)).keys(this)}
5async *entries(){yield*(await this.getNode(this.rootHash)).entriesIter(this)}[Symbol.asyncIterator](){return this.entries()}async *diff(e){let[t,r]=await Promise.all([this.getNode(this.rootHash),e.getNode(e.rootHash)]);yield*rp(r,t,e,this)}};async function*rp(e,t,r,n){if(e.level>t.level){let i=await e.getCompositeChildren(0,e.entries.length,r);yield*rp(i,t,r,n);return}if(t.level>e.level){let i=await t.getCompositeChildren(0,t.entries.length,n);yield*rp(e,i,r,n);return}if(ro(e)&&ro(t))return void(yield*function*(e,t){let r=e.length,n=t.length,i=0,a=0;for(;i<r&&a<n;){let r=e[i][0],n=t[a][0];r===n?(ez(e[i][1],t[a][1])||(yield{op:"change",key:r,oldValue:e[i][1],newValue:t[a][1]}),i++,a++):r<n?(yield{op:"del",key:r,oldValue:e[i][1]},i++):(yield{op:"add",key:n,newValue:t[a][1]},a++)}for(;i<r;i++)yield{op:"del",key:e[i][0],oldValue:e[i][1]};for(;a<n;a++)yield{op:"add",key:t[a][0],newValue:t[a][1]}}(e.entries,t.entries));for(let i of function*(e,t){let r=0,n=0,i;function a(e,t){-1===e[3]&&(e[3]=t)}function s(){return[r,0,0,-1]}for(;r<e.length&&n<t.length;)e[r][0]===t[n][0]?(ez(e[r][1],t[n][1])?i&&(a(i,0),yield i,i=void 0):(i||(i=s()),i[2]++,i[1]++,a(i,n)),r++,n++):e[r][0]<t[n][0]?(i||(i=s()),i[1]++,r++):(i||(i=s()),i[2]++,a(i,n),n++);n<t.length&&(i||(i=s()),i[2]+=t.length-n,a(i,n)),r<e.length&&(i||(i=s()),i[1]+=e.length-r),i&&(a(i,0),yield i)}(e.entries,t.entries)){let[a,s]=await Promise.all([e.getCompositeChildren(i[0],i[1],r),t.getCompositeChildren(i[3],i[2],n)]);yield*rp(a,s,r,n)}}async function*rf(e,t,r,n,i){if(r===tl)return;let a=await i(r),s=a[1],o=0;if(n&&(o=t8(n,s)),a[0]>0)for(;o<s.length;o++)yield*rf(e,t,s[o][1],n,i),n="";else for(;o<s.length;o++){let r=t();if(e!==r)return void(yield*rf(r,t,r,s[o][0],i));yield s[o]}}async function rm(e,t){let r=[],n="add"===t?e=>({op:"add",key:e[0],newValue:e[1]}):e=>({op:"del",key:e[0],oldValue:e[1]});for await(let t of e.entries())r.push(n(t));return r}var rg=class{meta;map;constructor(e,t){this.meta=e,this.map=t}},ry=class extends rg{flush(){return this.map.flush()}clear(){return this.map.clear()}};async function rb(e,t,r,n,i,a,s){try{for(let e of function(e,t,r,n){let i=function(e,t){if(""===t)return e;if(!t.startsWith("/"))throw Error(`Invalid JSON pointer: ${t}`);let r=t.split("/").slice(1).map(e=>e.replace(/~1/g,"/").replace(/~0/g,"~")),n=e;for(let e of r){let t;if(Array.isArray(n)){let r=function(e){if(!(e.startsWith("+")||e.startsWith("0")&&1!==e.length))return parseInt(e,10)}(e);if(void 0===r)return;t=n[r]}else{if(null===n)return;"object"==typeof n&&(t=n[e])}if(void 0===t)return;n=t}return n}(t,r);if(void 0===i){if(n)return[];throw Error(`No value at path: ${r}`)}let a=Array.isArray(i)?i:[i],s=[];for(let t of a)if("string"==typeof t)s.push(rw([t,e]));else throw Error("Unsupported target type");return s}(n,i,a,s))switch(r){case 0:await t.put(e,i);break;case 1:await t.del(e)}}catch(t){e.info?.("Not indexing value",i,":",t)}}function rw(e){let t=e[0],r=e[1];if(t.includes("\0"))throw Error("Secondary key cannot contain null byte");return"\0"+t+"\0"+r}function rv(e,t){let r=rw([e,t||""]);return void 0===t?r.slice(0,r.length-1):r}function r_(e){if("\0"!==e[0])throw Error("Invalid version");let t=e.indexOf("\0",1);if(-1===t)throw Error("Invalid formatting");return[e.slice(1,t),e.slice(t+1)]}var rk=class{#i;map;indexes;constructor(e,t,r){this.#i=e,this.map=t,this.indexes=r}has(e){return this.map.has(e)}get(e){return this.map.get(e)}isEmpty(){return this.map.isEmpty()}getMapForIndex(e){let t=this.indexes.get(e);if(void 0===t)throw Error(`Unknown index name: ${e}`);return t.map}get closed(){return this.#i.closed}close(){this.#i.release()}};async function rS(e,t,r){var n,i,a;let s,o;return n=await tV(e,t),s=rI(n,i=t,a=r),o=new rd(i,a,n.valueHash),new rk(i,o,s)}function rI(e,t,r){let n=new Map;for(let i of e.indexes)n.set(i.definition.name,new rg(i,new rd(t,r,i.valueHash)));return n}async function rx(e){let t=[];for await(let r of e)t.push(r);return t}function rD(e){return void 0!==e.indexName}function rE(e){return"string"==typeof e?[e]:e}var rN=class extends Error{constructor(){super("Transaction is closed")}};function r$(e){if(e.closed)throw new rN}function rC(e){return e.closed?Promise.reject(new rN):void 0}var rT=class{#i;#a;#s;#o;constructor(e,t,r,n){this.#i=e,this.#a=t,this.#s=r,this.#o=n}[Symbol.asyncIterator](){return this.values()}values(){return new rP(this.#l(e=>e[1]))}keys(){return new rP(this.#l(e=>e[0]))}entries(){return new rP(this.#l(e=>[e[0],e[1]]))}toArray(){return this.values().toArray()}#l(e){return rR(e,this.#i,this.#a,this.#s,this.#o)}},rP=class{#i;constructor(e){this.#i=e}next(){return this.#i.next()}[Symbol.asyncIterator](){return this.#i[Symbol.asyncIterator]()}toArray(){return rx(this.#i)}};async function*rR(e,t,r,n,i){r$(n);let{limit:a=1/0}=r,{prefix:s=""}
5=r,o=r.start?.exclusive,l=rD(r);for await(let n of t){let t=n[0];if(!(l?t[0]:t).startsWith(s))return;if(o){if(o=!0,l){if(function(e,t){let[r,n]=rE(t),[i,a]=rE(e);return i===r&&(void 0===n||a===n)}(t,r.start.key))continue}else if(t===r.start.key)continue}if(yield e(n),0==--a){l||i(t);return}}}var rO=0,rA=class{clientID;dbtx;d;location;environment;constructor(e,t,r,n="openReadTransaction"){this.clientID=e,this.dbtx=t,this.d=r.withContext(n).withContext("txid",rO++),this.environment="client",this.location="client"}get(e){return rC(this.dbtx)||this.dbtx.get(e)}async has(e){return r$(this.dbtx),this.dbtx.has(e)}async isEmpty(){return r$(this.dbtx),this.dbtx.isEmpty()}scan(e){return rM(e,this.dbtx,rj)}};function rj(e){}function rM(e,t,r){var n,i,a;return a=(n=t,(i=e)&&rD(i)?rU(n,i):n.map.scan(function(e){if(!e)return"";let{prefix:t="",start:r}=e;return r&&tX(r.key,t)>0?r.key:t}(i))),new rT(a,e??{},t,r)}var rz=class{#i=new Set;#a=[];#s;constructor(e){this.#s=e}get environment(){return this.#s.location}get location(){return this.#s.location}get clientID(){return this.#s.clientID}isEmpty(){return this.#a.push({options:{}}),this.#s.isEmpty()}get(e){return this.#i.add(e),this.#s.get(e)}has(e){return this.#i.add(e),this.#s.has(e)}scan(e){let t,r,n,i,a={options:e?(e.start&&({key:t,exclusive:r}=e.start,e.indexName?"string"==typeof t?i=t:(i=t[0],n=t[1]):n=t),{prefix:e.prefix,startSecondaryKey:i,startKey:n,startExclusive:r,limit:e.limit,indexName:e.indexName}):{},inclusiveLimitKey:void 0};return this.#a.push(a),rM(e,this.#s.dbtx,e=>{a.inclusiveLimitKey=e})}get keys(){return this.#i}get scans(){return this.#a}},rF=class extends rA{reason;mutationID;constructor(e,t,r,n,i,a="openWriteTransaction"){super(e,n,i,a),this.mutationID=t,this.reason=r}put(e,t){return this.set(e,t)}async set(e,t){r$(this.dbtx),await this.dbtx.put(this.d,e,t)}del(e){return rC(this.dbtx)??this.dbtx.del(this.d,e)}};async function*rU(e,t){for await(let r of e.getMapForIndex(t.indexName).scan(function(e){let{prefix:t,start:r}=e,n="";if(void 0!==t&&(n=rv(t,void 0)),!r)return n;let{key:i}=r,[a,s]=rE(i),o=rv(a,s);return tX(o,n)>0?o:n}(t)))yield[r_(r[0]),r[1]]}function rL(e,t){return rx(t.diff(e))}var rH=class extends rd{#i=new k;#a=new Map;minSize;maxSize;constructor(e,t,r=tl,n=8192,i=16384,a=eW,s){super(e,t,r,a,s),this.minSize=n,this.maxSize=i}#s(e){ef(e.isMutable),this.#a.set(e.hash,e),this.p.set(e.hash,e)}updateNode(e){ef(e.isMutable),this.#a.delete(e.hash),e.hash=tu(),this.#s(e)}newInternalNodeImpl(e,t){let r=new ra(e,tu(),t,!0);return this.#s(r),r}newDataNodeImpl(e){let t=new rn(e,tu(),!0);return this.#s(t),t}newNodeImpl(e,t){let r=rs(e,tu(),t,!0);return this.#s(r),r}put(e,t){return this.#i.withLock(async()=>{let r=await this.getNode(this.rootHash),n=this.getEntrySize(e,t),i=await r.set(e,t,n,this);if(i.getChildNodeSize(this)>this.maxSize){let e=this.chunkHeaderSize,t=rl(i.entries,e=>e[2],this.minSize-e,this.maxSize-e),{level:r}=i,n=t.map(e=>rh(this.newNodeImpl(e,r),this.getEntrySize)),a=this.newInternalNodeImpl(n,r+1);this.rootHash=a.hash;return}this.rootHash=i.hash})}del(e){return this.#i.withLock(async()=>{let t=await (await this.getNode(this.rootHash)).del(e,this),r=this.rootHash!==t.hash;return r&&(t.level>0&&1===t.entries.length?this.rootHash=t.entries[0][1]:this.rootHash=t.hash),r})}clear(){return this.#i.withLock(()=>{this.#a.clear(),this.rootHash=tl})}flush(){return this.#i.withLock(async()=>{let e=this.l;if(this.rootHash===tl){let t=e.createChunk(ru,[]);return await e.putChunk(t),t.hash}let t=[],r=function e(t,r,n,i,a){let s=i.get(t);if(void 0===s)return t;if(ro(s)){let e=n(rr(s,a),[]);return r.push(e),e.hash}let o=[],{entries:l}=s;for(let t=0;t<l.length;t++){let s=l[t],u=s[1],c=e(u,r,n,i,a);c!==u&&(l[t]=[s[0],c,s[2]]),o.push(c)}let u=n(rr(s,a),eY(o));return r.push(u),u.hash}(this.rootHash,t,e.createChunk,this.#a,this.u);return await Promise.all(t.map(t=>e.putChunk(t))),this.#a.clear(),this.rootHash=r,r})}};function rB(e){let t;return()=>(void 0===t&&(t=e()),t)}var rV=class extends Map{set(e,t){return 0===t.length?this:super.set(e,t)}};async function rq(e,t,r,n,i){let a=new rV;if(!n.shouldComputeDiffs())return a;let s=new rd(r,i,e.valueHash),o=new rd(r,i,t.valueHash),l=await rL(s,o);return a.set("",l),await rG(e,t,r,a,n,i),a}async function rG(e,t,r,n,i,a){let s=rI(e,r,a),o=rI(t,r,a);for(let[e,t]of s){if(!i.shouldComputeDiffsForIndex(e))continue;let r=o.get(e);if(void 0!==r){ef(r!==t);let i=await rL(t.map,r.map);o.delete(e),n.set(e,i)}else{let r=await rm(t.map,"del");n.set(e,r)}}for(let[e,t]of o){if(!i.shouldComputeDiffsForIndex(e))continue;let r=await rm(t.map,"add");n.set(e,r)}}var rK=class extends rk{#i;#a;#s;#o;#l;constructor(e,t,r,n,i,a,s){super(e,t,i),this.#i=e,this.#a=r,this.#s=n,this.#o=a,this.#l=s,void 0===r?ef(n.basisHash===tl):ef(n.basisHash===r.chunk.hash)}async put(e,t,r){if(1===this.#s.type)throw Error("Not allowed");let n=rB(()=>this.map.get(t));await rQ(e,this.indexes,t,n,r),await this.map.put(t,r)}getMutationID(){return tP(this.#o,this.#i,this.#s)}async del(e,t){if(1===this.#s.type)throw Error("Not allowed");let r=rB(()=>this.map.get(t));return void 0!==r&&await rQ(e,this.indexes,t,r,void 0),this.map.del(t)}async clear(){if(1===this.#s.type)throw Error("Not allowed");await this.map.clear();let e=[];for(let t of this.indexes.values())e.push(t.clear());await Promise.all(e)}async putCommit(){var e,t;let r=await this.map.flush(),n=[];for(let e of this.indexes.values()){let t=await e.flush(),r={definition:e.meta.definition,valueHash:t};n.push(r)}let i,a=this.#s;switch(a.type){case 2:{let{basisHash:e,mutationID:t,mutatorName:s,mutatorArgsJSON:o,originalHash:l,timestamp:u}=a;i=tZ(this.#i.createChunk,tY({type:2,basisHash:e,mutationID:t,mutatorName:s,mutatorArgsJSON:o,originalHash:l,timestamp:u},r,n));break}case 4:{ef(this.#l>=5);let{basisHash:s,mutationID:o,mutatorName:l,mutatorArgsJSON:u,originalHash:c,timestamp:h}=a;e=this.#i.createChunk,t=await tM(s,this.#i),i=tZ(e,tY({type:4,basisHash:s,baseSnapshotHash:t,mutationID:o,mutatorName:l,mutatorArgsJSON:u,originalHash:c,timestamp:h,clientID:this.#o},r,n));break}case 3:{ef(this.#l<=4);let{basisHash:e,lastMutationID:t,cookieJSON:s}=a;i=tZ(this.#i.createChunk,tY({type:3,basisHash:e,lastMutationID:t,cookieJSON:s},r,n));break}case 5:{ef(this.#l>5);let{basisHash:e,lastMutationIDs:t,cookieJSON:s}=a;i=tZ(this.#i.createChunk,tW(e,t,s,r,n));break}case 1:{let{basisHash:e,lastMutationID:t}=a;if(void 0!==this.#a){if(await this.#a.getMutationID(this.#o,this.#i)!==t)throw Error("Index change must not change mutationID");if(this.#a.valueHash!==r)throw Error("Index change must not change valueHash")}i=tZ(this.#i.createChunk,tY({type:1,basisHash:e,lastMutationID:t},r,n))}}return await this.#i.putChunk(i.chunk),i}async commit(e){let t=(await this.putCommit()).chunk.hash;return await this.#i.setHead(e,t),await this.#i.commit(),t}async commitWithDiffs(e,t){let r=this.putCommit(),n=await this.#u(t),i=(await r).chunk.hash;return await this.#i.setHead(e,i),await this.#i.commit(),n}async #u(e){let t,r=new rV;if(!e.shouldComputeDiffs())return r;let n=[];if(this.#a){let e=new rd(this.#i,this.#l,this.#a.valueHash);n=await rL(e,this.map)}for(let[i,a]of(r.set("",n),t=this.#a?rI(this.#a,this.#i,this.#l):new Map,this.indexes)){if(!e.shouldComputeDiffsForIndex(i))continue;let n=t.get(i);ef(a!==n);let s=await (n?rL(n.map,a.map):rm(a.map,"add"));r.set(i,s)}for(let[n,i]of t)if(!this.indexes.has(n)&&e.shouldComputeDiffsForIndex(n)){let e=await rm(i.map,"del");r.set(n,e)}return r}close(){this.#i.release()}};async function rJ(e,t,r,n,i,a,s,o){let l=await tB(e,i),u=new rH(i,o,l.valueHash),c=await l.getNextMutationID(s,i),h=rY(l,i,o);return new rK(i,u,l,o>=5?{type:4,basisHash:e,baseSnapshotHash:await tM(e,i),mutatorName:t,mutatorArgsJSON:r,mutationID:c,originalHash:n,timestamp:a,clientID:s}:{type:2,basisHash:e,mutatorName:t,mutatorArgsJSON:r,mutationID:c,originalHash:n,timestamp:a},h,s,o)}async function rW(e,t,r,n,i,a,s){ef(s<=4);let o=await tB(e,n),l=new rH(n,s,o.valueHash);return new rK(n,l,o,{basisHash:e,type:3,lastMutationID:t,cookieJSON:r},i,a,s)}async function rZ(e,t,r,n,i,a){let s=await tB(e,n),o=new rH(n,a,s.valueHash);return new rK(n,o,s,{basisHash:e,type:5,lastMutationIDs:t,cookieJSON:r},rY(s,n,a),i,a)}async function rQ(e,t,r,n,i){let a=[];for(let s of t.values()){let{keyPrefix:t}=s.meta.definition;if(!t||r.startsWith(t)){let t=await n();void 0!==t&&a.push(rb(e,s.map,1,r,t,s.meta.definition.jsonPointer,s.meta.definition.allowEmpty??!1)),void 0!==i&&a.push(rb(e,s.map,0,r,i,s.meta.definition.jsonPointer,s.meta.definition.allowEmpty??!1))}}await Promise.all(a)}function rY(e,t,r){let n=new Map;for(let i of e.indexes)n.set(i.definition.name,new ry(i,new rH(t,r,i.valueHash)));return n}async function rX(e,t,r,n,i,a,s){let o=new rH(t,s);for await(let t of r.scan(n)){let r=t[0];if(!r.startsWith(n))break;await rb(e,o,0,r,t[1],i,a)}return o}async function r0(e,t,r,n,i,a,s){var o;let l=e.meta,u=l.mutatorName;tq(l)&&ef(l.clientID===a,"mutationClientID must match clientID of LocalMeta");let c=n[u];c||i.error?.(`Cannot rebase unknown mutator ${u}`);let h=l.mutatorArgsJSON,d=await (await tB(r,t)).getNextMutationID(a,t);
5if(d!==l.mutationID)throw Error(`Inconsistent mutation ID: original: ${l.mutationID}, next: ${d} - mutationClientID: ${a} mutatorName: ${u}`);s>=5&&(em((o=l).clientID),function(e){if(eg(e.mutationID),em(e.mutatorName),!e.mutatorName)throw Error("Missing mutator name");eF(e.mutatorArgsJSON),null!==e.originalHash&&th(e.originalHash),eg(e.timestamp)}(o));let p=await rJ(r,u,h,e.chunk.hash,t,l.timestamp,a,s),f=new rF(a,await p.getMutationID(),"rebase",p,i);return await (c||(async()=>{}))(f,h),p}async function r1(e,t,r,n,i,a,s){return(await r0(e,t,r,n,i,a,s)).putCommit()}async function r2(e,t,r,n,i,a,s,o){return(await r0(e,t,r,i,a,s,o)).commit(n)}function r5(e,t){return"object"==typeof e&&null!==e&&e.error===t}function r3(e){return"string"==typeof e.error}function r4(e){return r5(e,"ClientStateNotFound")}function r6(e){if(!r5(e,"VersionNotSupported"))return!1;let{versionType:t}=e;switch(t){case void 0:case"pull":case"push":case"schema":return!0}return!1}async function r9(e,t,r,n){let i=new Request(e,{headers:{"Content-type":"application/json",Authorization:t,"X-Replicache-RequestID":r},body:JSON.stringify(n),method:"POST"}),a=await fetch(i),s=a.status;return 200!==s?[void 0,{httpStatusCode:s,errorMessage:await a.text()}]:[a,{httpStatusCode:s,errorMessage:""}]}function r8(e){eb(e),eg(e.httpStatusCode),em(e.errorMessage)}function r7(e){for(let t of(ew(e),e))!function(e){switch(eb(e),e.op){case"put":em(e.key),eF(e.value);break;case"update":var t;if(em(e.key),void 0!==e.merge&&(eb(t=e.merge),eU(t)),void 0!==e.constrain)for(let t of(ew(e.constrain),e.constrain))em(t);break;case"del":em(e.key);break;case"clear":break;default:throw Error(`unknown patch op \`${e.op}\`, expected one of \`put\`, \`del\`, \`clear\``)}}(t)}var ne=new WeakSet,nt=new WeakSet,nr=ts(ti({prefix:e5.string().optional(),jsonPointer:e5.string(),allowEmpty:e5.boolean().optional()}));function nn(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(let[r,n]of Object.entries(e)){let e=t[r];if(!e||n.jsonPointer!==e.jsonPointer||(n.allowEmpty??!1)!==(e.allowEmpty??!1)||(n.prefix??"")!==(e.prefix??""))return!1}return!0}var ni=ti({headHash:td,mutatorNames:ta(e5.string()),indexes:nr,mutationIDs:ts(e5.number()),lastServerAckdMutationIDs:e5.record(e5.number()),disabled:e5.boolean()}),na="client-groups";async function ns(e,t){let r=await t.getChunk(e);var n=r?.data;eb(n);let i=new Map;for(let[e,t]of Object.entries(n))void 0!==t&&(e7(t,ni,void 0),i.set(e,t));return i}async function no(e){let t=await e.getHead(na);return t?ns(t,e):new Map}async function nl(e,t){let r=await no(t);for(let[t,n]of e)nc(n,r.get(t));return nh(e,t)}async function nu(e,t,r){let n=await no(r);nc(t,n.get(e));let i=new Map(n);return i.set(e,t),nh(i,r)}function nc(e,t){let r=new Set(e.mutatorNames);ef(r.size===e.mutatorNames.length,"A client group's mutatorNames must be a set."),void 0!==t&&(ef(nn(t.indexes,e.indexes),"A client group's index definitions must never change."),ef(nd(r,t.mutatorNames),"A client group's mutatorNames must never change."))}async function nh(e,t){let r=function(e,t){let r={};for(let[n,i]of e.entries())t.assertValidHash(i.headHash),r[n]={...i,mutatorNames:[...i.mutatorNames.values()]};return r}(e,t),n=new Set;for(let t of e.values())n.add(t.headHash);let i=t.createChunk(r,eY(n));return await t.putChunk(i),await t.setHead(na,i.hash),e}function nd(e,t){if(t.length!==e.size)return!1;for(let r of t)if(!e.has(r))return!1;return!0}async function np(e,t){return(await no(t)).get(e)}function nf(e){for(let[t,r]of Object.entries(e.mutationIDs)){let n=e.lastServerAckdMutationIDs[t];if(void 0===n&&0!==r||n<r)return!0}return!1}async function nm(e,t){let r=await np(e,t);if(!r)return;let n={...r,disabled:!0};await nu(e,n,t)}var ng=e5.string(),ny=e5.string();function nb(e,t){return n_(e.read(),t)}function nw(e,t){return n_(e.write(),t)}function nv(e,t){return n_(e.write(),async e=>{let r=await t(e);return await e.commit(),r})}async function n_(e,t){let r=await e;try{return await t(r)}finally{r.release()}}function nk(){return(e2()<<64n|e2()).toString(32).slice(-18).padStart(18,"0")}var nS=ti({heartbeatTimestampMs:e5.number(),headHash:td,mutationID:e5.number(),lastServerAckdMutationID:e5.number()}),nI=ti({heartbeatTimestampMs:e5.number(),headHash:td,tempRefreshHash:td.nullable(),clientGroupID:ng}),nx=ti({heartbeatTimestampMs:e5.number(),refreshHashes:ta(td),persistHash:td.nullable(),clientGroupID:ng});function nD(e){return void 0!==e.refreshHashes}function nE(e){return void 0!==e.clientGroupID}var nN="clients",n$=e5.union(nS,nI,nx);function nC(e){e7(e,nS,void 0)}function nT(e){e7(e,nx,void 0)}async function nP(e){return nR(await e.getHead(nN),e)}async function nR(e,t){if(!e)return new Map;let r=await t.getChunk(e);var n=r?.data;eb(n);let i=new Map;for(let e in n)if(eM(n,e)){let t=n[e];void 0!==t&&(e7(t,n$,void 0),i.set(e,t))}return i}
5var nO=class extends Error{name="ClientStateNotFoundError";id;constructor(e){super(`Client state not found, id: ${e}`),this.id=e}};async function nA(e,t){if(!await nj(e,t))throw new nO(e)}async function nj(e,t){return!!await nM(e,t)}async function nM(e,t){return(await nP(t)).get(e)}async function nz(e,t){let r=await nM(e,t);if(!r)throw new nO(e);return r}async function nF(e,t,r){let n,i,a=new Set(t);for(let[t,s]of(await no(e))){if(!s.disabled&&nd(a,s.mutatorNames)&&nn(r,s.indexes))return{type:2,clientGroupID:t,headHash:s.headHash};let o=await tz(s.headHash,e);tJ(o);let{cookieJSON:l}=o.meta;(void 0===n||eL(l,n)>0)&&(n=l,i=o)}return i?{type:1,snapshot:i}:{type:0}}async function nU(e,t){let r=await nL(e,t);if(r)return np(r,t)}async function nL(e,t){let r=await nM(e,t);if(!(!r||!nE(r)))return r.clientGroupID}async function nH(e,t,r){return nB(new Map(await nP(r)).set(e,t),r)}async function nB(e,t){let r=function(e,t){for(let r of e.values())nD(r)?(r.refreshHashes.forEach(t.assertValidHash),r.persistHash&&t.assertValidHash(r.persistHash)):(t.assertValidHash(r.headHash),nE(r)&&r.tempRefreshHash&&t.assertValidHash(r.tempRefreshHash));return Object.fromEntries(e)}(e,t),n=t.createChunk(r,function(e){let t=new Set;for(let r of e.values())if(nD(r)){for(let e of r.refreshHashes)t.add(e);r.persistHash&&t.add(r.persistHash)}else t.add(r.headHash),nE(r)&&r.tempRefreshHash&&t.add(r.tempRefreshHash);return eY(t)}(e));return await t.putChunk(n),await t.setHead(nN,n.hash),n.hash}var nV="u">typeof navigator?navigator:void 0,nq=Symbol(),nG=class{r=new Map;#i;constructor(e){this.#i=e}has(e){switch(this.r.get(e)){case void 0:return this.#i.has(e);case nq:return eG;default:return eq}}async get(e){let t=this.r.get(e);switch(t){case nq:return;case void 0:return eQ(await this.#i.get(e));default:return t}}put(e,t){return this.r.set(e,t),eK}del(e){return this.r.set(e,nq),eK}release(){this.#i.release()}get closed(){return this.#i.closed}},nK={durability:"relaxed"},nJ="chunks",nW=class{#i;#a=!1;#s=!1;constructor(e){this.#i=function(e){return new Promise((t,r)=>{let n=indexedDB.open(e);n.onupgradeneeded=()=>{n.result.createObjectStore(nJ)},n.onsuccess=()=>{let e=n.result;e.onversionchange=()=>e.close(),t(e)},n.onerror=()=>r(n.error)})}(e)}read(){return this.#o(nX)}write(){return this.#o(nY)}async close(){this.#s||(await this.#i).close(),this.#a=!0}get closed(){return this.#a}async #o(e){let t=async e=>{let{promise:t,resolve:r,reject:n}=_(),i=indexedDB.open(e);i.onupgradeneeded=()=>{let t=i.transaction;(function(e){if(null===e)throw Error("Expected non-null value")})(t),t.abort(),this.#s=!0,n(new n1(`Replicache IndexedDB not found: ${e}`))},i.onsuccess=()=>r(i.result),i.onerror=()=>n(i.error);let a=await t;return a.onversionchange=()=>a.close(),a},r=await this.#i;try{return e(r)}catch(n){if(!this.#a&&n instanceof DOMException){if("InvalidStateError"===n.name)return this.#i=t(r.name),e(await this.#i);else if("NotFoundError"===n.name)throw this.#s=!0,indexedDB.deleteDatabase(r.name),new n1(`Replicache IndexedDB ${r.name} missing object store. Deleting db.`)}throw n}}},nZ=class{#i;#a=!1;constructor(e){this.#i=e}has(e){return new Promise((t,r)=>{let n=n0(this.#i).count(e);n.onsuccess=()=>t(n.result>0),n.onerror=()=>r(n.error)})}get(e){return new Promise((t,r)=>{let n=n0(this.#i).get(e);n.onsuccess=()=>t(eQ(n.result)),n.onerror=()=>r(n.error)})}release(){this.#a=!0}get closed(){return this.#a}},nQ=class extends nG{#i;#a=!1;constructor(e){super(new nZ(e)),this.#i=e}commit(){return 0===this.r.size?eK:new Promise((e,t)=>{let r=this.#i,n=n0(r);for(let[e,t]of this.r)t===nq?n.delete(e):n.put(t,e);r.oncomplete=()=>e(),r.onerror=()=>t(r.error)})}release(){this.#a=!0}get closed(){return this.#a}};function nY(e){return new nQ(e.transaction(nJ,"readwrite",nK))}function nX(e){return new nZ(e.transaction(nJ,"readonly"))}function n0(e){return e.objectStore(nJ)}var n1=class extends Error{name="IDBNotFoundError"},n2=class{#i;#a;#s=!1;constructor(e,t){this.#i=e,this.#a=t}release(){this.#a(),this.#s=!0}get closed(){return this.#s}has(e){return Promise.resolve(this.#i.has(e))}get(e){return Promise.resolve(this.#i.get(e))}},n5=class extends nG{#i;constructor(e,t){super(new n2(e,t)),this.#i=e}commit(){return this.r.forEach((e,t)=>{e===nq?this.#i.delete(t):this.#i.set(t,e)}),this.r.clear(),this.release(),eK}},n3=new Map;function n4(e){return n3.delete(e),eK}var n6=class{#i;#a;#s=!1;constructor(e){let t=n3.get(e),r,n;t?{lock:r,map:n}=t:(r=new S,n=new Map,n3.set(e,{lock:r,map:n})),this.#a=r,this.#i=n}async read(){let e=await this.#a.read();return new n2(this.#i,e)}async write(){let e=await this.#a.write();return new n5(this.#i,e)}close(){return this.#s=!0,eK}get closed(){return this.#s}},n9=class{#i;#a;#s;constructor(e,t){this.#i=e,this.#a=t,this.#s=new nW(t)}read(){return this.#o(e=>e.read())}write(){return this.#o(e=>e.write())}async #o(e){try{return await e(this.#s)}catch(t){if(n8(t))return this.#s instanceof nW&&(this.#i.info?.("Switching to MemStore because of Firefox private browsing error"),this.#s=new n6(this.#a)),e(this.#s);throw t}}close(){return this.#s.close()}get closed(){return this.#s.closed}};function n8(e){return n7()&&e instanceof DOMException&&"InvalidStateError"===e.name&&"A mutation operation was attempted on a database that did not allow mutations."===e.message}function n7(){return nV?.userAgent.includes("Firefox")??!1}function ie(e){if(!n7())return it(e);try{return it(e)}catch(t){if(n8(t))return n4(e)}return eK}function it(e){return new Promise((t,r)=>{let n=indexedDB.deleteDatabase(e);n.onsuccess=()=>t(),n.onerror=()=>r(n.error)})}function ir(e,t,r){let n=`rep:${e}:${r}`;return t?`${n}:${t}`:n}
5var ii=class{#i;constructor(e){this.#i=(e=>new aa(e))(e)}get pullURL(){return this.#i.pullURL}set pullURL(e){this.#i.pullURL=e}get pushURL(){return this.#i.pushURL}set pushURL(e){this.#i.pushURL=e}get auth(){return this.#i.auth}set auth(e){this.#i.auth=e}get name(){return this.#i.name}get idbName(){return ir(this.name,this.schemaVersion,7)}get schemaVersion(){return this.#i.schemaVersion}get mutate(){return this.#i.mutate}get pullInterval(){return this.#i.pullInterval}set pullInterval(e){this.#i.pullInterval=e}get pushDelay(){return this.#i.pushDelay}set pushDelay(e){this.#i.pushDelay=e}get puller(){return this.#i.puller}set puller(e){this.#i.puller=e}get pusher(){return this.#i.pusher}set pusher(e){this.#i.pusher=e}get requestOptions(){return this.#i.requestOptions}get onSync(){return this.#i.onSync}set onSync(e){this.#i.onSync=e}get onClientStateNotFound(){return this.#i.onClientStateNotFound}set onClientStateNotFound(e){this.#i.onClientStateNotFound=e}get onUpdateNeeded(){return this.#i.onUpdateNeeded}set onUpdateNeeded(e){this.#i.onUpdateNeeded=e}get getAuth(){return this.#i.getAuth}set getAuth(e){this.#i.getAuth=e}get profileID(){return this.#i.profileID}get clientID(){return this.#i.clientID}get clientGroupID(){return this.#i.clientGroupID}get onOnlineChange(){return this.#i.onOnlineChange}set onOnlineChange(e){this.#i.onOnlineChange=e}get online(){return this.#i.online}get closed(){return this.#i.closed}close(){return this.#i.close()}push({now:e=!1}={}){return this.#i.push({now:e})}pull({now:e=!1}={}){return this.#i.pull({now:e})}poke(e){return this.#i.poke(e)}subscribe(e,t){return this.#i.subscribe(e,t)}experimentalWatch(e,t){return this.#i.experimentalWatch(e,t)}query(e){return this.#i.query(e)}experimentalPendingMutations(){return this.#i.experimentalPendingMutations()}},ia=class extends Error{};function is(e){return new n6(e)}function io(e){return e instanceof Error?e:Error(String(e))}async function il(e,t,r){for(let n of r)switch(n.op){case"put":await t.put(e,n.key,n.value);break;case"update":{let r=await t.get(n.key),i=[],a=e=>{for(let[t,r]of Object.entries(e))(!n.constrain||0===n.constrain.length||n.constrain.indexOf(t)>-1)&&i.push([t,r])};void 0!==r&&(eb(r),a(r)),n.merge&&a(n.merge),await t.put(e,n.key,Object.fromEntries(i));break}case"del":await t.del(e,n.key);break;case"clear":await t.clear()}}var iu=class extends Error{name="PullError";causedBy;constructor(e){super("Failed to pull"),this.causedBy=e}},ic="sync";async function ih(e,t,r,n,i,a,s,o,l=!0){var u,c,h,d,p,f;let[m,g]=await nb(a,async e=>{let r=await e.getHead(tN);if(!r)throw Error("Internal no main head found");let n=await tz(r,e),i=n.meta.cookieJSON;return[await n.getMutationID(t,e),i]}),{response:y,httpRequestInfo:b}=await ip(o,n,{profileID:e,clientID:t,cookie:g,lastMutationID:m,pullVersion:0,schemaVersion:r},i);if(!y)return{httpRequestInfo:b,syncHead:tl};if(!l||r3(y))return{httpRequestInfo:b,pullResponse:y,syncHead:tl};let w=await (u=o,c=a,h=g,d=y,p=t,f=s,nw(c,async e=>{let t;ef(f<=4);let r=await e.getHead(tN);if(void 0===r)throw Error("Main head disappeared");let n=await tz(r,e),[i,a]=tU(n,p);if(!ez(h,a))return{type:2};if(d.lastMutationID<i)throw Error(im("lastMutationID",String(d.lastMutationID),String(i)));let s=d.cookie??null;if(ez(s,a))return d.patch.length>0&&u.error?.(`handlePullResponse: cookie ${JSON.stringify(a)} did not change, but patch is not empty`),d.lastMutationID!==i&&u.error?.(`handlePullResponse: cookie ${JSON.stringify(a)} did not change, but lastMutationID did change`),{type:1};for(let n of(await tH(r,e)))if(await n.getMutationID(p,e)<=d.lastMutationID){t=n;break}if(!t)throw Error("Internal invalid chain");let o=await rW(n.chunk.hash,d.lastMutationID,s,e,rY(t,e,f),p,f);await il(u,o,d.patch);let l=new rd(e,f,t.valueHash);for await(let e of o.map.diff(l))await rQ(u,o.indexes,e.key,()=>Promise.resolve(e.oldValue),e.newValue);return{type:0,syncHead:await o.commit(ic)}}));if(2===w.type)throw Error("Overlapping sync");return{httpRequestInfo:b,pullResponse:y,syncHead:0===w.type?w.syncHead:tl}}async function id(e,t,r,n,i,a,s,o,l,u=!0){let c=await nb(s,async e=>{let t=await e.getHead(tN);if(!t)throw Error("Internal no main head found");let r=(await tz(t,e)).meta;return tK(r),r.cookieJSON}),{response:h,httpRequestInfo:d}=await ip(l,i,{profileID:e,clientGroupID:r,cookie:c,pullVersion:1,schemaVersion:n},a);if(!h)return{httpRequestInfo:d,syncHead:tl};
5if(!u||r3(h))return{httpRequestInfo:d,pullResponse:h,syncHead:tl};let p=await ig(l,s,c,h,t,o);return{httpRequestInfo:d,pullResponse:h,syncHead:0===p.type?p.syncHead:tl}}async function ip(e,t,r,n){e.debug?.("Starting pull...");let i=Date.now(),a;try{a=await t(r,n),e.debug?.(`...Pull ${a.response?"complete":"failed"} in `,Date.now()-i,"ms")}catch(e){throw new iu(io(e))}try{var s,o,l,u;return 1===r.pullVersion?(s=a,eb(s),r8(s.httpRequestInfo),void 0!==s.response&&(eb(o=s.response),r4(o)||r6(o)||(void 0!==o.cookie&&eB(o.cookie),function(e){for(let[t,r]of(eb(e),Object.entries(e)))em(t),eg(r)}(o.lastMutationIDChanges),r7(o.patch)))):(l=a,eb(l),r8(l.httpRequestInfo),void 0!==l.response&&(eb(u=l.response),r4(u)||r6(u)||(void 0!==u.cookie&&eF(u.cookie),eg(u.lastMutationID),r7(u.patch)))),a}catch(e){throw new ia("Invalid puller result",io(e))}}function im(e,t,r){return`Received ${e} ${t} is < than last snapshot ${e} ${r}; ignoring client view`}function ig(e,t,r,n,i,a){return nw(t,async t=>{let s=await t.getHead(tN);if(void 0===s)throw Error("Main head disappeared");let o=await tz(s,t),l=o.meta;tK(l);let u=l.cookieJSON;if(!ez(r,u))return e.debug?.("handlePullResponse: cookie mismatch, response is not applicable"),{type:2};for(let[e,t]of Object.entries(n.lastMutationIDChanges)){let r=l.lastMutationIDs[e];if(void 0!==r&&t<r)throw Error(im(`${e} lastMutationID`,String(t),String(r)))}let c=n.cookie;if(0>eL(c,u))throw Error(im("cookie",JSON.stringify(c),JSON.stringify(u)));if(ez(c,u))return n.patch.length>0&&e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but patch is not empty`),Object.keys(n.lastMutationIDChanges).length>0&&(console.log(n.lastMutationIDChanges),e.error?.(`handlePullResponse: cookie ${JSON.stringify(u)} did not change, but lastMutationIDChanges is not empty`)),{type:1};let h=await rZ(o.chunk.hash,{...l.lastMutationIDs,...n.lastMutationIDChanges},c,t,i,a);return await il(e,h,n.patch),{type:0,syncHead:await h.commit(ic)}})}var iy=e5.unknown().chain(e=>el.ok(e));e5.unknown().chain(e=>el.ok(e));var ib=class extends Error{name="PushError";causedBy;constructor(e){super("Failed to push"),this.causedBy=e}},iw=ti({id:e5.number(),name:e5.string(),args:iy,timestamp:e5.number()}),iv=ti({id:e5.number(),name:e5.string(),args:iy,timestamp:e5.number(),clientID:ny});async function i_(e,t,r,n,i,a,s,o,l){var u,c;let h,d=await nb(t,async e=>{let t=await e.getHead(tN);if(!t)throw Error("Internal no main head");return tR(t,e)});if(0===d.length)return;if(d.reverse(),1===l){let e=[];for(let t of d)if(t$(t))e.push({id:(u=t.meta).mutationID,name:u.mutatorName,args:u.mutatorArgsJSON,timestamp:u.timestamp,clientID:u.clientID});else throw Error("Internal non local pending commit");ef(i),h={profileID:n,clientGroupID:i,mutations:e,pushVersion:1,schemaVersion:o}}else{ef(0===l);let e=[];for(let t of d)if(tG(t.meta))e.push({id:(c=t.meta).mutationID,name:c.mutatorName,args:c.mutatorArgsJSON,timestamp:c.timestamp});else throw Error("Internal non local pending commit");h={profileID:n,clientID:a,mutations:e,pushVersion:0,schemaVersion:o}}r.debug?.("Starting push...");let p=Date.now(),f=await ik(s,h,e);return r.debug?.("...Push complete in ",Date.now()-p,"ms"),f}async function ik(e,t,r){let n;try{n=await e(t,r)}catch(e){throw new ib(io(e))}try{var i,a;return i=n,eb(i),r8(i.httpRequestInfo),void 0!==i.response&&(a=i.response,r4(a)||ef(r6(a))),n}catch(e){throw new ia("Invalid pusher result",io(e))}}e5.object({pushVersion:e5.literal(0),schemaVersion:e5.string(),profileID:e5.string(),clientID:ny,mutations:e5.array(iw)}),e5.object({pushVersion:e5.literal(1),schemaVersion:e5.string(),profileID:e5.string(),clientGroupID:ng,mutations:e5.array(iv)});var iS=class{#i=!1;#a;constructor(e){this.#a=e}async recoverMutations(e,t,r,n,i,a){let{lc:s,enableMutationRecovery:o,isPushDisabled:l,delegate:u}=this.#a;if(!o||this.#i||!u.online||u.closed||l())return!1;let c="Recovering mutations.";s.debug?.("Start:",c);try{for(let o of(this.#i=!0,await t,await iE(n,this.#a,r,e),Object.values(await i.getDatabases()))){if(u.closed)return s.debug?.("Exiting early due to close:",c),!0;if(o.replicacheName===u.name&&o.name!==u.idbName)switch(o.replicacheFormatVersion){case 4:case 5:case
56:case 7:await iD(o,this.#a,void 0,a)}}}catch(e){iI(e,s,c,u)}finally{s.debug?.("End:",c),this.#i=!1}return!0}};function iI(e,t,r,n){n.closed?t.debug?.(`Mutation recovery error likely due to close during: 6${r} 7Error: 8`,e):t.error?.(`Mutation recovery error during: 9${r} 10Error: 11`,e)}async function ix(e,t,r,n,i,a){ef(4===n.replicacheFormatVersion),nC(e);let{delegate:s,lc:o,wrapInOnlineCheck:l,wrapInReauthRetries:u,isPushDisabled:c,isPullDisabled:h}=i,d=s.clientID;if(d===t||e.lastServerAckdMutationID>=e.mutationID)return;let p=`Recovering mutations for ${t}.`;o.debug?.("Start:",p);let f=new tb(r,0xa00000,e1,th);try{if(await nv(f,t=>t.setHead(tN,e.headHash)),c())return void o.debug?.(`Cannot recover mutations for client ${t} because push is disabled.`);let{pusher:i}=s,p="recoveringMutationsPush";if(!await l(async()=>{let{result:e}=await u(async(e,r)=>{e_(f);let a=await i_(e,f,r,await s.profileID,void 0,t,i,n.schemaVersion,0);return{result:a,httpRequestInfo:a?.httpRequestInfo}},p,o);return!!e&&200===e.httpRequestInfo.httpStatusCode},p))return void o.debug?.(`Failed to recover mutations for client ${t} due to a push error.`);if(h())return void o.debug?.(`Cannot confirm mutations were recovered for client ${t} because pull is disabled.`);let{puller:m}=s,g="recoveringMutationsPull",y;if(!await l(async()=>{let{result:e}=await u(async(e,r)=>{let i=await ih(await s.profileID,t,n.schemaVersion,m,e,f,a,r,!1);return{result:i,httpRequestInfo:i.httpRequestInfo}},g,o);return{pullResponse:y}=e,!!y&&200===e.httpRequestInfo.httpStatusCode},g))return void o.debug?.(`Failed to recover mutations for client ${t} due to a pull error.`);return o.debug&&y&&(r4(y)?o.debug?.(`Client ${d} cannot recover mutations for client ${t}. The client no longer exists on the server.`):r6(y)?o.debug?.(`Version is not supported on the server. versionType: ${y.versionType}. Cannot recover mutations for client ${t}.`):o.debug?.(`Client ${d} recovered mutations for client ${t}. Details`,{mutationID:e.mutationID,lastServerAckdMutationID:e.lastServerAckdMutationID,lastMutationID:y.lastMutationID})),await nv(r,async e=>{let r=await nP(e),n=r.get(t);if(!n)return r;nC(n);let i=async t=>(await nB(t,e),t);if(r4(y)||r6(y)){let e=new Map(r);return e.delete(t),i(e)}if(ef(y),n.lastServerAckdMutationID>=y.lastMutationID)return r;let a=new Map(r).set(t,{...n,lastServerAckdMutationID:y.lastMutationID});return i(a)})}catch(e){iI(e,o,p,s)}finally{await f.close(),o.debug?.("End:",p)}}async function iD(e,t,r,n){let i=new tx(n(e.name),tu,th);try{await iE(e,t,i,r)}finally{await i.close()}}function iE(e,t,r,n){return e.replicacheFormatVersion>=5?i$(e,t,r):iN(e,t,r,n)}async function iN(e,t,r,n){let{delegate:i,lc:a}=t,s=`Recovering mutations from db ${e.name}.`;a.debug?.("Start:",s);try{let o=t4(e.replicacheFormatVersion),l=n||await nb(r,e=>nP(e)),u=new Set;for(;l;){let n;for(let[c,h]of l){if(i.closed)return void a.debug?.("Exiting early due to close:",s);if(!u.has(c)&&(u.add(c),n=await ix(h,c,r,e,t,o)))break}l=n}}catch(e){iI(e,a,s,i)}a.debug?.("End:",s)}async function i$(e,t,r){let{delegate:n,lc:i}=t,a=`Recovering mutations from db ${e.name}.`;i.debug?.("Start:",a);try{let s=t4(e.replicacheFormatVersion),o=await nb(r,e=>no(e)),l=new Set;for(;o;){let u;for(let[c,h]of o){if(n.closed)return void i.debug?.("Exiting early due to close:",a);if(!l.has(c)&&(l.add(c),u=await iT(h,c,r,e,t,s)))break}o=u}}catch(e){iI(e,i,a,n)}i.debug?.("End:",a)}async function iC(e,t,r,n,i){r4(n)?e.debug?.(`Client group ${t} cannot recover mutations for client group ${r}. The client group is unknown on the server. Marking it as disabled.`):r6(n)&&e.debug?.(`Client group ${t} cannot recover mutations for client group ${r}. The client group's version is not supported on the server. versionType: ${n.versionType}. Marking it as disabled.`),await nv(i,e=>nm(r,e))}async function iT(e,t,r,n,i,a){ef(n.replicacheFormatVersion>=5);let{delegate:s,lc:o,wrapInOnlineCheck:l,wrapInReauthRetries:u,isPushDisabled:c,isPullDisabled:h,clientGroupIDPromise:d}=i,p=await d;if(e_(p),p===t)return;let f,m=!0;for(let[t,r]of Object.entries(e.mutationIDs))if(!e.lastServerAckdMutationIDs[t]||e.lastServerAckdMutationIDs[t]<r){f=t,m=!1;break}if(m)return;if(e.disabled)return void o.debug?.(`Not recovering mutations for client group ${t} because group is disabled.`);let g=`Recovering mutations for client group ${t}.`;o.debug?.("Start:",g);let y=new tb(r,0xa00000,e1,th);try{if(await nv(y,t=>t.setHead(tN,e.headHash)),c())return void o.debug?.(`Cannot recover mutations for client group ${t} because push is disabled.`);let{pusher:i}=s,d="recoveringMutationsPush";if(!await l(async()=>{let{result:e}=await u(async(e,r)=>{ef(f),ef(y);let a=await i_(e,y,r,await s.profileID,t,f,i,n.schemaVersion,1);return{result:a,httpRequestInfo:a?.httpRequestInfo}},d,o);if(!e)return!1;let a=e.response;return r4(a)||r6(a)?(await iC(o,p,t,a,r),!1):200===e.httpRequestInfo.httpStatusCode},d))return void o.debug?.(`Failed to recover mutations for client ${t} due to a push error.`);if(h())return void o.debug?.(`Cannot confirm mutations were recovered for client ${t} because pull is disabled.`);let{puller:m}=s,g="recoveringMutationsPull",b;if(!await l(async()=>{let{result:e}=await u(async(e,r)=>{ef(f);let i=await id(await s.profileID,f,t,n.schemaVersion,m,e,y,a,r,!1);return{result:i,httpRequestInfo:i.httpRequestInfo}},g,o),{pullResponse:i}=e;return r4(i)||r6(i)?(await iC(o,p,t,i,r),!1):!!i&&200===e.httpRequestInfo.httpStatusCode&&(b=i,!0)},g))return void o.debug?.(`Failed to recover mutations for client ${t} due to a pull error.`);return ef(b),o.debug?.(`Client group ${p} recovered mutations for client group ${t}. Details`,{mutationIDs:e.mutationIDs,lastServerAckdMutationIDs:e.lastServerAckdMutationIDs,lastMutationIDChanges:b.lastMutationIDChanges}),await nv(r,async e=>{let r=await no(e),n=r.get(t);if(!n)return r;ef(b);let i={},a=!1;for(let[e,t]of Object.entries(b.lastMutationIDChanges))(n.lastServerAckdMutationIDs[e]??0)<t&&(i[e]=t,a=!0);if(!a)return r;let s=new Map(r).set(t,{...n,lastServerAckdMutationIDs:{...n.lastServerAckdMutationIDs,...i}});return await nl(s,e),s})}catch(e){iI(e,o,g,s)}finally{await y.close(),o.debug?.("End:",g)}}var iP=typeof BroadcastChannel>"u"?class{name;onmessage=null;onmessageerror=null;constructor(e){this.name=e}addEventListener(){}removeEventListener(){}dispatchEvent(){return!1}close(){}postMessage(){}}:BroadcastChannel;async function iR(e){let t=await ty(tN,e);return(await tO(t,e)).map(e=>({id:e.meta.mutationID,name:e.meta.mutatorName,args:e.meta.mutatorArgsJSON,clientID:e.meta.clientID})).reverse()}async function iO(e,t,r,n,i){if(!i.aborted){for(n=n.withContext("bgIntervalProcess",e),n.debug?.("Starting");!i.aborted;){try{await eP(r(),i)}catch(e){if(!(e instanceof ep))throw e}if(!i.aborted){n.debug?.("Running");try{await t()}catch(e){i.aborted?n.debug?.("Error running most likely due to close.",e):n.error?.("Error running.",e)}}}n.debug?.("Stopping")}}var iA="profileId",ij=class{#i;constructor(e){this.#i=e("replicache-dbs-v0")}
11putDatabase(e){return this.#a({...e,lastOpenedTimestampMS:Date.now()})}putDatabaseForTesting(e){return this.#a(e)}#a(e){return nv(this.#i,async t=>{let r={...await iM(t),[e.name]:e};return await t.put("dbs",r),r})}clearDatabases(){return nv(this.#i,e=>e.del("dbs"))}deleteDatabases(e){return nv(this.#i,async t=>{let r={...await iM(t)};for(let t of e)delete r[t];await t.put("dbs",r)})}getDatabases(){return nb(this.#i,iM)}close(){return this.#i.close()}getProfileID(){return nv(this.#i,async e=>{let t=await e.get(iA);return void 0===t&&(t=`p${nk()}`,await e.put(iA,t)),em(t),t})}};async function iM(e){let t=await e.get("dbs");return t||(t={}),function(e){for(let[r,n]of(eb(e),Object.entries(e))){var t;em(r),eb(t=n),em(t.name),em(t.replicacheName),eg(t.replicacheFormatVersion),em(t.schemaVersion),void 0!==t.lastOpenedTimestampMS&&eg(t.lastOpenedTimestampMS),ef(r===n.name)}}(t),t}async function iz(e,t,r,n,i,a=iL){let s=Object.values(await e.getDatabases()),o=(await Promise.all(s.map(async e=>[e.name,await iH(e,t,r,n,a)]))).filter(e=>e[1]).map(e=>e[0]),{errors:l}=await iU(e,o,i);if(l.length)throw l[0]}async function iF(e,t,r){await r(e),await t.deleteDatabases([e])}async function iU(e,t,r){let n=await Promise.allSettled(t.map(async t=>(await iF(t,e,r),t))),i=[],a=[];for(let e of n)"fulfilled"===e.status?i.push(e.value):a.push(e.reason);return{dropped:i,errors:a}}function iL(e){return new tx(new nW(e),tu,th)}async function iH(e,t,r,n,i){if(e.replicacheFormatVersion>7)return!1;if(void 0!==e.lastOpenedTimestampMS){let a=e.replicacheFormatVersion>=5;return!(t-e.lastOpenedTimestampMS<(a?n:r))&&(!a||(ef(5===e.replicacheFormatVersion||6===e.replicacheFormatVersion||7===e.replicacheFormatVersion),!await iB(i(e.name))))}let a=i(e.name),s=await nb(a,nP);return await a.close(),function(e,t,r){for(let n of e.values())if(t-n.heartbeatTimestampMs<r)return!1;return!0}(s,t,r)}async function iB(e){for(let t of(await nb(e,no)).values())if(nf(t))return!0;return!1}var iV=class{#i=new Set;#a;constructor(e){this.#a=e}async visit(e){if(this.#i.has(e))return;this.#i.add(e);let t=await this.#a.mustGetChunk(e);await this.visitChunk(t)}async visitChunk(e){await Promise.all(e.meta.map(e=>this.visit(e)))}},iq=class extends iV{#i=new Map;#a;constructor(e){super(e),this.#a=e}get gatheredChunks(){return this.#i}visit(e){return this.#a.isMemOnlyChunkHash(e)?super.visit(e):eK}visitChunk(e){return this.#i.set(e.hash,e),super.visitChunk(e)}};async function iG(e,t,r,n,i,a,s,o=()=>Promise.resolve()){if(a())return;let[l,u,c]=await nb(n,async e=>{await nA(t,e);let r=await nL(t,e);ef(r,`No main client group for clientID: ${t}`);let[,n]=await iK(e,r),i=await n.getMutationID(t,e),a=await tF(n,e);return tJ(a),[i,a,r]});if(a())return;let[h,d,p]=await nb(r,async e=>{let r,n=await tV(tN,e),i=await tA(n,{[t]:l||0},e),a=await tF(n,e);if(tJ(a),tL(a,u)>0){await o();let t=a.chunk.hash,n=new iq(e);await n.visit(t),r=n.gatheredChunks}return[i,a,r]});if(a())return;let f=!1;await nv(n,async r=>{let[n,a]=await iK(r,c),o=a.chunk.hash,l={...n.mutationIDs},{lastServerAckdMutationIDs:u}=n;if(p){let c=await nz(t,r);nT(c);let h=await tF(a,r);if(tJ(h),tL(d,h)>0){f=!0,await Promise.all(Array.from(p.values(),e=>r.putChunk(e))),await nH(t,{...c,persistHash:d.chunk.hash},r),o=d.chunk.hash;let a=await tO(n.headHash,r);l={...u=d.meta.lastMutationIDs},o=await iJ(a,o,r,i,l,e,s)}}o=await iJ(h,o,r,i,l,e,s);let m={...n,headHash:o,mutationIDs:l,lastServerAckdMutationIDs:u};await nu(c,m,r)}),p&&f&&await nv(r,e=>e.chunksPersisted([...p.keys()]))}async function iK(e,t){let r=await np(t,e);return ef(r,`No client group for clientGroupID: ${t}`),[r,await tB(r.headHash,e)]}async function iJ(e,t,r,n,i,a,s){for(let o=e.length-1;o>=0;o--){let l=e[o],{meta:u}=l,c=await tB(t,r);await l.getMutationID(u.clientID,r)>await c.getMutationID(u.clientID,r)&&(i[u.clientID]=u.mutationID,t=(await r1(l,r,t,n,a,u.clientID,s)).chunk.hash)}return t}var iW=class extends iV{#i=new Map;#a=0;#s;#o;#l;constructor(e,t,r,n=eJ){super(e),this.#s=t,this.#o=r,this.#l=n}get gatheredChunks(){return this.#i}visit(e){return this.#a>=this.#o||this.#s.isCached(e)?eK:super.visit(e)}visitChunk(e){if(this.#a<this.#o){let t=this.#l(e);this.#i.set(e.hash,{chunk:e,size:t}),this.#a+=t}return super.visitChunk(e)}};async function iZ(e,t,r,n,i,a,s,o){if(s())return;let l=await nb(t,e=>tj(tN,e));tJ(l);let u=await t.withSuspendedSourceCacheEvictsAndDeletes(async()=>{let u=await nv(r,async e=>{let r=await nU(n,e);if(!r)throw new nO(n);let i=r.headHash,a=await (await tB(i,e)).getMutationID(n,e),s=await nz(n,e);nT(s);let o=await tz(i,e);if(tJ(o),iQ(l,o,i))return;let u=new iW(e,t,5242880);await u.visit(i);let{gatheredChunks:c}=u,h=new Set(s.refreshHashes);h.add(i);let d={...s,refreshHashes:[...h]};return await nH(n,d,e),[i,o,a,c,s.refreshHashes]});if(s()||!u||(await eP(300),s()))return{type:"aborted"};let[c,h,d,p,f]=u;return nv(t,async t=>{let r=await tV(tN,t),s=await tF(r,t);if(tJ(s),iQ(s,h,c))return{type:"aborted",refreshHashesForRevert:f};let l=await tA(r,{[n]:d},t),u=[];for(let{chunk:e,size:r}of p.values())u.push(t.putChunk(e,r));await Promise.all(u);let m=c;for(let r=l.length-1;r>=0;r--)m=(await r1(l[r],t,m,i,e,l[r].meta.clientID,o)).chunk.hash;let g=await tB(m,t),y=await rq(r,g,t,a,o);return await t.setHead(tN,m),{type:"complete",diffs:y,newPerdagClientHeadHash:c}})});if(s())return;let c=e=>nv(r,async t=>{let r={...await nz(n,t),refreshHashes:e};await nH(n,r,t)});if("aborted"===u.type){u.refreshHashesForRevert&&await c(u.refreshHashesForRevert);return}return await c([u.newPerdagClientHeadHash]),u.diffs}function iQ(e,t,r){let n=tL(e,t);return n>0||0===n&&r===t.chunk.hash}function iY(e){return new Promise(t=>{"function"==typeof requestIdleCallback?requestIdleCallback(()=>t(),{timeout:e}):setTimeout(()=>t(),e)})}var iX=class{#i;#a;#s;#o;#l;#u=void 0;#c=void 0;#h=Promise.resolve();#f=Promise.resolve();constructor(e,t,r,n,i=iY){this.#i=e,this.#a=t,this.#s=r,this.#o=n,this.#l=i,this.#o.addEventListener("abort",()=>{let e=new ep("Aborted");this.#c?.reject(e),this.#u?.reject(e),this.#c=void 0,this.#u=void 0},{once:!0})}schedule(){return this.#o.aborted?Promise.reject(new ep("Aborted")):(this.#u||(this.#u=_(),this.#p()),this.#u.promise)}async #p(){try{await this.#h}catch{}if(await this.#f,this.#u&&(await this.#l(this.#a),this.#u)){this.#f=i0(this.#s,this.#o),this.#c=this.#u,this.#u=void 0;try{this.#h=this.#i(),await this.#h,this.#c?.resolve()}catch(e){this.#c?.reject(e)}this.#c=void 0}}};async function i0(e,t){try{await eP(e,t)}catch(e){ef(e instanceof ep)}}var i1=new Set,i2=Symbol(),i5=class{#i;#a;#s=i2;#o=i1;#l=[];onError;onDone;#u;constructor(e,t,r,n,i=ez){this.#i=e,this.#a=t,this.onError=r,this.onDone=n,this.#u=i}hasIndexSubscription(e){for(let t of this.#l)if(t.options.indexName===e)return!0;return!1}invoke(e,t,r){return this.#i(e)}matches(e){for(let[t,r]of e)if(function(e,t,r,n){if(""===r){for(let t of n)if(e.has(t.key))return!0}for(let e of t)if(function(e,t,r){for(let n of r)if(function(e,t,r){let{indexName:n="",limit:i,prefix:a,startKey:s,startExclusive:o,startSecondaryKey:l}=e.options;if(t!==n)return!1;if(!n)return(void 0===i||!(i<=0))&&(!a&&!s||!(a&&(!r.startsWith(a)||i9(e,r))||s&&(o&&0>=tX(r,s)||0>tX(r,s)||i9(e,r))));if(!a&&!s&&!l)return!0;let[u,c]=r_(r);return!(a&&!u.startsWith(a)||l&&(o&&0>=tX(u,l)||0>tX(u,l))||s&&(o&&0>=tX(c,s)||0>tX(c,s)))}(e,t,n.key))return!0;return!1}(e,r,n))return!0;return!1}(this.#o,this.#l,t,r))return!0;return!1}updateDeps(e,t){this.#o=e,this.#l=t}onData(e){this.#s!==i2&&this.#u(this.#s,e)||(this.#s=e,this.#a(e))}},i3=class{#i;#a;#s;#o;onError=void 0;onDone=void 0;constructor(e,t){this.#i=e,this.#a=t?.prefix??"",this.#s=t?.indexName,this.#o=t?.initialValuesInFirstDiff??!1}hasIndexSubscription(e){return this.#s===e}onData(e){void 0!==e&&this.#i(e)}invoke(e,t,r){let n=async(n,i,a,s)=>{let o;if(0===t){if(!this.#o)return;ef(void 0===r);let t=[];for await(let r of e.scan({prefix:i,indexName:n}
11).entries())t.push({op:"add",key:r[0],newValue:r[1]});o=t}else ef(r),o=s(r.get(n??"")??[]);let l=[],{length:u}=o;for(let e=i8(o,i,a);e<u&&a(o[e]).startsWith(i);e++)l.push(o[e]);return 0===t||l.length>0?l:void 0};return this.#s?n(this.#s,this.#a,e=>e.key[0],e=>i4(e,r_)):n(void 0,this.#a,e=>e.key,e=>i4(e,e=>e))}matches(e){let t=e.get(this.#s??"");return void 0!==t&&function(e,t,r){if(""===t)return!0;let n=r?e=>r_(e.key)[0]:e=>e.key,i=i8(e,t,n);return i<e.length&&n(e[i]).startsWith(t)}(t,this.#a,this.#s)}updateDeps(e,t){}};function i4(e,t){return e.map(e=>{let r=t(e.key);switch(e.op){case"add":return{op:"add",key:r,newValue:e.newValue};case"change":return{op:"change",key:r,oldValue:e.oldValue,newValue:e.newValue};case"del":return{op:"del",key:r,oldValue:e.oldValue}}})}var i6=class{#i=new Set;#a=new Set;#s;#o;hasPendingSubscriptionRuns=!1;constructor(e,t){this.#s=e,this.#o=t}add(e){return this.#i.add(e),this.#u(e),()=>this.#i.delete(e)}clear(){for(let e of this.#i)e.onDone?.();this.#i.clear()}async fire(e){let t=function*(e,t){for(let r of e)r.matches(t)&&(yield r)}(this.#i,e);await this.#l(t,1,e)}async #l(e,t,r){let n=[...e];if(0===n.length)return;let i=await this.#s(e=>Promise.allSettled(n.map(async n=>{let i=new rz(e);try{return await n.invoke(i,t,r)}finally{n.updateDeps(i.keys,i.scans)}})));this.callCallbacks(n,i)}callCallbacks(e,t){for(let r=0;r<e.length;r++){let n=e[r],i=t[r];"fulfilled"===i.status?n.onData(i.value):n.onError?n.onError(i.reason):this.#o.error?.("Error in subscription body:",i.reason)}}async #u(e){if(this.#a.add(e),!this.hasPendingSubscriptionRuns){this.hasPendingSubscriptionRuns=!0,await Promise.resolve(),this.hasPendingSubscriptionRuns=!1;let e=[...this.#a];this.#a.clear(),await this.#l(e,0,void 0)}}shouldComputeDiffs(){return this.#i.size>0}shouldComputeDiffsForIndex(e){for(let t of this.#i)if(t.hasIndexSubscription(e))return!0;return!1}};function i9(e,t){let{inclusiveLimitKey:r}=e;return void 0!==e.options.limit&&void 0!==r&&tX(t,r)>0}function i8(e,t,r){return t3(e.length,n=>tX(t,r(e[n])))}var i7="",ae=new Map;function at(e){let t=ae.get(e);return t?(t++,ae.set(e,t)):(ae.set(e,0),t=0),`${e}-${function(){if(""===i7){let e=new Uint8Array(4);(function(e){if(null===e)throw TypeError("array cannot be null");for(let t=0;t<e.length;t++)e[t]=Math.floor(256*Math.random())})(e),i7=Array.from(e,e=>e.toString(16)).join("")}return i7}()}-${t}`}var ar=()=>{},an={type:"NewClientGroup"},ai=(e,t)=>new i6(e,t),aa=class{pullURL;pushURL;auth;name;subscriptions;#i;isClientGroupDisabled=!1;#a;lastMutationID=0;get idbName(){return ir(this.name,this.schemaVersion,7)}schemaVersion;get #s(){return{name:this.idbName,replicacheName:this.name,replicacheFormatVersion:7,schemaVersion:this.schemaVersion}}#o=!1;#l=!0;#u=nk();#c;#h;#f;#p={};mutate;#d=0;#m=0;#g;#y;pullInterval;pushDelay;#b;puller;pusher;memdag;perdag;#w;#v;#_=new AbortController;#k=!1;#S;#I;#x;#D=new iX(()=>this.persist(),1e3,500,this.#_.signal);#E;#N=new iX(()=>this.refresh(),1e3,500,this.#_.signal);get requestOptions(){return this.#b}onSync=null;onClientStateNotFound=al;onUpdateNeeded=al;getAuth=null;onPushInvoked=()=>{};onBeginPull=()=>{};onRecoverMutations=e=>e;constructor(e,t={}){!function(e){let{name:t,clientMaxAgeMs:r}=e;if("string"!=typeof t||!t)throw TypeError("name is required and must be non-empty");if(void 0!==r&&("number"!=typeof r||r<=3e5))throw TypeError("clientAgeMaxMs must be a number larger than 300000ms")}(e);let{name:r,logLevel:n="info",logSinks:i=[y],pullURL:a="",auth:s,pushDelay:o=10,pushURL:l="",schemaVersion:u="",pullInterval:c=6e4,mutators:h={},requestOptions:d={},puller:p,pusher:f,indexes:g={},clientMaxAgeMs:w=864e5}=e,{enableMutationRecovery:v=!0,enableScheduledPersist:k=!0,enableScheduledRefresh:S=!0,enablePullAndPushInOpen:I=!0,makeSubscriptionsManager:x=ai,enableClientGroupForking:D=!0}=t;this.auth=s??"",this.pullURL=a,this.pushURL=l,this.name=r,this.schemaVersion=u,this.pullInterval=c,this.pushDelay=o,this.puller=p??function(e){async function t(t,r){let[n,i]=await r9(e.pullURL,e.auth,r,t);return n?{response:await n.json(),httpRequestInfo:i}:{httpRequestInfo:i}}return ne.add(t),t}(this),this.pusher=f??function(e){async function t(t,r){let[n,i]=await r9(e.pushURL,e.auth,r,t);if(!n)return{httpRequestInfo:i};let a={httpRequestInfo:i},s;try{s=await n.json()}catch{return a}return(r4(s)||r6(s))&&(a.response=s),a}return nt.add(t),t}(this),this.#S=k,this.#I=S,this.#x=I,this.#v=function(e="info",t=[y],r){return new b(e,r,1===t.length?t[0]:new m(t))}(n,i,{name:r}),this.#v.debug?.("Constructing Replicache",{name:r,"replicache version":"15.3.0"}),this.subscriptions=x(this.#$,this.#v);let E=function(e,t){switch(t){case"idb":case void 0:return{create:t=>n7()?new n9(e,t):new nW(t),drop:ie};case"mem":return{create:is,drop:e=>n4(e)};default:return t}}(this.#v,e.kvStore);this.#a=E;let N=E.create(this.idbName);this.#w=new ij(E.create),this.perdag=new tx(N,tu,th),this.memdag=new tb(this.perdag,0x6400000,tu,th);let $=_();this.#c=$.promise;let{minDelayMs:C=30,maxDelayMs:T=6e4}=d;this.#b={maxDelayMs:T,minDelayMs:C};let P=function(e,t){return e?new eI(e,0,t):new eE}(eS(),this.#_.signal);this.#g=new eR(this.#v.withContext("PULL"),new e$(this,()=>this.#C()),P),this.#y=new eR(this.#v.withContext("PUSH"),new eC(this,()=>this.#T())),this.mutate=this.#P(h);let R=_();this.#h=R.promise;let O=_();this.#f=O.promise,this.#i=new iS({delegate:this,lc:this.#v,enableMutationRecovery:v,wrapInOnlineCheck:this.#R.bind(this),wrapInReauthRetries:this.#O.bind(this),isPullDisabled:this.#A.bind(this),isPushDisabled:this.#j.bind(this),clientGroupIDPromise:this.#f}),this.#E=function(e,t,r){if(t.aborted)return()=>{};let n=new iP(`replicache-on-persist:${e}`);return n.onmessage=e=>{let{data:t}=e;eb(t),em(t.clientGroupID),em(t.clientID),r({clientGroupID:t.clientGroupID,clientID:t.clientID})},t.addEventListener("abort",()=>n.close(),{once:!0}),e=>{t.aborted||(n.postMessage(e),r(e))}}(this.name,this.#_.signal,e=>{this.#M(e)}),this.#z(g,D,w,R.resolve,O.resolve,$.resolve)}async #z(e,t,r,n,i,s){var o,l,u,c,h,d,p,f,m,g,y,b,w,v;let _,k,{clientID:S}=this;await as.get(this.name),await this.#w.getProfileID().then(n),await this.#w.putDatabase(this.#s);let[I,x,D,E]=await (o=this.#v,l=this.perdag,u=Object.keys(this.#p),nw(l,async r=>{async function n(t,n,a,s){let o=tW(t,{},n,a,s),l=r.createChunk(o,tQ(o)),c=nk(),h={heartbeatTimestampMs:Date.now(),refreshHashes:[l.hash],persistHash:null,clientGroupID:c},d=new Map(i).set(S,h),p={headHash:l.hash,mutatorNames:u,indexes:e,mutationIDs:{},lastServerAckdMutationIDs:{},disabled:!1};return await Promise.all([r.putChunk(l),nB(d,r),nu(c,p,r)]),await r.commit(),[h,l.hash,d,!0]}let i=await nP(r),a=await nF(r,u,e);if(2===a.type){let{clientGroupID:e,headHash:t}=a,n={clientGroupID:e,refreshHashes:[t],heartbeatTimestampMs:Date.now(),persistHash:null},s=new Map(i).set(S,n);return await nB(s,r),await r.commit(),[n,t,s,!1]}if(!t||0===a.type){let t=r.createChunk(ru,[]);await r.putChunk(t);let i=[];for(let[r,n]of Object.entries(e)){let e={name:r,keyPrefix:n.prefix??"",jsonPointer:n.jsonPointer,allowEmpty:n.allowEmpty??!1};i.push({definition:e,valueHash:t.hash})}return n(null,null,t.hash,i)}ef(1===a.type);let{snapshot:s}=a,l=[],{valueHash:c,indexes:h}=s,d=new rd(r,7,c);for(let[t,n]of Object.entries(e)){let{prefix:e="",jsonPointer:i,allowEmpty:a=!1}=n,s={name:t,keyPrefix:e,jsonPointer:i,allowEmpty:a},u=function(e,t){return e.find(e=>{var r;return r=e.definition,r.jsonPointer===t.jsonPointer&&(r.allowEmpty??!1)===(t.allowEmpty??!1)&&r.keyPrefix===t.keyPrefix})}(h,s);if(u)l.push({definition:s,valueHash:u.valueHash});else{let t=await rX(o,r,d,e,i,a,7);l.push({definition:s,valueHash:await t.flush()})}}return n(s.meta.basisHash,s.meta.cookieJSON,s.valueHash,l)}));i(I.clientGroupID),await nv(this.memdag,e=>e.setHead(tN,x)),s(),this.#x&&(this.pull().catch(ar),this.push().catch(ar));let{signal:N}=this.#_;c=S,h=this.perdag,d=()=>{this.#F(S)},iO("Heartbeat",async()=>{var e;e=c,a=nv(h,async t=>{let r=await nP(t),n=r.get(e);if(!n)throw new nO(e);let i={...n,heartbeatTimestampMs:Date.now()},a=new Map(r).set(e,i);return await nB(a,t),a});try{return await a}catch(e){if(e instanceof nO)return void d();throw e}},()=>6e4,this.#v,N),p=S,f=this.perdag,m=r,iO("ClientGC",()=>{var e,t,r;return e=p,t=f,r=m,nv(t,async t=>{let n=Date.now(),i=await nP(t),a=Array.from(i).filter(([t,i])=>t===e||n-i.heartbeatTimestampMs<=r);if(a.length===i.size)return i;let s=new Map(a);return await nB(s,t),s})},()=>3e5,this.#v,N),g=this.#w,y=this.#a.drop,b=2*r,w=this.#v,_=!0,iO("C
11ollectIDBDatabases",async()=>{await iz(g,Date.now(),2592e6,b,y)},()=>_?(_=!1,3e5):432e5,w,N),v=this.perdag,iO("ClientGroupGC",()=>nv(v,async e=>{let t=await nP(e),r=new Set;for(let e of t.values())nT(e),r.add(e.clientGroupID);let n=new Map;for(let[t,i]of(await no(e)))(r.has(t)||nf(i))&&n.set(t,i);return await nl(n,e),n}),()=>3e5,this.#v,N),function(e,t,r,n,i,a,s){if(r.aborted)return;let o=new iP(`replicache-new-client-group-v1:${e}`);if(i){o.postMessage({clientGroupID:n,idbName:t});let r=new iP(`replicache-new-client-group:${e}`);r.postMessage([n]),r.close()}o.onmessage=async e=>{let{data:r}=e;if("object"==typeof r&&"string"==typeof r.clientGroupID&&"string"==typeof r.idbName){let{clientGroupID:e,idbName:i}=r;if(e!==n)if(i!==t)return void a();else await nb(s,async t=>await np(e,t)!==void 0)&&a()}},r.addEventListener("abort",()=>o.close(),{once:!0})}(this.name,this.idbName,N,I.clientGroupID,E,()=>{this.#U(an)},this.perdag),k=setInterval(()=>this.recoverMutations(),3e5),N.addEventListener("abort",()=>{clearInterval(k)}),this.recoverMutations(D),eS()?.addEventListener("visibilitychange",this.#L)}#L=async()=>{this.#o||eS()?.visibilityState==="visible"&&await this.#H()};async #H(){let{clientID:e}=this,t=await nb(this.perdag,t=>nj(e,t));return t||this.#F(e),!t}get profileID(){return this.#h}get clientID(){return this.#u}get clientGroupID(){return this.#f}onOnlineChange=null;get online(){return this.#l}get closed(){return this.#o}async close(){this.#o=!0;let{promise:e,resolve:t}=_();as.set(this.name,e),this.#_.abort(),eS()?.removeEventListener("visibilitychange",this.#L),await this.#c;let r=[this.memdag.close(),this.perdag.close(),this.#w.close()];this.#g.close(),this.#y.close(),this.subscriptions.clear(),await Promise.all(r),as.delete(this.name),t()}async maybeEndPull(e,t){for(;;){if(this.#o)return;await this.#c;let{clientID:r}=this,n=this.#v.withContext("maybeEndPull").withContext("requestID",t),{replayMutations:i,diffs:a}=await function(e,t,r,n,i){return nw(e,async e=>{let a=await e.getHead(ic);if(void 0===a)throw Error("Missing sync head");if(a!==r)throw t.error?.("maybeEndPull, Wrong sync head. Expecting:",r,"got:",a),Error("Wrong sync head");let s=await tz(a,e),o=await e.getHead(tN);if(void 0===o)throw Error("Missing main head");let l=await tz(o,e),{meta:u}=s,c=u.basisHash;if(null===s)throw Error("Sync snapshot with no basis");if(c!==l.chunk.hash)throw Error("Overlapping syncs");let h=await tB(a,e),d=[];for(let t of(await tR(o,e))){let r=n;t$(t)&&(r=t.meta.clientID),await t.getMutationID(r,e)>await h.getMutationID(r,e)&&d.push(t)}d.reverse();let p=new rV;if(d.length>0)return{syncHead:a,replayMutations:d,diffs:p};let f=await tB(o,e);if(i.shouldComputeDiffs()){let t=new rd(e,7,f.valueHash),r=new rd(e,7,h.valueHash),n=await rL(t,r);p.set("",n),await rG(f,h,e,p,i,7)}if(await Promise.all([e.setHead(tN,a),e.removeHead(ic)]),await e.commit(),t.debug){let[e,r]=tU(l,n),[i,u]=tU(s,n);t.debug("Successfully pulled new snapshot with lastMutationID:",i,"(prev:",e,"), cookie: ",u,"(prev:",r,"), sync head hash:",a,", main head hash:",o,", valueHash:",h.valueHash,"(prev:",l.valueHash)}return{syncHead:a,replayMutations:[],diffs:p}})}(this.memdag,n,e,r,this.subscriptions);if(!i||0===i.length){await this.subscriptions.fire(a),this.#B();return}for(let t of i){this.subscriptions.hasPendingSubscriptionRuns&&await Promise.resolve();let{meta:i}=t;e=await nw(this.memdag,a=>r2(t,a,e,ic,this.#p,n,tq(i)?i.clientID:r,7))}}}#C(){return this.#A()?Promise.resolve(!0):this.#R(async()=>{try{this.#V(0,1);let{syncHead:e,requestID:t,ok:r}=await this.beginPull();if(!r)return!1;e!==tl&&await this.maybeEndPull(e,t)}catch(e){throw await this.#q(e)}finally{this.#V(0,-1)}return!0},"Pull")}#A(){var e;return this.isClientGroupDisabled||""===this.pullURL&&(e=this.puller,ne.has(e))}async #R(e,t){let r=!0;try{return await e()}catch(e){return e instanceof ib||e instanceof iu?(r=!1,this.#v.debug?.(`${t} threw: 12`,e,` 13with cause: 14`,e.causedBy)):e instanceof ia?this.#v.error?.(e):this.#v.info?.(`${t} threw: 15`,e),!1}finally{this.#l!==r&&(this.#l=r,this.onOnlineChange?.(r),r&&this.recoverMutations())}}async #O(e,t,r,n=ar,i=ar){let{clientID:a}=this,s=0,o;r=r.withContext(t);do{let l,u=at(a),c=r.withContext("requestID",u),{httpRequestInfo:h,result:d}=await e(u,c);if(o=d,!h)return{result:d,authFailure:!1};let{errorMessage:p,httpStatusCode:f}=h;
15if((p||200!==f)&&c.error?.(`Got a non 200 response doing ${t}: ${f}`+(p?`: ${p}`:"")),401!==f)return{result:d,authFailure:!1};if(!this.getAuth)return{result:d,authFailure:!0};try{await n(),l=await this.getAuth()}finally{await i()}if(null==l)return{result:d,authFailure:!0};this.auth=l,s++}while(s<8)return r.info?.("Tried to reauthenticate too many times"),{result:o,authFailure:!0}}#j(){var e;return this.isClientGroupDisabled||""===this.pushURL&&(e=this.pusher,nt.has(e))}async #T(){if(this.#j())return!0;await this.#c;let e=await this.#h,{clientID:t}=this,r=await this.#f;return this.#R(async()=>{let{result:n}=await this.#O(async(n,i)=>{try{this.#V(1,0);let a=await i_(n,this.memdag,i,e,r,t,this.pusher,this.schemaVersion,1);return{result:a,httpRequestInfo:a?.httpRequestInfo}}finally{this.#V(-1,0)}},"push",this.#v);if(void 0===n)return!0;let{response:i,httpRequestInfo:a}=n;return r6(i)?this.#G(i):r4(i)&&await this.#K(),200===a.httpStatusCode},"Push")}#G(e){let t={type:e.error};e.versionType&&(t.versionType=e.versionType),this.#U(t)}push({now:e=!1}={}){return ao(this.#y.send(e))}pull({now:e=!1}={}){return ao(this.#g.send(e))}async poke(e){await this.#c;let{clientID:t}=this,r=at(t),n=this.#v.withContext("handlePullResponse").withContext("requestID",r),{pullResponse:i}=e;if(r6(i))return void this.#G(i);if(r4(i))return void await this.#K();let a=await ig(n,this.memdag,e.baseCookie,i,t,7);switch(a.type){case 0:await this.maybeEndPull(a.syncHead,r);break;case 2:throw Error("unexpected base cookie for poke: "+JSON.stringify(e))}}async beginPull(){await this.#c;let e=await this.profileID,{clientID:t}=this,r=await this.#f,{result:{beginPullResponse:n,requestID:i}}=await this.#O(async(n,i)=>{let a=await id(e,t,r,this.schemaVersion,this.puller,n,this.memdag,7,i);return{result:{beginPullResponse:a,requestID:n},httpRequestInfo:a.httpRequestInfo}},"pull",this.#v,()=>this.#V(0,-1),()=>this.#V(0,1)),{pullResponse:a}=n;r6(a)?this.#G(a):r4(n.pullResponse)&&await this.#K();let{syncHead:s,httpRequestInfo:o}=n;return{requestID:i,syncHead:s,ok:200===o.httpStatusCode}}async persist(){ef(!this.#k),this.#k=!0;try{let{clientID:e}=this;if(await this.#c,this.#o)return;try{await iG(this.#v,e,this.memdag,this.perdag,this.#p,()=>this.closed,7)}catch(t){if(t instanceof nO)this.#F(e);else if(this.#o)this.#v.debug?.("Exception persisting during close",t);else throw t}}finally{this.#k=!1}let{clientID:e}=this,t=await this.#f;ef(t),this.#E({clientID:e,clientGroupID:t})}async refresh(){let e;await this.#c;let{clientID:t}=this;if(!this.#o){try{e=await iZ(this.#v,this.memdag,this.perdag,t,this.#p,this.subscriptions,()=>this.closed,7)}catch(e){if(e instanceof nO)this.#F(t);else if(this.#o)this.#v.debug?.("Exception refreshing during close",e);else throw e}void 0!==e&&await this.subscriptions.fire(e)}}#J(){this.onClientStateNotFound?.()}#F(e){this.#v.error?.(`Client state not found on client, clientID: ${e}`),this.#J()}async #K(){let e=await this.#f;this.#v.error?.(`Client state not found on server, clientGroupID: ${e}`),await this.disableClientGroup(),this.#J()}async disableClientGroup(){let e=await this.#f;ef(e),this.isClientGroupDisabled=!0,await nv(this.perdag,t=>nm(e,t))}#U(e){this.#v.debug?.(`Update needed, reason: ${e}`),this.onUpdateNeeded?.(e)}async #B(){this.#S&&await this.#W("persist",this.#D)}async #M(e){this.#v.debug?.("Handling persist",e);let t=await this.#f;e.clientGroupID===t&&this.#Z()}async #Z(){this.#I&&await this.#W("refresh from storage",this.#N)}async #W(e,t){try{await t.schedule()}catch(t){t instanceof ep?this.#v.debug?.(`Scheduled ${e} did not complete before close.`):this.#v.error?.(`Error during ${e}`,t)}}#V(e,t){this.#d+=e,this.#m+=t;let r=this.#d+this.#m;if(1===e+t&&1===r||0===r){let e=r>0;Promise.resolve().then(()=>this.onSync?.(e))}}subscribe(e,t){"function"==typeof t&&(t={onData:t});let{onData:r,onError:n,onDone:i,isEqual:a}=t;return this.subscriptions.add(new i5(e,r,n,i,a))}experimentalWatch(e,t){return this.subscriptions.add(new i3(e,t))}query(e){return this.#$(e)}get cookie(){return this.#c.then(()=>nb(this.memdag,async e=>{let t=await e.getHead(tN);if(!t)throw Error("Internal no main head found");let r=(await tz(t,e)).meta.cookieJSON;return eB(r),r}))}#$=async e=>{await this.#c;let{clientID:t}=this;return nb(this.memdag,async r=>{try{let n=await rS(tN,r,7),i=new rA(t,n,this.#v);return await e(i)}catch(e){throw await this.#q(e)}})};#Q(e,t){return this.#p[e]=t,r=>this.#Y(e,t,r,performance.now())}#P(e){let t=Object.create(null);for(let r in e)t[r]=this.#Q(r,e[r]);return t}async #Y(e,t,r,n){let i=r??null;this.subscriptions.hasPendingSubscriptionRuns&&await Promise.resolve(),await this.#c;let{clientID:a}=this;return nw(this.memdag,async s=>{try{let o=await ty(tN,s),l=await rJ(o,e,i,null,s,n,a,7),u=new rF(a,await l.getMutationID(),"initial",l,this.#v),c=await t(u,r);r$(l);let h=await l.getMutationID(),d=await l.commitWithDiffs(tN,this.subscriptions);return this.lastMutationID=h,this.#y.send(!1).catch(()=>{}),await this.subscriptions.fire(d),this.#B(),c}catch(e){throw await this.#q(e)}})}async #q(e){return e instanceof tm&&await this.#H()?new nO(this.clientID):e}recoverMutations(e){return this.#i.recoverMutations(e,this.#c,this.perdag,this.#s,this.#w,this.#a.create)}experimentalPendingMutations(){return nb(this.memdag,iR)}},as=new Map;async function ao(e){let t=await e;if(t)throw t.error}function al(){"u">typeof location&&location.reload()}let au="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function ac(e,t,r){let n=r[0];if(null!=t&&e>=t)throw Error(e+" >= "+t);if(e.slice(-1)===n||t&&t.slice(-1)===n)throw Error("trailing zero");if(t){let i=0;for(;(e[i]||n)===t[i];)i++;if(i>0)return t.slice(0,i)+ac(e.slice(i),t.slice(i),r)}let i=e?r.indexOf(e[0]):0,a=null!=t?r.indexOf(t[0]):r.length;return a-i>
151?r[Math.round(.5*(i+a))]:t&&t.length>1?t.slice(0,1):r[i]+ac(e.slice(1),null,r)}function ah(e){if(e.length!==ad(e[0]))throw Error("invalid integer part of order key: "+e)}function ad(e){if(e>="a"&&e<="z")return e.charCodeAt(0)-97+2;if(e>="A"&&e<="Z")return 90-e.charCodeAt(0)+2;throw Error("invalid order key head: "+e)}function ap(e){let t=ad(e[0]);if(t>e.length)throw Error("invalid order key: "+e);return e.slice(0,t)}function af(e,t){if(e==="A"+t[0].repeat(26))throw Error("invalid order key: "+e);let r=ap(e);if(e.slice(r.length).slice(-1)===t[0])throw Error("invalid order key: "+e)}function am(e,t){ah(e);let[r,...n]=e.split(""),i=!0;for(let e=n.length-1;i&&e>=0;e--){let r=t.indexOf(n[e])+1;r===t.length?n[e]=t[0]:(n[e]=t[r],i=!1)}if(!i)return r+n.join("");{if("Z"===r)return"a"+t[0];if("z"===r)return null;let e=String.fromCharCode(r.charCodeAt(0)+1);return e>"a"?n.push(t[0]):n.pop(),e+n.join("")}}function ag(e,t,r=au){if(null!=e&&af(e,r),null!=t&&af(t,r),null!=e&&null!=t&&e>=t)throw Error(e+" >= "+t);if(null==e){if(null==t)return"a"+r[0];let e=ap(t),n=t.slice(e.length);if(e==="A"+r[0].repeat(26))return e+ac("",n,r);if(e<t)return e;let i=function(e,t){ah(e);let[r,...n]=e.split(""),i=!0;for(let e=n.length-1;i&&e>=0;e--){let r=t.indexOf(n[e])-1;-1===r?n[e]=t.slice(-1):(n[e]=t[r],i=!1)}if(!i)return r+n.join("");{if("a"===r)return"Z"+t.slice(-1);if("A"===r)return null;let e=String.fromCharCode(r.charCodeAt(0)-1);return e<"Z"?n.push(t.slice(-1)):n.pop(),e+n.join("")}}(e,r);if(null==i)throw Error("cannot decrement any more");return i}if(null==t){let t=ap(e),n=e.slice(t.length),i=am(t,r);return null==i?t+ac(n,null,r):i}let n=ap(e),i=e.slice(n.length),a=ap(t),s=t.slice(a.length);if(n===a)return n+ac(i,s,r);let o=am(n,r);if(null==o)throw Error("cannot increment any more");return o<t?o:n+ac(i,null,r)}function ay(e,t,r,n=au){if(0===r)return[];if(1===r)return[ag(e,t,n)];if(null==t){let i=ag(e,t,n),a=[i];for(let e=0;e<r-1;e++)a.push(i=ag(i,t,n));return a}if(null==e){let i=ag(e,t,n),a=[i];for(let t=0;t<r-1;t++)a.push(i=ag(e,i,n));return a.reverse(),a}let i=Math.floor(r/2),a=ag(e,t,n);return[...ay(e,a,i,n),a,...ay(a,t,r-i-1,n)]}function ab(e,t){let r=e.stackOrder??null,n=t.stackOrder??null;return null===r||null===n?r===n?aw(e,t):null===r?-1:1:r===n?aw(e,t):r<n?-1:1}function aw(e,t){return e.y===t.y?e.x-t.x:e.y-t.y}e.s(["generateKeyBetween",0,ag,"generateNKeysBetween",0,ay],478802),e.s(["CANVAS_DRAG_STACK_ORDER",0,1e4,"canvasBlockOrder",0,function(e,t){return e.y===t.y?e.x-t.x:e.y-t.y},"canvasStackOrders",0,function(e){let t=Array(e.length);return e.map((e,t)=>t).sort((t,r)=>ab(e[t],e[r])).forEach((e,r)=>{t[e]=r+1}),t},"canvasStackingOrder",0,ab],929495);let av=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;for(var a_=[],ak=0;ak<256;++ak)a_.push((ak+256).toString(16).slice(1));function aS(e,t=0){return(a_[e[t+0]]+a_[e[t+1]]+a_[e[t+2]]+a_[e[t+3]]+"-"+a_[e[t+4]]+a_[e[t+5]]+"-"+a_[e[t+6]]+a_[e[t+7]]+"-"+a_[e[t+8]]+a_[e[t+9]]+"-"+a_[e[t+10]]+a_[e[t+11]]+a_[e[t+12]]+a_[e[t+13]]+a_[e[t+14]]+a_[e[t+15]]).toLowerCase()}let aI=function(e){if(!("string"==typeof e&&av.test(e)))throw TypeError("Invalid UUID");var t,r=new Uint8Array(16);return r[0]=(t=parseInt(e.slice(0,8),16))>>>24,r[1]=t>>>16&255,r[2]=t>>>8&255,r[3]=255&t,r[4]=(t=parseInt(e.slice(9,13),16))>>>8,r[5]=255&t,r[6]=(t=parseInt(e.slice(14,18),16))>>>8,r[7]=255&t,r[8]=(t=parseInt(e.slice(19,23),16))>>>8,r[9]=255&t,r[10]=(t=parseInt(e.slice(24,36),16))/0x10000000000&255,r[11]=t/0x100000000&255,r[12]=t>>>24&255,r[13]=t>>>16&255,r[14]=t>>>8&255,r[15]=255&t,r};function ax(e,t){return e<<t|e>>>32-t}var aD=function(e){function t(t,r,n,i){if("string"==typeof t&&(t=function(e){e=unescape(encodeURIComponent(e));for(var t=[],r=0;r<e.length;++r)t.push(e.charCodeAt(r));return t}(t)),"string"==typeof r&&(r=aI(r)),(null==(a=r)?void 0:a.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var a,s=new Uint8Array(16+t.length);if(s.set(r),s.set(t,r.length),(s=e(s))[6]=15&s[6]|80,s[8]=63&s[8]|128,n){i=i||0;for(var o=0;o<16;++o)n[i+o]=s[o];return n}return aS(s)}try{t.name="v5"}catch(e){}return t.DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",t.URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8",t}(function(e){var t=[0x5a827999,0x6ed9eba1,0x8f1bbcdc,0xca62c1d6],r=[0x67452301,0xefcdab89,0x98badcfe,0x10325476,0xc3d2e1f0];if("string"==typeof e){var n=unescape(encodeURIComponent(e));e=[];for(var i=0;i<n.length;++i)e.push(n.charCodeAt(i))}else Array.isArray(e)||(e=Array.prototype.slice.call(e));e.push(128);for(var a=Math.ceil((e.length/4+2)/16),s=Array(a),o=0;o<a;++o){for(var l=new Uint32Array(16),u=0;u<16;++u)l[u]=e[64*o+4*u]<<24|e[64*o+4*u+1]<<16|e[64*o+4*u+2]<<8|e[64*o+4*u+3];s[o]=l}s[a-1][14]=(e.length-1)*8/0x100000000,s[a-1][14]=Math.floor(s[a-1][14]),s[a-1][15]=(e.length-1)*8|0;for(var c=0;c<a;++c){for(var h=new Uint32Array(80),d=0;d<16;++d)h[d]=s[c][d];for(var p=16;p<80;++p)h[p]=ax(h[p-3]^h[p-8]^h[p-14]^h[p-16],1);for(var f=r[0],m=r[1],g=r[2],y=r[3],b=r[4],w=0;w<80;++w){var v=Math.floor(w/20),_=ax(f,5)+function(e,t,r,n){switch(e){case 0:return t&r^~t&n;case 1:case 3:return t^r^n;case 2:return t&r^t&n^r&n}}(v,m,g,y)+b+t[v]+h[w]>>>0;b=y,y=g,g=ax(m,30)>>>0,m=f,f=_}r[0]=r[0]+f>>>0,r[1]=r[1]+m>>>0,r[2]=r[2]+g>>>0,r[3]=r[3]+y>>>0,r[4]=r[4]+b>>>0}return[r[0]>>24&255,r[0]>>16&255,r[0]>>8&255,255&r[0],r[1]>>24&255,r[1]>>16&255,r[1]>>8&255,255&r[1],r[2]>>24&255,r[2]>>16&255,r[2]>>8&255,255&r[2],r[3]>>24&255,r[3]>>16&255,r[3]>>8&255,255&r[3],r[4]>>24&255,r[4]>>16&255,r[4]>>8&255,255&r[4]]}),aE=new Uint8Array(16),aN=null,a$=null,aC=0;let aT=function(e,t,r){e=e||{};var n=t&&r||0,i=t||new Uint8Array(16),a=e.random||(e.rng||function(){if(!o&&!(o="u">typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return o(aE)})(),s=void 0!==e.msecs?e.msecs:Date.now(),l=void 0!==e.seq?e.seq:null,u=a$,c=aN;return s>aC&&void 0===e.msecs&&(aC=s,null!==l&&(u=null,c=null)),null!==l&&(l>0x7fffffff&&(l=0x7fffffff),u=l>>>19&4095,c=524287&l),(null===u||null===c)&&(u=(u=127&a[6])<<8|a[7],c=(c=(c=63&a[8])<<8|a[9])<<5|a[10]>>>3),s+1e4>aC&&null===l?++c>524287&&(c=0,++u>
154095&&(u=0,aC++)):aC=s,a$=u,aN=c,i[n++]=aC/0x10000000000&255,i[n++]=aC/0x100000000&255,i[n++]=aC/0x1000000&255,i[n++]=aC/65536&255,i[n++]=aC/256&255,i[n++]=255&aC,i[n++]=u>>>4&15|112,i[n++]=255&u,i[n++]=c>>>13&63|128,i[n++]=c>>>5&255,i[n++]=c<<3&255|7&a[10],i[n++]=a[11],i[n++]=a[12],i[n++]=a[13],i[n++]=a[14],i[n++]=a[15],t||aS(i)};e.s(["v7",0,aT],110383);var aP=e.i(738954);function aR(e,t,r){if(e>100||t>100)throw Error(`${e}x${t} doesn't fit in 100x100`);let{PI:n,round:i,max:a,cos:s,abs:o}=Math,l=0,u=0,c=0,h=0;for(let n=0,i=0;n<e*t;n++,i+=4){let e=r[i+3]/255;l+=e/255*r[i],u+=e/255*r[i+1],c+=e/255*r[i+2],h+=e}h&&(l/=h,u/=h,c/=h);let d=h<e*t,p=d?5:7,f=a(1,i(p*e/a(e,t))),m=a(1,i(p*t/a(e,t))),g=[],y=[],b=[],w=[];for(let n=0,i=0;n<e*t;n++,i+=4){let e=r[i+3]/255,t=l*(1-e)+e/255*r[i],a=u*(1-e)+e/255*r[i+1],s=c*(1-e)+e/255*r[i+2];g[n]=(t+a+s)/3,y[n]=(t+a)/2-s,b[n]=t-a,w[n]=e}let v=(r,i,l)=>{let u=0,c=[],h=0,d=[];for(let p=0;p<l;p++)for(let f=0;f*l<i*(l-p);f++){let i=0;for(let t=0;t<e;t++)d[t]=s(n/e*f*(t+.5));for(let a=0;a<t;a++)for(let o=0,l=s(n/t*p*(a+.5));o<e;o++)i+=r[o+a*e]*d[o]*l;i/=e*t,f||p?(c.push(i),h=a(h,o(i))):u=i}if(h)for(let e=0;e<c.length;e++)c[e]=.5+.5/h*c[e];return[u,c,h]},[_,k,S]=v(g,a(3,f),a(3,m)),[I,x,D]=v(y,3,3),[E,N,$]=v(b,3,3),[C,T,P]=d?v(w,5,5):[],R=e>t,O=i(63*_)|i(31.5+31.5*I)<<6|i(31.5+31.5*E)<<12|i(31*S)<<18|d<<23,A=(R?m:f)|i(63*D)<<3|i(63*$)<<9|R<<15,j=[255&O,O>>8&255,O>>16,255&A,A>>8],M=d?6:5,z=0;for(let e of(d&&j.push(i(15*C)|i(15*P)<<4),d?[k,x,N,T]:[k,x,N]))for(let t of e)j[M+(z>>1)]|=i(15*t)<<((1&z++)<<2);return new Uint8Array(j)}function aO(e){let t=function(e){var t;let r,n,i,{PI:a,min:s,max:o,cos:l,round:u}=Math,c=e[0]|e[1]<<8|e[2]<<16,h=e[3]|e[4]<<8,d=(63&c)/63,p=(c>>6&63)/31.5-1,f=(c>>12&63)/31.5-1,m=c>>23,g=h>>15,y=o(3,g?m?5:7:7&h),b=o(3,g?7&h:m?5:7),w=m?(15&e[5])/15:1,v=(e[5]>>4)/15,_=m?6:5,k=0,S=(t,r,n)=>{let i=[];for(let a=0;a<r;a++)for(let s=+!a;s*r<t*(r-a);s++)i.push(((e[_+(k>>1)]>>((1&k++)<<2)&15)/7.5-1)*n);return i},I=S(y,b,(c>>18&31)/31),x=S(3,3,(h>>3&63)/63*1.25),D=S(3,3,(h>>9&63)/63*1.25),E=m&&S(5,5,v),N=(r=(t=e)[3],n=128&t[2],((i=128&t[4])?n?5:7:7&r)/(i?7&r:n?5:7)),$=u(N>1?32:32*N),C=u(N>1?32/N:32),T=new Uint8Array($*C*4),P=[],R=[];for(let e=0,t=0;e<C;e++)for(let r=0;r<$;r++,t+=4){let n=d,i=p,u=f,c=w;for(let e=0,t=o(y,m?5:3);e<t;e++)P[e]=l(a/$*(r+.5)*e);for(let t=0,r=o(b,m?5:3);t<r;t++)R[t]=l(a/C*(e+.5)*t);for(let e=0,t=0;e<b;e++)for(let r=+!e,i=2*R[e];r*b<y*(b-e);r++,t++)n+=I[t]*P[r]*i;for(let e=0,t=0;e<3;e++)for(let r=+!e,n=2*R[e];r<3-e;r++,t++){let e=P[r]*n;i+=x[t]*e,u+=D[t]*e}if(m)for(let e=0,t=0;e<5;e++)for(let r=+!e,n=2*R[e];r<5-e;r++,t++)c+=E[t]*P[r]*n;let h=n-2/3*i,g=(3*n-h+u)/2,v=g-u;T[t]=o(0,255*s(1,g)),T[t+1]=o(0,255*s(1,v)),T[t+2]=o(0,255*s(1,h)),T[t+3]=o(0,255*s(1,c))}return{w:$,h:C,rgba:T}}(e);return function(e,t,r){let n=4*e+1,i=6+t*(5+n),a=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,e>>8,255&e,0,0,t>>8,255&t,8,6,0,0,0,0,0,0,0,i>>>24,i>>16&255,i>>8&255,255&i,73,68,65,84,120,1],s=[0,0x1db71064,0x3b6e20c8,0x26d930ac,0x76dc4190,0x6b6b51f4,0x4db26158,0x5005713c,-0x12477ce0,-0xff06cbc,-0x29295c18,-0x349e4c74,-0x649b3d50,-0x792c2d2c,-0x5ff51d88,-0x42420de4],o=1,l=0;for(let e=0,i=0,s=n-1;e<t;e++,s+=n-1)for(a.push(e+1<t?0:1,255&n,n>>8,255&~n,n>>8^255,0),l=(l+o)%65521;i<s;i++){let e=255&r[i];a.push(e),l=(l+(o=(o+e)%65521))%65521}for(let[e,t]of(a.push(l>>8,255&l,o>>8,255&o,0,0,0,0,0,0,0,0,73,69,78,68,174,66,96,130),[[12,29],[37,41+i]])){let r=-1;for(let n=e;n<t;n++)r^=a[n],r=(r=r>>>4^s[15&r])>>>4^s[15&r];r=~r,a[t++]=r>>>24,a[t++]=r>>16&255,a[t++]=r>>8&255,a[t++]=255&r}return"data:image/png;base64,"+btoa(String.fromCharCode(...a))}(t.w,t.h,t.rgba)}async function aA(e,t){let r=await new Promise(r=>e.toBlob(e=>r(e),"image/webp",t));if(!r)throw Error("Could not encode image");return r}async function aj(e,t){let r=function(e,t){let r=e.width,n=e.height;if(t){let e=Math.min(1,t/Math.max(r,n));r=Math.max(1,Math.round(r*e)),n=Math.max(1,Math.round(n*e))}let i=document.createElement("canvas");i.width=r,i.height=n;let a=i.getContext("2d");if(!a)throw Error("Could not get canvas context");return a.drawImage(e,0,0,r,n),i}(e,t.maxDimension);if(!t.preferLossless)return aA(r,t.quality);let[n,i]=await Promise.all([aA(r,1),aA(r,t.quality)]);return n.size<=i.size?n:i}async function aM(e){let t=await createImageBitmap(e,{imageOrientation:"from-image"});try{let e=await aj(t,{quality:.9,maxDimension:144});return new File([e],"icon.webp",{type:"image/webp"})}finally{t.close()}}e.s(["rgbaToThumbHash",0,aR,"thumbHashToDataURL",0,aO],854799),e.s(["encodeBitmapToWebP",0,aj,"encodeIconFile",0,aM],370257);var az=e.i(768834);let aF=(0,az.create)(()=>({uploads:{}}));function aU(e,t){aF.setState(r=>({uploads:{...r.uploads,[e]:t}}))}function aL(e){aF.setState(t=>{if(!(e in t.uploads))return t;let{[e]:r,...n}=t.uploads;return{uploads:n}})}e.s(["clearImageUploadStatus",0,aL,"setImageUploadStatus",0,aU,"useImageUploadStatus",0,aF],840124);let aH=new Map,aB=0,aV=[];async function aq(e,t,r){await (aB<4?(aB++,Promise.resolve()):new Promise(e=>{aV.push(()=>{aB++,e()})}));let n=!1,i=()=>
15{if(!n){let e;n=!0,aB--,(e=aV.shift())&&e()}};try{var a;let n,s,o,l,u,c=(0,aP.supabaseBrowserClient)(),h=await aJ(e),d=aT()+(h?"."+e.name.split(".").pop():""),p=c.storage.from("minilink-user-assets").getPublicUrl(d).data.publicUrl,f=await createImageBitmap(e),m=f.width,g=f.height,y=(a=f,s=(n=document.createElement("canvas")).getContext("2d"),o=a.width,l=a.height,o>l?o>100&&(l*=100/o,o=100):l>100&&(o*=100/l,l=100),n.width=o,n.height=l,s.drawImage(a,0,0,o,l),u=s.getImageData(0,0,o,l),aO(aR(u.width,u.height,u.data)));aH.set(p,URL.createObjectURL(e)),aU(p,{state:"uploading"});let b={entity:r.entityID,attribute:"block/image",ignoreUndo:r.ignoreUndo||void 0,data:{fallback:y,type:"image",local:t.clientID,src:p,height:g,width:m}},w=async()=>{try{let n=e;if(!h)try{n=await aj(f,{quality:.92,preferLossless:"image/png"===e.type})}catch{}f.close(),await aG({rep:t,fileID:d,url:p,blob:n,file:e,entityID:r.entityID,attribute:r.attribute,thumbhash:y,width:m,height:g,ignoreUndo:r.ignoreUndo})}finally{i()}};return{imageFact:b,finishUpload:w}}catch(e){throw i(),e}}async function aG(e){let t=(0,aP.supabaseBrowserClient)(),r=async()=>{try{let{error:r}=await t.storage.from("minilink-user-assets").upload(e.fileID,e.blob,{cacheControl:"31536000"});if(r&&!("409"===String(r.statusCode)||r.message?.toLowerCase().includes("already exists")))return r;return null}catch(e){return{message:e instanceof Error?e.message:String(e)}}},n=async t=>{await e.rep.mutate.assertFact({entity:e.entityID,attribute:e.attribute,ignoreUndo:t||void 0,data:{fallback:e.thumbhash,type:"image",src:e.url,height:e.height,width:e.width}}),aL(e.url)},i=(t,r)=>{(function(e){console.error("Image upload failed",e);try{fetch("/api/log_upload_failure",{method:"POST",keepalive:!0,headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}).catch(()=>{})}catch{}})({src:e.url,fileName:e.file.name,fileType:e.file.type,fileSize:e.file.size,uploadSize:e.blob.size,attempts:r,error:{message:t.message,statusCode:t.statusCode}}),aU(e.url,{state:"failed",retry:a})},a=async()=>{aU(e.url,{state:"uploading"});let t=await r();if(t)return i(t,"manual-retry");await n(!0)};aU(e.url,{state:"uploading"});let s=await r();if(s&&(s=await r()),s)return i(s,"initial+auto-retry");await n(e.ignoreUndo)}async function aK(e,t,r){let{imageFact:n,finishUpload:i}=await aq(e,t,r);await t.mutate.assertFact(n),await i()}async function aJ(e){if("image/gif"===e.type||"image/apng"===e.type)return!0;if("image/webp"===e.type)try{let t=await e.slice(0,64).arrayBuffer(),r=new Uint8Array(t);for(let e=12;e<r.length-3;e++)if(65===r[e]&&78===r[e+1]&&73===r[e+2]&&77===r[e+3])return!0}catch{}return!1}async function aW(e,t){await e.from("blob_cleanup_queue").upsert({path:t.split("?")[0].split("/").at(-1)},{onConflict:"path",ignoreDuplicates:!0}).throwOnError()}e.s(["addImage",0,aK,"localImages",0,aH,"prepareImage",0,aq,"uploadImageAndFinalize",0,aG],870370);var aZ=e.i(813029);function aQ(e){return"full"===e||"compact"===e}async function aY(e,t){let r=await e.scanIndex.eav(t,"canvas/block"),n=[];for(let t of r){let r=await e.scanIndex.eav(t.data.value,"canvas/block/stack-order");n.push({entityID:t.data.value,x:t.data.position.x,y:t.data.position.y,stackOrder:r[0]?.data.value??null})}return n.sort(ab)}e.s(["isPageLinkDisplay",0,aQ,"normalizePageLinkDisplay",0,function(e){return aQ(e)?e:"full"}],868679);let aX=async(e,t)=>{await t.createEntity({entityID:e.newEntityID,permission_set:e.permission_set}),await t.assertFact({entity:e.parent,id:e.factID,data:{type:"ordered-reference",value:e.newEntityID,position:e.position},attribute:"card/block"}),await t.assertFact({entity:e.newEntityID,data:{type:"block-type-union",value:e.type},attribute:"block/type"});let r=!e.list&&(await t.scanIndex.eav(e.parent,"block/type")).length>0;(e.list||r)&&await t.assertFact({entity:e.newEntityID,attribute:"block/is-list",data:{type:"boolean",value:!0}}),e.list?.listStyle&&await t.assertFact({entity:e.newEntityID,attribute:"block/list-style",data:{type:"list-style-union",value:e.list.listStyle}}),e.list?.checklist!==void 0&&await t.assertFact({entity:e.newEntityID,attribute:"block/check-list",data:{type:"boolean",value:e.list.checklist}})},a0=async(e,t)=>{await t.createEntity({entityID:e.pageEntity,permission_set:e.permission_set}),await t.assertFact({entity:e.blockEntity,attribute:"block/card",data:{type:"reference",value:e.pageEntity}}),aQ(e.display)&&await t.assertFact({entity:e.blockEntity,attribute:"page-link/display",data:{type:"page-link-display-union",value:e.display}}),await t.assertFact({attribute:"page/type",entity:e.pageEntity,data:{type:"page-type-union",value:e.type}}),await aX({factID:e.firstBlockFactID,permission_set:e.permission_set,newEntityID:e.firstBlockEntity,type:"heading",parent:e.pageEntity,position:"a0"},t)},a1=async(e,t)=>{let r=await t.scanIndex.eav(e.rootEntity,"root/page"),n=r.toSorted((e,t)=>e.data.position>t.data.position?1:-1)[r.length-1];await t.createEntity({entityID:e.pageEntity,permission_set:e.permission_set}),await t.assertFact({id:e.navFactID,entity:e.rootEntity,attribute:"root/page",data:{type:"ordered-reference",value:e.pageEntity,position:ag(n?.data.position||null,
15null)}}),await t.assertFact({entity:e.pageEntity,attribute:"page/type",data:{type:"page-type-union",value:"doc"}}),await t.assertFact({entity:e.pageEntity,attribute:"page/route",data:{type:"string",value:e.route}}),await t.assertFact({entity:e.pageEntity,attribute:"page/title",data:{type:"string",value:e.title}}),await aX({factID:e.firstBlockFactID,permission_set:e.permission_set,newEntityID:e.firstBlockEntity,type:"text",parent:e.pageEntity,position:"a0"},t)},a2=async(e,t)=>{let r=(await t.scanIndex.eav(e.parent,"card/block")).toSorted((e,t)=>e.data.position>t.data.position?1:-1),n=r.findIndex(t=>t.data.value===e.entityID);if(-1===n)return;let i=r[n+1];if(!i){if(!e.permission_set)return;let i=aT(),a=r[n-1],s=ag(a?.data.position||null,r[n].data.position);await aX({parent:e.parent,permission_set:e.permission_set,factID:aT(),type:"text",newEntityID:i,position:s},t);return}await t.assertFact({id:r[n].id,entity:e.parent,attribute:"card/block",data:{type:"ordered-reference",position:ag(i.data.position,r[n+2]?.data.position||null),value:e.entityID}})},a5=async(e,t)=>{let[r]=await t.scanIndex.eav(e.mailboxEntity,"mailbox/draft");r||(await t.createEntity({entityID:e.newEntity,permission_set:e.permission_set}),await t.assertFact({entity:e.mailboxEntity,attribute:"mailbox/draft",data:{type:"reference",value:e.newEntity}}),await aX({factID:e.firstBlockFactID,permission_set:e.permission_set,newEntityID:e.firstBlockEntity,type:"text",parent:e.newEntity,position:"a0"},t))};async function a3(e,t){await e.createEntity({entityID:t.entityID,permission_set:t.permission_set}),await e.assertFact({entity:t.entityID,attribute:"block/text",data:{type:"text",value:t.content},author_did:t.authorDid}),await e.assertFact({entity:t.entityID,attribute:"comment/author",data:{type:"string",value:t.authorDid},author_did:t.authorDid}),await e.assertFact({entity:t.entityID,attribute:"comment/created-at",data:{type:"string",value:t.createdAt},author_did:t.authorDid})}let a4={retractAttribute:async(e,t)=>{for(let r of[e.attribute].flat()){let n=(await t.scanIndex.eav(e.entity,r))[0];n&&await t.retractFact(n.id)}},addBlock:aX,addCanvasBlock:async(e,t)=>{await t.createEntity({entityID:e.newEntityID,permission_set:e.permission_set}),await t.assertFact({entity:e.parent,id:e.factID,data:{type:"spatial-reference",value:e.newEntityID,position:e.position},attribute:"canvas/block"}),await t.assertFact({entity:e.newEntityID,data:{type:"block-type-union",value:e.type},attribute:"block/type"}),void 0!==e.width&&await t.assertFact({entity:e.newEntityID,attribute:"canvas/block/width",data:{type:"number",value:e.width}});let r=await aY(t,e.parent),n=r[r.length-1]?.stackOrder??null;await t.assertFact({entity:e.newEntityID,attribute:"canvas/block/stack-order",data:{type:"string",value:ag(n,null)}})},moveCanvasBlockLayer:async(e,t)=>{let r=await aY(t,e.parent),n=r.findIndex(t=>t.entityID===e.entityID);if(-1===n||("forward"===e.action||"front"===e.action?n===r.length-1:0===n))return;let i=r.filter(e=>null===e.stackOrder).length;if(i>0){let e=ay(null,r[i]?.stackOrder||null,i);for(let n=0;n<i;n++)r[n].stackOrder=e[n],await t.assertFact({entity:r[n].entityID,attribute:"canvas/block/stack-order",data:{type:"string",value:e[n]}})}let a=r.map(e=>e.stackOrder),s="forward"===e.action?ag(a[n+1],a[n+2]||null):"backward"===e.action?ag(a[n-2]||null,a[n-1]):"front"===e.action?ag(a[a.length-1],null):ag(null,a[0]);await t.assertFact({entity:e.entityID,attribute:"canvas/block/stack-order",data:{type:"string",value:s}})},addLastBlock:async(e,t)=>{let r=await t.scanIndex.eav(e.parent,"card/block"),n=r.toSorted((e,t)=>e.data.position>t.data.position?1:-1)[r.length-1];await t.assertFact({entity:e.parent,id:e.factID,attribute:"card/block",data:{type:"ordered-reference",value:e.entity,position:ag(n?.data.position||null,null)}})}
15,outdentBlock:async(e,t)=>{let r=(await t.scanIndex.eav(e.newParent,"card/block")).toSorted((e,t)=>e.data.position>t.data.position?1:-1),n=(await t.scanIndex.eav(e.oldParent,"card/block")).toSorted((e,t)=>e.data.position>t.data.position?1:-1),i=n.findIndex(t=>t.data.value===e.block);if(-1===i)return;let a=r.findIndex(t=>t.data.value===e.after);if(-1===a)return;let s=new Set(e.excludeFromSiblings||[]),o=n.slice(i+1).filter(e=>!s.has(e.data.value)),l=(await t.scanIndex.eav(e.block,"card/block")).toSorted((e,t)=>e.data.position>t.data.position?1:-1),u=l[l.length-1]?.data.position||null;for(let r of o)u=ag(u,null),await t.assertFact({entity:e.block,id:r.id,attribute:"card/block",data:{type:"ordered-reference",position:u,value:r.data.value}});let c=ag(r[a]?.data.position,r[a+1]?.data.position||null);await t.assertFact({id:n[i].id,entity:e.newParent,attribute:"card/block",data:{type:"ordered-reference",position:c,value:e.block}})},moveBlockUp:async(e,t)=>{let r=(await t.scanIndex.eav(e.parent,"card/block")).toSorted((e,t)=>e.data.position>t.data.position?1:-1),n=r.findIndex(t=>t.data.value===e.entityID);if(-1===n)return;let i=r[n-1];i&&await t.assertFact({id:r[n].id,entity:e.parent,attribute:"card/block",data:{type:"ordered-reference",position:ag(r[n-2]?.data.position||null,i.data.position),value:e.entityID}})},moveBlockDown:a2,addPageLinkBlock:a0,addPublicationNavPage:a1,addPublicationNavLink:async(e,t)=>{let r=await t.scanIndex.eav(e.rootEntity,"root/page"),n=r.toSorted((e,t)=>e.data.position>t.data.position?1:-1)[r.length-1];await t.createEntity({entityID:e.linkEntity,permission_set:e.permission_set}),await t.assertFact({id:e.navFactID,entity:e.rootEntity,attribute:"root/page",data:{type:"ordered-reference",value:e.linkEntity,position:ag(n?.data.position||null,null)}}),await t.assertFact({entity:e.linkEntity,attribute:"page/external-url",data:{type:"string",value:e.url}}),await t.assertFact({entity:e.linkEntity,attribute:"page/title",data:{type:"string",value:e.title}})},removePublicationNavEntry:async(e,t)=>{let r=(await t.scanIndex.eav(e.rootEntity,"root/page")).find(t=>t.data.value===e.entity);r&&await t.retractFact(r.id),await t.deleteEntity(e.entity)},moveBlock:async(e,t)=>{let r,n=(await t.scanIndex.eav(e.oldParent,"card/block")).toSorted((e,t)=>e.data.position>t.data.position?1:-1),i=(await t.scanIndex.eav(e.newParent,"card/block")).toSorted((e,t)=>e.data.position>t.data.position?1:-1),a=n.find(t=>t.data.value===e.block);if(!a)return;let s=e.position;switch(s.type){case"first":r=ag(null,i[0]?.data.position||null);break;case"end":r=ag(i[i.length-1]?.data.position||null,null);break;case"before":{let e=i.findIndex(e=>e.data.value==s.entity);r=ag(e>0&&i[e-1].data.position||null,i[e]?.data.position||null);break}case"after":{let e=i.findIndex(e=>e.data.value==s?.entity);r=ag(i[e]?.data.position||null,i[e+1]?.data.position||null)}}await t.assertFact({id:a.id,entity:e.newParent,attribute:"card/block",data:{type:"ordered-reference",value:a.data.value,position:r}})},moveBlocks:async(e,t)=>{let r=(await t.scanIndex.eav(e.parent,"card/block")).toSorted((e,t)=>e.data.position>t.data.position?1:-1),n=new Set(e.blocks),i=e.blocks.map(e=>r.find(t=>t.data.value===e)).filter(e=>!!e);if(0===i.length)return;let a=r.filter(e=>!n.has(e.data.value)),s=null===e.after?-1:a.findIndex(t=>t.data.value===e.after),o=a[s]?.data.position||null,l=a[s+1]?.data.position||null,u=ag(o,l);for(let r of i)await t.assertFact({id:r.id,entity:e.parent,attribute:"card/block",data:{type:"ordered-reference",value:r.data.value,position:u}}),u=ag(u,l)},assertFact:async(e,t)=>{for(let r of[e].flat())await t.assertFact(r)},retractFact:async(e,t)=>{await t.retractFact(e.factID)},removeBlock:async(e,t)=>{for(let r of[e].flat()){let[e]=await t.scanIndex.eav(r.blockEntity,"block/image");await t.runOnServer(async({supabase:t})=>{e&&await aW(t,e.data.src)}),await t.runOnClient(async()=>{if(e){let t=aH.get(e.data.src);t&&(URL.revokeObjectURL(t),aH.delete(e.data.src)),aL(e.data.src)}}),await t.deleteEntity(r.blockEntity)}},deleteEntity:async(e,t)=>{await t.deleteEntity(e.entity)},moveChildren:async(e,t)=>{let r=(await t.scanIndex.eav(e.oldParent,"card/block")).toSorted((e,t)=>e.data.position>t.data.position?1:-1),n=(await t.scanIndex.eav(e.newParent,"card/block")).toSorted((e,t)=>e.data.position>t.data.position?1:-1),i=n.findIndex(t=>
15t.data.value===e.after),a=ag(n[i]?.data.position||null,n[i+1]?.data.position||null);for(let s of r)await t.assertFact({id:s.id,entity:e.newParent,attribute:"card/block",data:{type:"ordered-reference",value:s.data.value,position:a}}),a=ag(a,n[i+1]?.data.position||null)},increaseHeadingLevel:async(e,t)=>{let r=(await t.scanIndex.eav(e.entityID,"block/type"))[0],n=(await t.scanIndex.eav(e.entityID,"block/heading-level"))[0];return(r?.data.value!=="heading"&&await t.assertFact({entity:e.entityID,attribute:"block/type",data:{type:"block-type-union",value:"heading"}}),n&&r?.data.value==="heading")?n?.data.value!==3?await t.assertFact({entity:e.entityID,attribute:"block/heading-level",data:{type:"number",value:n.data.value+1}}):void 0:await t.assertFact({entity:e.entityID,attribute:"block/heading-level",data:{type:"number",value:1}})},archiveDraft:async(e,t)=>{let[r]=await t.scanIndex.eav(e.mailboxEntity,"mailbox/draft");if(!r)return;let[n]=await t.scanIndex.eav(e.mailboxEntity,"mailbox/archive"),i=n?.data.value;n||(i=e.archiveEntity,await t.createEntity({entityID:i,permission_set:e.entity_set}),await t.assertFact({entity:e.mailboxEntity,attribute:"mailbox/archive",data:{type:"reference",value:i}}));let a=(await t.scanIndex.eav(i,"card/block")).toSorted((e,t)=>e.data.position>t.data.position?1:-1)[0];await t.createEntity({entityID:e.newBlockEntity,permission_set:e.entity_set}),await t.assertFact({entity:e.newBlockEntity,attribute:"block/type",data:{type:"block-type-union",value:"card"}}),await t.assertFact({entity:e.newBlockEntity,attribute:"block/card",data:{type:"reference",value:r.data.value}}),await t.assertFact({entity:i,attribute:"card/block",data:{type:"ordered-reference",value:e.newBlockEntity,position:ag(null,a?.data.position)}}),await t.retractFact(r.id)},toggleTodoState:async(e,t)=>{let[r]=await t.scanIndex.eav(e.entityID,"block/check-list");r?r.data.value?await t.retractFact(r.id):await t.assertFact({entity:e.entityID,attribute:"block/check-list",data:{type:"boolean",value:!0}}):await t.assertFact({entity:e.entityID,attribute:"block/check-list",data:{type:"boolean",value:!1}})},createDraft:a5,createEntity:async(e,t)=>{for(let r of e)await t.createEntity(r)},addPollOption:async(e,t)=>{await t.createEntity({entityID:e.pollOptionEntity,permission_set:e.permission_set}),await t.assertFact({entity:e.pollOptionEntity,attribute:"poll-option/name",data:{type:"string",value:e.pollOptionName}});let r=await t.scanIndex.eav(e.pollEntity,"poll/options"),n=r.toSorted((e,t)=>e.data.position>t.data.position?1:-1)[r.length-1];await t.assertFact({entity:e.pollEntity,id:e.factID,attribute:"poll/options",data:{type:"ordered-reference",value:e.pollOptionEntity,position:ag(n?.data.position||null,null)}})},removePollOption:async(e,t)=>{await t.deleteEntity(e.optionEntity)},addGalleryImage:async(e,t)=>{await t.createEntity({entityID:e.imageEntity,permission_set:e.permission_set});let r=await t.scanIndex.eav(e.galleryEntity,"gallery/image"),n=r.toSorted((e,t)=>e.data.position>t.data.position?1:-1)[r.length-1];await t.assertFact({entity:e.galleryEntity,id:e.factID,attribute:"gallery/image",data:{type:"ordered-reference",value:e.imageEntity,position:ag(n?.data.position||null,null)}})},removeGalleryImage:async(e,t)=>{let[r]=await t.scanIndex.eav(e.imageEntity,"block/image");await t.runOnServer(async({supabase:e})=>{r&&await aW(e,r.data.src)}),await t.runOnClient(async()=>{if(r){let e=aH.get(r.data.src);e&&(URL.revokeObjectURL(e),aH.delete(r.data.src)),aL(r.data.src)}}),await t.deleteEntity(e.imageEntity)},updatePublicationDraft:async(e,t)=>{await t.runOnServer(async r=>{let n={};if(void 0!==e.description&&(n.description=e.description),void 0!==e.title&&(n.title=e.title),void 0!==e.tags&&(n.tags=e.tags),void 0!==e.preferences&&(n.preferences=e.preferences),Object.keys(n).length>0){let{data:e}=await r.supabase.from("leaflets_in_publications").update(n).eq("leaflet",t.permission_token_id).select("leaflet");e&&0!==e.length||await r.supabase.from("leaflets_to_documents").update(n).eq("leaflet",t.permission_token_id)}}),await t.runOnClient(async({tx:t})=>{void 0!==e.title&&await t.set("publication_title",e.title),void 0!==e.description&&await t.set("publication_description",e.description),void 0!==e.tags&&await t.set("publication_tags",e.tags),void 0!==e.localPublishedAt&&await t.set("publication_local_published_at",e.localPublishedAt),void 0!==e.preferences&&await t.set("post_preferences",e.preferences)})},updateLeafletMetadata:async(e,t)=>{await t.runOnServer(async r=>{let n={};if(void 0!==e.title&&(n.title=e.title),void 0!==e.description&&(n.description=e.description),0===Object.keys(n).length)return;let{data:i}=await r.supabase.from("permission_tokens").select("root_entity, permission_token_rights(write)").eq("id",t.permission_token_id).single();!i||i.permission_token_rights.some(e=>e.write)&&await r.supabase.from("permission_tokens").update(n).eq("root_entity",i.root_entity)})},toggleDraftContributor:async(e,t)=>{await t.runOnServer(async({supabase:r})=>{let{contributor_did:n}=e,i=t.permission_token_id;if(!e.selected)return void await r.from("leaflet_contributors").delete().eq("leaflet",i).eq("contributor_did",n);let{data:a}=await r.from("leaflets_in_publications").select("publication, publications(identity_did)").eq("leaflet",i).maybeSingle();if(a?.publication){if(n!==a.publications?.identity_did){let{data:e}=await r.from("publication_contributors").select("confirmed").eq("publication_uri",a.publication).eq("contributor_did",n).maybeSingle();if(!e?.confirmed)return}await r.from("leaflet_contributors").upsert({leaflet:i,contributor_did:n},{onConflict:"leaflet,contributor_did",ignoreDuplicates:!0})}}),await t.runOnClient(async({tx:t})=>{let r=await t.get("draft_contributors")??[],n=e.selected?r.includes(e.contributor_did)?r:[...r,e.contributor_did]:r.filter(t=>t!==e.contributor_did);await t.set("draft_contributors",n)})},toggleCollapsedBlocks:async(e,t)=>{if(await t.runOnClient(async()=>{aZ.useUIState.setState(t=>{let r=t.foldedBlocks.filter(t=>!e.uncollapse?.includes(t));for(let t of e.collapse??[])r.includes(t)||r.push(t);return{foldedBlocks:r}})}),!t.sessionDid)return;let r=(await t.scanIndex.eav(t.rootEntity,"root/collapsed-blocks")).find(e=>e.author_did===t.sessionDid),n=new Set(r?.data.value??[]);for(let t of e.uncollapse??[])n.delete(t);for(let t of e.collapse??[])n.add(t);if(0===n.size){r&&await t.retractFact(r.id);return}await t.assertFact({id:r?.id??aD(`${t.rootEntity}:${t.sessionDid}`,"5f4bfb95-2a1f-49f4-8f6b-77f0f1a72897"),entity:t.rootEntity,attribute:"root/collapsed-blocks",data:{type:"string-array",value:[...n]},author_did:t.sessionDid})},createFootnote:async(e,t)=>{await t.createEntity({entityID:e.footnoteEntityID,permission_set:e.permission_set}),await t.assertFact({id:e.footnoteFactID,entity:e.blockID,attribute:"block/footnote",data:{type:"ordered-reference",value:e.footnoteEntityID,position:e.position}})},deleteFootnote:async(e,t)=>{let r=(await t.scanIndex.eav(e.blockID,"block/footnote")).find(t=>t.data.value===e.footnoteEntityID);r&&(await t.retractFact(r.id),await t.deleteEntity(e.footnoteEntityID))},createEditorComment:async(e,t)=>{await a3(t,{...e,entityID:e.commentEntityID}),await t.assertFact({id:e.commentFactID,entity:e.blockID,attribute:"block/comment",data:{type:"ordered-reference",value:e.commentEntityID,position:e.position}}),await t.assertFact({entity:e.commentEntityID,attribute:"comment/anchor-start",data:{type:"number",value:e.anchorStart}}),await t.assertFact({entity:e.commentEntityID,attribute:"comment/anchor-end",data:{type:"number",value:e.anchorEnd}})},createEditorCommentReply:async(e,t)=>{await a3(t,{...e,entityID:e.replyEntityID}),await t.assertFact({id:e.replyFactID,entity:e.commentEntityID,attribute:"comment/reply",data:{type:"ordered-reference",value:e.replyEntityID,position:e.position}})},deleteEditorComment:async(e,t)=>{let r=(await t.scanIndex.eav(e.blockID,"block/comment")).find(t=>t.data.value===e.commentEntityID);for(let n of(r&&await t.retractFact(r.id),await t.scanIndex.eav(e.commentEntityID,"comment/reply")))await t.deleteEntity(n.data.value);await t.deleteEntity(e.commentEntityID)},deleteEditorCommentReply:async(e,t)=>{let r=(await t.scanIndex.eav(e.commentEntityID,"comment/reply")).find(t=>t.data.value===e.replyEntityID);r&&await t.retractFact(r.id),await t.deleteEntity(e.replyEntityID)},editEditorComment:async(e,t)=>{let r=await t.scanIndex.eav(e.entityID,"comment/author");if(r[0]?.data.value===e.authorDid){for(let r of(await t.scanIndex.eav(e.entityID,"block/text")))
15await t.retractFact(r.id);await t.assertFact({entity:e.entityID,attribute:"block/text",data:{type:"text",value:e.content},author_did:e.authorDid})}}},a6={"root/page":{type:"ordered-reference",cardinality:"many"},"root/cover-image":{type:"reference",cardinality:"one"},"root/collapsed-blocks":{type:"string-array",cardinality:"many"},"card/block":{type:"ordered-reference",cardinality:"many"},"page/type":{type:"page-type-union",cardinality:"one"},"page/route":{type:"string",cardinality:"one"},"page/title":{type:"string",cardinality:"one"},"page/external-url":{type:"string",cardinality:"one"},"canvas/block":{type:"spatial-reference",cardinality:"many"},"canvas/block/width":{type:"number",cardinality:"one"},"canvas/block/rotation":{type:"number",cardinality:"one"},"canvas/block/stack-order":{type:"string",cardinality:"one"},"canvas/narrow-width":{type:"boolean",cardinality:"one"},"canvas/background-pattern":{type:"canvas-pattern-union",cardinality:"one"},"block/type":{type:"block-type-union",cardinality:"one"},"block/is-list":{type:"boolean",cardinality:"one"},"block/members-only-audience":{type:"string",cardinality:"one"},"block/members-only-tier":{type:"string",cardinality:"many"},"block/is-locked":{type:"boolean",cardinality:"one"},"block/check-list":{type:"boolean",cardinality:"one"},"block/text-alignment":{type:"text-alignment-type-union",cardinality:"one"},"block/date-time":{type:"date-time",cardinality:"one"},"block/text":{type:"text",cardinality:"one"},"block/heading-level":{type:"number",cardinality:"one"},"block/text-size":{type:"text-size-union",cardinality:"one"},"block/image":{type:"image",cardinality:"one"},"block/card":{type:"reference",cardinality:"one"},"page-link/display":{type:"page-link-display-union",cardinality:"one"},"block/bluesky-post":{type:"bluesky-post",cardinality:"one"},"block/standard-site-post":{type:"string",cardinality:"one"},"standard-site-post/size":{type:"standard-site-post-size-union",cardinality:"one"},"standard-site-post/show-publication-theme":{type:"boolean",cardinality:"one"},"block/standard-site-publication":{type:"string",cardinality:"one"},"standard-site-publication/show-publication-theme":{type:"boolean",cardinality:"one"},"block/math":{type:"string",cardinality:"one"},"block/code":{type:"string",cardinality:"one"},"block/code-language":{type:"string",cardinality:"one"},"block/list-style":{type:"list-style-union",cardinality:"one"},"block/list-number":{type:"number",cardinality:"one"},"block/footnote":{type:"ordered-reference",cardinality:"many"},"block/comment":{type:"ordered-reference",cardinality:"many"},"comment/reply":{type:"ordered-reference",cardinality:"many"},"comment/author":{type:"string",cardinality:"one"},"comment/created-at":{type:"string",cardinality:"one"},"comment/anchor-start":{type:"number",cardinality:"one"},"comment/anchor-end":{type:"number",cardinality:"one"},"link/preview":{type:"image",cardinality:"one"},"link/url":{type:"string",cardinality:"one"},"link/description":{type:"string",cardinality:"one"},"link/title":{type:"string",cardinality:"one"},"theme/heading-font":{type:"string",cardinality:"one"},"theme/body-font":{type:"string",cardinality:"one"},"theme/page-leaflet-watermark":{type:"boolean",cardinality:"one"},"theme/page-width":{type:"number",cardinality:"one"},"theme/page-background":{type:"color",cardinality:"one"},"theme/background-image":{type:"image",cardinality:"one"},"theme/background-image-repeat":{type:"number",cardinality:"one"},"theme/wordmark-image":{type:"image",cardinality:"one"},"theme/wordmark-width":{type:"number",cardinality:"one"},"theme/card-background":{type:"color",cardinality:"one"},"theme/card-background-image":{type:"image",cardinality:"one"},"theme/card-background-image-repeat":{type:"number",cardinality:"one"},"theme/card-background-image-opacity":{type:"number",cardinality:"one"},"theme/card-border-hidden":{type:"boolean",cardinality:"one"},"theme/primary":{type:"color",cardinality:"one"},"theme/accent-background":{type:"color",cardinality:"one"},"theme/accent-text":{type:"color",cardinality:"one"},"theme/highlight-1":{type:"color",cardinality:"one"},"theme/highlight-2":{type:"color",cardinality:"one"},"theme/highlight-3":{type:"color",cardinality:"one"},"theme/code-theme":{type:"string",cardinality:"one"},"mailbox/draft":{type:"reference",cardinality:"one"},"mailbox/archive":{type:"reference",cardinality:"one"},"mailbox/subscriber-count":{type:"number",cardinality:"one"},"embed/url":{type:"string",cardinality:"one"},"embed/html":{type:"string",cardinality:"one"},"embed/height":{type:"number",cardinality:"one"},"embed/aspect-ratio":{type:"string",cardinality:"one"},"bluesky-post/url":{type:"string",cardinality:"one"},"bluesky-post/host":{type:"string",cardinality:"one"},"button/text":{type:"string",cardinality:"one"},"button/url":{type:"string",cardinality:"one"},"image/full-bleed":{type:"boolean",cardinality:"one"},"image/alt":{type:"string",cardinality:"one"},"image/name":{type:"string",cardinality:"one"},"image/max-width":{type:"number",cardinality:"one"},"gallery/image":{type:"ordered-reference",cardinality:"many"},"gallery/format":{type:"gallery-format-union",cardinality:"one"},"gallery/gap":{type:"number",cardinality:"one"},"gallery/max-width":{type:"number",cardinality:"one"},"poll/options":{type:"ordered-reference",cardinality:"many"},"poll-option/name":{type:"string",cardinality:"one"},"posts-list/view":{type:"posts-list-view-union",cardinality:"one"},"posts-list/highlight-first-post":{type:"boolean",cardinality:"one"},"posts-list/show-page-count":{type:"boolean",cardinality:"one"},"posts-list/filter-tag":{type:"string",cardinality:"many"},"posts-list/limit":{type:"number",cardinality:"one"}
15,"posts-list/reader-controls":{type:"boolean",cardinality:"one"},"posts-list/reader-search":{type:"boolean",cardinality:"one"},"posts-list/reader-tag-filter":{type:"boolean",cardinality:"one"},"posts-list/reader-sort":{type:"boolean",cardinality:"one"},"recommended-pubs/compact":{type:"boolean",cardinality:"one"},"post-header/compact":{type:"boolean",cardinality:"one"}};var a9=e.i(616009),a8=e.i(734582);let a7=Symbol.for("drizzle:entityKind");function se(e,t){if(!e||"object"!=typeof e)return!1;if(e instanceof t)return!0;if(!Object.prototype.hasOwnProperty.call(t,a7))throw Error(`Class "${t.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let r=e.constructor;if(r)for(;r;){if(a7 in r&&r[a7]===t[a7])return!0;r=Object.getPrototypeOf(r)}return!1}Symbol.for("drizzle:hasOwnEntityKind");let st=Symbol.for("drizzle:Name"),sr=Symbol.for("drizzle:Schema"),sn=Symbol.for("drizzle:Columns"),si=Symbol.for("drizzle:OriginalName"),sa=Symbol.for("drizzle:BaseName"),ss=Symbol.for("drizzle:IsAlias"),so=Symbol.for("drizzle:ExtraConfigBuilder"),sl=Symbol.for("drizzle:IsDrizzleTable");class su{static [a7]="Table";static Symbol={Name:st,Schema:sr,OriginalName:si,Columns:sn,BaseName:sa,IsAlias:ss,ExtraConfigBuilder:so};[st];[si];[sr];[sn];[sa];[ss]=!1;[so]=void 0;[sl]=!0;constructor(e,t,r){this[st]=this[si]=e,this[sr]=t,this[sa]=r}}let sc=Symbol.for("drizzle:PgInlineForeignKeys");class sh extends su{static [a7]="PgTable";static Symbol=Object.assign({},su.Symbol,{InlineForeignKeys:sc});[sc]=[];[su.Symbol.ExtraConfigBuilder]=void 0}let sd=(e,t,r)=>(function(e,t,r,n,i=e){let a=new sh(e,n,i),s=Object.fromEntries(Object.entries(t).map(([e,t])=>{let r=t.build(a);return a[sc].push(...t.buildForeignKeys(r,a)),[e,r]})),o=Object.assign(a,s);return o[su.Symbol.Columns]=s,r&&(o[sh.Symbol.ExtraConfigBuilder]=r),o})(e,t,r,void 0);class sp{static [a7]="ColumnBuilder";config;constructor(e,t,r){this.config={name:e,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:t,columnType:r}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}}class sf{constructor(e,t){this.table=e,this.config=t,this.name=t.name,this.notNull=t.notNull,this.default=t.default,this.defaultFn=t.defaultFn,this.onUpdateFn=t.onUpdateFn,this.hasDefault=t.hasDefault,this.primary=t.primaryKey,this.isUnique=t.isUnique,this.uniqueName=t.uniqueName,this.uniqueType=t.uniqueType,this.dataType=t.dataType,this.columnType=t.columnType}static [a7]="Column";name;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}}class sm{static [a7]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,t){this.reference=()=>{let{name:t,columns:r,foreignColumns:n}=e();return{name:t,columns:r,foreignTable:n[0].table,foreignColumns:n}},t&&(this._onUpdate=t.onUpdate,this._onDelete=t.onDelete)}onUpdate(e){return this._onUpdate=void 0===e?"no action":e,this}onDelete(e){return this._onDelete=void 0===e?"no action":e,this}build(e){return new sg(e,this)}}class sg{constructor(e,t){this.table=e,this.reference=t.reference,this.onUpdate=t._onUpdate,this.onDelete=t._onDelete}static [a7]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:t,foreignColumns:r}=this.reference(),n=t.map(e=>e.name),i=r.map(e=>e.name),a=[this.table[sh.Symbol.Name],...n,r[0].table[sh.Symbol.Name],...i];return e??`${a.join("_")}_fk`}}function sy(e,...t){return e(...t)}function sb(e){return new s_(e)}function sw(e,t){return`${e[sh.Symbol.Name]}_${t.join("_")}_unique`}class sv{constructor(e,t){this.name=t,this.columns=e}static [a7]="PgUniqueConstraintBuilder";columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new sk(e,this.columns,this.nullsNotDistinctConfig,this.name)}}class s_{static [a7]="PgUniqueOnConstraintBuilder";name;constructor(e){this.name=e}on(...e){return new sv(e,this.name)}}class sk{constructor(e,t,r,n){this.table=e,this.columns=t,this.name=n??sw(this.table,this.columns.map(e=>e.name)),this.nullsNotDistinct=r}static [a7]="PgUniqueConstraint";columns;name;nullsNotDistinct=!1;getName(){return this.name}}function sS(e,t,r){for(let n=t;n<e.length;n++){let i=e[n];if("\\"===i){n++;continue}if('"'===i)return[e.slice(t,n).replace(/\\/g,""),n+1];if(!r&&(","===i||"}"===i))return[e.slice(t,n).replace(/\\/g,""),n]}return[e.slice(t).replace(/\\/g,""),e.length]}class sI extends sp{foreignKeyConfigs=[];static [a7]="PgColumnBuilder";array(e){return new sD(this.config.name,this,e)}references(e,t={}){return this.foreignKeyConfigs.push({ref:e,actions:t}),this}unique(e,t){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=t?.nulls,this}buildForeignKeys(e,t){return this.foreignKeyConfigs.map(({ref:r,actions:n})=>sy((r,n)=>{let i=new sm(()=>({columns:[e],foreignColumns:[r()]}));return n.onUpdate&&i.onUpdate(n.onUpdate),n.onDelete&&i.onDelete(n.onDelete),i.build(t)},r,n))}}class sx extends sf{constructor(e,t){t.uniqueName||(t.uniqueName=sw(e,[t.name])),super(e,t),this.table=e}static [a7]="PgColumn"}class sD extends sI{static [a7]="PgArrayBuilder";constructor(e,t,r){super(e,"array","PgArray"),this.config.baseBuilder=t,this.config.size=r}build(e){let t=this.config.baseBuilder.build(e);return new sE(e,this.config,t)}}class sE extends sx{constructor(e,t,r,n){super(e,t),this.baseColumn=r,this.range=n,this.size=t.size}size;static [a7]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${"number"==typeof this.size?this.size:""}]`}mapFromDriverValue(e){return"string"==typeof e&&(e=function(e){let[t]=function e(t,r=0){let n=[],i=r,a=!1;for(;i<t.length;){let s=t[i];if(","===s){(a||i===r)&&n.push(""),a=!0,i++;continue}if(a=!1,"\\"===s){i+=2;continue}if('"'===s){let[e,r]=sS(t,i+1,!0);n.push(e),i=r;continue}if("}"===s)return[n,i+1];
15if("{"===s){let[r,a]=e(t,i+1);n.push(r),i=a;continue}let[o,l]=sS(t,i,!1);n.push(o),i=l}return[n,i]}(e,1);return t}(e)),e.map(e=>this.baseColumn.mapFromDriverValue(e))}mapToDriverValue(e,t=!1){let r=e.map(e=>null===e?null:se(this.baseColumn,sE)?this.baseColumn.mapToDriverValue(e,!0):this.baseColumn.mapToDriverValue(e));return t?r:function e(t){return`{${t.map(t=>Array.isArray(t)?e(t):"string"==typeof t?`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${t}`).join(",")}}`}(r)}}let sN=Symbol.for("drizzle:isPgEnum");class s$ extends sI{static [a7]="PgEnumColumnBuilder";constructor(e,t){super(e,"string","PgEnumColumn"),this.config.enum=t}build(e){return new sC(e,this.config)}}class sC extends sx{static [a7]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,t){super(e,t),this.enum=t.enum}getSQLType(){return this.enum.enumName}}function sT(e,t){let r;return r=Object.assign(e=>new s$(e,r),{enumName:e,enumValues:t,schema:void 0,[sN]:!0})}class sP extends sI{static [a7]="PgTextBuilder";constructor(e,t){super(e,"string","PgText"),this.config.enumValues=t.enum}build(e){return new sR(e,this.config)}}class sR extends sx{static [a7]="PgText";enumValues=this.config.enumValues;getSQLType(){return"text"}}function sO(e,t={}){return new sP(e,t)}class sA extends sI{static [a7]="PgJsonbBuilder";constructor(e){super(e,"json","PgJsonb")}build(e){return new sj(e,this.config)}}class sj extends sx{static [a7]="PgJsonb";constructor(e,t){super(e,t)}getSQLType(){return"jsonb"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if("string"==typeof e)try{return JSON.parse(e)}catch{}return e}}function sM(e){return new sA(e)}class sz{static [a7]="Subquery";constructor(e,t,r,n=!1){this._={brand:"Subquery",sql:e,selectedFields:t,alias:r,isWith:n}}}let sF=(e,n)=>t?(r||(r=t.trace.getTracer("drizzle-orm","0.30.10")),sy((t,r)=>r.startActiveSpan(e,e=>{try{return n(e)}catch(r){throw e.setStatus({code:t.SpanStatusCode.ERROR,message:r instanceof Error?r.message:"Unknown error"}),r}finally{e.end()}}),t,r)):n(),sU=Symbol.for("drizzle:ViewBaseConfig");class sL{static [a7]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new sH([this])}}class sH{constructor(e){this.queryChunks=e}static [a7]="SQL";decoder=sV;shouldInlineParams=!1;append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return sF("drizzle.buildSQL",t=>{let r=this.buildQueryFromSourceParams(this.queryChunks,e);return t?.setAttributes({"drizzle.query.text":r.sql,"drizzle.query.params":JSON.stringify(r.params)}),r})}buildQueryFromSourceParams(e,t){let r=Object.assign({},t,{inlineParams:t.inlineParams||this.shouldInlineParams,paramStartIndex:t.paramStartIndex||{value:0}}),{escapeName:n,escapeParam:i,prepareTyping:a,inlineParams:s,paramStartIndex:o}=r;var l=e.map(e=>{if(se(e,sL))return{sql:e.value.join(""),params:[]};if(se(e,sB))return{sql:n(e.value),params:[]};if(void 0===e)return{sql:"",params:[]};if(Array.isArray(e)){let t=[new sL("(")];for(let[r,n]of e.entries())t.push(n),r<e.length-1&&t.push(new sL(", "));return t.push(new sL(")")),this.buildQueryFromSourceParams(t,r)}if(se(e,sH))return this.buildQueryFromSourceParams(e.queryChunks,{...r,inlineParams:s||e.shouldInlineParams});if(se(e,su)){let t=e[su.Symbol.Schema],r=e[su.Symbol.Name];return{sql:void 0===t?n(r):n(t)+"."+n(r),params:[]}}if(se(e,sf))return{sql:n(e.table[su.Symbol.Name])+"."+n(e.name),params:[]};if(se(e,sW)){let t=e[sU].schema,r=e[sU].name;return{sql:void 0===t?n(r):n(t)+"."+n(r),params:[]}}if(se(e,sG)){let t,n=null===e.value?null:e.encoder.mapToDriverValue(e.value);return se(n,sH)?this.buildQueryFromSourceParams([n],r):s?{sql:this.mapInlineParam(n,r),params:[]}:(void 0!==a&&(t=[a(e.encoder)]),{sql:i(o.value++,n),params:[n],typings:t})}return se(e,sJ)?{sql:i(o.value++,e),params:[e]}:se(e,sH.Aliased)&&void 0!==e.fieldAlias?{sql:n(e.fieldAlias),params:[]}:se(e,sz)?e._.isWith?{sql:n(e._.alias),params:[]}:this.buildQueryFromSourceParams([new sL("("),e._.sql,new sL(") "),new sB(e._.alias)],r):e&&"function"==typeof e&&sN in e&&!0===e[sN]?e.schema?{sql:n(e.schema)+"."+n(e.enumName),params:[]}:{sql:n(e.enumName),params:[]}:null!=e&&"function"==typeof e.getSQL?this.buildQueryFromSourceParams([new sL("("),e.getSQL(),new sL(")")],r):s?{sql:this.mapInlineParam(e,r),params:[]}:{sql:i(o.value++,e),params:[e]}});let u={sql:"",params:[]};for(let e of l)u.sql+=e.sql,u.params.push(...e.params),e.typings?.length&&(u.typings||(u.typings=[]),u.typings.push(...e.typings));return u}mapInlineParam(e,{escapeString:t}
15){if(null===e)return"null";if("number"==typeof e||"boolean"==typeof e)return e.toString();if("string"==typeof e)return t(e);if("object"==typeof e){let r=e.toString();return"[object Object]"===r?t(JSON.stringify(e)):t(r)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return void 0===e?this:new sH.Aliased(this,e)}mapWith(e){return this.decoder="function"==typeof e?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}}class sB{constructor(e){this.value=e}static [a7]="Name";brand;getSQL(){return new sH([this])}}let sV={mapFromDriverValue:e=>e},sq={mapToDriverValue:e=>e};({...sV,...sq});class sG{constructor(e,t=sq){this.value=e,this.encoder=t}static [a7]="Param";brand;getSQL(){return new sH([this])}}function sK(e,...t){let r=[];for(let[n,i]of((t.length>0||e.length>0&&""!==e[0])&&r.push(new sL(e[0])),t.entries()))r.push(i,new sL(e[n+1]));return new sH(r)}(s=sK||(sK={})).empty=function(){return new sH([])},s.fromList=function(e){return new sH(e)},s.raw=function(e){return new sH([new sL(e)])},s.join=function(e,t){let r=[];for(let[n,i]of e.entries())n>0&&void 0!==t&&r.push(t),r.push(i);return new sH(r)},s.identifier=function(e){return new sB(e)},s.placeholder=function(e){return new sJ(e)},s.param=function(e,t){return new sG(e,t)},(sH||(sH={})).Aliased=class e{constructor(e,t){this.sql=e,this.fieldAlias=t}static [a7]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new e(this.sql,this.fieldAlias)}};class sJ{constructor(e){this.name=e}static [a7]="Placeholder";getSQL(){return new sH([this])}}class sW{static [a7]="View";[sU];constructor({name:e,schema:t,selectedFields:r,query:n}){this[sU]={name:e,originalName:e,schema:t,selectedFields:r,query:n,isExisting:!n,isAlias:!1}}getSQL(){return new sH([this])}}sf.prototype.getSQL=function(){return new sH([this])},su.prototype.getSQL=function(){return new sH([this])},sz.prototype.getSQL=function(){return new sH([this])};class sZ extends sI{static [a7]="PgDateColumnBaseBuilder";defaultNow(){return this.default(sK`now()`)}}class sQ extends sZ{static [a7]="PgTimestampBuilder";constructor(e,t,r){super(e,"date","PgTimestamp"),this.config.withTimezone=t,this.config.precision=r}build(e){return new sY(e,this.config)}}class sY extends sx{static [a7]="PgTimestamp";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){let e=void 0===this.precision?"":` (${this.precision})`;return`timestamp${e}${this.withTimezone?" with time zone":""}`}mapFromDriverValue=e=>new Date(this.withTimezone?e:e+"+0000");mapToDriverValue=e=>e.toISOString()}class sX extends sZ{static [a7]="PgTimestampStringBuilder";constructor(e,t,r){super(e,"string","PgTimestampString"),this.config.withTimezone=t,this.config.precision=r}build(e){return new s0(e,this.config)}}class s0 extends sx{static [a7]="PgTimestampString";withTimezone;precision;constructor(e,t){super(e,t),this.withTimezone=t.withTimezone,this.precision=t.precision}getSQLType(){let e=void 0===this.precision?"":`(${this.precision})`;return`timestamp${e}${this.withTimezone?" with time zone":""}`}}function s1(e,t={}){return"string"===t.mode?new sX(e,t.withTimezone??!1,t.precision):new sQ(e,t.withTimezone??!1,t.precision)}class s2 extends sI{static [a7]="PgBooleanBuilder";constructor(e){super(e,"boolean","PgBoolean")}build(e){return new s5(e,this.config)}}class s5 extends sx{static [a7]="PgBoolean";getSQLType(){return"boolean"}}function s3(e){return new s2(e)}class s4 extends sI{static [a7]="PgUUIDBuilder";constructor(e){super(e,"string","PgUUID")}defaultRandom(){return this.default(sK`gen_random_uuid()`)}build(e){return new s6(e,this.config)}}class s6 extends sx{static [a7]="PgUUID";getSQLType(){return"uuid"}}function s9(e){return new s4(e)}class s8{constructor(e,t){this.unique=e,this.name=t}static [a7]="PgIndexBuilderOn";on(...e){return new s7(e,this.unique,!1,this.name)}onOnly(...e){return new s7(e,this.unique,!0,this.name)}}class s7{static [a7]="PgIndexBuilder";config;constructor(e,t,r,n){this.config={name:n,columns:e,unique:t,only:r}}concurrently(){return this.config.concurrently=!0,this}using(e){return this.config.using=e,this}asc(){return this.config.order="asc",this}desc(){return this.config.order="desc",this}nullsFirst(){return this.config.nulls="first",this}nullsLast(){return this.config.nulls="last",this}where(e){return this.config.where=e,this}build(e){return new oe(this.config,e)}}class oe{static [a7]="PgIndex";config;constructor(e,t){this.config={...e,table:t}}}function ot(e){return new s8(!1,e)}function or(e){return new s8(!0,e)}class on extends sI{static [a7]="PgBigInt53Builder";constructor(e){super(e,"number","PgBigInt53")}build(e){return new oi(e,this.config)}}class oi extends sx{static [a7]="PgBigInt53";getSQLType(){return"bigint"}mapFromDriverValue(e){return"number"==typeof e?e:Number(e)}}class oa extends sI{static [a7]="PgBigInt64Builder";constructor(e){super(e,"bigint","PgBigInt64")}build(e){return new os(e,this.config)}}class os extends sx{static [a7]="PgBigInt64";getSQLType(){return"bigint"}mapFromDriverValue(e){return BigInt(e)}}function oo(e,t){return"number"===t.mode?new on(e):new oa(e)}class ol extends sx{static [a7]="PgSmallInt";
15getSQLType(){return"smallint"}mapFromDriverValue=e=>"string"==typeof e?Number(e):e}class ou extends sI{static [a7]="PgIntegerBuilder";constructor(e){super(e,"number","PgInteger")}build(e){return new oc(e,this.config)}}class oc extends sx{static [a7]="PgInteger";getSQLType(){return"integer"}mapFromDriverValue(e){return"string"==typeof e?Number.parseInt(e):e}}function oh(e){return new ou(e)}function od(...e){return e[0].columns?new op(e[0].columns,e[0].name):new op(e)}class op{static [a7]="PgPrimaryKeyBuilder";columns;name;constructor(e,t){this.columns=e,this.name=t}build(e){return new of(e,this.columns,this.name)}}class of{constructor(e,t,r){this.table=e,this.columns=t,this.name=r}static [a7]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[sh.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}class om{constructor(e,t){this.name=e,this.value=t}static [a7]="PgCheckBuilder";brand;build(e){return new og(e,this)}}class og{constructor(e,t){this.table=e,this.name=t.name,this.value=t.value}static [a7]="PgCheck";name;value}sT("aal_level",["aal1","aal2","aal3"]),sT("code_challenge_method",["s256","plain"]),sT("factor_status",["unverified","verified"]),sT("factor_type",["totp","webauthn","phone"]),sT("oauth_authorization_status",["pending","approved","denied","expired"]),sT("oauth_client_type",["public","confidential"]),sT("oauth_registration_type",["dynamic","manual"]),sT("oauth_response_type",["code"]),sT("one_time_token_type",["confirmation_token","reauthentication_token","recovery_token","email_change_token_new","email_change_token_current","phone_change_token"]),sT("key_status",["default","valid","invalid","expired"]),sT("key_type",["aead-ietf","aead-det","hmacsha512","hmacsha256","auth","shorthash","generichash","kdf","secretbox","secretstream","stream_xchacha20"]);let oy=sT("rsvp_status",["GOING","NOT_GOING","MAYBE"]);sT("action",["INSERT","UPDATE","DELETE","TRUNCATE","ERROR"]),sT("equality_op",["eq","neq","lt","lte","gt","gte","in"]),sT("buckettype",["STANDARD","ANALYTICS","VECTOR"]),sd("oauth_state_store",{key:sO("key").primaryKey().notNull(),state:sM("state").notNull()}),sd("notifications",{recipient:sO("recipient").notNull().references(()=>oI.atp_did,{onDelete:"cascade",onUpdate:"cascade"}),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),read:s3("read").default(!1).notNull(),data:sM("data").notNull(),id:s9("id").primaryKey().notNull()},e=>({recipient_created_at_id_idx:ot("notifications_recipient_created_at_id_idx").on(e.recipient,e.created_at,e.id)}));let ob=sd("publications",{uri:sO("uri").primaryKey().notNull(),indexed_at:s1("indexed_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),name:sO("name").notNull(),identity_did:sO("identity_did").notNull().references(()=>oI.atp_did,{onDelete:"cascade"}),record:sM("record"),draft_leaflet:s9("draft_leaflet").references(()=>ok.id)},e=>({identity_did_idx:ot("publications_identity_did_idx").on(e.identity_did)}));sd("comments_on_documents",{uri:sO("uri").primaryKey().notNull(),record:sM("record").notNull(),document:sO("document").references(()=>o$.uri,{onDelete:"cascade",onUpdate:"cascade"}),indexed_at:s1("indexed_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),profile:sO("profile")},e=>({document_idx:ot("comments_on_documents_document_idx").on(e.document)}));let ow=sd("entities",{id:s9("id").primaryKey().notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),set:s9("set").notNull().references(()=>o_.id,{onDelete:"cascade",onUpdate:"cascade"})},e=>({set_idx:ot("entities_set_idx").on(e.set)}));sd("facts",{id:s9("id").primaryKey().notNull(),entity:s9("entity").notNull().references(()=>ow.id,{onDelete:"cascade",onUpdate:"restrict"}),attribute:sO("attribute").notNull(),data:sM("data").notNull(),author_did:sO("author_did"),created_at:s1("created_at",{mode:"string"}).defaultNow().notNull(),updated_at:s1("updated_at",{mode:"string"}),version:oo("version",{mode:"number"}).default(0).notNull()},e=>({entity_idx:ot("facts_entity_idx").on(e.entity)})),sd("mention_services",{uri:sO("uri").primaryKey().notNull(),identity_did:sO("identity_did").notNull(),record:sM("record").notNull()},e=>({idx_mention_services_did:ot("idx_mention_services_did").on(e.identity_did)})),sd("mention_service_configs",{uri:sO("uri").primaryKey().notNull(),identity_did:sO("identity_did").notNull(),record:sM("record").notNull()},e=>({idx_mention_service_configs_did:ot("idx_mention_service_configs_did").on(e.identity_did),mention_service_configs_identity_did_key:sb("mention_service_configs_identity_did_key").on(e.identity_did)})),sd("replicache_clients",{client_id:sO("client_id").primaryKey().notNull(),client_group:sO("client_group").notNull(),last_mutation:oo("last_mutation",{mode:"number"}).notNull()},e=>({client_group_idx:ot("replicache_clients_client_group_idx").on(e.client_group)})),sd("email_auth_tokens",{id:s9("id").defaultRandom().primaryKey().notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),confirmed:s3("confirmed").default(!1).notNull(),email:sO("email"),confirmation_code:sO("confirmation_code").notNull(),identity:s9("identity").references(()=>
15oI.id,{onDelete:"cascade",onUpdate:"cascade"})});let ov=sd("bsky_posts",{uri:sO("uri").primaryKey().notNull(),indexed_at:s1("indexed_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),post_view:sM("post_view").notNull(),cid:sO("cid").notNull()});sd("recommends_on_documents",{uri:sO("uri").primaryKey().notNull(),record:sM("record").notNull(),document:sO("document").notNull().references(()=>o$.uri,{onDelete:"cascade",onUpdate:"cascade"}),recommender_did:sO("recommender_did").notNull().references(()=>oI.atp_did,{onDelete:"cascade",onUpdate:"cascade"}),indexed_at:s1("indexed_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()},e=>({document_idx:ot("recommends_on_documents_document_idx").on(e.document),recommender_did_idx:ot("recommends_on_documents_recommender_did_idx").on(e.recommender_did),recommender_document_idx:or("recommends_on_documents_recommender_document_idx").on(e.document,e.recommender_did)})),sd("bsky_profiles",{did:sO("did").primaryKey().notNull().references(()=>oI.atp_did,{onDelete:"cascade"}),record:sM("record").notNull(),indexed_at:s1("indexed_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),handle:sO("handle")});let o_=sd("entity_sets",{id:s9("id").defaultRandom().primaryKey().notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()});sd("poll_votes_on_entity",{id:s9("id").defaultRandom().primaryKey().notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),poll_entity:s9("poll_entity").notNull().references(()=>ow.id,{onDelete:"cascade",onUpdate:"cascade"}),option_entity:s9("option_entity").notNull().references(()=>ow.id,{onDelete:"cascade",onUpdate:"cascade"}),voter_token:s9("voter_token").notNull()});let ok=sd("permission_tokens",{id:s9("id").defaultRandom().primaryKey().notNull(),root_entity:s9("root_entity").notNull().references(()=>ow.id,{onDelete:"cascade",onUpdate:"cascade"}),blocked_by_admin:s3("blocked_by_admin"),title:sO("title"),description:sO("description")}),oS=sd("document_versions",{id:s9("id").primaryKey().notNull(),token:s9("token").notNull().references(()=>ok.id,{onDelete:"cascade",onUpdate:"cascade"}),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),kind:sO("kind").default("named").notNull(),name:sO("name"),author_did:sO("author_did"),author_identity:s9("author_identity").references(()=>oI.id,{onDelete:"set null"}),closure_hash:sO("closure_hash").notNull(),snapshot:sM("snapshot"),snapshot_path:sO("snapshot_path"),fact_count:oh("fact_count").notNull(),byte_size:oh("byte_size").notNull()},e=>({token_created_at_idx:ot("document_versions_token_created_at_idx").on(e.token,e.created_at)}));sd("document_version_blob_refs",{version:s9("version").notNull().references(()=>oS.id,{onDelete:"cascade",onUpdate:"cascade"}),path:sO("path").notNull()},e=>({path_idx:ot("document_version_blob_refs_path_idx").on(e.path),document_version_blob_refs_pkey:od({columns:[e.version,e.path],name:"document_version_blob_refs_pkey"})})),sd("blob_cleanup_queue",{path:sO("path").primaryKey().notNull(),queued_at:s1("queued_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()}),sd("user_subscriptions",{identity_id:s9("identity_id").primaryKey().notNull().references(()=>oI.id,{onDelete:"cascade"}),stripe_customer_id:sO("stripe_customer_id").notNull(),stripe_subscription_id:sO("stripe_subscription_id"),plan:sO("plan"),status:sO("status"),current_period_end:s1("current_period_end",{withTimezone:!0,mode:"string"}),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),updated_at:s1("updated_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()},e=>({stripe_customer_id_key:or("user_subscriptions_stripe_customer_id_key").on(e.stripe_customer_id),stripe_subscription_id_key:or("user_subscriptions_stripe_subscription_id_key").on(e.stripe_subscription_id)})),sd("stripe_connected_accounts",{identity_id:s9("identity_id").primaryKey().notNull().references(()=>oI.id,{onDelete:"cascade"}),stripe_account_id:sO("stripe_account_id").notNull(),charges_enabled:s3("charges_enabled").default(!1).notNull(),payouts_enabled:s3("payouts_enabled").default(!1).notNull(),details_submitted:s3("details_submitted").default(!1).notNull(),requirements:sM("requirements"),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),updated_at:s1("updated_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()},e=>({stripe_account_id_key:or("stripe_connected_accounts_stripe_account_id_key").on(e.stripe_account_id)}));let oI=sd("identities",{id:s9("id").defaultRandom().primaryKey().notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),home_page:s9("home_page").default(sK`create_identity_homepage()`).notNull().references(()=>
15ok.id,{onDelete:"cascade"}),email:sO("email"),atp_did:sO("atp_did"),interface_state:sM("interface_state"),metadata:sM("metadata")},e=>({identities_email_key:sb("identities_email_key").on(e.email),identities_atp_did_key:sb("identities_atp_did_key").on(e.atp_did)}));sd("publication_membership_settings",{publication:sO("publication").primaryKey().notNull().references(()=>ob.uri,{onDelete:"cascade"}),enabled:s3("enabled").default(!1).notNull(),subscriber_tier_name:sO("subscriber_tier_name").default("Free").notNull(),subscriber_tier_description:sO("subscriber_tier_description").default("Subscribe for free to get notified about new posts."),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),updated_at:s1("updated_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()},e=>({enabled_idx:ot("publication_membership_settings_enabled_idx").on(e.publication)}));let ox=sd("publication_membership_tiers",{id:s9("id").defaultRandom().primaryKey().notNull(),publication:sO("publication").notNull().references(()=>ob.uri,{onDelete:"cascade"}),name:sO("name").notNull(),description:sO("description"),monthly_price_cents:oh("monthly_price_cents").notNull(),annual_price_cents:oh("annual_price_cents"),currency:sO("currency").default("usd").notNull(),stripe_product_id:sO("stripe_product_id"),stripe_price_monthly_id:sO("stripe_price_monthly_id"),stripe_price_annual_id:sO("stripe_price_annual_id"),active:s3("active").default(!1).notNull(),sort_order:oh("sort_order").default(0).notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),updated_at:s1("updated_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()},e=>({publication_idx:ot("publication_membership_tiers_publication_idx").on(e.publication),id_publication_key:sb("publication_membership_tiers_id_publication_key").on(e.id,e.publication),monthly_price_check:new om("publication_membership_tiers_monthly_price_check",sK`${e.monthly_price_cents} >= 100`),annual_price_check:new om("publication_membership_tiers_annual_price_check",sK`${e.annual_price_cents} IS NULL OR ${e.annual_price_cents} >= 100`),active_monthly_price_check:new om("publication_membership_tiers_active_monthly_price_check",sK`NOT ${e.active} OR ${e.stripe_price_monthly_id} IS NOT NULL`)}));sd("publication_memberships",{id:s9("id").defaultRandom().primaryKey().notNull(),publication:sO("publication").notNull().references(()=>ob.uri,{onDelete:"cascade"}),identity_id:s9("identity_id").notNull().references(()=>oI.id,{onDelete:"cascade"}),tier:s9("tier").notNull(),stripe_customer_id:sO("stripe_customer_id"),stripe_subscription_id:sO("stripe_subscription_id"),status:sO("status"),current_period_end:s1("current_period_end",{withTimezone:!0,mode:"string"}),cancel_at_period_end:s3("cancel_at_period_end").default(!1).notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),updated_at:s1("updated_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()},e=>{var t;return{identity_idx:ot("publication_memberships_identity_idx").on(e.identity_id),publication_identity_key:sb("publication_memberships_publication_identity_key").on(e.publication,e.identity_id),stripe_subscription_id_key:or("publication_memberships_stripe_subscription_id_key").on(e.stripe_subscription_id),tier_publication_fkey:(t={columns:[e.tier,e.publication],foreignColumns:[ox.id,ox.publication],name:"publication_memberships_tier_publication_fkey"},new sm(function(){let{name:e,columns:r,foreignColumns:n}=t;return{name:e,columns:r,foreignColumns:n}})).onDelete("no action")}}),sd("phone_number_auth_tokens",{id:s9("id").defaultRandom().primaryKey().notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),confirmed:s3("confirmed").default(!1).notNull(),confirmation_code:sO("confirmation_code").notNull(),phone_number:sO("phone_number").notNull(),country_code:sO("country_code").notNull()}),sd("phone_rsvps_to_entity",{created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),phone_number:sO("phone_number").notNull(),country_code:sO("country_code").notNull(),status:oy("status").notNull(),id:s9("id").defaultRandom().primaryKey().notNull(),entity:s9("entity").notNull().references(()=>
15ow.id,{onDelete:"cascade",onUpdate:"cascade"}),name:sO("name").default("").notNull(),plus_ones:new class e extends sI{static [a7]="PgSmallIntBuilder";constructor(e){super(e,"number","PgSmallInt")}build(e){return new ol(e,this.config)}}("plus_ones").default(0).notNull()},e=>({unique_phone_number_entities:or("unique_phone_number_entities").on(e.phone_number,e.entity)}));let oD=sd("site_standard_publications",{uri:sO("uri").primaryKey().notNull(),data:sM("data").notNull(),indexed_at:s1("indexed_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),identity_did:sO("identity_did").notNull().references(()=>oI.atp_did,{onDelete:"cascade"})});sd("custom_domain_routes",{id:s9("id").defaultRandom().primaryKey().notNull(),domain:sO("domain").notNull().references(()=>oN.domain),route:sO("route").notNull(),edit_permission_token:s9("edit_permission_token").notNull().references(()=>ok.id,{onDelete:"cascade",onUpdate:"cascade"}),view_permission_token:s9("view_permission_token").notNull().references(()=>ok.id,{onDelete:"cascade",onUpdate:"cascade"}),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()},e=>({edit_permission_token_idx:ot("custom_domain_routes_edit_permission_token_idx").on(e.edit_permission_token),custom_domain_routes_domain_route_key:sb("custom_domain_routes_domain_route_key").on(e.domain,e.route)}));let oE=sd("site_standard_documents",{uri:sO("uri").primaryKey().notNull(),data:sM("data").notNull(),indexed_at:s1("indexed_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),identity_did:sO("identity_did").notNull().references(()=>oI.atp_did,{onDelete:"cascade"})}),oN=sd("custom_domains",{domain:sO("domain").primaryKey().notNull(),identity:sO("identity").default("").references(()=>oI.email,{onDelete:"cascade",onUpdate:"cascade"}),confirmed:s3("confirmed").notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),identity_id:s9("identity_id").references(()=>oI.id,{onDelete:"cascade"})});sd("email_subscriptions_to_entity",{id:s9("id").defaultRandom().primaryKey().notNull(),entity:s9("entity").notNull().references(()=>ow.id,{onDelete:"cascade"}),email:sO("email").notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),token:s9("token").notNull().references(()=>ok.id,{onDelete:"cascade"}),confirmed:s3("confirmed").default(!1).notNull(),confirmation_code:sO("confirmation_code").notNull()}),sd("atp_poll_votes",{uri:sO("uri").primaryKey().notNull(),record:sM("record").notNull(),voter_did:sO("voter_did").notNull(),poll_uri:sO("poll_uri").notNull().references(()=>oC.uri,{onDelete:"cascade",onUpdate:"cascade"}),poll_cid:sO("poll_cid").notNull(),indexed_at:s1("indexed_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()},e=>({poll_uri_idx:ot("atp_poll_votes_poll_uri_idx").on(e.poll_uri),voter_did_idx:ot("atp_poll_votes_voter_did_idx").on(e.voter_did)}));let o$=sd("documents",{uri:sO("uri").primaryKey().notNull(),data:sM("data").notNull(),indexed_at:s1("indexed_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),sort_date:s1("sort_date",{withTimezone:!0,mode:"string"}),bsky_like_count:oh("bsky_like_count").default(0).notNull(),recommend_count:oh("recommend_count").default(0).notNull(),indexed:s3("indexed").default(!1).notNull(),identity_did:sO("identity_did")},e=>({sort_date_idx:ot("documents_sort_date_idx").on(e.uri,e.sort_date),indexed_at_idx:ot("documents_indexed_at_idx").on(e.indexed_at),idx_documents_ranking:ot("idx_documents_ranking").on(e.uri,e.sort_date,e.bsky_like_count,e.recommend_count),identity_did_sort_idx:ot("documents_identity_did_sort_idx").on(e.uri,e.sort_date,e.identity_did)})),oC=sd("atp_poll_records",{uri:sO("uri").primaryKey().notNull(),cid:sO("cid").notNull(),record:sM("record").notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()});sd("oauth_session_store",{key:sO("key").primaryKey().notNull(),session:sM("session").notNull()}),sd("publication_newsletter_settings",{publication:sO("publication").primaryKey().notNull().references(()=>
15ob.uri,{onDelete:"cascade"}),enabled:s3("enabled").default(!1).notNull(),reply_to_email:sO("reply_to_email"),reply_to_verified_at:s1("reply_to_verified_at",{withTimezone:!0,mode:"string"}),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),updated_at:s1("updated_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),confirmation_code:sO("confirmation_code")},e=>({enabled_idx:ot("publication_newsletter_settings_enabled_idx").on(e.publication)}));let oT=sd("publication_email_subscribers",{id:s9("id").defaultRandom().primaryKey().notNull(),publication:sO("publication").notNull().references(()=>ob.uri,{onDelete:"cascade"}),email:sO("email").notNull(),identity_id:s9("identity_id").references(()=>oI.id,{onDelete:"set null"}),state:sO("state").default("pending").notNull(),confirmation_code:sO("confirmation_code"),unsubscribe_token:s9("unsubscribe_token").defaultRandom().notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),confirmed_at:s1("confirmed_at",{withTimezone:!0,mode:"string"}),unsubscribed_at:s1("unsubscribed_at",{withTimezone:!0,mode:"string"}),metadata:sM("metadata")},e=>({confirmed_idx:ot("publication_email_subscribers_confirmed_idx").on(e.publication),publication_email_subscribers_publication_email_key:sb("publication_email_subscribers_publication_email_key").on(e.publication,e.email),publication_email_subscribers_unsubscribe_token_key:sb("publication_email_subscribers_unsubscribe_token_key").on(e.unsubscribe_token)}));function oP(e){let t={eav:`${e.entity}-${e.attribute}-${e.id}`};return("reference"===e.data.type||"ordered-reference"===e.data.type||"spatial-reference"===e.data.type)&&(t.vae=`${e.data.value}-${e.attribute}`),{...e,indexes:t}}sd("publication_email_subscriber_events",{id:s9("id").defaultRandom().primaryKey().notNull(),subscriber:s9("subscriber").notNull().references(()=>oT.id,{onDelete:"cascade"}),publication:sO("publication").notNull().references(()=>ob.uri,{onDelete:"cascade"}),event_type:sO("event_type").notNull(),occurred_at:s1("occurred_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),metadata:sM("metadata")},e=>({subscriber_idx:ot("publication_email_subscriber_events_subscriber_idx").on(e.subscriber,e.occurred_at),publication_type_idx:ot("publication_email_subscriber_events_publication_type_idx").on(e.publication,e.event_type,e.occurred_at)})),sd("bsky_follows",{identity:sO("identity").default("").notNull().references(()=>oI.atp_did,{onDelete:"cascade"}),follows:sO("follows").notNull().references(()=>oI.atp_did,{onDelete:"cascade"})},e=>({bsky_follows_pkey:od({columns:[e.identity,e.follows],name:"bsky_follows_pkey"})})),sd("site_standard_documents_in_publications",{publication:sO("publication").notNull().references(()=>oD.uri,{onDelete:"cascade"}),document:sO("document").notNull().references(()=>oE.uri,{onDelete:"cascade"}),indexed_at:s1("indexed_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()},e=>({site_standard_documents_in_publications_pkey:od({columns:[e.publication,e.document],name:"site_standard_documents_in_publications_pkey"})})),sd("documents_in_publications",{publication:sO("publication").notNull().references(()=>ob.uri,{onDelete:"cascade"}),document:sO("document").notNull().references(()=>o$.uri,{onDelete:"cascade"}),indexed_at:s1("indexed_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),members_only:s3("members_only").default(!1).notNull()},e=>({publication_idx:ot("documents_in_publications_publication_idx").on(e.publication),document_idx:ot("documents_in_publications_document_idx").on(e.document),documents_in_publications_pkey:od({columns:[e.publication,e.document],name:"documents_in_publications_pkey"})})),sd("leaflet_contributors",{leaflet:s9("leaflet").notNull().references(()=>ok.id,{onDelete:"cascade",onUpdate:"cascade"}),contributor_did:sO("contributor_did").notNull().references(()=>oI.atp_did,{onDelete:"cascade",onUpdate:"cascade"}),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()},e=>({contributor_did_idx:ot("leaflet_contributors_contributor_did_idx").on(e.contributor_did),leaflet_contributors_pkey:od({columns:[e.leaflet,e.contributor_did],name:"leaflet_contributors_pkey"})})),sd("document_mentions_in_bsky",{uri:sO("uri").notNull().references(()=>
15ov.uri,{onDelete:"cascade"}),link:sO("link").notNull(),document:sO("document").notNull().references(()=>o$.uri,{onDelete:"cascade"}),indexed_at:s1("indexed_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()},e=>({document_idx:ot("document_mentions_in_bsky_document_idx").on(e.document),document_mentions_in_bsky_pkey:od({columns:[e.uri,e.document],name:"document_mentions_in_bsky_pkey"})})),sd("permission_token_on_homepage",{token:s9("token").notNull().references(()=>ok.id,{onDelete:"cascade",onUpdate:"cascade"}),identity:s9("identity").notNull().references(()=>oI.id,{onDelete:"cascade"}),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),archived:s3("archived")},e=>({permission_token_creator_pkey:od({columns:[e.token,e.identity],name:"permission_token_creator_pkey"})})),sd("publication_domains",{publication:sO("publication").notNull().references(()=>ob.uri,{onDelete:"cascade"}),domain:sO("domain").notNull().references(()=>oN.domain,{onDelete:"cascade"}),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),identity:sO("identity").notNull().references(()=>oI.atp_did,{onDelete:"cascade",onUpdate:"cascade"})},e=>({publication_idx:ot("publication_domains_publication_idx").on(e.publication),publication_domains_pkey:od({columns:[e.publication,e.domain],name:"publication_domains_pkey"})})),sd("publication_contributors",{publication_uri:sO("publication_uri").notNull().references(()=>ob.uri,{onDelete:"cascade"}),contributor_did:sO("contributor_did").notNull().references(()=>oI.atp_did,{onDelete:"cascade",onUpdate:"cascade"}),confirmed:s3("confirmed").default(!1).notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()},e=>({contributor_did_idx:ot("publication_contributors_contributor_did_idx").on(e.contributor_did),publication_contributors_pkey:od({columns:[e.publication_uri,e.contributor_did],name:"publication_contributors_pkey"})})),sd("publication_recommendations",{uri:sO("uri").notNull(),publication:sO("publication").notNull().references(()=>ob.uri,{onDelete:"cascade",onUpdate:"cascade"}),recommendation:sO("recommendation").notNull(),sort_order:oh("sort_order").notNull(),indexed_at:s1("indexed_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull()},e=>({uri_idx:ot("publication_recommendations_uri_idx").on(e.uri),recommendation_idx:ot("publication_recommendations_recommendation_idx").on(e.recommendation),publication_recommendations_pkey:od({columns:[e.publication,e.recommendation],name:"publication_recommendations_pkey"})})),sd("publication_subscriptions",{publication:sO("publication").notNull().references(()=>ob.uri,{onDelete:"cascade"}),identity:sO("identity").notNull().references(()=>oI.atp_did,{onDelete:"cascade"}),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),record:sM("record").notNull(),uri:sO("uri").notNull()},e=>({publication_idx:ot("publication_subscriptions_publication_idx").on(e.publication),publication_subscriptions_pkey:od({columns:[e.publication,e.identity],name:"publication_subscriptions_pkey"}),publication_subscriptions_uri_key:sb("publication_subscriptions_uri_key").on(e.uri)})),sd("site_standard_subscriptions",{publication:sO("publication").notNull().references(()=>oD.uri,{onDelete:"cascade"}),identity:sO("identity").notNull().references(()=>oI.atp_did,{onDelete:"cascade"}),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),record:sM("record").notNull(),uri:sO("uri").notNull()},e=>({site_standard_subscriptions_pkey:od({columns:[e.publication,e.identity],name:"site_standard_subscriptions_pkey"}),site_standard_subscriptions_uri_key:sb("site_standard_subscriptions_uri_key").on(e.uri)})),sd("user_entitlements",{identity_id:s9("identity_id").notNull().references(()=>oI.id,{onDelete:"cascade"}),entitlement_key:sO("entitlement_key").notNull(),granted_at:s1("granted_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),expires_at:s1("expires_at",{withTimezone:!0,mode:"string"}),source:sO("source"),metadata:sM("metadata")},e=>({identity_id_idx:ot("user_entitlements_identity_id_idx").on(e.identity_id),expires_at_idx:ot("user_entitlements_expires_at_idx").on(e.expires_at),user_entitlements_pkey:od({columns:[e.identity_id,e.entitlement_key],name:"user_entitlements_pkey"})})),sd("permission_token_rights",{token:s9("token").notNull().references(()=>
15ok.id,{onDelete:"cascade",onUpdate:"cascade"}),entity_set:s9("entity_set").notNull().references(()=>o_.id,{onDelete:"cascade",onUpdate:"cascade"}),read:s3("read").default(!1).notNull(),write:s3("write").default(!1).notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),create_token:s3("create_token").default(!1).notNull(),change_entity_set:s3("change_entity_set").default(!1).notNull()},e=>({token_idx:ot("permission_token_rights_token_idx").on(e.token),entity_set_idx:ot("permission_token_rights_entity_set_idx").on(e.entity_set),permission_token_rights_pkey:od({columns:[e.token,e.entity_set],name:"permission_token_rights_pkey"})})),sd("publication_post_sends",{publication:sO("publication").notNull().references(()=>ob.uri,{onDelete:"cascade"}),document:sO("document").notNull().references(()=>o$.uri,{onDelete:"cascade"}),status:sO("status").default("pending").notNull(),subscriber_count:oh("subscriber_count"),started_at:s1("started_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),completed_at:s1("completed_at",{withTimezone:!0,mode:"string"}),error:sO("error")},e=>({publication_started_idx:ot("publication_post_sends_publication_started_idx").on(e.publication,e.started_at),publication_post_sends_pkey:od({columns:[e.publication,e.document],name:"publication_post_sends_pkey"})})),sd("leaflets_to_documents",{leaflet:s9("leaflet").notNull().references(()=>ok.id,{onDelete:"cascade",onUpdate:"cascade"}),document:sO("document").notNull().references(()=>o$.uri,{onDelete:"cascade",onUpdate:"cascade"}),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),title:sO("title").default("").notNull(),description:sO("description").default("").notNull(),tags:sO("tags").default("RRAY[").array(),cover_image:sO("cover_image"),preferences:sM("preferences"),scheduled_publish_at:s1("scheduled_publish_at",{withTimezone:!0,mode:"string"}),scheduled_publish_data:sM("scheduled_publish_data")},e=>({leaflets_to_documents_pkey:od({columns:[e.leaflet,e.document],name:"leaflets_to_documents_pkey"})})),sd("leaflets_in_publications",{publication:sO("publication").notNull().references(()=>ob.uri,{onDelete:"cascade"}),doc:sO("doc").default("").references(()=>o$.uri,{onDelete:"set null"}),leaflet:s9("leaflet").notNull().references(()=>ok.id,{onDelete:"cascade",onUpdate:"cascade"}),description:sO("description").default("").notNull(),title:sO("title").default("").notNull(),archived:s3("archived"),tags:sO("tags").default("RRAY[").array(),cover_image:sO("cover_image"),preferences:sM("preferences"),scheduled_publish_at:s1("scheduled_publish_at",{withTimezone:!0,mode:"string"}),scheduled_publish_data:sM("scheduled_publish_data")},e=>({leaflet_idx:ot("leaflets_in_publications_leaflet_idx").on(e.leaflet),publication_idx:ot("leaflets_in_publications_publication_idx").on(e.publication),doc_idx:ot("leaflets_in_publications_doc_idx").on(e.doc),leaflets_in_publications_pkey:od({columns:[e.publication,e.leaflet],name:"leaflets_in_publications_pkey"})})),sd("publication_pages",{id:oo("id",{mode:"number"}).notNull(),created_at:s1("created_at",{withTimezone:!0,mode:"string"}).defaultNow().notNull(),page_entity:s9("page_entity"),document:sO("document").references(()=>o$.uri),path:sO("path"),publication:sO("publication").notNull().references(()=>ob.uri,{onDelete:"cascade",onUpdate:"cascade"}),title:sO("title").default("").notNull(),record:sM("record"),record_uri:sO("record_uri"),sort_order:sO("sort_order").notNull()},e=>({publication_pages_pkey:od({columns:[e.id,e.publication],name:"publication_pages_pkey"}),publication_pages_publication_page_entity_idx:or("publication_pages_publication_page_entity_idx").on(e.publication,e.page_entity)}));let oR=e=>({eav:async(t,r)=>(await e.scan({indexName:"eav",prefix:`${t}-${r}`}).toArray()).filter(e=>""===r||e.attribute===r),vae:async(t,r)=>(await e.scan({indexName:"vae",prefix:`${t}-${r}`}).toArray()).filter(e=>e.attribute===r)});e.s(["FactWithIndexes",0,oP,"scanIndex",0,oR,"scanIndexLocal",0,e=>({eav:(t,r)=>e.filter(e=>e.entity===t&&e.attribute===r)})],64572);var oO=e.i(935593),oA=e.i(760524);function oj(e){let t=t=>{for(let r of[e].flat())if((!r.skipIfDefaultPrevented||!t.defaultPrevented)&&!!r.shift===t.shiftKey&&!!r.altKey===t.altKey){if(r.metaAndCtrl){if(!(t.metaKey&&t.ctrlKey))continue}else if(!!r.metaKey!==((0,oA.isMac)()?t.metaKey:t.ctrlKey))continue;if([r.key].flat().includes(t.key))return t.preventDefault(),r.handler()}};return window.addEventListener("keydown",t),()=>window.removeEventListener("keydown",t)}e.s(["addShortcut",0,oj],581869);class oM{constructor(e={}
15){this._undoRedoStack=[],this._isGrouping=!1,this._lastGroupID=0,this._index=-1,this._prevUndoRedoStackState={canUndo:this.canUndo,canRedo:this.canRedo},this._onChange=void 0;const{maxSize:t=1e4,onChange:r}=e;this._maxSize=t,r&&(this._onChange=r)}_updateIndex(e){this._index=e;let t={canUndo:this.canUndo,canRedo:this.canRedo};(this._prevUndoRedoStackState.canRedo!==t.canRedo||this._prevUndoRedoStackState.canUndo!==t.canUndo)&&(this._onChange?.(t),this._prevUndoRedoStackState=t)}get canUndo(){return this._index>=0}get canRedo(){return this._index<this._undoRedoStack.length-1}async add(e){this._undoRedoStack.splice(this._index+1);let{undo:t}=e,{execute:r}=e,{redo:n=r}=e;n&&this._undoRedoStack.push({groupID:this._isGrouping?this._lastGroupID:void 0,undo:t,redo:n}),this._updateIndex(this._index+1),this._index>=this._maxSize&&(this._undoRedoStack.shift(),this._updateIndex(this._index-1)),r&&await r()}async undo(){if(!this.canUndo)return;let e=this._undoRedoStack[this._index];this._updateIndex(this._index-1);let t=this._undoRedoStack[this._index];await e.undo(),void 0!==e.groupID&&t&&t.groupID===e.groupID&&await this.undo()}async redo(){if(!this.canRedo)return;let e=this._undoRedoStack[this._index+1];this._updateIndex(this._index+1);let t=this._undoRedoStack[this._index+1];await e.redo(),void 0!==e.groupID&&t&&t.groupID===e.groupID&&await this.redo()}startGroup(){if(this._isGrouping)throw Error("UndoManager is already grouping.");this._isGrouping=!0,this._lastGroupID=this._lastGroupID+1}endGroup(){this._isGrouping=!1}}let oz=(0,az.create)(()=>({canUndo:!1,canRedo:!1})),oF=()=>{let e,t=new oM({onChange:e=>{oz.setState(e)}}),r=0,n=!1,i=!1,a=null,s=Promise.resolve(),o=()=>{null!==a&&(clearTimeout(a),a=null)},l=()=>{o(),i&&(i=!1,e=void 0,t.endGroup())},u={add:e=>{r>0&&(n||(l(),t.startGroup(),n=!0)),t.add(e)},startGroup:()=>{r++},endGroup:()=>{0!==r&&0==--r&&n&&(t.endGroup(),n=!1)},withUndoGroup:e=>{let t;u.startGroup();let r=()=>u.endGroup();try{t=e()}catch(e){throw r(),e}return t instanceof Promise?t.finally(r):(r(),t)},addGrouped:(r,s)=>{n?t.add(r):(i&&s!==e&&l(),i||(t.startGroup(),i=!0,e=s),t.add(r),o(),a=setTimeout(l,500))},undo:()=>(l(),s=s.then(()=>t.undo()).then(()=>{},()=>{})),redo:()=>(l(),s=s.then(()=>t.redo()).then(()=>{},()=>{}))};return u};e.s(["createUndoManager",0,oF,"useUndoState",0,oz],417223);var oU=e.i(806398),oL=e.i(968575),oH=e.i(297907),oB=e.i(849074),oV=e.i(399993),oq=e.i(850050),oG=e.i(709646);class oK extends oq.Observable{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{let e=oB.getUnixTime();null!==this.getLocalState()&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());let t=[];this.meta.forEach((r,n)=>{n!==this.clientID&&3e4<=e-r.lastUpdated&&this.states.has(n)&&t.push(n)}),t.length>0&&oJ(this,t,"timeout")},oV.floor(3e3)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){let t=this.clientID,r=this.meta.get(t),n=void 0===r?0:r.clock+1,i=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:n,lastUpdated:oB.getUnixTime()});let a=[],s=[],o=[],l=[];null===e?l.push(t):null==i?null!=e&&a.push(t):(s.push(t),oG.equalityDeep(i,e)||o.push(t)),(a.length>0||o.length>0||l.length>0)&&this.emit("change",[{added:a,updated:o,removed:l},"local"]),this.emit("update",[{added:a,updated:s,removed:l},"local"])}setLocalStateField(e,t){let r=this.getLocalState();null!==r&&this.setLocalState({...r,[e]:t})}getStates(){return this.states}}let oJ=(e,t,r)=>{let n=[];for(let r=0;r<t.length;r++){let i=t[r];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){let t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:oB.getUnixTime()})}n.push(i)}}n.length>0&&(e.emit("change",[{added:[],updated:[],removed:n},r]),e.emit("update",[{added:[],updated:[],removed:n},r]))},oW=(e,t,r=e.states)=>{let n=t.length,i=oL.createEncoder();oL.writeVarUint(i,n);for(let a=0;a<n;a++){let n=t[a],s=r.get(n)||null,o=e.meta.get(n).clock;oL.writeVarUint(i,n),oL.writeVarUint(i,o),oL.writeVarString(i,JSON.stringify(s))}return oL.toUint8Array(i)},oZ=(e,t,r)=>{let n=oH.createDecoder(t),i=oB.getUnixTime(),a=[],s=[],o=[],l=[],u=oH.readVarUint(n);for(let t=0;t<u;
15t++){let t=oH.readVarUint(n),r=oH.readVarUint(n),u=JSON.parse(oH.readVarString(n)),c=e.meta.get(t),h=e.states.get(t),d=void 0===c?0:c.clock;(d<r||d===r&&null===u&&e.states.has(t))&&(null===u?t===e.clientID&&null!=e.getLocalState()?r++:e.states.delete(t):e.states.set(t,u),e.meta.set(t,{clock:r,lastUpdated:i}),void 0===c&&null!==u?a.push(t):void 0!==c&&null===u?l.push(t):null!==u&&(oG.equalityDeep(u,h)||o.push(t),s.push(t)))}(a.length>0||o.length>0||l.length>0)&&e.emit("change",[{added:a,updated:o,removed:l},r]),(a.length>0||s.length>0||l.length>0)&&e.emit("update",[{added:a,updated:s,removed:l},r])};e.s(["Awareness",0,oK,"applyAwarenessUpdate",0,oZ,"encodeAwarenessUpdate",0,oW,"removeAwarenessStates",0,oJ],442957);var oQ=e.i(69497),oY=e.i(38226);let oX=45*Math.floor(8*Math.random());class o0{name;awareness;channel;connected;closed;otherPeers;presenceKey;lastRemoteBroadcast;docs;pendingDocUpdates;pendingAwarenessClients;docFlushTimeout;awarenessFlushTimeout;constructor(e,t){this.name=e,this.awareness=t,this.channel=null,this.connected=!1,this.closed=!1,this.otherPeers=0,this.presenceKey=crypto.randomUUID(),this.lastRemoteBroadcast=0,this.docs=new Map,this.pendingDocUpdates=new Map,this.pendingAwarenessClients=new Set,this.docFlushTimeout=null,this.awarenessFlushTimeout=null,this.onLocalAwarenessUpdate=({added:e,updated:t,removed:r},n)=>{n!==this&&this.queueAwareness(e.concat(t,r))},this.awareness.on("update",this.onLocalAwarenessUpdate)}onLocalAwarenessUpdate;ensureChannel(){if(this.channel||this.closed)return;let e=(0,aP.supabaseBrowserClient)();this.channel=e.channel(`yjs:${this.name}`,{config:{presence:{key:this.presenceKey,enabled:!0}}}),this.channel.on("broadcast",{event:"doc-update"},({payload:e})=>{this.lastRemoteBroadcast=Date.now(),this.onDocBroadcast(e)}),this.channel.on("broadcast",{event:"awareness"},({payload:e})=>{this.lastRemoteBroadcast=Date.now(),this.onAwarenessBroadcast(e)}),this.channel.on("broadcast",{event:"hello"},()=>{this.lastRemoteBroadcast=Date.now(),this.queueAwareness([this.awareness.clientID])}),this.channel.on("presence",{event:"sync"},()=>{this.otherPeers=Object.keys(this.channel?.presenceState()??{}).filter(e=>e!==this.presenceKey).length}),this.channel.on("presence",{event:"join"},({key:e})=>{e!==this.presenceKey&&this.queueAwareness([this.awareness.clientID])}),this.channel.on("presence",{event:"leave"},({key:e,leftPresences:t})=>{if(e===this.presenceKey)return;let r=t.map(e=>e.awarenessClientID).filter(e=>"number"==typeof e);r.length>0&&oJ(this.awareness,r,"presence-leave")}),this.channel.subscribe(async e=>{"SUBSCRIBED"===e?(this.connected=!0,await this.channel?.track({awarenessClientID:this.awareness.clientID}),this.channel?.send({type:"broadcast",event:"hello",payload:{}})):("CLOSED"===e||"CHANNEL_ERROR"===e)&&(this.connected=!1)})}register(e,t){this.ensureChannel();let r=this.docs.get(e);r||this.docs.set(e,r=new Set),r.add(t);let n=(t,r)=>{r&&r!==this&&this.queueDocUpdate(e,t)};return t.on("update",n),()=>{t.off("update",n),r.delete(t),0===r.size&&this.docs.get(e)===r&&this.docs.delete(e)}}destroy(){this.awareness.off("update",this.onLocalAwarenessUpdate),null!==this.docFlushTimeout&&window.clearTimeout(this.docFlushTimeout),null!==this.awarenessFlushTimeout&&(window.clearTimeout(this.awarenessFlushTimeout),this.flushAwareness()),this.closed=!0,this.connected=!1,this.channel?.unsubscribe(),this.channel=null}send(e,t){!this.channel||!this.connected||this.closed||0===this.otherPeers&&Date.now()-this.lastRemoteBroadcast>12e4||this.channel.send({type:"broadcast",event:e,payload:t})}queueDocUpdate(e,t){let r=this.pendingDocUpdates.get(e);r||this.pendingDocUpdates.set(e,r=[]),r.push(t),null===this.docFlushTimeout&&(this.docFlushTimeout=window.setTimeout(()=>{for(let[e,t]of(this.docFlushTimeout=null,this.pendingDocUpdates))this.send("doc-update",{entity:e,update:a8.fromByteArray(a9.mergeUpdates(t)),schemaVersion:oQ.SCHEMA_VERSION});this.pendingDocUpdates.clear()},50))}queueAwareness(e){for(let t of e)this.pendingAwarenessClients.add(t);null===this.awarenessFlushTimeout&&(this.awarenessFlushTimeout=window.setTimeout(()=>{this.awarenessFlushTimeout=null,this.flushAwareness()},80))}flushAwareness(){0!==this.pendingAwarenessClients.size&&(this.send("awareness",{update:a8.fromByteArray(oW(this.awareness,Array.from(this.pendingAwarenessClients)))}),this.pendingAwarenessClients.clear())}onDocBroadcast(e){if(!e?.entity||!e.update)return;if((e.schemaVersion??0)>oQ.SCHEMA_VERSION)return void(0,oY.markClientStale)();let t=this.docs.get(e.entity);if(!t)return;let r=a8.toByteArray(e.update);for(let e of t)try{a9.applyUpdate(e,r,this)}catch(e){console.error("failed to apply remote yjs update",e)}}onAwarenessBroadcast(e){if(e?.update)try{oZ(this.awareness,a8.toByteArray(e.update),this)}catch(e){console.error("failed to apply remote awareness update",e)}}}let o1=(0,c.createContext)(null);function o2(e){let t,r,n,i,a,s,o,h,d,p=(0,u.c)(18),[f]=(0,c.useState)(o5),[m,g]=(0,c.useState)(null),y=(0,c.useRef)(null);p[0]!==f?(t=()=>(null!==y.current&&clearTimeout(y.current),y.current=null,()=>{y.current=setTimeout(()=>f.destroy(),0)}),r=[f],p[0]=f,p[1]=t,p[2]=r):(t=p[1],r=p[2]),(0,c.useEffect)(t,r);let{identity:b}=(0,oU.useIdentityData)(),w=b?.bsky_profiles?.record?.displayName||b?.bsky_profiles?.handle||"Anonymous";return p[3]!==f||p[4]!==w?(n=()=>{f.setLocalStateField("user",{name:w,hue:oX})},i=[f,w],p[3]=f,p[4]=w,p[5]=n,p[6]=i):(n=p[5],i=p[6]),(0,c.useEffect)(n,i),p[7]!==f||p[8]!==e.enabled||p[9]!==e.name?(a=()=>
15{if(!e.enabled)return;let t=new o0(e.name,f);return g(t),()=>{t.destroy(),g(null)}},s=[e.name,e.enabled,f],p[7]=f,p[8]=e.enabled,p[9]=e.name,p[10]=a,p[11]=s):(a=p[10],s=p[11]),(0,c.useEffect)(a,s),p[12]!==f||p[13]!==m?(h={connection:m,awareness:f},p[12]=f,p[13]=m,p[14]=h):h=p[14],o=h,p[15]!==e.children||p[16]!==o?(d=(0,l.jsx)(o1.Provider,{value:o,children:e.children}),p[15]=e.children,p[16]=o,p[17]=d):d=p[17],d}function o5(){return new oK(new a9.Doc)}e.s(["YjsRealtimeConnection",0,o0,"YjsRealtimeProvider",0,o2,"useYjsRealtime",0,()=>(0,c.useContext)(o1)],867854);let o3=(0,c.createContext)({undoManager:oF(),rootEntity:"",rep:null,initialFacts:[],permission_token:{}});function o4(){return(0,c.useContext)(o3)}function o6(e,t){return e.data.position>t.data.position?1:-1}e.s(["ReplicacheProvider",0,function(e){var t;let[r,n]=(0,c.useState)(null),[i]=(0,c.useState)(oF()),a=(0,c.useRef)(e.token);a.current=e.token;let s=(0,c.useRef)(e.rootEntity);s.current=e.rootEntity;let{identity:o}=(0,oU.useIdentityData)(),u=(0,c.useRef)(null);u.current=o?.atp_did??null;let h=[(t=e.token).id,t.root_entity,...t.permission_token_rights.map(e=>[e.token,e.entity_set,e.read,e.write,e.change_entity_set,e.create_token].join(":")).sort()].join("|");return(0,c.useEffect)(()=>oj([{metaKey:!0,key:"z",handler:()=>{i.undo()}},{metaKey:!0,shift:!0,key:"z",handler:()=>{i.redo()}},{metaKey:!0,shift:!0,key:"Z",handler:()=>{i.redo()}}]),[i]),(0,c.useEffect)(()=>{if(e.initialFactsOnly)return;let t=(0,aP.supabaseBrowserClient)(),r=new ii({pullInterval:e.disablePull?null:3e5,pushDelay:1e3,mutators:Object.fromEntries(Object.keys(a4).map(e=>[e,async(t,n)=>{await a4[e](n,function(e,{rep:t,undoManager:r,ignoreUndo:n,defaultEntitySet:i,permission_token_id:a,rootEntity:s,sessionDid:o}){return{permission_token_id:a,rootEntity:s,sessionDid:o,async runOnServer(e){},runOnClient:async t=>t({supabase:(0,aP.supabaseBrowserClient)(),tx:e}),createEntity:async({entityID:t})=>(await e.set(t,!0),!0),scanIndex:{eav:async(t,r)=>oR(e).eav(t,r)},async assertFact(i){let a=a6[i.attribute];if(!a)return;let s=i.id||aT(),o={...i.data},l=[];if("one"===a.cardinality){if((l=await oR(e).eav(i.entity,i.attribute))[0]&&(s=l[0].id,"text"===a.type)){let e=a8.toByteArray((l[0]?.data).value),t=a8.toByteArray(o.value),r=a9.mergeUpdates([e,t]);o.value=a8.fromByteArray(r)}}else if(i.id){let t=await e.get(i.id);t&&(l=[t])}n||r.add({undo:()=>{l[0]?t.mutate.assertFact({ignoreUndo:!0,...l[0]}):("one"!==a.cardinality||i.id||t.mutate.retractAttribute({ignoreUndo:!0,attribute:i.attribute,entity:i.entity}),t.mutate.retractFact({ignoreUndo:!0,factID:s}))},redo:()=>{t.mutate.assertFact({ignoreUndo:!0,...i})}}),await e.set(s,oP({id:s,...i,data:o}))},async retractFact(i){let a=await e.get(i);n||r.add({undo:()=>{a?t.mutate.assertFact({ignoreUndo:!0,...a}):t.mutate.retractFact({ignoreUndo:!0,factID:i})},redo:()=>{t.mutate.retractFact({ignoreUndo:!0,factID:i})}}),await e.del(i)},async deleteEntity(a){let s=[...await e.scan({indexName:"eav",prefix:`${a}`}).toArray(),...await e.scan({indexName:"vae",prefix:a}).toArray()];await Promise.all(s.map(t=>e.del(t.id))),!n&&s.length>0&&r.add({undo:async()=>{let e=s.map(e=>({id:e.id,attribute:e.attribute,entity:e.entity,data:e.data}));e.ignoreUndo=!0,await t.mutate.createEntity([{entityID:a,permission_set:i}]),await t.mutate.assertFact(e)},redo:()=>{t.mutate.deleteEntity({entity:a,ignoreUndo:!0})}})}}}(t,{permission_token_id:a.current.id,rootEntity:s.current,sessionDid:u.current,undoManager:i,rep:r,ignoreUndo:n.ignoreUndo||"initial"!==t.reason,defaultEntitySet:a.current.permission_token_rights[0]?.entity_set}))}])),licenseKey:"l381074b8d5224dabaef869802421225a",pusher:async t=>{let n={...t,mutations:t.mutations.slice(0,250)},i=(await (0,oO.callRPC)("push",{pushRequest:n,token:a.current,rootEntity:e.name})).result;return t.mutations.length>250&&setTimeout(()=>{r.push()},50),{response:i,httpRequestInfo:{errorMessage:"",httpStatusCode:200}}},puller:async e=>({response:await (0,oO.callRPC)("pull",{pullRequest:e,token_id:a.current.id}),httpRequestInfo:{errorMessage:"",httpStatusCode:200}}
15),name:e.name,indexes:{eav:{jsonPointer:"/indexes/eav",allowEmpty:!0},vae:{jsonPointer:"/indexes/vae",allowEmpty:!0}}});n(r);let o=null;if(!e.disablePull){(o=t.channel(`rootEntity:${e.name}`)).on("broadcast",{event:"poke"},()=>{r.pull()});let n=!1;o.subscribe(e=>{"SUBSCRIBED"===e&&(n&&r.pull(),n=!0)})}return()=>{r.close(),n(null),o?.unsubscribe()}},[e.name,e.initialFactsOnly,h,e.disablePull]),(0,l.jsx)(o3.Provider,{value:{undoManager:i,rep:r,rootEntity:e.rootEntity,initialFacts:e.initialFacts,permission_token:e.token},children:(0,l.jsx)(o2,{name:e.name,enabled:!e.initialFactsOnly&&!e.disablePull,children:e.children})})},"useEntity",0,function(e,t){let r,n,i,a,s,o=(0,u.c)(18),{rep:l,initialFacts:c}=o4();if(o[0]!==t||o[1]!==e||o[2]!==c){let r;o[4]!==t||o[5]!==e?(r=r=>r.entity===e&&r.attribute===t,o[4]=t,o[5]=e,o[6]=r):r=o[6],n=c.filter(r),o[0]=t,o[1]=e,o[2]=c,o[3]=n}else n=o[3];r=n,o[7]!==t||o[8]!==e?(i=async r=>null!==e&&await r.get("initialized")?(await r.scan({indexName:"eav",prefix:`${e}-${t}`}).toArray()).filter(e=>e.attribute===t):null,o[7]=t,o[8]=e,o[9]=i):i=o[9],o[10]!==t||o[11]!==e?(a={default:null,dependencies:[e,t]},o[10]=t,o[11]=e,o[12]=a):a=o[12];let h=f(l,i,a),d=h||r,p=a6[t];return o[13]!==p.cardinality||o[14]!==p.type||o[15]!==d||o[16]!==h?(s="many"===p.cardinality?"ordered-reference"===p.type?d.sort(o6):d:0===d.length&&null===h?null:d[0],o[13]=p.cardinality,o[14]=p.type,o[15]=d,o[16]=h,o[17]=s):s=o[17],s},"useReferenceToEntity",0,function(e,t){let r,n,i,a,s=(0,u.c)(13),{rep:o,initialFacts:l}=o4();if(s[0]!==e||s[1]!==t||s[2]!==l){let r;s[4]!==e||s[5]!==t?(r=r=>r.data.value===t&&r.attribute===e,s[4]=e,s[5]=t,s[6]=r):r=s[6],n=l.filter(r),s[0]=e,s[1]=t,s[2]=l,s[3]=n}else n=s[3];return r=n,s[7]!==e||s[8]!==t?(i=async r=>null!==t&&await r.get("initialized")?(await r.scan({indexName:"vae",prefix:`${t}-${e}`}).toArray()).filter(t=>t.attribute===e):null,s[7]=e,s[8]=t,s[9]=i):i=s[9],s[10]!==e||s[11]!==t?(a={default:null,dependencies:[t,e]},s[10]=e,s[11]=t,s[12]=a):a=s[12],f(o,i,a)||r},"useReplicache",0,o4],467592)},813029,579473,e=>{"use strict";var t=e.i(500932),r=e.i(768834);function n(e,t){return(...r)=>Object.assign({},e,t(...r))}e.s(["combine",0,n,"subscribeWithSelector",0,e=>(t,r,n)=>{let i=n.subscribe;return n.subscribe=(e,t,r)=>{let a=e;if(t){let i=(null==r?void 0:r.equalityFn)||Object.is,s=e(n.getState());a=r=>{let n=e(r);if(!i(s,n)){let e=s;t(s=n,e)}},(null==r?void 0:r.fireImmediately)&&t(s,s)}return i(a)},e(t,r,n)}],579473);let i=e=>"string"==typeof e?e:`iframe:${e.url}`,a=(0,r.create)(n({lastUsedHighlight:"1",focusedEntity:null,foldedBlocks:[],zoomedBlocks:{},openPages:[],selectedBlocks:[]},e=>({openPage:(t,r)=>e(e=>{let n=i(t),a=e.openPages.findIndex(e=>i(e)===n);return{openPages:-1===a?[r]:[...e.openPages.slice(0,a+1),r]}}),closePage:t=>e(e=>{let r=[t].flat().map(i);return{openPages:e.openPages.filter(e=>!r.includes(i(e)))}}),setFocusedBlock:t=>e(()=>({focusedEntity:t})),zoomIntoBlock:(t,r)=>e(e=>({zoomedBlocks:{...e.zoomedBlocks,[t]:r}})),zoomOutOfBlock:t=>e(e=>{let{[t]:r,...n}=e.zoomedBlocks;return{zoomedBlocks:n}}),setSelectedBlock:t=>e(e=>1===e.selectedBlocks.length&&e.selectedBlocks[0].entityID===t.entityID&&e.selectedBlocks[0].parent===t.parent?e:{selectedBlocks:[s(t)]}),setSelectedBlocks:t=>e(()=>({selectedBlocks:t.map(s)})),addBlockToSelection:t=>e(e=>e.selectedBlocks.find(e=>e.entityID===t.entityID)?e:{selectedBlocks:[...e.selectedBlocks,s(t)]}),removeBlockFromSelection:t=>e(e=>({selectedBlocks:e.selectedBlocks.filter(e=>e.entityID!==t.entityID)})),focusAndSelectBlock:t=>e(e=>{let r=1===e.selectedBlocks.length&&e.selectedBlocks[0].entityID===t.entityID&&e.selectedBlocks[0].parent===t.parent,n=e.focusedEntity?.entityType==="block"&&e.focusedEntity.entityID===t.entityID&&e.focusedEntity.parent===t.parent;return r&&n?e:{selectedBlocks:r?e.selectedBlocks:[s(t)],focusedEntity:n?e.focusedEntity:{entityType:"block",entityID:t.entityID,parent:t.parent}}})}))),s=e=>({entityID:e.entityID,parent:e.parent});e.s(["getEditorPageKey",0,i,"isZoomedBlockRoot",0,e=>Object.values(a.getState().zoomedBlocks).includes(e),"useIsBlockSelected",0,e=>{let r,n=(0,t.c)(2);return n[0]!==e?(r=t=>t.selectedBlocks.some(t=>t.entityID===e),n[0]=e,n[1]=r):r=n[1],a(r)},"useIsPageFocused",0,e=>{let r,n=(0,t.c)(2);return n[0]!==e?(r=t=>
15t.focusedEntity?.entityType==="page"?t.focusedEntity.entityID===e:t.focusedEntity?.parent===e,n[0]=e,n[1]=r):r=n[1],a(r)},"useUIState",0,a],813029)},124670,e=>{"use strict";let t=e=>e.$link,r="/storage/v1/object/public/";e.s(["COVER_THUMBNAIL_WIDTH",0,{large:800,medium:360},"POST_BODY_IMAGE_WIDTH",0,1200,"blobRefCid",0,t,"blobRefToSrc",0,(e,n,i,a)=>{let s=t(e),o=i?i.replace(/\/$/,""):"";if(s.startsWith("http://")||s.startsWith("https://")){let e=a?.format&&(e=>{let t=e.indexOf(r);if(-1!==t)return e.slice(t+r.length).split("?")[0]||void 0})(s);if(!e)return s;let t=`${o}/api/resized_images?path=${encodeURIComponent(e)}&format=${a.format}`;return a.width&&(t+=`&width=${a.width}`),t}let l=`${o}/api/atproto_images?did=${n}&cid=${s}`;return a?.width&&(l+=`&width=${a.width}`),a?.height&&(l+=`&height=${a.height}`),a?.format&&(l+=`&format=${a.format}`),l+="&v=1"}])},250209,e=>{"use strict";var t=e.i(620196),r=e.i(314192),n=e.i(615405);function i(e){let t=(0,r.normalizePublicationRecord)(e.record);return t?.url&&1?t.url:(0,n.isLeafletPublication)(e.record)&&e.record.base_path&&1?`https://${e.record.base_path}`:a(e)}function a(e){let n=(0,r.normalizePublicationRecord)(e.record),i=new t.AtUri(e.uri),a=i.rkey||n?.name;return`/lish/${i.host}/${encodeURIComponent(a||"")}`}e.s(["getBasePublicationURL",0,a,"getDocumentURL",0,function(e,r,n){let a=e.path||"/"+new t.AtUri(r).rkey;return"/"!==a[0]&&(a="/"+a),(n?"site.standard.publication"===n.$type?n.url||e.site:i(n):e.site).replace(/\/+$/,"")+a},"getPublicationURL",0,i],250209)},314192,137224,615405,e=>{"use strict";var t=e.i(18262);let r=e.i(4220).is$typed;function n(e){return r(e,"pub.leaflet.publication","theme")}t.validate,e.s(["isTheme",0,n],137224);var i=e.i(620196);function a(e){return!!e&&"object"==typeof e&&("pub.leaflet.publication"===e.$type||"string"==typeof e.name&&!("url"in e))}function s(e){if(e&&"object"==typeof e&&"number"==typeof e.r&&"number"==typeof e.g&&"number"==typeof e.b)return{r:e.r,g:e.g,b:e.b}}let o=new Set(["pub.leaflet.theme.color#rgb","pub.leaflet.theme.color#rgba"]);function l(e){return!!e&&"object"==typeof e&&o.has(e.$type??"")}function u(e,t){if(!e||"object"!=typeof e)return null;if(e&&"object"==typeof e&&"site.standard.document"===e.$type){let t=e.preferences;return{...e,theme:e.theme,preferences:t}}if(e&&"object"==typeof e&&("pub.leaflet.document"===e.$type||Array.isArray(e.pages)&&"string"==typeof e.author)){let r=e.publishedAt;if(!r)return null;let n=e.publication||`https://leaflet.pub/p/${e.author}`,a=t?new i.AtUri(t).rkey:void 0,s=e.pages?{$type:"pub.leaflet.content",pages:e.pages}:void 0,o=e.preferences;return{$type:"site.standard.document",title:e.title,site:n,path:a,publishedAt:r,description:e.description,tags:e.tags,coverImage:e.coverImage,bskyPostRef:e.postRef,content:s,theme:e.theme,preferences:o?{...o,$type:"site.standard.publication#preferences"}:void 0}}return null}function c(e){if(!e||"object"!=typeof e)return null;if(e&&"object"==typeof e&&"site.standard.publication"===e.$type){let t;return e.theme&&(t=n(e.theme)?e.theme:{...e.theme,$type:"pub.leaflet.publication#theme"}),{...e,theme:t}}if(a(e)){let t,r=e.base_path?`https://${e.base_path}`:void 0;if(!r)return null;let i=function(e){if(!e)return;let t=s(e.backgroundColor),r=s(e.accentBackground)||s(e.primary),n=s(e.accentText);if(t&&r)return{$type:"site.standard.theme.basic",background:{$type:"site.standard.theme.color#rgb",...t},foreground:{$type:"site.standard.theme.color#rgb",r:0,g:0,b:0},accent:{$type:"site.standard.theme.color#rgb",...r},accentForeground:{$type:"site.standard.theme.color#rgb",...n||{r:255,g:255,b:255}}}}(e.theme);e.theme&&(t=n(e.theme)?e.theme:{...e.theme,$type:"pub.leaflet.publication#theme"});let a=e.preferences?{showInDiscover:e.preferences.showInDiscover,showComments:e.preferences.showComments,showMentions:e.preferences.showMentions,showPrevNext:e.preferences.showPrevNext,showFirstLast:e.preferences.showFirstLast,prevNextDirection:e.preferences.prevNextDirection,showRecommends:e.preferences.showRecommends,showOtherPublicationsInTags:e.preferences.showOtherPublicationsInTags}:void 0;return{$type:"site.standard.publication",name:e.name,url:r,description:e.description,icon:e.icon,basicTheme:i,theme:t,preferences:a}}return null}function h(e){return void 0!==e.content&&"pub.leaflet.content"===e.content.$type}e.s(["getDocumentPages",0,function(e){if(e.content&&h(e))return e.content.pages},"hasLeafletContent",0,h,"isLeafletPublication",0,a,"normalizeDocument",0,u,"normalizePublication",0,c,"resolvePublicationTheme",0,function(e){if(e){var t;
15return(t=e.theme)&&[t.backgroundColor,t.pageBackground,t.primary,t.accentBackground,t.accentText].some(l)?e.theme??void 0:e.basicTheme?function(e){if(!e)return;let t=e=>{let t=s(e);if(t)return{$type:"pub.leaflet.theme.color#rgb",...t}},r=t(e.background),n=t(e.foreground),i=t(e.accent),a=t(e.accentForeground);if(r)return{$type:"pub.leaflet.publication#theme",backgroundColor:r,primary:n,accentBackground:i,accentText:a,showPageBackground:!1}}(e.basicTheme):e.theme??void 0}}],615405),e.s(["normalizeDocumentRecord",0,function(e,t){return u(e,t)},"normalizePublicationRecord",0,function(e){return c(e)}],314192)}]);
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.