@malloy-publisher/sdk 0.8.2 → 0.8.3

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/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),v=require("@mui/material"),$=require("react"),u=require("./DocumentStorage-B0_YgSzt.cjs.js"),V=require("./ServerProvider-CuYLH_Yi.cjs.js"),Tn=require("@tanstack/react-query"),la=require("@mui/system"),He=require("@mui/icons-material"),ut=require("./RenderedResult-Bu25oAAr.cjs.js"),bn=require("react-router-dom");function Do(t){const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const f in t)if(f!=="default"){const a=Object.getOwnPropertyDescriptor(t,f);Object.defineProperty(o,f,a.get?a:{enumerable:!0,get:()=>t[f]})}}return o.default=t,Object.freeze(o)}const fe=Do($),jo=u.createSvgIcon(n.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function hr({label:t,href:o,onClick:f}){const a=p=>{const c=p.metaKey||p.ctrlKey||p.shiftKey||p.altKey||p.button!==0;o!==void 0&&c||(p.preventDefault(),f(p))};return n.jsxs(v.Link,{...o===void 0?{component:"button",type:"button"}:{href:o},onClick:a,underline:"none","aria-label":`Back to ${t}`,sx:{display:"inline-flex",alignItems:"center",gap:.5,cursor:"pointer",color:"text.secondary",fontSize:"0.875rem",mb:2,border:0,p:0,background:"none",font:"inherit","&:hover":{color:"primary.main"}},children:[n.jsx(jo,{sx:{fontSize:18}}),"Back to ",t]})}function Oo(){const t=bn.useNavigate();return(o,f)=>{if(!f||!f.metaKey&&!f.ctrlKey&&!f.shiftKey&&f.button!==1){t(o);return}const a=new URL(o,window.location.href).href;(f.metaKey||f.ctrlKey||f.button===1||f.shiftKey)&&window.open(a,"_blank")}}function Eo(){const[t]=bn.useSearchParams(),o=bn.useNavigate(),f=bn.useLocation(),a=$.useMemo(()=>Object.fromEntries(t.entries()),[t]),p=$.useRef(new Set),c=$.useCallback((l,h)=>{const d=new Set([...h,...p.current]);p.current=new Set([...p.current,...Object.keys(l),...h]);const m=new URLSearchParams(f.search);for(const x of d)Object.prototype.hasOwnProperty.call(l,x)||m.delete(x);for(const[x,S]of Object.entries(l))m.set(x,S);o({search:m.toString(),hash:f.hash},{replace:!0})},[o,f]);return{params:a,onGivensChange:c}}const ca=u.createSvgIcon(n.jsx("path",{d:"M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3z"})),Io="publisher:resize";function Fo(t){return typeof t=="object"&&t!==null&&t.type===Io&&typeof t.height=="number"}function ua(t){return t.replace(/\/api\/v0\/?$/,"")}function da({server:t,environmentName:o,packageName:f,path:a}){const p=a.startsWith("public/")?a.slice(7):a;return`${ua(t)}/environments/${encodeURIComponent(o)}/packages/${encodeURIComponent(f)}/`+p}function No(t){try{const{environmentName:o,packageName:f,modelPath:a}=u.parseResourceUri(t);return!o||!f||!a?null:{environmentName:o,packageName:f,dataAppPath:a}}catch{return null}}function Ao({resourceUri:t}){const{server:o,apiClients:f}=V.useServer(),a=No(t),p=a?.environmentName??"",c=a?.packageName??"",l=a?.dataAppPath??"",h=$.useMemo(()=>da({server:o,environmentName:p,packageName:c,path:l}),[o,p,c,l]),m=u.useQueryWithApiError({queryKey:["data-apps",p,c],queryFn:()=>f.dataApps.listDataApps(p,c),enabled:!!a}).data?.data?.find(w=>w.path===l),x=m?.title??l,S=m?.fit==="viewport",b=$.useRef(null),[g,k]=$.useState(120);return $.useEffect(()=>{if(S)return;function w(T){Fo(T.data)&&T.source===b.current?.contentWindow&&T.data.height>0&&k(Math.ceil(T.data.height))}return window.addEventListener("message",w),()=>window.removeEventListener("message",w)},[S]),a?n.jsxs(v.Box,{sx:{p:3,...S?{height:"100%",display:"flex",flexDirection:"column"}:{maxWidth:1200,mx:"auto"}},children:[n.jsxs(v.Stack,{direction:"row",alignItems:"baseline",spacing:1,sx:{mb:1,flexShrink:0},children:[n.jsx(v.Typography,{variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em"},children:x}),n.jsx(v.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:V.MONO_FONT_FAMILY},children:l}),n.jsx(v.Box,{sx:{flex:1}}),n.jsx(v.Tooltip,{title:"Open standalone in new tab",children:n.jsx(v.IconButton,{size:"small",href:h,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:n.jsx(ca,{fontSize:"small"})})})]}),n.jsx(v.Box,{sx:{border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden",backgroundColor:"background.paper",...S?{flex:1,minHeight:0}:{}},children:n.jsx("iframe",{ref:b,src:h,title:x,sandbox:"allow-scripts allow-same-origin allow-forms",style:{display:"block",width:"100%",height:S?"100%":g,border:0}})})]}):n.jsxs(v.Box,{sx:{p:3,maxWidth:1200,mx:"auto"},children:[n.jsx(v.Typography,{variant:"h6",sx:{fontWeight:600},children:"Can't open data app"}),n.jsxs(v.Typography,{variant:"body2",color:"text.secondary",sx:{mt:1},children:["This data app link is missing an environment, package, or path:",n.jsx(v.Box,{component:"span",sx:{fontFamily:V.MONO_FONT_FAMILY,ml:1},children:t})]})]})}function ze({title:t,count:o,description:f,action:a,children:p}){const c=$.useId();return n.jsxs(v.Box,{component:"section","aria-labelledby":c,sx:{mb:4},children:[n.jsxs(v.Stack,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:f?0:1,minHeight:40},children:[n.jsxs(v.Stack,{direction:"row",alignItems:"baseline",spacing:1,children:[n.jsx(v.Typography,{id:c,variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em",lineHeight:1.2},children:t}),o!==void 0&&n.jsxs(v.Typography,{variant:"caption",color:"text.secondary",children:["(",o,")"]})]}),a]}),f&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:f}),n.jsx(v.Box,{children:p})]})}function $o({resourceUri:t}){const{environmentName:o}=u.parseResourceUri(t),{apiClients:f}=V.useServer(),[a,p]=$.useState(!1),c=90,{data:l,isSuccess:h,isError:d,error:m}=u.useQueryWithApiError({queryKey:["about",o],queryFn:()=>f.environments.getEnvironment(o,!1)}),x=l?.data?.readme||"",S=x.split(/\s+/),b=S.length>c,g=S.slice(0,c).join(" ");return n.jsxs(n.Fragment,{children:[!h&&!d&&n.jsx(u.Loading,{text:"Fetching About..."}),h&&x&&n.jsxs(ze,{title:"Readme",children:[n.jsx(u.Prose,{variant:"caption",children:a||!b?x:g}),b&&n.jsx(v.Box,{sx:{mt:1},children:n.jsx(u.SecondaryButton,{label:a?"Read less":"Read more",onClick:()=>p(!a)})})]}),d&&n.jsx(u.ApiErrorDisplay,{error:m,context:`${o} > About`})]})}function Ro(t={}){const{autoHideDuration:o=null,disableWindowBlurListener:f=!1,onClose:a,open:p,resumeHideDuration:c}=t,l=u.useTimeout();fe.useEffect(()=>{if(!p)return;function M(D){D.defaultPrevented||D.key==="Escape"&&a?.(D,"escapeKeyDown")}return document.addEventListener("keydown",M),()=>{document.removeEventListener("keydown",M)}},[p,a]);const h=u.useEventCallback((M,D)=>{a?.(M,D)}),d=u.useEventCallback(M=>{!a||M==null||l.start(M,()=>{h(null,"timeout")})});fe.useEffect(()=>(p&&d(o),l.clear),[p,o,d,l]);const m=M=>{a?.(M,"clickaway")},x=l.clear,S=fe.useCallback(()=>{o!=null&&d(c??o*.5)},[o,c,d]),b=M=>D=>{const I=M.onBlur;I?.(D),S()},g=M=>D=>{const I=M.onFocus;I?.(D),x()},k=M=>D=>{const I=M.onMouseEnter;I?.(D),x()},w=M=>D=>{const I=M.onMouseLeave;I?.(D),S()};return fe.useEffect(()=>{if(!f&&p)return window.addEventListener("focus",S),window.addEventListener("blur",x),()=>{window.removeEventListener("focus",S),window.removeEventListener("blur",x)}},[f,p,S,x]),{getRootProps:(M={})=>{const D={...u.extractEventHandlers(t),...u.extractEventHandlers(M)};return{role:"presentation",...M,...D,onBlur:b(D),onFocus:g(D),onMouseEnter:k(D),onMouseLeave:w(D)}},onClickAway:m}}function Is(t){return t.substring(2).toLowerCase()}function Lo(t,o){return o.documentElement.clientWidth<t.clientX||o.documentElement.clientHeight<t.clientY}function _o(t){const{children:o,disableReactTree:f=!1,mouseEvent:a="onClick",onClickAway:p,touchEvent:c="onTouchEnd"}=t,l=fe.useRef(!1),h=fe.useRef(null),d=fe.useRef(!1),m=fe.useRef(!1);fe.useEffect(()=>(setTimeout(()=>{d.current=!0},0),()=>{d.current=!1}),[]);const x=u.useForkRef(u.getReactElementRef(o),h),S=u.useEventCallback(k=>{const w=m.current;m.current=!1;const T=u.ownerDocument(h.current);if(!d.current||!h.current||"clientX"in k&&Lo(k,T))return;if(l.current){l.current=!1;return}let M;k.composedPath?M=k.composedPath().includes(h.current):M=!T.documentElement.contains(k.target)||h.current.contains(k.target),!M&&(f||!w)&&p(k)}),b=k=>w=>{m.current=!0;const T=o.props[k];T&&T(w)},g={ref:x};return c!==!1&&(g[c]=b(c)),fe.useEffect(()=>{if(c!==!1){const k=Is(c),w=u.ownerDocument(h.current),T=()=>{l.current=!0};return w.addEventListener(k,S),w.addEventListener("touchmove",T),()=>{w.removeEventListener(k,S),w.removeEventListener("touchmove",T)}}},[S,c]),a!==!1&&(g[a]=b(a)),fe.useEffect(()=>{if(a!==!1){const k=Is(a),w=u.ownerDocument(h.current);return w.addEventListener(k,S),()=>{w.removeEventListener(k,S)}}},[S,a]),fe.cloneElement(o,g)}function Po(t){return u.generateUtilityClass("MuiSnackbarContent",t)}u.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const qo=t=>{const{classes:o}=t,f={root:["root"],action:["action"],message:["message"]};return u.composeClasses(f,Po,o)},Wo=u.styled(u.Paper,{name:"MuiSnackbarContent",slot:"Root"})(u.memoTheme(({theme:t})=>{const o=t.palette.mode==="light"?.8:.98;return{...t.typography.body2,color:t.vars?t.vars.palette.SnackbarContent.color:t.palette.getContrastText(u.emphasize(t.palette.background.default,o)),backgroundColor:t.vars?t.vars.palette.SnackbarContent.bg:u.emphasize(t.palette.background.default,o),display:"flex",alignItems:"center",flexWrap:"wrap",padding:"6px 16px",flexGrow:1,[t.breakpoints.up("sm")]:{flexGrow:"initial",minWidth:288}}})),zo=u.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),Ho=u.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),Vo=fe.forwardRef(function(o,f){const a=u.useDefaultProps({props:o,name:"MuiSnackbarContent"}),{action:p,className:c,message:l,role:h="alert",...d}=a,m=a,x=qo(m);return n.jsxs(Wo,{role:h,elevation:6,className:u.clsx(x.root,c),ownerState:m,ref:f,...d,children:[n.jsx(zo,{className:x.message,ownerState:m,children:l}),p?n.jsx(Ho,{className:x.action,ownerState:m,children:p}):null]})});function Uo(t){return u.generateUtilityClass("MuiSnackbar",t)}u.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const Bo=t=>{const{classes:o,anchorOrigin:f}=t,a={root:["root",`anchorOrigin${u.capitalize(f.vertical)}${u.capitalize(f.horizontal)}`]};return u.composeClasses(a,Uo,o)},Go=u.styled("div",{name:"MuiSnackbar",slot:"Root",overridesResolver:(t,o)=>{const{ownerState:f}=t;return[o.root,o[`anchorOrigin${u.capitalize(f.anchorOrigin.vertical)}${u.capitalize(f.anchorOrigin.horizontal)}`]]}})(u.memoTheme(({theme:t})=>({zIndex:(t.vars||t).zIndex.snackbar,position:"fixed",display:"flex",left:8,right:8,justifyContent:"center",alignItems:"center",variants:[{props:({ownerState:o})=>o.anchorOrigin.vertical==="top",style:{top:8,[t.breakpoints.up("sm")]:{top:24}}},{props:({ownerState:o})=>o.anchorOrigin.vertical!=="top",style:{bottom:8,[t.breakpoints.up("sm")]:{bottom:24}}},{props:({ownerState:o})=>o.anchorOrigin.horizontal==="left",style:{justifyContent:"flex-start",[t.breakpoints.up("sm")]:{left:24,right:"auto"}}},{props:({ownerState:o})=>o.anchorOrigin.horizontal==="right",style:{justifyContent:"flex-end",[t.breakpoints.up("sm")]:{right:24,left:"auto"}}},{props:({ownerState:o})=>o.anchorOrigin.horizontal==="center",style:{[t.breakpoints.up("sm")]:{left:"50%",right:"auto",transform:"translateX(-50%)"}}}]}))),Yo=fe.forwardRef(function(o,f){const a=u.useDefaultProps({props:o,name:"MuiSnackbar"}),p=u.useTheme(),c={enter:p.transitions.duration.enteringScreen,exit:p.transitions.duration.leavingScreen},{action:l,anchorOrigin:{vertical:h,horizontal:d}={vertical:"bottom",horizontal:"left"},autoHideDuration:m=null,children:x,className:S,ClickAwayListenerProps:b,ContentProps:g,disableWindowBlurListener:k=!1,message:w,onBlur:T,onClose:M,onFocus:D,onMouseEnter:I,onMouseLeave:E,open:L,resumeHideDuration:H,slots:_={},slotProps:G={},TransitionComponent:N,transitionDuration:q=c,TransitionProps:{onEnter:U,onExited:A,...P}={},...Y}=a,K={...a,anchorOrigin:{vertical:h,horizontal:d},autoHideDuration:m,disableWindowBlurListener:k,TransitionComponent:N,transitionDuration:q},X=Bo(K),{getRootProps:J,onClickAway:B}=Ro({...K}),[ne,W]=fe.useState(!0),Q=ye=>{W(!0),A&&A(ye)},R=(ye,Me)=>{W(!1),U&&U(ye,Me)},Z={slots:{transition:N,..._},slotProps:{content:g,clickAwayListener:b,transition:P,...G}},[de,ee]=u.useSlot("root",{ref:f,className:[X.root,S],elementType:Go,getSlotProps:J,externalForwardedProps:{...Z,...Y},ownerState:K}),[ie,{ownerState:ce,...De}]=u.useSlot("clickAwayListener",{elementType:_o,externalForwardedProps:Z,getSlotProps:ye=>({onClickAway:(...Me)=>{const Fe=Me[0];ye.onClickAway?.(...Me),!Fe?.defaultMuiPrevented&&B(...Me)}}),ownerState:K}),[be,ke]=u.useSlot("content",{elementType:Vo,shouldForwardComponentProp:!0,externalForwardedProps:Z,additionalProps:{message:w,action:l},ownerState:K}),[je,Re]=u.useSlot("transition",{elementType:u.Grow,externalForwardedProps:Z,getSlotProps:ye=>({onEnter:(...Me)=>{ye.onEnter?.(...Me),R(...Me)},onExited:(...Me)=>{ye.onExited?.(...Me),Q(...Me)}}),additionalProps:{appear:!0,in:L,timeout:q,direction:h==="top"?"down":"up"},ownerState:K});return!L&&ne?null:n.jsx(ie,{...De,..._.clickAwayListener&&{ownerState:ce},children:n.jsx(de,{...ee,children:n.jsx(je,{...Re,children:x||n.jsx(be,{...ke})})})})});let sr;function Zo(t){sr=t}function Fs(t){if(sr)try{sr(t)}catch{}}function Ke(t,o,f){return(async a=>{const p=Date.now();try{const c=await f(a);return Fs({type:"console.mutation",resource:t,action:o,ok:!0,durationMs:Date.now()-p}),c}catch(c){throw Fs({type:"console.mutation",resource:t,action:o,ok:!1,durationMs:Date.now()-p,reason:c instanceof Error?c.message:"An unknown error occurred"}),c}})}function Dt({mutationFn:t,success:o,invalidates:f,closeDialog:a,resource:p,action:c}){const l=Tn.useQueryClient(),[h,d]=$.useState(""),m=u.useMutationWithApiError({mutationFn:Ke(p,c,t),onSuccess(){a();for(const x of f)l.invalidateQueries({queryKey:x});d(o)},onError(x){d(x instanceof Error?x.message:"An unknown error occurred")}});return{mutate:m.mutate,isPending:m.isPending,notice:n.jsx(Yo,{open:h!=="",autoHideDuration:6e3,onClose:()=>d(""),message:h})}}const ha="https://docs.malloydata.dev/documentation",Gn=`${ha}/user_guides/publishing`,Ct="https://github.com/malloydata/publisher/blob/main/docs",Xe={docsHome:`${ha}/`,publishing:`${Gn}/publishing`,explorer:`${Gn}/explorer`,mcpAgents:`${Gn}/mcp_agents`,surfaces:`${Ct}/choosing-a-surface.md`,dashboards:`${Ct}/dashboards.md`,dataApps:`${Ct}/html-data-apps.md`,givens:`${Ct}/givens.md`,materialization:`${Ct}/materialization.md`,connections:`${Ct}/connections.md`};function Xo({resourceUri:t}){const[o,f]=$.useState(!1),{apiClients:a}=V.useServer(),{environmentName:p}=u.parseResourceUri(t),c=Dt({mutationFn(h){return a.packages.createPackage(p,{name:h.name,description:h.description,location:h.location})},success:"Package created",invalidates:[["packages",p]],closeDialog:()=>f(!1),resource:"package",action:"create"}),l=h=>{h.preventDefault();const d=new FormData(h.currentTarget),m=d.get("name")?.toString(),x=d.get("description")?.toString(),S=d.get("location")?.toString();c.mutate({name:m,description:x,location:S})};return n.jsxs(n.Fragment,{children:[n.jsx(u.AddButton,{label:"Package",onClick:()=>f(!0)}),n.jsx(u.AppDialog,{open:o,onClose:()=>f(!1),title:"New package",description:n.jsxs(n.Fragment,{children:["A package is a directory of Malloy models and their data. Give its location as a GitHub, S3 or GCS URL, or an absolute path the server can read; see the"," ",n.jsx(v.Box,{component:"a",href:Xe.publishing,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary"},children:"package format"}),"."]}),actions:n.jsxs(n.Fragment,{children:[n.jsx(v.Button,{disabled:c.isPending,onClick:()=>f(!1),children:"Cancel"}),n.jsx(v.Button,{type:"submit",form:"package-form",variant:"contained",loading:c.isPending,children:"Create package"})]}),children:n.jsx("form",{onSubmit:l,id:"package-form",children:n.jsxs(v.Stack,{sx:{gap:2},children:[n.jsx(v.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(v.TextField,{id:"description",name:"description",label:"Description",multiline:!0,rows:3,fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(v.TextField,{id:"location",name:"location",label:"Location",type:"text",placeholder:"e.g. s3://my-bucket/my-package.zip",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}})]})})}),c.notice]})}const Ko=u.createSvgIcon(n.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function Mn({icon:t,tint:o,label:f,mono:a,description:p,rightLabel:c,trailingAction:l,onClick:h,ariaLabel:d}){const m=!!h,x=S=>{h&&(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),h(S))};return n.jsxs(v.Box,{onClick:h,onKeyDown:m?x:void 0,role:m?"button":void 0,tabIndex:m?0:void 0,"aria-label":d,sx:S=>({display:"flex",alignItems:"center",gap:1.5,py:1,px:1,mx:-1,cursor:m?"pointer":"default",borderRadius:1.5,transition:"background-color 0.1s","&:hover":m?{backgroundColor:S.palette.mode==="dark"?"rgba(255, 255, 255, 0.08)":"grey.100"}:void 0,"&:focus-visible":m?{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}:void 0}),children:[n.jsx(v.Box,{sx:{width:32,height:32,borderRadius:1,bgcolor:o,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t}),n.jsxs(v.Box,{sx:{flex:1,minWidth:0,display:"flex",alignItems:"baseline",gap:1.5},children:[n.jsx(v.Typography,{variant:"body2",sx:{...a?{fontFamily:V.MONO_FONT_FAMILY}:{},flexShrink:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f}),p&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p})]}),c&&n.jsx(v.Typography,{variant:"caption",color:"text.secondary",sx:{flexShrink:0},children:c}),l&&n.jsx(v.Box,{sx:{flexShrink:0,display:"flex",alignItems:"center"},children:l})]})}const fa=u.createSvgIcon(n.jsx("path",{d:"M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6zM19 4h-3.5l-1-1h-5l-1 1H5v2h14z"})),Qo=u.generateUtilityClasses("MuiBox",["root"]),Jo=u.createTheme(),pe=la.createBox({themeId:u.THEME_ID,defaultTheme:Jo,defaultClassName:Qo.root,generateClassName:u.ClassNameGenerator.generate}),Dn=la.createStack({createStyledComponent:u.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:t=>u.useDefaultProps({props:t,name:"MuiStack"})}),Ns=u.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function el(t){return u.generateUtilityClass("MuiListItemIcon",t)}const As=u.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),tl=t=>{const{alignItems:o,classes:f}=t,a={root:["root",o==="flex-start"&&"alignItemsFlexStart"]};return u.composeClasses(a,el,f)},nl=u.styled("div",{name:"MuiListItemIcon",slot:"Root",overridesResolver:(t,o)=>{const{ownerState:f}=t;return[o.root,f.alignItems==="flex-start"&&o.alignItemsFlexStart]}})(u.memoTheme(({theme:t})=>({minWidth:56,color:(t.vars||t).palette.action.active,flexShrink:0,display:"inline-flex",variants:[{props:{alignItems:"flex-start"},style:{marginTop:8}}]}))),fr=fe.forwardRef(function(o,f){const a=u.useDefaultProps({props:o,name:"MuiListItemIcon"}),{className:p,...c}=a,l=fe.useContext(u.ListContext),h={...a,alignItems:l.alignItems},d=tl(h);return n.jsx(nl,{className:u.clsx(d.root,p),ownerState:h,ref:f,...c})});function rl(t){return u.generateUtilityClass("MuiListItemText",t)}const Mt=u.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),sl=t=>{const{classes:o,inset:f,primary:a,secondary:p,dense:c}=t,l={root:["root",f&&"inset",c&&"dense",a&&p&&"multiline"],primary:["primary"],secondary:["secondary"]};return u.composeClasses(l,rl,o)},al=u.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(t,o)=>{const{ownerState:f}=t;return[{[`& .${Mt.primary}`]:o.primary},{[`& .${Mt.secondary}`]:o.secondary},o.root,f.inset&&o.inset,f.primary&&f.secondary&&o.multiline,f.dense&&o.dense]}})({flex:"1 1 auto",minWidth:0,marginTop:4,marginBottom:4,[`.${u.typographyClasses.root}:where(& .${Mt.primary})`]:{display:"block"},[`.${u.typographyClasses.root}:where(& .${Mt.secondary})`]:{display:"block"},variants:[{props:({ownerState:t})=>t.primary&&t.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:t})=>t.inset,style:{paddingLeft:56}}]}),mr=fe.forwardRef(function(o,f){const a=u.useDefaultProps({props:o,name:"MuiListItemText"}),{children:p,className:c,disableTypography:l=!1,inset:h=!1,primary:d,primaryTypographyProps:m,secondary:x,secondaryTypographyProps:S,slots:b={},slotProps:g={},...k}=a,{dense:w}=fe.useContext(u.ListContext);let T=d??p,M=x;const D={...a,disableTypography:l,inset:h,primary:!!T,secondary:!!M,dense:w},I=sl(D),E={slots:b,slotProps:{primary:m,secondary:S,...g}},[L,H]=u.useSlot("root",{className:u.clsx(I.root,c),elementType:al,externalForwardedProps:{...E,...k},ownerState:D,ref:f}),[_,G]=u.useSlot("primary",{className:I.primary,elementType:u.Typography,externalForwardedProps:E,ownerState:D}),[N,q]=u.useSlot("secondary",{className:I.secondary,elementType:u.Typography,externalForwardedProps:E,ownerState:D});return T!=null&&T.type!==u.Typography&&!l&&(T=n.jsx(_,{variant:w?"body2":"body1",component:G?.variant?void 0:"span",...G,children:T})),M!=null&&M.type!==u.Typography&&!l&&(M=n.jsx(N,{variant:"body2",color:"textSecondary",...q,children:M})),n.jsxs(L,{...H,children:[T,M]})});function il(t){return u.generateUtilityClass("MuiMenuItem",t)}const Wt=u.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),ol=(t,o)=>{const{ownerState:f}=t;return[o.root,f.dense&&o.dense,f.divider&&o.divider,!f.disableGutters&&o.gutters]},ll=t=>{const{disabled:o,dense:f,divider:a,disableGutters:p,selected:c,classes:l}=t,h={root:["root",f&&"dense",o&&"disabled",!p&&"gutters",a&&"divider",c&&"selected"]},d=u.composeClasses(h,il,l);return{...l,...d}},cl=u.styled(u.ButtonBase,{shouldForwardProp:t=>u.rootShouldForwardProp(t)||t==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:ol})(u.memoTheme(({theme:t})=>({...t.typography.body1,display:"flex",justifyContent:"flex-start",alignItems:"center",position:"relative",textDecoration:"none",minHeight:48,paddingTop:6,paddingBottom:6,boxSizing:"border-box",whiteSpace:"nowrap","&:hover":{textDecoration:"none",backgroundColor:(t.vars||t).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},[`&.${Wt.selected}`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,(t.vars||t).palette.action.selectedOpacity),[`&.${Wt.focusVisible}`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,`${(t.vars||t).palette.action.selectedOpacity} + ${(t.vars||t).palette.action.focusOpacity}`)}},[`&.${Wt.selected}:hover`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,`${(t.vars||t).palette.action.selectedOpacity} + ${(t.vars||t).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:t.alpha((t.vars||t).palette.primary.main,(t.vars||t).palette.action.selectedOpacity)}},[`&.${Wt.focusVisible}`]:{backgroundColor:(t.vars||t).palette.action.focus},[`&.${Wt.disabled}`]:{opacity:(t.vars||t).palette.action.disabledOpacity},[`& + .${Ns.root}`]:{marginTop:t.spacing(1),marginBottom:t.spacing(1)},[`& + .${Ns.inset}`]:{marginLeft:52},[`& .${Mt.root}`]:{marginTop:0,marginBottom:0},[`& .${Mt.inset}`]:{paddingLeft:36},[`& .${As.root}`]:{minWidth:36},variants:[{props:({ownerState:o})=>!o.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:o})=>o.divider,style:{borderBottom:`1px solid ${(t.vars||t).palette.divider}`,backgroundClip:"padding-box"}},{props:({ownerState:o})=>!o.dense,style:{[t.breakpoints.up("sm")]:{minHeight:"auto"}}},{props:({ownerState:o})=>o.dense,style:{minHeight:32,paddingTop:4,paddingBottom:4,...t.typography.body2,[`& .${As.root} svg`]:{fontSize:"1.25rem"}}}]}))),ve=fe.forwardRef(function(o,f){const a=u.useDefaultProps({props:o,name:"MuiMenuItem"}),{autoFocus:p=!1,component:c="li",dense:l=!1,divider:h=!1,disableGutters:d=!1,focusVisibleClassName:m,role:x="menuitem",tabIndex:S,className:b,...g}=a,k=fe.useContext(u.ListContext),w=fe.useMemo(()=>({dense:l||k.dense||!1,disableGutters:d}),[k.dense,l,d]),T=fe.useRef(null);u.useEnhancedEffect(()=>{p&&T.current&&T.current.focus()},[p]);const M={...a,dense:w.dense,divider:h,disableGutters:d},D=ll(a),I=u.useForkRef(T,f);let E;return a.disabled||(E=S!==void 0?S:-1),n.jsx(u.ListContext.Provider,{value:w,children:n.jsx(cl,{ref:I,role:x,tabIndex:E,component:c,focusVisibleClassName:u.clsx(D.focusVisible,m),className:u.clsx(D.root,b),...g,ownerState:M,classes:D})})}),Qe={postgres:[{label:"Host",name:"host",type:"text",required:!1},{label:"Port",name:"port",type:"number",required:!1},{label:"Database Name",name:"databaseName",type:"text",required:!1},{label:"User Name",name:"userName",type:"text",required:!1},{label:"Password",name:"password",type:"password",required:!1},{label:"Connection String",name:"connectionString",type:"text",required:!1}],bigquery:[{label:"Project ID",name:"defaultProjectId",type:"text",required:!1},{label:"Billing Project ID",name:"billingProjectId",type:"text",required:!1},{label:"Location",name:"location",type:"text",required:!1},{label:"Service Account Key JSON",name:"serviceAccountKeyJson",type:"text",required:!0},{label:"Maximum Bytes Billed",name:"maximumBytesBilled",type:"text",required:!1},{label:"Query Timeout Milliseconds",name:"queryTimeoutMilliseconds",type:"text",required:!1}],snowflake:[{label:"Account",name:"account",type:"text",required:!0},{label:"Username",name:"username",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!1},{label:"Role",name:"role",type:"text",required:!1},{label:"Warehouse",name:"warehouse",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1},{label:"Schema",name:"schema",type:"text",required:!1},{label:"Response Timeout Milliseconds",name:"responseTimeoutMilliseconds",type:"text",required:!1},{label:"Private Key",name:"privateKey",type:"password",required:!1},{label:"Private Key Passphrase",name:"privateKeyPass",type:"password",required:!1}],trino:[{label:"Server",name:"server",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!1},{label:"Catalog",name:"catalog",type:"text",required:!1},{label:"Schema",name:"schema",type:"text",required:!1},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!1},{label:"Peaka Key",name:"peakaKey",type:"password",required:!1}],databricks:[{label:"Host",name:"host",type:"text",required:!0},{label:"HTTP Path",name:"path",type:"text",required:!0},{label:"Access Token",name:"token",type:"password",required:!1},{label:"OAuth Client ID",name:"oauthClientId",type:"text",required:!1},{label:"OAuth Client Secret",name:"oauthClientSecret",type:"password",required:!1},{label:"Default Catalog",name:"defaultCatalog",type:"text",required:!1},{label:"Default Schema",name:"defaultSchema",type:"text",required:!1}],mysql:[{label:"Host",name:"host",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!0},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!0},{label:"Database",name:"database",type:"text",required:!0}],duckdb:[],motherduck:[{label:"Access Token",name:"accessToken",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1}],ducklake:[],publisher:[]},Qt={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",trino:"trinoConnection",databricks:"databricksConnection",mysql:"mysqlConnection",duckdb:"duckdbConnection",motherduck:"motherduckConnection",ducklake:"ducklakeConnection",publisher:"publisherConnection"},ma=Object.values(V.ConnectionTypeEnum).filter(t=>t!==V.ConnectionTypeEnum.Publisher),ar={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},tn=[{label:"Credential Provider",name:"provider",type:"text",required:!1,selectOptions:[{label:"Access key pair",value:"config"},{label:"Host credential chain",value:"credential_chain"}]},{label:"Access Key ID",name:"accessKeyId",type:"text",required:!1,visibleWhen:{field:"provider",value:"config"}},{label:"Secret Access Key",name:"secretAccessKey",type:"password",required:!1,visibleWhen:{field:"provider",value:"config"}},{label:"Credential Chain",name:"chain",type:"text",required:!1,visibleWhen:{field:"provider",value:"credential_chain"}},{label:"Region",name:"region",type:"text",required:!1},{label:"Endpoint",name:"endpoint",type:"text",required:!1},{label:"Session Token",name:"sessionToken",type:"password",required:!1,visibleWhen:{field:"provider",value:"config"}}],nn=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],ul=[{label:"Auth Type",name:"authType",type:"text",required:!0,selectOptions:[{label:"SAS Token",value:"sas_token"},{label:"Service Principal (SPN)",value:"service_principal"}]},{label:"SAS URL (e.g. https://account.blob.core.windows.net/container/file.parquet?sp=r&st=...)",name:"sasUrl",type:"text",required:!1,visibleWhen:{field:"authType",value:"sas_token"}},{label:"Tenant ID",name:"tenantId",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Client ID",name:"clientId",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Client Secret",name:"clientSecret",type:"password",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Account Name",name:"accountName",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"File URL (e.g. abfss://container/path/file.parquet)",name:"fileUrl",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}}];function wn(t){return t==="postgres"||t==="bigquery"||t==="snowflake"?Qe[t]||[]:t==="s3"?tn:t==="gcs"?nn:t==="azure"?ul:[]}function dl({onSubmit:t,isSubmitting:o}){const[f,a]=$.useState(!1),[p,c]=$.useState("postgres"),[l,h]=$.useState([]),[d,m]=$.useState("postgres"),[x,S]=$.useState("s3"),[b,g]=$.useState("config"),k=()=>{a(!0)},w=()=>{a(!1),h([]),c("postgres"),m("postgres"),S("s3"),g("config")},T=async E=>{E.preventDefault();const L=new FormData(E.currentTarget),H=L.get("name")?.toString(),_=L.get("type")?.toString(),G=Qe[_];if(!H)throw new Error("Name is required");if(!_)throw new Error("Type is required");let N;if(_==="ducklake"){const q={};if(d==="postgres"){const P=Qe.postgres,Y={};if(P.forEach(K=>{const X=L.get(`ducklake_pg_${K.name}`)?.toString();X&&(Y[K.name]=X)}),Object.keys(Y).length===0)throw new Error("DuckLake requires catalog connection");q.postgresConnection=Y}const U=L.get("ducklake_bucketUrl")?.toString();if(!U)throw new Error("DuckLake requires a bucket URL");const A={bucketUrl:U};if(x==="s3"){const P={};if(tn.forEach(Y=>{const K=L.get(`ducklake_s3_${Y.name}`)?.toString();K&&(P[Y.name]=K)}),P.provider==="credential_chain")delete P.accessKeyId,delete P.secretAccessKey,delete P.sessionToken;else{if(delete P.chain,!P.accessKeyId)throw new Error("S3 Access Key ID is required");if(!P.secretAccessKey)throw new Error("S3 Secret Access Key is required")}Object.keys(P).length>0&&(A.s3Connection=P)}else if(x==="gcs"){const P={};if(nn.forEach(Y=>{const K=L.get(`ducklake_gcs_${Y.name}`)?.toString();K&&(P[Y.name]=K)}),!P.keyId)throw new Error("GCS Key ID is required");if(!P.secret)throw new Error("GCS Secret is required");Object.keys(P).length>0&&(A.gcsConnection=P)}N={name:H,type:_,ducklakeConnection:{catalog:q,storage:A}}}else if(_==="duckdb"){if(l.length===0)throw new Error("DuckDB connection must have at least one attached database");const q=l.map((U,A)=>{const P=U.dbType,Y=L.get(`attachedDb_${A}_name`)?.toString();if(!Y)throw new Error(`Attached database at index ${A} must have a name`);const K={name:Y,type:P},X=wn(P);if(X&&X.length>0){const J={};if(X.forEach(ne=>{const W=L.get(`attachedDb_${A}_${ne.name}`)?.toString();W&&(J[ne.name]=W)}),P==="s3"){if(J.provider==="credential_chain")delete J.accessKeyId,delete J.secretAccessKey,delete J.sessionToken;else if(delete J.chain,!J.accessKeyId||!J.secretAccessKey)throw new Error(`Attached database "${Y}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const B=ar[P];B&&(K[B]=J)}return K});N={name:H,type:_,duckdbConnection:{attachedDatabases:q}}}else{const q={};if(G.forEach(U=>{const A=L.get(U.name)?.toString();A&&(q[U.name]=A)}),_==="postgres"){if(!!!q.connectionString?.trim()){const A=["host","port","databaseName","userName","password"];for(const P of A)if(!q[P])throw new Error(`${G.find(Y=>Y.name===P)?.label||P} is required`)}}else if(_==="bigquery"){if(!q.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if(_==="snowflake"){if(!q.account)throw new Error("Account is required");if(!q.username)throw new Error("Username is required");if(!q.warehouse)throw new Error("Warehouse is required");if(!q.password&&!q.privateKey)throw new Error("Either password or private key is required")}else if(_==="trino"){if(!q.server)throw new Error("Server is required");if(!q.user)throw new Error("User is required");if(q.server.trim().startsWith("https://")&&!q.password&&!q.peakaKey)throw new Error("Password is required for HTTPS connections (or use Peaka Key)")}else if(_==="mysql"){const U=["host","port","database","user","password"];for(const A of U)if(!q[A])throw new Error(`${G.find(P=>P.name===A)?.label||A} is required`)}else if(_==="motherduck"){if(!q.accessToken)throw new Error("Access Token is required")}else if(_==="databricks"){if(!q.host)throw new Error("Host is required");if(!q.path)throw new Error("HTTP Path is required");const U=q.oauthClientId&&q.oauthClientSecret;if(!q.token&&!U)throw new Error("Either Access Token or OAuth Client ID + Secret is required")}N={name:H,type:_,[Qt[_]]:q}}await t(N),w()},M=()=>{h([...l,{name:"",dbType:"postgres"}])},D=E=>{h(l.filter((L,H)=>H!==E))},I=(E,L)=>{const H=[...l];H[E]={...H[E],dbType:L},h(H)};return n.jsxs($.Fragment,{children:[n.jsx(u.AddButton,{label:"Connection",onClick:k}),n.jsx(u.AppDialog,{open:f,onClose:w,title:"New connection",description:"Add a connection so packages in this environment can query your database with Malloy.",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:o,onClick:w,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"connection-form",variant:"contained",loading:o,children:"Create connection"})]}),children:n.jsx("form",{onSubmit:T,id:"connection-form",children:n.jsxs(Dn,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small"}),n.jsx(u.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:p,select:!0,onChange:E=>c(E.target.value),children:ma.map(E=>n.jsx(ve,{value:E,children:E},E))}),p==="ducklake"?n.jsxs(pe,{sx:{mt:2},children:[n.jsxs(pe,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),n.jsx(u.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:d,select:!0,onChange:E=>m(E.target.value),children:n.jsx(ve,{value:"postgres",children:"PostgreSQL"})}),d==="postgres"&&n.jsx(n.Fragment,{children:Qe.postgres.map(E=>n.jsx(u.TextField,{id:`ducklake_pg_${E.name}`,name:`ducklake_pg_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small"},`pg_${E.name}`))})]}),n.jsxs(pe,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),n.jsxs(u.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:x,select:!0,onChange:E=>S(E.target.value),children:[n.jsx(ve,{value:"s3",children:"S3"}),n.jsx(ve,{value:"gcs",children:"GCS"})]}),n.jsx(u.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:x==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small"}),x==="s3"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),tn.filter(E=>E.visibleWhen?b===E.visibleWhen.value:!0).map(E=>n.jsx(u.TextField,{id:`ducklake_s3_${E.name}`,name:`ducklake_s3_${E.name}`,label:E.label,type:E.selectOptions?void 0:E.type,fullWidth:!0,size:"small",required:E.required,select:!!E.selectOptions,defaultValue:E.selectOptions?b:void 0,onChange:E.name==="provider"?L=>g(L.target.value):void 0,placeholder:E.name==="region"?"us-east-1":void 0,children:E.selectOptions?.map(L=>n.jsx(ve,{value:L.value,children:L.label},L.value))},`s3_${E.name}`))]}),x==="gcs"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),nn.map(E=>n.jsx(u.TextField,{id:`ducklake_gcs_${E.name}`,name:`ducklake_gcs_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required},`gcs_${E.name}`))]})]})]}):p==="duckdb"?n.jsxs(pe,{sx:{mt:2},children:[n.jsxs(pe,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsx(u.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),n.jsx(u.SecondaryButton,{label:"Database",icon:n.jsx(u.AddIcon,{}),onClick:M,ariaLabel:"Add database"})]}),l.length===0&&n.jsx(u.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),l.map((E,L)=>{const H=wn(E.dbType);return n.jsxs(pe,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsxs(pe,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsxs(u.Typography,{variant:"subtitle2",children:["Database ",L+1]}),n.jsx(u.IconButton,{onClick:()=>D(L),size:"small",color:"error",children:n.jsx(fa,{fontSize:"small"})})]}),n.jsx(u.TextField,{required:!0,id:`attachedDb_${L}_name`,name:`attachedDb_${L}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:E.name}),n.jsx(u.TextField,{id:`attachedDb_${L}_type`,name:`attachedDb_${L}_type`,label:"Database Type",fullWidth:!0,size:"small",value:E.dbType,select:!0,onChange:_=>I(L,_.target.value),children:Object.values(V.AttachedDatabaseTypeEnum).map(_=>n.jsx(ve,{value:_,children:_},_))}),H.filter(_=>_.visibleWhen?(E[_.visibleWhen.field]||H.find(N=>N.name===_.visibleWhen?.field)?.selectOptions?.[0]?.value)===_.visibleWhen.value:!0).map(_=>n.jsx(u.TextField,{id:`attachedDb_${L}_${_.name}`,name:`attachedDb_${L}_${_.name}`,label:_.label,type:_.selectOptions?void 0:_.type,fullWidth:!0,size:"small",required:_.required,select:!!_.selectOptions,defaultValue:_.selectOptions?.[0]?.value,onChange:_.selectOptions?G=>{const N=[...l];N[L]={...N[L],[_.name]:G.target.value},h(N)}:void 0,children:_.selectOptions?.map(G=>n.jsx(ve,{value:G.value,children:G.label},G.value))},_.name))]},L)})]}):Qe[p].map(E=>n.jsx(u.TextField,{id:E.name,name:E.name,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required},E.name))]})})})]})}function hl({connection:t,onCloseDialog:o,isMutating:f,onDelete:a}){const[p,c]=$.useState(!1),l=()=>{c(!0)},h=()=>{c(!1),o()};return n.jsxs($.Fragment,{children:[n.jsxs(ve,{"aria-label":`Delete connection ${t?.name??""}`.trim(),onClick:d=>{d.stopPropagation(),l()},sx:{color:"error.main"},children:[n.jsx(fr,{sx:{color:"inherit"},children:n.jsx(He.Delete,{fontSize:"small"})}),n.jsx(mr,{children:"Delete"})]}),n.jsx(u.AppDialog,{open:p,onClose:h,title:"Delete connection",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{onClick:h,children:"Cancel"}),n.jsx(u.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>a(),loading:f,children:"Delete connection"})]}),children:n.jsxs(u.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:t.name}),"? Packages that query through it stop working, and this cannot be undone."]})})]})}const $s=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function Rs(t){const o=t.duckdbConnection?.attachedDatabases;return!o||o.length===0?[]:o.map(f=>({name:f.name||"",dbType:f.type||"postgres"}))}function Ls(t){const o=t.ducklakeConnection;return o&&o.storage?.gcsConnection?"gcs":"s3"}function fl({connection:t,onSubmit:o,isSubmitting:f,onCloseDialog:a}){const[p,c]=$.useState(!1),[l,h]=$.useState(t.type),d=$.useMemo(()=>new Set(t.withheldFields??[]),[t.withheldFields]),[m,x]=$.useState(()=>Rs(t)),[S,b]=$.useState("postgres"),[g,k]=$.useState(()=>Ls(t)),[w,T]=$.useState(()=>t.ducklakeConnection?.storage?.s3Connection?.provider??"config"),M=()=>{x(Rs(t)),h(t.type),T(t.ducklakeConnection?.storage?.s3Connection?.provider??"config"),b("postgres"),k(Ls(t)),c(!0)},D=()=>{c(!1),a?.()},I=async N=>{N.preventDefault();const q=new FormData(N.currentTarget),U=q.get("name")?.toString(),A=q.get("type")?.toString(),P=Qe[A];if(!U)throw new Error("Name is required");if(!A)throw new Error("Type is required");let Y;if(A==="ducklake"){const K={};if(S==="postgres"){const B=Qe.postgres,ne={};if(B.forEach(W=>{const Q=q.get(`ducklake_pg_${W.name}`)?.toString();Q&&(ne[W.name]=Q)}),Object.keys(ne).length===0)throw new Error("DuckLake requires catalog connection");K.postgresConnection=ne}const X=q.get("ducklake_bucketUrl")?.toString();if(!X)throw new Error("DuckLake requires a bucket URL");const J={bucketUrl:X};if(g==="s3"){const B={};tn.forEach(W=>{const Q=q.get(`ducklake_s3_${W.name}`)?.toString();Q&&(B[W.name]=Q)});const ne=t.ducklakeConnection?.storage?.s3Connection;if(ne&&(!B.provider&&ne.provider&&(B.provider=ne.provider),!B.chain&&ne.chain&&(B.chain=ne.chain),!B.accessKeyId&&ne.accessKeyId&&(B.accessKeyId=ne.accessKeyId)),B.provider==="credential_chain")delete B.accessKeyId,delete B.secretAccessKey,delete B.sessionToken;else if(delete B.chain,!B.accessKeyId)throw new Error("S3 Access Key ID is required");Object.keys(B).length>0&&(J.s3Connection=B)}else if(g==="gcs"){const B={};nn.forEach(W=>{const Q=q.get(`ducklake_gcs_${W.name}`)?.toString();Q&&(B[W.name]=Q)});const ne=t.ducklakeConnection?.storage?.gcsConnection;if(ne&&!B.keyId&&ne.keyId&&(B.keyId=ne.keyId),!B.keyId)throw new Error("GCS Key ID is required");Object.keys(B).length>0&&(J.gcsConnection=B)}Y={name:U,type:A,ducklakeConnection:{catalog:K,storage:J}}}else if(A==="duckdb"){if(m.length===0)throw new Error("DuckDB connection must have at least one attached database");const K=m.map((X,J)=>{const B=X.dbType,ne=q.get(`attachedDb_${J}_name`)?.toString();if(!ne)throw new Error(`Attached database at index ${J} must have a name`);const W={name:ne,type:B},Q=wn(B);if(Q&&Q.length>0){const R={};if(Q.forEach(de=>{const ee=q.get(`attachedDb_${J}_${de.name}`)?.toString();ee&&(R[de.name]=ee)}),B==="s3"){if(R.provider==="credential_chain")delete R.accessKeyId,delete R.secretAccessKey,delete R.sessionToken;else if(delete R.chain,!R.accessKeyId||!R.secretAccessKey)throw new Error(`Attached database "${ne}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const Z=ar[B];Z&&(W[Z]=R)}return W});Y={name:U,type:A,duckdbConnection:{attachedDatabases:K}}}else{const K=t[Qt[A]]||{},X={};if(P.forEach(J=>{const B=q.get(J.name)?.toString(),ne=K[J.name];B?X[J.name]=B:$s.has(J.name)||(B!==void 0?X[J.name]=B:ne&&(X[J.name]=ne))}),A==="postgres"){const J=["host","port","databaseName","userName"],B=d.has("postgresConnection.connectionString");if(!(!!X.connectionString?.trim()||B)){const W=J;for(const Q of W)if(!X[Q])throw new Error(`${P.find(R=>R.name===Q)?.label||Q} is required`)}}else if(A==="snowflake"){if(!X.account)throw new Error("Account is required");if(!X.username)throw new Error("Username is required");if(!X.warehouse)throw new Error("Warehouse is required")}else if(A==="trino"){if(!X.server)throw new Error("Server is required");if(!X.user)throw new Error("User is required")}else if(A==="mysql"){const J=["host","port","database","user"];for(const B of J)if(!X[B])throw new Error(`${P.find(ne=>ne.name===B)?.label||B} is required`)}else if(A==="databricks"){if(!X.host)throw new Error("Host is required");if(!X.path)throw new Error("HTTP Path is required")}Y={name:U,type:A,[Qt[A]]:X}}await o(Y),D()},E=()=>{x([...m,{name:"",dbType:"postgres"}])},L=N=>{x(m.filter((q,U)=>U!==N))},H=(N,q)=>{const U=[...m];U[N]={...U[N],dbType:q},x(U)},_=(N,q)=>{const U=t.duckdbConnection?.attachedDatabases;if(!U||!U[N])return"";const A=U[N],P=ar[A.type||""];return P&&A[P]?A[P][q]??"":""},G=N=>{const q=t.ducklakeConnection;if(!q)return"";if(N.startsWith("pg_")){const U=N.replace("pg_","");return q.catalog?.postgresConnection?.[U]??""}if(N==="bucketUrl")return q.storage?.bucketUrl??"";if(N.startsWith("s3_")){const U=N.replace("s3_","");return q.storage?.s3Connection?.[U]??""}if(N.startsWith("gcs_")){const U=N.replace("gcs_","");return q.storage?.gcsConnection?.[U]??""}return""};return n.jsxs($.Fragment,{children:[n.jsxs(ve,{"aria-label":`Edit connection ${t?.name??""}`.trim(),onClick:N=>{N.preventDefault(),N.stopPropagation(),M()},children:[n.jsx(fr,{children:n.jsx(He.Edit,{fontSize:"small"})}),n.jsx(mr,{children:"Edit"})]}),n.jsx(u.AppDialog,{open:p,onClose:D,title:"Edit connection",description:"Change how packages in this environment reach your database.",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:f,onClick:D,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"connection-form",variant:"contained",loading:f,children:"Save changes"})]}),children:n.jsx("form",{onSubmit:I,id:"connection-form",children:n.jsxs(Dn,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",defaultValue:t.name}),n.jsx(u.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:l,select:!0,onChange:N=>h(N.target.value),children:ma.map(N=>n.jsx(ve,{value:N,children:N},N))}),l==="ducklake"?n.jsxs(pe,{sx:{mt:2},children:[n.jsxs(pe,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),n.jsx(u.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:S,select:!0,onChange:N=>b(N.target.value),children:n.jsx(ve,{value:"postgres",children:"PostgreSQL"})}),S==="postgres"&&n.jsx(n.Fragment,{children:Qe.postgres.map(N=>n.jsx(u.TextField,{id:`ducklake_pg_${N.name}`,name:`ducklake_pg_${N.name}`,label:N.label,type:N.type,fullWidth:!0,size:"small",defaultValue:G(`pg_${N.name}`)},`pg_${N.name}`))})]}),n.jsxs(pe,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),n.jsxs(u.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:g,select:!0,onChange:N=>k(N.target.value),children:[n.jsx(ve,{value:"s3",children:"S3"}),n.jsx(ve,{value:"gcs",children:"GCS"})]}),n.jsx(u.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:g==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small",defaultValue:G("bucketUrl")}),g==="s3"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),tn.filter(N=>N.visibleWhen?w===N.visibleWhen.value:!0).map(N=>n.jsx(u.TextField,{id:`ducklake_s3_${N.name}`,name:`ducklake_s3_${N.name}`,label:N.label,type:N.selectOptions?void 0:N.type,fullWidth:!0,size:"small",required:N.required&&N.name!=="secretAccessKey",select:!!N.selectOptions,defaultValue:N.selectOptions?w:G(`s3_${N.name}`),onChange:N.name==="provider"?q=>T(q.target.value):void 0,placeholder:N.name==="region"?"us-east-1":N.name==="secretAccessKey"&&d.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:N.selectOptions?.map(q=>n.jsx(ve,{value:q.value,children:q.label},q.value))},`s3_${N.name}`))]}),g==="gcs"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),nn.map(N=>n.jsx(u.TextField,{id:`ducklake_gcs_${N.name}`,name:`ducklake_gcs_${N.name}`,label:N.label,type:N.type,fullWidth:!0,size:"small",required:N.required&&N.name!=="secret",defaultValue:G(`gcs_${N.name}`),placeholder:N.name==="secret"&&d.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${N.name}`))]})]})]}):l==="duckdb"?n.jsxs(pe,{sx:{mt:2},children:[n.jsxs(pe,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsx(u.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),n.jsx(u.SecondaryButton,{label:"Database",icon:n.jsx(u.AddIcon,{}),onClick:E,ariaLabel:"Add database"})]}),m.length===0&&n.jsx(u.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),m.map((N,q)=>{const U=wn(N.dbType);return n.jsxs(pe,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsxs(pe,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsxs(u.Typography,{variant:"subtitle2",children:["Database ",q+1]}),n.jsx(u.IconButton,{"aria-label":`Remove attached database ${q+1}`,onClick:()=>L(q),size:"small",color:"error",children:n.jsx(fa,{fontSize:"small"})})]}),n.jsx(u.TextField,{required:!0,id:`attachedDb_${q}_name`,name:`attachedDb_${q}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:N.name}),n.jsx(u.TextField,{id:`attachedDb_${q}_type`,name:`attachedDb_${q}_type`,label:"Database Type",fullWidth:!0,size:"small",value:N.dbType,select:!0,onChange:A=>H(q,A.target.value),children:Object.values(V.AttachedDatabaseTypeEnum).map(A=>n.jsx(ve,{value:A,children:A},A))}),U.filter(A=>A.visibleWhen?(N[A.visibleWhen.field]||_(q,A.visibleWhen.field)||U.find(Y=>Y.name===A.visibleWhen?.field)?.selectOptions?.[0]?.value)===A.visibleWhen.value:!0).map(A=>n.jsx(u.TextField,{id:`attachedDb_${q}_${A.name}`,name:`attachedDb_${q}_${A.name}`,label:A.label,type:A.selectOptions?void 0:A.type,fullWidth:!0,size:"small",required:A.required,select:!!A.selectOptions,defaultValue:_(q,A.name)||A.selectOptions?.[0]?.value,onChange:A.selectOptions?P=>{const Y=[...m];Y[q]={...Y[q],[A.name]:P.target.value},x(Y)}:void 0,children:A.selectOptions?.map(P=>n.jsx(ve,{value:P.value,children:P.label},P.value))},A.name))]},q)})]}):Qe[l].map(N=>{const q=t?.[Qt[l]??""]?.[N.name??""]??"",U=N.type==="password"||$s.has(N.name),A=d.has(`${Qt[l]??""}.${N.name}`);return n.jsx(u.TextField,{id:N.name,name:N.name,label:N.label,type:N.type,fullWidth:!0,size:"small",required:N.required&&!U&&!q,defaultValue:q,placeholder:A?"Leave empty to keep existing":void 0,helperText:U?A?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0},N.name)})]})})})]})}function _s(t,o){return!t||t.type!=="duckdb"?!1:(t.duckdbConnection?.attachedDatabases||[]).some(a=>a.type==="azure"&&a.name===o)}function ml(t){return t.startsWith("gs://")||t.startsWith("s3://")||t.startsWith("https://")||t.startsWith("abfss://")||t.startsWith("az://")}function pa({connectionName:t,resourceUri:o,schema:f,connection:a}){const{apiClients:p}=V.useServer(),{environmentName:c}=u.parseResourceUri(o),[l,h]=$.useState(null),[d,m]=$.useState(f||null),[x,S]=$.useState(!1),{data:b,isError:g,isLoading:k,error:w}=u.useQueryWithApiError({queryKey:["schemas",c,t],queryFn:()=>p.connections.listSchemas(c,t)}),T=b?.data||[];return n.jsxs(v.Grid,{container:!0,spacing:1,children:[!f&&n.jsx(v.Grid,{size:{xs:12,md:4},children:n.jsxs(v.Paper,{sx:{p:1,m:0},children:[n.jsxs(v.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:0},children:[n.jsx(v.Typography,{variant:"overline",fontWeight:"bold",children:"Table Paths"}),n.jsx(v.FormControlLabel,{control:n.jsx(v.Switch,{checked:x,onChange:M=>S(M.target.checked)}),label:"Hidden Schemas"})]}),n.jsx(v.Divider,{sx:{mt:"2px"}}),n.jsxs(v.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[k&&n.jsx(u.Loading,{text:"Loading schemas..."}),g&&n.jsx(u.ApiErrorDisplay,{error:w,context:`${c} > ${t} > Schemas`}),!k&&!g&&T.length===0&&n.jsx(v.Typography,{variant:"body2",children:"No Schemas"}),!k&&!g&&T.length>0&&n.jsx(v.List,{dense:!0,disablePadding:!0,children:T.map(M=>{const D=M.name;if(M.isHidden&&!x)return null;const E=d===D;return n.jsx(v.ListItemButton,{selected:E,onClick:()=>{m(D),h(null)},children:n.jsx(v.ListItemText,{primary:D})},D)})})]})]})}),n.jsx(v.Grid,{size:{xs:12,md:f?6:4},children:d&&n.jsx(v.Paper,{sx:{p:1,m:0},children:n.jsx(gl,{connectionName:t,schemaName:d,onTableSelect:M=>{h(M)},resourceUri:o,connection:a})})}),n.jsx(v.Grid,{size:{xs:12,md:f?6:4},children:d&&l&&n.jsx(pl,{environmentName:c,connectionName:t,schemaName:d,tableResource:l})})]})}function pl({environmentName:t,connectionName:o,schemaName:f,tableResource:a}){const{apiClients:p}=V.useServer(),{data:c,isLoading:l,isError:h,error:d}=u.useQueryWithApiError({queryKey:["connectionTableDetail",t,o,f,a],queryFn:()=>p.connections.getTable(t,o,f,a),enabled:!!f&&!!a}),m={resource:c?.data?.resource??a,columns:c?.data?.columns??[]};return n.jsxs(v.Paper,{sx:{p:1,m:0},children:[h&&n.jsx(u.ApiErrorDisplay,{error:d,context:`${t} > ${o} > ${f} > ${a}`}),!h&&n.jsx(yl,{table:m,loading:l})]})}function yl({table:t,loading:o}){return o?n.jsx(u.Loading,{text:"Loading columns..."}):n.jsxs(n.Fragment,{children:[n.jsxs(v.Typography,{variant:"overline",fontWeight:"bold",sx:{display:"block",wordBreak:"break-all"},children:[t.resource.includes("://")||/\.(parquet|csv|json|tsv|ndjson)$/i.test(t.resource)?"File":"Table",": ",t.resource]}),n.jsx(v.Divider,{}),n.jsx(v.Box,{sx:{mt:"10px",maxHeight:"600px",overflowY:"auto"},children:n.jsx(v.TableContainer,{children:n.jsxs(v.Table,{size:"small",sx:{"& .MuiTableCell-root":{padding:"10px"}},children:[n.jsx(v.TableHead,{children:n.jsxs(v.TableRow,{children:[n.jsx(v.TableCell,{children:"NAME"}),n.jsx(v.TableCell,{children:"TYPE"})]})}),n.jsx(v.TableBody,{children:t.columns?.sort((f,a)=>f.name.localeCompare(a.name))?.map(f=>n.jsxs(v.TableRow,{children:[n.jsx(v.TableCell,{children:f.name}),n.jsx(v.TableCell,{children:f.type})]},f.name))})]})})})]})}function gl({connectionName:t,schemaName:o,onTableSelect:f,resourceUri:a,connection:p}){const{environmentName:c}=u.parseResourceUri(a),{apiClients:l}=V.useServer(),[h,d]=$.useState(""),{data:m,isSuccess:x,isError:S,error:b,isLoading:g}=u.useQueryWithApiError({queryKey:["tablesInSchema",c,t,o],queryFn:()=>l.connections.listTables(c,t,o)}),k=_s(p,o),w=M=>k?M:M.split(".").pop()||M,T=x&&m?.data?m.data.filter(M=>w(M.resource).toLowerCase().includes(h.toLowerCase())).sort((M,D)=>w(M.resource).localeCompare(w(D.resource))):[];return n.jsxs(n.Fragment,{children:[n.jsx(v.Typography,{variant:"overline",fontWeight:"bold",children:ml(o)||_s(p,o)?`Files in ${o}`:`Tables in ${o}`}),n.jsx(v.Divider,{}),n.jsx(v.Box,{sx:{mt:1,mb:1},children:n.jsx(v.TextField,{size:"small",fullWidth:!0,placeholder:"Search tables...",value:h,onChange:M=>d(M.target.value),variant:"outlined"})}),n.jsx(v.Divider,{}),n.jsxs(v.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[g&&n.jsx(u.Loading,{text:"Fetching Tables..."}),S&&n.jsx(u.ApiErrorDisplay,{error:b,context:`${c} > ${t} > ${o}`}),x&&T.length===0&&n.jsx(v.Typography,{variant:"body2",children:"No Tables"}),x&&m?.data&&m.data.length>0&&n.jsx(v.List,{dense:!0,disablePadding:!0,children:T.map(M=>{let D=w(M.resource);return!k&&M.resource.includes("://")&&(D=M.resource.split("/").pop()||M.resource),n.jsx(v.ListItemButton,{onClick:()=>f(M.resource),children:n.jsx(v.ListItemText,{primary:D,secondary:M.columns.length>0?`${M.columns.length} columns`:void 0})},M.resource)})})]})]})}const xl={bigquery:"BigQuery",snowflake:"Snowflake",postgres:"PostgreSQL",mysql:"MySQL",trino:"Trino",databricks:"Databricks",duckdb:"DuckDB",ducklake:"DuckLake",s3:"S3",gcs:"GCS",azure:"Azure"};function bl(t){return t?xl[t]??t:""}function vl({resourceUri:t}){const{apiClients:o,mutable:f}=V.useServer(),a=Tn.useQueryClient(),{environmentName:p}=u.parseResourceUri(t),[c,l]=$.useState(""),[h,d]=$.useState(null),m=u.encodeResourceUri({environmentName:p,connectionName:h}),{data:x,isSuccess:S,isError:b,error:g}=u.useQueryWithApiError({queryKey:["connections",p],queryFn:()=>o.connections.listConnections(p)}),k=u.useMutationWithApiError({mutationFn:Ke("connection","create",I=>o.environments.updateEnvironment(p,{name:p,connections:[...x.data,I]})),onSuccess(){l("Connection added successfully"),a.invalidateQueries({queryKey:["connections",p]})},onError(I){l(I.message)}}),w=u.useMutationWithApiError({mutationFn:Ke("connection","update",I=>o.environments.updateEnvironment(p,{name:p,connections:x.data.map(E=>E.name===I.name?I:E)})),onSuccess(I,E){l(`Connection ${E.name} updated successfully`),a.invalidateQueries({queryKey:["connections",p]})},onError(I){l(I.message)}}),T=u.useMutationWithApiError({mutationFn:Ke("connection","delete",I=>{if(!I.name)throw new Error("Cannot delete a connection with no name");return o.connections.deleteConnection(p,I.name)}),onSuccess(I,E){l(`Connection ${E.name} deleted successfully`),a.invalidateQueries({queryKey:["connections",p]})},onError(I){l(I.message)}}),M=S?[...x.data].sort((I,E)=>(I.name??"").localeCompare(E.name??"")):[],D=k.isPending||w.isPending||T.isPending;return n.jsxs(ze,{title:"Connections",...S?{count:M.length}:{},description:"Database connections available to packages in this environment",...f&&S?{action:n.jsx(dl,{onSubmit:I=>k.mutateAsync(I),isSubmitting:k.isPending})}:{},children:[!S&&!b&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",children:"Fetching Connections..."}),b&&n.jsx(u.ApiErrorDisplay,{error:g,context:`${p} > Connections`}),S&&M.length===0&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),S&&M.length>0&&n.jsx(v.Stack,{children:M.map(I=>n.jsx(Sl,{connection:I,mutable:f,isMutating:D,onOpenExplorer:()=>d(I.name??null),onEdit:E=>w.mutateAsync(E),onDelete:E=>T.mutateAsync(E)},I.name))}),n.jsx(v.Snackbar,{open:c!=="",autoHideDuration:6e3,onClose:()=>l(""),message:c}),n.jsx(u.AppDialog,{open:h!==null,onClose:()=>d(null),maxWidth:"lg",title:`Connection explorer: ${h??""}`,showClose:!0,children:h&&n.jsx(pa,{resourceUri:m,connectionName:h,connection:x?.data?.find(I=>I.name===h)})})]})}function Sl({connection:t,mutable:o,isMutating:f,onOpenExplorer:a,onEdit:p,onDelete:c}){const[l,h]=$.useState(null),d=!!l,m=S=>{S.stopPropagation(),h(S.currentTarget)},x=()=>h(null);return n.jsx(Mn,{icon:n.jsx(Ko,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.connection,label:t.name??"",ariaLabel:t.name??"",description:bl(t.type),onClick:a,...o?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(v.IconButton,{size:"small",onClick:m,"aria-label":`Connection actions for ${t.name??""}`.trim(),children:n.jsx(He.MoreVert,{fontSize:"small"})}),n.jsxs(v.Menu,{anchorEl:l,open:d,onClose:x,onClick:S=>S.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(fl,{connection:t,onSubmit:p,isSubmitting:f,onCloseDialog:x}),n.jsx(hl,{connection:t,onCloseDialog:x,isMutating:f,onDelete:()=>c(t)})]})]})}:{}})}const wl=u.createSvgIcon([n.jsx("path",{d:"M20 2H4c-1 0-2 .9-2 2v3.01c0 .72.43 1.34 1 1.69V20c0 1.1 1.1 2 2 2h14c.9 0 2-.9 2-2V8.7c.57-.35 1-.97 1-1.69V4c0-1.1-1-2-2-2m-1 18H5V9h14zm1-13H4V4h16z"},"0"),n.jsx("path",{d:"M9 12h6v2H9z"},"1")]);function kl({resourceUri:t,onCloseDialog:o}){const[f,a]=$.useState(!1),{apiClients:p}=V.useServer(),c=()=>{a(!0)},l=()=>{a(!1),o()},{environmentName:h,packageName:d}=u.parseResourceUri(t),m=Dt({mutationFn:()=>p.packages.deletePackage(h,d),success:"Package deleted",invalidates:[["packages",h]],closeDialog:l,resource:"package",action:"delete"});return n.jsxs($.Fragment,{children:[n.jsxs(v.MenuItem,{onClick:c,children:[n.jsx(v.ListItemIcon,{children:n.jsx(He.Delete,{fontSize:"small"})}),n.jsx(v.ListItemText,{children:"Delete"})]}),n.jsx(u.AppDialog,{open:f,onClose:l,title:"Delete package",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{onClick:l,children:"Cancel"}),n.jsx(u.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>m.mutate(),loading:m.isPending,children:"Delete package"})]}),children:n.jsxs(u.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:d}),"? The package stops being served and this cannot be undone."]})}),m.notice]})}function Cl({package:t,resourceUri:o,onCloseDialog:f}){const[a,p]=$.useState(!1),{apiClients:c}=V.useServer(),l=()=>{p(!0)},h=()=>{p(!1),f()},{packageName:d,environmentName:m}=u.parseResourceUri(o),x=Dt({mutationFn(b){return c.packages.updatePackage(m,d,{name:d,description:b.description})},success:"Package updated",invalidates:[["packages",m]],closeDialog:h,resource:"package",action:"update"}),S=b=>{b.preventDefault();const k=new FormData(b.currentTarget).get("description")?.toString();x.mutate({description:k})};return n.jsxs($.Fragment,{children:[n.jsxs(v.MenuItem,{onClick:l,children:[n.jsx(v.ListItemIcon,{children:n.jsx(He.Edit,{fontSize:"small"})}),n.jsx(v.ListItemText,{children:"Edit"})]}),n.jsx(u.AppDialog,{open:a,onClose:h,title:"Edit package",description:`What ${t.name} is, for the people who open it.`,actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:x.isPending,onClick:h,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"package-form",variant:"contained",loading:x.isPending,children:"Save changes"})]}),children:n.jsx("form",{onSubmit:S,id:"package-form",children:n.jsxs(v.Stack,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:t.name,InputLabelProps:{shrink:!0}}),n.jsx(u.TextField,{id:"description",name:"description",label:"Description",multiline:!0,fullWidth:!0,rows:4,size:"small",defaultValue:t.description,InputLabelProps:{shrink:!0}})]})})}),x.notice]})}function ya({onSelectPackage:t,resourceUri:o}){const{apiClients:f}=V.useServer(),{environmentName:a}=u.parseResourceUri(o),{data:p,isSuccess:c,isError:l,error:h}=u.useQueryWithApiError({queryKey:["packages",a],queryFn:()=>f.packages.listPackages(a)});if(l)return n.jsx(u.ApiErrorDisplay,{error:h,context:`${a} > Packages`});if(!c)return n.jsx(u.Loading,{text:"Fetching Packages..."});const d=[...p.data].sort((m,x)=>m.name.localeCompare(x.name));return n.jsx(v.Stack,{children:d.map(m=>{const x=u.encodeResourceUri({environmentName:a,packageName:m.name});return n.jsx(Tl,{pkg:m,packageResourceUri:x,onSelectPackage:t},m.name)})})}function Tl({pkg:t,packageResourceUri:o,onSelectPackage:f}){const{mutable:a}=V.useServer(),[p,c]=$.useState(null),l=!!p,h=m=>{m.stopPropagation(),c(m.currentTarget)},d=()=>c(null);return n.jsx(Mn,{icon:n.jsx(wl,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.package,label:t.name,ariaLabel:t.name,...t.description?{description:t.description}:{},onClick:m=>f(t.name,m),...a?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(v.IconButton,{size:"small",onClick:h,"aria-label":`Package actions for ${t.name}`,children:n.jsx(He.MoreVert,{fontSize:"small"})}),n.jsxs(v.Menu,{anchorEl:p,open:l,onClose:d,onClick:m=>m.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(Cl,{package:t,resourceUri:o,onCloseDialog:d}),n.jsx(kl,{resourceUri:o,onCloseDialog:d})]})]})}:{}})}function Ml({onSelectPackage:t,resourceUri:o}){const{apiClients:f,mutable:a}=V.useServer(),{environmentName:p}=u.parseResourceUri(o),c=u.useQueryWithApiError({queryKey:["packages",p],queryFn:()=>f.packages.listPackages(p)});return $.useEffect(()=>{window.scrollTo({top:0,behavior:"auto"})},[]),n.jsxs(v.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[n.jsxs(v.Box,{sx:{mb:4},children:[n.jsx(v.Box,{children:n.jsx(hr,{label:"Publisher",onClick:l=>t("/",l)})}),n.jsx(v.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em",mb:.5},children:p}),n.jsx(v.Typography,{variant:"body2",color:"text.secondary",children:"Manage packages and database connections in this environment. Open a package to explore its models and notebooks."})]}),n.jsx(ze,{title:"Packages",...c.isSuccess?{count:c.data.data.length}:{},description:"Published packages available for use in this environment",...a?{action:n.jsx(Xo,{resourceUri:o})}:{},children:n.jsx(ya,{onSelectPackage:t,resourceUri:o})}),n.jsx(vl,{resourceUri:o}),n.jsx($o,{resourceUri:o})]})}u.dayjs.extend(u.utc);function Yn(t){switch(t){case"Star":return["Equals","Contains"];case"MinMax":return["Equals","Less Than","Greater Than","Between"];case"DateMinMax":return["Equals","Before","After","Between"];case"Retrieval":return["Semantic Search"];case"Boolean":return["Equals"];case"NONE":default:return[]}}function Dl(t){return t==="DateMinMax"}function Zn(t){return t==="Between"}function jl({spec:t,values:o,selection:f,onChange:a,retrievalFn:p}){const c=()=>f?.matchType?f.matchType:t.defaultMatchType?t.defaultMatchType:t.filterType==="DateMinMax"?"Between":Yn(t.filterType)[0]||"Equals",[l,h]=$.useState(c()),[d,m]=$.useState(f?.value??""),[x,S]=$.useState(f?.value2??""),[b,g]=$.useState([]),[k,w]=$.useState(!1),[T,M]=$.useState(""),[D,I]=$.useState(!1),[E,L]=$.useState(!1),H=$.useRef(null),_=$.useRef(0),[G,N]=$.useState(!1);$.useEffect(()=>{if(t.filterType!=="Retrieval"||!p)return;const W=T.trim();if(W.length<=2){g([]),I(!1);return}return H.current&&clearTimeout(H.current),H.current=setTimeout(async()=>{_.current+=1;const Q=_.current;w(!0);try{const R=await p(W,t);Q===_.current&&g(R)}catch(R){Q===_.current&&(console.error("Retrieval failed",R),g([]))}finally{Q===_.current&&(w(!1),I(!0))}},500),()=>{H.current&&clearTimeout(H.current)}},[T,t,p]),$.useEffect(()=>{f===null?(m(""),S(""),h(t.defaultMatchType??(t.filterType==="DateMinMax"?"Between":Yn(t.filterType)[0]||"Equals"))):f&&(h(f.matchType),m(f.value??""),S(f.value2??""))},[f,t.filterType,t.defaultMatchType]);const q=Yn(t.filterType),U=Dl(t.filterType),A=Zn(l),P=U&&o.length>=2&&o[0].value instanceof Date?u.dayjs.utc(o[0].value):void 0,Y=U&&o.length>=2&&o[1].value instanceof Date?u.dayjs.utc(o[1].value):void 0,K=t.filterType==="MinMax"&&o.length>=2&&typeof o[0].value=="number"?o[0].value:void 0,X=t.filterType==="MinMax"&&o.length>=2&&typeof o[1].value=="number"?o[1].value:void 0;if(q.length===0)return null;const J=W=>{const Q=W.target.value;h(Q),Zn(Q)||S(""),d&&a({dimensionName:t.dimensionName,source:t.source,filterName:t.filterName,matchType:Q,value:d,...Zn(Q)&&x&&{value2:x}})},B=(W,Q)=>{m(W??""),Q!==void 0&&S(Q??"");const R=Array.isArray(W)&&W.length===0;a(!R&&W!==""&&W!==null&&W!==void 0?{dimensionName:t.dimensionName,source:t.source,filterName:t.filterName,matchType:l,value:W,...A&&Q&&{value2:Q}}:null)},ne=()=>{m(""),S(""),a(null)};return n.jsxs(pe,{sx:{display:"flex",flexDirection:"column",gap:1.5,fontSize:"0.75rem","& .MuiInputBase-root":{fontSize:"0.75rem"},"& .MuiInputBase-input":{padding:"6px 10px"},"& .MuiSelect-select":{padding:"6px 10px !important"},"& .MuiAutocomplete-input":{padding:"0 !important"},"& .MuiAutocomplete-root .MuiInputBase-root":{padding:"5px 10px",minHeight:"29.5px",boxSizing:"border-box",flexWrap:"wrap"},"& .MuiChip-root":{height:"16px",margin:"0 2px 0 0"},"& .MuiChip-label":{fontSize:"0.7rem",padding:"0 6px"},"& .MuiChip-deleteIcon":{fontSize:"14px",margin:"0 2px 0 -4px"},"& .MuiInputLabel-root":{fontSize:"0.75rem",transform:"translate(10px, 6px) scale(1)"},"& .MuiInputLabel-shrink":{fontSize:"0.85rem",transform:"translate(14px, -9px) scale(0.75)"},"& .MuiOutlinedInput-notchedOutline legend":{fontSize:"0.65rem"},"& .MuiFormHelperText-root":{fontSize:"0.65rem",marginTop:"2px"},"& .MuiSvgIcon-root":{fontSize:"1.25rem"}},children:[n.jsxs(pe,{sx:{fontWeight:600,color:t.required&&!f?"error.main":"text.primary"},children:[t.label??t.dimensionName,t.required&&n.jsx(pe,{component:"span",sx:{color:f?"text.secondary":"error.main",fontWeight:400,fontSize:"0.7rem",ml:.5},children:"(required)"})]}),t.filterType!=="Boolean"&&!t.defaultMatchType&&q.length>1&&n.jsxs(u.FormControl,{size:"small",fullWidth:!0,children:[n.jsx(u.InputLabel,{children:"Match Type"}),n.jsx(u.Select,{value:l,label:"Match Type",onChange:J,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:q.map(W=>n.jsx(ve,{value:W,children:W},W))})]}),t.filterType==="Star"&&l==="Equals"&&n.jsx(u.Autocomplete,{multiple:!0,size:"small",options:o,getOptionLabel:W=>typeof W=="string"?W:typeof W=="object"&&W!==null&&"value"in W?String(W.value):String(W),value:Array.isArray(d)?d.map(W=>o.find(Q=>Q.value===W)||W):d?[o.find(W=>W.value===d)||d]:[],onChange:(W,Q)=>{const R=Q.map(Z=>typeof Z=="string"?Z:Z&&typeof Z=="object"&&"value"in Z?Z.value:Z);B(R)},noOptionsText:"No matches found",renderInput:W=>n.jsx(u.TextField,{...W,size:"small",label:"Values",placeholder:"Select values..."}),freeSolo:!t.values||t.values.length===0,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),t.filterType==="Star"&&l==="Contains"&&n.jsx(u.TextField,{size:"small",label:"Search Text",value:d,onChange:W=>m(W.target.value),onBlur:()=>B(d),onKeyDown:W=>{W.key==="Enter"&&B(d)},placeholder:"Enter text to search...",fullWidth:!0}),t.filterType==="Boolean"&&n.jsxs(u.FormControl,{size:"small",fullWidth:!0,children:[n.jsx(u.InputLabel,{children:"Value"}),n.jsxs(u.Select,{value:d===!0?"true":d===!1?"false":"",label:"Value",onChange:W=>{const Q=W.target.value;Q==="true"?B(!0):Q==="false"?B(!1):ne()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[n.jsx(ve,{value:"",children:n.jsx("em",{children:"Blank"})}),n.jsx(ve,{value:"true",children:"True"}),n.jsx(ve,{value:"false",children:"False"})]})]}),t.filterType==="Retrieval"&&l==="Semantic Search"&&n.jsx(u.Autocomplete,{multiple:!0,size:"small",options:b,loading:k,getOptionLabel:W=>typeof W=="string"?W:typeof W=="object"&&W!==null&&"value"in W?String(W.value):String(W),value:Array.isArray(d)?d.map(W=>b.find(R=>R.value===W)||{value:W}):d?[{value:d}]:[],onInputChange:(W,Q)=>{M(Q)},onChange:(W,Q)=>{const R=Q.map(Z=>typeof Z=="string"?Z:Z&&typeof Z=="object"&&"value"in Z?Z.value:Z);B(R)},noOptionsText:T.trim().length<=2?"Type at least 3 characters to search":"No matches found",renderInput:W=>n.jsx(u.TextField,{...W,size:"small",label:"Search Values",placeholder:"Type to search...",onFocus:()=>L(!0),onBlur:()=>L(!1),helperText:E&&!k&&D&&b.length===0?"No matches found":void 0,InputProps:{...W.InputProps,endAdornment:n.jsxs(n.Fragment,{children:[k?n.jsx(u.CircularProgress,{color:"inherit",size:20}):null,W.InputProps.endAdornment]})}}),freeSolo:!0,filterOptions:W=>W,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),t.filterType==="MinMax"&&!A&&n.jsx(u.TextField,{size:"small",type:"number",label:"Value",value:d,onChange:W=>B(parseFloat(W.target.value)||""),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:K,max:X},helperText:G&&K!==void 0&&X!==void 0?`Valid range: [${K} - ${X}]`:void 0}),t.filterType==="MinMax"&&A&&n.jsxs(pe,{sx:{display:"flex",flexDirection:"column",gap:1},children:[n.jsxs(pe,{sx:{display:"flex",gap:1,alignItems:"center"},children:[n.jsx(u.TextField,{size:"small",type:"number",label:"From",value:d,onChange:W=>B(parseFloat(W.target.value)||"",x),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:K,max:x||X}}),n.jsx(pe,{children:"to"}),n.jsx(u.TextField,{size:"small",type:"number",label:"To",value:x,onChange:W=>B(d,parseFloat(W.target.value)||""),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:d||K,max:X}})]}),G&&K!==void 0&&X!==void 0&&n.jsxs(u.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",K," - ",X,"]"]})]}),U&&!A&&n.jsx(u.LocalizationProvider,{dateAdapter:u.AdapterDayjs,children:n.jsx(u.DatePicker,{label:"Date",value:d instanceof Date?u.dayjs.utc(d):null,onChange:W=>{W===null?B(null):W.isValid()&&B(W.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?void 0:P,maxDate:d instanceof Date?void 0:Y,referenceDate:l==="After"&&P?P:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>N(!0),onBlur:()=>N(!1),helperText:G&&P&&Y?`Valid range: [${P.format("YYYY-MM-DD")} - ${Y.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),U&&A&&n.jsx(u.LocalizationProvider,{dateAdapter:u.AdapterDayjs,children:n.jsxs(pe,{sx:{display:"flex",flexDirection:"column",gap:1},children:[n.jsxs(pe,{sx:{display:"flex",gap:1,alignItems:"center"},children:[n.jsx(pe,{sx:{flex:1,minWidth:0},children:n.jsx(u.DatePicker,{label:"From",value:d instanceof Date?u.dayjs.utc(d):null,onChange:W=>{W===null?B(null,x):W.isValid()&&B(W.utc().toDate(),x)},timezone:"UTC",minDate:d instanceof Date?void 0:P,maxDate:x instanceof Date?u.dayjs.utc(x):d instanceof Date?void 0:Y,referenceDate:P,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>N(!0),onBlur:()=>N(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),n.jsx(pe,{children:"to"}),n.jsx(pe,{sx:{flex:1,minWidth:0},children:n.jsx(u.DatePicker,{label:"To",value:x instanceof Date?u.dayjs.utc(x):null,onChange:W=>{W===null?B(d,null):W.isValid()&&B(d,W.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?u.dayjs.utc(d):x instanceof Date?void 0:P,maxDate:x instanceof Date?void 0:Y,referenceDate:d instanceof Date?u.dayjs.utc(d):P,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>N(!0),onBlur:()=>N(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),G&&P&&Y&&n.jsxs(u.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",P.format("YYYY-MM-DD")," -"," ",Y.format("YYYY-MM-DD"),"]"]})]})})]})}function Ol(t){const o=new Set,f=t.schema?.fields;if(!f)return o;for(const a of f)"kind"in a&&a.kind==="join"&&a.name&&o.add(a.name);return o}function El(t){if(!t)return null;for(const o of t)if(o.startsWith("##(filters)")){const f=o.slice(11).trim();try{const a=JSON.parse(f);if(Array.isArray(a)){const p=[];for(const c of a)if(typeof c=="string"){const l=c.indexOf(".");l>0&&l<c.length-1&&p.push({source:c.substring(0,l),dimension:c.substring(l+1)})}if(p.length>0)return{filters:p}}}catch(a){console.error(`Failed to parse "${o}" annotation:`,a)}}return null}function ga(t){if(t.startsWith("#(filter)")){const o=t.slice(9).trim();try{const f=JSON.parse(o);if(f.type)return f}catch(f){console.error(`Failed to parse "${t}" annotation:`,f)}}return null}function Il(t){const o=t.match(/^#\s*label\s*=\s*"([^"]+)"/);return o?o[1]:null}function Fl(t){const o=new Map;let f="";for(const a of t)if(a.type==="code"){if(!f&&a.text){const c=a.text.split(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),v=require("@mui/material"),$=require("react"),u=require("./DocumentStorage-DvUNSOiN.cjs.js"),V=require("./ServerProvider-CuYLH_Yi.cjs.js"),Tn=require("@tanstack/react-query"),la=require("@mui/system"),He=require("@mui/icons-material"),ut=require("./RenderedResult-DpHdrFtp.cjs.js"),bn=require("react-router-dom");function Do(t){const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const f in t)if(f!=="default"){const a=Object.getOwnPropertyDescriptor(t,f);Object.defineProperty(o,f,a.get?a:{enumerable:!0,get:()=>t[f]})}}return o.default=t,Object.freeze(o)}const fe=Do($),jo=u.createSvgIcon(n.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function hr({label:t,href:o,onClick:f}){const a=p=>{const c=p.metaKey||p.ctrlKey||p.shiftKey||p.altKey||p.button!==0;o!==void 0&&c||(p.preventDefault(),f(p))};return n.jsxs(v.Link,{...o===void 0?{component:"button",type:"button"}:{href:o},onClick:a,underline:"none","aria-label":`Back to ${t}`,sx:{display:"inline-flex",alignItems:"center",gap:.5,cursor:"pointer",color:"text.secondary",fontSize:"0.875rem",mb:2,border:0,p:0,background:"none",font:"inherit","&:hover":{color:"primary.main"}},children:[n.jsx(jo,{sx:{fontSize:18}}),"Back to ",t]})}function Oo(){const t=bn.useNavigate();return(o,f)=>{if(!f||!f.metaKey&&!f.ctrlKey&&!f.shiftKey&&f.button!==1){t(o);return}const a=new URL(o,window.location.href).href;(f.metaKey||f.ctrlKey||f.button===1||f.shiftKey)&&window.open(a,"_blank")}}function Eo(){const[t]=bn.useSearchParams(),o=bn.useNavigate(),f=bn.useLocation(),a=$.useMemo(()=>Object.fromEntries(t.entries()),[t]),p=$.useRef(new Set),c=$.useCallback((l,h)=>{const d=new Set([...h,...p.current]);p.current=new Set([...p.current,...Object.keys(l),...h]);const m=new URLSearchParams(f.search);for(const x of d)Object.prototype.hasOwnProperty.call(l,x)||m.delete(x);for(const[x,S]of Object.entries(l))m.set(x,S);o({search:m.toString(),hash:f.hash},{replace:!0})},[o,f]);return{params:a,onGivensChange:c}}const ca=u.createSvgIcon(n.jsx("path",{d:"M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3z"})),Io="publisher:resize";function Fo(t){return typeof t=="object"&&t!==null&&t.type===Io&&typeof t.height=="number"}function ua(t){return t.replace(/\/api\/v0\/?$/,"")}function da({server:t,environmentName:o,packageName:f,path:a}){const p=a.startsWith("public/")?a.slice(7):a;return`${ua(t)}/environments/${encodeURIComponent(o)}/packages/${encodeURIComponent(f)}/`+p}function No(t){try{const{environmentName:o,packageName:f,modelPath:a}=u.parseResourceUri(t);return!o||!f||!a?null:{environmentName:o,packageName:f,dataAppPath:a}}catch{return null}}function Ao({resourceUri:t}){const{server:o,apiClients:f}=V.useServer(),a=No(t),p=a?.environmentName??"",c=a?.packageName??"",l=a?.dataAppPath??"",h=$.useMemo(()=>da({server:o,environmentName:p,packageName:c,path:l}),[o,p,c,l]),m=u.useQueryWithApiError({queryKey:["data-apps",p,c],queryFn:()=>f.dataApps.listDataApps(p,c),enabled:!!a}).data?.data?.find(w=>w.path===l),x=m?.title??l,S=m?.fit==="viewport",b=$.useRef(null),[g,k]=$.useState(120);return $.useEffect(()=>{if(S)return;function w(T){Fo(T.data)&&T.source===b.current?.contentWindow&&T.data.height>0&&k(Math.ceil(T.data.height))}return window.addEventListener("message",w),()=>window.removeEventListener("message",w)},[S]),a?n.jsxs(v.Box,{sx:{p:3,...S?{height:"100%",display:"flex",flexDirection:"column"}:{maxWidth:1200,mx:"auto"}},children:[n.jsxs(v.Stack,{direction:"row",alignItems:"baseline",spacing:1,sx:{mb:1,flexShrink:0},children:[n.jsx(v.Typography,{variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em"},children:x}),n.jsx(v.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:V.MONO_FONT_FAMILY},children:l}),n.jsx(v.Box,{sx:{flex:1}}),n.jsx(v.Tooltip,{title:"Open standalone in new tab",children:n.jsx(v.IconButton,{size:"small",href:h,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:n.jsx(ca,{fontSize:"small"})})})]}),n.jsx(v.Box,{sx:{border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden",backgroundColor:"background.paper",...S?{flex:1,minHeight:0}:{}},children:n.jsx("iframe",{ref:b,src:h,title:x,sandbox:"allow-scripts allow-same-origin allow-forms",style:{display:"block",width:"100%",height:S?"100%":g,border:0}})})]}):n.jsxs(v.Box,{sx:{p:3,maxWidth:1200,mx:"auto"},children:[n.jsx(v.Typography,{variant:"h6",sx:{fontWeight:600},children:"Can't open data app"}),n.jsxs(v.Typography,{variant:"body2",color:"text.secondary",sx:{mt:1},children:["This data app link is missing an environment, package, or path:",n.jsx(v.Box,{component:"span",sx:{fontFamily:V.MONO_FONT_FAMILY,ml:1},children:t})]})]})}function ze({title:t,count:o,description:f,action:a,children:p}){const c=$.useId();return n.jsxs(v.Box,{component:"section","aria-labelledby":c,sx:{mb:4},children:[n.jsxs(v.Stack,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:f?0:1,minHeight:40},children:[n.jsxs(v.Stack,{direction:"row",alignItems:"baseline",spacing:1,children:[n.jsx(v.Typography,{id:c,variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em",lineHeight:1.2},children:t}),o!==void 0&&n.jsxs(v.Typography,{variant:"caption",color:"text.secondary",children:["(",o,")"]})]}),a]}),f&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:f}),n.jsx(v.Box,{children:p})]})}function $o({resourceUri:t}){const{environmentName:o}=u.parseResourceUri(t),{apiClients:f}=V.useServer(),[a,p]=$.useState(!1),c=90,{data:l,isSuccess:h,isError:d,error:m}=u.useQueryWithApiError({queryKey:["about",o],queryFn:()=>f.environments.getEnvironment(o,!1)}),x=l?.data?.readme||"",S=x.split(/\s+/),b=S.length>c,g=S.slice(0,c).join(" ");return n.jsxs(n.Fragment,{children:[!h&&!d&&n.jsx(u.Loading,{text:"Fetching About..."}),h&&x&&n.jsxs(ze,{title:"Readme",children:[n.jsx(u.Prose,{variant:"caption",children:a||!b?x:g}),b&&n.jsx(v.Box,{sx:{mt:1},children:n.jsx(u.SecondaryButton,{label:a?"Read less":"Read more",onClick:()=>p(!a)})})]}),d&&n.jsx(u.ApiErrorDisplay,{error:m,context:`${o} > About`})]})}function Ro(t={}){const{autoHideDuration:o=null,disableWindowBlurListener:f=!1,onClose:a,open:p,resumeHideDuration:c}=t,l=u.useTimeout();fe.useEffect(()=>{if(!p)return;function M(D){D.defaultPrevented||D.key==="Escape"&&a?.(D,"escapeKeyDown")}return document.addEventListener("keydown",M),()=>{document.removeEventListener("keydown",M)}},[p,a]);const h=u.useEventCallback((M,D)=>{a?.(M,D)}),d=u.useEventCallback(M=>{!a||M==null||l.start(M,()=>{h(null,"timeout")})});fe.useEffect(()=>(p&&d(o),l.clear),[p,o,d,l]);const m=M=>{a?.(M,"clickaway")},x=l.clear,S=fe.useCallback(()=>{o!=null&&d(c??o*.5)},[o,c,d]),b=M=>D=>{const I=M.onBlur;I?.(D),S()},g=M=>D=>{const I=M.onFocus;I?.(D),x()},k=M=>D=>{const I=M.onMouseEnter;I?.(D),x()},w=M=>D=>{const I=M.onMouseLeave;I?.(D),S()};return fe.useEffect(()=>{if(!f&&p)return window.addEventListener("focus",S),window.addEventListener("blur",x),()=>{window.removeEventListener("focus",S),window.removeEventListener("blur",x)}},[f,p,S,x]),{getRootProps:(M={})=>{const D={...u.extractEventHandlers(t),...u.extractEventHandlers(M)};return{role:"presentation",...M,...D,onBlur:b(D),onFocus:g(D),onMouseEnter:k(D),onMouseLeave:w(D)}},onClickAway:m}}function Is(t){return t.substring(2).toLowerCase()}function Lo(t,o){return o.documentElement.clientWidth<t.clientX||o.documentElement.clientHeight<t.clientY}function _o(t){const{children:o,disableReactTree:f=!1,mouseEvent:a="onClick",onClickAway:p,touchEvent:c="onTouchEnd"}=t,l=fe.useRef(!1),h=fe.useRef(null),d=fe.useRef(!1),m=fe.useRef(!1);fe.useEffect(()=>(setTimeout(()=>{d.current=!0},0),()=>{d.current=!1}),[]);const x=u.useForkRef(u.getReactElementRef(o),h),S=u.useEventCallback(k=>{const w=m.current;m.current=!1;const T=u.ownerDocument(h.current);if(!d.current||!h.current||"clientX"in k&&Lo(k,T))return;if(l.current){l.current=!1;return}let M;k.composedPath?M=k.composedPath().includes(h.current):M=!T.documentElement.contains(k.target)||h.current.contains(k.target),!M&&(f||!w)&&p(k)}),b=k=>w=>{m.current=!0;const T=o.props[k];T&&T(w)},g={ref:x};return c!==!1&&(g[c]=b(c)),fe.useEffect(()=>{if(c!==!1){const k=Is(c),w=u.ownerDocument(h.current),T=()=>{l.current=!0};return w.addEventListener(k,S),w.addEventListener("touchmove",T),()=>{w.removeEventListener(k,S),w.removeEventListener("touchmove",T)}}},[S,c]),a!==!1&&(g[a]=b(a)),fe.useEffect(()=>{if(a!==!1){const k=Is(a),w=u.ownerDocument(h.current);return w.addEventListener(k,S),()=>{w.removeEventListener(k,S)}}},[S,a]),fe.cloneElement(o,g)}function Po(t){return u.generateUtilityClass("MuiSnackbarContent",t)}u.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const qo=t=>{const{classes:o}=t,f={root:["root"],action:["action"],message:["message"]};return u.composeClasses(f,Po,o)},Wo=u.styled(u.Paper,{name:"MuiSnackbarContent",slot:"Root"})(u.memoTheme(({theme:t})=>{const o=t.palette.mode==="light"?.8:.98;return{...t.typography.body2,color:t.vars?t.vars.palette.SnackbarContent.color:t.palette.getContrastText(u.emphasize(t.palette.background.default,o)),backgroundColor:t.vars?t.vars.palette.SnackbarContent.bg:u.emphasize(t.palette.background.default,o),display:"flex",alignItems:"center",flexWrap:"wrap",padding:"6px 16px",flexGrow:1,[t.breakpoints.up("sm")]:{flexGrow:"initial",minWidth:288}}})),zo=u.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),Ho=u.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),Vo=fe.forwardRef(function(o,f){const a=u.useDefaultProps({props:o,name:"MuiSnackbarContent"}),{action:p,className:c,message:l,role:h="alert",...d}=a,m=a,x=qo(m);return n.jsxs(Wo,{role:h,elevation:6,className:u.clsx(x.root,c),ownerState:m,ref:f,...d,children:[n.jsx(zo,{className:x.message,ownerState:m,children:l}),p?n.jsx(Ho,{className:x.action,ownerState:m,children:p}):null]})});function Uo(t){return u.generateUtilityClass("MuiSnackbar",t)}u.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const Bo=t=>{const{classes:o,anchorOrigin:f}=t,a={root:["root",`anchorOrigin${u.capitalize(f.vertical)}${u.capitalize(f.horizontal)}`]};return u.composeClasses(a,Uo,o)},Go=u.styled("div",{name:"MuiSnackbar",slot:"Root",overridesResolver:(t,o)=>{const{ownerState:f}=t;return[o.root,o[`anchorOrigin${u.capitalize(f.anchorOrigin.vertical)}${u.capitalize(f.anchorOrigin.horizontal)}`]]}})(u.memoTheme(({theme:t})=>({zIndex:(t.vars||t).zIndex.snackbar,position:"fixed",display:"flex",left:8,right:8,justifyContent:"center",alignItems:"center",variants:[{props:({ownerState:o})=>o.anchorOrigin.vertical==="top",style:{top:8,[t.breakpoints.up("sm")]:{top:24}}},{props:({ownerState:o})=>o.anchorOrigin.vertical!=="top",style:{bottom:8,[t.breakpoints.up("sm")]:{bottom:24}}},{props:({ownerState:o})=>o.anchorOrigin.horizontal==="left",style:{justifyContent:"flex-start",[t.breakpoints.up("sm")]:{left:24,right:"auto"}}},{props:({ownerState:o})=>o.anchorOrigin.horizontal==="right",style:{justifyContent:"flex-end",[t.breakpoints.up("sm")]:{right:24,left:"auto"}}},{props:({ownerState:o})=>o.anchorOrigin.horizontal==="center",style:{[t.breakpoints.up("sm")]:{left:"50%",right:"auto",transform:"translateX(-50%)"}}}]}))),Yo=fe.forwardRef(function(o,f){const a=u.useDefaultProps({props:o,name:"MuiSnackbar"}),p=u.useTheme(),c={enter:p.transitions.duration.enteringScreen,exit:p.transitions.duration.leavingScreen},{action:l,anchorOrigin:{vertical:h,horizontal:d}={vertical:"bottom",horizontal:"left"},autoHideDuration:m=null,children:x,className:S,ClickAwayListenerProps:b,ContentProps:g,disableWindowBlurListener:k=!1,message:w,onBlur:T,onClose:M,onFocus:D,onMouseEnter:I,onMouseLeave:E,open:L,resumeHideDuration:H,slots:_={},slotProps:G={},TransitionComponent:N,transitionDuration:q=c,TransitionProps:{onEnter:U,onExited:A,...P}={},...Y}=a,K={...a,anchorOrigin:{vertical:h,horizontal:d},autoHideDuration:m,disableWindowBlurListener:k,TransitionComponent:N,transitionDuration:q},X=Bo(K),{getRootProps:J,onClickAway:B}=Ro({...K}),[ne,W]=fe.useState(!0),Q=ye=>{W(!0),A&&A(ye)},R=(ye,Me)=>{W(!1),U&&U(ye,Me)},Z={slots:{transition:N,..._},slotProps:{content:g,clickAwayListener:b,transition:P,...G}},[de,ee]=u.useSlot("root",{ref:f,className:[X.root,S],elementType:Go,getSlotProps:J,externalForwardedProps:{...Z,...Y},ownerState:K}),[ie,{ownerState:ce,...De}]=u.useSlot("clickAwayListener",{elementType:_o,externalForwardedProps:Z,getSlotProps:ye=>({onClickAway:(...Me)=>{const Fe=Me[0];ye.onClickAway?.(...Me),!Fe?.defaultMuiPrevented&&B(...Me)}}),ownerState:K}),[be,ke]=u.useSlot("content",{elementType:Vo,shouldForwardComponentProp:!0,externalForwardedProps:Z,additionalProps:{message:w,action:l},ownerState:K}),[je,Re]=u.useSlot("transition",{elementType:u.Grow,externalForwardedProps:Z,getSlotProps:ye=>({onEnter:(...Me)=>{ye.onEnter?.(...Me),R(...Me)},onExited:(...Me)=>{ye.onExited?.(...Me),Q(...Me)}}),additionalProps:{appear:!0,in:L,timeout:q,direction:h==="top"?"down":"up"},ownerState:K});return!L&&ne?null:n.jsx(ie,{...De,..._.clickAwayListener&&{ownerState:ce},children:n.jsx(de,{...ee,children:n.jsx(je,{...Re,children:x||n.jsx(be,{...ke})})})})});let sr;function Zo(t){sr=t}function Fs(t){if(sr)try{sr(t)}catch{}}function Ke(t,o,f){return(async a=>{const p=Date.now();try{const c=await f(a);return Fs({type:"console.mutation",resource:t,action:o,ok:!0,durationMs:Date.now()-p}),c}catch(c){throw Fs({type:"console.mutation",resource:t,action:o,ok:!1,durationMs:Date.now()-p,reason:c instanceof Error?c.message:"An unknown error occurred"}),c}})}function Dt({mutationFn:t,success:o,invalidates:f,closeDialog:a,resource:p,action:c}){const l=Tn.useQueryClient(),[h,d]=$.useState(""),m=u.useMutationWithApiError({mutationFn:Ke(p,c,t),onSuccess(){a();for(const x of f)l.invalidateQueries({queryKey:x});d(o)},onError(x){d(x instanceof Error?x.message:"An unknown error occurred")}});return{mutate:m.mutate,isPending:m.isPending,notice:n.jsx(Yo,{open:h!=="",autoHideDuration:6e3,onClose:()=>d(""),message:h})}}const ha="https://docs.malloydata.dev/documentation",Gn=`${ha}/user_guides/publishing`,Ct="https://github.com/malloydata/publisher/blob/main/docs",Xe={docsHome:`${ha}/`,publishing:`${Gn}/publishing`,explorer:`${Gn}/explorer`,mcpAgents:`${Gn}/mcp_agents`,surfaces:`${Ct}/choosing-a-surface.md`,dashboards:`${Ct}/dashboards.md`,dataApps:`${Ct}/html-data-apps.md`,givens:`${Ct}/givens.md`,materialization:`${Ct}/materialization.md`,connections:`${Ct}/connections.md`};function Xo({resourceUri:t}){const[o,f]=$.useState(!1),{apiClients:a}=V.useServer(),{environmentName:p}=u.parseResourceUri(t),c=Dt({mutationFn(h){return a.packages.createPackage(p,{name:h.name,description:h.description,location:h.location})},success:"Package created",invalidates:[["packages",p]],closeDialog:()=>f(!1),resource:"package",action:"create"}),l=h=>{h.preventDefault();const d=new FormData(h.currentTarget),m=d.get("name")?.toString(),x=d.get("description")?.toString(),S=d.get("location")?.toString();c.mutate({name:m,description:x,location:S})};return n.jsxs(n.Fragment,{children:[n.jsx(u.AddButton,{label:"Package",onClick:()=>f(!0)}),n.jsx(u.AppDialog,{open:o,onClose:()=>f(!1),title:"New package",description:n.jsxs(n.Fragment,{children:["A package is a directory of Malloy models and their data. Give its location as a GitHub, S3 or GCS URL, or an absolute path the server can read; see the"," ",n.jsx(v.Box,{component:"a",href:Xe.publishing,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary"},children:"package format"}),"."]}),actions:n.jsxs(n.Fragment,{children:[n.jsx(v.Button,{disabled:c.isPending,onClick:()=>f(!1),children:"Cancel"}),n.jsx(v.Button,{type:"submit",form:"package-form",variant:"contained",loading:c.isPending,children:"Create package"})]}),children:n.jsx("form",{onSubmit:l,id:"package-form",children:n.jsxs(v.Stack,{sx:{gap:2},children:[n.jsx(v.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(v.TextField,{id:"description",name:"description",label:"Description",multiline:!0,rows:3,fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(v.TextField,{id:"location",name:"location",label:"Location",type:"text",placeholder:"e.g. s3://my-bucket/my-package.zip",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}})]})})}),c.notice]})}const Ko=u.createSvgIcon(n.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function Mn({icon:t,tint:o,label:f,mono:a,description:p,rightLabel:c,trailingAction:l,onClick:h,ariaLabel:d}){const m=!!h,x=S=>{h&&(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),h(S))};return n.jsxs(v.Box,{onClick:h,onKeyDown:m?x:void 0,role:m?"button":void 0,tabIndex:m?0:void 0,"aria-label":d,sx:S=>({display:"flex",alignItems:"center",gap:1.5,py:1,px:1,mx:-1,cursor:m?"pointer":"default",borderRadius:1.5,transition:"background-color 0.1s","&:hover":m?{backgroundColor:S.palette.mode==="dark"?"rgba(255, 255, 255, 0.08)":"grey.100"}:void 0,"&:focus-visible":m?{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}:void 0}),children:[n.jsx(v.Box,{sx:{width:32,height:32,borderRadius:1,bgcolor:o,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t}),n.jsxs(v.Box,{sx:{flex:1,minWidth:0,display:"flex",alignItems:"baseline",gap:1.5},children:[n.jsx(v.Typography,{variant:"body2",sx:{...a?{fontFamily:V.MONO_FONT_FAMILY}:{},flexShrink:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f}),p&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p})]}),c&&n.jsx(v.Typography,{variant:"caption",color:"text.secondary",sx:{flexShrink:0},children:c}),l&&n.jsx(v.Box,{sx:{flexShrink:0,display:"flex",alignItems:"center"},children:l})]})}const fa=u.createSvgIcon(n.jsx("path",{d:"M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6zM19 4h-3.5l-1-1h-5l-1 1H5v2h14z"})),Qo=u.generateUtilityClasses("MuiBox",["root"]),Jo=u.createTheme(),pe=la.createBox({themeId:u.THEME_ID,defaultTheme:Jo,defaultClassName:Qo.root,generateClassName:u.ClassNameGenerator.generate}),Dn=la.createStack({createStyledComponent:u.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:t=>u.useDefaultProps({props:t,name:"MuiStack"})}),Ns=u.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function el(t){return u.generateUtilityClass("MuiListItemIcon",t)}const As=u.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),tl=t=>{const{alignItems:o,classes:f}=t,a={root:["root",o==="flex-start"&&"alignItemsFlexStart"]};return u.composeClasses(a,el,f)},nl=u.styled("div",{name:"MuiListItemIcon",slot:"Root",overridesResolver:(t,o)=>{const{ownerState:f}=t;return[o.root,f.alignItems==="flex-start"&&o.alignItemsFlexStart]}})(u.memoTheme(({theme:t})=>({minWidth:56,color:(t.vars||t).palette.action.active,flexShrink:0,display:"inline-flex",variants:[{props:{alignItems:"flex-start"},style:{marginTop:8}}]}))),fr=fe.forwardRef(function(o,f){const a=u.useDefaultProps({props:o,name:"MuiListItemIcon"}),{className:p,...c}=a,l=fe.useContext(u.ListContext),h={...a,alignItems:l.alignItems},d=tl(h);return n.jsx(nl,{className:u.clsx(d.root,p),ownerState:h,ref:f,...c})});function rl(t){return u.generateUtilityClass("MuiListItemText",t)}const Mt=u.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),sl=t=>{const{classes:o,inset:f,primary:a,secondary:p,dense:c}=t,l={root:["root",f&&"inset",c&&"dense",a&&p&&"multiline"],primary:["primary"],secondary:["secondary"]};return u.composeClasses(l,rl,o)},al=u.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(t,o)=>{const{ownerState:f}=t;return[{[`& .${Mt.primary}`]:o.primary},{[`& .${Mt.secondary}`]:o.secondary},o.root,f.inset&&o.inset,f.primary&&f.secondary&&o.multiline,f.dense&&o.dense]}})({flex:"1 1 auto",minWidth:0,marginTop:4,marginBottom:4,[`.${u.typographyClasses.root}:where(& .${Mt.primary})`]:{display:"block"},[`.${u.typographyClasses.root}:where(& .${Mt.secondary})`]:{display:"block"},variants:[{props:({ownerState:t})=>t.primary&&t.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:t})=>t.inset,style:{paddingLeft:56}}]}),mr=fe.forwardRef(function(o,f){const a=u.useDefaultProps({props:o,name:"MuiListItemText"}),{children:p,className:c,disableTypography:l=!1,inset:h=!1,primary:d,primaryTypographyProps:m,secondary:x,secondaryTypographyProps:S,slots:b={},slotProps:g={},...k}=a,{dense:w}=fe.useContext(u.ListContext);let T=d??p,M=x;const D={...a,disableTypography:l,inset:h,primary:!!T,secondary:!!M,dense:w},I=sl(D),E={slots:b,slotProps:{primary:m,secondary:S,...g}},[L,H]=u.useSlot("root",{className:u.clsx(I.root,c),elementType:al,externalForwardedProps:{...E,...k},ownerState:D,ref:f}),[_,G]=u.useSlot("primary",{className:I.primary,elementType:u.Typography,externalForwardedProps:E,ownerState:D}),[N,q]=u.useSlot("secondary",{className:I.secondary,elementType:u.Typography,externalForwardedProps:E,ownerState:D});return T!=null&&T.type!==u.Typography&&!l&&(T=n.jsx(_,{variant:w?"body2":"body1",component:G?.variant?void 0:"span",...G,children:T})),M!=null&&M.type!==u.Typography&&!l&&(M=n.jsx(N,{variant:"body2",color:"textSecondary",...q,children:M})),n.jsxs(L,{...H,children:[T,M]})});function il(t){return u.generateUtilityClass("MuiMenuItem",t)}const Wt=u.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),ol=(t,o)=>{const{ownerState:f}=t;return[o.root,f.dense&&o.dense,f.divider&&o.divider,!f.disableGutters&&o.gutters]},ll=t=>{const{disabled:o,dense:f,divider:a,disableGutters:p,selected:c,classes:l}=t,h={root:["root",f&&"dense",o&&"disabled",!p&&"gutters",a&&"divider",c&&"selected"]},d=u.composeClasses(h,il,l);return{...l,...d}},cl=u.styled(u.ButtonBase,{shouldForwardProp:t=>u.rootShouldForwardProp(t)||t==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:ol})(u.memoTheme(({theme:t})=>({...t.typography.body1,display:"flex",justifyContent:"flex-start",alignItems:"center",position:"relative",textDecoration:"none",minHeight:48,paddingTop:6,paddingBottom:6,boxSizing:"border-box",whiteSpace:"nowrap","&:hover":{textDecoration:"none",backgroundColor:(t.vars||t).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},[`&.${Wt.selected}`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,(t.vars||t).palette.action.selectedOpacity),[`&.${Wt.focusVisible}`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,`${(t.vars||t).palette.action.selectedOpacity} + ${(t.vars||t).palette.action.focusOpacity}`)}},[`&.${Wt.selected}:hover`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,`${(t.vars||t).palette.action.selectedOpacity} + ${(t.vars||t).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:t.alpha((t.vars||t).palette.primary.main,(t.vars||t).palette.action.selectedOpacity)}},[`&.${Wt.focusVisible}`]:{backgroundColor:(t.vars||t).palette.action.focus},[`&.${Wt.disabled}`]:{opacity:(t.vars||t).palette.action.disabledOpacity},[`& + .${Ns.root}`]:{marginTop:t.spacing(1),marginBottom:t.spacing(1)},[`& + .${Ns.inset}`]:{marginLeft:52},[`& .${Mt.root}`]:{marginTop:0,marginBottom:0},[`& .${Mt.inset}`]:{paddingLeft:36},[`& .${As.root}`]:{minWidth:36},variants:[{props:({ownerState:o})=>!o.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:o})=>o.divider,style:{borderBottom:`1px solid ${(t.vars||t).palette.divider}`,backgroundClip:"padding-box"}},{props:({ownerState:o})=>!o.dense,style:{[t.breakpoints.up("sm")]:{minHeight:"auto"}}},{props:({ownerState:o})=>o.dense,style:{minHeight:32,paddingTop:4,paddingBottom:4,...t.typography.body2,[`& .${As.root} svg`]:{fontSize:"1.25rem"}}}]}))),ve=fe.forwardRef(function(o,f){const a=u.useDefaultProps({props:o,name:"MuiMenuItem"}),{autoFocus:p=!1,component:c="li",dense:l=!1,divider:h=!1,disableGutters:d=!1,focusVisibleClassName:m,role:x="menuitem",tabIndex:S,className:b,...g}=a,k=fe.useContext(u.ListContext),w=fe.useMemo(()=>({dense:l||k.dense||!1,disableGutters:d}),[k.dense,l,d]),T=fe.useRef(null);u.useEnhancedEffect(()=>{p&&T.current&&T.current.focus()},[p]);const M={...a,dense:w.dense,divider:h,disableGutters:d},D=ll(a),I=u.useForkRef(T,f);let E;return a.disabled||(E=S!==void 0?S:-1),n.jsx(u.ListContext.Provider,{value:w,children:n.jsx(cl,{ref:I,role:x,tabIndex:E,component:c,focusVisibleClassName:u.clsx(D.focusVisible,m),className:u.clsx(D.root,b),...g,ownerState:M,classes:D})})}),Qe={postgres:[{label:"Host",name:"host",type:"text",required:!1},{label:"Port",name:"port",type:"number",required:!1},{label:"Database Name",name:"databaseName",type:"text",required:!1},{label:"User Name",name:"userName",type:"text",required:!1},{label:"Password",name:"password",type:"password",required:!1},{label:"Connection String",name:"connectionString",type:"text",required:!1}],bigquery:[{label:"Project ID",name:"defaultProjectId",type:"text",required:!1},{label:"Billing Project ID",name:"billingProjectId",type:"text",required:!1},{label:"Location",name:"location",type:"text",required:!1},{label:"Service Account Key JSON",name:"serviceAccountKeyJson",type:"text",required:!0},{label:"Maximum Bytes Billed",name:"maximumBytesBilled",type:"text",required:!1},{label:"Query Timeout Milliseconds",name:"queryTimeoutMilliseconds",type:"text",required:!1}],snowflake:[{label:"Account",name:"account",type:"text",required:!0},{label:"Username",name:"username",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!1},{label:"Role",name:"role",type:"text",required:!1},{label:"Warehouse",name:"warehouse",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1},{label:"Schema",name:"schema",type:"text",required:!1},{label:"Response Timeout Milliseconds",name:"responseTimeoutMilliseconds",type:"text",required:!1},{label:"Private Key",name:"privateKey",type:"password",required:!1},{label:"Private Key Passphrase",name:"privateKeyPass",type:"password",required:!1}],trino:[{label:"Server",name:"server",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!1},{label:"Catalog",name:"catalog",type:"text",required:!1},{label:"Schema",name:"schema",type:"text",required:!1},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!1},{label:"Peaka Key",name:"peakaKey",type:"password",required:!1}],databricks:[{label:"Host",name:"host",type:"text",required:!0},{label:"HTTP Path",name:"path",type:"text",required:!0},{label:"Access Token",name:"token",type:"password",required:!1},{label:"OAuth Client ID",name:"oauthClientId",type:"text",required:!1},{label:"OAuth Client Secret",name:"oauthClientSecret",type:"password",required:!1},{label:"Default Catalog",name:"defaultCatalog",type:"text",required:!1},{label:"Default Schema",name:"defaultSchema",type:"text",required:!1}],mysql:[{label:"Host",name:"host",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!0},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!0},{label:"Database",name:"database",type:"text",required:!0}],duckdb:[],motherduck:[{label:"Access Token",name:"accessToken",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1}],ducklake:[],publisher:[]},Qt={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",trino:"trinoConnection",databricks:"databricksConnection",mysql:"mysqlConnection",duckdb:"duckdbConnection",motherduck:"motherduckConnection",ducklake:"ducklakeConnection",publisher:"publisherConnection"},ma=Object.values(V.ConnectionTypeEnum).filter(t=>t!==V.ConnectionTypeEnum.Publisher),ar={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},tn=[{label:"Credential Provider",name:"provider",type:"text",required:!1,selectOptions:[{label:"Access key pair",value:"config"},{label:"Host credential chain",value:"credential_chain"}]},{label:"Access Key ID",name:"accessKeyId",type:"text",required:!1,visibleWhen:{field:"provider",value:"config"}},{label:"Secret Access Key",name:"secretAccessKey",type:"password",required:!1,visibleWhen:{field:"provider",value:"config"}},{label:"Credential Chain",name:"chain",type:"text",required:!1,visibleWhen:{field:"provider",value:"credential_chain"}},{label:"Region",name:"region",type:"text",required:!1},{label:"Endpoint",name:"endpoint",type:"text",required:!1},{label:"Session Token",name:"sessionToken",type:"password",required:!1,visibleWhen:{field:"provider",value:"config"}}],nn=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],ul=[{label:"Auth Type",name:"authType",type:"text",required:!0,selectOptions:[{label:"SAS Token",value:"sas_token"},{label:"Service Principal (SPN)",value:"service_principal"}]},{label:"SAS URL (e.g. https://account.blob.core.windows.net/container/file.parquet?sp=r&st=...)",name:"sasUrl",type:"text",required:!1,visibleWhen:{field:"authType",value:"sas_token"}},{label:"Tenant ID",name:"tenantId",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Client ID",name:"clientId",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Client Secret",name:"clientSecret",type:"password",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Account Name",name:"accountName",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"File URL (e.g. abfss://container/path/file.parquet)",name:"fileUrl",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}}];function wn(t){return t==="postgres"||t==="bigquery"||t==="snowflake"?Qe[t]||[]:t==="s3"?tn:t==="gcs"?nn:t==="azure"?ul:[]}function dl({onSubmit:t,isSubmitting:o}){const[f,a]=$.useState(!1),[p,c]=$.useState("postgres"),[l,h]=$.useState([]),[d,m]=$.useState("postgres"),[x,S]=$.useState("s3"),[b,g]=$.useState("config"),k=()=>{a(!0)},w=()=>{a(!1),h([]),c("postgres"),m("postgres"),S("s3"),g("config")},T=async E=>{E.preventDefault();const L=new FormData(E.currentTarget),H=L.get("name")?.toString(),_=L.get("type")?.toString(),G=Qe[_];if(!H)throw new Error("Name is required");if(!_)throw new Error("Type is required");let N;if(_==="ducklake"){const q={};if(d==="postgres"){const P=Qe.postgres,Y={};if(P.forEach(K=>{const X=L.get(`ducklake_pg_${K.name}`)?.toString();X&&(Y[K.name]=X)}),Object.keys(Y).length===0)throw new Error("DuckLake requires catalog connection");q.postgresConnection=Y}const U=L.get("ducklake_bucketUrl")?.toString();if(!U)throw new Error("DuckLake requires a bucket URL");const A={bucketUrl:U};if(x==="s3"){const P={};if(tn.forEach(Y=>{const K=L.get(`ducklake_s3_${Y.name}`)?.toString();K&&(P[Y.name]=K)}),P.provider==="credential_chain")delete P.accessKeyId,delete P.secretAccessKey,delete P.sessionToken;else{if(delete P.chain,!P.accessKeyId)throw new Error("S3 Access Key ID is required");if(!P.secretAccessKey)throw new Error("S3 Secret Access Key is required")}Object.keys(P).length>0&&(A.s3Connection=P)}else if(x==="gcs"){const P={};if(nn.forEach(Y=>{const K=L.get(`ducklake_gcs_${Y.name}`)?.toString();K&&(P[Y.name]=K)}),!P.keyId)throw new Error("GCS Key ID is required");if(!P.secret)throw new Error("GCS Secret is required");Object.keys(P).length>0&&(A.gcsConnection=P)}N={name:H,type:_,ducklakeConnection:{catalog:q,storage:A}}}else if(_==="duckdb"){if(l.length===0)throw new Error("DuckDB connection must have at least one attached database");const q=l.map((U,A)=>{const P=U.dbType,Y=L.get(`attachedDb_${A}_name`)?.toString();if(!Y)throw new Error(`Attached database at index ${A} must have a name`);const K={name:Y,type:P},X=wn(P);if(X&&X.length>0){const J={};if(X.forEach(ne=>{const W=L.get(`attachedDb_${A}_${ne.name}`)?.toString();W&&(J[ne.name]=W)}),P==="s3"){if(J.provider==="credential_chain")delete J.accessKeyId,delete J.secretAccessKey,delete J.sessionToken;else if(delete J.chain,!J.accessKeyId||!J.secretAccessKey)throw new Error(`Attached database "${Y}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const B=ar[P];B&&(K[B]=J)}return K});N={name:H,type:_,duckdbConnection:{attachedDatabases:q}}}else{const q={};if(G.forEach(U=>{const A=L.get(U.name)?.toString();A&&(q[U.name]=A)}),_==="postgres"){if(!!!q.connectionString?.trim()){const A=["host","port","databaseName","userName","password"];for(const P of A)if(!q[P])throw new Error(`${G.find(Y=>Y.name===P)?.label||P} is required`)}}else if(_==="bigquery"){if(!q.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if(_==="snowflake"){if(!q.account)throw new Error("Account is required");if(!q.username)throw new Error("Username is required");if(!q.warehouse)throw new Error("Warehouse is required");if(!q.password&&!q.privateKey)throw new Error("Either password or private key is required")}else if(_==="trino"){if(!q.server)throw new Error("Server is required");if(!q.user)throw new Error("User is required");if(q.server.trim().startsWith("https://")&&!q.password&&!q.peakaKey)throw new Error("Password is required for HTTPS connections (or use Peaka Key)")}else if(_==="mysql"){const U=["host","port","database","user","password"];for(const A of U)if(!q[A])throw new Error(`${G.find(P=>P.name===A)?.label||A} is required`)}else if(_==="motherduck"){if(!q.accessToken)throw new Error("Access Token is required")}else if(_==="databricks"){if(!q.host)throw new Error("Host is required");if(!q.path)throw new Error("HTTP Path is required");const U=q.oauthClientId&&q.oauthClientSecret;if(!q.token&&!U)throw new Error("Either Access Token or OAuth Client ID + Secret is required")}N={name:H,type:_,[Qt[_]]:q}}await t(N),w()},M=()=>{h([...l,{name:"",dbType:"postgres"}])},D=E=>{h(l.filter((L,H)=>H!==E))},I=(E,L)=>{const H=[...l];H[E]={...H[E],dbType:L},h(H)};return n.jsxs($.Fragment,{children:[n.jsx(u.AddButton,{label:"Connection",onClick:k}),n.jsx(u.AppDialog,{open:f,onClose:w,title:"New connection",description:"Add a connection so packages in this environment can query your database with Malloy.",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:o,onClick:w,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"connection-form",variant:"contained",loading:o,children:"Create connection"})]}),children:n.jsx("form",{onSubmit:T,id:"connection-form",children:n.jsxs(Dn,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small"}),n.jsx(u.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:p,select:!0,onChange:E=>c(E.target.value),children:ma.map(E=>n.jsx(ve,{value:E,children:E},E))}),p==="ducklake"?n.jsxs(pe,{sx:{mt:2},children:[n.jsxs(pe,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),n.jsx(u.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:d,select:!0,onChange:E=>m(E.target.value),children:n.jsx(ve,{value:"postgres",children:"PostgreSQL"})}),d==="postgres"&&n.jsx(n.Fragment,{children:Qe.postgres.map(E=>n.jsx(u.TextField,{id:`ducklake_pg_${E.name}`,name:`ducklake_pg_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small"},`pg_${E.name}`))})]}),n.jsxs(pe,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),n.jsxs(u.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:x,select:!0,onChange:E=>S(E.target.value),children:[n.jsx(ve,{value:"s3",children:"S3"}),n.jsx(ve,{value:"gcs",children:"GCS"})]}),n.jsx(u.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:x==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small"}),x==="s3"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),tn.filter(E=>E.visibleWhen?b===E.visibleWhen.value:!0).map(E=>n.jsx(u.TextField,{id:`ducklake_s3_${E.name}`,name:`ducklake_s3_${E.name}`,label:E.label,type:E.selectOptions?void 0:E.type,fullWidth:!0,size:"small",required:E.required,select:!!E.selectOptions,defaultValue:E.selectOptions?b:void 0,onChange:E.name==="provider"?L=>g(L.target.value):void 0,placeholder:E.name==="region"?"us-east-1":void 0,children:E.selectOptions?.map(L=>n.jsx(ve,{value:L.value,children:L.label},L.value))},`s3_${E.name}`))]}),x==="gcs"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),nn.map(E=>n.jsx(u.TextField,{id:`ducklake_gcs_${E.name}`,name:`ducklake_gcs_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required},`gcs_${E.name}`))]})]})]}):p==="duckdb"?n.jsxs(pe,{sx:{mt:2},children:[n.jsxs(pe,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsx(u.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),n.jsx(u.SecondaryButton,{label:"Database",icon:n.jsx(u.AddIcon,{}),onClick:M,ariaLabel:"Add database"})]}),l.length===0&&n.jsx(u.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),l.map((E,L)=>{const H=wn(E.dbType);return n.jsxs(pe,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsxs(pe,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsxs(u.Typography,{variant:"subtitle2",children:["Database ",L+1]}),n.jsx(u.IconButton,{onClick:()=>D(L),size:"small",color:"error",children:n.jsx(fa,{fontSize:"small"})})]}),n.jsx(u.TextField,{required:!0,id:`attachedDb_${L}_name`,name:`attachedDb_${L}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:E.name}),n.jsx(u.TextField,{id:`attachedDb_${L}_type`,name:`attachedDb_${L}_type`,label:"Database Type",fullWidth:!0,size:"small",value:E.dbType,select:!0,onChange:_=>I(L,_.target.value),children:Object.values(V.AttachedDatabaseTypeEnum).map(_=>n.jsx(ve,{value:_,children:_},_))}),H.filter(_=>_.visibleWhen?(E[_.visibleWhen.field]||H.find(N=>N.name===_.visibleWhen?.field)?.selectOptions?.[0]?.value)===_.visibleWhen.value:!0).map(_=>n.jsx(u.TextField,{id:`attachedDb_${L}_${_.name}`,name:`attachedDb_${L}_${_.name}`,label:_.label,type:_.selectOptions?void 0:_.type,fullWidth:!0,size:"small",required:_.required,select:!!_.selectOptions,defaultValue:_.selectOptions?.[0]?.value,onChange:_.selectOptions?G=>{const N=[...l];N[L]={...N[L],[_.name]:G.target.value},h(N)}:void 0,children:_.selectOptions?.map(G=>n.jsx(ve,{value:G.value,children:G.label},G.value))},_.name))]},L)})]}):Qe[p].map(E=>n.jsx(u.TextField,{id:E.name,name:E.name,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required},E.name))]})})})]})}function hl({connection:t,onCloseDialog:o,isMutating:f,onDelete:a}){const[p,c]=$.useState(!1),l=()=>{c(!0)},h=()=>{c(!1),o()};return n.jsxs($.Fragment,{children:[n.jsxs(ve,{"aria-label":`Delete connection ${t?.name??""}`.trim(),onClick:d=>{d.stopPropagation(),l()},sx:{color:"error.main"},children:[n.jsx(fr,{sx:{color:"inherit"},children:n.jsx(He.Delete,{fontSize:"small"})}),n.jsx(mr,{children:"Delete"})]}),n.jsx(u.AppDialog,{open:p,onClose:h,title:"Delete connection",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{onClick:h,children:"Cancel"}),n.jsx(u.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>a(),loading:f,children:"Delete connection"})]}),children:n.jsxs(u.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:t.name}),"? Packages that query through it stop working, and this cannot be undone."]})})]})}const $s=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function Rs(t){const o=t.duckdbConnection?.attachedDatabases;return!o||o.length===0?[]:o.map(f=>({name:f.name||"",dbType:f.type||"postgres"}))}function Ls(t){const o=t.ducklakeConnection;return o&&o.storage?.gcsConnection?"gcs":"s3"}function fl({connection:t,onSubmit:o,isSubmitting:f,onCloseDialog:a}){const[p,c]=$.useState(!1),[l,h]=$.useState(t.type),d=$.useMemo(()=>new Set(t.withheldFields??[]),[t.withheldFields]),[m,x]=$.useState(()=>Rs(t)),[S,b]=$.useState("postgres"),[g,k]=$.useState(()=>Ls(t)),[w,T]=$.useState(()=>t.ducklakeConnection?.storage?.s3Connection?.provider??"config"),M=()=>{x(Rs(t)),h(t.type),T(t.ducklakeConnection?.storage?.s3Connection?.provider??"config"),b("postgres"),k(Ls(t)),c(!0)},D=()=>{c(!1),a?.()},I=async N=>{N.preventDefault();const q=new FormData(N.currentTarget),U=q.get("name")?.toString(),A=q.get("type")?.toString(),P=Qe[A];if(!U)throw new Error("Name is required");if(!A)throw new Error("Type is required");let Y;if(A==="ducklake"){const K={};if(S==="postgres"){const B=Qe.postgres,ne={};if(B.forEach(W=>{const Q=q.get(`ducklake_pg_${W.name}`)?.toString();Q&&(ne[W.name]=Q)}),Object.keys(ne).length===0)throw new Error("DuckLake requires catalog connection");K.postgresConnection=ne}const X=q.get("ducklake_bucketUrl")?.toString();if(!X)throw new Error("DuckLake requires a bucket URL");const J={bucketUrl:X};if(g==="s3"){const B={};tn.forEach(W=>{const Q=q.get(`ducklake_s3_${W.name}`)?.toString();Q&&(B[W.name]=Q)});const ne=t.ducklakeConnection?.storage?.s3Connection;if(ne&&(!B.provider&&ne.provider&&(B.provider=ne.provider),!B.chain&&ne.chain&&(B.chain=ne.chain),!B.accessKeyId&&ne.accessKeyId&&(B.accessKeyId=ne.accessKeyId)),B.provider==="credential_chain")delete B.accessKeyId,delete B.secretAccessKey,delete B.sessionToken;else if(delete B.chain,!B.accessKeyId)throw new Error("S3 Access Key ID is required");Object.keys(B).length>0&&(J.s3Connection=B)}else if(g==="gcs"){const B={};nn.forEach(W=>{const Q=q.get(`ducklake_gcs_${W.name}`)?.toString();Q&&(B[W.name]=Q)});const ne=t.ducklakeConnection?.storage?.gcsConnection;if(ne&&!B.keyId&&ne.keyId&&(B.keyId=ne.keyId),!B.keyId)throw new Error("GCS Key ID is required");Object.keys(B).length>0&&(J.gcsConnection=B)}Y={name:U,type:A,ducklakeConnection:{catalog:K,storage:J}}}else if(A==="duckdb"){if(m.length===0)throw new Error("DuckDB connection must have at least one attached database");const K=m.map((X,J)=>{const B=X.dbType,ne=q.get(`attachedDb_${J}_name`)?.toString();if(!ne)throw new Error(`Attached database at index ${J} must have a name`);const W={name:ne,type:B},Q=wn(B);if(Q&&Q.length>0){const R={};if(Q.forEach(de=>{const ee=q.get(`attachedDb_${J}_${de.name}`)?.toString();ee&&(R[de.name]=ee)}),B==="s3"){if(R.provider==="credential_chain")delete R.accessKeyId,delete R.secretAccessKey,delete R.sessionToken;else if(delete R.chain,!R.accessKeyId||!R.secretAccessKey)throw new Error(`Attached database "${ne}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const Z=ar[B];Z&&(W[Z]=R)}return W});Y={name:U,type:A,duckdbConnection:{attachedDatabases:K}}}else{const K=t[Qt[A]]||{},X={};if(P.forEach(J=>{const B=q.get(J.name)?.toString(),ne=K[J.name];B?X[J.name]=B:$s.has(J.name)||(B!==void 0?X[J.name]=B:ne&&(X[J.name]=ne))}),A==="postgres"){const J=["host","port","databaseName","userName"],B=d.has("postgresConnection.connectionString");if(!(!!X.connectionString?.trim()||B)){const W=J;for(const Q of W)if(!X[Q])throw new Error(`${P.find(R=>R.name===Q)?.label||Q} is required`)}}else if(A==="snowflake"){if(!X.account)throw new Error("Account is required");if(!X.username)throw new Error("Username is required");if(!X.warehouse)throw new Error("Warehouse is required")}else if(A==="trino"){if(!X.server)throw new Error("Server is required");if(!X.user)throw new Error("User is required")}else if(A==="mysql"){const J=["host","port","database","user"];for(const B of J)if(!X[B])throw new Error(`${P.find(ne=>ne.name===B)?.label||B} is required`)}else if(A==="databricks"){if(!X.host)throw new Error("Host is required");if(!X.path)throw new Error("HTTP Path is required")}Y={name:U,type:A,[Qt[A]]:X}}await o(Y),D()},E=()=>{x([...m,{name:"",dbType:"postgres"}])},L=N=>{x(m.filter((q,U)=>U!==N))},H=(N,q)=>{const U=[...m];U[N]={...U[N],dbType:q},x(U)},_=(N,q)=>{const U=t.duckdbConnection?.attachedDatabases;if(!U||!U[N])return"";const A=U[N],P=ar[A.type||""];return P&&A[P]?A[P][q]??"":""},G=N=>{const q=t.ducklakeConnection;if(!q)return"";if(N.startsWith("pg_")){const U=N.replace("pg_","");return q.catalog?.postgresConnection?.[U]??""}if(N==="bucketUrl")return q.storage?.bucketUrl??"";if(N.startsWith("s3_")){const U=N.replace("s3_","");return q.storage?.s3Connection?.[U]??""}if(N.startsWith("gcs_")){const U=N.replace("gcs_","");return q.storage?.gcsConnection?.[U]??""}return""};return n.jsxs($.Fragment,{children:[n.jsxs(ve,{"aria-label":`Edit connection ${t?.name??""}`.trim(),onClick:N=>{N.preventDefault(),N.stopPropagation(),M()},children:[n.jsx(fr,{children:n.jsx(He.Edit,{fontSize:"small"})}),n.jsx(mr,{children:"Edit"})]}),n.jsx(u.AppDialog,{open:p,onClose:D,title:"Edit connection",description:"Change how packages in this environment reach your database.",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:f,onClick:D,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"connection-form",variant:"contained",loading:f,children:"Save changes"})]}),children:n.jsx("form",{onSubmit:I,id:"connection-form",children:n.jsxs(Dn,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",defaultValue:t.name}),n.jsx(u.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:l,select:!0,onChange:N=>h(N.target.value),children:ma.map(N=>n.jsx(ve,{value:N,children:N},N))}),l==="ducklake"?n.jsxs(pe,{sx:{mt:2},children:[n.jsxs(pe,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),n.jsx(u.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:S,select:!0,onChange:N=>b(N.target.value),children:n.jsx(ve,{value:"postgres",children:"PostgreSQL"})}),S==="postgres"&&n.jsx(n.Fragment,{children:Qe.postgres.map(N=>n.jsx(u.TextField,{id:`ducklake_pg_${N.name}`,name:`ducklake_pg_${N.name}`,label:N.label,type:N.type,fullWidth:!0,size:"small",defaultValue:G(`pg_${N.name}`)},`pg_${N.name}`))})]}),n.jsxs(pe,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),n.jsxs(u.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:g,select:!0,onChange:N=>k(N.target.value),children:[n.jsx(ve,{value:"s3",children:"S3"}),n.jsx(ve,{value:"gcs",children:"GCS"})]}),n.jsx(u.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:g==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small",defaultValue:G("bucketUrl")}),g==="s3"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),tn.filter(N=>N.visibleWhen?w===N.visibleWhen.value:!0).map(N=>n.jsx(u.TextField,{id:`ducklake_s3_${N.name}`,name:`ducklake_s3_${N.name}`,label:N.label,type:N.selectOptions?void 0:N.type,fullWidth:!0,size:"small",required:N.required&&N.name!=="secretAccessKey",select:!!N.selectOptions,defaultValue:N.selectOptions?w:G(`s3_${N.name}`),onChange:N.name==="provider"?q=>T(q.target.value):void 0,placeholder:N.name==="region"?"us-east-1":N.name==="secretAccessKey"&&d.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:N.selectOptions?.map(q=>n.jsx(ve,{value:q.value,children:q.label},q.value))},`s3_${N.name}`))]}),g==="gcs"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),nn.map(N=>n.jsx(u.TextField,{id:`ducklake_gcs_${N.name}`,name:`ducklake_gcs_${N.name}`,label:N.label,type:N.type,fullWidth:!0,size:"small",required:N.required&&N.name!=="secret",defaultValue:G(`gcs_${N.name}`),placeholder:N.name==="secret"&&d.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${N.name}`))]})]})]}):l==="duckdb"?n.jsxs(pe,{sx:{mt:2},children:[n.jsxs(pe,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsx(u.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),n.jsx(u.SecondaryButton,{label:"Database",icon:n.jsx(u.AddIcon,{}),onClick:E,ariaLabel:"Add database"})]}),m.length===0&&n.jsx(u.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),m.map((N,q)=>{const U=wn(N.dbType);return n.jsxs(pe,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsxs(pe,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsxs(u.Typography,{variant:"subtitle2",children:["Database ",q+1]}),n.jsx(u.IconButton,{"aria-label":`Remove attached database ${q+1}`,onClick:()=>L(q),size:"small",color:"error",children:n.jsx(fa,{fontSize:"small"})})]}),n.jsx(u.TextField,{required:!0,id:`attachedDb_${q}_name`,name:`attachedDb_${q}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:N.name}),n.jsx(u.TextField,{id:`attachedDb_${q}_type`,name:`attachedDb_${q}_type`,label:"Database Type",fullWidth:!0,size:"small",value:N.dbType,select:!0,onChange:A=>H(q,A.target.value),children:Object.values(V.AttachedDatabaseTypeEnum).map(A=>n.jsx(ve,{value:A,children:A},A))}),U.filter(A=>A.visibleWhen?(N[A.visibleWhen.field]||_(q,A.visibleWhen.field)||U.find(Y=>Y.name===A.visibleWhen?.field)?.selectOptions?.[0]?.value)===A.visibleWhen.value:!0).map(A=>n.jsx(u.TextField,{id:`attachedDb_${q}_${A.name}`,name:`attachedDb_${q}_${A.name}`,label:A.label,type:A.selectOptions?void 0:A.type,fullWidth:!0,size:"small",required:A.required,select:!!A.selectOptions,defaultValue:_(q,A.name)||A.selectOptions?.[0]?.value,onChange:A.selectOptions?P=>{const Y=[...m];Y[q]={...Y[q],[A.name]:P.target.value},x(Y)}:void 0,children:A.selectOptions?.map(P=>n.jsx(ve,{value:P.value,children:P.label},P.value))},A.name))]},q)})]}):Qe[l].map(N=>{const q=t?.[Qt[l]??""]?.[N.name??""]??"",U=N.type==="password"||$s.has(N.name),A=d.has(`${Qt[l]??""}.${N.name}`);return n.jsx(u.TextField,{id:N.name,name:N.name,label:N.label,type:N.type,fullWidth:!0,size:"small",required:N.required&&!U&&!q,defaultValue:q,placeholder:A?"Leave empty to keep existing":void 0,helperText:U?A?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0},N.name)})]})})})]})}function _s(t,o){return!t||t.type!=="duckdb"?!1:(t.duckdbConnection?.attachedDatabases||[]).some(a=>a.type==="azure"&&a.name===o)}function ml(t){return t.startsWith("gs://")||t.startsWith("s3://")||t.startsWith("https://")||t.startsWith("abfss://")||t.startsWith("az://")}function pa({connectionName:t,resourceUri:o,schema:f,connection:a}){const{apiClients:p}=V.useServer(),{environmentName:c}=u.parseResourceUri(o),[l,h]=$.useState(null),[d,m]=$.useState(f||null),[x,S]=$.useState(!1),{data:b,isError:g,isLoading:k,error:w}=u.useQueryWithApiError({queryKey:["schemas",c,t],queryFn:()=>p.connections.listSchemas(c,t)}),T=b?.data||[];return n.jsxs(v.Grid,{container:!0,spacing:1,children:[!f&&n.jsx(v.Grid,{size:{xs:12,md:4},children:n.jsxs(v.Paper,{sx:{p:1,m:0},children:[n.jsxs(v.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:0},children:[n.jsx(v.Typography,{variant:"overline",fontWeight:"bold",children:"Table Paths"}),n.jsx(v.FormControlLabel,{control:n.jsx(v.Switch,{checked:x,onChange:M=>S(M.target.checked)}),label:"Hidden Schemas"})]}),n.jsx(v.Divider,{sx:{mt:"2px"}}),n.jsxs(v.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[k&&n.jsx(u.Loading,{text:"Loading schemas..."}),g&&n.jsx(u.ApiErrorDisplay,{error:w,context:`${c} > ${t} > Schemas`}),!k&&!g&&T.length===0&&n.jsx(v.Typography,{variant:"body2",children:"No Schemas"}),!k&&!g&&T.length>0&&n.jsx(v.List,{dense:!0,disablePadding:!0,children:T.map(M=>{const D=M.name;if(M.isHidden&&!x)return null;const E=d===D;return n.jsx(v.ListItemButton,{selected:E,onClick:()=>{m(D),h(null)},children:n.jsx(v.ListItemText,{primary:D})},D)})})]})]})}),n.jsx(v.Grid,{size:{xs:12,md:f?6:4},children:d&&n.jsx(v.Paper,{sx:{p:1,m:0},children:n.jsx(gl,{connectionName:t,schemaName:d,onTableSelect:M=>{h(M)},resourceUri:o,connection:a})})}),n.jsx(v.Grid,{size:{xs:12,md:f?6:4},children:d&&l&&n.jsx(pl,{environmentName:c,connectionName:t,schemaName:d,tableResource:l})})]})}function pl({environmentName:t,connectionName:o,schemaName:f,tableResource:a}){const{apiClients:p}=V.useServer(),{data:c,isLoading:l,isError:h,error:d}=u.useQueryWithApiError({queryKey:["connectionTableDetail",t,o,f,a],queryFn:()=>p.connections.getTable(t,o,f,a),enabled:!!f&&!!a}),m={resource:c?.data?.resource??a,columns:c?.data?.columns??[]};return n.jsxs(v.Paper,{sx:{p:1,m:0},children:[h&&n.jsx(u.ApiErrorDisplay,{error:d,context:`${t} > ${o} > ${f} > ${a}`}),!h&&n.jsx(yl,{table:m,loading:l})]})}function yl({table:t,loading:o}){return o?n.jsx(u.Loading,{text:"Loading columns..."}):n.jsxs(n.Fragment,{children:[n.jsxs(v.Typography,{variant:"overline",fontWeight:"bold",sx:{display:"block",wordBreak:"break-all"},children:[t.resource.includes("://")||/\.(parquet|csv|json|tsv|ndjson)$/i.test(t.resource)?"File":"Table",": ",t.resource]}),n.jsx(v.Divider,{}),n.jsx(v.Box,{sx:{mt:"10px",maxHeight:"600px",overflowY:"auto"},children:n.jsx(v.TableContainer,{children:n.jsxs(v.Table,{size:"small",sx:{"& .MuiTableCell-root":{padding:"10px"}},children:[n.jsx(v.TableHead,{children:n.jsxs(v.TableRow,{children:[n.jsx(v.TableCell,{children:"NAME"}),n.jsx(v.TableCell,{children:"TYPE"})]})}),n.jsx(v.TableBody,{children:t.columns?.sort((f,a)=>f.name.localeCompare(a.name))?.map(f=>n.jsxs(v.TableRow,{children:[n.jsx(v.TableCell,{children:f.name}),n.jsx(v.TableCell,{children:f.type})]},f.name))})]})})})]})}function gl({connectionName:t,schemaName:o,onTableSelect:f,resourceUri:a,connection:p}){const{environmentName:c}=u.parseResourceUri(a),{apiClients:l}=V.useServer(),[h,d]=$.useState(""),{data:m,isSuccess:x,isError:S,error:b,isLoading:g}=u.useQueryWithApiError({queryKey:["tablesInSchema",c,t,o],queryFn:()=>l.connections.listTables(c,t,o)}),k=_s(p,o),w=M=>k?M:M.split(".").pop()||M,T=x&&m?.data?m.data.filter(M=>w(M.resource).toLowerCase().includes(h.toLowerCase())).sort((M,D)=>w(M.resource).localeCompare(w(D.resource))):[];return n.jsxs(n.Fragment,{children:[n.jsx(v.Typography,{variant:"overline",fontWeight:"bold",children:ml(o)||_s(p,o)?`Files in ${o}`:`Tables in ${o}`}),n.jsx(v.Divider,{}),n.jsx(v.Box,{sx:{mt:1,mb:1},children:n.jsx(v.TextField,{size:"small",fullWidth:!0,placeholder:"Search tables...",value:h,onChange:M=>d(M.target.value),variant:"outlined"})}),n.jsx(v.Divider,{}),n.jsxs(v.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[g&&n.jsx(u.Loading,{text:"Fetching Tables..."}),S&&n.jsx(u.ApiErrorDisplay,{error:b,context:`${c} > ${t} > ${o}`}),x&&T.length===0&&n.jsx(v.Typography,{variant:"body2",children:"No Tables"}),x&&m?.data&&m.data.length>0&&n.jsx(v.List,{dense:!0,disablePadding:!0,children:T.map(M=>{let D=w(M.resource);return!k&&M.resource.includes("://")&&(D=M.resource.split("/").pop()||M.resource),n.jsx(v.ListItemButton,{onClick:()=>f(M.resource),children:n.jsx(v.ListItemText,{primary:D,secondary:M.columns.length>0?`${M.columns.length} columns`:void 0})},M.resource)})})]})]})}const xl={bigquery:"BigQuery",snowflake:"Snowflake",postgres:"PostgreSQL",mysql:"MySQL",trino:"Trino",databricks:"Databricks",duckdb:"DuckDB",ducklake:"DuckLake",s3:"S3",gcs:"GCS",azure:"Azure"};function bl(t){return t?xl[t]??t:""}function vl({resourceUri:t}){const{apiClients:o,mutable:f}=V.useServer(),a=Tn.useQueryClient(),{environmentName:p}=u.parseResourceUri(t),[c,l]=$.useState(""),[h,d]=$.useState(null),m=u.encodeResourceUri({environmentName:p,connectionName:h}),{data:x,isSuccess:S,isError:b,error:g}=u.useQueryWithApiError({queryKey:["connections",p],queryFn:()=>o.connections.listConnections(p)}),k=u.useMutationWithApiError({mutationFn:Ke("connection","create",I=>o.environments.updateEnvironment(p,{name:p,connections:[...x.data,I]})),onSuccess(){l("Connection added successfully"),a.invalidateQueries({queryKey:["connections",p]})},onError(I){l(I.message)}}),w=u.useMutationWithApiError({mutationFn:Ke("connection","update",I=>o.environments.updateEnvironment(p,{name:p,connections:x.data.map(E=>E.name===I.name?I:E)})),onSuccess(I,E){l(`Connection ${E.name} updated successfully`),a.invalidateQueries({queryKey:["connections",p]})},onError(I){l(I.message)}}),T=u.useMutationWithApiError({mutationFn:Ke("connection","delete",I=>{if(!I.name)throw new Error("Cannot delete a connection with no name");return o.connections.deleteConnection(p,I.name)}),onSuccess(I,E){l(`Connection ${E.name} deleted successfully`),a.invalidateQueries({queryKey:["connections",p]})},onError(I){l(I.message)}}),M=S?[...x.data].sort((I,E)=>(I.name??"").localeCompare(E.name??"")):[],D=k.isPending||w.isPending||T.isPending;return n.jsxs(ze,{title:"Connections",...S?{count:M.length}:{},description:"Database connections available to packages in this environment",...f&&S?{action:n.jsx(dl,{onSubmit:I=>k.mutateAsync(I),isSubmitting:k.isPending})}:{},children:[!S&&!b&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",children:"Fetching Connections..."}),b&&n.jsx(u.ApiErrorDisplay,{error:g,context:`${p} > Connections`}),S&&M.length===0&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),S&&M.length>0&&n.jsx(v.Stack,{children:M.map(I=>n.jsx(Sl,{connection:I,mutable:f,isMutating:D,onOpenExplorer:()=>d(I.name??null),onEdit:E=>w.mutateAsync(E),onDelete:E=>T.mutateAsync(E)},I.name))}),n.jsx(v.Snackbar,{open:c!=="",autoHideDuration:6e3,onClose:()=>l(""),message:c}),n.jsx(u.AppDialog,{open:h!==null,onClose:()=>d(null),maxWidth:"lg",title:`Connection explorer: ${h??""}`,showClose:!0,children:h&&n.jsx(pa,{resourceUri:m,connectionName:h,connection:x?.data?.find(I=>I.name===h)})})]})}function Sl({connection:t,mutable:o,isMutating:f,onOpenExplorer:a,onEdit:p,onDelete:c}){const[l,h]=$.useState(null),d=!!l,m=S=>{S.stopPropagation(),h(S.currentTarget)},x=()=>h(null);return n.jsx(Mn,{icon:n.jsx(Ko,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.connection,label:t.name??"",ariaLabel:t.name??"",description:bl(t.type),onClick:a,...o?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(v.IconButton,{size:"small",onClick:m,"aria-label":`Connection actions for ${t.name??""}`.trim(),children:n.jsx(He.MoreVert,{fontSize:"small"})}),n.jsxs(v.Menu,{anchorEl:l,open:d,onClose:x,onClick:S=>S.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(fl,{connection:t,onSubmit:p,isSubmitting:f,onCloseDialog:x}),n.jsx(hl,{connection:t,onCloseDialog:x,isMutating:f,onDelete:()=>c(t)})]})]})}:{}})}const wl=u.createSvgIcon([n.jsx("path",{d:"M20 2H4c-1 0-2 .9-2 2v3.01c0 .72.43 1.34 1 1.69V20c0 1.1 1.1 2 2 2h14c.9 0 2-.9 2-2V8.7c.57-.35 1-.97 1-1.69V4c0-1.1-1-2-2-2m-1 18H5V9h14zm1-13H4V4h16z"},"0"),n.jsx("path",{d:"M9 12h6v2H9z"},"1")]);function kl({resourceUri:t,onCloseDialog:o}){const[f,a]=$.useState(!1),{apiClients:p}=V.useServer(),c=()=>{a(!0)},l=()=>{a(!1),o()},{environmentName:h,packageName:d}=u.parseResourceUri(t),m=Dt({mutationFn:()=>p.packages.deletePackage(h,d),success:"Package deleted",invalidates:[["packages",h]],closeDialog:l,resource:"package",action:"delete"});return n.jsxs($.Fragment,{children:[n.jsxs(v.MenuItem,{onClick:c,children:[n.jsx(v.ListItemIcon,{children:n.jsx(He.Delete,{fontSize:"small"})}),n.jsx(v.ListItemText,{children:"Delete"})]}),n.jsx(u.AppDialog,{open:f,onClose:l,title:"Delete package",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{onClick:l,children:"Cancel"}),n.jsx(u.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>m.mutate(),loading:m.isPending,children:"Delete package"})]}),children:n.jsxs(u.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:d}),"? The package stops being served and this cannot be undone."]})}),m.notice]})}function Cl({package:t,resourceUri:o,onCloseDialog:f}){const[a,p]=$.useState(!1),{apiClients:c}=V.useServer(),l=()=>{p(!0)},h=()=>{p(!1),f()},{packageName:d,environmentName:m}=u.parseResourceUri(o),x=Dt({mutationFn(b){return c.packages.updatePackage(m,d,{name:d,description:b.description})},success:"Package updated",invalidates:[["packages",m]],closeDialog:h,resource:"package",action:"update"}),S=b=>{b.preventDefault();const k=new FormData(b.currentTarget).get("description")?.toString();x.mutate({description:k})};return n.jsxs($.Fragment,{children:[n.jsxs(v.MenuItem,{onClick:l,children:[n.jsx(v.ListItemIcon,{children:n.jsx(He.Edit,{fontSize:"small"})}),n.jsx(v.ListItemText,{children:"Edit"})]}),n.jsx(u.AppDialog,{open:a,onClose:h,title:"Edit package",description:`What ${t.name} is, for the people who open it.`,actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:x.isPending,onClick:h,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"package-form",variant:"contained",loading:x.isPending,children:"Save changes"})]}),children:n.jsx("form",{onSubmit:S,id:"package-form",children:n.jsxs(v.Stack,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:t.name,InputLabelProps:{shrink:!0}}),n.jsx(u.TextField,{id:"description",name:"description",label:"Description",multiline:!0,fullWidth:!0,rows:4,size:"small",defaultValue:t.description,InputLabelProps:{shrink:!0}})]})})}),x.notice]})}function ya({onSelectPackage:t,resourceUri:o}){const{apiClients:f}=V.useServer(),{environmentName:a}=u.parseResourceUri(o),{data:p,isSuccess:c,isError:l,error:h}=u.useQueryWithApiError({queryKey:["packages",a],queryFn:()=>f.packages.listPackages(a)});if(l)return n.jsx(u.ApiErrorDisplay,{error:h,context:`${a} > Packages`});if(!c)return n.jsx(u.Loading,{text:"Fetching Packages..."});const d=[...p.data].sort((m,x)=>m.name.localeCompare(x.name));return n.jsx(v.Stack,{children:d.map(m=>{const x=u.encodeResourceUri({environmentName:a,packageName:m.name});return n.jsx(Tl,{pkg:m,packageResourceUri:x,onSelectPackage:t},m.name)})})}function Tl({pkg:t,packageResourceUri:o,onSelectPackage:f}){const{mutable:a}=V.useServer(),[p,c]=$.useState(null),l=!!p,h=m=>{m.stopPropagation(),c(m.currentTarget)},d=()=>c(null);return n.jsx(Mn,{icon:n.jsx(wl,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.package,label:t.name,ariaLabel:t.name,...t.description?{description:t.description}:{},onClick:m=>f(t.name,m),...a?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(v.IconButton,{size:"small",onClick:h,"aria-label":`Package actions for ${t.name}`,children:n.jsx(He.MoreVert,{fontSize:"small"})}),n.jsxs(v.Menu,{anchorEl:p,open:l,onClose:d,onClick:m=>m.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(Cl,{package:t,resourceUri:o,onCloseDialog:d}),n.jsx(kl,{resourceUri:o,onCloseDialog:d})]})]})}:{}})}function Ml({onSelectPackage:t,resourceUri:o}){const{apiClients:f,mutable:a}=V.useServer(),{environmentName:p}=u.parseResourceUri(o),c=u.useQueryWithApiError({queryKey:["packages",p],queryFn:()=>f.packages.listPackages(p)});return $.useEffect(()=>{window.scrollTo({top:0,behavior:"auto"})},[]),n.jsxs(v.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[n.jsxs(v.Box,{sx:{mb:4},children:[n.jsx(v.Box,{children:n.jsx(hr,{label:"Publisher",onClick:l=>t("/",l)})}),n.jsx(v.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em",mb:.5},children:p}),n.jsx(v.Typography,{variant:"body2",color:"text.secondary",children:"Manage packages and database connections in this environment. Open a package to explore its models and notebooks."})]}),n.jsx(ze,{title:"Packages",...c.isSuccess?{count:c.data.data.length}:{},description:"Published packages available for use in this environment",...a?{action:n.jsx(Xo,{resourceUri:o})}:{},children:n.jsx(ya,{onSelectPackage:t,resourceUri:o})}),n.jsx(vl,{resourceUri:o}),n.jsx($o,{resourceUri:o})]})}u.dayjs.extend(u.utc);function Yn(t){switch(t){case"Star":return["Equals","Contains"];case"MinMax":return["Equals","Less Than","Greater Than","Between"];case"DateMinMax":return["Equals","Before","After","Between"];case"Retrieval":return["Semantic Search"];case"Boolean":return["Equals"];case"NONE":default:return[]}}function Dl(t){return t==="DateMinMax"}function Zn(t){return t==="Between"}function jl({spec:t,values:o,selection:f,onChange:a,retrievalFn:p}){const c=()=>f?.matchType?f.matchType:t.defaultMatchType?t.defaultMatchType:t.filterType==="DateMinMax"?"Between":Yn(t.filterType)[0]||"Equals",[l,h]=$.useState(c()),[d,m]=$.useState(f?.value??""),[x,S]=$.useState(f?.value2??""),[b,g]=$.useState([]),[k,w]=$.useState(!1),[T,M]=$.useState(""),[D,I]=$.useState(!1),[E,L]=$.useState(!1),H=$.useRef(null),_=$.useRef(0),[G,N]=$.useState(!1);$.useEffect(()=>{if(t.filterType!=="Retrieval"||!p)return;const W=T.trim();if(W.length<=2){g([]),I(!1);return}return H.current&&clearTimeout(H.current),H.current=setTimeout(async()=>{_.current+=1;const Q=_.current;w(!0);try{const R=await p(W,t);Q===_.current&&g(R)}catch(R){Q===_.current&&(console.error("Retrieval failed",R),g([]))}finally{Q===_.current&&(w(!1),I(!0))}},500),()=>{H.current&&clearTimeout(H.current)}},[T,t,p]),$.useEffect(()=>{f===null?(m(""),S(""),h(t.defaultMatchType??(t.filterType==="DateMinMax"?"Between":Yn(t.filterType)[0]||"Equals"))):f&&(h(f.matchType),m(f.value??""),S(f.value2??""))},[f,t.filterType,t.defaultMatchType]);const q=Yn(t.filterType),U=Dl(t.filterType),A=Zn(l),P=U&&o.length>=2&&o[0].value instanceof Date?u.dayjs.utc(o[0].value):void 0,Y=U&&o.length>=2&&o[1].value instanceof Date?u.dayjs.utc(o[1].value):void 0,K=t.filterType==="MinMax"&&o.length>=2&&typeof o[0].value=="number"?o[0].value:void 0,X=t.filterType==="MinMax"&&o.length>=2&&typeof o[1].value=="number"?o[1].value:void 0;if(q.length===0)return null;const J=W=>{const Q=W.target.value;h(Q),Zn(Q)||S(""),d&&a({dimensionName:t.dimensionName,source:t.source,filterName:t.filterName,matchType:Q,value:d,...Zn(Q)&&x&&{value2:x}})},B=(W,Q)=>{m(W??""),Q!==void 0&&S(Q??"");const R=Array.isArray(W)&&W.length===0;a(!R&&W!==""&&W!==null&&W!==void 0?{dimensionName:t.dimensionName,source:t.source,filterName:t.filterName,matchType:l,value:W,...A&&Q&&{value2:Q}}:null)},ne=()=>{m(""),S(""),a(null)};return n.jsxs(pe,{sx:{display:"flex",flexDirection:"column",gap:1.5,fontSize:"0.75rem","& .MuiInputBase-root":{fontSize:"0.75rem"},"& .MuiInputBase-input":{padding:"6px 10px"},"& .MuiSelect-select":{padding:"6px 10px !important"},"& .MuiAutocomplete-input":{padding:"0 !important"},"& .MuiAutocomplete-root .MuiInputBase-root":{padding:"5px 10px",minHeight:"29.5px",boxSizing:"border-box",flexWrap:"wrap"},"& .MuiChip-root":{height:"16px",margin:"0 2px 0 0"},"& .MuiChip-label":{fontSize:"0.7rem",padding:"0 6px"},"& .MuiChip-deleteIcon":{fontSize:"14px",margin:"0 2px 0 -4px"},"& .MuiInputLabel-root":{fontSize:"0.75rem",transform:"translate(10px, 6px) scale(1)"},"& .MuiInputLabel-shrink":{fontSize:"0.85rem",transform:"translate(14px, -9px) scale(0.75)"},"& .MuiOutlinedInput-notchedOutline legend":{fontSize:"0.65rem"},"& .MuiFormHelperText-root":{fontSize:"0.65rem",marginTop:"2px"},"& .MuiSvgIcon-root":{fontSize:"1.25rem"}},children:[n.jsxs(pe,{sx:{fontWeight:600,color:t.required&&!f?"error.main":"text.primary"},children:[t.label??t.dimensionName,t.required&&n.jsx(pe,{component:"span",sx:{color:f?"text.secondary":"error.main",fontWeight:400,fontSize:"0.7rem",ml:.5},children:"(required)"})]}),t.filterType!=="Boolean"&&!t.defaultMatchType&&q.length>1&&n.jsxs(u.FormControl,{size:"small",fullWidth:!0,children:[n.jsx(u.InputLabel,{children:"Match Type"}),n.jsx(u.Select,{value:l,label:"Match Type",onChange:J,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:q.map(W=>n.jsx(ve,{value:W,children:W},W))})]}),t.filterType==="Star"&&l==="Equals"&&n.jsx(u.Autocomplete,{multiple:!0,size:"small",options:o,getOptionLabel:W=>typeof W=="string"?W:typeof W=="object"&&W!==null&&"value"in W?String(W.value):String(W),value:Array.isArray(d)?d.map(W=>o.find(Q=>Q.value===W)||W):d?[o.find(W=>W.value===d)||d]:[],onChange:(W,Q)=>{const R=Q.map(Z=>typeof Z=="string"?Z:Z&&typeof Z=="object"&&"value"in Z?Z.value:Z);B(R)},noOptionsText:"No matches found",renderInput:W=>n.jsx(u.TextField,{...W,size:"small",label:"Values",placeholder:"Select values..."}),freeSolo:!t.values||t.values.length===0,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),t.filterType==="Star"&&l==="Contains"&&n.jsx(u.TextField,{size:"small",label:"Search Text",value:d,onChange:W=>m(W.target.value),onBlur:()=>B(d),onKeyDown:W=>{W.key==="Enter"&&B(d)},placeholder:"Enter text to search...",fullWidth:!0}),t.filterType==="Boolean"&&n.jsxs(u.FormControl,{size:"small",fullWidth:!0,children:[n.jsx(u.InputLabel,{children:"Value"}),n.jsxs(u.Select,{value:d===!0?"true":d===!1?"false":"",label:"Value",onChange:W=>{const Q=W.target.value;Q==="true"?B(!0):Q==="false"?B(!1):ne()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[n.jsx(ve,{value:"",children:n.jsx("em",{children:"Blank"})}),n.jsx(ve,{value:"true",children:"True"}),n.jsx(ve,{value:"false",children:"False"})]})]}),t.filterType==="Retrieval"&&l==="Semantic Search"&&n.jsx(u.Autocomplete,{multiple:!0,size:"small",options:b,loading:k,getOptionLabel:W=>typeof W=="string"?W:typeof W=="object"&&W!==null&&"value"in W?String(W.value):String(W),value:Array.isArray(d)?d.map(W=>b.find(R=>R.value===W)||{value:W}):d?[{value:d}]:[],onInputChange:(W,Q)=>{M(Q)},onChange:(W,Q)=>{const R=Q.map(Z=>typeof Z=="string"?Z:Z&&typeof Z=="object"&&"value"in Z?Z.value:Z);B(R)},noOptionsText:T.trim().length<=2?"Type at least 3 characters to search":"No matches found",renderInput:W=>n.jsx(u.TextField,{...W,size:"small",label:"Search Values",placeholder:"Type to search...",onFocus:()=>L(!0),onBlur:()=>L(!1),helperText:E&&!k&&D&&b.length===0?"No matches found":void 0,InputProps:{...W.InputProps,endAdornment:n.jsxs(n.Fragment,{children:[k?n.jsx(u.CircularProgress,{color:"inherit",size:20}):null,W.InputProps.endAdornment]})}}),freeSolo:!0,filterOptions:W=>W,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),t.filterType==="MinMax"&&!A&&n.jsx(u.TextField,{size:"small",type:"number",label:"Value",value:d,onChange:W=>B(parseFloat(W.target.value)||""),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:K,max:X},helperText:G&&K!==void 0&&X!==void 0?`Valid range: [${K} - ${X}]`:void 0}),t.filterType==="MinMax"&&A&&n.jsxs(pe,{sx:{display:"flex",flexDirection:"column",gap:1},children:[n.jsxs(pe,{sx:{display:"flex",gap:1,alignItems:"center"},children:[n.jsx(u.TextField,{size:"small",type:"number",label:"From",value:d,onChange:W=>B(parseFloat(W.target.value)||"",x),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:K,max:x||X}}),n.jsx(pe,{children:"to"}),n.jsx(u.TextField,{size:"small",type:"number",label:"To",value:x,onChange:W=>B(d,parseFloat(W.target.value)||""),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:d||K,max:X}})]}),G&&K!==void 0&&X!==void 0&&n.jsxs(u.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",K," - ",X,"]"]})]}),U&&!A&&n.jsx(u.LocalizationProvider,{dateAdapter:u.AdapterDayjs,children:n.jsx(u.DatePicker,{label:"Date",value:d instanceof Date?u.dayjs.utc(d):null,onChange:W=>{W===null?B(null):W.isValid()&&B(W.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?void 0:P,maxDate:d instanceof Date?void 0:Y,referenceDate:l==="After"&&P?P:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>N(!0),onBlur:()=>N(!1),helperText:G&&P&&Y?`Valid range: [${P.format("YYYY-MM-DD")} - ${Y.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),U&&A&&n.jsx(u.LocalizationProvider,{dateAdapter:u.AdapterDayjs,children:n.jsxs(pe,{sx:{display:"flex",flexDirection:"column",gap:1},children:[n.jsxs(pe,{sx:{display:"flex",gap:1,alignItems:"center"},children:[n.jsx(pe,{sx:{flex:1,minWidth:0},children:n.jsx(u.DatePicker,{label:"From",value:d instanceof Date?u.dayjs.utc(d):null,onChange:W=>{W===null?B(null,x):W.isValid()&&B(W.utc().toDate(),x)},timezone:"UTC",minDate:d instanceof Date?void 0:P,maxDate:x instanceof Date?u.dayjs.utc(x):d instanceof Date?void 0:Y,referenceDate:P,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>N(!0),onBlur:()=>N(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),n.jsx(pe,{children:"to"}),n.jsx(pe,{sx:{flex:1,minWidth:0},children:n.jsx(u.DatePicker,{label:"To",value:x instanceof Date?u.dayjs.utc(x):null,onChange:W=>{W===null?B(d,null):W.isValid()&&B(d,W.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?u.dayjs.utc(d):x instanceof Date?void 0:P,maxDate:x instanceof Date?void 0:Y,referenceDate:d instanceof Date?u.dayjs.utc(d):P,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>N(!0),onBlur:()=>N(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),G&&P&&Y&&n.jsxs(u.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",P.format("YYYY-MM-DD")," -"," ",Y.format("YYYY-MM-DD"),"]"]})]})})]})}function Ol(t){const o=new Set,f=t.schema?.fields;if(!f)return o;for(const a of f)"kind"in a&&a.kind==="join"&&a.name&&o.add(a.name);return o}function El(t){if(!t)return null;for(const o of t)if(o.startsWith("##(filters)")){const f=o.slice(11).trim();try{const a=JSON.parse(f);if(Array.isArray(a)){const p=[];for(const c of a)if(typeof c=="string"){const l=c.indexOf(".");l>0&&l<c.length-1&&p.push({source:c.substring(0,l),dimension:c.substring(l+1)})}if(p.length>0)return{filters:p}}}catch(a){console.error(`Failed to parse "${o}" annotation:`,a)}}return null}function ga(t){if(t.startsWith("#(filter)")){const o=t.slice(9).trim();try{const f=JSON.parse(o);if(f.type)return f}catch(f){console.error(`Failed to parse "${t}" annotation:`,f)}}return null}function Il(t){const o=t.match(/^#\s*label\s*=\s*"([^"]+)"/);return o?o[1]:null}function Fl(t){const o=new Map;let f="";for(const a of t)if(a.type==="code"){if(!f&&a.text){const c=a.text.split(`
2
2
  `).map(l=>l.trim()).find(l=>l.startsWith("import "))?.match(/['"]([^'"\n]+)['"]/);c&&(f=c[1])}if(a.newSources&&a.newSources.length>0)for(const p of a.newSources)try{const c=JSON.parse(p);c.name&&o.set(c.name,c)}catch(c){console.error("Failed to parse SourceInfo:",c)}}return{sourceInfoMap:o,modelPath:f}}function Nl(t,o,f){const a=[];for(const{source:p,dimension:c}of o){const l=t.get(p);if(!l){console.warn(`Source "${p}" not found in notebook sources`),a.push({source:p,model:f,dimensionName:c,filterType:"Star"});continue}const h=l.schema?.fields;if(!h){a.push({source:p,model:f,dimensionName:c,filterType:"Star"});continue}const d=h.find(S=>S.name===c);if(!d){console.warn(`Dimension "${c}" not found in source "${p}"`),a.push({source:p,model:f,dimensionName:c,filterType:"Star"});continue}let m="Star",x;if("annotations"in d&&d.annotations){for(const S of d.annotations)if(S.value){const b=ga(S.value);b&&(m=b.type);const g=Il(S.value);g&&(x=g)}}a.push({source:p,model:f,dimensionName:c,filterType:m,label:x})}return a}function Al(t,o,f){return t.length===0?"":t.map(p=>{const{dimensionName:c,source:l,matchType:h,value:d,value2:m}=p,S=l&&l!==f?`\`${l}\`.\`${c}\``:`\`${c}\``,b=d instanceof Date,g=(k,w=!1)=>k==null?"null":w&&k instanceof Date?`@${k.getFullYear()}-${String(k.getMonth()+1).padStart(2,"0")}-${String(k.getDate()).padStart(2,"0")}`:typeof k=="string"?`'${u.escapeMalloyString(k)}'`:typeof k=="boolean"?k?"true":"false":String(k);switch(h){case"Equals":case"Semantic Search":return Array.isArray(d)&&d.length>0?`(${d.map(w=>`${S} = ${g(w,b)}`).join(" or ")})`:`${S} = ${g(d,b)}`;case"Contains":return typeof d=="string"?`${S} ~ f'%${u.escapeMalloyString(d)}%'`:`${S} = ${g(d)}`;case"After":case"Greater Than":return`${S} > ${g(d,b)}`;case"Before":case"Less Than":return`${S} < ${g(d,b)}`;case"Between":return m!==void 0?`${S} >= ${g(d,b)} and ${S} <= ${g(m,b)}`:`${S} >= ${g(d,b)}`;default:return""}}).filter(p=>p.length>0).join(" and ")}function $l(t){const o=t.match(/run\s*:\s*(\w+)\s*->/);if(o)return o[1];const f=t.match(/^\s*(\w+)\s*->/m);return f?f[1]:null}function Rl(t,o){return`${t.trimEnd()} + {where: ${o}}`}const Ll=u.createSvgIcon(n.jsx("path",{d:"m9.17 6 2 2H20v10H4V6zM10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8z"})),xa=t=>{if(!t)return"Explore semantic models, run queries, and build dashboards";const o=t.replace(/^#+\s+/gm,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/`([^`]+)`/g,"$1").trim(),a=o.split(/\n\s*\n/)[1]||o;if(a.length<=120)return a;const p=a.substring(0,120).split(" ");return p.pop(),p.join(" ")+"..."},ba=(t,o)=>{const f=(t.readme||void 0)?.split(`
3
3
  `)??[];return f.length===0&&(f.push(`# ${t.name}`),f.push("")),(t.readme?.length??0)>0&&o?f.splice(2,1,o):o&&f.push(o),f.join(`
4
4
  `)};function Ps(){const[t,o]=$.useState(!1),{apiClients:f}=V.useServer(),a=()=>{o(!0)},p=()=>{o(!1)},c=Dt({mutationFn(h){return f.environments.createEnvironment({name:h.name,readme:ba({name:h.name,readme:""},h.description)})},success:"Environment created",invalidates:[["environments"]],closeDialog:p,resource:"environment",action:"create"}),l=async h=>{h.preventDefault();const d=new FormData(h.currentTarget),m=d.get("name")?.toString(),x=d.get("description")?.toString();if(!m)throw new Error("Name is required");c.mutate({name:m,description:x})};return n.jsxs($.Fragment,{children:[n.jsx(u.AddButton,{label:"Environment",onClick:a}),n.jsx(u.AppDialog,{open:t,onClose:p,title:"New environment",description:"An environment holds packages and the connections they query through.",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:c.isPending,onClick:p,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"environment-form",variant:"contained",loading:c.isPending,children:"Create environment"})]}),children:n.jsx("form",{onSubmit:l,id:"environment-form",children:n.jsxs(Dn,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(u.TextField,{id:"description",name:"description",label:"Description",placeholder:"Explore semantic models, run queries, and build dashboards",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}})]})})}),c.notice]})}function _l({environment:t,onCloseDialog:o}){const[f,a]=$.useState(!1),{apiClients:p}=V.useServer(),c=()=>{a(!0)},l=()=>{a(!1),o()},h=Dt({mutationFn:()=>p.environments.deleteEnvironment(t.name),success:"Environment deleted",invalidates:[["environments"]],closeDialog:l,resource:"environment",action:"delete"});return n.jsxs($.Fragment,{children:[n.jsxs(v.MenuItem,{onClick:c,children:[n.jsx(v.ListItemIcon,{children:n.jsx(He.Delete,{fontSize:"small"})}),n.jsx(v.ListItemText,{children:"Delete"})]}),n.jsx(u.AppDialog,{open:f,onClose:l,title:"Delete environment",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{onClick:l,children:"Cancel"}),n.jsx(u.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>h.mutate(),loading:h.isPending,children:"Delete environment"})]}),children:n.jsxs(u.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:t.name}),"? Its packages stop being served and this cannot be undone."]})}),h.notice]})}function Pl({environment:t,onCloseDialog:o}){const[f,a]=$.useState(!1),{apiClients:p}=V.useServer(),c=()=>{a(!0)},l=()=>{a(!1),o()},h=Dt({mutationFn(m){return p.environments.updateEnvironment(t.name,{name:t.name,readme:ba({name:t.name,readme:t.readme},m.description)})},success:"Environment updated",invalidates:[["environments"]],closeDialog:l,resource:"environment",action:"update"}),d=m=>{m.preventDefault();const S=new FormData(m.currentTarget).get("description")?.toString();h.mutate({description:S})};return n.jsxs($.Fragment,{children:[n.jsxs(v.MenuItem,{onClick:c,children:[n.jsx(v.ListItemIcon,{children:n.jsx(He.Edit,{fontSize:"small"})}),n.jsx(v.ListItemText,{children:"Edit"})]}),n.jsx(u.AppDialog,{open:f,onClose:l,title:"Edit environment",description:"What this environment is, for the people who open it.",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:h.isPending,onClick:l,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"environment-form",variant:"contained",loading:h.isPending,children:"Save changes"})]}),children:n.jsx("form",{onSubmit:d,id:"environment-form",children:n.jsxs(Dn,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:t.name,InputLabelProps:{shrink:!0}}),n.jsx(u.TextField,{id:"description",name:"description",label:"Description",type:"text",fullWidth:!0,size:"small",defaultValue:xa(t.readme),InputLabelProps:{shrink:!0}})]})})}),h.notice]})}const ql=[{title:"Model",body:"An agent writes what the data means in Malloy — sources, joins, measures — from a warehouse or a file, and validates each edit without a restart.",href:Xe.publishing},{title:"Analyze",body:"Claude, Cursor, Codex or an agent you build asks over MCP; applications and BI tools use REST. Every question runs against the model, never the raw tables.",href:Xe.mcpAgents},{title:"Surface",body:"Dashboards declared in Malloy, notebooks, and no-build HTML data apps, all shipped inside the package, plus this Console for browsing them.",href:Xe.surfaces},{title:"Govern",body:"Runtime parameters, row-level filters and per-source gates are declared in the model, so every surface reads the same rules rather than writing its own.",href:Xe.givens},{title:"Optimize",body:"One annotation materializes an expensive source into a table, and another rolls a measure up to a coarser grain, rebuilt on demand or on a schedule.",href:Xe.materialization},{title:"Run anywhere",body:"DuckDB is built in for CSV, Parquet, JSON and Excel; BigQuery, Snowflake, Postgres, Databricks, MotherDuck and more connect by configuration.",href:Xe.connections}];function Wl({href:t,children:o}){return n.jsx(v.Box,{component:"a",href:t,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary",textDecoration:"underline"},children:o})}function zl({onClickEnvironment:t}){const{apiClients:o,mutable:f}=V.useServer(),{data:a,isSuccess:p,isError:c,error:l}=u.useQueryWithApiError({queryKey:["environments"],queryFn:()=>o.environments.listEnvironments()});if(c)return n.jsx(u.ApiErrorDisplay,{error:l,context:"Environments List"});if(!p)return n.jsx(u.Loading,{text:"Loading environments..."});const h=a.data??[];return n.jsxs(v.Container,{maxWidth:"md",sx:{py:6},children:[n.jsxs(v.Box,{sx:{mb:5},children:[n.jsx(v.Typography,{variant:"h3",component:"h1",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Publisher"}),n.jsx(v.Typography,{variant:"body1",color:"text.secondary",sx:{mb:3},children:"The analytics engine for Malloy."}),n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{maxWidth:720,lineHeight:1.6},children:"One data model, served over MCP and REST to AI agents, applications and BI tools. Write down what your data means — the sources, the joins, the measures, who may see what — and every surface asks the same model, so the same question returns the same numbers tomorrow."})]}),n.jsx(v.Grid,{container:!0,spacing:4,sx:{mb:5},children:ql.map(d=>n.jsx(v.Grid,{size:{xs:12,sm:6},children:n.jsxs(v.Stack,{spacing:1,children:[n.jsx(v.Typography,{variant:"body2",component:"a",href:d.href,target:"_blank",rel:"noopener noreferrer",sx:{fontWeight:500,color:"text.primary",textDecoration:"none","&:hover":{textDecoration:"underline"}},children:d.title}),n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{lineHeight:1.6},children:d.body})]})},d.title))}),n.jsx(v.Divider,{sx:{my:4}}),h.length>0?n.jsx(ze,{title:"Environments",count:h.length,description:"Published environments available on this server",...f?{action:n.jsx(Ps,{})}:{},children:n.jsx(v.Stack,{children:h.map(d=>n.jsx(Hl,{environment:d,...t?{onClickEnvironment:t}:{}},d.name))})}):n.jsxs(v.Box,{sx:{mb:4},children:[n.jsx(v.Typography,{variant:"h5",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Get started"}),n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{mb:3,maxWidth:600},children:"Create your first Malloy environment to start exploring semantic models and building data experiences."}),f?n.jsx(Ps,{}):n.jsx(v.Button,{variant:"contained",color:"primary",href:Xe.publishing,target:"_blank",rel:"noopener noreferrer",children:"Learn how to create models"})]}),n.jsx(v.Divider,{sx:{my:4}}),n.jsxs(v.Typography,{variant:"body2",color:"text.secondary",sx:{maxWidth:720,lineHeight:1.6,mt:2},children:["Join the"," ",n.jsx(Wl,{href:"https://join.slack.com/t/malloy-community/shared_invite/zt-1kgfwgi5g-CrsdaRqs81QY67QW0~t_uw",children:"Malloy Slack community"})," ","to ask questions, share ideas, and contribute."]})]})}function Hl({environment:t,onClickEnvironment:o}){const{mutable:f}=V.useServer(),[a,p]=$.useState(null),c=!!a,l=xa(t.readme),h=m=>{m.stopPropagation(),p(m.currentTarget)},d=()=>p(null);return n.jsx(Mn,{icon:n.jsx(Ll,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.environment,label:t.name??"",ariaLabel:t.name??"",...l?{description:l}:{},...t.name&&o?{onClick:m=>o(`/${t.name}/`,m)}:{},...f?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(v.IconButton,{size:"small",onClick:h,"aria-label":`Environment actions for ${t.name}`,children:n.jsx(He.MoreVert,{fontSize:"small"})}),n.jsxs(v.Menu,{anchorEl:a,open:c,onClose:d,onClick:m=>m.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(Pl,{environment:t,onCloseDialog:d}),n.jsx(_l,{environment:t,onCloseDialog:d})]})]})}:{}})}var ot={},Ee={},zt={},lt={},Xn={},qs;function Vl(){return qs||(qs=1,Object.defineProperty(Xn,"__esModule",{value:!0})),Xn}var Ht={},Vt={},Ws;function dt(){if(Ws)return Vt;Ws=1,Object.defineProperty(Vt,"__esModule",{value:!0}),Vt.CronField=void 0;let t=class va{#e=!1;#n=!1;#a=!1;#s=[];options={rawValue:""};static get min(){throw new Error("min must be overridden")}static get max(){throw new Error("max must be overridden")}static get chars(){return Object.freeze([])}static get validChars(){return/^[?,*\dH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}static get constraints(){return{min:this.min,max:this.max,chars:this.chars,validChars:this.validChars}}constructor(f,a={rawValue:""}){if(!Array.isArray(f))throw new Error(`${this.constructor.name} Validation error, values is not an array`);if(!(f.length>0))throw new Error(`${this.constructor.name} Validation error, values contains no values`);this.options={...a,rawValue:a.rawValue??""},this.#s=f.sort(va.sorter),this.#a=this.options.wildcard!==void 0?this.options.wildcard:this.#r(),this.#e=this.options.rawValue.includes("L")||f.includes("L"),this.#n=this.options.rawValue.includes("?")||f.includes("?")}get min(){return this.constructor.min}get max(){return this.constructor.max}get chars(){return this.constructor.chars}get hasLastChar(){return this.#e}get hasQuestionMarkChar(){return this.#n}get isWildcard(){return this.#a}get values(){return this.#s}static sorter(f,a){const p=typeof f=="number",c=typeof a=="number";return p&&c?f-a:!p&&!c?f.localeCompare(a):p?-1:1}static findNearestValueInList(f,a,p){if(p){for(let c=f.length-1;c>=0;c--)if(f[c]<a)return f[c];return null}for(let c=0;c<f.length;c++)if(f[c]>a)return f[c];return null}findNearestValue(f,a){return this.constructor.findNearestValueInList(this.values,f,a)}serialize(){return{wildcard:this.#a,values:this.#s}}validate(){let f;const a=this.chars.length>0?` or chars ${this.chars.join("")}`:"",p=d=>m=>new RegExp(`^\\d{0,2}${m}$`).test(d),c=d=>(f=d,typeof d=="number"?d>=this.min&&d<=this.max:this.chars.some(p(d)));if(!this.#s.every(c))throw new Error(`${this.constructor.name} Validation error, got value ${f} expected range ${this.min}-${this.max}${a}`);const h=this.#s.find((d,m)=>this.#s.indexOf(d)!==m);if(h)throw new Error(`${this.constructor.name} Validation error, duplicate values found: ${h}`)}#r(){return this.options.rawValue.length>0?["*","?"].includes(this.options.rawValue):Array.from({length:this.max-this.min+1},(f,a)=>a+this.min).every(f=>this.#s.includes(f))}};return Vt.CronField=t,Vt}var zs;function Ul(){if(zs)return Ht;zs=1,Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.CronDayOfMonth=void 0;const t=dt(),o=1,f=31,a=Object.freeze(["L"]);let p=class extends t.CronField{static get min(){return o}static get max(){return f}static get chars(){return a}static get validChars(){return/^[?,*\dLH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(l,h){super(l,h),this.validate()}get values(){return super.values}};return Ht.CronDayOfMonth=p,Ht}var Ut={},Hs;function Bl(){if(Hs)return Ut;Hs=1,Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.CronDayOfWeek=void 0;const t=dt(),o=0,f=7,a=Object.freeze(["L"]);let p=class extends t.CronField{static get min(){return o}static get max(){return f}static get chars(){return a}static get validChars(){return/^[?,*\dLH#/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(l,h){super(l,h),this.validate()}get values(){return super.values}get nthDay(){return this.options.nthDayOfWeek??0}};return Ut.CronDayOfWeek=p,Ut}var Bt={},Vs;function Gl(){if(Vs)return Bt;Vs=1,Object.defineProperty(Bt,"__esModule",{value:!0}),Bt.CronHour=void 0;const t=dt(),o=0,f=23,a=Object.freeze([]);let p=class extends t.CronField{static get min(){return o}static get max(){return f}static get chars(){return a}constructor(l,h){super(l,h),this.validate()}get values(){return super.values}};return Bt.CronHour=p,Bt}var Gt={},Us;function Yl(){if(Us)return Gt;Us=1,Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.CronMinute=void 0;const t=dt(),o=0,f=59,a=Object.freeze([]);let p=class extends t.CronField{static get min(){return o}static get max(){return f}static get chars(){return a}constructor(l,h){super(l,h),this.validate()}get values(){return super.values}};return Gt.CronMinute=p,Gt}var Yt={},Kn={},Oe={},Bs;function Zl(){if(Bs)return Oe;Bs=1,Object.defineProperty(Oe,"__esModule",{value:!0});class t extends Error{}class o extends t{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class f extends t{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class a extends t{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class p extends t{}class c extends t{constructor(e){super(`Invalid unit ${e}`)}}class l extends t{}class h extends t{constructor(){super("Zone is an abstract class")}}const d="numeric",m="short",x="long",S={year:d,month:d,day:d},b={year:d,month:m,day:d},g={year:d,month:m,day:d,weekday:m},k={year:d,month:x,day:d},w={year:d,month:x,day:d,weekday:x},T={hour:d,minute:d},M={hour:d,minute:d,second:d},D={hour:d,minute:d,second:d,timeZoneName:m},I={hour:d,minute:d,second:d,timeZoneName:x},E={hour:d,minute:d,hourCycle:"h23"},L={hour:d,minute:d,second:d,hourCycle:"h23"},H={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:m},_={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:x},G={year:d,month:d,day:d,hour:d,minute:d},N={year:d,month:d,day:d,hour:d,minute:d,second:d},q={year:d,month:m,day:d,hour:d,minute:d},U={year:d,month:m,day:d,hour:d,minute:d,second:d},A={year:d,month:m,day:d,weekday:m,hour:d,minute:d},P={year:d,month:x,day:d,hour:d,minute:d,timeZoneName:m},Y={year:d,month:x,day:d,hour:d,minute:d,second:d,timeZoneName:m},K={year:d,month:x,day:d,weekday:x,hour:d,minute:d,timeZoneName:x},X={year:d,month:x,day:d,weekday:x,hour:d,minute:d,second:d,timeZoneName:x};class J{get type(){throw new h}get name(){throw new h}get ianaName(){return this.name}get isUniversal(){throw new h}offsetName(e,r){throw new h}formatOffset(e,r){throw new h}offset(e){throw new h}equals(e){throw new h}get isValid(){throw new h}}let B=null;class ne extends J{static get instance(){return B===null&&(B=new ne),B}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:i}){return Hr(e,r,i)}formatOffset(e,r){return It(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const W=new Map;function Q(s){let e=W.get(s);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:s,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),W.set(s,e)),e}const R={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Z(s,e){const r=s.format(e).replace(/\u200E/g,""),i=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(r),[,y,C,j,O,F,z,te]=i;return[j,y,C,O,F,z,te]}function de(s,e){const r=s.formatToParts(e),i=[];for(let y=0;y<r.length;y++){const{type:C,value:j}=r[y],O=R[C];C==="era"?i[O]=j:se(O)||(i[O]=parseInt(j,10))}return i}const ee=new Map;class ie extends J{static create(e){let r=ee.get(e);return r===void 0&&ee.set(e,r=new ie(e)),r}static resetCache(){ee.clear(),W.clear()}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=ie.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:i}){return Hr(e,r,i,this.name)}formatOffset(e,r){return It(this.offset(e),r)}offset(e){if(!this.valid)return NaN;const r=new Date(e);if(isNaN(r))return NaN;const i=Q(this.name);let[y,C,j,O,F,z,te]=i.formatToParts?de(i,r):Z(i,r);O==="BC"&&(y=-Math.abs(y)+1);const me=ln({year:y,month:C,day:j,hour:F===24?0:F,minute:z,second:te,millisecond:0});let re=+r;const we=re%1e3;return re-=we>=0?we:1e3+we,(me-re)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let ce={};function De(s,e={}){const r=JSON.stringify([s,e]);let i=ce[r];return i||(i=new Intl.ListFormat(s,e),ce[r]=i),i}const be=new Map;function ke(s,e={}){const r=JSON.stringify([s,e]);let i=be.get(r);return i===void 0&&(i=new Intl.DateTimeFormat(s,e),be.set(r,i)),i}const je=new Map;function Re(s,e={}){const r=JSON.stringify([s,e]);let i=je.get(r);return i===void 0&&(i=new Intl.NumberFormat(s,e),je.set(r,i)),i}const ye=new Map;function Me(s,e={}){const{base:r,...i}=e,y=JSON.stringify([s,i]);let C=ye.get(y);return C===void 0&&(C=new Intl.RelativeTimeFormat(s,e),ye.set(y,C)),C}let Fe=null;function ht(){return Fe||(Fe=new Intl.DateTimeFormat().resolvedOptions().locale,Fe)}const nt=new Map;function Ve(s){let e=nt.get(s);return e===void 0&&(e=new Intl.DateTimeFormat(s).resolvedOptions(),nt.set(s,e)),e}const jt=new Map;function rt(s){let e=jt.get(s);if(!e){const r=new Intl.Locale(s);e="getWeekInfo"in r?r.getWeekInfo():r.weekInfo,"minimalDays"in e||(e={...br,...e}),jt.set(s,e)}return e}function _a(s){const e=s.indexOf("-x-");e!==-1&&(s=s.substring(0,e));const r=s.indexOf("-u-");if(r===-1)return[s];{let i,y;try{i=ke(s).resolvedOptions(),y=s}catch{const F=s.substring(0,r);i=ke(F).resolvedOptions(),y=F}const{numberingSystem:C,calendar:j}=i;return[y,C,j]}}function Pa(s,e,r){return(r||e)&&(s.includes("-u-")||(s+="-u"),r&&(s+=`-ca-${r}`),e&&(s+=`-nu-${e}`)),s}function qa(s){const e=[];for(let r=1;r<=12;r++){const i=ae.utc(2009,r,1);e.push(s(i))}return e}function Wa(s){const e=[];for(let r=1;r<=7;r++){const i=ae.utc(2016,11,13+r);e.push(s(i))}return e}function rn(s,e,r,i){const y=s.listingMode();return y==="error"?null:y==="en"?r(e):i(e)}function za(s){return s.numberingSystem&&s.numberingSystem!=="latn"?!1:s.numberingSystem==="latn"||!s.locale||s.locale.startsWith("en")||Ve(s.locale).numberingSystem==="latn"}class Ha{constructor(e,r,i){this.padTo=i.padTo||0,this.floor=i.floor||!1;const{padTo:y,floor:C,...j}=i;if(!r||Object.keys(j).length>0){const O={useGrouping:!1,...i};i.padTo>0&&(O.minimumIntegerDigits=i.padTo),this.inf=Re(e,O)}}format(e){if(this.inf){const r=this.floor?Math.floor(e):e;return this.inf.format(r)}else{const r=this.floor?Math.floor(e):Rn(e,3);return Se(r,this.padTo)}}}class Va{constructor(e,r,i){this.opts=i,this.originalZone=void 0;let y;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){const j=-1*(e.offset/60),O=j>=0?`Etc/GMT+${j}`:`Etc/GMT${j}`;e.offset!==0&&ie.create(O).valid?(y=O,this.dt=e):(y="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,y=e.zone.name):(y="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);const C={...this.opts};C.timeZone=C.timeZone||y,this.dtf=ke(r,C)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(r=>{if(r.type==="timeZoneName"){const i=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...r,value:i}}else return r}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class Ua{constructor(e,r,i){this.opts={style:"long",...i},!r&&Pr()&&(this.rtf=Me(e,i))}format(e,r){return this.rtf?this.rtf.format(e,r):hi(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}}const br={firstDay:1,minimalDays:4,weekend:[6,7]};class he{static fromOpts(e){return he.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,r,i,y,C=!1){const j=e||ge.defaultLocale,O=j||(C?"en-US":ht()),F=r||ge.defaultNumberingSystem,z=i||ge.defaultOutputCalendar,te=An(y)||ge.defaultWeekSettings;return new he(O,F,z,te,j)}static resetCache(){Fe=null,be.clear(),je.clear(),ye.clear(),nt.clear(),jt.clear()}static fromObject({locale:e,numberingSystem:r,outputCalendar:i,weekSettings:y}={}){return he.create(e,r,i,y)}constructor(e,r,i,y,C){const[j,O,F]=_a(e);this.locale=j,this.numberingSystem=r||O||null,this.outputCalendar=i||F||null,this.weekSettings=y,this.intl=Pa(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=C,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=za(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),r=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&r?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:he.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,An(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,r=!1){return rn(this,e,Br,()=>{const i=this.intl==="ja"||this.intl.startsWith("ja-");r&=!i;const y=r?{month:e,day:"numeric"}:{month:e},C=r?"format":"standalone";if(!this.monthsCache[C][e]){const j=i?O=>this.dtFormatter(O,y).format():O=>this.extract(O,y,"month");this.monthsCache[C][e]=qa(j)}return this.monthsCache[C][e]})}weekdays(e,r=!1){return rn(this,e,Zr,()=>{const i=r?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},y=r?"format":"standalone";return this.weekdaysCache[y][e]||(this.weekdaysCache[y][e]=Wa(C=>this.extract(C,i,"weekday"))),this.weekdaysCache[y][e]})}meridiems(){return rn(this,void 0,()=>Xr,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[ae.utc(2016,11,13,9),ae.utc(2016,11,13,19)].map(r=>this.extract(r,e,"dayperiod"))}return this.meridiemCache})}eras(e){return rn(this,e,Kr,()=>{const r={era:e};return this.eraCache[e]||(this.eraCache[e]=[ae.utc(-40,1,1),ae.utc(2017,1,1)].map(i=>this.extract(i,r,"era"))),this.eraCache[e]})}extract(e,r,i){const y=this.dtFormatter(e,r),C=y.formatToParts(),j=C.find(O=>O.type.toLowerCase()===i);return j?j.value:null}numberFormatter(e={}){return new Ha(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new Va(e,this.intl,r)}relFormatter(e={}){return new Ua(this.intl,this.isEnglish(),e)}listFormatter(e={}){return De(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||Ve(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:qr()?rt(this.locale):br}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let jn=null;class Ce extends J{static get utcInstance(){return jn===null&&(jn=new Ce(0)),jn}static instance(e){return e===0?Ce.utcInstance:new Ce(e)}static parseSpecifier(e){if(e){const r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new Ce(cn(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${It(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${It(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return It(this.fixed,r)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class vr extends J{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function Je(s,e){if(se(s)||s===null)return e;if(s instanceof J)return s;if(Ka(s)){const r=s.toLowerCase();return r==="default"?e:r==="local"||r==="system"?ne.instance:r==="utc"||r==="gmt"?Ce.utcInstance:Ce.parseSpecifier(r)||ie.create(s)}else return et(s)?Ce.instance(s):typeof s=="object"&&"offset"in s&&typeof s.offset=="function"?s:new vr(s)}const On={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},Sr={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Ba=On.hanidec.replace(/[\[|\]]/g,"").split("");function Ga(s){let e=parseInt(s,10);if(isNaN(e)){e="";for(let r=0;r<s.length;r++){const i=s.charCodeAt(r);if(s[r].search(On.hanidec)!==-1)e+=Ba.indexOf(s[r]);else for(const y in Sr){const[C,j]=Sr[y];i>=C&&i<=j&&(e+=i-C)}}return parseInt(e,10)}else return e}const En=new Map;function Ya(){En.clear()}function Le({numberingSystem:s},e=""){const r=s||"latn";let i=En.get(r);i===void 0&&(i=new Map,En.set(r,i));let y=i.get(e);return y===void 0&&(y=new RegExp(`${On[r]}${e}`),i.set(e,y)),y}let wr=()=>Date.now(),kr="system",Cr=null,Tr=null,Mr=null,Dr=60,jr,Or=null;class ge{static get now(){return wr}static set now(e){wr=e}static set defaultZone(e){kr=e}static get defaultZone(){return Je(kr,ne.instance)}static get defaultLocale(){return Cr}static set defaultLocale(e){Cr=e}static get defaultNumberingSystem(){return Tr}static set defaultNumberingSystem(e){Tr=e}static get defaultOutputCalendar(){return Mr}static set defaultOutputCalendar(e){Mr=e}static get defaultWeekSettings(){return Or}static set defaultWeekSettings(e){Or=An(e)}static get twoDigitCutoffYear(){return Dr}static set twoDigitCutoffYear(e){Dr=e%100}static get throwOnInvalid(){return jr}static set throwOnInvalid(e){jr=e}static resetCaches(){he.resetCache(),ie.resetCache(),ae.resetCache(),Ya()}}class _e{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const Er=[0,31,59,90,120,151,181,212,243,273,304,334],Ir=[0,31,60,91,121,152,182,213,244,274,305,335];function Ne(s,e){return new _e("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${s}, which is invalid`)}function In(s,e,r){const i=new Date(Date.UTC(s,e-1,r));s<100&&s>=0&&i.setUTCFullYear(i.getUTCFullYear()-1900);const y=i.getUTCDay();return y===0?7:y}function Fr(s,e,r){return r+(Ot(s)?Ir:Er)[e-1]}function Nr(s,e){const r=Ot(s)?Ir:Er,i=r.findIndex(C=>C<e),y=e-r[i];return{month:i+1,day:y}}function Fn(s,e){return(s-e+7)%7+1}function sn(s,e=4,r=1){const{year:i,month:y,day:C}=s,j=Fr(i,y,C),O=Fn(In(i,y,C),r);let F=Math.floor((j-O+14-e)/7),z;return F<1?(z=i-1,F=Et(z,e,r)):F>Et(i,e,r)?(z=i+1,F=1):z=i,{weekYear:z,weekNumber:F,weekday:O,...dn(s)}}function Ar(s,e=4,r=1){const{weekYear:i,weekNumber:y,weekday:C}=s,j=Fn(In(i,1,e),r),O=mt(i);let F=y*7+C-j-7+e,z;F<1?(z=i-1,F+=mt(z)):F>O?(z=i+1,F-=mt(i)):z=i;const{month:te,day:oe}=Nr(z,F);return{year:z,month:te,day:oe,...dn(s)}}function Nn(s){const{year:e,month:r,day:i}=s,y=Fr(e,r,i);return{year:e,ordinal:y,...dn(s)}}function $r(s){const{year:e,ordinal:r}=s,{month:i,day:y}=Nr(e,r);return{year:e,month:i,day:y,...dn(s)}}function Rr(s,e){if(!se(s.localWeekday)||!se(s.localWeekNumber)||!se(s.localWeekYear)){if(!se(s.weekday)||!se(s.weekNumber)||!se(s.weekYear))throw new p("Cannot mix locale-based week fields with ISO-based week fields");return se(s.localWeekday)||(s.weekday=s.localWeekday),se(s.localWeekNumber)||(s.weekNumber=s.localWeekNumber),se(s.localWeekYear)||(s.weekYear=s.localWeekYear),delete s.localWeekday,delete s.localWeekNumber,delete s.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function Za(s,e=4,r=1){const i=an(s.weekYear),y=Ae(s.weekNumber,1,Et(s.weekYear,e,r)),C=Ae(s.weekday,1,7);return i?y?C?!1:Ne("weekday",s.weekday):Ne("week",s.weekNumber):Ne("weekYear",s.weekYear)}function Xa(s){const e=an(s.year),r=Ae(s.ordinal,1,mt(s.year));return e?r?!1:Ne("ordinal",s.ordinal):Ne("year",s.year)}function Lr(s){const e=an(s.year),r=Ae(s.month,1,12),i=Ae(s.day,1,on(s.year,s.month));return e?r?i?!1:Ne("day",s.day):Ne("month",s.month):Ne("year",s.year)}function _r(s){const{hour:e,minute:r,second:i,millisecond:y}=s,C=Ae(e,0,23)||e===24&&r===0&&i===0&&y===0,j=Ae(r,0,59),O=Ae(i,0,59),F=Ae(y,0,999);return C?j?O?F?!1:Ne("millisecond",y):Ne("second",i):Ne("minute",r):Ne("hour",e)}function se(s){return typeof s>"u"}function et(s){return typeof s=="number"}function an(s){return typeof s=="number"&&s%1===0}function Ka(s){return typeof s=="string"}function Qa(s){return Object.prototype.toString.call(s)==="[object Date]"}function Pr(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function qr(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function Ja(s){return Array.isArray(s)?s:[s]}function Wr(s,e,r){if(s.length!==0)return s.reduce((i,y)=>{const C=[e(y),y];return i&&r(i[0],C[0])===i[0]?i:C},null)[1]}function ei(s,e){return e.reduce((r,i)=>(r[i]=s[i],r),{})}function ft(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function An(s){if(s==null)return null;if(typeof s!="object")throw new l("Week settings must be an object");if(!Ae(s.firstDay,1,7)||!Ae(s.minimalDays,1,7)||!Array.isArray(s.weekend)||s.weekend.some(e=>!Ae(e,1,7)))throw new l("Invalid week settings");return{firstDay:s.firstDay,minimalDays:s.minimalDays,weekend:Array.from(s.weekend)}}function Ae(s,e,r){return an(s)&&s>=e&&s<=r}function ti(s,e){return s-e*Math.floor(s/e)}function Se(s,e=2){const r=s<0;let i;return r?i="-"+(""+-s).padStart(e,"0"):i=(""+s).padStart(e,"0"),i}function tt(s){if(!(se(s)||s===null||s===""))return parseInt(s,10)}function st(s){if(!(se(s)||s===null||s===""))return parseFloat(s)}function $n(s){if(!(se(s)||s===null||s==="")){const e=parseFloat("0."+s)*1e3;return Math.floor(e)}}function Rn(s,e,r="round"){const i=10**e;switch(r){case"expand":return s>0?Math.ceil(s*i)/i:Math.floor(s*i)/i;case"trunc":return Math.trunc(s*i)/i;case"round":return Math.round(s*i)/i;case"floor":return Math.floor(s*i)/i;case"ceil":return Math.ceil(s*i)/i;default:throw new RangeError(`Value rounding ${r} is out of range`)}}function Ot(s){return s%4===0&&(s%100!==0||s%400===0)}function mt(s){return Ot(s)?366:365}function on(s,e){const r=ti(e-1,12)+1,i=s+(e-r)/12;return r===2?Ot(i)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function ln(s){let e=Date.UTC(s.year,s.month-1,s.day,s.hour,s.minute,s.second,s.millisecond);return s.year<100&&s.year>=0&&(e=new Date(e),e.setUTCFullYear(s.year,s.month-1,s.day)),+e}function zr(s,e,r){return-Fn(In(s,1,e),r)+e-1}function Et(s,e=4,r=1){const i=zr(s,e,r),y=zr(s+1,e,r);return(mt(s)-i+y)/7}function Ln(s){return s>99?s:s>ge.twoDigitCutoffYear?1900+s:2e3+s}function Hr(s,e,r,i=null){const y=new Date(s),C={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};i&&(C.timeZone=i);const j={timeZoneName:e,...C},O=new Intl.DateTimeFormat(r,j).formatToParts(y).find(F=>F.type.toLowerCase()==="timezonename");return O?O.value:null}function cn(s,e){let r=parseInt(s,10);Number.isNaN(r)&&(r=0);const i=parseInt(e,10)||0,y=r<0||Object.is(r,-0)?-i:i;return r*60+y}function Vr(s){const e=Number(s);if(typeof s=="boolean"||s===""||!Number.isFinite(e))throw new l(`Invalid unit value ${s}`);return e}function un(s,e){const r={};for(const i in s)if(ft(s,i)){const y=s[i];if(y==null)continue;r[e(i)]=Vr(y)}return r}function It(s,e){const r=Math.trunc(Math.abs(s/60)),i=Math.trunc(Math.abs(s%60)),y=s>=0?"+":"-";switch(e){case"short":return`${y}${Se(r,2)}:${Se(i,2)}`;case"narrow":return`${y}${r}${i>0?`:${i}`:""}`;case"techie":return`${y}${Se(r,2)}${Se(i,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function dn(s){return ei(s,["hour","minute","second","millisecond"])}const ni=["January","February","March","April","May","June","July","August","September","October","November","December"],Ur=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ri=["J","F","M","A","M","J","J","A","S","O","N","D"];function Br(s){switch(s){case"narrow":return[...ri];case"short":return[...Ur];case"long":return[...ni];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}const Gr=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Yr=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],si=["M","T","W","T","F","S","S"];function Zr(s){switch(s){case"narrow":return[...si];case"short":return[...Yr];case"long":return[...Gr];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const Xr=["AM","PM"],ai=["Before Christ","Anno Domini"],ii=["BC","AD"],oi=["B","A"];function Kr(s){switch(s){case"narrow":return[...oi];case"short":return[...ii];case"long":return[...ai];default:return null}}function li(s){return Xr[s.hour<12?0:1]}function ci(s,e){return Zr(e)[s.weekday-1]}function ui(s,e){return Br(e)[s.month-1]}function di(s,e){return Kr(e)[s.year<0?0:1]}function hi(s,e,r="always",i=!1){const y={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},C=["hours","minutes","seconds"].indexOf(s)===-1;if(r==="auto"&&C){const oe=s==="days";switch(e){case 1:return oe?"tomorrow":`next ${y[s][0]}`;case-1:return oe?"yesterday":`last ${y[s][0]}`;case 0:return oe?"today":`this ${y[s][0]}`}}const j=Object.is(e,-0)||e<0,O=Math.abs(e),F=O===1,z=y[s],te=i?F?z[1]:z[2]||z[1]:F?y[s][0]:s;return j?`${O} ${te} ago`:`in ${O} ${te}`}function Qr(s,e){let r="";for(const i of s)i.literal?r+=i.val:r+=e(i.val);return r}const fi={D:S,DD:b,DDD:k,DDDD:w,t:T,tt:M,ttt:D,tttt:I,T:E,TT:L,TTT:H,TTTT:_,f:G,ff:q,fff:P,ffff:K,F:N,FF:U,FFF:Y,FFFF:X};class Te{static create(e,r={}){return new Te(e,r)}static parseFormat(e){let r=null,i="",y=!1;const C=[];for(let j=0;j<e.length;j++){const O=e.charAt(j);O==="'"?((i.length>0||y)&&C.push({literal:y||/^\s+$/.test(i),val:i===""?"'":i}),r=null,i="",y=!y):y||O===r?i+=O:(i.length>0&&C.push({literal:/^\s+$/.test(i),val:i}),i=O,r=O)}return i.length>0&&C.push({literal:y||/^\s+$/.test(i),val:i}),C}static macroTokenToFormatOpts(e){return fi[e]}constructor(e,r){this.opts=r,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,r){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...r}).format()}dtFormatter(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r})}formatDateTime(e,r){return this.dtFormatter(e,r).format()}formatDateTimeParts(e,r){return this.dtFormatter(e,r).formatToParts()}formatInterval(e,r){return this.dtFormatter(e.start,r).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,r){return this.dtFormatter(e,r).resolvedOptions()}num(e,r=0,i=void 0){if(this.opts.forceSimple)return Se(e,r);const y={...this.opts};return r>0&&(y.padTo=r),i&&(y.signDisplay=i),this.loc.numberFormatter(y).format(e)}formatDateTimeFromString(e,r){const i=this.loc.listingMode()==="en",y=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",C=(re,we)=>this.loc.extract(e,re,we),j=re=>e.isOffsetFixed&&e.offset===0&&re.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,re.format):"",O=()=>i?li(e):C({hour:"numeric",hourCycle:"h12"},"dayperiod"),F=(re,we)=>i?ui(e,re):C(we?{month:re}:{month:re,day:"numeric"},"month"),z=(re,we)=>i?ci(e,re):C(we?{weekday:re}:{weekday:re,month:"long",day:"numeric"},"weekday"),te=re=>{const we=Te.macroTokenToFormatOpts(re);return we?this.formatWithSystemDefault(e,we):re},oe=re=>i?di(e,re):C({era:re},"era"),me=re=>{switch(re){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return j({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return j({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return j({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return O();case"d":return y?C({day:"numeric"},"day"):this.num(e.day);case"dd":return y?C({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return z("short",!0);case"cccc":return z("long",!0);case"ccccc":return z("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return z("short",!1);case"EEEE":return z("long",!1);case"EEEEE":return z("narrow",!1);case"L":return y?C({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return y?C({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return F("short",!0);case"LLLL":return F("long",!0);case"LLLLL":return F("narrow",!0);case"M":return y?C({month:"numeric"},"month"):this.num(e.month);case"MM":return y?C({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return F("short",!1);case"MMMM":return F("long",!1);case"MMMMM":return F("narrow",!1);case"y":return y?C({year:"numeric"},"year"):this.num(e.year);case"yy":return y?C({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return y?C({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return y?C({year:"numeric"},"year"):this.num(e.year,6);case"G":return oe("short");case"GG":return oe("long");case"GGGGG":return oe("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return te(re)}};return Qr(Te.parseFormat(r),me)}formatDurationFromString(e,r){const i=this.opts.signMode==="negativeLargestOnly"?-1:1,y=te=>{switch(te[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},C=(te,oe)=>me=>{const re=y(me);if(re){const we=oe.isNegativeDuration&&re!==oe.largestUnit?i:1;let qe;return this.opts.signMode==="negativeLargestOnly"&&re!==oe.largestUnit?qe="never":this.opts.signMode==="all"?qe="always":qe="auto",this.num(te.get(re)*we,me.length,qe)}else return me},j=Te.parseFormat(r),O=j.reduce((te,{literal:oe,val:me})=>oe?te:te.concat(me),[]),F=e.shiftTo(...O.map(y).filter(te=>te)),z={isNegativeDuration:F<0,largestUnit:Object.keys(F.values)[0]};return Qr(j,C(F,z))}}const Jr=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function pt(...s){const e=s.reduce((r,i)=>r+i.source,"");return RegExp(`^${e}$`)}function yt(...s){return e=>s.reduce(([r,i,y],C)=>{const[j,O,F]=C(e,y);return[{...r,...j},O||i,F]},[{},null,1]).slice(0,2)}function gt(s,...e){if(s==null)return[null,null];for(const[r,i]of e){const y=r.exec(s);if(y)return i(y)}return[null,null]}function es(...s){return(e,r)=>{const i={};let y;for(y=0;y<s.length;y++)i[s[y]]=tt(e[r+y]);return[i,null,r+y]}}const ts=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,mi=`(?:${ts.source}?(?:\\[(${Jr.source})\\])?)?`,_n=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,ns=RegExp(`${_n.source}${mi}`),Pn=RegExp(`(?:[Tt]${ns.source})?`),pi=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,yi=/(\d{4})-?W(\d\d)(?:-?(\d))?/,gi=/(\d{4})-?(\d{3})/,xi=es("weekYear","weekNumber","weekDay"),bi=es("year","ordinal"),vi=/(\d{4})-(\d\d)-(\d\d)/,rs=RegExp(`${_n.source} ?(?:${ts.source}|(${Jr.source}))?`),Si=RegExp(`(?: ${rs.source})?`);function xt(s,e,r){const i=s[e];return se(i)?r:tt(i)}function wi(s,e){return[{year:xt(s,e),month:xt(s,e+1,1),day:xt(s,e+2,1)},null,e+3]}function bt(s,e){return[{hours:xt(s,e,0),minutes:xt(s,e+1,0),seconds:xt(s,e+2,0),milliseconds:$n(s[e+3])},null,e+4]}function Ft(s,e){const r=!s[e]&&!s[e+1],i=cn(s[e+1],s[e+2]),y=r?null:Ce.instance(i);return[{},y,e+3]}function Nt(s,e){const r=s[e]?ie.create(s[e]):null;return[{},r,e+1]}const ki=RegExp(`^T?${_n.source}$`),Ci=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function Ti(s){const[e,r,i,y,C,j,O,F,z]=s,te=e[0]==="-",oe=F&&F[0]==="-",me=(re,we=!1)=>re!==void 0&&(we||re&&te)?-re:re;return[{years:me(st(r)),months:me(st(i)),weeks:me(st(y)),days:me(st(C)),hours:me(st(j)),minutes:me(st(O)),seconds:me(st(F),F==="-0"),milliseconds:me($n(z),oe)}]}const Mi={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function qn(s,e,r,i,y,C,j){const O={year:e.length===2?Ln(tt(e)):tt(e),month:Ur.indexOf(r)+1,day:tt(i),hour:tt(y),minute:tt(C)};return j&&(O.second=tt(j)),s&&(O.weekday=s.length>3?Gr.indexOf(s)+1:Yr.indexOf(s)+1),O}const Di=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function ji(s){const[,e,r,i,y,C,j,O,F,z,te,oe]=s,me=qn(e,y,i,r,C,j,O);let re;return F?re=Mi[F]:z?re=0:re=cn(te,oe),[me,new Ce(re)]}function Oi(s){return s.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Ei=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,Ii=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,Fi=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function ss(s){const[,e,r,i,y,C,j,O]=s;return[qn(e,y,i,r,C,j,O),Ce.utcInstance]}function Ni(s){const[,e,r,i,y,C,j,O]=s;return[qn(e,O,r,i,y,C,j),Ce.utcInstance]}const Ai=pt(pi,Pn),$i=pt(yi,Pn),Ri=pt(gi,Pn),Li=pt(ns),as=yt(wi,bt,Ft,Nt),_i=yt(xi,bt,Ft,Nt),Pi=yt(bi,bt,Ft,Nt),qi=yt(bt,Ft,Nt);function Wi(s){return gt(s,[Ai,as],[$i,_i],[Ri,Pi],[Li,qi])}function zi(s){return gt(Oi(s),[Di,ji])}function Hi(s){return gt(s,[Ei,ss],[Ii,ss],[Fi,Ni])}function Vi(s){return gt(s,[Ci,Ti])}const Ui=yt(bt);function Bi(s){return gt(s,[ki,Ui])}const Gi=pt(vi,Si),Yi=pt(rs),Zi=yt(bt,Ft,Nt);function Xi(s){return gt(s,[Gi,as],[Yi,Zi])}const is="Invalid Duration",os={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},Ki={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...os},$e=146097/400,vt=146097/4800,Qi={years:{quarters:4,months:12,weeks:$e/7,days:$e,hours:$e*24,minutes:$e*24*60,seconds:$e*24*60*60,milliseconds:$e*24*60*60*1e3},quarters:{months:3,weeks:$e/28,days:$e/4,hours:$e*24/4,minutes:$e*24*60/4,seconds:$e*24*60*60/4,milliseconds:$e*24*60*60*1e3/4},months:{weeks:vt/7,days:vt,hours:vt*24,minutes:vt*24*60,seconds:vt*24*60*60,milliseconds:vt*24*60*60*1e3},...os},at=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Ji=at.slice(0).reverse();function Ze(s,e,r=!1){const i={values:r?e.values:{...s.values,...e.values||{}},loc:s.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||s.conversionAccuracy,matrix:e.matrix||s.matrix};return new le(i)}function ls(s,e){var r;let i=(r=e.milliseconds)!=null?r:0;for(const y of Ji.slice(1))e[y]&&(i+=e[y]*s[y].milliseconds);return i}function cs(s,e){const r=ls(s,e)<0?-1:1;at.reduceRight((i,y)=>{if(se(e[y]))return i;if(i){const C=e[i]*r,j=s[y][i],O=Math.floor(C/j);e[y]+=O*r,e[i]-=O*j*r}return y},null),at.reduce((i,y)=>{if(se(e[y]))return i;if(i){const C=e[i]%1;e[i]-=C,e[y]+=C*s[i][y]}return y},null)}function us(s){const e={};for(const[r,i]of Object.entries(s))i!==0&&(e[r]=i);return e}class le{constructor(e){const r=e.conversionAccuracy==="longterm"||!1;let i=r?Qi:Ki;e.matrix&&(i=e.matrix),this.values=e.values,this.loc=e.loc||he.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=i,this.isLuxonDuration=!0}static fromMillis(e,r){return le.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new l(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new le({values:un(e,le.normalizeUnit),loc:he.fromObject(r),conversionAccuracy:r.conversionAccuracy,matrix:r.matrix})}static fromDurationLike(e){if(et(e))return le.fromMillis(e);if(le.isDuration(e))return e;if(typeof e=="object")return le.fromObject(e);throw new l(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){const[i]=Vi(e);return i?le.fromObject(i,r):le.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){const[i]=Bi(e);return i?le.fromObject(i,r):le.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new l("need to specify a reason the Duration is invalid");const i=e instanceof _e?e:new _e(e,r);if(ge.throwOnInvalid)throw new a(i);return new le({invalid:i})}static normalizeUnit(e){const r={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!r)throw new c(e);return r}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,r={}){const i={...r,floor:r.round!==!1&&r.floor!==!1};return this.isValid?Te.create(this.loc,i).formatDurationFromString(this,e):is}toHuman(e={}){if(!this.isValid)return is;const r=e.showZeros!==!1,i=at.map(y=>{const C=this.values[y];return se(C)||C===0&&!r?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:y.slice(0,-1)}).format(C)}).filter(y=>y);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(i)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=Rn(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const r=this.toMillis();return r<0||r>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},ae.fromMillis(r,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?ls(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const r=le.fromDurationLike(e),i={};for(const y of at)(ft(r.values,y)||ft(this.values,y))&&(i[y]=r.get(y)+this.get(y));return Ze(this,{values:i},!0)}minus(e){if(!this.isValid)return this;const r=le.fromDurationLike(e);return this.plus(r.negate())}mapUnits(e){if(!this.isValid)return this;const r={};for(const i of Object.keys(this.values))r[i]=Vr(e(this.values[i],i));return Ze(this,{values:r},!0)}get(e){return this[le.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const r={...this.values,...un(e,le.normalizeUnit)};return Ze(this,{values:r})}reconfigure({locale:e,numberingSystem:r,conversionAccuracy:i,matrix:y}={}){const j={loc:this.loc.clone({locale:e,numberingSystem:r}),matrix:y,conversionAccuracy:i};return Ze(this,j)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return cs(this.matrix,e),Ze(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=us(this.normalize().shiftToAll().toObject());return Ze(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(j=>le.normalizeUnit(j));const r={},i={},y=this.toObject();let C;for(const j of at)if(e.indexOf(j)>=0){C=j;let O=0;for(const z in i)O+=this.matrix[z][j]*i[z],i[z]=0;et(y[j])&&(O+=y[j]);const F=Math.trunc(O);r[j]=F,i[j]=(O*1e3-F*1e3)/1e3}else et(y[j])&&(i[j]=y[j]);for(const j in i)i[j]!==0&&(r[C]+=j===C?i[j]:i[j]/this.matrix[C][j]);return cs(this.matrix,r),Ze(this,{values:r},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const e={};for(const r of Object.keys(this.values))e[r]=this.values[r]===0?0:-this.values[r];return Ze(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=us(this.values);return Ze(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function r(i,y){return i===void 0||i===0?y===void 0||y===0:i===y}for(const i of at)if(!r(this.values[i],e.values[i]))return!1;return!0}}const St="Invalid Interval";function eo(s,e){return!s||!s.isValid?xe.invalid("missing or invalid start"):!e||!e.isValid?xe.invalid("missing or invalid end"):e<s?xe.invalid("end before start",`The end of an interval must be after its start, but you had start=${s.toISO()} and end=${e.toISO()}`):null}class xe{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,r=null){if(!e)throw new l("need to specify a reason the Interval is invalid");const i=e instanceof _e?e:new _e(e,r);if(ge.throwOnInvalid)throw new f(i);return new xe({invalid:i})}static fromDateTimes(e,r){const i=Lt(e),y=Lt(r),C=eo(i,y);return C??new xe({start:i,end:y})}static after(e,r){const i=le.fromDurationLike(r),y=Lt(e);return xe.fromDateTimes(y,y.plus(i))}static before(e,r){const i=le.fromDurationLike(r),y=Lt(e);return xe.fromDateTimes(y.minus(i),y)}static fromISO(e,r){const[i,y]=(e||"").split("/",2);if(i&&y){let C,j;try{C=ae.fromISO(i,r),j=C.isValid}catch{j=!1}let O,F;try{O=ae.fromISO(y,r),F=O.isValid}catch{F=!1}if(j&&F)return xe.fromDateTimes(C,O);if(j){const z=le.fromISO(y,r);if(z.isValid)return xe.after(C,z)}else if(F){const z=le.fromISO(i,r);if(z.isValid)return xe.before(O,z)}}return xe.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",r){if(!this.isValid)return NaN;const i=this.start.startOf(e,r);let y;return r!=null&&r.useLocaleWeeks?y=this.end.reconfigure({locale:i.locale}):y=this.end,y=y.startOf(e,r),Math.floor(y.diff(i,e).get(e))+(y.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:r}={}){return this.isValid?xe.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];const r=e.map(Lt).filter(j=>this.contains(j)).sort((j,O)=>j.toMillis()-O.toMillis()),i=[];let{s:y}=this,C=0;for(;y<this.e;){const j=r[C]||this.e,O=+j>+this.e?this.e:j;i.push(xe.fromDateTimes(y,O)),y=O,C+=1}return i}splitBy(e){const r=le.fromDurationLike(e);if(!this.isValid||!r.isValid||r.as("milliseconds")===0)return[];let{s:i}=this,y=1,C;const j=[];for(;i<this.e;){const O=this.start.plus(r.mapUnits(F=>F*y));C=+O>+this.e?this.e:O,j.push(xe.fromDateTimes(i,C)),i=C,y+=1}return j}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const r=this.s>e.s?this.s:e.s,i=this.e<e.e?this.e:e.e;return r>=i?null:xe.fromDateTimes(r,i)}union(e){if(!this.isValid)return this;const r=this.s<e.s?this.s:e.s,i=this.e>e.e?this.e:e.e;return xe.fromDateTimes(r,i)}static merge(e){const[r,i]=e.sort((y,C)=>y.s-C.s).reduce(([y,C],j)=>C?C.overlaps(j)||C.abutsStart(j)?[y,C.union(j)]:[y.concat([C]),j]:[y,j],[[],null]);return i&&r.push(i),r}static xor(e){let r=null,i=0;const y=[],C=e.map(F=>[{time:F.s,type:"s"},{time:F.e,type:"e"}]),j=Array.prototype.concat(...C),O=j.sort((F,z)=>F.time-z.time);for(const F of O)i+=F.type==="s"?1:-1,i===1?r=F.time:(r&&+r!=+F.time&&y.push(xe.fromDateTimes(r,F.time)),r=null);return xe.merge(y)}difference(...e){return xe.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:St}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=S,r={}){return this.isValid?Te.create(this.s.loc.clone(r),e).formatInterval(this):St}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:St}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:St}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:St}toFormat(e,{separator:r=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:St}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):le.invalid(this.invalidReason)}mapEndpoints(e){return xe.fromDateTimes(e(this.s),e(this.e))}}class At{static hasDST(e=ge.defaultZone){const r=ae.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return ie.isValidZone(e)}static normalizeZone(e){return Je(e,ge.defaultZone)}static getStartOfWeek({locale:e=null,locObj:r=null}={}){return(r||he.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:r=null}={}){return(r||he.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:r=null}={}){return(r||he.create(e)).getWeekendDays().slice()}static months(e="long",{locale:r=null,numberingSystem:i=null,locObj:y=null,outputCalendar:C="gregory"}={}){return(y||he.create(r,i,C)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:i=null,locObj:y=null,outputCalendar:C="gregory"}={}){return(y||he.create(r,i,C)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:i=null,locObj:y=null}={}){return(y||he.create(r,i,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:i=null,locObj:y=null}={}){return(y||he.create(r,i,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return he.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return he.create(r,null,"gregory").eras(e)}static features(){return{relative:Pr(),localeWeek:qr()}}}function ds(s,e){const r=y=>y.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),i=r(e)-r(s);return Math.floor(le.fromMillis(i).as("days"))}function to(s,e,r){const i=[["years",(F,z)=>z.year-F.year],["quarters",(F,z)=>z.quarter-F.quarter+(z.year-F.year)*4],["months",(F,z)=>z.month-F.month+(z.year-F.year)*12],["weeks",(F,z)=>{const te=ds(F,z);return(te-te%7)/7}],["days",ds]],y={},C=s;let j,O;for(const[F,z]of i)r.indexOf(F)>=0&&(j=F,y[F]=z(s,e),O=C.plus(y),O>e?(y[F]--,s=C.plus(y),s>e&&(O=s,y[F]--,s=C.plus(y))):s=O);return[s,y,O,j]}function no(s,e,r,i){let[y,C,j,O]=to(s,e,r);const F=e-y,z=r.filter(oe=>["hours","minutes","seconds","milliseconds"].indexOf(oe)>=0);z.length===0&&(j<e&&(j=y.plus({[O]:1})),j!==y&&(C[O]=(C[O]||0)+F/(j-y)));const te=le.fromObject(C,i);return z.length>0?le.fromMillis(F,i).shiftTo(...z).plus(te):te}const ro="missing Intl.DateTimeFormat.formatToParts support";function ue(s,e=r=>r){return{regex:s,deser:([r])=>e(Ga(r))}}const hs="[  ]",fs=new RegExp(hs,"g");function so(s){return s.replace(/\./g,"\\.?").replace(fs,hs)}function ms(s){return s.replace(/\./g,"").replace(fs," ").toLowerCase()}function Pe(s,e){return s===null?null:{regex:RegExp(s.map(so).join("|")),deser:([r])=>s.findIndex(i=>ms(r)===ms(i))+e}}function ps(s,e){return{regex:s,deser:([,r,i])=>cn(r,i),groups:e}}function hn(s){return{regex:s,deser:([e])=>e}}function ao(s){return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function io(s,e){const r=Le(e),i=Le(e,"{2}"),y=Le(e,"{3}"),C=Le(e,"{4}"),j=Le(e,"{6}"),O=Le(e,"{1,2}"),F=Le(e,"{1,3}"),z=Le(e,"{1,6}"),te=Le(e,"{1,9}"),oe=Le(e,"{2,4}"),me=Le(e,"{4,6}"),re=Ue=>({regex:RegExp(ao(Ue.val)),deser:([kt])=>kt,literal:!0}),qe=(Ue=>{if(s.literal)return re(Ue);switch(Ue.val){case"G":return Pe(e.eras("short"),0);case"GG":return Pe(e.eras("long"),0);case"y":return ue(z);case"yy":return ue(oe,Ln);case"yyyy":return ue(C);case"yyyyy":return ue(me);case"yyyyyy":return ue(j);case"M":return ue(O);case"MM":return ue(i);case"MMM":return Pe(e.months("short",!0),1);case"MMMM":return Pe(e.months("long",!0),1);case"L":return ue(O);case"LL":return ue(i);case"LLL":return Pe(e.months("short",!1),1);case"LLLL":return Pe(e.months("long",!1),1);case"d":return ue(O);case"dd":return ue(i);case"o":return ue(F);case"ooo":return ue(y);case"HH":return ue(i);case"H":return ue(O);case"hh":return ue(i);case"h":return ue(O);case"mm":return ue(i);case"m":return ue(O);case"q":return ue(O);case"qq":return ue(i);case"s":return ue(O);case"ss":return ue(i);case"S":return ue(F);case"SSS":return ue(y);case"u":return hn(te);case"uu":return hn(O);case"uuu":return ue(r);case"a":return Pe(e.meridiems(),0);case"kkkk":return ue(C);case"kk":return ue(oe,Ln);case"W":return ue(O);case"WW":return ue(i);case"E":case"c":return ue(r);case"EEE":return Pe(e.weekdays("short",!1),1);case"EEEE":return Pe(e.weekdays("long",!1),1);case"ccc":return Pe(e.weekdays("short",!0),1);case"cccc":return Pe(e.weekdays("long",!0),1);case"Z":case"ZZ":return ps(new RegExp(`([+-]${O.source})(?::(${i.source}))?`),2);case"ZZZ":return ps(new RegExp(`([+-]${O.source})(${i.source})?`),2);case"z":return hn(/[a-z_+-/]{1,256}?/i);case" ":return hn(/[^\S\n\r]/);default:return re(Ue)}})(s)||{invalidReason:ro};return qe.token=s,qe}const oo={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function lo(s,e,r){const{type:i,value:y}=s;if(i==="literal"){const F=/^\s+$/.test(y);return{literal:!F,val:F?" ":y}}const C=e[i];let j=i;i==="hour"&&(e.hour12!=null?j=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?j="hour12":j="hour24":j=r.hour12?"hour12":"hour24");let O=oo[j];if(typeof O=="object"&&(O=O[C]),O)return{literal:!1,val:O}}function co(s){return[`^${s.map(r=>r.regex).reduce((r,i)=>`${r}(${i.source})`,"")}$`,s]}function uo(s,e,r){const i=s.match(e);if(i){const y={};let C=1;for(const j in r)if(ft(r,j)){const O=r[j],F=O.groups?O.groups+1:1;!O.literal&&O.token&&(y[O.token.val[0]]=O.deser(i.slice(C,C+F))),C+=F}return[i,y]}else return[i,{}]}function ho(s){const e=C=>{switch(C){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let r=null,i;return se(s.z)||(r=ie.create(s.z)),se(s.Z)||(r||(r=new Ce(s.Z)),i=s.Z),se(s.q)||(s.M=(s.q-1)*3+1),se(s.h)||(s.h<12&&s.a===1?s.h+=12:s.h===12&&s.a===0&&(s.h=0)),s.G===0&&s.y&&(s.y=-s.y),se(s.u)||(s.S=$n(s.u)),[Object.keys(s).reduce((C,j)=>{const O=e(j);return O&&(C[O]=s[j]),C},{}),r,i]}let Wn=null;function fo(){return Wn||(Wn=ae.fromMillis(1555555555555)),Wn}function mo(s,e){if(s.literal)return s;const r=Te.macroTokenToFormatOpts(s.val),i=bs(r,e);return i==null||i.includes(void 0)?s:i}function ys(s,e){return Array.prototype.concat(...s.map(r=>mo(r,e)))}class gs{constructor(e,r){if(this.locale=e,this.format=r,this.tokens=ys(Te.parseFormat(r),e),this.units=this.tokens.map(i=>io(i,e)),this.disqualifyingUnit=this.units.find(i=>i.invalidReason),!this.disqualifyingUnit){const[i,y]=co(this.units);this.regex=RegExp(i,"i"),this.handlers=y}}explainFromTokens(e){if(this.isValid){const[r,i]=uo(e,this.regex,this.handlers),[y,C,j]=i?ho(i):[null,null,void 0];if(ft(i,"a")&&ft(i,"H"))throw new p("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:r,matches:i,result:y,zone:C,specificOffset:j}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function xs(s,e,r){return new gs(s,r).explainFromTokens(e)}function po(s,e,r){const{result:i,zone:y,specificOffset:C,invalidReason:j}=xs(s,e,r);return[i,y,C,j]}function bs(s,e){if(!s)return null;const i=Te.create(e,s).dtFormatter(fo()),y=i.formatToParts(),C=i.resolvedOptions();return y.map(j=>lo(j,s,C))}const zn="Invalid DateTime",vs=864e13;function $t(s){return new _e("unsupported zone",`the zone "${s.name}" is not supported`)}function Hn(s){return s.weekData===null&&(s.weekData=sn(s.c)),s.weekData}function Vn(s){return s.localWeekData===null&&(s.localWeekData=sn(s.c,s.loc.getMinDaysInFirstWeek(),s.loc.getStartOfWeek())),s.localWeekData}function it(s,e){const r={ts:s.ts,zone:s.zone,c:s.c,o:s.o,loc:s.loc,invalid:s.invalid};return new ae({...r,...e,old:r})}function Ss(s,e,r){let i=s-e*60*1e3;const y=r.offset(i);if(e===y)return[i,e];i-=(y-e)*60*1e3;const C=r.offset(i);return y===C?[i,y]:[s-Math.min(y,C)*60*1e3,Math.max(y,C)]}function fn(s,e){s+=e*60*1e3;const r=new Date(s);return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),second:r.getUTCSeconds(),millisecond:r.getUTCMilliseconds()}}function mn(s,e,r){return Ss(ln(s),e,r)}function ws(s,e){const r=s.o,i=s.c.year+Math.trunc(e.years),y=s.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,C={...s.c,year:i,month:y,day:Math.min(s.c.day,on(i,y))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},j=le.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),O=ln(C);let[F,z]=Ss(O,r,s.zone);return j!==0&&(F+=j,z=s.zone.offset(F)),{ts:F,o:z}}function wt(s,e,r,i,y,C){const{setZone:j,zone:O}=r;if(s&&Object.keys(s).length!==0||e){const F=e||O,z=ae.fromObject(s,{...r,zone:F,specificOffset:C});return j?z:z.setZone(O)}else return ae.invalid(new _e("unparsable",`the input "${y}" can't be parsed as ${i}`))}function pn(s,e,r=!0){return s.isValid?Te.create(he.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(s,e):null}function Un(s,e,r){const i=s.c.year>9999||s.c.year<0;let y="";if(i&&s.c.year>=0&&(y+="+"),y+=Se(s.c.year,i?6:4),r==="year")return y;if(e){if(y+="-",y+=Se(s.c.month),r==="month")return y;y+="-"}else if(y+=Se(s.c.month),r==="month")return y;return y+=Se(s.c.day),y}function ks(s,e,r,i,y,C,j){let O=!r||s.c.millisecond!==0||s.c.second!==0,F="";switch(j){case"day":case"month":case"year":break;default:if(F+=Se(s.c.hour),j==="hour")break;if(e){if(F+=":",F+=Se(s.c.minute),j==="minute")break;O&&(F+=":",F+=Se(s.c.second))}else{if(F+=Se(s.c.minute),j==="minute")break;O&&(F+=Se(s.c.second))}if(j==="second")break;O&&(!i||s.c.millisecond!==0)&&(F+=".",F+=Se(s.c.millisecond,3))}return y&&(s.isOffsetFixed&&s.offset===0&&!C?F+="Z":s.o<0?(F+="-",F+=Se(Math.trunc(-s.o/60)),F+=":",F+=Se(Math.trunc(-s.o%60))):(F+="+",F+=Se(Math.trunc(s.o/60)),F+=":",F+=Se(Math.trunc(s.o%60)))),C&&(F+="["+s.zone.ianaName+"]"),F}const Cs={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},yo={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},go={ordinal:1,hour:0,minute:0,second:0,millisecond:0},yn=["year","month","day","hour","minute","second","millisecond"],xo=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],bo=["year","ordinal","hour","minute","second","millisecond"];function gn(s){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[s.toLowerCase()];if(!e)throw new c(s);return e}function Ts(s){switch(s.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return gn(s)}}function vo(s){if(Rt===void 0&&(Rt=ge.now()),s.type!=="iana")return s.offset(Rt);const e=s.name;let r=Bn.get(e);return r===void 0&&(r=s.offset(Rt),Bn.set(e,r)),r}function Ms(s,e){const r=Je(e.zone,ge.defaultZone);if(!r.isValid)return ae.invalid($t(r));const i=he.fromObject(e);let y,C;if(se(s.year))y=ge.now();else{for(const F of yn)se(s[F])&&(s[F]=Cs[F]);const j=Lr(s)||_r(s);if(j)return ae.invalid(j);const O=vo(r);[y,C]=mn(s,O,r)}return new ae({ts:y,zone:r,loc:i,o:C})}function Ds(s,e,r){const i=se(r.round)?!0:r.round,y=se(r.rounding)?"trunc":r.rounding,C=(O,F)=>(O=Rn(O,i||r.calendary?0:2,r.calendary?"round":y),e.loc.clone(r).relFormatter(r).format(O,F)),j=O=>r.calendary?e.hasSame(s,O)?0:e.startOf(O).diff(s.startOf(O),O).get(O):e.diff(s,O).get(O);if(r.unit)return C(j(r.unit),r.unit);for(const O of r.units){const F=j(O);if(Math.abs(F)>=1)return C(F,O)}return C(s>e?-0:0,r.units[r.units.length-1])}function js(s){let e={},r;return s.length>0&&typeof s[s.length-1]=="object"?(e=s[s.length-1],r=Array.from(s).slice(0,s.length-1)):r=Array.from(s),[e,r]}let Rt;const Bn=new Map;class ae{constructor(e){const r=e.zone||ge.defaultZone;let i=e.invalid||(Number.isNaN(e.ts)?new _e("invalid input"):null)||(r.isValid?null:$t(r));this.ts=se(e.ts)?ge.now():e.ts;let y=null,C=null;if(!i)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(r))[y,C]=[e.old.c,e.old.o];else{const O=et(e.o)&&!e.old?e.o:r.offset(this.ts);y=fn(this.ts,O),i=Number.isNaN(y.year)?new _e("invalid input"):null,y=i?null:y,C=i?null:O}this._zone=r,this.loc=e.loc||he.create(),this.invalid=i,this.weekData=null,this.localWeekData=null,this.c=y,this.o=C,this.isLuxonDateTime=!0}static now(){return new ae({})}static local(){const[e,r]=js(arguments),[i,y,C,j,O,F,z]=r;return Ms({year:i,month:y,day:C,hour:j,minute:O,second:F,millisecond:z},e)}static utc(){const[e,r]=js(arguments),[i,y,C,j,O,F,z]=r;return e.zone=Ce.utcInstance,Ms({year:i,month:y,day:C,hour:j,minute:O,second:F,millisecond:z},e)}static fromJSDate(e,r={}){const i=Qa(e)?e.valueOf():NaN;if(Number.isNaN(i))return ae.invalid("invalid input");const y=Je(r.zone,ge.defaultZone);return y.isValid?new ae({ts:i,zone:y,loc:he.fromObject(r)}):ae.invalid($t(y))}static fromMillis(e,r={}){if(et(e))return e<-vs||e>vs?ae.invalid("Timestamp out of range"):new ae({ts:e,zone:Je(r.zone,ge.defaultZone),loc:he.fromObject(r)});throw new l(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(et(e))return new ae({ts:e*1e3,zone:Je(r.zone,ge.defaultZone),loc:he.fromObject(r)});throw new l("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};const i=Je(r.zone,ge.defaultZone);if(!i.isValid)return ae.invalid($t(i));const y=he.fromObject(r),C=un(e,Ts),{minDaysInFirstWeek:j,startOfWeek:O}=Rr(C,y),F=ge.now(),z=se(r.specificOffset)?i.offset(F):r.specificOffset,te=!se(C.ordinal),oe=!se(C.year),me=!se(C.month)||!se(C.day),re=oe||me,we=C.weekYear||C.weekNumber;if((re||te)&&we)throw new p("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(me&&te)throw new p("Can't mix ordinal dates with month/day");const qe=we||C.weekday&&!re;let Ue,kt,_t=fn(F,z);qe?(Ue=xo,kt=yo,_t=sn(_t,j,O)):te?(Ue=bo,kt=go,_t=Nn(_t)):(Ue=yn,kt=Cs);let Os=!1;for(const qt of Ue){const Mo=C[qt];se(Mo)?Os?C[qt]=kt[qt]:C[qt]=_t[qt]:Os=!0}const wo=qe?Za(C,j,O):te?Xa(C):Lr(C),Es=wo||_r(C);if(Es)return ae.invalid(Es);const ko=qe?Ar(C,j,O):te?$r(C):C,[Co,To]=mn(ko,z,i),Pt=new ae({ts:Co,zone:i,o:To,loc:y});return C.weekday&&re&&e.weekday!==Pt.weekday?ae.invalid("mismatched weekday",`you can't specify both a weekday of ${C.weekday} and a date of ${Pt.toISO()}`):Pt.isValid?Pt:ae.invalid(Pt.invalid)}static fromISO(e,r={}){const[i,y]=Wi(e);return wt(i,y,r,"ISO 8601",e)}static fromRFC2822(e,r={}){const[i,y]=zi(e);return wt(i,y,r,"RFC 2822",e)}static fromHTTP(e,r={}){const[i,y]=Hi(e);return wt(i,y,r,"HTTP",r)}static fromFormat(e,r,i={}){if(se(e)||se(r))throw new l("fromFormat requires an input string and a format");const{locale:y=null,numberingSystem:C=null}=i,j=he.fromOpts({locale:y,numberingSystem:C,defaultToEN:!0}),[O,F,z,te]=po(j,e,r);return te?ae.invalid(te):wt(O,F,i,`format ${r}`,e,z)}static fromString(e,r,i={}){return ae.fromFormat(e,r,i)}static fromSQL(e,r={}){const[i,y]=Xi(e);return wt(i,y,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new l("need to specify a reason the DateTime is invalid");const i=e instanceof _e?e:new _e(e,r);if(ge.throwOnInvalid)throw new o(i);return new ae({invalid:i})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,r={}){const i=bs(e,he.fromObject(r));return i?i.map(y=>y?y.val:null).join(""):null}static expandFormat(e,r={}){return ys(Te.parseFormat(e),he.fromObject(r)).map(y=>y.val).join("")}static resetCache(){Rt=void 0,Bn.clear()}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?Hn(this).weekYear:NaN}get weekNumber(){return this.isValid?Hn(this).weekNumber:NaN}get weekday(){return this.isValid?Hn(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?Vn(this).weekday:NaN}get localWeekNumber(){return this.isValid?Vn(this).weekNumber:NaN}get localWeekYear(){return this.isValid?Vn(this).weekYear:NaN}get ordinal(){return this.isValid?Nn(this.c).ordinal:NaN}get monthShort(){return this.isValid?At.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?At.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?At.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?At.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const e=864e5,r=6e4,i=ln(this.c),y=this.zone.offset(i-e),C=this.zone.offset(i+e),j=this.zone.offset(i-y*r),O=this.zone.offset(i-C*r);if(j===O)return[this];const F=i-j*r,z=i-O*r,te=fn(F,j),oe=fn(z,O);return te.hour===oe.hour&&te.minute===oe.minute&&te.second===oe.second&&te.millisecond===oe.millisecond?[it(this,{ts:F}),it(this,{ts:z})]:[this]}get isInLeapYear(){return Ot(this.year)}get daysInMonth(){return on(this.year,this.month)}get daysInYear(){return this.isValid?mt(this.year):NaN}get weeksInWeekYear(){return this.isValid?Et(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Et(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:r,numberingSystem:i,calendar:y}=Te.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:i,outputCalendar:y}}toUTC(e=0,r={}){return this.setZone(Ce.instance(e),r)}toLocal(){return this.setZone(ge.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:i=!1}={}){if(e=Je(e,ge.defaultZone),e.equals(this.zone))return this;if(e.isValid){let y=this.ts;if(r||i){const C=e.offset(this.ts),j=this.toObject();[y]=mn(j,C,e)}return it(this,{ts:y,zone:e})}else return ae.invalid($t(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:i}={}){const y=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:i});return it(this,{loc:y})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const r=un(e,Ts),{minDaysInFirstWeek:i,startOfWeek:y}=Rr(r,this.loc),C=!se(r.weekYear)||!se(r.weekNumber)||!se(r.weekday),j=!se(r.ordinal),O=!se(r.year),F=!se(r.month)||!se(r.day),z=O||F,te=r.weekYear||r.weekNumber;if((z||j)&&te)throw new p("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(F&&j)throw new p("Can't mix ordinal dates with month/day");let oe;C?oe=Ar({...sn(this.c,i,y),...r},i,y):se(r.ordinal)?(oe={...this.toObject(),...r},se(r.day)&&(oe.day=Math.min(on(oe.year,oe.month),oe.day))):oe=$r({...Nn(this.c),...r});const[me,re]=mn(oe,this.o,this.zone);return it(this,{ts:me,o:re})}plus(e){if(!this.isValid)return this;const r=le.fromDurationLike(e);return it(this,ws(this,r))}minus(e){if(!this.isValid)return this;const r=le.fromDurationLike(e).negate();return it(this,ws(this,r))}startOf(e,{useLocaleWeeks:r=!1}={}){if(!this.isValid)return this;const i={},y=le.normalizeUnit(e);switch(y){case"years":i.month=1;case"quarters":case"months":i.day=1;case"weeks":case"days":i.hour=0;case"hours":i.minute=0;case"minutes":i.second=0;case"seconds":i.millisecond=0;break}if(y==="weeks")if(r){const C=this.loc.getStartOfWeek(),{weekday:j}=this;j<C&&(i.weekNumber=this.weekNumber-1),i.weekday=C}else i.weekday=1;if(y==="quarters"){const C=Math.ceil(this.month/3);i.month=(C-1)*3+1}return this.set(i)}endOf(e,r){return this.isValid?this.plus({[e]:1}).startOf(e,r).minus(1):this}toFormat(e,r={}){return this.isValid?Te.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):zn}toLocaleString(e=S,r={}){return this.isValid?Te.create(this.loc.clone(r),e).formatDateTime(this):zn}toLocaleParts(e={}){return this.isValid?Te.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:r=!1,suppressMilliseconds:i=!1,includeOffset:y=!0,extendedZone:C=!1,precision:j="milliseconds"}={}){if(!this.isValid)return null;j=gn(j);const O=e==="extended";let F=Un(this,O,j);return yn.indexOf(j)>=3&&(F+="T"),F+=ks(this,O,r,i,y,C,j),F}toISODate({format:e="extended",precision:r="day"}={}){return this.isValid?Un(this,e==="extended",gn(r)):null}toISOWeekDate(){return pn(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:r=!1,includeOffset:i=!0,includePrefix:y=!1,extendedZone:C=!1,format:j="extended",precision:O="milliseconds"}={}){return this.isValid?(O=gn(O),(y&&yn.indexOf(O)>=3?"T":"")+ks(this,j==="extended",r,e,i,C,O)):null}toRFC2822(){return pn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return pn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Un(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:r=!1,includeOffsetSpace:i=!0}={}){let y="HH:mm:ss.SSS";return(r||e)&&(i&&(y+=" "),r?y+="z":e&&(y+="ZZ")),pn(this,y,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():zn}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};const r={...this.c};return e.includeConfig&&(r.outputCalendar=this.outputCalendar,r.numberingSystem=this.loc.numberingSystem,r.locale=this.loc.locale),r}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,r="milliseconds",i={}){if(!this.isValid||!e.isValid)return le.invalid("created by diffing an invalid DateTime");const y={locale:this.locale,numberingSystem:this.numberingSystem,...i},C=Ja(r).map(le.normalizeUnit),j=e.valueOf()>this.valueOf(),O=j?this:e,F=j?e:this,z=no(O,F,C,y);return j?z.negate():z}diffNow(e="milliseconds",r={}){return this.diff(ae.now(),e,r)}until(e){return this.isValid?xe.fromDateTimes(this,e):this}hasSame(e,r,i){if(!this.isValid)return!1;const y=e.valueOf(),C=this.setZone(e.zone,{keepLocalTime:!0});return C.startOf(r,i)<=y&&y<=C.endOf(r,i)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const r=e.base||ae.fromObject({},{zone:this.zone}),i=e.padding?this<r?-e.padding:e.padding:0;let y=["years","months","days","hours","minutes","seconds"],C=e.unit;return Array.isArray(e.unit)&&(y=e.unit,C=void 0),Ds(r,this.plus(i),{...e,numeric:"always",units:y,unit:C})}toRelativeCalendar(e={}){return this.isValid?Ds(e.base||ae.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(ae.isDateTime))throw new l("min requires all arguments be DateTimes");return Wr(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(ae.isDateTime))throw new l("max requires all arguments be DateTimes");return Wr(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,i={}){const{locale:y=null,numberingSystem:C=null}=i,j=he.fromOpts({locale:y,numberingSystem:C,defaultToEN:!0});return xs(j,e,r)}static fromStringExplain(e,r,i={}){return ae.fromFormatExplain(e,r,i)}static buildFormatParser(e,r={}){const{locale:i=null,numberingSystem:y=null}=r,C=he.fromOpts({locale:i,numberingSystem:y,defaultToEN:!0});return new gs(C,e)}static fromFormatParser(e,r,i={}){if(se(e)||se(r))throw new l("fromFormatParser requires an input string and a format parser");const{locale:y=null,numberingSystem:C=null}=i,j=he.fromOpts({locale:y,numberingSystem:C,defaultToEN:!0});if(!j.equals(r.locale))throw new l(`fromFormatParser called with a locale of ${j}, but the format parser was created for ${r.locale}`);const{result:O,zone:F,specificOffset:z,invalidReason:te}=r.explainFromTokens(e);return te?ae.invalid(te):wt(O,F,i,`format ${r.format}`,e,z)}static get DATE_SHORT(){return S}static get DATE_MED(){return b}static get DATE_MED_WITH_WEEKDAY(){return g}static get DATE_FULL(){return k}static get DATE_HUGE(){return w}static get TIME_SIMPLE(){return T}static get TIME_WITH_SECONDS(){return M}static get TIME_WITH_SHORT_OFFSET(){return D}static get TIME_WITH_LONG_OFFSET(){return I}static get TIME_24_SIMPLE(){return E}static get TIME_24_WITH_SECONDS(){return L}static get TIME_24_WITH_SHORT_OFFSET(){return H}static get TIME_24_WITH_LONG_OFFSET(){return _}static get DATETIME_SHORT(){return G}static get DATETIME_SHORT_WITH_SECONDS(){return N}static get DATETIME_MED(){return q}static get DATETIME_MED_WITH_SECONDS(){return U}static get DATETIME_MED_WITH_WEEKDAY(){return A}static get DATETIME_FULL(){return P}static get DATETIME_FULL_WITH_SECONDS(){return Y}static get DATETIME_HUGE(){return K}static get DATETIME_HUGE_WITH_SECONDS(){return X}}function Lt(s){if(ae.isDateTime(s))return s;if(s&&s.valueOf&&et(s.valueOf()))return ae.fromJSDate(s);if(s&&typeof s=="object")return ae.fromObject(s);throw new l(`Unknown datetime argument: ${s}, of type ${typeof s}`)}const So="3.7.2";return Oe.DateTime=ae,Oe.Duration=le,Oe.FixedOffsetZone=Ce,Oe.IANAZone=ie,Oe.Info=At,Oe.Interval=xe,Oe.InvalidZone=vr,Oe.Settings=ge,Oe.SystemZone=ne,Oe.VERSION=So,Oe.Zone=J,Oe}var Gs;function pr(){return Gs||(Gs=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CronDate=t.DAYS_IN_MONTH=t.DateMathOp=t.TimeUnit=void 0;const o=Zl();var f;(function(c){c.Second="Second",c.Minute="Minute",c.Hour="Hour",c.Day="Day",c.Month="Month",c.Year="Year"})(f||(t.TimeUnit=f={}));var a;(function(c){c.Add="Add",c.Subtract="Subtract"})(a||(t.DateMathOp=a={})),t.DAYS_IN_MONTH=Object.freeze([31,29,31,30,31,30,31,31,30,31,30,31]);class p{#e;#n=null;#a=null;constructor(l,h){const d={zone:h};if(l?l instanceof p?(this.#e=l.#e,this.#n=l.#n,this.#a=l.#a):l instanceof Date?this.#e=o.DateTime.fromJSDate(l,d):typeof l=="number"?this.#e=o.DateTime.fromMillis(l,d):(this.#e=o.DateTime.fromISO(l,d),this.#e.isValid||(this.#e=o.DateTime.fromRFC2822(l,d)),this.#e.isValid||(this.#e=o.DateTime.fromSQL(l,d)),this.#e.isValid||(this.#e=o.DateTime.fromFormat(l,"EEE, d MMM yyyy HH:mm:ss",d))):this.#e=o.DateTime.local(),!this.#e.isValid)throw new Error(`CronDate: unhandled timestamp: ${l}`);h&&h!==this.#e.zoneName&&(this.#e=this.#e.setZone(h))}static#s(l){return l%4===0&&l%100!==0||l%400===0}get dstStart(){return this.#n}set dstStart(l){this.#n=l}get dstEnd(){return this.#a}set dstEnd(l){this.#a=l}addYear(){this.#e=this.#e.plus({years:1})}addMonth(){this.#e=this.#e.plus({months:1}).startOf("month")}addDay(){this.#e=this.#e.plus({days:1}).startOf("day")}addHour(){this.#e=this.#e.plus({hours:1}).startOf("hour")}addMinute(){this.#e=this.#e.plus({minutes:1}).startOf("minute")}addSecond(){this.#e=this.#e.plus({seconds:1})}subtractYear(){this.#e=this.#e.minus({years:1})}subtractMonth(){this.#e=this.#e.minus({months:1}).endOf("month").startOf("second")}subtractDay(){this.#e=this.#e.minus({days:1}).endOf("day").startOf("second")}subtractHour(){this.#e=this.#e.minus({hours:1}).endOf("hour").startOf("second")}subtractMinute(){this.#e=this.#e.minus({minutes:1}).endOf("minute").startOf("second")}subtractSecond(){this.#e=this.#e.minus({seconds:1})}addUnit(l){switch(l){case f.Year:return this.addYear();case f.Month:return this.addMonth();case f.Day:return this.addDay();case f.Hour:return this.addHour();case f.Minute:return this.addMinute();case f.Second:return this.addSecond()}}subtractUnit(l){switch(l){case f.Year:return this.subtractYear();case f.Month:return this.subtractMonth();case f.Day:return this.subtractDay();case f.Hour:return this.subtractHour();case f.Minute:return this.subtractMinute();case f.Second:return this.subtractSecond()}}invokeDateOperation(l,h){if(l===a.Add){this.addUnit(h);return}if(l===a.Subtract){this.subtractUnit(h);return}throw new Error(`Invalid verb: ${l}`)}getDate(){return this.#e.day}getFullYear(){return this.#e.year}getDay(){const l=this.#e.weekday;return l===7?0:l}getMonth(){return this.#e.month-1}getHours(){return this.#e.hour}getMinutes(){return this.#e.minute}getSeconds(){return this.#e.second}getMilliseconds(){return this.#e.millisecond}getUTCOffset(){return this.#e.offset}setStartOfDay(){this.#e=this.#e.startOf("day")}setEndOfDay(){this.#e=this.#e.endOf("day")}getTime(){return this.#e.valueOf()}getUTCDate(){return this.#r().day}getUTCFullYear(){return this.#r().year}getUTCDay(){const l=this.#r().weekday;return l===7?0:l}getUTCMonth(){return this.#r().month-1}getUTCHours(){return this.#r().hour}getUTCMinutes(){return this.#r().minute}getUTCSeconds(){return this.#r().second}toISOString(){return this.#e.toUTC().toISO()}toJSON(){return this.#e.toJSON()}setDate(l){this.#e=this.#e.set({day:l})}setFullYear(l){this.#e=this.#e.set({year:l})}setDay(l){this.#e=this.#e.set({weekday:l})}setMonth(l){this.#e=this.#e.set({month:l+1})}setHours(l){this.#e=this.#e.set({hour:l})}setMinutes(l){this.#e=this.#e.set({minute:l})}setSeconds(l){this.#e=this.#e.set({second:l})}setMilliseconds(l){this.#e=this.#e.set({millisecond:l})}toString(){return this.toDate().toString()}toDate(){return this.#e.toJSDate()}isLastDayOfMonth(){const{day:l,month:h}=this.#e;if(h===2){const d=p.#s(this.#e.year);return l===t.DAYS_IN_MONTH[h-1]-(d?0:1)}return l===t.DAYS_IN_MONTH[h-1]}isLastWeekdayOfMonth(){const{day:l,month:h}=this.#e;let d;return h===2?d=t.DAYS_IN_MONTH[h-1]-(p.#s(this.#e.year)?0:1):d=t.DAYS_IN_MONTH[h-1],l>d-7}applyDateOperation(l,h,d){if(h===f.Month||h===f.Day){this.invokeDateOperation(l,h);return}const m=this.getHours();this.invokeDateOperation(l,h);const x=this.getHours(),S=x-m;S===2?d!==24&&(this.dstStart=m+1):S===0&&this.getMinutes()===0&&this.getSeconds()===0&&d!==24&&(this.dstEnd=x)}#r(){return this.#e.toUTC()}}t.CronDate=p,t.default=p})(Kn)),Kn}var Ys;function Xl(){if(Ys)return Yt;Ys=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.CronMonth=void 0;const t=pr(),o=dt(),f=1,a=12,p=Object.freeze([]);let c=class extends o.CronField{static get min(){return f}static get max(){return a}static get chars(){return p}static get daysInMonth(){return t.DAYS_IN_MONTH}constructor(h,d){super(h,d),this.validate()}get values(){return super.values}};return Yt.CronMonth=c,Yt}var Zt={},Zs;function Kl(){if(Zs)return Zt;Zs=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.CronSecond=void 0;const t=dt(),o=0,f=59,a=Object.freeze([]);let p=class extends t.CronField{static get min(){return o}static get max(){return f}static get chars(){return a}constructor(l,h){super(l,h),this.validate()}get values(){return super.values}};return Zt.CronSecond=p,Zt}var Xs;function yr(){return Xs||(Xs=1,(function(t){var o=lt&&lt.__createBinding||(Object.create?(function(a,p,c,l){l===void 0&&(l=c);var h=Object.getOwnPropertyDescriptor(p,c);(!h||("get"in h?!p.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return p[c]}}),Object.defineProperty(a,l,h)}):(function(a,p,c,l){l===void 0&&(l=c),a[l]=p[c]})),f=lt&&lt.__exportStar||function(a,p){for(var c in a)c!=="default"&&!Object.prototype.hasOwnProperty.call(p,c)&&o(p,a,c)};Object.defineProperty(t,"__esModule",{value:!0}),f(Vl(),t),f(Ul(),t),f(Bl(),t),f(dt(),t),f(Gl(),t),f(Yl(),t),f(Xl(),t),f(Kl(),t)})(lt)),lt}var Ks;function Sa(){if(Ks)return zt;Ks=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.CronFieldCollection=void 0;const t=yr();let o=class Jt{#e;#n;#a;#s;#r;#t;static from(a,p){return new Jt({second:this.resolveField(t.CronSecond,a.second,p.second),minute:this.resolveField(t.CronMinute,a.minute,p.minute),hour:this.resolveField(t.CronHour,a.hour,p.hour),dayOfMonth:this.resolveField(t.CronDayOfMonth,a.dayOfMonth,p.dayOfMonth),month:this.resolveField(t.CronMonth,a.month,p.month),dayOfWeek:this.resolveField(t.CronDayOfWeek,a.dayOfWeek,p.dayOfWeek)})}static resolveField(a,p,c){return c?c instanceof t.CronField?c:new a(c):p}constructor({second:a,minute:p,hour:c,dayOfMonth:l,month:h,dayOfWeek:d}){if(!a)throw new Error("Validation error, Field second is missing");if(!p)throw new Error("Validation error, Field minute is missing");if(!c)throw new Error("Validation error, Field hour is missing");if(!l)throw new Error("Validation error, Field dayOfMonth is missing");if(!h)throw new Error("Validation error, Field month is missing");if(!d)throw new Error("Validation error, Field dayOfWeek is missing");if(h.values.length===1&&!l.hasLastChar&&d.isWildcard&&!(parseInt(l.values[0],10)<=t.CronMonth.daysInMonth[h.values[0]-1]))throw new Error("Invalid explicit day of month definition");this.#e=a,this.#n=p,this.#a=c,this.#r=h,this.#t=d,this.#s=l}get second(){return this.#e}get minute(){return this.#n}get hour(){return this.#a}get dayOfMonth(){return this.#s}get month(){return this.#r}get dayOfWeek(){return this.#t}static compactField(a){if(a.length===0)return[];const p=[];let c;return a.forEach((l,h,d)=>{if(c===void 0){c={start:l,count:1};return}const m=d[h-1]||c.start,x=d[h+1];if(l==="L"||l==="W"){p.push(c),p.push({start:l,count:1}),c=void 0;return}if(c.step===void 0&&x!==void 0){const S=l-m,b=x-l;if(S<=b){c={...c,count:2,end:l,step:S};return}c.step=1}l-(c.end??0)===c.step?(c.count++,c.end=l):(c.count===1?p.push({start:c.start,count:1}):c.count===2?(p.push({start:c.start,count:1}),p.push({start:c.end??m,count:1})):p.push(c),c={start:l,count:1})}),c&&p.push(c),p}static#c(a,p,c){const l=p.step;return l?l===1&&p.start===a.min&&p.end&&p.end>=c?a.hasQuestionMarkChar?"?":"*":l!==1&&p.start===a.min&&p.end&&p.end>=c-l+1?`*/${l}`:null:null}static#l(a,p){const c=a.step;if(c===1)return`${a.start}-${a.end}`;const l=a.start===0?a.count-1:a.count;if(!c)throw new Error("Unexpected range step");if(!a.end)throw new Error("Unexpected range end");if(c*l>a.end){const h=(m,x)=>{if(typeof a.start!="number")throw new Error("Unexpected range start");return x%c===0?a.start+x:null};if(typeof a.start!="number")throw new Error("Unexpected range start");const d={length:a.end-a.start+1};return Array.from(d,h).filter(m=>m!==null).join(",")}return a.end===p-c+1?`${a.start}/${c}`:`${a.start}-${a.end}/${c}`}stringifyField(a){let p=a.max,c=a.values;if(a instanceof t.CronDayOfWeek){p=6;const h=this.#t.values;c=h[h.length-1]===7?h.slice(0,-1):h}a instanceof t.CronDayOfMonth&&(p=this.#r.values.length===1?t.CronMonth.daysInMonth[this.#r.values[0]-1]:a.max);const l=Jt.compactField(c);if(l.length===1){const h=Jt.#c(a,l[0],p);if(h)return h}return l.map(h=>{const d=h.count===1?h.start.toString():Jt.#l(h,p);return a instanceof t.CronDayOfWeek&&a.nthDay>0?`${d}#${a.nthDay}`:d}).join(",")}stringify(a=!1){const p=[];return a&&p.push(this.stringifyField(this.#e)),p.push(this.stringifyField(this.#n),this.stringifyField(this.#a),this.stringifyField(this.#s),this.stringifyField(this.#r),this.stringifyField(this.#t)),p.join(" ")}serialize(){return{second:this.#e.serialize(),minute:this.#n.serialize(),hour:this.#a.serialize(),dayOfMonth:this.#s.serialize(),month:this.#r.serialize(),dayOfWeek:this.#t.serialize()}}};return zt.CronFieldCollection=o,zt}var Qn={},Qs;function wa(){return Qs||(Qs=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CronExpression=t.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE=t.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE=void 0;const o=pr();t.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE="Out of the time span range",t.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE="Invalid expression, loop limit exceeded";const f=1e4;class a{#e;#n;#a;#s;#r;#t;#c=null;#l=!1;constructor(c,l){this.#e=l,this.#n=l.tz,this.#s=l.startDate?new o.CronDate(l.startDate,this.#n):null,this.#r=l.endDate?new o.CronDate(l.endDate,this.#n):null;let h=l.currentDate??l.startDate;if(h){const d=new o.CronDate(h,this.#n);this.#s&&d.getTime()<this.#s.getTime()?h=this.#s:this.#r&&d.getTime()>this.#r.getTime()&&(h=this.#r)}this.#a=new o.CronDate(h,this.#n),this.#t=c}get fields(){return this.#t}static fieldsToExpression(c,l){return new a(c,l||{})}static#i(c,l){return l.some(h=>h===c)}#o(c,l){return c[l?c.length-1:0]}#d(c){const l=`${c.getFullYear()}-${c.getMonth()+1}-${c.getDate()}`;if(this.#c===l)return this.#l;const h=new o.CronDate(c);h.setStartOfDay();const d=new o.CronDate(c);return d.setEndOfDay(),this.#c=l,this.#l=h.getUTCOffset()!==d.getUTCOffset(),this.#l}#h(c,l,h){const d=this.#t.second.values,m=c.getSeconds(),x=this.#t.second.findNearestValue(m,h);if(x!==null){c.setSeconds(x);return}c.applyDateOperation(l,o.TimeUnit.Minute,this.#t.hour.values.length),c.setSeconds(this.#o(d,h))}#m(c,l,h){const d=this.#t.minute.values,m=this.#t.second.values,x=c.getMinutes(),S=this.#t.minute.findNearestValue(x,h);if(S!==null){c.setMinutes(S),c.setSeconds(this.#o(m,h));return}c.applyDateOperation(l,o.TimeUnit.Hour,this.#t.hour.values.length),c.setMinutes(this.#o(d,h)),c.setSeconds(this.#o(m,h))}static#p(c,l){const h=l.isLastWeekdayOfMonth();return c.some(d=>{const m=parseInt(d.toString().charAt(0),10)%7;if(Number.isNaN(m))throw new Error(`Invalid last weekday of the month expression: ${d}`);return l.getDay()===m&&h})}next(){return this.#u()}prev(){return this.#u(!0)}hasNext(){const c=this.#a;try{return this.#u(),!0}catch{return!1}finally{this.#a=c}}hasPrev(){const c=this.#a;try{return this.#u(!0),!0}catch{return!1}finally{this.#a=c}}take(c){const l=[];if(c>=0)for(let h=0;h<c;h++)try{l.push(this.next())}catch{return l}else for(let h=0;h>c;h--)try{l.push(this.prev())}catch{return l}return l}reset(c){this.#a=new o.CronDate(c||this.#e.currentDate,this.#n)}stringify(c=!1){return this.#t.stringify(c)}includesDate(c){const{second:l,minute:h,hour:d,month:m}=this.#t,x=new o.CronDate(c,this.#n);return!(!l.values.includes(x.getSeconds())||!h.values.includes(x.getMinutes())||!d.values.includes(x.getHours())||!m.values.includes(x.getMonth()+1)||!this.#f(x)||this.#t.dayOfWeek.nthDay>0&&Math.ceil(x.getDate()/7)!==this.#t.dayOfWeek.nthDay)}toString(){return this.#e.expression||this.stringify(!0)}#f(c){const l=this.#t.dayOfMonth.isWildcard,h=!l,d=this.#t.dayOfWeek.isWildcard,m=!d,x=a.#i(c.getDate(),this.#t.dayOfMonth.values)||this.#t.dayOfMonth.hasLastChar&&c.isLastDayOfMonth(),S=a.#i(c.getDay(),this.#t.dayOfWeek.values)||this.#t.dayOfWeek.hasLastChar&&a.#p(this.#t.dayOfWeek.values,c);return!!(h&&m&&(x||S)||x&&!m||l&&!d&&S)}#y(c,l,h){const d=this.#t.hour.values,m=d,x=c.getHours(),S=a.#i(x,d),b=c.dstEnd===x;if(c.dstStart!==null&&c.dstStart===x-1&&a.#i(c.dstStart,d))return!0;if(b&&!h)return c.dstEnd=null,c.applyDateOperation(o.DateMathOp.Add,o.TimeUnit.Hour,m.length),!1;if(S)return!0;c.dstStart=null;const g=this.#t.hour.findNearestValue(x,h);if(g===null)return c.applyDateOperation(l,o.TimeUnit.Day,m.length),!1;if(this.#d(c)){const k=h?x-g:g-x;for(let w=0;w<k&&(c.applyDateOperation(l,o.TimeUnit.Hour,m.length),!(!h&&c.getHours()>=g||h&&c.getHours()<=g));w++);}else c.setHours(g);return c.setMinutes(this.#o(this.#t.minute.values,h)),c.setSeconds(this.#o(this.#t.second.values,h)),!1}#g(c){if(!this.#s&&!this.#r)return;const l=c.getTime();if(this.#s&&l<this.#s.getTime())throw new Error(t.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE);if(this.#r&&l>this.#r.getTime())throw new Error(t.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE)}#u(c=!1){const l=c?o.DateMathOp.Subtract:o.DateMathOp.Add,h=new o.CronDate(this.#a),d=h.getTime();let m=0;for(;++m<f;){if(this.#g(h),!this.#f(h)){h.applyDateOperation(l,o.TimeUnit.Day,this.#t.hour.values.length);continue}if(!(this.#t.dayOfWeek.nthDay<=0||Math.ceil(h.getDate()/7)===this.#t.dayOfWeek.nthDay)){h.applyDateOperation(l,o.TimeUnit.Day,this.#t.hour.values.length);continue}if(!a.#i(h.getMonth()+1,this.#t.month.values)){h.applyDateOperation(l,o.TimeUnit.Month,this.#t.hour.values.length);continue}if(this.#y(h,l,c)){if(!a.#i(h.getMinutes(),this.#t.minute.values)){this.#m(h,l,c);continue}if(!a.#i(h.getSeconds(),this.#t.second.values)){this.#h(h,l,c);continue}if(d===h.getTime()){(l==="Add"||h.getMilliseconds()===0)&&h.applyDateOperation(l,o.TimeUnit.Second,this.#t.hour.values.length);continue}break}}if(m>f)throw new Error(t.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE);return h.getMilliseconds()!==0&&h.setMilliseconds(0),this.#a=h,h}[Symbol.iterator](){return{next:()=>{try{return{value:this.#u(),done:!1}}catch{return{value:void 0,done:!0}}}}}}t.CronExpression=a,t.default=a})(Qn)),Qn}var xn={},Js;function Ql(){if(Js)return xn;Js=1,Object.defineProperty(xn,"__esModule",{value:!0}),xn.seededRandom=f;function t(a){let p=2166136261;for(let c=0;c<a.length;c++)p^=a.charCodeAt(c),p=Math.imul(p,16777619);return()=>p>>>0}function o(a){return()=>{let p=a+=1831565813;return p=Math.imul(p^p>>>15,p|1),p^=p+Math.imul(p^p>>>7,p|61),((p^p>>>14)>>>0)/4294967296}}function f(a){const p=a?t(a)():Math.floor(Math.random()*1e10);return o(p)}return xn}var ea;function ir(){if(ea)return Ee;ea=1,Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.CronExpressionParser=Ee.DayOfWeek=Ee.Months=Ee.CronUnit=Ee.PredefinedExpressions=void 0;const t=Sa(),o=wa(),f=Ql(),a=yr();var p;(function(m){m["@yearly"]="0 0 0 1 1 *",m["@annually"]="0 0 0 1 1 *",m["@monthly"]="0 0 0 1 * *",m["@weekly"]="0 0 0 * * 0",m["@daily"]="0 0 0 * * *",m["@hourly"]="0 0 * * * *",m["@minutely"]="0 * * * * *",m["@secondly"]="* * * * * *",m["@weekdays"]="0 0 0 * * 1-5",m["@weekends"]="0 0 0 * * 0,6"})(p||(Ee.PredefinedExpressions=p={}));var c;(function(m){m.Second="Second",m.Minute="Minute",m.Hour="Hour",m.DayOfMonth="DayOfMonth",m.Month="Month",m.DayOfWeek="DayOfWeek"})(c||(Ee.CronUnit=c={}));var l;(function(m){m[m.jan=1]="jan",m[m.feb=2]="feb",m[m.mar=3]="mar",m[m.apr=4]="apr",m[m.may=5]="may",m[m.jun=6]="jun",m[m.jul=7]="jul",m[m.aug=8]="aug",m[m.sep=9]="sep",m[m.oct=10]="oct",m[m.nov=11]="nov",m[m.dec=12]="dec"})(l||(Ee.Months=l={}));var h;(function(m){m[m.sun=0]="sun",m[m.mon=1]="mon",m[m.tue=2]="tue",m[m.wed=3]="wed",m[m.thu=4]="thu",m[m.fri=5]="fri",m[m.sat=6]="sat"})(h||(Ee.DayOfWeek=h={}));let d=class Ie{static parse(x,S={}){const{strict:b=!1,hashSeed:g}=S,k=(0,f.seededRandom)(g);x=p[x]||x;const w=Ie.#e(x,b);if(!(w.dayOfMonth==="*"||w.dayOfWeek==="*"||!b))throw new Error("Cannot use both dayOfMonth and dayOfWeek together in strict mode!");const T=Ie.#n(c.Second,w.second,a.CronSecond.constraints,k),M=Ie.#n(c.Minute,w.minute,a.CronMinute.constraints,k),D=Ie.#n(c.Hour,w.hour,a.CronHour.constraints,k),I=Ie.#n(c.Month,w.month,a.CronMonth.constraints,k),E=Ie.#n(c.DayOfMonth,w.dayOfMonth,a.CronDayOfMonth.constraints,k),{dayOfWeek:L,nthDayOfWeek:H}=Ie.#d(w.dayOfWeek),_=Ie.#n(c.DayOfWeek,L,a.CronDayOfWeek.constraints,k),G=new t.CronFieldCollection({second:new a.CronSecond(T,{rawValue:w.second}),minute:new a.CronMinute(M,{rawValue:w.minute}),hour:new a.CronHour(D,{rawValue:w.hour}),dayOfMonth:new a.CronDayOfMonth(E,{rawValue:w.dayOfMonth}),month:new a.CronMonth(I,{rawValue:w.month}),dayOfWeek:new a.CronDayOfWeek(_,{rawValue:w.dayOfWeek,nthDayOfWeek:H})});return new o.CronExpression(G,{...S,expression:x})}static#e(x,S){if(S&&!x.length)throw new Error("Invalid cron expression");x=x||"0 * * * * *";const b=x.trim().split(/\s+/);if(S&&b.length<6)throw new Error("Invalid cron expression, expected 6 fields");if(b.length>6)throw new Error("Invalid cron expression, too many fields");const g=["*","*","*","*","*","0"];b.length<g.length&&b.unshift(...g.slice(b.length));const[k,w,T,M,D,I]=b;return{second:k,minute:w,hour:T,dayOfMonth:M,month:D,dayOfWeek:I}}static#n(x,S,b,g){if((x===c.Month||x===c.DayOfWeek)&&(S=S.replace(/[a-z]{3}/gi,k=>{k=k.toLowerCase();const w=l[k]||h[k];if(w===void 0)throw new Error(`Validation error, cannot resolve alias "${k}"`);return w.toString()})),!b.validChars.test(S))throw new Error(`Invalid characters, got value: ${S}`);return S=this.#a(S,b),S=this.#s(S,b,g),this.#r(x,S,b)}static#a(x,S){return x.replace(/[*?]/g,S.min+"-"+S.max)}static#s(x,S,b){const g=b();return x.replace(/H(?:\((\d+)-(\d+)\))?(?:\/(\d+))?/g,(k,w,T,M)=>{if(w&&T&&M){const D=parseInt(w,10),I=parseInt(T,10),E=parseInt(M,10);if(D>I)throw new Error(`Invalid range: ${D}-${I}, min > max`);if(E<=0)throw new Error(`Invalid step: ${E}, must be positive`);const L=Math.max(D,S.min),H=Math.floor(g*E),_=[];for(let G=Math.floor(L/E)*E+H;G<=I;G+=E)G>=L&&_.push(G);return _.join(",")}else if(w&&T){const D=parseInt(w,10),I=parseInt(T,10);if(D>I)throw new Error(`Invalid range: ${D}-${I}, min > max`);return String(Math.floor(g*(I-D+1))+D)}else if(M){const D=parseInt(M,10);if(D<=0)throw new Error(`Invalid step: ${D}, must be positive`);const I=Math.floor(g*D),E=[];for(let L=Math.floor(S.min/D)*D+I;L<=S.max;L+=D)L>=S.min&&E.push(L);return E.join(",")}else return String(Math.floor(g*(S.max-S.min+1)+S.min))})}static#r(x,S,b){const g=[];function k(T,M){if(Array.isArray(T))g.push(...T);else if(Ie.#h(M,T))g.push(T);else{const D=parseInt(T.toString(),10);if(!(D>=M.min&&D<=M.max))throw new Error(`Constraint error, got value ${T} expected range ${M.min}-${M.max}`);g.push(x===c.DayOfWeek?D%7:T)}}return S.split(",").forEach(T=>{if(!(T.length>0))throw new Error("Invalid list value format");k(Ie.#t(x,T,b),b)}),g}static#t(x,S,b){const g=S.split("/");if(g.length>2)throw new Error(`Invalid repeat: ${S}`);return g.length===2?(g[0].includes("-")||(g[0]=`${g[0]}-${b.max}`),Ie.#o(x,g[0],parseInt(g[1],10),b)):Ie.#o(x,S,1,b)}static#c(x,S,b){if(!(!isNaN(x)&&!isNaN(S)&&x>=b.min&&S<=b.max))throw new Error(`Constraint error, got range ${x}-${S} expected range ${b.min}-${b.max}`);if(x>S)throw new Error(`Invalid range: ${x}-${S}, min(${x}) > max(${S})`)}static#l(x){if(!(!isNaN(x)&&x>0))throw new Error(`Constraint error, cannot repeat at every ${x} time.`)}static#i(x,S,b,g){const k=[];x===c.DayOfWeek&&b%7===0&&k.push(0);for(let w=S;w<=b;w+=g)k.indexOf(w)===-1&&k.push(w);return k}static#o(x,S,b,g){const k=S.split("-");if(k.length<=1)return isNaN(+S)?S:+S;const[w,T]=k.map(M=>parseInt(M,10));return this.#c(w,T,g),this.#l(b),this.#i(x,w,T,b)}static#d(x){const S=x.split("#");if(S.length<=1)return{dayOfWeek:S[0]};const b=+S[S.length-1],g=x.match(/([,-/])/);if(g!==null)throw new Error(`Constraint error, invalid dayOfWeek \`#\` and \`${g?.[0]}\` special characters are incompatible`);if(!(S.length<=2&&!isNaN(b)&&b>=1&&b<=5))throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)");return{dayOfWeek:S[0],nthDayOfWeek:b}}static#h(x,S){return x.chars.some(b=>S.toString().includes(b))}};return Ee.CronExpressionParser=d,Ee}var We={};const Jl={},ec=Object.freeze(Object.defineProperty({__proto__:null,default:Jl},Symbol.toStringTag,{value:"Module"})),ta=u.getAugmentedNamespace(ec);var na;function tc(){if(na)return We;na=1;var t=We&&We.__createBinding||(Object.create?(function(c,l,h,d){d===void 0&&(d=h);var m=Object.getOwnPropertyDescriptor(l,h);(!m||("get"in m?!l.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return l[h]}}),Object.defineProperty(c,d,m)}):(function(c,l,h,d){d===void 0&&(d=h),c[d]=l[h]})),o=We&&We.__setModuleDefault||(Object.create?(function(c,l){Object.defineProperty(c,"default",{enumerable:!0,value:l})}):function(c,l){c.default=l}),f=We&&We.__importStar||(function(){var c=function(l){return c=Object.getOwnPropertyNames||function(h){var d=[];for(var m in h)Object.prototype.hasOwnProperty.call(h,m)&&(d[d.length]=m);return d},c(l)};return function(l){if(l&&l.__esModule)return l;var h={};if(l!=null)for(var d=c(l),m=0;m<d.length;m++)d[m]!=="default"&&t(h,l,d[m]);return o(h,l),h}})();Object.defineProperty(We,"__esModule",{value:!0}),We.CronFileParser=void 0;const a=ir();let p=class vn{static async parseFile(l){const{readFile:h}=await Promise.resolve().then(()=>f(ta)),d=await h(l,"utf8");return vn.#e(d)}static parseFileSync(l){const{readFileSync:h}=ta,d=h(l,"utf8");return vn.#e(d)}static#e(l){const h=l.split(`