@protobase/ui 0.21.5 → 0.21.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/app/embedded-list/cut-off-note.js +11 -0
- package/dist/app/embedded-list/embedded-list.js +14 -5
- package/dist/app/embedded-list/use-embedded-rows.js +15 -3
- package/dist/app/related-section.js +7 -8
- package/dist/live/related-column-rows.js +7 -8
- package/dist/live/search-all.js +27 -0
- package/dist/package.js +1 -1
- package/dist/shell/assets/{app-BmBlR0fJ.js → app-Dfqcc3td.js} +10 -10
- package/dist/shell/assets/{index-BMiDZRGI.js → index-BztYGbYc.js} +1 -1
- package/dist/shell/assets/{maplibre-BFMEpd4m.js → maplibre-CVOEAJ62.js} +1 -1
- package/dist/shell/assets/{markdown-content-yqq0wmAS.js → markdown-content-Bg8FC_aK.js} +1 -1
- package/dist/shell/assets/{record-map-DhpikXZs.js → record-map-ChUVZLR6.js} +1 -1
- package/dist/shell/assets/{records-map-LDeVJQab.js → records-map-BAI2D9VS.js} +1 -1
- package/dist/shell/assets/{shared-protobase-ui-DfPkkHCn.js → shared-protobase-ui-CzT3bJ35.js} +1 -1
- package/dist/shell/index.html +3 -3
- package/dist/shell/protobase.shell.json +1 -1
- package/package.json +4 -4
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/markdown-content-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/markdown-content-Bg8FC_aK.js","assets/rolldown-runtime-hePW80VL.js","assets/react-Cvdyeg_0.js","assets/jsx-runtime-NZYk81nU.js","assets/records-map-BAI2D9VS.js","assets/maplibre-CVOEAJ62.js","assets/react-dom-B-VxWsjA.js","assets/maplibre-DBE96hFo.css","assets/record-map-ChUVZLR6.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{n as e,r as t,t as n}from"./rolldown-runtime-hePW80VL.js";import{t as r}from"./react-Cvdyeg_0.js";import{t as i}from"./react-dom-B-VxWsjA.js";import{t as a}from"./jsx-runtime-NZYk81nU.js";var o=t(r(),1),s=e=>e?.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase();function c(e,t,n=[]){if(t==null)throw Error(`[lucide]: iconNode is required when icon name is used`);return{name:s(e),size:24,node:t,...n.length>0?{aliases:n}:{}}}var l=e=>{let t=``,n=!1;for(let r of e){if(r===`-`||r===`_`||r<=` `){n=t.length>0;continue}t.length===0?t+=r.toLowerCase():t+=n?r.toUpperCase():r,n=!1}return t},u=e=>{let t=l(e);return t.charAt(0).toUpperCase()+t.slice(1)},d=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),f={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":2,"stroke-linecap":`round`,"stroke-linejoin":`round`};function p(e){return e!=null}function m(e,t={}){let n=t.attributeNames??{},r=e=>n[e]??e,i=e.size??e.width??f.width,a=e.size??e.height??f.height,o=e.aliases?.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>`lucide-${e}`)??[],s=[...e.name?[`lucide-${e.name}`]:[],...o],c=t.className?.split(` `).filter(Boolean)??[],l=t.includeDefaultClasses===!1?d(...c):d(`lucide`,...s,...c),u=t.absoluteStrokeWidth?Number(t.strokeWidth??f[`stroke-width`])*Number(e.size??e.width??f.width)/Number(t.size??t.width??f.width):t.strokeWidth??f[`stroke-width`];return[`svg`,{...Object.entries(f).reduce((e,[t,n])=>(e[r(t)]=n,e),{}),...`color`in t&&t.color&&{[r(`stroke`)]:t.color},...`size`in t&&p(t.size)&&{[r(`width`)]:t.size,[r(`height`)]:t.size},...`width`in t&&p(t.width)&&{[r(`width`)]:t.width},...`height`in t&&p(t.height)&&{[r(`height`)]:t.height},[r(`stroke-width`)]:u,...l&&{[r(`class`)]:l},[r(`viewBox`)]:`0 0 ${i} ${a}`,...t.hasA11yProp===!1?{[r(`aria-hidden`)]:`true`}:{},...`attributes`in t&&t.attributes},e.node.map(e=>{let[n,i,a]=e,o=t.nonScalingStroke?{[r(`vector-effect`)]:`non-scaling-stroke`,...i}:i;return a?[n,o,a]:[n,o]})]}function h(e,t={}){return m(e,{...t,attributeNames:{...t.attributeNames,class:`className`,"stroke-width":`strokeWidth`,"stroke-linecap":`strokeLinecap`,"stroke-linejoin":`strokeLinejoin`,"vector-effect":`vectorEffect`}})}var g=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},_=(0,o.createContext)({}),v=()=>(0,o.useContext)(_),y=(0,o.forwardRef)(({color:e,size:t,width:n,height:r,strokeWidth:i,absoluteStrokeWidth:a,nonScalingStroke:s,className:c=``,children:l,iconNode:u=[],icon:f={node:u,aliases:[],size:24},...p},m)=>{let{size:_=24,strokeWidth:y=2,absoluteStrokeWidth:b=!1,nonScalingStroke:x=!1,color:S=`currentColor`,className:C=``}=v()??{},w=!!l||g(p),[T,E,D=[]]=h(f,{color:e??S,width:n??t??_,height:r??t??_,strokeWidth:i??y,absoluteStrokeWidth:a??b,nonScalingStroke:s??x,className:d(C,c),hasA11yProp:w,attributes:p});return(0,o.createElement)(T,{ref:m,...E},[...D.map(([e,t])=>(0,o.createElement)(e,t)),...Array.isArray(l)?l:[l]])});function b(e,t=[],n=[]){let r=typeof e==`string`?c(e,t,n):e,i=(0,o.forwardRef)(({className:e,...t},n)=>(0,o.createElement)(y,{ref:n,icon:r,className:e,...t}));return r.name&&(i.displayName=u(r.name)),i}var x={name:`arrow-down`,size:24,node:[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]};x.node;var S=b(x),C={name:`arrow-right`,size:24,node:[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]};C.node;var w=b(C),T={name:`arrow-up-down`,size:24,node:[[`path`,{d:`m21 16-4 4-4-4`,key:`f6ql7i`}],[`path`,{d:`M17 20V4`,key:`1ejh1v`}],[`path`,{d:`m3 8 4-4 4 4`,key:`11wl7u`}],[`path`,{d:`M7 4v16`,key:`1glfcx`}]]};T.node;var E=b(T),D={name:`arrow-up-right`,size:24,node:[[`path`,{d:`M7 7h10v10`,key:`1tivn9`}],[`path`,{d:`M7 17 17 7`,key:`1vkiza`}]]};D.node;var O=b(D),k={name:`arrow-up`,size:24,node:[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]};k.node;var A=b(k),j={name:`bath`,size:24,node:[[`path`,{d:`M10 4 8 6`,key:`1rru8s`}],[`path`,{d:`M17 19v2`,key:`ts1sot`}],[`path`,{d:`M2 12h20`,key:`9i4pu4`}],[`path`,{d:`M7 19v2`,key:`12npes`}],[`path`,{d:`M9 5 7.621 3.621A2.121 2.121 0 0 0 4 5v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5`,key:`14ym8i`}]]};j.node;var M=b(j),N={name:`bed`,size:24,node:[[`path`,{d:`M2 4v16`,key:`vw9hq8`}],[`path`,{d:`M2 8h18a2 2 0 0 1 2 2v10`,key:`1dgv2r`}],[`path`,{d:`M2 17h20`,key:`18nfp3`}],[`path`,{d:`M6 8v9`,key:`1yriud`}]]};N.node;var ee=b(N),P={name:`bell`,size:24,node:[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}]]};P.node;var te=b(P),F={name:`book-open`,size:24,node:[[`path`,{d:`M12 5v16`,key:`1f6ucr`}],[`path`,{d:`M20.001 19A2 2 0 0022 17V5a2 2 0 00-1.999-2L16 3.002A5 5 0 0012 5a5 5 0 00-4-2H4a2 2 0 00-2 2v12a2 2 0 001.999 2H8a5 5 0 014 2 5 5 0 014-2z`,key:`1fyvmf`}]]};F.node;var ne=b(F),re={name:`bookmark-check`,size:24,node:[[`path`,{d:`M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z`,key:`oz39mx`}],[`path`,{d:`m9 10 2 2 4-4`,key:`1gnqz4`}]]};re.node;var ie=b(re),I={name:`bookmark-plus`,size:24,node:[[`path`,{d:`M12 7v6`,key:`lw1j43`}],[`path`,{d:`M15 10H9`,key:`o6yqo3`}],[`path`,{d:`M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z`,key:`oz39mx`}]]};I.node;var ae=b(I),L={name:`bookmark`,size:24,node:[[`path`,{d:`M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z`,key:`oz39mx`}]]};L.node;var oe=b(L),R={name:`boxes`,size:24,node:[[`path`,{d:`M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z`,key:`lc1i9w`}],[`path`,{d:`m7 16.5-4.74-2.85`,key:`1o9zyk`}],[`path`,{d:`m7 16.5 5-3`,key:`va8pkn`}],[`path`,{d:`M7 16.5v5.17`,key:`jnp8gn`}],[`path`,{d:`M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z`,key:`8zsnat`}],[`path`,{d:`m17 16.5-5-3`,key:`8arw3v`}],[`path`,{d:`m17 16.5 4.74-2.85`,key:`8rfmw`}],[`path`,{d:`M17 16.5v5.17`,key:`k6z78m`}],[`path`,{d:`M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z`,key:`1xygjf`}],[`path`,{d:`M12 8 7.26 5.15`,key:`1vbdud`}],[`path`,{d:`m12 8 4.74-2.85`,key:`3rx089`}],[`path`,{d:`M12 13.5V8`,key:`1io7kd`}]]};R.node;var se=b(R),ce={name:`building-complex`,size:24,node:[[`path`,{d:`M10 12h4`,key:`a56b0p`}],[`path`,{d:`M10 8h4`,key:`1sr2af`}],[`path`,{d:`M14 21v-3a2 2 0 0 0-4 0v3`,key:`1rgiei`}],[`path`,{d:`M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2`,key:`secmi2`}],[`path`,{d:`M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16`,key:`16ra0t`}]],aliases:[`building-2`]};ce.node;var le=b(ce),ue={name:`calendar`,size:24,node:[[`path`,{d:`M8 2v3`,key:`1ioesn`}],[`path`,{d:`M16 2v3`,key:`otl347`}],[`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`,key:`h1oib`}],[`path`,{d:`M3 9h18`,key:`1pudct`}]]};ue.node;var de=b(ue),fe={name:`chart-column`,size:24,node:[[`path`,{d:`M3 3v16a2 2 0 0 0 2 2h16`,key:`c24i48`}],[`path`,{d:`M18 17V9`,key:`2bz60n`}],[`path`,{d:`M13 17V5`,key:`1frdt8`}],[`path`,{d:`M8 17v-3`,key:`17ska0`}]],aliases:[`bar-chart-3`]};fe.node;var pe=b(fe),me={name:`check`,size:24,node:[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]};me.node;var he=b(me),ge={name:`chevron-down`,size:24,node:[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]};ge.node;var _e=b(ge),ve={name:`chevron-left`,size:24,node:[[`path`,{d:`m15 18-6-6 6-6`,key:`1wnfg3`}]]};ve.node;var ye=b(ve),be={name:`chevron-right`,size:24,node:[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]};be.node;var xe=b(be),Se={name:`chevrons-up-down`,size:24,node:[[`path`,{d:`m7 15 5 5 5-5`,key:`1hf1tw`}],[`path`,{d:`m7 9 5-5 5 5`,key:`sgt6xg`}]]};Se.node;var Ce=b(Se),we={name:`circle-arrow-up`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m16 12-4-4-4 4`,key:`177agl`}],[`path`,{d:`M12 16V8`,key:`1sbj14`}]],aliases:[`arrow-up-circle`]};we.node;var Te=b(we),Ee={name:`circle-check`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m16 9-5.5 5.5L8 12`,key:`xofnsj`}]],aliases:[`check-circle-2`]};Ee.node;var De=b(Ee),Oe={name:`circle-dashed`,size:24,node:[[`path`,{d:`M10.1 2.182a10 10 0 0 1 3.8 0`,key:`5ilxe3`}],[`path`,{d:`M13.9 21.818a10 10 0 0 1-3.8 0`,key:`11zvb9`}],[`path`,{d:`M17.609 3.721a10 10 0 0 1 2.69 2.7`,key:`1iw5b2`}],[`path`,{d:`M2.182 13.9a10 10 0 0 1 0-3.8`,key:`c0bmvh`}],[`path`,{d:`M20.279 17.609a10 10 0 0 1-2.7 2.69`,key:`1ruxm7`}],[`path`,{d:`M21.818 10.1a10 10 0 0 1 0 3.8`,key:`qkgqxc`}],[`path`,{d:`M3.721 6.391a10 10 0 0 1 2.7-2.69`,key:`1mcia2`}],[`path`,{d:`M6.391 20.279a10 10 0 0 1-2.69-2.7`,key:`1fvljs`}]]};Oe.node;var ke=b(Oe),Ae={name:`circle-x`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m15 9-6 6`,key:`1uzhvr`}],[`path`,{d:`m9 9 6 6`,key:`z0biqf`}]],aliases:[`x-circle`]};Ae.node;var je=b(Ae),Me={name:`circle`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]};Me.node;var Ne=b(Me),Pe={name:`columns-3`,size:24,node:[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`M15 3v18`,key:`14nvp0`}]],aliases:[`panels-left-right`]};Pe.node;var Fe=b(Pe),Ie={name:`copy`,size:24,node:[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]};Ie.node;var Le=b(Ie),Re={name:`credit-card`,size:24,node:[[`rect`,{width:`20`,height:`14`,x:`2`,y:`5`,rx:`2`,key:`ynyp8z`}],[`line`,{x1:`2`,x2:`22`,y1:`10`,y2:`10`,key:`1b3vmo`}],[`path`,{d:`M6 14h2`,key:`mk7k0u`}]]};Re.node;var ze=b(Re),Be={name:`door-open`,size:24,node:[[`path`,{d:`M10 21H2`,key:`1sthdo`}],[`path`,{d:`M10 3H7a2 2 0 00-2 2v16`,key:`15gt7x`}],[`path`,{d:`M14 12h.01`,key:`1jfl7z`}],[`path`,{d:`M19 21V5a2 2 0 00-1.675-1.974l-6.163-1.013A1 1 0 0010 3v18a1 1 0 001.124.992z`,key:`tyvg9a`}],[`path`,{d:`M22 21h-3`,key:`1ec3tr`}]]};Be.node;var eee=b(Be),Ve={name:`download`,size:24,node:[[`path`,{d:`M12 15V3`,key:`m9g1x1`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`path`,{d:`m7 10 5 5 5-5`,key:`brsn70`}]]};Ve.node;var He=b(Ve),Ue={name:`earth`,size:24,node:[[`path`,{d:`M21.54 15H17a2 2 0 0 0-2 2v4.54`,key:`1djwo0`}],[`path`,{d:`M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17`,key:`1tzkfa`}],[`path`,{d:`M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05`,key:`14pb5j`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]],aliases:[`globe-2`]};Ue.node;var We=b(Ue),Ge={name:`ellipsis`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]],aliases:[`more-horizontal`]};Ge.node;var Ke=b(Ge),qe={name:`external-link`,size:24,node:[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]};qe.node;var Je=b(qe),Ye={name:`eye-off`,size:24,node:[[`path`,{d:`M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49`,key:`ct8e1f`}],[`path`,{d:`M14.084 14.158a3 3 0 0 1-4.242-4.242`,key:`151rxh`}],[`path`,{d:`M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143`,key:`13bj9a`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]};Ye.node;var Xe=b(Ye),Ze={name:`eye`,size:24,node:[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]};Ze.node;var Qe=b(Ze),$e={name:`file-code-corner`,size:24,node:[[`path`,{d:`M4 12.15V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2h-3.35`,key:`1wthlu`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m5 16-3 3 3 3`,key:`331omg`}],[`path`,{d:`m9 22 3-3-3-3`,key:`lsp7cz`}]],aliases:[`file-code-2`]};$e.node;var et=b($e),tt={name:`file-spreadsheet`,size:24,node:[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M8 13h2`,key:`yr2amv`}],[`path`,{d:`M14 13h2`,key:`un5t4a`}],[`path`,{d:`M8 17h2`,key:`2yhykz`}],[`path`,{d:`M14 17h2`,key:`10kma7`}]]};tt.node;var nt=b(tt),rt={name:`file-text`,size:24,node:[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]};rt.node;var it=b(rt),at={name:`grip-vertical`,size:24,node:[[`circle`,{cx:`9`,cy:`12`,r:`1`,key:`1vctgf`}],[`circle`,{cx:`9`,cy:`5`,r:`1`,key:`hp0tcf`}],[`circle`,{cx:`9`,cy:`19`,r:`1`,key:`fkjjf6`}],[`circle`,{cx:`15`,cy:`12`,r:`1`,key:`1tmaij`}],[`circle`,{cx:`15`,cy:`5`,r:`1`,key:`19l28e`}],[`circle`,{cx:`15`,cy:`19`,r:`1`,key:`f4zoj3`}]]};at.node;var ot=b(at),st={name:`heart`,size:24,node:[[`path`,{d:`M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5`,key:`mvr1a0`}]]};st.node;var ct=b(st),lt={name:`house`,size:24,node:[[`path`,{d:`M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8`,key:`5wwlr5`}],[`path`,{d:`M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`,key:`r6nss1`}]],aliases:[`home`]};lt.node;var ut=b(lt),dt={name:`images`,size:24,node:[[`path`,{d:`m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16`,key:`9kzy35`}],[`path`,{d:`M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2`,key:`1t0f0t`}],[`circle`,{cx:`13`,cy:`7`,r:`1`,fill:`currentColor`,key:`1obus6`}],[`rect`,{x:`8`,y:`2`,width:`14`,height:`14`,rx:`2`,key:`1gvhby`}]]};dt.node;var ft=b(dt),pt={name:`info`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]};pt.node;var mt=b(pt),ht={name:`key-round`,size:24,node:[[`path`,{d:`M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z`,key:`1s6t7t`}],[`circle`,{cx:`16.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`w0ekpg`}]]};ht.node;var gt=b(ht),_t={name:`land-plot`,size:24,node:[[`path`,{d:`m12 8 6-3-6-3v10`,key:`mvpnpy`}],[`path`,{d:`m8 11.99-5.5 3.14a1 1 0 0 0 0 1.74l8.5 4.86a2 2 0 0 0 2 0l8.5-4.86a1 1 0 0 0 0-1.74L16 12`,key:`ek95tt`}],[`path`,{d:`m6.49 12.85 11.02 6.3`,key:`1kt42w`}],[`path`,{d:`M17.51 12.85 6.5 19.15`,key:`v55bdg`}]]};_t.node;var vt=b(_t),yt={name:`layout-dashboard`,size:24,node:[[`rect`,{width:`7`,height:`9`,x:`3`,y:`3`,rx:`1`,key:`10lvy0`}],[`rect`,{width:`7`,height:`5`,x:`14`,y:`3`,rx:`1`,key:`16une8`}],[`rect`,{width:`7`,height:`9`,x:`14`,y:`12`,rx:`1`,key:`1hutg5`}],[`rect`,{width:`7`,height:`5`,x:`3`,y:`16`,rx:`1`,key:`ldoo1y`}]]};yt.node;var bt=b(yt),xt={name:`layout-grid`,size:24,node:[[`rect`,{width:`7`,height:`7`,x:`3`,y:`3`,rx:`1`,key:`1g98yp`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`3`,rx:`1`,key:`6d4xhi`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`14`,rx:`1`,key:`nxv5o0`}],[`rect`,{width:`7`,height:`7`,x:`3`,y:`14`,rx:`1`,key:`1bb6yr`}]]};xt.node;var St=b(xt),Ct={name:`leaf`,size:24,node:[[`path`,{d:`M11 20a10 10 0 0010-10 25.9 25.9 0 00-1.04-7.281 1 1 0 00-1.755-.325C15.833 5.5 13 5.5 9.8 6.1A7 7 0 0011 20`,key:`1wjnjv`}],[`path`,{d:`M2 21a5 5 0 012.911-4.544C7.613 15.212 8.351 15.24 11 13`,key:`c1ejpn`}]]};Ct.node;var tee=b(Ct),wt={name:`life-buoy`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m4.93 4.93 4.24 4.24`,key:`1ymg45`}],[`path`,{d:`m14.83 9.17 4.24-4.24`,key:`1cb5xl`}],[`path`,{d:`m14.83 14.83 4.24 4.24`,key:`q42g0n`}],[`path`,{d:`m9.17 14.83-4.24 4.24`,key:`bqpfvv`}],[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}]]};wt.node;var Tt=b(wt),Et={name:`link-2`,size:24,node:[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`,key:`8i5ue5`}],[`path`,{d:`M15 7h2a5 5 0 1 1 0 10h-2`,key:`1b9ql8`}],[`line`,{x1:`8`,x2:`16`,y1:`12`,y2:`12`,key:`1jonct`}]]};Et.node;var Dt=b(Et),Ot={name:`list`,size:24,node:[[`path`,{d:`M3 5h.01`,key:`18ugdj`}],[`path`,{d:`M3 12h.01`,key:`nlz23k`}],[`path`,{d:`M3 19h.01`,key:`noohij`}],[`path`,{d:`M8 5h13`,key:`1pao27`}],[`path`,{d:`M8 12h13`,key:`1za7za`}],[`path`,{d:`M8 19h13`,key:`m83p4d`}]]};Ot.node;var kt=b(Ot),At={name:`loader-circle`,size:24,node:[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]],aliases:[`loader-2`]};At.node;var jt=b(At),Mt={name:`lock`,size:24,node:[[`rect`,{width:`18`,height:`11`,x:`3`,y:`11`,rx:`2`,ry:`2`,key:`1w4ew1`}],[`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`,key:`fwvmzm`}]]};Mt.node;var Nt=b(Mt),Pt={name:`log-in`,size:24,node:[[`path`,{d:`m10 17 5-5-5-5`,key:`1bsop3`}],[`path`,{d:`M15 12H3`,key:`6jk70r`}],[`path`,{d:`M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4`,key:`u53s6r`}]]};Pt.node;var Ft=b(Pt),It={name:`log-out`,size:24,node:[[`path`,{d:`m16 17 5-5-5-5`,key:`1bji2h`}],[`path`,{d:`M21 12H9`,key:`dn1m92`}],[`path`,{d:`M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4`,key:`1uf3rs`}]]};It.node;var Lt=b(It),Rt={name:`mail`,size:24,node:[[`path`,{d:`m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7`,key:`132q7q`}],[`rect`,{x:`2`,y:`4`,width:`20`,height:`16`,rx:`2`,key:`izxlao`}]]};Rt.node;var zt=b(Rt),Bt={name:`map`,size:24,node:[[`path`,{d:`M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z`,key:`169xi5`}],[`path`,{d:`M15 5.764v15`,key:`1pn4in`}],[`path`,{d:`M9 3.236v15`,key:`1uimfh`}]]};Bt.node;var nee=b(Bt),Vt={name:`menu`,size:24,node:[[`path`,{d:`M4 5h16`,key:`1tepv9`}],[`path`,{d:`M4 12h16`,key:`1lakjw`}],[`path`,{d:`M4 19h16`,key:`1djgab`}]]};Vt.node;var ree=b(Vt),Ht={name:`minus`,size:24,node:[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]};Ht.node;var iee=b(Ht),Ut={name:`monitor`,size:24,node:[[`rect`,{width:`20`,height:`14`,x:`2`,y:`3`,rx:`2`,key:`48i651`}],[`line`,{x1:`8`,x2:`16`,y1:`21`,y2:`21`,key:`1svkeh`}],[`line`,{x1:`12`,x2:`12`,y1:`17`,y2:`21`,key:`vw1qmm`}]]};Ut.node;var Wt=b(Ut),Gt={name:`moon`,size:24,node:[[`path`,{d:`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`,key:`kfwtm`}]]};Gt.node;var Kt=b(Gt),qt={name:`network`,size:24,node:[[`rect`,{x:`16`,y:`16`,width:`6`,height:`6`,rx:`1`,key:`4q2zg0`}],[`rect`,{x:`2`,y:`16`,width:`6`,height:`6`,rx:`1`,key:`8cvhb9`}],[`rect`,{x:`9`,y:`2`,width:`6`,height:`6`,rx:`1`,key:`1egb70`}],[`path`,{d:`M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3`,key:`1jsf9p`}],[`path`,{d:`M12 12V8`,key:`2874zd`}]]};qt.node;var Jt=b(qt),Yt={name:`package`,size:24,node:[[`path`,{d:`M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z`,key:`1a0edw`}],[`path`,{d:`M12 22V12`,key:`d0xqtd`}],[`polyline`,{points:`3.29 7 12 12 20.71 7`,key:`ousv84`}],[`path`,{d:`m7.5 4.27 9 5.15`,key:`1c824w`}]]};Yt.node;var Xt=b(Yt),Zt={name:`paperclip`,size:24,node:[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`,key:`1miecu`}]]};Zt.node;var Qt=b(Zt),$t={name:`pencil`,size:24,node:[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]};$t.node;var en=b($t),tn={name:`plus`,size:24,node:[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]};tn.node;var nn=b(tn),rn={name:`puzzle`,size:24,node:[[`path`,{d:`M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z`,key:`w46dr5`}]]};rn.node;var an=b(rn),on={name:`receipt`,size:24,node:[[`path`,{d:`M12 17V7`,key:`pyj7ub`}],[`path`,{d:`M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8`,key:`1elt7d`}],[`path`,{d:`M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z`,key:`ycz6yz`}]]};on.node;var sn=b(on),cn={name:`refresh-cw`,size:24,node:[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]};cn.node;var ln=b(cn),un={name:`ruler-dimension-line`,size:24,node:[[`path`,{d:`M10 15v-3`,key:`1pjskw`}],[`path`,{d:`M14 15v-3`,key:`1o1mqj`}],[`path`,{d:`M18 15v-3`,key:`cws6he`}],[`path`,{d:`M2 8V4`,key:`3jv1jz`}],[`path`,{d:`M22 6H2`,key:`1iqbfk`}],[`path`,{d:`M22 8V4`,key:`16f4ou`}],[`path`,{d:`M6 15v-3`,key:`1ij1qe`}],[`rect`,{x:`2`,y:`12`,width:`20`,height:`8`,rx:`2`,key:`1tqiko`}]]};un.node;var aee=b(un),dn={name:`search`,size:24,node:[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]};dn.node;var fn=b(dn),pn={name:`send-horizontal`,size:24,node:[[`path`,{d:`M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z`,key:`117uat`}],[`path`,{d:`M6 12h16`,key:`s4cdu5`}]],aliases:[`send-horizonal`]};pn.node;var oee=b(pn),mn={name:`send`,size:24,node:[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`,key:`1ffxy3`}],[`path`,{d:`m21.854 2.147-10.94 10.939`,key:`12cjpa`}]]};mn.node;var see=b(mn),hn={name:`settings`,size:24,node:[[`path`,{d:`M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915`,key:`1i5ecw`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]};hn.node;var gn=b(hn),_n={name:`shield-check`,size:24,node:[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]};_n.node;var vn=b(_n),yn={name:`shopping-cart`,size:24,node:[[`path`,{d:`m2.05 2.05 1.099-.028a1 1 0 0 1 1.008.815l2.69 14.347A1 1 0 0 0 7.83 18H18`,key:`uebgi3`}],[`path`,{d:`M4.563 5h16.435a1 1 0 0 1 .981 1.204l-1.026 6.226A2 2 0 0 1 18.962 14H6.25`,key:`1j7c9p`}],[`circle`,{cx:`18`,cy:`20`,r:`2`,key:`t9985n`}],[`circle`,{cx:`8`,cy:`20`,r:`2`,key:`ckkr5m`}]]};yn.node;var bn=b(yn),xn={name:`sliders-horizontal`,size:24,node:[[`path`,{d:`M10 5H3`,key:`1qgfaw`}],[`path`,{d:`M12 19H3`,key:`yhmn1j`}],[`path`,{d:`M14 3v4`,key:`1sua03`}],[`path`,{d:`M16 17v4`,key:`1q0r14`}],[`path`,{d:`M21 12h-9`,key:`1o4lsq`}],[`path`,{d:`M21 19h-5`,key:`1rlt1p`}],[`path`,{d:`M21 5h-7`,key:`1oszz2`}],[`path`,{d:`M8 10v4`,key:`tgpxqk`}],[`path`,{d:`M8 12H3`,key:`a7s4jb`}]]};xn.node;var Sn=b(xn),Cn={name:`sparkles`,size:24,node:[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]],aliases:[`stars`]};Cn.node;var wn=b(Cn),Tn={name:`square-kanban`,size:24,node:[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M8 7v7`,key:`1x2jlm`}],[`path`,{d:`M12 7v4`,key:`xawao1`}],[`path`,{d:`M16 7v9`,key:`1hp2iy`}]],aliases:[`kanban-square`]};Tn.node;var En=b(Tn),Dn={name:`sun-moon`,size:24,node:[[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M14.837 16.385a6 6 0 1 1-7.223-7.222c.624-.147.97.66.715 1.248a4 4 0 0 0 5.26 5.259c.589-.255 1.396.09 1.248.715`,key:`xlf6rm`}],[`path`,{d:`M16 12a4 4 0 0 0-4-4`,key:`6vsxu`}],[`path`,{d:`m19 5-1.256 1.256`,key:`1yg6a6`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}]]};Dn.node;var On=b(Dn),kn={name:`sun`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]};kn.node;var An=b(kn),jn={name:`table-2`,size:24,node:[[`path`,{d:`M3 9h18`,key:`1pudct`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`,key:`h1oib`}]]};jn.node;var Mn=b(jn),Nn={name:`tag`,size:24,node:[[`path`,{d:`M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z`,key:`vktsd0`}],[`circle`,{cx:`7.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`kqv944`}]]};Nn.node;var Pn=b(Nn),Fn={name:`tags`,size:24,node:[[`path`,{d:`M13.172 2a2 2 0 0 1 1.414.586l6.71 6.71a2.4 2.4 0 0 1 0 3.408l-4.592 4.592a2.4 2.4 0 0 1-3.408 0l-6.71-6.71A2 2 0 0 1 6 9.172V3a1 1 0 0 1 1-1z`,key:`16rjxf`}],[`path`,{d:`M2 7v6.172a2 2 0 0 0 .586 1.414l6.71 6.71a2.4 2.4 0 0 0 3.191.193`,key:`178nd4`}],[`circle`,{cx:`10.5`,cy:`6.5`,r:`.5`,fill:`currentColor`,key:`12ikhr`}]]};Fn.node;var In=b(Fn),Ln={name:`trash`,size:24,node:[[`path`,{d:`M10 11v6`,key:`nco0om`}],[`path`,{d:`M14 11v6`,key:`outv1u`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,key:`miytrc`}],[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`,key:`e791ji`}]],aliases:[`trash-2`]};Ln.node;var Rn=b(Ln),zn={name:`triangle-alert`,size:24,node:[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]],aliases:[`alert-triangle`]};zn.node;var Bn=b(zn),Vn={name:`truck`,size:24,node:[[`path`,{d:`M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2`,key:`wrbu53`}],[`path`,{d:`M15 18H9`,key:`1lyqi6`}],[`path`,{d:`M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14`,key:`lysw3i`}],[`circle`,{cx:`17`,cy:`18`,r:`2`,key:`332jqn`}],[`circle`,{cx:`7`,cy:`18`,r:`2`,key:`19iecd`}]]};Vn.node;var Hn=b(Vn),Un={name:`upload`,size:24,node:[[`path`,{d:`M12 3v12`,key:`1x0j5s`}],[`path`,{d:`m17 8-5-5-5 5`,key:`7q97r8`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}]]};Un.node;var Wn=b(Un),Gn={name:`user-round-cog`,size:24,node:[[`path`,{d:`m14.305 19.53.923-.382`,key:`3m78fa`}],[`path`,{d:`m15.228 16.852-.923-.383`,key:`npixar`}],[`path`,{d:`m16.852 15.228-.383-.923`,key:`5xggr7`}],[`path`,{d:`m16.852 20.772-.383.924`,key:`dpfhf9`}],[`path`,{d:`m19.148 15.228.383-.923`,key:`1reyyz`}],[`path`,{d:`m19.53 21.696-.382-.924`,key:`1goivc`}],[`path`,{d:`M2 21a8 8 0 0 1 10.434-7.62`,key:`1yezr2`}],[`path`,{d:`m20.772 16.852.924-.383`,key:`htqkph`}],[`path`,{d:`m20.772 19.148.924.383`,key:`9w9pjp`}],[`circle`,{cx:`10`,cy:`8`,r:`5`,key:`o932ke`}],[`circle`,{cx:`18`,cy:`18`,r:`3`,key:`1xkwt0`}]],aliases:[`user-cog-2`]};Gn.node;var cee=b(Gn),Kn={name:`users`,size:24,node:[[`path`,{d:`M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2`,key:`1yyitq`}],[`path`,{d:`M16 3.128a4 4 0 0 1 0 7.744`,key:`16gr8j`}],[`path`,{d:`M22 21v-2a4 4 0 0 0-3-3.87`,key:`kshegd`}],[`circle`,{cx:`9`,cy:`7`,r:`4`,key:`nufk8`}]]};Kn.node;var qn=b(Kn),Jn={name:`wallet`,size:24,node:[[`path`,{d:`M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1`,key:`18etb6`}],[`path`,{d:`M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4`,key:`xoc0q4`}]]};Jn.node;var lee=b(Jn),Yn={name:`warehouse`,size:24,node:[[`path`,{d:`M18 21V10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1v11`,key:`pb2vm6`}],[`path`,{d:`M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 1.132-1.803l7.95-3.974a2 2 0 0 1 1.837 0l7.948 3.974A2 2 0 0 1 22 8z`,key:`doq5xv`}],[`path`,{d:`M6 13h12`,key:`yf64js`}],[`path`,{d:`M6 17h12`,key:`1jwigz`}]]};Yn.node;var Xn=b(Yn),Zn={name:`x`,size:24,node:[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]};Zn.node;var Qn=b(Zn),$n={name:`zap`,size:24,node:[[`path`,{d:`M15.914 4a1.5 1.5 0 00-2.474-1.561l-9 9A1.5 1.5 0 005.5 14h4.002a.5.5 0 01.471.666L8.086 20a1.5 1.5 0 002.475 1.56l9-9A1.5 1.5 0 0018.5 10h-3.997a.5.5 0 01-.472-.667z`,key:`1v7up4`}]]};$n.node;var er=b($n),tr=t(i()),nr=`/-/account`,rr=`/-/sign-in-policy`,ir=(e,t,n)=>[{id:`account-security`,label:`Sign-in & security`,icon:gt,href:`${e}${nr}`,active:t===nr},...n?[{id:`sign-in-policy`,label:`Sign-in policy`,icon:vn,href:`${e}${rr}`,active:t===rr}]:[]],ar=(e,t,n,r)=>({code:e,message:t,hint:n,span:r}),or=(e,t)=>{let n=Array.from({length:t.length+1},(e,t)=>t);for(let r=1;r<=e.length;r++){let i=[r];for(let a=1;a<=t.length;a++){let o=e[r-1]===t[a-1]?0:1;i[a]=Math.min(n[a]+1,i[a-1]+1,n[a-1]+o)}n=i}return n[t.length]},sr=(e,t)=>{let n=e.toLowerCase(),r=t.map(e=>({candidate:e,score:or(n,e.toLowerCase())})).sort((e,t)=>e.score-t.score)[0];return r&&r.score<=Math.max(2,Math.floor(e.length/3))?r.candidate:void 0},cr=(e,t)=>({start:e.start,end:t.end}),lr=(e,t)=>t===2?e%4==0&&(e%100!=0||e%400==0)?29:28:[4,6,9,11].includes(t)?30:31,ur=e=>{let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return!1;let[n,r,i]=[Number(t[1]),Number(t[2]),Number(t[3])];return r>=1&&r<=12&&i>=1&&i<=lr(n,r)},dr=e=>{let t=/^(\d{4}-\d{2}-\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))$/.exec(e);if(!t)return!1;let[n,r,i]=[Number(t[2]),Number(t[3]),Number(t[4])],[a,o]=[Number(t[5]??0),Number(t[6]??0)];return ur(t[1])&&n<=23&&r<=59&&i<=59&&a<=23&&o<=59},fr={s:1,m:60,h:3600,d:86400,w:604800},pr=e=>dr(e)?Date.parse(e.toUpperCase()):void 0,mr=/^(\d+(?:\.\d+)?)(s|m|h|d|w)$/,hr=e=>{let t=mr.exec(e);return t?Number(t[1])*fr[t[2]]:void 0},gr=/\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})/y,_r=/\d{4}-\d{2}-\d{2}/y,vr=/[TtZz0-9:.+-]*/y,yr=/0[xX][0-9a-fA-F]+/y,br=/\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/y,xr=(e,t,n)=>(e.lastIndex=n,e.exec(t)?.[0]),Sr=(e,t,n,r)=>{let i=xr(gr,e,t);if(i&&dr(i))return{kind:`timestamp`,end:t+i.length};if(i||xr(_r,e,t)){let n=t+(xr(vr,e,t)??``).length;return{kind:`error`,end:n,error:ar(`invalid-timestamp`,`"${e.slice(t,n)}" is not a valid RFC-3339 timestamp`,`Use a full timestamp like 2012-04-21T11:30:00Z, or quote a plain date: "2012-04-21"`,{start:t,end:n})}}let a=xr(yr,e,t);if(a)return n(e[t+a.length])?{kind:`number`,end:t+a.length}:void 0;let o=t+xr(br,e,t).length;return(r.durationUnits?`smhdw`:`s`).includes(e[o]??` `)&&n(e[o+1])?{kind:`duration`,end:o+1}:n(e[o])?{kind:`number`,end:o}:void 0},Cr={a:`\x07`,b:`\b`,f:`\f`,n:`
|
|
3
3
|
`,r:`\r`,t:` `,v:`\v`,"'":`'`,'"':`"`,"\\":`\\`,"?":`?`,"`":"`"},wr=(e,t,n)=>{let r=e.slice(t,t+n);return r.length===n&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):void 0},Tr=(e,t)=>{let n=e[t+1];if(n===void 0)return{error:`a backslash at the end`,end:t+1};if(Object.hasOwn(Cr,n))return{text:Cr[n],end:t+2};let r={x:2,u:4,U:8};if(Object.hasOwn(r,n)){let i=wr(e,t+2,r[n]),a=t+2+r[n];return i!==void 0&&i<=1114111&&!(i>=55296&&i<=57343)?{text:String.fromCodePoint(i),end:a}:{error:`\\${n} needs ${r[n]} hex digits naming a Unicode scalar value`,end:t+2}}let i=/^[0-3][0-7]{2}/.exec(e.slice(t+1,t+4));return i?{text:String.fromCharCode(parseInt(i[0],8)),end:t+4}:{error:`the escape "\\${n}"`,end:t+2}},Er=(e,t)=>{let n=e[t],r=[],i=``,a=t+1;for(;a<e.length;){let t=e[a];if(t===n)return{end:a+1,value:i,errors:r};if(t!==`\\`){i+=t,a++;continue}let o=Tr(e,a);`text`in o?i+=o.text:r.push(ar(`invalid-escape`,`Invalid escape: ${o.error}`,`Valid escapes: \\a \\b \\f \\n \\r \\t \\v \\' \\" \\\\ \\? \\\` \\xHH \\uXXXX \\UXXXXXXXX \\ooo`,{start:a,end:o.end})),a=o.end}return r.push(ar(`unterminated-string`,`String is missing its closing quote`,`Add a closing ${n}`,{start:t,end:e.length})),{end:e.length,value:void 0,errors:r}},Dr={"(":`lparen`,")":`rparen`,",":`comma`,".":`dot`,":":`has`,"=":`eq`,"<":`lt`,">":`gt`,"-":`minus`},Or={AND:`and`,OR:`or`,NOT:`not`},kr=e=>{let[t,n,r]=[e.at(-1),e.at(-2),e.at(-3)];return t?.kind===`rparen`&&n?.kind===`lparen`&&r?.text===`now`},Ar=(e,t={})=>{let n=[],r=[],i=e=>e!==void 0&&(e in Dr||e===`!`||t.arithmetic===!0&&e===`+`),a=e=>e===void 0||/\s/.test(e)||i(e)||e===`"`||e===`'`,o=(t,r,i,a=e.slice(r,i))=>n.push({kind:t,text:e.slice(r,i),value:a,span:{start:r,end:i}}),s=e.isWellFormed()?-1:e.search(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/);s>=0&&r.push(ar(`invalid-unicode`,`The filter contains an unpaired surrogate`,`Use well-formed UTF-16 text`,{start:s,end:s+1}));let c=0;for(;c<e.length;){let i=e[c];if(/\s/.test(i)){c++;continue}if(i===`"`||i===`'`){let t=Er(e,c);r.push(...t.errors),t.value!==void 0&&o(`string`,c,t.end,t.value),c=t.end;continue}if(/[0-9]/.test(i)){let n=Sr(e,c,a,t);if(n?.kind===`error`?r.push(n.error):n&&o(n.kind,c,n.end),n){c=n.end;continue}}if(i===`!`||i===`<`||i===`>`){let t=e[c+1]===`=`;if(i===`!`&&!t){r.push(ar(`unexpected-character`,`Unexpected character "!"`,`Use != for "not equal" or NOT / - for negation`,{start:c,end:c+1})),c++;continue}o(i===`!`?`ne`:i===`<`?t?`le`:`lt`:t?`ge`:`gt`,c,c+(t?2:1)),c+=t?2:1;continue}if(Object.hasOwn(Dr,i)){o(Dr[i],c,c+1),c++;continue}let s=t.arithmetic===`now-offset`&&kr(n);if(i===`+`&&(t.arithmetic===!0||s)){o(`plus`,c,c+1),c++;continue}let l=c+1;for(;!a(e[l]);)l++;let u=e.slice(c,l);o(Object.hasOwn(Or,u)?Or[u]:`text`,c,l),c=l}return o(`eof`,e.length,e.length),{tokens:n,errors:r}},jr=class extends Error{error;constructor(e){super(e.message),this.error=e}},Mr=(e,t,n,r)=>{throw new jr(ar(e,t,n,r))},z=(e,t=0)=>e.tokens[Math.min(e.pos+t,e.tokens.length-1)],Nr=e=>{let t=z(e);return t.kind!==`eof`&&e.pos++,t},Pr=(e,t)=>z(e).kind===t?Nr(e):void 0,Fr=e=>e.kind===`eof`?`end of input`:`"${e.text}"`,Ir=(e,t,n,r)=>Pr(e,t)??Mr(`expected-token`,`Expected ${n} but found ${Fr(z(e))}`,r,z(e).span),Lr=(e,t,n)=>{e.depth>=e.maxDepth&&Mr(`too-deep`,`The filter is nested too deeply`,`Nest at most ${e.maxDepth} levels`,t),e.depth++;try{return n()}finally{e.depth--}},Rr=[`text`,`and`,`or`,`not`],zr=e=>{let t=Ir(e,`text`,`a field name or value`,`Text may not contain spaces or the characters ( ) - . = : < > ! ,`),n=[t.text],r=t.span;for(;z(e).kind===`dot`;){let t=z(e,1),i=t.kind===`number`&&/^\d+(\.\d+)?$/.test(t.text);!Rr.includes(t.kind)&&!i&&Mr(`expected-token`,`Expected a field name after "." but found ${Fr(t)}`,`Write traversals like customer.country`,t.span),Nr(e),Nr(e),n.push(...i?t.text.split(`.`):[t.text]),r=cr(r,t.span)}return{kind:`member`,path:n,span:r}},uee=e=>({kind:`duration`,amount:Number(e.text.slice(0,-1)),unit:e.text.slice(-1),span:e.span}),dee=[`member`,`string`,`number`,`boolean`,`duration`,`timestamp`,`call`,`binary`],Br=e=>dee.includes(e.kind),fee=(e,t,n)=>Lr(e,n,()=>{Nr(e);let r=[];if(z(e).kind!==`rparen`)do r.push(Ur(e));while(Pr(e,`comma`));return{kind:`call`,name:t,args:r,span:cr(n,Ir(e,`rparen`,`")"`,`Close the call to ${t}() with ")"`).span)}}),Vr=e=>{let t=z(e);switch(t.kind){case`string`:return Nr(e),{kind:`string`,value:t.value,span:t.span};case`number`:return Nr(e),{kind:`number`,value:Number(t.text),raw:t.text,span:t.span};case`duration`:return Nr(e),uee(t);case`timestamp`:return Nr(e),{kind:`timestamp`,value:t.text,span:t.span};case`minus`:{let n=z(e,1);(n.kind!==`number`||n.span.start!==t.span.end)&&Mr(`unexpected-token`,`Expected a number after "-" but found ${Fr(n)}`,`Write negative numbers as -5, without a space`,n.span),Nr(e),Nr(e);let r=`-${n.text}`;return{kind:`number`,value:-Number(n.text),raw:r,span:cr(t.span,n.span)}}case`text`:{if((t.text===`true`||t.text===`false`)&&z(e,1).kind!==`dot`&&(z(e,1).kind!==`lparen`||z(e,1).span.start!==t.span.end))return Nr(e),{kind:`boolean`,value:t.text===`true`,span:t.span};let n=zr(e);return z(e).kind===`lparen`&&z(e).span.start===n.span.end?fee(e,n.path.join(`.`),n.span):n}default:return Mr(`unexpected-token`,`Expected a value but found ${Fr(t)}`,`Values are text, "strings", numbers, true/false, durations, timestamps or function calls`,t.span)}},pee=e=>{let t=Nr(e);return Lr(e,t.span,()=>{let n=e.expression(e);return Ir(e,`rparen`,`")"`,`Close the group opened here`),n?n.kind===`global`?n.value:n:Mr(`unexpected-token`,`Empty group`,`Put an expression inside the parentheses`,t.span)})},Hr=e=>z(e).kind===`lparen`?pee(e):Vr(e),mee=e=>[`text`,`string`,`number`,`duration`,`timestamp`,`lparen`,`minus`].includes(z(e,1).kind),Ur=e=>{let t=Hr(e);if(!e.extensions.arithmetic||!Br(t))return t;let n=t,r=e.extensions.arithmetic===`now-offset`,i=()=>n.kind===`call`&&n.name===`now`&&n.args.length===0,a=()=>!r||i()&&z(e,1).kind===`duration`;if(r&&i()&&(z(e).kind===`plus`||z(e).kind===`minus`)&&z(e,1).kind!==`duration`)return Mr(`expected-token`,`Expected a duration after "${z(e).text}" but found ${Fr(z(e,1))}`,`Durations need a unit, for example now() - 30d`,z(e,1).span);for(;(z(e).kind===`plus`||z(e).kind===`minus`)&&mee(e)&&a();){let t=Nr(e).kind===`plus`?`+`:`-`,r=Hr(e);if(!Br(r))return Mr(`unexpected-token`,`Arithmetic needs values, not conditions`,`Use values on both sides of + and -`,r.span);n={kind:`binary`,op:t,left:n,right:r,span:cr(n.span,r.span)}}return n},Wr=e=>{let t=z(e),n=Ur(e);return Br(n)||Mr(`unexpected-token`,`A comparison needs a value on the right`,`Write field = value`,t.span),n},hee={eq:`=`,ne:`!=`,lt:`<`,le:`<=`,gt:`>`,ge:`>=`},Gr=[`text`,`string`,`number`,`duration`,`timestamp`,`not`,`minus`,`lparen`],Kr=(e,t)=>{let n=t.filter(e=>e!==void 0);return n.length<=1?n[0]:{kind:e,args:n,span:cr(n[0].span,n[n.length-1].span)}},gee=e=>{let t=0;for(;;){let{kind:n}=z(e);if(n===`eof`||t===0&&(n===`and`||n===`or`||n===`rparen`))return;n===`lparen`&&t++,n===`rparen`&&t--,Nr(e)}},_ee=e=>{let t=Vr(e),n=z(e);if(n.kind===`has`){Nr(e);let n=z(e);if(n.kind===`text`&&n.text===`*`)return Nr(e),{kind:`present`,left:t,span:cr(t.span,n.span)};let r=Wr(e);return{kind:`has`,left:t,right:r,span:cr(t.span,r.span)}}let r=hee[n.kind];if(r){Nr(e);let n=Wr(e);return{kind:`compare`,op:r,left:t,right:n,span:cr(t.span,n.span)}}return t.kind===`call`?t:{kind:`global`,value:t,span:t.span}},qr=e=>{let t=z(e);return t.kind===`lparen`?(Nr(e),Lr(e,t.span,()=>{let n=Zr(e);return Pr(e,`rparen`)||e.errors.push(ar(`expected-token`,`Expected ")" but found ${Fr(z(e))}`,`Close the group opened here`,t.span)),n})):_ee(e)},vee=e=>{let t=z(e);if(t.kind!==`not`&&t.kind!==`minus`)return Gr.includes(t.kind)?Lr(e,t.span,()=>qr(e)):Mr(`unexpected-token`,`Unexpected ${Fr(t)}`,`Expected a field, a value or "("`,t.span);Nr(e);let n=z(e),r=n.kind===`minus`&&z(e,1).kind===`number`&&z(e,1).span.start===n.span.end;(n.kind===`not`||n.kind===`minus`&&!r)&&Mr(`unexpected-token`,`Negations cannot be stacked`,`Group the inner one: NOT (NOT a)`,n.span);let i=Lr(e,t.span,()=>qr(e));if(!i)return;let a=cr(t.span,i.span);if(t.kind===`minus`&&i.kind===`global`&&i.value.kind===`number`&&!i.value.raw.startsWith(`-`)){let{raw:e,value:t}=i.value;return{kind:`global`,value:{kind:`number`,value:-t,raw:`-${e}`,span:a},span:a}}return{kind:`not`,arg:i,span:a}},Jr=e=>{try{return vee(e)}catch(t){if(!(t instanceof jr))throw t;e.errors.push(t.error),gee(e);return}},Yr=e=>{let t=[Jr(e)];for(;Pr(e,`or`);)t.push(Jr(e));return Kr(`or`,t)},Xr=e=>{let t=[Yr(e)];for(;Gr.includes(z(e).kind);)t.push(Yr(e));return Kr(`sequence`,t)},Zr=e=>{let t=[Xr(e)];for(;Pr(e,`and`);)t.push(Xr(e));return Kr(`and`,t)},Qr=(e,t={})=>{let n=t.maxLength??1e4;if(e.length>n)return{ok:!1,ast:void 0,errors:[ar(`too-long`,`The filter is longer than ${n} characters`,`Shorten the filter`,{start:n,end:e.length})]};let r=t.extensions??{},i=Ar(e,r),a={tokens:i.tokens,pos:0,errors:i.errors,depth:0,maxDepth:t.maxDepth??64,extensions:r,expression:Zr},o=[];for(;z(a).kind!==`eof`;){if(z(a).kind===`rparen`){let e=Nr(a);a.errors.push(ar(`unexpected-token`,`Unmatched ")"`,`Remove it or add a matching "("`,e.span));continue}o.push(Zr(a))}let s=o.filter(e=>e!==void 0),c=s.length<=1?s[0]:{kind:`and`,args:s,span:{start:s[0].span.start,end:s[s.length-1].span.end}},l=[...a.errors].sort((e,t)=>e.span.start-t.span.start);return l.length===0?{ok:!0,ast:c,errors:[]}:{ok:!1,ast:c,errors:l}},$r=(e,t)=>{if(Object.hasOwn(e,t))return{name:t,spec:e[t]};let n=Object.entries(e).find(([,e])=>e.aliases?.includes(t));return n&&{name:n[0],spec:n[1]}},ei=(e,t)=>{let n=t.path[0],r=$r(e.schema.fields,n);if(!r){let r=Object.entries(e.schema.fields).filter(([,e])=>e.filterable!==!1).map(([e])=>e),i=sr(n,r);e.errors.push(ar(`unknown-field`,`Unknown field "${n}"`,i?`Did you mean "${i}"?`:`Available fields: ${r.join(`, `)}`,t.span));return}let i=[r.name],a=r.spec,o=a.filterable!==!1;for(let n of t.path.slice(1)){let r=a.type===`message`?a.fields?.[n]:a.type===`map`?a.value:a.type===`any`?a:void 0;if(!r||a.type===`message`&&!Object.hasOwn(a.fields??{},n)){e.errors.push(ar(`invalid-traversal`,`Cannot traverse into "${n}" of "${i.join(`.`)}"`,a.type===`message`?`Available fields: ${Object.keys(a.fields??{}).join(`, `)}`:`Only message, map and any fields can be traversed`,t.span));return}i.push(n),a=r,o&&=a.filterable!==!1}if(!o){e.errors.push(ar(`not-filterable`,`Field "${i.join(`.`)}" cannot be filtered on`,`Mark it filterable in the schema`,t.span));return}return{...t,path:i,field:{name:i.join(`.`),spec:a}}},ti=(e,t)=>({message:e,hint:t}),ni=(e,t)=>ti(`Expected ${e}`,t),ri=e=>e.kind===`string`?e.value:e.kind===`member`?e.path.join(`.`):void 0,ii={integer:/^-?(\d+|0[xX][0-9a-fA-F]+)$/,number:/^-?\d+(\.\d+)?([eE][+-]?\d+)?$|^-?0[xX][0-9a-fA-F]+$/},ai=(e,t)=>e===t||e===`any`||t===`any`||[`integer`,`number`].includes(e)&&[`integer`,`number`].includes(t),oi=(e,t,n)=>{let r=ri(n);switch(e){case`any`:return;case`string`:return r===void 0?ni(`a string`,`Quote text values: "..."`):void 0;case`enum`:return r!==void 0&&t?.values?.includes(r)?void 0:ti(`Invalid enum value`,`Allowed values: ${(t?.values??[]).join(`, `)}`);case`integer`:case`number`:{let t=n.kind===`number`?n.raw:r;return t!==void 0&&ii[e].test(t)?void 0:ni(e===`integer`?`an integer`:`a number`,`Write 42, -1.5 or 2.5e3, or quote a numeric string`)}case`boolean`:return n.kind===`boolean`||r===`true`||r===`false`?void 0:ni(`true or false`,`Write true or false`);case`timestamp`:return n.kind===`timestamp`||r!==void 0&&dr(r)?void 0:ni(`an RFC-3339 timestamp`,`Use "2012-04-21T11:30:00Z"`);case`duration`:return n.kind===`duration`||r!==void 0&&hr(r)!==void 0?void 0:ni(`a duration`,`Use a number with a unit, for example 20s or 1.5s`);case`map`:case`message`:return ti(`${e} fields cannot be compared`,`Compare a nested field, or use field:key`)}},si=e=>[`member`,`string`,`number`,`boolean`,`duration`,`timestamp`,`call`,`binary`].includes(e.kind),ci=(e,t,n,r)=>{if(!si(n)){e.errors.push(ar(`wrong-argument`,`Argument "${t.name}" must be a value`,`Pass a field, literal or function call`,n.span));return}if(t.type===`field`){if(n.kind!==`member`){e.errors.push(ar(`wrong-argument`,`Argument "${t.name}" must be a field`,`Pass a field name without quotes`,n.span));return}let r=ei(e,n);if(r&&t.of&&!t.of.includes(r.field.spec.type)){e.errors.push(ar(`wrong-argument`,`Argument "${t.name}" cannot be a ${r.field.spec.type} field`,`Accepted field types: ${t.of.join(`, `)}`,n.span));return}return r}let i=r(e,n);if(!i)return;if(t.type===`any`)return i.node;let a=i.type&&(n.kind===`call`||n.kind===`binary`)?ai(t.type,i.type)?void 0:{message:`Expected ${t.type}`,hint:`Argument "${t.name}" is ${i.type}`}:oi(t.type,void 0,i.node);return a&&e.errors.push(ar(`wrong-argument`,a.message,a.hint,n.span)),a?void 0:i.node},li=(e,t,n)=>{let r=e.schema.functions??{};if(!Object.hasOwn(r,t.name)){let n=sr(t.name,Object.keys(r));e.errors.push(ar(`unknown-function`,`Unknown function "${t.name}"`,n?`Did you mean "${n}"?`:`Available functions: ${Object.keys(r).join(`, `)||`none`}`,t.span));return}let i=r[t.name],a=i.params.length;if(t.args.length<a||!i.rest&&t.args.length>a){let n=i.rest?`at least ${a}`:String(a);e.errors.push(ar(`wrong-arity`,`${t.name}() takes ${n} argument(s) but got ${t.args.length}`,`Usage: ${t.name}(${[...i.params,...i.rest?[i.rest]:[]].map(e=>e.name).join(`, `)})`,t.span));return}let o=t.args.map((t,r)=>ci(e,i.params[r]??i.rest,t,n));if(!o.some(e=>e===void 0))return{call:{...t,args:o},returns:i.returns??`boolean`}},ui=(e,t,n)=>{if(e===`timestamp`&&t===`duration`)return`timestamp`;if(e===`timestamp`&&t===`timestamp`&&n===`-`||e===`duration`&&t===`duration`)return`duration`;if((e===`integer`||e===`number`)&&(t===`integer`||t===`number`))return e===`integer`&&t===`integer`?`integer`:`number`},di={number:`number`,boolean:`boolean`,duration:`duration`,timestamp:`timestamp`},fi=(e,t)=>{switch(t.kind){case`call`:{let n=li(e,t,fi);return n&&{node:n.call,type:n.returns}}case`binary`:{let n=fi(e,t.left),r=fi(e,t.right);if(!n||!r)return;let i=n.type&&r.type?ui(n.type,r.type,t.op):n.type??r.type??`number`;if(!i){e.errors.push(ar(`invalid-value`,`Cannot apply "${t.op}" to ${n.type} and ${r.type}`,`Add a duration to a timestamp, or combine numbers`,t.span));return}return{node:{...t,left:n.node,right:r.node},type:i}}case`number`:case`boolean`:case`duration`:case`timestamp`:return{node:t,type:di[t.kind]};default:return{node:t,type:void 0}}},pi=[`string`,`integer`,`number`,`timestamp`,`duration`,`any`],mi=(e,t)=>{if(t.kind===`member`){let n=ei(e,t);return n&&{node:n,type:n.field.spec.type,spec:n.field.spec}}let n=fi(e,t);return n&&{...n,spec:void 0}},hi=(e,t,n,r)=>{e.errors.push(ar(`operator-not-allowed`,t,n,r.span))},gi=(e,t,n)=>{if(!t.type)return fi(e,n)?.node;let r=fi(e,n);if(!r)return;let i=r.type&&(n.kind===`call`||n.kind===`binary`)?ai(t.type,r.type)?void 0:{message:`Expected ${t.type} but got ${r.type}`,hint:`Compare values of the same type`}:oi(t.type,t.spec,r.node);return i&&e.errors.push(ar(`invalid-value`,i.message,i.hint,n.span)),i?void 0:r.node},_i=(e,t)=>{let n=mi(e,t.left);if(!n)return;let r=n.type;if(n.spec?.repeated)return hi(e,`"${t.op}" is not supported on repeated fields`,`Use field:value to test membership`,t);if(r===`map`||r===`message`)return hi(e,`${r} fields cannot be compared`,`Use field:key, or compare a nested field`,t);if(r&&![`=`,`!=`].includes(t.op)&&!pi.includes(r))return hi(e,`"${t.op}" is not supported for ${r} fields`,`Supported: = !=`,t);let i=(t.op===`=`||t.op===`!=`)&&t.right.kind===`string`&&t.right.value.includes(`*`);if(i&&r&&r!==`string`&&r!==`any`){e.errors.push(ar(`wildcard-not-allowed`,`Wildcards are only supported on string fields, not ${r}`,`Remove the "*"`,t.right.span));return}let a=i?t.right:gi(e,n,t.right);return a&&{...t,left:n.node,right:a}},vi=(e,t)=>{let n=mi(e,t.left);if(!n)return;let{type:r,spec:i}=n,a=gi(e,!i?.repeated&&(r===`map`||r===`message`)?{...n,type:`string`}:n,t.right);return a&&{...t,left:n.node,right:a}},yi=(e,t)=>{switch(t.kind){case`sequence`:case`and`:case`or`:{let n=t.args.map(t=>yi(e,t));return n.every(e=>e)?{...t,args:n}:void 0}case`not`:{let n=yi(e,t.arg);return n&&{...t,arg:n}}case`compare`:return _i(e,t);case`has`:return vi(e,t);case`present`:{let n=mi(e,t.left);return n&&{...t,left:n.node}}case`global`:return t;case`call`:{let n=li(e,t,fi);if(n&&n.returns!==`boolean`){e.errors.push(ar(`not-boolean`,`${t.name}() returns ${n.returns}, not a condition`,`Compare its result: f(x) > 1`,t.span));return}return n?.call}}},bi=(e,t)=>{let n={schema:t,errors:[]},r=yi(n,e);return!r||n.errors.length>0?{ok:!1,errors:[...n.errors].sort((e,t)=>e.span.start-t.span.start)}:{ok:!0,ast:r}},xi={"\\":`\\\\`,'"':`\\"`,"\n":`\\n`,"\r":`\\r`," ":`\\t`,"\x07":`\\a`,"\b":`\\b`,"\f":`\\f`,"\v":`\\v`},Si=e=>{if(!e.isWellFormed())throw Error(`Strings with unpaired surrogates cannot be printed`);return`"${e.replace(/[\\"\u0000-\u001f\u007f-\u009f]/g,e=>xi[e]??`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`},Ci=e=>{switch(e.kind){case`string`:return Si(e.value);case`number`:return e.raw;case`boolean`:return String(e.value);case`duration`:return`${e.amount}${e.unit}`;case`timestamp`:return e.value}},wi=e=>e.kind===`number`&&e.raw.startsWith(`-`),Ti=e=>{switch(e.kind){case`member`:return e.path.join(`.`);case`call`:return`${e.name}(${e.args.map(Ei).join(`, `)})`;case`binary`:if(e.right.kind===`binary`)throw Error(`Arithmetic is left-associative; a binary on the right cannot be printed`);return`${Ti(e.left)} ${e.op} ${Ti(e.right)}`;default:return Ci(e)}},Ei=e=>Oi(e)?`(${ji(e)})`:Ti(e),Di=[`member`,`string`,`number`,`boolean`,`duration`,`timestamp`,`binary`],Oi=e=>!Di.includes(e.kind)&&e.kind!==`call`,ki=e=>{if(wi(e))throw Error(`A negative number cannot start a comparison; "-5 = x" parses as a negation`);return Ti(e)},Ai=(e,t)=>({and:[`and`,`or`],sequence:[`and`,`or`,`sequence`],or:[`and`,`or`,`sequence`],not:[`and`,`or`,`sequence`,`not`]})[e].includes(t.kind)?`(${ji(t)})`:ji(t),ji=e=>{switch(e.kind){case`and`:return e.args.map(e=>Ai(`and`,e)).join(` AND `);case`or`:return e.args.map(e=>Ai(`or`,e)).join(` OR `);case`sequence`:return e.args.map(e=>Ai(`sequence`,e)).join(` `);case`not`:return`NOT ${Ai(`not`,e.arg)}`;case`compare`:return`${ki(e.left)} ${e.op} ${Ti(e.right)}`;case`has`:return`${ki(e.left)}:${Ti(e.right)}`;case`present`:return`${ki(e.left)}:*`;case`global`:return Ti(e.value);case`call`:return Ti(e)}},Mi=class{int;scale;constructor(e,t){this.int=e,this.scale=t}compare(e){let t=Math.max(this.scale,e.scale),n=this.int*10n**BigInt(t-this.scale),r=e.int*10n**BigInt(t-e.scale);return n<r?-1:+(n>r)}toNumber(){return Number(`${this.int}e-${this.scale}`)}},Ni=/^(-?)(\d+)(?:\.(\d+))?$/,Pi=e=>{let t=Ni.exec(e);if(!t)return;let n=t[3]??``;return new Mi(BigInt(`${t[1]}${t[2]}${n}`),n.length)},Fi=/^-?(?:\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|0[xX][0-9a-fA-F]+)$/,Ii=e=>{if(typeof e==`number`)return e;if(typeof e==`bigint`)return Number(e);if(e instanceof Mi)return e.toNumber();if(typeof e==`string`&&Fi.test(e))return e.startsWith(`-`)?-Number(e.slice(1)):Number(e)},Li=e=>typeof e==`bigint`?new Mi(e,0):typeof e==`number`?Number.isFinite(e)?Pi(String(e)):void 0:typeof e==`string`?Pi(e):e instanceof Mi?e:void 0,Ri=(e,t)=>{let n=0,r=0,i=-1,a=0;for(;r<t.length;)if(n<e.length&&e[n]===`*`)i=n++,a=r;else if(n<e.length&&e[n]===t[r])n++,r++;else if(i>=0)n=i+1,r=++a;else return!1;for(;e[n]===`*`;)n++;return n===e.length},zi=e=>typeof e==`object`&&!!e&&!(e instanceof Date)&&!(e instanceof Mi)&&`seconds`in e&&typeof e.seconds==`number`,Bi=e=>{switch(e.kind){case`string`:return e.value;case`number`:return Pi(e.raw)??e.value;case`boolean`:return e.value;case`duration`:return{seconds:e.amount*fr[e.unit]};case`timestamp`:return new Date(pr(e.value)??NaN)}},Vi=e=>zi(e)?e.seconds:typeof e==`number`?e:typeof e==`string`?hr(e):void 0,Hi=e=>e instanceof Date?e.getTime():typeof e==`string`?pr(e):void 0,Ui=e=>{switch(e.kind){case`string`:return e.value;case`member`:return e.path.join(`.`);case`number`:return e.raw;case`boolean`:return String(e.value);case`duration`:return`${e.amount}${e.unit}`;case`timestamp`:return e.value;default:return}},Wi=(e,t)=>{switch(e){case`=`:return t===0;case`!=`:return t!==0;case`<`:return t<0;case`<=`:return t<=0;case`>`:return t>0;case`>=`:return t>=0}},Gi=(e,t)=>e<t?-1:+(e>t),Ki=(e,t)=>{let n=Li(e),r=Li(t);if(n&&r)return n.compare(r);let i=Ii(e),a=Ii(t);return i===void 0||a===void 0||Number.isNaN(i)||Number.isNaN(a)?void 0:Gi(i,a)},qi=(e,t,n)=>{let r=(e===`=`||e===`!=`)&&n.includes(`*`);if(typeof t==`string`)return r?Wi(e,+!Ri(n,t)):Wi(e,Gi(t,n));if(typeof t==`number`||typeof t==`bigint`){let r=Ki(t,n);return r===void 0?void 0:Wi(e,r)}if(t instanceof Date){let r=Hi(n);return r===void 0?void 0:Wi(e,Gi(t.getTime(),r))}if(typeof t==`boolean`)return n===`true`||n===`false`?Wi(e,Gi(String(t),n)):void 0;if(zi(t)){let r=Vi(n);return r===void 0?void 0:Wi(e,Gi(t.seconds,r))}},Ji=(e,t,n)=>{if(t==null)return!1;if(typeof n==`string`)return qi(e,t,n)??!1;if(n instanceof Mi||typeof n==`number`||typeof n==`bigint`){let r=Ki(t,n);return r!==void 0&&Wi(e,r)}if(typeof n==`boolean`){let r=typeof t==`string`?t===`true`||t!==`false`&&void 0:t;return typeof r==`boolean`&&Wi(e,Gi(String(r),String(n)))}if(n instanceof Date){let r=Hi(t);return r===void 0||Number.isNaN(n.getTime())?!1:Wi(e,Gi(r,n.getTime()))}if(zi(n)){let r=Vi(t);return r!==void 0&&Wi(e,Gi(r,n.seconds))}return!1},Yi=(e,t)=>{let n=[e];for(let e of t)n=n.flatMap(t=>Array.isArray(t)?t.flatMap(t=>Xi(t,e)):Xi(t,e));return n.filter(e=>e!=null)},Xi=(e,t)=>typeof e!=`object`||!e?[]:e instanceof Map?e.has(t)?[e.get(t)]:[]:Object.hasOwn(e,t)?[e[t]]:[],Zi=e=>e.flatMap(e=>Array.isArray(e)?e:[e]),Qi=32,$i=(e,t)=>t>Qi||e==null?[]:typeof e==`string`?[e]:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?[String(e)]:e instanceof Date?[e.toISOString()]:Array.isArray(e)?e.flatMap(e=>$i(e,t+1)):e instanceof Map?[...e.values()].flatMap(e=>$i(e,t+1)):typeof e==`object`?Object.values(e).flatMap(e=>$i(e,t+1)):[],ea=(e,t)=>{let n=e.toLowerCase();return $i(t,0).some(e=>e.toLowerCase().includes(n))},ta=e=>[`member`,`string`,`number`,`boolean`,`duration`,`timestamp`,`call`,`binary`].includes(e.kind),na=(e,t,n)=>{let r=e===`+`?1:-1;if(t instanceof Date&&zi(n))return new Date(t.getTime()+r*n.seconds*1e3);if(t instanceof Date&&n instanceof Date&&e===`-`)return{seconds:(t.getTime()-n.getTime())/1e3};if(zi(t)&&zi(n))return{seconds:t.seconds+r*n.seconds};let i=t instanceof Mi?t.toNumber():t,a=n instanceof Mi?n.toNumber():n;return typeof i==`number`&&typeof a==`number`?i+r*a:void 0},ra=(e,t)=>{let n=t.options.functions?.[e.name];if(!n?.evaluate)throw Error(`Function "${e.name}" has no evaluate implementation`);let r=e.args.map((e,r)=>{let i=n.params[r]??n.rest;return e.kind===`member`&&i?.type===`field`?Zi(Yi(t.record,e.path)):ta(e)?ia(e,t):ua(e,t)});return n.evaluate(...r)},ia=(e,t)=>{switch(e.kind){case`member`:return e.path.join(`.`);case`call`:return ra(e,t);case`binary`:return na(e.op,ia(e.left,t),ia(e.right,t));default:return Bi(e)}},aa=(e,t)=>e.kind===`member`?Yi(t.record,e.path):[ia(e,t)],oa=(e,t,n)=>Zi(t).some(t=>Ji(e,t,n)),sa=(e,t)=>{let n=e.kind===`member`?e.field?.spec.type:void 0;return typeof t!=`string`||!n?t:n===`timestamp`?Hi(t)===void 0?t:new Date(Hi(t)):n===`duration`?Vi(t)===void 0?t:{seconds:Vi(t)}:n===`integer`||n===`number`?Li(t)??t:n===`boolean`?t===`true`||t!==`false`&&t:t},ca=(e,t)=>{let n=sa(e.left,ia(e.right,t)),r=aa(e.left,t);return e.op===`!=`?!oa(`=`,r,n):oa(e.op,r,n)},la=(e,t)=>{let n=ia(e.right,t),r=Ui(e.right);return aa(e.left,t).some(e=>Array.isArray(e)?e.some(e=>Ji(`=`,e,n)):e instanceof Map?r!==void 0&&e.has(r):typeof e==`object`&&e&&!(e instanceof Date)&&!zi(e)&&!(e instanceof Mi)?r!==void 0&&Object.hasOwn(e,r):Ji(`=`,e,n))},ua=(e,t)=>{switch(e.kind){case`sequence`:case`and`:return e.args.every(e=>ua(e,t));case`or`:return e.args.some(e=>ua(e,t));case`not`:return!ua(e.arg,t);case`compare`:return ca(e,t);case`has`:return la(e,t);case`present`:return aa(e.left,t).some(e=>e!=null);case`global`:return(t.options.search??ea)(Ui(e.value)??String(ia(e.value,t)),t.record);case`call`:return ra(e,t)===!0}},da=(e,t,n={})=>ua(e,{record:t,options:n}),fa=(e,t,n,r)=>({code:e,message:t,hint:n,span:r}),pa=(e,t)=>{let n=Array.from({length:t.length+1},(e,t)=>t);for(let r=1;r<=e.length;r++){let i=[r];for(let a=1;a<=t.length;a++){let o=e[r-1]===t[a-1]?0:1;i[a]=Math.min(n[a]+1,i[a-1]+1,n[a-1]+o)}n=i}return n[t.length]},ma=(e,t)=>{let n=e.toLowerCase(),r=t.map(e=>({candidate:e,score:pa(n,e.toLowerCase())})).sort((e,t)=>e.score-t.score)[0];return r&&r.score<=Math.max(2,Math.floor(e.length/3))?r.candidate:void 0},ha={in:{params:[{name:`field`,type:`field`}],rest:{name:`value`,type:`any`}},search:{params:[{name:`text`,type:`string`}]},similar:{params:[{name:`field`,type:`field`,of:[`string`]},{name:`text`,type:`string`}]},regex:{params:[{name:`field`,type:`field`,of:[`string`]},{name:`pattern`,type:`string`}]},isNull:{params:[{name:`field`,type:`field`}]},now:{params:[],returns:`timestamp`}},ga={extensions:{arithmetic:`now-offset`,durationUnits:!0}},_a=e=>{switch(e.type){case`text`:return`string`;case`integer`:case`bigint`:return`integer`;case`boolean`:case`timestamp`:case`enum`:return e.type;default:return`any`}},va=e=>({fields:Object.fromEntries(Object.values(e.fields).map(e=>[e.name,{type:_a(e),filterable:e.filterable,sortable:e.sortable,aliases:e.aliases,...e.enumValues&&{values:e.enumValues}}])),functions:ha}),ya=(e,t,n,r)=>{e.errors.push(fa(`unsupported`,t,n,r))},ba=(e,t)=>t.kind===`member`?{kind:`field`,path:t.path,span:t.span}:ya(e,`Only fields can be compared`,`Put a field name on the left, for example total > 100`,t.span),yee=(e,t)=>{switch(t.kind){case`member`:return{kind:`string`,value:t.path.join(`.`),span:t.span};case`call`:return t.name===`now`&&t.args.length===0?{kind:`now`,span:t.span}:ya(e,`${t.name}() cannot be used as a value`,`Only now() is a value function`,t.span);case`binary`:{let n=t.left;return n.kind===`call`&&n.name===`now`&&n.args.length===0&&t.right.kind===`duration`?{kind:`now`,offset:{sign:t.op,duration:t.right},span:t.span}:ya(e,`Arithmetic is only supported as now() +/- duration`,`Write now() - 30d`,t.span)}default:return t}},xa=(e,t)=>(`kind`in t&&[`member`,`call`,`binary`].includes(t.kind)?void 0:t)||(t.kind===`member`?{kind:`string`,value:t.path.join(`.`),span:t.span}:ya(e,`Expected a literal value`,`Use strings, numbers, true/false, durations or timestamps`,t.span)),bee=e=>{switch(e.kind){case`member`:return e.path.join(`.`);case`string`:case`timestamp`:return e.kind,e.value;case`number`:return e.raw;case`boolean`:return String(e.value);case`duration`:return`${e.amount}${e.unit}`;default:return``}},xee=(e,t)=>{let[n,r,...i]=t.args,a=n?.kind===`member`?ba(e,n):void 0,o=e=>e?.kind===`string`?e.value:void 0,s=n=>{e.errors.push(fa(`invalid-arguments`,`Invalid arguments to ${t.name}()`,`Usage: ${n}`,t.span))};switch(t.name){case`in`:{let n=t.args.slice(1).map(t=>xa(e,t));return!a||n.length===0?s(`in(field, value1, value2, ...)`):n.every(e=>e)?{kind:`in`,field:a,values:n,span:t.span}:void 0}case`search`:return o(n)!==void 0&&!r?{kind:`search`,text:o(n),span:t.span}:s(`search("text")`);case`similar`:return a&&o(r)!==void 0&&i.length===0?{kind:`similar`,field:a,text:o(r),span:t.span}:s(`similar(field, "text")`);case`regex`:return a&&o(r)!==void 0&&i.length===0?{kind:`regex`,field:a,pattern:o(r),span:t.span}:s(`regex(field, "pattern")`);case`isNull`:return a&&!r?{kind:`isNull`,field:a,span:t.span}:s(`isNull(field)`);default:e.errors.push(fa(`unknown-function`,`Unknown function "${t.name}"`,`Available functions: ${Object.keys(ha).join(`, `)}`,t.span));return}},See=e=>e.every(e=>e)?e:void 0,Sa=(e,t)=>{switch(t.kind){case`sequence`:case`and`:case`or`:{let n=See(t.args.map(t=>Sa(e,t)));return n&&{kind:t.kind===`or`?`or`:`and`,args:n,span:t.span}}case`not`:{let n=Sa(e,t.arg);return n&&{kind:`not`,arg:n,span:t.span}}case`compare`:{let n=ba(e,t.left),r=yee(e,t.right);return n&&r&&{kind:`compare`,op:t.op,field:n,value:r,span:t.span}}case`has`:{let n=ba(e,t.left),r=xa(e,t.right);return n&&r&&{kind:`has`,field:n,value:r,span:t.span}}case`present`:{let n=ba(e,t.left);return n&&{kind:`present`,field:n,span:t.span}}case`global`:return{kind:`search`,text:bee(t.value),span:t.span};case`call`:return xee(e,t)}},Ca=(e,t={})=>{let n=Qr(e,{...ga,...t}),r={errors:[]},i=n.ast&&Sa(r,n.ast),a=[...n.errors,...r.errors].sort((e,t)=>e.span.start-t.span.start);return a.length===0?{ok:!0,ast:i,errors:[]}:{ok:!1,ast:i,errors:a}},Cee=(e,t)=>t===2?e%4==0&&(e%100!=0||e%400==0)?29:28:[4,6,9,11].includes(t)?30:31,wa=e=>{let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return!1;let[n,r,i]=[Number(t[1]),Number(t[2]),Number(t[3])];return r>=1&&r<=12&&i>=1&&i<=Cee(n,r)},wee=e=>{let t=/^(\d{4}-\d{2}-\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))$/.exec(e);if(!t)return!1;let[n,r,i]=[Number(t[2]),Number(t[3]),Number(t[4])],[a,o]=[Number(t[5]??0),Number(t[6]??0)];return wa(t[1])&&n<=23&&r<=59&&i<=59&&a<=23&&o<=59},Ta=(e,t)=>({message:e,hint:t}),Tee=-(2n**63n),Eee=2n**63n-1n,Dee=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ea=e=>e.kind===`number`?e.raw:e.kind===`string`?e.value:void 0,Da=(e,t=`Write ${e} values like the examples in the docs`)=>Ta(`Expected ${e}`,t),Oee=e=>{let t=Ea(e),n=t===void 0?NaN:Number(t);if(t===void 0||t.trim()===``||!Number.isSafeInteger(n))return Da(`a whole number`,`Use an integer such as 42, or a bigint field for larger values`)},kee=e=>{let t=Ea(e);if(t===void 0||!/^-?\d+$/.test(t)||BigInt(t)<Tee||BigInt(t)>Eee)return Da(`a 64-bit integer`,`Use plain digits such as 9007199254740993 (no exponent or fraction)`)},Aee=e=>{let t=Ea(e);if(t===void 0||!/^-?\d+(\.\d+)?$/.test(t))return Da(`a decimal number`,`Use plain digits such as 100.50, or quote it: "100.50" (no exponent)`)},jee=(e,t)=>{if(t.kind===`now`)return e.type===`date`||e.type===`timestamp`?void 0:Ta(`now() only works with date and timestamp fields`,`Field "${e.name}" is ${e.type}`);switch(e.type){case`text`:return t.kind===`string`?void 0:Da(`a quoted string`,`Wrap the text in double quotes`);case`integer`:return Oee(t);case`bigint`:return kee(t);case`decimal`:return Aee(t);case`boolean`:return t.kind===`boolean`?void 0:Da(`true or false`);case`date`:return t.kind===`string`&&wa(t.value)?void 0:Da(`a date`,`Quote a calendar date: "2012-04-21"`);case`timestamp`:return t.kind===`timestamp`||t.kind===`string`&&wee(t.value)?void 0:Da(`an RFC-3339 timestamp`,`Use 2012-04-21T11:30:00Z, or now() - 7d`);case`uuid`:return t.kind===`string`&&Dee.test(t.value)?void 0:Da(`a uuid`,`Quote a uuid like "0b5a4f0e-6f2a-4a3c-9d4e-1f2a3b4c5d6e"`);case`enum`:return t.kind===`string`&&e.enumValues?.includes(t.value)?void 0:Ta(`Invalid enum value`,`Allowed values: ${(e.enumValues??[]).join(`, `)}`);case`currency`:return t.kind===`string`&&/^[A-Z]{3}$/.test(t.value)?void 0:Da(`an ISO 4217 currency code`,`Use three capital letters, for example "EUR"`);case`country`:return t.kind===`string`&&/^[A-Z]{2}$/.test(t.value)?void 0:Da(`an ISO 3166-1 country code`,`Use two capital letters, for example "NL"`);case`relation`:return t.kind===`string`||t.kind===`number`&&Number.isSafeInteger(t.value)?void 0:Da(`a record key`,`Use the related record key: 42 or "abc"`);case`json`:case`file`:return Ta(`${e.type} fields cannot be compared`,`Use field:value on json fields, or isNull(field)`)}},Mee=(e,t)=>Object.hasOwn(e.fields,t)?e.fields[t]:Object.values(e.fields).find(e=>e.aliases.includes(t)),Oa=(e,t,n)=>{if(t.path.length>1){e.errors.push(fa(`unsupported-traversal`,`Traversal into "${t.path.join(`.`)}" is not supported yet`,`Filter on fields of this resource only`,t.span));return}let r=t.path[0],i=Mee(e.model,r);if(!i){let i=Object.values(e.model.fields).filter(e=>e[n]).map(e=>e.name),a=ma(r,i);e.errors.push(fa(`unknown-field`,`Unknown field "${r}"`,a?`Did you mean "${a}"?`:`Available fields: ${i.join(`, `)}`,t.span));return}if(!i[n]){let r=n===`filterable`?`filterable`:`sortable`;e.errors.push(fa(n===`filterable`?`not-filterable`:`not-sortable`,`Field "${i.name}" is not ${r}`,`Mark it with .${r}() in data.ts`,t.span));return}return i},Nee=[`=`,`!=`],Pee=[`=`,`!=`,`<`,`<=`,`>`,`>=`],Fee=e=>{switch(e){case`text`:case`integer`:case`bigint`:case`decimal`:case`date`:case`timestamp`:return Pee;case`json`:case`file`:return[];default:return Nee}},Iee=e=>e===`json`||e===`file`,ka=(e,t,n)=>{let r=jee(t,n);return r&&e.errors.push(fa(`invalid-value`,r.message,r.hint,n.span)),!r},Aa=(e,t,n,r)=>{e.errors.push(fa(`operator-not-allowed`,t,n,r))},ja=(e,t)=>(e===`=`||e===`!=`)&&t.kind===`string`&&t.value.includes(`*`),Lee=(e,t)=>{let n=Oa(e,t.field,`filterable`);if(!n)return;let r=Fee(n.type);if(!r.includes(t.op)){Aa(e,`Operator "${t.op}" is not supported for ${n.type} fields`,r.length?`Supported: ${r.join(` `)}`:`Use field:value on json fields, or isNull(field)`,t.span);return}if(ja(t.op,t.value)&&n.type!==`text`){e.errors.push(fa(`wildcard-not-allowed`,`Wildcards are only supported on text fields, not ${n.type}`,`Remove the "*" or filter a text field`,t.value.span));return}if(ja(t.op,t.value)||ka(e,n,t.value))return{...t,field:n}},Ree=(e,t)=>{let n=Oa(e,t.field,`filterable`);if(n){if(n.type!==`json`){Aa(e,`":" is only supported on json fields, not ${n.type}`,`Use = on ${n.type} fields, or field:* to test for a value`,t.span);return}return{...t,field:n}}},zee=(e,t)=>{let n=Oa(e,t.field,`filterable`);if(n){if(Iee(n.type)){Aa(e,`in() is not supported for ${n.type} fields`,`Use field:value on json fields`,t.span);return}return t.values.map(t=>ka(e,n,t)).every(Boolean)?{...t,field:n}:void 0}},Bee=(e,t,n)=>{let r=Oa(e,n,`filterable`);if(r&&r.type!==`text`){Aa(e,`${t}() only works on text fields, not ${r.type}`,`Field "${r.name}" is ${r.type}`,n.span);return}return r},Ma=(e,t)=>{switch(t.kind){case`and`:case`or`:{let n=t.args.map(t=>Ma(e,t));return n.every(e=>e)?{...t,args:n}:void 0}case`not`:{let n=Ma(e,t.arg);return n&&{...t,arg:n}}case`compare`:return Lee(e,t);case`has`:return Ree(e,t);case`in`:return zee(e,t);case`search`:if(e.model.search?.length)return t;e.errors.push(fa(`no-search-fields`,`This resource has no search fields`,`Declare them with .search((r) => [r.title]) in data.ts`,t.span));return;case`present`:case`isNull`:{let n=Oa(e,t.field,`filterable`);return n&&{...t,field:n}}case`similar`:case`regex`:{let n=Bee(e,t.kind,t.field);return n&&{...t,field:n}}}},Na=(e,t)=>{let n={model:e,errors:[]},r=Ma(n,t);return!r||n.errors.length>0?{ok:!1,errors:[...n.errors].sort((e,t)=>e.span.start-t.span.start)}:{ok:!0,filter:r}},Pa=(e,t)=>`path`in e?{kind:`member`,path:e.path,span:e.span}:{kind:`member`,path:[e.name],field:{name:e.name,spec:{type:_a(e)}},span:t},Fa=(e,t,n)=>({kind:`call`,name:e,args:t,span:n}),Ia=(e,t)=>({kind:`string`,value:e,span:t}),Vee=e=>{if(e.kind!==`now`)return e;let t={kind:`call`,name:`now`,args:[],span:e.span};return e.offset?{kind:`binary`,op:e.offset.sign,left:t,right:e.offset.duration,span:e.span}:t},La=(e,t={})=>{let n=e=>La(e,t);switch(e.kind){case`and`:case`or`:return{kind:e.kind,args:e.args.map(n),span:e.span};case`not`:return{kind:`not`,arg:n(e.arg),span:e.span};case`compare`:return{kind:`compare`,op:e.op,left:Pa(e.field,e.span),right:Vee(e.value),span:e.span};case`has`:return{kind:`has`,left:Pa(e.field,e.span),right:e.value,span:e.span};case`present`:return{kind:`present`,left:Pa(e.field,e.span),span:e.span};case`in`:return t.expand?{kind:`or`,args:e.values.map(t=>({kind:`compare`,op:`=`,left:Pa(e.field,e.span),right:t,span:e.span})),span:e.span}:Fa(`in`,[Pa(e.field,e.span),...e.values],e.span);case`search`:return Fa(`search`,[Ia(e.text,e.span)],e.span);case`similar`:return Fa(`similar`,[Pa(e.field,e.span),Ia(e.text,e.span)],e.span);case`regex`:return Fa(`regex`,[Pa(e.field,e.span),Ia(e.pattern,e.span)],e.span);case`isNull`:return t.expand?{kind:`not`,arg:{kind:`present`,left:Pa(e.field,e.span),span:e.span},span:e.span}:Fa(`isNull`,[Pa(e.field,e.span)],e.span)}},Ra=(e,t)=>{let n=Na(e,t);if(!n.ok&&n.errors.some(e=>e.code===`unsupported-traversal`))return n;let r=bi(La(t),va(e));return r.ok?Na(e,t):{ok:!1,errors:r.errors}},za=/^[\d\s+\-().\/]+$/,Ba=e=>za.test(e)?e.replace(/\D/g,``):``,Va=e=>{let t=e.split(/\s+/).filter(Boolean).map(e=>({text:e,digits:Ba(e),whole:!1})),n=t.length>1?Ba(e.trim()):``;return n?[{text:e.trim(),digits:n,whole:!0},...t]:t},Ha=(e,t,n)=>e==null?!1:n===`digitsEnd`?t.digits!==``&&String(e).replace(/\D/g,``).endsWith(t.digits):!t.whole&&String(e).toLowerCase().includes(t.text.toLowerCase()),Ua=(e,t,n)=>(e.search??[]).filter(r=>Ha(t[r],n,e.searchMatch?.[r])),Wa=(e,t,n)=>{let r=Va(n),i=r.filter(e=>!e.whole),a=r.find(e=>e.whole);return a&&Ua(e,t,a).length>0?!0:i.length>0&&i.every(n=>Ua(e,t,n).length>0)},Ga=(e,t,n,r)=>{for(let i of Va(n)){let n=Ua(e,t,i);if(n.length>0&&!n.some(e=>r.includes(e)))return n[0]}},Ka=e=>()=>{throw Error(`Not implemented: ${e}() needs the database (the resource's search fields, trigram matching), so it cannot be evaluated against a record`)},qa=(e,t,n)=>({...ha,search:{...ha.search,evaluate:n?e=>Wa(n,t,e):Ka(`search`)},similar:{...ha.similar,evaluate:Ka(`similar`)},regex:{...ha.regex,evaluate:(e,t)=>e.some(e=>typeof e==`string`&&new RegExp(t).test(e))},now:{...ha.now,evaluate:e}}),Ja=(e,t,n={})=>da(La(e,{expand:!0}),t,{functions:qa(n.now??(()=>new Date),t,n.search)}),Ya=e=>ji(La(e)),Xa=e=>{let t=[];for(let n of e.matchAll(/,|\.|[^\s,.]+/g)){let e=n.index,r=n[0]===`,`?`comma`:n[0]===`.`?`dot`:`word`;t.push({kind:r,text:n[0],span:{start:e,end:e+n[0].length}})}return t},Za=e=>{let t=Xa(e),n=[],r=[],i={start:e.length,end:e.length},a=0,o=(e,t,r,i)=>n.push(ar(e,t,r,i)),s=()=>{for(;a<t.length&&t[a].kind!==`comma`;)a++;a++},c=()=>{let e=t[a];if(!e||e.kind!==`word`)return o(`expected-field`,`Expected a field name but found ${e?`"${e.text}"`:`end of input`}`,`Write order_by like: createdAt desc, total`,e?.span??i),!1;let n=[e.text],s=e;for(a++;t[a]?.kind===`dot`;){let e=t[a+1];if(e?.kind!==`word`)return o(`expected-field`,`Expected a field name after "."`,`Write subfields like address.street`,e?.span??i),!1;n.push(e.text),s=e,a+=2}let c=t[a],l=`asc`;if(c?.kind===`word`){if(c.text!==`asc`&&c.text!==`desc`)return o(`unexpected-token`,`Expected "desc" or "," but found "${c.text}"`,`Separate fields with commas; append " desc" for descending order`,c.span),!1;l=c.text,s=c,a++}let u=t[a];return u&&u.kind!==`comma`?(o(`unexpected-token`,`Expected "," but found "${u.text}"`,`Separate fields with commas`,u.span),!1):(r.push({path:n,direction:l,span:{start:e.span.start,end:s.span.end}}),!0)};for(;a<t.length;){if(!c()){s();continue}t[a]?.kind===`comma`&&(a++,a>=t.length&&o(`expected-field`,`Expected a field name after ","`,`Remove the trailing comma`,i))}return n.length===0?{ok:!0,items:r,errors:[]}:{ok:!1,items:r,errors:n}},Qa=(e,t)=>{if(Object.hasOwn(e,t))return{name:t,field:e[t]};let n=Object.entries(e).find(([,e])=>e.aliases?.includes(t));return n&&{name:n[0],field:n[1]}},$a=(e,t)=>{let n=[],r=[];for(let i of e){let e=Qa(t.fields,i.path[0]);if(!e){let e=Object.entries(t.fields).filter(([,e])=>e.sortable!==!1).map(([e])=>e),r=sr(i.path[0],e);n.push(ar(`unknown-field`,`Unknown field "${i.path[0]}"`,r?`Did you mean "${r}"?`:`Available fields: ${e.join(`, `)}`,i.span));continue}let a=[e.name],o=e.field,s=o.sortable!==!1,c=!1;for(let e of i.path.slice(1)){let t=o.fields?Qa(o.fields,e)?.field:o.value;if(!t){n.push(ar(`invalid-traversal`,`Cannot sort by "${e}" inside "${a.join(`.`)}"`,`Only nested message fields and map values can be traversed`,i.span)),c=!0;break}a.push(o.fields?Qa(o.fields,e).name:e),o=t,s&&=o.sortable!==!1}if(!c){if(!s){n.push(ar(`not-sortable`,`Field "${a.join(`.`)}" cannot be sorted on`,`Mark it sortable in the schema`,i.span));continue}r.push({...i,path:a})}}return n.length===0?{ok:!0,items:r}:{ok:!1,errors:n}},eo=e=>e.map(e=>({path:e.path.path,direction:e.direction,span:e.span})),to=e=>e.replace(/([^\s,])(\s+)(asc|desc)(?=\s|,|$)/gi,(e,t,n,r)=>`${t}${n}${r.toLowerCase()}`),no=e=>{let t=Za(to(e)),n=t.items.map(e=>({path:{kind:`field`,path:e.path,span:e.span},direction:e.direction,span:e.span}));return t.ok?{ok:!0,items:n,errors:[]}:{ok:!1,items:n,errors:t.errors}},ro=(e,t)=>{let n=t.filter(e=>e.path.path.length>1).map(e=>fa(`unsupported-traversal`,`Traversal into "${e.path.path.join(`.`)}" is not supported yet`,`Sort on fields of this resource only`,e.path.span));if(n.length>0)return{ok:!1,errors:n};let r=$a(eo(t),va(e));return r.ok?{ok:!0,sort:r.items.map(e=>[e.path[0],e.direction])}:{ok:!1,errors:r.errors}},io=e=>{let t=/^(\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)([smhdw])$/.exec(e);if(!t)throw Error(`Invalid duration "${e}", expected for example 30d or 1.5h`);return{kind:`duration`,amount:Number(t[1]),unit:t[2],span:{start:0,end:0}}},ao={start:0,end:0},oo=e=>({kind:`field`,path:e.split(`.`),span:ao}),so=e=>{if(typeof e==`string`)return{kind:`string`,value:e,span:ao};if(typeof e==`boolean`)return{kind:`boolean`,value:e,span:ao};if(!Number.isFinite(e))throw Error(`Filter numbers must be finite`);return{kind:`number`,value:e,raw:String(e),span:ao}},co=e=>typeof e==`object`?e:so(e),lo=(e,t)=>{if(t.length===0)throw Error(`where.${e} needs at least one filter`);return t.length===1?t[0]:{kind:e,args:t,span:ao}},uo=()=>{let e=e=>(t,n)=>({kind:`compare`,op:e,field:oo(t),value:co(n),span:ao}),t=e=>t=>({kind:`now`,offset:{sign:e,duration:io(t)},span:ao});return{eq:e(`=`),ne:e(`!=`),lt:e(`<`),lte:e(`<=`),gt:e(`>`),gte:e(`>=`),between:(t,n,r)=>lo(`and`,[e(`>=`)(t,n),e(`<=`)(t,r)]),has:(e,t)=>({kind:`has`,field:oo(e),value:so(t),span:ao}),present:e=>({kind:`present`,field:oo(e),span:ao}),in:(e,t)=>({kind:`in`,field:oo(e),values:t.map(so),span:ao}),isNull:e=>({kind:`isNull`,field:oo(e),span:ao}),search:e=>({kind:`search`,text:e,span:ao}),similar:(e,t)=>({kind:`similar`,field:oo(e),text:t,span:ao}),regex:(e,t)=>({kind:`regex`,field:oo(e),pattern:t,span:ao}),and:(...e)=>lo(`and`,e),or:(...e)=>lo(`or`,e),not:e=>({kind:`not`,arg:e,span:ao}),now:()=>({kind:`now`,span:ao}),ago:t(`-`),fromNow:t(`+`)}},fo=uo(),po=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===1&&typeof e.$field==`string`,mo=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ho=e=>po(e)?e.$field:Array.isArray(e)?e.map(ho):mo(e)?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,ho(t)])):e,go=`table`,_o={text:`text`,integer:`integer`,decimal:`decimal`,boolean:`boolean`,date:`date`,choice:`text`,custom:`json`},vo=e=>({name:e.name,column:e.name,type:e.options?`enum`:_o[e.kind],nullable:!0,readOnly:!1,filterable:e.kind!==`custom`,sortable:!1,aliases:[],...e.options&&{enumValues:e.options.map(e=>e.value)}}),yo=e=>({name:`inputs`,table:{name:`inputs`},fields:Object.fromEntries(e.map(e=>[e.name,vo(e)])),primaryKey:[]}),bo=(e,t)=>{let n=e[t].when;if(n===void 0)return;let r=Ca(n);if(!r.ok)return r.errors.map(e=>e.message).join(`; `);if(!r.ast)return`it is empty`;let i=Ra(yo(e.slice(0,t)),r.ast);return i.ok?i.filter:i.errors.map(e=>e.message).join(`; `)},xo=(e,t)=>{let n=new Set,r={};return e.forEach((i,a)=>{let o=bo(e,a);if(typeof o==`string`)throw Error(`Input "${i.name}": ${o}`);let s=o===void 0||Ja(o,r)===!0;s&&n.add(i.name),r[i.name]=s?t[i.name]??null:null}),n},So=/\{([A-Za-z_][A-Za-z0-9_]*)\}/g,Co=e=>[...e.matchAll(So)].map(e=>e[1]),wo=e=>e.kind===`record`?(Array.isArray(e.key)?e.key:[e.key]).filter(e=>typeof e==`string`):e.kind===`list`?[e.filter,e.orderBy].filter(e=>e!==void 0):e.kind===`create`?Object.values(e.values??{}):[],To=e=>[...new Set(wo(e).flatMap(Co))],Eo=(e,t)=>e.replace(So,(e,n)=>t[n]===null||t[n]===void 0?``:String(t[n])),Do=(e,t={})=>{if(e.kind===`record`){let n=e=>typeof e==`string`?Eo(e,t):e;return{...e,key:Array.isArray(e.key)?e.key.map(n):n(e.key)}}return e.kind===`create`?e.values?{...e,values:Object.fromEntries(Object.entries(e.values).map(([e,n])=>[e,Eo(n,t)]))}:e:e.kind===`list`?{...e,...e.filter!==void 0&&{filter:Eo(e.filter,t)},...e.orderBy!==void 0&&{orderBy:Eo(e.orderBy,t)}}:e},Oo=e=>/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e)?.[1],ko=e=>`groupBy`in e,Ao=e=>{if(!Array.isArray(e))return String(e);let t=e;return t.length===1?String(t[0]):t.map(e=>encodeURIComponent(String(e))).join(`,`)},jo=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/,Mo=e=>{let t=jo.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:void 0},No=(e,t)=>e[0]-t[0]||e[1]-t[1]||e[2]-t[2],Po=/^(>=|<=|>|<|=)?(.+)$/,Fo={">=":e=>e>=0,"<=":e=>e<=0,">":e=>e>0,"<":e=>e<0,"=":e=>e===0},Io=(e,t)=>{let n=Mo(e),r=t.trim().split(/\s+/);if(!n||t.trim()===``)return;let i=!0;for(let e of r){let[,t=`=`,r=``]=Po.exec(e)??[],a=Mo(r);if(!a)return;i&&=Fo[t](No(n,a))}return i},Lo=(e,t)=>{if(e.api!==t.api)return`it is built for plugin API ${e.api}, and this app has plugin API ${t.api}`;let n=Io(t.version,e.protobase);if(n===void 0)return`its Protobase range "${e.protobase}" is not one this app reads, such as >=0.12.0`;if(!n)return`it needs Protobase ${e.protobase}, and this app runs ${t.version}`},Ro=`[Filtered]`,zo=/authorization|cookie|passw|secret|token|api[-_]?key|credential|session|csrf|signature|^sig$/i,Bo=new Set([`url`,`query_string`,`from`,`to`]),Vo=12,Ho=e=>e.replace(/(^|&)([^=&]*)=([^&]*)/g,(e,t,n)=>zo.test(n)?`${t}${n}=${Ro}`:e),Uo=e=>{let t=e.indexOf(`?`);if(t===-1)return e;let n=e.indexOf(`#`,t),r=n===-1?e.slice(t+1):e.slice(t+1,n);return`${e.slice(0,t+1)}${Ho(r)}${n===-1?``:e.slice(n)}`},Wo=(e,t,n)=>zo.test(e)?Ro:typeof t==`string`&&Bo.has(e)?e===`query_string`?Ho(t):Uo(t):Go(t,n+1),Go=(e,t)=>t>Vo||typeof e!=`object`||!e?e:Array.isArray(e)?e.map(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`?[e[0],Wo(e[0],e[1],t)]:Go(e,t+1)):Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Wo(e,n,t)])),Ko=e=>Go(e,0),qo=[`unknown-field`,`not-filterable`,`not-sortable`,`unsupported-traversal`,`invalid-traversal`],Jo=e=>e.replace(/(["']?)\{[A-Za-z_][A-Za-z0-9_]*\}\1/g,(e,t)=>t?`${t}x${t}`:`0`),Yo=(e,t)=>{let n=Ca(Jo(t));if(!n.ok)return n.errors.map(e=>`filter: ${e.message}`);if(!n.ast)return[];let r=Ra(e,n.ast);return r.ok?[]:r.errors.filter(e=>qo.includes(e.code)).map(e=>`filter: ${e.message}`)},Xo=(e,t)=>{if(To({kind:`list`,resource:e.name,orderBy:t}).length>0)return[];let n=no(t);if(!n.ok)return n.errors.map(e=>`orderBy: ${e.message}`);let r=ro(e,n.items);return r.ok?[]:r.errors.map(e=>`orderBy: ${e.message}`)},Zo=(e,{models:t,pages:n,source:r})=>{let i=To(e).flatMap(e=>r?Object.hasOwn(r.fields,e)?[]:[`"{${e}}" is not a field of ${r.name}`]:[`"{${e}}" takes a value from the record, but the link sits on none`]);switch(e.kind){case`page`:return n&&!n.has(e.page)?[`unknown page "${e.page}"`]:[];case`list`:case`record`:case`create`:{let n=Object.hasOwn(t,e.resource)?t[e.resource]:void 0;return n?e.kind===`create`?[...i,...Object.keys(e.values??{}).filter(e=>!Object.hasOwn(n.fields,e)).map(t=>`values: unknown field "${t}" on ${e.resource}`)]:e.kind===`list`?[...i,...e.filter?Yo(n,e.filter):[],...e.orderBy?Xo(n,e.orderBy):[]]:i:[`unknown resource "${e.resource}"`]}default:return[`an address's kind is list, record, create or page, not "${String(e.kind)}"`]}},Qo={messages:[],replying:!1},$o=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);return n===-1?[...e,t]:e.map((e,r)=>r===n?t:e)},es=(e,t,n)=>{let r=e.find(e=>e.id===t);return $o(e,r?{...r,parts:$o(r.parts,n)}:{id:t,from:`assistant`,parts:[n]})},ts=(e,t)=>{switch(t.type){case`state`:return t.state;case`message`:return{...e,messages:$o(e.messages,t.message)};case`part`:return{...e,messages:es(e.messages,t.messageId,t.part)};case`patch`:{let{replying:n=e.replying,status:r=e.status,placeholder:i=e.placeholder}=t;return{messages:e.messages,replying:n,...r!=null&&{status:r},...i!=null&&{placeholder:i}}}}},ns=async(e,t,n)=>{let r=new TextDecoder,i=e.getReader();n?.addEventListener(`abort`,()=>void i.cancel(),{once:!0});let a=``,o=[],s=e=>{if(e===``){o.length>0&&t(o.join(`
|
|
4
|
-
`)),o=[];return}e.startsWith(`data:`)&&o.push(e.slice(e.startsWith(`data: `)?6:5))};for(;;){let{done:e,value:t}=await i.read();a+=e?r.decode():r.decode(t,{stream:!0});let n=a.split(/\r\n|\r|\n/);if(a=e?``:n.pop()??``,n.forEach(s),e)return s(``)}},rs=(e,t)=>t?.[e]??e,is={filter:`filter`,orderBy:`order_by`,display:`display`,filterLayout:`layout`,map:`map`,savedSearch:`saved_search`,create:`new`,edit:`edit`},as=[`display`,`filter`,`orderBy`,`filterLayout`,`savedSearch`],os=e=>`${e.latitude.toFixed(5)},${e.longitude.toFixed(5)},${e.zoom.toFixed(2)}`,ss=(e,t,n=-t)=>Number.isFinite(e)&&e>=n&&e<=t,cs=e=>{let t=e?.split(`,`);if(t?.length!==3||t.some(e=>e.trim()===``))return;let[n,r,i]=t.map(Number);return ss(n,90)&&ss(r,180)&&ss(i,22,0)?{latitude:n,longitude:r,zoom:i}:void 0},ls=e=>{let t=new URLSearchParams;for(let n of as){let r=e[n];r!==void 0&&r!==``&&t.set(is[n],r)}e.map&&t.set(is.map,os(e.map));let n=t.toString();return n?`?${n}`:``},us=(e,t=``)=>{switch(e.kind){case`page`:return`${t}/${encodeURIComponent(e.page)}`;case`create`:return`${t}/${encodeURIComponent(e.resource)}/${is.create}${fs(e.values)}`;case`record`:return`${t}/${encodeURIComponent(e.resource)}/${encodeURIComponent(Ao(e.key))}${e.edit?`?${is.edit}=true`:``}`;case`list`:return`${t}/${encodeURIComponent(e.resource)}${ls(e)}`}},ds=e=>{try{return e.split(`/`).filter(Boolean).map(decodeURIComponent)}catch(e){if(e instanceof URIError)return;throw e}},fs=(e={})=>{let t=new URLSearchParams(Object.entries(e).filter(([,e])=>e!==``)).toString();return t?`?${t}`:``},ps=e=>e===`bar`||e===`panel`?e:void 0,ms=(e,t)=>{let n=new URL(e,`http://app`),r=ds(n.pathname);if(!r||r.length===0||r.length>2)return;let[i,a]=r;if(i===`-`)return;if(t.has(i))return a===void 0?{kind:`page`,page:i}:void 0;if(a===is.create){let e=Object.fromEntries([...n.searchParams].filter(([,e])=>e!==``));return{kind:`create`,resource:i,...Object.keys(e).length>0&&{values:e}}}if(a!==void 0)return{kind:`record`,resource:i,key:a,...n.searchParams.get(is.edit)===`true`&&{edit:!0}};let o=n.searchParams,s=o.get(is.display)||void 0,c=o.get(is.filter)||void 0,l=o.get(is.orderBy)||void 0,u=ps(o.get(is.filterLayout)),d=cs(o.get(is.map)),f=o.get(is.savedSearch)||void 0;return{kind:`list`,resource:i,...s&&{display:s},...c&&{filter:c},...l&&{orderBy:l},...u&&{filterLayout:u},...d&&{map:d},...f&&{savedSearch:f}}},hs=`/-/sign-in`,gs={step:`step`,next:`next`},_s=[`sign-in`,`forgot-password`,`email-code`,`sign-up`,`sign-up-code`,`sign-up-details`],vs=e=>_s.includes(e),ys=e=>{if(!e?.startsWith(`/`))return;let t=new URL(e,`http://local`);if(t.origin===`http://local`&&t.pathname!==`/-/sign-in`)return`${t.pathname}${t.search}`},bs=({step:e=`sign-in`,next:t}={})=>{let n=new URLSearchParams;e!==`sign-in`&&n.set(gs.step,e);let r=ys(t);r&&r!==`/`&&n.set(gs.next,r);let i=n.toString();return i?`${hs}?${i}`:hs},xs=(e,t)=>{if(e!==`/-/sign-in`)return;let n=t.get(gs.step),r=ys(t.get(gs.next));return{step:vs(n)?n:`sign-in`,...r&&{next:r}}},Ss=e=>typeof e==`string`?e:e&&Ya(e),Cs=e=>{let t=Object.entries(e??{}).map(([e,t])=>`${e}.${t}`);return t.length>0?t:void 0},ws=e=>({photos:e&&`${e.resource}.${e.field}.${e.image}`,photos_order_by:e?.sort}),Ts=(e={})=>({filter:Ss(e.filter)||void 0,order_by:e.orderBy,page_size:e.pageSize,page_token:e.pageToken||void 0,fields:e.fields?.join(`,`),labels:Cs(e.labels)?.join(`,`),...ws(e.photos),count:e.count}),Es=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))r!==void 0&&t.set(n,String(r));let n=t.toString();return n?`?${n}`:``},Ds=e=>e.startsWith(`/`)&&!e.startsWith(`//`),Os=e=>{if(typeof e!=`object`||!e)return!1;let{uri:t,url:n}=e;return typeof t==`string`&&typeof n==`string`&&Ds(n)},ks=e=>e!==void 0&&URL.canParse(e)?new URL(e).origin:void 0,As=(e,t)=>({...e,url:`${t}${e.url}`,...e.variants&&{variants:Object.fromEntries(Object.entries(e.variants).map(([e,n])=>[e,Ds(n.url)?{...n,url:`${t}${n.url}`}:n]))}}),js=(e,t)=>t===void 0||typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Os(n)?As(n,t):n])),Ms=(e,t)=>t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,n.map(e=>Os(e)?As(e,t):e)])),Ns=class extends Error{problem;constructor(e){super(e.detail??e.title),this.problem=e,this.name=`ApiError`}get status(){return this.problem.status}get slug(){return this.problem.type.split(`:`).at(-1)??``}get operation(){return this.problem.operation??this.errors.find(e=>e.operation!==void 0)?.operation}get blockedBy(){return this.problem.blockedBy}get errors(){return this.problem.errors??[]}get filterErrors(){return this.slug===`invalid-filter`?this.errors:[]}},Ps=class extends Ns{constructor(e){super(e),this.name=`PreconditionFailedError`}},Fs=e=>e instanceof Ns,Is=e=>typeof e==`object`&&!!e&&`type`in e&&`status`in e,Ls=async e=>{let t=e.headers.get(`content-type`)?.includes(`json`)??!1?await e.json():void 0,n=Is(t)?t:{type:`urn:protobase:problem:unknown`,title:e.statusText||`Request failed`,status:e.status};return n.status===412?new Ps(n):new Ns(n)},Rs=(e={})=>{let t=e.baseUrl??`/api/v1`,n=t.replace(/\/[^/]*$/,``),r=e.fetch??((e,t)=>fetch(e,t));return async({method:i,path:a,query:o=``,body:s,headers:c,accept:l=[],system:u,raw:d,via:f,signal:p})=>{let m=async l=>{let m=await e.token?.({refresh:l});return(f??r)(`${u?n:t}${a}${o}`,{method:i,headers:{...s!==void 0&&{"content-type":`application/json`},...m&&{authorization:`Bearer ${m}`},...e.headers?.(),...c},body:d??(s===void 0?void 0:JSON.stringify(s)),...p&&{signal:p}})},h=await m(!1);h.status===401&&e.token&&(h=await m(!0),h.status===401&&e.onUnauthenticated?.());let g=h.headers.get(`x-meta-version`);if(g&&e.onMetaVersion?.(g),!h.ok&&!l.includes(h.status))throw await Ls(h);return h}},zs=e=>new Headers(e.trim().split(/[\r\n]+/).filter(Boolean).map(e=>{let t=e.indexOf(`:`);return[e.slice(0,t).trim(),e.slice(t+1).trim()]})),Bs=e=>(t,n={})=>new Promise((r,i)=>{let a=new XMLHttpRequest;a.open(n.method??`GET`,String(t)),new Headers(n.headers).forEach((e,t)=>a.setRequestHeader(t,e)),a.responseType=`blob`,a.upload.onprogress=t=>e(t.loaded,t.lengthComputable?t.total:t.loaded),a.onload=()=>{let e=a.status===204||a.status===304;r(new Response(e?null:a.response,{status:a.status,statusText:a.statusText,headers:zs(a.getAllResponseHeaders())}))},a.onerror=()=>i(TypeError(`Network request failed`)),a.onabort=()=>i(new DOMException(`The upload was aborted`,`AbortError`)),n.signal?.addEventListener(`abort`,()=>a.abort()),a.send(n.body)}),Vs=e=>typeof e==`string`?e:e.toModel().name,Hs=(e,t)=>`/${Vs(e)}/${Ao(t)}`,Us=(e,t,n)=>({items:e.items.map(e=>js(e,n)),nextPageToken:e.next_page_token,totalSizeEstimate:e.total_size_estimate,...e.prev_page_token!==void 0&&{prevPageToken:e.prev_page_token},...e.total_size!==void 0&&{totalSize:e.total_size},...e.labels!==void 0&&{labels:e.labels},...e.photos!==void 0&&{photos:Ms(e.photos,n)},...t.headers.get(`x-protobase-warning`)&&{warning:t.headers.get(`x-protobase-warning`)}}),Ws=e=>e.headers.get(`etag`)??``,Gs=async(e,t)=>{let{permissions:n,...r}=await e.json();return{record:js(r,t),etag:Ws(e),...n&&{permissions:n}}},Ks=(e,t)=>({results:(e.results??[]).map(e=>e.op===`create`||e.op===`update`?{...e,record:js(e.record,t)}:e.op===`reorder`?{...e,records:e.records.map(e=>({...e,record:js(e.record,t)}))}:e)}),qs=(e={})=>{let t=Rs(e),n=ks(e.baseUrl);return{list:async(e,r)=>{let i=await t({method:`GET`,path:`/${Vs(e)}`,query:Es(Ts(r))});return Us(await i.json(),i,n)},search:async(e,r)=>{let i=Ts(r),a=await t({method:`POST`,path:`/${Vs(e)}:search`,body:{...i,fields:r?.fields,labels:Cs(r?.labels)}});return Us(await a.json(),a,n)},get:async(e,r)=>Gs(await t({method:`GET`,path:Hs(e,r)}),n),create:async(e,r)=>{let i=await t({method:`POST`,path:`/${Vs(e)}`,body:r});return{record:js(await i.json(),n),etag:Ws(i),location:i.headers.get(`location`)??``}},update:async(e,r,i,a)=>Gs(await t({method:`PATCH`,path:Hs(e,r),body:i,headers:{"if-match":a}}),n),remove:async(e,n,{etag:r}={})=>{await t({method:`DELETE`,path:Hs(e,n),headers:r?{"if-match":r}:void 0})},undelete:async(e,r)=>{let i=await t({method:`POST`,path:`${Hs(e,r)}:undelete`});return{record:js(await i.json(),n),etag:Ws(i)}},reveal:async(e,n,r)=>(await(await t({method:`POST`,path:`${Hs(e,n)}:reveal`,body:{field:r}})).json()).value,history:async(e,n,{pageSize:r,pageToken:i}={})=>{let a=Es({page_size:r,page_token:i||void 0}),o=await(await t({method:`GET`,path:`${Hs(e,n)}:history`,query:a})).json();return{items:o.items.map(({database_role:e,...t})=>({...t,databaseRole:e})),nextPageToken:o.next_page_token}},batchWrite:async e=>{let r=e=>typeof e==`object`&&e&&`$ref`in e?e:Ao(e),i=e.map(e=>({...e,resource:Vs(e.resource),...`key`in e&&{key:r(e.key)},...e.op===`reorder`&&{keys:e.keys.map(r)}}));return Ks(await(await t({method:`POST`,path:`:batchWrite`,body:{ops:i}})).json(),n)},facets:async(e,n,r={})=>(await(await t({method:`GET`,path:`/${Vs(e)}:facets`,query:Es({field:n,filter:Ss(r.filter)||void 0,limit:r.limit,label:r.label})})).json()).facets,aggregate:async(e,n)=>{let r=await(await t({method:`GET`,path:`/${Vs(e)}:aggregate`,query:Es({group_by:n.groupBy,filter:Ss(n.filter)||void 0,sum:n.sum,average:n.average,limit:n.limit,label:n.label,granularity:n.granularity,range:n.range,from:n.from,to:n.to,time_zone:n.timeZone})})).json();return{groupBy:r.group_by,granularity:r.granularity,timeZone:r.time_zone,groups:r.groups}},series:async(e,n)=>{let r=await(await t({method:`GET`,path:`/${Vs(e)}:series`,query:Es({field:n.field,range:n.range,from:n.from,to:n.to,granularity:n.granularity,time_zone:n.timeZone,filter:Ss(n.filter)||void 0})})).json();return{field:r.field,granularity:r.granularity,timeZone:r.time_zone,points:r.points}},histogram:async(e,n,r={})=>(await t({method:`GET`,path:`/${Vs(e)}:histogram`,query:Es({field:n,buckets:r.buckets,filter:Ss(r.filter)||void 0})})).json(),map:async(e,r)=>{let i=await(await t({method:`GET`,path:`/${Vs(e)}:map`,query:Es({latitude:r.latitude,longitude:r.longitude,zoom:r.zoom,filter:Ss(r.filter)||void 0,order_by:r.orderBy,fields:r.fields?.join(`,`),labels:Cs(r.labels)?.join(`,`),...ws(r.photos)})})).json();return{items:i.items.map(e=>js(e,n)),buckets:i.buckets,totalSize:i.total_size,...i.labels!==void 0&&{labels:i.labels},...i.photos!==void 0&&{photos:Ms(i.photos,n)}}},seek:async(e,r)=>{let i=await t({method:`GET`,path:`/${Vs(e)}:seek`,query:Es({...Ts(r),position:r.position})});return Us(await i.json(),i,n)},meta:async(e,{signal:n}={})=>{let r=await t({method:`GET`,path:`/meta`,system:!0,headers:e?{"if-none-match":e}:void 0,accept:[304],...n&&{signal:n}});return r.status===304?{status:`unchanged`}:{status:`modified`,meta:await r.json(),etag:Ws(r)}},invoke:async(e,{method:n,body:r,path:i=``,query:a,headers:o}={})=>{let s=await t({method:n??(r===void 0?`GET`:`POST`),path:`/functions/${encodeURIComponent(e)}${i}`,query:a?`?${new URLSearchParams(a)}`:``,body:r,headers:o,system:!0});if(s.status!==204)return s.headers.get(`content-type`)?.includes(`json`)?s.json():s.text()},upload:async(e,n,r,{onProgress:i,signal:a}={})=>{let o=`name`in r&&typeof r.name==`string`?r.name:void 0,s=i&&typeof XMLHttpRequest<`u`?Bs(i):void 0,c=await(await t({method:`POST`,path:`/${Vs(e)}:upload`,query:`?${new URLSearchParams({field:n,...o!==void 0&&{name:o}})}`,raw:r,headers:{"content-type":r.type||`application/octet-stream`},...s&&{via:s},...a&&{signal:a}})).json();return i?.(r.size,r.size),c}}},Js=e=>typeof e==`string`?e:e.toModel().name,Ys=(e,t)=>{let n=n=>t(Js(n))??e;return{list:(e,t)=>n(e).list(e,t),search:(e,t)=>n(e).search(e,t),get:(e,t)=>n(e).get(e,t),create:(e,t)=>n(e).create(e,t),update:(e,t,r,i)=>n(e).update(e,t,r,i),remove:(e,t,r)=>n(e).remove(e,t,r),undelete:(e,t)=>n(e).undelete(e,t),reveal:(e,t,r)=>n(e).reveal(e,t,r),history:(e,t,r)=>n(e).history(e,t,r),batchWrite:t=>{let r=[...new Set(t.map(e=>n(e.resource)))];return r.length>1?Promise.reject(Error(`A batch writes to one API, but these writes are for ${[...new Set(t.map(e=>Js(e.resource)))].join(`, `)}, which different APIs serve`)):(r[0]??e).batchWrite(t)},facets:(e,t,r)=>n(e).facets(e,t,r),aggregate:(e,t)=>n(e).aggregate(e,t),series:(e,t)=>n(e).series(e,t),histogram:(e,t,r)=>n(e).histogram(e,t,r),map:(e,t)=>n(e).map(e,t),seek:(e,t)=>n(e).seek(e,t),meta:(t,n)=>e.meta(t,n),invoke:(t,n)=>e.invoke(t,n),upload:(e,t,r,i)=>n(e).upload(e,t,r,i)}},Xs=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.type==`string`&&Array.isArray(e.children),Zs=e=>typeof e==`object`&&!!e&&e.kind===`member`,Qs=e=>Zs(e)?[e.path.join(`.`)]:typeof e!=`object`||!e?[]:Object.values(e).flatMap(Qs),$s=e=>Zs(e)?{...e,path:[e.path.join(`.`)]}:Array.isArray(e)?e.map($s):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,$s(t)])),ec=e=>{let t=Qr(e);return t.ok?t.ast?{ok:!0,ast:t.ast,paths:[...new Set(Qs(t.ast))]}:{ok:!1,message:`the condition is empty`}:{ok:!1,message:t.errors.map(e=>e.message).join(`; `)}},tc=(e,t)=>e.ast!==void 0&&da($s(e.ast),t),nc=(e,t)=>{let[n,r,...i]=e.split(`.`);return n&&r===`count`&&i.length===0&&!t(n)?n:void 0},rc=(e,t,n)=>{let r=[],i=e[t],a=n.split(`.`);for(let[o,s]of a.entries()){if(!i)return{ok:!1,message:`unknown resource "${t}"`};let c=Object.hasOwn(i.fields,s)?i.fields[s]:void 0;if(!c)return{ok:!1,message:`unknown field "${a.slice(0,o+1).join(`.`)}" on ${i.name}`};if(r.push({model:i,field:c}),o===a.length-1)break;if(c.type!==`relation`||!c.relation)return{ok:!1,message:`"${a.slice(0,o+1).join(`.`)}" is not a relation, so "${n}" cannot go through it`};t=c.relation.resource,i=e[t]}return{ok:!0,steps:r}},ic=(e,t)=>({...e,fields:Object.fromEntries(Object.entries(e.fields).map(([e,n])=>{if(!n.relation||Object.hasOwn(t,n.relation.resource))return[e,n];let{relation:r,...i}=n;return[e,i]}))}),ac=(e,t)=>{if(e.kind!==`related`)return[e];if(!Object.hasOwn(t,e.resource)||e.through&&!Object.hasOwn(t,e.through.resource))return[];let{columns:n,...r}=e,i=n?.filter(n=>rc(t,e.resource,n).ok);return[i&&i.length>0?{...r,columns:i}:r]},oc=(e,t,n)=>e.run?.kind!==`link`||!(`to`in e.run)||Zo(e.run.to,{models:n,pages:new Set,source:t}).length===0,sc=(e,t)=>({...e,layout:e.layout.flatMap(e=>ac(e,t)),actions:e.actions.filter(n=>oc(n,t[e.resource],t))}),cc=(e,t)=>{let n=e.resources.filter(e=>t.resources.includes(e.name)),r=Object.fromEntries(n.map(e=>[e.name,e])),i=n.map(e=>ic(e,r)),a=Object.fromEntries(i.map(e=>[e.name,e]));return{resources:i,views:e.views.filter(e=>Object.hasOwn(a,e.resource)).map(e=>sc(e,a)),permissions:Object.fromEntries(n.flatMap(t=>e.permissions?.[t.name]?[[t.name,e.permissions[t.name]]]:[]))}},lc=class extends Error{status;code;constructor(e,t,n){super(e),this.status=t,this.code=n,this.name=`AuthError`}},uc=(e,t)=>new lc(e?.message||t,e?.status??500,e?.code),dc=e=>({signInMethods:async()=>{let{data:t,error:n}=await e.$fetch(`/account/sign-in-methods`);if(n||!t)throw uc(n,`Could not read your sign-in methods`);return t},passkeys:async()=>{let{data:t,error:n}=await e.passkey.listUserPasskeys();if(n||!t)throw uc(n,`Could not read your passkeys`);return t.map(e=>({id:e.id,backedUp:e.backedUp,...e.name&&{name:e.name},...e.createdAt&&{createdAt:new Date(e.createdAt).toISOString()}}))},addPasskey:async t=>{let{error:n}=await e.passkey.addPasskey(t?{name:t}:{});if(n)throw uc(n,`Could not add the passkey`)},renamePasskey:async(t,n)=>{let{error:r}=await e.passkey.updatePasskey({id:t,name:n});if(r)throw uc(r,`Could not rename the passkey`)},removePasskey:async t=>{let{error:n}=await e.passkey.deletePasskey({id:t});if(n)throw uc(n,`Could not remove the passkey`)},startAuthenticatorApp:async t=>{let{data:n,error:r}=await e.twoFactor.enable({method:`totp`,...t&&{password:t}});if(r||n?.method!==`totp`)throw uc(r,`Could not start two-factor authentication`);return{totpURI:n.totpURI,backupCodes:n.backupCodes}},confirmAuthenticatorApp:async t=>{let{error:n}=await e.twoFactor.verifyTotp({code:t});if(n)throw uc(n,`The code did not work`)},turnOnEmailedCodes:async t=>{let{error:n}=await e.twoFactor.enable({method:`otp`,...t&&{password:t}});if(n)throw uc(n,`Could not turn on two-factor authentication`)},turnOffTwoFactor:async t=>{let{error:n}=await e.twoFactor.disable(t?{password:t}:{});if(n)throw uc(n,`Could not turn off two-factor authentication`)},linkedProviders:async()=>{let{data:t,error:n}=await e.listAccounts();if(n||!t)throw uc(n,`Could not read your linked accounts`);return[...new Set(t.map(e=>e.providerId).filter(e=>e!==`credential`))]},linkProvider:async(t,n)=>{let{data:r,error:i}=await e.linkSocial({provider:t,callbackURL:n,errorCallbackURL:n,disableRedirect:!0});if(i||!r?.url)throw uc(i,`Could not start linking the account`);return r.url},newBackupCodes:async t=>{let{data:n,error:r}=await e.twoFactor.generateBackupCodes(t?{password:t}:{});if(r||!n)throw uc(r,`Could not make new backup codes`);return n.backupCodes}});function fc(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}var pc=fc({CHALLENGE_NOT_FOUND:`Challenge not found`,YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY:`You are not allowed to register this passkey`,FAILED_TO_VERIFY_REGISTRATION:`Failed to verify registration`,PASSKEY_NOT_FOUND:`Passkey not found`,AUTHENTICATION_FAILED:`Authentication failed`,UNABLE_TO_CREATE_SESSION:`Unable to create session`,USER_NOT_FOUND:`User not found`,FAILED_TO_UPDATE_PASSKEY:`Failed to update passkey`,PREVIOUSLY_REGISTERED:`Previously registered`,REGISTRATION_CANCELLED:`Registration cancelled`,AUTH_CANCELLED:`Auth cancelled`,UNKNOWN_ERROR:`Unknown error`,SESSION_REQUIRED:`Passkey registration requires an authenticated session`,RESOLVE_USER_REQUIRED:`Passkey registration requires either an authenticated session or a resolveUser callback when requireSession is false`,RESOLVED_USER_INVALID:`Resolved user is invalid`}),mc=`1.7.7`;function hc(e){let t=new Uint8Array(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function gc(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=(4-t.length%4)%4,r=t.padEnd(t.length+n,`=`),i=atob(r),a=new ArrayBuffer(i.length),o=new Uint8Array(a);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);return a}function _c(){return vc.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential==`function`)}var vc={stubThis:e=>e};function yc(e){let{id:t}=e;return{...e,id:gc(t),transports:e.transports}}function bc(e){return e===`localhost`||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(e)}var xc=class extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r??n.name,this.code=t}};function Sc({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new xc({message:`Registration ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`ConstraintError`){if(n.authenticatorSelection?.requireResidentKey===!0)return new xc({message:`Discoverable credentials were required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT`,cause:e});if(t.mediation===`conditional`&&n.authenticatorSelection?.userVerification===`required`)return new xc({message:`User verification was required during automatic registration but it could not be performed`,code:`ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE`,cause:e});if(n.authenticatorSelection?.userVerification===`required`)return new xc({message:`User verification was required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT`,cause:e})}else if(e.name===`InvalidStateError`)return new xc({message:`The authenticator was previously registered`,code:`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`,cause:e});else if(e.name===`NotAllowedError`)return new xc({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`NotSupportedError`)return n.pubKeyCredParams.filter(e=>e.type===`public-key`).length===0?new xc({message:`No entry in pubKeyCredParams was of type "public-key"`,code:`ERROR_MALFORMED_PUBKEYCREDPARAMS`,cause:e}):new xc({message:`No available authenticator supported any of the specified pubKeyCredParams algorithms`,code:`ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!bc(t))return new xc({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rp.id!==t)return new xc({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`TypeError`){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new xc({message:`User ID was not between 1 and 64 characters`,code:`ERROR_INVALID_USER_ID_LENGTH`,cause:e})}else if(e.name===`UnknownError`)return new xc({message:`The authenticator was unable to process the specified options, or could not create a new credential`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}var Cc=new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let e=Error(`Cancelling existing WebAuthn API call for new one`);e.name=`AbortError`,this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error(`Manually cancelling existing WebAuthn API call`);e.name=`AbortError`,this.controller.abort(e),this.controller=void 0}}},wc=[`cross-platform`,`platform`];function Tc(e){if(e&&!(wc.indexOf(e)<0))return e}async function Ec(e){!e.optionsJSON&&e.challenge&&(console.warn(`startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useAutoRegister:n=!1}=e;if(!_c())throw Error(`WebAuthn is not supported in this browser`);let r={...t,challenge:gc(t.challenge),user:{...t.user,id:gc(t.user.id)},excludeCredentials:t.excludeCredentials?.map(yc)},i={};n&&(i.mediation=`conditional`),i.publicKey=r,i.signal=Cc.createNewAbortSignal();let a;try{a=await navigator.credentials.create(i)}catch(e){throw Sc({error:e,options:i})}if(!a)throw Error(`Registration was not completed`);let{id:o,rawId:s,response:c,type:l}=a,u;typeof c.getTransports==`function`&&(u=c.getTransports());let d;if(typeof c.getPublicKeyAlgorithm==`function`)try{d=c.getPublicKeyAlgorithm()}catch(e){Dc(`getPublicKeyAlgorithm()`,e)}let f;if(typeof c.getPublicKey==`function`)try{let e=c.getPublicKey();e!==null&&(f=hc(e))}catch(e){Dc(`getPublicKey()`,e)}let p;if(typeof c.getAuthenticatorData==`function`)try{p=hc(c.getAuthenticatorData())}catch(e){Dc(`getAuthenticatorData()`,e)}return{id:o,rawId:hc(s),response:{attestationObject:hc(c.attestationObject),clientDataJSON:hc(c.clientDataJSON),transports:u,publicKeyAlgorithm:d,publicKey:f,authenticatorData:p},type:l,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:Tc(a.authenticatorAttachment)}}function Dc(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}function Oc(){if(!_c())return kc.stubThis(new Promise(e=>e(!1)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?kc.stubThis(new Promise(e=>e(!1))):kc.stubThis(e.isConditionalMediationAvailable())}var kc={stubThis:e=>e};function Ac({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new xc({message:`Authentication ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`NotAllowedError`)return new xc({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!bc(t))return new xc({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rpId!==t)return new xc({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`UnknownError`)return new xc({message:`The authenticator was unable to process the specified options, or could not create a new assertion signature`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}async function jc(e){!e.optionsJSON&&e.challenge&&(console.warn(`startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useBrowserAutofill:n=!1,verifyBrowserAutofillInput:r=!0}=e;if(!_c())throw Error(`WebAuthn is not supported in this browser`);let i;t.allowCredentials?.length!==0&&(i=t.allowCredentials?.map(yc));let a={...t,challenge:gc(t.challenge),allowCredentials:i},o={};if(n){if(!await Oc())throw Error(`Browser does not support WebAuthn autofill`);if(document.querySelectorAll(`input[autocomplete$='webauthn']`).length<1&&r)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');o.mediation=`conditional`,a.allowCredentials=[]}o.publicKey=a,o.signal=Cc.createNewAbortSignal();let s;try{s=await navigator.credentials.get(o)}catch(e){throw Ac({error:e,options:o})}if(!s)throw Error(`Authentication was not completed`);let{id:c,rawId:l,response:u,type:d}=s,f;return u.userHandle&&(f=hc(u.userHandle)),{id:c,rawId:hc(l),response:{authenticatorData:hc(u.authenticatorData),clientDataJSON:hc(u.clientDataJSON),signature:hc(u.signature),userHandle:f},type:d,clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:Tc(s.authenticatorAttachment)}}var Mc=`1.7.7`,Nc=Symbol.for(`better-auth:broadcast-channel`),Pc=()=>Math.floor(Date.now()/1e3),Fc=class{listeners=new Set;name;constructor(e=`better-auth.message`){this.name=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}post(e){if(typeof window<`u`)try{localStorage.setItem(this.name,JSON.stringify({...e,timestamp:Pc()}))}catch{}}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=e=>{if(e.key!==this.name)return;let t=JSON.parse(e.newValue??`{}`);t?.event===`session`&&t?.data&&this.listeners.forEach(e=>e(t))};return window.addEventListener(`storage`,e),()=>{window.removeEventListener(`storage`,e)}}};function Ic(e=`better-auth.message`){return globalThis[Nc]||(globalThis[Nc]=new Fc(e)),globalThis[Nc]}var Lc=[],Rc=0,zc=null,Bc=4,Hee=globalThis.nanostoresGlobal||={epoch:0},Uee=()=>{let e,t;for(;Rc<Lc.length;){t=Rc,Rc+=Bc;let n=zc?.get(Lc[t]);if(n){if(!n.has(Lc[t+1]))continue;n.clear()}try{Lc[t](Lc[t+1].value,Lc[t+2],Lc[t+3])}catch(t){e=t}}if(Lc.length=Rc=0,e)throw e},Vc=e=>{let t=[],n={eq:Object.is,get(){return n.lc||n.listen(()=>{})(),n.value},init:e,lc:0,listen(e){return n.lc=t.push(e),()=>{zc?.get(e)?.delete(n);for(let t=Rc;t<Lc.length;)Lc[t]===e&&Lc[t+1]===n?Lc.splice(t,Bc):t+=Bc;let r=t.indexOf(e);~r&&(t.splice(r,1),--n.lc||n.off())}},notify(e,r){Hee.epoch++;let i=!Lc.length&&!0;for(let i of t)Lc.push(i,n,e,r);i&&Uee()},off(){},set(e){let t=n.value;n.eq(t,e)||(n.value=e,n.notify(t))},subscribe(e){let t=n.listen(e);return e(n.value),t},value:e};return n},Wee=2,Gee=5,Hc=6,Uc=10,Wc=(e,t,n,r)=>(e.events=e.events||{},e.events[n+Uc]||(e.events[n+Uc]=r(t=>{e.events[n].reduceRight((e,t)=>(t(e),e),{shared:{},...t})})),e.events[n]=e.events[n]||[],e.events[n].push(t),()=>{let r=e.events[n],i=r.indexOf(t);~i&&(r.splice(i,1),r.length||(e.events[n+Uc](),delete e.events[n+Uc]))}),Kee=(e,t)=>Wc(e,t,Wee,t=>{let n=e.set,r=e.setKey;return e.setKey&&=(n,i)=>{let a;if(t({abort:()=>{a=!0},changed:n,newValue:{...e.value,[n]:i}}),!a)return r(n,i)},e.set=e=>{let r;if(t({abort:()=>{r=!0},newValue:e}),!r)return n(e)},()=>{e.set=n,e.setKey=r}}),Gc=1e3,Kc=(e,t)=>Wc(e,n=>{let r=t(n);r&&e.events[Hc].push(r)},Gee,t=>{let n=e.listen;e.listen=(...r)=>(!e.lc&&!e.active&&(e.active=!0,t()),n(...r));let r=e.off;return e.events[Hc]=[],e.off=()=>{r(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let t of e.events[Hc])t();e.events[Hc]=[]}},Gc)},()=>{e.listen=n,e.off=r}});function qc(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Jc(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Jc(e[n],t[n]))return!1;return!0}if(qc(e)&&qc(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!(r in t)||!Jc(e[r],t[r]))return!1;return!0}return!1}function Yc(e,t){return Kee(e,({newValue:n,abort:r})=>{t(e.value,n)&&r()})}var Xc=Symbol.for(`better-auth:focus-manager`),qee=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setFocused(e){this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||typeof document>`u`||window.addEventListener===void 0)return()=>{};let e=()=>{document.visibilityState===`visible`&&this.setFocused(!0)};return document.addEventListener(`visibilitychange`,e,!1),()=>{document.removeEventListener(`visibilitychange`,e,!1)}}};function Zc(){return globalThis[Xc]||(globalThis[Xc]=new qee),globalThis[Xc]}var Qc=Symbol.for(`better-auth:online-manager`),Jee=class{listeners=new Set;isOnline=typeof navigator<`u`?navigator.onLine:!0;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setOnline(e){this.isOnline=e,this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=()=>this.setOnline(!0),t=()=>this.setOnline(!1);return window.addEventListener(`online`,e,!1),window.addEventListener(`offline`,t,!1),()=>{window.removeEventListener(`online`,e,!1),window.removeEventListener(`offline`,t,!1)}}};function $c(){return globalThis[Qc]||(globalThis[Qc]=new Jee),globalThis[Qc]}var Yee={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},Xee=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,el={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},Zee=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Qee(e){return e instanceof Date&&!isNaN(e.getTime())}function $ee(e){let t=Zee.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l,u,d]=t,f=new Date(Date.UTC(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(a,10),parseInt(o,10),parseInt(s,10),c?parseInt(c.padEnd(3,`0`),10):0));if(l){let e=(parseInt(u,10)*60+parseInt(d,10))*(l===`+`?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return Qee(f)?f:null}function ete(e,t={}){let{strict:n=!1,warnings:r=!1,reviver:i,parseDates:a=!0}=t;if(typeof e!=`string`)return e;let o=e.trim(),s=o.toLowerCase();if(s.length<=9&&s in el)return el[s];if(!Xee.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(Yee).some(([e,t])=>{let n=t.test(o);return n&&r&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),n})&&n)throw Error(`[better-json] Potential prototype pollution attempt detected`);try{return JSON.parse(o,(e,t)=>{if(e===`__proto__`||e===`constructor`&&t&&typeof t==`object`&&`prototype`in t){r&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);return}if(a&&typeof t==`string`){let e=$ee(t);if(e)return e}return i?i(e,t):t})}catch(t){if(n)throw t;return e}}function tte(e,t={strict:!0}){return ete(e,t)}var nte=Symbol.for(`better-auth:auth-query`);function tl(e){let t=Vc(e);return Object.defineProperty(t,nte,{value:!0}),t}var rte=()=>typeof window>`u`;function ite(e,t){return Jc(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}var ate=(e,t,n,r)=>{let i=tl({data:null,error:null,isPending:!0,isRefetching:!1,refetch:e=>o(e)});Kc(i,()=>Yc(i,ite));let a=0,o=async e=>{let o=++a;return new Promise(s=>{let c=typeof r==`function`?r({data:i.get().data,error:i.get().error,isPending:i.get().isPending}):r;n(t,{...c,query:{...c?.query,...e?.query},async onSuccess(e){if(o===a){let t=i.get(),n=t.data!=null&&e.data!=null&&Jc(t.data,e.data)?t.data:e.data;i.set({data:n,error:null,isPending:!1,isRefetching:!1,refetch:i.value.refetch})}await c?.onSuccess?.(e)},async onError(e){let{request:t}=e,n=typeof t.retry==`number`?t.retry:t.retry?.attempts,r=t.retryAttempt||0;if(!(n&&r<n)){if(o===a){let t=e.error.status===401;i.set({error:e.error,data:t?null:i.get().data,isPending:!1,isRefetching:!1,refetch:i.value.refetch})}await c?.onError?.(e)}},async onRequest(e){if(o===a){let e=i.get();i.set({isPending:e.data===null,data:e.data,error:null,isRefetching:!0,refetch:i.value.refetch})}await c?.onRequest?.(e)}}).catch(e=>{o===a&&i.set({error:e,data:i.get().data,isPending:!1,isRefetching:!1,refetch:i.value.refetch})}).finally(()=>{s(void 0)})})};e=Array.isArray(e)?e:[e];let s=!1,c=!1,l=!1,u=()=>{if(s){l=!0;return}s=!0,o().finally(()=>{s=!1;let e=l&&c;l=!1,e&&u()})};return Kc(i,()=>{if(rte())return;c=!0;let t=!1,n,r=e.map(e=>e.listen(()=>{t?o():(t=!0,clearTimeout(n),u())}));return n=setTimeout(()=>{t=!0,u()},0),()=>{c=!1;for(let e of r)e();clearTimeout(n)}}),i},nl=()=>Math.floor(Date.now()/1e3),ote=5;function ste(e){let{fetchSession:t,shouldPollSession:n=()=>!0,sessionSignal:r,options:i={}}=e,a=i.sessionOptions?.refetchInterval??0,o=i.sessionOptions?.refetchOnWindowFocus??!0,s=i.sessionOptions?.refetchWhenOffline??!1,c={isInitialized:!1,lastSessionRequest:0},l=()=>s||$c().isOnline,u=e=>{if(l()){if(e?.event===`storage`){t();return}if(e?.event===`poll`){c.lastSessionRequest=nl(),t();return}if(e?.event===`visibilitychange`){if(nl()-c.lastSessionRequest<ote)return;c.lastSessionRequest=nl(),t();return}t()}},d=e=>{Ic().post({event:`session`,data:{trigger:e},clientId:Math.random().toString(36).substring(7)})},f=()=>{a&&a>0&&(c.pollInterval=setInterval(()=>{n()&&u({event:`poll`})},a*1e3))},p=()=>{c.unsubscribeBroadcast=Ic().subscribe(()=>{u({event:`storage`})})},m=()=>{o&&(c.unsubscribeFocus=Zc().subscribe(()=>{u({event:`visibilitychange`})}))},h=()=>{c.unsubscribeOnline=$c().subscribe(e=>{e&&u({event:`visibilitychange`})})},g=()=>{c.unsubscribeSignal=r.listen(()=>{t()})};return{init:()=>{c.isInitialized||(c.isInitialized=!0,f(),p(),m(),h(),g(),c.cleanupBroadcastSetup=Ic().setup(),c.cleanupFocusSetup=Zc().setup(),c.cleanupOnlineSetup=$c().setup())},cleanup:()=>{c.isInitialized&&(c.pollInterval&&=(clearInterval(c.pollInterval),void 0),c.unsubscribeBroadcast&&=(c.unsubscribeBroadcast(),void 0),c.unsubscribeFocus&&=(c.unsubscribeFocus(),void 0),c.unsubscribeOnline&&=(c.unsubscribeOnline(),void 0),c.unsubscribeSignal&&=(c.unsubscribeSignal(),void 0),c.cleanupBroadcastSetup&&=(c.cleanupBroadcastSetup(),void 0),c.cleanupFocusSetup&&=(c.cleanupFocusSetup(),void 0),c.cleanupOnlineSetup&&=(c.cleanupOnlineSetup(),void 0),c.isInitialized=!1,c.lastSessionRequest=0)},triggerRefetch:u,broadcastSessionUpdate:d}}var rl=Object.create(null),il=e=>({}),al=new Proxy(rl,{get(e,t){return il()[t]??rl[t]},has(e,t){return t in il()||t in rl},set(e,t,n){let r=il(!0);return r[t]=n,!0},deleteProperty(e,t){if(!t)return!1;let n=il(!0);return delete n[t],!0},ownKeys(){let e=il(!0);return Object.keys(e)}});al.NODE_ENV;function ol(e,t){return typeof process<`u`?{}[e]??t:typeof Deno<`u`?Deno.env.get(e)??t:typeof Bun<`u`?Bun.env[e]??t:t}Object.freeze({get BETTER_AUTH_SECRET(){return ol(`BETTER_AUTH_SECRET`)},get AUTH_SECRET(){return ol(`AUTH_SECRET`)},get BETTER_AUTH_TELEMETRY(){return ol(`BETTER_AUTH_TELEMETRY`)},get BETTER_AUTH_TELEMETRY_ID(){return ol(`BETTER_AUTH_TELEMETRY_ID`)},get NODE_ENV(){return ol(`NODE_ENV`,`development`)},get PACKAGE_VERSION(){return ol(`PACKAGE_VERSION`,`0.0.0`)},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return ol(`BETTER_AUTH_TELEMETRY_ENDPOINT`,``)}});function cte(){let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(e,`writable`)?e.writable:e.set!==void 0}function lte(e){let t=e.split(`
|
|
4
|
+
`)),o=[];return}e.startsWith(`data:`)&&o.push(e.slice(e.startsWith(`data: `)?6:5))};for(;;){let{done:e,value:t}=await i.read();a+=e?r.decode():r.decode(t,{stream:!0});let n=a.split(/\r\n|\r|\n/);if(a=e?``:n.pop()??``,n.forEach(s),e)return s(``)}},rs=(e,t)=>t?.[e]??e,is={filter:`filter`,orderBy:`order_by`,display:`display`,filterLayout:`layout`,map:`map`,savedSearch:`saved_search`,create:`new`,edit:`edit`},as=[`display`,`filter`,`orderBy`,`filterLayout`,`savedSearch`],os=e=>`${e.latitude.toFixed(5)},${e.longitude.toFixed(5)},${e.zoom.toFixed(2)}`,ss=(e,t,n=-t)=>Number.isFinite(e)&&e>=n&&e<=t,cs=e=>{let t=e?.split(`,`);if(t?.length!==3||t.some(e=>e.trim()===``))return;let[n,r,i]=t.map(Number);return ss(n,90)&&ss(r,180)&&ss(i,22,0)?{latitude:n,longitude:r,zoom:i}:void 0},ls=e=>{let t=new URLSearchParams;for(let n of as){let r=e[n];r!==void 0&&r!==``&&t.set(is[n],r)}e.map&&t.set(is.map,os(e.map));let n=t.toString();return n?`?${n}`:``},us=(e,t=``)=>{switch(e.kind){case`page`:return`${t}/${encodeURIComponent(e.page)}`;case`create`:return`${t}/${encodeURIComponent(e.resource)}/${is.create}${fs(e.values)}`;case`record`:return`${t}/${encodeURIComponent(e.resource)}/${encodeURIComponent(Ao(e.key))}${e.edit?`?${is.edit}=true`:``}`;case`list`:return`${t}/${encodeURIComponent(e.resource)}${ls(e)}`}},ds=e=>{try{return e.split(`/`).filter(Boolean).map(decodeURIComponent)}catch(e){if(e instanceof URIError)return;throw e}},fs=(e={})=>{let t=new URLSearchParams(Object.entries(e).filter(([,e])=>e!==``)).toString();return t?`?${t}`:``},ps=e=>e===`bar`||e===`panel`?e:void 0,ms=(e,t)=>{let n=new URL(e,`http://app`),r=ds(n.pathname);if(!r||r.length===0||r.length>2)return;let[i,a]=r;if(i===`-`)return;if(t.has(i))return a===void 0?{kind:`page`,page:i}:void 0;if(a===is.create){let e=Object.fromEntries([...n.searchParams].filter(([,e])=>e!==``));return{kind:`create`,resource:i,...Object.keys(e).length>0&&{values:e}}}if(a!==void 0)return{kind:`record`,resource:i,key:a,...n.searchParams.get(is.edit)===`true`&&{edit:!0}};let o=n.searchParams,s=o.get(is.display)||void 0,c=o.get(is.filter)||void 0,l=o.get(is.orderBy)||void 0,u=ps(o.get(is.filterLayout)),d=cs(o.get(is.map)),f=o.get(is.savedSearch)||void 0;return{kind:`list`,resource:i,...s&&{display:s},...c&&{filter:c},...l&&{orderBy:l},...u&&{filterLayout:u},...d&&{map:d},...f&&{savedSearch:f}}},hs=`/-/sign-in`,gs={step:`step`,next:`next`},_s=[`sign-in`,`forgot-password`,`email-code`,`sign-up`,`sign-up-code`,`sign-up-details`],vs=e=>_s.includes(e),ys=e=>{if(!e?.startsWith(`/`))return;let t=new URL(e,`http://local`);if(t.origin===`http://local`&&t.pathname!==`/-/sign-in`)return`${t.pathname}${t.search}`},bs=({step:e=`sign-in`,next:t}={})=>{let n=new URLSearchParams;e!==`sign-in`&&n.set(gs.step,e);let r=ys(t);r&&r!==`/`&&n.set(gs.next,r);let i=n.toString();return i?`${hs}?${i}`:hs},xs=(e,t)=>{if(e!==`/-/sign-in`)return;let n=t.get(gs.step),r=ys(t.get(gs.next));return{step:vs(n)?n:`sign-in`,...r&&{next:r}}},Ss=e=>typeof e==`string`?e:e&&Ya(e),Cs=e=>{let t=Object.entries(e??{}).map(([e,t])=>`${e}.${t}`);return t.length>0?t:void 0},ws=e=>({photos:e&&`${e.resource}.${e.field}.${e.image}`,photos_order_by:e?.sort}),Ts=(e={})=>({filter:Ss(e.filter)||void 0,order_by:e.orderBy,page_size:e.pageSize,page_token:e.pageToken||void 0,fields:e.fields?.join(`,`),labels:Cs(e.labels)?.join(`,`),...ws(e.photos),count:e.count}),Es=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))r!==void 0&&t.set(n,String(r));let n=t.toString();return n?`?${n}`:``},Ds=e=>e.startsWith(`/`)&&!e.startsWith(`//`),Os=e=>{if(typeof e!=`object`||!e)return!1;let{uri:t,url:n}=e;return typeof t==`string`&&typeof n==`string`&&Ds(n)},ks=e=>e!==void 0&&URL.canParse(e)?new URL(e).origin:void 0,As=(e,t)=>({...e,url:`${t}${e.url}`,...e.variants&&{variants:Object.fromEntries(Object.entries(e.variants).map(([e,n])=>[e,Ds(n.url)?{...n,url:`${t}${n.url}`}:n]))}}),js=(e,t)=>t===void 0||typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Os(n)?As(n,t):n])),Ms=(e,t)=>t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,n.map(e=>Os(e)?As(e,t):e)])),Ns=class extends Error{problem;constructor(e){super(e.detail??e.title),this.problem=e,this.name=`ApiError`}get status(){return this.problem.status}get slug(){return this.problem.type.split(`:`).at(-1)??``}get operation(){return this.problem.operation??this.errors.find(e=>e.operation!==void 0)?.operation}get blockedBy(){return this.problem.blockedBy}get errors(){return this.problem.errors??[]}get filterErrors(){return this.slug===`invalid-filter`?this.errors:[]}},Ps=class extends Ns{constructor(e){super(e),this.name=`PreconditionFailedError`}},Fs=e=>e instanceof Ns,Is=e=>typeof e==`object`&&!!e&&`type`in e&&`status`in e,Ls=async e=>{let t=e.headers.get(`content-type`)?.includes(`json`)??!1?await e.json():void 0,n=Is(t)?t:{type:`urn:protobase:problem:unknown`,title:e.statusText||`Request failed`,status:e.status};return n.status===412?new Ps(n):new Ns(n)},Rs=(e={})=>{let t=e.baseUrl??`/api/v1`,n=t.replace(/\/[^/]*$/,``),r=e.fetch??((e,t)=>fetch(e,t));return async({method:i,path:a,query:o=``,body:s,headers:c,accept:l=[],system:u,raw:d,via:f,signal:p})=>{let m=async l=>{let m=await e.token?.({refresh:l});return(f??r)(`${u?n:t}${a}${o}`,{method:i,headers:{...s!==void 0&&{"content-type":`application/json`},...m&&{authorization:`Bearer ${m}`},...e.headers?.(),...c},body:d??(s===void 0?void 0:JSON.stringify(s)),...p&&{signal:p}})},h=await m(!1);h.status===401&&e.token&&(h=await m(!0),h.status===401&&e.onUnauthenticated?.());let g=h.headers.get(`x-meta-version`);if(g&&e.onMetaVersion?.(g),!h.ok&&!l.includes(h.status))throw await Ls(h);return h}},zs=e=>new Headers(e.trim().split(/[\r\n]+/).filter(Boolean).map(e=>{let t=e.indexOf(`:`);return[e.slice(0,t).trim(),e.slice(t+1).trim()]})),Bs=e=>(t,n={})=>new Promise((r,i)=>{let a=new XMLHttpRequest;a.open(n.method??`GET`,String(t)),new Headers(n.headers).forEach((e,t)=>a.setRequestHeader(t,e)),a.responseType=`blob`,a.upload.onprogress=t=>e(t.loaded,t.lengthComputable?t.total:t.loaded),a.onload=()=>{let e=a.status===204||a.status===304;r(new Response(e?null:a.response,{status:a.status,statusText:a.statusText,headers:zs(a.getAllResponseHeaders())}))},a.onerror=()=>i(TypeError(`Network request failed`)),a.onabort=()=>i(new DOMException(`The upload was aborted`,`AbortError`)),n.signal?.addEventListener(`abort`,()=>a.abort()),a.send(n.body)}),Vs=e=>typeof e==`string`?e:e.toModel().name,Hs=(e,t)=>`/${Vs(e)}/${Ao(t)}`,Us=(e,t,n)=>({items:e.items.map(e=>js(e,n)),nextPageToken:e.next_page_token,totalSizeEstimate:e.total_size_estimate,...e.prev_page_token!==void 0&&{prevPageToken:e.prev_page_token},...e.total_size!==void 0&&{totalSize:e.total_size},...e.labels!==void 0&&{labels:e.labels},...e.photos!==void 0&&{photos:Ms(e.photos,n)},...t.headers.get(`x-protobase-warning`)&&{warning:t.headers.get(`x-protobase-warning`)}}),Ws=e=>e.headers.get(`etag`)??``,Gs=async(e,t)=>{let{permissions:n,...r}=await e.json();return{record:js(r,t),etag:Ws(e),...n&&{permissions:n}}},Ks=(e,t)=>({results:(e.results??[]).map(e=>e.op===`create`||e.op===`update`?{...e,record:js(e.record,t)}:e.op===`reorder`?{...e,records:e.records.map(e=>({...e,record:js(e.record,t)}))}:e)}),qs=(e={})=>{let t=Rs(e),n=ks(e.baseUrl);return{list:async(e,r)=>{let i=await t({method:`GET`,path:`/${Vs(e)}`,query:Es(Ts(r))});return Us(await i.json(),i,n)},search:async(e,r)=>{let i=Ts(r),a=await t({method:`POST`,path:`/${Vs(e)}:search`,body:{...i,fields:r?.fields,labels:Cs(r?.labels)}});return Us(await a.json(),a,n)},get:async(e,r)=>Gs(await t({method:`GET`,path:Hs(e,r)}),n),create:async(e,r)=>{let i=await t({method:`POST`,path:`/${Vs(e)}`,body:r});return{record:js(await i.json(),n),etag:Ws(i),location:i.headers.get(`location`)??``}},update:async(e,r,i,a)=>Gs(await t({method:`PATCH`,path:Hs(e,r),body:i,headers:{"if-match":a}}),n),remove:async(e,n,{etag:r}={})=>{await t({method:`DELETE`,path:Hs(e,n),headers:r?{"if-match":r}:void 0})},undelete:async(e,r)=>{let i=await t({method:`POST`,path:`${Hs(e,r)}:undelete`});return{record:js(await i.json(),n),etag:Ws(i)}},reveal:async(e,n,r)=>(await(await t({method:`POST`,path:`${Hs(e,n)}:reveal`,body:{field:r}})).json()).value,history:async(e,n,{pageSize:r,pageToken:i}={})=>{let a=Es({page_size:r,page_token:i||void 0}),o=await(await t({method:`GET`,path:`${Hs(e,n)}:history`,query:a})).json();return{items:o.items.map(({database_role:e,...t})=>({...t,databaseRole:e})),nextPageToken:o.next_page_token}},batchWrite:async e=>{let r=e=>typeof e==`object`&&e&&`$ref`in e?e:Ao(e),i=e.map(e=>({...e,resource:Vs(e.resource),...`key`in e&&{key:r(e.key)},...e.op===`reorder`&&{keys:e.keys.map(r)}}));return Ks(await(await t({method:`POST`,path:`:batchWrite`,body:{ops:i}})).json(),n)},facets:async(e,n,r={})=>(await(await t({method:`GET`,path:`/${Vs(e)}:facets`,query:Es({field:n,filter:Ss(r.filter)||void 0,limit:r.limit,label:r.label})})).json()).facets,aggregate:async(e,n)=>{let r=await(await t({method:`GET`,path:`/${Vs(e)}:aggregate`,query:Es({group_by:n.groupBy,filter:Ss(n.filter)||void 0,sum:n.sum,average:n.average,limit:n.limit,label:n.label,granularity:n.granularity,range:n.range,from:n.from,to:n.to,time_zone:n.timeZone})})).json();return{groupBy:r.group_by,granularity:r.granularity,timeZone:r.time_zone,groups:r.groups}},series:async(e,n)=>{let r=await(await t({method:`GET`,path:`/${Vs(e)}:series`,query:Es({field:n.field,range:n.range,from:n.from,to:n.to,granularity:n.granularity,time_zone:n.timeZone,filter:Ss(n.filter)||void 0})})).json();return{field:r.field,granularity:r.granularity,timeZone:r.time_zone,points:r.points}},histogram:async(e,n,r={})=>(await t({method:`GET`,path:`/${Vs(e)}:histogram`,query:Es({field:n,buckets:r.buckets,filter:Ss(r.filter)||void 0})})).json(),map:async(e,r)=>{let i=await(await t({method:`GET`,path:`/${Vs(e)}:map`,query:Es({latitude:r.latitude,longitude:r.longitude,zoom:r.zoom,filter:Ss(r.filter)||void 0,order_by:r.orderBy,fields:r.fields?.join(`,`),labels:Cs(r.labels)?.join(`,`),...ws(r.photos)})})).json();return{items:i.items.map(e=>js(e,n)),buckets:i.buckets,totalSize:i.total_size,...i.labels!==void 0&&{labels:i.labels},...i.photos!==void 0&&{photos:Ms(i.photos,n)}}},seek:async(e,r)=>{let i=await t({method:`GET`,path:`/${Vs(e)}:seek`,query:Es({...Ts(r),position:r.position})});return Us(await i.json(),i,n)},meta:async(e,{signal:n}={})=>{let r=await t({method:`GET`,path:`/meta`,system:!0,headers:e?{"if-none-match":e}:void 0,accept:[304],...n&&{signal:n}});return r.status===304?{status:`unchanged`}:{status:`modified`,meta:await r.json(),etag:Ws(r)}},invoke:async(e,{method:n,body:r,path:i=``,query:a,headers:o}={})=>{let s=await t({method:n??(r===void 0?`GET`:`POST`),path:`/functions/${encodeURIComponent(e)}${i}`,query:a?`?${new URLSearchParams(a)}`:``,body:r,headers:o,system:!0});if(s.status!==204)return s.headers.get(`content-type`)?.includes(`json`)?s.json():s.text()},upload:async(e,n,r,{onProgress:i,signal:a}={})=>{let o=`name`in r&&typeof r.name==`string`?r.name:void 0,s=i&&typeof XMLHttpRequest<`u`?Bs(i):void 0,c=await(await t({method:`POST`,path:`/${Vs(e)}:upload`,query:`?${new URLSearchParams({field:n,...o!==void 0&&{name:o}})}`,raw:r,headers:{"content-type":r.type||`application/octet-stream`},...s&&{via:s},...a&&{signal:a}})).json();return i?.(r.size,r.size),c}}},Js=e=>typeof e==`string`?e:e.toModel().name,Ys=(e,t)=>{let n=n=>t(Js(n))??e;return{list:(e,t)=>n(e).list(e,t),search:(e,t)=>n(e).search(e,t),get:(e,t)=>n(e).get(e,t),create:(e,t)=>n(e).create(e,t),update:(e,t,r,i)=>n(e).update(e,t,r,i),remove:(e,t,r)=>n(e).remove(e,t,r),undelete:(e,t)=>n(e).undelete(e,t),reveal:(e,t,r)=>n(e).reveal(e,t,r),history:(e,t,r)=>n(e).history(e,t,r),batchWrite:t=>{let r=[...new Set(t.map(e=>n(e.resource)))];return r.length>1?Promise.reject(Error(`A batch writes to one API, but these writes are for ${[...new Set(t.map(e=>Js(e.resource)))].join(`, `)}, which different APIs serve`)):(r[0]??e).batchWrite(t)},facets:(e,t,r)=>n(e).facets(e,t,r),aggregate:(e,t)=>n(e).aggregate(e,t),series:(e,t)=>n(e).series(e,t),histogram:(e,t,r)=>n(e).histogram(e,t,r),map:(e,t)=>n(e).map(e,t),seek:(e,t)=>n(e).seek(e,t),meta:(t,n)=>e.meta(t,n),invoke:(t,n)=>e.invoke(t,n),upload:(e,t,r,i)=>n(e).upload(e,t,r,i)}},Xs=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.type==`string`&&Array.isArray(e.children),Zs=e=>typeof e==`object`&&!!e&&e.kind===`member`,Qs=e=>Zs(e)?[e.path.join(`.`)]:typeof e!=`object`||!e?[]:Object.values(e).flatMap(Qs),$s=e=>Zs(e)?{...e,path:[e.path.join(`.`)]}:Array.isArray(e)?e.map($s):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,$s(t)])),ec=e=>{let t=Qr(e);return t.ok?t.ast?{ok:!0,ast:t.ast,paths:[...new Set(Qs(t.ast))]}:{ok:!1,message:`the condition is empty`}:{ok:!1,message:t.errors.map(e=>e.message).join(`; `)}},tc=(e,t)=>e.ast!==void 0&&da($s(e.ast),t),nc=(e,t)=>{let[n,r,...i]=e.split(`.`);return n&&r===`count`&&i.length===0&&!t(n)?n:void 0},rc=(e,t,n)=>{let r=[],i=e[t],a=n.split(`.`);for(let[o,s]of a.entries()){if(!i)return{ok:!1,message:`unknown resource "${t}"`};let c=Object.hasOwn(i.fields,s)?i.fields[s]:void 0;if(!c)return{ok:!1,message:`unknown field "${a.slice(0,o+1).join(`.`)}" on ${i.name}`};if(r.push({model:i,field:c}),o===a.length-1)break;if(c.type!==`relation`||!c.relation)return{ok:!1,message:`"${a.slice(0,o+1).join(`.`)}" is not a relation, so "${n}" cannot go through it`};t=c.relation.resource,i=e[t]}return{ok:!0,steps:r}},ic=(e,t)=>({...e,fields:Object.fromEntries(Object.entries(e.fields).map(([e,n])=>{if(!n.relation||Object.hasOwn(t,n.relation.resource))return[e,n];let{relation:r,...i}=n;return[e,i]}))}),ac=(e,t)=>{if(e.kind!==`related`)return[e];if(!Object.hasOwn(t,e.resource)||e.through&&!Object.hasOwn(t,e.through.resource))return[];let{columns:n,...r}=e,i=n?.filter(n=>rc(t,e.resource,n).ok);return[i&&i.length>0?{...r,columns:i}:r]},oc=(e,t,n)=>e.run?.kind!==`link`||!(`to`in e.run)||Zo(e.run.to,{models:n,pages:new Set,source:t}).length===0,sc=(e,t)=>({...e,layout:e.layout.flatMap(e=>ac(e,t)),actions:e.actions.filter(n=>oc(n,t[e.resource],t))}),cc=(e,t)=>{let n=e.resources.filter(e=>t.resources.includes(e.name)),r=Object.fromEntries(n.map(e=>[e.name,e])),i=n.map(e=>ic(e,r)),a=Object.fromEntries(i.map(e=>[e.name,e]));return{resources:i,views:e.views.filter(e=>Object.hasOwn(a,e.resource)).map(e=>sc(e,a)),permissions:Object.fromEntries(n.flatMap(t=>e.permissions?.[t.name]?[[t.name,e.permissions[t.name]]]:[]))}},lc=class extends Error{status;code;constructor(e,t,n){super(e),this.status=t,this.code=n,this.name=`AuthError`}},B=(e,t)=>new lc(e?.message||t,e?.status??500,e?.code),uc=e=>({signInMethods:async()=>{let{data:t,error:n}=await e.$fetch(`/account/sign-in-methods`);if(n||!t)throw B(n,`Could not read your sign-in methods`);return t},passkeys:async()=>{let{data:t,error:n}=await e.passkey.listUserPasskeys();if(n||!t)throw B(n,`Could not read your passkeys`);return t.map(e=>({id:e.id,backedUp:e.backedUp,...e.name&&{name:e.name},...e.createdAt&&{createdAt:new Date(e.createdAt).toISOString()}}))},addPasskey:async t=>{let{error:n}=await e.passkey.addPasskey(t?{name:t}:{});if(n)throw B(n,`Could not add the passkey`)},renamePasskey:async(t,n)=>{let{error:r}=await e.passkey.updatePasskey({id:t,name:n});if(r)throw B(r,`Could not rename the passkey`)},removePasskey:async t=>{let{error:n}=await e.passkey.deletePasskey({id:t});if(n)throw B(n,`Could not remove the passkey`)},startAuthenticatorApp:async t=>{let{data:n,error:r}=await e.twoFactor.enable({method:`totp`,...t&&{password:t}});if(r||n?.method!==`totp`)throw B(r,`Could not start two-factor authentication`);return{totpURI:n.totpURI,backupCodes:n.backupCodes}},confirmAuthenticatorApp:async t=>{let{error:n}=await e.twoFactor.verifyTotp({code:t});if(n)throw B(n,`The code did not work`)},turnOnEmailedCodes:async t=>{let{error:n}=await e.twoFactor.enable({method:`otp`,...t&&{password:t}});if(n)throw B(n,`Could not turn on two-factor authentication`)},turnOffTwoFactor:async t=>{let{error:n}=await e.twoFactor.disable(t?{password:t}:{});if(n)throw B(n,`Could not turn off two-factor authentication`)},linkedProviders:async()=>{let{data:t,error:n}=await e.listAccounts();if(n||!t)throw B(n,`Could not read your linked accounts`);return[...new Set(t.map(e=>e.providerId).filter(e=>e!==`credential`))]},linkProvider:async(t,n)=>{let{data:r,error:i}=await e.linkSocial({provider:t,callbackURL:n,errorCallbackURL:n,disableRedirect:!0});if(i||!r?.url)throw B(i,`Could not start linking the account`);return r.url},newBackupCodes:async t=>{let{data:n,error:r}=await e.twoFactor.generateBackupCodes(t?{password:t}:{});if(r||!n)throw B(r,`Could not make new backup codes`);return n.backupCodes}});function dc(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}var fc=dc({CHALLENGE_NOT_FOUND:`Challenge not found`,YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY:`You are not allowed to register this passkey`,FAILED_TO_VERIFY_REGISTRATION:`Failed to verify registration`,PASSKEY_NOT_FOUND:`Passkey not found`,AUTHENTICATION_FAILED:`Authentication failed`,UNABLE_TO_CREATE_SESSION:`Unable to create session`,USER_NOT_FOUND:`User not found`,FAILED_TO_UPDATE_PASSKEY:`Failed to update passkey`,PREVIOUSLY_REGISTERED:`Previously registered`,REGISTRATION_CANCELLED:`Registration cancelled`,AUTH_CANCELLED:`Auth cancelled`,UNKNOWN_ERROR:`Unknown error`,SESSION_REQUIRED:`Passkey registration requires an authenticated session`,RESOLVE_USER_REQUIRED:`Passkey registration requires either an authenticated session or a resolveUser callback when requireSession is false`,RESOLVED_USER_INVALID:`Resolved user is invalid`}),pc=`1.7.7`;function mc(e){let t=new Uint8Array(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function hc(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=(4-t.length%4)%4,r=t.padEnd(t.length+n,`=`),i=atob(r),a=new ArrayBuffer(i.length),o=new Uint8Array(a);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);return a}function gc(){return _c.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential==`function`)}var _c={stubThis:e=>e};function vc(e){let{id:t}=e;return{...e,id:hc(t),transports:e.transports}}function yc(e){return e===`localhost`||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(e)}var bc=class extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r??n.name,this.code=t}};function xc({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new bc({message:`Registration ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`ConstraintError`){if(n.authenticatorSelection?.requireResidentKey===!0)return new bc({message:`Discoverable credentials were required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT`,cause:e});if(t.mediation===`conditional`&&n.authenticatorSelection?.userVerification===`required`)return new bc({message:`User verification was required during automatic registration but it could not be performed`,code:`ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE`,cause:e});if(n.authenticatorSelection?.userVerification===`required`)return new bc({message:`User verification was required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT`,cause:e})}else if(e.name===`InvalidStateError`)return new bc({message:`The authenticator was previously registered`,code:`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`,cause:e});else if(e.name===`NotAllowedError`)return new bc({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`NotSupportedError`)return n.pubKeyCredParams.filter(e=>e.type===`public-key`).length===0?new bc({message:`No entry in pubKeyCredParams was of type "public-key"`,code:`ERROR_MALFORMED_PUBKEYCREDPARAMS`,cause:e}):new bc({message:`No available authenticator supported any of the specified pubKeyCredParams algorithms`,code:`ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!yc(t))return new bc({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rp.id!==t)return new bc({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`TypeError`){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new bc({message:`User ID was not between 1 and 64 characters`,code:`ERROR_INVALID_USER_ID_LENGTH`,cause:e})}else if(e.name===`UnknownError`)return new bc({message:`The authenticator was unable to process the specified options, or could not create a new credential`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}var Sc=new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let e=Error(`Cancelling existing WebAuthn API call for new one`);e.name=`AbortError`,this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error(`Manually cancelling existing WebAuthn API call`);e.name=`AbortError`,this.controller.abort(e),this.controller=void 0}}},Cc=[`cross-platform`,`platform`];function wc(e){if(e&&!(Cc.indexOf(e)<0))return e}async function Tc(e){!e.optionsJSON&&e.challenge&&(console.warn(`startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useAutoRegister:n=!1}=e;if(!gc())throw Error(`WebAuthn is not supported in this browser`);let r={...t,challenge:hc(t.challenge),user:{...t.user,id:hc(t.user.id)},excludeCredentials:t.excludeCredentials?.map(vc)},i={};n&&(i.mediation=`conditional`),i.publicKey=r,i.signal=Sc.createNewAbortSignal();let a;try{a=await navigator.credentials.create(i)}catch(e){throw xc({error:e,options:i})}if(!a)throw Error(`Registration was not completed`);let{id:o,rawId:s,response:c,type:l}=a,u;typeof c.getTransports==`function`&&(u=c.getTransports());let d;if(typeof c.getPublicKeyAlgorithm==`function`)try{d=c.getPublicKeyAlgorithm()}catch(e){Ec(`getPublicKeyAlgorithm()`,e)}let f;if(typeof c.getPublicKey==`function`)try{let e=c.getPublicKey();e!==null&&(f=mc(e))}catch(e){Ec(`getPublicKey()`,e)}let p;if(typeof c.getAuthenticatorData==`function`)try{p=mc(c.getAuthenticatorData())}catch(e){Ec(`getAuthenticatorData()`,e)}return{id:o,rawId:mc(s),response:{attestationObject:mc(c.attestationObject),clientDataJSON:mc(c.clientDataJSON),transports:u,publicKeyAlgorithm:d,publicKey:f,authenticatorData:p},type:l,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:wc(a.authenticatorAttachment)}}function Ec(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}function Dc(){if(!gc())return Oc.stubThis(new Promise(e=>e(!1)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?Oc.stubThis(new Promise(e=>e(!1))):Oc.stubThis(e.isConditionalMediationAvailable())}var Oc={stubThis:e=>e};function kc({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new bc({message:`Authentication ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`NotAllowedError`)return new bc({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!yc(t))return new bc({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rpId!==t)return new bc({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`UnknownError`)return new bc({message:`The authenticator was unable to process the specified options, or could not create a new assertion signature`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}async function Ac(e){!e.optionsJSON&&e.challenge&&(console.warn(`startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useBrowserAutofill:n=!1,verifyBrowserAutofillInput:r=!0}=e;if(!gc())throw Error(`WebAuthn is not supported in this browser`);let i;t.allowCredentials?.length!==0&&(i=t.allowCredentials?.map(vc));let a={...t,challenge:hc(t.challenge),allowCredentials:i},o={};if(n){if(!await Dc())throw Error(`Browser does not support WebAuthn autofill`);if(document.querySelectorAll(`input[autocomplete$='webauthn']`).length<1&&r)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');o.mediation=`conditional`,a.allowCredentials=[]}o.publicKey=a,o.signal=Sc.createNewAbortSignal();let s;try{s=await navigator.credentials.get(o)}catch(e){throw kc({error:e,options:o})}if(!s)throw Error(`Authentication was not completed`);let{id:c,rawId:l,response:u,type:d}=s,f;return u.userHandle&&(f=mc(u.userHandle)),{id:c,rawId:mc(l),response:{authenticatorData:mc(u.authenticatorData),clientDataJSON:mc(u.clientDataJSON),signature:mc(u.signature),userHandle:f},type:d,clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:wc(s.authenticatorAttachment)}}var jc=`1.7.7`,Mc=Symbol.for(`better-auth:broadcast-channel`),Nc=()=>Math.floor(Date.now()/1e3),Pc=class{listeners=new Set;name;constructor(e=`better-auth.message`){this.name=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}post(e){if(typeof window<`u`)try{localStorage.setItem(this.name,JSON.stringify({...e,timestamp:Nc()}))}catch{}}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=e=>{if(e.key!==this.name)return;let t=JSON.parse(e.newValue??`{}`);t?.event===`session`&&t?.data&&this.listeners.forEach(e=>e(t))};return window.addEventListener(`storage`,e),()=>{window.removeEventListener(`storage`,e)}}};function Fc(e=`better-auth.message`){return globalThis[Mc]||(globalThis[Mc]=new Pc(e)),globalThis[Mc]}var Ic=[],Lc=0,Rc=null,zc=4,Hee=globalThis.nanostoresGlobal||={epoch:0},Uee=()=>{let e,t;for(;Lc<Ic.length;){t=Lc,Lc+=zc;let n=Rc?.get(Ic[t]);if(n){if(!n.has(Ic[t+1]))continue;n.clear()}try{Ic[t](Ic[t+1].value,Ic[t+2],Ic[t+3])}catch(t){e=t}}if(Ic.length=Lc=0,e)throw e},Bc=e=>{let t=[],n={eq:Object.is,get(){return n.lc||n.listen(()=>{})(),n.value},init:e,lc:0,listen(e){return n.lc=t.push(e),()=>{Rc?.get(e)?.delete(n);for(let t=Lc;t<Ic.length;)Ic[t]===e&&Ic[t+1]===n?Ic.splice(t,zc):t+=zc;let r=t.indexOf(e);~r&&(t.splice(r,1),--n.lc||n.off())}},notify(e,r){Hee.epoch++;let i=!Ic.length&&!0;for(let i of t)Ic.push(i,n,e,r);i&&Uee()},off(){},set(e){let t=n.value;n.eq(t,e)||(n.value=e,n.notify(t))},subscribe(e){let t=n.listen(e);return e(n.value),t},value:e};return n},Wee=2,Gee=5,Vc=6,Hc=10,Uc=(e,t,n,r)=>(e.events=e.events||{},e.events[n+Hc]||(e.events[n+Hc]=r(t=>{e.events[n].reduceRight((e,t)=>(t(e),e),{shared:{},...t})})),e.events[n]=e.events[n]||[],e.events[n].push(t),()=>{let r=e.events[n],i=r.indexOf(t);~i&&(r.splice(i,1),r.length||(e.events[n+Hc](),delete e.events[n+Hc]))}),Kee=(e,t)=>Uc(e,t,Wee,t=>{let n=e.set,r=e.setKey;return e.setKey&&=(n,i)=>{let a;if(t({abort:()=>{a=!0},changed:n,newValue:{...e.value,[n]:i}}),!a)return r(n,i)},e.set=e=>{let r;if(t({abort:()=>{r=!0},newValue:e}),!r)return n(e)},()=>{e.set=n,e.setKey=r}}),Wc=1e3,Gc=(e,t)=>Uc(e,n=>{let r=t(n);r&&e.events[Vc].push(r)},Gee,t=>{let n=e.listen;e.listen=(...r)=>(!e.lc&&!e.active&&(e.active=!0,t()),n(...r));let r=e.off;return e.events[Vc]=[],e.off=()=>{r(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let t of e.events[Vc])t();e.events[Vc]=[]}},Wc)},()=>{e.listen=n,e.off=r}});function Kc(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function qc(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!qc(e[n],t[n]))return!1;return!0}if(Kc(e)&&Kc(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!(r in t)||!qc(e[r],t[r]))return!1;return!0}return!1}function Jc(e,t){return Kee(e,({newValue:n,abort:r})=>{t(e.value,n)&&r()})}var Yc=Symbol.for(`better-auth:focus-manager`),qee=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setFocused(e){this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||typeof document>`u`||window.addEventListener===void 0)return()=>{};let e=()=>{document.visibilityState===`visible`&&this.setFocused(!0)};return document.addEventListener(`visibilitychange`,e,!1),()=>{document.removeEventListener(`visibilitychange`,e,!1)}}};function Xc(){return globalThis[Yc]||(globalThis[Yc]=new qee),globalThis[Yc]}var Zc=Symbol.for(`better-auth:online-manager`),Jee=class{listeners=new Set;isOnline=typeof navigator<`u`?navigator.onLine:!0;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setOnline(e){this.isOnline=e,this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=()=>this.setOnline(!0),t=()=>this.setOnline(!1);return window.addEventListener(`online`,e,!1),window.addEventListener(`offline`,t,!1),()=>{window.removeEventListener(`online`,e,!1),window.removeEventListener(`offline`,t,!1)}}};function Qc(){return globalThis[Zc]||(globalThis[Zc]=new Jee),globalThis[Zc]}var Yee={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},Xee=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,$c={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},Zee=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function Qee(e){return e instanceof Date&&!isNaN(e.getTime())}function $ee(e){let t=Zee.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l,u,d]=t,f=new Date(Date.UTC(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(a,10),parseInt(o,10),parseInt(s,10),c?parseInt(c.padEnd(3,`0`),10):0));if(l){let e=(parseInt(u,10)*60+parseInt(d,10))*(l===`+`?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return Qee(f)?f:null}function ete(e,t={}){let{strict:n=!1,warnings:r=!1,reviver:i,parseDates:a=!0}=t;if(typeof e!=`string`)return e;let o=e.trim(),s=o.toLowerCase();if(s.length<=9&&s in $c)return $c[s];if(!Xee.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(Yee).some(([e,t])=>{let n=t.test(o);return n&&r&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),n})&&n)throw Error(`[better-json] Potential prototype pollution attempt detected`);try{return JSON.parse(o,(e,t)=>{if(e===`__proto__`||e===`constructor`&&t&&typeof t==`object`&&`prototype`in t){r&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);return}if(a&&typeof t==`string`){let e=$ee(t);if(e)return e}return i?i(e,t):t})}catch(t){if(n)throw t;return e}}function tte(e,t={strict:!0}){return ete(e,t)}var nte=Symbol.for(`better-auth:auth-query`);function el(e){let t=Bc(e);return Object.defineProperty(t,nte,{value:!0}),t}var rte=()=>typeof window>`u`;function ite(e,t){return qc(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}var ate=(e,t,n,r)=>{let i=el({data:null,error:null,isPending:!0,isRefetching:!1,refetch:e=>o(e)});Gc(i,()=>Jc(i,ite));let a=0,o=async e=>{let o=++a;return new Promise(s=>{let c=typeof r==`function`?r({data:i.get().data,error:i.get().error,isPending:i.get().isPending}):r;n(t,{...c,query:{...c?.query,...e?.query},async onSuccess(e){if(o===a){let t=i.get(),n=t.data!=null&&e.data!=null&&qc(t.data,e.data)?t.data:e.data;i.set({data:n,error:null,isPending:!1,isRefetching:!1,refetch:i.value.refetch})}await c?.onSuccess?.(e)},async onError(e){let{request:t}=e,n=typeof t.retry==`number`?t.retry:t.retry?.attempts,r=t.retryAttempt||0;if(!(n&&r<n)){if(o===a){let t=e.error.status===401;i.set({error:e.error,data:t?null:i.get().data,isPending:!1,isRefetching:!1,refetch:i.value.refetch})}await c?.onError?.(e)}},async onRequest(e){if(o===a){let e=i.get();i.set({isPending:e.data===null,data:e.data,error:null,isRefetching:!0,refetch:i.value.refetch})}await c?.onRequest?.(e)}}).catch(e=>{o===a&&i.set({error:e,data:i.get().data,isPending:!1,isRefetching:!1,refetch:i.value.refetch})}).finally(()=>{s(void 0)})})};e=Array.isArray(e)?e:[e];let s=!1,c=!1,l=!1,u=()=>{if(s){l=!0;return}s=!0,o().finally(()=>{s=!1;let e=l&&c;l=!1,e&&u()})};return Gc(i,()=>{if(rte())return;c=!0;let t=!1,n,r=e.map(e=>e.listen(()=>{t?o():(t=!0,clearTimeout(n),u())}));return n=setTimeout(()=>{t=!0,u()},0),()=>{c=!1;for(let e of r)e();clearTimeout(n)}}),i},tl=()=>Math.floor(Date.now()/1e3),ote=5;function ste(e){let{fetchSession:t,shouldPollSession:n=()=>!0,sessionSignal:r,options:i={}}=e,a=i.sessionOptions?.refetchInterval??0,o=i.sessionOptions?.refetchOnWindowFocus??!0,s=i.sessionOptions?.refetchWhenOffline??!1,c={isInitialized:!1,lastSessionRequest:0},l=()=>s||Qc().isOnline,u=e=>{if(l()){if(e?.event===`storage`){t();return}if(e?.event===`poll`){c.lastSessionRequest=tl(),t();return}if(e?.event===`visibilitychange`){if(tl()-c.lastSessionRequest<ote)return;c.lastSessionRequest=tl(),t();return}t()}},d=e=>{Fc().post({event:`session`,data:{trigger:e},clientId:Math.random().toString(36).substring(7)})},f=()=>{a&&a>0&&(c.pollInterval=setInterval(()=>{n()&&u({event:`poll`})},a*1e3))},p=()=>{c.unsubscribeBroadcast=Fc().subscribe(()=>{u({event:`storage`})})},m=()=>{o&&(c.unsubscribeFocus=Xc().subscribe(()=>{u({event:`visibilitychange`})}))},h=()=>{c.unsubscribeOnline=Qc().subscribe(e=>{e&&u({event:`visibilitychange`})})},g=()=>{c.unsubscribeSignal=r.listen(()=>{t()})};return{init:()=>{c.isInitialized||(c.isInitialized=!0,f(),p(),m(),h(),g(),c.cleanupBroadcastSetup=Fc().setup(),c.cleanupFocusSetup=Xc().setup(),c.cleanupOnlineSetup=Qc().setup())},cleanup:()=>{c.isInitialized&&(c.pollInterval&&=(clearInterval(c.pollInterval),void 0),c.unsubscribeBroadcast&&=(c.unsubscribeBroadcast(),void 0),c.unsubscribeFocus&&=(c.unsubscribeFocus(),void 0),c.unsubscribeOnline&&=(c.unsubscribeOnline(),void 0),c.unsubscribeSignal&&=(c.unsubscribeSignal(),void 0),c.cleanupBroadcastSetup&&=(c.cleanupBroadcastSetup(),void 0),c.cleanupFocusSetup&&=(c.cleanupFocusSetup(),void 0),c.cleanupOnlineSetup&&=(c.cleanupOnlineSetup(),void 0),c.isInitialized=!1,c.lastSessionRequest=0)},triggerRefetch:u,broadcastSessionUpdate:d}}var nl=Object.create(null),rl=e=>({}),il=new Proxy(nl,{get(e,t){return rl()[t]??nl[t]},has(e,t){return t in rl()||t in nl},set(e,t,n){let r=rl(!0);return r[t]=n,!0},deleteProperty(e,t){if(!t)return!1;let n=rl(!0);return delete n[t],!0},ownKeys(){let e=rl(!0);return Object.keys(e)}});il.NODE_ENV;function al(e,t){return typeof process<`u`?{}[e]??t:typeof Deno<`u`?Deno.env.get(e)??t:typeof Bun<`u`?Bun.env[e]??t:t}Object.freeze({get BETTER_AUTH_SECRET(){return al(`BETTER_AUTH_SECRET`)},get AUTH_SECRET(){return al(`AUTH_SECRET`)},get BETTER_AUTH_TELEMETRY(){return al(`BETTER_AUTH_TELEMETRY`)},get BETTER_AUTH_TELEMETRY_ID(){return al(`BETTER_AUTH_TELEMETRY_ID`)},get NODE_ENV(){return al(`NODE_ENV`,`development`)},get PACKAGE_VERSION(){return al(`PACKAGE_VERSION`,`0.0.0`)},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return al(`BETTER_AUTH_TELEMETRY_ENDPOINT`,``)}});function cte(){let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(e,`writable`)?e.writable:e.set!==void 0}function lte(e){let t=e.split(`
|
|
5
5
|
at `);return t.length<=1?e:(t.splice(1,1),t.join(`
|
|
6
|
-
at `))}function ute(e,t){class n extends e{#e;constructor(...e){if(cte()){let t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);let t=Error().stack;t&&(this.#e=lte(t.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(n.prototype,"constructor",{get(){return t},enumerable:!1,configurable:!0}),n}var dte={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};ute(class extends Error{status;body;headers;statusCode;constructor(e=`INTERNAL_SERVER_ERROR`,t=void 0,n={},r=typeof e==`number`?e:dte[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=n,this.statusCode=r,this.name=`APIError`,this.status=e,this.headers=n,this.statusCode=r,this.body=t}},Error);var sl=class extends Error{constructor(e,t){super(e,t),this.name=`BetterAuthError`,this.message=e,this.stack=``}},fte=47;function cl(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===fte;)t--;return t===e.length?e:e.slice(0,t)}function pte(e){try{return(cl(new URL(e).pathname)||`/`)!==`/`}catch{throw new sl(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function mte(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new sl(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof sl?t:new sl(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function ll(e,t=`/api/auth`){if(mte(e),pte(e))return e;let n=cl(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function ul(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function hte(e,t,n,r,i){if(e)return ll(e,t);if(r!==!1){let e=al.BETTER_AUTH_URL||al.NEXT_PUBLIC_BETTER_AUTH_URL||al.PUBLIC_BETTER_AUTH_URL||al.NUXT_PUBLIC_BETTER_AUTH_URL||al.NUXT_PUBLIC_AUTH_URL||(al.BASE_URL===`/`?void 0:al.BASE_URL);if(e)return ll(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&ul(o,`proto`)&&ul(a,`host`))try{return ll(`${o}://${a}`,t)}catch{}if(n){let e=gte(n.url);if(!e)throw new sl(`Could not get origin from request. Please provide a valid base URL.`);return ll(e,t)}if(typeof window<`u`&&window.location)return ll(window.location.origin,t)}function gte(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}var _te=[`javascript:`,`data:`,`vbscript:`];function dl(e){let t;try{t=new URL(e)}catch{return!0}return!_te.includes(t.protocol)}var vte={id:`redirect`,name:`Redirect`,hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&dl(e.data.url)&&typeof window<`u`&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}},yte=()=>typeof window>`u`,bte=Gc;function xte(e,t){if(typeof window>`u`)return;let n=e.get();n.data===null&&t!==null&&e.set({...n,data:t,error:null,isPending:!1})}function fl(e){return typeof e==`object`&&e&&`data`in e&&`error`in e?e:{data:e,error:null}}function Ste(e){return!e||e.session===null&&e.user===null?null:e}function Cte(e,t){return Jc(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}function wte(e,t){let n=Vc(!1),r,i=0,a=0;n.listen(()=>{a++,i=0});let o=e=>u(e),s=tl({data:null,error:null,isPending:!0,isRefetching:!1,refetch:o});Yc(s,Cte);let c=async(t,n)=>{let r=s.value;if(s.set({...r,isPending:r.data===null,isRefetching:!0,error:null,refetch:o}),t.aborted)return`aborted`;try{let r=await e(`/get-session`,{method:`GET`,query:n?.query,signal:t});if(t.aborted)return`aborted`;let{data:i,error:a}=fl(r),c=`fresh`;if(i?.needsRefresh)try{let n=await e(`/get-session`,{method:`POST`,signal:t});if(t.aborted)return`aborted`;({data:i,error:a}=fl(n))}catch{if(t.aborted)return`aborted`;c=`stale`}if(a){let e=s.value,t=a?.status===401;return s.set({data:t?null:e.data,error:a,isPending:!1,isRefetching:!1,refetch:o}),`failed`}let l=Ste(i),u=s.value,d=u.data!=null&&l!=null&&Jc(u.data,l)?u.data:l;return s.set({data:d,error:null,isPending:!1,isRefetching:!1,refetch:o}),c}catch(e){if(t.aborted)return`aborted`;let n=s.value;return s.set({data:n.data,error:e,isPending:!1,isRefetching:!1,refetch:o}),`failed`}},l=()=>{let e=s.value.data?.session?.expiresAt,t=e instanceof Date?e.getTime():1/0;return Math.min(Date.now()+bte,t)},u=e=>{i=0,r?.cancel();let t=new AbortController,n={cancel:()=>t.abort(),promise:Promise.resolve().then(()=>t.signal.aborted?`aborted`:c(t.signal,e)),revision:a};r=n;let o=e=>{r===n&&(r=void 0,e===`fresh`&&n.revision===a&&(i=l()))};return n.promise.then(o,()=>o(`failed`)),n.promise.then(()=>void 0)},d=()=>r?.revision===a?r.promise.then(()=>void 0):Date.now()<i?Promise.resolve():u(),f=()=>{};return Kc(s,()=>{let e;yte()||(e=setTimeout(()=>{d()},0));let r=ste({fetchSession:u,shouldPollSession:()=>s.value.data!=null,sessionSignal:n,options:t});return r.init(),f=r.broadcastSessionUpdate,()=>{e&&clearTimeout(e),r.cleanup()}}),{session:s,$sessionSignal:n,broadcastSessionUpdate:e=>f(e)}}function pl(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function ml(e,t,n=`.`,r){if(!pl(t))return ml(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(i[t]=Array.isArray(a)&&Array.isArray(i[t])?[...a,...i[t]]:pl(a)&&pl(i[t])?ml(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function Tte(e){return(...t)=>t.reduce((t,n)=>ml(t,n,``,e),{})}var Ete=Tte(),Dte=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},Ote=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let t=await i.init?.call(i,e.toString(),n);n=t.options||n,e=t.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}},hl=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},kte=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function Ate(e){if(typeof e==`number`)return new hl({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new hl(e);case`exponential`:return new kte(e);default:throw Error(`Invalid retry strategy`)}}var jte=[`get`,`post`,`put`,`patch`,`delete`];function gl(e){if(!e.startsWith(`@`))return{method:void 0,path:e};let t=e.indexOf(`/`),n=e.slice(1,t===-1?void 0:t);return jte.includes(n)?{method:n,path:t===-1?e:e.slice(t+1)}:{method:void 0,path:e}}var Mte=e=>e===`.`||e===`..`,Nte=e=>e.split(`:`).map(e=>encodeURIComponent(e)).join(`:`);function Pte(e,t){let n=t.get(e);if(n===void 0)return Nte(e);if(Mte(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function Fte(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``,{path:o}=gl(e);o!==e&&(e=`/${o}`),a.endsWith(`/`)||(a+=`/`);let[s,c]=e.replace(a,``).split(`?`),l=new URLSearchParams(c);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)l.append(e,n);continue}else n=JSON.stringify(t);l.set(e,n)}let u=new Map;if(r){if(Array.isArray(r)){let e=s.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];u.set(n,String(e))}}else for(let[e,t]of Object.entries(r))u.set(`:${e}`,String(t))}s=s.split(`/`).map(e=>Pte(e,u)).join(`/`),s=s.replace(/^\/+/,``);let d=l.toString();return d=d.length>0?`?${d}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${s}${d}`,a):`${a}${s}${d}`}var Ite=async e=>{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},Lte=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Rte(e){let t=e.headers.get(`content-type`),n=new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return Lte.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function zte(e){try{return JSON.parse(e),!0}catch{return!1}}function _l(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function vl(e){try{return JSON.parse(e)}catch{return e}}function yl(e){return typeof e==`function`}function Bte(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&yl(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&yl(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function bl(...e){let t={};for(let n of e)if(n){if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}}return t}async function Vte(e){let t=new Headers(bl(e?.headers,await Ite(e)));if(!t.has(`content-type`)){let n=Hte(e?.body);n&&t.set(`content-type`,n)}return t}function Hte(e){return _l(e)?`application/json`:null}function Ute(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function Wte(e,t){let{body:n}=e;return n?!_l(n)||typeof n==`string`?n:Ute(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function Gte(e,t){if(t?.method)return t.method.toUpperCase();let{method:n}=gl(e);return n?n.toUpperCase():t?.body?`POST`:`GET`}function Kte(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var qte=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function xl(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new qte(n.issues);return n.value}function Sl(e){"@babel/helpers - typeof";return Sl=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},Sl(e)}function Jte(e,t){if(Sl(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Sl(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Yte(e){var t=Jte(e,`string`);return Sl(t)==`symbol`?t:t+``}function Xte(e,t,n){return(t=Yte(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Cl(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function wl(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Cl(Object(n),!0).forEach(function(t){Xte(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Cl(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var Tl=async(e,t)=>{var n;let{hooks:r,url:i,options:a}=await Ote(e,t),o=Bte(a),s=new AbortController,c=a.signal??s.signal,l=Fte(i,a),u=await Vte(a),d=Wte(a,u),f=Gte(i,a),p=wl(wl({},a),{},{url:l,headers:u,body:d,method:f,signal:c});for(let e of r.onRequest)if(e){let t=await e(p);typeof t==`object`&&t&&Object.assign(p,t)}(`pipeTo`in p&&typeof p.pipeTo==`function`||typeof(t==null||(n=t.body)==null?void 0:n.pipe)==`function`)&&(`duplex`in p||(p.duplex=`half`));let{clearTimeout:m}=Kte(a,s),h=await o(p.url,p);m();let g={response:h,request:p};for(let e of r.onResponse)if(e){var _;let n=await e(wl(wl({},g),{},{response:t!=null&&(_=t.hookOptions)!=null&&_.cloneResponse?h.clone():h}));n instanceof Response?h=n:typeof n==`object`&&n&&(h=n.response)}if(h.ok){if(p.method===`HEAD`)return{data:``,error:null};let e=Rte(h),n={data:null,response:h,request:p};if(e===`json`||e===`text`){let e=await h.text();n.data=await(p.jsonParser??vl)(e)}else n.data=await h[e]();p?.output&&p.output&&!p.disableValidation&&(n.data=await xl(p.output,n.data));for(let e of r.onSuccess)if(e){var v;await e(wl(wl({},n),{},{response:t!=null&&(v=t.hookOptions)!=null&&v.cloneResponse?h.clone():h}))}return t?.throw?n.data:{data:n.data,error:null}}let y=t?.jsonParser??vl,b=await h.text(),x=zte(b),S=x?await y(b):null,C={response:h,responseText:b,request:p,error:wl(wl({},S),{},{status:h.status,statusText:h.statusText})};for(let e of r.onError)if(e){var w;await e(wl(wl({},C),{},{response:t!=null&&(w=t.hookOptions)!=null&&w.cloneResponse?h.clone():h}))}if(t?.retry){let n=Ate(t.retry),i=t.retryAttempt??0;if(await n.shouldAttemptRetry(i,h)){for(let e of r.onRetry)e&&await e(g);let a=n.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await Tl(e,wl(wl({},t),{},{retryAttempt:i+1}))}}if(t?.throw)throw new Dte(h.status,h.statusText,x?S:b);return{data:null,error:wl(wl({},S),{},{status:h.status,statusText:h.statusText})}},Zte=e=>({id:`apply-schema`,name:`Apply Schema`,version:`1.0.0`,async init(t,n){var r;let i=wl(wl({},n),e.query!==void 0&&{query:wl(wl({},e.query),n?.query)}),a=((r=e.plugins)==null||(r=r.find(e=>e.schema?.config?t.startsWith(e.schema.config.baseURL||``)||t.startsWith(e.schema.config.prefix||``):!1))==null?void 0:r.schema)||e.schema;if(a){let r=t;a.config?.prefix&&r.startsWith(a.config.prefix)&&(r=r.replace(a.config.prefix,``),a.config.baseURL&&(t=t.replace(a.config.prefix,a.config.baseURL))),a.config?.baseURL&&r.startsWith(a.config.baseURL)&&(r=r.replace(a.config.baseURL,``)),r.startsWith(`/`)&&r.charAt(1)===`@`&&(r=r.substring(1));let o=a.schema[r];if(o){let{method:a,path:s}=gl(r);a&&(t=t.slice(0,t.length-r.length)+s);let c=n?.headers;if(o.headers&&!n?.disableValidation){let e={};if(n?.headers){if(n.headers instanceof Headers)n.headers.forEach((t,n)=>{e[n.toLowerCase()]=t});else if(typeof n.headers==`object`)for(let[t,r]of Object.entries(n.headers))r!=null&&(e[t.toLowerCase()]=r)}let t=await xl(o.headers,e),r={};for(let[e,n]of Object.entries(t))r[e.toLowerCase()]=n;c=r}let l=o.method??a;if(i=wl(wl(wl(wl({},i),l!==void 0&&{method:l}),o.output!==void 0&&{output:o.output}),c!==void 0&&{headers:c}),!n?.disableValidation){if(o.query&&(i.query=await xl(o.query,n?.query),i.query!==null&&typeof i.query==`object`)){let t=wl({},e.query);for(let e of Object.keys(t))n?.query&&Object.prototype.hasOwnProperty.call(n.query,e)&&(t[e]=n.query[e]);i.query=wl(wl({},t),i.query)}i=wl(wl({},i),{},{body:o.input?await xl(o.input,n?.body):n?.body,params:o.params?await xl(o.params,n?.params):n?.params})}return{url:t,options:i}}}return wl({url:t},(n!==void 0||e.query!==void 0)&&{options:i})}}),Qte=e=>{async function t(t,n){let r=wl(wl(wl({},e),n),{},{headers:bl(e?.headers,n?.headers),plugins:[...e?.plugins||[],Zte(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await Tl(t,r)}catch(e){return{data:null,error:{status:500,statusText:`Fetch Error`,message:`Fetch related error. Captured by catchAllError option. See error property for more details.`,error:e}}}return await Tl(t,r)}return t},El=e=>{if(typeof process>`u`)return;let t=e??`/api/auth`;if({}.NEXT_PUBLIC_AUTH_URL)return{}.NEXT_PUBLIC_AUTH_URL;if(typeof window>`u`){if({}.NEXTAUTH_URL)try{return{}.NEXTAUTH_URL}catch{}if({}.VERCEL_URL)try{let e={}.VERCEL_URL.startsWith(`http`)?``:`https://`;return`${new URL(`${e}${{}.VERCEL_URL}`).origin}${t}`}catch{}}},Dl=e=>e===`/sign-out`||e===`/update-user`||e===`/update-session`||e===`/sign-up/email`||e===`/sign-in/email`||e===`/delete-user`||e===`/verify-email`||e===`/revoke-sessions`||e===`/revoke-session`||e===`/revoke-other-sessions`||e===`/change-email`||e===`/change-password`,Ol=(e,t)=>{let n=`credentials`in Request.prototype,r=hte(e?.baseURL,e?.basePath,void 0,t)??El(e?.basePath)??`/api/auth`,i=e?.plugins?.flatMap(e=>e.fetchPlugins).filter(e=>e!==void 0)||[],a={id:`lifecycle-hooks`,name:`lifecycle-hooks`,hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:o,onError:s,onRequest:c,onResponse:l,...u}=e?.fetchOptions||{},d=Qte({baseURL:r,...n?{credentials:`include`}:{},method:`GET`,jsonParser(e){return e?tte(e,{strict:!1}):null},customFetchImpl:fetch,...u,plugins:[a,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[vte],...i]}),{$sessionSignal:f,session:p,broadcastSessionUpdate:m}=wte(d,e),h=!1,g=e=>{h||e===null||(h=!0,xte(p,e))},_=e?.plugins||[],v={},y={$sessionSignal:f,session:p},b={"/sign-out":`POST`,"/revoke-sessions":`POST`,"/revoke-other-sessions":`POST`,"/delete-user":`POST`},x=[{signal:`$sessionSignal`,matcher:Dl,callback(e){e===`/sign-out`?m(`signout`):(e===`/update-user`||e===`/update-session`)&&m(`updateUser`)}}];for(let e of _)e.getAtoms&&Object.assign(y,e.getAtoms?.(d)),e.pathMethods&&Object.assign(b,e.pathMethods),e.atomListeners&&x.push(...e.atomListeners);let S={notify:e=>{y[e].set(!y[e].get())},listen:(e,t)=>{y[e].subscribe(t)},atoms:y};for(let t of _)t.getActions&&(v=Ete(t.getActions?.(d,S,e)??{},v));return{get baseURL(){return r},pluginsActions:v,pluginsAtoms:y,pluginPathMethods:b,atomListeners:x,hydrateSession:g,$sessionSignal:f,$fetch:d,$store:S}};function kl(e){return typeof e==`object`&&!!e&&`get`in e&&typeof e.get==`function`&&`lc`in e&&typeof e.lc==`number`}function Al(e){return e.charAt(0).toUpperCase()+e.slice(1)}var jl=/[\p{Ll}\d]+|\p{Lu}+(?!\p{Ll})|\p{Lu}[\p{Ll}\d]+|\p{Lo}+/gu,Ml=/['\u2019]/g;function Nl(e){return e.replace(Ml,``).match(jl)??[]}function Pl(e){return Nl(e).map(e=>e.toLowerCase()).join(`-`)}function Fl(e,t,n){let r=t[e],{fetchOptions:i,query:a,...o}=n||{};return r||(i?.method?i.method:o&&Object.keys(o).length>0?`POST`:`GET`)}function Il(e,t,n,r,i){function a(o=[]){return new Proxy(function(){},{get(t,n){if(typeof n!=`string`||n===`then`||n===`catch`||n===`finally`)return;let r=[...o,n],i=e;for(let e of r)if(i&&typeof i==`object`&&e in i)i=i[e];else{i=void 0;break}return typeof i==`function`||kl(i)?i:a(r)},apply:async(e,a,s)=>{let c=`/`+o.map(Pl).join(`/`),l=s[0]||{},u=s[1]||{},{query:d,fetchOptions:f,...p}=l,m={...u,...f},h=Fl(c,n,l);return await t(c,{...m,body:h===`GET`?void 0:{...p,...m?.body||{}},query:d||m?.query,method:h,async onSuccess(e){if(await m?.onSuccess?.(e),!i||m.disableSignal)return;let t=i.filter(e=>e.matcher(c));if(!t.length)return;let n=new Set;for(let e of t){let t=r[e.signal];if(!t)return;if(n.has(e.signal))continue;n.add(e.signal);let i=t.get();setTimeout(()=>{t.set(!i)},10),e.callback?.(c)}}})}})}return a()}function Ll(e){let{pluginPathMethods:t,pluginsActions:n,pluginsAtoms:r,hydrateSession:i,$fetch:a,atomListeners:o,$store:s}=Ol(e),c={};for(let[e,t]of Object.entries(r))c[`use${Al(e)}`]=t;return Il({...n,...c,hydrateSession:i,$fetch:a,$store:s},a,t,r,o)}var Rl=(e,{$listPasskeys:t,$store:n})=>({signIn:{passkey:async(r,i)=>{let a=await e(`/passkey/generate-authenticate-options`,{method:`GET`,throw:!1});if(!a.data)return a;let o=a.data.extensions||r?.extensions?{...a.data.extensions||{},...r?.extensions||{}}:void 0,s;try{s=await jc({optionsJSON:{...a.data,extensions:o},useBrowserAutofill:r?.autoFill})}catch(e){return{data:null,error:{code:e instanceof xc?e.code:`AUTH_CANCELLED`,message:pc.AUTH_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}}try{let{clientExtensionResults:a,...o}=s,c=await e(`/passkey/verify-authentication`,{body:{response:o},...r?.fetchOptions,...i,method:`POST`,throw:!1});return t.set(Math.random()),n.notify(`$sessionSignal`),r?.returnWebAuthnResponse?{...c,webauthn:{response:s,clientExtensionResults:a}}:c}catch(e){return console.error(`[Better Auth] Error verifying passkey`,e),{data:null,error:{code:`AUTH_CANCELLED`,message:pc.AUTH_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}}}},passkey:{addPasskey:async(r,i)=>{let a=await e(`/passkey/generate-register-options`,{method:`GET`,query:{...r?.authenticatorAttachment&&{authenticatorAttachment:r.authenticatorAttachment},...r?.name&&{name:r.name},...r?.context&&{context:r.context}},throw:!1});if(!a.data)return a;try{let o=a.data.extensions||r?.extensions?{...a.data.extensions||{},...r?.extensions||{}}:void 0,s=await Ec({optionsJSON:{...a.data,extensions:o},useAutoRegister:r?.useAutoRegister}),{clientExtensionResults:c,...l}=s,u=await e(`/passkey/verify-registration`,{...r?.fetchOptions,...i,body:{response:l,name:r?.name,...r?.createSession&&{createSession:!0}},method:`POST`,throw:!1});return u.data?(t.set(Math.random()),u.data.session&&n.notify(`$sessionSignal`),r?.returnWebAuthnResponse?{...u,webauthn:{response:s,clientExtensionResults:c}}:u):u}catch(e){return e instanceof xc?e.code===`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`?{data:null,error:{code:e.code,message:pc.PREVIOUSLY_REGISTERED.message,status:400,statusText:`BAD_REQUEST`}}:e.code===`ERROR_CEREMONY_ABORTED`?{data:null,error:{code:e.code,message:pc.REGISTRATION_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}:{data:null,error:{code:e.code,message:e.message,status:400,statusText:`BAD_REQUEST`}}:{data:null,error:{code:`UNKNOWN_ERROR`,message:e instanceof Error?e.message:pc.UNKNOWN_ERROR.message,status:500,statusText:`INTERNAL_SERVER_ERROR`}}}}},$Infer:{}}),zl=()=>{let e=Vc();return{id:`passkey`,version:mc,$InferServerPlugin:{},getActions:(t,n)=>Rl(t,{$listPasskeys:e,$store:n}),getAtoms(t){return{listPasskeys:ate(e,`/passkey/list-user-passkeys`,t,{method:`GET`}),$listPasskeys:e}},pathMethods:{"/passkey/register":`POST`,"/passkey/authenticate":`POST`},atomListeners:[{matcher(e){return e===`/passkey/verify-registration`||e===`/passkey/delete-passkey`||e===`/passkey/update-passkey`||e===`/sign-out`},signal:`$listPasskeys`},{matcher:e=>e===`/passkey/verify-authentication`,signal:`$sessionSignal`}],$ERROR_CODES:pc}},Bl=fc({OTP_EXPIRED:`OTP expired`,INVALID_OTP:`Invalid OTP`,TOO_MANY_ATTEMPTS:`Too many attempts`}),Vl=()=>({id:`email-otp`,version:Mc,$InferServerPlugin:{},atomListeners:[{matcher:e=>e===`/email-otp/verify-email`||e===`/sign-in/email-otp`||e===`/email-otp/request-email-change`,signal:`$sessionSignal`}],$ERROR_CODES:Bl}),Hl=e=>{let t=e?.jwks?.jwksPath??`/jwks`;return{id:`better-auth-client`,version:Mc,$InferServerPlugin:{},pathMethods:{[t]:`GET`},getActions:(e,n,r)=>({jwks:async n=>await e(t,{method:`GET`,...n})})}},Ul=fc({OTP_NOT_ENABLED:`OTP not enabled`,OTP_NOT_CONFIGURED:`OTP is not available`,OTP_HAS_EXPIRED:`OTP has expired`,TOTP_NOT_ENABLED:`TOTP not enabled`,TOTP_ALREADY_ENABLED:`TOTP is already enabled`,TOTP_NOT_CONFIGURED:`TOTP is not available`,TWO_FACTOR_NOT_ENABLED:`Two factor isn't enabled`,BACKUP_CODES_NOT_ENABLED:`Backup codes aren't enabled`,INVALID_BACKUP_CODE:`Invalid backup code`,INVALID_CODE:`Invalid code`,TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:`Too many attempts. Please request a new code.`,ACCOUNT_TEMPORARILY_LOCKED:`Too many failed verification attempts. Your account is temporarily locked. Please try again later.`,INVALID_TWO_FACTOR_COOKIE:`Invalid two factor cookie`}),Wl=e=>({id:`two-factor`,version:Mc,$InferServerPlugin:{},atomListeners:[{matcher:e=>e.startsWith(`/two-factor/`),signal:`$sessionSignal`}],pathMethods:{"/two-factor/disable":`POST`,"/two-factor/enable":`POST`,"/two-factor/send-otp":`POST`,"/two-factor/generate-backup-codes":`POST`,"/two-factor/get-totp-uri":`POST`,"/two-factor/verify-totp":`POST`,"/two-factor/verify-otp":`POST`,"/two-factor/verify-backup-code":`POST`},fetchPlugins:[{id:`two-factor`,name:`two-factor`,hooks:{async onSuccess(t){if(t.data?.twoFactorRedirect){if(e?.onTwoFactorRedirect){await e.onTwoFactorRedirect({twoFactorMethods:t.data.twoFactorMethods});return}e?.twoFactorPage&&typeof window<`u`&&dl(e.twoFactorPage)&&(window.location.href=e.twoFactorPage)}}}}],$ERROR_CODES:Ul}),Gl=(e,t,n)=>Ll({baseURL:e,basePath:t,plugins:[Hl(),Vl(),Wl(),zl()],fetchOptions:{customFetchImpl:n}}),Kl=e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?JSON.parse(e):[],ql=e=>{let t=e.split(`,`);return t.includes(`owner`)?`owner`:t.includes(`admin`)?`admin`:`member`},Jl=e=>({id:e.id,userId:e.userId,name:e.user.name||e.user.email,email:e.user.email,role:ql(e.role),appRoles:Kl(e.appRoles),createdAt:new Date(e.createdAt).toISOString()}),Yl=e=>({id:e.id,email:e.email,role:ql(e.role),appRoles:Kl(e.appRoles),status:e.status,expiresAt:new Date(e.expiresAt).toISOString(),...e.organizationName&&{organizationName:e.organizationName}}),Xl=(e,t)=>{let n=async(t,n,r={})=>{let{data:i,error:a}=await e.$fetch(t,{method:r.method??(r.body?`POST`:`GET`),...r.body&&{body:r.body},...r.query&&{query:r.query}});if(a)throw uc(a,n);return i},r=async e=>(await t(),e);return{list:async()=>await n(`/organization/list`,`Could not read your organizations`)??[],current:()=>n(`/organization/current`,`Could not read the current organization`),switchTo:async e=>r(await n(`/organization/switch`,`Could not switch the organization`,{body:{organizationId:e}})),search:async e=>(await n(`/organization/search`,`Could not search the organizations`,{query:{query:e}})).organizations,create:async e=>r(await n(`/organization/create`,`Could not create the organization`,{body:e})),rename:(e,t)=>n(`/organization/update`,`Could not change the organization`,{body:{organizationId:e,data:t}}),remove:async e=>r(await n(`/organization/delete`,`Could not delete the organization`,{body:{organizationId:e}})),leave:async e=>r(await n(`/organization/leave`,`Could not leave the organization`,{body:{organizationId:e}})),members:async e=>(await n(`/organization/list-members`,`Could not read the members`,{query:{organizationId:e,limit:`1000`}})).members.map(Jl),setRole:(e,t,r)=>n(`/organization/update-member-role`,`Could not change the role`,{body:{organizationId:e,memberId:t,role:r}}),setAppRoles:(e,t)=>n(`/organization/set-app-roles`,`Could not change the app roles`,{body:{memberId:e,appRoles:t}}),removeMember:(e,t)=>n(`/organization/remove-member`,`Could not remove the member`,{body:{organizationId:e,memberIdOrEmail:t}}),transferOwnership:(e,t=`admin`)=>n(`/organization/transfer-ownership`,`Could not hand the organization over`,{body:{memberId:e,keepAs:t}}),invitations:async e=>(await n(`/organization/list-invitations`,`Could not read the invitations`,{query:{organizationId:e}})??[]).map(Yl),invite:async(e,t)=>{let r=await n(`/organization/invite-member`,`Could not send the invitation`,{body:{organizationId:e,...t}});return{invitation:Yl(r),...r.link&&{link:r.link}}},resend:async(e,t)=>{let r=await n(`/organization/invite-member`,`Could not send the invitation again`,{body:{organizationId:e,email:t.email,role:t.role,resend:!0}});return{invitation:Yl(r),...r.link&&{link:r.link}}},revoke:e=>n(`/organization/cancel-invitation`,`Could not revoke the invitation`,{body:{invitationId:e}}),myInvitations:async()=>(await n(`/organization/list-user-invitations`,`Could not read your invitations`)??[]).map(Yl),invitation:e=>n(`/invitation`,`This invitation link is not valid`,{query:{token:e}}),accept:async e=>r(await n(`/invitation/accept`,`Could not accept the invitation`,{body:{token:e}})),signUpFromInvitation:async(e,t)=>r(await n(`/invitation/sign-up`,`Could not create your account`,{body:{token:e,...t}}))}},Zl=(e,t)=>({current:async()=>{let{data:t,error:n}=await e.$fetch(`/role/current`,{method:`GET`});if(n)throw uc(n,`Could not read your roles`);return t},switchTo:async n=>{let{error:r}=await e.$fetch(`/role/switch`,{method:`POST`,body:{role:n}});if(r)throw uc(r,`Could not switch the role`);await t()}}),Ql=(e,t)=>{let n=async e=>e?.twoFactorRedirect?{kind:`two-factor`,methods:e.twoFactorMethods??[]}:(await t(),{kind:`signed-in`,user:e?.user});return{signIn:async(t,r)=>{let{data:i,error:a}=await e.signIn.email({email:t,password:r});if(a||!i)throw uc(a,`Sign-in failed`);return n(i)},sendSignInCode:async t=>{let{error:n}=await e.emailOtp.sendVerificationOtp({email:t,type:`sign-in`});if(n)throw uc(n,`Could not send the code`)},signInWithCode:async(t,r)=>{let{data:i,error:a}=await e.signIn.emailOtp({email:t,otp:r});if(a||!i)throw uc(a,`Sign-in failed`);return n(i)},sendSignUpCode:async t=>{let{error:n}=await e.$fetch(`/sign-up/send-code`,{method:`POST`,body:{email:t}});if(n)throw uc(n,`Could not send the code`)},verifySignUpCode:async(t,n)=>{let{data:r,error:i}=await e.$fetch(`/sign-up/verify-code`,{method:`POST`,body:{email:t,code:n}});if(i||!r)throw uc(i,`Could not check the code`);return r.ticket},signUp:async n=>{let{data:r,error:i}=await e.$fetch(`/sign-up/create`,{method:`POST`,body:n});if(i||!r)throw uc(i,`Could not create your account`);return await t(),r.user},signInWithPasskey:async n=>{let r=await e.$fetch(`/passkey/generate-authenticate-options`,{method:`GET`,...n&&{query:{rpId:n}}});if(r.error||!r.data)throw uc(r.error,`Sign-in failed`);let{clientExtensionResults:i,...a}=await jc({optionsJSON:r.data}).catch(e=>{throw new lc(`Auth cancelled`,400,e instanceof xc?e.code:`AUTH_CANCELLED`)}),o=await e.$fetch(`/passkey/verify-authentication`,{method:`POST`,body:{response:a}});if(o.error||!o.data)throw uc(o.error,`Sign-in failed`);return await t(),o.data.user},sendTwoFactorCode:async()=>{let{error:t}=await e.twoFactor.sendOtp();if(t)throw uc(t,`Could not send the code`)},verifyTwoFactor:async({method:n,code:r,trustDevice:i=!1})=>{let{data:a,error:o}=await(n===`totp`?e.twoFactor.verifyTotp:n===`otp`?e.twoFactor.verifyOtp:e.twoFactor.verifyBackupCode)({code:r,trustDevice:i});if(o||!a)throw uc(o,`The code did not work`);return await t(),a.user}}},$l=e=>({read:async()=>{let{data:t,error:n}=await e.$fetch(`/policy/sign-in`);if(n||!t)throw uc(n,`Could not read the sign-in policy`);return t},save:async t=>{let{data:n,error:r}=await e.$fetch(`/policy/sign-in`,{method:`POST`,body:t});if(r||!n)throw uc(r,`Could not save the sign-in policy`);return n}}),eu=e=>new Date(e).toISOString(),tu=({startedAt:e,expiresAt:t,endedAt:n,...r})=>({...r,startedAt:eu(e),expiresAt:eu(t),...n&&{endedAt:eu(n)}}),nu=e=>({start:async t=>{let{data:n,error:r}=await e.$fetch(`/staff/sign-in`,{method:`POST`,body:t});if(r||!n?.url)throw uc(r,`Could not start the staff sign-in`);return n.url},current:async()=>{let{data:t,error:n}=await e.$fetch(`/staff/session`);if(n||!t)throw uc(n,`Could not read the session`);return t.staff?tu(t.staff):void 0},stop:async()=>{let{error:t}=await e.$fetch(`/staff/stop`,{method:`POST`,body:{}});if(t)throw uc(t,`Could not end the staff session`)},log:async()=>{let{data:t,error:n}=await e.$fetch(`/staff/sign-ins`);if(n||!t)throw uc(n,`Could not read the staff sign-ins`);return t.signIns.map(tu)}}),ru=e=>{let t=e.split(`.`)[1];if(!t)throw Error(`Not a JWT`);let n=JSON.parse(atob(t.replace(/-/g,`+`).replace(/_/g,`/`)));if(typeof n.exp!=`number`)throw Error(`The token has no expiry`);return n.exp*1e3},iu=(e={})=>{let t=e.origin??globalThis.location?.origin??`http://localhost`,n=e.basePath??`/api/auth`,r=e.refreshMarginMs??6e4,i=e.fetch??((e,t)=>fetch(e,t)),a=Gl(t,n,i),o=nu(a),s,c,l,u=()=>{s=void 0,clearTimeout(l)},d=async()=>{let{data:t}=await a.$fetch(`/token`);if(!t?.token){u();return}return s={token:t.token,expiresAt:ru(t.token)},clearTimeout(l),l=setTimeout(()=>void f({refresh:!0}).then(t=>t||e.onSignedOut?.()),Math.max(1e3,s.expiresAt-Date.now()-r)),s.token},f=async({refresh:e=!1}={})=>!e&&s&&s.expiresAt-Date.now()>r?s.token:(c??=d().finally(()=>{c=void 0}),c);return{token:f,status:async()=>{let e=await i(`${t}${n}/status`);if(e.status===404)throw new lc(`This server has no sign-in. Is the API URL right?`,404);if(!e.ok)throw new lc(`Could not read the sign-in status`,e.status);let r=await e.json();return{needsAdmin:!!r.needsAdmin,signInMethods:r.signInMethods??[`password`],passwordReset:!!r.passwordReset,...r.signUp&&{signUp:!0},socialProviders:r.socialProviders??[],...r.platformSignIn&&{platformSignIn:r.platformSignIn},...r.staffSignIn&&{staffSignIn:r.staffSignIn},...r.passkeyDomains&&{passkeyDomains:r.passkeyDomains},...r.organizations&&{organizations:r.organizations},...r.anonymous&&{anonymous:!0},...r.plugins&&r.plugins.length>0&&{plugins:r.plugins}}},session:async()=>{let{data:e}=await a.getSession();return e?.user},...Ql(a,()=>f({refresh:!0})),signInSocial:async(e,t)=>{let{data:n,error:r}=await a.signIn.social({provider:e,callbackURL:t,errorCallbackURL:t,disableRedirect:!0});if(r||!n?.url)throw uc(r,`Sign-in failed`);return n.url},signOut:async()=>{u(),await a.signOut()},requestPasswordReset:async(e,t)=>{let{error:n}=await a.requestPasswordReset({email:e,redirectTo:t});if(n)throw uc(n,`Could not send the reset link`)},resetPassword:async(e,t)=>{let{error:n}=await a.resetPassword({token:e,newPassword:t});if(n)throw uc(n,`Could not set the password`)},account:dc(a),organizations:Xl(a,()=>f({refresh:!0})),roles:Zl(a,()=>f({refresh:!0})),signInPolicy:$l(a),staff:{...o,stop:async()=>{u(),await o.stop()}}}},au=e=>Math.min(3e4,1e3*2**e),ou=(e,t)=>new Promise(n=>{let r=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(r),n()},{once:!0})}),su=`http://same-origin.invalid`,cu=(e,t)=>{let n=new URL(e,su),r=new URL(t,`${n.href}/`);if(r.origin!==n.origin)throw Error(`${t} is not on the assistant backend's origin`);return n.origin===su?`${r.pathname}${r.search}`:r.href},lu=e=>{let t=e.url.replace(/\/+$/,``),n=e.fetch??((e,t)=>fetch(e,t)),r=e.retryDelayMs??au,i=async(r,i)=>{let a=await e.token(),o=await n(`${t}${r}`,{method:i.method,headers:{...i.body===void 0?{accept:`text/event-stream`}:{"content-type":`application/json`},...a&&{authorization:`Bearer ${a}`}},body:i.body===void 0?void 0:JSON.stringify(i.body),signal:i.signal});if(!o.ok)throw await Ls(o);return o},a=async(e,t,n)=>{let r=await i(`/events`,{method:`GET`,signal:e});if(!r.body)throw Error(`The assistant backend answered the event stream without a body`);n(),await ns(r.body,e=>t(JSON.parse(e)),e)};return{connect:(e,t)=>{let n=new AbortController,{signal:i}=n;return(async()=>{let n=0;for(;!i.aborted;){t?.({state:`connecting`});let o=await a(i,e,()=>{n=0,t?.({state:`open`})}).then(()=>void 0,e=>e??Error(`The assistant stream failed`));if(i.aborted)return;t?.({state:`retrying`,...o!==void 0&&{error:o}}),await ou(r(n++),i)}})(),()=>n.abort()},send:async(e,t)=>{await i(`/messages`,{method:`POST`,body:{text:e,...t&&{page:t}}})},act:async(e,t)=>{await i(`/actions`,{method:`POST`,body:{partId:e,actionId:t}})},fetch:async(r,i={})=>{let a=cu(t,r),o=await e.token(),s=new Headers(i.headers);o&&s.set(`authorization`,`Bearer ${o}`);let c=await n(a,{...i,headers:s});if(!c.ok)throw await Ls(c);return c}}},uu=e=>typeof e==`object`&&!!e&&`error`in e&&typeof e.error==`object`&&e.error!==null&&`code`in e.error&&`message`in e.error,du=async e=>{let t=e.headers.get(`content-type`)?.includes(`json`)??!1?await e.clone().json():void 0;return uu(t)?new Ns({type:`urn:protobase:problem:${t.error.code}`,title:e.statusText||`Request failed`,status:e.status,detail:t.error.message}):Ls(e)},fu=e=>{let t=e.url.replace(/\/+$/,``),n=e.fetch??((e,t)=>fetch(e,t)),r=async(r,i)=>{let a=await e.token(),o=await n(`${t}${r}`,{method:i,headers:{accept:`application/json`,...a&&{authorization:`Bearer ${a}`}}});if(!o.ok)throw await du(o);return await o.json()};return{status:()=>r(``,`GET`),update:()=>r(`/update`,`POST`)}},B=(...e)=>e.filter(Boolean).join(` `),pu=e=>(0,o.useSyncExternalStore)(t=>{let n=window.matchMedia(e);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)},()=>window.matchMedia(e).matches,()=>!1),mu=()=>pu(`(min-width: 768px)`),hu=()=>pu(`not all and (min-width: 640px)`),V=t(a(),1),gu=e=>e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey,_u=`flex min-h-[49px] min-w-0 flex-1 flex-col items-center justify-center gap-1 pb-1 pt-1.5 text-[10px] font-medium leading-none`,vu=({tabs:e,onNavigate:t,onMore:n,moreOpen:r,moreControls:i,sticky:a,ref:o})=>{let s=!e.some(e=>e.active);return(0,V.jsxs)(`nav`,{ref:o,"aria-label":`Tabs`,className:B(`flex shrink-0 border-t bg-background pb-[env(safe-area-inset-bottom)] md:hidden`,a&&`sticky bottom-0 z-30`),children:[e.map(e=>{let n=e.icon;return(0,V.jsxs)(`a`,{href:e.href,"aria-current":e.active?`page`:void 0,...e.external?{target:`_blank`,rel:`noreferrer`}:{},onClick:n=>{!e.external&&t&&gu(n)&&(n.preventDefault(),t(e.href))},className:B(_u,e.active?`text-primary-text`:`text-muted-foreground`),children:[(0,V.jsx)(n,{className:`size-6`,strokeWidth:e.active?2.2:1.9,"aria-hidden":!0}),(0,V.jsx)(`span`,{className:`max-w-full truncate px-0.5`,children:e.label})]},e.id)}),(0,V.jsxs)(`button`,{type:`button`,"aria-expanded":r,"aria-controls":i,"data-current":s||void 0,onClick:n,className:B(_u,s?`text-primary-text`:`text-muted-foreground`),children:[(0,V.jsx)(Ke,{className:`size-6`,strokeWidth:s?2.2:1.9,"aria-hidden":!0}),`More`]})]})},yu=`data-pb-scroll-locked`,bu=()=>{let{body:e,documentElement:t}=document,n=e.style.overflow,r=t.hasAttribute(yu);return window.innerWidth>t.clientWidth&&t.setAttribute(yu,``),e.style.overflow=`hidden`,()=>{e.style.overflow=n,r||t.removeAttribute(yu)}},xu=`a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`,Su=[],Cu=(e,t,n)=>{let r=(0,o.useRef)(n);r.current=n,(0,o.useEffect)(()=>{if(!t||!e.current)return;let n=e.current,i=document.activeElement instanceof HTMLElement?document.activeElement:null,a=bu(),o={};Su.push(o);let s=()=>[...n.querySelectorAll(xu)];(s()[0]??n).focus();let c=e=>{if(Su.at(-1)!==o)return;if(e.key===`Escape`)return r.current();if(e.key!==`Tab`)return;let t=s();if(t.length===0)return e.preventDefault();let i=t[0],a=t[t.length-1];e.shiftKey&&document.activeElement===i?(e.preventDefault(),a.focus()):!e.shiftKey&&document.activeElement===a?(e.preventDefault(),i.focus()):n.contains(document.activeElement)||(e.preventDefault(),i.focus())};return document.addEventListener(`keydown`,c),()=>{document.removeEventListener(`keydown`,c),Su.splice(Su.indexOf(o),1),a(),i?.focus()}},[t,e])},wu=({id:e,open:t,onClose:n,children:r})=>{let i=(0,o.useRef)(null);return Cu(i,t,n),t?(0,V.jsxs)(`div`,{className:`fixed inset-0 z-50 md:hidden`,children:[(0,V.jsx)(`div`,{className:`absolute inset-0 bg-backdrop/40`,onClick:n,"aria-hidden":!0}),(0,V.jsx)(`div`,{ref:i,id:e,role:`dialog`,"aria-modal":`true`,"aria-label":`Navigation`,tabIndex:-1,className:`absolute inset-y-0 left-0 flex w-60 max-w-[85vw] bg-sidebar shadow-pop outline-none`,onClick:e=>e.target.closest(`a`)&&n(),children:r})]}):null},Tu=(0,o.createContext)(()=>{}),Eu=e=>{let t=(0,o.useContext)(Tu);(0,o.useLayoutEffect)(()=>(t(e),()=>t(void 0)),[t,e])},Du=e=>{(0,o.useLayoutEffect)(()=>{if(!e)return;let t=document.documentElement;return t.style.setProperty(`scrollbar-gutter`,`stable`),()=>{t.style.removeProperty(`scrollbar-gutter`)}},[e])},Ou=[`--pb-sticky-top`,`--pb-sticky-bottom`,`scroll-padding-top`,`scroll-padding-bottom`],ku=(e,t,n,r)=>{(0,o.useLayoutEffect)(()=>{if(!e)return;let r=document.documentElement,i=()=>{let e=`${t.current?.offsetHeight??0}px`,i=`${n.current?.offsetHeight??0}px`;r.style.setProperty(`--pb-sticky-top`,e),r.style.setProperty(`--pb-sticky-bottom`,i),r.style.setProperty(`scroll-padding-top`,e),r.style.setProperty(`scroll-padding-bottom`,i)},a=new ResizeObserver(i);for(let e of[t.current,n.current])e&&a.observe(e);return i(),()=>{a.disconnect();for(let e of Ou)r.style.removeProperty(e)}},[e,t,n,r])},Au=({className:e})=>(0,V.jsx)(`span`,{className:B(`block h-3 rounded bg-muted [animation:pb-shimmer_1.4s_ease-in-out_infinite]`,e)}),ju=e=>e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey,Mu=({parts:e,onNavigate:t})=>(0,V.jsx)(`nav`,{"aria-label":`Breadcrumb`,className:`flex min-w-0 items-center gap-1.5`,children:e.map((n,r)=>{let i=r===e.length-1,{label:a,href:o,loading:s}=typeof n==`string`?{label:n,href:void 0,loading:!1}:n,c=s?(0,V.jsx)(Au,{className:`w-24`}):a,l=B(`truncate`,i?`font-semibold`:`text-muted-foreground`);return(0,V.jsxs)(`span`,{className:B(`min-w-0 items-center gap-1.5`,i?`flex`:`hidden md:flex`),children:[r>0&&(0,V.jsx)(xe,{className:`hidden size-3.5 shrink-0 text-faint-foreground md:block`}),o?(0,V.jsx)(`a`,{href:o,"aria-current":i?`page`:void 0,"aria-label":s?a:void 0,"aria-busy":s||void 0,onClick:e=>{t&&ju(e)&&(e.preventDefault(),t(o))},className:B(l,`rounded-sm hover:text-foreground hover:underline`),children:c}):(0,V.jsx)(`span`,{className:l,"aria-label":s?a:void 0,"aria-busy":s||void 0,children:c})]},`${r}-${a}`)})}),Nu=({to:e,onClick:t,...n})=>(0,V.jsx)(`a`,{href:e.href,onClick:n=>{t?.(n),!n.defaultPrevented&&ju(n)&&(n.preventDefault(),e.onFollow())},...n}),Pu=`M312.3 9.9Q257 9.9 217.1 -21.1Q177.3 -52.1 168.4 -108.8L181.1 -110.3V205H54.8V-510H176.7V-404.5L168.3 -407Q179.7 -460.8 221.2 -490.4Q262.7 -520 319.8 -520Q376.2 -520 417 -488.4Q457.8 -456.8 479.8 -398.6Q501.8 -340.5 501.8 -259.9Q501.8 -177.6 478.3 -116.8Q454.9 -55.9 412.5 -23Q370.1 9.9 312.3 9.9ZM274.4 -92.6Q320.2 -92.6 345.8 -133.8Q371.4 -175.1 371.4 -256.4Q371.4 -337.7 345.7 -377.6Q320.1 -417.5 274 -417.5Q228.6 -417.5 202.7 -376.4Q176.9 -335.3 176.9 -254Q176.9 -173.3 202.7 -132.9Q228.4 -92.6 274.4 -92.6Z M549.8 0V-510H671.7V-388.3H676.1V0H549.8ZM676.1 -286.5 661.3 -386.2Q677.9 -455.2 711.8 -487.6Q745.7 -520 794.3 -520Q809 -520 818 -516.6V-394.2Q814.2 -395.6 807.1 -396.1Q800 -396.6 789.4 -396.6Q734.6 -396.6 705.3 -370.5Q676.1 -344.4 676.1 -286.5Z M1043.8 10Q974.7 10 922.6 -23.6Q870.6 -57.2 842.1 -117.5Q813.6 -177.8 813.6 -257Q813.6 -336.5 842.2 -395.5Q870.8 -454.5 922.5 -487.2Q974.2 -520 1043.8 -520Q1113.7 -520 1165.4 -487.2Q1217.1 -454.5 1245.6 -395.5Q1274 -336.5 1274 -257Q1274 -177.8 1245.5 -117.5Q1217 -57.2 1165.3 -23.6Q1113.6 10 1043.8 10ZM1043.8 -90.5Q1073.5 -90.5 1095.9 -108.9Q1118.2 -127.3 1130.9 -164.4Q1143.6 -201.5 1143.6 -257.5Q1143.6 -339.8 1116 -379.7Q1088.4 -419.5 1043.8 -419.5Q999.3 -419.5 971.6 -379.5Q944 -339.5 944 -257.5Q944 -201.5 956.7 -164.4Q969.4 -127.3 991.8 -108.9Q1014.3 -90.5 1043.8 -90.5Z M1509 10.2Q1427.2 10.2 1387.6 -29.2Q1348 -68.6 1348 -147.7V-613.8L1474.2 -666.1V-146.7Q1474.2 -118.4 1489.9 -104.3Q1505.6 -90.3 1539.2 -90.3Q1552 -90.3 1562.7 -92.5Q1573.3 -94.8 1582.5 -98.7V-1.9Q1571.6 4 1552 7.1Q1532.4 10.2 1509 10.2ZM1270.1 -411V-510H1580.6V-411H1270.1Z M1810.8 10Q1741.7 10 1689.6 -23.6Q1637.6 -57.2 1609.1 -117.5Q1580.6 -177.8 1580.6 -257Q1580.6 -336.5 1609.2 -395.5Q1637.8 -454.5 1689.5 -487.2Q1741.2 -520 1810.8 -520Q1880.7 -520 1932.4 -487.2Q1984.1 -454.5 2012.6 -395.5Q2041 -336.5 2041 -257Q2041 -177.8 2012.5 -117.5Q1984 -57.2 1932.3 -23.6Q1880.6 10 1810.8 10ZM1810.8 -90.5Q1840.5 -90.5 1862.9 -108.9Q1885.2 -127.3 1897.9 -164.4Q1910.6 -201.5 1910.6 -257.5Q1910.6 -339.8 1883 -379.7Q1855.4 -419.5 1810.8 -419.5Q1766.3 -419.5 1738.6 -379.5Q1711 -339.5 1711 -257.5Q1711 -201.5 1723.7 -164.4Q1736.4 -127.3 1758.8 -108.9Q1781.3 -90.5 1810.8 -90.5Z M2343.3 9.9Q2288 9.9 2247.7 -21.1Q2207.4 -52.1 2198.5 -108.8L2205.8 -110.3V0H2085.8V-720H2212.1V-404.5L2203.7 -407Q2215.1 -460.8 2255.6 -490.4Q2296.2 -520 2351 -520Q2407.3 -520 2448 -488.4Q2488.8 -456.8 2510.8 -398.6Q2532.8 -340.5 2532.8 -259.9Q2532.8 -177.6 2509.3 -116.8Q2485.9 -55.9 2443.5 -23Q2401.1 9.9 2343.3 9.9ZM2305.4 -92.6Q2350.7 -92.6 2376.6 -133.8Q2402.4 -175.1 2402.4 -256.4Q2402.4 -337.7 2376.5 -377.6Q2350.6 -417.5 2305 -417.5Q2260.5 -417.5 2234.2 -376.4Q2207.9 -335.3 2207.9 -254Q2207.9 -173.3 2234.1 -132.9Q2260.3 -92.6 2305.4 -92.6Z M2834 0Q2828 -19.1 2825.7 -41.7Q2823.3 -64.2 2823.3 -91.8H2818.6V-356Q2818.6 -391.9 2803.1 -409.1Q2787.5 -426.3 2756.2 -426.3Q2724.2 -426.3 2706.4 -408.7Q2688.7 -391.2 2686.3 -358.9H2571.2Q2574.6 -429.6 2625.4 -474.8Q2676.1 -520 2763.5 -520Q2850.2 -520 2896.1 -476.5Q2941.9 -432.9 2941.9 -352.2V-91.8Q2941.9 -69.5 2944.7 -46.7Q2947.5 -23.8 2954.1 0H2834ZM2690.6 10Q2631.9 10 2595.4 -26.3Q2558.9 -62.5 2558.9 -124.5Q2558.9 -185 2594.3 -224Q2629.8 -263 2704.5 -287.6L2845.4 -337.4V-248.7L2753.4 -219.3Q2716.5 -206.1 2699.3 -186.6Q2682.2 -167.2 2682.2 -139Q2682.2 -112.4 2697.5 -98.4Q2712.9 -84.3 2739.4 -84.3Q2773.2 -84.3 2795.9 -104.1Q2818.6 -123.9 2818.6 -153.1L2829.9 -85.8Q2812.6 -37.4 2776.8 -13.7Q2741 10 2690.6 10Z M3168 10Q3080.6 10 3030.1 -34.2Q2979.6 -78.4 2974.7 -158.1H3082.4Q3086.3 -120 3108.9 -100.5Q3131.5 -80.9 3169.8 -80.9Q3202 -80.9 3218.9 -93.9Q3235.8 -106.9 3235.8 -131.3Q3235.8 -151.1 3224.3 -165.6Q3212.9 -180.1 3178.9 -195.4L3111.2 -224.8Q3053 -247.7 3023.8 -284.2Q2994.5 -320.8 2994.5 -373.9Q2994.5 -440.1 3040.1 -480Q3085.7 -520 3162.8 -520Q3242.2 -520 3288.4 -480Q3334.6 -440 3339.5 -367.9H3231.8Q3228.6 -399.7 3211.3 -414.4Q3194 -429.1 3164 -429.1Q3136.1 -429.1 3120.5 -417Q3104.8 -405 3104.8 -382.7Q3104.8 -364.2 3117.7 -349.8Q3130.6 -335.5 3162.4 -321.6L3236.6 -289.6Q3288.6 -269.2 3317.4 -229.2Q3346.1 -189.1 3346.1 -136.9Q3346.1 -69 3299.2 -29.5Q3252.3 10 3168 10Z M3587.8 10Q3520 10 3469.2 -23.3Q3418.5 -56.6 3390.5 -116.5Q3362.6 -176.3 3362.6 -255.8Q3362.6 -336.4 3390.9 -395.7Q3419.3 -454.9 3470.7 -487.5Q3522 -520 3591.1 -520Q3656.6 -520 3702.7 -489.8Q3748.8 -459.7 3773.7 -403.1Q3798.6 -346.5 3798.6 -266.5Q3798.6 -253.7 3798 -242.5Q3797.5 -231.3 3795.8 -221.4H3440V-306.9H3709L3681.8 -277.9Q3681.6 -355.2 3657.7 -390.7Q3633.8 -426.3 3589.3 -426.3Q3541.7 -426.3 3515.6 -384Q3489.5 -341.7 3489.5 -255Q3489.5 -168.4 3515 -126.1Q3540.5 -83.7 3590.6 -83.7Q3623.7 -83.7 3644.6 -102Q3665.5 -120.3 3673.8 -156.3H3788.9Q3772.2 -81.6 3721.5 -35.8Q3670.8 10 3587.8 10Z`,Fu=`fill-[#ff5a1f] dark:fill-[#ff6a33]`,Iu=`fill-[#14161a] dark:fill-[#f1f0ea]`,Lu=({className:e})=>(0,V.jsxs)(`svg`,{viewBox:`0 0 32 32`,className:B(`size-7 shrink-0`,e),"aria-hidden":!0,children:[(0,V.jsx)(`path`,{className:Fu,fillRule:`evenodd`,d:`M0 5a5 5 0 0 1 5-5h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2zM4 5a1 1 0 0 1 1-1h5v6H4z`}),(0,V.jsx)(`path`,{className:Iu,d:`M17 0h10a5 5 0 0 1 5 5v22a5 5 0 0 1-5 5H5a5 5 0 0 1-5-5V17h17z`})]}),Ru=({className:e})=>(0,V.jsx)(`svg`,{viewBox:`54.8 -720 3743.8 925`,className:B(`h-3.5 w-auto`,e),role:`img`,"aria-label":`Protobase`,children:(0,V.jsx)(`path`,{className:Iu,d:Pu})}),zu=({compact:e,workspace:t})=>(0,V.jsxs)(`div`,{className:`flex items-center gap-2.5 overflow-hidden`,children:[(0,V.jsx)(Lu,{}),!e&&(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5 leading-tight`,children:[(0,V.jsx)(Ru,{className:`self-start`}),t&&(0,V.jsx)(`div`,{className:`truncate text-[11px] text-muted-foreground`,children:t})]})]}),Bu=[{label:`Sales`,items:[{id:`orders`,label:`Orders`,icon:bn,count:12},{id:`customers`,label:`Customers`,icon:le},{id:`invoices`,label:`Invoices`,icon:it,count:3}]},{label:`Inventory`,items:[{id:`products`,label:`Products`,icon:Xt},{id:`stock-moves`,label:`Stock moves`,icon:se},{id:`warehouses`,label:`Warehouses`,icon:Xn},{id:`shipments`,label:`Shipments`,icon:Hn}]},{label:`Finance`,items:[{id:`payments`,label:`Payments`,icon:ze},{id:`credit-notes`,label:`Credit notes`,icon:sn},{id:`reports`,label:`Reports`,icon:pe}]},{label:`Admin`,items:[{id:`users`,label:`Users`,icon:qn},{id:`settings`,label:`Settings`,icon:gn}]}],Vu={xs:`size-5 text-[9px]`,sm:`size-6 text-[10px]`,md:`size-8 text-xs`},Hu=({initials:e,hue:t,size:n=`sm`,className:r})=>(0,V.jsx)(`span`,{className:B(`inline-flex shrink-0 select-none items-center justify-center rounded-full font-semibold text-white ring-2 ring-background`,Vu[n],r),style:{background:`oklch(0.58 0.13 ${t})`},children:e}),Uu=({people:e,size:t=`sm`})=>(0,V.jsx)(`span`,{className:`inline-flex -space-x-1`,children:e.map(e=>(0,V.jsx)(Hu,{...e,size:t},e.initials))}),Wu=e=>{let t=e.slice(1),n=t.length===3?[...t].map(e=>e+e).join(``):t,[r,i,a]=[0,2,4].map(e=>{let t=Number.parseInt(n.slice(e,e+2),16)/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},Gu=`#ffffff`,Ku=`#111827`,qu=e=>{let t=Wu(e);return 1.05/(t+.05)>=(t+.05)/(Wu(Ku)+.05)?Gu:Ku},Ju={neutral:`bg-muted text-muted-foreground`,blue:`bg-primary-soft text-primary-text`,green:`bg-success-soft text-success-text`,amber:`bg-warning-soft text-warning-text`,red:`bg-danger-soft text-danger-text`,violet:`bg-violet-soft text-violet-text`},Yu={neutral:`bg-faint-foreground`,blue:`bg-primary`,green:`bg-success`,amber:`bg-warning`,red:`bg-danger`,violet:`bg-violet`},Xu=`polygon(0 0, calc(100% - 0.625rem) 0, 100% 50%, calc(100% - 0.625rem) 100%, 0 100%)`,Zu=({tone:e=`neutral`,dot:t=!0,color:n,shape:r,children:i,className:a})=>(0,V.jsxs)(`span`,{style:{...n!==void 0&&{backgroundColor:n,color:qu(n)},...r===`arrow`&&{clipPath:Xu}},className:B(r===`arrow`?`inline-flex h-5 items-center gap-1.5 rounded-l-sm pr-4 pl-2 text-xs font-semibold whitespace-nowrap`:`inline-flex h-5 items-center gap-1.5 rounded-full px-2 text-xs font-medium whitespace-nowrap`,n===void 0&&Ju[e],a),children:[t&&n===void 0&&r===void 0&&(0,V.jsx)(`span`,{className:B(`size-1.5 rounded-full`,Yu[e])}),i]}),Qu=({label:e,current:t,others:n,rowClassName:r,onSwitch:i})=>(0,V.jsxs)(`div`,{className:`border-b py-1`,role:`group`,"aria-label":e,children:[t&&(0,V.jsxs)(`div`,{className:B(r,`text-foreground hover:bg-transparent`),"aria-current":`true`,children:[(0,V.jsx)(he,{className:`size-4`}),(0,V.jsx)(`span`,{className:`truncate`,children:t.label})]}),n.map(e=>(0,V.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>i(e.id),className:r,children:[(0,V.jsx)(`span`,{className:`size-4`}),(0,V.jsx)(`span`,{className:`truncate`,children:e.label})]},e.id))]}),$u={sm:{group:`h-7`,option:`px-2.5 text-xs`},md:{group:`h-8`,option:`px-3 text-body`}},ed=({value:e,options:t,onChange:n,label:r,size:i=`sm`,iconOnly:a=!1})=>(0,V.jsx)(`span`,{role:`group`,"aria-label":r,className:B(`inline-flex`,$u[i].group,`rounded-md bg-muted p-0.5`),children:t.map(t=>(0,V.jsxs)(`button`,{type:`button`,"aria-pressed":t.value===e,...a&&{"aria-label":t.label,title:t.label},onClick:()=>n(t.value),className:B(`inline-flex items-center gap-1.5 rounded`,$u[i].option,`font-medium transition-colors`,t.value===e?`bg-background text-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`),children:[t.icon&&(0,V.jsx)(t.icon,{className:`size-3.5`}),!a&&t.label]},t.value))}),td=[{value:`light`,label:`Light`,icon:An},{value:`dark`,label:`Dark`,icon:Kt},{value:`system`,label:`System`,icon:Wt}],nd=({theme:e,className:t})=>(0,V.jsxs)(`div`,{className:t,children:[(0,V.jsx)(On,{className:`size-4`}),(0,V.jsx)(`span`,{className:`flex-1`,children:`Theme`}),(0,V.jsx)(ed,{label:`Theme`,iconOnly:!0,value:e.preference,options:td,onChange:e.onChange})]}),rd=`flex min-h-11 w-full items-center gap-2.5 px-3 py-1.5 text-left text-muted-foreground hover:bg-muted md:min-h-0`,id=({user:e,compact:t,open:n,items:r=[],onNavigate:i,onSignOut:a,organizations:s,roles:c,theme:l})=>{let u=c?.roles.find(e=>e.name===c.active),[d,f]=(0,o.useState)(!1),p=n??d,m=(0,o.useRef)(null),[h,g]=(0,o.useState)();return(0,o.useEffect)(()=>{if(!p||n!==void 0)return;let e=e=>{(e instanceof KeyboardEvent?e.key===`Escape`:!m.current?.contains(e.target))&&f(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,e)}},[p,n]),(0,V.jsxs)(`div`,{ref:m,className:`relative`,children:[(0,V.jsxs)(`button`,{type:`button`,className:`flex min-h-11 w-full items-center gap-2.5 rounded-md p-1 text-left hover:bg-muted md:min-h-0`,"aria-label":`Profile menu`,"aria-haspopup":`menu`,"aria-expanded":p,onClick:()=>{let e=m.current?.getBoundingClientRect();e&&g({left:e.left,bottom:window.innerHeight-e.top+8}),f(!d)},children:[(0,V.jsx)(Hu,{initials:e.initials,hue:e.hue,size:`md`,className:`ring-0`}),!t&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`span`,{className:`min-w-0 flex-1 leading-tight`,children:[(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:e.name}),(0,V.jsx)(Zu,{tone:e.roleTone,dot:!1,className:`mt-0.5 h-4 px-1.5 text-[10px]`,children:e.role})]}),(0,V.jsx)(Ce,{className:`size-3.5 shrink-0 text-faint-foreground`})]})]}),p&&(0,V.jsxs)(`div`,{role:`menu`,className:n===void 0?`fixed z-[60] w-56 overflow-hidden rounded-lg border bg-background py-1 shadow-pop`:`absolute bottom-full left-0 z-50 mb-2 w-56 overflow-hidden rounded-lg border bg-background py-1 shadow-pop`,style:n===void 0&&h?{left:h.left,bottom:h.bottom}:void 0,children:[(0,V.jsxs)(`div`,{className:`border-b px-3 pb-2 pt-1.5`,children:[(0,V.jsx)(`div`,{className:`font-medium`,children:e.name}),(0,V.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:e.email})]}),s&&(s.current||s.others.length>0)&&(0,V.jsx)(Qu,{label:`Organizations`,...s.current&&{current:{id:s.current.id,label:s.current.name}},others:s.others.map(({id:e,name:t})=>({id:e,label:t})),rowClassName:rd,onSwitch:e=>{f(!1),s.onSwitch(e)}}),c&&c.roles.length>1&&(0,V.jsx)(Qu,{label:`Roles`,...u&&{current:{id:u.name,label:u.label}},others:c.roles.filter(e=>e!==u).map(({name:e,label:t})=>({id:e,label:t})),rowClassName:rd,onSwitch:e=>{f(!1),c.onSwitch(e)}}),r.length>0&&(0,V.jsx)(`div`,{className:B((l||a)&&`border-b`),children:r.map(e=>{let t=e.icon;return(0,V.jsxs)(`a`,{role:`menuitem`,href:e.href,"aria-current":e.active?`page`:void 0,...e.external?{target:`_blank`,rel:`noreferrer`}:{},onClick:t=>{f(!1),!e.external&&i&&(t.preventDefault(),i(e.href))},className:B(rd,e.active&&`bg-muted text-foreground`),children:[(0,V.jsx)(t,{className:`size-4`}),e.label]},e.id)})}),l&&(0,V.jsx)(`div`,{className:B(a&&`border-b`),children:(0,V.jsx)(nd,{theme:l,className:B(rd,`hover:bg-transparent`)})}),a&&(0,V.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:a,className:rd,children:[(0,V.jsx)(Lt,{className:`size-4`}),`Sign out`]})]})]})},ad=(e,t)=>{try{return e()}catch(e){if(!(e instanceof DOMException))throw e;return t}},od=`protobase:nav-open:`,sd=e=>`${od}${e}`,cd=(e,t)=>ad(()=>e.getItem(t)!==`false`,!0),ld=(e,t,n)=>ad(()=>n?e.removeItem(t):e.setItem(t,`false`),void 0),ud=({label:e,side:t=`right`,visible:n,children:r})=>(0,V.jsxs)(`span`,{className:`group/tooltip relative inline-flex`,children:[r,(0,V.jsx)(`span`,{role:`tooltip`,className:B(`pointer-events-none absolute z-50 whitespace-nowrap rounded-md bg-foreground px-2 py-1 text-xs font-medium text-background opacity-0 shadow-md transition-opacity group-hover/tooltip:opacity-100`,n&&`opacity-100`,t===`right`&&`left-full top-1/2 ml-2 -translate-y-1/2`,t===`top`&&`bottom-full left-1/2 mb-2 -translate-x-1/2`,t===`bottom`&&`left-1/2 top-full mt-2 -translate-x-1/2`),children:e})]}),dd=e=>e===`text-large`||e===`text-small`||e===`icon-expand`,fd=e=>e===`text-large`||e===`text-small`,pd={"text-large":`w-60`,"text-small":`w-52`,icon:`w-14`,"icon-label":`w-[76px]`,"icon-tooltip":`w-14`,"icon-expand":`w-14`},md={"text-large":`h-9 gap-3 px-3 text-sm`,"text-small":`h-7 gap-2.5 px-2.5 text-xs`,icon:`size-9 justify-center`,"icon-label":`w-full flex-col gap-0.5 py-1.5 text-[10px]`,"icon-tooltip":`size-9 justify-center`,"icon-expand":`h-8 gap-3 px-3`},hd=({item:e,mode:t,active:n,onNavigate:r,className:i})=>{let a=e.icon,o=(0,V.jsxs)(`a`,{onClick:r&&(t=>{t.preventDefault(),r(e.href??`#${e.id}`)}),href:e.href??`#${e.id}`,"aria-label":e.problem?`${e.label}: ${e.problem}`:e.label,"aria-current":n?`page`:void 0,title:e.problem,className:B(`flex shrink-0 items-center rounded-md font-medium transition-colors`,md[t],n?`bg-primary-soft text-primary-text`:`text-muted-foreground hover:bg-muted hover:text-foreground`,i),children:[(0,V.jsx)(a,{className:B(`shrink-0`,t===`text-small`?`size-4`:`size-[18px]`),strokeWidth:n?2.2:1.9}),(dd(t)||t===`icon-label`)&&(0,V.jsx)(`span`,{className:`whitespace-nowrap`,children:e.label}),fd(t)&&e.count&&(0,V.jsx)(`span`,{className:`ml-auto rounded bg-muted px-1.5 text-[11px] tabular-nums text-muted-foreground`,children:e.count}),fd(t)&&e.problem&&(0,V.jsx)(Bn,{"aria-hidden":!0,className:`ml-auto size-3.5 shrink-0 text-warning-text`})]});return t===`icon-tooltip`?(0,V.jsx)(ud,{label:e.label,children:o}):o},gd={neutral:`bg-faint-foreground`,info:`bg-primary`,success:`bg-success`,warning:`bg-warning`,danger:`bg-danger`},_d=({tone:e,pulse:t=!1,className:n})=>(0,V.jsxs)(`span`,{"aria-hidden":!0,className:B(`relative flex size-2 shrink-0`,n),"data-tone":e,"data-pulse":t||void 0,children:[t&&(0,V.jsx)(`span`,{className:B(`absolute inset-0 animate-ping rounded-full opacity-60 motion-reduce:animate-none`,gd[e])}),(0,V.jsx)(`span`,{className:B(`relative size-2 rounded-full`,gd[e])})]}),vd={"text-large":`h-8 gap-2.5 px-2.5`,"text-small":`h-7 gap-2 px-2 text-xs`},yd={"text-large":`ml-[20px]`,"text-small":`ml-[17px]`},bd=({item:e,recent:t,mode:n,active:r,onNavigate:i})=>{let a=sd(e.id),[s,c]=(0,o.useState)(()=>cd(localStorage,a)),l=(0,o.useId)(),u=e.href??`#${e.id}`,d=()=>{ld(localStorage,a,!s),c(!s)},f=e=>({href:e,onClick:i&&(t=>{t.preventDefault(),i(e)})});return(0,V.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,V.jsxs)(`div`,{className:`relative`,children:[(0,V.jsx)(hd,{item:e,mode:n,active:r,onNavigate:i,className:`pr-8`}),(0,V.jsx)(`button`,{type:`button`,"aria-expanded":s,"aria-controls":l,"aria-label":`Recent ${e.label.toLowerCase()}`,onClick:d,className:`absolute right-1 top-1/2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground`,children:(0,V.jsx)(xe,{className:B(`size-3.5 transition-transform`,s&&`rotate-90`)})})]}),s&&(0,V.jsxs)(`ul`,{id:l,"aria-label":`Recent ${e.label.toLowerCase()}`,className:B(`flex flex-col gap-0.5 border-l pl-1.5`,yd[n]),children:[t.state===`loading`&&(0,V.jsx)(`li`,{className:B(`flex items-center text-faint-foreground`,vd[n]),children:`Loading...`}),t.state===`error`&&(0,V.jsx)(`li`,{className:B(`flex items-center text-faint-foreground`,vd[n]),children:`Could not load`}),t.state===`ready`&&t.records.map(e=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(`a`,{...f(e.href),"aria-label":`${e.label}, ${e.status}`,title:`${e.label} (${e.status})`,"aria-current":e.active?`page`:void 0,className:B(`flex min-w-0 items-center rounded-md font-medium transition-colors`,vd[n],e.active?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),children:[(0,V.jsx)(_d,{tone:e.tone,pulse:e.pulse}),(0,V.jsx)(`span`,{className:`truncate`,children:e.label})]})},e.id)),(0,V.jsx)(`li`,{children:(0,V.jsx)(`a`,{...f(u),className:B(`flex items-center rounded-md text-faint-foreground transition-colors hover:bg-muted hover:text-foreground`,vd[n]),children:`View all`})})]})]})},xd=({mode:e,activeItem:t,user:n,workspace:r,forceExpanded:i,profileMenuOpen:a,groups:o=Bu,userMenu:s,onNavigate:c,onSignOut:l,signIn:u,organizations:d,roles:f,theme:p,sticky:m,logo:h=zu})=>{let g=e===`icon-expand`,_=g&&i,v=fd(e)||g;return(0,V.jsx)(`nav`,{"aria-label":`Resources`,className:B(m?`sticky top-0 h-dvh self-start`:`relative`,`z-30 shrink-0`,pd[e]),children:(0,V.jsxs)(`div`,{className:B(`group/side absolute inset-y-0 left-0 flex flex-col overflow-hidden border-r bg-sidebar`,g?`w-14 transition-[width,box-shadow] duration-150 hover:w-60 hover:shadow-pop focus-within:w-60 focus-within:shadow-pop`:`w-full`,_&&`w-60 shadow-pop`),children:[(0,V.jsx)(`div`,{className:B(`flex h-12 shrink-0 items-center px-3.5`,e===`icon-label`&&`justify-center px-0`),children:(0,V.jsx)(h,{compact:!v,workspace:r})}),(0,V.jsx)(`div`,{className:B(`flex-1 overflow-y-auto overflow-x-hidden pb-2`,`px-2`),children:o.map((n,r)=>(0,V.jsxs)(`div`,{className:B(`flex flex-col gap-0.5`,r>0&&`mt-3`),children:[v?(0,V.jsx)(`div`,{className:B(`px-3 pb-1 pt-1 text-[11px] font-medium uppercase tracking-wide text-faint-foreground`,g&&`h-4 whitespace-nowrap py-0 opacity-0 transition-opacity group-hover/side:opacity-100 group-focus-within/side:opacity-100`,_&&`opacity-100`),children:n.label}):r>0&&(0,V.jsx)(`div`,{className:`mx-auto mb-1 h-px w-6 bg-border`}),n.items.map(n=>n.recent&&fd(e)?(0,V.jsx)(bd,{item:n,recent:n.recent,mode:e,active:n.id===t,onNavigate:c},n.id):(0,V.jsx)(hd,{item:n,mode:e,active:n.id===t,onNavigate:c},n.id))]},n.label))}),(0,V.jsx)(`div`,{className:B(`shrink-0 border-t p-2`,e!==`text-large`&&e!==`text-small`&&!g&&`flex justify-center`),children:n?(0,V.jsx)(id,{user:n,compact:!v,open:a,items:s,onNavigate:c,onSignOut:l,organizations:d,roles:f,theme:p}):(0,V.jsxs)(V.Fragment,{children:[p&&v&&(0,V.jsx)(nd,{theme:p,className:`flex min-h-11 w-full items-center gap-2.5 whitespace-nowrap p-1.5 text-muted-foreground md:min-h-0`}),u&&(0,V.jsxs)(Nu,{to:u,"aria-label":`Sign in`,className:`flex min-h-11 w-full items-center gap-2.5 rounded-md p-1.5 text-left font-medium text-muted-foreground hover:bg-muted hover:text-foreground md:min-h-0`,children:[(0,V.jsx)(Ft,{className:`size-4 shrink-0`}),v&&(0,V.jsx)(`span`,{className:`whitespace-nowrap`,children:`Sign in`})]})]})})]})})},Sd=e=>{let t=e.at(-2);if(typeof t==`object`&&t.href&&!t.loading)return{label:t.label,href:t.href}},Cd=(0,o.createContext)(void 0),wd=()=>{let e=(0,o.useContext)(Cd);return e?{id:e.id,name:e.name,"aria-describedby":e.describedBy,"aria-invalid":e.invalid||void 0,"aria-required":e.required||void 0}:{}},Td=({leading:e,trailing:t,invalid:n,className:r,wrapperClassName:i,...a})=>{let o=wd();return(0,V.jsxs)(`span`,{className:B(`flex h-8 items-center gap-2 rounded-md border bg-background px-2.5 text-muted-foreground shadow-sm focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20`,n?`border-danger`:`border-border-strong`,i),children:[e,(0,V.jsx)(`input`,{className:B(`min-w-0 flex-1 bg-transparent text-body text-foreground outline-none placeholder:text-faint-foreground`,r),...o,...n&&{"aria-invalid":!0},...a}),t]})},Ed=({children:e})=>(0,V.jsx)(`kbd`,{className:`inline-flex h-5 items-center rounded border border-border-strong bg-background px-1.5 font-sans text-[11px] font-medium text-muted-foreground`,children:e}),Dd=({className:e})=>(0,V.jsx)(jt,{"aria-label":`Loading`,className:B(`size-4 animate-spin`,e)}),Od=(e,t,n)=>t===0?-1:e<0?n===1?0:t-1:(e+n+t)%t,kd=e=>e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0,Ad=({search:e,className:t=`w-96`,autoFocus:n,showShortcut:r=!0,ref:i})=>{let a=(0,o.useId)(),s=(0,o.useRef)(null),[c,l]=(0,o.useState)(!1),[u,d]=(0,o.useState)(-1),f=e.groups.flatMap(e=>e.hits),p=c&&(e.query!==``||e.loading),m=e=>`${a}-${e}`,h=e=>{s.current=e,typeof i==`function`?i(e):i&&(i.current=e)},g=t=>{e.onSelect(t),d(-1),s.current?.blur()},_=()=>{e.onTextChange(``),d(-1),s.current?.focus()},v=t=>{if(t.key===`ArrowDown`||t.key===`ArrowUp`)t.preventDefault(),d(e=>Od(e,f.length,t.key===`ArrowDown`?1:-1));else if(t.key===`Enter`){let e=f[u]??f[0];if(!e)return;t.preventDefault(),g(e.href)}else t.key===`Escape`&&(e.text?e.onTextChange(``):t.currentTarget.blur(),d(-1))},y=-1;return(0,V.jsxs)(`div`,{className:B(`relative`,t),children:[(0,V.jsx)(Td,{ref:h,wrapperClassName:`w-full bg-surface shadow-none`,leading:e.loading?(0,V.jsx)(Dd,{className:`size-4`}):(0,V.jsx)(fn,{className:`size-4`}),trailing:e.text?(0,V.jsx)(`button`,{type:`button`,"aria-label":`Clear search`,className:`-mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground`,onMouseDown:e=>e.preventDefault(),onClick:_,children:(0,V.jsx)(Qn,{className:`size-3.5`})}):r?(0,V.jsx)(`span`,{className:`hidden md:inline-flex`,children:(0,V.jsx)(Ed,{children:`⌘K`})}):void 0,placeholder:e.placeholder,"aria-label":`Global search`,role:`combobox`,"aria-autocomplete":`list`,"aria-expanded":p,"aria-controls":a,"aria-activedescendant":p&&f[u]?m(u):void 0,autoFocus:n,value:e.text,onChange:t=>{e.onTextChange(t.target.value),d(-1)},onFocus:()=>l(!0),onBlur:()=>l(!1),onKeyDown:v}),p&&(0,V.jsxs)(`div`,{id:a,role:`listbox`,"aria-label":`Search results`,className:`absolute right-0 top-full z-40 mt-1 max-h-96 w-full min-w-72 overflow-y-auto rounded-lg border bg-background py-1 shadow-pop`,children:[e.groups.length===0&&(0,V.jsx)(`p`,{className:`px-3 py-2 text-muted-foreground`,children:e.loading?`Searching`:`No matches for “${e.query}”`}),e.groups.map(e=>(0,V.jsxs)(`div`,{role:`group`,"aria-label":e.label,children:[(0,V.jsx)(`div`,{className:`px-3 pb-1 pt-2 text-[11px] font-medium uppercase tracking-wide text-faint-foreground`,children:e.label}),e.failed&&(0,V.jsxs)(`p`,{className:`px-3 py-1.5 text-danger-text`,children:[`Could not search `,e.label.toLowerCase()]}),e.hits.map(e=>{y+=1;let t=y;return(0,V.jsxs)(`a`,{id:m(t),href:e.href,tabIndex:-1,role:`option`,"aria-selected":t===u,className:B(`block px-3 py-1.5`,t===u?`bg-primary-soft text-primary-text`:`hover:bg-muted`),onMouseDown:e=>e.preventDefault(),onClick:t=>{kd(t)||(t.preventDefault(),g(e.href))},onMouseEnter:()=>d(t),children:[(0,V.jsx)(`span`,{className:`block truncate font-semibold`,children:e.title}),e.subtitle&&(0,V.jsx)(`span`,{className:B(`block truncate text-xs`,t===u?`text-primary-text/80`:`text-muted-foreground`),children:e.subtitle})]},e.id)})]},e.id))]})]})},jd=`inline-flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted md:hidden`,Md=({breadcrumb:e,onNavigate:t,actions:n,onMenu:r,menuOpen:i,menuControls:a,search:s,sticky:c,ref:l})=>{let[u,d]=(0,o.useState)(!1),f=Sd(e),p=(0,o.useRef)(null);return(0,o.useEffect)(()=>{if(!s)return;let e=e=>{if(e.key.toLowerCase()!==`k`||!(e.metaKey||e.ctrlKey))return;e.preventDefault();let t=p.current;t&&t.offsetParent!==null?t.focus():d(!0)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[s]),(0,V.jsxs)(`header`,{ref:l,className:B(c?`sticky top-0 z-30`:`relative`,`flex h-12 shrink-0 items-center gap-1 border-b bg-background pl-4 pr-2 md:gap-4 md:px-5`),children:[r&&(0,V.jsx)(`button`,{type:`button`,"aria-label":`Open navigation`,"aria-expanded":!!i,"aria-controls":a,onClick:r,className:B(jd,`-ml-3`),children:(0,V.jsx)(ree,{className:`size-5`})}),f&&(0,V.jsx)(`a`,{href:f.href,"aria-label":`Back to ${f.label}`,onClick:e=>{t&&ju(e)&&(e.preventDefault(),t(f.href))},className:B(jd,!r&&`-ml-3`),children:(0,V.jsx)(ye,{className:`size-5`})}),(0,V.jsx)(Mu,{parts:e,onNavigate:t}),(0,V.jsxs)(`div`,{className:`ml-auto flex items-center gap-1 md:gap-3`,children:[s&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`div`,{className:`hidden md:block`,children:(0,V.jsx)(Ad,{ref:p,search:s})}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Search`,"aria-expanded":u,onClick:()=>d(!0),className:jd,children:(0,V.jsx)(fn,{className:`size-5`})})]}),n]}),s&&u&&(0,V.jsxs)(`div`,{className:`absolute inset-0 z-20 flex items-center gap-1 bg-background px-3 md:hidden`,children:[(0,V.jsx)(Ad,{className:`min-w-0 flex-1`,autoFocus:!0,showShortcut:!1,search:{...s,onSelect:e=>{s.onSelect(e),d(!1)}}}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Close search`,onClick:()=>d(!1),className:jd,children:(0,V.jsx)(Qn,{className:`size-5`})})]})]})},Nd=`app-drawer`,Pd=({sidebarMode:e,activeItem:t,breadcrumb:n,user:r,workspace:i,logo:a,actions:s,rightPanel:c,forceExpanded:l,profileMenuOpen:u,navGroups:d,userMenu:f,bottomBar:p,onNavigate:m,onSignOut:h,signIn:g,organizations:_,roles:v,theme:y,search:b,pageScroll:x=!1,className:S,children:C})=>{let w=mu(),[T,E]=(0,o.useState)(!1);(0,o.useEffect)(()=>{w&&E(!1)},[w]);let D=!w&&p&&p.length>0?p:void 0,[O,k]=(0,o.useState)(),A=O??x,j=(0,o.useRef)(null),M=(0,o.useRef)(null);ku(A,j,M,!!D),Du(A);let N=(e,n=!1)=>(0,V.jsx)(xd,{mode:e,sticky:n,activeItem:t,user:r,workspace:i,forceExpanded:l,profileMenuOpen:u,groups:d,userMenu:f,onNavigate:m,onSignOut:h,signIn:g,organizations:_,roles:v,theme:y,logo:a});return(0,V.jsx)(Tu.Provider,{value:k,children:(0,V.jsxs)(`div`,{className:B(A?`flex min-h-full w-full overflow-x-clip bg-background`:`relative flex h-full min-h-0 w-full overflow-hidden bg-background`,S),children:[w?N(e,A):(0,V.jsx)(wu,{id:Nd,open:T,onClose:()=>E(!1),children:N(`text-large`)}),(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,V.jsx)(Md,{ref:j,sticky:A,breadcrumb:n,onNavigate:m,actions:s,onMenu:w||D?void 0:()=>E(!0),menuOpen:T,menuControls:Nd,search:b}),(0,V.jsx)(`main`,{className:A?`flex flex-1 flex-col`:`flex min-h-0 flex-1 flex-col`,children:C}),D&&(0,V.jsx)(vu,{ref:M,sticky:A,tabs:D,onNavigate:m,onMore:()=>E(!0),moreOpen:T,moreControls:Nd})]}),c&&(0,V.jsx)(`div`,{className:A?`sticky top-0 flex h-dvh shrink-0 self-start`:`flex shrink-0`,children:c})]})})},Fd=({title:e,subtitle:t,aside:n,actions:r})=>{let i=(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h1`,{className:`text-xl font-semibold tracking-tight`,children:e}),t&&(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:t})]});return(0,V.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-x-4 gap-y-2`,children:[n?(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center justify-between gap-3`,children:[i,n]}):i,r&&(0,V.jsx)(`div`,{className:`flex w-full flex-wrap items-center gap-2 sm:w-auto`,children:r})]})},Id=`Too many attempts. Wait a minute and try again.`,Ld=`The passkey prompt closed before it finished. Try again.`,Rd={INVALID_EMAIL_OR_PASSWORD:`The email or password is not right.`,INVALID_PASSWORD:`The password is not right.`,INVALID_OTP:`The code is not right.`,OTP_EXPIRED:`The code has expired. Ask for a new one.`,TOO_MANY_ATTEMPTS:`Too many wrong codes. Ask for a new one.`,INVALID_CODE:`The code is not right.`,INVALID_BACKUP_CODE:`The backup code is not right, or was used before.`,TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:`Too many wrong codes. Sign in again.`,ACCOUNT_TEMPORARILY_LOCKED:`Too many wrong codes. Wait 15 minutes and try again.`,INVALID_TWO_FACTOR_COOKIE:`This sign-in took too long. Sign in again.`,AUTH_CANCELLED:Ld,ERROR_CEREMONY_ABORTED:Ld,REGISTRATION_CANCELLED:Ld,PASSKEY_NOT_FOUND:`This passkey is not registered for an account here.`,AUTHENTICATION_FAILED:`The passkey could not be checked. Try again.`,PREVIOUSLY_REGISTERED:`This passkey is added already.`,ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED:`This passkey is added already.`,SESSION_NOT_FRESH:`For this change, sign out and sign in again first.`},zd=e=>e.code?Rd[e.code]:void 0,Bd=e=>zd(e)??(e.status===429?Id:e.message),Vd=e=>zd(e)??(e.status===429?Id:e.status===401?Rd.INVALID_EMAIL_OR_PASSWORD:e.message),Hd={STAFF_PERMISSION_MISSING:`Your staff account has no permission to sign in as people here.`,STAFF_SIGN_IN_NOT_STRONG:`Sign in to your staff account with a passkey or a second step, then try again.`,STAFF_SIGN_IN_STALE:`Your staff sign-in is too old. Sign in to your staff account again.`,STAFF_SIGN_IN_EXPIRED:`This staff sign-in took too long or was used already. Start again.`,STAFF_SIGN_IN_FAILED:`The staff sign-in did not go through at the provider. Try again.`,STAFF_USER_UNAVAILABLE:`There is no account with this address, or it is disabled.`,STAFF_REASON_REQUIRED:`Say why you sign in as this person, in at least 10 characters.`,SIGN_IN_METHOD_FORBIDDEN:`Staff sign-in is turned off for this app.`,INVALID_CALLBACK_URL:`This page is not on an address the server trusts.`},Ud=e=>{let t=typeof e==`string`?e:e.code;return t&&Hd[t]?Hd[t]:typeof e==`string`?`The staff sign-in did not go through. Try again.`:e.status===429?Id:e.message},Wd={signup_disabled:e=>`No account here belongs to this ${e} account. Ask an admin to add you, or sign in another way.`,account_not_linked:e=>`Your ${e} account is not linked to your account here. Sign in another way, then connect ${e} on the Sign-in & security page.`,account_already_linked_to_different_user:e=>`This ${e} account is linked to someone else here already.`,unable_to_link_account:e=>`Your ${e} account could not be linked. Try again.`,access_denied:e=>`${e} did not let you in, or you cancelled.`},Gd=(e,t)=>Wd[e]?.(t)??`Signing in with ${t} did not go through. Try again.`,Kd=`sign-in`,qd=`error`,Jd=e=>{let t=new URL(e).searchParams;if(!t.has(qd))return t.get(`sign-in`)||void 0},Yd=e=>new URL(e).searchParams.get(qd)||void 0,Xd=e=>{let t=new URL(e);for(let e of[Kd,qd])t.searchParams.delete(e);return`${t.pathname}${t.search}${t.hash}`},Zd={github:`GitHub`,gitlab:`GitLab`,google:`Google`,microsoft:`Microsoft`,apple:`Apple`},Qd=(e,t)=>t?.provider===e?t.name:Zd[e]??e.charAt(0).toUpperCase()+e.slice(1),$d=(0,o.createContext)(null),H=()=>{let e=(0,o.useContext)($d);if(!e)throw Error(`useAuth must be used inside AuthProvider`);return e},ef=({session:e,children:t})=>{let[n,r]=(0,o.useState)({kind:`loading`}),[i,a]=(0,o.useState)([`password`]),[s,c]=(0,o.useState)(!1),[l,u]=(0,o.useState)(!1),[d,f]=(0,o.useState)([]),[p,m]=(0,o.useState)([]),[h,g]=(0,o.useState)(),[_,v]=(0,o.useState)(),[y,b]=(0,o.useState)(),[x,S]=(0,o.useState)(!1),[C,w]=(0,o.useState)([]),T=(0,o.useCallback)(()=>x?{kind:`visitor`}:{kind:`signed-out`},[x]),E=(0,o.useCallback)(()=>r(e=>e.kind===`signed-in`?{kind:`signed-out`}:e),[]),D=(0,o.useRef)(E);D.current=E;let O=(0,o.useMemo)(()=>e??iu({onSignedOut:()=>D.current()}),[e]),k=(0,o.useCallback)(async e=>{let[{missing:t},n]=await Promise.all([O.account.signInMethods(),O.staff.current()]);r(t.length>0?{kind:`setup-required`,user:e,missing:t}:{kind:`signed-in`,user:e,...n&&{staff:n}})},[O]),A=(0,o.useCallback)(async e=>e.kind===`two-factor`?r({kind:`two-factor`,methods:e.methods}):k(e.user),[k]),j=(0,o.useCallback)(()=>{r({kind:`loading`}),O.status().then(async e=>{if(a(e.signInMethods),c(e.passwordReset),u(!!e.signUp),f(e.passkeyDomains??[]),m(e.socialProviders),g(e.platformSignIn),v(e.staffSignIn),b(e.organizations),S(!!e.anonymous),w(e.plugins??[]),e.needsAdmin)return r({kind:`needs-admin`});let t=await O.session();return t?k(t):r({kind:e.anonymous?`visitor`:`signed-out`})}).catch(e=>r({kind:`error`,message:e instanceof Error?e.message:`The server did not answer`}))},[O,k]);(0,o.useEffect)(j,[j]);let M=(0,o.useMemo)(()=>({state:n,session:O,signInMethods:i,passwordReset:s,canSignUp:l,passkeyDomains:d,socialProviders:p,signInProviders:p.map(e=>({id:e,name:Qd(e,h)})),staffSignIn:_,...y&&{organizations:y},markSignedOut:E,recheck:j,beforeSignIn:C,adoptSession:async()=>{let e=await O.session();return e?(await k(e),!0):!1},...x&&{browse:()=>{r(e=>e.kind===`signed-out`?{kind:`visitor`}:e)}},signIn:async(e,t)=>A(await O.signIn(e,t)),sendSignInCode:e=>O.sendSignInCode(e),signInWithCode:async(e,t)=>A(await O.signInWithCode(e,t)),sendSignUpCode:e=>O.sendSignUpCode(e),verifySignUpCode:(e,t)=>O.verifySignUpCode(e,t),signUp:async e=>k(await O.signUp(e)),signInWithPasskey:async e=>k(await O.signInWithPasskey(e)),verifyTwoFactor:async e=>k(await O.verifyTwoFactor(e)),signInSocial:async e=>{window.location.assign(await O.signInSocial(e,new URL(Xd(window.location.href),window.location.href).href))},linkProvider:async e=>{window.location.assign(await O.account.linkProvider(e,new URL(Xd(window.location.href),window.location.href).href))},stopStaffSession:async()=>{await O.staff.stop(),r(T())},signOut:async()=>{await O.signOut(),r(T())}}),[n,O,i,s,l,d,p,h,_,y,x,C,T,E,j,A,k]);return(0,V.jsx)($d.Provider,{value:M,children:t})},tf=new Map,nf=(e,t)=>{let n=`${e}:${t??``}`,r=tf.get(n);if(r)return r;let i=new Intl.NumberFormat(`en-IE`,{style:`currency`,currency:e,...t!==void 0&&{minimumFractionDigits:t,maximumFractionDigits:t}});return tf.set(n,i),i},rf=(e,t=`EUR`,n)=>nf(t,n).format(e/100),af=new Intl.NumberFormat(`en-IE`),of=e=>af.format(e),sf=e=>e>0?`+${af.format(e)}`:af.format(e).replace(`-`,`−`),cf=e=>`${e}%`,lf=e=>{if(e<1e4)return`${of(e)} rows`;let t=10**(Math.floor(Math.log10(e))-3);return`about ${of(Math.round(e/t)*t)} rows`},uf=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,year:`numeric`,timeZone:`UTC`}),df=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,timeZone:`UTC`}),ff=new Intl.DateTimeFormat(`en-GB`,{hour:`2-digit`,minute:`2-digit`,hour12:!1,timeZone:`UTC`}),pf=e=>uf.format(e),mf=e=>df.format(e),hf=e=>`${uf.format(e)}, ${ff.format(e)}`,gf=e=>e<60?`${e} s ago`:e<3600?`${Math.floor(e/60)} min ago`:e<86400?`${Math.floor(e/3600)} h ago`:`${Math.floor(e/86400)} d ago`,_f=new Intl.RelativeTimeFormat(`en`,{numeric:`auto`}),vf=[[`year`,31536e3],[`month`,2592e3],[`day`,86400],[`hour`,3600],[`minute`,60]],yf=e=>{let[t,n]=vf.find(([,t])=>e>=t)??[`second`,1];return t===`second`&&e<45?`just now`:_f.format(-Math.floor(e/n),t)},bf={primary:`bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm`,secondary:`bg-background text-foreground border border-border-strong hover:bg-muted shadow-sm`,ghost:`text-muted-foreground hover:bg-muted hover:text-foreground`,danger:`bg-background text-danger-text border border-border-strong hover:bg-danger-soft shadow-sm`},xf={sm:`h-7 px-2.5 text-xs gap-1.5`,md:`h-8 px-3 text-body gap-2`},Sf=({variant:e=`secondary`,size:t=`md`}={})=>B(`inline-flex shrink-0 items-center justify-center rounded-md font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-60 disabled:cursor-default`,bf[e],xf[t]),U=({variant:e=`secondary`,size:t=`md`,loading:n,className:r,children:i,disabled:a,...o})=>(0,V.jsxs)(`button`,{type:`button`,disabled:a||n,className:B(Sf({variant:e,size:t}),r),...o,children:[n&&(0,V.jsx)(Dd,{className:`size-3.5`}),i]}),Cf=({title:e,description:t,onClose:n,actions:r,children:i,wide:a=!1})=>{let s=(0,o.useRef)(null);return Cu(s,!0,n),(0,V.jsx)(`div`,{className:`fixed inset-0 z-[90] flex items-center justify-center bg-backdrop/30 p-4`,onMouseDown:e=>e.target===e.currentTarget&&n(),children:(0,V.jsxs)(`div`,{ref:s,tabIndex:-1,role:`dialog`,"aria-modal":`true`,"aria-label":e,className:B(`outline-none max-h-[90vh] w-full overflow-y-auto rounded-lg border bg-background p-4 shadow-pop sm:p-5`,a?`max-w-3xl`:`max-w-md`),children:[(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:e}),t&&(0,V.jsx)(`p`,{className:`mt-1.5 text-muted-foreground`,children:t}),i&&(0,V.jsx)(`div`,{className:`mt-4`,children:i}),(0,V.jsx)(`div`,{className:`mt-5 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end [&>*]:min-h-11 sm:[&>*]:min-h-0`,children:r})]})})},wf=({title:e,status:t,description:n,children:r})=>(0,V.jsxs)(`section`,{"aria-label":e,className:`rounded-lg border bg-background p-4 sm:p-5`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:e}),t]}),(0,V.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:n}),r&&(0,V.jsx)(`div`,{className:`mt-4`,children:r})]}),Tf=({message:e})=>e?(0,V.jsx)(`p`,{role:`alert`,className:`mb-3 text-xs font-medium text-danger-text`,children:e}):null,Ef={allowed:`Sign in with Face ID, Touch ID, Windows Hello, your phone or a security key instead of a password.`,required:`This app requires a passkey for every account. Sign in with Face ID, Touch ID, Windows Hello, your phone or a security key.`,forbidden:`Your admin turned passkeys off for this app, so they cannot be used to sign in.`},Df=({rule:e,passkeys:t,onAdd:n,onRename:r,onRemove:i})=>{let[a,s]=(0,o.useState)(!1),[c,l]=(0,o.useState)(),[u,d]=(0,o.useState)(),[f,p]=(0,o.useState)(``),m=e===`required`&&t.length<=1,h=async e=>{s(!0),l(void 0);try{await e(),d(void 0)}catch(e){if(!(e instanceof lc))throw e;l(Bd(e))}s(!1)};return(0,V.jsxs)(wf,{title:`Passkeys`,status:e===`required`&&(0,V.jsx)(Zu,{tone:`blue`,children:`Required`}),description:Ef[e],children:[(0,V.jsx)(Tf,{message:u?void 0:c}),t.length>0&&(0,V.jsx)(`ul`,{className:`mb-3 divide-y rounded-md border`,children:t.map(e=>(0,V.jsxs)(`li`,{className:`flex flex-wrap items-center gap-3 px-3 py-2.5`,children:[(0,V.jsx)(gt,{className:`size-4 shrink-0 text-muted-foreground`}),(0,V.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:e.name??`Passkey`}),(0,V.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[e.createdAt?`Added ${pf(Date.parse(e.createdAt))}`:`Added earlier`,` · `,e.backedUp?`Synced across your devices`:`On one device`]})]}),(0,V.jsxs)(`span`,{className:`flex gap-1`,children:[(0,V.jsx)(U,{size:`sm`,variant:`ghost`,onClick:()=>{p(e.name??``),d({kind:`rename`,passkey:e})},children:`Rename`}),(0,V.jsx)(U,{size:`sm`,variant:`ghost`,disabled:m,title:m?`Passkeys are required: add another one before removing this one.`:void 0,onClick:()=>d({kind:`remove`,passkey:e}),children:`Remove`})]})]},e.id))}),e!==`forbidden`&&(0,V.jsxs)(U,{loading:a&&!u,onClick:()=>void h(n),children:[(0,V.jsx)(nn,{className:`size-3.5`}),`Add a passkey`]}),u?.kind===`rename`&&(0,V.jsxs)(Cf,{title:`Rename passkey`,description:`A name that tells you where this passkey lives, such as the device or password manager.`,onClose:()=>d(void 0),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>d(void 0),children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,loading:a,disabled:!f.trim(),onClick:()=>void h(()=>r(u.passkey.id,f.trim())),children:`Save`})]}),children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Name`,(0,V.jsx)(Td,{autoFocus:!0,value:f,maxLength:60,onChange:e=>p(e.target.value)})]}),(0,V.jsx)(Tf,{message:c})]}),u?.kind===`remove`&&(0,V.jsx)(Cf,{title:`Remove passkey?`,description:`${u.passkey.name??`This passkey`} will no longer sign you in here. It stays on the device until you delete it there.`,onClose:()=>d(void 0),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>d(void 0),children:`Cancel`}),(0,V.jsx)(U,{variant:`danger`,loading:a,onClick:()=>void h(()=>i(u.passkey.id)),children:`Remove`})]}),children:c&&(0,V.jsx)(Tf,{message:c})})]})},Of=({providers:e,linked:t,onConnect:n,error:r})=>{let[i,a]=(0,o.useState)(),[s,c]=(0,o.useState)(r),l=async e=>{a(e),c(void 0);try{await n(e)}catch(e){if(!(e instanceof lc))throw e;c(Bd(e)),a(void 0)}};return(0,V.jsxs)(wf,{title:`Connected accounts`,description:`Sign in with these instead of your password. Connecting one asks you to sign in there; its address may differ from yours here.`,children:[(0,V.jsx)(Tf,{message:s}),(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:e.map(e=>(0,V.jsxs)(`li`,{className:`flex flex-wrap items-center gap-3 px-3 py-2.5`,children:[(0,V.jsx)(Dt,{className:`size-4 shrink-0 text-muted-foreground`}),(0,V.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-medium`,children:e.name}),t.includes(e.id)?(0,V.jsx)(Zu,{tone:`green`,children:`Connected`}):(0,V.jsxs)(U,{size:`sm`,loading:i===e.id,disabled:i!==void 0,onClick:()=>void l(e.id),children:[`Connect `,e.name]})]},e.id))})]})},kf=(e,t,n=`text/plain`)=>{let r=URL.createObjectURL(new Blob([e],{type:n}));Object.assign(document.createElement(`a`),{href:r,download:t}).click(),URL.revokeObjectURL(r)},Af=({codes:e})=>{let[t,n]=(0,o.useState)(!1),r=`${e.join(`
|
|
7
|
-
`)}\n`;return(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,V.jsx)(`ul`,{"aria-label":`Backup codes`,className:`grid grid-cols-2 gap-x-4 gap-y-1 rounded-md border bg-surface p-3 font-mono`,children:e.map(e=>(0,V.jsx)(`li`,{children:e},e))}),(0,V.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,V.jsxs)(U,{size:`sm`,onClick:()=>{navigator.clipboard.writeText(r).then(()=>{n(!0),setTimeout(()=>n(!1),2e3)})},children:[t?(0,V.jsx)(he,{className:`size-3.5 text-success`}):(0,V.jsx)(Le,{className:`size-3.5`}),t?`Copied`:`Copy`]}),(0,V.jsxs)(U,{size:`sm`,onClick:()=>kf(r,`backup-codes.txt`),children:[(0,V.jsx)(He,{className:`size-3.5`}),`Download`]})]})]})},jf=({title:e,description:t,confirmLabel:n,danger:r,needsPassword:i,onConfirm:a,onClose:s})=>{let[c,l]=(0,o.useState)(``),[u,d]=(0,o.useState)(!1),[f,p]=(0,o.useState)(),m=async()=>{d(!0),p(void 0);try{await a(i?c:void 0)}catch(e){if(!(e instanceof lc))throw e;p(Bd(e)),d(!1)}};return(0,V.jsxs)(Cf,{title:e,description:t,onClose:s,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:s,children:`Cancel`}),(0,V.jsx)(U,{variant:r?`danger`:`primary`,loading:u,disabled:i&&!c,onClick:()=>void m(),children:n})]}),children:[i&&(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Your password`,(0,V.jsx)(Td,{type:`password`,autoComplete:`current-password`,autoFocus:!0,value:c,invalid:!!f,onChange:e=>l(e.target.value),onKeyDown:e=>e.key===`Enter`&&c&&void m()})]}),f&&(0,V.jsx)(`p`,{role:`alert`,className:`mt-2 text-xs font-medium text-danger-text`,children:f})]})},Mf=(e,t)=>e.replace(/\D/g,``).slice(0,t),Nf=(e,t,n)=>{let r=Mf(t??``,n);return r.length===n?r:Mf(e,n)},Pf=(e,t,n,r)=>{let i=t.replace(/\D/g,``);return i.length>=r?i.slice(0,r):Mf(e.slice(0,n)+i+e.slice(n+i.length),r)},Ff=({value:e,onChange:t,onComplete:n,length:r=6,invalid:i,disabled:a,className:s,ref:c,onFocus:l,onBlur:u,onSelect:d,onKeyDown:f,onClick:p,onPaste:m,...h})=>{let g=(0,o.useRef)(null),[_,v]=(0,o.useState)(!1),[y,b]=(0,o.useState)(e.length),x=e.slice(0,r),S=Math.min(y,r-1),C=e=>{g.current=e,typeof c==`function`?c(e):c&&(c.current=e)},w=e=>{e!==x&&(t(e),e.length===r&&n?.(e))},T=e=>{let t=g.current;if(!t)return;let n=Math.max(0,Math.min(e,x.length));t.setSelectionRange(n,n<x.length?n+1:n),b(n)},E=e=>{if(f?.(e),e.defaultPrevented||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey)return;let t=e.currentTarget.selectionStart??x.length,n={ArrowLeft:t-1,ArrowRight:t+1,Home:0,End:x.length}[e.key];n!==void 0&&(e.preventDefault(),T(n))},D=e=>{p?.(e);let t=e.currentTarget.getBoundingClientRect();e.clientX<=t.left||e.clientX>=t.right||T(Math.floor((e.clientX-t.left)/t.width*r))};return(0,V.jsxs)(`div`,{className:B(`relative`,a&&`opacity-50`,s),children:[(0,V.jsx)(`div`,{"aria-hidden":!0,className:`flex justify-center gap-2`,children:Array.from({length:r},(e,t)=>{let n=_&&t===S;return(0,V.jsx)(`div`,{"data-slot":t,"data-digit":x[t],className:B(`flex h-12 min-w-0 max-w-12 flex-1 items-center justify-center rounded-md border bg-background font-mono text-xl font-semibold text-foreground shadow-sm transition-colors before:content-[attr(data-digit)]`,i?`border-danger`:n?`border-primary`:`border-border-strong`,n&&(i?`ring-2 ring-danger/20`:`ring-2 ring-primary/20`)),children:x[t]===void 0&&(n?(0,V.jsx)(`span`,{className:`h-6 w-px animate-pulse bg-foreground`}):(0,V.jsx)(`span`,{className:`size-1.5 rounded-full bg-border-strong`}))},t)})}),(0,V.jsx)(`input`,{ref:C,type:`text`,inputMode:`numeric`,autoComplete:`one-time-code`,pattern:`[0-9]{${r}}`,spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`,"aria-invalid":i||void 0,disabled:a,value:x,className:`absolute inset-0 size-full cursor-text bg-transparent text-transparent caret-transparent outline-none selection:bg-transparent disabled:cursor-not-allowed`,...h,onChange:e=>{let{data:t,dataTransfer:n}=e.nativeEvent;w(Nf(e.target.value,t??n?.getData(`text/plain`),r))},onPaste:e=>{if(m?.(e),e.defaultPrevented)return;e.preventDefault();let t=e.currentTarget,n=Pf(x,e.clipboardData.getData(`text`),t.selectionStart??x.length,r);w(n),b(n.length)},onSelect:e=>{d?.(e);let t=e.currentTarget,n=t.selectionStart??x.length;n===t.selectionEnd&&n<t.value.length&&t.setSelectionRange(n,n+1),b(n)},onKeyDown:E,onClick:D,onFocus:e=>{v(!0),l?.(e)},onBlur:e=>{v(!1),u?.(e)}})]})},If=(e=>(e[e.Border=-1]=`Border`,e[e.Data=0]=`Data`,e[e.Function=1]=`Function`,e[e.Position=2]=`Position`,e[e.Timing=3]=`Timing`,e[e.Alignment=4]=`Alignment`,e))(If||{}),Lf=[0,1],Rf=[1,0],zf=[2,3],Bf=[3,2],Vf={L:Lf,M:Rf,Q:zf,H:Bf},Hf=/^\d*$/,Uf=/^[A-Z0-9 $%*+./:-]*$/,Wf=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:`,Gf=1,Kf=40,qf=3,Jf=3,Yf=40,Xf=10,Zf=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],Qf=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],$f=class{constructor(e,t,n,r){if(this.version=e,this.ecc=t,e<Gf||e>Kf)throw RangeError(`Version value out of range`);if(r<-1||r>7)throw RangeError(`Mask value out of range`);this.size=e*4+17;let i=Array.from({length:this.size}).fill(!1);for(let e=0;e<this.size;e++)this.modules.push(i.slice()),this.types.push(i.map(()=>0));this.drawFunctionPatterns();let a=this.addEccAndInterleave(n);if(this.drawCodewords(a),r===-1){let e=1e9;for(let t=0;t<8;t++){this.applyMask(t),this.drawFormatBits(t);let n=this.getPenaltyScore();n<e&&(r=t,e=n),this.applyMask(t)}}this.mask=r,this.applyMask(r),this.drawFormatBits(r)}size;mask;modules=[];types=[];getModule(e,t){return e>=0&&e<this.size&&t>=0&&t<this.size&&this.modules[t][e]}drawFunctionPatterns(){for(let e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0,If.Timing),this.setFunctionModule(e,6,e%2==0,If.Timing);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);let e=this.getAlignmentPatternPositions(),t=e.length;for(let n=0;n<t;n++)for(let r=0;r<t;r++)n===0&&r===0||n===0&&r===t-1||n===t-1&&r===0||this.drawAlignmentPattern(e[n],e[r]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(e){let t=this.ecc[1]<<3|e,n=t;for(let e=0;e<10;e++)n=n<<1^(n>>>9)*1335;let r=(t<<10|n)^21522;for(let e=0;e<=5;e++)this.setFunctionModule(8,e,tp(r,e));this.setFunctionModule(8,7,tp(r,6)),this.setFunctionModule(8,8,tp(r,7)),this.setFunctionModule(7,8,tp(r,8));for(let e=9;e<15;e++)this.setFunctionModule(14-e,8,tp(r,e));for(let e=0;e<8;e++)this.setFunctionModule(this.size-1-e,8,tp(r,e));for(let e=8;e<15;e++)this.setFunctionModule(8,this.size-15+e,tp(r,e));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let t=0;t<12;t++)e=e<<1^(e>>>11)*7973;let t=this.version<<12|e;for(let e=0;e<18;e++){let n=tp(t,e),r=this.size-11+e%3,i=Math.floor(e/3);this.setFunctionModule(r,i,n),this.setFunctionModule(i,r,n)}}drawFinderPattern(e,t){for(let n=-4;n<=4;n++)for(let r=-4;r<=4;r++){let i=Math.max(Math.abs(r),Math.abs(n)),a=e+r,o=t+n;a>=0&&a<this.size&&o>=0&&o<this.size&&this.setFunctionModule(a,o,i!==2&&i!==4,If.Position)}}drawAlignmentPattern(e,t){for(let n=-2;n<=2;n++)for(let r=-2;r<=2;r++)this.setFunctionModule(e+r,t+n,Math.max(Math.abs(r),Math.abs(n))!==1,If.Alignment)}setFunctionModule(e,t,n,r=If.Function){this.modules[t][e]=n,this.types[t][e]=r}addEccAndInterleave(e){let t=this.version,n=this.ecc;if(e.length!==gp(t,n))throw RangeError(`Invalid argument`);let r=Qf[n[0]][t],i=Zf[n[0]][t],a=Math.floor(hp(t)/8),o=r-a%r,s=Math.floor(a/r),c=[],l=_p(i);for(let t=0,n=0;t<r;t++){let r=e.slice(n,n+s-i+(t<o?0:1));n+=r.length;let a=vp(r,l);t<o&&r.push(0),c.push(r.concat(a))}let u=[];for(let e=0;e<c[0].length;e++)c.forEach((t,n)=>{(e!==s-i||n>=o)&&u.push(t[e])});return u}drawCodewords(e){if(e.length!==Math.floor(hp(this.version)/8))throw RangeError(`Invalid argument`);let t=0;for(let n=this.size-1;n>=1;n-=2){n===6&&(n=5);for(let r=0;r<this.size;r++)for(let i=0;i<2;i++){let a=n-i,o=n+1&2?r:this.size-1-r;!this.types[o][a]&&t<e.length*8&&(this.modules[o][a]=tp(e[t>>>3],7-(t&7)),t++)}}}applyMask(e){if(e<0||e>7)throw RangeError(`Mask value out of range`);for(let t=0;t<this.size;t++)for(let n=0;n<this.size;n++){let r;switch(e){case 0:r=(n+t)%2==0;break;case 1:r=t%2==0;break;case 2:r=n%3==0;break;case 3:r=(n+t)%3==0;break;case 4:r=(Math.floor(n/3)+Math.floor(t/2))%2==0;break;case 5:r=n*t%2+n*t%3==0;break;case 6:r=(n*t%2+n*t%3)%2==0;break;case 7:r=((n+t)%2+n*t%3)%2==0;break;default:throw Error(`Unreachable`)}!this.types[t][n]&&r&&(this.modules[t][n]=!this.modules[t][n])}}getPenaltyScore(){let e=0;for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[t][a]===n?(r++,r===5?e+=qf:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*Yf),n=this.modules[t][a],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*Yf}for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[a][t]===n?(r++,r===5?e+=qf:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*Yf),n=this.modules[a][t],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*Yf}for(let t=0;t<this.size-1;t++)for(let n=0;n<this.size-1;n++){let r=this.modules[t][n];r===this.modules[t][n+1]&&r===this.modules[t+1][n]&&r===this.modules[t+1][n+1]&&(e+=Jf)}let t=0;for(let e of this.modules)t=e.reduce((e,t)=>e+ +!!t,t);let n=this.size*this.size,r=Math.ceil(Math.abs(t*20-n*10)/n)-1;return e+=r*Xf,e}getAlignmentPatternPositions(){if(this.version===1)return[];{let e=Math.floor(this.version/7)+2,t=this.version===32?26:Math.ceil((this.version*4+4)/(e*2-2))*2,n=[6];for(let r=this.size-7;n.length<e;r-=t)n.splice(1,0,r);return n}}finderPenaltyCountPatterns(e){let t=e[1],n=t>0&&e[2]===t&&e[3]===t*3&&e[4]===t&&e[5]===t;return(n&&e[0]>=t*4&&e[6]>=t?1:0)+(n&&e[6]>=t*4&&e[0]>=t?1:0)}finderPenaltyTerminateAndCount(e,t,n){return e&&(this.finderPenaltyAddHistory(t,n),t=0),t+=this.size,this.finderPenaltyAddHistory(t,n),this.finderPenaltyCountPatterns(n)}finderPenaltyAddHistory(e,t){t[0]===0&&(e+=this.size),t.pop(),t.unshift(e)}};function ep(e,t,n){if(t<0||t>31||e>>>t)throw RangeError(`Value out of range`);for(let r=t-1;r>=0;r--)n.push(e>>>r&1)}function tp(e,t){return!!(e>>>t&1)}var np=class{constructor(e,t,n){if(this.mode=e,this.numChars=t,this.bitData=n,t<0)throw RangeError(`Invalid argument`);this.bitData=n.slice()}getData(){return this.bitData.slice()}},rp=[1,10,12,14],ip=[2,9,11,13],ap=[4,8,16,16];function op(e,t){return e[Math.floor((t+7)/17)+1]}function sp(e){let t=[];for(let n of e)ep(n,8,t);return new np(ap,e.length,t)}function cp(e){if(!dp(e))throw RangeError(`String contains non-numeric characters`);let t=[];for(let n=0;n<e.length;){let r=Math.min(e.length-n,3);ep(Number.parseInt(e.substring(n,n+r),10),r*3+1,t),n+=r}return new np(rp,e.length,t)}function lp(e){if(!fp(e))throw RangeError(`String contains unencodable characters in alphanumeric mode`);let t=[],n=0;for(;n+2<=e.length;n+=2){let r=Wf.indexOf(e.charAt(n))*45;r+=Wf.indexOf(e.charAt(n+1)),ep(r,11,t)}return n<e.length&&ep(Wf.indexOf(e.charAt(n)),6,t),new np(ip,e.length,t)}function up(e){return e===``?[]:dp(e)?[cp(e)]:fp(e)?[lp(e)]:[sp(mp(e))]}function dp(e){return Hf.test(e)}function fp(e){return Uf.test(e)}function pp(e,t){let n=0;for(let r of e){let e=op(r.mode,t);if(r.numChars>=1<<e)return 1/0;n+=4+e+r.bitData.length}return n}function mp(e){e=encodeURI(e);let t=[];for(let n=0;n<e.length;n++)e.charAt(n)===`%`?(t.push(Number.parseInt(e.substring(n+1,n+3),16)),n+=2):t.push(e.charCodeAt(n));return t}function hp(e){if(e<Gf||e>Kf)throw RangeError(`Version number out of range`);let t=(16*e+128)*e+64;if(e>=2){let n=Math.floor(e/7)+2;t-=(25*n-10)*n-55,e>=7&&(t-=36)}return t}function gp(e,t){return Math.floor(hp(e)/8)-Zf[t[0]][e]*Qf[t[0]][e]}function _p(e){if(e<1||e>255)throw RangeError(`Degree out of range`);let t=[];for(let n=0;n<e-1;n++)t.push(0);t.push(1);let n=1;for(let r=0;r<e;r++){for(let e=0;e<t.length;e++)t[e]=yp(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=yp(n,2)}return t}function vp(e,t){let n=t.map(e=>0);for(let r of e){let e=r^n.shift();n.push(0),t.forEach((t,r)=>n[r]^=yp(t,e))}return n}function yp(e,t){if(e>>>8||t>>>8)throw RangeError(`Byte out of range`);let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return n}function bp(e,t,n=1,r=40,i=-1,a=!0){if(!(Gf<=n&&n<=r&&r<=Kf)||i<-1||i>7)throw RangeError(`Invalid value`);let o,s;for(o=n;;o++){let n=gp(o,t)*8,i=pp(e,o);if(i<=n){s=i;break}if(o>=r)throw RangeError(`Data too long`)}for(let e of[Rf,zf,Bf])a&&s<=gp(o,e)*8&&(t=e);let c=[];for(let t of e){ep(t.mode[0],4,c),ep(t.numChars,op(t.mode,o),c);for(let e of t.getData())c.push(e)}let l=gp(o,t)*8;ep(0,Math.min(4,l-c.length),c),ep(0,(8-c.length%8)%8,c);for(let e=236;c.length<l;e^=253)ep(e,8,c);let u=Array.from({length:Math.ceil(c.length/8)},()=>0);return c.forEach((e,t)=>u[t>>>3]|=e<<7-(t&7)),new $f(o,t,u,i)}function xp(e,t){let{ecc:n=`L`,boostEcc:r=!1,minVersion:i=1,maxVersion:a=40,maskPattern:o=-1,border:s=1}=t||{},c=typeof e==`string`?up(e):Array.isArray(e)?[sp(e)]:void 0;if(!c)throw Error(`uqr only supports encoding string and binary data, but got: ${typeof e}`);let l=bp(c,Vf[n],i,a,o,r),u=Sp({version:l.version,maskPattern:l.mask,size:l.size,data:l.modules,types:l.types},s);return t?.invert&&(u.data=u.data.map(e=>e.map(e=>!e))),t?.onEncoded?.(u),u}function Sp(e,t=1){if(!t)return e;let{size:n}=e,r=n+t*2;e.size=r,e.data.forEach(e=>{for(let n=0;n<t;n++)e.unshift(!1),e.push(!1)});for(let n=0;n<t;n++)e.data.unshift(Array.from({length:r},e=>!1)),e.data.push(Array.from({length:r},e=>!1));let i=If.Border;e.types.forEach(e=>{for(let n=0;n<t;n++)e.unshift(i),e.push(i)});for(let n=0;n<t;n++)e.types.unshift(Array.from({length:r},e=>i)),e.types.push(Array.from({length:r},e=>i));return e}var Cp=({uri:e,className:t})=>{let{size:n,path:r}=(0,o.useMemo)(()=>{let t=xp(e,{ecc:`M`,border:2}),n=t.data.flatMap((e,t)=>e.flatMap((e,n)=>e?[`M${n} ${t}h1v1h-1z`]:[]));return{size:t.size,path:n.join(``)}},[e]);return(0,V.jsxs)(`svg`,{viewBox:`0 0 ${n} ${n}`,role:`img`,"aria-label":`QR code for your authenticator app`,shapeRendering:`crispEdges`,className:t,children:[(0,V.jsx)(`rect`,{width:n,height:n,fill:`#fff`}),(0,V.jsx)(`path`,{d:r,fill:`#000`})]})},wp=e=>(new URL(e).searchParams.get(`secret`)??``).replace(/(.{4})(?=.)/g,`$1 `),Tp=[{value:`app`,label:`Authenticator app`,description:`A code from an app such as Google Authenticator, Microsoft Authenticator or 1Password. Comes with backup codes.`},{value:`email`,label:`Emailed code`,description:`A code mailed to your address each time you sign in with a password or an emailed sign-in code.`}],Ep=({offerEmailedCodes:e,needsPassword:t,onStartApp:n,onConfirmApp:r,onEmailedCodes:i,onDone:a,onCancel:s})=>{let[c,l]=(0,o.useState)({kind:`choose`}),[u,d]=(0,o.useState)(`app`),[f,p]=(0,o.useState)(``),[m,h]=(0,o.useState)(``),[g,_]=(0,o.useState)(!1),[v,y]=(0,o.useState)(),b=e?Tp:Tp.filter(e=>e.value===`app`),x=async e=>{_(!0),y(void 0);try{await e()}catch(e){if(!(e instanceof lc))throw e;y(Bd(e))}_(!1)},S=()=>x(async()=>{let e=t?f:void 0;if(u===`email`)return await i(e),a();l({kind:`scan`,setup:await n(e)})}),C=(e,t=m)=>x(async()=>{await r(t),l({kind:`backup-codes`,codes:e.backupCodes})}),w=v&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:v});return c.kind===`backup-codes`?(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Two-factor authentication is on. Keep these backup codes somewhere safe: each one signs you in once if you lose your phone. They are not shown again.`}),(0,V.jsx)(Af,{codes:c.codes}),(0,V.jsx)(U,{variant:`primary`,onClick:a,className:`min-h-10`,children:`I saved my backup codes`})]}):c.kind===`scan`?(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),C(c.setup)},children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Scan this code with your authenticator app, then enter the 6-digit code it shows.`}),(0,V.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,V.jsx)(Cp,{uri:c.setup.totpURI,className:`size-44 rounded-md border`}),(0,V.jsxs)(`p`,{className:`text-center text-xs text-muted-foreground`,children:[`Can't scan it? Enter this key in the app:`,(0,V.jsx)(`span`,{className:`mt-1 block break-all font-mono text-body text-foreground`,children:wp(c.setup.totpURI)})]})]}),(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Code from the app`,(0,V.jsx)(Ff,{name:`code`,required:!0,autoFocus:!0,value:m,invalid:!!v,onChange:h,onComplete:e=>!g&&void C(c.setup,e)})]}),w,(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:g,className:`min-h-10`,children:`Turn on`}),s&&(0,V.jsx)(U,{variant:`ghost`,onClick:s,className:`min-h-10`,children:`Cancel`})]}):(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),S()},children:[(0,V.jsx)(`div`,{role:`radiogroup`,"aria-label":`Second step`,className:`flex flex-col gap-2`,children:b.map(e=>(0,V.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":u===e.value,onClick:()=>d(e.value),className:B(`rounded-md border p-3 text-left transition-colors`,u===e.value?`border-primary bg-primary-soft`:`border-border-strong hover:bg-muted`),children:[(0,V.jsx)(`span`,{className:`block font-medium`,children:e.label}),(0,V.jsx)(`span`,{className:`mt-0.5 block text-xs text-muted-foreground`,children:e.description})]},e.value))}),t&&(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Your password`,(0,V.jsx)(Td,{type:`password`,name:`password`,autoComplete:`current-password`,required:!0,value:f,invalid:!!v,onChange:e=>p(e.target.value),className:`min-h-6`})]}),w,(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:g,className:`min-h-10`,children:`Continue`}),s&&(0,V.jsx)(U,{variant:`ghost`,onClick:s,className:`min-h-10`,children:`Cancel`})]})},Dp={allowed:`Ask for a second step after your password or an emailed sign-in code: a code from an authenticator app, or one emailed to you. A passkey needs no second step.`,required:`This app requires two-factor authentication for every account. Turn it on to keep using the app.`,forbidden:`Your admin turned two-factor authentication off for this app.`},Op=e=>{let{rule:t,enabled:n,authenticatorApp:r,mail:i,needsPassword:a,onTurnOff:s,onNewBackupCodes:c,onChanged:l}=e,[u,d]=(0,o.useState)(),f=()=>d(void 0),p=n?(0,V.jsx)(Zu,{tone:`green`,children:`On`}):t===`required`?(0,V.jsx)(Zu,{tone:`amber`,children:`Required`}):(0,V.jsx)(Zu,{children:`Off`}),m=n?r?`Signing in with a password or an emailed sign-in code also asks for a code from your authenticator app${i?`, or one emailed to you`:``}. Backup codes work when you do not have the app.`:`Signing in with a password or an emailed sign-in code also asks for a code emailed to you.`:Dp[t];return u?.kind===`setup`?(0,V.jsx)(wf,{title:`Two-factor authentication`,status:p,description:m,children:(0,V.jsx)(`div`,{className:`max-w-sm`,children:(0,V.jsx)(Ep,{offerEmailedCodes:i&&!u.appOnly,needsPassword:a,onStartApp:e.onStartApp,onConfirmApp:e.onConfirmApp,onEmailedCodes:e.onEmailedCodes,onCancel:f,onDone:()=>{f(),l()}})})}):(0,V.jsxs)(wf,{title:`Two-factor authentication`,status:p,description:m,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[!n&&t!==`forbidden`&&(0,V.jsx)(U,{variant:`primary`,onClick:()=>d({kind:`setup`,appOnly:!1}),children:`Turn on`}),n&&!r&&t!==`forbidden`&&(0,V.jsx)(U,{onClick:()=>d({kind:`setup`,appOnly:!0}),children:`Add an authenticator app`}),n&&r&&(0,V.jsx)(U,{onClick:()=>d({kind:`new-codes`}),children:`New backup codes`}),n&&(0,V.jsx)(U,{variant:`danger`,disabled:t===`required`,title:t===`required`?`This app requires two-factor authentication.`:void 0,onClick:()=>d({kind:`turn-off`}),children:`Turn off`})]}),u?.kind===`turn-off`&&(0,V.jsx)(jf,{title:`Turn off two-factor authentication?`,description:`Signing in then needs only your password or an emailed code. Your backup codes stop working.`,confirmLabel:`Turn off`,danger:!0,needsPassword:a,onClose:f,onConfirm:async e=>{await s(e),f(),l()}}),u?.kind===`new-codes`&&(0,V.jsx)(jf,{title:`Make new backup codes?`,description:`Your current backup codes stop working, and you get ten new ones.`,confirmLabel:`Make new codes`,needsPassword:a,onClose:f,onConfirm:async e=>d({kind:`codes`,codes:await c(e)})}),u?.kind===`codes`&&(0,V.jsx)(Cf,{title:`Your new backup codes`,description:`Keep them somewhere safe: each one signs you in once if you lose your phone. They are not shown again.`,onClose:f,actions:(0,V.jsx)(U,{variant:`primary`,onClick:f,children:`I saved my backup codes`}),children:(0,V.jsx)(Af,{codes:u.codes})})]})},kp=()=>{let e=Yd(window.location.href);return e&&window.history.replaceState(window.history.state,``,Xd(window.location.href)),e},Ap=({email:e})=>{let{session:t,signInProviders:n,linkProvider:r}=H(),{account:i}=t,[a,s]=(0,o.useState)(),[c,l]=(0,o.useState)(),[u]=(0,o.useState)(kp),d=(0,o.useCallback)(()=>{Promise.all([i.signInMethods(),i.passkeys(),i.linkedProviders()]).then(([e,t,n])=>s({methods:e,passkeys:t,linked:n}),e=>l(e instanceof lc?Bd(e):`Could not read your sign-in methods`))},[i]);(0,o.useEffect)(d,[d]);let f=e=>e.then(e=>(d(),e));return(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(Fd,{title:`Sign-in & security`,subtitle:e}),a?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Df,{rule:a.methods.policy.passkey,passkeys:a.passkeys,onAdd:()=>f(i.addPasskey()),onRename:(e,t)=>f(i.renamePasskey(e,t)),onRemove:e=>f(i.removePasskey(e))}),(0,V.jsx)(Op,{rule:a.methods.policy.twoFactor,enabled:a.methods.account.twoFactor,authenticatorApp:a.methods.account.authenticatorApp,mail:a.methods.mail,needsPassword:a.methods.account.password,onStartApp:e=>i.startAuthenticatorApp(e),onConfirmApp:e=>i.confirmAuthenticatorApp(e),onEmailedCodes:e=>i.turnOnEmailedCodes(e),onTurnOff:e=>i.turnOffTwoFactor(e),onNewBackupCodes:e=>i.newBackupCodes(e),onChanged:d}),n.length>0&&(0,V.jsx)(Of,{providers:n,linked:a.linked,onConnect:r,error:u&&Gd(u,n.length===1?n[0].name:`the provider`)})]}):c?(0,V.jsx)(`p`,{role:`alert`,className:`text-danger-text`,children:c}):(0,V.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(Dd,{}),` Loading`]})]})},jp=[{value:`allowed`,label:`On`},{value:`forbidden`,label:`Off`}],Mp=[{value:`allowed`,label:`Optional`},{value:`required`,label:`Required`},{value:`forbidden`,label:`Off`}],Np=[{method:`password`,label:`Password`,description:`Sign in with the email address and a password.`,rules:jp},{method:`emailCode`,label:`Emailed sign-in code`,description:`Sign in with a one-time code mailed to the account's address.`,rules:jp},{method:`passkey`,label:`Passkeys`,description:`Sign in with Face ID, Touch ID, Windows Hello, a phone or a security key. Required: everyone adds one after signing in.`,rules:Mp},{method:`twoFactor`,label:`Two-factor authentication`,description:`A code from an authenticator app, or an emailed one, after a password or an emailed sign-in code. Required: everyone turns it on after signing in.`,rules:Mp},{method:`staffAccess`,label:`Staff sign-in as a person`,description:`The team that runs this app signs in as someone to help them, with a reason, for a short session. Each time is in the log below; with "Email the person" they are told too.`,rules:[{value:`allowed`,label:`On`},{value:`notify`,label:`Email the person`},{value:`forbidden`,label:`Off`}]},{method:`platformSignIn`,label:`Sign-in through the platform`,description:`The sign-in provider the platform that runs this app adds, for people who have an account here already. It never creates accounts.`,rules:jp}],Pp=(e,t)=>{let n=Np.find(t=>t.method===e)?.rules.find(e=>e.value===t)?.label;if(n===void 0)throw Error(`No label for the ${t} rule of ${e}`);return n},Fp=({row:e,value:t,onChange:n})=>(0,V.jsx)(`span`,{role:`radiogroup`,"aria-label":e.label,className:`inline-flex h-8 shrink-0 rounded-md bg-muted p-0.5`,children:e.rules.map(e=>(0,V.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e.value===t,onClick:()=>n(e.value),className:B(`rounded px-3 text-xs font-medium transition-colors`,e.value===t?`bg-background text-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`),children:e.label},e.value))}),Ip=({method:e},t,{mail:n,effective:r,policy:i})=>{if(e===`emailCode`&&!n)return`Needs mail settings (PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM): off until they are set.`;if(e===`password`&&!n&&t.password===`forbidden`)return`Without mail settings, password sign-in stays on so nobody is locked out.`;if(e===`staffAccess`&&!n&&t.staffAccess===`notify`)return`Needs mail settings (PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM): staff cannot sign in until they are set.`;if(e===`platformSignIn`&&t.platformSignIn===`allowed`&&(t.passkey===`required`||t.twoFactor===`required`))return`Off while passkeys or two-factor authentication are required: it skips the second step.`;if(t[e]===i[e]&&r[e]!==i[e])return`Applies as ${Pp(e,r[e])} for now.`},Lp=({operator:e,platformSignIn:t})=>Np.flatMap(n=>n.method===`staffAccess`&&!e?[]:n.method===`platformSignIn`?t?[{...n,label:`Sign in with ${t} through the platform`}]:[]:[n]),Rp=({state:e,onSave:t,busy:n,error:r,notice:i})=>{let[a,s]=(0,o.useState)(e.policy),c=Lp(e),l=c.some(({method:t})=>a[t]!==e.policy[t]);return(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),t(a)},children:[(0,V.jsx)(`ul`,{className:`divide-y rounded-lg border bg-background`,children:c.map(t=>{let n=Ip(t,a,e);return(0,V.jsxs)(`li`,{className:`flex flex-col gap-3 p-4 sm:flex-row sm:items-start sm:justify-between`,children:[(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsx)(`h2`,{className:`font-semibold`,children:t.label}),(0,V.jsx)(`p`,{className:`mt-0.5 text-muted-foreground`,children:t.description}),n&&(0,V.jsx)(`p`,{className:`mt-1.5 text-xs font-medium text-warning-text`,children:n})]}),(0,V.jsx)(Fp,{row:t,value:a[t.method],onChange:e=>s({...a,[t.method]:e})})]},t.method)})}),r&&(0,V.jsx)(`p`,{role:`alert`,className:`rounded-md bg-danger-soft px-3 py-2 text-xs font-medium text-danger-text`,children:r}),i&&!l&&(0,V.jsx)(`p`,{role:`status`,className:`rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:i}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.savedAt?`Last saved${e.savedBy?` by ${e.savedBy}`:``} on ${hf(Date.parse(e.savedAt))}.`:`Never changed: everything is on, nothing is required.`}),(0,V.jsxs)(`div`,{className:`flex gap-2`,children:[l&&(0,V.jsx)(U,{onClick:()=>s(e.policy),children:`Reset`}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:n,disabled:!l,children:`Save`})]})]})]})},zp=(e,t)=>e.endedAt?(0,V.jsxs)(Zu,{tone:`neutral`,children:[`Stopped `,hf(Date.parse(e.endedAt))]}):Date.parse(e.expiresAt)<=t?(0,V.jsxs)(Zu,{tone:`neutral`,children:[`Ended `,hf(Date.parse(e.expiresAt))]}):(0,V.jsxs)(Zu,{tone:`amber`,children:[`Signed in until `,hf(Date.parse(e.expiresAt))]}),Bp=({signIns:e,operator:t,error:n,now:r=Date.now()})=>(0,V.jsxs)(wf,{title:`Staff sign-ins`,description:`Each time staff of ${t} signed in as someone here, newest first.`,children:[(0,V.jsx)(Tf,{message:n}),e&&e.length===0&&(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`No staff has signed in as anyone yet.`}),e&&e.length>0&&(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:e.map(e=>(0,V.jsxs)(`li`,{className:`flex flex-col gap-1.5 p-3`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,V.jsx)(`span`,{className:`font-medium break-all`,children:e.staffName?`${e.staffName} (${e.staff})`:e.staff}),(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`as`}),(0,V.jsx)(`span`,{className:`font-medium break-all`,children:e.user})]}),(0,V.jsx)(`p`,{className:`break-words`,children:e.reason}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[(0,V.jsx)(`span`,{children:hf(Date.parse(e.startedAt))}),zp(e,r)]})]},e.id))})]}),Vp=({operator:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)(),[i,a]=(0,o.useState)();return(0,o.useEffect)(()=>{t.staff.log().then(r,e=>a(e instanceof lc?Bd(e):`Could not read the staff sign-ins`))},[t]),(0,V.jsx)(Bp,{operator:e,signIns:n,error:i})},Hp=()=>{let{session:e}=H(),[t,n]=(0,o.useState)(),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)(),[c,l]=(0,o.useState)();(0,o.useEffect)(()=>{e.signInPolicy.read().then(n,e=>s(e instanceof lc?Bd(e):`Could not read the sign-in policy`))},[e]);let u=async t=>{i(!0),s(void 0),l(void 0);try{n(await e.signInPolicy.save(t)),l(`Saved. It applies to every sign-in from now on.`)}catch(e){if(!(e instanceof lc))throw e;s(Bd(e))}i(!1)};return(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(Fd,{title:`Sign-in policy`,subtitle:`How people sign in to this app. Signed-in people keep their session, and are asked for what is newly required within 15 minutes.`}),t?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Rp,{state:t,busy:r,error:a,notice:c,onSave:e=>void u(e)},t.savedAt??`default`),t.operator&&(0,V.jsx)(Vp,{operator:t.operator})]}):a?(0,V.jsx)(`p`,{role:`alert`,className:`text-danger-text`,children:a}):(0,V.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(Dd,{}),` Loading`]})]})},Up=o.createContext(void 0),Wp=e=>{let t=o.useContext(Up);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Gp=({client:e,children:t})=>(o.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,V.jsx)(Up.Provider,{value:e,children:t})),Kp={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},qp=new class{#e=Kp;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function Jp(e){setTimeout(e,0)}var Yp=typeof window>`u`||`Deno`in globalThis;function Xp(){}function Zp(e,t){return typeof e==`function`?e(t):e}function Qp(e){return typeof e==`number`&&e>=0&&e!==1/0}function $p(e,t){return Math.max(e+(t||0)-Date.now(),0)}function em(e,t){return typeof e==`function`?e(t):e}function tm(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==rm(o,t.options))return!1}else if(!am(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function nm(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(im(t.options.mutationKey)!==im(a))return!1}else if(!am(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function rm(e,t){return(t?.queryKeyHashFn||im)(e)}function im(e){return JSON.stringify(e,(e,t)=>um(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function am(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!am(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!am(e[r],t[r]))return!1;return!0}return!1}var om=Object.prototype.hasOwnProperty;function sm(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=lm(e)&&lm(t);if(!r&&!(um(e)&&um(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:om.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=sm(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function cm(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function lm(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function um(e){if(!dm(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!dm(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function dm(e){return Object.prototype.toString.call(e)===`[object Object]`}function fm(e){return new Promise(t=>{qp.setTimeout(t,e)})}function pm(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:sm(e,t)}function mm(e){return e}function hm(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function gm(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var _m=Symbol();function vm(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===_m?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ym(e,t){return typeof e==`function`?e(...t):!!e}function bm(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var xm=()=>Yp,Sm=()=>xm(),Cm=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},wm=new class extends Cm{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},Tm=Jp;function Em(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=Tm,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var Dm=Em(),Om=new class extends Cm{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function km(e){return Math.min(1e3*2**e,3e4)}function Am(e){return(e??`online`)!==`online`||Om.isOnline()}var jm=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function Mm(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(Xp);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new jm(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>wm.isFocused()&&(e.networkMode===`always`||Om.isOnline())&&e.canRun(),p=()=>Am(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=()=>new Promise(t=>{r=e=>{(c()||f())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(m).catch(r=>{if(c())return;let i=e.retry??(Sm()?0:3),a=e.retryDelay??km,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!s){h(r);return}n++,e.onFail?.(n,r),fm(o).then(()=>f()?void 0:g()).then(()=>{t?h(r):_()})})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g().then(_),s)}}var Nm=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Qp(this.gcTime)&&(this.#e=qp.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Sm()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(qp.clearTimeout(this.#e),this.#e=void 0)}};function Pm(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{bm(e,()=>t.signal,()=>n=!0)},u=vm(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?gm:hm;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Im:Fm,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:Fm(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function Fm(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Im(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Lm(e,t){return t?Fm(e,t)!=null:!1}function Rm(e,t){return!t||!e.getPreviousPageParam?!1:Im(e,t)!=null}var zm=class extends Nm{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Hm(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Hm(this.options);e.data!==void 0&&(this.setState(Vm(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=pm(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(Xp).catch(Xp):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>em(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===_m||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>em(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!$p(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=vm(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?Pm(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=Mm({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof jm&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof jm){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Bm(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Vm(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),Dm.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Bm(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Am(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Vm(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Hm(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Um=class extends Cm{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Gm(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Km(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Km(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof em(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!cm(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&qm(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||em(this.options.enabled,this.#t)!==em(t.enabled,this.#t)||em(this.options.staleTime,this.#t)!==em(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||em(this.options.enabled,this.#t)!==em(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return cm(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Xp)),t}#h(e){return!Sm()&&em(this.options.enabled,this.#t)!==!1&&Qp(e)}#g(){this.#b();let e=em(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=$p(this.#r.dataUpdatedAt,e)+1;this.#u=qp.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return em(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=qp.setInterval(()=>{(this.options.refetchIntervalInBackground||wm.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(qp.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(qp.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Gm(e,t),o=i&&qm(e,n,t,r);(a||o)&&(l={...l,...Bm(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=pm(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=pm(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:Jm(e,t),refetch:this.refetch,isEnabled:em(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),cm(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})();Dm.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function Wm(e,t){return em(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||em(t.retryOnMount,e)!==!1)}function Gm(e,t){return Wm(e,t)||e.state.data!==void 0&&Km(e,t,t.refetchOnMount)}function Km(e,t,n){if(em(t.enabled,e)!==!1&&em(t.staleTime,e)!==`static`){let r=em(n,e);return r===`always`||r!==!1&&Jm(e,t)}return!1}function qm(e,t,n,r){return(e!==t||em(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Jm(e,n)}function Jm(e,t){return em(t.enabled,e)!==!1&&e.isStaleByTime(em(t.staleTime,e))}var Ym=class extends Um{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type=`infinite`,super.setOptions(e)}getOptimisticResult(e){return e._type=`infinite`,super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`forward`}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`backward`}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:a,isError:o,isRefetchError:s}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c===`forward`,u=i&&c===`forward`,d=o&&c===`backward`,f=i&&c===`backward`;return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Lm(t,n.data),hasPreviousPage:Rm(t,n.data),isFetchNextPageError:l,isFetchingNextPage:u,isFetchPreviousPageError:d,isFetchingPreviousPage:f,isRefetchError:s&&!l&&!d,isRefetching:a&&!u&&!f}}},Xm=class extends Nm{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Zm(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=Mm({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),Dm.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Zm(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Qm=class extends Cm{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new Xm({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=$m(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=$m(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=$m(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=$m(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){Dm.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>nm(t,e))}findAll(e={}){return this.getAll().filter(t=>nm(e,t))}notify(e){Dm.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return Dm.batch(()=>Promise.all(e.map(e=>e.continue().catch(Xp))))}};function $m(e){return e.options.scope?.id}var eh=class extends Cm{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),cm(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&im(t.mutationKey)!==im(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??Zm();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){Dm.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,n=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{this.#r.onSuccess?.(e.data,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,n,r)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{this.#r.onError?.(e.error,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,n,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}};function th(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var nh=class extends Cm{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=[];constructor(e,t,n){super(),this.#e=e,this.#r=n,this.#n=[],this.#i=[],this.#t=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#i.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#i.forEach(e=>{e.destroy()})}setQueries(e,t){this.#n=e,this.#r=t,Dm.batch(()=>{let e=this.#i,t=this.#p(this.#n);t.forEach(e=>e.observer.setOptions(e.defaultedQueryOptions));let n=t.map(e=>e.observer),r=n.map(e=>e.getCurrentResult()),i=e.length!==n.length,a=n.some((t,n)=>t!==e[n]),o=i||a,s=o?!0:r.some((e,t)=>{let n=this.#t[t];return!n||!cm(e,n)});(o||s)&&(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(th(e,n).forEach(e=>{e.destroy()}),th(n,e).forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})),this.#h()))})}getCurrentResult(){return this.#t}getQueries(){return this.#i.map(e=>e.getCurrentQuery())}getObservers(){return this.#i}getOptimisticResult(e,t){let n=this.#p(e),r=n.map(e=>e.observer.getOptimisticResult(e.defaultedQueryOptions)),i=n.map(e=>e.defaultedQueryOptions.queryHash);return[r,e=>this.#d(e??r,t,i),()=>this.#u(r,n)]}#u(e,t){let n=new Set;return t.map((r,i)=>{let a=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?a:r.observer.trackResult(a,e=>{n.has(e)||(n.add(e),t.forEach(t=>{t.observer.trackProp(e)}))})})}#d(e,t,n){if(t){let r=this.#c,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((e,t)=>e!==r[t]));return(this.#t!==this.#s||i||t!==this.#o)&&(this.#o=t,this.#s=this.#t,n!==void 0&&(this.#c=n),this.#a=sm(this.#a,t(e))),this.#a}return e}#f(){return!this.#r?.combine||this.#i.some((e,t)=>e.options.suspense&&this.#t[t]?.data===void 0)}#p(e){let t=new Map;this.#i.forEach(e=>{let n=e.options.queryHash;if(!n)return;let r=t.get(n);r?r.push(e):t.set(n,[e])});let n=[];return e.forEach(e=>{let r=this.#e.defaultQueryOptions(e),i=t.get(r.queryHash)?.shift()??new Um(this.#e,r);n.push({defaultedQueryOptions:r,observer:i})}),n}#m(e,t){let n=this.#i.indexOf(e);n!==-1&&(this.#t=this.#t.slice(),this.#t[n]=t,this.#h())}#h(){if(this.hasListeners()){let e=this.#f(),t=this.#a,n=e?t:this.#d(this.#u(this.#t,this.#l),this.#r?.combine);(e||t!==n)&&Dm.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}},rh=class extends Cm{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??rm(r,t),a=this.get(i);return a||(a=new zm({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){this.#e.get(e.queryHash)===e&&(e.destroy(),this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){Dm.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>tm(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>tm(e,t)):t}notify(e){Dm.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Dm.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Dm.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},ih=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new rh,this.#t=e.mutationCache||new Qm,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=wm.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=Om.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(em(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=Zp(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return Dm.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;Dm.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return Dm.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=Dm.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(Xp).catch(Xp)}invalidateQueries(e,t={}){return Dm.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=Dm.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(Xp)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(Xp)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(em(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(em(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Xp).catch(Xp)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Xp).catch(Xp)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return Om.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(im(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{am(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(im(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{am(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=rm(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===_m&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},ah=o.createContext(!1),oh=()=>o.useContext(ah);ah.Provider;function sh(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var ch=o.createContext(sh()),lh=()=>o.useContext(ch),uh=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?ym(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},dh=e=>{o.useEffect(()=>{e.clearReset()},[e])},fh=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ym(n,[e.error,r])),ph=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},mh=(e,t)=>e?.suspense&&t.isPending,hh=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function gh({queries:e,...t},n){let r=Wp(n),i=oh(),a=lh(),s=t.subscribed!==!1,c=o.useMemo(()=>e.map(e=>{let t=r.defaultQueryOptions(e);return t._optimisticResults=i?`isRestoring`:s?`optimistic`:void 0,t}),[e,r,i,s]);c.forEach(e=>{ph(e);let t=r.getQueryCache().get(e.queryHash);uh(e,a,t)}),dh(a);let[l]=o.useState(()=>new nh(r,c,t)),[u,d,f]=l.getOptimisticResult(c,t.combine),p=!i&&s;o.useSyncExternalStore(o.useCallback(e=>p?l.subscribe(Dm.batchCalls(e)):Xp,[l,p]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),o.useEffect(()=>{l.setQueries(c,t)},[c,t,l]);let m=u.some((e,t)=>mh(c[t],e))?u.flatMap((e,t)=>{let n=c[t];return n&&mh(n,e)?hh(n,new Um(r,n),a):[]}):[];if(m.length>0)throw Promise.all(m);let h=u.find((e,t)=>{let n=c[t];return n&&fh({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(h)throw h.error;return d(f())}function _h(e,t,n){let r=oh(),i=lh(),a=Wp(n),s=a.defaultQueryOptions(e),c=a.getQueryCache().get(s.queryHash),l=e.subscribed!==!1;s._optimisticResults=r?`isRestoring`:l?`optimistic`:void 0,ph(s),uh(s,i,c),dh(i);let[u]=o.useState(()=>new t(a,s)),d=u.getOptimisticResult(s),f=!r&&l;if(o.useSyncExternalStore(o.useCallback(e=>{let t=f?u.subscribe(Dm.batchCalls(e)):Xp;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),o.useEffect(()=>{u.setOptions(s)},[s,u]),mh(s,d))throw hh(s,u,i);if(fh({result:d,errorResetBoundary:i,throwOnError:s.throwOnError,query:c,suspense:s.suspense}))throw d.error;return s.notifyOnChangeProps?d:u.trackResult(d)}function vh(e,t){return _h(e,Um,t)}function yh(e,t){let n=Wp(t),[r]=o.useState(()=>new eh(n,e));o.useEffect(()=>{r.setOptions(e)},[r,e]);let i=o.useSyncExternalStore(o.useCallback(e=>r.subscribe(Dm.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=o.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(Xp)},[r]);if(i.error&&ym(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function bh(e,t){return _h(e,Ym,t)}var $te=()=>{let e=0;return{refetchOnWindowFocus:()=>e>0?!1:`always`,pause:()=>{e+=1;let t=!1;return()=>{t||(t=!0,--e)}}}},xh=(0,o.createContext)(null),ene=e=>{let t=(0,o.useContext)(xh);(0,o.useEffect)(()=>e&&t?t.pause():void 0,[e,t])},tne=e=>{let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),window.addEventListener(`focus`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t),window.removeEventListener(`focus`,t)}},W={meta:[`meta`],sourceMeta:(e,t)=>[`source-meta`,e,t.join(`,`)],sourceMetas:e=>[`source-meta`,e],list:(e,t,n,r,i)=>[`list`,e,t,n,r,i],page:(e,t,n,r,i)=>[`page`,e,t,n,r,i],pages:(e,t,n)=>[`page`,e,t,n],navRecent:(e,t,n,r)=>[`list`,e,t,n,r,`nav-recent`],first:(e,t,n)=>[`first-page`,e,t,n],record:(e,t)=>[`record`,e,t],recordPreview:(e,t)=>[`record-preview`,e,t],history:(e,t,n)=>[`record`,e,t,`history`,n],facets:(e,t,n)=>[`facets`,e,t,n],series:(e,t,n,r,i)=>[`series`,e,t,n,r,i],aggregate:(e,t)=>[`aggregate`,e,t],histogram:(e,t,n,r)=>[`histogram`,e,t,n,r],map:(e,t,n,r,i)=>[`map`,e,t,n,r,i],relatedLabel:(e,t)=>[`related-label`,e,t],labels:(e,t)=>[`labels`,e,t],count:(e,t)=>[`count`,e,t],exportCount:(e,t)=>[`list`,e,t,`export-count`],firstRecord:(e,t,n)=>[`first-record`,e,t,n],pathValue:(e,t,n)=>[`path-value`,e,t,n]},Sh=(0,o.createContext)(null),Ch=(0,o.createContext)(null),wh=(0,o.createContext)(null),G=()=>{let e=(0,o.useContext)(Sh);if(!e)throw Error(`useClient must be used inside ApiProvider`);return e},Th=e=>{let t=G();return(0,o.useContext)(wh)?.(e)??t},nne=()=>{let e=G(),t=(0,o.useContext)(wh);return(0,o.useCallback)(n=>t?.(n)??e,[e,t])},rne=()=>{let e=(0,o.useContext)(Ch);if(!e)throw Error(`useSourceClients must be used inside ApiProvider`);return e},ine=({client:e,resourceClient:t,children:n})=>(0,V.jsx)(Sh.Provider,{value:e,children:(0,V.jsx)(wh.Provider,{value:t,children:n})}),Eh=({baseUrl:e,client:t,sources:n,fetch:r,queryClient:i,token:a,onUnauthenticated:s,children:c})=>{let[l]=(0,o.useState)($te),[u]=(0,o.useState)(()=>i??new ih({defaultOptions:{queries:{staleTime:3e4,retry:!1,refetchOnWindowFocus:l.refetchOnWindowFocus}}}));(0,o.useEffect)(()=>wm.setEventListener(tne),[]);let d=(0,o.useRef)(void 0),f=(0,o.useMemo)(()=>t??qs({baseUrl:e,fetch:r,token:a,onUnauthenticated:s,onMetaVersion:e=>{let t=d.current;d.current=e,t!==void 0&&t!==e&&u.invalidateQueries({queryKey:W.meta},{cancelRefetch:!1})}}),[t,e,r,u,a,s]),p=(0,o.useMemo)(()=>{let e=new Map;return t=>{let i=n?.[t.url]??e.get(t.url);if(i)return i;let o,s=qs({baseUrl:t.url,fetch:r,token:a,onMetaVersion:e=>{let n=o;o=e,n!==void 0&&n!==e&&u.invalidateQueries({queryKey:W.sourceMetas(t.url)},{cancelRefetch:!1})}});return e.set(t.url,s),s}},[n,r,a,u]);return(0,V.jsx)(Gp,{client:u,children:(0,V.jsx)(Sh.Provider,{value:f,children:(0,V.jsx)(Ch.Provider,{value:p,children:(0,V.jsx)(xh.Provider,{value:l,children:c})})})})},Dh=(0,o.createContext)(null),Oh=()=>{let e=(0,o.useContext)(Dh);if(!e)throw Error(`useRouter must be used inside Router`);return e},kh=()=>`${window.location.pathname}${window.location.search}`,Ah=e=>new URL(e,`http://local`).pathname,jh=()=>window.history.state?.protobaseIndex??0,ane=({basePath:e=``,initialUrl:t,children:n})=>{let r=t!==void 0,[i,a]=(0,o.useState)(t??kh()),s=(0,o.useRef)(new Set),c=(0,o.useRef)(i);c.current=i;let l=(0,o.useRef)(r?0:jh()),u=(0,o.useRef)(!1),d=(0,o.useRef)(!1),[f,p]=(0,o.useState)();(0,o.useEffect)(()=>{if(r)return;window.history.replaceState({protobaseIndex:l.current},``);let e=()=>{let e=jh();if(u.current){u.current=!1,l.current=e;return}let t=e-l.current,n=Ah(kh())!==Ah(c.current);if(!d.current&&s.current.size>0&&n){u.current=!0,window.history.go(-t),p({kind:`history`,delta:t});return}d.current=!1,l.current=e,a(kh())};return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[r]);let m=(0,o.useCallback)((e,t)=>{r||(l.current+=+!t,window.history[t?`replaceState`:`pushState`]({protobaseIndex:l.current},``,e)),a(e)},[r]),h=(0,o.useCallback)((t,{replace:n=!1}={})=>{let r=`${e}${t}`;if(Ah(r)!==Ah(c.current)&&s.current.size>0)return p({kind:`link`,full:r,replace:n});m(r,n)},[e,m]),g=(0,o.useCallback)(()=>{let e=Symbol(`guard`);return s.current.add(e),()=>void s.current.delete(e)},[]),_=()=>{if(f){if(p(void 0),f.kind===`link`)return m(f.full,f.replace);d.current=!0,window.history.go(f.delta)}},v=(0,o.useMemo)(()=>{let t=new URL(i,`http://local`);return{path:t.pathname.slice(e.length)||`/`,params:t.searchParams,basePath:e,entry:l.current,navigate:h,registerGuard:g}},[i,e,h,g]);return(0,V.jsxs)(Dh.Provider,{value:v,children:[n,f&&(0,V.jsx)(Cf,{title:`Leave without saving?`,description:`You have unsaved changes on this page. They stay in this browser, and come back when you open the record again.`,onClose:()=>p(void 0),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>p(void 0),children:`Stay`}),(0,V.jsx)(U,{variant:`primary`,onClick:_,children:`Leave`})]})})]})},one=({to:e,replace:t,...n})=>{let{navigate:r,basePath:i}=Oh();return(0,V.jsx)(Nu,{to:{href:`${i}${e}`,onFollow:()=>r(e,{replace:t})},...n})},sne=e=>{let{registerGuard:t}=Oh();(0,o.useEffect)(()=>e?t():void 0,[e,t]),(0,o.useEffect)(()=>{if(!e)return;let t=e=>e.preventDefault();return window.addEventListener(`beforeunload`,t),()=>window.removeEventListener(`beforeunload`,t)},[e])},Mh=({title:e,description:t,children:n})=>(0,V.jsx)(`div`,{className:`flex min-h-full w-full items-center justify-center bg-surface px-4 py-10`,children:(0,V.jsxs)(`div`,{className:`w-full max-w-sm`,children:[(0,V.jsxs)(`div`,{className:`mb-6 flex flex-col items-center text-center`,children:[(0,V.jsx)(Lu,{className:`size-10`}),(0,V.jsx)(`h1`,{className:`mt-4 text-xl font-semibold tracking-tight`,children:e}),t&&(0,V.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:t})]}),(0,V.jsx)(`div`,{className:`rounded-lg border bg-background p-5 shadow-sm`,children:n})]})}),Nh=({onResend:e,cooldown:t=30,disabled:n})=>{let[r,i]=(0,o.useState)(()=>Date.now()+t*1e3),[a,s]=(0,o.useState)(()=>Date.now()),c=Math.max(0,Math.ceil((r-a)/1e3));return(0,o.useEffect)(()=>{if(c===0)return;let e=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(e)},[c]),(0,V.jsx)(U,{variant:`ghost`,disabled:n||c>0,onClick:()=>{let n=Date.now();i(n+t*1e3),s(n),e()},className:`min-h-10`,children:c>0?`Send a new code in ${c}s`:`Send a new code`})},Ph=({title:e,description:t,explanation:n,submitLabel:r,onSubmit:i,onResend:a,onChangeAddress:s,changeAddressLabel:c,busy:l,error:u,notice:d,resendCooldown:f})=>{let[p,m]=(0,o.useState)(``);return(0,V.jsxs)(Mh,{title:e,description:t,children:[(0,V.jsx)(`p`,{className:`mb-4 text-muted-foreground`,children:n}),d&&(0,V.jsx)(`p`,{role:`status`,className:`mb-4 rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:d}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),i(p)},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Code`,(0,V.jsx)(Ff,{name:`code`,required:!0,autoFocus:!0,value:p,invalid:!!u,onChange:m,onComplete:e=>!l&&i(e)})]}),u&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:u}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:l,className:`min-h-10`,children:r}),(0,V.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-x-2 sm:justify-between`,children:[(0,V.jsx)(U,{variant:`ghost`,onClick:s,className:`min-h-10`,children:c}),(0,V.jsx)(Nh,{onResend:a,disabled:l,cooldown:f})]})]})]})},cne=({email:e,onBack:t,...n})=>(0,V.jsx)(Ph,{title:`Check your email`,description:`Enter the code we sent to sign in.`,explanation:(0,V.jsxs)(V.Fragment,{children:[`If `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:e}),` has an account, a 6-digit code is on its way. It works for 5 minutes, once.`]}),submitLabel:`Sign in`,onChangeAddress:t,changeAddressLabel:`Back to sign in`,...n}),lne=({email:e,onBack:t})=>{let{signInWithCode:n,sendSignInCode:r}=H(),[i,a]=(0,o.useState)(!1),[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(),d=async e=>{a(!0),c(void 0),u(void 0);try{await e()}catch(e){if(!(e instanceof lc))throw e;c(Bd(e))}a(!1)};return(0,V.jsx)(cne,{email:e,busy:i,error:s,notice:l,onBack:t,onSubmit:t=>void d(()=>n(e,t)),onResend:()=>void d(async()=>{await r(e),u(`A new code is on its way. Only the newest one works.`)})})},une=`protobase users create you@example.com`,dne=({command:e=une,onCheckAgain:t,busy:n})=>{let[r,i]=(0,o.useState)(!1);return(0,V.jsxs)(Mh,{title:`No admin yet`,description:`This Protobase has no users to sign in with.`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Run this in the terminal where Protobase runs, then reload. The first admin is created on the server, not in the browser, so nobody else can claim a fresh URL.`}),(0,V.jsxs)(`div`,{className:`mt-4 flex items-center gap-2 rounded-md border bg-surface py-1.5 pl-3 pr-1.5`,children:[(0,V.jsx)(`code`,{className:`min-w-0 flex-1 break-all font-mono text-xs`,children:e}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Copy command`,onClick:()=>{navigator.clipboard.writeText(e).then(()=>{i(!0),setTimeout(()=>i(!1),2e3)})},className:`inline-flex size-8 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted pointer-coarse:size-11`,children:r?(0,V.jsx)(he,{className:`size-4 text-success`}):(0,V.jsx)(Le,{className:`size-4`})})]}),(0,V.jsx)(U,{variant:`primary`,className:`mt-4 min-h-10 w-full`,loading:n,onClick:t,children:`Reload`})]})},fne=({onSubmit:e,back:t,busy:n,error:r,sentTo:i})=>{let[a,s]=(0,o.useState)(``);return i?(0,V.jsxs)(Mh,{title:`Check your email`,children:[(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`If `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:i}),` has an account, an email with a link to choose a new password is on its way. The link works once, for a limited time.`]}),(0,V.jsx)(Nu,{to:t,className:B(Sf({variant:`primary`}),`mt-4 min-h-10 w-full`),children:`Back to sign in`})]}):(0,V.jsx)(Mh,{title:`Reset your password`,description:`We email you a link to choose a new one.`,children:(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),e(a.trim())},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Email`,(0,V.jsx)(Td,{type:`email`,name:`email`,autoComplete:`username`,required:!0,autoFocus:!0,value:a,invalid:!!r,onChange:e=>s(e.target.value),className:`min-h-6`})]}),r&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:r}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:n,className:`min-h-10`,children:`Send reset link`}),(0,V.jsx)(Nu,{to:t,className:B(Sf({variant:`ghost`}),`min-h-10`),children:`Back to sign in`})]})})},Fh=`password-reset`,pne=e=>{let t=new URL(e);return`${t.origin}${t.pathname}?${Fh}`},mne=e=>{let t=new URL(e).searchParams;if(t.has(`password-reset`))return{token:t.get(`token`)||void 0}},hne=e=>{let t=new URL(e);for(let e of[Fh,`token`,`error`])t.searchParams.delete(e);return`${t.pathname}${t.search}${t.hash}`},gne=({back:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)(!1),[i,a]=(0,o.useState)(),[s,c]=(0,o.useState)(),l=async e=>{r(!0),a(void 0);try{await t.requestPasswordReset(e,pne(window.location.href)),c(e)}catch(e){if(!(e instanceof lc))throw e;a(e.status===429?`Too many requests. Wait a minute and try again.`:e.message)}r(!1)};return(0,V.jsx)(fne,{busy:n,error:i,sentTo:s,back:e,onSubmit:e=>void l(e)})},_ne=({name:e,workspace:t})=>(0,V.jsx)(Mh,{title:`Signing in with ${e}`,description:t,children:(0,V.jsxs)(`p`,{role:`status`,className:`flex items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(Dd,{}),` Taking you to `,e,`…`]})}),vne=({provider:e,workspace:t,onFailed:n})=>{let{signInProviders:r,signInSocial:i}=H(),a=r.find(t=>t.id===e),s=a?.name??Qd(e),c=(0,o.useRef)(!1);return(0,o.useEffect)(()=>{if(!c.current){if(c.current=!0,!a)return n(`Signing in with ${s} is not offered here. Sign in another way.`);i(e).catch(e=>{if(!(e instanceof lc))throw e;n(Vd(e))})}},[a,s,e,i,n]),(0,V.jsx)(_ne,{name:s,workspace:t})},yne=({onSubmit:e,invalidLink:t,onRequestNewLink:n,onBack:r,busy:i,error:a})=>{let[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(``),[d,f]=(0,o.useState)(!1);if(t)return(0,V.jsxs)(Mh,{title:`This link no longer works`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`A reset link works once, for a limited time. Ask for a new one to choose your password.`}),(0,V.jsxs)(`div`,{className:`mt-4 flex flex-col gap-2`,children:[n&&(0,V.jsx)(U,{variant:`primary`,className:`min-h-10`,onClick:n,children:`Send a new link`}),(0,V.jsx)(U,{variant:n?`ghost`:`primary`,className:`min-h-10`,onClick:r,children:`Back to sign in`})]})]});let p=d?`The passwords are not the same.`:a;return(0,V.jsx)(Mh,{title:`Choose a new password`,description:`At least 12 characters.`,children:(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),f(s!==l),s===l&&e(s)},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`New password`,(0,V.jsx)(Td,{type:`password`,name:`new-password`,autoComplete:`new-password`,required:!0,minLength:12,autoFocus:!0,value:s,invalid:!!p,onChange:e=>c(e.target.value),className:`min-h-6`})]}),(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Repeat new password`,(0,V.jsx)(Td,{type:`password`,name:`repeat-password`,autoComplete:`new-password`,required:!0,minLength:12,value:l,invalid:!!p,onChange:e=>u(e.target.value),className:`min-h-6`})]}),p&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:p}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:i,className:`min-h-10`,children:`Set new password`})]})})},bne=e=>e.status===429?`Too many attempts. Wait a minute and try again.`:e.code===`PASSWORD_TOO_SHORT`?`Use at least 12 characters.`:e.code===`PASSWORD_TOO_LONG`?`That password is too long.`:e.message,xne=({token:e,onDone:t,onRequestNewLink:n,onBack:r})=>{let{session:i}=H(),[a,s]=(0,o.useState)(!1),[c,l]=(0,o.useState)(),[u,d]=(0,o.useState)(!e),f=async n=>{s(!0),l(void 0);try{await i.resetPassword(e,n),t()}catch(e){if(!(e instanceof lc))throw e;e.code===`INVALID_TOKEN`?d(!0):l(bne(e)),s(!1)}};return(0,V.jsx)(yne,{busy:a,error:c,invalidLink:u,onRequestNewLink:n,onBack:r,onSubmit:e=>void f(e)})},Sne={twoFactor:`Turn on two-factor authentication`,passkey:`Add a passkey`},Cne=({step:e,twoFactor:t,onAddPasskey:n,busy:r,error:i,onSignOut:a})=>(0,V.jsxs)(Mh,{title:Sne[e],description:`This app requires it for every account.`,children:[e===`twoFactor`?(0,V.jsx)(Ep,{...t}):(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`A passkey signs you in with Face ID, Touch ID, Windows Hello, your phone or a security key. Your browser asks which one to use.`}),i&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:i}),(0,V.jsxs)(U,{variant:`primary`,loading:r,onClick:n,className:`min-h-10`,children:[(0,V.jsx)(gt,{className:`size-4`}),`Add a passkey`]})]}),(0,V.jsx)(`button`,{type:`button`,onClick:a,className:`mt-4 w-full text-center font-medium text-muted-foreground hover:underline`,children:`Sign out`})]}),wne=({missing:e})=>{let{session:t,recheck:n,signOut:r}=H(),[i,a]=(0,o.useState)(),[s,c]=(0,o.useState)(!1),[l,u]=(0,o.useState)();(0,o.useEffect)(()=>{t.account.signInMethods().then(a,e=>u(e instanceof lc?Bd(e):`Could not read your account`))},[t]);let d=async()=>{c(!0),u(void 0);try{await t.account.addPasskey(),n()}catch(e){if(!(e instanceof lc))throw e;u(Bd(e)),c(!1)}};return!i&&!l?(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(Dd,{}),` Loading`]}):(0,V.jsx)(Cne,{step:e[0],busy:s,error:l,onAddPasskey:()=>void d(),onSignOut:()=>void r(),twoFactor:{offerEmailedCodes:i?.mail??!1,needsPassword:i?.account.password??!0,onStartApp:e=>t.account.startAuthenticatorApp(e),onConfirmApp:e=>t.account.confirmAuthenticatorApp(e),onEmailedCodes:e=>t.account.turnOnEmailedCodes(e),onDone:n}})},Tne=({className:e})=>(0,V.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`currentColor`,className:B(`size-4 shrink-0`,e),"aria-hidden":!0,children:(0,V.jsx)(`path`,{d:`M10.226 17.284c-2.965-.36-5.054-2.493-5.054-5.256 0-1.123.404-2.336 1.078-3.144-.292-.741-.247-2.314.09-2.965.898-.112 2.111.36 2.83 1.01.853-.269 1.752-.404 2.853-.404 1.1 0 1.999.135 2.807.382.696-.629 1.932-1.1 2.83-.988.315.606.36 2.179.067 2.942.72.854 1.101 2 1.101 3.167 0 2.763-2.089 4.852-5.098 5.234.763.494 1.28 1.572 1.28 2.807v2.336c0 .674.561 1.056 1.235.786 4.066-1.55 7.255-5.615 7.255-10.646C23.5 6.188 18.334 1 11.978 1 5.62 1 .5 6.188.5 12.545c0 4.986 3.167 9.12 7.435 10.669.606.225 1.19-.18 1.19-.786V20.63a2.9 2.9 0 0 1-1.078.224c-1.483 0-2.359-.808-2.987-2.313-.247-.607-.517-.966-1.034-1.033-.27-.023-.359-.135-.359-.27 0-.27.45-.471.898-.471.652 0 1.213.404 1.797 1.235.45.651.921.943 1.483.943.561 0 .92-.202 1.437-.719.382-.381.674-.718.944-.943`})}),Ene=({id:e,className:t})=>e===`github`?(0,V.jsx)(Tne,{className:t}):null,Dne=()=>(0,V.jsxs)(`div`,{className:`my-4 flex items-center gap-3 text-xs text-muted-foreground`,children:[(0,V.jsx)(`span`,{className:`h-px flex-1 bg-border`}),`or`,(0,V.jsx)(`span`,{className:`h-px flex-1 bg-border`})]}),One=({onSubmit:e,busy:t,error:n,workspace:r,notice:i,methods:a=[`password`],onSendCode:s,onPasskey:c,passkeyDomains:l=[],forgotPassword:u,providers:d=[],onContinueWith:f,signUp:p,onBrowse:m})=>{let[h,g]=(0,o.useState)(``),[_,v]=(0,o.useState)(``),y=(0,o.useRef)(null),b=a.includes(`password`),x=a.includes(`emailCode`)&&s!==void 0,S=a.includes(`passkey`)&&c!==void 0,C=f?d:[],w=()=>{y.current?.reportValidity()&&s?.(h.trim())};return(0,V.jsxs)(Mh,{title:`Sign in to Protobase`,description:r,children:[i&&(0,V.jsx)(`p`,{role:`status`,className:`mb-4 rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:i}),(C.length>0||S)&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[C.map(e=>(0,V.jsxs)(U,{onClick:()=>f?.(e.id),disabled:t,className:`min-h-10 w-full`,children:[(0,V.jsx)(Ene,{id:e.id}),`Continue with `,e.name]},e.id)),S&&(0,V.jsxs)(U,{onClick:()=>c?.(),disabled:t,className:`min-h-10 w-full`,children:[(0,V.jsx)(gt,{className:`size-4`}),`Sign in with a passkey`]}),S&&l.slice(1).map(e=>(0,V.jsxs)(U,{variant:`ghost`,size:`sm`,onClick:()=>c?.(e),disabled:t,className:`w-full`,children:[`Use a passkey made for `,e]},e))]}),b||x?(0,V.jsx)(Dne,{}):n&&(0,V.jsx)(`p`,{role:`alert`,className:`mt-4 text-xs font-medium text-danger-text`,children:n})]}),(b||x)&&(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),b?e(h.trim(),_):w()},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Email`,(0,V.jsx)(Td,{ref:y,type:`email`,name:`email`,autoComplete:`username webauthn`,required:!0,autoFocus:!0,value:h,invalid:!!n,onChange:e=>g(e.target.value),className:`min-h-6`})]}),b&&(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Password`,(0,V.jsx)(Td,{type:`password`,name:`password`,autoComplete:`current-password`,required:!0,value:_,invalid:!!n,onChange:e=>v(e.target.value),className:`min-h-6`})]}),n&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:n}),b&&(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:t,className:`min-h-10`,children:`Sign in`}),x&&(0,V.jsxs)(U,{variant:b?`secondary`:`primary`,type:b?`button`:`submit`,onClick:b?w:void 0,loading:t&&!b,disabled:t,className:`min-h-10`,children:[(0,V.jsx)(zt,{className:`size-4`}),`Email me a sign-in code`]}),b&&u&&(0,V.jsx)(Nu,{to:u,className:`self-center font-medium text-primary-text hover:underline`,children:`Forgot password?`})]}),p&&(0,V.jsxs)(`p`,{className:`mt-4 text-center text-muted-foreground`,children:[`New here?`,` `,(0,V.jsx)(Nu,{to:p,className:`font-medium text-primary-text hover:underline`,children:`Create an account`})]}),m&&(0,V.jsx)(`button`,{type:`button`,onClick:m,className:`mt-4 w-full text-center font-medium text-muted-foreground hover:text-foreground hover:underline`,children:`Continue without signing in`})]})},kne=({workspace:e,notice:t,forgotPassword:n,signUp:r,onBrowse:i,onCodeSent:a,error:s})=>{let{signIn:c,signInSocial:l,signInProviders:u,signInMethods:d,passkeyDomains:f,sendSignInCode:p,signInWithPasskey:m}=H(),[h,g]=(0,o.useState)(!1),[_,v]=(0,o.useState)(s),y=async(e,t)=>{g(!0),v(void 0);try{await e()}catch(e){if(!(e instanceof lc))throw e;v(t(e)),g(!1)}};return(0,V.jsx)(One,{busy:h,error:_,workspace:e,notice:t,methods:d,forgotPassword:n,signUp:r,onBrowse:i,providers:u,onContinueWith:e=>void y(()=>l(e),Vd),passkeyDomains:f,onPasskey:e=>void y(()=>m(e),Bd),onSendCode:e=>void y(async()=>{await p(e),a(e)},Bd),onSubmit:(e,t)=>void y(()=>c(e,t),Vd)})},Ane=({email:e,onBack:t,...n})=>(0,V.jsx)(Ph,{title:`Check your email`,description:`Enter the code we sent to create your account.`,explanation:(0,V.jsxs)(V.Fragment,{children:[`A 6-digit code is on its way to `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:e}),`. It works for 5 minutes, once. If the address has an account already, the email says so instead.`]}),submitLabel:`Continue`,onChangeAddress:t,changeAddressLabel:`Use another address`,...n}),jne=({email:e,onSubmit:t,onBack:n,methods:r,busy:i,error:a})=>{let[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(``),d=(0,o.useId)(),f=r.includes(`password`),p=r.includes(`emailCode`);return(0,V.jsxs)(Mh,{title:`Your details`,description:`One last step to create your account.`,children:[(0,V.jsxs)(`p`,{className:`mb-4 text-muted-foreground`,children:[`The code was right: the account is for `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:e}),`.`]}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),t({name:s.trim(),...f&&l&&{password:l}})},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Your name`,(0,V.jsx)(Td,{name:`name`,autoComplete:`name`,required:!0,autoFocus:!0,maxLength:200,value:s,onChange:e=>c(e.target.value),className:`min-h-6`})]}),f&&(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[p?`Password (optional)`:`Password`,(0,V.jsx)(Td,{type:`password`,name:`password`,autoComplete:`new-password`,"aria-describedby":d,required:!p,minLength:12,maxLength:128,value:l,onChange:e=>u(e.target.value),className:`min-h-6`})]}),(0,V.jsxs)(`p`,{id:d,className:`text-xs text-muted-foreground`,children:[`At least `,12,` characters.`,p&&` Without one, you sign in with a code we email you.`]})]}),a&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:a}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:i,className:`min-h-10`,children:`Create account`}),(0,V.jsx)(U,{variant:`ghost`,onClick:n,className:`min-h-10`,children:`Use another address`})]})]})},Mne=({onSubmit:e,onSignIn:t,onBrowse:n,busy:r,error:i,workspace:a})=>{let[s,c]=(0,o.useState)(``);return(0,V.jsxs)(Mh,{title:`Create an account`,description:a,children:[(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),e(s.trim())},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Email`,(0,V.jsx)(Td,{type:`email`,name:`email`,autoComplete:`email`,required:!0,autoFocus:!0,value:s,invalid:!!i,onChange:e=>c(e.target.value),className:`min-h-6`})]}),(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`We email you a code to make sure the address is yours.`}),i&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:i}),(0,V.jsxs)(U,{variant:`primary`,type:`submit`,loading:r,className:`min-h-10`,children:[(0,V.jsx)(zt,{className:`size-4`}),`Email me a code`]}),(0,V.jsxs)(`p`,{className:`text-center text-muted-foreground`,children:[`Have an account?`,` `,(0,V.jsx)(`button`,{type:`button`,onClick:t,className:`font-medium text-primary-text hover:underline`,children:`Sign in`})]})]}),n&&(0,V.jsx)(`button`,{type:`button`,onClick:n,className:`mt-4 w-full text-center font-medium text-muted-foreground hover:text-foreground hover:underline`,children:`Continue without an account`})]})},Nne=({workspace:e,email:t,ticket:n,onCodeSent:r,onVerified:i,onBack:a,onSignIn:s,onBrowse:c})=>{let{signInMethods:l,sendSignUpCode:u,verifySignUpCode:d,signUp:f}=H(),[p,m]=(0,o.useState)(!1),[h,g]=(0,o.useState)(),[_,v]=(0,o.useState)(),y=async e=>{m(!0),g(void 0),v(void 0);try{await e()}catch(e){if(!(e instanceof lc))throw e;g(Bd(e))}m(!1)};return t===void 0?(0,V.jsx)(Mne,{workspace:e,busy:p,error:h,onSignIn:s,onBrowse:c,onSubmit:e=>void y(async()=>{await u(e),r(e)})}):n===void 0?(0,V.jsx)(Ane,{email:t,busy:p,error:h,notice:_,onBack:a,onSubmit:e=>void y(async()=>i(await d(t,e))),onResend:()=>void y(async()=>{await u(t),v(`A new code is on its way. Only the newest one works.`)})}):(0,V.jsx)(jne,{email:t,methods:l,busy:p,error:h,onBack:a,onSubmit:e=>void y(()=>f({ticket:n,...e}))})},Ih=`staff-sign-in`,Lh=`staff-error`,Pne=e=>{let t=new URL(e).searchParams,n=t.get(Lh);if(!t.has(`staff-sign-in`)&&!n)return;let r=t.has(Ih);return{email:r&&t.get(`email`)||``,reason:r&&t.get(`reason`)||``,...n&&{error:n}}},Rh=e=>{let t=new URL(e);if(t.searchParams.has(`staff-sign-in`))for(let e of[Ih,`email`,`reason`])t.searchParams.delete(e);return t.searchParams.delete(Lh),`${t.pathname}${t.search}${t.hash}`},Fne=10,Ine=({operator:e,email:t=``,reason:n=``,onSubmit:r,onBack:i,busy:a,error:s})=>{let[c,l]=(0,o.useState)(t),[u,d]=(0,o.useState)(n);return e?(0,V.jsx)(Mh,{title:`Sign in as a person`,description:`For staff of ${e}, to help someone with this app.`,children:(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),r(c.trim(),u.trim())},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Their email`,(0,V.jsx)(Td,{type:`email`,name:`email`,required:!0,autoFocus:!t,value:c,onChange:e=>l(e.target.value),className:`min-h-6`})]}),(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Reason`,(0,V.jsx)(`textarea`,{name:`reason`,required:!0,minLength:Fne,rows:3,value:u,placeholder:`Ticket 4211: the invoice totals look wrong`,onChange:e=>d(e.target.value),className:B(`resize-y rounded-md border bg-background px-2.5 py-1.5 font-normal shadow-sm outline-none placeholder:text-faint-foreground focus:border-primary focus:ring-2 focus:ring-primary/20`,s?`border-danger`:`border-border-strong`)})]}),(0,V.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`You sign in at `,e,` with a passkey or a second step. The session is short, shows a banner, and cannot change their sign-in. The app's admins see who signed in as whom, and why.`]}),s&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:s}),(0,V.jsxs)(U,{variant:`primary`,type:`submit`,loading:a,className:`min-h-10`,children:[`Continue with `,e]}),(0,V.jsx)(U,{variant:`ghost`,onClick:i,className:`min-h-10`,children:`Back to sign in`})]})}):(0,V.jsxs)(Mh,{title:`Staff sign-in`,description:`Staff of the team that runs this app cannot sign in as people here.`,children:[s&&(0,V.jsx)(`p`,{role:`alert`,className:`mb-4 text-xs font-medium text-danger-text`,children:s}),(0,V.jsx)(U,{variant:`primary`,className:`min-h-10 w-full`,onClick:i,children:`Back to sign in`})]})},Lne=({link:e,onBack:t})=>{let{session:n,staffSignIn:r}=H(),[i,a]=(0,o.useState)(!1),[s,c]=(0,o.useState)(e.error&&Ud(e.error)),l=async(e,t)=>{a(!0),c(void 0);try{let r=`${window.location.origin}${Rh(window.location.href)}`;window.location.assign(await n.staff.start({email:e,reason:t,callbackURL:r}))}catch(e){if(!(e instanceof lc))throw e;c(Ud(e)),a(!1)}};return(0,V.jsx)(Ine,{operator:r,email:e.email,reason:e.reason,busy:i,error:s,onBack:t,onSubmit:(e,t)=>void l(e,t)})},zh=({checked:e,indeterminate:t,onChange:n,label:r,disabled:i,className:a})=>(0,V.jsx)(`button`,{type:`button`,role:`checkbox`,"aria-checked":t?`mixed`:e,"aria-label":r,disabled:i,onClick:()=>n?.(!e),className:B(`relative inline-flex size-4 shrink-0 items-center justify-center rounded border transition-colors after:absolute after:-inset-1 after:content-[""] pointer-coarse:after:-inset-3.5`,e||t?`border-primary bg-primary text-primary-foreground`:`border-border-strong bg-background hover:border-faint-foreground`,a),children:t?(0,V.jsx)(iee,{className:`size-3`,strokeWidth:3}):e&&(0,V.jsx)(he,{className:`size-3`,strokeWidth:3})}),Rne={totp:`Enter the 6-digit code from your authenticator app.`,otp:`Enter the 6-digit code we emailed you. It works for 5 minutes.`,backup:`Enter one of the backup codes you saved when you set up the authenticator app. Each works once.`},zne=({methods:e,onVerify:t,onSendCode:n,onBack:r,busy:i,error:a,codeSent:s,initialStep:c})=>{let[l,u]=(0,o.useState)(c??(e.includes(`totp`)?`totp`:`otp`)),[d,f]=(0,o.useState)(``),[p,m]=(0,o.useState)(!1),h=l===`otp`&&!s,g=e=>{u(e),f(``),e===`otp`&&!s&&n()};return(0,V.jsxs)(Mh,{title:`Two-factor authentication`,description:`One more step to sign in.`,children:[h?(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`We email you a code to finish signing in.`}),a&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:a}),(0,V.jsx)(U,{variant:`primary`,loading:i,onClick:n,className:`min-h-10`,children:`Email me a code`})]}):(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),t({method:l,code:d.trim(),trustDevice:p})},children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:Rne[l]}),(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[l===`backup`?`Backup code`:`Code`,l===`backup`?(0,V.jsx)(Td,{name:`code`,autoComplete:`off`,spellCheck:!1,required:!0,autoFocus:!0,value:d,invalid:!!a,onChange:e=>f(e.target.value),className:`min-h-6 font-mono`}):(0,V.jsx)(Ff,{name:`code`,required:!0,autoFocus:!0,value:d,invalid:!!a,onChange:f})]}),(0,V.jsxs)(`label`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(zh,{checked:p,onChange:m,label:`Trust this browser`}),`Don't ask again in this browser for 30 days`]}),a&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:a}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:i,className:`min-h-10`,children:`Verify`})]}),(0,V.jsxs)(`div`,{className:`mt-4 flex flex-col items-center gap-2 border-t pt-4`,children:[l!==`totp`&&e.includes(`totp`)&&(0,V.jsx)(`button`,{type:`button`,onClick:()=>g(`totp`),className:`font-medium text-primary-text hover:underline`,children:`Use the authenticator app`}),l!==`otp`&&e.includes(`otp`)&&(0,V.jsx)(`button`,{type:`button`,onClick:()=>g(`otp`),className:`font-medium text-primary-text hover:underline`,children:`Email me a code instead`}),l!==`backup`&&e.includes(`totp`)&&(0,V.jsx)(`button`,{type:`button`,onClick:()=>g(`backup`),className:`font-medium text-primary-text hover:underline`,children:`Use a backup code`}),(0,V.jsx)(`button`,{type:`button`,onClick:r,className:`font-medium text-muted-foreground hover:underline`,children:`Back to sign in`})]})]})},Bne=({methods:e,onBack:t})=>{let{verifyTwoFactor:n,session:r}=H(),[i,a]=(0,o.useState)(!1),[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(!1),d=async e=>{a(!0),c(void 0);try{await e()}catch(e){if(!(e instanceof lc))throw e;c(Bd(e))}a(!1)};return(0,V.jsx)(zne,{methods:e,busy:i,error:s,codeSent:l,onBack:t,onVerify:e=>void d(()=>n(e)),onSendCode:()=>void d(async()=>{await r.sendTwoFactorCode(),u(!0)})})},Bh=()=>{let{path:e,params:t,basePath:n,navigate:r}=Oh(),i=(0,o.useMemo)(()=>xs(e,t),[e,t]),a=Xd(new URL(t.size>0?`${e}?${t}`:e,`http://local`).href),s=i?i.next:a,c=(0,o.useCallback)((e=`sign-in`,t)=>r(bs({step:e,next:s}),t),[r,s]);return{address:i,next:s,open:c,link:(0,o.useCallback)((e=`sign-in`,t)=>({href:`${n}${bs({step:e,next:s})}`,onFollow:()=>c(e,t)}),[n,s,c]),leave:(0,o.useCallback)(()=>r(s??`/`,{replace:!0}),[r,s])}},Vne=e=>{let t=new URL(e),n=t.searchParams.get(`token`);return t.pathname.endsWith(`/-/invitation`)&&n?{token:n}:void 0},Hne=e=>`${new URL(e).pathname.slice(0,-13)}/`,Vh=`/-/organizations`,Hh=`/-/organization`,Uh=`/-/organization/members`,Wh=`/-/organization/invitations`,Une={[Vh]:`Organizations`,[Hh]:`Organization`,[Uh]:`Members`,[Wh]:`Invitations`},Gh={owner:`Owner`,admin:`Admin`,member:`Member`},Kh=(e,t)=>e.find(e=>e.name===t)?.label??t,qh=e=>e?.role===`owner`||e?.role===`admin`,Wne=(e,t,n)=>{let r=(n,r,i,a)=>({id:n,label:r,icon:i,href:`${e}${a}`,active:t===a});return[r(`organizations`,`Organizations`,Jt,Vh),...n?.organization?[r(`organization`,`Organization`,le,Hh)]:[],...qh(n)?[r(`members`,`Members`,qn,Uh),r(`invitations`,`Invitations`,zt,Wh)]:[]]},Jh=(e,t)=>{let n=[...t?.globalRoles??[],...t?.appRoles??[]],r=e.filter(e=>e.membership).map(e=>e.name);if(n.includes(`admin`))return new Set(r);let i=n.flatMap(t=>e.find(e=>e.name===t)?.grants??[]);return new Set([...n,...i].filter(e=>r.includes(e)))},Yh=()=>{let[e,t]=(0,o.useState)(!1),[n,r]=(0,o.useState)();return{busy:e,error:n,run:async e=>{t(!0),r(void 0);try{await e()}catch(e){if(!(e instanceof lc))throw e;r(Bd(e))}t(!1)},setError:r}},Gne=({token:e,preview:t,onDone:n})=>{let{session:r,signInMethods:i,recheck:a}=H(),[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(``),{busy:d,error:f,run:p}=Yh(),m=i.includes(`password`),h=i.includes(`emailCode`),g=()=>p(async()=>{await r.organizations.signUpFromInvitation(e,{name:s.trim(),...m&&l&&{password:l}}),n(),a()});return(0,V.jsxs)(`form`,{className:`flex flex-col gap-3`,onSubmit:e=>{e.preventDefault(),g()},children:[(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Make your account for `,t.email,` to join.`]}),f&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:f}),(0,V.jsx)(Td,{"aria-label":`Your name`,placeholder:`Your name`,autoComplete:`name`,value:s,onChange:e=>c(e.target.value)}),m&&(0,V.jsx)(Td,{"aria-label":`Password`,type:`password`,autoComplete:`new-password`,placeholder:h?`Password (optional, 12+ characters)`:`Password (12+ characters)`,value:l,onChange:e=>u(e.target.value)}),(0,V.jsx)(U,{type:`submit`,variant:`primary`,loading:d,disabled:!s.trim()||m&&!h&&l.length<12,children:`Create account and join`})]})},Kne=({token:e,onDone:t,signIn:n})=>{let{session:r,state:i,signOut:a,organizations:s}=H(),[c,l]=(0,o.useState)(),[u,d]=(0,o.useState)(),{busy:f,error:p,run:m}=Yh();if((0,o.useEffect)(()=>{r.organizations.invitation(e).then(l,e=>d(e instanceof lc?Bd(e):`This invitation link is not valid`))},[r,e]),u)return(0,V.jsx)(Mh,{title:`Invitation`,description:u,children:(0,V.jsx)(U,{className:`w-full`,onClick:t,children:`Go to the app`})});if(!c)return(0,V.jsx)(Mh,{title:`Invitation`,children:(0,V.jsxs)(`div`,{className:`flex items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(Dd,{}),` Loading`]})});let h=c.appRoles.map(e=>Kh(s?.roles??[],e)),g=`${c.inviter.name} invites you to ${c.organization.name} as ${Gh[c.role].toLowerCase()}${h.length>0?`, with ${h.join(`, `)}`:``}.`,_=i.kind===`signed-in`?i.user:void 0;return _&&_.email.toLowerCase()!==c.email.toLowerCase()?(0,V.jsxs)(Mh,{title:`Join ${c.organization.name}`,description:g,children:[(0,V.jsxs)(`p`,{className:`mb-3 text-muted-foreground`,children:[`This invitation is for `,c.email,`, and you are signed in as `,_.email,`.`]}),(0,V.jsx)(U,{className:`w-full`,onClick:()=>void a(),children:`Sign out to accept it`})]}):(0,V.jsx)(Mh,{title:`Join ${c.organization.name}`,description:g,children:_?(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[p&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:p}),(0,V.jsxs)(U,{variant:`primary`,className:`w-full`,loading:f,onClick:()=>void m(async()=>{await r.organizations.accept(e),t()}),children:[`Join `,c.organization.name]})]}):c.hasAccount?(0,V.jsxs)(Nu,{to:n,className:B(Sf({variant:`primary`}),`w-full`),children:[`Sign in as `,c.email,` to join`]}):(0,V.jsx)(Gne,{token:e,preview:c,onDone:t})})},qne=`modulepreload`,Jne=function(e){return`/`+e},Xh={},Yne=function(e){return e.pathname.endsWith(`.css`)},Zh=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=Jne(t,n);let r=s(t);if(r.href in Xh)return;Xh[r.href]=!0;let i=Yne(r);if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let o=document.createElement(`link`);if(o.rel=i?`stylesheet`:qne,i||(o.as=`script`),o.crossOrigin=``,o.href=r.href,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),i)return new Promise((e,t)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>t(Error(`Unable to preload CSS for ${r}`)))})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Qh,$h,Xne=({dsn:e,environment:t})=>(Qh??=Zh(()=>import(`./prod-YZ9ZMG1O.js`).then(n=>{n.init({dsn:e,...t&&{environment:t},integrations:e=>e.filter(e=>e.name!==`BrowserSession`),beforeSend:e=>Ko(e)}),$h=(e,t)=>n.captureException(e,t?{contexts:{react:{componentStack:t}}}:void 0)}),[]),Qh),eg=(e,t)=>$h?.(e,t??void 0),tg=({children:e})=>(0,V.jsx)(`div`,{role:`alert`,className:`rounded-lg border border-dashed border-warning bg-warning-soft p-3 text-warning-text`,children:e}),ng=class extends o.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e,t){eg(e,t.componentStack)}render(){return this.state.failed?this.props.fallback===void 0?(0,V.jsxs)(tg,{children:[this.props.name,` could not be drawn.`]}):this.props.fallback:this.props.children}},Zne=/^[A-Z][A-Za-z0-9]*$/,Qne=e=>typeof e==`function`||typeof e==`object`&&!!e&&`$$typeof`in e,rg=e=>{let t=e.default??{},n=Object.entries(e).filter(e=>e[0]!=="default"&&Zne.test(e[0])&&Qne(e[1]));if(n.length===0)return t;for(let[e,r]of n)if(t.components&&Object.hasOwn(t.components,e)&&t.components[e]!==r)throw Error(`The component "${e}" is exported by name and given in components as another one; keep the export`);return{...t,components:{...t.components,...Object.fromEntries(n)}}},ig=class extends Error{name=`UiConflictError`},$ne=e=>Object.keys(e).some(e=>e==="default"||/^[A-Z]/.test(e))?rg(e):e,ag=(e,t)=>[...(e.extends??[]).map($ne).flatMap((e,n)=>ag(e,e.name??`${t} extends[${n}]`)),{ui:e,label:t}],og=(e,t,n)=>{let r={},i=new Map;for(let{ui:a,label:o}of t)for(let[t,s]of Object.entries(n(a)??{})){if(Object.hasOwn(r,t)&&r[t]!==s)throw new ig(`${e} "${t}" is defined twice, by ${i.get(t)} and by ${o}; rename one of them`);r[t]=s,i.set(t,i.get(t)??o)}return r},sg=e=>e.length<=1?e[0]:()=>e.map((e,t)=>(0,V.jsx)(e,{},t)),ere=e=>e.length<=1?e[0]:({children:t,...n})=>e.reduceRight((e,t)=>(0,V.jsx)(t,{...n,children:e}),t),cg=(...e)=>{let t=e.flatMap((e,t)=>ag(e,e.name??`UI config ${t+1}`)),n=og(`The component`,t,e=>e.components),r=og(`The action handler`,t,e=>e.actions),i=og(`The field type`,t,e=>e.fields),a=sg(t.flatMap(({ui:e})=>e.shell?.actions?[e.shell.actions]:[])),o=sg(t.flatMap(({ui:e})=>e.shell?.rightPanel?[e.shell.rightPanel]:[])),s=t.findLast(({ui:e})=>e.shell?.logo)?.ui.shell?.logo,c=ere(t.flatMap(({ui:e})=>e.beforeSignIn?[e.beforeSignIn]:[])),l=e.at(-1)?.name;return{...l&&{name:l},components:n,actions:r,...Object.keys(i).length>0&&{fields:i},...(a||o||s)&&{shell:{...a&&{actions:a},...o&&{rightPanel:o},...s&&{logo:s}}},...c&&{beforeSignIn:c}}},lg=(e,t)=>{let n=cg(e??{}),r=[],i=[];for(let e of t){if(e.kind===`off`){i.push(e);continue}try{cg(...r,e.ui,n),r.push(e.ui)}catch(t){if(!(t instanceof ig))throw t;i.push({kind:`off`,url:e.plugin.url,name:e.plugin.name,reason:t.message})}}return{ui:r.length===0?n:cg(...r,n),off:i}},ug=e=>typeof e==`string`&&e.trim()!==``,tre=e=>{if(typeof e!=`object`||!e||Array.isArray(e))return{problem:`its plugin.json is not an object`};let{name:t,version:n,api:r,protobase:i,entry:a,css:o}=e;return ug(t)?Number.isInteger(r)?ug(i)?ug(a)?o!==void 0&&!ug(o)?{problem:`its plugin.json names a stylesheet that is no URL`}:n!==void 0&&!ug(n)?{problem:`its plugin.json has a version that is no text`}:{manifest:{name:t,api:r,protobase:i,entry:a,...n!==void 0&&{version:n},...o!==void 0&&{css:o}}}:{problem:`its plugin.json names no module`}:{problem:`its plugin.json names no Protobase versions`}:{problem:`its plugin.json names no plugin API`}:{problem:`its plugin.json names no plugin`}},dg=(0,o.createContext)(null),nre=dg.Provider,rre=()=>{let e=(0,o.useContext)(dg);if(!e)throw Error(`usePlugin is for the components of a plugin the app loaded`);return e},fg=(e,t,n)=>{let r=n=>(0,V.jsx)(nre,{value:e,children:(0,V.jsx)(t,{...n})});return r.displayName=`${e.name}:${n}`,r},ire=(e,t,n)=>({of:n.of,display:fg(e,n.display,`fields.${t}.display`),...n.editor&&{editor:fg(e,n.editor,`fields.${t}.editor`)},...n.cell&&{cell:fg(e,n.cell,`fields.${t}.cell`)}}),are=(e,t)=>{let n=cg({...rg(t),name:e.name}),r=Object.fromEntries(Object.entries(n.components??{}).map(([t,n])=>[t,fg(e,n,t)])),i=n.fields&&Object.fromEntries(Object.entries(n.fields).map(([t,n])=>[t,ire(e,t,n)])),a=n.shell&&{...n.shell.actions&&{actions:fg(e,n.shell.actions,`shell.actions`)},...n.shell.rightPanel&&{rightPanel:fg(e,n.shell.rightPanel,`shell.rightPanel`)}},o=n.beforeSignIn&&fg(e,n.beforeSignIn,`beforeSignIn`);return{name:e.name,components:r,...n.actions&&{actions:n.actions},...i&&{fields:i},...a&&{shell:a},...o&&{beforeSignIn:o}}},pg={name:`@protobase/ui`,version:`0.21.5`,description:`The Protobase admin app and the React hooks and components for custom UI.`,license:`Apache-2.0`,repository:{type:`git`,url:`git+https://github.com/PrototeamHQ/protobase.git`,directory:`packages/ui`},homepage:`https://docs.protobase.net`,type:`module`,protobase:{pluginApi:1},sideEffects:[`*.css`,`./dist/app/main.js`],engines:{node:`>=22.12.0`},exports:{".":`./src/index.ts`,"./theme.css":`./src/theme.css`,"./styles.css":`./src/styles.css`},types:`./src/index.ts`,files:[`dist`],scripts:{build:`tsdown && protobase build-shell dist/shell`,prepack:`tsdown && protobase build-shell dist/shell`},publishConfig:{access:`public`,exports:{".":`./dist/index.js`,"./theme.css":`./dist/theme.css`,"./styles.css":`./dist/styles.css`},types:`./dist/index.d.ts`},dependencies:{"@dnd-kit/core":`^6.3.1`,"@dnd-kit/sortable":`^10.0.0`,"@protobase/client":`workspace:*`,"@protobase/layout":`workspace:*`,"@protobase/schema":`workspace:*`,"@sentry/browser":`^11.7.0`,"@tanstack/react-query":`^5.104.1`,"@tanstack/react-table":`^9.2.6`,dompurify:`^3.4.17`,fflate:`^0.8.3`,"lucide-react":`^1.52.0`,"maplibre-gl":`^6.14.0`,marked:`^18.1.1`,pmtiles:`^4.5.0`,react:`^19.3.0`,"react-dom":`^19.3.0`,"react-map-gl":`^8.1.3`,recharts:`^3.10.1`,tailwindcss:`^4.3.3`,thumbhash:`^0.1.1`,uqr:`^0.1.3`}},mg=pg.protobase.pluginApi,hg=pg.version,ore={readJson:async e=>{let t=await fetch(e,{cache:`no-cache`,credentials:`same-origin`});return t.ok?{json:await t.json()}:{status:t.status}},addStylesheet:e=>{if([...document.querySelectorAll(`link[rel="stylesheet"]`)].some(t=>t.href===e))return;let t=document.createElement(`link`);t.rel=`stylesheet`,t.href=e,document.head.append(t)},importModule:e=>Zh(()=>import(e),[])},sre={api:mg,version:hg},cre=e=>e instanceof Error?e.message:String(e),lre=async(e,t,n,r=sre)=>{let i=new URL(e.url,n).href,a=(e,t)=>({kind:`off`,url:i,...t&&{name:t},reason:e}),o;try{let n=await t.readJson(i);if(`status`in n)return a(`its plugin.json answered ${n.status}`);let s=tre(n.json);if(`problem`in s)return a(s.problem);let{manifest:c}=s;o=c.name;let l=Lo(c,r);if(l)return a(l,o);c.css&&t.addStylesheet(new URL(c.css,i).href);let u=await t.importModule(new URL(c.entry,i).href),d={name:o,...c.version&&{version:c.version},url:i,settings:e.settings??{}};return{kind:`loaded`,plugin:d,ui:are(d,u)}}catch(e){return a(`it could not be loaded: ${cre(e)}`,o)}},ure=e=>{let t=new Map;return{load:n=>{let r=JSON.stringify(n),i=t.get(r);if(i)return i;let a=lre(n,e,window.location.href);return t.set(r,a),a}}},gg=(0,o.createContext)(null),dre=({loader:e=ore,children:t})=>{let n=(0,o.useMemo)(()=>ure(e),[e]);return(0,V.jsx)(gg.Provider,{value:n,children:t})},_g=()=>{let e=(0,o.useContext)(gg);if(!e)throw Error(`usePluginSource must be used inside PluginSourceProvider`);return e},fre=1e4,vg=[],yg=(e,t)=>{let n=JSON.stringify(e),[r,i]=(0,o.useState)({key:`[]`,loads:vg,settled:!0});return(0,o.useEffect)(()=>{if(e.length===0)return;let r=!0,a=!1,o=e.map(()=>void 0),s=()=>{if(!r)return;let t=o.filter(e=>e!==void 0);i({key:n,loads:t,settled:a||t.length===e.length})},c=setTimeout(()=>{a=!0,s()},fre);return e.forEach((e,n)=>{t.load(e).then(e=>{o[n]=e,s()})}),()=>{r=!1,clearTimeout(c)}},[n,t]),e.length===0?{loads:vg,settled:!0}:r.key===n?r:{loads:vg,settled:!1}},pre=({children:e})=>{let{state:t,beforeSignIn:n,adoptSession:r}=H(),{path:i,params:a,navigate:s}=Oh(),{loads:c,settled:l}=yg(n,_g()),u=(0,o.useMemo)(()=>lg(void 0,c).ui.beforeSignIn,[c]),d=(0,o.useCallback)(e=>{let t=new URLSearchParams(a);for(let n of e)t.delete(n);s(t.size>0?`${i}?${t}`:i,{replace:!0})},[i,a,s]);return t.kind!==`signed-out`&&t.kind!==`visitor`?e:l?u?(0,V.jsx)(ng,{name:`beforeSignIn`,fallback:e,children:(0,V.jsx)(u,{signedIn:r,params:a,removeParams:d,children:e})}):e:(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(Dd,{}),` Loading`]})},mre=()=>{let e=window.location.href,t=mne(e);if(t)return{kind:`reset-password`,token:t.token};let n=Pne(e);if(n)return{kind:`staff-sign-in`,link:n};let r=Vne(e);if(r)return{kind:`invitation`,token:r.token};let i=Jd(e);if(i)return{kind:`provider-sign-in`,provider:i};let a=Yd(e);return a?{kind:`sign-in`,providerError:a}:{kind:`sign-in`}},bg=({to:e})=>{let{navigate:t}=Oh();return(0,o.useEffect)(()=>t(e,{replace:!0}),[t,e]),null},hre=({workspace:e,children:t})=>{let n=gre(e,t);return(0,V.jsx)(pre,{children:n})},gre=(e,t)=>{let{state:n,recheck:r,passwordReset:i,signOut:a,signInProviders:s,canSignUp:c,browse:l}=H(),{path:u,params:d,basePath:f,navigate:p}=Oh(),{address:m,next:h,open:g,link:_,leave:v}=Bh(),[y,b]=(0,o.useState)(mre),[x,S]=(0,o.useState)(),[C,w]=(0,o.useState)(),[T,E]=(0,o.useState)(),D=new URL(`${f}${u}${d.size>0?`?${d}`:``}`,window.location.origin).href,O=(0,o.useCallback)(e=>{let t=e(D).slice(f.length);p(t.startsWith(`/`)?t:`/${t}`,{replace:!0})},[D,f,p]),k=n.kind===`signed-in`||n.kind===`two-factor`||n.kind===`setup-required`;(0,o.useEffect)(()=>{k&&(y.kind===`provider-sign-in`&&O(Xd),(y.kind===`provider-sign-in`||y.kind===`sign-in`&&(y.notice||y.error||y.providerError))&&b({kind:`sign-in`}),S(void 0),w(void 0),E(void 0))},[k,y,O]);let A=m!==void 0&&Yd(D)!==void 0;(0,o.useEffect)(()=>{!k&&y.kind===`sign-in`&&y.providerError&&A&&O(Xd)},[k,y,A,O]);let j=(0,o.useCallback)(e=>b({kind:`sign-in`,error:e}),[]),M=e=>{O(hne),b(e)},N=async()=>{n.kind===`signed-in`&&await a(),M({kind:`sign-in`,notice:`Your password is changed. Sign in with the new one.`})},ee=()=>{b({kind:`sign-in`}),a().then(()=>g(`sign-in`,{replace:!0}))};switch(n.kind){case`loading`:return(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(Dd,{}),` Loading`]});case`error`:return(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 flex-col items-center justify-center gap-3 p-8 text-center`,children:[(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Cannot reach the server: `,n.message]}),(0,V.jsx)(U,{onClick:r,children:`Try again`})]});case`needs-admin`:return(0,V.jsx)(dne,{onCheckAgain:r})}if(n.kind===`signed-in`&&m)return(0,V.jsx)(bg,{to:h??`/`});if(y.kind===`reset-password`)return(0,V.jsx)(xne,{token:y.token,onDone:()=>void N(),onRequestNewLink:i?()=>{b({kind:`sign-in`}),p(bs({step:`forgot-password`}),{replace:!0})}:void 0,onBack:()=>M({kind:`sign-in`})});if(y.kind===`staff-sign-in`)return(0,V.jsx)(Lne,{link:y.link,onBack:()=>{O(Rh),b({kind:`sign-in`})}});let P=n.kind===`signed-out`||n.kind===`visitor`;if(y.kind===`invitation`&&(n.kind===`signed-in`||P&&!m))return(0,V.jsx)(Kne,{token:y.token,onDone:()=>{O(Hne),b({kind:`sign-in`})},signIn:_()});if(n.kind===`signed-in`)return t;if(n.kind===`two-factor`)return(0,V.jsx)(Bne,{methods:n.methods,onBack:ee});if(n.kind===`setup-required`)return(0,V.jsx)(wne,{missing:n.missing},n.missing.join());if(y.kind===`provider-sign-in`)return(0,V.jsx)(vne,{provider:y.provider,workspace:e,onFailed:j});let te=y.kind===`sign-in`?y:{kind:`sign-in`};if(!m){let e=te.notice||te.error||te.providerError;return n.kind===`visitor`&&!e?t:(0,V.jsx)(bg,{to:bs({next:h})})}let F={"sign-in":!0,"forgot-password":i,"email-code":x!==void 0,"sign-up":c,"sign-up-code":c&&C!==void 0,"sign-up-details":c&&T!==void 0}[m.step]?m.step:`sign-in`,ne=e=>()=>g(e,{replace:!0}),re=l&&(()=>{l(),v()});if(F===`forgot-password`)return(0,V.jsx)(gne,{back:_(`sign-in`,{replace:!0})});if(F===`email-code`)return(0,V.jsx)(lne,{email:x,onBack:ne(`sign-in`)});if(F===`sign-up`||F===`sign-up-code`||F===`sign-up-details`)return(0,V.jsx)(Nne,{workspace:e,email:F===`sign-up`?void 0:C,ticket:F===`sign-up-details`?T:void 0,onCodeSent:e=>{w(e),E(void 0),g(`sign-up-code`)},onVerified:e=>{E(e),g(`sign-up-details`,{replace:!0})},onBack:ne(`sign-up`),onSignIn:()=>g(`sign-in`),onBrowse:re},F);let ie=te.providerError&&Gd(te.providerError,s.length===1?s[0].name:`the provider`),I=te.error??ie;return(0,V.jsx)(kne,{workspace:e,notice:te.notice,error:I,forgotPassword:i?_(`forgot-password`):void 0,onCodeSent:e=>{S(e),g(`email-code`)},signUp:c?_(`sign-up`):void 0,onBrowse:re},I)},_re=e=>[...e].reduce((e,t)=>(e*31+t.charCodeAt(0))%360,7),vre=e=>e.split(/[\s@.]+/).filter(Boolean).slice(0,2).map(e=>e[0].toUpperCase()).join(``),xg=e=>(e.role??`user`).split(`,`).map(e=>e.trim()),Sg=e=>xg(e).includes(`admin`),yre=e=>{let t=xg(e),n=t.includes(`admin`);return{name:e.name||e.email,email:e.email,initials:vre(e.name||e.email)||`?`,hue:_re(e.id||e.email),role:n?`Admin`:(t[0]??`user`).replace(/^./,e=>e.toUpperCase()),roleTone:n?`violet`:`blue`}},bre=3e4,xre=(e,t=Date.now())=>Math.max(1e3,ru(e)-t-bre),Cg=()=>{let{state:e,session:t}=H(),n=e.kind===`signed-in`,[r,i]=(0,o.useState)();return(0,o.useEffect)(()=>{if(!n)return;let e=!0,r,a=async n=>{let o=await t.token(),s=o!==void 0&&o===n?await t.token({refresh:!0}):o;e&&(i(s),s&&(r=setTimeout(()=>void a(s),xre(s))))};return a(),()=>{e=!1,clearTimeout(r)}},[t,n]),n?r:void 0},wg=(e,t,n=!0)=>{let r=G(),i=Ao(t);return vh({queryKey:W.record(e,i),enabled:n,queryFn:()=>r.get(e,t)})},Tg=(e,t,n=!0)=>{let r=G(),i=Wp(),a=Ao(t);return vh({queryKey:W.record(e,a),enabled:n,queryFn:()=>r.get(e,t),placeholderData:()=>i.getQueryData(W.recordPreview(e,a))})},Sre=[`name`,`title`,`number`,`sku`,`email`,`code`,`description`],Eg=(e,t)=>t?.title??Sre.find(t=>e.fields[t]?.type===`text`)??Object.values(e.fields).find(e=>e.type===`text`)?.name??e.primaryKey[0],Dg=(e,t)=>t?.title??t?.list?.columns.find(t=>e.fields[t]?.type===`text`)??Eg(e),Og=(e,t,n,r)=>{let i=Dg(e,t),a=n[i];return a==null?r:e.fields[i]?.type===`enum`?rs(String(a),t?.fields[i]?.valueLabels):String(a)},kg=(e,t,n)=>{let r=t[n];return e.fields[n]?.type===`relation`&&typeof r==`object`&&r&&`id`in r?r.id:r},Ag=(e,t)=>e.primaryKey.map(n=>String(kg(e,t,n))).join(`,`),jg=(e,t)=>{let n=e.primaryKey.map(n=>kg(e,t,n));return n.length===1?n[0]:n},Cre=e=>e.charAt(0).toUpperCase()+e.slice(1),K=e=>Cre(e.replace(/(Id|Code|_id|_code)$/,``).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/_+/g,` `).trim().toLowerCase()||e),wre=[`light`,`dark`,`system`],Mg=`protobase:theme`,Tre=`(prefers-color-scheme: dark)`,Ere=e=>wre.includes(e),Ng=e=>ad(()=>{let t=e.getItem(Mg);return Ere(t)?t:`system`},`system`),Dre=(e,t)=>ad(()=>t===`system`?e.removeItem(Mg):e.setItem(Mg,t),void 0),Ore=(e,t)=>e===`system`?t?`dark`:`light`:e,Pg=(0,o.createContext)(void 0),kre=({children:e})=>{let[t,n]=(0,o.useState)(()=>Ng(localStorage)),r=Ore(t,pu(Tre));return(0,o.useEffect)(()=>{document.documentElement.dataset.theme=r},[r]),(0,o.useEffect)(()=>{let e=e=>{(e.key===`protobase:theme`||e.key===null)&&n(Ng(localStorage))};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),(0,V.jsx)(Pg.Provider,{value:{preference:t,theme:r,choose:e=>{Dre(localStorage,e),n(e)}},children:e})},Are=()=>{let e=(0,o.useContext)(Pg);if(!e)throw Error(`useTheme needs a ThemeProvider above it`);return e},Fg=`-my-0.5 rounded px-1.5 py-0.5 font-medium text-primary-text hover:bg-primary-soft`,jre=({action:e})=>{if(`onClick`in e)return(0,V.jsx)(`button`,{type:`button`,onClick:e.onClick,className:Fg,children:e.label});let{href:t,onNavigate:n}=e;return(0,V.jsx)(`a`,{href:t,onClick:e=>{n&&ju(e)&&(e.preventDefault(),n(t))},className:Fg,children:e.label})},Mre={loading:(0,V.jsx)(Dd,{className:`text-primary`}),success:(0,V.jsx)(De,{className:`size-4 text-success`}),error:(0,V.jsx)(je,{className:`size-4 text-danger`})},Nre=({state:e,title:t,description:n,action:r,onDismiss:i})=>(0,V.jsxs)(`div`,{role:e===`error`?`alert`:`status`,className:B(`flex w-full max-w-80 items-start gap-3 rounded-lg border bg-background p-3 shadow-pop [animation:pb-slide-in_160ms_ease-out]`,e===`error`&&`border-danger/40`),children:[(0,V.jsx)(`span`,{className:`mt-0.5`,children:Mre[e]}),(0,V.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,V.jsx)(`p`,{className:`font-medium text-foreground`,children:t}),n&&(0,V.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:n})]}),r&&(0,V.jsx)(jre,{action:r}),i&&(0,V.jsx)(`button`,{type:`button`,"aria-label":`Dismiss`,onClick:i,className:`inline-flex items-center justify-center rounded p-0.5 text-faint-foreground hover:bg-muted hover:text-foreground pointer-coarse:size-9`,children:(0,V.jsx)(Qn,{className:`size-3.5`})})]}),Pre={loading:1/0,success:3500,error:8e3},Fre=8e3,Ig=(0,o.createContext)(null),Lg=()=>{let e=(0,o.useContext)(Ig);if(!e)throw Error(`useToast must be used inside ToastProvider`);return e},Ire=({children:e})=>{let[t,n]=(0,o.useState)([]),r=(0,o.useRef)(1),i=(0,o.useRef)(new Map),a=(0,o.useCallback)(e=>{clearTimeout(i.current.get(e)),i.current.delete(e),n(t=>t.filter(t=>t.id!==e))},[]),s=(0,o.useCallback)((e,t,n=!1)=>{clearTimeout(i.current.get(e));let r=n?Fre:Pre[t];r!==1/0&&i.current.set(e,setTimeout(()=>a(e),r))},[a]),c=(0,o.useMemo)(()=>({show:e=>{let t=r.current++;return n(n=>[...n,{...e,id:t}]),s(t,e.state,!!e.action),t},update:(e,t)=>{n(n=>n.map(n=>n.id===e?{...n,...t}:n)),t.state&&s(e,t.state,!!t.action)},dismiss:a}),[a,s]);return(0,V.jsxs)(Ig.Provider,{value:c,children:[e,(0,V.jsx)(`div`,{className:`pointer-events-none fixed inset-x-4 bottom-24 z-[100] flex flex-col items-end gap-2 md:inset-x-auto md:bottom-4 md:right-4`,children:t.map(e=>(0,V.jsx)(`div`,{className:`pointer-events-auto`,children:(0,V.jsx)(Nre,{state:e.state,title:e.title,description:e.description,action:e.action,onDismiss:()=>a(e.id)})},e.id))})]})},Rg=({from:e,children:t})=>(0,V.jsx)(`div`,{"data-from":e,className:B(`flex min-w-0 flex-col gap-2 whitespace-pre-wrap break-words`,e===`user`?`ml-8 self-end rounded-lg rounded-br-sm bg-primary px-3 py-2 text-primary-foreground shadow-sm`:`mr-4 text-foreground`),children:t}),zg=({children:e,empty:t,length:n})=>{let r=(0,o.useRef)(null);return(0,o.useEffect)(()=>{let e=r.current;e&&(e.scrollTop=e.scrollHeight)},[n]),(0,V.jsx)(`div`,{ref:r,role:`log`,"aria-live":`polite`,className:`flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4`,children:n===0&&t?(0,V.jsx)(`div`,{className:`m-auto max-w-60 text-center text-muted-foreground`,children:t}):e})},Bg=({onSend:e,busy:t,placeholder:n,inputRef:r})=>{let[i,a]=(0,o.useState)(``),s=i.trim(),c=()=>{s&&!t&&(e?.(s),a(``))};return(0,V.jsxs)(`form`,{className:`flex gap-2`,onSubmit:e=>{e.preventDefault(),c()},children:[(0,V.jsx)(Td,{ref:r,"aria-label":`Message`,placeholder:n,value:i,onChange:e=>a(e.target.value),wrapperClassName:`flex-1`}),(0,V.jsx)(U,{type:`submit`,variant:`primary`,className:`w-8 px-0`,"aria-label":`Send`,disabled:!s||t,children:(0,V.jsx)(oee,{className:`size-4`})})]})},Lre=e=>{let[t,n]=(0,o.useState)();return(0,o.useEffect)(()=>{let t=window.visualViewport;if(!e||!t)return n(void 0);let r=()=>n({top:t.offsetTop,height:t.height});return r(),t.addEventListener(`resize`,r),t.addEventListener(`scroll`,r),()=>{t.removeEventListener(`resize`,r),t.removeEventListener(`scroll`,r)}},[e]),e?t:void 0},Vg=({title:e,icon:t,status:n,onClose:r,footer:i,children:a})=>{let o=Lre(!mu());return(0,V.jsxs)(`aside`,{"aria-label":e,className:`flex h-full w-[380px] max-w-full shrink-0 flex-col border-l border-border bg-surface max-md:fixed max-md:inset-0 max-md:z-40 max-md:w-full max-md:border-l-0`,style:o&&{top:o.top,bottom:`auto`,height:o.height},children:[(0,V.jsxs)(`header`,{className:`flex h-12 shrink-0 items-center gap-2 border-b border-border bg-background px-4`,children:[t,(0,V.jsx)(`h2`,{className:`flex-1 font-semibold`,children:e}),n&&(0,V.jsx)(`span`,{className:`truncate text-xs font-medium text-muted-foreground`,children:n}),r&&(0,V.jsx)(U,{variant:`ghost`,size:`sm`,className:`w-7 px-0`,"aria-label":`Close`,onClick:r,children:(0,V.jsx)(Qn,{className:`size-4`})})]}),a,i&&(0,V.jsx)(`footer`,{className:`shrink-0 space-y-2 border-t border-border bg-background p-3`,children:i})]})},Hg={neutral:{border:`border-border-strong`,header:`bg-surface text-foreground`},info:{border:`border-primary-border`,header:`bg-primary-soft text-primary-text`},success:{border:`border-success/40`,header:`bg-success-soft text-success-text`},warning:{border:`border-warning/40`,header:`bg-warning-soft text-warning-text`},danger:{border:`border-danger/40`,header:`bg-danger-soft text-danger-text`}},Ug=({title:e,tone:t=`neutral`,badge:n,note:r,actions:i=[],onAction:a,children:s,frameless:c=!1})=>{let[l,u]=(0,o.useState)(),d=i.flatMap(e=>e.hint?[e.hint]:[]),f=e=>e.confirm?u(e):a?.(e.id);return(0,V.jsxs)(`section`,{"aria-label":e,className:c?`whitespace-normal text-foreground`:B(`shrink-0 overflow-hidden rounded-lg border bg-background whitespace-normal text-foreground shadow-sm`,Hg[t].border),children:[!c&&(0,V.jsxs)(`header`,{className:B(`flex items-center gap-2 px-3 py-2`,Hg[t].header),children:[(0,V.jsx)(`h3`,{className:`min-w-0 flex-1 font-semibold`,children:e}),n&&(0,V.jsx)(`span`,{className:`shrink-0 text-xs font-medium`,children:n})]}),(s||r||i.length>0)&&(0,V.jsxs)(`div`,{className:B(`space-y-2.5`,!c&&`px-3 py-2.5`),children:[s,r&&(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:r}),i.length>0&&(0,V.jsx)(`div`,{className:`flex flex-wrap gap-2 pt-0.5`,children:i.map(e=>(0,V.jsx)(U,{size:`sm`,variant:e.style??`secondary`,className:B(e.style===`primary`&&`flex-1`),disabled:e.disabled,onClick:()=>f(e),children:e.label},e.id))}),d.map(e=>(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e},e))]}),l&&(0,V.jsx)(Cf,{title:`${l.label}?`,description:l.confirm,onClose:()=>u(void 0),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>u(void 0),children:`Cancel`}),(0,V.jsx)(U,{variant:l.style===`danger`?`danger`:`primary`,onClick:()=>{u(void 0),a?.(l.id)},children:l.label})]})})]})},Wg=({fields:e})=>(0,V.jsx)(`dl`,{className:`grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs`,children:e.map((e,t)=>(0,V.jsxs)(`div`,{className:`contents`,children:[(0,V.jsx)(`dt`,{className:`text-muted-foreground`,children:e.label}),(0,V.jsx)(`dd`,{className:`min-w-0 break-words`,children:e.value})]},`${t}-${e.label}`))}),Rre=e=>e==null?`null`:typeof e==`object`?JSON.stringify(e):String(e),Gg=({columns:e,rows:t,caption:n,truncated:r,className:i})=>(0,V.jsxs)(`section`,{"aria-label":n??`Table`,className:B(`shrink-0 overflow-hidden rounded-lg border border-border-strong bg-background shadow-sm`,i),children:[n&&(0,V.jsx)(`code`,{className:`block whitespace-pre-wrap break-words bg-surface px-3 py-2 font-mono text-[11px] text-foreground`,children:n}),t.length===0?(0,V.jsx)(`p`,{className:`px-3 py-2 text-xs text-muted-foreground`,children:`No rows.`}):(0,V.jsx)(`div`,{className:`max-h-64 overflow-auto`,children:(0,V.jsxs)(`table`,{className:`w-full border-collapse text-left text-[11px]`,children:[(0,V.jsx)(`thead`,{className:`sticky top-0 bg-background`,children:(0,V.jsx)(`tr`,{children:e.map(e=>(0,V.jsx)(`th`,{scope:`col`,className:`border-b border-border px-2 py-1 font-semibold whitespace-nowrap`,children:e},e))})}),(0,V.jsx)(`tbody`,{children:t.map((e,t)=>(0,V.jsx)(`tr`,{className:`border-b border-border last:border-b-0`,children:e.map((e,t)=>(0,V.jsx)(`td`,{className:B(`px-2 py-1 whitespace-nowrap`,e===null&&`text-faint-foreground`),children:Rre(e)},t))},t))})]})}),(0,V.jsxs)(`footer`,{className:`border-t border-border px-3 py-1.5 text-[11px] text-muted-foreground`,children:[t.length,` `,t.length===1?`row`:`rows`,r&&`, cut off at the limit`]})]}),Kg=(e,t=1)=>{let n=t,r=t;return e.split(`
|
|
8
|
-
`).map(e=>e.startsWith(`+`)?{kind:`add`,text:e.slice(1),newNo:r++}:e.startsWith(`-`)?{kind:`del`,text:e.slice(1),oldNo:n++}:{kind:`ctx`,text:e.startsWith(` `)?e.slice(1):e,oldNo:n++,newNo:r++})},qg=e=>({added:e.filter(e=>e.kind===`add`).length,removed:e.filter(e=>e.kind===`del`).length}),zre={add:`bg-success-soft text-success-text`,del:`bg-danger-soft text-danger-text`,ctx:`text-muted-foreground`},Bre={add:`+`,del:`−`,ctx:``},Jg=({source:e,start:t,path:n,className:r})=>{let i=Kg(e,t),a=qg(i);return(0,V.jsxs)(`div`,{className:B(`overflow-hidden`,r),children:[n&&(0,V.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border bg-surface px-3 py-1.5`,children:[(0,V.jsx)(et,{className:`size-3.5 text-muted-foreground`}),(0,V.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-[11px] text-foreground`,children:n}),(0,V.jsxs)(`span`,{className:`text-[11px] font-medium text-success-text`,children:[`+`,a.added]}),a.removed>0&&(0,V.jsxs)(`span`,{className:`text-[11px] font-medium text-danger-text`,children:[`−`,a.removed]})]}),(0,V.jsx)(`pre`,{className:`overflow-x-auto bg-background py-1 font-mono text-[11px] leading-[18px]`,children:i.map((e,t)=>(0,V.jsxs)(`div`,{className:B(`flex`,zre[e.kind]),children:[(0,V.jsx)(`span`,{className:`w-8 shrink-0 select-none pr-2 text-right opacity-60`,children:e.newNo??e.oldNo}),(0,V.jsx)(`span`,{className:`w-3 shrink-0 select-none`,children:Bre[e.kind]}),(0,V.jsx)(`span`,{className:`min-w-0 whitespace-pre-wrap break-words pr-3`,children:e.text})]},t))})]})},Vre={pending:(0,V.jsx)(Ne,{className:`size-3 text-faint-foreground`}),running:(0,V.jsx)(Dd,{className:`size-3.5 text-primary`}),done:(0,V.jsx)(he,{className:`size-3.5 text-success`,strokeWidth:2.5}),failed:(0,V.jsx)(Qn,{className:`size-3.5 text-danger`,strokeWidth:2.5})},Hre={pending:`text-muted-foreground`,running:`text-foreground`,done:`text-muted-foreground`,failed:`text-danger-text`},Yg=({steps:e,className:t})=>(0,V.jsx)(`ul`,{className:B(`shrink-0 space-y-2`,t),children:e.map((e,t)=>(0,V.jsxs)(`li`,{className:`flex items-start gap-2.5`,"data-state":e.state,children:[(0,V.jsx)(`span`,{className:`mt-0.5 flex size-4 shrink-0 items-center justify-center`,children:Vre[e.state]}),(0,V.jsx)(`span`,{className:Hre[e.state],children:e.label})]},`${t}-${e.label}`))}),Ure=e=>e,Wre=e=>e,Xg=(0,o.createContext)({}),Zg=()=>(0,o.useContext)(Xg),Qg=({part:e,note:t})=>e.fallback?(0,V.jsx)(Ug,{title:e.fallback.title,note:t,children:e.fallback.body&&(0,V.jsx)(`p`,{children:e.fallback.body})}):(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`${e.name}: ${t}`}),Gre=class extends o.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e,t){eg(e,t.componentStack)}render(){return this.state.failed?(0,V.jsx)(Qg,{part:this.props.part,note:`It could not be drawn.`}):this.props.children}},Kre=({part:e})=>{let{components:t={}}=Zg(),n=Object.hasOwn(t,e.name)?t[e.name]:void 0;return n?(0,V.jsx)(Gre,{part:e,children:(0,V.jsx)(n,{...e.props})}):(0,V.jsx)(Qg,{part:e,note:`This version of the app cannot show it live.`})},$g=({part:e,onAction:t})=>{switch(e.type){case`text`:return(0,V.jsx)(`p`,{children:e.text});case`table`:return(0,V.jsx)(Gg,{columns:e.columns,rows:e.rows,caption:e.caption,truncated:e.truncated});case`card`:return(0,V.jsxs)(Ug,{title:e.title,tone:e.tone,badge:e.badge,note:e.note,actions:e.actions,onAction:n=>t?.(e.id,n),children:[e.body&&(0,V.jsx)(`p`,{children:e.body}),e.code&&(0,V.jsx)(`pre`,{className:`overflow-x-auto rounded-md bg-surface px-2.5 py-2 font-mono text-[11px] whitespace-pre-wrap break-words`,children:e.code}),e.fields&&e.fields.length>0&&(0,V.jsx)(Wg,{fields:e.fields}),e.steps&&e.steps.length>0&&(0,V.jsx)(Yg,{steps:e.steps}),e.diffs?.map((e,t)=>(0,V.jsx)(Jg,{source:e.source,start:e.start,path:e.path,className:`rounded-md border border-border`},`${t}-${e.path}`))]});case`widget`:return(0,V.jsx)(Kre,{part:e})}},e_=(0,o.createContext)(void 0),t_=e=>e instanceof Error?e:Error(`The assistant backend did not answer`),qre=(e,t)=>typeof e==`function`?e(t):e,Jre=(e,{refreshMs:t=!1}={})=>{let n=(0,o.useContext)(e_),[r,i]=(0,o.useState)({}),[a,s]=(0,o.useState)(0),c=(0,o.useRef)(t);c.current=t;let l=(0,o.useRef)(void 0);return(0,o.useEffect)(()=>{if(!n){i({error:Error(`useBackendData works only in a widget the assistant dock draws`)});return}let t=!0,r,a=async()=>{let o=await n.fetch(e).then(e=>e.json()).then(e=>({data:e}),e=>({data:l.current,error:t_(e)}));if(!t)return;l.current=o.data,i(o);let s=qre(c.current,o.data);s!==!1&&(r=setTimeout(a,s))};return a(),()=>{t=!1,clearTimeout(r)}},[n,e,a]),{...r,reload:()=>s(e=>e+1),post:async(e,t)=>{if(!n)throw Error(`useBackendData works only in a widget the assistant dock draws`);let r={method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t??{})},a=await n.fetch(e,r).then(e=>e.json()).then(e=>({data:e}),e=>({data:l.current,error:t_(e)}));l.current=a.data,i(a)}}},Yre=`Ask a question...`,n_=({state:e,offline:t,error:n,onSend:r,onAction:i,onClose:a,client:s})=>{let c=(0,o.useRef)(null);return(0,o.useEffect)(()=>{e.placeholder&&c.current?.focus()},[e.placeholder]),(0,V.jsx)(Vg,{title:`Assistant`,icon:(0,V.jsx)(wn,{className:`size-4 text-primary`}),status:t?`Reconnecting...`:e.status,onClose:a,footer:(0,V.jsxs)(V.Fragment,{children:[n&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs text-danger-text`,children:n}),(0,V.jsx)(Bg,{inputRef:c,onSend:r,busy:e.replying,placeholder:e.placeholder??Yre})]}),children:(0,V.jsx)(e_.Provider,{value:s,children:(0,V.jsx)(zg,{length:e.messages.reduce((e,t)=>e+t.parts.length,0),empty:`Ask a question about this app or its data.`,children:e.messages.map(e=>(0,V.jsx)(Rg,{from:e.from,children:e.parts.map(e=>(0,V.jsx)($g,{part:e,onAction:i},e.id))},e.id))})})})},Xre=e=>e instanceof Error?e.message:`The assistant did not answer`,r_=e=>{let[t,n]=(0,o.useState)(Qo),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)();(0,o.useEffect)(()=>{if(e)return e.connect(e=>n(t=>ts(t,e)),e=>i(e.state===`retrying`))},[e]);let c=e=>{s(void 0),e.catch(e=>s(Xre(e)))};return{state:t,offline:r,error:a,send:(t,n)=>e&&c(e.send(t,n)),act:(t,n)=>e&&c(e.act(t,n))}},i_=e=>{let t=Cg(),n=(0,o.useRef)(t);n.current=t;let r=t!==void 0;return(0,o.useMemo)(()=>r?lu({url:e,token:()=>n.current}):void 0,[e,r])},Zre=({open:e,onToggle:t})=>(0,V.jsxs)(U,{size:`sm`,variant:e?`primary`:`secondary`,"aria-pressed":e,onClick:t,className:`max-md:size-9 max-md:p-0`,children:[(0,V.jsx)(wn,{className:`size-3.5`}),(0,V.jsx)(`span`,{className:`max-md:sr-only`,children:`Assistant`})]}),a_=({client:e,page:t,onClose:n})=>{let{state:r,offline:i,error:a,send:o,act:s}=r_(e);return(0,V.jsx)(n_,{state:r,offline:i,error:a,onSend:e=>o(e,t),onAction:s,onClose:n,client:e})},Qre=({url:e,...t})=>(0,V.jsx)(a_,{client:i_(e),...t}),$re=({url:e,client:t,...n})=>t?(0,V.jsx)(a_,{client:t,...n}):(0,V.jsx)(Qre,{url:e,...n}),eie={orders:bn,orderLines:bn,companies:le,invoices:it,invoiceLines:sn,products:Xt,categories:In,tags:In,companyTags:In,stockMoves:se,stockLevels:se,warehouses:Xn,locations:Xn,people:qn,users:qn,empMaster:qn,organizations:gn,countries:We,currencies:ze,shipments:Hn},o_=e=>eie[e]??Mn,s_={bell:te,"book-open":ne,bookmark:oe,building:le,"credit-card":ze,"external-link":Je,"file-text":it,heart:ct,key:gt,"layout-dashboard":bt,"life-buoy":Tt,mail:zt,receipt:sn,settings:gn,shield:vn,users:qn};Object.keys(s_);var c_=(e,t)=>e?s_[e]??t:t,tie=(e,t,n)=>(e.bottomBar?.items??[]).map((r,i)=>r.kind===`link`?{id:`link-${i}`,label:r.label,icon:c_(r.icon,Je),href:r.href,external:!0}:r.kind===`page`?{id:r.page,label:r.label,icon:c_(r.icon??e.pages[r.page]?.icon,bt),href:us({kind:`page`,page:r.page},t),active:r.page===n}:{id:r.resource,label:r.label,icon:c_(r.icon,o_(r.resource)),href:us({kind:`list`,resource:r.resource},t),active:r.resource===n}),nie=({basePath:e,address:t,group:n,page:r,resourceLabel:i,recordTitle:a,recordLoading:o})=>{let s=n?[n]:[];if(r)return[...s,{label:r.title,href:us({kind:`page`,page:r.name},e)}];if(!t||t.kind===`page`)return[`Admin`];let c=i?[{label:i,href:us({kind:`list`,resource:t.resource},e)}]:[];if(t.kind===`list`)return[...s,...c];let l=us(t,e),u=t.kind===`create`?{label:`New`,href:l}:a===void 0&&o?{label:`Loading record`,href:l,loading:!0}:{label:a??t.key,href:l};return[...s,...c,u]},rie=({address:e,page:t,accountPage:n,resourceLabel:r,singular:i,recordTitle:a,recordLoading:o})=>{if(n)return[n];if(t)return[t.title];if(!e||e.kind===`page`)return[];let s=r?[r]:[];if(e.kind===`list`)return s;if(e.kind===`create`)return[...i?[`New ${i.toLowerCase()}`]:[],...s];let c=a??(o?void 0:e.key);return[...c?[c]:[],...s]},iie=(e,t)=>[...e.filter(Boolean),t].join(` · `),aie=e=>{(0,o.useEffect)(()=>{let t=document.title;return document.title=e,()=>{document.title=t}},[e])},l_=(0,o.createContext)(null),oie={create:!0,update:!0,delete:!0,conditional:[]},u_=()=>{let e=G(),t=Wp(),n=(0,o.useContext)(l_),r=vh({queryKey:W.meta,staleTime:0,refetchOnWindowFocus:`always`,queryFn:async()=>{let n=t.getQueryData(W.meta),r=await e.meta(n?.etag);if(r.status===`unchanged`){if(!n)throw Error(`The server answered 304 to a request without If-None-Match`);return n}return{etag:r.etag,appName:r.meta.appName,resources:Object.fromEntries(r.meta.resources.map(e=>[e.name,e])),views:Object.fromEntries(r.meta.views.map(e=>[e.resource,e])),pages:Object.fromEntries((r.meta.pages??[]).map(e=>[e.name,e])),permissions:r.meta.permissions??{},...r.meta.userMenu&&{userMenu:r.meta.userMenu},...r.meta.signIn&&{signIn:Object.fromEntries(r.meta.signIn.map(e=>[e.resource,e]))},...r.meta.bottomBar&&{bottomBar:r.meta.bottomBar},...r.meta.assistant&&{assistant:r.meta.assistant},...r.meta.runtime&&{runtime:r.meta.runtime},...r.meta.errorReporting&&{errorReporting:r.meta.errorReporting},...r.meta.maps&&{maps:r.meta.maps},...r.meta.files&&{files:r.meta.files},...r.meta.plugins&&{plugins:r.meta.plugins},...r.meta.sources&&{sources:r.meta.sources.map(e=>({source:e,state:`loading`}))}}}});return(0,o.useMemo)(()=>n&&r.data?{...r,data:n}:r,[n,r])},sie=1e4,cie=e=>e.map(e=>({data:e.data?.meta,error:e.error})),lie=(e,t)=>{let n=Wp(),r=gh({queries:e.map(e=>{let r=W.sourceMeta(e.url,e.resources);return{queryKey:r,staleTime:0,refetchOnWindowFocus:`always`,queryFn:async()=>{let i=n.getQueryData(r),a=await t(e).meta(i?.etag,{signal:AbortSignal.timeout(sie)});if(a.status===`unchanged`){if(!i)throw Error(`${e.label} answered 304 to a request without If-None-Match`);return i}return{etag:a.etag,meta:cc(a.meta,e)}}}}),combine:cie});return(0,o.useMemo)(()=>e.map((e,t)=>{let{data:n,error:i}=r[t];return n?{source:e,state:`ready`,meta:n}:i?{source:e,state:`error`,error:i}:{source:e,state:`loading`}}),[e,r])},uie=(e,t)=>{if(t.length===0)return e;let n=t.flatMap(e=>e.state===`ready`?[e.meta]:[]),r=t.map(e=>e.state===`error`?{source:e.source,state:`error`,error:e.error}:{source:e.source,state:e.state});return{...e,resources:{...e.resources,...Object.fromEntries(n.flatMap(e=>e.resources.map(e=>[e.name,e])))},views:{...e.views,...Object.fromEntries(n.flatMap(e=>e.views.map(e=>[e.resource,e])))},permissions:{...e.permissions,...Object.assign({},...n.map(e=>e.permissions))},sources:r}},die=(e,t)=>e.sources?.find(e=>e.source.resources.includes(t)),q=()=>{let e=(0,o.useContext)(l_);if(!e)throw Error(`useAdminMeta must be used inside MetaGate`);return e},d_=({title:e,children:t})=>(0,V.jsx)(`div`,{className:`flex h-full min-h-48 flex-1 items-center justify-center p-8`,children:(0,V.jsxs)(`div`,{className:`max-w-md text-center`,children:[(0,V.jsx)(`h1`,{className:`text-[16px] font-semibold`,children:e}),(0,V.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:t})]})}),fie=({meta:e,children:t})=>{let n=G(),r=rne(),i=(0,o.useMemo)(()=>(e.sources??[]).map(e=>e.source),[e.sources]),a=lie(i,r),s=(0,o.useMemo)(()=>uie(e,a),[e,a]),c=(0,o.useMemo)(()=>{let e=new Map(i.flatMap(e=>e.resources.map(t=>[t,e]))),t=t=>{let n=e.get(t);return n&&r(n)};return{client:Ys(n,t),resourceClient:t}},[i,n,r]);return(0,V.jsx)(ine,{client:c.client,resourceClient:c.resourceClient,children:(0,V.jsx)(l_.Provider,{value:s,children:t})})},pie=({children:e})=>{let t=u_();return t.isPending?(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(Dd,{}),` Loading`]}):t.error?(0,V.jsx)(d_,{title:`Cannot reach the API`,children:Fs(t.error)?t.error.message:`The server did not answer. Is it running?`}):(0,V.jsx)(fie,{meta:t.data,children:e})},f_=e=>q().permissions[e]??oie,p_=(e,t)=>t>=60&&t>Math.abs(e),m_=({title:e,open:t,onClose:n,children:r})=>{let i=(0,o.useRef)(null),a=(0,o.useRef)(void 0);return Cu(i,t,n),t?(0,V.jsxs)(`div`,{className:`fixed inset-0 z-[80]`,children:[(0,V.jsx)(`div`,{className:`absolute inset-0 bg-backdrop/40`,onClick:n,"aria-hidden":!0}),(0,V.jsxs)(`div`,{ref:i,role:`dialog`,"aria-modal":`true`,"aria-label":e,tabIndex:-1,className:`absolute inset-x-0 bottom-0 flex max-h-[85vh] flex-col rounded-t-xl border-t bg-background shadow-pop outline-none`,children:[(0,V.jsxs)(`header`,{className:`relative flex shrink-0 touch-none items-center justify-between border-b px-4`,onPointerDown:e=>{e.pointerType===`touch`&&(a.current={x:e.clientX,y:e.clientY})},onPointerUp:e=>{if(!a.current)return;let t=p_(e.clientX-a.current.x,e.clientY-a.current.y);a.current=void 0,t&&n()},onPointerCancel:()=>a.current=void 0,children:[(0,V.jsx)(`span`,{className:`absolute left-1/2 top-1.5 h-1 w-9 -translate-x-1/2 rounded-full bg-border-strong`,"aria-hidden":!0}),(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:e}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Close`,onClick:n,className:`-mr-2 inline-flex size-11 items-center justify-center rounded-md text-muted-foreground hover:bg-muted`,children:(0,V.jsx)(Qn,{className:`size-5`})})]}),(0,V.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 pb-6`,children:r})]})]}):null},h_=({title:e,description:t,open:n,onClose:r,actions:i,children:a,wide:o})=>{let s=mu();return n?s?(0,V.jsx)(Cf,{title:e,description:t,onClose:r,actions:i,wide:o,children:a}):(0,V.jsx)(m_,{title:e,open:!0,onClose:r,children:(0,V.jsxs)(`div`,{className:`pt-3`,children:[t&&(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:t}),a&&(0,V.jsx)(`div`,{className:`mt-4`,children:a}),(0,V.jsx)(`div`,{className:`mt-5 flex flex-col-reverse gap-2 [&>*]:min-h-11`,children:i})]})}):null};function g_(){var e=[...arguments];return(0,o.useMemo)(()=>t=>{e.forEach(e=>e(t))},e)}var __=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function v_(e){let t=Object.prototype.toString.call(e);return t===`[object Window]`||t===`[object global]`}function y_(e){return`nodeType`in e}function b_(e){return e?v_(e)?e:y_(e)?e.ownerDocument?.defaultView??window:window:window}function x_(e){let{Document:t}=b_(e);return e instanceof t}function S_(e){return!v_(e)&&e instanceof b_(e).HTMLElement}function C_(e){return e instanceof b_(e).SVGElement}function w_(e){return e?v_(e)?e.document:y_(e)?x_(e)?e:S_(e)||C_(e)?e.ownerDocument:document:document:document}var T_=__?o.useLayoutEffect:o.useEffect;function E_(e){let t=(0,o.useRef)(e);return T_(()=>{t.current=e}),(0,o.useCallback)(function(){var e=[...arguments];return t.current==null?void 0:t.current(...e)},[])}function D_(){let e=(0,o.useRef)(null);return[(0,o.useCallback)((t,n)=>{e.current=setInterval(t,n)},[]),(0,o.useCallback)(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[])]}function O_(e,t){t===void 0&&(t=[e]);let n=(0,o.useRef)(e);return T_(()=>{n.current!==e&&(n.current=e)},t),n}function k_(e,t){let n=(0,o.useRef)();return(0,o.useMemo)(()=>{let t=e(n.current);return n.current=t,t},[...t])}function A_(e){let t=E_(e),n=(0,o.useRef)(null);return[n,(0,o.useCallback)(e=>{e!==n.current&&t?.(e,n.current),n.current=e},[])]}function j_(e){let t=(0,o.useRef)();return(0,o.useEffect)(()=>{t.current=e},[e]),t.current}var M_={};function N_(e,t){return(0,o.useMemo)(()=>{if(t)return t;let n=M_[e]==null?0:M_[e]+1;return M_[e]=n,e+`-`+n},[e,t])}function P_(e){return function(t){return[...arguments].slice(1).reduce((t,n)=>{let r=Object.entries(n);for(let[n,i]of r){let r=t[n];r!=null&&(t[n]=r+e*i)}return t},{...t})}}var F_=P_(1),I_=P_(-1);function L_(e){return`clientX`in e&&`clientY`in e}function R_(e){if(!e)return!1;let{KeyboardEvent:t}=b_(e.target);return t&&e instanceof t}function z_(e){if(!e)return!1;let{TouchEvent:t}=b_(e.target);return t&&e instanceof t}function B_(e){if(z_(e)){if(e.touches&&e.touches.length){let{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}if(e.changedTouches&&e.changedTouches.length){let{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return L_(e)?{x:e.clientX,y:e.clientY}:null}var V_=Object.freeze({Translate:{toString(e){if(!e)return;let{x:t,y:n}=e;return`translate3d(`+(t?Math.round(t):0)+`px, `+(n?Math.round(n):0)+`px, 0)`}},Scale:{toString(e){if(!e)return;let{scaleX:t,scaleY:n}=e;return`scaleX(`+t+`) scaleY(`+n+`)`}},Transform:{toString(e){if(e)return[V_.Translate.toString(e),V_.Scale.toString(e)].join(` `)}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+` `+n+`ms `+r}}}),H_=`a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]`;function U_(e){return e.matches(H_)?e:e.querySelector(H_)}var W_={display:`none`};function G_(e){let{id:t,value:n}=e;return o.createElement(`div`,{id:t,style:W_},n)}function K_(e){let{id:t,announcement:n,ariaLiveType:r=`assertive`}=e;return o.createElement(`div`,{id:t,style:{position:`fixed`,top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:`hidden`,clip:`rect(0 0 0 0)`,clipPath:`inset(100%)`,whiteSpace:`nowrap`},role:`status`,"aria-live":r,"aria-atomic":!0},n)}function q_(){let[e,t]=(0,o.useState)(``);return{announce:(0,o.useCallback)(e=>{e!=null&&t(e)},[]),announcement:e}}var J_=(0,o.createContext)(null);function Y_(e){let t=(0,o.useContext)(J_);(0,o.useEffect)(()=>{if(!t)throw Error(`useDndMonitor must be used within a children of <DndContext>`);return t(e)},[e,t])}function X_(){let[e]=(0,o.useState)(()=>new Set),t=(0,o.useCallback)(t=>(e.add(t),()=>e.delete(t)),[e]);return[(0,o.useCallback)(t=>{let{type:n,event:r}=t;e.forEach(e=>e[n]?.call(e,r))},[e]),t]}var Z_={draggable:`
|
|
6
|
+
at `))}function ute(e,t){class n extends e{#e;constructor(...e){if(cte()){let t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);let t=Error().stack;t&&(this.#e=lte(t.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(n.prototype,"constructor",{get(){return t},enumerable:!1,configurable:!0}),n}var dte={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};ute(class extends Error{status;body;headers;statusCode;constructor(e=`INTERNAL_SERVER_ERROR`,t=void 0,n={},r=typeof e==`number`?e:dte[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=n,this.statusCode=r,this.name=`APIError`,this.status=e,this.headers=n,this.statusCode=r,this.body=t}},Error);var ol=class extends Error{constructor(e,t){super(e,t),this.name=`BetterAuthError`,this.message=e,this.stack=``}},fte=47;function sl(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===fte;)t--;return t===e.length?e:e.slice(0,t)}function pte(e){try{return(sl(new URL(e).pathname)||`/`)!==`/`}catch{throw new ol(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function mte(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new ol(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof ol?t:new ol(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function cl(e,t=`/api/auth`){if(mte(e),pte(e))return e;let n=sl(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function ll(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function hte(e,t,n,r,i){if(e)return cl(e,t);if(r!==!1){let e=il.BETTER_AUTH_URL||il.NEXT_PUBLIC_BETTER_AUTH_URL||il.PUBLIC_BETTER_AUTH_URL||il.NUXT_PUBLIC_BETTER_AUTH_URL||il.NUXT_PUBLIC_AUTH_URL||(il.BASE_URL===`/`?void 0:il.BASE_URL);if(e)return cl(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&ll(o,`proto`)&&ll(a,`host`))try{return cl(`${o}://${a}`,t)}catch{}if(n){let e=gte(n.url);if(!e)throw new ol(`Could not get origin from request. Please provide a valid base URL.`);return cl(e,t)}if(typeof window<`u`&&window.location)return cl(window.location.origin,t)}function gte(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}var _te=[`javascript:`,`data:`,`vbscript:`];function ul(e){let t;try{t=new URL(e)}catch{return!0}return!_te.includes(t.protocol)}var vte={id:`redirect`,name:`Redirect`,hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&ul(e.data.url)&&typeof window<`u`&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}},yte=()=>typeof window>`u`,bte=Wc;function xte(e,t){if(typeof window>`u`)return;let n=e.get();n.data===null&&t!==null&&e.set({...n,data:t,error:null,isPending:!1})}function dl(e){return typeof e==`object`&&e&&`data`in e&&`error`in e?e:{data:e,error:null}}function Ste(e){return!e||e.session===null&&e.user===null?null:e}function Cte(e,t){return qc(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}function wte(e,t){let n=Bc(!1),r,i=0,a=0;n.listen(()=>{a++,i=0});let o=e=>u(e),s=el({data:null,error:null,isPending:!0,isRefetching:!1,refetch:o});Jc(s,Cte);let c=async(t,n)=>{let r=s.value;if(s.set({...r,isPending:r.data===null,isRefetching:!0,error:null,refetch:o}),t.aborted)return`aborted`;try{let r=await e(`/get-session`,{method:`GET`,query:n?.query,signal:t});if(t.aborted)return`aborted`;let{data:i,error:a}=dl(r),c=`fresh`;if(i?.needsRefresh)try{let n=await e(`/get-session`,{method:`POST`,signal:t});if(t.aborted)return`aborted`;({data:i,error:a}=dl(n))}catch{if(t.aborted)return`aborted`;c=`stale`}if(a){let e=s.value,t=a?.status===401;return s.set({data:t?null:e.data,error:a,isPending:!1,isRefetching:!1,refetch:o}),`failed`}let l=Ste(i),u=s.value,d=u.data!=null&&l!=null&&qc(u.data,l)?u.data:l;return s.set({data:d,error:null,isPending:!1,isRefetching:!1,refetch:o}),c}catch(e){if(t.aborted)return`aborted`;let n=s.value;return s.set({data:n.data,error:e,isPending:!1,isRefetching:!1,refetch:o}),`failed`}},l=()=>{let e=s.value.data?.session?.expiresAt,t=e instanceof Date?e.getTime():1/0;return Math.min(Date.now()+bte,t)},u=e=>{i=0,r?.cancel();let t=new AbortController,n={cancel:()=>t.abort(),promise:Promise.resolve().then(()=>t.signal.aborted?`aborted`:c(t.signal,e)),revision:a};r=n;let o=e=>{r===n&&(r=void 0,e===`fresh`&&n.revision===a&&(i=l()))};return n.promise.then(o,()=>o(`failed`)),n.promise.then(()=>void 0)},d=()=>r?.revision===a?r.promise.then(()=>void 0):Date.now()<i?Promise.resolve():u(),f=()=>{};return Gc(s,()=>{let e;yte()||(e=setTimeout(()=>{d()},0));let r=ste({fetchSession:u,shouldPollSession:()=>s.value.data!=null,sessionSignal:n,options:t});return r.init(),f=r.broadcastSessionUpdate,()=>{e&&clearTimeout(e),r.cleanup()}}),{session:s,$sessionSignal:n,broadcastSessionUpdate:e=>f(e)}}function fl(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function pl(e,t,n=`.`,r){if(!fl(t))return pl(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(i[t]=Array.isArray(a)&&Array.isArray(i[t])?[...a,...i[t]]:fl(a)&&fl(i[t])?pl(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function Tte(e){return(...t)=>t.reduce((t,n)=>pl(t,n,``,e),{})}var Ete=Tte(),Dte=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},Ote=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let t=await i.init?.call(i,e.toString(),n);n=t.options||n,e=t.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}},ml=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},kte=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function Ate(e){if(typeof e==`number`)return new ml({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new ml(e);case`exponential`:return new kte(e);default:throw Error(`Invalid retry strategy`)}}var jte=[`get`,`post`,`put`,`patch`,`delete`];function hl(e){if(!e.startsWith(`@`))return{method:void 0,path:e};let t=e.indexOf(`/`),n=e.slice(1,t===-1?void 0:t);return jte.includes(n)?{method:n,path:t===-1?e:e.slice(t+1)}:{method:void 0,path:e}}var Mte=e=>e===`.`||e===`..`,Nte=e=>e.split(`:`).map(e=>encodeURIComponent(e)).join(`:`);function Pte(e,t){let n=t.get(e);if(n===void 0)return Nte(e);if(Mte(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function Fte(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``,{path:o}=hl(e);o!==e&&(e=`/${o}`),a.endsWith(`/`)||(a+=`/`);let[s,c]=e.replace(a,``).split(`?`),l=new URLSearchParams(c);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)l.append(e,n);continue}else n=JSON.stringify(t);l.set(e,n)}let u=new Map;if(r){if(Array.isArray(r)){let e=s.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];u.set(n,String(e))}}else for(let[e,t]of Object.entries(r))u.set(`:${e}`,String(t))}s=s.split(`/`).map(e=>Pte(e,u)).join(`/`),s=s.replace(/^\/+/,``);let d=l.toString();return d=d.length>0?`?${d}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${s}${d}`,a):`${a}${s}${d}`}var Ite=async e=>{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},Lte=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Rte(e){let t=e.headers.get(`content-type`),n=new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return Lte.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function zte(e){try{return JSON.parse(e),!0}catch{return!1}}function gl(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function _l(e){try{return JSON.parse(e)}catch{return e}}function vl(e){return typeof e==`function`}function Bte(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&vl(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&vl(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function yl(...e){let t={};for(let n of e)if(n){if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}}return t}async function Vte(e){let t=new Headers(yl(e?.headers,await Ite(e)));if(!t.has(`content-type`)){let n=Hte(e?.body);n&&t.set(`content-type`,n)}return t}function Hte(e){return gl(e)?`application/json`:null}function Ute(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function Wte(e,t){let{body:n}=e;return n?!gl(n)||typeof n==`string`?n:Ute(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function Gte(e,t){if(t?.method)return t.method.toUpperCase();let{method:n}=hl(e);return n?n.toUpperCase():t?.body?`POST`:`GET`}function Kte(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var qte=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function bl(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new qte(n.issues);return n.value}function xl(e){"@babel/helpers - typeof";return xl=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},xl(e)}function Jte(e,t){if(xl(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(xl(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Yte(e){var t=Jte(e,`string`);return xl(t)==`symbol`?t:t+``}function Xte(e,t,n){return(t=Yte(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Sl(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Cl(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Sl(Object(n),!0).forEach(function(t){Xte(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Sl(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var wl=async(e,t)=>{var n;let{hooks:r,url:i,options:a}=await Ote(e,t),o=Bte(a),s=new AbortController,c=a.signal??s.signal,l=Fte(i,a),u=await Vte(a),d=Wte(a,u),f=Gte(i,a),p=Cl(Cl({},a),{},{url:l,headers:u,body:d,method:f,signal:c});for(let e of r.onRequest)if(e){let t=await e(p);typeof t==`object`&&t&&Object.assign(p,t)}(`pipeTo`in p&&typeof p.pipeTo==`function`||typeof(t==null||(n=t.body)==null?void 0:n.pipe)==`function`)&&(`duplex`in p||(p.duplex=`half`));let{clearTimeout:m}=Kte(a,s),h=await o(p.url,p);m();let g={response:h,request:p};for(let e of r.onResponse)if(e){var _;let n=await e(Cl(Cl({},g),{},{response:t!=null&&(_=t.hookOptions)!=null&&_.cloneResponse?h.clone():h}));n instanceof Response?h=n:typeof n==`object`&&n&&(h=n.response)}if(h.ok){if(p.method===`HEAD`)return{data:``,error:null};let e=Rte(h),n={data:null,response:h,request:p};if(e===`json`||e===`text`){let e=await h.text();n.data=await(p.jsonParser??_l)(e)}else n.data=await h[e]();p?.output&&p.output&&!p.disableValidation&&(n.data=await bl(p.output,n.data));for(let e of r.onSuccess)if(e){var v;await e(Cl(Cl({},n),{},{response:t!=null&&(v=t.hookOptions)!=null&&v.cloneResponse?h.clone():h}))}return t?.throw?n.data:{data:n.data,error:null}}let y=t?.jsonParser??_l,b=await h.text(),x=zte(b),S=x?await y(b):null,C={response:h,responseText:b,request:p,error:Cl(Cl({},S),{},{status:h.status,statusText:h.statusText})};for(let e of r.onError)if(e){var w;await e(Cl(Cl({},C),{},{response:t!=null&&(w=t.hookOptions)!=null&&w.cloneResponse?h.clone():h}))}if(t?.retry){let n=Ate(t.retry),i=t.retryAttempt??0;if(await n.shouldAttemptRetry(i,h)){for(let e of r.onRetry)e&&await e(g);let a=n.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await wl(e,Cl(Cl({},t),{},{retryAttempt:i+1}))}}if(t?.throw)throw new Dte(h.status,h.statusText,x?S:b);return{data:null,error:Cl(Cl({},S),{},{status:h.status,statusText:h.statusText})}},Zte=e=>({id:`apply-schema`,name:`Apply Schema`,version:`1.0.0`,async init(t,n){var r;let i=Cl(Cl({},n),e.query!==void 0&&{query:Cl(Cl({},e.query),n?.query)}),a=((r=e.plugins)==null||(r=r.find(e=>e.schema?.config?t.startsWith(e.schema.config.baseURL||``)||t.startsWith(e.schema.config.prefix||``):!1))==null?void 0:r.schema)||e.schema;if(a){let r=t;a.config?.prefix&&r.startsWith(a.config.prefix)&&(r=r.replace(a.config.prefix,``),a.config.baseURL&&(t=t.replace(a.config.prefix,a.config.baseURL))),a.config?.baseURL&&r.startsWith(a.config.baseURL)&&(r=r.replace(a.config.baseURL,``)),r.startsWith(`/`)&&r.charAt(1)===`@`&&(r=r.substring(1));let o=a.schema[r];if(o){let{method:a,path:s}=hl(r);a&&(t=t.slice(0,t.length-r.length)+s);let c=n?.headers;if(o.headers&&!n?.disableValidation){let e={};if(n?.headers){if(n.headers instanceof Headers)n.headers.forEach((t,n)=>{e[n.toLowerCase()]=t});else if(typeof n.headers==`object`)for(let[t,r]of Object.entries(n.headers))r!=null&&(e[t.toLowerCase()]=r)}let t=await bl(o.headers,e),r={};for(let[e,n]of Object.entries(t))r[e.toLowerCase()]=n;c=r}let l=o.method??a;if(i=Cl(Cl(Cl(Cl({},i),l!==void 0&&{method:l}),o.output!==void 0&&{output:o.output}),c!==void 0&&{headers:c}),!n?.disableValidation){if(o.query&&(i.query=await bl(o.query,n?.query),i.query!==null&&typeof i.query==`object`)){let t=Cl({},e.query);for(let e of Object.keys(t))n?.query&&Object.prototype.hasOwnProperty.call(n.query,e)&&(t[e]=n.query[e]);i.query=Cl(Cl({},t),i.query)}i=Cl(Cl({},i),{},{body:o.input?await bl(o.input,n?.body):n?.body,params:o.params?await bl(o.params,n?.params):n?.params})}return{url:t,options:i}}}return Cl({url:t},(n!==void 0||e.query!==void 0)&&{options:i})}}),Qte=e=>{async function t(t,n){let r=Cl(Cl(Cl({},e),n),{},{headers:yl(e?.headers,n?.headers),plugins:[...e?.plugins||[],Zte(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await wl(t,r)}catch(e){return{data:null,error:{status:500,statusText:`Fetch Error`,message:`Fetch related error. Captured by catchAllError option. See error property for more details.`,error:e}}}return await wl(t,r)}return t},Tl=e=>{if(typeof process>`u`)return;let t=e??`/api/auth`;if({}.NEXT_PUBLIC_AUTH_URL)return{}.NEXT_PUBLIC_AUTH_URL;if(typeof window>`u`){if({}.NEXTAUTH_URL)try{return{}.NEXTAUTH_URL}catch{}if({}.VERCEL_URL)try{let e={}.VERCEL_URL.startsWith(`http`)?``:`https://`;return`${new URL(`${e}${{}.VERCEL_URL}`).origin}${t}`}catch{}}},El=e=>e===`/sign-out`||e===`/update-user`||e===`/update-session`||e===`/sign-up/email`||e===`/sign-in/email`||e===`/delete-user`||e===`/verify-email`||e===`/revoke-sessions`||e===`/revoke-session`||e===`/revoke-other-sessions`||e===`/change-email`||e===`/change-password`,Dl=(e,t)=>{let n=`credentials`in Request.prototype,r=hte(e?.baseURL,e?.basePath,void 0,t)??Tl(e?.basePath)??`/api/auth`,i=e?.plugins?.flatMap(e=>e.fetchPlugins).filter(e=>e!==void 0)||[],a={id:`lifecycle-hooks`,name:`lifecycle-hooks`,hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:o,onError:s,onRequest:c,onResponse:l,...u}=e?.fetchOptions||{},d=Qte({baseURL:r,...n?{credentials:`include`}:{},method:`GET`,jsonParser(e){return e?tte(e,{strict:!1}):null},customFetchImpl:fetch,...u,plugins:[a,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[vte],...i]}),{$sessionSignal:f,session:p,broadcastSessionUpdate:m}=wte(d,e),h=!1,g=e=>{h||e===null||(h=!0,xte(p,e))},_=e?.plugins||[],v={},y={$sessionSignal:f,session:p},b={"/sign-out":`POST`,"/revoke-sessions":`POST`,"/revoke-other-sessions":`POST`,"/delete-user":`POST`},x=[{signal:`$sessionSignal`,matcher:El,callback(e){e===`/sign-out`?m(`signout`):(e===`/update-user`||e===`/update-session`)&&m(`updateUser`)}}];for(let e of _)e.getAtoms&&Object.assign(y,e.getAtoms?.(d)),e.pathMethods&&Object.assign(b,e.pathMethods),e.atomListeners&&x.push(...e.atomListeners);let S={notify:e=>{y[e].set(!y[e].get())},listen:(e,t)=>{y[e].subscribe(t)},atoms:y};for(let t of _)t.getActions&&(v=Ete(t.getActions?.(d,S,e)??{},v));return{get baseURL(){return r},pluginsActions:v,pluginsAtoms:y,pluginPathMethods:b,atomListeners:x,hydrateSession:g,$sessionSignal:f,$fetch:d,$store:S}};function Ol(e){return typeof e==`object`&&!!e&&`get`in e&&typeof e.get==`function`&&`lc`in e&&typeof e.lc==`number`}function kl(e){return e.charAt(0).toUpperCase()+e.slice(1)}var Al=/[\p{Ll}\d]+|\p{Lu}+(?!\p{Ll})|\p{Lu}[\p{Ll}\d]+|\p{Lo}+/gu,jl=/['\u2019]/g;function Ml(e){return e.replace(jl,``).match(Al)??[]}function Nl(e){return Ml(e).map(e=>e.toLowerCase()).join(`-`)}function Pl(e,t,n){let r=t[e],{fetchOptions:i,query:a,...o}=n||{};return r||(i?.method?i.method:o&&Object.keys(o).length>0?`POST`:`GET`)}function Fl(e,t,n,r,i){function a(o=[]){return new Proxy(function(){},{get(t,n){if(typeof n!=`string`||n===`then`||n===`catch`||n===`finally`)return;let r=[...o,n],i=e;for(let e of r)if(i&&typeof i==`object`&&e in i)i=i[e];else{i=void 0;break}return typeof i==`function`||Ol(i)?i:a(r)},apply:async(e,a,s)=>{let c=`/`+o.map(Nl).join(`/`),l=s[0]||{},u=s[1]||{},{query:d,fetchOptions:f,...p}=l,m={...u,...f},h=Pl(c,n,l);return await t(c,{...m,body:h===`GET`?void 0:{...p,...m?.body||{}},query:d||m?.query,method:h,async onSuccess(e){if(await m?.onSuccess?.(e),!i||m.disableSignal)return;let t=i.filter(e=>e.matcher(c));if(!t.length)return;let n=new Set;for(let e of t){let t=r[e.signal];if(!t)return;if(n.has(e.signal))continue;n.add(e.signal);let i=t.get();setTimeout(()=>{t.set(!i)},10),e.callback?.(c)}}})}})}return a()}function Il(e){let{pluginPathMethods:t,pluginsActions:n,pluginsAtoms:r,hydrateSession:i,$fetch:a,atomListeners:o,$store:s}=Dl(e),c={};for(let[e,t]of Object.entries(r))c[`use${kl(e)}`]=t;return Fl({...n,...c,hydrateSession:i,$fetch:a,$store:s},a,t,r,o)}var Ll=(e,{$listPasskeys:t,$store:n})=>({signIn:{passkey:async(r,i)=>{let a=await e(`/passkey/generate-authenticate-options`,{method:`GET`,throw:!1});if(!a.data)return a;let o=a.data.extensions||r?.extensions?{...a.data.extensions||{},...r?.extensions||{}}:void 0,s;try{s=await Ac({optionsJSON:{...a.data,extensions:o},useBrowserAutofill:r?.autoFill})}catch(e){return{data:null,error:{code:e instanceof bc?e.code:`AUTH_CANCELLED`,message:fc.AUTH_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}}try{let{clientExtensionResults:a,...o}=s,c=await e(`/passkey/verify-authentication`,{body:{response:o},...r?.fetchOptions,...i,method:`POST`,throw:!1});return t.set(Math.random()),n.notify(`$sessionSignal`),r?.returnWebAuthnResponse?{...c,webauthn:{response:s,clientExtensionResults:a}}:c}catch(e){return console.error(`[Better Auth] Error verifying passkey`,e),{data:null,error:{code:`AUTH_CANCELLED`,message:fc.AUTH_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}}}},passkey:{addPasskey:async(r,i)=>{let a=await e(`/passkey/generate-register-options`,{method:`GET`,query:{...r?.authenticatorAttachment&&{authenticatorAttachment:r.authenticatorAttachment},...r?.name&&{name:r.name},...r?.context&&{context:r.context}},throw:!1});if(!a.data)return a;try{let o=a.data.extensions||r?.extensions?{...a.data.extensions||{},...r?.extensions||{}}:void 0,s=await Tc({optionsJSON:{...a.data,extensions:o},useAutoRegister:r?.useAutoRegister}),{clientExtensionResults:c,...l}=s,u=await e(`/passkey/verify-registration`,{...r?.fetchOptions,...i,body:{response:l,name:r?.name,...r?.createSession&&{createSession:!0}},method:`POST`,throw:!1});return u.data?(t.set(Math.random()),u.data.session&&n.notify(`$sessionSignal`),r?.returnWebAuthnResponse?{...u,webauthn:{response:s,clientExtensionResults:c}}:u):u}catch(e){return e instanceof bc?e.code===`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`?{data:null,error:{code:e.code,message:fc.PREVIOUSLY_REGISTERED.message,status:400,statusText:`BAD_REQUEST`}}:e.code===`ERROR_CEREMONY_ABORTED`?{data:null,error:{code:e.code,message:fc.REGISTRATION_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}:{data:null,error:{code:e.code,message:e.message,status:400,statusText:`BAD_REQUEST`}}:{data:null,error:{code:`UNKNOWN_ERROR`,message:e instanceof Error?e.message:fc.UNKNOWN_ERROR.message,status:500,statusText:`INTERNAL_SERVER_ERROR`}}}}},$Infer:{}}),Rl=()=>{let e=Bc();return{id:`passkey`,version:pc,$InferServerPlugin:{},getActions:(t,n)=>Ll(t,{$listPasskeys:e,$store:n}),getAtoms(t){return{listPasskeys:ate(e,`/passkey/list-user-passkeys`,t,{method:`GET`}),$listPasskeys:e}},pathMethods:{"/passkey/register":`POST`,"/passkey/authenticate":`POST`},atomListeners:[{matcher(e){return e===`/passkey/verify-registration`||e===`/passkey/delete-passkey`||e===`/passkey/update-passkey`||e===`/sign-out`},signal:`$listPasskeys`},{matcher:e=>e===`/passkey/verify-authentication`,signal:`$sessionSignal`}],$ERROR_CODES:fc}},zl=dc({OTP_EXPIRED:`OTP expired`,INVALID_OTP:`Invalid OTP`,TOO_MANY_ATTEMPTS:`Too many attempts`}),Bl=()=>({id:`email-otp`,version:jc,$InferServerPlugin:{},atomListeners:[{matcher:e=>e===`/email-otp/verify-email`||e===`/sign-in/email-otp`||e===`/email-otp/request-email-change`,signal:`$sessionSignal`}],$ERROR_CODES:zl}),Vl=e=>{let t=e?.jwks?.jwksPath??`/jwks`;return{id:`better-auth-client`,version:jc,$InferServerPlugin:{},pathMethods:{[t]:`GET`},getActions:(e,n,r)=>({jwks:async n=>await e(t,{method:`GET`,...n})})}},Hl=dc({OTP_NOT_ENABLED:`OTP not enabled`,OTP_NOT_CONFIGURED:`OTP is not available`,OTP_HAS_EXPIRED:`OTP has expired`,TOTP_NOT_ENABLED:`TOTP not enabled`,TOTP_ALREADY_ENABLED:`TOTP is already enabled`,TOTP_NOT_CONFIGURED:`TOTP is not available`,TWO_FACTOR_NOT_ENABLED:`Two factor isn't enabled`,BACKUP_CODES_NOT_ENABLED:`Backup codes aren't enabled`,INVALID_BACKUP_CODE:`Invalid backup code`,INVALID_CODE:`Invalid code`,TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:`Too many attempts. Please request a new code.`,ACCOUNT_TEMPORARILY_LOCKED:`Too many failed verification attempts. Your account is temporarily locked. Please try again later.`,INVALID_TWO_FACTOR_COOKIE:`Invalid two factor cookie`}),Ul=e=>({id:`two-factor`,version:jc,$InferServerPlugin:{},atomListeners:[{matcher:e=>e.startsWith(`/two-factor/`),signal:`$sessionSignal`}],pathMethods:{"/two-factor/disable":`POST`,"/two-factor/enable":`POST`,"/two-factor/send-otp":`POST`,"/two-factor/generate-backup-codes":`POST`,"/two-factor/get-totp-uri":`POST`,"/two-factor/verify-totp":`POST`,"/two-factor/verify-otp":`POST`,"/two-factor/verify-backup-code":`POST`},fetchPlugins:[{id:`two-factor`,name:`two-factor`,hooks:{async onSuccess(t){if(t.data?.twoFactorRedirect){if(e?.onTwoFactorRedirect){await e.onTwoFactorRedirect({twoFactorMethods:t.data.twoFactorMethods});return}e?.twoFactorPage&&typeof window<`u`&&ul(e.twoFactorPage)&&(window.location.href=e.twoFactorPage)}}}}],$ERROR_CODES:Hl}),Wl=(e,t,n)=>Il({baseURL:e,basePath:t,plugins:[Vl(),Bl(),Ul(),Rl()],fetchOptions:{customFetchImpl:n}}),Gl=e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?JSON.parse(e):[],Kl=e=>{let t=e.split(`,`);return t.includes(`owner`)?`owner`:t.includes(`admin`)?`admin`:`member`},ql=e=>({id:e.id,userId:e.userId,name:e.user.name||e.user.email,email:e.user.email,role:Kl(e.role),appRoles:Gl(e.appRoles),createdAt:new Date(e.createdAt).toISOString()}),Jl=e=>({id:e.id,email:e.email,role:Kl(e.role),appRoles:Gl(e.appRoles),status:e.status,expiresAt:new Date(e.expiresAt).toISOString(),...e.organizationName&&{organizationName:e.organizationName}}),Yl=(e,t)=>{let n=async(t,n,r={})=>{let{data:i,error:a}=await e.$fetch(t,{method:r.method??(r.body?`POST`:`GET`),...r.body&&{body:r.body},...r.query&&{query:r.query}});if(a)throw B(a,n);return i},r=async e=>(await t(),e);return{list:async()=>await n(`/organization/list`,`Could not read your organizations`)??[],current:()=>n(`/organization/current`,`Could not read the current organization`),switchTo:async e=>r(await n(`/organization/switch`,`Could not switch the organization`,{body:{organizationId:e}})),search:async e=>(await n(`/organization/search`,`Could not search the organizations`,{query:{query:e}})).organizations,create:async e=>r(await n(`/organization/create`,`Could not create the organization`,{body:e})),rename:(e,t)=>n(`/organization/update`,`Could not change the organization`,{body:{organizationId:e,data:t}}),remove:async e=>r(await n(`/organization/delete`,`Could not delete the organization`,{body:{organizationId:e}})),leave:async e=>r(await n(`/organization/leave`,`Could not leave the organization`,{body:{organizationId:e}})),members:async e=>(await n(`/organization/list-members`,`Could not read the members`,{query:{organizationId:e,limit:`1000`}})).members.map(ql),setRole:(e,t,r)=>n(`/organization/update-member-role`,`Could not change the role`,{body:{organizationId:e,memberId:t,role:r}}),setAppRoles:(e,t)=>n(`/organization/set-app-roles`,`Could not change the app roles`,{body:{memberId:e,appRoles:t}}),removeMember:(e,t)=>n(`/organization/remove-member`,`Could not remove the member`,{body:{organizationId:e,memberIdOrEmail:t}}),transferOwnership:(e,t=`admin`)=>n(`/organization/transfer-ownership`,`Could not hand the organization over`,{body:{memberId:e,keepAs:t}}),invitations:async e=>(await n(`/organization/list-invitations`,`Could not read the invitations`,{query:{organizationId:e}})??[]).map(Jl),invite:async(e,t)=>{let r=await n(`/organization/invite-member`,`Could not send the invitation`,{body:{organizationId:e,...t}});return{invitation:Jl(r),...r.link&&{link:r.link}}},resend:async(e,t)=>{let r=await n(`/organization/invite-member`,`Could not send the invitation again`,{body:{organizationId:e,email:t.email,role:t.role,resend:!0}});return{invitation:Jl(r),...r.link&&{link:r.link}}},revoke:e=>n(`/organization/cancel-invitation`,`Could not revoke the invitation`,{body:{invitationId:e}}),myInvitations:async()=>(await n(`/organization/list-user-invitations`,`Could not read your invitations`)??[]).map(Jl),invitation:e=>n(`/invitation`,`This invitation link is not valid`,{query:{token:e}}),accept:async e=>r(await n(`/invitation/accept`,`Could not accept the invitation`,{body:{token:e}})),signUpFromInvitation:async(e,t)=>r(await n(`/invitation/sign-up`,`Could not create your account`,{body:{token:e,...t}}))}},Xl=(e,t)=>({current:async()=>{let{data:t,error:n}=await e.$fetch(`/role/current`,{method:`GET`});if(n)throw B(n,`Could not read your roles`);return t},switchTo:async n=>{let{error:r}=await e.$fetch(`/role/switch`,{method:`POST`,body:{role:n}});if(r)throw B(r,`Could not switch the role`);await t()}}),Zl=(e,t)=>{let n=async e=>e?.twoFactorRedirect?{kind:`two-factor`,methods:e.twoFactorMethods??[]}:(await t(),{kind:`signed-in`,user:e?.user});return{signIn:async(t,r)=>{let{data:i,error:a}=await e.signIn.email({email:t,password:r});if(a||!i)throw B(a,`Sign-in failed`);return n(i)},sendSignInCode:async t=>{let{error:n}=await e.emailOtp.sendVerificationOtp({email:t,type:`sign-in`});if(n)throw B(n,`Could not send the code`)},signInWithCode:async(t,r)=>{let{data:i,error:a}=await e.signIn.emailOtp({email:t,otp:r});if(a||!i)throw B(a,`Sign-in failed`);return n(i)},sendSignUpCode:async t=>{let{error:n}=await e.$fetch(`/sign-up/send-code`,{method:`POST`,body:{email:t}});if(n)throw B(n,`Could not send the code`)},verifySignUpCode:async(t,n)=>{let{data:r,error:i}=await e.$fetch(`/sign-up/verify-code`,{method:`POST`,body:{email:t,code:n}});if(i||!r)throw B(i,`Could not check the code`);return r.ticket},signUp:async n=>{let{data:r,error:i}=await e.$fetch(`/sign-up/create`,{method:`POST`,body:n});if(i||!r)throw B(i,`Could not create your account`);return await t(),r.user},signInWithPasskey:async n=>{let r=await e.$fetch(`/passkey/generate-authenticate-options`,{method:`GET`,...n&&{query:{rpId:n}}});if(r.error||!r.data)throw B(r.error,`Sign-in failed`);let{clientExtensionResults:i,...a}=await Ac({optionsJSON:r.data}).catch(e=>{throw new lc(`Auth cancelled`,400,e instanceof bc?e.code:`AUTH_CANCELLED`)}),o=await e.$fetch(`/passkey/verify-authentication`,{method:`POST`,body:{response:a}});if(o.error||!o.data)throw B(o.error,`Sign-in failed`);return await t(),o.data.user},sendTwoFactorCode:async()=>{let{error:t}=await e.twoFactor.sendOtp();if(t)throw B(t,`Could not send the code`)},verifyTwoFactor:async({method:n,code:r,trustDevice:i=!1})=>{let{data:a,error:o}=await(n===`totp`?e.twoFactor.verifyTotp:n===`otp`?e.twoFactor.verifyOtp:e.twoFactor.verifyBackupCode)({code:r,trustDevice:i});if(o||!a)throw B(o,`The code did not work`);return await t(),a.user}}},Ql=e=>({read:async()=>{let{data:t,error:n}=await e.$fetch(`/policy/sign-in`);if(n||!t)throw B(n,`Could not read the sign-in policy`);return t},save:async t=>{let{data:n,error:r}=await e.$fetch(`/policy/sign-in`,{method:`POST`,body:t});if(r||!n)throw B(r,`Could not save the sign-in policy`);return n}}),$l=e=>new Date(e).toISOString(),eu=({startedAt:e,expiresAt:t,endedAt:n,...r})=>({...r,startedAt:$l(e),expiresAt:$l(t),...n&&{endedAt:$l(n)}}),tu=e=>({start:async t=>{let{data:n,error:r}=await e.$fetch(`/staff/sign-in`,{method:`POST`,body:t});if(r||!n?.url)throw B(r,`Could not start the staff sign-in`);return n.url},current:async()=>{let{data:t,error:n}=await e.$fetch(`/staff/session`);if(n||!t)throw B(n,`Could not read the session`);return t.staff?eu(t.staff):void 0},stop:async()=>{let{error:t}=await e.$fetch(`/staff/stop`,{method:`POST`,body:{}});if(t)throw B(t,`Could not end the staff session`)},log:async()=>{let{data:t,error:n}=await e.$fetch(`/staff/sign-ins`);if(n||!t)throw B(n,`Could not read the staff sign-ins`);return t.signIns.map(eu)}}),nu=e=>{let t=e.split(`.`)[1];if(!t)throw Error(`Not a JWT`);let n=JSON.parse(atob(t.replace(/-/g,`+`).replace(/_/g,`/`)));if(typeof n.exp!=`number`)throw Error(`The token has no expiry`);return n.exp*1e3},ru=(e={})=>{let t=e.origin??globalThis.location?.origin??`http://localhost`,n=e.basePath??`/api/auth`,r=e.refreshMarginMs??6e4,i=e.fetch??((e,t)=>fetch(e,t)),a=Wl(t,n,i),o=tu(a),s,c,l,u=()=>{s=void 0,clearTimeout(l)},d=async()=>{let{data:t}=await a.$fetch(`/token`);if(!t?.token){u();return}return s={token:t.token,expiresAt:nu(t.token)},clearTimeout(l),l=setTimeout(()=>void f({refresh:!0}).then(t=>t||e.onSignedOut?.()),Math.max(1e3,s.expiresAt-Date.now()-r)),s.token},f=async({refresh:e=!1}={})=>!e&&s&&s.expiresAt-Date.now()>r?s.token:(c??=d().finally(()=>{c=void 0}),c);return{token:f,status:async()=>{let e=await i(`${t}${n}/status`);if(e.status===404)throw new lc(`This server has no sign-in. Is the API URL right?`,404);if(!e.ok)throw new lc(`Could not read the sign-in status`,e.status);let r=await e.json();return{needsAdmin:!!r.needsAdmin,signInMethods:r.signInMethods??[`password`],passwordReset:!!r.passwordReset,...r.signUp&&{signUp:!0},socialProviders:r.socialProviders??[],...r.platformSignIn&&{platformSignIn:r.platformSignIn},...r.staffSignIn&&{staffSignIn:r.staffSignIn},...r.passkeyDomains&&{passkeyDomains:r.passkeyDomains},...r.organizations&&{organizations:r.organizations},...r.anonymous&&{anonymous:!0},...r.plugins&&r.plugins.length>0&&{plugins:r.plugins}}},session:async()=>{let{data:e}=await a.getSession();return e?.user},...Zl(a,()=>f({refresh:!0})),signInSocial:async(e,t)=>{let{data:n,error:r}=await a.signIn.social({provider:e,callbackURL:t,errorCallbackURL:t,disableRedirect:!0});if(r||!n?.url)throw B(r,`Sign-in failed`);return n.url},signOut:async()=>{u(),await a.signOut()},requestPasswordReset:async(e,t)=>{let{error:n}=await a.requestPasswordReset({email:e,redirectTo:t});if(n)throw B(n,`Could not send the reset link`)},resetPassword:async(e,t)=>{let{error:n}=await a.resetPassword({token:e,newPassword:t});if(n)throw B(n,`Could not set the password`)},account:uc(a),organizations:Yl(a,()=>f({refresh:!0})),roles:Xl(a,()=>f({refresh:!0})),signInPolicy:Ql(a),staff:{...o,stop:async()=>{u(),await o.stop()}}}},iu=e=>Math.min(3e4,1e3*2**e),au=(e,t)=>new Promise(n=>{let r=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(r),n()},{once:!0})}),ou=`http://same-origin.invalid`,su=(e,t)=>{let n=new URL(e,ou),r=new URL(t,`${n.href}/`);if(r.origin!==n.origin)throw Error(`${t} is not on the assistant backend's origin`);return n.origin===ou?`${r.pathname}${r.search}`:r.href},cu=e=>{let t=e.url.replace(/\/+$/,``),n=e.fetch??((e,t)=>fetch(e,t)),r=e.retryDelayMs??iu,i=async(r,i)=>{let a=await e.token(),o=await n(`${t}${r}`,{method:i.method,headers:{...i.body===void 0?{accept:`text/event-stream`}:{"content-type":`application/json`},...a&&{authorization:`Bearer ${a}`}},body:i.body===void 0?void 0:JSON.stringify(i.body),signal:i.signal});if(!o.ok)throw await Ls(o);return o},a=async(e,t,n)=>{let r=await i(`/events`,{method:`GET`,signal:e});if(!r.body)throw Error(`The assistant backend answered the event stream without a body`);n(),await ns(r.body,e=>t(JSON.parse(e)),e)};return{connect:(e,t)=>{let n=new AbortController,{signal:i}=n;return(async()=>{let n=0;for(;!i.aborted;){t?.({state:`connecting`});let o=await a(i,e,()=>{n=0,t?.({state:`open`})}).then(()=>void 0,e=>e??Error(`The assistant stream failed`));if(i.aborted)return;t?.({state:`retrying`,...o!==void 0&&{error:o}}),await au(r(n++),i)}})(),()=>n.abort()},send:async(e,t)=>{await i(`/messages`,{method:`POST`,body:{text:e,...t&&{page:t}}})},act:async(e,t)=>{await i(`/actions`,{method:`POST`,body:{partId:e,actionId:t}})},fetch:async(r,i={})=>{let a=su(t,r),o=await e.token(),s=new Headers(i.headers);o&&s.set(`authorization`,`Bearer ${o}`);let c=await n(a,{...i,headers:s});if(!c.ok)throw await Ls(c);return c}}},lu=e=>typeof e==`object`&&!!e&&`error`in e&&typeof e.error==`object`&&e.error!==null&&`code`in e.error&&`message`in e.error,uu=async e=>{let t=e.headers.get(`content-type`)?.includes(`json`)??!1?await e.clone().json():void 0;return lu(t)?new Ns({type:`urn:protobase:problem:${t.error.code}`,title:e.statusText||`Request failed`,status:e.status,detail:t.error.message}):Ls(e)},du=e=>{let t=e.url.replace(/\/+$/,``),n=e.fetch??((e,t)=>fetch(e,t)),r=async(r,i)=>{let a=await e.token(),o=await n(`${t}${r}`,{method:i,headers:{accept:`application/json`,...a&&{authorization:`Bearer ${a}`}}});if(!o.ok)throw await uu(o);return await o.json()};return{status:()=>r(``,`GET`),update:()=>r(`/update`,`POST`)}},V=(...e)=>e.filter(Boolean).join(` `),fu=e=>(0,o.useSyncExternalStore)(t=>{let n=window.matchMedia(e);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)},()=>window.matchMedia(e).matches,()=>!1),pu=()=>fu(`(min-width: 768px)`),mu=()=>fu(`not all and (min-width: 640px)`),H=t(a(),1),hu=e=>e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey,gu=`flex min-h-[49px] min-w-0 flex-1 flex-col items-center justify-center gap-1 pb-1 pt-1.5 text-[10px] font-medium leading-none`,_u=({tabs:e,onNavigate:t,onMore:n,moreOpen:r,moreControls:i,sticky:a,ref:o})=>{let s=!e.some(e=>e.active);return(0,H.jsxs)(`nav`,{ref:o,"aria-label":`Tabs`,className:V(`flex shrink-0 border-t bg-background pb-[env(safe-area-inset-bottom)] md:hidden`,a&&`sticky bottom-0 z-30`),children:[e.map(e=>{let n=e.icon;return(0,H.jsxs)(`a`,{href:e.href,"aria-current":e.active?`page`:void 0,...e.external?{target:`_blank`,rel:`noreferrer`}:{},onClick:n=>{!e.external&&t&&hu(n)&&(n.preventDefault(),t(e.href))},className:V(gu,e.active?`text-primary-text`:`text-muted-foreground`),children:[(0,H.jsx)(n,{className:`size-6`,strokeWidth:e.active?2.2:1.9,"aria-hidden":!0}),(0,H.jsx)(`span`,{className:`max-w-full truncate px-0.5`,children:e.label})]},e.id)}),(0,H.jsxs)(`button`,{type:`button`,"aria-expanded":r,"aria-controls":i,"data-current":s||void 0,onClick:n,className:V(gu,s?`text-primary-text`:`text-muted-foreground`),children:[(0,H.jsx)(Ke,{className:`size-6`,strokeWidth:s?2.2:1.9,"aria-hidden":!0}),`More`]})]})},vu=`data-pb-scroll-locked`,yu=()=>{let{body:e,documentElement:t}=document,n=e.style.overflow,r=t.hasAttribute(vu);return window.innerWidth>t.clientWidth&&t.setAttribute(vu,``),e.style.overflow=`hidden`,()=>{e.style.overflow=n,r||t.removeAttribute(vu)}},bu=`a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`,xu=[],Su=(e,t,n)=>{let r=(0,o.useRef)(n);r.current=n,(0,o.useEffect)(()=>{if(!t||!e.current)return;let n=e.current,i=document.activeElement instanceof HTMLElement?document.activeElement:null,a=yu(),o={};xu.push(o);let s=()=>[...n.querySelectorAll(bu)];(s()[0]??n).focus();let c=e=>{if(xu.at(-1)!==o)return;if(e.key===`Escape`)return r.current();if(e.key!==`Tab`)return;let t=s();if(t.length===0)return e.preventDefault();let i=t[0],a=t[t.length-1];e.shiftKey&&document.activeElement===i?(e.preventDefault(),a.focus()):!e.shiftKey&&document.activeElement===a?(e.preventDefault(),i.focus()):n.contains(document.activeElement)||(e.preventDefault(),i.focus())};return document.addEventListener(`keydown`,c),()=>{document.removeEventListener(`keydown`,c),xu.splice(xu.indexOf(o),1),a(),i?.focus()}},[t,e])},Cu=({id:e,open:t,onClose:n,children:r})=>{let i=(0,o.useRef)(null);return Su(i,t,n),t?(0,H.jsxs)(`div`,{className:`fixed inset-0 z-50 md:hidden`,children:[(0,H.jsx)(`div`,{className:`absolute inset-0 bg-backdrop/40`,onClick:n,"aria-hidden":!0}),(0,H.jsx)(`div`,{ref:i,id:e,role:`dialog`,"aria-modal":`true`,"aria-label":`Navigation`,tabIndex:-1,className:`absolute inset-y-0 left-0 flex w-60 max-w-[85vw] bg-sidebar shadow-pop outline-none`,onClick:e=>e.target.closest(`a`)&&n(),children:r})]}):null},wu=(0,o.createContext)(()=>{}),Tu=e=>{let t=(0,o.useContext)(wu);(0,o.useLayoutEffect)(()=>(t(e),()=>t(void 0)),[t,e])},Eu=e=>{(0,o.useLayoutEffect)(()=>{if(!e)return;let t=document.documentElement;return t.style.setProperty(`scrollbar-gutter`,`stable`),()=>{t.style.removeProperty(`scrollbar-gutter`)}},[e])},Du=[`--pb-sticky-top`,`--pb-sticky-bottom`,`scroll-padding-top`,`scroll-padding-bottom`],Ou=(e,t,n,r)=>{(0,o.useLayoutEffect)(()=>{if(!e)return;let r=document.documentElement,i=()=>{let e=`${t.current?.offsetHeight??0}px`,i=`${n.current?.offsetHeight??0}px`;r.style.setProperty(`--pb-sticky-top`,e),r.style.setProperty(`--pb-sticky-bottom`,i),r.style.setProperty(`scroll-padding-top`,e),r.style.setProperty(`scroll-padding-bottom`,i)},a=new ResizeObserver(i);for(let e of[t.current,n.current])e&&a.observe(e);return i(),()=>{a.disconnect();for(let e of Du)r.style.removeProperty(e)}},[e,t,n,r])},ku=({className:e})=>(0,H.jsx)(`span`,{className:V(`block h-3 rounded bg-muted [animation:pb-shimmer_1.4s_ease-in-out_infinite]`,e)}),Au=e=>e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey,ju=({parts:e,onNavigate:t})=>(0,H.jsx)(`nav`,{"aria-label":`Breadcrumb`,className:`flex min-w-0 items-center gap-1.5`,children:e.map((n,r)=>{let i=r===e.length-1,{label:a,href:o,loading:s}=typeof n==`string`?{label:n,href:void 0,loading:!1}:n,c=s?(0,H.jsx)(ku,{className:`w-24`}):a,l=V(`truncate`,i?`font-semibold`:`text-muted-foreground`);return(0,H.jsxs)(`span`,{className:V(`min-w-0 items-center gap-1.5`,i?`flex`:`hidden md:flex`),children:[r>0&&(0,H.jsx)(xe,{className:`hidden size-3.5 shrink-0 text-faint-foreground md:block`}),o?(0,H.jsx)(`a`,{href:o,"aria-current":i?`page`:void 0,"aria-label":s?a:void 0,"aria-busy":s||void 0,onClick:e=>{t&&Au(e)&&(e.preventDefault(),t(o))},className:V(l,`rounded-sm hover:text-foreground hover:underline`),children:c}):(0,H.jsx)(`span`,{className:l,"aria-label":s?a:void 0,"aria-busy":s||void 0,children:c})]},`${r}-${a}`)})}),Mu=({to:e,onClick:t,...n})=>(0,H.jsx)(`a`,{href:e.href,onClick:n=>{t?.(n),!n.defaultPrevented&&Au(n)&&(n.preventDefault(),e.onFollow())},...n}),Nu=`M312.3 9.9Q257 9.9 217.1 -21.1Q177.3 -52.1 168.4 -108.8L181.1 -110.3V205H54.8V-510H176.7V-404.5L168.3 -407Q179.7 -460.8 221.2 -490.4Q262.7 -520 319.8 -520Q376.2 -520 417 -488.4Q457.8 -456.8 479.8 -398.6Q501.8 -340.5 501.8 -259.9Q501.8 -177.6 478.3 -116.8Q454.9 -55.9 412.5 -23Q370.1 9.9 312.3 9.9ZM274.4 -92.6Q320.2 -92.6 345.8 -133.8Q371.4 -175.1 371.4 -256.4Q371.4 -337.7 345.7 -377.6Q320.1 -417.5 274 -417.5Q228.6 -417.5 202.7 -376.4Q176.9 -335.3 176.9 -254Q176.9 -173.3 202.7 -132.9Q228.4 -92.6 274.4 -92.6Z M549.8 0V-510H671.7V-388.3H676.1V0H549.8ZM676.1 -286.5 661.3 -386.2Q677.9 -455.2 711.8 -487.6Q745.7 -520 794.3 -520Q809 -520 818 -516.6V-394.2Q814.2 -395.6 807.1 -396.1Q800 -396.6 789.4 -396.6Q734.6 -396.6 705.3 -370.5Q676.1 -344.4 676.1 -286.5Z M1043.8 10Q974.7 10 922.6 -23.6Q870.6 -57.2 842.1 -117.5Q813.6 -177.8 813.6 -257Q813.6 -336.5 842.2 -395.5Q870.8 -454.5 922.5 -487.2Q974.2 -520 1043.8 -520Q1113.7 -520 1165.4 -487.2Q1217.1 -454.5 1245.6 -395.5Q1274 -336.5 1274 -257Q1274 -177.8 1245.5 -117.5Q1217 -57.2 1165.3 -23.6Q1113.6 10 1043.8 10ZM1043.8 -90.5Q1073.5 -90.5 1095.9 -108.9Q1118.2 -127.3 1130.9 -164.4Q1143.6 -201.5 1143.6 -257.5Q1143.6 -339.8 1116 -379.7Q1088.4 -419.5 1043.8 -419.5Q999.3 -419.5 971.6 -379.5Q944 -339.5 944 -257.5Q944 -201.5 956.7 -164.4Q969.4 -127.3 991.8 -108.9Q1014.3 -90.5 1043.8 -90.5Z M1509 10.2Q1427.2 10.2 1387.6 -29.2Q1348 -68.6 1348 -147.7V-613.8L1474.2 -666.1V-146.7Q1474.2 -118.4 1489.9 -104.3Q1505.6 -90.3 1539.2 -90.3Q1552 -90.3 1562.7 -92.5Q1573.3 -94.8 1582.5 -98.7V-1.9Q1571.6 4 1552 7.1Q1532.4 10.2 1509 10.2ZM1270.1 -411V-510H1580.6V-411H1270.1Z M1810.8 10Q1741.7 10 1689.6 -23.6Q1637.6 -57.2 1609.1 -117.5Q1580.6 -177.8 1580.6 -257Q1580.6 -336.5 1609.2 -395.5Q1637.8 -454.5 1689.5 -487.2Q1741.2 -520 1810.8 -520Q1880.7 -520 1932.4 -487.2Q1984.1 -454.5 2012.6 -395.5Q2041 -336.5 2041 -257Q2041 -177.8 2012.5 -117.5Q1984 -57.2 1932.3 -23.6Q1880.6 10 1810.8 10ZM1810.8 -90.5Q1840.5 -90.5 1862.9 -108.9Q1885.2 -127.3 1897.9 -164.4Q1910.6 -201.5 1910.6 -257.5Q1910.6 -339.8 1883 -379.7Q1855.4 -419.5 1810.8 -419.5Q1766.3 -419.5 1738.6 -379.5Q1711 -339.5 1711 -257.5Q1711 -201.5 1723.7 -164.4Q1736.4 -127.3 1758.8 -108.9Q1781.3 -90.5 1810.8 -90.5Z M2343.3 9.9Q2288 9.9 2247.7 -21.1Q2207.4 -52.1 2198.5 -108.8L2205.8 -110.3V0H2085.8V-720H2212.1V-404.5L2203.7 -407Q2215.1 -460.8 2255.6 -490.4Q2296.2 -520 2351 -520Q2407.3 -520 2448 -488.4Q2488.8 -456.8 2510.8 -398.6Q2532.8 -340.5 2532.8 -259.9Q2532.8 -177.6 2509.3 -116.8Q2485.9 -55.9 2443.5 -23Q2401.1 9.9 2343.3 9.9ZM2305.4 -92.6Q2350.7 -92.6 2376.6 -133.8Q2402.4 -175.1 2402.4 -256.4Q2402.4 -337.7 2376.5 -377.6Q2350.6 -417.5 2305 -417.5Q2260.5 -417.5 2234.2 -376.4Q2207.9 -335.3 2207.9 -254Q2207.9 -173.3 2234.1 -132.9Q2260.3 -92.6 2305.4 -92.6Z M2834 0Q2828 -19.1 2825.7 -41.7Q2823.3 -64.2 2823.3 -91.8H2818.6V-356Q2818.6 -391.9 2803.1 -409.1Q2787.5 -426.3 2756.2 -426.3Q2724.2 -426.3 2706.4 -408.7Q2688.7 -391.2 2686.3 -358.9H2571.2Q2574.6 -429.6 2625.4 -474.8Q2676.1 -520 2763.5 -520Q2850.2 -520 2896.1 -476.5Q2941.9 -432.9 2941.9 -352.2V-91.8Q2941.9 -69.5 2944.7 -46.7Q2947.5 -23.8 2954.1 0H2834ZM2690.6 10Q2631.9 10 2595.4 -26.3Q2558.9 -62.5 2558.9 -124.5Q2558.9 -185 2594.3 -224Q2629.8 -263 2704.5 -287.6L2845.4 -337.4V-248.7L2753.4 -219.3Q2716.5 -206.1 2699.3 -186.6Q2682.2 -167.2 2682.2 -139Q2682.2 -112.4 2697.5 -98.4Q2712.9 -84.3 2739.4 -84.3Q2773.2 -84.3 2795.9 -104.1Q2818.6 -123.9 2818.6 -153.1L2829.9 -85.8Q2812.6 -37.4 2776.8 -13.7Q2741 10 2690.6 10Z M3168 10Q3080.6 10 3030.1 -34.2Q2979.6 -78.4 2974.7 -158.1H3082.4Q3086.3 -120 3108.9 -100.5Q3131.5 -80.9 3169.8 -80.9Q3202 -80.9 3218.9 -93.9Q3235.8 -106.9 3235.8 -131.3Q3235.8 -151.1 3224.3 -165.6Q3212.9 -180.1 3178.9 -195.4L3111.2 -224.8Q3053 -247.7 3023.8 -284.2Q2994.5 -320.8 2994.5 -373.9Q2994.5 -440.1 3040.1 -480Q3085.7 -520 3162.8 -520Q3242.2 -520 3288.4 -480Q3334.6 -440 3339.5 -367.9H3231.8Q3228.6 -399.7 3211.3 -414.4Q3194 -429.1 3164 -429.1Q3136.1 -429.1 3120.5 -417Q3104.8 -405 3104.8 -382.7Q3104.8 -364.2 3117.7 -349.8Q3130.6 -335.5 3162.4 -321.6L3236.6 -289.6Q3288.6 -269.2 3317.4 -229.2Q3346.1 -189.1 3346.1 -136.9Q3346.1 -69 3299.2 -29.5Q3252.3 10 3168 10Z M3587.8 10Q3520 10 3469.2 -23.3Q3418.5 -56.6 3390.5 -116.5Q3362.6 -176.3 3362.6 -255.8Q3362.6 -336.4 3390.9 -395.7Q3419.3 -454.9 3470.7 -487.5Q3522 -520 3591.1 -520Q3656.6 -520 3702.7 -489.8Q3748.8 -459.7 3773.7 -403.1Q3798.6 -346.5 3798.6 -266.5Q3798.6 -253.7 3798 -242.5Q3797.5 -231.3 3795.8 -221.4H3440V-306.9H3709L3681.8 -277.9Q3681.6 -355.2 3657.7 -390.7Q3633.8 -426.3 3589.3 -426.3Q3541.7 -426.3 3515.6 -384Q3489.5 -341.7 3489.5 -255Q3489.5 -168.4 3515 -126.1Q3540.5 -83.7 3590.6 -83.7Q3623.7 -83.7 3644.6 -102Q3665.5 -120.3 3673.8 -156.3H3788.9Q3772.2 -81.6 3721.5 -35.8Q3670.8 10 3587.8 10Z`,Pu=`fill-[#ff5a1f] dark:fill-[#ff6a33]`,Fu=`fill-[#14161a] dark:fill-[#f1f0ea]`,Iu=({className:e})=>(0,H.jsxs)(`svg`,{viewBox:`0 0 32 32`,className:V(`size-7 shrink-0`,e),"aria-hidden":!0,children:[(0,H.jsx)(`path`,{className:Pu,fillRule:`evenodd`,d:`M0 5a5 5 0 0 1 5-5h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2zM4 5a1 1 0 0 1 1-1h5v6H4z`}),(0,H.jsx)(`path`,{className:Fu,d:`M17 0h10a5 5 0 0 1 5 5v22a5 5 0 0 1-5 5H5a5 5 0 0 1-5-5V17h17z`})]}),Lu=({className:e})=>(0,H.jsx)(`svg`,{viewBox:`54.8 -720 3743.8 925`,className:V(`h-3.5 w-auto`,e),role:`img`,"aria-label":`Protobase`,children:(0,H.jsx)(`path`,{className:Fu,d:Nu})}),Ru=({compact:e,workspace:t})=>(0,H.jsxs)(`div`,{className:`flex items-center gap-2.5 overflow-hidden`,children:[(0,H.jsx)(Iu,{}),!e&&(0,H.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5 leading-tight`,children:[(0,H.jsx)(Lu,{className:`self-start`}),t&&(0,H.jsx)(`div`,{className:`truncate text-[11px] text-muted-foreground`,children:t})]})]}),zu=[{label:`Sales`,items:[{id:`orders`,label:`Orders`,icon:bn,count:12},{id:`customers`,label:`Customers`,icon:le},{id:`invoices`,label:`Invoices`,icon:it,count:3}]},{label:`Inventory`,items:[{id:`products`,label:`Products`,icon:Xt},{id:`stock-moves`,label:`Stock moves`,icon:se},{id:`warehouses`,label:`Warehouses`,icon:Xn},{id:`shipments`,label:`Shipments`,icon:Hn}]},{label:`Finance`,items:[{id:`payments`,label:`Payments`,icon:ze},{id:`credit-notes`,label:`Credit notes`,icon:sn},{id:`reports`,label:`Reports`,icon:pe}]},{label:`Admin`,items:[{id:`users`,label:`Users`,icon:qn},{id:`settings`,label:`Settings`,icon:gn}]}],Bu={xs:`size-5 text-[9px]`,sm:`size-6 text-[10px]`,md:`size-8 text-xs`},Vu=({initials:e,hue:t,size:n=`sm`,className:r})=>(0,H.jsx)(`span`,{className:V(`inline-flex shrink-0 select-none items-center justify-center rounded-full font-semibold text-white ring-2 ring-background`,Bu[n],r),style:{background:`oklch(0.58 0.13 ${t})`},children:e}),Hu=({people:e,size:t=`sm`})=>(0,H.jsx)(`span`,{className:`inline-flex -space-x-1`,children:e.map(e=>(0,H.jsx)(Vu,{...e,size:t},e.initials))}),Uu=e=>{let t=e.slice(1),n=t.length===3?[...t].map(e=>e+e).join(``):t,[r,i,a]=[0,2,4].map(e=>{let t=Number.parseInt(n.slice(e,e+2),16)/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},Wu=`#ffffff`,Gu=`#111827`,Ku=e=>{let t=Uu(e);return 1.05/(t+.05)>=(t+.05)/(Uu(Gu)+.05)?Wu:Gu},qu={neutral:`bg-muted text-muted-foreground`,blue:`bg-primary-soft text-primary-text`,green:`bg-success-soft text-success-text`,amber:`bg-warning-soft text-warning-text`,red:`bg-danger-soft text-danger-text`,violet:`bg-violet-soft text-violet-text`},Ju={neutral:`bg-faint-foreground`,blue:`bg-primary`,green:`bg-success`,amber:`bg-warning`,red:`bg-danger`,violet:`bg-violet`},Yu=`polygon(0 0, calc(100% - 0.625rem) 0, 100% 50%, calc(100% - 0.625rem) 100%, 0 100%)`,Xu=({tone:e=`neutral`,dot:t=!0,color:n,shape:r,children:i,className:a})=>(0,H.jsxs)(`span`,{style:{...n!==void 0&&{backgroundColor:n,color:Ku(n)},...r===`arrow`&&{clipPath:Yu}},className:V(r===`arrow`?`inline-flex h-5 items-center gap-1.5 rounded-l-sm pr-4 pl-2 text-xs font-semibold whitespace-nowrap`:`inline-flex h-5 items-center gap-1.5 rounded-full px-2 text-xs font-medium whitespace-nowrap`,n===void 0&&qu[e],a),children:[t&&n===void 0&&r===void 0&&(0,H.jsx)(`span`,{className:V(`size-1.5 rounded-full`,Ju[e])}),i]}),Zu=({label:e,current:t,others:n,rowClassName:r,onSwitch:i})=>(0,H.jsxs)(`div`,{className:`border-b py-1`,role:`group`,"aria-label":e,children:[t&&(0,H.jsxs)(`div`,{className:V(r,`text-foreground hover:bg-transparent`),"aria-current":`true`,children:[(0,H.jsx)(he,{className:`size-4`}),(0,H.jsx)(`span`,{className:`truncate`,children:t.label})]}),n.map(e=>(0,H.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>i(e.id),className:r,children:[(0,H.jsx)(`span`,{className:`size-4`}),(0,H.jsx)(`span`,{className:`truncate`,children:e.label})]},e.id))]}),Qu={sm:{group:`h-7`,option:`px-2.5 text-xs`},md:{group:`h-8`,option:`px-3 text-body`}},$u=({value:e,options:t,onChange:n,label:r,size:i=`sm`,iconOnly:a=!1})=>(0,H.jsx)(`span`,{role:`group`,"aria-label":r,className:V(`inline-flex`,Qu[i].group,`rounded-md bg-muted p-0.5`),children:t.map(t=>(0,H.jsxs)(`button`,{type:`button`,"aria-pressed":t.value===e,...a&&{"aria-label":t.label,title:t.label},onClick:()=>n(t.value),className:V(`inline-flex items-center gap-1.5 rounded`,Qu[i].option,`font-medium transition-colors`,t.value===e?`bg-background text-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`),children:[t.icon&&(0,H.jsx)(t.icon,{className:`size-3.5`}),!a&&t.label]},t.value))}),ed=[{value:`light`,label:`Light`,icon:An},{value:`dark`,label:`Dark`,icon:Kt},{value:`system`,label:`System`,icon:Wt}],td=({theme:e,className:t})=>(0,H.jsxs)(`div`,{className:t,children:[(0,H.jsx)(On,{className:`size-4`}),(0,H.jsx)(`span`,{className:`flex-1`,children:`Theme`}),(0,H.jsx)($u,{label:`Theme`,iconOnly:!0,value:e.preference,options:ed,onChange:e.onChange})]}),nd=`flex min-h-11 w-full items-center gap-2.5 px-3 py-1.5 text-left text-muted-foreground hover:bg-muted md:min-h-0`,rd=({user:e,compact:t,open:n,items:r=[],onNavigate:i,onSignOut:a,organizations:s,roles:c,theme:l})=>{let u=c?.roles.find(e=>e.name===c.active),[d,f]=(0,o.useState)(!1),p=n??d,m=(0,o.useRef)(null),[h,g]=(0,o.useState)();return(0,o.useEffect)(()=>{if(!p||n!==void 0)return;let e=e=>{(e instanceof KeyboardEvent?e.key===`Escape`:!m.current?.contains(e.target))&&f(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,e)}},[p,n]),(0,H.jsxs)(`div`,{ref:m,className:`relative`,children:[(0,H.jsxs)(`button`,{type:`button`,className:`flex min-h-11 w-full items-center gap-2.5 rounded-md p-1 text-left hover:bg-muted md:min-h-0`,"aria-label":`Profile menu`,"aria-haspopup":`menu`,"aria-expanded":p,onClick:()=>{let e=m.current?.getBoundingClientRect();e&&g({left:e.left,bottom:window.innerHeight-e.top+8}),f(!d)},children:[(0,H.jsx)(Vu,{initials:e.initials,hue:e.hue,size:`md`,className:`ring-0`}),!t&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`span`,{className:`min-w-0 flex-1 leading-tight`,children:[(0,H.jsx)(`span`,{className:`block truncate font-medium`,children:e.name}),(0,H.jsx)(Xu,{tone:e.roleTone,dot:!1,className:`mt-0.5 h-4 px-1.5 text-[10px]`,children:e.role})]}),(0,H.jsx)(Ce,{className:`size-3.5 shrink-0 text-faint-foreground`})]})]}),p&&(0,H.jsxs)(`div`,{role:`menu`,className:n===void 0?`fixed z-[60] w-56 overflow-hidden rounded-lg border bg-background py-1 shadow-pop`:`absolute bottom-full left-0 z-50 mb-2 w-56 overflow-hidden rounded-lg border bg-background py-1 shadow-pop`,style:n===void 0&&h?{left:h.left,bottom:h.bottom}:void 0,children:[(0,H.jsxs)(`div`,{className:`border-b px-3 pb-2 pt-1.5`,children:[(0,H.jsx)(`div`,{className:`font-medium`,children:e.name}),(0,H.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:e.email})]}),s&&(s.current||s.others.length>0)&&(0,H.jsx)(Zu,{label:`Organizations`,...s.current&&{current:{id:s.current.id,label:s.current.name}},others:s.others.map(({id:e,name:t})=>({id:e,label:t})),rowClassName:nd,onSwitch:e=>{f(!1),s.onSwitch(e)}}),c&&c.roles.length>1&&(0,H.jsx)(Zu,{label:`Roles`,...u&&{current:{id:u.name,label:u.label}},others:c.roles.filter(e=>e!==u).map(({name:e,label:t})=>({id:e,label:t})),rowClassName:nd,onSwitch:e=>{f(!1),c.onSwitch(e)}}),r.length>0&&(0,H.jsx)(`div`,{className:V((l||a)&&`border-b`),children:r.map(e=>{let t=e.icon;return(0,H.jsxs)(`a`,{role:`menuitem`,href:e.href,"aria-current":e.active?`page`:void 0,...e.external?{target:`_blank`,rel:`noreferrer`}:{},onClick:t=>{f(!1),!e.external&&i&&(t.preventDefault(),i(e.href))},className:V(nd,e.active&&`bg-muted text-foreground`),children:[(0,H.jsx)(t,{className:`size-4`}),e.label]},e.id)})}),l&&(0,H.jsx)(`div`,{className:V(a&&`border-b`),children:(0,H.jsx)(td,{theme:l,className:V(nd,`hover:bg-transparent`)})}),a&&(0,H.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:a,className:nd,children:[(0,H.jsx)(Lt,{className:`size-4`}),`Sign out`]})]})]})},id=(e,t)=>{try{return e()}catch(e){if(!(e instanceof DOMException))throw e;return t}},ad=`protobase:nav-open:`,od=e=>`${ad}${e}`,sd=(e,t)=>id(()=>e.getItem(t)!==`false`,!0),cd=(e,t,n)=>id(()=>n?e.removeItem(t):e.setItem(t,`false`),void 0),ld=({label:e,side:t=`right`,visible:n,children:r})=>(0,H.jsxs)(`span`,{className:`group/tooltip relative inline-flex`,children:[r,(0,H.jsx)(`span`,{role:`tooltip`,className:V(`pointer-events-none absolute z-50 whitespace-nowrap rounded-md bg-foreground px-2 py-1 text-xs font-medium text-background opacity-0 shadow-md transition-opacity group-hover/tooltip:opacity-100`,n&&`opacity-100`,t===`right`&&`left-full top-1/2 ml-2 -translate-y-1/2`,t===`top`&&`bottom-full left-1/2 mb-2 -translate-x-1/2`,t===`bottom`&&`left-1/2 top-full mt-2 -translate-x-1/2`),children:e})]}),ud=e=>e===`text-large`||e===`text-small`||e===`icon-expand`,dd=e=>e===`text-large`||e===`text-small`,fd={"text-large":`w-60`,"text-small":`w-52`,icon:`w-14`,"icon-label":`w-[76px]`,"icon-tooltip":`w-14`,"icon-expand":`w-14`},pd={"text-large":`h-9 gap-3 px-3 text-sm`,"text-small":`h-7 gap-2.5 px-2.5 text-xs`,icon:`size-9 justify-center`,"icon-label":`w-full flex-col gap-0.5 py-1.5 text-[10px]`,"icon-tooltip":`size-9 justify-center`,"icon-expand":`h-8 gap-3 px-3`},md=({item:e,mode:t,active:n,onNavigate:r,className:i})=>{let a=e.icon,o=(0,H.jsxs)(`a`,{onClick:r&&(t=>{t.preventDefault(),r(e.href??`#${e.id}`)}),href:e.href??`#${e.id}`,"aria-label":e.problem?`${e.label}: ${e.problem}`:e.label,"aria-current":n?`page`:void 0,title:e.problem,className:V(`flex shrink-0 items-center rounded-md font-medium transition-colors`,pd[t],n?`bg-primary-soft text-primary-text`:`text-muted-foreground hover:bg-muted hover:text-foreground`,i),children:[(0,H.jsx)(a,{className:V(`shrink-0`,t===`text-small`?`size-4`:`size-[18px]`),strokeWidth:n?2.2:1.9}),(ud(t)||t===`icon-label`)&&(0,H.jsx)(`span`,{className:`whitespace-nowrap`,children:e.label}),dd(t)&&e.count&&(0,H.jsx)(`span`,{className:`ml-auto rounded bg-muted px-1.5 text-[11px] tabular-nums text-muted-foreground`,children:e.count}),dd(t)&&e.problem&&(0,H.jsx)(Bn,{"aria-hidden":!0,className:`ml-auto size-3.5 shrink-0 text-warning-text`})]});return t===`icon-tooltip`?(0,H.jsx)(ld,{label:e.label,children:o}):o},hd={neutral:`bg-faint-foreground`,info:`bg-primary`,success:`bg-success`,warning:`bg-warning`,danger:`bg-danger`},gd=({tone:e,pulse:t=!1,className:n})=>(0,H.jsxs)(`span`,{"aria-hidden":!0,className:V(`relative flex size-2 shrink-0`,n),"data-tone":e,"data-pulse":t||void 0,children:[t&&(0,H.jsx)(`span`,{className:V(`absolute inset-0 animate-ping rounded-full opacity-60 motion-reduce:animate-none`,hd[e])}),(0,H.jsx)(`span`,{className:V(`relative size-2 rounded-full`,hd[e])})]}),_d={"text-large":`h-8 gap-2.5 px-2.5`,"text-small":`h-7 gap-2 px-2 text-xs`},vd={"text-large":`ml-[20px]`,"text-small":`ml-[17px]`},yd=({item:e,recent:t,mode:n,active:r,onNavigate:i})=>{let a=od(e.id),[s,c]=(0,o.useState)(()=>sd(localStorage,a)),l=(0,o.useId)(),u=e.href??`#${e.id}`,d=()=>{cd(localStorage,a,!s),c(!s)},f=e=>({href:e,onClick:i&&(t=>{t.preventDefault(),i(e)})});return(0,H.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,H.jsxs)(`div`,{className:`relative`,children:[(0,H.jsx)(md,{item:e,mode:n,active:r,onNavigate:i,className:`pr-8`}),(0,H.jsx)(`button`,{type:`button`,"aria-expanded":s,"aria-controls":l,"aria-label":`Recent ${e.label.toLowerCase()}`,onClick:d,className:`absolute right-1 top-1/2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground`,children:(0,H.jsx)(xe,{className:V(`size-3.5 transition-transform`,s&&`rotate-90`)})})]}),s&&(0,H.jsxs)(`ul`,{id:l,"aria-label":`Recent ${e.label.toLowerCase()}`,className:V(`flex flex-col gap-0.5 border-l pl-1.5`,vd[n]),children:[t.state===`loading`&&(0,H.jsx)(`li`,{className:V(`flex items-center text-faint-foreground`,_d[n]),children:`Loading...`}),t.state===`error`&&(0,H.jsx)(`li`,{className:V(`flex items-center text-faint-foreground`,_d[n]),children:`Could not load`}),t.state===`ready`&&t.records.map(e=>(0,H.jsx)(`li`,{children:(0,H.jsxs)(`a`,{...f(e.href),"aria-label":`${e.label}, ${e.status}`,title:`${e.label} (${e.status})`,"aria-current":e.active?`page`:void 0,className:V(`flex min-w-0 items-center rounded-md font-medium transition-colors`,_d[n],e.active?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),children:[(0,H.jsx)(gd,{tone:e.tone,pulse:e.pulse}),(0,H.jsx)(`span`,{className:`truncate`,children:e.label})]})},e.id)),(0,H.jsx)(`li`,{children:(0,H.jsx)(`a`,{...f(u),className:V(`flex items-center rounded-md text-faint-foreground transition-colors hover:bg-muted hover:text-foreground`,_d[n]),children:`View all`})})]})]})},bd=({mode:e,activeItem:t,user:n,workspace:r,forceExpanded:i,profileMenuOpen:a,groups:o=zu,userMenu:s,onNavigate:c,onSignOut:l,signIn:u,organizations:d,roles:f,theme:p,sticky:m,logo:h=Ru})=>{let g=e===`icon-expand`,_=g&&i,v=dd(e)||g;return(0,H.jsx)(`nav`,{"aria-label":`Resources`,className:V(m?`sticky top-0 h-dvh self-start`:`relative`,`z-30 shrink-0`,fd[e]),children:(0,H.jsxs)(`div`,{className:V(`group/side absolute inset-y-0 left-0 flex flex-col overflow-hidden border-r bg-sidebar`,g?`w-14 transition-[width,box-shadow] duration-150 hover:w-60 hover:shadow-pop focus-within:w-60 focus-within:shadow-pop`:`w-full`,_&&`w-60 shadow-pop`),children:[(0,H.jsx)(`div`,{className:V(`flex h-12 shrink-0 items-center px-3.5`,e===`icon-label`&&`justify-center px-0`),children:(0,H.jsx)(h,{compact:!v,workspace:r})}),(0,H.jsx)(`div`,{className:V(`flex-1 overflow-y-auto overflow-x-hidden pb-2`,`px-2`),children:o.map((n,r)=>(0,H.jsxs)(`div`,{className:V(`flex flex-col gap-0.5`,r>0&&`mt-3`),children:[v?(0,H.jsx)(`div`,{className:V(`px-3 pb-1 pt-1 text-[11px] font-medium uppercase tracking-wide text-faint-foreground`,g&&`h-4 whitespace-nowrap py-0 opacity-0 transition-opacity group-hover/side:opacity-100 group-focus-within/side:opacity-100`,_&&`opacity-100`),children:n.label}):r>0&&(0,H.jsx)(`div`,{className:`mx-auto mb-1 h-px w-6 bg-border`}),n.items.map(n=>n.recent&&dd(e)?(0,H.jsx)(yd,{item:n,recent:n.recent,mode:e,active:n.id===t,onNavigate:c},n.id):(0,H.jsx)(md,{item:n,mode:e,active:n.id===t,onNavigate:c},n.id))]},n.label))}),(0,H.jsx)(`div`,{className:V(`shrink-0 border-t p-2`,e!==`text-large`&&e!==`text-small`&&!g&&`flex justify-center`),children:n?(0,H.jsx)(rd,{user:n,compact:!v,open:a,items:s,onNavigate:c,onSignOut:l,organizations:d,roles:f,theme:p}):(0,H.jsxs)(H.Fragment,{children:[p&&v&&(0,H.jsx)(td,{theme:p,className:`flex min-h-11 w-full items-center gap-2.5 whitespace-nowrap p-1.5 text-muted-foreground md:min-h-0`}),u&&(0,H.jsxs)(Mu,{to:u,"aria-label":`Sign in`,className:`flex min-h-11 w-full items-center gap-2.5 rounded-md p-1.5 text-left font-medium text-muted-foreground hover:bg-muted hover:text-foreground md:min-h-0`,children:[(0,H.jsx)(Ft,{className:`size-4 shrink-0`}),v&&(0,H.jsx)(`span`,{className:`whitespace-nowrap`,children:`Sign in`})]})]})})]})})},xd=e=>{let t=e.at(-2);if(typeof t==`object`&&t.href&&!t.loading)return{label:t.label,href:t.href}},Sd=(0,o.createContext)(void 0),Cd=()=>{let e=(0,o.useContext)(Sd);return e?{id:e.id,name:e.name,"aria-describedby":e.describedBy,"aria-invalid":e.invalid||void 0,"aria-required":e.required||void 0}:{}},wd=({leading:e,trailing:t,invalid:n,className:r,wrapperClassName:i,...a})=>{let o=Cd();return(0,H.jsxs)(`span`,{className:V(`flex h-8 items-center gap-2 rounded-md border bg-background px-2.5 text-muted-foreground shadow-sm focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20`,n?`border-danger`:`border-border-strong`,i),children:[e,(0,H.jsx)(`input`,{className:V(`min-w-0 flex-1 bg-transparent text-body text-foreground outline-none placeholder:text-faint-foreground`,r),...o,...n&&{"aria-invalid":!0},...a}),t]})},Td=({children:e})=>(0,H.jsx)(`kbd`,{className:`inline-flex h-5 items-center rounded border border-border-strong bg-background px-1.5 font-sans text-[11px] font-medium text-muted-foreground`,children:e}),Ed=({className:e})=>(0,H.jsx)(jt,{"aria-label":`Loading`,className:V(`size-4 animate-spin`,e)}),Dd=(e,t,n)=>t===0?-1:e<0?n===1?0:t-1:(e+n+t)%t,Od=e=>e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0,kd=({search:e,className:t=`w-96`,autoFocus:n,showShortcut:r=!0,ref:i})=>{let a=(0,o.useId)(),s=(0,o.useRef)(null),[c,l]=(0,o.useState)(!1),[u,d]=(0,o.useState)(-1),f=e.groups.flatMap(e=>e.hits),p=c&&(e.query!==``||e.loading),m=e=>`${a}-${e}`,h=e=>{s.current=e,typeof i==`function`?i(e):i&&(i.current=e)},g=t=>{e.onSelect(t),d(-1),s.current?.blur()},_=()=>{e.onTextChange(``),d(-1),s.current?.focus()},v=t=>{if(t.key===`ArrowDown`||t.key===`ArrowUp`)t.preventDefault(),d(e=>Dd(e,f.length,t.key===`ArrowDown`?1:-1));else if(t.key===`Enter`){let e=f[u]??f[0];if(!e)return;t.preventDefault(),g(e.href)}else t.key===`Escape`&&(e.text?e.onTextChange(``):t.currentTarget.blur(),d(-1))},y=-1;return(0,H.jsxs)(`div`,{className:V(`relative`,t),children:[(0,H.jsx)(wd,{ref:h,wrapperClassName:`w-full bg-surface shadow-none`,leading:e.loading?(0,H.jsx)(Ed,{className:`size-4`}):(0,H.jsx)(fn,{className:`size-4`}),trailing:e.text?(0,H.jsx)(`button`,{type:`button`,"aria-label":`Clear search`,className:`-mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground`,onMouseDown:e=>e.preventDefault(),onClick:_,children:(0,H.jsx)(Qn,{className:`size-3.5`})}):r?(0,H.jsx)(`span`,{className:`hidden md:inline-flex`,children:(0,H.jsx)(Td,{children:`⌘K`})}):void 0,placeholder:e.placeholder,"aria-label":`Global search`,role:`combobox`,"aria-autocomplete":`list`,"aria-expanded":p,"aria-controls":a,"aria-activedescendant":p&&f[u]?m(u):void 0,autoFocus:n,value:e.text,onChange:t=>{e.onTextChange(t.target.value),d(-1)},onFocus:()=>l(!0),onBlur:()=>l(!1),onKeyDown:v}),p&&(0,H.jsxs)(`div`,{id:a,role:`listbox`,"aria-label":`Search results`,className:`absolute right-0 top-full z-40 mt-1 max-h-96 w-full min-w-72 overflow-y-auto rounded-lg border bg-background py-1 shadow-pop`,children:[e.groups.length===0&&(0,H.jsx)(`p`,{className:`px-3 py-2 text-muted-foreground`,children:e.loading?`Searching`:`No matches for “${e.query}”`}),e.groups.map(e=>(0,H.jsxs)(`div`,{role:`group`,"aria-label":e.label,children:[(0,H.jsx)(`div`,{className:`px-3 pb-1 pt-2 text-[11px] font-medium uppercase tracking-wide text-faint-foreground`,children:e.label}),e.failed&&(0,H.jsxs)(`p`,{className:`px-3 py-1.5 text-danger-text`,children:[`Could not search `,e.label.toLowerCase()]}),e.hits.map(e=>{y+=1;let t=y;return(0,H.jsxs)(`a`,{id:m(t),href:e.href,tabIndex:-1,role:`option`,"aria-selected":t===u,className:V(`block px-3 py-1.5`,t===u?`bg-primary-soft text-primary-text`:`hover:bg-muted`),onMouseDown:e=>e.preventDefault(),onClick:t=>{Od(t)||(t.preventDefault(),g(e.href))},onMouseEnter:()=>d(t),children:[(0,H.jsx)(`span`,{className:`block truncate font-semibold`,children:e.title}),e.subtitle&&(0,H.jsx)(`span`,{className:V(`block truncate text-xs`,t===u?`text-primary-text/80`:`text-muted-foreground`),children:e.subtitle})]},e.id)})]},e.id))]})]})},Ad=`inline-flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted md:hidden`,jd=({breadcrumb:e,onNavigate:t,actions:n,onMenu:r,menuOpen:i,menuControls:a,search:s,sticky:c,ref:l})=>{let[u,d]=(0,o.useState)(!1),f=xd(e),p=(0,o.useRef)(null);return(0,o.useEffect)(()=>{if(!s)return;let e=e=>{if(e.key.toLowerCase()!==`k`||!(e.metaKey||e.ctrlKey))return;e.preventDefault();let t=p.current;t&&t.offsetParent!==null?t.focus():d(!0)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[s]),(0,H.jsxs)(`header`,{ref:l,className:V(c?`sticky top-0 z-30`:`relative`,`flex h-12 shrink-0 items-center gap-1 border-b bg-background pl-4 pr-2 md:gap-4 md:px-5`),children:[r&&(0,H.jsx)(`button`,{type:`button`,"aria-label":`Open navigation`,"aria-expanded":!!i,"aria-controls":a,onClick:r,className:V(Ad,`-ml-3`),children:(0,H.jsx)(ree,{className:`size-5`})}),f&&(0,H.jsx)(`a`,{href:f.href,"aria-label":`Back to ${f.label}`,onClick:e=>{t&&Au(e)&&(e.preventDefault(),t(f.href))},className:V(Ad,!r&&`-ml-3`),children:(0,H.jsx)(ye,{className:`size-5`})}),(0,H.jsx)(ju,{parts:e,onNavigate:t}),(0,H.jsxs)(`div`,{className:`ml-auto flex items-center gap-1 md:gap-3`,children:[s&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`div`,{className:`hidden md:block`,children:(0,H.jsx)(kd,{ref:p,search:s})}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Search`,"aria-expanded":u,onClick:()=>d(!0),className:Ad,children:(0,H.jsx)(fn,{className:`size-5`})})]}),n]}),s&&u&&(0,H.jsxs)(`div`,{className:`absolute inset-0 z-20 flex items-center gap-1 bg-background px-3 md:hidden`,children:[(0,H.jsx)(kd,{className:`min-w-0 flex-1`,autoFocus:!0,showShortcut:!1,search:{...s,onSelect:e=>{s.onSelect(e),d(!1)}}}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Close search`,onClick:()=>d(!1),className:Ad,children:(0,H.jsx)(Qn,{className:`size-5`})})]})]})},Md=`app-drawer`,Nd=({sidebarMode:e,activeItem:t,breadcrumb:n,user:r,workspace:i,logo:a,actions:s,rightPanel:c,forceExpanded:l,profileMenuOpen:u,navGroups:d,userMenu:f,bottomBar:p,onNavigate:m,onSignOut:h,signIn:g,organizations:_,roles:v,theme:y,search:b,pageScroll:x=!1,className:S,children:C})=>{let w=pu(),[T,E]=(0,o.useState)(!1);(0,o.useEffect)(()=>{w&&E(!1)},[w]);let D=!w&&p&&p.length>0?p:void 0,[O,k]=(0,o.useState)(),A=O??x,j=(0,o.useRef)(null),M=(0,o.useRef)(null);Ou(A,j,M,!!D),Eu(A);let N=(e,n=!1)=>(0,H.jsx)(bd,{mode:e,sticky:n,activeItem:t,user:r,workspace:i,forceExpanded:l,profileMenuOpen:u,groups:d,userMenu:f,onNavigate:m,onSignOut:h,signIn:g,organizations:_,roles:v,theme:y,logo:a});return(0,H.jsx)(wu.Provider,{value:k,children:(0,H.jsxs)(`div`,{className:V(A?`flex min-h-full w-full overflow-x-clip bg-background`:`relative flex h-full min-h-0 w-full overflow-hidden bg-background`,S),children:[w?N(e,A):(0,H.jsx)(Cu,{id:Md,open:T,onClose:()=>E(!1),children:N(`text-large`)}),(0,H.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,H.jsx)(jd,{ref:j,sticky:A,breadcrumb:n,onNavigate:m,actions:s,onMenu:w||D?void 0:()=>E(!0),menuOpen:T,menuControls:Md,search:b}),(0,H.jsx)(`main`,{className:A?`flex flex-1 flex-col`:`flex min-h-0 flex-1 flex-col`,children:C}),D&&(0,H.jsx)(_u,{ref:M,sticky:A,tabs:D,onNavigate:m,onMore:()=>E(!0),moreOpen:T,moreControls:Md})]}),c&&(0,H.jsx)(`div`,{className:A?`sticky top-0 flex h-dvh shrink-0 self-start`:`flex shrink-0`,children:c})]})})},Pd=({title:e,subtitle:t,aside:n,actions:r})=>{let i=(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`h1`,{className:`text-xl font-semibold tracking-tight`,children:e}),t&&(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:t})]});return(0,H.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-x-4 gap-y-2`,children:[n?(0,H.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center justify-between gap-3`,children:[i,n]}):i,r&&(0,H.jsx)(`div`,{className:`flex w-full flex-wrap items-center gap-2 sm:w-auto`,children:r})]})},Fd=`Too many attempts. Wait a minute and try again.`,Id=`The passkey prompt closed before it finished. Try again.`,Ld={INVALID_EMAIL_OR_PASSWORD:`The email or password is not right.`,INVALID_PASSWORD:`The password is not right.`,INVALID_OTP:`The code is not right.`,OTP_EXPIRED:`The code has expired. Ask for a new one.`,TOO_MANY_ATTEMPTS:`Too many wrong codes. Ask for a new one.`,INVALID_CODE:`The code is not right.`,INVALID_BACKUP_CODE:`The backup code is not right, or was used before.`,TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:`Too many wrong codes. Sign in again.`,ACCOUNT_TEMPORARILY_LOCKED:`Too many wrong codes. Wait 15 minutes and try again.`,INVALID_TWO_FACTOR_COOKIE:`This sign-in took too long. Sign in again.`,AUTH_CANCELLED:Id,ERROR_CEREMONY_ABORTED:Id,REGISTRATION_CANCELLED:Id,PASSKEY_NOT_FOUND:`This passkey is not registered for an account here.`,AUTHENTICATION_FAILED:`The passkey could not be checked. Try again.`,PREVIOUSLY_REGISTERED:`This passkey is added already.`,ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED:`This passkey is added already.`,SESSION_NOT_FRESH:`For this change, sign out and sign in again first.`},Rd=e=>e.code?Ld[e.code]:void 0,zd=e=>Rd(e)??(e.status===429?Fd:e.message),Bd=e=>Rd(e)??(e.status===429?Fd:e.status===401?Ld.INVALID_EMAIL_OR_PASSWORD:e.message),Vd={STAFF_PERMISSION_MISSING:`Your staff account has no permission to sign in as people here.`,STAFF_SIGN_IN_NOT_STRONG:`Sign in to your staff account with a passkey or a second step, then try again.`,STAFF_SIGN_IN_STALE:`Your staff sign-in is too old. Sign in to your staff account again.`,STAFF_SIGN_IN_EXPIRED:`This staff sign-in took too long or was used already. Start again.`,STAFF_SIGN_IN_FAILED:`The staff sign-in did not go through at the provider. Try again.`,STAFF_USER_UNAVAILABLE:`There is no account with this address, or it is disabled.`,STAFF_REASON_REQUIRED:`Say why you sign in as this person, in at least 10 characters.`,SIGN_IN_METHOD_FORBIDDEN:`Staff sign-in is turned off for this app.`,INVALID_CALLBACK_URL:`This page is not on an address the server trusts.`},Hd=e=>{let t=typeof e==`string`?e:e.code;return t&&Vd[t]?Vd[t]:typeof e==`string`?`The staff sign-in did not go through. Try again.`:e.status===429?Fd:e.message},Ud={signup_disabled:e=>`No account here belongs to this ${e} account. Ask an admin to add you, or sign in another way.`,account_not_linked:e=>`Your ${e} account is not linked to your account here. Sign in another way, then connect ${e} on the Sign-in & security page.`,account_already_linked_to_different_user:e=>`This ${e} account is linked to someone else here already.`,unable_to_link_account:e=>`Your ${e} account could not be linked. Try again.`,access_denied:e=>`${e} did not let you in, or you cancelled.`},Wd=(e,t)=>Ud[e]?.(t)??`Signing in with ${t} did not go through. Try again.`,Gd=`sign-in`,Kd=`error`,qd=e=>{let t=new URL(e).searchParams;if(!t.has(Kd))return t.get(`sign-in`)||void 0},Jd=e=>new URL(e).searchParams.get(Kd)||void 0,Yd=e=>{let t=new URL(e);for(let e of[Gd,Kd])t.searchParams.delete(e);return`${t.pathname}${t.search}${t.hash}`},Xd={github:`GitHub`,gitlab:`GitLab`,google:`Google`,microsoft:`Microsoft`,apple:`Apple`},Zd=(e,t)=>t?.provider===e?t.name:Xd[e]??e.charAt(0).toUpperCase()+e.slice(1),Qd=(0,o.createContext)(null),U=()=>{let e=(0,o.useContext)(Qd);if(!e)throw Error(`useAuth must be used inside AuthProvider`);return e},$d=({session:e,children:t})=>{let[n,r]=(0,o.useState)({kind:`loading`}),[i,a]=(0,o.useState)([`password`]),[s,c]=(0,o.useState)(!1),[l,u]=(0,o.useState)(!1),[d,f]=(0,o.useState)([]),[p,m]=(0,o.useState)([]),[h,g]=(0,o.useState)(),[_,v]=(0,o.useState)(),[y,b]=(0,o.useState)(),[x,S]=(0,o.useState)(!1),[C,w]=(0,o.useState)([]),T=(0,o.useCallback)(()=>x?{kind:`visitor`}:{kind:`signed-out`},[x]),E=(0,o.useCallback)(()=>r(e=>e.kind===`signed-in`?{kind:`signed-out`}:e),[]),D=(0,o.useRef)(E);D.current=E;let O=(0,o.useMemo)(()=>e??ru({onSignedOut:()=>D.current()}),[e]),k=(0,o.useCallback)(async e=>{let[{missing:t},n]=await Promise.all([O.account.signInMethods(),O.staff.current()]);r(t.length>0?{kind:`setup-required`,user:e,missing:t}:{kind:`signed-in`,user:e,...n&&{staff:n}})},[O]),A=(0,o.useCallback)(async e=>e.kind===`two-factor`?r({kind:`two-factor`,methods:e.methods}):k(e.user),[k]),j=(0,o.useCallback)(()=>{r({kind:`loading`}),O.status().then(async e=>{if(a(e.signInMethods),c(e.passwordReset),u(!!e.signUp),f(e.passkeyDomains??[]),m(e.socialProviders),g(e.platformSignIn),v(e.staffSignIn),b(e.organizations),S(!!e.anonymous),w(e.plugins??[]),e.needsAdmin)return r({kind:`needs-admin`});let t=await O.session();return t?k(t):r({kind:e.anonymous?`visitor`:`signed-out`})}).catch(e=>r({kind:`error`,message:e instanceof Error?e.message:`The server did not answer`}))},[O,k]);(0,o.useEffect)(j,[j]);let M=(0,o.useMemo)(()=>({state:n,session:O,signInMethods:i,passwordReset:s,canSignUp:l,passkeyDomains:d,socialProviders:p,signInProviders:p.map(e=>({id:e,name:Zd(e,h)})),staffSignIn:_,...y&&{organizations:y},markSignedOut:E,recheck:j,beforeSignIn:C,adoptSession:async()=>{let e=await O.session();return e?(await k(e),!0):!1},...x&&{browse:()=>{r(e=>e.kind===`signed-out`?{kind:`visitor`}:e)}},signIn:async(e,t)=>A(await O.signIn(e,t)),sendSignInCode:e=>O.sendSignInCode(e),signInWithCode:async(e,t)=>A(await O.signInWithCode(e,t)),sendSignUpCode:e=>O.sendSignUpCode(e),verifySignUpCode:(e,t)=>O.verifySignUpCode(e,t),signUp:async e=>k(await O.signUp(e)),signInWithPasskey:async e=>k(await O.signInWithPasskey(e)),verifyTwoFactor:async e=>k(await O.verifyTwoFactor(e)),signInSocial:async e=>{window.location.assign(await O.signInSocial(e,new URL(Yd(window.location.href),window.location.href).href))},linkProvider:async e=>{window.location.assign(await O.account.linkProvider(e,new URL(Yd(window.location.href),window.location.href).href))},stopStaffSession:async()=>{await O.staff.stop(),r(T())},signOut:async()=>{await O.signOut(),r(T())}}),[n,O,i,s,l,d,p,h,_,y,x,C,T,E,j,A,k]);return(0,H.jsx)(Qd.Provider,{value:M,children:t})},ef=new Map,tf=(e,t)=>{let n=`${e}:${t??``}`,r=ef.get(n);if(r)return r;let i=new Intl.NumberFormat(`en-IE`,{style:`currency`,currency:e,...t!==void 0&&{minimumFractionDigits:t,maximumFractionDigits:t}});return ef.set(n,i),i},nf=(e,t=`EUR`,n)=>tf(t,n).format(e/100),rf=new Intl.NumberFormat(`en-IE`),af=e=>rf.format(e),of=e=>e>0?`+${rf.format(e)}`:rf.format(e).replace(`-`,`−`),sf=e=>`${e}%`,cf=e=>{if(e<1e4)return`${af(e)} rows`;let t=10**(Math.floor(Math.log10(e))-3);return`about ${af(Math.round(e/t)*t)} rows`},lf=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,year:`numeric`,timeZone:`UTC`}),uf=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,timeZone:`UTC`}),df=new Intl.DateTimeFormat(`en-GB`,{hour:`2-digit`,minute:`2-digit`,hour12:!1,timeZone:`UTC`}),ff=e=>lf.format(e),pf=e=>uf.format(e),mf=e=>`${lf.format(e)}, ${df.format(e)}`,hf=e=>e<60?`${e} s ago`:e<3600?`${Math.floor(e/60)} min ago`:e<86400?`${Math.floor(e/3600)} h ago`:`${Math.floor(e/86400)} d ago`,gf=new Intl.RelativeTimeFormat(`en`,{numeric:`auto`}),_f=[[`year`,31536e3],[`month`,2592e3],[`day`,86400],[`hour`,3600],[`minute`,60]],vf=e=>{let[t,n]=_f.find(([,t])=>e>=t)??[`second`,1];return t===`second`&&e<45?`just now`:gf.format(-Math.floor(e/n),t)},yf={primary:`bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm`,secondary:`bg-background text-foreground border border-border-strong hover:bg-muted shadow-sm`,ghost:`text-muted-foreground hover:bg-muted hover:text-foreground`,danger:`bg-background text-danger-text border border-border-strong hover:bg-danger-soft shadow-sm`},bf={sm:`h-7 px-2.5 text-xs gap-1.5`,md:`h-8 px-3 text-body gap-2`},xf=({variant:e=`secondary`,size:t=`md`}={})=>V(`inline-flex shrink-0 items-center justify-center rounded-md font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-60 disabled:cursor-default`,yf[e],bf[t]),W=({variant:e=`secondary`,size:t=`md`,loading:n,className:r,children:i,disabled:a,...o})=>(0,H.jsxs)(`button`,{type:`button`,disabled:a||n,className:V(xf({variant:e,size:t}),r),...o,children:[n&&(0,H.jsx)(Ed,{className:`size-3.5`}),i]}),Sf=({title:e,description:t,onClose:n,actions:r,children:i,wide:a=!1})=>{let s=(0,o.useRef)(null);return Su(s,!0,n),(0,H.jsx)(`div`,{className:`fixed inset-0 z-[90] flex items-center justify-center bg-backdrop/30 p-4`,onMouseDown:e=>e.target===e.currentTarget&&n(),children:(0,H.jsxs)(`div`,{ref:s,tabIndex:-1,role:`dialog`,"aria-modal":`true`,"aria-label":e,className:V(`outline-none max-h-[90vh] w-full overflow-y-auto rounded-lg border bg-background p-4 shadow-pop sm:p-5`,a?`max-w-3xl`:`max-w-md`),children:[(0,H.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:e}),t&&(0,H.jsx)(`p`,{className:`mt-1.5 text-muted-foreground`,children:t}),i&&(0,H.jsx)(`div`,{className:`mt-4`,children:i}),(0,H.jsx)(`div`,{className:`mt-5 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end [&>*]:min-h-11 sm:[&>*]:min-h-0`,children:r})]})})},Cf=({title:e,status:t,description:n,children:r})=>(0,H.jsxs)(`section`,{"aria-label":e,className:`rounded-lg border bg-background p-4 sm:p-5`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,H.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:e}),t]}),(0,H.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:n}),r&&(0,H.jsx)(`div`,{className:`mt-4`,children:r})]}),wf=({message:e})=>e?(0,H.jsx)(`p`,{role:`alert`,className:`mb-3 text-xs font-medium text-danger-text`,children:e}):null,Tf={allowed:`Sign in with Face ID, Touch ID, Windows Hello, your phone or a security key instead of a password.`,required:`This app requires a passkey for every account. Sign in with Face ID, Touch ID, Windows Hello, your phone or a security key.`,forbidden:`Your admin turned passkeys off for this app, so they cannot be used to sign in.`},Ef=({rule:e,passkeys:t,onAdd:n,onRename:r,onRemove:i})=>{let[a,s]=(0,o.useState)(!1),[c,l]=(0,o.useState)(),[u,d]=(0,o.useState)(),[f,p]=(0,o.useState)(``),m=e===`required`&&t.length<=1,h=async e=>{s(!0),l(void 0);try{await e(),d(void 0)}catch(e){if(!(e instanceof lc))throw e;l(zd(e))}s(!1)};return(0,H.jsxs)(Cf,{title:`Passkeys`,status:e===`required`&&(0,H.jsx)(Xu,{tone:`blue`,children:`Required`}),description:Tf[e],children:[(0,H.jsx)(wf,{message:u?void 0:c}),t.length>0&&(0,H.jsx)(`ul`,{className:`mb-3 divide-y rounded-md border`,children:t.map(e=>(0,H.jsxs)(`li`,{className:`flex flex-wrap items-center gap-3 px-3 py-2.5`,children:[(0,H.jsx)(gt,{className:`size-4 shrink-0 text-muted-foreground`}),(0,H.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`block truncate font-medium`,children:e.name??`Passkey`}),(0,H.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[e.createdAt?`Added ${ff(Date.parse(e.createdAt))}`:`Added earlier`,` · `,e.backedUp?`Synced across your devices`:`On one device`]})]}),(0,H.jsxs)(`span`,{className:`flex gap-1`,children:[(0,H.jsx)(W,{size:`sm`,variant:`ghost`,onClick:()=>{p(e.name??``),d({kind:`rename`,passkey:e})},children:`Rename`}),(0,H.jsx)(W,{size:`sm`,variant:`ghost`,disabled:m,title:m?`Passkeys are required: add another one before removing this one.`:void 0,onClick:()=>d({kind:`remove`,passkey:e}),children:`Remove`})]})]},e.id))}),e!==`forbidden`&&(0,H.jsxs)(W,{loading:a&&!u,onClick:()=>void h(n),children:[(0,H.jsx)(nn,{className:`size-3.5`}),`Add a passkey`]}),u?.kind===`rename`&&(0,H.jsxs)(Sf,{title:`Rename passkey`,description:`A name that tells you where this passkey lives, such as the device or password manager.`,onClose:()=>d(void 0),actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:()=>d(void 0),children:`Cancel`}),(0,H.jsx)(W,{variant:`primary`,loading:a,disabled:!f.trim(),onClick:()=>void h(()=>r(u.passkey.id,f.trim())),children:`Save`})]}),children:[(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Name`,(0,H.jsx)(wd,{autoFocus:!0,value:f,maxLength:60,onChange:e=>p(e.target.value)})]}),(0,H.jsx)(wf,{message:c})]}),u?.kind===`remove`&&(0,H.jsx)(Sf,{title:`Remove passkey?`,description:`${u.passkey.name??`This passkey`} will no longer sign you in here. It stays on the device until you delete it there.`,onClose:()=>d(void 0),actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:()=>d(void 0),children:`Cancel`}),(0,H.jsx)(W,{variant:`danger`,loading:a,onClick:()=>void h(()=>i(u.passkey.id)),children:`Remove`})]}),children:c&&(0,H.jsx)(wf,{message:c})})]})},Df=({providers:e,linked:t,onConnect:n,error:r})=>{let[i,a]=(0,o.useState)(),[s,c]=(0,o.useState)(r),l=async e=>{a(e),c(void 0);try{await n(e)}catch(e){if(!(e instanceof lc))throw e;c(zd(e)),a(void 0)}};return(0,H.jsxs)(Cf,{title:`Connected accounts`,description:`Sign in with these instead of your password. Connecting one asks you to sign in there; its address may differ from yours here.`,children:[(0,H.jsx)(wf,{message:s}),(0,H.jsx)(`ul`,{className:`divide-y rounded-md border`,children:e.map(e=>(0,H.jsxs)(`li`,{className:`flex flex-wrap items-center gap-3 px-3 py-2.5`,children:[(0,H.jsx)(Dt,{className:`size-4 shrink-0 text-muted-foreground`}),(0,H.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-medium`,children:e.name}),t.includes(e.id)?(0,H.jsx)(Xu,{tone:`green`,children:`Connected`}):(0,H.jsxs)(W,{size:`sm`,loading:i===e.id,disabled:i!==void 0,onClick:()=>void l(e.id),children:[`Connect `,e.name]})]},e.id))})]})},Of=(e,t,n=`text/plain`)=>{let r=URL.createObjectURL(new Blob([e],{type:n}));Object.assign(document.createElement(`a`),{href:r,download:t}).click(),URL.revokeObjectURL(r)},kf=({codes:e})=>{let[t,n]=(0,o.useState)(!1),r=`${e.join(`
|
|
7
|
+
`)}\n`;return(0,H.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,H.jsx)(`ul`,{"aria-label":`Backup codes`,className:`grid grid-cols-2 gap-x-4 gap-y-1 rounded-md border bg-surface p-3 font-mono`,children:e.map(e=>(0,H.jsx)(`li`,{children:e},e))}),(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,H.jsxs)(W,{size:`sm`,onClick:()=>{navigator.clipboard.writeText(r).then(()=>{n(!0),setTimeout(()=>n(!1),2e3)})},children:[t?(0,H.jsx)(he,{className:`size-3.5 text-success`}):(0,H.jsx)(Le,{className:`size-3.5`}),t?`Copied`:`Copy`]}),(0,H.jsxs)(W,{size:`sm`,onClick:()=>Of(r,`backup-codes.txt`),children:[(0,H.jsx)(He,{className:`size-3.5`}),`Download`]})]})]})},Af=({title:e,description:t,confirmLabel:n,danger:r,needsPassword:i,onConfirm:a,onClose:s})=>{let[c,l]=(0,o.useState)(``),[u,d]=(0,o.useState)(!1),[f,p]=(0,o.useState)(),m=async()=>{d(!0),p(void 0);try{await a(i?c:void 0)}catch(e){if(!(e instanceof lc))throw e;p(zd(e)),d(!1)}};return(0,H.jsxs)(Sf,{title:e,description:t,onClose:s,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:s,children:`Cancel`}),(0,H.jsx)(W,{variant:r?`danger`:`primary`,loading:u,disabled:i&&!c,onClick:()=>void m(),children:n})]}),children:[i&&(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Your password`,(0,H.jsx)(wd,{type:`password`,autoComplete:`current-password`,autoFocus:!0,value:c,invalid:!!f,onChange:e=>l(e.target.value),onKeyDown:e=>e.key===`Enter`&&c&&void m()})]}),f&&(0,H.jsx)(`p`,{role:`alert`,className:`mt-2 text-xs font-medium text-danger-text`,children:f})]})},jf=(e,t)=>e.replace(/\D/g,``).slice(0,t),Mf=(e,t,n)=>{let r=jf(t??``,n);return r.length===n?r:jf(e,n)},Nf=(e,t,n,r)=>{let i=t.replace(/\D/g,``);return i.length>=r?i.slice(0,r):jf(e.slice(0,n)+i+e.slice(n+i.length),r)},Pf=({value:e,onChange:t,onComplete:n,length:r=6,invalid:i,disabled:a,className:s,ref:c,onFocus:l,onBlur:u,onSelect:d,onKeyDown:f,onClick:p,onPaste:m,...h})=>{let g=(0,o.useRef)(null),[_,v]=(0,o.useState)(!1),[y,b]=(0,o.useState)(e.length),x=e.slice(0,r),S=Math.min(y,r-1),C=e=>{g.current=e,typeof c==`function`?c(e):c&&(c.current=e)},w=e=>{e!==x&&(t(e),e.length===r&&n?.(e))},T=e=>{let t=g.current;if(!t)return;let n=Math.max(0,Math.min(e,x.length));t.setSelectionRange(n,n<x.length?n+1:n),b(n)},E=e=>{if(f?.(e),e.defaultPrevented||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey)return;let t=e.currentTarget.selectionStart??x.length,n={ArrowLeft:t-1,ArrowRight:t+1,Home:0,End:x.length}[e.key];n!==void 0&&(e.preventDefault(),T(n))},D=e=>{p?.(e);let t=e.currentTarget.getBoundingClientRect();e.clientX<=t.left||e.clientX>=t.right||T(Math.floor((e.clientX-t.left)/t.width*r))};return(0,H.jsxs)(`div`,{className:V(`relative`,a&&`opacity-50`,s),children:[(0,H.jsx)(`div`,{"aria-hidden":!0,className:`flex justify-center gap-2`,children:Array.from({length:r},(e,t)=>{let n=_&&t===S;return(0,H.jsx)(`div`,{"data-slot":t,"data-digit":x[t],className:V(`flex h-12 min-w-0 max-w-12 flex-1 items-center justify-center rounded-md border bg-background font-mono text-xl font-semibold text-foreground shadow-sm transition-colors before:content-[attr(data-digit)]`,i?`border-danger`:n?`border-primary`:`border-border-strong`,n&&(i?`ring-2 ring-danger/20`:`ring-2 ring-primary/20`)),children:x[t]===void 0&&(n?(0,H.jsx)(`span`,{className:`h-6 w-px animate-pulse bg-foreground`}):(0,H.jsx)(`span`,{className:`size-1.5 rounded-full bg-border-strong`}))},t)})}),(0,H.jsx)(`input`,{ref:C,type:`text`,inputMode:`numeric`,autoComplete:`one-time-code`,pattern:`[0-9]{${r}}`,spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`,"aria-invalid":i||void 0,disabled:a,value:x,className:`absolute inset-0 size-full cursor-text bg-transparent text-transparent caret-transparent outline-none selection:bg-transparent disabled:cursor-not-allowed`,...h,onChange:e=>{let{data:t,dataTransfer:n}=e.nativeEvent;w(Mf(e.target.value,t??n?.getData(`text/plain`),r))},onPaste:e=>{if(m?.(e),e.defaultPrevented)return;e.preventDefault();let t=e.currentTarget,n=Nf(x,e.clipboardData.getData(`text`),t.selectionStart??x.length,r);w(n),b(n.length)},onSelect:e=>{d?.(e);let t=e.currentTarget,n=t.selectionStart??x.length;n===t.selectionEnd&&n<t.value.length&&t.setSelectionRange(n,n+1),b(n)},onKeyDown:E,onClick:D,onFocus:e=>{v(!0),l?.(e)},onBlur:e=>{v(!1),u?.(e)}})]})},Ff=(e=>(e[e.Border=-1]=`Border`,e[e.Data=0]=`Data`,e[e.Function=1]=`Function`,e[e.Position=2]=`Position`,e[e.Timing=3]=`Timing`,e[e.Alignment=4]=`Alignment`,e))(Ff||{}),If=[0,1],Lf=[1,0],Rf=[2,3],zf=[3,2],Bf={L:If,M:Lf,Q:Rf,H:zf},Vf=/^\d*$/,Hf=/^[A-Z0-9 $%*+./:-]*$/,Uf=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:`,Wf=1,Gf=40,Kf=3,qf=3,Jf=40,Yf=10,Xf=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],Zf=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],Qf=class{constructor(e,t,n,r){if(this.version=e,this.ecc=t,e<Wf||e>Gf)throw RangeError(`Version value out of range`);if(r<-1||r>7)throw RangeError(`Mask value out of range`);this.size=e*4+17;let i=Array.from({length:this.size}).fill(!1);for(let e=0;e<this.size;e++)this.modules.push(i.slice()),this.types.push(i.map(()=>0));this.drawFunctionPatterns();let a=this.addEccAndInterleave(n);if(this.drawCodewords(a),r===-1){let e=1e9;for(let t=0;t<8;t++){this.applyMask(t),this.drawFormatBits(t);let n=this.getPenaltyScore();n<e&&(r=t,e=n),this.applyMask(t)}}this.mask=r,this.applyMask(r),this.drawFormatBits(r)}size;mask;modules=[];types=[];getModule(e,t){return e>=0&&e<this.size&&t>=0&&t<this.size&&this.modules[t][e]}drawFunctionPatterns(){for(let e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0,Ff.Timing),this.setFunctionModule(e,6,e%2==0,Ff.Timing);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);let e=this.getAlignmentPatternPositions(),t=e.length;for(let n=0;n<t;n++)for(let r=0;r<t;r++)n===0&&r===0||n===0&&r===t-1||n===t-1&&r===0||this.drawAlignmentPattern(e[n],e[r]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(e){let t=this.ecc[1]<<3|e,n=t;for(let e=0;e<10;e++)n=n<<1^(n>>>9)*1335;let r=(t<<10|n)^21522;for(let e=0;e<=5;e++)this.setFunctionModule(8,e,ep(r,e));this.setFunctionModule(8,7,ep(r,6)),this.setFunctionModule(8,8,ep(r,7)),this.setFunctionModule(7,8,ep(r,8));for(let e=9;e<15;e++)this.setFunctionModule(14-e,8,ep(r,e));for(let e=0;e<8;e++)this.setFunctionModule(this.size-1-e,8,ep(r,e));for(let e=8;e<15;e++)this.setFunctionModule(8,this.size-15+e,ep(r,e));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let t=0;t<12;t++)e=e<<1^(e>>>11)*7973;let t=this.version<<12|e;for(let e=0;e<18;e++){let n=ep(t,e),r=this.size-11+e%3,i=Math.floor(e/3);this.setFunctionModule(r,i,n),this.setFunctionModule(i,r,n)}}drawFinderPattern(e,t){for(let n=-4;n<=4;n++)for(let r=-4;r<=4;r++){let i=Math.max(Math.abs(r),Math.abs(n)),a=e+r,o=t+n;a>=0&&a<this.size&&o>=0&&o<this.size&&this.setFunctionModule(a,o,i!==2&&i!==4,Ff.Position)}}drawAlignmentPattern(e,t){for(let n=-2;n<=2;n++)for(let r=-2;r<=2;r++)this.setFunctionModule(e+r,t+n,Math.max(Math.abs(r),Math.abs(n))!==1,Ff.Alignment)}setFunctionModule(e,t,n,r=Ff.Function){this.modules[t][e]=n,this.types[t][e]=r}addEccAndInterleave(e){let t=this.version,n=this.ecc;if(e.length!==hp(t,n))throw RangeError(`Invalid argument`);let r=Zf[n[0]][t],i=Xf[n[0]][t],a=Math.floor(mp(t)/8),o=r-a%r,s=Math.floor(a/r),c=[],l=gp(i);for(let t=0,n=0;t<r;t++){let r=e.slice(n,n+s-i+(t<o?0:1));n+=r.length;let a=_p(r,l);t<o&&r.push(0),c.push(r.concat(a))}let u=[];for(let e=0;e<c[0].length;e++)c.forEach((t,n)=>{(e!==s-i||n>=o)&&u.push(t[e])});return u}drawCodewords(e){if(e.length!==Math.floor(mp(this.version)/8))throw RangeError(`Invalid argument`);let t=0;for(let n=this.size-1;n>=1;n-=2){n===6&&(n=5);for(let r=0;r<this.size;r++)for(let i=0;i<2;i++){let a=n-i,o=n+1&2?r:this.size-1-r;!this.types[o][a]&&t<e.length*8&&(this.modules[o][a]=ep(e[t>>>3],7-(t&7)),t++)}}}applyMask(e){if(e<0||e>7)throw RangeError(`Mask value out of range`);for(let t=0;t<this.size;t++)for(let n=0;n<this.size;n++){let r;switch(e){case 0:r=(n+t)%2==0;break;case 1:r=t%2==0;break;case 2:r=n%3==0;break;case 3:r=(n+t)%3==0;break;case 4:r=(Math.floor(n/3)+Math.floor(t/2))%2==0;break;case 5:r=n*t%2+n*t%3==0;break;case 6:r=(n*t%2+n*t%3)%2==0;break;case 7:r=((n+t)%2+n*t%3)%2==0;break;default:throw Error(`Unreachable`)}!this.types[t][n]&&r&&(this.modules[t][n]=!this.modules[t][n])}}getPenaltyScore(){let e=0;for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[t][a]===n?(r++,r===5?e+=Kf:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*Jf),n=this.modules[t][a],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*Jf}for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[a][t]===n?(r++,r===5?e+=Kf:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*Jf),n=this.modules[a][t],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*Jf}for(let t=0;t<this.size-1;t++)for(let n=0;n<this.size-1;n++){let r=this.modules[t][n];r===this.modules[t][n+1]&&r===this.modules[t+1][n]&&r===this.modules[t+1][n+1]&&(e+=qf)}let t=0;for(let e of this.modules)t=e.reduce((e,t)=>e+ +!!t,t);let n=this.size*this.size,r=Math.ceil(Math.abs(t*20-n*10)/n)-1;return e+=r*Yf,e}getAlignmentPatternPositions(){if(this.version===1)return[];{let e=Math.floor(this.version/7)+2,t=this.version===32?26:Math.ceil((this.version*4+4)/(e*2-2))*2,n=[6];for(let r=this.size-7;n.length<e;r-=t)n.splice(1,0,r);return n}}finderPenaltyCountPatterns(e){let t=e[1],n=t>0&&e[2]===t&&e[3]===t*3&&e[4]===t&&e[5]===t;return(n&&e[0]>=t*4&&e[6]>=t?1:0)+(n&&e[6]>=t*4&&e[0]>=t?1:0)}finderPenaltyTerminateAndCount(e,t,n){return e&&(this.finderPenaltyAddHistory(t,n),t=0),t+=this.size,this.finderPenaltyAddHistory(t,n),this.finderPenaltyCountPatterns(n)}finderPenaltyAddHistory(e,t){t[0]===0&&(e+=this.size),t.pop(),t.unshift(e)}};function $f(e,t,n){if(t<0||t>31||e>>>t)throw RangeError(`Value out of range`);for(let r=t-1;r>=0;r--)n.push(e>>>r&1)}function ep(e,t){return!!(e>>>t&1)}var tp=class{constructor(e,t,n){if(this.mode=e,this.numChars=t,this.bitData=n,t<0)throw RangeError(`Invalid argument`);this.bitData=n.slice()}getData(){return this.bitData.slice()}},np=[1,10,12,14],rp=[2,9,11,13],ip=[4,8,16,16];function ap(e,t){return e[Math.floor((t+7)/17)+1]}function op(e){let t=[];for(let n of e)$f(n,8,t);return new tp(ip,e.length,t)}function sp(e){if(!up(e))throw RangeError(`String contains non-numeric characters`);let t=[];for(let n=0;n<e.length;){let r=Math.min(e.length-n,3);$f(Number.parseInt(e.substring(n,n+r),10),r*3+1,t),n+=r}return new tp(np,e.length,t)}function cp(e){if(!dp(e))throw RangeError(`String contains unencodable characters in alphanumeric mode`);let t=[],n=0;for(;n+2<=e.length;n+=2){let r=Uf.indexOf(e.charAt(n))*45;r+=Uf.indexOf(e.charAt(n+1)),$f(r,11,t)}return n<e.length&&$f(Uf.indexOf(e.charAt(n)),6,t),new tp(rp,e.length,t)}function lp(e){return e===``?[]:up(e)?[sp(e)]:dp(e)?[cp(e)]:[op(pp(e))]}function up(e){return Vf.test(e)}function dp(e){return Hf.test(e)}function fp(e,t){let n=0;for(let r of e){let e=ap(r.mode,t);if(r.numChars>=1<<e)return 1/0;n+=4+e+r.bitData.length}return n}function pp(e){e=encodeURI(e);let t=[];for(let n=0;n<e.length;n++)e.charAt(n)===`%`?(t.push(Number.parseInt(e.substring(n+1,n+3),16)),n+=2):t.push(e.charCodeAt(n));return t}function mp(e){if(e<Wf||e>Gf)throw RangeError(`Version number out of range`);let t=(16*e+128)*e+64;if(e>=2){let n=Math.floor(e/7)+2;t-=(25*n-10)*n-55,e>=7&&(t-=36)}return t}function hp(e,t){return Math.floor(mp(e)/8)-Xf[t[0]][e]*Zf[t[0]][e]}function gp(e){if(e<1||e>255)throw RangeError(`Degree out of range`);let t=[];for(let n=0;n<e-1;n++)t.push(0);t.push(1);let n=1;for(let r=0;r<e;r++){for(let e=0;e<t.length;e++)t[e]=vp(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=vp(n,2)}return t}function _p(e,t){let n=t.map(e=>0);for(let r of e){let e=r^n.shift();n.push(0),t.forEach((t,r)=>n[r]^=vp(t,e))}return n}function vp(e,t){if(e>>>8||t>>>8)throw RangeError(`Byte out of range`);let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return n}function yp(e,t,n=1,r=40,i=-1,a=!0){if(!(Wf<=n&&n<=r&&r<=Gf)||i<-1||i>7)throw RangeError(`Invalid value`);let o,s;for(o=n;;o++){let n=hp(o,t)*8,i=fp(e,o);if(i<=n){s=i;break}if(o>=r)throw RangeError(`Data too long`)}for(let e of[Lf,Rf,zf])a&&s<=hp(o,e)*8&&(t=e);let c=[];for(let t of e){$f(t.mode[0],4,c),$f(t.numChars,ap(t.mode,o),c);for(let e of t.getData())c.push(e)}let l=hp(o,t)*8;$f(0,Math.min(4,l-c.length),c),$f(0,(8-c.length%8)%8,c);for(let e=236;c.length<l;e^=253)$f(e,8,c);let u=Array.from({length:Math.ceil(c.length/8)},()=>0);return c.forEach((e,t)=>u[t>>>3]|=e<<7-(t&7)),new Qf(o,t,u,i)}function bp(e,t){let{ecc:n=`L`,boostEcc:r=!1,minVersion:i=1,maxVersion:a=40,maskPattern:o=-1,border:s=1}=t||{},c=typeof e==`string`?lp(e):Array.isArray(e)?[op(e)]:void 0;if(!c)throw Error(`uqr only supports encoding string and binary data, but got: ${typeof e}`);let l=yp(c,Bf[n],i,a,o,r),u=xp({version:l.version,maskPattern:l.mask,size:l.size,data:l.modules,types:l.types},s);return t?.invert&&(u.data=u.data.map(e=>e.map(e=>!e))),t?.onEncoded?.(u),u}function xp(e,t=1){if(!t)return e;let{size:n}=e,r=n+t*2;e.size=r,e.data.forEach(e=>{for(let n=0;n<t;n++)e.unshift(!1),e.push(!1)});for(let n=0;n<t;n++)e.data.unshift(Array.from({length:r},e=>!1)),e.data.push(Array.from({length:r},e=>!1));let i=Ff.Border;e.types.forEach(e=>{for(let n=0;n<t;n++)e.unshift(i),e.push(i)});for(let n=0;n<t;n++)e.types.unshift(Array.from({length:r},e=>i)),e.types.push(Array.from({length:r},e=>i));return e}var Sp=({uri:e,className:t})=>{let{size:n,path:r}=(0,o.useMemo)(()=>{let t=bp(e,{ecc:`M`,border:2}),n=t.data.flatMap((e,t)=>e.flatMap((e,n)=>e?[`M${n} ${t}h1v1h-1z`]:[]));return{size:t.size,path:n.join(``)}},[e]);return(0,H.jsxs)(`svg`,{viewBox:`0 0 ${n} ${n}`,role:`img`,"aria-label":`QR code for your authenticator app`,shapeRendering:`crispEdges`,className:t,children:[(0,H.jsx)(`rect`,{width:n,height:n,fill:`#fff`}),(0,H.jsx)(`path`,{d:r,fill:`#000`})]})},Cp=e=>(new URL(e).searchParams.get(`secret`)??``).replace(/(.{4})(?=.)/g,`$1 `),wp=[{value:`app`,label:`Authenticator app`,description:`A code from an app such as Google Authenticator, Microsoft Authenticator or 1Password. Comes with backup codes.`},{value:`email`,label:`Emailed code`,description:`A code mailed to your address each time you sign in with a password or an emailed sign-in code.`}],Tp=({offerEmailedCodes:e,needsPassword:t,onStartApp:n,onConfirmApp:r,onEmailedCodes:i,onDone:a,onCancel:s})=>{let[c,l]=(0,o.useState)({kind:`choose`}),[u,d]=(0,o.useState)(`app`),[f,p]=(0,o.useState)(``),[m,h]=(0,o.useState)(``),[g,_]=(0,o.useState)(!1),[v,y]=(0,o.useState)(),b=e?wp:wp.filter(e=>e.value===`app`),x=async e=>{_(!0),y(void 0);try{await e()}catch(e){if(!(e instanceof lc))throw e;y(zd(e))}_(!1)},S=()=>x(async()=>{let e=t?f:void 0;if(u===`email`)return await i(e),a();l({kind:`scan`,setup:await n(e)})}),C=(e,t=m)=>x(async()=>{await r(t),l({kind:`backup-codes`,codes:e.backupCodes})}),w=v&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:v});return c.kind===`backup-codes`?(0,H.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:`Two-factor authentication is on. Keep these backup codes somewhere safe: each one signs you in once if you lose your phone. They are not shown again.`}),(0,H.jsx)(kf,{codes:c.codes}),(0,H.jsx)(W,{variant:`primary`,onClick:a,className:`min-h-10`,children:`I saved my backup codes`})]}):c.kind===`scan`?(0,H.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),C(c.setup)},children:[(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:`Scan this code with your authenticator app, then enter the 6-digit code it shows.`}),(0,H.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,H.jsx)(Sp,{uri:c.setup.totpURI,className:`size-44 rounded-md border`}),(0,H.jsxs)(`p`,{className:`text-center text-xs text-muted-foreground`,children:[`Can't scan it? Enter this key in the app:`,(0,H.jsx)(`span`,{className:`mt-1 block break-all font-mono text-body text-foreground`,children:Cp(c.setup.totpURI)})]})]}),(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Code from the app`,(0,H.jsx)(Pf,{name:`code`,required:!0,autoFocus:!0,value:m,invalid:!!v,onChange:h,onComplete:e=>!g&&void C(c.setup,e)})]}),w,(0,H.jsx)(W,{variant:`primary`,type:`submit`,loading:g,className:`min-h-10`,children:`Turn on`}),s&&(0,H.jsx)(W,{variant:`ghost`,onClick:s,className:`min-h-10`,children:`Cancel`})]}):(0,H.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),S()},children:[(0,H.jsx)(`div`,{role:`radiogroup`,"aria-label":`Second step`,className:`flex flex-col gap-2`,children:b.map(e=>(0,H.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":u===e.value,onClick:()=>d(e.value),className:V(`rounded-md border p-3 text-left transition-colors`,u===e.value?`border-primary bg-primary-soft`:`border-border-strong hover:bg-muted`),children:[(0,H.jsx)(`span`,{className:`block font-medium`,children:e.label}),(0,H.jsx)(`span`,{className:`mt-0.5 block text-xs text-muted-foreground`,children:e.description})]},e.value))}),t&&(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Your password`,(0,H.jsx)(wd,{type:`password`,name:`password`,autoComplete:`current-password`,required:!0,value:f,invalid:!!v,onChange:e=>p(e.target.value),className:`min-h-6`})]}),w,(0,H.jsx)(W,{variant:`primary`,type:`submit`,loading:g,className:`min-h-10`,children:`Continue`}),s&&(0,H.jsx)(W,{variant:`ghost`,onClick:s,className:`min-h-10`,children:`Cancel`})]})},Ep={allowed:`Ask for a second step after your password or an emailed sign-in code: a code from an authenticator app, or one emailed to you. A passkey needs no second step.`,required:`This app requires two-factor authentication for every account. Turn it on to keep using the app.`,forbidden:`Your admin turned two-factor authentication off for this app.`},Dp=e=>{let{rule:t,enabled:n,authenticatorApp:r,mail:i,needsPassword:a,onTurnOff:s,onNewBackupCodes:c,onChanged:l}=e,[u,d]=(0,o.useState)(),f=()=>d(void 0),p=n?(0,H.jsx)(Xu,{tone:`green`,children:`On`}):t===`required`?(0,H.jsx)(Xu,{tone:`amber`,children:`Required`}):(0,H.jsx)(Xu,{children:`Off`}),m=n?r?`Signing in with a password or an emailed sign-in code also asks for a code from your authenticator app${i?`, or one emailed to you`:``}. Backup codes work when you do not have the app.`:`Signing in with a password or an emailed sign-in code also asks for a code emailed to you.`:Ep[t];return u?.kind===`setup`?(0,H.jsx)(Cf,{title:`Two-factor authentication`,status:p,description:m,children:(0,H.jsx)(`div`,{className:`max-w-sm`,children:(0,H.jsx)(Tp,{offerEmailedCodes:i&&!u.appOnly,needsPassword:a,onStartApp:e.onStartApp,onConfirmApp:e.onConfirmApp,onEmailedCodes:e.onEmailedCodes,onCancel:f,onDone:()=>{f(),l()}})})}):(0,H.jsxs)(Cf,{title:`Two-factor authentication`,status:p,description:m,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[!n&&t!==`forbidden`&&(0,H.jsx)(W,{variant:`primary`,onClick:()=>d({kind:`setup`,appOnly:!1}),children:`Turn on`}),n&&!r&&t!==`forbidden`&&(0,H.jsx)(W,{onClick:()=>d({kind:`setup`,appOnly:!0}),children:`Add an authenticator app`}),n&&r&&(0,H.jsx)(W,{onClick:()=>d({kind:`new-codes`}),children:`New backup codes`}),n&&(0,H.jsx)(W,{variant:`danger`,disabled:t===`required`,title:t===`required`?`This app requires two-factor authentication.`:void 0,onClick:()=>d({kind:`turn-off`}),children:`Turn off`})]}),u?.kind===`turn-off`&&(0,H.jsx)(Af,{title:`Turn off two-factor authentication?`,description:`Signing in then needs only your password or an emailed code. Your backup codes stop working.`,confirmLabel:`Turn off`,danger:!0,needsPassword:a,onClose:f,onConfirm:async e=>{await s(e),f(),l()}}),u?.kind===`new-codes`&&(0,H.jsx)(Af,{title:`Make new backup codes?`,description:`Your current backup codes stop working, and you get ten new ones.`,confirmLabel:`Make new codes`,needsPassword:a,onClose:f,onConfirm:async e=>d({kind:`codes`,codes:await c(e)})}),u?.kind===`codes`&&(0,H.jsx)(Sf,{title:`Your new backup codes`,description:`Keep them somewhere safe: each one signs you in once if you lose your phone. They are not shown again.`,onClose:f,actions:(0,H.jsx)(W,{variant:`primary`,onClick:f,children:`I saved my backup codes`}),children:(0,H.jsx)(kf,{codes:u.codes})})]})},Op=()=>{let e=Jd(window.location.href);return e&&window.history.replaceState(window.history.state,``,Yd(window.location.href)),e},kp=({email:e})=>{let{session:t,signInProviders:n,linkProvider:r}=U(),{account:i}=t,[a,s]=(0,o.useState)(),[c,l]=(0,o.useState)(),[u]=(0,o.useState)(Op),d=(0,o.useCallback)(()=>{Promise.all([i.signInMethods(),i.passkeys(),i.linkedProviders()]).then(([e,t,n])=>s({methods:e,passkeys:t,linked:n}),e=>l(e instanceof lc?zd(e):`Could not read your sign-in methods`))},[i]);(0,o.useEffect)(d,[d]);let f=e=>e.then(e=>(d(),e));return(0,H.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,H.jsx)(Pd,{title:`Sign-in & security`,subtitle:e}),a?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Ef,{rule:a.methods.policy.passkey,passkeys:a.passkeys,onAdd:()=>f(i.addPasskey()),onRename:(e,t)=>f(i.renamePasskey(e,t)),onRemove:e=>f(i.removePasskey(e))}),(0,H.jsx)(Dp,{rule:a.methods.policy.twoFactor,enabled:a.methods.account.twoFactor,authenticatorApp:a.methods.account.authenticatorApp,mail:a.methods.mail,needsPassword:a.methods.account.password,onStartApp:e=>i.startAuthenticatorApp(e),onConfirmApp:e=>i.confirmAuthenticatorApp(e),onEmailedCodes:e=>i.turnOnEmailedCodes(e),onTurnOff:e=>i.turnOffTwoFactor(e),onNewBackupCodes:e=>i.newBackupCodes(e),onChanged:d}),n.length>0&&(0,H.jsx)(Df,{providers:n,linked:a.linked,onConnect:r,error:u&&Wd(u,n.length===1?n[0].name:`the provider`)})]}):c?(0,H.jsx)(`p`,{role:`alert`,className:`text-danger-text`,children:c}):(0,H.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,H.jsx)(Ed,{}),` Loading`]})]})},Ap=[{value:`allowed`,label:`On`},{value:`forbidden`,label:`Off`}],jp=[{value:`allowed`,label:`Optional`},{value:`required`,label:`Required`},{value:`forbidden`,label:`Off`}],Mp=[{method:`password`,label:`Password`,description:`Sign in with the email address and a password.`,rules:Ap},{method:`emailCode`,label:`Emailed sign-in code`,description:`Sign in with a one-time code mailed to the account's address.`,rules:Ap},{method:`passkey`,label:`Passkeys`,description:`Sign in with Face ID, Touch ID, Windows Hello, a phone or a security key. Required: everyone adds one after signing in.`,rules:jp},{method:`twoFactor`,label:`Two-factor authentication`,description:`A code from an authenticator app, or an emailed one, after a password or an emailed sign-in code. Required: everyone turns it on after signing in.`,rules:jp},{method:`staffAccess`,label:`Staff sign-in as a person`,description:`The team that runs this app signs in as someone to help them, with a reason, for a short session. Each time is in the log below; with "Email the person" they are told too.`,rules:[{value:`allowed`,label:`On`},{value:`notify`,label:`Email the person`},{value:`forbidden`,label:`Off`}]},{method:`platformSignIn`,label:`Sign-in through the platform`,description:`The sign-in provider the platform that runs this app adds, for people who have an account here already. It never creates accounts.`,rules:Ap}],Np=(e,t)=>{let n=Mp.find(t=>t.method===e)?.rules.find(e=>e.value===t)?.label;if(n===void 0)throw Error(`No label for the ${t} rule of ${e}`);return n},Pp=({row:e,value:t,onChange:n})=>(0,H.jsx)(`span`,{role:`radiogroup`,"aria-label":e.label,className:`inline-flex h-8 shrink-0 rounded-md bg-muted p-0.5`,children:e.rules.map(e=>(0,H.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e.value===t,onClick:()=>n(e.value),className:V(`rounded px-3 text-xs font-medium transition-colors`,e.value===t?`bg-background text-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`),children:e.label},e.value))}),Fp=({method:e},t,{mail:n,effective:r,policy:i})=>{if(e===`emailCode`&&!n)return`Needs mail settings (PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM): off until they are set.`;if(e===`password`&&!n&&t.password===`forbidden`)return`Without mail settings, password sign-in stays on so nobody is locked out.`;if(e===`staffAccess`&&!n&&t.staffAccess===`notify`)return`Needs mail settings (PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM): staff cannot sign in until they are set.`;if(e===`platformSignIn`&&t.platformSignIn===`allowed`&&(t.passkey===`required`||t.twoFactor===`required`))return`Off while passkeys or two-factor authentication are required: it skips the second step.`;if(t[e]===i[e]&&r[e]!==i[e])return`Applies as ${Np(e,r[e])} for now.`},Ip=({operator:e,platformSignIn:t})=>Mp.flatMap(n=>n.method===`staffAccess`&&!e?[]:n.method===`platformSignIn`?t?[{...n,label:`Sign in with ${t} through the platform`}]:[]:[n]),Lp=({state:e,onSave:t,busy:n,error:r,notice:i})=>{let[a,s]=(0,o.useState)(e.policy),c=Ip(e),l=c.some(({method:t})=>a[t]!==e.policy[t]);return(0,H.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),t(a)},children:[(0,H.jsx)(`ul`,{className:`divide-y rounded-lg border bg-background`,children:c.map(t=>{let n=Fp(t,a,e);return(0,H.jsxs)(`li`,{className:`flex flex-col gap-3 p-4 sm:flex-row sm:items-start sm:justify-between`,children:[(0,H.jsxs)(`div`,{className:`min-w-0`,children:[(0,H.jsx)(`h2`,{className:`font-semibold`,children:t.label}),(0,H.jsx)(`p`,{className:`mt-0.5 text-muted-foreground`,children:t.description}),n&&(0,H.jsx)(`p`,{className:`mt-1.5 text-xs font-medium text-warning-text`,children:n})]}),(0,H.jsx)(Pp,{row:t,value:a[t.method],onChange:e=>s({...a,[t.method]:e})})]},t.method)})}),r&&(0,H.jsx)(`p`,{role:`alert`,className:`rounded-md bg-danger-soft px-3 py-2 text-xs font-medium text-danger-text`,children:r}),i&&!l&&(0,H.jsx)(`p`,{role:`status`,className:`rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:i}),(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.savedAt?`Last saved${e.savedBy?` by ${e.savedBy}`:``} on ${mf(Date.parse(e.savedAt))}.`:`Never changed: everything is on, nothing is required.`}),(0,H.jsxs)(`div`,{className:`flex gap-2`,children:[l&&(0,H.jsx)(W,{onClick:()=>s(e.policy),children:`Reset`}),(0,H.jsx)(W,{variant:`primary`,type:`submit`,loading:n,disabled:!l,children:`Save`})]})]})]})},Rp=(e,t)=>e.endedAt?(0,H.jsxs)(Xu,{tone:`neutral`,children:[`Stopped `,mf(Date.parse(e.endedAt))]}):Date.parse(e.expiresAt)<=t?(0,H.jsxs)(Xu,{tone:`neutral`,children:[`Ended `,mf(Date.parse(e.expiresAt))]}):(0,H.jsxs)(Xu,{tone:`amber`,children:[`Signed in until `,mf(Date.parse(e.expiresAt))]}),zp=({signIns:e,operator:t,error:n,now:r=Date.now()})=>(0,H.jsxs)(Cf,{title:`Staff sign-ins`,description:`Each time staff of ${t} signed in as someone here, newest first.`,children:[(0,H.jsx)(wf,{message:n}),e&&e.length===0&&(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:`No staff has signed in as anyone yet.`}),e&&e.length>0&&(0,H.jsx)(`ul`,{className:`divide-y rounded-md border`,children:e.map(e=>(0,H.jsxs)(`li`,{className:`flex flex-col gap-1.5 p-3`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,H.jsx)(`span`,{className:`font-medium break-all`,children:e.staffName?`${e.staffName} (${e.staff})`:e.staff}),(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`as`}),(0,H.jsx)(`span`,{className:`font-medium break-all`,children:e.user})]}),(0,H.jsx)(`p`,{className:`break-words`,children:e.reason}),(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[(0,H.jsx)(`span`,{children:mf(Date.parse(e.startedAt))}),Rp(e,r)]})]},e.id))})]}),Bp=({operator:e})=>{let{session:t}=U(),[n,r]=(0,o.useState)(),[i,a]=(0,o.useState)();return(0,o.useEffect)(()=>{t.staff.log().then(r,e=>a(e instanceof lc?zd(e):`Could not read the staff sign-ins`))},[t]),(0,H.jsx)(zp,{operator:e,signIns:n,error:i})},Vp=()=>{let{session:e}=U(),[t,n]=(0,o.useState)(),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)(),[c,l]=(0,o.useState)();(0,o.useEffect)(()=>{e.signInPolicy.read().then(n,e=>s(e instanceof lc?zd(e):`Could not read the sign-in policy`))},[e]);let u=async t=>{i(!0),s(void 0),l(void 0);try{n(await e.signInPolicy.save(t)),l(`Saved. It applies to every sign-in from now on.`)}catch(e){if(!(e instanceof lc))throw e;s(zd(e))}i(!1)};return(0,H.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,H.jsx)(Pd,{title:`Sign-in policy`,subtitle:`How people sign in to this app. Signed-in people keep their session, and are asked for what is newly required within 15 minutes.`}),t?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Lp,{state:t,busy:r,error:a,notice:c,onSave:e=>void u(e)},t.savedAt??`default`),t.operator&&(0,H.jsx)(Bp,{operator:t.operator})]}):a?(0,H.jsx)(`p`,{role:`alert`,className:`text-danger-text`,children:a}):(0,H.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,H.jsx)(Ed,{}),` Loading`]})]})},Hp=o.createContext(void 0),Up=e=>{let t=o.useContext(Hp);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Wp=({client:e,children:t})=>(o.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,H.jsx)(Hp.Provider,{value:e,children:t})),Gp={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Kp=new class{#e=Gp;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function qp(e){setTimeout(e,0)}var Jp=typeof window>`u`||`Deno`in globalThis;function Yp(){}function Xp(e,t){return typeof e==`function`?e(t):e}function Zp(e){return typeof e==`number`&&e>=0&&e!==1/0}function Qp(e,t){return Math.max(e+(t||0)-Date.now(),0)}function $p(e,t){return typeof e==`function`?e(t):e}function em(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==nm(o,t.options))return!1}else if(!im(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function tm(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(rm(t.options.mutationKey)!==rm(a))return!1}else if(!im(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function nm(e,t){return(t?.queryKeyHashFn||rm)(e)}function rm(e){return JSON.stringify(e,(e,t)=>lm(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function im(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!im(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!im(e[r],t[r]))return!1;return!0}return!1}var am=Object.prototype.hasOwnProperty;function om(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=cm(e)&&cm(t);if(!r&&!(lm(e)&&lm(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:am.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=om(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function sm(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function cm(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function lm(e){if(!um(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!um(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function um(e){return Object.prototype.toString.call(e)===`[object Object]`}function dm(e){return new Promise(t=>{Kp.setTimeout(t,e)})}function fm(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:om(e,t)}function pm(e){return e}function mm(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function hm(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var gm=Symbol();function _m(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===gm?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function vm(e,t){return typeof e==`function`?e(...t):!!e}function ym(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var bm=()=>Jp,xm=()=>bm(),Sm=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Cm=new class extends Sm{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},wm=qp;function Tm(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=wm,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var Em=Tm(),Dm=new class extends Sm{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function Om(e){return Math.min(1e3*2**e,3e4)}function km(e){return(e??`online`)!==`online`||Dm.isOnline()}var Am=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function jm(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(Yp);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new Am(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>Cm.isFocused()&&(e.networkMode===`always`||Dm.isOnline())&&e.canRun(),p=()=>km(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=()=>new Promise(t=>{r=e=>{(c()||f())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(m).catch(r=>{if(c())return;let i=e.retry??(xm()?0:3),a=e.retryDelay??Om,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!s){h(r);return}n++,e.onFail?.(n,r),dm(o).then(()=>f()?void 0:g()).then(()=>{t?h(r):_()})})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g().then(_),s)}}var Mm=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),Zp(this.gcTime)&&(this.#e=Kp.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(xm()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Kp.clearTimeout(this.#e),this.#e=void 0)}};function Nm(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{ym(e,()=>t.signal,()=>n=!0)},u=_m(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?hm:mm;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Fm:Pm,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:Pm(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function Pm(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Fm(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Im(e,t){return t?Pm(e,t)!=null:!1}function Lm(e,t){return!t||!e.getPreviousPageParam?!1:Fm(e,t)!=null}var Rm=class extends Mm{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Vm(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Vm(this.options);e.data!==void 0&&(this.setState(Bm(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=fm(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(Yp).catch(Yp):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>$p(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===gm||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>$p(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!Qp(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=_m(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?Nm(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=jm({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Am&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof Am){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...zm(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Bm(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),Em.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function zm(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:km(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Bm(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Vm(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Hm=class extends Sm{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Wm(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Gm(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Gm(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof $p(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!sm(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&Km(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||$p(this.options.enabled,this.#t)!==$p(t.enabled,this.#t)||$p(this.options.staleTime,this.#t)!==$p(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||$p(this.options.enabled,this.#t)!==$p(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return sm(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Yp)),t}#h(e){return!xm()&&$p(this.options.enabled,this.#t)!==!1&&Zp(e)}#g(){this.#b();let e=$p(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=Qp(this.#r.dataUpdatedAt,e)+1;this.#u=Kp.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return $p(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=Kp.setInterval(()=>{(this.options.refetchIntervalInBackground||Cm.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(Kp.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(Kp.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Wm(e,t),o=i&&Km(e,n,t,r);(a||o)&&(l={...l,...zm(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=fm(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=fm(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:qm(e,t),refetch:this.refetch,isEnabled:$p(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),sm(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})();Em.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function Um(e,t){return $p(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||$p(t.retryOnMount,e)!==!1)}function Wm(e,t){return Um(e,t)||e.state.data!==void 0&&Gm(e,t,t.refetchOnMount)}function Gm(e,t,n){if($p(t.enabled,e)!==!1&&$p(t.staleTime,e)!==`static`){let r=$p(n,e);return r===`always`||r!==!1&&qm(e,t)}return!1}function Km(e,t,n,r){return(e!==t||$p(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&qm(e,n)}function qm(e,t){return $p(t.enabled,e)!==!1&&e.isStaleByTime($p(t.staleTime,e))}var Jm=class extends Hm{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type=`infinite`,super.setOptions(e)}getOptimisticResult(e){return e._type=`infinite`,super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`forward`}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`backward`}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:a,isError:o,isRefetchError:s}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c===`forward`,u=i&&c===`forward`,d=o&&c===`backward`,f=i&&c===`backward`;return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Im(t,n.data),hasPreviousPage:Lm(t,n.data),isFetchNextPageError:l,isFetchingNextPage:u,isFetchPreviousPageError:d,isFetchingPreviousPage:f,isRefetchError:s&&!l&&!d,isRefetching:a&&!u&&!f}}},Ym=class extends Mm{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Xm(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=jm({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),Em.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Xm(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Zm=class extends Sm{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new Ym({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=Qm(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=Qm(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=Qm(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=Qm(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){Em.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>tm(t,e))}findAll(e={}){return this.getAll().filter(t=>tm(e,t))}notify(e){Em.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return Em.batch(()=>Promise.all(e.map(e=>e.continue().catch(Yp))))}};function Qm(e){return e.options.scope?.id}var $m=class extends Sm{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),sm(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&rm(t.mutationKey)!==rm(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??Xm();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){Em.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,n=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{this.#r.onSuccess?.(e.data,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,n,r)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{this.#r.onError?.(e.error,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,n,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}};function eh(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var th=class extends Sm{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=[];constructor(e,t,n){super(),this.#e=e,this.#r=n,this.#n=[],this.#i=[],this.#t=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#i.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#i.forEach(e=>{e.destroy()})}setQueries(e,t){this.#n=e,this.#r=t,Em.batch(()=>{let e=this.#i,t=this.#p(this.#n);t.forEach(e=>e.observer.setOptions(e.defaultedQueryOptions));let n=t.map(e=>e.observer),r=n.map(e=>e.getCurrentResult()),i=e.length!==n.length,a=n.some((t,n)=>t!==e[n]),o=i||a,s=o?!0:r.some((e,t)=>{let n=this.#t[t];return!n||!sm(e,n)});(o||s)&&(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(eh(e,n).forEach(e=>{e.destroy()}),eh(n,e).forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})),this.#h()))})}getCurrentResult(){return this.#t}getQueries(){return this.#i.map(e=>e.getCurrentQuery())}getObservers(){return this.#i}getOptimisticResult(e,t){let n=this.#p(e),r=n.map(e=>e.observer.getOptimisticResult(e.defaultedQueryOptions)),i=n.map(e=>e.defaultedQueryOptions.queryHash);return[r,e=>this.#d(e??r,t,i),()=>this.#u(r,n)]}#u(e,t){let n=new Set;return t.map((r,i)=>{let a=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?a:r.observer.trackResult(a,e=>{n.has(e)||(n.add(e),t.forEach(t=>{t.observer.trackProp(e)}))})})}#d(e,t,n){if(t){let r=this.#c,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((e,t)=>e!==r[t]));return(this.#t!==this.#s||i||t!==this.#o)&&(this.#o=t,this.#s=this.#t,n!==void 0&&(this.#c=n),this.#a=om(this.#a,t(e))),this.#a}return e}#f(){return!this.#r?.combine||this.#i.some((e,t)=>e.options.suspense&&this.#t[t]?.data===void 0)}#p(e){let t=new Map;this.#i.forEach(e=>{let n=e.options.queryHash;if(!n)return;let r=t.get(n);r?r.push(e):t.set(n,[e])});let n=[];return e.forEach(e=>{let r=this.#e.defaultQueryOptions(e),i=t.get(r.queryHash)?.shift()??new Hm(this.#e,r);n.push({defaultedQueryOptions:r,observer:i})}),n}#m(e,t){let n=this.#i.indexOf(e);n!==-1&&(this.#t=this.#t.slice(),this.#t[n]=t,this.#h())}#h(){if(this.hasListeners()){let e=this.#f(),t=this.#a,n=e?t:this.#d(this.#u(this.#t,this.#l),this.#r?.combine);(e||t!==n)&&Em.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}},nh=class extends Sm{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??nm(r,t),a=this.get(i);return a||(a=new Rm({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){this.#e.get(e.queryHash)===e&&(e.destroy(),this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){Em.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>em(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>em(e,t)):t}notify(e){Em.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Em.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Em.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},rh=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new nh,this.#t=e.mutationCache||new Zm,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Cm.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=Dm.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime($p(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=Xp(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return Em.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;Em.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return Em.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=Em.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(Yp).catch(Yp)}invalidateQueries(e,t={}){return Em.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=Em.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(Yp)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(Yp)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime($p(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime($p(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Yp).catch(Yp)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Yp).catch(Yp)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return Dm.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(rm(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{im(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(rm(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{im(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=nm(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===gm&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},ih=o.createContext(!1),ah=()=>o.useContext(ih);ih.Provider;function oh(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var sh=o.createContext(oh()),ch=()=>o.useContext(sh),lh=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?vm(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},uh=e=>{o.useEffect(()=>{e.clearReset()},[e])},dh=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||vm(n,[e.error,r])),fh=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},ph=(e,t)=>e?.suspense&&t.isPending,mh=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function hh({queries:e,...t},n){let r=Up(n),i=ah(),a=ch(),s=t.subscribed!==!1,c=o.useMemo(()=>e.map(e=>{let t=r.defaultQueryOptions(e);return t._optimisticResults=i?`isRestoring`:s?`optimistic`:void 0,t}),[e,r,i,s]);c.forEach(e=>{fh(e);let t=r.getQueryCache().get(e.queryHash);lh(e,a,t)}),uh(a);let[l]=o.useState(()=>new th(r,c,t)),[u,d,f]=l.getOptimisticResult(c,t.combine),p=!i&&s;o.useSyncExternalStore(o.useCallback(e=>p?l.subscribe(Em.batchCalls(e)):Yp,[l,p]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),o.useEffect(()=>{l.setQueries(c,t)},[c,t,l]);let m=u.some((e,t)=>ph(c[t],e))?u.flatMap((e,t)=>{let n=c[t];return n&&ph(n,e)?mh(n,new Hm(r,n),a):[]}):[];if(m.length>0)throw Promise.all(m);let h=u.find((e,t)=>{let n=c[t];return n&&dh({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(h)throw h.error;return d(f())}function gh(e,t,n){let r=ah(),i=ch(),a=Up(n),s=a.defaultQueryOptions(e),c=a.getQueryCache().get(s.queryHash),l=e.subscribed!==!1;s._optimisticResults=r?`isRestoring`:l?`optimistic`:void 0,fh(s),lh(s,i,c),uh(i);let[u]=o.useState(()=>new t(a,s)),d=u.getOptimisticResult(s),f=!r&&l;if(o.useSyncExternalStore(o.useCallback(e=>{let t=f?u.subscribe(Em.batchCalls(e)):Yp;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),o.useEffect(()=>{u.setOptions(s)},[s,u]),ph(s,d))throw mh(s,u,i);if(dh({result:d,errorResetBoundary:i,throwOnError:s.throwOnError,query:c,suspense:s.suspense}))throw d.error;return s.notifyOnChangeProps?d:u.trackResult(d)}function _h(e,t){return gh(e,Hm,t)}function vh(e,t){let n=Up(t),[r]=o.useState(()=>new $m(n,e));o.useEffect(()=>{r.setOptions(e)},[r,e]);let i=o.useSyncExternalStore(o.useCallback(e=>r.subscribe(Em.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=o.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(Yp)},[r]);if(i.error&&vm(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function yh(e,t){return gh(e,Jm,t)}var $te=()=>{let e=0;return{refetchOnWindowFocus:()=>e>0?!1:`always`,pause:()=>{e+=1;let t=!1;return()=>{t||(t=!0,--e)}}}},bh=(0,o.createContext)(null),ene=e=>{let t=(0,o.useContext)(bh);(0,o.useEffect)(()=>e&&t?t.pause():void 0,[e,t])},tne=e=>{let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),window.addEventListener(`focus`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t),window.removeEventListener(`focus`,t)}},G={meta:[`meta`],sourceMeta:(e,t)=>[`source-meta`,e,t.join(`,`)],sourceMetas:e=>[`source-meta`,e],list:(e,t,n,r,i)=>[`list`,e,t,n,r,i],page:(e,t,n,r,i)=>[`page`,e,t,n,r,i],pages:(e,t,n)=>[`page`,e,t,n],navRecent:(e,t,n,r)=>[`list`,e,t,n,r,`nav-recent`],first:(e,t,n)=>[`first-page`,e,t,n],record:(e,t)=>[`record`,e,t],recordPreview:(e,t)=>[`record-preview`,e,t],history:(e,t,n)=>[`record`,e,t,`history`,n],facets:(e,t,n)=>[`facets`,e,t,n],series:(e,t,n,r,i)=>[`series`,e,t,n,r,i],aggregate:(e,t)=>[`aggregate`,e,t],histogram:(e,t,n,r)=>[`histogram`,e,t,n,r],map:(e,t,n,r,i)=>[`map`,e,t,n,r,i],relatedLabel:(e,t)=>[`related-label`,e,t],labels:(e,t)=>[`labels`,e,t],count:(e,t)=>[`count`,e,t],exportCount:(e,t)=>[`list`,e,t,`export-count`],firstRecord:(e,t,n)=>[`first-record`,e,t,n],pathValue:(e,t,n)=>[`path-value`,e,t,n]},xh=(0,o.createContext)(null),Sh=(0,o.createContext)(null),Ch=(0,o.createContext)(null),K=()=>{let e=(0,o.useContext)(xh);if(!e)throw Error(`useClient must be used inside ApiProvider`);return e},wh=e=>{let t=K();return(0,o.useContext)(Ch)?.(e)??t},nne=()=>{let e=K(),t=(0,o.useContext)(Ch);return(0,o.useCallback)(n=>t?.(n)??e,[e,t])},rne=()=>{let e=(0,o.useContext)(Sh);if(!e)throw Error(`useSourceClients must be used inside ApiProvider`);return e},ine=({client:e,resourceClient:t,children:n})=>(0,H.jsx)(xh.Provider,{value:e,children:(0,H.jsx)(Ch.Provider,{value:t,children:n})}),Th=({baseUrl:e,client:t,sources:n,fetch:r,queryClient:i,token:a,onUnauthenticated:s,children:c})=>{let[l]=(0,o.useState)($te),[u]=(0,o.useState)(()=>i??new rh({defaultOptions:{queries:{staleTime:3e4,retry:!1,refetchOnWindowFocus:l.refetchOnWindowFocus}}}));(0,o.useEffect)(()=>Cm.setEventListener(tne),[]);let d=(0,o.useRef)(void 0),f=(0,o.useMemo)(()=>t??qs({baseUrl:e,fetch:r,token:a,onUnauthenticated:s,onMetaVersion:e=>{let t=d.current;d.current=e,t!==void 0&&t!==e&&u.invalidateQueries({queryKey:G.meta},{cancelRefetch:!1})}}),[t,e,r,u,a,s]),p=(0,o.useMemo)(()=>{let e=new Map;return t=>{let i=n?.[t.url]??e.get(t.url);if(i)return i;let o,s=qs({baseUrl:t.url,fetch:r,token:a,onMetaVersion:e=>{let n=o;o=e,n!==void 0&&n!==e&&u.invalidateQueries({queryKey:G.sourceMetas(t.url)},{cancelRefetch:!1})}});return e.set(t.url,s),s}},[n,r,a,u]);return(0,H.jsx)(Wp,{client:u,children:(0,H.jsx)(xh.Provider,{value:f,children:(0,H.jsx)(Sh.Provider,{value:p,children:(0,H.jsx)(bh.Provider,{value:l,children:c})})})})},Eh=(0,o.createContext)(null),Dh=()=>{let e=(0,o.useContext)(Eh);if(!e)throw Error(`useRouter must be used inside Router`);return e},Oh=()=>`${window.location.pathname}${window.location.search}`,kh=e=>new URL(e,`http://local`).pathname,Ah=()=>window.history.state?.protobaseIndex??0,ane=({basePath:e=``,initialUrl:t,children:n})=>{let r=t!==void 0,[i,a]=(0,o.useState)(t??Oh()),s=(0,o.useRef)(new Set),c=(0,o.useRef)(i);c.current=i;let l=(0,o.useRef)(r?0:Ah()),u=(0,o.useRef)(!1),d=(0,o.useRef)(!1),[f,p]=(0,o.useState)();(0,o.useEffect)(()=>{if(r)return;window.history.replaceState({protobaseIndex:l.current},``);let e=()=>{let e=Ah();if(u.current){u.current=!1,l.current=e;return}let t=e-l.current,n=kh(Oh())!==kh(c.current);if(!d.current&&s.current.size>0&&n){u.current=!0,window.history.go(-t),p({kind:`history`,delta:t});return}d.current=!1,l.current=e,a(Oh())};return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[r]);let m=(0,o.useCallback)((e,t)=>{r||(l.current+=+!t,window.history[t?`replaceState`:`pushState`]({protobaseIndex:l.current},``,e)),a(e)},[r]),h=(0,o.useCallback)((t,{replace:n=!1}={})=>{let r=`${e}${t}`;if(kh(r)!==kh(c.current)&&s.current.size>0)return p({kind:`link`,full:r,replace:n});m(r,n)},[e,m]),g=(0,o.useCallback)(()=>{let e=Symbol(`guard`);return s.current.add(e),()=>void s.current.delete(e)},[]),_=()=>{if(f){if(p(void 0),f.kind===`link`)return m(f.full,f.replace);d.current=!0,window.history.go(f.delta)}},v=(0,o.useMemo)(()=>{let t=new URL(i,`http://local`);return{path:t.pathname.slice(e.length)||`/`,params:t.searchParams,basePath:e,entry:l.current,navigate:h,registerGuard:g}},[i,e,h,g]);return(0,H.jsxs)(Eh.Provider,{value:v,children:[n,f&&(0,H.jsx)(Sf,{title:`Leave without saving?`,description:`You have unsaved changes on this page. They stay in this browser, and come back when you open the record again.`,onClose:()=>p(void 0),actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:()=>p(void 0),children:`Stay`}),(0,H.jsx)(W,{variant:`primary`,onClick:_,children:`Leave`})]})})]})},one=({to:e,replace:t,...n})=>{let{navigate:r,basePath:i}=Dh();return(0,H.jsx)(Mu,{to:{href:`${i}${e}`,onFollow:()=>r(e,{replace:t})},...n})},sne=e=>{let{registerGuard:t}=Dh();(0,o.useEffect)(()=>e?t():void 0,[e,t]),(0,o.useEffect)(()=>{if(!e)return;let t=e=>e.preventDefault();return window.addEventListener(`beforeunload`,t),()=>window.removeEventListener(`beforeunload`,t)},[e])},jh=({title:e,description:t,children:n})=>(0,H.jsx)(`div`,{className:`flex min-h-full w-full items-center justify-center bg-surface px-4 py-10`,children:(0,H.jsxs)(`div`,{className:`w-full max-w-sm`,children:[(0,H.jsxs)(`div`,{className:`mb-6 flex flex-col items-center text-center`,children:[(0,H.jsx)(Iu,{className:`size-10`}),(0,H.jsx)(`h1`,{className:`mt-4 text-xl font-semibold tracking-tight`,children:e}),t&&(0,H.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:t})]}),(0,H.jsx)(`div`,{className:`rounded-lg border bg-background p-5 shadow-sm`,children:n})]})}),Mh=({onResend:e,cooldown:t=30,disabled:n})=>{let[r,i]=(0,o.useState)(()=>Date.now()+t*1e3),[a,s]=(0,o.useState)(()=>Date.now()),c=Math.max(0,Math.ceil((r-a)/1e3));return(0,o.useEffect)(()=>{if(c===0)return;let e=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(e)},[c]),(0,H.jsx)(W,{variant:`ghost`,disabled:n||c>0,onClick:()=>{let n=Date.now();i(n+t*1e3),s(n),e()},className:`min-h-10`,children:c>0?`Send a new code in ${c}s`:`Send a new code`})},Nh=({title:e,description:t,explanation:n,submitLabel:r,onSubmit:i,onResend:a,onChangeAddress:s,changeAddressLabel:c,busy:l,error:u,notice:d,resendCooldown:f})=>{let[p,m]=(0,o.useState)(``);return(0,H.jsxs)(jh,{title:e,description:t,children:[(0,H.jsx)(`p`,{className:`mb-4 text-muted-foreground`,children:n}),d&&(0,H.jsx)(`p`,{role:`status`,className:`mb-4 rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:d}),(0,H.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),i(p)},children:[(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Code`,(0,H.jsx)(Pf,{name:`code`,required:!0,autoFocus:!0,value:p,invalid:!!u,onChange:m,onComplete:e=>!l&&i(e)})]}),u&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:u}),(0,H.jsx)(W,{variant:`primary`,type:`submit`,loading:l,className:`min-h-10`,children:r}),(0,H.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-x-2 sm:justify-between`,children:[(0,H.jsx)(W,{variant:`ghost`,onClick:s,className:`min-h-10`,children:c}),(0,H.jsx)(Mh,{onResend:a,disabled:l,cooldown:f})]})]})]})},cne=({email:e,onBack:t,...n})=>(0,H.jsx)(Nh,{title:`Check your email`,description:`Enter the code we sent to sign in.`,explanation:(0,H.jsxs)(H.Fragment,{children:[`If `,(0,H.jsx)(`span`,{className:`font-medium text-foreground`,children:e}),` has an account, a 6-digit code is on its way. It works for 5 minutes, once.`]}),submitLabel:`Sign in`,onChangeAddress:t,changeAddressLabel:`Back to sign in`,...n}),lne=({email:e,onBack:t})=>{let{signInWithCode:n,sendSignInCode:r}=U(),[i,a]=(0,o.useState)(!1),[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(),d=async e=>{a(!0),c(void 0),u(void 0);try{await e()}catch(e){if(!(e instanceof lc))throw e;c(zd(e))}a(!1)};return(0,H.jsx)(cne,{email:e,busy:i,error:s,notice:l,onBack:t,onSubmit:t=>void d(()=>n(e,t)),onResend:()=>void d(async()=>{await r(e),u(`A new code is on its way. Only the newest one works.`)})})},une=`protobase users create you@example.com`,dne=({command:e=une,onCheckAgain:t,busy:n})=>{let[r,i]=(0,o.useState)(!1);return(0,H.jsxs)(jh,{title:`No admin yet`,description:`This Protobase has no users to sign in with.`,children:[(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:`Run this in the terminal where Protobase runs, then reload. The first admin is created on the server, not in the browser, so nobody else can claim a fresh URL.`}),(0,H.jsxs)(`div`,{className:`mt-4 flex items-center gap-2 rounded-md border bg-surface py-1.5 pl-3 pr-1.5`,children:[(0,H.jsx)(`code`,{className:`min-w-0 flex-1 break-all font-mono text-xs`,children:e}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Copy command`,onClick:()=>{navigator.clipboard.writeText(e).then(()=>{i(!0),setTimeout(()=>i(!1),2e3)})},className:`inline-flex size-8 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted pointer-coarse:size-11`,children:r?(0,H.jsx)(he,{className:`size-4 text-success`}):(0,H.jsx)(Le,{className:`size-4`})})]}),(0,H.jsx)(W,{variant:`primary`,className:`mt-4 min-h-10 w-full`,loading:n,onClick:t,children:`Reload`})]})},fne=({onSubmit:e,back:t,busy:n,error:r,sentTo:i})=>{let[a,s]=(0,o.useState)(``);return i?(0,H.jsxs)(jh,{title:`Check your email`,children:[(0,H.jsxs)(`p`,{className:`text-muted-foreground`,children:[`If `,(0,H.jsx)(`span`,{className:`font-medium text-foreground`,children:i}),` has an account, an email with a link to choose a new password is on its way. The link works once, for a limited time.`]}),(0,H.jsx)(Mu,{to:t,className:V(xf({variant:`primary`}),`mt-4 min-h-10 w-full`),children:`Back to sign in`})]}):(0,H.jsx)(jh,{title:`Reset your password`,description:`We email you a link to choose a new one.`,children:(0,H.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),e(a.trim())},children:[(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Email`,(0,H.jsx)(wd,{type:`email`,name:`email`,autoComplete:`username`,required:!0,autoFocus:!0,value:a,invalid:!!r,onChange:e=>s(e.target.value),className:`min-h-6`})]}),r&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:r}),(0,H.jsx)(W,{variant:`primary`,type:`submit`,loading:n,className:`min-h-10`,children:`Send reset link`}),(0,H.jsx)(Mu,{to:t,className:V(xf({variant:`ghost`}),`min-h-10`),children:`Back to sign in`})]})})},Ph=`password-reset`,pne=e=>{let t=new URL(e);return`${t.origin}${t.pathname}?${Ph}`},mne=e=>{let t=new URL(e).searchParams;if(t.has(`password-reset`))return{token:t.get(`token`)||void 0}},hne=e=>{let t=new URL(e);for(let e of[Ph,`token`,`error`])t.searchParams.delete(e);return`${t.pathname}${t.search}${t.hash}`},gne=({back:e})=>{let{session:t}=U(),[n,r]=(0,o.useState)(!1),[i,a]=(0,o.useState)(),[s,c]=(0,o.useState)(),l=async e=>{r(!0),a(void 0);try{await t.requestPasswordReset(e,pne(window.location.href)),c(e)}catch(e){if(!(e instanceof lc))throw e;a(e.status===429?`Too many requests. Wait a minute and try again.`:e.message)}r(!1)};return(0,H.jsx)(fne,{busy:n,error:i,sentTo:s,back:e,onSubmit:e=>void l(e)})},_ne=({name:e,workspace:t})=>(0,H.jsx)(jh,{title:`Signing in with ${e}`,description:t,children:(0,H.jsxs)(`p`,{role:`status`,className:`flex items-center justify-center gap-2 text-muted-foreground`,children:[(0,H.jsx)(Ed,{}),` Taking you to `,e,`…`]})}),vne=({provider:e,workspace:t,onFailed:n})=>{let{signInProviders:r,signInSocial:i}=U(),a=r.find(t=>t.id===e),s=a?.name??Zd(e),c=(0,o.useRef)(!1);return(0,o.useEffect)(()=>{if(!c.current){if(c.current=!0,!a)return n(`Signing in with ${s} is not offered here. Sign in another way.`);i(e).catch(e=>{if(!(e instanceof lc))throw e;n(Bd(e))})}},[a,s,e,i,n]),(0,H.jsx)(_ne,{name:s,workspace:t})},yne=({onSubmit:e,invalidLink:t,onRequestNewLink:n,onBack:r,busy:i,error:a})=>{let[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(``),[d,f]=(0,o.useState)(!1);if(t)return(0,H.jsxs)(jh,{title:`This link no longer works`,children:[(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:`A reset link works once, for a limited time. Ask for a new one to choose your password.`}),(0,H.jsxs)(`div`,{className:`mt-4 flex flex-col gap-2`,children:[n&&(0,H.jsx)(W,{variant:`primary`,className:`min-h-10`,onClick:n,children:`Send a new link`}),(0,H.jsx)(W,{variant:n?`ghost`:`primary`,className:`min-h-10`,onClick:r,children:`Back to sign in`})]})]});let p=d?`The passwords are not the same.`:a;return(0,H.jsx)(jh,{title:`Choose a new password`,description:`At least 12 characters.`,children:(0,H.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),f(s!==l),s===l&&e(s)},children:[(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`New password`,(0,H.jsx)(wd,{type:`password`,name:`new-password`,autoComplete:`new-password`,required:!0,minLength:12,autoFocus:!0,value:s,invalid:!!p,onChange:e=>c(e.target.value),className:`min-h-6`})]}),(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Repeat new password`,(0,H.jsx)(wd,{type:`password`,name:`repeat-password`,autoComplete:`new-password`,required:!0,minLength:12,value:l,invalid:!!p,onChange:e=>u(e.target.value),className:`min-h-6`})]}),p&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:p}),(0,H.jsx)(W,{variant:`primary`,type:`submit`,loading:i,className:`min-h-10`,children:`Set new password`})]})})},bne=e=>e.status===429?`Too many attempts. Wait a minute and try again.`:e.code===`PASSWORD_TOO_SHORT`?`Use at least 12 characters.`:e.code===`PASSWORD_TOO_LONG`?`That password is too long.`:e.message,xne=({token:e,onDone:t,onRequestNewLink:n,onBack:r})=>{let{session:i}=U(),[a,s]=(0,o.useState)(!1),[c,l]=(0,o.useState)(),[u,d]=(0,o.useState)(!e),f=async n=>{s(!0),l(void 0);try{await i.resetPassword(e,n),t()}catch(e){if(!(e instanceof lc))throw e;e.code===`INVALID_TOKEN`?d(!0):l(bne(e)),s(!1)}};return(0,H.jsx)(yne,{busy:a,error:c,invalidLink:u,onRequestNewLink:n,onBack:r,onSubmit:e=>void f(e)})},Sne={twoFactor:`Turn on two-factor authentication`,passkey:`Add a passkey`},Cne=({step:e,twoFactor:t,onAddPasskey:n,busy:r,error:i,onSignOut:a})=>(0,H.jsxs)(jh,{title:Sne[e],description:`This app requires it for every account.`,children:[e===`twoFactor`?(0,H.jsx)(Tp,{...t}):(0,H.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:`A passkey signs you in with Face ID, Touch ID, Windows Hello, your phone or a security key. Your browser asks which one to use.`}),i&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:i}),(0,H.jsxs)(W,{variant:`primary`,loading:r,onClick:n,className:`min-h-10`,children:[(0,H.jsx)(gt,{className:`size-4`}),`Add a passkey`]})]}),(0,H.jsx)(`button`,{type:`button`,onClick:a,className:`mt-4 w-full text-center font-medium text-muted-foreground hover:underline`,children:`Sign out`})]}),wne=({missing:e})=>{let{session:t,recheck:n,signOut:r}=U(),[i,a]=(0,o.useState)(),[s,c]=(0,o.useState)(!1),[l,u]=(0,o.useState)();(0,o.useEffect)(()=>{t.account.signInMethods().then(a,e=>u(e instanceof lc?zd(e):`Could not read your account`))},[t]);let d=async()=>{c(!0),u(void 0);try{await t.account.addPasskey(),n()}catch(e){if(!(e instanceof lc))throw e;u(zd(e)),c(!1)}};return!i&&!l?(0,H.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,H.jsx)(Ed,{}),` Loading`]}):(0,H.jsx)(Cne,{step:e[0],busy:s,error:l,onAddPasskey:()=>void d(),onSignOut:()=>void r(),twoFactor:{offerEmailedCodes:i?.mail??!1,needsPassword:i?.account.password??!0,onStartApp:e=>t.account.startAuthenticatorApp(e),onConfirmApp:e=>t.account.confirmAuthenticatorApp(e),onEmailedCodes:e=>t.account.turnOnEmailedCodes(e),onDone:n}})},Tne=({className:e})=>(0,H.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`currentColor`,className:V(`size-4 shrink-0`,e),"aria-hidden":!0,children:(0,H.jsx)(`path`,{d:`M10.226 17.284c-2.965-.36-5.054-2.493-5.054-5.256 0-1.123.404-2.336 1.078-3.144-.292-.741-.247-2.314.09-2.965.898-.112 2.111.36 2.83 1.01.853-.269 1.752-.404 2.853-.404 1.1 0 1.999.135 2.807.382.696-.629 1.932-1.1 2.83-.988.315.606.36 2.179.067 2.942.72.854 1.101 2 1.101 3.167 0 2.763-2.089 4.852-5.098 5.234.763.494 1.28 1.572 1.28 2.807v2.336c0 .674.561 1.056 1.235.786 4.066-1.55 7.255-5.615 7.255-10.646C23.5 6.188 18.334 1 11.978 1 5.62 1 .5 6.188.5 12.545c0 4.986 3.167 9.12 7.435 10.669.606.225 1.19-.18 1.19-.786V20.63a2.9 2.9 0 0 1-1.078.224c-1.483 0-2.359-.808-2.987-2.313-.247-.607-.517-.966-1.034-1.033-.27-.023-.359-.135-.359-.27 0-.27.45-.471.898-.471.652 0 1.213.404 1.797 1.235.45.651.921.943 1.483.943.561 0 .92-.202 1.437-.719.382-.381.674-.718.944-.943`})}),Ene=({id:e,className:t})=>e===`github`?(0,H.jsx)(Tne,{className:t}):null,Dne=()=>(0,H.jsxs)(`div`,{className:`my-4 flex items-center gap-3 text-xs text-muted-foreground`,children:[(0,H.jsx)(`span`,{className:`h-px flex-1 bg-border`}),`or`,(0,H.jsx)(`span`,{className:`h-px flex-1 bg-border`})]}),One=({onSubmit:e,busy:t,error:n,workspace:r,notice:i,methods:a=[`password`],onSendCode:s,onPasskey:c,passkeyDomains:l=[],forgotPassword:u,providers:d=[],onContinueWith:f,signUp:p,onBrowse:m})=>{let[h,g]=(0,o.useState)(``),[_,v]=(0,o.useState)(``),y=(0,o.useRef)(null),b=a.includes(`password`),x=a.includes(`emailCode`)&&s!==void 0,S=a.includes(`passkey`)&&c!==void 0,C=f?d:[],w=()=>{y.current?.reportValidity()&&s?.(h.trim())};return(0,H.jsxs)(jh,{title:`Sign in to Protobase`,description:r,children:[i&&(0,H.jsx)(`p`,{role:`status`,className:`mb-4 rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:i}),(C.length>0||S)&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[C.map(e=>(0,H.jsxs)(W,{onClick:()=>f?.(e.id),disabled:t,className:`min-h-10 w-full`,children:[(0,H.jsx)(Ene,{id:e.id}),`Continue with `,e.name]},e.id)),S&&(0,H.jsxs)(W,{onClick:()=>c?.(),disabled:t,className:`min-h-10 w-full`,children:[(0,H.jsx)(gt,{className:`size-4`}),`Sign in with a passkey`]}),S&&l.slice(1).map(e=>(0,H.jsxs)(W,{variant:`ghost`,size:`sm`,onClick:()=>c?.(e),disabled:t,className:`w-full`,children:[`Use a passkey made for `,e]},e))]}),b||x?(0,H.jsx)(Dne,{}):n&&(0,H.jsx)(`p`,{role:`alert`,className:`mt-4 text-xs font-medium text-danger-text`,children:n})]}),(b||x)&&(0,H.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),b?e(h.trim(),_):w()},children:[(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Email`,(0,H.jsx)(wd,{ref:y,type:`email`,name:`email`,autoComplete:`username webauthn`,required:!0,autoFocus:!0,value:h,invalid:!!n,onChange:e=>g(e.target.value),className:`min-h-6`})]}),b&&(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Password`,(0,H.jsx)(wd,{type:`password`,name:`password`,autoComplete:`current-password`,required:!0,value:_,invalid:!!n,onChange:e=>v(e.target.value),className:`min-h-6`})]}),n&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:n}),b&&(0,H.jsx)(W,{variant:`primary`,type:`submit`,loading:t,className:`min-h-10`,children:`Sign in`}),x&&(0,H.jsxs)(W,{variant:b?`secondary`:`primary`,type:b?`button`:`submit`,onClick:b?w:void 0,loading:t&&!b,disabled:t,className:`min-h-10`,children:[(0,H.jsx)(zt,{className:`size-4`}),`Email me a sign-in code`]}),b&&u&&(0,H.jsx)(Mu,{to:u,className:`self-center font-medium text-primary-text hover:underline`,children:`Forgot password?`})]}),p&&(0,H.jsxs)(`p`,{className:`mt-4 text-center text-muted-foreground`,children:[`New here?`,` `,(0,H.jsx)(Mu,{to:p,className:`font-medium text-primary-text hover:underline`,children:`Create an account`})]}),m&&(0,H.jsx)(`button`,{type:`button`,onClick:m,className:`mt-4 w-full text-center font-medium text-muted-foreground hover:text-foreground hover:underline`,children:`Continue without signing in`})]})},kne=({workspace:e,notice:t,forgotPassword:n,signUp:r,onBrowse:i,onCodeSent:a,error:s})=>{let{signIn:c,signInSocial:l,signInProviders:u,signInMethods:d,passkeyDomains:f,sendSignInCode:p,signInWithPasskey:m}=U(),[h,g]=(0,o.useState)(!1),[_,v]=(0,o.useState)(s),y=async(e,t)=>{g(!0),v(void 0);try{await e()}catch(e){if(!(e instanceof lc))throw e;v(t(e)),g(!1)}};return(0,H.jsx)(One,{busy:h,error:_,workspace:e,notice:t,methods:d,forgotPassword:n,signUp:r,onBrowse:i,providers:u,onContinueWith:e=>void y(()=>l(e),Bd),passkeyDomains:f,onPasskey:e=>void y(()=>m(e),zd),onSendCode:e=>void y(async()=>{await p(e),a(e)},zd),onSubmit:(e,t)=>void y(()=>c(e,t),Bd)})},Ane=({email:e,onBack:t,...n})=>(0,H.jsx)(Nh,{title:`Check your email`,description:`Enter the code we sent to create your account.`,explanation:(0,H.jsxs)(H.Fragment,{children:[`A 6-digit code is on its way to `,(0,H.jsx)(`span`,{className:`font-medium text-foreground`,children:e}),`. It works for 5 minutes, once. If the address has an account already, the email says so instead.`]}),submitLabel:`Continue`,onChangeAddress:t,changeAddressLabel:`Use another address`,...n}),jne=({email:e,onSubmit:t,onBack:n,methods:r,busy:i,error:a})=>{let[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(``),d=(0,o.useId)(),f=r.includes(`password`),p=r.includes(`emailCode`);return(0,H.jsxs)(jh,{title:`Your details`,description:`One last step to create your account.`,children:[(0,H.jsxs)(`p`,{className:`mb-4 text-muted-foreground`,children:[`The code was right: the account is for `,(0,H.jsx)(`span`,{className:`font-medium text-foreground`,children:e}),`.`]}),(0,H.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),t({name:s.trim(),...f&&l&&{password:l}})},children:[(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Your name`,(0,H.jsx)(wd,{name:`name`,autoComplete:`name`,required:!0,autoFocus:!0,maxLength:200,value:s,onChange:e=>c(e.target.value),className:`min-h-6`})]}),f&&(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[p?`Password (optional)`:`Password`,(0,H.jsx)(wd,{type:`password`,name:`password`,autoComplete:`new-password`,"aria-describedby":d,required:!p,minLength:12,maxLength:128,value:l,onChange:e=>u(e.target.value),className:`min-h-6`})]}),(0,H.jsxs)(`p`,{id:d,className:`text-xs text-muted-foreground`,children:[`At least `,12,` characters.`,p&&` Without one, you sign in with a code we email you.`]})]}),a&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:a}),(0,H.jsx)(W,{variant:`primary`,type:`submit`,loading:i,className:`min-h-10`,children:`Create account`}),(0,H.jsx)(W,{variant:`ghost`,onClick:n,className:`min-h-10`,children:`Use another address`})]})]})},Mne=({onSubmit:e,onSignIn:t,onBrowse:n,busy:r,error:i,workspace:a})=>{let[s,c]=(0,o.useState)(``);return(0,H.jsxs)(jh,{title:`Create an account`,description:a,children:[(0,H.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),e(s.trim())},children:[(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Email`,(0,H.jsx)(wd,{type:`email`,name:`email`,autoComplete:`email`,required:!0,autoFocus:!0,value:s,invalid:!!i,onChange:e=>c(e.target.value),className:`min-h-6`})]}),(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:`We email you a code to make sure the address is yours.`}),i&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:i}),(0,H.jsxs)(W,{variant:`primary`,type:`submit`,loading:r,className:`min-h-10`,children:[(0,H.jsx)(zt,{className:`size-4`}),`Email me a code`]}),(0,H.jsxs)(`p`,{className:`text-center text-muted-foreground`,children:[`Have an account?`,` `,(0,H.jsx)(`button`,{type:`button`,onClick:t,className:`font-medium text-primary-text hover:underline`,children:`Sign in`})]})]}),n&&(0,H.jsx)(`button`,{type:`button`,onClick:n,className:`mt-4 w-full text-center font-medium text-muted-foreground hover:text-foreground hover:underline`,children:`Continue without an account`})]})},Nne=({workspace:e,email:t,ticket:n,onCodeSent:r,onVerified:i,onBack:a,onSignIn:s,onBrowse:c})=>{let{signInMethods:l,sendSignUpCode:u,verifySignUpCode:d,signUp:f}=U(),[p,m]=(0,o.useState)(!1),[h,g]=(0,o.useState)(),[_,v]=(0,o.useState)(),y=async e=>{m(!0),g(void 0),v(void 0);try{await e()}catch(e){if(!(e instanceof lc))throw e;g(zd(e))}m(!1)};return t===void 0?(0,H.jsx)(Mne,{workspace:e,busy:p,error:h,onSignIn:s,onBrowse:c,onSubmit:e=>void y(async()=>{await u(e),r(e)})}):n===void 0?(0,H.jsx)(Ane,{email:t,busy:p,error:h,notice:_,onBack:a,onSubmit:e=>void y(async()=>i(await d(t,e))),onResend:()=>void y(async()=>{await u(t),v(`A new code is on its way. Only the newest one works.`)})}):(0,H.jsx)(jne,{email:t,methods:l,busy:p,error:h,onBack:a,onSubmit:e=>void y(()=>f({ticket:n,...e}))})},Fh=`staff-sign-in`,Ih=`staff-error`,Pne=e=>{let t=new URL(e).searchParams,n=t.get(Ih);if(!t.has(`staff-sign-in`)&&!n)return;let r=t.has(Fh);return{email:r&&t.get(`email`)||``,reason:r&&t.get(`reason`)||``,...n&&{error:n}}},Lh=e=>{let t=new URL(e);if(t.searchParams.has(`staff-sign-in`))for(let e of[Fh,`email`,`reason`])t.searchParams.delete(e);return t.searchParams.delete(Ih),`${t.pathname}${t.search}${t.hash}`},Fne=10,Ine=({operator:e,email:t=``,reason:n=``,onSubmit:r,onBack:i,busy:a,error:s})=>{let[c,l]=(0,o.useState)(t),[u,d]=(0,o.useState)(n);return e?(0,H.jsx)(jh,{title:`Sign in as a person`,description:`For staff of ${e}, to help someone with this app.`,children:(0,H.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),r(c.trim(),u.trim())},children:[(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Their email`,(0,H.jsx)(wd,{type:`email`,name:`email`,required:!0,autoFocus:!t,value:c,onChange:e=>l(e.target.value),className:`min-h-6`})]}),(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Reason`,(0,H.jsx)(`textarea`,{name:`reason`,required:!0,minLength:Fne,rows:3,value:u,placeholder:`Ticket 4211: the invoice totals look wrong`,onChange:e=>d(e.target.value),className:V(`resize-y rounded-md border bg-background px-2.5 py-1.5 font-normal shadow-sm outline-none placeholder:text-faint-foreground focus:border-primary focus:ring-2 focus:ring-primary/20`,s?`border-danger`:`border-border-strong`)})]}),(0,H.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`You sign in at `,e,` with a passkey or a second step. The session is short, shows a banner, and cannot change their sign-in. The app's admins see who signed in as whom, and why.`]}),s&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:s}),(0,H.jsxs)(W,{variant:`primary`,type:`submit`,loading:a,className:`min-h-10`,children:[`Continue with `,e]}),(0,H.jsx)(W,{variant:`ghost`,onClick:i,className:`min-h-10`,children:`Back to sign in`})]})}):(0,H.jsxs)(jh,{title:`Staff sign-in`,description:`Staff of the team that runs this app cannot sign in as people here.`,children:[s&&(0,H.jsx)(`p`,{role:`alert`,className:`mb-4 text-xs font-medium text-danger-text`,children:s}),(0,H.jsx)(W,{variant:`primary`,className:`min-h-10 w-full`,onClick:i,children:`Back to sign in`})]})},Lne=({link:e,onBack:t})=>{let{session:n,staffSignIn:r}=U(),[i,a]=(0,o.useState)(!1),[s,c]=(0,o.useState)(e.error&&Hd(e.error)),l=async(e,t)=>{a(!0),c(void 0);try{let r=`${window.location.origin}${Lh(window.location.href)}`;window.location.assign(await n.staff.start({email:e,reason:t,callbackURL:r}))}catch(e){if(!(e instanceof lc))throw e;c(Hd(e)),a(!1)}};return(0,H.jsx)(Ine,{operator:r,email:e.email,reason:e.reason,busy:i,error:s,onBack:t,onSubmit:(e,t)=>void l(e,t)})},Rh=({checked:e,indeterminate:t,onChange:n,label:r,disabled:i,className:a})=>(0,H.jsx)(`button`,{type:`button`,role:`checkbox`,"aria-checked":t?`mixed`:e,"aria-label":r,disabled:i,onClick:()=>n?.(!e),className:V(`relative inline-flex size-4 shrink-0 items-center justify-center rounded border transition-colors after:absolute after:-inset-1 after:content-[""] pointer-coarse:after:-inset-3.5`,e||t?`border-primary bg-primary text-primary-foreground`:`border-border-strong bg-background hover:border-faint-foreground`,a),children:t?(0,H.jsx)(iee,{className:`size-3`,strokeWidth:3}):e&&(0,H.jsx)(he,{className:`size-3`,strokeWidth:3})}),Rne={totp:`Enter the 6-digit code from your authenticator app.`,otp:`Enter the 6-digit code we emailed you. It works for 5 minutes.`,backup:`Enter one of the backup codes you saved when you set up the authenticator app. Each works once.`},zne=({methods:e,onVerify:t,onSendCode:n,onBack:r,busy:i,error:a,codeSent:s,initialStep:c})=>{let[l,u]=(0,o.useState)(c??(e.includes(`totp`)?`totp`:`otp`)),[d,f]=(0,o.useState)(``),[p,m]=(0,o.useState)(!1),h=l===`otp`&&!s,g=e=>{u(e),f(``),e===`otp`&&!s&&n()};return(0,H.jsxs)(jh,{title:`Two-factor authentication`,description:`One more step to sign in.`,children:[h?(0,H.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:`We email you a code to finish signing in.`}),a&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:a}),(0,H.jsx)(W,{variant:`primary`,loading:i,onClick:n,className:`min-h-10`,children:`Email me a code`})]}):(0,H.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),t({method:l,code:d.trim(),trustDevice:p})},children:[(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:Rne[l]}),(0,H.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[l===`backup`?`Backup code`:`Code`,l===`backup`?(0,H.jsx)(wd,{name:`code`,autoComplete:`off`,spellCheck:!1,required:!0,autoFocus:!0,value:d,invalid:!!a,onChange:e=>f(e.target.value),className:`min-h-6 font-mono`}):(0,H.jsx)(Pf,{name:`code`,required:!0,autoFocus:!0,value:d,invalid:!!a,onChange:f})]}),(0,H.jsxs)(`label`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,H.jsx)(Rh,{checked:p,onChange:m,label:`Trust this browser`}),`Don't ask again in this browser for 30 days`]}),a&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:a}),(0,H.jsx)(W,{variant:`primary`,type:`submit`,loading:i,className:`min-h-10`,children:`Verify`})]}),(0,H.jsxs)(`div`,{className:`mt-4 flex flex-col items-center gap-2 border-t pt-4`,children:[l!==`totp`&&e.includes(`totp`)&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>g(`totp`),className:`font-medium text-primary-text hover:underline`,children:`Use the authenticator app`}),l!==`otp`&&e.includes(`otp`)&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>g(`otp`),className:`font-medium text-primary-text hover:underline`,children:`Email me a code instead`}),l!==`backup`&&e.includes(`totp`)&&(0,H.jsx)(`button`,{type:`button`,onClick:()=>g(`backup`),className:`font-medium text-primary-text hover:underline`,children:`Use a backup code`}),(0,H.jsx)(`button`,{type:`button`,onClick:r,className:`font-medium text-muted-foreground hover:underline`,children:`Back to sign in`})]})]})},Bne=({methods:e,onBack:t})=>{let{verifyTwoFactor:n,session:r}=U(),[i,a]=(0,o.useState)(!1),[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(!1),d=async e=>{a(!0),c(void 0);try{await e()}catch(e){if(!(e instanceof lc))throw e;c(zd(e))}a(!1)};return(0,H.jsx)(zne,{methods:e,busy:i,error:s,codeSent:l,onBack:t,onVerify:e=>void d(()=>n(e)),onSendCode:()=>void d(async()=>{await r.sendTwoFactorCode(),u(!0)})})},zh=()=>{let{path:e,params:t,basePath:n,navigate:r}=Dh(),i=(0,o.useMemo)(()=>xs(e,t),[e,t]),a=Yd(new URL(t.size>0?`${e}?${t}`:e,`http://local`).href),s=i?i.next:a,c=(0,o.useCallback)((e=`sign-in`,t)=>r(bs({step:e,next:s}),t),[r,s]);return{address:i,next:s,open:c,link:(0,o.useCallback)((e=`sign-in`,t)=>({href:`${n}${bs({step:e,next:s})}`,onFollow:()=>c(e,t)}),[n,s,c]),leave:(0,o.useCallback)(()=>r(s??`/`,{replace:!0}),[r,s])}},Vne=e=>{let t=new URL(e),n=t.searchParams.get(`token`);return t.pathname.endsWith(`/-/invitation`)&&n?{token:n}:void 0},Hne=e=>`${new URL(e).pathname.slice(0,-13)}/`,Bh=`/-/organizations`,Vh=`/-/organization`,Hh=`/-/organization/members`,Uh=`/-/organization/invitations`,Une={[Bh]:`Organizations`,[Vh]:`Organization`,[Hh]:`Members`,[Uh]:`Invitations`},Wh={owner:`Owner`,admin:`Admin`,member:`Member`},Gh=(e,t)=>e.find(e=>e.name===t)?.label??t,Kh=e=>e?.role===`owner`||e?.role===`admin`,Wne=(e,t,n)=>{let r=(n,r,i,a)=>({id:n,label:r,icon:i,href:`${e}${a}`,active:t===a});return[r(`organizations`,`Organizations`,Jt,Bh),...n?.organization?[r(`organization`,`Organization`,le,Vh)]:[],...Kh(n)?[r(`members`,`Members`,qn,Hh),r(`invitations`,`Invitations`,zt,Uh)]:[]]},qh=(e,t)=>{let n=[...t?.globalRoles??[],...t?.appRoles??[]],r=e.filter(e=>e.membership).map(e=>e.name);if(n.includes(`admin`))return new Set(r);let i=n.flatMap(t=>e.find(e=>e.name===t)?.grants??[]);return new Set([...n,...i].filter(e=>r.includes(e)))},Jh=()=>{let[e,t]=(0,o.useState)(!1),[n,r]=(0,o.useState)();return{busy:e,error:n,run:async e=>{t(!0),r(void 0);try{await e()}catch(e){if(!(e instanceof lc))throw e;r(zd(e))}t(!1)},setError:r}},Gne=({token:e,preview:t,onDone:n})=>{let{session:r,signInMethods:i,recheck:a}=U(),[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(``),{busy:d,error:f,run:p}=Jh(),m=i.includes(`password`),h=i.includes(`emailCode`),g=()=>p(async()=>{await r.organizations.signUpFromInvitation(e,{name:s.trim(),...m&&l&&{password:l}}),n(),a()});return(0,H.jsxs)(`form`,{className:`flex flex-col gap-3`,onSubmit:e=>{e.preventDefault(),g()},children:[(0,H.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Make your account for `,t.email,` to join.`]}),f&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:f}),(0,H.jsx)(wd,{"aria-label":`Your name`,placeholder:`Your name`,autoComplete:`name`,value:s,onChange:e=>c(e.target.value)}),m&&(0,H.jsx)(wd,{"aria-label":`Password`,type:`password`,autoComplete:`new-password`,placeholder:h?`Password (optional, 12+ characters)`:`Password (12+ characters)`,value:l,onChange:e=>u(e.target.value)}),(0,H.jsx)(W,{type:`submit`,variant:`primary`,loading:d,disabled:!s.trim()||m&&!h&&l.length<12,children:`Create account and join`})]})},Kne=({token:e,onDone:t,signIn:n})=>{let{session:r,state:i,signOut:a,organizations:s}=U(),[c,l]=(0,o.useState)(),[u,d]=(0,o.useState)(),{busy:f,error:p,run:m}=Jh();if((0,o.useEffect)(()=>{r.organizations.invitation(e).then(l,e=>d(e instanceof lc?zd(e):`This invitation link is not valid`))},[r,e]),u)return(0,H.jsx)(jh,{title:`Invitation`,description:u,children:(0,H.jsx)(W,{className:`w-full`,onClick:t,children:`Go to the app`})});if(!c)return(0,H.jsx)(jh,{title:`Invitation`,children:(0,H.jsxs)(`div`,{className:`flex items-center justify-center gap-2 text-muted-foreground`,children:[(0,H.jsx)(Ed,{}),` Loading`]})});let h=c.appRoles.map(e=>Gh(s?.roles??[],e)),g=`${c.inviter.name} invites you to ${c.organization.name} as ${Wh[c.role].toLowerCase()}${h.length>0?`, with ${h.join(`, `)}`:``}.`,_=i.kind===`signed-in`?i.user:void 0;return _&&_.email.toLowerCase()!==c.email.toLowerCase()?(0,H.jsxs)(jh,{title:`Join ${c.organization.name}`,description:g,children:[(0,H.jsxs)(`p`,{className:`mb-3 text-muted-foreground`,children:[`This invitation is for `,c.email,`, and you are signed in as `,_.email,`.`]}),(0,H.jsx)(W,{className:`w-full`,onClick:()=>void a(),children:`Sign out to accept it`})]}):(0,H.jsx)(jh,{title:`Join ${c.organization.name}`,description:g,children:_?(0,H.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[p&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:p}),(0,H.jsxs)(W,{variant:`primary`,className:`w-full`,loading:f,onClick:()=>void m(async()=>{await r.organizations.accept(e),t()}),children:[`Join `,c.organization.name]})]}):c.hasAccount?(0,H.jsxs)(Mu,{to:n,className:V(xf({variant:`primary`}),`w-full`),children:[`Sign in as `,c.email,` to join`]}):(0,H.jsx)(Gne,{token:e,preview:c,onDone:t})})},qne=`modulepreload`,Jne=function(e){return`/`+e},Yh={},Yne=function(e){return e.pathname.endsWith(`.css`)},Xh=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=Jne(t,n);let r=s(t);if(r.href in Yh)return;Yh[r.href]=!0;let i=Yne(r);if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let o=document.createElement(`link`);if(o.rel=i?`stylesheet`:qne,i||(o.as=`script`),o.crossOrigin=``,o.href=r.href,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),i)return new Promise((e,t)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>t(Error(`Unable to preload CSS for ${r}`)))})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Zh,Qh,Xne=({dsn:e,environment:t})=>(Zh??=Xh(()=>import(`./prod-YZ9ZMG1O.js`).then(n=>{n.init({dsn:e,...t&&{environment:t},integrations:e=>e.filter(e=>e.name!==`BrowserSession`),beforeSend:e=>Ko(e)}),Qh=(e,t)=>n.captureException(e,t?{contexts:{react:{componentStack:t}}}:void 0)}),[]),Zh),$h=(e,t)=>Qh?.(e,t??void 0),eg=({children:e})=>(0,H.jsx)(`div`,{role:`alert`,className:`rounded-lg border border-dashed border-warning bg-warning-soft p-3 text-warning-text`,children:e}),tg=class extends o.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e,t){$h(e,t.componentStack)}render(){return this.state.failed?this.props.fallback===void 0?(0,H.jsxs)(eg,{children:[this.props.name,` could not be drawn.`]}):this.props.fallback:this.props.children}},Zne=/^[A-Z][A-Za-z0-9]*$/,Qne=e=>typeof e==`function`||typeof e==`object`&&!!e&&`$$typeof`in e,ng=e=>{let t=e.default??{},n=Object.entries(e).filter(e=>e[0]!=="default"&&Zne.test(e[0])&&Qne(e[1]));if(n.length===0)return t;for(let[e,r]of n)if(t.components&&Object.hasOwn(t.components,e)&&t.components[e]!==r)throw Error(`The component "${e}" is exported by name and given in components as another one; keep the export`);return{...t,components:{...t.components,...Object.fromEntries(n)}}},rg=class extends Error{name=`UiConflictError`},$ne=e=>Object.keys(e).some(e=>e==="default"||/^[A-Z]/.test(e))?ng(e):e,ig=(e,t)=>[...(e.extends??[]).map($ne).flatMap((e,n)=>ig(e,e.name??`${t} extends[${n}]`)),{ui:e,label:t}],ag=(e,t,n)=>{let r={},i=new Map;for(let{ui:a,label:o}of t)for(let[t,s]of Object.entries(n(a)??{})){if(Object.hasOwn(r,t)&&r[t]!==s)throw new rg(`${e} "${t}" is defined twice, by ${i.get(t)} and by ${o}; rename one of them`);r[t]=s,i.set(t,i.get(t)??o)}return r},og=e=>e.length<=1?e[0]:()=>e.map((e,t)=>(0,H.jsx)(e,{},t)),ere=e=>e.length<=1?e[0]:({children:t,...n})=>e.reduceRight((e,t)=>(0,H.jsx)(t,{...n,children:e}),t),sg=(...e)=>{let t=e.flatMap((e,t)=>ig(e,e.name??`UI config ${t+1}`)),n=ag(`The component`,t,e=>e.components),r=ag(`The action handler`,t,e=>e.actions),i=ag(`The field type`,t,e=>e.fields),a=og(t.flatMap(({ui:e})=>e.shell?.actions?[e.shell.actions]:[])),o=og(t.flatMap(({ui:e})=>e.shell?.rightPanel?[e.shell.rightPanel]:[])),s=t.findLast(({ui:e})=>e.shell?.logo)?.ui.shell?.logo,c=ere(t.flatMap(({ui:e})=>e.beforeSignIn?[e.beforeSignIn]:[])),l=e.at(-1)?.name;return{...l&&{name:l},components:n,actions:r,...Object.keys(i).length>0&&{fields:i},...(a||o||s)&&{shell:{...a&&{actions:a},...o&&{rightPanel:o},...s&&{logo:s}}},...c&&{beforeSignIn:c}}},cg=(e,t)=>{let n=sg(e??{}),r=[],i=[];for(let e of t){if(e.kind===`off`){i.push(e);continue}try{sg(...r,e.ui,n),r.push(e.ui)}catch(t){if(!(t instanceof rg))throw t;i.push({kind:`off`,url:e.plugin.url,name:e.plugin.name,reason:t.message})}}return{ui:r.length===0?n:sg(...r,n),off:i}},lg=e=>typeof e==`string`&&e.trim()!==``,tre=e=>{if(typeof e!=`object`||!e||Array.isArray(e))return{problem:`its plugin.json is not an object`};let{name:t,version:n,api:r,protobase:i,entry:a,css:o}=e;return lg(t)?Number.isInteger(r)?lg(i)?lg(a)?o!==void 0&&!lg(o)?{problem:`its plugin.json names a stylesheet that is no URL`}:n!==void 0&&!lg(n)?{problem:`its plugin.json has a version that is no text`}:{manifest:{name:t,api:r,protobase:i,entry:a,...n!==void 0&&{version:n},...o!==void 0&&{css:o}}}:{problem:`its plugin.json names no module`}:{problem:`its plugin.json names no Protobase versions`}:{problem:`its plugin.json names no plugin API`}:{problem:`its plugin.json names no plugin`}},ug=(0,o.createContext)(null),nre=ug.Provider,rre=()=>{let e=(0,o.useContext)(ug);if(!e)throw Error(`usePlugin is for the components of a plugin the app loaded`);return e},dg=(e,t,n)=>{let r=n=>(0,H.jsx)(nre,{value:e,children:(0,H.jsx)(t,{...n})});return r.displayName=`${e.name}:${n}`,r},ire=(e,t,n)=>({of:n.of,display:dg(e,n.display,`fields.${t}.display`),...n.editor&&{editor:dg(e,n.editor,`fields.${t}.editor`)},...n.cell&&{cell:dg(e,n.cell,`fields.${t}.cell`)}}),are=(e,t)=>{let n=sg({...ng(t),name:e.name}),r=Object.fromEntries(Object.entries(n.components??{}).map(([t,n])=>[t,dg(e,n,t)])),i=n.fields&&Object.fromEntries(Object.entries(n.fields).map(([t,n])=>[t,ire(e,t,n)])),a=n.shell&&{...n.shell.actions&&{actions:dg(e,n.shell.actions,`shell.actions`)},...n.shell.rightPanel&&{rightPanel:dg(e,n.shell.rightPanel,`shell.rightPanel`)}},o=n.beforeSignIn&&dg(e,n.beforeSignIn,`beforeSignIn`);return{name:e.name,components:r,...n.actions&&{actions:n.actions},...i&&{fields:i},...a&&{shell:a},...o&&{beforeSignIn:o}}},fg={name:`@protobase/ui`,version:`0.21.6`,description:`The Protobase admin app and the React hooks and components for custom UI.`,license:`Apache-2.0`,repository:{type:`git`,url:`git+https://github.com/PrototeamHQ/protobase.git`,directory:`packages/ui`},homepage:`https://docs.protobase.net`,type:`module`,protobase:{pluginApi:1},sideEffects:[`*.css`,`./dist/app/main.js`],engines:{node:`>=22.12.0`},exports:{".":`./src/index.ts`,"./theme.css":`./src/theme.css`,"./styles.css":`./src/styles.css`},types:`./src/index.ts`,files:[`dist`],scripts:{build:`tsdown && protobase build-shell dist/shell`,prepack:`tsdown && protobase build-shell dist/shell`},publishConfig:{access:`public`,exports:{".":`./dist/index.js`,"./theme.css":`./dist/theme.css`,"./styles.css":`./dist/styles.css`},types:`./dist/index.d.ts`},dependencies:{"@dnd-kit/core":`^6.3.1`,"@dnd-kit/sortable":`^10.0.0`,"@protobase/client":`workspace:*`,"@protobase/layout":`workspace:*`,"@protobase/schema":`workspace:*`,"@sentry/browser":`^11.7.0`,"@tanstack/react-query":`^5.104.1`,"@tanstack/react-table":`^9.2.6`,dompurify:`^3.4.17`,fflate:`^0.8.3`,"lucide-react":`^1.52.0`,"maplibre-gl":`^6.14.0`,marked:`^18.1.1`,pmtiles:`^4.5.0`,react:`^19.3.0`,"react-dom":`^19.3.0`,"react-map-gl":`^8.1.3`,recharts:`^3.10.1`,tailwindcss:`^4.3.3`,thumbhash:`^0.1.1`,uqr:`^0.1.3`}},pg=fg.protobase.pluginApi,mg=fg.version,ore={readJson:async e=>{let t=await fetch(e,{cache:`no-cache`,credentials:`same-origin`});return t.ok?{json:await t.json()}:{status:t.status}},addStylesheet:e=>{if([...document.querySelectorAll(`link[rel="stylesheet"]`)].some(t=>t.href===e))return;let t=document.createElement(`link`);t.rel=`stylesheet`,t.href=e,document.head.append(t)},importModule:e=>Xh(()=>import(e),[])},sre={api:pg,version:mg},cre=e=>e instanceof Error?e.message:String(e),lre=async(e,t,n,r=sre)=>{let i=new URL(e.url,n).href,a=(e,t)=>({kind:`off`,url:i,...t&&{name:t},reason:e}),o;try{let n=await t.readJson(i);if(`status`in n)return a(`its plugin.json answered ${n.status}`);let s=tre(n.json);if(`problem`in s)return a(s.problem);let{manifest:c}=s;o=c.name;let l=Lo(c,r);if(l)return a(l,o);c.css&&t.addStylesheet(new URL(c.css,i).href);let u=await t.importModule(new URL(c.entry,i).href),d={name:o,...c.version&&{version:c.version},url:i,settings:e.settings??{}};return{kind:`loaded`,plugin:d,ui:are(d,u)}}catch(e){return a(`it could not be loaded: ${cre(e)}`,o)}},ure=e=>{let t=new Map;return{load:n=>{let r=JSON.stringify(n),i=t.get(r);if(i)return i;let a=lre(n,e,window.location.href);return t.set(r,a),a}}},hg=(0,o.createContext)(null),dre=({loader:e=ore,children:t})=>{let n=(0,o.useMemo)(()=>ure(e),[e]);return(0,H.jsx)(hg.Provider,{value:n,children:t})},gg=()=>{let e=(0,o.useContext)(hg);if(!e)throw Error(`usePluginSource must be used inside PluginSourceProvider`);return e},fre=1e4,_g=[],vg=(e,t)=>{let n=JSON.stringify(e),[r,i]=(0,o.useState)({key:`[]`,loads:_g,settled:!0});return(0,o.useEffect)(()=>{if(e.length===0)return;let r=!0,a=!1,o=e.map(()=>void 0),s=()=>{if(!r)return;let t=o.filter(e=>e!==void 0);i({key:n,loads:t,settled:a||t.length===e.length})},c=setTimeout(()=>{a=!0,s()},fre);return e.forEach((e,n)=>{t.load(e).then(e=>{o[n]=e,s()})}),()=>{r=!1,clearTimeout(c)}},[n,t]),e.length===0?{loads:_g,settled:!0}:r.key===n?r:{loads:_g,settled:!1}},pre=({children:e})=>{let{state:t,beforeSignIn:n,adoptSession:r}=U(),{path:i,params:a,navigate:s}=Dh(),{loads:c,settled:l}=vg(n,gg()),u=(0,o.useMemo)(()=>cg(void 0,c).ui.beforeSignIn,[c]),d=(0,o.useCallback)(e=>{let t=new URLSearchParams(a);for(let n of e)t.delete(n);s(t.size>0?`${i}?${t}`:i,{replace:!0})},[i,a,s]);return t.kind!==`signed-out`&&t.kind!==`visitor`?e:l?u?(0,H.jsx)(tg,{name:`beforeSignIn`,fallback:e,children:(0,H.jsx)(u,{signedIn:r,params:a,removeParams:d,children:e})}):e:(0,H.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,H.jsx)(Ed,{}),` Loading`]})},mre=()=>{let e=window.location.href,t=mne(e);if(t)return{kind:`reset-password`,token:t.token};let n=Pne(e);if(n)return{kind:`staff-sign-in`,link:n};let r=Vne(e);if(r)return{kind:`invitation`,token:r.token};let i=qd(e);if(i)return{kind:`provider-sign-in`,provider:i};let a=Jd(e);return a?{kind:`sign-in`,providerError:a}:{kind:`sign-in`}},yg=({to:e})=>{let{navigate:t}=Dh();return(0,o.useEffect)(()=>t(e,{replace:!0}),[t,e]),null},hre=({workspace:e,children:t})=>{let n=gre(e,t);return(0,H.jsx)(pre,{children:n})},gre=(e,t)=>{let{state:n,recheck:r,passwordReset:i,signOut:a,signInProviders:s,canSignUp:c,browse:l}=U(),{path:u,params:d,basePath:f,navigate:p}=Dh(),{address:m,next:h,open:g,link:_,leave:v}=zh(),[y,b]=(0,o.useState)(mre),[x,S]=(0,o.useState)(),[C,w]=(0,o.useState)(),[T,E]=(0,o.useState)(),D=new URL(`${f}${u}${d.size>0?`?${d}`:``}`,window.location.origin).href,O=(0,o.useCallback)(e=>{let t=e(D).slice(f.length);p(t.startsWith(`/`)?t:`/${t}`,{replace:!0})},[D,f,p]),k=n.kind===`signed-in`||n.kind===`two-factor`||n.kind===`setup-required`;(0,o.useEffect)(()=>{k&&(y.kind===`provider-sign-in`&&O(Yd),(y.kind===`provider-sign-in`||y.kind===`sign-in`&&(y.notice||y.error||y.providerError))&&b({kind:`sign-in`}),S(void 0),w(void 0),E(void 0))},[k,y,O]);let A=m!==void 0&&Jd(D)!==void 0;(0,o.useEffect)(()=>{!k&&y.kind===`sign-in`&&y.providerError&&A&&O(Yd)},[k,y,A,O]);let j=(0,o.useCallback)(e=>b({kind:`sign-in`,error:e}),[]),M=e=>{O(hne),b(e)},N=async()=>{n.kind===`signed-in`&&await a(),M({kind:`sign-in`,notice:`Your password is changed. Sign in with the new one.`})},ee=()=>{b({kind:`sign-in`}),a().then(()=>g(`sign-in`,{replace:!0}))};switch(n.kind){case`loading`:return(0,H.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,H.jsx)(Ed,{}),` Loading`]});case`error`:return(0,H.jsxs)(`div`,{className:`flex h-full min-h-48 flex-col items-center justify-center gap-3 p-8 text-center`,children:[(0,H.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Cannot reach the server: `,n.message]}),(0,H.jsx)(W,{onClick:r,children:`Try again`})]});case`needs-admin`:return(0,H.jsx)(dne,{onCheckAgain:r})}if(n.kind===`signed-in`&&m)return(0,H.jsx)(yg,{to:h??`/`});if(y.kind===`reset-password`)return(0,H.jsx)(xne,{token:y.token,onDone:()=>void N(),onRequestNewLink:i?()=>{b({kind:`sign-in`}),p(bs({step:`forgot-password`}),{replace:!0})}:void 0,onBack:()=>M({kind:`sign-in`})});if(y.kind===`staff-sign-in`)return(0,H.jsx)(Lne,{link:y.link,onBack:()=>{O(Lh),b({kind:`sign-in`})}});let P=n.kind===`signed-out`||n.kind===`visitor`;if(y.kind===`invitation`&&(n.kind===`signed-in`||P&&!m))return(0,H.jsx)(Kne,{token:y.token,onDone:()=>{O(Hne),b({kind:`sign-in`})},signIn:_()});if(n.kind===`signed-in`)return t;if(n.kind===`two-factor`)return(0,H.jsx)(Bne,{methods:n.methods,onBack:ee});if(n.kind===`setup-required`)return(0,H.jsx)(wne,{missing:n.missing},n.missing.join());if(y.kind===`provider-sign-in`)return(0,H.jsx)(vne,{provider:y.provider,workspace:e,onFailed:j});let te=y.kind===`sign-in`?y:{kind:`sign-in`};if(!m){let e=te.notice||te.error||te.providerError;return n.kind===`visitor`&&!e?t:(0,H.jsx)(yg,{to:bs({next:h})})}let F={"sign-in":!0,"forgot-password":i,"email-code":x!==void 0,"sign-up":c,"sign-up-code":c&&C!==void 0,"sign-up-details":c&&T!==void 0}[m.step]?m.step:`sign-in`,ne=e=>()=>g(e,{replace:!0}),re=l&&(()=>{l(),v()});if(F===`forgot-password`)return(0,H.jsx)(gne,{back:_(`sign-in`,{replace:!0})});if(F===`email-code`)return(0,H.jsx)(lne,{email:x,onBack:ne(`sign-in`)});if(F===`sign-up`||F===`sign-up-code`||F===`sign-up-details`)return(0,H.jsx)(Nne,{workspace:e,email:F===`sign-up`?void 0:C,ticket:F===`sign-up-details`?T:void 0,onCodeSent:e=>{w(e),E(void 0),g(`sign-up-code`)},onVerified:e=>{E(e),g(`sign-up-details`,{replace:!0})},onBack:ne(`sign-up`),onSignIn:()=>g(`sign-in`),onBrowse:re},F);let ie=te.providerError&&Wd(te.providerError,s.length===1?s[0].name:`the provider`),I=te.error??ie;return(0,H.jsx)(kne,{workspace:e,notice:te.notice,error:I,forgotPassword:i?_(`forgot-password`):void 0,onCodeSent:e=>{S(e),g(`email-code`)},signUp:c?_(`sign-up`):void 0,onBrowse:re},I)},_re=e=>[...e].reduce((e,t)=>(e*31+t.charCodeAt(0))%360,7),vre=e=>e.split(/[\s@.]+/).filter(Boolean).slice(0,2).map(e=>e[0].toUpperCase()).join(``),bg=e=>(e.role??`user`).split(`,`).map(e=>e.trim()),xg=e=>bg(e).includes(`admin`),yre=e=>{let t=bg(e),n=t.includes(`admin`);return{name:e.name||e.email,email:e.email,initials:vre(e.name||e.email)||`?`,hue:_re(e.id||e.email),role:n?`Admin`:(t[0]??`user`).replace(/^./,e=>e.toUpperCase()),roleTone:n?`violet`:`blue`}},bre=3e4,xre=(e,t=Date.now())=>Math.max(1e3,nu(e)-t-bre),Sg=()=>{let{state:e,session:t}=U(),n=e.kind===`signed-in`,[r,i]=(0,o.useState)();return(0,o.useEffect)(()=>{if(!n)return;let e=!0,r,a=async n=>{let o=await t.token(),s=o!==void 0&&o===n?await t.token({refresh:!0}):o;e&&(i(s),s&&(r=setTimeout(()=>void a(s),xre(s))))};return a(),()=>{e=!1,clearTimeout(r)}},[t,n]),n?r:void 0},Cg=(e,t,n=!0)=>{let r=K(),i=Ao(t);return _h({queryKey:G.record(e,i),enabled:n,queryFn:()=>r.get(e,t)})},wg=(e,t,n=!0)=>{let r=K(),i=Up(),a=Ao(t);return _h({queryKey:G.record(e,a),enabled:n,queryFn:()=>r.get(e,t),placeholderData:()=>i.getQueryData(G.recordPreview(e,a))})},Sre=[`name`,`title`,`number`,`sku`,`email`,`code`,`description`],Tg=(e,t)=>t?.title??Sre.find(t=>e.fields[t]?.type===`text`)??Object.values(e.fields).find(e=>e.type===`text`)?.name??e.primaryKey[0],Eg=(e,t)=>t?.title??t?.list?.columns.find(t=>e.fields[t]?.type===`text`)??Tg(e),Dg=(e,t,n,r)=>{let i=Eg(e,t),a=n[i];return a==null?r:e.fields[i]?.type===`enum`?rs(String(a),t?.fields[i]?.valueLabels):String(a)},Og=(e,t,n)=>{let r=t[n];return e.fields[n]?.type===`relation`&&typeof r==`object`&&r&&`id`in r?r.id:r},kg=(e,t)=>e.primaryKey.map(n=>String(Og(e,t,n))).join(`,`),Ag=(e,t)=>{let n=e.primaryKey.map(n=>Og(e,t,n));return n.length===1?n[0]:n},Cre=e=>e.charAt(0).toUpperCase()+e.slice(1),q=e=>Cre(e.replace(/(Id|Code|_id|_code)$/,``).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/_+/g,` `).trim().toLowerCase()||e),wre=[`light`,`dark`,`system`],jg=`protobase:theme`,Tre=`(prefers-color-scheme: dark)`,Ere=e=>wre.includes(e),Mg=e=>id(()=>{let t=e.getItem(jg);return Ere(t)?t:`system`},`system`),Dre=(e,t)=>id(()=>t===`system`?e.removeItem(jg):e.setItem(jg,t),void 0),Ore=(e,t)=>e===`system`?t?`dark`:`light`:e,Ng=(0,o.createContext)(void 0),kre=({children:e})=>{let[t,n]=(0,o.useState)(()=>Mg(localStorage)),r=Ore(t,fu(Tre));return(0,o.useEffect)(()=>{document.documentElement.dataset.theme=r},[r]),(0,o.useEffect)(()=>{let e=e=>{(e.key===`protobase:theme`||e.key===null)&&n(Mg(localStorage))};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),(0,H.jsx)(Ng.Provider,{value:{preference:t,theme:r,choose:e=>{Dre(localStorage,e),n(e)}},children:e})},Are=()=>{let e=(0,o.useContext)(Ng);if(!e)throw Error(`useTheme needs a ThemeProvider above it`);return e},Pg=`-my-0.5 rounded px-1.5 py-0.5 font-medium text-primary-text hover:bg-primary-soft`,jre=({action:e})=>{if(`onClick`in e)return(0,H.jsx)(`button`,{type:`button`,onClick:e.onClick,className:Pg,children:e.label});let{href:t,onNavigate:n}=e;return(0,H.jsx)(`a`,{href:t,onClick:e=>{n&&Au(e)&&(e.preventDefault(),n(t))},className:Pg,children:e.label})},Mre={loading:(0,H.jsx)(Ed,{className:`text-primary`}),success:(0,H.jsx)(De,{className:`size-4 text-success`}),error:(0,H.jsx)(je,{className:`size-4 text-danger`})},Nre=({state:e,title:t,description:n,action:r,onDismiss:i})=>(0,H.jsxs)(`div`,{role:e===`error`?`alert`:`status`,className:V(`flex w-full max-w-80 items-start gap-3 rounded-lg border bg-background p-3 shadow-pop [animation:pb-slide-in_160ms_ease-out]`,e===`error`&&`border-danger/40`),children:[(0,H.jsx)(`span`,{className:`mt-0.5`,children:Mre[e]}),(0,H.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,H.jsx)(`p`,{className:`font-medium text-foreground`,children:t}),n&&(0,H.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:n})]}),r&&(0,H.jsx)(jre,{action:r}),i&&(0,H.jsx)(`button`,{type:`button`,"aria-label":`Dismiss`,onClick:i,className:`inline-flex items-center justify-center rounded p-0.5 text-faint-foreground hover:bg-muted hover:text-foreground pointer-coarse:size-9`,children:(0,H.jsx)(Qn,{className:`size-3.5`})})]}),Pre={loading:1/0,success:3500,error:8e3},Fre=8e3,Fg=(0,o.createContext)(null),Ig=()=>{let e=(0,o.useContext)(Fg);if(!e)throw Error(`useToast must be used inside ToastProvider`);return e},Ire=({children:e})=>{let[t,n]=(0,o.useState)([]),r=(0,o.useRef)(1),i=(0,o.useRef)(new Map),a=(0,o.useCallback)(e=>{clearTimeout(i.current.get(e)),i.current.delete(e),n(t=>t.filter(t=>t.id!==e))},[]),s=(0,o.useCallback)((e,t,n=!1)=>{clearTimeout(i.current.get(e));let r=n?Fre:Pre[t];r!==1/0&&i.current.set(e,setTimeout(()=>a(e),r))},[a]),c=(0,o.useMemo)(()=>({show:e=>{let t=r.current++;return n(n=>[...n,{...e,id:t}]),s(t,e.state,!!e.action),t},update:(e,t)=>{n(n=>n.map(n=>n.id===e?{...n,...t}:n)),t.state&&s(e,t.state,!!t.action)},dismiss:a}),[a,s]);return(0,H.jsxs)(Fg.Provider,{value:c,children:[e,(0,H.jsx)(`div`,{className:`pointer-events-none fixed inset-x-4 bottom-24 z-[100] flex flex-col items-end gap-2 md:inset-x-auto md:bottom-4 md:right-4`,children:t.map(e=>(0,H.jsx)(`div`,{className:`pointer-events-auto`,children:(0,H.jsx)(Nre,{state:e.state,title:e.title,description:e.description,action:e.action,onDismiss:()=>a(e.id)})},e.id))})]})},Lg=({from:e,children:t})=>(0,H.jsx)(`div`,{"data-from":e,className:V(`flex min-w-0 flex-col gap-2 whitespace-pre-wrap break-words`,e===`user`?`ml-8 self-end rounded-lg rounded-br-sm bg-primary px-3 py-2 text-primary-foreground shadow-sm`:`mr-4 text-foreground`),children:t}),Rg=({children:e,empty:t,length:n})=>{let r=(0,o.useRef)(null);return(0,o.useEffect)(()=>{let e=r.current;e&&(e.scrollTop=e.scrollHeight)},[n]),(0,H.jsx)(`div`,{ref:r,role:`log`,"aria-live":`polite`,className:`flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4`,children:n===0&&t?(0,H.jsx)(`div`,{className:`m-auto max-w-60 text-center text-muted-foreground`,children:t}):e})},zg=({onSend:e,busy:t,placeholder:n,inputRef:r})=>{let[i,a]=(0,o.useState)(``),s=i.trim(),c=()=>{s&&!t&&(e?.(s),a(``))};return(0,H.jsxs)(`form`,{className:`flex gap-2`,onSubmit:e=>{e.preventDefault(),c()},children:[(0,H.jsx)(wd,{ref:r,"aria-label":`Message`,placeholder:n,value:i,onChange:e=>a(e.target.value),wrapperClassName:`flex-1`}),(0,H.jsx)(W,{type:`submit`,variant:`primary`,className:`w-8 px-0`,"aria-label":`Send`,disabled:!s||t,children:(0,H.jsx)(oee,{className:`size-4`})})]})},Lre=e=>{let[t,n]=(0,o.useState)();return(0,o.useEffect)(()=>{let t=window.visualViewport;if(!e||!t)return n(void 0);let r=()=>n({top:t.offsetTop,height:t.height});return r(),t.addEventListener(`resize`,r),t.addEventListener(`scroll`,r),()=>{t.removeEventListener(`resize`,r),t.removeEventListener(`scroll`,r)}},[e]),e?t:void 0},Bg=({title:e,icon:t,status:n,onClose:r,footer:i,children:a})=>{let o=Lre(!pu());return(0,H.jsxs)(`aside`,{"aria-label":e,className:`flex h-full w-[380px] max-w-full shrink-0 flex-col border-l border-border bg-surface max-md:fixed max-md:inset-0 max-md:z-40 max-md:w-full max-md:border-l-0`,style:o&&{top:o.top,bottom:`auto`,height:o.height},children:[(0,H.jsxs)(`header`,{className:`flex h-12 shrink-0 items-center gap-2 border-b border-border bg-background px-4`,children:[t,(0,H.jsx)(`h2`,{className:`flex-1 font-semibold`,children:e}),n&&(0,H.jsx)(`span`,{className:`truncate text-xs font-medium text-muted-foreground`,children:n}),r&&(0,H.jsx)(W,{variant:`ghost`,size:`sm`,className:`w-7 px-0`,"aria-label":`Close`,onClick:r,children:(0,H.jsx)(Qn,{className:`size-4`})})]}),a,i&&(0,H.jsx)(`footer`,{className:`shrink-0 space-y-2 border-t border-border bg-background p-3`,children:i})]})},Vg={neutral:{border:`border-border-strong`,header:`bg-surface text-foreground`},info:{border:`border-primary-border`,header:`bg-primary-soft text-primary-text`},success:{border:`border-success/40`,header:`bg-success-soft text-success-text`},warning:{border:`border-warning/40`,header:`bg-warning-soft text-warning-text`},danger:{border:`border-danger/40`,header:`bg-danger-soft text-danger-text`}},Hg=({title:e,tone:t=`neutral`,badge:n,note:r,actions:i=[],onAction:a,children:s,frameless:c=!1})=>{let[l,u]=(0,o.useState)(),d=i.flatMap(e=>e.hint?[e.hint]:[]),f=e=>e.confirm?u(e):a?.(e.id);return(0,H.jsxs)(`section`,{"aria-label":e,className:c?`whitespace-normal text-foreground`:V(`shrink-0 overflow-hidden rounded-lg border bg-background whitespace-normal text-foreground shadow-sm`,Vg[t].border),children:[!c&&(0,H.jsxs)(`header`,{className:V(`flex items-center gap-2 px-3 py-2`,Vg[t].header),children:[(0,H.jsx)(`h3`,{className:`min-w-0 flex-1 font-semibold`,children:e}),n&&(0,H.jsx)(`span`,{className:`shrink-0 text-xs font-medium`,children:n})]}),(s||r||i.length>0)&&(0,H.jsxs)(`div`,{className:V(`space-y-2.5`,!c&&`px-3 py-2.5`),children:[s,r&&(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:r}),i.length>0&&(0,H.jsx)(`div`,{className:`flex flex-wrap gap-2 pt-0.5`,children:i.map(e=>(0,H.jsx)(W,{size:`sm`,variant:e.style??`secondary`,className:V(e.style===`primary`&&`flex-1`),disabled:e.disabled,onClick:()=>f(e),children:e.label},e.id))}),d.map(e=>(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e},e))]}),l&&(0,H.jsx)(Sf,{title:`${l.label}?`,description:l.confirm,onClose:()=>u(void 0),actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:()=>u(void 0),children:`Cancel`}),(0,H.jsx)(W,{variant:l.style===`danger`?`danger`:`primary`,onClick:()=>{u(void 0),a?.(l.id)},children:l.label})]})})]})},Ug=({fields:e})=>(0,H.jsx)(`dl`,{className:`grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs`,children:e.map((e,t)=>(0,H.jsxs)(`div`,{className:`contents`,children:[(0,H.jsx)(`dt`,{className:`text-muted-foreground`,children:e.label}),(0,H.jsx)(`dd`,{className:`min-w-0 break-words`,children:e.value})]},`${t}-${e.label}`))}),Rre=e=>e==null?`null`:typeof e==`object`?JSON.stringify(e):String(e),Wg=({columns:e,rows:t,caption:n,truncated:r,className:i})=>(0,H.jsxs)(`section`,{"aria-label":n??`Table`,className:V(`shrink-0 overflow-hidden rounded-lg border border-border-strong bg-background shadow-sm`,i),children:[n&&(0,H.jsx)(`code`,{className:`block whitespace-pre-wrap break-words bg-surface px-3 py-2 font-mono text-[11px] text-foreground`,children:n}),t.length===0?(0,H.jsx)(`p`,{className:`px-3 py-2 text-xs text-muted-foreground`,children:`No rows.`}):(0,H.jsx)(`div`,{className:`max-h-64 overflow-auto`,children:(0,H.jsxs)(`table`,{className:`w-full border-collapse text-left text-[11px]`,children:[(0,H.jsx)(`thead`,{className:`sticky top-0 bg-background`,children:(0,H.jsx)(`tr`,{children:e.map(e=>(0,H.jsx)(`th`,{scope:`col`,className:`border-b border-border px-2 py-1 font-semibold whitespace-nowrap`,children:e},e))})}),(0,H.jsx)(`tbody`,{children:t.map((e,t)=>(0,H.jsx)(`tr`,{className:`border-b border-border last:border-b-0`,children:e.map((e,t)=>(0,H.jsx)(`td`,{className:V(`px-2 py-1 whitespace-nowrap`,e===null&&`text-faint-foreground`),children:Rre(e)},t))},t))})]})}),(0,H.jsxs)(`footer`,{className:`border-t border-border px-3 py-1.5 text-[11px] text-muted-foreground`,children:[t.length,` `,t.length===1?`row`:`rows`,r&&`, cut off at the limit`]})]}),Gg=(e,t=1)=>{let n=t,r=t;return e.split(`
|
|
8
|
+
`).map(e=>e.startsWith(`+`)?{kind:`add`,text:e.slice(1),newNo:r++}:e.startsWith(`-`)?{kind:`del`,text:e.slice(1),oldNo:n++}:{kind:`ctx`,text:e.startsWith(` `)?e.slice(1):e,oldNo:n++,newNo:r++})},Kg=e=>({added:e.filter(e=>e.kind===`add`).length,removed:e.filter(e=>e.kind===`del`).length}),zre={add:`bg-success-soft text-success-text`,del:`bg-danger-soft text-danger-text`,ctx:`text-muted-foreground`},Bre={add:`+`,del:`−`,ctx:``},qg=({source:e,start:t,path:n,className:r})=>{let i=Gg(e,t),a=Kg(i);return(0,H.jsxs)(`div`,{className:V(`overflow-hidden`,r),children:[n&&(0,H.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border bg-surface px-3 py-1.5`,children:[(0,H.jsx)(et,{className:`size-3.5 text-muted-foreground`}),(0,H.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-[11px] text-foreground`,children:n}),(0,H.jsxs)(`span`,{className:`text-[11px] font-medium text-success-text`,children:[`+`,a.added]}),a.removed>0&&(0,H.jsxs)(`span`,{className:`text-[11px] font-medium text-danger-text`,children:[`−`,a.removed]})]}),(0,H.jsx)(`pre`,{className:`overflow-x-auto bg-background py-1 font-mono text-[11px] leading-[18px]`,children:i.map((e,t)=>(0,H.jsxs)(`div`,{className:V(`flex`,zre[e.kind]),children:[(0,H.jsx)(`span`,{className:`w-8 shrink-0 select-none pr-2 text-right opacity-60`,children:e.newNo??e.oldNo}),(0,H.jsx)(`span`,{className:`w-3 shrink-0 select-none`,children:Bre[e.kind]}),(0,H.jsx)(`span`,{className:`min-w-0 whitespace-pre-wrap break-words pr-3`,children:e.text})]},t))})]})},Vre={pending:(0,H.jsx)(Ne,{className:`size-3 text-faint-foreground`}),running:(0,H.jsx)(Ed,{className:`size-3.5 text-primary`}),done:(0,H.jsx)(he,{className:`size-3.5 text-success`,strokeWidth:2.5}),failed:(0,H.jsx)(Qn,{className:`size-3.5 text-danger`,strokeWidth:2.5})},Hre={pending:`text-muted-foreground`,running:`text-foreground`,done:`text-muted-foreground`,failed:`text-danger-text`},Jg=({steps:e,className:t})=>(0,H.jsx)(`ul`,{className:V(`shrink-0 space-y-2`,t),children:e.map((e,t)=>(0,H.jsxs)(`li`,{className:`flex items-start gap-2.5`,"data-state":e.state,children:[(0,H.jsx)(`span`,{className:`mt-0.5 flex size-4 shrink-0 items-center justify-center`,children:Vre[e.state]}),(0,H.jsx)(`span`,{className:Hre[e.state],children:e.label})]},`${t}-${e.label}`))}),Ure=e=>e,Wre=e=>e,Yg=(0,o.createContext)({}),Xg=()=>(0,o.useContext)(Yg),Zg=({part:e,note:t})=>e.fallback?(0,H.jsx)(Hg,{title:e.fallback.title,note:t,children:e.fallback.body&&(0,H.jsx)(`p`,{children:e.fallback.body})}):(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`${e.name}: ${t}`}),Gre=class extends o.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e,t){$h(e,t.componentStack)}render(){return this.state.failed?(0,H.jsx)(Zg,{part:this.props.part,note:`It could not be drawn.`}):this.props.children}},Kre=({part:e})=>{let{components:t={}}=Xg(),n=Object.hasOwn(t,e.name)?t[e.name]:void 0;return n?(0,H.jsx)(Gre,{part:e,children:(0,H.jsx)(n,{...e.props})}):(0,H.jsx)(Zg,{part:e,note:`This version of the app cannot show it live.`})},Qg=({part:e,onAction:t})=>{switch(e.type){case`text`:return(0,H.jsx)(`p`,{children:e.text});case`table`:return(0,H.jsx)(Wg,{columns:e.columns,rows:e.rows,caption:e.caption,truncated:e.truncated});case`card`:return(0,H.jsxs)(Hg,{title:e.title,tone:e.tone,badge:e.badge,note:e.note,actions:e.actions,onAction:n=>t?.(e.id,n),children:[e.body&&(0,H.jsx)(`p`,{children:e.body}),e.code&&(0,H.jsx)(`pre`,{className:`overflow-x-auto rounded-md bg-surface px-2.5 py-2 font-mono text-[11px] whitespace-pre-wrap break-words`,children:e.code}),e.fields&&e.fields.length>0&&(0,H.jsx)(Ug,{fields:e.fields}),e.steps&&e.steps.length>0&&(0,H.jsx)(Jg,{steps:e.steps}),e.diffs?.map((e,t)=>(0,H.jsx)(qg,{source:e.source,start:e.start,path:e.path,className:`rounded-md border border-border`},`${t}-${e.path}`))]});case`widget`:return(0,H.jsx)(Kre,{part:e})}},$g=(0,o.createContext)(void 0),e_=e=>e instanceof Error?e:Error(`The assistant backend did not answer`),qre=(e,t)=>typeof e==`function`?e(t):e,Jre=(e,{refreshMs:t=!1}={})=>{let n=(0,o.useContext)($g),[r,i]=(0,o.useState)({}),[a,s]=(0,o.useState)(0),c=(0,o.useRef)(t);c.current=t;let l=(0,o.useRef)(void 0);return(0,o.useEffect)(()=>{if(!n){i({error:Error(`useBackendData works only in a widget the assistant dock draws`)});return}let t=!0,r,a=async()=>{let o=await n.fetch(e).then(e=>e.json()).then(e=>({data:e}),e=>({data:l.current,error:e_(e)}));if(!t)return;l.current=o.data,i(o);let s=qre(c.current,o.data);s!==!1&&(r=setTimeout(a,s))};return a(),()=>{t=!1,clearTimeout(r)}},[n,e,a]),{...r,reload:()=>s(e=>e+1),post:async(e,t)=>{if(!n)throw Error(`useBackendData works only in a widget the assistant dock draws`);let r={method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t??{})},a=await n.fetch(e,r).then(e=>e.json()).then(e=>({data:e}),e=>({data:l.current,error:e_(e)}));l.current=a.data,i(a)}}},Yre=`Ask a question...`,t_=({state:e,offline:t,error:n,onSend:r,onAction:i,onClose:a,client:s})=>{let c=(0,o.useRef)(null);return(0,o.useEffect)(()=>{e.placeholder&&c.current?.focus()},[e.placeholder]),(0,H.jsx)(Bg,{title:`Assistant`,icon:(0,H.jsx)(wn,{className:`size-4 text-primary`}),status:t?`Reconnecting...`:e.status,onClose:a,footer:(0,H.jsxs)(H.Fragment,{children:[n&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs text-danger-text`,children:n}),(0,H.jsx)(zg,{inputRef:c,onSend:r,busy:e.replying,placeholder:e.placeholder??Yre})]}),children:(0,H.jsx)($g.Provider,{value:s,children:(0,H.jsx)(Rg,{length:e.messages.reduce((e,t)=>e+t.parts.length,0),empty:`Ask a question about this app or its data.`,children:e.messages.map(e=>(0,H.jsx)(Lg,{from:e.from,children:e.parts.map(e=>(0,H.jsx)(Qg,{part:e,onAction:i},e.id))},e.id))})})})},Xre=e=>e instanceof Error?e.message:`The assistant did not answer`,n_=e=>{let[t,n]=(0,o.useState)(Qo),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)();(0,o.useEffect)(()=>{if(e)return e.connect(e=>n(t=>ts(t,e)),e=>i(e.state===`retrying`))},[e]);let c=e=>{s(void 0),e.catch(e=>s(Xre(e)))};return{state:t,offline:r,error:a,send:(t,n)=>e&&c(e.send(t,n)),act:(t,n)=>e&&c(e.act(t,n))}},r_=e=>{let t=Sg(),n=(0,o.useRef)(t);n.current=t;let r=t!==void 0;return(0,o.useMemo)(()=>r?cu({url:e,token:()=>n.current}):void 0,[e,r])},Zre=({open:e,onToggle:t})=>(0,H.jsxs)(W,{size:`sm`,variant:e?`primary`:`secondary`,"aria-pressed":e,onClick:t,className:`max-md:size-9 max-md:p-0`,children:[(0,H.jsx)(wn,{className:`size-3.5`}),(0,H.jsx)(`span`,{className:`max-md:sr-only`,children:`Assistant`})]}),i_=({client:e,page:t,onClose:n})=>{let{state:r,offline:i,error:a,send:o,act:s}=n_(e);return(0,H.jsx)(t_,{state:r,offline:i,error:a,onSend:e=>o(e,t),onAction:s,onClose:n,client:e})},Qre=({url:e,...t})=>(0,H.jsx)(i_,{client:r_(e),...t}),$re=({url:e,client:t,...n})=>t?(0,H.jsx)(i_,{client:t,...n}):(0,H.jsx)(Qre,{url:e,...n}),eie={orders:bn,orderLines:bn,companies:le,invoices:it,invoiceLines:sn,products:Xt,categories:In,tags:In,companyTags:In,stockMoves:se,stockLevels:se,warehouses:Xn,locations:Xn,people:qn,users:qn,empMaster:qn,organizations:gn,countries:We,currencies:ze,shipments:Hn},a_=e=>eie[e]??Mn,o_={bell:te,"book-open":ne,bookmark:oe,building:le,"credit-card":ze,"external-link":Je,"file-text":it,heart:ct,key:gt,"layout-dashboard":bt,"life-buoy":Tt,mail:zt,receipt:sn,settings:gn,shield:vn,users:qn};Object.keys(o_);var s_=(e,t)=>e?o_[e]??t:t,tie=(e,t,n)=>(e.bottomBar?.items??[]).map((r,i)=>r.kind===`link`?{id:`link-${i}`,label:r.label,icon:s_(r.icon,Je),href:r.href,external:!0}:r.kind===`page`?{id:r.page,label:r.label,icon:s_(r.icon??e.pages[r.page]?.icon,bt),href:us({kind:`page`,page:r.page},t),active:r.page===n}:{id:r.resource,label:r.label,icon:s_(r.icon,a_(r.resource)),href:us({kind:`list`,resource:r.resource},t),active:r.resource===n}),nie=({basePath:e,address:t,group:n,page:r,resourceLabel:i,recordTitle:a,recordLoading:o})=>{let s=n?[n]:[];if(r)return[...s,{label:r.title,href:us({kind:`page`,page:r.name},e)}];if(!t||t.kind===`page`)return[`Admin`];let c=i?[{label:i,href:us({kind:`list`,resource:t.resource},e)}]:[];if(t.kind===`list`)return[...s,...c];let l=us(t,e),u=t.kind===`create`?{label:`New`,href:l}:a===void 0&&o?{label:`Loading record`,href:l,loading:!0}:{label:a??t.key,href:l};return[...s,...c,u]},rie=({address:e,page:t,accountPage:n,resourceLabel:r,singular:i,recordTitle:a,recordLoading:o})=>{if(n)return[n];if(t)return[t.title];if(!e||e.kind===`page`)return[];let s=r?[r]:[];if(e.kind===`list`)return s;if(e.kind===`create`)return[...i?[`New ${i.toLowerCase()}`]:[],...s];let c=a??(o?void 0:e.key);return[...c?[c]:[],...s]},iie=(e,t)=>[...e.filter(Boolean),t].join(` · `),aie=e=>{(0,o.useEffect)(()=>{let t=document.title;return document.title=e,()=>{document.title=t}},[e])},c_=(0,o.createContext)(null),oie={create:!0,update:!0,delete:!0,conditional:[]},l_=()=>{let e=K(),t=Up(),n=(0,o.useContext)(c_),r=_h({queryKey:G.meta,staleTime:0,refetchOnWindowFocus:`always`,queryFn:async()=>{let n=t.getQueryData(G.meta),r=await e.meta(n?.etag);if(r.status===`unchanged`){if(!n)throw Error(`The server answered 304 to a request without If-None-Match`);return n}return{etag:r.etag,appName:r.meta.appName,resources:Object.fromEntries(r.meta.resources.map(e=>[e.name,e])),views:Object.fromEntries(r.meta.views.map(e=>[e.resource,e])),pages:Object.fromEntries((r.meta.pages??[]).map(e=>[e.name,e])),permissions:r.meta.permissions??{},...r.meta.userMenu&&{userMenu:r.meta.userMenu},...r.meta.signIn&&{signIn:Object.fromEntries(r.meta.signIn.map(e=>[e.resource,e]))},...r.meta.bottomBar&&{bottomBar:r.meta.bottomBar},...r.meta.assistant&&{assistant:r.meta.assistant},...r.meta.runtime&&{runtime:r.meta.runtime},...r.meta.errorReporting&&{errorReporting:r.meta.errorReporting},...r.meta.maps&&{maps:r.meta.maps},...r.meta.files&&{files:r.meta.files},...r.meta.plugins&&{plugins:r.meta.plugins},...r.meta.sources&&{sources:r.meta.sources.map(e=>({source:e,state:`loading`}))}}}});return(0,o.useMemo)(()=>n&&r.data?{...r,data:n}:r,[n,r])},sie=1e4,cie=e=>e.map(e=>({data:e.data?.meta,error:e.error})),lie=(e,t)=>{let n=Up(),r=hh({queries:e.map(e=>{let r=G.sourceMeta(e.url,e.resources);return{queryKey:r,staleTime:0,refetchOnWindowFocus:`always`,queryFn:async()=>{let i=n.getQueryData(r),a=await t(e).meta(i?.etag,{signal:AbortSignal.timeout(sie)});if(a.status===`unchanged`){if(!i)throw Error(`${e.label} answered 304 to a request without If-None-Match`);return i}return{etag:a.etag,meta:cc(a.meta,e)}}}}),combine:cie});return(0,o.useMemo)(()=>e.map((e,t)=>{let{data:n,error:i}=r[t];return n?{source:e,state:`ready`,meta:n}:i?{source:e,state:`error`,error:i}:{source:e,state:`loading`}}),[e,r])},uie=(e,t)=>{if(t.length===0)return e;let n=t.flatMap(e=>e.state===`ready`?[e.meta]:[]),r=t.map(e=>e.state===`error`?{source:e.source,state:`error`,error:e.error}:{source:e.source,state:e.state});return{...e,resources:{...e.resources,...Object.fromEntries(n.flatMap(e=>e.resources.map(e=>[e.name,e])))},views:{...e.views,...Object.fromEntries(n.flatMap(e=>e.views.map(e=>[e.resource,e])))},permissions:{...e.permissions,...Object.assign({},...n.map(e=>e.permissions))},sources:r}},die=(e,t)=>e.sources?.find(e=>e.source.resources.includes(t)),J=()=>{let e=(0,o.useContext)(c_);if(!e)throw Error(`useAdminMeta must be used inside MetaGate`);return e},u_=({title:e,children:t})=>(0,H.jsx)(`div`,{className:`flex h-full min-h-48 flex-1 items-center justify-center p-8`,children:(0,H.jsxs)(`div`,{className:`max-w-md text-center`,children:[(0,H.jsx)(`h1`,{className:`text-[16px] font-semibold`,children:e}),(0,H.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:t})]})}),fie=({meta:e,children:t})=>{let n=K(),r=rne(),i=(0,o.useMemo)(()=>(e.sources??[]).map(e=>e.source),[e.sources]),a=lie(i,r),s=(0,o.useMemo)(()=>uie(e,a),[e,a]),c=(0,o.useMemo)(()=>{let e=new Map(i.flatMap(e=>e.resources.map(t=>[t,e]))),t=t=>{let n=e.get(t);return n&&r(n)};return{client:Ys(n,t),resourceClient:t}},[i,n,r]);return(0,H.jsx)(ine,{client:c.client,resourceClient:c.resourceClient,children:(0,H.jsx)(c_.Provider,{value:s,children:t})})},pie=({children:e})=>{let t=l_();return t.isPending?(0,H.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,H.jsx)(Ed,{}),` Loading`]}):t.error?(0,H.jsx)(u_,{title:`Cannot reach the API`,children:Fs(t.error)?t.error.message:`The server did not answer. Is it running?`}):(0,H.jsx)(fie,{meta:t.data,children:e})},d_=e=>J().permissions[e]??oie,f_=(e,t)=>t>=60&&t>Math.abs(e),p_=({title:e,open:t,onClose:n,children:r})=>{let i=(0,o.useRef)(null),a=(0,o.useRef)(void 0);return Su(i,t,n),t?(0,H.jsxs)(`div`,{className:`fixed inset-0 z-[80]`,children:[(0,H.jsx)(`div`,{className:`absolute inset-0 bg-backdrop/40`,onClick:n,"aria-hidden":!0}),(0,H.jsxs)(`div`,{ref:i,role:`dialog`,"aria-modal":`true`,"aria-label":e,tabIndex:-1,className:`absolute inset-x-0 bottom-0 flex max-h-[85vh] flex-col rounded-t-xl border-t bg-background shadow-pop outline-none`,children:[(0,H.jsxs)(`header`,{className:`relative flex shrink-0 touch-none items-center justify-between border-b px-4`,onPointerDown:e=>{e.pointerType===`touch`&&(a.current={x:e.clientX,y:e.clientY})},onPointerUp:e=>{if(!a.current)return;let t=f_(e.clientX-a.current.x,e.clientY-a.current.y);a.current=void 0,t&&n()},onPointerCancel:()=>a.current=void 0,children:[(0,H.jsx)(`span`,{className:`absolute left-1/2 top-1.5 h-1 w-9 -translate-x-1/2 rounded-full bg-border-strong`,"aria-hidden":!0}),(0,H.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:e}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Close`,onClick:n,className:`-mr-2 inline-flex size-11 items-center justify-center rounded-md text-muted-foreground hover:bg-muted`,children:(0,H.jsx)(Qn,{className:`size-5`})})]}),(0,H.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 pb-6`,children:r})]})]}):null},m_=({title:e,description:t,open:n,onClose:r,actions:i,children:a,wide:o})=>{let s=pu();return n?s?(0,H.jsx)(Sf,{title:e,description:t,onClose:r,actions:i,wide:o,children:a}):(0,H.jsx)(p_,{title:e,open:!0,onClose:r,children:(0,H.jsxs)(`div`,{className:`pt-3`,children:[t&&(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:t}),a&&(0,H.jsx)(`div`,{className:`mt-4`,children:a}),(0,H.jsx)(`div`,{className:`mt-5 flex flex-col-reverse gap-2 [&>*]:min-h-11`,children:i})]})}):null};function h_(){var e=[...arguments];return(0,o.useMemo)(()=>t=>{e.forEach(e=>e(t))},e)}var g_=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function __(e){let t=Object.prototype.toString.call(e);return t===`[object Window]`||t===`[object global]`}function v_(e){return`nodeType`in e}function y_(e){return e?__(e)?e:v_(e)?e.ownerDocument?.defaultView??window:window:window}function b_(e){let{Document:t}=y_(e);return e instanceof t}function x_(e){return!__(e)&&e instanceof y_(e).HTMLElement}function S_(e){return e instanceof y_(e).SVGElement}function C_(e){return e?__(e)?e.document:v_(e)?b_(e)?e:x_(e)||S_(e)?e.ownerDocument:document:document:document}var w_=g_?o.useLayoutEffect:o.useEffect;function T_(e){let t=(0,o.useRef)(e);return w_(()=>{t.current=e}),(0,o.useCallback)(function(){var e=[...arguments];return t.current==null?void 0:t.current(...e)},[])}function E_(){let e=(0,o.useRef)(null);return[(0,o.useCallback)((t,n)=>{e.current=setInterval(t,n)},[]),(0,o.useCallback)(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[])]}function D_(e,t){t===void 0&&(t=[e]);let n=(0,o.useRef)(e);return w_(()=>{n.current!==e&&(n.current=e)},t),n}function O_(e,t){let n=(0,o.useRef)();return(0,o.useMemo)(()=>{let t=e(n.current);return n.current=t,t},[...t])}function k_(e){let t=T_(e),n=(0,o.useRef)(null);return[n,(0,o.useCallback)(e=>{e!==n.current&&t?.(e,n.current),n.current=e},[])]}function A_(e){let t=(0,o.useRef)();return(0,o.useEffect)(()=>{t.current=e},[e]),t.current}var j_={};function M_(e,t){return(0,o.useMemo)(()=>{if(t)return t;let n=j_[e]==null?0:j_[e]+1;return j_[e]=n,e+`-`+n},[e,t])}function N_(e){return function(t){return[...arguments].slice(1).reduce((t,n)=>{let r=Object.entries(n);for(let[n,i]of r){let r=t[n];r!=null&&(t[n]=r+e*i)}return t},{...t})}}var P_=N_(1),F_=N_(-1);function I_(e){return`clientX`in e&&`clientY`in e}function L_(e){if(!e)return!1;let{KeyboardEvent:t}=y_(e.target);return t&&e instanceof t}function R_(e){if(!e)return!1;let{TouchEvent:t}=y_(e.target);return t&&e instanceof t}function z_(e){if(R_(e)){if(e.touches&&e.touches.length){let{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}if(e.changedTouches&&e.changedTouches.length){let{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return I_(e)?{x:e.clientX,y:e.clientY}:null}var B_=Object.freeze({Translate:{toString(e){if(!e)return;let{x:t,y:n}=e;return`translate3d(`+(t?Math.round(t):0)+`px, `+(n?Math.round(n):0)+`px, 0)`}},Scale:{toString(e){if(!e)return;let{scaleX:t,scaleY:n}=e;return`scaleX(`+t+`) scaleY(`+n+`)`}},Transform:{toString(e){if(e)return[B_.Translate.toString(e),B_.Scale.toString(e)].join(` `)}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+` `+n+`ms `+r}}}),V_=`a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]`;function H_(e){return e.matches(V_)?e:e.querySelector(V_)}var U_={display:`none`};function W_(e){let{id:t,value:n}=e;return o.createElement(`div`,{id:t,style:U_},n)}function G_(e){let{id:t,announcement:n,ariaLiveType:r=`assertive`}=e;return o.createElement(`div`,{id:t,style:{position:`fixed`,top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:`hidden`,clip:`rect(0 0 0 0)`,clipPath:`inset(100%)`,whiteSpace:`nowrap`},role:`status`,"aria-live":r,"aria-atomic":!0},n)}function K_(){let[e,t]=(0,o.useState)(``);return{announce:(0,o.useCallback)(e=>{e!=null&&t(e)},[]),announcement:e}}var q_=(0,o.createContext)(null);function J_(e){let t=(0,o.useContext)(q_);(0,o.useEffect)(()=>{if(!t)throw Error(`useDndMonitor must be used within a children of <DndContext>`);return t(e)},[e,t])}function Y_(){let[e]=(0,o.useState)(()=>new Set),t=(0,o.useCallback)(t=>(e.add(t),()=>e.delete(t)),[e]);return[(0,o.useCallback)(t=>{let{type:n,event:r}=t;e.forEach(e=>e[n]?.call(e,r))},[e]),t]}var X_={draggable:`
|
|
9
9
|
To pick up a draggable item, press the space bar.
|
|
10
10
|
While dragging, use the arrow keys to move the item.
|
|
11
11
|
Press space again to drop the item in its new position, or press escape to cancel.
|
|
12
|
-
`},Q_={onDragStart(e){let{active:t}=e;return`Picked up draggable item `+t.id+`.`},onDragOver(e){let{active:t,over:n}=e;return n?`Draggable item `+t.id+` was moved over droppable area `+n.id+`.`:`Draggable item `+t.id+` is no longer over a droppable area.`},onDragEnd(e){let{active:t,over:n}=e;return n?`Draggable item `+t.id+` was dropped over droppable area `+n.id:`Draggable item `+t.id+` was dropped.`},onDragCancel(e){let{active:t}=e;return`Dragging was cancelled. Draggable item `+t.id+` was dropped.`}};function $_(e){let{announcements:t=Q_,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=Z_}=e,{announce:a,announcement:s}=q_(),c=N_(`DndLiveRegion`),[l,u]=(0,o.useState)(!1);if((0,o.useEffect)(()=>{u(!0)},[]),Y_((0,o.useMemo)(()=>({onDragStart(e){let{active:n}=e;a(t.onDragStart({active:n}))},onDragMove(e){let{active:n,over:r}=e;t.onDragMove&&a(t.onDragMove({active:n,over:r}))},onDragOver(e){let{active:n,over:r}=e;a(t.onDragOver({active:n,over:r}))},onDragEnd(e){let{active:n,over:r}=e;a(t.onDragEnd({active:n,over:r}))},onDragCancel(e){let{active:n,over:r}=e;a(t.onDragCancel({active:n,over:r}))}}),[a,t])),!l)return null;let d=o.createElement(o.Fragment,null,o.createElement(G_,{id:r,value:i.draggable}),o.createElement(K_,{id:c,announcement:s}));return n?(0,tr.createPortal)(d,n):d}var ev;(function(e){e.DragStart=`dragStart`,e.DragMove=`dragMove`,e.DragEnd=`dragEnd`,e.DragCancel=`dragCancel`,e.DragOver=`dragOver`,e.RegisterDroppable=`registerDroppable`,e.SetDroppableDisabled=`setDroppableDisabled`,e.UnregisterDroppable=`unregisterDroppable`})(ev||={});function tv(){}function nv(e,t){return(0,o.useMemo)(()=>({sensor:e,options:t??{}}),[e,t])}function rv(){var e=[...arguments];return(0,o.useMemo)(()=>[...e].filter(e=>e!=null),[...e])}var iv=Object.freeze({x:0,y:0});function av(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function ov(e,t){let n=B_(e);if(!n)return`0 0`;let r={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return r.x+`% `+r.y+`%`}function sv(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return n-r}function cv(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function lv(e){let{left:t,top:n,height:r,width:i}=e;return[{x:t,y:n},{x:t+i,y:n},{x:t,y:n+r},{x:t+i,y:n+r}]}function uv(e,t){if(!e||e.length===0)return null;let[n]=e;return t?n[t]:n}function dv(e,t,n){return t===void 0&&(t=e.left),n===void 0&&(n=e.top),{x:t+e.width*.5,y:n+e.height*.5}}var fv=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e,i=dv(t,t.left,t.top),a=[];for(let e of r){let{id:t}=e,r=n.get(t);if(r){let n=av(dv(r),i);a.push({id:t,data:{droppableContainer:e,value:n}})}}return a.sort(sv)},pv=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e,i=lv(t),a=[];for(let e of r){let{id:t}=e,r=n.get(t);if(r){let n=lv(r),o=i.reduce((e,t,r)=>e+av(n[r],t),0),s=Number((o/4).toFixed(4));a.push({id:t,data:{droppableContainer:e,value:s}})}}return a.sort(sv)};function mv(e,t){let n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),i=Math.min(t.left+t.width,e.left+e.width),a=Math.min(t.top+t.height,e.top+e.height),o=i-r,s=a-n;if(r<i&&n<a){let n=t.width*t.height,r=e.width*e.height,i=o*s,a=i/(n+r-i);return Number(a.toFixed(4))}return 0}var hv=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e,i=[];for(let e of r){let{id:r}=e,a=n.get(r);if(a){let n=mv(a,t);n>0&&i.push({id:r,data:{droppableContainer:e,value:n}})}}return i.sort(cv)};function gv(e,t){let{top:n,left:r,bottom:i,right:a}=t;return n<=e.y&&e.y<=i&&r<=e.x&&e.x<=a}var _v=e=>{let{droppableContainers:t,droppableRects:n,pointerCoordinates:r}=e;if(!r)return[];let i=[];for(let e of t){let{id:t}=e,a=n.get(t);if(a&&gv(r,a)){let n=lv(a).reduce((e,t)=>e+av(r,t),0),o=Number((n/4).toFixed(4));i.push({id:t,data:{droppableContainer:e,value:o}})}}return i.sort(sv)};function vv(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function yv(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:iv}function bv(e){return function(t){return[...arguments].slice(1).reduce((t,n)=>({...t,top:t.top+e*n.y,bottom:t.bottom+e*n.y,left:t.left+e*n.x,right:t.right+e*n.x}),{...t})}}var xv=bv(1);function Sv(e){if(e.startsWith(`matrix3d(`)){let t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}if(e.startsWith(`matrix(`)){let t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function Cv(e,t,n){let r=Sv(t);if(!r)return e;let{scaleX:i,scaleY:a,x:o,y:s}=r,c=e.left-o-(1-i)*parseFloat(n),l=e.top-s-(1-a)*parseFloat(n.slice(n.indexOf(` `)+1)),u=i?e.width/i:e.width,d=a?e.height/a:e.height;return{width:u,height:d,top:l,right:c+u,bottom:l+d,left:c}}var wv={ignoreTransform:!1};function Tv(e,t){t===void 0&&(t=wv);let n=e.getBoundingClientRect();if(t.ignoreTransform){let{transform:t,transformOrigin:r}=b_(e).getComputedStyle(e);t&&(n=Cv(n,t,r))}let{top:r,left:i,width:a,height:o,bottom:s,right:c}=n;return{top:r,left:i,width:a,height:o,bottom:s,right:c}}function Ev(e){return Tv(e,{ignoreTransform:!0})}function Dv(e){let t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function Ov(e,t){return t===void 0&&(t=b_(e).getComputedStyle(e)),t.position===`fixed`}function kv(e,t){t===void 0&&(t=b_(e).getComputedStyle(e));let n=/(auto|scroll|overlay)/;return[`overflow`,`overflowX`,`overflowY`].some(e=>{let r=t[e];return typeof r==`string`&&n.test(r)})}function Av(e,t){let n=[];function r(i){if(t!=null&&n.length>=t||!i)return n;if(x_(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!S_(i)||C_(i)||n.includes(i))return n;let a=b_(e).getComputedStyle(i);return i!==e&&kv(i,a)&&n.push(i),Ov(i,a)?n:r(i.parentNode)}return e?r(e):n}function jv(e){let[t]=Av(e,1);return t??null}function Mv(e){return!__||!e?null:v_(e)?e:y_(e)?x_(e)||e===w_(e).scrollingElement?window:S_(e)?e:null:null}function Nv(e){return v_(e)?e.scrollX:e.scrollLeft}function Pv(e){return v_(e)?e.scrollY:e.scrollTop}function Fv(e){return{x:Nv(e),y:Pv(e)}}var Iv;(function(e){e[e.Forward=1]=`Forward`,e[e.Backward=-1]=`Backward`})(Iv||={});function Lv(e){return!__||!e?!1:e===document.scrollingElement}function Rv(e){let t={x:0,y:0},n=Lv(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height};return{isTop:e.scrollTop<=t.y,isLeft:e.scrollLeft<=t.x,isBottom:e.scrollTop>=r.y,isRight:e.scrollLeft>=r.x,maxScroll:r,minScroll:t}}var zv={x:.2,y:.2};function Bv(e,t,n,r,i){let{top:a,left:o,right:s,bottom:c}=n;r===void 0&&(r=10),i===void 0&&(i=zv);let{isTop:l,isBottom:u,isLeft:d,isRight:f}=Rv(e),p={x:0,y:0},m={x:0,y:0},h={height:t.height*i.y,width:t.width*i.x};return!l&&a<=t.top+h.height?(p.y=Iv.Backward,m.y=r*Math.abs((t.top+h.height-a)/h.height)):!u&&c>=t.bottom-h.height&&(p.y=Iv.Forward,m.y=r*Math.abs((t.bottom-h.height-c)/h.height)),!f&&s>=t.right-h.width?(p.x=Iv.Forward,m.x=r*Math.abs((t.right-h.width-s)/h.width)):!d&&o<=t.left+h.width&&(p.x=Iv.Backward,m.x=r*Math.abs((t.left+h.width-o)/h.width)),{direction:p,speed:m}}function Vv(e){if(e===document.scrollingElement){let{innerWidth:e,innerHeight:t}=window;return{top:0,left:0,right:e,bottom:t,width:e,height:t}}let{top:t,left:n,right:r,bottom:i}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:i,width:e.clientWidth,height:e.clientHeight}}function Hv(e){return e.reduce((e,t)=>F_(e,Fv(t)),iv)}function Uv(e){return e.reduce((e,t)=>e+Nv(t),0)}function Wv(e){return e.reduce((e,t)=>e+Pv(t),0)}function Gv(e,t){if(t===void 0&&(t=Tv),!e)return;let{top:n,left:r,bottom:i,right:a}=t(e);jv(e)&&(i<=0||a<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:`center`,inline:`center`})}var Kv=[[`x`,[`left`,`right`],Uv],[`y`,[`top`,`bottom`],Wv]],qv=class{constructor(e,t){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;let n=Av(t),r=Hv(n);this.rect={...e},this.width=e.width,this.height=e.height;for(let[e,t,i]of Kv)for(let a of t)Object.defineProperty(this,a,{get:()=>{let t=i(n),o=r[e]-t;return this.rect[a]+o},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}},Jv=class{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(e=>this.target?.removeEventListener(...e))},this.target=e}add(e,t,n){var r;(r=this.target)==null||r.addEventListener(e,t,n),this.listeners.push([e,t,n])}};function Yv(e){let{EventTarget:t}=b_(e);return e instanceof t?e:w_(e)}function Xv(e,t){let n=Math.abs(e.x),r=Math.abs(e.y);return typeof t==`number`?Math.sqrt(n**2+r**2)>t:`x`in t&&`y`in t?n>t.x&&r>t.y:`x`in t?n>t.x:`y`in t&&r>t.y}var Zv;(function(e){e.Click=`click`,e.DragStart=`dragstart`,e.Keydown=`keydown`,e.ContextMenu=`contextmenu`,e.Resize=`resize`,e.SelectionChange=`selectionchange`,e.VisibilityChange=`visibilitychange`})(Zv||={});function Qv(e){e.preventDefault()}function $v(e){e.stopPropagation()}var J;(function(e){e.Space=`Space`,e.Down=`ArrowDown`,e.Right=`ArrowRight`,e.Left=`ArrowLeft`,e.Up=`ArrowUp`,e.Esc=`Escape`,e.Enter=`Enter`,e.Tab=`Tab`})(J||={});var ey={start:[J.Space,J.Enter],cancel:[J.Esc],end:[J.Space,J.Enter,J.Tab]},ty=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case J.Right:return{...n,x:n.x+25};case J.Left:return{...n,x:n.x-25};case J.Down:return{...n,y:n.y+25};case J.Up:return{...n,y:n.y-25}}},ny=class{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;let{event:{target:t}}=e;this.props=e,this.listeners=new Jv(w_(t)),this.windowListeners=new Jv(b_(t)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Zv.Resize,this.handleCancel),this.windowListeners.add(Zv.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Zv.Keydown,this.handleKeyDown))}handleStart(){let{activeNode:e,onStart:t}=this.props,n=e.node.current;n&&Gv(n),t(iv)}handleKeyDown(e){if(R_(e)){let{active:t,context:n,options:r}=this.props,{keyboardCodes:i=ey,coordinateGetter:a=ty,scrollBehavior:o=`smooth`}=r,{code:s}=e;if(i.end.includes(s)){this.handleEnd(e);return}if(i.cancel.includes(s)){this.handleCancel(e);return}let{collisionRect:c}=n.current,l=c?{x:c.left,y:c.top}:iv;this.referenceCoordinates||=l;let u=a(e,{active:t,context:n.current,currentCoordinates:l});if(u){let t=I_(u,l),r={x:0,y:0},{scrollableAncestors:i}=n.current;for(let n of i){let i=e.code,{isTop:a,isRight:s,isLeft:c,isBottom:l,maxScroll:d,minScroll:f}=Rv(n),p=Vv(n),m={x:Math.min(i===J.Right?p.right-p.width/2:p.right,Math.max(i===J.Right?p.left:p.left+p.width/2,u.x)),y:Math.min(i===J.Down?p.bottom-p.height/2:p.bottom,Math.max(i===J.Down?p.top:p.top+p.height/2,u.y))},h=i===J.Right&&!s||i===J.Left&&!c,g=i===J.Down&&!l||i===J.Up&&!a;if(h&&m.x!==u.x){let e=n.scrollLeft+t.x,a=i===J.Right&&e<=d.x||i===J.Left&&e>=f.x;if(a&&!t.y){n.scrollTo({left:e,behavior:o});return}r.x=a?n.scrollLeft-e:i===J.Right?n.scrollLeft-d.x:n.scrollLeft-f.x,r.x&&n.scrollBy({left:-r.x,behavior:o});break}if(g&&m.y!==u.y){let e=n.scrollTop+t.y,a=i===J.Down&&e<=d.y||i===J.Up&&e>=f.y;if(a&&!t.x){n.scrollTo({top:e,behavior:o});return}r.y=a?n.scrollTop-e:i===J.Down?n.scrollTop-d.y:n.scrollTop-f.y,r.y&&n.scrollBy({top:-r.y,behavior:o});break}}this.handleMove(e,F_(I_(u,this.referenceCoordinates),r))}}}handleMove(e,t){let{onMove:n}=this.props;e.preventDefault(),n(t)}handleEnd(e){let{onEnd:t}=this.props;e.preventDefault(),this.detach(),t()}handleCancel(e){let{onCancel:t}=this.props;e.preventDefault(),this.detach(),t()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}};ny.activators=[{eventName:`onKeyDown`,handler:(e,t,n)=>{let{keyboardCodes:r=ey,onActivation:i}=t,{active:a}=n,{code:o}=e.nativeEvent;if(r.start.includes(o)){let t=a.activatorNode.current;return t&&e.target!==t?!1:(e.preventDefault(),i?.({event:e.nativeEvent}),!0)}return!1}}];function ry(e){return!!(e&&`distance`in e)}function iy(e){return!!(e&&`delay`in e)}var ay=class{constructor(e,t,n){n===void 0&&(n=Yv(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=t;let{event:r}=e,{target:i}=r;this.props=e,this.events=t,this.document=w_(i),this.documentListeners=new Jv(this.document),this.listeners=new Jv(n),this.windowListeners=new Jv(b_(i)),this.initialCoordinates=B_(r)??iv,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){let{events:e,props:{options:{activationConstraint:t,bypassActivationConstraint:n}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(Zv.Resize,this.handleCancel),this.windowListeners.add(Zv.DragStart,Qv),this.windowListeners.add(Zv.VisibilityChange,this.handleCancel),this.windowListeners.add(Zv.ContextMenu,Qv),this.documentListeners.add(Zv.Keydown,this.handleKeydown),t){if(n!=null&&n({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(iy(t)){this.timeoutId=setTimeout(this.handleStart,t.delay),this.handlePending(t);return}if(ry(t)){this.handlePending(t);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,t){let{active:n,onPending:r}=this.props;r(n,e,this.initialCoordinates,t)}handleStart(){let{initialCoordinates:e}=this,{onStart:t}=this.props;e&&(this.activated=!0,this.documentListeners.add(Zv.Click,$v,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Zv.SelectionChange,this.removeTextSelection),t(e))}handleMove(e){let{activated:t,initialCoordinates:n,props:r}=this,{onMove:i,options:{activationConstraint:a}}=r;if(!n)return;let o=B_(e)??iv,s=I_(n,o);if(!t&&a){if(ry(a)){if(a.tolerance!=null&&Xv(s,a.tolerance))return this.handleCancel();if(Xv(s,a.distance))return this.handleStart()}if(iy(a)&&Xv(s,a.tolerance))return this.handleCancel();this.handlePending(a,s);return}e.cancelable&&e.preventDefault(),i(o)}handleEnd(){let{onAbort:e,onEnd:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleCancel(){let{onAbort:e,onCancel:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleKeydown(e){e.code===J.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}},oy={cancel:{name:`pointercancel`},move:{name:`pointermove`},end:{name:`pointerup`}},sy=class extends ay{constructor(e){let{event:t}=e,n=w_(t.target);super(e,oy,n)}};sy.activators=[{eventName:`onPointerDown`,handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];var cy={move:{name:`mousemove`},end:{name:`mouseup`}},ly;(function(e){e[e.RightClick=2]=`RightClick`})(ly||={});var uy=class extends ay{constructor(e){super(e,cy,w_(e.event.target))}};uy.activators=[{eventName:`onMouseDown`,handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button!==ly.RightClick&&(r?.({event:n}),!0)}}];var dy={cancel:{name:`touchcancel`},move:{name:`touchmove`},end:{name:`touchend`}},fy=class extends ay{constructor(e){super(e,dy)}static setup(){return window.addEventListener(dy.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(dy.move.name,e)};function e(){}}};fy.activators=[{eventName:`onTouchStart`,handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t,{touches:i}=n;return i.length>1?!1:(r?.({event:n}),!0)}}];var py;(function(e){e[e.Pointer=0]=`Pointer`,e[e.DraggableRect=1]=`DraggableRect`})(py||={});var my;(function(e){e[e.TreeOrder=0]=`TreeOrder`,e[e.ReversedTreeOrder=1]=`ReversedTreeOrder`})(my||={});function hy(e){let{acceleration:t,activator:n=py.Pointer,canScroll:r,draggingRect:i,enabled:a,interval:s=5,order:c=my.TreeOrder,pointerCoordinates:l,scrollableAncestors:u,scrollableAncestorRects:d,delta:f,threshold:p}=e,m=_y({delta:f,disabled:!a}),[h,g]=D_(),_=(0,o.useRef)({x:0,y:0}),v=(0,o.useRef)({x:0,y:0}),y=(0,o.useMemo)(()=>{switch(n){case py.Pointer:return l?{top:l.y,bottom:l.y,left:l.x,right:l.x}:null;case py.DraggableRect:return i}},[n,i,l]),b=(0,o.useRef)(null),x=(0,o.useCallback)(()=>{let e=b.current;if(!e)return;let t=_.current.x*v.current.x,n=_.current.y*v.current.y;e.scrollBy(t,n)},[]),S=(0,o.useMemo)(()=>c===my.TreeOrder?[...u].reverse():u,[c,u]);(0,o.useEffect)(()=>{if(!a||!u.length||!y){g();return}for(let e of S){if(r?.(e)===!1)continue;let n=u.indexOf(e),i=d[n];if(!i)continue;let{direction:a,speed:o}=Bv(e,i,y,t,p);for(let e of[`x`,`y`])m[e][a[e]]||(o[e]=0,a[e]=0);if(o.x>0||o.y>0){g(),b.current=e,h(x,s),_.current=o,v.current=a;return}}_.current={x:0,y:0},v.current={x:0,y:0},g()},[t,x,r,g,a,s,JSON.stringify(y),JSON.stringify(m),h,u,S,d,JSON.stringify(p)])}var gy={x:{[Iv.Backward]:!1,[Iv.Forward]:!1},y:{[Iv.Backward]:!1,[Iv.Forward]:!1}};function _y(e){let{delta:t,disabled:n}=e,r=j_(t);return k_(e=>{if(n||!r||!e)return gy;let i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[Iv.Backward]:e.x[Iv.Backward]||i.x===-1,[Iv.Forward]:e.x[Iv.Forward]||i.x===1},y:{[Iv.Backward]:e.y[Iv.Backward]||i.y===-1,[Iv.Forward]:e.y[Iv.Forward]||i.y===1}}},[n,t,r])}function vy(e,t){let n=t==null?void 0:e.get(t),r=n?n.node.current:null;return k_(e=>t==null?null:r??e??null,[r,t])}function yy(e,t){return(0,o.useMemo)(()=>e.reduce((e,n)=>{let{sensor:r}=n,i=r.activators.map(e=>({eventName:e.eventName,handler:t(e.handler,n)}));return[...e,...i]},[]),[e,t])}var by;(function(e){e[e.Always=0]=`Always`,e[e.BeforeDragging=1]=`BeforeDragging`,e[e.WhileDragging=2]=`WhileDragging`})(by||={});var xy;(function(e){e.Optimized=`optimized`})(xy||={});var Sy=new Map;function Cy(e,t){let{dragging:n,dependencies:r,config:i}=t,[a,s]=(0,o.useState)(null),{frequency:c,measure:l,strategy:u}=i,d=(0,o.useRef)(e),f=_(),p=O_(f),m=(0,o.useCallback)(function(e){e===void 0&&(e=[]),!p.current&&s(t=>t===null?e:t.concat(e.filter(e=>!t.includes(e))))},[p]),h=(0,o.useRef)(null),g=k_(t=>{if(f&&!n)return Sy;if(!t||t===Sy||d.current!==e||a!=null){let t=new Map;for(let n of e){if(!n)continue;if(a&&a.length>0&&!a.includes(n.id)&&n.rect.current){t.set(n.id,n.rect.current);continue}let e=n.node.current,r=e?new qv(l(e),e):null;n.rect.current=r,r&&t.set(n.id,r)}return t}return t},[e,a,n,f,l]);return(0,o.useEffect)(()=>{d.current=e},[e]),(0,o.useEffect)(()=>{f||m()},[n,f]),(0,o.useEffect)(()=>{a&&a.length>0&&s(null)},[JSON.stringify(a)]),(0,o.useEffect)(()=>{f||typeof c!=`number`||h.current!==null||(h.current=setTimeout(()=>{m(),h.current=null},c))},[c,f,m,...r]),{droppableRects:g,measureDroppableContainers:m,measuringScheduled:a!=null};function _(){switch(u){case by.Always:return!1;case by.BeforeDragging:return n;default:return!n}}}function wy(e,t){return k_(n=>e?n||(typeof t==`function`?t(e):e):null,[t,e])}function Ty(e,t){return wy(e,t)}function Ey(e){let{callback:t,disabled:n}=e,r=E_(t),i=(0,o.useMemo)(()=>{if(n||typeof window>`u`||window.MutationObserver===void 0)return;let{MutationObserver:e}=window;return new e(r)},[r,n]);return(0,o.useEffect)(()=>()=>i?.disconnect(),[i]),i}function Dy(e){let{callback:t,disabled:n}=e,r=E_(t),i=(0,o.useMemo)(()=>{if(n||typeof window>`u`||window.ResizeObserver===void 0)return;let{ResizeObserver:e}=window;return new e(r)},[n]);return(0,o.useEffect)(()=>()=>i?.disconnect(),[i]),i}function Oy(e){return new qv(Tv(e),e)}function ky(e,t,n){t===void 0&&(t=Oy);let[r,i]=(0,o.useState)(null);function a(){i(r=>{if(!e)return null;if(e.isConnected===!1)return r??n??null;let i=t(e);return JSON.stringify(r)===JSON.stringify(i)?r:i})}let s=Ey({callback(t){if(e)for(let n of t){let{type:t,target:r}=n;if(t===`childList`&&r instanceof HTMLElement&&r.contains(e)){a();break}}}}),c=Dy({callback:a});return T_(()=>{a(),e?(c?.observe(e),s?.observe(document.body,{childList:!0,subtree:!0})):(c?.disconnect(),s?.disconnect())},[e]),r}function Ay(e){return yv(e,wy(e))}var jy=[];function My(e){let t=(0,o.useRef)(e),n=k_(n=>e?n&&n!==jy&&e&&t.current&&e.parentNode===t.current.parentNode?n:Av(e):jy,[e]);return(0,o.useEffect)(()=>{t.current=e},[e]),n}function Ny(e){let[t,n]=(0,o.useState)(null),r=(0,o.useRef)(e),i=(0,o.useCallback)(e=>{let t=Mv(e.target);t&&n(e=>e?(e.set(t,Fv(t)),new Map(e)):null)},[]);return(0,o.useEffect)(()=>{let t=r.current;if(e!==t){a(t);let o=e.map(e=>{let t=Mv(e);return t?(t.addEventListener(`scroll`,i,{passive:!0}),[t,Fv(t)]):null}).filter(e=>e!=null);n(o.length?new Map(o):null),r.current=e}return()=>{a(e),a(t)};function a(e){e.forEach(e=>{Mv(e)?.removeEventListener(`scroll`,i)})}},[i,e]),(0,o.useMemo)(()=>e.length?t?Array.from(t.values()).reduce((e,t)=>F_(e,t),iv):Hv(e):iv,[e,t])}function Py(e,t){t===void 0&&(t=[]);let n=(0,o.useRef)(null);return(0,o.useEffect)(()=>{n.current=null},t),(0,o.useEffect)(()=>{let t=e!==iv;t&&!n.current&&(n.current=e),!t&&n.current&&(n.current=null)},[e]),n.current?I_(e,n.current):iv}function Fy(e){(0,o.useEffect)(()=>{if(!__)return;let t=e.map(e=>{let{sensor:t}=e;return t.setup==null?void 0:t.setup()});return()=>{for(let e of t)e?.()}},e.map(e=>{let{sensor:t}=e;return t}))}function Iy(e,t){return(0,o.useMemo)(()=>e.reduce((e,n)=>{let{eventName:r,handler:i}=n;return e[r]=e=>{i(e,t)},e},{}),[e,t])}function Ly(e){return(0,o.useMemo)(()=>e?Dv(e):null,[e])}var Ry=[];function zy(e,t){t===void 0&&(t=Tv);let[n]=e,r=Ly(n?b_(n):null),[i,a]=(0,o.useState)(Ry);function s(){a(()=>e.length?e.map(e=>Lv(e)?r:new qv(t(e),e)):Ry)}let c=Dy({callback:s});return T_(()=>{c?.disconnect(),s(),e.forEach(e=>c?.observe(e))},[e]),i}function By(e){if(!e)return null;if(e.children.length>1)return e;let t=e.children[0];return S_(t)?t:e}function Vy(e){let{measure:t}=e,[n,r]=(0,o.useState)(null),i=Dy({callback:(0,o.useCallback)(e=>{for(let{target:n}of e)if(S_(n)){r(e=>{let r=t(n);return e?{...e,width:r.width,height:r.height}:r});break}},[t])}),[a,s]=A_((0,o.useCallback)(e=>{let n=By(e);i?.disconnect(),n&&i?.observe(n),r(n?t(n):null)},[t,i]));return(0,o.useMemo)(()=>({nodeRef:a,rect:n,setRef:s}),[n,a,s])}var Hy=[{sensor:sy,options:{}},{sensor:ny,options:{}}],Uy={current:{}},Wy={draggable:{measure:Ev},droppable:{measure:Ev,strategy:by.WhileDragging,frequency:xy.Optimized},dragOverlay:{measure:Tv}},Gy=class extends Map{get(e){return e==null?void 0:super.get(e)??void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:t}=e;return!t})}getNodeFor(e){return this.get(e)?.node.current??void 0}},Ky={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Gy,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:tv},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Wy,measureDroppableContainers:tv,windowRect:null,measuringScheduled:!1},qy={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:``},dispatch:tv,draggableNodes:new Map,over:null,measureDroppableContainers:tv},Jy=(0,o.createContext)(qy),Yy=(0,o.createContext)(Ky);function Xy(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Gy}}}function Zy(e,t){switch(t.type){case ev.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case ev.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case ev.DragEnd:case ev.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ev.RegisterDroppable:{let{element:n}=t,{id:r}=n,i=new Gy(e.droppable.containers);return i.set(r,n),{...e,droppable:{...e.droppable,containers:i}}}case ev.SetDroppableDisabled:{let{id:n,key:r,disabled:i}=t,a=e.droppable.containers.get(n);if(!a||r!==a.key)return e;let o=new Gy(e.droppable.containers);return o.set(n,{...a,disabled:i}),{...e,droppable:{...e.droppable,containers:o}}}case ev.UnregisterDroppable:{let{id:n,key:r}=t,i=e.droppable.containers.get(n);if(!i||r!==i.key)return e;let a=new Gy(e.droppable.containers);return a.delete(n),{...e,droppable:{...e.droppable,containers:a}}}default:return e}}function Qy(e){let{disabled:t}=e,{active:n,activatorEvent:r,draggableNodes:i}=(0,o.useContext)(Jy),a=j_(r),s=j_(n?.id);return(0,o.useEffect)(()=>{if(!t&&!r&&a&&s!=null){if(!R_(a)||document.activeElement===a.target)return;let e=i.get(s);if(!e)return;let{activatorNode:t,node:n}=e;if(!t.current&&!n.current)return;requestAnimationFrame(()=>{for(let e of[t.current,n.current]){if(!e)continue;let t=U_(e);if(t){t.focus();break}}})}},[r,t,i,s,a]),null}function $y(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((e,t)=>t({transform:e,...r}),n):n}function eb(e){return(0,o.useMemo)(()=>({draggable:{...Wy.draggable,...e?.draggable},droppable:{...Wy.droppable,...e?.droppable},dragOverlay:{...Wy.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function tb(e){let{activeNode:t,measure:n,initialRect:r,config:i=!0}=e,a=(0,o.useRef)(!1),{x:s,y:c}=typeof i==`boolean`?{x:i,y:i}:i;T_(()=>{if(!s&&!c||!t){a.current=!1;return}if(a.current||!r)return;let e=t?.node.current;if(!e||e.isConnected===!1)return;let i=yv(n(e),r);if(s||(i.x=0),c||(i.y=0),a.current=!0,Math.abs(i.x)>0||Math.abs(i.y)>0){let t=jv(e);t&&t.scrollBy({top:i.y,left:i.x})}},[t,s,c,r,n])}var nb=(0,o.createContext)({...iv,scaleX:1,scaleY:1}),rb;(function(e){e[e.Uninitialized=0]=`Uninitialized`,e[e.Initializing=1]=`Initializing`,e[e.Initialized=2]=`Initialized`})(rb||={});var ib=(0,o.memo)(function(e){let{id:t,accessibility:n,autoScroll:r=!0,children:i,sensors:a=Hy,collisionDetection:s=hv,measuring:c,modifiers:l,...u}=e,[d,f]=(0,o.useReducer)(Zy,void 0,Xy),[p,m]=X_(),[h,g]=(0,o.useState)(rb.Uninitialized),_=h===rb.Initialized,{draggable:{active:v,nodes:y,translate:b},droppable:{containers:x}}=d,S=v==null?null:y.get(v),C=(0,o.useRef)({initial:null,translated:null}),w=(0,o.useMemo)(()=>v==null?null:{id:v,data:S?.data??Uy,rect:C},[v,S]),T=(0,o.useRef)(null),[E,D]=(0,o.useState)(null),[O,k]=(0,o.useState)(null),A=O_(u,Object.values(u)),j=N_(`DndDescribedBy`,t),M=(0,o.useMemo)(()=>x.getEnabled(),[x]),N=eb(c),{droppableRects:ee,measureDroppableContainers:P,measuringScheduled:te}=Cy(M,{dragging:_,dependencies:[b.x,b.y],config:N.droppable}),F=vy(y,v),ne=(0,o.useMemo)(()=>O?B_(O):null,[O]),re=je(),ie=Ty(F,N.draggable.measure);tb({activeNode:v==null?null:y.get(v),config:re.layoutShiftCompensation,initialRect:ie,measure:N.draggable.measure});let I=ky(F,N.draggable.measure,ie),ae=ky(F?F.parentElement:null),L=(0,o.useRef)({activatorEvent:null,active:null,activeNode:F,collisionRect:null,collisions:null,droppableRects:ee,draggableNodes:y,draggingNode:null,draggingNodeRect:null,droppableContainers:x,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),oe=x.getNodeFor(L.current.over?.id),R=Vy({measure:N.dragOverlay.measure}),se=R.nodeRef.current??F,ce=_?R.rect??I:null,le=!!(R.nodeRef.current&&R.rect),ue=Ay(le?null:I),de=Ly(se?b_(se):null),fe=My(_?oe??F:null),pe=zy(fe),me=$y(l,{transform:{x:b.x-ue.x,y:b.y-ue.y,scaleX:1,scaleY:1},activatorEvent:O,active:w,activeNodeRect:I,containerNodeRect:ae,draggingNodeRect:ce,over:L.current.over,overlayNodeRect:R.rect,scrollableAncestors:fe,scrollableAncestorRects:pe,windowRect:de}),he=ne?F_(ne,b):null,ge=Ny(fe),_e=Py(ge),ve=Py(ge,[I]),ye=F_(me,_e),be=ce?xv(ce,me):null,xe=w&&be?s({active:w,collisionRect:be,droppableRects:ee,droppableContainers:M,pointerCoordinates:he}):null,Se=uv(xe,`id`),[Ce,we]=(0,o.useState)(null),Te=vv(le?me:F_(me,ve),Ce?.rect??null,I),Ee=(0,o.useRef)(null),De=(0,o.useCallback)((e,t)=>{let{sensor:n,options:r}=t;if(T.current==null)return;let i=y.get(T.current);if(!i)return;let a=e.nativeEvent,o=new n({active:T.current,activeNode:i,event:a,options:r,context:L,onAbort(e){if(!y.get(e))return;let{onDragAbort:t}=A.current,n={id:e};t?.(n),p({type:`onDragAbort`,event:n})},onPending(e,t,n,r){if(!y.get(e))return;let{onDragPending:i}=A.current,a={id:e,constraint:t,initialCoordinates:n,offset:r};i?.(a),p({type:`onDragPending`,event:a})},onStart(e){let t=T.current;if(t==null)return;let n=y.get(t);if(!n)return;let{onDragStart:r}=A.current,i={activatorEvent:a,active:{id:t,data:n.data,rect:C}};(0,tr.unstable_batchedUpdates)(()=>{r?.(i),g(rb.Initializing),f({type:ev.DragStart,initialCoordinates:e,active:t}),p({type:`onDragStart`,event:i}),D(Ee.current),k(a)})},onMove(e){f({type:ev.DragMove,coordinates:e})},onEnd:s(ev.DragEnd),onCancel:s(ev.DragCancel)});Ee.current=o;function s(e){return async function(){let{active:t,collisions:n,over:r,scrollAdjustedTranslate:i}=L.current,o=null;if(t&&i){let{cancelDrop:s}=A.current;o={activatorEvent:a,active:t,collisions:n,delta:i,over:r},e===ev.DragEnd&&typeof s==`function`&&await Promise.resolve(s(o))&&(e=ev.DragCancel)}T.current=null,(0,tr.unstable_batchedUpdates)(()=>{f({type:e}),g(rb.Uninitialized),we(null),D(null),k(null),Ee.current=null;let t=e===ev.DragEnd?`onDragEnd`:`onDragCancel`;if(o){let e=A.current[t];e?.(o),p({type:t,event:o})}})}}},[y]),Oe=yy(a,(0,o.useCallback)((e,t)=>(n,r)=>{let i=n.nativeEvent,a=y.get(r);if(T.current!==null||!a||i.dndKit||i.defaultPrevented)return;let o={active:a};e(n,t.options,o)===!0&&(i.dndKit={capturedBy:t.sensor},T.current=r,De(n,t))},[y,De]));Fy(a),T_(()=>{I&&h===rb.Initializing&&g(rb.Initialized)},[I,h]),(0,o.useEffect)(()=>{let{onDragMove:e}=A.current,{active:t,activatorEvent:n,collisions:r,over:i}=L.current;if(!t||!n)return;let a={active:t,activatorEvent:n,collisions:r,delta:{x:ye.x,y:ye.y},over:i};(0,tr.unstable_batchedUpdates)(()=>{e?.(a),p({type:`onDragMove`,event:a})})},[ye.x,ye.y]),(0,o.useEffect)(()=>{let{active:e,activatorEvent:t,collisions:n,droppableContainers:r,scrollAdjustedTranslate:i}=L.current;if(!e||T.current==null||!t||!i)return;let{onDragOver:a}=A.current,o=r.get(Se),s=o&&o.rect.current?{id:o.id,rect:o.rect.current,data:o.data,disabled:o.disabled}:null,c={active:e,activatorEvent:t,collisions:n,delta:{x:i.x,y:i.y},over:s};(0,tr.unstable_batchedUpdates)(()=>{we(s),a?.(c),p({type:`onDragOver`,event:c})})},[Se]),T_(()=>{L.current={activatorEvent:O,active:w,activeNode:F,collisionRect:be,collisions:xe,droppableRects:ee,draggableNodes:y,draggingNode:se,draggingNodeRect:ce,droppableContainers:x,over:Ce,scrollableAncestors:fe,scrollAdjustedTranslate:ye},C.current={initial:ce,translated:be}},[w,F,xe,be,y,se,ce,ee,x,Ce,fe,ye]),hy({...re,delta:b,draggingRect:be,pointerCoordinates:he,scrollableAncestors:fe,scrollableAncestorRects:pe});let ke=(0,o.useMemo)(()=>({active:w,activeNode:F,activeNodeRect:I,activatorEvent:O,collisions:xe,containerNodeRect:ae,dragOverlay:R,draggableNodes:y,droppableContainers:x,droppableRects:ee,over:Ce,measureDroppableContainers:P,scrollableAncestors:fe,scrollableAncestorRects:pe,measuringConfiguration:N,measuringScheduled:te,windowRect:de}),[w,F,I,O,xe,ae,R,y,x,ee,Ce,P,fe,pe,N,te,de]),Ae=(0,o.useMemo)(()=>({activatorEvent:O,activators:Oe,active:w,activeNodeRect:I,ariaDescribedById:{draggable:j},dispatch:f,draggableNodes:y,over:Ce,measureDroppableContainers:P}),[O,Oe,w,I,f,j,y,Ce,P]);return o.createElement(J_.Provider,{value:m},o.createElement(Jy.Provider,{value:Ae},o.createElement(Yy.Provider,{value:ke},o.createElement(nb.Provider,{value:Te},i)),o.createElement(Qy,{disabled:n?.restoreFocus===!1})),o.createElement($_,{...n,hiddenTextDescribedById:j}));function je(){let e=E?.autoScrollEnabled===!1,t=typeof r==`object`?r.enabled===!1:r===!1,n=_&&!e&&!t;return typeof r==`object`?{...r,enabled:n}:{enabled:n}}}),ab=(0,o.createContext)(null),ob=`button`,sb=`Draggable`;function cb(e){let{id:t,data:n,disabled:r=!1,attributes:i}=e,a=N_(sb),{activators:s,activatorEvent:c,active:l,activeNodeRect:u,ariaDescribedById:d,draggableNodes:f,over:p}=(0,o.useContext)(Jy),{role:m=ob,roleDescription:h=`draggable`,tabIndex:g=0}=i??{},_=l?.id===t,v=(0,o.useContext)(_?nb:ab),[y,b]=A_(),[x,S]=A_(),C=Iy(s,t),w=O_(n);return T_(()=>(f.set(t,{id:t,key:a,node:y,activatorNode:x,data:w}),()=>{let e=f.get(t);e&&e.key===a&&f.delete(t)}),[f,t]),{active:l,activatorEvent:c,activeNodeRect:u,attributes:(0,o.useMemo)(()=>({role:m,tabIndex:g,"aria-disabled":r,"aria-pressed":_&&m===ob?!0:void 0,"aria-roledescription":h,"aria-describedby":d.draggable}),[r,m,g,_,h,d.draggable]),isDragging:_,listeners:r?void 0:C,node:y,over:p,setNodeRef:b,setActivatorNodeRef:S,transform:v}}function lb(){return(0,o.useContext)(Yy)}var ub=`Droppable`,db={timeout:25};function fb(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:i}=e,a=N_(ub),{active:s,dispatch:c,over:l,measureDroppableContainers:u}=(0,o.useContext)(Jy),d=(0,o.useRef)({disabled:n}),f=(0,o.useRef)(!1),p=(0,o.useRef)(null),m=(0,o.useRef)(null),{disabled:h,updateMeasurementsFor:g,timeout:_}={...db,...i},v=O_(g??r),y=Dy({callback:(0,o.useCallback)(()=>{if(!f.current){f.current=!0;return}m.current!=null&&clearTimeout(m.current),m.current=setTimeout(()=>{u(Array.isArray(v.current)?v.current:[v.current]),m.current=null},_)},[_]),disabled:h||!s}),[b,x]=A_((0,o.useCallback)((e,t)=>{y&&(t&&(y.unobserve(t),f.current=!1),e&&y.observe(e))},[y])),S=O_(t);return(0,o.useEffect)(()=>{y&&b.current&&(y.disconnect(),f.current=!1,y.observe(b.current))},[b,y]),(0,o.useEffect)(()=>(c({type:ev.RegisterDroppable,element:{id:r,key:a,disabled:n,node:b,rect:p,data:S}}),()=>c({type:ev.UnregisterDroppable,key:a,id:r})),[r]),(0,o.useEffect)(()=>{n!==d.current.disabled&&(c({type:ev.SetDroppableDisabled,id:r,key:a,disabled:n}),d.current.disabled=n)},[r,a,n,c]),{active:s,rect:p,isOver:l?.id===r,node:b,over:l,setNodeRef:x}}function pb(e){let{animation:t,children:n}=e,[r,i]=(0,o.useState)(null),[a,s]=(0,o.useState)(null),c=j_(n);return!n&&!r&&c&&i(c),T_(()=>{if(!a)return;let e=r?.key,n=r?.props.id;if(e==null||n==null){i(null);return}Promise.resolve(t(n,a)).then(()=>{i(null)})},[t,r,a]),o.createElement(o.Fragment,null,n,r?(0,o.cloneElement)(r,{ref:s}):null)}var mb={x:0,y:0,scaleX:1,scaleY:1};function hb(e){let{children:t}=e;return o.createElement(Jy.Provider,{value:qy},o.createElement(nb.Provider,{value:mb},t))}var gb={position:`fixed`,touchAction:`none`},_b=e=>R_(e)?`transform 250ms ease`:void 0,vb=(0,o.forwardRef)((e,t)=>{let{as:n,activatorEvent:r,adjustScale:i,children:a,className:s,rect:c,style:l,transform:u,transition:d=_b}=e;if(!c)return null;let f=i?u:{...u,scaleX:1,scaleY:1},p={...gb,width:c.width,height:c.height,top:c.top,left:c.left,transform:V_.Transform.toString(f),transformOrigin:i&&r?ov(r,c):void 0,transition:typeof d==`function`?d(r):d,...l};return o.createElement(n,{className:s,style:p,ref:t},a)}),yb={duration:250,easing:`ease`,keyframes:e=>{let{transform:{initial:t,final:n}}=e;return[{transform:V_.Transform.toString(t)},{transform:V_.Transform.toString(n)}]},sideEffects:(e=>t=>{let{active:n,dragOverlay:r}=t,i={},{styles:a,className:o}=e;if(a!=null&&a.active)for(let[e,t]of Object.entries(a.active))t!==void 0&&(i[e]=n.node.style.getPropertyValue(e),n.node.style.setProperty(e,t));if(a!=null&&a.dragOverlay)for(let[e,t]of Object.entries(a.dragOverlay))t!==void 0&&r.node.style.setProperty(e,t);return o!=null&&o.active&&n.node.classList.add(o.active),o!=null&&o.dragOverlay&&r.node.classList.add(o.dragOverlay),function(){for(let[e,t]of Object.entries(i))n.node.style.setProperty(e,t);o!=null&&o.active&&n.node.classList.remove(o.active)}})({styles:{active:{opacity:`0`}}})};function bb(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:i}=e;return E_((e,a)=>{if(t===null)return;let o=n.get(e);if(!o)return;let s=o.node.current;if(!s)return;let c=By(a);if(!c)return;let{transform:l}=b_(a).getComputedStyle(a),u=Sv(l);if(!u)return;let d=typeof t==`function`?t:xb(t);return Gv(s,i.draggable.measure),d({active:{id:e,data:o.data,node:s,rect:i.draggable.measure(s)},draggableNodes:n,dragOverlay:{node:a,rect:i.dragOverlay.measure(c)},droppableContainers:r,measuringConfiguration:i,transform:u})})}function xb(e){let{duration:t,easing:n,sideEffects:r,keyframes:i}={...yb,...e};return e=>{let{active:a,dragOverlay:o,transform:s,...c}=e;if(!t)return;let l={x:o.rect.left-a.rect.left,y:o.rect.top-a.rect.top},u={scaleX:s.scaleX===1?1:a.rect.width*s.scaleX/o.rect.width,scaleY:s.scaleY===1?1:a.rect.height*s.scaleY/o.rect.height},d={x:s.x-l.x,y:s.y-l.y,...u},f=i({...c,active:a,dragOverlay:o,transform:{initial:s,final:d}}),[p]=f,m=f[f.length-1];if(JSON.stringify(p)===JSON.stringify(m))return;let h=r?.({active:a,dragOverlay:o,...c}),g=o.node.animate(f,{duration:t,easing:n,fill:`forwards`});return new Promise(e=>{g.onfinish=()=>{h?.(),e()}})}}var Sb=0;function Cb(e){return(0,o.useMemo)(()=>{if(e!=null)return Sb++,Sb},[e])}var wb=o.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:i,transition:a,modifiers:s,wrapperElement:c=`div`,className:l,zIndex:u=999}=e,{activatorEvent:d,active:f,activeNodeRect:p,containerNodeRect:m,draggableNodes:h,droppableContainers:g,dragOverlay:_,over:v,measuringConfiguration:y,scrollableAncestors:b,scrollableAncestorRects:x,windowRect:S}=lb(),C=(0,o.useContext)(nb),w=Cb(f?.id),T=$y(s,{activatorEvent:d,active:f,activeNodeRect:p,containerNodeRect:m,draggingNodeRect:_.rect,over:v,overlayNodeRect:_.rect,scrollableAncestors:b,scrollableAncestorRects:x,transform:C,windowRect:S}),E=wy(p),D=bb({config:r,draggableNodes:h,droppableContainers:g,measuringConfiguration:y}),O=E?_.setRef:void 0;return o.createElement(hb,null,o.createElement(pb,{animation:D},f&&w?o.createElement(vb,{key:w,id:f.id,ref:O,as:c,activatorEvent:d,adjustScale:t,className:l,transition:a,rect:E,style:{zIndex:u,...i},transform:T},n):null))});function Tb(e,t,n){let r=e.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function Eb(e,t){return e.reduce((e,n,r)=>{let i=t.get(n);return i&&(e[r]=i),e},Array(e.length))}function Db(e){return e!==null&&e>=0}function Ob(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function kb(e){return typeof e==`boolean`?{draggable:e,droppable:e}:e}var Ab=e=>{let{rects:t,activeIndex:n,overIndex:r,index:i}=e,a=Tb(t,r,n),o=t[i],s=a[i];return!s||!o?null:{x:s.left-o.left,y:s.top-o.top,scaleX:s.width/o.width,scaleY:s.height/o.height}},jb={scaleX:1,scaleY:1},Mb=e=>{let{activeIndex:t,activeNodeRect:n,index:r,rects:i,overIndex:a}=e,o=i[t]??n;if(!o)return null;if(r===t){let e=i[a];return e?{x:0,y:t<a?e.top+e.height-(o.top+o.height):e.top-o.top,...jb}:null}let s=Nb(i,r,t);return r>t&&r<=a?{x:0,y:-o.height-s,...jb}:r<t&&r>=a?{x:0,y:o.height+s,...jb}:{x:0,y:0,...jb}};function Nb(e,t,n){let r=e[t],i=e[t-1],a=e[t+1];return r?n<t?i?r.top-(i.top+i.height):a?a.top-(r.top+r.height):0:a?a.top-(r.top+r.height):i?r.top-(i.top+i.height):0:0}var Pb=`Sortable`,Fb=o.createContext({activeIndex:-1,containerId:Pb,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:Ab,disabled:{draggable:!1,droppable:!1}});function Ib(e){let{children:t,id:n,items:r,strategy:i=Ab,disabled:a=!1}=e,{active:s,dragOverlay:c,droppableRects:l,over:u,measureDroppableContainers:d}=lb(),f=N_(Pb,n),p=c.rect!==null,m=(0,o.useMemo)(()=>r.map(e=>typeof e==`object`&&`id`in e?e.id:e),[r]),h=s!=null,g=s?m.indexOf(s.id):-1,_=u?m.indexOf(u.id):-1,v=(0,o.useRef)(m),y=!Ob(m,v.current),b=_!==-1&&g===-1||y,x=kb(a);T_(()=>{y&&h&&d(m)},[y,m,h,d]),(0,o.useEffect)(()=>{v.current=m},[m]);let S=(0,o.useMemo)(()=>({activeIndex:g,containerId:f,disabled:x,disableTransforms:b,items:m,overIndex:_,useDragOverlay:p,sortedRects:Eb(m,l),strategy:i}),[g,f,x.draggable,x.droppable,b,m,_,l,p,i]);return o.createElement(Fb.Provider,{value:S},t)}var Lb=e=>{let{id:t,items:n,activeIndex:r,overIndex:i}=e;return Tb(n,r,i).indexOf(t)},Rb=e=>{let{containerId:t,isSorting:n,wasDragging:r,index:i,items:a,newIndex:o,previousItems:s,previousContainerId:c,transition:l}=e;return!l||!r||s!==a&&i===o?!1:n?!0:o!==i&&t===c},zb={duration:200,easing:`ease`},Bb=`transform`,Vb=V_.Transition.toString({property:Bb,duration:0,easing:`linear`}),Hb={roleDescription:`sortable`};function Ub(e){let{disabled:t,index:n,node:r,rect:i}=e,[a,s]=(0,o.useState)(null),c=(0,o.useRef)(n);return T_(()=>{if(!t&&n!==c.current&&r.current){let e=i.current;if(e){let t=Tv(r.current,{ignoreTransform:!0}),n={x:e.left-t.left,y:e.top-t.top,scaleX:e.width/t.width,scaleY:e.height/t.height};(n.x||n.y)&&s(n)}}n!==c.current&&(c.current=n)},[t,n,r,i]),(0,o.useEffect)(()=>{a&&s(null)},[a]),a}function Wb(e){let{animateLayoutChanges:t=Rb,attributes:n,disabled:r,data:i,getNewIndex:a=Lb,id:s,strategy:c,resizeObserverConfig:l,transition:u=zb}=e,{items:d,containerId:f,activeIndex:p,disabled:m,disableTransforms:h,sortedRects:g,overIndex:_,useDragOverlay:v,strategy:y}=(0,o.useContext)(Fb),b=Gb(r,m),x=d.indexOf(s),S=(0,o.useMemo)(()=>({sortable:{containerId:f,index:x,items:d},...i}),[f,i,x,d]),C=(0,o.useMemo)(()=>d.slice(d.indexOf(s)),[d,s]),{rect:w,node:T,isOver:E,setNodeRef:D}=fb({id:s,data:S,disabled:b.droppable,resizeObserverConfig:{updateMeasurementsFor:C,...l}}),{active:O,activatorEvent:k,activeNodeRect:A,attributes:j,setNodeRef:M,listeners:N,isDragging:ee,over:P,setActivatorNodeRef:te,transform:F}=cb({id:s,data:S,attributes:{...Hb,...n},disabled:b.draggable}),ne=g_(D,M),re=!!O,ie=re&&!h&&Db(p)&&Db(_),I=!v&&ee,ae=ie?(I&&ie?F:null)??(c??y)({rects:g,activeNodeRect:A,activeIndex:p,overIndex:_,index:x}):null,L=Db(p)&&Db(_)?a({id:s,items:d,activeIndex:p,overIndex:_}):x,oe=O?.id,R=(0,o.useRef)({activeId:oe,items:d,newIndex:L,containerId:f}),se=d!==R.current.items,ce=t({active:O,containerId:f,isDragging:ee,isSorting:re,id:s,index:x,items:d,newIndex:R.current.newIndex,previousItems:R.current.items,previousContainerId:R.current.containerId,transition:u,wasDragging:R.current.activeId!=null}),le=Ub({disabled:!ce,index:x,node:T,rect:w});return(0,o.useEffect)(()=>{re&&R.current.newIndex!==L&&(R.current.newIndex=L),f!==R.current.containerId&&(R.current.containerId=f),d!==R.current.items&&(R.current.items=d)},[re,L,f,d]),(0,o.useEffect)(()=>{if(oe===R.current.activeId)return;if(oe!=null&&R.current.activeId==null){R.current.activeId=oe;return}let e=setTimeout(()=>{R.current.activeId=oe},50);return()=>clearTimeout(e)},[oe]),{active:O,activeIndex:p,attributes:j,data:S,rect:w,index:x,newIndex:L,items:d,isOver:E,isSorting:re,isDragging:ee,listeners:N,node:T,overIndex:_,over:P,setNodeRef:ne,setActivatorNodeRef:te,setDroppableNodeRef:D,setDraggableNodeRef:M,transform:le??ae,transition:ue()};function ue(){if(le||se&&R.current.newIndex===x)return Vb;if(!(I&&!R_(k)||!u)&&(re||ce))return V_.Transition.toString({...u,property:Bb})}}function Gb(e,t){return typeof e==`boolean`?{draggable:e,droppable:!1}:{draggable:e?.draggable??t.draggable,droppable:e?.droppable??t.droppable}}function Kb(e){if(!e)return!1;let t=e.data.current;return!!(t&&`sortable`in t&&typeof t.sortable==`object`&&`containerId`in t.sortable&&`items`in t.sortable&&`index`in t.sortable)}var qb=[J.Down,J.Right,J.Up,J.Left],Jb=(e,t)=>{let{context:{active:n,collisionRect:r,droppableRects:i,droppableContainers:a,over:o,scrollableAncestors:s}}=t;if(qb.includes(e.code)){if(e.preventDefault(),!n||!r)return;let t=[];a.getEnabled().forEach(n=>{if(!n||n!=null&&n.disabled)return;let a=i.get(n.id);if(a)switch(e.code){case J.Down:r.top<a.top&&t.push(n);break;case J.Up:r.top>a.top&&t.push(n);break;case J.Left:r.left>a.left&&t.push(n);break;case J.Right:r.left<a.left&&t.push(n)}});let c=pv({active:n,collisionRect:r,droppableRects:i,droppableContainers:t,pointerCoordinates:null}),l=uv(c,`id`);if(l===o?.id&&c.length>1&&(l=c[1].id),l!=null){let e=a.get(n.id),t=a.get(l),o=t?i.get(t.id):null,c=t?.node.current;if(c&&o&&e&&t){let n=Av(c).some((e,t)=>s[t]!==e),i=Yb(e,t),a=Xb(e,t),l=n||!i?{x:0,y:0}:{x:a?r.width-o.width:0,y:a?r.height-o.height:0},u={x:o.left,y:o.top};return l.x&&l.y?u:I_(u,l)}}}};function Yb(e,t){return!Kb(e)||!Kb(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function Xb(e,t){return!Kb(e)||!Kb(t)||!Yb(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}var Zb=Date.UTC(2026,9,6,9,41),Qb=(e,t)=>{let n=(e^Math.imul(t+2654435769,2246822507))>>>0;return n=Math.imul(n^n>>>16,2246822507),n=Math.imul(n^n>>>13,3266489909),(n^n>>>16)>>>0},$b=(e,t)=>{let n=Qb(e,t);return()=>{n=n+1831565813>>>0;let e=n;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}},ex=[{id:`u1`,name:`Sanne M.`,initials:`SM`,hue:250,role:`Admin`},{id:`u2`,name:`Jonas K.`,initials:`JK`,hue:160,role:`Sales`},{id:`u3`,name:`Lieke D.`,initials:`LD`,hue:20,role:`Finance`},{id:`u4`,name:`Tobias R.`,initials:`TR`,hue:310,role:`Warehouse`},{id:`u5`,name:`Imke V.`,initials:`IV`,hue:200,role:`Sales`},{id:`u6`,name:`Marek W.`,initials:`MW`,hue:80,role:`Warehouse`},{id:`u7`,name:`Hanna B.`,initials:`HB`,hue:350,role:`Finance`},{id:`u8`,name:`Daan P.`,initials:`DP`,hue:120,role:`Sales`}],tx=e=>ex.find(t=>t.id===e)??ex[0];ex.filter(e=>e.role===`Sales`);var nx=[[`M8 hex bolt A2, 100 pcs`,`FST`,1890],[`M10 hex nut A2, 100 pcs`,`FST`,1240],[`Stainless washer 8 mm, 250 pcs`,`FST`,990],[`Cable tie 300 mm, 100 pcs`,`ELC`,650],[`Cable gland M20, 25 pcs`,`ELC`,2340],[`Junction box IP65`,`ELC`,1480],[`Hydraulic hose 1/2 in, 5 m`,`HYD`,8650],[`Hydraulic coupling 3/8 in`,`HYD`,1895],[`Pallet wrap 500 mm`,`PKG`,740],[`Corrugated box 400 x 300`,`PKG`,215],[`Bubble wrap roll 50 m`,`PKG`,1990],[`Safety gloves, size L`,`PPE`,395],[`Safety glasses, clear`,`PPE`,450],[`Ear defenders SNR 31`,`PPE`,1295],[`Ball bearing 6204-2RS`,`BRG`,685],[`Taper roller bearing 30205`,`BRG`,1420],[`Timing belt HTD 5M, 600 mm`,`BLT`,2780],[`V-belt SPA 1250`,`BLT`,1360],[`Grease cartridge, 400 g`,`LUB`,920],[`Machine oil ISO 68, 5 l`,`LUB`,3950],[`Angle grinder disc 125 mm, 10 pcs`,`ABR`,1880],[`Drill bit set HSS, 19 pcs`,`TLS`,3490],[`Torque wrench 20-100 Nm`,`TLS`,14900],[`Pneumatic cylinder 40 x 100`,`PNE`,6120],[`Air hose PU 8 mm, 20 m`,`PNE`,2475],[`LED panel 600 x 600, 40 W`,`LGT`,3290],[`Pallet label roll 100 x 150`,`LBL`,1175],[`Thermal printer ribbon`,`LBL`,890],[`Euro pallet EPAL, used`,`PLT`,1150],[`Roll container, galvanised`,`PLT`,9800]];nx.length;var rx=e=>{let[t,n,r]=nx[e%nx.length],i=e%nx.length;return{id:`P-${200+i}`,sku:`${n}-${String(1e3+i*7).padStart(4,`0`)}`,name:t,category:n,priceCents:r}},ix=e=>e.quantity*e.unitPriceCents,ax=(e,t=.21)=>{let n=e.reduce((e,t)=>e+ix(t),0),r=Math.round(n*t);return{subtotalCents:n,vatCents:r,totalCents:n+r}},ox=864e5,sx=e=>Array.from({length:e},(t,n)=>{let r=Zb-(e-1-n)*ox,i=new Date(r).getUTCDay();return{at:r,count:Math.round((i===0||i===6?120:410)*(.8+$b(71,n)()*.45)*(1+n/e/3))}}),cx=e=>{if(e===`day`)return sx(30);let t=sx(84);return Array.from({length:12},(e,n)=>{let r=t.slice(n*7,n*7+7);return{at:r[0].at,count:r.reduce((e,t)=>e+t.count,0)}})},lx=`grid grid-cols-[28px_minmax(0,1fr)_88px_112px_112px_32px] items-center gap-2 pointer-coarse:grid-cols-[44px_minmax(0,1fr)_88px_112px_112px_44px]`,ux=({items:e,label:t})=>{let[n,r]=(0,o.useState)(!1),i=(0,o.useRef)(null);return(0,o.useEffect)(()=>{if(!n)return;let e=e=>{(e instanceof KeyboardEvent?e.key===`Escape`:!i.current?.contains(e.target))&&r(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,e)}},[n]),(0,V.jsxs)(`div`,{ref:i,className:`relative flex justify-center`,children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":t,"aria-haspopup":`menu`,"aria-expanded":n,onClick:()=>r(!n),className:`inline-flex size-7 items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground pointer-coarse:size-11`,children:(0,V.jsx)(Ke,{className:`size-4`})}),n&&(0,V.jsx)(`ul`,{role:`menu`,className:`absolute right-0 top-full z-30 mt-1 min-w-36 rounded-md border bg-background py-1 shadow-pop`,children:e.map(e=>(0,V.jsx)(`li`,{role:`none`,children:(0,V.jsx)(`button`,{type:`button`,role:`menuitem`,disabled:e.disabled,className:B(`block min-h-9 w-full whitespace-nowrap px-3 py-1.5 text-left hover:bg-muted disabled:text-faint-foreground disabled:hover:bg-transparent`,e.destructive&&`text-danger-text`),onClick:()=>{r(!1),e.onSelect()},children:e.label})},e.label))})]})},dx=({value:e,onCommit:t,format:n,parse:r,label:i,width:a=`w-full`})=>{let[s,c]=(0,o.useState)(null);return(0,V.jsx)(`input`,{"aria-label":i,inputMode:`decimal`,value:s??n(e),onFocus:e=>e.currentTarget.select(),onChange:e=>c(e.target.value),onBlur:()=>{if(s===null)return;let e=r(s);c(null),Number.isFinite(e)&&e>=0&&t(e)},onKeyDown:e=>e.key===`Enter`&&e.currentTarget.blur(),className:B(`h-7 rounded-md border border-transparent bg-transparent px-2 text-right tabular-nums text-foreground outline-none hover:border-border-strong focus:border-primary focus:bg-background focus:ring-2 focus:ring-primary/20`,a)})},fx=e=>Math.round(Number(e.replace(`,`,`.`).replace(/[^0-9.]/g,``))*100),px=({line:e,position:t,count:n,reorderable:r,editable:i,onChange:a,onRemove:o,onMove:s})=>{let{attributes:c,listeners:l,setNodeRef:u,setActivatorNodeRef:d,transform:f,transition:p,isDragging:m}=Wb({id:e.id,disabled:!r}),h=[...r?[{label:`Move up`,disabled:t===0,onSelect:()=>s(t-1)},{label:`Move down`,disabled:t===n-1,onSelect:()=>s(t+1)}]:[],...i?[{label:`Remove line`,destructive:!0,onSelect:o}]:[]];return(0,V.jsxs)(`div`,{ref:u,"data-line-id":e.id,style:{transform:f?`translate3d(0, ${f.y}px, 0)`:void 0,transition:p},className:B(`group relative border-b border-border bg-background px-2 py-1 last:border-b-0 hover:bg-surface`,lx,m&&`z-10 bg-surface opacity-80 shadow-pop`),children:[r?(0,V.jsx)(`button`,{ref:d,type:`button`,"aria-label":`Drag to reorder ${e.description}`,...c,...l,style:{touchAction:`none`},className:`flex size-7 cursor-grab items-center justify-center rounded text-faint-foreground opacity-60 hover:bg-muted hover:opacity-100 focus-visible:opacity-100 active:cursor-grabbing pointer-coarse:size-11`,children:(0,V.jsx)(ot,{className:`size-4`})}):(0,V.jsx)(`span`,{}),(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsx)(`p`,{className:`truncate text-foreground`,children:e.description}),(0,V.jsx)(`p`,{className:`font-mono text-[11px] text-faint-foreground`,children:e.productId})]}),i?(0,V.jsx)(dx,{label:`Quantity`,value:e.quantity,format:String,parse:e=>Math.round(Number(e)),onCommit:e=>a({quantity:e})}):(0,V.jsx)(`span`,{className:`px-2 text-right tabular-nums`,children:e.quantity}),i?(0,V.jsx)(dx,{label:`Unit price`,value:e.unitPriceCents,format:e=>(e/100).toFixed(2),parse:fx,onCommit:e=>a({unitPriceCents:e})}):(0,V.jsx)(`span`,{className:`px-2 text-right tabular-nums`,children:(e.unitPriceCents/100).toFixed(2)}),(0,V.jsx)(`span`,{className:`px-2 text-right font-medium tabular-nums text-foreground`,children:rf(ix(e))}),h.length>0?(0,V.jsx)(ux,{label:`Actions for ${e.description}`,items:h}):(0,V.jsx)(`span`,{})]})},mx=(e,t,n)=>{if(t===n||t<0||t>=e.length)return[...e];let r=[...e],[i]=r.splice(t,1);return r.splice(Math.min(Math.max(n,0),r.length),0,i),r},hx=({lines:e,vatRate:t})=>{let n=ax(e,t);return(0,V.jsxs)(`dl`,{className:`ml-auto grid w-64 grid-cols-[1fr_auto] gap-x-6 gap-y-1 px-2 pt-3 tabular-nums`,children:[(0,V.jsx)(`dt`,{className:`text-muted-foreground`,children:`Subtotal`}),(0,V.jsx)(`dd`,{className:`text-right text-foreground`,children:rf(n.subtotalCents)}),(0,V.jsxs)(`dt`,{className:`text-muted-foreground`,children:[`VAT `,Math.round(t*100),`%`]}),(0,V.jsx)(`dd`,{className:`text-right text-foreground`,children:rf(n.vatCents)}),(0,V.jsx)(`dt`,{className:`mt-1 border-t border-border pt-2 font-semibold text-foreground`,children:`Total`}),(0,V.jsx)(`dd`,{className:`mt-1 border-t border-border pt-2 text-right text-[16px] font-semibold text-foreground`,children:rf(n.totalCents)})]})},gx=`px-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,_x=`To pick up a line, press space or enter on its drag handle. Use the up and down arrow keys to move it, space or enter to drop it, and escape to cancel. The row menu also has Move up and Move down.`,vx=e=>{let t=t=>e.find(e=>e.id===t)?.description??`line`,n=t=>e.findIndex(e=>e.id===t)+1;return{onDragStart:({active:r})=>`Picked up ${t(r.id)}, line ${n(r.id)} of ${e.length}.`,onDragOver:({active:r,over:i})=>i?`${t(r.id)} is over line ${n(i.id)} of ${e.length}.`:void 0,onDragEnd:({active:r,over:i})=>i?`${t(r.id)} was dropped at line ${n(i.id)} of ${e.length}.`:`${t(r.id)} was dropped where it started.`,onDragCancel:({active:e})=>`Moving ${t(e.id)} was cancelled. It is back at line ${n(e.id)}.`}},yx=({lines:e,onChange:t,onReorder:n,vatRate:r=.21,readOnly:i,reorderable:a=!i})=>{let o=rv(nv(uy,{activationConstraint:{distance:4}}),nv(fy,{activationConstraint:{delay:250,tolerance:5}}),nv(ny,{coordinateGetter:Jb})),s=(r,i)=>{let a=e[r];!a||i<0||i>=e.length||r===i||(n??(e=>t(e)))(mx(e,r,i),{id:a.id,from:r,to:i})};return(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:[(0,V.jsxs)(`div`,{className:`${lx} border-b border-border bg-surface px-2 py-2`,children:[(0,V.jsx)(`span`,{}),(0,V.jsx)(`span`,{className:gx,children:`Item`}),(0,V.jsx)(`span`,{className:`${gx} text-right`,children:`Qty`}),(0,V.jsx)(`span`,{className:`${gx} text-right`,children:`Unit price`}),(0,V.jsx)(`span`,{className:`${gx} text-right`,children:`Line total`}),(0,V.jsx)(`span`,{})]}),(0,V.jsx)(ib,{sensors:o,collisionDetection:fv,onDragEnd:({active:t,over:n})=>{n&&t.id!==n.id&&s(e.findIndex(e=>e.id===t.id),e.findIndex(e=>e.id===n.id))},accessibility:{announcements:vx(e),screenReaderInstructions:{draggable:_x}},children:(0,V.jsx)(Ib,{items:e.map(e=>e.id),strategy:Mb,children:e.map((n,r)=>(0,V.jsx)(px,{line:n,position:r,count:e.length,reorderable:a,editable:!i,onChange:r=>t(e.map(e=>e.id===n.id?{...e,...r}:e)),onRemove:()=>t(e.filter(e=>e.id!==n.id)),onMove:e=>s(r,e)},n.id))})}),!i&&(0,V.jsx)(`div`,{className:`border-t border-border bg-surface px-2 py-1.5`,children:(0,V.jsxs)(U,{variant:`ghost`,size:`sm`,onClick:()=>{let n=rx(e.length*3+1);t([...e,{id:`new-${e.length}-${n.id}`,productId:n.id,description:n.name,quantity:1,unitPriceCents:n.priceCents}])},children:[(0,V.jsx)(nn,{className:`size-3.5`}),`Add line`]})})]}),(0,V.jsx)(hx,{lines:e,vatRate:r})]})},bx=({name:e,label:t,required:n,help:r,example:i,error:a,conflict:s,wide:c,children:l})=>{let u=(0,o.useId)(),d=[r&&`${u}-help`,i&&`${u}-example`,a&&`${u}-error`].filter(Boolean).join(` `)||void 0;return(0,V.jsxs)(`div`,{className:c?`sm:col-span-2`:void 0,children:[(0,V.jsxs)(`div`,{className:`mb-1.5 flex items-center gap-2`,children:[(0,V.jsxs)(`label`,{htmlFor:u,className:`font-medium text-foreground`,children:[t,n&&(0,V.jsx)(`span`,{className:`ml-0.5 text-danger-text`,"aria-hidden":`true`,children:`*`})]}),s&&(0,V.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-warning-text`,title:`${s.user.name} saved a different value`,children:[(0,V.jsx)(Bn,{className:`size-3.5`}),(0,V.jsx)(Hu,{initials:s.user.initials,hue:s.user.hue,size:`xs`})]})]}),(0,V.jsx)(Cd,{value:{id:u,name:e,describedBy:d,invalid:!!a,required:!!n},children:l}),r&&(0,V.jsx)(`p`,{id:`${u}-help`,className:`mt-1.5 text-xs text-muted-foreground`,children:r}),i&&(0,V.jsxs)(`p`,{id:`${u}-example`,className:`mt-0.5 text-xs text-faint-foreground`,children:[`Example: `,i]}),a&&(0,V.jsx)(`p`,{id:`${u}-error`,className:`mt-1.5 text-xs font-medium text-danger-text`,children:a}),s&&(0,V.jsxs)(`div`,{className:`mt-2 flex items-center justify-between gap-3 rounded-md border border-warning/30 bg-warning-soft px-3 py-2 text-xs text-warning-text`,children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:s.user.name}),` saved this `,s.ago,`: `,(0,V.jsx)(`strong`,{children:s.theirValue})]}),(0,V.jsxs)(`span`,{className:`flex gap-1.5`,children:[(0,V.jsx)(U,{size:`sm`,onClick:s.onKeepMine,children:`Keep mine`}),(0,V.jsx)(U,{size:`sm`,onClick:s.onUseTheirs,children:`Use theirs`})]})]})]})},xx=({title:e,help:t,actions:n,children:r})=>{let i=(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold text-foreground`,children:e});return(0,V.jsxs)(`section`,{className:`py-8 first:pt-8`,children:[n?(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-x-4 gap-y-2`,children:[i,n]}):i,t&&(0,V.jsx)(`p`,{className:`mt-1 max-w-xl leading-6 text-muted-foreground`,children:t}),(0,V.jsx)(`div`,{className:`mt-5`,children:r})]})},Sx=`flex min-h-11 items-center gap-2 rounded-md border border-border-strong px-3 text-left hover:bg-surface disabled:cursor-default disabled:opacity-60 md:min-h-0 md:w-full md:items-start md:gap-3 md:rounded-none md:border-0 md:px-4 md:py-3`,Cx=({actions:e})=>(0,V.jsxs)(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:[(0,V.jsx)(`h3`,{className:`hidden border-b border-border px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground md:block`,children:`Actions`}),(0,V.jsx)(`ul`,{className:`flex flex-wrap gap-2 p-2 md:block md:divide-y md:divide-border md:p-0`,children:e.map(({name:e,description:t,icon:n,onRun:r,blocked:i,running:a,tone:o,render:s})=>{let c=(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(n,{className:B(`size-4 shrink-0 md:mt-0.5`,o===`danger`?`text-danger-text`:`text-muted-foreground`),"aria-hidden":!0}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`span`,{className:B(`block font-medium`,o===`danger`?`text-danger-text`:`text-foreground`),children:e}),t&&(0,V.jsx)(`span`,{className:`mt-0.5 hidden text-xs leading-snug text-muted-foreground md:block`,children:t})]})]});return(0,V.jsx)(`li`,{children:s?s({className:Sx,children:c}):(0,V.jsx)(`button`,{type:`button`,onClick:r,disabled:!!i||a,title:i,className:Sx,children:c})},e)})})]}),wx=({rows:e})=>(0,V.jsx)(`dl`,{className:`grid grid-cols-[auto_1fr] gap-x-4 gap-y-2`,children:e.map(e=>(0,V.jsxs)(`div`,{className:`contents`,children:[(0,V.jsx)(`dt`,{className:`text-muted-foreground`,children:e.label}),(0,V.jsx)(`dd`,{className:`text-right tabular-nums text-foreground`,children:e.value})]},e.label))}),Tx=({records:e,onNavigate:t})=>(0,V.jsx)(`ul`,{className:`-mx-2`,children:e.map(e=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(`a`,{href:e.href??`#`,onClick:n=>{n.preventDefault(),e.href&&t?.(e.href)},className:`group flex items-center justify-between gap-3 rounded-md px-2 py-2 hover:bg-muted`,children:[(0,V.jsxs)(`span`,{className:`min-w-0`,children:[(0,V.jsx)(`span`,{className:`block text-[11px] uppercase tracking-wide text-faint-foreground`,children:e.kind}),(0,V.jsx)(`span`,{className:`block truncate font-medium text-primary-text`,children:e.label}),e.meta&&(0,V.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:e.meta})]}),(0,V.jsx)(xe,{className:`size-4 shrink-0 text-faint-foreground group-hover:text-foreground`})]})},e.label))}),Ex=({title:e,children:t})=>(0,V.jsxs)(`div`,{className:`rounded-lg border border-border bg-background p-4`,children:[(0,V.jsx)(`h3`,{className:`mb-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:e}),t]}),Dx=({title:e,rows:t})=>t.length===0?null:(0,V.jsx)(Ex,{title:e,children:(0,V.jsx)(wx,{rows:t})}),Ox=({collection:e,title:t,titleHidden:n,status:r,lastEditedBy:i,presence:a=[],actions:o})=>n&&!e&&!r&&!i&&a.length===0&&!o?(0,V.jsx)(`h1`,{className:`sr-only`,children:t}):(0,V.jsxs)(`header`,{className:`flex flex-col gap-4 border-b border-border pb-6 md:flex-row md:items-end md:justify-between md:gap-6`,children:[(0,V.jsxs)(`div`,{children:[e&&(0,V.jsx)(`p`,{className:`mb-1 text-xs text-muted-foreground`,children:e}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,V.jsx)(`h1`,{className:n?`sr-only`:`text-xl font-semibold tracking-tight text-foreground md:text-2xl`,children:t}),r&&(0,V.jsx)(Zu,{tone:r.tone,children:r.label})]}),i&&(0,V.jsx)(`p`,{className:`mt-1.5 text-xs text-muted-foreground`,children:i.name?(0,V.jsxs)(V.Fragment,{children:[`Last edited by `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:i.name}),` `,i.ago]}):(0,V.jsxs)(V.Fragment,{children:[`Last updated `,i.ago]})})]}),(0,V.jsxs)(`div`,{className:`flex items-center gap-4`,children:[a.length>0&&(0,V.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,V.jsx)(Uu,{people:a,size:`md`}),a.length,` viewing`]}),o]})]}),kx=({rows:e})=>(0,V.jsx)(`dl`,{className:`border-t border-border`,children:e.map(e=>(0,V.jsxs)(`div`,{className:B(`grid gap-x-4 border-b border-border py-2.5`,e.wide?`grid-cols-1 gap-y-1.5`:`grid-cols-[minmax(0,2fr)_minmax(0,3fr)]`),children:[(0,V.jsxs)(`dt`,{className:`min-w-0 text-muted-foreground`,children:[e.label,e.help&&(0,V.jsx)(`span`,{className:`mt-0.5 block text-xs text-faint-foreground`,children:e.help})]}),(0,V.jsx)(`dd`,{className:`min-w-0 break-words text-foreground`,children:e.value})]},e.label))}),Ax=({facts:e})=>(0,V.jsx)(`dl`,{className:`grid grid-cols-2 gap-x-4 gap-y-5 sm:flex sm:flex-wrap sm:gap-x-10`,children:e.map(({label:e,value:t,icon:n})=>(0,V.jsxs)(`div`,{title:e,className:`flex min-w-0 flex-col gap-1.5`,children:[(0,V.jsx)(`dt`,{className:`text-muted-foreground`,children:n?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(n,{className:`size-5`,"aria-hidden":!0}),(0,V.jsx)(`span`,{className:`sr-only`,children:e})]}):e}),(0,V.jsx)(`dd`,{className:`min-w-0 break-words text-[16px] font-semibold text-foreground`,children:t})]},e))}),jx=e=>typeof e==`object`&&!!e&&typeof e.uri==`string`,Mx=e=>typeof e==`object`&&!!e&&typeof e.uploaded?.value==`string`,Nx=e=>{if(Mx(e))return{...e.uploaded.file,...e.preview&&{url:e.preview},corrected:e.uploaded.corrected};if(jx(e))return`missing`in e?{name:`File missing`,type:``,missing:!0}:e},Px=[`bytes`,`kB`,`MB`,`GB`],Fx=e=>{let t=e,n=0;for(;t>=1e3&&n<Px.length-1;)t/=1e3,n+=1;return n===0?`${e} ${e===1?`byte`:`bytes`}`:`${t<10?t.toFixed(1):Math.round(t)} ${Px[n]}`},Ix=e=>e.startsWith(`image/`)&&e!==`image/svg+xml`,Lx=2,Rx=1e5,zx=(e,t)=>(e.width!==void 0||e.height!==void 0)&&(e.width??Rx)>=t.width*Lx&&(e.height??Rx)>=t.height*Lx,Bx=e=>(e.width??Rx)*(e.height??Rx),Vx=(e,t)=>{let n=Nx(e);if(!(!n||`missing`in n||!n.url||!Ix(n.type)))return{url:(`variants`in n&&n.variants?Object.values(n.variants):[]).filter(e=>zx(e,t)).sort((e,t)=>Bx(e)-Bx(t))[0]?.url??n.url,...`placeholder`in n&&n.placeholder!==void 0&&{placeholder:n.placeholder}}},Hx=e=>{let t=e.file?.accept??[];return t.length===0||t.includes(`*/*`)?void 0:t.join(`,`)},Ux=e=>Mx(e)?e.uploaded.value:jx(e)?e.uri:null,Wx=(e,t)=>{if(Mx(e))return!0;let n=e=>jx(e)?e.uri:null;return n(e)!==n(t)},Gx=e=>e==null?``:typeof e==`object`?JSON.stringify(e):String(e),Kx=new Set([`text`,`integer`,`bigint`,`decimal`,`date`,`currency`,`country`]),qx=e=>!e.readOnly&&e.type!==`json`&&e.type!==`uuid`&&e.type!==`timestamp`&&e.type!==`relation`,Jx=e=>!e.readOnly&&!e.nullable&&e.type!==`boolean`,Yx=(e,t)=>{if(e.type===`boolean`)return!!t;if(e.type===`file`)return Ux(t);let n=String(t).trim();if(n===``)return e.nullable?null:``;if(e.type===`integer`)return Number(n);if(e.type===`relation`)return typeof t==`number`?t:n;if(Kx.has(e.type)||e.type===`enum`)return n;throw Error(`Not implemented: editing ${e.type} fields`)},Xx=(e,t)=>e.type===`boolean`?!!t:String(t??``).trim()===``?null:Yx(e,t),Zx=(e,t)=>e.type===`boolean`?!!t:Gx(t),Qx=(e,t,n)=>{if(e.type===`boolean`)return!!t!=!!n;if(e.type===`file`)return Wx(t,n);let r=String(t??``).trim(),i=Gx(n);return e.type===`decimal`||e.type===`integer`?r===``||i===``?r!==i:Number(r)!==Number(i):r!==i},$x=(e,t,n)=>t?e===void 0||e===`edit`||n?{shown:`form`,offersEdit:!1,editing:!0}:{shown:e,offersEdit:t,editing:!1}:{shown:`read`,offersEdit:!1,editing:!1},eS=(e,t,n)=>(e??t?.helpWhen??`always`)===`always`||n,tS=(e,t,n)=>e?.help!==void 0&&eS(e.helpWhen,t,n)?e.help:void 0,nS=(e,t)=>e===`editing`?t:e!==`reading`||!t,rS=e=>typeof e==`object`&&!!e&&`key`in e,iS=(e,t)=>t.name!==e.tenant&&!t.readOnly&&(t.type===`relation`||qx(t)),aS=(e,t)=>{let n=Object.values(e.fields).filter(t=>iS(e,t)).map(e=>e.name),r=new Set,i=(t?.layout??[]).flatMap(e=>{if(e.kind!==`section`||!nS(e.when,!0))return[];let i=e.fields.filter(e=>n.includes(e)&&!r.has(e)&&nS(t?.fields[e]?.when,!0));return i.forEach(e=>r.add(e)),i.length>0?[{title:e.title,help:e.help,fields:i}]:[]}),a=n.filter(e=>!r.has(e));return a.length===0?i:[...i,{title:i.length===0?`Details`:`Other fields`,fields:a}]},oS=(e,t)=>(e?.primaryKey.length===1?e.fields[e.primaryKey[0]]?.type:void 0)===`integer`?Number(t):t,sS=(e,t,n)=>Object.fromEntries(Object.entries(n).flatMap(([n,r])=>{let i=e.fields[n];return i?rS(r)?[[n,oS(t[i.relation?.resource??``],r.key)]]:i.type===`boolean`?[[n,!!r]]:i.type===`file`?r?[[n,Yx(i,r)]]:[]:String(r).trim()===``?[]:[[n,Yx(i,r)]]:[]})),cS=e=>!e.nullable&&!e.default&&e.type!==`boolean`,lS=(e,t)=>e.type===`relation`?{key:t,label:t}:e.type===`boolean`?t===`true`:t,uS=(e,t,n={})=>Object.fromEntries(t.flatMap(t=>t.fields.flatMap(t=>{let r=e.fields[t];if(Object.hasOwn(n,t))return[[t,lS(r,n[t])]];let i=r.default;return!i||!(`value`in i)||i.value===null||i.value===void 0?[]:[[t,typeof i.value==`boolean`?i.value:String(i.value)]]}))),dS=e=>!!(e.default&&`db`in e.default),fS=e=>{if(!Fs(e))return[{message:e instanceof Error?e.message:`Something went wrong`}];let t=e.errors.map(e=>({message:e.message,hint:e.hint}));return t.length>0?t:[{message:e.message}]},pS=({error:e,title:t})=>(0,V.jsxs)(`div`,{role:`alert`,className:`flex gap-2.5 rounded-lg border border-danger/30 bg-danger-soft px-3 py-2 text-danger-text`,children:[(0,V.jsx)(Bn,{className:`mt-0.5 size-4 shrink-0`}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`p`,{className:`font-medium`,children:t}),fS(e).map(e=>(0,V.jsxs)(`p`,{className:`text-xs`,children:[e.message,e.hint&&(0,V.jsxs)(`span`,{className:`text-muted-foreground`,children:[` `,e.hint]})]},e.message))]})]}),mS=({checked:e,onChange:t,label:n})=>{let r=wd();return(0,V.jsx)(`button`,{type:`button`,role:`switch`,id:r.id,"aria-describedby":r[`aria-describedby`],"aria-checked":e,"aria-label":n,onClick:()=>t?.(!e),className:B(`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors`,e?`bg-primary`:`bg-border-strong`),children:(0,V.jsx)(`span`,{className:B(`size-4 rounded-full bg-white shadow transition-transform`,e?`translate-x-[18px]`:`translate-x-0.5`)})})},hS=e=>{e.style.height=`auto`,e.style.height=`${e.scrollHeight+e.offsetHeight-e.clientHeight}px`},gS=({invalid:e,className:t,rows:n=3,value:r,...i})=>{let a=(0,o.useRef)(null),s=wd();return(0,o.useLayoutEffect)(()=>{a.current&&hS(a.current)},[r]),(0,o.useEffect)(()=>{let e=a.current;if(!e)return;let t=e.clientWidth,n=new ResizeObserver(()=>{e.clientWidth!==t&&(t=e.clientWidth,hS(e))});return n.observe(e),()=>n.disconnect()},[]),(0,V.jsx)(`textarea`,{ref:a,rows:n,value:r,className:B(`block w-full resize-none overflow-hidden rounded-md border bg-background px-2.5 py-1.5 text-body text-foreground shadow-sm outline-none placeholder:text-faint-foreground focus:border-primary focus:ring-2 focus:ring-primary/20`,e?`border-danger`:`border-border-strong`,t),...s,...e&&{"aria-invalid":!0},...i})},_S=e=>typeof e==`object`&&e&&`name`in e?String(e.name):String(e),vS=(e,t)=>{if(t==null)return`—`;switch(e.kind){case`text`:case`id`:return String(t);case`money`:return`${rf(Number(t),e.currency,e.decimals)}${e.suffix??``}`;case`date`:return pf(Number(t));case`datetime`:return hf(Number(t));case`number`:return`${of(Number(t))}${e.suffix??``}`;case`signed`:return`${sf(Number(t))}${e.suffix??``}`;case`percent`:return Number(t)===0?`—`:cf(Number(t));case`status`:return rs(String(t),e.labels);case`relation`:return _S(t);case`boolean`:return t?void 0:`No`;case`file`:return Nx(t)?.name??`—`;case`user`:return tx(String(t)).name}},yS=(e,t)=>Math.ceil(e.length*7.2)+24+(t?16:0)+28,bS=e=>Math.ceil(Math.max(0,...e.map(e=>e.length))*7.2)+56,xS={body:7.5,mono:7.2,numeric:8},SS=24,CS=24,wS=16,TS=new Set([`status`,`money`,`number`,`signed`,`percent`,`date`,`datetime`,`boolean`]),ES=new Set([`money`,`number`,`signed`,`percent`,`date`,`datetime`]),DS=80,OS=400,kS=240,AS=e=>e===`id`?xS.mono:ES.has(e)?xS.numeric:xS.body,jS=(e,t)=>e.value?e.value(t):t[e.id],MS=(e,t)=>{let n=t.map(t=>vS(e,jS(e,t)));if(e.kind===`status`)return bS(n.map(e=>e??``));let r=e.kind===`user`||e.kind===`file`?CS:0;return Math.max(0,...n.map(t=>t===void 0?wS:Math.ceil(t.length*AS(e.kind))))+r+SS},NS=(e,t,n)=>Math.min(n,Math.max(t,e)),PS=(e,t)=>{if(TS.has(e.kind)&&!e.title)return{...e,fixed:!0,width:Math.max(e.minWidth??0,t)};let n={...e,fixed:!1,width:NS(t,DS,OS)};return e.kind===`id`?{...n,minWidth:Math.max(yS(e.header,e.sortable??!1),Math.min(t,kS))}:n},FS=(e,t)=>{if(t.length===0)return e;let n=e.map(e=>e.render?e:PS(e,MS(e,t))),r=n.filter((t,n)=>!t.fixed&&!t.title&&!e[n].render).map(e=>e.width),i=Math.max(0,...r);return n.map((t,n)=>t.title&&!e[n].render?{...t,width:Math.max(t.width,i)}:t)},IS=[[/^\s*(```|~~~).*$/,``],[/^\s*\[[^\]]+\]:\s+\S.*$/,``],[/^\s*([-*_]\s*){3,}$/,``],[/^\s*\|?(\s*:?-+:?\s*\|)+\s*:?-*:?\s*$/,``],[/^\s*#{1,6}\s+/,``],[/^\s*(>\s?)+/,``],[/^\s*([-*+]|\d+[.)])\s+(\[[ xX]\]\s+)?/,``]],LS=[[/!\[([^\]]*)\]\([^)]*\)/g,`$1`],[/\[([^\]]*)\]\([^)]*\)/g,`$1`],[/\[([^\]]+)\]\[[^\]]*\]/g,`$1`],[/<((?:https?|mailto):[^>\s]+)>/gi,`$1`],[/<\/?[a-z][^>]*>/gi,``],[/`([^`]+)`/g,`$1`],[/(?<!\\)(\*\*|__)(?=\S)(.+?)(?<=\S)\1/g,`$2`],[/(?<![\\\w*])\*(?=\S)(.+?)(?<=\S)\*/g,`$1`],[/(?<![\\\w])_(?=\S)(.+?)(?<=\S)_(?!\w)/g,`$1`],[/(?<!\\)~~(.+?)~~/g,`$1`],[/\s*\|\s*/g,` `],[/\\([\\`*_{}[\]()#+\-.!>~|])/g,`$1`]],RS=200,zS=e=>{let t=e.split(/\r?\n/).map(e=>IS.reduce((e,[t,n])=>e.replace(t,n),e)),n=LS.reduce((e,[t,n])=>e.replace(t,n),t.join(`
|
|
13
|
-
`)).replace(/\s+/g,` `).trim();return n.length>RS?`${n.slice(0,199).trimEnd()}…`:n},BS=(e,t)=>e.type===`text`&&!!t?.markdown,VS={draft:`neutral`,confirmed:`blue`,picking:`amber`,shipped:`violet`,delivered:`green`,cancelled:`red`,sent:`blue`,paid:`green`,overdue:`red`,lead:`blue`,active:`green`,dormant:`neutral`,receipt:`green`,issue:`blue`,transfer:`violet`,adjustment:`amber`},HS=e=>VS[e]??`neutral`,US={text:200,id:140,money:120,date:110,datetime:170,status:150,relation:200,boolean:64,number:100,signed:110,percent:110,user:130,file:180},WS=new Set([`datetime`,`date`,`boolean`,`percent`]),GS=/^(number|sku|reference|code)$/,KS=(e,t,n)=>{switch(e.type){case`relation`:return`relation`;case`file`:return`file`;case`enum`:return`status`;case`boolean`:return`boolean`;case`timestamp`:return`datetime`;case`date`:return`date`;case`decimal`:return t?.format===`percent`?`percent`:t?.prefix===`€`?`money`:`number`;case`integer`:case`bigint`:return/quantity|delta/.test(e.name)?`signed`:`number`;default:return GS.test(e.name)||n===0&&e.name===`id`?`id`:`text`}},qS=e=>Math.round(Number.parseFloat(String(e))*100),JS=(e,t)=>t?.list?.columns??Object.keys(e.fields).slice(0,6),YS=(e,t,n=[],r=JS(e,t))=>{let i=Dg(e,t);return r.flatMap((r,a)=>{let o=e.fields[r];if(!o)return[];let s=t?.fields[r],c=KS(o,s,a),l=Object.fromEntries((o.enumValues??[]).map(e=>[e,rs(e,s?.valueLabels)])),u=s?.suffix?Math.ceil(s.suffix.length*7.2):0;return[{id:r,header:s?.label??K(r),kind:c,width:(r===`name`?260:US[c])+u,sortable:o.sortable,minWidth:Math.max(c===`id`?150:0,yS(s?.label??K(r),o.sortable),c===`status`?bS(Object.values(l)):0,u>0?US[c]+u:0),...WS.has(c)&&{fixed:!0},...r===i&&{title:!0},...n.includes(r)&&{highlight:!0},...o.type===`enum`&&{tones:Object.fromEntries((o.enumValues??[]).map(e=>[e,HS(e)])),labels:l},...o.type===`enum`&&s?.valueColors&&{colors:s.valueColors},...o.type===`enum`&&s?.badgeShape&&{shape:s.badgeShape},...s?.suffix!==void 0&&{suffix:s.suffix},...c===`money`&&s?.decimals!==void 0&&{decimals:s.decimals},...c===`money`&&{currency:`EUR`,value:e=>e[r]==null?null:qS(e[r])},...(c===`datetime`||c===`date`)&&{value:e=>e[r]==null?null:Date.parse(String(e[r]))},...BS(o,s)&&{value:e=>typeof e[r]==`string`?zS(e[r]):e[r]},...(c===`percent`||c===`number`&&o.type===`decimal`)&&{value:e=>e[r]==null?null:Number(e[r])}}]})},XS=(e,t)=>`${t.prefix??``}${e}${t.suffix??``}`,ZS=(e,t,n={})=>{if(t==null||t===``)return`—`;switch(e.type){case`boolean`:return t?`Yes`:`No`;case`file`:return Nx(t)?.name??`—`;case`enum`:return rs(String(t),n.valueLabels);case`timestamp`:return hf(Date.parse(String(t)));case`date`:return pf(Date.parse(String(t)));case`decimal`:{let e=n.decimals===void 0?String(t):Number(t).toFixed(n.decimals);return n.format===`percent`?`${Number(t)}%`:XS(Number(e).toLocaleString(`en-IE`,{minimumFractionDigits:n.decimals??0,maximumFractionDigits:n.decimals??20}),n)}case`integer`:case`bigint`:return XS(String(t),n);default:return typeof t==`object`?JSON.stringify(t):String(t)}},QS=`$photos`,$S=e=>{for(let t of e?.list?.displays??[])if(t.kind===`cards`&&t.photos)return t.photos},eC=(e,t,n)=>{if(n===void 0||e.primaryKey.length!==1)return t;let r=e.primaryKey[0];return t.map(e=>({...e,[QS]:n[String(e[r])]??[]}))},tC=(e,t)=>t.filter(t=>e[t]!==null&&e[t]!==void 0&&e[t]!==``),nC=(e,t,n)=>{let r=e.fields[n.by];if(!r)return[];let i=t?.fields[n.by],a=(r.enumValues??[]).map(e=>({value:e,label:rs(e,i?.valueLabels)}));return r.nullable?[...a,{value:null,label:`No ${(i?.label??K(n.by)).toLowerCase()}`}]:a},rC=(e,t,n)=>{let r=Ya(n===null?fo.isNull(t):fo.eq(t,n));return e===``?r:`(${e}) AND ${r}`},iC=(e,t,n)=>({kind:`cards`,name:n.name,title:n.title??Dg(e,t),...n.subtitle!==void 0&&{subtitle:n.subtitle},...n.badge!==void 0&&{badge:n.badge},...n.meta&&{meta:n.meta}}),aC=e=>{if(!Fs(e))return e instanceof Error?e.message:`Something went wrong`;let t=e.errors.map(e=>e.message);return t.length>0?t.join(`; `):e.message},oC=e=>e?.list?.displays??[],sC=(e,t,n)=>{let r=n??e?.list?.default??`table`;if(!t)return r;let i=oC(e).filter(e=>e.kind===`cards`);return i.find(e=>e.name===r)?.name??i[0]?.name??r},cC=`rows`,lC=(e,t)=>{if(oC(t).some(e=>e.kind===`cards`||e.name===`rows`))return;let n=Dg(e,t),r=JS(e,t).filter(t=>t!==n&&e.fields[t]!==void 0),i=r.find(t=>e.fields[t].type===`enum`),a=r.filter(t=>t!==i&&e.fields[t].type!==`boolean`).slice(0,2);return{kind:`cards`,name:cC,label:`List`,icon:`list`,title:n,...i!==void 0&&{badge:i},footer:a}},uC=(e,t)=>t.name===`rows`&&!oC(e).some(e=>e.name===`rows`),dC=(e,t,n)=>{let r=sC(t,n);return n&&r===`table`&&lC(e,t)?cC:r},fC=(e,t,n)=>(n===`rows`?lC(e,t):void 0)??pC(t,n),pC=(e,t)=>{if(t===`table`)return;let n=t=>oC(e).find(e=>e.name===t);return n(t)??n(e?.list?.default)},mC={cards:`cards`,map:`map`,board:`kanban`},hC=e=>[{name:go,label:`Table`,icon:`table`},...oC(e).map(e=>({name:e.name,label:e.label??K(e.name),icon:e.icon??mC[e.kind]}))],gC=(e,t,n)=>{let r=hC(t);return n&&lC(e,t)?[...r,{name:cC,label:`List`,icon:`list`}]:r},_C=(e,t,n)=>({image:n.image,title:n.title??Dg(e,t),subtitle:n.subtitle,amount:n.amount??[],badge:n.badge,meta:n.meta??[],footer:n.footer??[],flags:n.flags??[]}),vC=(e,t)=>tC(e.record,t),yC=(e,t)=>vC(e,t)[0],bC=(e,t,n={})=>{let{suffix:r,...i}=n;return e.type!==`decimal`&&e.type!==`integer`&&e.type!==`bigint`||r===void 0||n.format===`percent`?{amount:ZS(e,t,n)}:{amount:ZS(e,t,i),suffix:r}},xC=(e,t)=>{let n=oC(e).filter(e=>e.kind===`cards`);return(t.cards===void 0?n[0]:n.find(e=>e.name===t.cards))??{kind:`cards`,name:t.name}},SC=(e,t,n)=>{if(n.kind===`custom`)return n.fields;if(n.kind===`map`)return[n.latitude,n.longitude,...SC(e,t,xC(t,n))];if(n.kind===`board`){let r=iC(e,t,n);return[n.by,r.title,r.subtitle,r.badge,...r.meta??[]].filter(e=>e!==void 0)}let{image:r,title:i,subtitle:a,amount:o,badge:s,meta:c,footer:l,flags:u}=_C(e,t,n);return[r,i,a,...o,s,...c,...l,...u].filter(e=>e!==void 0)},CC=(e,t,n)=>{let r=lC(e,t),i=r?[...oC(t),r]:oC(t);return[...new Set([...n,...i.flatMap(n=>SC(e,t,n))])]},wC=(e,t,n)=>{let r=uC(t,n)?[Dg(e,t),...JS(e,t)]:SC(e,t,n);return[...new Set(r)].filter(t=>e.fields[t]?.sortable)},TC=e=>typeof e==`object`&&!!e&&`id`in e&&`name`in e,EC=(e,t)=>{let n={},r={},i=Array.isArray(t.$photos)?t[QS]:void 0;for(let[i,a]of Object.entries(t))(i!==`id`&&i!==`$photos`||Object.hasOwn(e.fields,i))&&(e.fields[i]?.type===`relation`&&TC(a)?(n[i]=a.id,r[i]=a.name):n[i]=a);return{key:Ao(jg(e,n)),record:n,labels:r,...i&&{photos:i}}},DC=(e,t)=>{let n=t?.list?.sort?.[0];return n?`${n[0]} ${n[1]}`:`${e.primaryKey[0]} asc`},OC=e=>{let[t=``,n]=e.trim().split(/\s+/);return{columnId:t,direction:n===`desc`?`desc`:`asc`}},kC=e=>`${e.columnId} ${e.direction}`,AC=(e,t,n)=>{let r=e[n],i=t[n]?.listOf,a=i===void 0?void 0:r?.fields[i]?.relation?.resource;return a!==void 0&&e[a]?{model:e[a],view:t[a],listOf:!0}:{model:r,view:t[n],listOf:!1}},jC=(e,t,n=!1)=>({display:e?dC(e,t,n):sC(t,n),orderBy:e?DC(e,t):``,filterLayout:`bar`}),MC=(e,t)=>e?.kind===`record`?{kind:`record`,resource:e.resource,key:Ao(e.key),...e.edit&&{edit:!0}}:e?.kind===`list`?{...t(e.resource),filter:``,...e}:e,NC=(e,t,n)=>{let r={...e,...t},i=e=>r[e]!==void 0&&r[e]!==n[e];return{kind:`list`,resource:e.resource,...r.filter&&{filter:r.filter},...i(`display`)&&{display:r.display},...i(`orderBy`)&&{orderBy:r.orderBy},...i(`filterLayout`)&&{filterLayout:r.filterLayout},...r.map&&{map:r.map},...r.savedSearch&&{savedSearch:r.savedSearch}}},PC=()=>{let{path:e,params:t,basePath:n,navigate:r}=Oh(),{pages:i,resources:a,views:s}=q(),c=hu(),l=(0,o.useMemo)(()=>new Set(Object.keys(i)),[i]),u=t.toString(),d=(0,o.useMemo)(()=>ms(u?`${e}?${u}`:e,l),[e,u,l]),f=(0,o.useCallback)(e=>{let t=AC(a,s,e);return jC(t.model,t.view,c)},[a,s,c]),p=(0,o.useMemo)(()=>MC(d,f),[d,f]),m=(0,o.useCallback)((e,t)=>r(us(e),t),[r]);return{address:p,set:(0,o.useCallback)(e=>{if(d?.kind!==`list`)throw Error(`set changes the list the app shows; use go to move to another address`);m(NC(d,e,f(d.resource)),{replace:!0})},[d,f,m]),go:m,href:(0,o.useCallback)(e=>us(e,n),[n]),open:(0,o.useCallback)(e=>r(e.startsWith(`${n}/`)?e.slice(n.length):e),[n,r])}},FC=({to:e,...t})=>(0,V.jsx)(one,{to:us(e),...t}),IC=(e,{filter:t,orderBy:n,pageSize:r=50,fields:i,startToken:a=``,enabled:o=!0}={})=>{let s=G(),c=Ss(t)??``,l=bh({queryKey:[...W.list(e,c,n??``,r,a),i?.join(`,`)??``],enabled:o,initialPageParam:a,queryFn:({pageParam:t})=>s.list(e,{filter:c,orderBy:n,pageSize:r,fields:i,pageToken:t}),getNextPageParam:e=>e.nextPageToken||void 0}),u=l.data?.pages??[];return{...l,items:u.flatMap(e=>e.items),totalEstimate:u[0]?.totalSizeEstimate}},LC=uo(),RC=e=>e.split(/\s+/).filter(Boolean),zC=(e,t,n,r=!1)=>{let i=RC(n);if(i.length===0)return{filter:void 0,local:!1};if(r)return{filter:void 0,local:!0};if(e.search?.length)return{filter:Ya(LC.search(n)),local:!1};let a=e.fields[t];if(a?.type!==`text`||!a.filterable)return{filter:void 0,local:!0};let o=i.map(e=>LC.eq(t,`*${e.replaceAll(`*`,``)}*`));return{filter:Ya(LC.and(...o)),local:!1}},BC=(e,t)=>{if(e==null)return!1;let n=String(e).toLowerCase();return RC(t).every(e=>n.includes(e.toLowerCase()))},VC=(e,t,n,r)=>{(0,o.useEffect)(()=>{if(!e||!t)return;let n=new IntersectionObserver(e=>e.some(e=>e.isIntersecting)&&r(),{root:e});return n.observe(t),()=>n.disconnect()},[e,t,n,r])},HC=({target:e,view:t,value:n,label:r,invalid:i,onChange:a})=>{let[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(!1),[d,f]=(0,o.useState)(-1),[p,m]=(0,o.useState)(null),[h,g]=(0,o.useState)(null),_=(0,o.useId)(),v=e.primaryKey[0],y=Eg(e,t),[b,x]=(0,o.useState)(!1),S=zC(e,y,s,b),C=IC(e.name,{filter:S.filter,fields:[v,y],enabled:l}),w=S.filter!==void 0&&C.error instanceof Ns&&C.error.slug===`expensive-query`;(0,o.useEffect)(()=>{w&&x(!0)},[w]);let T=S.local?C.items.filter(e=>BC(e[y],s)):C.items,E=!!C.hasNextPage,D=C.isPending||C.isFetchingNextPage,{fetchNextPage:O}=C;VC(p,h,C.items.length,(0,o.useCallback)(()=>O({cancelRefetch:!1}),[O]));let k=e=>`${_}-${e}`,A=(0,o.useRef)(null);(0,o.useEffect)(()=>{!l&&document.activeElement===A.current&&A.current?.select()},[l]),(0,o.useEffect)(()=>{l&&d>=0&&document.getElementById(k(d))?.scrollIntoView({block:`nearest`})});let j=()=>{c(``),f(-1),u(!1)},M=e=>{a(String(e[v]),String(e[y])),j()};return(0,V.jsxs)(`div`,{className:`relative`,children:[(0,V.jsx)(Td,{ref:A,role:`combobox`,"aria-autocomplete":`list`,"aria-expanded":l,"aria-controls":_,"aria-activedescendant":l&&T[d]?k(d):void 0,invalid:i,placeholder:`Search ${(t?.names?.plural??K(e.name)).toLowerCase()}`,value:l?s:r??n,onFocus:()=>u(!0),onBlur:j,onKeyDown:e=>{if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(e.preventDefault(),!l)return u(!0);let t=e.key===`ArrowDown`?1:-1;f(e=>Math.min(Math.max(e+t,0),T.length-1));return}if(e.key===`Enter`&&l&&T[d]){e.preventDefault(),M(T[d]);return}e.key===`Escape`&&l&&(e.preventDefault(),e.stopPropagation(),j())},onChange:e=>{c(e.target.value),f(e.target.value.trim()?0:-1),u(!0)}}),l&&(0,V.jsxs)(`ul`,{ref:m,id:_,role:`listbox`,className:`absolute z-30 mt-1 max-h-60 w-full overflow-y-auto rounded-md border bg-background py-1 shadow-pop`,onMouseDown:e=>e.preventDefault(),children:[T.map((e,t)=>(0,V.jsx)(`li`,{id:k(t),role:`option`,"aria-selected":t===d,className:B(`cursor-pointer truncate px-3 py-1.5`,t===d&&`bg-muted`,String(e[v])===n&&`font-medium`),onMouseMove:()=>t!==d&&f(t),onClick:()=>M(e),children:String(e[y])},String(e[v]))),E&&(0,V.jsx)(`li`,{ref:g,"aria-hidden":!0,className:`h-px`}),C.error&&!w&&(0,V.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`Could not load the options`}),!E&&!D&&!C.error&&T.length===0&&(0,V.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`No matches`}),D&&(0,V.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`Loading`})]})]})},UC=`••••••••••`,WC=({field:e,hints:t,value:n,reveal:r,locked:i,invalid:a,placeholder:s,onChange:c})=>{let[l,u]=(0,o.useState)(!1),d=yh({mutationFn:async()=>r(),onSuccess:()=>u(!0)}),f=Gx(n)!==``,p=t?.label??K(e.name),m=(0,V.jsx)(U,{variant:`ghost`,size:`sm`,className:`-mr-1.5 px-1.5`,"aria-label":`${l?`Hide`:`Show`} ${p}`,"aria-pressed":l,loading:d.isPending,onClick:()=>{l||f||!r||d.isSuccess?u(!l):d.mutate()},children:!d.isPending&&(l?(0,V.jsx)(Xe,{className:`size-3.5`}):(0,V.jsx)(Qe,{className:`size-3.5`}))}),h=d.error&&(0,V.jsx)(`div`,{className:`mt-2`,children:(0,V.jsx)(pS,{title:`Could not show the ${p}`,error:d.error})});if(i)return(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2 py-1`,children:[(0,V.jsx)(`span`,{className:B(l?t?.format===`code`?`font-mono text-xs`:``:`tracking-widest text-muted-foreground`),children:l?ZS(e,d.data,t):UC}),r&&m]}),h]});let g=f?Gx(n):l&&d.isSuccess?Gx(d.data):``;return(0,V.jsxs)(`div`,{children:[(0,V.jsx)(Td,{type:l?`text`:`password`,autoComplete:`off`,invalid:a,"aria-label":p,className:B(t?.format===`code`&&`font-mono text-xs`),placeholder:f||!r?s:UC,value:g,trailing:m,onChange:e=>c(e.target.value)}),h]})};function GC(e){let{PI:t,min:n,max:r,cos:i,round:a}=Math,o=e[0]|e[1]<<8|e[2]<<16,s=e[3]|e[4]<<8,c=(o&63)/63,l=(o>>6&63)/31.5-1,u=(o>>12&63)/31.5-1,d=(o>>18&31)/31,f=o>>23,p=(s>>3&63)/63,m=(s>>9&63)/63,h=s>>15,g=r(3,h?f?5:7:s&7),_=r(3,h?s&7:f?5:7),v=f?(e[5]&15)/15:1,y=(e[5]>>4)/15,b=f?6:5,x=0,S=(t,n,r)=>{let i=[];for(let a=0;a<n;a++)for(let o=+!a;o*n<t*(n-a);o++)i.push(((e[b+(x>>1)]>>((x++&1)<<2)&15)/7.5-1)*r);return i},C=S(g,_,d),w=S(3,3,p*1.25),T=S(3,3,m*1.25),E=f&&S(5,5,y),D=KC(e),O=a(D>1?32:32*D),k=a(D>1?32/D:32),A=new Uint8Array(O*k*4),j=[],M=[];for(let e=0,a=0;e<k;e++)for(let o=0;o<O;o++,a+=4){let s=c,d=l,p=u,m=v;for(let e=0,n=r(g,f?5:3);e<n;e++)j[e]=i(t/O*(o+.5)*e);for(let n=0,a=r(_,f?5:3);n<a;n++)M[n]=i(t/k*(e+.5)*n);for(let e=0,t=0;e<_;e++)for(let n=+!e,r=M[e]*2;n*_<g*(_-e);n++,t++)s+=C[t]*j[n]*r;for(let e=0,t=0;e<3;e++)for(let n=+!e,r=M[e]*2;n<3-e;n++,t++){let e=j[n]*r;d+=w[t]*e,p+=T[t]*e}if(f)for(let e=0,t=0;e<5;e++)for(let n=+!e,r=M[e]*2;n<5-e;n++,t++)m+=E[t]*j[n]*r;let h=s-2/3*d,y=(3*s-h+p)/2,b=y-p;A[a]=r(0,255*n(1,y)),A[a+1]=r(0,255*n(1,b)),A[a+2]=r(0,255*n(1,h)),A[a+3]=r(0,255*n(1,m))}return{w:O,h:k,rgba:A}}function KC(e){let t=e[3],n=e[2]&128,r=e[4]&128;return(r?n?5:7:t&7)/(r?t&7:n?5:7)}function qC(e,t,n){let r=e*4+1,i=6+t*(5+r),a=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,e>>8,e&255,0,0,t>>8,t&255,8,6,0,0,0,0,0,0,0,i>>>24,i>>16&255,i>>8&255,i&255,73,68,65,84,120,1],o=[0,498536548,997073096,651767980,1994146192,1802195444,1303535960,1342533948,-306674912,-267414716,-690576408,-882789492,-1687895376,-2032938284,-1609899400,-1111625188],s=1,c=0;for(let e=0,i=0,o=r-1;e<t;e++,o+=r-1)for(a.push(e+1<t?0:1,r&255,r>>8,~r&255,r>>8^255,0),c=(c+s)%65521;i<o;i++){let e=n[i]&255;a.push(e),s=(s+e)%65521,c=(c+s)%65521}a.push(c>>8,c&255,s>>8,s&255,0,0,0,0,0,0,0,0,73,69,78,68,174,66,96,130);for(let[e,t]of[[12,29],[37,41+i]]){let n=-1;for(let r=e;r<t;r++)n^=a[r],n=n>>>4^o[n&15],n=n>>>4^o[n&15];n=~n,a[t++]=n>>>24,a[t++]=n>>16&255,a[t++]=n>>8&255,a[t++]=n&255}return`data:image/png;base64,`+btoa(String.fromCharCode(...a))}function JC(e){let t=GC(e);return qC(t.w,t.h,t.rgba)}var YC=(e,t,n)=>{if(!URL.canParse(e,t))return`no-referrer`;let r=new URL(e,t);if((r.protocol===`http:`||r.protocol===`https:`)&&!(r.origin===new URL(t).origin||n.includes(r.hostname)))return`no-referrer`},XC=e=>URL.canParse(e)?[new URL(e).hostname]:[],ZC=()=>{let e=(0,o.useContext)(l_);return(0,o.useMemo)(()=>[...e?.files?.trustedHosts??[],...(e?.sources??[]).flatMap(({source:e})=>XC(e.url))],[e?.files,e?.sources])},QC=e=>{let t;try{t=atob(e)}catch(e){if(e instanceof DOMException&&e.name===`InvalidCharacterError`)return;throw e}return JC(Uint8Array.from(t,e=>e.charCodeAt(0)))},$C=({image:e,className:t,loading:n})=>{let[r,i]=(0,o.useState)(),a=ZC(),s=(0,o.useMemo)(()=>e.placeholder===void 0?void 0:QC(e.placeholder),[e.placeholder]),c=s!==void 0&&r!==e.url;return(0,V.jsx)(`img`,{src:e.url,alt:``,loading:n,decoding:`async`,referrerPolicy:YC(e.url,window.location.href,a),onLoad:()=>i(e.url),className:t,style:c?{backgroundImage:`url("${s}")`,backgroundSize:`cover`,backgroundPosition:`center`}:void 0})},ew=({value:e})=>{let t=Vx(e,{width:40,height:40});return t?(0,V.jsx)($C,{image:t,className:`size-10 shrink-0 rounded border border-border object-cover`}):(0,V.jsx)(`span`,{className:`flex size-10 shrink-0 items-center justify-center rounded border border-border bg-muted text-muted-foreground`,children:(0,V.jsx)(it,{className:`size-4`})})},tw=({value:e})=>{let t=Nx(e);if(!t)return(0,V.jsx)(`div`,{className:`py-1.5 text-muted-foreground`,children:`—`});if(`missing`in t)return(0,V.jsx)(`div`,{className:`py-1.5 text-danger-text`,children:`The file is missing from storage`});let n=`url`in t?t.url:void 0,r=`corrected`in t?t.corrected:void 0;return(0,V.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3 py-1`,children:[(0,V.jsx)(ew,{value:e}),(0,V.jsxs)(`div`,{className:`min-w-0`,children:[n&&!n.startsWith(`blob:`)?(0,V.jsx)(`a`,{href:n,target:`_blank`,rel:`noreferrer`,className:`block truncate font-medium text-primary-text hover:underline`,children:t.name}):(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:t.name}),(0,V.jsxs)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:[t.type,t.size!==void 0&&` · ${Fx(t.size)}`,r&&` · sent as ${r.from}`]})]})]})},nw=({field:e,hints:t,resource:n,value:r,locked:i,invalid:a,onChange:s})=>{let c=G(),l=(0,o.useRef)(null),[u,d]=(0,o.useState)(),[f,p]=(0,o.useState)(!1),m=t?.label??K(e.name),h=yh({mutationFn:async t=>{d(0);let r=await c.upload(n,e.name,t,{onProgress:(e,t)=>d(t>0?e/t:0)});return{uploaded:r,...Ix(r.file.type)&&{preview:URL.createObjectURL(t)}}},onSuccess:e=>s(e),onSettled:()=>d(void 0)});if(i||e.readOnly)return(0,V.jsx)(tw,{value:r});let g=e=>{let t=e?.[0];t&&h.mutate(t)},_=e=>{e.preventDefault(),p(!1),g(e.dataTransfer.files)},v=(0,V.jsx)(`input`,{ref:l,type:`file`,hidden:!0,accept:Hx(e),"aria-label":`Choose a file for ${m}`,onChange:e=>g(e.target.files)}),y=h.error&&(0,V.jsx)(`div`,{className:`mt-2`,children:(0,V.jsx)(pS,{title:`Not uploaded`,error:h.error})});return h.isPending?(0,V.jsxs)(`div`,{className:`py-1.5`,role:`status`,"aria-label":`Uploading ${m}`,children:[(0,V.jsx)(`div`,{className:`h-1.5 overflow-hidden rounded-full bg-muted`,children:(0,V.jsx)(`div`,{className:`h-full rounded-full bg-primary transition-[width]`,style:{width:`${Math.round((u??0)*100)}%`}})}),(0,V.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`Uploading… `,Math.round((u??0)*100),`%`]})]}):Nx(r)?(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,V.jsx)(tw,{value:r})}),(0,V.jsx)(U,{size:`sm`,onClick:()=>l.current?.click(),children:`Replace`}),e.nullable&&(0,V.jsx)(U,{size:`sm`,variant:`ghost`,onClick:()=>s(null),children:`Remove`})]}),v,y]}):(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),p(!0)},onDragLeave:()=>p(!1),onDrop:_,className:B(`flex items-center gap-3 rounded-md border border-dashed px-3 py-2.5 text-muted-foreground`,f?`border-primary bg-primary/5`:a?`border-danger`:`border-border-strong`),children:[(0,V.jsx)(Wn,{className:`size-4 shrink-0`}),(0,V.jsx)(`span`,{className:`flex-1`,children:`Drop a file here or`}),(0,V.jsxs)(U,{size:`sm`,onClick:()=>l.current?.click(),children:[(0,V.jsx)(Qt,{className:`size-3.5`}),`Choose a file`]})]}),v,y]})},rw=(e,t,n)=>{let r=n?.widget;if(!r||t.sensitive||!e||!Object.hasOwn(e,r.name))return;let i=e[r.name];return i.of.includes(t.type)?{name:r.name,widget:i,props:r.props??{}}:void 0},iw=(e,t)=>rw(Zg().fields,e,t),aw=({shown:e,part:t,field:n,value:r,onChange:i,invalid:a=!1})=>{let{widget:o,props:s}=e,c={field:n,value:r??null,props:s};if(t!==`editor`){let e=t===`cell`?o.cell??o.display:o.display;return(0,V.jsx)(e,{...c})}let l=o.editor;return l&&i?(0,V.jsx)(l,{...c,onChange:i,invalid:a}):void 0},ow=({fallback:e,...t})=>{let n=aw(t);return n?(0,V.jsx)(ng,{name:`The field type ${t.shown.name}`,fallback:e,children:n}):e},sw=(0,o.lazy)(()=>Zh(()=>import(`./markdown-content-yqq0wmAS.js`).then(e=>({default:e.MarkdownContent})),__vite__mapDeps([0,1,2,3]))),cw=e=>(0,V.jsx)(o.Suspense,{fallback:(0,V.jsx)(`div`,{className:B(`whitespace-pre-line break-words`,e.className),children:e.source}),children:(0,V.jsx)(sw,{...e})}),lw=[{value:`write`,label:`Write`},{value:`preview`,label:`Preview`}],uw=({value:e,onChange:t,label:n,invalid:r,placeholder:i})=>{let[a,s]=(0,o.useState)(`write`);return(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsx)(`span`,{className:`self-start`,children:(0,V.jsx)(ed,{value:a,options:lw,onChange:s,label:n})}),a===`write`?(0,V.jsx)(gS,{rows:5,invalid:r,placeholder:i,value:e,onChange:e=>t(e.target.value)}):(0,V.jsx)(`div`,{className:`min-h-[7.5rem] rounded-md border border-border px-2.5 py-1.5`,children:e.trim()===``?(0,V.jsx)(`span`,{className:`text-faint-foreground`,children:`Nothing to preview`}):(0,V.jsx)(cw,{source:e})})]})},dw=new Set([`integer`,`bigint`,`decimal`]),fw=e=>e===`integer`||e===`bigint`?{inputMode:`numeric`,enterKeyHint:`done`}:e===`decimal`?{inputMode:`decimal`,enterKeyHint:`done`}:{},pw=({field:e,hints:t,value:n,stored:r,relationLabel:i,relationTo:a,relationPicker:o,invalid:s,locked:c,placeholder:l,reveal:u,resource:d,onChange:f})=>{let p=wd();if(e.type===`file`)return(0,V.jsx)(nw,{field:e,hints:t,resource:d??``,value:n,locked:c||!d,invalid:s,onChange:f});if(e.sensitive)return(0,V.jsx)(WC,{field:e,hints:t,value:n,reveal:u,locked:c||e.readOnly,invalid:s,placeholder:l,onChange:f});if(e.type===`relation`&&o&&!e.readOnly&&!c){let e=(0,V.jsx)(HC,{target:o.target,view:o.view,value:String(n),label:i,invalid:s,onChange:(e,t)=>f({key:e,label:t})});return a?(0,V.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,V.jsx)(`div`,{className:`min-w-0 flex-1`,children:e}),(0,V.jsx)(FC,{to:a,"aria-label":`Open ${i??String(n)}`,title:`Open`,className:B(Sf({variant:`ghost`}),`w-8 px-0`),children:(0,V.jsx)(O,{className:`size-4`})})]}):e}if(e.type===`boolean`&&c)return(0,V.jsx)(`div`,{className:`py-1.5 text-muted-foreground`,children:ZS(e,r,t)});if(e.type===`boolean`)return(0,V.jsx)(mS,{checked:!!n,onChange:f,label:t?.label??K(e.name)});if(e.type===`relation`){let e=i??String(r??`—`);return(0,V.jsx)(`div`,{className:`py-1.5`,children:a?(0,V.jsx)(FC,{to:a,className:`font-medium text-primary-text hover:underline`,children:e}):e})}let m=!!t?.multiline&&e.type===`text`,h=BS(e,t);return(!qx(e)||c)&&h&&typeof r==`string`&&r!==``?(0,V.jsx)(cw,{source:r,className:`py-1.5`}):!qx(e)||c?(0,V.jsx)(`div`,{className:B(`py-1.5 tabular-nums`,e.type===`decimal`||e.type===`integer`?`font-medium`:`text-muted-foreground`,m&&`whitespace-pre-line break-words`),children:ZS(e,r,t)}):e.type===`enum`?(0,V.jsxs)(`select`,{...p,...s&&{"aria-invalid":!0},value:String(n),onChange:e=>f(e.target.value),className:`h-8 w-full rounded-md border border-border-strong bg-background px-2 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20`,children:[n===``&&(0,V.jsx)(`option`,{value:``,children:`Choose...`}),(e.enumValues??[]).map(e=>(0,V.jsx)(`option`,{value:e,children:rs(e,t?.valueLabels)},e))]}):h?(0,V.jsx)(uw,{label:t?.label??K(e.name),invalid:s,placeholder:l,value:String(n),onChange:f}):m?(0,V.jsx)(gS,{invalid:s,placeholder:l,value:String(n),onChange:e=>f(e.target.value)}):(0,V.jsx)(Td,{invalid:s,leading:t?.prefix?(0,V.jsx)(`span`,{children:t.prefix}):void 0,trailing:t?.suffix?(0,V.jsx)(`span`,{children:t.suffix.trim()}):void 0,placeholder:l,className:B(dw.has(e.type)&&`text-right tabular-nums`),...fw(e.type),value:String(n),onChange:e=>f(e.target.value)})},mw=e=>{let{field:t,hints:n,value:r,stored:i,invalid:a,locked:o,onChange:s}=e,c=iw(t,n),l=(0,V.jsx)(pw,{...e});return c?o||!qx(t)?(0,V.jsx)(ow,{shown:c,part:`display`,field:t,value:i,fallback:l}):t.type===`file`||t.type===`relation`?l:(0,V.jsx)(ow,{shown:c,part:`editor`,field:t,value:Xx(t,r),invalid:!!a,onChange:e=>s(Zx(t,e)),fallback:l}):l},hw={text:`text`,integer:`integer`,decimal:`decimal`,boolean:`boolean`,date:`date`},gw=e=>{let t={name:e.name,column:e.name,nullable:!0,readOnly:!1,filterable:!1,sortable:!1,aliases:[]};return e.kind===`custom`?{...t,type:`json`}:e.kind===`choice`?e.resource===void 0?{...t,type:`enum`,enumValues:(e.options??[]).map(e=>e.value)}:{...t,type:`relation`,relation:{resource:e.resource,columns:[e.name]}}:{...t,type:hw[e.kind]}},_w=e=>({label:e.label,...e.multiline&&{multiline:!0},...e.options&&{valueLabels:Object.fromEntries(e.options.map(e=>[e.value,e.label]))}}),vw=e=>Object.fromEntries(e.map(e=>e.kind===`custom`?[e.name,e.default??null]:e.kind===`boolean`?[e.name,!!e.default]:[e.name,Gx(e.default)])),yw=(e,t)=>e.kind===`custom`?t??null:rS(t)?t.key:e.resource===void 0?Yx(gw(e),t):String(t??``)===``?null:String(t),bw=(e,t)=>{let n=Object.fromEntries(e.map(e=>[e.name,yw(e,t[e.name])])),r=xo(e,n);return{shown:r,values:Object.fromEntries(Object.entries(n).filter(([e])=>r.has(e)))}},xw=/^-?\d+(\.\d+)?$/,Sw=/^\d{4}-\d{2}-\d{2}$/,Cw=(e,t)=>{if(t===null||t===``)return e.required?`Required`:void 0;if(e.kind===`integer`&&!Number.isInteger(t))return`A whole number`;if(e.kind===`decimal`&&!xw.test(String(t)))return`A number`;if(e.kind===`date`&&!Sw.test(String(t)))return`A date as YYYY-MM-DD`;if(e.max!==void 0&&String(t).length>e.max)return`At most ${e.max} characters`},ww=(e,t)=>Object.fromEntries(e.flatMap(e=>{if(!Object.hasOwn(t,e.name))return[];let n=Cw(e,t[e.name]);return n?[[e.name,n]]:[]})),Tw=class extends Error{errors;constructor(e){super(Object.values(e).join(`; `)),this.errors=e,this.name=`ActionInputError`}},Ew=(e,t)=>{let n=new Set(t.map(e=>e.name)),r=e instanceof Tw?Object.entries(e.errors):Fs(e)?e.errors.flatMap(e=>e.field?[[e.field,e.message]]:[]):[];return Object.fromEntries(r.filter(([e])=>n.has(e)))},Dw=({input:e,held:t,invalid:n,onChange:r})=>{let{resources:i,views:a}=q(),{components:o}=Zg();if(e.kind===`custom`){let i=o?.[e.component??``];if(!i)throw Error(`Input "${e.name}": the app has no component "${e.component}"`);return(0,V.jsx)(i,{input:e,value:t??null,onChange:r,invalid:n,props:e.props??{}})}let s=e.resource===void 0?void 0:i[e.resource];return(0,V.jsx)(mw,{field:gw(e),hints:_w(e),value:rS(t)?t.key:t,stored:void 0,relationLabel:rS(t)?t.label:void 0,relationPicker:s?{target:s,view:a[s.name]}:void 0,invalid:n,onChange:r})},Ow=({action:e,label:t,danger:n,onCancel:r,onSubmit:i})=>{let[a,s]=(0,o.useState)(()=>vw(e.inputs)),[c,l]=(0,o.useState)({}),[u,d]=(0,o.useState)(),[f,p]=(0,o.useState)(!1),m=(0,o.useId)(),{shown:h,values:g}=bw(e.inputs,a),_=async()=>{let t=ww(e.inputs,g);l(t),d(void 0),!(Object.keys(t).length>0)&&(p(!0),await i(g).catch(t=>{l(Ew(t,e.inputs)),d(t)}),p(!1))},v=(e,t)=>{l(({[e]:t,...n})=>n),s(n=>({...n,[e]:t}))};return(0,V.jsx)(h_,{title:t,description:e.confirm,open:!0,onClose:r,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:r,children:`Cancel`}),(0,V.jsx)(U,{variant:n?`danger`:`primary`,type:`submit`,form:m,loading:f,children:t})]}),children:(0,V.jsxs)(`form`,{id:m,className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),_()},children:[u!==void 0&&Object.keys(c).length===0&&(0,V.jsx)(pS,{title:`${t} failed`,error:u}),e.inputs.filter(e=>h.has(e.name)).map(e=>(0,V.jsx)(bx,{label:e.label,required:e.required,help:e.help,error:c[e.name],children:(0,V.jsx)(Dw,{input:e,held:a[e.name],invalid:!!c[e.name],onChange:t=>v(e.name,t)})},e.name))]})})},kw=({action:e,label:t,danger:n,onCancel:r,onConfirm:i})=>(0,V.jsx)(Cf,{title:`${t}?`,description:e.confirm,onClose:r,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:r,children:`Cancel`}),(0,V.jsx)(U,{variant:n?`danger`:`primary`,onClick:i,children:t})]})}),Aw=e=>!!(e.confirm||e.inputs?.length),jw=({action:e,label:t,danger:n,onCancel:r,onConfirm:i,onSubmit:a})=>{let{inputs:o}=e;return o?.length?(0,V.jsx)(Ow,{action:{...e,inputs:o},label:t,danger:n,onCancel:r,onSubmit:a}):(0,V.jsx)(kw,{action:e,label:t,danger:n,onCancel:r,onConfirm:i})},Mw=(0,o.createContext)(void 0),Nw=({value:e,children:t})=>(0,V.jsx)(Mw.Provider,{value:e,children:t}),Pw=()=>(0,o.useContext)(Mw),Fw=(e,t)=>e[t]||e.conditional.includes(t),Iw=(e,t)=>e.permissions?.[t]??!0,Lw=(e,t)=>e?.fields?e.fields[t]??`hidden`:`edit`,Rw=(e,t={})=>e.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(e,n)=>encodeURIComponent(t[n]===null||t[n]===void 0?``:String(t[n]))),zw=e=>{if(typeof e!=`string`||!URL.canParse(e))return;let t=new URL(e);return t.protocol===`https:`||t.protocol===`http:`?t.href:void 0},Bw=(e,t={})=>{let n=Oo(e);return n===void 0?Rw(e,t):zw(t[n])},Vw=e=>{e!==void 0&&(/^https?:/i.test(e)?window.open(e,`_blank`,`noopener,noreferrer`):window.location.assign(e))},Hw=e=>URL.canParse(e)?new URL(e).hostname.replace(/^www\./,``):``,Uw=(e,t)=>Object.entries(t).every(([t,n])=>Object.is(e[t],n)),Ww=(e,t)=>{let n=e.run;if(n?.kind===`update`)return t&&Uw(t,n.values)?void 0:e;if(n?.kind!==`link`||!(`href`in n))return e;let r=Bw(n.href,t);if(r!==void 0)return e.label.includes(`{host}`)?{...e,label:e.label.replaceAll(`{host}`,Hw(r))}:e},Gw=(e,t)=>({model:e,record:t,key:Ao(jg(e,t)),etag:typeof t.etag==`string`?t.etag:void 0,permissions:t.permissions}),Kw=(e,t,n=``)=>({queryKey:W.count(t.name,n),queryFn:async()=>{let r=await e.list(t.name,{filter:n||void 0,pageSize:1,count:`exact`,fields:t.primaryKey});return r.totalSize??r.totalSizeEstimate}}),qw=(e,t=``)=>vh(Kw(G(),e,t)),Jw=(e,{filter:t=``,sort:n=``,key:r})=>{let i=G();return vh({queryKey:r===void 0?W.firstRecord(e.name,t,n):W.record(e.name,r),queryFn:async()=>{if(r!==void 0){let t=await i.get(e.name,r);return{...Gw(e,t.record),etag:t.etag,permissions:t.permissions}}let a=await i.list(e.name,{filter:t||void 0,orderBy:n||void 0,pageSize:1});return a.items[0]?Gw(e,a.items[0]):null}})},Yw=(e,{filter:t=``,sort:n=``,pageSize:r,pageToken:i=``})=>{let a=G();return vh({queryKey:W.list(e.name,t,n,r,i),placeholderData:mm,queryFn:()=>a.list(e.name,{filter:t||void 0,orderBy:n||void 0,pageSize:r,pageToken:i||void 0})})},Xw=()=>{let e=Wp();return(0,o.useCallback)(t=>e.invalidateQueries({predicate:e=>e.queryKey[1]===t}),[e])},Zw=e=>e instanceof Error?e.message:`Something went wrong`,Qw=(e,t,n)=>{let{views:r}=q(),{actions:i,components:a}=Zg(),s=f_(e),c=G(),l=Th(e),u=Lg(),d=Xw(),{go:f}=PC(),[p,m]=(0,o.useState)(),h=(r[e]?.actions??[]).flatMap(e=>Ww(e,t?.record)??[]),g=e=>{let n=e.run?.kind;if((n===`update`||n===`delete`)&&!t)return`Needs a record`;if(n===`update`&&(!Fw(s,`update`)||t?.permissions?.update===!1))return`You cannot change this record`;if(n===`delete`&&(!Fw(s,`delete`)||t?.permissions?.delete===!1))return`You cannot delete this record`;if(!e.run&&!i?.[e.name])return`The app has no handler for "${e.name}"`;let r=e.inputs?.find(e=>e.kind===`custom`&&!a?.[e.component??``]);if(r)return`The app has no component "${r.component}" for input "${r.name}"`},_=async(r,a)=>{let{run:o}=r;if(o?.kind===`link`){`to`in o?f(Do(o.to,t?.record)):Vw(Bw(o.href,t?.record));return}o?.kind===`update`?await c.update(e,t.key,o.values,t.etag??`*`):o?.kind===`delete`?await c.remove(e,t.key,{etag:t.etag}):await i[r.name]({resource:e,record:t?.record,recordKey:t?.key,etag:t?.etag,client:l,navigate:f,...a&&{values:a}}),await d(e),u.show({state:`success`,title:`${r.label}: done`}),n?.(r)};return{actions:h,blocked:g,running:p,run:async e=>{g(e)||(m(e.name),await _(e).catch(t=>u.show({state:`error`,title:`${e.label} failed`,description:Zw(t)})),m(void 0))},submit:async(e,t)=>{g(e)||(m(e.name),await _(e,t).finally(()=>m(void 0)))}}},$w=(e,t,n)=>{let r=Qw(e,n),i=r.actions.find(e=>e.name===t);return{action:i,blocked:i?r.blocked(i):`No action "${t}"`,running:r.running===t,run:()=>i?r.run(i):Promise.resolve(),submit:e=>i?r.submit(i,e):Promise.resolve()}},eT=e=>e.props,tT=({node:e})=>{let{name:t,resource:n,label:r,variant:i}=eT(e),a=Pw(),s=$w(n??a?.model.name??``,t,n===void 0||n===a?.model.name?a:void 0),[c,l]=(0,o.useState)(!1);if(!s.action)return null;let u=r??s.action.label;return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{size:`sm`,variant:i??`secondary`,loading:s.running,disabled:!!s.blocked,title:s.blocked,onClick:()=>Aw(s.action)?l(!0):void s.run(),children:u}),c&&(0,V.jsx)(jw,{action:s.action,label:u,danger:i===`danger`,onCancel:()=>l(!1),onConfirm:()=>{l(!1),s.run()},onSubmit:async e=>{await s.submit(e),l(!1)}})]})},nT=({title:e,description:t,actions:n,className:r,bodyClassName:i,children:a})=>(0,V.jsxs)(`section`,{className:B(`flex min-w-0 flex-col rounded-lg border border-border bg-background`,r),"aria-label":e,children:[(e||t||n)&&(0,V.jsxs)(`header`,{className:`flex flex-wrap items-start justify-between gap-x-4 gap-y-2 px-4 pt-4`,children:[(0,V.jsxs)(`div`,{className:`min-w-0`,children:[e&&(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold tracking-tight`,children:e}),t&&(0,V.jsx)(`p`,{className:`mt-0.5 text-muted-foreground`,children:t})]}),n&&(0,V.jsx)(`div`,{className:`flex flex-wrap items-center gap-2`,children:n})]}),(0,V.jsx)(`div`,{className:B(`min-w-0 flex-1 p-4`,i),children:a})]}),rT=({children:e})=>(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:e}),iT=({node:e,children:t,slots:n})=>{let{title:r,description:i}=eT(e);return(0,V.jsx)(nT,{title:r,description:i,actions:n.actions,className:`h-full`,children:(0,V.jsx)(`div`,{className:`flex flex-col gap-3`,children:t})})},aT=({model:e,filter:t,sort:n,limit:r=12,title:i,description:a,empty:o,actions:s,children:c})=>{let l=Yw(e,{filter:t,sort:n,pageSize:r}),u=l.data?.items??[];return(0,V.jsx)(nT,{title:i,description:a,actions:s,children:l.isPending?(0,V.jsx)(`div`,{className:`flex gap-3`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(Au,{className:`h-24 w-56`},t))}):l.error?(0,V.jsx)(pS,{title:`Could not load`,error:l.error}):u.length===0?(0,V.jsx)(rT,{children:o??`Nothing here yet.`}):(0,V.jsx)(`ul`,{className:`-mx-4 flex snap-x gap-3 overflow-x-auto px-4 pb-1`,children:u.map(t=>{let n=Gw(e,t);return(0,V.jsx)(`li`,{className:`flex w-60 shrink-0 snap-start flex-col gap-2 rounded-lg border border-border bg-surface p-3`,children:(0,V.jsx)(Nw,{value:n,children:c})},n.key)})})})},oT=({node:e,children:t,slots:n})=>{let{resource:r,...i}=eT(e),a=q().resources[r];return a?(0,V.jsx)(aT,{...i,model:a,actions:n.actions,children:t}):null},sT=(e,t,n,r=!0)=>{let i=G(),a=Ss(n)??``;return vh({queryKey:W.facets(e,t,a),enabled:r,queryFn:()=>i.facets(e,t,{filter:a,limit:50})})},cT=(e,t,n=!0)=>{let r=G(),i=Ss(t.filter)??``;return vh({queryKey:W.series(e,t.field,`${t.range??``}${t.from??``}${t.to??``}`,t.granularity??``,i),enabled:n,queryFn:()=>r.series(e,{...t,filter:i})})},lT=(e,t,n,r=20,i=!0)=>{let a=G(),o=Ss(n)??``;return vh({queryKey:W.histogram(e,t,r,o),enabled:i,queryFn:()=>a.histogram(e,t,{filter:o,buckets:r})})},uT=(e,t,n=!0)=>{let r=G(),i={...t,filter:Ss(t.filter)??``};return vh({queryKey:W.aggregate(e,JSON.stringify(i)),enabled:n,queryFn:()=>r.aggregate(e,i)})},dT=uo(),fT=e=>e>=0&&e<8?`var(--chart-${e+1})`:`var(--faint-foreground)`,pT=(e,t,n,r)=>{let i=String(n);return n===null?`var(--faint-foreground)`:t?.valueColors&&Object.hasOwn(t.valueColors,i)?t.valueColors[i]:e.type===`enum`?fT(e.enumValues?.indexOf(i)??-1):e.type===`boolean`?fT(+!n):fT(r)},mT=(e,t,n)=>n.value===null?`Not set`:e.type===`enum`?rs(String(n.value),t?.valueLabels):e.type===`boolean`?n.value?`Yes`:`No`:n.label??String(n.value),hT=(e,t,n=``)=>{let r=Ya(t===null?dT.isNull(e.name):dT.eq(e.name,t));return n.trim()?`(${n}) AND ${r}`:r},gT=(e,t)=>t.kind===`count`?e.count:e[t.kind]??null,_T=(e,t,n,r,i=``)=>e.map((e,a)=>({key:String(e.value),label:mT(t,n,e),value:gT(e,r),count:e.count,color:pT(t,n,e.value,a),filter:hT(t,e.value,i)})),vT=(e,t)=>e.map(e=>({at:Date.parse(`${String(e.value)}Z`),value:gT(e,t),count:e.count})),yT=(e,t)=>{if(e===null)return`—`;if(t.kind===`count`)return e.toLocaleString(`en-IE`);let n=t.hints?.decimals??(Number.isInteger(e)?0:2),r=e.toLocaleString(`en-IE`,{minimumFractionDigits:n,maximumFractionDigits:n});return`${t.hints?.prefix??``}${r}${t.hints?.suffix??``}`},bT=({resource:e,slices:t,measure:n})=>{let r=Math.max(0,...t.map(e=>e.value??0));return(0,V.jsx)(`ul`,{className:`flex flex-col gap-1`,children:t.map(t=>{let i=r>0&&t.value!==null?Math.max(0,t.value)/r:0;return(0,V.jsx)(`li`,{children:(0,V.jsxs)(FC,{to:{kind:`list`,resource:e,filter:t.filter},className:`group grid grid-cols-[minmax(6rem,35%)_1fr_auto] items-center gap-3 rounded-md px-1 py-1 hover:bg-muted`,title:n.kind===`count`?void 0:`${yT(t.count,{kind:`count`})} records`,children:[(0,V.jsx)(`span`,{className:`truncate group-hover:text-primary-text`,children:t.label}),(0,V.jsx)(`span`,{className:`h-3 rounded-r bg-muted`,"aria-hidden":!0,children:(0,V.jsx)(`span`,{className:`block h-full rounded-r`,style:{width:`${i*100}%`,background:`var(--chart-1)`}})}),(0,V.jsx)(`span`,{className:`text-right font-medium tabular-nums`,children:yT(t.value,n)})]})},t.key)})})};function xT(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`){if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(n=xT(e[t]))&&(r&&(r+=` `),r+=n)}else for(n in e)e[n]&&(r&&(r+=` `),r+=n)}return r}function ST(){for(var e,t,n=0,r=``,i=arguments.length;n<i;n++)(e=arguments[n])&&(t=xT(e))&&(r&&(r+=` `),r+=t);return r}var CT=`dangerouslySetInnerHTML.onCopy.onCopyCapture.onCut.onCutCapture.onPaste.onPasteCapture.onCompositionEnd.onCompositionEndCapture.onCompositionStart.onCompositionStartCapture.onCompositionUpdate.onCompositionUpdateCapture.onFocus.onFocusCapture.onBlur.onBlurCapture.onChange.onChangeCapture.onBeforeInput.onBeforeInputCapture.onInput.onInputCapture.onReset.onResetCapture.onSubmit.onSubmitCapture.onInvalid.onInvalidCapture.onLoad.onLoadCapture.onError.onErrorCapture.onKeyDown.onKeyDownCapture.onKeyPress.onKeyPressCapture.onKeyUp.onKeyUpCapture.onAbort.onAbortCapture.onCanPlay.onCanPlayCapture.onCanPlayThrough.onCanPlayThroughCapture.onDurationChange.onDurationChangeCapture.onEmptied.onEmptiedCapture.onEncrypted.onEncryptedCapture.onEnded.onEndedCapture.onLoadedData.onLoadedDataCapture.onLoadedMetadata.onLoadedMetadataCapture.onLoadStart.onLoadStartCapture.onPause.onPauseCapture.onPlay.onPlayCapture.onPlaying.onPlayingCapture.onProgress.onProgressCapture.onRateChange.onRateChangeCapture.onSeeked.onSeekedCapture.onSeeking.onSeekingCapture.onStalled.onStalledCapture.onSuspend.onSuspendCapture.onTimeUpdate.onTimeUpdateCapture.onVolumeChange.onVolumeChangeCapture.onWaiting.onWaitingCapture.onAuxClick.onAuxClickCapture.onClick.onClickCapture.onContextMenu.onContextMenuCapture.onDoubleClick.onDoubleClickCapture.onDrag.onDragCapture.onDragEnd.onDragEndCapture.onDragEnter.onDragEnterCapture.onDragExit.onDragExitCapture.onDragLeave.onDragLeaveCapture.onDragOver.onDragOverCapture.onDragStart.onDragStartCapture.onDrop.onDropCapture.onMouseDown.onMouseDownCapture.onMouseEnter.onMouseLeave.onMouseMove.onMouseMoveCapture.onMouseOut.onMouseOutCapture.onMouseOver.onMouseOverCapture.onMouseUp.onMouseUpCapture.onSelect.onSelectCapture.onTouchCancel.onTouchCancelCapture.onTouchEnd.onTouchEndCapture.onTouchMove.onTouchMoveCapture.onTouchStart.onTouchStartCapture.onPointerDown.onPointerDownCapture.onPointerMove.onPointerMoveCapture.onPointerUp.onPointerUpCapture.onPointerCancel.onPointerCancelCapture.onPointerEnter.onPointerEnterCapture.onPointerLeave.onPointerLeaveCapture.onPointerOver.onPointerOverCapture.onPointerOut.onPointerOutCapture.onGotPointerCapture.onGotPointerCaptureCapture.onLostPointerCapture.onLostPointerCaptureCapture.onScroll.onScrollCapture.onWheel.onWheelCapture.onAnimationStart.onAnimationStartCapture.onAnimationEnd.onAnimationEndCapture.onAnimationIteration.onAnimationIterationCapture.onTransitionEnd.onTransitionEndCapture`.split(`.`);function wT(e){return typeof e==`string`&&CT.includes(e)}var TT=new Set(`aria-activedescendant.aria-atomic.aria-autocomplete.aria-busy.aria-checked.aria-colcount.aria-colindex.aria-colspan.aria-controls.aria-current.aria-describedby.aria-details.aria-disabled.aria-errormessage.aria-expanded.aria-flowto.aria-haspopup.aria-hidden.aria-invalid.aria-keyshortcuts.aria-label.aria-labelledby.aria-level.aria-live.aria-modal.aria-multiline.aria-multiselectable.aria-orientation.aria-owns.aria-placeholder.aria-posinset.aria-pressed.aria-readonly.aria-relevant.aria-required.aria-roledescription.aria-rowcount.aria-rowindex.aria-rowspan.aria-selected.aria-setsize.aria-sort.aria-valuemax.aria-valuemin.aria-valuenow.aria-valuetext.className.color.height.id.lang.max.media.method.min.name.style.target.width.role.tabIndex.accentHeight.accumulate.additive.alignmentBaseline.allowReorder.alphabetic.amplitude.arabicForm.ascent.attributeName.attributeType.autoReverse.azimuth.baseFrequency.baselineShift.baseProfile.bbox.begin.bias.by.calcMode.capHeight.clip.clipPath.clipPathUnits.clipRule.colorInterpolation.colorInterpolationFilters.colorProfile.colorRendering.contentScriptType.contentStyleType.cursor.cx.cy.d.decelerate.descent.diffuseConstant.direction.display.divisor.dominantBaseline.dur.dx.dy.edgeMode.elevation.enableBackground.end.exponent.externalResourcesRequired.fill.fillOpacity.fillRule.filter.filterRes.filterUnits.floodColor.floodOpacity.focusable.fontFamily.fontSize.fontSizeAdjust.fontStretch.fontStyle.fontVariant.fontWeight.format.from.fx.fy.g1.g2.glyphName.glyphOrientationHorizontal.glyphOrientationVertical.glyphRef.gradientTransform.gradientUnits.hanging.horizAdvX.horizOriginX.href.ideographic.imageRendering.in2.in.intercept.k1.k2.k3.k4.k.kernelMatrix.kernelUnitLength.kerning.keyPoints.keySplines.keyTimes.lengthAdjust.letterSpacing.lightingColor.limitingConeAngle.local.markerEnd.markerHeight.markerMid.markerStart.markerUnits.markerWidth.mask.maskContentUnits.maskUnits.mathematical.mode.numOctaves.offset.opacity.operator.order.orient.orientation.origin.overflow.overlinePosition.overlineThickness.paintOrder.panose1.pathLength.patternContentUnits.patternTransform.patternUnits.pointerEvents.pointsAtX.pointsAtY.pointsAtZ.preserveAlpha.preserveAspectRatio.primitiveUnits.r.radius.refX.refY.renderingIntent.repeatCount.repeatDur.requiredExtensions.requiredFeatures.restart.result.rotate.rx.ry.seed.shapeRendering.slope.spacing.specularConstant.specularExponent.speed.spreadMethod.startOffset.stdDeviation.stemh.stemv.stitchTiles.stopColor.stopOpacity.strikethroughPosition.strikethroughThickness.string.stroke.strokeDasharray.strokeDashoffset.strokeLinecap.strokeLinejoin.strokeMiterlimit.strokeOpacity.strokeWidth.surfaceScale.systemLanguage.tableValues.targetX.targetY.textAnchor.textDecoration.textLength.textRendering.to.transform.u1.u2.underlinePosition.underlineThickness.unicode.unicodeBidi.unicodeRange.unitsPerEm.vAlphabetic.values.vectorEffect.version.vertAdvY.vertOriginX.vertOriginY.vHanging.vIdeographic.viewTarget.visibility.vMathematical.widths.wordSpacing.writingMode.x1.x2.x.xChannelSelector.xHeight.xlinkActuate.xlinkArcrole.xlinkHref.xlinkRole.xlinkShow.xlinkTitle.xlinkType.xmlBase.xmlLang.xmlns.xmlnsXlink.xmlSpace.y1.y2.y.yChannelSelector.z.zoomAndPan.ref.key.angle`.split(`.`));function ET(e){return typeof e==`string`&&TT.has(e)}function DT(e){return typeof e==`string`&&e.startsWith(`data-`)}function OT(e){if(typeof e!=`object`||!e)return{};var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(ET(n)||DT(n))&&(t[n]=e[n]);return t}function kT(e){if(e==null)return null;if((0,o.isValidElement)(e)&&typeof e.props==`object`&&e.props!==null){var t=e.props;return OT(t)}return typeof e==`object`&&!Array.isArray(e)?OT(e):null}function AT(e){var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(ET(n)||DT(n)||wT(n))&&(t[n]=e[n]);return t}function jT(e){return e==null?null:(0,o.isValidElement)(e)?AT(e.props):typeof e==`object`&&!Array.isArray(e)?AT(e):null}var MT=[`children`,`width`,`height`,`viewBox`,`className`,`style`,`title`,`desc`];function NT(){return NT=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},NT.apply(null,arguments)}function PT(e,t){if(e==null)return{};var n,r,i=FT(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function FT(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var IT=(0,o.forwardRef)((e,t)=>{var n=e.children,r=e.width,i=e.height,a=e.viewBox,s=e.className,c=e.style,l=e.title,u=e.desc,d=PT(e,MT),f=a||{width:r,height:i,x:0,y:0},p=ST(`recharts-surface`,s);return o.createElement(`svg`,NT({},AT(d),{className:p,width:r,height:i,style:c,viewBox:`${f.x} ${f.y} ${f.width} ${f.height}`,ref:t}),o.createElement(`title`,null,l),o.createElement(`desc`,null,u),n)}),LT=[`children`,`className`];function RT(){return RT=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},RT.apply(null,arguments)}function zT(e,t){if(e==null)return{};var n,r,i=BT(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function BT(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var VT=o.forwardRef((e,t)=>{var n=e.children,r=e.className,i=zT(e,LT),a=ST(`recharts-layer`,r);return o.createElement(`g`,RT({className:a},AT(i),{ref:t}),n)});function HT(e){return e===`__proto__`}var UT=/\.|(\[(?:[^[\]]*|(["'])(?:(?!\2)[^\\]|\\.)*?\2)\])/;function WT(e){switch(typeof e){case`number`:case`symbol`:return!1;case`string`:return e===``||e.startsWith(`.`)||e.endsWith(`.`)?!1:UT.test(e);default:return!1}}function GT(e){return typeof e==`string`||typeof e==`symbol`?e:Object.is(e?.valueOf?.(),-0)?`-0`:String(e)}function KT(e){return typeof e==`symbol`||e instanceof Symbol}function qT(e){return e==null?``:JT(e)}function JT(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(JT).join(`,`);if(KT(e))return e.toString();let t=e+``;return t===`0`&&Object.is(Number(e),-0)?`-0`:t}function YT(e){if(Array.isArray(e))return e.map(GT);if(typeof e==`symbol`)return[e];e=qT(e);let t=[],n=e.length;if(n===0)return t;let r=0,i=``,a=``,o=!1,s=!1,c=/^-?\d+(?:\.\d+)?$/;for(e.charCodeAt(0)===46&&t.push(``);r<n;){let l=e[r];if(a)l===`\\`&&r+1<n?(r++,i+=e[r]):l===a?a=``:i+=l;else if(o){if(l===`"`||l===`'`)a=l,s=!0;else if(l===`]`){if(o=!1,!s&&i.includes(`.`)&&!c.test(i)){let e=i.split(`.`);for(let n=0;n<e.length;n++)e[n]!==``&&t.push(e[n])}else t.push(i);i=``}else i+=l}else if(l===`[`)o=!0,s=!1,i&&=(t.push(i),``);else if(l===`.`){i&&=(t.push(i),``);let n=e[r+1];(n===void 0||n===`.`)&&t.push(``)}else i+=l;r++}return i&&t.push(i),t}function XT(e,t,n){if(e==null)return n;switch(typeof t){case`string`:{if(HT(t))return n;let r=e[t];return r===void 0?WT(t)&&!Object.hasOwn(e,t)?XT(e,YT(t),n):n:r}case`number`:case`symbol`:{typeof t==`number`&&(t=GT(t));let r=e[t];return r===void 0?n:r}default:{if(Array.isArray(t))return ZT(e,t,n);if(t=Object.is(t?.valueOf(),-0)?`-0`:String(t),HT(t))return n;let r=e[t];return r===void 0?n:r}}}function ZT(e,t,n){if(t.length===0)return n;let r=e;for(let e=0;e<t.length;e++){if(r==null||HT(t[e]))return n;r=r[t[e]]}return r===void 0?n:r}var QT=4;function $T(e){var t=10**(arguments.length>1&&arguments[1]!==void 0?arguments[1]:QT),n=Math.round(e*t)/t;return Object.is(n,-0)?0:n}function eE(e){var t=[...arguments].slice(1);return e.reduce((e,n,r)=>{var i=t[r-1];return typeof i==`string`?e+i+n:i===void 0?e+n:e+$T(i)+n},``)}var tE=e=>e===0?0:e>0?1:-1,nE=e=>typeof e==`number`&&e!=+e,rE=e=>typeof e==`string`&&e.length>1&&e.indexOf(`%`)===e.length-1,Y=e=>(typeof e==`number`||e instanceof Number)&&!nE(e),iE=e=>Y(e)||typeof e==`string`,aE=0,oE=e=>{var t=++aE;return`${e||``}${t}`},sE=function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,r=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(!Y(e)&&typeof e!=`string`)return n;var i;if(rE(e)){if(t==null)return n;var a=e.indexOf(`%`);i=t*parseFloat(e.slice(0,a))/100}else i=+e;return nE(i)&&(i=n),r&&t!=null&&i>t&&(i=t),i},cE=e=>{if(!Array.isArray(e))return!1;for(var t=e.length,n={},r=0;r<t;r++)if(!n[String(e[r])])n[String(e[r])]=!0;else return!0;return!1};function lE(e,t,n){return Y(e)&&Y(t)?$T(e+n*(t-e)):t}function uE(e,t,n){if(e&&e.length)return e.find(e=>e&&(typeof t==`function`?t(e):XT(e,t))===n)}var dE=e=>e==null,fE=e=>dE(e)?e:`${e.charAt(0).toUpperCase()}${e.slice(1)}`;function pE(e){return e!=null}function mE(){}function hE(e){if(e)return{x:e.x,y:e.y,upperWidth:`upperWidth`in e?e.upperWidth:e.width,lowerWidth:`lowerWidth`in e?e.lowerWidth:e.width,width:e.width,height:e.height}}function gE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function _E(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?gE(Object(n),!0).forEach(function(t){vE(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gE(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function vE(e,t,n){return(t=yE(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function yE(e){var t=bE(e,`string`);return typeof t==`symbol`?t:t+``}function bE(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var xE=e=>{var t=e.viewBox,n=e.position,r=e.offset,i=r===void 0?0:r,a=e.parentViewBox,o=e.clamp,s=hE(t),c=s.x,l=s.y,u=s.height,d=s.upperWidth,f=s.lowerWidth,p=c,m=c+(d-f)/2,h=(p+m)/2,g=(d+f)/2,_=p+d/2,v=u>=0?1:-1,y=v*i,b=v>0?`end`:`start`,x=v>0?`start`:`end`,S=d>=0?1:-1,C=S*i,w=S>0?`end`:`start`,T=S>0?`start`:`end`,E=a;if(n===`top`){var D={x:p+d/2,y:l-y,horizontalAnchor:`middle`,verticalAnchor:b};return o&&E&&(D.height=Math.max(l-E.y,0),D.width=d),D}if(n===`bottom`){var O={x:m+f/2,y:l+u+y,horizontalAnchor:`middle`,verticalAnchor:x};return o&&E&&(O.height=Math.max(E.y+E.height-(l+u),0),O.width=f),O}if(n===`left`){var k={x:h-C,y:l+u/2,horizontalAnchor:w,verticalAnchor:`middle`};return o&&E&&(k.width=Math.max(k.x-E.x,0),k.height=u),k}if(n===`right`){var A={x:h+g+C,y:l+u/2,horizontalAnchor:T,verticalAnchor:`middle`};return o&&E&&(A.width=Math.max(E.x+E.width-A.x,0),A.height=u),A}var j=o&&E?{width:g,height:u}:{};return n===`insideLeft`?_E({x:h+C,y:l+u/2,horizontalAnchor:T,verticalAnchor:`middle`},j):n===`insideRight`?_E({x:h+g-C,y:l+u/2,horizontalAnchor:w,verticalAnchor:`middle`},j):n===`insideTop`?_E({x:p+d/2,y:l+y,horizontalAnchor:`middle`,verticalAnchor:x},j):n===`insideBottom`?_E({x:m+f/2,y:l+u-y,horizontalAnchor:`middle`,verticalAnchor:b},j):n===`insideTopLeft`?_E({x:p+C,y:l+y,horizontalAnchor:T,verticalAnchor:x},j):n===`insideTopRight`?_E({x:p+d-C,y:l+y,horizontalAnchor:w,verticalAnchor:x},j):n===`insideBottomLeft`?_E({x:m+C,y:l+u-y,horizontalAnchor:T,verticalAnchor:b},j):n===`insideBottomRight`?_E({x:m+f-C,y:l+u-y,horizontalAnchor:w,verticalAnchor:b},j):n&&typeof n==`object`&&(Y(n.x)||rE(n.x))&&(Y(n.y)||rE(n.y))?_E({x:c+sE(n.x,g),y:l+sE(n.y,u),horizontalAnchor:`end`,verticalAnchor:`end`},j):_E({x:_,y:l+u/2,horizontalAnchor:`middle`,verticalAnchor:`middle`},j)},SE=[`top`,`left`,`right`,`bottom`];function CE(e){return e==null?!1:typeof e==`object`||SE.includes(e)}var wE=(0,o.createContext)(null);function TE(e){return function(){return e}}var EE=Math.PI,DE=2*EE,OE=1e-6,kE=DE-OE;function AE(e){this._+=e[0];for(let t=1,n=e.length;t<n;++t)this._+=arguments[t]+e[t]}function jE(e){let t=Math.floor(e);if(!(t>=0))throw Error(`invalid digits: ${e}`);if(t>15)return AE;let n=10**t;return function(e){this._+=e[0];for(let t=1,r=e.length;t<r;++t)this._+=Math.round(arguments[t]*n)/n+e[t]}}var ME=class{constructor(e){this._x0=this._y0=this._x1=this._y1=null,this._=``,this._append=e==null?AE:jE(e)}moveTo(e,t){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+t}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(e,t){this._append`L${this._x1=+e},${this._y1=+t}`}quadraticCurveTo(e,t,n,r){this._append`Q${+e},${+t},${this._x1=+n},${this._y1=+r}`}bezierCurveTo(e,t,n,r,i,a){this._append`C${+e},${+t},${+n},${+r},${this._x1=+i},${this._y1=+a}`}arcTo(e,t,n,r,i){if(e=+e,t=+t,n=+n,r=+r,i=+i,i<0)throw Error(`negative radius: ${i}`);let a=this._x1,o=this._y1,s=n-e,c=r-t,l=a-e,u=o-t,d=l*l+u*u;if(this._x1===null)this._append`M${this._x1=e},${this._y1=t}`;else if(d>OE){if(!(Math.abs(u*s-c*l)>OE)||!i)this._append`L${this._x1=e},${this._y1=t}`;else{let f=n-a,p=r-o,m=s*s+c*c,h=f*f+p*p,g=Math.sqrt(m),_=Math.sqrt(d),v=i*Math.tan((EE-Math.acos((m+d-h)/(2*g*_)))/2),y=v/_,b=v/g;Math.abs(y-1)>OE&&this._append`L${e+y*l},${t+y*u}`,this._append`A${i},${i},0,0,${+(u*f>l*p)},${this._x1=e+b*s},${this._y1=t+b*c}`}}}arc(e,t,n,r,i,a){if(e=+e,t=+t,n=+n,a=!!a,n<0)throw Error(`negative radius: ${n}`);let o=n*Math.cos(r),s=n*Math.sin(r),c=e+o,l=t+s,u=1^a,d=a?r-i:i-r;this._x1===null?this._append`M${c},${l}`:(Math.abs(this._x1-c)>OE||Math.abs(this._y1-l)>OE)&&this._append`L${c},${l}`,n&&(d<0&&(d=d%DE+DE),d>kE?this._append`A${n},${n},0,1,${u},${e-o},${t-s}A${n},${n},0,1,${u},${this._x1=c},${this._y1=l}`:d>OE&&this._append`A${n},${n},0,${+(d>=EE)},${u},${this._x1=e+n*Math.cos(i)},${this._y1=t+n*Math.sin(i)}`)}rect(e,t,n,r){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+t}h${n=+n}v${+r}h${-n}Z`}toString(){return this._}};ME.prototype;function NE(e){let t=3;return e.digits=function(n){if(!arguments.length)return t;if(n==null)t=null;else{let e=Math.floor(n);if(!(e>=0))throw RangeError(`invalid digits: ${n}`);t=e}return e},()=>new ME(t)}Array.prototype.slice;function PE(e){return typeof e==`object`&&`length`in e?e:Array.from(e)}function FE(e){this._context=e}FE.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t)}}};function IE(e){return new FE(e)}function LE(e){return e[0]}function RE(e){return e[1]}function zE(e,t){var n=TE(!0),r=null,i=IE,a=null,o=NE(s);e=typeof e==`function`?e:e===void 0?LE:TE(e),t=typeof t==`function`?t:t===void 0?RE:TE(t);function s(s){var c,l=(s=PE(s)).length,u,d=!1,f;for(r??(a=i(f=o())),c=0;c<=l;++c)!(c<l&&n(u=s[c],c,s))===d&&((d=!d)?a.lineStart():a.lineEnd()),d&&a.point(+e(u,c,s),+t(u,c,s));if(f)return a=null,f+``||null}return s.x=function(t){return arguments.length?(e=typeof t==`function`?t:TE(+t),s):e},s.y=function(e){return arguments.length?(t=typeof e==`function`?e:TE(+e),s):t},s.defined=function(e){return arguments.length?(n=typeof e==`function`?e:TE(!!e),s):n},s.curve=function(e){return arguments.length?(i=e,r!=null&&(a=i(r)),s):i},s.context=function(e){return arguments.length?(e==null?r=a=null:a=i(r=e),s):r},s}function BE(e,t,n){var r=null,i=TE(!0),a=null,o=IE,s=null,c=NE(l);e=typeof e==`function`?e:e===void 0?LE:TE(+e),t=typeof t==`function`?t:TE(t===void 0?0:+t),n=typeof n==`function`?n:n===void 0?RE:TE(+n);function l(l){var u,d,f,p=(l=PE(l)).length,m,h=!1,g,_=Array(p),v=Array(p);for(a??(s=o(g=c())),u=0;u<=p;++u){if(!(u<p&&i(m=l[u],u,l))===h){if(h=!h)d=u,s.areaStart(),s.lineStart();else{for(s.lineEnd(),s.lineStart(),f=u-1;f>=d;--f)s.point(_[f],v[f]);s.lineEnd(),s.areaEnd()}}h&&(_[u]=+e(m,u,l),v[u]=+t(m,u,l),s.point(r?+r(m,u,l):_[u],n?+n(m,u,l):v[u]))}if(g)return s=null,g+``||null}function u(){return zE().defined(i).curve(o).context(a)}return l.x=function(t){return arguments.length?(e=typeof t==`function`?t:TE(+t),r=null,l):e},l.x0=function(t){return arguments.length?(e=typeof t==`function`?t:TE(+t),l):e},l.x1=function(e){return arguments.length?(r=e==null?null:typeof e==`function`?e:TE(+e),l):r},l.y=function(e){return arguments.length?(t=typeof e==`function`?e:TE(+e),n=null,l):t},l.y0=function(e){return arguments.length?(t=typeof e==`function`?e:TE(+e),l):t},l.y1=function(e){return arguments.length?(n=e==null?null:typeof e==`function`?e:TE(+e),l):n},l.lineX0=l.lineY0=function(){return u().x(e).y(t)},l.lineY1=function(){return u().x(e).y(n)},l.lineX1=function(){return u().x(r).y(t)},l.defined=function(e){return arguments.length?(i=typeof e==`function`?e:TE(!!e),l):i},l.curve=function(e){return arguments.length?(o=e,a!=null&&(s=o(a)),l):o},l.context=function(e){return arguments.length?(e==null?a=s=null:s=o(a=e),l):a},l}var VE=class{constructor(e,t){this._context=e,this._x=t}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,t,e,t):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+t)/2,e,this._y0,e,t)}this._x0=e,this._y0=t}};function HE(e){return new VE(e,!0)}function UE(e){return new VE(e,!1)}function WE(){}function GE(e,t,n){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+n)/6)}function KE(e){this._context=e}KE.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:GE(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:GE(this,e,t)}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function qE(e){return new KE(e)}function JE(e){this._context=e}JE.prototype={areaStart:WE,areaEnd:WE,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:GE(this,e,t)}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function YE(e){return new JE(e)}function XE(e){this._context=e}XE.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+e)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:GE(this,e,t)}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function ZE(e){return new XE(e)}function QE(e){this._context=e}QE.prototype={areaStart:WE,areaEnd:WE,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function $E(e){return new QE(e)}function eD(e){return e<0?-1:1}function tD(e,t,n){var r=e._x1-e._x0,i=t-e._x1,a=(e._y1-e._y0)/(r||i<0&&-0),o=(n-e._y1)/(i||r<0&&-0),s=(a*i+o*r)/(r+i);return(eD(a)+eD(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(s))||0}function nD(e,t){var n=e._x1-e._x0;return n?(3*(e._y1-e._y0)/n-t)/2:t}function rD(e,t,n){var r=e._x0,i=e._y0,a=e._x1,o=e._y1,s=(a-r)/3;e._context.bezierCurveTo(r+s,i+s*t,a-s,o-s*n,a,o)}function iD(e){this._context=e}iD.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:rD(this,this._t0,nD(this,this._t0))}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var n=NaN;if(e=+e,t=+t,e!==this._x1||t!==this._y1){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,rD(this,nD(this,n=tD(this,e,t)),n);break;default:rD(this,this._t0,n=tD(this,e,t))}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=n}}};function aD(e){this._context=new oD(e)}(aD.prototype=Object.create(iD.prototype)).point=function(e,t){iD.prototype.point.call(this,t,e)};function oD(e){this._context=e}oD.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,n,r,i,a){this._context.bezierCurveTo(t,e,r,n,a,i)}};function sD(e){return new iD(e)}function cD(e){return new aD(e)}function lD(e){this._context=e}lD.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,n=e.length;if(n){if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),n===2)this._context.lineTo(e[1],t[1]);else for(var r=uD(e),i=uD(t),a=0,o=1;o<n;++a,++o)this._context.bezierCurveTo(r[0][a],i[0][a],r[1][a],i[1][a],e[o],t[o])}(this._line||this._line!==0&&n===1)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(e,t){this._x.push(+e),this._y.push(+t)}};function uD(e){var t,n=e.length-1,r,i=Array(n),a=Array(n),o=Array(n);for(i[0]=0,a[0]=2,o[0]=e[0]+2*e[1],t=1;t<n-1;++t)i[t]=1,a[t]=4,o[t]=4*e[t]+2*e[t+1];for(i[n-1]=2,a[n-1]=7,o[n-1]=8*e[n-1]+e[n],t=1;t<n;++t)r=i[t]/a[t-1],a[t]-=r,o[t]-=r*o[t-1];for(i[n-1]=o[n-1]/a[n-1],t=n-2;t>=0;--t)i[t]=(o[t]-i[t+1])/a[t];for(a[n-1]=(e[n]+i[n-1])/2,t=0;t<n-1;++t)a[t]=2*e[t+1]-i[t+1];return[i,a]}function dD(e){return new lD(e)}function fD(e,t){this._context=e,this._t=t}fD.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&this._point===2&&this._context.lineTo(this._x,this._y),(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var n=this._x*(1-this._t)+e*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}}this._x=e,this._y=t}};function pD(e){return new fD(e,.5)}function mD(e){return new fD(e,0)}function hD(e){return new fD(e,1)}function gD(e,t){if((o=e.length)>1)for(var n=1,r,i,a=e[t[0]],o,s=a.length;n<o;++n)for(i=a,a=e[t[n]],r=0;r<s;++r)a[r][1]+=a[r][0]=isNaN(i[r][1])?i[r][0]:i[r][1]}function _D(e){for(var t=e.length,n=Array(t);--t>=0;)n[t]=t;return n}function vD(e,t){return e[t]}function yD(e){let t=[];return t.key=e,t}function bD(){var e=TE([]),t=_D,n=gD,r=vD;function i(i){var a=Array.from(e.apply(this,arguments),yD),o,s=a.length,c=-1,l;for(let e of i)for(o=0,++c;o<s;++o)(a[o][c]=[0,+r(e,a[o].key,c,i)]).data=e;for(o=0,l=PE(t(a));o<s;++o)a[l[o]].index=o;return n(a,l),a}return i.keys=function(t){return arguments.length?(e=typeof t==`function`?t:TE(Array.from(t)),i):e},i.value=function(e){return arguments.length?(r=typeof e==`function`?e:TE(+e),i):r},i.order=function(e){return arguments.length?(t=e==null?_D:typeof e==`function`?e:TE(Array.from(e)),i):t},i.offset=function(e){return arguments.length?(n=e??gD,i):n},i}function xD(e,t){if((r=e.length)>0){for(var n,r,i=0,a=e[0].length,o;i<a;++i){for(o=n=0;n<r;++n)o+=e[n][i][1]||0;if(o)for(n=0;n<r;++n)e[n][i][1]/=o}gD(e,t)}}function SD(e,t){if((i=e.length)>0){for(var n=0,r=e[t[0]],i,a=r.length;n<a;++n){for(var o=0,s=0;o<i;++o)s+=e[o][n][1]||0;r[n][1]+=r[n][0]=-s/2}gD(e,t)}}function CD(e,t){if((o=e.length)>0&&(a=(i=e[t[0]]).length)>0){for(var n=0,r=1,i,a,o;r<a;++r){for(var s=0,c=0,l=0;s<o;++s){for(var u=e[t[s]],d=u[r][1]||0,f=(d-(u[r-1][1]||0))/2,p=0;p<s;++p){var m=e[t[p]],h=m[r][1]||0,g=m[r-1][1]||0;f+=h-g}c+=d,l+=f*d}i[r-1][1]+=i[r-1][0]=n,c&&(n-=l/c)}i[r-1][1]+=i[r-1][0]=n,gD(e,t)}}var wD=e=>`radius`in e&&`startAngle`in e&&`endAngle`in e,TD=(e,t)=>{if(!e||typeof e==`function`||typeof e==`boolean`)return null;var n=e;if((0,o.isValidElement)(e)&&(n=e.props),typeof n!=`object`&&typeof n!=`function`)return null;var r={};return Object.keys(n).forEach(e=>{wT(e)&&typeof n[e]==`function`&&(r[e]=t||(t=>n[e](n,t)))}),r},ED=(e,t,n)=>r=>(e(t,n,r),null),DD=(e,t,n)=>{if(e===null||typeof e!=`object`&&typeof e!=`function`)return null;var r=null;return Object.keys(e).forEach(i=>{var a=e[i];wT(i)&&typeof a==`function`&&(r||={},r[i]=ED(a,t,n))}),r};function OD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function kD(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?OD(Object(n),!0).forEach(function(t){AD(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):OD(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function AD(e,t,n){return(t=jD(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function jD(e){var t=MD(e,`string`);return typeof t==`symbol`?t:t+``}function MD(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ND(e,t){var n=kD({},e),r=t;return Object.keys(t).reduce((e,t)=>(e[t]===void 0&&r[t]!==void 0&&(e[t]=r[t]),e),n)}function PD(e,t){let n=new Map;for(let r=0;r<e.length;r++){let i=e[r],a=t(i,r,e);n.has(a)||n.set(a,i)}return Array.from(n.values())}function FD(e,t){return function(...n){return e.apply(this,n.slice(0,t))}}function ID(e){return e}function LD(e){return Number.isSafeInteger(e)&&e>=0}function RD(e){return e!=null&&typeof e!=`function`&&LD(e.length)}function zD(e){return function(t){return XT(t,e)}}function BD(e){return e==null||typeof e!=`object`&&typeof e!=`function`}function VD(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function HD(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function UD(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:Object.prototype.toString.call(e)}var WD=`[object RegExp]`,GD=`[object String]`,KD=`[object Number]`,qD=`[object Boolean]`,JD=`[object Arguments]`,YD=`[object Symbol]`,XD=`[object Date]`,ZD=`[object Map]`,QD=`[object Set]`,$D=`[object Array]`,eO=`[object Function]`,tO=`[object ArrayBuffer]`,nO=`[object Object]`,rO=`[object Error]`,iO=`[object DataView]`,aO=`[object Uint8Array]`,oO=`[object Uint8ClampedArray]`,sO=`[object Uint16Array]`,cO=`[object Uint32Array]`,mie=`[object BigUint64Array]`,lO=`[object Int8Array]`,uO=`[object Int16Array]`,dO=`[object Int32Array]`,hie=`[object BigInt64Array]`,fO=`[object Float32Array]`,pO=`[object Float64Array]`,mO=typeof globalThis==`object`&&globalThis||typeof window==`object`&&window||typeof self==`object`&&self||typeof global==`object`&&global||(function(){return this})();function hO(e){return mO.Buffer!==void 0&&mO.Buffer.isBuffer(e)}function gie(e,t){return gO(e,void 0,e,new Map,t)}function gO(e,t,n,r=new Map,i=void 0){let a=i?.(e,t,n,r);if(a!==void 0)return a;if(BD(e))return e;if(r.has(e))return r.get(e);if(Array.isArray(e)){let t=Array(e.length);r.set(e,t);for(let a=0;a<e.length;a++)t[a]=gO(e[a],a,n,r,i);return Object.hasOwn(e,`index`)&&(t.index=e.index),Object.hasOwn(e,`input`)&&(t.input=e.input),t}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){let t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,t}if(e instanceof Map){let t=new Map;r.set(e,t);for(let[a,o]of e)t.set(a,gO(o,a,n,r,i));return t}if(e instanceof Set){let t=new Set;r.set(e,t);for(let a of e)t.add(gO(a,void 0,n,r,i));return t}if(hO(e))return e.subarray();if(VD(e)){let t=new(Object.getPrototypeOf(e)).constructor(e.length);r.set(e,t);for(let a=0;a<e.length;a++)t[a]=gO(e[a],a,n,r,i);return t}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){let t=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return r.set(e,t),_O(t,e,n,r,i),t}if(typeof File<`u`&&e instanceof File){let t=new File([e],e.name,{type:e.type});return r.set(e,t),_O(t,e,n,r,i),t}if(typeof Blob<`u`&&e instanceof Blob){let t=new Blob([e],{type:e.type});return r.set(e,t),_O(t,e,n,r,i),t}if(e instanceof Error){let t=structuredClone(e);return r.set(e,t),t.message=e.message,t.name=e.name,t.stack=e.stack,t.cause=e.cause,t.constructor=e.constructor,_O(t,e,n,r,i),t}if(e instanceof Boolean){let t=new Boolean(e.valueOf());return r.set(e,t),_O(t,e,n,r,i),t}if(e instanceof Number){let t=new Number(e.valueOf());return r.set(e,t),_O(t,e,n,r,i),t}if(e instanceof String){let t=new String(e.valueOf());return r.set(e,t),_O(t,e,n,r,i),t}if(typeof e==`object`&&_ie(e)){let t=Object.create(Object.getPrototypeOf(e));return r.set(e,t),_O(t,e,n,r,i),t}return e}function _O(e,t,n=e,r,i){let a=[...Object.keys(t),...HD(t)];for(let o=0;o<a.length;o++){let s=a[o],c=Object.getOwnPropertyDescriptor(e,s);(c==null||c.writable)&&(e[s]=gO(t[s],s,n,r,i))}}function _ie(e){switch(UD(e)){case JD:case $D:case tO:case iO:case qD:case XD:case fO:case pO:case lO:case uO:case dO:case ZD:case KD:case nO:case WD:case QD:case GD:case YD:case aO:case oO:case sO:case cO:return!0;default:return!1}}function vie(e){return gO(e,void 0,e,new Map,void 0)}function vO(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function yO(e){return e!==null&&(typeof e==`object`||typeof e==`function`)}function bO(e,t,n){return typeof n==`function`?xO(e,t,function e(t,r,i,a,o,s){let c=n(t,r,i,a,o,s);return c===void 0?xO(t,r,e,s,!1):!!c},new Map,!0):bO(e,t,()=>void 0)}function xO(e,t,n,r,i=!1){if(t===e)return!0;switch(typeof t){case`object`:return yie(e,t,n,r,i);case`function`:return Object.keys(t).length>0?xO(e,{...t},n,r,i):vO(e,t);default:return yO(e)&&i?typeof t!=`string`||t===``:vO(e,t)}}function yie(e,t,n,r,i=!1){if(t==null)return!0;if(Array.isArray(t))return SO(e,t,n,r);if(t instanceof Map)return bie(e,t,n,r);if(t instanceof Set)return xie(e,t,n,r);let a=Object.keys(t);if(e==null)return i&&a.length===0;if(i)BD(e)&&(e=Object(e));else{let t=UD(e);if(t!==`[object Object]`&&t!==`[object Arguments]`)return!1}if(a.length===0)return!0;if(r?.has(t))return r.get(t)===e;r?.set(t,e);try{for(let i=0;i<a.length;i++){let o=a[i];if(!(o in e)||t[o]===void 0&&e[o]!==void 0||t[o]===null&&e[o]!==null||!n(e[o],t[o],o,e,t,r))return!1}return!0}finally{r?.delete(t)}}function bie(e,t,n,r){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[i,a]of t.entries())if(n(e.get(i),a,i,e,t,r)===!1)return!1;return!0}function SO(e,t,n,r){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let i=new Set;for(let a=0;a<t.length;a++){let o=t[a],s=!1;for(let c=0;c<e.length;c++){if(i.has(c))continue;let l=e[c],u=!1;if(n(l,o,a,e,t,r)&&(u=!0),u){i.add(c),s=!0;break}}if(!s)return!1}return!0}function xie(e,t,n,r){return t.size===0||e instanceof Set&&SO([...e],[...t],n,r)}function CO(e,t){return bO(e,t,()=>void 0)}function Sie(e){return e=vie(e),t=>CO(t,e)}function Cie(e,t){return gie(e,(n,r,i,a)=>{let o=t?.(n,r,i,a);if(o!==void 0)return o;if(typeof e==`object`){if(UD(e)===`[object Object]`&&typeof e.constructor!=`function`){let t={};return a.set(e,t),_O(t,e,i,a),t}switch(Object.prototype.toString.call(e)){case KD:case GD:case qD:{let t=new e.constructor(e?.valueOf());return _O(t,e),t}case JD:{let t={};return _O(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}})}function wie(e){return Cie(e)}var Tie=/^(?:0|[1-9]\d*)$/;function wO(e,t=2**53-1){switch(typeof e){case`number`:return Number.isInteger(e)&&e>=0&&e<t;case`symbol`:return!1;case`string`:return Tie.test(e)}}function Eie(e){return typeof e==`object`&&!!e&&UD(e)===`[object Arguments]`}function Die(e,t){let n;if(n=Array.isArray(t)?t:typeof t==`string`&&WT(t)&&!(t in Object(e))?YT(t):[t],n.length===0)return!1;let r=e;for(let e=0;e<n.length;e++){let t=GT(n[e]);if((r==null||!Object.hasOwn(r,t))&&!((Array.isArray(r)||Eie(r))&&wO(t)&&Number(t)<r.length))return!1;r=r[t]}return!0}function Oie(e,t){switch(typeof e){case`object`:Object.is(e?.valueOf(),-0)&&(e=`-0`);break;case`number`:e=GT(e)}return t=wie(t),function(n){let r=XT(n,e);return r===void 0?Die(n,e):t===void 0?r===void 0:CO(r,t)}}function kie(e){if(e==null)return ID;switch(typeof e){case`function`:return e;case`object`:return Array.isArray(e)&&e.length===2?Oie(e[0],e[1]):Sie(e);default:return zD(e)}}function Aie(e){return e===0?0:e}function TO(e,t=ID){return RD(e)?PD(Array.from(e),FD(kie(t),1)).map(Aie):[]}function jie(e,t,n){return t===!0?TO(e,n):typeof t==`function`?TO(e,t):e}var Mie=n((e=>{var t=r();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:n,a=t.useState,o=t.useEffect,s=t.useLayoutEffect,c=t.useDebugValue;function l(e,t){var n=t(),r=a({inst:{value:n,getSnapshot:t}}),i=r[0].inst,l=r[1];return s(function(){i.value=n,i.getSnapshot=t,u(i)&&l({inst:i})},[e,n,t]),o(function(){return u(i)&&l({inst:i}),e(function(){u(i)&&l({inst:i})})},[e]),c(n),n}function u(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!i(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:l;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),Nie=n(((e,t)=>{t.exports=Mie()})),Pie=n((e=>{var t=r(),n=Nie();function i(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var a=typeof Object.is==`function`?Object.is:i,o=n.useSyncExternalStore,s=t.useRef,c=t.useEffect,l=t.useMemo,u=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var d=s(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=l(function(){function e(e){if(!o){if(o=!0,s=e,e=r(e),i!==void 0&&f.hasValue){var t=f.value;if(i(t,e))return c=t}return c=e}if(t=c,a(s,e))return t;var n=r(e);return i!==void 0&&i(t,n)?(s=e,t):(s=e,c=n)}var o=!1,s,c,l=n===void 0?null:n;return[function(){return e(t())},l===null?void 0:function(){return e(l())}]},[t,n,r,i]);var p=o(e,d[0],d[1]);return c(function(){f.hasValue=!0,f.value=p},[p]),u(p),p}})),EO=n(((e,t)=>{t.exports=Pie()}))(),DO=(0,o.createContext)(null),Fie=e=>e,OO=()=>{var e=(0,o.useContext)(DO);return e?e.store.dispatch:Fie},kO=()=>{},Iie=()=>kO,Lie=(e,t)=>e===t;function X(e){var t=(0,o.useContext)(DO),n=(0,o.useMemo)(()=>t?t=>{if(t!=null)return e(t)}:kO,[t,e]);return(0,EO.useSyncExternalStoreWithSelector)(t?t.subscription.addNestedSub:Iie,t?t.store.getState:kO,t?t.store.getState:kO,n,Lie)}function Rie(e,t=`expected a function, instead received ${typeof e}`){if(typeof e!=`function`)throw TypeError(t)}function zie(e,t=`expected all items to be functions, instead received the following types: `){if(!e.every(e=>typeof e==`function`)){let n=e.map(e=>typeof e==`function`?`function ${e.name||`unnamed`}()`:typeof e).join(`, `);throw TypeError(`${t}[${n}]`)}}var AO=e=>Array.isArray(e)?e:[e];function Bie(e){let t=Array.isArray(e[0])?e[0]:e;return zie(t,`createSelector expects all input-selectors to be functions, but received the following types: `),t}function Vie(e,t){let n=[],{length:r}=e;for(let i=0;i<r;i++)n.push(e[i].apply(null,t));return n}var Hie=class{constructor(e){this.value=e}deref(){return this.value}},jO=typeof WeakRef>`u`?Hie:WeakRef,Uie=0,MO=1;function NO(){return{s:Uie,v:void 0,o:null,p:null}}function Wie(e){return e instanceof jO?e.deref():e}function PO(e,t={}){let n=NO(),{resultEqualityCheck:r}=t,i,a=0;function o(){let t=n,{length:o}=arguments;for(let e=0,n=o;e<n;e++){let n=arguments[e];if(typeof n==`function`||typeof n==`object`&&n){let e=t.o;e===null&&(t.o=e=new WeakMap);let r=e.get(n);r===void 0?(t=NO(),e.set(n,t)):t=r}else{let e=t.p;e===null&&(t.p=e=new Map);let r=e.get(n);r===void 0?(t=NO(),e.set(n,t)):t=r}}let s=t,c;if(t.s===MO)c=t.v;else if(c=e.apply(null,arguments),a++,r){let e=Wie(i);e!=null&&r(e,c)&&(c=e,a!==0&&a--),i=typeof c==`object`&&c||typeof c==`function`?new jO(c):c}return s.s=MO,s.v=c,c}return o.clearCache=()=>{n=NO(),o.resetResultsCount()},o.resultsCount=()=>a,o.resetResultsCount=()=>{a=0},o}function Gie(e,...t){let n=typeof e==`function`?{memoize:e,memoizeOptions:t}:e,r=(...e)=>{let t=0,r=0,i,a={},o=e.pop();typeof o==`object`&&(a=o,o=e.pop()),Rie(o,`createSelector expects an output function after the inputs, but received: [${typeof o}]`);let{memoize:s,memoizeOptions:c=[],argsMemoize:l=PO,argsMemoizeOptions:u=[]}={...n,...a},d=AO(c),f=AO(u),p=Bie(e),m=s(function(){return t++,o.apply(null,arguments)},...d),h=l(function(){r++;let e=Vie(p,arguments);return i=m.apply(null,e),i},...f);return Object.assign(h,{resultFunc:o,memoizedResultFunc:m,dependencies:p,dependencyRecomputations:()=>r,resetDependencyRecomputations:()=>{r=0},lastResult:()=>i,recomputations:()=>t,resetRecomputations:()=>{t=0},memoize:s,argsMemoize:l})};return Object.assign(r,{withTypes:()=>r}),r}var Z=Gie(PO);function Kie(e,t=1){let n=[],r=Math.floor(t),i=(e,t)=>{for(let a=0;a<e.length;a++){let o=e[a];Array.isArray(o)&&t<r?i(o,t+1):n.push(o)}};return i(e,0),n}function FO(e,t,n){return yO(n)&&(typeof t==`number`&&RD(n)&&wO(t)&&t<n.length||typeof t==`string`&&t in n)?vO(n[t],e):!1}function IO(e){return typeof e==`symbol`?1:e===null?2:e===void 0?3:e===e?0:4}var qie=(e,t,n)=>{if(e!==t){let r=IO(e),i=IO(t);if(r===i&&r===0){if(e<t)return n===`desc`?1:-1;if(e>t)return n===`desc`?-1:1}return n===`desc`?i-r:r-i}return 0},Jie=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Yie=/^\w*$/;function Xie(e,t){return Array.isArray(e)?!1:typeof e==`number`||typeof e==`boolean`||e==null||KT(e)?!0:typeof e==`string`&&(Yie.test(e)||!Jie.test(e))||t!=null&&Object.hasOwn(t,e)}function Zie(e,t,n,r){if(e==null)return[];n=r?void 0:n,Array.isArray(e)||(e=RD(e)?Array.from(e):Object.values(e)),Array.isArray(t)||(t=t==null?[null]:[t]),t.length===0&&(t=[null]),Array.isArray(n)||(n=n==null?[]:[n]),n=n.map(e=>String(e));let i=(e,t)=>{let n=e,r=0;for(;r<t.length&&n!=null;++r)n=n[t[r]];return r>0&&r===t.length?n:void 0},a=(e,t)=>{if(e==null)return t;if(t!=null)return typeof e==`object`&&`key`in e?Object.hasOwn(t,e.key)?t[e.key]:i(t,e.path):typeof e==`function`?e(t):Array.isArray(e)?i(t,e):t[e]},o=t.map(e=>(Array.isArray(e)&&e.length===1&&(e=e[0]),e==null||typeof e==`function`||Array.isArray(e)||Xie(e)?e:{key:e,path:YT(e)}));return e.map(e=>({original:e,criteria:o.map(t=>a(t,e))})).slice().sort((e,t)=>{for(let r=0;r<o.length;r++){let i=qie(e.criteria[r],t.criteria[r],n[r]);if(i!==0)return i}return 0}).map(e=>e.original)}function LO(e,...t){let n=t.length;return n>1&&FO(e,t[0],t[1])?t=[]:n>2&&FO(t[0],t[1],t[2])&&(t=[t[0]]),Zie(e,Kie(t),[`asc`])}var RO=e=>e.legend.settings,Qie=e=>e.legend.size;Z([e=>e.legend.payload,RO],(e,t)=>{var n=t.itemSorter,r=e.flat(1);return n?LO(r,n):r});function $ie(e,t){return rae(e)||nae(e,t)||tae(e,t)||eae()}function eae(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
12
|
+
`},Z_={onDragStart(e){let{active:t}=e;return`Picked up draggable item `+t.id+`.`},onDragOver(e){let{active:t,over:n}=e;return n?`Draggable item `+t.id+` was moved over droppable area `+n.id+`.`:`Draggable item `+t.id+` is no longer over a droppable area.`},onDragEnd(e){let{active:t,over:n}=e;return n?`Draggable item `+t.id+` was dropped over droppable area `+n.id:`Draggable item `+t.id+` was dropped.`},onDragCancel(e){let{active:t}=e;return`Dragging was cancelled. Draggable item `+t.id+` was dropped.`}};function Q_(e){let{announcements:t=Z_,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=X_}=e,{announce:a,announcement:s}=K_(),c=M_(`DndLiveRegion`),[l,u]=(0,o.useState)(!1);if((0,o.useEffect)(()=>{u(!0)},[]),J_((0,o.useMemo)(()=>({onDragStart(e){let{active:n}=e;a(t.onDragStart({active:n}))},onDragMove(e){let{active:n,over:r}=e;t.onDragMove&&a(t.onDragMove({active:n,over:r}))},onDragOver(e){let{active:n,over:r}=e;a(t.onDragOver({active:n,over:r}))},onDragEnd(e){let{active:n,over:r}=e;a(t.onDragEnd({active:n,over:r}))},onDragCancel(e){let{active:n,over:r}=e;a(t.onDragCancel({active:n,over:r}))}}),[a,t])),!l)return null;let d=o.createElement(o.Fragment,null,o.createElement(W_,{id:r,value:i.draggable}),o.createElement(G_,{id:c,announcement:s}));return n?(0,tr.createPortal)(d,n):d}var $_;(function(e){e.DragStart=`dragStart`,e.DragMove=`dragMove`,e.DragEnd=`dragEnd`,e.DragCancel=`dragCancel`,e.DragOver=`dragOver`,e.RegisterDroppable=`registerDroppable`,e.SetDroppableDisabled=`setDroppableDisabled`,e.UnregisterDroppable=`unregisterDroppable`})($_||={});function ev(){}function tv(e,t){return(0,o.useMemo)(()=>({sensor:e,options:t??{}}),[e,t])}function nv(){var e=[...arguments];return(0,o.useMemo)(()=>[...e].filter(e=>e!=null),[...e])}var rv=Object.freeze({x:0,y:0});function iv(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function av(e,t){let n=z_(e);if(!n)return`0 0`;let r={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return r.x+`% `+r.y+`%`}function ov(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return n-r}function sv(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function cv(e){let{left:t,top:n,height:r,width:i}=e;return[{x:t,y:n},{x:t+i,y:n},{x:t,y:n+r},{x:t+i,y:n+r}]}function lv(e,t){if(!e||e.length===0)return null;let[n]=e;return t?n[t]:n}function uv(e,t,n){return t===void 0&&(t=e.left),n===void 0&&(n=e.top),{x:t+e.width*.5,y:n+e.height*.5}}var dv=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e,i=uv(t,t.left,t.top),a=[];for(let e of r){let{id:t}=e,r=n.get(t);if(r){let n=iv(uv(r),i);a.push({id:t,data:{droppableContainer:e,value:n}})}}return a.sort(ov)},fv=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e,i=cv(t),a=[];for(let e of r){let{id:t}=e,r=n.get(t);if(r){let n=cv(r),o=i.reduce((e,t,r)=>e+iv(n[r],t),0),s=Number((o/4).toFixed(4));a.push({id:t,data:{droppableContainer:e,value:s}})}}return a.sort(ov)};function pv(e,t){let n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),i=Math.min(t.left+t.width,e.left+e.width),a=Math.min(t.top+t.height,e.top+e.height),o=i-r,s=a-n;if(r<i&&n<a){let n=t.width*t.height,r=e.width*e.height,i=o*s,a=i/(n+r-i);return Number(a.toFixed(4))}return 0}var mv=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e,i=[];for(let e of r){let{id:r}=e,a=n.get(r);if(a){let n=pv(a,t);n>0&&i.push({id:r,data:{droppableContainer:e,value:n}})}}return i.sort(sv)};function hv(e,t){let{top:n,left:r,bottom:i,right:a}=t;return n<=e.y&&e.y<=i&&r<=e.x&&e.x<=a}var gv=e=>{let{droppableContainers:t,droppableRects:n,pointerCoordinates:r}=e;if(!r)return[];let i=[];for(let e of t){let{id:t}=e,a=n.get(t);if(a&&hv(r,a)){let n=cv(a).reduce((e,t)=>e+iv(r,t),0),o=Number((n/4).toFixed(4));i.push({id:t,data:{droppableContainer:e,value:o}})}}return i.sort(ov)};function _v(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function vv(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:rv}function yv(e){return function(t){return[...arguments].slice(1).reduce((t,n)=>({...t,top:t.top+e*n.y,bottom:t.bottom+e*n.y,left:t.left+e*n.x,right:t.right+e*n.x}),{...t})}}var bv=yv(1);function xv(e){if(e.startsWith(`matrix3d(`)){let t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}if(e.startsWith(`matrix(`)){let t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function Sv(e,t,n){let r=xv(t);if(!r)return e;let{scaleX:i,scaleY:a,x:o,y:s}=r,c=e.left-o-(1-i)*parseFloat(n),l=e.top-s-(1-a)*parseFloat(n.slice(n.indexOf(` `)+1)),u=i?e.width/i:e.width,d=a?e.height/a:e.height;return{width:u,height:d,top:l,right:c+u,bottom:l+d,left:c}}var Cv={ignoreTransform:!1};function wv(e,t){t===void 0&&(t=Cv);let n=e.getBoundingClientRect();if(t.ignoreTransform){let{transform:t,transformOrigin:r}=y_(e).getComputedStyle(e);t&&(n=Sv(n,t,r))}let{top:r,left:i,width:a,height:o,bottom:s,right:c}=n;return{top:r,left:i,width:a,height:o,bottom:s,right:c}}function Tv(e){return wv(e,{ignoreTransform:!0})}function Ev(e){let t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function Dv(e,t){return t===void 0&&(t=y_(e).getComputedStyle(e)),t.position===`fixed`}function Ov(e,t){t===void 0&&(t=y_(e).getComputedStyle(e));let n=/(auto|scroll|overlay)/;return[`overflow`,`overflowX`,`overflowY`].some(e=>{let r=t[e];return typeof r==`string`&&n.test(r)})}function kv(e,t){let n=[];function r(i){if(t!=null&&n.length>=t||!i)return n;if(b_(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!x_(i)||S_(i)||n.includes(i))return n;let a=y_(e).getComputedStyle(i);return i!==e&&Ov(i,a)&&n.push(i),Dv(i,a)?n:r(i.parentNode)}return e?r(e):n}function Av(e){let[t]=kv(e,1);return t??null}function jv(e){return!g_||!e?null:__(e)?e:v_(e)?b_(e)||e===C_(e).scrollingElement?window:x_(e)?e:null:null}function Mv(e){return __(e)?e.scrollX:e.scrollLeft}function Nv(e){return __(e)?e.scrollY:e.scrollTop}function Pv(e){return{x:Mv(e),y:Nv(e)}}var Fv;(function(e){e[e.Forward=1]=`Forward`,e[e.Backward=-1]=`Backward`})(Fv||={});function Iv(e){return!g_||!e?!1:e===document.scrollingElement}function Lv(e){let t={x:0,y:0},n=Iv(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height};return{isTop:e.scrollTop<=t.y,isLeft:e.scrollLeft<=t.x,isBottom:e.scrollTop>=r.y,isRight:e.scrollLeft>=r.x,maxScroll:r,minScroll:t}}var Rv={x:.2,y:.2};function zv(e,t,n,r,i){let{top:a,left:o,right:s,bottom:c}=n;r===void 0&&(r=10),i===void 0&&(i=Rv);let{isTop:l,isBottom:u,isLeft:d,isRight:f}=Lv(e),p={x:0,y:0},m={x:0,y:0},h={height:t.height*i.y,width:t.width*i.x};return!l&&a<=t.top+h.height?(p.y=Fv.Backward,m.y=r*Math.abs((t.top+h.height-a)/h.height)):!u&&c>=t.bottom-h.height&&(p.y=Fv.Forward,m.y=r*Math.abs((t.bottom-h.height-c)/h.height)),!f&&s>=t.right-h.width?(p.x=Fv.Forward,m.x=r*Math.abs((t.right-h.width-s)/h.width)):!d&&o<=t.left+h.width&&(p.x=Fv.Backward,m.x=r*Math.abs((t.left+h.width-o)/h.width)),{direction:p,speed:m}}function Bv(e){if(e===document.scrollingElement){let{innerWidth:e,innerHeight:t}=window;return{top:0,left:0,right:e,bottom:t,width:e,height:t}}let{top:t,left:n,right:r,bottom:i}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:i,width:e.clientWidth,height:e.clientHeight}}function Vv(e){return e.reduce((e,t)=>P_(e,Pv(t)),rv)}function Hv(e){return e.reduce((e,t)=>e+Mv(t),0)}function Uv(e){return e.reduce((e,t)=>e+Nv(t),0)}function Wv(e,t){if(t===void 0&&(t=wv),!e)return;let{top:n,left:r,bottom:i,right:a}=t(e);Av(e)&&(i<=0||a<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:`center`,inline:`center`})}var Gv=[[`x`,[`left`,`right`],Hv],[`y`,[`top`,`bottom`],Uv]],Kv=class{constructor(e,t){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;let n=kv(t),r=Vv(n);this.rect={...e},this.width=e.width,this.height=e.height;for(let[e,t,i]of Gv)for(let a of t)Object.defineProperty(this,a,{get:()=>{let t=i(n),o=r[e]-t;return this.rect[a]+o},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}},qv=class{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(e=>this.target?.removeEventListener(...e))},this.target=e}add(e,t,n){var r;(r=this.target)==null||r.addEventListener(e,t,n),this.listeners.push([e,t,n])}};function Jv(e){let{EventTarget:t}=y_(e);return e instanceof t?e:C_(e)}function Yv(e,t){let n=Math.abs(e.x),r=Math.abs(e.y);return typeof t==`number`?Math.sqrt(n**2+r**2)>t:`x`in t&&`y`in t?n>t.x&&r>t.y:`x`in t?n>t.x:`y`in t&&r>t.y}var Xv;(function(e){e.Click=`click`,e.DragStart=`dragstart`,e.Keydown=`keydown`,e.ContextMenu=`contextmenu`,e.Resize=`resize`,e.SelectionChange=`selectionchange`,e.VisibilityChange=`visibilitychange`})(Xv||={});function Zv(e){e.preventDefault()}function Qv(e){e.stopPropagation()}var $v;(function(e){e.Space=`Space`,e.Down=`ArrowDown`,e.Right=`ArrowRight`,e.Left=`ArrowLeft`,e.Up=`ArrowUp`,e.Esc=`Escape`,e.Enter=`Enter`,e.Tab=`Tab`})($v||={});var ey={start:[$v.Space,$v.Enter],cancel:[$v.Esc],end:[$v.Space,$v.Enter,$v.Tab]},ty=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case $v.Right:return{...n,x:n.x+25};case $v.Left:return{...n,x:n.x-25};case $v.Down:return{...n,y:n.y+25};case $v.Up:return{...n,y:n.y-25}}},ny=class{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;let{event:{target:t}}=e;this.props=e,this.listeners=new qv(C_(t)),this.windowListeners=new qv(y_(t)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Xv.Resize,this.handleCancel),this.windowListeners.add(Xv.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Xv.Keydown,this.handleKeyDown))}handleStart(){let{activeNode:e,onStart:t}=this.props,n=e.node.current;n&&Wv(n),t(rv)}handleKeyDown(e){if(L_(e)){let{active:t,context:n,options:r}=this.props,{keyboardCodes:i=ey,coordinateGetter:a=ty,scrollBehavior:o=`smooth`}=r,{code:s}=e;if(i.end.includes(s)){this.handleEnd(e);return}if(i.cancel.includes(s)){this.handleCancel(e);return}let{collisionRect:c}=n.current,l=c?{x:c.left,y:c.top}:rv;this.referenceCoordinates||=l;let u=a(e,{active:t,context:n.current,currentCoordinates:l});if(u){let t=F_(u,l),r={x:0,y:0},{scrollableAncestors:i}=n.current;for(let n of i){let i=e.code,{isTop:a,isRight:s,isLeft:c,isBottom:l,maxScroll:d,minScroll:f}=Lv(n),p=Bv(n),m={x:Math.min(i===$v.Right?p.right-p.width/2:p.right,Math.max(i===$v.Right?p.left:p.left+p.width/2,u.x)),y:Math.min(i===$v.Down?p.bottom-p.height/2:p.bottom,Math.max(i===$v.Down?p.top:p.top+p.height/2,u.y))},h=i===$v.Right&&!s||i===$v.Left&&!c,g=i===$v.Down&&!l||i===$v.Up&&!a;if(h&&m.x!==u.x){let e=n.scrollLeft+t.x,a=i===$v.Right&&e<=d.x||i===$v.Left&&e>=f.x;if(a&&!t.y){n.scrollTo({left:e,behavior:o});return}r.x=a?n.scrollLeft-e:i===$v.Right?n.scrollLeft-d.x:n.scrollLeft-f.x,r.x&&n.scrollBy({left:-r.x,behavior:o});break}if(g&&m.y!==u.y){let e=n.scrollTop+t.y,a=i===$v.Down&&e<=d.y||i===$v.Up&&e>=f.y;if(a&&!t.x){n.scrollTo({top:e,behavior:o});return}r.y=a?n.scrollTop-e:i===$v.Down?n.scrollTop-d.y:n.scrollTop-f.y,r.y&&n.scrollBy({top:-r.y,behavior:o});break}}this.handleMove(e,P_(F_(u,this.referenceCoordinates),r))}}}handleMove(e,t){let{onMove:n}=this.props;e.preventDefault(),n(t)}handleEnd(e){let{onEnd:t}=this.props;e.preventDefault(),this.detach(),t()}handleCancel(e){let{onCancel:t}=this.props;e.preventDefault(),this.detach(),t()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}};ny.activators=[{eventName:`onKeyDown`,handler:(e,t,n)=>{let{keyboardCodes:r=ey,onActivation:i}=t,{active:a}=n,{code:o}=e.nativeEvent;if(r.start.includes(o)){let t=a.activatorNode.current;return t&&e.target!==t?!1:(e.preventDefault(),i?.({event:e.nativeEvent}),!0)}return!1}}];function ry(e){return!!(e&&`distance`in e)}function iy(e){return!!(e&&`delay`in e)}var ay=class{constructor(e,t,n){n===void 0&&(n=Jv(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=t;let{event:r}=e,{target:i}=r;this.props=e,this.events=t,this.document=C_(i),this.documentListeners=new qv(this.document),this.listeners=new qv(n),this.windowListeners=new qv(y_(i)),this.initialCoordinates=z_(r)??rv,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){let{events:e,props:{options:{activationConstraint:t,bypassActivationConstraint:n}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(Xv.Resize,this.handleCancel),this.windowListeners.add(Xv.DragStart,Zv),this.windowListeners.add(Xv.VisibilityChange,this.handleCancel),this.windowListeners.add(Xv.ContextMenu,Zv),this.documentListeners.add(Xv.Keydown,this.handleKeydown),t){if(n!=null&&n({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(iy(t)){this.timeoutId=setTimeout(this.handleStart,t.delay),this.handlePending(t);return}if(ry(t)){this.handlePending(t);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,t){let{active:n,onPending:r}=this.props;r(n,e,this.initialCoordinates,t)}handleStart(){let{initialCoordinates:e}=this,{onStart:t}=this.props;e&&(this.activated=!0,this.documentListeners.add(Xv.Click,Qv,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Xv.SelectionChange,this.removeTextSelection),t(e))}handleMove(e){let{activated:t,initialCoordinates:n,props:r}=this,{onMove:i,options:{activationConstraint:a}}=r;if(!n)return;let o=z_(e)??rv,s=F_(n,o);if(!t&&a){if(ry(a)){if(a.tolerance!=null&&Yv(s,a.tolerance))return this.handleCancel();if(Yv(s,a.distance))return this.handleStart()}if(iy(a)&&Yv(s,a.tolerance))return this.handleCancel();this.handlePending(a,s);return}e.cancelable&&e.preventDefault(),i(o)}handleEnd(){let{onAbort:e,onEnd:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleCancel(){let{onAbort:e,onCancel:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleKeydown(e){e.code===$v.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}},oy={cancel:{name:`pointercancel`},move:{name:`pointermove`},end:{name:`pointerup`}},sy=class extends ay{constructor(e){let{event:t}=e,n=C_(t.target);super(e,oy,n)}};sy.activators=[{eventName:`onPointerDown`,handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];var cy={move:{name:`mousemove`},end:{name:`mouseup`}},ly;(function(e){e[e.RightClick=2]=`RightClick`})(ly||={});var uy=class extends ay{constructor(e){super(e,cy,C_(e.event.target))}};uy.activators=[{eventName:`onMouseDown`,handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button!==ly.RightClick&&(r?.({event:n}),!0)}}];var dy={cancel:{name:`touchcancel`},move:{name:`touchmove`},end:{name:`touchend`}},fy=class extends ay{constructor(e){super(e,dy)}static setup(){return window.addEventListener(dy.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(dy.move.name,e)};function e(){}}};fy.activators=[{eventName:`onTouchStart`,handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t,{touches:i}=n;return i.length>1?!1:(r?.({event:n}),!0)}}];var py;(function(e){e[e.Pointer=0]=`Pointer`,e[e.DraggableRect=1]=`DraggableRect`})(py||={});var my;(function(e){e[e.TreeOrder=0]=`TreeOrder`,e[e.ReversedTreeOrder=1]=`ReversedTreeOrder`})(my||={});function hy(e){let{acceleration:t,activator:n=py.Pointer,canScroll:r,draggingRect:i,enabled:a,interval:s=5,order:c=my.TreeOrder,pointerCoordinates:l,scrollableAncestors:u,scrollableAncestorRects:d,delta:f,threshold:p}=e,m=_y({delta:f,disabled:!a}),[h,g]=E_(),_=(0,o.useRef)({x:0,y:0}),v=(0,o.useRef)({x:0,y:0}),y=(0,o.useMemo)(()=>{switch(n){case py.Pointer:return l?{top:l.y,bottom:l.y,left:l.x,right:l.x}:null;case py.DraggableRect:return i}},[n,i,l]),b=(0,o.useRef)(null),x=(0,o.useCallback)(()=>{let e=b.current;if(!e)return;let t=_.current.x*v.current.x,n=_.current.y*v.current.y;e.scrollBy(t,n)},[]),S=(0,o.useMemo)(()=>c===my.TreeOrder?[...u].reverse():u,[c,u]);(0,o.useEffect)(()=>{if(!a||!u.length||!y){g();return}for(let e of S){if(r?.(e)===!1)continue;let n=u.indexOf(e),i=d[n];if(!i)continue;let{direction:a,speed:o}=zv(e,i,y,t,p);for(let e of[`x`,`y`])m[e][a[e]]||(o[e]=0,a[e]=0);if(o.x>0||o.y>0){g(),b.current=e,h(x,s),_.current=o,v.current=a;return}}_.current={x:0,y:0},v.current={x:0,y:0},g()},[t,x,r,g,a,s,JSON.stringify(y),JSON.stringify(m),h,u,S,d,JSON.stringify(p)])}var gy={x:{[Fv.Backward]:!1,[Fv.Forward]:!1},y:{[Fv.Backward]:!1,[Fv.Forward]:!1}};function _y(e){let{delta:t,disabled:n}=e,r=A_(t);return O_(e=>{if(n||!r||!e)return gy;let i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[Fv.Backward]:e.x[Fv.Backward]||i.x===-1,[Fv.Forward]:e.x[Fv.Forward]||i.x===1},y:{[Fv.Backward]:e.y[Fv.Backward]||i.y===-1,[Fv.Forward]:e.y[Fv.Forward]||i.y===1}}},[n,t,r])}function vy(e,t){let n=t==null?void 0:e.get(t),r=n?n.node.current:null;return O_(e=>t==null?null:r??e??null,[r,t])}function yy(e,t){return(0,o.useMemo)(()=>e.reduce((e,n)=>{let{sensor:r}=n,i=r.activators.map(e=>({eventName:e.eventName,handler:t(e.handler,n)}));return[...e,...i]},[]),[e,t])}var by;(function(e){e[e.Always=0]=`Always`,e[e.BeforeDragging=1]=`BeforeDragging`,e[e.WhileDragging=2]=`WhileDragging`})(by||={});var xy;(function(e){e.Optimized=`optimized`})(xy||={});var Sy=new Map;function Cy(e,t){let{dragging:n,dependencies:r,config:i}=t,[a,s]=(0,o.useState)(null),{frequency:c,measure:l,strategy:u}=i,d=(0,o.useRef)(e),f=_(),p=D_(f),m=(0,o.useCallback)(function(e){e===void 0&&(e=[]),!p.current&&s(t=>t===null?e:t.concat(e.filter(e=>!t.includes(e))))},[p]),h=(0,o.useRef)(null),g=O_(t=>{if(f&&!n)return Sy;if(!t||t===Sy||d.current!==e||a!=null){let t=new Map;for(let n of e){if(!n)continue;if(a&&a.length>0&&!a.includes(n.id)&&n.rect.current){t.set(n.id,n.rect.current);continue}let e=n.node.current,r=e?new Kv(l(e),e):null;n.rect.current=r,r&&t.set(n.id,r)}return t}return t},[e,a,n,f,l]);return(0,o.useEffect)(()=>{d.current=e},[e]),(0,o.useEffect)(()=>{f||m()},[n,f]),(0,o.useEffect)(()=>{a&&a.length>0&&s(null)},[JSON.stringify(a)]),(0,o.useEffect)(()=>{f||typeof c!=`number`||h.current!==null||(h.current=setTimeout(()=>{m(),h.current=null},c))},[c,f,m,...r]),{droppableRects:g,measureDroppableContainers:m,measuringScheduled:a!=null};function _(){switch(u){case by.Always:return!1;case by.BeforeDragging:return n;default:return!n}}}function wy(e,t){return O_(n=>e?n||(typeof t==`function`?t(e):e):null,[t,e])}function Ty(e,t){return wy(e,t)}function Ey(e){let{callback:t,disabled:n}=e,r=T_(t),i=(0,o.useMemo)(()=>{if(n||typeof window>`u`||window.MutationObserver===void 0)return;let{MutationObserver:e}=window;return new e(r)},[r,n]);return(0,o.useEffect)(()=>()=>i?.disconnect(),[i]),i}function Dy(e){let{callback:t,disabled:n}=e,r=T_(t),i=(0,o.useMemo)(()=>{if(n||typeof window>`u`||window.ResizeObserver===void 0)return;let{ResizeObserver:e}=window;return new e(r)},[n]);return(0,o.useEffect)(()=>()=>i?.disconnect(),[i]),i}function Oy(e){return new Kv(wv(e),e)}function ky(e,t,n){t===void 0&&(t=Oy);let[r,i]=(0,o.useState)(null);function a(){i(r=>{if(!e)return null;if(e.isConnected===!1)return r??n??null;let i=t(e);return JSON.stringify(r)===JSON.stringify(i)?r:i})}let s=Ey({callback(t){if(e)for(let n of t){let{type:t,target:r}=n;if(t===`childList`&&r instanceof HTMLElement&&r.contains(e)){a();break}}}}),c=Dy({callback:a});return w_(()=>{a(),e?(c?.observe(e),s?.observe(document.body,{childList:!0,subtree:!0})):(c?.disconnect(),s?.disconnect())},[e]),r}function Ay(e){return vv(e,wy(e))}var jy=[];function My(e){let t=(0,o.useRef)(e),n=O_(n=>e?n&&n!==jy&&e&&t.current&&e.parentNode===t.current.parentNode?n:kv(e):jy,[e]);return(0,o.useEffect)(()=>{t.current=e},[e]),n}function Ny(e){let[t,n]=(0,o.useState)(null),r=(0,o.useRef)(e),i=(0,o.useCallback)(e=>{let t=jv(e.target);t&&n(e=>e?(e.set(t,Pv(t)),new Map(e)):null)},[]);return(0,o.useEffect)(()=>{let t=r.current;if(e!==t){a(t);let o=e.map(e=>{let t=jv(e);return t?(t.addEventListener(`scroll`,i,{passive:!0}),[t,Pv(t)]):null}).filter(e=>e!=null);n(o.length?new Map(o):null),r.current=e}return()=>{a(e),a(t)};function a(e){e.forEach(e=>{jv(e)?.removeEventListener(`scroll`,i)})}},[i,e]),(0,o.useMemo)(()=>e.length?t?Array.from(t.values()).reduce((e,t)=>P_(e,t),rv):Vv(e):rv,[e,t])}function Py(e,t){t===void 0&&(t=[]);let n=(0,o.useRef)(null);return(0,o.useEffect)(()=>{n.current=null},t),(0,o.useEffect)(()=>{let t=e!==rv;t&&!n.current&&(n.current=e),!t&&n.current&&(n.current=null)},[e]),n.current?F_(e,n.current):rv}function Fy(e){(0,o.useEffect)(()=>{if(!g_)return;let t=e.map(e=>{let{sensor:t}=e;return t.setup==null?void 0:t.setup()});return()=>{for(let e of t)e?.()}},e.map(e=>{let{sensor:t}=e;return t}))}function Iy(e,t){return(0,o.useMemo)(()=>e.reduce((e,n)=>{let{eventName:r,handler:i}=n;return e[r]=e=>{i(e,t)},e},{}),[e,t])}function Ly(e){return(0,o.useMemo)(()=>e?Ev(e):null,[e])}var Ry=[];function zy(e,t){t===void 0&&(t=wv);let[n]=e,r=Ly(n?y_(n):null),[i,a]=(0,o.useState)(Ry);function s(){a(()=>e.length?e.map(e=>Iv(e)?r:new Kv(t(e),e)):Ry)}let c=Dy({callback:s});return w_(()=>{c?.disconnect(),s(),e.forEach(e=>c?.observe(e))},[e]),i}function By(e){if(!e)return null;if(e.children.length>1)return e;let t=e.children[0];return x_(t)?t:e}function Vy(e){let{measure:t}=e,[n,r]=(0,o.useState)(null),i=Dy({callback:(0,o.useCallback)(e=>{for(let{target:n}of e)if(x_(n)){r(e=>{let r=t(n);return e?{...e,width:r.width,height:r.height}:r});break}},[t])}),[a,s]=k_((0,o.useCallback)(e=>{let n=By(e);i?.disconnect(),n&&i?.observe(n),r(n?t(n):null)},[t,i]));return(0,o.useMemo)(()=>({nodeRef:a,rect:n,setRef:s}),[n,a,s])}var Hy=[{sensor:sy,options:{}},{sensor:ny,options:{}}],Uy={current:{}},Wy={draggable:{measure:Tv},droppable:{measure:Tv,strategy:by.WhileDragging,frequency:xy.Optimized},dragOverlay:{measure:wv}},Gy=class extends Map{get(e){return e==null?void 0:super.get(e)??void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:t}=e;return!t})}getNodeFor(e){return this.get(e)?.node.current??void 0}},Ky={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Gy,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:ev},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Wy,measureDroppableContainers:ev,windowRect:null,measuringScheduled:!1},qy={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:``},dispatch:ev,draggableNodes:new Map,over:null,measureDroppableContainers:ev},Jy=(0,o.createContext)(qy),Yy=(0,o.createContext)(Ky);function Xy(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Gy}}}function Zy(e,t){switch(t.type){case $_.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case $_.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case $_.DragEnd:case $_.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case $_.RegisterDroppable:{let{element:n}=t,{id:r}=n,i=new Gy(e.droppable.containers);return i.set(r,n),{...e,droppable:{...e.droppable,containers:i}}}case $_.SetDroppableDisabled:{let{id:n,key:r,disabled:i}=t,a=e.droppable.containers.get(n);if(!a||r!==a.key)return e;let o=new Gy(e.droppable.containers);return o.set(n,{...a,disabled:i}),{...e,droppable:{...e.droppable,containers:o}}}case $_.UnregisterDroppable:{let{id:n,key:r}=t,i=e.droppable.containers.get(n);if(!i||r!==i.key)return e;let a=new Gy(e.droppable.containers);return a.delete(n),{...e,droppable:{...e.droppable,containers:a}}}default:return e}}function Qy(e){let{disabled:t}=e,{active:n,activatorEvent:r,draggableNodes:i}=(0,o.useContext)(Jy),a=A_(r),s=A_(n?.id);return(0,o.useEffect)(()=>{if(!t&&!r&&a&&s!=null){if(!L_(a)||document.activeElement===a.target)return;let e=i.get(s);if(!e)return;let{activatorNode:t,node:n}=e;if(!t.current&&!n.current)return;requestAnimationFrame(()=>{for(let e of[t.current,n.current]){if(!e)continue;let t=H_(e);if(t){t.focus();break}}})}},[r,t,i,s,a]),null}function $y(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((e,t)=>t({transform:e,...r}),n):n}function eb(e){return(0,o.useMemo)(()=>({draggable:{...Wy.draggable,...e?.draggable},droppable:{...Wy.droppable,...e?.droppable},dragOverlay:{...Wy.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function tb(e){let{activeNode:t,measure:n,initialRect:r,config:i=!0}=e,a=(0,o.useRef)(!1),{x:s,y:c}=typeof i==`boolean`?{x:i,y:i}:i;w_(()=>{if(!s&&!c||!t){a.current=!1;return}if(a.current||!r)return;let e=t?.node.current;if(!e||e.isConnected===!1)return;let i=vv(n(e),r);if(s||(i.x=0),c||(i.y=0),a.current=!0,Math.abs(i.x)>0||Math.abs(i.y)>0){let t=Av(e);t&&t.scrollBy({top:i.y,left:i.x})}},[t,s,c,r,n])}var nb=(0,o.createContext)({...rv,scaleX:1,scaleY:1}),rb;(function(e){e[e.Uninitialized=0]=`Uninitialized`,e[e.Initializing=1]=`Initializing`,e[e.Initialized=2]=`Initialized`})(rb||={});var ib=(0,o.memo)(function(e){let{id:t,accessibility:n,autoScroll:r=!0,children:i,sensors:a=Hy,collisionDetection:s=mv,measuring:c,modifiers:l,...u}=e,[d,f]=(0,o.useReducer)(Zy,void 0,Xy),[p,m]=Y_(),[h,g]=(0,o.useState)(rb.Uninitialized),_=h===rb.Initialized,{draggable:{active:v,nodes:y,translate:b},droppable:{containers:x}}=d,S=v==null?null:y.get(v),C=(0,o.useRef)({initial:null,translated:null}),w=(0,o.useMemo)(()=>v==null?null:{id:v,data:S?.data??Uy,rect:C},[v,S]),T=(0,o.useRef)(null),[E,D]=(0,o.useState)(null),[O,k]=(0,o.useState)(null),A=D_(u,Object.values(u)),j=M_(`DndDescribedBy`,t),M=(0,o.useMemo)(()=>x.getEnabled(),[x]),N=eb(c),{droppableRects:ee,measureDroppableContainers:P,measuringScheduled:te}=Cy(M,{dragging:_,dependencies:[b.x,b.y],config:N.droppable}),F=vy(y,v),ne=(0,o.useMemo)(()=>O?z_(O):null,[O]),re=je(),ie=Ty(F,N.draggable.measure);tb({activeNode:v==null?null:y.get(v),config:re.layoutShiftCompensation,initialRect:ie,measure:N.draggable.measure});let I=ky(F,N.draggable.measure,ie),ae=ky(F?F.parentElement:null),L=(0,o.useRef)({activatorEvent:null,active:null,activeNode:F,collisionRect:null,collisions:null,droppableRects:ee,draggableNodes:y,draggingNode:null,draggingNodeRect:null,droppableContainers:x,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),oe=x.getNodeFor(L.current.over?.id),R=Vy({measure:N.dragOverlay.measure}),se=R.nodeRef.current??F,ce=_?R.rect??I:null,le=!!(R.nodeRef.current&&R.rect),ue=Ay(le?null:I),de=Ly(se?y_(se):null),fe=My(_?oe??F:null),pe=zy(fe),me=$y(l,{transform:{x:b.x-ue.x,y:b.y-ue.y,scaleX:1,scaleY:1},activatorEvent:O,active:w,activeNodeRect:I,containerNodeRect:ae,draggingNodeRect:ce,over:L.current.over,overlayNodeRect:R.rect,scrollableAncestors:fe,scrollableAncestorRects:pe,windowRect:de}),he=ne?P_(ne,b):null,ge=Ny(fe),_e=Py(ge),ve=Py(ge,[I]),ye=P_(me,_e),be=ce?bv(ce,me):null,xe=w&&be?s({active:w,collisionRect:be,droppableRects:ee,droppableContainers:M,pointerCoordinates:he}):null,Se=lv(xe,`id`),[Ce,we]=(0,o.useState)(null),Te=_v(le?me:P_(me,ve),Ce?.rect??null,I),Ee=(0,o.useRef)(null),De=(0,o.useCallback)((e,t)=>{let{sensor:n,options:r}=t;if(T.current==null)return;let i=y.get(T.current);if(!i)return;let a=e.nativeEvent,o=new n({active:T.current,activeNode:i,event:a,options:r,context:L,onAbort(e){if(!y.get(e))return;let{onDragAbort:t}=A.current,n={id:e};t?.(n),p({type:`onDragAbort`,event:n})},onPending(e,t,n,r){if(!y.get(e))return;let{onDragPending:i}=A.current,a={id:e,constraint:t,initialCoordinates:n,offset:r};i?.(a),p({type:`onDragPending`,event:a})},onStart(e){let t=T.current;if(t==null)return;let n=y.get(t);if(!n)return;let{onDragStart:r}=A.current,i={activatorEvent:a,active:{id:t,data:n.data,rect:C}};(0,tr.unstable_batchedUpdates)(()=>{r?.(i),g(rb.Initializing),f({type:$_.DragStart,initialCoordinates:e,active:t}),p({type:`onDragStart`,event:i}),D(Ee.current),k(a)})},onMove(e){f({type:$_.DragMove,coordinates:e})},onEnd:s($_.DragEnd),onCancel:s($_.DragCancel)});Ee.current=o;function s(e){return async function(){let{active:t,collisions:n,over:r,scrollAdjustedTranslate:i}=L.current,o=null;if(t&&i){let{cancelDrop:s}=A.current;o={activatorEvent:a,active:t,collisions:n,delta:i,over:r},e===$_.DragEnd&&typeof s==`function`&&await Promise.resolve(s(o))&&(e=$_.DragCancel)}T.current=null,(0,tr.unstable_batchedUpdates)(()=>{f({type:e}),g(rb.Uninitialized),we(null),D(null),k(null),Ee.current=null;let t=e===$_.DragEnd?`onDragEnd`:`onDragCancel`;if(o){let e=A.current[t];e?.(o),p({type:t,event:o})}})}}},[y]),Oe=yy(a,(0,o.useCallback)((e,t)=>(n,r)=>{let i=n.nativeEvent,a=y.get(r);if(T.current!==null||!a||i.dndKit||i.defaultPrevented)return;let o={active:a};e(n,t.options,o)===!0&&(i.dndKit={capturedBy:t.sensor},T.current=r,De(n,t))},[y,De]));Fy(a),w_(()=>{I&&h===rb.Initializing&&g(rb.Initialized)},[I,h]),(0,o.useEffect)(()=>{let{onDragMove:e}=A.current,{active:t,activatorEvent:n,collisions:r,over:i}=L.current;if(!t||!n)return;let a={active:t,activatorEvent:n,collisions:r,delta:{x:ye.x,y:ye.y},over:i};(0,tr.unstable_batchedUpdates)(()=>{e?.(a),p({type:`onDragMove`,event:a})})},[ye.x,ye.y]),(0,o.useEffect)(()=>{let{active:e,activatorEvent:t,collisions:n,droppableContainers:r,scrollAdjustedTranslate:i}=L.current;if(!e||T.current==null||!t||!i)return;let{onDragOver:a}=A.current,o=r.get(Se),s=o&&o.rect.current?{id:o.id,rect:o.rect.current,data:o.data,disabled:o.disabled}:null,c={active:e,activatorEvent:t,collisions:n,delta:{x:i.x,y:i.y},over:s};(0,tr.unstable_batchedUpdates)(()=>{we(s),a?.(c),p({type:`onDragOver`,event:c})})},[Se]),w_(()=>{L.current={activatorEvent:O,active:w,activeNode:F,collisionRect:be,collisions:xe,droppableRects:ee,draggableNodes:y,draggingNode:se,draggingNodeRect:ce,droppableContainers:x,over:Ce,scrollableAncestors:fe,scrollAdjustedTranslate:ye},C.current={initial:ce,translated:be}},[w,F,xe,be,y,se,ce,ee,x,Ce,fe,ye]),hy({...re,delta:b,draggingRect:be,pointerCoordinates:he,scrollableAncestors:fe,scrollableAncestorRects:pe});let ke=(0,o.useMemo)(()=>({active:w,activeNode:F,activeNodeRect:I,activatorEvent:O,collisions:xe,containerNodeRect:ae,dragOverlay:R,draggableNodes:y,droppableContainers:x,droppableRects:ee,over:Ce,measureDroppableContainers:P,scrollableAncestors:fe,scrollableAncestorRects:pe,measuringConfiguration:N,measuringScheduled:te,windowRect:de}),[w,F,I,O,xe,ae,R,y,x,ee,Ce,P,fe,pe,N,te,de]),Ae=(0,o.useMemo)(()=>({activatorEvent:O,activators:Oe,active:w,activeNodeRect:I,ariaDescribedById:{draggable:j},dispatch:f,draggableNodes:y,over:Ce,measureDroppableContainers:P}),[O,Oe,w,I,f,j,y,Ce,P]);return o.createElement(q_.Provider,{value:m},o.createElement(Jy.Provider,{value:Ae},o.createElement(Yy.Provider,{value:ke},o.createElement(nb.Provider,{value:Te},i)),o.createElement(Qy,{disabled:n?.restoreFocus===!1})),o.createElement(Q_,{...n,hiddenTextDescribedById:j}));function je(){let e=E?.autoScrollEnabled===!1,t=typeof r==`object`?r.enabled===!1:r===!1,n=_&&!e&&!t;return typeof r==`object`?{...r,enabled:n}:{enabled:n}}}),ab=(0,o.createContext)(null),ob=`button`,sb=`Draggable`;function cb(e){let{id:t,data:n,disabled:r=!1,attributes:i}=e,a=M_(sb),{activators:s,activatorEvent:c,active:l,activeNodeRect:u,ariaDescribedById:d,draggableNodes:f,over:p}=(0,o.useContext)(Jy),{role:m=ob,roleDescription:h=`draggable`,tabIndex:g=0}=i??{},_=l?.id===t,v=(0,o.useContext)(_?nb:ab),[y,b]=k_(),[x,S]=k_(),C=Iy(s,t),w=D_(n);return w_(()=>(f.set(t,{id:t,key:a,node:y,activatorNode:x,data:w}),()=>{let e=f.get(t);e&&e.key===a&&f.delete(t)}),[f,t]),{active:l,activatorEvent:c,activeNodeRect:u,attributes:(0,o.useMemo)(()=>({role:m,tabIndex:g,"aria-disabled":r,"aria-pressed":_&&m===ob?!0:void 0,"aria-roledescription":h,"aria-describedby":d.draggable}),[r,m,g,_,h,d.draggable]),isDragging:_,listeners:r?void 0:C,node:y,over:p,setNodeRef:b,setActivatorNodeRef:S,transform:v}}function lb(){return(0,o.useContext)(Yy)}var ub=`Droppable`,db={timeout:25};function fb(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:i}=e,a=M_(ub),{active:s,dispatch:c,over:l,measureDroppableContainers:u}=(0,o.useContext)(Jy),d=(0,o.useRef)({disabled:n}),f=(0,o.useRef)(!1),p=(0,o.useRef)(null),m=(0,o.useRef)(null),{disabled:h,updateMeasurementsFor:g,timeout:_}={...db,...i},v=D_(g??r),y=Dy({callback:(0,o.useCallback)(()=>{if(!f.current){f.current=!0;return}m.current!=null&&clearTimeout(m.current),m.current=setTimeout(()=>{u(Array.isArray(v.current)?v.current:[v.current]),m.current=null},_)},[_]),disabled:h||!s}),[b,x]=k_((0,o.useCallback)((e,t)=>{y&&(t&&(y.unobserve(t),f.current=!1),e&&y.observe(e))},[y])),S=D_(t);return(0,o.useEffect)(()=>{y&&b.current&&(y.disconnect(),f.current=!1,y.observe(b.current))},[b,y]),(0,o.useEffect)(()=>(c({type:$_.RegisterDroppable,element:{id:r,key:a,disabled:n,node:b,rect:p,data:S}}),()=>c({type:$_.UnregisterDroppable,key:a,id:r})),[r]),(0,o.useEffect)(()=>{n!==d.current.disabled&&(c({type:$_.SetDroppableDisabled,id:r,key:a,disabled:n}),d.current.disabled=n)},[r,a,n,c]),{active:s,rect:p,isOver:l?.id===r,node:b,over:l,setNodeRef:x}}function pb(e){let{animation:t,children:n}=e,[r,i]=(0,o.useState)(null),[a,s]=(0,o.useState)(null),c=A_(n);return!n&&!r&&c&&i(c),w_(()=>{if(!a)return;let e=r?.key,n=r?.props.id;if(e==null||n==null){i(null);return}Promise.resolve(t(n,a)).then(()=>{i(null)})},[t,r,a]),o.createElement(o.Fragment,null,n,r?(0,o.cloneElement)(r,{ref:s}):null)}var mb={x:0,y:0,scaleX:1,scaleY:1};function hb(e){let{children:t}=e;return o.createElement(Jy.Provider,{value:qy},o.createElement(nb.Provider,{value:mb},t))}var gb={position:`fixed`,touchAction:`none`},_b=e=>L_(e)?`transform 250ms ease`:void 0,vb=(0,o.forwardRef)((e,t)=>{let{as:n,activatorEvent:r,adjustScale:i,children:a,className:s,rect:c,style:l,transform:u,transition:d=_b}=e;if(!c)return null;let f=i?u:{...u,scaleX:1,scaleY:1},p={...gb,width:c.width,height:c.height,top:c.top,left:c.left,transform:B_.Transform.toString(f),transformOrigin:i&&r?av(r,c):void 0,transition:typeof d==`function`?d(r):d,...l};return o.createElement(n,{className:s,style:p,ref:t},a)}),yb={duration:250,easing:`ease`,keyframes:e=>{let{transform:{initial:t,final:n}}=e;return[{transform:B_.Transform.toString(t)},{transform:B_.Transform.toString(n)}]},sideEffects:(e=>t=>{let{active:n,dragOverlay:r}=t,i={},{styles:a,className:o}=e;if(a!=null&&a.active)for(let[e,t]of Object.entries(a.active))t!==void 0&&(i[e]=n.node.style.getPropertyValue(e),n.node.style.setProperty(e,t));if(a!=null&&a.dragOverlay)for(let[e,t]of Object.entries(a.dragOverlay))t!==void 0&&r.node.style.setProperty(e,t);return o!=null&&o.active&&n.node.classList.add(o.active),o!=null&&o.dragOverlay&&r.node.classList.add(o.dragOverlay),function(){for(let[e,t]of Object.entries(i))n.node.style.setProperty(e,t);o!=null&&o.active&&n.node.classList.remove(o.active)}})({styles:{active:{opacity:`0`}}})};function bb(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:i}=e;return T_((e,a)=>{if(t===null)return;let o=n.get(e);if(!o)return;let s=o.node.current;if(!s)return;let c=By(a);if(!c)return;let{transform:l}=y_(a).getComputedStyle(a),u=xv(l);if(!u)return;let d=typeof t==`function`?t:xb(t);return Wv(s,i.draggable.measure),d({active:{id:e,data:o.data,node:s,rect:i.draggable.measure(s)},draggableNodes:n,dragOverlay:{node:a,rect:i.dragOverlay.measure(c)},droppableContainers:r,measuringConfiguration:i,transform:u})})}function xb(e){let{duration:t,easing:n,sideEffects:r,keyframes:i}={...yb,...e};return e=>{let{active:a,dragOverlay:o,transform:s,...c}=e;if(!t)return;let l={x:o.rect.left-a.rect.left,y:o.rect.top-a.rect.top},u={scaleX:s.scaleX===1?1:a.rect.width*s.scaleX/o.rect.width,scaleY:s.scaleY===1?1:a.rect.height*s.scaleY/o.rect.height},d={x:s.x-l.x,y:s.y-l.y,...u},f=i({...c,active:a,dragOverlay:o,transform:{initial:s,final:d}}),[p]=f,m=f[f.length-1];if(JSON.stringify(p)===JSON.stringify(m))return;let h=r?.({active:a,dragOverlay:o,...c}),g=o.node.animate(f,{duration:t,easing:n,fill:`forwards`});return new Promise(e=>{g.onfinish=()=>{h?.(),e()}})}}var Sb=0;function Cb(e){return(0,o.useMemo)(()=>{if(e!=null)return Sb++,Sb},[e])}var wb=o.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:i,transition:a,modifiers:s,wrapperElement:c=`div`,className:l,zIndex:u=999}=e,{activatorEvent:d,active:f,activeNodeRect:p,containerNodeRect:m,draggableNodes:h,droppableContainers:g,dragOverlay:_,over:v,measuringConfiguration:y,scrollableAncestors:b,scrollableAncestorRects:x,windowRect:S}=lb(),C=(0,o.useContext)(nb),w=Cb(f?.id),T=$y(s,{activatorEvent:d,active:f,activeNodeRect:p,containerNodeRect:m,draggingNodeRect:_.rect,over:v,overlayNodeRect:_.rect,scrollableAncestors:b,scrollableAncestorRects:x,transform:C,windowRect:S}),E=wy(p),D=bb({config:r,draggableNodes:h,droppableContainers:g,measuringConfiguration:y}),O=E?_.setRef:void 0;return o.createElement(hb,null,o.createElement(pb,{animation:D},f&&w?o.createElement(vb,{key:w,id:f.id,ref:O,as:c,activatorEvent:d,adjustScale:t,className:l,transition:a,rect:E,style:{zIndex:u,...i},transform:T},n):null))});function Tb(e,t,n){let r=e.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function Eb(e,t){return e.reduce((e,n,r)=>{let i=t.get(n);return i&&(e[r]=i),e},Array(e.length))}function Db(e){return e!==null&&e>=0}function Ob(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function kb(e){return typeof e==`boolean`?{draggable:e,droppable:e}:e}var Ab=e=>{let{rects:t,activeIndex:n,overIndex:r,index:i}=e,a=Tb(t,r,n),o=t[i],s=a[i];return!s||!o?null:{x:s.left-o.left,y:s.top-o.top,scaleX:s.width/o.width,scaleY:s.height/o.height}},jb={scaleX:1,scaleY:1},Mb=e=>{let{activeIndex:t,activeNodeRect:n,index:r,rects:i,overIndex:a}=e,o=i[t]??n;if(!o)return null;if(r===t){let e=i[a];return e?{x:0,y:t<a?e.top+e.height-(o.top+o.height):e.top-o.top,...jb}:null}let s=Nb(i,r,t);return r>t&&r<=a?{x:0,y:-o.height-s,...jb}:r<t&&r>=a?{x:0,y:o.height+s,...jb}:{x:0,y:0,...jb}};function Nb(e,t,n){let r=e[t],i=e[t-1],a=e[t+1];return r?n<t?i?r.top-(i.top+i.height):a?a.top-(r.top+r.height):0:a?a.top-(r.top+r.height):i?r.top-(i.top+i.height):0:0}var Pb=`Sortable`,Fb=o.createContext({activeIndex:-1,containerId:Pb,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:Ab,disabled:{draggable:!1,droppable:!1}});function Ib(e){let{children:t,id:n,items:r,strategy:i=Ab,disabled:a=!1}=e,{active:s,dragOverlay:c,droppableRects:l,over:u,measureDroppableContainers:d}=lb(),f=M_(Pb,n),p=c.rect!==null,m=(0,o.useMemo)(()=>r.map(e=>typeof e==`object`&&`id`in e?e.id:e),[r]),h=s!=null,g=s?m.indexOf(s.id):-1,_=u?m.indexOf(u.id):-1,v=(0,o.useRef)(m),y=!Ob(m,v.current),b=_!==-1&&g===-1||y,x=kb(a);w_(()=>{y&&h&&d(m)},[y,m,h,d]),(0,o.useEffect)(()=>{v.current=m},[m]);let S=(0,o.useMemo)(()=>({activeIndex:g,containerId:f,disabled:x,disableTransforms:b,items:m,overIndex:_,useDragOverlay:p,sortedRects:Eb(m,l),strategy:i}),[g,f,x.draggable,x.droppable,b,m,_,l,p,i]);return o.createElement(Fb.Provider,{value:S},t)}var Lb=e=>{let{id:t,items:n,activeIndex:r,overIndex:i}=e;return Tb(n,r,i).indexOf(t)},Rb=e=>{let{containerId:t,isSorting:n,wasDragging:r,index:i,items:a,newIndex:o,previousItems:s,previousContainerId:c,transition:l}=e;return!l||!r||s!==a&&i===o?!1:n?!0:o!==i&&t===c},zb={duration:200,easing:`ease`},Bb=`transform`,Vb=B_.Transition.toString({property:Bb,duration:0,easing:`linear`}),Hb={roleDescription:`sortable`};function Ub(e){let{disabled:t,index:n,node:r,rect:i}=e,[a,s]=(0,o.useState)(null),c=(0,o.useRef)(n);return w_(()=>{if(!t&&n!==c.current&&r.current){let e=i.current;if(e){let t=wv(r.current,{ignoreTransform:!0}),n={x:e.left-t.left,y:e.top-t.top,scaleX:e.width/t.width,scaleY:e.height/t.height};(n.x||n.y)&&s(n)}}n!==c.current&&(c.current=n)},[t,n,r,i]),(0,o.useEffect)(()=>{a&&s(null)},[a]),a}function Wb(e){let{animateLayoutChanges:t=Rb,attributes:n,disabled:r,data:i,getNewIndex:a=Lb,id:s,strategy:c,resizeObserverConfig:l,transition:u=zb}=e,{items:d,containerId:f,activeIndex:p,disabled:m,disableTransforms:h,sortedRects:g,overIndex:_,useDragOverlay:v,strategy:y}=(0,o.useContext)(Fb),b=Gb(r,m),x=d.indexOf(s),S=(0,o.useMemo)(()=>({sortable:{containerId:f,index:x,items:d},...i}),[f,i,x,d]),C=(0,o.useMemo)(()=>d.slice(d.indexOf(s)),[d,s]),{rect:w,node:T,isOver:E,setNodeRef:D}=fb({id:s,data:S,disabled:b.droppable,resizeObserverConfig:{updateMeasurementsFor:C,...l}}),{active:O,activatorEvent:k,activeNodeRect:A,attributes:j,setNodeRef:M,listeners:N,isDragging:ee,over:P,setActivatorNodeRef:te,transform:F}=cb({id:s,data:S,attributes:{...Hb,...n},disabled:b.draggable}),ne=h_(D,M),re=!!O,ie=re&&!h&&Db(p)&&Db(_),I=!v&&ee,ae=ie?(I&&ie?F:null)??(c??y)({rects:g,activeNodeRect:A,activeIndex:p,overIndex:_,index:x}):null,L=Db(p)&&Db(_)?a({id:s,items:d,activeIndex:p,overIndex:_}):x,oe=O?.id,R=(0,o.useRef)({activeId:oe,items:d,newIndex:L,containerId:f}),se=d!==R.current.items,ce=t({active:O,containerId:f,isDragging:ee,isSorting:re,id:s,index:x,items:d,newIndex:R.current.newIndex,previousItems:R.current.items,previousContainerId:R.current.containerId,transition:u,wasDragging:R.current.activeId!=null}),le=Ub({disabled:!ce,index:x,node:T,rect:w});return(0,o.useEffect)(()=>{re&&R.current.newIndex!==L&&(R.current.newIndex=L),f!==R.current.containerId&&(R.current.containerId=f),d!==R.current.items&&(R.current.items=d)},[re,L,f,d]),(0,o.useEffect)(()=>{if(oe===R.current.activeId)return;if(oe!=null&&R.current.activeId==null){R.current.activeId=oe;return}let e=setTimeout(()=>{R.current.activeId=oe},50);return()=>clearTimeout(e)},[oe]),{active:O,activeIndex:p,attributes:j,data:S,rect:w,index:x,newIndex:L,items:d,isOver:E,isSorting:re,isDragging:ee,listeners:N,node:T,overIndex:_,over:P,setNodeRef:ne,setActivatorNodeRef:te,setDroppableNodeRef:D,setDraggableNodeRef:M,transform:le??ae,transition:ue()};function ue(){if(le||se&&R.current.newIndex===x)return Vb;if(!(I&&!L_(k)||!u)&&(re||ce))return B_.Transition.toString({...u,property:Bb})}}function Gb(e,t){return typeof e==`boolean`?{draggable:e,droppable:!1}:{draggable:e?.draggable??t.draggable,droppable:e?.droppable??t.droppable}}function Kb(e){if(!e)return!1;let t=e.data.current;return!!(t&&`sortable`in t&&typeof t.sortable==`object`&&`containerId`in t.sortable&&`items`in t.sortable&&`index`in t.sortable)}var qb=[$v.Down,$v.Right,$v.Up,$v.Left],Jb=(e,t)=>{let{context:{active:n,collisionRect:r,droppableRects:i,droppableContainers:a,over:o,scrollableAncestors:s}}=t;if(qb.includes(e.code)){if(e.preventDefault(),!n||!r)return;let t=[];a.getEnabled().forEach(n=>{if(!n||n!=null&&n.disabled)return;let a=i.get(n.id);if(a)switch(e.code){case $v.Down:r.top<a.top&&t.push(n);break;case $v.Up:r.top>a.top&&t.push(n);break;case $v.Left:r.left>a.left&&t.push(n);break;case $v.Right:r.left<a.left&&t.push(n)}});let c=fv({active:n,collisionRect:r,droppableRects:i,droppableContainers:t,pointerCoordinates:null}),l=lv(c,`id`);if(l===o?.id&&c.length>1&&(l=c[1].id),l!=null){let e=a.get(n.id),t=a.get(l),o=t?i.get(t.id):null,c=t?.node.current;if(c&&o&&e&&t){let n=kv(c).some((e,t)=>s[t]!==e),i=Yb(e,t),a=Xb(e,t),l=n||!i?{x:0,y:0}:{x:a?r.width-o.width:0,y:a?r.height-o.height:0},u={x:o.left,y:o.top};return l.x&&l.y?u:F_(u,l)}}}};function Yb(e,t){return!Kb(e)||!Kb(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function Xb(e,t){return!Kb(e)||!Kb(t)||!Yb(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}var Zb=Date.UTC(2026,9,6,9,41),Qb=(e,t)=>{let n=(e^Math.imul(t+2654435769,2246822507))>>>0;return n=Math.imul(n^n>>>16,2246822507),n=Math.imul(n^n>>>13,3266489909),(n^n>>>16)>>>0},$b=(e,t)=>{let n=Qb(e,t);return()=>{n=n+1831565813>>>0;let e=n;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}},ex=[{id:`u1`,name:`Sanne M.`,initials:`SM`,hue:250,role:`Admin`},{id:`u2`,name:`Jonas K.`,initials:`JK`,hue:160,role:`Sales`},{id:`u3`,name:`Lieke D.`,initials:`LD`,hue:20,role:`Finance`},{id:`u4`,name:`Tobias R.`,initials:`TR`,hue:310,role:`Warehouse`},{id:`u5`,name:`Imke V.`,initials:`IV`,hue:200,role:`Sales`},{id:`u6`,name:`Marek W.`,initials:`MW`,hue:80,role:`Warehouse`},{id:`u7`,name:`Hanna B.`,initials:`HB`,hue:350,role:`Finance`},{id:`u8`,name:`Daan P.`,initials:`DP`,hue:120,role:`Sales`}],tx=e=>ex.find(t=>t.id===e)??ex[0];ex.filter(e=>e.role===`Sales`);var nx=[[`M8 hex bolt A2, 100 pcs`,`FST`,1890],[`M10 hex nut A2, 100 pcs`,`FST`,1240],[`Stainless washer 8 mm, 250 pcs`,`FST`,990],[`Cable tie 300 mm, 100 pcs`,`ELC`,650],[`Cable gland M20, 25 pcs`,`ELC`,2340],[`Junction box IP65`,`ELC`,1480],[`Hydraulic hose 1/2 in, 5 m`,`HYD`,8650],[`Hydraulic coupling 3/8 in`,`HYD`,1895],[`Pallet wrap 500 mm`,`PKG`,740],[`Corrugated box 400 x 300`,`PKG`,215],[`Bubble wrap roll 50 m`,`PKG`,1990],[`Safety gloves, size L`,`PPE`,395],[`Safety glasses, clear`,`PPE`,450],[`Ear defenders SNR 31`,`PPE`,1295],[`Ball bearing 6204-2RS`,`BRG`,685],[`Taper roller bearing 30205`,`BRG`,1420],[`Timing belt HTD 5M, 600 mm`,`BLT`,2780],[`V-belt SPA 1250`,`BLT`,1360],[`Grease cartridge, 400 g`,`LUB`,920],[`Machine oil ISO 68, 5 l`,`LUB`,3950],[`Angle grinder disc 125 mm, 10 pcs`,`ABR`,1880],[`Drill bit set HSS, 19 pcs`,`TLS`,3490],[`Torque wrench 20-100 Nm`,`TLS`,14900],[`Pneumatic cylinder 40 x 100`,`PNE`,6120],[`Air hose PU 8 mm, 20 m`,`PNE`,2475],[`LED panel 600 x 600, 40 W`,`LGT`,3290],[`Pallet label roll 100 x 150`,`LBL`,1175],[`Thermal printer ribbon`,`LBL`,890],[`Euro pallet EPAL, used`,`PLT`,1150],[`Roll container, galvanised`,`PLT`,9800]];nx.length;var rx=e=>{let[t,n,r]=nx[e%nx.length],i=e%nx.length;return{id:`P-${200+i}`,sku:`${n}-${String(1e3+i*7).padStart(4,`0`)}`,name:t,category:n,priceCents:r}},ix=e=>e.quantity*e.unitPriceCents,ax=(e,t=.21)=>{let n=e.reduce((e,t)=>e+ix(t),0),r=Math.round(n*t);return{subtotalCents:n,vatCents:r,totalCents:n+r}},ox=864e5,sx=e=>Array.from({length:e},(t,n)=>{let r=Zb-(e-1-n)*ox,i=new Date(r).getUTCDay();return{at:r,count:Math.round((i===0||i===6?120:410)*(.8+$b(71,n)()*.45)*(1+n/e/3))}}),cx=e=>{if(e===`day`)return sx(30);let t=sx(84);return Array.from({length:12},(e,n)=>{let r=t.slice(n*7,n*7+7);return{at:r[0].at,count:r.reduce((e,t)=>e+t.count,0)}})},lx=`grid grid-cols-[28px_minmax(0,1fr)_88px_112px_112px_32px] items-center gap-2 pointer-coarse:grid-cols-[44px_minmax(0,1fr)_88px_112px_112px_44px]`,ux=({items:e,label:t})=>{let[n,r]=(0,o.useState)(!1),i=(0,o.useRef)(null);return(0,o.useEffect)(()=>{if(!n)return;let e=e=>{(e instanceof KeyboardEvent?e.key===`Escape`:!i.current?.contains(e.target))&&r(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,e)}},[n]),(0,H.jsxs)(`div`,{ref:i,className:`relative flex justify-center`,children:[(0,H.jsx)(`button`,{type:`button`,"aria-label":t,"aria-haspopup":`menu`,"aria-expanded":n,onClick:()=>r(!n),className:`inline-flex size-7 items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground pointer-coarse:size-11`,children:(0,H.jsx)(Ke,{className:`size-4`})}),n&&(0,H.jsx)(`ul`,{role:`menu`,className:`absolute right-0 top-full z-30 mt-1 min-w-36 rounded-md border bg-background py-1 shadow-pop`,children:e.map(e=>(0,H.jsx)(`li`,{role:`none`,children:(0,H.jsx)(`button`,{type:`button`,role:`menuitem`,disabled:e.disabled,className:V(`block min-h-9 w-full whitespace-nowrap px-3 py-1.5 text-left hover:bg-muted disabled:text-faint-foreground disabled:hover:bg-transparent`,e.destructive&&`text-danger-text`),onClick:()=>{r(!1),e.onSelect()},children:e.label})},e.label))})]})},dx=({value:e,onCommit:t,format:n,parse:r,label:i,width:a=`w-full`})=>{let[s,c]=(0,o.useState)(null);return(0,H.jsx)(`input`,{"aria-label":i,inputMode:`decimal`,value:s??n(e),onFocus:e=>e.currentTarget.select(),onChange:e=>c(e.target.value),onBlur:()=>{if(s===null)return;let e=r(s);c(null),Number.isFinite(e)&&e>=0&&t(e)},onKeyDown:e=>e.key===`Enter`&&e.currentTarget.blur(),className:V(`h-7 rounded-md border border-transparent bg-transparent px-2 text-right tabular-nums text-foreground outline-none hover:border-border-strong focus:border-primary focus:bg-background focus:ring-2 focus:ring-primary/20`,a)})},fx=e=>Math.round(Number(e.replace(`,`,`.`).replace(/[^0-9.]/g,``))*100),px=({line:e,position:t,count:n,reorderable:r,editable:i,onChange:a,onRemove:o,onMove:s})=>{let{attributes:c,listeners:l,setNodeRef:u,setActivatorNodeRef:d,transform:f,transition:p,isDragging:m}=Wb({id:e.id,disabled:!r}),h=[...r?[{label:`Move up`,disabled:t===0,onSelect:()=>s(t-1)},{label:`Move down`,disabled:t===n-1,onSelect:()=>s(t+1)}]:[],...i?[{label:`Remove line`,destructive:!0,onSelect:o}]:[]];return(0,H.jsxs)(`div`,{ref:u,"data-line-id":e.id,style:{transform:f?`translate3d(0, ${f.y}px, 0)`:void 0,transition:p},className:V(`group relative border-b border-border bg-background px-2 py-1 last:border-b-0 hover:bg-surface`,lx,m&&`z-10 bg-surface opacity-80 shadow-pop`),children:[r?(0,H.jsx)(`button`,{ref:d,type:`button`,"aria-label":`Drag to reorder ${e.description}`,...c,...l,style:{touchAction:`none`},className:`flex size-7 cursor-grab items-center justify-center rounded text-faint-foreground opacity-60 hover:bg-muted hover:opacity-100 focus-visible:opacity-100 active:cursor-grabbing pointer-coarse:size-11`,children:(0,H.jsx)(ot,{className:`size-4`})}):(0,H.jsx)(`span`,{}),(0,H.jsxs)(`div`,{className:`min-w-0`,children:[(0,H.jsx)(`p`,{className:`truncate text-foreground`,children:e.description}),(0,H.jsx)(`p`,{className:`font-mono text-[11px] text-faint-foreground`,children:e.productId})]}),i?(0,H.jsx)(dx,{label:`Quantity`,value:e.quantity,format:String,parse:e=>Math.round(Number(e)),onCommit:e=>a({quantity:e})}):(0,H.jsx)(`span`,{className:`px-2 text-right tabular-nums`,children:e.quantity}),i?(0,H.jsx)(dx,{label:`Unit price`,value:e.unitPriceCents,format:e=>(e/100).toFixed(2),parse:fx,onCommit:e=>a({unitPriceCents:e})}):(0,H.jsx)(`span`,{className:`px-2 text-right tabular-nums`,children:(e.unitPriceCents/100).toFixed(2)}),(0,H.jsx)(`span`,{className:`px-2 text-right font-medium tabular-nums text-foreground`,children:nf(ix(e))}),h.length>0?(0,H.jsx)(ux,{label:`Actions for ${e.description}`,items:h}):(0,H.jsx)(`span`,{})]})},mx=(e,t,n)=>{if(t===n||t<0||t>=e.length)return[...e];let r=[...e],[i]=r.splice(t,1);return r.splice(Math.min(Math.max(n,0),r.length),0,i),r},hx=({lines:e,vatRate:t})=>{let n=ax(e,t);return(0,H.jsxs)(`dl`,{className:`ml-auto grid w-64 grid-cols-[1fr_auto] gap-x-6 gap-y-1 px-2 pt-3 tabular-nums`,children:[(0,H.jsx)(`dt`,{className:`text-muted-foreground`,children:`Subtotal`}),(0,H.jsx)(`dd`,{className:`text-right text-foreground`,children:nf(n.subtotalCents)}),(0,H.jsxs)(`dt`,{className:`text-muted-foreground`,children:[`VAT `,Math.round(t*100),`%`]}),(0,H.jsx)(`dd`,{className:`text-right text-foreground`,children:nf(n.vatCents)}),(0,H.jsx)(`dt`,{className:`mt-1 border-t border-border pt-2 font-semibold text-foreground`,children:`Total`}),(0,H.jsx)(`dd`,{className:`mt-1 border-t border-border pt-2 text-right text-[16px] font-semibold text-foreground`,children:nf(n.totalCents)})]})},gx=`px-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,_x=`To pick up a line, press space or enter on its drag handle. Use the up and down arrow keys to move it, space or enter to drop it, and escape to cancel. The row menu also has Move up and Move down.`,vx=e=>{let t=t=>e.find(e=>e.id===t)?.description??`line`,n=t=>e.findIndex(e=>e.id===t)+1;return{onDragStart:({active:r})=>`Picked up ${t(r.id)}, line ${n(r.id)} of ${e.length}.`,onDragOver:({active:r,over:i})=>i?`${t(r.id)} is over line ${n(i.id)} of ${e.length}.`:void 0,onDragEnd:({active:r,over:i})=>i?`${t(r.id)} was dropped at line ${n(i.id)} of ${e.length}.`:`${t(r.id)} was dropped where it started.`,onDragCancel:({active:e})=>`Moving ${t(e.id)} was cancelled. It is back at line ${n(e.id)}.`}},yx=({lines:e,onChange:t,onReorder:n,vatRate:r=.21,readOnly:i,reorderable:a=!i})=>{let o=nv(tv(uy,{activationConstraint:{distance:4}}),tv(fy,{activationConstraint:{delay:250,tolerance:5}}),tv(ny,{coordinateGetter:Jb})),s=(r,i)=>{let a=e[r];!a||i<0||i>=e.length||r===i||(n??(e=>t(e)))(mx(e,r,i),{id:a.id,from:r,to:i})};return(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:[(0,H.jsxs)(`div`,{className:`${lx} border-b border-border bg-surface px-2 py-2`,children:[(0,H.jsx)(`span`,{}),(0,H.jsx)(`span`,{className:gx,children:`Item`}),(0,H.jsx)(`span`,{className:`${gx} text-right`,children:`Qty`}),(0,H.jsx)(`span`,{className:`${gx} text-right`,children:`Unit price`}),(0,H.jsx)(`span`,{className:`${gx} text-right`,children:`Line total`}),(0,H.jsx)(`span`,{})]}),(0,H.jsx)(ib,{sensors:o,collisionDetection:dv,onDragEnd:({active:t,over:n})=>{n&&t.id!==n.id&&s(e.findIndex(e=>e.id===t.id),e.findIndex(e=>e.id===n.id))},accessibility:{announcements:vx(e),screenReaderInstructions:{draggable:_x}},children:(0,H.jsx)(Ib,{items:e.map(e=>e.id),strategy:Mb,children:e.map((n,r)=>(0,H.jsx)(px,{line:n,position:r,count:e.length,reorderable:a,editable:!i,onChange:r=>t(e.map(e=>e.id===n.id?{...e,...r}:e)),onRemove:()=>t(e.filter(e=>e.id!==n.id)),onMove:e=>s(r,e)},n.id))})}),!i&&(0,H.jsx)(`div`,{className:`border-t border-border bg-surface px-2 py-1.5`,children:(0,H.jsxs)(W,{variant:`ghost`,size:`sm`,onClick:()=>{let n=rx(e.length*3+1);t([...e,{id:`new-${e.length}-${n.id}`,productId:n.id,description:n.name,quantity:1,unitPriceCents:n.priceCents}])},children:[(0,H.jsx)(nn,{className:`size-3.5`}),`Add line`]})})]}),(0,H.jsx)(hx,{lines:e,vatRate:r})]})},bx=({name:e,label:t,required:n,help:r,example:i,error:a,conflict:s,wide:c,children:l})=>{let u=(0,o.useId)(),d=[r&&`${u}-help`,i&&`${u}-example`,a&&`${u}-error`].filter(Boolean).join(` `)||void 0;return(0,H.jsxs)(`div`,{className:c?`sm:col-span-2`:void 0,children:[(0,H.jsxs)(`div`,{className:`mb-1.5 flex items-center gap-2`,children:[(0,H.jsxs)(`label`,{htmlFor:u,className:`font-medium text-foreground`,children:[t,n&&(0,H.jsx)(`span`,{className:`ml-0.5 text-danger-text`,"aria-hidden":`true`,children:`*`})]}),s&&(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-warning-text`,title:`${s.user.name} saved a different value`,children:[(0,H.jsx)(Bn,{className:`size-3.5`}),(0,H.jsx)(Vu,{initials:s.user.initials,hue:s.user.hue,size:`xs`})]})]}),(0,H.jsx)(Sd,{value:{id:u,name:e,describedBy:d,invalid:!!a,required:!!n},children:l}),r&&(0,H.jsx)(`p`,{id:`${u}-help`,className:`mt-1.5 text-xs text-muted-foreground`,children:r}),i&&(0,H.jsxs)(`p`,{id:`${u}-example`,className:`mt-0.5 text-xs text-faint-foreground`,children:[`Example: `,i]}),a&&(0,H.jsx)(`p`,{id:`${u}-error`,className:`mt-1.5 text-xs font-medium text-danger-text`,children:a}),s&&(0,H.jsxs)(`div`,{className:`mt-2 flex items-center justify-between gap-3 rounded-md border border-warning/30 bg-warning-soft px-3 py-2 text-xs text-warning-text`,children:[(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`strong`,{children:s.user.name}),` saved this `,s.ago,`: `,(0,H.jsx)(`strong`,{children:s.theirValue})]}),(0,H.jsxs)(`span`,{className:`flex gap-1.5`,children:[(0,H.jsx)(W,{size:`sm`,onClick:s.onKeepMine,children:`Keep mine`}),(0,H.jsx)(W,{size:`sm`,onClick:s.onUseTheirs,children:`Use theirs`})]})]})]})},xx=({title:e,help:t,actions:n,children:r})=>{let i=(0,H.jsx)(`h2`,{className:`text-[16px] font-semibold text-foreground`,children:e});return(0,H.jsxs)(`section`,{className:`py-8 first:pt-8`,children:[n?(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-x-4 gap-y-2`,children:[i,n]}):i,t&&(0,H.jsx)(`p`,{className:`mt-1 max-w-xl leading-6 text-muted-foreground`,children:t}),(0,H.jsx)(`div`,{className:`mt-5`,children:r})]})},Sx=`flex min-h-11 items-center gap-2 rounded-md border border-border-strong px-3 text-left hover:bg-surface disabled:cursor-default disabled:opacity-60 md:min-h-0 md:w-full md:items-start md:gap-3 md:rounded-none md:border-0 md:px-4 md:py-3`,Cx=({actions:e})=>(0,H.jsxs)(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:[(0,H.jsx)(`h3`,{className:`hidden border-b border-border px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground md:block`,children:`Actions`}),(0,H.jsx)(`ul`,{className:`flex flex-wrap gap-2 p-2 md:block md:divide-y md:divide-border md:p-0`,children:e.map(({name:e,description:t,icon:n,onRun:r,blocked:i,running:a,tone:o,render:s})=>{let c=(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(n,{className:V(`size-4 shrink-0 md:mt-0.5`,o===`danger`?`text-danger-text`:`text-muted-foreground`),"aria-hidden":!0}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`span`,{className:V(`block font-medium`,o===`danger`?`text-danger-text`:`text-foreground`),children:e}),t&&(0,H.jsx)(`span`,{className:`mt-0.5 hidden text-xs leading-snug text-muted-foreground md:block`,children:t})]})]});return(0,H.jsx)(`li`,{children:s?s({className:Sx,children:c}):(0,H.jsx)(`button`,{type:`button`,onClick:r,disabled:!!i||a,title:i,className:Sx,children:c})},e)})})]}),wx=({rows:e})=>(0,H.jsx)(`dl`,{className:`grid grid-cols-[auto_1fr] gap-x-4 gap-y-2`,children:e.map(e=>(0,H.jsxs)(`div`,{className:`contents`,children:[(0,H.jsx)(`dt`,{className:`text-muted-foreground`,children:e.label}),(0,H.jsx)(`dd`,{className:`text-right tabular-nums text-foreground`,children:e.value})]},e.label))}),Tx=({records:e,onNavigate:t})=>(0,H.jsx)(`ul`,{className:`-mx-2`,children:e.map(e=>(0,H.jsx)(`li`,{children:(0,H.jsxs)(`a`,{href:e.href??`#`,onClick:n=>{n.preventDefault(),e.href&&t?.(e.href)},className:`group flex items-center justify-between gap-3 rounded-md px-2 py-2 hover:bg-muted`,children:[(0,H.jsxs)(`span`,{className:`min-w-0`,children:[(0,H.jsx)(`span`,{className:`block text-[11px] uppercase tracking-wide text-faint-foreground`,children:e.kind}),(0,H.jsx)(`span`,{className:`block truncate font-medium text-primary-text`,children:e.label}),e.meta&&(0,H.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:e.meta})]}),(0,H.jsx)(xe,{className:`size-4 shrink-0 text-faint-foreground group-hover:text-foreground`})]})},e.label))}),Ex=({title:e,children:t})=>(0,H.jsxs)(`div`,{className:`rounded-lg border border-border bg-background p-4`,children:[(0,H.jsx)(`h3`,{className:`mb-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:e}),t]}),Dx=({title:e,rows:t})=>t.length===0?null:(0,H.jsx)(Ex,{title:e,children:(0,H.jsx)(wx,{rows:t})}),Ox=({collection:e,title:t,titleHidden:n,status:r,lastEditedBy:i,presence:a=[],actions:o})=>n&&!e&&!r&&!i&&a.length===0&&!o?(0,H.jsx)(`h1`,{className:`sr-only`,children:t}):(0,H.jsxs)(`header`,{className:`flex flex-col gap-4 border-b border-border pb-6 md:flex-row md:items-end md:justify-between md:gap-6`,children:[(0,H.jsxs)(`div`,{children:[e&&(0,H.jsx)(`p`,{className:`mb-1 text-xs text-muted-foreground`,children:e}),(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,H.jsx)(`h1`,{className:n?`sr-only`:`text-xl font-semibold tracking-tight text-foreground md:text-2xl`,children:t}),r&&(0,H.jsx)(Xu,{tone:r.tone,children:r.label})]}),i&&(0,H.jsx)(`p`,{className:`mt-1.5 text-xs text-muted-foreground`,children:i.name?(0,H.jsxs)(H.Fragment,{children:[`Last edited by `,(0,H.jsx)(`span`,{className:`font-medium text-foreground`,children:i.name}),` `,i.ago]}):(0,H.jsxs)(H.Fragment,{children:[`Last updated `,i.ago]})})]}),(0,H.jsxs)(`div`,{className:`flex items-center gap-4`,children:[a.length>0&&(0,H.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,H.jsx)(Hu,{people:a,size:`md`}),a.length,` viewing`]}),o]})]}),kx=({rows:e})=>(0,H.jsx)(`dl`,{className:`border-t border-border`,children:e.map(e=>(0,H.jsxs)(`div`,{className:V(`grid gap-x-4 border-b border-border py-2.5`,e.wide?`grid-cols-1 gap-y-1.5`:`grid-cols-[minmax(0,2fr)_minmax(0,3fr)]`),children:[(0,H.jsxs)(`dt`,{className:`min-w-0 text-muted-foreground`,children:[e.label,e.help&&(0,H.jsx)(`span`,{className:`mt-0.5 block text-xs text-faint-foreground`,children:e.help})]}),(0,H.jsx)(`dd`,{className:`min-w-0 break-words text-foreground`,children:e.value})]},e.label))}),Ax=({facts:e})=>(0,H.jsx)(`dl`,{className:`grid grid-cols-2 gap-x-4 gap-y-5 sm:flex sm:flex-wrap sm:gap-x-10`,children:e.map(({label:e,value:t,icon:n})=>(0,H.jsxs)(`div`,{title:e,className:`flex min-w-0 flex-col gap-1.5`,children:[(0,H.jsx)(`dt`,{className:`text-muted-foreground`,children:n?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(n,{className:`size-5`,"aria-hidden":!0}),(0,H.jsx)(`span`,{className:`sr-only`,children:e})]}):e}),(0,H.jsx)(`dd`,{className:`min-w-0 break-words text-[16px] font-semibold text-foreground`,children:t})]},e))}),jx=e=>typeof e==`object`&&!!e&&typeof e.uri==`string`,Mx=e=>typeof e==`object`&&!!e&&typeof e.uploaded?.value==`string`,Nx=e=>{if(Mx(e))return{...e.uploaded.file,...e.preview&&{url:e.preview},corrected:e.uploaded.corrected};if(jx(e))return`missing`in e?{name:`File missing`,type:``,missing:!0}:e},Px=[`bytes`,`kB`,`MB`,`GB`],Fx=e=>{let t=e,n=0;for(;t>=1e3&&n<Px.length-1;)t/=1e3,n+=1;return n===0?`${e} ${e===1?`byte`:`bytes`}`:`${t<10?t.toFixed(1):Math.round(t)} ${Px[n]}`},Ix=e=>e.startsWith(`image/`)&&e!==`image/svg+xml`,Lx=2,Rx=1e5,zx=(e,t)=>(e.width!==void 0||e.height!==void 0)&&(e.width??Rx)>=t.width*Lx&&(e.height??Rx)>=t.height*Lx,Bx=e=>(e.width??Rx)*(e.height??Rx),Vx=(e,t)=>{let n=Nx(e);if(!(!n||`missing`in n||!n.url||!Ix(n.type)))return{url:(`variants`in n&&n.variants?Object.values(n.variants):[]).filter(e=>zx(e,t)).sort((e,t)=>Bx(e)-Bx(t))[0]?.url??n.url,...`placeholder`in n&&n.placeholder!==void 0&&{placeholder:n.placeholder}}},Hx=e=>{let t=e.file?.accept??[];return t.length===0||t.includes(`*/*`)?void 0:t.join(`,`)},Ux=e=>Mx(e)?e.uploaded.value:jx(e)?e.uri:null,Wx=(e,t)=>{if(Mx(e))return!0;let n=e=>jx(e)?e.uri:null;return n(e)!==n(t)},Gx=e=>e==null?``:typeof e==`object`?JSON.stringify(e):String(e),Kx=new Set([`text`,`integer`,`bigint`,`decimal`,`date`,`currency`,`country`]),qx=e=>!e.readOnly&&e.type!==`json`&&e.type!==`uuid`&&e.type!==`timestamp`&&e.type!==`relation`,Jx=e=>!e.readOnly&&!e.nullable&&e.type!==`boolean`,Yx=(e,t)=>{if(e.type===`boolean`)return!!t;if(e.type===`file`)return Ux(t);let n=String(t).trim();if(n===``)return e.nullable?null:``;if(e.type===`integer`)return Number(n);if(e.type===`relation`)return typeof t==`number`?t:n;if(Kx.has(e.type)||e.type===`enum`)return n;throw Error(`Not implemented: editing ${e.type} fields`)},Xx=(e,t)=>e.type===`boolean`?!!t:String(t??``).trim()===``?null:Yx(e,t),Zx=(e,t)=>e.type===`boolean`?!!t:Gx(t),Qx=(e,t,n)=>{if(e.type===`boolean`)return!!t!=!!n;if(e.type===`file`)return Wx(t,n);let r=String(t??``).trim(),i=Gx(n);return e.type===`decimal`||e.type===`integer`?r===``||i===``?r!==i:Number(r)!==Number(i):r!==i},$x=(e,t,n)=>t?e===void 0||e===`edit`||n?{shown:`form`,offersEdit:!1,editing:!0}:{shown:e,offersEdit:t,editing:!1}:{shown:`read`,offersEdit:!1,editing:!1},eS=(e,t,n)=>(e??t?.helpWhen??`always`)===`always`||n,tS=(e,t,n)=>e?.help!==void 0&&eS(e.helpWhen,t,n)?e.help:void 0,nS=(e,t)=>e===`editing`?t:e!==`reading`||!t,rS=e=>typeof e==`object`&&!!e&&`key`in e,iS=(e,t)=>t.name!==e.tenant&&!t.readOnly&&(t.type===`relation`||qx(t)),aS=(e,t)=>{let n=Object.values(e.fields).filter(t=>iS(e,t)).map(e=>e.name),r=new Set,i=(t?.layout??[]).flatMap(e=>{if(e.kind!==`section`||!nS(e.when,!0))return[];let i=e.fields.filter(e=>n.includes(e)&&!r.has(e)&&nS(t?.fields[e]?.when,!0));return i.forEach(e=>r.add(e)),i.length>0?[{title:e.title,help:e.help,fields:i}]:[]}),a=n.filter(e=>!r.has(e));return a.length===0?i:[...i,{title:i.length===0?`Details`:`Other fields`,fields:a}]},oS=(e,t)=>(e?.primaryKey.length===1?e.fields[e.primaryKey[0]]?.type:void 0)===`integer`?Number(t):t,sS=(e,t,n)=>Object.fromEntries(Object.entries(n).flatMap(([n,r])=>{let i=e.fields[n];return i?rS(r)?[[n,oS(t[i.relation?.resource??``],r.key)]]:i.type===`boolean`?[[n,!!r]]:i.type===`file`?r?[[n,Yx(i,r)]]:[]:String(r).trim()===``?[]:[[n,Yx(i,r)]]:[]})),cS=e=>!e.nullable&&!e.default&&e.type!==`boolean`,lS=(e,t)=>e.type===`relation`?{key:t,label:t}:e.type===`boolean`?t===`true`:t,uS=(e,t,n={})=>Object.fromEntries(t.flatMap(t=>t.fields.flatMap(t=>{let r=e.fields[t];if(Object.hasOwn(n,t))return[[t,lS(r,n[t])]];let i=r.default;return!i||!(`value`in i)||i.value===null||i.value===void 0?[]:[[t,typeof i.value==`boolean`?i.value:String(i.value)]]}))),dS=e=>!!(e.default&&`db`in e.default),fS=e=>{if(!Fs(e))return[{message:e instanceof Error?e.message:`Something went wrong`}];let t=e.errors.map(e=>({message:e.message,hint:e.hint}));return t.length>0?t:[{message:e.message}]},pS=({error:e,title:t})=>(0,H.jsxs)(`div`,{role:`alert`,className:`flex gap-2.5 rounded-lg border border-danger/30 bg-danger-soft px-3 py-2 text-danger-text`,children:[(0,H.jsx)(Bn,{className:`mt-0.5 size-4 shrink-0`}),(0,H.jsxs)(`div`,{children:[(0,H.jsx)(`p`,{className:`font-medium`,children:t}),fS(e).map(e=>(0,H.jsxs)(`p`,{className:`text-xs`,children:[e.message,e.hint&&(0,H.jsxs)(`span`,{className:`text-muted-foreground`,children:[` `,e.hint]})]},e.message))]})]}),mS=({checked:e,onChange:t,label:n})=>{let r=Cd();return(0,H.jsx)(`button`,{type:`button`,role:`switch`,id:r.id,"aria-describedby":r[`aria-describedby`],"aria-checked":e,"aria-label":n,onClick:()=>t?.(!e),className:V(`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors`,e?`bg-primary`:`bg-border-strong`),children:(0,H.jsx)(`span`,{className:V(`size-4 rounded-full bg-white shadow transition-transform`,e?`translate-x-[18px]`:`translate-x-0.5`)})})},hS=e=>{e.style.height=`auto`,e.style.height=`${e.scrollHeight+e.offsetHeight-e.clientHeight}px`},gS=({invalid:e,className:t,rows:n=3,value:r,...i})=>{let a=(0,o.useRef)(null),s=Cd();return(0,o.useLayoutEffect)(()=>{a.current&&hS(a.current)},[r]),(0,o.useEffect)(()=>{let e=a.current;if(!e)return;let t=e.clientWidth,n=new ResizeObserver(()=>{e.clientWidth!==t&&(t=e.clientWidth,hS(e))});return n.observe(e),()=>n.disconnect()},[]),(0,H.jsx)(`textarea`,{ref:a,rows:n,value:r,className:V(`block w-full resize-none overflow-hidden rounded-md border bg-background px-2.5 py-1.5 text-body text-foreground shadow-sm outline-none placeholder:text-faint-foreground focus:border-primary focus:ring-2 focus:ring-primary/20`,e?`border-danger`:`border-border-strong`,t),...s,...e&&{"aria-invalid":!0},...i})},_S=e=>typeof e==`object`&&e&&`name`in e?String(e.name):String(e),vS=(e,t)=>{if(t==null)return`—`;switch(e.kind){case`text`:case`id`:return String(t);case`money`:return`${nf(Number(t),e.currency,e.decimals)}${e.suffix??``}`;case`date`:return ff(Number(t));case`datetime`:return mf(Number(t));case`number`:return`${af(Number(t))}${e.suffix??``}`;case`signed`:return`${of(Number(t))}${e.suffix??``}`;case`percent`:return Number(t)===0?`—`:sf(Number(t));case`status`:return rs(String(t),e.labels);case`relation`:return _S(t);case`boolean`:return t?void 0:`No`;case`file`:return Nx(t)?.name??`—`;case`user`:return tx(String(t)).name}},yS=(e,t)=>Math.ceil(e.length*7.2)+24+(t?16:0)+28,bS=e=>Math.ceil(Math.max(0,...e.map(e=>e.length))*7.2)+56,xS={body:7.5,mono:7.2,numeric:8},SS=24,CS=24,wS=16,TS=new Set([`status`,`money`,`number`,`signed`,`percent`,`date`,`datetime`,`boolean`]),ES=new Set([`money`,`number`,`signed`,`percent`,`date`,`datetime`]),DS=80,OS=400,kS=240,AS=e=>e===`id`?xS.mono:ES.has(e)?xS.numeric:xS.body,jS=(e,t)=>e.value?e.value(t):t[e.id],MS=(e,t)=>{let n=t.map(t=>vS(e,jS(e,t)));if(e.kind===`status`)return bS(n.map(e=>e??``));let r=e.kind===`user`||e.kind===`file`?CS:0;return Math.max(0,...n.map(t=>t===void 0?wS:Math.ceil(t.length*AS(e.kind))))+r+SS},NS=(e,t,n)=>Math.min(n,Math.max(t,e)),PS=(e,t)=>{if(TS.has(e.kind)&&!e.title)return{...e,fixed:!0,width:Math.max(e.minWidth??0,t)};let n={...e,fixed:!1,width:NS(t,DS,OS)};return e.kind===`id`?{...n,minWidth:Math.max(yS(e.header,e.sortable??!1),Math.min(t,kS))}:n},FS=(e,t)=>{if(t.length===0)return e;let n=e.map(e=>e.render?e:PS(e,MS(e,t))),r=n.filter((t,n)=>!t.fixed&&!t.title&&!e[n].render).map(e=>e.width),i=Math.max(0,...r);return n.map((t,n)=>t.title&&!e[n].render?{...t,width:Math.max(t.width,i)}:t)},IS=[[/^\s*(```|~~~).*$/,``],[/^\s*\[[^\]]+\]:\s+\S.*$/,``],[/^\s*([-*_]\s*){3,}$/,``],[/^\s*\|?(\s*:?-+:?\s*\|)+\s*:?-*:?\s*$/,``],[/^\s*#{1,6}\s+/,``],[/^\s*(>\s?)+/,``],[/^\s*([-*+]|\d+[.)])\s+(\[[ xX]\]\s+)?/,``]],LS=[[/!\[([^\]]*)\]\([^)]*\)/g,`$1`],[/\[([^\]]*)\]\([^)]*\)/g,`$1`],[/\[([^\]]+)\]\[[^\]]*\]/g,`$1`],[/<((?:https?|mailto):[^>\s]+)>/gi,`$1`],[/<\/?[a-z][^>]*>/gi,``],[/`([^`]+)`/g,`$1`],[/(?<!\\)(\*\*|__)(?=\S)(.+?)(?<=\S)\1/g,`$2`],[/(?<![\\\w*])\*(?=\S)(.+?)(?<=\S)\*/g,`$1`],[/(?<![\\\w])_(?=\S)(.+?)(?<=\S)_(?!\w)/g,`$1`],[/(?<!\\)~~(.+?)~~/g,`$1`],[/\s*\|\s*/g,` `],[/\\([\\`*_{}[\]()#+\-.!>~|])/g,`$1`]],RS=200,zS=e=>{let t=e.split(/\r?\n/).map(e=>IS.reduce((e,[t,n])=>e.replace(t,n),e)),n=LS.reduce((e,[t,n])=>e.replace(t,n),t.join(`
|
|
13
|
+
`)).replace(/\s+/g,` `).trim();return n.length>RS?`${n.slice(0,199).trimEnd()}…`:n},BS=(e,t)=>e.type===`text`&&!!t?.markdown,VS={draft:`neutral`,confirmed:`blue`,picking:`amber`,shipped:`violet`,delivered:`green`,cancelled:`red`,sent:`blue`,paid:`green`,overdue:`red`,lead:`blue`,active:`green`,dormant:`neutral`,receipt:`green`,issue:`blue`,transfer:`violet`,adjustment:`amber`},HS=e=>VS[e]??`neutral`,US={text:200,id:140,money:120,date:110,datetime:170,status:150,relation:200,boolean:64,number:100,signed:110,percent:110,user:130,file:180},WS=new Set([`datetime`,`date`,`boolean`,`percent`]),GS=/^(number|sku|reference|code)$/,KS=(e,t,n)=>{switch(e.type){case`relation`:return`relation`;case`file`:return`file`;case`enum`:return`status`;case`boolean`:return`boolean`;case`timestamp`:return`datetime`;case`date`:return`date`;case`decimal`:return t?.format===`percent`?`percent`:t?.prefix===`€`?`money`:`number`;case`integer`:case`bigint`:return/quantity|delta/.test(e.name)?`signed`:`number`;default:return GS.test(e.name)||n===0&&e.name===`id`?`id`:`text`}},qS=e=>Math.round(Number.parseFloat(String(e))*100),JS=(e,t)=>t?.list?.columns??Object.keys(e.fields).slice(0,6),YS=(e,t,n=[],r=JS(e,t))=>{let i=Eg(e,t);return r.flatMap((r,a)=>{let o=e.fields[r];if(!o)return[];let s=t?.fields[r],c=KS(o,s,a),l=Object.fromEntries((o.enumValues??[]).map(e=>[e,rs(e,s?.valueLabels)])),u=s?.suffix?Math.ceil(s.suffix.length*7.2):0;return[{id:r,header:s?.label??q(r),kind:c,width:(r===`name`?260:US[c])+u,sortable:o.sortable,minWidth:Math.max(c===`id`?150:0,yS(s?.label??q(r),o.sortable),c===`status`?bS(Object.values(l)):0,u>0?US[c]+u:0),...WS.has(c)&&{fixed:!0},...r===i&&{title:!0},...n.includes(r)&&{highlight:!0},...o.type===`enum`&&{tones:Object.fromEntries((o.enumValues??[]).map(e=>[e,HS(e)])),labels:l},...o.type===`enum`&&s?.valueColors&&{colors:s.valueColors},...o.type===`enum`&&s?.badgeShape&&{shape:s.badgeShape},...s?.suffix!==void 0&&{suffix:s.suffix},...c===`money`&&s?.decimals!==void 0&&{decimals:s.decimals},...c===`money`&&{currency:`EUR`,value:e=>e[r]==null?null:qS(e[r])},...(c===`datetime`||c===`date`)&&{value:e=>e[r]==null?null:Date.parse(String(e[r]))},...BS(o,s)&&{value:e=>typeof e[r]==`string`?zS(e[r]):e[r]},...(c===`percent`||c===`number`&&o.type===`decimal`)&&{value:e=>e[r]==null?null:Number(e[r])}}]})},XS=(e,t)=>`${t.prefix??``}${e}${t.suffix??``}`,ZS=(e,t,n={})=>{if(t==null||t===``)return`—`;switch(e.type){case`boolean`:return t?`Yes`:`No`;case`file`:return Nx(t)?.name??`—`;case`enum`:return rs(String(t),n.valueLabels);case`timestamp`:return mf(Date.parse(String(t)));case`date`:return ff(Date.parse(String(t)));case`decimal`:{let e=n.decimals===void 0?String(t):Number(t).toFixed(n.decimals);return n.format===`percent`?`${Number(t)}%`:XS(Number(e).toLocaleString(`en-IE`,{minimumFractionDigits:n.decimals??0,maximumFractionDigits:n.decimals??20}),n)}case`integer`:case`bigint`:return XS(String(t),n);default:return typeof t==`object`?JSON.stringify(t):String(t)}},QS=`$photos`,$S=e=>{for(let t of e?.list?.displays??[])if(t.kind===`cards`&&t.photos)return t.photos},eC=(e,t,n)=>{if(n===void 0||e.primaryKey.length!==1)return t;let r=e.primaryKey[0];return t.map(e=>({...e,[QS]:n[String(e[r])]??[]}))},tC=(e,t)=>t.filter(t=>e[t]!==null&&e[t]!==void 0&&e[t]!==``),nC=(e,t,n)=>{let r=e.fields[n.by];if(!r)return[];let i=t?.fields[n.by],a=(r.enumValues??[]).map(e=>({value:e,label:rs(e,i?.valueLabels)}));return r.nullable?[...a,{value:null,label:`No ${(i?.label??q(n.by)).toLowerCase()}`}]:a},rC=(e,t,n)=>{let r=Ya(n===null?fo.isNull(t):fo.eq(t,n));return e===``?r:`(${e}) AND ${r}`},iC=(e,t,n)=>({kind:`cards`,name:n.name,title:n.title??Eg(e,t),...n.subtitle!==void 0&&{subtitle:n.subtitle},...n.badge!==void 0&&{badge:n.badge},...n.meta&&{meta:n.meta}}),aC=e=>{if(!Fs(e))return e instanceof Error?e.message:`Something went wrong`;let t=e.errors.map(e=>e.message);return t.length>0?t.join(`; `):e.message},oC=e=>e?.list?.displays??[],sC=(e,t,n)=>{let r=n??e?.list?.default??`table`;if(!t)return r;let i=oC(e).filter(e=>e.kind===`cards`);return i.find(e=>e.name===r)?.name??i[0]?.name??r},cC=`rows`,lC=(e,t)=>{if(oC(t).some(e=>e.kind===`cards`||e.name===`rows`))return;let n=Eg(e,t),r=JS(e,t).filter(t=>t!==n&&e.fields[t]!==void 0),i=r.find(t=>e.fields[t].type===`enum`),a=r.filter(t=>t!==i&&e.fields[t].type!==`boolean`).slice(0,2);return{kind:`cards`,name:cC,label:`List`,icon:`list`,title:n,...i!==void 0&&{badge:i},footer:a}},uC=(e,t)=>t.name===`rows`&&!oC(e).some(e=>e.name===`rows`),dC=(e,t,n)=>{let r=sC(t,n);return n&&r===`table`&&lC(e,t)?cC:r},fC=(e,t,n)=>(n===`rows`?lC(e,t):void 0)??pC(t,n),pC=(e,t)=>{if(t===`table`)return;let n=t=>oC(e).find(e=>e.name===t);return n(t)??n(e?.list?.default)},mC={cards:`cards`,map:`map`,board:`kanban`},hC=e=>[{name:go,label:`Table`,icon:`table`},...oC(e).map(e=>({name:e.name,label:e.label??q(e.name),icon:e.icon??mC[e.kind]}))],gC=(e,t,n)=>{let r=hC(t);return n&&lC(e,t)?[...r,{name:cC,label:`List`,icon:`list`}]:r},_C=(e,t,n)=>({image:n.image,title:n.title??Eg(e,t),subtitle:n.subtitle,amount:n.amount??[],badge:n.badge,meta:n.meta??[],footer:n.footer??[],flags:n.flags??[]}),vC=(e,t)=>tC(e.record,t),yC=(e,t)=>vC(e,t)[0],bC=(e,t,n={})=>{let{suffix:r,...i}=n;return e.type!==`decimal`&&e.type!==`integer`&&e.type!==`bigint`||r===void 0||n.format===`percent`?{amount:ZS(e,t,n)}:{amount:ZS(e,t,i),suffix:r}},xC=(e,t)=>{let n=oC(e).filter(e=>e.kind===`cards`);return(t.cards===void 0?n[0]:n.find(e=>e.name===t.cards))??{kind:`cards`,name:t.name}},SC=(e,t,n)=>{if(n.kind===`custom`)return n.fields;if(n.kind===`map`)return[n.latitude,n.longitude,...SC(e,t,xC(t,n))];if(n.kind===`board`){let r=iC(e,t,n);return[n.by,r.title,r.subtitle,r.badge,...r.meta??[]].filter(e=>e!==void 0)}let{image:r,title:i,subtitle:a,amount:o,badge:s,meta:c,footer:l,flags:u}=_C(e,t,n);return[r,i,a,...o,s,...c,...l,...u].filter(e=>e!==void 0)},CC=(e,t,n)=>{let r=lC(e,t),i=r?[...oC(t),r]:oC(t);return[...new Set([...n,...i.flatMap(n=>SC(e,t,n))])]},wC=(e,t,n)=>{let r=uC(t,n)?[Eg(e,t),...JS(e,t)]:SC(e,t,n);return[...new Set(r)].filter(t=>e.fields[t]?.sortable)},TC=e=>typeof e==`object`&&!!e&&`id`in e&&`name`in e,EC=(e,t)=>{let n={},r={},i=Array.isArray(t.$photos)?t[QS]:void 0;for(let[i,a]of Object.entries(t))(i!==`id`&&i!==`$photos`||Object.hasOwn(e.fields,i))&&(e.fields[i]?.type===`relation`&&TC(a)?(n[i]=a.id,r[i]=a.name):n[i]=a);return{key:Ao(Ag(e,n)),record:n,labels:r,...i&&{photos:i}}},DC=(e,t)=>{let n=t?.list?.sort?.[0];return n?`${n[0]} ${n[1]}`:`${e.primaryKey[0]} asc`},OC=e=>{let[t=``,n]=e.trim().split(/\s+/);return{columnId:t,direction:n===`desc`?`desc`:`asc`}},kC=e=>`${e.columnId} ${e.direction}`,AC=(e,t,n)=>{let r=e[n],i=t[n]?.listOf,a=i===void 0?void 0:r?.fields[i]?.relation?.resource;return a!==void 0&&e[a]?{model:e[a],view:t[a],listOf:!0}:{model:r,view:t[n],listOf:!1}},jC=(e,t,n=!1)=>({display:e?dC(e,t,n):sC(t,n),orderBy:e?DC(e,t):``,filterLayout:`bar`}),MC=(e,t)=>e?.kind===`record`?{kind:`record`,resource:e.resource,key:Ao(e.key),...e.edit&&{edit:!0}}:e?.kind===`list`?{...t(e.resource),filter:``,...e}:e,NC=(e,t,n)=>{let r={...e,...t},i=e=>r[e]!==void 0&&r[e]!==n[e];return{kind:`list`,resource:e.resource,...r.filter&&{filter:r.filter},...i(`display`)&&{display:r.display},...i(`orderBy`)&&{orderBy:r.orderBy},...i(`filterLayout`)&&{filterLayout:r.filterLayout},...r.map&&{map:r.map},...r.savedSearch&&{savedSearch:r.savedSearch}}},PC=()=>{let{path:e,params:t,basePath:n,navigate:r}=Dh(),{pages:i,resources:a,views:s}=J(),c=mu(),l=(0,o.useMemo)(()=>new Set(Object.keys(i)),[i]),u=t.toString(),d=(0,o.useMemo)(()=>ms(u?`${e}?${u}`:e,l),[e,u,l]),f=(0,o.useCallback)(e=>{let t=AC(a,s,e);return jC(t.model,t.view,c)},[a,s,c]),p=(0,o.useMemo)(()=>MC(d,f),[d,f]),m=(0,o.useCallback)((e,t)=>r(us(e),t),[r]);return{address:p,set:(0,o.useCallback)(e=>{if(d?.kind!==`list`)throw Error(`set changes the list the app shows; use go to move to another address`);m(NC(d,e,f(d.resource)),{replace:!0})},[d,f,m]),go:m,href:(0,o.useCallback)(e=>us(e,n),[n]),open:(0,o.useCallback)(e=>r(e.startsWith(`${n}/`)?e.slice(n.length):e),[n,r])}},FC=({to:e,...t})=>(0,H.jsx)(one,{to:us(e),...t}),IC=(e,{filter:t,orderBy:n,pageSize:r=50,fields:i,startToken:a=``,enabled:o=!0}={})=>{let s=K(),c=Ss(t)??``,l=yh({queryKey:[...G.list(e,c,n??``,r,a),i?.join(`,`)??``],enabled:o,initialPageParam:a,queryFn:({pageParam:t})=>s.list(e,{filter:c,orderBy:n,pageSize:r,fields:i,pageToken:t}),getNextPageParam:e=>e.nextPageToken||void 0}),u=l.data?.pages??[];return{...l,items:u.flatMap(e=>e.items),totalEstimate:u[0]?.totalSizeEstimate}},LC=uo(),RC=e=>e.split(/\s+/).filter(Boolean),zC=(e,t,n,r=!1)=>{let i=RC(n);if(i.length===0)return{filter:void 0,local:!1};if(r)return{filter:void 0,local:!0};if(e.search?.length)return{filter:Ya(LC.search(n)),local:!1};let a=e.fields[t];if(a?.type!==`text`||!a.filterable)return{filter:void 0,local:!0};let o=i.map(e=>LC.eq(t,`*${e.replaceAll(`*`,``)}*`));return{filter:Ya(LC.and(...o)),local:!1}},BC=(e,t)=>{if(e==null)return!1;let n=String(e).toLowerCase();return RC(t).every(e=>n.includes(e.toLowerCase()))},VC=(e,t,n,r)=>{(0,o.useEffect)(()=>{if(!e||!t)return;let n=new IntersectionObserver(e=>e.some(e=>e.isIntersecting)&&r(),{root:e});return n.observe(t),()=>n.disconnect()},[e,t,n,r])},HC=({target:e,view:t,value:n,label:r,invalid:i,onChange:a})=>{let[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(!1),[d,f]=(0,o.useState)(-1),[p,m]=(0,o.useState)(null),[h,g]=(0,o.useState)(null),_=(0,o.useId)(),v=e.primaryKey[0],y=Tg(e,t),[b,x]=(0,o.useState)(!1),S=zC(e,y,s,b),C=IC(e.name,{filter:S.filter,fields:[v,y],enabled:l}),w=S.filter!==void 0&&C.error instanceof Ns&&C.error.slug===`expensive-query`;(0,o.useEffect)(()=>{w&&x(!0)},[w]);let T=S.local?C.items.filter(e=>BC(e[y],s)):C.items,E=!!C.hasNextPage,D=C.isPending||C.isFetchingNextPage,{fetchNextPage:O}=C;VC(p,h,C.items.length,(0,o.useCallback)(()=>O({cancelRefetch:!1}),[O]));let k=e=>`${_}-${e}`,A=(0,o.useRef)(null);(0,o.useEffect)(()=>{!l&&document.activeElement===A.current&&A.current?.select()},[l]),(0,o.useEffect)(()=>{l&&d>=0&&document.getElementById(k(d))?.scrollIntoView({block:`nearest`})});let j=()=>{c(``),f(-1),u(!1)},M=e=>{a(String(e[v]),String(e[y])),j()};return(0,H.jsxs)(`div`,{className:`relative`,children:[(0,H.jsx)(wd,{ref:A,role:`combobox`,"aria-autocomplete":`list`,"aria-expanded":l,"aria-controls":_,"aria-activedescendant":l&&T[d]?k(d):void 0,invalid:i,placeholder:`Search ${(t?.names?.plural??q(e.name)).toLowerCase()}`,value:l?s:r??n,onFocus:()=>u(!0),onBlur:j,onKeyDown:e=>{if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(e.preventDefault(),!l)return u(!0);let t=e.key===`ArrowDown`?1:-1;f(e=>Math.min(Math.max(e+t,0),T.length-1));return}if(e.key===`Enter`&&l&&T[d]){e.preventDefault(),M(T[d]);return}e.key===`Escape`&&l&&(e.preventDefault(),e.stopPropagation(),j())},onChange:e=>{c(e.target.value),f(e.target.value.trim()?0:-1),u(!0)}}),l&&(0,H.jsxs)(`ul`,{ref:m,id:_,role:`listbox`,className:`absolute z-30 mt-1 max-h-60 w-full overflow-y-auto rounded-md border bg-background py-1 shadow-pop`,onMouseDown:e=>e.preventDefault(),children:[T.map((e,t)=>(0,H.jsx)(`li`,{id:k(t),role:`option`,"aria-selected":t===d,className:V(`cursor-pointer truncate px-3 py-1.5`,t===d&&`bg-muted`,String(e[v])===n&&`font-medium`),onMouseMove:()=>t!==d&&f(t),onClick:()=>M(e),children:String(e[y])},String(e[v]))),E&&(0,H.jsx)(`li`,{ref:g,"aria-hidden":!0,className:`h-px`}),C.error&&!w&&(0,H.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`Could not load the options`}),!E&&!D&&!C.error&&T.length===0&&(0,H.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`No matches`}),D&&(0,H.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`Loading`})]})]})},UC=`••••••••••`,WC=({field:e,hints:t,value:n,reveal:r,locked:i,invalid:a,placeholder:s,onChange:c})=>{let[l,u]=(0,o.useState)(!1),d=vh({mutationFn:async()=>r(),onSuccess:()=>u(!0)}),f=Gx(n)!==``,p=t?.label??q(e.name),m=(0,H.jsx)(W,{variant:`ghost`,size:`sm`,className:`-mr-1.5 px-1.5`,"aria-label":`${l?`Hide`:`Show`} ${p}`,"aria-pressed":l,loading:d.isPending,onClick:()=>{l||f||!r||d.isSuccess?u(!l):d.mutate()},children:!d.isPending&&(l?(0,H.jsx)(Xe,{className:`size-3.5`}):(0,H.jsx)(Qe,{className:`size-3.5`}))}),h=d.error&&(0,H.jsx)(`div`,{className:`mt-2`,children:(0,H.jsx)(pS,{title:`Could not show the ${p}`,error:d.error})});if(i)return(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2 py-1`,children:[(0,H.jsx)(`span`,{className:V(l?t?.format===`code`?`font-mono text-xs`:``:`tracking-widest text-muted-foreground`),children:l?ZS(e,d.data,t):UC}),r&&m]}),h]});let g=f?Gx(n):l&&d.isSuccess?Gx(d.data):``;return(0,H.jsxs)(`div`,{children:[(0,H.jsx)(wd,{type:l?`text`:`password`,autoComplete:`off`,invalid:a,"aria-label":p,className:V(t?.format===`code`&&`font-mono text-xs`),placeholder:f||!r?s:UC,value:g,trailing:m,onChange:e=>c(e.target.value)}),h]})};function GC(e){let{PI:t,min:n,max:r,cos:i,round:a}=Math,o=e[0]|e[1]<<8|e[2]<<16,s=e[3]|e[4]<<8,c=(o&63)/63,l=(o>>6&63)/31.5-1,u=(o>>12&63)/31.5-1,d=(o>>18&31)/31,f=o>>23,p=(s>>3&63)/63,m=(s>>9&63)/63,h=s>>15,g=r(3,h?f?5:7:s&7),_=r(3,h?s&7:f?5:7),v=f?(e[5]&15)/15:1,y=(e[5]>>4)/15,b=f?6:5,x=0,S=(t,n,r)=>{let i=[];for(let a=0;a<n;a++)for(let o=+!a;o*n<t*(n-a);o++)i.push(((e[b+(x>>1)]>>((x++&1)<<2)&15)/7.5-1)*r);return i},C=S(g,_,d),w=S(3,3,p*1.25),T=S(3,3,m*1.25),E=f&&S(5,5,y),D=KC(e),O=a(D>1?32:32*D),k=a(D>1?32/D:32),A=new Uint8Array(O*k*4),j=[],M=[];for(let e=0,a=0;e<k;e++)for(let o=0;o<O;o++,a+=4){let s=c,d=l,p=u,m=v;for(let e=0,n=r(g,f?5:3);e<n;e++)j[e]=i(t/O*(o+.5)*e);for(let n=0,a=r(_,f?5:3);n<a;n++)M[n]=i(t/k*(e+.5)*n);for(let e=0,t=0;e<_;e++)for(let n=+!e,r=M[e]*2;n*_<g*(_-e);n++,t++)s+=C[t]*j[n]*r;for(let e=0,t=0;e<3;e++)for(let n=+!e,r=M[e]*2;n<3-e;n++,t++){let e=j[n]*r;d+=w[t]*e,p+=T[t]*e}if(f)for(let e=0,t=0;e<5;e++)for(let n=+!e,r=M[e]*2;n<5-e;n++,t++)m+=E[t]*j[n]*r;let h=s-2/3*d,y=(3*s-h+p)/2,b=y-p;A[a]=r(0,255*n(1,y)),A[a+1]=r(0,255*n(1,b)),A[a+2]=r(0,255*n(1,h)),A[a+3]=r(0,255*n(1,m))}return{w:O,h:k,rgba:A}}function KC(e){let t=e[3],n=e[2]&128,r=e[4]&128;return(r?n?5:7:t&7)/(r?t&7:n?5:7)}function qC(e,t,n){let r=e*4+1,i=6+t*(5+r),a=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,e>>8,e&255,0,0,t>>8,t&255,8,6,0,0,0,0,0,0,0,i>>>24,i>>16&255,i>>8&255,i&255,73,68,65,84,120,1],o=[0,498536548,997073096,651767980,1994146192,1802195444,1303535960,1342533948,-306674912,-267414716,-690576408,-882789492,-1687895376,-2032938284,-1609899400,-1111625188],s=1,c=0;for(let e=0,i=0,o=r-1;e<t;e++,o+=r-1)for(a.push(e+1<t?0:1,r&255,r>>8,~r&255,r>>8^255,0),c=(c+s)%65521;i<o;i++){let e=n[i]&255;a.push(e),s=(s+e)%65521,c=(c+s)%65521}a.push(c>>8,c&255,s>>8,s&255,0,0,0,0,0,0,0,0,73,69,78,68,174,66,96,130);for(let[e,t]of[[12,29],[37,41+i]]){let n=-1;for(let r=e;r<t;r++)n^=a[r],n=n>>>4^o[n&15],n=n>>>4^o[n&15];n=~n,a[t++]=n>>>24,a[t++]=n>>16&255,a[t++]=n>>8&255,a[t++]=n&255}return`data:image/png;base64,`+btoa(String.fromCharCode(...a))}function JC(e){let t=GC(e);return qC(t.w,t.h,t.rgba)}var YC=(e,t,n)=>{if(!URL.canParse(e,t))return`no-referrer`;let r=new URL(e,t);if((r.protocol===`http:`||r.protocol===`https:`)&&!(r.origin===new URL(t).origin||n.includes(r.hostname)))return`no-referrer`},XC=e=>URL.canParse(e)?[new URL(e).hostname]:[],ZC=()=>{let e=(0,o.useContext)(c_);return(0,o.useMemo)(()=>[...e?.files?.trustedHosts??[],...(e?.sources??[]).flatMap(({source:e})=>XC(e.url))],[e?.files,e?.sources])},QC=e=>{let t;try{t=atob(e)}catch(e){if(e instanceof DOMException&&e.name===`InvalidCharacterError`)return;throw e}return JC(Uint8Array.from(t,e=>e.charCodeAt(0)))},$C=({image:e,className:t,loading:n})=>{let[r,i]=(0,o.useState)(),a=ZC(),s=(0,o.useMemo)(()=>e.placeholder===void 0?void 0:QC(e.placeholder),[e.placeholder]),c=s!==void 0&&r!==e.url;return(0,H.jsx)(`img`,{src:e.url,alt:``,loading:n,decoding:`async`,referrerPolicy:YC(e.url,window.location.href,a),onLoad:()=>i(e.url),className:t,style:c?{backgroundImage:`url("${s}")`,backgroundSize:`cover`,backgroundPosition:`center`}:void 0})},ew=({value:e})=>{let t=Vx(e,{width:40,height:40});return t?(0,H.jsx)($C,{image:t,className:`size-10 shrink-0 rounded border border-border object-cover`}):(0,H.jsx)(`span`,{className:`flex size-10 shrink-0 items-center justify-center rounded border border-border bg-muted text-muted-foreground`,children:(0,H.jsx)(it,{className:`size-4`})})},tw=({value:e})=>{let t=Nx(e);if(!t)return(0,H.jsx)(`div`,{className:`py-1.5 text-muted-foreground`,children:`—`});if(`missing`in t)return(0,H.jsx)(`div`,{className:`py-1.5 text-danger-text`,children:`The file is missing from storage`});let n=`url`in t?t.url:void 0,r=`corrected`in t?t.corrected:void 0;return(0,H.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3 py-1`,children:[(0,H.jsx)(ew,{value:e}),(0,H.jsxs)(`div`,{className:`min-w-0`,children:[n&&!n.startsWith(`blob:`)?(0,H.jsx)(`a`,{href:n,target:`_blank`,rel:`noreferrer`,className:`block truncate font-medium text-primary-text hover:underline`,children:t.name}):(0,H.jsx)(`span`,{className:`block truncate font-medium`,children:t.name}),(0,H.jsxs)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:[t.type,t.size!==void 0&&` · ${Fx(t.size)}`,r&&` · sent as ${r.from}`]})]})]})},nw=({field:e,hints:t,resource:n,value:r,locked:i,invalid:a,onChange:s})=>{let c=K(),l=(0,o.useRef)(null),[u,d]=(0,o.useState)(),[f,p]=(0,o.useState)(!1),m=t?.label??q(e.name),h=vh({mutationFn:async t=>{d(0);let r=await c.upload(n,e.name,t,{onProgress:(e,t)=>d(t>0?e/t:0)});return{uploaded:r,...Ix(r.file.type)&&{preview:URL.createObjectURL(t)}}},onSuccess:e=>s(e),onSettled:()=>d(void 0)});if(i||e.readOnly)return(0,H.jsx)(tw,{value:r});let g=e=>{let t=e?.[0];t&&h.mutate(t)},_=e=>{e.preventDefault(),p(!1),g(e.dataTransfer.files)},v=(0,H.jsx)(`input`,{ref:l,type:`file`,hidden:!0,accept:Hx(e),"aria-label":`Choose a file for ${m}`,onChange:e=>g(e.target.files)}),y=h.error&&(0,H.jsx)(`div`,{className:`mt-2`,children:(0,H.jsx)(pS,{title:`Not uploaded`,error:h.error})});return h.isPending?(0,H.jsxs)(`div`,{className:`py-1.5`,role:`status`,"aria-label":`Uploading ${m}`,children:[(0,H.jsx)(`div`,{className:`h-1.5 overflow-hidden rounded-full bg-muted`,children:(0,H.jsx)(`div`,{className:`h-full rounded-full bg-primary transition-[width]`,style:{width:`${Math.round((u??0)*100)}%`}})}),(0,H.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`Uploading… `,Math.round((u??0)*100),`%`]})]}):Nx(r)?(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,H.jsx)(tw,{value:r})}),(0,H.jsx)(W,{size:`sm`,onClick:()=>l.current?.click(),children:`Replace`}),e.nullable&&(0,H.jsx)(W,{size:`sm`,variant:`ghost`,onClick:()=>s(null),children:`Remove`})]}),v,y]}):(0,H.jsxs)(`div`,{children:[(0,H.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),p(!0)},onDragLeave:()=>p(!1),onDrop:_,className:V(`flex items-center gap-3 rounded-md border border-dashed px-3 py-2.5 text-muted-foreground`,f?`border-primary bg-primary/5`:a?`border-danger`:`border-border-strong`),children:[(0,H.jsx)(Wn,{className:`size-4 shrink-0`}),(0,H.jsx)(`span`,{className:`flex-1`,children:`Drop a file here or`}),(0,H.jsxs)(W,{size:`sm`,onClick:()=>l.current?.click(),children:[(0,H.jsx)(Qt,{className:`size-3.5`}),`Choose a file`]})]}),v,y]})},rw=(e,t,n)=>{let r=n?.widget;if(!r||t.sensitive||!e||!Object.hasOwn(e,r.name))return;let i=e[r.name];return i.of.includes(t.type)?{name:r.name,widget:i,props:r.props??{}}:void 0},iw=(e,t)=>rw(Xg().fields,e,t),aw=({shown:e,part:t,field:n,value:r,onChange:i,invalid:a=!1})=>{let{widget:o,props:s}=e,c={field:n,value:r??null,props:s};if(t!==`editor`){let e=t===`cell`?o.cell??o.display:o.display;return(0,H.jsx)(e,{...c})}let l=o.editor;return l&&i?(0,H.jsx)(l,{...c,onChange:i,invalid:a}):void 0},ow=({fallback:e,...t})=>{let n=aw(t);return n?(0,H.jsx)(tg,{name:`The field type ${t.shown.name}`,fallback:e,children:n}):e},sw=(0,o.lazy)(()=>Xh(()=>import(`./markdown-content-Bg8FC_aK.js`).then(e=>({default:e.MarkdownContent})),__vite__mapDeps([0,1,2,3]))),cw=e=>(0,H.jsx)(o.Suspense,{fallback:(0,H.jsx)(`div`,{className:V(`whitespace-pre-line break-words`,e.className),children:e.source}),children:(0,H.jsx)(sw,{...e})}),lw=[{value:`write`,label:`Write`},{value:`preview`,label:`Preview`}],uw=({value:e,onChange:t,label:n,invalid:r,placeholder:i})=>{let[a,s]=(0,o.useState)(`write`);return(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`span`,{className:`self-start`,children:(0,H.jsx)($u,{value:a,options:lw,onChange:s,label:n})}),a===`write`?(0,H.jsx)(gS,{rows:5,invalid:r,placeholder:i,value:e,onChange:e=>t(e.target.value)}):(0,H.jsx)(`div`,{className:`min-h-[7.5rem] rounded-md border border-border px-2.5 py-1.5`,children:e.trim()===``?(0,H.jsx)(`span`,{className:`text-faint-foreground`,children:`Nothing to preview`}):(0,H.jsx)(cw,{source:e})})]})},dw=new Set([`integer`,`bigint`,`decimal`]),fw=e=>e===`integer`||e===`bigint`?{inputMode:`numeric`,enterKeyHint:`done`}:e===`decimal`?{inputMode:`decimal`,enterKeyHint:`done`}:{},pw=({field:e,hints:t,value:n,stored:r,relationLabel:i,relationTo:a,relationPicker:o,invalid:s,locked:c,placeholder:l,reveal:u,resource:d,onChange:f})=>{let p=Cd();if(e.type===`file`)return(0,H.jsx)(nw,{field:e,hints:t,resource:d??``,value:n,locked:c||!d,invalid:s,onChange:f});if(e.sensitive)return(0,H.jsx)(WC,{field:e,hints:t,value:n,reveal:u,locked:c||e.readOnly,invalid:s,placeholder:l,onChange:f});if(e.type===`relation`&&o&&!e.readOnly&&!c){let e=(0,H.jsx)(HC,{target:o.target,view:o.view,value:String(n),label:i,invalid:s,onChange:(e,t)=>f({key:e,label:t})});return a?(0,H.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,H.jsx)(`div`,{className:`min-w-0 flex-1`,children:e}),(0,H.jsx)(FC,{to:a,"aria-label":`Open ${i??String(n)}`,title:`Open`,className:V(xf({variant:`ghost`}),`w-8 px-0`),children:(0,H.jsx)(O,{className:`size-4`})})]}):e}if(e.type===`boolean`&&c)return(0,H.jsx)(`div`,{className:`py-1.5 text-muted-foreground`,children:ZS(e,r,t)});if(e.type===`boolean`)return(0,H.jsx)(mS,{checked:!!n,onChange:f,label:t?.label??q(e.name)});if(e.type===`relation`){let e=i??String(r??`—`);return(0,H.jsx)(`div`,{className:`py-1.5`,children:a?(0,H.jsx)(FC,{to:a,className:`font-medium text-primary-text hover:underline`,children:e}):e})}let m=!!t?.multiline&&e.type===`text`,h=BS(e,t);return(!qx(e)||c)&&h&&typeof r==`string`&&r!==``?(0,H.jsx)(cw,{source:r,className:`py-1.5`}):!qx(e)||c?(0,H.jsx)(`div`,{className:V(`py-1.5 tabular-nums`,e.type===`decimal`||e.type===`integer`?`font-medium`:`text-muted-foreground`,m&&`whitespace-pre-line break-words`),children:ZS(e,r,t)}):e.type===`enum`?(0,H.jsxs)(`select`,{...p,...s&&{"aria-invalid":!0},value:String(n),onChange:e=>f(e.target.value),className:`h-8 w-full rounded-md border border-border-strong bg-background px-2 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20`,children:[n===``&&(0,H.jsx)(`option`,{value:``,children:`Choose...`}),(e.enumValues??[]).map(e=>(0,H.jsx)(`option`,{value:e,children:rs(e,t?.valueLabels)},e))]}):h?(0,H.jsx)(uw,{label:t?.label??q(e.name),invalid:s,placeholder:l,value:String(n),onChange:f}):m?(0,H.jsx)(gS,{invalid:s,placeholder:l,value:String(n),onChange:e=>f(e.target.value)}):(0,H.jsx)(wd,{invalid:s,leading:t?.prefix?(0,H.jsx)(`span`,{children:t.prefix}):void 0,trailing:t?.suffix?(0,H.jsx)(`span`,{children:t.suffix.trim()}):void 0,placeholder:l,className:V(dw.has(e.type)&&`text-right tabular-nums`),...fw(e.type),value:String(n),onChange:e=>f(e.target.value)})},mw=e=>{let{field:t,hints:n,value:r,stored:i,invalid:a,locked:o,onChange:s}=e,c=iw(t,n),l=(0,H.jsx)(pw,{...e});return c?o||!qx(t)?(0,H.jsx)(ow,{shown:c,part:`display`,field:t,value:i,fallback:l}):t.type===`file`||t.type===`relation`?l:(0,H.jsx)(ow,{shown:c,part:`editor`,field:t,value:Xx(t,r),invalid:!!a,onChange:e=>s(Zx(t,e)),fallback:l}):l},hw={text:`text`,integer:`integer`,decimal:`decimal`,boolean:`boolean`,date:`date`},gw=e=>{let t={name:e.name,column:e.name,nullable:!0,readOnly:!1,filterable:!1,sortable:!1,aliases:[]};return e.kind===`custom`?{...t,type:`json`}:e.kind===`choice`?e.resource===void 0?{...t,type:`enum`,enumValues:(e.options??[]).map(e=>e.value)}:{...t,type:`relation`,relation:{resource:e.resource,columns:[e.name]}}:{...t,type:hw[e.kind]}},_w=e=>({label:e.label,...e.multiline&&{multiline:!0},...e.options&&{valueLabels:Object.fromEntries(e.options.map(e=>[e.value,e.label]))}}),vw=e=>Object.fromEntries(e.map(e=>e.kind===`custom`?[e.name,e.default??null]:e.kind===`boolean`?[e.name,!!e.default]:[e.name,Gx(e.default)])),yw=(e,t)=>e.kind===`custom`?t??null:rS(t)?t.key:e.resource===void 0?Yx(gw(e),t):String(t??``)===``?null:String(t),bw=(e,t)=>{let n=Object.fromEntries(e.map(e=>[e.name,yw(e,t[e.name])])),r=xo(e,n);return{shown:r,values:Object.fromEntries(Object.entries(n).filter(([e])=>r.has(e)))}},xw=/^-?\d+(\.\d+)?$/,Sw=/^\d{4}-\d{2}-\d{2}$/,Cw=(e,t)=>{if(t===null||t===``)return e.required?`Required`:void 0;if(e.kind===`integer`&&!Number.isInteger(t))return`A whole number`;if(e.kind===`decimal`&&!xw.test(String(t)))return`A number`;if(e.kind===`date`&&!Sw.test(String(t)))return`A date as YYYY-MM-DD`;if(e.max!==void 0&&String(t).length>e.max)return`At most ${e.max} characters`},ww=(e,t)=>Object.fromEntries(e.flatMap(e=>{if(!Object.hasOwn(t,e.name))return[];let n=Cw(e,t[e.name]);return n?[[e.name,n]]:[]})),Tw=class extends Error{errors;constructor(e){super(Object.values(e).join(`; `)),this.errors=e,this.name=`ActionInputError`}},Ew=(e,t)=>{let n=new Set(t.map(e=>e.name)),r=e instanceof Tw?Object.entries(e.errors):Fs(e)?e.errors.flatMap(e=>e.field?[[e.field,e.message]]:[]):[];return Object.fromEntries(r.filter(([e])=>n.has(e)))},Dw=({input:e,held:t,invalid:n,onChange:r})=>{let{resources:i,views:a}=J(),{components:o}=Xg();if(e.kind===`custom`){let i=o?.[e.component??``];if(!i)throw Error(`Input "${e.name}": the app has no component "${e.component}"`);return(0,H.jsx)(i,{input:e,value:t??null,onChange:r,invalid:n,props:e.props??{}})}let s=e.resource===void 0?void 0:i[e.resource];return(0,H.jsx)(mw,{field:gw(e),hints:_w(e),value:rS(t)?t.key:t,stored:void 0,relationLabel:rS(t)?t.label:void 0,relationPicker:s?{target:s,view:a[s.name]}:void 0,invalid:n,onChange:r})},Ow=({action:e,label:t,danger:n,onCancel:r,onSubmit:i})=>{let[a,s]=(0,o.useState)(()=>vw(e.inputs)),[c,l]=(0,o.useState)({}),[u,d]=(0,o.useState)(),[f,p]=(0,o.useState)(!1),m=(0,o.useId)(),{shown:h,values:g}=bw(e.inputs,a),_=async()=>{let t=ww(e.inputs,g);l(t),d(void 0),!(Object.keys(t).length>0)&&(p(!0),await i(g).catch(t=>{l(Ew(t,e.inputs)),d(t)}),p(!1))},v=(e,t)=>{l(({[e]:t,...n})=>n),s(n=>({...n,[e]:t}))};return(0,H.jsx)(m_,{title:t,description:e.confirm,open:!0,onClose:r,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:r,children:`Cancel`}),(0,H.jsx)(W,{variant:n?`danger`:`primary`,type:`submit`,form:m,loading:f,children:t})]}),children:(0,H.jsxs)(`form`,{id:m,className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),_()},children:[u!==void 0&&Object.keys(c).length===0&&(0,H.jsx)(pS,{title:`${t} failed`,error:u}),e.inputs.filter(e=>h.has(e.name)).map(e=>(0,H.jsx)(bx,{label:e.label,required:e.required,help:e.help,error:c[e.name],children:(0,H.jsx)(Dw,{input:e,held:a[e.name],invalid:!!c[e.name],onChange:t=>v(e.name,t)})},e.name))]})})},kw=({action:e,label:t,danger:n,onCancel:r,onConfirm:i})=>(0,H.jsx)(Sf,{title:`${t}?`,description:e.confirm,onClose:r,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:r,children:`Cancel`}),(0,H.jsx)(W,{variant:n?`danger`:`primary`,onClick:i,children:t})]})}),Aw=e=>!!(e.confirm||e.inputs?.length),jw=({action:e,label:t,danger:n,onCancel:r,onConfirm:i,onSubmit:a})=>{let{inputs:o}=e;return o?.length?(0,H.jsx)(Ow,{action:{...e,inputs:o},label:t,danger:n,onCancel:r,onSubmit:a}):(0,H.jsx)(kw,{action:e,label:t,danger:n,onCancel:r,onConfirm:i})},Mw=(0,o.createContext)(void 0),Nw=({value:e,children:t})=>(0,H.jsx)(Mw.Provider,{value:e,children:t}),Pw=()=>(0,o.useContext)(Mw),Fw=(e,t)=>e[t]||e.conditional.includes(t),Iw=(e,t)=>e.permissions?.[t]??!0,Lw=(e,t)=>e?.fields?e.fields[t]??`hidden`:`edit`,Rw=(e,t={})=>e.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(e,n)=>encodeURIComponent(t[n]===null||t[n]===void 0?``:String(t[n]))),zw=e=>{if(typeof e!=`string`||!URL.canParse(e))return;let t=new URL(e);return t.protocol===`https:`||t.protocol===`http:`?t.href:void 0},Bw=(e,t={})=>{let n=Oo(e);return n===void 0?Rw(e,t):zw(t[n])},Vw=e=>{e!==void 0&&(/^https?:/i.test(e)?window.open(e,`_blank`,`noopener,noreferrer`):window.location.assign(e))},Hw=e=>URL.canParse(e)?new URL(e).hostname.replace(/^www\./,``):``,Uw=(e,t)=>Object.entries(t).every(([t,n])=>Object.is(e[t],n)),Ww=(e,t)=>{let n=e.run;if(n?.kind===`update`)return t&&Uw(t,n.values)?void 0:e;if(n?.kind!==`link`||!(`href`in n))return e;let r=Bw(n.href,t);if(r!==void 0)return e.label.includes(`{host}`)?{...e,label:e.label.replaceAll(`{host}`,Hw(r))}:e},Gw=(e,t)=>({model:e,record:t,key:Ao(Ag(e,t)),etag:typeof t.etag==`string`?t.etag:void 0,permissions:t.permissions}),Kw=(e,t,n=``)=>({queryKey:G.count(t.name,n),queryFn:async()=>{let r=await e.list(t.name,{filter:n||void 0,pageSize:1,count:`exact`,fields:t.primaryKey});return r.totalSize??r.totalSizeEstimate}}),qw=(e,t=``)=>_h(Kw(K(),e,t)),Jw=(e,{filter:t=``,sort:n=``,key:r})=>{let i=K();return _h({queryKey:r===void 0?G.firstRecord(e.name,t,n):G.record(e.name,r),queryFn:async()=>{if(r!==void 0){let t=await i.get(e.name,r);return{...Gw(e,t.record),etag:t.etag,permissions:t.permissions}}let a=await i.list(e.name,{filter:t||void 0,orderBy:n||void 0,pageSize:1});return a.items[0]?Gw(e,a.items[0]):null}})},Yw=(e,{filter:t=``,sort:n=``,pageSize:r,pageToken:i=``})=>{let a=K();return _h({queryKey:G.list(e.name,t,n,r,i),placeholderData:pm,queryFn:()=>a.list(e.name,{filter:t||void 0,orderBy:n||void 0,pageSize:r,pageToken:i||void 0})})},Xw=()=>{let e=Up();return(0,o.useCallback)(t=>e.invalidateQueries({predicate:e=>e.queryKey[1]===t}),[e])},Zw=e=>e instanceof Error?e.message:`Something went wrong`,Qw=(e,t,n)=>{let{views:r}=J(),{actions:i,components:a}=Xg(),s=d_(e),c=K(),l=wh(e),u=Ig(),d=Xw(),{go:f}=PC(),[p,m]=(0,o.useState)(),h=(r[e]?.actions??[]).flatMap(e=>Ww(e,t?.record)??[]),g=e=>{let n=e.run?.kind;if((n===`update`||n===`delete`)&&!t)return`Needs a record`;if(n===`update`&&(!Fw(s,`update`)||t?.permissions?.update===!1))return`You cannot change this record`;if(n===`delete`&&(!Fw(s,`delete`)||t?.permissions?.delete===!1))return`You cannot delete this record`;if(!e.run&&!i?.[e.name])return`The app has no handler for "${e.name}"`;let r=e.inputs?.find(e=>e.kind===`custom`&&!a?.[e.component??``]);if(r)return`The app has no component "${r.component}" for input "${r.name}"`},_=async(r,a)=>{let{run:o}=r;if(o?.kind===`link`){`to`in o?f(Do(o.to,t?.record)):Vw(Bw(o.href,t?.record));return}o?.kind===`update`?await c.update(e,t.key,o.values,t.etag??`*`):o?.kind===`delete`?await c.remove(e,t.key,{etag:t.etag}):await i[r.name]({resource:e,record:t?.record,recordKey:t?.key,etag:t?.etag,client:l,navigate:f,...a&&{values:a}}),await d(e),u.show({state:`success`,title:`${r.label}: done`}),n?.(r)};return{actions:h,blocked:g,running:p,run:async e=>{g(e)||(m(e.name),await _(e).catch(t=>u.show({state:`error`,title:`${e.label} failed`,description:Zw(t)})),m(void 0))},submit:async(e,t)=>{g(e)||(m(e.name),await _(e,t).finally(()=>m(void 0)))}}},$w=(e,t,n)=>{let r=Qw(e,n),i=r.actions.find(e=>e.name===t);return{action:i,blocked:i?r.blocked(i):`No action "${t}"`,running:r.running===t,run:()=>i?r.run(i):Promise.resolve(),submit:e=>i?r.submit(i,e):Promise.resolve()}},eT=e=>e.props,tT=({node:e})=>{let{name:t,resource:n,label:r,variant:i}=eT(e),a=Pw(),s=$w(n??a?.model.name??``,t,n===void 0||n===a?.model.name?a:void 0),[c,l]=(0,o.useState)(!1);if(!s.action)return null;let u=r??s.action.label;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{size:`sm`,variant:i??`secondary`,loading:s.running,disabled:!!s.blocked,title:s.blocked,onClick:()=>Aw(s.action)?l(!0):void s.run(),children:u}),c&&(0,H.jsx)(jw,{action:s.action,label:u,danger:i===`danger`,onCancel:()=>l(!1),onConfirm:()=>{l(!1),s.run()},onSubmit:async e=>{await s.submit(e),l(!1)}})]})},nT=({title:e,description:t,actions:n,className:r,bodyClassName:i,children:a})=>(0,H.jsxs)(`section`,{className:V(`flex min-w-0 flex-col rounded-lg border border-border bg-background`,r),"aria-label":e,children:[(e||t||n)&&(0,H.jsxs)(`header`,{className:`flex flex-wrap items-start justify-between gap-x-4 gap-y-2 px-4 pt-4`,children:[(0,H.jsxs)(`div`,{className:`min-w-0`,children:[e&&(0,H.jsx)(`h2`,{className:`text-[16px] font-semibold tracking-tight`,children:e}),t&&(0,H.jsx)(`p`,{className:`mt-0.5 text-muted-foreground`,children:t})]}),n&&(0,H.jsx)(`div`,{className:`flex flex-wrap items-center gap-2`,children:n})]}),(0,H.jsx)(`div`,{className:V(`min-w-0 flex-1 p-4`,i),children:a})]}),rT=({children:e})=>(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:e}),iT=({node:e,children:t,slots:n})=>{let{title:r,description:i}=eT(e);return(0,H.jsx)(nT,{title:r,description:i,actions:n.actions,className:`h-full`,children:(0,H.jsx)(`div`,{className:`flex flex-col gap-3`,children:t})})},aT=({model:e,filter:t,sort:n,limit:r=12,title:i,description:a,empty:o,actions:s,children:c})=>{let l=Yw(e,{filter:t,sort:n,pageSize:r}),u=l.data?.items??[];return(0,H.jsx)(nT,{title:i,description:a,actions:s,children:l.isPending?(0,H.jsx)(`div`,{className:`flex gap-3`,children:Array.from({length:3},(e,t)=>(0,H.jsx)(ku,{className:`h-24 w-56`},t))}):l.error?(0,H.jsx)(pS,{title:`Could not load`,error:l.error}):u.length===0?(0,H.jsx)(rT,{children:o??`Nothing here yet.`}):(0,H.jsx)(`ul`,{className:`-mx-4 flex snap-x gap-3 overflow-x-auto px-4 pb-1`,children:u.map(t=>{let n=Gw(e,t);return(0,H.jsx)(`li`,{className:`flex w-60 shrink-0 snap-start flex-col gap-2 rounded-lg border border-border bg-surface p-3`,children:(0,H.jsx)(Nw,{value:n,children:c})},n.key)})})})},oT=({node:e,children:t,slots:n})=>{let{resource:r,...i}=eT(e),a=J().resources[r];return a?(0,H.jsx)(aT,{...i,model:a,actions:n.actions,children:t}):null},sT=(e,t,n,r=!0)=>{let i=K(),a=Ss(n)??``;return _h({queryKey:G.facets(e,t,a),enabled:r,queryFn:()=>i.facets(e,t,{filter:a,limit:50})})},cT=(e,t,n=!0)=>{let r=K(),i=Ss(t.filter)??``;return _h({queryKey:G.series(e,t.field,`${t.range??``}${t.from??``}${t.to??``}`,t.granularity??``,i),enabled:n,queryFn:()=>r.series(e,{...t,filter:i})})},lT=(e,t,n,r=20,i=!0)=>{let a=K(),o=Ss(n)??``;return _h({queryKey:G.histogram(e,t,r,o),enabled:i,queryFn:()=>a.histogram(e,t,{filter:o,buckets:r})})},uT=(e,t,n=!0)=>{let r=K(),i={...t,filter:Ss(t.filter)??``};return _h({queryKey:G.aggregate(e,JSON.stringify(i)),enabled:n,queryFn:()=>r.aggregate(e,i)})},dT=uo(),fT=e=>e>=0&&e<8?`var(--chart-${e+1})`:`var(--faint-foreground)`,pT=(e,t,n,r)=>{let i=String(n);return n===null?`var(--faint-foreground)`:t?.valueColors&&Object.hasOwn(t.valueColors,i)?t.valueColors[i]:e.type===`enum`?fT(e.enumValues?.indexOf(i)??-1):e.type===`boolean`?fT(+!n):fT(r)},mT=(e,t,n)=>n.value===null?`Not set`:e.type===`enum`?rs(String(n.value),t?.valueLabels):e.type===`boolean`?n.value?`Yes`:`No`:n.label??String(n.value),hT=(e,t,n=``)=>{let r=Ya(t===null?dT.isNull(e.name):dT.eq(e.name,t));return n.trim()?`(${n}) AND ${r}`:r},gT=(e,t)=>t.kind===`count`?e.count:e[t.kind]??null,_T=(e,t,n,r,i=``)=>e.map((e,a)=>({key:String(e.value),label:mT(t,n,e),value:gT(e,r),count:e.count,color:pT(t,n,e.value,a),filter:hT(t,e.value,i)})),vT=(e,t)=>e.map(e=>({at:Date.parse(`${String(e.value)}Z`),value:gT(e,t),count:e.count})),yT=(e,t)=>{if(e===null)return`—`;if(t.kind===`count`)return e.toLocaleString(`en-IE`);let n=t.hints?.decimals??(Number.isInteger(e)?0:2),r=e.toLocaleString(`en-IE`,{minimumFractionDigits:n,maximumFractionDigits:n});return`${t.hints?.prefix??``}${r}${t.hints?.suffix??``}`},bT=({resource:e,slices:t,measure:n})=>{let r=Math.max(0,...t.map(e=>e.value??0));return(0,H.jsx)(`ul`,{className:`flex flex-col gap-1`,children:t.map(t=>{let i=r>0&&t.value!==null?Math.max(0,t.value)/r:0;return(0,H.jsx)(`li`,{children:(0,H.jsxs)(FC,{to:{kind:`list`,resource:e,filter:t.filter},className:`group grid grid-cols-[minmax(6rem,35%)_1fr_auto] items-center gap-3 rounded-md px-1 py-1 hover:bg-muted`,title:n.kind===`count`?void 0:`${yT(t.count,{kind:`count`})} records`,children:[(0,H.jsx)(`span`,{className:`truncate group-hover:text-primary-text`,children:t.label}),(0,H.jsx)(`span`,{className:`h-3 rounded-r bg-muted`,"aria-hidden":!0,children:(0,H.jsx)(`span`,{className:`block h-full rounded-r`,style:{width:`${i*100}%`,background:`var(--chart-1)`}})}),(0,H.jsx)(`span`,{className:`text-right font-medium tabular-nums`,children:yT(t.value,n)})]})},t.key)})})};function xT(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`){if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(n=xT(e[t]))&&(r&&(r+=` `),r+=n)}else for(n in e)e[n]&&(r&&(r+=` `),r+=n)}return r}function ST(){for(var e,t,n=0,r=``,i=arguments.length;n<i;n++)(e=arguments[n])&&(t=xT(e))&&(r&&(r+=` `),r+=t);return r}var CT=`dangerouslySetInnerHTML.onCopy.onCopyCapture.onCut.onCutCapture.onPaste.onPasteCapture.onCompositionEnd.onCompositionEndCapture.onCompositionStart.onCompositionStartCapture.onCompositionUpdate.onCompositionUpdateCapture.onFocus.onFocusCapture.onBlur.onBlurCapture.onChange.onChangeCapture.onBeforeInput.onBeforeInputCapture.onInput.onInputCapture.onReset.onResetCapture.onSubmit.onSubmitCapture.onInvalid.onInvalidCapture.onLoad.onLoadCapture.onError.onErrorCapture.onKeyDown.onKeyDownCapture.onKeyPress.onKeyPressCapture.onKeyUp.onKeyUpCapture.onAbort.onAbortCapture.onCanPlay.onCanPlayCapture.onCanPlayThrough.onCanPlayThroughCapture.onDurationChange.onDurationChangeCapture.onEmptied.onEmptiedCapture.onEncrypted.onEncryptedCapture.onEnded.onEndedCapture.onLoadedData.onLoadedDataCapture.onLoadedMetadata.onLoadedMetadataCapture.onLoadStart.onLoadStartCapture.onPause.onPauseCapture.onPlay.onPlayCapture.onPlaying.onPlayingCapture.onProgress.onProgressCapture.onRateChange.onRateChangeCapture.onSeeked.onSeekedCapture.onSeeking.onSeekingCapture.onStalled.onStalledCapture.onSuspend.onSuspendCapture.onTimeUpdate.onTimeUpdateCapture.onVolumeChange.onVolumeChangeCapture.onWaiting.onWaitingCapture.onAuxClick.onAuxClickCapture.onClick.onClickCapture.onContextMenu.onContextMenuCapture.onDoubleClick.onDoubleClickCapture.onDrag.onDragCapture.onDragEnd.onDragEndCapture.onDragEnter.onDragEnterCapture.onDragExit.onDragExitCapture.onDragLeave.onDragLeaveCapture.onDragOver.onDragOverCapture.onDragStart.onDragStartCapture.onDrop.onDropCapture.onMouseDown.onMouseDownCapture.onMouseEnter.onMouseLeave.onMouseMove.onMouseMoveCapture.onMouseOut.onMouseOutCapture.onMouseOver.onMouseOverCapture.onMouseUp.onMouseUpCapture.onSelect.onSelectCapture.onTouchCancel.onTouchCancelCapture.onTouchEnd.onTouchEndCapture.onTouchMove.onTouchMoveCapture.onTouchStart.onTouchStartCapture.onPointerDown.onPointerDownCapture.onPointerMove.onPointerMoveCapture.onPointerUp.onPointerUpCapture.onPointerCancel.onPointerCancelCapture.onPointerEnter.onPointerEnterCapture.onPointerLeave.onPointerLeaveCapture.onPointerOver.onPointerOverCapture.onPointerOut.onPointerOutCapture.onGotPointerCapture.onGotPointerCaptureCapture.onLostPointerCapture.onLostPointerCaptureCapture.onScroll.onScrollCapture.onWheel.onWheelCapture.onAnimationStart.onAnimationStartCapture.onAnimationEnd.onAnimationEndCapture.onAnimationIteration.onAnimationIterationCapture.onTransitionEnd.onTransitionEndCapture`.split(`.`);function wT(e){return typeof e==`string`&&CT.includes(e)}var TT=new Set(`aria-activedescendant.aria-atomic.aria-autocomplete.aria-busy.aria-checked.aria-colcount.aria-colindex.aria-colspan.aria-controls.aria-current.aria-describedby.aria-details.aria-disabled.aria-errormessage.aria-expanded.aria-flowto.aria-haspopup.aria-hidden.aria-invalid.aria-keyshortcuts.aria-label.aria-labelledby.aria-level.aria-live.aria-modal.aria-multiline.aria-multiselectable.aria-orientation.aria-owns.aria-placeholder.aria-posinset.aria-pressed.aria-readonly.aria-relevant.aria-required.aria-roledescription.aria-rowcount.aria-rowindex.aria-rowspan.aria-selected.aria-setsize.aria-sort.aria-valuemax.aria-valuemin.aria-valuenow.aria-valuetext.className.color.height.id.lang.max.media.method.min.name.style.target.width.role.tabIndex.accentHeight.accumulate.additive.alignmentBaseline.allowReorder.alphabetic.amplitude.arabicForm.ascent.attributeName.attributeType.autoReverse.azimuth.baseFrequency.baselineShift.baseProfile.bbox.begin.bias.by.calcMode.capHeight.clip.clipPath.clipPathUnits.clipRule.colorInterpolation.colorInterpolationFilters.colorProfile.colorRendering.contentScriptType.contentStyleType.cursor.cx.cy.d.decelerate.descent.diffuseConstant.direction.display.divisor.dominantBaseline.dur.dx.dy.edgeMode.elevation.enableBackground.end.exponent.externalResourcesRequired.fill.fillOpacity.fillRule.filter.filterRes.filterUnits.floodColor.floodOpacity.focusable.fontFamily.fontSize.fontSizeAdjust.fontStretch.fontStyle.fontVariant.fontWeight.format.from.fx.fy.g1.g2.glyphName.glyphOrientationHorizontal.glyphOrientationVertical.glyphRef.gradientTransform.gradientUnits.hanging.horizAdvX.horizOriginX.href.ideographic.imageRendering.in2.in.intercept.k1.k2.k3.k4.k.kernelMatrix.kernelUnitLength.kerning.keyPoints.keySplines.keyTimes.lengthAdjust.letterSpacing.lightingColor.limitingConeAngle.local.markerEnd.markerHeight.markerMid.markerStart.markerUnits.markerWidth.mask.maskContentUnits.maskUnits.mathematical.mode.numOctaves.offset.opacity.operator.order.orient.orientation.origin.overflow.overlinePosition.overlineThickness.paintOrder.panose1.pathLength.patternContentUnits.patternTransform.patternUnits.pointerEvents.pointsAtX.pointsAtY.pointsAtZ.preserveAlpha.preserveAspectRatio.primitiveUnits.r.radius.refX.refY.renderingIntent.repeatCount.repeatDur.requiredExtensions.requiredFeatures.restart.result.rotate.rx.ry.seed.shapeRendering.slope.spacing.specularConstant.specularExponent.speed.spreadMethod.startOffset.stdDeviation.stemh.stemv.stitchTiles.stopColor.stopOpacity.strikethroughPosition.strikethroughThickness.string.stroke.strokeDasharray.strokeDashoffset.strokeLinecap.strokeLinejoin.strokeMiterlimit.strokeOpacity.strokeWidth.surfaceScale.systemLanguage.tableValues.targetX.targetY.textAnchor.textDecoration.textLength.textRendering.to.transform.u1.u2.underlinePosition.underlineThickness.unicode.unicodeBidi.unicodeRange.unitsPerEm.vAlphabetic.values.vectorEffect.version.vertAdvY.vertOriginX.vertOriginY.vHanging.vIdeographic.viewTarget.visibility.vMathematical.widths.wordSpacing.writingMode.x1.x2.x.xChannelSelector.xHeight.xlinkActuate.xlinkArcrole.xlinkHref.xlinkRole.xlinkShow.xlinkTitle.xlinkType.xmlBase.xmlLang.xmlns.xmlnsXlink.xmlSpace.y1.y2.y.yChannelSelector.z.zoomAndPan.ref.key.angle`.split(`.`));function ET(e){return typeof e==`string`&&TT.has(e)}function DT(e){return typeof e==`string`&&e.startsWith(`data-`)}function OT(e){if(typeof e!=`object`||!e)return{};var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(ET(n)||DT(n))&&(t[n]=e[n]);return t}function kT(e){if(e==null)return null;if((0,o.isValidElement)(e)&&typeof e.props==`object`&&e.props!==null){var t=e.props;return OT(t)}return typeof e==`object`&&!Array.isArray(e)?OT(e):null}function AT(e){var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(ET(n)||DT(n)||wT(n))&&(t[n]=e[n]);return t}function jT(e){return e==null?null:(0,o.isValidElement)(e)?AT(e.props):typeof e==`object`&&!Array.isArray(e)?AT(e):null}var MT=[`children`,`width`,`height`,`viewBox`,`className`,`style`,`title`,`desc`];function NT(){return NT=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},NT.apply(null,arguments)}function PT(e,t){if(e==null)return{};var n,r,i=FT(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function FT(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var IT=(0,o.forwardRef)((e,t)=>{var n=e.children,r=e.width,i=e.height,a=e.viewBox,s=e.className,c=e.style,l=e.title,u=e.desc,d=PT(e,MT),f=a||{width:r,height:i,x:0,y:0},p=ST(`recharts-surface`,s);return o.createElement(`svg`,NT({},AT(d),{className:p,width:r,height:i,style:c,viewBox:`${f.x} ${f.y} ${f.width} ${f.height}`,ref:t}),o.createElement(`title`,null,l),o.createElement(`desc`,null,u),n)}),LT=[`children`,`className`];function RT(){return RT=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},RT.apply(null,arguments)}function zT(e,t){if(e==null)return{};var n,r,i=BT(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function BT(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var VT=o.forwardRef((e,t)=>{var n=e.children,r=e.className,i=zT(e,LT),a=ST(`recharts-layer`,r);return o.createElement(`g`,RT({className:a},AT(i),{ref:t}),n)});function HT(e){return e===`__proto__`}var UT=/\.|(\[(?:[^[\]]*|(["'])(?:(?!\2)[^\\]|\\.)*?\2)\])/;function WT(e){switch(typeof e){case`number`:case`symbol`:return!1;case`string`:return e===``||e.startsWith(`.`)||e.endsWith(`.`)?!1:UT.test(e);default:return!1}}function GT(e){return typeof e==`string`||typeof e==`symbol`?e:Object.is(e?.valueOf?.(),-0)?`-0`:String(e)}function KT(e){return typeof e==`symbol`||e instanceof Symbol}function qT(e){return e==null?``:JT(e)}function JT(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(JT).join(`,`);if(KT(e))return e.toString();let t=e+``;return t===`0`&&Object.is(Number(e),-0)?`-0`:t}function YT(e){if(Array.isArray(e))return e.map(GT);if(typeof e==`symbol`)return[e];e=qT(e);let t=[],n=e.length;if(n===0)return t;let r=0,i=``,a=``,o=!1,s=!1,c=/^-?\d+(?:\.\d+)?$/;for(e.charCodeAt(0)===46&&t.push(``);r<n;){let l=e[r];if(a)l===`\\`&&r+1<n?(r++,i+=e[r]):l===a?a=``:i+=l;else if(o){if(l===`"`||l===`'`)a=l,s=!0;else if(l===`]`){if(o=!1,!s&&i.includes(`.`)&&!c.test(i)){let e=i.split(`.`);for(let n=0;n<e.length;n++)e[n]!==``&&t.push(e[n])}else t.push(i);i=``}else i+=l}else if(l===`[`)o=!0,s=!1,i&&=(t.push(i),``);else if(l===`.`){i&&=(t.push(i),``);let n=e[r+1];(n===void 0||n===`.`)&&t.push(``)}else i+=l;r++}return i&&t.push(i),t}function XT(e,t,n){if(e==null)return n;switch(typeof t){case`string`:{if(HT(t))return n;let r=e[t];return r===void 0?WT(t)&&!Object.hasOwn(e,t)?XT(e,YT(t),n):n:r}case`number`:case`symbol`:{typeof t==`number`&&(t=GT(t));let r=e[t];return r===void 0?n:r}default:{if(Array.isArray(t))return ZT(e,t,n);if(t=Object.is(t?.valueOf(),-0)?`-0`:String(t),HT(t))return n;let r=e[t];return r===void 0?n:r}}}function ZT(e,t,n){if(t.length===0)return n;let r=e;for(let e=0;e<t.length;e++){if(r==null||HT(t[e]))return n;r=r[t[e]]}return r===void 0?n:r}var QT=4;function $T(e){var t=10**(arguments.length>1&&arguments[1]!==void 0?arguments[1]:QT),n=Math.round(e*t)/t;return Object.is(n,-0)?0:n}function eE(e){var t=[...arguments].slice(1);return e.reduce((e,n,r)=>{var i=t[r-1];return typeof i==`string`?e+i+n:i===void 0?e+n:e+$T(i)+n},``)}var tE=e=>e===0?0:e>0?1:-1,nE=e=>typeof e==`number`&&e!=+e,rE=e=>typeof e==`string`&&e.length>1&&e.indexOf(`%`)===e.length-1,Y=e=>(typeof e==`number`||e instanceof Number)&&!nE(e),iE=e=>Y(e)||typeof e==`string`,aE=0,oE=e=>{var t=++aE;return`${e||``}${t}`},sE=function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,r=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(!Y(e)&&typeof e!=`string`)return n;var i;if(rE(e)){if(t==null)return n;var a=e.indexOf(`%`);i=t*parseFloat(e.slice(0,a))/100}else i=+e;return nE(i)&&(i=n),r&&t!=null&&i>t&&(i=t),i},cE=e=>{if(!Array.isArray(e))return!1;for(var t=e.length,n={},r=0;r<t;r++)if(!n[String(e[r])])n[String(e[r])]=!0;else return!0;return!1};function lE(e,t,n){return Y(e)&&Y(t)?$T(e+n*(t-e)):t}function uE(e,t,n){if(e&&e.length)return e.find(e=>e&&(typeof t==`function`?t(e):XT(e,t))===n)}var dE=e=>e==null,fE=e=>dE(e)?e:`${e.charAt(0).toUpperCase()}${e.slice(1)}`;function pE(e){return e!=null}function mE(){}function hE(e){if(e)return{x:e.x,y:e.y,upperWidth:`upperWidth`in e?e.upperWidth:e.width,lowerWidth:`lowerWidth`in e?e.lowerWidth:e.width,width:e.width,height:e.height}}function gE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function _E(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?gE(Object(n),!0).forEach(function(t){vE(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gE(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function vE(e,t,n){return(t=yE(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function yE(e){var t=bE(e,`string`);return typeof t==`symbol`?t:t+``}function bE(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var xE=e=>{var t=e.viewBox,n=e.position,r=e.offset,i=r===void 0?0:r,a=e.parentViewBox,o=e.clamp,s=hE(t),c=s.x,l=s.y,u=s.height,d=s.upperWidth,f=s.lowerWidth,p=c,m=c+(d-f)/2,h=(p+m)/2,g=(d+f)/2,_=p+d/2,v=u>=0?1:-1,y=v*i,b=v>0?`end`:`start`,x=v>0?`start`:`end`,S=d>=0?1:-1,C=S*i,w=S>0?`end`:`start`,T=S>0?`start`:`end`,E=a;if(n===`top`){var D={x:p+d/2,y:l-y,horizontalAnchor:`middle`,verticalAnchor:b};return o&&E&&(D.height=Math.max(l-E.y,0),D.width=d),D}if(n===`bottom`){var O={x:m+f/2,y:l+u+y,horizontalAnchor:`middle`,verticalAnchor:x};return o&&E&&(O.height=Math.max(E.y+E.height-(l+u),0),O.width=f),O}if(n===`left`){var k={x:h-C,y:l+u/2,horizontalAnchor:w,verticalAnchor:`middle`};return o&&E&&(k.width=Math.max(k.x-E.x,0),k.height=u),k}if(n===`right`){var A={x:h+g+C,y:l+u/2,horizontalAnchor:T,verticalAnchor:`middle`};return o&&E&&(A.width=Math.max(E.x+E.width-A.x,0),A.height=u),A}var j=o&&E?{width:g,height:u}:{};return n===`insideLeft`?_E({x:h+C,y:l+u/2,horizontalAnchor:T,verticalAnchor:`middle`},j):n===`insideRight`?_E({x:h+g-C,y:l+u/2,horizontalAnchor:w,verticalAnchor:`middle`},j):n===`insideTop`?_E({x:p+d/2,y:l+y,horizontalAnchor:`middle`,verticalAnchor:x},j):n===`insideBottom`?_E({x:m+f/2,y:l+u-y,horizontalAnchor:`middle`,verticalAnchor:b},j):n===`insideTopLeft`?_E({x:p+C,y:l+y,horizontalAnchor:T,verticalAnchor:x},j):n===`insideTopRight`?_E({x:p+d-C,y:l+y,horizontalAnchor:w,verticalAnchor:x},j):n===`insideBottomLeft`?_E({x:m+C,y:l+u-y,horizontalAnchor:T,verticalAnchor:b},j):n===`insideBottomRight`?_E({x:m+f-C,y:l+u-y,horizontalAnchor:w,verticalAnchor:b},j):n&&typeof n==`object`&&(Y(n.x)||rE(n.x))&&(Y(n.y)||rE(n.y))?_E({x:c+sE(n.x,g),y:l+sE(n.y,u),horizontalAnchor:`end`,verticalAnchor:`end`},j):_E({x:_,y:l+u/2,horizontalAnchor:`middle`,verticalAnchor:`middle`},j)},SE=[`top`,`left`,`right`,`bottom`];function CE(e){return e==null?!1:typeof e==`object`||SE.includes(e)}var wE=(0,o.createContext)(null);function TE(e){return function(){return e}}var EE=Math.PI,DE=2*EE,OE=1e-6,kE=DE-OE;function AE(e){this._+=e[0];for(let t=1,n=e.length;t<n;++t)this._+=arguments[t]+e[t]}function jE(e){let t=Math.floor(e);if(!(t>=0))throw Error(`invalid digits: ${e}`);if(t>15)return AE;let n=10**t;return function(e){this._+=e[0];for(let t=1,r=e.length;t<r;++t)this._+=Math.round(arguments[t]*n)/n+e[t]}}var ME=class{constructor(e){this._x0=this._y0=this._x1=this._y1=null,this._=``,this._append=e==null?AE:jE(e)}moveTo(e,t){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+t}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(e,t){this._append`L${this._x1=+e},${this._y1=+t}`}quadraticCurveTo(e,t,n,r){this._append`Q${+e},${+t},${this._x1=+n},${this._y1=+r}`}bezierCurveTo(e,t,n,r,i,a){this._append`C${+e},${+t},${+n},${+r},${this._x1=+i},${this._y1=+a}`}arcTo(e,t,n,r,i){if(e=+e,t=+t,n=+n,r=+r,i=+i,i<0)throw Error(`negative radius: ${i}`);let a=this._x1,o=this._y1,s=n-e,c=r-t,l=a-e,u=o-t,d=l*l+u*u;if(this._x1===null)this._append`M${this._x1=e},${this._y1=t}`;else if(d>OE){if(!(Math.abs(u*s-c*l)>OE)||!i)this._append`L${this._x1=e},${this._y1=t}`;else{let f=n-a,p=r-o,m=s*s+c*c,h=f*f+p*p,g=Math.sqrt(m),_=Math.sqrt(d),v=i*Math.tan((EE-Math.acos((m+d-h)/(2*g*_)))/2),y=v/_,b=v/g;Math.abs(y-1)>OE&&this._append`L${e+y*l},${t+y*u}`,this._append`A${i},${i},0,0,${+(u*f>l*p)},${this._x1=e+b*s},${this._y1=t+b*c}`}}}arc(e,t,n,r,i,a){if(e=+e,t=+t,n=+n,a=!!a,n<0)throw Error(`negative radius: ${n}`);let o=n*Math.cos(r),s=n*Math.sin(r),c=e+o,l=t+s,u=1^a,d=a?r-i:i-r;this._x1===null?this._append`M${c},${l}`:(Math.abs(this._x1-c)>OE||Math.abs(this._y1-l)>OE)&&this._append`L${c},${l}`,n&&(d<0&&(d=d%DE+DE),d>kE?this._append`A${n},${n},0,1,${u},${e-o},${t-s}A${n},${n},0,1,${u},${this._x1=c},${this._y1=l}`:d>OE&&this._append`A${n},${n},0,${+(d>=EE)},${u},${this._x1=e+n*Math.cos(i)},${this._y1=t+n*Math.sin(i)}`)}rect(e,t,n,r){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+t}h${n=+n}v${+r}h${-n}Z`}toString(){return this._}};ME.prototype;function NE(e){let t=3;return e.digits=function(n){if(!arguments.length)return t;if(n==null)t=null;else{let e=Math.floor(n);if(!(e>=0))throw RangeError(`invalid digits: ${n}`);t=e}return e},()=>new ME(t)}Array.prototype.slice;function PE(e){return typeof e==`object`&&`length`in e?e:Array.from(e)}function FE(e){this._context=e}FE.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t)}}};function IE(e){return new FE(e)}function LE(e){return e[0]}function RE(e){return e[1]}function zE(e,t){var n=TE(!0),r=null,i=IE,a=null,o=NE(s);e=typeof e==`function`?e:e===void 0?LE:TE(e),t=typeof t==`function`?t:t===void 0?RE:TE(t);function s(s){var c,l=(s=PE(s)).length,u,d=!1,f;for(r??(a=i(f=o())),c=0;c<=l;++c)!(c<l&&n(u=s[c],c,s))===d&&((d=!d)?a.lineStart():a.lineEnd()),d&&a.point(+e(u,c,s),+t(u,c,s));if(f)return a=null,f+``||null}return s.x=function(t){return arguments.length?(e=typeof t==`function`?t:TE(+t),s):e},s.y=function(e){return arguments.length?(t=typeof e==`function`?e:TE(+e),s):t},s.defined=function(e){return arguments.length?(n=typeof e==`function`?e:TE(!!e),s):n},s.curve=function(e){return arguments.length?(i=e,r!=null&&(a=i(r)),s):i},s.context=function(e){return arguments.length?(e==null?r=a=null:a=i(r=e),s):r},s}function BE(e,t,n){var r=null,i=TE(!0),a=null,o=IE,s=null,c=NE(l);e=typeof e==`function`?e:e===void 0?LE:TE(+e),t=typeof t==`function`?t:TE(t===void 0?0:+t),n=typeof n==`function`?n:n===void 0?RE:TE(+n);function l(l){var u,d,f,p=(l=PE(l)).length,m,h=!1,g,_=Array(p),v=Array(p);for(a??(s=o(g=c())),u=0;u<=p;++u){if(!(u<p&&i(m=l[u],u,l))===h){if(h=!h)d=u,s.areaStart(),s.lineStart();else{for(s.lineEnd(),s.lineStart(),f=u-1;f>=d;--f)s.point(_[f],v[f]);s.lineEnd(),s.areaEnd()}}h&&(_[u]=+e(m,u,l),v[u]=+t(m,u,l),s.point(r?+r(m,u,l):_[u],n?+n(m,u,l):v[u]))}if(g)return s=null,g+``||null}function u(){return zE().defined(i).curve(o).context(a)}return l.x=function(t){return arguments.length?(e=typeof t==`function`?t:TE(+t),r=null,l):e},l.x0=function(t){return arguments.length?(e=typeof t==`function`?t:TE(+t),l):e},l.x1=function(e){return arguments.length?(r=e==null?null:typeof e==`function`?e:TE(+e),l):r},l.y=function(e){return arguments.length?(t=typeof e==`function`?e:TE(+e),n=null,l):t},l.y0=function(e){return arguments.length?(t=typeof e==`function`?e:TE(+e),l):t},l.y1=function(e){return arguments.length?(n=e==null?null:typeof e==`function`?e:TE(+e),l):n},l.lineX0=l.lineY0=function(){return u().x(e).y(t)},l.lineY1=function(){return u().x(e).y(n)},l.lineX1=function(){return u().x(r).y(t)},l.defined=function(e){return arguments.length?(i=typeof e==`function`?e:TE(!!e),l):i},l.curve=function(e){return arguments.length?(o=e,a!=null&&(s=o(a)),l):o},l.context=function(e){return arguments.length?(e==null?a=s=null:s=o(a=e),l):a},l}var VE=class{constructor(e,t){this._context=e,this._x=t}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,t,e,t):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+t)/2,e,this._y0,e,t)}this._x0=e,this._y0=t}};function HE(e){return new VE(e,!0)}function UE(e){return new VE(e,!1)}function WE(){}function GE(e,t,n){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+n)/6)}function KE(e){this._context=e}KE.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:GE(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:GE(this,e,t)}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function qE(e){return new KE(e)}function JE(e){this._context=e}JE.prototype={areaStart:WE,areaEnd:WE,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:GE(this,e,t)}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function YE(e){return new JE(e)}function XE(e){this._context=e}XE.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+e)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:GE(this,e,t)}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function ZE(e){return new XE(e)}function QE(e){this._context=e}QE.prototype={areaStart:WE,areaEnd:WE,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function $E(e){return new QE(e)}function eD(e){return e<0?-1:1}function tD(e,t,n){var r=e._x1-e._x0,i=t-e._x1,a=(e._y1-e._y0)/(r||i<0&&-0),o=(n-e._y1)/(i||r<0&&-0),s=(a*i+o*r)/(r+i);return(eD(a)+eD(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(s))||0}function nD(e,t){var n=e._x1-e._x0;return n?(3*(e._y1-e._y0)/n-t)/2:t}function rD(e,t,n){var r=e._x0,i=e._y0,a=e._x1,o=e._y1,s=(a-r)/3;e._context.bezierCurveTo(r+s,i+s*t,a-s,o-s*n,a,o)}function iD(e){this._context=e}iD.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:rD(this,this._t0,nD(this,this._t0))}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var n=NaN;if(e=+e,t=+t,e!==this._x1||t!==this._y1){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,rD(this,nD(this,n=tD(this,e,t)),n);break;default:rD(this,this._t0,n=tD(this,e,t))}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=n}}};function aD(e){this._context=new oD(e)}(aD.prototype=Object.create(iD.prototype)).point=function(e,t){iD.prototype.point.call(this,t,e)};function oD(e){this._context=e}oD.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,n,r,i,a){this._context.bezierCurveTo(t,e,r,n,a,i)}};function sD(e){return new iD(e)}function cD(e){return new aD(e)}function lD(e){this._context=e}lD.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,n=e.length;if(n){if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),n===2)this._context.lineTo(e[1],t[1]);else for(var r=uD(e),i=uD(t),a=0,o=1;o<n;++a,++o)this._context.bezierCurveTo(r[0][a],i[0][a],r[1][a],i[1][a],e[o],t[o])}(this._line||this._line!==0&&n===1)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(e,t){this._x.push(+e),this._y.push(+t)}};function uD(e){var t,n=e.length-1,r,i=Array(n),a=Array(n),o=Array(n);for(i[0]=0,a[0]=2,o[0]=e[0]+2*e[1],t=1;t<n-1;++t)i[t]=1,a[t]=4,o[t]=4*e[t]+2*e[t+1];for(i[n-1]=2,a[n-1]=7,o[n-1]=8*e[n-1]+e[n],t=1;t<n;++t)r=i[t]/a[t-1],a[t]-=r,o[t]-=r*o[t-1];for(i[n-1]=o[n-1]/a[n-1],t=n-2;t>=0;--t)i[t]=(o[t]-i[t+1])/a[t];for(a[n-1]=(e[n]+i[n-1])/2,t=0;t<n-1;++t)a[t]=2*e[t+1]-i[t+1];return[i,a]}function dD(e){return new lD(e)}function fD(e,t){this._context=e,this._t=t}fD.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&this._point===2&&this._context.lineTo(this._x,this._y),(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var n=this._x*(1-this._t)+e*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}}this._x=e,this._y=t}};function pD(e){return new fD(e,.5)}function mD(e){return new fD(e,0)}function hD(e){return new fD(e,1)}function gD(e,t){if((o=e.length)>1)for(var n=1,r,i,a=e[t[0]],o,s=a.length;n<o;++n)for(i=a,a=e[t[n]],r=0;r<s;++r)a[r][1]+=a[r][0]=isNaN(i[r][1])?i[r][0]:i[r][1]}function _D(e){for(var t=e.length,n=Array(t);--t>=0;)n[t]=t;return n}function vD(e,t){return e[t]}function yD(e){let t=[];return t.key=e,t}function bD(){var e=TE([]),t=_D,n=gD,r=vD;function i(i){var a=Array.from(e.apply(this,arguments),yD),o,s=a.length,c=-1,l;for(let e of i)for(o=0,++c;o<s;++o)(a[o][c]=[0,+r(e,a[o].key,c,i)]).data=e;for(o=0,l=PE(t(a));o<s;++o)a[l[o]].index=o;return n(a,l),a}return i.keys=function(t){return arguments.length?(e=typeof t==`function`?t:TE(Array.from(t)),i):e},i.value=function(e){return arguments.length?(r=typeof e==`function`?e:TE(+e),i):r},i.order=function(e){return arguments.length?(t=e==null?_D:typeof e==`function`?e:TE(Array.from(e)),i):t},i.offset=function(e){return arguments.length?(n=e??gD,i):n},i}function xD(e,t){if((r=e.length)>0){for(var n,r,i=0,a=e[0].length,o;i<a;++i){for(o=n=0;n<r;++n)o+=e[n][i][1]||0;if(o)for(n=0;n<r;++n)e[n][i][1]/=o}gD(e,t)}}function SD(e,t){if((i=e.length)>0){for(var n=0,r=e[t[0]],i,a=r.length;n<a;++n){for(var o=0,s=0;o<i;++o)s+=e[o][n][1]||0;r[n][1]+=r[n][0]=-s/2}gD(e,t)}}function CD(e,t){if((o=e.length)>0&&(a=(i=e[t[0]]).length)>0){for(var n=0,r=1,i,a,o;r<a;++r){for(var s=0,c=0,l=0;s<o;++s){for(var u=e[t[s]],d=u[r][1]||0,f=(d-(u[r-1][1]||0))/2,p=0;p<s;++p){var m=e[t[p]],h=m[r][1]||0,g=m[r-1][1]||0;f+=h-g}c+=d,l+=f*d}i[r-1][1]+=i[r-1][0]=n,c&&(n-=l/c)}i[r-1][1]+=i[r-1][0]=n,gD(e,t)}}var wD=e=>`radius`in e&&`startAngle`in e&&`endAngle`in e,TD=(e,t)=>{if(!e||typeof e==`function`||typeof e==`boolean`)return null;var n=e;if((0,o.isValidElement)(e)&&(n=e.props),typeof n!=`object`&&typeof n!=`function`)return null;var r={};return Object.keys(n).forEach(e=>{wT(e)&&typeof n[e]==`function`&&(r[e]=t||(t=>n[e](n,t)))}),r},ED=(e,t,n)=>r=>(e(t,n,r),null),DD=(e,t,n)=>{if(e===null||typeof e!=`object`&&typeof e!=`function`)return null;var r=null;return Object.keys(e).forEach(i=>{var a=e[i];wT(i)&&typeof a==`function`&&(r||={},r[i]=ED(a,t,n))}),r};function OD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function kD(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?OD(Object(n),!0).forEach(function(t){AD(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):OD(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function AD(e,t,n){return(t=jD(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function jD(e){var t=MD(e,`string`);return typeof t==`symbol`?t:t+``}function MD(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ND(e,t){var n=kD({},e),r=t;return Object.keys(t).reduce((e,t)=>(e[t]===void 0&&r[t]!==void 0&&(e[t]=r[t]),e),n)}function PD(e,t){let n=new Map;for(let r=0;r<e.length;r++){let i=e[r],a=t(i,r,e);n.has(a)||n.set(a,i)}return Array.from(n.values())}function FD(e,t){return function(...n){return e.apply(this,n.slice(0,t))}}function ID(e){return e}function LD(e){return Number.isSafeInteger(e)&&e>=0}function RD(e){return e!=null&&typeof e!=`function`&&LD(e.length)}function zD(e){return function(t){return XT(t,e)}}function BD(e){return e==null||typeof e!=`object`&&typeof e!=`function`}function VD(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function HD(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function UD(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:Object.prototype.toString.call(e)}var WD=`[object RegExp]`,GD=`[object String]`,KD=`[object Number]`,qD=`[object Boolean]`,JD=`[object Arguments]`,YD=`[object Symbol]`,XD=`[object Date]`,ZD=`[object Map]`,QD=`[object Set]`,$D=`[object Array]`,eO=`[object Function]`,tO=`[object ArrayBuffer]`,nO=`[object Object]`,rO=`[object Error]`,iO=`[object DataView]`,aO=`[object Uint8Array]`,oO=`[object Uint8ClampedArray]`,sO=`[object Uint16Array]`,cO=`[object Uint32Array]`,mie=`[object BigUint64Array]`,lO=`[object Int8Array]`,uO=`[object Int16Array]`,dO=`[object Int32Array]`,hie=`[object BigInt64Array]`,fO=`[object Float32Array]`,pO=`[object Float64Array]`,mO=typeof globalThis==`object`&&globalThis||typeof window==`object`&&window||typeof self==`object`&&self||typeof global==`object`&&global||(function(){return this})();function hO(e){return mO.Buffer!==void 0&&mO.Buffer.isBuffer(e)}function gie(e,t){return gO(e,void 0,e,new Map,t)}function gO(e,t,n,r=new Map,i=void 0){let a=i?.(e,t,n,r);if(a!==void 0)return a;if(BD(e))return e;if(r.has(e))return r.get(e);if(Array.isArray(e)){let t=Array(e.length);r.set(e,t);for(let a=0;a<e.length;a++)t[a]=gO(e[a],a,n,r,i);return Object.hasOwn(e,`index`)&&(t.index=e.index),Object.hasOwn(e,`input`)&&(t.input=e.input),t}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){let t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,t}if(e instanceof Map){let t=new Map;r.set(e,t);for(let[a,o]of e)t.set(a,gO(o,a,n,r,i));return t}if(e instanceof Set){let t=new Set;r.set(e,t);for(let a of e)t.add(gO(a,void 0,n,r,i));return t}if(hO(e))return e.subarray();if(VD(e)){let t=new(Object.getPrototypeOf(e)).constructor(e.length);r.set(e,t);for(let a=0;a<e.length;a++)t[a]=gO(e[a],a,n,r,i);return t}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){let t=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return r.set(e,t),_O(t,e,n,r,i),t}if(typeof File<`u`&&e instanceof File){let t=new File([e],e.name,{type:e.type});return r.set(e,t),_O(t,e,n,r,i),t}if(typeof Blob<`u`&&e instanceof Blob){let t=new Blob([e],{type:e.type});return r.set(e,t),_O(t,e,n,r,i),t}if(e instanceof Error){let t=structuredClone(e);return r.set(e,t),t.message=e.message,t.name=e.name,t.stack=e.stack,t.cause=e.cause,t.constructor=e.constructor,_O(t,e,n,r,i),t}if(e instanceof Boolean){let t=new Boolean(e.valueOf());return r.set(e,t),_O(t,e,n,r,i),t}if(e instanceof Number){let t=new Number(e.valueOf());return r.set(e,t),_O(t,e,n,r,i),t}if(e instanceof String){let t=new String(e.valueOf());return r.set(e,t),_O(t,e,n,r,i),t}if(typeof e==`object`&&_ie(e)){let t=Object.create(Object.getPrototypeOf(e));return r.set(e,t),_O(t,e,n,r,i),t}return e}function _O(e,t,n=e,r,i){let a=[...Object.keys(t),...HD(t)];for(let o=0;o<a.length;o++){let s=a[o],c=Object.getOwnPropertyDescriptor(e,s);(c==null||c.writable)&&(e[s]=gO(t[s],s,n,r,i))}}function _ie(e){switch(UD(e)){case JD:case $D:case tO:case iO:case qD:case XD:case fO:case pO:case lO:case uO:case dO:case ZD:case KD:case nO:case WD:case QD:case GD:case YD:case aO:case oO:case sO:case cO:return!0;default:return!1}}function vie(e){return gO(e,void 0,e,new Map,void 0)}function vO(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function yO(e){return e!==null&&(typeof e==`object`||typeof e==`function`)}function bO(e,t,n){return typeof n==`function`?xO(e,t,function e(t,r,i,a,o,s){let c=n(t,r,i,a,o,s);return c===void 0?xO(t,r,e,s,!1):!!c},new Map,!0):bO(e,t,()=>void 0)}function xO(e,t,n,r,i=!1){if(t===e)return!0;switch(typeof t){case`object`:return yie(e,t,n,r,i);case`function`:return Object.keys(t).length>0?xO(e,{...t},n,r,i):vO(e,t);default:return yO(e)&&i?typeof t!=`string`||t===``:vO(e,t)}}function yie(e,t,n,r,i=!1){if(t==null)return!0;if(Array.isArray(t))return SO(e,t,n,r);if(t instanceof Map)return bie(e,t,n,r);if(t instanceof Set)return xie(e,t,n,r);let a=Object.keys(t);if(e==null)return i&&a.length===0;if(i)BD(e)&&(e=Object(e));else{let t=UD(e);if(t!==`[object Object]`&&t!==`[object Arguments]`)return!1}if(a.length===0)return!0;if(r?.has(t))return r.get(t)===e;r?.set(t,e);try{for(let i=0;i<a.length;i++){let o=a[i];if(!(o in e)||t[o]===void 0&&e[o]!==void 0||t[o]===null&&e[o]!==null||!n(e[o],t[o],o,e,t,r))return!1}return!0}finally{r?.delete(t)}}function bie(e,t,n,r){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[i,a]of t.entries())if(n(e.get(i),a,i,e,t,r)===!1)return!1;return!0}function SO(e,t,n,r){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let i=new Set;for(let a=0;a<t.length;a++){let o=t[a],s=!1;for(let c=0;c<e.length;c++){if(i.has(c))continue;let l=e[c],u=!1;if(n(l,o,a,e,t,r)&&(u=!0),u){i.add(c),s=!0;break}}if(!s)return!1}return!0}function xie(e,t,n,r){return t.size===0||e instanceof Set&&SO([...e],[...t],n,r)}function CO(e,t){return bO(e,t,()=>void 0)}function Sie(e){return e=vie(e),t=>CO(t,e)}function Cie(e,t){return gie(e,(n,r,i,a)=>{let o=t?.(n,r,i,a);if(o!==void 0)return o;if(typeof e==`object`){if(UD(e)===`[object Object]`&&typeof e.constructor!=`function`){let t={};return a.set(e,t),_O(t,e,i,a),t}switch(Object.prototype.toString.call(e)){case KD:case GD:case qD:{let t=new e.constructor(e?.valueOf());return _O(t,e),t}case JD:{let t={};return _O(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}})}function wie(e){return Cie(e)}var Tie=/^(?:0|[1-9]\d*)$/;function wO(e,t=2**53-1){switch(typeof e){case`number`:return Number.isInteger(e)&&e>=0&&e<t;case`symbol`:return!1;case`string`:return Tie.test(e)}}function Eie(e){return typeof e==`object`&&!!e&&UD(e)===`[object Arguments]`}function Die(e,t){let n;if(n=Array.isArray(t)?t:typeof t==`string`&&WT(t)&&!(t in Object(e))?YT(t):[t],n.length===0)return!1;let r=e;for(let e=0;e<n.length;e++){let t=GT(n[e]);if((r==null||!Object.hasOwn(r,t))&&!((Array.isArray(r)||Eie(r))&&wO(t)&&Number(t)<r.length))return!1;r=r[t]}return!0}function Oie(e,t){switch(typeof e){case`object`:Object.is(e?.valueOf(),-0)&&(e=`-0`);break;case`number`:e=GT(e)}return t=wie(t),function(n){let r=XT(n,e);return r===void 0?Die(n,e):t===void 0?r===void 0:CO(r,t)}}function kie(e){if(e==null)return ID;switch(typeof e){case`function`:return e;case`object`:return Array.isArray(e)&&e.length===2?Oie(e[0],e[1]):Sie(e);default:return zD(e)}}function Aie(e){return e===0?0:e}function TO(e,t=ID){return RD(e)?PD(Array.from(e),FD(kie(t),1)).map(Aie):[]}function jie(e,t,n){return t===!0?TO(e,n):typeof t==`function`?TO(e,t):e}var Mie=n((e=>{var t=r();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:n,a=t.useState,o=t.useEffect,s=t.useLayoutEffect,c=t.useDebugValue;function l(e,t){var n=t(),r=a({inst:{value:n,getSnapshot:t}}),i=r[0].inst,l=r[1];return s(function(){i.value=n,i.getSnapshot=t,u(i)&&l({inst:i})},[e,n,t]),o(function(){return u(i)&&l({inst:i}),e(function(){u(i)&&l({inst:i})})},[e]),c(n),n}function u(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!i(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:l;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),Nie=n(((e,t)=>{t.exports=Mie()})),Pie=n((e=>{var t=r(),n=Nie();function i(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var a=typeof Object.is==`function`?Object.is:i,o=n.useSyncExternalStore,s=t.useRef,c=t.useEffect,l=t.useMemo,u=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var d=s(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=l(function(){function e(e){if(!o){if(o=!0,s=e,e=r(e),i!==void 0&&f.hasValue){var t=f.value;if(i(t,e))return c=t}return c=e}if(t=c,a(s,e))return t;var n=r(e);return i!==void 0&&i(t,n)?(s=e,t):(s=e,c=n)}var o=!1,s,c,l=n===void 0?null:n;return[function(){return e(t())},l===null?void 0:function(){return e(l())}]},[t,n,r,i]);var p=o(e,d[0],d[1]);return c(function(){f.hasValue=!0,f.value=p},[p]),u(p),p}})),EO=n(((e,t)=>{t.exports=Pie()}))(),DO=(0,o.createContext)(null),Fie=e=>e,OO=()=>{var e=(0,o.useContext)(DO);return e?e.store.dispatch:Fie},kO=()=>{},Iie=()=>kO,Lie=(e,t)=>e===t;function X(e){var t=(0,o.useContext)(DO),n=(0,o.useMemo)(()=>t?t=>{if(t!=null)return e(t)}:kO,[t,e]);return(0,EO.useSyncExternalStoreWithSelector)(t?t.subscription.addNestedSub:Iie,t?t.store.getState:kO,t?t.store.getState:kO,n,Lie)}function Rie(e,t=`expected a function, instead received ${typeof e}`){if(typeof e!=`function`)throw TypeError(t)}function zie(e,t=`expected all items to be functions, instead received the following types: `){if(!e.every(e=>typeof e==`function`)){let n=e.map(e=>typeof e==`function`?`function ${e.name||`unnamed`}()`:typeof e).join(`, `);throw TypeError(`${t}[${n}]`)}}var AO=e=>Array.isArray(e)?e:[e];function Bie(e){let t=Array.isArray(e[0])?e[0]:e;return zie(t,`createSelector expects all input-selectors to be functions, but received the following types: `),t}function Vie(e,t){let n=[],{length:r}=e;for(let i=0;i<r;i++)n.push(e[i].apply(null,t));return n}var Hie=class{constructor(e){this.value=e}deref(){return this.value}},jO=typeof WeakRef>`u`?Hie:WeakRef,Uie=0,MO=1;function NO(){return{s:Uie,v:void 0,o:null,p:null}}function Wie(e){return e instanceof jO?e.deref():e}function PO(e,t={}){let n=NO(),{resultEqualityCheck:r}=t,i,a=0;function o(){let t=n,{length:o}=arguments;for(let e=0,n=o;e<n;e++){let n=arguments[e];if(typeof n==`function`||typeof n==`object`&&n){let e=t.o;e===null&&(t.o=e=new WeakMap);let r=e.get(n);r===void 0?(t=NO(),e.set(n,t)):t=r}else{let e=t.p;e===null&&(t.p=e=new Map);let r=e.get(n);r===void 0?(t=NO(),e.set(n,t)):t=r}}let s=t,c;if(t.s===MO)c=t.v;else if(c=e.apply(null,arguments),a++,r){let e=Wie(i);e!=null&&r(e,c)&&(c=e,a!==0&&a--),i=typeof c==`object`&&c||typeof c==`function`?new jO(c):c}return s.s=MO,s.v=c,c}return o.clearCache=()=>{n=NO(),o.resetResultsCount()},o.resultsCount=()=>a,o.resetResultsCount=()=>{a=0},o}function Gie(e,...t){let n=typeof e==`function`?{memoize:e,memoizeOptions:t}:e,r=(...e)=>{let t=0,r=0,i,a={},o=e.pop();typeof o==`object`&&(a=o,o=e.pop()),Rie(o,`createSelector expects an output function after the inputs, but received: [${typeof o}]`);let{memoize:s,memoizeOptions:c=[],argsMemoize:l=PO,argsMemoizeOptions:u=[]}={...n,...a},d=AO(c),f=AO(u),p=Bie(e),m=s(function(){return t++,o.apply(null,arguments)},...d),h=l(function(){r++;let e=Vie(p,arguments);return i=m.apply(null,e),i},...f);return Object.assign(h,{resultFunc:o,memoizedResultFunc:m,dependencies:p,dependencyRecomputations:()=>r,resetDependencyRecomputations:()=>{r=0},lastResult:()=>i,recomputations:()=>t,resetRecomputations:()=>{t=0},memoize:s,argsMemoize:l})};return Object.assign(r,{withTypes:()=>r}),r}var Z=Gie(PO);function Kie(e,t=1){let n=[],r=Math.floor(t),i=(e,t)=>{for(let a=0;a<e.length;a++){let o=e[a];Array.isArray(o)&&t<r?i(o,t+1):n.push(o)}};return i(e,0),n}function FO(e,t,n){return yO(n)&&(typeof t==`number`&&RD(n)&&wO(t)&&t<n.length||typeof t==`string`&&t in n)?vO(n[t],e):!1}function IO(e){return typeof e==`symbol`?1:e===null?2:e===void 0?3:e===e?0:4}var qie=(e,t,n)=>{if(e!==t){let r=IO(e),i=IO(t);if(r===i&&r===0){if(e<t)return n===`desc`?1:-1;if(e>t)return n===`desc`?-1:1}return n===`desc`?i-r:r-i}return 0},Jie=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Yie=/^\w*$/;function Xie(e,t){return Array.isArray(e)?!1:typeof e==`number`||typeof e==`boolean`||e==null||KT(e)?!0:typeof e==`string`&&(Yie.test(e)||!Jie.test(e))||t!=null&&Object.hasOwn(t,e)}function Zie(e,t,n,r){if(e==null)return[];n=r?void 0:n,Array.isArray(e)||(e=RD(e)?Array.from(e):Object.values(e)),Array.isArray(t)||(t=t==null?[null]:[t]),t.length===0&&(t=[null]),Array.isArray(n)||(n=n==null?[]:[n]),n=n.map(e=>String(e));let i=(e,t)=>{let n=e,r=0;for(;r<t.length&&n!=null;++r)n=n[t[r]];return r>0&&r===t.length?n:void 0},a=(e,t)=>{if(e==null)return t;if(t!=null)return typeof e==`object`&&`key`in e?Object.hasOwn(t,e.key)?t[e.key]:i(t,e.path):typeof e==`function`?e(t):Array.isArray(e)?i(t,e):t[e]},o=t.map(e=>(Array.isArray(e)&&e.length===1&&(e=e[0]),e==null||typeof e==`function`||Array.isArray(e)||Xie(e)?e:{key:e,path:YT(e)}));return e.map(e=>({original:e,criteria:o.map(t=>a(t,e))})).slice().sort((e,t)=>{for(let r=0;r<o.length;r++){let i=qie(e.criteria[r],t.criteria[r],n[r]);if(i!==0)return i}return 0}).map(e=>e.original)}function LO(e,...t){let n=t.length;return n>1&&FO(e,t[0],t[1])?t=[]:n>2&&FO(t[0],t[1],t[2])&&(t=[t[0]]),Zie(e,Kie(t),[`asc`])}var RO=e=>e.legend.settings,Qie=e=>e.legend.size;Z([e=>e.legend.payload,RO],(e,t)=>{var n=t.itemSorter,r=e.flat(1);return n?LO(r,n):r});function $ie(e,t){return rae(e)||nae(e,t)||tae(e,t)||eae()}function eae(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
14
14
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function tae(e,t){if(e){if(typeof e==`string`)return zO(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?zO(e,t):void 0}}function zO(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function nae(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function rae(e){if(Array.isArray(e))return e}var BO=1;function VO(e,t){return Math.abs(e.height-t.height)>BO||Math.abs(e.left-t.left)>BO||Math.abs(e.top-t.top)>BO||Math.abs(e.width-t.width)>BO}function HO(e){var t=e.getBoundingClientRect();return{height:t.height,left:t.left,top:t.top,width:t.width}}function iae(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=$ie((0,o.useState)({height:0,left:0,top:0,width:0}),2),n=t[0],r=t[1],i=(0,o.useRef)(null),a=(0,o.useRef)(n);a.current=n;var s=(0,o.useCallback)(e=>{if(i.current!=null&&(i.current.disconnect(),i.current=null),e!=null){var t=HO(e);if(VO(t,a.current)&&r(t),typeof ResizeObserver<`u`){var n=new ResizeObserver(()=>{var t=HO(e);VO(t,a.current)&&r(t)});n.observe(e),i.current=n}}},[...e]);return(0,o.useEffect)(()=>()=>{var e;(e=i.current)==null||e.disconnect()},[]),[n,s]}function UO(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var WO=typeof Symbol==`function`&&Symbol.observable||`@@observable`,GO=()=>Math.random().toString(36).substring(7).split(``).join(`.`),KO={INIT:`@@redux/INIT${GO()}`,REPLACE:`@@redux/REPLACE${GO()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${GO()}`};function qO(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function JO(e,t,n){if(typeof e!=`function`)throw Error(UO(2));if(typeof t==`function`&&typeof n==`function`||typeof n==`function`&&typeof arguments[3]==`function`)throw Error(UO(0));if(typeof t==`function`&&n===void 0&&(n=t,t=void 0),n!==void 0){if(typeof n!=`function`)throw Error(UO(1));return n(JO)(e,t)}let r=e,i=t,a=new Map,o=a,s=0,c=!1;function l(){o===a&&(o=new Map,a.forEach((e,t)=>{o.set(t,e)}))}function u(){if(c)throw Error(UO(3));return i}function d(e){if(typeof e!=`function`)throw Error(UO(4));if(c)throw Error(UO(5));let t=!0;l();let n=s++;return o.set(n,e),function(){if(t){if(c)throw Error(UO(6));t=!1,l(),o.delete(n),a=null}}}function f(e){if(!qO(e))throw Error(UO(7));if(e.type===void 0)throw Error(UO(8));if(typeof e.type!=`string`)throw Error(UO(17));if(c)throw Error(UO(9));try{c=!0,i=r(i,e)}finally{c=!1}return(a=o).forEach(e=>{e()}),e}function p(e){if(typeof e!=`function`)throw Error(UO(10));r=e,f({type:KO.REPLACE})}function m(){let e=d;return{subscribe(t){if(typeof t!=`object`||!t)throw Error(UO(11));function n(){let e=t;e.next&&e.next(u())}return n(),{unsubscribe:e(n)}},[WO](){return this}}}return f({type:KO.INIT}),{dispatch:f,subscribe:d,getState:u,replaceReducer:p,[WO]:m}}function aae(e){Object.keys(e).forEach(t=>{let n=e[t];if(n(void 0,{type:KO.INIT})===void 0)throw Error(UO(12));if(n(void 0,{type:KO.PROBE_UNKNOWN_ACTION()})===void 0)throw Error(UO(13))})}function YO(e){let t=Object.keys(e),n={};for(let r=0;r<t.length;r++){let i=t[r];typeof e[i]==`function`&&(n[i]=e[i])}let r=Object.keys(n),i;try{aae(n)}catch(e){i=e}return function(e={},t){if(i)throw i;let a=!1,o={};for(let i=0;i<r.length;i++){let s=r[i],c=n[s],l=e[s],u=c(l,t);if(u===void 0)throw t&&t.type,Error(UO(14));o[s]=u,a||=u!==l}return a||=r.length!==Object.keys(e).length,a?o:e}}function XO(...e){return e.length===0?e=>e:e.length===1?e[0]:e.reduce((e,t)=>(...n)=>e(t(...n)))}function oae(...e){return t=>(n,r)=>{let i=t(n,r),a=()=>{throw Error(UO(15))},o={getState:i.getState,dispatch:(e,...t)=>a(e,...t)};return a=XO(...e.map(e=>e(o)))(i.dispatch),{...i,dispatch:a}}}function ZO(e){return qO(e)&&`type`in e&&typeof e.type==`string`}var QO=Symbol.for(`immer-nothing`),$O=Symbol.for(`immer-draftable`),ek=Symbol.for(`immer-state`);function tk(e,...t){throw Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var nk=Object,rk=nk.getPrototypeOf,ik=`constructor`,ak=`prototype`,ok=`configurable`,sk=`enumerable`,ck=`writable`,lk=`value`,uk=e=>!!e&&!!e[ek];function dk(e){return e?pk(e)||yk(e)||!!e[$O]||!!e[ik]?.[$O]||bk(e)||xk(e):!1}var sae=nk[ak][ik].toString(),fk=new WeakMap;function pk(e){if(!e||!Sk(e))return!1;let t=rk(e);if(t===null||t===nk[ak])return!0;let n=nk.hasOwnProperty.call(t,ik)&&t[ik];if(n===Object)return!0;if(!Ck(n))return!1;let r=fk.get(n);return r===void 0&&(r=Function.toString.call(n),fk.set(n,r)),r===sae}function mk(e,t,n=!0){hk(e)===0?(n?Reflect.ownKeys(e):nk.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function hk(e){let t=e[ek];return t?t.type_:yk(e)?1:bk(e)?2:xk(e)?3:0}var gk=(e,t,n=hk(e))=>n===2?e.has(t):nk[ak].hasOwnProperty.call(e,t),_k=(e,t,n=hk(e))=>n===2?e.get(t):e[t],vk=(e,t,n,r=hk(e))=>{r===2?e.set(t,n):r===3?e.add(n):e[t]=n};function cae(e,t){return e===t?e!==0||1/e==1/t:e!==e&&t!==t}var yk=Array.isArray,bk=e=>e instanceof Map,xk=e=>e instanceof Set,Sk=e=>typeof e==`object`,Ck=e=>typeof e==`function`,wk=e=>typeof e==`boolean`;function lae(e){let t=+e;return Number.isInteger(t)&&String(t)===e}var Tk=e=>e.copy_||e.base_,Ek=e=>e.modified_?e.copy_:e.base_;function Dk(e,t){if(bk(e))return new Map(e);if(xk(e))return new Set(e);if(yk(e))return Array[ak].slice.call(e);let n=pk(e);if(t===!0||t===`class_only`&&!n){let t=nk.getOwnPropertyDescriptors(e);delete t[ek];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){let i=n[r],a=t[i];a[ck]===!1&&(a[ck]=!0,a[ok]=!0),(a.get||a.set)&&(t[i]={[ok]:!0,[ck]:!0,[sk]:a[sk],[lk]:e[i]})}return nk.create(rk(e),t)}{let t=rk(e);if(t!==null&&n)return{...e};let r=nk.create(t);return nk.assign(r,e)}}function Ok(e,t=!1){return Ak(e)||uk(e)||!dk(e)?e:(hk(e)>1&&nk.defineProperties(e,{set:kk,add:kk,clear:kk,delete:kk}),nk.freeze(e),t&&mk(e,(e,t)=>{Ok(t,!0)},!1),e)}function uae(){tk(2)}var kk={[lk]:uae};function Ak(e){return e===null||!Sk(e)||nk.isFrozen(e)}var jk=`MapSet`,Mk=`Patches`,Nk=`ArrayMethods`,Pk={};function Fk(e){let t=Pk[e];return t||tk(0,e),t}var Ik=e=>!!Pk[e],Lk,Rk=()=>Lk,dae=(e,t)=>({drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:Ik(jk)?Fk(jk):void 0,arrayMethodsPlugin_:Ik(Nk)?Fk(Nk):void 0});function zk(e,t){t&&(e.patchPlugin_=Fk(Mk),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function Bk(e){Vk(e),e.drafts_.forEach(fae),e.drafts_=null}function Vk(e){e===Lk&&(Lk=e.parent_)}var Hk=e=>Lk=dae(Lk,e);function fae(e){let t=e[ek];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function Uk(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];if(e!==void 0&&e!==n){n[ek].modified_&&(Bk(t),tk(4)),dk(e)&&(e=Wk(t,e));let{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[ek].base_,e,t)}else e=Wk(t,n);return pae(t,e,!0),Bk(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e===QO?void 0:e}function Wk(e,t){if(Ak(t))return t;let n=t[ek];if(!n)return Yk(t,e.handledSet_,e);if(!Kk(n,e))return t;if(!n.modified_)return n.base_;if(!n.finalized_){let{callbacks_:t}=n;if(t)for(;t.length>0;)t.pop()(e);Jk(n,e)}return n.copy_}function pae(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&Ok(t,n)}function Gk(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var Kk=(e,t)=>e.scope_===t,mae=[];function qk(e,t,n,r){let i=Tk(e),a=e.type_;if(r!==void 0&&_k(i,r,a)===t){vk(i,r,n,a);return}if(!e.draftLocations_){let t=e.draftLocations_=new Map;mk(i,(e,n)=>{if(uk(n)){let r=t.get(n)||[];r.push(e),t.set(n,r)}})}let o=e.draftLocations_.get(t)??mae;for(let e of o)vk(i,e,n,a)}function hae(e,t,n){e.callbacks_.push(function(r){let i=t;if(!i||!Kk(i,r))return;r.mapSetPlugin_?.fixSetContents(i);let a=Ek(i);qk(e,i.draft_??i,a,n),Jk(i,r)})}function Jk(e,t){if(e.modified_&&!e.finalized_&&(e.type_===3||e.type_===1&&e.allIndicesReassigned_||(e.assigned_?.size??0)>0)){let{patchPlugin_:n}=t;if(n){let r=n.getPath(e);r&&n.generatePatches_(e,r,t)}Gk(e)}}function gae(e,t,n){let{scope_:r}=e;if(uk(n)){let i=n[ek];Kk(i,r)&&i.callbacks_.push(function(){tA(e),qk(e,n,Ek(i),t)})}else dk(n)&&e.callbacks_.push(function(){let i=Tk(e);e.type_===3?i.has(n)&&Yk(n,r.handledSet_,r):_k(i,t,e.type_)===n&&r.drafts_.length>1&&(e.assigned_.get(t)??!1)===!0&&e.copy_&&Yk(_k(e.copy_,t,e.type_),r.handledSet_,r)})}function Yk(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||uk(e)||t.has(e)||!dk(e)||Ak(e)?e:(t.add(e),mk(e,(r,i)=>{if(uk(i)){let t=i[ek];Kk(t,n)&&(vk(e,r,Ek(t),e.type_),Gk(t))}else dk(i)&&Yk(i,t,n)}),e)}function _ae(e,t){let n=yk(e),r={type_:+!!n,scope_:t?t.scope_:Rk(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0},i=r,a=Xk;n&&(i=[r],a=Zk);let{revoke:o,proxy:s}=Proxy.revocable(i,a);return r.draft_=s,r.revoke_=o,[s,r]}var Xk={get(e,t){if(t===ek)return e;let n=e.scope_.arrayMethodsPlugin_,r=e.type_===1&&typeof t==`string`;if(r&&n?.isArrayOperationMethod(t))return n.createMethodInterceptor(e,t);let i=Tk(e);if(!gk(i,t,e.type_))return yae(e,i,t);let a=i[t];if(e.finalized_||!dk(a)||r&&e.operationMethod&&n?.isMutatingArrayMethod(e.operationMethod)&&lae(t))return a;if(a===Qk(e.base_,t)||vae(e,t,a)){tA(e);let n=e.type_===1?+t:t,r=nA(e.scope_,a,e,n);return e.copy_[n]=r}return a},has(e,t){return t in Tk(e)},ownKeys(e){return Reflect.ownKeys(Tk(e))},set(e,t,n){let r=$k(Tk(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let r=Qk(Tk(e),t),i=r?.[ek];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_.delete(t),!0;if(cae(n,r)&&(n!==void 0||gk(e.base_,t,e.type_)))return!0;tA(e),eA(e)}return e.copy_[t]===n&&(n!==void 0||gk(e.copy_,t,e.type_))||Number.isNaN(n)&&Number.isNaN(e.copy_[t])?!0:(e.copy_[t]=n,e.assigned_.set(t,!0),gae(e,t,n),!0)},deleteProperty(e,t){return tA(e),Qk(e.base_,t)!==void 0||t in e.base_?(e.assigned_.set(t,!1),eA(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=Tk(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{[ck]:!0,[ok]:e.type_!==1||t!==`length`,[sk]:r[sk],[lk]:n[t]}},defineProperty(){tk(11)},getPrototypeOf(e){return rk(e.base_)},setPrototypeOf(){tk(12)}},Zk={};for(let e in Xk){let t=Xk[e];Zk[e]=function(){let e=arguments;return e[0]=e[0][0],t.apply(this,e)}}Zk.deleteProperty=function(e,t){return Zk.set.call(this,e,t,void 0)},Zk.set=function(e,t,n){return Xk.set.call(this,e[0],t,n,e[0])};function Qk(e,t){let n=e[ek];return(n?Tk(n):e)[t]}function vae(e,t,n){return e.type_!==1||!e.allIndicesReassigned_||e.assigned_?.get(t)||!dk(n)||n[ek]?!1:e.baseRefs_.has(n)}function yae(e,t,n){let r=$k(t,n);return r?lk in r?r[lk]:r.get?.call(e.draft_):void 0}function $k(e,t){if(!(t in e))return;let n=rk(e);for(;n;){let e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=rk(n)}}function eA(e){e.modified_||(e.modified_=!0,e.parent_&&eA(e.parent_))}function tA(e){e.copy_||=(e.assigned_=new Map,Dk(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var bae=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(Ck(e)&&!Ck(t)){let n=t;t=e;let r=this;return function(e=n,...i){return r.produce(e,e=>t.call(this,e,...i))}}Ck(t)||tk(6),n!==void 0&&!Ck(n)&&tk(7);let r;if(dk(e)){let i=Hk(this),a=nA(i,e,void 0),o=!0;try{r=t(a),o=!1}finally{o?Bk(i):Vk(i)}return zk(i,n),Uk(r,i)}if(!e||!Sk(e)){if(r=t(e),r===void 0&&(r=e),r===QO&&(r=void 0),this.autoFreeze_&&Ok(r,!0),n){let t=[],i=[];Fk(Mk).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:i}),n(t,i)}return r}tk(1,e)},this.produceWithPatches=(e,t)=>{if(Ck(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,r;return[this.produce(e,t,(e,t)=>{n=e,r=t}),n,r]},wk(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),wk(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),wk(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){dk(e)||tk(8),uk(e)&&(e=rA(e));let t=Hk(this),n=nA(t,e,void 0);return n[ek].isManual_=!0,Vk(t),n}finishDraft(e,t){let n=e&&e[ek];(!n||!n.isManual_)&&tk(9);let{scope_:r}=n;return zk(r,t),Uk(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let r=t[n];if(r.path.length===0&&r.op===`replace`){e=r.value;break}}n>-1&&(t=t.slice(n+1));let r=Fk(Mk).applyPatches_;return uk(e)?r(e,t):this.produce(e,e=>r(e,t))}};function nA(e,t,n,r){let[i,a]=bk(t)?Fk(jk).proxyMap_(t,n):xk(t)?Fk(jk).proxySet_(t,n):_ae(t,n);return(n?.scope_??Rk()).drafts_.push(i),a.callbacks_=n?.callbacks_??[],a.key_=r,n&&r!==void 0?hae(n,a,r):a.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(a);let{patchPlugin_:t}=e;a.modified_&&t&&t.generatePatches_(a,[],e)}),i}function rA(e){return uk(e)||tk(10,e),iA(e)}function iA(e){if(!dk(e)||Ak(e))return e;let t=e[ek],n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=Dk(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=Dk(e,!0);return mk(n,(e,t)=>{vk(n,e,iA(t))},r),t&&(t.finalized_=!1),n}globalThis.Iterator?.from;var aA=new bae().produce,oA=e=>e;function sA(e){return({dispatch:t,getState:n})=>r=>i=>typeof i==`function`?i(t,n,e):r(i)}var xae=sA(),Sae=sA,Cae=typeof window<`u`&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]==`object`?XO:XO.apply(null,arguments)};typeof window<`u`&&window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__;function cA(e,t){function n(...n){if(t){let r=t(...n);if(!r)throw Error(UA(0));return{type:e,payload:r.payload,...`meta`in r&&{meta:r.meta},...`error`in r&&{error:r.error}}}return{type:e,payload:n[0]}}return n.toString=()=>`${e}`,n.type=e,n.match=t=>ZO(t)&&t.type===e,n}var lA=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return t.length===1&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function uA(e){return dk(e)?aA(e,()=>{}):e}function dA(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}function wae(e){return typeof e==`boolean`}var Tae=()=>function(e){let{thunk:t=!0,immutableCheck:n=!0,serializableCheck:r=!0,actionCreatorCheck:i=!0}=e??{},a=new lA;return t&&(wae(t)?a.push(xae):a.push(Sae(t.extraArgument))),a},fA=`RTK_autoBatch`,pA=()=>e=>({payload:e,meta:{[fA]:!0}}),mA=e=>t=>{setTimeout(t,e)},Eae=(e,t)=>n=>{let r=!1,i,a,o=()=>{r||(r=!0,cancelAnimationFrame(i),clearTimeout(a),n())};i=e(o),a=setTimeout(o,t)},hA=(e={type:`raf`})=>t=>(...n)=>{let r=t(...n),i=!0,a=!1,o=!1,s=new Set,c=e.type===`tick`?queueMicrotask:e.type===`raf`?typeof window<`u`&&window.requestAnimationFrame?Eae(window.requestAnimationFrame,100):mA(10):e.type===`callback`?e.queueNotification:mA(e.timeout),l=()=>{o=!1,a&&(a=!1,s.forEach(e=>e()))};return Object.assign({},r,{subscribe(e){let t=r.subscribe(()=>i&&e());return s.add(e),()=>{t(),s.delete(e)}},dispatch(e){try{return i=!e?.meta?.[fA],a=!i,a&&(o||(o=!0,c(l))),r.dispatch(e)}finally{i=!0}}})},Dae=e=>function(t){let{autoBatch:n=!0}=t??{},r=new lA(e);return n&&r.push(hA(typeof n==`object`?n:void 0)),r};function Oae(e){let t=Tae(),{reducer:n=void 0,middleware:r,devTools:i=!0,duplicateMiddlewareCheck:a=!0,preloadedState:o=void 0,enhancers:s=void 0}=e||{},c;if(typeof n==`function`)c=n;else if(qO(n))c=YO(n);else throw Error(UA(1));let l;l=typeof r==`function`?r(t):t();let u=XO;i&&(u=Cae({trace:!1,...typeof i==`object`&&i}));let d=Dae(oae(...l)),f=typeof s==`function`?s(d):d(),p=u(...f);return JO(c,o,p)}function gA(e){let t={},n=[],r,i={addCase(e,n){let r=typeof e==`string`?e:e.type;if(!r)throw Error(UA(28));if(r in t)throw Error(UA(29));return t[r]=n,i},addAsyncThunk(e,r){return r.pending&&(t[e.pending.type]=r.pending),r.rejected&&(t[e.rejected.type]=r.rejected),r.fulfilled&&(t[e.fulfilled.type]=r.fulfilled),r.settled&&n.push({matcher:e.settled,reducer:r.settled}),i},addMatcher(e,t){return n.push({matcher:e,reducer:t}),i},addDefaultCase(e){return r=e,i}};return e(i),[t,n,r]}function kae(e){return typeof e==`function`}function Aae(e,t){let[n,r,i]=gA(t),a;if(kae(e))a=()=>uA(e());else{let t=uA(e);a=()=>t}function o(e=a(),t){let o=[n[t.type],...r.filter(({matcher:e})=>e(t)).map(({reducer:e})=>e)];return o.filter(e=>!!e).length===0&&(o=[i]),o.reduce((e,n)=>{if(n){if(uk(e)){let r=n(e,t);return r===void 0?e:r}if(dk(e))return aA(e,e=>n(e,t));{let r=n(e,t);if(r===void 0){if(e===null)return e;throw Error(UA(9))}return r}}return e},e)}return o.getInitialState=a,o}var jae=`ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW`,Mae=(e=21)=>{let t=``,n=e;for(;n--;)t+=jae[Math.random()*64|0];return t},Nae=Symbol.for(`rtk-slice-createasyncthunk`);function Pae(e,t){return`${e}/${t}`}function Fae({creators:e}={}){let t=e?.asyncThunk?.[Nae];return function(e){let{name:n,reducerPath:r=n}=e;if(!n)throw Error(UA(11));let i=(typeof e.reducers==`function`?e.reducers(Lae()):e.reducers)||{},a=Object.keys(i),o={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},s={addCase(e,t){let n=typeof e==`string`?e:e.type;if(!n)throw Error(UA(12));if(n in o.sliceCaseReducersByType)throw Error(UA(13));return o.sliceCaseReducersByType[n]=t,s},addMatcher(e,t){return o.sliceMatchers.push({matcher:e,reducer:t}),s},exposeAction(e,t){return o.actionCreators[e]=t,s},exposeCaseReducer(e,t){return o.sliceCaseReducersByName[e]=t,s}};a.forEach(r=>{let a=i[r],o={reducerName:r,type:Pae(n,r),createNotation:typeof e.reducers==`function`};zae(a)?Vae(o,a,s,t):Rae(o,a,s)});function c(){let[t={},n=[],r=void 0]=typeof e.extraReducers==`function`?gA(e.extraReducers):[e.extraReducers],i={...t,...o.sliceCaseReducersByType};return Aae(e.initialState,e=>{for(let t in i)e.addCase(t,i[t]);for(let t of o.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of n)e.addMatcher(t.matcher,t.reducer);r&&e.addDefaultCase(r)})}let l=e=>e,u=new Map,d=new WeakMap,f;function p(e,t){return f||=c(),f(e,t)}function m(){return f||=c(),f.getInitialState()}function h(t,n=!1){function r(e){let i=e[t];return i===void 0&&n&&(i=dA(d,r,m)),i}function i(t=l){return dA(dA(u,n,()=>new WeakMap),t,()=>{let r={};for(let[i,a]of Object.entries(e.selectors??{}))r[i]=Iae(a,t,()=>dA(d,t,m),n);return r})}return{reducerPath:t,getSelectors:i,get selectors(){return i(r)},selectSlice:r}}let g={name:n,reducer:p,actions:o.actionCreators,caseReducers:o.sliceCaseReducersByName,getInitialState:m,...h(r),injectInto(e,{reducerPath:t,...n}={}){let i=t??r;return e.inject({reducerPath:i,reducer:p},n),{...g,...h(i,!0)}}};return g}}function Iae(e,t,n,r){function i(i,...a){let o=t(i);return o===void 0&&r&&(o=n()),e(o,...a)}return i.unwrapped=e,i}var _A=Fae();function Lae(){function e(e,t){return{_reducerDefinitionType:`asyncThunk`,payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer(e){return Object.assign({[e.name](...t){return e(...t)}}[e.name],{_reducerDefinitionType:`reducer`})},preparedReducer(e,t){return{_reducerDefinitionType:`reducerWithPrepare`,prepare:e,reducer:t}},asyncThunk:e}}function Rae({type:e,reducerName:t,createNotation:n},r,i){let a,o;if(`reducer`in r){if(n&&!Bae(r))throw Error(UA(17));a=r.reducer,o=r.prepare}else a=r;i.addCase(e,a).exposeCaseReducer(t,a).exposeAction(t,o?cA(e,o):cA(e))}function zae(e){return e._reducerDefinitionType===`asyncThunk`}function Bae(e){return e._reducerDefinitionType===`reducerWithPrepare`}function Vae({type:e,reducerName:t},n,r,i){if(!i)throw Error(UA(18));let{payloadCreator:a,fulfilled:o,pending:s,rejected:c,settled:l,options:u}=n,d=i(e,a,u);r.exposeAction(t,d),o&&r.addCase(d.fulfilled,o),s&&r.addCase(d.pending,s),c&&r.addCase(d.rejected,c),l&&r.addMatcher(d.settled,l),r.exposeCaseReducer(t,{fulfilled:o||vA,pending:s||vA,rejected:c||vA,settled:l||vA})}function vA(){}var Hae=`task`,yA=`listener`,bA=`completed`,xA=`cancelled`,Uae=`task-${xA}`,Wae=`task-${bA}`,SA=`${yA}-${xA}`,Gae=`${yA}-${bA}`,CA=class{code;name=`TaskAbortError`;message;constructor(e){this.code=e,this.message=`${Hae} ${xA} (reason: ${e})`}},wA=(e,t)=>{if(typeof e!=`function`)throw TypeError(UA(32))},TA=()=>{},EA=(e,t=TA)=>(e.catch(t),e),DA=(e,t)=>(e.addEventListener(`abort`,t,{once:!0}),()=>e.removeEventListener(`abort`,t)),OA=e=>{if(e.aborted)throw new CA(e.reason)};function kA(e,t){let n=TA;return new Promise((r,i)=>{let a=()=>i(new CA(e.reason));if(e.aborted){a();return}n=DA(e,a),t.finally(()=>n()).then(r,i)}).finally(()=>{n=TA})}var Kae=async(e,t)=>{try{return await Promise.resolve(),{status:`ok`,value:await e()}}catch(e){return{status:e instanceof CA?`cancelled`:`rejected`,error:e}}finally{t?.()}},AA=e=>t=>EA(kA(e,t).then(t=>(OA(e),t))),jA=e=>{let t=AA(e);return e=>t(new Promise(t=>setTimeout(t,e)))},{assign:MA}=Object,NA={},PA=`listenerMiddleware`,qae=(e,t)=>{let n=t=>DA(e,()=>t.abort(e.reason));return(r,i)=>{wA(r,`taskExecutor`);let a=new AbortController;n(a);let o=Kae(async()=>{OA(e),OA(a.signal);let t=await r({pause:AA(a.signal),delay:jA(a.signal),signal:a.signal});return OA(a.signal),t},()=>a.abort(Wae));return i?.autoJoin&&t.push(o.catch(TA)),{result:AA(e)(o),cancel(){a.abort(Uae)}}}},Jae=(e,t)=>{let n=async(n,r)=>{OA(t);let i=()=>{},a=[new Promise((t,r)=>{let a=e({predicate:n,effect:(e,n)=>{n.unsubscribe(),t([e,n.getState(),n.getOriginalState()])}});i=()=>{a(),r()}})];r!=null&&a.push(new Promise(e=>setTimeout(e,r,null)));try{let e=await kA(t,Promise.race(a));return OA(t),e}finally{i()}};return((e,t)=>EA(n(e,t)))},FA=e=>{let{type:t,actionCreator:n,matcher:r,predicate:i,effect:a}=e;if(t)i=cA(t).match;else if(n)t=n.type,i=n.match;else if(r)i=r;else if(!i)throw Error(UA(21));return wA(a,`options.listener`),{predicate:i,type:t,effect:a}},IA=MA(e=>{let{type:t,predicate:n,effect:r}=FA(e);return{id:Mae(),effect:r,type:t,predicate:n,pending:new Set,unsubscribe:()=>{throw Error(UA(22))}}},{withTypes:()=>IA}),LA=(e,t)=>{let{type:n,effect:r,predicate:i}=FA(t);return Array.from(e.values()).find(e=>(typeof n==`string`?e.type===n:e.predicate===i)&&e.effect===r)},RA=e=>{e.pending.forEach(e=>{e.abort(SA)})},Yae=(e,t)=>()=>{for(let e of t.keys())RA(e);e.clear()},zA=(e,t,n)=>{try{e(t,n)}catch(e){setTimeout(()=>{throw e},0)}},BA=MA(cA(`${PA}/add`),{withTypes:()=>BA}),Xae=cA(`${PA}/removeAll`),VA=MA(cA(`${PA}/remove`),{withTypes:()=>VA}),Zae=(...e)=>{console.error(`${PA}/error`,...e)},HA=(e={})=>{let t=new Map,n=new Map,r=e=>{let t=n.get(e)??0;n.set(e,t+1)},i=e=>{let t=n.get(e)??1;t===1?n.delete(e):n.set(e,t-1)},{extra:a,onError:o=Zae}=e;wA(o,`onError`);let s=e=>(e.unsubscribe=()=>t.delete(e.id),t.set(e.id,e),t=>{e.unsubscribe(),t?.cancelActive&&RA(e)}),c=(e=>{let n=LA(t,e)??IA(e);return s(n)});MA(c,{withTypes:()=>c});let l=e=>{let n=LA(t,e);return n&&(n.unsubscribe(),e.cancelActive&&RA(n)),!!n};MA(l,{withTypes:()=>l});let u=async(e,n,s,l)=>{let u=new AbortController,d=Jae(c,u.signal),f=[];try{e.pending.add(u),r(e),await Promise.resolve(e.effect(n,MA({},s,{getOriginalState:l,condition:(e,t)=>d(e,t).then(Boolean),take:d,delay:jA(u.signal),pause:AA(u.signal),extra:a,signal:u.signal,fork:qae(u.signal,f),unsubscribe:e.unsubscribe,subscribe:()=>{t.set(e.id,e)},cancelActiveListeners:()=>{e.pending.forEach((e,t,n)=>{e!==u&&(e.abort(SA),n.delete(e))})},cancel:()=>{u.abort(SA),e.pending.delete(u)},throwIfCancelled:()=>{OA(u.signal)}})))}catch(e){e instanceof CA||zA(o,e,{raisedBy:`effect`})}finally{await Promise.all(f),u.abort(Gae),i(e),e.pending.delete(u)}},d=Yae(t,n);return{middleware:e=>n=>r=>{if(!ZO(r))return n(r);if(BA.match(r))return c(r.payload);if(Xae.match(r)){d();return}if(VA.match(r))return l(r.payload);let i=e.getState(),a=()=>{if(i===NA)throw Error(UA(23));return i},s;try{if(s=n(r),t.size>0){let n=e.getState(),s=Array.from(t.values());for(let t of s){let s=!1;try{s=t.predicate(r,n,i)}catch(e){s=!1,zA(o,e,{raisedBy:`predicate`})}s&&u(t,r,e,a)}}}finally{i=NA}return s},startListening:c,stopListening:l,clearListeners:d}};function UA(e){return`Minified Redux Toolkit error #${e}; visit https://redux-toolkit.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var WA=_A({name:`chartLayout`,initialState:{layoutType:`horizontal`,width:0,height:0,margin:{top:5,right:5,bottom:5,left:5},scale:1},reducers:{setLayout(e,t){e.layoutType=t.payload},setChartSize(e,t){e.width=t.payload.width,e.height=t.payload.height},setMargin(e,t){e.margin.top=t.payload.top??0,e.margin.right=t.payload.right??0,e.margin.bottom=t.payload.bottom??0,e.margin.left=t.payload.left??0},setScale(e,t){e.scale=t.payload}}}),GA=WA.actions,Qae=GA.setMargin,$ae=GA.setLayout,eoe=GA.setChartSize,toe=GA.setScale,noe=WA.reducer;function KA(e,t,n){return Array.isArray(e)&&e&&t+n!==0?e.slice(t,n+1):e}function Q(e){return Number.isFinite(e)}function qA(e){return typeof e==`number`&&e>0&&Number.isFinite(e)}function JA(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function YA(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?JA(Object(n),!0).forEach(function(t){roe(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):JA(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function roe(e,t,n){return(t=ioe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ioe(e){var t=aoe(e,`string`);return typeof t==`symbol`?t:t+``}function aoe(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function XA(e,t,n){return dE(e)||dE(t)?n:iE(t)?XT(e,t,n):typeof t==`function`?t(e):n}var ooe=(e,t,n)=>{if(t&&n){var r=n.width,i=n.height,a=t.align,o=t.verticalAlign,s=t.layout,c=t.position,l=t.offset,u=l===void 0?0:l;if(c!=null){if(CE(c)){if(c===`top`&&Y(e.top))return YA(YA({},e),{},{top:e.top+(i||0)+u});if(c===`bottom`&&Y(e.bottom))return YA(YA({},e),{},{bottom:e.bottom+(i||0)+u});if(c===`left`&&Y(e.left))return YA(YA({},e),{},{left:e.left+(r||0)+u});if(c===`right`&&Y(e.right))return YA(YA({},e),{},{right:e.right+(r||0)+u})}return e}if((s===`vertical`||s===`horizontal`&&o===`middle`)&&a!==`center`&&Y(e[a]))return YA(YA({},e),{},{[a]:e[a]+(r||0)});if((s===`horizontal`||s===`vertical`&&a===`center`)&&o!==`middle`&&Y(e[o]))return YA(YA({},e),{},{[o]:e[o]+(i||0)})}return e},ZA=(e,t)=>e===`horizontal`&&t===`xAxis`||e===`vertical`&&t===`yAxis`||e===`centric`&&t===`angleAxis`||e===`radial`&&t===`radiusAxis`,QA=(e,t,n,r)=>{if(r)return e.map(e=>e.coordinate);var i,a,o=e.map(e=>(e.coordinate===t&&(i=!0),e.coordinate===n&&(a=!0),e.coordinate));return i||o.push(t),a||o.push(n),o},$A=(e,t,n)=>{if(!e)return null;var r=e.duplicateDomain,i=e.type,a=e.range,o=e.scale,s=e.realScaleType,c=e.isCategorical,l=e.categoricalDomain,u=e.tickCount,d=e.ticks,f=e.niceTicks,p=e.axisType;if(!o)return null;var m=s===`scaleBand`&&o.bandwidth?o.bandwidth()/2:2,h=(t||n)&&i===`category`&&o.bandwidth?o.bandwidth()/m:0;return h=p===`angleAxis`&&a&&a.length>=2?tE(a[0]-a[1])*2*h:h,t&&(d||f)?(d||f||[]).map((e,t)=>{var n=r?r.indexOf(e):e,i=o.map(n);return Q(i)?{coordinate:i+h,value:e,offset:h,index:t}:null}).filter(pE):c&&l?l.map((e,t)=>{var n=o.map(e);return Q(n)?{coordinate:n+h,value:e,index:t,offset:h}:null}).filter(pE):o.ticks&&!n&&u!=null?o.ticks(u).map((e,t)=>{var n=o.map(e);return Q(n)?{coordinate:n+h,value:e,index:t,offset:h}:null}).filter(pE):o.domain().map((e,t)=>{var n=o.map(e);return Q(n)?{coordinate:n+h,value:r?r[e]:e,index:t,offset:h}:null}).filter(pE)},soe=(e,t)=>{if(!t||t.length!==2||!Y(t[0])||!Y(t[1]))return e;var n=Math.min(t[0],t[1]),r=Math.max(t[0],t[1]),i=[e[0],e[1]];return(!Y(e[0])||e[0]<n)&&(i[0]=n),(!Y(e[1])||e[1]>r)&&(i[1]=r),i[0]>r&&(i[0]=r),i[1]<n&&(i[1]=n),i},coe={sign:e=>{var t=e.length;if(!(t<=0)){var n=e[0]?.length;if(!(n==null||n<=0))for(var r=0;r<n;++r)for(var i=0,a=0,o=0;o<t;++o){var s=e[o]?.[r];if(s!=null){var c=s[1],l=s[0],u=nE(c)?l:c;u>=0?(s[0]=i,i+=u,s[1]=i):(s[0]=a,a+=u,s[1]=a)}}}},expand:xD,none:gD,silhouette:SD,wiggle:CD,positive:e=>{var t=e.length;if(!(t<=0)){var n=e[0]?.length;if(!(n==null||n<=0))for(var r=0;r<n;++r)for(var i=0,a=0;a<t;++a){var o=e[a]?.[r];if(o!=null){var s=nE(o[1])?o[0]:o[1];s>=0?(o[0]=i,i+=s,o[1]=i):(o[0]=0,o[1]=0)}}}}},loe=(e,t,n)=>{var r=coe[n]??gD,i=bD().keys(t).value((e,t)=>Number(XA(e,t,0))).order(_D).offset(r)(e);return i.forEach((n,r)=>{n.forEach((n,i)=>{var a=XA(e[i],t[r],0);Array.isArray(a)&&a.length===2&&Y(a[0])&&Y(a[1])&&(n[0]=a[0],n[1]=a[1])})}),i};function uoe(e){return e==null?void 0:String(e)}function ej(e){var t=e.axis,n=e.ticks,r=e.bandSize,i=e.entry,a=e.index,o=e.dataKey;if(t.type===`category`){if(!t.allowDuplicatedCategory&&t.dataKey&&!dE(i[t.dataKey])){var s=uE(n,`value`,i[t.dataKey]);if(s)return s.coordinate+r/2}return n!=null&&n[a]?n[a].coordinate+r/2:null}var c=XA(i,dE(o)?t.dataKey:o),l=t.scale.map(c);return Y(l)?l:null}var tj=e=>{var t=e.axis,n=e.ticks,r=e.offset,i=e.bandSize,a=e.entry,o=e.index;if(t.type===`category`)return n[o]?n[o].coordinate+r:null;var s=XA(a,t.dataKey,t.scale.domain()[o]);if(dE(s))return null;var c=t.scale.map(s);return Y(c)?c-i/2+r:null},doe=e=>{var t=e.numericAxis,n=t.scale.domain();if(t.type===`number`){var r=Math.min(n[0],n[1]),i=Math.max(n[0],n[1]);return r<=0&&i>=0?0:i<0?i:r}return n[0]},foe=e=>{var t=e.flat(2).filter(Y);return[Math.min(...t),Math.max(...t)]},poe=e=>[e[0]===1/0?0:e[0],e[1]===-1/0?0:e[1]],moe=(e,t,n)=>{if(e!=null&&Object.keys(e).length!==0)return poe(Object.keys(e).reduce((r,i)=>{var a=e[i];if(!a)return r;var o=a.stackedData.reduce((e,r)=>{var i=foe(KA(r,t,n));return!Q(i[0])||!Q(i[1])?e:[Math.min(e[0],i[0]),Math.max(e[1],i[1])]},[1/0,-1/0]);return[Math.min(o[0],r[0]),Math.max(o[1],r[1])]},[1/0,-1/0]))},nj=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,rj=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,ij=(e,t,n)=>{if(e&&e.scale&&e.scale.bandwidth){var r=e.scale.bandwidth();if(!n||r>0)return r}if(e&&t&&t.length>=2){for(var i=LO(t,e=>e.coordinate),a=[],o=0,s=1,c=i.length;s<c;s++){var l=(i[s]?.coordinate||0)-(i[s-1]?.coordinate||0);a.push(l),o=Math.max(l,o)}var u=o*1e-4,d=1/0;for(var f of a)f>u&&(d=Math.min(f,d));return d===1/0?0:d}return n?void 0:0};function aj(e){var t=e.tooltipEntrySettings,n=e.dataKey,r=e.payload,i=e.value,a=e.name;return YA(YA({},t),{},{dataKey:n,payload:r,value:i,name:a})}function oj(e,t){if(e!=null)return String(e);if(typeof t==`string`)return t}var hoe=(e,t)=>{if(t===`horizontal`)return e.relativeX;if(t===`vertical`)return e.relativeY},goe=(e,t)=>t===`centric`?e.angle:e.radius,sj=e=>e.layout.width,cj=e=>e.layout.height,_oe=e=>e.layout.scale,lj=e=>e.layout.margin,uj=Z(e=>e.cartesianAxis.xAxis,e=>Object.values(e)),dj=Z(e=>e.cartesianAxis.yAxis,e=>Object.values(e)),fj=`data-recharts-item-index`,voe=`data-recharts-item-id`;function pj(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function mj(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?pj(Object(n),!0).forEach(function(t){yoe(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):pj(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function yoe(e,t,n){return(t=boe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function boe(e){var t=xoe(e,`string`);return typeof t==`symbol`?t:t+``}function xoe(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var Soe=e=>e.brush.height;function Coe(e){return dj(e).reduce((e,t)=>t.orientation===`left`&&!t.mirror&&!t.hide?e+(typeof t.width==`number`?t.width:60):e,0)}function woe(e){return dj(e).reduce((e,t)=>t.orientation===`right`&&!t.mirror&&!t.hide?e+(typeof t.width==`number`?t.width:60):e,0)}function Toe(e){return uj(e).reduce((e,t)=>t.orientation===`top`&&!t.mirror&&!t.hide?e+(typeof t.height==`number`?t.height:30):e,0)}function Eoe(e){return uj(e).reduce((e,t)=>t.orientation===`bottom`&&!t.mirror&&!t.hide?e+(typeof t.height==`number`?t.height:30):e,0)}var hj=Z([sj,cj,lj,Soe,Coe,woe,Toe,Eoe,RO,Qie],(e,t,n,r,i,a,o,s,c,l)=>{var u={left:(n.left||0)+i,right:(n.right||0)+a},d=mj(mj({},{top:(n.top||0)+o,bottom:(n.bottom||0)+s}),u),f=d.bottom;d.bottom+=r,d=ooe(d,c,l);var p=e-d.left-d.right,m=t-d.top-d.bottom;return mj(mj({brushBottom:f},d),{},{width:Math.max(p,0),height:Math.max(m,0)})}),Doe=Z(hj,e=>({x:e.left,y:e.top,width:e.width,height:e.height})),gj=Z(sj,cj,(e,t)=>({x:0,y:0,width:e,height:t})),Ooe=(0,o.createContext)(null),_j=()=>(0,o.useContext)(Ooe)!=null,vj=e=>e.brush,yj=Z([vj,hj,lj],(e,t,n)=>({height:e.height,x:Y(e.x)?e.x:t.left,y:Y(e.y)?e.y:t.top+t.height+t.brushBottom-(n?.bottom||0),width:Y(e.width)?e.width:t.width}));function koe(e,t,{signal:n,edges:r}={}){let i,a=null,o=r!=null&&r.includes(`leading`),s=r==null||r.includes(`trailing`),c=()=>{a!==null&&(e.apply(i,a),i=void 0,a=null)},l=()=>{s&&c(),p()},u=null,d=()=>{u!=null&&clearTimeout(u),u=setTimeout(()=>{u=null,l()},t)},f=()=>{u!==null&&(clearTimeout(u),u=null)},p=()=>{f(),i=void 0,a=null},m=()=>{c()},h=function(...e){if(n?.aborted)return;i=this,a=e;let t=u==null;d(),o&&t&&c()};return h.schedule=d,h.cancel=p,h.flush=m,n?.addEventListener(`abort`,p,{once:!0}),h}function Aoe(e,t=0,n={}){typeof n!=`object`&&(n={});let{leading:r=!1,trailing:i=!0,maxWait:a}=n,o=[,,];r&&(o[0]=`leading`),i&&(o[1]=`trailing`);let s,c=null,l=koe(function(...t){s=e.apply(this,t),c=null},t,{edges:o}),u=function(...t){return a!=null&&(c===null&&(c=Date.now()),Date.now()-c>=a)?((r||i)&&(s=e.apply(this,t)),c=Date.now(),l.cancel(),l.schedule(),s):(l.apply(this,t),s)};return u.cancel=l.cancel,u.flush=()=>(l.flush(),s),u}function joe(e,t=0,n={}){let{leading:r=!0,trailing:i=!0}=n;return Aoe(e,t,{leading:r,maxWait:t,trailing:i})}var bj=function(e,t){var n=[...arguments].slice(2);if(typeof console<`u`&&console.warn&&(t===void 0&&console.warn(`LogUtils requires an error message argument`),!e)){if(t===void 0)console.warn(`Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.`);else{var r=0;console.warn(t.replace(/%s/g,()=>n[r++]))}}},xj={width:`100%`,height:`100%`,debounce:0,minWidth:0,initialDimension:{width:-1,height:-1}},Sj=(e,t,n)=>{var r=n.width,i=r===void 0?xj.width:r,a=n.height,o=a===void 0?xj.height:a,s=n.aspect,c=n.maxHeight,l=rE(i)?e:Number(i),u=rE(o)?t:Number(o);return s&&s>0&&(l?u=l/s:u&&(l=u*s),c&&u!=null&&u>c&&(u=c)),{calculatedWidth:l,calculatedHeight:u}},Moe={width:0,height:0,overflow:`visible`},Noe={width:0,overflowX:`visible`},Poe={height:0,overflowY:`visible`},Foe={},Ioe=e=>{var t=e.width,n=e.height,r=rE(t),i=rE(n);return r&&i?Moe:r?Noe:i?Poe:Foe};function Loe(e){var t=e.width,n=e.height,r=e.aspect,i=t,a=n;return i===void 0&&a===void 0?(i=xj.width,a=xj.height):i===void 0?i=r&&r>0?void 0:xj.width:a===void 0&&(a=r&&r>0?void 0:xj.height),{width:i,height:a}}var Roe=[`aspect`,`initialDimension`,`width`,`height`,`minWidth`,`minHeight`,`maxHeight`,`children`,`debounce`,`id`,`className`,`onResize`,`style`];function Cj(){return Cj=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Cj.apply(null,arguments)}function wj(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Tj(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?wj(Object(n),!0).forEach(function(t){zoe(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):wj(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function zoe(e,t,n){return(t=Boe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Boe(e){var t=Voe(e,`string`);return typeof t==`symbol`?t:t+``}function Voe(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Hoe(e,t){return Koe(e)||Goe(e,t)||Woe(e,t)||Uoe()}function Uoe(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
15
15
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Woe(e,t){if(e){if(typeof e==`string`)return Ej(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Ej(e,t):void 0}}function Ej(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Goe(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function Koe(e){if(Array.isArray(e))return e}function qoe(e,t){if(e==null)return{};var n,r,i=Joe(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Joe(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var Dj=(0,o.createContext)(xj.initialDimension);function Yoe(e){return qA(e.width)&&qA(e.height)}function Oj(e){var t=e.children,n=e.width,r=e.height,i=(0,o.useMemo)(()=>({width:n,height:r}),[n,r]);return Yoe(i)?o.createElement(Dj.Provider,{value:i},t):null}var kj=()=>(0,o.useContext)(Dj),Xoe=(0,o.forwardRef)((e,t)=>{var n=e.aspect,r=e.initialDimension,i=r===void 0?xj.initialDimension:r,a=e.width,s=e.height,c=e.minWidth,l=c===void 0?xj.minWidth:c,u=e.minHeight,d=e.maxHeight,f=e.children,p=e.debounce,m=p===void 0?xj.debounce:p,h=e.id,g=e.className,_=e.onResize,v=e.style,y=v===void 0?{}:v,b=qoe(e,Roe),x=(0,o.useRef)(null),S=(0,o.useRef)();S.current=_,(0,o.useImperativeHandle)(t,()=>x.current);var C=Hoe((0,o.useState)({containerWidth:i.width,containerHeight:i.height}),2),w=C[0],T=C[1],E=(0,o.useCallback)((e,t)=>{T(n=>{var r=Math.round(e),i=Math.round(t);return n.containerWidth===r&&n.containerHeight===i?n:{containerWidth:r,containerHeight:i}})},[]);(0,o.useEffect)(()=>{if(x.current==null||typeof ResizeObserver>`u`)return mE;var e=e=>{var t,n=e[0];if(n!=null){var r=n.contentRect,i=r.width,a=r.height;E(i,a),(t=S.current)==null||t.call(S,i,a)}};m>0&&(e=joe(e,m,{trailing:!0,leading:!1}));var t=new ResizeObserver(e),n=x.current.getBoundingClientRect(),r=n.width,i=n.height;return E(r,i),t.observe(x.current),()=>{t.disconnect()}},[E,m]);var D=w.containerWidth,O=w.containerHeight;bj(!n||n>0,`The aspect(%s) must be greater than zero.`,n);var k=Sj(D,O,{width:a,height:s,aspect:n,maxHeight:d}),A=k.calculatedWidth,j=k.calculatedHeight;return bj(D<0||O<0||A!=null&&A>0||j!=null&&j>0,`The width(%s) and height(%s) of chart should be greater than 0,
|
|
16
16
|
please check the style of container, or the props width(%s) and height(%s),
|
|
@@ -64,6 +64,6 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
64
64
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function M$(e,t){if(e){if(typeof e==`string`)return N$(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?N$(e,t):void 0}}function N$(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function P$(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function F$(e){if(Array.isArray(e))return e}function I$(e,t){if(e==null)return{};var n,r,i=L$(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function L$(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function R$(){return R$=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},R$.apply(null,arguments)}function z$(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function B$(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?z$(Object(n),!0).forEach(function(t){V$(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):z$(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function V$(e,t,n){return(t=H$(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function H$(e){var t=U$(e,`string`);return typeof t==`symbol`?t:t+``}function U$(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var W$={x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:`bottom`,ticks:[],stroke:`#666`,tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:`preserveEnd`,zIndex:sF.axis};function G$(e){var t=e.x,n=e.y,r=e.width,i=e.height,a=e.orientation,s=e.mirror,c=e.axisLine,l=e.otherSvgProps;if(!c)return null;var u=B$(B$(B$({},l),OT(c)),{},{fill:`none`});if(a===`top`||a===`bottom`){var d=+(a===`top`&&!s||a===`bottom`&&s);u=B$(B$({},u),{},{x1:t,y1:n+d*i,x2:t+r,y2:n+d*i})}else{var f=+(a===`left`&&!s||a===`right`&&s);u=B$(B$({},u),{},{x1:t+f*r,y1:n,x2:t+f*r,y2:n+i})}return o.createElement(`line`,R$({},u,{className:ST(`recharts-cartesian-axis-line`,XT(c,`className`))}))}function K$(e,t,n,r,i,a,o,s,c){var l,u,d,f,p,m,h=s?-1:1,g=e.tickSize||o,_=Y(e.tickCoord)?e.tickCoord:e.coordinate;switch(a){case`top`:l=u=e.coordinate,f=n+ +!s*i,d=f-h*g,m=d-h*c,p=_;break;case`left`:d=f=e.coordinate,u=t+ +!s*r,l=u-h*g,p=l-h*c,m=_;break;case`right`:d=f=e.coordinate,u=t+ +s*r,l=u+h*g,p=l+h*c,m=_;break;default:l=u=e.coordinate,f=n+ +s*i,d=f+h*g,m=d+h*c,p=_}return{line:{x1:l,y1:d,x2:u,y2:f},tick:{x:p,y:m}}}function q$(e,t){switch(e){case`left`:return t?`start`:`end`;case`right`:return t?`end`:`start`;default:return`middle`}}function J$(e,t){switch(e){case`left`:case`right`:return`middle`;case`top`:return t?`start`:`end`;default:return t?`end`:`start`}}function Y$(e){var t=e.option,n=e.tickProps,r=e.value,i,a=ST(n.className,`recharts-cartesian-axis-tick-value`);if(o.isValidElement(t))i=o.cloneElement(t,B$(B$({},n),{},{className:a}));else if(typeof t==`function`)i=t(B$(B$({},n),{},{className:a}));else{var s=`recharts-cartesian-axis-tick-value`;typeof t!=`boolean`&&(s=ST(s,AY(t))),i=o.createElement(jJ,R$({},n,{className:s}),r)}return i}function X$(e){var t=e.ticks,n=e.axisType,r=e.axisId,i=OO(),a=(0,o.useRef)(null);return(0,o.useEffect)(()=>{if(r!=null&&n!=null){var e=t.map(e=>({value:e.value,coordinate:e.coordinate,offset:e.offset,index:e.index})),o=a.current;o!=null&&o.axisId===r&&o.axisType===n&&o$(o.ticks,e)||(a.current={ticks:e,axisId:r,axisType:n},i(E$({ticks:e,axisId:r,axisType:n})))}},[i,t,r,n]),(0,o.useEffect)(()=>r==null||n==null?mE:()=>{i(D$({axisId:r,axisType:n}))},[i,r,n]),null}var Z$=(0,o.forwardRef)((e,t)=>{var n=e.ticks,r=n===void 0?[]:n,i=e.tick,a=e.tickLine,s=e.stroke,c=e.tickFormatter,l=e.unit,u=e.padding,d=e.tickTextProps,f=e.orientation,p=e.mirror,m=e.x,h=e.y,g=e.width,_=e.height,v=e.tickSize,y=e.tickMargin,b=e.fontSize,x=e.letterSpacing,S=e.getTicksConfig,C=e.events,w=e.axisType,T=e.axisId,E=x$(B$(B$({},S),{},{ticks:r}),b,x),D=OT(S),O=kT(i),k=bJ(D.textAnchor)?D.textAnchor:q$(f,p),A=J$(f,p),j={};typeof a==`object`&&(j=a);var M=B$(B$({},D),{},{fill:`none`},j),N=E.map(e=>B$({entry:e},K$(e,m,h,g,_,f,v,p,y))),ee=N.map(e=>{var t=e.entry,n=e.line;return o.createElement(VT,{className:`recharts-cartesian-axis-tick`,key:`tick-${t.value}-${t.coordinate}-${t.tickCoord}`},a&&o.createElement(`line`,R$({},M,n,{className:ST(`recharts-cartesian-axis-tick-line`,XT(a,`className`))})))}),P=N.map((e,t)=>{var n=e.entry,r=e.tick,a=B$(B$({},B$(B$(B$(B$({verticalAnchor:A},D),{},{textAnchor:k,stroke:`none`,fill:s},r),{},{index:t,payload:n,visibleTicksCount:E.length,tickFormatter:c,padding:u},d),{},{angle:d?.angle??D.angle??0})),O);return o.createElement(VT,R$({className:`recharts-cartesian-axis-tick-label`,key:`tick-label-${n.value}-${n.coordinate}-${n.tickCoord}`},DD(C,n,t)),i&&o.createElement(Y$,{option:i,tickProps:a,value:`${typeof c==`function`?c(n.value,t):n.value}${l||``}`}))});return o.createElement(`g`,{className:`recharts-cartesian-axis-ticks recharts-${w}-ticks`},o.createElement(X$,{ticks:E,axisId:T,axisType:w}),P.length>0&&o.createElement(vK,{zIndex:sF.label},o.createElement(`g`,{className:`recharts-cartesian-axis-tick-labels recharts-${w}-tick-labels`,ref:t},P)),ee.length>0&&o.createElement(`g`,{className:`recharts-cartesian-axis-tick-lines recharts-${w}-tick-lines`},ee))}),Q$=(0,o.forwardRef)((e,t)=>{var n=e.axisLine,r=e.width,i=e.height,a=e.className,s=e.hide,c=e.ticks,l=e.axisType,u=e.axisId,d=I$(e,k$),f=A$((0,o.useState)(``),2),p=f[0],m=f[1],h=A$((0,o.useState)(``),2),g=h[0],_=h[1],v=(0,o.useRef)(null);(0,o.useImperativeHandle)(t,()=>({getCalculatedWidth:()=>S$({ticks:v.current,label:e.labelRef?.current,labelGapWithTick:5,tickSize:e.tickSize,tickMargin:e.tickMargin}),getCalculatedHeight:()=>C$({ticks:v.current,label:e.labelRef?.current,labelGapWithTick:5,tickSize:e.tickSize,tickMargin:e.tickMargin})}));var y=(0,o.useCallback)(e=>{if(e){var t=e.getElementsByClassName(`recharts-cartesian-axis-tick-value`);v.current=t;var n=t[0];if(n){var r=window.getComputedStyle(n),i=r.fontSize,a=r.letterSpacing;(i!==p||a!==g)&&(m(i),_(a))}}},[p,g]);return s||r!=null&&r<=0||i!=null&&i<=0?null:o.createElement(vK,{zIndex:e.zIndex},o.createElement(VT,{className:ST(`recharts-cartesian-axis`,a)},o.createElement(G$,{x:e.x,y:e.y,width:r,height:i,orientation:e.orientation,mirror:e.mirror,axisLine:n,otherSvgProps:OT(e)}),o.createElement(Z$,{ref:y,axisType:l,events:d,fontSize:p,getTicksConfig:e,height:e.height,letterSpacing:g,mirror:e.mirror,orientation:e.orientation,padding:e.padding,stroke:e.stroke,tick:e.tick,tickFormatter:e.tickFormatter,tickLine:e.tickLine,tickMargin:e.tickMargin,tickSize:e.tickSize,tickTextProps:e.tickTextProps,ticks:c,unit:e.unit,width:e.width,x:e.x,y:e.y,axisId:u}),o.createElement(UJ,{x:e.x,y:e.y,width:e.width,height:e.height,lowerWidth:e.width,upperWidth:e.width},o.createElement(iY,{label:e.label,labelRef:e.labelRef}),e.children)))}),$$=o.forwardRef((e,t)=>{var n=ND(e,W$);return o.createElement(Q$,R$({},n,{ref:t}))});$$.displayName=`CartesianAxis`;var e1=(0,o.createContext)({grid:{stroke:`#ccc`,fill:`none`}});e1.Provider;var t1=()=>(0,o.useContext)(e1),n1=[`x1`,`y1`,`x2`,`y2`,`key`],r1=[`offset`],i1=[`xAxisId`,`yAxisId`],a1=[`xAxisId`,`yAxisId`];function o1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function s1(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?o1(Object(n),!0).forEach(function(t){c1(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):o1(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function c1(e,t,n){return(t=l1(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function l1(e){var t=u1(e,`string`);return typeof t==`symbol`?t:t+``}function u1(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function d1(){return d1=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d1.apply(null,arguments)}function f1(e,t){if(e==null)return{};var n,r,i=p1(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function p1(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var m1=e=>{var t=e.fill;if(!t||t===`none`)return null;var n=e.fillOpacity,r=e.x,i=e.y,a=e.width,s=e.height,c=e.ry;return o.createElement(`rect`,{x:r,y:i,ry:c,width:a,height:s,stroke:`none`,fill:t,fillOpacity:n,className:`recharts-cartesian-grid-bg`})};function h1(e){var t=e.option,n=e.lineItemProps,r;if(o.isValidElement(t))r=o.cloneElement(t,n);else if(typeof t==`function`)r=t(n);else{var i=n.x1,a=n.y1,s=n.x2,c=n.y2,l=n.key,u=OT(f1(n,n1))??{};u.offset;var d=f1(u,r1),f=Array.isArray(d.strokeDasharray)?d.strokeDasharray.join(`,`):d.strokeDasharray;r=o.createElement(`line`,d1({},d,{strokeDasharray:f,x1:i,y1:a,x2:s,y2:c,fill:`none`,key:l}))}return r}function g1(e){var t=e.x,n=e.width,r=e.horizontal,i=r===void 0||r,a=e.horizontalPoints;if(!i||!a||!a.length)return null;e.xAxisId,e.yAxisId;var s=f1(e,i1),c=a.map((e,r)=>{var a=s1(s1({},s),{},{x1:t,y1:e,x2:t+n,y2:e,key:`line-${r}`,index:r});return o.createElement(h1,{key:`line-${r}`,option:i,lineItemProps:a})});return o.createElement(`g`,{className:`recharts-cartesian-grid-horizontal`},c)}function _1(e){var t=e.y,n=e.height,r=e.vertical,i=r===void 0||r,a=e.verticalPoints;if(!i||!a||!a.length)return null;e.xAxisId,e.yAxisId;var s=f1(e,a1),c=a.map((e,r)=>{var a=s1(s1({},s),{},{x1:e,y1:t,x2:e,y2:t+n,key:`line-${r}`,index:r});return o.createElement(h1,{option:i,lineItemProps:a,key:`line-${r}`})});return o.createElement(`g`,{className:`recharts-cartesian-grid-vertical`},c)}function v1(e){var t=e.horizontalFill,n=e.fillOpacity,r=e.x,i=e.y,a=e.width,s=e.height,c=e.horizontalPoints,l=e.horizontal;if(!(l===void 0||l)||!t||!t.length||c==null)return null;var u=c.map(e=>Math.round(e+i-i)).sort((e,t)=>e-t);i!==u[0]&&u.unshift(0);var d=u.map((e,c)=>{var l=u[c+1],d=l==null?i+s-e:l-e;if(d<=0)return null;var f=c%t.length;return o.createElement(`rect`,{key:`react-${c}`,y:e,x:r,height:d,width:a,stroke:`none`,fill:t[f],fillOpacity:n,className:`recharts-cartesian-grid-bg`})});return o.createElement(`g`,{className:`recharts-cartesian-gridstripes-horizontal`},d)}function y1(e){var t=e.vertical,n=t===void 0||t,r=e.verticalFill,i=e.fillOpacity,a=e.x,s=e.y,c=e.width,l=e.height,u=e.verticalPoints;if(!n||!r||!r.length)return null;var d=u.map(e=>Math.round(e+a-a)).sort((e,t)=>e-t);a!==d[0]&&d.unshift(0);var f=d.map((e,t)=>{var n=d[t+1],u=n==null?a+c-e:n-e;if(u<=0)return null;var f=t%r.length;return o.createElement(`rect`,{key:`react-${t}`,x:e,y:s,width:u,height:l,stroke:`none`,fill:r[f],fillOpacity:i,className:`recharts-cartesian-grid-bg`})});return o.createElement(`g`,{className:`recharts-cartesian-gridstripes-vertical`},f)}var b1=(e,t)=>{var n=e.xAxis,r=e.width,i=e.height,a=e.offset;return QA(x$(s1(s1(s1({},W$),n),{},{ticks:$A(n,!0),viewBox:{x:0,y:0,width:r,height:i}})),a.left,a.left+a.width,t)},x1=(e,t)=>{var n=e.yAxis,r=e.width,i=e.height,a=e.offset;return QA(x$(s1(s1(s1({},W$),n),{},{ticks:$A(n,!0),viewBox:{x:0,y:0,width:r,height:i}})),a.top,a.top+a.height,t)},S1={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],verticalFill:[],horizontalFill:[],xAxisId:0,yAxisId:0,syncWithTicks:!1,zIndex:sF.grid};function C1(e){var t=Nj(),n=Pj(),r=Mj(),i=s1(s1({},ND(e,S1)),{},{x:Y(e.x)?e.x:r.left,y:Y(e.y)?e.y:r.top,width:Y(e.width)?e.width:r.width,height:Y(e.height)?e.height:r.height}),a=i.xAxisId,s=i.yAxisId,c=i.x,l=i.y,u=i.width,d=i.height,f=i.syncWithTicks,p=i.horizontalValues,m=i.verticalValues,h=_j(),g=X(e=>HU(e,`xAxis`,a,h)),_=X(e=>HU(e,`yAxis`,s,h)),v=t1(),y={stroke:i.stroke??v.grid.stroke,strokeWidth:i.strokeWidth??v.grid.strokeWidth,strokeOpacity:i.strokeOpacity??v.grid.strokeOpacity,strokeDasharray:i.strokeDasharray??v.grid.strokeDasharray};if(!qA(u)||!qA(d)||!Y(c)||!Y(l))return null;var b=i.verticalCoordinatesGenerator||b1,x=i.horizontalCoordinatesGenerator||x1,S=i.horizontalPoints,C=i.verticalPoints;if((!S||!S.length)&&typeof x==`function`){var w=p&&p.length,T=x({yAxis:_?s1(s1({},_),{},{ticks:w?p:_.ticks}):void 0,width:t??u,height:n??d,offset:r},w?!0:f);bj(Array.isArray(T),`horizontalCoordinatesGenerator should return Array but instead it returned [${typeof T}]`),Array.isArray(T)&&(S=T)}if((!C||!C.length)&&typeof b==`function`){var E=m&&m.length,D=b({xAxis:g?s1(s1({},g),{},{ticks:E?m:g.ticks}):void 0,width:t??u,height:n??d,offset:r},E?!0:f);bj(Array.isArray(D),`verticalCoordinatesGenerator should return Array but instead it returned [${typeof D}]`),Array.isArray(D)&&(C=D)}return o.createElement(vK,{zIndex:i.zIndex},o.createElement(`g`,{className:`recharts-cartesian-grid`},o.createElement(m1,{fill:i.fill??v.grid.fill,fillOpacity:i.fillOpacity??v.grid.fillOpacity,x:i.x,y:i.y,width:i.width,height:i.height,ry:i.ry}),o.createElement(v1,d1({},i,{horizontalPoints:S})),o.createElement(y1,d1({},i,{verticalPoints:C})),o.createElement(g1,d1({},i,y,{offset:r,horizontalPoints:S,xAxis:g,yAxis:_})),o.createElement(_1,d1({},i,y,{offset:r,verticalPoints:C,xAxis:g,yAxis:_}))))}C1.displayName=`CartesianGrid`;var w1=[`animationElapsedTime`,`isAnimating`,`isEntrance`,`visibleLength`,`strokeDasharray`,`connectNulls`];function T1(){return T1=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},T1.apply(null,arguments)}function E1(e,t){if(e==null)return{};var n,r,i=D1(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function D1(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function O1(e){try{return e&&e.getTotalLength&&e.getTotalLength()||0}catch{return 0}}function k1(e,t){return`${t}px ${e}px`}function A1(e){return e.length%2==0?e:[...e,...e]}function j1(e,t){for(var n=[],r=0;r<t;++r)n.push(...e);return n}function M1(e,t,n){var r=A1(n),i=r.reduce((e,t)=>e+t,0);if(!i)return k1(t,e);for(var a=Math.floor(e/i),o=e%i,s=[],c=0,l=0;c<r.length;l+=(u=r[c])??0,++c){var u,d=r[c];if(d!=null&&l+d>o){s=[...r.slice(0,c),o-l];break}}var f=s.length%2==0?[0,t]:[t];return[...j1(r,a),...s,...f].map(e=>`${e}px`).join(`, `)}function N1(e,t,n){return e?M1(n,t,`${e}`.split(/[,\s]+/gim).map(e=>parseFloat(e))):k1(t,n)}function P1(e){e.animationElapsedTime,e.isAnimating,e.isEntrance;var t=e.visibleLength,n=e.strokeDasharray,r=e.connectNulls,i=E1(e,w1),a=r??!1,s;if(t!=null){var c=i.pathRef;s=N1(n,O1(c?.current??null),t)}else n!=null&&(s=String(n));return o.createElement(_M,T1({},i,{connectNulls:a,strokeDasharray:s}))}function F1(e){var t=(0,o.useRef)(0),n=(0,o.useRef)(0),r=(0,o.useRef)(!1),i=(0,o.useRef)(e);return i.current!==e&&(t.current=n.current,i.current=e),(0,o.useCallback)((e,i)=>{if(r.current)return null;var a=Math.min($T(t.current+e*i),i);return e>0&&i>0&&(n.current=Math.max(n.current,a),a>=i)?(r.current=!0,null):a},[])}var I1=_A({name:`errorBars`,initialState:{},reducers:{addErrorBar:(e,t)=>{var n=t.payload,r=n.itemId,i=n.errorBar;e[r]||(e[r]=[]),e[r].push(i)},replaceErrorBar:(e,t)=>{var n=t.payload,r=n.itemId,i=n.prev,a=n.next;e[r]&&(e[r]=e[r].map(e=>e.dataKey===i.dataKey&&e.direction===i.direction?a:e))},removeErrorBar:(e,t)=>{var n=t.payload,r=n.itemId,i=n.errorBar;e[r]&&(e[r]=e[r].filter(e=>e.dataKey!==i.dataKey||e.direction!==i.direction))}}}),L1=I1.actions;L1.addErrorBar,L1.replaceErrorBar,L1.removeErrorBar;var R1=I1.reducer,z1=[`children`];function B1(e,t){if(e==null)return{};var n,r,i=V1(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function V1(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var H1=(0,o.createContext)({data:[],xAxisId:`xAxis-0`,yAxisId:`yAxis-0`,dataPointFormatter:()=>({x:0,y:0,value:0}),errorBarOffset:0});function U1(e){var t=e.children,n=B1(e,z1);return o.createElement(H1.Provider,{value:n},t)}function W1(e,t){var n=X(t=>UV(t,e)),r=X(e=>KV(e,t)),i=n?.allowDataOverflow??VV.allowDataOverflow,a=r?.allowDataOverflow??WV.allowDataOverflow;return{needClip:i||a,needClipX:i,needClipY:a}}function G1(e){var t=e.xAxisId,n=e.yAxisId,r=e.clipPathId,i=dQ(),a=W1(t,n),s=a.needClipX,c=a.needClipY,l=a.needClip,u=X(e=>gU(e,t,!1)),d=X(e=>_U(e,n,!1));if(!l||!i)return null;var f=i.x,p=i.y,m=i.width,h=i.height,g=s&&u?Math.min(u[0],u[1]):f-m/2,_=c&&d?Math.min(d[0],d[1]):p-h/2,v=s&&u?Math.abs(u[1]-u[0]):m*2,y=c&&d?Math.abs(d[1]-d[0]):h*2;return o.createElement(`clipPath`,{id:`clipPath-${r}`},o.createElement(`rect`,{x:g,y:_,width:v,height:y}))}var K1=(e,t,n,r)=>GU(e,`xAxis`,t,r),q1=(e,t,n,r)=>WU(e,`xAxis`,t,r),J1=(e,t,n,r)=>GU(e,`yAxis`,n,r),Y1=(e,t,n,r)=>WU(e,`yAxis`,n,r),X1=Z([Fj,K1,J1,q1,Y1],(e,t,n,r,i)=>ZA(e,`xAxis`)?ij(t,r,!1):ij(n,i,!1)),Z1=(e,t,n,r,i)=>i;function Q1(e){return e.type===`line`}var $1=Z([Fj,K1,J1,q1,Y1,Z([eH,Z1],(e,t)=>e.filter(Q1).find(e=>e.id===t)),X1,xP],(e,t,n,r,i,a,o,s)=>{var c=s.chartData,l=s.dataStartIndex,u=s.dataEndIndex;if(!(a==null||t==null||n==null||r==null||i==null||r.length===0||i.length===0||o==null||e!==`horizontal`&&e!==`vertical`)){var d=a.dataKey,f=a.data,p=f!=null&&f.length>0?f:c?.slice(l,u+1);if(p!=null)return T0({layout:e,xAxis:t,yAxis:n,xAxisTicks:r,yAxisTicks:i,dataKey:d,bandSize:o,displayedData:p})}});function e0(e){var t=kT(e),n=3,r=2;if(t!=null){var i=t.r,a=t.strokeWidth,o=Number(i),s=Number(a);return(Number.isNaN(o)||o<0)&&(o=n),(Number.isNaN(s)||s<0)&&(s=r),{r:o,strokeWidth:s}}return{r:n,strokeWidth:r}}var t0=[`id`],n0=[`type`,`layout`,`connectNulls`,`needClip`,`shape`,`strokeDasharray`],r0=[`activeDot`,`animateNewValues`,`animationBegin`,`animationDuration`,`animationEasing`,`connectNulls`,`dot`,`hide`,`isAnimationActive`,`label`,`legendType`,`xAxisId`,`yAxisId`,`id`];function i0(){return i0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},i0.apply(null,arguments)}function a0(e,t){if(e==null)return{};var n,r,i=o0(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function o0(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function s0(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function c0(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?s0(Object(n),!0).forEach(function(t){l0(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):s0(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function l0(e,t,n){return(t=u0(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u0(e){var t=d0(e,`string`);return typeof t==`symbol`?t:t+``}function d0(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function f0(e){try{return e&&e.getTotalLength&&e.getTotalLength()||0}catch{return 0}}function p0(e){var t=0,n=0;for(var r of e)r.status===`matched`&&r.prev.x!=null&&r.next.x!=null&&(t+=r.next.x-r.prev.x,n++);return n>0?t/n:0}var m0={activeDot:!0,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:`ease`,animationInterpolateFn:(e,t)=>{if(e==null)return[];if(t===1)return e.flatMap(e=>e.status===`removed`?[]:[e.next]);var n=p0(e),r=[];for(var i of e)if(i.status===`matched`)r.push(c0(c0({},i.next),{},{x:lE(i.prev.x,i.next.x,t),y:lE(i.prev.y,i.next.y,t)}));else if(i.status===`added`){if(i.next.x!=null){var a=i.next.x-n;r.push(c0(c0({},i.next),{},{x:lE(a,i.next.x,t),y:i.next.y}))}else r.push(i.next)}else if(i.status===`removed`&&i.prev.x!=null){var o=i.prev.x+n;r.push(c0(c0({},i.prev),{},{x:lE(i.prev.x,o,t),y:i.prev.y}))}return r},animationMatchBy:yX,connectNulls:!1,dot:!0,fill:`#fff`,hide:!1,isAnimationActive:`auto`,label:!1,legendType:`line`,shape:P1,stroke:`#3182bd`,strokeWidth:1,xAxisId:0,yAxisId:0,zIndex:sF.line,type:`linear`},h0=e=>{var t=e.dataKey,n=e.name,r=e.stroke,i=e.legendType;return[{inactive:e.hide,dataKey:t,type:i,color:r,value:oj(n,t),payload:e}]},g0=o.memo(e=>{var t=e.dataKey,n=e.data,r=e.stroke,i=e.strokeWidth,a=e.fill,s=e.name,c=e.hide,l=e.unit,u=e.formatter,d=e.tooltipType,f=e.id,p={dataDefinedOnItem:n,getPosition:mE,settings:{stroke:r,strokeWidth:i,fill:a,dataKey:t,nameKey:void 0,name:oj(s,t),hide:c,type:d,color:r,unit:l,formatter:u,graphicalItemId:f}};return o.createElement(uX,{tooltipEntrySettings:p})});function _0(e){var t=e.clipPathId,n=e.points,r=e.props,i=r.dot,a=r.dataKey,s=r.needClip;r.id;var c=OT(a0(r,t0));return o.createElement(qZ,{points:n,dot:i,className:`recharts-line-dots`,dotClassName:`recharts-line-dot`,dataKey:a,baseProps:c,needClip:s,clipPathId:t})}function v0(e){var t=e.showLabels,n=e.children,r=e.points,i=(0,o.useMemo)(()=>r?.map(e=>{var t={x:e.x??0,y:e.y??0,width:0,lowerWidth:0,upperWidth:0,height:0};return c0(c0({},t),{},{value:e.value,payload:e.payload,viewBox:t,parentViewBox:void 0,fill:void 0})}),[r]);return o.createElement(fY,{value:t?i:void 0},n)}function y0(e){var t=e.clipPathId,n=e.pathRef,r=e.points,i=e.props,a=e.animationElapsedTime,s=e.isAnimating,c=e.isEntrance,l=e.visibleLength,u=i.type,d=i.layout,f=i.connectNulls,p=i.needClip,m=i.shape,h=i.strokeDasharray,g=c0(c0({},AT(a0(i,n0))),{},{fill:`none`,className:`recharts-line-curve`,clipPath:p?`url(#clipPath-${t})`:void 0,points:r,type:u,layout:d,connectNulls:f,strokeDasharray:h??i.strokeDasharray,pathRef:n,animationElapsedTime:a,isAnimating:s,isEntrance:i.animateNewValues?c:!1,visibleLength:l});return o.createElement(o.Fragment,null,r?.length>1&&o.createElement(oX,{option:m,DefaultShape:m0.shape,shapeProps:g}),o.createElement(_0,{points:r,clipPathId:t,props:i}))}function b0(e){var t=e.clipPathId,n=e.props,r=e.pathRef,i=e.previousPointsRef,a=n.points,s=n.isAnimationActive,c=n.animationBegin,l=n.animationDuration,u=n.animationEasing,d=n.animationMatchBy,f=n.animationInterpolateFn,p=n.layout,m=f0(r.current),h=PX(n.onAnimationStart,n.onAnimationEnd),g=h.isAnimating,_=h.handleAnimationStart,v=h.handleAnimationEnd,y=!g,b=F1(a),x=(0,o.useCallback)(e=>e>0&&m>0,[m]);return o.createElement(v0,{points:a,showLabels:y},n.children,o.createElement(FX,{animationInput:a,animationIdPrefix:`recharts-line-`,items:a,previousItemsRef:i,isAnimationActive:s,animationBegin:c,animationDuration:l,animationEasing:u,onAnimationStart:_,onAnimationEnd:v,animationInterpolateFn:f,animationMatchBy:d,shouldUpdatePreviousRef:x,layout:p},(e,i,a)=>{var s=g||i<1,c=s?b(i,m):null;return o.createElement(y0,{props:n,points:e,clipPathId:t,pathRef:r,animationElapsedTime:i,isAnimating:s,isEntrance:a,visibleLength:c})}),o.createElement(vY,{label:n.label}))}function x0(e){var t=e.clipPathId,n=e.props,r=(0,o.useRef)(null),i=(0,o.useRef)(null);return o.createElement(b0,{props:n,clipPathId:t,previousPointsRef:r,pathRef:i})}var S0=(e,t)=>({x:e.x??void 0,y:e.y??void 0,value:e.value,errorVal:XA(e.payload,t)}),C0=class extends o.Component{render(){var e=this.props,t=e.hide,n=e.dot,r=e.points,i=e.className,a=e.xAxisId,s=e.yAxisId,c=e.top,l=e.left,u=e.width,d=e.height,f=e.id,p=e.needClip,m=e.zIndex;if(t)return null;var h=ST(`recharts-line`,i),g=f,_=e0(n),v=_.r,y=_.strokeWidth,b=YY(n),x=v*2+y,S=p?`url(#clipPath-${b?``:`dots-`}${g})`:void 0;return o.createElement(vK,{zIndex:m},o.createElement(VT,{className:h},p&&o.createElement(`defs`,null,o.createElement(G1,{clipPathId:g,xAxisId:a,yAxisId:s}),!b&&o.createElement(`clipPath`,{id:`clipPath-dots-${g}`},o.createElement(`rect`,{x:l-x/2,y:c-x/2,width:u+x,height:d+x}))),o.createElement(U1,{xAxisId:a,yAxisId:s,data:r,dataPointFormatter:S0,errorBarOffset:0},o.createElement(x0,{props:this.props,clipPathId:g}))),o.createElement(yQ,{activeDot:this.props.activeDot,points:r,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:S}))}};function w0(e){var t=ND(e,m0),n=t.activeDot,r=t.animateNewValues,i=t.animationBegin,a=t.animationDuration,s=t.animationEasing,c=t.connectNulls,l=t.dot,u=t.hide,d=t.isAnimationActive,f=t.label,p=t.legendType,m=t.xAxisId,h=t.yAxisId,g=t.id,_=a0(t,r0),v=W1(m,h).needClip,y=dQ(),b=Ij(),x=_j(),S=X(e=>$1(e,m,h,x,g));if(b!==`horizontal`&&b!==`vertical`||S==null||y==null)return null;var C=y.height,w=y.width,T=y.x,E=y.y;return o.createElement(C0,i0({},_,{id:g,connectNulls:c,dot:l,activeDot:n,animateNewValues:r,animationBegin:i,animationDuration:a,animationEasing:s,isAnimationActive:d,hide:u,label:f,legendType:p,xAxisId:m,yAxisId:h,points:S,layout:b,height:C,width:w,left:T,top:E,needClip:v}))}function T0(e){var t=e.layout,n=e.xAxis,r=e.yAxis,i=e.xAxisTicks,a=e.yAxisTicks,o=e.dataKey,s=e.bandSize;return e.displayedData.map((e,c)=>{var l=XA(e,o);if(t===`horizontal`)return{x:ej({axis:n,ticks:i,bandSize:s,entry:e,index:c}),y:(dE(l)?null:r.scale.map(l))??null,value:l,payload:e};var u=dE(l)?null:n.scale.map(l),d=ej({axis:r,ticks:a,bandSize:s,entry:e,index:c});return u==null||d==null?null:{x:u,y:d,value:l,payload:e}}).filter(Boolean)}function E0(e){var t=ND(e,m0),n=_j();return o.createElement(GX,{id:t.id,type:`line`},e=>o.createElement(o.Fragment,null,o.createElement(dX,{legendPayload:h0(t)}),o.createElement(g0,{dataKey:t.dataKey,data:t.data,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,unit:t.unit,formatter:t.formatter,tooltipType:t.tooltipType,id:e}),o.createElement(tZ,{type:`line`,id:e,data:t.data,xAxisId:t.xAxisId,yAxisId:t.yAxisId,zAxisId:0,dataKey:t.dataKey,hide:t.hide,isPanorama:n}),o.createElement(w0,i0({},t,{id:e}))))}var D0=o.memo(E0,qj);D0.displayName=`Line`;function O0(e,t){return e.graphicalItems.cartesianItems.find(e=>e.id===t)?.xAxisId??0}function k0(e,t){return e.graphicalItems.cartesianItems.find(e=>e.id===t)?.yAxisId??0}var A0=`Invariant failed`;function j0(e,t){if(!e)throw Error(A0)}var M0=[`option`];function N0(e,t){if(e==null)return{};var n,r,i=P0(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function P0(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var F0=RN;function I0(e){var t=e.option,n=N0(e,M0);return o.createElement(oX,{option:t,DefaultShape:F0,shapeProps:n,activeClassName:`recharts-active-bar`,inActiveClassName:`recharts-inactive-bar`})}var L0=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return(n,r)=>{if(Y(e))return e;var i=Y(n)||dE(n);return i?e(n,r):(!i&&j0(!1,`minPointSize callback function received a value with type of ${typeof n}. Currently only numbers or null/undefined are supported.`),t)}},R0=(e,t,n)=>n,z0=Z([eH,(e,t)=>t],(e,t)=>e.filter(e=>e.type===`bar`).find(e=>e.id===t)),B0=Z([z0],e=>e?.maxBarSize),V0=(e,t,n,r)=>r,H0=Z([Fj,eH,O0,k0,R0],(e,t,n,r,i)=>t.filter(t=>e===`horizontal`?t.xAxisId===n:t.yAxisId===r).filter(e=>e.isPanorama===i).filter(e=>e.hide===!1).filter(e=>e.type===`bar`)),U0=(e,t,n)=>{var r=Fj(e),i=O0(e,t),a=k0(e,t);if(i!=null&&a!=null)return r===`horizontal`?EH(e,`yAxis`,a,n):EH(e,`xAxis`,i,n)},W0=Z([H0,eF,(e,t)=>{var n=Fj(e),r=O0(e,t),i=k0(e,t);if(r!=null&&i!=null)return n===`horizontal`?zU(e,`xAxis`,r):zU(e,`yAxis`,i)}],DQ),G0=(e,t,n)=>{var r=z0(e,t);if(r==null)return 0;var i=O0(e,t),a=k0(e,t);if(i==null||a==null)return 0;var o=Fj(e),s=ZP(e),c=r.maxBarSize,l=dE(c)?s:c,u,d;return o===`horizontal`?(u=GU(e,`xAxis`,i,n),d=WU(e,`xAxis`,i,n)):(u=GU(e,`yAxis`,a,n),d=WU(e,`yAxis`,a,n)),ij(u,d,!0)??l??0},K0=(e,t,n)=>{var r=Fj(e),i=O0(e,t),a=k0(e,t);if(i!=null&&a!=null){var o,s;return r===`horizontal`?(o=GU(e,`xAxis`,i,n),s=WU(e,`xAxis`,i,n)):(o=GU(e,`yAxis`,a,n),s=WU(e,`yAxis`,a,n)),ij(o,s)}},q0=Z([hj,gj,(e,t,n)=>{var r=O0(e,t);if(r!=null)return GU(e,`xAxis`,r,n)},(e,t,n)=>{var r=k0(e,t);if(r!=null)return GU(e,`yAxis`,r,n)},(e,t,n)=>{var r=O0(e,t);if(r!=null)return WU(e,`xAxis`,r,n)},(e,t,n)=>{var r=k0(e,t);if(r!=null)return WU(e,`yAxis`,r,n)},Z([Z([W0,ZP,QP,$P,G0,K0,B0],PQ),z0],IQ),Fj,SP,K0,Z([U0,z0],FQ),z0,V0],(e,t,n,r,i,a,o,s,c,l,u,d,f)=>{var p=c.chartData,m=c.dataStartIndex,h=c.dataEndIndex;if(!(d==null||o==null||t==null||s!==`horizontal`&&s!==`vertical`||n==null||r==null||i==null||a==null||l==null)){var g=d.data,_=g!=null&&g.length>0?g:p?.slice(m,h+1);if(_!=null)return jce({layout:s,barSettings:d,pos:o,parentViewBox:t,bandSize:l,xAxis:n,yAxis:r,xAxisTicks:i,yAxisTicks:a,stackedData:u,displayedData:_,offset:e,cells:f,dataStartIndex:m})}}),J0=[`index`];function Y0(){return Y0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Y0.apply(null,arguments)}function X0(e,t){if(e==null)return{};var n,r,i=Z0(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Z0(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var Q0=(0,o.createContext)(void 0),nce=e=>{var t=(0,o.useContext)(Q0);if(t!=null)return t.stackId;if(e!=null)return uoe(e)},rce=(e,t)=>`recharts-bar-stack-clip-path-${e}-${t}`,ice=e=>{var t=(0,o.useContext)(Q0);if(t!=null){var n=t.stackId;return`url(#${rce(n,e)})`}},$0=e=>{var t=e.index,n=X0(e,J0),r=ice(t);return o.createElement(VT,Y0({className:`recharts-bar-stack-layer`,clipPath:r},n))},ace=[`onMouseEnter`,`onMouseLeave`,`onClick`],oce=[`value`,`background`,`tooltipPosition`],sce=[`id`],cce=[`onMouseEnter`,`onClick`,`onMouseLeave`];function e2(e,t){return fce(e)||dce(e,t)||uce(e,t)||lce()}function lce(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
65
65
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function uce(e,t){if(e){if(typeof e==`string`)return t2(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?t2(e,t):void 0}}function t2(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function dce(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function fce(e){if(Array.isArray(e))return e}function n2(){return n2=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},n2.apply(null,arguments)}function r2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function i2(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?r2(Object(n),!0).forEach(function(t){pce(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r2(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function pce(e,t,n){return(t=mce(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function mce(e){var t=hce(e,`string`);return typeof t==`symbol`?t:t+``}function hce(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function a2(e,t){if(e==null)return{};var n,r,i=gce(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function gce(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var _ce=e=>{var t=e.dataKey,n=e.name,r=e.fill,i=e.legendType;return[{inactive:e.hide,dataKey:t,type:i,color:r,value:oj(n,t),payload:e}]},vce=o.memo(e=>{var t=e.dataKey,n=e.stroke,r=e.strokeWidth,i=e.fill,a=e.name,s=e.hide,c=e.unit,l=e.formatter,u=e.tooltipType,d=e.id,f={dataDefinedOnItem:void 0,getPosition:mE,settings:{stroke:n,strokeWidth:r,fill:i,dataKey:t,nameKey:void 0,name:oj(a,t),hide:s,type:u,color:i,unit:c,formatter:l,graphicalItemId:d}};return o.createElement(uX,{tooltipEntrySettings:f})});function yce(e){var t=X(mG),n=e.data,r=e.dataKey,i=e.background,a=e.allOtherBarProps,s=a.onMouseEnter,c=a.onMouseLeave,l=a.onClick,u=a2(a,ace),d=sX(s,r,a.id),f=cX(c),p=lX(l,r,a.id);if(!i||n==null)return null;var m=kT(i);return o.createElement(vK,{zIndex:LQ(i,sF.barBackground)},n.map((e,n)=>{e.value;var a=e.background;e.tooltipPosition;var s=a2(e,oce);if(!a)return null;var c=d(e,e.originalDataIndex),l=f(e,e.originalDataIndex),h=p(e,e.originalDataIndex),g=i2(i2(i2(i2(i2({option:i,isActive:String(e.originalDataIndex)===t},s),{},{fill:`#eee`},a),m),DD(u,e,n)),{},{onMouseEnter:c,onMouseLeave:l,onClick:h,dataKey:r,index:n,className:`recharts-bar-background-rectangle`});return o.createElement(I0,n2({key:`background-bar-${n}`},g))}))}function bce(e){var t=e.showLabels,n=e.children,r=e.rects?.map(e=>{var t={x:e.x,y:e.y,width:e.width,lowerWidth:e.width,upperWidth:e.width,height:e.height};return i2(i2({},t),{},{value:e.value,payload:e.payload,parentViewBox:e.parentViewBox,viewBox:t,fill:e.fill})});return o.createElement(fY,{value:t?r:void 0},n)}function xce(e){var t=e.shape,n=e.activeBar,r=e.baseProps,i=e.entry,a=e.index,s=e.dataKey,c=X(mG),l=X(gG),u=n&&String(i.originalDataIndex)===c&&(l==null||s===l),d=c!=null&&(String(i.originalDataIndex)!==c||l!=null&&s!==l),f=e2((0,o.useState)(!1),2),p=f[0],m=f[1],h=e2((0,o.useState)(!1),2),g=h[0],_=h[1];(0,o.useEffect)(()=>{var e;return u?(m(!0),e=requestAnimationFrame(()=>{_(!0)})):(_(!1),d&&m(!1)),()=>{cancelAnimationFrame(e)}},[u,d]);var v=(0,o.useCallback)(()=>{u||m(!1)},[u]),y=u&&g,b=u||p,x=u?n===!0?t:n:t,S=o.createElement(I0,n2({},r,{name:String(r.name)},i,{isActive:y,option:x,index:a,dataKey:s,animationElapsedTime:e.animationElapsedTime,isAnimating:e.isAnimating,isEntrance:e.isEntrance,onTransitionEnd:v}));return b?o.createElement(vK,{zIndex:sF.activeBar},o.createElement($0,{index:i.originalDataIndex},S)):S}function Sce(e){var t=e.shape,n=e.baseProps,r=e.entry,i=e.index,a=e.dataKey;return o.createElement(I0,n2({},n,{name:String(n.name)},r,{isActive:!1,option:t,index:i,dataKey:a,animationElapsedTime:e.animationElapsedTime,isAnimating:e.isAnimating,isEntrance:e.isEntrance}))}function Cce(e){var t=e.data,n=e.props,r=e.animationElapsedTime,i=e.isAnimating,a=e.isEntrance,s=OT(n)??{},c=s.id,l=a2(s,sce),u=n.shape,d=n.dataKey,f=n.activeBar,p=n.onMouseEnter,m=n.onClick,h=n.onMouseLeave,g=a2(n,cce),_=sX(p,d,c),v=cX(h),y=lX(m,d,c);return t?o.createElement(o.Fragment,null,t.map((e,t)=>o.createElement($0,n2({index:e.originalDataIndex,key:`rectangle-${e?.x}-${e?.y}-${e?.value}-${t}`,className:`recharts-bar-rectangle`},DD(g,e,t),{onMouseEnter:_(e,e.originalDataIndex),onMouseLeave:v(e,e.originalDataIndex),onClick:y(e,e.originalDataIndex)}),f?o.createElement(xce,{shape:u,activeBar:f,baseProps:l,entry:e,index:t,dataKey:d,animationElapsedTime:r,isAnimating:i,isEntrance:a}):o.createElement(Sce,{shape:u,baseProps:l,entry:e,index:t,dataKey:d,animationElapsedTime:r,isAnimating:i,isEntrance:a})))):null}var wce=(e,t,n)=>e==null?[]:t===1?e.flatMap(e=>e.status===`removed`?[]:[e.next]):e.flatMap(e=>{if(e.status===`removed`)return n===`horizontal`?[i2(i2({},e.prev),{},{height:lE(e.prev.height,0,t),y:lE(e.prev.y,e.prev.y+e.prev.height,t)})]:[i2(i2({},e.prev),{},{width:lE(e.prev.width,0,t)})];if(e.status===`matched`)return[i2(i2({},e.next),{},{x:lE(e.prev.x,e.next.x,t),y:lE(e.prev.y,e.next.y,t),width:lE(e.prev.width,e.next.width,t),height:lE(e.prev.height,e.next.height,t)})];var r=e.next;return n===`horizontal`?[i2(i2({},r),{},{height:lE(0,r.height,t),y:lE(r.stackedBarStart,r.y,t)})]:[i2(i2({},r),{},{width:lE(0,r.width,t),x:lE(r.stackedBarStart,r.x,t)})]});function Tce(e){var t=e.props,n=e.previousRectanglesRef,r=t.data,i=t.isAnimationActive,a=t.animationBegin,s=t.animationDuration,c=t.animationEasing,l=t.animationInterpolateFn,u=t.layout,d=PX(t.onAnimationStart,t.onAnimationEnd),f=d.isAnimating,p=d.handleAnimationStart,m=d.handleAnimationEnd;return o.createElement(bce,{showLabels:!f,rects:r},o.createElement(FX,{animationInput:r,animationIdPrefix:`recharts-bar-`,items:r,previousItemsRef:n,isAnimationActive:i,animationBegin:a,animationDuration:s,animationEasing:c,onAnimationStart:p,onAnimationEnd:m,animationInterpolateFn:l,animationMatchBy:t.animationMatchBy,layout:u},(e,n,r)=>o.createElement(VT,null,o.createElement(Cce,{props:t,data:e,animationElapsedTime:n,isAnimating:f||n<1,isEntrance:r}))),o.createElement(vY,{label:t.label}),t.children)}function Ece(e){var t=(0,o.useRef)(null);return o.createElement(Tce,{previousRectanglesRef:t,props:e})}var o2=0,Dce=(e,t)=>{var n=Array.isArray(e.value)?e.value[1]:e.value;return{x:e.x,y:e.y,value:n,errorVal:XA(e,t)}},Oce=class extends o.PureComponent{render(){var e=this.props,t=e.hide,n=e.data,r=e.dataKey,i=e.className,a=e.xAxisId,s=e.yAxisId,c=e.needClip,l=e.background,u=e.id;if(t||n==null)return null;var d=ST(`recharts-bar`,i),f=u;return o.createElement(VT,{className:d,id:u},c&&o.createElement(`defs`,null,o.createElement(G1,{clipPathId:f,xAxisId:a,yAxisId:s})),o.createElement(VT,{className:`recharts-bar-rectangles`,clipPath:c?`url(#clipPath-${f})`:void 0},o.createElement(yce,{data:n,dataKey:r,background:l,allOtherBarProps:this.props}),o.createElement(Ece,this.props)))}},kce={activeBar:!1,animationBegin:0,animationDuration:400,animationEasing:`ease`,animationInterpolateFn:wce,animationMatchBy:bX,background:!1,hide:!1,isAnimationActive:`auto`,label:!1,legendType:`rect`,minPointSize:o2,shape:F0,xAxisId:0,yAxisId:0,zIndex:sF.bar};function Ace(e){var t=e.xAxisId,n=e.yAxisId,r=e.hide,i=e.legendType,a=e.minPointSize,s=e.activeBar,c=e.animationBegin,l=e.animationDuration,u=e.animationEasing,d=e.isAnimationActive,f=W1(t,n).needClip,p=Ij(),m=_j(),h=JY(e.children,vq),g=X(t=>q0(t,e.id,m,h));if(p!==`vertical`&&p!==`horizontal`)return null;var _,v=g?.[0];return _=v==null||v.height==null||v.width==null?0:p===`vertical`?v.height/2:v.width/2,o.createElement(U1,{xAxisId:t,yAxisId:n,data:g,dataPointFormatter:Dce,errorBarOffset:_},o.createElement(Oce,n2({},e,{layout:p,needClip:f,data:g,xAxisId:t,yAxisId:n,hide:r,legendType:i,minPointSize:a,activeBar:s,animationBegin:c,animationDuration:l,animationEasing:u,isAnimationActive:d})))}function jce(e){var t=e.layout,n=e.barSettings,r=n.dataKey,i=n.minPointSize,a=n.hasCustomShape,o=e.pos,s=e.bandSize,c=e.xAxis,l=e.yAxis,u=e.xAxisTicks,d=e.yAxisTicks,f=e.stackedData,p=e.displayedData,m=e.offset,h=e.cells,g=e.parentViewBox,_=e.dataStartIndex,v=t===`horizontal`?l:c,y=f?v.scale.domain():null,b=doe({numericAxis:v}),x=v.scale.map(b);return p.map((e,n)=>{var p,v,S,C,w,T;if(f){var E=f[n+_];if(E==null)return null;p=soe(E,y)}else p=XA(e,r),Array.isArray(p)||(p=[b,p]);var D=L0(i,o2)(p[1],n);if(t===`horizontal`){var O=l.scale.map(p[0]),k=l.scale.map(p[1]);if(O==null||k==null)return null;v=tj({axis:c,ticks:u,bandSize:s,offset:o.offset,entry:e,index:n}),S=k??O??void 0,C=o.size;var A=O-k;if(w=nE(A)?0:A,T={x:v,y:m.top,width:C,height:m.height},Math.abs(D)>0&&Math.abs(w)<Math.abs(D)){var j=tE(w||D)*(Math.abs(D)-Math.abs(w));S-=j,w+=j}}else{var M=c.scale.map(p[0]),N=c.scale.map(p[1]);if(M==null||N==null)return null;if(v=M,S=tj({axis:l,ticks:d,bandSize:s,offset:o.offset,entry:e,index:n}),C=N-M,w=o.size,T={x:m.left,y:S,width:m.width,height:w},Math.abs(D)>0&&Math.abs(C)<Math.abs(D)){var ee=tE(C||D)*(Math.abs(D)-Math.abs(C));C+=ee}}return v==null||S==null||C==null||w==null||!a&&(C===0||w===0)?null:i2(i2({},e),{},{stackedBarStart:x,x:v,y:S,width:C,height:w,value:f?p:p[1],payload:e,background:T,tooltipPosition:{x:v+C/2,y:S+w/2},parentViewBox:g,originalDataIndex:n},h&&h[n]&&h[n].props)}).filter(Boolean)}function Mce(e){var t=ND(e,kce),n=nce(t.stackId),r=_j();return o.createElement(GX,{id:t.id,type:`bar`},e=>o.createElement(o.Fragment,null,o.createElement(dX,{legendPayload:_ce(t)}),o.createElement(vce,{dataKey:t.dataKey,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,unit:t.unit,formatter:t.formatter,tooltipType:t.tooltipType,id:e}),o.createElement(tZ,{type:`bar`,id:e,data:void 0,xAxisId:t.xAxisId,yAxisId:t.yAxisId,zAxisId:0,dataKey:t.dataKey,stackId:n,hide:t.hide,barSize:t.barSize,minPointSize:t.minPointSize,maxBarSize:t.maxBarSize,isPanorama:r,hasCustomShape:t.shape!=null&&t.shape!==F0}),o.createElement(vK,{zIndex:t.zIndex},o.createElement(Ace,n2({},t,{id:e})))))}var s2=o.memo(Mce,qj);s2.displayName=`Bar`;var Nce=[`domain`,`range`],Pce=[`domain`,`range`];function c2(e,t){if(e==null)return{};var n,r,i=Fce(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Fce(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function l2(e,t){return e===t?!0:Array.isArray(e)&&e.length===2&&Array.isArray(t)&&t.length===2?e[0]===t[0]&&e[1]===t[1]:!1}function u2(e,t){if(e===t)return!0;var n=e.domain,r=e.range,i=c2(e,Nce),a=t.domain,o=t.range,s=c2(t,Pce);return!l2(n,a)||!l2(r,o)?!1:qj(i,s)}var Ice=[`type`],Lce=[`dangerouslySetInnerHTML`,`ticks`,`scale`],Rce=[`id`,`scale`];function d2(){return d2=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},d2.apply(null,arguments)}function f2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function p2(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?f2(Object(n),!0).forEach(function(t){zce(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):f2(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function zce(e,t,n){return(t=Bce(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Bce(e){var t=Vce(e,`string`);return typeof t==`symbol`?t:t+``}function Vce(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function m2(e,t){if(e==null)return{};var n,r,i=Hce(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Hce(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Uce(e){var t=OO(),n=(0,o.useRef)(null),r=Lj(),i=e.type,a=m2(e,Ice),s=dF(r,`xAxis`,i),c=(0,o.useMemo)(()=>{if(s!=null)return p2(p2({},a),{},{type:s})},[a,s]);return(0,o.useLayoutEffect)(()=>{c!=null&&(n.current===null?t(tQ(c)):n.current!==c&&t(nQ({prev:n.current,next:c})),n.current=c)},[c,t]),(0,o.useLayoutEffect)(()=>()=>{n.current&&=(t(rQ(n.current)),null)},[t]),null}var Wce=e=>{var t=e.xAxisId,n=e.className,r=e.height,i=e.label,a=(0,o.useRef)(null),s=(0,o.useRef)(null),c=X(gj),l=_j(),u=OO(),d=`xAxis`,f=X(e=>UU(e,d,t,l)),p=X(e=>jU(e,t)),m=X(e=>IU(e,t)),h=X(e=>HV(e,t));if((0,o.useLayoutEffect)(()=>{if(!(r!==`auto`||!p||YJ(i)||(0,o.isValidElement)(i)||h==null)){var e=a.current;if(e){var n=e.getCalculatedHeight();Math.round(p.height)!==Math.round(n)&&u(cQ({id:t,height:n}))}}},[f,p,u,i,t,r,h]),p==null||m==null||h==null)return null;e.dangerouslySetInnerHTML,e.ticks,e.scale;var g=m2(e,Lce);h.id,h.scale;var _=m2(h,Rce);return o.createElement($$,d2({},g,_,{ref:a,labelRef:s,x:m.x,y:m.y,width:p.width,height:p.height,className:ST(`recharts-${d} ${d}`,n),viewBox:c,ticks:f,axisType:d,axisId:t}))},Gce={allowDataOverflow:VV.allowDataOverflow,allowDecimals:VV.allowDecimals,allowDuplicatedCategory:VV.allowDuplicatedCategory,angle:VV.angle,axisLine:W$.axisLine,height:VV.height,hide:!1,includeHidden:VV.includeHidden,interval:VV.interval,label:!1,minTickGap:VV.minTickGap,mirror:VV.mirror,orientation:VV.orientation,padding:VV.padding,reversed:VV.reversed,scale:VV.scale,tick:VV.tick,tickCount:VV.tickCount,tickLine:W$.tickLine,tickSize:W$.tickSize,type:VV.type,niceTicks:VV.niceTicks,xAxisId:0},h2=o.memo(e=>{var t=ND(e,Gce);return o.createElement(o.Fragment,null,o.createElement(Uce,{allowDataOverflow:t.allowDataOverflow,allowDecimals:t.allowDecimals,allowDuplicatedCategory:t.allowDuplicatedCategory,angle:t.angle,dataKey:t.dataKey,domain:t.domain,height:t.height,hide:t.hide,id:t.xAxisId,includeHidden:t.includeHidden,interval:t.interval,minTickGap:t.minTickGap,mirror:t.mirror,name:t.name,orientation:t.orientation,padding:t.padding,reversed:t.reversed,scale:t.scale,tick:t.tick,tickCount:t.tickCount,tickFormatter:t.tickFormatter,ticks:t.ticks,type:t.type,unit:t.unit,niceTicks:t.niceTicks}),o.createElement(Wce,t))},u2);h2.displayName=`XAxis`;var Kce=[`type`],qce=[`dangerouslySetInnerHTML`,`ticks`,`scale`],Jce=[`id`,`scale`];function g2(){return g2=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},g2.apply(null,arguments)}function _2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function v2(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?_2(Object(n),!0).forEach(function(t){Yce(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):_2(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Yce(e,t,n){return(t=Xce(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Xce(e){var t=Zce(e,`string`);return typeof t==`symbol`?t:t+``}function Zce(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function y2(e,t){if(e==null)return{};var n,r,i=Qce(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Qce(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function $ce(e){var t=OO(),n=(0,o.useRef)(null),r=Lj(),i=e.type,a=y2(e,Kce),s=dF(r,`yAxis`,i),c=(0,o.useMemo)(()=>{if(s!=null)return v2(v2({},a),{},{type:s})},[s,a]);return(0,o.useLayoutEffect)(()=>{c!=null&&(n.current===null?t(iQ(c)):n.current!==c&&t(aQ({prev:n.current,next:c})),n.current=c)},[c,t]),(0,o.useLayoutEffect)(()=>()=>{n.current&&=(t(oQ(n.current)),null)},[t]),null}function ele(e){var t=e.yAxisId,n=e.className,r=e.width,i=e.label,a=(0,o.useRef)(null),s=(0,o.useRef)(null),c=X(gj),l=_j(),u=OO(),d=`yAxis`,f=X(e=>RU(e,t)),p=X(e=>LU(e,t)),m=X(e=>UU(e,d,t,l)),h=X(e=>GV(e,t));if((0,o.useLayoutEffect)(()=>{if(!(r!==`auto`||!f||YJ(i)||(0,o.isValidElement)(i)||h==null)){var e=a.current;if(e){var n=e.getCalculatedWidth();Math.round(f.width)!==Math.round(n)&&u(sQ({id:t,width:n}))}}},[m,f,u,i,t,r,h]),f==null||p==null||h==null)return null;e.dangerouslySetInnerHTML,e.ticks,e.scale;var g=y2(e,qce);h.id,h.scale;var _=y2(h,Jce);return o.createElement($$,g2({},g,_,{ref:a,labelRef:s,x:p.x,y:p.y,tickTextProps:r===`auto`?{width:void 0}:{width:r},width:f.width,height:f.height,className:ST(`recharts-${d} ${d}`,n),viewBox:c,ticks:m,axisType:d,axisId:t}))}var tle={allowDataOverflow:WV.allowDataOverflow,allowDecimals:WV.allowDecimals,allowDuplicatedCategory:WV.allowDuplicatedCategory,angle:WV.angle,axisLine:W$.axisLine,hide:!1,includeHidden:WV.includeHidden,interval:WV.interval,label:!1,minTickGap:WV.minTickGap,mirror:WV.mirror,orientation:WV.orientation,padding:WV.padding,reversed:WV.reversed,scale:WV.scale,tick:WV.tick,tickCount:WV.tickCount,tickLine:W$.tickLine,tickSize:W$.tickSize,type:WV.type,niceTicks:WV.niceTicks,width:WV.width,yAxisId:0},b2=o.memo(e=>{var t=ND(e,tle);return o.createElement(o.Fragment,null,o.createElement($ce,{interval:t.interval,id:t.yAxisId,scale:t.scale,type:t.type,domain:t.domain,allowDataOverflow:t.allowDataOverflow,dataKey:t.dataKey,allowDuplicatedCategory:t.allowDuplicatedCategory,allowDecimals:t.allowDecimals,tickCount:t.tickCount,padding:t.padding,includeHidden:t.includeHidden,reversed:t.reversed,ticks:t.ticks,width:t.width,orientation:t.orientation,mirror:t.mirror,hide:t.hide,unit:t.unit,name:t.name,angle:t.angle,minTickGap:t.minTickGap,tick:t.tick,tickFormatter:t.tickFormatter,niceTicks:t.niceTicks}),o.createElement(ele,t))},u2);b2.displayName=`YAxis`;var x2=Z([(e,t)=>t,Fj,DF,IF,sG,lG,HG,hj],eK);function nle(e){return`getBBox`in e.currentTarget&&typeof e.currentTarget.getBBox==`function`}function S2(e){var t=e.currentTarget.getBoundingClientRect(),n,r;if(nle(e)){var i=e.currentTarget.getBBox();n=i.width>0?t.width/i.width:1,r=i.height>0?t.height/i.height:1}else{var a=e.currentTarget;n=a.offsetWidth>0?t.width/a.offsetWidth:1,r=a.offsetHeight>0?t.height/a.offsetHeight:1}var o=(e,i)=>({relativeX:Math.round((e-t.left)/n),relativeY:Math.round((i-t.top)/r)});return`touches`in e?Array.from(e.touches).map(e=>o(e.clientX,e.clientY)):o(e.clientX,e.clientY)}var C2=cA(`mouseClick`),w2=HA();w2.startListening({actionCreator:C2,effect:(e,t)=>{var n=e.payload,r=x2(t.getState(),S2(n));r?.activeIndex!=null&&t.dispatch(fW({activeIndex:r.activeIndex,activeDataKey:void 0,activeCoordinate:r.activeCoordinate}))}});var T2=cA(`mouseMove`),E2=HA(),D2=null,O2=null,k2=null;E2.startListening({actionCreator:T2,effect:(e,t)=>{var n=e.payload,r=t.getState().eventSettings,i=r.throttleDelay,a=r.throttledEvents,o=a===`all`||a?.includes(`mousemove`);D2!==null&&(cancelAnimationFrame(D2),D2=null),O2!==null&&(typeof i!=`number`||!o)&&(clearTimeout(O2),O2=null),k2=S2(n);var s=()=>{var e=t.getState(),n=XU(e,e.tooltip.settings.shared);if(!k2){D2=null,O2=null;return}if(n===`axis`){var r=x2(e,k2);r?.activeIndex==null?t.dispatch(lW()):t.dispatch(dW({activeIndex:r.activeIndex,activeDataKey:void 0,activeCoordinate:r.activeCoordinate}))}D2=null,O2=null};if(!o){s();return}i===`raf`?D2=requestAnimationFrame(s):typeof i==`number`&&O2===null&&(O2=setTimeout(s,i))}});function rle(e,t){return t instanceof HTMLElement?`HTMLElement <${t.tagName} class="${t.className}">`:t===window?`global.window`:e===`children`&&typeof t==`object`&&t?`<<CHILDREN>>`:t}var A2={accessibilityLayer:!0,barCategoryGap:`10%`,barGap:4,barSize:void 0,className:void 0,maxBarSize:void 0,stackOffset:`none`,syncId:void 0,syncMethod:`index`,baseValue:void 0,reverseStackOrder:!1},j2=_A({name:`rootProps`,initialState:A2,reducers:{updateOptions:(e,t)=>{e.accessibilityLayer=t.payload.accessibilityLayer,e.barCategoryGap=t.payload.barCategoryGap,e.barGap=t.payload.barGap??A2.barGap,e.barSize=t.payload.barSize,e.maxBarSize=t.payload.maxBarSize,e.stackOffset=t.payload.stackOffset,e.syncId=t.payload.syncId,e.syncMethod=t.payload.syncMethod,e.className=t.payload.className,e.baseValue=t.payload.baseValue,e.reverseStackOrder=t.payload.reverseStackOrder}}}),ile=j2.reducer,ale=j2.actions.updateOptions,M2=_A({name:`polarOptions`,initialState:null,reducers:{updatePolarOptions:(e,t)=>e===null?t.payload:(e.startAngle=t.payload.startAngle,e.endAngle=t.payload.endAngle,e.cx=t.payload.cx,e.cy=t.payload.cy,e.innerRadius=t.payload.innerRadius,e.outerRadius=t.payload.outerRadius,e)}}),ole=M2.actions.updatePolarOptions,sle=M2.reducer,N2=cA(`keyDown`),P2=cA(`focus`),F2=cA(`blur`),I2=HA(),L2=null,R2=null,z2=null;I2.startListening({actionCreator:N2,effect:(e,t)=>{z2=e.payload,L2!==null&&(cancelAnimationFrame(L2),L2=null);var n=t.getState().eventSettings,r=n.throttleDelay,i=n.throttledEvents,a=i===`all`||i.includes(`keydown`);R2!==null&&(typeof r!=`number`||!a)&&(clearTimeout(R2),R2=null);var o=()=>{try{var e=t.getState();if(e.rootProps.accessibilityLayer===!1)return;var n=e.tooltip.keyboardInteraction,r=z2;if(r!==`ArrowRight`&&r!==`ArrowLeft`&&r!==`Enter`)return;var i=DW(n,YW(e),CH(e),iG(e)),a=i==null?-1:Number(i),o=!Number.isFinite(a)||a<0,s=lG(e),c=YW(e),l=XU(e,e.tooltip.settings.shared);if(r===`Enter`){if(o)return;var u=qG(e,l,`hover`,String(n.index));t.dispatch(mW({active:!n.active,activeIndex:n.index,activeCoordinate:u}));return}var d=KU(e)===`left-to-right`?1:-1,f=r===`ArrowRight`?1:-1,p;if(o){var m=CH(e),h=iG(e),g=f*d,_=e=>({active:!1,index:String(e),dataKey:void 0,graphicalItemId:void 0,coordinate:void 0});if(p=-1,g>0){for(var v=0;v<c.length;v++)if(DW(_(v),c,m,h)!=null){p=v;break}}else for(var y=c.length-1;y>=0;y--)if(DW(_(y),c,m,h)!=null){p=y;break}if(p<0)return}else{p=a+f*d;var b=s?.length||c.length;if(b===0||p>=b||p<0)return}var x=qG(e,l,`hover`,String(p));t.dispatch(mW({active:!0,activeIndex:p.toString(),activeCoordinate:x}))}finally{L2=null,R2=null}};if(!a){o();return}r===`raf`?L2=requestAnimationFrame(o):typeof r==`number`&&R2===null&&(o(),z2=null,R2=setTimeout(()=>{z2?o():(R2=null,L2=null)},r))}}),I2.startListening({actionCreator:P2,effect:(e,t)=>{var n=t.getState();if(n.rootProps.accessibilityLayer!==!1){var r=n.tooltip.keyboardInteraction;if(!r.active&&r.index==null){var i=`0`,a=qG(n,XU(n,n.tooltip.settings.shared),`hover`,String(i));t.dispatch(mW({active:!0,activeIndex:i,activeCoordinate:a}))}}}}),I2.startListening({actionCreator:F2,effect:(e,t)=>{var n=t.getState();if(n.rootProps.accessibilityLayer!==!1){var r=n.tooltip.keyboardInteraction;r.active&&t.dispatch(mW({active:!1,activeIndex:r.index,activeCoordinate:r.coordinate}))}}});function B2(e){e.persist();var t=e.currentTarget;return new Proxy(e,{get:(e,n)=>{if(n===`currentTarget`)return t;var r=Reflect.get(e,n);return typeof r==`function`?r.bind(e):r}})}var V2=cA(`externalEvent`),H2=HA(),U2=new Map,W2=new Map,G2=new Map;H2.startListening({actionCreator:V2,effect:(e,t)=>{var n=e.payload,r=n.handler,i=n.reactEvent;if(r!=null){var a=i.type,o=B2(i);G2.set(a,{handler:r,reactEvent:o});var s=U2.get(a);s!==void 0&&(cancelAnimationFrame(s),U2.delete(a));var c=t.getState().eventSettings,l=c.throttleDelay,u=c.throttledEvents,d=u===`all`||u?.includes(a),f=W2.get(a);f!==void 0&&(typeof l!=`number`||!d)&&(clearTimeout(f),W2.delete(a));var p=()=>{var e=G2.get(a);try{if(!e)return;var n=e.handler,r=e.reactEvent,i=t.getState(),o={activeCoordinate:yG(i),activeDataKey:gG(i),activeIndex:mG(i),activeLabel:hG(i),activeTooltipIndex:mG(i),isTooltipActive:bG(i)};n&&n(o,r)}finally{U2.delete(a),W2.delete(a),G2.delete(a)}};if(!d){p();return}if(l===`raf`){var m=requestAnimationFrame(p);U2.set(a,m)}else if(typeof l==`number`){if(!W2.has(a)){p();var h=setTimeout(p,l);W2.set(a,h)}}else p()}}});var cle=Z([Z([jW],e=>e.tooltipItemPayloads),(e,t)=>t,(e,t,n)=>n],(e,t,n)=>{if(t!=null){var r=e.find(e=>e.settings.graphicalItemId===n);if(r!=null){var i=r.getPosition;if(i!=null)return i(t)}}}),K2=cA(`touchMove`),q2=HA(),J2=null,Y2=null,X2=null,Z2=null;q2.startListening({actionCreator:K2,effect:(e,t)=>{var n=e.payload;if(n.touches!=null&&n.touches.length!==0){Z2=B2(n);var r=t.getState().eventSettings,i=r.throttleDelay,a=r.throttledEvents,o=a===`all`||a.includes(`touchmove`);J2!==null&&(cancelAnimationFrame(J2),J2=null),Y2!==null&&(typeof i!=`number`||!o)&&(clearTimeout(Y2),Y2=null),X2=Array.from(n.touches).map(e=>S2({clientX:e.clientX,clientY:e.clientY,currentTarget:n.currentTarget}));var s=()=>{if(Z2!=null){var e=t.getState(),n=XU(e,e.tooltip.settings.shared);if(n===`axis`){var r=X2?.[0];if(r==null){J2=null,Y2=null;return}var i=x2(e,r);i?.activeIndex!=null&&t.dispatch(dW({activeIndex:i.activeIndex,activeDataKey:void 0,activeCoordinate:i.activeCoordinate}))}else if(n===`item`){var a=Z2.touches[0];if(document.elementFromPoint==null||a==null)return;var o=document.elementFromPoint(a.clientX,a.clientY);if(!o||!o.getAttribute)return;var s=o.getAttribute(fj),c=o.getAttribute(`data-recharts-item-id`)??void 0,l=GW(e).find(e=>e.id===c);if(s==null||l==null||c==null)return;var u=l.dataKey,d=cle(e,s,c);t.dispatch(sW({activeDataKey:u,activeIndex:s,activeCoordinate:d,activeGraphicalItemId:c}))}J2=null,Y2=null}};if(!o){s();return}i===`raf`?J2=requestAnimationFrame(s):typeof i==`number`&&Y2===null&&(s(),Z2=null,Y2=setTimeout(()=>{Z2?s():(Y2=null,J2=null)},i))}}});var Q2={throttleDelay:`raf`,throttledEvents:[`mousemove`,`touchmove`,`pointermove`,`scroll`,`wheel`]},$2=_A({name:`eventSettings`,initialState:Q2,reducers:{setEventSettings:(e,t)=>{t.payload.throttleDelay!=null&&(e.throttleDelay=t.payload.throttleDelay),t.payload.throttledEvents!=null&&(e.throttledEvents=oA(t.payload.throttledEvents))}}}),lle=$2.actions.setEventSettings,ule=$2.reducer,dle=YO({brush:VQ,cartesianAxis:lQ,chartData:UK,errorBars:R1,eventSettings:ule,graphicalItems:eZ,layout:noe,legend:ese,options:IK,polarAxis:kY,polarOptions:sle,referenceElements:KQ,renderedTicks:O$,rootProps:ile,tooltip:hW,zIndex:_K}),fle=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Chart`;return Oae({reducer:dle,preloadedState:e,middleware:e=>e({serializableCheck:!1,immutableCheck:![`commonjs`,`es6`,`production`].includes(`es6`)}).concat([w2.middleware,E2.middleware,I2.middleware,H2.middleware,q2.middleware]),enhancers:e=>{var t=e;return typeof e==`function`&&(t=e()),t.concat(hA({type:`raf`}))},devTools:tM.devToolsEnabled&&{serialize:{replacer:rle},name:`recharts-${t}`}})};function e4(e){var t=e.preloadedState,n=e.children,r=e.reduxStoreName,i=_j(),a=(0,o.useRef)(null);if(i)return n;a.current??=fle(t,r);var s=DO;return o.createElement(mse,{context:s,store:a.current},n)}function ple(e){var t=e.layout,n=e.margin,r=OO(),i=_j();return(0,o.useEffect)(()=>{i||(r($ae(t)),r(Qae(n)))},[r,i,t,n]),null}var t4=(0,o.memo)(ple,qj);function n4(e){var t=OO();return(0,o.useEffect)(()=>{t(ale(e))},[t,e]),null}var r4=(0,o.memo)(e=>{var t=OO();return(0,o.useEffect)(()=>{t(lle(e))},[t,e]),null},qj);function i4(e){var t=e.zIndex,n=e.isPanorama,r=(0,o.useRef)(null),i=OO();return(0,o.useLayoutEffect)(()=>(r.current&&i(hK({zIndex:t,element:r.current,isPanorama:n})),()=>{i(gK({zIndex:t,isPanorama:n}))}),[i,t,n]),o.createElement(`g`,{tabIndex:-1,ref:r,className:`recharts-zIndex-layer_${t}`})}function a4(e){var t=e.children,n=e.isPanorama,r=X(nK);if(!r||r.length===0)return t;var i=r.filter(e=>e<0),a=r.filter(e=>e>0);return o.createElement(o.Fragment,null,i.map(e=>o.createElement(i4,{key:e,zIndex:e,isPanorama:n})),t,a.map(e=>o.createElement(i4,{key:e,zIndex:e,isPanorama:n})))}var mle=[`children`];function hle(e,t){if(e==null)return{};var n,r,i=gle(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function gle(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function o4(){return o4=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},o4.apply(null,arguments)}var _le={width:`100%`,height:`100%`,display:`block`},vle=(0,o.forwardRef)((e,t)=>{var n=Nj(),r=Pj(),i=sM();if(!qA(n)||!qA(r))return null;var a=e.children,s=e.otherAttributes,c=e.title,l=e.desc,u,d;return s!=null&&(u=typeof s.tabIndex==`number`?s.tabIndex:i?0:void 0,d=typeof s.role==`string`?s.role:i?`application`:void 0),o.createElement(IT,o4({},s,{title:c,desc:l,role:d,tabIndex:u,width:n,height:r,style:_le,ref:t}),a)}),yle=e=>{var t=e.children,n=X(yj);if(!n)return null;var r=n.width,i=n.height,a=n.y,s=n.x;return o.createElement(IT,{width:r,height:i,x:s,y:a},t)},s4=(0,o.forwardRef)((e,t)=>{var n=e.children,r=hle(e,mle);return _j()?o.createElement(yle,null,o.createElement(a4,{isPanorama:!0},n)):o.createElement(vle,o4({ref:t},r),o.createElement(a4,{isPanorama:!1},n))});function ble(e,t){return wle(e)||Cle(e,t)||Sle(e,t)||xle()}function xle(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
66
66
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Sle(e,t){if(e){if(typeof e==`string`)return c4(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?c4(e,t):void 0}}function c4(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Cle(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function wle(e){if(Array.isArray(e))return e}function Tle(){var e=OO(),t=ble((0,o.useState)(null),2),n=t[0],r=t[1],i=X(_oe);return(0,o.useEffect)(()=>{if(n!=null){var t=n.getBoundingClientRect().width/n.offsetWidth;Q(t)&&t!==i&&e(toe(t))}},[n,e,i]),r}function l4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Ele(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?l4(Object(n),!0).forEach(function(t){Dle(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l4(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Dle(e,t,n){return(t=Ole(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ole(e){var t=kle(e,`string`);return typeof t==`symbol`?t:t+``}function kle(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function u4(){return u4=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},u4.apply(null,arguments)}function d4(e,t){return Nle(e)||Mle(e,t)||jle(e,t)||Ale()}function Ale(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
67
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function jle(e,t){if(e){if(typeof e==`string`)return f4(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?f4(e,t):void 0}}function f4(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Mle(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function Nle(e){if(Array.isArray(e))return e}var Ple=()=>(eq(),null);function p4(e){if(typeof e==`number`)return e;if(typeof e==`string`){var t=parseFloat(e);if(!Number.isNaN(t))return t}return 0}var Fle=(0,o.forwardRef)((e,t)=>{var n=(0,o.useRef)(null),r=d4((0,o.useState)({containerWidth:p4(e.style?.width),containerHeight:p4(e.style?.height)}),2),i=r[0],a=r[1],s=(0,o.useCallback)((e,t)=>{a(n=>{var r=Math.round(e),i=Math.round(t);return n.containerWidth===r&&n.containerHeight===i?n:{containerWidth:r,containerHeight:i}})},[]),c=(0,o.useCallback)(e=>{if(typeof t==`function`&&t(e),n.current!=null&&(n.current.disconnect(),n.current=null),e!=null&&typeof ResizeObserver<`u`){var r=e.getBoundingClientRect(),i=r.width,a=r.height;s(i,a);var o=new ResizeObserver(e=>{var t=e[0];if(t!=null){var n=t.contentRect,r=n.width,i=n.height;s(r,i)}});o.observe(e),n.current=o}},[t,s]);return(0,o.useEffect)(()=>()=>{n.current?.disconnect()},[s]),o.createElement(o.Fragment,null,o.createElement(zj,{width:i.containerWidth,height:i.containerHeight}),o.createElement(`div`,u4({ref:c},e)))}),Ile=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height,i=d4((0,o.useState)({containerWidth:p4(n),containerHeight:p4(r)}),2),a=i[0],s=i[1],c=(0,o.useCallback)((e,t)=>{s(n=>{var r=Math.round(e),i=Math.round(t);return n.containerWidth===r&&n.containerHeight===i?n:{containerWidth:r,containerHeight:i}})},[]),l=(0,o.useCallback)(e=>{if(typeof t==`function`&&t(e),e!=null){var n=e.getBoundingClientRect(),r=n.width,i=n.height;c(r,i)}},[t,c]);return o.createElement(o.Fragment,null,o.createElement(zj,{width:a.containerWidth,height:a.containerHeight}),o.createElement(`div`,u4({ref:l},e)))}),Lle=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height;return o.createElement(o.Fragment,null,o.createElement(zj,{width:n,height:r}),o.createElement(`div`,u4({ref:t},e)))}),Rle=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height;return typeof n==`string`||typeof r==`string`?o.createElement(Ile,u4({},e,{ref:t})):typeof n==`number`&&typeof r==`number`?o.createElement(Lle,u4({},e,{width:n,height:r,ref:t})):o.createElement(o.Fragment,null,o.createElement(zj,{width:n,height:r}),o.createElement(`div`,u4({ref:t},e)))});function zle(e){return e?Fle:Rle}var Ble=(0,o.forwardRef)((e,t)=>{var n=e.children,r=e.className,i=e.height,a=e.onClick,s=e.onContextMenu,c=e.onDoubleClick,l=e.onMouseDown,u=e.onMouseEnter,d=e.onMouseLeave,f=e.onMouseMove,p=e.onMouseUp,m=e.onTouchEnd,h=e.onTouchMove,g=e.onTouchStart,_=e.style,v=e.width,y=e.responsive,b=e.dispatchTouchEvents,x=b===void 0||b,S=(0,o.useRef)(null),C=OO(),w=d4((0,o.useState)(null),2),T=w[0],E=w[1],D=d4((0,o.useState)(null),2),O=D[0],k=D[1],A=Tle(),j=kj(),M=j?.width>0?j.width:v,N=j?.height>0?j.height:i,ee=(0,o.useCallback)(e=>{A(e),typeof t==`function`&&t(e),E(e),k(e),e!=null&&(S.current=e)},[A,t,E,k]),P=(0,o.useCallback)(e=>{C(C2(e)),C(V2({handler:a,reactEvent:e}))},[C,a]),te=(0,o.useCallback)(e=>{C(T2(e)),C(V2({handler:u,reactEvent:e}))},[C,u]),F=(0,o.useCallback)(e=>{C(lW()),C(V2({handler:d,reactEvent:e}))},[C,d]),ne=(0,o.useCallback)(e=>{C(T2(e)),C(V2({handler:f,reactEvent:e}))},[C,f]),re=(0,o.useCallback)(()=>{C(P2())},[C]),ie=(0,o.useCallback)(()=>{C(F2())},[C]),I=(0,o.useCallback)(e=>{C(N2(e.key))},[C]),ae=(0,o.useCallback)(e=>{C(V2({handler:s,reactEvent:e}))},[C,s]),L=(0,o.useCallback)(e=>{C(V2({handler:c,reactEvent:e}))},[C,c]),oe=(0,o.useCallback)(e=>{C(V2({handler:l,reactEvent:e}))},[C,l]),R=(0,o.useCallback)(e=>{C(V2({handler:p,reactEvent:e}))},[C,p]),se=(0,o.useCallback)(e=>{C(V2({handler:g,reactEvent:e}))},[C,g]),ce=(0,o.useCallback)(e=>{x&&C(K2(e)),C(V2({handler:h,reactEvent:e}))},[C,x,h]),le=(0,o.useCallback)(e=>{C(V2({handler:m,reactEvent:e}))},[C,m]),ue=zle(y);return o.createElement(OK.Provider,{value:T},o.createElement(wE.Provider,{value:O},o.createElement(ue,{width:M??_?.width,height:N??_?.height,className:ST(`recharts-wrapper`,r),style:Ele({position:`relative`,cursor:`default`,width:M,height:N},_),onClick:P,onContextMenu:ae,onDoubleClick:L,onFocus:re,onBlur:ie,onKeyDown:I,onMouseDown:oe,onMouseEnter:te,onMouseLeave:F,onMouseMove:ne,onMouseUp:R,onTouchEnd:le,onTouchMove:ce,onTouchStart:se,ref:ee},o.createElement(Ple,null),n)))}),Vle=[`width`,`height`,`responsive`,`children`,`className`,`style`,`compact`,`title`,`desc`];function Hle(e,t){if(e==null)return{};var n,r,i=Ule(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Ule(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var m4=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height,i=e.responsive,a=e.children,s=e.className,c=e.style,l=e.compact,u=e.title,d=e.desc,f=OT(Hle(e,Vle));return l?o.createElement(o.Fragment,null,o.createElement(zj,{width:n,height:r}),o.createElement(s4,{otherAttributes:f,title:u,desc:d},a)):o.createElement(Ble,{className:s,style:c,width:n,height:r,responsive:i??!1,onClick:e.onClick,onMouseLeave:e.onMouseLeave,onMouseEnter:e.onMouseEnter,onMouseMove:e.onMouseMove,onMouseDown:e.onMouseDown,onMouseUp:e.onMouseUp,onContextMenu:e.onContextMenu,onDoubleClick:e.onDoubleClick,onTouchStart:e.onTouchStart,onTouchMove:e.onTouchMove,onTouchEnd:e.onTouchEnd},o.createElement(s4,{otherAttributes:f,title:u,desc:d,ref:t},o.createElement(e$,null,a)))});function h4(){return h4=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},h4.apply(null,arguments)}function g4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Wle(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?g4(Object(n),!0).forEach(function(t){Gle(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):g4(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Gle(e,t,n){return(t=Kle(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Kle(e){var t=qle(e,`string`);return typeof t==`symbol`?t:t+``}function qle(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var Jle=Wle({accessibilityLayer:!0,barCategoryGap:`10%`,barGap:4,layout:`horizontal`,margin:{top:5,right:5,bottom:5,left:5},responsive:!1,reverseStackOrder:!1,stackOffset:`none`,syncMethod:`index`},Q2),_4=(0,o.forwardRef)(function(e,t){var n=ND(e.categoricalChartProps,Jle),r=e.chartName,i=e.defaultTooltipEventType,a=e.validateTooltipEventTypes,s=e.tooltipPayloadSearcher,c=e.categoricalChartProps,l={chartName:r,defaultTooltipEventType:i,validateTooltipEventTypes:a,tooltipPayloadSearcher:s,eventEmitter:void 0};return o.createElement(e4,{preloadedState:{options:l},reduxStoreName:c.id??r},o.createElement(RQ,{chartData:c.data}),o.createElement(t4,{layout:n.layout,margin:n.margin}),o.createElement(r4,{throttleDelay:n.throttleDelay,throttledEvents:n.throttledEvents}),o.createElement(n4,{baseValue:n.baseValue,accessibilityLayer:n.accessibilityLayer,barCategoryGap:n.barCategoryGap,maxBarSize:n.maxBarSize,stackOffset:n.stackOffset,barGap:n.barGap,barSize:n.barSize,syncId:n.syncId,syncMethod:n.syncMethod,className:n.className,reverseStackOrder:n.reverseStackOrder}),o.createElement(m4,h4({},n,{ref:t})))}),Yle=[`axis`],Xle=(0,o.forwardRef)((e,t)=>o.createElement(_4,{chartName:`LineChart`,defaultTooltipEventType:`axis`,validateTooltipEventTypes:Yle,tooltipPayloadSearcher:PK,categoricalChartProps:e,ref:t})),Zle=[`axis`,`item`],v4=(0,o.forwardRef)((e,t)=>o.createElement(_4,{chartName:`BarChart`,defaultTooltipEventType:`axis`,validateTooltipEventTypes:Zle,tooltipPayloadSearcher:PK,categoricalChartProps:e,ref:t}));function Qle(e){var t=OO();return(0,o.useEffect)(()=>{t(ole(e))},[t,e]),null}var $le=[`layout`];function y4(){return y4=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},y4.apply(null,arguments)}function eue(e,t){if(e==null)return{};var n,r,i=tue(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function tue(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function b4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function nue(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?b4(Object(n),!0).forEach(function(t){rue(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):b4(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function rue(e,t,n){return(t=iue(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function iue(e){var t=aue(e,`string`);return typeof t==`symbol`?t:t+``}function aue(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var x4=nue({accessibilityLayer:!0,stackOffset:`none`,barCategoryGap:`10%`,barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:`index`,layout:`radial`,responsive:!1,cx:`50%`,cy:`50%`,innerRadius:0,outerRadius:`80%`},Q2),oue=(0,o.forwardRef)(function(e,t){var n=ND(e.categoricalChartProps,x4),r=n.layout,i=eue(n,$le),a=e.chartName,s={chartName:a,defaultTooltipEventType:e.defaultTooltipEventType,validateTooltipEventTypes:e.validateTooltipEventTypes,tooltipPayloadSearcher:e.tooltipPayloadSearcher,eventEmitter:void 0};return o.createElement(e4,{preloadedState:{options:s},reduxStoreName:n.id??a},o.createElement(RQ,{chartData:n.data}),o.createElement(t4,{layout:r,margin:n.margin}),o.createElement(r4,{throttleDelay:n.throttleDelay,throttledEvents:n.throttledEvents}),o.createElement(n4,{baseValue:void 0,accessibilityLayer:n.accessibilityLayer,barCategoryGap:n.barCategoryGap,maxBarSize:n.maxBarSize,stackOffset:n.stackOffset,barGap:n.barGap,barSize:n.barSize,syncId:n.syncId,syncMethod:n.syncMethod,className:n.className,reverseStackOrder:n.reverseStackOrder}),o.createElement(Qle,{cx:n.cx,cy:n.cy,startAngle:n.startAngle,endAngle:n.endAngle,innerRadius:n.innerRadius,outerRadius:n.outerRadius}),o.createElement(m4,y4({},i,{ref:t})))});function S4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function C4(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?S4(Object(n),!0).forEach(function(t){sue(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):S4(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function sue(e,t,n){return(t=cue(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function cue(e){var t=lue(e,`string`);return typeof t==`symbol`?t:t+``}function lue(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var uue=[`item`],due=C4(C4({},x4),{},{layout:`centric`,startAngle:0,endAngle:360}),fue=(0,o.forwardRef)((e,t)=>{var n=ND(e,due);return o.createElement(oue,{chartName:`PieChart`,defaultTooltipEventType:`item`,validateTooltipEventTypes:uue,tooltipPayloadSearcher:PK,categoricalChartProps:n,ref:t})}),pue=(e,t)=>t>0?`${Math.round(e/t*100)}%`:``,mue=({active:e,payload:t,measure:n})=>{let r=t?.[0]?.payload;return!e||!r?null:(0,V.jsxs)(`div`,{className:`rounded-md border bg-background px-2.5 py-1.5 text-xs shadow-pop`,children:[(0,V.jsx)(`div`,{className:`text-muted-foreground`,children:r.label}),(0,V.jsx)(`div`,{className:`font-semibold tabular-nums`,children:yT(r.value,n)})]})},hue=({resource:e,slices:t,measure:n})=>{let r=t.filter(e=>e.value!==null&&e.value>0),i=r.reduce((e,t)=>e+t.value,0);return(0,V.jsxs)(`div`,{className:`flex flex-col items-center gap-4 sm:flex-row sm:items-center`,children:[(0,V.jsx)(`div`,{className:`size-36 shrink-0`,children:(0,V.jsx)(Aj,{width:`100%`,height:`100%`,children:(0,V.jsxs)(fue,{children:[(0,V.jsx)(FZ,{data:r,dataKey:`value`,nameKey:`label`,innerRadius:`62%`,outerRadius:`100%`,paddingAngle:+(r.length>1),stroke:`var(--background)`,strokeWidth:2,isAnimationActive:!1,children:r.map(e=>(0,V.jsx)(vq,{fill:e.color},e.key))}),(0,V.jsx)(_q,{content:(0,V.jsx)(mue,{measure:n}),isAnimationActive:!1})]})})}),(0,V.jsx)(`ul`,{className:`flex w-full min-w-0 flex-col gap-0.5`,children:t.map(t=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(FC,{to:{kind:`list`,resource:e,filter:t.filter},className:`group flex items-center gap-2 rounded-md px-1 py-0.5 hover:bg-muted`,children:[(0,V.jsx)(`span`,{className:`size-2.5 shrink-0 rounded-full`,style:{background:t.color},"aria-hidden":!0}),(0,V.jsx)(`span`,{className:`min-w-0 flex-1 truncate group-hover:text-primary-text`,children:t.label}),(0,V.jsx)(`span`,{className:`font-medium tabular-nums`,children:yT(t.value,n)}),(0,V.jsx)(`span`,{className:`w-9 text-right text-xs text-muted-foreground tabular-nums`,children:pue(t.value??0,i)})]})},t.key))})]})},gue={hour:{hour:`2-digit`,minute:`2-digit`,hour12:!1},day:{day:`numeric`,month:`short`},week:{day:`numeric`,month:`short`},month:{month:`short`,year:`2-digit`},year:{year:`numeric`}},_ue={hour:{day:`numeric`,month:`short`,hour:`2-digit`,minute:`2-digit`,hour12:!1},day:{day:`numeric`,month:`short`,year:`numeric`},week:{day:`numeric`,month:`short`,year:`numeric`},month:{month:`long`,year:`numeric`},year:{year:`numeric`}},w4=e=>{let t=new Intl.DateTimeFormat(`en-GB`,{...e,timeZone:`UTC`});return e=>t.format(e)},T4={fontSize:11,fill:`var(--muted-foreground)`},vue=({active:e,payload:t,measure:n,bucket:r})=>{let i=t?.[0]?.payload;return!e||!i?null:(0,V.jsxs)(`div`,{className:`rounded-md border bg-background px-2.5 py-1.5 text-xs shadow-pop`,children:[(0,V.jsx)(`div`,{className:`text-muted-foreground`,children:(r===`week`?`Week of `:``)+w4(_ue[r])(i.at)}),(0,V.jsx)(`div`,{className:`font-semibold tabular-nums`,children:yT(i.value,n)})]})},yue=({points:e,measure:t,bucket:n,type:r})=>{let i=pu(`(min-width: 640px)`),a=w4(gue[n]),o=(0,V.jsx)(C1,{vertical:!1,stroke:`var(--border)`}),s=(0,V.jsx)(h2,{dataKey:`at`,tickFormatter:a,tick:T4,axisLine:!1,tickLine:!1,minTickGap:i?24:40,height:18}),c=(0,V.jsx)(b2,{width:i?48:36,tick:T4,axisLine:!1,tickLine:!1,tickCount:3,tickFormatter:e=>e.toLocaleString(`en-IE`,{notation:`compact`})}),l=(0,V.jsx)(_q,{cursor:r===`bar`?{fill:`var(--muted)`}:{stroke:`var(--border-strong)`},content:(0,V.jsx)(vue,{measure:t,bucket:n}),isAnimationActive:!1});return(0,V.jsx)(`div`,{className:`h-40`,children:(0,V.jsx)(Aj,{width:`100%`,height:`100%`,children:r===`line`?(0,V.jsxs)(Xle,{data:e,margin:{top:6,right:6,bottom:0,left:0},children:[o,s,c,l,(0,V.jsx)(D0,{dataKey:`value`,stroke:`var(--chart-1)`,strokeWidth:2,dot:e.length<=31&&{r:3,fill:`var(--chart-1)`,strokeWidth:0},activeDot:{r:4,stroke:`var(--background)`,strokeWidth:2},isAnimationActive:!1})]}):(0,V.jsxs)(v4,{data:e,margin:{top:6,right:0,bottom:0,left:0},barCategoryGap:`22%`,children:[o,s,c,l,(0,V.jsx)(s2,{dataKey:`value`,fill:`var(--chart-1)`,radius:[4,4,0,0],isAnimationActive:!1})]})})})},bue=(e,t,n,r)=>{let i=n??r,a=i===void 0?void 0:e.fields[i];return!a||i===void 0?{kind:`count`}:{kind:n===void 0?`average`:`sum`,field:a,hints:t?.fields[i]}},E4=({model:e,view:t,groupBy:n,type:r=`bar`,sum:i,average:a,filter:o=``,granularity:s=`day`,range:c=`30d`,limit:l=10,empty:u=`Nothing to chart yet.`})=>{let{resources:d,views:f}=q(),p=e.fields[n],m=p?.type===`date`||p?.type===`timestamp`,h=p?.type===`relation`&&p.relation?d[p.relation.resource]:void 0,g=h&&h.primaryKey.length===1?Eg(h,f[h.name]):void 0,_=m?{granularity:s,range:c}:{limit:l,...g&&{label:g}},v=uT(e.name,{groupBy:n,filter:o,...i&&{sum:i},...a&&{average:a},..._},!!p),y=bue(e,t,i,a);if(!p)return null;if(v.isPending)return(0,V.jsx)(Au,{className:`h-36 w-full`});if(v.error)return(0,V.jsx)(`p`,{className:`text-danger-text`,children:`Could not load the chart.`});let{groups:b}=v.data;if(b.every(e=>e.count===0))return(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:u});if(m)return(0,V.jsx)(yue,{points:vT(b,y),measure:y,bucket:s,type:r===`line`?`line`:`bar`});let x=_T(b,p,t?.fields[n],y,o);return r===`donut`?(0,V.jsx)(hue,{resource:e.name,slices:x,measure:y}):(0,V.jsx)(bT,{resource:e.name,slices:x,measure:y})},xue=({node:e,slots:t})=>{let{resource:n,title:r,description:i,actions:a,span:o,...s}=eT(e),{resources:c,views:l}=q(),u=c[n];return u?(0,V.jsx)(nT,{title:r,description:i,actions:t.actions,className:`h-full`,children:(0,V.jsx)(E4,{model:u,view:l[n],...s})}):null},Sue=uo(),D4=async(e,t,n,r,i)=>{let a=n.primaryKey[0],o=[...new Set(r)].sort();if(o.length===0||n.primaryKey.length!==1)return new Map;let s=Eg(n,i),c=await e.fetchQuery({queryKey:W.labels(n.name,o.join(`,`)),staleTime:3e5,queryFn:async()=>(await t.list(n.name,{filter:Ya(Sue.in(a,o)),fields:[a,s],pageSize:o.length})).items.map(e=>[String(e[a]),String(e[s])])});return new Map(c)},O4=(e,t,n)=>n.flatMap(n=>{let r=t.fields[n],i=r?.type===`relation`&&r.relation?e[r.relation.resource]:void 0;return i?[{name:n,target:i}]:[]}),k4=(e,t,n,r)=>Object.fromEntries(O4(e,n,r).filter(({target:e})=>e.primaryKey.length===1).map(({name:e,target:n})=>[e,Eg(n,t[n.name])])),A4=(e,t,n,r,i={})=>{let a=O4(e,t,n);return r.map(e=>{let t={...e};for(let{name:n}of a)e[n]!=null&&(t[n]={id:e[n],name:i[n]?.[String(e[n])]??String(e[n])});return t})},j4=(e,t)=>{let n=String(t);return e&&Object.hasOwn(e,n)?e[n]:void 0},M4=({value:e,hints:t,children:n})=>(0,V.jsx)(Zu,{tone:HS(String(e)),color:j4(t?.valueColors,e),shape:t?.badgeShape,children:n}),Cue=({field:e,value:t,known:n})=>{let{resources:r,views:i}=q(),a=G(),o=Wp(),s=e.relation?r[e.relation.resource]:void 0,c=String(t),l=vh({queryKey:W.relatedLabel(s?.name??``,c),enabled:!!s&&n===void 0,queryFn:async()=>(await D4(o,a,s,[c],i[s.name])).get(c)??c});return s?(0,V.jsx)(FC,{to:{kind:`record`,resource:s.name,key:c},className:`font-medium text-primary-text hover:underline`,children:n??l.data??c}):(0,V.jsx)(`span`,{children:c})},wue=({model:e,field:t,value:n,format:r,relationLabel:i})=>{let{views:a}=q(),o={...a[e.name]?.fields[t.name],...r&&{format:r}};if(n==null||n===``)return(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`—`});if(t.type===`relation`)return(0,V.jsx)(Cue,{field:t,value:n,known:i});let s=t.type===`file`?Nx(n):void 0;if(s&&`url`in s&&s.url){let e=Vx(n,{width:40,height:40});return(0,V.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[e&&(0,V.jsx)($C,{image:e,className:`size-10 shrink-0 rounded border border-border object-cover`}),(0,V.jsx)(`a`,{href:s.url,target:`_blank`,rel:`noreferrer`,className:`truncate font-medium text-primary-text hover:underline`,children:s.name})]})}if(BS(t,o))return(0,V.jsx)(cw,{source:String(n)});let c=ZS(t,n,o);return t.type===`enum`||o.format===`badge`?(0,V.jsx)(M4,{value:n,hints:o,children:c}):(0,V.jsx)(`span`,{className:B(o.format===`code`&&`font-mono text-xs`,(t.type===`decimal`||t.type===`integer`)&&`tabular-nums`,o.multiline&&`whitespace-pre-line break-words`),children:c})},N4=e=>{let{views:t}=q(),n=iw(e.field,t[e.model.name]?.fields[e.field.name]),r=(0,V.jsx)(wue,{...e});return n?(0,V.jsx)(ow,{shown:n,part:`display`,field:e.field,value:e.value,fallback:r}):r},P4=(e,t,n)=>{if(!t)return[];let r=rc(e,t.model.name,n);return r.ok?r.steps:[]},F4=(e,t,n,r,i)=>({queryKey:W.pathValue(n?.model.name??``,n?.key??``,r),enabled:i.length>1,queryFn:async()=>{let r=n.record;for(let n of i.slice(0,-1)){let i=r[n.field.name];if(i==null)return null;let a=n.field.relation.resource;r=(await t.fetchQuery({queryKey:W.record(a,String(i)),queryFn:()=>e.get(a,String(i))})).record}return r[i.at(-1).field.name]??null}}),I4=(e,t,n)=>{let r=t.at(-1);return!e||!r?{state:`missing`}:t.length===1?{state:`ready`,value:e.record[r.field.name],field:r.field,model:r.model}:n.isPending?{state:`loading`}:{state:`ready`,value:n.data??null,field:r.field,model:r.model}},L4=(e,t)=>{let{resources:n}=q(),r=P4(n,e,t);return I4(e,r,vh(F4(G(),Wp(),e,t,r)))},Tue=(e,t)=>{let{resources:n}=q(),r=G(),i=Wp(),a=t.map(t=>P4(n,e,t)),o=gh({queries:t.map((t,n)=>F4(r,i,e,t,a[n]))});return t.map((t,n)=>I4(e,a[n],o[n]))},Eue=(e,t)=>{if(t)return t;let n=e.split(`.`).map(e=>K(e).toLowerCase()).join(` `);return n[0].toUpperCase()+n.slice(1)},Due=({node:e})=>{let{name:t,label:n,format:r}=eT(e),{views:i}=q(),a=L4(Pw(),t);if(a.state===`missing`)return null;let o=a.state===`loading`?(0,V.jsx)(Au,{className:`h-4 w-24`}):(0,V.jsx)(N4,{model:a.model,field:a.field,value:a.value,format:r});if(n===!1)return(0,V.jsx)(`div`,{children:o});let s=n??Eue(t,a.state===`ready`?i[a.model.name]?.fields[a.field.name]?.label:void 0);return(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:s}),(0,V.jsx)(`div`,{className:`mt-0.5 truncate`,children:o})]})},Oue={1:``,2:`md:grid-cols-2`,3:`md:grid-cols-2 xl:grid-cols-3`,4:`sm:grid-cols-2 xl:grid-cols-4`},kue={1:``,2:`grid-cols-2`,3:`grid-cols-2 xl:grid-cols-3`,4:`grid-cols-2 xl:grid-cols-4`},Aue={1:``,2:`md:col-span-2`,3:`md:col-span-2 xl:col-span-3`,4:`sm:col-span-2 md:col-span-2 xl:col-span-4`},jue=e=>typeof e==`object`&&!e.custom&&e.type===`Stat`,Mue=({node:e,children:t})=>{let{columns:n=2}=eT(e),r=e.children,i=r.length>0&&r.every(jue);return(0,V.jsx)(`div`,{className:B(`grid grid-cols-1 gap-4`,i?kue[n]:Oue[n]),children:t.map((e,t)=>{let n=r[t],i=typeof n==`object`?n.props.span:void 0;return(0,V.jsx)(`div`,{className:B(`min-w-0`,i&&Aue[i]),children:e},t)})})},R4=`font-medium text-primary-text hover:underline`,Nue=({node:e})=>{let t=eT(e),n=Pw()?.record,r=e.children.filter(e=>typeof e==`string`).join(``);if(t.to){let e=Do(t.to,n);return(0,V.jsx)(FC,{to:e,className:R4,children:r||us(e)})}let i=t.href??``;return(0,V.jsx)(`a`,{href:i,className:R4,...i.startsWith(`http`)&&{target:`_blank`,rel:`noreferrer`},children:r||i})},z4=(e,t)=>typeof e?.[t]==`number`?e[t]:void 0,B4=e=>`${of(e)} character${e===1?``:`s`}`,Pue=(e,t)=>{let n=z4(t,`min`),r=z4(t,`max`);if(n!==void 0)return`${e} needs at least ${B4(n)}`;if(r!==void 0)return`${e} can have at most ${B4(r)}`},Fue=e=>{let t=z4(e,`min`),n=z4(e,`max`);return t===void 0?n===void 0?`Enter a whole number`:`Enter a whole number of at most ${of(n)}`:`Enter a whole number of at least ${of(t)}`},Iue=e=>{let t=z4(e,`precision`),n=z4(e,`scale`);if(t===void 0||n===void 0)return`Enter a number`;let r=of(10**(t-n));return n===0?`Enter a whole number below ${r}`:`Enter a number with at most ${n} decimal${n===1?``:`s`}, below ${r}`},Lue={text:Pue,integer:(e,t)=>Fue(t),bigint:()=>`Enter a whole number`,decimal:(e,t)=>Iue(t),date:()=>`Enter a date`,timestamp:()=>`Enter a date and time`,country:()=>`Enter a two-letter country code, such as NL`,currency:()=>`Enter a three-letter currency code, such as EUR`,uuid:()=>`Enter a valid ID`,enum:()=>`Choose one of the options`,relation:()=>`Choose a record`,json:()=>`Enter valid JSON`},V4=(e,t,n)=>n.code===`required`?`${t} is required`:n.code!==`invalid-value`||!e?n.message:Lue[e.type]?.(t,n.params)??n.message,H4=e=>{if(!Fs(e))return{};let t={};for(let n of e.errors)n.field&&n.field!==`_record`&&!Object.hasOwn(t,n.field)&&(t[n.field]=n);return t},Rue=e=>{if(e.operation!==void 0)return e.message;let t=new Set(e.errors.flatMap(e=>e.field&&e.field!==`_record`?[e.field]:[])),n=e.errors.flatMap(e=>e.field===`_record`?[e.message]:[]);return t.size===0&&n.length===0?e.message:[...t.size===0?[]:[`Check ${t.size===1?`the marked field`:`${t.size} fields`}.`],...n].join(` `)},U4=e=>{let t=(0,o.useRef)(null);return(0,o.useEffect)(()=>{e!==0&&t.current?.querySelector(`[aria-invalid="true"]`)?.focus()},[e]),t},zue=(e,t,n)=>Object.fromEntries(t.map(t=>{let r=e.fields[t];if(r.type===`file`)return[t,n?.record[t]??null];if(n)return[t,r.type===`boolean`?!!n.record[t]:Gx(n.record[t])];let i=r.default&&`value`in r.default?r.default.value:void 0;return[t,r.type===`boolean`?!!i:Gx(i)]})),Bue=(e,t,n)=>Object.fromEntries(Object.entries(t).flatMap(([t,r])=>{let i=e.fields[t];return rS(r)?r.key===Gx(n.record[t])?[]:[[t,i.type===`integer`?Number(r.key):r.key]]:Qx(i,r,n.record[t])?[[t,Yx(i,r)]]:[]})),Vue=({model:e,record:t,mode:n,label:r,title:i,fields:a,values:s,onClose:c})=>{let{resources:l,views:u}=q(),d=G(),f=Lg(),p=Xw(),m=u[e.name],[h,g]=(0,o.useState)(()=>zue(e,a,t)),[_,v]=(0,o.useState)({}),[y,b]=(0,o.useState)(0),x=U4(y),[S,C]=(0,o.useState)(),[w,T]=(0,o.useState)(!1),E=async()=>{T(!0),C(void 0),await(n===`create`?d.create(e.name,{...sS(e,l,h),...s}):d.update(e.name,t.key,Bue(e,h,t),t.etag??`*`)).then(async()=>{await p(e.name),f.show({state:`success`,title:`${i??r}: saved`}),c()},e=>{let t=H4(e);v(t),Object.keys(t).length>0&&b(e=>e+1),C(e)}),T(!1)};return(0,V.jsx)(Cf,{title:i??r,onClose:c,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:c,children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,loading:w,onClick:()=>void E(),children:n===`create`?`Create`:`Save`})]}),children:(0,V.jsxs)(`form`,{ref:x,className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),E()},children:[S!==void 0&&Object.keys(_).length===0&&(0,V.jsx)(pS,{title:`Not saved`,error:S}),a.map(n=>{let r=e.fields[n],i=h[n],a=r.relation?l[r.relation.resource]:void 0,o=m?.fields[n]?.label??K(n),s=_[n];return(0,V.jsx)(bx,{name:n,label:o,help:m?.fields[n]?.help,error:s&&V4(r,o,s),children:(0,V.jsx)(mw,{field:r,hints:m?.fields[n],value:rS(i)?i.key:i,stored:t?.record[n],relationLabel:rS(i)?i.label:void 0,relationPicker:a?{target:a,view:u[a.name]}:void 0,invalid:!!_[n],resource:e.name,onChange:e=>{v(({[n]:e,...t})=>t),g(t=>({...t,[n]:e}))}})},n)})]})})},Hue=({model:e,recordKey:t,children:n})=>{let r=Jw(e,{key:t});return(0,V.jsx)(V.Fragment,{children:n(r.data??void 0)})},Uue=({node:e})=>{let t=eT(e),n=Pw(),{resources:r}=q(),i=r[t.resource??n?.model.name??``],a=f_(i?.name??``),[s,c]=(0,o.useState)(!1);if(!i||!(t.mode===`create`?Fw(a,`create`):Fw(a,`update`)&&n?.permissions?.update!==!1))return null;let l=e=>(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{size:`sm`,variant:t.variant??`secondary`,disabled:t.mode===`edit`&&!e,onClick:()=>c(!0),children:t.label}),s&&(0,V.jsx)(Vue,{...t,model:i,record:t.mode===`edit`?e:void 0,onClose:()=>c(!1)})]});return t.mode===`edit`&&t.recordKey!==void 0?(0,V.jsx)(Hue,{model:i,recordKey:t.recordKey,children:l}):l(t.mode===`edit`?n:void 0)},Wue=({node:e,children:t,slots:n})=>{let{title:r,description:i}=eT(e);return(0,V.jsx)(`div`,{className:`flex-1`,children:(0,V.jsxs)(`div`,{className:`mx-auto flex max-w-[1200px] flex-col gap-6 px-4 pb-16 pt-6 md:px-10 md:py-8`,children:[(0,V.jsx)(Fd,{title:r,subtitle:i,actions:n.actions}),t]})})},W4=(e,t)=>{let n=Pw(),r=L4(typeof e==`string`?n:void 0,typeof e==`string`?e:``);return typeof e==`number`?e:e===void 0?t:r.state===`ready`?Number(r.value):r.state===`loading`?void 0:NaN},Gue=({node:e})=>{let{value:t,max:n,label:r}=eT(e),i=W4(t,0),a=W4(n,100);if(i===void 0||a===void 0)return(0,V.jsx)(Au,{className:`h-6 w-full`});if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=a>0?Math.min(1,Math.max(0,i/a)):0;return(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs`,children:[(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:r}),(0,V.jsxs)(`span`,{className:`tabular-nums`,children:[i.toLocaleString(`en-IE`),` / `,a.toLocaleString(`en-IE`)]})]}),(0,V.jsx)(`div`,{role:`progressbar`,"aria-label":r,"aria-valuenow":i,"aria-valuemin":0,"aria-valuemax":a,className:`mt-1.5 h-2 overflow-hidden rounded-full bg-muted`,children:(0,V.jsx)(`div`,{className:o>=.9?`h-full rounded-full bg-warning`:`h-full rounded-full bg-primary`,style:{width:`${o*100}%`}})})]})},Kue=({model:e,filter:t,sort:n,recordKey:r,title:i,description:a,empty:o,actions:s,children:c})=>{let l=Jw(e,{filter:t,sort:n,key:r}),u=e=>l.data?(0,V.jsx)(Nw,{value:l.data,children:e}):void 0,d=l.isPending?(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsx)(Au,{className:`h-4 w-1/2`}),(0,V.jsx)(Au,{className:`h-4 w-1/3`})]}):l.error?(0,V.jsx)(pS,{title:`Could not load`,error:l.error}):l.data?u((0,V.jsx)(`div`,{className:`flex flex-col gap-3`,children:c})):(0,V.jsx)(rT,{children:o??`Nothing here yet.`});return(0,V.jsx)(nT,{title:i,description:a,actions:s?u(s):void 0,className:`h-full`,children:d})},que=({node:e,children:t,slots:n})=>{let{resource:r,filter:i,sort:a,recordKey:o,title:s,description:c,empty:l}=eT(e),u=q().resources[r];return u?(0,V.jsx)(Kue,{model:u,filter:i,sort:a,recordKey:o,title:s,description:c,empty:l,actions:n.actions,children:t}):null};function Jue(e){return Yue(e)||typeof e==`function`||Xue(e)}function Yue(e){return typeof e==`function`&&(()=>{let t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function Xue(e){return typeof e==`object`&&typeof e.$$typeof==`symbol`&&[`react.memo`,`react.forward_ref`].includes(e.$$typeof.description)}function G4(e,t){return e==null?null:Jue(e)?o.createElement(e,t):e}function Zue(e){if(`cell`in e&&e.cell){let t=e.cell,n=t.column.columnDef,r=t,i=n;return r.getIsAggregated?.()?G4(i.aggregatedCell??n.cell,t.getContext()):r.getIsPlaceholder?.()?null:G4(n.cell,t.getContext())}return`header`in e&&e.header?G4(e.header.column.columnDef.header,e.header.getContext()):`footer`in e&&e.footer?G4(e.footer.column.columnDef.footer,e.footer.getContext()):null}function Que({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(1)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(1)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function $ue(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var K4=[],q4=0,{link:J4,unlink:ede,propagate:tde,checkDirty:Y4,shallowPropagate:X4}=Que({update(e){return e._update()},notify(e){K4[Q4++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,t3(e))}}),Z4=0,Q4=0,$4,e3=0;function nde(e){try{++e3,e()}finally{--e3||n3()}}function t3(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=ede(n,e)}function n3(){if(!(e3>0)){for(;Z4<Q4;){let e=K4[Z4];K4[Z4++]=void 0,e.notify()}Z4=0,Q4=0}}function rde(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:+!n,get(){return $4!==void 0&&J4(i,$4,q4),i._snapshot},subscribe(e){let t=$ue(e),n={current:!1},r=ide(()=>{i.get(),n.current?($4=void 0,t.next?.(i._snapshot)):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=$4,o=t?.compare??Object.is;if(n)$4=i,++q4,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=5);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{$4=a,n&&(i.flags&=-5),t3(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&Y4(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&X4(e)}}else e&32&&(i.flags=e&-33);return $4!==void 0&&J4(i,$4,q4),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(tde(e),X4(e),n3())}},i}function ide(e){let t=()=>{let t=$4;$4=n,++q4,n.depsTail=void 0,n.flags=6;try{return e()}finally{$4=t,n.flags&=-5,t3(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){let e=this.flags;e&16||e&32&&Y4(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,t3(this)}};return t(),n}function r3(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();let n=i3(e);if(n.length!==i3(t).length)return!1;for(let r=0;r<n.length;r++)if(!Object.prototype.hasOwnProperty.call(t,n[r])||!Object.is(e[n[r]],t[n[r]]))return!1;return!0}function i3(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function ade(e,t){return e===t}function a3(e,t=e=>e,n){let r=n?.compare??ade,i=(0,o.useCallback)(t=>{let{unsubscribe:n}=e.subscribe(t);return n},[e]),a=(0,o.useCallback)(()=>e.get(),[e]);return(0,EO.useSyncExternalStoreWithSelector)(i,a,a,t,r)}function ode(e){let t=a3(e.source,e.selector,{compare:r3});return typeof e.children==`function`?e.children(t):e.children}function sde(e){let t=e;return Object.defineProperty(e,"state",{get(){return e.get()}}),`set`in e&&(t.setState=e.set.bind(e)),t}function cde(e){let{createAtom:t,batch:n}=e,r=t(0);return{createOptionsStore:!1,wrapExternalAtoms:!1,addSubscription:()=>{throw Error(`Feature not supported in current reactivity implementation`)},unmount:()=>{throw Error(`Feature not supported in current reactivity implementation`)},schedule:e.schedule??(e=>queueMicrotask(e)),batch:n,untrack:e=>e(),createReadonlyAtom:(e,n)=>{let i=n?.compare??Object.is,a=!1,o,s=()=>{let t=e();return(!a||!i(o,t))&&(o=t,a=!0),o},c=t(()=>(r.get(),s()),{compare:i});return{get:s,subscribe:c.subscribe.bind(c)}},createWritableAtom:(e,n)=>t(e,{compare:n?.compare}),commit:()=>{r.set(e=>e+1)}}}function lde(e,t=Object.is){let n=!1,r;return{get:e.get,markCommitted:e=>{r=e,n=!0},subscribe:i=>e.subscribe(e=>{(!n||!t(r,e))&&i(e)})}}function ude(){return cde({createAtom:rde,batch:nde})}function o3(e,t){return typeof e==`function`?e(t):e}function s3(e){if(Array.isArray(e))return e.map(s3);if(e&&typeof e==`object`){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let n=t===null?c3():{},r=Object.keys(e);for(let t=0;t<r.length;t++){let i=r[t];Object.defineProperty(n,i,{configurable:!0,enumerable:!0,value:s3(e[i]),writable:!0})}return n}return e}function dde(e,t){let n=Object.keys(t),r=e;for(let e=0;e<n.length;e++){let i=n[e];!i.startsWith(`_memo_`)&&i!==`_cellsCache`&&(r[i]=t[i])}return e}function c3(){return Object.create(null)}function l3(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function u3(e,t){return n=>{(t.options.atoms?.[e]??t.baseAtoms[e]).set(e=>o3(n,e))}}function d3(e){if(typeof e!=`object`||!e)return!1;if(Array.isArray(e))return!0;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function f3(e){return Reflect.ownKeys(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}var fde=3;function pde(e,t){return p3(e,t,fde)}function p3(e,t,n){if(Object.is(e,t))return!0;if(n<=0||!d3(e)||!d3(t)||(Array.isArray(e)||Array.isArray(t))&&(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length))return!1;let r=f3(e),i=f3(t);if(r.length!==i.length)return!1;let a=e,o=t;for(let e=0;e<r.length;e++){let i=r[e];if(!Object.prototype.propertyIsEnumerable.call(t,i)||!p3(a[i],o[i],n-1))return!1}return!0}function m3(e,t,n,r=pde){let i=`on${t.charAt(0).toUpperCase()}${t.slice(1)}Change`,a=e.options[i];a&&a(e=>{let t=o3(n,e);return r(e,t)?e:t})}function mde(e){return e instanceof Function}function hde(e,t){let n=[],r=e=>{e.forEach(e=>{n.push(e);let i=t(e);i.length&&r(i)})};return r(e),n}var gde=({fn:e,memoDeps:t,onAfterCompare:n,onAfterUpdate:r,onBeforeCompare:i,onBeforeUpdate:a})=>{let o=[],s;return c=>{i?.();let l=t?.(c),u=!l||l.length!==o?.length;if(!u&&l){for(let e=0;e<l.length;e++)if(l[e]!==o[e]){u=!0;break}}return n?.(u),u?(o=l,a?.(),s=e(...l??[]),r?.(s),s):s}};function _de(e){let t=!1;return()=>{if(!t){t=!0;return}e()}}function h3({feature:e,fnName:t,objectId:n,onAfterUpdate:r,table:i,...a}){let o=()=>{if(!r)return;let{schedule:e,untrack:t}=i._reactivity;e(()=>t(()=>r()))},s={onAfterUpdate:()=>{o()}};return gde({...a,...s})}function g3(e,t=`_`){let[n,r]=e.split(t);return{fnKey:r,fnName:`${n}.${r}`,parentName:n}}function _3(e,t,n){for(let[r,{fn:i,memoDeps:a}]of Object.entries(n)){let{fnKey:n,fnName:o}=g3(r);t[n]=a?h3({memoDeps:a,fn:i,fnName:o,table:t,feature:e}):i}}function v3(e,t,n,r){for(let[i,{fn:a,memoDeps:o}]of Object.entries(r)){let{fnKey:r,fnName:s}=g3(i);if(o){let i=`_memo_${r}`;t[r]=function(...t){if(!this[i]){let t=this;this[i]=h3({memoDeps:e=>o(t,e),fn:(...e)=>a(t,...e),fnName:s,objectId:t.id,table:n,feature:e})}return this[i](...t)}}else t[r]=function(...e){return a(this,...e)}}}function y3(e,t,n,...r){return e[t]?.(...r)??n(e,...r)}function vde(e){return e.row.getValue(e.column.id)}function yde(e){return e.getValue()??e.table.options.renderFallbackValue}function bde(e){return{table:e.table,column:e.column,row:e.row,cell:e,getValue:()=>e.getValue(),renderValue:()=>e.renderValue()}}var xde={assignCellPrototype:(e,t)=>{v3(`coreCellsFeature`,e,t,{cell_getValue:{fn:e=>vde(e)},cell_renderValue:{fn:e=>yde(e)},cell_getContext:{fn:e=>bde(e),memoDeps:e=>[e]}})}};function Sde(e){if(!e._headerPrototype){e._headerPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignHeaderPrototype?.(e._headerPrototype,e)}return e._headerPrototype}function b3(e,t,n){let r=Sde(e),i=Object.create(r);i.colSpan=0,i.column=t,i.depth=n.depth,i.headerGroup=null,i.id=n.id??t.id,i.index=n.index,i.isPlaceholder=!!n.isPlaceholder,i.placeholderId=n.placeholderId,i.rowSpan=0,i.subHeaders=[];let a=e._headerInstanceInitFns;for(let e=0;e<a.length;e++)a[e](i);return i}function Cde(){return{start:[],end:[]}}function x3(e){let t=e.table.atoms.columnVisibility?.get();if(!t)return!0;let n=e.columns;return n.length?n.some(e=>y3(e,`getIsVisible`,x3)):(l3(t,e.id)?t[e.id]:void 0)??!0}function wde(e){return e.getAllLeafColumns().filter(e=>y3(e,`getIsVisible`,x3))}function S3(e,t=1){let n=t;for(let r=0;r<e.length;r++){let i=e[r];y3(i,`getIsVisible`,x3)&&i.columns.length&&(n=Math.max(n,S3(i.columns,t+1)))}return n}function Tde(e,t){return e?`${e}_${t}`:String(t)}function Ede(e,t,n,r){let i=e??``;return t&&(i=i?`${i}_${t}`:String(t)),n&&(i=i?`${i}_${n}`:n),r&&(i=i?`${i}_${r}`:r),i}function Dde(e,t){let n=0;for(let r=0;r<e.length;r++)e[r].column===t&&n++;return n}function C3(e,t,n,r,i,a){let o={depth:t,id:Tde(r,t),headers:[]},s=[];for(let i=0;i<e.length;i++){if(!(i in e))continue;let a=e[i],c=s[s.length-1],l=a.column.depth===o.depth,u,d=!1;if(l&&a.column.parent?u=a.column.parent:(u=a.column,d=!0),c&&c.column===u)c.subHeaders.push(a);else{let e=b3(n,u,{id:Ede(r,t,u.id,a.id),isPlaceholder:d,placeholderId:d?String(Dde(s,u)):void 0,depth:t,index:s.length});e.subHeaders.push(a),s.push(e)}o.headers.push(a),a.headerGroup=o}for(let e=0;e<a.length;e++)a[e](o);i.push(o),t>0&&C3(s,t-1,n,r,i,a)}function w3(e){for(let t=0;t<e.length;t++){let n=e[t];if(!y3(n.column,`getIsVisible`,x3))continue;let r=0;if(n.subHeaders.length){w3(n.subHeaders);for(let e=0;e<n.subHeaders.length;e++){let t=n.subHeaders[e];y3(t.column,`getIsVisible`,x3)&&(r+=t.colSpan)}}else r=1;if(n.colSpan=r,n.isPlaceholder&&n.subHeaders.length===1&&n.subHeaders[0].column===n.column){let e=1,t=n.subHeaders[0];for(;t;)t.rowSpan=0,e++,t=t.subHeaders.length===1&&t.subHeaders[0].column===n.column?t.subHeaders[0]:void 0;n.rowSpan=e}else n.rowSpan=1}}function T3(e,t,n,r){let i=S3(e),a=[],o=n._headerGroupInstanceInitFns,s=Array(t.length);for(let e=0;e<t.length;e++)e in t&&(s[e]=b3(n,t[e],{depth:i,index:e}));return C3(s,i-1,n,r,a,o),a.reverse(),w3(a[0]?.headers??[]),a}function Ode(e){if(!e._columnPrototype){e._columnPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignColumnPrototype?.(e._columnPrototype,e)}return e._columnPrototype}function kde(e,t,n,r){let i={...e.getDefaultColumnDef(),...t},a=i.accessorKey,o=a===void 0?void 0:String(a),s=i.id??o?.replaceAll(`.`,`_`)??(typeof i.header==`string`?i.header:void 0),c;if(i.accessorFn)c=i.accessorFn;else if(a!==void 0){if(typeof a==`string`&&a.includes(`.`)){let e=a.split(`.`);c=t=>{let n=t;for(let t=0;t<e.length;t++){let r=e[t];n=n?.[r]}return n}}else c=e=>e[i.accessorKey]}if(!s)throw Error();let l=Ode(e),u=Object.create(l);u.accessorFn=c,u.columnDef=i,u.columns=[],u.depth=n,u.id=`${String(s)}`,u.parent=r;let d=e._columnInstanceInitFns;for(let e=0;e<d.length;e++)d[e](u);return u}function E3(e){let t=e.atoms.columnOrder?.get();return n=>{let r=[];if(!t?.length)r=n;else{let e=new Map;for(let t=0;t<n.length;t++){let r=n[t];e.set(r.id,r)}for(let n=0;n<t.length;n++){let i=t[n],a=e.get(i);a&&(r.push(a),e.delete(i))}for(let t=0;t<n.length;t++){let i=n[t];e.has(i.id)&&r.push(i)}}return Ade(e,r)}}function Ade(e,t){let n=e.atoms.grouping?.get()??[],{groupedColumnMode:r}=e.options;if(!n.length||!r)return t;let i=t.filter(e=>!n.includes(e.id));if(r===`remove`)return i;let a=new Map;for(let e=0;e<t.length;e++){let n=t[e];a.set(n.id,n)}let o=[];for(let e=0;e<n.length;e++){let t=a.get(n[e]);t&&o.push(t)}return[...o,...i]}function jde(e){return[e,...e.columns.flatMap(e=>e.getFlatColumns())]}function Mde(e){if(e.columns.length){let t=e.columns.flatMap(e=>e.getLeafColumns());return y3(e.table,`getOrderColumns`,E3)(t)}return[e]}function Nde(e){return{header:e=>{let t=e.header.column.columnDef;return t.accessorKey?t.accessorKey:t.accessorFn?t.id:null},cell:e=>e.renderValue()?.toString?.()??null,...Object.values(e._features).reduce((e,t)=>Object.assign(e,t.getDefaultColumnDef?.()),{}),...e.options.defaultColumn}}function D3(e,t,n,r=0){let i=Array(t.length);for(let a=0;a<t.length;a++){if(!(a in t))continue;let o=t[a],s=kde(e,o,r,n),c=o;s.columns=c.columns?D3(e,c.columns,s,r+1):[],i[a]=s}return i}function Pde(e){return D3(e,e.options.columns)}function Fde(e){return e.getAllColumns().flatMap(e=>e.getFlatColumns())}function Ide(e){let t=c3(),n=e.getAllFlatColumns();for(let e=0;e<n.length;e++){let r=n[e];t[r.id]=r}return t}function Lde(e){let t=e.getAllColumns().flatMap(e=>e.getLeafColumns());return y3(e,`getOrderColumns`,E3)(t)}function Rde(e){let t=c3(),n=e.getAllLeafColumns();for(let e=0;e<n.length;e++){let r=n[e];t[r.id]=r}return t}function zde(e,t){return e.getAllFlatColumnsById()[t]}var Bde={assignColumnPrototype:(e,t)=>{v3(`coreColumnsFeature`,e,t,{column_getFlatColumns:{fn:e=>jde(e),memoDeps:e=>[e.table.options.columns]},column_getLeafColumns:{fn:e=>Mde(e),memoDeps:e=>[e.table.atoms.columnOrder?.get(),e.table.atoms.grouping?.get(),e.table.options.columns,e.table.options.groupedColumnMode]}})},constructTableAPIs:e=>{_3(`coreColumnsFeature`,e,{table_getDefaultColumnDef:{fn:()=>Nde(e),memoDeps:()=>[e.options.defaultColumn]},table_getAllColumns:{fn:()=>Pde(e),memoDeps:()=>[e.options.columns]},table_getAllFlatColumns:{fn:()=>Fde(e),memoDeps:()=>[e.options.columns]},table_getAllFlatColumnsById:{fn:()=>Ide(e),memoDeps:()=>[e.options.columns]},table_getAllLeafColumns:{fn:()=>Lde(e),memoDeps:()=>[e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.options.columns,e.options.groupedColumnMode]},table_getAllLeafColumnsById:{fn:()=>Rde(e),memoDeps:()=>[e.getAllLeafColumns()]},table_getColumn:{fn:t=>zde(e,t)}})}};function O3(e,t){for(let n=0;n<e.subHeaders.length;n++)O3(e.subHeaders[n],t);t.push(e)}function Vde(e){let t=[];return O3(e,t),t}function Hde(e){return{column:e.column,header:e,table:e.column.table}}function Ude(e){let{start:t,end:n}=e.atoms.columnPinning?.get()??Cde(),r=e.getAllColumns(),i=y3(e,`getVisibleLeafColumns`,wde);if(!t.length&&!n.length)return T3(r,i,e);let a=e.getAllLeafColumnsById(),o=[];for(let e=0;e<t.length;e++){let n=a[t[e]];n&&y3(n,`getIsVisible`,x3)&&o.push(n)}let s=[];for(let e=0;e<n.length;e++){let t=a[n[e]];t&&y3(t,`getIsVisible`,x3)&&s.push(t)}let c=i.filter(e=>!t.includes(e.id)&&!n.includes(e.id));return T3(r,[...o,...c,...s],e)}function Wde(e){return[...e.getHeaderGroups()].reverse()}function Gde(e){let t=e.getHeaderGroups(),n=[];for(let e=0;e<t.length;e++){let r=t[e].headers;for(let e=0;e<r.length;e++)n.push(r[e])}return n}function Kde(e){let t=e.getHeaderGroups()[0]?.headers??[],n=[];for(let e=0;e<t.length;e++){let r=t[e].getLeafHeaders();for(let e=0;e<r.length;e++)n.push(r[e])}return n}var qde={assignHeaderPrototype:(e,t)=>{v3(`coreHeadersFeature`,e,t,{header_getLeafHeaders:{fn:e=>Vde(e),memoDeps:e=>[e.column.table.options.columns]},header_getContext:{fn:e=>Hde(e),memoDeps:e=>[e.column.table.options.columns]}})},constructTableAPIs:e=>{_3(`coreHeadersFeature`,e,{table_getHeaderGroups:{fn:()=>Ude(e),memoDeps:()=>[e.options.columns,e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.atoms.columnPinning?.get(),e.atoms.columnVisibility?.get(),e.options.groupedColumnMode]},table_getFooterGroups:{fn:()=>Wde(e),memoDeps:()=>[e.getHeaderGroups()]},table_getFlatHeaders:{fn:()=>Gde(e),memoDeps:()=>[e.getHeaderGroups()]},table_getLeafHeaders:{fn:()=>Kde(e),memoDeps:()=>[e.getHeaderGroups()]}})}};function Jde(e){if(!e._rowPrototype){e._rowPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignRowPrototype?.(e._rowPrototype,e)}return e._rowPrototype}var Yde=(e,t,n,r,i,a,o)=>{let s=Jde(e),c=Object.create(s);c._displayIndexCache=-1,c._uniqueValuesCache=c3(),c._valuesCache=c3(),c.depth=i,c.id=t,c.index=r,c.original=n,c.parentId=o,c.subRows=a??[];let l=e._rowInstanceInitFns;for(let e=0;e<l.length;e++)l[e](c);return c},Xde=/([0-9]+)/gm;function k3(e){let t=Object.assign((e,n,r)=>{let i=e.getValue(r),a=n.getValue(r),o=t.resolveDataValue;return o&&(i=o(i),a=o(a)),t.sort(i,a,e,n,r)},e);return t}k3({resolveDataValue:e=>M3(e).toLowerCase(),sort:(e,t)=>N3(e,t)}),k3({resolveDataValue:e=>M3(e),sort:(e,t)=>N3(e,t)}),k3({resolveDataValue:e=>M3(e).toLowerCase(),sort:(e,t)=>j3(e,t)}),k3({resolveDataValue:e=>M3(e),sort:(e,t)=>j3(e,t)}),k3({resolveDataValue:e=>Zde(e),sort:(e,t)=>e>t?1:e<t?-1:0});var A3=k3({sort:(e,t)=>j3(e,t)});function j3(e,t){return e===t?0:e>t?1:-1}function Zde(e){return e instanceof Date?e.getTime():e}function M3(e){return typeof e==`number`?isNaN(e)||e===1/0||e===-1/0?``:String(e):typeof e==`string`?e:``}function N3(e,t){let n=0,r=0,i=e.length,a=t.length;for(;n<i&&r<a;){let i=P3(e.charCodeAt(n)),a=P3(t.charCodeAt(r)),o=F3(e,n,i),s=F3(t,r,a);if(!i&&!a){let i=Qde(e,n,o,t,r,s);if(i)return i;n=o,r=s;continue}if(i!==a)return i?1:-1;let c=$de(e,n,o,t,r,s);if(c)return c;n=o,r=s}return L3(e,n)-L3(t,r)}function P3(e){return e>=48&&e<=57}function F3(e,t,n){let r=t+1;for(;r<e.length&&P3(e.charCodeAt(r))===n;)r++;return r}function Qde(e,t,n,r,i,a){let o=n-t,s=a-i,c=o<s?o:s;for(let n=0;n<c;n++){let a=e.charCodeAt(t+n),o=r.charCodeAt(i+n);if(a>o)return 1;if(o>a)return-1}return o>s?1:s>o?-1:0}function $de(e,t,n,r,i,a){let o=t;for(;o<n&&e.charCodeAt(o)===48;)o++;let s=i;for(;s<a&&r.charCodeAt(s)===48;)s++;let c=n-o,l=a-s;if(c===0&&l===0)return 0;if(c<=15&&l<=15){let t=I3(e,o,n),i=I3(r,s,a);return t>i?1:i>t?-1:0}let u=parseInt(e.slice(t,n),10),d=parseInt(r.slice(i,a),10);return u>d?1:d>u?-1:0}function I3(e,t,n){let r=0;for(let i=t;i<n;i++)r=r*10+e.charCodeAt(i)-48;return r}function L3(e,t){let n=0,r=t;for(;r<e.length;)n++,r=F3(e,r,P3(e.charCodeAt(r)));return n}function R3(){return[]}function efe(e,t){m3(e,`cellSelection`,t?R3():s3(e.initialState.cellSelection)??R3())}function tfe(e){e.atoms.cellSelection&&(e.options.autoResetAll??e.options.autoResetCellSelection??!0)&&e._reactivity.schedule(()=>efe(e))}function nfe(e){e.atoms.expanded&&(e.options.autoResetAll??e.options.autoResetExpanded??!e.options.manualExpanding)&&e._reactivity.schedule(()=>rfe(e))}function rfe(e,t){let n=e.initialState.expanded;m3(e,`expanded`,t?c3():n===!0||Object.assign(c3(),s3(n??{})))}var z3=0;function ife(e){if(e.options.autoResetAll??e.options.autoResetPageIndex??!e.options.manualPagination){if((e.atoms.pagination?.get()?.pageIndex??z3)===z3)return;sfe(e,!0)}}function afe(e,t){m3(e,`pagination`,t)}function ofe(e,t){afe(e,n=>{let r=o3(t,n.pageIndex),i=e.options.pageCount===void 0||e.options.pageCount===-1?2**53-1:e.options.pageCount-1;return r=Math.max(0,Math.min(r,i)),{...n,pageIndex:r}})}function sfe(e,t){ofe(e,t?z3:e.initialState.pagination?.pageIndex??z3)}function cfe(){return[]}function B3(e,t){m3(e,`sorting`,t)}function V3(e,t){B3(e,t?[]:s3(e.initialState.sorting??[]))}function lfe(e){e.atoms.sorting&&(e.options.autoResetAll??e.options.autoResetSorting??!1)&&V3(e)}function H3(e){let t=e.table._rowModelFns.sortFns,n=e.table.getFilteredRowModel().flatRows.slice(0,10),r,i=!1;for(let t=0;t<n.length;t++){let a=n[t].getValue(e.id);if(Object.prototype.toString.call(a)===`[object Date]`){r=`datetime`;break}if(typeof a==`string`&&(i=!0,a.split(Xde).length>1)){r=`alphanumeric`;break}}if(!r&&i&&(r=`text`),r){let e=t?.[r];if(e||r===`alphanumeric`&&(e=t?.text),e)return e}return A3}function U3(e){let t=e.table.getFilteredRowModel().flatRows.slice(0,10);for(let n=0;n<t.length;n++){let r=t[n].getValue(e.id);if(r!=null)return typeof r==`string`?`asc`:`desc`}return`desc`}function ufe(e){let t=e.table._rowModelFns.sortFns;return mde(e.columnDef.sortFn)?e.columnDef.sortFn:e.columnDef.sortFn===`auto`?H3(e):t?.[e.columnDef.sortFn]??A3}function W3(e,t,n){let r=K3(e,n&&J3(e)),i=t!==void 0;B3(e.table,a=>{let o=a.findIndex(t=>t.id===e.id),s=o===-1?void 0:a[o],c=[],l,u=i?t:r===`desc`,d=!!(a.length&&J3(e)&&n);return l=d?s?`toggle`:`add`:s?`toggle`:`replace`,l===`toggle`&&(i||r||(l=`remove`)),l===`add`?(c=[...a,{id:e.id,desc:u}],c.splice(0,c.length-(e.table.options.maxMultiSortColCount??2**53-1))):c=l===`toggle`?d?a.map(t=>t.id===e.id?{...t,desc:u}:t):[{id:e.id,desc:u}]:l===`remove`?d?a.filter(t=>t.id!==e.id):[]:[{id:e.id,desc:u}],c})}function G3(e){return e.columnDef.sortDescFirst??e.table.options.sortDescFirst??U3(e)===`desc`?`desc`:`asc`}function K3(e,t){let n=G3(e),r=Y3(e);return r?r!==n&&(e.table.options.enableSortingRemoval??!0)&&(!t||(e.table.options.enableMultiRemove??!0))?!1:r===`desc`?`asc`:`desc`:n}function q3(e){return(e.columnDef.enableSorting??!0)&&(e.table.options.enableSorting??!0)&&!!e.accessorFn}function J3(e){return e.columnDef.enableMultiSort??e.table.options.enableMultiSort??!!e.accessorFn}function Y3(e){let t=e.table.atoms.sorting?.get()?.find(t=>t.id===e.id);return t?t.desc?`desc`:`asc`:!1}function dfe(e){return e.table.atoms.sorting?.get()?.findIndex(t=>t.id===e.id)??-1}function ffe(e){B3(e.table,t=>t.length?t.filter(t=>t.id!==e.id):[])}function pfe(e){let t=q3(e);return n=>{t&&W3(e,void 0,J3(e)?e.table.options.isMultiSortEvent?.(n):!1)}}function mfe(){return e=>h3({feature:`coreRowModelsFeature`,table:e,fnName:`table.getCoreRowModel`,memoDeps:()=>[e.options.data],fn:()=>hfe(e,e.options.data),onAfterUpdate:_de(()=>{nfe(e),ife(e),lfe(e),tfe(e)})})}function X3(e,t,n,r=0,i){let a=[];for(let o=0;o<n.length;o++){let s=n[o],c=Yde(e,e.getRowId(s,o,i),s,o,r,void 0,i?.id);t.flatRows.push(c),t.rowsById[c.id]=c,a.push(c),e.options.getSubRows&&(c.originalSubRows=e.options.getSubRows(s,o),c.originalSubRows?.length&&(c.subRows=X3(e,t,c.originalSubRows,r+1,c)))}return a}function hfe(e,t){let n={rows:[],flatRows:[],rowsById:c3()};return n.rows=X3(e,n,t),n}function gfe(e){return e._rowModels.coreRowModel||(e._rowModels.coreRowModel=e.options.features.coreRowModel?.(e)??mfe()(e)),e._rowModels.coreRowModel()}function _fe(e){return e.getCoreRowModel()}function vfe(e){return e._rowModels.filteredRowModel||(e._rowModels.filteredRowModel=e.options.features.filteredRowModel?.(e)),e.options.manualFiltering||!e._rowModels.filteredRowModel?e.getPreFilteredRowModel():e._rowModels.filteredRowModel()}function yfe(e){return e.getFilteredRowModel()}function bfe(e){return e._rowModels.groupedRowModel||(e._rowModels.groupedRowModel=e.options.features.groupedRowModel?.(e)),e.options.manualGrouping||!e._rowModels.groupedRowModel?e.getPreGroupedRowModel():e._rowModels.groupedRowModel()}function xfe(e){return e.getGroupedRowModel()}function Sfe(e){return e._rowModels.sortedRowModel||(e._rowModels.sortedRowModel=e.options.features.sortedRowModel?.(e)),e.options.manualSorting||!e._rowModels.sortedRowModel?e.getPreSortedRowModel():e._rowModels.sortedRowModel()}function Cfe(e){return e.getSortedRowModel()}function wfe(e){return e._rowModels.expandedRowModel||(e._rowModels.expandedRowModel=e.options.features.expandedRowModel?.(e)),e.options.manualExpanding||!e._rowModels.expandedRowModel?e.getPreExpandedRowModel():e._rowModels.expandedRowModel()}function Tfe(e){return e.getExpandedRowModel()}function Efe(e){return e._rowModels.paginatedRowModel||(e._rowModels.paginatedRowModel=e.options.features.paginatedRowModel?.(e)),e.options.manualPagination||!e._rowModels.paginatedRowModel?e.getPrePaginatedRowModel():e._rowModels.paginatedRowModel()}function Dfe(e){return e.getPaginatedRowModel()}var Ofe={constructTableAPIs:e=>{_3(`coreRowModelsFeature`,e,{table_getCoreRowModel:{fn:()=>gfe(e)},table_getPreFilteredRowModel:{fn:()=>_fe(e)},table_getFilteredRowModel:{fn:()=>vfe(e)},table_getPreGroupedRowModel:{fn:()=>yfe(e)},table_getGroupedRowModel:{fn:()=>bfe(e)},table_getPreSortedRowModel:{fn:()=>xfe(e)},table_getSortedRowModel:{fn:()=>Sfe(e)},table_getPreExpandedRowModel:{fn:()=>Cfe(e)},table_getExpandedRowModel:{fn:()=>wfe(e)},table_getPrePaginatedRowModel:{fn:()=>Tfe(e)},table_getPaginatedRowModel:{fn:()=>Efe(e)},table_getRowModel:{fn:()=>Dfe(e)}})}};function kfe(e){if(!e._cellPrototype){e._cellPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignCellPrototype?.(e._cellPrototype,e)}return e._cellPrototype}function Afe(e,t,n){let r=kfe(n),i=Object.create(r);i.column=e,i.id=`${t.id}_${e.id}`,i.row=t;let a=n._cellInstanceInitFns;for(let e=0;e<a.length;e++)a[e](i);return i}function jfe(e){let t=e.table.getRowsInDisplayOrder(),n=e._displayIndexCache;return t[n]===e?n:-1}function Mfe(e){let t=e.getPrePaginatedRowModel().rows;if(e.options.paginateExpandedRows===!1){let e=[],n=t=>{t._displayIndexCache=e.length,e.push(t),t.subRows.length&&t.getIsExpanded?.()&&t.subRows.forEach(n)};return t.forEach(n),e}for(let e=0;e<t.length;e++)t[e]._displayIndexCache=e;return t}function Nfe(e,t){if(l3(e._valuesCache,t))return e._valuesCache[t];let n=e.table.getColumn(t);if(n?.accessorFn)return e._valuesCache[t]=n.accessorFn(e.original,e.index),e._valuesCache[t]}function Pfe(e,t){if(l3(e._uniqueValuesCache,t))return e._uniqueValuesCache[t];let n=e.table.getColumn(t);if(n?.accessorFn)return n.columnDef.getUniqueValues?(e._uniqueValuesCache[t]=n.columnDef.getUniqueValues(e.original,e.index),e._uniqueValuesCache[t]):(e._uniqueValuesCache[t]=[e.getValue(t)],e._uniqueValuesCache[t])}function Ffe(e,t){return e.getValue(t)??e.table.options.renderFallbackValue}function Ife(e){return hde(e.subRows,e=>e.subRows)}function Lfe(e){let t=e.getCoreRowModel().flatRows,n=0;for(let e=0;e<t.length;e++)n=Math.max(n,t[e].depth);return n}function Rfe(e){if(e.parentId)return e.table.getCoreRowModel().rowsById[e.parentId]??e.table.getRow(e.parentId,!0)}function zfe(e){let t=[],n=e;for(;;){let e=n.getParentRow();if(!e)break;t.push(e),n=e}return t.reverse()}function Bfe(e){let t=e.table.getAllLeafColumns(),n=e._cellsCache;n||=e._cellsCache=new WeakMap;let r=Array(t.length);for(let i=0;i<t.length;i++){let a=t[i],o=n.get(a);o||(o=Afe(a,e,e.table),n.set(a,o)),r[i]=o}return r}function Vfe(e){let t=c3(),n=e.getAllCells();for(let e=0;e<n.length;e++){let r=n[e];t[r.column.id]=r}return t}function Hfe(e,t,n,r){return t.options.getRowId?.(e,n,r)??(r?`${r.id}.${n}`:String(n))}function Ufe(e,t,n){let r=(n?e.getPrePaginatedRowModel():e.getRowModel()).rowsById[t];if(!r&&(r=e.getCoreRowModel().rowsById[t],!r))throw Error();return r}var Wfe={assignRowPrototype:(e,t)=>{v3(`coreRowsFeature`,e,t,{row_getDisplayIndex:{fn:e=>jfe(e)},row_getAllCellsByColumnId:{fn:e=>Vfe(e),memoDeps:e=>[e.getAllCells()]},row_getAllCells:{fn:e=>Bfe(e),memoDeps:e=>[e.table.getAllLeafColumns()]},row_getLeafRows:{fn:e=>Ife(e),memoDeps:e=>[e.subRows]},row_getParentRow:{fn:e=>Rfe(e)},row_getParentRows:{fn:e=>zfe(e)},row_getUniqueValues:{fn:(e,t)=>Pfe(e,t)},row_getValue:{fn:(e,t)=>Nfe(e,t)},row_renderValue:{fn:(e,t)=>Ffe(e,t)}})},constructTableAPIs:e=>{_3(`coreRowsFeature`,e,{table_getRowsInDisplayOrder:{fn:()=>Mfe(e),memoDeps:()=>[e.getPrePaginatedRowModel().rows,e.options.paginateExpandedRows,e.options.paginateExpandedRows===!1?e.atoms.expanded?.get():void 0]},table_getRowId:{fn:(t,n,r)=>Hfe(t,e,n,r)},table_getRow:{fn:(t,n)=>Ufe(e,t,n)},table_getMaxSubRowDepth:{fn:()=>Lfe(e),memoDeps:()=>[e.getCoreRowModel()]}})}};function Z3(e,t,n=(e,t)=>e===t){let r=t===void 0?e.options.state:t;e._reactivity.batch(()=>{if(r)for(let t in r){let i=e.baseAtoms[t];if(!i)continue;let a=r[t],o=a===void 0?e.initialState[t]:a;n(e._reactivity.untrack(()=>i.get()),o)||i.set(()=>o)}})}function Q3(e,t,n=(e,t)=>e===t){e._reactivity.batch(()=>{Z3(e,t,n),e._reactivity.commit?.()})}function Gfe(e){let t=s3(e.initialState);e._reactivity.batch(()=>{let n=Object.keys(t);for(let r=0;r<n.length;r++){let i=n[r];e.baseAtoms[i].set(t[i])}});let n=Object.values(e._features);for(let t=0;t<n.length;t++)n[t].resetTableInstanceData?.(e)}function Kfe(e,t){let{features:n,atoms:r,initialState:i}=e.options;if(!e.options.mergeOptions)return{...e.options,...t,features:n,atoms:r,initialState:i};let a=e.options.mergeOptions(e.options,t),o={...Object.getOwnPropertyDescriptors(a)};return Object.defineProperties(Object.create(Object.getPrototypeOf(a)),{...o,features:{value:n,enumerable:!0,configurable:!0,writable:!0},atoms:{value:r,enumerable:!0,configurable:!0,writable:!0},initialState:{value:i,enumerable:!0,configurable:!0,writable:!0}})}function $3(e,t,n){let r=Kfe(e,o3(t,e.options));e.optionsStore?e.optionsStore.set(()=>r):e.options=r,n?.syncExternalState!==!1&&Q3(e,r.state??null)}var qfe={coreCellsFeature:xde,coreColumnsFeature:Bde,coreHeadersFeature:qde,coreRowModelsFeature:Ofe,coreRowsFeature:Wfe,coreTablesFeature:{constructTableAPIs:e=>{_3(`coreTablesFeature`,e,{table_reset:{fn:()=>Gfe(e)},table_setOptions:{fn:t=>$3(e,t)}})}}};function Jfe(){return{accessor:(e,t)=>typeof e==`function`?{...t,accessorFn:e}:{...t,accessorKey:e},columns:e=>e,display:e=>e,group:e=>e}}function Yfe(e){return e}function Xfe(e,t={}){return Object.values(e).forEach(e=>{t=e.getInitialState?.(t)??t}),s3(t)}function Zfe(e){let t=e.features.coreReactivityFeature,{aggregationFns:n,columnMeta:r,coreRowModel:i,expandedRowModel:a,facetedMinMaxValues:o,facetedRowModel:s,facetedUniqueValues:c,filterFns:l,filterMeta:u,filteredRowModel:d,groupedRowModel:f,paginatedRowModel:p,sortFns:m,sortedRowModel:h,tableMeta:g,..._}=e.features,v={_cellInstanceInitFns:[],_columnInstanceInitFns:[],_features:{...qfe,..._},_headerGroupInstanceInitFns:[],_headerInstanceInitFns:[],_reactivity:t,_rowInstanceInitFns:[],_rowModelFns:{aggregationFns:n,filterFns:l,sortFns:m},_rowModels:{},atoms:{},baseAtoms:{}},y=Object.values(v._features),b={...y.reduce((e,t)=>Object.assign(e,t.getDefaultTableOptions?.(v)),{}),...e};if(t.wrapExternalAtoms&&b.atoms)for(let[e,n]of Object.entries(b.atoms)){let r=n,i=t.createWritableAtom(r.get(),{debugName:`externalAtom/${e}`});b.atoms[e]=i;let a=!1,o=r.subscribe(e=>{a||i.set(e)}),s=i.subscribe(e=>{a=!0,r.set(e),a=!1});t.addSubscription(o),t.addSubscription(s)}t.createOptionsStore?(v.optionsStore=t.createWritableAtom(b,{debugName:`table/optionsStore`}),Object.defineProperty(v,"options",{configurable:!0,enumerable:!0,get(){return v.optionsStore.get()},set(e){v.optionsStore.set(()=>e)}})):v.options=b,v.initialState=Xfe(v._features,v.options.initialState);let x=Object.keys(v.initialState);for(let e=0;e<x.length;e++){let n=x[e];v.baseAtoms[n]=t.createWritableAtom(v.initialState[n],{debugName:`table/baseAtoms/${n}`}),v.atoms[n]=t.createReadonlyAtom(()=>{let e=v.options,t=e.atoms?.[n],r=t?t.get():v.baseAtoms[n].get();if(t)return r;let i=e.state;if(i&&l3(i,n)){let e=i[n];return e===void 0?v.initialState[n]:e}return r},{debugName:`table/atoms/${n}`})}Z3(v),v.store=sde(t.createReadonlyAtom(()=>{let e={};for(let t=0;t<x.length;t++){let n=x[t];e[n]=v.atoms[n].get()}return e},{compare:r3,debugName:`table/store`}));for(let e=0;e<y.length;e++){let t=y[e];t.initTableInstanceData?.(v),t.initCellInstanceData&&v._cellInstanceInitFns.push(t.initCellInstanceData.bind(t)),t.initColumnInstanceData&&v._columnInstanceInitFns.push(t.initColumnInstanceData.bind(t)),t.initHeaderGroupInstanceData&&v._headerGroupInstanceInitFns.push(t.initHeaderGroupInstanceData.bind(t)),t.initHeaderInstanceData&&v._headerInstanceInitFns.push(t.initHeaderInstanceData.bind(t)),t.initRowInstanceData&&v._rowInstanceInitFns.push(t.initRowInstanceData.bind(t)),t.constructTableAPIs?.(v)}return v}function Qfe(){return c3()}function e6(e,t){e.options.onRowSelectionChange?.(t)}function $fe(e,t){e._lastSelectedRowId=null,e6(e,t?c3():Object.assign(c3(),s3(e.initialState.rowSelection??{})))}function t6(e,t,n){e._lastSelectedRowId=null,e6(e,r=>{if(t=t===void 0?!y3(e,`getIsAllRowsSelected`,i6):t,n?.deselectAll&&!t)return c3();let i=Object.assign(c3(),r),a=e.getPreGroupedRowModel().flatRows;if(t){let e=new Map;a.forEach(t=>{m6(t,e)&&(i[t.id]=!0)})}else a.forEach(e=>{u6(e)&&delete i[e.id]});return i})}function n6(e,t,n){e._lastSelectedRowId=null,e6(e,r=>{let i=t===void 0?!y3(e,`getIsAllPageRowsSelected`,a6):t;if(n?.deselectAll&&!i)return c3();let a=Object.assign(c3(),r);return e.getRowModel().rows.forEach(t=>{p6(a,t.id,i,!0,e,!0)}),a})}function epe(e){return e.getCoreRowModel()}function tpe(e){let t=e.getCoreRowModel();return y3(e,`getIsSomeRowsSelected`,o6)?_6(t,e):{rows:[],flatRows:[],rowsById:c3()}}function npe(e){let t=e.getFilteredRowModel();return y3(e,`getIsSomeRowsSelected`,o6)?_6(t,e):{rows:[],flatRows:[],rowsById:c3()}}function rpe(e){let t=e.getSortedRowModel();return y3(e,`getIsSomeRowsSelected`,o6)?_6(t,e):{rows:[],flatRows:[],rowsById:c3()}}function r6(e){return Object.keys(e.atoms.rowSelection?.get()??{})}function i6(e){let t=e.getFilteredRowModel().flatRows,n=e.atoms.rowSelection?.get()??{},r=!!(t.length&&Object.keys(n).length);if(r){let e=new Map;t.some(t=>!v6(t,n)&&m6(t,e))&&(r=!1)}return r}function a6(e){let t=e.getPaginatedRowModel().flatRows,n=e.atoms.rowSelection?.get()??{},r=new Map,i=!1;for(let e=0;e<t.length;e++){let a=t[e];if(v6(a,n))!i&&m6(a,r)&&(i=!0);else if(m6(a,r))return!1}return i}function o6(e){return y3(e,`getSelectedRowIds`,r6).length>0}function ipe(e){return e.getPaginatedRowModel().flatRows.filter(e=>u6(e)).some(e=>c6(e)||y3(e,`getIsSomeSelected`,l6))}function ape(e){return t=>{t6(e,t.target.checked)}}function ope(e){return t=>{n6(e,t.target.checked)}}function s6(e,t,n){let r=c6(e);e6(e.table,i=>{t=t===void 0?!r:t;let a=Object.assign(c3(),i);return p6(a,e.id,t,(n?.selectChildren??!0)&&f6(e),e.table),!t&&n?.deselectParents&&h6(a,e),a})}function c6(e){return v6(e,e.table.atoms.rowSelection?.get()??{})}function l6(e){return y6(e)===`some`}function spe(e){return y6(e)===`all`}function u6(e){let t=e.table.options;return typeof t.enableRowSelection==`function`?t.enableRowSelection(e):t.enableRowSelection??!0}function d6(e){let t=e.table.options;return typeof t.enableSubRowSelection==`function`?t.enableSubRowSelection(e):t.enableSubRowSelection??!0}function f6(e){let t=e.table.options;return typeof t.enableMultiRowSelection==`function`?t.enableMultiRowSelection(e):t.enableMultiRowSelection??!0}function cpe(e,t){let n=u6(e);return r=>{if(!n)return;let i=r,a=e.table,o=i.target.checked,s=a._lastSelectedRowId;(!(a.options.enableRowRangeSelection!==!1&&s!==null&&f6(e)&&(a.options.isRowRangeSelectionEvent?.(r)??!1))||!lpe(e,s,o,t))&&s6(e,o,t),a._lastSelectedRowId=e.id}}function lpe(e,t,n,r){let i=r?.selectChildren??!0,a=e.table,o=a.getRowsInDisplayOrder(),s=a.getPrePaginatedRowModel().rowsById[t]??a.getCoreRowModel().rowsById[t];if(!s)return!1;let c=s.getDisplayIndex(),l=e.getDisplayIndex(),u=o[c],d=o[l];if(c<0||l<0||c>=o.length||l>=o.length||u?.id!==s.id||d?.id!==e.id||!f6(s)||!f6(e))return!1;let f=Math.min(c,l),p=Math.max(c,l);return e6(a,e=>{let t=Object.assign(c3(),e);for(let e=f;e<=p;e++){let s=o[e];u6(s)&&f6(s)&&(p6(t,s.id,n,i,a),!n&&r?.deselectParents&&h6(t,s))}return t}),!0}function p6(e,t,n,r,i,a){let o=i.getRow(t,!0);n?(f6(o)||Object.keys(e).forEach(t=>delete e[t]),u6(o)&&(e[t]=!0)):(!a||u6(o))&&delete e[t],r&&o.subRows.length&&d6(o)&&o.subRows.forEach(t=>p6(e,t.id,n,r,i,a))}function m6(e,t){if(!u6(e))return!1;let n=e.table;if(n.options.enableSubRowSelection===!0)return!0;let r=e.parentId;if(r===void 0)return!0;let i=t.get(r);if(i!==void 0)return i;let a=n.getCoreRowModel().rowsById,o=[],s=!0,c=r;for(;c!==void 0;){let e=t.get(c);if(e!==void 0){s=e;break}o.push(c);let r=a[c]??n.getRow(c,!0);if(!d6(r)){s=!1;break}c=r.parentId}return o.forEach(e=>t.set(e,s)),s}function h6(e,t){let n=t.table.getCoreRowModel().rowsById,r=t.parentId;for(;r!==void 0;)delete e[r],r=(n[r]??t.table.getRow(r,!0)).parentId}function g6(e,t,n,r){let i=[];for(let a=0;a<e.length;a++){let o=e[a],s=v6(o,t);if(s&&(n.push(o),r[o.id]=o),o.subRows.length){let e=g6(o.subRows,t,n,r);if(s){let t=Object.create(Object.getPrototypeOf(o));dde(t,o),t.subRows=e,i.push(t)}}else s&&i.push(o)}return i}function _6(e,t){let n=[],r=c3(),i=t.atoms.rowSelection?.get()??{};return{rows:g6(e.rows,i,n,r),flatRows:n,rowsById:r}}function v6(e,t){return!!(l3(t,e.id)&&t[e.id])}function y6(e){if(!e.subRows.length)return!1;let t=e.table.atoms.rowSelection?.get()??{},n=!1,r=!0,i=!1;for(let a=0;a<e.subRows.length;a++){let o=e.subRows[a];if(n&&!r)break;if(u6(o)&&(i=!0,v6(o,t)?n=!0:r=!1),o.subRows.length){let e=y6(o);e===`all`?(n=!0,i=!0):e===`some`?(n=!0,r=!1,i=!0):r=!1}}return i?r?`all`:n?`some`:!1:!1}var upe={initTableInstanceData:e=>{e._lastSelectedRowId=null},resetTableInstanceData:e=>{e._lastSelectedRowId=null},getInitialState:e=>({rowSelection:Qfe(),...e}),getDefaultTableOptions:e=>({onRowSelectionChange:u3(`rowSelection`,e),enableRowSelection:!0,enableMultiRowSelection:!0,enableRowRangeSelection:!0,enableSubRowSelection:!0,isRowRangeSelectionEvent:e=>{let t=e;return!!(t.shiftKey||t.nativeEvent?.shiftKey)}}),assignRowPrototype:(e,t)=>{v3(`rowSelectionFeature`,e,t,{row_toggleSelected:{fn:(e,t,n)=>s6(e,t,n)},row_getIsSelected:{fn:e=>c6(e)},row_getIsSomeSelected:{fn:e=>l6(e),memoDeps:e=>[e.subRows,e.table.atoms.rowSelection?.get(),e.table.options.enableRowSelection]},row_getIsAllSubRowsSelected:{fn:e=>spe(e),memoDeps:e=>[e.subRows,e.table.atoms.rowSelection?.get(),e.table.options.enableRowSelection]},row_getCanSelect:{fn:e=>u6(e)},row_getCanSelectSubRows:{fn:e=>d6(e)},row_getCanMultiSelect:{fn:e=>f6(e)},row_getToggleSelectedHandler:{fn:(e,t)=>cpe(e,t)}})},constructTableAPIs:e=>{_3(`rowSelectionFeature`,e,{table_setRowSelection:{fn:t=>e6(e,t)},table_resetRowSelection:{fn:t=>$fe(e,t)},table_toggleAllRowsSelected:{fn:(t,n)=>t6(e,t,n)},table_toggleAllPageRowsSelected:{fn:(t,n)=>n6(e,t,n)},table_getPreSelectedRowModel:{fn:()=>epe(e)},table_getSelectedRowModel:{fn:()=>tpe(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getCoreRowModel()]},table_getFilteredSelectedRowModel:{fn:()=>npe(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getFilteredRowModel()]},table_getGroupedSelectedRowModel:{fn:()=>rpe(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getSortedRowModel()]},table_getSelectedRowIds:{fn:()=>r6(e),memoDeps:()=>[e.atoms.rowSelection?.get()]},table_getIsAllRowsSelected:{fn:()=>i6(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getFilteredRowModel(),e.options.enableRowSelection,e.options.enableSubRowSelection]},table_getIsAllPageRowsSelected:{fn:()=>a6(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getPaginatedRowModel(),e.options.enableRowSelection,e.options.enableSubRowSelection]},table_getIsSomeRowsSelected:{fn:()=>o6(e),memoDeps:()=>[e.atoms.rowSelection?.get()]},table_getIsSomePageRowsSelected:{fn:()=>ipe(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getPaginatedRowModel(),e.options.enableRowSelection]},table_getToggleAllRowsSelectedHandler:{fn:()=>ape(e)},table_getToggleAllPageRowsSelectedHandler:{fn:()=>ope(e)}})}},dpe={getInitialState(e){return{sorting:cfe(),...e}},getDefaultColumnDef(){return{sortFn:`auto`,sortUndefined:1}},getDefaultTableOptions(e){return{autoResetSorting:!1,onSortingChange:u3(`sorting`,e),isMultiSortEvent:e=>e.shiftKey}},assignColumnPrototype(e,t){v3(`rowSortingFeature`,e,t,{column_getAutoSortFn:{fn:e=>H3(e)},column_getAutoSortDir:{fn:e=>U3(e)},column_getSortFn:{fn:e=>ufe(e)},column_toggleSorting:{fn:(e,t,n)=>W3(e,t,n)},column_getFirstSortDir:{fn:e=>G3(e)},column_getNextSortingOrder:{fn:(e,t)=>K3(e,t)},column_getCanSort:{fn:e=>q3(e)},column_getCanMultiSort:{fn:e=>J3(e)},column_getIsSorted:{fn:e=>Y3(e)},column_getSortIndex:{fn:e=>dfe(e)},column_clearSorting:{fn:e=>ffe(e)},column_getToggleSortingHandler:{fn:e=>pfe(e)}})},constructTableAPIs(e){_3(`rowSortingFeature`,e,{table_setSorting:{fn:t=>B3(e,t)},table_resetSorting:{fn:t=>V3(e,t)}})}},fpe=typeof window>`u`?o.useEffect:o.useLayoutEffect;function ppe(e,t){let[{table:n,rootSource:r}]=(0,o.useState)(()=>{let t=Zfe({...e,features:{coreReactivityFeature:ude(),...e.features}});return t.Subscribe=(e=>ode({...e,source:e.source??t.store})),t.FlexRender=Zue,{table:t,rootSource:lde(t.store,r3)}}),i=n;$3(i,t=>({...t,...e}),{syncExternalState:!1});let a=i.options.state,s=r.get(),c=a3(r,t,{compare:r3});return fpe(()=>{r.markCommitted(s),Q3(i,a??null,r3)}),(0,o.useMemo)(()=>({...n,options:e,state:c}),[n,e,c])}var mpe=e=>t=>{let n=t.currentTarget;n.scrollWidth>Math.ceil(n.getBoundingClientRect().width)?n.title=e:n.removeAttribute(`title`)},b6=({text:e,className:t})=>(0,V.jsx)(`span`,{className:B(`truncate`,t),onMouseEnter:mpe(e),children:e}),x6=e=>(0,V.jsx)(`span`,{className:`text-faint-foreground`,children:e}),S6=(e,t)=>{if(t==null)return x6(`—`);let n=vS(e,t)??``;switch(e.kind){case`text`:return(0,V.jsx)(b6,{text:n});case`id`:return(0,V.jsx)(b6,{text:n,className:`font-mono text-xs text-muted-foreground`});case`money`:return(0,V.jsx)(`span`,{className:`tabular-nums`,children:n});case`date`:return(0,V.jsx)(`span`,{className:`tabular-nums text-muted-foreground`,children:n});case`datetime`:return(0,V.jsx)(`span`,{className:`tabular-nums text-muted-foreground`,children:n});case`number`:return(0,V.jsx)(`span`,{className:`tabular-nums`,children:n});case`signed`:return(0,V.jsx)(`span`,{className:B(`tabular-nums`,Number(t)<0?`text-danger-text`:`text-success-text`),children:n});case`percent`:return Number(t)===0?x6(`—`):(0,V.jsx)(`span`,{className:`tabular-nums`,children:n});case`status`:return(0,V.jsx)(Zu,{tone:e.tones?.[String(t)]??`neutral`,color:j4(e.colors,t),shape:e.shape,children:n});case`relation`:return(0,V.jsx)(b6,{text:n,className:`font-medium text-primary-text hover:underline`});case`boolean`:return t?(0,V.jsx)(`span`,{className:`inline-flex size-4 items-center justify-center rounded-full bg-success-soft text-success-text`,children:(0,V.jsx)(he,{className:`size-3`,strokeWidth:3})}):x6(`No`);case`file`:{let e=Nx(t);if(!e)return x6(`—`);if(`missing`in e)return(0,V.jsx)(b6,{text:e.name,className:`text-danger-text`});let n=Vx(t,{width:20,height:20});return(0,V.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[n?(0,V.jsx)($C,{image:n,className:`size-5 shrink-0 rounded-sm object-cover`}):(0,V.jsx)(Qt,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,V.jsx)(b6,{text:e.name})]})}case`user`:{let e=tx(String(t));return(0,V.jsxs)(`span`,{className:`inline-flex items-center gap-2 truncate`,children:[(0,V.jsx)(Hu,{initials:e.initials,hue:e.hue,size:`xs`,className:`ring-0`}),(0,V.jsx)(b6,{text:e.name,className:`text-muted-foreground`})]})}}},hpe=Yfe({rowSortingFeature:dpe,rowSelectionFeature:upe}),C6=Jfe(),gpe=e=>C6.columns(e.map(e=>C6.accessor(t=>e.value?e.value(t):t[e.id],{id:e.id,header:e.header,enableSorting:e.sortable??!1,cell:t=>e.render?e.render(t.row.original):S6(e,t.getValue())}))),_pe=({total:e,selectedCount:t,bulkActions:n=[],className:r})=>(0,V.jsx)(`div`,{className:B(`flex h-9 shrink-0 items-center border-t bg-surface px-3 text-xs text-muted-foreground`,r),children:(0,V.jsxs)(`span`,{className:`flex items-center tabular-nums`,children:[lf(e),t>0&&(0,V.jsxs)(`span`,{className:`ml-3 font-medium text-primary-text`,children:[of(t),` selected`]}),t>0&&n.map(e=>(0,V.jsx)(`button`,{type:`button`,onClick:e.onRun,className:B(`ml-3 rounded border bg-background px-2 py-0.5 font-medium hover:bg-muted`,e.destructive?`border-danger/40 text-danger-text`:`text-foreground`),children:e.label},e.label))]})}),vpe=(e,t)=>e.filter(e=>e.available?.(t)??!0),w6=4,ype=(e,t)=>{let n=e.bottom+w6;return{top:n+t>window.innerHeight-w6?Math.max(w6,e.top-w6-t):n,right:window.innerWidth-e.right}},bpe=({row:e,actions:t})=>{let[n,r]=(0,o.useState)(!1),[i,a]=(0,o.useState)(),s=(0,o.useRef)(null),c=(0,o.useRef)(null);return(0,o.useLayoutEffect)(()=>{if(!n||!s.current||!c.current){a(void 0);return}a(ype(s.current.getBoundingClientRect(),c.current.offsetHeight))},[n]),(0,o.useEffect)(()=>{if(!n)return;let e=e=>s.current?.contains(e)||c.current?.contains(e),t=t=>{(t instanceof KeyboardEvent?t.key===`Escape`:!e(t.target))&&r(!1)},i=()=>r(!1);return document.addEventListener(`mousedown`,t),document.addEventListener(`keydown`,t),document.addEventListener(`scroll`,i,!0),window.addEventListener(`resize`,i),()=>{document.removeEventListener(`mousedown`,t),document.removeEventListener(`keydown`,t),document.removeEventListener(`scroll`,i,!0),window.removeEventListener(`resize`,i)}},[n]),(0,V.jsxs)(`div`,{className:`relative flex justify-center bg-inherit`,onClick:e=>e.stopPropagation(),children:[(0,V.jsx)(`button`,{ref:s,type:`button`,"aria-label":`Row actions`,"aria-haspopup":`menu`,"aria-expanded":n,onClick:()=>r(!n),className:`inline-flex items-center justify-center rounded p-1 text-faint-foreground hover:bg-muted hover:text-foreground pointer-coarse:size-11`,children:(0,V.jsx)(Ke,{className:`size-4`})}),n&&(0,tr.createPortal)((0,V.jsx)(`ul`,{ref:c,role:`menu`,onClick:e=>e.stopPropagation(),style:i??{visibility:`hidden`},className:`fixed z-50 min-w-36 rounded-md border bg-background py-1 shadow-pop`,children:t.map(t=>(0,V.jsx)(`li`,{role:`none`,children:(0,V.jsx)(`button`,{type:`button`,role:`menuitem`,className:B(`block w-full px-3 py-1.5 text-left hover:bg-muted`,t.destructive&&`text-danger-text`),onClick:()=>{r(!1),t.onSelect(e)},children:t.label})},t.label))}),document.body)]})},xpe=e=>52+Math.ceil(String(e).length*1.33)*7,T6=.6,E6=(e,t)=>Math.max(e.minWidth??0,e.width*t),Spe=(e,t)=>e.fixed?`${Math.max(e.minWidth??0,e.width)}px`:`minmax(${E6(e,t)}px, ${e.width}fr)`,D6=(e,t,n=0,r=T6)=>`${t}px ${e.map(e=>Spe(e,r)).join(` `)}${n>0?` ${n}px`:``}`,Cpe=(e,t,n=0,r=T6)=>t+n+e.reduce((e,t)=>e+(t.fixed?Math.max(t.minWidth??0,t.width):E6(t,r)),0),wpe=()=>{let e=(0,o.useRef)(null),t=(0,o.useRef)(null),[n,r]=(0,o.useState)({scrolled:!1,more:!1}),i=(0,o.useCallback)(()=>{let t=e.current;if(!t)return;let n={scrolled:t.scrollLeft>1,more:t.scrollLeft+t.clientWidth<t.scrollWidth-1};r(e=>e.scrolled===n.scrolled&&e.more===n.more?e:n)},[]);return{ref:e,attach:(0,o.useCallback)(n=>{if(t.current?.disconnect(),t.current=null,e.current=n,!n)return;let r=new ResizeObserver(i);r.observe(n);for(let e of Array.from(n.children))r.observe(e);t.current=r,i()},[i]),onScroll:i,...n}},Tpe=`protobase:pinned:`,Epe=(e,t)=>`${Tpe}${e}:${t}`,Dpe=(e,t)=>ad(()=>{let n=e.getItem(t);if(n===null)return;let r=JSON.parse(n);return Array.isArray(r)&&r.every(e=>typeof e==`string`)?r:void 0},void 0),Ope=(e,t,n)=>ad(()=>e.setItem(t,JSON.stringify(n)),void 0),kpe=(e,t=[])=>{let[n,r]=(0,o.useState)(()=>e?Dpe(localStorage,e):void 0),i=(0,o.useCallback)(t=>{r(t),e&&Ope(localStorage,e,t)},[e]);return[n??t,i]},Ape=e=>{let t=e.findIndex(e=>e.title);return t<0||t>1?[]:e.slice(0,t+1).map(e=>e.id)},jpe=e=>Object.fromEntries(e.map(({id:e,width:t,minWidth:n,fixed:r})=>[e,{width:t,minWidth:n,fixed:r}])),Mpe=(e,t)=>{let n=e.map(e=>e.id).sort().join(` `),[r,i]=(0,o.useState)(),a=r?.key===n?r:void 0;!a&&t.length>0&&i({key:n,sizes:jpe(FS(e,t))});let s=a?.sizes;return(0,o.useMemo)(()=>s?e.map(e=>({...e,...s[e.id]})):e,[e,s])},O6=e=>e===`money`||e===`number`||e===`signed`||e===`percent`,Npe=({header:e,pinned:t,onTogglePin:n})=>{let[r,i]=(0,o.useState)(!1),a=(0,o.useRef)(null);return(0,o.useEffect)(()=>{if(!r)return;let e=e=>{(e instanceof KeyboardEvent?e.key===`Escape`:!a.current?.contains(e.target))&&i(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,e)}},[r]),(0,V.jsxs)(`div`,{ref:a,className:`relative ml-auto shrink-0`,children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":`${e} column menu`,"aria-haspopup":`menu`,"aria-expanded":r,onClick:()=>i(!r),className:`relative inline-flex size-5 items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground focus-visible:opacity-100 after:absolute after:-inset-2 after:content-[''] md:opacity-0 md:group-hover/cell:opacity-100 aria-expanded:opacity-100`,children:(0,V.jsx)(Ke,{className:`size-3.5`})}),r&&(0,V.jsx)(`ul`,{role:`menu`,className:`absolute right-0 top-full z-30 mt-1 min-w-32 rounded-md border bg-background py-1 text-body font-normal text-foreground shadow-pop`,children:(0,V.jsx)(`li`,{role:`none`,children:(0,V.jsx)(`button`,{type:`button`,role:`menuitem`,className:`block min-h-9 w-full whitespace-nowrap px-3 py-1.5 text-left hover:bg-muted`,onClick:()=>{i(!1),n()},children:t?`Unpin`:`Pin to left`})})})]})},Ppe=({sorted:e})=>e===`asc`?(0,V.jsx)(A,{className:`size-3 text-foreground`}):e===`desc`?(0,V.jsx)(S,{className:`size-3 text-foreground`}):(0,V.jsx)(Ce,{className:`size-3 opacity-0 group-hover/head:opacity-100`}),Fpe=({cells:e,specs:t,gutter:n,selectedCount:r,selectable:i,trailing:a,minScale:o,pins:s={},lastPinned:c,scrolled:l,onTogglePin:u,onClearSelection:d})=>(0,V.jsxs)(`div`,{className:`grid h-8 shrink-0 items-center border-b bg-surface text-xs font-medium text-muted-foreground`,style:{gridTemplateColumns:D6(t,n,a,o)},role:`row`,children:[(0,V.jsxs)(`div`,{className:B(`sticky left-0 z-10 flex h-full items-center gap-2 bg-inherit pl-3`,l&&!c&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),style:{width:n},children:[i&&(0,V.jsx)(zh,{checked:!1,indeterminate:r>0,label:r>0?`Clear selection`:`No rows selected`,disabled:r===0,onChange:d,className:B(r===0&&`opacity-60`)}),n>40&&(0,V.jsx)(`span`,{className:`w-6 text-right text-faint-foreground`,children:`#`})]}),e.map(({spec:e,sorted:t,onSort:n})=>{let r=e.id in s;return(0,V.jsxs)(`div`,{"data-col-id":e.id,style:r?{left:s[e.id]}:void 0,className:B(`group/cell flex h-full min-w-0 items-center`,r&&`sticky z-10 bg-inherit`,r&&l&&e.id===c&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`,e.highlight&&`bg-primary-soft text-primary-text`),children:[(0,V.jsxs)(`button`,{type:`button`,onClick:n,disabled:!e.sortable,className:B(`group/head flex h-full min-w-0 flex-1 items-center gap-1 pl-3 pr-1 text-left`,O6(e.kind)&&`justify-end`,e.sortable&&`hover:text-foreground`,t&&`text-foreground`),children:[(0,V.jsx)(`span`,{className:`truncate`,children:e.header}),e.highlight&&(0,V.jsx)(`span`,{className:`rounded bg-primary px-1 text-[10px] font-semibold uppercase leading-4 text-primary-foreground`,children:`New`}),e.sortable&&(0,V.jsx)(Ppe,{sorted:t})]}),(0,V.jsx)(`div`,{className:`pr-1.5`,children:(0,V.jsx)(Npe,{header:e.header,pinned:r,onTogglePin:()=>u(e.id)})})]},e.id)}),a?(0,V.jsx)(`div`,{className:`sticky right-0 z-10 h-full bg-inherit`}):null]}),k6=e=>({gridTemplateColumns:D6(e.specs,e.gutter,e.trailing,e.minScale),height:e.height,transform:`translateY(${e.offset}px)`}),A6=(e,t)=>B(`flex h-full min-w-0 items-center overflow-hidden whitespace-nowrap px-3`,O6(e.kind)&&`justify-end`,e.highlight&&`bg-primary-soft/60`,t.pins&&e.id in t.pins&&`sticky z-10 bg-inherit`,t.scrolled&&e.id===t.lastPinned&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),j6=(e,t)=>t&&e.id in t?{left:t[e.id]}:void 0,M6=({width:e,index:t,selectable:n,selected:r,onToggle:i,edge:a})=>(0,V.jsxs)(`div`,{onClick:n?e=>{e.stopPropagation(),i?.()}:void 0,className:B(`sticky left-0 z-10 flex h-full items-center gap-2 bg-inherit pl-3`,n&&`cursor-default`,a&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),style:{width:e},children:[n&&(0,V.jsx)(zh,{checked:!!r,label:`Select row ${t+1}`}),e>40&&(0,V.jsx)(`span`,{className:`min-w-6 text-right text-[11px] tabular-nums text-faint-foreground`,children:of(t+1)})]}),Ipe=(e,t,n)=>({gridTemplateColumns:D6(e.specs,e.gutter,e.trailing,e.minScale),height:e.height,top:e.offset,transform:t===0?void 0:`translateY(${t}px)`,transition:n}),Lpe=e=>t=>{t.target.closest(`a`)||e()},N6=({cells:e,selected:t,onToggle:n,onOpen:r,menu:i,handle:a,rowRef:o,dragY:s,transition:c,dragging:l,...u})=>(0,V.jsxs)(`div`,{ref:o,role:`row`,onClick:r&&Lpe(r),className:B(`absolute inset-x-0 top-0 grid items-center border-b`,t?`bg-primary-soft`:`bg-background hover:bg-surface`,r&&`cursor-pointer`,l&&`z-30 bg-surface shadow-pop`),style:s===void 0?k6(u):Ipe(u,s,c),children:[a?(0,V.jsx)(`div`,{className:B(`sticky left-0 z-10 flex h-full items-center bg-inherit pl-1.5`,u.scrolled&&!u.lastPinned&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),style:{width:u.gutter},children:a}):(0,V.jsx)(M6,{width:u.gutter,index:u.index,selectable:u.selectable,selected:t,onToggle:n,edge:u.scrolled&&!u.lastPinned}),e.map(({spec:e,content:t,props:n,chosen:r,editing:i,editable:a})=>(0,V.jsx)(`div`,{role:n?`gridcell`:`cell`,...n,className:B(A6(e,u),n&&`scroll-mb-[calc(var(--pb-sticky-bottom,0px)+3rem)] scroll-mt-[calc(var(--pb-sticky-top,0px)+2rem)] outline-none`,a&&!i&&`cursor-default`,r&&`shadow-[inset_0_0_0_2px_var(--primary)]`,i&&`z-30 overflow-visible bg-background px-1`),style:j6(e,u.pins),children:t},e.id)),i&&(0,V.jsx)(`div`,{className:`sticky right-0 z-10 flex h-full items-center justify-center bg-inherit`,children:i})]}),P6=[`w-3/4`,`w-1/2`,`w-2/3`,`w-5/6`,`w-2/5`],Rpe=e=>(0,V.jsxs)(`div`,{role:`row`,"aria-busy":!0,className:`absolute inset-x-0 top-0 grid items-center border-b bg-background`,style:k6(e),children:[(0,V.jsx)(M6,{width:e.gutter,index:e.index,selectable:!1,edge:e.scrolled&&!e.lastPinned}),e.specs.map((t,n)=>(0,V.jsx)(`div`,{className:A6(t,e),style:j6(t,e.pins),children:(0,V.jsx)(Au,{className:B(`h-2.5`,P6[(e.index+n)%P6.length],O6(t.kind)&&`ml-auto`)})},t.id))]}),zpe=(e,t)=>{let n=new Map;return{get:t=>n.get(Math.floor(t/e))?.[t%e],hasPage:e=>n.has(e),setPage:(e,r)=>{if(n.delete(e),n.set(e,r),n.size<=t)return;let i=n.keys().next();i.done||n.delete(i.value)},keepOnly:e=>{for(let t of[...n.keys()])e.includes(t)||n.delete(t)},get size(){return n.size}}},F6=(e,t,n)=>{let r=Math.floor(e/n),i=Math.floor(t/n);return Array.from({length:i-r+1},(e,t)=>r+t)},I6=(e,t)=>Math.max(0,Math.min(40,e-t*40)),L6=({total:e,rowAt:t,loadRows:n,revision:r,latencyMs:i},a,s)=>{let c=(0,o.useMemo)(()=>zpe(40,60),[t,n]),[l,u]=(0,o.useState)(0),d=Math.floor(a/40),f=Math.floor(s/40),p=!n&&i===0;(0,o.useEffect)(()=>{if(p)return;let r=F6(d*40,f*40,40).filter(e=>!c.hasPage(e)),a=t=>I6(e,t),o=(e,t)=>{c.setPage(e,t),u(e=>e+1)};if(n){let e=!1;for(let t of r)n(t*40,a(t)).then(n=>{e||o(t,n)});return()=>{e=!0}}let s=r.map(e=>setTimeout(()=>o(e,Array.from({length:a(e)},(n,r)=>t(e*40+r))),i));return()=>s.forEach(clearTimeout)},[c,d,f,i,e,t,n,p]);let m=(0,o.useRef)(r);return(0,o.useEffect)(()=>{if(!n||r===m.current)return;m.current=r;let t=F6(d*40,f*40,40);c.keepOnly(t);for(let r of t.filter(e=>c.hasPage(e)))n(r*40,I6(e,r)).then(e=>{c.setPage(r,e),u(e=>e+1)})},[c,r,n,d,f,e]),(0,o.useCallback)(e=>p?t(e):c.get(e),[c,p,t,l])},Bpe=1e7,R6=(e,t,n)=>{let r=e*t,i=Math.min(r,Bpe);return{rowHeight:t,trueHeight:r,contentHeight:i,scaled:r>i,maxTop:Math.max(0,r-n),maxScroll:Math.max(0,i-n)}},Vpe=(e,t)=>!e.scaled||t<=0?t:t>=e.maxScroll?e.maxTop+t-e.maxScroll:t/e.maxScroll*e.maxTop,z6=(e,t)=>!e.scaled||t<=0?t:t>=e.maxTop?e.maxScroll+t-e.maxTop:t/e.maxTop*e.maxScroll,Hpe=(e,t,n,r)=>{let i=t*e.rowHeight;return e.scaled?i-n+r:i},B6=(e,t,n,r,i)=>{let a=Math.min(e,Math.max(0,Math.floor(t/n)-i)),o=Math.min(e-1,Math.floor((t+r)/n)+i);return{first:a,last:Math.max(a-1,o)}},Upe=e=>{let t=document.scrollingElement??document.documentElement;for(let n=e.parentElement;n&&n!==t&&n!==document.body;n=n.parentElement)if(/auto|scroll/.test(getComputedStyle(n).overflowY))return n;return t},V6=e=>e===(document.scrollingElement??document.documentElement),Wpe=e=>V6(e)?window:e,H6=e=>Number.parseFloat(e)||0,Gpe=e=>{let t=getComputedStyle(e),n=V6(e)?{top:0,height:e.clientHeight}:{top:e.getBoundingClientRect().top+e.clientTop,height:e.clientHeight},r=H6(t.scrollPaddingTop);return{top:n.top+r,height:Math.max(0,n.height-r-H6(t.scrollPaddingBottom))}},U6=6,W6=(e,t,n)=>{let r=R6(t,n,e.height),i=Vpe(r,e.position);return{geometry:r,top:i,topIndex:Math.floor(Math.max(0,i)/n),...B6(t,i,n,e.height,U6)}},G6=({total:e,rowHeight:t,initialIndex:n,inset:r=0,settle:i,ready:a=!0})=>{let s=(0,o.useRef)(null),c=(0,o.useRef)(null),[l,u]=(0,o.useState)({position:0,height:0}),d=(0,o.useRef)({total:e,rowHeight:t,initialIndex:n,inset:r,ready:a});d.current={total:e,rowHeight:t,initialIndex:n,inset:r,ready:a};let f=(0,o.useCallback)(()=>{let e=s.current;if(!e||!c.current)return;let t=Gpe(c.current),n=d.current.inset;return{position:t.top+n-e.getBoundingClientRect().top,height:Math.max(0,t.height-n)}},[]),p=(0,o.useRef)(l);p.current=l;let m=(0,o.useCallback)(()=>{let e=f();if(!e)return;let t=p.current,{total:n,rowHeight:r}=d.current,i=W6(t,n,r),a=W6(e,n,r),o=!a.geometry.scaled&&i.first===a.first&&i.last===a.last&&i.topIndex===a.topIndex;(t.height!==e.height||t.position!==e.position&&!o)&&(p.current=e,u(e))},[f]),h=(0,o.useRef)({pending:!0,laidOut:!1}),g=(0,o.useCallback)(()=>{if(!h.current.pending||!h.current.laidOut||!d.current.ready)return;let e=f(),t=c.current;if(!e||!t)return;h.current.pending=!1;let{total:n,rowHeight:r,initialIndex:i}=d.current;i>0?t.scrollTop+=z6(R6(n,r,e.height),i*r)-e.position:e.position>0&&(t.scrollTop=0)},[f]);(0,o.useLayoutEffect)(()=>{let e=s.current;if(!e)return;let t=Upe(e);c.current=t;let n=Wpe(t);n.addEventListener(`scroll`,m,{passive:!0}),window.addEventListener(`resize`,m,{passive:!0});let r=new ResizeObserver(()=>{h.current.laidOut=!0,g(),m()});return r.observe(t),r.observe(e),m(),()=>{n.removeEventListener(`scroll`,m),window.removeEventListener(`resize`,m),r.disconnect(),c.current=null}},[m,g]),(0,o.useLayoutEffect)(()=>{g(),m()});let _=(0,o.useCallback)(e=>{let t=f();if(!t||!c.current)return;let n=R6(d.current.total,d.current.rowHeight,t.height);c.current.scrollTop+=z6(n,e)-t.position,m()},[f,m]),v=W6(l,e,t),y=i?i(v.top):v.top,{first:b,last:x}=i?B6(e,y,t,l.height,U6):v,S=Array.from({length:x-b+1},(e,t)=>({index:b+t,offset:Hpe(v.geometry,b+t,y,l.position)}));return{ref:s,height:l.height,top:y,geometry:v.geometry,rows:S,first:b,last:x,scrollTo:_}},Kpe=e=>e===`ArrowUp`||e===`ArrowDown`||e===`ArrowLeft`||e===`ArrowRight`,qpe=(e,t,n,r)=>{let i=n.indexOf(e.column);if(t===`ArrowUp`)return e.index>0?{...e,index:e.index-1}:void 0;if(t===`ArrowDown`)return e.index<r-1?{...e,index:e.index+1}:void 0;let a=n[t===`ArrowLeft`?i-1:i+1];return i>=0&&a!==void 0?{...e,column:a}:void 0},Jpe=(e,t,n,r)=>{let i=t.indexOf(e);return(r===1?t.slice(i+1):t.slice(0,Math.max(0,i)).reverse()).find(n)},K6=e=>`${e.index}:${e.column}`,Ype=({editor:e,columns:t,total:n,rowAt:r,onOpenRow:i,container:a})=>{let[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(!1),d=(0,o.useRef)(!1),f=(0,o.useRef)(!1);if((0,o.useEffect)(()=>{if(!s||l||!d.current)return;d.current=!1;let e=a.current?.querySelector(`[data-cell="${K6(s)}"]`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`nearest`,inline:`nearest`}))},[s,l,a]),!e)return;let p=t=>{let n=r(t.index);return n!==void 0&&e.editable(n,t.column)},m=(e,t=!1)=>{d.current=!0,c(e),u(t&&p(e))},h=n=>{if(!s)return;let i=r(s.index),o=n&&i?Jpe(s.column,t,t=>e.editable(i,t),n):void 0,c=!!a.current?.contains(document.activeElement);m(o?{...s,column:o}:s,o!==void 0),d.current=c};return{cell:(n,r,i,a)=>{let o={index:n,column:i},u=s?.index===n&&s.column===i,d=e.editable(r,i),p=u||!s&&n===0&&i===t[0];return{content:u&&l?e.render(r,i,h):a,chosen:u,editing:u&&l,editable:d,props:{"data-cell":K6(o),tabIndex:p?0:-1,"aria-selected":u,onMouseDown:()=>{f.current=u},onFocus:e=>{e.target===e.currentTarget&&!u&&c(o)},onClick:e=>{d&&(e.stopPropagation(),f.current&&!l&&m(o,!0))},onDoubleClick:e=>{d&&(e.stopPropagation(),u&&l||m(o,!0))}}}},onKeyDown:e=>{if(l||!s||!(e.target instanceof HTMLElement)||e.target.dataset.cell!==K6(s))return;let a=e.key===`Tab`?e.shiftKey?`ArrowLeft`:`ArrowRight`:e.key;if(Kpe(a)){let i=qpe(s,a,t,n);if(!i&&e.key===`Tab`)return;e.preventDefault(),i&&r(i.index)&&m(i);return}if(e.key===`Enter`||e.key===`F2`){e.preventDefault();let t=r(s.index);p(s)?m(s,!0):e.key===`Enter`&&t&&i?.(t);return}e.key===`Escape`&&c(void 0)}}},Xpe=`To move a row, press Space on its handle, move it with the up and down arrow keys, and press Space again to drop it there. Escape puts it back.`,Zpe=({ids:e,rowAt:t,reorder:n,children:r})=>{let i=rv(nv(uy,{activationConstraint:{distance:4}}),nv(fy,{activationConstraint:{delay:250,tolerance:5}}),nv(ny,{coordinateGetter:Jb})),a=t=>e.indexOf(String(t)),o=e=>{let r=t(a(e));return r?n.label(r):`row`};return(0,V.jsx)(ib,{sensors:i,collisionDetection:fv,onDragEnd:({active:e,over:t})=>{t&&e.id!==t.id&&n.onMove(a(e.id),a(t.id))},accessibility:{announcements:{onDragStart:({active:t})=>`Picked up ${o(t.id)}, row ${a(t.id)+1} of ${e.length}.`,onDragOver:({active:t,over:n})=>n?`${o(t.id)} is over row ${a(n.id)+1} of ${e.length}.`:void 0,onDragEnd:({active:t,over:n})=>n?`${o(t.id)} was dropped at row ${a(n.id)+1} of ${e.length}.`:`${o(t.id)} was put back.`,onDragCancel:({active:e})=>`Moving ${o(e.id)} was cancelled. It is back at row ${a(e.id)+1}.`},screenReaderInstructions:{draggable:Xpe}},children:(0,V.jsx)(Ib,{items:e,strategy:Mb,children:r})})},Qpe=({row:e,label:t,...n})=>{let{attributes:r,listeners:i,setNodeRef:a,setActivatorNodeRef:o,transform:s,transition:c,isDragging:l}=Wb({id:e.id}),u=(0,V.jsx)(`button`,{ref:o,type:`button`,"aria-label":`Move ${t}`,...r,...i,onClick:e=>e.stopPropagation(),style:{touchAction:`none`},className:`flex size-7 cursor-grab items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground focus-visible:text-foreground active:cursor-grabbing pointer-coarse:size-9`,children:(0,V.jsx)(ot,{className:`size-4`})});return(0,V.jsx)(N6,{...n,rowRef:a,handle:u,dragY:s?.y??0,transition:c,dragging:l})},q6=32,J6=({columns:e,source:t,naturalSort:n,initialScrollIndex:r=0,onScrollIndex:i,latencyMs:a=150,sort:s,onSortChange:c,onOpenRow:l,rowLink:u,rowActions:d,cellEditor:f,rowPatches:p,bulkActions:m,pinKey:h,defaultPinned:g,rowNumbers:_=!0,compact:v=!1,selectable:y=!0,reorder:b,fit:x=!1,scroll:S=`own`,className:C})=>{let w=y&&!b,T=v?28:36,E=!mu(),D=(g??(E?[]:Ape(e))).join(` `),[O,k]=kpe(h,(0,o.useMemo)(()=>D?D.split(` `):[],[D])),A=(0,o.useMemo)(()=>[...O.flatMap(t=>e.find(e=>e.id===t)??[]),...e.filter(e=>!O.includes(e.id))],[e,O]),j=A.slice(0,A.filter(e=>O.includes(e.id)).length).map(e=>e.id),{total:M}=t,[N,ee]=(0,o.useState)(n?[{id:n.columnId,desc:n.direction===`desc`}]:[]),P=s?[{id:s.columnId,desc:s.direction===`desc`}]:N,te=e=>{let t=typeof e==`function`?e(P):e,n=t[0];c&&n&&c({columnId:n.id,direction:n.desc?`desc`:`asc`}),s||ee(t)},[F,ne]=(0,o.useState)({}),re=(0,o.useMemo)(()=>gpe(A),[A]),ie=P[0],I=!!(!s&&n&&ie&&ie.id===n.columnId&&(ie.desc?`desc`:`asc`)!==n.direction),ae=t.rowAt,L=(0,o.useCallback)(e=>ae(I?M-1-e:e),[ae,I,M]),[oe]=(0,o.useState)(r),{ref:R,top:se,geometry:ce,rows:le,first:ue,last:de}=G6({total:M,rowHeight:T,initialIndex:oe,inset:q6}),fe=E||!_?40:xpe(M),pe=Math.floor(Math.max(0,se)/T);(0,o.useEffect)(()=>i?.(pe),[pe,i]);let me=L6({total:M,rowAt:ae?L:void 0,loadRows:t.loadRows,revision:t.revision,latencyMs:a},ue,de),he=(0,o.useCallback)(e=>{let t=me(e),n=t&&p?.get(t.id);return n?{...t,...n}:t},[me,p]),ge=le.map(({index:e,offset:t})=>({index:e,offset:t,row:he(e)})),_e=(0,o.useMemo)(()=>ge.flatMap(({row:e})=>e?[e]:[]),[he,ue,de]),ve=Mpe(A,_e),ye=ppe({features:hpe,columns:re,data:_e,state:{sorting:P,rowSelection:F},onSortingChange:te,onRowSelectionChange:ne,manualSorting:!0,enableMultiSort:!1,enableSortingRemoval:!1,getRowId:e=>e.id}),be=new Map(ye.getRowModel().rows.map(e=>[e.id,e])),xe=Object.keys(F).length,Se=(0,o.useRef)(new Map);for(let e of ye.getRowModel().rows)e.getIsSelected()&&Se.current.set(e.id,e.original);let Ce=d&&d.length>0?40:0,we=E?1:T6,Te=wpe(),Ee=(0,o.useRef)(null),De=()=>{Te.onScroll(),Ee.current&&Te.ref.current&&(Ee.current.scrollLeft=Te.ref.current.scrollLeft)},[Oe,ke]=(0,o.useState)({});(0,o.useLayoutEffect)(()=>{let e=Ee.current?.querySelector(`[role=row]`);if(!e)return;let t=fe,n={};for(let r of j)n[r]=t,t+=e.querySelector(`[data-col-id="${r}"]`)?.offsetWidth??0;JSON.stringify(Oe)!==JSON.stringify(n)&&ke(n)});let Ae=j.at(-1),je=e=>k(O.includes(e)?O.filter(t=>t!==e):[...O,e]),Me=ye.getHeaderGroups().flatMap(e=>e.headers.map(e=>({spec:A.find(t=>t.id===e.column.id),sorted:e.column.getIsSorted(),onSort:t=>e.column.getToggleSortingHandler()?.(t)}))),Ne=(0,o.useRef)(null),Pe=Ype({editor:f,columns:(0,o.useMemo)(()=>A.map(e=>e.id),[A]),total:M,rowAt:he,onOpenRow:l,container:Ne}),Fe=(A.find(e=>e.title)??A[0])?.id,Ie=Cpe(ve,fe,Ce,we),Le=S===`own`,Re=(0,V.jsx)(`div`,{ref:Ee,className:B(`sticky z-20 shrink-0 overflow-hidden`,Le?`top-0`:`top-[var(--pb-sticky-top,0px)]`),children:(0,V.jsx)(`div`,{style:{minWidth:Ie},children:(0,V.jsx)(Fpe,{cells:Me,specs:ve,gutter:fe,trailing:Ce,minScale:we,pins:Oe,lastPinned:Ae,scrolled:Te.scrolled,onTogglePin:je,selectable:w,selectedCount:xe,onClearSelection:()=>ne({})})})}),ze=ge.map(({index:e,offset:t,row:n})=>{let r={specs:ve,gutter:fe,index:e,offset:t,height:T,selectable:w,trailing:Ce,minScale:we,scrolled:Te.scrolled,pins:Oe,lastPinned:Ae},i=n?be.get(n.id):void 0;if(!i||!n)return(0,V.jsx)(Rpe,{...r},`skeleton-${e}`);let a=Ce?vpe(d,n):[],o={...r,selected:i.getIsSelected(),onToggle:()=>i.toggleSelected(),onOpen:l?()=>l(n):void 0,menu:a.length>0?(0,V.jsx)(bpe,{row:n,actions:a}):void 0,cells:i.getAllCells().map(t=>{let r=(0,V.jsx)(ye.FlexRender,{cell:t}),i=!!f?.editable(n,t.column.id),a=u&&t.column.id===Fe&&!i?(0,V.jsx)(Nu,{to:u(n),className:`flex min-w-0 items-center hover:underline`,children:r}):r;return{spec:A.find(e=>e.id===t.column.id),...Pe?Pe.cell(e,n,t.column.id,a):{content:a}}})};return b?(0,V.jsx)(Qpe,{...o,row:n,label:b.label(n)},n.id):(0,V.jsx)(N6,{...o},n.id)}),Be=(0,V.jsx)(`div`,{ref:Te.attach,onScroll:De,className:`overflow-x-auto overflow-y-hidden overscroll-x-contain [-webkit-overflow-scrolling:touch]`,children:(0,V.jsx)(`div`,{ref:R,className:`relative`,style:{minWidth:Ie,height:ce.contentHeight},children:b?(0,V.jsx)(Zpe,{ids:Array.from({length:M},(e,t)=>he(t)?.id??`missing-${t}`),rowAt:he,reorder:b,children:ze}):ze})});return(0,V.jsxs)(`div`,{ref:Ne,role:`grid`,"aria-rowcount":M,onKeyDown:Pe?.onKeyDown,className:B(`flex flex-col rounded-lg border bg-background`,Le?`min-h-0 overflow-hidden`:`overflow-clip`,C),style:x&&Le?{height:q6+M*T+2}:void 0,children:[(0,V.jsxs)(`div`,{className:B(`relative`,Le&&`flex min-h-0 flex-1 flex-col`),children:[Le?(0,V.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto overflow-x-hidden`,children:[Re,Be]}):(0,V.jsxs)(V.Fragment,{children:[Re,Be]}),Te.more&&(0,V.jsx)(`div`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-y-0 right-0 z-20 w-8 bg-gradient-to-l from-backdrop/15 to-transparent`})]}),!x&&(0,V.jsx)(_pe,{total:M,className:Le?void 0:`sticky bottom-[var(--pb-sticky-bottom,0px)] z-20`,selectedCount:xe,bulkActions:m?.map(e=>({label:e.label(xe),destructive:e.destructive,onRun:()=>{e.onRun(Object.keys(F).flatMap(e=>Se.current.get(e)??[])),ne({}),Se.current.clear()}}))})]})},Y6=uo(),X6=(...e)=>{let t=e.filter(e=>!!e);return t.length===1?t[0]:t.map(e=>`(${e})`).join(` AND `)},Z6=e=>e==null?void 0:String(e),$pe=(e,t,n)=>{let r=new Map;for(let[t,n]of e)r.set(n,(r.get(n)??new Set).add(t));let i=new Map;for(let e of t){let t=e[n],a=Z6(typeof t==`object`&&t&&`id`in t?t.id:t);for(let t of a===void 0?[]:r.get(a)??[])i.set(t,[...i.get(t)??[],e])}return i},eme=async(e,t,n,r)=>{let i=n.through;if(!i)return r.map(e=>[e,e]);let a=t[i.resource],o=i.key??a?.primaryKey[0];if(!a||o===void 0)throw Error(`The related column ${n.name} names a join resource the app does not have: ${i.resource}`);return(await e.search(a.name,{filter:X6(Ya(Y6.in(i.field,r)),i.filter),fields:[i.field,o],pageSize:500})).items.flatMap(e=>{let t=Z6(e[i.field]),n=Z6(e[o]);return t===void 0||n===void 0?[]:[[t,n]]})},tme=async({client:e,resources:t,views:n,load:r,owners:i})=>{let{column:a,fields:o}=r,s=t[a.resource];if(!s)throw Error(`The related column ${a.name} shows a resource the app does not have: ${a.resource}`);if(i.length===0)return new Map;let c=await eme(e,t,a,i),l=[...new Set(c.map(([,e])=>e))];if(l.length===0)return new Map;let u=[...new Set([...s.primaryKey,a.field,a.status,...o])],d=k4(t,n,s,u),f=await e.search(s.name,{filter:X6(Ya(Y6.in(a.field,l)),a.filter),...a.sort&&{orderBy:a.sort},fields:u,pageSize:500,labels:d});return $pe(c,A4(t,s,u,f.items,f.labels),a.field)},nme=5e3,rme=({queryClient:e,client:t,resources:n,views:r,model:i,columns:a,filter:o,orderBy:s,related:c=[]})=>{let l=c.map(e=>e.column.name).join(`,`),u=e=>c.length===0?W.page(i.name,o,s,40,e):[...W.page(i.name,o,s,40,e),l],d=k4(n,r,i,a),f=$S(r[i.name]),p=async e=>e.nextPageToken===``?e.items.length:e.totalSizeEstimate>nme?e.totalSizeEstimate:(await t.list(i.name,{filter:o,orderBy:s,pageSize:1,count:`exact`})).totalSize??e.totalSizeEstimate,m=async t=>{if(t===0)return``;let n=u(t-1),r=e.getQueryData(n);if(r)return r.nextPageToken;if(e.getQueryState(n)?.fetchStatus===`fetching`)return(await g(t-1)).nextPageToken},h=async e=>{let l=await m(e);if(e>0&&l===``)return{rows:[],total:0,nextPageToken:``};let u={filter:o,orderBy:s,pageSize:40,labels:d,photos:f},h=l===void 0?await t.seek(i.name,{...u,position:e*40}):await t.list(i.name,{...u,pageToken:l});if(h.items.length===0&&e>0)return{rows:[],total:0,nextPageToken:``};let g=h.items.map(e=>Ag(i,e)),_=A4(n,i,a,eC(i,h.items,h.photos),h.labels),v=await Promise.all(c.map(e=>tme({client:t,resources:n,views:r,load:e,owners:g})));return{rows:_.map((e,t)=>({...e,...Object.fromEntries(c.map((e,n)=>[e.column.name,v[n].get(g[t])??[]])),id:g[t]})),total:e===0?await p(h):h.totalSizeEstimate,nextPageToken:h.nextPageToken}},g=t=>e.fetchQuery({queryKey:u(t),staleTime:6e4,queryFn:()=>h(t)});return{page:g,loadRows:async e=>(await g(Math.floor(e/40))).rows}},Q6=({resources:e,views:t,model:n,columns:r,filter:i,orderBy:a,related:s})=>{let c=G(),l=Wp(),u=r.join(`,`),d=JSON.stringify(s??[]),f=(0,o.useMemo)(()=>rme({queryClient:l,client:c,resources:e,views:t,model:n,columns:r,filter:i,orderBy:a,...s&&{related:s}}),[l,c,e,t,n,u,i,a,d]),p=vh({queryKey:[...W.first(n.name,i,a),u],queryFn:async()=>(await l.invalidateQueries({queryKey:W.pages(n.name,i,a),refetchType:`none`}),f.page(0))});return{source:(0,o.useMemo)(()=>p.data?{total:p.data.total,loadRows:f.loadRows,revision:p.dataUpdatedAt}:void 0,[p.data,p.dataUpdatedAt,f]),error:p.error,isLoading:p.isLoading,page:f.page,key:[...W.first(n.name,i,a),u]}},ime=`protobase:embedded-display:`,ame=e=>`${ime}${e}`,ome=(e,t)=>ad(()=>e.getItem(t)??void 0,void 0),sme=(e,t,n)=>ad(()=>e.setItem(t,n),void 0),cme=(e,t,{picked:n,preferred:r})=>{let i=hC(e).map(e=>e.name);return n!==void 0&&i.includes(n)?n:sC(e,t,r!==void 0&&i.includes(r)?r:void 0)},$6=(e,t,n,{resource:r=e.name,...i})=>NC({kind:`list`,resource:r},i,{...jC(e,t,n),display:sC(t,n)}),e8=`inline-flex h-6 items-center rounded-full border border-primary-border bg-primary-soft px-2.5 text-xs font-medium text-primary-text`,t8=({chips:e,className:t})=>(0,V.jsx)(`ul`,{className:B(`flex flex-wrap gap-1.5`,t),"aria-label":`Filters`,children:e.map(e=>(0,V.jsx)(`li`,{className:e8,children:e.label},e.key))}),n8=({chips:e})=>(0,V.jsx)(`span`,{className:`flex flex-wrap gap-1.5`,children:e.map((e,t)=>(0,V.jsxs)(`span`,{className:e8,children:[t>0&&(0,V.jsx)(`span`,{className:`sr-only`,children:`, `}),e.label]},e.key))}),lme=e=>e.map(e=>e.label).join(`, `),ume=`inline-flex h-6 items-center gap-1 rounded-full border border-primary-border bg-primary-soft pl-2.5 pr-1.5 text-xs font-medium text-primary-text`,r8=({chips:e,lockedLabels:t=[],onRemove:n,onClear:r,scroll:i})=>e.length===0&&t.length===0?null:(0,V.jsxs)(`div`,{className:i?`flex flex-nowrap items-center gap-1.5 overflow-x-auto pb-1 [&>*]:shrink-0`:`flex flex-wrap items-center gap-1.5`,children:[t.map(e=>(0,V.jsxs)(`span`,{className:`inline-flex h-6 items-center gap-1.5 rounded-full border border-border-strong bg-muted px-2.5 text-xs font-medium text-foreground`,children:[(0,V.jsx)(Nt,{className:`size-3 text-muted-foreground`}),e]},e)),e.map(e=>(0,V.jsxs)(`span`,{className:ume,children:[e.label,(0,V.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.label}`,onClick:()=>n(e.key),className:`rounded-full p-0.5 hover:bg-primary-border/60`,children:(0,V.jsx)(Qn,{className:`size-3`})})]},e.key)),e.length>0&&(0,V.jsx)(`button`,{type:`button`,onClick:r,className:`ml-1 text-xs font-medium text-muted-foreground hover:text-foreground`,children:`Clear all`})]}),dme=[`7d`,`30d`,`year`],i8={today:`Today`,yesterday:`Yesterday`,"7d":`Last 7 days`,"30d":`Last 30 days`,"90d":`Last 90 days`,month:`This month`,quarter:`This quarter`,year:`This year`},fme=({value:e,presets:t=dme,onChange:n})=>(0,V.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(t=>{let r=i8[t];return(0,V.jsx)(`button`,{type:`button`,disabled:!r,title:r?void 0:`The server offers the preset "${t}", which this UI does not know`,onClick:()=>n(e===t?void 0:t),className:B(`h-7 rounded-md border px-2.5 text-xs font-medium transition-colors`,!r&&`border-dashed text-danger-text`,e===t?`border-primary-border bg-primary-soft text-primary-text`:`border-border-strong bg-background text-muted-foreground hover:bg-muted`),children:r??`${t} (unsupported)`},t)})}),a8={facets:{},toggles:[]},o8=(e,t,n)=>{let r=e.facets[t]??[],i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,facets:{...e.facets,[t]:i}}},s8=(e,t)=>({...e,toggles:e.toggles.includes(t)?e.toggles.filter(e=>e!==t):[...e.toggles,t]}),c8=(e,t,n)=>{let{[t]:r,...i}=e.ranges??{};return{...e,ranges:n?{...i,[t]:n}:i}},l8=(e,t)=>e.options.find(e=>e.value===t)?.label??e.labels?.[t]??t,u8=(e,t)=>{let n=e.facets.flatMap(e=>(t.facets[e.id]??[]).map(t=>({key:`facet:${e.id}:${t}`,label:`${e.label}: ${l8(e,t)}`}))),r=(e.ranges??[]).flatMap(e=>{let n=t.ranges?.[e.id];return n?[{key:`range:${e.id}`,label:`${e.label}: ${e.format(n[0])} – ${e.format(n[1])}`}]:[]}),i=t.date?[{key:`date`,label:i8[t.date]??t.date}]:[],a=t.toggles.map(t=>({key:`toggle:${t}`,label:e.toggles?.find(e=>e.id===t)?.label??t}));return[...n,...r,...i,...a]},d8=(e,t)=>{if(t===`date`)return{...e,date:void 0};let[n,r,i]=t.split(`:`);if(n===`range`)return c8(e,r,void 0);if(n===`toggle`)return s8(e,r);if(n===`facet`)return o8(e,r,i);throw Error(`Unknown filter chip key: ${t}`)},f8=(e,t)=>e.toLowerCase().includes(t.trim().toLowerCase()),pme=(e,t)=>e.onSearch?e.options:e.options.filter(e=>f8(e.label,t)),mme=(e,t,n)=>t===0?-1:n===`ArrowDown`?e<0?0:(e+1)%t:e<0?t-1:(e-1+t)%t,hme=({config:e,selected:t,onToggle:n,inline:r=!1})=>{let i=(0,o.useId)(),a=(0,o.useRef)(null),[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(!1),[d,f]=(0,o.useState)(-1),p=r||l,m=pme(e,s),h=(0,o.useRef)(e.onSearch);h.current=e.onSearch,(0,o.useEffect)(()=>()=>h.current?.(``),[]);let g=t=>{c(t),f(-1),e.onSearch?.(t)};return(0,V.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,V.jsxs)(`div`,{className:`flex min-h-8 cursor-text flex-wrap items-center gap-1 rounded-md border border-border-strong bg-background px-2 py-1 shadow-sm focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20`,onClick:()=>a.current?.focus(),children:[(0,V.jsx)(fn,{className:`size-3.5 shrink-0 text-muted-foreground`}),t.map(t=>(0,V.jsxs)(`span`,{className:`inline-flex h-5 max-w-full items-center gap-0.5 rounded bg-primary-soft pl-1.5 pr-0.5 text-xs font-medium text-primary-text`,children:[(0,V.jsx)(`span`,{className:`truncate`,children:l8(e,t)}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Remove ${l8(e,t)}`,className:`rounded p-0.5 hover:bg-primary-border/60`,onMouseDown:e=>e.preventDefault(),onClick:()=>n(t),children:(0,V.jsx)(Qn,{className:`size-3`})})]},t)),(0,V.jsx)(`input`,{ref:a,autoFocus:r,role:`combobox`,"aria-label":e.label,"aria-expanded":p,"aria-controls":`${i}-options`,"aria-autocomplete":`list`,"aria-activedescendant":m[d]?`${i}-${d}`:void 0,placeholder:t.length>0?``:`Search ${e.label.toLowerCase()}`,className:`h-6 min-w-16 flex-1 bg-transparent text-foreground outline-none placeholder:text-faint-foreground`,value:s,onChange:e=>g(e.target.value),onKeyDown:e=>{if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),f(mme(d,m.length,e.key));return}if(e.key===`Enter`&&m[d]){e.preventDefault(),n(m[d].value);return}if(e.key===`Backspace`&&s===``&&t.length>0){n(t[t.length-1]);return}e.key===`Escape`&&s!==``&&(e.stopPropagation(),g(``))},onFocus:()=>u(!0),onBlur:()=>{u(!1),f(-1),!r&&s!==``&&g(``)}})]}),p&&(0,V.jsxs)(`ul`,{id:`${i}-options`,role:`listbox`,"aria-label":e.label,"aria-multiselectable":!0,className:B(`flex max-h-60 flex-col gap-px overflow-y-auto`,!r&&`rounded-md border bg-background p-1 shadow-sm`),children:[m.map((e,r)=>{let a=t.includes(e.value);return(0,V.jsxs)(`li`,{id:`${i}-${r}`,role:`option`,"aria-selected":a,tabIndex:-1,className:B(`flex cursor-pointer items-center gap-2 rounded px-1.5 py-1 hover:bg-muted`,r===d&&`bg-muted`),onMouseDown:e=>e.preventDefault(),onClick:()=>n(e.value),children:[(0,V.jsx)(`span`,{className:B(`inline-flex size-4 shrink-0 items-center justify-center rounded border`,a?`border-primary bg-primary text-primary-foreground`:`border-border-strong bg-background`),children:a&&(0,V.jsx)(he,{className:`size-3`,strokeWidth:3})}),(0,V.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.count!==void 0&&(0,V.jsx)(`span`,{className:`text-xs tabular-nums text-faint-foreground`,children:of(e.count)})]},e.value)}),m.length===0&&(0,V.jsx)(`li`,{className:`px-1.5 py-1 text-xs text-faint-foreground`,children:`No matches`})]})]})},gme=({config:e,selected:t,onToggle:n})=>{let[r,i]=(0,o.useState)(``),a=e.options.filter(e=>f8(e.label,r));return(0,V.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[e.searchable&&(0,V.jsx)(Td,{wrapperClassName:`mb-1 h-7`,leading:(0,V.jsx)(fn,{className:`size-3.5`}),placeholder:`Search ${e.label.toLowerCase()}`,value:r,onChange:e=>i(e.target.value)}),a.map(e=>(0,V.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded px-1 py-1 hover:bg-muted`,children:[(0,V.jsx)(zh,{checked:t.includes(e.value),onChange:()=>n(e.value),label:e.label}),(0,V.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.count!==void 0&&(0,V.jsx)(`span`,{className:`text-xs tabular-nums text-faint-foreground`,children:of(e.count)})]},e.value)),a.length===0&&(0,V.jsx)(`span`,{className:`px-1 py-1 text-xs text-faint-foreground`,children:`No matches`})]})},p8=({label:e,activeCount:t,width:n=240,defaultOpen:r=!1,children:i})=>{let[a,s]=(0,o.useState)(r),[c,l]=(0,o.useState)(!1),u=(0,o.useRef)(null);return(0,o.useLayoutEffect)(()=>{a&&u.current&&l(u.current.getBoundingClientRect().left+n>document.documentElement.clientWidth)},[a,n]),(0,o.useEffect)(()=>{if(!a)return;let e=e=>{e.target instanceof Node&&!u.current?.contains(e.target)&&s(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[a]),(0,V.jsxs)(`div`,{ref:u,className:`relative`,children:[(0,V.jsxs)(`button`,{type:`button`,"aria-expanded":a,onClick:()=>s(!a),className:B(`inline-flex h-8 items-center gap-1.5 rounded-md border bg-background px-2.5 font-medium shadow-sm transition-colors hover:bg-muted`,t>0?`border-primary-border text-primary-text`:`border-border-strong text-foreground`),children:[e,t>0&&(0,V.jsx)(`span`,{className:`rounded-full bg-primary px-1.5 text-[11px] leading-4 text-primary-foreground`,children:t}),(0,V.jsx)(_e,{className:`size-3.5 text-muted-foreground`})]}),a&&(0,V.jsx)(`div`,{className:B(`absolute top-full z-30 mt-1.5 rounded-lg border bg-background p-3 shadow-pop`,c?`right-0`:`left-0`),style:{width:n},children:i})]})},m8=({title:e,children:t})=>(0,V.jsxs)(`section`,{className:`flex flex-col gap-2 border-b py-3 last:border-b-0`,children:[(0,V.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:e}),t]}),h8=(e,t)=>{let[n,r]=(0,o.useState)(e);return(0,o.useEffect)(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n},_me=(e,t,n,r,i)=>{let a=n+(r-n)*e/t;return n+(r-n)*(e+1)/t>i[0]&&a<i[1]},g8=(e,t,n)=>n===t?0:(e-t)/(n-t),vme=(e,t,n)=>t===0?[Math.min(n,e[1]),e[1]]:[e[0],Math.max(n,e[0])],yme=1e3,bme=({config:e,value:t,onChange:n})=>{let{min:r,max:i,step:a,histogram:s,format:c}=e,[l,u]=(0,o.useState)(),d=l??t??[r,i],f=Math.max(...s),p=()=>{l&&(u(void 0),n(l[0]===r&&l[1]===i?void 0:l))},m=h8(l,yme);return(0,o.useEffect)(()=>{m&&p()},[m]),(0,V.jsxs)(`div`,{className:`w-full`,children:[(0,V.jsxs)(`div`,{className:`px-[7px]`,children:[s.length>0&&(0,V.jsx)(`div`,{className:`mb-1 flex h-12 items-end gap-0.5`,children:s.map((e,t)=>(0,V.jsx)(`span`,{className:B(`flex-1 rounded-t-sm`,_me(t,s.length,r,i,d)?`bg-primary/70`:`bg-border`),style:{height:`${Math.max(6,e/f*100)}%`}},t))}),(0,V.jsxs)(`div`,{className:`relative h-4`,children:[(0,V.jsx)(`span`,{className:`absolute inset-x-0 top-1/2 h-1 -translate-y-1/2 rounded-full bg-border`}),(0,V.jsx)(`span`,{className:`absolute top-1/2 h-1 -translate-y-1/2 rounded-full bg-primary`,style:{left:`${g8(d[0],r,i)*100}%`,right:`${100-g8(d[1],r,i)*100}%`}})]})]}),(0,V.jsx)(`div`,{className:`relative -mt-4 h-4`,children:[0,1].map(t=>(0,V.jsx)(`input`,{type:`range`,className:`pb-range`,"aria-label":`${e.label} ${t===0?`minimum`:`maximum`}`,min:r,max:i,step:a,value:d[t],onChange:e=>u(vme(d,t,Number(e.target.value))),onPointerUp:p,onTouchEnd:p,onBlur:p},t))}),(0,V.jsxs)(`div`,{className:`mt-2 flex justify-between text-xs tabular-nums text-muted-foreground`,children:[(0,V.jsx)(`span`,{children:c(d[0])}),(0,V.jsx)(`span`,{children:c(d[1])})]})]})},_8=({label:e,checked:t,onChange:n})=>(0,V.jsxs)(`label`,{className:`flex cursor-pointer items-center justify-between gap-3 py-1`,children:[(0,V.jsx)(`span`,{children:e}),(0,V.jsx)(mS,{checked:t,onChange:n,label:e})]}),v8=(e,t)=>e.some(e=>e.length>0)||!!t,y8=({groups:e,trailing:t})=>{if(!v8(e,t))return null;let n=e.filter(e=>e.length>0);return(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n.map((e,t)=>(0,V.jsxs)(o.Fragment,{children:[t>0&&(0,V.jsx)(`span`,{className:`mx-1 h-5 w-px bg-border`}),e]},t)),t&&(0,V.jsx)(`div`,{className:`flex min-w-32 flex-1 justify-end`,children:t})]})},xme=(e,t,n)=>{let[r,i]=(0,o.useState)(t??a8);return[e??r,e=>{i(e),n?.(e)}]},b8=({config:e,layout:t,value:n,defaultValue:r,onChange:i,lockedLabels:a,defaultOpenMenu:s,fullWidth:c,leading:l,trailing:u})=>{let[d,f]=xme(n,r,i),p=u8(e,d),m=(0,V.jsx)(r8,{chips:p,lockedLabels:a,onRemove:e=>f(d8(d,e)),onClear:()=>f(a8)}),h=(e,t=!1)=>{let n=d.facets[e.id]??[],r=t=>f(o8(d,e.id,t));return e.combobox?(0,V.jsx)(hme,{config:e,selected:n,onToggle:r,inline:t}):(0,V.jsx)(gme,{config:e,selected:n,onToggle:r})},g=e.ranges??[],_=e=>(0,V.jsx)(bme,{config:e,value:d.ranges?.[e.id],onChange:t=>f(c8(d,e.id,t))}),v=e.datePresets&&(0,V.jsx)(fme,{value:d.date,presets:Array.isArray(e.datePresets)?e.datePresets:void 0,onChange:e=>f({...d,date:e})}),y=(e.toggles??[]).map(e=>(0,V.jsx)(_8,{label:e.label,checked:d.toggles.includes(e.id),onChange:()=>f(s8(d,e.id))},e.id));if(t===`panel`)return(0,V.jsxs)(`aside`,{className:c?`flex w-full flex-col gap-1`:`flex w-64 shrink-0 flex-col gap-1 overflow-y-auto rounded-lg border bg-background px-4 py-3`,children:[(0,V.jsx)(`div`,{className:`flex items-center justify-between pb-1`,children:(0,V.jsx)(`h2`,{className:`font-semibold`,children:`Filters`})}),(p.length>0||(a?.length??0)>0)&&(0,V.jsx)(`div`,{className:`border-b pb-3`,children:m}),l,e.facets.map(e=>(0,V.jsx)(m8,{title:e.label,children:h(e)},e.id)),g.map(e=>(0,V.jsx)(m8,{title:e.label,children:_(e)},e.id)),v&&(0,V.jsx)(m8,{title:`Date`,children:v}),y.length>0&&(0,V.jsx)(m8,{title:`Show only`,children:y})]});let b=[...e.facets.map(e=>(0,V.jsx)(p8,{label:e.label,activeCount:(d.facets[e.id]??[]).length,width:e.combobox?280:void 0,defaultOpen:s===e.id,children:h(e,!0)},e.id)),...g.map(e=>(0,V.jsx)(p8,{label:e.label,activeCount:+!!d.ranges?.[e.id],width:280,defaultOpen:s===e.id,children:_(e)},`range:${e.id}`)),...v?[(0,V.jsx)(o.Fragment,{children:v},`date`)]:[]],x=(e.toggles??[]).map(e=>(0,V.jsx)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:(0,V.jsx)(_8,{label:e.label,checked:d.toggles.includes(e.id),onChange:()=>f(s8(d,e.id))})},e.id)),S=[l?[(0,V.jsx)(o.Fragment,{children:l},`leading`)]:[],b,x];return!v8(S,u)&&p.length===0&&!a?.length?null:(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsx)(y8,{groups:S,trailing:u}),m]})},x8=uo(),S8={start:0,end:0},C8={"7d":{amount:7,unit:`d`},"30d":{amount:30,unit:`d`},"90d":{amount:90,unit:`d`}},Sme=e=>new Date(e).toISOString().replace(`.000Z`,`Z`),w8=(e,t)=>{let[n,r,i]=[t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()];return Sme(e===`year`?Date.UTC(n,0,1):e===`quarter`?Date.UTC(n,Math.floor(r/3)*3,1):e===`month`?Date.UTC(n,r,1):e===`yesterday`?Date.UTC(n,r,i-1):Date.UTC(n,r,i))},T8=[`year`,`quarter`,`month`,`yesterday`,`today`],E8=(e,t)=>t===`date`?{kind:`string`,value:e.slice(0,10),span:S8}:{kind:`timestamp`,value:e,span:S8},Cme=(e,t,n,r)=>{if(t in C8)return[x8.gte(e,x8.ago(t))];let i=x8.gte(e,E8(w8(t,n),r));return t===`yesterday`?[i,x8.lt(e,E8(w8(`today`,n),r))]:[i]},wme=(e,t,n=new Date)=>{let r=e.facets.flatMap(e=>{let n=t.facets[e.id]??[];if(n.length===0)return[];if(e.flags){let t=e.options.filter(e=>n.includes(e.value)).map(e=>x8.eq(e.value,!0));return t.length===0?[]:[t.length===1?t[0]:x8.or(...t)]}return[n.length===1?x8.eq(e.id,n[0]):x8.in(e.id,n)]}),i=(e.ranges??[]).flatMap(e=>{let n=t.ranges?.[e.id];return n?[x8.gte(e.id,n[0]),x8.lte(e.id,n[1])]:[]}),a=e.dateField&&t.date?Cme(e.dateField,t.date,n,e.dateKind):[],o=(e.toggles??[]).filter(e=>t.toggles.includes(e.id)).map(e=>x8.eq(e.id,!0));return[...r,...i,...a,...o]},Tme=e=>e.length===0?``:Ya(x8.and(...e)),D8=(e,t,n=[],r=new Date)=>Tme([...wme(e,t,r),...n]),O8=e=>e.kind===`and`?e.args.flatMap(O8):[e],k8=e=>e.field.path.join(`.`),Eme=e=>e.kind===`compare`&&e.op===`=`&&e.value.kind===`boolean`&&e.value.value,Dme=(e,t)=>{let n=e.kind===`or`?e.args:[e];if(!n.every(Eme))return;let r=n.map(k8),i=t.get(r[0]);return i!==void 0&&r.every(e=>t.get(e)===i)?{group:i,fields:r}:void 0},A8=e=>e.kind===`number`?String(e.raw):e.kind===`string`?String(e.value):void 0,j8=(e,t)=>{let n=e.value;if(n.kind===`now`&&n.offset?.sign===`-`){let{amount:e,unit:t}=n.offset.duration;return Object.entries(C8).find(([,n])=>n.amount===e&&n.unit===t)?.[0]}if(n.kind===`timestamp`)return T8.find(e=>w8(e,t)===n.value);if(n.kind===`string`)return T8.find(e=>w8(e,t).slice(0,10)===n.value)},M8=(e,t,n=new Date)=>{let r=Ca(t);if(!r.ok)return{ok:!1,errors:r.errors};let i={facets:{},toggles:[]},a=[],o=new Set(e.facets.filter(e=>!e.flags).map(e=>e.id)),s=new Map(e.facets.filter(e=>e.flags).flatMap(e=>e.options.map(t=>[t.value,e.id]))),c=new Set((e.toggles??[]).map(e=>e.id)),l=new Set((e.ranges??[]).map(e=>e.id)),u=new Map,d,f;for(let t of r.ast?O8(r.ast):[]){let r=Dme(t,s);if(r&&!i.facets[r.group])i.facets[r.group]=r.fields;else if(t.kind===`compare`&&o.has(k8(t))&&t.op===`=`&&A8(t.value)!==void 0)i.facets[k8(t)]=[...i.facets[k8(t)]??[],A8(t.value)];else if(t.kind===`in`&&o.has(k8(t))&&t.values.every(e=>A8(e)!==void 0))i.facets[k8(t)]=[...i.facets[k8(t)]??[],...t.values.map(e=>A8(e))];else if(t.kind===`compare`&&e.dateField===k8(t)&&t.op===`>=`&&j8(t,n)&&!i.date)i.date=j8(t,n),d=t;else if(t.kind===`compare`&&e.dateField===k8(t)&&t.op===`<`&&(t.value.kind===`timestamp`||t.value.kind===`string`)&&w8(`today`,n).startsWith(t.value.value.slice(0,10)))f=t;else if(t.kind===`compare`&&c.has(k8(t))&&t.op===`=`&&t.value.kind===`boolean`&&t.value.value)i.toggles.push(k8(t));else if(t.kind===`compare`&&l.has(k8(t))&&(t.op===`>=`||t.op===`<=`)&&t.value.kind===`number`){let e=u.get(k8(t))??{clauses:[]};t.op===`>=`?e.low=t.value.value:e.high=t.value.value,e.clauses.push(t),u.set(k8(t),e)}else a.push(t)}i.date===`yesterday`&&!f&&(a.push(d),i.date=void 0),f&&i.date!==`yesterday`&&a.push(f);for(let[e,t]of u)t.low!==void 0&&t.high!==void 0?i.ranges={...i.ranges,[e]:[t.low,t.high]}:a.push(...t.clauses);return{ok:!0,state:i,extras:a}},Ome=[`integer`,`bigint`,`decimal`],kme=(e,t)=>{let n=e?.fields[t]?.type;return n!==void 0&&Ome.includes(n)},N8=(e,t)=>e.kind===`range`||e.kind===`facets`&&kme(t,e.field),Ame=e=>({id:e,label:e,min:0,max:0,step:1,histogram:[],format:String}),P8=(e,t)=>{let n=e?.filters??[],r=n.find(e=>e.kind===`dateRange`);return{facets:n.flatMap(e=>e.kind===`facets`&&!N8(e,t)?[{id:e.field,label:e.field,options:[],searchable:e.search,...t?.fields[e.field]?.type===`relation`&&{combobox:!0}}]:e.kind===`flags`?[{id:e.fields.join(`|`),label:e.label,options:e.fields.map(e=>({value:e,label:e,count:0})),flags:!0}]:[]),ranges:n.flatMap(e=>e.kind!==`flags`&&N8(e,t)?[Ame(e.field)]:[]),...r&&{dateField:r.field,dateKind:t?.fields[r.field]?.type===`date`?`date`:`timestamp`,...r.presets.length>0&&{datePresets:r.presets}},toggles:n.flatMap(e=>e.kind===`toggle`?[{id:e.field,label:e.field}]:[])}},F8=(e,t)=>(e?.filters??[]).some(e=>e.kind===`range`&&e.field===t&&e.histogram),I8=(e,t)=>{let n=e?.fields[t],r=n?.suffix??``;return e=>`${n?.prefix===`€`?rf(e*100).replace(`.00`,``):String(e)}${r}`},L8=uo(),jme={start:0,end:0},Mme=(e,t,n)=>{let r=M8(P8(t,e),n);return r.ok?Object.fromEntries(Object.entries(r.state.facets).filter(([t,n])=>e.fields[t]?.type===`relation`&&n.length>0)):{}},Nme=(e,t,n)=>{let r=e=>t?.fields[e]?.label??K(e),i=P8(t,e);return{...i,facets:i.facets.map(i=>{if(i.flags)return{...i,options:i.options.map(e=>({...e,label:r(e.value)}))};let a=e.fields[i.id]?.enumValues??[],o=e.fields[i.id]?.type===`enum`?Object.fromEntries(a.map(e=>[e,rs(e,t?.fields[i.id]?.valueLabels)])):n[i.id]??{};return{...i,label:r(i.id),labels:o}}),ranges:(i.ranges??[]).map(e=>({...e,label:r(e.id),format:I8(t,e.id)})),toggles:i.toggles?.map(e=>({...e,label:r(e.id)}))}},R8=(e,t,n,r={})=>{let i=Nme(e,t,r),a=M8(i,n);if(!a.ok)return[{key:`unreadable`,label:`A filter that cannot be read`}];let o=a.extras.map((e,t)=>({key:`extra:${t}`,label:e.kind===`search`?`"${e.text}"`:Ya(e)}));return[...u8(i,a.state),...o]},Pme=e=>Object.fromEntries(e.facets.filter(e=>!e.flags).map(e=>[e.id,{...e.labels,...Object.fromEntries(e.options.map(e=>[e.value,e.label]))}])),Fme=(e,t,n)=>{if(typeof n!=`string`||n===``)return e;let r=L8.gt(t,{kind:`timestamp`,value:new Date(n).toISOString(),span:jme}),i=Ca(e);if(!i.ok)throw Error(`The saved filter cannot be read: ${i.errors.map(e=>e.message).join(`; `)}`);return Ya(i.ast?L8.and(i.ast,r):r)},Ime=(e,t)=>typeof t!=`string`||t===``?!0:typeof e!=`string`||e===``?!1:new Date(e).getTime()>new Date(t).getTime(),z8=(e,t)=>{let n=G(),r=Wp(),{resources:i,views:a}=q(),o=a[e.name],s=Object.entries(Mme(e,o,t)),c=gh({queries:s.map(([t,o])=>{let s=i[e.fields[t].relation.resource];return{queryKey:W.labels(`chips:${e.name}.${t}`,o.join(`,`)),enabled:s!==void 0,queryFn:async()=>Object.fromEntries(await D4(r,n,s,o,a[s.name]))}})});return R8(e,o,t,Object.fromEntries(s.flatMap(([e],t)=>c[t]?.data?[[e,c[t].data]]:[])))},Lme=(e,t)=>({record:Object.fromEntries(Object.entries(t).filter(([t])=>Object.hasOwn(e.fields,t))),etag:typeof t.etag==`string`?t.etag:``,...typeof t.permissions==`object`&&t.permissions!==null&&{permissions:t.permissions}}),B8=e=>{let t=Wp();return(0,o.useCallback)(n=>t.setQueryData(W.recordPreview(e.name,Ao(jg(e,n))),Lme(e,n)),[t,e])},V8={wallet:lee,"file-text":it,send:see,ruler:aee,bed:ee,bath:M,house:ut,"door-open":eee,"land-plot":vt,leaf:tee,tag:Pn,key:gt,calendar:de,heart:ct,bell:te,bookmark:oe,"external-link":Je},H8=e=>e!==void 0&&Object.hasOwn(V8,e)?V8[e]:void 0,U8=({benefits:e})=>e&&e.length>0?(0,V.jsx)(`ul`,{className:`flex flex-col gap-2 text-left`,children:e.map(e=>(0,V.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,V.jsx)(he,{className:`mt-0.5 size-4 shrink-0 text-primary`,"aria-hidden":!0}),e]},e))}):null,W8=({prompt:e})=>{let{canSignUp:t}=H(),{link:n}=Bh(),r=Sf({variant:`primary`}),i=e.signUp?(0,V.jsx)(`a`,{href:e.signUp.href,target:`_blank`,rel:`noreferrer`,className:r,children:e.signUp.label}):t&&(0,V.jsx)(Nu,{to:n(`sign-up`),className:r,children:`Create an account`});return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Nu,{to:n(),className:i?Sf():r,children:`Sign in`}),i]})},G8=e=>{let{prompt:t}=e,n=(0,o.useId)();if(e.as===`dialog`)return(0,V.jsx)(h_,{title:t.title,description:t.description,open:e.open,onClose:e.onClose,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:e.onClose,children:`Not now`}),(0,V.jsx)(W8,{prompt:t})]}),children:(0,V.jsx)(U8,{benefits:t.benefits})});let r=H8(t.icon)??Ft;return(0,V.jsxs)(`section`,{"aria-labelledby":n,className:`mx-auto flex w-full max-w-md flex-col items-center gap-4 px-5 py-10 text-center sm:py-16`,children:[(0,V.jsx)(`span`,{className:`flex size-12 items-center justify-center rounded-full bg-primary/10 text-primary`,children:(0,V.jsx)(r,{className:`size-6`,"aria-hidden":!0})}),(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsx)(`h1`,{id:n,className:`text-lg font-semibold`,children:t.title}),(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:t.description})]}),(0,V.jsx)(U8,{benefits:t.benefits}),(0,V.jsx)(`div`,{className:`mt-2 flex w-full flex-col-reverse gap-2 sm:w-auto sm:flex-row sm:justify-center [&>*]:min-h-11 sm:[&>*]:min-h-0`,children:(0,V.jsx)(W8,{prompt:t})})]})},Rme=uo(),K8=e=>{if(typeof e==`string`||typeof e==`number`)return e;if(e&&typeof e==`object`&&`id`in e)return K8(e.id)},zme=(e,t,n)=>n.flatMap(n=>{let r=K8(n[t]);return r===void 0?[]:[{key:Ao(jg(e,n)),target:r}]}),Bme=(e,t)=>e.find(e=>Ao(e.target)===t),Vme=(e,t)=>[...e,{key:``,target:t}],Hme=(e,t)=>e.filter(e=>Ao(e.target)!==t),q8=(e,t)=>{let[n]=e.primaryKey;if(e.primaryKey.length!==1||n===void 0)throw Error(`${e.name} has a composite key, so its saved records cannot be listed`);let r=[...new Set(t.map(e=>e.target))];return r.length===0?void 0:Rme.in(n,r)},J8=(e,t)=>W.list(e,``,``,500,`saved:${t}`),Y8=(e,t,n)=>{let r=G(),i=q().resources[e];return vh({queryKey:J8(e,t),enabled:n&&i!==void 0,queryFn:async()=>{let n=[],a;do{let o=await r.list(e,{pageSize:500,fields:[...i.primaryKey,t],...a&&{pageToken:a}});n.push(...o.items),a=o.nextPageToken||void 0}while(a);return zme(i,t,n)}})},Ume=e=>e instanceof Error?e.message:`Something went wrong`,Wme=(e,t,n)=>{let r=q(),i=G(),a=Wp(),o=Lg(),s=Xw(),{resource:c,field:l}=e,u=r.permissions[c],d=r.resources[c]!==void 0&&u!==void 0&&Fw(u,`create`)&&Fw(u,`delete`),f=r.signIn?.[c]?.signIn,p=Y8(c,l,d),m=p.data&&Bme(p.data,t),h=J8(c,l),g=yh({mutationFn:async e=>{e?await i.remove(c,e.key):await i.create(c,{[l]:n})},onMutate:async e=>{await a.cancelQueries({queryKey:h,exact:!0});let r=a.getQueryData(h);return a.setQueryData(h,(r=[])=>e?Hme(r,t):Vme(r,n)),{before:r}},onError:(e,t,n)=>{a.setQueryData(h,n?.before),o.show({state:`error`,title:t?`Could not take it off`:`Could not save it`,description:Ume(e)})},onSettled:()=>s(c)});return{mode:d?`save`:f?`sign-in`:void 0,prompt:f,saved:m!==void 0,ready:p.data!==void 0&&!g.isPending,toggle:()=>g.mutate(m)}},Gme=({favorite:e,recordKey:t,target:n,className:r})=>{let i=Wme(e,t,n),[a,s]=(0,o.useState)(!1);if(!i.mode)return null;let c=e.label??`Favorite`,l=B(`absolute right-2 top-2 flex size-8 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,r);return i.mode===`sign-in`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":c,"aria-haspopup":`dialog`,className:l,onClick:()=>s(!0),children:(0,V.jsx)(ct,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsx)(G8,{as:`dialog`,prompt:i.prompt,open:a,onClose:()=>s(!1)})]}):(0,V.jsx)(`button`,{type:`button`,"aria-label":c,"aria-pressed":i.saved,"aria-disabled":!i.ready,className:l,onClick:()=>i.ready&&i.toggle(),children:(0,V.jsx)(ct,{className:B(`size-4`,i.saved&&`fill-current text-danger`),"aria-hidden":!0})})},X8=6,Kme=(e,t,n)=>{let r=e.bottom+X8;return{top:r+t.height>n.height-X8?Math.max(X8,e.top-X8-t.height):r,left:Math.max(X8,Math.min(e.left,n.width-X8-t.width))}},Z8=(e,t)=>{let n=oC(e).find(e=>e.kind===`cards`);if(!n)return{kind:`cards`,name:`dot`,badge:t};let{photos:r,favorite:i,dots:a,...o}=n;return o},qme=(e,t,n,r)=>(e?.list?.relatedColumns??[]).filter(e=>r.includes(e.name)).flatMap(e=>{let r=t[e.resource];return r?[{column:e,fields:SC(r,n[r.name],Z8(n[r.name],e.status))}]:[]}),Jme=(e,{values:t,label:n,singular:r,plural:i})=>{if(e.length===0)return`No ${i}`;let a=new Map;for(let t of e)t!=null&&a.set(String(t),(a.get(String(t))??0)+1);let o=[...t,...[...a.keys()].filter(e=>!t.includes(e))].filter(e=>a.has(e)).map(e=>`${a.get(e)} ${n(e)}`),s=`${e.length} ${e.length===1?r:i}`;return o.length===0?s:`${s}: ${o.join(`, `)}`},Q8=`flex shrink-0 items-center justify-center rounded-full p-0.5 pointer-coarse:p-1.5`,$8=`size-2.5 rounded-full`,e5=`flex min-w-0 items-center gap-0.5`,Yme=150,t5=288,Xme=({shown:e,row:t,target:n,view:r,column:i,Card:a,onEnter:s,onLeave:c})=>{let l=(0,o.useRef)(null),[u,d]=(0,o.useState)();return(0,o.useLayoutEffect)(()=>{l.current&&d(Kme(e.dot,{width:t5,height:l.current.offsetHeight},{width:window.innerWidth,height:window.innerHeight}))},[e]),(0,tr.createPortal)((0,V.jsx)(`div`,{ref:l,"data-dot-card":!0,onMouseEnter:s,onMouseLeave:c,style:{width:t5,...u??{visibility:`hidden`,top:0,left:0}},className:`fixed z-50 rounded-lg shadow-pop`,children:(0,V.jsx)(a,{model:n,view:r,display:Z8(r,i.status),row:t})}),document.body)},n5=({column:e,records:t,target:n,view:r,wrap:i=!1,Card:a})=>{let s=(0,o.useMemo)(()=>t.map(e=>EC(n,e)),[t,n]),[c,l]=(0,o.useState)(),u=(0,o.useRef)(void 0),d=(0,o.useRef)(`mouse`),f=(0,o.useRef)(null),p=n.fields[e.status],m=r?.fields[e.status],h=t=>p?ZS(p,t.record[e.status],m):``,g=Dg(n,r),_=e=>e.labels[g]??String(e.record[g]??e.key),v=(r?.names?.singular??K(n.name)).toLowerCase(),y=(r?.names?.plural??K(n.name)).toLowerCase(),b=Jme(s.map(t=>t.record[e.status]),{values:p?.enumValues??[],label:e=>p?ZS(p,e,m):e,singular:v,plural:y}),x=()=>window.clearTimeout(u.current),S=()=>{x(),u.current=window.setTimeout(()=>l(void 0),Yme)},C=(e,t)=>{x(),l({key:e,dot:t.getBoundingClientRect()})};(0,o.useEffect)(()=>x,[]),(0,o.useEffect)(()=>{if(!c)return;let e=()=>l(void 0),t=t=>t.key===`Escape`&&e(),n=t=>{let n=t.target;!f.current?.contains(n)&&!n?.closest?.(`[data-dot-card]`)&&e()};return document.addEventListener(`keydown`,t),document.addEventListener(`pointerdown`,n),document.addEventListener(`scroll`,e,!0),window.addEventListener(`resize`,e),()=>{document.removeEventListener(`keydown`,t),document.removeEventListener(`pointerdown`,n),document.removeEventListener(`scroll`,e,!0),window.removeEventListener(`resize`,e)}},[c]);let w=e=>t=>{d.current===`touch`&&c?.key!==e&&(t.preventDefault(),C(e,t.currentTarget))},T=e=>{e.relatedTarget?.closest?.(`[data-dot-card]`)||S()},E=c&&s.find(e=>e.key===c.key);return(0,V.jsxs)(`div`,{ref:f,className:B(e5,i&&`pointer-events-none flex-wrap`),onClick:e=>e.stopPropagation(),onPointerDown:e=>d.current=e.pointerType,children:[(0,V.jsx)(`span`,{className:`sr-only`,children:b}),s.map(t=>{let r=t.record[e.status],i=j4(m?.valueColors,r);return(0,V.jsx)(FC,{to:{kind:`record`,resource:n.name,key:t.key},"aria-label":`${_(t)}, ${h(t)}`,onPointerEnter:e=>e.pointerType!==`touch`&&C(t.key,e.currentTarget),onPointerLeave:e=>e.pointerType!==`touch`&&S(),onFocus:e=>e.currentTarget.matches(`:focus-visible`)&&C(t.key,e.currentTarget),onBlur:T,onClick:w(t.key),className:B(Q8,`pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40`),children:(0,V.jsx)(`span`,{"aria-hidden":!0,style:i===void 0?void 0:{backgroundColor:i},className:B($8,i===void 0&&Yu[HS(String(r))],c?.key===t.key&&`ring-2 ring-foreground/30`)})},t.key)}),c&&E&&(0,V.jsx)(Xme,{shown:c,row:E,target:n,view:r,column:e,Card:a,onEnter:x,onLeave:S})]})},Zme=({count:e})=>(0,V.jsx)(`span`,{"aria-hidden":!0,className:B(e5,`invisible flex-wrap`),children:Array.from({length:e},(e,t)=>(0,V.jsx)(`span`,{className:Q8,children:(0,V.jsx)(`span`,{className:$8})},t))}),r5=`flex flex-col gap-1.5`,Qme=({dots:e})=>(0,V.jsx)(`span`,{className:r5,children:e.map(({column:e,records:t})=>(0,V.jsx)(Zme,{count:t.length},e.name))}),$me=({dots:e,Card:t})=>{let{resources:n,views:r}=q();return(0,V.jsx)(`div`,{className:`pointer-events-none absolute inset-x-[calc(0.75rem+1px)] bottom-[calc(0.75rem+1px)] ${r5}`,children:e.map(({column:e,records:i})=>{let a=n[e.resource];return a&&(0,V.jsx)(n5,{column:e,records:i,target:a,view:r[a.name],Card:t,wrap:!0},e.name)})})},ehe=(e,t,n)=>(t.dots??[]).flatMap(t=>{let r=e?.list?.relatedColumns?.find(e=>e.name===t),i=n.record[t];return r&&Array.isArray(i)&&i.length>0?[{column:r,records:i}]:[]}),i5=({value:e})=>{let t=Vx(e,{width:320,height:240});return t?(0,V.jsx)($C,{image:t,loading:`lazy`,className:`size-full object-cover`}):null},a5=({children:e})=>(0,V.jsx)(`span`,{className:`-mx-3 -mt-3 mb-1.5 block aspect-[4/3] overflow-hidden rounded-t-lg border-b border-border bg-muted`,children:e}),the=({value:e})=>(0,V.jsx)(a5,{children:(0,V.jsx)(i5,{value:e})}),nhe=10,rhe=(e,t)=>{let n=jx(e)?e.uri:void 0,r=t.filter(e=>jx(e)&&e.uri!==n);return(n===void 0?r:[e,...r]).slice(0,nhe)},ihe=(e,t)=>t===0?0:(e%t+t)%t,ahe=(e,t,n)=>t<=0||n===0?0:Math.min(n-1,Math.max(0,Math.round(e/t))),o5=`pointer-events-auto absolute top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm opacity-0 transition-opacity group-has-[[data-card-photos]:hover]/card:opacity-100 group-hover/arrows:opacity-100 group-has-[:focus-visible]/arrows:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,s5=`[@media(hover:none)]:opacity-100`,ohe=({photos:e,cover:t,swipe:n=!0,children:r})=>{let i=(0,o.useRef)(null),a=(0,o.useRef)(void 0),[s,c]=(0,o.useState)(0),l=rhe(t,e),u=e=>{let t=i.current;t&&t.scrollTo({left:e*t.clientWidth})},d=e=>{a.current=ihe((a.current??s)+e,l.length),u(a.current)},f=()=>{a.current=void 0},p=e=>{c(ahe(e.scrollLeft,e.clientWidth,l.length)),a.current!==void 0&&Math.abs(e.scrollLeft-a.current*e.clientWidth)<1&&(a.current=void 0)},m=(0,V.jsx)(a5,{children:(0,V.jsx)(`span`,{ref:i,tabIndex:-1,"data-card-photos":!0,onPointerDown:f,onScroll:e=>p(e.currentTarget),className:B(`flex size-full snap-x snap-mandatory outline-none [scrollbar-width:none] motion-safe:scroll-smooth [&::-webkit-scrollbar]:hidden`,n?`overflow-x-auto overscroll-x-contain`:`overflow-x-hidden`),children:l.map((e,t)=>(0,V.jsx)(`span`,{className:`block size-full shrink-0 snap-start snap-always`,children:(0,V.jsx)(i5,{value:e})},t))})});return(0,V.jsxs)(V.Fragment,{children:[r(m),l.length>1&&(0,V.jsxs)(`div`,{className:`group/arrows pointer-events-none absolute inset-x-px top-px aspect-[4/3]`,children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":`Previous photo`,className:B(o5,!n&&s5,`left-2`),onClick:()=>d(-1),children:(0,V.jsx)(ye,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Next photo`,className:B(o5,!n&&s5,`right-2`),onClick:()=>d(1),children:(0,V.jsx)(xe,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsxs)(`span`,{className:`absolute inset-x-0 bottom-2 flex justify-center`,"aria-live":`polite`,children:[(0,V.jsx)(`span`,{className:`sr-only`,children:`Photo ${s+1} of ${l.length}`}),(0,V.jsx)(`span`,{className:`flex items-center gap-1 rounded-full bg-background/70 px-1.5 py-1 leading-none`,"aria-hidden":!0,children:l.map((e,t)=>(0,V.jsx)(`span`,{className:B(`size-1.5 rounded-full`,t===s?`bg-foreground`:`bg-foreground/35`)},t))})]})]})]})},she=({icon:e,children:t})=>{let n=H8(e);return(0,V.jsxs)(`dd`,{className:`flex items-center gap-1 tabular-nums`,children:[n&&(0,V.jsx)(n,{className:`size-3.5 shrink-0`,"aria-hidden":!0}),t]})},c5=({model:e,view:t,display:n,row:r,swipe:i=!0,mark:a})=>{let{image:o,title:s,subtitle:c,amount:l,badge:u,meta:d,footer:f,flags:p}=_C(e,t,n),m=e=>t?.fields[e]?.label??K(e),h=n=>{let i=e.fields[n];if(!i)return``;let a=r.record[n];return r.labels[n]===void 0&&BS(i,t?.fields[n])&&typeof a==`string`&&a!==``?zS(a):r.labels[n]??ZS(i,a,t?.fields[n])},{fields:g,components:_}=Zg(),v=B8(e),y=n.card===void 0?void 0:_?.[n.card],b=n=>{let i=e.fields[n],a=i&&rw(g,i,t?.fields[n]);return a?(0,V.jsx)(ow,{shown:a,part:`display`,field:i,value:r.record[n],fallback:h(n)}):h(n)},x=n=>{let i=e.fields[n],a=r.record[n];return!i||!BS(i,t?.fields[n])||rw(g,i,t?.fields[n])||typeof a!=`string`||a===``?b(n):(0,V.jsx)(cw,{source:a,inLink:!0})},S=n=>{let i=e.fields[n],a=t?.fields[n],o=r.record[n];return!i||a?.format!==`badge`||rw(g,i,a)||o==null||o===``?b(n):(0,V.jsx)(M4,{value:o,hints:a,children:h(n)})},C=n=>{let i=e.fields[n];if(!i)return;if(r.labels[n]!==void 0||rw(g,i,t?.fields[n]))return(0,V.jsx)(`strong`,{className:`font-semibold text-foreground`,children:b(n)});let a=bC(i,r.record[n],t?.fields[n]);return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`strong`,{className:`font-semibold text-foreground`,children:a.amount}),a.suffix]})},w=y?void 0:n.photos,T=u===void 0?void 0:r.record[u],E=p.filter(e=>r.record[e]===!0),D=o===void 0?void 0:r.record[o],O=yC(r,l),k=vC(r,f),A=o!==void 0||w!==void 0,j=n.favorite,M=y?[]:ehe(t,n,r),N=e=>(0,V.jsxs)(V.Fragment,{children:[A&&e,(0,V.jsxs)(`span`,{className:`flex items-start justify-between gap-2 ${j&&!A?`pr-8`:``}`,children:[(0,V.jsx)(`span`,{className:`min-w-0 truncate font-medium`,children:b(s)}),u!==void 0&&T!=null&&(0,V.jsx)(M4,{value:T,hints:t?.fields[u],children:h(u)})]}),c!==void 0&&(0,V.jsx)(`span`,{className:t?.fields[c]?.markdown?`line-clamp-3 break-words text-muted-foreground`:t?.fields[c]?.multiline?`line-clamp-3 whitespace-pre-line break-words text-muted-foreground`:`truncate text-muted-foreground`,children:x(c)}),O!==void 0&&(0,V.jsx)(`span`,{className:`truncate tabular-nums text-muted-foreground`,children:C(O)}),d.length>0&&(0,V.jsx)(`dl`,{className:`mt-auto flex flex-wrap items-center gap-x-3 gap-y-0.5 pt-1 text-xs text-muted-foreground`,children:vC(r,d).map(e=>(0,V.jsxs)(`div`,{className:`flex gap-1`,children:[(0,V.jsx)(`dt`,{className:`sr-only`,children:m(e)}),(0,V.jsx)(she,{icon:t?.fields[e]?.icon,children:S(e)})]},e))}),E.length>0&&(0,V.jsx)(`ul`,{className:`flex flex-wrap gap-1`,"aria-label":`Features`,children:E.map(e=>(0,V.jsx)(`li`,{children:(0,V.jsx)(Zu,{dot:!1,children:m(e)})},e))}),k.length>0&&(0,V.jsx)(`span`,{className:`truncate text-xs text-muted-foreground ${d.length>0?``:`mt-auto`}`,children:k.map((e,t)=>(0,V.jsxs)(`span`,{children:[t>0&&(0,V.jsx)(`span`,{"aria-hidden":!0,children:` • `}),b(e)]},e))}),M.length>0&&(0,V.jsx)(Qme,{dots:M})]}),ee=t=>(0,V.jsxs)(FC,{to:{kind:`record`,resource:e.name,key:r.key},onClick:()=>v(r.record),className:`flex h-full flex-col gap-1.5 rounded-lg border border-border bg-background p-3 hover:border-border-strong hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,children:[a&&!A&&(0,V.jsx)(Zu,{tone:`blue`,className:`self-start`,children:a}),y?(0,V.jsx)(ng,{name:n.card,fallback:N(t),children:(0,V.jsx)(y,{row:r})}):N(t)]});return(0,V.jsxs)(`div`,{className:w?`group/card relative h-full`:j||a||M.length>0?`relative h-full`:`h-full`,children:[w?(0,V.jsx)(ohe,{photos:r.photos??[],cover:D,swipe:i,children:ee},r.key):ee((0,V.jsx)(the,{value:D})),a&&A&&(0,V.jsx)(Zu,{tone:`blue`,className:`pointer-events-none absolute top-2 left-2 shadow-sm`,children:a}),M.length>0&&(0,V.jsx)($me,{dots:M,Card:c5}),j&&(0,V.jsx)(Gme,{favorite:j,recordKey:r.key,target:jg(e,r.record),className:A?void 0:`right-1.5 top-1.5`})]})},l5=268,u5=3,d5=(e,t,n)=>{let r=Math.floor(Math.max(0,e)/l5),i=Math.ceil((Math.max(0,e)+t)/l5);return{start:Math.max(0,r-u5),end:Math.min(n,i+u5)}},f5=e=>e*l5,che=e=>{let t=(0,o.useRef)(null),[n,r]=(0,o.useState)({left:0,width:0});(0,o.useLayoutEffect)(()=>{let n=t.current;if(!n)return;let i=()=>r(t=>{let r={left:n.scrollLeft,width:n.clientWidth};return((t,n)=>{let[r,i]=[d5(t.left,t.width,e),d5(n.left,n.width,e)];return r.start===i.start&&r.end===i.end&&t.width===n.width&&t.left>0==n.left>0&&Math.abs(t.left-n.left)<1})(t,r)?t:r});i();let a=new ResizeObserver(i);return a.observe(n),n.addEventListener(`scroll`,i,{passive:!0}),()=>{a.disconnect(),n.removeEventListener(`scroll`,i)}},[e]);let i=Math.max(0,f5(e)-12),a=e=>t.current?.scrollBy({left:e*Math.max(f5(1),n.width-12),behavior:`smooth`});return{ref:t,...d5(n.left,n.width,e),back:n.left>0,on:n.left+n.width<i-1,page:a}},p5=`absolute top-1/2 z-10 hidden size-8 -translate-y-1/2 items-center justify-center rounded-full border border-border-strong bg-background shadow-pop hover:bg-muted sm:flex`,m5=({cards:e})=>e>0?(0,V.jsx)(`li`,{"aria-hidden":!0,className:`shrink-0`,style:{width:f5(e)-12}}):null,lhe=({model:e,view:t,display:n,source:r,label:i,isNew:a})=>{let{total:o}=r,s=che(o),c=L6({total:o,rowAt:r.rowAt,loadRows:r.loadRows,revision:r.revision,latencyMs:0},s.start,Math.max(s.start,s.end-1)),l=Array.from({length:s.end-s.start},(e,t)=>s.start+t);return(0,V.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,V.jsxs)(`ul`,{ref:s.ref,"aria-label":i,className:`flex snap-x gap-3 overflow-x-auto overflow-y-hidden pb-1`,style:{scrollbarWidth:`thin`},children:[(0,V.jsx)(m5,{cards:s.start}),l.map(r=>{let i=c(r);if(!i)return(0,V.jsx)(`li`,{"aria-hidden":!0,className:`shrink-0`,style:{width:256},children:(0,V.jsx)(Au,{className:`h-full min-h-24 rounded-lg`})},`skeleton-${r}`);let s=EC(e,i);return(0,V.jsx)(`li`,{"aria-posinset":r+1,"aria-setsize":o,className:`grid shrink-0 snap-start grid-cols-[minmax(0,1fr)]`,style:{width:256},children:(0,V.jsx)(c5,{model:e,view:t,display:n,row:s,swipe:!1,mark:a?.(s)?`New`:void 0})},s.key)}),(0,V.jsx)(m5,{cards:o-s.end})]}),s.back&&(0,V.jsx)(`button`,{type:`button`,"aria-label":`Previous ${i.toLowerCase()}`,onClick:()=>s.page(-1),className:`${p5} -left-3`,children:(0,V.jsx)(ye,{className:`size-4`,"aria-hidden":!0})}),s.on&&(0,V.jsx)(`button`,{type:`button`,"aria-label":`Next ${i.toLowerCase()}`,onClick:()=>s.page(1),className:`${p5} -right-3`,children:(0,V.jsx)(xe,{className:`size-4`,"aria-hidden":!0})})]})},uhe=uo(),dhe=(e,t)=>{if(!t)return e;let n=Ca(e);if(!n.ok)throw Error(`The filter cannot be read: ${n.errors.map(e=>e.message).join(`; `)}`);return Ya(n.ast?uhe.and(n.ast,t):t)},fhe=(e,t)=>{let n=oC(e).filter(e=>e.kind===`cards`);return n.find(e=>e.name===t)??n[0]??{kind:`cards`,name:`cards`}},phe=()=>(0,V.jsx)(`div`,{className:`flex gap-3 overflow-hidden`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(Au,{className:`h-24 w-64 shrink-0`},t))}),h5=({model:e,view:t,filter:n,sort:r=``,display:i,limit:a,chips:s=!0,empty:c,note:l,isNew:u,viewAll:d,scope:f,list:p})=>{let{resources:m,views:h}=q(),g=hu(),_=fhe(t,i),v=r||DC(e,t),y=Q6({resources:m,views:h,model:e,columns:(0,o.useMemo)(()=>CC(e,t,[]),[e,t]),filter:(0,o.useMemo)(()=>dhe(n,f),[n,f]),orderBy:v}),b=z8(e,n),x=(t?.names?.singular??K(e.name)).toLowerCase(),S=t?.names?.plural??K(e.name),C=y.source?.total,T=(0,o.useMemo)(()=>y.source&&{...y.source,total:Math.min(y.source.total,a??1/0)},[y.source,a]);return(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3`,children:[s&&b.length>0||C!==void 0||l?(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[s&&b.length>0?(0,V.jsx)(t8,{chips:b}):(0,V.jsx)(`span`,{}),(0,V.jsxs)(`p`,{className:`flex flex-wrap gap-x-3 text-muted-foreground`,children:[l&&(0,V.jsx)(`span`,{children:l}),C!==void 0&&(0,V.jsx)(`span`,{className:`tabular-nums`,children:`${C.toLocaleString(`en-GB`)} ${C===1?x:S.toLowerCase()}`})]})]}):null,y.isLoading?(0,V.jsx)(phe,{}):y.error?(0,V.jsx)(pS,{title:`Could not load`,error:y.error}):!T||T.total===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:c??`No ${S.toLowerCase()} match.`}):(0,V.jsx)(lhe,{model:e,view:t,display:_,source:T,label:S,isNew:u}),(0,V.jsxs)(FC,{to:$6(e,t,g,{filter:n,orderBy:v,display:_.name,savedSearch:d?.savedSearch,resource:p}),onClick:d?.onOpen,className:`flex items-center gap-1 self-end font-medium text-primary-text hover:underline`,children:[d?.label??(0,V.jsxs)(V.Fragment,{children:[`View all `,(0,V.jsx)(`span`,{className:`sr-only`,children:S.toLowerCase()})]}),(0,V.jsx)(w,{className:`size-3.5`,"aria-hidden":!0})]})]})},mhe=({model:e,view:t,empty:n,...r})=>{let{resources:i,views:a}=q(),o=AC(i,a,e.name),s=Y8(e.name,t.listOf,!0),c=(t.names?.plural??K(e.name)).toLowerCase();if(!o.listOf)return null;if(s.error)return(0,V.jsx)(pS,{title:`Could not load your ${c}`,error:s.error});if(!s.data)return(0,V.jsx)(Au,{className:`h-24`});let l=q8(o.model,s.data);return l?(0,V.jsx)(h5,{...r,model:o.model,view:o.view,filter:``,scope:l,list:e.name,empty:n}):(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:n??`No ${c} yet.`})},hhe=e=>W.list(e,``,``,500,`saved-searches`),g5=(e,t)=>{let n=G(),{resources:r,views:i}=q(),a=r[e];return vh({queryKey:hhe(e),enabled:t&&a!==void 0,queryFn:async()=>{let t=[],r;do{let o=await n.list(e,{pageSize:500,orderBy:DC(a,i[e]),...r&&{pageToken:r}});t.push(...o.items),r=o.nextPageToken||void 0}while(r);return t}})},_5=({model:e,of:t,target:n,targetView:r,row:i,recordKey:a})=>{let o=G(),s=Xw(),c=String(i[t.filter]??``),l=z8(n,c),u=t.name===void 0?void 0:i[t.name],d=typeof u==`string`&&u!==``?u:void 0,f=t.unseen,p=yh({mutationFn:t=>o.update(e.name,a,{[f.seenAt]:t},i.etag??`*`),onSettled:()=>s(e.name)}),m=vh({...Kw(o,n,f?Fme(c,f.field,i[f.seenAt]):``),enabled:f!==void 0}),h=(r?.names?.plural??K(n.name)).toLowerCase(),g={model:n,view:r,filter:c,sort:f?`${f.field} desc`:void 0,limit:t.limit,chips:d!==void 0,empty:`No ${h} match.`,note:f&&m.data===0&&`No new ${h} since you last looked.`,isNew:f&&(e=>Ime(e.record[f.field],i[f.seenAt])),viewAll:{label:`View all results`,savedSearch:a,...f&&{onOpen:()=>p.mutate(new Date().toISOString())}}};return{name:d,chips:l,title:d??lme(l),body:g}},ghe=({model:e,view:t,target:n,targetView:r,row:i})=>{let a=Ao(jg(e,i)),{name:o,chips:s,title:c,body:l}=_5({model:e,of:t.searchesOf,target:n,targetView:r,row:i,recordKey:a});return(0,V.jsxs)(`section`,{"aria-label":c,className:`flex flex-col gap-3 py-4 first:pt-0 last:pb-0`,children:[(0,V.jsx)(`h3`,{className:`text-[15px] font-semibold`,children:(0,V.jsx)(FC,{to:{kind:`record`,resource:e.name,key:a},className:`hover:underline`,children:o??(0,V.jsx)(n8,{chips:s})})}),(0,V.jsx)(h5,{...l})]})},_he=({model:e,view:t,empty:n})=>{let{resources:r,views:i}=q(),a=t.searchesOf,o=r[a.resource],s=g5(e.name,!0),c=(t.names?.plural??K(e.name)).toLowerCase();return o?s.error?(0,V.jsx)(pS,{title:`Could not load your ${c}`,error:s.error}):s.data?s.data.length===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:n??`No ${c} yet.`}):(0,V.jsx)(`div`,{className:`flex flex-col divide-y`,children:s.data.map(n=>(0,V.jsx)(ghe,{model:e,view:t,target:o,targetView:i[a.resource],row:n},Ao(jg(e,n))))}):(0,V.jsx)(Au,{className:`h-40`}):null},vhe=({node:e,slots:t})=>{let{resource:n,filter:r=``,sort:i,limit:a,display:o,title:s,description:c,empty:l}=eT(e),{resources:u,views:d}=q(),f=u[n];if(!f)return null;let p=d[f.name];return(0,V.jsx)(nT,{title:s,description:c,actions:t.actions,children:p?.searchesOf?(0,V.jsx)(_he,{model:f,view:p,empty:l}):p?.listOf===void 0?(0,V.jsx)(h5,{model:f,view:p,filter:r,sort:i,limit:a,display:o,empty:l}):(0,V.jsx)(mhe,{model:f,view:p,limit:a,display:o,empty:l})})},yhe=({node:e,children:t})=>{let{when:n}=eT(e),{resources:r}=q(),i=G(),a=Pw(),s=(0,o.useMemo)(()=>ec(n),[n]),c=s.ok?s.paths:[],l=c.map(e=>nc(e,e=>!!(a&&Object.hasOwn(a.model.fields,e)))),u=c.filter((e,t)=>l[t]===void 0),d=Tue(a,u),f=gh({queries:l.flatMap(e=>{let t=e===void 0?void 0:r[e];return t?[Kw(i,t)]:[]})});if(!s.ok||d.some(e=>e.state===`loading`)||f.some(e=>e.isPending))return null;let p={};u.forEach((e,t)=>{let n=d[t];n.state===`ready`&&(p[e]=n.value)});let m=0;return c.forEach((e,t)=>{l[t]!==void 0&&(p[e]=r[l[t]]?f[m++]?.data??0:0)}),tc(s,p)?(0,V.jsx)(V.Fragment,{children:t}):null},v5=`text-2xl font-semibold tracking-tight tabular-nums`,bhe=({model:e,filter:t})=>{let n=qw(e,t);return n.isPending?(0,V.jsx)(Au,{className:`h-8 w-16`}):n.error?(0,V.jsx)(`span`,{className:`text-danger-text`,children:`Could not count`}):(0,V.jsx)(FC,{to:{kind:`list`,resource:e.name,filter:t},className:`${v5} hover:text-primary-text after:absolute after:inset-0 after:content-['']`,children:n.data.toLocaleString(`en-IE`)})},xhe=({field:e,format:t})=>{let n=L4(Pw(),e);return n.state===`loading`?(0,V.jsx)(Au,{className:`h-8 w-16`}):n.state===`missing`?null:(0,V.jsx)(`span`,{className:v5,children:(0,V.jsx)(N4,{model:n.model,field:n.field,value:n.value,format:t})})},She=({node:e})=>{let{label:t,value:n,resource:r,filter:i,field:a,format:o,description:s}=eT(e),{resources:c}=q(),l=r===void 0?void 0:c[r];return(0,V.jsxs)(nT,{className:`relative h-full`,bodyClassName:`flex flex-col`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground break-words`,children:t}),(0,V.jsxs)(`div`,{className:`mt-auto pt-1`,children:[n!==void 0&&(0,V.jsx)(`span`,{className:v5,children:n}),l&&(0,V.jsx)(bhe,{model:l,filter:i}),a!==void 0&&(0,V.jsx)(xhe,{field:a,format:o})]}),s&&(0,V.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s})]})},y5=e=>e===null?`none`:`value:${e}`,Che=e=>{let t=_v(e);return t.length>0?t:hv(e)},whe=(e,{context:{collisionRect:t,droppableRects:n,droppableContainers:r,over:i}})=>{let a=e.code===`ArrowRight`?1:e.code===`ArrowLeft`?-1:0;if(a===0||!t)return;e.preventDefault();let o=r.getEnabled().flatMap(e=>{let t=n.get(e.id);return t?[{id:e.id,rect:t}]:[]}).sort((e,t)=>e.rect.left-t.rect.left),s=t.left+t.width/2,c=i?o.findIndex(e=>e.id===i.id):o.findIndex(e=>e.rect.left<=s&&s<=e.rect.right),l=o[c+a];if(c!==-1&&l)return{x:l.rect.left+(l.rect.width-t.width)/2,y:l.rect.top}},b5=(e,t,n,r)=>{let i=bh({queryKey:[...n,`display`],enabled:r,initialPageParam:0,queryFn:({pageParam:e})=>t(e),getNextPageParam:(e,t)=>e.rows.length===40&&t.length*40<(t[0]?.total??0)?t.length:void 0}),a=i.data?.pages??[];return{resource:e.name,rows:a.flatMap(t=>t.rows.map(t=>EC(e,t))),total:a[0]?.total??0,loading:i.isPending,error:i.error,more:i.hasNextPage,loadMore:()=>void i.fetchNextPage()}},The=({model:e,by:t,value:n,fields:r,filter:i,orderBy:a})=>{let{resources:o,views:s}=q(),c=Q6({resources:o,views:s,model:e,columns:r,filter:rC(i,t,n),orderBy:a});return b5(e,c.page,c.key,!0)},Ehe=({model:e,view:t,display:n,column:r,fields:i,filter:a,orderBy:o,limit:s,moves:c,movable:l,dragged:u})=>{let d=The({model:e,by:n.by,value:r.value,fields:i,filter:a,orderBy:o}),{setNodeRef:f,isOver:p}=fb({id:y5(r.value)}),m=iC(e,t,n),h=new Set(d.rows.map(e=>e.key)),g=new Map(c.map(e=>[e.row.key,e])),_=d.rows.filter(e=>g.has(e.key)&&g.get(e.key).to!==r.value),v=c.filter(e=>e.to===r.value&&!h.has(e.row.key)).map(e=>e.row),y=d.rows.filter(e=>!_.includes(e)).map(e=>g.has(e.key)?g.get(e.key).row:e),b=[...v,...y].slice(0,s),x=d.total-_.length+v.length;if(r.value===null&&!d.loading&&x===0&&!p)return null;let S=(t?.names?.plural??K(e.name)).toLowerCase(),C=t?.fields[n.by];return(0,V.jsxs)(`section`,{ref:f,"aria-label":`${r.label}, ${x}`,className:B(`flex w-72 shrink-0 snap-start flex-col gap-2 rounded-lg bg-surface p-2`,p&&`ring-2 ring-primary/30`),children:[(0,V.jsxs)(`header`,{className:`flex items-center justify-between gap-2 px-1 pt-0.5`,children:[(0,V.jsx)(`h2`,{className:`min-w-0 truncate text-xs font-medium`,children:r.value===null?(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:r.label}):(0,V.jsx)(M4,{value:r.value,hints:C,children:r.label})}),!d.loading&&(0,V.jsx)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:x.toLocaleString(`en-IE`)})]}),d.loading?Array.from({length:3},(e,t)=>(0,V.jsx)(Au,{className:`h-20`},t)):d.error?(0,V.jsx)(pS,{title:`Could not load rows`,error:d.error}):b.length===0?(0,V.jsxs)(`p`,{className:`px-1 py-4 text-center text-xs text-muted-foreground`,children:[`No `,S]}):(0,V.jsx)(`ul`,{className:`flex flex-col gap-2`,children:b.map(n=>(0,V.jsx)(`li`,{children:(0,V.jsx)(Dhe,{model:e,view:t,card:m,row:n,movable:l&&Iw(n.record,`update`),dragged:u})},n.key))}),s===void 0&&d.more&&(0,V.jsx)(U,{size:`sm`,variant:`ghost`,onClick:d.loadMore,children:`Show more`})]})},Dhe=({model:e,view:t,card:n,row:r,movable:i,dragged:a})=>{let{setNodeRef:o,setActivatorNodeRef:s,listeners:c,isDragging:l}=cb({id:r.key,data:{row:r},disabled:!i});return(0,V.jsx)(`div`,{ref:e=>{o(e),s(e?.querySelector(`a`)??e)},...c,onDragStart:e=>e.preventDefault(),onClickCapture:e=>{a()&&(e.preventDefault(),e.stopPropagation())},className:B(i&&`cursor-grab touch-manipulation`,l&&`opacity-40`),children:(0,V.jsx)(c5,{model:e,view:t,display:n,row:r,swipe:!1})})},Ohe=(e,t)=>{let n=G(),r=Lg(),i=Xw(),[a,s]=(0,o.useState)([]),c=e=>s(t=>t.filter(t=>t.row.key!==e)),l=yh({mutationFn:({row:r,to:i})=>{let a=typeof r.record.etag==`string`?r.record.etag:`*`;return n.update(e.name,jg(e,r.record),{[t]:i.value},a)},onMutate:({row:e,to:n})=>{let r={...e,record:{...e.record,[t]:n.value}};s(t=>[...t.filter(t=>t.row.key!==e.key),{row:r,to:n.value}])},onError:(e,{row:t,to:n})=>{c(t.key),r.show({state:`error`,title:`Could not move it to ${n.label}`,description:aC(e)})},onSettled:async(t,n,{row:r})=>{await i(e.name),c(r.key)}});return{moves:a,move:(e,t)=>l.mutate({row:e,to:t})}},x5=({model:e,view:t,display:n,fields:r,filter:i,orderBy:a,limit:s})=>{let c=nC(e,t,n),l=iC(e,t,n),u=Fw(f_(e.name),`update`)&&!e.fields[n.by]?.readOnly,{moves:d,move:f}=Ohe(e,n.by),[p,m]=(0,o.useState)(),h=(0,o.useRef)(!1),g=rv(nv(uy,{activationConstraint:{distance:4}}),nv(fy,{activationConstraint:{delay:250,tolerance:5}}),nv(ny,{keyboardCodes:{start:[`Space`],cancel:[`Escape`],end:[`Space`,`Enter`]},coordinateGetter:whe})),_=e=>String(e.labels[l.title]??e.record[l.title]??e.key),v=e=>c.find(t=>y5(t.value)===e),y=e=>e.record[n.by]??null;return(0,V.jsxs)(ib,{sensors:g,collisionDetection:Che,onDragStart:({active:e})=>{h.current=!0,m(e.data.current.row)},onDragEnd:({active:e,over:t})=>{m(void 0),setTimeout(()=>h.current=!1);let n=e.data.current.row,r=t?v(t.id):void 0;r&&r.value!==y(n)&&f(n,r)},onDragCancel:()=>{m(void 0),setTimeout(()=>h.current=!1)},accessibility:{announcements:{onDragStart:({active:e})=>`Picked up ${_(e.data.current.row)}.`,onDragOver:({active:e,over:t})=>`${_(e.data.current.row)} is over ${t?v(t.id)?.label:`no column`}.`,onDragEnd:({active:e,over:t})=>t?`${_(e.data.current.row)} was moved to ${v(t.id)?.label}.`:`${_(e.data.current.row)} was put back.`,onDragCancel:({active:e})=>`Moving ${_(e.data.current.row)} was cancelled.`},screenReaderInstructions:{draggable:`To move a card to another column, press Space, move it with the left and right arrow keys, and press Space again to drop it there. Escape puts it back.`}},children:[(0,V.jsx)(`div`,{className:`min-w-0 flex-1 overflow-x-auto`,children:(0,V.jsx)(`div`,{className:`flex snap-x items-start gap-3 pb-2`,children:c.map(o=>(0,V.jsx)(Ehe,{model:e,view:t,display:n,column:o,fields:r,filter:i,orderBy:a,limit:s,moves:d,movable:u,dragged:()=>h.current},y5(o.value)))})}),(0,V.jsx)(wb,{children:p&&(0,V.jsx)(c5,{model:e,view:t,display:l,row:p,swipe:!1})})]})},khe=({list:e,empty:t,loading:n,children:r})=>(0,V.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:e.loading?n:e.error?(0,V.jsx)(pS,{title:`Could not load rows`,error:e.error}):e.rows.length===0?(0,V.jsx)(`p`,{className:`py-8 text-center text-muted-foreground`,children:t}):r}),Ahe=({list:e})=>(0,V.jsxs)(`div`,{className:`flex items-center justify-between gap-3 py-3 text-xs text-muted-foreground`,children:[(0,V.jsxs)(`span`,{children:[e.rows.length.toLocaleString(`en-IE`),` of `,e.total.toLocaleString(`en-IE`)]}),e.more&&(0,V.jsx)(U,{size:`sm`,onClick:e.loadMore,children:`Show more`})]}),S5=`grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3`,jhe=`flex snap-x snap-mandatory gap-3 overflow-x-auto pb-1`,Mhe=({model:e,view:t,display:n,list:r,row:i=!1,footer:a=!0})=>{let o=(t?.names?.plural??K(e.name)).toLowerCase();return(0,V.jsxs)(khe,{list:r,empty:`No ${o} match.`,loading:(0,V.jsx)(`div`,{className:S5,children:Array.from({length:6},(e,t)=>(0,V.jsx)(Au,{className:`h-24`},t))}),children:[(0,V.jsx)(`ul`,{className:i?jhe:S5,"aria-label":t?.names?.plural??K(e.name),children:r.rows.map(r=>(0,V.jsx)(`li`,{className:B(i&&`w-64 shrink-0 snap-start`),children:(0,V.jsx)(c5,{model:e,view:t,display:n,row:r,swipe:!i})},r.key))}),a&&(0,V.jsx)(Ahe,{list:r})]})},C5=(0,o.createContext)(void 0),Nhe=({value:e,children:t})=>(0,V.jsx)(C5.Provider,{value:e,children:t}),Phe=()=>{let e=(0,o.useContext)(C5);if(!e)throw Error(`useListDisplay is used inside a list display, which the list page draws`);return e},Fhe=()=>(0,o.useContext)(C5),w5=({display:e,list:t})=>{let{components:n}=Zg(),r=n?.[e.component];return r?(0,V.jsx)(Nhe,{value:t,children:(0,V.jsx)(`div`,{className:`min-w-0 flex-1 overflow-x-auto`,children:(0,V.jsx)(ng,{name:e.component,children:(0,V.jsx)(r,{...ho(e.props??{})})})})}):(0,V.jsxs)(tg,{children:[`No component is registered as `,e.component,`. Export it from protobase.ui.tsx, or load the plugin that provides it.`]})},T5=uo(),Ihe={bounds:{south:-90,west:-180,north:90,east:180},zoom:0},Lhe=22,E5=e=>Math.floor(e*1e6)/1e6,D5=e=>Math.ceil(e*1e6)/1e6,O5=e=>((e+180)%360+360)%360-180,Rhe=(e,t)=>{let n=[T5.gte(e.latitude,E5(Math.max(t.south,-90))),T5.lte(e.latitude,D5(Math.min(t.north,90)))];if(t.east-t.west>=360)return T5.and(...n);let r=T5.gte(e.longitude,E5(O5(t.west))),i=T5.lte(e.longitude,D5(O5(t.east)));return O5(t.west)<=O5(t.east)?T5.and(...n,r,i):T5.and(...n,T5.or(r,i))},zhe=(e,t,n)=>{let r=Ya(Rhe(t,n));return e.trim()===``?r:`(${e}) AND ${r}`},Bhe=e=>Math.min(Math.max(Math.floor(e),0),Lhe),Vhe=(e,t)=>{let n=[...e.map(e=>({south:e.latitude,west:e.longitude,north:e.latitude,east:e.longitude})),...t.map(e=>e.bounds)];if(n.length!==0)return{south:Math.min(...n.map(e=>e.south)),west:Math.min(...n.map(e=>e.west)),north:Math.max(...n.map(e=>e.north)),east:Math.max(...n.map(e=>e.east))}},k5=e=>{if(typeof e==`number`)return e;if(typeof e==`string`&&e.trim()!==``)return Number(e)},A5=(e,t)=>{let n=k5(e[t.latitude]),r=k5(e[t.longitude]);if(n!==void 0&&r!==void 0&&Math.abs(n)<=90&&Math.abs(r)<=180)return{latitude:n,longitude:r}},Hhe=6371008.8,j5=64,M5=(e,t)=>t.approximate===void 0?t.exact!==void 0&&e[t.exact]===!1:e[t.approximate]===!0,N5=(e,t)=>{let n=t/Hhe,r=e.latitude*Math.PI/180,i=e.longitude*Math.PI/180;return{type:`Polygon`,coordinates:[Array.from({length:65},(e,t)=>{let a=t%j5/j5*2*Math.PI,o=Math.asin(Math.sin(r)*Math.cos(n)+Math.cos(r)*Math.sin(n)*Math.cos(a));return[(i+Math.atan2(Math.sin(a)*Math.sin(n)*Math.cos(r),Math.cos(n)-Math.sin(r)*Math.sin(o)))*180/Math.PI,o*180/Math.PI]})]}},Uhe=e=>Array.isArray(e)&&e.length>=2&&typeof e[0]==`number`&&typeof e[1]==`number`&&Math.abs(e[0])<=180&&Math.abs(e[1])<=90,P5=(e,t)=>Array.isArray(e)&&e.length>=t&&e.every(Uhe),F5=e=>Array.isArray(e)&&e.length>0&&e.every(e=>P5(e,4)),Whe=e=>Array.isArray(e)&&e.length>0&&e.every(e=>P5(e,2)),Ghe=e=>{if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch(e){if(e instanceof SyntaxError)return;throw e}},Khe=e=>{let t=Ghe(e);if(typeof t!=`object`||!t)return;let n=t.type===`Feature`?t.geometry:t;if(typeof n!=`object`||!n)return;let{type:r,coordinates:i}=n;if(r===`Polygon`&&F5(i)||r===`MultiPolygon`&&Array.isArray(i)&&i.length>0&&i.every(F5)||r===`LineString`&&P5(i,2)||r===`MultiLineString`&&Whe(i))return{type:r,coordinates:i}},qhe=(e,t,n)=>{if(!M5(e,t))return;let r=t.area===void 0?void 0:Khe(e[t.area]);if(r)return r;let i=t.radius===void 0?void 0:k5(e[t.radius]);return i!==void 0&&Number.isFinite(i)&&i>0?N5(n,i):t.defaultRadius===void 0?void 0:N5(n,t.defaultRadius)},I5=(e,t)=>e.flatMap(e=>{let n=A5(e.record,t);if(!n)return[];if(!M5(e.record,t))return[{key:e.key,...n}];let r=qhe(e.record,t,n);return[{key:e.key,...n,approximate:!0,...r&&{area:r}}]}),Jhe=(e,t)=>{let n=[];for(let r of e){let e=n.find(e=>Math.hypot(e.at.x-r.x,e.at.y-r.y)<=t);e?e.keys.push(r.key):n.push({at:r,keys:[r.key]})}return n.map(e=>({keys:e.keys,at:e.at.key}))},Yhe=(e,t)=>{if(!e)return;let n=new Set(t.map(e=>e.key)),r=e.keys.filter(e=>n.has(e));if(r.length===0)return;let i=r.indexOf(e.keys[e.index]);return{keys:r,index:Math.max(i,0)}},L5=(e,t)=>({keys:e.keys,index:((e.index+t)%e.keys.length+e.keys.length)%e.keys.length}),Xhe=({model:e,display:t,fields:n,filter:r,orderBy:i,area:a})=>{let o=G(),{resources:s,views:c}=q(),l={latitude:t.latitude,longitude:t.longitude},u=a?zhe(r,l,a.bounds):``,d=a?Bhe(a.zoom):0;return vh({queryKey:W.map(e.name,`${l.latitude},${l.longitude}`,d,u,i),enabled:a!==void 0,placeholderData:mm,queryFn:async()=>{let t=await o.map(e.name,{...l,zoom:d,filter:u,orderBy:i,labels:k4(s,c,e,n),photos:$S(c[e.name])});return{rows:A4(s,e,n,eC(e,t.items,t.photos),t.labels).map(t=>EC(e,t)),buckets:t.buckets,total:t.totalSize}}})},Zhe=(0,o.lazy)(()=>Zh(()=>import(`./records-map-LDeVJQab.js`).then(e=>({default:e.RecordsMap})),__vite__mapDeps([4,1,2,5,6,3,7]))),Qhe=250,R5=`flex size-8 items-center justify-center rounded-full border border-border bg-background hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,z5=({model:e,view:t,display:n,filter:r,orderBy:i,fields:a,at:s,onMove:c,footer:l=!0,flush:u=!1})=>{let d=q().maps,f=d?.style,[p,m]=(0,o.useState)(),[h,g]=(0,o.useState)(),_=h8(h,Qhe),[v,y]=(0,o.useState)(s===void 0),b=Xhe({model:e,display:n,fields:a,filter:r,orderBy:i,area:v?Ihe:_}),x=b.isPlaceholderData?void 0:b.data,S=b.data?.rows??[],C=b.data?.buckets??[],w=I5(S,n),T=v&&x?Vhe(I5(x.rows,n),x.buckets):void 0,E=xC(t,n),D=(t?.names?.plural??K(e.name)).toLowerCase(),O=(t?.names?.singular??K(e.name)).toLowerCase(),k=Yhe(p,S),A=k&&S.find(e=>e.key===k.keys[k.index]),j=new Set(w.filter(e=>e.approximate).map(e=>e.key)),M=e=>{let t=e.filter(e=>j.has(e)).length;return e.length===1?t===1?`Show the ${O}, at an approximate position`:`Show the ${O}`:t===0?`Show ${e.length} ${D}`:t===e.length?`Show ${e.length} ${D}, at approximate positions`:`Show ${e.length} ${D}, ${t} at approximate positions`},N=e=>`Zoom in on ${e.toLocaleString(`en-IE`)} ${e===1?O:D}`,ee=(0,o.useRef)(null),[P,te]=(0,o.useState)(0);if((0,o.useLayoutEffect)(()=>te(ee.current?.offsetHeight??0),[A?.key]),!f)return(0,V.jsx)(tg,{children:`The map display needs a map style: set PROTOBASE_MAP_STYLE_URL.`});let F=x?.total===0;return(0,V.jsxs)(`div`,{className:B(`flex h-full min-h-[36rem] flex-1 flex-col sm:min-h-[28rem]`,u&&`max-md:-mx-5 max-md:-mb-4 max-md:min-h-0`),children:[(0,V.jsxs)(`div`,{className:B(`relative min-h-0 flex-1 overflow-hidden rounded-lg border border-border bg-muted`,u&&`max-md:rounded-none max-md:border-0`),children:[(0,V.jsx)(o.Suspense,{fallback:null,children:(0,V.jsx)(Zhe,{style:f,layers:d?.layers,initial:s,points:w,buckets:C,fit:T,onFitted:()=>y(!1),onMove:(e,t)=>{g(e),c?.(t)},selected:k?.keys,covered:k?P:0,onSelect:e=>m({keys:e,index:0}),onClear:()=>m(void 0),markerLabel:M,bucketLabel:N})}),b.error&&(0,V.jsx)(`div`,{className:`absolute inset-x-3 top-3 z-10`,children:(0,V.jsx)(pS,{title:`Could not load rows`,error:b.error})}),F&&(0,V.jsx)(`div`,{className:`pointer-events-none absolute inset-x-3 top-3 z-10 flex justify-center`,children:(0,V.jsxs)(`p`,{className:`pointer-events-auto flex items-center gap-3 rounded-full border border-border bg-background px-4 py-1.5 text-muted-foreground shadow`,role:`status`,children:[v?`No ${D} match.`:`No ${D} in this part of the map.`,!v&&(0,V.jsx)(U,{size:`sm`,onClick:()=>y(!0),children:`Show all`})]})}),k&&A&&(0,V.jsx)(`div`,{ref:ee,className:`pointer-events-none absolute inset-x-3 bottom-3 z-10 flex justify-center`,children:(0,V.jsxs)(`div`,{className:`pointer-events-auto flex w-full max-w-[16rem] flex-col gap-2 sm:max-w-xs`,role:`group`,"aria-label":`Chosen ${O}`,children:[(0,V.jsxs)(`div`,{className:`flex items-center justify-end gap-1.5`,children:[j.has(A.key)&&(0,V.jsxs)(`span`,{className:`mr-auto flex items-center gap-1 rounded-full border border-border bg-background px-2 py-1 text-xs`,children:[(0,V.jsx)(ke,{className:`size-3.5`,"aria-hidden":!0}),`Approximate position`]}),k.keys.length>1&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":`Previous`,className:R5,onClick:()=>m(L5(k,-1)),children:(0,V.jsx)(ye,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsxs)(`span`,{className:`rounded-full border border-border bg-background px-2 py-1 text-xs tabular-nums`,"aria-live":`polite`,children:[k.index+1,` / `,k.keys.length]}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Next`,className:R5,onClick:()=>m(L5(k,1)),children:(0,V.jsx)(xe,{className:`size-4`,"aria-hidden":!0})})]}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Close`,className:R5,onClick:()=>m(void 0),children:(0,V.jsx)(Qn,{className:`size-4`,"aria-hidden":!0})})]}),(0,V.jsx)(`div`,{className:`shadow-lg`,children:(0,V.jsx)(c5,{model:e,view:t,display:E,row:A})})]})})]}),l&&(0,V.jsx)(`p`,{className:`hidden py-3 text-xs text-muted-foreground md:block`,children:$he(b.data,D)})]})},$he=(e,t)=>{if(!e)return`\xA0`;let n=e.total.toLocaleString(`en-IE`);return e.buckets.length===0&&e.rows.length<e.total?`${e.rows.length.toLocaleString(`en-IE`)} of ${n} ${t} in view`:`${n} ${t} in view`},ege=(e,t,n)=>{if(n!==0){if(e===`Home`)return 0;if(e===`End`)return n-1;if(e===`ArrowDown`)return t<0?0:(t+1)%n;if(e===`ArrowUp`)return t<0?n-1:(t-1+n)%n}},B5=({value:e,options:t,onChange:n,label:r})=>{let[i,a]=(0,o.useState)(!1),s=(0,o.useRef)(null),c=(0,o.useRef)(null),l=(0,o.useRef)([]),u=t.findIndex(t=>t.value===e),d=t[u];(0,o.useEffect)(()=>{if(!i)return;l.current[Math.max(u,0)]?.focus();let e=e=>{e.target instanceof Node&&!s.current?.contains(e.target)&&a(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[i]);let f=()=>{a(!1),c.current?.focus()};return(0,V.jsxs)(`div`,{ref:s,className:`relative shrink-0`,children:[(0,V.jsxs)(`button`,{ref:c,type:`button`,"aria-label":d?`${r}: ${d.label}`:r,"aria-haspopup":`menu`,"aria-expanded":i,onClick:()=>a(!i),className:`inline-flex h-8 items-center gap-1.5 rounded-md border border-border-strong bg-background px-2.5 text-body font-medium shadow-sm transition-colors hover:bg-muted pointer-coarse:h-11`,children:[d?.icon&&(0,V.jsx)(d.icon,{className:`size-3.5`}),d?.label??r,(0,V.jsx)(_e,{className:`size-3.5 text-muted-foreground`})]}),i&&(0,V.jsx)(`ul`,{role:`menu`,"aria-label":r,onKeyDown:e=>{if(e.key===`Escape`)return f();if(e.key===`Tab`)return a(!1);let n=ege(e.key,l.current.indexOf(document.activeElement),t.length);n!==void 0&&(e.preventDefault(),l.current[n]?.focus())},className:`absolute right-0 top-full z-30 mt-1 min-w-40 rounded-md border bg-background py-1 text-body shadow-pop`,children:t.map((t,r)=>(0,V.jsx)(`li`,{role:`none`,children:(0,V.jsxs)(`button`,{ref:e=>{l.current[r]=e},type:`button`,role:`menuitemradio`,"aria-checked":t.value===e,onClick:()=>{f(),t.value!==e&&n(t.value)},className:B(`flex min-h-9 w-full items-center gap-2 whitespace-nowrap px-3 py-1.5 text-left hover:bg-muted focus:bg-muted focus:outline-none pointer-coarse:min-h-11`,t.value===e&&`font-medium`),children:[t.icon?(0,V.jsx)(t.icon,{className:`size-3.5`}):(0,V.jsx)(`span`,{className:`size-3.5`}),(0,V.jsx)(`span`,{className:`flex-1`,children:t.label}),t.value===e&&(0,V.jsx)(he,{className:`size-3.5 text-primary-text`})]})},t.value))})]})},tge={table:Mn,cards:St,kanban:En,board:Fe,list:kt,calendar:de,map:nee},V5=({view:e,value:t,onChange:n,menu:r=!1,choices:i=hC(e)})=>{if(i.length<2)return null;let a=i.map(e=>({value:e.name,label:e.label,icon:e.icon===void 0?void 0:tge[e.icon]}));return r?(0,V.jsx)(B5,{label:`Display`,value:t,onChange:n,options:a}):(0,V.jsx)(ed,{label:`Display`,size:`md`,value:t,onChange:n,options:a})},nge=[[`asc`,`ascending`],[`desc`,`descending`]],H5=({model:e,view:t,display:n,orderBy:r,onChange:i,className:a})=>{let o=OC(r),s=wC(e,t,n),c=s.includes(o.columnId)?s:[o.columnId,...s],l=e=>t?.fields[e]?.label??K(e);return(0,V.jsx)(`select`,{"aria-label":`Sort`,value:`${o.columnId} ${o.direction}`,onChange:e=>i(e.target.value),className:B(`h-8 rounded-md border border-border-strong bg-background px-2.5 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20`,a),children:c.flatMap(e=>nge.map(([t,n])=>(0,V.jsxs)(`option`,{value:`${e} ${t}`,children:[l(e),`, `,n]},`${e} ${t}`)))})},U5=(e,t,n,r)=>e.map(e=>{let i=t.fields[e.id],a=i&&rw(r,i,n?.fields[e.id]);return a?{...e,render:t=>(0,V.jsx)(ow,{shown:a,part:`cell`,field:i,value:t[e.id],fallback:S6(e,e.value?e.value(t):t[e.id])})}:e}),W5=e=>e.includes(`.`),rge=({model:e,row:t,column:n})=>{let r=L4(Gw(e,EC(e,t).record),n);return r.state===`loading`?(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`…`}):r.state===`missing`?(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`—`}):(0,V.jsx)(N4,{model:r.model,field:r.field,value:r.value})},ige=(e,t,{resources:n,views:r})=>{let i=rc(n,e.name,t),a=i.ok?i.steps.at(-1):void 0,o=a?.field.name??t;return{id:t,header:r[a?.model.name??e.name]?.fields[o]?.label??K(o),kind:`text`,width:200,render:n=>(0,V.jsx)(rge,{model:e,row:n,column:t})}},G5=(e,t,n,r)=>{let i=new Map(U5(YS(e,t,[],n.filter(e=>!W5(e))),e,t,r.fieldTypes).map(e=>[e.id,e]));return n.flatMap(t=>W5(t)?[ige(e,t,r)]:i.get(t)??[])},age=({model:e,filter:t,orderBy:n,limit:r,fields:i})=>{let a=G(),{resources:o,views:s}=q();return vh({queryKey:[...W.list(e.name,t,n,r,`embedded`),i.join(`,`)],placeholderData:mm,queryFn:async()=>{let c=k4(o,s,e,i),l=$S(s[e.name]),u=await a.search(e.name,{filter:t||void 0,orderBy:n||void 0,pageSize:r,labels:c,photos:l});return A4(o,e,i,eC(e,u.items,u.photos),u.labels).map((t,n)=>({...t,id:Ag(e,u.items[n])}))}})},K5=({view:e,value:t,onChange:n})=>(0,V.jsx)(V5,{view:e,value:t,onChange:n,menu:!mu()}),oge=()=>(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(Au,{className:`h-4 w-full`},t))}),q5=({model:e,view:t,filter:n,sort:r,columns:i,limit:a,display:s,empty:c,row:l=!1,viewAll:u,link:d=!0})=>{let{resources:f,views:p}=q(),{fields:m}=Zg(),{go:h,href:g}=PC(),_=hu(),[v,y]=(0,o.useState)(r||DC(e,t)),b=i??JS(e,t),x=(0,o.useMemo)(()=>G5(e,t,b,{resources:f,views:p,fieldTypes:m}),[e,t,b.join(`,`),f,p,m]),S=(0,o.useMemo)(()=>CC(e,t,x.map(e=>e.id)),[e,t,x]),C=age({model:e,filter:n,orderBy:v,limit:a,fields:S}),T=C.data,E=(0,o.useMemo)(()=>T&&{total:T.length,rowAt:e=>T[e]},[T]),D=pC(t,s),O=t?.names?.plural??K(e.name),k=d&&(0,V.jsxs)(FC,{to:$6(e,t,_,u?{filter:u.filter,orderBy:DC(e,t),display:s,savedSearch:u.savedSearch}:{filter:n,orderBy:v,display:s}),onClick:u?.onOpen,className:`flex items-center gap-1 self-end font-medium text-primary-text hover:underline`,children:[u?u.label:(0,V.jsxs)(V.Fragment,{children:[`View all `,(0,V.jsx)(`span`,{className:`sr-only`,children:O.toLowerCase()})]}),(0,V.jsx)(w,{className:`size-3.5`,"aria-hidden":!0})]});if(C.isPending)return(0,V.jsx)(oge,{});if(C.error)return(0,V.jsx)(pS,{title:`Could not load`,error:C.error});if(!E||E.total===0){let e=(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:c??`Nothing here yet.`});return u&&d?(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[e,k]}):e}let A={resource:e.name,rows:C.data.map(t=>EC(e,t)),total:C.data.length,loading:!1,error:null,more:!1,loadMore:()=>void 0},j=t=>h({kind:`record`,resource:e.name,key:jg(e,t)}),M=t=>({href:g({kind:`record`,resource:e.name,key:jg(e,t)}),onFollow:()=>j(t)}),N=t?.names?.singular??K(e.name);return(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[D?D.kind===`cards`?(0,V.jsx)(Mhe,{model:e,view:t,display:D,list:A,row:l||_,footer:!1}):D.kind===`map`?(0,V.jsx)(z5,{model:e,view:t,display:D,filter:n,orderBy:v,fields:S,footer:!1}):D.kind===`board`?(0,V.jsx)(x5,{model:e,view:t,display:D,fields:S,filter:n,orderBy:v,limit:a}):(0,V.jsx)(w5,{display:D,list:A}):(0,V.jsx)(J6,{fit:!0,columns:x,source:E,latencyMs:0,sort:OC(v),onSortChange:e=>y(kC(e)),onOpenRow:j,rowLink:M,rowActions:[{label:`Open ${N.toLowerCase()}`,onSelect:j}],rowNumbers:!1,selectable:!1}),k]})},J5=(e,t,n)=>{let r=hu(),i=ame(t),[a,s]=(0,o.useState)(()=>ome(localStorage,i)),c=(0,o.useCallback)(e=>{s(e),sme(localStorage,i,e)},[i]);return[cme(e,r,{picked:a,preferred:n}),c]},sge=({model:e,view:t,filter:n=``,sort:r=``,columns:i,limit:a=10,display:o,title:s,description:c,empty:l,actions:u})=>{let[d,f]=J5(t,`page:${e.name}:${s??``}:${n}`,o);return(0,V.jsx)(nT,{title:s,description:c,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(K5,{view:t,value:d,onChange:f}),u]}),className:`h-full`,children:(0,V.jsx)(q5,{model:e,view:t,filter:n,sort:r,columns:i,limit:a,display:d,empty:l})})},cge={Page:Wue,Grid:Mue,Card:iT,Stat:She,RecordCard:que,Field:Due,Table:({node:e,slots:t})=>{let n=eT(e),{resources:r,views:i}=q(),a=r[n.resource];return a?(0,V.jsx)(sge,{...n,model:a,view:i[a.name],actions:t.actions}):null},CardRow:oT,RecordRow:vhe,Chart:xue,Progress:Gue,ModalForm:Uue,Action:tT,Show:yhe,Link:Nue},Y5=e=>typeof e==`string`||!e.custom&&e.type===`Link`,X5=e=>{let t=[];for(let n of e){let e=t.at(-1);Y5(n)&&e&&Y5(e[0])?e.push(n):t.push([n])}return t.map((e,t)=>{let[n]=e;return Y5(n)?(0,V.jsx)(`p`,{className:`leading-6`,children:e.map((e,t)=>typeof e==`string`?(0,V.jsx)(o.Fragment,{children:e},t):(0,V.jsx)(Z5,{node:e},t))},t):(0,V.jsx)(Z5,{node:n},t)})},lge=e=>Xs(e)||Array.isArray(e)&&e.length>0&&e.every(Xs),uge=e=>Object.fromEntries(Object.entries(e.props).flatMap(([e,t])=>lge(t)?[[e,(0,V.jsx)(V.Fragment,{children:X5(Array.isArray(t)?t:[t])})]]:[])),Z5=({node:e})=>{let{components:t}=Zg();if(e.custom){let n=t?.[e.type];return n?(0,V.jsx)(ng,{name:e.type,children:(0,V.jsx)(n,{...ho(e.props),children:e.children.length>0?X5(e.children):void 0})}):(0,V.jsxs)(tg,{children:[`No component is registered as `,e.type,`. Export it from protobase.ui.tsx, or load the plugin that provides it.`]})}let n=cge[e.type];return n?(0,V.jsx)(n,{node:e,slots:uge(e),children:X5(e.children)}):(0,V.jsxs)(tg,{children:[e.type,` is not a block this version of the app knows.`]})},Q5=({name:e})=>{let t=q().pages[e];return t?(0,V.jsx)(Z5,{node:t.tree}):(0,V.jsxs)(d_,{title:`Not found`,children:[`There is no page called `,e,`.`]})},dge=2e3,$5=(e,t)=>{let n=Lg(),[r,i]=(0,o.useState)(`idle`),[a,s]=(0,o.useState)(),c=(0,o.useRef)(void 0);return(0,o.useEffect)(()=>()=>clearTimeout(c.current),[]),{phase:r,message:a,run:async r=>{let a=e===`toast`?n.show({state:`loading`,title:`Saving ${t}...`}):void 0;s(void 0),e===`button`&&i(`saving`);try{return await r(),a!==void 0&&n.update(a,{state:`success`,title:`${t} saved`}),e===`button`&&(i(`saved`),c.current=setTimeout(()=>i(`idle`),dge)),!0}catch(t){if(!Fs(t))throw t;let r=t.status===412?`Changed by someone else`:`Could not save`,o=Rue(t);return a!==void 0&&n.update(a,{state:`error`,title:r,description:o}),e===`button`&&(i(`idle`),s(`${r}: ${o}`)),!1}}}},e7=({title:e,eyebrow:t,submit:n,saving:r,disabled:i,error:a,errorTitle:o=`Not saved`,onSubmit:s,onCancel:c,children:l,ref:u})=>{let d=(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[c&&(0,V.jsx)(U,{className:`max-sm:min-h-11`,onClick:c,children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,className:`max-sm:min-h-11 max-sm:flex-1`,loading:r,disabled:i,children:n})]}),f=a!==void 0&&(0,V.jsx)(`div`,{className:`mt-4`,children:(0,V.jsx)(pS,{title:o,error:a})}),p=(0,V.jsx)(`div`,{className:`divide-y divide-border`,children:l}),m=e=>{e.preventDefault(),s()};return e===void 0?(0,V.jsxs)(`form`,{ref:u,className:`max-w-[760px]`,onSubmit:m,children:[f,p,(0,V.jsx)(`footer`,{className:`border-t pt-6 sm:flex sm:justify-end`,children:d})]}):(0,V.jsx)(`form`,{ref:u,className:`flex-1`,onSubmit:m,children:(0,V.jsxs)(`div`,{className:`mx-auto max-w-[760px] px-4 py-6 md:px-10 md:py-8`,children:[(0,V.jsxs)(`header`,{className:`flex flex-col gap-4 border-b pb-6 sm:flex-row sm:items-end sm:justify-between sm:gap-6`,children:[(0,V.jsxs)(`div`,{children:[t&&(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:t}),(0,V.jsx)(`h1`,{className:`mt-1 text-2xl font-semibold tracking-tight`,children:e})]}),d]}),f,p]})})},fge=({noun:e,collection:t,sections:n,saving:r,message:i,onSubmit:a,onCancel:o,ref:s})=>(0,V.jsx)(e7,{ref:s,title:`New ${e.toLowerCase()}`,eyebrow:t,submit:`Create ${e.toLowerCase()}`,saving:r,error:i?Error(i):void 0,errorTitle:`Not created`,onSubmit:a,onCancel:o,children:n.map(e=>(0,V.jsx)(xx,{title:e.title,help:e.help,children:(0,V.jsx)(`div`,{className:`grid grid-cols-1 gap-x-6 gap-y-5 sm:grid-cols-2`,children:e.fields.map(e=>(0,V.jsx)(bx,{name:e.name,label:e.label,required:e.required,help:e.help,error:e.error,wide:e.wide,children:e.editor},e.name))})},e.title))}),pge=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),mge=({resource:e,values:t})=>{let n=q(),r=n.resources[e],i=f_(e);return r?Fw(i,`create`)?(0,V.jsx)(hge,{resource:e,values:t}):(0,V.jsxs)(d_,{title:`Not allowed`,children:[`You cannot create `,n.views[e]?.names?.plural.toLowerCase()??e,`.`]}):(0,V.jsxs)(d_,{title:`Not found`,children:[`There is no resource called `,e,`.`]})},hge=({resource:e,values:t})=>{let n=q(),r=n.resources[e],i=n.views[e],a=G(),s=Wp(),{go:c}=PC(),l=i?.names?.singular??K(e),u=$5(i?.saveFeedback??`toast`,`New ${l.toLowerCase()}`),d=aS(r,i),[f,p]=(0,o.useState)(()=>uS(r,d,t)),[m,h]=(0,o.useState)({}),[g,_]=(0,o.useState)(0),v=U4(g);(0,o.useEffect)(()=>{for(let[e,i]of Object.entries(t??{})){let t=n.resources[r.fields[e]?.relation?.resource??``];t&&D4(s,a,t,[i],n.views[t.name]).then(t=>{let n=t.get(i);n&&p(t=>rS(t[e])&&t[e].key===i?{...t,[e]:{key:i,label:n}}:t)})}},[t,n,r,a,s]);let y=(e,t)=>{h(t=>pge(t,e)),p(n=>({...n,[e]:t}))},b=()=>u.run(async()=>{let t;try{t=await a.create(e,sS(r,n.resources,f))}catch(e){let t=H4(e);throw h(t),Object.keys(t).length>0&&_(e=>e+1),e}for(let t of[`page`,`list`,`first-page`,`map`,`facets`,`series`])s.invalidateQueries({queryKey:[t,e]});c({kind:`record`,resource:e,key:jg(r,t.record)},{replace:!0})}),x=d.map(e=>({title:e.title,help:e.help,fields:e.fields.map(e=>{let t=r.fields[e],a=f[e],o=t.relation?n.resources[t.relation.resource]:void 0,s=i?.fields[e]?.label??K(e),c=m[e];return{name:e,label:s,help:i?.fields[e]?.help,required:cS(t),error:c&&V4(t,s,c),wide:!!(i?.fields[e]?.multiline||i?.fields[e]?.markdown),editor:(0,V.jsx)(mw,{field:t,hints:i?.fields[e],value:rS(a)?a.key:a??(t.type!==`boolean`&&``),stored:void 0,relationLabel:rS(a)?a.label:void 0,placeholder:dS(t)?`Set by the database`:void 0,relationPicker:o?{target:o,view:n.views[o.name]}:void 0,invalid:!!m[e],resource:r.name,onChange:t=>y(e,t)})}})}));return(0,V.jsx)(fge,{ref:v,noun:l,collection:i?.names?.plural??K(e),sections:x,saving:u.phase===`saving`,message:u.message,onSubmit:()=>void b(),onCancel:()=>c({kind:`list`,resource:e})})},gge=({resource:e,values:t})=>{let n=q(),r=n.views[e];return r?.create?n.pages[r.create.page]?(0,V.jsx)(Q5,{name:r.create.page}):(0,V.jsxs)(d_,{title:`Not allowed`,children:[`You cannot create `,r.names?.plural.toLowerCase()??K(e),`.`]}):(0,V.jsx)(mge,{resource:e,values:t},new URLSearchParams(t).toString())},_ge=(e,t)=>{let n=new Map(t.map(e=>[e.value,e.count]));return e.map(([e,t])=>({value:e,label:t,...n.get(e)!==void 0&&{count:n.get(e)}}))},vge=(e,t)=>[...new Set(t.filter(t=>!e.includes(t)))],yge=uo(),bge=(e,t)=>{let n=G(),[r,i]=(0,o.useState)({}),a=e=>!!e?.search?.length&&e.primaryKey.length===1,s=gh({queries:e.map(({id:e,target:i})=>{let o=(r[e]??``).trim();return{queryKey:[`reference-search`,e,i?.name??``,o],enabled:a(i)&&o!==``,placeholderData:mm,queryFn:async()=>{let e=i.primaryKey[0],r=Eg(i,t[i.name]);return(await n.list(i.name,{filter:Ya(yge.search(o)),fields:[e,r],pageSize:20})).items.map(t=>[String(t[e]),String(t[r])])}}})});return e.map(({id:e,target:t},n)=>{if(!a(t))return{};let o=t=>i(n=>({...n,[e]:t}));return(r[e]??``).trim()===``?{onSearch:o}:{onSearch:o,matches:s[n]?.data??[]}})},xge=24,Sge=({model:e,resources:t,views:n,view:r,state:i,extras:a})=>{let o=G(),s=Wp(),c=P8(r,e),l=e=>r?.fields[e]?.label??K(e),u=n=>{let r=e.fields[n];return r?.type===`relation`&&r.relation?t[r.relation.resource]:void 0},d=c.facets.flatMap(e=>(e.flags?e.options.map(e=>e.value):[e.id]).map(t=>({group:e.id,field:t}))),f=gh({queries:d.map(({group:t,field:r})=>{let s=D8(c,{...i,facets:{...i.facets,[t]:[]}},a),l=u(r),d=l?.primaryKey.length===1?Eg(l,n[l.name]):void 0;return{queryKey:W.facets(e.name,r,s),queryFn:()=>o.facets(e.name,r,{filter:s,limit:50,...d&&{label:d}})}})}),p=(e,t)=>f[d.findIndex(n=>n.group===e&&n.field===t)]?.data,m=gh({queries:c.facets.map(t=>{let r=u(t.id),a=vge((p(t.id,t.id)??[]).flatMap(e=>e.value===null?[]:[String(e.value)]),i.facets[t.id]??[]);return{queryKey:W.labels(`facet:${e.name}.${t.id}`,a.join(`,`)),enabled:!!r&&a.length>0,queryFn:async()=>[...await D4(s,o,r,a,n[r.name])]}})}),h=bge(c.facets.map(e=>({id:e.id,target:e.combobox?u(e.id):void 0})),n),g=c.ranges??[],_=gh({queries:g.map(t=>{let n=D8(c,c8(i,t.id,void 0),a),s=F8(r,t.id)?xge:1;return{queryKey:W.histogram(e.name,t.id,s,n),queryFn:()=>o.histogram(e.name,t.id,{filter:n,buckets:s})}})});return{facets:c.facets.map((t,n)=>{if(t.flags){let e=t.options.map(({value:e})=>({value:e,label:l(e),count:p(t.id,e)?.find(e=>String(e.value)===`true`)?.count??0}));return{...t,options:e}}let i=e.fields[t.id],a=(p(t.id,t.id)??[]).flatMap(e=>e.label===void 0?[]:[[String(e.value),e.label]]),o=new Map([...a,...m[n]?.data??[]]),s=(p(t.id,t.id)??[]).flatMap(e=>e.value===null?[]:[{value:String(e.value),label:i?.type===`enum`?rs(String(e.value),r?.fields[t.id]?.valueLabels):o.get(String(e.value))??String(e.value),count:e.count}]),c=h[n];return{...t,label:l(t.id),options:c.matches?_ge(c.matches,s):s,...o.size>0&&{labels:Object.fromEntries(o)},...c.onSearch&&{onSearch:c.onSearch}}}),ranges:g.flatMap((e,t)=>{let n=_[t]?.data;return!n||n.min===null||n.max===null?[]:[{...e,label:l(e.id),min:Math.floor(n.min),max:Math.ceil(n.max),step:Math.max(1,Math.round((n.max-n.min)/100)),histogram:F8(r,e.id)?n.buckets.map(e=>e.count):[],format:I8(r,e.id)}]}),...c.dateField&&{datePresets:c.datePresets??!0,dateField:c.dateField,dateKind:c.dateKind},toggles:c.toggles?.map(e=>({...e,label:l(e.id)}))}},Cge=uo(),wge=({blockingPlural:e,noun:t})=>`${e} still point at this ${t.toLowerCase()}.`,Tge=({blockedBy:e,resources:t,views:n,noun:r,key:i})=>{let{resource:a,field:o}=e;if(!t[a])return;let s=n[a]?.names?.plural??K(a),c=wge({blockingPlural:s,noun:r});if(!o||i===void 0)return{text:c};let l={kind:`list`,resource:a,filter:Ya(Cge.eq(o,i))};return{text:c,link:{label:`Show ${s.toLowerCase()}`,to:l}}},Ege=({title:e,noun:t,busy:n,onConfirm:r,onCancel:i})=>(0,V.jsx)(Cf,{title:`Delete ${e}?`,description:`This ${t.toLowerCase()} will be removed. This cannot be undone.`,onClose:i,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:i,children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,className:`bg-danger hover:bg-danger/90`,loading:n,onClick:r,children:`Delete`})]})}),Dge=({title:e,changes:t,busy:n,onReview:r,onDeleteAnyway:i,onCancel:a})=>(0,V.jsx)(Cf,{title:`${e} was changed since you opened it`,description:`Someone saved this record in the meantime. Review what changed before you delete it.`,onClose:a,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:r,children:`Review changes`}),(0,V.jsx)(U,{variant:`primary`,className:`bg-danger hover:bg-danger/90`,loading:n,onClick:i,children:`Delete anyway`})]}),children:t.length===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`No visible fields differ; the record was saved again with the same values.`}):(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:t.map(e=>(0,V.jsxs)(`li`,{className:`grid grid-cols-[96px_1fr] gap-3 px-3 py-2`,children:[(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:e.label}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`span`,{className:`text-muted-foreground line-through`,children:e.before}),` `,(0,V.jsx)(`span`,{className:`font-medium`,children:e.after})]})]},e.field))})}),t7=e=>{if(e.stage===`confirm`)return(0,V.jsx)(Cf,{title:`Delete ${e.count} ${e.count===1?e.plural.replace(/s$/,``):e.plural.toLowerCase()}?`,description:`This cannot be undone. Each record is deleted only if it has not changed since the list loaded; anything that changed is reported and kept.`,onClose:e.onCancel,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:e.onCancel,children:`Cancel`}),(0,V.jsxs)(U,{variant:`primary`,className:`bg-danger hover:bg-danger/90`,onClick:e.onConfirm,children:[`Delete `,e.count]})]})});if(e.stage===`running`)return(0,V.jsx)(Cf,{title:`Deleting`,description:`${e.done} of ${e.total} done`,onClose:()=>void 0,actions:(0,V.jsx)(U,{loading:!0,disabled:!0,children:`Working`})});let t=e.total-e.failures.length;return(0,V.jsx)(Cf,{title:e.failures.length===0?`Deleted ${t}`:`Deleted ${t} of ${e.total}`,description:e.failures.length===0?void 0:`${e.failures.length} could not be deleted and were kept.`,onClose:e.onClose,actions:(0,V.jsx)(U,{variant:`primary`,onClick:e.onClose,children:`Done`}),children:e.failures.length>0&&(0,V.jsx)(`ul`,{className:`max-h-48 divide-y overflow-y-auto rounded-md border`,children:e.failures.map(e=>(0,V.jsxs)(`li`,{className:`px-3 py-2`,children:[(0,V.jsx)(`span`,{className:`font-medium`,children:e.title}),(0,V.jsx)(`span`,{className:`block text-xs text-danger-text`,children:e.message})]},e.title))})})},Oge=new Set([`updated_at`,`updatedAt`]),kge=(e,t,n,r)=>Object.values(e.fields).flatMap(e=>{if(Oge.has(e.name)||JSON.stringify(n[e.name]??null)===JSON.stringify(r[e.name]??null))return[];let i=t?.fields[e.name];return[{field:e.name,label:i?.label??K(e.name),before:ZS(e,n[e.name],i),after:ZS(e,r[e.name],i)}]}),Age=4,n7=({model:e,view:t,onDeleted:n,onReview:r,restore:i})=>{let a=G(),s=Wp(),c=Lg(),[l,u]=(0,o.useState)(),[d,f]=(0,o.useState)(!1),p=t?.names?.singular??K(e.name),m=t?.names?.plural??K(e.name),{resources:h,views:g}=q(),{href:_,open:v}=PC(),y=(t,n)=>t.blockedBy&&Tge({blockedBy:t.blockedBy,resources:h,views:g,noun:p,...e.primaryKey.length===1&&{key:n.key}}),b=()=>{for(let t of[`page`,`list`,`first-page`,`map`])s.invalidateQueries({queryKey:[t,e.name]});for(let t of[`facets`,`series`,`histogram`])s.invalidateQueries({queryKey:[t,e.name]})},x=async(t,n)=>{let r=n??(await a.get(e.name,t.key)).etag;try{await a.remove(e.name,t.key,{etag:r})}catch(e){if(!(e instanceof Ps))throw e;return e}},S=t=>{b(),u(void 0),n?.(t),c.show({state:`success`,title:`${t.title} deleted`,...e.softDelete&&i&&{action:{label:`Undo`,onClick:()=>{i(t).then(()=>{b(),c.show({state:`success`,title:`${t.title} restored`})},e=>{if(!Fs(e))throw e;b(),c.show({state:e.status===409?`success`:`error`,title:e.status===409?`${t.title} is already back`:`Could not restore ${t.title}`,description:e.status===409?void 0:e.message})})}}}})},C=async(n,r)=>{f(!0);try{if(!await x(n,r))return S(n);let i=(await a.get(e.name,n.key)).record;u({kind:`conflict`,target:n,fresh:i,changes:kge(e,t,n.snapshot,i)})}catch(e){if(!Fs(e))throw e;u(void 0);let t=y(e,n);c.show({state:`error`,title:`Could not delete ${n.title}`,description:t?.text??e.message,...t?.link&&{action:{label:t.link.label,href:_(t.link.to),onNavigate:v}}})}finally{f(!1)}},w=async e=>{try{return await x(e,e.etag)?{title:e.title,message:`Changed since the list loaded, so it was kept.`}:void 0}catch(t){if(!Fs(t))throw t;return{title:e.title,message:y(t,e)?.text??t.message}}},T=async e=>{let t=[],n=0;u({kind:`bulk-running`,done:n,total:e.length});let r=[...e];await Promise.all(Array.from({length:Math.min(Age,e.length)},async()=>{for(let i=r.shift();i;i=r.shift()){let r=await w(i);r&&t.push(r),n+=1,u({kind:`bulk-running`,done:n,total:e.length})}})),b(),u({kind:`bulk-done`,total:e.length,failures:t})},E=()=>u(void 0);return{dialogs:l&&(0,V.jsxs)(V.Fragment,{children:[l.kind===`confirm`&&(0,V.jsx)(Ege,{title:l.target.title,noun:p,busy:d,onCancel:E,onConfirm:()=>void C(l.target,l.target.etag)}),l.kind===`conflict`&&(0,V.jsx)(Dge,{title:l.target.title,changes:l.changes,busy:d,onCancel:E,onReview:()=>{E(),r?.(l.target,l.fresh)},onDeleteAnyway:()=>void C(l.target,`*`)}),l.kind===`bulk-confirm`&&(0,V.jsx)(t7,{stage:`confirm`,count:l.targets.length,plural:m,onCancel:E,onConfirm:()=>void T(l.targets)}),l.kind===`bulk-running`&&(0,V.jsx)(t7,{stage:`running`,done:l.done,total:l.total}),l.kind===`bulk-done`&&(0,V.jsx)(t7,{stage:`done`,total:l.total,failures:l.failures,onClose:E})]}),start:t=>e.softDelete?C(t,t.etag):u({kind:`confirm`,target:t}),startBulk:e=>u({kind:`bulk-confirm`,targets:e})}},r7=e=>{let t=G();return e.softDelete?async n=>void await t.undelete(e.name,n.key):void 0},jge=(e,t,n)=>e?.create?Object.hasOwn(t,e.create.page):Fw(n,`create`),i7=e=>typeof e==`object`&&!!e,a7=e=>e===null||typeof e==`string`&&e.trim()===``,o7=e=>e===null?``:i7(e)?e.date.replace(`T`,` `):typeof e==`boolean`?e?`TRUE`:`FALSE`:String(e),s7=e=>e<26?String.fromCharCode(65+e):s7(Math.floor(e/26)-1)+s7(e%26),c7=(e,t)=>e[t]?.trim()?e[t]:`Column ${s7(t)}`,Mge=e=>/[",\r\n]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e,Nge=(e,t)=>{let n=[...t].sort((e,t)=>e.line-t.line).map(t=>[...e.map((e,n)=>o7(t.cells[n]??null)),String(t.line),t.problems.join(`; `)]);return`${[[...e,`Line`,`Problems`],...n].map(e=>e.map(Mge).join(`,`)).join(`\r
|
|
68
|
-
`)}\r\n`},l7=({label:e,counts:t})=>(0,V.jsx)(`dl`,{"aria-label":e,className:`grid grid-cols-2 gap-3 sm:grid-cols-4`,children:t.map(([e,t])=>(0,V.jsxs)(`div`,{className:`rounded-lg border px-3 py-2`,children:[(0,V.jsx)(`dt`,{className:`text-xs text-muted-foreground`,children:e}),(0,V.jsx)(`dd`,{className:`text-lg font-semibold tabular-nums`,children:t.toLocaleString(`en-IE`)})]},e))}),u7=(e,t)=>e?.fields[t]?.label??K(t),Pge=new Set([`text`,`integer`,`bigint`,`decimal`,`boolean`,`date`,`timestamp`,`uuid`,`enum`,`relation`,`currency`,`country`]),d7=(e,t)=>{let n=e.relation?t[e.relation.resource]:void 0;return n?.primaryKey.length===1?n:void 0},Fge=(e,t)=>Object.values(e.fields).filter(n=>n.readOnly||n.name===e.tenant||!Pge.has(n.type)?!1:n.type!==`relation`||d7(n,t)!==void 0),Ige=new Set([`text`,`integer`,`bigint`,`uuid`,`date`,`currency`,`country`,`enum`]),f7=e=>{let t=e.primaryKey.length===1?[e.fields[e.primaryKey[0]]]:[],n=Object.values(e.fields).filter(t=>t.filterable&&!t.sensitive&&Ige.has(t.type)&&!e.primaryKey.includes(t.name));return[...t,...n]},p7=(e,t)=>d7(e,t),m7=e=>!e.nullable&&!e.default,h7=e=>e.toLowerCase().replace(/[\s_-]+/g,``),g7=(e,t,n)=>{let r=new Set;return e.flatMap((e,i)=>{let a=h7(e);if(a===``)return[];let o=t.find(e=>!r.has(e.name)&&(h7(u7(n,e.name))===a||h7(e.name)===a));return o?(r.add(o.name),[{column:i,field:o.name}]):[]})},_7=(e,t,n)=>{if(e===`update`)return[];let r=new Set(n.map(e=>e.field));return t.filter(e=>m7(e)&&!r.has(e.name))},v7=e=>({ok:!0,value:e}),y7=e=>({ok:!1,problem:e}),b7=e=>`“${o7(e)}”`,x7=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),Lge=(e,t)=>{let n=`[${x7(t===`.`?`,`:`.`)}\\s\\u00a0\\u202f']`,r=RegExp(`^([-+]?)(\\d{1,3}(?:${n}\\d{3})+|\\d+)(?:${x7(t)}(\\d+))?$`).exec(e.trim());if(r)return`${r[1]===`-`?`-`:``}${r[2].replace(/\D/g,``)}${r[3]?`.${r[3]}`:``}`;if(t===`.`&&/^[-+]?\d+(\.\d+)?e[-+]?\d+$/i.test(e.trim()))return String(Number(e.trim()))},S7=(e,t)=>{if(typeof e==`number`)return String(e);if(typeof e==`string`)return Lge(e,t.decimal)},Rge=(e,t,n)=>{let r=S7(t,n);if(r===void 0)return y7(`${b7(t)} is not a number`);let[i,a=``]=r.split(`.`);if(/[1-9]/.test(a)||/e/i.test(r))return y7(`${b7(t)} is not a whole number`);if(e.type===`bigint`)return v7(String(BigInt(i)));let o=Number(i);return Number.isSafeInteger(o)?v7(o):y7(`${b7(t)} is too large`)},zge=(e,t)=>{let n=S7(e,t);return n===void 0?y7(`${b7(e)} is not a number`):v7(n)},Bge=new Set([`true`,`yes`,`1`]),Vge=new Set([`false`,`no`,`0`]),Hge=e=>{if(typeof e==`boolean`)return v7(e);let t=typeof e==`string`||typeof e==`number`?String(e).trim().toLowerCase():``;return Bge.has(t)?v7(!0):Vge.has(t)?v7(!1):y7(`${b7(e)} is not true or false (true, false, yes, no, 1 or 0)`)},C7=e=>String(e).padStart(2,`0`),Uge=(e,t,n)=>{let r=new Date(Date.UTC(e,t-1,n));if(r.getUTCFullYear()===e&&r.getUTCMonth()===t-1&&r.getUTCDate()===n)return`${e}-${C7(t)}-${C7(n)}`},w7=`(\\d{1,2}):(\\d{2})(?::(\\d{2})(?:\\.\\d+)?)?`,Wge=(e,t)=>{let n=RegExp(`^(\\d{4})[-/](\\d{1,2})[-/](\\d{1,2})(?:[T ]${w7}(Z|[+-]\\d{2}:?\\d{2})?)?$`).exec(e.trim()),r=RegExp(`^(\\d{1,2})[./-](\\d{1,2})[./-](\\d{4})(?: ${w7})?$`).exec(e.trim());if(!n&&!r)return;let[i,a,o]=n?[n[1],n[2],n[3]].map(Number):t===`dmy`?[r[3],r[2],r[1]].map(Number):[r[3],r[1],r[2]].map(Number),s=Uge(i,a,o);if(!s)return;let[c,l,u=`0`]=n?n.slice(4,7):r.slice(4,7);if(c===void 0)return{date:s};if(!(Number(c)>23||Number(l)>59||Number(u)>59))return{date:s,time:`${C7(Number(c))}:${l}:${C7(Number(u))}`,zone:n?.[7]}},T7=(e,t)=>{if(i7(e)){let[t,n]=e.date.split(`T`);return{date:t,time:n}}return typeof e==`string`?Wge(e,t.dateOrder):void 0},E7=(e,t)=>y7(`${b7(e)} is not a date (2026-04-03 or ${t.dateOrder===`dmy`?`day/month/year`:`month/day/year`})`),Gge=(e,t)=>{let n=T7(e,t);return n?n.time&&n.time!==`00:00:00`?y7(`${b7(e)} has a time of day; the field holds a date`):v7(n.date):E7(e,t)},Kge=(e,t)=>{let n=T7(e,t);if(!n)return E7(e,t);if(n.zone)return v7(new Date(`${n.date}T${n.time}${n.zone===`Z`?`Z`:n.zone.replace(/^([+-]\d{2})(\d{2})$/,`$1:$2`)}`).toISOString());let[r,i,a]=n.date.split(`-`).map(Number),[o,s,c]=(n.time??`00:00:00`).split(`:`).map(Number);return v7(new Date(r,i-1,a,o,s,c).toISOString())},D7=e=>e.trim().toLowerCase().replace(/\s+/g,` `),qge=(e,t,n)=>{let r=e.enumValues??[],i=D7(o7(n)),a=r.filter(e=>D7(e)===i||D7(rs(e,t?.valueLabels))===i);return a.length===1?v7(a[0]):a.length>1?y7(`${b7(n)} matches more than one value: ${a.map(e=>rs(e,t?.valueLabels)).join(`, `)}`):y7(`${b7(n)} is not one of ${r.map(e=>rs(e,t?.valueLabels)).join(`, `)}`)},Jge=e=>typeof e==`boolean`?y7(`${b7(e)} is true or false, not text`):v7(o7(e)),O7=(e,t,n,r)=>{if(a7(n))return e.nullable?v7(null):y7(`is empty, and it is required`);switch(e.type){case`integer`:case`bigint`:return Rge(e,n,r);case`decimal`:return zge(n,r);case`boolean`:return Hge(n);case`date`:return Gge(n,r);case`timestamp`:return Kge(n,r);case`enum`:return qge(e,t,n);case`text`:case`uuid`:case`currency`:case`country`:return Jge(n);default:throw Error(`Not implemented: importing ${e.type} fields, which importableFields leaves out`)}},Yge=(e,t)=>e[t]?.names?.singular??K(t),Xge=(e,t)=>e[t]?.names?.plural??K(t),Zge=(e,t,n)=>{let{model:r,resources:i,views:a}=n,o=a[r.name],s={},c={},l=[],u=[];for(let{column:n,field:d,matchBy:f}of t.columns){let p=r.fields[d],m=e.cells[n]??null,h=u7(o,d),g=p7(p,i);if(g&&!a7(m)){let e=f??g.primaryKey[0],n=O7(g.fields[e],a[g.name]?.fields[e],m,t.options);n.ok?u.push({field:d,finding:{model:g,field:e,value:n.value}}):l.push(`${h}: ${n.problem}`),s[d]=o7(m);continue}let _=O7(p,o?.fields[d],m,t.options);_.ok?c[d]=s[d]=_.value:l.push(`${h}: ${_.problem}`)}let d;if(t.match&&t.mode!==`create`){let n=r.fields[t.match.field],i=O7({...n,nullable:!1},o?.fields[n.name],e.cells[t.match.column]??null,t.options);i.ok?d={model:r,field:n.name,value:i.value}:l.push(`${u7(o,n.name)}: ${i.problem}`)}return{values:s,data:c,problems:l,relations:u,match:d}},k7=(e,t)=>{let n=e.lookups.keysOf(t.model.name,t.field,t.value),r=`${u7(e.views[t.model.name],t.field).toLowerCase()} “${String(t.value)}”`;return n.length===1?{key:n[0]}:n.length===0?{none:`no ${Yge(e.views,t.model.name).toLowerCase()} has ${r}`}:{several:`${n.length} ${Xge(e.views,t.model.name).toLowerCase()} have ${r}`}},Qge=e=>e.cells.every(a7),A7=async(e,t,n)=>{let{model:r,views:i}=n,a=e.filter(e=>!Qge(e)).map(e=>({row:e,...Zge(e,t,n)})),o=new Map;for(let e of a.flatMap(e=>[...e.relations.map(e=>e.finding),...e.match?[e.match]:[]])){let t=`${e.model.name}.${e.field}`;o.has(t)||o.set(t,{model:e.model,field:e.field,values:[]}),o.get(t).values.push(e.value)}for(let{model:e,field:t,values:r}of o.values())await n.lookups.load(e,t,r);return a.map(({row:e,values:a,data:o,problems:s,relations:c,match:l})=>{let u={...o};for(let{field:e,finding:t}of c){let a=k7(n,t);`key`in a?u[e]=a.key:s.push(`${u7(i[r.name],e)}: ${a.none??a.several}`)}let d=l&&k7(n,l);d?.several&&s.push(`Not one record: ${d.several}`),d?.none&&t.mode===`update`&&s.push(`Nothing to update: ${d.none}`);let f={line:e.line,cells:e.cells,values:a,problems:s};return s.length>0?f:d&&`key`in d?{...f,op:{op:`update`,resource:r.name,key:d.key,etag:`*`,data:u}}:{...f,op:{op:`create`,resource:r.name,data:u}}})},$ge=5,e_e=5,t_e=async(e,t)=>{let n=e.rows(t),{value:r=[]}=await n.next();await n.return(void 0);let[i,...a]=r;return{headers:(i?.cells??[]).map(o7),sample:a.slice(0,$ge)}};async function*j7(e,t){let n=!0;for await(let r of e.rows(t))yield n?r.slice(1):r,n=!1}var n_e=async(e,t,n,r,i,a)=>{let o={rows:0,creates:0,updates:0,problems:[],preview:[]};for await(let s of j7(e,t)){a?.throwIfAborted();for(let e of await A7(s,n,r))o.rows++,o.preview.length<e_e&&o.preview.push(e),e.op?.op===`create`?o.creates++:e.op?.op===`update`?o.updates++:o.problems.push({line:e.line,cells:e.cells,problems:e.problems});i(o.rows)}return o},r_e=(e,t)=>{if(!Fs(e))return[e.message];let n=e.errors.filter(e=>e.field);return n.length===0?[e.message]:n.map(e=>`${u7(t.views[t.model.name],e.field)}: ${e.message}`)},i_e=async(e,t,n,r,{client:i,onProgress:a,cancelled:o})=>{let s={created:0,updated:0,skipped:0,failed:0,notWritten:[]},c=async e=>{let t=[...e];for(;t.length>0;){let e=t.map(e=>e.op);try{let{results:t}=await i.batchWrite(e);for(let e of t)e.op===`create`?s.created++:e.op===`update`&&s.updated++;return}catch(e){let n=Fs(e)?e.operation:void 0;if(n===void 0||!t[n])throw e;let[i]=t.splice(n,1);s.failed++,s.notWritten.push({line:i.line,cells:i.cells,problems:r_e(e,r)})}}},l=[],u=async e=>{for(;l.length>=100||e&&l.length>0;){if(o())return!1;await c(l.splice(0,100)),a({...s})}return!0};for await(let i of j7(e,t)){for(let e of await A7(i,n,r))e.op?l.push(e):(s.skipped++,s.notWritten.push({line:e.line,cells:e.cells,problems:e.problems}));if(!await u(!1))return{...s,cancelled:!0}}return await u(!0)?{...s,cancelled:!1}:{...s,cancelled:!0}},M7=50,N7=(e,t,n)=>kf(Nge(t,n),`${(e??`import`).replace(/\.[^.]+$/,``)} - not imported.csv`,`text/csv`),P7=({rows:e})=>(0,V.jsxs)(`ul`,{"aria-label":`Rows not imported`,className:`flex flex-col gap-1 text-xs`,children:[e.slice(0,M7).map(e=>(0,V.jsxs)(`li`,{children:[(0,V.jsxs)(`span`,{className:`font-medium`,children:[`Row `,e.line,`:`]}),` `,e.problems.join(`; `)]},e.line)),e.length>M7&&(0,V.jsxs)(`li`,{className:`text-muted-foreground`,children:[`And `,(e.length-M7).toLocaleString(`en-IE`),` more rows, all in the file.`]})]}),a_e=({rows:e})=>(0,V.jsxs)(`p`,{className:`flex items-center gap-2 text-muted-foreground`,role:`status`,children:[(0,V.jsx)(Dd,{className:`size-3.5`}),`Checking rows… `,e.toLocaleString(`en-IE`),` read`]}),o_e=({check:e,model:t,resources:n,views:r,columns:i,headers:a,fileName:o})=>{let s=r[t.name],c=i.map(e=>t.fields[e.field]);return(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,V.jsx)(l7,{label:`Check`,counts:[[`Rows`,e.rows],[`To create`,e.creates],[`To update`,e.updates],[`With problems`,e.problems.length]]}),e.preview.length>0&&(0,V.jsx)(`div`,{className:`overflow-x-auto rounded-lg border`,children:(0,V.jsxs)(`table`,{"aria-label":`First rows`,className:`w-full text-left text-xs`,children:[(0,V.jsx)(`thead`,{className:`bg-muted text-muted-foreground`,children:(0,V.jsxs)(`tr`,{children:[(0,V.jsx)(`th`,{className:`px-2 py-1.5 font-medium`,children:`Row`}),c.map(e=>(0,V.jsx)(`th`,{className:`whitespace-nowrap px-2 py-1.5 font-medium`,children:u7(s,e.name)},e.name))]})}),(0,V.jsx)(`tbody`,{className:`divide-y`,children:e.preview.map(e=>(0,V.jsxs)(`tr`,{className:e.problems.length>0?`bg-danger-soft`:void 0,children:[(0,V.jsx)(`td`,{className:`px-2 py-1.5 tabular-nums text-muted-foreground`,children:e.line}),c.map(t=>(0,V.jsx)(`td`,{className:`max-w-48 truncate px-2 py-1.5`,children:p7(t,n)?String(e.values[t.name]??`—`):t.name in e.values?ZS(t,e.values[t.name],s?.fields[t.name]):``},t.name))]},e.line))})]})}),e.problems.length>0&&(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,V.jsx)(`h3`,{className:`font-medium`,children:`Rows with problems, which are skipped`}),(0,V.jsxs)(U,{size:`sm`,onClick:()=>N7(o,a,e.problems),children:[(0,V.jsx)(He,{className:`size-3.5`}),`Download`]})]}),(0,V.jsx)(P7,{rows:e.problems})]}),(0,V.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Rows are saved in batches of `,100,`. Cancelling, or an error, keeps the batches already saved; a row the server refuses is listed and the others are saved.`]})]})},F7=({label:e,name:t,value:n,options:r,onChange:i,help:a,className:s})=>{let c=(0,o.useId)();return(0,V.jsxs)(`div`,{className:B(`flex min-w-0 flex-col gap-1.5`,s),children:[(0,V.jsx)(`label`,{htmlFor:c,className:`font-medium`,children:e}),(0,V.jsx)(`select`,{id:c,"aria-label":t,value:n,onChange:e=>i(e.target.value),className:`h-8 w-full min-w-0 rounded-md border border-border-strong bg-background px-2 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 max-sm:min-h-11`,children:r.map(e=>(0,V.jsx)(`option`,{value:e.value,children:e.label},e.value))}),a&&(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:a})]})},s_e=({file:e,sheets:t,sheet:n,reading:r,onChoose:i,onSheet:a})=>{let s=(0,o.useId)();return(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsx)(`label`,{htmlFor:s,className:`font-medium`,children:`File`}),(0,V.jsx)(`input`,{id:s,type:`file`,accept:`.xlsx,.csv,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,disabled:r,onChange:e=>{let t=e.target.files?.[0];t&&i(t)},className:`file:mr-3 file:h-8 file:rounded-md file:border file:border-border-strong file:bg-background file:px-3 file:font-medium file:text-foreground max-sm:file:min-h-11`}),(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`An Excel workbook (.xlsx) or a CSV file saved as UTF-8. Its first row names the columns.`})]}),r&&(0,V.jsxs)(`p`,{className:`flex items-center gap-2 text-muted-foreground`,role:`status`,children:[(0,V.jsx)(Dd,{className:`size-3.5`}),`Reading `,e?.name??`the file`,`…`]}),!r&&t.length>1&&(0,V.jsxs)(`div`,{className:`flex items-end gap-3`,children:[(0,V.jsx)(nt,{className:`mb-2 size-4 shrink-0 text-muted-foreground`}),(0,V.jsx)(F7,{className:`flex-1`,label:`Sheet`,value:n??``,options:t.map(e=>({value:e,label:e})),onChange:a})]})]})},c_e=[{value:`create`,label:`Create`},{value:`update`,label:`Update`},{value:`upsert`,label:`Create or update`}],l_e={create:`Each row creates a record.`,update:`Each row updates the record its value finds; a row that finds none is not imported.`,upsert:`Each row updates the record its value finds, or creates one when it finds none.`},I7=``,u_e=({flow:e,model:t,resources:n,views:r,canUpdate:i})=>{let a=r[t.name],o=e.head?.headers??[],s=e.head?.sample??[],c=_7(e.mode,e.fields,e.columns),l=[{value:I7,label:`Do not import`},...e.fields.map(e=>({value:e.name,label:`${u7(a,e.name)}${m7(e)?` *`:``}`}))],u=o.map((e,t)=>({value:String(t),label:c7(o,t)})),d=f7(t);return(0,V.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[i&&(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsx)(`span`,{className:`font-medium`,children:`Rows`}),(0,V.jsx)(`div`,{children:(0,V.jsx)(ed,{label:`What each row does`,size:`md`,value:e.mode,options:c_e,onChange:e.setMode})}),(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:l_e[e.mode]})]}),e.mode!==`create`&&(0,V.jsxs)(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[(0,V.jsx)(F7,{label:`Find records by`,value:e.match?.field??I7,options:[{value:I7,label:`Choose a field`},...d.map(e=>({value:e.name,label:u7(a,e.name)}))],onChange:t=>e.setMatch(t?{field:t,column:e.match?.column??0}:void 0),help:`A field no two records share, such as the key or an email.`}),(0,V.jsx)(F7,{label:`Found in column`,value:e.match?String(e.match.column):I7,options:[{value:I7,label:`Choose a column`},...u],onChange:t=>e.setMatch(t&&e.match?{...e.match,column:Number(t)}:e.match)})]}),(0,V.jsxs)(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[(0,V.jsx)(F7,{label:`Numbers`,value:e.options.decimal,options:[{value:`.`,label:`1,234.56`},{value:`,`,label:`1.234,56`}],onChange:t=>e.setOptions({...e.options,decimal:t})}),(0,V.jsx)(F7,{label:`Dates`,value:e.options.dateOrder,options:[{value:`dmy`,label:`Day first (31/12/2026)`},{value:`mdy`,label:`Month first (12/31/2026)`}],onChange:t=>e.setOptions({...e.options,dateOrder:t}),help:`Dates written as 2026-12-31 read the same either way. Times without a zone are your own time.`})]}),e.mode!==`update`&&(0,V.jsx)(`p`,{className:`-mb-3 text-xs text-muted-foreground`,children:`New records need the fields marked *.`}),(0,V.jsx)(`section`,{"aria-label":`Columns`,className:`flex flex-col divide-y divide-border border-y`,children:o.map((i,c)=>{let u=e.columns.find(e=>e.column===c),d=u?t.fields[u.field]:void 0,f=d?p7(d,n):void 0,p=s.map(e=>o7(e.cells[c]??null)).filter(e=>e!==``).slice(0,3),m=c7(o,c);return(0,V.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 py-3 sm:grid-cols-2 sm:gap-4`,children:[(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsx)(`p`,{className:`truncate font-medium`,children:m}),(0,V.jsx)(`p`,{className:`truncate text-xs text-muted-foreground`,children:p.length>0?p.join(`, `):`Empty in the first rows`})]}),(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,V.jsx)(F7,{label:`Field`,name:`Field for ${m}`,value:u?.field??I7,options:l,onChange:t=>e.mapColumn(c,t||void 0)}),f&&(0,V.jsx)(F7,{label:`Found by`,name:`${r[f.name]?.names?.plural??u7(a,d.name)} found by`,value:u.matchBy??f.primaryKey[0],options:f7(f).map(e=>({value:e.name,label:u7(r[f.name],e.name)})),onChange:t=>e.matchColumnBy(c,t)})]})]},c)})}),c.length>0&&(0,V.jsxs)(`p`,{role:`alert`,className:`flex gap-2 rounded-lg border border-warning/30 bg-warning-soft px-3 py-2 text-warning-text`,children:[(0,V.jsx)(Bn,{className:`mt-0.5 size-4 shrink-0`}),(0,V.jsxs)(`span`,{children:[`No column fills `,c.map(e=>u7(a,e.name)).join(`, `),`, which new records need.`]})]})]})},L7=e=>e.toLocaleString(`en-IE`),d_e=({progress:e,total:t,cancelling:n})=>{let r=e.created+e.updated+e.failed;return(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs`,children:[(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:n?`Stopping after this batch…`:`Saving rows…`}),(0,V.jsxs)(`span`,{className:`tabular-nums`,children:[L7(r),` / `,L7(t)]})]}),(0,V.jsx)(`div`,{role:`progressbar`,"aria-label":`Rows saved`,"aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":t,className:`h-2 overflow-hidden rounded-full bg-muted`,children:(0,V.jsx)(`div`,{className:`h-full rounded-full bg-primary transition-[width]`,style:{width:`${t>0?Math.min(100,r/t*100):0}%`}})})]})},f_e=({result:e,stopped:t,headers:n,fileName:r})=>(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[t!==void 0&&(0,V.jsx)(pS,{title:`The import stopped. The rows counted below were saved.`,error:t}),e.cancelled&&(0,V.jsx)(`p`,{role:`status`,children:`Cancelled. The rows counted below were saved.`}),(0,V.jsx)(l7,{label:`Import summary`,counts:[[`Created`,e.created],[`Updated`,e.updated],[`Skipped`,e.skipped],[`Failed`,e.failed]]}),e.notWritten.length>0&&(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,V.jsx)(`h3`,{className:`font-medium`,children:`Rows not imported`}),(0,V.jsxs)(U,{size:`sm`,onClick:()=>N7(r,n,e.notWritten),children:[(0,V.jsx)(He,{className:`size-3.5`}),`Download`]})]}),(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Skipped rows had problems in the file; the server refused the failed ones. The file holds each with the reason, to fix and import again.`}),(0,V.jsx)(P7,{rows:[...e.notWritten].sort((e,t)=>e.line-t.line)})]})]}),p_e=e=>{let t=new Intl.NumberFormat(e).formatToParts(1.5).find(e=>e.type===`decimal`)?.value===`,`?`,`:`.`,n=new Intl.DateTimeFormat(e).formatToParts(new Date(2026,3,3)).map(e=>e.type);return{decimal:t,dateOrder:n.indexOf(`month`)<n.indexOf(`day`)?`mdy`:`dmy`}},m_e=uo(),R7=100,z7=e=>String(e),h_e=e=>{let t=new Map,n=(e,n)=>{let r=`${e}.${n}`;return t.has(r)||t.set(r,new Map),t.get(r)};return{load:async(t,r,i)=>{let a=n(t.name,r),o=[...new Map(i.filter(e=>!a.has(z7(e))).map(e=>[z7(e),e])).values()],s=t.primaryKey[0];for(let n=0;n<o.length;n+=R7){let i=o.slice(n,n+R7);for(let e of i)a.set(z7(e),[]);let c=Ya(m_e.in(r,i)),l;do{let n=await e(t.name).list(t.name,{filter:c,fields:[...new Set([s,r])],pageSize:1e3,pageToken:l});for(let e of n.items)a.get(z7(e[r]))?.push(e[s]);l=n.nextPageToken||void 0}while(l)}},keysOf:(e,t,r)=>n(e,t).get(z7(r))??[]}},g_e=500,B7=()=>{let e=new Worker(new URL(`/assets/parse-worker-BtcY0dQw.js`,``+import.meta.url),{type:`module`}),t=[],n;return e.onmessage=e=>{if(n){let t=n;n=void 0,t(e.data)}else t.push(e.data)},e.onerror=e=>{e.preventDefault();let r={type:`error`,message:`The file could not be read`};n?n(r):t.push(r)},{send:t=>e.postMessage(t),receive:()=>t.length>0?Promise.resolve(t.shift()):new Promise(e=>n=e),stop:()=>e.terminate()}},__e=e=>({sheets:async()=>{let t=B7();try{t.send({type:`sheets`,file:e});let n=await t.receive();if(n.type===`error`)throw Error(n.message);if(n.type!==`sheets`)throw Error(`The parse worker answered ${n.type} to a request for sheets`);return n.sheets}finally{t.stop()}},rows:async function*(t){let n=B7();try{for(n.send({type:`read`,file:e,sheet:t,chunk:g_e});;){let e=await n.receive();if(e.type===`error`)throw Error(e.message);if(e.type===`end`)return;if(e.type!==`rows`)throw Error(`The parse worker answered ${e.type} to a read`);yield e.rows,n.send({type:`next`})}}finally{n.stop()}}}),V7={created:0,updated:0,skipped:0,failed:0,notWritten:[]},v_e=({model:e,resources:t,views:n,sourceFor:r=__e})=>{let i=nne(),a=Wp(),s=n[e.name],c=(0,o.useMemo)(()=>Fge(e,t),[e,t]),[l,u]=(0,o.useState)({kind:`file`,reading:!1}),[d,f]=(0,o.useState)(),[p,m]=(0,o.useState)(),[h,g]=(0,o.useState)(),[_,v]=(0,o.useState)(),[y,b]=(0,o.useState)(`create`),[x,S]=(0,o.useState)([]),[C,w]=(0,o.useState)(),[T,E]=(0,o.useState)(()=>p_e()),D=(0,o.useRef)(!1),O=(0,o.useRef)(void 0),k=e=>t=>{f(t),u(e)},A=e=>{f(void 0),u({kind:`file`,reading:!0});let t=r(e);t.sheets().then(n=>{if(m({file:e,source:t,sheets:n}),g(n[0]),n.length<=1)return j(t,n[0]);u({kind:`file`,reading:!1})}).catch(k({kind:`file`,reading:!1}))},j=async(t,n)=>{u({kind:`file`,reading:!0});let r=await t_e(t,n);v(r),S(g7(r.headers,c,s));let i=f7(e)[0],a=i?g7(r.headers,[i],s)[0]:void 0;w(i&&a?{field:i.name,column:a.column}:void 0),u({kind:`map`})},M=()=>{p&&(f(void 0),j(p.source,h).catch(k({kind:`file`,reading:!1})))},N=(e,t)=>S(n=>{let r=n.filter(n=>n.column!==e&&n.field!==t);return t?[...r,{column:e,field:t}].sort((e,t)=>e.column-t.column):r}),ee=(e,t)=>S(n=>n.map(n=>n.column===e?{...n,matchBy:t}:n)),P=()=>({mode:y,columns:x,match:y===`create`?void 0:C,options:T}),te=()=>({model:e,resources:t,views:n,lookups:h_e(i)});return{step:l,error:d,file:p?.file,sheets:p?.sheets??[],sheet:h,setSheet:g,head:_,fields:c,mode:y,setMode:b,columns:x,mapColumn:N,matchColumnBy:ee,match:C,setMatch:w,options:T,setOptions:E,choose:A,openSheet:M,check:()=>{if(!p)return;f(void 0);let e=new AbortController;O.current=e,u({kind:`checking`,rows:0}),n_e(p.source,h,P(),te(),e=>u({kind:`checking`,rows:e}),e.signal).then(t=>{e.signal.aborted||u({kind:`checked`,check:t})}).catch(t=>{e.signal.aborted||k({kind:`map`})(t)})},back:()=>{O.current?.abort(),f(void 0),u({kind:`map`})},start:t=>{if(!p)return;f(void 0),D.current=!1,u({kind:`importing`,progress:V7,total:t,cancelling:!1});let n=V7;i_e(p.source,h,P(),te(),{client:i(e.name),onProgress:e=>{n=e,u({kind:`importing`,progress:e,total:t,cancelling:D.current})},cancelled:()=>D.current}).then(e=>u({kind:`done`,result:e})).catch(e=>u({kind:`done`,result:{...n,cancelled:!1},stopped:e})).finally(()=>{for(let t of[`page`,`list`,`first-page`,`map`,`facets`,`series`])a.invalidateQueries({queryKey:[t,e.name]})})},cancel:()=>{D.current=!0,u(e=>e.kind===`importing`?{...e,cancelling:!0}:e)},stop:()=>O.current?.abort()}},y_e=e=>e.step.kind===`file`?`Could not read the file`:`Could not check the rows`,b_e=e=>e.columns.length===0?!1:e.mode===`create`?_7(`create`,e.fields,e.columns).length===0:e.match!==void 0,x_e=({model:e,resources:t,views:n,canUpdate:r,onClose:i,sourceFor:a})=>{let o=v_e({model:e,resources:t,views:n,sourceFor:a}),s=n[e.name]?.names?.plural??K(e.name),{step:c}=o,l=o.head?.headers??[],u=()=>{c.kind!==`importing`&&(o.stop(),i())},d=(0,V.jsx)(U,{onClick:u,children:`Cancel`});return(0,V.jsx)(h_,{open:!0,wide:!0,title:`Import ${s.toLowerCase()}`,description:o.file&&c.kind!==`file`?o.file.name:void 0,onClose:u,actions:(()=>{switch(c.kind){case`file`:return(0,V.jsxs)(V.Fragment,{children:[d,o.sheets.length>1&&(0,V.jsx)(U,{variant:`primary`,loading:c.reading,onClick:o.openSheet,children:`Next`})]});case`map`:return(0,V.jsxs)(V.Fragment,{children:[d,(0,V.jsx)(U,{variant:`primary`,disabled:!b_e(o),onClick:o.check,children:`Check rows`})]});case`checking`:return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:o.back,children:`Back`}),(0,V.jsx)(U,{variant:`primary`,loading:!0,children:`Checking`})]});case`checked`:{let e=c.check.creates+c.check.updates;return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:o.back,children:`Back`}),(0,V.jsxs)(U,{variant:`primary`,disabled:e===0,onClick:()=>o.start(e),children:[`Import `,e.toLocaleString(`en-IE`),` `,e===1?`row`:`rows`]})]})}case`importing`:return(0,V.jsx)(U,{variant:`danger`,disabled:c.cancelling,onClick:o.cancel,children:`Cancel import`});case`done`:return(0,V.jsx)(U,{variant:`primary`,onClick:i,children:`Done`})}})(),children:(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[o.error!==void 0&&(0,V.jsx)(pS,{title:y_e(o),error:o.error}),(()=>{switch(c.kind){case`file`:return(0,V.jsx)(s_e,{file:o.file,sheets:o.sheets,sheet:o.sheet,reading:c.reading,onChoose:o.choose,onSheet:o.setSheet});case`map`:return(0,V.jsx)(u_e,{flow:o,model:e,resources:t,views:n,canUpdate:r});case`checking`:return(0,V.jsx)(a_e,{rows:c.rows});case`checked`:return(0,V.jsx)(o_e,{check:c.check,model:e,resources:t,views:n,columns:o.columns,headers:l,fileName:o.file?.name});case`importing`:return(0,V.jsx)(d_e,{progress:c.progress,total:c.total,cancelling:c.cancelling});case`done`:return(0,V.jsx)(f_e,{result:c.result,stopped:c.stopped,headers:l,fileName:o.file?.name})}})()]})})},S_e=({model:e})=>{let{resources:t,views:n}=q(),r=f_(e.name),[i,a]=(0,o.useState)(!1);return n[e.name]?.import===!1||!Fw(r,`create`)?null:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{onClick:()=>a(!0),"aria-haspopup":`dialog`,children:[(0,V.jsx)(Wn,{className:`size-3.5`}),`Import`]}),i&&(0,V.jsx)(x_e,{model:e,resources:t,views:n,canUpdate:Fw(r,`update`),onClose:()=>a(!1)})]})},C_e=()=>new DOMException(`The export was cancelled`,`AbortError`),w_e=async({client:e,resource:t,filters:n,orderBy:r,plan:i,labels:a,limit:o,port:s,sink:c,signal:l,onProgress:u})=>{let d=i.columns.map(e=>e.name),f=0;try{await c.write(await s.send({kind:`start`,plan:i}));for(let[i,p]of n.entries()){let m=``;do{let h=await e.search(t,{filter:p,orderBy:r,pageSize:500,pageToken:m,fields:d,labels:a});if(l.aborted)throw C_e();let g=h.items.slice(0,o-f);if(await c.write(await s.send({kind:`page`,records:g,labels:h.labels??{}})),f+=g.length,u(f),m=h.nextPageToken,f>=o)return await H7(s,c),{rows:f,truncated:g.length<h.items.length||m!==``||i+1<n.length}}while(m!==``)}return await H7(s,c),{rows:f,truncated:!1}}catch(e){throw await c.abort(),e}finally{s.close()}},H7=async(e,t)=>{await t.write(await e.send({kind:`finish`})),await t.close()},T_e=1048575,U7=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
69
|
-
`,W7=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,G7=`http://schemas.openxmlformats.org/package/2006/relationships`;`${U7}`,`${U7}${G7}${W7}`,`${U7}${G7}${W7}${W7}`,new TextEncoder;var E_e=uo(),K7=e=>e?.export!==!1,q7=e=>Object.values(e.fields).flatMap(e=>e.sensitive?[]:[e.name]),D_e=(e,t)=>{let n=new Set(q7(e));return JS(e,t).filter(e=>n.has(e))},J7=(e,t,n)=>Object.fromEntries(YS(e,t,[],n).map(e=>[e.id,e.header])),O_e=(e,t,n)=>{let r=J7(e,t,n);return n.flatMap(n=>{let i=e.fields[n];return i?[{name:n,header:r[n],field:i,hints:t?.fields[n]??{}}]:[]})},Y7=(e,t)=>{let n=e?.export?e.export.maxRows??1/0:1/0;return Math.min(n,t===`xlsx`?T_e:1/0)},X7=e=>e.primaryKey.length===1,k_e=(e,t)=>{let[n]=e.primaryKey;if(!n||e.primaryKey.length!==1)throw Error(`Not implemented: selected rows are exported by a single-field key`);let r=[];for(let e=0;e<t.length;e+=500)r.push(Ya(E_e.in(n,t.slice(e,e+500))));return r},A_e=()=>{let e=new Worker(new URL(`/assets/export-worker-CVd5saLq.js`,``+import.meta.url),{type:`module`,name:`protobase-export`}),t=[];return e.onmessage=e=>t.shift()?.resolve(e.data.bytes),e.onerror=e=>{e.preventDefault();let n=Error(`The export could not be built: ${e.message}`);for(let e of t.splice(0))e.reject(n)},{send:n=>new Promise((r,i)=>{t.push({resolve:r,reject:i}),e.postMessage(n)}),close:()=>e.terminate()}},j_e=[{value:`xlsx`,label:`Excel (.xlsx)`},{value:`csv`,label:`CSV`}],M_e=[{value:`shown`,label:`As shown`},{value:`raw`,label:`Raw values`}],Z7={shown:`Labels, dates and numbers as the list shows them.`,raw:`Values as they are stored, such as keys and codes.`},N_e=e=>e.kind===`counting`?`Counting rows…`:e.kind===`exact`||e.rows>1e4?lf(e.rows):`more than 10,000 rows`,Q7=e=>{if(e.kind!==`counting`)return e.kind===`exact`?e.rows:Math.max(e.rows,10001)},$7=({label:e,help:t,children:n})=>(0,V.jsxs)(`div`,{className:`flex flex-col items-start gap-1.5`,children:[(0,V.jsx)(`span`,{className:`text-[13px] font-medium`,children:e}),n,t&&(0,V.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t})]}),e9=(e,t,n)=>{let r=e.indexOf(t),i=[...e];return i.splice(r,1),i.splice(r+n,0,t),i},P_e=({fields:e,columns:t,onChange:n})=>{let r=Object.fromEntries(e.map(e=>[e.name,e.label])),i=[...t,...e.map(e=>e.name).filter(e=>!t.includes(e))];return(0,V.jsx)(`ul`,{className:`divide-y self-stretch rounded-md border`,"aria-label":`Columns`,children:i.map(e=>{let i=t.includes(e),a=t.indexOf(e);return(0,V.jsxs)(`li`,{className:`flex min-h-10 items-center gap-2 px-3 py-1`,children:[(0,V.jsxs)(`label`,{className:`flex min-w-0 flex-1 cursor-pointer items-center gap-2.5`,children:[(0,V.jsx)(zh,{checked:i,label:r[e],onChange:r=>n(r?[...t,e]:t.filter(t=>t!==e))}),(0,V.jsx)(`span`,{className:i?`truncate`:`truncate text-muted-foreground`,children:r[e]})]}),i&&(0,V.jsxs)(`span`,{className:`flex shrink-0 gap-1`,children:[(0,V.jsx)(U,{size:`sm`,variant:`ghost`,className:`min-h-8 px-2`,"aria-label":`Move ${r[e]} up`,disabled:a===0,onClick:()=>n(e9(t,e,-1)),children:(0,V.jsx)(A,{className:`size-3.5`})}),(0,V.jsx)(U,{size:`sm`,variant:`ghost`,className:`min-h-8 px-2`,"aria-label":`Move ${r[e]} down`,disabled:a===t.length-1,onClick:()=>n(e9(t,e,1)),children:(0,V.jsx)(S,{className:`size-3.5`})})]})]},e)})})},F_e=({plural:e,view:t,fields:n,initialColumns:r,count:i,selected:a,open:s,onExport:c,onClose:l})=>{let[u,d]=(0,o.useState)(`xlsx`),[f,p]=(0,o.useState)(a?`selected`:`list`),[m,h]=(0,o.useState)(r),[g,_]=(0,o.useState)(`shown`),v=Y7(t,u),y=f===`selected`?`${of(a??0)} selected ${a===1?`row`:`rows`}`:N_e(i),b=(f===`selected`?a??0:Q7(i)??0)>v,x=[{value:`list`,label:`Rows in the list`},{value:`selected`,label:`Selected (${of(a??0)})`}];return(0,V.jsx)(h_,{title:`Export ${e.toLowerCase()}`,open:s,onClose:l,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:l,children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,disabled:m.length===0,onClick:()=>c({format:u,scope:f,columns:m,mode:g}),children:`Export`})]}),children:(0,V.jsxs)(`div`,{className:`flex flex-col gap-4 text-[13px]`,children:[(0,V.jsx)($7,{label:`Format`,children:(0,V.jsx)(ed,{size:`md`,label:`Format`,value:u,options:j_e,onChange:d})}),a!==void 0&&a>0&&(0,V.jsx)($7,{label:`Rows`,help:f===`list`?`With the list’s filters, search and sort.`:void 0,children:(0,V.jsx)(ed,{size:`md`,label:`Rows`,value:f,options:x,onChange:p})}),(0,V.jsx)($7,{label:`Values`,help:Z7[g],children:(0,V.jsx)(ed,{size:`md`,label:`Values`,value:g,options:M_e,onChange:_})}),(0,V.jsx)($7,{label:`Columns`,children:(0,V.jsx)(P_e,{fields:n,columns:m,onChange:h})}),(0,V.jsxs)(`p`,{role:`status`,className:`text-muted-foreground`,children:[`Exports `,y,`.`,b&&` A file holds at most ${of(v)} rows; the rest are left out.`]})]})})},I_e=({plural:e,done:t,total:n,onCancel:r})=>{let i=n?Math.min(1,t/n):void 0;return(0,V.jsx)(h_,{title:`Exporting ${e.toLowerCase()}`,open:!0,onClose:r,actions:(0,V.jsx)(U,{onClick:r,children:`Cancel`}),children:(0,V.jsxs)(`div`,{className:`flex flex-col gap-2 text-[13px]`,children:[(0,V.jsx)(`div`,{role:`progressbar`,"aria-label":`Rows exported`,"aria-valuemin":0,"aria-valuemax":n,"aria-valuenow":t,className:`h-1.5 overflow-hidden rounded-full bg-muted`,children:(0,V.jsx)(`div`,{className:`h-full rounded-full bg-primary transition-[width]`,style:{width:`${(i??0)*100}%`}})}),(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:n?`${of(t)} of ${of(n)} rows`:`${of(t)} rows`})]})})},t9={xlsx:{mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,extension:`.xlsx`,description:`Excel workbook`},csv:{mime:`text/csv`,extension:`.csv`,description:`CSV file`}},L_e=/[\\/:*?"<>|\u0000-\u001f]/g,R_e=(e,t,n=new Date)=>{let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,`0`),String(n.getDate()).padStart(2,`0`)].join(`-`);return`${e.replace(L_e,` `).trim()} ${r}${t9[t].extension}`},z_e=8e6,B_e=(e,t)=>{let n=new Blob([],{type:t9[t].mime}),r=[],i=0,a=()=>{n=new Blob([n,...r],{type:t9[t].mime}),r=[],i=0};return{write:async e=>{e.length!==0&&(r.push(e),i+=e.length,i>=z_e&&a())},close:async()=>{a();let t=URL.createObjectURL(n),r=document.createElement(`a`);r.href=t,r.download=e,r.click(),setTimeout(()=>URL.revokeObjectURL(t),6e4)},abort:async()=>{r=[],n=new Blob([])}}},n9=()=>globalThis.showSaveFilePicker,V_e=()=>typeof n9()==`function`,H_e=async(e,t)=>{let n=n9();if(!n)throw Error(`This browser cannot save a file as it is built`);let r=t9[t],i;try{i=await n({suggestedName:e,types:[{description:r.description,accept:{[r.mime]:[r.extension]}}]})}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}let a=await i.createWritable();return{write:async e=>{e.length>0&&await a.write(e)},close:()=>a.close(),abort:()=>a.abort()}},U_e=(e,t)=>V_e()?H_e(e,t):Promise.resolve(B_e(e,t)),W_e=(e,t)=>{let n=t[e.primaryKey[0]];return typeof n==`object`&&n&&`id`in n?n.id:n},G_e=({model:e,view:t,resources:n,views:r,plural:i,filter:a,orderBy:s,createPort:c=A_e,createSink:l=U_e})=>{let u=G(),d=Lg(),[f,p]=(0,o.useState)({kind:`closed`}),m=(0,o.useRef)(void 0),h=vh({queryKey:W.exportCount(e.name,a),enabled:f.kind===`settings`,queryFn:async()=>{let t=await u.list(e.name,{filter:a||void 0,pageSize:1,count:`exact`,fields:e.primaryKey});return t.totalSize===void 0?{kind:`estimate`,rows:t.totalSizeEstimate}:{kind:`exact`,rows:t.totalSize}}}).data??{kind:`counting`},g=(t=[])=>p({kind:`settings`,selected:X7(e)?t.map(t=>W_e(e,t)):[]}),_=async(o,f)=>{let g=R_e(i,o.format),_=await l(g,o.format);if(!_)return;let v=Y7(t,o.format),y=o.scope===`selected`?f.length:Q7(h),b=y===void 0?void 0:Math.min(y,v),x=new AbortController;m.current=x,p({kind:`running`,done:0,total:b});try{let l=await w_e({client:u,resource:e.name,filters:o.scope===`selected`?k_e(e,f):[a],orderBy:s,plan:{format:o.format,mode:o.mode,name:i,columns:O_e(e,t,o.columns)},labels:o.mode===`shown`?k4(n,r,e,o.columns):{},limit:v,port:c(),sink:_,signal:x.signal,onProgress:e=>x.signal.aborted||p({kind:`running`,done:e,total:b})});d.show({state:`success`,title:`Exported ${of(l.rows)} ${i.toLowerCase()}`,description:l.truncated?`${g}: the first ${of(l.rows)} rows, as many as a file holds.`:g})}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;if(!Fs(e))throw e;d.show({state:`error`,title:`Could not export ${i.toLowerCase()}`,description:e.message})}finally{m.current=void 0,p(e=>e.kind===`running`?{kind:`closed`}:e)}},v=()=>{m.current?.abort(),p({kind:`closed`})},y=q7(e),b=J7(e,t,y);return{open:g,dialogs:f.kind===`settings`?(0,V.jsx)(F_e,{plural:i,view:t,fields:y.map(e=>({name:e,label:b[e]})),initialColumns:D_e(e,t),count:h,selected:f.selected.length>0?f.selected.length:void 0,open:!0,onExport:e=>void _(e,f.selected),onClose:()=>p({kind:`closed`})}):f.kind===`running`?(0,V.jsx)(I_e,{plural:i,done:f.done,total:f.total,onCancel:v}):null}},K_e=({state:e,onClearSearch:t,onClearFilters:n,create:r})=>(0,V.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-8 text-center text-muted-foreground`,children:[(0,V.jsx)(`p`,{children:e.message}),(e.clearSearch||e.clearFilters||e.create&&r)&&(0,V.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[e.clearSearch&&(0,V.jsx)(U,{onClick:t,children:`Clear search`}),e.clearFilters&&(0,V.jsx)(U,{onClick:n,children:`Clear filters`}),e.create&&r]})]}),q_e=({plural:e,search:t,filtered:n,scoped:r,canCreate:i})=>{let a=e.toLowerCase();return t?{message:`No ${a} match “${t}”.`,clearSearch:!0,clearFilters:n,create:!1}:n?{message:`No ${a} match these filters.`,clearSearch:!1,clearFilters:!0,create:!1}:r?{message:`No ${a} match.`,clearSearch:!1,clearFilters:!1,create:!1}:{message:`No ${a} yet.`,clearSearch:!1,clearFilters:!1,create:i}},J_e=(e,t)=>{},Y_e=({windowMs:e=1e3,comebacks:t=2,onHold:n=J_e}={})=>{let r,i=[],a;return(o,s)=>{if(a?.among.has(o))return a.value;if(a&&(a=void 0,i=[]),o===r||(r=o,i=i.filter(t=>s-t.at<=e),i.push({value:o,at:s,comeback:i.some(e=>e.value===o)}),i.filter(e=>e.comeback).length<t))return o;let c=new Set(i.slice(-2*t).map(e=>e.value));return a={value:Math.min(...c),among:c},n(a.value,[...c]),a.value}},X_e=e=>Math.max(1,Math.floor((e+12)/252)),Z_e=(e,t)=>Math.max(0,(e-(t-1)*12)/t),Q_e=(e,t,n,r)=>({start:e*n,end:Math.max(0,Math.min(r,(t+1)*n)-1)}),$_e=(e,t,n)=>{let r=e/t.rowHeight;return t.columns===n.columns?r*n.rowHeight:Math.floor(Math.floor(r)*t.columns/n.columns)*n.rowHeight},eve=8,tve=(e,t,n)=>{let r=e.get(t);if(r!==void 0&&r>=n)return e;let i=new Map(e);i.delete(t),i.set(t,n);for(let e of i.keys()){if(i.size<=eve)break;i.delete(e)}return i},nve=({source:e,label:t,initialIndex:n,onScrollIndex:r,minHeight:i,children:a})=>{let{total:s}=e,[c]=(0,o.useState)(n),[l,u]=(0,o.useState)(0),d=X_e(l),f=Z_e(l,d),[p,m]=(0,o.useState)(()=>new Map),h=Math.ceil(Math.max(i(f),p.get(f)??0)),g=h+12,_={columns:d,rowHeight:g},v=(0,o.useRef)({layout:_,top:0}),y=v.current.top>0&&(v.current.layout.columns!==d||v.current.layout.rowHeight!==g),b=e=>y?$_e(v.current.top,v.current.layout,_):e,x=f>0&&p.has(f),S=G6({total:Math.ceil(s/d),rowHeight:g,initialIndex:Math.floor(c/d),settle:b,ready:x});(0,o.useLayoutEffect)(()=>{y&&S.scrollTo(S.top),v.current={layout:_,top:S.top},y||r(Math.floor(Math.max(0,S.top)/g)*d)});let C=Q_e(S.first,S.last,d,s),w=L6({total:s,rowAt:e.rowAt,loadRows:e.loadRows,revision:e.revision,latencyMs:0},C.start,C.end),[T]=(0,o.useState)(()=>Y_e());(0,o.useLayoutEffect)(()=>{let e=S.ref.current;if(!e)return;let t=()=>u(T(e.clientWidth,performance.now())),n=new ResizeObserver(t);return n.observe(e),t(),()=>n.disconnect()},[T]);let E=(0,o.useRef)(f);E.current=f;let[D]=(0,o.useState)(()=>new ResizeObserver(e=>{let t=Math.max(...e.map(e=>e.borderBoxSize[0]?.blockSize??e.contentRect.height)),n=E.current;m(e=>tve(e,n,t))}));(0,o.useLayoutEffect)(()=>()=>D.disconnect(),[D]);let O=(0,o.useCallback)(e=>{if(e)return D.observe(e),()=>D.unobserve(e)},[D]);return(0,V.jsx)(`ul`,{ref:S.ref,className:`relative min-w-0 flex-auto`,"aria-label":t,style:{height:S.geometry.contentHeight},children:S.rows.flatMap(({index:e,offset:t})=>Array.from({length:d},(n,r)=>{let i=e*d+r;if(i>=s)return[];let o=w(i),c={top:t,left:r*(f+12),width:f,minHeight:h};return o?(0,V.jsx)(`li`,{ref:O,"aria-posinset":i+1,"aria-setsize":s,className:`absolute grid grid-cols-[minmax(0,1fr)]`,style:c,children:a(o)},o.id):(0,V.jsx)(`li`,{"aria-hidden":!0,className:`absolute grid grid-cols-[minmax(0,1fr)]`,style:c,children:(0,V.jsx)(Au,{className:`h-full rounded-lg`})},`skeleton-${i}`)}))})},rve=`grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3`,ive=e=>e*.75,ave=44,ove=({model:e,view:t,display:n,list:r,empty:i})=>{let a=t?.names?.plural??K(e.name),o=n.card===void 0&&(n.image!==void 0||n.photos!==void 0);return r.isLoading?(0,V.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden ${rve}`,children:Array.from({length:6},(e,t)=>(0,V.jsx)(Au,{className:`h-24`},t))}):r.error?(0,V.jsx)(pS,{title:`Could not load rows`,error:r.error}):!r.source||r.source.total===0?i??(0,V.jsxs)(`p`,{className:`py-8 text-center text-muted-foreground`,children:[`No `,a.toLowerCase(),` match.`]}):(0,V.jsx)(nve,{source:r.source,label:a,initialIndex:r.initialIndex,onScrollIndex:r.onScrollIndex,minHeight:e=>(o?ive(e):0)+ave,children:r=>(0,V.jsx)(c5,{model:e,view:t,display:n,row:EC(e,r)})})},r9=new Map,sve=()=>{let{entry:e,path:t,params:n}=Oh(),r=`${t}?${n.toString()}`,i=r9.get(e),a=(0,o.useCallback)(t=>void r9.set(e,{url:r,index:t}),[e,r]);return{initialIndex:i?.url===r?i.index:0,remember:a}},i9=e=>e.reduce((e,t)=>e+t.count,0),cve=e=>{let t=Math.floor(e.length/2),n=i9(e.slice(0,t)),r=i9(e.slice(e.length-t));return n===0?0:(r-n)/n*100},lve=({active:e,payload:t,noun:n})=>{let r=t?.[0]?.payload;return!e||!r?null:(0,V.jsxs)(`div`,{className:`rounded-md border bg-background px-2.5 py-1.5 text-xs shadow-pop`,children:[(0,V.jsx)(`div`,{className:`text-muted-foreground`,children:pf(r.at)}),(0,V.jsxs)(`div`,{className:`font-semibold tabular-nums`,children:[of(r.count),` `,n]})]})},a9={fontSize:11,fill:`var(--muted-foreground)`},uve=({title:e=`Orders created`,noun:t=`orders`,defaultGranularity:n=`day`,data:r,granularity:i,onGranularityChange:a,periodLabel:s,className:c})=>{let[l,u]=(0,o.useState)(n),d=i??l,f=a??u,p=r??cx(d),m=pu(`(min-width: 640px)`),h=cve(p);return(0,V.jsxs)(`section`,{className:B(`rounded-lg border bg-background px-4 pb-2 pt-3`,c),children:[(0,V.jsxs)(`header`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,V.jsx)(`h2`,{className:`font-semibold`,children:e}),(0,V.jsx)(`span`,{className:`font-semibold tabular-nums`,children:of(i9(p))}),(0,V.jsxs)(`span`,{className:B(`text-xs font-medium tabular-nums`,h>=0?`text-success-text`:`text-danger-text`),children:[h>=0?`+`:`−`,Math.abs(h).toFixed(1),`%`]}),(0,V.jsx)(`span`,{className:`hidden text-xs text-muted-foreground sm:inline`,children:s??`last ${d===`day`?`30 days`:`12 weeks`}`})]}),(0,V.jsx)(ed,{value:d,onChange:f,options:[{value:`day`,label:`Day`},{value:`week`,label:`Week`}]})]}),(0,V.jsx)(`div`,{className:`mt-2 h-24`,children:(0,V.jsx)(Aj,{width:`100%`,height:`100%`,children:(0,V.jsxs)(v4,{data:p,margin:{top:4,right:0,bottom:0,left:0},barCategoryGap:d===`day`?`22%`:`30%`,children:[(0,V.jsx)(C1,{vertical:!1,stroke:`var(--border)`}),(0,V.jsx)(h2,{dataKey:`at`,padding:{left:4,right:m?4:18},tickFormatter:mf,tick:a9,axisLine:!1,tickLine:!1,interval:d===`day`?m?4:9:m?1:3,height:18}),(0,V.jsx)(b2,{width:m?36:28,tick:a9,axisLine:!1,tickLine:!1,tickCount:3}),(0,V.jsx)(_q,{cursor:{fill:`var(--muted)`},content:(0,V.jsx)(lve,{noun:t}),isAnimationActive:!1}),(0,V.jsx)(s2,{dataKey:`count`,fill:`var(--primary)`,radius:[2,2,0,0],isAnimationActive:!1})]})})})]})},dve={"7d":`last 7 days`,"30d":`last 30 days`,"90d":`last 90 days`,"1y":`last year`,all:`all time`},fve=({resource:e,chart:t,title:n,noun:r,filter:i})=>{let[a,s]=(0,o.useState)(t.granularity===`week`?`week`:`day`),c=a===`week`?`90d`:t.range,l=cT(e,{field:t.field,range:c,granularity:a,filter:i}).data?.points.map(e=>({at:Date.parse(`${e.bucket}Z`),count:e.count}))??[];return(0,V.jsx)(uve,{title:n,noun:r,data:l,granularity:a,onGranularityChange:s,periodLabel:a===`week`?`last 12 weeks`:dve[c]})},o9=(e,t,n)=>{let r=e.sum??e.average;if(r===void 0)return n;let i=t?.fields[r]?.label??K(r);return e.sum===void 0?`Average ${i.toLowerCase()}`:`${i}`},pve=({model:e,view:t,chart:n,plural:r,filter:i})=>{let a=t?.fields[n.groupBy]?.label??K(n.groupBy);return(0,V.jsxs)(`section`,{className:`rounded-lg border bg-background px-4 pb-3 pt-3`,"aria-label":`${o9(n,t,r)} by ${a.toLowerCase()}`,children:[(0,V.jsxs)(`h2`,{className:`mb-2 font-semibold`,children:[o9(n,t,r),` by `,a.toLowerCase()]}),(0,V.jsx)(E4,{model:e,view:t,groupBy:n.groupBy,type:n.type,sum:n.sum,average:n.average,limit:n.limit,filter:i})]})},mve=({value:e,onCommit:t,placeholder:n,className:r})=>{let[i,a]=(0,o.useState)(e);return(0,o.useEffect)(()=>a(e),[e]),(0,o.useEffect)(()=>{if(i===e)return;let n=setTimeout(()=>t(i),350);return()=>clearTimeout(n)},[i,e,t]),(0,V.jsx)(Td,{wrapperClassName:B(`min-w-0 flex-1 sm:w-72 sm:flex-initial`,r),leading:(0,V.jsx)(fn,{className:`size-4`}),placeholder:n,"aria-label":`Search`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>e.key===`Enter`&&t(i)})},hve=(e,t,n,r,i)=>{let a=n?.list?.relatedColumns??[];if(a.length===0)return e;let o=new Map(e.map(e=>[e.id,e]));return JS(t,n).flatMap(e=>{let t=o.get(e);if(t)return[t];let n=a.find(t=>t.name===e),s=n&&r[n.resource];if(!n||!s)return[];let c=n.label??K(n.name);return[{id:n.name,header:c,kind:`text`,width:160,minWidth:yS(c,!1),sortable:!1,render:e=>(0,V.jsx)(n5,{column:n,records:e[n.name]??[],target:s,view:i[s.name],Card:c5})}]})},gve=({model:e,view:t,target:n,children:r})=>{let i=Y8(e.name,t.listOf,!0),a=t.names?.plural??K(e.name),o=e=>(0,V.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 px-5 py-4`,children:[(0,V.jsx)(Fd,{title:a,subtitle:t.help}),e]});if(i.error)return o((0,V.jsx)(pS,{title:`Could not load your ${a.toLowerCase()}`,error:i.error}));if(!i.data)return o((0,V.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(Au,{className:`h-24`},t))}));let s=q8(n,i.data);return s?r(s):o((0,V.jsxs)(`p`,{className:`py-8 text-center text-muted-foreground`,children:[`No `,a.toLowerCase(),` yet.`]}))},s9=({title:e,chips:t,label:n,required:r,initial:i=``,busy:a,onSave:s,onClose:c})=>{let l=(0,o.useId)(),[u,d]=(0,o.useState)(i),f=`${l}-form`;return(0,V.jsx)(h_,{open:!0,title:e,onClose:c,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:c,children:`Cancel`}),(0,V.jsx)(U,{type:`submit`,form:f,variant:`primary`,loading:a,children:`Save`})]}),children:(0,V.jsxs)(`form`,{id:f,className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),s(u.trim()===``?null:u.trim())},children:[t.length>0&&(0,V.jsx)(t8,{chips:t}),(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,V.jsx)(`label`,{htmlFor:l,className:`font-medium`,children:n}),!r&&(0,V.jsx)(`span`,{id:`${l}-hint`,className:`text-xs text-muted-foreground`,children:`Optional`})]}),(0,V.jsx)(Td,{id:l,value:u,required:r,pattern:r?`.*\\S.*`:void 0,"aria-describedby":r?void 0:`${l}-hint`,autoFocus:!0,autoComplete:`off`,onChange:e=>d(e.target.value)})]})]})})},c9=uo(),_ve={start:0,end:0},l9=(e,t)=>c9.and(t,{kind:`present`,field:e.field,span:_ve}),u9=e=>{switch(e.kind){case`and`:case`or`:return{...e,args:e.args.map(u9)};case`not`:return d9(e.arg);case`search`:case`present`:case`isNull`:return e;default:return l9(e,e)}},d9=e=>{switch(e.kind){case`and`:return c9.or(...e.args.map(d9));case`or`:return c9.and(...e.args.map(d9));case`not`:return u9(e.arg);case`search`:case`present`:case`isNull`:return c9.not(e);default:return l9(e,c9.not(e))}},f9=e=>{let t=Ca(e);if(!t.ok)throw Error(`The filter cannot be read: ${t.errors.map(e=>e.message).join(`; `)}`);return t.ast},p9=(e,t)=>{let n=f9(e);if(!n)return null;let r=f9(t),i=c9.not(u9(n));return Ya(r?c9.and(r,i):i)},vve=(e,t)=>p9(t,e),m9=e=>e.key.startsWith(`extra:`)?`extra:${e.label}`:e.key,yve=(e,t)=>{let n=new Map(e.map(e=>[m9(e),e])),r=new Map(t.map(e=>[m9(e),e])),i=e.filter(e=>!r.has(m9(e))).map(e=>({kind:`removed`,label:e.label})),a=t.flatMap(e=>{let t=n.get(m9(e));return t&&t.label!==e.label?[{kind:`changed`,label:e.label,before:t.label}]:[]}),o=t.filter(e=>!n.has(m9(e))).map(e=>({kind:`added`,label:e.label}));return[...i,...a,...o]},bve=(e,t,n,r)=>{let i=e-t;return i===0?`As many ${r}`:`${Math.abs(i)} ${i>0?`more`:`fewer`} ${Math.abs(i)===1?n:r}`},h9=12,g9={added:{word:`Added`,className:`text-success-text`},removed:{word:`Removed`,className:`text-danger-text`},changed:{word:`Changed`,className:`text-primary-text`}},xve=({changes:e})=>(0,V.jsx)(`ul`,{"aria-label":`Filter changes`,className:`divide-y rounded-md border`,children:e.map(e=>(0,V.jsxs)(`li`,{className:`grid grid-cols-[72px_1fr] gap-3 px-3 py-2`,children:[(0,V.jsx)(`span`,{className:`font-medium ${g9[e.kind].className}`,children:g9[e.kind].word}),e.kind===`changed`?(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`span`,{className:`text-muted-foreground line-through`,children:e.before}),` `,(0,V.jsx)(`span`,{className:`font-medium`,children:e.label})]}):(0,V.jsx)(`span`,{className:e.kind===`removed`?`text-muted-foreground line-through`:`font-medium`,children:e.label})]},`${e.kind}:${e.label}`))}),_9=(e,t)=>{let n=vh({...Kw(G(),e,t??``),enabled:t!==null});return t===null?0:n.data},Sve=(e,t,n)=>`${e} ${e===1?t:n}`,v9=({model:e,view:t,title:n,filter:r,total:i,plural:a})=>{let o=t?.list?.displays?.find(e=>e.kind===`cards`);return(0,V.jsxs)(`section`,{"aria-label":n,className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`h3`,{className:`font-semibold`,children:[n,` `,(0,V.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`(`,i??`…`,`)`]})]}),i!==void 0&&i>h9&&(0,V.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`The first `,h9,` of `,i,`.`]}),r===null||i===0?(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`No `,a,`.`]}):(0,V.jsx)(q5,{model:e,view:t,filter:r,sort:DC(e,t),limit:h9,display:o?.name??`table`,row:!0,link:!1,empty:`No ${a}.`})]})},Cve=({model:e,view:t,title:n,before:r,after:i,saveNewLabel:a,updating:s,creating:c,onUpdate:l,onSaveNew:u,onCancel:d})=>{let f=yve(z8(e,r),z8(e,i)),p=(0,o.useMemo)(()=>p9(r,i),[r,i]),m=(0,o.useMemo)(()=>vve(r,i),[r,i]),h=_9(e,p),g=_9(e,m),_=(t?.names?.singular??K(e.name)).toLowerCase(),v=(t?.names?.plural??K(e.name)).toLowerCase(),y=h!==void 0&&g!==void 0;return(0,V.jsx)(h_,{open:!0,wide:!0,title:n,onClose:d,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:d,children:`Cancel`}),(0,V.jsx)(U,{loading:c,disabled:s,onClick:u,children:a}),(0,V.jsx)(U,{variant:`primary`,loading:s,disabled:c,onClick:l,children:`Update`})]}),children:(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[f.length>0&&(0,V.jsx)(xve,{changes:f}),y?(0,V.jsxs)(`p`,{children:[(0,V.jsx)(`span`,{className:`font-semibold`,children:bve(h,g,_,v)}),(0,V.jsxs)(`span`,{className:`text-muted-foreground`,children:[`: `,Sve(h,_,v),` added, `,g,` removed`]})]}):(0,V.jsx)(Au,{className:`h-4 w-48`}),(0,V.jsx)(v9,{model:e,view:t,title:`Added`,filter:p,total:h,plural:v}),(0,V.jsx)(v9,{model:e,view:t,title:`Removed`,filter:m,total:g,plural:v})]})})},wve=()=>{let{address:e,set:t}=PC();return{key:e?.kind===`list`?e.savedSearch:void 0,open:e=>t({savedSearch:e})}},y9=e=>e instanceof Error?e.message:`Something went wrong`,Tve=(e,t)=>{let n=q(),r=G(),i=Lg(),a=Xw(),{href:o,open:s}=PC(),c=wve(),{resource:l}=e,u=n.resources[l],d=n.views[l]?.searchesOf,f=n.permissions[l],p=u!==void 0&&d!==void 0&&f!==void 0&&Fw(f,`create`)&&Fw(f,`delete`),m=n.signIn?.[l]?.signIn,h=g5(l,p),g=e=>Ao(jg(u,e)),_=d&&h.data?.find(e=>e[d.filter]===t),v=_||c.key===void 0||!f||!Fw(f,`update`)?void 0:h.data?.find(e=>g(e)===c.key),y=n.views[l]?.names,b=y?.plural??`saved searches`,x=d?.name===void 0?void 0:u?.fields[d.name],S=yh({mutationFn:e=>r.create(l,{[d.filter]:t,...d.name&&{[d.name]:e}}),onSuccess:e=>{c.open(g(e.record)),i.show({state:`success`,title:`Search saved`,action:{label:`Open ${b.toLowerCase()}`,href:o({kind:`list`,resource:l}),onNavigate:s}})},onError:e=>i.show({state:`error`,title:`Could not save the search`,description:y9(e)}),onSettled:()=>a(l)}),C=yh({mutationFn:e=>r.remove(l,g(e)),onError:e=>i.show({state:`error`,title:`Could not take the search off`,description:y9(e)}),onSettled:()=>a(l)}),w=yh({mutationFn:e=>r.update(l,g(e),{[d.filter]:t},e.etag??`*`),onSuccess:()=>i.show({state:`success`,title:`Search updated`}),onError:e=>i.show({state:`error`,title:`Could not update the search`,description:y9(e)}),onSettled:()=>a(l)}),T=S.isPending||C.isPending||w.isPending;return{mode:p?`save`:m?`sign-in`:void 0,prompt:m,saved:_!==void 0,opened:v&&{filter:String(v[d.filter]??``),name:d.name&&typeof v[d.name]==`string`&&v[d.name]!==``?String(v[d.name]):void 0},noun:(y?.singular??K(l)).toLowerCase(),naming:x&&{label:n.views[l]?.fields[x.name]?.label??K(x.name),required:!x.nullable},ready:h.data!==void 0&&!T,updating:w.isPending,creating:S.isPending,remove:()=>_&&C.mutate(_),saveNew:(e,t)=>S.mutate(e,t),update:e=>v&&w.mutate(v,e)}},Eve=({model:e,view:t,search:n,filter:r,chips:i,className:a})=>{let s=Tve(n,r),[c,l]=(0,o.useState)(!1),[u,d]=(0,o.useState)(!1),[f,p]=(0,o.useState)();if(!s.mode)return null;let m=n.label??`Save search`;if(s.mode===`sign-in`)return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{className:a,"aria-haspopup":`dialog`,onClick:()=>l(!0),children:[(0,V.jsx)(oe,{className:`size-3.5`,"aria-hidden":!0}),m]}),(0,V.jsx)(G8,{as:`dialog`,prompt:s.prompt,open:c,onClose:()=>l(!1)})]});let h=e=>{d(!1),s.naming?p(e):s.saveNew(null)},g=f!==void 0&&s.naming&&(0,V.jsx)(s9,{title:f,chips:i,label:s.naming.label,required:s.naming.required,busy:s.creating,onSave:e=>s.saveNew(e,{onSuccess:()=>p(void 0)}),onClose:()=>p(void 0)}),_=s.opened;if(_){let n=`Save as new ${s.noun}`;return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{className:a,"aria-haspopup":`dialog`,"aria-disabled":!s.ready,onClick:()=>s.ready&&d(!0),children:[(0,V.jsx)(ln,{className:`size-3.5`,"aria-hidden":!0}),(0,V.jsx)(`span`,{className:`max-w-60 truncate`,children:_.name?`Update ${_.name}`:`Update ${s.noun}`})]}),(0,V.jsxs)(U,{className:a,"aria-haspopup":s.naming?`dialog`:void 0,"aria-disabled":!s.ready,onClick:()=>s.ready&&h(n),children:[(0,V.jsx)(ae,{className:`size-3.5`,"aria-hidden":!0}),n]}),u&&(0,V.jsx)(Cve,{model:e,view:t,title:_.name?`Update ${_.name}?`:`Update this ${s.noun}?`,before:_.filter,after:r,saveNewLabel:n,updating:s.updating,creating:s.creating,onUpdate:()=>s.update({onSuccess:()=>d(!1)}),onSaveNew:()=>h(n),onCancel:()=>d(!1)}),g]})}let v=s.saved?ie:oe;return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{className:a,"aria-pressed":s.saved,"aria-haspopup":!s.saved&&s.naming?`dialog`:void 0,"aria-disabled":!s.ready,onClick:()=>s.ready&&(s.saved?s.remove():h(m)),children:[(0,V.jsx)(v,{className:s.saved?`size-3.5 text-primary`:`size-3.5`,"aria-hidden":!0}),m]}),g]})},Dve=e=>e instanceof Error?e.message:`Something went wrong`,Ove=({model:e,view:t,name:n,value:r,onChange:i})=>{let a=(0,o.useId)(),s=e.fields[n],c=t.fields[n],l=c?.label??K(n);if(s?.type===`boolean`)return(0,V.jsx)(mS,{checked:r===!0,onChange:i,label:l});if(s?.type!==`enum`)throw Error(`Not implemented: "${n}" is ${s?.type??`unknown`}, and a saved search's controls are enums or booleans`);return(0,V.jsxs)(`label`,{htmlFor:a,className:`flex items-center gap-2 text-muted-foreground`,children:[l,(0,V.jsx)(`select`,{id:a,value:String(r??``),onChange:e=>i(e.target.value),className:`h-8 rounded-md border border-border-strong bg-background px-2 text-foreground shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20`,children:(s.enumValues??[]).map(e=>(0,V.jsx)(`option`,{value:e,children:rs(e,c?.valueLabels)},e))})]})},kve=(e,t,n)=>Object.entries(n).map(([n,r])=>`${t.fields[n]?.label??K(n)}: ${e.fields[n]?.type===`boolean`?r===!0?`On`:`Off`:rs(String(r),t.fields[n]?.valueLabels)}`).join(`, `),Ave=({model:e,view:t,recordKey:n,title:r,row:i,fields:a})=>{let o=G(),s=Lg(),c=Xw(),l=yh({mutationFn:t=>o.update(e.name,n,t,i.etag??`*`),onSuccess:(n,i)=>s.show({state:`success`,title:`${r} saved`,description:kve(e,t,i)}),onError:e=>s.show({state:`error`,title:`Could not change the search`,description:Dve(e)}),onSettled:()=>c(e.name)});return(0,V.jsx)(`div`,{className:`flex flex-wrap items-center gap-3`,children:a.map(n=>(0,V.jsx)(Ove,{model:e,view:t,name:n,value:l.isPending&&n in(l.variables??{})?l.variables[n]:i[n],onChange:e=>l.mutate({[n]:e})},n))})},jve=e=>e instanceof Error?e.message:`Something went wrong`,Mve=({model:e,view:t,of:n,target:r,targetView:i,row:a,recordKey:s,canRename:c,onDelete:l})=>{let u=G(),d=Lg(),f=Xw(),[p,m]=(0,o.useState)(!1),{name:h,chips:g,title:_,body:v}=_5({model:e,of:n,target:r,targetView:i,row:a,recordKey:s}),y=yh({mutationFn:t=>u.update(e.name,s,{[n.name]:t},a.etag??`*`),onSuccess:()=>m(!1),onError:e=>d.show({state:`error`,title:`Could not rename the search`,description:jve(e)}),onSettled:()=>f(e.name)}),b=n.name===void 0?void 0:e.fields[n.name];return(0,V.jsxs)(`section`,{"aria-label":_,className:`flex flex-col gap-3 rounded-lg border bg-surface p-4`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,V.jsx)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:(0,V.jsx)(FC,{to:{kind:`record`,resource:e.name,key:s},className:`hover:underline`,children:h??(0,V.jsx)(n8,{chips:g})})})}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n.controls&&(0,V.jsx)(Ave,{model:e,view:t,recordKey:s,title:_,row:a,fields:n.controls}),c&&b&&(0,V.jsx)(U,{variant:`ghost`,"aria-label":`Rename ${_}`,"aria-haspopup":`dialog`,onClick:()=>m(!0),children:(0,V.jsx)(en,{className:`size-3.5`,"aria-hidden":!0})}),l&&(0,V.jsx)(U,{variant:`ghost`,"aria-label":`Delete ${_}`,onClick:()=>l(_),children:(0,V.jsx)(Rn,{className:`size-3.5`,"aria-hidden":!0})})]})]}),p&&b&&(0,V.jsx)(s9,{title:`Rename ${_}`,chips:g,label:t.fields[b.name]?.label??K(b.name),required:!b.nullable,initial:h,busy:y.isPending,onSave:e=>y.mutate(e),onClose:()=>m(!1)}),(0,V.jsx)(h5,{...v})]})},Nve=({model:e,view:t})=>{let{resources:n,views:r}=q(),i=t.searchesOf,a=n[i.resource],o=r[i.resource],s=g5(e.name,!0),c=f_(e.name),l=n7({model:e,view:t}),u=t.names?.plural??K(e.name),d=e=>(0,V.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 px-5 py-4`,children:[l.dialogs,(0,V.jsx)(Fd,{title:u,subtitle:t.help}),e]});if(!a)return d((0,V.jsxs)(d_,{title:`Not found`,children:[`There is no resource called `,i.resource,`.`]}));if(s.error)return d((0,V.jsx)(pS,{title:`Could not load your ${u.toLowerCase()}`,error:s.error}));if(!s.data)return d((0,V.jsx)(`div`,{className:`flex flex-col gap-3`,children:Array.from({length:2},(e,t)=>(0,V.jsx)(Au,{className:`h-56`},t))}));if(s.data.length===0){let e=(o?.names?.plural??K(a.name)).toLowerCase();return d((0,V.jsxs)(`p`,{className:`py-8 text-center text-muted-foreground`,children:[`No `,u.toLowerCase(),` yet. Filter the`,` `,(0,V.jsx)(FC,{to:{kind:`list`,resource:a.name},className:`font-medium text-primary-text hover:underline`,children:e}),` `,`and save the search.`]}))}return d((0,V.jsx)(`div`,{className:`flex flex-col gap-4`,children:s.data.map(n=>{let r=Ao(jg(e,n)),s=Fw(c,`delete`)?e=>void l.start({key:r,title:e,etag:n.etag,snapshot:n}):void 0;return(0,V.jsx)(Mve,{model:e,view:t,of:i,target:a,targetView:o,row:n,recordKey:r,canRename:Fw(c,`update`),onDelete:s},r)})}))},Pve=({field:e,hints:t,resource:n,stored:r,onSave:i,close:a})=>{let[s,c]=(0,o.useState)(()=>Zx(e,r)),l=(0,o.useRef)(null),u=(0,o.useRef)(!1),d=!t?.widget&&(e.type===`boolean`||e.type===`enum`);(0,o.useEffect)(()=>{l.current?.querySelector(`input, select, textarea, button, [tabindex]`)?.focus()},[]);let f=(t,n,o=s)=>{u.current||(u.current=!0,t&&Qx(e,o,r)&&i(Yx(e,o)),a(n))};return(0,V.jsx)(`div`,{ref:l,className:`w-full min-w-0`,onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),f(!0)):e.key===`Tab`?(e.preventDefault(),f(!0,e.shiftKey?-1:1)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),f(!1))},onBlur:e=>{l.current?.contains(e.relatedTarget)||f(!0)},children:(0,V.jsx)(mw,{field:e,hints:t,value:s,stored:r,resource:n,onChange:e=>{c(e),d&&f(!0,void 0,e)}})})},Fve=e=>{let t=G(),n=Wp(),r=Lg(),[i,a]=(0,o.useState)(new Map),s=(0,o.useRef)(i),c=(0,o.useRef)(new Map),l=(e,t)=>{s.current=new Map(s.current).set(e,{...s.current.get(e),...t}),a(s.current)},u=async(i,a,o)=>{let c=jg(e,i),u=String(s.current.get(i.id)?.etag??i.etag);try{let r=await t.update(e.name,c,{[a]:o},u);l(i.id,{[a]:r.record[a],etag:r.etag}),n.setQueryData(W.record(e.name,Ao(c)),r),n.invalidateQueries({queryKey:[`page`,e.name]}),n.invalidateQueries({queryKey:[`list`,e.name]}),n.invalidateQueries({queryKey:[`map`,e.name]})}catch(n){if(!Fs(n))throw l(i.id,{[a]:i[a]}),n;let o=n.status===412,s=o?await t.get(e.name,c):void 0;l(i.id,s?{[a]:s.record[a],etag:s.etag}:{[a]:i[a]});let u=n.errors.find(e=>e.field===a)?.message??n.message;r.show({state:`error`,title:o?`Changed by someone else`:`Could not save`,description:u})}};return{patches:i,save:(e,t,n)=>{l(e.id,{[t]:n});let r=(c.current.get(e.id)??Promise.resolve()).then(()=>u(e,t,n));return c.current.set(e.id,r.catch(()=>void 0)),r}}},Ive=(e,t,n)=>{let r=Fve(e),i=t?.list?.editable??[];return{editor:i.length>0&&Fw(n,`update`)?{editable:(t,n)=>i.includes(n)&&e.fields[n]!==void 0&&qx(e.fields[n])&&Iw(t,`update`),render:(n,i,a)=>(0,V.jsx)(Pve,{field:e.fields[i],hints:t?.fields[i],resource:e.name,stored:n[i],onSave:e=>void r.save(n,i,e),close:a})}:void 0,patches:r.patches}},b9=(e,t)=>{let n=e.position;if(!n||!Fw(t,`update`))return;let r=e.fields[n.field];return r&&!r.readOnly?n.field:void 0},Lve=(e,t)=>e.position?.within===void 0?b9(e,t):void 0,Rve=(e,t,n)=>t.position?.within!==void 0&&e.field===t.position.within&&!e.through&&!e.filter?b9(t,n):void 0,zve=({model:e,field:t,filter:n,fields:r})=>{let i=G(),a=Lg(),s=Xw(),{resources:c,views:l}=q(),u=`${t} asc`,d=vh({queryKey:[...W.list(e.name,n,u,500,`hand-order`),r.join(`,`)],queryFn:async()=>{let t=k4(c,l,e,r),a=await i.search(e.name,{filter:n||void 0,orderBy:u,pageSize:500,labels:t});return{rows:A4(c,e,r,a.items,a.labels).map((t,n)=>({...t,id:Ag(e,a.items[n])})),more:!!a.nextPageToken}}}),[f,p]=(0,o.useState)(),m=(0,o.useRef)(void 0),h=(0,o.useRef)(Promise.resolve()),g=(0,o.useRef)(0),_=async()=>{let n=m.current;if(!n)return;let r=Object.fromEntries(n.flatMap(t=>typeof t.etag==`string`?[[Ao(jg(e,t)),t.etag]]:[])),a=(await i.batchWrite([{op:`reorder`,resource:e.name,field:t,keys:n.map(t=>jg(e,t)),etags:r}])).results[0];if(a?.op!==`reorder`||!m.current)return;let o=new Map(a.records.map(t=>[Ag(e,t.record),t]));m.current=m.current.map(e=>{let n=o.get(e.id);return n?{...e,[t]:n.record[t],etag:n.etag}:e})},v=e=>{m.current=void 0,p(void 0),a.show({state:`error`,title:`Could not change the order`,description:aC(e)})},y=async()=>{--g.current,!(g.current>0)&&(await s(e.name),!(g.current>0)&&(m.current=void 0,p(void 0)))};return{rows:f??d.data?.rows,more:d.data?.more??!1,loading:d.isPending,error:d.error,move:(e,t)=>{let n=m.current??d.data?.rows;n&&e!==t&&(m.current=Tb(n,e,t),p(m.current),g.current+=1,h.current=h.current.then(_).catch(v).then(y))}}},x9=({model:e,view:t,field:n,filter:r,columns:i})=>{let{resources:a,views:s}=q(),{fields:c}=Zg(),{go:l,href:u}=PC(),d=(0,o.useMemo)(()=>G5(e,t,i,{resources:a,views:s,fieldTypes:c}).map(e=>({...e,sortable:!1})),[e,t,i.join(`,`),a,s,c]),f=zve({model:e,field:n,filter:r,fields:(0,o.useMemo)(()=>CC(e,t,d.map(e=>e.id)),[e,t,d])}),p=f.rows,m=(0,o.useMemo)(()=>p&&{total:p.length,rowAt:e=>p[e]},[p]),h=(t?.names?.plural??K(e.name)).toLowerCase();if(f.loading)return(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(Au,{className:`h-4 w-full`},t))});if(f.error)return(0,V.jsx)(pS,{title:`Could not load`,error:f.error});if(f.more)return(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`There are more than `,500 .toLocaleString(`en-IE`),` `,h,`, too many to sort by hand.`]});if(!m||m.total===0)return(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Nothing here yet.`});let g=t=>l({kind:`record`,resource:e.name,key:jg(e,t)});return(0,V.jsx)(J6,{fit:!0,scroll:`parent`,columns:d,source:m,latencyMs:0,onOpenRow:g,rowLink:t=>({href:u({kind:`record`,resource:e.name,key:jg(e,t)}),onFollow:()=>g(t)}),rowNumbers:!1,reorder:{label:n=>Og(e,t,n,n.id),onMove:f.move}})},S9=({sorting:e,onChange:t,size:n,iconOnly:r=!1})=>{let i=e?`Done`:`Sort`;return(0,V.jsxs)(U,{size:n,variant:e?`primary`:`secondary`,onClick:()=>t(!e),...r&&{"aria-label":i,title:i},children:[e?(0,V.jsx)(he,{className:`size-3.5`}):(0,V.jsx)(E,{className:`size-3.5`}),!r&&i]})},Bve=uo(),Vve=e=>e.find(e=>e.kind===`search`),Hve=({address:e})=>{let{resources:t,views:n,signIn:r}=q(),i=t[e.resource],a=r?.[e.resource];if(!i)return a?(0,V.jsx)(G8,{as:`page`,prompt:a.signIn}):(0,V.jsxs)(d_,{title:`Not found`,children:[`There is no resource called `,e.resource,`.`]});let o=n[e.resource];if(o?.searchesOf)return(0,V.jsx)(Nve,{model:i,view:o});let s=AC(t,n,e.resource);if(o&&s.listOf){let t=s.model;return(0,V.jsx)(gve,{model:i,view:o,target:t,children:n=>(0,V.jsx)(C9,{model:t,address:e,scope:n,heading:{title:o.names?.plural??K(i.name),subtitle:o.help}})})}return(0,V.jsx)(C9,{model:i,address:e})},C9=({model:e,address:t,scope:n,heading:r})=>{let i=q(),{set:a,go:s,href:c}=PC(),l=e.name,u=i.views[l],d=(0,o.useMemo)(()=>P8(u,e),[u,e]),{fields:f}=Zg(),p=(0,o.useMemo)(()=>hve(U5(YS(e,u),e,u,f),e,u,i.resources,i.views),[e,u,f,i.resources,i.views]),m=t.filter,h=(0,o.useMemo)(()=>M8(d,m),[d,m]),g=h.ok?h.state:a8,_=h.ok?h.extras:[],{orderBy:v,filterLayout:y}=t,b=mu(),x=hu(),[S,C]=(0,o.useState)(!1),w=n?[..._,n]:_,T=Sge({model:e,resources:i.resources,views:i.views,view:u,state:g,extras:w}),E=n?D8(d,g,w):h.ok?m:``,D=(0,o.useMemo)(()=>CC(e,u,p.map(e=>e.id)),[e,u,p]),O=(0,o.useMemo)(()=>qme(u,i.resources,i.views,D),[u,i.resources,i.views,D]),k=Q6({resources:i.resources,views:i.views,model:e,columns:D,filter:E,orderBy:v,related:O}),A=fC(e,u,t.display),j=f_(l),M=n?void 0:Lve(e,j),[N,ee]=(0,o.useState)(!1),P=N&&M!==void 0,te=P||A?.kind!==`map`;Eu(te);let F=b5(e,k.page,k.key,A?.kind===`custom`),ne=sve(),re=Dg(e,u),ie=e=>({key:e.id,title:String(typeof e[re]==`object`?e[re].name:e[re]??e.id),etag:typeof e.etag==`string`?e.etag:void 0,snapshot:e}),I=u?.names?.singular??K(l),ae=Ive(e,u,j),{state:L}=H(),oe=n7({model:e,view:u,restore:r7(e),onReview:e=>s({kind:`record`,resource:l,key:e.key})}),R=(e,t=_)=>a({filter:D8(d,e,t)}),se=Vve(_),ce=e=>{let t=_.filter(e=>e.kind!==`search`);R(g,e?[...t,Bve.search(e)]:t)},le=u?.names?.plural??K(l),ue=A&&(0,V.jsx)(H5,{model:e,view:u,display:A,orderBy:v,onChange:e=>a({orderBy:e})}),de=e.search?.length?(0,V.jsx)(mve,{value:se?.kind===`search`?se.text:``,onCommit:ce,placeholder:`Search ${le.toLowerCase()}`,className:b?void 0:`min-h-11`}):null,fe=(0,V.jsx)(b8,{layout:y,config:T,value:g,onChange:R,leading:y===`bar`?ue:void 0,trailing:de}),pe=y===`bar`?fe:(0,V.jsx)(y8,{groups:[ue?[ue]:[]],trailing:de}),me=u8(T,g),he=(0,V.jsx)(r8,{scroll:!0,chips:me,onRemove:e=>R(d8(g,e)),onClear:()=>R(a8)}),ge=A&&(0,V.jsx)(m8,{title:`Sort`,children:(0,V.jsx)(H5,{model:e,view:u,display:A,orderBy:v,onChange:e=>a({orderBy:e}),className:`min-h-11 w-full`})}),_e=(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsxs)(U,{className:`min-h-11`,onClick:()=>C(!0),"aria-haspopup":`dialog`,children:[(0,V.jsx)(Sn,{className:`size-3.5`}),`Filters`,me.length>0&&` (${me.length})`]}),de??(0,V.jsx)(`div`,{className:`min-w-0 flex-1`,children:he})]}),de&&he,(0,V.jsx)(m_,{title:`Filters`,open:S,onClose:()=>C(!1),children:(0,V.jsx)(b8,{layout:`panel`,fullWidth:!0,config:T,value:g,onChange:R,leading:ge})})]}),ve=!n&&jge(u,i.pages,j)&&(0,V.jsxs)(FC,{to:{kind:`create`,resource:l},className:Sf({variant:`primary`}),children:[(0,V.jsx)(nn,{className:`size-3.5`}),`New `,I.toLowerCase()]}),ye=u?.saveSearch&&!n&&h.ok&&m&&(0,V.jsx)(Eve,{model:e,view:u,search:u.saveSearch,filter:m,chips:R8(e,u,m,Pme(T))}),be=!n&&(0,V.jsx)(S_e,{model:e}),xe=G_e({model:e,view:u,resources:i.resources,views:i.views,plural:le,filter:E,orderBy:v}),Se=K7(u)&&(0,V.jsxs)(U,{onClick:()=>xe.open(),...!b&&{"aria-label":`Export`,title:`Export`},children:[(0,V.jsx)(He,{className:`size-3.5`}),b&&`Export`]}),Ce=M&&(0,V.jsx)(S9,{sorting:P,onChange:ee,iconOnly:!b}),we=t=>!P&&(0,V.jsx)(V5,{view:u,choices:gC(e,u,x),value:A?.name??`table`,onChange:e=>a({display:e}),menu:t}),Te=B8(e),Ee=t=>{Te(EC(e,t).record),s({kind:`record`,resource:l,key:jg(e,t)})},De=k.source?(0,V.jsx)(J6,{columns:p,source:k.source,sort:OC(v),onSortChange:e=>a({orderBy:kC(e)}),onOpenRow:Ee,rowLink:t=>({href:c({kind:`record`,resource:l,key:jg(e,t)}),onFollow:()=>Ee(t)}),cellEditor:ae.editor,rowPatches:ae.patches,initialScrollIndex:ne.initialIndex,onScrollIndex:ne.remember,rowActions:[{label:`Open ${I.toLowerCase()}`,onSelect:Ee},...Fw(j,`delete`)?[{label:`Delete`,destructive:!0,available:e=>Iw(e,`delete`),onSelect:e=>void oe.start(ie(e))}]:[]],bulkActions:[...K7(u)&&X7(e)?[{label:e=>`Export ${e}`,onRun:e=>xe.open(e)}]:[],...Fw(j,`delete`)?[{label:e=>`Delete ${e}`,destructive:!0,onRun:e=>oe.startBulk(e.map(ie))}]:[]],rowNumbers:!1,pinKey:L.kind===`signed-in`?Epe(L.user.id,l):void 0,scroll:`parent`,className:`flex-1`}):(0,V.jsx)(`div`,{className:`flex-1 rounded-lg border bg-surface`}),Oe={...k,initialIndex:ne.initialIndex,onScrollIndex:ne.remember},ke=q_e({plural:le,search:se?.kind===`search`?se.text:``,filtered:me.length>0,scoped:!!n||_.some(e=>e.kind!==`search`),canCreate:!!ve}),Ae=(0,V.jsx)(K_e,{state:ke,onClearSearch:()=>ce(``),onClearFilters:()=>R(a8),create:ve}),je=P?(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Drag a row by its handle to move it. Every move is saved as you drop it.`}),(0,V.jsx)(x9,{model:e,view:u,field:M,filter:``,columns:JS(e,u)})]}):A?A.kind===`cards`?(0,V.jsx)(ove,{model:e,view:u,display:A,list:Oe,empty:Ae},k.key.join(` `)):A.kind===`map`?(0,V.jsx)(z5,{model:e,view:u,display:A,filter:E,orderBy:v,fields:D,at:t.map,onMove:e=>a({map:e}),flush:!0}):A.kind===`board`?(0,V.jsx)(x5,{model:e,view:u,display:A,fields:D,filter:E,orderBy:v}):(0,V.jsx)(w5,{display:A,list:F}):k.source?.total===0&&!k.error?Ae:De;return(0,V.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 px-5 py-4`,children:[oe.dialogs,xe.dialogs,(0,V.jsx)(Fd,{title:r?.title??le,subtitle:r?r.subtitle:u?.help,aside:!b&&we(!0),actions:b?(0,V.jsxs)(V.Fragment,{children:[we(!1),Ce,ye,be,Se,ve]}):(0,V.jsxs)(V.Fragment,{children:[Ce,ye,be,Se,ve]})}),!h.ok&&(0,V.jsx)(pS,{title:`The filter in the address could not be read`,error:Error(h.errors.map(e=>e.message).join(`; `))}),k.error&&!A&&!P&&(0,V.jsx)(pS,{title:`Could not load rows`,error:k.error}),u?.chart&&!P&&(ko(u.chart)?(0,V.jsx)(pve,{model:e,view:u,chart:u.chart,plural:le,filter:E}):(0,V.jsx)(fve,{resource:l,chart:u.chart,title:`${le} created`,noun:le.toLowerCase(),filter:E})),!P&&(b?pe:_e),b&&y===`panel`&&!P?(0,V.jsxs)(`div`,{className:`flex min-h-0 flex-1 gap-4`,children:[(0,V.jsx)(`div`,{className:te?`sticky top-[calc(var(--pb-sticky-top,0px)+1rem)] flex max-h-[calc(100dvh-var(--pb-sticky-top,0px)-var(--pb-sticky-bottom,0px)-2rem)] shrink-0 self-start`:`flex shrink-0`,children:fe}),je]}):je]})},w9=({roles:e,selected:t,grantable:n,disabled:r,onChange:i})=>(0,V.jsx)(`div`,{className:`flex flex-wrap gap-x-4 gap-y-2`,children:e.filter(e=>e.membership).map(e=>{let a=t.includes(e.name),o=r||!n.has(e.name);return(0,V.jsxs)(`label`,{title:o&&!r?`You cannot give or take away this role`:void 0,className:B(`inline-flex items-center gap-1.5`,o&&`text-muted-foreground`),children:[(0,V.jsx)(zh,{checked:a,label:e.label,onChange:o?void 0:n=>i(n?[...t,e.name]:t.filter(t=>t!==e.name)),className:B(o&&`cursor-default opacity-60`)}),e.label]},e.name)})}),T9=e=>e?.role===`owner`?[`owner`,`admin`,`member`]:[`admin`,`member`],Uve=({member:e,current:t,onChanged:n})=>{let{session:r,organizations:i}=H(),a=t.organization.id,{busy:o,error:s,run:c}=Yh(),l=i?.roles??[],u=e.id===t.memberId,d=T9(t),f=e.role===`owner`&&t.role!==`owner`;return(0,V.jsxs)(`li`,{className:`flex flex-col gap-2 px-3 py-3`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,V.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,V.jsxs)(`span`,{className:`block truncate font-medium`,children:[e.name,u&&` (you)`]}),(0,V.jsx)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:e.email})]}),(0,V.jsx)(`select`,{"aria-label":`Organization role of ${e.name}`,value:e.role,disabled:o||f,onChange:t=>void c(async()=>{await r.organizations.setRole(a,e.id,t.target.value),n()}),className:`h-7 rounded-md border border-border-strong bg-background px-2 text-xs`,children:(f?[e.role]:d).map(e=>(0,V.jsx)(`option`,{value:e,children:Gh[e]},e))}),!u&&(0,V.jsx)(U,{size:`sm`,variant:`danger`,loading:o,disabled:f,onClick:()=>void c(async()=>{await r.organizations.removeMember(a,e.id),n()}),children:`Remove`})]}),(0,V.jsx)(w9,{roles:l,selected:e.appRoles,grantable:Jh(l,t),disabled:o,onChange:t=>void c(async()=>{await r.organizations.setAppRoles(e.id,t),n()})}),(0,V.jsx)(Tf,{message:s})]})},Wve=({current:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)(),[i,a]=(0,o.useState)(),s=e?.organization?.id,c=(0,o.useCallback)(()=>{s&&t.organizations.members(s).then(r,e=>a(e instanceof lc?Bd(e):`Could not read the members`))},[t,s]);return(0,o.useEffect)(c,[c]),e?.organization?(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(Fd,{title:`Members`,subtitle:`Who works in ${e.organization.name}, and with which roles.`}),(0,V.jsxs)(wf,{title:`Members`,description:`Owners and admins manage the organization; app roles decide what each member sees and does in the app.`,children:[(0,V.jsx)(Tf,{message:i}),n?(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:n.map(t=>(0,V.jsx)(Uve,{member:t,current:e,onChanged:c},`${t.id}/${t.role}/${t.appRoles.join()}`))}):!i&&(0,V.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(Dd,{}),` Loading`]})]})]}):null},E9=({link:e})=>e?(0,V.jsxs)(`p`,{className:`mt-3 break-all rounded-md border bg-muted px-3 py-2 text-xs`,children:[`This app cannot send email, so pass this link on yourself. It works once, until the invitation expires: `,(0,V.jsx)(`span`,{className:`font-mono`,children:e})]}):null,Gve=({current:e,onSent:t})=>{let{session:n,organizations:r}=H(),i=r?.roles??[],[a,s]=(0,o.useState)(``),[c,l]=(0,o.useState)(`member`),[u,d]=(0,o.useState)([]),[f,p]=(0,o.useState)(),{busy:m,error:h,run:g}=Yh(),_=()=>g(async()=>{let r=await n.organizations.invite(e.organization.id,{email:a.trim(),role:c,appRoles:u});p(r.link),s(``),d([]),t()});return(0,V.jsxs)(wf,{title:`Invite someone`,description:`They get an email with a link to join, or to make an account first. You can give the app roles you hold, and those your roles grant.`,children:[(0,V.jsx)(Tf,{message:h}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-3`,onSubmit:e=>{e.preventDefault(),_()},children:[(0,V.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row`,children:[(0,V.jsx)(Td,{"aria-label":`Email`,type:`email`,placeholder:`name@example.com`,value:a,onChange:e=>s(e.target.value),wrapperClassName:`flex-1`}),(0,V.jsx)(`select`,{"aria-label":`Organization role`,value:c,onChange:e=>l(e.target.value),className:`h-8 rounded-md border border-border-strong bg-background px-2`,children:T9(e).map(e=>(0,V.jsx)(`option`,{value:e,children:Gh[e]},e))}),(0,V.jsx)(U,{type:`submit`,variant:`primary`,loading:m,disabled:!a.trim(),children:`Invite`})]}),(0,V.jsx)(w9,{roles:i,selected:u,grantable:Jh(i,e),onChange:d})]}),(0,V.jsx)(E9,{link:f})]})},Kve=({invitation:e,organizationId:t,onChanged:n})=>{let{session:r,organizations:i}=H(),[a,s]=(0,o.useState)(),{busy:c,error:l,run:u}=Yh(),d=new Date(e.expiresAt).getTime()<Date.now();return(0,V.jsxs)(`li`,{className:`px-3 py-2.5`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,V.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:e.email}),(0,V.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[Gh[e.role],e.appRoles.length>0&&` · ${e.appRoles.map(e=>Kh(i?.roles??[],e)).join(`, `)}`,` · `,d?`Expired`:`Until ${new Date(e.expiresAt).toLocaleDateString()}`]})]}),(0,V.jsx)(U,{size:`sm`,loading:c,onClick:()=>void u(async()=>{s((await r.organizations.resend(t,e)).link),n()}),children:`Send again`}),(0,V.jsx)(U,{size:`sm`,variant:`danger`,loading:c,onClick:()=>void u(async()=>{await r.organizations.revoke(e.id),n()}),children:`Revoke`})]}),(0,V.jsx)(Tf,{message:l}),(0,V.jsx)(E9,{link:a})]})},qve=({current:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)([]),i=e?.organization?.id,a=(0,o.useCallback)(()=>{i&&t.organizations.invitations(i).then(e=>r(e.filter(e=>e.status===`pending`)),()=>r([]))},[t,i]);return(0,o.useEffect)(a,[a]),!e?.organization||!i?null:(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(Fd,{title:`Invitations`,subtitle:`People invited to ${e.organization.name}.`}),(0,V.jsx)(Gve,{current:e,onSent:a}),(0,V.jsx)(wf,{title:`Not accepted yet`,description:n.length>0?`Sending again gives a new link, which replaces the earlier one.`:`Nobody is waiting.`,children:n.length>0&&(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:n.map(e=>(0,V.jsx)(Kve,{invitation:e,organizationId:i,onChanged:a},e.id))})})]})},Jve=e=>{let{session:t}=H(),[n,r]=(0,o.useState)(),[i,a]=(0,o.useState)([]),[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(0),d=(0,o.useCallback)(()=>u(e=>e+1),[]);return(0,o.useEffect)(()=>{e&&Promise.all([t.organizations.current(),t.organizations.list()]).then(([e,t])=>{r(e),a(t)},e=>c(e instanceof lc?Bd(e):`Could not read your organizations`))},[e,t,l]),{current:n,organizations:i,...s&&{error:s},reload:d}},D9=e=>window.location.assign(`${e}/`),Yve=({organization:e,editable:t,onSaved:n})=>{let{session:r}=H(),[i,a]=(0,o.useState)(e.name),[s,c]=(0,o.useState)(e.slug),{busy:l,error:u,run:d}=Yh(),f=i.trim()!==e.name||s!==e.slug;return(0,V.jsxs)(wf,{title:`Details`,description:t?`The name people see, and the slug that names it in links.`:`Owners and admins can change these.`,children:[(0,V.jsx)(Tf,{message:u}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-2 sm:flex-row`,onSubmit:t=>{t.preventDefault(),d(async()=>{await r.organizations.rename(e.id,{name:i.trim(),slug:s}),n()})},children:[(0,V.jsx)(Td,{"aria-label":`Name`,value:i,disabled:!t,onChange:e=>a(e.target.value),wrapperClassName:`flex-1`}),(0,V.jsx)(Td,{"aria-label":`Slug`,value:s,disabled:!t,onChange:e=>c(e.target.value),wrapperClassName:`sm:w-48`}),t&&(0,V.jsx)(U,{type:`submit`,variant:`primary`,loading:l,disabled:!f||!i.trim(),children:`Save`})]})]})},Xve=({organization:e,memberId:t})=>{let{session:n}=H(),[r,i]=(0,o.useState)([]),[a,s]=(0,o.useState)(``),{busy:c,error:l,run:u}=Yh();return(0,o.useEffect)(()=>{n.organizations.members(e.id).then(e=>i(e.filter(e=>e.id!==t)),()=>i([]))},[n,e.id,t]),(0,V.jsxs)(wf,{title:`Hand over`,description:`Make another member the owner. You stay as an admin.`,children:[(0,V.jsx)(Tf,{message:l}),(0,V.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row`,children:[(0,V.jsxs)(`select`,{"aria-label":`New owner`,value:a,onChange:e=>s(e.target.value),className:`h-8 flex-1 rounded-md border border-border-strong bg-background px-2`,children:[(0,V.jsx)(`option`,{value:``,children:`Choose a member`}),r.map(e=>(0,V.jsxs)(`option`,{value:e.id,children:[e.name,` (`,e.email,`)`]},e.id))]}),(0,V.jsx)(U,{loading:c,disabled:!a,onClick:()=>void u(async()=>{await n.organizations.transferOwnership(a),window.location.reload()}),children:`Hand over`})]})]})},Zve=({organization:e,basePath:t})=>{let{session:n}=H(),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)(``),{busy:c,error:l,run:u}=Yh(),d=()=>u(async()=>{await n.organizations.remove(e.id),D9(t)});return(0,V.jsxs)(wf,{title:`Delete organization`,description:`Takes the organization and its members and invitations away. Its records must be deleted first.`,children:[(0,V.jsx)(Tf,{message:r?void 0:l}),(0,V.jsx)(U,{variant:`danger`,onClick:()=>i(!0),children:`Delete organization`}),r&&(0,V.jsxs)(Cf,{title:`Delete ${e.name}?`,description:`Type its name to confirm. This cannot be undone.`,onClose:()=>i(!1),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>i(!1),children:`Cancel`}),(0,V.jsx)(U,{variant:`danger`,loading:c,disabled:a!==e.name,onClick:()=>void d(),children:`Delete`})]}),children:[(0,V.jsx)(Tf,{message:l}),(0,V.jsx)(Td,{"aria-label":`Organization name`,value:a,onChange:e=>s(e.target.value)})]})]})},Qve=({organization:e,basePath:t,owner:n})=>{let{session:r}=H(),{busy:i,error:a,run:o}=Yh();return(0,V.jsxs)(wf,{title:`Leave`,description:n?`An organization keeps an owner: hand it over before you leave, unless it has another owner.`:`You stop being a member, and lose your roles here.`,children:[(0,V.jsx)(Tf,{message:a}),(0,V.jsxs)(U,{loading:i,onClick:()=>void o(async()=>{await r.organizations.leave(e.id),D9(t)}),children:[`Leave `,e.name]})]})},$ve=({current:e,basePath:t,onChanged:n})=>{let r=e?.organization;if(!r)return(0,V.jsx)(`div`,{className:`mx-auto w-full max-w-3xl px-4 py-6 md:px-6`,children:(0,V.jsx)(Fd,{title:`Organization`,subtitle:`You do not work in an organization now. Choose one under Organizations.`})});let i=e.role===`owner`;return(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(Fd,{title:r.name,subtitle:e.role?`You are ${Gh[e.role].toLowerCase()} here.`:`You work here through your global roles, without being a member.`}),(0,V.jsx)(Yve,{organization:r,editable:qh(e),onSaved:n},`${r.name}/${r.slug}`),i&&e.memberId&&(0,V.jsx)(Xve,{organization:r,memberId:e.memberId}),e.role&&(0,V.jsx)(Qve,{organization:r,basePath:t,owner:i}),i&&(0,V.jsx)(Zve,{organization:r,basePath:t})]})},O9=e=>e.normalize(`NFKD`).replace(/[̀-ͯ]/g,``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,63),k9=({organization:e,current:t,busy:n,onOpen:r})=>(0,V.jsxs)(`li`,{className:`flex items-center gap-3 px-3 py-2.5`,children:[(0,V.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:e.name}),(0,V.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:e.slug})]}),t?(0,V.jsx)(Zu,{tone:`green`,children:`Current`}):(0,V.jsx)(U,{size:`sm`,loading:n,onClick:r,children:`Open`})]}),eye=({basePath:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)(``),[i,a]=(0,o.useState)(),{busy:s,error:c,run:l}=Yh(),u=()=>l(async()=>{await t.organizations.create({name:n.trim(),slug:i??O9(n)}),D9(e)});return(0,V.jsxs)(wf,{title:`New organization`,description:`You become its owner, with every role, and work in it once it is made.`,children:[(0,V.jsx)(Tf,{message:c}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-2 sm:flex-row`,onSubmit:e=>{e.preventDefault(),u()},children:[(0,V.jsx)(Td,{"aria-label":`Name`,placeholder:`Name`,value:n,onChange:e=>r(e.target.value),wrapperClassName:`flex-1`}),(0,V.jsx)(Td,{"aria-label":`Slug`,placeholder:`slug`,value:i??O9(n),onChange:e=>a(e.target.value),wrapperClassName:`sm:w-48`}),(0,V.jsx)(U,{type:`submit`,variant:`primary`,loading:s,disabled:!n.trim(),children:`Create`})]})]})},tye=({basePath:e,currentId:t})=>{let{session:n}=H(),[r,i]=(0,o.useState)(``),[a,s]=(0,o.useState)([]),{busy:c,error:l,run:u}=Yh();return(0,o.useEffect)(()=>{let e=setTimeout(()=>void n.organizations.search(r).then(s,()=>s([])),200);return()=>clearTimeout(e)},[n,r]),(0,V.jsxs)(wf,{title:`Find an organization`,description:`Your global roles let you work in any organization, with what those roles allow there. Opening one you are not a member of is written to the audit log.`,children:[(0,V.jsx)(Tf,{message:l}),(0,V.jsx)(Td,{"aria-label":`Find an organization`,placeholder:`Name or slug`,value:r,onChange:e=>i(e.target.value),leading:(0,V.jsx)(fn,{className:`size-3.5`}),wrapperClassName:`mb-3`}),a.length>0&&(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:a.map(r=>(0,V.jsx)(k9,{organization:r,current:r.id===t,busy:c,onOpen:()=>void u(async()=>{await n.organizations.switchTo(r.id),D9(e)})},r.id))})]})},nye=()=>{let{session:e,organizations:t}=H(),[n,r]=(0,o.useState)([]);if((0,o.useEffect)(()=>{e.organizations.myInvitations().then(r,()=>r([]))},[e]),n.length===0)return null;let i=t?.roles??[];return(0,V.jsx)(wf,{title:`Invitations for you`,description:`Open the link in the invitation email to accept one.`,children:(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:n.map(e=>(0,V.jsxs)(`li`,{className:`px-3 py-2.5`,children:[(0,V.jsx)(`span`,{className:`font-medium`,children:e.organizationName??`An organization`}),`: `,e.appRoles.map(e=>Kh(i,e)).join(`, `)||`no app roles`,(0,V.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[`Until `,new Date(e.expiresAt).toLocaleDateString()]})]},e.id))})})},rye=({state:e,basePath:t})=>{let{session:n,organizations:r,state:i}=H(),{busy:a,error:o,run:s}=Yh(),c=i.kind===`signed-in`?i.user:void 0,l=r?.create===`everyone`||c!==void 0&&Sg(c),u=e.current?.organization?.id;return(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(Fd,{title:`Organizations`,subtitle:`You work in one organization at a time; what you see follows from your roles there.`}),(0,V.jsxs)(wf,{title:`Your organizations`,description:e.organizations.length>0?`The organizations you are a member of.`:`You are not a member of an organization yet.`,children:[(0,V.jsx)(Tf,{message:o??e.error}),e.organizations.length>0&&(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:e.organizations.map(e=>(0,V.jsx)(k9,{organization:e,current:e.id===u,busy:a,onOpen:()=>void s(async()=>{await n.organizations.switchTo(e.id),D9(t)})},e.id))})]}),(0,V.jsx)(nye,{}),l&&(0,V.jsx)(eye,{basePath:t}),(e.current?.globalRoles.length??0)>0&&(0,V.jsx)(tye,{basePath:t,currentId:u})]})},iye=(e,t)=>t?.active?{...e,role:t.active}:e,A9=(e,t)=>e instanceof lc?Bd(e):t,aye=(e,t=!0)=>{let{session:n}=H(),r=Lg(),[i,a]=(0,o.useState)();(0,o.useEffect)(()=>{t&&n.roles.current().then(a,e=>r.show({state:`error`,title:A9(e,`Could not read your roles`)}))},[n,r,t]);let s=(0,o.useCallback)(t=>void n.roles.switchTo(t).then(e,e=>r.show({state:`error`,title:A9(e,`Could not switch the role`)})),[n,r,e]);return{...i&&{current:i},switchTo:s}},j9=e=>new Set((e.userMenu?.items??[]).flatMap(e=>e.kind===`resource`?[e.resource]:e.kind===`page`?[e.page]:[])),oye=(e,t,n)=>(e.userMenu?.items??[]).map((r,i)=>{if(r.kind===`link`)return{id:`link-${i}`,label:r.label,icon:c_(r.icon,Je),href:r.href,external:!0};if(r.kind===`page`){let i=e.pages[r.page];return{id:r.page,label:r.label??i?.title??K(r.page),icon:c_(r.icon??i?.icon,bt),href:us({kind:`page`,page:r.page},t),active:r.page===n}}return{id:r.resource,label:r.label??e.views[r.resource]?.names?.plural??K(r.resource),icon:c_(r.icon,o_(r.resource)),href:us({kind:`list`,resource:r.resource},t),active:r.resource===n}}),sye={sales:`Sales`,crm:`CRM`,catalog:`Catalog`,inventory:`Inventory`,core:`Admin`,hr:`HR`},cye=(e,t=``,n={})=>{let r=new Map,i=new Map,a=j9(e);for(let n of Object.values(e.pages)){if(n.nav?.hidden||a.has(n.name))continue;let e=n.nav?.group??`Pages`,o=r.get(e)??{label:e,items:[]};o.items.push({id:n.name,label:n.title,icon:c_(n.icon,bt),href:us({kind:`page`,page:n.name},t)}),r.set(e,o),i.set(n.name,n.nav?.order??2**53-1)}for(let o of Object.values(e.resources)){let s=e.views[o.name];if(!s||s.nav?.hidden||a.has(o.name))continue;let c=o.table.schema??`public`,l=s.nav?.group??sye[c]??K(c),u=r.get(l)??{label:l,items:[]};u.items.push({id:o.name,label:s.names?.plural??K(o.name),icon:o_(o.name),href:us({kind:`list`,resource:o.name},t),...n[o.name]&&{recent:n[o.name]}}),r.set(l,u),i.set(o.name,s.nav?.order??2**53-1)}for(let n of Object.values(e.signIn??{})){if(n.nav?.hidden||a.has(n.resource))continue;let e=n.nav?.group??`Account`,o=r.get(e)??{label:e,items:[]};o.items.push({id:n.resource,label:n.names?.plural??K(n.resource),icon:o_(n.resource),href:us({kind:`list`,resource:n.resource},t)}),r.set(e,o),i.set(n.resource,n.nav?.order??2**53-1)}for(let n of e.sources??[]){if(n.state!==`error`)continue;let e=r.get(n.source.label)??{label:n.source.label,items:[]};for(let r of n.source.resources)e.items.push({id:r,label:K(r),icon:o_(r),href:us({kind:`list`,resource:r},t),problem:`Cannot reach ${n.source.label}`});r.set(n.source.label,e)}return[...r.values()].map(e=>({...e,items:[...e.items].sort((e,t)=>(i.get(e.id)??0)-(i.get(t.id)??0))}))},lye=e=>{let t=Zg().shell?.logo;return t?(0,V.jsx)(ng,{name:`shell.logo`,fallback:(0,V.jsx)(zu,{...e}),children:(0,V.jsx)(t,{...e})}):(0,V.jsx)(zu,{...e})},M9=(0,o.createContext)([]),uye=()=>(0,o.useContext)(M9),dye=({ui:e,children:t})=>{let{plugins:n=[]}=q(),{loads:r,settled:i}=yg(n,_g()),a=(0,o.useMemo)(()=>lg(e,r),[e,r]);return i?(0,V.jsx)(Xg.Provider,{value:a.ui,children:(0,V.jsx)(M9.Provider,{value:a.off,children:t})}):(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(Dd,{}),` Loading`]})},fye=({off:e})=>{let[t,n]=(0,o.useState)(!1);return t||e.length===0?null:(0,V.jsxs)(`div`,{role:`region`,"aria-label":`Plugins off`,className:`flex items-start gap-3 border-b border-warning/40 bg-warning-soft px-4 py-2 text-warning-text`,children:[(0,V.jsx)(an,{"aria-hidden":!0,className:`mt-0.5 size-4 shrink-0`}),(0,V.jsx)(`ul`,{className:`min-w-0 flex-1 space-y-0.5 break-words`,children:e.map(e=>(0,V.jsxs)(`li`,{children:[`The plugin `,(0,V.jsx)(`span`,{className:`font-semibold`,children:e.name??e.url}),` is off: `,e.reason,`.`]},e.url))}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Dismiss`,className:`rounded p-0.5 hover:bg-warning/10`,onClick:()=>n(!0),children:(0,V.jsx)(Qn,{"aria-hidden":!0,className:`size-4`})})]})},N9=(e,t)=>[`${t}_at`,`${t}At`].find(t=>e.fields[t]),P9=({item:e,scope:t})=>{let{components:n}=Zg(),r=n?.[e.component],i=r?(0,V.jsx)(Nw,{value:t,children:(0,V.jsx)(ng,{name:e.component,children:(0,V.jsx)(r,{...ho(e.props??{})})})}):(0,V.jsxs)(tg,{children:[`No component is registered as `,e.component,`. Export it from protobase.ui.tsx, or load the plugin that provides it.`]});return e.sidebar?e.title?(0,V.jsx)(Ex,{title:e.title,children:i}):i:e.title?(0,V.jsx)(xx,{title:e.title,children:i}):(0,V.jsx)(`section`,{className:`py-8`,children:i})},pye=(0,o.lazy)(()=>Zh(()=>import(`./record-map-DhpikXZs.js`).then(e=>({default:e.RecordMap})),__vite__mapDeps([8,1,5,2,6,3,7]))),mye=15,F9=({item:e,record:t})=>{let n=q().maps,r=n?.style,i=A5(t,e);if(!r||!i)return null;let a=(0,V.jsx)(`div`,{className:`overflow-hidden rounded-lg border border-border bg-muted ${e.sidebar?`h-48`:`h-64 md:h-80`}`,children:(0,V.jsx)(o.Suspense,{fallback:null,children:(0,V.jsx)(pye,{style:r,layers:n?.layers,position:i,zoom:e.zoom??mye},`${i.latitude},${i.longitude}`)})});return e.sidebar?(0,V.jsx)(Ex,{title:e.title,children:a}):(0,V.jsx)(xx,{title:e.title,children:a})},hye=e=>H8(e)??er,gye=({model:e,stored:t,recordKey:n,edit:r,onDelete:i})=>{let{go:a}=PC(),s={model:e,record:t.record,key:n,etag:t.etag,permissions:t.permissions},c=Qw(e.name,s,t=>t.run?.kind===`delete`&&a({kind:`list`,resource:e.name},{replace:!0})),[l,u]=(0,o.useState)(),d=c.actions.map(e=>({name:e.label,icon:hye(e.icon),blocked:c.blocked(e),running:c.running===e.name,...e.run?.kind===`delete`&&{tone:`danger`},onRun:()=>Aw(e)?u(e):void c.run(e)})),f=c.actions.some(e=>e.run?.kind===`delete`),p=[...r?[{name:`Edit`,icon:en,render:({className:e,children:t})=>(0,V.jsx)(FC,{to:r,className:e,children:t})}]:[],...d,...i&&!f?[{name:`Delete`,icon:Rn,tone:`danger`,onRun:i}]:[]];return p.length===0?null:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Cx,{actions:p}),l&&(0,V.jsx)(jw,{action:l,label:l.label,danger:l.run?.kind===`delete`,onCancel:()=>u(void 0),onConfirm:()=>{u(void 0),c.run(l)},onSubmit:async e=>{await c.submit(l,e),u(void 0)}})]})},_ye=(e,t)=>Object.values(e).find(e=>e.name!==t.name&&e.fields.position&&e.fields.quantity&&Object.values(e.fields).some(e=>e.type===`relation`&&e.relation?.resource===t.name)),vye=e=>({id:String(e.id),productId:String(e.productId??``),description:String(e.description??``),quantity:Number(e.quantity),unitPriceCents:Math.round(Number(e.unitPrice)*100)}),yye=({lines:e,draft:t,vatRate:n,saving:r,locked:i=!1})=>{let a=Fw(f_(e.name),`update`);return(0,V.jsx)(xx,{title:`Lines`,help:`What the document bills for. Drag the handle, or use the menu, to change the order; Save applies it.`,children:(0,V.jsx)(`div`,{className:`-mx-4 overflow-x-auto px-4 [-webkit-overflow-scrolling:touch] md:mx-0 md:px-0`,children:(0,V.jsx)(`div`,{className:`min-w-[560px]`,children:(0,V.jsx)(yx,{lines:t.shown.map(vye),onChange:()=>void 0,onReorder:e=>t.setOrder(e.map(e=>e.id)),vatRate:n,readOnly:!0,reorderable:a&&!r&&!i})})})})},bye=(e,t,n)=>`protobase:draft:${e}:${t}:${n}`,xye=(e,t,n)=>ad(()=>{let r=e.getItem(t);if(r===null)return;let i=JSON.parse(r);if(i&&i.etag===n&&typeof i.fields==`object`&&i.fields!==null)return{etag:n,fields:i.fields,...Array.isArray(i.order)&&{order:i.order.map(String)}}},void 0),Sye=(e,t,n)=>ad(()=>n?e.setItem(t,JSON.stringify(n)):e.removeItem(t),void 0),Cye=(e,t)=>Number(e.position)-Number(t.position),wye=(e,t,n)=>{let r=e&&Object.values(e.fields).find(e=>e.type===`relation`&&e.relation?.resource===t.name),i=IC(e?.name??``,{enabled:!!(e&&r),filter:r?`${r.name} = "${n}"`:void 0,pageSize:200,...e?.fields.position?.sortable&&{orderBy:`position asc`}});return{items:[...i.items].sort(Cye),loading:i.isPending&&!!e}},Tye=(e,t)=>{let[n,r]=(0,o.useState)(),i=t.map(e=>String(e.id)),a=(0,o.useMemo)(()=>{if(!n)return t;let e=n.flatMap(e=>t.filter(t=>String(t.id)===e)),r=t.filter(e=>!n.includes(String(e.id)));return[...e,...r]},[n,t]),s=a.map(e=>String(e.id)),c=n!==void 0&&s.some((e,t)=>e!==i[t]),l=(0,o.useCallback)(()=>!e||!c?[]:[{op:`reorder`,resource:e.name,field:`position`,keys:a.map(t=>jg(e,t)),etags:Object.fromEntries(a.flatMap(t=>typeof t.etag==`string`?[[Ao(jg(e,t)),t.etag]]:[]))}],[e,c,a]);return{shown:a,dirty:c,order:c?s:void 0,setOrder:e=>r(e),reset:()=>r(void 0),op:l}},Eye=e=>{let t=e>=5?5:e===4?3:e;return{shown:t,more:e-t}},Dye=(e,t)=>Math.abs(e)<40||Math.abs(e)<=Math.abs(t)?0:e<0?1:-1,Oye=e=>e===`ArrowRight`?1:e===`ArrowLeft`?-1:0,kye=(e,t,n)=>Math.min(Math.max(e+t,0),Math.max(n-1,0)),Aye=e=>e.key===`i`&&!e.ctrlKey&&!e.metaKey&&!e.altKey,I9=`protobase:lightbox-details`,jye=e=>ad(()=>e.getItem(I9)===`true`,!1),Mye=(e,t)=>ad(()=>t?e.setItem(I9,`true`):e.removeItem(I9),void 0),L9=`flex size-10 shrink-0 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40`,Nye=({title:e,photos:t,index:n,onIndex:r,onClose:i,details:a,detailsTitle:s=`Details`})=>{let c=(0,o.useRef)(null),l=(0,o.useRef)(void 0),u=(0,o.useId)(),d=mu(),[f,p]=(0,o.useState)(()=>jye(localStorage)),[m,h]=(0,o.useState)(!1);Cu(c,!0,i),(0,o.useEffect)(()=>h(!0),[]);let g=t.length,_=e=>{let t=kye(n,e,g);t!==n&&r(t)},v=Vx(t[n],{width:1600,height:1200}),y=a?.(n),b=y!==void 0,x=e=>{p(e),Mye(localStorage,e)};return(0,V.jsxs)(`div`,{ref:c,tabIndex:-1,role:`dialog`,"aria-modal":`true`,"aria-label":e,onKeyDown:e=>{if(b&&Aye(e))return e.preventDefault(),x(!f);let t=Oye(e.key);t!==0&&(e.preventDefault(),_(t))},className:`fixed inset-0 z-[90] flex flex-col overflow-y-auto overscroll-contain bg-backdrop outline-none md:flex-row`,children:[(0,V.jsxs)(`div`,{className:`flex h-dvh shrink-0 flex-col md:sticky md:top-0 md:min-w-0 md:flex-1`,children:[(0,V.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 p-3`,children:[(0,V.jsx)(`span`,{className:`rounded-full bg-background/85 px-3 py-1 font-medium tabular-nums text-foreground`,"aria-live":`polite`,children:`${n+1} / ${g}`}),(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[b&&(0,V.jsx)(`button`,{type:`button`,className:B(L9,`aria-expanded:bg-foreground aria-expanded:text-background`),"aria-label":s,"aria-expanded":f,"aria-controls":d?u:void 0,"aria-keyshortcuts":`i`,onClick:()=>x(!f),children:(0,V.jsx)(mt,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsx)(`button`,{type:`button`,className:L9,"aria-label":`Close`,onClick:i,children:(0,V.jsx)(Qn,{className:`size-4`,"aria-hidden":!0})})]})]}),(0,V.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 touch-pan-y items-center justify-center px-3 pb-3 md:px-16`,onPointerDown:e=>{e.pointerType===`touch`&&(l.current={x:e.clientX,y:e.clientY})},onPointerUp:e=>{l.current&&=(_(Dye(e.clientX-l.current.x,e.clientY-l.current.y)),void 0)},onPointerCancel:()=>l.current=void 0,children:[v&&(0,V.jsx)($C,{image:v,className:`max-h-full max-w-full select-none object-contain`},v.url),g>1&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{type:`button`,className:B(L9,`absolute left-3 top-1/2 -translate-y-1/2 aria-disabled:cursor-default aria-disabled:opacity-40`),"aria-label":`Previous photo`,"aria-disabled":n===0,onClick:()=>_(-1),children:(0,V.jsx)(ye,{className:`size-5`,"aria-hidden":!0})}),(0,V.jsx)(`button`,{type:`button`,className:B(L9,`absolute right-3 top-1/2 -translate-y-1/2 aria-disabled:cursor-default aria-disabled:opacity-40`),"aria-label":`Next photo`,"aria-disabled":n===g-1,onClick:()=>_(1),children:(0,V.jsx)(xe,{className:`size-5`,"aria-hidden":!0})})]})]})]}),b&&f&&d&&(0,V.jsxs)(`aside`,{id:u,"aria-label":s,className:`min-h-dvh w-[360px] shrink-0 border-l border-border bg-background p-5 text-foreground`,children:[(0,V.jsx)(`h2`,{className:`mb-3 text-[16px] font-semibold`,children:s}),y]}),(0,V.jsx)(m_,{title:s,open:b&&f&&!d&&m,onClose:()=>x(!1),children:(0,V.jsx)(`div`,{className:`pt-3`,children:y})})]})},Pye=(e,t,n)=>{let r=(t?.layout??[]).flatMap(e=>e.kind===`section`&&nS(e.when,!1)?e.fields:[]);return(r.length>0?[...new Set(r)]:Object.keys(e.fields).filter(t=>t!==e.tenant&&!e.primaryKey.includes(t))).filter(r=>e.fields[r]&&!e.fields[r].sensitive&&!n.includes(r)&&nS(t?.fields[r]?.when,!1))},Fye=({model:e,view:t,photoKey:n,fields:r})=>{let i=wg(e.name,n),a=(t?.names?.singular??K(e.name)).toLowerCase();if(i.isPending)return(0,V.jsx)(Au,{className:`h-4 w-48`});if(i.error)return(0,V.jsx)(pS,{title:`Could not load the ${a}`,error:i.error});let o=r.filter(e=>Lw(i.data.permissions,e)!==`hidden`);return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(kx,{rows:o.map(n=>({label:t?.fields[n]?.label??K(n),value:(0,V.jsx)(N4,{model:e,field:e.fields[n],value:i.data.record[n]})}))}),(0,V.jsx)(FC,{to:{kind:`record`,resource:e.name,key:n},className:`mt-3 inline-block font-medium text-primary-text hover:underline`,children:`Open ${a}`})]})},R9=e=>Vx(e,{width:0,height:0})!==void 0,Iye=(e,t)=>{let n=e.primaryKey.map(e=>t[e]);if(!n.some(e=>e==null))return Ao(n)},Lye=(e,t,n,r)=>{let i=n===void 0?[]:t.flatMap(e=>{let t=e[n];if(!jx(t)||!R9(t))return[];let i=r&&Iye(r,e);return[{file:t,...i!==void 0&&{key:i}}]});if(!jx(e)||!R9(e))return i;let a=t=>jx(t.file)&&t.file.uri===e.uri,o=i.find(a)?.key;return[{file:e,...o!==void 0&&{key:o}},...i.filter(e=>!a(e))]},Rye=uo(),zye=(e,t,n)=>{let r=G(),{resources:i}=q(),a=e.photos?i[e.photos.resource]:void 0,o=e.photos?Ya(Rye.eq(e.photos.field,n)):``,s=e.photos?.sort??``,c=vh({queryKey:W.list(a?.name??``,o,s,500,`gallery`),enabled:a!==void 0,queryFn:async()=>(await r.list(a.name,{filter:o,...s&&{orderBy:s},pageSize:500})).items});return{holder:a,items:Lye(e.image===void 0?void 0:t[e.image],c.data??[],e.photos?.image,a),isPending:a!==void 0&&c.isPending,error:c.error}},Bye={1:[`md:col-span-4 md:row-span-2`],2:[`md:col-span-2 md:row-span-2`,`md:col-span-2 md:row-span-2`],3:[`md:col-span-2 md:row-span-2`,`md:col-span-2`,`md:col-span-2`],5:[`md:col-span-2 md:row-span-2`,``,``,``,``]},Vye=({photo:e,large:t})=>{let n=Vx(e,t?{width:960,height:720}:{width:480,height:360});return n?(0,V.jsx)($C,{image:n,loading:`lazy`,className:`size-full object-cover transition-transform duration-300 group-hover/tile:scale-[1.02]`}):null},Hye=({item:e,record:t,recordKey:n})=>{let{views:r}=q(),i=zye(e,t,n),a=f_(i.holder?.name??``),[s,c]=(0,o.useState)();if(i.isPending)return(0,V.jsx)(xx,{title:e.title,children:(0,V.jsx)(Au,{className:`aspect-[4/3] w-full rounded-lg md:aspect-[2/1]`})});if(i.error)return(0,V.jsx)(xx,{title:e.title,children:(0,V.jsx)(pS,{title:`Could not load the photos`,error:i.error})});let l=i.items.length;if(l===0)return null;let{shown:u,more:d}=Eye(l),f=i.holder,p=f&&r[f.name],m=f?Pye(f,p,[e.photos?.image,e.photos?.field].filter(e=>e!==void 0)):[],h=f!==void 0&&a.read!==!1&&m.length>0;return(0,V.jsxs)(xx,{title:e.title,children:[(0,V.jsx)(`div`,{className:`grid aspect-[4/3] grid-cols-4 grid-rows-2 gap-1.5 overflow-hidden rounded-lg md:aspect-[2/1]`,children:i.items.slice(0,u).map((e,t)=>{let n=t===u-1&&d>0;return(0,V.jsxs)(`button`,{type:`button`,"aria-label":n?`Show all ${l} photos`:`Show photo ${t+1} of ${l}`,onClick:()=>c(t),className:B(`group/tile relative overflow-hidden bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary`,t===0?`col-span-4 row-span-2`:`max-md:hidden`,Bye[u][t]),children:[(0,V.jsx)(Vye,{photo:e.file,large:t===0}),n&&(0,V.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-backdrop/55 text-lg font-semibold text-white`,"aria-hidden":!0,children:`+${d}`}),t===0&&l>1&&(0,V.jsxs)(`span`,{className:`absolute bottom-2 right-2 flex items-center gap-1.5 rounded-full bg-background/85 px-2.5 py-1 text-xs font-medium tabular-nums text-foreground md:hidden`,"aria-hidden":!0,children:[(0,V.jsx)(ft,{className:`size-3.5`}),l]})]},t)})}),s!==void 0&&(0,V.jsx)(Nye,{title:e.title,photos:i.items.map(e=>e.file),index:s,onIndex:c,onClose:()=>c(void 0),details:e=>{let t=i.items[e]?.key;return h&&t!==void 0?(0,V.jsx)(Fye,{model:f,view:p,photoKey:t,fields:m},t):void 0},detailsTitle:f&&`${p?.names?.singular??K(f.name)} details`})]})},Uye={create:`created this`,update:`changed`,delete:`deleted this`,undelete:`restored this`},Wye=e=>e.actor?e.actor.name??e.actor.id:e.databaseRole?`Database (${e.databaseRole})`:`Database`,Gye=(e,t,n)=>{let r=(e.operation===`create`?[]:e.changed).flatMap(r=>{let i=t.fields[r];if(!i||r===t.softDelete)return[];let a=n?.fields[r],o=a?.label??K(r);return i.sensitive||!e.before||!e.after?[{name:r,label:o}]:[{name:r,label:o,before:ZS(i,e.before[r],a),after:ZS(i,e.after[r],a)}]}),i=e.operation===`update`&&r.length===0?`changed this`:Uye[e.operation];return{who:Wye(e),verb:i,fields:r}},Kye=1500,qye=(e,t,n,r)=>{let i=G(),a=bh({queryKey:W.history(e,t,n),initialPageParam:``,queryFn:({pageParam:r})=>i.history(e,t,{pageSize:n,pageToken:r}),getNextPageParam:e=>e.nextPageToken||void 0}),{refetch:s}=a;return(0,o.useEffect)(()=>{let e=setTimeout(()=>void s(),Kye);return()=>clearTimeout(e)},[r,s]),{...a,items:a.data?.pages.flatMap(e=>e.items)??[]}},Jye=()=>(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(Au,{className:`h-4 w-full`},t))}),Yye=({change:e,model:t,view:n})=>{let{who:r,verb:i,fields:a}=Gye(e,t,n),o=Date.parse(e.at);return(0,V.jsxs)(`li`,{className:`flex flex-col gap-1.5 py-3 first:pt-0 last:pb-0`,children:[(0,V.jsxs)(`p`,{children:[(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:r}),` `,(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:i}),` `,(0,V.jsxs)(`time`,{dateTime:e.at,title:hf(o),className:`text-muted-foreground`,children:[`· `,yf(Math.max(0,Math.round((Date.now()-o)/1e3)))]})]}),a.length>0&&(0,V.jsx)(`dl`,{className:`grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-4 gap-y-1`,children:a.map(e=>(0,V.jsxs)(`div`,{className:`contents`,children:[(0,V.jsx)(`dt`,{className:`text-muted-foreground`,children:e.label}),(0,V.jsx)(`dd`,{className:`min-w-0 break-words`,children:e.before===void 0?(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`changed`}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`del`,{className:`text-muted-foreground`,children:e.before}),` → `,(0,V.jsx)(`ins`,{className:`no-underline`,children:e.after})]})})]},e.name))})]})},Xye=({item:e,model:t,view:n,recordKey:r,etag:i})=>{let a=qye(t.name,r,e.limit??10,i);return(0,V.jsx)(xx,{title:e.title,children:a.isPending?(0,V.jsx)(Jye,{}):a.error?(0,V.jsx)(pS,{title:`Could not load the history`,error:a.error}):a.items.length===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`No changes kept yet.`}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`ol`,{className:`divide-y divide-border`,children:a.items.map(e=>(0,V.jsx)(Yye,{change:e,model:t,view:n},e.id))}),a.hasNextPage&&(0,V.jsx)(U,{size:`sm`,className:`mt-4`,disabled:a.isFetchingNextPage,onClick:()=>void a.fetchNextPage(),children:`Show more`})]})})},z9=(e,t)=>{let n=G(),r=Wp(),i=Ao(t);return yh({mutationFn:({patch:r,etag:i})=>n.update(e,t,r,i),onSuccess:t=>{r.setQueryData(W.record(e,i),t),r.invalidateQueries({queryKey:[`page`,e]}),r.invalidateQueries({queryKey:[`list`,e]}),r.invalidateQueries({queryKey:[`map`,e]})}})},B9=e=>e instanceof Ps,Zye=e=>{let t=typeof e.resource==`string`?e.resource:e.resource.toModel().name;return e.op===`reorder`?`reorder ${t} by ${e.field}`:`${e.op} ${t}`},Qye=(e,t)=>{let n=e.operation,r=n===void 0?void 0:t[n];return r?`Operation ${n+1} (${Zye(r)}) failed: ${e.message} Nothing was saved.`:`${e.message} Nothing was saved.`},$ye=(e,t)=>new e.constructor({...e.problem,detail:Qye(e,t)}),V9=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),ebe=({model:e,stored:t,recordKey:n,mode:r,subject:i,draftKey:a,lines:s})=>{let c=G(),l=Wp(),u=z9(e.name,n),d=$5(r,i),[f]=(0,o.useState)(()=>a?xye(localStorage,a,t.etag):void 0),[p,m]=(0,o.useState)(f?.fields??{}),[h,g]=(0,o.useState)(!!f),[_,v]=(0,o.useState)(!1),[y,b]=(0,o.useState)({}),[x,S]=(0,o.useState)({}),[C,w]=(0,o.useState)(0),T=Object.entries(p).filter(([n,r])=>Qx(e.fields[n],r,t.record[n])),E=T.length>0,D=E||!!s?.dirty;(0,o.useEffect)(()=>{f?.order&&s?.setOrder(f.order)},[]),(0,o.useEffect)(()=>{if(!a)return;let n=Object.fromEntries(Object.entries(p).filter(([t])=>!e.fields[t]?.sensitive)),r=Object.keys(n).length>0||!!s?.dirty;Sye(localStorage,a,r?{etag:t.etag,fields:n,...s?.order&&{order:s.order}}:void 0)},[a,e,p,s?.dirty,s?.order,t.etag]);let O=n=>n in p?p[n]:[`boolean`,`file`].includes(e.fields[n].type)?t.record[n]:Gx(t.record[n]),k=(n,r)=>{S(e=>V9(e,n));let i=typeof r==`string`?r!==Gx(t.record[n]):Qx(e.fields[n],r,t.record[n]);m(e=>i?{...e,[n]:r}:V9(e,n))},A=async()=>{let r=await c.get(e.name,n);l.setQueryData(W.record(e.name,n),r);let i={},a={};for(let[n,o]of Object.entries(p)){let s=e.fields[n];Qx(s,o,r.record[n])&&(a[n]=o,Gx(r.record[n])!==Gx(t.record[n])&&(i[n]=s.type===`file`?ZS(s,r.record[n]):Gx(r.record[n])))}m(a),b(i)},j=()=>Object.fromEntries(T.map(([t,n])=>[t,Yx(e.fields[t],n)])),M=e=>{let t=H4(e);S(t),Object.keys(t).length>0&&w(e=>e+1)},N=async()=>{try{await u.mutateAsync({patch:j(),etag:t.etag})}catch(e){throw B9(e)?await A():Fs(e)&&M(e),e}},ee=async r=>{let i=[...E?[{op:`update`,resource:e.name,key:n,data:j(),etag:t.etag}]:[],...r];try{await c.batchWrite(i)}catch(e){throw B9(e)?(await A(),await l.invalidateQueries({queryKey:[`list`]}),v(!0)):Fs(e)&&M(e),Fs(e)?$ye(e,i):e}await Promise.all([l.invalidateQueries({queryKey:W.record(e.name,n)}),l.invalidateQueries({queryKey:[`list`]}),l.invalidateQueries({queryKey:[`page`]}),l.invalidateQueries({queryKey:[`map`]})]),s?.reset()};return{value:O,change:k,save:()=>d.run(async()=>{let e=s?.op()??[];e.length>0?await ee(e):await N(),m({}),b({}),S({}),v(!1),g(!1)}),dirty:D,discard:()=>{m({}),b({}),S({}),v(!1),g(!1),s?.reset()},restored:h&&D,dismissRestored:()=>g(!1),linesConflict:_,saving:d.phase===`saving`,phase:d.phase,message:d.message,conflicts:y,errors:x,rejections:C,keepMine:e=>b(t=>V9(t,e)),useTheirs:e=>{b(t=>V9(t,e)),m(t=>V9(t,e))}}},H9=(e,t,n,r,i,a)=>{let o=G(),s=Wp(),c=Object.values(e.fields).filter(t=>t.type===`relation`&&t.relation&&t.name!==e.tenant&&i[t.name]!=null&&n[t.relation.resource]?.primaryKey.length===1),l=gh({queries:c.map(e=>{let t=n[e.relation.resource],a=String(i[e.name]);return{queryKey:W.relatedLabel(t.name,a),queryFn:async()=>(await D4(s,o,t,[a],r[t.name])).get(a)??a}})}),u=c.map(e=>({kind:`record`,resource:e.relation.resource,key:String(i[e.name])}));return{addresses:Object.fromEntries(c.map((e,t)=>[e.name,u[t]])),labels:Object.fromEntries(c.map((e,t)=>[e.name,l[t]?.data])),records:c.map((e,n)=>({kind:t?.fields[e.name]?.label??K(e.name),label:l[n]?.data??String(i[e.name]),href:us(u[n],a)}))}},U9=uo(),W9=500,G9=(...e)=>{let t=e.filter(e=>!!e);return t.length===1?t[0]:t.map(e=>`(${e})`).join(` AND `)},tbe=(e,t)=>{let n=G(),{resources:r}=q(),i=e.through,a=i?r[i.resource]:void 0,o=i?.key??a?.primaryKey[0],s=i?G9(Ya(U9.eq(i.field,t)),i.filter):``,c=vh({queryKey:W.list(a?.name??``,s,``,W9,`related:${o}`),enabled:!!(a&&o),queryFn:async()=>{let e=await n.search(a.name,{filter:s,fields:[o],pageSize:W9});return[...new Set(e.items.flatMap(e=>e[o]===null||e[o]===void 0?[]:[String(e[o])]))]}});return i?c.data?{filter:c.data.length===0?null:G9(Ya(U9.in(e.field,c.data)),e.filter),isPending:!1,error:null}:{filter:void 0,isPending:c.isPending,error:c.error}:{filter:G9(Ya(U9.eq(e.field,t)),e.filter),isPending:!1,error:null}},nbe=()=>(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(Au,{className:`h-4 w-full`},t))}),rbe=({text:e})=>(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:e??`Nothing here yet.`}),ibe=({item:e,recordKey:t,owner:n})=>{let{resources:r,views:i}=q(),a=r[e.resource],s=a&&i[a.name],c=tbe(e,t),[l,u]=J5(s,`related:${n}:${e.title}`,e.display),d=f_(e.resource),[f,p]=(0,o.useState)(!1);if(!a)return null;let m=e.columns??JS(a,s).filter(t=>t!==e.field),h=Rve(e,a,d),g=(0,V.jsx)(K5,{view:s,value:l,onChange:u}),_=h?(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[!f&&g,(0,V.jsx)(S9,{size:`sm`,sorting:f,onChange:p})]}):g;return f&&h?(0,V.jsx)(xx,{title:e.title,help:e.help,actions:_,children:(0,V.jsx)(x9,{model:a,view:s,field:h,filter:Ya(U9.eq(e.field,t)),columns:m})}):(0,V.jsx)(xx,{title:e.title,help:e.help,actions:_,children:c.isPending?(0,V.jsx)(nbe,{}):c.error?(0,V.jsx)(pS,{title:`Could not load`,error:c.error}):c.filter===null||c.filter===void 0?(0,V.jsx)(rbe,{text:e.empty}):(0,V.jsx)(q5,{model:a,view:s,filter:c.filter,sort:e.sort??``,columns:m,limit:e.limit??10,display:l,empty:e.empty},c.filter)})},abe=(e,t)=>t===e.tenant||e.primaryKey.includes(t),obe=(e,t,n)=>{if(t&&t.layout.length>0)return t.layout;let r=Object.values(e.fields).filter(t=>!abe(e,t.name)),i=r.filter(e=>!e.readOnly);return[{kind:`section`,title:`Details`,fields:(i.length>0&&!n?i:r).map(e=>e.name)},...e.history?[{kind:`history`,title:`History`}]:[]]},sbe=({resource:e,recordKey:t})=>{let{resources:n}=q(),r=n[e],i=Tg(e,t);return r?i.isPending?(0,V.jsx)(d_,{title:`Loading`,children:`Fetching the record.`}):i.error?(0,V.jsx)(`div`,{className:`p-8`,children:Fs(i.error)&&i.error.status===404?(0,V.jsx)(d_,{title:`Not found`,children:`This record does not exist, or you cannot see it.`}):(0,V.jsx)(pS,{title:`Could not load the record`,error:i.error})}):(0,V.jsx)(cbe,{model:r,recordKey:t,stored:i.data,preview:i.isPlaceholderData},i.isPlaceholderData?`preview`:`loaded`):(0,V.jsxs)(d_,{title:`Not found`,children:[`There is no resource called `,e,`.`]})},cbe=({model:e,recordKey:t,stored:n,preview:r})=>{let i=q(),{basePath:a}=Oh(),{address:s,go:c,open:l}=PC(),u=i.views[e.name],d=Og(e,u,n.record,t),{state:f}=H(),p=(0,o.useMemo)(()=>_ye(i.resources,e),[i.resources,e]),m=Tye(p,wye(p,e,t).items),h=ebe({model:e,stored:n,recordKey:t,mode:u?.saveFeedback??`toast`,subject:d,draftKey:!r&&f.kind===`signed-in`?bye(f.user.id,e.name,t):void 0,lines:m}),g=Wp(),_=G(),v=U4(h.rejections),y=f_(e.name),b=r7(e),x=Fw(y,`update`)&&n.permissions?.update!==!1,{shown:S,offersEdit:C,editing:w}=$x(u?.recordMode,x,s?.kind===`record`&&s.edit===!0);sne(h.dirty&&S===`form`),ene(h.dirty);let T={kind:`record`,resource:e.name,key:t},E={...T,edit:!0},D=S===`form`&&u?.recordMode!==void 0&&u.recordMode!==`edit`,O=Fw(y,`delete`)&&n.permissions?.delete!==!1,k=n7({model:e,view:u,restore:b,onDeleted:()=>c({kind:`list`,resource:e.name},{replace:!0}),onReview:()=>void g.invalidateQueries({queryKey:W.record(e.name,t)})}),A=H9(e,u,i.resources,i.views,n.record,a),j=t=>{let n=e.fields[t],r=n?.relation?i.resources[n.relation.resource]:void 0;if(r&&r.primaryKey.length===1&&t!==e.tenant&&!e.primaryKey.includes(t))return r},M=Object.values(e.fields).filter(e=>j(e.name)),N={...n.record,...Object.fromEntries(M.map(e=>[e.name,Xx(e,h.value(e.name))]))},ee=H9(e,u,i.resources,i.views,N,a),P=(e,t)=>{let n=j(e);if(!n||!rS(t))return h.change(e,t);g.setQueryData(W.relatedLabel(n.name,t.key),t.label),h.change(e,oS(n,t.key))},{fields:te}=Zg(),F=obe(e,u,S===`read`).filter(e=>nS(e.when,w)),ne=F.flatMap(e=>e.kind===`sidebar`?e.fields:[]),re=e.fields.status?.type===`enum`,ie=n.record.status,I=re&&!ne.includes(`status`)&&ie!=null&&ie!==``?String(ie):void 0,ae=N9(e,`updated`),L=e=>u?.fields[e],oe=e=>Lw(n.permissions,e)!==`hidden`&&nS(L(e)?.when,w),R=e=>!r||Object.hasOwn(n.record,e),se=r=>{let a=e.fields[r],o=Lw(n.permissions,r);if(!a||o===`hidden`)return null;let s=h.conflicts[r],c=j(r),l=L(r)?.label??K(r),d=h.errors[r];return(0,V.jsx)(bx,{name:r,label:l,required:S===`form`&&o!==`read`&&Jx(a),help:tS(L(r),u,w),error:d&&V4(a,l,d),wide:!!(L(r)?.multiline||L(r)?.markdown),conflict:s===void 0?void 0:{user:{name:`Someone else`,initials:`?`,hue:40},ago:`just now`,theirValue:s||`—`,onKeepMine:()=>h.keepMine(r),onUseTheirs:()=>h.useTheirs(r)},children:R(r)?(0,V.jsx)(mw,{field:a,hints:L(r),value:h.value(r),stored:n.record[r],relationLabel:ee.labels[r],relationTo:ee.addresses[r],relationPicker:c&&{target:c,view:i.views[c.name]},locked:S!==`form`||o===`read`,invalid:!!h.errors[r],reveal:a.sensitive?()=>_.reveal(e.name,t,r):void 0,resource:e.name,onChange:e=>P(r,e)}):(0,V.jsx)(Au,{className:`h-9`})},a.sensitive?`${r}:${n.etag}`:r)},ce=r=>{let i=e.fields[r],a=R(r)?i.sensitive?(0,V.jsx)(mw,{field:i,hints:L(r),value:``,stored:n.record[r],locked:!0,reveal:()=>_.reveal(e.name,t,r),resource:e.name,onChange:e=>h.change(r,e)}):(0,V.jsx)(N4,{model:e,field:i,value:n.record[r],relationLabel:A.labels[r]}):(0,V.jsx)(Au,{className:`h-4 w-32`});return{label:L(r)?.label??K(r),help:tS(L(r),u,w),wide:!!(L(r)?.multiline||L(r)?.markdown),value:a}},le=F.findIndex(e=>e.kind===`sidebar`),ue=(0,V.jsx)(Dx,{title:`Summary`,rows:ne.flatMap(t=>{let r=e.fields[t];if(!r||!oe(t))return[];if(!R(t))return[{label:L(t)?.label??K(t),value:(0,V.jsx)(Au,{className:`h-4 w-24`})}];let i=ZS(r,n.record[t],L(t)),a=n.record[t],o=BS(r,L(t))&&typeof a==`string`&&a!==``,s=r.type===`enum`?(0,V.jsx)(M4,{value:a,hints:L(t),children:i}):o?(0,V.jsx)(cw,{source:a}):(0,V.jsx)(`strong`,{className:L(t)?.multiline?`whitespace-pre-line break-words`:void 0,children:i}),c=rw(te,r,L(t));return[{label:L(t)?.label??K(t),value:c?(0,V.jsx)(ow,{shown:c,part:`display`,field:r,value:n.record[t],fallback:s}):s}]})}),de={model:e,record:n.record,key:t,etag:n.etag,permissions:n.permissions},fe=async()=>{await h.save()&&D&&c(T,{replace:!0})},pe=O?()=>void k.start({key:t,title:d,etag:n.etag,snapshot:n.record}):void 0,me=S===`form`&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{variant:`primary`,className:`max-md:min-h-11 max-md:flex-1 md:w-full`,loading:h.saving,disabled:!h.dirty&&h.phase!==`saved`,onClick:()=>void fe(),children:[h.phase===`saved`&&(0,V.jsx)(he,{className:`size-4`}),h.phase===`saved`?`Saved`:`Save`]}),D&&(0,V.jsx)(FC,{to:T,className:B(Sf(),`max-md:min-h-11 md:w-full`),onClick:e=>ju(e)&&h.discard(),children:`Cancel`}),h.dirty&&(0,V.jsx)(`span`,{className:`text-xs text-muted-foreground max-md:order-first`,children:`Unsaved changes`})]});return(0,V.jsxs)(`div`,{ref:v,className:`flex flex-1 flex-col`,inert:r,children:[k.dialogs,(0,V.jsx)(`div`,{className:`flex-1`,children:(0,V.jsxs)(`div`,{className:`mx-auto max-w-[1100px] px-4 pb-8 pt-6 md:px-10 md:py-8`,children:[(0,V.jsx)(Ox,{title:d,titleHidden:!0,status:I?{label:rs(I,L(`status`)?.valueLabels),tone:HS(I)}:void 0}),h.message&&(0,V.jsx)(`div`,{className:`mt-4`,children:(0,V.jsx)(pS,{title:`Not saved`,error:Error(h.message)})}),h.linesConflict&&(0,V.jsx)(`div`,{className:`mt-4`,children:(0,V.jsx)(pS,{title:`The lines were changed by someone else`,error:Error(`The lines were reloaded. Your new order is kept: Save again to apply it.`)})}),S!==`form`&&C&&h.dirty&&(0,V.jsxs)(`div`,{className:`mt-4 flex items-center justify-between gap-3 rounded-lg border bg-surface px-3 py-2`,role:`status`,children:[(0,V.jsx)(`span`,{children:`You have unsaved changes to this record.`}),(0,V.jsxs)(`span`,{className:`flex gap-2`,children:[(0,V.jsx)(FC,{to:E,className:Sf({size:`sm`}),children:`Continue editing`}),(0,V.jsx)(U,{size:`sm`,onClick:h.discard,children:`Discard`})]})]}),S===`form`&&h.restored&&(0,V.jsxs)(`div`,{className:`mt-4 flex items-center justify-between gap-3 rounded-lg border bg-surface px-3 py-2`,role:`status`,children:[(0,V.jsx)(`span`,{children:`Your unsaved changes were restored.`}),(0,V.jsxs)(`span`,{className:`flex gap-2`,children:[(0,V.jsx)(U,{size:`sm`,onClick:h.dismissRestored,children:`Keep`}),(0,V.jsx)(U,{size:`sm`,onClick:h.discard,children:`Discard`})]})]}),(0,V.jsxs)(`div`,{className:`grid grid-cols-1 gap-8 md:grid-cols-[minmax(0,1fr)_300px] md:gap-12`,children:[(0,V.jsxs)(`main`,{className:B(`divide-y divide-border`,!I&&`*:first:pt-0!`),children:[F.flatMap((i,a)=>{if(i.kind===`related`)return[(0,V.jsx)(ibe,{item:i,recordKey:t,owner:e.name},`related:${i.title}`)];if(r&&(i.kind===`custom`||i.kind===`map`||i.kind===`gallery`))return[];if(i.kind===`custom`)return i.sidebar?[]:[(0,V.jsx)(P9,{item:i,scope:de},`custom:${a}`)];if(i.kind===`map`)return i.sidebar?[]:[(0,V.jsx)(F9,{item:i,record:n.record},`map:${a}`)];if(i.kind===`gallery`)return[(0,V.jsx)(Hye,{item:i,record:n.record,recordKey:t},`gallery:${a}`)];if(i.kind===`history`)return[(0,V.jsx)(Xye,{item:i,model:e,view:u,recordKey:t,etag:n.etag},`history:${a}`)];if(i.kind!==`section`)return[];let o=i.fields.filter(t=>e.fields[t]&&oe(t)),s=S===`read`&&i.presentation===`facts`,c=s?tC(n.record,o):o;return c.length===0?[]:[(0,V.jsx)(xx,{title:i.title,help:eS(i.helpWhen,u,w)?i.help:void 0,children:s?(0,V.jsx)(Ax,{facts:c.map(e=>({label:ce(e).label,value:ce(e).value,icon:H8(L(e)?.icon)}))}):S===`read`?(0,V.jsx)(kx,{rows:c.map(ce)}):(0,V.jsx)(`div`,{className:`grid grid-cols-1 gap-x-6 gap-y-5 sm:grid-cols-2`,children:c.map(se)})},i.title)]}),p&&!r&&(0,V.jsx)(yye,{lines:p,draft:m,vatRate:Number(n.record.vatRate??21)/100,saving:h.saving,locked:S!==`form`})]}),(0,V.jsxs)(`aside`,{className:B(`space-y-4`,I&&`md:pt-8`),children:[me&&(0,V.jsx)(`div`,{className:`hidden flex-col items-center gap-2 md:flex`,children:me}),!r&&(0,V.jsx)(gye,{model:e,stored:n,recordKey:t,edit:C?E:void 0,onDelete:pe}),le===-1&&ue,F.map((e,t)=>e.kind===`custom`&&e.sidebar&&!r?(0,V.jsx)(P9,{item:e,scope:de},`custom:${t}`):e.kind===`map`&&e.sidebar&&!r?(0,V.jsx)(F9,{item:e,record:n.record},`map:${t}`):t===le?(0,V.jsx)(o.Fragment,{children:ue},`summary`):null),(0,V.jsx)(Dx,{title:`Details`,rows:[N9(e,`created`),ae].flatMap(t=>{let r=t?e.fields[t]:void 0;return!t||!r||!oe(t)?[]:[{label:L(t)?.label??K(t),value:R(t)?ZS(r,n.record[t],L(t)):(0,V.jsx)(Au,{className:`h-4 w-24`})}]})}),A.records.length>0&&(0,V.jsx)(Ex,{title:`Related records`,children:(0,V.jsx)(Tx,{records:A.records,onNavigate:l})})]})]})]})}),me&&(0,V.jsx)(`div`,{className:`sticky bottom-[var(--pb-sticky-bottom,0px)] z-20 flex shrink-0 items-center gap-2 border-t bg-background p-3 md:hidden`,children:me})]})},lbe=e=>Fs(e)?e.status===401||e.status===403?`It did not accept your sign-in: ${e.message}`:e.message:`It did not answer.`,ube=({status:e})=>{let t=Wp();return e.state===`error`?(0,V.jsx)(`div`,{className:`flex h-full min-h-48 flex-1 items-center justify-center p-8`,children:(0,V.jsxs)(`div`,{className:`max-w-md text-center`,children:[(0,V.jsxs)(`h1`,{className:`text-[16px] font-semibold`,children:[`Cannot reach `,e.source.label]}),(0,V.jsxs)(`p`,{className:`mt-1 text-muted-foreground`,children:[lbe(e.error),` The rest of the app works as before.`]}),(0,V.jsx)(U,{className:`mt-3`,onClick:()=>void t.refetchQueries({queryKey:W.sourceMetas(e.source.url)}),children:`Try again`})]})}):(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 flex-1 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(Dd,{}),` Loading from `,e.source.label]})},dbe=uo(),fbe=e=>Object.values(e.resources).flatMap(t=>{let n=e.views[t.name];return!t.search?.length||!n||n.nav?.hidden||e.permissions[t.name]?.read===!1?[]:[{model:t,view:n,label:n.names?.plural??K(t.name)}]}),pbe=e=>{let t=e.map(e=>e.label.toLowerCase());return t.length===0?`Search`:t.length===1?`Search ${t[0]}`:t.length===2?`Search ${t[0]} and ${t[1]}`:`Search ${t[0]}, ${t[1]} and more`},mbe=e=>Ya(dbe.search(e.trim())),K9=e=>{let t=e.view?.searchResult?.title;return t?.length?t:[Dg(e.model,e.view)]},q9=e=>{let t=K9(e);return e.view?.searchResult?.subtitle??e.model.search?.find(e=>!t.includes(e))},hbe=e=>{let t=q9(e),n=[...K9(e),...t?[t]:[],...e.model.search??[]];return[...new Set([...e.model.primaryKey,...n.filter(t=>Object.hasOwn(e.model.fields,t))])]},J9=(e,t,n)=>{let r=t[n];return r==null?``:e.model.fields[n]?.type===`enum`?rs(String(r),e.view?.fields[n]?.valueLabels):String(r)},gbe=(e,t,n,r=``)=>{let i=Ao(jg(e.model,t)),a=K9(e),o=q9(e),s=Ga(e.model,t,n,[...a,...o?[o]:[]])??o,c=s?J9(e,t,s):``;return{id:i,title:a.map(n=>J9(e,t,n)).filter(Boolean).join(` `)||i,...c&&{subtitle:c},href:us({kind:`record`,resource:e.model.name,key:i},r)}},_be=()=>{let e=q(),t=G(),{basePath:n}=Oh(),r=(0,o.useMemo)(()=>fbe(e),[e]),[i,a]=(0,o.useState)(``),s=i.trim(),c=h8(s,200),l=s.length>=2,u=l&&c.length>=2,d=gh({queries:r.map(e=>({queryKey:[`global-search`,e.model.name,c],enabled:u,staleTime:1/0,gcTime:0,queryFn:()=>t.list(e.model.name,{filter:mbe(c),pageSize:5,fields:hbe(e)})}))}),f=r.flatMap((e,t)=>{let r=d[t];if(!u||!r)return[];if(r.error)return[{id:e.model.name,label:e.label,hits:[],failed:!0}];let i=(r.data?.items??[]).map(t=>gbe(e,t,c,n));return i.length>0?[{id:e.model.name,label:e.label,hits:i}]:[]});return{available:r.length>0,placeholder:pbe(r),text:i,setText:a,query:u?c:``,loading:l&&(s!==c||d.some(e=>e.isFetching)),groups:f}},vbe=e=>!!(e?.updateAvailable&&e.indicator),ybe=e=>e?5e3:18e5,Y9={immediate:`Updates as soon as a release is out`,weekly:`Updates at a set time every week`,scheduled:`Updates at the time set for this release`,manual:`Updates only when asked to`},bbe={job:`Preparing the update`,build:`Building`},xbe=(e,t)=>{if(!e.updateStage)return`Updating now`;let n=bbe[e.updateStage];return e.updateStartedAt?`${n}, started ${gf(Math.max(0,Math.floor((t-Date.parse(e.updateStartedAt))/1e3)))}`:n},X9=(e,t=Date.now())=>e.updating?xbe(e,t):e.nextUpdateAt?`${Y9[e.policy]}: next on ${hf(Date.parse(e.nextUpdateAt))} UTC`:Y9[e.policy],Sbe=e=>{let t=`${hf(Date.parse(e.finishedAt))} UTC`,n={succeeded:`Updated to ${e.toVersion} on ${t}`,unchanged:`The update to ${e.toVersion} on ${t} changed nothing`,failed:`The update to ${e.toVersion} failed on ${t}`}[e.outcome];return e.message?`${n}: ${e.message}`:`${n}.`},Cbe=e=>Fs(e)&&e.status<500&&e.problem.detail?e.problem.detail:Fs(e)&&e.status===409?`Already on the latest version, or an update is running.`:Fs(e)&&e.status===403?`Only an admin can update the runtime.`:`The update could not be started. Try again later.`,Z9=({label:e,value:t})=>(0,V.jsxs)(`div`,{className:`flex justify-between gap-4 py-1`,children:[(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:e}),(0,V.jsx)(`span`,{className:`font-medium tabular-nums`,children:t})]}),wbe=({status:e,requesting:t,error:n,checkError:r,onUpdate:i,onClose:a})=>{let o=e.updating?void 0:e.lastUpdate;return(0,V.jsxs)(Cf,{title:`Runtime update`,description:e.updating?(0,V.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,V.jsx)(Dd,{className:`size-3.5`}),X9(e)]}):X9(e),onClose:a,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:a,children:`Close`}),(0,V.jsx)(U,{variant:`primary`,loading:t,disabled:e.updating||!e.updateAvailable,onClick:i,children:e.updating?`Updating…`:`Update now`})]}),children:[(0,V.jsx)(Z9,{label:`Current version`,value:e.version}),(0,V.jsx)(Z9,{label:`Latest version`,value:e.latest}),o&&(0,V.jsx)(`p`,{className:o.outcome===`failed`?`mt-3 text-danger-text`:`mt-3 text-muted-foreground`,children:Sbe(o)}),n!==void 0&&(0,V.jsx)(`p`,{role:`alert`,className:`mt-3 text-danger-text`,children:Cbe(n)}),r!==void 0&&(0,V.jsx)(`p`,{className:`mt-3 text-muted-foreground`,children:`The status could not be checked again; this is the last one read.`})]})},Tbe=e=>{let t=Cg(),n=(0,o.useRef)(t);n.current=t;let r=t!==void 0;return(0,o.useMemo)(()=>r?fu({url:e,token:()=>n.current}):void 0,[e,r])},Ebe=e=>{let[t,n]=(0,o.useState)(),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)(),[c,l]=(0,o.useState)(),u=t?.updating??!1;return(0,o.useEffect)(()=>{if(!e)return;let t=!0,r=()=>e.status().then(e=>{t&&(n(e),l(void 0))},e=>t&&l(e));r();let i=setInterval(()=>void r(),ybe(u));return()=>{t=!1,clearInterval(i)}},[e,u]),{status:t,update:(0,o.useCallback)(async()=>{e&&(i(!0),s(void 0),await e.update().then(n,s),i(!1))},[e]),requesting:r,error:a,checkError:c}},Q9=({client:e})=>{let{status:t,update:n,requesting:r,error:i,checkError:a}=Ebe(e),[s,c]=(0,o.useState)(!1);return!t||!s&&!vbe(t)?null:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{size:`sm`,variant:`ghost`,"aria-label":`Update available`,title:`Update available`,onClick:()=>c(!0),className:`max-md:size-9 max-md:p-0`,children:[(0,V.jsx)(Te,{className:`size-3.5 text-primary`}),(0,V.jsx)(`span`,{className:`max-md:sr-only`,children:`Update`})]}),s&&(0,V.jsx)(wbe,{status:t,requesting:r,error:i,checkError:a,onUpdate:()=>void n(),onClose:()=>c(!1)})]})},Dbe=({url:e})=>(0,V.jsx)(Q9,{client:Tbe(e)}),Obe=({url:e,client:t})=>t?(0,V.jsx)(Q9,{client:t}):(0,V.jsx)(Dbe,{url:e}),kbe=({signIn:e,onStop:t})=>{let[n,r]=(0,o.useState)(!1),[i,a]=(0,o.useState)(),s=async()=>{r(!0),a(void 0);try{await t()}catch(e){if(!(e instanceof lc))throw e;a(Bd(e)),r(!1)}};return(0,V.jsxs)(`div`,{role:`region`,"aria-label":`Staff session`,className:`flex flex-wrap items-center gap-x-3 gap-y-2 border-b border-warning/40 bg-warning-soft px-4 py-2 text-warning-text`,children:[(0,V.jsx)(cee,{"aria-hidden":!0,className:`size-4 shrink-0`}),(0,V.jsxs)(`p`,{className:`min-w-64 flex-1 break-words`,children:[(0,V.jsx)(`span`,{className:`font-semibold`,children:e.staffName??e.staff}),` is signed in as `,(0,V.jsx)(`span`,{className:`font-semibold`,children:e.user}),` until`,` `,hf(Date.parse(e.expiresAt)),`. Reason: `,e.reason]}),i&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:i}),(0,V.jsx)(U,{size:`sm`,loading:n,onClick:()=>void s(),children:`Stop staff session`})]})},Abe=(e,t,n)=>({filter:n.filter??``,orderBy:n.orderBy??DC(e,t),pageSize:n.limit??3,fields:[...new Set([...e.primaryKey,Dg(e,t),n.status])]}),jbe=(e,t,n,r,i,a)=>r.map(r=>{let o=Ao(jg(e,r)),s=String(r[n.status]??``);return{id:o,label:Og(e,t,r,o),href:us({kind:`record`,resource:e.name,key:o},i),status:e.fields[n.status]?.type===`enum`&&s?rs(s,t.fields[n.status]?.valueLabels):s,tone:n.tones[s]??`neutral`,pulse:n.pulse?.includes(s)??!1,active:o===a}}),Mbe=(e,t,n,r,i)=>{let a=n.find(t=>Ao(jg(e,t))===r);return a!==void 0&&t.some(e=>!Object.is(a[e],i[e]))},$9=({model:e,request:t})=>W.navRecent(e.name,t.filter,t.orderBy,t.pageSize),Nbe=e=>{let t=Wp();(0,o.useEffect)(()=>t.getQueryCache().subscribe(n=>{if(n.type!==`updated`||n.action.type!==`success`)return;let[r,i,a]=n.query.queryKey,o=n.action.data?.record;if(r===`record`&&typeof a==`string`&&o)for(let n of e){if(n.model.name!==i)continue;let e=t.getQueryData($9(n));e&&Mbe(n.model,n.request.fields,e.items,a,o)&&t.invalidateQueries({queryKey:$9(n),exact:!0})}}),[t,e])},Pbe=(e,t,n)=>{let r=G(),i=(0,o.useMemo)(()=>{let t=j9(e);return Object.values(e.views).flatMap(n=>{let r=e.resources[n.resource],i=n.nav?.recent;return r&&i&&!n.nav?.hidden&&!t.has(r.name)?[{model:r,view:n,recent:i,request:Abe(r,n,i)}]:[]})},[e]);Nbe(i);let a=gh({queries:i.map(e=>({queryKey:$9(e),queryFn:()=>r.list(e.model.name,e.request)}))});return Object.fromEntries(i.map(({model:e,view:r,recent:i},o)=>{let s=a[o];if(s.isPending)return[e.name,{state:`loading`}];if(s.isError)return[e.name,{state:`error`}];let c=n.resource===e.name?n.key:void 0;return[e.name,{state:`ready`,records:jbe(e,r,i,s.data.items,t,c)}]}))},Fbe=e=>e?.kind===`page`?e.page:e?.resource,Ibe=e=>e?.kind===`record`?e:void 0,Lbe=({workspace:e,sidebarMode:t,assistant:n,runtime:r})=>{let i=q(),{state:a,session:s,signOut:c,stopStaffSession:l,organizations:u}=H(),d=Bh();if(a.kind!==`signed-in`&&a.kind!==`visitor`)throw Error(`The shell is only rendered for a signed-in user or a visitor`);let f=a.kind===`signed-in`?a.user:void 0,p=a.kind===`signed-in`?a.staff:void 0,{path:m,params:h,basePath:g}=Oh(),{address:_,go:v,open:y}=PC(),b=Fbe(_),x=Ibe(_),S=_be(),C=Are(),w=cye(i,g,Pbe(i,g,{resource:b,key:x?.key})),T=Object.keys(i.pages)[0],E=Object.keys(i.resources)[0],D=_?.kind===`page`?i.pages[_.page]:void 0;(0,o.useEffect)(()=>{m===`/`&&(T?v({kind:`page`,page:T},{replace:!0}):E&&v({kind:`list`,resource:E},{replace:!0}))},[m,T,E,v]);let O=_?.kind===`page`?void 0:_?.resource,k=O?die(i,O):void 0,A=O?i.views[O]:void 0,j=w.find(e=>e.items.some(e=>e.id===b)),M=O?i.resources[O]:void 0,N=Tg(x?.resource??``,x?.key??``,!!(M&&x)),ee=M&&x&&N.data?Og(M,A,N.data.record,x.key):void 0,P=!!x&&(N.isLoading||k?.state===`loading`),{shell:te}=Zg(),F=te?.actions,ne=te?.rightPanel,[re,ie]=(0,o.useState)(!1),I=i.assistant?.url,ae=I&&(0,V.jsx)(Zre,{open:re,onToggle:()=>ie(!re)}),L=I&&re&&(0,V.jsx)($re,{url:I,client:n,page:h.size>0?`${m}?${h}`:m,onClose:()=>ie(!1)}),oe=i.errorReporting;(0,o.useEffect)(()=>{oe&&Xne(oe)},[oe]);let R=i.runtime?.url,se=R&&(0,V.jsx)(Obe,{url:R,client:r}),ce=aye((0,o.useCallback)(()=>D9(g),[g]),!!f),le=f&&iye(f,ce.current),ue=le?Sg(le):!1,de=uye(),fe=Jve(!!(u&&f)),pe=fe.current,me=!!u&&pe!==void 0&&!pe.organization,he=u&&f?Une[m]:void 0,ge=f?m===`/-/account`?`Sign-in & security`:m===`/-/sign-in-policy`?`Sign-in policy`:he:void 0,_e=A?.names?.plural??(O&&K(O)),ve=ge?[ge]:nie({basePath:g,address:_,group:j?.label,page:D,resourceLabel:_e,recordTitle:ee,recordLoading:P});aie(iie(rie({address:_,page:D,accountPage:ge,resourceLabel:_e,singular:A?.names?.singular??(O&&K(O)),recordTitle:ee,recordLoading:P}),i.appName));let ye=f&&m===`/-/account`?(0,V.jsx)(Ap,{email:f.email}):f&&m===`/-/sign-in-policy`?ue?(0,V.jsx)(Hp,{}):(0,V.jsx)(d_,{title:`Admins only`,children:`Only an admin can change how people sign in.`}):he&&m===`/-/organization`?(0,V.jsx)($ve,{current:pe,basePath:g,onChanged:fe.reload}):he&&(m===`/-/organization/members`||m===`/-/organization/invitations`)?qh(pe)?m===`/-/organization/members`?(0,V.jsx)(Wve,{current:pe}):(0,V.jsx)(qve,{current:pe}):(0,V.jsx)(d_,{title:`Owners and admins only`,children:`Only the organization's owners and admins manage its members.`}):he&&m===`/-/organizations`||me?(0,V.jsx)(rye,{state:fe,basePath:g}):_?_.kind===`page`?D?(0,V.jsx)(Q5,{name:D.name},D.name):(0,V.jsxs)(d_,{title:`Not found`,children:[`There is no page called `,_.page,`.`]}):k&&k.state!==`ready`?(0,V.jsx)(ube,{status:k}):_.kind===`create`?(0,V.jsx)(gge,{resource:_.resource,values:_.values},_.resource):_.kind===`record`?(0,V.jsx)(sbe,{resource:_.resource,recordKey:_.key},`${_.resource}/${_.key}`):(0,V.jsx)(Hve,{address:_},_.resource):m===`/`?(0,V.jsx)(d_,{title:`Choose a resource`,children:`Pick one from the sidebar.`}):(0,V.jsx)(d_,{title:`Not found`,children:`There is nothing at this address.`}),be=(0,V.jsx)(Pd,{pageScroll:!0,sidebarMode:t??`text-small`,activeItem:b??``,breadcrumb:ve,user:le&&yre(le),onSignOut:f&&(()=>void c()),signIn:f?void 0:d.link(),workspace:pe?.organization?.name??e,logo:lye,navGroups:w,bottomBar:tie(i,g,b),userMenu:[...oye(i,g,b),...u&&f?Wne(g,m,pe):[],...f?ir(g,m,ue):[]],organizations:u&&{...pe?.organization&&{current:{id:pe.organization.id,name:pe.organization.name}},others:fe.organizations.filter(e=>e.id!==pe?.organization?.id),onSwitch:e=>void s.organizations.switchTo(e).then(()=>D9(g))},theme:{preference:C.preference,onChange:C.choose},roles:ce.current?.active?{active:ce.current.active,roles:ce.current.roles,onSwitch:ce.switchTo}:void 0,onNavigate:y,search:S.available?{placeholder:S.placeholder,text:S.text,onTextChange:S.setText,query:S.query,loading:S.loading,groups:S.groups,onSelect:y}:void 0,actions:(F||se||ae)&&(0,V.jsxs)(V.Fragment,{children:[F&&(0,V.jsx)(ng,{name:`shell.actions`,fallback:null,children:(0,V.jsx)(F,{})}),se,ae]}),rightPanel:(ne||L)&&(0,V.jsxs)(V.Fragment,{children:[ne&&(0,V.jsx)(ng,{name:`shell.rightPanel`,fallback:null,children:(0,V.jsx)(ne,{})}),L]}),children:ye}),xe=ue&&de.length>0;return!p&&!xe?be:(0,V.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[p&&(0,V.jsx)(kbe,{signIn:p,onStop:l}),xe&&(0,V.jsx)(fye,{off:de}),(0,V.jsx)(`div`,{className:`min-h-0 flex-1`,children:be})]})},Rbe=({baseUrl:e,client:t,sources:n,workspace:r,sidebarMode:i,ui:a,assistant:o,runtime:s})=>{let{state:c,session:l,markSignedOut:u}=H();return(0,V.jsx)(Eh,{baseUrl:e,client:t,sources:n,token:c.kind===`visitor`?void 0:l.token,onUnauthenticated:u,children:(0,V.jsx)(pie,{children:(0,V.jsx)(Ire,{children:(0,V.jsx)(dye,{ui:a,children:(0,V.jsx)(Lbe,{workspace:r,sidebarMode:i,assistant:o,runtime:s})})})})})},zbe=({auth:e,workspace:t,basePath:n,initialUrl:r,pluginLoader:i,...a})=>(0,V.jsx)(kre,{children:(0,V.jsx)(ef,{session:e,children:(0,V.jsx)(ane,{basePath:n,initialUrl:r,children:(0,V.jsx)(dre,{...i&&{loader:i},children:(0,V.jsx)(hre,{workspace:t,children:(0,V.jsx)(Rbe,{workspace:t,...a})})})})})});export{G as $,Yg as A,Rg as B,i_ as C,$g as D,Jre as E,Wg as F,rre as G,Cg as H,Ug as I,Zh as J,cg as K,Vg as L,qg as M,Kg as N,Wre as O,Gg as P,Eh as Q,Bg as R,u_ as S,n_ as T,mg as U,wg as V,hg as W,Nh as X,Ph as Y,Mh as Z,PC as _,B5 as a,Dd as at,bx as b,Fhe as c,ad as ct,lT as d,B as dt,Th as et,cT as f,b as ft,FC as g,IC as h,e7 as i,Sf as it,Jg as j,Ure as k,G8 as l,ed as lt,Tw as m,B9 as n,Cf as nt,Jhe as o,Td as ot,Pw as p,rg as q,z9 as r,U as rt,Phe as s,wd as st,zbe as t,Ff as tt,sT as u,Lu as ut,gS as v,r_ as w,h_ as x,xx as y,zg as z};
|
|
67
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function jle(e,t){if(e){if(typeof e==`string`)return f4(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?f4(e,t):void 0}}function f4(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Mle(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function Nle(e){if(Array.isArray(e))return e}var Ple=()=>(eq(),null);function p4(e){if(typeof e==`number`)return e;if(typeof e==`string`){var t=parseFloat(e);if(!Number.isNaN(t))return t}return 0}var Fle=(0,o.forwardRef)((e,t)=>{var n=(0,o.useRef)(null),r=d4((0,o.useState)({containerWidth:p4(e.style?.width),containerHeight:p4(e.style?.height)}),2),i=r[0],a=r[1],s=(0,o.useCallback)((e,t)=>{a(n=>{var r=Math.round(e),i=Math.round(t);return n.containerWidth===r&&n.containerHeight===i?n:{containerWidth:r,containerHeight:i}})},[]),c=(0,o.useCallback)(e=>{if(typeof t==`function`&&t(e),n.current!=null&&(n.current.disconnect(),n.current=null),e!=null&&typeof ResizeObserver<`u`){var r=e.getBoundingClientRect(),i=r.width,a=r.height;s(i,a);var o=new ResizeObserver(e=>{var t=e[0];if(t!=null){var n=t.contentRect,r=n.width,i=n.height;s(r,i)}});o.observe(e),n.current=o}},[t,s]);return(0,o.useEffect)(()=>()=>{n.current?.disconnect()},[s]),o.createElement(o.Fragment,null,o.createElement(zj,{width:i.containerWidth,height:i.containerHeight}),o.createElement(`div`,u4({ref:c},e)))}),Ile=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height,i=d4((0,o.useState)({containerWidth:p4(n),containerHeight:p4(r)}),2),a=i[0],s=i[1],c=(0,o.useCallback)((e,t)=>{s(n=>{var r=Math.round(e),i=Math.round(t);return n.containerWidth===r&&n.containerHeight===i?n:{containerWidth:r,containerHeight:i}})},[]),l=(0,o.useCallback)(e=>{if(typeof t==`function`&&t(e),e!=null){var n=e.getBoundingClientRect(),r=n.width,i=n.height;c(r,i)}},[t,c]);return o.createElement(o.Fragment,null,o.createElement(zj,{width:a.containerWidth,height:a.containerHeight}),o.createElement(`div`,u4({ref:l},e)))}),Lle=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height;return o.createElement(o.Fragment,null,o.createElement(zj,{width:n,height:r}),o.createElement(`div`,u4({ref:t},e)))}),Rle=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height;return typeof n==`string`||typeof r==`string`?o.createElement(Ile,u4({},e,{ref:t})):typeof n==`number`&&typeof r==`number`?o.createElement(Lle,u4({},e,{width:n,height:r,ref:t})):o.createElement(o.Fragment,null,o.createElement(zj,{width:n,height:r}),o.createElement(`div`,u4({ref:t},e)))});function zle(e){return e?Fle:Rle}var Ble=(0,o.forwardRef)((e,t)=>{var n=e.children,r=e.className,i=e.height,a=e.onClick,s=e.onContextMenu,c=e.onDoubleClick,l=e.onMouseDown,u=e.onMouseEnter,d=e.onMouseLeave,f=e.onMouseMove,p=e.onMouseUp,m=e.onTouchEnd,h=e.onTouchMove,g=e.onTouchStart,_=e.style,v=e.width,y=e.responsive,b=e.dispatchTouchEvents,x=b===void 0||b,S=(0,o.useRef)(null),C=OO(),w=d4((0,o.useState)(null),2),T=w[0],E=w[1],D=d4((0,o.useState)(null),2),O=D[0],k=D[1],A=Tle(),j=kj(),M=j?.width>0?j.width:v,N=j?.height>0?j.height:i,ee=(0,o.useCallback)(e=>{A(e),typeof t==`function`&&t(e),E(e),k(e),e!=null&&(S.current=e)},[A,t,E,k]),P=(0,o.useCallback)(e=>{C(C2(e)),C(V2({handler:a,reactEvent:e}))},[C,a]),te=(0,o.useCallback)(e=>{C(T2(e)),C(V2({handler:u,reactEvent:e}))},[C,u]),F=(0,o.useCallback)(e=>{C(lW()),C(V2({handler:d,reactEvent:e}))},[C,d]),ne=(0,o.useCallback)(e=>{C(T2(e)),C(V2({handler:f,reactEvent:e}))},[C,f]),re=(0,o.useCallback)(()=>{C(P2())},[C]),ie=(0,o.useCallback)(()=>{C(F2())},[C]),I=(0,o.useCallback)(e=>{C(N2(e.key))},[C]),ae=(0,o.useCallback)(e=>{C(V2({handler:s,reactEvent:e}))},[C,s]),L=(0,o.useCallback)(e=>{C(V2({handler:c,reactEvent:e}))},[C,c]),oe=(0,o.useCallback)(e=>{C(V2({handler:l,reactEvent:e}))},[C,l]),R=(0,o.useCallback)(e=>{C(V2({handler:p,reactEvent:e}))},[C,p]),se=(0,o.useCallback)(e=>{C(V2({handler:g,reactEvent:e}))},[C,g]),ce=(0,o.useCallback)(e=>{x&&C(K2(e)),C(V2({handler:h,reactEvent:e}))},[C,x,h]),le=(0,o.useCallback)(e=>{C(V2({handler:m,reactEvent:e}))},[C,m]),ue=zle(y);return o.createElement(OK.Provider,{value:T},o.createElement(wE.Provider,{value:O},o.createElement(ue,{width:M??_?.width,height:N??_?.height,className:ST(`recharts-wrapper`,r),style:Ele({position:`relative`,cursor:`default`,width:M,height:N},_),onClick:P,onContextMenu:ae,onDoubleClick:L,onFocus:re,onBlur:ie,onKeyDown:I,onMouseDown:oe,onMouseEnter:te,onMouseLeave:F,onMouseMove:ne,onMouseUp:R,onTouchEnd:le,onTouchMove:ce,onTouchStart:se,ref:ee},o.createElement(Ple,null),n)))}),Vle=[`width`,`height`,`responsive`,`children`,`className`,`style`,`compact`,`title`,`desc`];function Hle(e,t){if(e==null)return{};var n,r,i=Ule(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Ule(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var m4=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height,i=e.responsive,a=e.children,s=e.className,c=e.style,l=e.compact,u=e.title,d=e.desc,f=OT(Hle(e,Vle));return l?o.createElement(o.Fragment,null,o.createElement(zj,{width:n,height:r}),o.createElement(s4,{otherAttributes:f,title:u,desc:d},a)):o.createElement(Ble,{className:s,style:c,width:n,height:r,responsive:i??!1,onClick:e.onClick,onMouseLeave:e.onMouseLeave,onMouseEnter:e.onMouseEnter,onMouseMove:e.onMouseMove,onMouseDown:e.onMouseDown,onMouseUp:e.onMouseUp,onContextMenu:e.onContextMenu,onDoubleClick:e.onDoubleClick,onTouchStart:e.onTouchStart,onTouchMove:e.onTouchMove,onTouchEnd:e.onTouchEnd},o.createElement(s4,{otherAttributes:f,title:u,desc:d,ref:t},o.createElement(e$,null,a)))});function h4(){return h4=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},h4.apply(null,arguments)}function g4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Wle(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?g4(Object(n),!0).forEach(function(t){Gle(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):g4(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Gle(e,t,n){return(t=Kle(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Kle(e){var t=qle(e,`string`);return typeof t==`symbol`?t:t+``}function qle(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var Jle=Wle({accessibilityLayer:!0,barCategoryGap:`10%`,barGap:4,layout:`horizontal`,margin:{top:5,right:5,bottom:5,left:5},responsive:!1,reverseStackOrder:!1,stackOffset:`none`,syncMethod:`index`},Q2),_4=(0,o.forwardRef)(function(e,t){var n=ND(e.categoricalChartProps,Jle),r=e.chartName,i=e.defaultTooltipEventType,a=e.validateTooltipEventTypes,s=e.tooltipPayloadSearcher,c=e.categoricalChartProps,l={chartName:r,defaultTooltipEventType:i,validateTooltipEventTypes:a,tooltipPayloadSearcher:s,eventEmitter:void 0};return o.createElement(e4,{preloadedState:{options:l},reduxStoreName:c.id??r},o.createElement(RQ,{chartData:c.data}),o.createElement(t4,{layout:n.layout,margin:n.margin}),o.createElement(r4,{throttleDelay:n.throttleDelay,throttledEvents:n.throttledEvents}),o.createElement(n4,{baseValue:n.baseValue,accessibilityLayer:n.accessibilityLayer,barCategoryGap:n.barCategoryGap,maxBarSize:n.maxBarSize,stackOffset:n.stackOffset,barGap:n.barGap,barSize:n.barSize,syncId:n.syncId,syncMethod:n.syncMethod,className:n.className,reverseStackOrder:n.reverseStackOrder}),o.createElement(m4,h4({},n,{ref:t})))}),Yle=[`axis`],Xle=(0,o.forwardRef)((e,t)=>o.createElement(_4,{chartName:`LineChart`,defaultTooltipEventType:`axis`,validateTooltipEventTypes:Yle,tooltipPayloadSearcher:PK,categoricalChartProps:e,ref:t})),Zle=[`axis`,`item`],v4=(0,o.forwardRef)((e,t)=>o.createElement(_4,{chartName:`BarChart`,defaultTooltipEventType:`axis`,validateTooltipEventTypes:Zle,tooltipPayloadSearcher:PK,categoricalChartProps:e,ref:t}));function Qle(e){var t=OO();return(0,o.useEffect)(()=>{t(ole(e))},[t,e]),null}var $le=[`layout`];function y4(){return y4=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},y4.apply(null,arguments)}function eue(e,t){if(e==null)return{};var n,r,i=tue(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function tue(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function b4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function nue(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?b4(Object(n),!0).forEach(function(t){rue(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):b4(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function rue(e,t,n){return(t=iue(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function iue(e){var t=aue(e,`string`);return typeof t==`symbol`?t:t+``}function aue(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var x4=nue({accessibilityLayer:!0,stackOffset:`none`,barCategoryGap:`10%`,barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:`index`,layout:`radial`,responsive:!1,cx:`50%`,cy:`50%`,innerRadius:0,outerRadius:`80%`},Q2),oue=(0,o.forwardRef)(function(e,t){var n=ND(e.categoricalChartProps,x4),r=n.layout,i=eue(n,$le),a=e.chartName,s={chartName:a,defaultTooltipEventType:e.defaultTooltipEventType,validateTooltipEventTypes:e.validateTooltipEventTypes,tooltipPayloadSearcher:e.tooltipPayloadSearcher,eventEmitter:void 0};return o.createElement(e4,{preloadedState:{options:s},reduxStoreName:n.id??a},o.createElement(RQ,{chartData:n.data}),o.createElement(t4,{layout:r,margin:n.margin}),o.createElement(r4,{throttleDelay:n.throttleDelay,throttledEvents:n.throttledEvents}),o.createElement(n4,{baseValue:void 0,accessibilityLayer:n.accessibilityLayer,barCategoryGap:n.barCategoryGap,maxBarSize:n.maxBarSize,stackOffset:n.stackOffset,barGap:n.barGap,barSize:n.barSize,syncId:n.syncId,syncMethod:n.syncMethod,className:n.className,reverseStackOrder:n.reverseStackOrder}),o.createElement(Qle,{cx:n.cx,cy:n.cy,startAngle:n.startAngle,endAngle:n.endAngle,innerRadius:n.innerRadius,outerRadius:n.outerRadius}),o.createElement(m4,y4({},i,{ref:t})))});function S4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function C4(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?S4(Object(n),!0).forEach(function(t){sue(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):S4(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function sue(e,t,n){return(t=cue(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function cue(e){var t=lue(e,`string`);return typeof t==`symbol`?t:t+``}function lue(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var uue=[`item`],due=C4(C4({},x4),{},{layout:`centric`,startAngle:0,endAngle:360}),fue=(0,o.forwardRef)((e,t)=>{var n=ND(e,due);return o.createElement(oue,{chartName:`PieChart`,defaultTooltipEventType:`item`,validateTooltipEventTypes:uue,tooltipPayloadSearcher:PK,categoricalChartProps:n,ref:t})}),pue=(e,t)=>t>0?`${Math.round(e/t*100)}%`:``,mue=({active:e,payload:t,measure:n})=>{let r=t?.[0]?.payload;return!e||!r?null:(0,H.jsxs)(`div`,{className:`rounded-md border bg-background px-2.5 py-1.5 text-xs shadow-pop`,children:[(0,H.jsx)(`div`,{className:`text-muted-foreground`,children:r.label}),(0,H.jsx)(`div`,{className:`font-semibold tabular-nums`,children:yT(r.value,n)})]})},hue=({resource:e,slices:t,measure:n})=>{let r=t.filter(e=>e.value!==null&&e.value>0),i=r.reduce((e,t)=>e+t.value,0);return(0,H.jsxs)(`div`,{className:`flex flex-col items-center gap-4 sm:flex-row sm:items-center`,children:[(0,H.jsx)(`div`,{className:`size-36 shrink-0`,children:(0,H.jsx)(Aj,{width:`100%`,height:`100%`,children:(0,H.jsxs)(fue,{children:[(0,H.jsx)(FZ,{data:r,dataKey:`value`,nameKey:`label`,innerRadius:`62%`,outerRadius:`100%`,paddingAngle:+(r.length>1),stroke:`var(--background)`,strokeWidth:2,isAnimationActive:!1,children:r.map(e=>(0,H.jsx)(vq,{fill:e.color},e.key))}),(0,H.jsx)(_q,{content:(0,H.jsx)(mue,{measure:n}),isAnimationActive:!1})]})})}),(0,H.jsx)(`ul`,{className:`flex w-full min-w-0 flex-col gap-0.5`,children:t.map(t=>(0,H.jsx)(`li`,{children:(0,H.jsxs)(FC,{to:{kind:`list`,resource:e,filter:t.filter},className:`group flex items-center gap-2 rounded-md px-1 py-0.5 hover:bg-muted`,children:[(0,H.jsx)(`span`,{className:`size-2.5 shrink-0 rounded-full`,style:{background:t.color},"aria-hidden":!0}),(0,H.jsx)(`span`,{className:`min-w-0 flex-1 truncate group-hover:text-primary-text`,children:t.label}),(0,H.jsx)(`span`,{className:`font-medium tabular-nums`,children:yT(t.value,n)}),(0,H.jsx)(`span`,{className:`w-9 text-right text-xs text-muted-foreground tabular-nums`,children:pue(t.value??0,i)})]})},t.key))})]})},gue={hour:{hour:`2-digit`,minute:`2-digit`,hour12:!1},day:{day:`numeric`,month:`short`},week:{day:`numeric`,month:`short`},month:{month:`short`,year:`2-digit`},year:{year:`numeric`}},_ue={hour:{day:`numeric`,month:`short`,hour:`2-digit`,minute:`2-digit`,hour12:!1},day:{day:`numeric`,month:`short`,year:`numeric`},week:{day:`numeric`,month:`short`,year:`numeric`},month:{month:`long`,year:`numeric`},year:{year:`numeric`}},w4=e=>{let t=new Intl.DateTimeFormat(`en-GB`,{...e,timeZone:`UTC`});return e=>t.format(e)},T4={fontSize:11,fill:`var(--muted-foreground)`},vue=({active:e,payload:t,measure:n,bucket:r})=>{let i=t?.[0]?.payload;return!e||!i?null:(0,H.jsxs)(`div`,{className:`rounded-md border bg-background px-2.5 py-1.5 text-xs shadow-pop`,children:[(0,H.jsx)(`div`,{className:`text-muted-foreground`,children:(r===`week`?`Week of `:``)+w4(_ue[r])(i.at)}),(0,H.jsx)(`div`,{className:`font-semibold tabular-nums`,children:yT(i.value,n)})]})},yue=({points:e,measure:t,bucket:n,type:r})=>{let i=fu(`(min-width: 640px)`),a=w4(gue[n]),o=(0,H.jsx)(C1,{vertical:!1,stroke:`var(--border)`}),s=(0,H.jsx)(h2,{dataKey:`at`,tickFormatter:a,tick:T4,axisLine:!1,tickLine:!1,minTickGap:i?24:40,height:18}),c=(0,H.jsx)(b2,{width:i?48:36,tick:T4,axisLine:!1,tickLine:!1,tickCount:3,tickFormatter:e=>e.toLocaleString(`en-IE`,{notation:`compact`})}),l=(0,H.jsx)(_q,{cursor:r===`bar`?{fill:`var(--muted)`}:{stroke:`var(--border-strong)`},content:(0,H.jsx)(vue,{measure:t,bucket:n}),isAnimationActive:!1});return(0,H.jsx)(`div`,{className:`h-40`,children:(0,H.jsx)(Aj,{width:`100%`,height:`100%`,children:r===`line`?(0,H.jsxs)(Xle,{data:e,margin:{top:6,right:6,bottom:0,left:0},children:[o,s,c,l,(0,H.jsx)(D0,{dataKey:`value`,stroke:`var(--chart-1)`,strokeWidth:2,dot:e.length<=31&&{r:3,fill:`var(--chart-1)`,strokeWidth:0},activeDot:{r:4,stroke:`var(--background)`,strokeWidth:2},isAnimationActive:!1})]}):(0,H.jsxs)(v4,{data:e,margin:{top:6,right:0,bottom:0,left:0},barCategoryGap:`22%`,children:[o,s,c,l,(0,H.jsx)(s2,{dataKey:`value`,fill:`var(--chart-1)`,radius:[4,4,0,0],isAnimationActive:!1})]})})})},bue=(e,t,n,r)=>{let i=n??r,a=i===void 0?void 0:e.fields[i];return!a||i===void 0?{kind:`count`}:{kind:n===void 0?`average`:`sum`,field:a,hints:t?.fields[i]}},E4=({model:e,view:t,groupBy:n,type:r=`bar`,sum:i,average:a,filter:o=``,granularity:s=`day`,range:c=`30d`,limit:l=10,empty:u=`Nothing to chart yet.`})=>{let{resources:d,views:f}=J(),p=e.fields[n],m=p?.type===`date`||p?.type===`timestamp`,h=p?.type===`relation`&&p.relation?d[p.relation.resource]:void 0,g=h&&h.primaryKey.length===1?Tg(h,f[h.name]):void 0,_=m?{granularity:s,range:c}:{limit:l,...g&&{label:g}},v=uT(e.name,{groupBy:n,filter:o,...i&&{sum:i},...a&&{average:a},..._},!!p),y=bue(e,t,i,a);if(!p)return null;if(v.isPending)return(0,H.jsx)(ku,{className:`h-36 w-full`});if(v.error)return(0,H.jsx)(`p`,{className:`text-danger-text`,children:`Could not load the chart.`});let{groups:b}=v.data;if(b.every(e=>e.count===0))return(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:u});if(m)return(0,H.jsx)(yue,{points:vT(b,y),measure:y,bucket:s,type:r===`line`?`line`:`bar`});let x=_T(b,p,t?.fields[n],y,o);return r===`donut`?(0,H.jsx)(hue,{resource:e.name,slices:x,measure:y}):(0,H.jsx)(bT,{resource:e.name,slices:x,measure:y})},xue=({node:e,slots:t})=>{let{resource:n,title:r,description:i,actions:a,span:o,...s}=eT(e),{resources:c,views:l}=J(),u=c[n];return u?(0,H.jsx)(nT,{title:r,description:i,actions:t.actions,className:`h-full`,children:(0,H.jsx)(E4,{model:u,view:l[n],...s})}):null},Sue=uo(),D4=async(e,t,n,r,i)=>{let a=n.primaryKey[0],o=[...new Set(r)].sort();if(o.length===0||n.primaryKey.length!==1)return new Map;let s=Tg(n,i),c=await e.fetchQuery({queryKey:G.labels(n.name,o.join(`,`)),staleTime:3e5,queryFn:async()=>(await t.list(n.name,{filter:Ya(Sue.in(a,o)),fields:[a,s],pageSize:o.length})).items.map(e=>[String(e[a]),String(e[s])])});return new Map(c)},O4=(e,t,n)=>n.flatMap(n=>{let r=t.fields[n],i=r?.type===`relation`&&r.relation?e[r.relation.resource]:void 0;return i?[{name:n,target:i}]:[]}),k4=(e,t,n,r)=>Object.fromEntries(O4(e,n,r).filter(({target:e})=>e.primaryKey.length===1).map(({name:e,target:n})=>[e,Tg(n,t[n.name])])),A4=(e,t,n,r,i={})=>{let a=O4(e,t,n);return r.map(e=>{let t={...e};for(let{name:n}of a)e[n]!=null&&(t[n]={id:e[n],name:i[n]?.[String(e[n])]??String(e[n])});return t})},j4=(e,t)=>{let n=String(t);return e&&Object.hasOwn(e,n)?e[n]:void 0},M4=({value:e,hints:t,children:n})=>(0,H.jsx)(Xu,{tone:HS(String(e)),color:j4(t?.valueColors,e),shape:t?.badgeShape,children:n}),Cue=({field:e,value:t,known:n})=>{let{resources:r,views:i}=J(),a=K(),o=Up(),s=e.relation?r[e.relation.resource]:void 0,c=String(t),l=_h({queryKey:G.relatedLabel(s?.name??``,c),enabled:!!s&&n===void 0,queryFn:async()=>(await D4(o,a,s,[c],i[s.name])).get(c)??c});return s?(0,H.jsx)(FC,{to:{kind:`record`,resource:s.name,key:c},className:`font-medium text-primary-text hover:underline`,children:n??l.data??c}):(0,H.jsx)(`span`,{children:c})},wue=({model:e,field:t,value:n,format:r,relationLabel:i})=>{let{views:a}=J(),o={...a[e.name]?.fields[t.name],...r&&{format:r}};if(n==null||n===``)return(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`—`});if(t.type===`relation`)return(0,H.jsx)(Cue,{field:t,value:n,known:i});let s=t.type===`file`?Nx(n):void 0;if(s&&`url`in s&&s.url){let e=Vx(n,{width:40,height:40});return(0,H.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[e&&(0,H.jsx)($C,{image:e,className:`size-10 shrink-0 rounded border border-border object-cover`}),(0,H.jsx)(`a`,{href:s.url,target:`_blank`,rel:`noreferrer`,className:`truncate font-medium text-primary-text hover:underline`,children:s.name})]})}if(BS(t,o))return(0,H.jsx)(cw,{source:String(n)});let c=ZS(t,n,o);return t.type===`enum`||o.format===`badge`?(0,H.jsx)(M4,{value:n,hints:o,children:c}):(0,H.jsx)(`span`,{className:V(o.format===`code`&&`font-mono text-xs`,(t.type===`decimal`||t.type===`integer`)&&`tabular-nums`,o.multiline&&`whitespace-pre-line break-words`),children:c})},N4=e=>{let{views:t}=J(),n=iw(e.field,t[e.model.name]?.fields[e.field.name]),r=(0,H.jsx)(wue,{...e});return n?(0,H.jsx)(ow,{shown:n,part:`display`,field:e.field,value:e.value,fallback:r}):r},P4=(e,t,n)=>{if(!t)return[];let r=rc(e,t.model.name,n);return r.ok?r.steps:[]},F4=(e,t,n,r,i)=>({queryKey:G.pathValue(n?.model.name??``,n?.key??``,r),enabled:i.length>1,queryFn:async()=>{let r=n.record;for(let n of i.slice(0,-1)){let i=r[n.field.name];if(i==null)return null;let a=n.field.relation.resource;r=(await t.fetchQuery({queryKey:G.record(a,String(i)),queryFn:()=>e.get(a,String(i))})).record}return r[i.at(-1).field.name]??null}}),I4=(e,t,n)=>{let r=t.at(-1);return!e||!r?{state:`missing`}:t.length===1?{state:`ready`,value:e.record[r.field.name],field:r.field,model:r.model}:n.isPending?{state:`loading`}:{state:`ready`,value:n.data??null,field:r.field,model:r.model}},L4=(e,t)=>{let{resources:n}=J(),r=P4(n,e,t);return I4(e,r,_h(F4(K(),Up(),e,t,r)))},Tue=(e,t)=>{let{resources:n}=J(),r=K(),i=Up(),a=t.map(t=>P4(n,e,t)),o=hh({queries:t.map((t,n)=>F4(r,i,e,t,a[n]))});return t.map((t,n)=>I4(e,a[n],o[n]))},Eue=(e,t)=>{if(t)return t;let n=e.split(`.`).map(e=>q(e).toLowerCase()).join(` `);return n[0].toUpperCase()+n.slice(1)},Due=({node:e})=>{let{name:t,label:n,format:r}=eT(e),{views:i}=J(),a=L4(Pw(),t);if(a.state===`missing`)return null;let o=a.state===`loading`?(0,H.jsx)(ku,{className:`h-4 w-24`}):(0,H.jsx)(N4,{model:a.model,field:a.field,value:a.value,format:r});if(n===!1)return(0,H.jsx)(`div`,{children:o});let s=n??Eue(t,a.state===`ready`?i[a.model.name]?.fields[a.field.name]?.label:void 0);return(0,H.jsxs)(`div`,{className:`min-w-0`,children:[(0,H.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:s}),(0,H.jsx)(`div`,{className:`mt-0.5 truncate`,children:o})]})},Oue={1:``,2:`md:grid-cols-2`,3:`md:grid-cols-2 xl:grid-cols-3`,4:`sm:grid-cols-2 xl:grid-cols-4`},kue={1:``,2:`grid-cols-2`,3:`grid-cols-2 xl:grid-cols-3`,4:`grid-cols-2 xl:grid-cols-4`},Aue={1:``,2:`md:col-span-2`,3:`md:col-span-2 xl:col-span-3`,4:`sm:col-span-2 md:col-span-2 xl:col-span-4`},jue=e=>typeof e==`object`&&!e.custom&&e.type===`Stat`,Mue=({node:e,children:t})=>{let{columns:n=2}=eT(e),r=e.children,i=r.length>0&&r.every(jue);return(0,H.jsx)(`div`,{className:V(`grid grid-cols-1 gap-4`,i?kue[n]:Oue[n]),children:t.map((e,t)=>{let n=r[t],i=typeof n==`object`?n.props.span:void 0;return(0,H.jsx)(`div`,{className:V(`min-w-0`,i&&Aue[i]),children:e},t)})})},R4=`font-medium text-primary-text hover:underline`,Nue=({node:e})=>{let t=eT(e),n=Pw()?.record,r=e.children.filter(e=>typeof e==`string`).join(``);if(t.to){let e=Do(t.to,n);return(0,H.jsx)(FC,{to:e,className:R4,children:r||us(e)})}let i=t.href??``;return(0,H.jsx)(`a`,{href:i,className:R4,...i.startsWith(`http`)&&{target:`_blank`,rel:`noreferrer`},children:r||i})},z4=(e,t)=>typeof e?.[t]==`number`?e[t]:void 0,B4=e=>`${af(e)} character${e===1?``:`s`}`,Pue=(e,t)=>{let n=z4(t,`min`),r=z4(t,`max`);if(n!==void 0)return`${e} needs at least ${B4(n)}`;if(r!==void 0)return`${e} can have at most ${B4(r)}`},Fue=e=>{let t=z4(e,`min`),n=z4(e,`max`);return t===void 0?n===void 0?`Enter a whole number`:`Enter a whole number of at most ${af(n)}`:`Enter a whole number of at least ${af(t)}`},Iue=e=>{let t=z4(e,`precision`),n=z4(e,`scale`);if(t===void 0||n===void 0)return`Enter a number`;let r=af(10**(t-n));return n===0?`Enter a whole number below ${r}`:`Enter a number with at most ${n} decimal${n===1?``:`s`}, below ${r}`},Lue={text:Pue,integer:(e,t)=>Fue(t),bigint:()=>`Enter a whole number`,decimal:(e,t)=>Iue(t),date:()=>`Enter a date`,timestamp:()=>`Enter a date and time`,country:()=>`Enter a two-letter country code, such as NL`,currency:()=>`Enter a three-letter currency code, such as EUR`,uuid:()=>`Enter a valid ID`,enum:()=>`Choose one of the options`,relation:()=>`Choose a record`,json:()=>`Enter valid JSON`},V4=(e,t,n)=>n.code===`required`?`${t} is required`:n.code!==`invalid-value`||!e?n.message:Lue[e.type]?.(t,n.params)??n.message,H4=e=>{if(!Fs(e))return{};let t={};for(let n of e.errors)n.field&&n.field!==`_record`&&!Object.hasOwn(t,n.field)&&(t[n.field]=n);return t},Rue=e=>{if(e.operation!==void 0)return e.message;let t=new Set(e.errors.flatMap(e=>e.field&&e.field!==`_record`?[e.field]:[])),n=e.errors.flatMap(e=>e.field===`_record`?[e.message]:[]);return t.size===0&&n.length===0?e.message:[...t.size===0?[]:[`Check ${t.size===1?`the marked field`:`${t.size} fields`}.`],...n].join(` `)},U4=e=>{let t=(0,o.useRef)(null);return(0,o.useEffect)(()=>{e!==0&&t.current?.querySelector(`[aria-invalid="true"]`)?.focus()},[e]),t},zue=(e,t,n)=>Object.fromEntries(t.map(t=>{let r=e.fields[t];if(r.type===`file`)return[t,n?.record[t]??null];if(n)return[t,r.type===`boolean`?!!n.record[t]:Gx(n.record[t])];let i=r.default&&`value`in r.default?r.default.value:void 0;return[t,r.type===`boolean`?!!i:Gx(i)]})),Bue=(e,t,n)=>Object.fromEntries(Object.entries(t).flatMap(([t,r])=>{let i=e.fields[t];return rS(r)?r.key===Gx(n.record[t])?[]:[[t,i.type===`integer`?Number(r.key):r.key]]:Qx(i,r,n.record[t])?[[t,Yx(i,r)]]:[]})),Vue=({model:e,record:t,mode:n,label:r,title:i,fields:a,values:s,onClose:c})=>{let{resources:l,views:u}=J(),d=K(),f=Ig(),p=Xw(),m=u[e.name],[h,g]=(0,o.useState)(()=>zue(e,a,t)),[_,v]=(0,o.useState)({}),[y,b]=(0,o.useState)(0),x=U4(y),[S,C]=(0,o.useState)(),[w,T]=(0,o.useState)(!1),E=async()=>{T(!0),C(void 0),await(n===`create`?d.create(e.name,{...sS(e,l,h),...s}):d.update(e.name,t.key,Bue(e,h,t),t.etag??`*`)).then(async()=>{await p(e.name),f.show({state:`success`,title:`${i??r}: saved`}),c()},e=>{let t=H4(e);v(t),Object.keys(t).length>0&&b(e=>e+1),C(e)}),T(!1)};return(0,H.jsx)(Sf,{title:i??r,onClose:c,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:c,children:`Cancel`}),(0,H.jsx)(W,{variant:`primary`,loading:w,onClick:()=>void E(),children:n===`create`?`Create`:`Save`})]}),children:(0,H.jsxs)(`form`,{ref:x,className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),E()},children:[S!==void 0&&Object.keys(_).length===0&&(0,H.jsx)(pS,{title:`Not saved`,error:S}),a.map(n=>{let r=e.fields[n],i=h[n],a=r.relation?l[r.relation.resource]:void 0,o=m?.fields[n]?.label??q(n),s=_[n];return(0,H.jsx)(bx,{name:n,label:o,help:m?.fields[n]?.help,error:s&&V4(r,o,s),children:(0,H.jsx)(mw,{field:r,hints:m?.fields[n],value:rS(i)?i.key:i,stored:t?.record[n],relationLabel:rS(i)?i.label:void 0,relationPicker:a?{target:a,view:u[a.name]}:void 0,invalid:!!_[n],resource:e.name,onChange:e=>{v(({[n]:e,...t})=>t),g(t=>({...t,[n]:e}))}})},n)})]})})},Hue=({model:e,recordKey:t,children:n})=>{let r=Jw(e,{key:t});return(0,H.jsx)(H.Fragment,{children:n(r.data??void 0)})},Uue=({node:e})=>{let t=eT(e),n=Pw(),{resources:r}=J(),i=r[t.resource??n?.model.name??``],a=d_(i?.name??``),[s,c]=(0,o.useState)(!1);if(!i||!(t.mode===`create`?Fw(a,`create`):Fw(a,`update`)&&n?.permissions?.update!==!1))return null;let l=e=>(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{size:`sm`,variant:t.variant??`secondary`,disabled:t.mode===`edit`&&!e,onClick:()=>c(!0),children:t.label}),s&&(0,H.jsx)(Vue,{...t,model:i,record:t.mode===`edit`?e:void 0,onClose:()=>c(!1)})]});return t.mode===`edit`&&t.recordKey!==void 0?(0,H.jsx)(Hue,{model:i,recordKey:t.recordKey,children:l}):l(t.mode===`edit`?n:void 0)},Wue=({node:e,children:t,slots:n})=>{let{title:r,description:i}=eT(e);return(0,H.jsx)(`div`,{className:`flex-1`,children:(0,H.jsxs)(`div`,{className:`mx-auto flex max-w-[1200px] flex-col gap-6 px-4 pb-16 pt-6 md:px-10 md:py-8`,children:[(0,H.jsx)(Pd,{title:r,subtitle:i,actions:n.actions}),t]})})},W4=(e,t)=>{let n=Pw(),r=L4(typeof e==`string`?n:void 0,typeof e==`string`?e:``);return typeof e==`number`?e:e===void 0?t:r.state===`ready`?Number(r.value):r.state===`loading`?void 0:NaN},Gue=({node:e})=>{let{value:t,max:n,label:r}=eT(e),i=W4(t,0),a=W4(n,100);if(i===void 0||a===void 0)return(0,H.jsx)(ku,{className:`h-6 w-full`});if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=a>0?Math.min(1,Math.max(0,i/a)):0;return(0,H.jsxs)(`div`,{className:`min-w-0`,children:[(0,H.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs`,children:[(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:r}),(0,H.jsxs)(`span`,{className:`tabular-nums`,children:[i.toLocaleString(`en-IE`),` / `,a.toLocaleString(`en-IE`)]})]}),(0,H.jsx)(`div`,{role:`progressbar`,"aria-label":r,"aria-valuenow":i,"aria-valuemin":0,"aria-valuemax":a,className:`mt-1.5 h-2 overflow-hidden rounded-full bg-muted`,children:(0,H.jsx)(`div`,{className:o>=.9?`h-full rounded-full bg-warning`:`h-full rounded-full bg-primary`,style:{width:`${o*100}%`}})})]})},Kue=({model:e,filter:t,sort:n,recordKey:r,title:i,description:a,empty:o,actions:s,children:c})=>{let l=Jw(e,{filter:t,sort:n,key:r}),u=e=>l.data?(0,H.jsx)(Nw,{value:l.data,children:e}):void 0,d=l.isPending?(0,H.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,H.jsx)(ku,{className:`h-4 w-1/2`}),(0,H.jsx)(ku,{className:`h-4 w-1/3`})]}):l.error?(0,H.jsx)(pS,{title:`Could not load`,error:l.error}):l.data?u((0,H.jsx)(`div`,{className:`flex flex-col gap-3`,children:c})):(0,H.jsx)(rT,{children:o??`Nothing here yet.`});return(0,H.jsx)(nT,{title:i,description:a,actions:s?u(s):void 0,className:`h-full`,children:d})},que=({node:e,children:t,slots:n})=>{let{resource:r,filter:i,sort:a,recordKey:o,title:s,description:c,empty:l}=eT(e),u=J().resources[r];return u?(0,H.jsx)(Kue,{model:u,filter:i,sort:a,recordKey:o,title:s,description:c,empty:l,actions:n.actions,children:t}):null};function Jue(e){return Yue(e)||typeof e==`function`||Xue(e)}function Yue(e){return typeof e==`function`&&(()=>{let t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function Xue(e){return typeof e==`object`&&typeof e.$$typeof==`symbol`&&[`react.memo`,`react.forward_ref`].includes(e.$$typeof.description)}function G4(e,t){return e==null?null:Jue(e)?o.createElement(e,t):e}function Zue(e){if(`cell`in e&&e.cell){let t=e.cell,n=t.column.columnDef,r=t,i=n;return r.getIsAggregated?.()?G4(i.aggregatedCell??n.cell,t.getContext()):r.getIsPlaceholder?.()?null:G4(n.cell,t.getContext())}return`header`in e&&e.header?G4(e.header.column.columnDef.header,e.header.getContext()):`footer`in e&&e.footer?G4(e.footer.column.columnDef.footer,e.footer.getContext()):null}function Que({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(1)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(1)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function $ue(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var K4=[],q4=0,{link:J4,unlink:ede,propagate:tde,checkDirty:Y4,shallowPropagate:X4}=Que({update(e){return e._update()},notify(e){K4[Q4++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,t3(e))}}),Z4=0,Q4=0,$4,e3=0;function nde(e){try{++e3,e()}finally{--e3||n3()}}function t3(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=ede(n,e)}function n3(){if(!(e3>0)){for(;Z4<Q4;){let e=K4[Z4];K4[Z4++]=void 0,e.notify()}Z4=0,Q4=0}}function rde(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:+!n,get(){return $4!==void 0&&J4(i,$4,q4),i._snapshot},subscribe(e){let t=$ue(e),n={current:!1},r=ide(()=>{i.get(),n.current?($4=void 0,t.next?.(i._snapshot)):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=$4,o=t?.compare??Object.is;if(n)$4=i,++q4,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=5);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{$4=a,n&&(i.flags&=-5),t3(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&Y4(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&X4(e)}}else e&32&&(i.flags=e&-33);return $4!==void 0&&J4(i,$4,q4),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(tde(e),X4(e),n3())}},i}function ide(e){let t=()=>{let t=$4;$4=n,++q4,n.depsTail=void 0,n.flags=6;try{return e()}finally{$4=t,n.flags&=-5,t3(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){let e=this.flags;e&16||e&32&&Y4(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,t3(this)}};return t(),n}function r3(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();let n=i3(e);if(n.length!==i3(t).length)return!1;for(let r=0;r<n.length;r++)if(!Object.prototype.hasOwnProperty.call(t,n[r])||!Object.is(e[n[r]],t[n[r]]))return!1;return!0}function i3(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function ade(e,t){return e===t}function a3(e,t=e=>e,n){let r=n?.compare??ade,i=(0,o.useCallback)(t=>{let{unsubscribe:n}=e.subscribe(t);return n},[e]),a=(0,o.useCallback)(()=>e.get(),[e]);return(0,EO.useSyncExternalStoreWithSelector)(i,a,a,t,r)}function ode(e){let t=a3(e.source,e.selector,{compare:r3});return typeof e.children==`function`?e.children(t):e.children}function sde(e){let t=e;return Object.defineProperty(e,"state",{get(){return e.get()}}),`set`in e&&(t.setState=e.set.bind(e)),t}function cde(e){let{createAtom:t,batch:n}=e,r=t(0);return{createOptionsStore:!1,wrapExternalAtoms:!1,addSubscription:()=>{throw Error(`Feature not supported in current reactivity implementation`)},unmount:()=>{throw Error(`Feature not supported in current reactivity implementation`)},schedule:e.schedule??(e=>queueMicrotask(e)),batch:n,untrack:e=>e(),createReadonlyAtom:(e,n)=>{let i=n?.compare??Object.is,a=!1,o,s=()=>{let t=e();return(!a||!i(o,t))&&(o=t,a=!0),o},c=t(()=>(r.get(),s()),{compare:i});return{get:s,subscribe:c.subscribe.bind(c)}},createWritableAtom:(e,n)=>t(e,{compare:n?.compare}),commit:()=>{r.set(e=>e+1)}}}function lde(e,t=Object.is){let n=!1,r;return{get:e.get,markCommitted:e=>{r=e,n=!0},subscribe:i=>e.subscribe(e=>{(!n||!t(r,e))&&i(e)})}}function ude(){return cde({createAtom:rde,batch:nde})}function o3(e,t){return typeof e==`function`?e(t):e}function s3(e){if(Array.isArray(e))return e.map(s3);if(e&&typeof e==`object`){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let n=t===null?c3():{},r=Object.keys(e);for(let t=0;t<r.length;t++){let i=r[t];Object.defineProperty(n,i,{configurable:!0,enumerable:!0,value:s3(e[i]),writable:!0})}return n}return e}function dde(e,t){let n=Object.keys(t),r=e;for(let e=0;e<n.length;e++){let i=n[e];!i.startsWith(`_memo_`)&&i!==`_cellsCache`&&(r[i]=t[i])}return e}function c3(){return Object.create(null)}function l3(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function u3(e,t){return n=>{(t.options.atoms?.[e]??t.baseAtoms[e]).set(e=>o3(n,e))}}function d3(e){if(typeof e!=`object`||!e)return!1;if(Array.isArray(e))return!0;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function f3(e){return Reflect.ownKeys(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}var fde=3;function pde(e,t){return p3(e,t,fde)}function p3(e,t,n){if(Object.is(e,t))return!0;if(n<=0||!d3(e)||!d3(t)||(Array.isArray(e)||Array.isArray(t))&&(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length))return!1;let r=f3(e),i=f3(t);if(r.length!==i.length)return!1;let a=e,o=t;for(let e=0;e<r.length;e++){let i=r[e];if(!Object.prototype.propertyIsEnumerable.call(t,i)||!p3(a[i],o[i],n-1))return!1}return!0}function m3(e,t,n,r=pde){let i=`on${t.charAt(0).toUpperCase()}${t.slice(1)}Change`,a=e.options[i];a&&a(e=>{let t=o3(n,e);return r(e,t)?e:t})}function mde(e){return e instanceof Function}function hde(e,t){let n=[],r=e=>{e.forEach(e=>{n.push(e);let i=t(e);i.length&&r(i)})};return r(e),n}var gde=({fn:e,memoDeps:t,onAfterCompare:n,onAfterUpdate:r,onBeforeCompare:i,onBeforeUpdate:a})=>{let o=[],s;return c=>{i?.();let l=t?.(c),u=!l||l.length!==o?.length;if(!u&&l){for(let e=0;e<l.length;e++)if(l[e]!==o[e]){u=!0;break}}return n?.(u),u?(o=l,a?.(),s=e(...l??[]),r?.(s),s):s}};function _de(e){let t=!1;return()=>{if(!t){t=!0;return}e()}}function h3({feature:e,fnName:t,objectId:n,onAfterUpdate:r,table:i,...a}){let o=()=>{if(!r)return;let{schedule:e,untrack:t}=i._reactivity;e(()=>t(()=>r()))},s={onAfterUpdate:()=>{o()}};return gde({...a,...s})}function g3(e,t=`_`){let[n,r]=e.split(t);return{fnKey:r,fnName:`${n}.${r}`,parentName:n}}function _3(e,t,n){for(let[r,{fn:i,memoDeps:a}]of Object.entries(n)){let{fnKey:n,fnName:o}=g3(r);t[n]=a?h3({memoDeps:a,fn:i,fnName:o,table:t,feature:e}):i}}function v3(e,t,n,r){for(let[i,{fn:a,memoDeps:o}]of Object.entries(r)){let{fnKey:r,fnName:s}=g3(i);if(o){let i=`_memo_${r}`;t[r]=function(...t){if(!this[i]){let t=this;this[i]=h3({memoDeps:e=>o(t,e),fn:(...e)=>a(t,...e),fnName:s,objectId:t.id,table:n,feature:e})}return this[i](...t)}}else t[r]=function(...e){return a(this,...e)}}}function y3(e,t,n,...r){return e[t]?.(...r)??n(e,...r)}function vde(e){return e.row.getValue(e.column.id)}function yde(e){return e.getValue()??e.table.options.renderFallbackValue}function bde(e){return{table:e.table,column:e.column,row:e.row,cell:e,getValue:()=>e.getValue(),renderValue:()=>e.renderValue()}}var xde={assignCellPrototype:(e,t)=>{v3(`coreCellsFeature`,e,t,{cell_getValue:{fn:e=>vde(e)},cell_renderValue:{fn:e=>yde(e)},cell_getContext:{fn:e=>bde(e),memoDeps:e=>[e]}})}};function Sde(e){if(!e._headerPrototype){e._headerPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignHeaderPrototype?.(e._headerPrototype,e)}return e._headerPrototype}function b3(e,t,n){let r=Sde(e),i=Object.create(r);i.colSpan=0,i.column=t,i.depth=n.depth,i.headerGroup=null,i.id=n.id??t.id,i.index=n.index,i.isPlaceholder=!!n.isPlaceholder,i.placeholderId=n.placeholderId,i.rowSpan=0,i.subHeaders=[];let a=e._headerInstanceInitFns;for(let e=0;e<a.length;e++)a[e](i);return i}function Cde(){return{start:[],end:[]}}function x3(e){let t=e.table.atoms.columnVisibility?.get();if(!t)return!0;let n=e.columns;return n.length?n.some(e=>y3(e,`getIsVisible`,x3)):(l3(t,e.id)?t[e.id]:void 0)??!0}function wde(e){return e.getAllLeafColumns().filter(e=>y3(e,`getIsVisible`,x3))}function S3(e,t=1){let n=t;for(let r=0;r<e.length;r++){let i=e[r];y3(i,`getIsVisible`,x3)&&i.columns.length&&(n=Math.max(n,S3(i.columns,t+1)))}return n}function Tde(e,t){return e?`${e}_${t}`:String(t)}function Ede(e,t,n,r){let i=e??``;return t&&(i=i?`${i}_${t}`:String(t)),n&&(i=i?`${i}_${n}`:n),r&&(i=i?`${i}_${r}`:r),i}function Dde(e,t){let n=0;for(let r=0;r<e.length;r++)e[r].column===t&&n++;return n}function C3(e,t,n,r,i,a){let o={depth:t,id:Tde(r,t),headers:[]},s=[];for(let i=0;i<e.length;i++){if(!(i in e))continue;let a=e[i],c=s[s.length-1],l=a.column.depth===o.depth,u,d=!1;if(l&&a.column.parent?u=a.column.parent:(u=a.column,d=!0),c&&c.column===u)c.subHeaders.push(a);else{let e=b3(n,u,{id:Ede(r,t,u.id,a.id),isPlaceholder:d,placeholderId:d?String(Dde(s,u)):void 0,depth:t,index:s.length});e.subHeaders.push(a),s.push(e)}o.headers.push(a),a.headerGroup=o}for(let e=0;e<a.length;e++)a[e](o);i.push(o),t>0&&C3(s,t-1,n,r,i,a)}function w3(e){for(let t=0;t<e.length;t++){let n=e[t];if(!y3(n.column,`getIsVisible`,x3))continue;let r=0;if(n.subHeaders.length){w3(n.subHeaders);for(let e=0;e<n.subHeaders.length;e++){let t=n.subHeaders[e];y3(t.column,`getIsVisible`,x3)&&(r+=t.colSpan)}}else r=1;if(n.colSpan=r,n.isPlaceholder&&n.subHeaders.length===1&&n.subHeaders[0].column===n.column){let e=1,t=n.subHeaders[0];for(;t;)t.rowSpan=0,e++,t=t.subHeaders.length===1&&t.subHeaders[0].column===n.column?t.subHeaders[0]:void 0;n.rowSpan=e}else n.rowSpan=1}}function T3(e,t,n,r){let i=S3(e),a=[],o=n._headerGroupInstanceInitFns,s=Array(t.length);for(let e=0;e<t.length;e++)e in t&&(s[e]=b3(n,t[e],{depth:i,index:e}));return C3(s,i-1,n,r,a,o),a.reverse(),w3(a[0]?.headers??[]),a}function Ode(e){if(!e._columnPrototype){e._columnPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignColumnPrototype?.(e._columnPrototype,e)}return e._columnPrototype}function kde(e,t,n,r){let i={...e.getDefaultColumnDef(),...t},a=i.accessorKey,o=a===void 0?void 0:String(a),s=i.id??o?.replaceAll(`.`,`_`)??(typeof i.header==`string`?i.header:void 0),c;if(i.accessorFn)c=i.accessorFn;else if(a!==void 0){if(typeof a==`string`&&a.includes(`.`)){let e=a.split(`.`);c=t=>{let n=t;for(let t=0;t<e.length;t++){let r=e[t];n=n?.[r]}return n}}else c=e=>e[i.accessorKey]}if(!s)throw Error();let l=Ode(e),u=Object.create(l);u.accessorFn=c,u.columnDef=i,u.columns=[],u.depth=n,u.id=`${String(s)}`,u.parent=r;let d=e._columnInstanceInitFns;for(let e=0;e<d.length;e++)d[e](u);return u}function E3(e){let t=e.atoms.columnOrder?.get();return n=>{let r=[];if(!t?.length)r=n;else{let e=new Map;for(let t=0;t<n.length;t++){let r=n[t];e.set(r.id,r)}for(let n=0;n<t.length;n++){let i=t[n],a=e.get(i);a&&(r.push(a),e.delete(i))}for(let t=0;t<n.length;t++){let i=n[t];e.has(i.id)&&r.push(i)}}return Ade(e,r)}}function Ade(e,t){let n=e.atoms.grouping?.get()??[],{groupedColumnMode:r}=e.options;if(!n.length||!r)return t;let i=t.filter(e=>!n.includes(e.id));if(r===`remove`)return i;let a=new Map;for(let e=0;e<t.length;e++){let n=t[e];a.set(n.id,n)}let o=[];for(let e=0;e<n.length;e++){let t=a.get(n[e]);t&&o.push(t)}return[...o,...i]}function jde(e){return[e,...e.columns.flatMap(e=>e.getFlatColumns())]}function Mde(e){if(e.columns.length){let t=e.columns.flatMap(e=>e.getLeafColumns());return y3(e.table,`getOrderColumns`,E3)(t)}return[e]}function Nde(e){return{header:e=>{let t=e.header.column.columnDef;return t.accessorKey?t.accessorKey:t.accessorFn?t.id:null},cell:e=>e.renderValue()?.toString?.()??null,...Object.values(e._features).reduce((e,t)=>Object.assign(e,t.getDefaultColumnDef?.()),{}),...e.options.defaultColumn}}function D3(e,t,n,r=0){let i=Array(t.length);for(let a=0;a<t.length;a++){if(!(a in t))continue;let o=t[a],s=kde(e,o,r,n),c=o;s.columns=c.columns?D3(e,c.columns,s,r+1):[],i[a]=s}return i}function Pde(e){return D3(e,e.options.columns)}function Fde(e){return e.getAllColumns().flatMap(e=>e.getFlatColumns())}function Ide(e){let t=c3(),n=e.getAllFlatColumns();for(let e=0;e<n.length;e++){let r=n[e];t[r.id]=r}return t}function Lde(e){let t=e.getAllColumns().flatMap(e=>e.getLeafColumns());return y3(e,`getOrderColumns`,E3)(t)}function Rde(e){let t=c3(),n=e.getAllLeafColumns();for(let e=0;e<n.length;e++){let r=n[e];t[r.id]=r}return t}function zde(e,t){return e.getAllFlatColumnsById()[t]}var Bde={assignColumnPrototype:(e,t)=>{v3(`coreColumnsFeature`,e,t,{column_getFlatColumns:{fn:e=>jde(e),memoDeps:e=>[e.table.options.columns]},column_getLeafColumns:{fn:e=>Mde(e),memoDeps:e=>[e.table.atoms.columnOrder?.get(),e.table.atoms.grouping?.get(),e.table.options.columns,e.table.options.groupedColumnMode]}})},constructTableAPIs:e=>{_3(`coreColumnsFeature`,e,{table_getDefaultColumnDef:{fn:()=>Nde(e),memoDeps:()=>[e.options.defaultColumn]},table_getAllColumns:{fn:()=>Pde(e),memoDeps:()=>[e.options.columns]},table_getAllFlatColumns:{fn:()=>Fde(e),memoDeps:()=>[e.options.columns]},table_getAllFlatColumnsById:{fn:()=>Ide(e),memoDeps:()=>[e.options.columns]},table_getAllLeafColumns:{fn:()=>Lde(e),memoDeps:()=>[e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.options.columns,e.options.groupedColumnMode]},table_getAllLeafColumnsById:{fn:()=>Rde(e),memoDeps:()=>[e.getAllLeafColumns()]},table_getColumn:{fn:t=>zde(e,t)}})}};function O3(e,t){for(let n=0;n<e.subHeaders.length;n++)O3(e.subHeaders[n],t);t.push(e)}function Vde(e){let t=[];return O3(e,t),t}function Hde(e){return{column:e.column,header:e,table:e.column.table}}function Ude(e){let{start:t,end:n}=e.atoms.columnPinning?.get()??Cde(),r=e.getAllColumns(),i=y3(e,`getVisibleLeafColumns`,wde);if(!t.length&&!n.length)return T3(r,i,e);let a=e.getAllLeafColumnsById(),o=[];for(let e=0;e<t.length;e++){let n=a[t[e]];n&&y3(n,`getIsVisible`,x3)&&o.push(n)}let s=[];for(let e=0;e<n.length;e++){let t=a[n[e]];t&&y3(t,`getIsVisible`,x3)&&s.push(t)}let c=i.filter(e=>!t.includes(e.id)&&!n.includes(e.id));return T3(r,[...o,...c,...s],e)}function Wde(e){return[...e.getHeaderGroups()].reverse()}function Gde(e){let t=e.getHeaderGroups(),n=[];for(let e=0;e<t.length;e++){let r=t[e].headers;for(let e=0;e<r.length;e++)n.push(r[e])}return n}function Kde(e){let t=e.getHeaderGroups()[0]?.headers??[],n=[];for(let e=0;e<t.length;e++){let r=t[e].getLeafHeaders();for(let e=0;e<r.length;e++)n.push(r[e])}return n}var qde={assignHeaderPrototype:(e,t)=>{v3(`coreHeadersFeature`,e,t,{header_getLeafHeaders:{fn:e=>Vde(e),memoDeps:e=>[e.column.table.options.columns]},header_getContext:{fn:e=>Hde(e),memoDeps:e=>[e.column.table.options.columns]}})},constructTableAPIs:e=>{_3(`coreHeadersFeature`,e,{table_getHeaderGroups:{fn:()=>Ude(e),memoDeps:()=>[e.options.columns,e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.atoms.columnPinning?.get(),e.atoms.columnVisibility?.get(),e.options.groupedColumnMode]},table_getFooterGroups:{fn:()=>Wde(e),memoDeps:()=>[e.getHeaderGroups()]},table_getFlatHeaders:{fn:()=>Gde(e),memoDeps:()=>[e.getHeaderGroups()]},table_getLeafHeaders:{fn:()=>Kde(e),memoDeps:()=>[e.getHeaderGroups()]}})}};function Jde(e){if(!e._rowPrototype){e._rowPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignRowPrototype?.(e._rowPrototype,e)}return e._rowPrototype}var Yde=(e,t,n,r,i,a,o)=>{let s=Jde(e),c=Object.create(s);c._displayIndexCache=-1,c._uniqueValuesCache=c3(),c._valuesCache=c3(),c.depth=i,c.id=t,c.index=r,c.original=n,c.parentId=o,c.subRows=a??[];let l=e._rowInstanceInitFns;for(let e=0;e<l.length;e++)l[e](c);return c},Xde=/([0-9]+)/gm;function k3(e){let t=Object.assign((e,n,r)=>{let i=e.getValue(r),a=n.getValue(r),o=t.resolveDataValue;return o&&(i=o(i),a=o(a)),t.sort(i,a,e,n,r)},e);return t}k3({resolveDataValue:e=>M3(e).toLowerCase(),sort:(e,t)=>N3(e,t)}),k3({resolveDataValue:e=>M3(e),sort:(e,t)=>N3(e,t)}),k3({resolveDataValue:e=>M3(e).toLowerCase(),sort:(e,t)=>j3(e,t)}),k3({resolveDataValue:e=>M3(e),sort:(e,t)=>j3(e,t)}),k3({resolveDataValue:e=>Zde(e),sort:(e,t)=>e>t?1:e<t?-1:0});var A3=k3({sort:(e,t)=>j3(e,t)});function j3(e,t){return e===t?0:e>t?1:-1}function Zde(e){return e instanceof Date?e.getTime():e}function M3(e){return typeof e==`number`?isNaN(e)||e===1/0||e===-1/0?``:String(e):typeof e==`string`?e:``}function N3(e,t){let n=0,r=0,i=e.length,a=t.length;for(;n<i&&r<a;){let i=P3(e.charCodeAt(n)),a=P3(t.charCodeAt(r)),o=F3(e,n,i),s=F3(t,r,a);if(!i&&!a){let i=Qde(e,n,o,t,r,s);if(i)return i;n=o,r=s;continue}if(i!==a)return i?1:-1;let c=$de(e,n,o,t,r,s);if(c)return c;n=o,r=s}return L3(e,n)-L3(t,r)}function P3(e){return e>=48&&e<=57}function F3(e,t,n){let r=t+1;for(;r<e.length&&P3(e.charCodeAt(r))===n;)r++;return r}function Qde(e,t,n,r,i,a){let o=n-t,s=a-i,c=o<s?o:s;for(let n=0;n<c;n++){let a=e.charCodeAt(t+n),o=r.charCodeAt(i+n);if(a>o)return 1;if(o>a)return-1}return o>s?1:s>o?-1:0}function $de(e,t,n,r,i,a){let o=t;for(;o<n&&e.charCodeAt(o)===48;)o++;let s=i;for(;s<a&&r.charCodeAt(s)===48;)s++;let c=n-o,l=a-s;if(c===0&&l===0)return 0;if(c<=15&&l<=15){let t=I3(e,o,n),i=I3(r,s,a);return t>i?1:i>t?-1:0}let u=parseInt(e.slice(t,n),10),d=parseInt(r.slice(i,a),10);return u>d?1:d>u?-1:0}function I3(e,t,n){let r=0;for(let i=t;i<n;i++)r=r*10+e.charCodeAt(i)-48;return r}function L3(e,t){let n=0,r=t;for(;r<e.length;)n++,r=F3(e,r,P3(e.charCodeAt(r)));return n}function R3(){return[]}function efe(e,t){m3(e,`cellSelection`,t?R3():s3(e.initialState.cellSelection)??R3())}function tfe(e){e.atoms.cellSelection&&(e.options.autoResetAll??e.options.autoResetCellSelection??!0)&&e._reactivity.schedule(()=>efe(e))}function nfe(e){e.atoms.expanded&&(e.options.autoResetAll??e.options.autoResetExpanded??!e.options.manualExpanding)&&e._reactivity.schedule(()=>rfe(e))}function rfe(e,t){let n=e.initialState.expanded;m3(e,`expanded`,t?c3():n===!0||Object.assign(c3(),s3(n??{})))}var z3=0;function ife(e){if(e.options.autoResetAll??e.options.autoResetPageIndex??!e.options.manualPagination){if((e.atoms.pagination?.get()?.pageIndex??z3)===z3)return;sfe(e,!0)}}function afe(e,t){m3(e,`pagination`,t)}function ofe(e,t){afe(e,n=>{let r=o3(t,n.pageIndex),i=e.options.pageCount===void 0||e.options.pageCount===-1?2**53-1:e.options.pageCount-1;return r=Math.max(0,Math.min(r,i)),{...n,pageIndex:r}})}function sfe(e,t){ofe(e,t?z3:e.initialState.pagination?.pageIndex??z3)}function cfe(){return[]}function B3(e,t){m3(e,`sorting`,t)}function V3(e,t){B3(e,t?[]:s3(e.initialState.sorting??[]))}function lfe(e){e.atoms.sorting&&(e.options.autoResetAll??e.options.autoResetSorting??!1)&&V3(e)}function H3(e){let t=e.table._rowModelFns.sortFns,n=e.table.getFilteredRowModel().flatRows.slice(0,10),r,i=!1;for(let t=0;t<n.length;t++){let a=n[t].getValue(e.id);if(Object.prototype.toString.call(a)===`[object Date]`){r=`datetime`;break}if(typeof a==`string`&&(i=!0,a.split(Xde).length>1)){r=`alphanumeric`;break}}if(!r&&i&&(r=`text`),r){let e=t?.[r];if(e||r===`alphanumeric`&&(e=t?.text),e)return e}return A3}function U3(e){let t=e.table.getFilteredRowModel().flatRows.slice(0,10);for(let n=0;n<t.length;n++){let r=t[n].getValue(e.id);if(r!=null)return typeof r==`string`?`asc`:`desc`}return`desc`}function ufe(e){let t=e.table._rowModelFns.sortFns;return mde(e.columnDef.sortFn)?e.columnDef.sortFn:e.columnDef.sortFn===`auto`?H3(e):t?.[e.columnDef.sortFn]??A3}function W3(e,t,n){let r=K3(e,n&&J3(e)),i=t!==void 0;B3(e.table,a=>{let o=a.findIndex(t=>t.id===e.id),s=o===-1?void 0:a[o],c=[],l,u=i?t:r===`desc`,d=!!(a.length&&J3(e)&&n);return l=d?s?`toggle`:`add`:s?`toggle`:`replace`,l===`toggle`&&(i||r||(l=`remove`)),l===`add`?(c=[...a,{id:e.id,desc:u}],c.splice(0,c.length-(e.table.options.maxMultiSortColCount??2**53-1))):c=l===`toggle`?d?a.map(t=>t.id===e.id?{...t,desc:u}:t):[{id:e.id,desc:u}]:l===`remove`?d?a.filter(t=>t.id!==e.id):[]:[{id:e.id,desc:u}],c})}function G3(e){return e.columnDef.sortDescFirst??e.table.options.sortDescFirst??U3(e)===`desc`?`desc`:`asc`}function K3(e,t){let n=G3(e),r=Y3(e);return r?r!==n&&(e.table.options.enableSortingRemoval??!0)&&(!t||(e.table.options.enableMultiRemove??!0))?!1:r===`desc`?`asc`:`desc`:n}function q3(e){return(e.columnDef.enableSorting??!0)&&(e.table.options.enableSorting??!0)&&!!e.accessorFn}function J3(e){return e.columnDef.enableMultiSort??e.table.options.enableMultiSort??!!e.accessorFn}function Y3(e){let t=e.table.atoms.sorting?.get()?.find(t=>t.id===e.id);return t?t.desc?`desc`:`asc`:!1}function dfe(e){return e.table.atoms.sorting?.get()?.findIndex(t=>t.id===e.id)??-1}function ffe(e){B3(e.table,t=>t.length?t.filter(t=>t.id!==e.id):[])}function pfe(e){let t=q3(e);return n=>{t&&W3(e,void 0,J3(e)?e.table.options.isMultiSortEvent?.(n):!1)}}function mfe(){return e=>h3({feature:`coreRowModelsFeature`,table:e,fnName:`table.getCoreRowModel`,memoDeps:()=>[e.options.data],fn:()=>hfe(e,e.options.data),onAfterUpdate:_de(()=>{nfe(e),ife(e),lfe(e),tfe(e)})})}function X3(e,t,n,r=0,i){let a=[];for(let o=0;o<n.length;o++){let s=n[o],c=Yde(e,e.getRowId(s,o,i),s,o,r,void 0,i?.id);t.flatRows.push(c),t.rowsById[c.id]=c,a.push(c),e.options.getSubRows&&(c.originalSubRows=e.options.getSubRows(s,o),c.originalSubRows?.length&&(c.subRows=X3(e,t,c.originalSubRows,r+1,c)))}return a}function hfe(e,t){let n={rows:[],flatRows:[],rowsById:c3()};return n.rows=X3(e,n,t),n}function gfe(e){return e._rowModels.coreRowModel||(e._rowModels.coreRowModel=e.options.features.coreRowModel?.(e)??mfe()(e)),e._rowModels.coreRowModel()}function _fe(e){return e.getCoreRowModel()}function vfe(e){return e._rowModels.filteredRowModel||(e._rowModels.filteredRowModel=e.options.features.filteredRowModel?.(e)),e.options.manualFiltering||!e._rowModels.filteredRowModel?e.getPreFilteredRowModel():e._rowModels.filteredRowModel()}function yfe(e){return e.getFilteredRowModel()}function bfe(e){return e._rowModels.groupedRowModel||(e._rowModels.groupedRowModel=e.options.features.groupedRowModel?.(e)),e.options.manualGrouping||!e._rowModels.groupedRowModel?e.getPreGroupedRowModel():e._rowModels.groupedRowModel()}function xfe(e){return e.getGroupedRowModel()}function Sfe(e){return e._rowModels.sortedRowModel||(e._rowModels.sortedRowModel=e.options.features.sortedRowModel?.(e)),e.options.manualSorting||!e._rowModels.sortedRowModel?e.getPreSortedRowModel():e._rowModels.sortedRowModel()}function Cfe(e){return e.getSortedRowModel()}function wfe(e){return e._rowModels.expandedRowModel||(e._rowModels.expandedRowModel=e.options.features.expandedRowModel?.(e)),e.options.manualExpanding||!e._rowModels.expandedRowModel?e.getPreExpandedRowModel():e._rowModels.expandedRowModel()}function Tfe(e){return e.getExpandedRowModel()}function Efe(e){return e._rowModels.paginatedRowModel||(e._rowModels.paginatedRowModel=e.options.features.paginatedRowModel?.(e)),e.options.manualPagination||!e._rowModels.paginatedRowModel?e.getPrePaginatedRowModel():e._rowModels.paginatedRowModel()}function Dfe(e){return e.getPaginatedRowModel()}var Ofe={constructTableAPIs:e=>{_3(`coreRowModelsFeature`,e,{table_getCoreRowModel:{fn:()=>gfe(e)},table_getPreFilteredRowModel:{fn:()=>_fe(e)},table_getFilteredRowModel:{fn:()=>vfe(e)},table_getPreGroupedRowModel:{fn:()=>yfe(e)},table_getGroupedRowModel:{fn:()=>bfe(e)},table_getPreSortedRowModel:{fn:()=>xfe(e)},table_getSortedRowModel:{fn:()=>Sfe(e)},table_getPreExpandedRowModel:{fn:()=>Cfe(e)},table_getExpandedRowModel:{fn:()=>wfe(e)},table_getPrePaginatedRowModel:{fn:()=>Tfe(e)},table_getPaginatedRowModel:{fn:()=>Efe(e)},table_getRowModel:{fn:()=>Dfe(e)}})}};function kfe(e){if(!e._cellPrototype){e._cellPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignCellPrototype?.(e._cellPrototype,e)}return e._cellPrototype}function Afe(e,t,n){let r=kfe(n),i=Object.create(r);i.column=e,i.id=`${t.id}_${e.id}`,i.row=t;let a=n._cellInstanceInitFns;for(let e=0;e<a.length;e++)a[e](i);return i}function jfe(e){let t=e.table.getRowsInDisplayOrder(),n=e._displayIndexCache;return t[n]===e?n:-1}function Mfe(e){let t=e.getPrePaginatedRowModel().rows;if(e.options.paginateExpandedRows===!1){let e=[],n=t=>{t._displayIndexCache=e.length,e.push(t),t.subRows.length&&t.getIsExpanded?.()&&t.subRows.forEach(n)};return t.forEach(n),e}for(let e=0;e<t.length;e++)t[e]._displayIndexCache=e;return t}function Nfe(e,t){if(l3(e._valuesCache,t))return e._valuesCache[t];let n=e.table.getColumn(t);if(n?.accessorFn)return e._valuesCache[t]=n.accessorFn(e.original,e.index),e._valuesCache[t]}function Pfe(e,t){if(l3(e._uniqueValuesCache,t))return e._uniqueValuesCache[t];let n=e.table.getColumn(t);if(n?.accessorFn)return n.columnDef.getUniqueValues?(e._uniqueValuesCache[t]=n.columnDef.getUniqueValues(e.original,e.index),e._uniqueValuesCache[t]):(e._uniqueValuesCache[t]=[e.getValue(t)],e._uniqueValuesCache[t])}function Ffe(e,t){return e.getValue(t)??e.table.options.renderFallbackValue}function Ife(e){return hde(e.subRows,e=>e.subRows)}function Lfe(e){let t=e.getCoreRowModel().flatRows,n=0;for(let e=0;e<t.length;e++)n=Math.max(n,t[e].depth);return n}function Rfe(e){if(e.parentId)return e.table.getCoreRowModel().rowsById[e.parentId]??e.table.getRow(e.parentId,!0)}function zfe(e){let t=[],n=e;for(;;){let e=n.getParentRow();if(!e)break;t.push(e),n=e}return t.reverse()}function Bfe(e){let t=e.table.getAllLeafColumns(),n=e._cellsCache;n||=e._cellsCache=new WeakMap;let r=Array(t.length);for(let i=0;i<t.length;i++){let a=t[i],o=n.get(a);o||(o=Afe(a,e,e.table),n.set(a,o)),r[i]=o}return r}function Vfe(e){let t=c3(),n=e.getAllCells();for(let e=0;e<n.length;e++){let r=n[e];t[r.column.id]=r}return t}function Hfe(e,t,n,r){return t.options.getRowId?.(e,n,r)??(r?`${r.id}.${n}`:String(n))}function Ufe(e,t,n){let r=(n?e.getPrePaginatedRowModel():e.getRowModel()).rowsById[t];if(!r&&(r=e.getCoreRowModel().rowsById[t],!r))throw Error();return r}var Wfe={assignRowPrototype:(e,t)=>{v3(`coreRowsFeature`,e,t,{row_getDisplayIndex:{fn:e=>jfe(e)},row_getAllCellsByColumnId:{fn:e=>Vfe(e),memoDeps:e=>[e.getAllCells()]},row_getAllCells:{fn:e=>Bfe(e),memoDeps:e=>[e.table.getAllLeafColumns()]},row_getLeafRows:{fn:e=>Ife(e),memoDeps:e=>[e.subRows]},row_getParentRow:{fn:e=>Rfe(e)},row_getParentRows:{fn:e=>zfe(e)},row_getUniqueValues:{fn:(e,t)=>Pfe(e,t)},row_getValue:{fn:(e,t)=>Nfe(e,t)},row_renderValue:{fn:(e,t)=>Ffe(e,t)}})},constructTableAPIs:e=>{_3(`coreRowsFeature`,e,{table_getRowsInDisplayOrder:{fn:()=>Mfe(e),memoDeps:()=>[e.getPrePaginatedRowModel().rows,e.options.paginateExpandedRows,e.options.paginateExpandedRows===!1?e.atoms.expanded?.get():void 0]},table_getRowId:{fn:(t,n,r)=>Hfe(t,e,n,r)},table_getRow:{fn:(t,n)=>Ufe(e,t,n)},table_getMaxSubRowDepth:{fn:()=>Lfe(e),memoDeps:()=>[e.getCoreRowModel()]}})}};function Z3(e,t,n=(e,t)=>e===t){let r=t===void 0?e.options.state:t;e._reactivity.batch(()=>{if(r)for(let t in r){let i=e.baseAtoms[t];if(!i)continue;let a=r[t],o=a===void 0?e.initialState[t]:a;n(e._reactivity.untrack(()=>i.get()),o)||i.set(()=>o)}})}function Q3(e,t,n=(e,t)=>e===t){e._reactivity.batch(()=>{Z3(e,t,n),e._reactivity.commit?.()})}function Gfe(e){let t=s3(e.initialState);e._reactivity.batch(()=>{let n=Object.keys(t);for(let r=0;r<n.length;r++){let i=n[r];e.baseAtoms[i].set(t[i])}});let n=Object.values(e._features);for(let t=0;t<n.length;t++)n[t].resetTableInstanceData?.(e)}function Kfe(e,t){let{features:n,atoms:r,initialState:i}=e.options;if(!e.options.mergeOptions)return{...e.options,...t,features:n,atoms:r,initialState:i};let a=e.options.mergeOptions(e.options,t),o={...Object.getOwnPropertyDescriptors(a)};return Object.defineProperties(Object.create(Object.getPrototypeOf(a)),{...o,features:{value:n,enumerable:!0,configurable:!0,writable:!0},atoms:{value:r,enumerable:!0,configurable:!0,writable:!0},initialState:{value:i,enumerable:!0,configurable:!0,writable:!0}})}function $3(e,t,n){let r=Kfe(e,o3(t,e.options));e.optionsStore?e.optionsStore.set(()=>r):e.options=r,n?.syncExternalState!==!1&&Q3(e,r.state??null)}var qfe={coreCellsFeature:xde,coreColumnsFeature:Bde,coreHeadersFeature:qde,coreRowModelsFeature:Ofe,coreRowsFeature:Wfe,coreTablesFeature:{constructTableAPIs:e=>{_3(`coreTablesFeature`,e,{table_reset:{fn:()=>Gfe(e)},table_setOptions:{fn:t=>$3(e,t)}})}}};function Jfe(){return{accessor:(e,t)=>typeof e==`function`?{...t,accessorFn:e}:{...t,accessorKey:e},columns:e=>e,display:e=>e,group:e=>e}}function Yfe(e){return e}function Xfe(e,t={}){return Object.values(e).forEach(e=>{t=e.getInitialState?.(t)??t}),s3(t)}function Zfe(e){let t=e.features.coreReactivityFeature,{aggregationFns:n,columnMeta:r,coreRowModel:i,expandedRowModel:a,facetedMinMaxValues:o,facetedRowModel:s,facetedUniqueValues:c,filterFns:l,filterMeta:u,filteredRowModel:d,groupedRowModel:f,paginatedRowModel:p,sortFns:m,sortedRowModel:h,tableMeta:g,..._}=e.features,v={_cellInstanceInitFns:[],_columnInstanceInitFns:[],_features:{...qfe,..._},_headerGroupInstanceInitFns:[],_headerInstanceInitFns:[],_reactivity:t,_rowInstanceInitFns:[],_rowModelFns:{aggregationFns:n,filterFns:l,sortFns:m},_rowModels:{},atoms:{},baseAtoms:{}},y=Object.values(v._features),b={...y.reduce((e,t)=>Object.assign(e,t.getDefaultTableOptions?.(v)),{}),...e};if(t.wrapExternalAtoms&&b.atoms)for(let[e,n]of Object.entries(b.atoms)){let r=n,i=t.createWritableAtom(r.get(),{debugName:`externalAtom/${e}`});b.atoms[e]=i;let a=!1,o=r.subscribe(e=>{a||i.set(e)}),s=i.subscribe(e=>{a=!0,r.set(e),a=!1});t.addSubscription(o),t.addSubscription(s)}t.createOptionsStore?(v.optionsStore=t.createWritableAtom(b,{debugName:`table/optionsStore`}),Object.defineProperty(v,"options",{configurable:!0,enumerable:!0,get(){return v.optionsStore.get()},set(e){v.optionsStore.set(()=>e)}})):v.options=b,v.initialState=Xfe(v._features,v.options.initialState);let x=Object.keys(v.initialState);for(let e=0;e<x.length;e++){let n=x[e];v.baseAtoms[n]=t.createWritableAtom(v.initialState[n],{debugName:`table/baseAtoms/${n}`}),v.atoms[n]=t.createReadonlyAtom(()=>{let e=v.options,t=e.atoms?.[n],r=t?t.get():v.baseAtoms[n].get();if(t)return r;let i=e.state;if(i&&l3(i,n)){let e=i[n];return e===void 0?v.initialState[n]:e}return r},{debugName:`table/atoms/${n}`})}Z3(v),v.store=sde(t.createReadonlyAtom(()=>{let e={};for(let t=0;t<x.length;t++){let n=x[t];e[n]=v.atoms[n].get()}return e},{compare:r3,debugName:`table/store`}));for(let e=0;e<y.length;e++){let t=y[e];t.initTableInstanceData?.(v),t.initCellInstanceData&&v._cellInstanceInitFns.push(t.initCellInstanceData.bind(t)),t.initColumnInstanceData&&v._columnInstanceInitFns.push(t.initColumnInstanceData.bind(t)),t.initHeaderGroupInstanceData&&v._headerGroupInstanceInitFns.push(t.initHeaderGroupInstanceData.bind(t)),t.initHeaderInstanceData&&v._headerInstanceInitFns.push(t.initHeaderInstanceData.bind(t)),t.initRowInstanceData&&v._rowInstanceInitFns.push(t.initRowInstanceData.bind(t)),t.constructTableAPIs?.(v)}return v}function Qfe(){return c3()}function e6(e,t){e.options.onRowSelectionChange?.(t)}function $fe(e,t){e._lastSelectedRowId=null,e6(e,t?c3():Object.assign(c3(),s3(e.initialState.rowSelection??{})))}function t6(e,t,n){e._lastSelectedRowId=null,e6(e,r=>{if(t=t===void 0?!y3(e,`getIsAllRowsSelected`,i6):t,n?.deselectAll&&!t)return c3();let i=Object.assign(c3(),r),a=e.getPreGroupedRowModel().flatRows;if(t){let e=new Map;a.forEach(t=>{m6(t,e)&&(i[t.id]=!0)})}else a.forEach(e=>{u6(e)&&delete i[e.id]});return i})}function n6(e,t,n){e._lastSelectedRowId=null,e6(e,r=>{let i=t===void 0?!y3(e,`getIsAllPageRowsSelected`,a6):t;if(n?.deselectAll&&!i)return c3();let a=Object.assign(c3(),r);return e.getRowModel().rows.forEach(t=>{p6(a,t.id,i,!0,e,!0)}),a})}function epe(e){return e.getCoreRowModel()}function tpe(e){let t=e.getCoreRowModel();return y3(e,`getIsSomeRowsSelected`,o6)?_6(t,e):{rows:[],flatRows:[],rowsById:c3()}}function npe(e){let t=e.getFilteredRowModel();return y3(e,`getIsSomeRowsSelected`,o6)?_6(t,e):{rows:[],flatRows:[],rowsById:c3()}}function rpe(e){let t=e.getSortedRowModel();return y3(e,`getIsSomeRowsSelected`,o6)?_6(t,e):{rows:[],flatRows:[],rowsById:c3()}}function r6(e){return Object.keys(e.atoms.rowSelection?.get()??{})}function i6(e){let t=e.getFilteredRowModel().flatRows,n=e.atoms.rowSelection?.get()??{},r=!!(t.length&&Object.keys(n).length);if(r){let e=new Map;t.some(t=>!v6(t,n)&&m6(t,e))&&(r=!1)}return r}function a6(e){let t=e.getPaginatedRowModel().flatRows,n=e.atoms.rowSelection?.get()??{},r=new Map,i=!1;for(let e=0;e<t.length;e++){let a=t[e];if(v6(a,n))!i&&m6(a,r)&&(i=!0);else if(m6(a,r))return!1}return i}function o6(e){return y3(e,`getSelectedRowIds`,r6).length>0}function ipe(e){return e.getPaginatedRowModel().flatRows.filter(e=>u6(e)).some(e=>c6(e)||y3(e,`getIsSomeSelected`,l6))}function ape(e){return t=>{t6(e,t.target.checked)}}function ope(e){return t=>{n6(e,t.target.checked)}}function s6(e,t,n){let r=c6(e);e6(e.table,i=>{t=t===void 0?!r:t;let a=Object.assign(c3(),i);return p6(a,e.id,t,(n?.selectChildren??!0)&&f6(e),e.table),!t&&n?.deselectParents&&h6(a,e),a})}function c6(e){return v6(e,e.table.atoms.rowSelection?.get()??{})}function l6(e){return y6(e)===`some`}function spe(e){return y6(e)===`all`}function u6(e){let t=e.table.options;return typeof t.enableRowSelection==`function`?t.enableRowSelection(e):t.enableRowSelection??!0}function d6(e){let t=e.table.options;return typeof t.enableSubRowSelection==`function`?t.enableSubRowSelection(e):t.enableSubRowSelection??!0}function f6(e){let t=e.table.options;return typeof t.enableMultiRowSelection==`function`?t.enableMultiRowSelection(e):t.enableMultiRowSelection??!0}function cpe(e,t){let n=u6(e);return r=>{if(!n)return;let i=r,a=e.table,o=i.target.checked,s=a._lastSelectedRowId;(!(a.options.enableRowRangeSelection!==!1&&s!==null&&f6(e)&&(a.options.isRowRangeSelectionEvent?.(r)??!1))||!lpe(e,s,o,t))&&s6(e,o,t),a._lastSelectedRowId=e.id}}function lpe(e,t,n,r){let i=r?.selectChildren??!0,a=e.table,o=a.getRowsInDisplayOrder(),s=a.getPrePaginatedRowModel().rowsById[t]??a.getCoreRowModel().rowsById[t];if(!s)return!1;let c=s.getDisplayIndex(),l=e.getDisplayIndex(),u=o[c],d=o[l];if(c<0||l<0||c>=o.length||l>=o.length||u?.id!==s.id||d?.id!==e.id||!f6(s)||!f6(e))return!1;let f=Math.min(c,l),p=Math.max(c,l);return e6(a,e=>{let t=Object.assign(c3(),e);for(let e=f;e<=p;e++){let s=o[e];u6(s)&&f6(s)&&(p6(t,s.id,n,i,a),!n&&r?.deselectParents&&h6(t,s))}return t}),!0}function p6(e,t,n,r,i,a){let o=i.getRow(t,!0);n?(f6(o)||Object.keys(e).forEach(t=>delete e[t]),u6(o)&&(e[t]=!0)):(!a||u6(o))&&delete e[t],r&&o.subRows.length&&d6(o)&&o.subRows.forEach(t=>p6(e,t.id,n,r,i,a))}function m6(e,t){if(!u6(e))return!1;let n=e.table;if(n.options.enableSubRowSelection===!0)return!0;let r=e.parentId;if(r===void 0)return!0;let i=t.get(r);if(i!==void 0)return i;let a=n.getCoreRowModel().rowsById,o=[],s=!0,c=r;for(;c!==void 0;){let e=t.get(c);if(e!==void 0){s=e;break}o.push(c);let r=a[c]??n.getRow(c,!0);if(!d6(r)){s=!1;break}c=r.parentId}return o.forEach(e=>t.set(e,s)),s}function h6(e,t){let n=t.table.getCoreRowModel().rowsById,r=t.parentId;for(;r!==void 0;)delete e[r],r=(n[r]??t.table.getRow(r,!0)).parentId}function g6(e,t,n,r){let i=[];for(let a=0;a<e.length;a++){let o=e[a],s=v6(o,t);if(s&&(n.push(o),r[o.id]=o),o.subRows.length){let e=g6(o.subRows,t,n,r);if(s){let t=Object.create(Object.getPrototypeOf(o));dde(t,o),t.subRows=e,i.push(t)}}else s&&i.push(o)}return i}function _6(e,t){let n=[],r=c3(),i=t.atoms.rowSelection?.get()??{};return{rows:g6(e.rows,i,n,r),flatRows:n,rowsById:r}}function v6(e,t){return!!(l3(t,e.id)&&t[e.id])}function y6(e){if(!e.subRows.length)return!1;let t=e.table.atoms.rowSelection?.get()??{},n=!1,r=!0,i=!1;for(let a=0;a<e.subRows.length;a++){let o=e.subRows[a];if(n&&!r)break;if(u6(o)&&(i=!0,v6(o,t)?n=!0:r=!1),o.subRows.length){let e=y6(o);e===`all`?(n=!0,i=!0):e===`some`?(n=!0,r=!1,i=!0):r=!1}}return i?r?`all`:n?`some`:!1:!1}var upe={initTableInstanceData:e=>{e._lastSelectedRowId=null},resetTableInstanceData:e=>{e._lastSelectedRowId=null},getInitialState:e=>({rowSelection:Qfe(),...e}),getDefaultTableOptions:e=>({onRowSelectionChange:u3(`rowSelection`,e),enableRowSelection:!0,enableMultiRowSelection:!0,enableRowRangeSelection:!0,enableSubRowSelection:!0,isRowRangeSelectionEvent:e=>{let t=e;return!!(t.shiftKey||t.nativeEvent?.shiftKey)}}),assignRowPrototype:(e,t)=>{v3(`rowSelectionFeature`,e,t,{row_toggleSelected:{fn:(e,t,n)=>s6(e,t,n)},row_getIsSelected:{fn:e=>c6(e)},row_getIsSomeSelected:{fn:e=>l6(e),memoDeps:e=>[e.subRows,e.table.atoms.rowSelection?.get(),e.table.options.enableRowSelection]},row_getIsAllSubRowsSelected:{fn:e=>spe(e),memoDeps:e=>[e.subRows,e.table.atoms.rowSelection?.get(),e.table.options.enableRowSelection]},row_getCanSelect:{fn:e=>u6(e)},row_getCanSelectSubRows:{fn:e=>d6(e)},row_getCanMultiSelect:{fn:e=>f6(e)},row_getToggleSelectedHandler:{fn:(e,t)=>cpe(e,t)}})},constructTableAPIs:e=>{_3(`rowSelectionFeature`,e,{table_setRowSelection:{fn:t=>e6(e,t)},table_resetRowSelection:{fn:t=>$fe(e,t)},table_toggleAllRowsSelected:{fn:(t,n)=>t6(e,t,n)},table_toggleAllPageRowsSelected:{fn:(t,n)=>n6(e,t,n)},table_getPreSelectedRowModel:{fn:()=>epe(e)},table_getSelectedRowModel:{fn:()=>tpe(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getCoreRowModel()]},table_getFilteredSelectedRowModel:{fn:()=>npe(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getFilteredRowModel()]},table_getGroupedSelectedRowModel:{fn:()=>rpe(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getSortedRowModel()]},table_getSelectedRowIds:{fn:()=>r6(e),memoDeps:()=>[e.atoms.rowSelection?.get()]},table_getIsAllRowsSelected:{fn:()=>i6(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getFilteredRowModel(),e.options.enableRowSelection,e.options.enableSubRowSelection]},table_getIsAllPageRowsSelected:{fn:()=>a6(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getPaginatedRowModel(),e.options.enableRowSelection,e.options.enableSubRowSelection]},table_getIsSomeRowsSelected:{fn:()=>o6(e),memoDeps:()=>[e.atoms.rowSelection?.get()]},table_getIsSomePageRowsSelected:{fn:()=>ipe(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getPaginatedRowModel(),e.options.enableRowSelection]},table_getToggleAllRowsSelectedHandler:{fn:()=>ape(e)},table_getToggleAllPageRowsSelectedHandler:{fn:()=>ope(e)}})}},dpe={getInitialState(e){return{sorting:cfe(),...e}},getDefaultColumnDef(){return{sortFn:`auto`,sortUndefined:1}},getDefaultTableOptions(e){return{autoResetSorting:!1,onSortingChange:u3(`sorting`,e),isMultiSortEvent:e=>e.shiftKey}},assignColumnPrototype(e,t){v3(`rowSortingFeature`,e,t,{column_getAutoSortFn:{fn:e=>H3(e)},column_getAutoSortDir:{fn:e=>U3(e)},column_getSortFn:{fn:e=>ufe(e)},column_toggleSorting:{fn:(e,t,n)=>W3(e,t,n)},column_getFirstSortDir:{fn:e=>G3(e)},column_getNextSortingOrder:{fn:(e,t)=>K3(e,t)},column_getCanSort:{fn:e=>q3(e)},column_getCanMultiSort:{fn:e=>J3(e)},column_getIsSorted:{fn:e=>Y3(e)},column_getSortIndex:{fn:e=>dfe(e)},column_clearSorting:{fn:e=>ffe(e)},column_getToggleSortingHandler:{fn:e=>pfe(e)}})},constructTableAPIs(e){_3(`rowSortingFeature`,e,{table_setSorting:{fn:t=>B3(e,t)},table_resetSorting:{fn:t=>V3(e,t)}})}},fpe=typeof window>`u`?o.useEffect:o.useLayoutEffect;function ppe(e,t){let[{table:n,rootSource:r}]=(0,o.useState)(()=>{let t=Zfe({...e,features:{coreReactivityFeature:ude(),...e.features}});return t.Subscribe=(e=>ode({...e,source:e.source??t.store})),t.FlexRender=Zue,{table:t,rootSource:lde(t.store,r3)}}),i=n;$3(i,t=>({...t,...e}),{syncExternalState:!1});let a=i.options.state,s=r.get(),c=a3(r,t,{compare:r3});return fpe(()=>{r.markCommitted(s),Q3(i,a??null,r3)}),(0,o.useMemo)(()=>({...n,options:e,state:c}),[n,e,c])}var mpe=e=>t=>{let n=t.currentTarget;n.scrollWidth>Math.ceil(n.getBoundingClientRect().width)?n.title=e:n.removeAttribute(`title`)},b6=({text:e,className:t})=>(0,H.jsx)(`span`,{className:V(`truncate`,t),onMouseEnter:mpe(e),children:e}),x6=e=>(0,H.jsx)(`span`,{className:`text-faint-foreground`,children:e}),S6=(e,t)=>{if(t==null)return x6(`—`);let n=vS(e,t)??``;switch(e.kind){case`text`:return(0,H.jsx)(b6,{text:n});case`id`:return(0,H.jsx)(b6,{text:n,className:`font-mono text-xs text-muted-foreground`});case`money`:return(0,H.jsx)(`span`,{className:`tabular-nums`,children:n});case`date`:return(0,H.jsx)(`span`,{className:`tabular-nums text-muted-foreground`,children:n});case`datetime`:return(0,H.jsx)(`span`,{className:`tabular-nums text-muted-foreground`,children:n});case`number`:return(0,H.jsx)(`span`,{className:`tabular-nums`,children:n});case`signed`:return(0,H.jsx)(`span`,{className:V(`tabular-nums`,Number(t)<0?`text-danger-text`:`text-success-text`),children:n});case`percent`:return Number(t)===0?x6(`—`):(0,H.jsx)(`span`,{className:`tabular-nums`,children:n});case`status`:return(0,H.jsx)(Xu,{tone:e.tones?.[String(t)]??`neutral`,color:j4(e.colors,t),shape:e.shape,children:n});case`relation`:return(0,H.jsx)(b6,{text:n,className:`font-medium text-primary-text hover:underline`});case`boolean`:return t?(0,H.jsx)(`span`,{className:`inline-flex size-4 items-center justify-center rounded-full bg-success-soft text-success-text`,children:(0,H.jsx)(he,{className:`size-3`,strokeWidth:3})}):x6(`No`);case`file`:{let e=Nx(t);if(!e)return x6(`—`);if(`missing`in e)return(0,H.jsx)(b6,{text:e.name,className:`text-danger-text`});let n=Vx(t,{width:20,height:20});return(0,H.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[n?(0,H.jsx)($C,{image:n,className:`size-5 shrink-0 rounded-sm object-cover`}):(0,H.jsx)(Qt,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,H.jsx)(b6,{text:e.name})]})}case`user`:{let e=tx(String(t));return(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-2 truncate`,children:[(0,H.jsx)(Vu,{initials:e.initials,hue:e.hue,size:`xs`,className:`ring-0`}),(0,H.jsx)(b6,{text:e.name,className:`text-muted-foreground`})]})}}},hpe=Yfe({rowSortingFeature:dpe,rowSelectionFeature:upe}),C6=Jfe(),gpe=e=>C6.columns(e.map(e=>C6.accessor(t=>e.value?e.value(t):t[e.id],{id:e.id,header:e.header,enableSorting:e.sortable??!1,cell:t=>e.render?e.render(t.row.original):S6(e,t.getValue())}))),_pe=({total:e,selectedCount:t,bulkActions:n=[],className:r})=>(0,H.jsx)(`div`,{className:V(`flex h-9 shrink-0 items-center border-t bg-surface px-3 text-xs text-muted-foreground`,r),children:(0,H.jsxs)(`span`,{className:`flex items-center tabular-nums`,children:[cf(e),t>0&&(0,H.jsxs)(`span`,{className:`ml-3 font-medium text-primary-text`,children:[af(t),` selected`]}),t>0&&n.map(e=>(0,H.jsx)(`button`,{type:`button`,onClick:e.onRun,className:V(`ml-3 rounded border bg-background px-2 py-0.5 font-medium hover:bg-muted`,e.destructive?`border-danger/40 text-danger-text`:`text-foreground`),children:e.label},e.label))]})}),vpe=(e,t)=>e.filter(e=>e.available?.(t)??!0),w6=4,ype=(e,t)=>{let n=e.bottom+w6;return{top:n+t>window.innerHeight-w6?Math.max(w6,e.top-w6-t):n,right:window.innerWidth-e.right}},bpe=({row:e,actions:t})=>{let[n,r]=(0,o.useState)(!1),[i,a]=(0,o.useState)(),s=(0,o.useRef)(null),c=(0,o.useRef)(null);return(0,o.useLayoutEffect)(()=>{if(!n||!s.current||!c.current){a(void 0);return}a(ype(s.current.getBoundingClientRect(),c.current.offsetHeight))},[n]),(0,o.useEffect)(()=>{if(!n)return;let e=e=>s.current?.contains(e)||c.current?.contains(e),t=t=>{(t instanceof KeyboardEvent?t.key===`Escape`:!e(t.target))&&r(!1)},i=()=>r(!1);return document.addEventListener(`mousedown`,t),document.addEventListener(`keydown`,t),document.addEventListener(`scroll`,i,!0),window.addEventListener(`resize`,i),()=>{document.removeEventListener(`mousedown`,t),document.removeEventListener(`keydown`,t),document.removeEventListener(`scroll`,i,!0),window.removeEventListener(`resize`,i)}},[n]),(0,H.jsxs)(`div`,{className:`relative flex justify-center bg-inherit`,onClick:e=>e.stopPropagation(),children:[(0,H.jsx)(`button`,{ref:s,type:`button`,"aria-label":`Row actions`,"aria-haspopup":`menu`,"aria-expanded":n,onClick:()=>r(!n),className:`inline-flex items-center justify-center rounded p-1 text-faint-foreground hover:bg-muted hover:text-foreground pointer-coarse:size-11`,children:(0,H.jsx)(Ke,{className:`size-4`})}),n&&(0,tr.createPortal)((0,H.jsx)(`ul`,{ref:c,role:`menu`,onClick:e=>e.stopPropagation(),style:i??{visibility:`hidden`},className:`fixed z-50 min-w-36 rounded-md border bg-background py-1 shadow-pop`,children:t.map(t=>(0,H.jsx)(`li`,{role:`none`,children:(0,H.jsx)(`button`,{type:`button`,role:`menuitem`,className:V(`block w-full px-3 py-1.5 text-left hover:bg-muted`,t.destructive&&`text-danger-text`),onClick:()=>{r(!1),t.onSelect(e)},children:t.label})},t.label))}),document.body)]})},xpe=e=>52+Math.ceil(String(e).length*1.33)*7,T6=.6,E6=(e,t)=>Math.max(e.minWidth??0,e.width*t),Spe=(e,t)=>e.fixed?`${Math.max(e.minWidth??0,e.width)}px`:`minmax(${E6(e,t)}px, ${e.width}fr)`,D6=(e,t,n=0,r=T6)=>`${t}px ${e.map(e=>Spe(e,r)).join(` `)}${n>0?` ${n}px`:``}`,Cpe=(e,t,n=0,r=T6)=>t+n+e.reduce((e,t)=>e+(t.fixed?Math.max(t.minWidth??0,t.width):E6(t,r)),0),wpe=()=>{let e=(0,o.useRef)(null),t=(0,o.useRef)(null),[n,r]=(0,o.useState)({scrolled:!1,more:!1}),i=(0,o.useCallback)(()=>{let t=e.current;if(!t)return;let n={scrolled:t.scrollLeft>1,more:t.scrollLeft+t.clientWidth<t.scrollWidth-1};r(e=>e.scrolled===n.scrolled&&e.more===n.more?e:n)},[]);return{ref:e,attach:(0,o.useCallback)(n=>{if(t.current?.disconnect(),t.current=null,e.current=n,!n)return;let r=new ResizeObserver(i);r.observe(n);for(let e of Array.from(n.children))r.observe(e);t.current=r,i()},[i]),onScroll:i,...n}},Tpe=`protobase:pinned:`,Epe=(e,t)=>`${Tpe}${e}:${t}`,Dpe=(e,t)=>id(()=>{let n=e.getItem(t);if(n===null)return;let r=JSON.parse(n);return Array.isArray(r)&&r.every(e=>typeof e==`string`)?r:void 0},void 0),Ope=(e,t,n)=>id(()=>e.setItem(t,JSON.stringify(n)),void 0),kpe=(e,t=[])=>{let[n,r]=(0,o.useState)(()=>e?Dpe(localStorage,e):void 0),i=(0,o.useCallback)(t=>{r(t),e&&Ope(localStorage,e,t)},[e]);return[n??t,i]},Ape=e=>{let t=e.findIndex(e=>e.title);return t<0||t>1?[]:e.slice(0,t+1).map(e=>e.id)},jpe=e=>Object.fromEntries(e.map(({id:e,width:t,minWidth:n,fixed:r})=>[e,{width:t,minWidth:n,fixed:r}])),Mpe=(e,t)=>{let n=e.map(e=>e.id).sort().join(` `),[r,i]=(0,o.useState)(),a=r?.key===n?r:void 0;!a&&t.length>0&&i({key:n,sizes:jpe(FS(e,t))});let s=a?.sizes;return(0,o.useMemo)(()=>s?e.map(e=>({...e,...s[e.id]})):e,[e,s])},O6=e=>e===`money`||e===`number`||e===`signed`||e===`percent`,Npe=({header:e,pinned:t,onTogglePin:n})=>{let[r,i]=(0,o.useState)(!1),a=(0,o.useRef)(null);return(0,o.useEffect)(()=>{if(!r)return;let e=e=>{(e instanceof KeyboardEvent?e.key===`Escape`:!a.current?.contains(e.target))&&i(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,e)}},[r]),(0,H.jsxs)(`div`,{ref:a,className:`relative ml-auto shrink-0`,children:[(0,H.jsx)(`button`,{type:`button`,"aria-label":`${e} column menu`,"aria-haspopup":`menu`,"aria-expanded":r,onClick:()=>i(!r),className:`relative inline-flex size-5 items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground focus-visible:opacity-100 after:absolute after:-inset-2 after:content-[''] md:opacity-0 md:group-hover/cell:opacity-100 aria-expanded:opacity-100`,children:(0,H.jsx)(Ke,{className:`size-3.5`})}),r&&(0,H.jsx)(`ul`,{role:`menu`,className:`absolute right-0 top-full z-30 mt-1 min-w-32 rounded-md border bg-background py-1 text-body font-normal text-foreground shadow-pop`,children:(0,H.jsx)(`li`,{role:`none`,children:(0,H.jsx)(`button`,{type:`button`,role:`menuitem`,className:`block min-h-9 w-full whitespace-nowrap px-3 py-1.5 text-left hover:bg-muted`,onClick:()=>{i(!1),n()},children:t?`Unpin`:`Pin to left`})})})]})},Ppe=({sorted:e})=>e===`asc`?(0,H.jsx)(A,{className:`size-3 text-foreground`}):e===`desc`?(0,H.jsx)(S,{className:`size-3 text-foreground`}):(0,H.jsx)(Ce,{className:`size-3 opacity-0 group-hover/head:opacity-100`}),Fpe=({cells:e,specs:t,gutter:n,selectedCount:r,selectable:i,trailing:a,minScale:o,pins:s={},lastPinned:c,scrolled:l,onTogglePin:u,onClearSelection:d})=>(0,H.jsxs)(`div`,{className:`grid h-8 shrink-0 items-center border-b bg-surface text-xs font-medium text-muted-foreground`,style:{gridTemplateColumns:D6(t,n,a,o)},role:`row`,children:[(0,H.jsxs)(`div`,{className:V(`sticky left-0 z-10 flex h-full items-center gap-2 bg-inherit pl-3`,l&&!c&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),style:{width:n},children:[i&&(0,H.jsx)(Rh,{checked:!1,indeterminate:r>0,label:r>0?`Clear selection`:`No rows selected`,disabled:r===0,onChange:d,className:V(r===0&&`opacity-60`)}),n>40&&(0,H.jsx)(`span`,{className:`w-6 text-right text-faint-foreground`,children:`#`})]}),e.map(({spec:e,sorted:t,onSort:n})=>{let r=e.id in s;return(0,H.jsxs)(`div`,{"data-col-id":e.id,style:r?{left:s[e.id]}:void 0,className:V(`group/cell flex h-full min-w-0 items-center`,r&&`sticky z-10 bg-inherit`,r&&l&&e.id===c&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`,e.highlight&&`bg-primary-soft text-primary-text`),children:[(0,H.jsxs)(`button`,{type:`button`,onClick:n,disabled:!e.sortable,className:V(`group/head flex h-full min-w-0 flex-1 items-center gap-1 pl-3 pr-1 text-left`,O6(e.kind)&&`justify-end`,e.sortable&&`hover:text-foreground`,t&&`text-foreground`),children:[(0,H.jsx)(`span`,{className:`truncate`,children:e.header}),e.highlight&&(0,H.jsx)(`span`,{className:`rounded bg-primary px-1 text-[10px] font-semibold uppercase leading-4 text-primary-foreground`,children:`New`}),e.sortable&&(0,H.jsx)(Ppe,{sorted:t})]}),(0,H.jsx)(`div`,{className:`pr-1.5`,children:(0,H.jsx)(Npe,{header:e.header,pinned:r,onTogglePin:()=>u(e.id)})})]},e.id)}),a?(0,H.jsx)(`div`,{className:`sticky right-0 z-10 h-full bg-inherit`}):null]}),k6=e=>({gridTemplateColumns:D6(e.specs,e.gutter,e.trailing,e.minScale),height:e.height,transform:`translateY(${e.offset}px)`}),A6=(e,t)=>V(`flex h-full min-w-0 items-center overflow-hidden whitespace-nowrap px-3`,O6(e.kind)&&`justify-end`,e.highlight&&`bg-primary-soft/60`,t.pins&&e.id in t.pins&&`sticky z-10 bg-inherit`,t.scrolled&&e.id===t.lastPinned&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),j6=(e,t)=>t&&e.id in t?{left:t[e.id]}:void 0,M6=({width:e,index:t,selectable:n,selected:r,onToggle:i,edge:a})=>(0,H.jsxs)(`div`,{onClick:n?e=>{e.stopPropagation(),i?.()}:void 0,className:V(`sticky left-0 z-10 flex h-full items-center gap-2 bg-inherit pl-3`,n&&`cursor-default`,a&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),style:{width:e},children:[n&&(0,H.jsx)(Rh,{checked:!!r,label:`Select row ${t+1}`}),e>40&&(0,H.jsx)(`span`,{className:`min-w-6 text-right text-[11px] tabular-nums text-faint-foreground`,children:af(t+1)})]}),Ipe=(e,t,n)=>({gridTemplateColumns:D6(e.specs,e.gutter,e.trailing,e.minScale),height:e.height,top:e.offset,transform:t===0?void 0:`translateY(${t}px)`,transition:n}),Lpe=e=>t=>{t.target.closest(`a`)||e()},N6=({cells:e,selected:t,onToggle:n,onOpen:r,menu:i,handle:a,rowRef:o,dragY:s,transition:c,dragging:l,...u})=>(0,H.jsxs)(`div`,{ref:o,role:`row`,onClick:r&&Lpe(r),className:V(`absolute inset-x-0 top-0 grid items-center border-b`,t?`bg-primary-soft`:`bg-background hover:bg-surface`,r&&`cursor-pointer`,l&&`z-30 bg-surface shadow-pop`),style:s===void 0?k6(u):Ipe(u,s,c),children:[a?(0,H.jsx)(`div`,{className:V(`sticky left-0 z-10 flex h-full items-center bg-inherit pl-1.5`,u.scrolled&&!u.lastPinned&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),style:{width:u.gutter},children:a}):(0,H.jsx)(M6,{width:u.gutter,index:u.index,selectable:u.selectable,selected:t,onToggle:n,edge:u.scrolled&&!u.lastPinned}),e.map(({spec:e,content:t,props:n,chosen:r,editing:i,editable:a})=>(0,H.jsx)(`div`,{role:n?`gridcell`:`cell`,...n,className:V(A6(e,u),n&&`scroll-mb-[calc(var(--pb-sticky-bottom,0px)+3rem)] scroll-mt-[calc(var(--pb-sticky-top,0px)+2rem)] outline-none`,a&&!i&&`cursor-default`,r&&`shadow-[inset_0_0_0_2px_var(--primary)]`,i&&`z-30 overflow-visible bg-background px-1`),style:j6(e,u.pins),children:t},e.id)),i&&(0,H.jsx)(`div`,{className:`sticky right-0 z-10 flex h-full items-center justify-center bg-inherit`,children:i})]}),P6=[`w-3/4`,`w-1/2`,`w-2/3`,`w-5/6`,`w-2/5`],Rpe=e=>(0,H.jsxs)(`div`,{role:`row`,"aria-busy":!0,className:`absolute inset-x-0 top-0 grid items-center border-b bg-background`,style:k6(e),children:[(0,H.jsx)(M6,{width:e.gutter,index:e.index,selectable:!1,edge:e.scrolled&&!e.lastPinned}),e.specs.map((t,n)=>(0,H.jsx)(`div`,{className:A6(t,e),style:j6(t,e.pins),children:(0,H.jsx)(ku,{className:V(`h-2.5`,P6[(e.index+n)%P6.length],O6(t.kind)&&`ml-auto`)})},t.id))]}),zpe=(e,t)=>{let n=new Map;return{get:t=>n.get(Math.floor(t/e))?.[t%e],hasPage:e=>n.has(e),setPage:(e,r)=>{if(n.delete(e),n.set(e,r),n.size<=t)return;let i=n.keys().next();i.done||n.delete(i.value)},keepOnly:e=>{for(let t of[...n.keys()])e.includes(t)||n.delete(t)},get size(){return n.size}}},F6=(e,t,n)=>{let r=Math.floor(e/n),i=Math.floor(t/n);return Array.from({length:i-r+1},(e,t)=>r+t)},I6=(e,t)=>Math.max(0,Math.min(40,e-t*40)),L6=({total:e,rowAt:t,loadRows:n,revision:r,latencyMs:i},a,s)=>{let c=(0,o.useMemo)(()=>zpe(40,60),[t,n]),[l,u]=(0,o.useState)(0),d=Math.floor(a/40),f=Math.floor(s/40),p=!n&&i===0;(0,o.useEffect)(()=>{if(p)return;let r=F6(d*40,f*40,40).filter(e=>!c.hasPage(e)),a=t=>I6(e,t),o=(e,t)=>{c.setPage(e,t),u(e=>e+1)};if(n){let e=!1;for(let t of r)n(t*40,a(t)).then(n=>{e||o(t,n)});return()=>{e=!0}}let s=r.map(e=>setTimeout(()=>o(e,Array.from({length:a(e)},(n,r)=>t(e*40+r))),i));return()=>s.forEach(clearTimeout)},[c,d,f,i,e,t,n,p]);let m=(0,o.useRef)(r);return(0,o.useEffect)(()=>{if(!n||r===m.current)return;m.current=r;let t=F6(d*40,f*40,40);c.keepOnly(t);for(let r of t.filter(e=>c.hasPage(e)))n(r*40,I6(e,r)).then(e=>{c.setPage(r,e),u(e=>e+1)})},[c,r,n,d,f,e]),(0,o.useCallback)(e=>p?t(e):c.get(e),[c,p,t,l])},Bpe=1e7,R6=(e,t,n)=>{let r=e*t,i=Math.min(r,Bpe);return{rowHeight:t,trueHeight:r,contentHeight:i,scaled:r>i,maxTop:Math.max(0,r-n),maxScroll:Math.max(0,i-n)}},Vpe=(e,t)=>!e.scaled||t<=0?t:t>=e.maxScroll?e.maxTop+t-e.maxScroll:t/e.maxScroll*e.maxTop,z6=(e,t)=>!e.scaled||t<=0?t:t>=e.maxTop?e.maxScroll+t-e.maxTop:t/e.maxTop*e.maxScroll,Hpe=(e,t,n,r)=>{let i=t*e.rowHeight;return e.scaled?i-n+r:i},B6=(e,t,n,r,i)=>{let a=Math.min(e,Math.max(0,Math.floor(t/n)-i)),o=Math.min(e-1,Math.floor((t+r)/n)+i);return{first:a,last:Math.max(a-1,o)}},Upe=e=>{let t=document.scrollingElement??document.documentElement;for(let n=e.parentElement;n&&n!==t&&n!==document.body;n=n.parentElement)if(/auto|scroll/.test(getComputedStyle(n).overflowY))return n;return t},V6=e=>e===(document.scrollingElement??document.documentElement),Wpe=e=>V6(e)?window:e,H6=e=>Number.parseFloat(e)||0,Gpe=e=>{let t=getComputedStyle(e),n=V6(e)?{top:0,height:e.clientHeight}:{top:e.getBoundingClientRect().top+e.clientTop,height:e.clientHeight},r=H6(t.scrollPaddingTop);return{top:n.top+r,height:Math.max(0,n.height-r-H6(t.scrollPaddingBottom))}},U6=6,W6=(e,t,n)=>{let r=R6(t,n,e.height),i=Vpe(r,e.position);return{geometry:r,top:i,topIndex:Math.floor(Math.max(0,i)/n),...B6(t,i,n,e.height,U6)}},G6=({total:e,rowHeight:t,initialIndex:n,inset:r=0,settle:i,ready:a=!0})=>{let s=(0,o.useRef)(null),c=(0,o.useRef)(null),[l,u]=(0,o.useState)({position:0,height:0}),d=(0,o.useRef)({total:e,rowHeight:t,initialIndex:n,inset:r,ready:a});d.current={total:e,rowHeight:t,initialIndex:n,inset:r,ready:a};let f=(0,o.useCallback)(()=>{let e=s.current;if(!e||!c.current)return;let t=Gpe(c.current),n=d.current.inset;return{position:t.top+n-e.getBoundingClientRect().top,height:Math.max(0,t.height-n)}},[]),p=(0,o.useRef)(l);p.current=l;let m=(0,o.useCallback)(()=>{let e=f();if(!e)return;let t=p.current,{total:n,rowHeight:r}=d.current,i=W6(t,n,r),a=W6(e,n,r),o=!a.geometry.scaled&&i.first===a.first&&i.last===a.last&&i.topIndex===a.topIndex;(t.height!==e.height||t.position!==e.position&&!o)&&(p.current=e,u(e))},[f]),h=(0,o.useRef)({pending:!0,laidOut:!1}),g=(0,o.useCallback)(()=>{if(!h.current.pending||!h.current.laidOut||!d.current.ready)return;let e=f(),t=c.current;if(!e||!t)return;h.current.pending=!1;let{total:n,rowHeight:r,initialIndex:i}=d.current;i>0?t.scrollTop+=z6(R6(n,r,e.height),i*r)-e.position:e.position>0&&(t.scrollTop=0)},[f]);(0,o.useLayoutEffect)(()=>{let e=s.current;if(!e)return;let t=Upe(e);c.current=t;let n=Wpe(t);n.addEventListener(`scroll`,m,{passive:!0}),window.addEventListener(`resize`,m,{passive:!0});let r=new ResizeObserver(()=>{h.current.laidOut=!0,g(),m()});return r.observe(t),r.observe(e),m(),()=>{n.removeEventListener(`scroll`,m),window.removeEventListener(`resize`,m),r.disconnect(),c.current=null}},[m,g]),(0,o.useLayoutEffect)(()=>{g(),m()});let _=(0,o.useCallback)(e=>{let t=f();if(!t||!c.current)return;let n=R6(d.current.total,d.current.rowHeight,t.height);c.current.scrollTop+=z6(n,e)-t.position,m()},[f,m]),v=W6(l,e,t),y=i?i(v.top):v.top,{first:b,last:x}=i?B6(e,y,t,l.height,U6):v,S=Array.from({length:x-b+1},(e,t)=>({index:b+t,offset:Hpe(v.geometry,b+t,y,l.position)}));return{ref:s,height:l.height,top:y,geometry:v.geometry,rows:S,first:b,last:x,scrollTo:_}},Kpe=e=>e===`ArrowUp`||e===`ArrowDown`||e===`ArrowLeft`||e===`ArrowRight`,qpe=(e,t,n,r)=>{let i=n.indexOf(e.column);if(t===`ArrowUp`)return e.index>0?{...e,index:e.index-1}:void 0;if(t===`ArrowDown`)return e.index<r-1?{...e,index:e.index+1}:void 0;let a=n[t===`ArrowLeft`?i-1:i+1];return i>=0&&a!==void 0?{...e,column:a}:void 0},Jpe=(e,t,n,r)=>{let i=t.indexOf(e);return(r===1?t.slice(i+1):t.slice(0,Math.max(0,i)).reverse()).find(n)},K6=e=>`${e.index}:${e.column}`,Ype=({editor:e,columns:t,total:n,rowAt:r,onOpenRow:i,container:a})=>{let[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(!1),d=(0,o.useRef)(!1),f=(0,o.useRef)(!1);if((0,o.useEffect)(()=>{if(!s||l||!d.current)return;d.current=!1;let e=a.current?.querySelector(`[data-cell="${K6(s)}"]`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`nearest`,inline:`nearest`}))},[s,l,a]),!e)return;let p=t=>{let n=r(t.index);return n!==void 0&&e.editable(n,t.column)},m=(e,t=!1)=>{d.current=!0,c(e),u(t&&p(e))},h=n=>{if(!s)return;let i=r(s.index),o=n&&i?Jpe(s.column,t,t=>e.editable(i,t),n):void 0,c=!!a.current?.contains(document.activeElement);m(o?{...s,column:o}:s,o!==void 0),d.current=c};return{cell:(n,r,i,a)=>{let o={index:n,column:i},u=s?.index===n&&s.column===i,d=e.editable(r,i),p=u||!s&&n===0&&i===t[0];return{content:u&&l?e.render(r,i,h):a,chosen:u,editing:u&&l,editable:d,props:{"data-cell":K6(o),tabIndex:p?0:-1,"aria-selected":u,onMouseDown:()=>{f.current=u},onFocus:e=>{e.target===e.currentTarget&&!u&&c(o)},onClick:e=>{d&&(e.stopPropagation(),f.current&&!l&&m(o,!0))},onDoubleClick:e=>{d&&(e.stopPropagation(),u&&l||m(o,!0))}}}},onKeyDown:e=>{if(l||!s||!(e.target instanceof HTMLElement)||e.target.dataset.cell!==K6(s))return;let a=e.key===`Tab`?e.shiftKey?`ArrowLeft`:`ArrowRight`:e.key;if(Kpe(a)){let i=qpe(s,a,t,n);if(!i&&e.key===`Tab`)return;e.preventDefault(),i&&r(i.index)&&m(i);return}if(e.key===`Enter`||e.key===`F2`){e.preventDefault();let t=r(s.index);p(s)?m(s,!0):e.key===`Enter`&&t&&i?.(t);return}e.key===`Escape`&&c(void 0)}}},Xpe=`To move a row, press Space on its handle, move it with the up and down arrow keys, and press Space again to drop it there. Escape puts it back.`,Zpe=({ids:e,rowAt:t,reorder:n,children:r})=>{let i=nv(tv(uy,{activationConstraint:{distance:4}}),tv(fy,{activationConstraint:{delay:250,tolerance:5}}),tv(ny,{coordinateGetter:Jb})),a=t=>e.indexOf(String(t)),o=e=>{let r=t(a(e));return r?n.label(r):`row`};return(0,H.jsx)(ib,{sensors:i,collisionDetection:dv,onDragEnd:({active:e,over:t})=>{t&&e.id!==t.id&&n.onMove(a(e.id),a(t.id))},accessibility:{announcements:{onDragStart:({active:t})=>`Picked up ${o(t.id)}, row ${a(t.id)+1} of ${e.length}.`,onDragOver:({active:t,over:n})=>n?`${o(t.id)} is over row ${a(n.id)+1} of ${e.length}.`:void 0,onDragEnd:({active:t,over:n})=>n?`${o(t.id)} was dropped at row ${a(n.id)+1} of ${e.length}.`:`${o(t.id)} was put back.`,onDragCancel:({active:e})=>`Moving ${o(e.id)} was cancelled. It is back at row ${a(e.id)+1}.`},screenReaderInstructions:{draggable:Xpe}},children:(0,H.jsx)(Ib,{items:e,strategy:Mb,children:r})})},Qpe=({row:e,label:t,...n})=>{let{attributes:r,listeners:i,setNodeRef:a,setActivatorNodeRef:o,transform:s,transition:c,isDragging:l}=Wb({id:e.id}),u=(0,H.jsx)(`button`,{ref:o,type:`button`,"aria-label":`Move ${t}`,...r,...i,onClick:e=>e.stopPropagation(),style:{touchAction:`none`},className:`flex size-7 cursor-grab items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground focus-visible:text-foreground active:cursor-grabbing pointer-coarse:size-9`,children:(0,H.jsx)(ot,{className:`size-4`})});return(0,H.jsx)(N6,{...n,rowRef:a,handle:u,dragY:s?.y??0,transition:c,dragging:l})},q6=32,J6=({columns:e,source:t,naturalSort:n,initialScrollIndex:r=0,onScrollIndex:i,latencyMs:a=150,sort:s,onSortChange:c,onOpenRow:l,rowLink:u,rowActions:d,cellEditor:f,rowPatches:p,bulkActions:m,pinKey:h,defaultPinned:g,rowNumbers:_=!0,compact:v=!1,selectable:y=!0,reorder:b,fit:x=!1,scroll:S=`own`,className:C})=>{let w=y&&!b,T=v?28:36,E=!pu(),D=(g??(E?[]:Ape(e))).join(` `),[O,k]=kpe(h,(0,o.useMemo)(()=>D?D.split(` `):[],[D])),A=(0,o.useMemo)(()=>[...O.flatMap(t=>e.find(e=>e.id===t)??[]),...e.filter(e=>!O.includes(e.id))],[e,O]),j=A.slice(0,A.filter(e=>O.includes(e.id)).length).map(e=>e.id),{total:M}=t,[N,ee]=(0,o.useState)(n?[{id:n.columnId,desc:n.direction===`desc`}]:[]),P=s?[{id:s.columnId,desc:s.direction===`desc`}]:N,te=e=>{let t=typeof e==`function`?e(P):e,n=t[0];c&&n&&c({columnId:n.id,direction:n.desc?`desc`:`asc`}),s||ee(t)},[F,ne]=(0,o.useState)({}),re=(0,o.useMemo)(()=>gpe(A),[A]),ie=P[0],I=!!(!s&&n&&ie&&ie.id===n.columnId&&(ie.desc?`desc`:`asc`)!==n.direction),ae=t.rowAt,L=(0,o.useCallback)(e=>ae(I?M-1-e:e),[ae,I,M]),[oe]=(0,o.useState)(r),{ref:R,top:se,geometry:ce,rows:le,first:ue,last:de}=G6({total:M,rowHeight:T,initialIndex:oe,inset:q6}),fe=E||!_?40:xpe(M),pe=Math.floor(Math.max(0,se)/T);(0,o.useEffect)(()=>i?.(pe),[pe,i]);let me=L6({total:M,rowAt:ae?L:void 0,loadRows:t.loadRows,revision:t.revision,latencyMs:a},ue,de),he=(0,o.useCallback)(e=>{let t=me(e),n=t&&p?.get(t.id);return n?{...t,...n}:t},[me,p]),ge=le.map(({index:e,offset:t})=>({index:e,offset:t,row:he(e)})),_e=(0,o.useMemo)(()=>ge.flatMap(({row:e})=>e?[e]:[]),[he,ue,de]),ve=Mpe(A,_e),ye=ppe({features:hpe,columns:re,data:_e,state:{sorting:P,rowSelection:F},onSortingChange:te,onRowSelectionChange:ne,manualSorting:!0,enableMultiSort:!1,enableSortingRemoval:!1,getRowId:e=>e.id}),be=new Map(ye.getRowModel().rows.map(e=>[e.id,e])),xe=Object.keys(F).length,Se=(0,o.useRef)(new Map);for(let e of ye.getRowModel().rows)e.getIsSelected()&&Se.current.set(e.id,e.original);let Ce=d&&d.length>0?40:0,we=E?1:T6,Te=wpe(),Ee=(0,o.useRef)(null),De=()=>{Te.onScroll(),Ee.current&&Te.ref.current&&(Ee.current.scrollLeft=Te.ref.current.scrollLeft)},[Oe,ke]=(0,o.useState)({});(0,o.useLayoutEffect)(()=>{let e=Ee.current?.querySelector(`[role=row]`);if(!e)return;let t=fe,n={};for(let r of j)n[r]=t,t+=e.querySelector(`[data-col-id="${r}"]`)?.offsetWidth??0;JSON.stringify(Oe)!==JSON.stringify(n)&&ke(n)});let Ae=j.at(-1),je=e=>k(O.includes(e)?O.filter(t=>t!==e):[...O,e]),Me=ye.getHeaderGroups().flatMap(e=>e.headers.map(e=>({spec:A.find(t=>t.id===e.column.id),sorted:e.column.getIsSorted(),onSort:t=>e.column.getToggleSortingHandler()?.(t)}))),Ne=(0,o.useRef)(null),Pe=Ype({editor:f,columns:(0,o.useMemo)(()=>A.map(e=>e.id),[A]),total:M,rowAt:he,onOpenRow:l,container:Ne}),Fe=(A.find(e=>e.title)??A[0])?.id,Ie=Cpe(ve,fe,Ce,we),Le=S===`own`,Re=(0,H.jsx)(`div`,{ref:Ee,className:V(`sticky z-20 shrink-0 overflow-hidden`,Le?`top-0`:`top-[var(--pb-sticky-top,0px)]`),children:(0,H.jsx)(`div`,{style:{minWidth:Ie},children:(0,H.jsx)(Fpe,{cells:Me,specs:ve,gutter:fe,trailing:Ce,minScale:we,pins:Oe,lastPinned:Ae,scrolled:Te.scrolled,onTogglePin:je,selectable:w,selectedCount:xe,onClearSelection:()=>ne({})})})}),ze=ge.map(({index:e,offset:t,row:n})=>{let r={specs:ve,gutter:fe,index:e,offset:t,height:T,selectable:w,trailing:Ce,minScale:we,scrolled:Te.scrolled,pins:Oe,lastPinned:Ae},i=n?be.get(n.id):void 0;if(!i||!n)return(0,H.jsx)(Rpe,{...r},`skeleton-${e}`);let a=Ce?vpe(d,n):[],o={...r,selected:i.getIsSelected(),onToggle:()=>i.toggleSelected(),onOpen:l?()=>l(n):void 0,menu:a.length>0?(0,H.jsx)(bpe,{row:n,actions:a}):void 0,cells:i.getAllCells().map(t=>{let r=(0,H.jsx)(ye.FlexRender,{cell:t}),i=!!f?.editable(n,t.column.id),a=u&&t.column.id===Fe&&!i?(0,H.jsx)(Mu,{to:u(n),className:`flex min-w-0 items-center hover:underline`,children:r}):r;return{spec:A.find(e=>e.id===t.column.id),...Pe?Pe.cell(e,n,t.column.id,a):{content:a}}})};return b?(0,H.jsx)(Qpe,{...o,row:n,label:b.label(n)},n.id):(0,H.jsx)(N6,{...o},n.id)}),Be=(0,H.jsx)(`div`,{ref:Te.attach,onScroll:De,className:`overflow-x-auto overflow-y-hidden overscroll-x-contain [-webkit-overflow-scrolling:touch]`,children:(0,H.jsx)(`div`,{ref:R,className:`relative`,style:{minWidth:Ie,height:ce.contentHeight},children:b?(0,H.jsx)(Zpe,{ids:Array.from({length:M},(e,t)=>he(t)?.id??`missing-${t}`),rowAt:he,reorder:b,children:ze}):ze})});return(0,H.jsxs)(`div`,{ref:Ne,role:`grid`,"aria-rowcount":M,onKeyDown:Pe?.onKeyDown,className:V(`flex flex-col rounded-lg border bg-background`,Le?`min-h-0 overflow-hidden`:`overflow-clip`,C),style:x&&Le?{height:q6+M*T+2}:void 0,children:[(0,H.jsxs)(`div`,{className:V(`relative`,Le&&`flex min-h-0 flex-1 flex-col`),children:[Le?(0,H.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto overflow-x-hidden`,children:[Re,Be]}):(0,H.jsxs)(H.Fragment,{children:[Re,Be]}),Te.more&&(0,H.jsx)(`div`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-y-0 right-0 z-20 w-8 bg-gradient-to-l from-backdrop/15 to-transparent`})]}),!x&&(0,H.jsx)(_pe,{total:M,className:Le?void 0:`sticky bottom-[var(--pb-sticky-bottom,0px)] z-20`,selectedCount:xe,bulkActions:m?.map(e=>({label:e.label(xe),destructive:e.destructive,onRun:()=>{e.onRun(Object.keys(F).flatMap(e=>Se.current.get(e)??[])),ne({}),Se.current.clear()}}))})]})},$pe=500,Y6=async(e,t,n)=>{let r=[],i={},a;do{let o=await e.search(t,{...n,pageSize:$pe,...a&&{pageToken:a}});r.push(...o.items);for(let[e,t]of Object.entries(o.labels??{}))i[e]={...i[e],...t};a=o.nextPageToken||void 0}while(a);return{items:r,labels:i}},X6=uo(),Z6=(...e)=>{let t=e.filter(e=>!!e);return t.length===1?t[0]:t.map(e=>`(${e})`).join(` AND `)},Q6=e=>e==null?void 0:String(e),eme=(e,t,n)=>{let r=new Map;for(let[t,n]of e)r.set(n,(r.get(n)??new Set).add(t));let i=new Map;for(let e of t){let t=e[n],a=Q6(typeof t==`object`&&t&&`id`in t?t.id:t);for(let t of a===void 0?[]:r.get(a)??[])i.set(t,[...i.get(t)??[],e])}return i},tme=async(e,t,n,r)=>{let i=n.through;if(!i)return r.map(e=>[e,e]);let a=t[i.resource],o=i.key??a?.primaryKey[0];if(!a||o===void 0)throw Error(`The related column ${n.name} names a join resource the app does not have: ${i.resource}`);return(await Y6(e,a.name,{filter:Z6(Ya(X6.in(i.field,r)),i.filter),fields:[i.field,o]})).items.flatMap(e=>{let t=Q6(e[i.field]),n=Q6(e[o]);return t===void 0||n===void 0?[]:[[t,n]]})},nme=async({client:e,resources:t,views:n,load:r,owners:i})=>{let{column:a,fields:o}=r,s=t[a.resource];if(!s)throw Error(`The related column ${a.name} shows a resource the app does not have: ${a.resource}`);if(i.length===0)return new Map;let c=await tme(e,t,a,i),l=[...new Set(c.map(([,e])=>e))];if(l.length===0)return new Map;let u=[...new Set([...s.primaryKey,a.field,a.status,...o])],d=k4(t,n,s,u),f=await Y6(e,s.name,{filter:Z6(Ya(X6.in(a.field,l)),a.filter),...a.sort&&{orderBy:a.sort},fields:u,labels:d});return eme(c,A4(t,s,u,f.items,f.labels),a.field)},rme=5e3,ime=({queryClient:e,client:t,resources:n,views:r,model:i,columns:a,filter:o,orderBy:s,related:c=[]})=>{let l=c.map(e=>e.column.name).join(`,`),u=e=>c.length===0?G.page(i.name,o,s,40,e):[...G.page(i.name,o,s,40,e),l],d=k4(n,r,i,a),f=$S(r[i.name]),p=async e=>e.nextPageToken===``?e.items.length:e.totalSizeEstimate>rme?e.totalSizeEstimate:(await t.list(i.name,{filter:o,orderBy:s,pageSize:1,count:`exact`})).totalSize??e.totalSizeEstimate,m=async t=>{if(t===0)return``;let n=u(t-1),r=e.getQueryData(n);if(r)return r.nextPageToken;if(e.getQueryState(n)?.fetchStatus===`fetching`)return(await g(t-1)).nextPageToken},h=async e=>{let l=await m(e);if(e>0&&l===``)return{rows:[],total:0,nextPageToken:``};let u={filter:o,orderBy:s,pageSize:40,labels:d,photos:f},h=l===void 0?await t.seek(i.name,{...u,position:e*40}):await t.list(i.name,{...u,pageToken:l});if(h.items.length===0&&e>0)return{rows:[],total:0,nextPageToken:``};let g=h.items.map(e=>kg(i,e)),_=A4(n,i,a,eC(i,h.items,h.photos),h.labels),v=await Promise.all(c.map(e=>nme({client:t,resources:n,views:r,load:e,owners:g})));return{rows:_.map((e,t)=>({...e,...Object.fromEntries(c.map((e,n)=>[e.column.name,v[n].get(g[t])??[]])),id:g[t]})),total:e===0?await p(h):h.totalSizeEstimate,nextPageToken:h.nextPageToken}},g=t=>e.fetchQuery({queryKey:u(t),staleTime:6e4,queryFn:()=>h(t)});return{page:g,loadRows:async e=>(await g(Math.floor(e/40))).rows}},$6=({resources:e,views:t,model:n,columns:r,filter:i,orderBy:a,related:s})=>{let c=K(),l=Up(),u=r.join(`,`),d=JSON.stringify(s??[]),f=(0,o.useMemo)(()=>ime({queryClient:l,client:c,resources:e,views:t,model:n,columns:r,filter:i,orderBy:a,...s&&{related:s}}),[l,c,e,t,n,u,i,a,d]),p=_h({queryKey:[...G.first(n.name,i,a),u],queryFn:async()=>(await l.invalidateQueries({queryKey:G.pages(n.name,i,a),refetchType:`none`}),f.page(0))});return{source:(0,o.useMemo)(()=>p.data?{total:p.data.total,loadRows:f.loadRows,revision:p.dataUpdatedAt}:void 0,[p.data,p.dataUpdatedAt,f]),error:p.error,isLoading:p.isLoading,page:f.page,key:[...G.first(n.name,i,a),u]}},ame=`protobase:embedded-display:`,ome=e=>`${ame}${e}`,sme=(e,t)=>id(()=>e.getItem(t)??void 0,void 0),cme=(e,t,n)=>id(()=>e.setItem(t,n),void 0),lme=(e,t,{picked:n,preferred:r})=>{let i=hC(e).map(e=>e.name);return n!==void 0&&i.includes(n)?n:sC(e,t,r!==void 0&&i.includes(r)?r:void 0)},e8=(e,t,n,{resource:r=e.name,...i})=>NC({kind:`list`,resource:r},i,{...jC(e,t,n),display:sC(t,n)}),t8=`inline-flex h-6 items-center rounded-full border border-primary-border bg-primary-soft px-2.5 text-xs font-medium text-primary-text`,n8=({chips:e,className:t})=>(0,H.jsx)(`ul`,{className:V(`flex flex-wrap gap-1.5`,t),"aria-label":`Filters`,children:e.map(e=>(0,H.jsx)(`li`,{className:t8,children:e.label},e.key))}),r8=({chips:e})=>(0,H.jsx)(`span`,{className:`flex flex-wrap gap-1.5`,children:e.map((e,t)=>(0,H.jsxs)(`span`,{className:t8,children:[t>0&&(0,H.jsx)(`span`,{className:`sr-only`,children:`, `}),e.label]},e.key))}),ume=e=>e.map(e=>e.label).join(`, `),dme=`inline-flex h-6 items-center gap-1 rounded-full border border-primary-border bg-primary-soft pl-2.5 pr-1.5 text-xs font-medium text-primary-text`,i8=({chips:e,lockedLabels:t=[],onRemove:n,onClear:r,scroll:i})=>e.length===0&&t.length===0?null:(0,H.jsxs)(`div`,{className:i?`flex flex-nowrap items-center gap-1.5 overflow-x-auto pb-1 [&>*]:shrink-0`:`flex flex-wrap items-center gap-1.5`,children:[t.map(e=>(0,H.jsxs)(`span`,{className:`inline-flex h-6 items-center gap-1.5 rounded-full border border-border-strong bg-muted px-2.5 text-xs font-medium text-foreground`,children:[(0,H.jsx)(Nt,{className:`size-3 text-muted-foreground`}),e]},e)),e.map(e=>(0,H.jsxs)(`span`,{className:dme,children:[e.label,(0,H.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.label}`,onClick:()=>n(e.key),className:`rounded-full p-0.5 hover:bg-primary-border/60`,children:(0,H.jsx)(Qn,{className:`size-3`})})]},e.key)),e.length>0&&(0,H.jsx)(`button`,{type:`button`,onClick:r,className:`ml-1 text-xs font-medium text-muted-foreground hover:text-foreground`,children:`Clear all`})]}),fme=[`7d`,`30d`,`year`],a8={today:`Today`,yesterday:`Yesterday`,"7d":`Last 7 days`,"30d":`Last 30 days`,"90d":`Last 90 days`,month:`This month`,quarter:`This quarter`,year:`This year`},pme=({value:e,presets:t=fme,onChange:n})=>(0,H.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(t=>{let r=a8[t];return(0,H.jsx)(`button`,{type:`button`,disabled:!r,title:r?void 0:`The server offers the preset "${t}", which this UI does not know`,onClick:()=>n(e===t?void 0:t),className:V(`h-7 rounded-md border px-2.5 text-xs font-medium transition-colors`,!r&&`border-dashed text-danger-text`,e===t?`border-primary-border bg-primary-soft text-primary-text`:`border-border-strong bg-background text-muted-foreground hover:bg-muted`),children:r??`${t} (unsupported)`},t)})}),o8={facets:{},toggles:[]},s8=(e,t,n)=>{let r=e.facets[t]??[],i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,facets:{...e.facets,[t]:i}}},c8=(e,t)=>({...e,toggles:e.toggles.includes(t)?e.toggles.filter(e=>e!==t):[...e.toggles,t]}),l8=(e,t,n)=>{let{[t]:r,...i}=e.ranges??{};return{...e,ranges:n?{...i,[t]:n}:i}},u8=(e,t)=>e.options.find(e=>e.value===t)?.label??e.labels?.[t]??t,d8=(e,t)=>{let n=e.facets.flatMap(e=>(t.facets[e.id]??[]).map(t=>({key:`facet:${e.id}:${t}`,label:`${e.label}: ${u8(e,t)}`}))),r=(e.ranges??[]).flatMap(e=>{let n=t.ranges?.[e.id];return n?[{key:`range:${e.id}`,label:`${e.label}: ${e.format(n[0])} – ${e.format(n[1])}`}]:[]}),i=t.date?[{key:`date`,label:a8[t.date]??t.date}]:[],a=t.toggles.map(t=>({key:`toggle:${t}`,label:e.toggles?.find(e=>e.id===t)?.label??t}));return[...n,...r,...i,...a]},f8=(e,t)=>{if(t===`date`)return{...e,date:void 0};let[n,r,i]=t.split(`:`);if(n===`range`)return l8(e,r,void 0);if(n===`toggle`)return c8(e,r);if(n===`facet`)return s8(e,r,i);throw Error(`Unknown filter chip key: ${t}`)},p8=(e,t)=>e.toLowerCase().includes(t.trim().toLowerCase()),mme=(e,t)=>e.onSearch?e.options:e.options.filter(e=>p8(e.label,t)),hme=(e,t,n)=>t===0?-1:n===`ArrowDown`?e<0?0:(e+1)%t:e<0?t-1:(e-1+t)%t,gme=({config:e,selected:t,onToggle:n,inline:r=!1})=>{let i=(0,o.useId)(),a=(0,o.useRef)(null),[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(!1),[d,f]=(0,o.useState)(-1),p=r||l,m=mme(e,s),h=(0,o.useRef)(e.onSearch);h.current=e.onSearch,(0,o.useEffect)(()=>()=>h.current?.(``),[]);let g=t=>{c(t),f(-1),e.onSearch?.(t)};return(0,H.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,H.jsxs)(`div`,{className:`flex min-h-8 cursor-text flex-wrap items-center gap-1 rounded-md border border-border-strong bg-background px-2 py-1 shadow-sm focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20`,onClick:()=>a.current?.focus(),children:[(0,H.jsx)(fn,{className:`size-3.5 shrink-0 text-muted-foreground`}),t.map(t=>(0,H.jsxs)(`span`,{className:`inline-flex h-5 max-w-full items-center gap-0.5 rounded bg-primary-soft pl-1.5 pr-0.5 text-xs font-medium text-primary-text`,children:[(0,H.jsx)(`span`,{className:`truncate`,children:u8(e,t)}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Remove ${u8(e,t)}`,className:`rounded p-0.5 hover:bg-primary-border/60`,onMouseDown:e=>e.preventDefault(),onClick:()=>n(t),children:(0,H.jsx)(Qn,{className:`size-3`})})]},t)),(0,H.jsx)(`input`,{ref:a,autoFocus:r,role:`combobox`,"aria-label":e.label,"aria-expanded":p,"aria-controls":`${i}-options`,"aria-autocomplete":`list`,"aria-activedescendant":m[d]?`${i}-${d}`:void 0,placeholder:t.length>0?``:`Search ${e.label.toLowerCase()}`,className:`h-6 min-w-16 flex-1 bg-transparent text-foreground outline-none placeholder:text-faint-foreground`,value:s,onChange:e=>g(e.target.value),onKeyDown:e=>{if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),f(hme(d,m.length,e.key));return}if(e.key===`Enter`&&m[d]){e.preventDefault(),n(m[d].value);return}if(e.key===`Backspace`&&s===``&&t.length>0){n(t[t.length-1]);return}e.key===`Escape`&&s!==``&&(e.stopPropagation(),g(``))},onFocus:()=>u(!0),onBlur:()=>{u(!1),f(-1),!r&&s!==``&&g(``)}})]}),p&&(0,H.jsxs)(`ul`,{id:`${i}-options`,role:`listbox`,"aria-label":e.label,"aria-multiselectable":!0,className:V(`flex max-h-60 flex-col gap-px overflow-y-auto`,!r&&`rounded-md border bg-background p-1 shadow-sm`),children:[m.map((e,r)=>{let a=t.includes(e.value);return(0,H.jsxs)(`li`,{id:`${i}-${r}`,role:`option`,"aria-selected":a,tabIndex:-1,className:V(`flex cursor-pointer items-center gap-2 rounded px-1.5 py-1 hover:bg-muted`,r===d&&`bg-muted`),onMouseDown:e=>e.preventDefault(),onClick:()=>n(e.value),children:[(0,H.jsx)(`span`,{className:V(`inline-flex size-4 shrink-0 items-center justify-center rounded border`,a?`border-primary bg-primary text-primary-foreground`:`border-border-strong bg-background`),children:a&&(0,H.jsx)(he,{className:`size-3`,strokeWidth:3})}),(0,H.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.count!==void 0&&(0,H.jsx)(`span`,{className:`text-xs tabular-nums text-faint-foreground`,children:af(e.count)})]},e.value)}),m.length===0&&(0,H.jsx)(`li`,{className:`px-1.5 py-1 text-xs text-faint-foreground`,children:`No matches`})]})]})},_me=({config:e,selected:t,onToggle:n})=>{let[r,i]=(0,o.useState)(``),a=e.options.filter(e=>p8(e.label,r));return(0,H.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[e.searchable&&(0,H.jsx)(wd,{wrapperClassName:`mb-1 h-7`,leading:(0,H.jsx)(fn,{className:`size-3.5`}),placeholder:`Search ${e.label.toLowerCase()}`,value:r,onChange:e=>i(e.target.value)}),a.map(e=>(0,H.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded px-1 py-1 hover:bg-muted`,children:[(0,H.jsx)(Rh,{checked:t.includes(e.value),onChange:()=>n(e.value),label:e.label}),(0,H.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.count!==void 0&&(0,H.jsx)(`span`,{className:`text-xs tabular-nums text-faint-foreground`,children:af(e.count)})]},e.value)),a.length===0&&(0,H.jsx)(`span`,{className:`px-1 py-1 text-xs text-faint-foreground`,children:`No matches`})]})},m8=({label:e,activeCount:t,width:n=240,defaultOpen:r=!1,children:i})=>{let[a,s]=(0,o.useState)(r),[c,l]=(0,o.useState)(!1),u=(0,o.useRef)(null);return(0,o.useLayoutEffect)(()=>{a&&u.current&&l(u.current.getBoundingClientRect().left+n>document.documentElement.clientWidth)},[a,n]),(0,o.useEffect)(()=>{if(!a)return;let e=e=>{e.target instanceof Node&&!u.current?.contains(e.target)&&s(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[a]),(0,H.jsxs)(`div`,{ref:u,className:`relative`,children:[(0,H.jsxs)(`button`,{type:`button`,"aria-expanded":a,onClick:()=>s(!a),className:V(`inline-flex h-8 items-center gap-1.5 rounded-md border bg-background px-2.5 font-medium shadow-sm transition-colors hover:bg-muted`,t>0?`border-primary-border text-primary-text`:`border-border-strong text-foreground`),children:[e,t>0&&(0,H.jsx)(`span`,{className:`rounded-full bg-primary px-1.5 text-[11px] leading-4 text-primary-foreground`,children:t}),(0,H.jsx)(_e,{className:`size-3.5 text-muted-foreground`})]}),a&&(0,H.jsx)(`div`,{className:V(`absolute top-full z-30 mt-1.5 rounded-lg border bg-background p-3 shadow-pop`,c?`right-0`:`left-0`),style:{width:n},children:i})]})},h8=({title:e,children:t})=>(0,H.jsxs)(`section`,{className:`flex flex-col gap-2 border-b py-3 last:border-b-0`,children:[(0,H.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:e}),t]}),g8=(e,t)=>{let[n,r]=(0,o.useState)(e);return(0,o.useEffect)(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n},vme=(e,t,n,r,i)=>{let a=n+(r-n)*e/t;return n+(r-n)*(e+1)/t>i[0]&&a<i[1]},_8=(e,t,n)=>n===t?0:(e-t)/(n-t),yme=(e,t,n)=>t===0?[Math.min(n,e[1]),e[1]]:[e[0],Math.max(n,e[0])],bme=1e3,xme=({config:e,value:t,onChange:n})=>{let{min:r,max:i,step:a,histogram:s,format:c}=e,[l,u]=(0,o.useState)(),d=l??t??[r,i],f=Math.max(...s),p=()=>{l&&(u(void 0),n(l[0]===r&&l[1]===i?void 0:l))},m=g8(l,bme);return(0,o.useEffect)(()=>{m&&p()},[m]),(0,H.jsxs)(`div`,{className:`w-full`,children:[(0,H.jsxs)(`div`,{className:`px-[7px]`,children:[s.length>0&&(0,H.jsx)(`div`,{className:`mb-1 flex h-12 items-end gap-0.5`,children:s.map((e,t)=>(0,H.jsx)(`span`,{className:V(`flex-1 rounded-t-sm`,vme(t,s.length,r,i,d)?`bg-primary/70`:`bg-border`),style:{height:`${Math.max(6,e/f*100)}%`}},t))}),(0,H.jsxs)(`div`,{className:`relative h-4`,children:[(0,H.jsx)(`span`,{className:`absolute inset-x-0 top-1/2 h-1 -translate-y-1/2 rounded-full bg-border`}),(0,H.jsx)(`span`,{className:`absolute top-1/2 h-1 -translate-y-1/2 rounded-full bg-primary`,style:{left:`${_8(d[0],r,i)*100}%`,right:`${100-_8(d[1],r,i)*100}%`}})]})]}),(0,H.jsx)(`div`,{className:`relative -mt-4 h-4`,children:[0,1].map(t=>(0,H.jsx)(`input`,{type:`range`,className:`pb-range`,"aria-label":`${e.label} ${t===0?`minimum`:`maximum`}`,min:r,max:i,step:a,value:d[t],onChange:e=>u(yme(d,t,Number(e.target.value))),onPointerUp:p,onTouchEnd:p,onBlur:p},t))}),(0,H.jsxs)(`div`,{className:`mt-2 flex justify-between text-xs tabular-nums text-muted-foreground`,children:[(0,H.jsx)(`span`,{children:c(d[0])}),(0,H.jsx)(`span`,{children:c(d[1])})]})]})},v8=({label:e,checked:t,onChange:n})=>(0,H.jsxs)(`label`,{className:`flex cursor-pointer items-center justify-between gap-3 py-1`,children:[(0,H.jsx)(`span`,{children:e}),(0,H.jsx)(mS,{checked:t,onChange:n,label:e})]}),y8=(e,t)=>e.some(e=>e.length>0)||!!t,b8=({groups:e,trailing:t})=>{if(!y8(e,t))return null;let n=e.filter(e=>e.length>0);return(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n.map((e,t)=>(0,H.jsxs)(o.Fragment,{children:[t>0&&(0,H.jsx)(`span`,{className:`mx-1 h-5 w-px bg-border`}),e]},t)),t&&(0,H.jsx)(`div`,{className:`flex min-w-32 flex-1 justify-end`,children:t})]})},Sme=(e,t,n)=>{let[r,i]=(0,o.useState)(t??o8);return[e??r,e=>{i(e),n?.(e)}]},x8=({config:e,layout:t,value:n,defaultValue:r,onChange:i,lockedLabels:a,defaultOpenMenu:s,fullWidth:c,leading:l,trailing:u})=>{let[d,f]=Sme(n,r,i),p=d8(e,d),m=(0,H.jsx)(i8,{chips:p,lockedLabels:a,onRemove:e=>f(f8(d,e)),onClear:()=>f(o8)}),h=(e,t=!1)=>{let n=d.facets[e.id]??[],r=t=>f(s8(d,e.id,t));return e.combobox?(0,H.jsx)(gme,{config:e,selected:n,onToggle:r,inline:t}):(0,H.jsx)(_me,{config:e,selected:n,onToggle:r})},g=e.ranges??[],_=e=>(0,H.jsx)(xme,{config:e,value:d.ranges?.[e.id],onChange:t=>f(l8(d,e.id,t))}),v=e.datePresets&&(0,H.jsx)(pme,{value:d.date,presets:Array.isArray(e.datePresets)?e.datePresets:void 0,onChange:e=>f({...d,date:e})}),y=(e.toggles??[]).map(e=>(0,H.jsx)(v8,{label:e.label,checked:d.toggles.includes(e.id),onChange:()=>f(c8(d,e.id))},e.id));if(t===`panel`)return(0,H.jsxs)(`aside`,{className:c?`flex w-full flex-col gap-1`:`flex w-64 shrink-0 flex-col gap-1 overflow-y-auto rounded-lg border bg-background px-4 py-3`,children:[(0,H.jsx)(`div`,{className:`flex items-center justify-between pb-1`,children:(0,H.jsx)(`h2`,{className:`font-semibold`,children:`Filters`})}),(p.length>0||(a?.length??0)>0)&&(0,H.jsx)(`div`,{className:`border-b pb-3`,children:m}),l,e.facets.map(e=>(0,H.jsx)(h8,{title:e.label,children:h(e)},e.id)),g.map(e=>(0,H.jsx)(h8,{title:e.label,children:_(e)},e.id)),v&&(0,H.jsx)(h8,{title:`Date`,children:v}),y.length>0&&(0,H.jsx)(h8,{title:`Show only`,children:y})]});let b=[...e.facets.map(e=>(0,H.jsx)(m8,{label:e.label,activeCount:(d.facets[e.id]??[]).length,width:e.combobox?280:void 0,defaultOpen:s===e.id,children:h(e,!0)},e.id)),...g.map(e=>(0,H.jsx)(m8,{label:e.label,activeCount:+!!d.ranges?.[e.id],width:280,defaultOpen:s===e.id,children:_(e)},`range:${e.id}`)),...v?[(0,H.jsx)(o.Fragment,{children:v},`date`)]:[]],x=(e.toggles??[]).map(e=>(0,H.jsx)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:(0,H.jsx)(v8,{label:e.label,checked:d.toggles.includes(e.id),onChange:()=>f(c8(d,e.id))})},e.id)),S=[l?[(0,H.jsx)(o.Fragment,{children:l},`leading`)]:[],b,x];return!y8(S,u)&&p.length===0&&!a?.length?null:(0,H.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,H.jsx)(b8,{groups:S,trailing:u}),m]})},S8=uo(),C8={start:0,end:0},w8={"7d":{amount:7,unit:`d`},"30d":{amount:30,unit:`d`},"90d":{amount:90,unit:`d`}},Cme=e=>new Date(e).toISOString().replace(`.000Z`,`Z`),T8=(e,t)=>{let[n,r,i]=[t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()];return Cme(e===`year`?Date.UTC(n,0,1):e===`quarter`?Date.UTC(n,Math.floor(r/3)*3,1):e===`month`?Date.UTC(n,r,1):e===`yesterday`?Date.UTC(n,r,i-1):Date.UTC(n,r,i))},E8=[`year`,`quarter`,`month`,`yesterday`,`today`],D8=(e,t)=>t===`date`?{kind:`string`,value:e.slice(0,10),span:C8}:{kind:`timestamp`,value:e,span:C8},wme=(e,t,n,r)=>{if(t in w8)return[S8.gte(e,S8.ago(t))];let i=S8.gte(e,D8(T8(t,n),r));return t===`yesterday`?[i,S8.lt(e,D8(T8(`today`,n),r))]:[i]},Tme=(e,t,n=new Date)=>{let r=e.facets.flatMap(e=>{let n=t.facets[e.id]??[];if(n.length===0)return[];if(e.flags){let t=e.options.filter(e=>n.includes(e.value)).map(e=>S8.eq(e.value,!0));return t.length===0?[]:[t.length===1?t[0]:S8.or(...t)]}return[n.length===1?S8.eq(e.id,n[0]):S8.in(e.id,n)]}),i=(e.ranges??[]).flatMap(e=>{let n=t.ranges?.[e.id];return n?[S8.gte(e.id,n[0]),S8.lte(e.id,n[1])]:[]}),a=e.dateField&&t.date?wme(e.dateField,t.date,n,e.dateKind):[],o=(e.toggles??[]).filter(e=>t.toggles.includes(e.id)).map(e=>S8.eq(e.id,!0));return[...r,...i,...a,...o]},Eme=e=>e.length===0?``:Ya(S8.and(...e)),O8=(e,t,n=[],r=new Date)=>Eme([...Tme(e,t,r),...n]),k8=e=>e.kind===`and`?e.args.flatMap(k8):[e],A8=e=>e.field.path.join(`.`),Dme=e=>e.kind===`compare`&&e.op===`=`&&e.value.kind===`boolean`&&e.value.value,Ome=(e,t)=>{let n=e.kind===`or`?e.args:[e];if(!n.every(Dme))return;let r=n.map(A8),i=t.get(r[0]);return i!==void 0&&r.every(e=>t.get(e)===i)?{group:i,fields:r}:void 0},j8=e=>e.kind===`number`?String(e.raw):e.kind===`string`?String(e.value):void 0,M8=(e,t)=>{let n=e.value;if(n.kind===`now`&&n.offset?.sign===`-`){let{amount:e,unit:t}=n.offset.duration;return Object.entries(w8).find(([,n])=>n.amount===e&&n.unit===t)?.[0]}if(n.kind===`timestamp`)return E8.find(e=>T8(e,t)===n.value);if(n.kind===`string`)return E8.find(e=>T8(e,t).slice(0,10)===n.value)},N8=(e,t,n=new Date)=>{let r=Ca(t);if(!r.ok)return{ok:!1,errors:r.errors};let i={facets:{},toggles:[]},a=[],o=new Set(e.facets.filter(e=>!e.flags).map(e=>e.id)),s=new Map(e.facets.filter(e=>e.flags).flatMap(e=>e.options.map(t=>[t.value,e.id]))),c=new Set((e.toggles??[]).map(e=>e.id)),l=new Set((e.ranges??[]).map(e=>e.id)),u=new Map,d,f;for(let t of r.ast?k8(r.ast):[]){let r=Ome(t,s);if(r&&!i.facets[r.group])i.facets[r.group]=r.fields;else if(t.kind===`compare`&&o.has(A8(t))&&t.op===`=`&&j8(t.value)!==void 0)i.facets[A8(t)]=[...i.facets[A8(t)]??[],j8(t.value)];else if(t.kind===`in`&&o.has(A8(t))&&t.values.every(e=>j8(e)!==void 0))i.facets[A8(t)]=[...i.facets[A8(t)]??[],...t.values.map(e=>j8(e))];else if(t.kind===`compare`&&e.dateField===A8(t)&&t.op===`>=`&&M8(t,n)&&!i.date)i.date=M8(t,n),d=t;else if(t.kind===`compare`&&e.dateField===A8(t)&&t.op===`<`&&(t.value.kind===`timestamp`||t.value.kind===`string`)&&T8(`today`,n).startsWith(t.value.value.slice(0,10)))f=t;else if(t.kind===`compare`&&c.has(A8(t))&&t.op===`=`&&t.value.kind===`boolean`&&t.value.value)i.toggles.push(A8(t));else if(t.kind===`compare`&&l.has(A8(t))&&(t.op===`>=`||t.op===`<=`)&&t.value.kind===`number`){let e=u.get(A8(t))??{clauses:[]};t.op===`>=`?e.low=t.value.value:e.high=t.value.value,e.clauses.push(t),u.set(A8(t),e)}else a.push(t)}i.date===`yesterday`&&!f&&(a.push(d),i.date=void 0),f&&i.date!==`yesterday`&&a.push(f);for(let[e,t]of u)t.low!==void 0&&t.high!==void 0?i.ranges={...i.ranges,[e]:[t.low,t.high]}:a.push(...t.clauses);return{ok:!0,state:i,extras:a}},kme=[`integer`,`bigint`,`decimal`],Ame=(e,t)=>{let n=e?.fields[t]?.type;return n!==void 0&&kme.includes(n)},P8=(e,t)=>e.kind===`range`||e.kind===`facets`&&Ame(t,e.field),jme=e=>({id:e,label:e,min:0,max:0,step:1,histogram:[],format:String}),F8=(e,t)=>{let n=e?.filters??[],r=n.find(e=>e.kind===`dateRange`);return{facets:n.flatMap(e=>e.kind===`facets`&&!P8(e,t)?[{id:e.field,label:e.field,options:[],searchable:e.search,...t?.fields[e.field]?.type===`relation`&&{combobox:!0}}]:e.kind===`flags`?[{id:e.fields.join(`|`),label:e.label,options:e.fields.map(e=>({value:e,label:e,count:0})),flags:!0}]:[]),ranges:n.flatMap(e=>e.kind!==`flags`&&P8(e,t)?[jme(e.field)]:[]),...r&&{dateField:r.field,dateKind:t?.fields[r.field]?.type===`date`?`date`:`timestamp`,...r.presets.length>0&&{datePresets:r.presets}},toggles:n.flatMap(e=>e.kind===`toggle`?[{id:e.field,label:e.field}]:[])}},I8=(e,t)=>(e?.filters??[]).some(e=>e.kind===`range`&&e.field===t&&e.histogram),L8=(e,t)=>{let n=e?.fields[t],r=n?.suffix??``;return e=>`${n?.prefix===`€`?nf(e*100).replace(`.00`,``):String(e)}${r}`},R8=uo(),Mme={start:0,end:0},Nme=(e,t,n)=>{let r=N8(F8(t,e),n);return r.ok?Object.fromEntries(Object.entries(r.state.facets).filter(([t,n])=>e.fields[t]?.type===`relation`&&n.length>0)):{}},Pme=(e,t,n)=>{let r=e=>t?.fields[e]?.label??q(e),i=F8(t,e);return{...i,facets:i.facets.map(i=>{if(i.flags)return{...i,options:i.options.map(e=>({...e,label:r(e.value)}))};let a=e.fields[i.id]?.enumValues??[],o=e.fields[i.id]?.type===`enum`?Object.fromEntries(a.map(e=>[e,rs(e,t?.fields[i.id]?.valueLabels)])):n[i.id]??{};return{...i,label:r(i.id),labels:o}}),ranges:(i.ranges??[]).map(e=>({...e,label:r(e.id),format:L8(t,e.id)})),toggles:i.toggles?.map(e=>({...e,label:r(e.id)}))}},z8=(e,t,n,r={})=>{let i=Pme(e,t,r),a=N8(i,n);if(!a.ok)return[{key:`unreadable`,label:`A filter that cannot be read`}];let o=a.extras.map((e,t)=>({key:`extra:${t}`,label:e.kind===`search`?`"${e.text}"`:Ya(e)}));return[...d8(i,a.state),...o]},Fme=e=>Object.fromEntries(e.facets.filter(e=>!e.flags).map(e=>[e.id,{...e.labels,...Object.fromEntries(e.options.map(e=>[e.value,e.label]))}])),Ime=(e,t,n)=>{if(typeof n!=`string`||n===``)return e;let r=R8.gt(t,{kind:`timestamp`,value:new Date(n).toISOString(),span:Mme}),i=Ca(e);if(!i.ok)throw Error(`The saved filter cannot be read: ${i.errors.map(e=>e.message).join(`; `)}`);return Ya(i.ast?R8.and(i.ast,r):r)},Lme=(e,t)=>typeof t!=`string`||t===``?!0:typeof e!=`string`||e===``?!1:new Date(e).getTime()>new Date(t).getTime(),B8=(e,t)=>{let n=K(),r=Up(),{resources:i,views:a}=J(),o=a[e.name],s=Object.entries(Nme(e,o,t)),c=hh({queries:s.map(([t,o])=>{let s=i[e.fields[t].relation.resource];return{queryKey:G.labels(`chips:${e.name}.${t}`,o.join(`,`)),enabled:s!==void 0,queryFn:async()=>Object.fromEntries(await D4(r,n,s,o,a[s.name]))}})});return z8(e,o,t,Object.fromEntries(s.flatMap(([e],t)=>c[t]?.data?[[e,c[t].data]]:[])))},Rme=(e,t)=>({record:Object.fromEntries(Object.entries(t).filter(([t])=>Object.hasOwn(e.fields,t))),etag:typeof t.etag==`string`?t.etag:``,...typeof t.permissions==`object`&&t.permissions!==null&&{permissions:t.permissions}}),V8=e=>{let t=Up();return(0,o.useCallback)(n=>t.setQueryData(G.recordPreview(e.name,Ao(Ag(e,n))),Rme(e,n)),[t,e])},H8={wallet:lee,"file-text":it,send:see,ruler:aee,bed:ee,bath:M,house:ut,"door-open":eee,"land-plot":vt,leaf:tee,tag:Pn,key:gt,calendar:de,heart:ct,bell:te,bookmark:oe,"external-link":Je},U8=e=>e!==void 0&&Object.hasOwn(H8,e)?H8[e]:void 0,W8=({benefits:e})=>e&&e.length>0?(0,H.jsx)(`ul`,{className:`flex flex-col gap-2 text-left`,children:e.map(e=>(0,H.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,H.jsx)(he,{className:`mt-0.5 size-4 shrink-0 text-primary`,"aria-hidden":!0}),e]},e))}):null,G8=({prompt:e})=>{let{canSignUp:t}=U(),{link:n}=zh(),r=xf({variant:`primary`}),i=e.signUp?(0,H.jsx)(`a`,{href:e.signUp.href,target:`_blank`,rel:`noreferrer`,className:r,children:e.signUp.label}):t&&(0,H.jsx)(Mu,{to:n(`sign-up`),className:r,children:`Create an account`});return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Mu,{to:n(),className:i?xf():r,children:`Sign in`}),i]})},K8=e=>{let{prompt:t}=e,n=(0,o.useId)();if(e.as===`dialog`)return(0,H.jsx)(m_,{title:t.title,description:t.description,open:e.open,onClose:e.onClose,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:e.onClose,children:`Not now`}),(0,H.jsx)(G8,{prompt:t})]}),children:(0,H.jsx)(W8,{benefits:t.benefits})});let r=U8(t.icon)??Ft;return(0,H.jsxs)(`section`,{"aria-labelledby":n,className:`mx-auto flex w-full max-w-md flex-col items-center gap-4 px-5 py-10 text-center sm:py-16`,children:[(0,H.jsx)(`span`,{className:`flex size-12 items-center justify-center rounded-full bg-primary/10 text-primary`,children:(0,H.jsx)(r,{className:`size-6`,"aria-hidden":!0})}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`h1`,{id:n,className:`text-lg font-semibold`,children:t.title}),(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:t.description})]}),(0,H.jsx)(W8,{benefits:t.benefits}),(0,H.jsx)(`div`,{className:`mt-2 flex w-full flex-col-reverse gap-2 sm:w-auto sm:flex-row sm:justify-center [&>*]:min-h-11 sm:[&>*]:min-h-0`,children:(0,H.jsx)(G8,{prompt:t})})]})},zme=uo(),q8=e=>{if(typeof e==`string`||typeof e==`number`)return e;if(e&&typeof e==`object`&&`id`in e)return q8(e.id)},Bme=(e,t,n)=>n.flatMap(n=>{let r=q8(n[t]);return r===void 0?[]:[{key:Ao(Ag(e,n)),target:r}]}),Vme=(e,t)=>e.find(e=>Ao(e.target)===t),Hme=(e,t)=>[...e,{key:``,target:t}],Ume=(e,t)=>e.filter(e=>Ao(e.target)!==t),J8=(e,t)=>{let[n]=e.primaryKey;if(e.primaryKey.length!==1||n===void 0)throw Error(`${e.name} has a composite key, so its saved records cannot be listed`);let r=[...new Set(t.map(e=>e.target))];return r.length===0?void 0:zme.in(n,r)},Y8=(e,t)=>G.list(e,``,``,500,`saved:${t}`),X8=(e,t,n)=>{let r=K(),i=J().resources[e];return _h({queryKey:Y8(e,t),enabled:n&&i!==void 0,queryFn:async()=>{let n=[],a;do{let o=await r.list(e,{pageSize:500,fields:[...i.primaryKey,t],...a&&{pageToken:a}});n.push(...o.items),a=o.nextPageToken||void 0}while(a);return Bme(i,t,n)}})},Wme=e=>e instanceof Error?e.message:`Something went wrong`,Gme=(e,t,n)=>{let r=J(),i=K(),a=Up(),o=Ig(),s=Xw(),{resource:c,field:l}=e,u=r.permissions[c],d=r.resources[c]!==void 0&&u!==void 0&&Fw(u,`create`)&&Fw(u,`delete`),f=r.signIn?.[c]?.signIn,p=X8(c,l,d),m=p.data&&Vme(p.data,t),h=Y8(c,l),g=vh({mutationFn:async e=>{e?await i.remove(c,e.key):await i.create(c,{[l]:n})},onMutate:async e=>{await a.cancelQueries({queryKey:h,exact:!0});let r=a.getQueryData(h);return a.setQueryData(h,(r=[])=>e?Ume(r,t):Hme(r,n)),{before:r}},onError:(e,t,n)=>{a.setQueryData(h,n?.before),o.show({state:`error`,title:t?`Could not take it off`:`Could not save it`,description:Wme(e)})},onSettled:()=>s(c)});return{mode:d?`save`:f?`sign-in`:void 0,prompt:f,saved:m!==void 0,ready:p.data!==void 0&&!g.isPending,toggle:()=>g.mutate(m)}},Kme=({favorite:e,recordKey:t,target:n,className:r})=>{let i=Gme(e,t,n),[a,s]=(0,o.useState)(!1);if(!i.mode)return null;let c=e.label??`Favorite`,l=V(`absolute right-2 top-2 flex size-8 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,r);return i.mode===`sign-in`?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`button`,{type:`button`,"aria-label":c,"aria-haspopup":`dialog`,className:l,onClick:()=>s(!0),children:(0,H.jsx)(ct,{className:`size-4`,"aria-hidden":!0})}),(0,H.jsx)(K8,{as:`dialog`,prompt:i.prompt,open:a,onClose:()=>s(!1)})]}):(0,H.jsx)(`button`,{type:`button`,"aria-label":c,"aria-pressed":i.saved,"aria-disabled":!i.ready,className:l,onClick:()=>i.ready&&i.toggle(),children:(0,H.jsx)(ct,{className:V(`size-4`,i.saved&&`fill-current text-danger`),"aria-hidden":!0})})},Z8=6,qme=(e,t,n)=>{let r=e.bottom+Z8;return{top:r+t.height>n.height-Z8?Math.max(Z8,e.top-Z8-t.height):r,left:Math.max(Z8,Math.min(e.left,n.width-Z8-t.width))}},Q8=(e,t)=>{let n=oC(e).find(e=>e.kind===`cards`);if(!n)return{kind:`cards`,name:`dot`,badge:t};let{photos:r,favorite:i,dots:a,...o}=n;return o},Jme=(e,t,n,r)=>(e?.list?.relatedColumns??[]).filter(e=>r.includes(e.name)).flatMap(e=>{let r=t[e.resource];return r?[{column:e,fields:SC(r,n[r.name],Q8(n[r.name],e.status))}]:[]}),Yme=(e,{values:t,label:n,singular:r,plural:i})=>{if(e.length===0)return`No ${i}`;let a=new Map;for(let t of e)t!=null&&a.set(String(t),(a.get(String(t))??0)+1);let o=[...t,...[...a.keys()].filter(e=>!t.includes(e))].filter(e=>a.has(e)).map(e=>`${a.get(e)} ${n(e)}`),s=`${e.length} ${e.length===1?r:i}`;return o.length===0?s:`${s}: ${o.join(`, `)}`},$8=`flex shrink-0 items-center justify-center rounded-full p-0.5 pointer-coarse:p-1.5`,e5=`size-2.5 rounded-full`,t5=`flex min-w-0 items-center gap-0.5`,Xme=150,n5=288,Zme=({shown:e,row:t,target:n,view:r,column:i,Card:a,onEnter:s,onLeave:c})=>{let l=(0,o.useRef)(null),[u,d]=(0,o.useState)();return(0,o.useLayoutEffect)(()=>{l.current&&d(qme(e.dot,{width:n5,height:l.current.offsetHeight},{width:window.innerWidth,height:window.innerHeight}))},[e]),(0,tr.createPortal)((0,H.jsx)(`div`,{ref:l,"data-dot-card":!0,onMouseEnter:s,onMouseLeave:c,style:{width:n5,...u??{visibility:`hidden`,top:0,left:0}},className:`fixed z-50 rounded-lg shadow-pop`,children:(0,H.jsx)(a,{model:n,view:r,display:Q8(r,i.status),row:t})}),document.body)},r5=({column:e,records:t,target:n,view:r,wrap:i=!1,Card:a})=>{let s=(0,o.useMemo)(()=>t.map(e=>EC(n,e)),[t,n]),[c,l]=(0,o.useState)(),u=(0,o.useRef)(void 0),d=(0,o.useRef)(`mouse`),f=(0,o.useRef)(null),p=n.fields[e.status],m=r?.fields[e.status],h=t=>p?ZS(p,t.record[e.status],m):``,g=Eg(n,r),_=e=>e.labels[g]??String(e.record[g]??e.key),v=(r?.names?.singular??q(n.name)).toLowerCase(),y=(r?.names?.plural??q(n.name)).toLowerCase(),b=Yme(s.map(t=>t.record[e.status]),{values:p?.enumValues??[],label:e=>p?ZS(p,e,m):e,singular:v,plural:y}),x=()=>window.clearTimeout(u.current),S=()=>{x(),u.current=window.setTimeout(()=>l(void 0),Xme)},C=(e,t)=>{x(),l({key:e,dot:t.getBoundingClientRect()})};(0,o.useEffect)(()=>x,[]),(0,o.useEffect)(()=>{if(!c)return;let e=()=>l(void 0),t=t=>t.key===`Escape`&&e(),n=t=>{let n=t.target;!f.current?.contains(n)&&!n?.closest?.(`[data-dot-card]`)&&e()};return document.addEventListener(`keydown`,t),document.addEventListener(`pointerdown`,n),document.addEventListener(`scroll`,e,!0),window.addEventListener(`resize`,e),()=>{document.removeEventListener(`keydown`,t),document.removeEventListener(`pointerdown`,n),document.removeEventListener(`scroll`,e,!0),window.removeEventListener(`resize`,e)}},[c]);let w=e=>t=>{d.current===`touch`&&c?.key!==e&&(t.preventDefault(),C(e,t.currentTarget))},T=e=>{e.relatedTarget?.closest?.(`[data-dot-card]`)||S()},E=c&&s.find(e=>e.key===c.key);return(0,H.jsxs)(`div`,{ref:f,className:V(t5,i&&`pointer-events-none flex-wrap`),onClick:e=>e.stopPropagation(),onPointerDown:e=>d.current=e.pointerType,children:[(0,H.jsx)(`span`,{className:`sr-only`,children:b}),s.map(t=>{let r=t.record[e.status],i=j4(m?.valueColors,r);return(0,H.jsx)(FC,{to:{kind:`record`,resource:n.name,key:t.key},"aria-label":`${_(t)}, ${h(t)}`,onPointerEnter:e=>e.pointerType!==`touch`&&C(t.key,e.currentTarget),onPointerLeave:e=>e.pointerType!==`touch`&&S(),onFocus:e=>e.currentTarget.matches(`:focus-visible`)&&C(t.key,e.currentTarget),onBlur:T,onClick:w(t.key),className:V($8,`pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40`),children:(0,H.jsx)(`span`,{"aria-hidden":!0,style:i===void 0?void 0:{backgroundColor:i},className:V(e5,i===void 0&&Ju[HS(String(r))],c?.key===t.key&&`ring-2 ring-foreground/30`)})},t.key)}),c&&E&&(0,H.jsx)(Zme,{shown:c,row:E,target:n,view:r,column:e,Card:a,onEnter:x,onLeave:S})]})},Qme=({count:e})=>(0,H.jsx)(`span`,{"aria-hidden":!0,className:V(t5,`invisible flex-wrap`),children:Array.from({length:e},(e,t)=>(0,H.jsx)(`span`,{className:$8,children:(0,H.jsx)(`span`,{className:e5})},t))}),i5=`flex flex-col gap-1.5`,$me=({dots:e})=>(0,H.jsx)(`span`,{className:i5,children:e.map(({column:e,records:t})=>(0,H.jsx)(Qme,{count:t.length},e.name))}),ehe=({dots:e,Card:t})=>{let{resources:n,views:r}=J();return(0,H.jsx)(`div`,{className:`pointer-events-none absolute inset-x-[calc(0.75rem+1px)] bottom-[calc(0.75rem+1px)] ${i5}`,children:e.map(({column:e,records:i})=>{let a=n[e.resource];return a&&(0,H.jsx)(r5,{column:e,records:i,target:a,view:r[a.name],Card:t,wrap:!0},e.name)})})},the=(e,t,n)=>(t.dots??[]).flatMap(t=>{let r=e?.list?.relatedColumns?.find(e=>e.name===t),i=n.record[t];return r&&Array.isArray(i)&&i.length>0?[{column:r,records:i}]:[]}),a5=({value:e})=>{let t=Vx(e,{width:320,height:240});return t?(0,H.jsx)($C,{image:t,loading:`lazy`,className:`size-full object-cover`}):null},o5=({children:e})=>(0,H.jsx)(`span`,{className:`-mx-3 -mt-3 mb-1.5 block aspect-[4/3] overflow-hidden rounded-t-lg border-b border-border bg-muted`,children:e}),nhe=({value:e})=>(0,H.jsx)(o5,{children:(0,H.jsx)(a5,{value:e})}),rhe=10,ihe=(e,t)=>{let n=jx(e)?e.uri:void 0,r=t.filter(e=>jx(e)&&e.uri!==n);return(n===void 0?r:[e,...r]).slice(0,rhe)},ahe=(e,t)=>t===0?0:(e%t+t)%t,ohe=(e,t,n)=>t<=0||n===0?0:Math.min(n-1,Math.max(0,Math.round(e/t))),s5=`pointer-events-auto absolute top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm opacity-0 transition-opacity group-has-[[data-card-photos]:hover]/card:opacity-100 group-hover/arrows:opacity-100 group-has-[:focus-visible]/arrows:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,c5=`[@media(hover:none)]:opacity-100`,she=({photos:e,cover:t,swipe:n=!0,children:r})=>{let i=(0,o.useRef)(null),a=(0,o.useRef)(void 0),[s,c]=(0,o.useState)(0),l=ihe(t,e),u=e=>{let t=i.current;t&&t.scrollTo({left:e*t.clientWidth})},d=e=>{a.current=ahe((a.current??s)+e,l.length),u(a.current)},f=()=>{a.current=void 0},p=e=>{c(ohe(e.scrollLeft,e.clientWidth,l.length)),a.current!==void 0&&Math.abs(e.scrollLeft-a.current*e.clientWidth)<1&&(a.current=void 0)},m=(0,H.jsx)(o5,{children:(0,H.jsx)(`span`,{ref:i,tabIndex:-1,"data-card-photos":!0,onPointerDown:f,onScroll:e=>p(e.currentTarget),className:V(`flex size-full snap-x snap-mandatory outline-none [scrollbar-width:none] motion-safe:scroll-smooth [&::-webkit-scrollbar]:hidden`,n?`overflow-x-auto overscroll-x-contain`:`overflow-x-hidden`),children:l.map((e,t)=>(0,H.jsx)(`span`,{className:`block size-full shrink-0 snap-start snap-always`,children:(0,H.jsx)(a5,{value:e})},t))})});return(0,H.jsxs)(H.Fragment,{children:[r(m),l.length>1&&(0,H.jsxs)(`div`,{className:`group/arrows pointer-events-none absolute inset-x-px top-px aspect-[4/3]`,children:[(0,H.jsx)(`button`,{type:`button`,"aria-label":`Previous photo`,className:V(s5,!n&&c5,`left-2`),onClick:()=>d(-1),children:(0,H.jsx)(ye,{className:`size-4`,"aria-hidden":!0})}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Next photo`,className:V(s5,!n&&c5,`right-2`),onClick:()=>d(1),children:(0,H.jsx)(xe,{className:`size-4`,"aria-hidden":!0})}),(0,H.jsxs)(`span`,{className:`absolute inset-x-0 bottom-2 flex justify-center`,"aria-live":`polite`,children:[(0,H.jsx)(`span`,{className:`sr-only`,children:`Photo ${s+1} of ${l.length}`}),(0,H.jsx)(`span`,{className:`flex items-center gap-1 rounded-full bg-background/70 px-1.5 py-1 leading-none`,"aria-hidden":!0,children:l.map((e,t)=>(0,H.jsx)(`span`,{className:V(`size-1.5 rounded-full`,t===s?`bg-foreground`:`bg-foreground/35`)},t))})]})]})]})},che=({icon:e,children:t})=>{let n=U8(e);return(0,H.jsxs)(`dd`,{className:`flex items-center gap-1 tabular-nums`,children:[n&&(0,H.jsx)(n,{className:`size-3.5 shrink-0`,"aria-hidden":!0}),t]})},l5=({model:e,view:t,display:n,row:r,swipe:i=!0,mark:a})=>{let{image:o,title:s,subtitle:c,amount:l,badge:u,meta:d,footer:f,flags:p}=_C(e,t,n),m=e=>t?.fields[e]?.label??q(e),h=n=>{let i=e.fields[n];if(!i)return``;let a=r.record[n];return r.labels[n]===void 0&&BS(i,t?.fields[n])&&typeof a==`string`&&a!==``?zS(a):r.labels[n]??ZS(i,a,t?.fields[n])},{fields:g,components:_}=Xg(),v=V8(e),y=n.card===void 0?void 0:_?.[n.card],b=n=>{let i=e.fields[n],a=i&&rw(g,i,t?.fields[n]);return a?(0,H.jsx)(ow,{shown:a,part:`display`,field:i,value:r.record[n],fallback:h(n)}):h(n)},x=n=>{let i=e.fields[n],a=r.record[n];return!i||!BS(i,t?.fields[n])||rw(g,i,t?.fields[n])||typeof a!=`string`||a===``?b(n):(0,H.jsx)(cw,{source:a,inLink:!0})},S=n=>{let i=e.fields[n],a=t?.fields[n],o=r.record[n];return!i||a?.format!==`badge`||rw(g,i,a)||o==null||o===``?b(n):(0,H.jsx)(M4,{value:o,hints:a,children:h(n)})},C=n=>{let i=e.fields[n];if(!i)return;if(r.labels[n]!==void 0||rw(g,i,t?.fields[n]))return(0,H.jsx)(`strong`,{className:`font-semibold text-foreground`,children:b(n)});let a=bC(i,r.record[n],t?.fields[n]);return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`strong`,{className:`font-semibold text-foreground`,children:a.amount}),a.suffix]})},w=y?void 0:n.photos,T=u===void 0?void 0:r.record[u],E=p.filter(e=>r.record[e]===!0),D=o===void 0?void 0:r.record[o],O=yC(r,l),k=vC(r,f),A=o!==void 0||w!==void 0,j=n.favorite,M=y?[]:the(t,n,r),N=e=>(0,H.jsxs)(H.Fragment,{children:[A&&e,(0,H.jsxs)(`span`,{className:`flex items-start justify-between gap-2 ${j&&!A?`pr-8`:``}`,children:[(0,H.jsx)(`span`,{className:`min-w-0 truncate font-medium`,children:b(s)}),u!==void 0&&T!=null&&(0,H.jsx)(M4,{value:T,hints:t?.fields[u],children:h(u)})]}),c!==void 0&&(0,H.jsx)(`span`,{className:t?.fields[c]?.markdown?`line-clamp-3 break-words text-muted-foreground`:t?.fields[c]?.multiline?`line-clamp-3 whitespace-pre-line break-words text-muted-foreground`:`truncate text-muted-foreground`,children:x(c)}),O!==void 0&&(0,H.jsx)(`span`,{className:`truncate tabular-nums text-muted-foreground`,children:C(O)}),d.length>0&&(0,H.jsx)(`dl`,{className:`mt-auto flex flex-wrap items-center gap-x-3 gap-y-0.5 pt-1 text-xs text-muted-foreground`,children:vC(r,d).map(e=>(0,H.jsxs)(`div`,{className:`flex gap-1`,children:[(0,H.jsx)(`dt`,{className:`sr-only`,children:m(e)}),(0,H.jsx)(che,{icon:t?.fields[e]?.icon,children:S(e)})]},e))}),E.length>0&&(0,H.jsx)(`ul`,{className:`flex flex-wrap gap-1`,"aria-label":`Features`,children:E.map(e=>(0,H.jsx)(`li`,{children:(0,H.jsx)(Xu,{dot:!1,children:m(e)})},e))}),k.length>0&&(0,H.jsx)(`span`,{className:`truncate text-xs text-muted-foreground ${d.length>0?``:`mt-auto`}`,children:k.map((e,t)=>(0,H.jsxs)(`span`,{children:[t>0&&(0,H.jsx)(`span`,{"aria-hidden":!0,children:` • `}),b(e)]},e))}),M.length>0&&(0,H.jsx)($me,{dots:M})]}),ee=t=>(0,H.jsxs)(FC,{to:{kind:`record`,resource:e.name,key:r.key},onClick:()=>v(r.record),className:`flex h-full flex-col gap-1.5 rounded-lg border border-border bg-background p-3 hover:border-border-strong hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,children:[a&&!A&&(0,H.jsx)(Xu,{tone:`blue`,className:`self-start`,children:a}),y?(0,H.jsx)(tg,{name:n.card,fallback:N(t),children:(0,H.jsx)(y,{row:r})}):N(t)]});return(0,H.jsxs)(`div`,{className:w?`group/card relative h-full`:j||a||M.length>0?`relative h-full`:`h-full`,children:[w?(0,H.jsx)(she,{photos:r.photos??[],cover:D,swipe:i,children:ee},r.key):ee((0,H.jsx)(nhe,{value:D})),a&&A&&(0,H.jsx)(Xu,{tone:`blue`,className:`pointer-events-none absolute top-2 left-2 shadow-sm`,children:a}),M.length>0&&(0,H.jsx)(ehe,{dots:M,Card:l5}),j&&(0,H.jsx)(Kme,{favorite:j,recordKey:r.key,target:Ag(e,r.record),className:A?void 0:`right-1.5 top-1.5`})]})},u5=268,d5=3,f5=(e,t,n)=>{let r=Math.floor(Math.max(0,e)/u5),i=Math.ceil((Math.max(0,e)+t)/u5);return{start:Math.max(0,r-d5),end:Math.min(n,i+d5)}},p5=e=>e*u5,lhe=e=>{let t=(0,o.useRef)(null),[n,r]=(0,o.useState)({left:0,width:0});(0,o.useLayoutEffect)(()=>{let n=t.current;if(!n)return;let i=()=>r(t=>{let r={left:n.scrollLeft,width:n.clientWidth};return((t,n)=>{let[r,i]=[f5(t.left,t.width,e),f5(n.left,n.width,e)];return r.start===i.start&&r.end===i.end&&t.width===n.width&&t.left>0==n.left>0&&Math.abs(t.left-n.left)<1})(t,r)?t:r});i();let a=new ResizeObserver(i);return a.observe(n),n.addEventListener(`scroll`,i,{passive:!0}),()=>{a.disconnect(),n.removeEventListener(`scroll`,i)}},[e]);let i=Math.max(0,p5(e)-12),a=e=>t.current?.scrollBy({left:e*Math.max(p5(1),n.width-12),behavior:`smooth`});return{ref:t,...f5(n.left,n.width,e),back:n.left>0,on:n.left+n.width<i-1,page:a}},m5=`absolute top-1/2 z-10 hidden size-8 -translate-y-1/2 items-center justify-center rounded-full border border-border-strong bg-background shadow-pop hover:bg-muted sm:flex`,h5=({cards:e})=>e>0?(0,H.jsx)(`li`,{"aria-hidden":!0,className:`shrink-0`,style:{width:p5(e)-12}}):null,uhe=({model:e,view:t,display:n,source:r,label:i,isNew:a})=>{let{total:o}=r,s=lhe(o),c=L6({total:o,rowAt:r.rowAt,loadRows:r.loadRows,revision:r.revision,latencyMs:0},s.start,Math.max(s.start,s.end-1)),l=Array.from({length:s.end-s.start},(e,t)=>s.start+t);return(0,H.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,H.jsxs)(`ul`,{ref:s.ref,"aria-label":i,className:`flex snap-x gap-3 overflow-x-auto overflow-y-hidden pb-1`,style:{scrollbarWidth:`thin`},children:[(0,H.jsx)(h5,{cards:s.start}),l.map(r=>{let i=c(r);if(!i)return(0,H.jsx)(`li`,{"aria-hidden":!0,className:`shrink-0`,style:{width:256},children:(0,H.jsx)(ku,{className:`h-full min-h-24 rounded-lg`})},`skeleton-${r}`);let s=EC(e,i);return(0,H.jsx)(`li`,{"aria-posinset":r+1,"aria-setsize":o,className:`grid shrink-0 snap-start grid-cols-[minmax(0,1fr)]`,style:{width:256},children:(0,H.jsx)(l5,{model:e,view:t,display:n,row:s,swipe:!1,mark:a?.(s)?`New`:void 0})},s.key)}),(0,H.jsx)(h5,{cards:o-s.end})]}),s.back&&(0,H.jsx)(`button`,{type:`button`,"aria-label":`Previous ${i.toLowerCase()}`,onClick:()=>s.page(-1),className:`${m5} -left-3`,children:(0,H.jsx)(ye,{className:`size-4`,"aria-hidden":!0})}),s.on&&(0,H.jsx)(`button`,{type:`button`,"aria-label":`Next ${i.toLowerCase()}`,onClick:()=>s.page(1),className:`${m5} -right-3`,children:(0,H.jsx)(xe,{className:`size-4`,"aria-hidden":!0})})]})},dhe=uo(),fhe=(e,t)=>{if(!t)return e;let n=Ca(e);if(!n.ok)throw Error(`The filter cannot be read: ${n.errors.map(e=>e.message).join(`; `)}`);return Ya(n.ast?dhe.and(n.ast,t):t)},phe=(e,t)=>{let n=oC(e).filter(e=>e.kind===`cards`);return n.find(e=>e.name===t)??n[0]??{kind:`cards`,name:`cards`}},mhe=()=>(0,H.jsx)(`div`,{className:`flex gap-3 overflow-hidden`,children:Array.from({length:3},(e,t)=>(0,H.jsx)(ku,{className:`h-24 w-64 shrink-0`},t))}),g5=({model:e,view:t,filter:n,sort:r=``,display:i,limit:a,chips:s=!0,empty:c,note:l,isNew:u,viewAll:d,scope:f,list:p})=>{let{resources:m,views:h}=J(),g=mu(),_=phe(t,i),v=r||DC(e,t),y=$6({resources:m,views:h,model:e,columns:(0,o.useMemo)(()=>CC(e,t,[]),[e,t]),filter:(0,o.useMemo)(()=>fhe(n,f),[n,f]),orderBy:v}),b=B8(e,n),x=(t?.names?.singular??q(e.name)).toLowerCase(),S=t?.names?.plural??q(e.name),C=y.source?.total,T=(0,o.useMemo)(()=>y.source&&{...y.source,total:Math.min(y.source.total,a??1/0)},[y.source,a]);return(0,H.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3`,children:[s&&b.length>0||C!==void 0||l?(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[s&&b.length>0?(0,H.jsx)(n8,{chips:b}):(0,H.jsx)(`span`,{}),(0,H.jsxs)(`p`,{className:`flex flex-wrap gap-x-3 text-muted-foreground`,children:[l&&(0,H.jsx)(`span`,{children:l}),C!==void 0&&(0,H.jsx)(`span`,{className:`tabular-nums`,children:`${C.toLocaleString(`en-GB`)} ${C===1?x:S.toLowerCase()}`})]})]}):null,y.isLoading?(0,H.jsx)(mhe,{}):y.error?(0,H.jsx)(pS,{title:`Could not load`,error:y.error}):!T||T.total===0?(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:c??`No ${S.toLowerCase()} match.`}):(0,H.jsx)(uhe,{model:e,view:t,display:_,source:T,label:S,isNew:u}),(0,H.jsxs)(FC,{to:e8(e,t,g,{filter:n,orderBy:v,display:_.name,savedSearch:d?.savedSearch,resource:p}),onClick:d?.onOpen,className:`flex items-center gap-1 self-end font-medium text-primary-text hover:underline`,children:[d?.label??(0,H.jsxs)(H.Fragment,{children:[`View all `,(0,H.jsx)(`span`,{className:`sr-only`,children:S.toLowerCase()})]}),(0,H.jsx)(w,{className:`size-3.5`,"aria-hidden":!0})]})]})},hhe=({model:e,view:t,empty:n,...r})=>{let{resources:i,views:a}=J(),o=AC(i,a,e.name),s=X8(e.name,t.listOf,!0),c=(t.names?.plural??q(e.name)).toLowerCase();if(!o.listOf)return null;if(s.error)return(0,H.jsx)(pS,{title:`Could not load your ${c}`,error:s.error});if(!s.data)return(0,H.jsx)(ku,{className:`h-24`});let l=J8(o.model,s.data);return l?(0,H.jsx)(g5,{...r,model:o.model,view:o.view,filter:``,scope:l,list:e.name,empty:n}):(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:n??`No ${c} yet.`})},ghe=e=>G.list(e,``,``,500,`saved-searches`),_5=(e,t)=>{let n=K(),{resources:r,views:i}=J(),a=r[e];return _h({queryKey:ghe(e),enabled:t&&a!==void 0,queryFn:async()=>{let t=[],r;do{let o=await n.list(e,{pageSize:500,orderBy:DC(a,i[e]),...r&&{pageToken:r}});t.push(...o.items),r=o.nextPageToken||void 0}while(r);return t}})},v5=({model:e,of:t,target:n,targetView:r,row:i,recordKey:a})=>{let o=K(),s=Xw(),c=String(i[t.filter]??``),l=B8(n,c),u=t.name===void 0?void 0:i[t.name],d=typeof u==`string`&&u!==``?u:void 0,f=t.unseen,p=vh({mutationFn:t=>o.update(e.name,a,{[f.seenAt]:t},i.etag??`*`),onSettled:()=>s(e.name)}),m=_h({...Kw(o,n,f?Ime(c,f.field,i[f.seenAt]):``),enabled:f!==void 0}),h=(r?.names?.plural??q(n.name)).toLowerCase(),g={model:n,view:r,filter:c,sort:f?`${f.field} desc`:void 0,limit:t.limit,chips:d!==void 0,empty:`No ${h} match.`,note:f&&m.data===0&&`No new ${h} since you last looked.`,isNew:f&&(e=>Lme(e.record[f.field],i[f.seenAt])),viewAll:{label:`View all results`,savedSearch:a,...f&&{onOpen:()=>p.mutate(new Date().toISOString())}}};return{name:d,chips:l,title:d??ume(l),body:g}},_he=({model:e,view:t,target:n,targetView:r,row:i})=>{let a=Ao(Ag(e,i)),{name:o,chips:s,title:c,body:l}=v5({model:e,of:t.searchesOf,target:n,targetView:r,row:i,recordKey:a});return(0,H.jsxs)(`section`,{"aria-label":c,className:`flex flex-col gap-3 py-4 first:pt-0 last:pb-0`,children:[(0,H.jsx)(`h3`,{className:`text-[15px] font-semibold`,children:(0,H.jsx)(FC,{to:{kind:`record`,resource:e.name,key:a},className:`hover:underline`,children:o??(0,H.jsx)(r8,{chips:s})})}),(0,H.jsx)(g5,{...l})]})},vhe=({model:e,view:t,empty:n})=>{let{resources:r,views:i}=J(),a=t.searchesOf,o=r[a.resource],s=_5(e.name,!0),c=(t.names?.plural??q(e.name)).toLowerCase();return o?s.error?(0,H.jsx)(pS,{title:`Could not load your ${c}`,error:s.error}):s.data?s.data.length===0?(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:n??`No ${c} yet.`}):(0,H.jsx)(`div`,{className:`flex flex-col divide-y`,children:s.data.map(n=>(0,H.jsx)(_he,{model:e,view:t,target:o,targetView:i[a.resource],row:n},Ao(Ag(e,n))))}):(0,H.jsx)(ku,{className:`h-40`}):null},yhe=({node:e,slots:t})=>{let{resource:n,filter:r=``,sort:i,limit:a,display:o,title:s,description:c,empty:l}=eT(e),{resources:u,views:d}=J(),f=u[n];if(!f)return null;let p=d[f.name];return(0,H.jsx)(nT,{title:s,description:c,actions:t.actions,children:p?.searchesOf?(0,H.jsx)(vhe,{model:f,view:p,empty:l}):p?.listOf===void 0?(0,H.jsx)(g5,{model:f,view:p,filter:r,sort:i,limit:a,display:o,empty:l}):(0,H.jsx)(hhe,{model:f,view:p,limit:a,display:o,empty:l})})},bhe=({node:e,children:t})=>{let{when:n}=eT(e),{resources:r}=J(),i=K(),a=Pw(),s=(0,o.useMemo)(()=>ec(n),[n]),c=s.ok?s.paths:[],l=c.map(e=>nc(e,e=>!!(a&&Object.hasOwn(a.model.fields,e)))),u=c.filter((e,t)=>l[t]===void 0),d=Tue(a,u),f=hh({queries:l.flatMap(e=>{let t=e===void 0?void 0:r[e];return t?[Kw(i,t)]:[]})});if(!s.ok||d.some(e=>e.state===`loading`)||f.some(e=>e.isPending))return null;let p={};u.forEach((e,t)=>{let n=d[t];n.state===`ready`&&(p[e]=n.value)});let m=0;return c.forEach((e,t)=>{l[t]!==void 0&&(p[e]=r[l[t]]?f[m++]?.data??0:0)}),tc(s,p)?(0,H.jsx)(H.Fragment,{children:t}):null},y5=`text-2xl font-semibold tracking-tight tabular-nums`,xhe=({model:e,filter:t})=>{let n=qw(e,t);return n.isPending?(0,H.jsx)(ku,{className:`h-8 w-16`}):n.error?(0,H.jsx)(`span`,{className:`text-danger-text`,children:`Could not count`}):(0,H.jsx)(FC,{to:{kind:`list`,resource:e.name,filter:t},className:`${y5} hover:text-primary-text after:absolute after:inset-0 after:content-['']`,children:n.data.toLocaleString(`en-IE`)})},She=({field:e,format:t})=>{let n=L4(Pw(),e);return n.state===`loading`?(0,H.jsx)(ku,{className:`h-8 w-16`}):n.state===`missing`?null:(0,H.jsx)(`span`,{className:y5,children:(0,H.jsx)(N4,{model:n.model,field:n.field,value:n.value,format:t})})},Che=({node:e})=>{let{label:t,value:n,resource:r,filter:i,field:a,format:o,description:s}=eT(e),{resources:c}=J(),l=r===void 0?void 0:c[r];return(0,H.jsxs)(nT,{className:`relative h-full`,bodyClassName:`flex flex-col`,children:[(0,H.jsx)(`p`,{className:`text-muted-foreground break-words`,children:t}),(0,H.jsxs)(`div`,{className:`mt-auto pt-1`,children:[n!==void 0&&(0,H.jsx)(`span`,{className:y5,children:n}),l&&(0,H.jsx)(xhe,{model:l,filter:i}),a!==void 0&&(0,H.jsx)(She,{field:a,format:o})]}),s&&(0,H.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s})]})},b5=e=>e===null?`none`:`value:${e}`,whe=e=>{let t=gv(e);return t.length>0?t:mv(e)},The=(e,{context:{collisionRect:t,droppableRects:n,droppableContainers:r,over:i}})=>{let a=e.code===`ArrowRight`?1:e.code===`ArrowLeft`?-1:0;if(a===0||!t)return;e.preventDefault();let o=r.getEnabled().flatMap(e=>{let t=n.get(e.id);return t?[{id:e.id,rect:t}]:[]}).sort((e,t)=>e.rect.left-t.rect.left),s=t.left+t.width/2,c=i?o.findIndex(e=>e.id===i.id):o.findIndex(e=>e.rect.left<=s&&s<=e.rect.right),l=o[c+a];if(c!==-1&&l)return{x:l.rect.left+(l.rect.width-t.width)/2,y:l.rect.top}},x5=(e,t,n,r)=>{let i=yh({queryKey:[...n,`display`],enabled:r,initialPageParam:0,queryFn:({pageParam:e})=>t(e),getNextPageParam:(e,t)=>e.rows.length===40&&t.length*40<(t[0]?.total??0)?t.length:void 0}),a=i.data?.pages??[];return{resource:e.name,rows:a.flatMap(t=>t.rows.map(t=>EC(e,t))),total:a[0]?.total??0,loading:i.isPending,error:i.error,more:i.hasNextPage,loadMore:()=>void i.fetchNextPage()}},Ehe=({model:e,by:t,value:n,fields:r,filter:i,orderBy:a})=>{let{resources:o,views:s}=J(),c=$6({resources:o,views:s,model:e,columns:r,filter:rC(i,t,n),orderBy:a});return x5(e,c.page,c.key,!0)},Dhe=({model:e,view:t,display:n,column:r,fields:i,filter:a,orderBy:o,limit:s,moves:c,movable:l,dragged:u})=>{let d=Ehe({model:e,by:n.by,value:r.value,fields:i,filter:a,orderBy:o}),{setNodeRef:f,isOver:p}=fb({id:b5(r.value)}),m=iC(e,t,n),h=new Set(d.rows.map(e=>e.key)),g=new Map(c.map(e=>[e.row.key,e])),_=d.rows.filter(e=>g.has(e.key)&&g.get(e.key).to!==r.value),v=c.filter(e=>e.to===r.value&&!h.has(e.row.key)).map(e=>e.row),y=d.rows.filter(e=>!_.includes(e)).map(e=>g.has(e.key)?g.get(e.key).row:e),b=[...v,...y].slice(0,s),x=d.total-_.length+v.length;if(r.value===null&&!d.loading&&x===0&&!p)return null;let S=(t?.names?.plural??q(e.name)).toLowerCase(),C=t?.fields[n.by];return(0,H.jsxs)(`section`,{ref:f,"aria-label":`${r.label}, ${x}`,className:V(`flex w-72 shrink-0 snap-start flex-col gap-2 rounded-lg bg-surface p-2`,p&&`ring-2 ring-primary/30`),children:[(0,H.jsxs)(`header`,{className:`flex items-center justify-between gap-2 px-1 pt-0.5`,children:[(0,H.jsx)(`h2`,{className:`min-w-0 truncate text-xs font-medium`,children:r.value===null?(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:r.label}):(0,H.jsx)(M4,{value:r.value,hints:C,children:r.label})}),!d.loading&&(0,H.jsx)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:x.toLocaleString(`en-IE`)})]}),d.loading?Array.from({length:3},(e,t)=>(0,H.jsx)(ku,{className:`h-20`},t)):d.error?(0,H.jsx)(pS,{title:`Could not load rows`,error:d.error}):b.length===0?(0,H.jsxs)(`p`,{className:`px-1 py-4 text-center text-xs text-muted-foreground`,children:[`No `,S]}):(0,H.jsx)(`ul`,{className:`flex flex-col gap-2`,children:b.map(n=>(0,H.jsx)(`li`,{children:(0,H.jsx)(Ohe,{model:e,view:t,card:m,row:n,movable:l&&Iw(n.record,`update`),dragged:u})},n.key))}),s===void 0&&d.more&&(0,H.jsx)(W,{size:`sm`,variant:`ghost`,onClick:d.loadMore,children:`Show more`})]})},Ohe=({model:e,view:t,card:n,row:r,movable:i,dragged:a})=>{let{setNodeRef:o,setActivatorNodeRef:s,listeners:c,isDragging:l}=cb({id:r.key,data:{row:r},disabled:!i});return(0,H.jsx)(`div`,{ref:e=>{o(e),s(e?.querySelector(`a`)??e)},...c,onDragStart:e=>e.preventDefault(),onClickCapture:e=>{a()&&(e.preventDefault(),e.stopPropagation())},className:V(i&&`cursor-grab touch-manipulation`,l&&`opacity-40`),children:(0,H.jsx)(l5,{model:e,view:t,display:n,row:r,swipe:!1})})},khe=(e,t)=>{let n=K(),r=Ig(),i=Xw(),[a,s]=(0,o.useState)([]),c=e=>s(t=>t.filter(t=>t.row.key!==e)),l=vh({mutationFn:({row:r,to:i})=>{let a=typeof r.record.etag==`string`?r.record.etag:`*`;return n.update(e.name,Ag(e,r.record),{[t]:i.value},a)},onMutate:({row:e,to:n})=>{let r={...e,record:{...e.record,[t]:n.value}};s(t=>[...t.filter(t=>t.row.key!==e.key),{row:r,to:n.value}])},onError:(e,{row:t,to:n})=>{c(t.key),r.show({state:`error`,title:`Could not move it to ${n.label}`,description:aC(e)})},onSettled:async(t,n,{row:r})=>{await i(e.name),c(r.key)}});return{moves:a,move:(e,t)=>l.mutate({row:e,to:t})}},S5=({model:e,view:t,display:n,fields:r,filter:i,orderBy:a,limit:s})=>{let c=nC(e,t,n),l=iC(e,t,n),u=Fw(d_(e.name),`update`)&&!e.fields[n.by]?.readOnly,{moves:d,move:f}=khe(e,n.by),[p,m]=(0,o.useState)(),h=(0,o.useRef)(!1),g=nv(tv(uy,{activationConstraint:{distance:4}}),tv(fy,{activationConstraint:{delay:250,tolerance:5}}),tv(ny,{keyboardCodes:{start:[`Space`],cancel:[`Escape`],end:[`Space`,`Enter`]},coordinateGetter:The})),_=e=>String(e.labels[l.title]??e.record[l.title]??e.key),v=e=>c.find(t=>b5(t.value)===e),y=e=>e.record[n.by]??null;return(0,H.jsxs)(ib,{sensors:g,collisionDetection:whe,onDragStart:({active:e})=>{h.current=!0,m(e.data.current.row)},onDragEnd:({active:e,over:t})=>{m(void 0),setTimeout(()=>h.current=!1);let n=e.data.current.row,r=t?v(t.id):void 0;r&&r.value!==y(n)&&f(n,r)},onDragCancel:()=>{m(void 0),setTimeout(()=>h.current=!1)},accessibility:{announcements:{onDragStart:({active:e})=>`Picked up ${_(e.data.current.row)}.`,onDragOver:({active:e,over:t})=>`${_(e.data.current.row)} is over ${t?v(t.id)?.label:`no column`}.`,onDragEnd:({active:e,over:t})=>t?`${_(e.data.current.row)} was moved to ${v(t.id)?.label}.`:`${_(e.data.current.row)} was put back.`,onDragCancel:({active:e})=>`Moving ${_(e.data.current.row)} was cancelled.`},screenReaderInstructions:{draggable:`To move a card to another column, press Space, move it with the left and right arrow keys, and press Space again to drop it there. Escape puts it back.`}},children:[(0,H.jsx)(`div`,{className:`min-w-0 flex-1 overflow-x-auto`,children:(0,H.jsx)(`div`,{className:`flex snap-x items-start gap-3 pb-2`,children:c.map(o=>(0,H.jsx)(Dhe,{model:e,view:t,display:n,column:o,fields:r,filter:i,orderBy:a,limit:s,moves:d,movable:u,dragged:()=>h.current},b5(o.value)))})}),(0,H.jsx)(wb,{children:p&&(0,H.jsx)(l5,{model:e,view:t,display:l,row:p,swipe:!1})})]})},Ahe=({list:e,empty:t,loading:n,children:r})=>(0,H.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:e.loading?n:e.error?(0,H.jsx)(pS,{title:`Could not load rows`,error:e.error}):e.rows.length===0?(0,H.jsx)(`p`,{className:`py-8 text-center text-muted-foreground`,children:t}):r}),jhe=({list:e})=>(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-3 py-3 text-xs text-muted-foreground`,children:[(0,H.jsxs)(`span`,{children:[e.rows.length.toLocaleString(`en-IE`),` of `,e.total.toLocaleString(`en-IE`)]}),e.more&&(0,H.jsx)(W,{size:`sm`,onClick:e.loadMore,children:`Show more`})]}),C5=`grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3`,Mhe=`flex snap-x snap-mandatory gap-3 overflow-x-auto pb-1`,Nhe=({model:e,view:t,display:n,list:r,row:i=!1,footer:a=!0})=>{let o=(t?.names?.plural??q(e.name)).toLowerCase();return(0,H.jsxs)(Ahe,{list:r,empty:`No ${o} match.`,loading:(0,H.jsx)(`div`,{className:C5,children:Array.from({length:6},(e,t)=>(0,H.jsx)(ku,{className:`h-24`},t))}),children:[(0,H.jsx)(`ul`,{className:i?Mhe:C5,"aria-label":t?.names?.plural??q(e.name),children:r.rows.map(r=>(0,H.jsx)(`li`,{className:V(i&&`w-64 shrink-0 snap-start`),children:(0,H.jsx)(l5,{model:e,view:t,display:n,row:r,swipe:!i})},r.key))}),a&&(0,H.jsx)(jhe,{list:r})]})},w5=(0,o.createContext)(void 0),Phe=({value:e,children:t})=>(0,H.jsx)(w5.Provider,{value:e,children:t}),Fhe=()=>{let e=(0,o.useContext)(w5);if(!e)throw Error(`useListDisplay is used inside a list display, which the list page draws`);return e},Ihe=()=>(0,o.useContext)(w5),T5=({display:e,list:t})=>{let{components:n}=Xg(),r=n?.[e.component];return r?(0,H.jsx)(Phe,{value:t,children:(0,H.jsx)(`div`,{className:`min-w-0 flex-1 overflow-x-auto`,children:(0,H.jsx)(tg,{name:e.component,children:(0,H.jsx)(r,{...ho(e.props??{})})})})}):(0,H.jsxs)(eg,{children:[`No component is registered as `,e.component,`. Export it from protobase.ui.tsx, or load the plugin that provides it.`]})},E5=uo(),Lhe={bounds:{south:-90,west:-180,north:90,east:180},zoom:0},Rhe=22,D5=e=>Math.floor(e*1e6)/1e6,O5=e=>Math.ceil(e*1e6)/1e6,k5=e=>((e+180)%360+360)%360-180,zhe=(e,t)=>{let n=[E5.gte(e.latitude,D5(Math.max(t.south,-90))),E5.lte(e.latitude,O5(Math.min(t.north,90)))];if(t.east-t.west>=360)return E5.and(...n);let r=E5.gte(e.longitude,D5(k5(t.west))),i=E5.lte(e.longitude,O5(k5(t.east)));return k5(t.west)<=k5(t.east)?E5.and(...n,r,i):E5.and(...n,E5.or(r,i))},Bhe=(e,t,n)=>{let r=Ya(zhe(t,n));return e.trim()===``?r:`(${e}) AND ${r}`},Vhe=e=>Math.min(Math.max(Math.floor(e),0),Rhe),Hhe=(e,t)=>{let n=[...e.map(e=>({south:e.latitude,west:e.longitude,north:e.latitude,east:e.longitude})),...t.map(e=>e.bounds)];if(n.length!==0)return{south:Math.min(...n.map(e=>e.south)),west:Math.min(...n.map(e=>e.west)),north:Math.max(...n.map(e=>e.north)),east:Math.max(...n.map(e=>e.east))}},A5=e=>{if(typeof e==`number`)return e;if(typeof e==`string`&&e.trim()!==``)return Number(e)},j5=(e,t)=>{let n=A5(e[t.latitude]),r=A5(e[t.longitude]);if(n!==void 0&&r!==void 0&&Math.abs(n)<=90&&Math.abs(r)<=180)return{latitude:n,longitude:r}},Uhe=6371008.8,M5=64,N5=(e,t)=>t.approximate===void 0?t.exact!==void 0&&e[t.exact]===!1:e[t.approximate]===!0,P5=(e,t)=>{let n=t/Uhe,r=e.latitude*Math.PI/180,i=e.longitude*Math.PI/180;return{type:`Polygon`,coordinates:[Array.from({length:65},(e,t)=>{let a=t%M5/M5*2*Math.PI,o=Math.asin(Math.sin(r)*Math.cos(n)+Math.cos(r)*Math.sin(n)*Math.cos(a));return[(i+Math.atan2(Math.sin(a)*Math.sin(n)*Math.cos(r),Math.cos(n)-Math.sin(r)*Math.sin(o)))*180/Math.PI,o*180/Math.PI]})]}},Whe=e=>Array.isArray(e)&&e.length>=2&&typeof e[0]==`number`&&typeof e[1]==`number`&&Math.abs(e[0])<=180&&Math.abs(e[1])<=90,F5=(e,t)=>Array.isArray(e)&&e.length>=t&&e.every(Whe),I5=e=>Array.isArray(e)&&e.length>0&&e.every(e=>F5(e,4)),Ghe=e=>Array.isArray(e)&&e.length>0&&e.every(e=>F5(e,2)),Khe=e=>{if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch(e){if(e instanceof SyntaxError)return;throw e}},qhe=e=>{let t=Khe(e);if(typeof t!=`object`||!t)return;let n=t.type===`Feature`?t.geometry:t;if(typeof n!=`object`||!n)return;let{type:r,coordinates:i}=n;if(r===`Polygon`&&I5(i)||r===`MultiPolygon`&&Array.isArray(i)&&i.length>0&&i.every(I5)||r===`LineString`&&F5(i,2)||r===`MultiLineString`&&Ghe(i))return{type:r,coordinates:i}},Jhe=(e,t,n)=>{if(!N5(e,t))return;let r=t.area===void 0?void 0:qhe(e[t.area]);if(r)return r;let i=t.radius===void 0?void 0:A5(e[t.radius]);return i!==void 0&&Number.isFinite(i)&&i>0?P5(n,i):t.defaultRadius===void 0?void 0:P5(n,t.defaultRadius)},L5=(e,t)=>e.flatMap(e=>{let n=j5(e.record,t);if(!n)return[];if(!N5(e.record,t))return[{key:e.key,...n}];let r=Jhe(e.record,t,n);return[{key:e.key,...n,approximate:!0,...r&&{area:r}}]}),Yhe=(e,t)=>{let n=[];for(let r of e){let e=n.find(e=>Math.hypot(e.at.x-r.x,e.at.y-r.y)<=t);e?e.keys.push(r.key):n.push({at:r,keys:[r.key]})}return n.map(e=>({keys:e.keys,at:e.at.key}))},Xhe=(e,t)=>{if(!e)return;let n=new Set(t.map(e=>e.key)),r=e.keys.filter(e=>n.has(e));if(r.length===0)return;let i=r.indexOf(e.keys[e.index]);return{keys:r,index:Math.max(i,0)}},R5=(e,t)=>({keys:e.keys,index:((e.index+t)%e.keys.length+e.keys.length)%e.keys.length}),Zhe=({model:e,display:t,fields:n,filter:r,orderBy:i,area:a})=>{let o=K(),{resources:s,views:c}=J(),l={latitude:t.latitude,longitude:t.longitude},u=a?Bhe(r,l,a.bounds):``,d=a?Vhe(a.zoom):0;return _h({queryKey:G.map(e.name,`${l.latitude},${l.longitude}`,d,u,i),enabled:a!==void 0,placeholderData:pm,queryFn:async()=>{let t=await o.map(e.name,{...l,zoom:d,filter:u,orderBy:i,labels:k4(s,c,e,n),photos:$S(c[e.name])});return{rows:A4(s,e,n,eC(e,t.items,t.photos),t.labels).map(t=>EC(e,t)),buckets:t.buckets,total:t.totalSize}}})},Qhe=(0,o.lazy)(()=>Xh(()=>import(`./records-map-BAI2D9VS.js`).then(e=>({default:e.RecordsMap})),__vite__mapDeps([4,1,2,5,6,3,7]))),$he=250,z5=`flex size-8 items-center justify-center rounded-full border border-border bg-background hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,B5=({model:e,view:t,display:n,filter:r,orderBy:i,fields:a,at:s,onMove:c,footer:l=!0,flush:u=!1})=>{let d=J().maps,f=d?.style,[p,m]=(0,o.useState)(),[h,g]=(0,o.useState)(),_=g8(h,$he),[v,y]=(0,o.useState)(s===void 0),b=Zhe({model:e,display:n,fields:a,filter:r,orderBy:i,area:v?Lhe:_}),x=b.isPlaceholderData?void 0:b.data,S=b.data?.rows??[],C=b.data?.buckets??[],w=L5(S,n),T=v&&x?Hhe(L5(x.rows,n),x.buckets):void 0,E=xC(t,n),D=(t?.names?.plural??q(e.name)).toLowerCase(),O=(t?.names?.singular??q(e.name)).toLowerCase(),k=Xhe(p,S),A=k&&S.find(e=>e.key===k.keys[k.index]),j=new Set(w.filter(e=>e.approximate).map(e=>e.key)),M=e=>{let t=e.filter(e=>j.has(e)).length;return e.length===1?t===1?`Show the ${O}, at an approximate position`:`Show the ${O}`:t===0?`Show ${e.length} ${D}`:t===e.length?`Show ${e.length} ${D}, at approximate positions`:`Show ${e.length} ${D}, ${t} at approximate positions`},N=e=>`Zoom in on ${e.toLocaleString(`en-IE`)} ${e===1?O:D}`,ee=(0,o.useRef)(null),[P,te]=(0,o.useState)(0);if((0,o.useLayoutEffect)(()=>te(ee.current?.offsetHeight??0),[A?.key]),!f)return(0,H.jsx)(eg,{children:`The map display needs a map style: set PROTOBASE_MAP_STYLE_URL.`});let F=x?.total===0;return(0,H.jsxs)(`div`,{className:V(`flex h-full min-h-[36rem] flex-1 flex-col sm:min-h-[28rem]`,u&&`max-md:-mx-5 max-md:-mb-4 max-md:min-h-0`),children:[(0,H.jsxs)(`div`,{className:V(`relative min-h-0 flex-1 overflow-hidden rounded-lg border border-border bg-muted`,u&&`max-md:rounded-none max-md:border-0`),children:[(0,H.jsx)(o.Suspense,{fallback:null,children:(0,H.jsx)(Qhe,{style:f,layers:d?.layers,initial:s,points:w,buckets:C,fit:T,onFitted:()=>y(!1),onMove:(e,t)=>{g(e),c?.(t)},selected:k?.keys,covered:k?P:0,onSelect:e=>m({keys:e,index:0}),onClear:()=>m(void 0),markerLabel:M,bucketLabel:N})}),b.error&&(0,H.jsx)(`div`,{className:`absolute inset-x-3 top-3 z-10`,children:(0,H.jsx)(pS,{title:`Could not load rows`,error:b.error})}),F&&(0,H.jsx)(`div`,{className:`pointer-events-none absolute inset-x-3 top-3 z-10 flex justify-center`,children:(0,H.jsxs)(`p`,{className:`pointer-events-auto flex items-center gap-3 rounded-full border border-border bg-background px-4 py-1.5 text-muted-foreground shadow`,role:`status`,children:[v?`No ${D} match.`:`No ${D} in this part of the map.`,!v&&(0,H.jsx)(W,{size:`sm`,onClick:()=>y(!0),children:`Show all`})]})}),k&&A&&(0,H.jsx)(`div`,{ref:ee,className:`pointer-events-none absolute inset-x-3 bottom-3 z-10 flex justify-center`,children:(0,H.jsxs)(`div`,{className:`pointer-events-auto flex w-full max-w-[16rem] flex-col gap-2 sm:max-w-xs`,role:`group`,"aria-label":`Chosen ${O}`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-end gap-1.5`,children:[j.has(A.key)&&(0,H.jsxs)(`span`,{className:`mr-auto flex items-center gap-1 rounded-full border border-border bg-background px-2 py-1 text-xs`,children:[(0,H.jsx)(ke,{className:`size-3.5`,"aria-hidden":!0}),`Approximate position`]}),k.keys.length>1&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`button`,{type:`button`,"aria-label":`Previous`,className:z5,onClick:()=>m(R5(k,-1)),children:(0,H.jsx)(ye,{className:`size-4`,"aria-hidden":!0})}),(0,H.jsxs)(`span`,{className:`rounded-full border border-border bg-background px-2 py-1 text-xs tabular-nums`,"aria-live":`polite`,children:[k.index+1,` / `,k.keys.length]}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Next`,className:z5,onClick:()=>m(R5(k,1)),children:(0,H.jsx)(xe,{className:`size-4`,"aria-hidden":!0})})]}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Close`,className:z5,onClick:()=>m(void 0),children:(0,H.jsx)(Qn,{className:`size-4`,"aria-hidden":!0})})]}),(0,H.jsx)(`div`,{className:`shadow-lg`,children:(0,H.jsx)(l5,{model:e,view:t,display:E,row:A})})]})})]}),l&&(0,H.jsx)(`p`,{className:`hidden py-3 text-xs text-muted-foreground md:block`,children:ege(b.data,D)})]})},ege=(e,t)=>{if(!e)return`\xA0`;let n=e.total.toLocaleString(`en-IE`);return e.buckets.length===0&&e.rows.length<e.total?`${e.rows.length.toLocaleString(`en-IE`)} of ${n} ${t} in view`:`${n} ${t} in view`},tge=(e,t,n)=>{if(n!==0){if(e===`Home`)return 0;if(e===`End`)return n-1;if(e===`ArrowDown`)return t<0?0:(t+1)%n;if(e===`ArrowUp`)return t<0?n-1:(t-1+n)%n}},V5=({value:e,options:t,onChange:n,label:r})=>{let[i,a]=(0,o.useState)(!1),s=(0,o.useRef)(null),c=(0,o.useRef)(null),l=(0,o.useRef)([]),u=t.findIndex(t=>t.value===e),d=t[u];(0,o.useEffect)(()=>{if(!i)return;l.current[Math.max(u,0)]?.focus();let e=e=>{e.target instanceof Node&&!s.current?.contains(e.target)&&a(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[i]);let f=()=>{a(!1),c.current?.focus()};return(0,H.jsxs)(`div`,{ref:s,className:`relative shrink-0`,children:[(0,H.jsxs)(`button`,{ref:c,type:`button`,"aria-label":d?`${r}: ${d.label}`:r,"aria-haspopup":`menu`,"aria-expanded":i,onClick:()=>a(!i),className:`inline-flex h-8 items-center gap-1.5 rounded-md border border-border-strong bg-background px-2.5 text-body font-medium shadow-sm transition-colors hover:bg-muted pointer-coarse:h-11`,children:[d?.icon&&(0,H.jsx)(d.icon,{className:`size-3.5`}),d?.label??r,(0,H.jsx)(_e,{className:`size-3.5 text-muted-foreground`})]}),i&&(0,H.jsx)(`ul`,{role:`menu`,"aria-label":r,onKeyDown:e=>{if(e.key===`Escape`)return f();if(e.key===`Tab`)return a(!1);let n=tge(e.key,l.current.indexOf(document.activeElement),t.length);n!==void 0&&(e.preventDefault(),l.current[n]?.focus())},className:`absolute right-0 top-full z-30 mt-1 min-w-40 rounded-md border bg-background py-1 text-body shadow-pop`,children:t.map((t,r)=>(0,H.jsx)(`li`,{role:`none`,children:(0,H.jsxs)(`button`,{ref:e=>{l.current[r]=e},type:`button`,role:`menuitemradio`,"aria-checked":t.value===e,onClick:()=>{f(),t.value!==e&&n(t.value)},className:V(`flex min-h-9 w-full items-center gap-2 whitespace-nowrap px-3 py-1.5 text-left hover:bg-muted focus:bg-muted focus:outline-none pointer-coarse:min-h-11`,t.value===e&&`font-medium`),children:[t.icon?(0,H.jsx)(t.icon,{className:`size-3.5`}):(0,H.jsx)(`span`,{className:`size-3.5`}),(0,H.jsx)(`span`,{className:`flex-1`,children:t.label}),t.value===e&&(0,H.jsx)(he,{className:`size-3.5 text-primary-text`})]})},t.value))})]})},nge={table:Mn,cards:St,kanban:En,board:Fe,list:kt,calendar:de,map:nee},H5=({view:e,value:t,onChange:n,menu:r=!1,choices:i=hC(e)})=>{if(i.length<2)return null;let a=i.map(e=>({value:e.name,label:e.label,icon:e.icon===void 0?void 0:nge[e.icon]}));return r?(0,H.jsx)(V5,{label:`Display`,value:t,onChange:n,options:a}):(0,H.jsx)($u,{label:`Display`,size:`md`,value:t,onChange:n,options:a})},rge=[[`asc`,`ascending`],[`desc`,`descending`]],U5=({model:e,view:t,display:n,orderBy:r,onChange:i,className:a})=>{let o=OC(r),s=wC(e,t,n),c=s.includes(o.columnId)?s:[o.columnId,...s],l=e=>t?.fields[e]?.label??q(e);return(0,H.jsx)(`select`,{"aria-label":`Sort`,value:`${o.columnId} ${o.direction}`,onChange:e=>i(e.target.value),className:V(`h-8 rounded-md border border-border-strong bg-background px-2.5 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20`,a),children:c.flatMap(e=>rge.map(([t,n])=>(0,H.jsxs)(`option`,{value:`${e} ${t}`,children:[l(e),`, `,n]},`${e} ${t}`)))})},W5=(e,t,n,r)=>e.map(e=>{let i=t.fields[e.id],a=i&&rw(r,i,n?.fields[e.id]);return a?{...e,render:t=>(0,H.jsx)(ow,{shown:a,part:`cell`,field:i,value:t[e.id],fallback:S6(e,e.value?e.value(t):t[e.id])})}:e}),G5=e=>e.includes(`.`),ige=({model:e,row:t,column:n})=>{let r=L4(Gw(e,EC(e,t).record),n);return r.state===`loading`?(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`…`}):r.state===`missing`?(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`—`}):(0,H.jsx)(N4,{model:r.model,field:r.field,value:r.value})},age=(e,t,{resources:n,views:r})=>{let i=rc(n,e.name,t),a=i.ok?i.steps.at(-1):void 0,o=a?.field.name??t;return{id:t,header:r[a?.model.name??e.name]?.fields[o]?.label??q(o),kind:`text`,width:200,render:n=>(0,H.jsx)(ige,{model:e,row:n,column:t})}},K5=(e,t,n,r)=>{let i=new Map(W5(YS(e,t,[],n.filter(e=>!G5(e))),e,t,r.fieldTypes).map(e=>[e.id,e]));return n.flatMap(t=>G5(t)?[age(e,t,r)]:i.get(t)??[])},oge=(e,t,n)=>{if(!(e>=t))return`The first ${e} of ${n?`about `:``}${t.toLocaleString(`en-GB`)}.`},sge=({model:e,filter:t,orderBy:n,limit:r,fields:i})=>{let a=K(),{resources:o,views:s}=J();return _h({queryKey:[...G.list(e.name,t,n,r,`embedded`),i.join(`,`)],placeholderData:pm,queryFn:async()=>{let c=k4(o,s,e,i),l=$S(s[e.name]),u=await a.search(e.name,{filter:t||void 0,orderBy:n||void 0,pageSize:r,count:`exact`,labels:c,photos:l}),d=A4(o,e,i,eC(e,u.items,u.photos),u.labels).map((t,n)=>({...t,id:kg(e,u.items[n])}));return u.nextPageToken===``?{rows:d,total:d.length,estimated:!1}:{rows:d,total:u.totalSize??u.totalSizeEstimate,estimated:u.totalSize===void 0}}})},q5=({view:e,value:t,onChange:n})=>(0,H.jsx)(H5,{view:e,value:t,onChange:n,menu:!pu()}),cge=()=>(0,H.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,H.jsx)(ku,{className:`h-4 w-full`},t))}),J5=({model:e,view:t,filter:n,sort:r,columns:i,limit:a,display:s,empty:c,row:l=!1,viewAll:u,link:d=!0})=>{let{resources:f,views:p}=J(),{fields:m}=Xg(),{go:h,href:g}=PC(),_=mu(),[v,y]=(0,o.useState)(r||DC(e,t)),b=i??JS(e,t),x=(0,o.useMemo)(()=>K5(e,t,b,{resources:f,views:p,fieldTypes:m}),[e,t,b.join(`,`),f,p,m]),S=(0,o.useMemo)(()=>CC(e,t,x.map(e=>e.id)),[e,t,x]),C=sge({model:e,filter:n,orderBy:v,limit:a,fields:S}),T=C.data?.rows,E=(0,o.useMemo)(()=>T&&{total:T.length,rowAt:e=>T[e]},[T]),D=pC(t,s),O=t?.names?.plural??q(e.name),k=d&&(0,H.jsxs)(FC,{to:e8(e,t,_,u?{filter:u.filter,orderBy:DC(e,t),display:s,savedSearch:u.savedSearch}:{filter:n,orderBy:v,display:s}),onClick:u?.onOpen,className:`flex items-center gap-1 self-end font-medium text-primary-text hover:underline`,children:[u?u.label:(0,H.jsxs)(H.Fragment,{children:[`View all `,(0,H.jsx)(`span`,{className:`sr-only`,children:O.toLowerCase()})]}),(0,H.jsx)(w,{className:`size-3.5`,"aria-hidden":!0})]});if(C.isPending)return(0,H.jsx)(cge,{});if(C.error)return(0,H.jsx)(pS,{title:`Could not load`,error:C.error});if(!E||E.total===0){let e=(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:c??`Nothing here yet.`});return u&&d?(0,H.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[e,k]}):e}let A={resource:e.name,rows:C.data.rows.map(t=>EC(e,t)),total:C.data.total,loading:!1,error:null,more:!1,loadMore:()=>void 0},j=t=>h({kind:`record`,resource:e.name,key:Ag(e,t)}),M=t=>({href:g({kind:`record`,resource:e.name,key:Ag(e,t)}),onFollow:()=>j(t)}),N=t?.names?.singular??q(e.name),ee=oge(E.total,C.data.total,C.data.estimated);return(0,H.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[D?D.kind===`cards`?(0,H.jsx)(Nhe,{model:e,view:t,display:D,list:A,row:l||_,footer:!1}):D.kind===`map`?(0,H.jsx)(B5,{model:e,view:t,display:D,filter:n,orderBy:v,fields:S,footer:!1}):D.kind===`board`?(0,H.jsx)(S5,{model:e,view:t,display:D,fields:S,filter:n,orderBy:v,limit:a}):(0,H.jsx)(T5,{display:D,list:A}):(0,H.jsx)(J6,{fit:!0,columns:x,source:E,latencyMs:0,sort:OC(v),onSortChange:e=>y(kC(e)),onOpenRow:j,rowLink:M,rowActions:[{label:`Open ${N.toLowerCase()}`,onSelect:j}],rowNumbers:!1,selectable:!1}),ee&&d?(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:ee}),k]}):k]})},Y5=(e,t,n)=>{let r=mu(),i=ome(t),[a,s]=(0,o.useState)(()=>sme(localStorage,i)),c=(0,o.useCallback)(e=>{s(e),cme(localStorage,i,e)},[i]);return[lme(e,r,{picked:a,preferred:n}),c]},lge=({model:e,view:t,filter:n=``,sort:r=``,columns:i,limit:a=10,display:o,title:s,description:c,empty:l,actions:u})=>{let[d,f]=Y5(t,`page:${e.name}:${s??``}:${n}`,o);return(0,H.jsx)(nT,{title:s,description:c,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(q5,{view:t,value:d,onChange:f}),u]}),className:`h-full`,children:(0,H.jsx)(J5,{model:e,view:t,filter:n,sort:r,columns:i,limit:a,display:d,empty:l})})},uge={Page:Wue,Grid:Mue,Card:iT,Stat:Che,RecordCard:que,Field:Due,Table:({node:e,slots:t})=>{let n=eT(e),{resources:r,views:i}=J(),a=r[n.resource];return a?(0,H.jsx)(lge,{...n,model:a,view:i[a.name],actions:t.actions}):null},CardRow:oT,RecordRow:yhe,Chart:xue,Progress:Gue,ModalForm:Uue,Action:tT,Show:bhe,Link:Nue},X5=e=>typeof e==`string`||!e.custom&&e.type===`Link`,Z5=e=>{let t=[];for(let n of e){let e=t.at(-1);X5(n)&&e&&X5(e[0])?e.push(n):t.push([n])}return t.map((e,t)=>{let[n]=e;return X5(n)?(0,H.jsx)(`p`,{className:`leading-6`,children:e.map((e,t)=>typeof e==`string`?(0,H.jsx)(o.Fragment,{children:e},t):(0,H.jsx)(Q5,{node:e},t))},t):(0,H.jsx)(Q5,{node:n},t)})},dge=e=>Xs(e)||Array.isArray(e)&&e.length>0&&e.every(Xs),fge=e=>Object.fromEntries(Object.entries(e.props).flatMap(([e,t])=>dge(t)?[[e,(0,H.jsx)(H.Fragment,{children:Z5(Array.isArray(t)?t:[t])})]]:[])),Q5=({node:e})=>{let{components:t}=Xg();if(e.custom){let n=t?.[e.type];return n?(0,H.jsx)(tg,{name:e.type,children:(0,H.jsx)(n,{...ho(e.props),children:e.children.length>0?Z5(e.children):void 0})}):(0,H.jsxs)(eg,{children:[`No component is registered as `,e.type,`. Export it from protobase.ui.tsx, or load the plugin that provides it.`]})}let n=uge[e.type];return n?(0,H.jsx)(n,{node:e,slots:fge(e),children:Z5(e.children)}):(0,H.jsxs)(eg,{children:[e.type,` is not a block this version of the app knows.`]})},$5=({name:e})=>{let t=J().pages[e];return t?(0,H.jsx)(Q5,{node:t.tree}):(0,H.jsxs)(u_,{title:`Not found`,children:[`There is no page called `,e,`.`]})},pge=2e3,e7=(e,t)=>{let n=Ig(),[r,i]=(0,o.useState)(`idle`),[a,s]=(0,o.useState)(),c=(0,o.useRef)(void 0);return(0,o.useEffect)(()=>()=>clearTimeout(c.current),[]),{phase:r,message:a,run:async r=>{let a=e===`toast`?n.show({state:`loading`,title:`Saving ${t}...`}):void 0;s(void 0),e===`button`&&i(`saving`);try{return await r(),a!==void 0&&n.update(a,{state:`success`,title:`${t} saved`}),e===`button`&&(i(`saved`),c.current=setTimeout(()=>i(`idle`),pge)),!0}catch(t){if(!Fs(t))throw t;let r=t.status===412?`Changed by someone else`:`Could not save`,o=Rue(t);return a!==void 0&&n.update(a,{state:`error`,title:r,description:o}),e===`button`&&(i(`idle`),s(`${r}: ${o}`)),!1}}}},t7=({title:e,eyebrow:t,submit:n,saving:r,disabled:i,error:a,errorTitle:o=`Not saved`,onSubmit:s,onCancel:c,children:l,ref:u})=>{let d=(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[c&&(0,H.jsx)(W,{className:`max-sm:min-h-11`,onClick:c,children:`Cancel`}),(0,H.jsx)(W,{variant:`primary`,type:`submit`,className:`max-sm:min-h-11 max-sm:flex-1`,loading:r,disabled:i,children:n})]}),f=a!==void 0&&(0,H.jsx)(`div`,{className:`mt-4`,children:(0,H.jsx)(pS,{title:o,error:a})}),p=(0,H.jsx)(`div`,{className:`divide-y divide-border`,children:l}),m=e=>{e.preventDefault(),s()};return e===void 0?(0,H.jsxs)(`form`,{ref:u,className:`max-w-[760px]`,onSubmit:m,children:[f,p,(0,H.jsx)(`footer`,{className:`border-t pt-6 sm:flex sm:justify-end`,children:d})]}):(0,H.jsx)(`form`,{ref:u,className:`flex-1`,onSubmit:m,children:(0,H.jsxs)(`div`,{className:`mx-auto max-w-[760px] px-4 py-6 md:px-10 md:py-8`,children:[(0,H.jsxs)(`header`,{className:`flex flex-col gap-4 border-b pb-6 sm:flex-row sm:items-end sm:justify-between sm:gap-6`,children:[(0,H.jsxs)(`div`,{children:[t&&(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:t}),(0,H.jsx)(`h1`,{className:`mt-1 text-2xl font-semibold tracking-tight`,children:e})]}),d]}),f,p]})})},mge=({noun:e,collection:t,sections:n,saving:r,message:i,onSubmit:a,onCancel:o,ref:s})=>(0,H.jsx)(t7,{ref:s,title:`New ${e.toLowerCase()}`,eyebrow:t,submit:`Create ${e.toLowerCase()}`,saving:r,error:i?Error(i):void 0,errorTitle:`Not created`,onSubmit:a,onCancel:o,children:n.map(e=>(0,H.jsx)(xx,{title:e.title,help:e.help,children:(0,H.jsx)(`div`,{className:`grid grid-cols-1 gap-x-6 gap-y-5 sm:grid-cols-2`,children:e.fields.map(e=>(0,H.jsx)(bx,{name:e.name,label:e.label,required:e.required,help:e.help,error:e.error,wide:e.wide,children:e.editor},e.name))})},e.title))}),hge=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),gge=({resource:e,values:t})=>{let n=J(),r=n.resources[e],i=d_(e);return r?Fw(i,`create`)?(0,H.jsx)(_ge,{resource:e,values:t}):(0,H.jsxs)(u_,{title:`Not allowed`,children:[`You cannot create `,n.views[e]?.names?.plural.toLowerCase()??e,`.`]}):(0,H.jsxs)(u_,{title:`Not found`,children:[`There is no resource called `,e,`.`]})},_ge=({resource:e,values:t})=>{let n=J(),r=n.resources[e],i=n.views[e],a=K(),s=Up(),{go:c}=PC(),l=i?.names?.singular??q(e),u=e7(i?.saveFeedback??`toast`,`New ${l.toLowerCase()}`),d=aS(r,i),[f,p]=(0,o.useState)(()=>uS(r,d,t)),[m,h]=(0,o.useState)({}),[g,_]=(0,o.useState)(0),v=U4(g);(0,o.useEffect)(()=>{for(let[e,i]of Object.entries(t??{})){let t=n.resources[r.fields[e]?.relation?.resource??``];t&&D4(s,a,t,[i],n.views[t.name]).then(t=>{let n=t.get(i);n&&p(t=>rS(t[e])&&t[e].key===i?{...t,[e]:{key:i,label:n}}:t)})}},[t,n,r,a,s]);let y=(e,t)=>{h(t=>hge(t,e)),p(n=>({...n,[e]:t}))},b=()=>u.run(async()=>{let t;try{t=await a.create(e,sS(r,n.resources,f))}catch(e){let t=H4(e);throw h(t),Object.keys(t).length>0&&_(e=>e+1),e}for(let t of[`page`,`list`,`first-page`,`map`,`facets`,`series`])s.invalidateQueries({queryKey:[t,e]});c({kind:`record`,resource:e,key:Ag(r,t.record)},{replace:!0})}),x=d.map(e=>({title:e.title,help:e.help,fields:e.fields.map(e=>{let t=r.fields[e],a=f[e],o=t.relation?n.resources[t.relation.resource]:void 0,s=i?.fields[e]?.label??q(e),c=m[e];return{name:e,label:s,help:i?.fields[e]?.help,required:cS(t),error:c&&V4(t,s,c),wide:!!(i?.fields[e]?.multiline||i?.fields[e]?.markdown),editor:(0,H.jsx)(mw,{field:t,hints:i?.fields[e],value:rS(a)?a.key:a??(t.type!==`boolean`&&``),stored:void 0,relationLabel:rS(a)?a.label:void 0,placeholder:dS(t)?`Set by the database`:void 0,relationPicker:o?{target:o,view:n.views[o.name]}:void 0,invalid:!!m[e],resource:r.name,onChange:t=>y(e,t)})}})}));return(0,H.jsx)(mge,{ref:v,noun:l,collection:i?.names?.plural??q(e),sections:x,saving:u.phase===`saving`,message:u.message,onSubmit:()=>void b(),onCancel:()=>c({kind:`list`,resource:e})})},vge=({resource:e,values:t})=>{let n=J(),r=n.views[e];return r?.create?n.pages[r.create.page]?(0,H.jsx)($5,{name:r.create.page}):(0,H.jsxs)(u_,{title:`Not allowed`,children:[`You cannot create `,r.names?.plural.toLowerCase()??q(e),`.`]}):(0,H.jsx)(gge,{resource:e,values:t},new URLSearchParams(t).toString())},yge=(e,t)=>{let n=new Map(t.map(e=>[e.value,e.count]));return e.map(([e,t])=>({value:e,label:t,...n.get(e)!==void 0&&{count:n.get(e)}}))},bge=(e,t)=>[...new Set(t.filter(t=>!e.includes(t)))],xge=uo(),Sge=(e,t)=>{let n=K(),[r,i]=(0,o.useState)({}),a=e=>!!e?.search?.length&&e.primaryKey.length===1,s=hh({queries:e.map(({id:e,target:i})=>{let o=(r[e]??``).trim();return{queryKey:[`reference-search`,e,i?.name??``,o],enabled:a(i)&&o!==``,placeholderData:pm,queryFn:async()=>{let e=i.primaryKey[0],r=Tg(i,t[i.name]);return(await n.list(i.name,{filter:Ya(xge.search(o)),fields:[e,r],pageSize:20})).items.map(t=>[String(t[e]),String(t[r])])}}})});return e.map(({id:e,target:t},n)=>{if(!a(t))return{};let o=t=>i(n=>({...n,[e]:t}));return(r[e]??``).trim()===``?{onSearch:o}:{onSearch:o,matches:s[n]?.data??[]}})},Cge=24,wge=({model:e,resources:t,views:n,view:r,state:i,extras:a})=>{let o=K(),s=Up(),c=F8(r,e),l=e=>r?.fields[e]?.label??q(e),u=n=>{let r=e.fields[n];return r?.type===`relation`&&r.relation?t[r.relation.resource]:void 0},d=c.facets.flatMap(e=>(e.flags?e.options.map(e=>e.value):[e.id]).map(t=>({group:e.id,field:t}))),f=hh({queries:d.map(({group:t,field:r})=>{let s=O8(c,{...i,facets:{...i.facets,[t]:[]}},a),l=u(r),d=l?.primaryKey.length===1?Tg(l,n[l.name]):void 0;return{queryKey:G.facets(e.name,r,s),queryFn:()=>o.facets(e.name,r,{filter:s,limit:50,...d&&{label:d}})}})}),p=(e,t)=>f[d.findIndex(n=>n.group===e&&n.field===t)]?.data,m=hh({queries:c.facets.map(t=>{let r=u(t.id),a=bge((p(t.id,t.id)??[]).flatMap(e=>e.value===null?[]:[String(e.value)]),i.facets[t.id]??[]);return{queryKey:G.labels(`facet:${e.name}.${t.id}`,a.join(`,`)),enabled:!!r&&a.length>0,queryFn:async()=>[...await D4(s,o,r,a,n[r.name])]}})}),h=Sge(c.facets.map(e=>({id:e.id,target:e.combobox?u(e.id):void 0})),n),g=c.ranges??[],_=hh({queries:g.map(t=>{let n=O8(c,l8(i,t.id,void 0),a),s=I8(r,t.id)?Cge:1;return{queryKey:G.histogram(e.name,t.id,s,n),queryFn:()=>o.histogram(e.name,t.id,{filter:n,buckets:s})}})});return{facets:c.facets.map((t,n)=>{if(t.flags){let e=t.options.map(({value:e})=>({value:e,label:l(e),count:p(t.id,e)?.find(e=>String(e.value)===`true`)?.count??0}));return{...t,options:e}}let i=e.fields[t.id],a=(p(t.id,t.id)??[]).flatMap(e=>e.label===void 0?[]:[[String(e.value),e.label]]),o=new Map([...a,...m[n]?.data??[]]),s=(p(t.id,t.id)??[]).flatMap(e=>e.value===null?[]:[{value:String(e.value),label:i?.type===`enum`?rs(String(e.value),r?.fields[t.id]?.valueLabels):o.get(String(e.value))??String(e.value),count:e.count}]),c=h[n];return{...t,label:l(t.id),options:c.matches?yge(c.matches,s):s,...o.size>0&&{labels:Object.fromEntries(o)},...c.onSearch&&{onSearch:c.onSearch}}}),ranges:g.flatMap((e,t)=>{let n=_[t]?.data;return!n||n.min===null||n.max===null?[]:[{...e,label:l(e.id),min:Math.floor(n.min),max:Math.ceil(n.max),step:Math.max(1,Math.round((n.max-n.min)/100)),histogram:I8(r,e.id)?n.buckets.map(e=>e.count):[],format:L8(r,e.id)}]}),...c.dateField&&{datePresets:c.datePresets??!0,dateField:c.dateField,dateKind:c.dateKind},toggles:c.toggles?.map(e=>({...e,label:l(e.id)}))}},Tge=uo(),Ege=({blockingPlural:e,noun:t})=>`${e} still point at this ${t.toLowerCase()}.`,Dge=({blockedBy:e,resources:t,views:n,noun:r,key:i})=>{let{resource:a,field:o}=e;if(!t[a])return;let s=n[a]?.names?.plural??q(a),c=Ege({blockingPlural:s,noun:r});if(!o||i===void 0)return{text:c};let l={kind:`list`,resource:a,filter:Ya(Tge.eq(o,i))};return{text:c,link:{label:`Show ${s.toLowerCase()}`,to:l}}},Oge=({title:e,noun:t,busy:n,onConfirm:r,onCancel:i})=>(0,H.jsx)(Sf,{title:`Delete ${e}?`,description:`This ${t.toLowerCase()} will be removed. This cannot be undone.`,onClose:i,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:i,children:`Cancel`}),(0,H.jsx)(W,{variant:`primary`,className:`bg-danger hover:bg-danger/90`,loading:n,onClick:r,children:`Delete`})]})}),kge=({title:e,changes:t,busy:n,onReview:r,onDeleteAnyway:i,onCancel:a})=>(0,H.jsx)(Sf,{title:`${e} was changed since you opened it`,description:`Someone saved this record in the meantime. Review what changed before you delete it.`,onClose:a,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:r,children:`Review changes`}),(0,H.jsx)(W,{variant:`primary`,className:`bg-danger hover:bg-danger/90`,loading:n,onClick:i,children:`Delete anyway`})]}),children:t.length===0?(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:`No visible fields differ; the record was saved again with the same values.`}):(0,H.jsx)(`ul`,{className:`divide-y rounded-md border`,children:t.map(e=>(0,H.jsxs)(`li`,{className:`grid grid-cols-[96px_1fr] gap-3 px-3 py-2`,children:[(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:e.label}),(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`span`,{className:`text-muted-foreground line-through`,children:e.before}),` `,(0,H.jsx)(`span`,{className:`font-medium`,children:e.after})]})]},e.field))})}),n7=e=>{if(e.stage===`confirm`)return(0,H.jsx)(Sf,{title:`Delete ${e.count} ${e.count===1?e.plural.replace(/s$/,``):e.plural.toLowerCase()}?`,description:`This cannot be undone. Each record is deleted only if it has not changed since the list loaded; anything that changed is reported and kept.`,onClose:e.onCancel,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:e.onCancel,children:`Cancel`}),(0,H.jsxs)(W,{variant:`primary`,className:`bg-danger hover:bg-danger/90`,onClick:e.onConfirm,children:[`Delete `,e.count]})]})});if(e.stage===`running`)return(0,H.jsx)(Sf,{title:`Deleting`,description:`${e.done} of ${e.total} done`,onClose:()=>void 0,actions:(0,H.jsx)(W,{loading:!0,disabled:!0,children:`Working`})});let t=e.total-e.failures.length;return(0,H.jsx)(Sf,{title:e.failures.length===0?`Deleted ${t}`:`Deleted ${t} of ${e.total}`,description:e.failures.length===0?void 0:`${e.failures.length} could not be deleted and were kept.`,onClose:e.onClose,actions:(0,H.jsx)(W,{variant:`primary`,onClick:e.onClose,children:`Done`}),children:e.failures.length>0&&(0,H.jsx)(`ul`,{className:`max-h-48 divide-y overflow-y-auto rounded-md border`,children:e.failures.map(e=>(0,H.jsxs)(`li`,{className:`px-3 py-2`,children:[(0,H.jsx)(`span`,{className:`font-medium`,children:e.title}),(0,H.jsx)(`span`,{className:`block text-xs text-danger-text`,children:e.message})]},e.title))})})},Age=new Set([`updated_at`,`updatedAt`]),jge=(e,t,n,r)=>Object.values(e.fields).flatMap(e=>{if(Age.has(e.name)||JSON.stringify(n[e.name]??null)===JSON.stringify(r[e.name]??null))return[];let i=t?.fields[e.name];return[{field:e.name,label:i?.label??q(e.name),before:ZS(e,n[e.name],i),after:ZS(e,r[e.name],i)}]}),Mge=4,r7=({model:e,view:t,onDeleted:n,onReview:r,restore:i})=>{let a=K(),s=Up(),c=Ig(),[l,u]=(0,o.useState)(),[d,f]=(0,o.useState)(!1),p=t?.names?.singular??q(e.name),m=t?.names?.plural??q(e.name),{resources:h,views:g}=J(),{href:_,open:v}=PC(),y=(t,n)=>t.blockedBy&&Dge({blockedBy:t.blockedBy,resources:h,views:g,noun:p,...e.primaryKey.length===1&&{key:n.key}}),b=()=>{for(let t of[`page`,`list`,`first-page`,`map`])s.invalidateQueries({queryKey:[t,e.name]});for(let t of[`facets`,`series`,`histogram`])s.invalidateQueries({queryKey:[t,e.name]})},x=async(t,n)=>{let r=n??(await a.get(e.name,t.key)).etag;try{await a.remove(e.name,t.key,{etag:r})}catch(e){if(!(e instanceof Ps))throw e;return e}},S=t=>{b(),u(void 0),n?.(t),c.show({state:`success`,title:`${t.title} deleted`,...e.softDelete&&i&&{action:{label:`Undo`,onClick:()=>{i(t).then(()=>{b(),c.show({state:`success`,title:`${t.title} restored`})},e=>{if(!Fs(e))throw e;b(),c.show({state:e.status===409?`success`:`error`,title:e.status===409?`${t.title} is already back`:`Could not restore ${t.title}`,description:e.status===409?void 0:e.message})})}}}})},C=async(n,r)=>{f(!0);try{if(!await x(n,r))return S(n);let i=(await a.get(e.name,n.key)).record;u({kind:`conflict`,target:n,fresh:i,changes:jge(e,t,n.snapshot,i)})}catch(e){if(!Fs(e))throw e;u(void 0);let t=y(e,n);c.show({state:`error`,title:`Could not delete ${n.title}`,description:t?.text??e.message,...t?.link&&{action:{label:t.link.label,href:_(t.link.to),onNavigate:v}}})}finally{f(!1)}},w=async e=>{try{return await x(e,e.etag)?{title:e.title,message:`Changed since the list loaded, so it was kept.`}:void 0}catch(t){if(!Fs(t))throw t;return{title:e.title,message:y(t,e)?.text??t.message}}},T=async e=>{let t=[],n=0;u({kind:`bulk-running`,done:n,total:e.length});let r=[...e];await Promise.all(Array.from({length:Math.min(Mge,e.length)},async()=>{for(let i=r.shift();i;i=r.shift()){let r=await w(i);r&&t.push(r),n+=1,u({kind:`bulk-running`,done:n,total:e.length})}})),b(),u({kind:`bulk-done`,total:e.length,failures:t})},E=()=>u(void 0);return{dialogs:l&&(0,H.jsxs)(H.Fragment,{children:[l.kind===`confirm`&&(0,H.jsx)(Oge,{title:l.target.title,noun:p,busy:d,onCancel:E,onConfirm:()=>void C(l.target,l.target.etag)}),l.kind===`conflict`&&(0,H.jsx)(kge,{title:l.target.title,changes:l.changes,busy:d,onCancel:E,onReview:()=>{E(),r?.(l.target,l.fresh)},onDeleteAnyway:()=>void C(l.target,`*`)}),l.kind===`bulk-confirm`&&(0,H.jsx)(n7,{stage:`confirm`,count:l.targets.length,plural:m,onCancel:E,onConfirm:()=>void T(l.targets)}),l.kind===`bulk-running`&&(0,H.jsx)(n7,{stage:`running`,done:l.done,total:l.total}),l.kind===`bulk-done`&&(0,H.jsx)(n7,{stage:`done`,total:l.total,failures:l.failures,onClose:E})]}),start:t=>e.softDelete?C(t,t.etag):u({kind:`confirm`,target:t}),startBulk:e=>u({kind:`bulk-confirm`,targets:e})}},i7=e=>{let t=K();return e.softDelete?async n=>void await t.undelete(e.name,n.key):void 0},Nge=(e,t,n)=>e?.create?Object.hasOwn(t,e.create.page):Fw(n,`create`),a7=e=>typeof e==`object`&&!!e,o7=e=>e===null||typeof e==`string`&&e.trim()===``,s7=e=>e===null?``:a7(e)?e.date.replace(`T`,` `):typeof e==`boolean`?e?`TRUE`:`FALSE`:String(e),c7=e=>e<26?String.fromCharCode(65+e):c7(Math.floor(e/26)-1)+c7(e%26),l7=(e,t)=>e[t]?.trim()?e[t]:`Column ${c7(t)}`,Pge=e=>/[",\r\n]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e,Fge=(e,t)=>{let n=[...t].sort((e,t)=>e.line-t.line).map(t=>[...e.map((e,n)=>s7(t.cells[n]??null)),String(t.line),t.problems.join(`; `)]);return`${[[...e,`Line`,`Problems`],...n].map(e=>e.map(Pge).join(`,`)).join(`\r
|
|
68
|
+
`)}\r\n`},u7=({label:e,counts:t})=>(0,H.jsx)(`dl`,{"aria-label":e,className:`grid grid-cols-2 gap-3 sm:grid-cols-4`,children:t.map(([e,t])=>(0,H.jsxs)(`div`,{className:`rounded-lg border px-3 py-2`,children:[(0,H.jsx)(`dt`,{className:`text-xs text-muted-foreground`,children:e}),(0,H.jsx)(`dd`,{className:`text-lg font-semibold tabular-nums`,children:t.toLocaleString(`en-IE`)})]},e))}),d7=(e,t)=>e?.fields[t]?.label??q(t),Ige=new Set([`text`,`integer`,`bigint`,`decimal`,`boolean`,`date`,`timestamp`,`uuid`,`enum`,`relation`,`currency`,`country`]),f7=(e,t)=>{let n=e.relation?t[e.relation.resource]:void 0;return n?.primaryKey.length===1?n:void 0},Lge=(e,t)=>Object.values(e.fields).filter(n=>n.readOnly||n.name===e.tenant||!Ige.has(n.type)?!1:n.type!==`relation`||f7(n,t)!==void 0),Rge=new Set([`text`,`integer`,`bigint`,`uuid`,`date`,`currency`,`country`,`enum`]),p7=e=>{let t=e.primaryKey.length===1?[e.fields[e.primaryKey[0]]]:[],n=Object.values(e.fields).filter(t=>t.filterable&&!t.sensitive&&Rge.has(t.type)&&!e.primaryKey.includes(t.name));return[...t,...n]},m7=(e,t)=>f7(e,t),h7=e=>!e.nullable&&!e.default,g7=e=>e.toLowerCase().replace(/[\s_-]+/g,``),_7=(e,t,n)=>{let r=new Set;return e.flatMap((e,i)=>{let a=g7(e);if(a===``)return[];let o=t.find(e=>!r.has(e.name)&&(g7(d7(n,e.name))===a||g7(e.name)===a));return o?(r.add(o.name),[{column:i,field:o.name}]):[]})},v7=(e,t,n)=>{if(e===`update`)return[];let r=new Set(n.map(e=>e.field));return t.filter(e=>h7(e)&&!r.has(e.name))},y7=e=>({ok:!0,value:e}),b7=e=>({ok:!1,problem:e}),x7=e=>`“${s7(e)}”`,S7=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),zge=(e,t)=>{let n=`[${S7(t===`.`?`,`:`.`)}\\s\\u00a0\\u202f']`,r=RegExp(`^([-+]?)(\\d{1,3}(?:${n}\\d{3})+|\\d+)(?:${S7(t)}(\\d+))?$`).exec(e.trim());if(r)return`${r[1]===`-`?`-`:``}${r[2].replace(/\D/g,``)}${r[3]?`.${r[3]}`:``}`;if(t===`.`&&/^[-+]?\d+(\.\d+)?e[-+]?\d+$/i.test(e.trim()))return String(Number(e.trim()))},C7=(e,t)=>{if(typeof e==`number`)return String(e);if(typeof e==`string`)return zge(e,t.decimal)},Bge=(e,t,n)=>{let r=C7(t,n);if(r===void 0)return b7(`${x7(t)} is not a number`);let[i,a=``]=r.split(`.`);if(/[1-9]/.test(a)||/e/i.test(r))return b7(`${x7(t)} is not a whole number`);if(e.type===`bigint`)return y7(String(BigInt(i)));let o=Number(i);return Number.isSafeInteger(o)?y7(o):b7(`${x7(t)} is too large`)},Vge=(e,t)=>{let n=C7(e,t);return n===void 0?b7(`${x7(e)} is not a number`):y7(n)},Hge=new Set([`true`,`yes`,`1`]),Uge=new Set([`false`,`no`,`0`]),Wge=e=>{if(typeof e==`boolean`)return y7(e);let t=typeof e==`string`||typeof e==`number`?String(e).trim().toLowerCase():``;return Hge.has(t)?y7(!0):Uge.has(t)?y7(!1):b7(`${x7(e)} is not true or false (true, false, yes, no, 1 or 0)`)},w7=e=>String(e).padStart(2,`0`),Gge=(e,t,n)=>{let r=new Date(Date.UTC(e,t-1,n));if(r.getUTCFullYear()===e&&r.getUTCMonth()===t-1&&r.getUTCDate()===n)return`${e}-${w7(t)}-${w7(n)}`},T7=`(\\d{1,2}):(\\d{2})(?::(\\d{2})(?:\\.\\d+)?)?`,Kge=(e,t)=>{let n=RegExp(`^(\\d{4})[-/](\\d{1,2})[-/](\\d{1,2})(?:[T ]${T7}(Z|[+-]\\d{2}:?\\d{2})?)?$`).exec(e.trim()),r=RegExp(`^(\\d{1,2})[./-](\\d{1,2})[./-](\\d{4})(?: ${T7})?$`).exec(e.trim());if(!n&&!r)return;let[i,a,o]=n?[n[1],n[2],n[3]].map(Number):t===`dmy`?[r[3],r[2],r[1]].map(Number):[r[3],r[1],r[2]].map(Number),s=Gge(i,a,o);if(!s)return;let[c,l,u=`0`]=n?n.slice(4,7):r.slice(4,7);if(c===void 0)return{date:s};if(!(Number(c)>23||Number(l)>59||Number(u)>59))return{date:s,time:`${w7(Number(c))}:${l}:${w7(Number(u))}`,zone:n?.[7]}},E7=(e,t)=>{if(a7(e)){let[t,n]=e.date.split(`T`);return{date:t,time:n}}return typeof e==`string`?Kge(e,t.dateOrder):void 0},D7=(e,t)=>b7(`${x7(e)} is not a date (2026-04-03 or ${t.dateOrder===`dmy`?`day/month/year`:`month/day/year`})`),qge=(e,t)=>{let n=E7(e,t);return n?n.time&&n.time!==`00:00:00`?b7(`${x7(e)} has a time of day; the field holds a date`):y7(n.date):D7(e,t)},Jge=(e,t)=>{let n=E7(e,t);if(!n)return D7(e,t);if(n.zone)return y7(new Date(`${n.date}T${n.time}${n.zone===`Z`?`Z`:n.zone.replace(/^([+-]\d{2})(\d{2})$/,`$1:$2`)}`).toISOString());let[r,i,a]=n.date.split(`-`).map(Number),[o,s,c]=(n.time??`00:00:00`).split(`:`).map(Number);return y7(new Date(r,i-1,a,o,s,c).toISOString())},O7=e=>e.trim().toLowerCase().replace(/\s+/g,` `),Yge=(e,t,n)=>{let r=e.enumValues??[],i=O7(s7(n)),a=r.filter(e=>O7(e)===i||O7(rs(e,t?.valueLabels))===i);return a.length===1?y7(a[0]):a.length>1?b7(`${x7(n)} matches more than one value: ${a.map(e=>rs(e,t?.valueLabels)).join(`, `)}`):b7(`${x7(n)} is not one of ${r.map(e=>rs(e,t?.valueLabels)).join(`, `)}`)},Xge=e=>typeof e==`boolean`?b7(`${x7(e)} is true or false, not text`):y7(s7(e)),k7=(e,t,n,r)=>{if(o7(n))return e.nullable?y7(null):b7(`is empty, and it is required`);switch(e.type){case`integer`:case`bigint`:return Bge(e,n,r);case`decimal`:return Vge(n,r);case`boolean`:return Wge(n);case`date`:return qge(n,r);case`timestamp`:return Jge(n,r);case`enum`:return Yge(e,t,n);case`text`:case`uuid`:case`currency`:case`country`:return Xge(n);default:throw Error(`Not implemented: importing ${e.type} fields, which importableFields leaves out`)}},Zge=(e,t)=>e[t]?.names?.singular??q(t),Qge=(e,t)=>e[t]?.names?.plural??q(t),$ge=(e,t,n)=>{let{model:r,resources:i,views:a}=n,o=a[r.name],s={},c={},l=[],u=[];for(let{column:n,field:d,matchBy:f}of t.columns){let p=r.fields[d],m=e.cells[n]??null,h=d7(o,d),g=m7(p,i);if(g&&!o7(m)){let e=f??g.primaryKey[0],n=k7(g.fields[e],a[g.name]?.fields[e],m,t.options);n.ok?u.push({field:d,finding:{model:g,field:e,value:n.value}}):l.push(`${h}: ${n.problem}`),s[d]=s7(m);continue}let _=k7(p,o?.fields[d],m,t.options);_.ok?c[d]=s[d]=_.value:l.push(`${h}: ${_.problem}`)}let d;if(t.match&&t.mode!==`create`){let n=r.fields[t.match.field],i=k7({...n,nullable:!1},o?.fields[n.name],e.cells[t.match.column]??null,t.options);i.ok?d={model:r,field:n.name,value:i.value}:l.push(`${d7(o,n.name)}: ${i.problem}`)}return{values:s,data:c,problems:l,relations:u,match:d}},A7=(e,t)=>{let n=e.lookups.keysOf(t.model.name,t.field,t.value),r=`${d7(e.views[t.model.name],t.field).toLowerCase()} “${String(t.value)}”`;return n.length===1?{key:n[0]}:n.length===0?{none:`no ${Zge(e.views,t.model.name).toLowerCase()} has ${r}`}:{several:`${n.length} ${Qge(e.views,t.model.name).toLowerCase()} have ${r}`}},e_e=e=>e.cells.every(o7),j7=async(e,t,n)=>{let{model:r,views:i}=n,a=e.filter(e=>!e_e(e)).map(e=>({row:e,...$ge(e,t,n)})),o=new Map;for(let e of a.flatMap(e=>[...e.relations.map(e=>e.finding),...e.match?[e.match]:[]])){let t=`${e.model.name}.${e.field}`;o.has(t)||o.set(t,{model:e.model,field:e.field,values:[]}),o.get(t).values.push(e.value)}for(let{model:e,field:t,values:r}of o.values())await n.lookups.load(e,t,r);return a.map(({row:e,values:a,data:o,problems:s,relations:c,match:l})=>{let u={...o};for(let{field:e,finding:t}of c){let a=A7(n,t);`key`in a?u[e]=a.key:s.push(`${d7(i[r.name],e)}: ${a.none??a.several}`)}let d=l&&A7(n,l);d?.several&&s.push(`Not one record: ${d.several}`),d?.none&&t.mode===`update`&&s.push(`Nothing to update: ${d.none}`);let f={line:e.line,cells:e.cells,values:a,problems:s};return s.length>0?f:d&&`key`in d?{...f,op:{op:`update`,resource:r.name,key:d.key,etag:`*`,data:u}}:{...f,op:{op:`create`,resource:r.name,data:u}}})},t_e=5,n_e=5,r_e=async(e,t)=>{let n=e.rows(t),{value:r=[]}=await n.next();await n.return(void 0);let[i,...a]=r;return{headers:(i?.cells??[]).map(s7),sample:a.slice(0,t_e)}};async function*M7(e,t){let n=!0;for await(let r of e.rows(t))yield n?r.slice(1):r,n=!1}var i_e=async(e,t,n,r,i,a)=>{let o={rows:0,creates:0,updates:0,problems:[],preview:[]};for await(let s of M7(e,t)){a?.throwIfAborted();for(let e of await j7(s,n,r))o.rows++,o.preview.length<n_e&&o.preview.push(e),e.op?.op===`create`?o.creates++:e.op?.op===`update`?o.updates++:o.problems.push({line:e.line,cells:e.cells,problems:e.problems});i(o.rows)}return o},a_e=(e,t)=>{if(!Fs(e))return[e.message];let n=e.errors.filter(e=>e.field);return n.length===0?[e.message]:n.map(e=>`${d7(t.views[t.model.name],e.field)}: ${e.message}`)},o_e=async(e,t,n,r,{client:i,onProgress:a,cancelled:o})=>{let s={created:0,updated:0,skipped:0,failed:0,notWritten:[]},c=async e=>{let t=[...e];for(;t.length>0;){let e=t.map(e=>e.op);try{let{results:t}=await i.batchWrite(e);for(let e of t)e.op===`create`?s.created++:e.op===`update`&&s.updated++;return}catch(e){let n=Fs(e)?e.operation:void 0;if(n===void 0||!t[n])throw e;let[i]=t.splice(n,1);s.failed++,s.notWritten.push({line:i.line,cells:i.cells,problems:a_e(e,r)})}}},l=[],u=async e=>{for(;l.length>=100||e&&l.length>0;){if(o())return!1;await c(l.splice(0,100)),a({...s})}return!0};for await(let i of M7(e,t)){for(let e of await j7(i,n,r))e.op?l.push(e):(s.skipped++,s.notWritten.push({line:e.line,cells:e.cells,problems:e.problems}));if(!await u(!1))return{...s,cancelled:!0}}return await u(!0)?{...s,cancelled:!1}:{...s,cancelled:!0}},N7=50,P7=(e,t,n)=>Of(Fge(t,n),`${(e??`import`).replace(/\.[^.]+$/,``)} - not imported.csv`,`text/csv`),F7=({rows:e})=>(0,H.jsxs)(`ul`,{"aria-label":`Rows not imported`,className:`flex flex-col gap-1 text-xs`,children:[e.slice(0,N7).map(e=>(0,H.jsxs)(`li`,{children:[(0,H.jsxs)(`span`,{className:`font-medium`,children:[`Row `,e.line,`:`]}),` `,e.problems.join(`; `)]},e.line)),e.length>N7&&(0,H.jsxs)(`li`,{className:`text-muted-foreground`,children:[`And `,(e.length-N7).toLocaleString(`en-IE`),` more rows, all in the file.`]})]}),s_e=({rows:e})=>(0,H.jsxs)(`p`,{className:`flex items-center gap-2 text-muted-foreground`,role:`status`,children:[(0,H.jsx)(Ed,{className:`size-3.5`}),`Checking rows… `,e.toLocaleString(`en-IE`),` read`]}),c_e=({check:e,model:t,resources:n,views:r,columns:i,headers:a,fileName:o})=>{let s=r[t.name],c=i.map(e=>t.fields[e.field]);return(0,H.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,H.jsx)(u7,{label:`Check`,counts:[[`Rows`,e.rows],[`To create`,e.creates],[`To update`,e.updates],[`With problems`,e.problems.length]]}),e.preview.length>0&&(0,H.jsx)(`div`,{className:`overflow-x-auto rounded-lg border`,children:(0,H.jsxs)(`table`,{"aria-label":`First rows`,className:`w-full text-left text-xs`,children:[(0,H.jsx)(`thead`,{className:`bg-muted text-muted-foreground`,children:(0,H.jsxs)(`tr`,{children:[(0,H.jsx)(`th`,{className:`px-2 py-1.5 font-medium`,children:`Row`}),c.map(e=>(0,H.jsx)(`th`,{className:`whitespace-nowrap px-2 py-1.5 font-medium`,children:d7(s,e.name)},e.name))]})}),(0,H.jsx)(`tbody`,{className:`divide-y`,children:e.preview.map(e=>(0,H.jsxs)(`tr`,{className:e.problems.length>0?`bg-danger-soft`:void 0,children:[(0,H.jsx)(`td`,{className:`px-2 py-1.5 tabular-nums text-muted-foreground`,children:e.line}),c.map(t=>(0,H.jsx)(`td`,{className:`max-w-48 truncate px-2 py-1.5`,children:m7(t,n)?String(e.values[t.name]??`—`):t.name in e.values?ZS(t,e.values[t.name],s?.fields[t.name]):``},t.name))]},e.line))})]})}),e.problems.length>0&&(0,H.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,H.jsx)(`h3`,{className:`font-medium`,children:`Rows with problems, which are skipped`}),(0,H.jsxs)(W,{size:`sm`,onClick:()=>P7(o,a,e.problems),children:[(0,H.jsx)(He,{className:`size-3.5`}),`Download`]})]}),(0,H.jsx)(F7,{rows:e.problems})]}),(0,H.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Rows are saved in batches of `,100,`. Cancelling, or an error, keeps the batches already saved; a row the server refuses is listed and the others are saved.`]})]})},I7=({label:e,name:t,value:n,options:r,onChange:i,help:a,className:s})=>{let c=(0,o.useId)();return(0,H.jsxs)(`div`,{className:V(`flex min-w-0 flex-col gap-1.5`,s),children:[(0,H.jsx)(`label`,{htmlFor:c,className:`font-medium`,children:e}),(0,H.jsx)(`select`,{id:c,"aria-label":t,value:n,onChange:e=>i(e.target.value),className:`h-8 w-full min-w-0 rounded-md border border-border-strong bg-background px-2 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 max-sm:min-h-11`,children:r.map(e=>(0,H.jsx)(`option`,{value:e.value,children:e.label},e.value))}),a&&(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:a})]})},l_e=({file:e,sheets:t,sheet:n,reading:r,onChoose:i,onSheet:a})=>{let s=(0,o.useId)();return(0,H.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`label`,{htmlFor:s,className:`font-medium`,children:`File`}),(0,H.jsx)(`input`,{id:s,type:`file`,accept:`.xlsx,.csv,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,disabled:r,onChange:e=>{let t=e.target.files?.[0];t&&i(t)},className:`file:mr-3 file:h-8 file:rounded-md file:border file:border-border-strong file:bg-background file:px-3 file:font-medium file:text-foreground max-sm:file:min-h-11`}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`An Excel workbook (.xlsx) or a CSV file saved as UTF-8. Its first row names the columns.`})]}),r&&(0,H.jsxs)(`p`,{className:`flex items-center gap-2 text-muted-foreground`,role:`status`,children:[(0,H.jsx)(Ed,{className:`size-3.5`}),`Reading `,e?.name??`the file`,`…`]}),!r&&t.length>1&&(0,H.jsxs)(`div`,{className:`flex items-end gap-3`,children:[(0,H.jsx)(nt,{className:`mb-2 size-4 shrink-0 text-muted-foreground`}),(0,H.jsx)(I7,{className:`flex-1`,label:`Sheet`,value:n??``,options:t.map(e=>({value:e,label:e})),onChange:a})]})]})},u_e=[{value:`create`,label:`Create`},{value:`update`,label:`Update`},{value:`upsert`,label:`Create or update`}],d_e={create:`Each row creates a record.`,update:`Each row updates the record its value finds; a row that finds none is not imported.`,upsert:`Each row updates the record its value finds, or creates one when it finds none.`},L7=``,f_e=({flow:e,model:t,resources:n,views:r,canUpdate:i})=>{let a=r[t.name],o=e.head?.headers??[],s=e.head?.sample??[],c=v7(e.mode,e.fields,e.columns),l=[{value:L7,label:`Do not import`},...e.fields.map(e=>({value:e.name,label:`${d7(a,e.name)}${h7(e)?` *`:``}`}))],u=o.map((e,t)=>({value:String(t),label:l7(o,t)})),d=p7(t);return(0,H.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[i&&(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsx)(`span`,{className:`font-medium`,children:`Rows`}),(0,H.jsx)(`div`,{children:(0,H.jsx)($u,{label:`What each row does`,size:`md`,value:e.mode,options:u_e,onChange:e.setMode})}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:d_e[e.mode]})]}),e.mode!==`create`&&(0,H.jsxs)(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[(0,H.jsx)(I7,{label:`Find records by`,value:e.match?.field??L7,options:[{value:L7,label:`Choose a field`},...d.map(e=>({value:e.name,label:d7(a,e.name)}))],onChange:t=>e.setMatch(t?{field:t,column:e.match?.column??0}:void 0),help:`A field no two records share, such as the key or an email.`}),(0,H.jsx)(I7,{label:`Found in column`,value:e.match?String(e.match.column):L7,options:[{value:L7,label:`Choose a column`},...u],onChange:t=>e.setMatch(t&&e.match?{...e.match,column:Number(t)}:e.match)})]}),(0,H.jsxs)(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[(0,H.jsx)(I7,{label:`Numbers`,value:e.options.decimal,options:[{value:`.`,label:`1,234.56`},{value:`,`,label:`1.234,56`}],onChange:t=>e.setOptions({...e.options,decimal:t})}),(0,H.jsx)(I7,{label:`Dates`,value:e.options.dateOrder,options:[{value:`dmy`,label:`Day first (31/12/2026)`},{value:`mdy`,label:`Month first (12/31/2026)`}],onChange:t=>e.setOptions({...e.options,dateOrder:t}),help:`Dates written as 2026-12-31 read the same either way. Times without a zone are your own time.`})]}),e.mode!==`update`&&(0,H.jsx)(`p`,{className:`-mb-3 text-xs text-muted-foreground`,children:`New records need the fields marked *.`}),(0,H.jsx)(`section`,{"aria-label":`Columns`,className:`flex flex-col divide-y divide-border border-y`,children:o.map((i,c)=>{let u=e.columns.find(e=>e.column===c),d=u?t.fields[u.field]:void 0,f=d?m7(d,n):void 0,p=s.map(e=>s7(e.cells[c]??null)).filter(e=>e!==``).slice(0,3),m=l7(o,c);return(0,H.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 py-3 sm:grid-cols-2 sm:gap-4`,children:[(0,H.jsxs)(`div`,{className:`min-w-0`,children:[(0,H.jsx)(`p`,{className:`truncate font-medium`,children:m}),(0,H.jsx)(`p`,{className:`truncate text-xs text-muted-foreground`,children:p.length>0?p.join(`, `):`Empty in the first rows`})]}),(0,H.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,H.jsx)(I7,{label:`Field`,name:`Field for ${m}`,value:u?.field??L7,options:l,onChange:t=>e.mapColumn(c,t||void 0)}),f&&(0,H.jsx)(I7,{label:`Found by`,name:`${r[f.name]?.names?.plural??d7(a,d.name)} found by`,value:u.matchBy??f.primaryKey[0],options:p7(f).map(e=>({value:e.name,label:d7(r[f.name],e.name)})),onChange:t=>e.matchColumnBy(c,t)})]})]},c)})}),c.length>0&&(0,H.jsxs)(`p`,{role:`alert`,className:`flex gap-2 rounded-lg border border-warning/30 bg-warning-soft px-3 py-2 text-warning-text`,children:[(0,H.jsx)(Bn,{className:`mt-0.5 size-4 shrink-0`}),(0,H.jsxs)(`span`,{children:[`No column fills `,c.map(e=>d7(a,e.name)).join(`, `),`, which new records need.`]})]})]})},R7=e=>e.toLocaleString(`en-IE`),p_e=({progress:e,total:t,cancelling:n})=>{let r=e.created+e.updated+e.failed;return(0,H.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,H.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs`,children:[(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:n?`Stopping after this batch…`:`Saving rows…`}),(0,H.jsxs)(`span`,{className:`tabular-nums`,children:[R7(r),` / `,R7(t)]})]}),(0,H.jsx)(`div`,{role:`progressbar`,"aria-label":`Rows saved`,"aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":t,className:`h-2 overflow-hidden rounded-full bg-muted`,children:(0,H.jsx)(`div`,{className:`h-full rounded-full bg-primary transition-[width]`,style:{width:`${t>0?Math.min(100,r/t*100):0}%`}})})]})},m_e=({result:e,stopped:t,headers:n,fileName:r})=>(0,H.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[t!==void 0&&(0,H.jsx)(pS,{title:`The import stopped. The rows counted below were saved.`,error:t}),e.cancelled&&(0,H.jsx)(`p`,{role:`status`,children:`Cancelled. The rows counted below were saved.`}),(0,H.jsx)(u7,{label:`Import summary`,counts:[[`Created`,e.created],[`Updated`,e.updated],[`Skipped`,e.skipped],[`Failed`,e.failed]]}),e.notWritten.length>0&&(0,H.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,H.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,H.jsx)(`h3`,{className:`font-medium`,children:`Rows not imported`}),(0,H.jsxs)(W,{size:`sm`,onClick:()=>P7(r,n,e.notWritten),children:[(0,H.jsx)(He,{className:`size-3.5`}),`Download`]})]}),(0,H.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Skipped rows had problems in the file; the server refused the failed ones. The file holds each with the reason, to fix and import again.`}),(0,H.jsx)(F7,{rows:[...e.notWritten].sort((e,t)=>e.line-t.line)})]})]}),h_e=e=>{let t=new Intl.NumberFormat(e).formatToParts(1.5).find(e=>e.type===`decimal`)?.value===`,`?`,`:`.`,n=new Intl.DateTimeFormat(e).formatToParts(new Date(2026,3,3)).map(e=>e.type);return{decimal:t,dateOrder:n.indexOf(`month`)<n.indexOf(`day`)?`mdy`:`dmy`}},g_e=uo(),z7=100,B7=e=>String(e),__e=e=>{let t=new Map,n=(e,n)=>{let r=`${e}.${n}`;return t.has(r)||t.set(r,new Map),t.get(r)};return{load:async(t,r,i)=>{let a=n(t.name,r),o=[...new Map(i.filter(e=>!a.has(B7(e))).map(e=>[B7(e),e])).values()],s=t.primaryKey[0];for(let n=0;n<o.length;n+=z7){let i=o.slice(n,n+z7);for(let e of i)a.set(B7(e),[]);let c=Ya(g_e.in(r,i)),l;do{let n=await e(t.name).list(t.name,{filter:c,fields:[...new Set([s,r])],pageSize:1e3,pageToken:l});for(let e of n.items)a.get(B7(e[r]))?.push(e[s]);l=n.nextPageToken||void 0}while(l)}},keysOf:(e,t,r)=>n(e,t).get(B7(r))??[]}},v_e=500,V7=()=>{let e=new Worker(new URL(`/assets/parse-worker-BtcY0dQw.js`,``+import.meta.url),{type:`module`}),t=[],n;return e.onmessage=e=>{if(n){let t=n;n=void 0,t(e.data)}else t.push(e.data)},e.onerror=e=>{e.preventDefault();let r={type:`error`,message:`The file could not be read`};n?n(r):t.push(r)},{send:t=>e.postMessage(t),receive:()=>t.length>0?Promise.resolve(t.shift()):new Promise(e=>n=e),stop:()=>e.terminate()}},y_e=e=>({sheets:async()=>{let t=V7();try{t.send({type:`sheets`,file:e});let n=await t.receive();if(n.type===`error`)throw Error(n.message);if(n.type!==`sheets`)throw Error(`The parse worker answered ${n.type} to a request for sheets`);return n.sheets}finally{t.stop()}},rows:async function*(t){let n=V7();try{for(n.send({type:`read`,file:e,sheet:t,chunk:v_e});;){let e=await n.receive();if(e.type===`error`)throw Error(e.message);if(e.type===`end`)return;if(e.type!==`rows`)throw Error(`The parse worker answered ${e.type} to a read`);yield e.rows,n.send({type:`next`})}}finally{n.stop()}}}),H7={created:0,updated:0,skipped:0,failed:0,notWritten:[]},b_e=({model:e,resources:t,views:n,sourceFor:r=y_e})=>{let i=nne(),a=Up(),s=n[e.name],c=(0,o.useMemo)(()=>Lge(e,t),[e,t]),[l,u]=(0,o.useState)({kind:`file`,reading:!1}),[d,f]=(0,o.useState)(),[p,m]=(0,o.useState)(),[h,g]=(0,o.useState)(),[_,v]=(0,o.useState)(),[y,b]=(0,o.useState)(`create`),[x,S]=(0,o.useState)([]),[C,w]=(0,o.useState)(),[T,E]=(0,o.useState)(()=>h_e()),D=(0,o.useRef)(!1),O=(0,o.useRef)(void 0),k=e=>t=>{f(t),u(e)},A=e=>{f(void 0),u({kind:`file`,reading:!0});let t=r(e);t.sheets().then(n=>{if(m({file:e,source:t,sheets:n}),g(n[0]),n.length<=1)return j(t,n[0]);u({kind:`file`,reading:!1})}).catch(k({kind:`file`,reading:!1}))},j=async(t,n)=>{u({kind:`file`,reading:!0});let r=await r_e(t,n);v(r),S(_7(r.headers,c,s));let i=p7(e)[0],a=i?_7(r.headers,[i],s)[0]:void 0;w(i&&a?{field:i.name,column:a.column}:void 0),u({kind:`map`})},M=()=>{p&&(f(void 0),j(p.source,h).catch(k({kind:`file`,reading:!1})))},N=(e,t)=>S(n=>{let r=n.filter(n=>n.column!==e&&n.field!==t);return t?[...r,{column:e,field:t}].sort((e,t)=>e.column-t.column):r}),ee=(e,t)=>S(n=>n.map(n=>n.column===e?{...n,matchBy:t}:n)),P=()=>({mode:y,columns:x,match:y===`create`?void 0:C,options:T}),te=()=>({model:e,resources:t,views:n,lookups:__e(i)});return{step:l,error:d,file:p?.file,sheets:p?.sheets??[],sheet:h,setSheet:g,head:_,fields:c,mode:y,setMode:b,columns:x,mapColumn:N,matchColumnBy:ee,match:C,setMatch:w,options:T,setOptions:E,choose:A,openSheet:M,check:()=>{if(!p)return;f(void 0);let e=new AbortController;O.current=e,u({kind:`checking`,rows:0}),i_e(p.source,h,P(),te(),e=>u({kind:`checking`,rows:e}),e.signal).then(t=>{e.signal.aborted||u({kind:`checked`,check:t})}).catch(t=>{e.signal.aborted||k({kind:`map`})(t)})},back:()=>{O.current?.abort(),f(void 0),u({kind:`map`})},start:t=>{if(!p)return;f(void 0),D.current=!1,u({kind:`importing`,progress:H7,total:t,cancelling:!1});let n=H7;o_e(p.source,h,P(),te(),{client:i(e.name),onProgress:e=>{n=e,u({kind:`importing`,progress:e,total:t,cancelling:D.current})},cancelled:()=>D.current}).then(e=>u({kind:`done`,result:e})).catch(e=>u({kind:`done`,result:{...n,cancelled:!1},stopped:e})).finally(()=>{for(let t of[`page`,`list`,`first-page`,`map`,`facets`,`series`])a.invalidateQueries({queryKey:[t,e.name]})})},cancel:()=>{D.current=!0,u(e=>e.kind===`importing`?{...e,cancelling:!0}:e)},stop:()=>O.current?.abort()}},x_e=e=>e.step.kind===`file`?`Could not read the file`:`Could not check the rows`,S_e=e=>e.columns.length===0?!1:e.mode===`create`?v7(`create`,e.fields,e.columns).length===0:e.match!==void 0,C_e=({model:e,resources:t,views:n,canUpdate:r,onClose:i,sourceFor:a})=>{let o=b_e({model:e,resources:t,views:n,sourceFor:a}),s=n[e.name]?.names?.plural??q(e.name),{step:c}=o,l=o.head?.headers??[],u=()=>{c.kind!==`importing`&&(o.stop(),i())},d=(0,H.jsx)(W,{onClick:u,children:`Cancel`});return(0,H.jsx)(m_,{open:!0,wide:!0,title:`Import ${s.toLowerCase()}`,description:o.file&&c.kind!==`file`?o.file.name:void 0,onClose:u,actions:(()=>{switch(c.kind){case`file`:return(0,H.jsxs)(H.Fragment,{children:[d,o.sheets.length>1&&(0,H.jsx)(W,{variant:`primary`,loading:c.reading,onClick:o.openSheet,children:`Next`})]});case`map`:return(0,H.jsxs)(H.Fragment,{children:[d,(0,H.jsx)(W,{variant:`primary`,disabled:!S_e(o),onClick:o.check,children:`Check rows`})]});case`checking`:return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:o.back,children:`Back`}),(0,H.jsx)(W,{variant:`primary`,loading:!0,children:`Checking`})]});case`checked`:{let e=c.check.creates+c.check.updates;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:o.back,children:`Back`}),(0,H.jsxs)(W,{variant:`primary`,disabled:e===0,onClick:()=>o.start(e),children:[`Import `,e.toLocaleString(`en-IE`),` `,e===1?`row`:`rows`]})]})}case`importing`:return(0,H.jsx)(W,{variant:`danger`,disabled:c.cancelling,onClick:o.cancel,children:`Cancel import`});case`done`:return(0,H.jsx)(W,{variant:`primary`,onClick:i,children:`Done`})}})(),children:(0,H.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[o.error!==void 0&&(0,H.jsx)(pS,{title:x_e(o),error:o.error}),(()=>{switch(c.kind){case`file`:return(0,H.jsx)(l_e,{file:o.file,sheets:o.sheets,sheet:o.sheet,reading:c.reading,onChoose:o.choose,onSheet:o.setSheet});case`map`:return(0,H.jsx)(f_e,{flow:o,model:e,resources:t,views:n,canUpdate:r});case`checking`:return(0,H.jsx)(s_e,{rows:c.rows});case`checked`:return(0,H.jsx)(c_e,{check:c.check,model:e,resources:t,views:n,columns:o.columns,headers:l,fileName:o.file?.name});case`importing`:return(0,H.jsx)(p_e,{progress:c.progress,total:c.total,cancelling:c.cancelling});case`done`:return(0,H.jsx)(m_e,{result:c.result,stopped:c.stopped,headers:l,fileName:o.file?.name})}})()]})})},w_e=({model:e})=>{let{resources:t,views:n}=J(),r=d_(e.name),[i,a]=(0,o.useState)(!1);return n[e.name]?.import===!1||!Fw(r,`create`)?null:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(W,{onClick:()=>a(!0),"aria-haspopup":`dialog`,children:[(0,H.jsx)(Wn,{className:`size-3.5`}),`Import`]}),i&&(0,H.jsx)(C_e,{model:e,resources:t,views:n,canUpdate:Fw(r,`update`),onClose:()=>a(!1)})]})},T_e=()=>new DOMException(`The export was cancelled`,`AbortError`),E_e=async({client:e,resource:t,filters:n,orderBy:r,plan:i,labels:a,limit:o,port:s,sink:c,signal:l,onProgress:u})=>{let d=i.columns.map(e=>e.name),f=0;try{await c.write(await s.send({kind:`start`,plan:i}));for(let[i,p]of n.entries()){let m=``;do{let h=await e.search(t,{filter:p,orderBy:r,pageSize:500,pageToken:m,fields:d,labels:a});if(l.aborted)throw T_e();let g=h.items.slice(0,o-f);if(await c.write(await s.send({kind:`page`,records:g,labels:h.labels??{}})),f+=g.length,u(f),m=h.nextPageToken,f>=o)return await U7(s,c),{rows:f,truncated:g.length<h.items.length||m!==``||i+1<n.length}}while(m!==``)}return await U7(s,c),{rows:f,truncated:!1}}catch(e){throw await c.abort(),e}finally{s.close()}},U7=async(e,t)=>{await t.write(await e.send({kind:`finish`})),await t.close()},D_e=1048575,W7=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
69
|
+
`,G7=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,K7=`http://schemas.openxmlformats.org/package/2006/relationships`;`${W7}`,`${W7}${K7}${G7}`,`${W7}${K7}${G7}${G7}`,new TextEncoder;var O_e=uo(),q7=e=>e?.export!==!1,J7=e=>Object.values(e.fields).flatMap(e=>e.sensitive?[]:[e.name]),k_e=(e,t)=>{let n=new Set(J7(e));return JS(e,t).filter(e=>n.has(e))},Y7=(e,t,n)=>Object.fromEntries(YS(e,t,[],n).map(e=>[e.id,e.header])),A_e=(e,t,n)=>{let r=Y7(e,t,n);return n.flatMap(n=>{let i=e.fields[n];return i?[{name:n,header:r[n],field:i,hints:t?.fields[n]??{}}]:[]})},X7=(e,t)=>{let n=e?.export?e.export.maxRows??1/0:1/0;return Math.min(n,t===`xlsx`?D_e:1/0)},Z7=e=>e.primaryKey.length===1,j_e=(e,t)=>{let[n]=e.primaryKey;if(!n||e.primaryKey.length!==1)throw Error(`Not implemented: selected rows are exported by a single-field key`);let r=[];for(let e=0;e<t.length;e+=500)r.push(Ya(O_e.in(n,t.slice(e,e+500))));return r},Q7=()=>{let e=new Worker(new URL(`/assets/export-worker-CVd5saLq.js`,``+import.meta.url),{type:`module`,name:`protobase-export`}),t=[];return e.onmessage=e=>t.shift()?.resolve(e.data.bytes),e.onerror=e=>{e.preventDefault();let n=Error(`The export could not be built: ${e.message}`);for(let e of t.splice(0))e.reject(n)},{send:n=>new Promise((r,i)=>{t.push({resolve:r,reject:i}),e.postMessage(n)}),close:()=>e.terminate()}},M_e=[{value:`xlsx`,label:`Excel (.xlsx)`},{value:`csv`,label:`CSV`}],N_e=[{value:`shown`,label:`As shown`},{value:`raw`,label:`Raw values`}],P_e={shown:`Labels, dates and numbers as the list shows them.`,raw:`Values as they are stored, such as keys and codes.`},F_e=e=>e.kind===`counting`?`Counting rows…`:e.kind===`exact`||e.rows>1e4?cf(e.rows):`more than 10,000 rows`,$7=e=>{if(e.kind!==`counting`)return e.kind===`exact`?e.rows:Math.max(e.rows,10001)},e9=({label:e,help:t,children:n})=>(0,H.jsxs)(`div`,{className:`flex flex-col items-start gap-1.5`,children:[(0,H.jsx)(`span`,{className:`text-[13px] font-medium`,children:e}),n,t&&(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t})]}),t9=(e,t,n)=>{let r=e.indexOf(t),i=[...e];return i.splice(r,1),i.splice(r+n,0,t),i},I_e=({fields:e,columns:t,onChange:n})=>{let r=Object.fromEntries(e.map(e=>[e.name,e.label])),i=[...t,...e.map(e=>e.name).filter(e=>!t.includes(e))];return(0,H.jsx)(`ul`,{className:`divide-y self-stretch rounded-md border`,"aria-label":`Columns`,children:i.map(e=>{let i=t.includes(e),a=t.indexOf(e);return(0,H.jsxs)(`li`,{className:`flex min-h-10 items-center gap-2 px-3 py-1`,children:[(0,H.jsxs)(`label`,{className:`flex min-w-0 flex-1 cursor-pointer items-center gap-2.5`,children:[(0,H.jsx)(Rh,{checked:i,label:r[e],onChange:r=>n(r?[...t,e]:t.filter(t=>t!==e))}),(0,H.jsx)(`span`,{className:i?`truncate`:`truncate text-muted-foreground`,children:r[e]})]}),i&&(0,H.jsxs)(`span`,{className:`flex shrink-0 gap-1`,children:[(0,H.jsx)(W,{size:`sm`,variant:`ghost`,className:`min-h-8 px-2`,"aria-label":`Move ${r[e]} up`,disabled:a===0,onClick:()=>n(t9(t,e,-1)),children:(0,H.jsx)(A,{className:`size-3.5`})}),(0,H.jsx)(W,{size:`sm`,variant:`ghost`,className:`min-h-8 px-2`,"aria-label":`Move ${r[e]} down`,disabled:a===t.length-1,onClick:()=>n(t9(t,e,1)),children:(0,H.jsx)(S,{className:`size-3.5`})})]})]},e)})})},L_e=({plural:e,view:t,fields:n,initialColumns:r,count:i,selected:a,open:s,onExport:c,onClose:l})=>{let[u,d]=(0,o.useState)(`xlsx`),[f,p]=(0,o.useState)(a?`selected`:`list`),[m,h]=(0,o.useState)(r),[g,_]=(0,o.useState)(`shown`),v=X7(t,u),y=f===`selected`?`${af(a??0)} selected ${a===1?`row`:`rows`}`:F_e(i),b=(f===`selected`?a??0:$7(i)??0)>v,x=[{value:`list`,label:`Rows in the list`},{value:`selected`,label:`Selected (${af(a??0)})`}];return(0,H.jsx)(m_,{title:`Export ${e.toLowerCase()}`,open:s,onClose:l,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:l,children:`Cancel`}),(0,H.jsx)(W,{variant:`primary`,disabled:m.length===0,onClick:()=>c({format:u,scope:f,columns:m,mode:g}),children:`Export`})]}),children:(0,H.jsxs)(`div`,{className:`flex flex-col gap-4 text-[13px]`,children:[(0,H.jsx)(e9,{label:`Format`,children:(0,H.jsx)($u,{size:`md`,label:`Format`,value:u,options:M_e,onChange:d})}),a!==void 0&&a>0&&(0,H.jsx)(e9,{label:`Rows`,help:f===`list`?`With the list’s filters, search and sort.`:void 0,children:(0,H.jsx)($u,{size:`md`,label:`Rows`,value:f,options:x,onChange:p})}),(0,H.jsx)(e9,{label:`Values`,help:P_e[g],children:(0,H.jsx)($u,{size:`md`,label:`Values`,value:g,options:N_e,onChange:_})}),(0,H.jsx)(e9,{label:`Columns`,children:(0,H.jsx)(I_e,{fields:n,columns:m,onChange:h})}),(0,H.jsxs)(`p`,{role:`status`,className:`text-muted-foreground`,children:[`Exports `,y,`.`,b&&` A file holds at most ${af(v)} rows; the rest are left out.`]})]})})},R_e=({plural:e,done:t,total:n,onCancel:r})=>{let i=n?Math.min(1,t/n):void 0;return(0,H.jsx)(m_,{title:`Exporting ${e.toLowerCase()}`,open:!0,onClose:r,actions:(0,H.jsx)(W,{onClick:r,children:`Cancel`}),children:(0,H.jsxs)(`div`,{className:`flex flex-col gap-2 text-[13px]`,children:[(0,H.jsx)(`div`,{role:`progressbar`,"aria-label":`Rows exported`,"aria-valuemin":0,"aria-valuemax":n,"aria-valuenow":t,className:`h-1.5 overflow-hidden rounded-full bg-muted`,children:(0,H.jsx)(`div`,{className:`h-full rounded-full bg-primary transition-[width]`,style:{width:`${(i??0)*100}%`}})}),(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:n?`${af(t)} of ${af(n)} rows`:`${af(t)} rows`})]})})},n9={xlsx:{mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,extension:`.xlsx`,description:`Excel workbook`},csv:{mime:`text/csv`,extension:`.csv`,description:`CSV file`}},z_e=/[\\/:*?"<>|\u0000-\u001f]/g,B_e=(e,t,n=new Date)=>{let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,`0`),String(n.getDate()).padStart(2,`0`)].join(`-`);return`${e.replace(z_e,` `).trim()} ${r}${n9[t].extension}`},V_e=8e6,H_e=(e,t)=>{let n=new Blob([],{type:n9[t].mime}),r=[],i=0,a=()=>{n=new Blob([n,...r],{type:n9[t].mime}),r=[],i=0};return{write:async e=>{e.length!==0&&(r.push(e),i+=e.length,i>=V_e&&a())},close:async()=>{a();let t=URL.createObjectURL(n),r=document.createElement(`a`);r.href=t,r.download=e,r.click(),setTimeout(()=>URL.revokeObjectURL(t),6e4)},abort:async()=>{r=[],n=new Blob([])}}},r9=()=>globalThis.showSaveFilePicker,U_e=()=>typeof r9()==`function`,W_e=async(e,t)=>{let n=r9();if(!n)throw Error(`This browser cannot save a file as it is built`);let r=n9[t],i;try{i=await n({suggestedName:e,types:[{description:r.description,accept:{[r.mime]:[r.extension]}}]})}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}let a=await i.createWritable();return{write:async e=>{e.length>0&&await a.write(e)},close:()=>a.close(),abort:()=>a.abort()}},G_e=(e,t)=>U_e()?W_e(e,t):Promise.resolve(H_e(e,t)),K_e=(e,t)=>{let n=t[e.primaryKey[0]];return typeof n==`object`&&n&&`id`in n?n.id:n},q_e=({model:e,view:t,resources:n,views:r,plural:i,filter:a,orderBy:s,createPort:c=Q7,createSink:l=G_e})=>{let u=K(),d=Ig(),[f,p]=(0,o.useState)({kind:`closed`}),m=(0,o.useRef)(void 0),h=_h({queryKey:G.exportCount(e.name,a),enabled:f.kind===`settings`,queryFn:async()=>{let t=await u.list(e.name,{filter:a||void 0,pageSize:1,count:`exact`,fields:e.primaryKey});return t.totalSize===void 0?{kind:`estimate`,rows:t.totalSizeEstimate}:{kind:`exact`,rows:t.totalSize}}}).data??{kind:`counting`},g=(t=[])=>p({kind:`settings`,selected:Z7(e)?t.map(t=>K_e(e,t)):[]}),_=async(o,f)=>{let g=B_e(i,o.format),_=await l(g,o.format);if(!_)return;let v=X7(t,o.format),y=o.scope===`selected`?f.length:$7(h),b=y===void 0?void 0:Math.min(y,v),x=new AbortController;m.current=x,p({kind:`running`,done:0,total:b});try{let l=await E_e({client:u,resource:e.name,filters:o.scope===`selected`?j_e(e,f):[a],orderBy:s,plan:{format:o.format,mode:o.mode,name:i,columns:A_e(e,t,o.columns)},labels:o.mode===`shown`?k4(n,r,e,o.columns):{},limit:v,port:c(),sink:_,signal:x.signal,onProgress:e=>x.signal.aborted||p({kind:`running`,done:e,total:b})});d.show({state:`success`,title:`Exported ${af(l.rows)} ${i.toLowerCase()}`,description:l.truncated?`${g}: the first ${af(l.rows)} rows, as many as a file holds.`:g})}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;if(!Fs(e))throw e;d.show({state:`error`,title:`Could not export ${i.toLowerCase()}`,description:e.message})}finally{m.current=void 0,p(e=>e.kind===`running`?{kind:`closed`}:e)}},v=()=>{m.current?.abort(),p({kind:`closed`})},y=J7(e),b=Y7(e,t,y);return{open:g,dialogs:f.kind===`settings`?(0,H.jsx)(L_e,{plural:i,view:t,fields:y.map(e=>({name:e,label:b[e]})),initialColumns:k_e(e,t),count:h,selected:f.selected.length>0?f.selected.length:void 0,open:!0,onExport:e=>void _(e,f.selected),onClose:()=>p({kind:`closed`})}):f.kind===`running`?(0,H.jsx)(R_e,{plural:i,done:f.done,total:f.total,onCancel:v}):null}},J_e=({state:e,onClearSearch:t,onClearFilters:n,create:r})=>(0,H.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-8 text-center text-muted-foreground`,children:[(0,H.jsx)(`p`,{children:e.message}),(e.clearSearch||e.clearFilters||e.create&&r)&&(0,H.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[e.clearSearch&&(0,H.jsx)(W,{onClick:t,children:`Clear search`}),e.clearFilters&&(0,H.jsx)(W,{onClick:n,children:`Clear filters`}),e.create&&r]})]}),Y_e=({plural:e,search:t,filtered:n,scoped:r,canCreate:i})=>{let a=e.toLowerCase();return t?{message:`No ${a} match “${t}”.`,clearSearch:!0,clearFilters:n,create:!1}:n?{message:`No ${a} match these filters.`,clearSearch:!1,clearFilters:!0,create:!1}:r?{message:`No ${a} match.`,clearSearch:!1,clearFilters:!1,create:!1}:{message:`No ${a} yet.`,clearSearch:!1,clearFilters:!1,create:i}},X_e=(e,t)=>{},Z_e=({windowMs:e=1e3,comebacks:t=2,onHold:n=X_e}={})=>{let r,i=[],a;return(o,s)=>{if(a?.among.has(o))return a.value;if(a&&(a=void 0,i=[]),o===r||(r=o,i=i.filter(t=>s-t.at<=e),i.push({value:o,at:s,comeback:i.some(e=>e.value===o)}),i.filter(e=>e.comeback).length<t))return o;let c=new Set(i.slice(-2*t).map(e=>e.value));return a={value:Math.min(...c),among:c},n(a.value,[...c]),a.value}},Q_e=e=>Math.max(1,Math.floor((e+12)/252)),$_e=(e,t)=>Math.max(0,(e-(t-1)*12)/t),eve=(e,t,n,r)=>({start:e*n,end:Math.max(0,Math.min(r,(t+1)*n)-1)}),tve=(e,t,n)=>{let r=e/t.rowHeight;return t.columns===n.columns?r*n.rowHeight:Math.floor(Math.floor(r)*t.columns/n.columns)*n.rowHeight},nve=8,rve=(e,t,n)=>{let r=e.get(t);if(r!==void 0&&r>=n)return e;let i=new Map(e);i.delete(t),i.set(t,n);for(let e of i.keys()){if(i.size<=nve)break;i.delete(e)}return i},ive=({source:e,label:t,initialIndex:n,onScrollIndex:r,minHeight:i,children:a})=>{let{total:s}=e,[c]=(0,o.useState)(n),[l,u]=(0,o.useState)(0),d=Q_e(l),f=$_e(l,d),[p,m]=(0,o.useState)(()=>new Map),h=Math.ceil(Math.max(i(f),p.get(f)??0)),g=h+12,_={columns:d,rowHeight:g},v=(0,o.useRef)({layout:_,top:0}),y=v.current.top>0&&(v.current.layout.columns!==d||v.current.layout.rowHeight!==g),b=e=>y?tve(v.current.top,v.current.layout,_):e,x=f>0&&p.has(f),S=G6({total:Math.ceil(s/d),rowHeight:g,initialIndex:Math.floor(c/d),settle:b,ready:x});(0,o.useLayoutEffect)(()=>{y&&S.scrollTo(S.top),v.current={layout:_,top:S.top},y||r(Math.floor(Math.max(0,S.top)/g)*d)});let C=eve(S.first,S.last,d,s),w=L6({total:s,rowAt:e.rowAt,loadRows:e.loadRows,revision:e.revision,latencyMs:0},C.start,C.end),[T]=(0,o.useState)(()=>Z_e());(0,o.useLayoutEffect)(()=>{let e=S.ref.current;if(!e)return;let t=()=>u(T(e.clientWidth,performance.now())),n=new ResizeObserver(t);return n.observe(e),t(),()=>n.disconnect()},[T]);let E=(0,o.useRef)(f);E.current=f;let[D]=(0,o.useState)(()=>new ResizeObserver(e=>{let t=Math.max(...e.map(e=>e.borderBoxSize[0]?.blockSize??e.contentRect.height)),n=E.current;m(e=>rve(e,n,t))}));(0,o.useLayoutEffect)(()=>()=>D.disconnect(),[D]);let O=(0,o.useCallback)(e=>{if(e)return D.observe(e),()=>D.unobserve(e)},[D]);return(0,H.jsx)(`ul`,{ref:S.ref,className:`relative min-w-0 flex-auto`,"aria-label":t,style:{height:S.geometry.contentHeight},children:S.rows.flatMap(({index:e,offset:t})=>Array.from({length:d},(n,r)=>{let i=e*d+r;if(i>=s)return[];let o=w(i),c={top:t,left:r*(f+12),width:f,minHeight:h};return o?(0,H.jsx)(`li`,{ref:O,"aria-posinset":i+1,"aria-setsize":s,className:`absolute grid grid-cols-[minmax(0,1fr)]`,style:c,children:a(o)},o.id):(0,H.jsx)(`li`,{"aria-hidden":!0,className:`absolute grid grid-cols-[minmax(0,1fr)]`,style:c,children:(0,H.jsx)(ku,{className:`h-full rounded-lg`})},`skeleton-${i}`)}))})},ave=`grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3`,ove=e=>e*.75,sve=44,cve=({model:e,view:t,display:n,list:r,empty:i})=>{let a=t?.names?.plural??q(e.name),o=n.card===void 0&&(n.image!==void 0||n.photos!==void 0);return r.isLoading?(0,H.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden ${ave}`,children:Array.from({length:6},(e,t)=>(0,H.jsx)(ku,{className:`h-24`},t))}):r.error?(0,H.jsx)(pS,{title:`Could not load rows`,error:r.error}):!r.source||r.source.total===0?i??(0,H.jsxs)(`p`,{className:`py-8 text-center text-muted-foreground`,children:[`No `,a.toLowerCase(),` match.`]}):(0,H.jsx)(ive,{source:r.source,label:a,initialIndex:r.initialIndex,onScrollIndex:r.onScrollIndex,minHeight:e=>(o?ove(e):0)+sve,children:r=>(0,H.jsx)(l5,{model:e,view:t,display:n,row:EC(e,r)})})},i9=new Map,lve=()=>{let{entry:e,path:t,params:n}=Dh(),r=`${t}?${n.toString()}`,i=i9.get(e),a=(0,o.useCallback)(t=>void i9.set(e,{url:r,index:t}),[e,r]);return{initialIndex:i?.url===r?i.index:0,remember:a}},a9=e=>e.reduce((e,t)=>e+t.count,0),uve=e=>{let t=Math.floor(e.length/2),n=a9(e.slice(0,t)),r=a9(e.slice(e.length-t));return n===0?0:(r-n)/n*100},dve=({active:e,payload:t,noun:n})=>{let r=t?.[0]?.payload;return!e||!r?null:(0,H.jsxs)(`div`,{className:`rounded-md border bg-background px-2.5 py-1.5 text-xs shadow-pop`,children:[(0,H.jsx)(`div`,{className:`text-muted-foreground`,children:ff(r.at)}),(0,H.jsxs)(`div`,{className:`font-semibold tabular-nums`,children:[af(r.count),` `,n]})]})},o9={fontSize:11,fill:`var(--muted-foreground)`},fve=({title:e=`Orders created`,noun:t=`orders`,defaultGranularity:n=`day`,data:r,granularity:i,onGranularityChange:a,periodLabel:s,className:c})=>{let[l,u]=(0,o.useState)(n),d=i??l,f=a??u,p=r??cx(d),m=fu(`(min-width: 640px)`),h=uve(p);return(0,H.jsxs)(`section`,{className:V(`rounded-lg border bg-background px-4 pb-2 pt-3`,c),children:[(0,H.jsxs)(`header`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,H.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,H.jsx)(`h2`,{className:`font-semibold`,children:e}),(0,H.jsx)(`span`,{className:`font-semibold tabular-nums`,children:af(a9(p))}),(0,H.jsxs)(`span`,{className:V(`text-xs font-medium tabular-nums`,h>=0?`text-success-text`:`text-danger-text`),children:[h>=0?`+`:`−`,Math.abs(h).toFixed(1),`%`]}),(0,H.jsx)(`span`,{className:`hidden text-xs text-muted-foreground sm:inline`,children:s??`last ${d===`day`?`30 days`:`12 weeks`}`})]}),(0,H.jsx)($u,{value:d,onChange:f,options:[{value:`day`,label:`Day`},{value:`week`,label:`Week`}]})]}),(0,H.jsx)(`div`,{className:`mt-2 h-24`,children:(0,H.jsx)(Aj,{width:`100%`,height:`100%`,children:(0,H.jsxs)(v4,{data:p,margin:{top:4,right:0,bottom:0,left:0},barCategoryGap:d===`day`?`22%`:`30%`,children:[(0,H.jsx)(C1,{vertical:!1,stroke:`var(--border)`}),(0,H.jsx)(h2,{dataKey:`at`,padding:{left:4,right:m?4:18},tickFormatter:pf,tick:o9,axisLine:!1,tickLine:!1,interval:d===`day`?m?4:9:m?1:3,height:18}),(0,H.jsx)(b2,{width:m?36:28,tick:o9,axisLine:!1,tickLine:!1,tickCount:3}),(0,H.jsx)(_q,{cursor:{fill:`var(--muted)`},content:(0,H.jsx)(dve,{noun:t}),isAnimationActive:!1}),(0,H.jsx)(s2,{dataKey:`count`,fill:`var(--primary)`,radius:[2,2,0,0],isAnimationActive:!1})]})})})]})},pve={"7d":`last 7 days`,"30d":`last 30 days`,"90d":`last 90 days`,"1y":`last year`,all:`all time`},mve=({resource:e,chart:t,title:n,noun:r,filter:i})=>{let[a,s]=(0,o.useState)(t.granularity===`week`?`week`:`day`),c=a===`week`?`90d`:t.range,l=cT(e,{field:t.field,range:c,granularity:a,filter:i}).data?.points.map(e=>({at:Date.parse(`${e.bucket}Z`),count:e.count}))??[];return(0,H.jsx)(fve,{title:n,noun:r,data:l,granularity:a,onGranularityChange:s,periodLabel:a===`week`?`last 12 weeks`:pve[c]})},s9=(e,t,n)=>{let r=e.sum??e.average;if(r===void 0)return n;let i=t?.fields[r]?.label??q(r);return e.sum===void 0?`Average ${i.toLowerCase()}`:`${i}`},hve=({model:e,view:t,chart:n,plural:r,filter:i})=>{let a=t?.fields[n.groupBy]?.label??q(n.groupBy);return(0,H.jsxs)(`section`,{className:`rounded-lg border bg-background px-4 pb-3 pt-3`,"aria-label":`${s9(n,t,r)} by ${a.toLowerCase()}`,children:[(0,H.jsxs)(`h2`,{className:`mb-2 font-semibold`,children:[s9(n,t,r),` by `,a.toLowerCase()]}),(0,H.jsx)(E4,{model:e,view:t,groupBy:n.groupBy,type:n.type,sum:n.sum,average:n.average,limit:n.limit,filter:i})]})},gve=({value:e,onCommit:t,placeholder:n,className:r})=>{let[i,a]=(0,o.useState)(e);return(0,o.useEffect)(()=>a(e),[e]),(0,o.useEffect)(()=>{if(i===e)return;let n=setTimeout(()=>t(i),350);return()=>clearTimeout(n)},[i,e,t]),(0,H.jsx)(wd,{wrapperClassName:V(`min-w-0 flex-1 sm:w-72 sm:flex-initial`,r),leading:(0,H.jsx)(fn,{className:`size-4`}),placeholder:n,"aria-label":`Search`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>e.key===`Enter`&&t(i)})},_ve=(e,t,n,r,i)=>{let a=n?.list?.relatedColumns??[];if(a.length===0)return e;let o=new Map(e.map(e=>[e.id,e]));return JS(t,n).flatMap(e=>{let t=o.get(e);if(t)return[t];let n=a.find(t=>t.name===e),s=n&&r[n.resource];if(!n||!s)return[];let c=n.label??q(n.name);return[{id:n.name,header:c,kind:`text`,width:160,minWidth:yS(c,!1),sortable:!1,render:e=>(0,H.jsx)(r5,{column:n,records:e[n.name]??[],target:s,view:i[s.name],Card:l5})}]})},vve=({model:e,view:t,target:n,children:r})=>{let i=X8(e.name,t.listOf,!0),a=t.names?.plural??q(e.name),o=e=>(0,H.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 px-5 py-4`,children:[(0,H.jsx)(Pd,{title:a,subtitle:t.help}),e]});if(i.error)return o((0,H.jsx)(pS,{title:`Could not load your ${a.toLowerCase()}`,error:i.error}));if(!i.data)return o((0,H.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3`,children:Array.from({length:3},(e,t)=>(0,H.jsx)(ku,{className:`h-24`},t))}));let s=J8(n,i.data);return s?r(s):o((0,H.jsxs)(`p`,{className:`py-8 text-center text-muted-foreground`,children:[`No `,a.toLowerCase(),` yet.`]}))},c9=({title:e,chips:t,label:n,required:r,initial:i=``,busy:a,onSave:s,onClose:c})=>{let l=(0,o.useId)(),[u,d]=(0,o.useState)(i),f=`${l}-form`;return(0,H.jsx)(m_,{open:!0,title:e,onClose:c,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:c,children:`Cancel`}),(0,H.jsx)(W,{type:`submit`,form:f,variant:`primary`,loading:a,children:`Save`})]}),children:(0,H.jsxs)(`form`,{id:f,className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),s(u.trim()===``?null:u.trim())},children:[t.length>0&&(0,H.jsx)(n8,{chips:t}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,H.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,H.jsx)(`label`,{htmlFor:l,className:`font-medium`,children:n}),!r&&(0,H.jsx)(`span`,{id:`${l}-hint`,className:`text-xs text-muted-foreground`,children:`Optional`})]}),(0,H.jsx)(wd,{id:l,value:u,required:r,pattern:r?`.*\\S.*`:void 0,"aria-describedby":r?void 0:`${l}-hint`,autoFocus:!0,autoComplete:`off`,onChange:e=>d(e.target.value)})]})]})})},l9=uo(),yve={start:0,end:0},u9=(e,t)=>l9.and(t,{kind:`present`,field:e.field,span:yve}),d9=e=>{switch(e.kind){case`and`:case`or`:return{...e,args:e.args.map(d9)};case`not`:return f9(e.arg);case`search`:case`present`:case`isNull`:return e;default:return u9(e,e)}},f9=e=>{switch(e.kind){case`and`:return l9.or(...e.args.map(f9));case`or`:return l9.and(...e.args.map(f9));case`not`:return d9(e.arg);case`search`:case`present`:case`isNull`:return l9.not(e);default:return u9(e,l9.not(e))}},p9=e=>{let t=Ca(e);if(!t.ok)throw Error(`The filter cannot be read: ${t.errors.map(e=>e.message).join(`; `)}`);return t.ast},m9=(e,t)=>{let n=p9(e);if(!n)return null;let r=p9(t),i=l9.not(d9(n));return Ya(r?l9.and(r,i):i)},bve=(e,t)=>m9(t,e),h9=e=>e.key.startsWith(`extra:`)?`extra:${e.label}`:e.key,xve=(e,t)=>{let n=new Map(e.map(e=>[h9(e),e])),r=new Map(t.map(e=>[h9(e),e])),i=e.filter(e=>!r.has(h9(e))).map(e=>({kind:`removed`,label:e.label})),a=t.flatMap(e=>{let t=n.get(h9(e));return t&&t.label!==e.label?[{kind:`changed`,label:e.label,before:t.label}]:[]}),o=t.filter(e=>!n.has(h9(e))).map(e=>({kind:`added`,label:e.label}));return[...i,...a,...o]},Sve=(e,t,n,r)=>{let i=e-t;return i===0?`As many ${r}`:`${Math.abs(i)} ${i>0?`more`:`fewer`} ${Math.abs(i)===1?n:r}`},g9=12,_9={added:{word:`Added`,className:`text-success-text`},removed:{word:`Removed`,className:`text-danger-text`},changed:{word:`Changed`,className:`text-primary-text`}},Cve=({changes:e})=>(0,H.jsx)(`ul`,{"aria-label":`Filter changes`,className:`divide-y rounded-md border`,children:e.map(e=>(0,H.jsxs)(`li`,{className:`grid grid-cols-[72px_1fr] gap-3 px-3 py-2`,children:[(0,H.jsx)(`span`,{className:`font-medium ${_9[e.kind].className}`,children:_9[e.kind].word}),e.kind===`changed`?(0,H.jsxs)(`span`,{children:[(0,H.jsx)(`span`,{className:`text-muted-foreground line-through`,children:e.before}),` `,(0,H.jsx)(`span`,{className:`font-medium`,children:e.label})]}):(0,H.jsx)(`span`,{className:e.kind===`removed`?`text-muted-foreground line-through`:`font-medium`,children:e.label})]},`${e.kind}:${e.label}`))}),v9=(e,t)=>{let n=_h({...Kw(K(),e,t??``),enabled:t!==null});return t===null?0:n.data},wve=(e,t,n)=>`${e} ${e===1?t:n}`,y9=({model:e,view:t,title:n,filter:r,total:i,plural:a})=>{let o=t?.list?.displays?.find(e=>e.kind===`cards`);return(0,H.jsxs)(`section`,{"aria-label":n,className:`flex flex-col gap-2`,children:[(0,H.jsxs)(`h3`,{className:`font-semibold`,children:[n,` `,(0,H.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`(`,i??`…`,`)`]})]}),i!==void 0&&i>g9&&(0,H.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`The first `,g9,` of `,i,`.`]}),r===null||i===0?(0,H.jsxs)(`p`,{className:`text-muted-foreground`,children:[`No `,a,`.`]}):(0,H.jsx)(J5,{model:e,view:t,filter:r,sort:DC(e,t),limit:g9,display:o?.name??`table`,row:!0,link:!1,empty:`No ${a}.`})]})},Tve=({model:e,view:t,title:n,before:r,after:i,saveNewLabel:a,updating:s,creating:c,onUpdate:l,onSaveNew:u,onCancel:d})=>{let f=xve(B8(e,r),B8(e,i)),p=(0,o.useMemo)(()=>m9(r,i),[r,i]),m=(0,o.useMemo)(()=>bve(r,i),[r,i]),h=v9(e,p),g=v9(e,m),_=(t?.names?.singular??q(e.name)).toLowerCase(),v=(t?.names?.plural??q(e.name)).toLowerCase(),y=h!==void 0&&g!==void 0;return(0,H.jsx)(m_,{open:!0,wide:!0,title:n,onClose:d,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:d,children:`Cancel`}),(0,H.jsx)(W,{loading:c,disabled:s,onClick:u,children:a}),(0,H.jsx)(W,{variant:`primary`,loading:s,disabled:c,onClick:l,children:`Update`})]}),children:(0,H.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[f.length>0&&(0,H.jsx)(Cve,{changes:f}),y?(0,H.jsxs)(`p`,{children:[(0,H.jsx)(`span`,{className:`font-semibold`,children:Sve(h,g,_,v)}),(0,H.jsxs)(`span`,{className:`text-muted-foreground`,children:[`: `,wve(h,_,v),` added, `,g,` removed`]})]}):(0,H.jsx)(ku,{className:`h-4 w-48`}),(0,H.jsx)(y9,{model:e,view:t,title:`Added`,filter:p,total:h,plural:v}),(0,H.jsx)(y9,{model:e,view:t,title:`Removed`,filter:m,total:g,plural:v})]})})},Eve=()=>{let{address:e,set:t}=PC();return{key:e?.kind===`list`?e.savedSearch:void 0,open:e=>t({savedSearch:e})}},b9=e=>e instanceof Error?e.message:`Something went wrong`,Dve=(e,t)=>{let n=J(),r=K(),i=Ig(),a=Xw(),{href:o,open:s}=PC(),c=Eve(),{resource:l}=e,u=n.resources[l],d=n.views[l]?.searchesOf,f=n.permissions[l],p=u!==void 0&&d!==void 0&&f!==void 0&&Fw(f,`create`)&&Fw(f,`delete`),m=n.signIn?.[l]?.signIn,h=_5(l,p),g=e=>Ao(Ag(u,e)),_=d&&h.data?.find(e=>e[d.filter]===t),v=_||c.key===void 0||!f||!Fw(f,`update`)?void 0:h.data?.find(e=>g(e)===c.key),y=n.views[l]?.names,b=y?.plural??`saved searches`,x=d?.name===void 0?void 0:u?.fields[d.name],S=vh({mutationFn:e=>r.create(l,{[d.filter]:t,...d.name&&{[d.name]:e}}),onSuccess:e=>{c.open(g(e.record)),i.show({state:`success`,title:`Search saved`,action:{label:`Open ${b.toLowerCase()}`,href:o({kind:`list`,resource:l}),onNavigate:s}})},onError:e=>i.show({state:`error`,title:`Could not save the search`,description:b9(e)}),onSettled:()=>a(l)}),C=vh({mutationFn:e=>r.remove(l,g(e)),onError:e=>i.show({state:`error`,title:`Could not take the search off`,description:b9(e)}),onSettled:()=>a(l)}),w=vh({mutationFn:e=>r.update(l,g(e),{[d.filter]:t},e.etag??`*`),onSuccess:()=>i.show({state:`success`,title:`Search updated`}),onError:e=>i.show({state:`error`,title:`Could not update the search`,description:b9(e)}),onSettled:()=>a(l)}),T=S.isPending||C.isPending||w.isPending;return{mode:p?`save`:m?`sign-in`:void 0,prompt:m,saved:_!==void 0,opened:v&&{filter:String(v[d.filter]??``),name:d.name&&typeof v[d.name]==`string`&&v[d.name]!==``?String(v[d.name]):void 0},noun:(y?.singular??q(l)).toLowerCase(),naming:x&&{label:n.views[l]?.fields[x.name]?.label??q(x.name),required:!x.nullable},ready:h.data!==void 0&&!T,updating:w.isPending,creating:S.isPending,remove:()=>_&&C.mutate(_),saveNew:(e,t)=>S.mutate(e,t),update:e=>v&&w.mutate(v,e)}},Ove=({model:e,view:t,search:n,filter:r,chips:i,className:a})=>{let s=Dve(n,r),[c,l]=(0,o.useState)(!1),[u,d]=(0,o.useState)(!1),[f,p]=(0,o.useState)();if(!s.mode)return null;let m=n.label??`Save search`;if(s.mode===`sign-in`)return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(W,{className:a,"aria-haspopup":`dialog`,onClick:()=>l(!0),children:[(0,H.jsx)(oe,{className:`size-3.5`,"aria-hidden":!0}),m]}),(0,H.jsx)(K8,{as:`dialog`,prompt:s.prompt,open:c,onClose:()=>l(!1)})]});let h=e=>{d(!1),s.naming?p(e):s.saveNew(null)},g=f!==void 0&&s.naming&&(0,H.jsx)(c9,{title:f,chips:i,label:s.naming.label,required:s.naming.required,busy:s.creating,onSave:e=>s.saveNew(e,{onSuccess:()=>p(void 0)}),onClose:()=>p(void 0)}),_=s.opened;if(_){let n=`Save as new ${s.noun}`;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(W,{className:a,"aria-haspopup":`dialog`,"aria-disabled":!s.ready,onClick:()=>s.ready&&d(!0),children:[(0,H.jsx)(ln,{className:`size-3.5`,"aria-hidden":!0}),(0,H.jsx)(`span`,{className:`max-w-60 truncate`,children:_.name?`Update ${_.name}`:`Update ${s.noun}`})]}),(0,H.jsxs)(W,{className:a,"aria-haspopup":s.naming?`dialog`:void 0,"aria-disabled":!s.ready,onClick:()=>s.ready&&h(n),children:[(0,H.jsx)(ae,{className:`size-3.5`,"aria-hidden":!0}),n]}),u&&(0,H.jsx)(Tve,{model:e,view:t,title:_.name?`Update ${_.name}?`:`Update this ${s.noun}?`,before:_.filter,after:r,saveNewLabel:n,updating:s.updating,creating:s.creating,onUpdate:()=>s.update({onSuccess:()=>d(!1)}),onSaveNew:()=>h(n),onCancel:()=>d(!1)}),g]})}let v=s.saved?ie:oe;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(W,{className:a,"aria-pressed":s.saved,"aria-haspopup":!s.saved&&s.naming?`dialog`:void 0,"aria-disabled":!s.ready,onClick:()=>s.ready&&(s.saved?s.remove():h(m)),children:[(0,H.jsx)(v,{className:s.saved?`size-3.5 text-primary`:`size-3.5`,"aria-hidden":!0}),m]}),g]})},kve=e=>e instanceof Error?e.message:`Something went wrong`,Ave=({model:e,view:t,name:n,value:r,onChange:i})=>{let a=(0,o.useId)(),s=e.fields[n],c=t.fields[n],l=c?.label??q(n);if(s?.type===`boolean`)return(0,H.jsx)(mS,{checked:r===!0,onChange:i,label:l});if(s?.type!==`enum`)throw Error(`Not implemented: "${n}" is ${s?.type??`unknown`}, and a saved search's controls are enums or booleans`);return(0,H.jsxs)(`label`,{htmlFor:a,className:`flex items-center gap-2 text-muted-foreground`,children:[l,(0,H.jsx)(`select`,{id:a,value:String(r??``),onChange:e=>i(e.target.value),className:`h-8 rounded-md border border-border-strong bg-background px-2 text-foreground shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20`,children:(s.enumValues??[]).map(e=>(0,H.jsx)(`option`,{value:e,children:rs(e,c?.valueLabels)},e))})]})},jve=(e,t,n)=>Object.entries(n).map(([n,r])=>`${t.fields[n]?.label??q(n)}: ${e.fields[n]?.type===`boolean`?r===!0?`On`:`Off`:rs(String(r),t.fields[n]?.valueLabels)}`).join(`, `),Mve=({model:e,view:t,recordKey:n,title:r,row:i,fields:a})=>{let o=K(),s=Ig(),c=Xw(),l=vh({mutationFn:t=>o.update(e.name,n,t,i.etag??`*`),onSuccess:(n,i)=>s.show({state:`success`,title:`${r} saved`,description:jve(e,t,i)}),onError:e=>s.show({state:`error`,title:`Could not change the search`,description:kve(e)}),onSettled:()=>c(e.name)});return(0,H.jsx)(`div`,{className:`flex flex-wrap items-center gap-3`,children:a.map(n=>(0,H.jsx)(Ave,{model:e,view:t,name:n,value:l.isPending&&n in(l.variables??{})?l.variables[n]:i[n],onChange:e=>l.mutate({[n]:e})},n))})},Nve=e=>e instanceof Error?e.message:`Something went wrong`,Pve=({model:e,view:t,of:n,target:r,targetView:i,row:a,recordKey:s,canRename:c,onDelete:l})=>{let u=K(),d=Ig(),f=Xw(),[p,m]=(0,o.useState)(!1),{name:h,chips:g,title:_,body:v}=v5({model:e,of:n,target:r,targetView:i,row:a,recordKey:s}),y=vh({mutationFn:t=>u.update(e.name,s,{[n.name]:t},a.etag??`*`),onSuccess:()=>m(!1),onError:e=>d.show({state:`error`,title:`Could not rename the search`,description:Nve(e)}),onSettled:()=>f(e.name)}),b=n.name===void 0?void 0:e.fields[n.name];return(0,H.jsxs)(`section`,{"aria-label":_,className:`flex flex-col gap-3 rounded-lg border bg-surface p-4`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,H.jsx)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:(0,H.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:(0,H.jsx)(FC,{to:{kind:`record`,resource:e.name,key:s},className:`hover:underline`,children:h??(0,H.jsx)(r8,{chips:g})})})}),(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n.controls&&(0,H.jsx)(Mve,{model:e,view:t,recordKey:s,title:_,row:a,fields:n.controls}),c&&b&&(0,H.jsx)(W,{variant:`ghost`,"aria-label":`Rename ${_}`,"aria-haspopup":`dialog`,onClick:()=>m(!0),children:(0,H.jsx)(en,{className:`size-3.5`,"aria-hidden":!0})}),l&&(0,H.jsx)(W,{variant:`ghost`,"aria-label":`Delete ${_}`,onClick:()=>l(_),children:(0,H.jsx)(Rn,{className:`size-3.5`,"aria-hidden":!0})})]})]}),p&&b&&(0,H.jsx)(c9,{title:`Rename ${_}`,chips:g,label:t.fields[b.name]?.label??q(b.name),required:!b.nullable,initial:h,busy:y.isPending,onSave:e=>y.mutate(e),onClose:()=>m(!1)}),(0,H.jsx)(g5,{...v})]})},Fve=({model:e,view:t})=>{let{resources:n,views:r}=J(),i=t.searchesOf,a=n[i.resource],o=r[i.resource],s=_5(e.name,!0),c=d_(e.name),l=r7({model:e,view:t}),u=t.names?.plural??q(e.name),d=e=>(0,H.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 px-5 py-4`,children:[l.dialogs,(0,H.jsx)(Pd,{title:u,subtitle:t.help}),e]});if(!a)return d((0,H.jsxs)(u_,{title:`Not found`,children:[`There is no resource called `,i.resource,`.`]}));if(s.error)return d((0,H.jsx)(pS,{title:`Could not load your ${u.toLowerCase()}`,error:s.error}));if(!s.data)return d((0,H.jsx)(`div`,{className:`flex flex-col gap-3`,children:Array.from({length:2},(e,t)=>(0,H.jsx)(ku,{className:`h-56`},t))}));if(s.data.length===0){let e=(o?.names?.plural??q(a.name)).toLowerCase();return d((0,H.jsxs)(`p`,{className:`py-8 text-center text-muted-foreground`,children:[`No `,u.toLowerCase(),` yet. Filter the`,` `,(0,H.jsx)(FC,{to:{kind:`list`,resource:a.name},className:`font-medium text-primary-text hover:underline`,children:e}),` `,`and save the search.`]}))}return d((0,H.jsx)(`div`,{className:`flex flex-col gap-4`,children:s.data.map(n=>{let r=Ao(Ag(e,n)),s=Fw(c,`delete`)?e=>void l.start({key:r,title:e,etag:n.etag,snapshot:n}):void 0;return(0,H.jsx)(Pve,{model:e,view:t,of:i,target:a,targetView:o,row:n,recordKey:r,canRename:Fw(c,`update`),onDelete:s},r)})}))},Ive=({field:e,hints:t,resource:n,stored:r,onSave:i,close:a})=>{let[s,c]=(0,o.useState)(()=>Zx(e,r)),l=(0,o.useRef)(null),u=(0,o.useRef)(!1),d=!t?.widget&&(e.type===`boolean`||e.type===`enum`);(0,o.useEffect)(()=>{l.current?.querySelector(`input, select, textarea, button, [tabindex]`)?.focus()},[]);let f=(t,n,o=s)=>{u.current||(u.current=!0,t&&Qx(e,o,r)&&i(Yx(e,o)),a(n))};return(0,H.jsx)(`div`,{ref:l,className:`w-full min-w-0`,onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),f(!0)):e.key===`Tab`?(e.preventDefault(),f(!0,e.shiftKey?-1:1)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),f(!1))},onBlur:e=>{l.current?.contains(e.relatedTarget)||f(!0)},children:(0,H.jsx)(mw,{field:e,hints:t,value:s,stored:r,resource:n,onChange:e=>{c(e),d&&f(!0,void 0,e)}})})},Lve=e=>{let t=K(),n=Up(),r=Ig(),[i,a]=(0,o.useState)(new Map),s=(0,o.useRef)(i),c=(0,o.useRef)(new Map),l=(e,t)=>{s.current=new Map(s.current).set(e,{...s.current.get(e),...t}),a(s.current)},u=async(i,a,o)=>{let c=Ag(e,i),u=String(s.current.get(i.id)?.etag??i.etag);try{let r=await t.update(e.name,c,{[a]:o},u);l(i.id,{[a]:r.record[a],etag:r.etag}),n.setQueryData(G.record(e.name,Ao(c)),r),n.invalidateQueries({queryKey:[`page`,e.name]}),n.invalidateQueries({queryKey:[`list`,e.name]}),n.invalidateQueries({queryKey:[`map`,e.name]})}catch(n){if(!Fs(n))throw l(i.id,{[a]:i[a]}),n;let o=n.status===412,s=o?await t.get(e.name,c):void 0;l(i.id,s?{[a]:s.record[a],etag:s.etag}:{[a]:i[a]});let u=n.errors.find(e=>e.field===a)?.message??n.message;r.show({state:`error`,title:o?`Changed by someone else`:`Could not save`,description:u})}};return{patches:i,save:(e,t,n)=>{l(e.id,{[t]:n});let r=(c.current.get(e.id)??Promise.resolve()).then(()=>u(e,t,n));return c.current.set(e.id,r.catch(()=>void 0)),r}}},Rve=(e,t,n)=>{let r=Lve(e),i=t?.list?.editable??[];return{editor:i.length>0&&Fw(n,`update`)?{editable:(t,n)=>i.includes(n)&&e.fields[n]!==void 0&&qx(e.fields[n])&&Iw(t,`update`),render:(n,i,a)=>(0,H.jsx)(Ive,{field:e.fields[i],hints:t?.fields[i],resource:e.name,stored:n[i],onSave:e=>void r.save(n,i,e),close:a})}:void 0,patches:r.patches}},x9=(e,t)=>{let n=e.position;if(!n||!Fw(t,`update`))return;let r=e.fields[n.field];return r&&!r.readOnly?n.field:void 0},zve=(e,t)=>e.position?.within===void 0?x9(e,t):void 0,Bve=(e,t,n)=>t.position?.within!==void 0&&e.field===t.position.within&&!e.through&&!e.filter?x9(t,n):void 0,Vve=({model:e,field:t,filter:n,fields:r})=>{let i=K(),a=Ig(),s=Xw(),{resources:c,views:l}=J(),u=`${t} asc`,d=_h({queryKey:[...G.list(e.name,n,u,500,`hand-order`),r.join(`,`)],queryFn:async()=>{let t=k4(c,l,e,r),a=await i.search(e.name,{filter:n||void 0,orderBy:u,pageSize:500,labels:t});return{rows:A4(c,e,r,a.items,a.labels).map((t,n)=>({...t,id:kg(e,a.items[n])})),more:!!a.nextPageToken}}}),[f,p]=(0,o.useState)(),m=(0,o.useRef)(void 0),h=(0,o.useRef)(Promise.resolve()),g=(0,o.useRef)(0),_=async()=>{let n=m.current;if(!n)return;let r=Object.fromEntries(n.flatMap(t=>typeof t.etag==`string`?[[Ao(Ag(e,t)),t.etag]]:[])),a=(await i.batchWrite([{op:`reorder`,resource:e.name,field:t,keys:n.map(t=>Ag(e,t)),etags:r}])).results[0];if(a?.op!==`reorder`||!m.current)return;let o=new Map(a.records.map(t=>[kg(e,t.record),t]));m.current=m.current.map(e=>{let n=o.get(e.id);return n?{...e,[t]:n.record[t],etag:n.etag}:e})},v=e=>{m.current=void 0,p(void 0),a.show({state:`error`,title:`Could not change the order`,description:aC(e)})},y=async()=>{--g.current,!(g.current>0)&&(await s(e.name),!(g.current>0)&&(m.current=void 0,p(void 0)))};return{rows:f??d.data?.rows,more:d.data?.more??!1,loading:d.isPending,error:d.error,move:(e,t)=>{let n=m.current??d.data?.rows;n&&e!==t&&(m.current=Tb(n,e,t),p(m.current),g.current+=1,h.current=h.current.then(_).catch(v).then(y))}}},S9=({model:e,view:t,field:n,filter:r,columns:i})=>{let{resources:a,views:s}=J(),{fields:c}=Xg(),{go:l,href:u}=PC(),d=(0,o.useMemo)(()=>K5(e,t,i,{resources:a,views:s,fieldTypes:c}).map(e=>({...e,sortable:!1})),[e,t,i.join(`,`),a,s,c]),f=Vve({model:e,field:n,filter:r,fields:(0,o.useMemo)(()=>CC(e,t,d.map(e=>e.id)),[e,t,d])}),p=f.rows,m=(0,o.useMemo)(()=>p&&{total:p.length,rowAt:e=>p[e]},[p]),h=(t?.names?.plural??q(e.name)).toLowerCase();if(f.loading)return(0,H.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,H.jsx)(ku,{className:`h-4 w-full`},t))});if(f.error)return(0,H.jsx)(pS,{title:`Could not load`,error:f.error});if(f.more)return(0,H.jsxs)(`p`,{className:`text-muted-foreground`,children:[`There are more than `,500 .toLocaleString(`en-IE`),` `,h,`, too many to sort by hand.`]});if(!m||m.total===0)return(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:`Nothing here yet.`});let g=t=>l({kind:`record`,resource:e.name,key:Ag(e,t)});return(0,H.jsx)(J6,{fit:!0,scroll:`parent`,columns:d,source:m,latencyMs:0,onOpenRow:g,rowLink:t=>({href:u({kind:`record`,resource:e.name,key:Ag(e,t)}),onFollow:()=>g(t)}),rowNumbers:!1,reorder:{label:n=>Dg(e,t,n,n.id),onMove:f.move}})},C9=({sorting:e,onChange:t,size:n,iconOnly:r=!1})=>{let i=e?`Done`:`Sort`;return(0,H.jsxs)(W,{size:n,variant:e?`primary`:`secondary`,onClick:()=>t(!e),...r&&{"aria-label":i,title:i},children:[e?(0,H.jsx)(he,{className:`size-3.5`}):(0,H.jsx)(E,{className:`size-3.5`}),!r&&i]})},Hve=uo(),Uve=e=>e.find(e=>e.kind===`search`),Wve=({address:e})=>{let{resources:t,views:n,signIn:r}=J(),i=t[e.resource],a=r?.[e.resource];if(!i)return a?(0,H.jsx)(K8,{as:`page`,prompt:a.signIn}):(0,H.jsxs)(u_,{title:`Not found`,children:[`There is no resource called `,e.resource,`.`]});let o=n[e.resource];if(o?.searchesOf)return(0,H.jsx)(Fve,{model:i,view:o});let s=AC(t,n,e.resource);if(o&&s.listOf){let t=s.model;return(0,H.jsx)(vve,{model:i,view:o,target:t,children:n=>(0,H.jsx)(w9,{model:t,address:e,scope:n,heading:{title:o.names?.plural??q(i.name),subtitle:o.help}})})}return(0,H.jsx)(w9,{model:i,address:e})},w9=({model:e,address:t,scope:n,heading:r})=>{let i=J(),{set:a,go:s,href:c}=PC(),l=e.name,u=i.views[l],d=(0,o.useMemo)(()=>F8(u,e),[u,e]),{fields:f}=Xg(),p=(0,o.useMemo)(()=>_ve(W5(YS(e,u),e,u,f),e,u,i.resources,i.views),[e,u,f,i.resources,i.views]),m=t.filter,h=(0,o.useMemo)(()=>N8(d,m),[d,m]),g=h.ok?h.state:o8,_=h.ok?h.extras:[],{orderBy:v,filterLayout:y}=t,b=pu(),x=mu(),[S,C]=(0,o.useState)(!1),w=n?[..._,n]:_,T=wge({model:e,resources:i.resources,views:i.views,view:u,state:g,extras:w}),E=n?O8(d,g,w):h.ok?m:``,D=(0,o.useMemo)(()=>CC(e,u,p.map(e=>e.id)),[e,u,p]),O=(0,o.useMemo)(()=>Jme(u,i.resources,i.views,D),[u,i.resources,i.views,D]),k=$6({resources:i.resources,views:i.views,model:e,columns:D,filter:E,orderBy:v,related:O}),A=fC(e,u,t.display),j=d_(l),M=n?void 0:zve(e,j),[N,ee]=(0,o.useState)(!1),P=N&&M!==void 0,te=P||A?.kind!==`map`;Tu(te);let F=x5(e,k.page,k.key,A?.kind===`custom`),ne=lve(),re=Eg(e,u),ie=e=>({key:e.id,title:String(typeof e[re]==`object`?e[re].name:e[re]??e.id),etag:typeof e.etag==`string`?e.etag:void 0,snapshot:e}),I=u?.names?.singular??q(l),ae=Rve(e,u,j),{state:L}=U(),oe=r7({model:e,view:u,restore:i7(e),onReview:e=>s({kind:`record`,resource:l,key:e.key})}),R=(e,t=_)=>a({filter:O8(d,e,t)}),se=Uve(_),ce=e=>{let t=_.filter(e=>e.kind!==`search`);R(g,e?[...t,Hve.search(e)]:t)},le=u?.names?.plural??q(l),ue=A&&(0,H.jsx)(U5,{model:e,view:u,display:A,orderBy:v,onChange:e=>a({orderBy:e})}),de=e.search?.length?(0,H.jsx)(gve,{value:se?.kind===`search`?se.text:``,onCommit:ce,placeholder:`Search ${le.toLowerCase()}`,className:b?void 0:`min-h-11`}):null,fe=(0,H.jsx)(x8,{layout:y,config:T,value:g,onChange:R,leading:y===`bar`?ue:void 0,trailing:de}),pe=y===`bar`?fe:(0,H.jsx)(b8,{groups:[ue?[ue]:[]],trailing:de}),me=d8(T,g),he=(0,H.jsx)(i8,{scroll:!0,chips:me,onRemove:e=>R(f8(g,e)),onClear:()=>R(o8)}),ge=A&&(0,H.jsx)(h8,{title:`Sort`,children:(0,H.jsx)(U5,{model:e,view:u,display:A,orderBy:v,onChange:e=>a({orderBy:e}),className:`min-h-11 w-full`})}),_e=(0,H.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,H.jsxs)(W,{className:`min-h-11`,onClick:()=>C(!0),"aria-haspopup":`dialog`,children:[(0,H.jsx)(Sn,{className:`size-3.5`}),`Filters`,me.length>0&&` (${me.length})`]}),de??(0,H.jsx)(`div`,{className:`min-w-0 flex-1`,children:he})]}),de&&he,(0,H.jsx)(p_,{title:`Filters`,open:S,onClose:()=>C(!1),children:(0,H.jsx)(x8,{layout:`panel`,fullWidth:!0,config:T,value:g,onChange:R,leading:ge})})]}),ve=!n&&Nge(u,i.pages,j)&&(0,H.jsxs)(FC,{to:{kind:`create`,resource:l},className:xf({variant:`primary`}),children:[(0,H.jsx)(nn,{className:`size-3.5`}),`New `,I.toLowerCase()]}),ye=u?.saveSearch&&!n&&h.ok&&m&&(0,H.jsx)(Ove,{model:e,view:u,search:u.saveSearch,filter:m,chips:z8(e,u,m,Fme(T))}),be=!n&&(0,H.jsx)(w_e,{model:e}),xe=q_e({model:e,view:u,resources:i.resources,views:i.views,plural:le,filter:E,orderBy:v}),Se=q7(u)&&(0,H.jsxs)(W,{onClick:()=>xe.open(),...!b&&{"aria-label":`Export`,title:`Export`},children:[(0,H.jsx)(He,{className:`size-3.5`}),b&&`Export`]}),Ce=M&&(0,H.jsx)(C9,{sorting:P,onChange:ee,iconOnly:!b}),we=t=>!P&&(0,H.jsx)(H5,{view:u,choices:gC(e,u,x),value:A?.name??`table`,onChange:e=>a({display:e}),menu:t}),Te=V8(e),Ee=t=>{Te(EC(e,t).record),s({kind:`record`,resource:l,key:Ag(e,t)})},De=k.source?(0,H.jsx)(J6,{columns:p,source:k.source,sort:OC(v),onSortChange:e=>a({orderBy:kC(e)}),onOpenRow:Ee,rowLink:t=>({href:c({kind:`record`,resource:l,key:Ag(e,t)}),onFollow:()=>Ee(t)}),cellEditor:ae.editor,rowPatches:ae.patches,initialScrollIndex:ne.initialIndex,onScrollIndex:ne.remember,rowActions:[{label:`Open ${I.toLowerCase()}`,onSelect:Ee},...Fw(j,`delete`)?[{label:`Delete`,destructive:!0,available:e=>Iw(e,`delete`),onSelect:e=>void oe.start(ie(e))}]:[]],bulkActions:[...q7(u)&&Z7(e)?[{label:e=>`Export ${e}`,onRun:e=>xe.open(e)}]:[],...Fw(j,`delete`)?[{label:e=>`Delete ${e}`,destructive:!0,onRun:e=>oe.startBulk(e.map(ie))}]:[]],rowNumbers:!1,pinKey:L.kind===`signed-in`?Epe(L.user.id,l):void 0,scroll:`parent`,className:`flex-1`}):(0,H.jsx)(`div`,{className:`flex-1 rounded-lg border bg-surface`}),Oe={...k,initialIndex:ne.initialIndex,onScrollIndex:ne.remember},ke=Y_e({plural:le,search:se?.kind===`search`?se.text:``,filtered:me.length>0,scoped:!!n||_.some(e=>e.kind!==`search`),canCreate:!!ve}),Ae=(0,H.jsx)(J_e,{state:ke,onClearSearch:()=>ce(``),onClearFilters:()=>R(o8),create:ve}),je=P?(0,H.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:`Drag a row by its handle to move it. Every move is saved as you drop it.`}),(0,H.jsx)(S9,{model:e,view:u,field:M,filter:``,columns:JS(e,u)})]}):A?A.kind===`cards`?(0,H.jsx)(cve,{model:e,view:u,display:A,list:Oe,empty:Ae},k.key.join(` `)):A.kind===`map`?(0,H.jsx)(B5,{model:e,view:u,display:A,filter:E,orderBy:v,fields:D,at:t.map,onMove:e=>a({map:e}),flush:!0}):A.kind===`board`?(0,H.jsx)(S5,{model:e,view:u,display:A,fields:D,filter:E,orderBy:v}):(0,H.jsx)(T5,{display:A,list:F}):k.source?.total===0&&!k.error?Ae:De;return(0,H.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 px-5 py-4`,children:[oe.dialogs,xe.dialogs,(0,H.jsx)(Pd,{title:r?.title??le,subtitle:r?r.subtitle:u?.help,aside:!b&&we(!0),actions:b?(0,H.jsxs)(H.Fragment,{children:[we(!1),Ce,ye,be,Se,ve]}):(0,H.jsxs)(H.Fragment,{children:[Ce,ye,be,Se,ve]})}),!h.ok&&(0,H.jsx)(pS,{title:`The filter in the address could not be read`,error:Error(h.errors.map(e=>e.message).join(`; `))}),k.error&&!A&&!P&&(0,H.jsx)(pS,{title:`Could not load rows`,error:k.error}),u?.chart&&!P&&(ko(u.chart)?(0,H.jsx)(hve,{model:e,view:u,chart:u.chart,plural:le,filter:E}):(0,H.jsx)(mve,{resource:l,chart:u.chart,title:`${le} created`,noun:le.toLowerCase(),filter:E})),!P&&(b?pe:_e),b&&y===`panel`&&!P?(0,H.jsxs)(`div`,{className:`flex min-h-0 flex-1 gap-4`,children:[(0,H.jsx)(`div`,{className:te?`sticky top-[calc(var(--pb-sticky-top,0px)+1rem)] flex max-h-[calc(100dvh-var(--pb-sticky-top,0px)-var(--pb-sticky-bottom,0px)-2rem)] shrink-0 self-start`:`flex shrink-0`,children:fe}),je]}):je]})},T9=({roles:e,selected:t,grantable:n,disabled:r,onChange:i})=>(0,H.jsx)(`div`,{className:`flex flex-wrap gap-x-4 gap-y-2`,children:e.filter(e=>e.membership).map(e=>{let a=t.includes(e.name),o=r||!n.has(e.name);return(0,H.jsxs)(`label`,{title:o&&!r?`You cannot give or take away this role`:void 0,className:V(`inline-flex items-center gap-1.5`,o&&`text-muted-foreground`),children:[(0,H.jsx)(Rh,{checked:a,label:e.label,onChange:o?void 0:n=>i(n?[...t,e.name]:t.filter(t=>t!==e.name)),className:V(o&&`cursor-default opacity-60`)}),e.label]},e.name)})}),E9=e=>e?.role===`owner`?[`owner`,`admin`,`member`]:[`admin`,`member`],Gve=({member:e,current:t,onChanged:n})=>{let{session:r,organizations:i}=U(),a=t.organization.id,{busy:o,error:s,run:c}=Jh(),l=i?.roles??[],u=e.id===t.memberId,d=E9(t),f=e.role===`owner`&&t.role!==`owner`;return(0,H.jsxs)(`li`,{className:`flex flex-col gap-2 px-3 py-3`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,H.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,H.jsxs)(`span`,{className:`block truncate font-medium`,children:[e.name,u&&` (you)`]}),(0,H.jsx)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:e.email})]}),(0,H.jsx)(`select`,{"aria-label":`Organization role of ${e.name}`,value:e.role,disabled:o||f,onChange:t=>void c(async()=>{await r.organizations.setRole(a,e.id,t.target.value),n()}),className:`h-7 rounded-md border border-border-strong bg-background px-2 text-xs`,children:(f?[e.role]:d).map(e=>(0,H.jsx)(`option`,{value:e,children:Wh[e]},e))}),!u&&(0,H.jsx)(W,{size:`sm`,variant:`danger`,loading:o,disabled:f,onClick:()=>void c(async()=>{await r.organizations.removeMember(a,e.id),n()}),children:`Remove`})]}),(0,H.jsx)(T9,{roles:l,selected:e.appRoles,grantable:qh(l,t),disabled:o,onChange:t=>void c(async()=>{await r.organizations.setAppRoles(e.id,t),n()})}),(0,H.jsx)(wf,{message:s})]})},Kve=({current:e})=>{let{session:t}=U(),[n,r]=(0,o.useState)(),[i,a]=(0,o.useState)(),s=e?.organization?.id,c=(0,o.useCallback)(()=>{s&&t.organizations.members(s).then(r,e=>a(e instanceof lc?zd(e):`Could not read the members`))},[t,s]);return(0,o.useEffect)(c,[c]),e?.organization?(0,H.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,H.jsx)(Pd,{title:`Members`,subtitle:`Who works in ${e.organization.name}, and with which roles.`}),(0,H.jsxs)(Cf,{title:`Members`,description:`Owners and admins manage the organization; app roles decide what each member sees and does in the app.`,children:[(0,H.jsx)(wf,{message:i}),n?(0,H.jsx)(`ul`,{className:`divide-y rounded-md border`,children:n.map(t=>(0,H.jsx)(Gve,{member:t,current:e,onChanged:c},`${t.id}/${t.role}/${t.appRoles.join()}`))}):!i&&(0,H.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,H.jsx)(Ed,{}),` Loading`]})]})]}):null},D9=({link:e})=>e?(0,H.jsxs)(`p`,{className:`mt-3 break-all rounded-md border bg-muted px-3 py-2 text-xs`,children:[`This app cannot send email, so pass this link on yourself. It works once, until the invitation expires: `,(0,H.jsx)(`span`,{className:`font-mono`,children:e})]}):null,qve=({current:e,onSent:t})=>{let{session:n,organizations:r}=U(),i=r?.roles??[],[a,s]=(0,o.useState)(``),[c,l]=(0,o.useState)(`member`),[u,d]=(0,o.useState)([]),[f,p]=(0,o.useState)(),{busy:m,error:h,run:g}=Jh(),_=()=>g(async()=>{let r=await n.organizations.invite(e.organization.id,{email:a.trim(),role:c,appRoles:u});p(r.link),s(``),d([]),t()});return(0,H.jsxs)(Cf,{title:`Invite someone`,description:`They get an email with a link to join, or to make an account first. You can give the app roles you hold, and those your roles grant.`,children:[(0,H.jsx)(wf,{message:h}),(0,H.jsxs)(`form`,{className:`flex flex-col gap-3`,onSubmit:e=>{e.preventDefault(),_()},children:[(0,H.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row`,children:[(0,H.jsx)(wd,{"aria-label":`Email`,type:`email`,placeholder:`name@example.com`,value:a,onChange:e=>s(e.target.value),wrapperClassName:`flex-1`}),(0,H.jsx)(`select`,{"aria-label":`Organization role`,value:c,onChange:e=>l(e.target.value),className:`h-8 rounded-md border border-border-strong bg-background px-2`,children:E9(e).map(e=>(0,H.jsx)(`option`,{value:e,children:Wh[e]},e))}),(0,H.jsx)(W,{type:`submit`,variant:`primary`,loading:m,disabled:!a.trim(),children:`Invite`})]}),(0,H.jsx)(T9,{roles:i,selected:u,grantable:qh(i,e),onChange:d})]}),(0,H.jsx)(D9,{link:f})]})},Jve=({invitation:e,organizationId:t,onChanged:n})=>{let{session:r,organizations:i}=U(),[a,s]=(0,o.useState)(),{busy:c,error:l,run:u}=Jh(),d=new Date(e.expiresAt).getTime()<Date.now();return(0,H.jsxs)(`li`,{className:`px-3 py-2.5`,children:[(0,H.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,H.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`block truncate font-medium`,children:e.email}),(0,H.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[Wh[e.role],e.appRoles.length>0&&` · ${e.appRoles.map(e=>Gh(i?.roles??[],e)).join(`, `)}`,` · `,d?`Expired`:`Until ${new Date(e.expiresAt).toLocaleDateString()}`]})]}),(0,H.jsx)(W,{size:`sm`,loading:c,onClick:()=>void u(async()=>{s((await r.organizations.resend(t,e)).link),n()}),children:`Send again`}),(0,H.jsx)(W,{size:`sm`,variant:`danger`,loading:c,onClick:()=>void u(async()=>{await r.organizations.revoke(e.id),n()}),children:`Revoke`})]}),(0,H.jsx)(wf,{message:l}),(0,H.jsx)(D9,{link:a})]})},Yve=({current:e})=>{let{session:t}=U(),[n,r]=(0,o.useState)([]),i=e?.organization?.id,a=(0,o.useCallback)(()=>{i&&t.organizations.invitations(i).then(e=>r(e.filter(e=>e.status===`pending`)),()=>r([]))},[t,i]);return(0,o.useEffect)(a,[a]),!e?.organization||!i?null:(0,H.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,H.jsx)(Pd,{title:`Invitations`,subtitle:`People invited to ${e.organization.name}.`}),(0,H.jsx)(qve,{current:e,onSent:a}),(0,H.jsx)(Cf,{title:`Not accepted yet`,description:n.length>0?`Sending again gives a new link, which replaces the earlier one.`:`Nobody is waiting.`,children:n.length>0&&(0,H.jsx)(`ul`,{className:`divide-y rounded-md border`,children:n.map(e=>(0,H.jsx)(Jve,{invitation:e,organizationId:i,onChanged:a},e.id))})})]})},Xve=e=>{let{session:t}=U(),[n,r]=(0,o.useState)(),[i,a]=(0,o.useState)([]),[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(0),d=(0,o.useCallback)(()=>u(e=>e+1),[]);return(0,o.useEffect)(()=>{e&&Promise.all([t.organizations.current(),t.organizations.list()]).then(([e,t])=>{r(e),a(t)},e=>c(e instanceof lc?zd(e):`Could not read your organizations`))},[e,t,l]),{current:n,organizations:i,...s&&{error:s},reload:d}},O9=e=>window.location.assign(`${e}/`),Zve=({organization:e,editable:t,onSaved:n})=>{let{session:r}=U(),[i,a]=(0,o.useState)(e.name),[s,c]=(0,o.useState)(e.slug),{busy:l,error:u,run:d}=Jh(),f=i.trim()!==e.name||s!==e.slug;return(0,H.jsxs)(Cf,{title:`Details`,description:t?`The name people see, and the slug that names it in links.`:`Owners and admins can change these.`,children:[(0,H.jsx)(wf,{message:u}),(0,H.jsxs)(`form`,{className:`flex flex-col gap-2 sm:flex-row`,onSubmit:t=>{t.preventDefault(),d(async()=>{await r.organizations.rename(e.id,{name:i.trim(),slug:s}),n()})},children:[(0,H.jsx)(wd,{"aria-label":`Name`,value:i,disabled:!t,onChange:e=>a(e.target.value),wrapperClassName:`flex-1`}),(0,H.jsx)(wd,{"aria-label":`Slug`,value:s,disabled:!t,onChange:e=>c(e.target.value),wrapperClassName:`sm:w-48`}),t&&(0,H.jsx)(W,{type:`submit`,variant:`primary`,loading:l,disabled:!f||!i.trim(),children:`Save`})]})]})},Qve=({organization:e,memberId:t})=>{let{session:n}=U(),[r,i]=(0,o.useState)([]),[a,s]=(0,o.useState)(``),{busy:c,error:l,run:u}=Jh();return(0,o.useEffect)(()=>{n.organizations.members(e.id).then(e=>i(e.filter(e=>e.id!==t)),()=>i([]))},[n,e.id,t]),(0,H.jsxs)(Cf,{title:`Hand over`,description:`Make another member the owner. You stay as an admin.`,children:[(0,H.jsx)(wf,{message:l}),(0,H.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row`,children:[(0,H.jsxs)(`select`,{"aria-label":`New owner`,value:a,onChange:e=>s(e.target.value),className:`h-8 flex-1 rounded-md border border-border-strong bg-background px-2`,children:[(0,H.jsx)(`option`,{value:``,children:`Choose a member`}),r.map(e=>(0,H.jsxs)(`option`,{value:e.id,children:[e.name,` (`,e.email,`)`]},e.id))]}),(0,H.jsx)(W,{loading:c,disabled:!a,onClick:()=>void u(async()=>{await n.organizations.transferOwnership(a),window.location.reload()}),children:`Hand over`})]})]})},$ve=({organization:e,basePath:t})=>{let{session:n}=U(),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)(``),{busy:c,error:l,run:u}=Jh(),d=()=>u(async()=>{await n.organizations.remove(e.id),O9(t)});return(0,H.jsxs)(Cf,{title:`Delete organization`,description:`Takes the organization and its members and invitations away. Its records must be deleted first.`,children:[(0,H.jsx)(wf,{message:r?void 0:l}),(0,H.jsx)(W,{variant:`danger`,onClick:()=>i(!0),children:`Delete organization`}),r&&(0,H.jsxs)(Sf,{title:`Delete ${e.name}?`,description:`Type its name to confirm. This cannot be undone.`,onClose:()=>i(!1),actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:()=>i(!1),children:`Cancel`}),(0,H.jsx)(W,{variant:`danger`,loading:c,disabled:a!==e.name,onClick:()=>void d(),children:`Delete`})]}),children:[(0,H.jsx)(wf,{message:l}),(0,H.jsx)(wd,{"aria-label":`Organization name`,value:a,onChange:e=>s(e.target.value)})]})]})},eye=({organization:e,basePath:t,owner:n})=>{let{session:r}=U(),{busy:i,error:a,run:o}=Jh();return(0,H.jsxs)(Cf,{title:`Leave`,description:n?`An organization keeps an owner: hand it over before you leave, unless it has another owner.`:`You stop being a member, and lose your roles here.`,children:[(0,H.jsx)(wf,{message:a}),(0,H.jsxs)(W,{loading:i,onClick:()=>void o(async()=>{await r.organizations.leave(e.id),O9(t)}),children:[`Leave `,e.name]})]})},tye=({current:e,basePath:t,onChanged:n})=>{let r=e?.organization;if(!r)return(0,H.jsx)(`div`,{className:`mx-auto w-full max-w-3xl px-4 py-6 md:px-6`,children:(0,H.jsx)(Pd,{title:`Organization`,subtitle:`You do not work in an organization now. Choose one under Organizations.`})});let i=e.role===`owner`;return(0,H.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,H.jsx)(Pd,{title:r.name,subtitle:e.role?`You are ${Wh[e.role].toLowerCase()} here.`:`You work here through your global roles, without being a member.`}),(0,H.jsx)(Zve,{organization:r,editable:Kh(e),onSaved:n},`${r.name}/${r.slug}`),i&&e.memberId&&(0,H.jsx)(Qve,{organization:r,memberId:e.memberId}),e.role&&(0,H.jsx)(eye,{organization:r,basePath:t,owner:i}),i&&(0,H.jsx)($ve,{organization:r,basePath:t})]})},k9=e=>e.normalize(`NFKD`).replace(/[̀-ͯ]/g,``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,63),A9=({organization:e,current:t,busy:n,onOpen:r})=>(0,H.jsxs)(`li`,{className:`flex items-center gap-3 px-3 py-2.5`,children:[(0,H.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,H.jsx)(`span`,{className:`block truncate font-medium`,children:e.name}),(0,H.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:e.slug})]}),t?(0,H.jsx)(Xu,{tone:`green`,children:`Current`}):(0,H.jsx)(W,{size:`sm`,loading:n,onClick:r,children:`Open`})]}),nye=({basePath:e})=>{let{session:t}=U(),[n,r]=(0,o.useState)(``),[i,a]=(0,o.useState)(),{busy:s,error:c,run:l}=Jh(),u=()=>l(async()=>{await t.organizations.create({name:n.trim(),slug:i??k9(n)}),O9(e)});return(0,H.jsxs)(Cf,{title:`New organization`,description:`You become its owner, with every role, and work in it once it is made.`,children:[(0,H.jsx)(wf,{message:c}),(0,H.jsxs)(`form`,{className:`flex flex-col gap-2 sm:flex-row`,onSubmit:e=>{e.preventDefault(),u()},children:[(0,H.jsx)(wd,{"aria-label":`Name`,placeholder:`Name`,value:n,onChange:e=>r(e.target.value),wrapperClassName:`flex-1`}),(0,H.jsx)(wd,{"aria-label":`Slug`,placeholder:`slug`,value:i??k9(n),onChange:e=>a(e.target.value),wrapperClassName:`sm:w-48`}),(0,H.jsx)(W,{type:`submit`,variant:`primary`,loading:s,disabled:!n.trim(),children:`Create`})]})]})},rye=({basePath:e,currentId:t})=>{let{session:n}=U(),[r,i]=(0,o.useState)(``),[a,s]=(0,o.useState)([]),{busy:c,error:l,run:u}=Jh();return(0,o.useEffect)(()=>{let e=setTimeout(()=>void n.organizations.search(r).then(s,()=>s([])),200);return()=>clearTimeout(e)},[n,r]),(0,H.jsxs)(Cf,{title:`Find an organization`,description:`Your global roles let you work in any organization, with what those roles allow there. Opening one you are not a member of is written to the audit log.`,children:[(0,H.jsx)(wf,{message:l}),(0,H.jsx)(wd,{"aria-label":`Find an organization`,placeholder:`Name or slug`,value:r,onChange:e=>i(e.target.value),leading:(0,H.jsx)(fn,{className:`size-3.5`}),wrapperClassName:`mb-3`}),a.length>0&&(0,H.jsx)(`ul`,{className:`divide-y rounded-md border`,children:a.map(r=>(0,H.jsx)(A9,{organization:r,current:r.id===t,busy:c,onOpen:()=>void u(async()=>{await n.organizations.switchTo(r.id),O9(e)})},r.id))})]})},iye=()=>{let{session:e,organizations:t}=U(),[n,r]=(0,o.useState)([]);if((0,o.useEffect)(()=>{e.organizations.myInvitations().then(r,()=>r([]))},[e]),n.length===0)return null;let i=t?.roles??[];return(0,H.jsx)(Cf,{title:`Invitations for you`,description:`Open the link in the invitation email to accept one.`,children:(0,H.jsx)(`ul`,{className:`divide-y rounded-md border`,children:n.map(e=>(0,H.jsxs)(`li`,{className:`px-3 py-2.5`,children:[(0,H.jsx)(`span`,{className:`font-medium`,children:e.organizationName??`An organization`}),`: `,e.appRoles.map(e=>Gh(i,e)).join(`, `)||`no app roles`,(0,H.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[`Until `,new Date(e.expiresAt).toLocaleDateString()]})]},e.id))})})},aye=({state:e,basePath:t})=>{let{session:n,organizations:r,state:i}=U(),{busy:a,error:o,run:s}=Jh(),c=i.kind===`signed-in`?i.user:void 0,l=r?.create===`everyone`||c!==void 0&&xg(c),u=e.current?.organization?.id;return(0,H.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,H.jsx)(Pd,{title:`Organizations`,subtitle:`You work in one organization at a time; what you see follows from your roles there.`}),(0,H.jsxs)(Cf,{title:`Your organizations`,description:e.organizations.length>0?`The organizations you are a member of.`:`You are not a member of an organization yet.`,children:[(0,H.jsx)(wf,{message:o??e.error}),e.organizations.length>0&&(0,H.jsx)(`ul`,{className:`divide-y rounded-md border`,children:e.organizations.map(e=>(0,H.jsx)(A9,{organization:e,current:e.id===u,busy:a,onOpen:()=>void s(async()=>{await n.organizations.switchTo(e.id),O9(t)})},e.id))})]}),(0,H.jsx)(iye,{}),l&&(0,H.jsx)(nye,{basePath:t}),(e.current?.globalRoles.length??0)>0&&(0,H.jsx)(rye,{basePath:t,currentId:u})]})},oye=(e,t)=>t?.active?{...e,role:t.active}:e,j9=(e,t)=>e instanceof lc?zd(e):t,sye=(e,t=!0)=>{let{session:n}=U(),r=Ig(),[i,a]=(0,o.useState)();(0,o.useEffect)(()=>{t&&n.roles.current().then(a,e=>r.show({state:`error`,title:j9(e,`Could not read your roles`)}))},[n,r,t]);let s=(0,o.useCallback)(t=>void n.roles.switchTo(t).then(e,e=>r.show({state:`error`,title:j9(e,`Could not switch the role`)})),[n,r,e]);return{...i&&{current:i},switchTo:s}},M9=e=>new Set((e.userMenu?.items??[]).flatMap(e=>e.kind===`resource`?[e.resource]:e.kind===`page`?[e.page]:[])),cye=(e,t,n)=>(e.userMenu?.items??[]).map((r,i)=>{if(r.kind===`link`)return{id:`link-${i}`,label:r.label,icon:s_(r.icon,Je),href:r.href,external:!0};if(r.kind===`page`){let i=e.pages[r.page];return{id:r.page,label:r.label??i?.title??q(r.page),icon:s_(r.icon??i?.icon,bt),href:us({kind:`page`,page:r.page},t),active:r.page===n}}return{id:r.resource,label:r.label??e.views[r.resource]?.names?.plural??q(r.resource),icon:s_(r.icon,a_(r.resource)),href:us({kind:`list`,resource:r.resource},t),active:r.resource===n}}),lye={sales:`Sales`,crm:`CRM`,catalog:`Catalog`,inventory:`Inventory`,core:`Admin`,hr:`HR`},uye=(e,t=``,n={})=>{let r=new Map,i=new Map,a=M9(e);for(let n of Object.values(e.pages)){if(n.nav?.hidden||a.has(n.name))continue;let e=n.nav?.group??`Pages`,o=r.get(e)??{label:e,items:[]};o.items.push({id:n.name,label:n.title,icon:s_(n.icon,bt),href:us({kind:`page`,page:n.name},t)}),r.set(e,o),i.set(n.name,n.nav?.order??2**53-1)}for(let o of Object.values(e.resources)){let s=e.views[o.name];if(!s||s.nav?.hidden||a.has(o.name))continue;let c=o.table.schema??`public`,l=s.nav?.group??lye[c]??q(c),u=r.get(l)??{label:l,items:[]};u.items.push({id:o.name,label:s.names?.plural??q(o.name),icon:a_(o.name),href:us({kind:`list`,resource:o.name},t),...n[o.name]&&{recent:n[o.name]}}),r.set(l,u),i.set(o.name,s.nav?.order??2**53-1)}for(let n of Object.values(e.signIn??{})){if(n.nav?.hidden||a.has(n.resource))continue;let e=n.nav?.group??`Account`,o=r.get(e)??{label:e,items:[]};o.items.push({id:n.resource,label:n.names?.plural??q(n.resource),icon:a_(n.resource),href:us({kind:`list`,resource:n.resource},t)}),r.set(e,o),i.set(n.resource,n.nav?.order??2**53-1)}for(let n of e.sources??[]){if(n.state!==`error`)continue;let e=r.get(n.source.label)??{label:n.source.label,items:[]};for(let r of n.source.resources)e.items.push({id:r,label:q(r),icon:a_(r),href:us({kind:`list`,resource:r},t),problem:`Cannot reach ${n.source.label}`});r.set(n.source.label,e)}return[...r.values()].map(e=>({...e,items:[...e.items].sort((e,t)=>(i.get(e.id)??0)-(i.get(t.id)??0))}))},dye=e=>{let t=Xg().shell?.logo;return t?(0,H.jsx)(tg,{name:`shell.logo`,fallback:(0,H.jsx)(Ru,{...e}),children:(0,H.jsx)(t,{...e})}):(0,H.jsx)(Ru,{...e})},N9=(0,o.createContext)([]),fye=()=>(0,o.useContext)(N9),pye=({ui:e,children:t})=>{let{plugins:n=[]}=J(),{loads:r,settled:i}=vg(n,gg()),a=(0,o.useMemo)(()=>cg(e,r),[e,r]);return i?(0,H.jsx)(Yg.Provider,{value:a.ui,children:(0,H.jsx)(N9.Provider,{value:a.off,children:t})}):(0,H.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,H.jsx)(Ed,{}),` Loading`]})},mye=({off:e})=>{let[t,n]=(0,o.useState)(!1);return t||e.length===0?null:(0,H.jsxs)(`div`,{role:`region`,"aria-label":`Plugins off`,className:`flex items-start gap-3 border-b border-warning/40 bg-warning-soft px-4 py-2 text-warning-text`,children:[(0,H.jsx)(an,{"aria-hidden":!0,className:`mt-0.5 size-4 shrink-0`}),(0,H.jsx)(`ul`,{className:`min-w-0 flex-1 space-y-0.5 break-words`,children:e.map(e=>(0,H.jsxs)(`li`,{children:[`The plugin `,(0,H.jsx)(`span`,{className:`font-semibold`,children:e.name??e.url}),` is off: `,e.reason,`.`]},e.url))}),(0,H.jsx)(`button`,{type:`button`,"aria-label":`Dismiss`,className:`rounded p-0.5 hover:bg-warning/10`,onClick:()=>n(!0),children:(0,H.jsx)(Qn,{"aria-hidden":!0,className:`size-4`})})]})},P9=(e,t)=>[`${t}_at`,`${t}At`].find(t=>e.fields[t]),F9=({item:e,scope:t})=>{let{components:n}=Xg(),r=n?.[e.component],i=r?(0,H.jsx)(Nw,{value:t,children:(0,H.jsx)(tg,{name:e.component,children:(0,H.jsx)(r,{...ho(e.props??{})})})}):(0,H.jsxs)(eg,{children:[`No component is registered as `,e.component,`. Export it from protobase.ui.tsx, or load the plugin that provides it.`]});return e.sidebar?e.title?(0,H.jsx)(Ex,{title:e.title,children:i}):i:e.title?(0,H.jsx)(xx,{title:e.title,children:i}):(0,H.jsx)(`section`,{className:`py-8`,children:i})},hye=(0,o.lazy)(()=>Xh(()=>import(`./record-map-ChUVZLR6.js`).then(e=>({default:e.RecordMap})),__vite__mapDeps([8,1,5,2,6,3,7]))),gye=15,I9=({item:e,record:t})=>{let n=J().maps,r=n?.style,i=j5(t,e);if(!r||!i)return null;let a=(0,H.jsx)(`div`,{className:`overflow-hidden rounded-lg border border-border bg-muted ${e.sidebar?`h-48`:`h-64 md:h-80`}`,children:(0,H.jsx)(o.Suspense,{fallback:null,children:(0,H.jsx)(hye,{style:r,layers:n?.layers,position:i,zoom:e.zoom??gye},`${i.latitude},${i.longitude}`)})});return e.sidebar?(0,H.jsx)(Ex,{title:e.title,children:a}):(0,H.jsx)(xx,{title:e.title,children:a})},_ye=e=>U8(e)??er,vye=({model:e,stored:t,recordKey:n,edit:r,onDelete:i})=>{let{go:a}=PC(),s={model:e,record:t.record,key:n,etag:t.etag,permissions:t.permissions},c=Qw(e.name,s,t=>t.run?.kind===`delete`&&a({kind:`list`,resource:e.name},{replace:!0})),[l,u]=(0,o.useState)(),d=c.actions.map(e=>({name:e.label,icon:_ye(e.icon),blocked:c.blocked(e),running:c.running===e.name,...e.run?.kind===`delete`&&{tone:`danger`},onRun:()=>Aw(e)?u(e):void c.run(e)})),f=c.actions.some(e=>e.run?.kind===`delete`),p=[...r?[{name:`Edit`,icon:en,render:({className:e,children:t})=>(0,H.jsx)(FC,{to:r,className:e,children:t})}]:[],...d,...i&&!f?[{name:`Delete`,icon:Rn,tone:`danger`,onRun:i}]:[]];return p.length===0?null:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Cx,{actions:p}),l&&(0,H.jsx)(jw,{action:l,label:l.label,danger:l.run?.kind===`delete`,onCancel:()=>u(void 0),onConfirm:()=>{u(void 0),c.run(l)},onSubmit:async e=>{await c.submit(l,e),u(void 0)}})]})},yye=(e,t)=>Object.values(e).find(e=>e.name!==t.name&&e.fields.position&&e.fields.quantity&&Object.values(e.fields).some(e=>e.type===`relation`&&e.relation?.resource===t.name)),bye=e=>({id:String(e.id),productId:String(e.productId??``),description:String(e.description??``),quantity:Number(e.quantity),unitPriceCents:Math.round(Number(e.unitPrice)*100)}),xye=({lines:e,draft:t,vatRate:n,saving:r,locked:i=!1})=>{let a=Fw(d_(e.name),`update`);return(0,H.jsx)(xx,{title:`Lines`,help:`What the document bills for. Drag the handle, or use the menu, to change the order; Save applies it.`,children:(0,H.jsx)(`div`,{className:`-mx-4 overflow-x-auto px-4 [-webkit-overflow-scrolling:touch] md:mx-0 md:px-0`,children:(0,H.jsx)(`div`,{className:`min-w-[560px]`,children:(0,H.jsx)(yx,{lines:t.shown.map(bye),onChange:()=>void 0,onReorder:e=>t.setOrder(e.map(e=>e.id)),vatRate:n,readOnly:!0,reorderable:a&&!r&&!i})})})})},Sye=(e,t,n)=>`protobase:draft:${e}:${t}:${n}`,Cye=(e,t,n)=>id(()=>{let r=e.getItem(t);if(r===null)return;let i=JSON.parse(r);if(i&&i.etag===n&&typeof i.fields==`object`&&i.fields!==null)return{etag:n,fields:i.fields,...Array.isArray(i.order)&&{order:i.order.map(String)}}},void 0),wye=(e,t,n)=>id(()=>n?e.setItem(t,JSON.stringify(n)):e.removeItem(t),void 0),Tye=(e,t)=>Number(e.position)-Number(t.position),Eye=(e,t,n)=>{let r=e&&Object.values(e.fields).find(e=>e.type===`relation`&&e.relation?.resource===t.name),i=IC(e?.name??``,{enabled:!!(e&&r),filter:r?`${r.name} = "${n}"`:void 0,pageSize:200,...e?.fields.position?.sortable&&{orderBy:`position asc`}});return{items:[...i.items].sort(Tye),loading:i.isPending&&!!e}},Dye=(e,t)=>{let[n,r]=(0,o.useState)(),i=t.map(e=>String(e.id)),a=(0,o.useMemo)(()=>{if(!n)return t;let e=n.flatMap(e=>t.filter(t=>String(t.id)===e)),r=t.filter(e=>!n.includes(String(e.id)));return[...e,...r]},[n,t]),s=a.map(e=>String(e.id)),c=n!==void 0&&s.some((e,t)=>e!==i[t]),l=(0,o.useCallback)(()=>!e||!c?[]:[{op:`reorder`,resource:e.name,field:`position`,keys:a.map(t=>Ag(e,t)),etags:Object.fromEntries(a.flatMap(t=>typeof t.etag==`string`?[[Ao(Ag(e,t)),t.etag]]:[]))}],[e,c,a]);return{shown:a,dirty:c,order:c?s:void 0,setOrder:e=>r(e),reset:()=>r(void 0),op:l}},Oye=e=>{let t=e>=5?5:e===4?3:e;return{shown:t,more:e-t}},kye=(e,t)=>Math.abs(e)<40||Math.abs(e)<=Math.abs(t)?0:e<0?1:-1,Aye=e=>e===`ArrowRight`?1:e===`ArrowLeft`?-1:0,jye=(e,t,n)=>Math.min(Math.max(e+t,0),Math.max(n-1,0)),Mye=e=>e.key===`i`&&!e.ctrlKey&&!e.metaKey&&!e.altKey,L9=`protobase:lightbox-details`,Nye=e=>id(()=>e.getItem(L9)===`true`,!1),Pye=(e,t)=>id(()=>t?e.setItem(L9,`true`):e.removeItem(L9),void 0),R9=`flex size-10 shrink-0 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40`,Fye=({title:e,photos:t,index:n,onIndex:r,onClose:i,details:a,detailsTitle:s=`Details`})=>{let c=(0,o.useRef)(null),l=(0,o.useRef)(void 0),u=(0,o.useId)(),d=pu(),[f,p]=(0,o.useState)(()=>Nye(localStorage)),[m,h]=(0,o.useState)(!1);Su(c,!0,i),(0,o.useEffect)(()=>h(!0),[]);let g=t.length,_=e=>{let t=jye(n,e,g);t!==n&&r(t)},v=Vx(t[n],{width:1600,height:1200}),y=a?.(n),b=y!==void 0,x=e=>{p(e),Pye(localStorage,e)};return(0,H.jsxs)(`div`,{ref:c,tabIndex:-1,role:`dialog`,"aria-modal":`true`,"aria-label":e,onKeyDown:e=>{if(b&&Mye(e))return e.preventDefault(),x(!f);let t=Aye(e.key);t!==0&&(e.preventDefault(),_(t))},className:`fixed inset-0 z-[90] flex flex-col overflow-y-auto overscroll-contain bg-backdrop outline-none md:flex-row`,children:[(0,H.jsxs)(`div`,{className:`flex h-dvh shrink-0 flex-col md:sticky md:top-0 md:min-w-0 md:flex-1`,children:[(0,H.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 p-3`,children:[(0,H.jsx)(`span`,{className:`rounded-full bg-background/85 px-3 py-1 font-medium tabular-nums text-foreground`,"aria-live":`polite`,children:`${n+1} / ${g}`}),(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[b&&(0,H.jsx)(`button`,{type:`button`,className:V(R9,`aria-expanded:bg-foreground aria-expanded:text-background`),"aria-label":s,"aria-expanded":f,"aria-controls":d?u:void 0,"aria-keyshortcuts":`i`,onClick:()=>x(!f),children:(0,H.jsx)(mt,{className:`size-4`,"aria-hidden":!0})}),(0,H.jsx)(`button`,{type:`button`,className:R9,"aria-label":`Close`,onClick:i,children:(0,H.jsx)(Qn,{className:`size-4`,"aria-hidden":!0})})]})]}),(0,H.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 touch-pan-y items-center justify-center px-3 pb-3 md:px-16`,onPointerDown:e=>{e.pointerType===`touch`&&(l.current={x:e.clientX,y:e.clientY})},onPointerUp:e=>{l.current&&=(_(kye(e.clientX-l.current.x,e.clientY-l.current.y)),void 0)},onPointerCancel:()=>l.current=void 0,children:[v&&(0,H.jsx)($C,{image:v,className:`max-h-full max-w-full select-none object-contain`},v.url),g>1&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`button`,{type:`button`,className:V(R9,`absolute left-3 top-1/2 -translate-y-1/2 aria-disabled:cursor-default aria-disabled:opacity-40`),"aria-label":`Previous photo`,"aria-disabled":n===0,onClick:()=>_(-1),children:(0,H.jsx)(ye,{className:`size-5`,"aria-hidden":!0})}),(0,H.jsx)(`button`,{type:`button`,className:V(R9,`absolute right-3 top-1/2 -translate-y-1/2 aria-disabled:cursor-default aria-disabled:opacity-40`),"aria-label":`Next photo`,"aria-disabled":n===g-1,onClick:()=>_(1),children:(0,H.jsx)(xe,{className:`size-5`,"aria-hidden":!0})})]})]})]}),b&&f&&d&&(0,H.jsxs)(`aside`,{id:u,"aria-label":s,className:`min-h-dvh w-[360px] shrink-0 border-l border-border bg-background p-5 text-foreground`,children:[(0,H.jsx)(`h2`,{className:`mb-3 text-[16px] font-semibold`,children:s}),y]}),(0,H.jsx)(p_,{title:s,open:b&&f&&!d&&m,onClose:()=>x(!1),children:(0,H.jsx)(`div`,{className:`pt-3`,children:y})})]})},Iye=(e,t,n)=>{let r=(t?.layout??[]).flatMap(e=>e.kind===`section`&&nS(e.when,!1)?e.fields:[]);return(r.length>0?[...new Set(r)]:Object.keys(e.fields).filter(t=>t!==e.tenant&&!e.primaryKey.includes(t))).filter(r=>e.fields[r]&&!e.fields[r].sensitive&&!n.includes(r)&&nS(t?.fields[r]?.when,!1))},Lye=({model:e,view:t,photoKey:n,fields:r})=>{let i=Cg(e.name,n),a=(t?.names?.singular??q(e.name)).toLowerCase();if(i.isPending)return(0,H.jsx)(ku,{className:`h-4 w-48`});if(i.error)return(0,H.jsx)(pS,{title:`Could not load the ${a}`,error:i.error});let o=r.filter(e=>Lw(i.data.permissions,e)!==`hidden`);return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(kx,{rows:o.map(n=>({label:t?.fields[n]?.label??q(n),value:(0,H.jsx)(N4,{model:e,field:e.fields[n],value:i.data.record[n]})}))}),(0,H.jsx)(FC,{to:{kind:`record`,resource:e.name,key:n},className:`mt-3 inline-block font-medium text-primary-text hover:underline`,children:`Open ${a}`})]})},z9=e=>Vx(e,{width:0,height:0})!==void 0,Rye=(e,t)=>{let n=e.primaryKey.map(e=>t[e]);if(!n.some(e=>e==null))return Ao(n)},zye=(e,t,n,r)=>{let i=n===void 0?[]:t.flatMap(e=>{let t=e[n];if(!jx(t)||!z9(t))return[];let i=r&&Rye(r,e);return[{file:t,...i!==void 0&&{key:i}}]});if(!jx(e)||!z9(e))return i;let a=t=>jx(t.file)&&t.file.uri===e.uri,o=i.find(a)?.key;return[{file:e,...o!==void 0&&{key:o}},...i.filter(e=>!a(e))]},Bye=uo(),Vye=(e,t,n)=>{let r=K(),{resources:i}=J(),a=e.photos?i[e.photos.resource]:void 0,o=e.photos?Ya(Bye.eq(e.photos.field,n)):``,s=e.photos?.sort??``,c=_h({queryKey:G.list(a?.name??``,o,s,500,`gallery`),enabled:a!==void 0,queryFn:async()=>(await r.list(a.name,{filter:o,...s&&{orderBy:s},pageSize:500})).items});return{holder:a,items:zye(e.image===void 0?void 0:t[e.image],c.data??[],e.photos?.image,a),isPending:a!==void 0&&c.isPending,error:c.error}},Hye={1:[`md:col-span-4 md:row-span-2`],2:[`md:col-span-2 md:row-span-2`,`md:col-span-2 md:row-span-2`],3:[`md:col-span-2 md:row-span-2`,`md:col-span-2`,`md:col-span-2`],5:[`md:col-span-2 md:row-span-2`,``,``,``,``]},Uye=({photo:e,large:t})=>{let n=Vx(e,t?{width:960,height:720}:{width:480,height:360});return n?(0,H.jsx)($C,{image:n,loading:`lazy`,className:`size-full object-cover transition-transform duration-300 group-hover/tile:scale-[1.02]`}):null},Wye=({item:e,record:t,recordKey:n})=>{let{views:r}=J(),i=Vye(e,t,n),a=d_(i.holder?.name??``),[s,c]=(0,o.useState)();if(i.isPending)return(0,H.jsx)(xx,{title:e.title,children:(0,H.jsx)(ku,{className:`aspect-[4/3] w-full rounded-lg md:aspect-[2/1]`})});if(i.error)return(0,H.jsx)(xx,{title:e.title,children:(0,H.jsx)(pS,{title:`Could not load the photos`,error:i.error})});let l=i.items.length;if(l===0)return null;let{shown:u,more:d}=Oye(l),f=i.holder,p=f&&r[f.name],m=f?Iye(f,p,[e.photos?.image,e.photos?.field].filter(e=>e!==void 0)):[],h=f!==void 0&&a.read!==!1&&m.length>0;return(0,H.jsxs)(xx,{title:e.title,children:[(0,H.jsx)(`div`,{className:`grid aspect-[4/3] grid-cols-4 grid-rows-2 gap-1.5 overflow-hidden rounded-lg md:aspect-[2/1]`,children:i.items.slice(0,u).map((e,t)=>{let n=t===u-1&&d>0;return(0,H.jsxs)(`button`,{type:`button`,"aria-label":n?`Show all ${l} photos`:`Show photo ${t+1} of ${l}`,onClick:()=>c(t),className:V(`group/tile relative overflow-hidden bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary`,t===0?`col-span-4 row-span-2`:`max-md:hidden`,Hye[u][t]),children:[(0,H.jsx)(Uye,{photo:e.file,large:t===0}),n&&(0,H.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-backdrop/55 text-lg font-semibold text-white`,"aria-hidden":!0,children:`+${d}`}),t===0&&l>1&&(0,H.jsxs)(`span`,{className:`absolute bottom-2 right-2 flex items-center gap-1.5 rounded-full bg-background/85 px-2.5 py-1 text-xs font-medium tabular-nums text-foreground md:hidden`,"aria-hidden":!0,children:[(0,H.jsx)(ft,{className:`size-3.5`}),l]})]},t)})}),s!==void 0&&(0,H.jsx)(Fye,{title:e.title,photos:i.items.map(e=>e.file),index:s,onIndex:c,onClose:()=>c(void 0),details:e=>{let t=i.items[e]?.key;return h&&t!==void 0?(0,H.jsx)(Lye,{model:f,view:p,photoKey:t,fields:m},t):void 0},detailsTitle:f&&`${p?.names?.singular??q(f.name)} details`})]})},Gye={create:`created this`,update:`changed`,delete:`deleted this`,undelete:`restored this`},Kye=e=>e.actor?e.actor.name??e.actor.id:e.databaseRole?`Database (${e.databaseRole})`:`Database`,qye=(e,t,n)=>{let r=(e.operation===`create`?[]:e.changed).flatMap(r=>{let i=t.fields[r];if(!i||r===t.softDelete)return[];let a=n?.fields[r],o=a?.label??q(r);return i.sensitive||!e.before||!e.after?[{name:r,label:o}]:[{name:r,label:o,before:ZS(i,e.before[r],a),after:ZS(i,e.after[r],a)}]}),i=e.operation===`update`&&r.length===0?`changed this`:Gye[e.operation];return{who:Kye(e),verb:i,fields:r}},Jye=1500,Yye=(e,t,n,r)=>{let i=K(),a=yh({queryKey:G.history(e,t,n),initialPageParam:``,queryFn:({pageParam:r})=>i.history(e,t,{pageSize:n,pageToken:r}),getNextPageParam:e=>e.nextPageToken||void 0}),{refetch:s}=a;return(0,o.useEffect)(()=>{let e=setTimeout(()=>void s(),Jye);return()=>clearTimeout(e)},[r,s]),{...a,items:a.data?.pages.flatMap(e=>e.items)??[]}},Xye=()=>(0,H.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,H.jsx)(ku,{className:`h-4 w-full`},t))}),Zye=({change:e,model:t,view:n})=>{let{who:r,verb:i,fields:a}=qye(e,t,n),o=Date.parse(e.at);return(0,H.jsxs)(`li`,{className:`flex flex-col gap-1.5 py-3 first:pt-0 last:pb-0`,children:[(0,H.jsxs)(`p`,{children:[(0,H.jsx)(`span`,{className:`font-medium text-foreground`,children:r}),` `,(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:i}),` `,(0,H.jsxs)(`time`,{dateTime:e.at,title:mf(o),className:`text-muted-foreground`,children:[`· `,vf(Math.max(0,Math.round((Date.now()-o)/1e3)))]})]}),a.length>0&&(0,H.jsx)(`dl`,{className:`grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-4 gap-y-1`,children:a.map(e=>(0,H.jsxs)(`div`,{className:`contents`,children:[(0,H.jsx)(`dt`,{className:`text-muted-foreground`,children:e.label}),(0,H.jsx)(`dd`,{className:`min-w-0 break-words`,children:e.before===void 0?(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:`changed`}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`del`,{className:`text-muted-foreground`,children:e.before}),` → `,(0,H.jsx)(`ins`,{className:`no-underline`,children:e.after})]})})]},e.name))})]})},Qye=({item:e,model:t,view:n,recordKey:r,etag:i})=>{let a=Yye(t.name,r,e.limit??10,i);return(0,H.jsx)(xx,{title:e.title,children:a.isPending?(0,H.jsx)(Xye,{}):a.error?(0,H.jsx)(pS,{title:`Could not load the history`,error:a.error}):a.items.length===0?(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:`No changes kept yet.`}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(`ol`,{className:`divide-y divide-border`,children:a.items.map(e=>(0,H.jsx)(Zye,{change:e,model:t,view:n},e.id))}),a.hasNextPage&&(0,H.jsx)(W,{size:`sm`,className:`mt-4`,disabled:a.isFetchingNextPage,onClick:()=>void a.fetchNextPage(),children:`Show more`})]})})},B9=(e,t)=>{let n=K(),r=Up(),i=Ao(t);return vh({mutationFn:({patch:r,etag:i})=>n.update(e,t,r,i),onSuccess:t=>{r.setQueryData(G.record(e,i),t),r.invalidateQueries({queryKey:[`page`,e]}),r.invalidateQueries({queryKey:[`list`,e]}),r.invalidateQueries({queryKey:[`map`,e]})}})},V9=e=>e instanceof Ps,$ye=e=>{let t=typeof e.resource==`string`?e.resource:e.resource.toModel().name;return e.op===`reorder`?`reorder ${t} by ${e.field}`:`${e.op} ${t}`},ebe=(e,t)=>{let n=e.operation,r=n===void 0?void 0:t[n];return r?`Operation ${n+1} (${$ye(r)}) failed: ${e.message} Nothing was saved.`:`${e.message} Nothing was saved.`},tbe=(e,t)=>new e.constructor({...e.problem,detail:ebe(e,t)}),H9=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),nbe=({model:e,stored:t,recordKey:n,mode:r,subject:i,draftKey:a,lines:s})=>{let c=K(),l=Up(),u=B9(e.name,n),d=e7(r,i),[f]=(0,o.useState)(()=>a?Cye(localStorage,a,t.etag):void 0),[p,m]=(0,o.useState)(f?.fields??{}),[h,g]=(0,o.useState)(!!f),[_,v]=(0,o.useState)(!1),[y,b]=(0,o.useState)({}),[x,S]=(0,o.useState)({}),[C,w]=(0,o.useState)(0),T=Object.entries(p).filter(([n,r])=>Qx(e.fields[n],r,t.record[n])),E=T.length>0,D=E||!!s?.dirty;(0,o.useEffect)(()=>{f?.order&&s?.setOrder(f.order)},[]),(0,o.useEffect)(()=>{if(!a)return;let n=Object.fromEntries(Object.entries(p).filter(([t])=>!e.fields[t]?.sensitive)),r=Object.keys(n).length>0||!!s?.dirty;wye(localStorage,a,r?{etag:t.etag,fields:n,...s?.order&&{order:s.order}}:void 0)},[a,e,p,s?.dirty,s?.order,t.etag]);let O=n=>n in p?p[n]:[`boolean`,`file`].includes(e.fields[n].type)?t.record[n]:Gx(t.record[n]),k=(n,r)=>{S(e=>H9(e,n));let i=typeof r==`string`?r!==Gx(t.record[n]):Qx(e.fields[n],r,t.record[n]);m(e=>i?{...e,[n]:r}:H9(e,n))},A=async()=>{let r=await c.get(e.name,n);l.setQueryData(G.record(e.name,n),r);let i={},a={};for(let[n,o]of Object.entries(p)){let s=e.fields[n];Qx(s,o,r.record[n])&&(a[n]=o,Gx(r.record[n])!==Gx(t.record[n])&&(i[n]=s.type===`file`?ZS(s,r.record[n]):Gx(r.record[n])))}m(a),b(i)},j=()=>Object.fromEntries(T.map(([t,n])=>[t,Yx(e.fields[t],n)])),M=e=>{let t=H4(e);S(t),Object.keys(t).length>0&&w(e=>e+1)},N=async()=>{try{await u.mutateAsync({patch:j(),etag:t.etag})}catch(e){throw V9(e)?await A():Fs(e)&&M(e),e}},ee=async r=>{let i=[...E?[{op:`update`,resource:e.name,key:n,data:j(),etag:t.etag}]:[],...r];try{await c.batchWrite(i)}catch(e){throw V9(e)?(await A(),await l.invalidateQueries({queryKey:[`list`]}),v(!0)):Fs(e)&&M(e),Fs(e)?tbe(e,i):e}await Promise.all([l.invalidateQueries({queryKey:G.record(e.name,n)}),l.invalidateQueries({queryKey:[`list`]}),l.invalidateQueries({queryKey:[`page`]}),l.invalidateQueries({queryKey:[`map`]})]),s?.reset()};return{value:O,change:k,save:()=>d.run(async()=>{let e=s?.op()??[];e.length>0?await ee(e):await N(),m({}),b({}),S({}),v(!1),g(!1)}),dirty:D,discard:()=>{m({}),b({}),S({}),v(!1),g(!1),s?.reset()},restored:h&&D,dismissRestored:()=>g(!1),linesConflict:_,saving:d.phase===`saving`,phase:d.phase,message:d.message,conflicts:y,errors:x,rejections:C,keepMine:e=>b(t=>H9(t,e)),useTheirs:e=>{b(t=>H9(t,e)),m(t=>H9(t,e))}}},U9=(e,t,n,r,i,a)=>{let o=K(),s=Up(),c=Object.values(e.fields).filter(t=>t.type===`relation`&&t.relation&&t.name!==e.tenant&&i[t.name]!=null&&n[t.relation.resource]?.primaryKey.length===1),l=hh({queries:c.map(e=>{let t=n[e.relation.resource],a=String(i[e.name]);return{queryKey:G.relatedLabel(t.name,a),queryFn:async()=>(await D4(s,o,t,[a],r[t.name])).get(a)??a}})}),u=c.map(e=>({kind:`record`,resource:e.relation.resource,key:String(i[e.name])}));return{addresses:Object.fromEntries(c.map((e,t)=>[e.name,u[t]])),labels:Object.fromEntries(c.map((e,t)=>[e.name,l[t]?.data])),records:c.map((e,n)=>({kind:t?.fields[e.name]?.label??q(e.name),label:l[n]?.data??String(i[e.name]),href:us(u[n],a)}))}},W9=uo(),G9=(...e)=>{let t=e.filter(e=>!!e);return t.length===1?t[0]:t.map(e=>`(${e})`).join(` AND `)},rbe=(e,t)=>{let n=K(),{resources:r}=J(),i=e.through,a=i?r[i.resource]:void 0,o=i?.key??a?.primaryKey[0],s=i?G9(Ya(W9.eq(i.field,t)),i.filter):``,c=_h({queryKey:G.list(a?.name??``,s,``,0,`related:${o}`),enabled:!!(a&&o),queryFn:async()=>{let e=await Y6(n,a.name,{filter:s,fields:[o]});return[...new Set(e.items.flatMap(e=>e[o]===null||e[o]===void 0?[]:[String(e[o])]))]}});return i?c.data?{filter:c.data.length===0?null:G9(Ya(W9.in(e.field,c.data)),e.filter),isPending:!1,error:null}:{filter:void 0,isPending:c.isPending,error:c.error}:{filter:G9(Ya(W9.eq(e.field,t)),e.filter),isPending:!1,error:null}},ibe=()=>(0,H.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,H.jsx)(ku,{className:`h-4 w-full`},t))}),abe=({text:e})=>(0,H.jsx)(`p`,{className:`text-muted-foreground`,children:e??`Nothing here yet.`}),obe=({item:e,recordKey:t,owner:n})=>{let{resources:r,views:i}=J(),a=r[e.resource],s=a&&i[a.name],c=rbe(e,t),[l,u]=Y5(s,`related:${n}:${e.title}`,e.display),d=d_(e.resource),[f,p]=(0,o.useState)(!1);if(!a)return null;let m=e.columns??JS(a,s).filter(t=>t!==e.field),h=Bve(e,a,d),g=(0,H.jsx)(q5,{view:s,value:l,onChange:u}),_=h?(0,H.jsxs)(`div`,{className:`flex items-center gap-2`,children:[!f&&g,(0,H.jsx)(C9,{size:`sm`,sorting:f,onChange:p})]}):g;return f&&h?(0,H.jsx)(xx,{title:e.title,help:e.help,actions:_,children:(0,H.jsx)(S9,{model:a,view:s,field:h,filter:Ya(W9.eq(e.field,t)),columns:m})}):(0,H.jsx)(xx,{title:e.title,help:e.help,actions:_,children:c.isPending?(0,H.jsx)(ibe,{}):c.error?(0,H.jsx)(pS,{title:`Could not load`,error:c.error}):c.filter===null||c.filter===void 0?(0,H.jsx)(abe,{text:e.empty}):(0,H.jsx)(J5,{model:a,view:s,filter:c.filter,sort:e.sort??``,columns:m,limit:e.limit??10,display:l,empty:e.empty},c.filter)})},sbe=(e,t)=>t===e.tenant||e.primaryKey.includes(t),cbe=(e,t,n)=>{if(t&&t.layout.length>0)return t.layout;let r=Object.values(e.fields).filter(t=>!sbe(e,t.name)),i=r.filter(e=>!e.readOnly);return[{kind:`section`,title:`Details`,fields:(i.length>0&&!n?i:r).map(e=>e.name)},...e.history?[{kind:`history`,title:`History`}]:[]]},lbe=({resource:e,recordKey:t})=>{let{resources:n}=J(),r=n[e],i=wg(e,t);return r?i.isPending?(0,H.jsx)(u_,{title:`Loading`,children:`Fetching the record.`}):i.error?(0,H.jsx)(`div`,{className:`p-8`,children:Fs(i.error)&&i.error.status===404?(0,H.jsx)(u_,{title:`Not found`,children:`This record does not exist, or you cannot see it.`}):(0,H.jsx)(pS,{title:`Could not load the record`,error:i.error})}):(0,H.jsx)(ube,{model:r,recordKey:t,stored:i.data,preview:i.isPlaceholderData},i.isPlaceholderData?`preview`:`loaded`):(0,H.jsxs)(u_,{title:`Not found`,children:[`There is no resource called `,e,`.`]})},ube=({model:e,recordKey:t,stored:n,preview:r})=>{let i=J(),{basePath:a}=Dh(),{address:s,go:c,open:l}=PC(),u=i.views[e.name],d=Dg(e,u,n.record,t),{state:f}=U(),p=(0,o.useMemo)(()=>yye(i.resources,e),[i.resources,e]),m=Dye(p,Eye(p,e,t).items),h=nbe({model:e,stored:n,recordKey:t,mode:u?.saveFeedback??`toast`,subject:d,draftKey:!r&&f.kind===`signed-in`?Sye(f.user.id,e.name,t):void 0,lines:m}),g=Up(),_=K(),v=U4(h.rejections),y=d_(e.name),b=i7(e),x=Fw(y,`update`)&&n.permissions?.update!==!1,{shown:S,offersEdit:C,editing:w}=$x(u?.recordMode,x,s?.kind===`record`&&s.edit===!0);sne(h.dirty&&S===`form`),ene(h.dirty);let T={kind:`record`,resource:e.name,key:t},E={...T,edit:!0},D=S===`form`&&u?.recordMode!==void 0&&u.recordMode!==`edit`,O=Fw(y,`delete`)&&n.permissions?.delete!==!1,k=r7({model:e,view:u,restore:b,onDeleted:()=>c({kind:`list`,resource:e.name},{replace:!0}),onReview:()=>void g.invalidateQueries({queryKey:G.record(e.name,t)})}),A=U9(e,u,i.resources,i.views,n.record,a),j=t=>{let n=e.fields[t],r=n?.relation?i.resources[n.relation.resource]:void 0;if(r&&r.primaryKey.length===1&&t!==e.tenant&&!e.primaryKey.includes(t))return r},M=Object.values(e.fields).filter(e=>j(e.name)),N={...n.record,...Object.fromEntries(M.map(e=>[e.name,Xx(e,h.value(e.name))]))},ee=U9(e,u,i.resources,i.views,N,a),P=(e,t)=>{let n=j(e);if(!n||!rS(t))return h.change(e,t);g.setQueryData(G.relatedLabel(n.name,t.key),t.label),h.change(e,oS(n,t.key))},{fields:te}=Xg(),F=cbe(e,u,S===`read`).filter(e=>nS(e.when,w)),ne=F.flatMap(e=>e.kind===`sidebar`?e.fields:[]),re=e.fields.status?.type===`enum`,ie=n.record.status,I=re&&!ne.includes(`status`)&&ie!=null&&ie!==``?String(ie):void 0,ae=P9(e,`updated`),L=e=>u?.fields[e],oe=e=>Lw(n.permissions,e)!==`hidden`&&nS(L(e)?.when,w),R=e=>!r||Object.hasOwn(n.record,e),se=r=>{let a=e.fields[r],o=Lw(n.permissions,r);if(!a||o===`hidden`)return null;let s=h.conflicts[r],c=j(r),l=L(r)?.label??q(r),d=h.errors[r];return(0,H.jsx)(bx,{name:r,label:l,required:S===`form`&&o!==`read`&&Jx(a),help:tS(L(r),u,w),error:d&&V4(a,l,d),wide:!!(L(r)?.multiline||L(r)?.markdown),conflict:s===void 0?void 0:{user:{name:`Someone else`,initials:`?`,hue:40},ago:`just now`,theirValue:s||`—`,onKeepMine:()=>h.keepMine(r),onUseTheirs:()=>h.useTheirs(r)},children:R(r)?(0,H.jsx)(mw,{field:a,hints:L(r),value:h.value(r),stored:n.record[r],relationLabel:ee.labels[r],relationTo:ee.addresses[r],relationPicker:c&&{target:c,view:i.views[c.name]},locked:S!==`form`||o===`read`,invalid:!!h.errors[r],reveal:a.sensitive?()=>_.reveal(e.name,t,r):void 0,resource:e.name,onChange:e=>P(r,e)}):(0,H.jsx)(ku,{className:`h-9`})},a.sensitive?`${r}:${n.etag}`:r)},ce=r=>{let i=e.fields[r],a=R(r)?i.sensitive?(0,H.jsx)(mw,{field:i,hints:L(r),value:``,stored:n.record[r],locked:!0,reveal:()=>_.reveal(e.name,t,r),resource:e.name,onChange:e=>h.change(r,e)}):(0,H.jsx)(N4,{model:e,field:i,value:n.record[r],relationLabel:A.labels[r]}):(0,H.jsx)(ku,{className:`h-4 w-32`});return{label:L(r)?.label??q(r),help:tS(L(r),u,w),wide:!!(L(r)?.multiline||L(r)?.markdown),value:a}},le=F.findIndex(e=>e.kind===`sidebar`),ue=(0,H.jsx)(Dx,{title:`Summary`,rows:ne.flatMap(t=>{let r=e.fields[t];if(!r||!oe(t))return[];if(!R(t))return[{label:L(t)?.label??q(t),value:(0,H.jsx)(ku,{className:`h-4 w-24`})}];let i=ZS(r,n.record[t],L(t)),a=n.record[t],o=BS(r,L(t))&&typeof a==`string`&&a!==``,s=r.type===`enum`?(0,H.jsx)(M4,{value:a,hints:L(t),children:i}):o?(0,H.jsx)(cw,{source:a}):(0,H.jsx)(`strong`,{className:L(t)?.multiline?`whitespace-pre-line break-words`:void 0,children:i}),c=rw(te,r,L(t));return[{label:L(t)?.label??q(t),value:c?(0,H.jsx)(ow,{shown:c,part:`display`,field:r,value:n.record[t],fallback:s}):s}]})}),de={model:e,record:n.record,key:t,etag:n.etag,permissions:n.permissions},fe=async()=>{await h.save()&&D&&c(T,{replace:!0})},pe=O?()=>void k.start({key:t,title:d,etag:n.etag,snapshot:n.record}):void 0,me=S===`form`&&(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(W,{variant:`primary`,className:`max-md:min-h-11 max-md:flex-1 md:w-full`,loading:h.saving,disabled:!h.dirty&&h.phase!==`saved`,onClick:()=>void fe(),children:[h.phase===`saved`&&(0,H.jsx)(he,{className:`size-4`}),h.phase===`saved`?`Saved`:`Save`]}),D&&(0,H.jsx)(FC,{to:T,className:V(xf(),`max-md:min-h-11 md:w-full`),onClick:e=>Au(e)&&h.discard(),children:`Cancel`}),h.dirty&&(0,H.jsx)(`span`,{className:`text-xs text-muted-foreground max-md:order-first`,children:`Unsaved changes`})]});return(0,H.jsxs)(`div`,{ref:v,className:`flex flex-1 flex-col`,inert:r,children:[k.dialogs,(0,H.jsx)(`div`,{className:`flex-1`,children:(0,H.jsxs)(`div`,{className:`mx-auto max-w-[1100px] px-4 pb-8 pt-6 md:px-10 md:py-8`,children:[(0,H.jsx)(Ox,{title:d,titleHidden:!0,status:I?{label:rs(I,L(`status`)?.valueLabels),tone:HS(I)}:void 0}),h.message&&(0,H.jsx)(`div`,{className:`mt-4`,children:(0,H.jsx)(pS,{title:`Not saved`,error:Error(h.message)})}),h.linesConflict&&(0,H.jsx)(`div`,{className:`mt-4`,children:(0,H.jsx)(pS,{title:`The lines were changed by someone else`,error:Error(`The lines were reloaded. Your new order is kept: Save again to apply it.`)})}),S!==`form`&&C&&h.dirty&&(0,H.jsxs)(`div`,{className:`mt-4 flex items-center justify-between gap-3 rounded-lg border bg-surface px-3 py-2`,role:`status`,children:[(0,H.jsx)(`span`,{children:`You have unsaved changes to this record.`}),(0,H.jsxs)(`span`,{className:`flex gap-2`,children:[(0,H.jsx)(FC,{to:E,className:xf({size:`sm`}),children:`Continue editing`}),(0,H.jsx)(W,{size:`sm`,onClick:h.discard,children:`Discard`})]})]}),S===`form`&&h.restored&&(0,H.jsxs)(`div`,{className:`mt-4 flex items-center justify-between gap-3 rounded-lg border bg-surface px-3 py-2`,role:`status`,children:[(0,H.jsx)(`span`,{children:`Your unsaved changes were restored.`}),(0,H.jsxs)(`span`,{className:`flex gap-2`,children:[(0,H.jsx)(W,{size:`sm`,onClick:h.dismissRestored,children:`Keep`}),(0,H.jsx)(W,{size:`sm`,onClick:h.discard,children:`Discard`})]})]}),(0,H.jsxs)(`div`,{className:`grid grid-cols-1 gap-8 md:grid-cols-[minmax(0,1fr)_300px] md:gap-12`,children:[(0,H.jsxs)(`main`,{className:V(`divide-y divide-border`,!I&&`*:first:pt-0!`),children:[F.flatMap((i,a)=>{if(i.kind===`related`)return[(0,H.jsx)(obe,{item:i,recordKey:t,owner:e.name},`related:${i.title}`)];if(r&&(i.kind===`custom`||i.kind===`map`||i.kind===`gallery`))return[];if(i.kind===`custom`)return i.sidebar?[]:[(0,H.jsx)(F9,{item:i,scope:de},`custom:${a}`)];if(i.kind===`map`)return i.sidebar?[]:[(0,H.jsx)(I9,{item:i,record:n.record},`map:${a}`)];if(i.kind===`gallery`)return[(0,H.jsx)(Wye,{item:i,record:n.record,recordKey:t},`gallery:${a}`)];if(i.kind===`history`)return[(0,H.jsx)(Qye,{item:i,model:e,view:u,recordKey:t,etag:n.etag},`history:${a}`)];if(i.kind!==`section`)return[];let o=i.fields.filter(t=>e.fields[t]&&oe(t)),s=S===`read`&&i.presentation===`facts`,c=s?tC(n.record,o):o;return c.length===0?[]:[(0,H.jsx)(xx,{title:i.title,help:eS(i.helpWhen,u,w)?i.help:void 0,children:s?(0,H.jsx)(Ax,{facts:c.map(e=>({label:ce(e).label,value:ce(e).value,icon:U8(L(e)?.icon)}))}):S===`read`?(0,H.jsx)(kx,{rows:c.map(ce)}):(0,H.jsx)(`div`,{className:`grid grid-cols-1 gap-x-6 gap-y-5 sm:grid-cols-2`,children:c.map(se)})},i.title)]}),p&&!r&&(0,H.jsx)(xye,{lines:p,draft:m,vatRate:Number(n.record.vatRate??21)/100,saving:h.saving,locked:S!==`form`})]}),(0,H.jsxs)(`aside`,{className:V(`space-y-4`,I&&`md:pt-8`),children:[me&&(0,H.jsx)(`div`,{className:`hidden flex-col items-center gap-2 md:flex`,children:me}),!r&&(0,H.jsx)(vye,{model:e,stored:n,recordKey:t,edit:C?E:void 0,onDelete:pe}),le===-1&&ue,F.map((e,t)=>e.kind===`custom`&&e.sidebar&&!r?(0,H.jsx)(F9,{item:e,scope:de},`custom:${t}`):e.kind===`map`&&e.sidebar&&!r?(0,H.jsx)(I9,{item:e,record:n.record},`map:${t}`):t===le?(0,H.jsx)(o.Fragment,{children:ue},`summary`):null),(0,H.jsx)(Dx,{title:`Details`,rows:[P9(e,`created`),ae].flatMap(t=>{let r=t?e.fields[t]:void 0;return!t||!r||!oe(t)?[]:[{label:L(t)?.label??q(t),value:R(t)?ZS(r,n.record[t],L(t)):(0,H.jsx)(ku,{className:`h-4 w-24`})}]})}),A.records.length>0&&(0,H.jsx)(Ex,{title:`Related records`,children:(0,H.jsx)(Tx,{records:A.records,onNavigate:l})})]})]})]})}),me&&(0,H.jsx)(`div`,{className:`sticky bottom-[var(--pb-sticky-bottom,0px)] z-20 flex shrink-0 items-center gap-2 border-t bg-background p-3 md:hidden`,children:me})]})},dbe=e=>Fs(e)?e.status===401||e.status===403?`It did not accept your sign-in: ${e.message}`:e.message:`It did not answer.`,fbe=({status:e})=>{let t=Up();return e.state===`error`?(0,H.jsx)(`div`,{className:`flex h-full min-h-48 flex-1 items-center justify-center p-8`,children:(0,H.jsxs)(`div`,{className:`max-w-md text-center`,children:[(0,H.jsxs)(`h1`,{className:`text-[16px] font-semibold`,children:[`Cannot reach `,e.source.label]}),(0,H.jsxs)(`p`,{className:`mt-1 text-muted-foreground`,children:[dbe(e.error),` The rest of the app works as before.`]}),(0,H.jsx)(W,{className:`mt-3`,onClick:()=>void t.refetchQueries({queryKey:G.sourceMetas(e.source.url)}),children:`Try again`})]})}):(0,H.jsxs)(`div`,{className:`flex h-full min-h-48 flex-1 items-center justify-center gap-2 text-muted-foreground`,children:[(0,H.jsx)(Ed,{}),` Loading from `,e.source.label]})},pbe=uo(),mbe=e=>Object.values(e.resources).flatMap(t=>{let n=e.views[t.name];return!t.search?.length||!n||n.nav?.hidden||e.permissions[t.name]?.read===!1?[]:[{model:t,view:n,label:n.names?.plural??q(t.name)}]}),hbe=e=>{let t=e.map(e=>e.label.toLowerCase());return t.length===0?`Search`:t.length===1?`Search ${t[0]}`:t.length===2?`Search ${t[0]} and ${t[1]}`:`Search ${t[0]}, ${t[1]} and more`},gbe=e=>Ya(pbe.search(e.trim())),K9=e=>{let t=e.view?.searchResult?.title;return t?.length?t:[Eg(e.model,e.view)]},q9=e=>{let t=K9(e);return e.view?.searchResult?.subtitle??e.model.search?.find(e=>!t.includes(e))},_be=e=>{let t=q9(e),n=[...K9(e),...t?[t]:[],...e.model.search??[]];return[...new Set([...e.model.primaryKey,...n.filter(t=>Object.hasOwn(e.model.fields,t))])]},J9=(e,t,n)=>{let r=t[n];return r==null?``:e.model.fields[n]?.type===`enum`?rs(String(r),e.view?.fields[n]?.valueLabels):String(r)},vbe=(e,t,n,r=``)=>{let i=Ao(Ag(e.model,t)),a=K9(e),o=q9(e),s=Ga(e.model,t,n,[...a,...o?[o]:[]])??o,c=s?J9(e,t,s):``;return{id:i,title:a.map(n=>J9(e,t,n)).filter(Boolean).join(` `)||i,...c&&{subtitle:c},href:us({kind:`record`,resource:e.model.name,key:i},r)}},ybe=()=>{let e=J(),t=K(),{basePath:n}=Dh(),r=(0,o.useMemo)(()=>mbe(e),[e]),[i,a]=(0,o.useState)(``),s=i.trim(),c=g8(s,200),l=s.length>=2,u=l&&c.length>=2,d=hh({queries:r.map(e=>({queryKey:[`global-search`,e.model.name,c],enabled:u,staleTime:1/0,gcTime:0,queryFn:()=>t.list(e.model.name,{filter:gbe(c),pageSize:5,fields:_be(e)})}))}),f=r.flatMap((e,t)=>{let r=d[t];if(!u||!r)return[];if(r.error)return[{id:e.model.name,label:e.label,hits:[],failed:!0}];let i=(r.data?.items??[]).map(t=>vbe(e,t,c,n));return i.length>0?[{id:e.model.name,label:e.label,hits:i}]:[]});return{available:r.length>0,placeholder:hbe(r),text:i,setText:a,query:u?c:``,loading:l&&(s!==c||d.some(e=>e.isFetching)),groups:f}},bbe=e=>!!(e?.updateAvailable&&e.indicator),xbe=e=>e?5e3:18e5,Y9={immediate:`Updates as soon as a release is out`,weekly:`Updates at a set time every week`,scheduled:`Updates at the time set for this release`,manual:`Updates only when asked to`},Sbe={job:`Preparing the update`,build:`Building`},Cbe=(e,t)=>{if(!e.updateStage)return`Updating now`;let n=Sbe[e.updateStage];return e.updateStartedAt?`${n}, started ${hf(Math.max(0,Math.floor((t-Date.parse(e.updateStartedAt))/1e3)))}`:n},X9=(e,t=Date.now())=>e.updating?Cbe(e,t):e.nextUpdateAt?`${Y9[e.policy]}: next on ${mf(Date.parse(e.nextUpdateAt))} UTC`:Y9[e.policy],wbe=e=>{let t=`${mf(Date.parse(e.finishedAt))} UTC`,n={succeeded:`Updated to ${e.toVersion} on ${t}`,unchanged:`The update to ${e.toVersion} on ${t} changed nothing`,failed:`The update to ${e.toVersion} failed on ${t}`}[e.outcome];return e.message?`${n}: ${e.message}`:`${n}.`},Tbe=e=>Fs(e)&&e.status<500&&e.problem.detail?e.problem.detail:Fs(e)&&e.status===409?`Already on the latest version, or an update is running.`:Fs(e)&&e.status===403?`Only an admin can update the runtime.`:`The update could not be started. Try again later.`,Z9=({label:e,value:t})=>(0,H.jsxs)(`div`,{className:`flex justify-between gap-4 py-1`,children:[(0,H.jsx)(`span`,{className:`text-muted-foreground`,children:e}),(0,H.jsx)(`span`,{className:`font-medium tabular-nums`,children:t})]}),Ebe=({status:e,requesting:t,error:n,checkError:r,onUpdate:i,onClose:a})=>{let o=e.updating?void 0:e.lastUpdate;return(0,H.jsxs)(Sf,{title:`Runtime update`,description:e.updating?(0,H.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,H.jsx)(Ed,{className:`size-3.5`}),X9(e)]}):X9(e),onClose:a,actions:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(W,{onClick:a,children:`Close`}),(0,H.jsx)(W,{variant:`primary`,loading:t,disabled:e.updating||!e.updateAvailable,onClick:i,children:e.updating?`Updating…`:`Update now`})]}),children:[(0,H.jsx)(Z9,{label:`Current version`,value:e.version}),(0,H.jsx)(Z9,{label:`Latest version`,value:e.latest}),o&&(0,H.jsx)(`p`,{className:o.outcome===`failed`?`mt-3 text-danger-text`:`mt-3 text-muted-foreground`,children:wbe(o)}),n!==void 0&&(0,H.jsx)(`p`,{role:`alert`,className:`mt-3 text-danger-text`,children:Tbe(n)}),r!==void 0&&(0,H.jsx)(`p`,{className:`mt-3 text-muted-foreground`,children:`The status could not be checked again; this is the last one read.`})]})},Dbe=e=>{let t=Sg(),n=(0,o.useRef)(t);n.current=t;let r=t!==void 0;return(0,o.useMemo)(()=>r?du({url:e,token:()=>n.current}):void 0,[e,r])},Obe=e=>{let[t,n]=(0,o.useState)(),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)(),[c,l]=(0,o.useState)(),u=t?.updating??!1;return(0,o.useEffect)(()=>{if(!e)return;let t=!0,r=()=>e.status().then(e=>{t&&(n(e),l(void 0))},e=>t&&l(e));r();let i=setInterval(()=>void r(),xbe(u));return()=>{t=!1,clearInterval(i)}},[e,u]),{status:t,update:(0,o.useCallback)(async()=>{e&&(i(!0),s(void 0),await e.update().then(n,s),i(!1))},[e]),requesting:r,error:a,checkError:c}},Q9=({client:e})=>{let{status:t,update:n,requesting:r,error:i,checkError:a}=Obe(e),[s,c]=(0,o.useState)(!1);return!t||!s&&!bbe(t)?null:(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(W,{size:`sm`,variant:`ghost`,"aria-label":`Update available`,title:`Update available`,onClick:()=>c(!0),className:`max-md:size-9 max-md:p-0`,children:[(0,H.jsx)(Te,{className:`size-3.5 text-primary`}),(0,H.jsx)(`span`,{className:`max-md:sr-only`,children:`Update`})]}),s&&(0,H.jsx)(Ebe,{status:t,requesting:r,error:i,checkError:a,onUpdate:()=>void n(),onClose:()=>c(!1)})]})},kbe=({url:e})=>(0,H.jsx)(Q9,{client:Dbe(e)}),Abe=({url:e,client:t})=>t?(0,H.jsx)(Q9,{client:t}):(0,H.jsx)(kbe,{url:e}),jbe=({signIn:e,onStop:t})=>{let[n,r]=(0,o.useState)(!1),[i,a]=(0,o.useState)(),s=async()=>{r(!0),a(void 0);try{await t()}catch(e){if(!(e instanceof lc))throw e;a(zd(e)),r(!1)}};return(0,H.jsxs)(`div`,{role:`region`,"aria-label":`Staff session`,className:`flex flex-wrap items-center gap-x-3 gap-y-2 border-b border-warning/40 bg-warning-soft px-4 py-2 text-warning-text`,children:[(0,H.jsx)(cee,{"aria-hidden":!0,className:`size-4 shrink-0`}),(0,H.jsxs)(`p`,{className:`min-w-64 flex-1 break-words`,children:[(0,H.jsx)(`span`,{className:`font-semibold`,children:e.staffName??e.staff}),` is signed in as `,(0,H.jsx)(`span`,{className:`font-semibold`,children:e.user}),` until`,` `,mf(Date.parse(e.expiresAt)),`. Reason: `,e.reason]}),i&&(0,H.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:i}),(0,H.jsx)(W,{size:`sm`,loading:n,onClick:()=>void s(),children:`Stop staff session`})]})},Mbe=(e,t,n)=>({filter:n.filter??``,orderBy:n.orderBy??DC(e,t),pageSize:n.limit??3,fields:[...new Set([...e.primaryKey,Eg(e,t),n.status])]}),Nbe=(e,t,n,r,i,a)=>r.map(r=>{let o=Ao(Ag(e,r)),s=String(r[n.status]??``);return{id:o,label:Dg(e,t,r,o),href:us({kind:`record`,resource:e.name,key:o},i),status:e.fields[n.status]?.type===`enum`&&s?rs(s,t.fields[n.status]?.valueLabels):s,tone:n.tones[s]??`neutral`,pulse:n.pulse?.includes(s)??!1,active:o===a}}),Pbe=(e,t,n,r,i)=>{let a=n.find(t=>Ao(Ag(e,t))===r);return a!==void 0&&t.some(e=>!Object.is(a[e],i[e]))},$9=({model:e,request:t})=>G.navRecent(e.name,t.filter,t.orderBy,t.pageSize),Fbe=e=>{let t=Up();(0,o.useEffect)(()=>t.getQueryCache().subscribe(n=>{if(n.type!==`updated`||n.action.type!==`success`)return;let[r,i,a]=n.query.queryKey,o=n.action.data?.record;if(r===`record`&&typeof a==`string`&&o)for(let n of e){if(n.model.name!==i)continue;let e=t.getQueryData($9(n));e&&Pbe(n.model,n.request.fields,e.items,a,o)&&t.invalidateQueries({queryKey:$9(n),exact:!0})}}),[t,e])},Ibe=(e,t,n)=>{let r=K(),i=(0,o.useMemo)(()=>{let t=M9(e);return Object.values(e.views).flatMap(n=>{let r=e.resources[n.resource],i=n.nav?.recent;return r&&i&&!n.nav?.hidden&&!t.has(r.name)?[{model:r,view:n,recent:i,request:Mbe(r,n,i)}]:[]})},[e]);Fbe(i);let a=hh({queries:i.map(e=>({queryKey:$9(e),queryFn:()=>r.list(e.model.name,e.request)}))});return Object.fromEntries(i.map(({model:e,view:r,recent:i},o)=>{let s=a[o];if(s.isPending)return[e.name,{state:`loading`}];if(s.isError)return[e.name,{state:`error`}];let c=n.resource===e.name?n.key:void 0;return[e.name,{state:`ready`,records:Nbe(e,r,i,s.data.items,t,c)}]}))},Lbe=e=>e?.kind===`page`?e.page:e?.resource,Rbe=e=>e?.kind===`record`?e:void 0,zbe=({workspace:e,sidebarMode:t,assistant:n,runtime:r})=>{let i=J(),{state:a,session:s,signOut:c,stopStaffSession:l,organizations:u}=U(),d=zh();if(a.kind!==`signed-in`&&a.kind!==`visitor`)throw Error(`The shell is only rendered for a signed-in user or a visitor`);let f=a.kind===`signed-in`?a.user:void 0,p=a.kind===`signed-in`?a.staff:void 0,{path:m,params:h,basePath:g}=Dh(),{address:_,go:v,open:y}=PC(),b=Lbe(_),x=Rbe(_),S=ybe(),C=Are(),w=uye(i,g,Ibe(i,g,{resource:b,key:x?.key})),T=Object.keys(i.pages)[0],E=Object.keys(i.resources)[0],D=_?.kind===`page`?i.pages[_.page]:void 0;(0,o.useEffect)(()=>{m===`/`&&(T?v({kind:`page`,page:T},{replace:!0}):E&&v({kind:`list`,resource:E},{replace:!0}))},[m,T,E,v]);let O=_?.kind===`page`?void 0:_?.resource,k=O?die(i,O):void 0,A=O?i.views[O]:void 0,j=w.find(e=>e.items.some(e=>e.id===b)),M=O?i.resources[O]:void 0,N=wg(x?.resource??``,x?.key??``,!!(M&&x)),ee=M&&x&&N.data?Dg(M,A,N.data.record,x.key):void 0,P=!!x&&(N.isLoading||k?.state===`loading`),{shell:te}=Xg(),F=te?.actions,ne=te?.rightPanel,[re,ie]=(0,o.useState)(!1),I=i.assistant?.url,ae=I&&(0,H.jsx)(Zre,{open:re,onToggle:()=>ie(!re)}),L=I&&re&&(0,H.jsx)($re,{url:I,client:n,page:h.size>0?`${m}?${h}`:m,onClose:()=>ie(!1)}),oe=i.errorReporting;(0,o.useEffect)(()=>{oe&&Xne(oe)},[oe]);let R=i.runtime?.url,se=R&&(0,H.jsx)(Abe,{url:R,client:r}),ce=sye((0,o.useCallback)(()=>O9(g),[g]),!!f),le=f&&oye(f,ce.current),ue=le?xg(le):!1,de=fye(),fe=Xve(!!(u&&f)),pe=fe.current,me=!!u&&pe!==void 0&&!pe.organization,he=u&&f?Une[m]:void 0,ge=f?m===`/-/account`?`Sign-in & security`:m===`/-/sign-in-policy`?`Sign-in policy`:he:void 0,_e=A?.names?.plural??(O&&q(O)),ve=ge?[ge]:nie({basePath:g,address:_,group:j?.label,page:D,resourceLabel:_e,recordTitle:ee,recordLoading:P});aie(iie(rie({address:_,page:D,accountPage:ge,resourceLabel:_e,singular:A?.names?.singular??(O&&q(O)),recordTitle:ee,recordLoading:P}),i.appName));let ye=f&&m===`/-/account`?(0,H.jsx)(kp,{email:f.email}):f&&m===`/-/sign-in-policy`?ue?(0,H.jsx)(Vp,{}):(0,H.jsx)(u_,{title:`Admins only`,children:`Only an admin can change how people sign in.`}):he&&m===`/-/organization`?(0,H.jsx)(tye,{current:pe,basePath:g,onChanged:fe.reload}):he&&(m===`/-/organization/members`||m===`/-/organization/invitations`)?Kh(pe)?m===`/-/organization/members`?(0,H.jsx)(Kve,{current:pe}):(0,H.jsx)(Yve,{current:pe}):(0,H.jsx)(u_,{title:`Owners and admins only`,children:`Only the organization's owners and admins manage its members.`}):he&&m===`/-/organizations`||me?(0,H.jsx)(aye,{state:fe,basePath:g}):_?_.kind===`page`?D?(0,H.jsx)($5,{name:D.name},D.name):(0,H.jsxs)(u_,{title:`Not found`,children:[`There is no page called `,_.page,`.`]}):k&&k.state!==`ready`?(0,H.jsx)(fbe,{status:k}):_.kind===`create`?(0,H.jsx)(vge,{resource:_.resource,values:_.values},_.resource):_.kind===`record`?(0,H.jsx)(lbe,{resource:_.resource,recordKey:_.key},`${_.resource}/${_.key}`):(0,H.jsx)(Wve,{address:_},_.resource):m===`/`?(0,H.jsx)(u_,{title:`Choose a resource`,children:`Pick one from the sidebar.`}):(0,H.jsx)(u_,{title:`Not found`,children:`There is nothing at this address.`}),be=(0,H.jsx)(Nd,{pageScroll:!0,sidebarMode:t??`text-small`,activeItem:b??``,breadcrumb:ve,user:le&&yre(le),onSignOut:f&&(()=>void c()),signIn:f?void 0:d.link(),workspace:pe?.organization?.name??e,logo:dye,navGroups:w,bottomBar:tie(i,g,b),userMenu:[...cye(i,g,b),...u&&f?Wne(g,m,pe):[],...f?ir(g,m,ue):[]],organizations:u&&{...pe?.organization&&{current:{id:pe.organization.id,name:pe.organization.name}},others:fe.organizations.filter(e=>e.id!==pe?.organization?.id),onSwitch:e=>void s.organizations.switchTo(e).then(()=>O9(g))},theme:{preference:C.preference,onChange:C.choose},roles:ce.current?.active?{active:ce.current.active,roles:ce.current.roles,onSwitch:ce.switchTo}:void 0,onNavigate:y,search:S.available?{placeholder:S.placeholder,text:S.text,onTextChange:S.setText,query:S.query,loading:S.loading,groups:S.groups,onSelect:y}:void 0,actions:(F||se||ae)&&(0,H.jsxs)(H.Fragment,{children:[F&&(0,H.jsx)(tg,{name:`shell.actions`,fallback:null,children:(0,H.jsx)(F,{})}),se,ae]}),rightPanel:(ne||L)&&(0,H.jsxs)(H.Fragment,{children:[ne&&(0,H.jsx)(tg,{name:`shell.rightPanel`,fallback:null,children:(0,H.jsx)(ne,{})}),L]}),children:ye}),xe=ue&&de.length>0;return!p&&!xe?be:(0,H.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[p&&(0,H.jsx)(jbe,{signIn:p,onStop:l}),xe&&(0,H.jsx)(mye,{off:de}),(0,H.jsx)(`div`,{className:`min-h-0 flex-1`,children:be})]})},Bbe=({baseUrl:e,client:t,sources:n,workspace:r,sidebarMode:i,ui:a,assistant:o,runtime:s})=>{let{state:c,session:l,markSignedOut:u}=U();return(0,H.jsx)(Th,{baseUrl:e,client:t,sources:n,token:c.kind===`visitor`?void 0:l.token,onUnauthenticated:u,children:(0,H.jsx)(pie,{children:(0,H.jsx)(Ire,{children:(0,H.jsx)(pye,{ui:a,children:(0,H.jsx)(zbe,{workspace:r,sidebarMode:i,assistant:o,runtime:s})})})})})},Vbe=({auth:e,workspace:t,basePath:n,initialUrl:r,pluginLoader:i,...a})=>(0,H.jsx)(kre,{children:(0,H.jsx)($d,{session:e,children:(0,H.jsx)(ane,{basePath:n,initialUrl:r,children:(0,H.jsx)(dre,{...i&&{loader:i},children:(0,H.jsx)(hre,{workspace:t,children:(0,H.jsx)(Bbe,{workspace:t,...a})})})})})});export{K as $,Jg as A,Lg as B,r_ as C,Qg as D,Jre as E,Ug as F,rre as G,Sg as H,Hg as I,Xh as J,sg as K,Bg as L,Kg as M,Gg as N,Wre as O,Wg as P,Th as Q,zg as R,l_ as S,t_ as T,pg as U,Cg as V,mg as W,Mh as X,Nh as Y,jh as Z,PC as _,V5 as a,Ed as at,bx as b,Ihe as c,id as ct,lT as d,V as dt,wh as et,cT as f,b as ft,FC as g,IC as h,t7 as i,xf as it,qg as j,Ure as k,K8 as l,$u as lt,Tw as m,V9 as n,Sf as nt,Yhe as o,wd as ot,Pw as p,ng as q,B9 as r,W as rt,Fhe as s,Cd as st,Vbe as t,Pf as tt,sT as u,Iu as ut,gS as v,n_ as w,m_ as x,xx as y,Rg as z};
|