@malloy-publisher/sdk 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),S=require("@mui/material"),A=require("react"),d=require("./DocumentStorage-mMn5SZ1c.cjs.js"),V=require("./ServerProvider-CC9ein5-.cjs.js"),kn=require("@tanstack/react-query"),ia=require("@mui/system"),Ve=require("@mui/icons-material"),ct=require("./RenderedResult-GukOadCi.cjs.js"),xn=require("react-router-dom");function Mo(t){const l=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(l,f,a.get?a:{enumerable:!0,get:()=>t[f]})}}return l.default=t,Object.freeze(l)}const he=Mo(A),Do=d.createSvgIcon(n.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function dr({label:t,href:l,onClick:f}){const a=p=>{const o=p.metaKey||p.ctrlKey||p.shiftKey||p.altKey||p.button!==0;l!==void 0&&o||(p.preventDefault(),f(p))};return n.jsxs(S.Link,{...l===void 0?{component:"button",type:"button"}:{href:l},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(Do,{sx:{fontSize:18}}),"Back to ",t]})}function jo(){const t=xn.useNavigate();return(l,f)=>{if(!f||!f.metaKey&&!f.ctrlKey&&!f.shiftKey&&f.button!==1){t(l);return}const a=new URL(l,window.location.href).href;(f.metaKey||f.ctrlKey||f.button===1||f.shiftKey)&&window.open(a,"_blank")}}function Oo(){const[t]=xn.useSearchParams(),l=xn.useNavigate(),f=xn.useLocation(),a=A.useMemo(()=>Object.fromEntries(t.entries()),[t]),p=A.useRef(new Set),o=A.useCallback((c,m)=>{const u=new Set([...m,...p.current]);p.current=new Set([...p.current,...Object.keys(c),...m]);const h=new URLSearchParams(f.search);for(const x of u)Object.prototype.hasOwnProperty.call(c,x)||h.delete(x);for(const[x,v]of Object.entries(c))h.set(x,v);l({search:h.toString(),hash:f.hash},{replace:!0})},[l,f]);return{params:a,onGivensChange:o}}const oa=d.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"})),Eo="publisher:resize";function Io(t){return typeof t=="object"&&t!==null&&t.type===Eo&&typeof t.height=="number"}function la(t){return t.replace(/\/api\/v0\/?$/,"")}function ca({server:t,environmentName:l,packageName:f,path:a}){const p=a.startsWith("public/")?a.slice(7):a;return`${la(t)}/environments/${encodeURIComponent(l)}/packages/${encodeURIComponent(f)}/`+p}function Fo(t){try{const{environmentName:l,packageName:f,modelPath:a}=d.parseResourceUri(t);return!l||!f||!a?null:{environmentName:l,packageName:f,dataAppPath:a}}catch{return null}}function No({resourceUri:t}){const{server:l,apiClients:f}=V.useServer(),a=Fo(t),p=a?.environmentName??"",o=a?.packageName??"",c=a?.dataAppPath??"",m=A.useMemo(()=>ca({server:l,environmentName:p,packageName:o,path:c}),[l,p,o,c]),h=d.useQueryWithApiError({queryKey:["data-apps",p,o],queryFn:()=>f.dataApps.listDataApps(p,o),enabled:!!a}).data?.data?.find(w=>w.path===c),x=h?.title??c,v=h?.fit==="viewport",b=A.useRef(null),[g,k]=A.useState(120);return A.useEffect(()=>{if(v)return;function w(T){Io(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)},[v]),a?n.jsxs(S.Box,{sx:{p:3,...v?{height:"100%",display:"flex",flexDirection:"column"}:{maxWidth:1200,mx:"auto"}},children:[n.jsxs(S.Stack,{direction:"row",alignItems:"baseline",spacing:1,sx:{mb:1,flexShrink:0},children:[n.jsx(S.Typography,{variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em"},children:x}),n.jsx(S.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:V.MONO_FONT_FAMILY},children:c}),n.jsx(S.Box,{sx:{flex:1}}),n.jsx(S.Tooltip,{title:"Open standalone in new tab",children:n.jsx(S.IconButton,{size:"small",href:m,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:n.jsx(oa,{fontSize:"small"})})})]}),n.jsx(S.Box,{sx:{border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden",backgroundColor:"background.paper",...v?{flex:1,minHeight:0}:{}},children:n.jsx("iframe",{ref:b,src:m,title:x,sandbox:"allow-scripts allow-same-origin allow-forms",style:{display:"block",width:"100%",height:v?"100%":g,border:0}})})]}):n.jsxs(S.Box,{sx:{p:3,maxWidth:1200,mx:"auto"},children:[n.jsx(S.Typography,{variant:"h6",sx:{fontWeight:600},children:"Can't open data app"}),n.jsxs(S.Typography,{variant:"body2",color:"text.secondary",sx:{mt:1},children:["This data app link is missing an environment, package, or path:",n.jsx(S.Box,{component:"span",sx:{fontFamily:V.MONO_FONT_FAMILY,ml:1},children:t})]})]})}function He({title:t,count:l,description:f,action:a,children:p}){const o=A.useId();return n.jsxs(S.Box,{component:"section","aria-labelledby":o,sx:{mb:4},children:[n.jsxs(S.Stack,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:f?0:1,minHeight:40},children:[n.jsxs(S.Stack,{direction:"row",alignItems:"baseline",spacing:1,children:[n.jsx(S.Typography,{id:o,variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em",lineHeight:1.2},children:t}),l!==void 0&&n.jsxs(S.Typography,{variant:"caption",color:"text.secondary",children:["(",l,")"]})]}),a]}),f&&n.jsx(S.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:f}),n.jsx(S.Box,{children:p})]})}function Ao({resourceUri:t}){const{environmentName:l}=d.parseResourceUri(t),{apiClients:f}=V.useServer(),[a,p]=A.useState(!1),o=90,{data:c,isSuccess:m,isError:u,error:h}=d.useQueryWithApiError({queryKey:["about",l],queryFn:()=>f.environments.getEnvironment(l,!1)}),x=c?.data?.readme||"",v=x.split(/\s+/),b=v.length>o,g=v.slice(0,o).join(" ");return n.jsxs(n.Fragment,{children:[!m&&!u&&n.jsx(d.Loading,{text:"Fetching About..."}),m&&x&&n.jsxs(He,{title:"Readme",children:[n.jsx(d.Prose,{variant:"caption",children:a||!b?x:g}),b&&n.jsx(S.Box,{sx:{mt:1},children:n.jsx(d.SecondaryButton,{label:a?"Read less":"Read more",onClick:()=>p(!a)})})]}),u&&n.jsx(d.ApiErrorDisplay,{error:h,context:`${l} > About`})]})}function $o(t={}){const{autoHideDuration:l=null,disableWindowBlurListener:f=!1,onClose:a,open:p,resumeHideDuration:o}=t,c=d.useTimeout();he.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 m=d.useEventCallback((M,D)=>{a?.(M,D)}),u=d.useEventCallback(M=>{!a||M==null||c.start(M,()=>{m(null,"timeout")})});he.useEffect(()=>(p&&u(l),c.clear),[p,l,u,c]);const h=M=>{a?.(M,"clickaway")},x=c.clear,v=he.useCallback(()=>{l!=null&&u(o??l*.5)},[l,o,u]),b=M=>D=>{const I=M.onBlur;I?.(D),v()},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),v()};return he.useEffect(()=>{if(!f&&p)return window.addEventListener("focus",v),window.addEventListener("blur",x),()=>{window.removeEventListener("focus",v),window.removeEventListener("blur",x)}},[f,p,v,x]),{getRootProps:(M={})=>{const D={...d.extractEventHandlers(t),...d.extractEventHandlers(M)};return{role:"presentation",...M,...D,onBlur:b(D),onFocus:g(D),onMouseEnter:k(D),onMouseLeave:w(D)}},onClickAway:h}}function Os(t){return t.substring(2).toLowerCase()}function Ro(t,l){return l.documentElement.clientWidth<t.clientX||l.documentElement.clientHeight<t.clientY}function Lo(t){const{children:l,disableReactTree:f=!1,mouseEvent:a="onClick",onClickAway:p,touchEvent:o="onTouchEnd"}=t,c=he.useRef(!1),m=he.useRef(null),u=he.useRef(!1),h=he.useRef(!1);he.useEffect(()=>(setTimeout(()=>{u.current=!0},0),()=>{u.current=!1}),[]);const x=d.useForkRef(d.getReactElementRef(l),m),v=d.useEventCallback(k=>{const w=h.current;h.current=!1;const T=d.ownerDocument(m.current);if(!u.current||!m.current||"clientX"in k&&Ro(k,T))return;if(c.current){c.current=!1;return}let M;k.composedPath?M=k.composedPath().includes(m.current):M=!T.documentElement.contains(k.target)||m.current.contains(k.target),!M&&(f||!w)&&p(k)}),b=k=>w=>{h.current=!0;const T=l.props[k];T&&T(w)},g={ref:x};return o!==!1&&(g[o]=b(o)),he.useEffect(()=>{if(o!==!1){const k=Os(o),w=d.ownerDocument(m.current),T=()=>{c.current=!0};return w.addEventListener(k,v),w.addEventListener("touchmove",T),()=>{w.removeEventListener(k,v),w.removeEventListener("touchmove",T)}}},[v,o]),a!==!1&&(g[a]=b(a)),he.useEffect(()=>{if(a!==!1){const k=Os(a),w=d.ownerDocument(m.current);return w.addEventListener(k,v),()=>{w.removeEventListener(k,v)}}},[v,a]),he.cloneElement(l,g)}function _o(t){return d.generateUtilityClass("MuiSnackbarContent",t)}d.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const Po=t=>{const{classes:l}=t,f={root:["root"],action:["action"],message:["message"]};return d.composeClasses(f,_o,l)},qo=d.styled(d.Paper,{name:"MuiSnackbarContent",slot:"Root"})(d.memoTheme(({theme:t})=>{const l=t.palette.mode==="light"?.8:.98;return{...t.typography.body2,color:t.vars?t.vars.palette.SnackbarContent.color:t.palette.getContrastText(d.emphasize(t.palette.background.default,l)),backgroundColor:t.vars?t.vars.palette.SnackbarContent.bg:d.emphasize(t.palette.background.default,l),display:"flex",alignItems:"center",flexWrap:"wrap",padding:"6px 16px",flexGrow:1,[t.breakpoints.up("sm")]:{flexGrow:"initial",minWidth:288}}})),Wo=d.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),zo=d.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),Ho=he.forwardRef(function(l,f){const a=d.useDefaultProps({props:l,name:"MuiSnackbarContent"}),{action:p,className:o,message:c,role:m="alert",...u}=a,h=a,x=Po(h);return n.jsxs(qo,{role:m,elevation:6,className:d.clsx(x.root,o),ownerState:h,ref:f,...u,children:[n.jsx(Wo,{className:x.message,ownerState:h,children:c}),p?n.jsx(zo,{className:x.action,ownerState:h,children:p}):null]})});function Vo(t){return d.generateUtilityClass("MuiSnackbar",t)}d.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const Uo=t=>{const{classes:l,anchorOrigin:f}=t,a={root:["root",`anchorOrigin${d.capitalize(f.vertical)}${d.capitalize(f.horizontal)}`]};return d.composeClasses(a,Vo,l)},Bo=d.styled("div",{name:"MuiSnackbar",slot:"Root",overridesResolver:(t,l)=>{const{ownerState:f}=t;return[l.root,l[`anchorOrigin${d.capitalize(f.anchorOrigin.vertical)}${d.capitalize(f.anchorOrigin.horizontal)}`]]}})(d.memoTheme(({theme:t})=>({zIndex:(t.vars||t).zIndex.snackbar,position:"fixed",display:"flex",left:8,right:8,justifyContent:"center",alignItems:"center",variants:[{props:({ownerState:l})=>l.anchorOrigin.vertical==="top",style:{top:8,[t.breakpoints.up("sm")]:{top:24}}},{props:({ownerState:l})=>l.anchorOrigin.vertical!=="top",style:{bottom:8,[t.breakpoints.up("sm")]:{bottom:24}}},{props:({ownerState:l})=>l.anchorOrigin.horizontal==="left",style:{justifyContent:"flex-start",[t.breakpoints.up("sm")]:{left:24,right:"auto"}}},{props:({ownerState:l})=>l.anchorOrigin.horizontal==="right",style:{justifyContent:"flex-end",[t.breakpoints.up("sm")]:{right:24,left:"auto"}}},{props:({ownerState:l})=>l.anchorOrigin.horizontal==="center",style:{[t.breakpoints.up("sm")]:{left:"50%",right:"auto",transform:"translateX(-50%)"}}}]}))),Yo=he.forwardRef(function(l,f){const a=d.useDefaultProps({props:l,name:"MuiSnackbar"}),p=d.useTheme(),o={enter:p.transitions.duration.enteringScreen,exit:p.transitions.duration.leavingScreen},{action:c,anchorOrigin:{vertical:m,horizontal:u}={vertical:"bottom",horizontal:"left"},autoHideDuration:h=null,children:x,className:v,ClickAwayListenerProps:b,ContentProps:g,disableWindowBlurListener:k=!1,message:w,onBlur:T,onClose:M,onFocus:D,onMouseEnter:I,onMouseLeave:E,open:L,resumeHideDuration:z,slots:P={},slotProps:Z={},TransitionComponent:N,transitionDuration:q=o,TransitionProps:{onEnter:U,onExited:R,..._}={},...Y}=a,Q={...a,anchorOrigin:{vertical:m,horizontal:u},autoHideDuration:h,disableWindowBlurListener:k,TransitionComponent:N,transitionDuration:q},K=Uo(Q),{getRootProps:ee,onClickAway:B}=$o({...Q}),[te,W]=he.useState(!0),J=De=>{W(!0),R&&R(De)},$=(De,Se)=>{W(!1),U&&U(De,Se)},X={slots:{transition:N,...P},slotProps:{content:g,clickAwayListener:b,transition:_,...Z}},[le,G]=d.useSlot("root",{ref:f,className:[K.root,v],elementType:Bo,getSlotProps:ee,externalForwardedProps:{...X,...Y},ownerState:Q}),[oe,{ownerState:we,...ve}]=d.useSlot("clickAwayListener",{elementType:Lo,externalForwardedProps:X,getSlotProps:De=>({onClickAway:(...Se)=>{const Ne=Se[0];De.onClickAway?.(...Se),!Ne?.defaultMuiPrevented&&B(...Se)}}),ownerState:Q}),[Te,Fe]=d.useSlot("content",{elementType:Ho,shouldForwardComponentProp:!0,externalForwardedProps:X,additionalProps:{message:w,action:c},ownerState:Q}),[Oe,Me]=d.useSlot("transition",{elementType:d.Grow,externalForwardedProps:X,getSlotProps:De=>({onEnter:(...Se)=>{De.onEnter?.(...Se),$(...Se)},onExited:(...Se)=>{De.onExited?.(...Se),J(...Se)}}),additionalProps:{appear:!0,in:L,timeout:q,direction:m==="top"?"down":"up"},ownerState:Q});return!L&&te?null:n.jsx(oe,{...ve,...P.clickAwayListener&&{ownerState:we},children:n.jsx(le,{...G,children:n.jsx(Oe,{...Me,children:x||n.jsx(Te,{...Fe})})})})});let nr;function Zo(t){nr=t}function Es(t){if(nr)try{nr(t)}catch{}}function Qe(t,l,f){return(async a=>{const p=Date.now();try{const o=await f(a);return Es({type:"console.mutation",resource:t,action:l,ok:!0,durationMs:Date.now()-p}),o}catch(o){throw Es({type:"console.mutation",resource:t,action:l,ok:!1,durationMs:Date.now()-p,reason:o instanceof Error?o.message:"An unknown error occurred"}),o}})}function Tt({mutationFn:t,success:l,invalidates:f,closeDialog:a,resource:p,action:o}){const c=kn.useQueryClient(),[m,u]=A.useState(""),h=d.useMutationWithApiError({mutationFn:Qe(p,o,t),onSuccess(){a();for(const x of f)c.invalidateQueries({queryKey:x});u(l)},onError(x){u(x instanceof Error?x.message:"An unknown error occurred")}});return{mutate:h.mutate,isPending:h.isPending,notice:n.jsx(Yo,{open:m!=="",autoHideDuration:6e3,onClose:()=>u(""),message:m})}}const ua="https://docs.malloydata.dev/documentation",Un=`${ua}/user_guides/publishing`,wt="https://github.com/malloydata/publisher/blob/main/docs",Ke={docsHome:`${ua}/`,publishing:`${Un}/publishing`,explorer:`${Un}/explorer`,mcpAgents:`${Un}/mcp_agents`,surfaces:`${wt}/choosing-a-surface.md`,dashboards:`${wt}/dashboards.md`,dataApps:`${wt}/html-data-apps.md`,givens:`${wt}/givens.md`,materialization:`${wt}/materialization.md`,connections:`${wt}/connections.md`};function Go({resourceUri:t}){const[l,f]=A.useState(!1),{apiClients:a}=V.useServer(),{environmentName:p}=d.parseResourceUri(t),o=Tt({mutationFn(m){return a.packages.createPackage(p,{name:m.name,description:m.description,location:m.location})},success:"Package created",invalidates:[["packages",p]],closeDialog:()=>f(!1),resource:"package",action:"create"}),c=m=>{m.preventDefault();const u=new FormData(m.currentTarget),h=u.get("name")?.toString(),x=u.get("description")?.toString(),v=u.get("location")?.toString();o.mutate({name:h,description:x,location:v})};return n.jsxs(n.Fragment,{children:[n.jsx(d.AddButton,{label:"Package",onClick:()=>f(!0)}),n.jsx(d.AppDialog,{open:l,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(S.Box,{component:"a",href:Ke.publishing,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary"},children:"package format"}),"."]}),actions:n.jsxs(n.Fragment,{children:[n.jsx(S.Button,{disabled:o.isPending,onClick:()=>f(!1),children:"Cancel"}),n.jsx(S.Button,{type:"submit",form:"package-form",variant:"contained",loading:o.isPending,children:"Create package"})]}),children:n.jsx("form",{onSubmit:c,id:"package-form",children:n.jsxs(S.Stack,{sx:{gap:2},children:[n.jsx(S.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(S.TextField,{id:"description",name:"description",label:"Description",multiline:!0,rows:3,fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(S.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}})]})})}),o.notice]})}const Xo=d.createSvgIcon(n.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function Cn({icon:t,tint:l,label:f,mono:a,description:p,rightLabel:o,trailingAction:c,onClick:m,ariaLabel:u}){const h=!!m,x=v=>{m&&(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),m(v))};return n.jsxs(S.Box,{onClick:m,onKeyDown:h?x:void 0,role:h?"button":void 0,tabIndex:h?0:void 0,"aria-label":u,sx:v=>({display:"flex",alignItems:"center",gap:1.5,py:1,px:1,mx:-1,cursor:h?"pointer":"default",borderRadius:1.5,transition:"background-color 0.1s","&:hover":h?{backgroundColor:v.palette.mode==="dark"?"rgba(255, 255, 255, 0.08)":"grey.100"}:void 0,"&:focus-visible":h?{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}:void 0}),children:[n.jsx(S.Box,{sx:{width:32,height:32,borderRadius:1,bgcolor:l,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t}),n.jsxs(S.Box,{sx:{flex:1,minWidth:0,display:"flex",alignItems:"baseline",gap:1.5},children:[n.jsx(S.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(S.Typography,{variant:"body2",color:"text.secondary",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p})]}),o&&n.jsx(S.Typography,{variant:"caption",color:"text.secondary",sx:{flexShrink:0},children:o}),c&&n.jsx(S.Box,{sx:{flexShrink:0,display:"flex",alignItems:"center"},children:c})]})}const da=d.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"})),Ko=d.generateUtilityClasses("MuiBox",["root"]),Qo=d.createTheme(),me=ia.createBox({themeId:d.THEME_ID,defaultTheme:Qo,defaultClassName:Ko.root,generateClassName:d.ClassNameGenerator.generate}),Tn=ia.createStack({createStyledComponent:d.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:t=>d.useDefaultProps({props:t,name:"MuiStack"})}),Is=d.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function Jo(t){return d.generateUtilityClass("MuiListItemIcon",t)}const Fs=d.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),el=t=>{const{alignItems:l,classes:f}=t,a={root:["root",l==="flex-start"&&"alignItemsFlexStart"]};return d.composeClasses(a,Jo,f)},tl=d.styled("div",{name:"MuiListItemIcon",slot:"Root",overridesResolver:(t,l)=>{const{ownerState:f}=t;return[l.root,f.alignItems==="flex-start"&&l.alignItemsFlexStart]}})(d.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}}]}))),hr=he.forwardRef(function(l,f){const a=d.useDefaultProps({props:l,name:"MuiListItemIcon"}),{className:p,...o}=a,c=he.useContext(d.ListContext),m={...a,alignItems:c.alignItems},u=el(m);return n.jsx(tl,{className:d.clsx(u.root,p),ownerState:m,ref:f,...o})});function nl(t){return d.generateUtilityClass("MuiListItemText",t)}const Ct=d.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),rl=t=>{const{classes:l,inset:f,primary:a,secondary:p,dense:o}=t,c={root:["root",f&&"inset",o&&"dense",a&&p&&"multiline"],primary:["primary"],secondary:["secondary"]};return d.composeClasses(c,nl,l)},sl=d.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(t,l)=>{const{ownerState:f}=t;return[{[`& .${Ct.primary}`]:l.primary},{[`& .${Ct.secondary}`]:l.secondary},l.root,f.inset&&l.inset,f.primary&&f.secondary&&l.multiline,f.dense&&l.dense]}})({flex:"1 1 auto",minWidth:0,marginTop:4,marginBottom:4,[`.${d.typographyClasses.root}:where(& .${Ct.primary})`]:{display:"block"},[`.${d.typographyClasses.root}:where(& .${Ct.secondary})`]:{display:"block"},variants:[{props:({ownerState:t})=>t.primary&&t.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:t})=>t.inset,style:{paddingLeft:56}}]}),fr=he.forwardRef(function(l,f){const a=d.useDefaultProps({props:l,name:"MuiListItemText"}),{children:p,className:o,disableTypography:c=!1,inset:m=!1,primary:u,primaryTypographyProps:h,secondary:x,secondaryTypographyProps:v,slots:b={},slotProps:g={},...k}=a,{dense:w}=he.useContext(d.ListContext);let T=u??p,M=x;const D={...a,disableTypography:c,inset:m,primary:!!T,secondary:!!M,dense:w},I=rl(D),E={slots:b,slotProps:{primary:h,secondary:v,...g}},[L,z]=d.useSlot("root",{className:d.clsx(I.root,o),elementType:sl,externalForwardedProps:{...E,...k},ownerState:D,ref:f}),[P,Z]=d.useSlot("primary",{className:I.primary,elementType:d.Typography,externalForwardedProps:E,ownerState:D}),[N,q]=d.useSlot("secondary",{className:I.secondary,elementType:d.Typography,externalForwardedProps:E,ownerState:D});return T!=null&&T.type!==d.Typography&&!c&&(T=n.jsx(P,{variant:w?"body2":"body1",component:Z?.variant?void 0:"span",...Z,children:T})),M!=null&&M.type!==d.Typography&&!c&&(M=n.jsx(N,{variant:"body2",color:"textSecondary",...q,children:M})),n.jsxs(L,{...z,children:[T,M]})});function al(t){return d.generateUtilityClass("MuiMenuItem",t)}const Pt=d.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),il=(t,l)=>{const{ownerState:f}=t;return[l.root,f.dense&&l.dense,f.divider&&l.divider,!f.disableGutters&&l.gutters]},ol=t=>{const{disabled:l,dense:f,divider:a,disableGutters:p,selected:o,classes:c}=t,m={root:["root",f&&"dense",l&&"disabled",!p&&"gutters",a&&"divider",o&&"selected"]},u=d.composeClasses(m,al,c);return{...c,...u}},ll=d.styled(d.ButtonBase,{shouldForwardProp:t=>d.rootShouldForwardProp(t)||t==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:il})(d.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"}},[`&.${Pt.selected}`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,(t.vars||t).palette.action.selectedOpacity),[`&.${Pt.focusVisible}`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,`${(t.vars||t).palette.action.selectedOpacity} + ${(t.vars||t).palette.action.focusOpacity}`)}},[`&.${Pt.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)}},[`&.${Pt.focusVisible}`]:{backgroundColor:(t.vars||t).palette.action.focus},[`&.${Pt.disabled}`]:{opacity:(t.vars||t).palette.action.disabledOpacity},[`& + .${Is.root}`]:{marginTop:t.spacing(1),marginBottom:t.spacing(1)},[`& + .${Is.inset}`]:{marginLeft:52},[`& .${Ct.root}`]:{marginTop:0,marginBottom:0},[`& .${Ct.inset}`]:{paddingLeft:36},[`& .${Fs.root}`]:{minWidth:36},variants:[{props:({ownerState:l})=>!l.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:l})=>l.divider,style:{borderBottom:`1px solid ${(t.vars||t).palette.divider}`,backgroundClip:"padding-box"}},{props:({ownerState:l})=>!l.dense,style:{[t.breakpoints.up("sm")]:{minHeight:"auto"}}},{props:({ownerState:l})=>l.dense,style:{minHeight:32,paddingTop:4,paddingBottom:4,...t.typography.body2,[`& .${Fs.root} svg`]:{fontSize:"1.25rem"}}}]}))),ge=he.forwardRef(function(l,f){const a=d.useDefaultProps({props:l,name:"MuiMenuItem"}),{autoFocus:p=!1,component:o="li",dense:c=!1,divider:m=!1,disableGutters:u=!1,focusVisibleClassName:h,role:x="menuitem",tabIndex:v,className:b,...g}=a,k=he.useContext(d.ListContext),w=he.useMemo(()=>({dense:c||k.dense||!1,disableGutters:u}),[k.dense,c,u]),T=he.useRef(null);d.useEnhancedEffect(()=>{p&&T.current&&T.current.focus()},[p]);const M={...a,dense:w.dense,divider:m,disableGutters:u},D=ol(a),I=d.useForkRef(T,f);let E;return a.disabled||(E=v!==void 0?v:-1),n.jsx(d.ListContext.Provider,{value:w,children:n.jsx(ll,{ref:I,role:x,tabIndex:E,component:o,focusVisibleClassName:d.clsx(D.focusVisible,h),className:d.clsx(D.root,b),...g,ownerState:M,classes:D})})}),Je={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:[]},Xt={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",trino:"trinoConnection",databricks:"databricksConnection",mysql:"mysqlConnection",duckdb:"duckdbConnection",motherduck:"motherduckConnection",ducklake:"ducklakeConnection",publisher:"publisherConnection"},ha=Object.values(V.ConnectionTypeEnum).filter(t=>t!==V.ConnectionTypeEnum.Publisher),rr={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},Jt=[{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"}}],en=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],cl=[{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 vn(t){return t==="postgres"||t==="bigquery"||t==="snowflake"?Je[t]||[]:t==="s3"?Jt:t==="gcs"?en:t==="azure"?cl:[]}function ul({onSubmit:t,isSubmitting:l}){const[f,a]=A.useState(!1),[p,o]=A.useState("postgres"),[c,m]=A.useState([]),[u,h]=A.useState("postgres"),[x,v]=A.useState("s3"),[b,g]=A.useState("config"),k=()=>{a(!0)},w=()=>{a(!1),m([]),o("postgres"),h("postgres"),v("s3"),g("config")},T=async E=>{E.preventDefault();const L=new FormData(E.currentTarget),z=L.get("name")?.toString(),P=L.get("type")?.toString(),Z=Je[P];if(!z)throw new Error("Name is required");if(!P)throw new Error("Type is required");let N;if(P==="ducklake"){const q={};if(u==="postgres"){const _=Je.postgres,Y={};if(_.forEach(Q=>{const K=L.get(`ducklake_pg_${Q.name}`)?.toString();K&&(Y[Q.name]=K)}),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 R={bucketUrl:U};if(x==="s3"){const _={};if(Jt.forEach(Y=>{const Q=L.get(`ducklake_s3_${Y.name}`)?.toString();Q&&(_[Y.name]=Q)}),_.provider==="credential_chain")delete _.accessKeyId,delete _.secretAccessKey,delete _.sessionToken;else{if(delete _.chain,!_.accessKeyId)throw new Error("S3 Access Key ID is required");if(!_.secretAccessKey)throw new Error("S3 Secret Access Key is required")}Object.keys(_).length>0&&(R.s3Connection=_)}else if(x==="gcs"){const _={};if(en.forEach(Y=>{const Q=L.get(`ducklake_gcs_${Y.name}`)?.toString();Q&&(_[Y.name]=Q)}),!_.keyId)throw new Error("GCS Key ID is required");if(!_.secret)throw new Error("GCS Secret is required");Object.keys(_).length>0&&(R.gcsConnection=_)}N={name:z,type:P,ducklakeConnection:{catalog:q,storage:R}}}else if(P==="duckdb"){if(c.length===0)throw new Error("DuckDB connection must have at least one attached database");const q=c.map((U,R)=>{const _=U.dbType,Y=L.get(`attachedDb_${R}_name`)?.toString();if(!Y)throw new Error(`Attached database at index ${R} must have a name`);const Q={name:Y,type:_},K=vn(_);if(K&&K.length>0){const ee={};if(K.forEach(te=>{const W=L.get(`attachedDb_${R}_${te.name}`)?.toString();W&&(ee[te.name]=W)}),_==="s3"){if(ee.provider==="credential_chain")delete ee.accessKeyId,delete ee.secretAccessKey,delete ee.sessionToken;else if(delete ee.chain,!ee.accessKeyId||!ee.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=rr[_];B&&(Q[B]=ee)}return Q});N={name:z,type:P,duckdbConnection:{attachedDatabases:q}}}else{const q={};if(Z.forEach(U=>{const R=L.get(U.name)?.toString();R&&(q[U.name]=R)}),P==="postgres"){if(!!!q.connectionString?.trim()){const R=["host","port","databaseName","userName","password"];for(const _ of R)if(!q[_])throw new Error(`${Z.find(Y=>Y.name===_)?.label||_} is required`)}}else if(P==="bigquery"){if(!q.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if(P==="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(P==="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(P==="mysql"){const U=["host","port","database","user","password"];for(const R of U)if(!q[R])throw new Error(`${Z.find(_=>_.name===R)?.label||R} is required`)}else if(P==="motherduck"){if(!q.accessToken)throw new Error("Access Token is required")}else if(P==="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:z,type:P,[Xt[P]]:q}}await t(N),w()},M=()=>{m([...c,{name:"",dbType:"postgres"}])},D=E=>{m(c.filter((L,z)=>z!==E))},I=(E,L)=>{const z=[...c];z[E]={...z[E],dbType:L},m(z)};return n.jsxs(A.Fragment,{children:[n.jsx(d.AddButton,{label:"Connection",onClick:k}),n.jsx(d.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(d.Button,{disabled:l,onClick:w,children:"Cancel"}),n.jsx(d.Button,{type:"submit",form:"connection-form",variant:"contained",loading:l,children:"Create connection"})]}),children:n.jsx("form",{onSubmit:T,id:"connection-form",children:n.jsxs(Tn,{sx:{gap:2},children:[n.jsx(d.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small"}),n.jsx(d.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:p,select:!0,onChange:E=>o(E.target.value),children:ha.map(E=>n.jsx(ge,{value:E,children:E},E))}),p==="ducklake"?n.jsxs(me,{sx:{mt:2},children:[n.jsxs(me,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(d.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),n.jsx(d.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:u,select:!0,onChange:E=>h(E.target.value),children:n.jsx(ge,{value:"postgres",children:"PostgreSQL"})}),u==="postgres"&&n.jsx(n.Fragment,{children:Je.postgres.map(E=>n.jsx(d.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(me,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(d.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),n.jsxs(d.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:x,select:!0,onChange:E=>v(E.target.value),children:[n.jsx(ge,{value:"s3",children:"S3"}),n.jsx(ge,{value:"gcs",children:"GCS"})]}),n.jsx(d.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(d.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),Jt.filter(E=>E.visibleWhen?b===E.visibleWhen.value:!0).map(E=>n.jsx(d.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(ge,{value:L.value,children:L.label},L.value))},`s3_${E.name}`))]}),x==="gcs"&&n.jsxs(n.Fragment,{children:[n.jsx(d.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),en.map(E=>n.jsx(d.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(me,{sx:{mt:2},children:[n.jsxs(me,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsx(d.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),n.jsx(d.SecondaryButton,{label:"Database",icon:n.jsx(d.AddIcon,{}),onClick:M,ariaLabel:"Add database"})]}),c.length===0&&n.jsx(d.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),c.map((E,L)=>{const z=vn(E.dbType);return n.jsxs(me,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsxs(me,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsxs(d.Typography,{variant:"subtitle2",children:["Database ",L+1]}),n.jsx(d.IconButton,{onClick:()=>D(L),size:"small",color:"error",children:n.jsx(da,{fontSize:"small"})})]}),n.jsx(d.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(d.TextField,{id:`attachedDb_${L}_type`,name:`attachedDb_${L}_type`,label:"Database Type",fullWidth:!0,size:"small",value:E.dbType,select:!0,onChange:P=>I(L,P.target.value),children:Object.values(V.AttachedDatabaseTypeEnum).map(P=>n.jsx(ge,{value:P,children:P},P))}),z.filter(P=>P.visibleWhen?(E[P.visibleWhen.field]||z.find(N=>N.name===P.visibleWhen?.field)?.selectOptions?.[0]?.value)===P.visibleWhen.value:!0).map(P=>n.jsx(d.TextField,{id:`attachedDb_${L}_${P.name}`,name:`attachedDb_${L}_${P.name}`,label:P.label,type:P.selectOptions?void 0:P.type,fullWidth:!0,size:"small",required:P.required,select:!!P.selectOptions,defaultValue:P.selectOptions?.[0]?.value,onChange:P.selectOptions?Z=>{const N=[...c];N[L]={...N[L],[P.name]:Z.target.value},m(N)}:void 0,children:P.selectOptions?.map(Z=>n.jsx(ge,{value:Z.value,children:Z.label},Z.value))},P.name))]},L)})]}):Je[p].map(E=>n.jsx(d.TextField,{id:E.name,name:E.name,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required},E.name))]})})})]})}function dl({connection:t,onCloseDialog:l,isMutating:f,onDelete:a}){const[p,o]=A.useState(!1),c=()=>{o(!0)},m=()=>{o(!1),l()};return n.jsxs(A.Fragment,{children:[n.jsxs(ge,{"aria-label":`Delete connection ${t?.name??""}`.trim(),onClick:u=>{u.stopPropagation(),c()},sx:{color:"error.main"},children:[n.jsx(hr,{sx:{color:"inherit"},children:n.jsx(Ve.Delete,{fontSize:"small"})}),n.jsx(fr,{children:"Delete"})]}),n.jsx(d.AppDialog,{open:p,onClose:m,title:"Delete connection",actions:n.jsxs(n.Fragment,{children:[n.jsx(d.Button,{onClick:m,children:"Cancel"}),n.jsx(d.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>a(),loading:f,children:"Delete connection"})]}),children:n.jsxs(d.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:t.name}),"? Packages that query through it stop working, and this cannot be undone."]})})]})}const Ns=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function As(t){const l=t.duckdbConnection?.attachedDatabases;return!l||l.length===0?[]:l.map(f=>({name:f.name||"",dbType:f.type||"postgres"}))}function $s(t){const l=t.ducklakeConnection;return l&&l.storage?.gcsConnection?"gcs":"s3"}function hl({connection:t,onSubmit:l,isSubmitting:f,onCloseDialog:a}){const[p,o]=A.useState(!1),[c,m]=A.useState(t.type),u=A.useMemo(()=>new Set(t.withheldFields??[]),[t.withheldFields]),[h,x]=A.useState(()=>As(t)),[v,b]=A.useState("postgres"),[g,k]=A.useState(()=>$s(t)),[w,T]=A.useState(()=>t.ducklakeConnection?.storage?.s3Connection?.provider??"config"),M=()=>{x(As(t)),m(t.type),T(t.ducklakeConnection?.storage?.s3Connection?.provider??"config"),b("postgres"),k($s(t)),o(!0)},D=()=>{o(!1),a?.()},I=async N=>{N.preventDefault();const q=new FormData(N.currentTarget),U=q.get("name")?.toString(),R=q.get("type")?.toString(),_=Je[R];if(!U)throw new Error("Name is required");if(!R)throw new Error("Type is required");let Y;if(R==="ducklake"){const Q={};if(v==="postgres"){const B=Je.postgres,te={};if(B.forEach(W=>{const J=q.get(`ducklake_pg_${W.name}`)?.toString();J&&(te[W.name]=J)}),Object.keys(te).length===0)throw new Error("DuckLake requires catalog connection");Q.postgresConnection=te}const K=q.get("ducklake_bucketUrl")?.toString();if(!K)throw new Error("DuckLake requires a bucket URL");const ee={bucketUrl:K};if(g==="s3"){const B={};Jt.forEach(W=>{const J=q.get(`ducklake_s3_${W.name}`)?.toString();J&&(B[W.name]=J)});const te=t.ducklakeConnection?.storage?.s3Connection;if(te&&(!B.provider&&te.provider&&(B.provider=te.provider),!B.chain&&te.chain&&(B.chain=te.chain),!B.accessKeyId&&te.accessKeyId&&(B.accessKeyId=te.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&&(ee.s3Connection=B)}else if(g==="gcs"){const B={};en.forEach(W=>{const J=q.get(`ducklake_gcs_${W.name}`)?.toString();J&&(B[W.name]=J)});const te=t.ducklakeConnection?.storage?.gcsConnection;if(te&&!B.keyId&&te.keyId&&(B.keyId=te.keyId),!B.keyId)throw new Error("GCS Key ID is required");Object.keys(B).length>0&&(ee.gcsConnection=B)}Y={name:U,type:R,ducklakeConnection:{catalog:Q,storage:ee}}}else if(R==="duckdb"){if(h.length===0)throw new Error("DuckDB connection must have at least one attached database");const Q=h.map((K,ee)=>{const B=K.dbType,te=q.get(`attachedDb_${ee}_name`)?.toString();if(!te)throw new Error(`Attached database at index ${ee} must have a name`);const W={name:te,type:B},J=vn(B);if(J&&J.length>0){const $={};if(J.forEach(le=>{const G=q.get(`attachedDb_${ee}_${le.name}`)?.toString();G&&($[le.name]=G)}),B==="s3"){if($.provider==="credential_chain")delete $.accessKeyId,delete $.secretAccessKey,delete $.sessionToken;else if(delete $.chain,!$.accessKeyId||!$.secretAccessKey)throw new Error(`Attached database "${te}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const X=rr[B];X&&(W[X]=$)}return W});Y={name:U,type:R,duckdbConnection:{attachedDatabases:Q}}}else{const Q=t[Xt[R]]||{},K={};if(_.forEach(ee=>{const B=q.get(ee.name)?.toString(),te=Q[ee.name];B?K[ee.name]=B:Ns.has(ee.name)||(B!==void 0?K[ee.name]=B:te&&(K[ee.name]=te))}),R==="postgres"){const ee=["host","port","databaseName","userName"],B=u.has("postgresConnection.connectionString");if(!(!!K.connectionString?.trim()||B)){const W=ee;for(const J of W)if(!K[J])throw new Error(`${_.find($=>$.name===J)?.label||J} is required`)}}else if(R==="snowflake"){if(!K.account)throw new Error("Account is required");if(!K.username)throw new Error("Username is required");if(!K.warehouse)throw new Error("Warehouse is required")}else if(R==="trino"){if(!K.server)throw new Error("Server is required");if(!K.user)throw new Error("User is required")}else if(R==="mysql"){const ee=["host","port","database","user"];for(const B of ee)if(!K[B])throw new Error(`${_.find(te=>te.name===B)?.label||B} is required`)}else if(R==="databricks"){if(!K.host)throw new Error("Host is required");if(!K.path)throw new Error("HTTP Path is required")}Y={name:U,type:R,[Xt[R]]:K}}await l(Y),D()},E=()=>{x([...h,{name:"",dbType:"postgres"}])},L=N=>{x(h.filter((q,U)=>U!==N))},z=(N,q)=>{const U=[...h];U[N]={...U[N],dbType:q},x(U)},P=(N,q)=>{const U=t.duckdbConnection?.attachedDatabases;if(!U||!U[N])return"";const R=U[N],_=rr[R.type||""];return _&&R[_]?R[_][q]??"":""},Z=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(A.Fragment,{children:[n.jsxs(ge,{"aria-label":`Edit connection ${t?.name??""}`.trim(),onClick:N=>{N.preventDefault(),N.stopPropagation(),M()},children:[n.jsx(hr,{children:n.jsx(Ve.Edit,{fontSize:"small"})}),n.jsx(fr,{children:"Edit"})]}),n.jsx(d.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(d.Button,{disabled:f,onClick:D,children:"Cancel"}),n.jsx(d.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(Tn,{sx:{gap:2},children:[n.jsx(d.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",defaultValue:t.name}),n.jsx(d.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:c,select:!0,onChange:N=>m(N.target.value),children:ha.map(N=>n.jsx(ge,{value:N,children:N},N))}),c==="ducklake"?n.jsxs(me,{sx:{mt:2},children:[n.jsxs(me,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(d.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),n.jsx(d.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:v,select:!0,onChange:N=>b(N.target.value),children:n.jsx(ge,{value:"postgres",children:"PostgreSQL"})}),v==="postgres"&&n.jsx(n.Fragment,{children:Je.postgres.map(N=>n.jsx(d.TextField,{id:`ducklake_pg_${N.name}`,name:`ducklake_pg_${N.name}`,label:N.label,type:N.type,fullWidth:!0,size:"small",defaultValue:Z(`pg_${N.name}`)},`pg_${N.name}`))})]}),n.jsxs(me,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(d.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),n.jsxs(d.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:g,select:!0,onChange:N=>k(N.target.value),children:[n.jsx(ge,{value:"s3",children:"S3"}),n.jsx(ge,{value:"gcs",children:"GCS"})]}),n.jsx(d.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:Z("bucketUrl")}),g==="s3"&&n.jsxs(n.Fragment,{children:[n.jsx(d.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),Jt.filter(N=>N.visibleWhen?w===N.visibleWhen.value:!0).map(N=>n.jsx(d.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:Z(`s3_${N.name}`),onChange:N.name==="provider"?q=>T(q.target.value):void 0,placeholder:N.name==="region"?"us-east-1":N.name==="secretAccessKey"&&u.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:N.selectOptions?.map(q=>n.jsx(ge,{value:q.value,children:q.label},q.value))},`s3_${N.name}`))]}),g==="gcs"&&n.jsxs(n.Fragment,{children:[n.jsx(d.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),en.map(N=>n.jsx(d.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:Z(`gcs_${N.name}`),placeholder:N.name==="secret"&&u.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${N.name}`))]})]})]}):c==="duckdb"?n.jsxs(me,{sx:{mt:2},children:[n.jsxs(me,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsx(d.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),n.jsx(d.SecondaryButton,{label:"Database",icon:n.jsx(d.AddIcon,{}),onClick:E,ariaLabel:"Add database"})]}),h.length===0&&n.jsx(d.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),h.map((N,q)=>{const U=vn(N.dbType);return n.jsxs(me,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsxs(me,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsxs(d.Typography,{variant:"subtitle2",children:["Database ",q+1]}),n.jsx(d.IconButton,{"aria-label":`Remove attached database ${q+1}`,onClick:()=>L(q),size:"small",color:"error",children:n.jsx(da,{fontSize:"small"})})]}),n.jsx(d.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(d.TextField,{id:`attachedDb_${q}_type`,name:`attachedDb_${q}_type`,label:"Database Type",fullWidth:!0,size:"small",value:N.dbType,select:!0,onChange:R=>z(q,R.target.value),children:Object.values(V.AttachedDatabaseTypeEnum).map(R=>n.jsx(ge,{value:R,children:R},R))}),U.filter(R=>R.visibleWhen?(N[R.visibleWhen.field]||P(q,R.visibleWhen.field)||U.find(Y=>Y.name===R.visibleWhen?.field)?.selectOptions?.[0]?.value)===R.visibleWhen.value:!0).map(R=>n.jsx(d.TextField,{id:`attachedDb_${q}_${R.name}`,name:`attachedDb_${q}_${R.name}`,label:R.label,type:R.selectOptions?void 0:R.type,fullWidth:!0,size:"small",required:R.required,select:!!R.selectOptions,defaultValue:P(q,R.name)||R.selectOptions?.[0]?.value,onChange:R.selectOptions?_=>{const Y=[...h];Y[q]={...Y[q],[R.name]:_.target.value},x(Y)}:void 0,children:R.selectOptions?.map(_=>n.jsx(ge,{value:_.value,children:_.label},_.value))},R.name))]},q)})]}):Je[c].map(N=>{const q=t?.[Xt[c]??""]?.[N.name??""]??"",U=N.type==="password"||Ns.has(N.name),R=u.has(`${Xt[c]??""}.${N.name}`);return n.jsx(d.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:R?"Leave empty to keep existing":void 0,helperText:U?R?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0},N.name)})]})})})]})}function Rs(t,l){return!t||t.type!=="duckdb"?!1:(t.duckdbConnection?.attachedDatabases||[]).some(a=>a.type==="azure"&&a.name===l)}function fl(t){return t.startsWith("gs://")||t.startsWith("s3://")||t.startsWith("https://")||t.startsWith("abfss://")||t.startsWith("az://")}function fa({connectionName:t,resourceUri:l,schema:f,connection:a}){const{apiClients:p}=V.useServer(),{environmentName:o}=d.parseResourceUri(l),[c,m]=A.useState(null),[u,h]=A.useState(f||null),[x,v]=A.useState(!1),{data:b,isError:g,isLoading:k,error:w}=d.useQueryWithApiError({queryKey:["schemas",o,t],queryFn:()=>p.connections.listSchemas(o,t)}),T=b?.data||[];return n.jsxs(S.Grid,{container:!0,spacing:1,children:[!f&&n.jsx(S.Grid,{size:{xs:12,md:4},children:n.jsxs(S.Paper,{sx:{p:1,m:0},children:[n.jsxs(S.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:0},children:[n.jsx(S.Typography,{variant:"overline",fontWeight:"bold",children:"Table Paths"}),n.jsx(S.FormControlLabel,{control:n.jsx(S.Switch,{checked:x,onChange:M=>v(M.target.checked)}),label:"Hidden Schemas"})]}),n.jsx(S.Divider,{sx:{mt:"2px"}}),n.jsxs(S.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[k&&n.jsx(d.Loading,{text:"Loading schemas..."}),g&&n.jsx(d.ApiErrorDisplay,{error:w,context:`${o} > ${t} > Schemas`}),!k&&!g&&T.length===0&&n.jsx(S.Typography,{variant:"body2",children:"No Schemas"}),!k&&!g&&T.length>0&&n.jsx(S.List,{dense:!0,disablePadding:!0,children:T.map(M=>{const D=M.name;if(M.isHidden&&!x)return null;const E=u===D;return n.jsx(S.ListItemButton,{selected:E,onClick:()=>{h(D),m(null)},children:n.jsx(S.ListItemText,{primary:D})},D)})})]})]})}),n.jsx(S.Grid,{size:{xs:12,md:f?6:4},children:u&&n.jsx(S.Paper,{sx:{p:1,m:0},children:n.jsx(yl,{connectionName:t,schemaName:u,onTableSelect:M=>{m(M)},resourceUri:l,connection:a})})}),n.jsx(S.Grid,{size:{xs:12,md:f?6:4},children:u&&c&&n.jsx(ml,{environmentName:o,connectionName:t,schemaName:u,tableResource:c})})]})}function ml({environmentName:t,connectionName:l,schemaName:f,tableResource:a}){const{apiClients:p}=V.useServer(),{data:o,isLoading:c,isError:m,error:u}=d.useQueryWithApiError({queryKey:["connectionTableDetail",t,l,f,a],queryFn:()=>p.connections.getTable(t,l,f,a),enabled:!!f&&!!a}),h={resource:o?.data?.resource??a,columns:o?.data?.columns??[]};return n.jsxs(S.Paper,{sx:{p:1,m:0},children:[m&&n.jsx(d.ApiErrorDisplay,{error:u,context:`${t} > ${l} > ${f} > ${a}`}),!m&&n.jsx(pl,{table:h,loading:c})]})}function pl({table:t,loading:l}){return l?n.jsx(d.Loading,{text:"Loading columns..."}):n.jsxs(n.Fragment,{children:[n.jsxs(S.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(S.Divider,{}),n.jsx(S.Box,{sx:{mt:"10px",maxHeight:"600px",overflowY:"auto"},children:n.jsx(S.TableContainer,{children:n.jsxs(S.Table,{size:"small",sx:{"& .MuiTableCell-root":{padding:"10px"}},children:[n.jsx(S.TableHead,{children:n.jsxs(S.TableRow,{children:[n.jsx(S.TableCell,{children:"NAME"}),n.jsx(S.TableCell,{children:"TYPE"})]})}),n.jsx(S.TableBody,{children:t.columns?.sort((f,a)=>f.name.localeCompare(a.name))?.map(f=>n.jsxs(S.TableRow,{children:[n.jsx(S.TableCell,{children:f.name}),n.jsx(S.TableCell,{children:f.type})]},f.name))})]})})})]})}function yl({connectionName:t,schemaName:l,onTableSelect:f,resourceUri:a,connection:p}){const{environmentName:o}=d.parseResourceUri(a),{apiClients:c}=V.useServer(),[m,u]=A.useState(""),{data:h,isSuccess:x,isError:v,error:b,isLoading:g}=d.useQueryWithApiError({queryKey:["tablesInSchema",o,t,l],queryFn:()=>c.connections.listTables(o,t,l)}),k=Rs(p,l),w=M=>k?M:M.split(".").pop()||M,T=x&&h?.data?h.data.filter(M=>w(M.resource).toLowerCase().includes(m.toLowerCase())).sort((M,D)=>w(M.resource).localeCompare(w(D.resource))):[];return n.jsxs(n.Fragment,{children:[n.jsx(S.Typography,{variant:"overline",fontWeight:"bold",children:fl(l)||Rs(p,l)?`Files in ${l}`:`Tables in ${l}`}),n.jsx(S.Divider,{}),n.jsx(S.Box,{sx:{mt:1,mb:1},children:n.jsx(S.TextField,{size:"small",fullWidth:!0,placeholder:"Search tables...",value:m,onChange:M=>u(M.target.value),variant:"outlined"})}),n.jsx(S.Divider,{}),n.jsxs(S.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[g&&n.jsx(d.Loading,{text:"Fetching Tables..."}),v&&n.jsx(d.ApiErrorDisplay,{error:b,context:`${o} > ${t} > ${l}`}),x&&T.length===0&&n.jsx(S.Typography,{variant:"body2",children:"No Tables"}),x&&h?.data&&h.data.length>0&&n.jsx(S.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(S.ListItemButton,{onClick:()=>f(M.resource),children:n.jsx(S.ListItemText,{primary:D,secondary:M.columns.length>0?`${M.columns.length} columns`:void 0})},M.resource)})})]})]})}const gl={bigquery:"BigQuery",snowflake:"Snowflake",postgres:"PostgreSQL",mysql:"MySQL",trino:"Trino",databricks:"Databricks",duckdb:"DuckDB",ducklake:"DuckLake",s3:"S3",gcs:"GCS",azure:"Azure"};function xl(t){return t?gl[t]??t:""}function bl({resourceUri:t}){const{apiClients:l,mutable:f}=V.useServer(),a=kn.useQueryClient(),{environmentName:p}=d.parseResourceUri(t),[o,c]=A.useState(""),[m,u]=A.useState(null),h=d.encodeResourceUri({environmentName:p,connectionName:m}),{data:x,isSuccess:v,isError:b,error:g}=d.useQueryWithApiError({queryKey:["connections",p],queryFn:()=>l.connections.listConnections(p)}),k=d.useMutationWithApiError({mutationFn:Qe("connection","create",I=>l.environments.updateEnvironment(p,{name:p,connections:[...x.data,I]})),onSuccess(){c("Connection added successfully"),a.invalidateQueries({queryKey:["connections",p]})},onError(I){c(I.message)}}),w=d.useMutationWithApiError({mutationFn:Qe("connection","update",I=>l.environments.updateEnvironment(p,{name:p,connections:x.data.map(E=>E.name===I.name?I:E)})),onSuccess(I,E){c(`Connection ${E.name} updated successfully`),a.invalidateQueries({queryKey:["connections",p]})},onError(I){c(I.message)}}),T=d.useMutationWithApiError({mutationFn:Qe("connection","delete",I=>{if(!I.name)throw new Error("Cannot delete a connection with no name");return l.connections.deleteConnection(p,I.name)}),onSuccess(I,E){c(`Connection ${E.name} deleted successfully`),a.invalidateQueries({queryKey:["connections",p]})},onError(I){c(I.message)}}),M=v?[...x.data].sort((I,E)=>(I.name??"").localeCompare(E.name??"")):[],D=k.isPending||w.isPending||T.isPending;return n.jsxs(He,{title:"Connections",...v?{count:M.length}:{},description:"Database connections available to packages in this environment",...f&&v?{action:n.jsx(ul,{onSubmit:I=>k.mutateAsync(I),isSubmitting:k.isPending})}:{},children:[!v&&!b&&n.jsx(S.Typography,{variant:"body2",color:"text.secondary",children:"Fetching Connections..."}),b&&n.jsx(d.ApiErrorDisplay,{error:g,context:`${p} > Connections`}),v&&M.length===0&&n.jsx(S.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),v&&M.length>0&&n.jsx(S.Stack,{children:M.map(I=>n.jsx(vl,{connection:I,mutable:f,isMutating:D,onOpenExplorer:()=>u(I.name??null),onEdit:E=>w.mutateAsync(E),onDelete:E=>T.mutateAsync(E)},I.name))}),n.jsx(S.Snackbar,{open:o!=="",autoHideDuration:6e3,onClose:()=>c(""),message:o}),n.jsx(d.AppDialog,{open:m!==null,onClose:()=>u(null),maxWidth:"lg",title:`Connection explorer: ${m??""}`,showClose:!0,children:m&&n.jsx(fa,{resourceUri:h,connectionName:m,connection:x?.data?.find(I=>I.name===m)})})]})}function vl({connection:t,mutable:l,isMutating:f,onOpenExplorer:a,onEdit:p,onDelete:o}){const[c,m]=A.useState(null),u=!!c,h=v=>{v.stopPropagation(),m(v.currentTarget)},x=()=>m(null);return n.jsx(Cn,{icon:n.jsx(Xo,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.connection,label:t.name??"",ariaLabel:t.name??"",description:xl(t.type),onClick:a,...l?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(S.IconButton,{size:"small",onClick:h,"aria-label":`Connection actions for ${t.name??""}`.trim(),children:n.jsx(Ve.MoreVert,{fontSize:"small"})}),n.jsxs(S.Menu,{anchorEl:c,open:u,onClose:x,onClick:v=>v.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(hl,{connection:t,onSubmit:p,isSubmitting:f,onCloseDialog:x}),n.jsx(dl,{connection:t,onCloseDialog:x,isMutating:f,onDelete:()=>o(t)})]})]})}:{}})}const Sl=d.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 wl({resourceUri:t,onCloseDialog:l}){const[f,a]=A.useState(!1),{apiClients:p}=V.useServer(),o=()=>{a(!0)},c=()=>{a(!1),l()},{environmentName:m,packageName:u}=d.parseResourceUri(t),h=Tt({mutationFn:()=>p.packages.deletePackage(m,u),success:"Package deleted",invalidates:[["packages",m]],closeDialog:c,resource:"package",action:"delete"});return n.jsxs(A.Fragment,{children:[n.jsxs(S.MenuItem,{onClick:o,children:[n.jsx(S.ListItemIcon,{children:n.jsx(Ve.Delete,{fontSize:"small"})}),n.jsx(S.ListItemText,{children:"Delete"})]}),n.jsx(d.AppDialog,{open:f,onClose:c,title:"Delete package",actions:n.jsxs(n.Fragment,{children:[n.jsx(d.Button,{onClick:c,children:"Cancel"}),n.jsx(d.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>h.mutate(),loading:h.isPending,children:"Delete package"})]}),children:n.jsxs(d.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:u}),"? The package stops being served and this cannot be undone."]})}),h.notice]})}function kl({package:t,resourceUri:l,onCloseDialog:f}){const[a,p]=A.useState(!1),{apiClients:o}=V.useServer(),c=()=>{p(!0)},m=()=>{p(!1),f()},{packageName:u,environmentName:h}=d.parseResourceUri(l),x=Tt({mutationFn(b){return o.packages.updatePackage(h,u,{name:u,description:b.description})},success:"Package updated",invalidates:[["packages",h]],closeDialog:m,resource:"package",action:"update"}),v=b=>{b.preventDefault();const k=new FormData(b.currentTarget).get("description")?.toString();x.mutate({description:k})};return n.jsxs(A.Fragment,{children:[n.jsxs(S.MenuItem,{onClick:c,children:[n.jsx(S.ListItemIcon,{children:n.jsx(Ve.Edit,{fontSize:"small"})}),n.jsx(S.ListItemText,{children:"Edit"})]}),n.jsx(d.AppDialog,{open:a,onClose:m,title:"Edit package",description:`What ${t.name} is, for the people who open it.`,actions:n.jsxs(n.Fragment,{children:[n.jsx(d.Button,{disabled:x.isPending,onClick:m,children:"Cancel"}),n.jsx(d.Button,{type:"submit",form:"package-form",variant:"contained",loading:x.isPending,children:"Save changes"})]}),children:n.jsx("form",{onSubmit:v,id:"package-form",children:n.jsxs(S.Stack,{sx:{gap:2},children:[n.jsx(d.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(d.TextField,{id:"description",name:"description",label:"Description",multiline:!0,fullWidth:!0,rows:4,size:"small",defaultValue:t.description,InputLabelProps:{shrink:!0}})]})})}),x.notice]})}function ma({onSelectPackage:t,resourceUri:l}){const{apiClients:f}=V.useServer(),{environmentName:a}=d.parseResourceUri(l),{data:p,isSuccess:o,isError:c,error:m}=d.useQueryWithApiError({queryKey:["packages",a],queryFn:()=>f.packages.listPackages(a)});if(c)return n.jsx(d.ApiErrorDisplay,{error:m,context:`${a} > Packages`});if(!o)return n.jsx(d.Loading,{text:"Fetching Packages..."});const u=[...p.data].sort((h,x)=>h.name.localeCompare(x.name));return n.jsx(S.Stack,{children:u.map(h=>{const x=d.encodeResourceUri({environmentName:a,packageName:h.name});return n.jsx(Cl,{pkg:h,packageResourceUri:x,onSelectPackage:t},h.name)})})}function Cl({pkg:t,packageResourceUri:l,onSelectPackage:f}){const{mutable:a}=V.useServer(),[p,o]=A.useState(null),c=!!p,m=h=>{h.stopPropagation(),o(h.currentTarget)},u=()=>o(null);return n.jsx(Cn,{icon:n.jsx(Sl,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.package,label:t.name,ariaLabel:t.name,...t.description?{description:t.description}:{},onClick:h=>f(t.name,h),...a?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(S.IconButton,{size:"small",onClick:m,"aria-label":`Package actions for ${t.name}`,children:n.jsx(Ve.MoreVert,{fontSize:"small"})}),n.jsxs(S.Menu,{anchorEl:p,open:c,onClose:u,onClick:h=>h.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(kl,{package:t,resourceUri:l,onCloseDialog:u}),n.jsx(wl,{resourceUri:l,onCloseDialog:u})]})]})}:{}})}function Tl({onSelectPackage:t,resourceUri:l}){const{apiClients:f,mutable:a}=V.useServer(),{environmentName:p}=d.parseResourceUri(l),o=d.useQueryWithApiError({queryKey:["packages",p],queryFn:()=>f.packages.listPackages(p)});return A.useEffect(()=>{window.scrollTo({top:0,behavior:"auto"})},[]),n.jsxs(S.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[n.jsxs(S.Box,{sx:{mb:4},children:[n.jsx(S.Box,{children:n.jsx(dr,{label:"Publisher",onClick:c=>t("/",c)})}),n.jsx(S.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em",mb:.5},children:p}),n.jsx(S.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(He,{title:"Packages",...o.isSuccess?{count:o.data.data.length}:{},description:"Published packages available for use in this environment",...a?{action:n.jsx(Go,{resourceUri:l})}:{},children:n.jsx(ma,{onSelectPackage:t,resourceUri:l})}),n.jsx(bl,{resourceUri:l}),n.jsx(Ao,{resourceUri:l})]})}d.dayjs.extend(d.utc);function Bn(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 Ml(t){return t==="DateMinMax"}function Yn(t){return t==="Between"}function Dl({spec:t,values:l,selection:f,onChange:a,retrievalFn:p}){const o=()=>f?.matchType?f.matchType:t.defaultMatchType?t.defaultMatchType:t.filterType==="DateMinMax"?"Between":Bn(t.filterType)[0]||"Equals",[c,m]=A.useState(o()),[u,h]=A.useState(f?.value??""),[x,v]=A.useState(f?.value2??""),[b,g]=A.useState([]),[k,w]=A.useState(!1),[T,M]=A.useState(""),[D,I]=A.useState(!1),[E,L]=A.useState(!1),z=A.useRef(null),P=A.useRef(0),[Z,N]=A.useState(!1);A.useEffect(()=>{if(t.filterType!=="Retrieval"||!p)return;const W=T.trim();if(W.length<=2){g([]),I(!1);return}return z.current&&clearTimeout(z.current),z.current=setTimeout(async()=>{P.current+=1;const J=P.current;w(!0);try{const $=await p(W,t);J===P.current&&g($)}catch($){J===P.current&&(console.error("Retrieval failed",$),g([]))}finally{J===P.current&&(w(!1),I(!0))}},500),()=>{z.current&&clearTimeout(z.current)}},[T,t,p]),A.useEffect(()=>{f===null?(h(""),v(""),m(t.defaultMatchType??(t.filterType==="DateMinMax"?"Between":Bn(t.filterType)[0]||"Equals"))):f&&(m(f.matchType),h(f.value??""),v(f.value2??""))},[f,t.filterType,t.defaultMatchType]);const q=Bn(t.filterType),U=Ml(t.filterType),R=Yn(c),_=U&&l.length>=2&&l[0].value instanceof Date?d.dayjs.utc(l[0].value):void 0,Y=U&&l.length>=2&&l[1].value instanceof Date?d.dayjs.utc(l[1].value):void 0,Q=t.filterType==="MinMax"&&l.length>=2&&typeof l[0].value=="number"?l[0].value:void 0,K=t.filterType==="MinMax"&&l.length>=2&&typeof l[1].value=="number"?l[1].value:void 0;if(q.length===0)return null;const ee=W=>{const J=W.target.value;m(J),Yn(J)||v(""),u&&a({dimensionName:t.dimensionName,source:t.source,filterName:t.filterName,matchType:J,value:u,...Yn(J)&&x&&{value2:x}})},B=(W,J)=>{h(W??""),J!==void 0&&v(J??"");const $=Array.isArray(W)&&W.length===0;a(!$&&W!==""&&W!==null&&W!==void 0?{dimensionName:t.dimensionName,source:t.source,filterName:t.filterName,matchType:c,value:W,...R&&J&&{value2:J}}:null)},te=()=>{h(""),v(""),a(null)};return n.jsxs(me,{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(me,{sx:{fontWeight:600,color:t.required&&!f?"error.main":"text.primary"},children:[t.label??t.dimensionName,t.required&&n.jsx(me,{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(d.FormControl,{size:"small",fullWidth:!0,children:[n.jsx(d.InputLabel,{children:"Match Type"}),n.jsx(d.Select,{value:c,label:"Match Type",onChange:ee,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:q.map(W=>n.jsx(ge,{value:W,children:W},W))})]}),t.filterType==="Star"&&c==="Equals"&&n.jsx(d.Autocomplete,{multiple:!0,size:"small",options:l,getOptionLabel:W=>typeof W=="string"?W:typeof W=="object"&&W!==null&&"value"in W?String(W.value):String(W),value:Array.isArray(u)?u.map(W=>l.find(J=>J.value===W)||W):u?[l.find(W=>W.value===u)||u]:[],onChange:(W,J)=>{const $=J.map(X=>typeof X=="string"?X:X&&typeof X=="object"&&"value"in X?X.value:X);B($)},noOptionsText:"No matches found",renderInput:W=>n.jsx(d.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"&&c==="Contains"&&n.jsx(d.TextField,{size:"small",label:"Search Text",value:u,onChange:W=>h(W.target.value),onBlur:()=>B(u),onKeyDown:W=>{W.key==="Enter"&&B(u)},placeholder:"Enter text to search...",fullWidth:!0}),t.filterType==="Boolean"&&n.jsxs(d.FormControl,{size:"small",fullWidth:!0,children:[n.jsx(d.InputLabel,{children:"Value"}),n.jsxs(d.Select,{value:u===!0?"true":u===!1?"false":"",label:"Value",onChange:W=>{const J=W.target.value;J==="true"?B(!0):J==="false"?B(!1):te()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[n.jsx(ge,{value:"",children:n.jsx("em",{children:"Blank"})}),n.jsx(ge,{value:"true",children:"True"}),n.jsx(ge,{value:"false",children:"False"})]})]}),t.filterType==="Retrieval"&&c==="Semantic Search"&&n.jsx(d.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(u)?u.map(W=>b.find($=>$.value===W)||{value:W}):u?[{value:u}]:[],onInputChange:(W,J)=>{M(J)},onChange:(W,J)=>{const $=J.map(X=>typeof X=="string"?X:X&&typeof X=="object"&&"value"in X?X.value:X);B($)},noOptionsText:T.trim().length<=2?"Type at least 3 characters to search":"No matches found",renderInput:W=>n.jsx(d.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(d.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"&&!R&&n.jsx(d.TextField,{size:"small",type:"number",label:"Value",value:u,onChange:W=>B(parseFloat(W.target.value)||""),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:Q,max:K},helperText:Z&&Q!==void 0&&K!==void 0?`Valid range: [${Q} - ${K}]`:void 0}),t.filterType==="MinMax"&&R&&n.jsxs(me,{sx:{display:"flex",flexDirection:"column",gap:1},children:[n.jsxs(me,{sx:{display:"flex",gap:1,alignItems:"center"},children:[n.jsx(d.TextField,{size:"small",type:"number",label:"From",value:u,onChange:W=>B(parseFloat(W.target.value)||"",x),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:Q,max:x||K}}),n.jsx(me,{children:"to"}),n.jsx(d.TextField,{size:"small",type:"number",label:"To",value:x,onChange:W=>B(u,parseFloat(W.target.value)||""),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:u||Q,max:K}})]}),Z&&Q!==void 0&&K!==void 0&&n.jsxs(d.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",Q," - ",K,"]"]})]}),U&&!R&&n.jsx(d.LocalizationProvider,{dateAdapter:d.AdapterDayjs,children:n.jsx(d.DatePicker,{label:"Date",value:u instanceof Date?d.dayjs.utc(u):null,onChange:W=>{W===null?B(null):W.isValid()&&B(W.utc().toDate())},timezone:"UTC",minDate:u instanceof Date?void 0:_,maxDate:u instanceof Date?void 0:Y,referenceDate:c==="After"&&_?_:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>N(!0),onBlur:()=>N(!1),helperText:Z&&_&&Y?`Valid range: [${_.format("YYYY-MM-DD")} - ${Y.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),U&&R&&n.jsx(d.LocalizationProvider,{dateAdapter:d.AdapterDayjs,children:n.jsxs(me,{sx:{display:"flex",flexDirection:"column",gap:1},children:[n.jsxs(me,{sx:{display:"flex",gap:1,alignItems:"center"},children:[n.jsx(me,{sx:{flex:1,minWidth:0},children:n.jsx(d.DatePicker,{label:"From",value:u instanceof Date?d.dayjs.utc(u):null,onChange:W=>{W===null?B(null,x):W.isValid()&&B(W.utc().toDate(),x)},timezone:"UTC",minDate:u instanceof Date?void 0:_,maxDate:x instanceof Date?d.dayjs.utc(x):u instanceof Date?void 0:Y,referenceDate:_,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>N(!0),onBlur:()=>N(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),n.jsx(me,{children:"to"}),n.jsx(me,{sx:{flex:1,minWidth:0},children:n.jsx(d.DatePicker,{label:"To",value:x instanceof Date?d.dayjs.utc(x):null,onChange:W=>{W===null?B(u,null):W.isValid()&&B(u,W.utc().toDate())},timezone:"UTC",minDate:u instanceof Date?d.dayjs.utc(u):x instanceof Date?void 0:_,maxDate:x instanceof Date?void 0:Y,referenceDate:u instanceof Date?d.dayjs.utc(u):_,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>N(!0),onBlur:()=>N(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),Z&&_&&Y&&n.jsxs(d.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",_.format("YYYY-MM-DD")," -"," ",Y.format("YYYY-MM-DD"),"]"]})]})})]})}function jl(t){const l=new Set,f=t.schema?.fields;if(!f)return l;for(const a of f)"kind"in a&&a.kind==="join"&&a.name&&l.add(a.name);return l}function Ol(t){if(!t)return null;for(const l of t)if(l.startsWith("##(filters)")){const f=l.slice(11).trim();try{const a=JSON.parse(f);if(Array.isArray(a)){const p=[];for(const o of a)if(typeof o=="string"){const c=o.indexOf(".");c>0&&c<o.length-1&&p.push({source:o.substring(0,c),dimension:o.substring(c+1)})}if(p.length>0)return{filters:p}}}catch(a){console.error(`Failed to parse "${l}" annotation:`,a)}}return null}function pa(t){if(t.startsWith("#(filter)")){const l=t.slice(9).trim();try{const f=JSON.parse(l);if(f.type)return f}catch(f){console.error(`Failed to parse "${t}" annotation:`,f)}}return null}function El(t){const l=t.match(/^#\s*label\s*=\s*"([^"]+)"/);return l?l[1]:null}function Il(t){const l=new Map;let f="";for(const a of t)if(a.type==="code"){if(!f&&a.text){const o=a.text.split(`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),S=require("@mui/material"),A=require("react"),d=require("./DocumentStorage-D7yF4_T3.cjs.js"),V=require("./ServerProvider-CuYLH_Yi.cjs.js"),kn=require("@tanstack/react-query"),ia=require("@mui/system"),Ve=require("@mui/icons-material"),ct=require("./RenderedResult-ChkvK7b2.cjs.js"),xn=require("react-router-dom");function Mo(t){const l=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(l,f,a.get?a:{enumerable:!0,get:()=>t[f]})}}return l.default=t,Object.freeze(l)}const he=Mo(A),Do=d.createSvgIcon(n.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function dr({label:t,href:l,onClick:f}){const a=p=>{const o=p.metaKey||p.ctrlKey||p.shiftKey||p.altKey||p.button!==0;l!==void 0&&o||(p.preventDefault(),f(p))};return n.jsxs(S.Link,{...l===void 0?{component:"button",type:"button"}:{href:l},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(Do,{sx:{fontSize:18}}),"Back to ",t]})}function jo(){const t=xn.useNavigate();return(l,f)=>{if(!f||!f.metaKey&&!f.ctrlKey&&!f.shiftKey&&f.button!==1){t(l);return}const a=new URL(l,window.location.href).href;(f.metaKey||f.ctrlKey||f.button===1||f.shiftKey)&&window.open(a,"_blank")}}function Oo(){const[t]=xn.useSearchParams(),l=xn.useNavigate(),f=xn.useLocation(),a=A.useMemo(()=>Object.fromEntries(t.entries()),[t]),p=A.useRef(new Set),o=A.useCallback((c,m)=>{const u=new Set([...m,...p.current]);p.current=new Set([...p.current,...Object.keys(c),...m]);const h=new URLSearchParams(f.search);for(const x of u)Object.prototype.hasOwnProperty.call(c,x)||h.delete(x);for(const[x,v]of Object.entries(c))h.set(x,v);l({search:h.toString(),hash:f.hash},{replace:!0})},[l,f]);return{params:a,onGivensChange:o}}const oa=d.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"})),Eo="publisher:resize";function Io(t){return typeof t=="object"&&t!==null&&t.type===Eo&&typeof t.height=="number"}function la(t){return t.replace(/\/api\/v0\/?$/,"")}function ca({server:t,environmentName:l,packageName:f,path:a}){const p=a.startsWith("public/")?a.slice(7):a;return`${la(t)}/environments/${encodeURIComponent(l)}/packages/${encodeURIComponent(f)}/`+p}function Fo(t){try{const{environmentName:l,packageName:f,modelPath:a}=d.parseResourceUri(t);return!l||!f||!a?null:{environmentName:l,packageName:f,dataAppPath:a}}catch{return null}}function No({resourceUri:t}){const{server:l,apiClients:f}=V.useServer(),a=Fo(t),p=a?.environmentName??"",o=a?.packageName??"",c=a?.dataAppPath??"",m=A.useMemo(()=>ca({server:l,environmentName:p,packageName:o,path:c}),[l,p,o,c]),h=d.useQueryWithApiError({queryKey:["data-apps",p,o],queryFn:()=>f.dataApps.listDataApps(p,o),enabled:!!a}).data?.data?.find(w=>w.path===c),x=h?.title??c,v=h?.fit==="viewport",b=A.useRef(null),[g,k]=A.useState(120);return A.useEffect(()=>{if(v)return;function w(T){Io(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)},[v]),a?n.jsxs(S.Box,{sx:{p:3,...v?{height:"100%",display:"flex",flexDirection:"column"}:{maxWidth:1200,mx:"auto"}},children:[n.jsxs(S.Stack,{direction:"row",alignItems:"baseline",spacing:1,sx:{mb:1,flexShrink:0},children:[n.jsx(S.Typography,{variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em"},children:x}),n.jsx(S.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:V.MONO_FONT_FAMILY},children:c}),n.jsx(S.Box,{sx:{flex:1}}),n.jsx(S.Tooltip,{title:"Open standalone in new tab",children:n.jsx(S.IconButton,{size:"small",href:m,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:n.jsx(oa,{fontSize:"small"})})})]}),n.jsx(S.Box,{sx:{border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden",backgroundColor:"background.paper",...v?{flex:1,minHeight:0}:{}},children:n.jsx("iframe",{ref:b,src:m,title:x,sandbox:"allow-scripts allow-same-origin allow-forms",style:{display:"block",width:"100%",height:v?"100%":g,border:0}})})]}):n.jsxs(S.Box,{sx:{p:3,maxWidth:1200,mx:"auto"},children:[n.jsx(S.Typography,{variant:"h6",sx:{fontWeight:600},children:"Can't open data app"}),n.jsxs(S.Typography,{variant:"body2",color:"text.secondary",sx:{mt:1},children:["This data app link is missing an environment, package, or path:",n.jsx(S.Box,{component:"span",sx:{fontFamily:V.MONO_FONT_FAMILY,ml:1},children:t})]})]})}function He({title:t,count:l,description:f,action:a,children:p}){const o=A.useId();return n.jsxs(S.Box,{component:"section","aria-labelledby":o,sx:{mb:4},children:[n.jsxs(S.Stack,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:f?0:1,minHeight:40},children:[n.jsxs(S.Stack,{direction:"row",alignItems:"baseline",spacing:1,children:[n.jsx(S.Typography,{id:o,variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em",lineHeight:1.2},children:t}),l!==void 0&&n.jsxs(S.Typography,{variant:"caption",color:"text.secondary",children:["(",l,")"]})]}),a]}),f&&n.jsx(S.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:f}),n.jsx(S.Box,{children:p})]})}function Ao({resourceUri:t}){const{environmentName:l}=d.parseResourceUri(t),{apiClients:f}=V.useServer(),[a,p]=A.useState(!1),o=90,{data:c,isSuccess:m,isError:u,error:h}=d.useQueryWithApiError({queryKey:["about",l],queryFn:()=>f.environments.getEnvironment(l,!1)}),x=c?.data?.readme||"",v=x.split(/\s+/),b=v.length>o,g=v.slice(0,o).join(" ");return n.jsxs(n.Fragment,{children:[!m&&!u&&n.jsx(d.Loading,{text:"Fetching About..."}),m&&x&&n.jsxs(He,{title:"Readme",children:[n.jsx(d.Prose,{variant:"caption",children:a||!b?x:g}),b&&n.jsx(S.Box,{sx:{mt:1},children:n.jsx(d.SecondaryButton,{label:a?"Read less":"Read more",onClick:()=>p(!a)})})]}),u&&n.jsx(d.ApiErrorDisplay,{error:h,context:`${l} > About`})]})}function $o(t={}){const{autoHideDuration:l=null,disableWindowBlurListener:f=!1,onClose:a,open:p,resumeHideDuration:o}=t,c=d.useTimeout();he.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 m=d.useEventCallback((M,D)=>{a?.(M,D)}),u=d.useEventCallback(M=>{!a||M==null||c.start(M,()=>{m(null,"timeout")})});he.useEffect(()=>(p&&u(l),c.clear),[p,l,u,c]);const h=M=>{a?.(M,"clickaway")},x=c.clear,v=he.useCallback(()=>{l!=null&&u(o??l*.5)},[l,o,u]),b=M=>D=>{const I=M.onBlur;I?.(D),v()},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),v()};return he.useEffect(()=>{if(!f&&p)return window.addEventListener("focus",v),window.addEventListener("blur",x),()=>{window.removeEventListener("focus",v),window.removeEventListener("blur",x)}},[f,p,v,x]),{getRootProps:(M={})=>{const D={...d.extractEventHandlers(t),...d.extractEventHandlers(M)};return{role:"presentation",...M,...D,onBlur:b(D),onFocus:g(D),onMouseEnter:k(D),onMouseLeave:w(D)}},onClickAway:h}}function Os(t){return t.substring(2).toLowerCase()}function Ro(t,l){return l.documentElement.clientWidth<t.clientX||l.documentElement.clientHeight<t.clientY}function Lo(t){const{children:l,disableReactTree:f=!1,mouseEvent:a="onClick",onClickAway:p,touchEvent:o="onTouchEnd"}=t,c=he.useRef(!1),m=he.useRef(null),u=he.useRef(!1),h=he.useRef(!1);he.useEffect(()=>(setTimeout(()=>{u.current=!0},0),()=>{u.current=!1}),[]);const x=d.useForkRef(d.getReactElementRef(l),m),v=d.useEventCallback(k=>{const w=h.current;h.current=!1;const T=d.ownerDocument(m.current);if(!u.current||!m.current||"clientX"in k&&Ro(k,T))return;if(c.current){c.current=!1;return}let M;k.composedPath?M=k.composedPath().includes(m.current):M=!T.documentElement.contains(k.target)||m.current.contains(k.target),!M&&(f||!w)&&p(k)}),b=k=>w=>{h.current=!0;const T=l.props[k];T&&T(w)},g={ref:x};return o!==!1&&(g[o]=b(o)),he.useEffect(()=>{if(o!==!1){const k=Os(o),w=d.ownerDocument(m.current),T=()=>{c.current=!0};return w.addEventListener(k,v),w.addEventListener("touchmove",T),()=>{w.removeEventListener(k,v),w.removeEventListener("touchmove",T)}}},[v,o]),a!==!1&&(g[a]=b(a)),he.useEffect(()=>{if(a!==!1){const k=Os(a),w=d.ownerDocument(m.current);return w.addEventListener(k,v),()=>{w.removeEventListener(k,v)}}},[v,a]),he.cloneElement(l,g)}function _o(t){return d.generateUtilityClass("MuiSnackbarContent",t)}d.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const Po=t=>{const{classes:l}=t,f={root:["root"],action:["action"],message:["message"]};return d.composeClasses(f,_o,l)},qo=d.styled(d.Paper,{name:"MuiSnackbarContent",slot:"Root"})(d.memoTheme(({theme:t})=>{const l=t.palette.mode==="light"?.8:.98;return{...t.typography.body2,color:t.vars?t.vars.palette.SnackbarContent.color:t.palette.getContrastText(d.emphasize(t.palette.background.default,l)),backgroundColor:t.vars?t.vars.palette.SnackbarContent.bg:d.emphasize(t.palette.background.default,l),display:"flex",alignItems:"center",flexWrap:"wrap",padding:"6px 16px",flexGrow:1,[t.breakpoints.up("sm")]:{flexGrow:"initial",minWidth:288}}})),Wo=d.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),zo=d.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),Ho=he.forwardRef(function(l,f){const a=d.useDefaultProps({props:l,name:"MuiSnackbarContent"}),{action:p,className:o,message:c,role:m="alert",...u}=a,h=a,x=Po(h);return n.jsxs(qo,{role:m,elevation:6,className:d.clsx(x.root,o),ownerState:h,ref:f,...u,children:[n.jsx(Wo,{className:x.message,ownerState:h,children:c}),p?n.jsx(zo,{className:x.action,ownerState:h,children:p}):null]})});function Vo(t){return d.generateUtilityClass("MuiSnackbar",t)}d.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const Uo=t=>{const{classes:l,anchorOrigin:f}=t,a={root:["root",`anchorOrigin${d.capitalize(f.vertical)}${d.capitalize(f.horizontal)}`]};return d.composeClasses(a,Vo,l)},Bo=d.styled("div",{name:"MuiSnackbar",slot:"Root",overridesResolver:(t,l)=>{const{ownerState:f}=t;return[l.root,l[`anchorOrigin${d.capitalize(f.anchorOrigin.vertical)}${d.capitalize(f.anchorOrigin.horizontal)}`]]}})(d.memoTheme(({theme:t})=>({zIndex:(t.vars||t).zIndex.snackbar,position:"fixed",display:"flex",left:8,right:8,justifyContent:"center",alignItems:"center",variants:[{props:({ownerState:l})=>l.anchorOrigin.vertical==="top",style:{top:8,[t.breakpoints.up("sm")]:{top:24}}},{props:({ownerState:l})=>l.anchorOrigin.vertical!=="top",style:{bottom:8,[t.breakpoints.up("sm")]:{bottom:24}}},{props:({ownerState:l})=>l.anchorOrigin.horizontal==="left",style:{justifyContent:"flex-start",[t.breakpoints.up("sm")]:{left:24,right:"auto"}}},{props:({ownerState:l})=>l.anchorOrigin.horizontal==="right",style:{justifyContent:"flex-end",[t.breakpoints.up("sm")]:{right:24,left:"auto"}}},{props:({ownerState:l})=>l.anchorOrigin.horizontal==="center",style:{[t.breakpoints.up("sm")]:{left:"50%",right:"auto",transform:"translateX(-50%)"}}}]}))),Yo=he.forwardRef(function(l,f){const a=d.useDefaultProps({props:l,name:"MuiSnackbar"}),p=d.useTheme(),o={enter:p.transitions.duration.enteringScreen,exit:p.transitions.duration.leavingScreen},{action:c,anchorOrigin:{vertical:m,horizontal:u}={vertical:"bottom",horizontal:"left"},autoHideDuration:h=null,children:x,className:v,ClickAwayListenerProps:b,ContentProps:g,disableWindowBlurListener:k=!1,message:w,onBlur:T,onClose:M,onFocus:D,onMouseEnter:I,onMouseLeave:E,open:L,resumeHideDuration:z,slots:P={},slotProps:Z={},TransitionComponent:N,transitionDuration:q=o,TransitionProps:{onEnter:U,onExited:R,..._}={},...Y}=a,Q={...a,anchorOrigin:{vertical:m,horizontal:u},autoHideDuration:h,disableWindowBlurListener:k,TransitionComponent:N,transitionDuration:q},K=Uo(Q),{getRootProps:ee,onClickAway:B}=$o({...Q}),[te,W]=he.useState(!0),J=De=>{W(!0),R&&R(De)},$=(De,Se)=>{W(!1),U&&U(De,Se)},X={slots:{transition:N,...P},slotProps:{content:g,clickAwayListener:b,transition:_,...Z}},[le,G]=d.useSlot("root",{ref:f,className:[K.root,v],elementType:Bo,getSlotProps:ee,externalForwardedProps:{...X,...Y},ownerState:Q}),[oe,{ownerState:we,...ve}]=d.useSlot("clickAwayListener",{elementType:Lo,externalForwardedProps:X,getSlotProps:De=>({onClickAway:(...Se)=>{const Ne=Se[0];De.onClickAway?.(...Se),!Ne?.defaultMuiPrevented&&B(...Se)}}),ownerState:Q}),[Te,Fe]=d.useSlot("content",{elementType:Ho,shouldForwardComponentProp:!0,externalForwardedProps:X,additionalProps:{message:w,action:c},ownerState:Q}),[Oe,Me]=d.useSlot("transition",{elementType:d.Grow,externalForwardedProps:X,getSlotProps:De=>({onEnter:(...Se)=>{De.onEnter?.(...Se),$(...Se)},onExited:(...Se)=>{De.onExited?.(...Se),J(...Se)}}),additionalProps:{appear:!0,in:L,timeout:q,direction:m==="top"?"down":"up"},ownerState:Q});return!L&&te?null:n.jsx(oe,{...ve,...P.clickAwayListener&&{ownerState:we},children:n.jsx(le,{...G,children:n.jsx(Oe,{...Me,children:x||n.jsx(Te,{...Fe})})})})});let nr;function Zo(t){nr=t}function Es(t){if(nr)try{nr(t)}catch{}}function Qe(t,l,f){return(async a=>{const p=Date.now();try{const o=await f(a);return Es({type:"console.mutation",resource:t,action:l,ok:!0,durationMs:Date.now()-p}),o}catch(o){throw Es({type:"console.mutation",resource:t,action:l,ok:!1,durationMs:Date.now()-p,reason:o instanceof Error?o.message:"An unknown error occurred"}),o}})}function Tt({mutationFn:t,success:l,invalidates:f,closeDialog:a,resource:p,action:o}){const c=kn.useQueryClient(),[m,u]=A.useState(""),h=d.useMutationWithApiError({mutationFn:Qe(p,o,t),onSuccess(){a();for(const x of f)c.invalidateQueries({queryKey:x});u(l)},onError(x){u(x instanceof Error?x.message:"An unknown error occurred")}});return{mutate:h.mutate,isPending:h.isPending,notice:n.jsx(Yo,{open:m!=="",autoHideDuration:6e3,onClose:()=>u(""),message:m})}}const ua="https://docs.malloydata.dev/documentation",Un=`${ua}/user_guides/publishing`,wt="https://github.com/malloydata/publisher/blob/main/docs",Ke={docsHome:`${ua}/`,publishing:`${Un}/publishing`,explorer:`${Un}/explorer`,mcpAgents:`${Un}/mcp_agents`,surfaces:`${wt}/choosing-a-surface.md`,dashboards:`${wt}/dashboards.md`,dataApps:`${wt}/html-data-apps.md`,givens:`${wt}/givens.md`,materialization:`${wt}/materialization.md`,connections:`${wt}/connections.md`};function Go({resourceUri:t}){const[l,f]=A.useState(!1),{apiClients:a}=V.useServer(),{environmentName:p}=d.parseResourceUri(t),o=Tt({mutationFn(m){return a.packages.createPackage(p,{name:m.name,description:m.description,location:m.location})},success:"Package created",invalidates:[["packages",p]],closeDialog:()=>f(!1),resource:"package",action:"create"}),c=m=>{m.preventDefault();const u=new FormData(m.currentTarget),h=u.get("name")?.toString(),x=u.get("description")?.toString(),v=u.get("location")?.toString();o.mutate({name:h,description:x,location:v})};return n.jsxs(n.Fragment,{children:[n.jsx(d.AddButton,{label:"Package",onClick:()=>f(!0)}),n.jsx(d.AppDialog,{open:l,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(S.Box,{component:"a",href:Ke.publishing,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary"},children:"package format"}),"."]}),actions:n.jsxs(n.Fragment,{children:[n.jsx(S.Button,{disabled:o.isPending,onClick:()=>f(!1),children:"Cancel"}),n.jsx(S.Button,{type:"submit",form:"package-form",variant:"contained",loading:o.isPending,children:"Create package"})]}),children:n.jsx("form",{onSubmit:c,id:"package-form",children:n.jsxs(S.Stack,{sx:{gap:2},children:[n.jsx(S.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(S.TextField,{id:"description",name:"description",label:"Description",multiline:!0,rows:3,fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(S.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}})]})})}),o.notice]})}const Xo=d.createSvgIcon(n.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function Cn({icon:t,tint:l,label:f,mono:a,description:p,rightLabel:o,trailingAction:c,onClick:m,ariaLabel:u}){const h=!!m,x=v=>{m&&(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),m(v))};return n.jsxs(S.Box,{onClick:m,onKeyDown:h?x:void 0,role:h?"button":void 0,tabIndex:h?0:void 0,"aria-label":u,sx:v=>({display:"flex",alignItems:"center",gap:1.5,py:1,px:1,mx:-1,cursor:h?"pointer":"default",borderRadius:1.5,transition:"background-color 0.1s","&:hover":h?{backgroundColor:v.palette.mode==="dark"?"rgba(255, 255, 255, 0.08)":"grey.100"}:void 0,"&:focus-visible":h?{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}:void 0}),children:[n.jsx(S.Box,{sx:{width:32,height:32,borderRadius:1,bgcolor:l,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t}),n.jsxs(S.Box,{sx:{flex:1,minWidth:0,display:"flex",alignItems:"baseline",gap:1.5},children:[n.jsx(S.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(S.Typography,{variant:"body2",color:"text.secondary",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p})]}),o&&n.jsx(S.Typography,{variant:"caption",color:"text.secondary",sx:{flexShrink:0},children:o}),c&&n.jsx(S.Box,{sx:{flexShrink:0,display:"flex",alignItems:"center"},children:c})]})}const da=d.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"})),Ko=d.generateUtilityClasses("MuiBox",["root"]),Qo=d.createTheme(),me=ia.createBox({themeId:d.THEME_ID,defaultTheme:Qo,defaultClassName:Ko.root,generateClassName:d.ClassNameGenerator.generate}),Tn=ia.createStack({createStyledComponent:d.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:t=>d.useDefaultProps({props:t,name:"MuiStack"})}),Is=d.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function Jo(t){return d.generateUtilityClass("MuiListItemIcon",t)}const Fs=d.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),el=t=>{const{alignItems:l,classes:f}=t,a={root:["root",l==="flex-start"&&"alignItemsFlexStart"]};return d.composeClasses(a,Jo,f)},tl=d.styled("div",{name:"MuiListItemIcon",slot:"Root",overridesResolver:(t,l)=>{const{ownerState:f}=t;return[l.root,f.alignItems==="flex-start"&&l.alignItemsFlexStart]}})(d.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}}]}))),hr=he.forwardRef(function(l,f){const a=d.useDefaultProps({props:l,name:"MuiListItemIcon"}),{className:p,...o}=a,c=he.useContext(d.ListContext),m={...a,alignItems:c.alignItems},u=el(m);return n.jsx(tl,{className:d.clsx(u.root,p),ownerState:m,ref:f,...o})});function nl(t){return d.generateUtilityClass("MuiListItemText",t)}const Ct=d.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),rl=t=>{const{classes:l,inset:f,primary:a,secondary:p,dense:o}=t,c={root:["root",f&&"inset",o&&"dense",a&&p&&"multiline"],primary:["primary"],secondary:["secondary"]};return d.composeClasses(c,nl,l)},sl=d.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(t,l)=>{const{ownerState:f}=t;return[{[`& .${Ct.primary}`]:l.primary},{[`& .${Ct.secondary}`]:l.secondary},l.root,f.inset&&l.inset,f.primary&&f.secondary&&l.multiline,f.dense&&l.dense]}})({flex:"1 1 auto",minWidth:0,marginTop:4,marginBottom:4,[`.${d.typographyClasses.root}:where(& .${Ct.primary})`]:{display:"block"},[`.${d.typographyClasses.root}:where(& .${Ct.secondary})`]:{display:"block"},variants:[{props:({ownerState:t})=>t.primary&&t.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:t})=>t.inset,style:{paddingLeft:56}}]}),fr=he.forwardRef(function(l,f){const a=d.useDefaultProps({props:l,name:"MuiListItemText"}),{children:p,className:o,disableTypography:c=!1,inset:m=!1,primary:u,primaryTypographyProps:h,secondary:x,secondaryTypographyProps:v,slots:b={},slotProps:g={},...k}=a,{dense:w}=he.useContext(d.ListContext);let T=u??p,M=x;const D={...a,disableTypography:c,inset:m,primary:!!T,secondary:!!M,dense:w},I=rl(D),E={slots:b,slotProps:{primary:h,secondary:v,...g}},[L,z]=d.useSlot("root",{className:d.clsx(I.root,o),elementType:sl,externalForwardedProps:{...E,...k},ownerState:D,ref:f}),[P,Z]=d.useSlot("primary",{className:I.primary,elementType:d.Typography,externalForwardedProps:E,ownerState:D}),[N,q]=d.useSlot("secondary",{className:I.secondary,elementType:d.Typography,externalForwardedProps:E,ownerState:D});return T!=null&&T.type!==d.Typography&&!c&&(T=n.jsx(P,{variant:w?"body2":"body1",component:Z?.variant?void 0:"span",...Z,children:T})),M!=null&&M.type!==d.Typography&&!c&&(M=n.jsx(N,{variant:"body2",color:"textSecondary",...q,children:M})),n.jsxs(L,{...z,children:[T,M]})});function al(t){return d.generateUtilityClass("MuiMenuItem",t)}const Pt=d.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),il=(t,l)=>{const{ownerState:f}=t;return[l.root,f.dense&&l.dense,f.divider&&l.divider,!f.disableGutters&&l.gutters]},ol=t=>{const{disabled:l,dense:f,divider:a,disableGutters:p,selected:o,classes:c}=t,m={root:["root",f&&"dense",l&&"disabled",!p&&"gutters",a&&"divider",o&&"selected"]},u=d.composeClasses(m,al,c);return{...c,...u}},ll=d.styled(d.ButtonBase,{shouldForwardProp:t=>d.rootShouldForwardProp(t)||t==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:il})(d.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"}},[`&.${Pt.selected}`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,(t.vars||t).palette.action.selectedOpacity),[`&.${Pt.focusVisible}`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,`${(t.vars||t).palette.action.selectedOpacity} + ${(t.vars||t).palette.action.focusOpacity}`)}},[`&.${Pt.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)}},[`&.${Pt.focusVisible}`]:{backgroundColor:(t.vars||t).palette.action.focus},[`&.${Pt.disabled}`]:{opacity:(t.vars||t).palette.action.disabledOpacity},[`& + .${Is.root}`]:{marginTop:t.spacing(1),marginBottom:t.spacing(1)},[`& + .${Is.inset}`]:{marginLeft:52},[`& .${Ct.root}`]:{marginTop:0,marginBottom:0},[`& .${Ct.inset}`]:{paddingLeft:36},[`& .${Fs.root}`]:{minWidth:36},variants:[{props:({ownerState:l})=>!l.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:l})=>l.divider,style:{borderBottom:`1px solid ${(t.vars||t).palette.divider}`,backgroundClip:"padding-box"}},{props:({ownerState:l})=>!l.dense,style:{[t.breakpoints.up("sm")]:{minHeight:"auto"}}},{props:({ownerState:l})=>l.dense,style:{minHeight:32,paddingTop:4,paddingBottom:4,...t.typography.body2,[`& .${Fs.root} svg`]:{fontSize:"1.25rem"}}}]}))),ge=he.forwardRef(function(l,f){const a=d.useDefaultProps({props:l,name:"MuiMenuItem"}),{autoFocus:p=!1,component:o="li",dense:c=!1,divider:m=!1,disableGutters:u=!1,focusVisibleClassName:h,role:x="menuitem",tabIndex:v,className:b,...g}=a,k=he.useContext(d.ListContext),w=he.useMemo(()=>({dense:c||k.dense||!1,disableGutters:u}),[k.dense,c,u]),T=he.useRef(null);d.useEnhancedEffect(()=>{p&&T.current&&T.current.focus()},[p]);const M={...a,dense:w.dense,divider:m,disableGutters:u},D=ol(a),I=d.useForkRef(T,f);let E;return a.disabled||(E=v!==void 0?v:-1),n.jsx(d.ListContext.Provider,{value:w,children:n.jsx(ll,{ref:I,role:x,tabIndex:E,component:o,focusVisibleClassName:d.clsx(D.focusVisible,h),className:d.clsx(D.root,b),...g,ownerState:M,classes:D})})}),Je={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:[]},Xt={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",trino:"trinoConnection",databricks:"databricksConnection",mysql:"mysqlConnection",duckdb:"duckdbConnection",motherduck:"motherduckConnection",ducklake:"ducklakeConnection",publisher:"publisherConnection"},ha=Object.values(V.ConnectionTypeEnum).filter(t=>t!==V.ConnectionTypeEnum.Publisher),rr={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},Jt=[{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"}}],en=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],cl=[{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 vn(t){return t==="postgres"||t==="bigquery"||t==="snowflake"?Je[t]||[]:t==="s3"?Jt:t==="gcs"?en:t==="azure"?cl:[]}function ul({onSubmit:t,isSubmitting:l}){const[f,a]=A.useState(!1),[p,o]=A.useState("postgres"),[c,m]=A.useState([]),[u,h]=A.useState("postgres"),[x,v]=A.useState("s3"),[b,g]=A.useState("config"),k=()=>{a(!0)},w=()=>{a(!1),m([]),o("postgres"),h("postgres"),v("s3"),g("config")},T=async E=>{E.preventDefault();const L=new FormData(E.currentTarget),z=L.get("name")?.toString(),P=L.get("type")?.toString(),Z=Je[P];if(!z)throw new Error("Name is required");if(!P)throw new Error("Type is required");let N;if(P==="ducklake"){const q={};if(u==="postgres"){const _=Je.postgres,Y={};if(_.forEach(Q=>{const K=L.get(`ducklake_pg_${Q.name}`)?.toString();K&&(Y[Q.name]=K)}),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 R={bucketUrl:U};if(x==="s3"){const _={};if(Jt.forEach(Y=>{const Q=L.get(`ducklake_s3_${Y.name}`)?.toString();Q&&(_[Y.name]=Q)}),_.provider==="credential_chain")delete _.accessKeyId,delete _.secretAccessKey,delete _.sessionToken;else{if(delete _.chain,!_.accessKeyId)throw new Error("S3 Access Key ID is required");if(!_.secretAccessKey)throw new Error("S3 Secret Access Key is required")}Object.keys(_).length>0&&(R.s3Connection=_)}else if(x==="gcs"){const _={};if(en.forEach(Y=>{const Q=L.get(`ducklake_gcs_${Y.name}`)?.toString();Q&&(_[Y.name]=Q)}),!_.keyId)throw new Error("GCS Key ID is required");if(!_.secret)throw new Error("GCS Secret is required");Object.keys(_).length>0&&(R.gcsConnection=_)}N={name:z,type:P,ducklakeConnection:{catalog:q,storage:R}}}else if(P==="duckdb"){if(c.length===0)throw new Error("DuckDB connection must have at least one attached database");const q=c.map((U,R)=>{const _=U.dbType,Y=L.get(`attachedDb_${R}_name`)?.toString();if(!Y)throw new Error(`Attached database at index ${R} must have a name`);const Q={name:Y,type:_},K=vn(_);if(K&&K.length>0){const ee={};if(K.forEach(te=>{const W=L.get(`attachedDb_${R}_${te.name}`)?.toString();W&&(ee[te.name]=W)}),_==="s3"){if(ee.provider==="credential_chain")delete ee.accessKeyId,delete ee.secretAccessKey,delete ee.sessionToken;else if(delete ee.chain,!ee.accessKeyId||!ee.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=rr[_];B&&(Q[B]=ee)}return Q});N={name:z,type:P,duckdbConnection:{attachedDatabases:q}}}else{const q={};if(Z.forEach(U=>{const R=L.get(U.name)?.toString();R&&(q[U.name]=R)}),P==="postgres"){if(!!!q.connectionString?.trim()){const R=["host","port","databaseName","userName","password"];for(const _ of R)if(!q[_])throw new Error(`${Z.find(Y=>Y.name===_)?.label||_} is required`)}}else if(P==="bigquery"){if(!q.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if(P==="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(P==="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(P==="mysql"){const U=["host","port","database","user","password"];for(const R of U)if(!q[R])throw new Error(`${Z.find(_=>_.name===R)?.label||R} is required`)}else if(P==="motherduck"){if(!q.accessToken)throw new Error("Access Token is required")}else if(P==="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:z,type:P,[Xt[P]]:q}}await t(N),w()},M=()=>{m([...c,{name:"",dbType:"postgres"}])},D=E=>{m(c.filter((L,z)=>z!==E))},I=(E,L)=>{const z=[...c];z[E]={...z[E],dbType:L},m(z)};return n.jsxs(A.Fragment,{children:[n.jsx(d.AddButton,{label:"Connection",onClick:k}),n.jsx(d.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(d.Button,{disabled:l,onClick:w,children:"Cancel"}),n.jsx(d.Button,{type:"submit",form:"connection-form",variant:"contained",loading:l,children:"Create connection"})]}),children:n.jsx("form",{onSubmit:T,id:"connection-form",children:n.jsxs(Tn,{sx:{gap:2},children:[n.jsx(d.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small"}),n.jsx(d.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:p,select:!0,onChange:E=>o(E.target.value),children:ha.map(E=>n.jsx(ge,{value:E,children:E},E))}),p==="ducklake"?n.jsxs(me,{sx:{mt:2},children:[n.jsxs(me,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(d.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),n.jsx(d.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:u,select:!0,onChange:E=>h(E.target.value),children:n.jsx(ge,{value:"postgres",children:"PostgreSQL"})}),u==="postgres"&&n.jsx(n.Fragment,{children:Je.postgres.map(E=>n.jsx(d.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(me,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(d.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),n.jsxs(d.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:x,select:!0,onChange:E=>v(E.target.value),children:[n.jsx(ge,{value:"s3",children:"S3"}),n.jsx(ge,{value:"gcs",children:"GCS"})]}),n.jsx(d.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(d.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),Jt.filter(E=>E.visibleWhen?b===E.visibleWhen.value:!0).map(E=>n.jsx(d.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(ge,{value:L.value,children:L.label},L.value))},`s3_${E.name}`))]}),x==="gcs"&&n.jsxs(n.Fragment,{children:[n.jsx(d.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),en.map(E=>n.jsx(d.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(me,{sx:{mt:2},children:[n.jsxs(me,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsx(d.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),n.jsx(d.SecondaryButton,{label:"Database",icon:n.jsx(d.AddIcon,{}),onClick:M,ariaLabel:"Add database"})]}),c.length===0&&n.jsx(d.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),c.map((E,L)=>{const z=vn(E.dbType);return n.jsxs(me,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsxs(me,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsxs(d.Typography,{variant:"subtitle2",children:["Database ",L+1]}),n.jsx(d.IconButton,{onClick:()=>D(L),size:"small",color:"error",children:n.jsx(da,{fontSize:"small"})})]}),n.jsx(d.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(d.TextField,{id:`attachedDb_${L}_type`,name:`attachedDb_${L}_type`,label:"Database Type",fullWidth:!0,size:"small",value:E.dbType,select:!0,onChange:P=>I(L,P.target.value),children:Object.values(V.AttachedDatabaseTypeEnum).map(P=>n.jsx(ge,{value:P,children:P},P))}),z.filter(P=>P.visibleWhen?(E[P.visibleWhen.field]||z.find(N=>N.name===P.visibleWhen?.field)?.selectOptions?.[0]?.value)===P.visibleWhen.value:!0).map(P=>n.jsx(d.TextField,{id:`attachedDb_${L}_${P.name}`,name:`attachedDb_${L}_${P.name}`,label:P.label,type:P.selectOptions?void 0:P.type,fullWidth:!0,size:"small",required:P.required,select:!!P.selectOptions,defaultValue:P.selectOptions?.[0]?.value,onChange:P.selectOptions?Z=>{const N=[...c];N[L]={...N[L],[P.name]:Z.target.value},m(N)}:void 0,children:P.selectOptions?.map(Z=>n.jsx(ge,{value:Z.value,children:Z.label},Z.value))},P.name))]},L)})]}):Je[p].map(E=>n.jsx(d.TextField,{id:E.name,name:E.name,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required},E.name))]})})})]})}function dl({connection:t,onCloseDialog:l,isMutating:f,onDelete:a}){const[p,o]=A.useState(!1),c=()=>{o(!0)},m=()=>{o(!1),l()};return n.jsxs(A.Fragment,{children:[n.jsxs(ge,{"aria-label":`Delete connection ${t?.name??""}`.trim(),onClick:u=>{u.stopPropagation(),c()},sx:{color:"error.main"},children:[n.jsx(hr,{sx:{color:"inherit"},children:n.jsx(Ve.Delete,{fontSize:"small"})}),n.jsx(fr,{children:"Delete"})]}),n.jsx(d.AppDialog,{open:p,onClose:m,title:"Delete connection",actions:n.jsxs(n.Fragment,{children:[n.jsx(d.Button,{onClick:m,children:"Cancel"}),n.jsx(d.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>a(),loading:f,children:"Delete connection"})]}),children:n.jsxs(d.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:t.name}),"? Packages that query through it stop working, and this cannot be undone."]})})]})}const Ns=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function As(t){const l=t.duckdbConnection?.attachedDatabases;return!l||l.length===0?[]:l.map(f=>({name:f.name||"",dbType:f.type||"postgres"}))}function $s(t){const l=t.ducklakeConnection;return l&&l.storage?.gcsConnection?"gcs":"s3"}function hl({connection:t,onSubmit:l,isSubmitting:f,onCloseDialog:a}){const[p,o]=A.useState(!1),[c,m]=A.useState(t.type),u=A.useMemo(()=>new Set(t.withheldFields??[]),[t.withheldFields]),[h,x]=A.useState(()=>As(t)),[v,b]=A.useState("postgres"),[g,k]=A.useState(()=>$s(t)),[w,T]=A.useState(()=>t.ducklakeConnection?.storage?.s3Connection?.provider??"config"),M=()=>{x(As(t)),m(t.type),T(t.ducklakeConnection?.storage?.s3Connection?.provider??"config"),b("postgres"),k($s(t)),o(!0)},D=()=>{o(!1),a?.()},I=async N=>{N.preventDefault();const q=new FormData(N.currentTarget),U=q.get("name")?.toString(),R=q.get("type")?.toString(),_=Je[R];if(!U)throw new Error("Name is required");if(!R)throw new Error("Type is required");let Y;if(R==="ducklake"){const Q={};if(v==="postgres"){const B=Je.postgres,te={};if(B.forEach(W=>{const J=q.get(`ducklake_pg_${W.name}`)?.toString();J&&(te[W.name]=J)}),Object.keys(te).length===0)throw new Error("DuckLake requires catalog connection");Q.postgresConnection=te}const K=q.get("ducklake_bucketUrl")?.toString();if(!K)throw new Error("DuckLake requires a bucket URL");const ee={bucketUrl:K};if(g==="s3"){const B={};Jt.forEach(W=>{const J=q.get(`ducklake_s3_${W.name}`)?.toString();J&&(B[W.name]=J)});const te=t.ducklakeConnection?.storage?.s3Connection;if(te&&(!B.provider&&te.provider&&(B.provider=te.provider),!B.chain&&te.chain&&(B.chain=te.chain),!B.accessKeyId&&te.accessKeyId&&(B.accessKeyId=te.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&&(ee.s3Connection=B)}else if(g==="gcs"){const B={};en.forEach(W=>{const J=q.get(`ducklake_gcs_${W.name}`)?.toString();J&&(B[W.name]=J)});const te=t.ducklakeConnection?.storage?.gcsConnection;if(te&&!B.keyId&&te.keyId&&(B.keyId=te.keyId),!B.keyId)throw new Error("GCS Key ID is required");Object.keys(B).length>0&&(ee.gcsConnection=B)}Y={name:U,type:R,ducklakeConnection:{catalog:Q,storage:ee}}}else if(R==="duckdb"){if(h.length===0)throw new Error("DuckDB connection must have at least one attached database");const Q=h.map((K,ee)=>{const B=K.dbType,te=q.get(`attachedDb_${ee}_name`)?.toString();if(!te)throw new Error(`Attached database at index ${ee} must have a name`);const W={name:te,type:B},J=vn(B);if(J&&J.length>0){const $={};if(J.forEach(le=>{const G=q.get(`attachedDb_${ee}_${le.name}`)?.toString();G&&($[le.name]=G)}),B==="s3"){if($.provider==="credential_chain")delete $.accessKeyId,delete $.secretAccessKey,delete $.sessionToken;else if(delete $.chain,!$.accessKeyId||!$.secretAccessKey)throw new Error(`Attached database "${te}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const X=rr[B];X&&(W[X]=$)}return W});Y={name:U,type:R,duckdbConnection:{attachedDatabases:Q}}}else{const Q=t[Xt[R]]||{},K={};if(_.forEach(ee=>{const B=q.get(ee.name)?.toString(),te=Q[ee.name];B?K[ee.name]=B:Ns.has(ee.name)||(B!==void 0?K[ee.name]=B:te&&(K[ee.name]=te))}),R==="postgres"){const ee=["host","port","databaseName","userName"],B=u.has("postgresConnection.connectionString");if(!(!!K.connectionString?.trim()||B)){const W=ee;for(const J of W)if(!K[J])throw new Error(`${_.find($=>$.name===J)?.label||J} is required`)}}else if(R==="snowflake"){if(!K.account)throw new Error("Account is required");if(!K.username)throw new Error("Username is required");if(!K.warehouse)throw new Error("Warehouse is required")}else if(R==="trino"){if(!K.server)throw new Error("Server is required");if(!K.user)throw new Error("User is required")}else if(R==="mysql"){const ee=["host","port","database","user"];for(const B of ee)if(!K[B])throw new Error(`${_.find(te=>te.name===B)?.label||B} is required`)}else if(R==="databricks"){if(!K.host)throw new Error("Host is required");if(!K.path)throw new Error("HTTP Path is required")}Y={name:U,type:R,[Xt[R]]:K}}await l(Y),D()},E=()=>{x([...h,{name:"",dbType:"postgres"}])},L=N=>{x(h.filter((q,U)=>U!==N))},z=(N,q)=>{const U=[...h];U[N]={...U[N],dbType:q},x(U)},P=(N,q)=>{const U=t.duckdbConnection?.attachedDatabases;if(!U||!U[N])return"";const R=U[N],_=rr[R.type||""];return _&&R[_]?R[_][q]??"":""},Z=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(A.Fragment,{children:[n.jsxs(ge,{"aria-label":`Edit connection ${t?.name??""}`.trim(),onClick:N=>{N.preventDefault(),N.stopPropagation(),M()},children:[n.jsx(hr,{children:n.jsx(Ve.Edit,{fontSize:"small"})}),n.jsx(fr,{children:"Edit"})]}),n.jsx(d.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(d.Button,{disabled:f,onClick:D,children:"Cancel"}),n.jsx(d.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(Tn,{sx:{gap:2},children:[n.jsx(d.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",defaultValue:t.name}),n.jsx(d.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:c,select:!0,onChange:N=>m(N.target.value),children:ha.map(N=>n.jsx(ge,{value:N,children:N},N))}),c==="ducklake"?n.jsxs(me,{sx:{mt:2},children:[n.jsxs(me,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(d.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),n.jsx(d.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:v,select:!0,onChange:N=>b(N.target.value),children:n.jsx(ge,{value:"postgres",children:"PostgreSQL"})}),v==="postgres"&&n.jsx(n.Fragment,{children:Je.postgres.map(N=>n.jsx(d.TextField,{id:`ducklake_pg_${N.name}`,name:`ducklake_pg_${N.name}`,label:N.label,type:N.type,fullWidth:!0,size:"small",defaultValue:Z(`pg_${N.name}`)},`pg_${N.name}`))})]}),n.jsxs(me,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(d.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),n.jsxs(d.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:g,select:!0,onChange:N=>k(N.target.value),children:[n.jsx(ge,{value:"s3",children:"S3"}),n.jsx(ge,{value:"gcs",children:"GCS"})]}),n.jsx(d.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:Z("bucketUrl")}),g==="s3"&&n.jsxs(n.Fragment,{children:[n.jsx(d.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),Jt.filter(N=>N.visibleWhen?w===N.visibleWhen.value:!0).map(N=>n.jsx(d.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:Z(`s3_${N.name}`),onChange:N.name==="provider"?q=>T(q.target.value):void 0,placeholder:N.name==="region"?"us-east-1":N.name==="secretAccessKey"&&u.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:N.selectOptions?.map(q=>n.jsx(ge,{value:q.value,children:q.label},q.value))},`s3_${N.name}`))]}),g==="gcs"&&n.jsxs(n.Fragment,{children:[n.jsx(d.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),en.map(N=>n.jsx(d.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:Z(`gcs_${N.name}`),placeholder:N.name==="secret"&&u.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${N.name}`))]})]})]}):c==="duckdb"?n.jsxs(me,{sx:{mt:2},children:[n.jsxs(me,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsx(d.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),n.jsx(d.SecondaryButton,{label:"Database",icon:n.jsx(d.AddIcon,{}),onClick:E,ariaLabel:"Add database"})]}),h.length===0&&n.jsx(d.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),h.map((N,q)=>{const U=vn(N.dbType);return n.jsxs(me,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsxs(me,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsxs(d.Typography,{variant:"subtitle2",children:["Database ",q+1]}),n.jsx(d.IconButton,{"aria-label":`Remove attached database ${q+1}`,onClick:()=>L(q),size:"small",color:"error",children:n.jsx(da,{fontSize:"small"})})]}),n.jsx(d.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(d.TextField,{id:`attachedDb_${q}_type`,name:`attachedDb_${q}_type`,label:"Database Type",fullWidth:!0,size:"small",value:N.dbType,select:!0,onChange:R=>z(q,R.target.value),children:Object.values(V.AttachedDatabaseTypeEnum).map(R=>n.jsx(ge,{value:R,children:R},R))}),U.filter(R=>R.visibleWhen?(N[R.visibleWhen.field]||P(q,R.visibleWhen.field)||U.find(Y=>Y.name===R.visibleWhen?.field)?.selectOptions?.[0]?.value)===R.visibleWhen.value:!0).map(R=>n.jsx(d.TextField,{id:`attachedDb_${q}_${R.name}`,name:`attachedDb_${q}_${R.name}`,label:R.label,type:R.selectOptions?void 0:R.type,fullWidth:!0,size:"small",required:R.required,select:!!R.selectOptions,defaultValue:P(q,R.name)||R.selectOptions?.[0]?.value,onChange:R.selectOptions?_=>{const Y=[...h];Y[q]={...Y[q],[R.name]:_.target.value},x(Y)}:void 0,children:R.selectOptions?.map(_=>n.jsx(ge,{value:_.value,children:_.label},_.value))},R.name))]},q)})]}):Je[c].map(N=>{const q=t?.[Xt[c]??""]?.[N.name??""]??"",U=N.type==="password"||Ns.has(N.name),R=u.has(`${Xt[c]??""}.${N.name}`);return n.jsx(d.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:R?"Leave empty to keep existing":void 0,helperText:U?R?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0},N.name)})]})})})]})}function Rs(t,l){return!t||t.type!=="duckdb"?!1:(t.duckdbConnection?.attachedDatabases||[]).some(a=>a.type==="azure"&&a.name===l)}function fl(t){return t.startsWith("gs://")||t.startsWith("s3://")||t.startsWith("https://")||t.startsWith("abfss://")||t.startsWith("az://")}function fa({connectionName:t,resourceUri:l,schema:f,connection:a}){const{apiClients:p}=V.useServer(),{environmentName:o}=d.parseResourceUri(l),[c,m]=A.useState(null),[u,h]=A.useState(f||null),[x,v]=A.useState(!1),{data:b,isError:g,isLoading:k,error:w}=d.useQueryWithApiError({queryKey:["schemas",o,t],queryFn:()=>p.connections.listSchemas(o,t)}),T=b?.data||[];return n.jsxs(S.Grid,{container:!0,spacing:1,children:[!f&&n.jsx(S.Grid,{size:{xs:12,md:4},children:n.jsxs(S.Paper,{sx:{p:1,m:0},children:[n.jsxs(S.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:0},children:[n.jsx(S.Typography,{variant:"overline",fontWeight:"bold",children:"Table Paths"}),n.jsx(S.FormControlLabel,{control:n.jsx(S.Switch,{checked:x,onChange:M=>v(M.target.checked)}),label:"Hidden Schemas"})]}),n.jsx(S.Divider,{sx:{mt:"2px"}}),n.jsxs(S.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[k&&n.jsx(d.Loading,{text:"Loading schemas..."}),g&&n.jsx(d.ApiErrorDisplay,{error:w,context:`${o} > ${t} > Schemas`}),!k&&!g&&T.length===0&&n.jsx(S.Typography,{variant:"body2",children:"No Schemas"}),!k&&!g&&T.length>0&&n.jsx(S.List,{dense:!0,disablePadding:!0,children:T.map(M=>{const D=M.name;if(M.isHidden&&!x)return null;const E=u===D;return n.jsx(S.ListItemButton,{selected:E,onClick:()=>{h(D),m(null)},children:n.jsx(S.ListItemText,{primary:D})},D)})})]})]})}),n.jsx(S.Grid,{size:{xs:12,md:f?6:4},children:u&&n.jsx(S.Paper,{sx:{p:1,m:0},children:n.jsx(yl,{connectionName:t,schemaName:u,onTableSelect:M=>{m(M)},resourceUri:l,connection:a})})}),n.jsx(S.Grid,{size:{xs:12,md:f?6:4},children:u&&c&&n.jsx(ml,{environmentName:o,connectionName:t,schemaName:u,tableResource:c})})]})}function ml({environmentName:t,connectionName:l,schemaName:f,tableResource:a}){const{apiClients:p}=V.useServer(),{data:o,isLoading:c,isError:m,error:u}=d.useQueryWithApiError({queryKey:["connectionTableDetail",t,l,f,a],queryFn:()=>p.connections.getTable(t,l,f,a),enabled:!!f&&!!a}),h={resource:o?.data?.resource??a,columns:o?.data?.columns??[]};return n.jsxs(S.Paper,{sx:{p:1,m:0},children:[m&&n.jsx(d.ApiErrorDisplay,{error:u,context:`${t} > ${l} > ${f} > ${a}`}),!m&&n.jsx(pl,{table:h,loading:c})]})}function pl({table:t,loading:l}){return l?n.jsx(d.Loading,{text:"Loading columns..."}):n.jsxs(n.Fragment,{children:[n.jsxs(S.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(S.Divider,{}),n.jsx(S.Box,{sx:{mt:"10px",maxHeight:"600px",overflowY:"auto"},children:n.jsx(S.TableContainer,{children:n.jsxs(S.Table,{size:"small",sx:{"& .MuiTableCell-root":{padding:"10px"}},children:[n.jsx(S.TableHead,{children:n.jsxs(S.TableRow,{children:[n.jsx(S.TableCell,{children:"NAME"}),n.jsx(S.TableCell,{children:"TYPE"})]})}),n.jsx(S.TableBody,{children:t.columns?.sort((f,a)=>f.name.localeCompare(a.name))?.map(f=>n.jsxs(S.TableRow,{children:[n.jsx(S.TableCell,{children:f.name}),n.jsx(S.TableCell,{children:f.type})]},f.name))})]})})})]})}function yl({connectionName:t,schemaName:l,onTableSelect:f,resourceUri:a,connection:p}){const{environmentName:o}=d.parseResourceUri(a),{apiClients:c}=V.useServer(),[m,u]=A.useState(""),{data:h,isSuccess:x,isError:v,error:b,isLoading:g}=d.useQueryWithApiError({queryKey:["tablesInSchema",o,t,l],queryFn:()=>c.connections.listTables(o,t,l)}),k=Rs(p,l),w=M=>k?M:M.split(".").pop()||M,T=x&&h?.data?h.data.filter(M=>w(M.resource).toLowerCase().includes(m.toLowerCase())).sort((M,D)=>w(M.resource).localeCompare(w(D.resource))):[];return n.jsxs(n.Fragment,{children:[n.jsx(S.Typography,{variant:"overline",fontWeight:"bold",children:fl(l)||Rs(p,l)?`Files in ${l}`:`Tables in ${l}`}),n.jsx(S.Divider,{}),n.jsx(S.Box,{sx:{mt:1,mb:1},children:n.jsx(S.TextField,{size:"small",fullWidth:!0,placeholder:"Search tables...",value:m,onChange:M=>u(M.target.value),variant:"outlined"})}),n.jsx(S.Divider,{}),n.jsxs(S.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[g&&n.jsx(d.Loading,{text:"Fetching Tables..."}),v&&n.jsx(d.ApiErrorDisplay,{error:b,context:`${o} > ${t} > ${l}`}),x&&T.length===0&&n.jsx(S.Typography,{variant:"body2",children:"No Tables"}),x&&h?.data&&h.data.length>0&&n.jsx(S.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(S.ListItemButton,{onClick:()=>f(M.resource),children:n.jsx(S.ListItemText,{primary:D,secondary:M.columns.length>0?`${M.columns.length} columns`:void 0})},M.resource)})})]})]})}const gl={bigquery:"BigQuery",snowflake:"Snowflake",postgres:"PostgreSQL",mysql:"MySQL",trino:"Trino",databricks:"Databricks",duckdb:"DuckDB",ducklake:"DuckLake",s3:"S3",gcs:"GCS",azure:"Azure"};function xl(t){return t?gl[t]??t:""}function bl({resourceUri:t}){const{apiClients:l,mutable:f}=V.useServer(),a=kn.useQueryClient(),{environmentName:p}=d.parseResourceUri(t),[o,c]=A.useState(""),[m,u]=A.useState(null),h=d.encodeResourceUri({environmentName:p,connectionName:m}),{data:x,isSuccess:v,isError:b,error:g}=d.useQueryWithApiError({queryKey:["connections",p],queryFn:()=>l.connections.listConnections(p)}),k=d.useMutationWithApiError({mutationFn:Qe("connection","create",I=>l.environments.updateEnvironment(p,{name:p,connections:[...x.data,I]})),onSuccess(){c("Connection added successfully"),a.invalidateQueries({queryKey:["connections",p]})},onError(I){c(I.message)}}),w=d.useMutationWithApiError({mutationFn:Qe("connection","update",I=>l.environments.updateEnvironment(p,{name:p,connections:x.data.map(E=>E.name===I.name?I:E)})),onSuccess(I,E){c(`Connection ${E.name} updated successfully`),a.invalidateQueries({queryKey:["connections",p]})},onError(I){c(I.message)}}),T=d.useMutationWithApiError({mutationFn:Qe("connection","delete",I=>{if(!I.name)throw new Error("Cannot delete a connection with no name");return l.connections.deleteConnection(p,I.name)}),onSuccess(I,E){c(`Connection ${E.name} deleted successfully`),a.invalidateQueries({queryKey:["connections",p]})},onError(I){c(I.message)}}),M=v?[...x.data].sort((I,E)=>(I.name??"").localeCompare(E.name??"")):[],D=k.isPending||w.isPending||T.isPending;return n.jsxs(He,{title:"Connections",...v?{count:M.length}:{},description:"Database connections available to packages in this environment",...f&&v?{action:n.jsx(ul,{onSubmit:I=>k.mutateAsync(I),isSubmitting:k.isPending})}:{},children:[!v&&!b&&n.jsx(S.Typography,{variant:"body2",color:"text.secondary",children:"Fetching Connections..."}),b&&n.jsx(d.ApiErrorDisplay,{error:g,context:`${p} > Connections`}),v&&M.length===0&&n.jsx(S.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),v&&M.length>0&&n.jsx(S.Stack,{children:M.map(I=>n.jsx(vl,{connection:I,mutable:f,isMutating:D,onOpenExplorer:()=>u(I.name??null),onEdit:E=>w.mutateAsync(E),onDelete:E=>T.mutateAsync(E)},I.name))}),n.jsx(S.Snackbar,{open:o!=="",autoHideDuration:6e3,onClose:()=>c(""),message:o}),n.jsx(d.AppDialog,{open:m!==null,onClose:()=>u(null),maxWidth:"lg",title:`Connection explorer: ${m??""}`,showClose:!0,children:m&&n.jsx(fa,{resourceUri:h,connectionName:m,connection:x?.data?.find(I=>I.name===m)})})]})}function vl({connection:t,mutable:l,isMutating:f,onOpenExplorer:a,onEdit:p,onDelete:o}){const[c,m]=A.useState(null),u=!!c,h=v=>{v.stopPropagation(),m(v.currentTarget)},x=()=>m(null);return n.jsx(Cn,{icon:n.jsx(Xo,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.connection,label:t.name??"",ariaLabel:t.name??"",description:xl(t.type),onClick:a,...l?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(S.IconButton,{size:"small",onClick:h,"aria-label":`Connection actions for ${t.name??""}`.trim(),children:n.jsx(Ve.MoreVert,{fontSize:"small"})}),n.jsxs(S.Menu,{anchorEl:c,open:u,onClose:x,onClick:v=>v.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(hl,{connection:t,onSubmit:p,isSubmitting:f,onCloseDialog:x}),n.jsx(dl,{connection:t,onCloseDialog:x,isMutating:f,onDelete:()=>o(t)})]})]})}:{}})}const Sl=d.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 wl({resourceUri:t,onCloseDialog:l}){const[f,a]=A.useState(!1),{apiClients:p}=V.useServer(),o=()=>{a(!0)},c=()=>{a(!1),l()},{environmentName:m,packageName:u}=d.parseResourceUri(t),h=Tt({mutationFn:()=>p.packages.deletePackage(m,u),success:"Package deleted",invalidates:[["packages",m]],closeDialog:c,resource:"package",action:"delete"});return n.jsxs(A.Fragment,{children:[n.jsxs(S.MenuItem,{onClick:o,children:[n.jsx(S.ListItemIcon,{children:n.jsx(Ve.Delete,{fontSize:"small"})}),n.jsx(S.ListItemText,{children:"Delete"})]}),n.jsx(d.AppDialog,{open:f,onClose:c,title:"Delete package",actions:n.jsxs(n.Fragment,{children:[n.jsx(d.Button,{onClick:c,children:"Cancel"}),n.jsx(d.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>h.mutate(),loading:h.isPending,children:"Delete package"})]}),children:n.jsxs(d.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:u}),"? The package stops being served and this cannot be undone."]})}),h.notice]})}function kl({package:t,resourceUri:l,onCloseDialog:f}){const[a,p]=A.useState(!1),{apiClients:o}=V.useServer(),c=()=>{p(!0)},m=()=>{p(!1),f()},{packageName:u,environmentName:h}=d.parseResourceUri(l),x=Tt({mutationFn(b){return o.packages.updatePackage(h,u,{name:u,description:b.description})},success:"Package updated",invalidates:[["packages",h]],closeDialog:m,resource:"package",action:"update"}),v=b=>{b.preventDefault();const k=new FormData(b.currentTarget).get("description")?.toString();x.mutate({description:k})};return n.jsxs(A.Fragment,{children:[n.jsxs(S.MenuItem,{onClick:c,children:[n.jsx(S.ListItemIcon,{children:n.jsx(Ve.Edit,{fontSize:"small"})}),n.jsx(S.ListItemText,{children:"Edit"})]}),n.jsx(d.AppDialog,{open:a,onClose:m,title:"Edit package",description:`What ${t.name} is, for the people who open it.`,actions:n.jsxs(n.Fragment,{children:[n.jsx(d.Button,{disabled:x.isPending,onClick:m,children:"Cancel"}),n.jsx(d.Button,{type:"submit",form:"package-form",variant:"contained",loading:x.isPending,children:"Save changes"})]}),children:n.jsx("form",{onSubmit:v,id:"package-form",children:n.jsxs(S.Stack,{sx:{gap:2},children:[n.jsx(d.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(d.TextField,{id:"description",name:"description",label:"Description",multiline:!0,fullWidth:!0,rows:4,size:"small",defaultValue:t.description,InputLabelProps:{shrink:!0}})]})})}),x.notice]})}function ma({onSelectPackage:t,resourceUri:l}){const{apiClients:f}=V.useServer(),{environmentName:a}=d.parseResourceUri(l),{data:p,isSuccess:o,isError:c,error:m}=d.useQueryWithApiError({queryKey:["packages",a],queryFn:()=>f.packages.listPackages(a)});if(c)return n.jsx(d.ApiErrorDisplay,{error:m,context:`${a} > Packages`});if(!o)return n.jsx(d.Loading,{text:"Fetching Packages..."});const u=[...p.data].sort((h,x)=>h.name.localeCompare(x.name));return n.jsx(S.Stack,{children:u.map(h=>{const x=d.encodeResourceUri({environmentName:a,packageName:h.name});return n.jsx(Cl,{pkg:h,packageResourceUri:x,onSelectPackage:t},h.name)})})}function Cl({pkg:t,packageResourceUri:l,onSelectPackage:f}){const{mutable:a}=V.useServer(),[p,o]=A.useState(null),c=!!p,m=h=>{h.stopPropagation(),o(h.currentTarget)},u=()=>o(null);return n.jsx(Cn,{icon:n.jsx(Sl,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.package,label:t.name,ariaLabel:t.name,...t.description?{description:t.description}:{},onClick:h=>f(t.name,h),...a?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(S.IconButton,{size:"small",onClick:m,"aria-label":`Package actions for ${t.name}`,children:n.jsx(Ve.MoreVert,{fontSize:"small"})}),n.jsxs(S.Menu,{anchorEl:p,open:c,onClose:u,onClick:h=>h.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(kl,{package:t,resourceUri:l,onCloseDialog:u}),n.jsx(wl,{resourceUri:l,onCloseDialog:u})]})]})}:{}})}function Tl({onSelectPackage:t,resourceUri:l}){const{apiClients:f,mutable:a}=V.useServer(),{environmentName:p}=d.parseResourceUri(l),o=d.useQueryWithApiError({queryKey:["packages",p],queryFn:()=>f.packages.listPackages(p)});return A.useEffect(()=>{window.scrollTo({top:0,behavior:"auto"})},[]),n.jsxs(S.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[n.jsxs(S.Box,{sx:{mb:4},children:[n.jsx(S.Box,{children:n.jsx(dr,{label:"Publisher",onClick:c=>t("/",c)})}),n.jsx(S.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em",mb:.5},children:p}),n.jsx(S.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(He,{title:"Packages",...o.isSuccess?{count:o.data.data.length}:{},description:"Published packages available for use in this environment",...a?{action:n.jsx(Go,{resourceUri:l})}:{},children:n.jsx(ma,{onSelectPackage:t,resourceUri:l})}),n.jsx(bl,{resourceUri:l}),n.jsx(Ao,{resourceUri:l})]})}d.dayjs.extend(d.utc);function Bn(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 Ml(t){return t==="DateMinMax"}function Yn(t){return t==="Between"}function Dl({spec:t,values:l,selection:f,onChange:a,retrievalFn:p}){const o=()=>f?.matchType?f.matchType:t.defaultMatchType?t.defaultMatchType:t.filterType==="DateMinMax"?"Between":Bn(t.filterType)[0]||"Equals",[c,m]=A.useState(o()),[u,h]=A.useState(f?.value??""),[x,v]=A.useState(f?.value2??""),[b,g]=A.useState([]),[k,w]=A.useState(!1),[T,M]=A.useState(""),[D,I]=A.useState(!1),[E,L]=A.useState(!1),z=A.useRef(null),P=A.useRef(0),[Z,N]=A.useState(!1);A.useEffect(()=>{if(t.filterType!=="Retrieval"||!p)return;const W=T.trim();if(W.length<=2){g([]),I(!1);return}return z.current&&clearTimeout(z.current),z.current=setTimeout(async()=>{P.current+=1;const J=P.current;w(!0);try{const $=await p(W,t);J===P.current&&g($)}catch($){J===P.current&&(console.error("Retrieval failed",$),g([]))}finally{J===P.current&&(w(!1),I(!0))}},500),()=>{z.current&&clearTimeout(z.current)}},[T,t,p]),A.useEffect(()=>{f===null?(h(""),v(""),m(t.defaultMatchType??(t.filterType==="DateMinMax"?"Between":Bn(t.filterType)[0]||"Equals"))):f&&(m(f.matchType),h(f.value??""),v(f.value2??""))},[f,t.filterType,t.defaultMatchType]);const q=Bn(t.filterType),U=Ml(t.filterType),R=Yn(c),_=U&&l.length>=2&&l[0].value instanceof Date?d.dayjs.utc(l[0].value):void 0,Y=U&&l.length>=2&&l[1].value instanceof Date?d.dayjs.utc(l[1].value):void 0,Q=t.filterType==="MinMax"&&l.length>=2&&typeof l[0].value=="number"?l[0].value:void 0,K=t.filterType==="MinMax"&&l.length>=2&&typeof l[1].value=="number"?l[1].value:void 0;if(q.length===0)return null;const ee=W=>{const J=W.target.value;m(J),Yn(J)||v(""),u&&a({dimensionName:t.dimensionName,source:t.source,filterName:t.filterName,matchType:J,value:u,...Yn(J)&&x&&{value2:x}})},B=(W,J)=>{h(W??""),J!==void 0&&v(J??"");const $=Array.isArray(W)&&W.length===0;a(!$&&W!==""&&W!==null&&W!==void 0?{dimensionName:t.dimensionName,source:t.source,filterName:t.filterName,matchType:c,value:W,...R&&J&&{value2:J}}:null)},te=()=>{h(""),v(""),a(null)};return n.jsxs(me,{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(me,{sx:{fontWeight:600,color:t.required&&!f?"error.main":"text.primary"},children:[t.label??t.dimensionName,t.required&&n.jsx(me,{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(d.FormControl,{size:"small",fullWidth:!0,children:[n.jsx(d.InputLabel,{children:"Match Type"}),n.jsx(d.Select,{value:c,label:"Match Type",onChange:ee,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:q.map(W=>n.jsx(ge,{value:W,children:W},W))})]}),t.filterType==="Star"&&c==="Equals"&&n.jsx(d.Autocomplete,{multiple:!0,size:"small",options:l,getOptionLabel:W=>typeof W=="string"?W:typeof W=="object"&&W!==null&&"value"in W?String(W.value):String(W),value:Array.isArray(u)?u.map(W=>l.find(J=>J.value===W)||W):u?[l.find(W=>W.value===u)||u]:[],onChange:(W,J)=>{const $=J.map(X=>typeof X=="string"?X:X&&typeof X=="object"&&"value"in X?X.value:X);B($)},noOptionsText:"No matches found",renderInput:W=>n.jsx(d.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"&&c==="Contains"&&n.jsx(d.TextField,{size:"small",label:"Search Text",value:u,onChange:W=>h(W.target.value),onBlur:()=>B(u),onKeyDown:W=>{W.key==="Enter"&&B(u)},placeholder:"Enter text to search...",fullWidth:!0}),t.filterType==="Boolean"&&n.jsxs(d.FormControl,{size:"small",fullWidth:!0,children:[n.jsx(d.InputLabel,{children:"Value"}),n.jsxs(d.Select,{value:u===!0?"true":u===!1?"false":"",label:"Value",onChange:W=>{const J=W.target.value;J==="true"?B(!0):J==="false"?B(!1):te()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[n.jsx(ge,{value:"",children:n.jsx("em",{children:"Blank"})}),n.jsx(ge,{value:"true",children:"True"}),n.jsx(ge,{value:"false",children:"False"})]})]}),t.filterType==="Retrieval"&&c==="Semantic Search"&&n.jsx(d.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(u)?u.map(W=>b.find($=>$.value===W)||{value:W}):u?[{value:u}]:[],onInputChange:(W,J)=>{M(J)},onChange:(W,J)=>{const $=J.map(X=>typeof X=="string"?X:X&&typeof X=="object"&&"value"in X?X.value:X);B($)},noOptionsText:T.trim().length<=2?"Type at least 3 characters to search":"No matches found",renderInput:W=>n.jsx(d.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(d.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"&&!R&&n.jsx(d.TextField,{size:"small",type:"number",label:"Value",value:u,onChange:W=>B(parseFloat(W.target.value)||""),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:Q,max:K},helperText:Z&&Q!==void 0&&K!==void 0?`Valid range: [${Q} - ${K}]`:void 0}),t.filterType==="MinMax"&&R&&n.jsxs(me,{sx:{display:"flex",flexDirection:"column",gap:1},children:[n.jsxs(me,{sx:{display:"flex",gap:1,alignItems:"center"},children:[n.jsx(d.TextField,{size:"small",type:"number",label:"From",value:u,onChange:W=>B(parseFloat(W.target.value)||"",x),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:Q,max:x||K}}),n.jsx(me,{children:"to"}),n.jsx(d.TextField,{size:"small",type:"number",label:"To",value:x,onChange:W=>B(u,parseFloat(W.target.value)||""),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:u||Q,max:K}})]}),Z&&Q!==void 0&&K!==void 0&&n.jsxs(d.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",Q," - ",K,"]"]})]}),U&&!R&&n.jsx(d.LocalizationProvider,{dateAdapter:d.AdapterDayjs,children:n.jsx(d.DatePicker,{label:"Date",value:u instanceof Date?d.dayjs.utc(u):null,onChange:W=>{W===null?B(null):W.isValid()&&B(W.utc().toDate())},timezone:"UTC",minDate:u instanceof Date?void 0:_,maxDate:u instanceof Date?void 0:Y,referenceDate:c==="After"&&_?_:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>N(!0),onBlur:()=>N(!1),helperText:Z&&_&&Y?`Valid range: [${_.format("YYYY-MM-DD")} - ${Y.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),U&&R&&n.jsx(d.LocalizationProvider,{dateAdapter:d.AdapterDayjs,children:n.jsxs(me,{sx:{display:"flex",flexDirection:"column",gap:1},children:[n.jsxs(me,{sx:{display:"flex",gap:1,alignItems:"center"},children:[n.jsx(me,{sx:{flex:1,minWidth:0},children:n.jsx(d.DatePicker,{label:"From",value:u instanceof Date?d.dayjs.utc(u):null,onChange:W=>{W===null?B(null,x):W.isValid()&&B(W.utc().toDate(),x)},timezone:"UTC",minDate:u instanceof Date?void 0:_,maxDate:x instanceof Date?d.dayjs.utc(x):u instanceof Date?void 0:Y,referenceDate:_,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>N(!0),onBlur:()=>N(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),n.jsx(me,{children:"to"}),n.jsx(me,{sx:{flex:1,minWidth:0},children:n.jsx(d.DatePicker,{label:"To",value:x instanceof Date?d.dayjs.utc(x):null,onChange:W=>{W===null?B(u,null):W.isValid()&&B(u,W.utc().toDate())},timezone:"UTC",minDate:u instanceof Date?d.dayjs.utc(u):x instanceof Date?void 0:_,maxDate:x instanceof Date?void 0:Y,referenceDate:u instanceof Date?d.dayjs.utc(u):_,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>N(!0),onBlur:()=>N(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),Z&&_&&Y&&n.jsxs(d.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",_.format("YYYY-MM-DD")," -"," ",Y.format("YYYY-MM-DD"),"]"]})]})})]})}function jl(t){const l=new Set,f=t.schema?.fields;if(!f)return l;for(const a of f)"kind"in a&&a.kind==="join"&&a.name&&l.add(a.name);return l}function Ol(t){if(!t)return null;for(const l of t)if(l.startsWith("##(filters)")){const f=l.slice(11).trim();try{const a=JSON.parse(f);if(Array.isArray(a)){const p=[];for(const o of a)if(typeof o=="string"){const c=o.indexOf(".");c>0&&c<o.length-1&&p.push({source:o.substring(0,c),dimension:o.substring(c+1)})}if(p.length>0)return{filters:p}}}catch(a){console.error(`Failed to parse "${l}" annotation:`,a)}}return null}function pa(t){if(t.startsWith("#(filter)")){const l=t.slice(9).trim();try{const f=JSON.parse(l);if(f.type)return f}catch(f){console.error(`Failed to parse "${t}" annotation:`,f)}}return null}function El(t){const l=t.match(/^#\s*label\s*=\s*"([^"]+)"/);return l?l[1]:null}function Il(t){const l=new Map;let f="";for(const a of t)if(a.type==="code"){if(!f&&a.text){const o=a.text.split(`
2
2
  `).map(c=>c.trim()).find(c=>c.startsWith("import "))?.match(/['"]([^'"\n]+)['"]/);o&&(f=o[1])}if(a.newSources&&a.newSources.length>0)for(const p of a.newSources)try{const o=JSON.parse(p);o.name&&l.set(o.name,o)}catch(o){console.error("Failed to parse SourceInfo:",o)}}return{sourceInfoMap:l,modelPath:f}}function Fl(t,l,f){const a=[];for(const{source:p,dimension:o}of l){const c=t.get(p);if(!c){console.warn(`Source "${p}" not found in notebook sources`),a.push({source:p,model:f,dimensionName:o,filterType:"Star"});continue}const m=c.schema?.fields;if(!m){a.push({source:p,model:f,dimensionName:o,filterType:"Star"});continue}const u=m.find(v=>v.name===o);if(!u){console.warn(`Dimension "${o}" not found in source "${p}"`),a.push({source:p,model:f,dimensionName:o,filterType:"Star"});continue}let h="Star",x;if("annotations"in u&&u.annotations){for(const v of u.annotations)if(v.value){const b=pa(v.value);b&&(h=b.type);const g=El(v.value);g&&(x=g)}}a.push({source:p,model:f,dimensionName:o,filterType:h,label:x})}return a}function Nl(t,l,f){return t.length===0?"":t.map(p=>{const{dimensionName:o,source:c,matchType:m,value:u,value2:h}=p,v=c&&c!==f?`\`${c}\`.\`${o}\``:`\`${o}\``,b=u 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"?`'${d.escapeMalloyString(k)}'`:typeof k=="boolean"?k?"true":"false":String(k);switch(m){case"Equals":case"Semantic Search":return Array.isArray(u)&&u.length>0?`(${u.map(w=>`${v} = ${g(w,b)}`).join(" or ")})`:`${v} = ${g(u,b)}`;case"Contains":return typeof u=="string"?`${v} ~ f'%${d.escapeMalloyString(u)}%'`:`${v} = ${g(u)}`;case"After":case"Greater Than":return`${v} > ${g(u,b)}`;case"Before":case"Less Than":return`${v} < ${g(u,b)}`;case"Between":return h!==void 0?`${v} >= ${g(u,b)} and ${v} <= ${g(h,b)}`:`${v} >= ${g(u,b)}`;default:return""}}).filter(p=>p.length>0).join(" and ")}function Al(t){const l=t.match(/run\s*:\s*(\w+)\s*->/);if(l)return l[1];const f=t.match(/^\s*(\w+)\s*->/m);return f?f[1]:null}function $l(t,l){return`${t.trimEnd()} + {where: ${l}}`}const Rl=d.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"})),ya=t=>{if(!t)return"Explore semantic models, run queries, and build dashboards";const l=t.replace(/^#+\s+/gm,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/`([^`]+)`/g,"$1").trim(),a=l.split(/\n\s*\n/)[1]||l;if(a.length<=120)return a;const p=a.substring(0,120).split(" ");return p.pop(),p.join(" ")+"..."},ga=(t,l)=>{const f=(t.readme||void 0)?.split(`
3
3
  `)??[];return f.length===0&&(f.push(`# ${t.name}`),f.push("")),(t.readme?.length??0)>0&&l?f.splice(2,1,l):l&&f.push(l),f.join(`
4
4
  `)};function Ls(){const[t,l]=A.useState(!1),{apiClients:f}=V.useServer(),a=()=>{l(!0)},p=()=>{l(!1)},o=Tt({mutationFn(m){return f.environments.createEnvironment({name:m.name,readme:ga({name:m.name,readme:""},m.description)})},success:"Environment created",invalidates:[["environments"]],closeDialog:p,resource:"environment",action:"create"}),c=async m=>{m.preventDefault();const u=new FormData(m.currentTarget),h=u.get("name")?.toString(),x=u.get("description")?.toString();if(!h)throw new Error("Name is required");o.mutate({name:h,description:x})};return n.jsxs(A.Fragment,{children:[n.jsx(d.AddButton,{label:"Environment",onClick:a}),n.jsx(d.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(d.Button,{disabled:o.isPending,onClick:p,children:"Cancel"}),n.jsx(d.Button,{type:"submit",form:"environment-form",variant:"contained",loading:o.isPending,children:"Create environment"})]}),children:n.jsx("form",{onSubmit:c,id:"environment-form",children:n.jsxs(Tn,{sx:{gap:2},children:[n.jsx(d.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(d.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}})]})})}),o.notice]})}function Ll({environment:t,onCloseDialog:l}){const[f,a]=A.useState(!1),{apiClients:p}=V.useServer(),o=()=>{a(!0)},c=()=>{a(!1),l()},m=Tt({mutationFn:()=>p.environments.deleteEnvironment(t.name),success:"Environment deleted",invalidates:[["environments"]],closeDialog:c,resource:"environment",action:"delete"});return n.jsxs(A.Fragment,{children:[n.jsxs(S.MenuItem,{onClick:o,children:[n.jsx(S.ListItemIcon,{children:n.jsx(Ve.Delete,{fontSize:"small"})}),n.jsx(S.ListItemText,{children:"Delete"})]}),n.jsx(d.AppDialog,{open:f,onClose:c,title:"Delete environment",actions:n.jsxs(n.Fragment,{children:[n.jsx(d.Button,{onClick:c,children:"Cancel"}),n.jsx(d.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>m.mutate(),loading:m.isPending,children:"Delete environment"})]}),children:n.jsxs(d.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:t.name}),"? Its packages stop being served and this cannot be undone."]})}),m.notice]})}function _l({environment:t,onCloseDialog:l}){const[f,a]=A.useState(!1),{apiClients:p}=V.useServer(),o=()=>{a(!0)},c=()=>{a(!1),l()},m=Tt({mutationFn(h){return p.environments.updateEnvironment(t.name,{name:t.name,readme:ga({name:t.name,readme:t.readme},h.description)})},success:"Environment updated",invalidates:[["environments"]],closeDialog:c,resource:"environment",action:"update"}),u=h=>{h.preventDefault();const v=new FormData(h.currentTarget).get("description")?.toString();m.mutate({description:v})};return n.jsxs(A.Fragment,{children:[n.jsxs(S.MenuItem,{onClick:o,children:[n.jsx(S.ListItemIcon,{children:n.jsx(Ve.Edit,{fontSize:"small"})}),n.jsx(S.ListItemText,{children:"Edit"})]}),n.jsx(d.AppDialog,{open:f,onClose:c,title:"Edit environment",description:"What this environment is, for the people who open it.",actions:n.jsxs(n.Fragment,{children:[n.jsx(d.Button,{disabled:m.isPending,onClick:c,children:"Cancel"}),n.jsx(d.Button,{type:"submit",form:"environment-form",variant:"contained",loading:m.isPending,children:"Save changes"})]}),children:n.jsx("form",{onSubmit:u,id:"environment-form",children:n.jsxs(Tn,{sx:{gap:2},children:[n.jsx(d.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(d.TextField,{id:"description",name:"description",label:"Description",type:"text",fullWidth:!0,size:"small",defaultValue:ya(t.readme),InputLabelProps:{shrink:!0}})]})})}),m.notice]})}const Pl=[{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:Ke.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:Ke.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:Ke.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:Ke.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:Ke.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:Ke.connections}];function ql({href:t,children:l}){return n.jsx(S.Box,{component:"a",href:t,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary",textDecoration:"underline"},children:l})}function Wl({onClickEnvironment:t}){const{apiClients:l,mutable:f}=V.useServer(),{data:a,isSuccess:p,isError:o,error:c}=d.useQueryWithApiError({queryKey:["environments"],queryFn:()=>l.environments.listEnvironments()});if(o)return n.jsx(d.ApiErrorDisplay,{error:c,context:"Environments List"});if(!p)return n.jsx(d.Loading,{text:"Loading environments..."});const m=a.data??[];return n.jsxs(S.Container,{maxWidth:"md",sx:{py:6},children:[n.jsxs(S.Box,{sx:{mb:5},children:[n.jsx(S.Typography,{variant:"h3",component:"h1",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Publisher"}),n.jsx(S.Typography,{variant:"body1",color:"text.secondary",sx:{mb:3},children:"The analytics engine for Malloy."}),n.jsx(S.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(S.Grid,{container:!0,spacing:4,sx:{mb:5},children:Pl.map(u=>n.jsx(S.Grid,{size:{xs:12,sm:6},children:n.jsxs(S.Stack,{spacing:1,children:[n.jsx(S.Typography,{variant:"body2",component:"a",href:u.href,target:"_blank",rel:"noopener noreferrer",sx:{fontWeight:500,color:"text.primary",textDecoration:"none","&:hover":{textDecoration:"underline"}},children:u.title}),n.jsx(S.Typography,{variant:"body2",color:"text.secondary",sx:{lineHeight:1.6},children:u.body})]})},u.title))}),n.jsx(S.Divider,{sx:{my:4}}),m.length>0?n.jsx(He,{title:"Environments",count:m.length,description:"Published environments available on this server",...f?{action:n.jsx(Ls,{})}:{},children:n.jsx(S.Stack,{children:m.map(u=>n.jsx(zl,{environment:u,...t?{onClickEnvironment:t}:{}},u.name))})}):n.jsxs(S.Box,{sx:{mb:4},children:[n.jsx(S.Typography,{variant:"h5",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Get started"}),n.jsx(S.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(Ls,{}):n.jsx(S.Button,{variant:"contained",color:"primary",href:Ke.publishing,target:"_blank",rel:"noopener noreferrer",children:"Learn how to create models"})]}),n.jsx(S.Divider,{sx:{my:4}}),n.jsxs(S.Typography,{variant:"body2",color:"text.secondary",sx:{maxWidth:720,lineHeight:1.6,mt:2},children:["Join the"," ",n.jsx(ql,{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 zl({environment:t,onClickEnvironment:l}){const{mutable:f}=V.useServer(),[a,p]=A.useState(null),o=!!a,c=ya(t.readme),m=h=>{h.stopPropagation(),p(h.currentTarget)},u=()=>p(null);return n.jsx(Cn,{icon:n.jsx(Rl,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.environment,label:t.name??"",ariaLabel:t.name??"",...c?{description:c}:{},...t.name&&l?{onClick:h=>l(`/${t.name}/`,h)}:{},...f?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(S.IconButton,{size:"small",onClick:m,"aria-label":`Environment actions for ${t.name}`,children:n.jsx(Ve.MoreVert,{fontSize:"small"})}),n.jsxs(S.Menu,{anchorEl:a,open:o,onClose:u,onClick:h=>h.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(_l,{environment:t,onCloseDialog:u}),n.jsx(Ll,{environment:t,onCloseDialog:u})]})]})}:{}})}var it={},Ee={},qt={},ot={},Zn={},_s;function Hl(){return _s||(_s=1,Object.defineProperty(Zn,"__esModule",{value:!0})),Zn}var Wt={},zt={},Ps;function ut(){if(Ps)return zt;Ps=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.CronField=void 0;let t=class xa{#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(xa.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",o=typeof a=="number";return p&&o?f-a:!p&&!o?f.localeCompare(a):p?-1:1}static findNearestValueInList(f,a,p){if(p){for(let o=f.length-1;o>=0;o--)if(f[o]<a)return f[o];return null}for(let o=0;o<f.length;o++)if(f[o]>a)return f[o];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=u=>h=>new RegExp(`^\\d{0,2}${h}$`).test(u),o=u=>(f=u,typeof u=="number"?u>=this.min&&u<=this.max:this.chars.some(p(u)));if(!this.#s.every(o))throw new Error(`${this.constructor.name} Validation error, got value ${f} expected range ${this.min}-${this.max}${a}`);const m=this.#s.find((u,h)=>this.#s.indexOf(u)!==h);if(m)throw new Error(`${this.constructor.name} Validation error, duplicate values found: ${m}`)}#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 zt.CronField=t,zt}var qs;function Vl(){if(qs)return Wt;qs=1,Object.defineProperty(Wt,"__esModule",{value:!0}),Wt.CronDayOfMonth=void 0;const t=ut(),l=1,f=31,a=Object.freeze(["L"]);let p=class extends t.CronField{static get min(){return l}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(c,m){super(c,m),this.validate()}get values(){return super.values}};return Wt.CronDayOfMonth=p,Wt}var Ht={},Ws;function Ul(){if(Ws)return Ht;Ws=1,Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.CronDayOfWeek=void 0;const t=ut(),l=0,f=7,a=Object.freeze(["L"]);let p=class extends t.CronField{static get min(){return l}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(c,m){super(c,m),this.validate()}get values(){return super.values}get nthDay(){return this.options.nthDayOfWeek??0}};return Ht.CronDayOfWeek=p,Ht}var Vt={},zs;function Bl(){if(zs)return Vt;zs=1,Object.defineProperty(Vt,"__esModule",{value:!0}),Vt.CronHour=void 0;const t=ut(),l=0,f=23,a=Object.freeze([]);let p=class extends t.CronField{static get min(){return l}static get max(){return f}static get chars(){return a}constructor(c,m){super(c,m),this.validate()}get values(){return super.values}};return Vt.CronHour=p,Vt}var Ut={},Hs;function Yl(){if(Hs)return Ut;Hs=1,Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.CronMinute=void 0;const t=ut(),l=0,f=59,a=Object.freeze([]);let p=class extends t.CronField{static get min(){return l}static get max(){return f}static get chars(){return a}constructor(c,m){super(c,m),this.validate()}get values(){return super.values}};return Ut.CronMinute=p,Ut}var Bt={},Gn={},je={},Vs;function Zl(){if(Vs)return je;Vs=1,Object.defineProperty(je,"__esModule",{value:!0});class t extends Error{}class l 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 o extends t{constructor(e){super(`Invalid unit ${e}`)}}class c extends t{}class m extends t{constructor(){super("Zone is an abstract class")}}const u="numeric",h="short",x="long",v={year:u,month:u,day:u},b={year:u,month:h,day:u},g={year:u,month:h,day:u,weekday:h},k={year:u,month:x,day:u},w={year:u,month:x,day:u,weekday:x},T={hour:u,minute:u},M={hour:u,minute:u,second:u},D={hour:u,minute:u,second:u,timeZoneName:h},I={hour:u,minute:u,second:u,timeZoneName:x},E={hour:u,minute:u,hourCycle:"h23"},L={hour:u,minute:u,second:u,hourCycle:"h23"},z={hour:u,minute:u,second:u,hourCycle:"h23",timeZoneName:h},P={hour:u,minute:u,second:u,hourCycle:"h23",timeZoneName:x},Z={year:u,month:u,day:u,hour:u,minute:u},N={year:u,month:u,day:u,hour:u,minute:u,second:u},q={year:u,month:h,day:u,hour:u,minute:u},U={year:u,month:h,day:u,hour:u,minute:u,second:u},R={year:u,month:h,day:u,weekday:h,hour:u,minute:u},_={year:u,month:x,day:u,hour:u,minute:u,timeZoneName:h},Y={year:u,month:x,day:u,hour:u,minute:u,second:u,timeZoneName:h},Q={year:u,month:x,day:u,weekday:x,hour:u,minute:u,timeZoneName:x},K={year:u,month:x,day:u,weekday:x,hour:u,minute:u,second:u,timeZoneName:x};class ee{get type(){throw new m}get name(){throw new m}get ianaName(){return this.name}get isUniversal(){throw new m}offsetName(e,r){throw new m}formatOffset(e,r){throw new m}offset(e){throw new m}equals(e){throw new m}get isValid(){throw new m}}let B=null;class te extends ee{static get instance(){return B===null&&(B=new te),B}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:i}){return Wr(e,r,i)}formatOffset(e,r){return Ot(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 J(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 $={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function X(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,H,ne]=i;return[j,y,C,O,F,H,ne]}function le(s,e){const r=s.formatToParts(e),i=[];for(let y=0;y<r.length;y++){const{type:C,value:j}=r[y],O=$[C];C==="era"?i[O]=j:se(O)||(i[O]=parseInt(j,10))}return i}const G=new Map;class oe extends ee{static create(e){let r=G.get(e);return r===void 0&&G.set(e,r=new oe(e)),r}static resetCache(){G.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=oe.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:i}){return Wr(e,r,i,this.name)}formatOffset(e,r){return Ot(this.offset(e),r)}offset(e){if(!this.valid)return NaN;const r=new Date(e);if(isNaN(r))return NaN;const i=J(this.name);let[y,C,j,O,F,H,ne]=i.formatToParts?le(i,r):X(i,r);O==="BC"&&(y=-Math.abs(y)+1);const fe=on({year:y,month:C,day:j,hour:F===24?0:F,minute:H,second:ne,millisecond:0});let re=+r;const be=re%1e3;return re-=be>=0?be:1e3+be,(fe-re)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let we={};function ve(s,e={}){const r=JSON.stringify([s,e]);let i=we[r];return i||(i=new Intl.ListFormat(s,e),we[r]=i),i}const Te=new Map;function Fe(s,e={}){const r=JSON.stringify([s,e]);let i=Te.get(r);return i===void 0&&(i=new Intl.DateTimeFormat(s,e),Te.set(r,i)),i}const Oe=new Map;function Me(s,e={}){const r=JSON.stringify([s,e]);let i=Oe.get(r);return i===void 0&&(i=new Intl.NumberFormat(s,e),Oe.set(r,i)),i}const De=new Map;function Se(s,e={}){const{base:r,...i}=e,y=JSON.stringify([s,i]);let C=De.get(y);return C===void 0&&(C=new Intl.RelativeTimeFormat(s,e),De.set(y,C)),C}let Ne=null;function Mt(){return Ne||(Ne=new Intl.DateTimeFormat().resolvedOptions().locale,Ne)}const Le=new Map;function tn(s){let e=Le.get(s);return e===void 0&&(e=new Intl.DateTimeFormat(s).resolvedOptions(),Le.set(s,e)),e}const Ge=new Map;function Ra(s){let e=Ge.get(s);if(!e){const r=new Intl.Locale(s);e="getWeekInfo"in r?r.getWeekInfo():r.weekInfo,"minimalDays"in e||(e={...gr,...e}),Ge.set(s,e)}return e}function La(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=Fe(s).resolvedOptions(),y=s}catch{const F=s.substring(0,r);i=Fe(F).resolvedOptions(),y=F}const{numberingSystem:C,calendar:j}=i;return[y,C,j]}}function _a(s,e,r){return(r||e)&&(s.includes("-u-")||(s+="-u"),r&&(s+=`-ca-${r}`),e&&(s+=`-nu-${e}`)),s}function Pa(s){const e=[];for(let r=1;r<=12;r++){const i=ae.utc(2009,r,1);e.push(s(i))}return e}function qa(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 nn(s,e,r,i){const y=s.listingMode();return y==="error"?null:y==="en"?r(e):i(e)}function Wa(s){return s.numberingSystem&&s.numberingSystem!=="latn"?!1:s.numberingSystem==="latn"||!s.locale||s.locale.startsWith("en")||tn(s.locale).numberingSystem==="latn"}class za{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=Me(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):An(e,3);return xe(r,this.padTo)}}}class Ha{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&&oe.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=Fe(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 Va{constructor(e,r,i){this.opts={style:"long",...i},!r&&Lr()&&(this.rtf=Se(e,i))}format(e,r){return this.rtf?this.rtf.format(e,r):di(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}}const gr={firstDay:1,minimalDays:4,weekend:[6,7]};class de{static fromOpts(e){return de.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,r,i,y,C=!1){const j=e||pe.defaultLocale,O=j||(C?"en-US":Mt()),F=r||pe.defaultNumberingSystem,H=i||pe.defaultOutputCalendar,ne=Fn(y)||pe.defaultWeekSettings;return new de(O,F,H,ne,j)}static resetCache(){Ne=null,Te.clear(),Oe.clear(),De.clear(),Le.clear(),Ge.clear()}static fromObject({locale:e,numberingSystem:r,outputCalendar:i,weekSettings:y}={}){return de.create(e,r,i,y)}constructor(e,r,i,y,C){const[j,O,F]=La(e);this.locale=j,this.numberingSystem=r||O||null,this.outputCalendar=i||F||null,this.weekSettings=y,this.intl=_a(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=Wa(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:de.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,Fn(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 nn(this,e,Vr,()=>{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]=Pa(j)}return this.monthsCache[C][e]})}weekdays(e,r=!1){return nn(this,e,Yr,()=>{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]=qa(C=>this.extract(C,i,"weekday"))),this.weekdaysCache[y][e]})}meridiems(){return nn(this,void 0,()=>Zr,()=>{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 nn(this,e,Gr,()=>{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 za(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new Ha(e,this.intl,r)}relFormatter(e={}){return new Va(this.intl,this.isEnglish(),e)}listFormatter(e={}){return ve(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||tn(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:_r()?Ra(this.locale):gr}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 Mn=null;class ke extends ee{static get utcInstance(){return Mn===null&&(Mn=new ke(0)),Mn}static instance(e){return e===0?ke.utcInstance:new ke(e)}static parseSpecifier(e){if(e){const r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new ke(ln(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Ot(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Ot(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return Ot(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 xr extends ee{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 et(s,e){if(se(s)||s===null)return e;if(s instanceof ee)return s;if(Xa(s)){const r=s.toLowerCase();return r==="default"?e:r==="local"||r==="system"?te.instance:r==="utc"||r==="gmt"?ke.utcInstance:ke.parseSpecifier(r)||oe.create(s)}else return tt(s)?ke.instance(s):typeof s=="object"&&"offset"in s&&typeof s.offset=="function"?s:new xr(s)}const Dn={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},br={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]},Ua=Dn.hanidec.replace(/[\[|\]]/g,"").split("");function Ba(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(Dn.hanidec)!==-1)e+=Ua.indexOf(s[r]);else for(const y in br){const[C,j]=br[y];i>=C&&i<=j&&(e+=i-C)}}return parseInt(e,10)}else return e}const jn=new Map;function Ya(){jn.clear()}function _e({numberingSystem:s},e=""){const r=s||"latn";let i=jn.get(r);i===void 0&&(i=new Map,jn.set(r,i));let y=i.get(e);return y===void 0&&(y=new RegExp(`${Dn[r]}${e}`),i.set(e,y)),y}let vr=()=>Date.now(),Sr="system",wr=null,kr=null,Cr=null,Tr=60,Mr,Dr=null;class pe{static get now(){return vr}static set now(e){vr=e}static set defaultZone(e){Sr=e}static get defaultZone(){return et(Sr,te.instance)}static get defaultLocale(){return wr}static set defaultLocale(e){wr=e}static get defaultNumberingSystem(){return kr}static set defaultNumberingSystem(e){kr=e}static get defaultOutputCalendar(){return Cr}static set defaultOutputCalendar(e){Cr=e}static get defaultWeekSettings(){return Dr}static set defaultWeekSettings(e){Dr=Fn(e)}static get twoDigitCutoffYear(){return Tr}static set twoDigitCutoffYear(e){Tr=e%100}static get throwOnInvalid(){return Mr}static set throwOnInvalid(e){Mr=e}static resetCaches(){de.resetCache(),oe.resetCache(),ae.resetCache(),Ya()}}class Pe{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const jr=[0,31,59,90,120,151,181,212,243,273,304,334],Or=[0,31,60,91,121,152,182,213,244,274,305,335];function Ae(s,e){return new Pe("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${s}, which is invalid`)}function On(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 Er(s,e,r){return r+(Dt(s)?Or:jr)[e-1]}function Ir(s,e){const r=Dt(s)?Or:jr,i=r.findIndex(C=>C<e),y=e-r[i];return{month:i+1,day:y}}function En(s,e){return(s-e+7)%7+1}function rn(s,e=4,r=1){const{year:i,month:y,day:C}=s,j=Er(i,y,C),O=En(On(i,y,C),r);let F=Math.floor((j-O+14-e)/7),H;return F<1?(H=i-1,F=jt(H,e,r)):F>jt(i,e,r)?(H=i+1,F=1):H=i,{weekYear:H,weekNumber:F,weekday:O,...un(s)}}function Fr(s,e=4,r=1){const{weekYear:i,weekNumber:y,weekday:C}=s,j=En(On(i,1,e),r),O=ht(i);let F=y*7+C-j-7+e,H;F<1?(H=i-1,F+=ht(H)):F>O?(H=i+1,F-=ht(i)):H=i;const{month:ne,day:ie}=Ir(H,F);return{year:H,month:ne,day:ie,...un(s)}}function In(s){const{year:e,month:r,day:i}=s,y=Er(e,r,i);return{year:e,ordinal:y,...un(s)}}function Nr(s){const{year:e,ordinal:r}=s,{month:i,day:y}=Ir(e,r);return{year:e,month:i,day:y,...un(s)}}function Ar(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=sn(s.weekYear),y=$e(s.weekNumber,1,jt(s.weekYear,e,r)),C=$e(s.weekday,1,7);return i?y?C?!1:Ae("weekday",s.weekday):Ae("week",s.weekNumber):Ae("weekYear",s.weekYear)}function Ga(s){const e=sn(s.year),r=$e(s.ordinal,1,ht(s.year));return e?r?!1:Ae("ordinal",s.ordinal):Ae("year",s.year)}function $r(s){const e=sn(s.year),r=$e(s.month,1,12),i=$e(s.day,1,an(s.year,s.month));return e?r?i?!1:Ae("day",s.day):Ae("month",s.month):Ae("year",s.year)}function Rr(s){const{hour:e,minute:r,second:i,millisecond:y}=s,C=$e(e,0,23)||e===24&&r===0&&i===0&&y===0,j=$e(r,0,59),O=$e(i,0,59),F=$e(y,0,999);return C?j?O?F?!1:Ae("millisecond",y):Ae("second",i):Ae("minute",r):Ae("hour",e)}function se(s){return typeof s>"u"}function tt(s){return typeof s=="number"}function sn(s){return typeof s=="number"&&s%1===0}function Xa(s){return typeof s=="string"}function Ka(s){return Object.prototype.toString.call(s)==="[object Date]"}function Lr(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function _r(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function Qa(s){return Array.isArray(s)?s:[s]}function Pr(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 Ja(s,e){return e.reduce((r,i)=>(r[i]=s[i],r),{})}function dt(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Fn(s){if(s==null)return null;if(typeof s!="object")throw new c("Week settings must be an object");if(!$e(s.firstDay,1,7)||!$e(s.minimalDays,1,7)||!Array.isArray(s.weekend)||s.weekend.some(e=>!$e(e,1,7)))throw new c("Invalid week settings");return{firstDay:s.firstDay,minimalDays:s.minimalDays,weekend:Array.from(s.weekend)}}function $e(s,e,r){return sn(s)&&s>=e&&s<=r}function ei(s,e){return s-e*Math.floor(s/e)}function xe(s,e=2){const r=s<0;let i;return r?i="-"+(""+-s).padStart(e,"0"):i=(""+s).padStart(e,"0"),i}function nt(s){if(!(se(s)||s===null||s===""))return parseInt(s,10)}function rt(s){if(!(se(s)||s===null||s===""))return parseFloat(s)}function Nn(s){if(!(se(s)||s===null||s==="")){const e=parseFloat("0."+s)*1e3;return Math.floor(e)}}function An(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 Dt(s){return s%4===0&&(s%100!==0||s%400===0)}function ht(s){return Dt(s)?366:365}function an(s,e){const r=ei(e-1,12)+1,i=s+(e-r)/12;return r===2?Dt(i)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function on(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 qr(s,e,r){return-En(On(s,1,e),r)+e-1}function jt(s,e=4,r=1){const i=qr(s,e,r),y=qr(s+1,e,r);return(ht(s)-i+y)/7}function $n(s){return s>99?s:s>pe.twoDigitCutoffYear?1900+s:2e3+s}function Wr(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 ln(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 zr(s){const e=Number(s);if(typeof s=="boolean"||s===""||!Number.isFinite(e))throw new c(`Invalid unit value ${s}`);return e}function cn(s,e){const r={};for(const i in s)if(dt(s,i)){const y=s[i];if(y==null)continue;r[e(i)]=zr(y)}return r}function Ot(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}${xe(r,2)}:${xe(i,2)}`;case"narrow":return`${y}${r}${i>0?`:${i}`:""}`;case"techie":return`${y}${xe(r,2)}${xe(i,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function un(s){return Ja(s,["hour","minute","second","millisecond"])}const ti=["January","February","March","April","May","June","July","August","September","October","November","December"],Hr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],ni=["J","F","M","A","M","J","J","A","S","O","N","D"];function Vr(s){switch(s){case"narrow":return[...ni];case"short":return[...Hr];case"long":return[...ti];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 Ur=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Br=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],ri=["M","T","W","T","F","S","S"];function Yr(s){switch(s){case"narrow":return[...ri];case"short":return[...Br];case"long":return[...Ur];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const Zr=["AM","PM"],si=["Before Christ","Anno Domini"],ai=["BC","AD"],ii=["B","A"];function Gr(s){switch(s){case"narrow":return[...ii];case"short":return[...ai];case"long":return[...si];default:return null}}function oi(s){return Zr[s.hour<12?0:1]}function li(s,e){return Yr(e)[s.weekday-1]}function ci(s,e){return Vr(e)[s.month-1]}function ui(s,e){return Gr(e)[s.year<0?0:1]}function di(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 ie=s==="days";switch(e){case 1:return ie?"tomorrow":`next ${y[s][0]}`;case-1:return ie?"yesterday":`last ${y[s][0]}`;case 0:return ie?"today":`this ${y[s][0]}`}}const j=Object.is(e,-0)||e<0,O=Math.abs(e),F=O===1,H=y[s],ne=i?F?H[1]:H[2]||H[1]:F?y[s][0]:s;return j?`${O} ${ne} ago`:`in ${O} ${ne}`}function Xr(s,e){let r="";for(const i of s)i.literal?r+=i.val:r+=e(i.val);return r}const hi={D:v,DD:b,DDD:k,DDDD:w,t:T,tt:M,ttt:D,tttt:I,T:E,TT:L,TTT:z,TTTT:P,f:Z,ff:q,fff:_,ffff:Q,F:N,FF:U,FFF:Y,FFFF:K};class Ce{static create(e,r={}){return new Ce(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 hi[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 xe(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,be)=>this.loc.extract(e,re,be),j=re=>e.isOffsetFixed&&e.offset===0&&re.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,re.format):"",O=()=>i?oi(e):C({hour:"numeric",hourCycle:"h12"},"dayperiod"),F=(re,be)=>i?ci(e,re):C(be?{month:re}:{month:re,day:"numeric"},"month"),H=(re,be)=>i?li(e,re):C(be?{weekday:re}:{weekday:re,month:"long",day:"numeric"},"weekday"),ne=re=>{const be=Ce.macroTokenToFormatOpts(re);return be?this.formatWithSystemDefault(e,be):re},ie=re=>i?ui(e,re):C({era:re},"era"),fe=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 H("short",!0);case"cccc":return H("long",!0);case"ccccc":return H("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return H("short",!1);case"EEEE":return H("long",!1);case"EEEEE":return H("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 ie("short");case"GG":return ie("long");case"GGGGG":return ie("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 ne(re)}};return Xr(Ce.parseFormat(r),fe)}formatDurationFromString(e,r){const i=this.opts.signMode==="negativeLargestOnly"?-1:1,y=ne=>{switch(ne[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=(ne,ie)=>fe=>{const re=y(fe);if(re){const be=ie.isNegativeDuration&&re!==ie.largestUnit?i:1;let We;return this.opts.signMode==="negativeLargestOnly"&&re!==ie.largestUnit?We="never":this.opts.signMode==="all"?We="always":We="auto",this.num(ne.get(re)*be,fe.length,We)}else return fe},j=Ce.parseFormat(r),O=j.reduce((ne,{literal:ie,val:fe})=>ie?ne:ne.concat(fe),[]),F=e.shiftTo(...O.map(y).filter(ne=>ne)),H={isNegativeDuration:F<0,largestUnit:Object.keys(F.values)[0]};return Xr(j,C(F,H))}}const Kr=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function ft(...s){const e=s.reduce((r,i)=>r+i.source,"");return RegExp(`^${e}$`)}function mt(...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 pt(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 Qr(...s){return(e,r)=>{const i={};let y;for(y=0;y<s.length;y++)i[s[y]]=nt(e[r+y]);return[i,null,r+y]}}const Jr=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,fi=`(?:${Jr.source}?(?:\\[(${Kr.source})\\])?)?`,Rn=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,es=RegExp(`${Rn.source}${fi}`),Ln=RegExp(`(?:[Tt]${es.source})?`),mi=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,pi=/(\d{4})-?W(\d\d)(?:-?(\d))?/,yi=/(\d{4})-?(\d{3})/,gi=Qr("weekYear","weekNumber","weekDay"),xi=Qr("year","ordinal"),bi=/(\d{4})-(\d\d)-(\d\d)/,ts=RegExp(`${Rn.source} ?(?:${Jr.source}|(${Kr.source}))?`),vi=RegExp(`(?: ${ts.source})?`);function yt(s,e,r){const i=s[e];return se(i)?r:nt(i)}function Si(s,e){return[{year:yt(s,e),month:yt(s,e+1,1),day:yt(s,e+2,1)},null,e+3]}function gt(s,e){return[{hours:yt(s,e,0),minutes:yt(s,e+1,0),seconds:yt(s,e+2,0),milliseconds:Nn(s[e+3])},null,e+4]}function Et(s,e){const r=!s[e]&&!s[e+1],i=ln(s[e+1],s[e+2]),y=r?null:ke.instance(i);return[{},y,e+3]}function It(s,e){const r=s[e]?oe.create(s[e]):null;return[{},r,e+1]}const wi=RegExp(`^T?${Rn.source}$`),ki=/^-?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 Ci(s){const[e,r,i,y,C,j,O,F,H]=s,ne=e[0]==="-",ie=F&&F[0]==="-",fe=(re,be=!1)=>re!==void 0&&(be||re&&ne)?-re:re;return[{years:fe(rt(r)),months:fe(rt(i)),weeks:fe(rt(y)),days:fe(rt(C)),hours:fe(rt(j)),minutes:fe(rt(O)),seconds:fe(rt(F),F==="-0"),milliseconds:fe(Nn(H),ie)}]}const Ti={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function _n(s,e,r,i,y,C,j){const O={year:e.length===2?$n(nt(e)):nt(e),month:Hr.indexOf(r)+1,day:nt(i),hour:nt(y),minute:nt(C)};return j&&(O.second=nt(j)),s&&(O.weekday=s.length>3?Ur.indexOf(s)+1:Br.indexOf(s)+1),O}const Mi=/^(?:(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 Di(s){const[,e,r,i,y,C,j,O,F,H,ne,ie]=s,fe=_n(e,y,i,r,C,j,O);let re;return F?re=Ti[F]:H?re=0:re=ln(ne,ie),[fe,new ke(re)]}function ji(s){return s.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Oi=/^(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$/,Ei=/^(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$/,Ii=/^(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 ns(s){const[,e,r,i,y,C,j,O]=s;return[_n(e,y,i,r,C,j,O),ke.utcInstance]}function Fi(s){const[,e,r,i,y,C,j,O]=s;return[_n(e,O,r,i,y,C,j),ke.utcInstance]}const Ni=ft(mi,Ln),Ai=ft(pi,Ln),$i=ft(yi,Ln),Ri=ft(es),rs=mt(Si,gt,Et,It),Li=mt(gi,gt,Et,It),_i=mt(xi,gt,Et,It),Pi=mt(gt,Et,It);function qi(s){return pt(s,[Ni,rs],[Ai,Li],[$i,_i],[Ri,Pi])}function Wi(s){return pt(ji(s),[Mi,Di])}function zi(s){return pt(s,[Oi,ns],[Ei,ns],[Ii,Fi])}function Hi(s){return pt(s,[ki,Ci])}const Vi=mt(gt);function Ui(s){return pt(s,[wi,Vi])}const Bi=ft(bi,vi),Yi=ft(ts),Zi=mt(gt,Et,It);function Gi(s){return pt(s,[Bi,rs],[Yi,Zi])}const ss="Invalid Duration",as={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}},Xi={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},...as},Re=146097/400,xt=146097/4800,Ki={years:{quarters:4,months:12,weeks:Re/7,days:Re,hours:Re*24,minutes:Re*24*60,seconds:Re*24*60*60,milliseconds:Re*24*60*60*1e3},quarters:{months:3,weeks:Re/28,days:Re/4,hours:Re*24/4,minutes:Re*24*60/4,seconds:Re*24*60*60/4,milliseconds:Re*24*60*60*1e3/4},months:{weeks:xt/7,days:xt,hours:xt*24,minutes:xt*24*60,seconds:xt*24*60*60,milliseconds:xt*24*60*60*1e3},...as},st=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Qi=st.slice(0).reverse();function Xe(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 ce(i)}function is(s,e){var r;let i=(r=e.milliseconds)!=null?r:0;for(const y of Qi.slice(1))e[y]&&(i+=e[y]*s[y].milliseconds);return i}function os(s,e){const r=is(s,e)<0?-1:1;st.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),st.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 ls(s){const e={};for(const[r,i]of Object.entries(s))i!==0&&(e[r]=i);return e}class ce{constructor(e){const r=e.conversionAccuracy==="longterm"||!1;let i=r?Ki:Xi;e.matrix&&(i=e.matrix),this.values=e.values,this.loc=e.loc||de.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=i,this.isLuxonDuration=!0}static fromMillis(e,r){return ce.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new c(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new ce({values:cn(e,ce.normalizeUnit),loc:de.fromObject(r),conversionAccuracy:r.conversionAccuracy,matrix:r.matrix})}static fromDurationLike(e){if(tt(e))return ce.fromMillis(e);if(ce.isDuration(e))return e;if(typeof e=="object")return ce.fromObject(e);throw new c(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){const[i]=Hi(e);return i?ce.fromObject(i,r):ce.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){const[i]=Ui(e);return i?ce.fromObject(i,r):ce.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new c("need to specify a reason the Duration is invalid");const i=e instanceof Pe?e:new Pe(e,r);if(pe.throwOnInvalid)throw new a(i);return new ce({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 o(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?Ce.create(this.loc,i).formatDurationFromString(this,e):ss}toHuman(e={}){if(!this.isValid)return ss;const r=e.showZeros!==!1,i=st.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+=An(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?is(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const r=ce.fromDurationLike(e),i={};for(const y of st)(dt(r.values,y)||dt(this.values,y))&&(i[y]=r.get(y)+this.get(y));return Xe(this,{values:i},!0)}minus(e){if(!this.isValid)return this;const r=ce.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]=zr(e(this.values[i],i));return Xe(this,{values:r},!0)}get(e){return this[ce.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const r={...this.values,...cn(e,ce.normalizeUnit)};return Xe(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 Xe(this,j)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return os(this.matrix,e),Xe(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=ls(this.normalize().shiftToAll().toObject());return Xe(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(j=>ce.normalizeUnit(j));const r={},i={},y=this.toObject();let C;for(const j of st)if(e.indexOf(j)>=0){C=j;let O=0;for(const H in i)O+=this.matrix[H][j]*i[H],i[H]=0;tt(y[j])&&(O+=y[j]);const F=Math.trunc(O);r[j]=F,i[j]=(O*1e3-F*1e3)/1e3}else tt(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 os(this.matrix,r),Xe(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 Xe(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=ls(this.values);return Xe(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 st)if(!r(this.values[i],e.values[i]))return!1;return!0}}const bt="Invalid Interval";function Ji(s,e){return!s||!s.isValid?ye.invalid("missing or invalid start"):!e||!e.isValid?ye.invalid("missing or invalid end"):e<s?ye.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 ye{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 c("need to specify a reason the Interval is invalid");const i=e instanceof Pe?e:new Pe(e,r);if(pe.throwOnInvalid)throw new f(i);return new ye({invalid:i})}static fromDateTimes(e,r){const i=$t(e),y=$t(r),C=Ji(i,y);return C??new ye({start:i,end:y})}static after(e,r){const i=ce.fromDurationLike(r),y=$t(e);return ye.fromDateTimes(y,y.plus(i))}static before(e,r){const i=ce.fromDurationLike(r),y=$t(e);return ye.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 ye.fromDateTimes(C,O);if(j){const H=ce.fromISO(y,r);if(H.isValid)return ye.after(C,H)}else if(F){const H=ce.fromISO(i,r);if(H.isValid)return ye.before(O,H)}}return ye.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?ye.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];const r=e.map($t).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(ye.fromDateTimes(y,O)),y=O,C+=1}return i}splitBy(e){const r=ce.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(ye.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:ye.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 ye.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,H)=>F.time-H.time);for(const F of O)i+=F.type==="s"?1:-1,i===1?r=F.time:(r&&+r!=+F.time&&y.push(ye.fromDateTimes(r,F.time)),r=null);return ye.merge(y)}difference(...e){return ye.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:bt}[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=v,r={}){return this.isValid?Ce.create(this.s.loc.clone(r),e).formatInterval(this):bt}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:bt}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:bt}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:bt}toFormat(e,{separator:r=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:bt}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):ce.invalid(this.invalidReason)}mapEndpoints(e){return ye.fromDateTimes(e(this.s),e(this.e))}}class Ft{static hasDST(e=pe.defaultZone){const r=ae.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return oe.isValidZone(e)}static normalizeZone(e){return et(e,pe.defaultZone)}static getStartOfWeek({locale:e=null,locObj:r=null}={}){return(r||de.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:r=null}={}){return(r||de.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:r=null}={}){return(r||de.create(e)).getWeekendDays().slice()}static months(e="long",{locale:r=null,numberingSystem:i=null,locObj:y=null,outputCalendar:C="gregory"}={}){return(y||de.create(r,i,C)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:i=null,locObj:y=null,outputCalendar:C="gregory"}={}){return(y||de.create(r,i,C)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:i=null,locObj:y=null}={}){return(y||de.create(r,i,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:i=null,locObj:y=null}={}){return(y||de.create(r,i,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return de.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return de.create(r,null,"gregory").eras(e)}static features(){return{relative:Lr(),localeWeek:_r()}}}function cs(s,e){const r=y=>y.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),i=r(e)-r(s);return Math.floor(ce.fromMillis(i).as("days"))}function eo(s,e,r){const i=[["years",(F,H)=>H.year-F.year],["quarters",(F,H)=>H.quarter-F.quarter+(H.year-F.year)*4],["months",(F,H)=>H.month-F.month+(H.year-F.year)*12],["weeks",(F,H)=>{const ne=cs(F,H);return(ne-ne%7)/7}],["days",cs]],y={},C=s;let j,O;for(const[F,H]of i)r.indexOf(F)>=0&&(j=F,y[F]=H(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 to(s,e,r,i){let[y,C,j,O]=eo(s,e,r);const F=e-y,H=r.filter(ie=>["hours","minutes","seconds","milliseconds"].indexOf(ie)>=0);H.length===0&&(j<e&&(j=y.plus({[O]:1})),j!==y&&(C[O]=(C[O]||0)+F/(j-y)));const ne=ce.fromObject(C,i);return H.length>0?ce.fromMillis(F,i).shiftTo(...H).plus(ne):ne}const no="missing Intl.DateTimeFormat.formatToParts support";function ue(s,e=r=>r){return{regex:s,deser:([r])=>e(Ba(r))}}const us="[  ]",ds=new RegExp(us,"g");function ro(s){return s.replace(/\./g,"\\.?").replace(ds,us)}function hs(s){return s.replace(/\./g,"").replace(ds," ").toLowerCase()}function qe(s,e){return s===null?null:{regex:RegExp(s.map(ro).join("|")),deser:([r])=>s.findIndex(i=>hs(r)===hs(i))+e}}function fs(s,e){return{regex:s,deser:([,r,i])=>ln(r,i),groups:e}}function dn(s){return{regex:s,deser:([e])=>e}}function so(s){return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function ao(s,e){const r=_e(e),i=_e(e,"{2}"),y=_e(e,"{3}"),C=_e(e,"{4}"),j=_e(e,"{6}"),O=_e(e,"{1,2}"),F=_e(e,"{1,3}"),H=_e(e,"{1,6}"),ne=_e(e,"{1,9}"),ie=_e(e,"{2,4}"),fe=_e(e,"{4,6}"),re=Ue=>({regex:RegExp(so(Ue.val)),deser:([St])=>St,literal:!0}),We=(Ue=>{if(s.literal)return re(Ue);switch(Ue.val){case"G":return qe(e.eras("short"),0);case"GG":return qe(e.eras("long"),0);case"y":return ue(H);case"yy":return ue(ie,$n);case"yyyy":return ue(C);case"yyyyy":return ue(fe);case"yyyyyy":return ue(j);case"M":return ue(O);case"MM":return ue(i);case"MMM":return qe(e.months("short",!0),1);case"MMMM":return qe(e.months("long",!0),1);case"L":return ue(O);case"LL":return ue(i);case"LLL":return qe(e.months("short",!1),1);case"LLLL":return qe(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 dn(ne);case"uu":return dn(O);case"uuu":return ue(r);case"a":return qe(e.meridiems(),0);case"kkkk":return ue(C);case"kk":return ue(ie,$n);case"W":return ue(O);case"WW":return ue(i);case"E":case"c":return ue(r);case"EEE":return qe(e.weekdays("short",!1),1);case"EEEE":return qe(e.weekdays("long",!1),1);case"ccc":return qe(e.weekdays("short",!0),1);case"cccc":return qe(e.weekdays("long",!0),1);case"Z":case"ZZ":return fs(new RegExp(`([+-]${O.source})(?::(${i.source}))?`),2);case"ZZZ":return fs(new RegExp(`([+-]${O.source})(${i.source})?`),2);case"z":return dn(/[a-z_+-/]{1,256}?/i);case" ":return dn(/[^\S\n\r]/);default:return re(Ue)}})(s)||{invalidReason:no};return We.token=s,We}const io={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 oo(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=io[j];if(typeof O=="object"&&(O=O[C]),O)return{literal:!1,val:O}}function lo(s){return[`^${s.map(r=>r.regex).reduce((r,i)=>`${r}(${i.source})`,"")}$`,s]}function co(s,e,r){const i=s.match(e);if(i){const y={};let C=1;for(const j in r)if(dt(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 uo(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=oe.create(s.z)),se(s.Z)||(r||(r=new ke(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=Nn(s.u)),[Object.keys(s).reduce((C,j)=>{const O=e(j);return O&&(C[O]=s[j]),C},{}),r,i]}let Pn=null;function ho(){return Pn||(Pn=ae.fromMillis(1555555555555)),Pn}function fo(s,e){if(s.literal)return s;const r=Ce.macroTokenToFormatOpts(s.val),i=gs(r,e);return i==null||i.includes(void 0)?s:i}function ms(s,e){return Array.prototype.concat(...s.map(r=>fo(r,e)))}class ps{constructor(e,r){if(this.locale=e,this.format=r,this.tokens=ms(Ce.parseFormat(r),e),this.units=this.tokens.map(i=>ao(i,e)),this.disqualifyingUnit=this.units.find(i=>i.invalidReason),!this.disqualifyingUnit){const[i,y]=lo(this.units);this.regex=RegExp(i,"i"),this.handlers=y}}explainFromTokens(e){if(this.isValid){const[r,i]=co(e,this.regex,this.handlers),[y,C,j]=i?uo(i):[null,null,void 0];if(dt(i,"a")&&dt(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 ys(s,e,r){return new ps(s,r).explainFromTokens(e)}function mo(s,e,r){const{result:i,zone:y,specificOffset:C,invalidReason:j}=ys(s,e,r);return[i,y,C,j]}function gs(s,e){if(!s)return null;const i=Ce.create(e,s).dtFormatter(ho()),y=i.formatToParts(),C=i.resolvedOptions();return y.map(j=>oo(j,s,C))}const qn="Invalid DateTime",xs=864e13;function Nt(s){return new Pe("unsupported zone",`the zone "${s.name}" is not supported`)}function Wn(s){return s.weekData===null&&(s.weekData=rn(s.c)),s.weekData}function zn(s){return s.localWeekData===null&&(s.localWeekData=rn(s.c,s.loc.getMinDaysInFirstWeek(),s.loc.getStartOfWeek())),s.localWeekData}function at(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 bs(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 hn(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 fn(s,e,r){return bs(on(s),e,r)}function vs(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,an(i,y))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},j=ce.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=on(C);let[F,H]=bs(O,r,s.zone);return j!==0&&(F+=j,H=s.zone.offset(F)),{ts:F,o:H}}function vt(s,e,r,i,y,C){const{setZone:j,zone:O}=r;if(s&&Object.keys(s).length!==0||e){const F=e||O,H=ae.fromObject(s,{...r,zone:F,specificOffset:C});return j?H:H.setZone(O)}else return ae.invalid(new Pe("unparsable",`the input "${y}" can't be parsed as ${i}`))}function mn(s,e,r=!0){return s.isValid?Ce.create(de.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(s,e):null}function Hn(s,e,r){const i=s.c.year>9999||s.c.year<0;let y="";if(i&&s.c.year>=0&&(y+="+"),y+=xe(s.c.year,i?6:4),r==="year")return y;if(e){if(y+="-",y+=xe(s.c.month),r==="month")return y;y+="-"}else if(y+=xe(s.c.month),r==="month")return y;return y+=xe(s.c.day),y}function Ss(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+=xe(s.c.hour),j==="hour")break;if(e){if(F+=":",F+=xe(s.c.minute),j==="minute")break;O&&(F+=":",F+=xe(s.c.second))}else{if(F+=xe(s.c.minute),j==="minute")break;O&&(F+=xe(s.c.second))}if(j==="second")break;O&&(!i||s.c.millisecond!==0)&&(F+=".",F+=xe(s.c.millisecond,3))}return y&&(s.isOffsetFixed&&s.offset===0&&!C?F+="Z":s.o<0?(F+="-",F+=xe(Math.trunc(-s.o/60)),F+=":",F+=xe(Math.trunc(-s.o%60))):(F+="+",F+=xe(Math.trunc(s.o/60)),F+=":",F+=xe(Math.trunc(s.o%60)))),C&&(F+="["+s.zone.ianaName+"]"),F}const ws={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},po={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},yo={ordinal:1,hour:0,minute:0,second:0,millisecond:0},pn=["year","month","day","hour","minute","second","millisecond"],go=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],xo=["year","ordinal","hour","minute","second","millisecond"];function yn(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 o(s);return e}function ks(s){switch(s.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return yn(s)}}function bo(s){if(At===void 0&&(At=pe.now()),s.type!=="iana")return s.offset(At);const e=s.name;let r=Vn.get(e);return r===void 0&&(r=s.offset(At),Vn.set(e,r)),r}function Cs(s,e){const r=et(e.zone,pe.defaultZone);if(!r.isValid)return ae.invalid(Nt(r));const i=de.fromObject(e);let y,C;if(se(s.year))y=pe.now();else{for(const F of pn)se(s[F])&&(s[F]=ws[F]);const j=$r(s)||Rr(s);if(j)return ae.invalid(j);const O=bo(r);[y,C]=fn(s,O,r)}return new ae({ts:y,zone:r,loc:i,o:C})}function Ts(s,e,r){const i=se(r.round)?!0:r.round,y=se(r.rounding)?"trunc":r.rounding,C=(O,F)=>(O=An(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 Ms(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 At;const Vn=new Map;class ae{constructor(e){const r=e.zone||pe.defaultZone;let i=e.invalid||(Number.isNaN(e.ts)?new Pe("invalid input"):null)||(r.isValid?null:Nt(r));this.ts=se(e.ts)?pe.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=tt(e.o)&&!e.old?e.o:r.offset(this.ts);y=hn(this.ts,O),i=Number.isNaN(y.year)?new Pe("invalid input"):null,y=i?null:y,C=i?null:O}this._zone=r,this.loc=e.loc||de.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]=Ms(arguments),[i,y,C,j,O,F,H]=r;return Cs({year:i,month:y,day:C,hour:j,minute:O,second:F,millisecond:H},e)}static utc(){const[e,r]=Ms(arguments),[i,y,C,j,O,F,H]=r;return e.zone=ke.utcInstance,Cs({year:i,month:y,day:C,hour:j,minute:O,second:F,millisecond:H},e)}static fromJSDate(e,r={}){const i=Ka(e)?e.valueOf():NaN;if(Number.isNaN(i))return ae.invalid("invalid input");const y=et(r.zone,pe.defaultZone);return y.isValid?new ae({ts:i,zone:y,loc:de.fromObject(r)}):ae.invalid(Nt(y))}static fromMillis(e,r={}){if(tt(e))return e<-xs||e>xs?ae.invalid("Timestamp out of range"):new ae({ts:e,zone:et(r.zone,pe.defaultZone),loc:de.fromObject(r)});throw new c(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(tt(e))return new ae({ts:e*1e3,zone:et(r.zone,pe.defaultZone),loc:de.fromObject(r)});throw new c("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};const i=et(r.zone,pe.defaultZone);if(!i.isValid)return ae.invalid(Nt(i));const y=de.fromObject(r),C=cn(e,ks),{minDaysInFirstWeek:j,startOfWeek:O}=Ar(C,y),F=pe.now(),H=se(r.specificOffset)?i.offset(F):r.specificOffset,ne=!se(C.ordinal),ie=!se(C.year),fe=!se(C.month)||!se(C.day),re=ie||fe,be=C.weekYear||C.weekNumber;if((re||ne)&&be)throw new p("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(fe&&ne)throw new p("Can't mix ordinal dates with month/day");const We=be||C.weekday&&!re;let Ue,St,Rt=hn(F,H);We?(Ue=go,St=po,Rt=rn(Rt,j,O)):ne?(Ue=xo,St=yo,Rt=In(Rt)):(Ue=pn,St=ws);let Ds=!1;for(const _t of Ue){const To=C[_t];se(To)?Ds?C[_t]=St[_t]:C[_t]=Rt[_t]:Ds=!0}const So=We?Za(C,j,O):ne?Ga(C):$r(C),js=So||Rr(C);if(js)return ae.invalid(js);const wo=We?Fr(C,j,O):ne?Nr(C):C,[ko,Co]=fn(wo,H,i),Lt=new ae({ts:ko,zone:i,o:Co,loc:y});return C.weekday&&re&&e.weekday!==Lt.weekday?ae.invalid("mismatched weekday",`you can't specify both a weekday of ${C.weekday} and a date of ${Lt.toISO()}`):Lt.isValid?Lt:ae.invalid(Lt.invalid)}static fromISO(e,r={}){const[i,y]=qi(e);return vt(i,y,r,"ISO 8601",e)}static fromRFC2822(e,r={}){const[i,y]=Wi(e);return vt(i,y,r,"RFC 2822",e)}static fromHTTP(e,r={}){const[i,y]=zi(e);return vt(i,y,r,"HTTP",r)}static fromFormat(e,r,i={}){if(se(e)||se(r))throw new c("fromFormat requires an input string and a format");const{locale:y=null,numberingSystem:C=null}=i,j=de.fromOpts({locale:y,numberingSystem:C,defaultToEN:!0}),[O,F,H,ne]=mo(j,e,r);return ne?ae.invalid(ne):vt(O,F,i,`format ${r}`,e,H)}static fromString(e,r,i={}){return ae.fromFormat(e,r,i)}static fromSQL(e,r={}){const[i,y]=Gi(e);return vt(i,y,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new c("need to specify a reason the DateTime is invalid");const i=e instanceof Pe?e:new Pe(e,r);if(pe.throwOnInvalid)throw new l(i);return new ae({invalid:i})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,r={}){const i=gs(e,de.fromObject(r));return i?i.map(y=>y?y.val:null).join(""):null}static expandFormat(e,r={}){return ms(Ce.parseFormat(e),de.fromObject(r)).map(y=>y.val).join("")}static resetCache(){At=void 0,Vn.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?Wn(this).weekYear:NaN}get weekNumber(){return this.isValid?Wn(this).weekNumber:NaN}get weekday(){return this.isValid?Wn(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?zn(this).weekday:NaN}get localWeekNumber(){return this.isValid?zn(this).weekNumber:NaN}get localWeekYear(){return this.isValid?zn(this).weekYear:NaN}get ordinal(){return this.isValid?In(this.c).ordinal:NaN}get monthShort(){return this.isValid?Ft.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Ft.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Ft.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Ft.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=on(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,H=i-O*r,ne=hn(F,j),ie=hn(H,O);return ne.hour===ie.hour&&ne.minute===ie.minute&&ne.second===ie.second&&ne.millisecond===ie.millisecond?[at(this,{ts:F}),at(this,{ts:H})]:[this]}get isInLeapYear(){return Dt(this.year)}get daysInMonth(){return an(this.year,this.month)}get daysInYear(){return this.isValid?ht(this.year):NaN}get weeksInWeekYear(){return this.isValid?jt(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?jt(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:r,numberingSystem:i,calendar:y}=Ce.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:i,outputCalendar:y}}toUTC(e=0,r={}){return this.setZone(ke.instance(e),r)}toLocal(){return this.setZone(pe.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:i=!1}={}){if(e=et(e,pe.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]=fn(j,C,e)}return at(this,{ts:y,zone:e})}else return ae.invalid(Nt(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:i}={}){const y=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:i});return at(this,{loc:y})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const r=cn(e,ks),{minDaysInFirstWeek:i,startOfWeek:y}=Ar(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),H=O||F,ne=r.weekYear||r.weekNumber;if((H||j)&&ne)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 ie;C?ie=Fr({...rn(this.c,i,y),...r},i,y):se(r.ordinal)?(ie={...this.toObject(),...r},se(r.day)&&(ie.day=Math.min(an(ie.year,ie.month),ie.day))):ie=Nr({...In(this.c),...r});const[fe,re]=fn(ie,this.o,this.zone);return at(this,{ts:fe,o:re})}plus(e){if(!this.isValid)return this;const r=ce.fromDurationLike(e);return at(this,vs(this,r))}minus(e){if(!this.isValid)return this;const r=ce.fromDurationLike(e).negate();return at(this,vs(this,r))}startOf(e,{useLocaleWeeks:r=!1}={}){if(!this.isValid)return this;const i={},y=ce.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?Ce.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):qn}toLocaleString(e=v,r={}){return this.isValid?Ce.create(this.loc.clone(r),e).formatDateTime(this):qn}toLocaleParts(e={}){return this.isValid?Ce.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=yn(j);const O=e==="extended";let F=Hn(this,O,j);return pn.indexOf(j)>=3&&(F+="T"),F+=Ss(this,O,r,i,y,C,j),F}toISODate({format:e="extended",precision:r="day"}={}){return this.isValid?Hn(this,e==="extended",yn(r)):null}toISOWeekDate(){return mn(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=yn(O),(y&&pn.indexOf(O)>=3?"T":"")+Ss(this,j==="extended",r,e,i,C,O)):null}toRFC2822(){return mn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return mn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Hn(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")),mn(this,y,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():qn}[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 ce.invalid("created by diffing an invalid DateTime");const y={locale:this.locale,numberingSystem:this.numberingSystem,...i},C=Qa(r).map(ce.normalizeUnit),j=e.valueOf()>this.valueOf(),O=j?this:e,F=j?e:this,H=to(O,F,C,y);return j?H.negate():H}diffNow(e="milliseconds",r={}){return this.diff(ae.now(),e,r)}until(e){return this.isValid?ye.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),Ts(r,this.plus(i),{...e,numeric:"always",units:y,unit:C})}toRelativeCalendar(e={}){return this.isValid?Ts(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 c("min requires all arguments be DateTimes");return Pr(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(ae.isDateTime))throw new c("max requires all arguments be DateTimes");return Pr(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,i={}){const{locale:y=null,numberingSystem:C=null}=i,j=de.fromOpts({locale:y,numberingSystem:C,defaultToEN:!0});return ys(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=de.fromOpts({locale:i,numberingSystem:y,defaultToEN:!0});return new ps(C,e)}static fromFormatParser(e,r,i={}){if(se(e)||se(r))throw new c("fromFormatParser requires an input string and a format parser");const{locale:y=null,numberingSystem:C=null}=i,j=de.fromOpts({locale:y,numberingSystem:C,defaultToEN:!0});if(!j.equals(r.locale))throw new c(`fromFormatParser called with a locale of ${j}, but the format parser was created for ${r.locale}`);const{result:O,zone:F,specificOffset:H,invalidReason:ne}=r.explainFromTokens(e);return ne?ae.invalid(ne):vt(O,F,i,`format ${r.format}`,e,H)}static get DATE_SHORT(){return v}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 z}static get TIME_24_WITH_LONG_OFFSET(){return P}static get DATETIME_SHORT(){return Z}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 R}static get DATETIME_FULL(){return _}static get DATETIME_FULL_WITH_SECONDS(){return Y}static get DATETIME_HUGE(){return Q}static get DATETIME_HUGE_WITH_SECONDS(){return K}}function $t(s){if(ae.isDateTime(s))return s;if(s&&s.valueOf&&tt(s.valueOf()))return ae.fromJSDate(s);if(s&&typeof s=="object")return ae.fromObject(s);throw new c(`Unknown datetime argument: ${s}, of type ${typeof s}`)}const vo="3.7.2";return je.DateTime=ae,je.Duration=ce,je.FixedOffsetZone=ke,je.IANAZone=oe,je.Info=Ft,je.Interval=ye,je.InvalidZone=xr,je.Settings=pe,je.SystemZone=te,je.VERSION=vo,je.Zone=ee,je}var Us;function mr(){return Us||(Us=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CronDate=t.DAYS_IN_MONTH=t.DateMathOp=t.TimeUnit=void 0;const l=Zl();var f;(function(o){o.Second="Second",o.Minute="Minute",o.Hour="Hour",o.Day="Day",o.Month="Month",o.Year="Year"})(f||(t.TimeUnit=f={}));var a;(function(o){o.Add="Add",o.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(c,m){const u={zone:m};if(c?c instanceof p?(this.#e=c.#e,this.#n=c.#n,this.#a=c.#a):c instanceof Date?this.#e=l.DateTime.fromJSDate(c,u):typeof c=="number"?this.#e=l.DateTime.fromMillis(c,u):(this.#e=l.DateTime.fromISO(c,u),this.#e.isValid||(this.#e=l.DateTime.fromRFC2822(c,u)),this.#e.isValid||(this.#e=l.DateTime.fromSQL(c,u)),this.#e.isValid||(this.#e=l.DateTime.fromFormat(c,"EEE, d MMM yyyy HH:mm:ss",u))):this.#e=l.DateTime.local(),!this.#e.isValid)throw new Error(`CronDate: unhandled timestamp: ${c}`);m&&m!==this.#e.zoneName&&(this.#e=this.#e.setZone(m))}static#s(c){return c%4===0&&c%100!==0||c%400===0}get dstStart(){return this.#n}set dstStart(c){this.#n=c}get dstEnd(){return this.#a}set dstEnd(c){this.#a=c}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(c){switch(c){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(c){switch(c){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(c,m){if(c===a.Add){this.addUnit(m);return}if(c===a.Subtract){this.subtractUnit(m);return}throw new Error(`Invalid verb: ${c}`)}getDate(){return this.#e.day}getFullYear(){return this.#e.year}getDay(){const c=this.#e.weekday;return c===7?0:c}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 c=this.#r().weekday;return c===7?0:c}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(c){this.#e=this.#e.set({day:c})}setFullYear(c){this.#e=this.#e.set({year:c})}setDay(c){this.#e=this.#e.set({weekday:c})}setMonth(c){this.#e=this.#e.set({month:c+1})}setHours(c){this.#e=this.#e.set({hour:c})}setMinutes(c){this.#e=this.#e.set({minute:c})}setSeconds(c){this.#e=this.#e.set({second:c})}setMilliseconds(c){this.#e=this.#e.set({millisecond:c})}toString(){return this.toDate().toString()}toDate(){return this.#e.toJSDate()}isLastDayOfMonth(){const{day:c,month:m}=this.#e;if(m===2){const u=p.#s(this.#e.year);return c===t.DAYS_IN_MONTH[m-1]-(u?0:1)}return c===t.DAYS_IN_MONTH[m-1]}isLastWeekdayOfMonth(){const{day:c,month:m}=this.#e;let u;return m===2?u=t.DAYS_IN_MONTH[m-1]-(p.#s(this.#e.year)?0:1):u=t.DAYS_IN_MONTH[m-1],c>u-7}applyDateOperation(c,m,u){if(m===f.Month||m===f.Day){this.invokeDateOperation(c,m);return}const h=this.getHours();this.invokeDateOperation(c,m);const x=this.getHours(),v=x-h;v===2?u!==24&&(this.dstStart=h+1):v===0&&this.getMinutes()===0&&this.getSeconds()===0&&u!==24&&(this.dstEnd=x)}#r(){return this.#e.toUTC()}}t.CronDate=p,t.default=p})(Gn)),Gn}var Bs;function Gl(){if(Bs)return Bt;Bs=1,Object.defineProperty(Bt,"__esModule",{value:!0}),Bt.CronMonth=void 0;const t=mr(),l=ut(),f=1,a=12,p=Object.freeze([]);let o=class extends l.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(m,u){super(m,u),this.validate()}get values(){return super.values}};return Bt.CronMonth=o,Bt}var Yt={},Ys;function Xl(){if(Ys)return Yt;Ys=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.CronSecond=void 0;const t=ut(),l=0,f=59,a=Object.freeze([]);let p=class extends t.CronField{static get min(){return l}static get max(){return f}static get chars(){return a}constructor(c,m){super(c,m),this.validate()}get values(){return super.values}};return Yt.CronSecond=p,Yt}var Zs;function pr(){return Zs||(Zs=1,(function(t){var l=ot&&ot.__createBinding||(Object.create?(function(a,p,o,c){c===void 0&&(c=o);var m=Object.getOwnPropertyDescriptor(p,o);(!m||("get"in m?!p.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return p[o]}}),Object.defineProperty(a,c,m)}):(function(a,p,o,c){c===void 0&&(c=o),a[c]=p[o]})),f=ot&&ot.__exportStar||function(a,p){for(var o in a)o!=="default"&&!Object.prototype.hasOwnProperty.call(p,o)&&l(p,a,o)};Object.defineProperty(t,"__esModule",{value:!0}),f(Hl(),t),f(Vl(),t),f(Ul(),t),f(ut(),t),f(Bl(),t),f(Yl(),t),f(Gl(),t),f(Xl(),t)})(ot)),ot}var Gs;function ba(){if(Gs)return qt;Gs=1,Object.defineProperty(qt,"__esModule",{value:!0}),qt.CronFieldCollection=void 0;const t=pr();let l=class Kt{#e;#n;#a;#s;#r;#t;static from(a,p){return new Kt({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,o){return o?o instanceof t.CronField?o:new a(o):p}constructor({second:a,minute:p,hour:o,dayOfMonth:c,month:m,dayOfWeek:u}){if(!a)throw new Error("Validation error, Field second is missing");if(!p)throw new Error("Validation error, Field minute is missing");if(!o)throw new Error("Validation error, Field hour is missing");if(!c)throw new Error("Validation error, Field dayOfMonth is missing");if(!m)throw new Error("Validation error, Field month is missing");if(!u)throw new Error("Validation error, Field dayOfWeek is missing");if(m.values.length===1&&!c.hasLastChar&&u.isWildcard&&!(parseInt(c.values[0],10)<=t.CronMonth.daysInMonth[m.values[0]-1]))throw new Error("Invalid explicit day of month definition");this.#e=a,this.#n=p,this.#a=o,this.#r=m,this.#t=u,this.#s=c}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 o;return a.forEach((c,m,u)=>{if(o===void 0){o={start:c,count:1};return}const h=u[m-1]||o.start,x=u[m+1];if(c==="L"||c==="W"){p.push(o),p.push({start:c,count:1}),o=void 0;return}if(o.step===void 0&&x!==void 0){const v=c-h,b=x-c;if(v<=b){o={...o,count:2,end:c,step:v};return}o.step=1}c-(o.end??0)===o.step?(o.count++,o.end=c):(o.count===1?p.push({start:o.start,count:1}):o.count===2?(p.push({start:o.start,count:1}),p.push({start:o.end??h,count:1})):p.push(o),o={start:c,count:1})}),o&&p.push(o),p}static#c(a,p,o){const c=p.step;return c?c===1&&p.start===a.min&&p.end&&p.end>=o?a.hasQuestionMarkChar?"?":"*":c!==1&&p.start===a.min&&p.end&&p.end>=o-c+1?`*/${c}`:null:null}static#l(a,p){const o=a.step;if(o===1)return`${a.start}-${a.end}`;const c=a.start===0?a.count-1:a.count;if(!o)throw new Error("Unexpected range step");if(!a.end)throw new Error("Unexpected range end");if(o*c>a.end){const m=(h,x)=>{if(typeof a.start!="number")throw new Error("Unexpected range start");return x%o===0?a.start+x:null};if(typeof a.start!="number")throw new Error("Unexpected range start");const u={length:a.end-a.start+1};return Array.from(u,m).filter(h=>h!==null).join(",")}return a.end===p-o+1?`${a.start}/${o}`:`${a.start}-${a.end}/${o}`}stringifyField(a){let p=a.max,o=a.values;if(a instanceof t.CronDayOfWeek){p=6;const m=this.#t.values;o=m[m.length-1]===7?m.slice(0,-1):m}a instanceof t.CronDayOfMonth&&(p=this.#r.values.length===1?t.CronMonth.daysInMonth[this.#r.values[0]-1]:a.max);const c=Kt.compactField(o);if(c.length===1){const m=Kt.#c(a,c[0],p);if(m)return m}return c.map(m=>{const u=m.count===1?m.start.toString():Kt.#l(m,p);return a instanceof t.CronDayOfWeek&&a.nthDay>0?`${u}#${a.nthDay}`:u}).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 qt.CronFieldCollection=l,qt}var Xn={},Xs;function va(){return Xs||(Xs=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 l=mr();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(o,c){this.#e=c,this.#n=c.tz,this.#s=c.startDate?new l.CronDate(c.startDate,this.#n):null,this.#r=c.endDate?new l.CronDate(c.endDate,this.#n):null;let m=c.currentDate??c.startDate;if(m){const u=new l.CronDate(m,this.#n);this.#s&&u.getTime()<this.#s.getTime()?m=this.#s:this.#r&&u.getTime()>this.#r.getTime()&&(m=this.#r)}this.#a=new l.CronDate(m,this.#n),this.#t=o}get fields(){return this.#t}static fieldsToExpression(o,c){return new a(o,c||{})}static#i(o,c){return c.some(m=>m===o)}#o(o,c){return o[c?o.length-1:0]}#d(o){const c=`${o.getFullYear()}-${o.getMonth()+1}-${o.getDate()}`;if(this.#c===c)return this.#l;const m=new l.CronDate(o);m.setStartOfDay();const u=new l.CronDate(o);return u.setEndOfDay(),this.#c=c,this.#l=m.getUTCOffset()!==u.getUTCOffset(),this.#l}#h(o,c,m){const u=this.#t.second.values,h=o.getSeconds(),x=this.#t.second.findNearestValue(h,m);if(x!==null){o.setSeconds(x);return}o.applyDateOperation(c,l.TimeUnit.Minute,this.#t.hour.values.length),o.setSeconds(this.#o(u,m))}#m(o,c,m){const u=this.#t.minute.values,h=this.#t.second.values,x=o.getMinutes(),v=this.#t.minute.findNearestValue(x,m);if(v!==null){o.setMinutes(v),o.setSeconds(this.#o(h,m));return}o.applyDateOperation(c,l.TimeUnit.Hour,this.#t.hour.values.length),o.setMinutes(this.#o(u,m)),o.setSeconds(this.#o(h,m))}static#p(o,c){const m=c.isLastWeekdayOfMonth();return o.some(u=>{const h=parseInt(u.toString().charAt(0),10)%7;if(Number.isNaN(h))throw new Error(`Invalid last weekday of the month expression: ${u}`);return c.getDay()===h&&m})}next(){return this.#u()}prev(){return this.#u(!0)}hasNext(){const o=this.#a;try{return this.#u(),!0}catch{return!1}finally{this.#a=o}}hasPrev(){const o=this.#a;try{return this.#u(!0),!0}catch{return!1}finally{this.#a=o}}take(o){const c=[];if(o>=0)for(let m=0;m<o;m++)try{c.push(this.next())}catch{return c}else for(let m=0;m>o;m--)try{c.push(this.prev())}catch{return c}return c}reset(o){this.#a=new l.CronDate(o||this.#e.currentDate,this.#n)}stringify(o=!1){return this.#t.stringify(o)}includesDate(o){const{second:c,minute:m,hour:u,month:h}=this.#t,x=new l.CronDate(o,this.#n);return!(!c.values.includes(x.getSeconds())||!m.values.includes(x.getMinutes())||!u.values.includes(x.getHours())||!h.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(o){const c=this.#t.dayOfMonth.isWildcard,m=!c,u=this.#t.dayOfWeek.isWildcard,h=!u,x=a.#i(o.getDate(),this.#t.dayOfMonth.values)||this.#t.dayOfMonth.hasLastChar&&o.isLastDayOfMonth(),v=a.#i(o.getDay(),this.#t.dayOfWeek.values)||this.#t.dayOfWeek.hasLastChar&&a.#p(this.#t.dayOfWeek.values,o);return!!(m&&h&&(x||v)||x&&!h||c&&!u&&v)}#y(o,c,m){const u=this.#t.hour.values,h=u,x=o.getHours(),v=a.#i(x,u),b=o.dstEnd===x;if(o.dstStart!==null&&o.dstStart===x-1&&a.#i(o.dstStart,u))return!0;if(b&&!m)return o.dstEnd=null,o.applyDateOperation(l.DateMathOp.Add,l.TimeUnit.Hour,h.length),!1;if(v)return!0;o.dstStart=null;const g=this.#t.hour.findNearestValue(x,m);if(g===null)return o.applyDateOperation(c,l.TimeUnit.Day,h.length),!1;if(this.#d(o)){const k=m?x-g:g-x;for(let w=0;w<k&&(o.applyDateOperation(c,l.TimeUnit.Hour,h.length),!(!m&&o.getHours()>=g||m&&o.getHours()<=g));w++);}else o.setHours(g);return o.setMinutes(this.#o(this.#t.minute.values,m)),o.setSeconds(this.#o(this.#t.second.values,m)),!1}#g(o){if(!this.#s&&!this.#r)return;const c=o.getTime();if(this.#s&&c<this.#s.getTime())throw new Error(t.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE);if(this.#r&&c>this.#r.getTime())throw new Error(t.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE)}#u(o=!1){const c=o?l.DateMathOp.Subtract:l.DateMathOp.Add,m=new l.CronDate(this.#a),u=m.getTime();let h=0;for(;++h<f;){if(this.#g(m),!this.#f(m)){m.applyDateOperation(c,l.TimeUnit.Day,this.#t.hour.values.length);continue}if(!(this.#t.dayOfWeek.nthDay<=0||Math.ceil(m.getDate()/7)===this.#t.dayOfWeek.nthDay)){m.applyDateOperation(c,l.TimeUnit.Day,this.#t.hour.values.length);continue}if(!a.#i(m.getMonth()+1,this.#t.month.values)){m.applyDateOperation(c,l.TimeUnit.Month,this.#t.hour.values.length);continue}if(this.#y(m,c,o)){if(!a.#i(m.getMinutes(),this.#t.minute.values)){this.#m(m,c,o);continue}if(!a.#i(m.getSeconds(),this.#t.second.values)){this.#h(m,c,o);continue}if(u===m.getTime()){(c==="Add"||m.getMilliseconds()===0)&&m.applyDateOperation(c,l.TimeUnit.Second,this.#t.hour.values.length);continue}break}}if(h>f)throw new Error(t.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE);return m.getMilliseconds()!==0&&m.setMilliseconds(0),this.#a=m,m}[Symbol.iterator](){return{next:()=>{try{return{value:this.#u(),done:!1}}catch{return{value:void 0,done:!0}}}}}}t.CronExpression=a,t.default=a})(Xn)),Xn}var gn={},Ks;function Kl(){if(Ks)return gn;Ks=1,Object.defineProperty(gn,"__esModule",{value:!0}),gn.seededRandom=f;function t(a){let p=2166136261;for(let o=0;o<a.length;o++)p^=a.charCodeAt(o),p=Math.imul(p,16777619);return()=>p>>>0}function l(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 l(p)}return gn}var Qs;function sr(){if(Qs)return Ee;Qs=1,Object.defineProperty(Ee,"__esModule",{value:!0}),Ee.CronExpressionParser=Ee.DayOfWeek=Ee.Months=Ee.CronUnit=Ee.PredefinedExpressions=void 0;const t=ba(),l=va(),f=Kl(),a=pr();var p;(function(h){h["@yearly"]="0 0 0 1 1 *",h["@annually"]="0 0 0 1 1 *",h["@monthly"]="0 0 0 1 * *",h["@weekly"]="0 0 0 * * 0",h["@daily"]="0 0 0 * * *",h["@hourly"]="0 0 * * * *",h["@minutely"]="0 * * * * *",h["@secondly"]="* * * * * *",h["@weekdays"]="0 0 0 * * 1-5",h["@weekends"]="0 0 0 * * 0,6"})(p||(Ee.PredefinedExpressions=p={}));var o;(function(h){h.Second="Second",h.Minute="Minute",h.Hour="Hour",h.DayOfMonth="DayOfMonth",h.Month="Month",h.DayOfWeek="DayOfWeek"})(o||(Ee.CronUnit=o={}));var c;(function(h){h[h.jan=1]="jan",h[h.feb=2]="feb",h[h.mar=3]="mar",h[h.apr=4]="apr",h[h.may=5]="may",h[h.jun=6]="jun",h[h.jul=7]="jul",h[h.aug=8]="aug",h[h.sep=9]="sep",h[h.oct=10]="oct",h[h.nov=11]="nov",h[h.dec=12]="dec"})(c||(Ee.Months=c={}));var m;(function(h){h[h.sun=0]="sun",h[h.mon=1]="mon",h[h.tue=2]="tue",h[h.wed=3]="wed",h[h.thu=4]="thu",h[h.fri=5]="fri",h[h.sat=6]="sat"})(m||(Ee.DayOfWeek=m={}));let u=class Ie{static parse(x,v={}){const{strict:b=!1,hashSeed:g}=v,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(o.Second,w.second,a.CronSecond.constraints,k),M=Ie.#n(o.Minute,w.minute,a.CronMinute.constraints,k),D=Ie.#n(o.Hour,w.hour,a.CronHour.constraints,k),I=Ie.#n(o.Month,w.month,a.CronMonth.constraints,k),E=Ie.#n(o.DayOfMonth,w.dayOfMonth,a.CronDayOfMonth.constraints,k),{dayOfWeek:L,nthDayOfWeek:z}=Ie.#d(w.dayOfWeek),P=Ie.#n(o.DayOfWeek,L,a.CronDayOfWeek.constraints,k),Z=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(P,{rawValue:w.dayOfWeek,nthDayOfWeek:z})});return new l.CronExpression(Z,{...v,expression:x})}static#e(x,v){if(v&&!x.length)throw new Error("Invalid cron expression");x=x||"0 * * * * *";const b=x.trim().split(/\s+/);if(v&&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,v,b,g){if((x===o.Month||x===o.DayOfWeek)&&(v=v.replace(/[a-z]{3}/gi,k=>{k=k.toLowerCase();const w=c[k]||m[k];if(w===void 0)throw new Error(`Validation error, cannot resolve alias "${k}"`);return w.toString()})),!b.validChars.test(v))throw new Error(`Invalid characters, got value: ${v}`);return v=this.#a(v,b),v=this.#s(v,b,g),this.#r(x,v,b)}static#a(x,v){return x.replace(/[*?]/g,v.min+"-"+v.max)}static#s(x,v,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,v.min),z=Math.floor(g*E),P=[];for(let Z=Math.floor(L/E)*E+z;Z<=I;Z+=E)Z>=L&&P.push(Z);return P.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(v.min/D)*D+I;L<=v.max;L+=D)L>=v.min&&E.push(L);return E.join(",")}else return String(Math.floor(g*(v.max-v.min+1)+v.min))})}static#r(x,v,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===o.DayOfWeek?D%7:T)}}return v.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,v,b){const g=v.split("/");if(g.length>2)throw new Error(`Invalid repeat: ${v}`);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,v,1,b)}static#c(x,v,b){if(!(!isNaN(x)&&!isNaN(v)&&x>=b.min&&v<=b.max))throw new Error(`Constraint error, got range ${x}-${v} expected range ${b.min}-${b.max}`);if(x>v)throw new Error(`Invalid range: ${x}-${v}, min(${x}) > max(${v})`)}static#l(x){if(!(!isNaN(x)&&x>0))throw new Error(`Constraint error, cannot repeat at every ${x} time.`)}static#i(x,v,b,g){const k=[];x===o.DayOfWeek&&b%7===0&&k.push(0);for(let w=v;w<=b;w+=g)k.indexOf(w)===-1&&k.push(w);return k}static#o(x,v,b,g){const k=v.split("-");if(k.length<=1)return isNaN(+v)?v:+v;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 v=x.split("#");if(v.length<=1)return{dayOfWeek:v[0]};const b=+v[v.length-1],g=x.match(/([,-/])/);if(g!==null)throw new Error(`Constraint error, invalid dayOfWeek \`#\` and \`${g?.[0]}\` special characters are incompatible`);if(!(v.length<=2&&!isNaN(b)&&b>=1&&b<=5))throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)");return{dayOfWeek:v[0],nthDayOfWeek:b}}static#h(x,v){return x.chars.some(b=>v.toString().includes(b))}};return Ee.CronExpressionParser=u,Ee}var ze={};const Ql={},Jl=Object.freeze(Object.defineProperty({__proto__:null,default:Ql},Symbol.toStringTag,{value:"Module"})),Js=d.getAugmentedNamespace(Jl);var ea;function ec(){if(ea)return ze;ea=1;var t=ze&&ze.__createBinding||(Object.create?(function(o,c,m,u){u===void 0&&(u=m);var h=Object.getOwnPropertyDescriptor(c,m);(!h||("get"in h?!c.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return c[m]}}),Object.defineProperty(o,u,h)}):(function(o,c,m,u){u===void 0&&(u=m),o[u]=c[m]})),l=ze&&ze.__setModuleDefault||(Object.create?(function(o,c){Object.defineProperty(o,"default",{enumerable:!0,value:c})}):function(o,c){o.default=c}),f=ze&&ze.__importStar||(function(){var o=function(c){return o=Object.getOwnPropertyNames||function(m){var u=[];for(var h in m)Object.prototype.hasOwnProperty.call(m,h)&&(u[u.length]=h);return u},o(c)};return function(c){if(c&&c.__esModule)return c;var m={};if(c!=null)for(var u=o(c),h=0;h<u.length;h++)u[h]!=="default"&&t(m,c,u[h]);return l(m,c),m}})();Object.defineProperty(ze,"__esModule",{value:!0}),ze.CronFileParser=void 0;const a=sr();let p=class bn{static async parseFile(c){const{readFile:m}=await Promise.resolve().then(()=>f(Js)),u=await m(c,"utf8");return bn.#e(u)}static parseFileSync(c){const{readFileSync:m}=Js,u=m(c,"utf8");return bn.#e(u)}static#e(c){const m=c.split(`