@malloy-publisher/sdk 0.18.0 → 0.18.2
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/{RenderedResult-QdYnecnr.es.js → RenderedResult--fYcsY1h.es.js} +2 -2
- package/dist/{ServerProvider-DAVb5QK1.es.js → ServerProvider-nC__R_WW.es.js} +8 -8
- package/dist/builder/index.es.js +3 -3
- package/dist/client/api.d.ts +9 -9
- package/dist/client/index.es.js +1 -1
- package/dist/index.cjs.js +28 -28
- package/dist/index.d.ts +1 -1
- package/dist/index.es.js +2687 -2651
- package/dist/{useCompiledDocument-BbdwlcRj.es.js → useCompiledDocument-X00FD-D6.es.js} +2 -2
- package/dist/utils/dataAppEmbed.d.ts +29 -0
- package/package.json +1 -1
- package/src/components/DataAppViewer/DataAppViewer.spec.tsx +202 -0
- package/src/components/DataAppViewer/DataAppViewer.tsx +68 -5
- package/src/index.ts +7 -1
- package/src/utils/dataAppEmbed.spec.ts +44 -0
- package/src/utils/dataAppEmbed.ts +60 -0
package/dist/index.cjs.js
CHANGED
|
@@ -1,41 +1,41 @@
|
|
|
1
|
-
"use strict";var Uu=Object.create;var wi=Object.defineProperty;var Gu=Object.getOwnPropertyDescriptor;var Yu=Object.getOwnPropertyNames;var Ku=Object.getPrototypeOf,Qu=Object.prototype.hasOwnProperty;var Zu=(e,n,r,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of Yu(n))!Qu.call(e,i)&&i!==r&&wi(e,i,{get:()=>n[i],enumerable:!(o=Gu(n,i))||o.enumerable});return e};var Si=(e,n,r)=>(r=e!=null?Uu(Ku(e)):{},Zu(n||!e||!e.__esModule?wi(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),p=require("@mui/material"),j=require("react"),c=require("./useCompiledDocument-5KuF7E_O.cjs.js"),q=require("./ServerProvider-BPCJnHae.cjs.js"),mt=require("@tanstack/react-query"),wr=require("@mui/system"),Pt=require("@mui/icons-material"),Xu=require("@malloydata/malloy-tag"),so=require("./text-entry-BJwltZiy.cjs.js"),fn=require("./RenderedResult-DAPv24rW.cjs.js"),Ju=require("@malloydata/malloy-filter"),Gr=require("react-router-dom");function ed(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:()=>e[r]})}}return n.default=e,Object.freeze(n)}const je=ed(j),td=c.createSvgIcon(t.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function nd({label:e,href:n,onClick:r}){const o=i=>{const l=i.metaKey||i.ctrlKey||i.shiftKey||i.altKey||i.button!==0;n!==void 0&&l||(i.preventDefault(),r(i))};return t.jsxs(p.Link,{...n===void 0?{component:"button",type:"button"}:{href:n},onClick:o,underline:"none","aria-label":`Back to ${e}`,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:[t.jsx(td,{sx:{fontSize:18}}),"Back to ",e]})}const $a="(max-width:599.95px)";function Fa(){return p.useMediaQuery($a,{noSsr:!0})}function Aa(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia($a).matches}function rd({children:e}){const[n]=j.useState(Aa),[r,o]=j.useState(!1);return!n||r?t.jsx(t.Fragment,{children:e}):t.jsxs(p.Stack,{sx:{alignItems:"flex-start",gap:1.5,py:3},children:[t.jsx(p.Typography,{variant:"h6",children:"Editing works best on a larger screen"}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"The editor is built for a wider window. You can still try it here."}),t.jsx(p.Button,{variant:"outlined",onClick:()=>o(!0),children:"Edit anyway"})]})}function sd(){const e=Gr.useNavigate();return(n,r)=>{if(!r||!r.metaKey&&!r.ctrlKey&&!r.shiftKey&&r.button!==1){e(n);return}const o=new URL(n,window.location.href).href;(r.metaKey||r.ctrlKey||r.button===1||r.shiftKey)&&window.open(o,"_blank")}}function Ra(e,n){return e.flatMap(({filter:r})=>{if(r.kind!=="literal_equality"||r.expression.kind!=="field_reference")return[];const o=od(r.value,n);return o===void 0?[]:[{field:r.expression.name,label:o,expression:r.expression}]})}function La(e,n){switch(e.kind){case"string_literal":return`'${c.escapeMalloyString(e.string_value)}'`;case"number_literal":return e.string_value!==void 0?/^-?\d+(\.\d+)?$/.test(e.string_value)?e.string_value:void 0:Number.isFinite(e.number_value)?String(e.number_value):void 0;case"boolean_literal":return String(e.boolean_value);case"date_literal":{const r=_a(e.date_value);return r&&`@${r[0]}-${r[1]}-${r[2]}`}case"timestamp_literal":{const r=Pa(e.timestamp_value,n);return r&&`@${r[0]}-${r[1]}-${r[2]} ${r[3]}:${r[4]}:${r[5]}${Na(e.timestamp_value)}`}default:return}}function od(e,n){switch(e.kind){case"string_literal":return e.string_value;case"null_literal":return"null";case"date_literal":{const r=_a(e.date_value);return r&&ki([...r,"00","00","00"],e.granularity??"day")}case"timestamp_literal":{const r=Pa(e.timestamp_value,n);return r&&ki(r,e.granularity??"second")+(e.granularity===void 0?Na(e.timestamp_value):"")}default:return La(e)}}function _a(e){const n=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);return n?[n[1],n[2],n[3]]:void 0}function Na(e){const n=/:\d{2}\.(\d+)/.exec(e)?.[1]?.replace(/0+$/,"");return n?`.${n}`:""}function Pa(e,n){const r=new Date(e);if(Number.isNaN(r.getTime()))return;let o;try{o=new Intl.DateTimeFormat("en-US",{timeZone:n??"UTC",hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(r)}catch{return}const i=l=>o.find(a=>a.type===l)?.value??"";return[i("year").padStart(4,"0"),i("month"),i("day"),i("hour"),i("minute"),i("second")]}function ki([e,n,r,o,i,l],a){switch(a){case"year":return e;case"quarter":return`${e}-Q${Math.floor((Number(n)-1)/3)+1}`;case"month":return`${e}-${n}`;case"week":case"day":return`${e}-${n}-${r}`;case"hour":return`${e}-${n}-${r} ${o}`;case"minute":return`${e}-${n}-${r} ${o}:${i}`;default:return`${e}-${n}-${r} ${o}:${i}:${l}`}}const id="drill_metadata_corrected",Zr=e=>e,Rn=e=>{try{return e?.()}catch{return}},za=e=>Rn(e.isBasic?.bind(e))===!0&&Rn(e.wasDimension?.bind(e))===!0,ad=e=>[e.isString,e.isNumber,e.isBoolean,e.isTime].some(n=>Rn(n?.bind(e))===!0);function Xr(e){const n=e.metadataTag?.text("drill_expression","code");return n===void 0||n.trim()===""?void 0:n}function Wa(e){const n=[];for(let r=e.parent;r;r=r.parent)n.push(r);return n}function qa(e){const n=Wa(e),o=(n[n.length-1]??e).metadataTag,i=o?.text("source","name");if(!i||!o?.array||o.array("source","parameters")!==void 0||o.has?.(id)!==!0)return;const l=[];for(const u of[...n].reverse())if(Rn(u.isArray?.bind(u))===!0){if(u.metadataTag?.has?.("drillable")!==!0)return;for(const d of u.metadataTag?.array?.("drill_filters")??[]){const h=d.text("code");if(!h)return;l.push(h)}}const a=o?.text("query_name");return{source:i,filters:l,...a&&!a.startsWith("__")?{queryName:a}:{}}}function Er(e){const n=new Set;for(const r of Wa(e))for(const o of r.fields??[])za(o)&&n.add(o);return[...n]}function Ba(e){const n=new Set(Er(e).filter(r=>Rn(r.isTime?.bind(r))===!0).map(r=>Rn(r.getEffectiveQueryTimezone?.bind(r))));return n.size>1?null:[...n][0]}function Ci(e){return!za(e)||Xr(e)===void 0||qa(e)===void 0||Ba(e)===null?!1:Er(e).every(n=>Xr(n)!==void 0&&n.drillStableExpression!==void 0&&ad(n))}function ld(e,n){const r=Er(e),o=[],i=new Set;for(const l of n){if(l.kind==="drill")continue;const{filter:a}=l;if(a.kind!=="literal_equality")return;const u=JSON.stringify(a.expression),d=r.find(y=>JSON.stringify(y.drillStableExpression)===u),h=d&&Xr(d);if(d===void 0||h===void 0)return;o.push({code:h,value:a.value}),i.add(d)}return r.every(l=>i.has(l))&&o.length>0?o:void 0}const cd=360;function Hs(e){return e?e.getLabel?.()??e.tag?.text("label")??Zr(e).metadataTag?.text("label")??e.name:""}function ud(e,n){const r=e.drillClauses?Ra(e.drillClauses,e.timezone):[];if(r.length===0)return`${Hs(n)}: ${e.label}`;const o=Er(Zr(n));return r.map(i=>{const l=JSON.stringify(i.expression),a=o.find(u=>JSON.stringify(u.drillStableExpression)===l);return`${a?Hs(a):i.field}: ${i.label}`}).join(", ")}function oo({onNavigate:e,onSelf:n,destinationTitle:r,canSelf:o,onRows:i}){const[l,a]=j.useState(null),u=j.useCallback((S,T)=>S.filter(O=>O===c.DRILL_SELF?n!==void 0&&(o?.(T)??!0):e!==void 0),[e,n,o]),d=j.useCallback((S,T,O)=>{if(T===c.DRILL_SELF){n?.(S.given,S.rawValue);return}e?.({path:T,dashboard:T,givens:{[S.given]:S.value}},O)},[e,n]),h=j.useCallback(S=>{if(!i||S.noRows||S.isHeader||!S.field)return;const T=Zr(S.field);if(!Ci(T))return;const O=qa(T);if(O===void 0)return;const M=S.drillClauses;let E;if(M!==void 0){const P=ld(T,M);if(P===void 0)return;E={dimensions:P}}else{const P=Xr(T);if(P===void 0||Er(T).length!==1||c.drillValueToFilter(S.value)===void 0||typeof S.value=="number"&&Number.isInteger(S.value)&&!Number.isSafeInteger(S.value))return;E={code:P}}const R=Ba(T)??void 0;return{field:S.field.name,rawValue:S.value,label:c.drillValueLabel(S.value),target:O,...E,...S.context===void 0?{}:{context:S.context},...M===void 0?{}:{drillClauses:M},...R===void 0?{}:{timezone:R}}},[i]),y=j.useCallback(S=>{const T=c.resolveDrill(S),O=h(S),M=T?Array.from(new Set(u(T.to,T.given))).sort((P,F)=>+(F===c.DRILL_SELF)-+(P===c.DRILL_SELF)):[],E=`${Hs(S.field)}: ${T?.label??c.drillValueLabel(S.value)}`,R=M.map(P=>({key:`to:${P}`,label:P===c.DRILL_SELF?`Filter to ${E}`:`Open ${r?.(P)??c.humanizeSlug(P.split("/").pop()??P)} (${E})`,run:()=>{T&&d(T,P,S.event)}}));O&&S.field&&R.push({key:"rows",label:`Show rows (${ud(O,S.field)})`,run:()=>i?.(O)}),R.length!==0&&a({items:R,top:S.event?.clientY??0,left:S.event?.clientX??0})},[d,u,i,h,r]),b=j.useCallback(S=>u(c.drillDestinations(S),c.drillGivenName(S)).length>0,[u]),x=j.useCallback(S=>i!==void 0&&Ci(Zr(S)),[i]),v=j.useMemo(()=>({onClick:y,canDrill:S=>b(S)||x(S)}),[y,b,x]),k=j.useCallback((S,T)=>({canDrill:O=>b(O)||T&&x(O),onClick:O=>y({...O,...S===void 0?{}:{context:S},...T?{}:{noRows:!0}})}),[y,b,x]),C=j.useCallback(()=>a(null),[]);return{drill:v,bindingFor:k,drillMenu:t.jsx(p.Menu,{open:l!==null,onClose:C,anchorReference:"anchorPosition",anchorPosition:{top:l?.top??0,left:l?.left??0},children:(l?.items??[]).map(S=>t.jsx(p.MenuItem,{title:S.label,"aria-label":S.label,onClick:()=>{C(),S.run()},sx:{maxWidth:cd},children:t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.label})},S.key))})}}const dd=e=>{const n=je.useRef({});return je.useEffect(()=>{n.current=e}),n.current};function hd(){const[e]=Gr.useSearchParams(),n=Gr.useNavigate(),r=Gr.useLocation(),o=j.useMemo(()=>Object.fromEntries(e.entries()),[e]),i=j.useRef(new Set),l=j.useRef(null),a=j.useCallback(h=>{const y=l.current,b=new URLSearchParams(y?.key===r.key?y.search:r.search);h(b);const x=b.toString();l.current={key:r.key,search:x},n({search:x,hash:r.hash},{replace:!0})},[n,r]),u=j.useCallback((h,y)=>{const b=new Set([...y,...i.current]);i.current=new Set([...i.current,...Object.keys(h),...y]),a(x=>{for(const v of b)Object.prototype.hasOwnProperty.call(h,v)||x.delete(v);for(const[v,k]of Object.entries(h))x.set(v,k)})},[a]),d=j.useCallback((h,y)=>a(b=>{y===void 0?b.delete(h):b.set(h,y)}),[a]);return{params:o,onGivensChange:u,setParam:d}}const fd=c.createSvgIcon(t.jsx("path",{d:"M5 20h14v-2H5zM19 9h-4V3H9v6H5l7 7z"}));function fr(e){return/^[=+\-@\t\r]/.test(e)?`'${e}`:e}function mr(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function md(e){if(e===void 0)return"";switch(e.kind){case"null_cell":return"";case"number_cell":return e.string_value??String(e.number_value);case"boolean_cell":return e.boolean_value?"true":"false";case"date_cell":return e.date_value;case"timestamp_cell":return e.timestamp_value;case"string_cell":return mr(fr(e.string_value));case"json_cell":return mr(fr(e.json_value));case"sql_native_cell":return mr(fr(e.sql_native_value));default:return mr(fr(JSON.stringify(e)))}}function Va(e){const n=e.data;return n?.kind!=="array_cell"?[]:n.array_value.flatMap(r=>r.kind==="record_cell"?[r.record_value]:[])}function pd(e){const n=e.schema.fields;return`\uFEFF${[n.map(o=>mr(fr(o.name))).join(","),...Va(e).map(o=>n.map((i,l)=>md(o[l])).join(","))].join(`\r
|
|
1
|
+
"use strict";var Ku=Object.create;var wi=Object.defineProperty;var Qu=Object.getOwnPropertyDescriptor;var Zu=Object.getOwnPropertyNames;var Xu=Object.getPrototypeOf,Ju=Object.prototype.hasOwnProperty;var ed=(e,n,r,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of Zu(n))!Ju.call(e,i)&&i!==r&&wi(e,i,{get:()=>n[i],enumerable:!(o=Qu(n,i))||o.enumerable});return e};var Si=(e,n,r)=>(r=e!=null?Ku(Xu(e)):{},ed(n||!e||!e.__esModule?wi(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),m=require("@mui/material"),T=require("react"),c=require("./useCompiledDocument-5KuF7E_O.cjs.js"),q=require("./ServerProvider-BPCJnHae.cjs.js"),pt=require("@tanstack/react-query"),wr=require("@mui/system"),Pt=require("@mui/icons-material"),td=require("@malloydata/malloy-tag"),so=require("./text-entry-BJwltZiy.cjs.js"),fn=require("./RenderedResult-DAPv24rW.cjs.js"),nd=require("@malloydata/malloy-filter"),Gr=require("react-router-dom");function rd(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:()=>e[r]})}}return n.default=e,Object.freeze(n)}const Te=rd(T),sd=c.createSvgIcon(t.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function od({label:e,href:n,onClick:r}){const o=i=>{const l=i.metaKey||i.ctrlKey||i.shiftKey||i.altKey||i.button!==0;n!==void 0&&l||(i.preventDefault(),r(i))};return t.jsxs(m.Link,{...n===void 0?{component:"button",type:"button"}:{href:n},onClick:o,underline:"none","aria-label":`Back to ${e}`,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:[t.jsx(sd,{sx:{fontSize:18}}),"Back to ",e]})}const Aa="(max-width:599.95px)";function Ra(){return m.useMediaQuery(Aa,{noSsr:!0})}function $a(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Aa).matches}function id({children:e}){const[n]=T.useState($a),[r,o]=T.useState(!1);return!n||r?t.jsx(t.Fragment,{children:e}):t.jsxs(m.Stack,{sx:{alignItems:"flex-start",gap:1.5,py:3},children:[t.jsx(m.Typography,{variant:"h6",children:"Editing works best on a larger screen"}),t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:"The editor is built for a wider window. You can still try it here."}),t.jsx(m.Button,{variant:"outlined",onClick:()=>o(!0),children:"Edit anyway"})]})}function ad(){const e=Gr.useNavigate();return(n,r)=>{if(!r||!r.metaKey&&!r.ctrlKey&&!r.shiftKey&&r.button!==1){e(n);return}const o=new URL(n,window.location.href).href;(r.metaKey||r.ctrlKey||r.button===1||r.shiftKey)&&window.open(o,"_blank")}}function Fa(e,n){return e.flatMap(({filter:r})=>{if(r.kind!=="literal_equality"||r.expression.kind!=="field_reference")return[];const o=ld(r.value,n);return o===void 0?[]:[{field:r.expression.name,label:o,expression:r.expression}]})}function La(e,n){switch(e.kind){case"string_literal":return`'${c.escapeMalloyString(e.string_value)}'`;case"number_literal":return e.string_value!==void 0?/^-?\d+(\.\d+)?$/.test(e.string_value)?e.string_value:void 0:Number.isFinite(e.number_value)?String(e.number_value):void 0;case"boolean_literal":return String(e.boolean_value);case"date_literal":{const r=_a(e.date_value);return r&&`@${r[0]}-${r[1]}-${r[2]}`}case"timestamp_literal":{const r=Pa(e.timestamp_value,n);return r&&`@${r[0]}-${r[1]}-${r[2]} ${r[3]}:${r[4]}:${r[5]}${Na(e.timestamp_value)}`}default:return}}function ld(e,n){switch(e.kind){case"string_literal":return e.string_value;case"null_literal":return"null";case"date_literal":{const r=_a(e.date_value);return r&&ki([...r,"00","00","00"],e.granularity??"day")}case"timestamp_literal":{const r=Pa(e.timestamp_value,n);return r&&ki(r,e.granularity??"second")+(e.granularity===void 0?Na(e.timestamp_value):"")}default:return La(e)}}function _a(e){const n=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);return n?[n[1],n[2],n[3]]:void 0}function Na(e){const n=/:\d{2}\.(\d+)/.exec(e)?.[1]?.replace(/0+$/,"");return n?`.${n}`:""}function Pa(e,n){const r=new Date(e);if(Number.isNaN(r.getTime()))return;let o;try{o=new Intl.DateTimeFormat("en-US",{timeZone:n??"UTC",hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(r)}catch{return}const i=l=>o.find(a=>a.type===l)?.value??"";return[i("year").padStart(4,"0"),i("month"),i("day"),i("hour"),i("minute"),i("second")]}function ki([e,n,r,o,i,l],a){switch(a){case"year":return e;case"quarter":return`${e}-Q${Math.floor((Number(n)-1)/3)+1}`;case"month":return`${e}-${n}`;case"week":case"day":return`${e}-${n}-${r}`;case"hour":return`${e}-${n}-${r} ${o}`;case"minute":return`${e}-${n}-${r} ${o}:${i}`;default:return`${e}-${n}-${r} ${o}:${i}:${l}`}}const cd="drill_metadata_corrected",Zr=e=>e,Fn=e=>{try{return e?.()}catch{return}},za=e=>Fn(e.isBasic?.bind(e))===!0&&Fn(e.wasDimension?.bind(e))===!0,ud=e=>[e.isString,e.isNumber,e.isBoolean,e.isTime].some(n=>Fn(n?.bind(e))===!0);function Xr(e){const n=e.metadataTag?.text("drill_expression","code");return n===void 0||n.trim()===""?void 0:n}function Wa(e){const n=[];for(let r=e.parent;r;r=r.parent)n.push(r);return n}function qa(e){const n=Wa(e),o=(n[n.length-1]??e).metadataTag,i=o?.text("source","name");if(!i||!o?.array||o.array("source","parameters")!==void 0||o.has?.(cd)!==!0)return;const l=[];for(const u of[...n].reverse())if(Fn(u.isArray?.bind(u))===!0){if(u.metadataTag?.has?.("drillable")!==!0)return;for(const d of u.metadataTag?.array?.("drill_filters")??[]){const h=d.text("code");if(!h)return;l.push(h)}}const a=o?.text("query_name");return{source:i,filters:l,...a&&!a.startsWith("__")?{queryName:a}:{}}}function Er(e){const n=new Set;for(const r of Wa(e))for(const o of r.fields??[])za(o)&&n.add(o);return[...n]}function Ba(e){const n=new Set(Er(e).filter(r=>Fn(r.isTime?.bind(r))===!0).map(r=>Fn(r.getEffectiveQueryTimezone?.bind(r))));return n.size>1?null:[...n][0]}function Ci(e){return!za(e)||Xr(e)===void 0||qa(e)===void 0||Ba(e)===null?!1:Er(e).every(n=>Xr(n)!==void 0&&n.drillStableExpression!==void 0&&ud(n))}function dd(e,n){const r=Er(e),o=[],i=new Set;for(const l of n){if(l.kind==="drill")continue;const{filter:a}=l;if(a.kind!=="literal_equality")return;const u=JSON.stringify(a.expression),d=r.find(y=>JSON.stringify(y.drillStableExpression)===u),h=d&&Xr(d);if(d===void 0||h===void 0)return;o.push({code:h,value:a.value}),i.add(d)}return r.every(l=>i.has(l))&&o.length>0?o:void 0}const hd=360;function Hs(e){return e?e.getLabel?.()??e.tag?.text("label")??Zr(e).metadataTag?.text("label")??e.name:""}function fd(e,n){const r=e.drillClauses?Fa(e.drillClauses,e.timezone):[];if(r.length===0)return`${Hs(n)}: ${e.label}`;const o=Er(Zr(n));return r.map(i=>{const l=JSON.stringify(i.expression),a=o.find(u=>JSON.stringify(u.drillStableExpression)===l);return`${a?Hs(a):i.field}: ${i.label}`}).join(", ")}function oo({onNavigate:e,onSelf:n,destinationTitle:r,canSelf:o,onRows:i}){const[l,a]=T.useState(null),u=T.useCallback((S,j)=>S.filter(M=>M===c.DRILL_SELF?n!==void 0&&(o?.(j)??!0):e!==void 0),[e,n,o]),d=T.useCallback((S,j,M)=>{if(j===c.DRILL_SELF){n?.(S.given,S.rawValue);return}e?.({path:j,dashboard:j,givens:{[S.given]:S.value}},M)},[e,n]),h=T.useCallback(S=>{if(!i||S.noRows||S.isHeader||!S.field)return;const j=Zr(S.field);if(!Ci(j))return;const M=qa(j);if(M===void 0)return;const O=S.drillClauses;let E;if(O!==void 0){const P=dd(j,O);if(P===void 0)return;E={dimensions:P}}else{const P=Xr(j);if(P===void 0||Er(j).length!==1||c.drillValueToFilter(S.value)===void 0||typeof S.value=="number"&&Number.isInteger(S.value)&&!Number.isSafeInteger(S.value))return;E={code:P}}const $=Ba(j)??void 0;return{field:S.field.name,rawValue:S.value,label:c.drillValueLabel(S.value),target:M,...E,...S.context===void 0?{}:{context:S.context},...O===void 0?{}:{drillClauses:O},...$===void 0?{}:{timezone:$}}},[i]),y=T.useCallback(S=>{const j=c.resolveDrill(S),M=h(S),O=j?Array.from(new Set(u(j.to,j.given))).sort((P,A)=>+(A===c.DRILL_SELF)-+(P===c.DRILL_SELF)):[],E=`${Hs(S.field)}: ${j?.label??c.drillValueLabel(S.value)}`,$=O.map(P=>({key:`to:${P}`,label:P===c.DRILL_SELF?`Filter to ${E}`:`Open ${r?.(P)??c.humanizeSlug(P.split("/").pop()??P)} (${E})`,run:()=>{j&&d(j,P,S.event)}}));M&&S.field&&$.push({key:"rows",label:`Show rows (${fd(M,S.field)})`,run:()=>i?.(M)}),$.length!==0&&a({items:$,top:S.event?.clientY??0,left:S.event?.clientX??0})},[d,u,i,h,r]),b=T.useCallback(S=>u(c.drillDestinations(S),c.drillGivenName(S)).length>0,[u]),x=T.useCallback(S=>i!==void 0&&Ci(Zr(S)),[i]),v=T.useMemo(()=>({onClick:y,canDrill:S=>b(S)||x(S)}),[y,b,x]),k=T.useCallback((S,j)=>({canDrill:M=>b(M)||j&&x(M),onClick:M=>y({...M,...S===void 0?{}:{context:S},...j?{}:{noRows:!0}})}),[y,b,x]),C=T.useCallback(()=>a(null),[]);return{drill:v,bindingFor:k,drillMenu:t.jsx(m.Menu,{open:l!==null,onClose:C,anchorReference:"anchorPosition",anchorPosition:{top:l?.top??0,left:l?.left??0},children:(l?.items??[]).map(S=>t.jsx(m.MenuItem,{title:S.label,"aria-label":S.label,onClick:()=>{C(),S.run()},sx:{maxWidth:hd},children:t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.label})},S.key))})}}const pd=e=>{const n=Te.useRef({});return Te.useEffect(()=>{n.current=e}),n.current};function md(){const[e]=Gr.useSearchParams(),n=Gr.useNavigate(),r=Gr.useLocation(),o=T.useMemo(()=>Object.fromEntries(e.entries()),[e]),i=T.useRef(new Set),l=T.useRef(null),a=T.useCallback(h=>{const y=l.current,b=new URLSearchParams(y?.key===r.key?y.search:r.search);h(b);const x=b.toString();l.current={key:r.key,search:x},n({search:x,hash:r.hash},{replace:!0})},[n,r]),u=T.useCallback((h,y)=>{const b=new Set([...y,...i.current]);i.current=new Set([...i.current,...Object.keys(h),...y]),a(x=>{for(const v of b)Object.prototype.hasOwnProperty.call(h,v)||x.delete(v);for(const[v,k]of Object.entries(h))x.set(v,k)})},[a]),d=T.useCallback((h,y)=>a(b=>{y===void 0?b.delete(h):b.set(h,y)}),[a]);return{params:o,onGivensChange:u,setParam:d}}const gd=c.createSvgIcon(t.jsx("path",{d:"M5 20h14v-2H5zM19 9h-4V3H9v6H5l7 7z"}));function fr(e){return/^[=+\-@\t\r]/.test(e)?`'${e}`:e}function pr(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function yd(e){if(e===void 0)return"";switch(e.kind){case"null_cell":return"";case"number_cell":return e.string_value??String(e.number_value);case"boolean_cell":return e.boolean_value?"true":"false";case"date_cell":return e.date_value;case"timestamp_cell":return e.timestamp_value;case"string_cell":return pr(fr(e.string_value));case"json_cell":return pr(fr(e.json_value));case"sql_native_cell":return pr(fr(e.sql_native_value));default:return pr(fr(JSON.stringify(e)))}}function Va(e){const n=e.data;return n?.kind!=="array_cell"?[]:n.array_value.flatMap(r=>r.kind==="record_cell"?[r.record_value]:[])}function xd(e){const n=e.schema.fields;return`\uFEFF${[n.map(o=>pr(fr(o.name))).join(","),...Va(e).map(o=>n.map((i,l)=>yd(o[l])).join(","))].join(`\r
|
|
2
2
|
`)}\r
|
|
3
|
-
`}function gd(e,n){return[e,"rows",...n].join("_").replace(/[^A-Za-z0-9._-]+/g,"_").replace(/_+/g,"_").replace(/^[_.]+|[_.]+$/g,"").slice(0,120)||"rows"}function yd(e,n,r){return r==="server_default"&&n!==void 0&&e>=n?n:void 0}const ji="Download the rows behind this value as CSV, up to the server's row limit",xd=4e4;function vd(e,n){const r=URL.createObjectURL(new Blob([e],{type:"text/csv;charset=utf-8"})),o=document.createElement("a");o.href=r,o.download=n,document.body.appendChild(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(r),xd)}function bd(e){const r=e?.response?.data?.message;return typeof r=="string"&&r!==""?r:e instanceof Error&&e.message!==""?e.message:"The request failed."}function Ha({query:e,preamble:n,environmentName:r,packageName:o,modelPath:i,versionId:l,givens:a,fileName:u}){const{apiClients:d}=q.useServer(),[h,y]=j.useState(!1),[b,x]=j.useState(ji),[v,k]=j.useState(void 0),C=j.useRef(void 0);j.useEffect(()=>()=>C.current?.abort(),[]);const S=async()=>{C.current?.abort();const T=new AbortController;C.current=T,y(!0),k(void 0);try{const O=await d.models.executeQueryModel(r,o,i,{query:n===void 0?e:c.withPreamble(n,e),givens:a,versionId:l},void 0,void 0,{signal:T.signal});if(T.signal.aborted)return;const M=O.data,E=JSON.parse(M.result??"{}"),R=yd(Va(E).length,M.queryRowLimit,M.queryRowLimitSource);x(R===void 0?ji:`First ${R} rows: the server's row limit, so there may be more`),vd(pd(E),R===void 0?`${u}.csv`:`${u}_first_${R}_rows_server_limit.csv`)}catch(O){if(T.signal.aborted)return;k(`Download failed: ${bd(O)}`)}finally{C.current===T&&(C.current=void 0,y(!1))}};return t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[v&&t.jsx(p.Typography,{role:"alert",variant:"caption",color:"error",sx:{maxWidth:320},children:v}),t.jsx(p.Tooltip,{title:b,children:t.jsx("span",{children:t.jsx(p.Button,{size:"small",startIcon:t.jsx(fd,{fontSize:"small"}),onClick:()=>void S(),disabled:h,children:"Download CSV"})})})]})}const Ua=200;function wd(e){const{target:n}=e;if(n!==void 0&&!(e.dimensions===void 0&&e.code===void 0))return{...e,target:n}}function Ti(e,n=Ua){const r=kd(e);if(r===void 0)return;const o=[...e.target.filters,...r].join(", "),i=e.timezone?`timezone: '${c.escapeMalloyString(e.timezone)}'; `:"",l=n===null?"":`; limit: ${n}`,a=Sd(e.target.source);if(a!==void 0)return`run: ${a} -> { ${i}where: ${o}; select: *${l} }`}function Sd(e){return so.isBareName(e)?e:e.includes("`")?void 0:`\`${e}\``}function Cs(e){return/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(e)?e:`(${e})`}function kd(e){if(e.dimensions){const r=[];for(const{code:o,value:i}of e.dimensions){if(i.kind==="null_literal"){r.push(`${Cs(o)} is null`);continue}const l=La(i,e.timezone);if(l===void 0)return;r.push(`${Cs(o)} = ${l}`)}return r}const n=c.malloyLiteral(e.rawValue);return e.code!==void 0&&n?[`${Cs(e.code)} = ${n}`]:void 0}const Cd="This value cannot be written as a filter, so its rows cannot be fetched.";function Oi(e){const n=e.drillClauses?Ra(e.drillClauses,e.timezone):[];return n.length>0?n:[{field:e.field,label:e.label}]}function jd({request:e,environmentName:n,packageName:r,versionId:o,modelPath:i,preamble:l,givens:a,onClose:u,onDone:d,actions:h}){const{theme:y}=q.usePublisherTheme(),b=e?Ti(e):void 0,x=e?Ti(e,null):void 0,v=e&&x!==void 0?{query:x,...l===void 0?{}:{preamble:l},environmentName:n,packageName:r,modelPath:i,...o===void 0?{}:{versionId:o},givens:a,fileName:gd(e.target.source,Oi(e).map(k=>k.label))}:void 0;return t.jsxs(p.Dialog,{open:e!==void 0,onClose:u,maxWidth:"lg",fullWidth:!0,children:[t.jsxs(p.DialogTitle,{sx:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",pb:.5},children:[t.jsxs(p.Box,{children:[e?t.jsxs(t.Fragment,{children:["Rows where"," ",Oi(e).map((k,C)=>t.jsxs(j.Fragment,{children:[C>0&&" and ",t.jsx(p.Box,{component:"code",sx:{fontSize:"0.9em"},children:k.field})," ","is ",k.label]},C))]}):"Rows",t.jsx(p.Typography,{component:"div",variant:"caption",sx:{color:y.tileTitle,mt:.25},children:e?`The first ${Ua} rows of ${e.target.source} behind this value, with the tile's own filters and the controls applied.`:""})]}),t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",gap:1,ml:1},children:[v&&(h?h(v):t.jsx(Ha,{...v})),t.jsx(p.IconButton,{onClick:u,"aria-label":"Close",size:"small",sx:{color:"text.secondary"},children:t.jsx(c.CloseIcon,{fontSize:"small"})})]})]}),t.jsxs(p.DialogContent,{dividers:!0,sx:{p:0,minHeight:240},children:[b===void 0&&e&&t.jsx(p.Typography,{variant:"body2",sx:{p:2},children:Cd}),b!==void 0&&t.jsx(Td,{query:l===void 0?b:c.withPreamble(l,b),environmentName:n,packageName:r,...o===void 0?{}:{versionId:o},modelPath:i,givens:a,...d?{onDone:d}:{}})]}),t.jsxs(p.DialogActions,{sx:{px:3,py:1.5},children:[b!==void 0&&t.jsx(p.Typography,{variant:"caption",sx:{mr:"auto",color:y.tileTitle,fontFamily:y.ui.font.mono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:b,children:b}),t.jsx(p.Button,{onClick:u,children:"Close"})]})]})}function Td({query:e,environmentName:n,packageName:r,versionId:o,modelPath:i,givens:l,onDone:a}){const u=c.useQueryResult({environmentName:n,packageName:r,modelPath:i,...o===void 0?{}:{versionId:o},query:e,givens:l}),{isSuccess:d,isError:h}=u,y=j.useRef(void 0);return j.useEffect(()=>{y.current=c.now()},[e]),j.useEffect(()=>{y.current===void 0||!d&&!h||(a?.(d,c.now()-y.current),y.current=void 0)},[d,h,a]),t.jsx(p.Box,{sx:{p:1},children:t.jsx(c.ResultPanel,{state:u,context:e})})}function Ga({manifest:e,environmentName:n,packageName:r,versionId:o,documentName:i,givens:l,onGivensChange:a,onNavigate:u,height:d,maxResultSize:h,controlsLayout:y="bar",preamble:b,runModelPath:x,hiddenGivens:v,literalReads:k,onLinkNavigate:C,actions:S,rowsActions:T}){const O=j.useMemo(()=>C?{environmentName:n,packageName:r,sourcePath:e.path??i,onNavigate:C}:void 0,[n,r,e.path,i,C]),M=j.useMemo(()=>(e.givens??[]).filter(te=>!(b!==void 0&&te.secure===!0)&&!(te.name!==void 0&&v?.includes(te.name))),[e,v,b]),E=j.useMemo(()=>l===void 0?void 0:Object.fromEntries(Object.entries(l).filter(([,te])=>typeof te=="string")),[l]),R=c.useDocumentControls({specs:M,loaded:!0,startingValues:e.startingGivens,params:E,onGivensChange:a,documentKey:`${n}/${r}/${o??""}/${i}`,autorun:e.autorun!==!1,environmentName:n,packageName:r,modelPath:x??e.path,versionId:o,documentName:i,...b!==void 0?{preamble:b}:{},...l?{hostGivens:l}:{}}),{applied:P,declaredTypes:F,canSelf:B,onSelf:D}=R,_=c.useReportEvents(),V=j.useMemo(()=>{const te=new Set((e.tiles??[]).flatMap(K=>K.givenNames??[]));return Object.fromEntries(Object.entries(l??{}).filter(([K])=>te.has(K)&&!F.has(K)))},[e,l,F]),[$,W]=j.useState(void 0),Z=j.useCallback(te=>{const K=wd(te);K!==void 0&&W(K)},[]),ne=j.useMemo(()=>c.withHostGivens(c.givensToRequest(P,F),V),[P,F,V]),{reports:J}=c.useReportListing(n,r,o,u!==void 0),H=j.useCallback(te=>{const K=c.resolveDrillTarget(te,J);if(K.kind!=="path")return;const he=K.report.path;return J.find(we=>we.path===he)?.title||void 0},[J]),{bindingFor:Q,drillMenu:re}=oo({onNavigate:u,onSelf:D,canSelf:B,onRows:Z,destinationTitle:H}),z=j.useCallback((te,K)=>Q(te,K!==!0),[Q]),{columns:oe,layout:se,tileMaxHeight:ie,tableMaxHeight:De}=c.layoutRules(e.layout,e.dashboardColumns),de=j.useMemo(()=>c.missingRequiredGivens(M,P,l),[M,P,l]);if(e.error)return t.jsx(c.ReportPage,{layout:se,header:t.jsx(Mi,{manifest:e,links:O,actions:S}),children:t.jsx(p.Alert,{severity:"error",children:e.error})});const ue=x??e.path,be=e.tiles??[],Me=c.isPlaced(be);return t.jsxs(c.ReportPage,{layout:se,header:t.jsx(Mi,{manifest:e,links:O,actions:S}),controls:M.length>0?t.jsx(c.StickyControls,{children:t.jsx(c.GivensPanel,{...R.panel,layout:y})}):void 0,children:[de.length>0&&t.jsx(p.Alert,{severity:"info",children:c.requiredPrompt(de)}),ue===void 0?t.jsx(p.Alert,{severity:"error",children:"This dashboard has no model path, so there is nothing to run."}):be.length>0?t.jsx(c.DashboardGrid,{tiles:be,columns:oe,minTilePx:c.MIN_TILE_PX,rowGapPx:c.GRID_GAP_PX,keyOf:(te,K)=>`${K}:${te.kind==="text"?`text:${te.name}`:te.query}`,renderTile:(te,K)=>te.kind==="text"||te.query===void 0?t.jsx(p.Box,{sx:te.rowspan!==void 0||Me?{minHeight:0,overflow:"auto"}:void 0,children:t.jsx(Od,{markdown:te.markdown??"",links:O})}):t.jsx(c.DashboardTile,{index:K,environmentName:n,packageName:r,versionId:o,modelPath:ue,tile:te.query,label:te.label,subtitle:te.subtitle,borderless:te.borderless,givens:P,hostGivens:V,declaredTypes:F,givenNames:te.givenNames,height:te.rowspan!==void 0||Me?c.tileHeightPx(te.rowspan??c.PLACED_DEFAULT_ROWSPAN.query):se==="grid"?d??ie:ie,tableMaxHeight:De,fixedHeight:te.rowspan!==void 0||Me,maxResultSize:h,drill:z(te.query,te.restricted),ignoredFilters:c.tileIgnoredFilterLabels(te.givenNames&&(te.query&&k?.[te.query]?[...te.givenNames,...k[te.query]]:te.givenNames),M),...b!==void 0?{preamble:b,restricted:te.restricted}:{},...(()=>{const he=c.waitingOn(de,te.givenNames);return he.length>0?{waitingFor:c.waitingText(he)}:{}})()})}):t.jsx(p.Alert,{severity:"warning",children:"This dashboard names neither a query nor any tiles."}),re,ue!==void 0&&t.jsx(jd,{request:$,environmentName:n,packageName:r,...o===void 0?{}:{versionId:o},modelPath:ue,...b===void 0?{}:{preamble:b},givens:ne,...T===void 0?{}:{actions:T},onClose:()=>W(void 0),onDone:(te,K)=>{$&&_.emit({type:"report.rows_shown",source:$.target.source,view:$.target.queryName??"",field:$.field,ok:te,durationMs:K})}})]})}function Od({markdown:e,links:n}){return t.jsx(c.TextTileFrame,{children:t.jsx(c.Prose,{variant:"document",links:n,children:e})})}function Mi({manifest:e,links:n,actions:r}){return t.jsx(c.ReportHeader,{title:e.title??e.name,actions:r,description:e.description?t.jsx(c.TextTileFrame,{children:t.jsx(c.Prose,{variant:"document",links:n,children:e.description})}):void 0})}const Ya=c.createSvgIcon(t.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"})),Md="publisher:resize";function Ed(e){return typeof e=="object"&&e!==null&&e.type===Md&&typeof e.height=="number"}function Ka(e){return e.replace(/\/api\/v0\/?$/,"")}function Qa({server:e,environmentName:n,packageName:r,path:o,versionId:i}){const l=o.startsWith("public/")?o.slice(7):o,a=`${Ka(e)}/environments/${encodeURIComponent(n)}/packages/${encodeURIComponent(r)}/`+l;return i===void 0?a:`${a}${a.includes("?")?"&":"?"}versionId=${encodeURIComponent(i)}`}function Id(e){try{const{environmentName:n,packageName:r,modelPath:o,versionId:i}=c.parseResourceUri(e);return!n||!r||!o?null:{environmentName:n,packageName:r,dataAppPath:o,versionId:i}}catch{return null}}function Dd({resourceUri:e}){const{server:n,apiClients:r}=q.useServer(),o=Id(e),i=o?.environmentName??"",l=o?.packageName??"",a=o?.dataAppPath??"",u=o?.versionId,d=j.useMemo(()=>Qa({server:n,environmentName:i,packageName:l,path:a,...u!==void 0?{versionId:u}:{}}),[n,i,l,a,u]),y=c.useQueryWithApiError({queryKey:["data-apps",i,l,u],queryFn:()=>r.dataApps.listDataApps(i,l,u),enabled:!!o}).data?.data?.find(S=>S.path===a),b=y?.title??a,x=y?.fit==="viewport",v=j.useRef(null),[k,C]=j.useState(120);return j.useEffect(()=>{if(x)return;function S(T){Ed(T.data)&&T.source===v.current?.contentWindow&&T.data.height>0&&C(Math.ceil(T.data.height))}return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[x]),o?t.jsxs(p.Box,{sx:{p:3,...x?{height:"100%",display:"flex",flexDirection:"column"}:{maxWidth:1600,mx:"auto"}},children:[t.jsxs(p.Stack,{direction:"row",alignItems:"baseline",spacing:1,sx:{mb:1,flexShrink:0},children:[t.jsx(p.Typography,{variant:"h6",sx:{fontWeight:"fontWeightMedium",letterSpacing:"-0.025em"},children:b}),t.jsx(p.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:q.MONO_FONT_FAMILY},children:a}),t.jsx(p.Box,{sx:{flex:1}}),t.jsx(p.Tooltip,{title:"Open standalone in new tab",children:t.jsx(p.IconButton,{size:"small",href:d,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:t.jsx(Ya,{fontSize:"small"})})})]}),t.jsx(p.Box,{sx:{border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden",backgroundColor:"background.paper",...x?{flex:1,minHeight:0}:{}},children:t.jsx("iframe",{ref:v,src:d,title:b,sandbox:"allow-scripts allow-same-origin allow-forms",style:{display:"block",width:"100%",height:x?"100%":k,border:0}})})]}):t.jsxs(p.Box,{sx:{p:3,maxWidth:1600,mx:"auto"},children:[t.jsx(p.Typography,{variant:"h6",sx:{fontWeight:"fontWeightMedium"},children:"Can't open data app"}),t.jsxs(p.Typography,{variant:"body2",color:"text.secondary",sx:{mt:1},children:["This data app link is missing an environment, package, or path:",t.jsx(p.Box,{component:"span",sx:{fontFamily:q.MONO_FONT_FAMILY,ml:1},children:e})]})]})}function Nt({title:e,count:n,description:r,action:o,children:i}){const l=j.useId();return t.jsxs(p.Box,{component:"section","aria-labelledby":l,sx:{mb:4},children:[t.jsxs(p.Stack,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:r?0:1,minHeight:40},children:[t.jsxs(p.Stack,{direction:"row",alignItems:"baseline",spacing:1,children:[t.jsx(p.Typography,{id:l,variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em",lineHeight:1.2},children:e}),n!==void 0&&t.jsxs(p.Typography,{variant:"caption",color:"text.secondary",children:["(",n,")"]})]}),o]}),r&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:r}),t.jsx(p.Box,{children:i})]})}function $d({resourceUri:e}){const{environmentName:n}=c.parseResourceUri(e),{apiClients:r}=q.useServer(),[o,i]=j.useState(!1),l=90,{data:a,isSuccess:u,isError:d,error:h}=c.useQueryWithApiError({queryKey:["about",n],queryFn:()=>r.environments.getEnvironment(n,!1)}),y=a?.data?.readme||"",b=y.split(/\s+/),x=b.length>l,v=b.slice(0,l).join(" ");return t.jsxs(t.Fragment,{children:[!u&&!d&&t.jsx(c.Loading,{text:"Fetching About..."}),u&&y&&t.jsxs(Nt,{title:"Readme",children:[t.jsx(c.Prose,{variant:"caption",children:o||!x?y:v}),x&&t.jsx(p.Box,{sx:{mt:1},children:t.jsx(c.SecondaryButton,{label:o?"Read less":"Read more",onClick:()=>i(!o)})})]}),d&&t.jsx(c.ApiErrorDisplay,{error:h,context:`${n} > About`})]})}function Fd(e={}){const{autoHideDuration:n=null,disableWindowBlurListener:r=!1,onClose:o,open:i,resumeHideDuration:l}=e,a=c.useTimeout();je.useEffect(()=>{if(!i)return;function T(O){O.defaultPrevented||O.key==="Escape"&&o?.(O,"escapeKeyDown")}return document.addEventListener("keydown",T),()=>{document.removeEventListener("keydown",T)}},[i,o]);const u=c.useEventCallback((T,O)=>{o?.(T,O)}),d=c.useEventCallback(T=>{!o||T==null||a.start(T,()=>{u(null,"timeout")})});je.useEffect(()=>(i&&d(n),a.clear),[i,n,d,a]);const h=T=>{o?.(T,"clickaway")},y=a.clear,b=je.useCallback(()=>{n!=null&&d(l??n*.5)},[n,l,d]),x=T=>O=>{const M=T.onBlur;M?.(O),b()},v=T=>O=>{const M=T.onFocus;M?.(O),y()},k=T=>O=>{const M=T.onMouseEnter;M?.(O),y()},C=T=>O=>{const M=T.onMouseLeave;M?.(O),b()};return je.useEffect(()=>{if(!r&&i)return window.addEventListener("focus",b),window.addEventListener("blur",y),()=>{window.removeEventListener("focus",b),window.removeEventListener("blur",y)}},[r,i,b,y]),{getRootProps:(T={})=>{const O={...c.extractEventHandlers(e),...c.extractEventHandlers(T)};return{role:"presentation",...T,...O,onBlur:x(O),onFocus:v(O),onMouseEnter:k(O),onMouseLeave:C(O)}},onClickAway:h}}function Ei(e){return e.substring(2).toLowerCase()}function Ad(e,n){return n.documentElement.clientWidth<e.clientX||n.documentElement.clientHeight<e.clientY}function Rd(e){const{children:n,disableReactTree:r=!1,mouseEvent:o="onClick",onClickAway:i,touchEvent:l="onTouchEnd"}=e,a=je.useRef(!1),u=je.useRef(null),d=je.useRef(!1),h=je.useRef(!1);je.useEffect(()=>(setTimeout(()=>{d.current=!0},0),()=>{d.current=!1}),[]);const y=c.useForkRef(c.getReactElementRef(n),u),b=c.useEventCallback(k=>{const C=h.current;h.current=!1;const S=c.ownerDocument(u.current);if(!d.current||!u.current||"clientX"in k&&Ad(k,S))return;if(a.current){a.current=!1;return}let T;k.composedPath?T=k.composedPath().includes(u.current):T=!S.documentElement.contains(k.target)||u.current.contains(k.target),!T&&(r||!C)&&i(k)}),x=k=>C=>{h.current=!0;const S=n.props[k];S&&S(C)},v={ref:y};return l!==!1&&(v[l]=x(l)),je.useEffect(()=>{if(l!==!1){const k=Ei(l),C=c.ownerDocument(u.current),S=()=>{a.current=!0};return C.addEventListener(k,b),C.addEventListener("touchmove",S),()=>{C.removeEventListener(k,b),C.removeEventListener("touchmove",S)}}},[b,l]),o!==!1&&(v[o]=x(o)),je.useEffect(()=>{if(o!==!1){const k=Ei(o),C=c.ownerDocument(u.current);return C.addEventListener(k,b),()=>{C.removeEventListener(k,b)}}},[b,o]),je.cloneElement(n,v)}function Ld(e){return c.generateUtilityClass("MuiSnackbarContent",e)}c.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const _d=e=>{const{classes:n}=e,r={root:["root"],action:["action"],message:["message"]};return c.composeClasses(r,Ld,n)},Nd=c.styled(c.Paper,{name:"MuiSnackbarContent",slot:"Root"})(c.memoTheme(({theme:e})=>{const n=e.palette.mode==="light"?.8:.98;return{...e.typography.body2,color:e.vars?e.vars.palette.SnackbarContent.color:e.palette.getContrastText(c.emphasize(e.palette.background.default,n)),backgroundColor:e.vars?e.vars.palette.SnackbarContent.bg:c.emphasize(e.palette.background.default,n),display:"flex",alignItems:"center",flexWrap:"wrap",padding:"6px 16px",flexGrow:1,[e.breakpoints.up("sm")]:{flexGrow:"initial",minWidth:288}}})),Pd=c.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),zd=c.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),Wd=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiSnackbarContent"}),{action:i,className:l,message:a,role:u="alert",...d}=o,h=o,y=_d(h);return t.jsxs(Nd,{role:u,elevation:6,className:c.clsx(y.root,l),ownerState:h,ref:r,...d,children:[t.jsx(Pd,{className:y.message,ownerState:h,children:a}),i?t.jsx(zd,{className:y.action,ownerState:h,children:i}):null]})});function qd(e){return c.generateUtilityClass("MuiSnackbar",e)}c.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const Bd=e=>{const{classes:n,anchorOrigin:r}=e,o={root:["root",`anchorOrigin${c.capitalize(r.vertical)}${c.capitalize(r.horizontal)}`]};return c.composeClasses(o,qd,n)},Vd=c.styled("div",{name:"MuiSnackbar",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,n[`anchorOrigin${c.capitalize(r.anchorOrigin.vertical)}${c.capitalize(r.anchorOrigin.horizontal)}`]]}})(c.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.snackbar,position:"fixed",display:"flex",left:8,right:8,justifyContent:"center",alignItems:"center",variants:[{props:({ownerState:n})=>n.anchorOrigin.vertical==="top",style:{top:8,[e.breakpoints.up("sm")]:{top:24}}},{props:({ownerState:n})=>n.anchorOrigin.vertical!=="top",style:{bottom:8,[e.breakpoints.up("sm")]:{bottom:24}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="left",style:{justifyContent:"flex-start",[e.breakpoints.up("sm")]:{left:24,right:"auto"}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="right",style:{justifyContent:"flex-end",[e.breakpoints.up("sm")]:{right:24,left:"auto"}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="center",style:{[e.breakpoints.up("sm")]:{left:"50%",right:"auto",transform:"translateX(-50%)"}}}]}))),Hd=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiSnackbar"}),i=c.useTheme(),l={enter:i.transitions.duration.enteringScreen,exit:i.transitions.duration.leavingScreen},{action:a,anchorOrigin:{vertical:u,horizontal:d}={vertical:"bottom",horizontal:"left"},autoHideDuration:h=null,children:y,className:b,ClickAwayListenerProps:x,ContentProps:v,disableWindowBlurListener:k=!1,message:C,onBlur:S,onClose:T,onFocus:O,onMouseEnter:M,onMouseLeave:E,open:R,resumeHideDuration:P,slots:F={},slotProps:B={},TransitionComponent:D,transitionDuration:_=l,TransitionProps:{onEnter:V,onExited:$,...W}={},...Z}=o,ne={...o,anchorOrigin:{vertical:u,horizontal:d},autoHideDuration:h,disableWindowBlurListener:k,TransitionComponent:D,transitionDuration:_},J=Bd(ne),{getRootProps:H,onClickAway:Q}=Fd({...ne}),[re,z]=je.useState(!0),oe=ge=>{z(!0),$&&$(ge)},se=(ge,pe)=>{z(!1),V&&V(ge,pe)},ie={slots:{transition:D,...F},slotProps:{content:v,clickAwayListener:x,transition:W,...B}},[De,de]=c.useSlot("root",{ref:r,className:[J.root,b],elementType:Vd,getSlotProps:H,externalForwardedProps:{...ie,...Z},ownerState:ne}),[ue,{ownerState:be,...Me}]=c.useSlot("clickAwayListener",{elementType:Rd,externalForwardedProps:ie,getSlotProps:ge=>({onClickAway:(...pe)=>{const ye=pe[0];ge.onClickAway?.(...pe),!ye?.defaultMuiPrevented&&Q(...pe)}}),ownerState:ne}),[te,K]=c.useSlot("content",{elementType:Wd,shouldForwardComponentProp:!0,externalForwardedProps:ie,additionalProps:{message:C,action:a},ownerState:ne}),[he,we]=c.useSlot("transition",{elementType:c.Grow,externalForwardedProps:ie,getSlotProps:ge=>({onEnter:(...pe)=>{ge.onEnter?.(...pe),se(...pe)},onExited:(...pe)=>{ge.onExited?.(...pe),oe(...pe)}}),additionalProps:{appear:!0,in:R,timeout:_,direction:u==="top"?"down":"up"},ownerState:ne});return!R&&re?null:t.jsx(ue,{...Me,...F.clickAwayListener&&{ownerState:be},children:t.jsx(De,{...de,children:t.jsx(he,{...we,children:y||t.jsx(te,{...K})})})})});let Us;function Ud(e){Us=e}function Ii(e){if(Us)try{Us(e)}catch{}}function Ht(e,n,r){return(async o=>{const i=Date.now();try{const l=await r(o);return Ii({type:"console.mutation",resource:e,action:n,ok:!0,durationMs:Date.now()-i}),l}catch(l){throw Ii({type:"console.mutation",resource:e,action:n,ok:!1,durationMs:Date.now()-i,reason:l instanceof Error?l.message:"An unknown error occurred"}),l}})}function Nn({mutationFn:e,success:n,invalidates:r,closeDialog:o,resource:i,action:l}){const a=mt.useQueryClient(),[u,d]=j.useState(""),h=c.useMutationWithApiError({mutationFn:Ht(i,l,e),onSuccess(){o();for(const y of r)a.invalidateQueries({queryKey:y});d(n)},onError(y){d(y instanceof Error?y.message:"An unknown error occurred")}});return{mutate:h.mutate,isPending:h.isPending,notice:t.jsx(Hd,{open:u!=="",autoHideDuration:6e3,onClose:()=>d(""),message:u})}}const Za="https://docs.malloydata.dev/documentation",js=`${Za}/user_guides/publishing`,In="https://github.com/malloydata/publisher/blob/main/docs",Vt={docsHome:`${Za}/`,publishing:`${js}/publishing`,explorer:`${js}/explorer`,mcpAgents:`${js}/mcp_agents`,surfaces:`${In}/choosing-a-surface.md`,dashboards:`${In}/dashboards.md`,dataApps:`${In}/html-data-apps.md`,givens:`${In}/givens.md`,materialization:`${In}/materialization.md`,connections:`${In}/connections.md`};function Gd({resourceUri:e}){const[n,r]=j.useState(!1),{apiClients:o}=q.useServer(),{environmentName:i}=c.parseResourceUri(e),l=Nn({mutationFn(u){return o.packages.createPackage(i,{name:u.name,description:u.description,location:u.location})},success:"Package created",invalidates:[["packages",i]],closeDialog:()=>r(!1),resource:"package",action:"create"}),a=u=>{u.preventDefault();const d=new FormData(u.currentTarget),h=d.get("name")?.toString(),y=d.get("description")?.toString(),b=d.get("location")?.toString();l.mutate({name:h,description:y,location:b})};return t.jsxs(t.Fragment,{children:[t.jsx(c.AddButton,{label:"Package",onClick:()=>r(!0)}),t.jsx(c.AppDialog,{open:n,onClose:()=>r(!1),title:"New package",description:t.jsxs(t.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"," ",t.jsx(p.Box,{component:"a",href:Vt.publishing,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary"},children:"package format"}),"."]}),actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{disabled:l.isPending,onClick:()=>r(!1),children:"Cancel"}),t.jsx(p.Button,{type:"submit",form:"package-form",variant:"contained",loading:l.isPending,children:"Create package"})]}),children:t.jsx("form",{onSubmit:a,id:"package-form",children:t.jsxs(p.Stack,{sx:{gap:2},children:[t.jsx(p.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(p.TextField,{id:"description",name:"description",label:"Description",multiline:!0,rows:3,fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(p.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}})]})})}),l.notice]})}const Yd=c.createSvgIcon(t.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function rs({icon:e,tint:n,label:r,mono:o,description:i,rightLabel:l,trailingAction:a,onClick:u,ariaLabel:d}){const h=!!u,y=b=>{u&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),u(b))};return t.jsxs(p.Box,{onClick:u,onKeyDown:h?y:void 0,role:h?"button":void 0,tabIndex:h?0:void 0,"aria-label":d,sx:b=>({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:b.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:[t.jsx(p.Box,{sx:{width:32,height:32,borderRadius:1,bgcolor:n,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:e}),t.jsxs(p.Box,{sx:{flex:1,minWidth:0,display:"flex",alignItems:"baseline",gap:1.5},children:[t.jsx(p.Typography,{variant:"body2",sx:{...o?{fontFamily:q.MONO_FONT_FAMILY}:{},flexShrink:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),i&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i})]}),l&&t.jsx(p.Typography,{variant:"caption",color:"text.secondary",sx:{flexShrink:0},children:l}),a&&t.jsx(p.Box,{sx:{flexShrink:0,display:"flex",alignItems:"center"},children:a})]})}const Xa=c.createSvgIcon(t.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"})),Kd=c.generateUtilityClasses("MuiBox",["root"]),Qd=c.createTheme(),Ge=wr.createBox({themeId:c.THEME_ID,defaultTheme:Qd,defaultClassName:Kd.root,generateClassName:c.ClassNameGenerator.generate}),ss=wr.createStack({createStyledComponent:c.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:e=>c.useDefaultProps({props:e,name:"MuiStack"})}),Di=c.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function Zd(e){return c.generateUtilityClass("MuiListItemIcon",e)}const $i=c.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),Xd=e=>{const{alignItems:n,classes:r}=e,o={root:["root",n==="flex-start"&&"alignItemsFlexStart"]};return c.composeClasses(o,Zd,r)},Jd=c.styled("div",{name:"MuiListItemIcon",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,r.alignItems==="flex-start"&&n.alignItemsFlexStart]}})(c.memoTheme(({theme:e})=>({minWidth:56,color:(e.vars||e).palette.action.active,flexShrink:0,display:"inline-flex",variants:[{props:{alignItems:"flex-start"},style:{marginTop:8}}]}))),io=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiListItemIcon"}),{className:i,...l}=o,a=je.useContext(c.ListContext),u={...o,alignItems:a.alignItems},d=Xd(u);return t.jsx(Jd,{className:c.clsx(d.root,i),ownerState:u,ref:r,...l})});function eh(e){return c.generateUtilityClass("MuiListItemText",e)}const $n=c.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),th=e=>{const{classes:n,inset:r,primary:o,secondary:i,dense:l}=e,a={root:["root",r&&"inset",l&&"dense",o&&i&&"multiline"],primary:["primary"],secondary:["secondary"]};return c.composeClasses(a,eh,n)},nh=c.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${$n.primary}`]:n.primary},{[`& .${$n.secondary}`]:n.secondary},n.root,r.inset&&n.inset,r.primary&&r.secondary&&n.multiline,r.dense&&n.dense]}})({flex:"1 1 auto",minWidth:0,marginTop:4,marginBottom:4,[`.${c.typographyClasses.root}:where(& .${$n.primary})`]:{display:"block"},[`.${c.typographyClasses.root}:where(& .${$n.secondary})`]:{display:"block"},variants:[{props:({ownerState:e})=>e.primary&&e.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:e})=>e.inset,style:{paddingLeft:56}}]}),ao=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiListItemText"}),{children:i,className:l,disableTypography:a=!1,inset:u=!1,primary:d,primaryTypographyProps:h,secondary:y,secondaryTypographyProps:b,slots:x={},slotProps:v={},...k}=o,{dense:C}=je.useContext(c.ListContext);let S=d??i,T=y;const O={...o,disableTypography:a,inset:u,primary:!!S,secondary:!!T,dense:C},M=th(O),E={slots:x,slotProps:{primary:h,secondary:b,...v}},[R,P]=c.useSlot("root",{className:c.clsx(M.root,l),elementType:nh,externalForwardedProps:{...E,...k},ownerState:O,ref:r}),[F,B]=c.useSlot("primary",{className:M.primary,elementType:c.Typography,externalForwardedProps:E,ownerState:O}),[D,_]=c.useSlot("secondary",{className:M.secondary,elementType:c.Typography,externalForwardedProps:E,ownerState:O});return S!=null&&S.type!==c.Typography&&!a&&(S=t.jsx(F,{variant:C?"body2":"body1",component:B?.variant?void 0:"span",...B,children:S})),T!=null&&T.type!==c.Typography&&!a&&(T=t.jsx(D,{variant:"body2",color:"textSecondary",..._,children:T})),t.jsxs(R,{...P,children:[S,T]})});function rh(e){return c.generateUtilityClass("MuiMenuItem",e)}const er=c.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),sh=(e,n)=>{const{ownerState:r}=e;return[n.root,r.dense&&n.dense,r.divider&&n.divider,!r.disableGutters&&n.gutters]},oh=e=>{const{disabled:n,dense:r,divider:o,disableGutters:i,selected:l,classes:a}=e,u={root:["root",r&&"dense",n&&"disabled",!i&&"gutters",o&&"divider",l&&"selected"]},d=c.composeClasses(u,rh,a);return{...a,...d}},ih=c.styled(c.ButtonBase,{shouldForwardProp:e=>c.rootShouldForwardProp(e)||e==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:sh})(c.memoTheme(({theme:e})=>({...e.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:(e.vars||e).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},[`&.${er.selected}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity),[`&.${er.focusVisible}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.focusOpacity}`)}},[`&.${er.selected}:hover`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity)}},[`&.${er.focusVisible}`]:{backgroundColor:(e.vars||e).palette.action.focus},[`&.${er.disabled}`]:{opacity:(e.vars||e).palette.action.disabledOpacity},[`& + .${Di.root}`]:{marginTop:e.spacing(1),marginBottom:e.spacing(1)},[`& + .${Di.inset}`]:{marginLeft:52},[`& .${$n.root}`]:{marginTop:0,marginBottom:0},[`& .${$n.inset}`]:{paddingLeft:36},[`& .${$i.root}`]:{minWidth:36},variants:[{props:({ownerState:n})=>!n.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:n})=>n.divider,style:{borderBottom:`1px solid ${(e.vars||e).palette.divider}`,backgroundClip:"padding-box"}},{props:({ownerState:n})=>!n.dense,style:{[e.breakpoints.up("sm")]:{minHeight:"auto"}}},{props:({ownerState:n})=>n.dense,style:{minHeight:32,paddingTop:4,paddingBottom:4,...e.typography.body2,[`& .${$i.root} svg`]:{fontSize:"1.25rem"}}}]}))),et=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiMenuItem"}),{autoFocus:i=!1,component:l="li",dense:a=!1,divider:u=!1,disableGutters:d=!1,focusVisibleClassName:h,role:y="menuitem",tabIndex:b,className:x,...v}=o,k=je.useContext(c.ListContext),C=je.useMemo(()=>({dense:a||k.dense||!1,disableGutters:d}),[k.dense,a,d]),S=je.useRef(null);c.useEnhancedEffect(()=>{i&&S.current&&S.current.focus()},[i]);const T={...o,dense:C.dense,divider:u,disableGutters:d},O=oh(o),M=c.useForkRef(S,r);let E;return o.disabled||(E=b!==void 0?b:-1),t.jsx(c.ListContext.Provider,{value:C,children:t.jsx(ih,{ref:M,role:y,tabIndex:E,component:l,focusVisibleClassName:c.clsx(O.focusVisible,h),className:c.clsx(O.root,x),...v,ownerState:T,classes:O})})}),Gt={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},{label:"Database Metadata",name:"dbmeta",type:"text",required:!1,selectOptions:[{label:"No",value:"false"},{label:"Yes",value:"true"}]}],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}],sqlserver:[{label:"Server",name:"server",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!1},{label:"Database",name:"database",type:"text",required:!0},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!0},{label:"Encrypt",name:"encrypt",type:"text",required:!1,selectOptions:[{label:"Yes",value:"true"},{label:"No",value:"false"}]},{label:"Trust server certificate",name:"trustServerCertificate",type:"text",required:!1,selectOptions:[{label:"No",value:"false"},{label:"Yes",value:"true"}]},{label:"Host name in certificate",name:"hostNameInCertificate",type:"text",required:!1},{label:"Instance name",name:"instanceName",type:"text",required:!1}],duckdb:[],motherduck:[{label:"Access Token",name:"accessToken",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1}],ducklake:[],publisher:[]},pr={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",trino:"trinoConnection",databricks:"databricksConnection",mysql:"mysqlConnection",sqlserver:"sqlserverConnection",duckdb:"duckdbConnection",motherduck:"motherduckConnection",ducklake:"ducklakeConnection",publisher:"publisherConnection"},ah={bigquery:{dbmeta:"boolean"},sqlserver:{port:"integer",encrypt:"boolean",trustServerCertificate:"boolean"}},lh={sqlserver:["hostNameInCertificate","instanceName"]};function Ja(e,n){const r=ah[e],o=lh[e];if(!r&&!o)return n;const i={...n};for(const l of o??[])i[l]===""&&delete i[l];for(const[l,a]of Object.entries(r??{})){const u=n[l];if(u!==void 0){if(u===""){delete i[l];continue}if(a==="integer"){const d=Number(u);Number.isInteger(d)&&(i[l]=d)}else(u==="true"||u==="false")&&(i[l]=u==="true")}}return i}const el=Object.values(q.ConnectionTypeEnum).filter(e=>e!==q.ConnectionTypeEnum.Publisher),Gs={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},Sr=[{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"}}],kr=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],ch=[{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 Jr(e){return e==="postgres"||e==="bigquery"||e==="snowflake"?Gt[e]||[]:e==="s3"?Sr:e==="gcs"?kr:e==="azure"?ch:[]}function uh({onSubmit:e,isSubmitting:n}){const[r,o]=j.useState(!1),[i,l]=j.useState("postgres"),[a,u]=j.useState([]),[d,h]=j.useState("postgres"),[y,b]=j.useState("s3"),[x,v]=j.useState("config"),k=()=>{o(!0)},C=()=>{o(!1),u([]),l("postgres"),h("postgres"),b("s3"),v("config")},S=async E=>{E.preventDefault();const R=new FormData(E.currentTarget),P=R.get("name")?.toString(),F=R.get("type")?.toString(),B=Gt[F];if(!P)throw new Error("Name is required");if(!F)throw new Error("Type is required");let D;if(F==="ducklake"){const _={};if(d==="postgres"){const W=Gt.postgres,Z={};if(W.forEach(ne=>{const J=R.get(`ducklake_pg_${ne.name}`)?.toString();J&&(Z[ne.name]=J)}),Object.keys(Z).length===0)throw new Error("DuckLake requires catalog connection");_.postgresConnection=Z}const V=R.get("ducklake_bucketUrl")?.toString();if(!V)throw new Error("DuckLake requires a bucket URL");const $={bucketUrl:V};if(y==="s3"){const W={};if(Sr.forEach(Z=>{const ne=R.get(`ducklake_s3_${Z.name}`)?.toString();ne&&(W[Z.name]=ne)}),W.provider==="credential_chain")delete W.accessKeyId,delete W.secretAccessKey,delete W.sessionToken;else{if(delete W.chain,!W.accessKeyId)throw new Error("S3 Access Key ID is required");if(!W.secretAccessKey)throw new Error("S3 Secret Access Key is required")}Object.keys(W).length>0&&($.s3Connection=W)}else if(y==="gcs"){const W={};if(kr.forEach(Z=>{const ne=R.get(`ducklake_gcs_${Z.name}`)?.toString();ne&&(W[Z.name]=ne)}),!W.keyId)throw new Error("GCS Key ID is required");if(!W.secret)throw new Error("GCS Secret is required");Object.keys(W).length>0&&($.gcsConnection=W)}D={name:P,type:F,ducklakeConnection:{catalog:_,storage:$}}}else if(F==="duckdb"){if(a.length===0)throw new Error("DuckDB connection must have at least one attached database");const _=a.map((V,$)=>{const W=V.dbType,Z=R.get(`attachedDb_${$}_name`)?.toString();if(!Z)throw new Error(`Attached database at index ${$} must have a name`);const ne={name:Z,type:W},J=Jr(W);if(J&&J.length>0){const H={};if(J.forEach(re=>{const z=R.get(`attachedDb_${$}_${re.name}`)?.toString();z&&(H[re.name]=z)}),W==="s3"){if(H.provider==="credential_chain")delete H.accessKeyId,delete H.secretAccessKey,delete H.sessionToken;else if(delete H.chain,!H.accessKeyId||!H.secretAccessKey)throw new Error(`Attached database "${Z}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const Q=Gs[W];Q&&(ne[Q]=H)}return ne});D={name:P,type:F,duckdbConnection:{attachedDatabases:_}}}else{const _={};if(B.forEach(V=>{const $=R.get(V.name)?.toString();$&&(_[V.name]=$)}),F==="postgres"){if(!!!_.connectionString?.trim()){const $=["host","port","databaseName","userName","password"];for(const W of $)if(!_[W])throw new Error(`${B.find(Z=>Z.name===W)?.label||W} is required`)}}else if(F==="bigquery"){if(!_.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if(F==="snowflake"){if(!_.account)throw new Error("Account is required");if(!_.username)throw new Error("Username is required");if(!_.warehouse)throw new Error("Warehouse is required");if(!_.password&&!_.privateKey)throw new Error("Either password or private key is required")}else if(F==="trino"){if(!_.server)throw new Error("Server is required");if(!_.user)throw new Error("User is required");if(_.server.trim().startsWith("https://")&&!_.password&&!_.peakaKey)throw new Error("Password is required for HTTPS connections (or use Peaka Key)")}else if(F==="mysql"){const V=["host","port","database","user","password"];for(const $ of V)if(!_[$])throw new Error(`${B.find(W=>W.name===$)?.label||$} is required`)}else if(F==="sqlserver"){const V=["server","database","user","password"];if(!_.instanceName&&!_.port)throw new Error("Port is required unless an instance name is given");for(const $ of V)if(!_[$])throw new Error(`${B.find(W=>W.name===$)?.label||$} is required`)}else if(F==="motherduck"){if(!_.accessToken)throw new Error("Access Token is required")}else if(F==="databricks"){if(!_.host)throw new Error("Host is required");if(!_.path)throw new Error("HTTP Path is required");const V=_.oauthClientId&&_.oauthClientSecret;if(!_.token&&!V)throw new Error("Either Access Token or OAuth Client ID + Secret is required")}D={name:P,type:F,[pr[F]]:Ja(F,_)}}await e(D),C()},T=()=>{u([...a,{name:"",dbType:"postgres"}])},O=E=>{u(a.filter((R,P)=>P!==E))},M=(E,R)=>{const P=[...a];P[E]={...P[E],dbType:R},u(P)};return t.jsxs(j.Fragment,{children:[t.jsx(c.AddButton,{label:"Connection",onClick:k}),t.jsx(c.AppDialog,{open:r,onClose:C,title:"New connection",description:"Add a connection so packages in this environment can query your database with Malloy.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:n,onClick:C,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"connection-form",variant:"contained",loading:n,children:"Create connection"})]}),children:t.jsx("form",{onSubmit:S,id:"connection-form",children:t.jsxs(ss,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small"}),t.jsx(c.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:i,select:!0,onChange:E=>l(E.target.value),children:el.map(E=>t.jsx(et,{value:E,children:E},E))}),i==="ducklake"?t.jsxs(Ge,{sx:{mt:2},children:[t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),t.jsx(c.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:d,select:!0,onChange:E=>h(E.target.value),children:t.jsx(et,{value:"postgres",children:"PostgreSQL"})}),d==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(E=>t.jsx(c.TextField,{id:`ducklake_pg_${E.name}`,name:`ducklake_pg_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small"},`pg_${E.name}`))})]}),t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),t.jsxs(c.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:y,select:!0,onChange:E=>b(E.target.value),children:[t.jsx(et,{value:"s3",children:"S3"}),t.jsx(et,{value:"gcs",children:"GCS"})]}),t.jsx(c.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:y==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small"}),y==="s3"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),Sr.filter(E=>E.visibleWhen?x===E.visibleWhen.value:!0).map(E=>t.jsx(c.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?x:void 0,onChange:E.name==="provider"?R=>v(R.target.value):void 0,placeholder:E.name==="region"?"us-east-1":void 0,children:E.selectOptions?.map(R=>t.jsx(et,{value:R.value,children:R.label},R.value))},`s3_${E.name}`))]}),y==="gcs"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),kr.map(E=>t.jsx(c.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}`))]})]})]}):i==="duckdb"?t.jsxs(Ge,{sx:{mt:2},children:[t.jsxs(Ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsx(c.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),t.jsx(c.SecondaryButton,{label:"Database",icon:t.jsx(c.AddIcon,{}),onClick:T,ariaLabel:"Add database"})]}),a.length===0&&t.jsx(c.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),a.map((E,R)=>{const P=Jr(E.dbType);return t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(c.Typography,{variant:"subtitle2",children:["Database ",R+1]}),t.jsx(c.IconButton,{onClick:()=>O(R),size:"small",color:"error",children:t.jsx(Xa,{fontSize:"small"})})]}),t.jsx(c.TextField,{required:!0,id:`attachedDb_${R}_name`,name:`attachedDb_${R}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:E.name}),t.jsx(c.TextField,{id:`attachedDb_${R}_type`,name:`attachedDb_${R}_type`,label:"Database Type",fullWidth:!0,size:"small",value:E.dbType,select:!0,onChange:F=>M(R,F.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map(F=>t.jsx(et,{value:F,children:F},F))}),P.filter(F=>F.visibleWhen?(E[F.visibleWhen.field]||P.find(D=>D.name===F.visibleWhen?.field)?.selectOptions?.[0]?.value)===F.visibleWhen.value:!0).map(F=>t.jsx(c.TextField,{id:`attachedDb_${R}_${F.name}`,name:`attachedDb_${R}_${F.name}`,label:F.label,type:F.selectOptions?void 0:F.type,fullWidth:!0,size:"small",required:F.required,select:!!F.selectOptions,defaultValue:F.selectOptions?.[0]?.value,onChange:F.selectOptions?B=>{const D=[...a];D[R]={...D[R],[F.name]:B.target.value},u(D)}:void 0,children:F.selectOptions?.map(B=>t.jsx(et,{value:B.value,children:B.label},B.value))},F.name))]},R)})]}):Gt[i].map(E=>t.jsx(c.TextField,{id:E.name,name:E.name,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required,select:!!E.selectOptions,defaultValue:E.selectOptions?E.selectOptions[0]?.value:void 0,children:E.selectOptions?.map(R=>t.jsx(et,{value:R.value,children:R.label},R.value))},E.name))]})})})]})}function dh({connection:e,onCloseDialog:n,isMutating:r,onDelete:o}){const[i,l]=j.useState(!1),a=()=>{l(!0)},u=()=>{l(!1),n()};return t.jsxs(j.Fragment,{children:[t.jsxs(et,{"aria-label":`Delete connection ${e?.name??""}`.trim(),onClick:d=>{d.stopPropagation(),a()},sx:{color:"error.main"},children:[t.jsx(io,{sx:{color:"inherit"},children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(ao,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:i,onClose:u,title:"Delete connection",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:u,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>o(),loading:r,children:"Delete connection"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:e.name}),"? Packages that query through it stop working, and this cannot be undone."]})})]})}const Fi=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function Ai(e){const n=e.duckdbConnection?.attachedDatabases;return!n||n.length===0?[]:n.map(r=>({name:r.name||"",dbType:r.type||"postgres"}))}function Ri(e){const n=e.ducklakeConnection;return n&&n.storage?.gcsConnection?"gcs":"s3"}function hh({connection:e,onSubmit:n,isSubmitting:r,onCloseDialog:o}){const[i,l]=j.useState(!1),[a,u]=j.useState(e.type),d=j.useMemo(()=>new Set(e.withheldFields??[]),[e.withheldFields]),[h,y]=j.useState(()=>Ai(e)),[b,x]=j.useState("postgres"),[v,k]=j.useState(()=>Ri(e)),[C,S]=j.useState(()=>e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),T=()=>{y(Ai(e)),u(e.type),S(e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),x("postgres"),k(Ri(e)),l(!0)},O=()=>{l(!1),o?.()},M=async D=>{D.preventDefault();const _=new FormData(D.currentTarget),V=_.get("name")?.toString(),$=_.get("type")?.toString(),W=Gt[$];if(!V)throw new Error("Name is required");if(!$)throw new Error("Type is required");let Z;if($==="ducklake"){const ne={};if(b==="postgres"){const Q=Gt.postgres,re={};if(Q.forEach(z=>{const oe=_.get(`ducklake_pg_${z.name}`)?.toString();oe&&(re[z.name]=oe)}),Object.keys(re).length===0)throw new Error("DuckLake requires catalog connection");ne.postgresConnection=re}const J=_.get("ducklake_bucketUrl")?.toString();if(!J)throw new Error("DuckLake requires a bucket URL");const H={bucketUrl:J};if(v==="s3"){const Q={};Sr.forEach(z=>{const oe=_.get(`ducklake_s3_${z.name}`)?.toString();oe&&(Q[z.name]=oe)});const re=e.ducklakeConnection?.storage?.s3Connection;if(re&&(!Q.provider&&re.provider&&(Q.provider=re.provider),!Q.chain&&re.chain&&(Q.chain=re.chain),!Q.accessKeyId&&re.accessKeyId&&(Q.accessKeyId=re.accessKeyId)),Q.provider==="credential_chain")delete Q.accessKeyId,delete Q.secretAccessKey,delete Q.sessionToken;else if(delete Q.chain,!Q.accessKeyId)throw new Error("S3 Access Key ID is required");Object.keys(Q).length>0&&(H.s3Connection=Q)}else if(v==="gcs"){const Q={};kr.forEach(z=>{const oe=_.get(`ducklake_gcs_${z.name}`)?.toString();oe&&(Q[z.name]=oe)});const re=e.ducklakeConnection?.storage?.gcsConnection;if(re&&!Q.keyId&&re.keyId&&(Q.keyId=re.keyId),!Q.keyId)throw new Error("GCS Key ID is required");Object.keys(Q).length>0&&(H.gcsConnection=Q)}Z={name:V,type:$,ducklakeConnection:{catalog:ne,storage:H}}}else if($==="duckdb"){if(h.length===0)throw new Error("DuckDB connection must have at least one attached database");const ne=h.map((J,H)=>{const Q=J.dbType,re=_.get(`attachedDb_${H}_name`)?.toString();if(!re)throw new Error(`Attached database at index ${H} must have a name`);const z={name:re,type:Q},oe=Jr(Q);if(oe&&oe.length>0){const se={};if(oe.forEach(De=>{const de=_.get(`attachedDb_${H}_${De.name}`)?.toString();de&&(se[De.name]=de)}),Q==="s3"){if(se.provider==="credential_chain")delete se.accessKeyId,delete se.secretAccessKey,delete se.sessionToken;else if(delete se.chain,!se.accessKeyId||!se.secretAccessKey)throw new Error(`Attached database "${re}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const ie=Gs[Q];ie&&(z[ie]=se)}return z});Z={name:V,type:$,duckdbConnection:{attachedDatabases:ne}}}else{const ne=e[pr[$]]||{},J={};if(W.forEach(H=>{const Q=_.get(H.name)?.toString(),re=ne[H.name];Q?J[H.name]=Q:Fi.has(H.name)||(Q!==void 0?J[H.name]=Q:re&&(J[H.name]=re))}),$==="postgres"){const H=["host","port","databaseName","userName"],Q=d.has("postgresConnection.connectionString");if(!(!!J.connectionString?.trim()||Q)){const z=H;for(const oe of z)if(!J[oe])throw new Error(`${W.find(se=>se.name===oe)?.label||oe} is required`)}}else if($==="snowflake"){if(!J.account)throw new Error("Account is required");if(!J.username)throw new Error("Username is required");if(!J.warehouse)throw new Error("Warehouse is required")}else if($==="trino"){if(!J.server)throw new Error("Server is required");if(!J.user)throw new Error("User is required")}else if($==="mysql"){const H=["host","port","database","user"];for(const Q of H)if(!J[Q])throw new Error(`${W.find(re=>re.name===Q)?.label||Q} is required`)}else if($==="sqlserver"){const H=["server","database","user"];if(!J.instanceName&&!J.port)throw new Error("Port is required unless an instance name is given");for(const Q of H)if(!J[Q])throw new Error(`${W.find(re=>re.name===Q)?.label||Q} is required`)}else if($==="databricks"){if(!J.host)throw new Error("Host is required");if(!J.path)throw new Error("HTTP Path is required")}Z={name:V,type:$,[pr[$]]:Ja($,J)}}await n(Z),O()},E=()=>{y([...h,{name:"",dbType:"postgres"}])},R=D=>{y(h.filter((_,V)=>V!==D))},P=(D,_)=>{const V=[...h];V[D]={...V[D],dbType:_},y(V)},F=(D,_)=>{const V=e.duckdbConnection?.attachedDatabases;if(!V||!V[D])return"";const $=V[D],W=Gs[$.type||""];return W&&$[W]?$[W][_]??"":""},B=D=>{const _=e.ducklakeConnection;if(!_)return"";if(D.startsWith("pg_")){const V=D.replace("pg_","");return _.catalog?.postgresConnection?.[V]??""}if(D==="bucketUrl")return _.storage?.bucketUrl??"";if(D.startsWith("s3_")){const V=D.replace("s3_","");return _.storage?.s3Connection?.[V]??""}if(D.startsWith("gcs_")){const V=D.replace("gcs_","");return _.storage?.gcsConnection?.[V]??""}return""};return t.jsxs(j.Fragment,{children:[t.jsxs(et,{"aria-label":`Edit connection ${e?.name??""}`.trim(),onClick:D=>{D.preventDefault(),D.stopPropagation(),T()},children:[t.jsx(io,{children:t.jsx(Pt.Edit,{fontSize:"small"})}),t.jsx(ao,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:i,onClose:O,title:"Edit connection",description:"Change how packages in this environment reach your database.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:r,onClick:O,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"connection-form",variant:"contained",loading:r,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:M,id:"connection-form",children:t.jsxs(ss,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",defaultValue:e.name}),t.jsx(c.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:a,select:!0,onChange:D=>u(D.target.value),children:el.map(D=>t.jsx(et,{value:D,children:D},D))}),a==="ducklake"?t.jsxs(Ge,{sx:{mt:2},children:[t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),t.jsx(c.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:b,select:!0,onChange:D=>x(D.target.value),children:t.jsx(et,{value:"postgres",children:"PostgreSQL"})}),b==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(D=>t.jsx(c.TextField,{id:`ducklake_pg_${D.name}`,name:`ducklake_pg_${D.name}`,label:D.label,type:D.type,fullWidth:!0,size:"small",defaultValue:B(`pg_${D.name}`)},`pg_${D.name}`))})]}),t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),t.jsxs(c.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:v,select:!0,onChange:D=>k(D.target.value),children:[t.jsx(et,{value:"s3",children:"S3"}),t.jsx(et,{value:"gcs",children:"GCS"})]}),t.jsx(c.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:v==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small",defaultValue:B("bucketUrl")}),v==="s3"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),Sr.filter(D=>D.visibleWhen?C===D.visibleWhen.value:!0).map(D=>t.jsx(c.TextField,{id:`ducklake_s3_${D.name}`,name:`ducklake_s3_${D.name}`,label:D.label,type:D.selectOptions?void 0:D.type,fullWidth:!0,size:"small",required:D.required&&D.name!=="secretAccessKey",select:!!D.selectOptions,defaultValue:D.selectOptions?C:B(`s3_${D.name}`),onChange:D.name==="provider"?_=>S(_.target.value):void 0,placeholder:D.name==="region"?"us-east-1":D.name==="secretAccessKey"&&d.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:D.selectOptions?.map(_=>t.jsx(et,{value:_.value,children:_.label},_.value))},`s3_${D.name}`))]}),v==="gcs"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),kr.map(D=>t.jsx(c.TextField,{id:`ducklake_gcs_${D.name}`,name:`ducklake_gcs_${D.name}`,label:D.label,type:D.type,fullWidth:!0,size:"small",required:D.required&&D.name!=="secret",defaultValue:B(`gcs_${D.name}`),placeholder:D.name==="secret"&&d.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${D.name}`))]})]})]}):a==="duckdb"?t.jsxs(Ge,{sx:{mt:2},children:[t.jsxs(Ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsx(c.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),t.jsx(c.SecondaryButton,{label:"Database",icon:t.jsx(c.AddIcon,{}),onClick:E,ariaLabel:"Add database"})]}),h.length===0&&t.jsx(c.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((D,_)=>{const V=Jr(D.dbType);return t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(c.Typography,{variant:"subtitle2",children:["Database ",_+1]}),t.jsx(c.IconButton,{"aria-label":`Remove attached database ${_+1}`,onClick:()=>R(_),size:"small",color:"error",children:t.jsx(Xa,{fontSize:"small"})})]}),t.jsx(c.TextField,{required:!0,id:`attachedDb_${_}_name`,name:`attachedDb_${_}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:D.name}),t.jsx(c.TextField,{id:`attachedDb_${_}_type`,name:`attachedDb_${_}_type`,label:"Database Type",fullWidth:!0,size:"small",value:D.dbType,select:!0,onChange:$=>P(_,$.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map($=>t.jsx(et,{value:$,children:$},$))}),V.filter($=>$.visibleWhen?(D[$.visibleWhen.field]||F(_,$.visibleWhen.field)||V.find(Z=>Z.name===$.visibleWhen?.field)?.selectOptions?.[0]?.value)===$.visibleWhen.value:!0).map($=>t.jsx(c.TextField,{id:`attachedDb_${_}_${$.name}`,name:`attachedDb_${_}_${$.name}`,label:$.label,type:$.selectOptions?void 0:$.type,fullWidth:!0,size:"small",required:$.required,select:!!$.selectOptions,defaultValue:F(_,$.name)||$.selectOptions?.[0]?.value,onChange:$.selectOptions?W=>{const Z=[...h];Z[_]={...Z[_],[$.name]:W.target.value},y(Z)}:void 0,children:$.selectOptions?.map(W=>t.jsx(et,{value:W.value,children:W.label},W.value))},$.name))]},_)})]}):Gt[a].map(D=>{const _=e?.[pr[a]??""]?.[D.name??""]??"",V=D.type==="password"||Fi.has(D.name),$=d.has(`${pr[a]??""}.${D.name}`),W=D.selectOptions?_===""||_===void 0?D.selectOptions[0]?.value:String(_):void 0;return t.jsx(c.TextField,{id:D.name,name:D.name,label:D.label,type:D.type,fullWidth:!0,size:"small",required:D.required&&!V&&!_,select:!!D.selectOptions,defaultValue:D.selectOptions?W:_,placeholder:$?"Leave empty to keep existing":void 0,helperText:V?$?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0,children:D.selectOptions?.map(Z=>t.jsx(et,{value:Z.value,children:Z.label},Z.value))},D.name)})]})})})]})}function Li(e,n){return!e||e.type!=="duckdb"?!1:(e.duckdbConnection?.attachedDatabases||[]).some(o=>o.type==="azure"&&o.name===n)}function fh(e){return e.startsWith("gs://")||e.startsWith("s3://")||e.startsWith("https://")||e.startsWith("abfss://")||e.startsWith("az://")}function tl({connectionName:e,resourceUri:n,schema:r,connection:o}){const{apiClients:i}=q.useServer(),{environmentName:l}=c.parseResourceUri(n),[a,u]=j.useState(null),[d,h]=j.useState(r||null),[y,b]=j.useState(!1),{data:x,isError:v,isLoading:k,error:C}=c.useQueryWithApiError({queryKey:["schemas",l,e],queryFn:()=>i.connections.listSchemas(l,e)}),S=x?.data||[];return t.jsxs(p.Grid,{container:!0,spacing:1,children:[!r&&t.jsx(p.Grid,{size:{xs:12,md:4},children:t.jsxs(p.Paper,{sx:{p:1,m:0},children:[t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:0},children:[t.jsx(p.Typography,{variant:"overline",fontWeight:"bold",children:"Table Paths"}),t.jsx(p.FormControlLabel,{control:t.jsx(p.Switch,{checked:y,onChange:T=>b(T.target.checked)}),label:"Hidden Schemas"})]}),t.jsx(p.Divider,{sx:{mt:"2px"}}),t.jsxs(p.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[k&&t.jsx(c.Loading,{text:"Loading schemas..."}),v&&t.jsx(c.ApiErrorDisplay,{error:C,context:`${l} > ${e} > Schemas`}),!k&&!v&&S.length===0&&t.jsx(p.Typography,{variant:"body2",children:"No Schemas"}),!k&&!v&&S.length>0&&t.jsx(p.List,{dense:!0,disablePadding:!0,children:S.map(T=>{const O=T.name;if(T.isHidden&&!y)return null;const E=d===O;return t.jsx(p.ListItemButton,{selected:E,onClick:()=>{h(O),u(null)},children:t.jsx(p.ListItemText,{primary:O})},O)})})]})]})}),t.jsx(p.Grid,{size:{xs:12,md:r?6:4},children:d&&t.jsx(p.Paper,{sx:{p:1,m:0},children:t.jsx(gh,{connectionName:e,schemaName:d,onTableSelect:T=>{u(T)},resourceUri:n,connection:o})})}),t.jsx(p.Grid,{size:{xs:12,md:r?6:4},children:d&&a&&t.jsx(mh,{environmentName:l,connectionName:e,schemaName:d,tableResource:a})})]})}function mh({environmentName:e,connectionName:n,schemaName:r,tableResource:o}){const{apiClients:i}=q.useServer(),{data:l,isLoading:a,isError:u,error:d}=c.useQueryWithApiError({queryKey:["connectionTableDetail",e,n,r,o],queryFn:()=>i.connections.getTable(e,n,r,o),enabled:!!r&&!!o}),h={resource:l?.data?.resource??o,columns:l?.data?.columns??[]};return t.jsxs(p.Paper,{sx:{p:1,m:0},children:[u&&t.jsx(c.ApiErrorDisplay,{error:d,context:`${e} > ${n} > ${r} > ${o}`}),!u&&t.jsx(ph,{table:h,loading:a})]})}function ph({table:e,loading:n}){return n?t.jsx(c.Loading,{text:"Loading columns..."}):t.jsxs(t.Fragment,{children:[t.jsxs(p.Typography,{variant:"overline",fontWeight:"bold",sx:{display:"block",wordBreak:"break-all"},children:[e.resource.includes("://")||/\.(parquet|csv|json|tsv|ndjson)$/i.test(e.resource)?"File":"Table",": ",e.resource]}),t.jsx(p.Divider,{}),t.jsx(p.Box,{sx:{mt:"10px",maxHeight:"600px",overflowY:"auto"},children:t.jsx(p.TableContainer,{children:t.jsxs(p.Table,{size:"small",sx:{"& .MuiTableCell-root":{padding:"10px"}},children:[t.jsx(p.TableHead,{children:t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:"NAME"}),t.jsx(p.TableCell,{children:"TYPE"})]})}),t.jsx(p.TableBody,{children:e.columns?.sort((r,o)=>r.name.localeCompare(o.name))?.map(r=>t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:r.name}),t.jsx(p.TableCell,{children:r.type})]},r.name))})]})})})]})}function gh({connectionName:e,schemaName:n,onTableSelect:r,resourceUri:o,connection:i}){const{environmentName:l}=c.parseResourceUri(o),{apiClients:a}=q.useServer(),[u,d]=j.useState(""),{data:h,isSuccess:y,isError:b,error:x,isLoading:v}=c.useQueryWithApiError({queryKey:["tablesInSchema",l,e,n],queryFn:()=>a.connections.listTables(l,e,n)}),k=Li(i,n),C=T=>k?T:T.split(".").pop()||T,S=y&&h?.data?h.data.filter(T=>C(T.resource).toLowerCase().includes(u.toLowerCase())).sort((T,O)=>C(T.resource).localeCompare(C(O.resource))):[];return t.jsxs(t.Fragment,{children:[t.jsx(p.Typography,{variant:"overline",fontWeight:"bold",children:fh(n)||Li(i,n)?`Files in ${n}`:`Tables in ${n}`}),t.jsx(p.Divider,{}),t.jsx(p.Box,{sx:{mt:1,mb:1},children:t.jsx(p.TextField,{size:"small",fullWidth:!0,placeholder:"Search tables...",value:u,onChange:T=>d(T.target.value),variant:"outlined"})}),t.jsx(p.Divider,{}),t.jsxs(p.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[v&&t.jsx(c.Loading,{text:"Fetching Tables..."}),b&&t.jsx(c.ApiErrorDisplay,{error:x,context:`${l} > ${e} > ${n}`}),y&&S.length===0&&t.jsx(p.Typography,{variant:"body2",children:"No Tables"}),y&&h?.data&&h.data.length>0&&t.jsx(p.List,{dense:!0,disablePadding:!0,children:S.map(T=>{let O=C(T.resource);return!k&&T.resource.includes("://")&&(O=T.resource.split("/").pop()||T.resource),t.jsx(p.ListItemButton,{onClick:()=>r(T.resource),children:t.jsx(p.ListItemText,{primary:O,secondary:T.columns.length>0?`${T.columns.length} columns`:void 0})},T.resource)})})]})]})}const yh={bigquery:"BigQuery",snowflake:"Snowflake",postgres:"PostgreSQL",mysql:"MySQL",sqlserver:"SQL Server",trino:"Trino",databricks:"Databricks",duckdb:"DuckDB",ducklake:"DuckLake",s3:"S3",gcs:"GCS",azure:"Azure"};function xh(e){return e?yh[e]??e:""}function vh({resourceUri:e}){const{apiClients:n,mutable:r}=q.useServer(),o=mt.useQueryClient(),{environmentName:i}=c.parseResourceUri(e),[l,a]=j.useState(""),[u,d]=j.useState(null),h=c.encodeResourceUri({environmentName:i,connectionName:u}),{data:y,isSuccess:b,isError:x,error:v}=c.useQueryWithApiError({queryKey:["connections",i],queryFn:()=>n.connections.listConnections(i)}),k=c.useMutationWithApiError({mutationFn:Ht("connection","create",M=>n.environments.updateEnvironment(i,{name:i,connections:[...y.data,M]})),onSuccess(){a("Connection added successfully"),o.invalidateQueries({queryKey:["connections",i]})},onError(M){a(M.message)}}),C=c.useMutationWithApiError({mutationFn:Ht("connection","update",M=>n.environments.updateEnvironment(i,{name:i,connections:y.data.map(E=>E.name===M.name?M:E)})),onSuccess(M,E){a(`Connection ${E.name} updated successfully`),o.invalidateQueries({queryKey:["connections",i]})},onError(M){a(M.message)}}),S=c.useMutationWithApiError({mutationFn:Ht("connection","delete",M=>{if(!M.name)throw new Error("Cannot delete a connection with no name");return n.connections.deleteConnection(i,M.name)}),onSuccess(M,E){a(`Connection ${E.name} deleted successfully`),o.invalidateQueries({queryKey:["connections",i]})},onError(M){a(M.message)}}),T=b?[...y.data].sort((M,E)=>(M.name??"").localeCompare(E.name??"")):[],O=k.isPending||C.isPending||S.isPending;return t.jsxs(Nt,{title:"Connections",...b?{count:T.length}:{},description:"Database connections available to packages in this environment",...r&&b?{action:t.jsx(uh,{onSubmit:M=>k.mutateAsync(M),isSubmitting:k.isPending})}:{},children:[!b&&!x&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"Fetching Connections..."}),x&&t.jsx(c.ApiErrorDisplay,{error:v,context:`${i} > Connections`}),b&&T.length===0&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),b&&T.length>0&&t.jsx(p.Stack,{children:T.map(M=>t.jsx(bh,{connection:M,mutable:r,isMutating:O,onOpenExplorer:()=>d(M.name??null),onEdit:E=>C.mutateAsync(E),onDelete:E=>S.mutateAsync(E)},M.name))}),t.jsx(p.Snackbar,{open:l!=="",autoHideDuration:6e3,onClose:()=>a(""),message:l}),t.jsx(c.AppDialog,{open:u!==null,onClose:()=>d(null),maxWidth:"lg",title:`Connection explorer: ${u??""}`,showClose:!0,children:u&&t.jsx(tl,{resourceUri:h,connectionName:u,connection:y?.data?.find(M=>M.name===u)})})]})}function bh({connection:e,mutable:n,isMutating:r,onOpenExplorer:o,onEdit:i,onDelete:l}){const[a,u]=j.useState(null),d=!!a,h=b=>{b.stopPropagation(),u(b.currentTarget)},y=()=>u(null);return t.jsx(rs,{icon:t.jsx(Yd,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.connection,label:e.name??"",ariaLabel:e.name??"",description:xh(e.type),onClick:o,...n?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(p.IconButton,{size:"small",onClick:h,"aria-label":`Connection actions for ${e.name??""}`.trim(),children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(p.Menu,{anchorEl:a,open:d,onClose:y,onClick:b=>b.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[t.jsx(hh,{connection:e,onSubmit:i,isSubmitting:r,onCloseDialog:y}),t.jsx(dh,{connection:e,onCloseDialog:y,isMutating:r,onDelete:()=>l(e)})]})]})}:{}})}const wh=c.createSvgIcon([t.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"),t.jsx("path",{d:"M9 12h6v2H9z"},"1")]);function Sh({resourceUri:e,onCloseDialog:n}){const[r,o]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{o(!0)},a=()=>{o(!1),n()},{environmentName:u,packageName:d}=c.parseResourceUri(e),h=Nn({mutationFn:()=>i.packages.deletePackage(u,d),success:"Package deleted",invalidates:[["packages",u]],closeDialog:a,resource:"package",action:"delete"});return t.jsxs(j.Fragment,{children:[t.jsxs(p.MenuItem,{onClick:l,children:[t.jsx(p.ListItemIcon,{children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:r,onClose:a,title:"Delete package",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:a,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>h.mutate(),loading:h.isPending,children:"Delete package"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:d}),"? The package stops being served and this cannot be undone."]})}),h.notice]})}function kh({package:e,resourceUri:n,onCloseDialog:r}){const[o,i]=j.useState(!1),{apiClients:l}=q.useServer(),a=()=>{i(!0)},u=()=>{i(!1),r()},{packageName:d,environmentName:h}=c.parseResourceUri(n),y=Nn({mutationFn(x){return l.packages.updatePackage(h,d,{name:d,description:x.description})},success:"Package updated",invalidates:[["packages",h]],closeDialog:u,resource:"package",action:"update"}),b=x=>{x.preventDefault();const k=new FormData(x.currentTarget).get("description")?.toString();y.mutate({description:k})};return t.jsxs(j.Fragment,{children:[t.jsxs(p.MenuItem,{onClick:a,children:[t.jsx(p.ListItemIcon,{children:t.jsx(Pt.Edit,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:o,onClose:u,title:"Edit package",description:`What ${e.name} is, for the people who open it.`,actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:y.isPending,onClick:u,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"package-form",variant:"contained",loading:y.isPending,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:b,id:"package-form",children:t.jsxs(p.Stack,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:e.name,InputLabelProps:{shrink:!0}}),t.jsx(c.TextField,{id:"description",name:"description",label:"Description",multiline:!0,fullWidth:!0,rows:4,size:"small",defaultValue:e.description,InputLabelProps:{shrink:!0}})]})})}),y.notice]})}function nl({onSelectPackage:e,resourceUri:n}){const{apiClients:r}=q.useServer(),{environmentName:o}=c.parseResourceUri(n),{data:i,isSuccess:l,isError:a,error:u}=c.useQueryWithApiError({queryKey:["packages",o],queryFn:()=>r.packages.listPackages(o)});if(a)return t.jsx(c.ApiErrorDisplay,{error:u,context:`${o} > Packages`});if(!l)return t.jsx(c.Loading,{text:"Fetching Packages..."});const d=[...i.data].sort((h,y)=>h.name.localeCompare(y.name));return t.jsx(p.Stack,{children:d.map(h=>{const y=c.encodeResourceUri({environmentName:o,packageName:h.name});return t.jsx(Ch,{pkg:h,packageResourceUri:y,onSelectPackage:e},h.name)})})}function Ch({pkg:e,packageResourceUri:n,onSelectPackage:r}){const{mutable:o}=q.useServer(),i=e.versionId!==void 0||e.latestVersion!==void 0,[l,a]=j.useState(null),u=!!l,d=y=>{y.stopPropagation(),a(y.currentTarget)},h=()=>a(null);return t.jsx(rs,{icon:t.jsx(wh,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.package,label:e.name,ariaLabel:e.name,...e.description?{description:e.description}:{},onClick:y=>r(e.name,y),...o?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(p.IconButton,{size:"small",onClick:d,"aria-label":`Package actions for ${e.name}`,children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(p.Menu,{anchorEl:l,open:u,onClose:h,onClick:y=>y.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[!i&&t.jsx(kh,{package:e,resourceUri:n,onCloseDialog:h}),t.jsx(Sh,{resourceUri:n,onCloseDialog:h})]})]})}:{}})}function jh({onSelectPackage:e,resourceUri:n}){const{apiClients:r,mutable:o}=q.useServer(),{environmentName:i}=c.parseResourceUri(n),l=c.useQueryWithApiError({queryKey:["packages",i],queryFn:()=>r.packages.listPackages(i)});return j.useEffect(()=>{window.scrollTo({top:0,behavior:"auto"})},[]),t.jsxs(p.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsxs(p.Box,{sx:{mb:4},children:[t.jsx(p.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em",mb:.5},children:i}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"Manage packages and database connections in this environment. Open a package to explore its models and notebooks."})]}),t.jsx(Nt,{title:"Packages",...l.isSuccess?{count:l.data.data.length}:{},description:"Published packages available for use in this environment",...o?{action:t.jsx(Gd,{resourceUri:n})}:{},children:t.jsx(nl,{onSelectPackage:e,resourceUri:n})}),t.jsx(vh,{resourceUri:n}),t.jsx($d,{resourceUri:n})]})}function _i({array1:e,array2:n,parser:r=o=>o}){return e&&n&&e.length===n.length&&e.every((o,i)=>r(o)===r(n[i]))}function Ni(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}function Th(e={}){const{ignoreAccents:n=!0,ignoreCase:r=!0,limit:o,matchFrom:i="any",stringify:l,trim:a=!1}=e;return(u,{inputValue:d,getOptionLabel:h})=>{let y=a?d.trim():d;r&&(y=y.toLowerCase()),n&&(y=Ni(y));const b=y?u.filter(x=>{let v=(l||h)(x);return r&&(v=v.toLowerCase()),n&&(v=Ni(v)),i==="start"?v.startsWith(y):v.includes(y)}):u;return typeof o=="number"?b.slice(0,o):b}}const Oh=Th(),Pi=5,Mh=e=>e.current!==null&&e.current.parentElement?.contains(document.activeElement),Eh=[];function zi(e,n,r,o){if(n||e==null||o)return"";const i=r(e);return typeof i=="string"?i:""}function Ih(e){const{unstable_isActiveElementInListbox:n=Mh,unstable_classNamePrefix:r="Mui",autoComplete:o=!1,autoHighlight:i=!1,autoSelect:l=!1,blurOnSelect:a=!1,clearOnBlur:u=!e.freeSolo,clearOnEscape:d=!1,componentName:h="useAutocomplete",defaultValue:y=e.multiple?Eh:null,disableClearable:b=!1,disableCloseOnSelect:x=!1,disabled:v,disabledItemsFocusable:k=!1,disableListWrap:C=!1,filterOptions:S=Oh,filterSelectedOptions:T=!1,freeSolo:O=!1,getOptionDisabled:M,getOptionKey:E,getOptionLabel:R=G=>G.label??G,groupBy:P,handleHomeEndKeys:F=!e.freeSolo,id:B,includeInputInList:D=!1,inputValue:_,isOptionEqualToValue:V=(G,U)=>G===U,multiple:$=!1,onChange:W,onClose:Z,onHighlightChange:ne,onInputChange:J,onOpen:H,open:Q,openOnFocus:re=!1,options:z,readOnly:oe=!1,renderValue:se,selectOnFocus:ie=!e.freeSolo,value:De}=e,de=c.useId(B);let ue=R;ue=G=>{const U=R(G);return typeof U!="string"?String(U):U};const be=je.useRef(!1),Me=je.useRef(!0),te=je.useRef(null),K=je.useRef(null),[he,we]=je.useState(null),[ge,pe]=je.useState(-1),ye=i?0:-1,Le=je.useRef(ye),st=je.useRef(zi(y??De,$,ue)).current,[ce,Y]=c.useControlled({controlled:De,default:y,name:h}),[ae,Fe]=c.useControlled({controlled:_,default:st,name:h,state:"inputValue"}),[Ve,St]=je.useState(!1),Ee=je.useCallback((G,U,le)=>{if(!($?ce.length<U.length:U!==null)&&!u)return;const ee=zi(U,$,ue,se);ae!==ee&&(Fe(ee),J&&J(G,ee,le))},[ue,ae,$,J,Fe,u,ce,se]),[at,yt]=c.useControlled({controlled:Q,default:!1,name:h,state:"open"}),[xt,Ot]=je.useState(!0),pt=!$&&ce!=null&&ae===ue(ce),Ye=at&&!oe,fe=Ye?S(z.filter(G=>!(T&&($?ce:[ce]).some(U=>U!==null&&V(G,U)))),{inputValue:pt&&xt?"":ae,getOptionLabel:ue}):[],Ke=dd({filteredOptions:fe,value:ce,inputValue:ae});je.useEffect(()=>{const G=ce!==Ke.value;Ve&&!G||O&&!G||Ee(null,ce,"reset")},[ce,Ee,Ve,Ke.value,O]);const ze=at&&fe.length>0&&!oe,lt=c.useEventCallback(G=>{if(G===-1)te.current.focus();else{const U=se?"data-item-index":"data-tag-index";he.querySelector(`[${U}="${G}"]`).focus()}});je.useEffect(()=>{$&&ge>ce.length-1&&(pe(-1),lt(-1))},[ce,$,ge,lt]);function ct(G,U){if(!K.current||G<0||G>=fe.length)return-1;let le=G;for(;;){const ve=K.current.querySelector(`[data-option-index="${le}"]`),ee=k?!1:!ve||ve.disabled||ve.getAttribute("aria-disabled")==="true";if(ve&&ve.hasAttribute("tabindex")&&!ee)return le;if(U==="next"?le=(le+1)%fe.length:le=(le-1+fe.length)%fe.length,le===G)return-1}}const Qe=c.useEventCallback(({event:G,index:U,reason:le})=>{if(Le.current=U,U===-1?te.current.removeAttribute("aria-activedescendant"):te.current.setAttribute("aria-activedescendant",`${de}-option-${U}`),ne&&["mouse","keyboard","touch"].includes(le)&&ne(G,U===-1?null:fe[U],le),!K.current)return;const ve=K.current.querySelector(`[role="option"].${r}-focused`);ve&&(ve.classList.remove(`${r}-focused`),ve.classList.remove(`${r}-focusVisible`));let ee=K.current;if(K.current.getAttribute("role")!=="listbox"&&(ee=K.current.parentElement.querySelector('[role="listbox"]')),!ee)return;if(U===-1){ee.scrollTop=0;return}const qe=K.current.querySelector(`[data-option-index="${U}"]`);if(qe&&(qe.classList.add(`${r}-focused`),le==="keyboard"&&qe.classList.add(`${r}-focusVisible`),ee.scrollHeight>ee.clientHeight&&le!=="mouse"&&le!=="touch")){const Ue=qe,Ct=ee.clientHeight+ee.scrollTop,vn=Ue.offsetTop+Ue.offsetHeight;vn>Ct?ee.scrollTop=vn-ee.clientHeight:Ue.offsetTop-Ue.offsetHeight*(P?1.3:0)<ee.scrollTop&&(ee.scrollTop=Ue.offsetTop-Ue.offsetHeight*(P?1.3:0))}}),me=c.useEventCallback(({event:G,diff:U,direction:le="next",reason:ve})=>{if(!Ye)return;const qe=ct((()=>{const Ue=fe.length-1;if(U==="reset")return ye;if(U==="start")return 0;if(U==="end")return Ue;const Ct=Le.current+U;return Ct<0?Ct===-1&&D?-1:C&&Le.current!==-1||Math.abs(U)>1?0:Ue:Ct>Ue?Ct===Ue+1&&D?-1:C||Math.abs(U)>1?Ue:0:Ct})(),le);if(Qe({index:qe,reason:ve,event:G}),o&&U!=="reset")if(qe===-1)te.current.value=ae;else{const Ue=ue(fe[qe]);te.current.value=Ue,Ue.toLowerCase().indexOf(ae.toLowerCase())===0&&ae.length>0&&te.current.setSelectionRange(ae.length,Ue.length)}}),He=!_i({array1:Ke.filteredOptions,array2:fe,parser:ue}),vt=()=>{const G=(U,le)=>{const ve=U?ue(U):"",ee=le?ue(le):"";return ve===ee};if(Le.current!==-1&&!_i({array1:Ke.filteredOptions,array2:fe,parser:ue})&&Ke.inputValue===ae&&($?ce.length===Ke.value.length&&Ke.value.every((U,le)=>ue(ce[le])===ue(U)):G(Ke.value,ce))){const U=Ke.filteredOptions[Le.current];if(U)return fe.findIndex(le=>ue(le)===ue(U))}return-1},Ce=je.useCallback(()=>{if(!Ye)return;const G=vt();if(G!==-1){Le.current=G;return}const U=$?ce[0]:ce;if(fe.length===0||U==null){me({diff:"reset"});return}if(K.current){if(U!=null){const le=fe[Le.current];if($&&le&&ce.findIndex(ee=>V(le,ee))!==-1)return;const ve=fe.findIndex(ee=>V(ee,U));ve===-1?me({diff:"reset"}):Qe({index:ve});return}if(Le.current>=fe.length-1){Qe({index:fe.length-1});return}Qe({index:Le.current})}},[fe.length,$?!1:ce,T,me,Qe,Ye,ae,$]),Re=c.useEventCallback(G=>{c.setRef(K,G),G&&Ce()});je.useEffect(()=>{He&&Ce()},[Ce,He]);const Ie=G=>{at||(yt(!0),Ot(!0),H&&H(G))},We=(G,U)=>{at&&(yt(!1),Z&&Z(G,U))},dt=(G,U,le,ve)=>{if($){if(ce.length===U.length&&ce.every((ee,qe)=>ee===U[qe]))return}else if(ce===U)return;W&&W(G,U,le,ve),Y(U)},Pe=je.useRef(!1),tt=(G,U,le="selectOption",ve="options")=>{let ee=le,qe=U;if($){qe=Array.isArray(ce)?ce.slice():[];const Ue=qe.findIndex(Ct=>V(U,Ct));Ue===-1?qe.push(U):ve!=="freeSolo"&&(qe.splice(Ue,1),ee="removeOption")}Ee(G,qe,ee),dt(G,qe,ee,{option:U}),!x&&(!G||!G.ctrlKey&&!G.metaKey)&&We(G,ee),(a===!0||a==="touch"&&Pe.current||a==="mouse"&&!Pe.current)&&te.current.blur()};function Mt(G,U){if(G===-1)return-1;let le=G;for(;;){if(U==="next"&&le===ce.length||U==="previous"&&le===-1)return-1;const ve=se?"data-item-index":"data-tag-index",ee=he.querySelector(`[${ve}="${le}"]`);if(!ee||!ee.hasAttribute("tabindex")||ee.disabled||ee.getAttribute("aria-disabled")==="true")le+=U==="next"?1:-1;else return le}}const kt=(G,U)=>{if(!$)return;ae===""&&We(G,"toggleInput");let le=ge;ge===-1?ae===""&&U==="previous"&&(le=ce.length-1):(le+=U==="next"?1:-1,le<0&&(le=0),le===ce.length&&(le=-1)),le=Mt(le,U),pe(le),lt(le)},Ft=G=>{be.current=!0,Fe(""),J&&J(G,"","clear"),dt(G,$?[]:null,"clear")},gn=G=>U=>{if(G.onKeyDown&&G.onKeyDown(U),!U.defaultMuiPrevented&&(ge!==-1&&!["ArrowLeft","ArrowRight"].includes(U.key)&&(pe(-1),lt(-1)),U.which!==229))switch(U.key){case"Home":Ye&&F&&(U.preventDefault(),me({diff:"start",direction:"next",reason:"keyboard",event:U}));break;case"End":Ye&&F&&(U.preventDefault(),me({diff:"end",direction:"previous",reason:"keyboard",event:U}));break;case"PageUp":U.preventDefault(),me({diff:-Pi,direction:"previous",reason:"keyboard",event:U}),Ie(U);break;case"PageDown":U.preventDefault(),me({diff:Pi,direction:"next",reason:"keyboard",event:U}),Ie(U);break;case"ArrowDown":U.preventDefault(),me({diff:1,direction:"next",reason:"keyboard",event:U}),Ie(U);break;case"ArrowUp":U.preventDefault(),me({diff:-1,direction:"previous",reason:"keyboard",event:U}),Ie(U);break;case"ArrowLeft":!$&&se?lt(0):kt(U,"previous");break;case"ArrowRight":!$&&se?lt(-1):kt(U,"next");break;case"Enter":if(Le.current!==-1&&Ye){const le=fe[Le.current],ve=M?M(le):!1;if(U.preventDefault(),ve)return;tt(U,le,"selectOption"),o&&te.current.setSelectionRange(te.current.value.length,te.current.value.length)}else O&&ae!==""&&pt===!1&&($&&U.preventDefault(),tt(U,ae,"createOption","freeSolo"));break;case"Escape":Ye?(U.preventDefault(),U.stopPropagation(),We(U,"escape")):d&&(ae!==""||$&&ce.length>0||se)&&(U.preventDefault(),U.stopPropagation(),Ft(U));break;case"Backspace":if($&&!oe&&ae===""&&ce.length>0){const le=ge===-1?ce.length-1:ge,ve=ce.slice();ve.splice(le,1),dt(U,ve,"removeOption",{option:ce[le]})}!$&&se&&!oe&&(Y(null),lt(-1));break;case"Delete":if($&&!oe&&ae===""&&ce.length>0&&ge!==-1){const le=ge,ve=ce.slice();ve.splice(le,1),dt(U,ve,"removeOption",{option:ce[le]})}!$&&se&&!oe&&(Y(null),lt(-1));break}},Ne=G=>{St(!0),re&&!be.current&&Ie(G)},ut=G=>{if(n(K)){te.current.focus();return}St(!1),Me.current=!0,be.current=!1,l&&Le.current!==-1&&Ye?tt(G,fe[Le.current],"blur"):l&&O&&ae!==""?tt(G,ae,"blur","freeSolo"):u&&Ee(G,ce,"blur"),We(G,"blur")},Kt=G=>{const U=G.target.value;ae!==U&&(Fe(U),Ot(!1),J&&J(G,U,"input")),U===""?!b&&!$&&dt(G,null,"clear"):Ie(G)},yn=G=>{const U=Number(G.currentTarget.getAttribute("data-option-index"));Le.current!==U&&Qe({event:G,index:U,reason:"mouse"})},ht=G=>{Qe({event:G,index:Number(G.currentTarget.getAttribute("data-option-index")),reason:"touch"}),Pe.current=!0},en=G=>{const U=Number(G.currentTarget.getAttribute("data-option-index"));tt(G,fe[U],"selectOption"),Pe.current=!1},xn=G=>U=>{const le=ce.slice();le.splice(G,1),dt(U,le,"removeOption",{option:ce[G]})},Qt=G=>{dt(G,null,"removeOption",{option:ce})},Ze=G=>{at?We(G,"toggleInput"):Ie(G)},Xe=G=>{G.currentTarget.contains(G.target)&&G.target.getAttribute("id")!==de&&G.preventDefault()},At=G=>{G.currentTarget.contains(G.target)&&(te.current.focus(),ie&&Me.current&&te.current.selectionEnd-te.current.selectionStart===0&&te.current.select(),Me.current=!1)},tn=G=>{!v&&(ae===""||!at)&&Ze(G)};let Zt=O&&ae.length>0;Zt=Zt||($?ce.length>0:ce!==null);let nn=fe;return P&&(nn=fe.reduce((G,U,le)=>{const ve=P(U);return G.length>0&&G[G.length-1].group===ve?G[G.length-1].options.push(U):G.push({key:le,index:le,group:ve,options:[U]}),G},[])),v&&Ve&&ut(),{getRootProps:(G={})=>({...G,onKeyDown:gn(G),onMouseDown:Xe,onClick:At}),getInputLabelProps:()=>({id:`${de}-label`,htmlFor:de}),getInputProps:()=>({id:de,value:ae,onBlur:ut,onFocus:Ne,onChange:Kt,onMouseDown:tn,"aria-activedescendant":Ye?"":null,"aria-autocomplete":o?"both":"list","aria-controls":ze?`${de}-listbox`:void 0,"aria-expanded":ze,autoComplete:"off",ref:te,autoCapitalize:"none",spellCheck:"false",role:"combobox",disabled:v}),getClearProps:()=>({tabIndex:-1,type:"button",onClick:Ft}),getItemProps:({index:G=0}={})=>({...$&&{key:G},...se?{"data-item-index":G}:{"data-tag-index":G},tabIndex:-1,...!oe&&{onDelete:$?xn(G):Qt}}),getPopupIndicatorProps:()=>({tabIndex:-1,type:"button",onClick:Ze}),getTagProps:({index:G})=>({key:G,"data-tag-index":G,tabIndex:-1,...!oe&&{onDelete:xn(G)}}),getListboxProps:()=>({role:"listbox",id:`${de}-listbox`,"aria-labelledby":`${de}-label`,ref:Re,onMouseDown:G=>{G.preventDefault()}}),getOptionProps:({index:G,option:U})=>{const le=($?ce:[ce]).some(ee=>ee!=null&&V(U,ee)),ve=M?M(U):!1;return{key:E?.(U)??ue(U),tabIndex:-1,role:"option",id:`${de}-option-${G}`,onMouseMove:yn,onClick:en,onTouchStart:ht,"data-option-index":G,"aria-disabled":ve,"aria-selected":le}},id:de,inputValue:ae,value:ce,dirty:Zt,expanded:Ye&&he,popupOpen:Ye,focused:Ve||ge!==-1,anchorEl:he,setAnchorEl:we,focusedItem:ge,focusedTag:ge,groupedOptions:nn}}function Dh(e){return c.generateUtilityClass("MuiListSubheader",e)}c.generateUtilityClasses("MuiListSubheader",["root","colorPrimary","colorInherit","gutters","inset","sticky"]);const $h=e=>{const{classes:n,color:r,disableGutters:o,inset:i,disableSticky:l}=e,a={root:["root",r!=="default"&&`color${c.capitalize(r)}`,!o&&"gutters",i&&"inset",!l&&"sticky"]};return c.composeClasses(a,Dh,n)},Fh=c.styled("li",{name:"MuiListSubheader",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,r.color!=="default"&&n[`color${c.capitalize(r.color)}`],!r.disableGutters&&n.gutters,r.inset&&n.inset,!r.disableSticky&&n.sticky]}})(c.memoTheme(({theme:e})=>({boxSizing:"border-box",lineHeight:"48px",listStyle:"none",color:(e.vars||e).palette.text.secondary,fontFamily:e.typography.fontFamily,fontWeight:e.typography.fontWeightMedium,fontSize:e.typography.pxToRem(14),variants:[{props:{color:"primary"},style:{color:(e.vars||e).palette.primary.main}},{props:{color:"inherit"},style:{color:"inherit"}},{props:({ownerState:n})=>!n.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:n})=>n.inset,style:{paddingLeft:72}},{props:({ownerState:n})=>!n.disableSticky,style:{position:"sticky",top:0,zIndex:1,backgroundColor:(e.vars||e).palette.background.paper}}]}))),Ys=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiListSubheader"}),{className:i,color:l="default",component:a="li",disableGutters:u=!1,disableSticky:d=!1,inset:h=!1,...y}=o,b={...o,color:l,component:a,disableGutters:u,disableSticky:d,inset:h},x=$h(b);return t.jsx(Fh,{as:a,className:c.clsx(x.root,i),ref:r,ownerState:b,...y})});Ys&&(Ys.muiSkipListHighlight=!0);const Ah=c.createSvgIcon(t.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}));function Rh(e){return c.generateUtilityClass("MuiAutocomplete",e)}const Oe=c.generateUtilityClasses("MuiAutocomplete",["root","expanded","fullWidth","focused","focusVisible","tag","tagSizeSmall","tagSizeMedium","hasPopupIcon","hasClearIcon","inputRoot","input","inputFocused","endAdornment","clearIndicator","popupIndicator","popupIndicatorOpen","popper","popperDisablePortal","paper","listbox","loading","noOptions","option","groupLabel","groupUl"]);var Wi,qi;const Lh=e=>{const{classes:n,disablePortal:r,expanded:o,focused:i,fullWidth:l,hasClearIcon:a,hasPopupIcon:u,inputFocused:d,popupOpen:h,size:y}=e,b={root:["root",o&&"expanded",i&&"focused",l&&"fullWidth",a&&"hasClearIcon",u&&"hasPopupIcon"],inputRoot:["inputRoot"],input:["input",d&&"inputFocused"],tag:["tag",`tagSize${c.capitalize(y)}`],endAdornment:["endAdornment"],clearIndicator:["clearIndicator"],popupIndicator:["popupIndicator",h&&"popupIndicatorOpen"],popper:["popper",r&&"popperDisablePortal"],paper:["paper"],listbox:["listbox"],loading:["loading"],noOptions:["noOptions"],option:["option"],groupLabel:["groupLabel"],groupUl:["groupUl"]};return c.composeClasses(b,Rh,n)},_h=c.styled("div",{name:"MuiAutocomplete",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e,{fullWidth:o,hasClearIcon:i,hasPopupIcon:l,inputFocused:a,size:u}=r;return[{[`& .${Oe.tag}`]:n.tag},{[`& .${Oe.tag}`]:n[`tagSize${c.capitalize(u)}`]},{[`& .${Oe.inputRoot}`]:n.inputRoot},{[`& .${Oe.input}`]:n.input},{[`& .${Oe.input}`]:a&&n.inputFocused},n.root,o&&n.fullWidth,l&&n.hasPopupIcon,i&&n.hasClearIcon]}})({[`&.${Oe.focused} .${Oe.clearIndicator}`]:{visibility:"visible"},"@media (pointer: fine)":{[`&:hover .${Oe.clearIndicator}`]:{visibility:"visible"}},[`& .${Oe.tag}`]:{margin:3,maxWidth:"calc(100% - 6px)"},[`& .${Oe.inputRoot}`]:{[`.${Oe.hasPopupIcon}&, .${Oe.hasClearIcon}&`]:{paddingRight:30},[`.${Oe.hasPopupIcon}.${Oe.hasClearIcon}&`]:{paddingRight:56},[`& .${Oe.input}`]:{width:0,minWidth:30}},[`& .${c.inputClasses.root}`]:{paddingBottom:1,"& .MuiInput-input":{padding:"4px 4px 4px 0px"}},[`& .${c.inputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{[`& .${c.inputClasses.input}`]:{padding:"2px 4px 3px 0"}},[`& .${c.outlinedInputClasses.root}`]:{padding:9,[`.${Oe.hasPopupIcon}&, .${Oe.hasClearIcon}&`]:{paddingRight:39},[`.${Oe.hasPopupIcon}.${Oe.hasClearIcon}&`]:{paddingRight:65},[`& .${Oe.input}`]:{padding:"7.5px 4px 7.5px 5px"},[`& .${Oe.endAdornment}`]:{right:9}},[`& .${c.outlinedInputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{paddingTop:6,paddingBottom:6,paddingLeft:6,[`& .${Oe.input}`]:{padding:"2.5px 4px 2.5px 8px"}},[`& .${c.filledInputClasses.root}`]:{paddingTop:19,paddingLeft:8,[`.${Oe.hasPopupIcon}&, .${Oe.hasClearIcon}&`]:{paddingRight:39},[`.${Oe.hasPopupIcon}.${Oe.hasClearIcon}&`]:{paddingRight:65},[`& .${c.filledInputClasses.input}`]:{padding:"7px 4px"},[`& .${Oe.endAdornment}`]:{right:9}},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{paddingBottom:1,[`& .${c.filledInputClasses.input}`]:{padding:"2.5px 4px"}},[`& .${c.inputBaseClasses.hiddenLabel}`]:{paddingTop:8},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.hiddenLabel}`]:{paddingTop:0,paddingBottom:0,[`& .${Oe.input}`]:{paddingTop:16,paddingBottom:17}},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.hiddenLabel}.${c.inputBaseClasses.sizeSmall}`]:{[`& .${Oe.input}`]:{paddingTop:8,paddingBottom:9}},[`& .${Oe.input}`]:{flexGrow:1,textOverflow:"ellipsis",opacity:0},variants:[{props:{fullWidth:!0},style:{width:"100%"}},{props:{size:"small"},style:{[`& .${Oe.tag}`]:{margin:2,maxWidth:"calc(100% - 4px)"}}},{props:{inputFocused:!0},style:{[`& .${Oe.input}`]:{opacity:1}}},{props:{multiple:!0},style:{[`& .${Oe.inputRoot}`]:{flexWrap:"wrap"}}}]}),Nh=c.styled("div",{name:"MuiAutocomplete",slot:"EndAdornment"})({position:"absolute",right:0,top:"50%",transform:"translate(0, -50%)"}),Ph=c.styled(c.IconButton,{name:"MuiAutocomplete",slot:"ClearIndicator"})({marginRight:-2,padding:4,visibility:"hidden"}),zh=c.styled(c.IconButton,{name:"MuiAutocomplete",slot:"PopupIndicator",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.popupIndicator,r.popupOpen&&n.popupIndicatorOpen]}})({padding:2,marginRight:-2,variants:[{props:{popupOpen:!0},style:{transform:"rotate(180deg)"}}]}),Wh=c.styled(c.Popper,{name:"MuiAutocomplete",slot:"Popper",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${Oe.option}`]:n.option},n.popper,r.disablePortal&&n.popperDisablePortal]}})(c.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.modal,variants:[{props:{disablePortal:!0},style:{position:"absolute"}}]}))),qh=c.styled(c.Paper,{name:"MuiAutocomplete",slot:"Paper"})(c.memoTheme(({theme:e})=>({...e.typography.body1,overflow:"auto"}))),Bh=c.styled("div",{name:"MuiAutocomplete",slot:"Loading"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Vh=c.styled("div",{name:"MuiAutocomplete",slot:"NoOptions"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Hh=c.styled("ul",{name:"MuiAutocomplete",slot:"Listbox"})(c.memoTheme(({theme:e})=>({listStyle:"none",margin:0,padding:"8px 0",maxHeight:"40vh",overflow:"auto",position:"relative",[`& .${Oe.option}`]:{minHeight:48,display:"flex",overflow:"hidden",justifyContent:"flex-start",alignItems:"center",cursor:"pointer",paddingTop:6,boxSizing:"border-box",outline:"0",WebkitTapHighlightColor:"transparent",paddingBottom:6,paddingLeft:16,paddingRight:16,[e.breakpoints.up("sm")]:{minHeight:"auto"},[`&.${Oe.focused}`]:{backgroundColor:(e.vars||e).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},'&[aria-disabled="true"]':{opacity:(e.vars||e).palette.action.disabledOpacity,pointerEvents:"none"},[`&.${Oe.focusVisible}`]:{backgroundColor:(e.vars||e).palette.action.focus},'&[aria-selected="true"]':{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity),[`&.${Oe.focused}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:(e.vars||e).palette.action.selected}},[`&.${Oe.focusVisible}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.focusOpacity}`)}}}}))),Uh=c.styled(Ys,{name:"MuiAutocomplete",slot:"GroupLabel"})(c.memoTheme(({theme:e})=>({backgroundColor:(e.vars||e).palette.background.paper,top:-8}))),Gh=c.styled("ul",{name:"MuiAutocomplete",slot:"GroupUl"})({padding:0,[`& .${Oe.option}`]:{paddingLeft:24}}),Ks=je.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiAutocomplete"}),{autoComplete:i=!1,autoHighlight:l=!1,autoSelect:a=!1,blurOnSelect:u=!1,ChipProps:d,className:h,clearIcon:y=Wi||(Wi=t.jsx(Ah,{fontSize:"small"})),clearOnBlur:b=!o.freeSolo,clearOnEscape:x=!1,clearText:v="Clear",closeText:k="Close",componentsProps:C,defaultValue:S=o.multiple?[]:null,disableClearable:T=!1,disableCloseOnSelect:O=!1,disabled:M=!1,disabledItemsFocusable:E=!1,disableListWrap:R=!1,disablePortal:P=!1,filterOptions:F,filterSelectedOptions:B=!1,forcePopupIcon:D="auto",freeSolo:_=!1,fullWidth:V=!1,getLimitTagsText:$=$e=>`+${$e}`,getOptionDisabled:W,getOptionKey:Z,getOptionLabel:ne,isOptionEqualToValue:J,groupBy:H,handleHomeEndKeys:Q=!o.freeSolo,id:re,includeInputInList:z=!1,inputValue:oe,limitTags:se=-1,ListboxComponent:ie,ListboxProps:De,loading:de=!1,loadingText:ue="Loading…",multiple:be=!1,noOptionsText:Me="No options",onChange:te,onClose:K,onHighlightChange:he,onInputChange:we,onOpen:ge,open:pe,openOnFocus:ye=!1,openText:Le="Open",options:st,PaperComponent:ce,PopperComponent:Y,popupIcon:ae=qi||(qi=t.jsx(c.ArrowDropDownIcon,{})),readOnly:Fe=!1,renderGroup:Ve,renderInput:St,renderOption:Ee,renderTags:at,renderValue:yt,selectOnFocus:xt=!o.freeSolo,size:Ot="medium",slots:pt={},slotProps:Ye={},value:fe,...Ke}=o,{getRootProps:ze,getInputProps:lt,getInputLabelProps:ct,getPopupIndicatorProps:Qe,getClearProps:me,getItemProps:He,getListboxProps:vt,getOptionProps:Ce,value:Re,dirty:Ie,expanded:We,id:dt,popupOpen:Pe,focused:tt,focusedItem:Mt,anchorEl:kt,setAnchorEl:Ft,inputValue:gn,groupedOptions:Ne}=Ih({...o,componentName:"Autocomplete"}),ut=!T&&!M&&Ie&&!Fe,Kt=(!_||D===!0)&&D!==!1,{onMouseDown:yn}=lt(),{ref:ht,...en}=vt(),Qt=ne||($e=>$e.label??$e),Ze={...o,disablePortal:P,expanded:We,focused:tt,fullWidth:V,getOptionLabel:Qt,hasClearIcon:ut,hasPopupIcon:Kt,inputFocused:Mt===-1,popupOpen:Pe,size:Ot},Xe=Lh(Ze),At={slots:{paper:ce,popper:Y,...pt},slotProps:{chip:d,listbox:De,...C,...Ye}},[tn,Zt]=c.useSlot("listbox",{elementType:Hh,externalForwardedProps:At,ownerState:Ze,className:Xe.listbox,additionalProps:en,ref:ht}),[nn,G]=c.useSlot("paper",{elementType:c.Paper,externalForwardedProps:At,ownerState:Ze,className:Xe.paper}),[U,le]=c.useSlot("popper",{elementType:c.Popper,externalForwardedProps:At,ownerState:Ze,className:Xe.popper,additionalProps:{disablePortal:P,style:{width:kt?kt.clientWidth:null},role:"presentation",anchorEl:kt,open:Pe}});let ve;const ee=$e=>({className:Xe.tag,disabled:M,...He($e)});if(be?Re.length>0&&(at?ve=at(Re,ee,Ze):yt?ve=yt(Re,ee,Ze):ve=Re.map(($e,zt)=>{const{key:gt,...qt}=ee({index:zt});return t.jsx(c.Chip,{label:Qt($e),size:Ot,...qt,...At.slotProps.chip},gt)})):yt&&Re!=null&&(ve=yt(Re,ee,Ze)),se>-1&&Array.isArray(ve)){const $e=ve.length-se;!tt&&$e>0&&(ve=ve.splice(0,se),ve.push(t.jsx("span",{className:Xe.tag,children:$($e)},ve.length)))}const Ue=Ve||($e=>t.jsxs("li",{children:[t.jsx(Uh,{className:Xe.groupLabel,ownerState:Ze,component:"div",children:$e.group}),t.jsx(Gh,{className:Xe.groupUl,ownerState:Ze,children:$e.children})]},$e.key)),vn=Ee||(($e,zt)=>{const{key:gt,...qt}=$e;return t.jsx("li",{...qt,children:Qt(zt)},gt)}),zn=($e,zt)=>{const gt=Ce({option:$e,index:zt});return vn({...gt,className:Xe.option},$e,{selected:gt["aria-selected"],index:zt,inputValue:gn},Ze)},Wn=At.slotProps.clearIndicator,Dr=At.slotProps.popupIndicator;return t.jsxs(je.Fragment,{children:[t.jsx(_h,{ref:r,className:c.clsx(Xe.root,h),ownerState:Ze,...ze(Ke),children:St({id:dt,disabled:M,fullWidth:!0,size:Ot==="small"?"small":void 0,InputLabelProps:ct(),InputProps:{ref:Ft,className:Xe.inputRoot,startAdornment:ve,onMouseDown:$e=>{$e.target===$e.currentTarget&&yn($e)},...(ut||Kt)&&{endAdornment:t.jsxs(Nh,{className:Xe.endAdornment,ownerState:Ze,children:[ut?t.jsx(Ph,{...me(),"aria-label":v,title:v,ownerState:Ze,...Wn,className:c.clsx(Xe.clearIndicator,Wn?.className),children:y}):null,Kt?t.jsx(zh,{...Qe(),disabled:M,"aria-label":Pe?k:Le,title:Pe?k:Le,ownerState:Ze,...Dr,className:c.clsx(Xe.popupIndicator,Dr?.className),children:ae}):null]})}},inputProps:{className:Xe.input,disabled:M,readOnly:Fe,...lt()}})}),kt?t.jsx(Wh,{as:U,...le,children:t.jsxs(qh,{as:nn,...G,children:[de&&Ne.length===0?t.jsx(Bh,{className:Xe.loading,ownerState:Ze,children:ue}):null,Ne.length===0&&!_&&!de?t.jsx(Vh,{className:Xe.noOptions,ownerState:Ze,role:"presentation",onMouseDown:$e=>{$e.preventDefault()},children:Me}):null,Ne.length>0?t.jsx(tn,{as:ie,...Zt,children:Ne.map(($e,zt)=>H?Ue({key:$e.key,group:$e.group,children:$e.options.map((gt,qt)=>zn(gt,$e.index+qt))}):zn($e,zt))}):null]})}):null]})});c.dayjs.extend(c.utc);function Ts(e){switch(e){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 Yh(e){return e==="DateMinMax"}function Os(e){return e==="Between"}function Kh({spec:e,values:n,selection:r,onChange:o,retrievalFn:i}){const l=()=>r?.matchType?r.matchType:e.defaultMatchType?e.defaultMatchType:e.filterType==="DateMinMax"?"Between":Ts(e.filterType)[0]||"Equals",[a,u]=j.useState(l()),[d,h]=j.useState(r?.value??""),[y,b]=j.useState(r?.value2??""),[x,v]=j.useState([]),[k,C]=j.useState(!1),[S,T]=j.useState(""),[O,M]=j.useState(!1),[E,R]=j.useState(!1),P=j.useRef(null),F=j.useRef(0),[B,D]=j.useState(!1);j.useEffect(()=>{if(e.filterType!=="Retrieval"||!i)return;const z=S.trim();if(z.length<=2){v([]),M(!1);return}return P.current&&clearTimeout(P.current),P.current=setTimeout(async()=>{F.current+=1;const oe=F.current;C(!0);try{const se=await i(z,e);oe===F.current&&v(se)}catch(se){oe===F.current&&(console.error("Retrieval failed",se),v([]))}finally{oe===F.current&&(C(!1),M(!0))}},500),()=>{P.current&&clearTimeout(P.current)}},[S,e,i]),j.useEffect(()=>{r===null?(h(""),b(""),u(e.defaultMatchType??(e.filterType==="DateMinMax"?"Between":Ts(e.filterType)[0]||"Equals"))):r&&(u(r.matchType),h(r.value??""),b(r.value2??""))},[r,e.filterType,e.defaultMatchType]);const _=Ts(e.filterType),V=Yh(e.filterType),$=Os(a),W=V&&n.length>=2&&n[0].value instanceof Date?c.dayjs.utc(n[0].value):void 0,Z=V&&n.length>=2&&n[1].value instanceof Date?c.dayjs.utc(n[1].value):void 0,ne=e.filterType==="MinMax"&&n.length>=2&&typeof n[0].value=="number"?n[0].value:void 0,J=e.filterType==="MinMax"&&n.length>=2&&typeof n[1].value=="number"?n[1].value:void 0;if(_.length===0)return null;const H=z=>{const oe=z.target.value;u(oe),Os(oe)||b(""),d&&o({dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:oe,value:d,...Os(oe)&&y&&{value2:y}})},Q=(z,oe)=>{h(z??""),oe!==void 0&&b(oe??"");const se=Array.isArray(z)&&z.length===0;o(!se&&z!==""&&z!==null&&z!==void 0?{dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:a,value:z,...$&&oe&&{value2:oe}}:null)},re=()=>{h(""),b(""),o(null)};return t.jsxs(Ge,{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:[t.jsxs(Ge,{sx:{fontWeight:600,color:e.required&&!r?"error.main":"text.primary"},children:[e.label??e.dimensionName,e.required&&t.jsx(Ge,{component:"span",sx:{color:r?"text.secondary":"error.main",fontWeight:400,fontSize:"0.7rem",ml:.5},children:"(required)"})]}),e.filterType!=="Boolean"&&!e.defaultMatchType&&_.length>1&&t.jsxs(c.FormControl,{size:"small",fullWidth:!0,children:[t.jsx(c.InputLabel,{children:"Match Type"}),t.jsx(c.Select,{value:a,label:"Match Type",onChange:H,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:_.map(z=>t.jsx(et,{value:z,children:z},z))})]}),e.filterType==="Star"&&a==="Equals"&&t.jsx(Ks,{multiple:!0,size:"small",options:n,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(d)?d.map(z=>n.find(oe=>oe.value===z)||z):d?[n.find(z=>z.value===d)||d]:[],onChange:(z,oe)=>{const se=oe.map(ie=>typeof ie=="string"?ie:ie&&typeof ie=="object"&&"value"in ie?ie.value:ie);Q(se)},noOptionsText:"No matches found",renderInput:z=>t.jsx(c.TextField,{...z,size:"small",label:"Values",placeholder:"Select values..."}),freeSolo:!e.values||e.values.length===0,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),e.filterType==="Star"&&a==="Contains"&&t.jsx(c.TextField,{size:"small",label:"Search Text",value:d,onChange:z=>h(z.target.value),onBlur:()=>Q(d),onKeyDown:z=>{z.key==="Enter"&&Q(d)},placeholder:"Enter text to search...",fullWidth:!0}),e.filterType==="Boolean"&&t.jsxs(c.FormControl,{size:"small",fullWidth:!0,children:[t.jsx(c.InputLabel,{children:"Value"}),t.jsxs(c.Select,{value:d===!0?"true":d===!1?"false":"",label:"Value",onChange:z=>{const oe=z.target.value;oe==="true"?Q(!0):oe==="false"?Q(!1):re()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[t.jsx(et,{value:"",children:t.jsx("em",{children:"Blank"})}),t.jsx(et,{value:"true",children:"True"}),t.jsx(et,{value:"false",children:"False"})]})]}),e.filterType==="Retrieval"&&a==="Semantic Search"&&t.jsx(Ks,{multiple:!0,size:"small",options:x,loading:k,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(d)?d.map(z=>x.find(se=>se.value===z)||{value:z}):d?[{value:d}]:[],onInputChange:(z,oe)=>{T(oe)},onChange:(z,oe)=>{const se=oe.map(ie=>typeof ie=="string"?ie:ie&&typeof ie=="object"&&"value"in ie?ie.value:ie);Q(se)},noOptionsText:S.trim().length<=2?"Type at least 3 characters to search":"No matches found",renderInput:z=>t.jsx(c.TextField,{...z,size:"small",label:"Search Values",placeholder:"Type to search...",onFocus:()=>R(!0),onBlur:()=>R(!1),helperText:E&&!k&&O&&x.length===0?"No matches found":void 0,InputProps:{...z.InputProps,endAdornment:t.jsxs(t.Fragment,{children:[k?t.jsx(c.CircularProgress,{color:"inherit",size:20}):null,z.InputProps.endAdornment]})}}),freeSolo:!0,filterOptions:z=>z,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),e.filterType==="MinMax"&&!$&&t.jsx(c.TextField,{size:"small",type:"number",label:"Value",value:d,onChange:z=>Q(parseFloat(z.target.value)||""),onFocus:()=>D(!0),onBlur:()=>D(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:ne,max:J},helperText:B&&ne!==void 0&&J!==void 0?`Valid range: [${ne} - ${J}]`:void 0}),e.filterType==="MinMax"&&$&&t.jsxs(Ge,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ge,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(c.TextField,{size:"small",type:"number",label:"From",value:d,onChange:z=>Q(parseFloat(z.target.value)||"",y),onFocus:()=>D(!0),onBlur:()=>D(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:ne,max:y||J}}),t.jsx(Ge,{children:"to"}),t.jsx(c.TextField,{size:"small",type:"number",label:"To",value:y,onChange:z=>Q(d,parseFloat(z.target.value)||""),onFocus:()=>D(!0),onBlur:()=>D(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:d||ne,max:J}})]}),B&&ne!==void 0&&J!==void 0&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",ne," - ",J,"]"]})]}),V&&!$&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsx(c.DatePicker,{label:"Date",value:d instanceof Date?c.dayjs.utc(d):null,onChange:z=>{z===null?Q(null):z.isValid()&&Q(z.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?void 0:W,maxDate:d instanceof Date?void 0:Z,referenceDate:a==="After"&&W?W:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>D(!0),onBlur:()=>D(!1),helperText:B&&W&&Z?`Valid range: [${W.format("YYYY-MM-DD")} - ${Z.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),V&&$&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsxs(Ge,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ge,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(Ge,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"From",value:d instanceof Date?c.dayjs.utc(d):null,onChange:z=>{z===null?Q(null,y):z.isValid()&&Q(z.utc().toDate(),y)},timezone:"UTC",minDate:d instanceof Date?void 0:W,maxDate:y instanceof Date?c.dayjs.utc(y):d instanceof Date?void 0:Z,referenceDate:W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>D(!0),onBlur:()=>D(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),t.jsx(Ge,{children:"to"}),t.jsx(Ge,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"To",value:y instanceof Date?c.dayjs.utc(y):null,onChange:z=>{z===null?Q(d,null):z.isValid()&&Q(d,z.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?c.dayjs.utc(d):y instanceof Date?void 0:W,maxDate:y instanceof Date?void 0:Z,referenceDate:d instanceof Date?c.dayjs.utc(d):W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>D(!0),onBlur:()=>D(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),B&&W&&Z&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",W.format("YYYY-MM-DD")," -"," ",Z.format("YYYY-MM-DD"),"]"]})]})})]})}function os(e,n){const{matchType:r,value:o,value2:i}=n;if(Array.isArray(o))return r!=="Equals"&&r!=="Semantic Search"||o.length===0?"":`(${o.map(a=>`${e} = ${c.formatMalloyValue(a)}`).join(" or ")})`;switch(r){case"Equals":case"Semantic Search":return`${e} = ${c.formatMalloyValue(o)}`;case"Contains":if(typeof o=="string"){const l=Ju.StringFilterExpression.unparse({operator:"contains",values:[o]});return`${e} ~ ${c.malloyFilterLiteral(l)}`}return`${e} = ${c.formatMalloyValue(o)}`;case"After":case"Greater Than":return`${e} > ${c.formatMalloyValue(o)}`;case"Before":case"Less Than":return`${e} < ${c.formatMalloyValue(o)}`;case"Between":return i!==void 0?`${e} >= ${c.formatMalloyValue(o)} and ${e} <= ${c.formatMalloyValue(i)}`:`${e} >= ${c.formatMalloyValue(o)}`;default:return""}}function Qh(e){const n=new Set,r=e.schema?.fields;if(!r)return n;for(const o of r)"kind"in o&&o.kind==="join"&&o.name&&n.add(o.name);return n}function Zh(e){if(!e)return null;for(const n of e)if(n.startsWith("##(filters)")){const r=n.slice(11).trim();try{const o=JSON.parse(r);if(Array.isArray(o)){const i=[];for(const l of o)if(typeof l=="string"){const a=l.indexOf(".");a>0&&a<l.length-1&&i.push({source:l.substring(0,a),dimension:l.substring(a+1)})}if(i.length>0)return{filters:i}}}catch(o){console.error(`Failed to parse "${n}" annotation:`,o)}}return null}function rl(e){if(e.startsWith("#(filter)")){const n=e.slice(9).trim();try{const r=JSON.parse(n);if(r.type)return r}catch(r){console.error(`Failed to parse "${e}" annotation:`,r)}}return null}function Xh(e){const n=e.match(/^#\s*label\s*=\s*"([^"]+)"/);return n?n[1]:null}function Jh(e){const n=new Map;let r="";for(const o of e)if(o.type==="code"){if(!r&&o.text){const l=o.text.split(`
|
|
4
|
-
`).map(a=>a.trim()).find(a=>a.startsWith("import "))?.match(/['"]([^'"\n]+)['"]/);l&&(r=l[1])}if(o.newSources&&o.newSources.length>0)for(const i of o.newSources)try{const l=JSON.parse(i);l.name&&n.set(l.name,l)}catch(l){console.error("Failed to parse SourceInfo:",l)}}return{sourceInfoMap:n,modelPath:r}}function
|
|
3
|
+
`}function vd(e,n){return[e,"rows",...n].join("_").replace(/[^A-Za-z0-9._-]+/g,"_").replace(/_+/g,"_").replace(/^[_.]+|[_.]+$/g,"").slice(0,120)||"rows"}function bd(e,n,r){return r==="server_default"&&n!==void 0&&e>=n?n:void 0}const Ti="Download the rows behind this value as CSV, up to the server's row limit",wd=4e4;function Sd(e,n){const r=URL.createObjectURL(new Blob([e],{type:"text/csv;charset=utf-8"})),o=document.createElement("a");o.href=r,o.download=n,document.body.appendChild(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(r),wd)}function kd(e){const r=e?.response?.data?.message;return typeof r=="string"&&r!==""?r:e instanceof Error&&e.message!==""?e.message:"The request failed."}function Ha({query:e,preamble:n,environmentName:r,packageName:o,modelPath:i,versionId:l,givens:a,fileName:u}){const{apiClients:d}=q.useServer(),[h,y]=T.useState(!1),[b,x]=T.useState(Ti),[v,k]=T.useState(void 0),C=T.useRef(void 0);T.useEffect(()=>()=>C.current?.abort(),[]);const S=async()=>{C.current?.abort();const j=new AbortController;C.current=j,y(!0),k(void 0);try{const M=await d.models.executeQueryModel(r,o,i,{query:n===void 0?e:c.withPreamble(n,e),givens:a,versionId:l},void 0,void 0,{signal:j.signal});if(j.signal.aborted)return;const O=M.data,E=JSON.parse(O.result??"{}"),$=bd(Va(E).length,O.queryRowLimit,O.queryRowLimitSource);x($===void 0?Ti:`First ${$} rows: the server's row limit, so there may be more`),Sd(xd(E),$===void 0?`${u}.csv`:`${u}_first_${$}_rows_server_limit.csv`)}catch(M){if(j.signal.aborted)return;k(`Download failed: ${kd(M)}`)}finally{C.current===j&&(C.current=void 0,y(!1))}};return t.jsxs(m.Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[v&&t.jsx(m.Typography,{role:"alert",variant:"caption",color:"error",sx:{maxWidth:320},children:v}),t.jsx(m.Tooltip,{title:b,children:t.jsx("span",{children:t.jsx(m.Button,{size:"small",startIcon:t.jsx(gd,{fontSize:"small"}),onClick:()=>void S(),disabled:h,children:"Download CSV"})})})]})}const Ua=200;function Cd(e){const{target:n}=e;if(n!==void 0&&!(e.dimensions===void 0&&e.code===void 0))return{...e,target:n}}function ji(e,n=Ua){const r=jd(e);if(r===void 0)return;const o=[...e.target.filters,...r].join(", "),i=e.timezone?`timezone: '${c.escapeMalloyString(e.timezone)}'; `:"",l=n===null?"":`; limit: ${n}`,a=Td(e.target.source);if(a!==void 0)return`run: ${a} -> { ${i}where: ${o}; select: *${l} }`}function Td(e){return so.isBareName(e)?e:e.includes("`")?void 0:`\`${e}\``}function Cs(e){return/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(e)?e:`(${e})`}function jd(e){if(e.dimensions){const r=[];for(const{code:o,value:i}of e.dimensions){if(i.kind==="null_literal"){r.push(`${Cs(o)} is null`);continue}const l=La(i,e.timezone);if(l===void 0)return;r.push(`${Cs(o)} = ${l}`)}return r}const n=c.malloyLiteral(e.rawValue);return e.code!==void 0&&n?[`${Cs(e.code)} = ${n}`]:void 0}const Md="This value cannot be written as a filter, so its rows cannot be fetched.";function Mi(e){const n=e.drillClauses?Fa(e.drillClauses,e.timezone):[];return n.length>0?n:[{field:e.field,label:e.label}]}function Od({request:e,environmentName:n,packageName:r,versionId:o,modelPath:i,preamble:l,givens:a,onClose:u,onDone:d,actions:h}){const{theme:y}=q.usePublisherTheme(),b=e?ji(e):void 0,x=e?ji(e,null):void 0,v=e&&x!==void 0?{query:x,...l===void 0?{}:{preamble:l},environmentName:n,packageName:r,modelPath:i,...o===void 0?{}:{versionId:o},givens:a,fileName:vd(e.target.source,Mi(e).map(k=>k.label))}:void 0;return t.jsxs(m.Dialog,{open:e!==void 0,onClose:u,maxWidth:"lg",fullWidth:!0,children:[t.jsxs(m.DialogTitle,{sx:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",pb:.5},children:[t.jsxs(m.Box,{children:[e?t.jsxs(t.Fragment,{children:["Rows where"," ",Mi(e).map((k,C)=>t.jsxs(T.Fragment,{children:[C>0&&" and ",t.jsx(m.Box,{component:"code",sx:{fontSize:"0.9em"},children:k.field})," ","is ",k.label]},C))]}):"Rows",t.jsx(m.Typography,{component:"div",variant:"caption",sx:{color:y.tileTitle,mt:.25},children:e?`The first ${Ua} rows of ${e.target.source} behind this value, with the tile's own filters and the controls applied.`:""})]}),t.jsxs(m.Box,{sx:{display:"flex",alignItems:"center",gap:1,ml:1},children:[v&&(h?h(v):t.jsx(Ha,{...v})),t.jsx(m.IconButton,{onClick:u,"aria-label":"Close",size:"small",sx:{color:"text.secondary"},children:t.jsx(c.CloseIcon,{fontSize:"small"})})]})]}),t.jsxs(m.DialogContent,{dividers:!0,sx:{p:0,minHeight:240},children:[b===void 0&&e&&t.jsx(m.Typography,{variant:"body2",sx:{p:2},children:Md}),b!==void 0&&t.jsx(Ed,{query:l===void 0?b:c.withPreamble(l,b),environmentName:n,packageName:r,...o===void 0?{}:{versionId:o},modelPath:i,givens:a,...d?{onDone:d}:{}})]}),t.jsxs(m.DialogActions,{sx:{px:3,py:1.5},children:[b!==void 0&&t.jsx(m.Typography,{variant:"caption",sx:{mr:"auto",color:y.tileTitle,fontFamily:y.ui.font.mono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:b,children:b}),t.jsx(m.Button,{onClick:u,children:"Close"})]})]})}function Ed({query:e,environmentName:n,packageName:r,versionId:o,modelPath:i,givens:l,onDone:a}){const u=c.useQueryResult({environmentName:n,packageName:r,modelPath:i,...o===void 0?{}:{versionId:o},query:e,givens:l}),{isSuccess:d,isError:h}=u,y=T.useRef(void 0);return T.useEffect(()=>{y.current=c.now()},[e]),T.useEffect(()=>{y.current===void 0||!d&&!h||(a?.(d,c.now()-y.current),y.current=void 0)},[d,h,a]),t.jsx(m.Box,{sx:{p:1},children:t.jsx(c.ResultPanel,{state:u,context:e})})}function Ga({manifest:e,environmentName:n,packageName:r,versionId:o,documentName:i,givens:l,onGivensChange:a,onNavigate:u,height:d,maxResultSize:h,controlsLayout:y="bar",preamble:b,runModelPath:x,hiddenGivens:v,literalReads:k,onLinkNavigate:C,actions:S,rowsActions:j}){const M=T.useMemo(()=>C?{environmentName:n,packageName:r,sourcePath:e.path??i,onNavigate:C}:void 0,[n,r,e.path,i,C]),O=T.useMemo(()=>(e.givens??[]).filter(te=>!(b!==void 0&&te.secure===!0)&&!(te.name!==void 0&&v?.includes(te.name))),[e,v,b]),E=T.useMemo(()=>l===void 0?void 0:Object.fromEntries(Object.entries(l).filter(([,te])=>typeof te=="string")),[l]),$=c.useDocumentControls({specs:O,loaded:!0,startingValues:e.startingGivens,params:E,onGivensChange:a,documentKey:`${n}/${r}/${o??""}/${i}`,autorun:e.autorun!==!1,environmentName:n,packageName:r,modelPath:x??e.path,versionId:o,documentName:i,...b!==void 0?{preamble:b}:{},...l?{hostGivens:l}:{}}),{applied:P,declaredTypes:A,canSelf:B,onSelf:D}=$,_=c.useReportEvents(),V=T.useMemo(()=>{const te=new Set((e.tiles??[]).flatMap(K=>K.givenNames??[]));return Object.fromEntries(Object.entries(l??{}).filter(([K])=>te.has(K)&&!A.has(K)))},[e,l,A]),[R,W]=T.useState(void 0),Z=T.useCallback(te=>{const K=Cd(te);K!==void 0&&W(K)},[]),ne=T.useMemo(()=>c.withHostGivens(c.givensToRequest(P,A),V),[P,A,V]),{reports:J}=c.useReportListing(n,r,o,u!==void 0),H=T.useCallback(te=>{const K=c.resolveDrillTarget(te,J);if(K.kind!=="path")return;const he=K.report.path;return J.find(we=>we.path===he)?.title||void 0},[J]),{bindingFor:Q,drillMenu:re}=oo({onNavigate:u,onSelf:D,canSelf:B,onRows:Z,destinationTitle:H}),z=T.useCallback((te,K)=>Q(te,K!==!0),[Q]),{columns:oe,layout:se,tileMaxHeight:ie,tableMaxHeight:De}=c.layoutRules(e.layout,e.dashboardColumns),de=T.useMemo(()=>c.missingRequiredGivens(O,P,l),[O,P,l]);if(e.error)return t.jsx(c.ReportPage,{layout:se,header:t.jsx(Oi,{manifest:e,links:M,actions:S}),children:t.jsx(m.Alert,{severity:"error",children:e.error})});const ue=x??e.path,be=e.tiles??[],Oe=c.isPlaced(be);return t.jsxs(c.ReportPage,{layout:se,header:t.jsx(Oi,{manifest:e,links:M,actions:S}),controls:O.length>0?t.jsx(c.StickyControls,{children:t.jsx(c.GivensPanel,{...$.panel,layout:y})}):void 0,children:[de.length>0&&t.jsx(m.Alert,{severity:"info",children:c.requiredPrompt(de)}),ue===void 0?t.jsx(m.Alert,{severity:"error",children:"This dashboard has no model path, so there is nothing to run."}):be.length>0?t.jsx(c.DashboardGrid,{tiles:be,columns:oe,minTilePx:c.MIN_TILE_PX,rowGapPx:c.GRID_GAP_PX,keyOf:(te,K)=>`${K}:${te.kind==="text"?`text:${te.name}`:te.query}`,renderTile:(te,K)=>te.kind==="text"||te.query===void 0?t.jsx(m.Box,{sx:te.rowspan!==void 0||Oe?{minHeight:0,overflow:"auto"}:void 0,children:t.jsx(Id,{markdown:te.markdown??"",links:M})}):t.jsx(c.DashboardTile,{index:K,environmentName:n,packageName:r,versionId:o,modelPath:ue,tile:te.query,label:te.label,subtitle:te.subtitle,borderless:te.borderless,givens:P,hostGivens:V,declaredTypes:A,givenNames:te.givenNames,height:te.rowspan!==void 0||Oe?c.tileHeightPx(te.rowspan??c.PLACED_DEFAULT_ROWSPAN.query):se==="grid"?d??ie:ie,tableMaxHeight:De,fixedHeight:te.rowspan!==void 0||Oe,maxResultSize:h,drill:z(te.query,te.restricted),ignoredFilters:c.tileIgnoredFilterLabels(te.givenNames&&(te.query&&k?.[te.query]?[...te.givenNames,...k[te.query]]:te.givenNames),O),...b!==void 0?{preamble:b,restricted:te.restricted}:{},...(()=>{const he=c.waitingOn(de,te.givenNames);return he.length>0?{waitingFor:c.waitingText(he)}:{}})()})}):t.jsx(m.Alert,{severity:"warning",children:"This dashboard names neither a query nor any tiles."}),re,ue!==void 0&&t.jsx(Od,{request:R,environmentName:n,packageName:r,...o===void 0?{}:{versionId:o},modelPath:ue,...b===void 0?{}:{preamble:b},givens:ne,...j===void 0?{}:{actions:j},onClose:()=>W(void 0),onDone:(te,K)=>{R&&_.emit({type:"report.rows_shown",source:R.target.source,view:R.target.queryName??"",field:R.field,ok:te,durationMs:K})}})]})}function Id({markdown:e,links:n}){return t.jsx(c.TextTileFrame,{children:t.jsx(c.Prose,{variant:"document",links:n,children:e})})}function Oi({manifest:e,links:n,actions:r}){return t.jsx(c.ReportHeader,{title:e.title??e.name,actions:r,description:e.description?t.jsx(c.TextTileFrame,{children:t.jsx(c.Prose,{variant:"document",links:n,children:e.description})}):void 0})}const Ya=c.createSvgIcon(t.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"})),Dd="publisher:resize";function Ad(e){return typeof e=="object"&&e!==null&&e.type===Dd&&typeof e.height=="number"}const Ka="publisher:color-scheme",Qa="publisher:color-scheme-request",Za="publisher:color-scheme-applied",Rd=e=>e==="light"||e==="dark";function $d(e){return typeof e=="object"&&e!==null&&e.type===Qa}function Fd(e){return typeof e=="object"&&e!==null&&e.type===Za&&Rd(e.mode)}function Xa(e){return e.replace(/\/api\/v0\/?$/,"")}function Ja({server:e,environmentName:n,packageName:r,path:o,versionId:i}){const l=o.startsWith("public/")?o.slice(7):o,a=`${Xa(e)}/environments/${encodeURIComponent(n)}/packages/${encodeURIComponent(r)}/`+l;return i===void 0?a:`${a}${a.includes("?")?"&":"?"}versionId=${encodeURIComponent(i)}`}function Ld(e){try{const{environmentName:n,packageName:r,modelPath:o,versionId:i}=c.parseResourceUri(e);return!n||!r||!o?null:{environmentName:n,packageName:r,dataAppPath:o,versionId:i}}catch{return null}}function _d({resourceUri:e}){const{server:n,apiClients:r}=q.useServer(),o=Ld(e),i=o?.environmentName??"",l=o?.packageName??"",a=o?.dataAppPath??"",u=o?.versionId,d=T.useMemo(()=>Ja({server:n,environmentName:i,packageName:l,path:a,...u!==void 0?{versionId:u}:{}}),[n,i,l,a,u]),y=c.useQueryWithApiError({queryKey:["data-apps",i,l,u],queryFn:()=>r.dataApps.listDataApps(i,l,u),enabled:!!o}).data?.data?.find(P=>P.path===a),b=y?.title??a,x=y?.fit==="viewport",v=T.useRef(null),[k,C]=T.useState(120),S=m.useTheme().palette.mode==="dark"?"dark":"light",j=T.useRef(S);j.current=S;const[M,O]=T.useState(null),E=T.useMemo(()=>{try{return new URL(d,window.location.href).origin}catch{return null}},[d]),$=T.useCallback(()=>{const P=v.current?.contentWindow;!P||!E||P.postMessage({type:Ka,mode:j.current},E)},[E]);return T.useEffect($,[S,$]),T.useEffect(()=>{function P(A){A.source===v.current?.contentWindow&&(E&&A.origin!==E||($d(A.data)?$():Fd(A.data)&&O(A.data.mode)))}return window.addEventListener("message",P),()=>window.removeEventListener("message",P)},[E,$]),T.useEffect(()=>{if(x)return;function P(A){Ad(A.data)&&A.source===v.current?.contentWindow&&A.data.height>0&&C(Math.ceil(A.data.height))}return window.addEventListener("message",P),()=>window.removeEventListener("message",P)},[x]),o?t.jsxs(m.Box,{sx:{p:3,...x?{height:"100%",display:"flex",flexDirection:"column"}:{maxWidth:1600,mx:"auto"}},children:[t.jsxs(m.Stack,{direction:"row",alignItems:"baseline",spacing:1,sx:{mb:1,flexShrink:0},children:[t.jsx(m.Typography,{variant:"h6",sx:{fontWeight:"fontWeightMedium",letterSpacing:"-0.025em"},children:b}),t.jsx(m.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:q.MONO_FONT_FAMILY},children:a}),t.jsx(m.Box,{sx:{flex:1}}),t.jsx(m.Tooltip,{title:"Open standalone in new tab",children:t.jsx(m.IconButton,{size:"small",href:d,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:t.jsx(Ya,{fontSize:"small"})})})]}),t.jsx(m.Box,{sx:{border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden",backgroundColor:"background.paper",...x?{flex:1,minHeight:0}:{}},children:t.jsx("iframe",{ref:v,src:d,onLoad:()=>{O(null),$()},title:b,sandbox:"allow-scripts allow-same-origin allow-forms allow-downloads allow-popups",allow:"clipboard-write; fullscreen",style:{display:"block",width:"100%",height:x?"100%":k,border:0,...M?{colorScheme:M}:{}}})})]}):t.jsxs(m.Box,{sx:{p:3,maxWidth:1600,mx:"auto"},children:[t.jsx(m.Typography,{variant:"h6",sx:{fontWeight:"fontWeightMedium"},children:"Can't open data app"}),t.jsxs(m.Typography,{variant:"body2",color:"text.secondary",sx:{mt:1},children:["This data app link is missing an environment, package, or path:",t.jsx(m.Box,{component:"span",sx:{fontFamily:q.MONO_FONT_FAMILY,ml:1},children:e})]})]})}function Nt({title:e,count:n,description:r,action:o,children:i}){const l=T.useId();return t.jsxs(m.Box,{component:"section","aria-labelledby":l,sx:{mb:4},children:[t.jsxs(m.Stack,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:r?0:1,minHeight:40},children:[t.jsxs(m.Stack,{direction:"row",alignItems:"baseline",spacing:1,children:[t.jsx(m.Typography,{id:l,variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em",lineHeight:1.2},children:e}),n!==void 0&&t.jsxs(m.Typography,{variant:"caption",color:"text.secondary",children:["(",n,")"]})]}),o]}),r&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:r}),t.jsx(m.Box,{children:i})]})}function Nd({resourceUri:e}){const{environmentName:n}=c.parseResourceUri(e),{apiClients:r}=q.useServer(),[o,i]=T.useState(!1),l=90,{data:a,isSuccess:u,isError:d,error:h}=c.useQueryWithApiError({queryKey:["about",n],queryFn:()=>r.environments.getEnvironment(n,!1)}),y=a?.data?.readme||"",b=y.split(/\s+/),x=b.length>l,v=b.slice(0,l).join(" ");return t.jsxs(t.Fragment,{children:[!u&&!d&&t.jsx(c.Loading,{text:"Fetching About..."}),u&&y&&t.jsxs(Nt,{title:"Readme",children:[t.jsx(c.Prose,{variant:"caption",children:o||!x?y:v}),x&&t.jsx(m.Box,{sx:{mt:1},children:t.jsx(c.SecondaryButton,{label:o?"Read less":"Read more",onClick:()=>i(!o)})})]}),d&&t.jsx(c.ApiErrorDisplay,{error:h,context:`${n} > About`})]})}function Pd(e={}){const{autoHideDuration:n=null,disableWindowBlurListener:r=!1,onClose:o,open:i,resumeHideDuration:l}=e,a=c.useTimeout();Te.useEffect(()=>{if(!i)return;function j(M){M.defaultPrevented||M.key==="Escape"&&o?.(M,"escapeKeyDown")}return document.addEventListener("keydown",j),()=>{document.removeEventListener("keydown",j)}},[i,o]);const u=c.useEventCallback((j,M)=>{o?.(j,M)}),d=c.useEventCallback(j=>{!o||j==null||a.start(j,()=>{u(null,"timeout")})});Te.useEffect(()=>(i&&d(n),a.clear),[i,n,d,a]);const h=j=>{o?.(j,"clickaway")},y=a.clear,b=Te.useCallback(()=>{n!=null&&d(l??n*.5)},[n,l,d]),x=j=>M=>{const O=j.onBlur;O?.(M),b()},v=j=>M=>{const O=j.onFocus;O?.(M),y()},k=j=>M=>{const O=j.onMouseEnter;O?.(M),y()},C=j=>M=>{const O=j.onMouseLeave;O?.(M),b()};return Te.useEffect(()=>{if(!r&&i)return window.addEventListener("focus",b),window.addEventListener("blur",y),()=>{window.removeEventListener("focus",b),window.removeEventListener("blur",y)}},[r,i,b,y]),{getRootProps:(j={})=>{const M={...c.extractEventHandlers(e),...c.extractEventHandlers(j)};return{role:"presentation",...j,...M,onBlur:x(M),onFocus:v(M),onMouseEnter:k(M),onMouseLeave:C(M)}},onClickAway:h}}function Ei(e){return e.substring(2).toLowerCase()}function zd(e,n){return n.documentElement.clientWidth<e.clientX||n.documentElement.clientHeight<e.clientY}function Wd(e){const{children:n,disableReactTree:r=!1,mouseEvent:o="onClick",onClickAway:i,touchEvent:l="onTouchEnd"}=e,a=Te.useRef(!1),u=Te.useRef(null),d=Te.useRef(!1),h=Te.useRef(!1);Te.useEffect(()=>(setTimeout(()=>{d.current=!0},0),()=>{d.current=!1}),[]);const y=c.useForkRef(c.getReactElementRef(n),u),b=c.useEventCallback(k=>{const C=h.current;h.current=!1;const S=c.ownerDocument(u.current);if(!d.current||!u.current||"clientX"in k&&zd(k,S))return;if(a.current){a.current=!1;return}let j;k.composedPath?j=k.composedPath().includes(u.current):j=!S.documentElement.contains(k.target)||u.current.contains(k.target),!j&&(r||!C)&&i(k)}),x=k=>C=>{h.current=!0;const S=n.props[k];S&&S(C)},v={ref:y};return l!==!1&&(v[l]=x(l)),Te.useEffect(()=>{if(l!==!1){const k=Ei(l),C=c.ownerDocument(u.current),S=()=>{a.current=!0};return C.addEventListener(k,b),C.addEventListener("touchmove",S),()=>{C.removeEventListener(k,b),C.removeEventListener("touchmove",S)}}},[b,l]),o!==!1&&(v[o]=x(o)),Te.useEffect(()=>{if(o!==!1){const k=Ei(o),C=c.ownerDocument(u.current);return C.addEventListener(k,b),()=>{C.removeEventListener(k,b)}}},[b,o]),Te.cloneElement(n,v)}function qd(e){return c.generateUtilityClass("MuiSnackbarContent",e)}c.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const Bd=e=>{const{classes:n}=e,r={root:["root"],action:["action"],message:["message"]};return c.composeClasses(r,qd,n)},Vd=c.styled(c.Paper,{name:"MuiSnackbarContent",slot:"Root"})(c.memoTheme(({theme:e})=>{const n=e.palette.mode==="light"?.8:.98;return{...e.typography.body2,color:e.vars?e.vars.palette.SnackbarContent.color:e.palette.getContrastText(c.emphasize(e.palette.background.default,n)),backgroundColor:e.vars?e.vars.palette.SnackbarContent.bg:c.emphasize(e.palette.background.default,n),display:"flex",alignItems:"center",flexWrap:"wrap",padding:"6px 16px",flexGrow:1,[e.breakpoints.up("sm")]:{flexGrow:"initial",minWidth:288}}})),Hd=c.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),Ud=c.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),Gd=Te.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiSnackbarContent"}),{action:i,className:l,message:a,role:u="alert",...d}=o,h=o,y=Bd(h);return t.jsxs(Vd,{role:u,elevation:6,className:c.clsx(y.root,l),ownerState:h,ref:r,...d,children:[t.jsx(Hd,{className:y.message,ownerState:h,children:a}),i?t.jsx(Ud,{className:y.action,ownerState:h,children:i}):null]})});function Yd(e){return c.generateUtilityClass("MuiSnackbar",e)}c.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const Kd=e=>{const{classes:n,anchorOrigin:r}=e,o={root:["root",`anchorOrigin${c.capitalize(r.vertical)}${c.capitalize(r.horizontal)}`]};return c.composeClasses(o,Yd,n)},Qd=c.styled("div",{name:"MuiSnackbar",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,n[`anchorOrigin${c.capitalize(r.anchorOrigin.vertical)}${c.capitalize(r.anchorOrigin.horizontal)}`]]}})(c.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.snackbar,position:"fixed",display:"flex",left:8,right:8,justifyContent:"center",alignItems:"center",variants:[{props:({ownerState:n})=>n.anchorOrigin.vertical==="top",style:{top:8,[e.breakpoints.up("sm")]:{top:24}}},{props:({ownerState:n})=>n.anchorOrigin.vertical!=="top",style:{bottom:8,[e.breakpoints.up("sm")]:{bottom:24}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="left",style:{justifyContent:"flex-start",[e.breakpoints.up("sm")]:{left:24,right:"auto"}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="right",style:{justifyContent:"flex-end",[e.breakpoints.up("sm")]:{right:24,left:"auto"}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="center",style:{[e.breakpoints.up("sm")]:{left:"50%",right:"auto",transform:"translateX(-50%)"}}}]}))),Zd=Te.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiSnackbar"}),i=c.useTheme(),l={enter:i.transitions.duration.enteringScreen,exit:i.transitions.duration.leavingScreen},{action:a,anchorOrigin:{vertical:u,horizontal:d}={vertical:"bottom",horizontal:"left"},autoHideDuration:h=null,children:y,className:b,ClickAwayListenerProps:x,ContentProps:v,disableWindowBlurListener:k=!1,message:C,onBlur:S,onClose:j,onFocus:M,onMouseEnter:O,onMouseLeave:E,open:$,resumeHideDuration:P,slots:A={},slotProps:B={},TransitionComponent:D,transitionDuration:_=l,TransitionProps:{onEnter:V,onExited:R,...W}={},...Z}=o,ne={...o,anchorOrigin:{vertical:u,horizontal:d},autoHideDuration:h,disableWindowBlurListener:k,TransitionComponent:D,transitionDuration:_},J=Kd(ne),{getRootProps:H,onClickAway:Q}=Pd({...ne}),[re,z]=Te.useState(!0),oe=ge=>{z(!0),R&&R(ge)},se=(ge,me)=>{z(!1),V&&V(ge,me)},ie={slots:{transition:D,...A},slotProps:{content:v,clickAwayListener:x,transition:W,...B}},[De,de]=c.useSlot("root",{ref:r,className:[J.root,b],elementType:Qd,getSlotProps:H,externalForwardedProps:{...ie,...Z},ownerState:ne}),[ue,{ownerState:be,...Oe}]=c.useSlot("clickAwayListener",{elementType:Wd,externalForwardedProps:ie,getSlotProps:ge=>({onClickAway:(...me)=>{const ye=me[0];ge.onClickAway?.(...me),!ye?.defaultMuiPrevented&&Q(...me)}}),ownerState:ne}),[te,K]=c.useSlot("content",{elementType:Gd,shouldForwardComponentProp:!0,externalForwardedProps:ie,additionalProps:{message:C,action:a},ownerState:ne}),[he,we]=c.useSlot("transition",{elementType:c.Grow,externalForwardedProps:ie,getSlotProps:ge=>({onEnter:(...me)=>{ge.onEnter?.(...me),se(...me)},onExited:(...me)=>{ge.onExited?.(...me),oe(...me)}}),additionalProps:{appear:!0,in:$,timeout:_,direction:u==="top"?"down":"up"},ownerState:ne});return!$&&re?null:t.jsx(ue,{...Oe,...A.clickAwayListener&&{ownerState:be},children:t.jsx(De,{...de,children:t.jsx(he,{...we,children:y||t.jsx(te,{...K})})})})});let Us;function Xd(e){Us=e}function Ii(e){if(Us)try{Us(e)}catch{}}function Ht(e,n,r){return(async o=>{const i=Date.now();try{const l=await r(o);return Ii({type:"console.mutation",resource:e,action:n,ok:!0,durationMs:Date.now()-i}),l}catch(l){throw Ii({type:"console.mutation",resource:e,action:n,ok:!1,durationMs:Date.now()-i,reason:l instanceof Error?l.message:"An unknown error occurred"}),l}})}function Nn({mutationFn:e,success:n,invalidates:r,closeDialog:o,resource:i,action:l}){const a=pt.useQueryClient(),[u,d]=T.useState(""),h=c.useMutationWithApiError({mutationFn:Ht(i,l,e),onSuccess(){o();for(const y of r)a.invalidateQueries({queryKey:y});d(n)},onError(y){d(y instanceof Error?y.message:"An unknown error occurred")}});return{mutate:h.mutate,isPending:h.isPending,notice:t.jsx(Zd,{open:u!=="",autoHideDuration:6e3,onClose:()=>d(""),message:u})}}const el="https://docs.malloydata.dev/documentation",Ts=`${el}/user_guides/publishing`,In="https://github.com/malloydata/publisher/blob/main/docs",Vt={docsHome:`${el}/`,publishing:`${Ts}/publishing`,explorer:`${Ts}/explorer`,mcpAgents:`${Ts}/mcp_agents`,surfaces:`${In}/choosing-a-surface.md`,dashboards:`${In}/dashboards.md`,dataApps:`${In}/html-data-apps.md`,givens:`${In}/givens.md`,materialization:`${In}/materialization.md`,connections:`${In}/connections.md`};function Jd({resourceUri:e}){const[n,r]=T.useState(!1),{apiClients:o}=q.useServer(),{environmentName:i}=c.parseResourceUri(e),l=Nn({mutationFn(u){return o.packages.createPackage(i,{name:u.name,description:u.description,location:u.location})},success:"Package created",invalidates:[["packages",i]],closeDialog:()=>r(!1),resource:"package",action:"create"}),a=u=>{u.preventDefault();const d=new FormData(u.currentTarget),h=d.get("name")?.toString(),y=d.get("description")?.toString(),b=d.get("location")?.toString();l.mutate({name:h,description:y,location:b})};return t.jsxs(t.Fragment,{children:[t.jsx(c.AddButton,{label:"Package",onClick:()=>r(!0)}),t.jsx(c.AppDialog,{open:n,onClose:()=>r(!1),title:"New package",description:t.jsxs(t.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"," ",t.jsx(m.Box,{component:"a",href:Vt.publishing,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary"},children:"package format"}),"."]}),actions:t.jsxs(t.Fragment,{children:[t.jsx(m.Button,{disabled:l.isPending,onClick:()=>r(!1),children:"Cancel"}),t.jsx(m.Button,{type:"submit",form:"package-form",variant:"contained",loading:l.isPending,children:"Create package"})]}),children:t.jsx("form",{onSubmit:a,id:"package-form",children:t.jsxs(m.Stack,{sx:{gap:2},children:[t.jsx(m.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(m.TextField,{id:"description",name:"description",label:"Description",multiline:!0,rows:3,fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(m.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}})]})})}),l.notice]})}const eh=c.createSvgIcon(t.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function rs({icon:e,tint:n,label:r,mono:o,description:i,rightLabel:l,trailingAction:a,onClick:u,ariaLabel:d}){const h=!!u,y=b=>{u&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),u(b))};return t.jsxs(m.Box,{onClick:u,onKeyDown:h?y:void 0,role:h?"button":void 0,tabIndex:h?0:void 0,"aria-label":d,sx:b=>({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:b.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:[t.jsx(m.Box,{sx:{width:32,height:32,borderRadius:1,bgcolor:n,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:e}),t.jsxs(m.Box,{sx:{flex:1,minWidth:0,display:"flex",alignItems:"baseline",gap:1.5},children:[t.jsx(m.Typography,{variant:"body2",sx:{...o?{fontFamily:q.MONO_FONT_FAMILY}:{},flexShrink:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),i&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i})]}),l&&t.jsx(m.Typography,{variant:"caption",color:"text.secondary",sx:{flexShrink:0},children:l}),a&&t.jsx(m.Box,{sx:{flexShrink:0,display:"flex",alignItems:"center"},children:a})]})}const tl=c.createSvgIcon(t.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"})),th=c.generateUtilityClasses("MuiBox",["root"]),nh=c.createTheme(),Ge=wr.createBox({themeId:c.THEME_ID,defaultTheme:nh,defaultClassName:th.root,generateClassName:c.ClassNameGenerator.generate}),ss=wr.createStack({createStyledComponent:c.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:e=>c.useDefaultProps({props:e,name:"MuiStack"})}),Di=c.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function rh(e){return c.generateUtilityClass("MuiListItemIcon",e)}const Ai=c.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),sh=e=>{const{alignItems:n,classes:r}=e,o={root:["root",n==="flex-start"&&"alignItemsFlexStart"]};return c.composeClasses(o,rh,r)},oh=c.styled("div",{name:"MuiListItemIcon",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,r.alignItems==="flex-start"&&n.alignItemsFlexStart]}})(c.memoTheme(({theme:e})=>({minWidth:56,color:(e.vars||e).palette.action.active,flexShrink:0,display:"inline-flex",variants:[{props:{alignItems:"flex-start"},style:{marginTop:8}}]}))),io=Te.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiListItemIcon"}),{className:i,...l}=o,a=Te.useContext(c.ListContext),u={...o,alignItems:a.alignItems},d=sh(u);return t.jsx(oh,{className:c.clsx(d.root,i),ownerState:u,ref:r,...l})});function ih(e){return c.generateUtilityClass("MuiListItemText",e)}const An=c.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),ah=e=>{const{classes:n,inset:r,primary:o,secondary:i,dense:l}=e,a={root:["root",r&&"inset",l&&"dense",o&&i&&"multiline"],primary:["primary"],secondary:["secondary"]};return c.composeClasses(a,ih,n)},lh=c.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${An.primary}`]:n.primary},{[`& .${An.secondary}`]:n.secondary},n.root,r.inset&&n.inset,r.primary&&r.secondary&&n.multiline,r.dense&&n.dense]}})({flex:"1 1 auto",minWidth:0,marginTop:4,marginBottom:4,[`.${c.typographyClasses.root}:where(& .${An.primary})`]:{display:"block"},[`.${c.typographyClasses.root}:where(& .${An.secondary})`]:{display:"block"},variants:[{props:({ownerState:e})=>e.primary&&e.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:e})=>e.inset,style:{paddingLeft:56}}]}),ao=Te.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiListItemText"}),{children:i,className:l,disableTypography:a=!1,inset:u=!1,primary:d,primaryTypographyProps:h,secondary:y,secondaryTypographyProps:b,slots:x={},slotProps:v={},...k}=o,{dense:C}=Te.useContext(c.ListContext);let S=d??i,j=y;const M={...o,disableTypography:a,inset:u,primary:!!S,secondary:!!j,dense:C},O=ah(M),E={slots:x,slotProps:{primary:h,secondary:b,...v}},[$,P]=c.useSlot("root",{className:c.clsx(O.root,l),elementType:lh,externalForwardedProps:{...E,...k},ownerState:M,ref:r}),[A,B]=c.useSlot("primary",{className:O.primary,elementType:c.Typography,externalForwardedProps:E,ownerState:M}),[D,_]=c.useSlot("secondary",{className:O.secondary,elementType:c.Typography,externalForwardedProps:E,ownerState:M});return S!=null&&S.type!==c.Typography&&!a&&(S=t.jsx(A,{variant:C?"body2":"body1",component:B?.variant?void 0:"span",...B,children:S})),j!=null&&j.type!==c.Typography&&!a&&(j=t.jsx(D,{variant:"body2",color:"textSecondary",..._,children:j})),t.jsxs($,{...P,children:[S,j]})});function ch(e){return c.generateUtilityClass("MuiMenuItem",e)}const er=c.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),uh=(e,n)=>{const{ownerState:r}=e;return[n.root,r.dense&&n.dense,r.divider&&n.divider,!r.disableGutters&&n.gutters]},dh=e=>{const{disabled:n,dense:r,divider:o,disableGutters:i,selected:l,classes:a}=e,u={root:["root",r&&"dense",n&&"disabled",!i&&"gutters",o&&"divider",l&&"selected"]},d=c.composeClasses(u,ch,a);return{...a,...d}},hh=c.styled(c.ButtonBase,{shouldForwardProp:e=>c.rootShouldForwardProp(e)||e==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:uh})(c.memoTheme(({theme:e})=>({...e.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:(e.vars||e).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},[`&.${er.selected}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity),[`&.${er.focusVisible}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.focusOpacity}`)}},[`&.${er.selected}:hover`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity)}},[`&.${er.focusVisible}`]:{backgroundColor:(e.vars||e).palette.action.focus},[`&.${er.disabled}`]:{opacity:(e.vars||e).palette.action.disabledOpacity},[`& + .${Di.root}`]:{marginTop:e.spacing(1),marginBottom:e.spacing(1)},[`& + .${Di.inset}`]:{marginLeft:52},[`& .${An.root}`]:{marginTop:0,marginBottom:0},[`& .${An.inset}`]:{paddingLeft:36},[`& .${Ai.root}`]:{minWidth:36},variants:[{props:({ownerState:n})=>!n.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:n})=>n.divider,style:{borderBottom:`1px solid ${(e.vars||e).palette.divider}`,backgroundClip:"padding-box"}},{props:({ownerState:n})=>!n.dense,style:{[e.breakpoints.up("sm")]:{minHeight:"auto"}}},{props:({ownerState:n})=>n.dense,style:{minHeight:32,paddingTop:4,paddingBottom:4,...e.typography.body2,[`& .${Ai.root} svg`]:{fontSize:"1.25rem"}}}]}))),et=Te.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiMenuItem"}),{autoFocus:i=!1,component:l="li",dense:a=!1,divider:u=!1,disableGutters:d=!1,focusVisibleClassName:h,role:y="menuitem",tabIndex:b,className:x,...v}=o,k=Te.useContext(c.ListContext),C=Te.useMemo(()=>({dense:a||k.dense||!1,disableGutters:d}),[k.dense,a,d]),S=Te.useRef(null);c.useEnhancedEffect(()=>{i&&S.current&&S.current.focus()},[i]);const j={...o,dense:C.dense,divider:u,disableGutters:d},M=dh(o),O=c.useForkRef(S,r);let E;return o.disabled||(E=b!==void 0?b:-1),t.jsx(c.ListContext.Provider,{value:C,children:t.jsx(hh,{ref:O,role:y,tabIndex:E,component:l,focusVisibleClassName:c.clsx(M.focusVisible,h),className:c.clsx(M.root,x),...v,ownerState:j,classes:M})})}),Gt={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},{label:"Database Metadata",name:"dbmeta",type:"text",required:!1,selectOptions:[{label:"No",value:"false"},{label:"Yes",value:"true"}]}],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}],sqlserver:[{label:"Server",name:"server",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!1},{label:"Database",name:"database",type:"text",required:!0},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!0},{label:"Encrypt",name:"encrypt",type:"text",required:!1,selectOptions:[{label:"Yes",value:"true"},{label:"No",value:"false"}]},{label:"Trust server certificate",name:"trustServerCertificate",type:"text",required:!1,selectOptions:[{label:"No",value:"false"},{label:"Yes",value:"true"}]},{label:"Host name in certificate",name:"hostNameInCertificate",type:"text",required:!1},{label:"Instance name",name:"instanceName",type:"text",required:!1}],duckdb:[],motherduck:[{label:"Access Token",name:"accessToken",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1}],ducklake:[],publisher:[]},mr={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",trino:"trinoConnection",databricks:"databricksConnection",mysql:"mysqlConnection",sqlserver:"sqlserverConnection",duckdb:"duckdbConnection",motherduck:"motherduckConnection",ducklake:"ducklakeConnection",publisher:"publisherConnection"},fh={bigquery:{dbmeta:"boolean"},sqlserver:{port:"integer",encrypt:"boolean",trustServerCertificate:"boolean"}},ph={sqlserver:["hostNameInCertificate","instanceName"]};function nl(e,n){const r=fh[e],o=ph[e];if(!r&&!o)return n;const i={...n};for(const l of o??[])i[l]===""&&delete i[l];for(const[l,a]of Object.entries(r??{})){const u=n[l];if(u!==void 0){if(u===""){delete i[l];continue}if(a==="integer"){const d=Number(u);Number.isInteger(d)&&(i[l]=d)}else(u==="true"||u==="false")&&(i[l]=u==="true")}}return i}const rl=Object.values(q.ConnectionTypeEnum).filter(e=>e!==q.ConnectionTypeEnum.Publisher),Gs={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},Sr=[{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"}}],kr=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],mh=[{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 Jr(e){return e==="postgres"||e==="bigquery"||e==="snowflake"?Gt[e]||[]:e==="s3"?Sr:e==="gcs"?kr:e==="azure"?mh:[]}function gh({onSubmit:e,isSubmitting:n}){const[r,o]=T.useState(!1),[i,l]=T.useState("postgres"),[a,u]=T.useState([]),[d,h]=T.useState("postgres"),[y,b]=T.useState("s3"),[x,v]=T.useState("config"),k=()=>{o(!0)},C=()=>{o(!1),u([]),l("postgres"),h("postgres"),b("s3"),v("config")},S=async E=>{E.preventDefault();const $=new FormData(E.currentTarget),P=$.get("name")?.toString(),A=$.get("type")?.toString(),B=Gt[A];if(!P)throw new Error("Name is required");if(!A)throw new Error("Type is required");let D;if(A==="ducklake"){const _={};if(d==="postgres"){const W=Gt.postgres,Z={};if(W.forEach(ne=>{const J=$.get(`ducklake_pg_${ne.name}`)?.toString();J&&(Z[ne.name]=J)}),Object.keys(Z).length===0)throw new Error("DuckLake requires catalog connection");_.postgresConnection=Z}const V=$.get("ducklake_bucketUrl")?.toString();if(!V)throw new Error("DuckLake requires a bucket URL");const R={bucketUrl:V};if(y==="s3"){const W={};if(Sr.forEach(Z=>{const ne=$.get(`ducklake_s3_${Z.name}`)?.toString();ne&&(W[Z.name]=ne)}),W.provider==="credential_chain")delete W.accessKeyId,delete W.secretAccessKey,delete W.sessionToken;else{if(delete W.chain,!W.accessKeyId)throw new Error("S3 Access Key ID is required");if(!W.secretAccessKey)throw new Error("S3 Secret Access Key is required")}Object.keys(W).length>0&&(R.s3Connection=W)}else if(y==="gcs"){const W={};if(kr.forEach(Z=>{const ne=$.get(`ducklake_gcs_${Z.name}`)?.toString();ne&&(W[Z.name]=ne)}),!W.keyId)throw new Error("GCS Key ID is required");if(!W.secret)throw new Error("GCS Secret is required");Object.keys(W).length>0&&(R.gcsConnection=W)}D={name:P,type:A,ducklakeConnection:{catalog:_,storage:R}}}else if(A==="duckdb"){if(a.length===0)throw new Error("DuckDB connection must have at least one attached database");const _=a.map((V,R)=>{const W=V.dbType,Z=$.get(`attachedDb_${R}_name`)?.toString();if(!Z)throw new Error(`Attached database at index ${R} must have a name`);const ne={name:Z,type:W},J=Jr(W);if(J&&J.length>0){const H={};if(J.forEach(re=>{const z=$.get(`attachedDb_${R}_${re.name}`)?.toString();z&&(H[re.name]=z)}),W==="s3"){if(H.provider==="credential_chain")delete H.accessKeyId,delete H.secretAccessKey,delete H.sessionToken;else if(delete H.chain,!H.accessKeyId||!H.secretAccessKey)throw new Error(`Attached database "${Z}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const Q=Gs[W];Q&&(ne[Q]=H)}return ne});D={name:P,type:A,duckdbConnection:{attachedDatabases:_}}}else{const _={};if(B.forEach(V=>{const R=$.get(V.name)?.toString();R&&(_[V.name]=R)}),A==="postgres"){if(!!!_.connectionString?.trim()){const R=["host","port","databaseName","userName","password"];for(const W of R)if(!_[W])throw new Error(`${B.find(Z=>Z.name===W)?.label||W} is required`)}}else if(A==="bigquery"){if(!_.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if(A==="snowflake"){if(!_.account)throw new Error("Account is required");if(!_.username)throw new Error("Username is required");if(!_.warehouse)throw new Error("Warehouse is required");if(!_.password&&!_.privateKey)throw new Error("Either password or private key is required")}else if(A==="trino"){if(!_.server)throw new Error("Server is required");if(!_.user)throw new Error("User is required");if(_.server.trim().startsWith("https://")&&!_.password&&!_.peakaKey)throw new Error("Password is required for HTTPS connections (or use Peaka Key)")}else if(A==="mysql"){const V=["host","port","database","user","password"];for(const R of V)if(!_[R])throw new Error(`${B.find(W=>W.name===R)?.label||R} is required`)}else if(A==="sqlserver"){const V=["server","database","user","password"];if(!_.instanceName&&!_.port)throw new Error("Port is required unless an instance name is given");for(const R of V)if(!_[R])throw new Error(`${B.find(W=>W.name===R)?.label||R} is required`)}else if(A==="motherduck"){if(!_.accessToken)throw new Error("Access Token is required")}else if(A==="databricks"){if(!_.host)throw new Error("Host is required");if(!_.path)throw new Error("HTTP Path is required");const V=_.oauthClientId&&_.oauthClientSecret;if(!_.token&&!V)throw new Error("Either Access Token or OAuth Client ID + Secret is required")}D={name:P,type:A,[mr[A]]:nl(A,_)}}await e(D),C()},j=()=>{u([...a,{name:"",dbType:"postgres"}])},M=E=>{u(a.filter(($,P)=>P!==E))},O=(E,$)=>{const P=[...a];P[E]={...P[E],dbType:$},u(P)};return t.jsxs(T.Fragment,{children:[t.jsx(c.AddButton,{label:"Connection",onClick:k}),t.jsx(c.AppDialog,{open:r,onClose:C,title:"New connection",description:"Add a connection so packages in this environment can query your database with Malloy.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:n,onClick:C,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"connection-form",variant:"contained",loading:n,children:"Create connection"})]}),children:t.jsx("form",{onSubmit:S,id:"connection-form",children:t.jsxs(ss,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small"}),t.jsx(c.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:i,select:!0,onChange:E=>l(E.target.value),children:rl.map(E=>t.jsx(et,{value:E,children:E},E))}),i==="ducklake"?t.jsxs(Ge,{sx:{mt:2},children:[t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),t.jsx(c.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:d,select:!0,onChange:E=>h(E.target.value),children:t.jsx(et,{value:"postgres",children:"PostgreSQL"})}),d==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(E=>t.jsx(c.TextField,{id:`ducklake_pg_${E.name}`,name:`ducklake_pg_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small"},`pg_${E.name}`))})]}),t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),t.jsxs(c.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:y,select:!0,onChange:E=>b(E.target.value),children:[t.jsx(et,{value:"s3",children:"S3"}),t.jsx(et,{value:"gcs",children:"GCS"})]}),t.jsx(c.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:y==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small"}),y==="s3"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),Sr.filter(E=>E.visibleWhen?x===E.visibleWhen.value:!0).map(E=>t.jsx(c.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?x:void 0,onChange:E.name==="provider"?$=>v($.target.value):void 0,placeholder:E.name==="region"?"us-east-1":void 0,children:E.selectOptions?.map($=>t.jsx(et,{value:$.value,children:$.label},$.value))},`s3_${E.name}`))]}),y==="gcs"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),kr.map(E=>t.jsx(c.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}`))]})]})]}):i==="duckdb"?t.jsxs(Ge,{sx:{mt:2},children:[t.jsxs(Ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsx(c.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),t.jsx(c.SecondaryButton,{label:"Database",icon:t.jsx(c.AddIcon,{}),onClick:j,ariaLabel:"Add database"})]}),a.length===0&&t.jsx(c.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),a.map((E,$)=>{const P=Jr(E.dbType);return t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(c.Typography,{variant:"subtitle2",children:["Database ",$+1]}),t.jsx(c.IconButton,{onClick:()=>M($),size:"small",color:"error",children:t.jsx(tl,{fontSize:"small"})})]}),t.jsx(c.TextField,{required:!0,id:`attachedDb_${$}_name`,name:`attachedDb_${$}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:E.name}),t.jsx(c.TextField,{id:`attachedDb_${$}_type`,name:`attachedDb_${$}_type`,label:"Database Type",fullWidth:!0,size:"small",value:E.dbType,select:!0,onChange:A=>O($,A.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map(A=>t.jsx(et,{value:A,children:A},A))}),P.filter(A=>A.visibleWhen?(E[A.visibleWhen.field]||P.find(D=>D.name===A.visibleWhen?.field)?.selectOptions?.[0]?.value)===A.visibleWhen.value:!0).map(A=>t.jsx(c.TextField,{id:`attachedDb_${$}_${A.name}`,name:`attachedDb_${$}_${A.name}`,label:A.label,type:A.selectOptions?void 0:A.type,fullWidth:!0,size:"small",required:A.required,select:!!A.selectOptions,defaultValue:A.selectOptions?.[0]?.value,onChange:A.selectOptions?B=>{const D=[...a];D[$]={...D[$],[A.name]:B.target.value},u(D)}:void 0,children:A.selectOptions?.map(B=>t.jsx(et,{value:B.value,children:B.label},B.value))},A.name))]},$)})]}):Gt[i].map(E=>t.jsx(c.TextField,{id:E.name,name:E.name,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required,select:!!E.selectOptions,defaultValue:E.selectOptions?E.selectOptions[0]?.value:void 0,children:E.selectOptions?.map($=>t.jsx(et,{value:$.value,children:$.label},$.value))},E.name))]})})})]})}function yh({connection:e,onCloseDialog:n,isMutating:r,onDelete:o}){const[i,l]=T.useState(!1),a=()=>{l(!0)},u=()=>{l(!1),n()};return t.jsxs(T.Fragment,{children:[t.jsxs(et,{"aria-label":`Delete connection ${e?.name??""}`.trim(),onClick:d=>{d.stopPropagation(),a()},sx:{color:"error.main"},children:[t.jsx(io,{sx:{color:"inherit"},children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(ao,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:i,onClose:u,title:"Delete connection",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:u,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>o(),loading:r,children:"Delete connection"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:e.name}),"? Packages that query through it stop working, and this cannot be undone."]})})]})}const Ri=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function $i(e){const n=e.duckdbConnection?.attachedDatabases;return!n||n.length===0?[]:n.map(r=>({name:r.name||"",dbType:r.type||"postgres"}))}function Fi(e){const n=e.ducklakeConnection;return n&&n.storage?.gcsConnection?"gcs":"s3"}function xh({connection:e,onSubmit:n,isSubmitting:r,onCloseDialog:o}){const[i,l]=T.useState(!1),[a,u]=T.useState(e.type),d=T.useMemo(()=>new Set(e.withheldFields??[]),[e.withheldFields]),[h,y]=T.useState(()=>$i(e)),[b,x]=T.useState("postgres"),[v,k]=T.useState(()=>Fi(e)),[C,S]=T.useState(()=>e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),j=()=>{y($i(e)),u(e.type),S(e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),x("postgres"),k(Fi(e)),l(!0)},M=()=>{l(!1),o?.()},O=async D=>{D.preventDefault();const _=new FormData(D.currentTarget),V=_.get("name")?.toString(),R=_.get("type")?.toString(),W=Gt[R];if(!V)throw new Error("Name is required");if(!R)throw new Error("Type is required");let Z;if(R==="ducklake"){const ne={};if(b==="postgres"){const Q=Gt.postgres,re={};if(Q.forEach(z=>{const oe=_.get(`ducklake_pg_${z.name}`)?.toString();oe&&(re[z.name]=oe)}),Object.keys(re).length===0)throw new Error("DuckLake requires catalog connection");ne.postgresConnection=re}const J=_.get("ducklake_bucketUrl")?.toString();if(!J)throw new Error("DuckLake requires a bucket URL");const H={bucketUrl:J};if(v==="s3"){const Q={};Sr.forEach(z=>{const oe=_.get(`ducklake_s3_${z.name}`)?.toString();oe&&(Q[z.name]=oe)});const re=e.ducklakeConnection?.storage?.s3Connection;if(re&&(!Q.provider&&re.provider&&(Q.provider=re.provider),!Q.chain&&re.chain&&(Q.chain=re.chain),!Q.accessKeyId&&re.accessKeyId&&(Q.accessKeyId=re.accessKeyId)),Q.provider==="credential_chain")delete Q.accessKeyId,delete Q.secretAccessKey,delete Q.sessionToken;else if(delete Q.chain,!Q.accessKeyId)throw new Error("S3 Access Key ID is required");Object.keys(Q).length>0&&(H.s3Connection=Q)}else if(v==="gcs"){const Q={};kr.forEach(z=>{const oe=_.get(`ducklake_gcs_${z.name}`)?.toString();oe&&(Q[z.name]=oe)});const re=e.ducklakeConnection?.storage?.gcsConnection;if(re&&!Q.keyId&&re.keyId&&(Q.keyId=re.keyId),!Q.keyId)throw new Error("GCS Key ID is required");Object.keys(Q).length>0&&(H.gcsConnection=Q)}Z={name:V,type:R,ducklakeConnection:{catalog:ne,storage:H}}}else if(R==="duckdb"){if(h.length===0)throw new Error("DuckDB connection must have at least one attached database");const ne=h.map((J,H)=>{const Q=J.dbType,re=_.get(`attachedDb_${H}_name`)?.toString();if(!re)throw new Error(`Attached database at index ${H} must have a name`);const z={name:re,type:Q},oe=Jr(Q);if(oe&&oe.length>0){const se={};if(oe.forEach(De=>{const de=_.get(`attachedDb_${H}_${De.name}`)?.toString();de&&(se[De.name]=de)}),Q==="s3"){if(se.provider==="credential_chain")delete se.accessKeyId,delete se.secretAccessKey,delete se.sessionToken;else if(delete se.chain,!se.accessKeyId||!se.secretAccessKey)throw new Error(`Attached database "${re}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const ie=Gs[Q];ie&&(z[ie]=se)}return z});Z={name:V,type:R,duckdbConnection:{attachedDatabases:ne}}}else{const ne=e[mr[R]]||{},J={};if(W.forEach(H=>{const Q=_.get(H.name)?.toString(),re=ne[H.name];Q?J[H.name]=Q:Ri.has(H.name)||(Q!==void 0?J[H.name]=Q:re&&(J[H.name]=re))}),R==="postgres"){const H=["host","port","databaseName","userName"],Q=d.has("postgresConnection.connectionString");if(!(!!J.connectionString?.trim()||Q)){const z=H;for(const oe of z)if(!J[oe])throw new Error(`${W.find(se=>se.name===oe)?.label||oe} is required`)}}else if(R==="snowflake"){if(!J.account)throw new Error("Account is required");if(!J.username)throw new Error("Username is required");if(!J.warehouse)throw new Error("Warehouse is required")}else if(R==="trino"){if(!J.server)throw new Error("Server is required");if(!J.user)throw new Error("User is required")}else if(R==="mysql"){const H=["host","port","database","user"];for(const Q of H)if(!J[Q])throw new Error(`${W.find(re=>re.name===Q)?.label||Q} is required`)}else if(R==="sqlserver"){const H=["server","database","user"];if(!J.instanceName&&!J.port)throw new Error("Port is required unless an instance name is given");for(const Q of H)if(!J[Q])throw new Error(`${W.find(re=>re.name===Q)?.label||Q} is required`)}else if(R==="databricks"){if(!J.host)throw new Error("Host is required");if(!J.path)throw new Error("HTTP Path is required")}Z={name:V,type:R,[mr[R]]:nl(R,J)}}await n(Z),M()},E=()=>{y([...h,{name:"",dbType:"postgres"}])},$=D=>{y(h.filter((_,V)=>V!==D))},P=(D,_)=>{const V=[...h];V[D]={...V[D],dbType:_},y(V)},A=(D,_)=>{const V=e.duckdbConnection?.attachedDatabases;if(!V||!V[D])return"";const R=V[D],W=Gs[R.type||""];return W&&R[W]?R[W][_]??"":""},B=D=>{const _=e.ducklakeConnection;if(!_)return"";if(D.startsWith("pg_")){const V=D.replace("pg_","");return _.catalog?.postgresConnection?.[V]??""}if(D==="bucketUrl")return _.storage?.bucketUrl??"";if(D.startsWith("s3_")){const V=D.replace("s3_","");return _.storage?.s3Connection?.[V]??""}if(D.startsWith("gcs_")){const V=D.replace("gcs_","");return _.storage?.gcsConnection?.[V]??""}return""};return t.jsxs(T.Fragment,{children:[t.jsxs(et,{"aria-label":`Edit connection ${e?.name??""}`.trim(),onClick:D=>{D.preventDefault(),D.stopPropagation(),j()},children:[t.jsx(io,{children:t.jsx(Pt.Edit,{fontSize:"small"})}),t.jsx(ao,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:i,onClose:M,title:"Edit connection",description:"Change how packages in this environment reach your database.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:r,onClick:M,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"connection-form",variant:"contained",loading:r,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:O,id:"connection-form",children:t.jsxs(ss,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",defaultValue:e.name}),t.jsx(c.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:a,select:!0,onChange:D=>u(D.target.value),children:rl.map(D=>t.jsx(et,{value:D,children:D},D))}),a==="ducklake"?t.jsxs(Ge,{sx:{mt:2},children:[t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),t.jsx(c.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:b,select:!0,onChange:D=>x(D.target.value),children:t.jsx(et,{value:"postgres",children:"PostgreSQL"})}),b==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(D=>t.jsx(c.TextField,{id:`ducklake_pg_${D.name}`,name:`ducklake_pg_${D.name}`,label:D.label,type:D.type,fullWidth:!0,size:"small",defaultValue:B(`pg_${D.name}`)},`pg_${D.name}`))})]}),t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),t.jsxs(c.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:v,select:!0,onChange:D=>k(D.target.value),children:[t.jsx(et,{value:"s3",children:"S3"}),t.jsx(et,{value:"gcs",children:"GCS"})]}),t.jsx(c.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:v==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small",defaultValue:B("bucketUrl")}),v==="s3"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),Sr.filter(D=>D.visibleWhen?C===D.visibleWhen.value:!0).map(D=>t.jsx(c.TextField,{id:`ducklake_s3_${D.name}`,name:`ducklake_s3_${D.name}`,label:D.label,type:D.selectOptions?void 0:D.type,fullWidth:!0,size:"small",required:D.required&&D.name!=="secretAccessKey",select:!!D.selectOptions,defaultValue:D.selectOptions?C:B(`s3_${D.name}`),onChange:D.name==="provider"?_=>S(_.target.value):void 0,placeholder:D.name==="region"?"us-east-1":D.name==="secretAccessKey"&&d.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:D.selectOptions?.map(_=>t.jsx(et,{value:_.value,children:_.label},_.value))},`s3_${D.name}`))]}),v==="gcs"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),kr.map(D=>t.jsx(c.TextField,{id:`ducklake_gcs_${D.name}`,name:`ducklake_gcs_${D.name}`,label:D.label,type:D.type,fullWidth:!0,size:"small",required:D.required&&D.name!=="secret",defaultValue:B(`gcs_${D.name}`),placeholder:D.name==="secret"&&d.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${D.name}`))]})]})]}):a==="duckdb"?t.jsxs(Ge,{sx:{mt:2},children:[t.jsxs(Ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsx(c.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),t.jsx(c.SecondaryButton,{label:"Database",icon:t.jsx(c.AddIcon,{}),onClick:E,ariaLabel:"Add database"})]}),h.length===0&&t.jsx(c.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((D,_)=>{const V=Jr(D.dbType);return t.jsxs(Ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(c.Typography,{variant:"subtitle2",children:["Database ",_+1]}),t.jsx(c.IconButton,{"aria-label":`Remove attached database ${_+1}`,onClick:()=>$(_),size:"small",color:"error",children:t.jsx(tl,{fontSize:"small"})})]}),t.jsx(c.TextField,{required:!0,id:`attachedDb_${_}_name`,name:`attachedDb_${_}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:D.name}),t.jsx(c.TextField,{id:`attachedDb_${_}_type`,name:`attachedDb_${_}_type`,label:"Database Type",fullWidth:!0,size:"small",value:D.dbType,select:!0,onChange:R=>P(_,R.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map(R=>t.jsx(et,{value:R,children:R},R))}),V.filter(R=>R.visibleWhen?(D[R.visibleWhen.field]||A(_,R.visibleWhen.field)||V.find(Z=>Z.name===R.visibleWhen?.field)?.selectOptions?.[0]?.value)===R.visibleWhen.value:!0).map(R=>t.jsx(c.TextField,{id:`attachedDb_${_}_${R.name}`,name:`attachedDb_${_}_${R.name}`,label:R.label,type:R.selectOptions?void 0:R.type,fullWidth:!0,size:"small",required:R.required,select:!!R.selectOptions,defaultValue:A(_,R.name)||R.selectOptions?.[0]?.value,onChange:R.selectOptions?W=>{const Z=[...h];Z[_]={...Z[_],[R.name]:W.target.value},y(Z)}:void 0,children:R.selectOptions?.map(W=>t.jsx(et,{value:W.value,children:W.label},W.value))},R.name))]},_)})]}):Gt[a].map(D=>{const _=e?.[mr[a]??""]?.[D.name??""]??"",V=D.type==="password"||Ri.has(D.name),R=d.has(`${mr[a]??""}.${D.name}`),W=D.selectOptions?_===""||_===void 0?D.selectOptions[0]?.value:String(_):void 0;return t.jsx(c.TextField,{id:D.name,name:D.name,label:D.label,type:D.type,fullWidth:!0,size:"small",required:D.required&&!V&&!_,select:!!D.selectOptions,defaultValue:D.selectOptions?W:_,placeholder:R?"Leave empty to keep existing":void 0,helperText:V?R?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0,children:D.selectOptions?.map(Z=>t.jsx(et,{value:Z.value,children:Z.label},Z.value))},D.name)})]})})})]})}function Li(e,n){return!e||e.type!=="duckdb"?!1:(e.duckdbConnection?.attachedDatabases||[]).some(o=>o.type==="azure"&&o.name===n)}function vh(e){return e.startsWith("gs://")||e.startsWith("s3://")||e.startsWith("https://")||e.startsWith("abfss://")||e.startsWith("az://")}function sl({connectionName:e,resourceUri:n,schema:r,connection:o}){const{apiClients:i}=q.useServer(),{environmentName:l}=c.parseResourceUri(n),[a,u]=T.useState(null),[d,h]=T.useState(r||null),[y,b]=T.useState(!1),{data:x,isError:v,isLoading:k,error:C}=c.useQueryWithApiError({queryKey:["schemas",l,e],queryFn:()=>i.connections.listSchemas(l,e)}),S=x?.data||[];return t.jsxs(m.Grid,{container:!0,spacing:1,children:[!r&&t.jsx(m.Grid,{size:{xs:12,md:4},children:t.jsxs(m.Paper,{sx:{p:1,m:0},children:[t.jsxs(m.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:0},children:[t.jsx(m.Typography,{variant:"overline",fontWeight:"bold",children:"Table Paths"}),t.jsx(m.FormControlLabel,{control:t.jsx(m.Switch,{checked:y,onChange:j=>b(j.target.checked)}),label:"Hidden Schemas"})]}),t.jsx(m.Divider,{sx:{mt:"2px"}}),t.jsxs(m.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[k&&t.jsx(c.Loading,{text:"Loading schemas..."}),v&&t.jsx(c.ApiErrorDisplay,{error:C,context:`${l} > ${e} > Schemas`}),!k&&!v&&S.length===0&&t.jsx(m.Typography,{variant:"body2",children:"No Schemas"}),!k&&!v&&S.length>0&&t.jsx(m.List,{dense:!0,disablePadding:!0,children:S.map(j=>{const M=j.name;if(j.isHidden&&!y)return null;const E=d===M;return t.jsx(m.ListItemButton,{selected:E,onClick:()=>{h(M),u(null)},children:t.jsx(m.ListItemText,{primary:M})},M)})})]})]})}),t.jsx(m.Grid,{size:{xs:12,md:r?6:4},children:d&&t.jsx(m.Paper,{sx:{p:1,m:0},children:t.jsx(Sh,{connectionName:e,schemaName:d,onTableSelect:j=>{u(j)},resourceUri:n,connection:o})})}),t.jsx(m.Grid,{size:{xs:12,md:r?6:4},children:d&&a&&t.jsx(bh,{environmentName:l,connectionName:e,schemaName:d,tableResource:a})})]})}function bh({environmentName:e,connectionName:n,schemaName:r,tableResource:o}){const{apiClients:i}=q.useServer(),{data:l,isLoading:a,isError:u,error:d}=c.useQueryWithApiError({queryKey:["connectionTableDetail",e,n,r,o],queryFn:()=>i.connections.getTable(e,n,r,o),enabled:!!r&&!!o}),h={resource:l?.data?.resource??o,columns:l?.data?.columns??[]};return t.jsxs(m.Paper,{sx:{p:1,m:0},children:[u&&t.jsx(c.ApiErrorDisplay,{error:d,context:`${e} > ${n} > ${r} > ${o}`}),!u&&t.jsx(wh,{table:h,loading:a})]})}function wh({table:e,loading:n}){return n?t.jsx(c.Loading,{text:"Loading columns..."}):t.jsxs(t.Fragment,{children:[t.jsxs(m.Typography,{variant:"overline",fontWeight:"bold",sx:{display:"block",wordBreak:"break-all"},children:[e.resource.includes("://")||/\.(parquet|csv|json|tsv|ndjson)$/i.test(e.resource)?"File":"Table",": ",e.resource]}),t.jsx(m.Divider,{}),t.jsx(m.Box,{sx:{mt:"10px",maxHeight:"600px",overflowY:"auto"},children:t.jsx(m.TableContainer,{children:t.jsxs(m.Table,{size:"small",sx:{"& .MuiTableCell-root":{padding:"10px"}},children:[t.jsx(m.TableHead,{children:t.jsxs(m.TableRow,{children:[t.jsx(m.TableCell,{children:"NAME"}),t.jsx(m.TableCell,{children:"TYPE"})]})}),t.jsx(m.TableBody,{children:e.columns?.sort((r,o)=>r.name.localeCompare(o.name))?.map(r=>t.jsxs(m.TableRow,{children:[t.jsx(m.TableCell,{children:r.name}),t.jsx(m.TableCell,{children:r.type})]},r.name))})]})})})]})}function Sh({connectionName:e,schemaName:n,onTableSelect:r,resourceUri:o,connection:i}){const{environmentName:l}=c.parseResourceUri(o),{apiClients:a}=q.useServer(),[u,d]=T.useState(""),{data:h,isSuccess:y,isError:b,error:x,isLoading:v}=c.useQueryWithApiError({queryKey:["tablesInSchema",l,e,n],queryFn:()=>a.connections.listTables(l,e,n)}),k=Li(i,n),C=j=>k?j:j.split(".").pop()||j,S=y&&h?.data?h.data.filter(j=>C(j.resource).toLowerCase().includes(u.toLowerCase())).sort((j,M)=>C(j.resource).localeCompare(C(M.resource))):[];return t.jsxs(t.Fragment,{children:[t.jsx(m.Typography,{variant:"overline",fontWeight:"bold",children:vh(n)||Li(i,n)?`Files in ${n}`:`Tables in ${n}`}),t.jsx(m.Divider,{}),t.jsx(m.Box,{sx:{mt:1,mb:1},children:t.jsx(m.TextField,{size:"small",fullWidth:!0,placeholder:"Search tables...",value:u,onChange:j=>d(j.target.value),variant:"outlined"})}),t.jsx(m.Divider,{}),t.jsxs(m.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[v&&t.jsx(c.Loading,{text:"Fetching Tables..."}),b&&t.jsx(c.ApiErrorDisplay,{error:x,context:`${l} > ${e} > ${n}`}),y&&S.length===0&&t.jsx(m.Typography,{variant:"body2",children:"No Tables"}),y&&h?.data&&h.data.length>0&&t.jsx(m.List,{dense:!0,disablePadding:!0,children:S.map(j=>{let M=C(j.resource);return!k&&j.resource.includes("://")&&(M=j.resource.split("/").pop()||j.resource),t.jsx(m.ListItemButton,{onClick:()=>r(j.resource),children:t.jsx(m.ListItemText,{primary:M,secondary:j.columns.length>0?`${j.columns.length} columns`:void 0})},j.resource)})})]})]})}const kh={bigquery:"BigQuery",snowflake:"Snowflake",postgres:"PostgreSQL",mysql:"MySQL",sqlserver:"SQL Server",trino:"Trino",databricks:"Databricks",duckdb:"DuckDB",ducklake:"DuckLake",s3:"S3",gcs:"GCS",azure:"Azure"};function Ch(e){return e?kh[e]??e:""}function Th({resourceUri:e}){const{apiClients:n,mutable:r}=q.useServer(),o=pt.useQueryClient(),{environmentName:i}=c.parseResourceUri(e),[l,a]=T.useState(""),[u,d]=T.useState(null),h=c.encodeResourceUri({environmentName:i,connectionName:u}),{data:y,isSuccess:b,isError:x,error:v}=c.useQueryWithApiError({queryKey:["connections",i],queryFn:()=>n.connections.listConnections(i)}),k=c.useMutationWithApiError({mutationFn:Ht("connection","create",O=>n.environments.updateEnvironment(i,{name:i,connections:[...y.data,O]})),onSuccess(){a("Connection added successfully"),o.invalidateQueries({queryKey:["connections",i]})},onError(O){a(O.message)}}),C=c.useMutationWithApiError({mutationFn:Ht("connection","update",O=>n.environments.updateEnvironment(i,{name:i,connections:y.data.map(E=>E.name===O.name?O:E)})),onSuccess(O,E){a(`Connection ${E.name} updated successfully`),o.invalidateQueries({queryKey:["connections",i]})},onError(O){a(O.message)}}),S=c.useMutationWithApiError({mutationFn:Ht("connection","delete",O=>{if(!O.name)throw new Error("Cannot delete a connection with no name");return n.connections.deleteConnection(i,O.name)}),onSuccess(O,E){a(`Connection ${E.name} deleted successfully`),o.invalidateQueries({queryKey:["connections",i]})},onError(O){a(O.message)}}),j=b?[...y.data].sort((O,E)=>(O.name??"").localeCompare(E.name??"")):[],M=k.isPending||C.isPending||S.isPending;return t.jsxs(Nt,{title:"Connections",...b?{count:j.length}:{},description:"Database connections available to packages in this environment",...r&&b?{action:t.jsx(gh,{onSubmit:O=>k.mutateAsync(O),isSubmitting:k.isPending})}:{},children:[!b&&!x&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:"Fetching Connections..."}),x&&t.jsx(c.ApiErrorDisplay,{error:v,context:`${i} > Connections`}),b&&j.length===0&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),b&&j.length>0&&t.jsx(m.Stack,{children:j.map(O=>t.jsx(jh,{connection:O,mutable:r,isMutating:M,onOpenExplorer:()=>d(O.name??null),onEdit:E=>C.mutateAsync(E),onDelete:E=>S.mutateAsync(E)},O.name))}),t.jsx(m.Snackbar,{open:l!=="",autoHideDuration:6e3,onClose:()=>a(""),message:l}),t.jsx(c.AppDialog,{open:u!==null,onClose:()=>d(null),maxWidth:"lg",title:`Connection explorer: ${u??""}`,showClose:!0,children:u&&t.jsx(sl,{resourceUri:h,connectionName:u,connection:y?.data?.find(O=>O.name===u)})})]})}function jh({connection:e,mutable:n,isMutating:r,onOpenExplorer:o,onEdit:i,onDelete:l}){const[a,u]=T.useState(null),d=!!a,h=b=>{b.stopPropagation(),u(b.currentTarget)},y=()=>u(null);return t.jsx(rs,{icon:t.jsx(eh,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.connection,label:e.name??"",ariaLabel:e.name??"",description:Ch(e.type),onClick:o,...n?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(m.IconButton,{size:"small",onClick:h,"aria-label":`Connection actions for ${e.name??""}`.trim(),children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(m.Menu,{anchorEl:a,open:d,onClose:y,onClick:b=>b.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[t.jsx(xh,{connection:e,onSubmit:i,isSubmitting:r,onCloseDialog:y}),t.jsx(yh,{connection:e,onCloseDialog:y,isMutating:r,onDelete:()=>l(e)})]})]})}:{}})}const Mh=c.createSvgIcon([t.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"),t.jsx("path",{d:"M9 12h6v2H9z"},"1")]);function Oh({resourceUri:e,onCloseDialog:n}){const[r,o]=T.useState(!1),{apiClients:i}=q.useServer(),l=()=>{o(!0)},a=()=>{o(!1),n()},{environmentName:u,packageName:d}=c.parseResourceUri(e),h=Nn({mutationFn:()=>i.packages.deletePackage(u,d),success:"Package deleted",invalidates:[["packages",u]],closeDialog:a,resource:"package",action:"delete"});return t.jsxs(T.Fragment,{children:[t.jsxs(m.MenuItem,{onClick:l,children:[t.jsx(m.ListItemIcon,{children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(m.ListItemText,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:r,onClose:a,title:"Delete package",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:a,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>h.mutate(),loading:h.isPending,children:"Delete package"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:d}),"? The package stops being served and this cannot be undone."]})}),h.notice]})}function Eh({package:e,resourceUri:n,onCloseDialog:r}){const[o,i]=T.useState(!1),{apiClients:l}=q.useServer(),a=()=>{i(!0)},u=()=>{i(!1),r()},{packageName:d,environmentName:h}=c.parseResourceUri(n),y=Nn({mutationFn(x){return l.packages.updatePackage(h,d,{name:d,description:x.description})},success:"Package updated",invalidates:[["packages",h]],closeDialog:u,resource:"package",action:"update"}),b=x=>{x.preventDefault();const k=new FormData(x.currentTarget).get("description")?.toString();y.mutate({description:k})};return t.jsxs(T.Fragment,{children:[t.jsxs(m.MenuItem,{onClick:a,children:[t.jsx(m.ListItemIcon,{children:t.jsx(Pt.Edit,{fontSize:"small"})}),t.jsx(m.ListItemText,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:o,onClose:u,title:"Edit package",description:`What ${e.name} is, for the people who open it.`,actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:y.isPending,onClick:u,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"package-form",variant:"contained",loading:y.isPending,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:b,id:"package-form",children:t.jsxs(m.Stack,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:e.name,InputLabelProps:{shrink:!0}}),t.jsx(c.TextField,{id:"description",name:"description",label:"Description",multiline:!0,fullWidth:!0,rows:4,size:"small",defaultValue:e.description,InputLabelProps:{shrink:!0}})]})})}),y.notice]})}function ol({onSelectPackage:e,resourceUri:n}){const{apiClients:r}=q.useServer(),{environmentName:o}=c.parseResourceUri(n),{data:i,isSuccess:l,isError:a,error:u}=c.useQueryWithApiError({queryKey:["packages",o],queryFn:()=>r.packages.listPackages(o)});if(a)return t.jsx(c.ApiErrorDisplay,{error:u,context:`${o} > Packages`});if(!l)return t.jsx(c.Loading,{text:"Fetching Packages..."});const d=[...i.data].sort((h,y)=>h.name.localeCompare(y.name));return t.jsx(m.Stack,{children:d.map(h=>{const y=c.encodeResourceUri({environmentName:o,packageName:h.name});return t.jsx(Ih,{pkg:h,packageResourceUri:y,onSelectPackage:e},h.name)})})}function Ih({pkg:e,packageResourceUri:n,onSelectPackage:r}){const{mutable:o}=q.useServer(),i=e.versionId!==void 0||e.latestVersion!==void 0,[l,a]=T.useState(null),u=!!l,d=y=>{y.stopPropagation(),a(y.currentTarget)},h=()=>a(null);return t.jsx(rs,{icon:t.jsx(Mh,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.package,label:e.name,ariaLabel:e.name,...e.description?{description:e.description}:{},onClick:y=>r(e.name,y),...o?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(m.IconButton,{size:"small",onClick:d,"aria-label":`Package actions for ${e.name}`,children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(m.Menu,{anchorEl:l,open:u,onClose:h,onClick:y=>y.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[!i&&t.jsx(Eh,{package:e,resourceUri:n,onCloseDialog:h}),t.jsx(Oh,{resourceUri:n,onCloseDialog:h})]})]})}:{}})}function Dh({onSelectPackage:e,resourceUri:n}){const{apiClients:r,mutable:o}=q.useServer(),{environmentName:i}=c.parseResourceUri(n),l=c.useQueryWithApiError({queryKey:["packages",i],queryFn:()=>r.packages.listPackages(i)});return T.useEffect(()=>{window.scrollTo({top:0,behavior:"auto"})},[]),t.jsxs(m.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsxs(m.Box,{sx:{mb:4},children:[t.jsx(m.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em",mb:.5},children:i}),t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:"Manage packages and database connections in this environment. Open a package to explore its models and notebooks."})]}),t.jsx(Nt,{title:"Packages",...l.isSuccess?{count:l.data.data.length}:{},description:"Published packages available for use in this environment",...o?{action:t.jsx(Jd,{resourceUri:n})}:{},children:t.jsx(ol,{onSelectPackage:e,resourceUri:n})}),t.jsx(Th,{resourceUri:n}),t.jsx(Nd,{resourceUri:n})]})}function _i({array1:e,array2:n,parser:r=o=>o}){return e&&n&&e.length===n.length&&e.every((o,i)=>r(o)===r(n[i]))}function Ni(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}function Ah(e={}){const{ignoreAccents:n=!0,ignoreCase:r=!0,limit:o,matchFrom:i="any",stringify:l,trim:a=!1}=e;return(u,{inputValue:d,getOptionLabel:h})=>{let y=a?d.trim():d;r&&(y=y.toLowerCase()),n&&(y=Ni(y));const b=y?u.filter(x=>{let v=(l||h)(x);return r&&(v=v.toLowerCase()),n&&(v=Ni(v)),i==="start"?v.startsWith(y):v.includes(y)}):u;return typeof o=="number"?b.slice(0,o):b}}const Rh=Ah(),Pi=5,$h=e=>e.current!==null&&e.current.parentElement?.contains(document.activeElement),Fh=[];function zi(e,n,r,o){if(n||e==null||o)return"";const i=r(e);return typeof i=="string"?i:""}function Lh(e){const{unstable_isActiveElementInListbox:n=$h,unstable_classNamePrefix:r="Mui",autoComplete:o=!1,autoHighlight:i=!1,autoSelect:l=!1,blurOnSelect:a=!1,clearOnBlur:u=!e.freeSolo,clearOnEscape:d=!1,componentName:h="useAutocomplete",defaultValue:y=e.multiple?Fh:null,disableClearable:b=!1,disableCloseOnSelect:x=!1,disabled:v,disabledItemsFocusable:k=!1,disableListWrap:C=!1,filterOptions:S=Rh,filterSelectedOptions:j=!1,freeSolo:M=!1,getOptionDisabled:O,getOptionKey:E,getOptionLabel:$=G=>G.label??G,groupBy:P,handleHomeEndKeys:A=!e.freeSolo,id:B,includeInputInList:D=!1,inputValue:_,isOptionEqualToValue:V=(G,U)=>G===U,multiple:R=!1,onChange:W,onClose:Z,onHighlightChange:ne,onInputChange:J,onOpen:H,open:Q,openOnFocus:re=!1,options:z,readOnly:oe=!1,renderValue:se,selectOnFocus:ie=!e.freeSolo,value:De}=e,de=c.useId(B);let ue=$;ue=G=>{const U=$(G);return typeof U!="string"?String(U):U};const be=Te.useRef(!1),Oe=Te.useRef(!0),te=Te.useRef(null),K=Te.useRef(null),[he,we]=Te.useState(null),[ge,me]=Te.useState(-1),ye=i?0:-1,Le=Te.useRef(ye),st=Te.useRef(zi(y??De,R,ue)).current,[ce,Y]=c.useControlled({controlled:De,default:y,name:h}),[ae,Re]=c.useControlled({controlled:_,default:st,name:h,state:"inputValue"}),[Ve,St]=Te.useState(!1),Ee=Te.useCallback((G,U,le)=>{if(!(R?ce.length<U.length:U!==null)&&!u)return;const ee=zi(U,R,ue,se);ae!==ee&&(Re(ee),J&&J(G,ee,le))},[ue,ae,R,J,Re,u,ce,se]),[at,yt]=c.useControlled({controlled:Q,default:!1,name:h,state:"open"}),[xt,Mt]=Te.useState(!0),mt=!R&&ce!=null&&ae===ue(ce),Ye=at&&!oe,fe=Ye?S(z.filter(G=>!(j&&(R?ce:[ce]).some(U=>U!==null&&V(G,U)))),{inputValue:mt&&xt?"":ae,getOptionLabel:ue}):[],Ke=pd({filteredOptions:fe,value:ce,inputValue:ae});Te.useEffect(()=>{const G=ce!==Ke.value;Ve&&!G||M&&!G||Ee(null,ce,"reset")},[ce,Ee,Ve,Ke.value,M]);const ze=at&&fe.length>0&&!oe,lt=c.useEventCallback(G=>{if(G===-1)te.current.focus();else{const U=se?"data-item-index":"data-tag-index";he.querySelector(`[${U}="${G}"]`).focus()}});Te.useEffect(()=>{R&&ge>ce.length-1&&(me(-1),lt(-1))},[ce,R,ge,lt]);function ct(G,U){if(!K.current||G<0||G>=fe.length)return-1;let le=G;for(;;){const ve=K.current.querySelector(`[data-option-index="${le}"]`),ee=k?!1:!ve||ve.disabled||ve.getAttribute("aria-disabled")==="true";if(ve&&ve.hasAttribute("tabindex")&&!ee)return le;if(U==="next"?le=(le+1)%fe.length:le=(le-1+fe.length)%fe.length,le===G)return-1}}const Qe=c.useEventCallback(({event:G,index:U,reason:le})=>{if(Le.current=U,U===-1?te.current.removeAttribute("aria-activedescendant"):te.current.setAttribute("aria-activedescendant",`${de}-option-${U}`),ne&&["mouse","keyboard","touch"].includes(le)&&ne(G,U===-1?null:fe[U],le),!K.current)return;const ve=K.current.querySelector(`[role="option"].${r}-focused`);ve&&(ve.classList.remove(`${r}-focused`),ve.classList.remove(`${r}-focusVisible`));let ee=K.current;if(K.current.getAttribute("role")!=="listbox"&&(ee=K.current.parentElement.querySelector('[role="listbox"]')),!ee)return;if(U===-1){ee.scrollTop=0;return}const qe=K.current.querySelector(`[data-option-index="${U}"]`);if(qe&&(qe.classList.add(`${r}-focused`),le==="keyboard"&&qe.classList.add(`${r}-focusVisible`),ee.scrollHeight>ee.clientHeight&&le!=="mouse"&&le!=="touch")){const Ue=qe,Ct=ee.clientHeight+ee.scrollTop,vn=Ue.offsetTop+Ue.offsetHeight;vn>Ct?ee.scrollTop=vn-ee.clientHeight:Ue.offsetTop-Ue.offsetHeight*(P?1.3:0)<ee.scrollTop&&(ee.scrollTop=Ue.offsetTop-Ue.offsetHeight*(P?1.3:0))}}),pe=c.useEventCallback(({event:G,diff:U,direction:le="next",reason:ve})=>{if(!Ye)return;const qe=ct((()=>{const Ue=fe.length-1;if(U==="reset")return ye;if(U==="start")return 0;if(U==="end")return Ue;const Ct=Le.current+U;return Ct<0?Ct===-1&&D?-1:C&&Le.current!==-1||Math.abs(U)>1?0:Ue:Ct>Ue?Ct===Ue+1&&D?-1:C||Math.abs(U)>1?Ue:0:Ct})(),le);if(Qe({index:qe,reason:ve,event:G}),o&&U!=="reset")if(qe===-1)te.current.value=ae;else{const Ue=ue(fe[qe]);te.current.value=Ue,Ue.toLowerCase().indexOf(ae.toLowerCase())===0&&ae.length>0&&te.current.setSelectionRange(ae.length,Ue.length)}}),He=!_i({array1:Ke.filteredOptions,array2:fe,parser:ue}),vt=()=>{const G=(U,le)=>{const ve=U?ue(U):"",ee=le?ue(le):"";return ve===ee};if(Le.current!==-1&&!_i({array1:Ke.filteredOptions,array2:fe,parser:ue})&&Ke.inputValue===ae&&(R?ce.length===Ke.value.length&&Ke.value.every((U,le)=>ue(ce[le])===ue(U)):G(Ke.value,ce))){const U=Ke.filteredOptions[Le.current];if(U)return fe.findIndex(le=>ue(le)===ue(U))}return-1},Ce=Te.useCallback(()=>{if(!Ye)return;const G=vt();if(G!==-1){Le.current=G;return}const U=R?ce[0]:ce;if(fe.length===0||U==null){pe({diff:"reset"});return}if(K.current){if(U!=null){const le=fe[Le.current];if(R&&le&&ce.findIndex(ee=>V(le,ee))!==-1)return;const ve=fe.findIndex(ee=>V(ee,U));ve===-1?pe({diff:"reset"}):Qe({index:ve});return}if(Le.current>=fe.length-1){Qe({index:fe.length-1});return}Qe({index:Le.current})}},[fe.length,R?!1:ce,j,pe,Qe,Ye,ae,R]),Fe=c.useEventCallback(G=>{c.setRef(K,G),G&&Ce()});Te.useEffect(()=>{He&&Ce()},[Ce,He]);const Ie=G=>{at||(yt(!0),Mt(!0),H&&H(G))},We=(G,U)=>{at&&(yt(!1),Z&&Z(G,U))},dt=(G,U,le,ve)=>{if(R){if(ce.length===U.length&&ce.every((ee,qe)=>ee===U[qe]))return}else if(ce===U)return;W&&W(G,U,le,ve),Y(U)},Pe=Te.useRef(!1),tt=(G,U,le="selectOption",ve="options")=>{let ee=le,qe=U;if(R){qe=Array.isArray(ce)?ce.slice():[];const Ue=qe.findIndex(Ct=>V(U,Ct));Ue===-1?qe.push(U):ve!=="freeSolo"&&(qe.splice(Ue,1),ee="removeOption")}Ee(G,qe,ee),dt(G,qe,ee,{option:U}),!x&&(!G||!G.ctrlKey&&!G.metaKey)&&We(G,ee),(a===!0||a==="touch"&&Pe.current||a==="mouse"&&!Pe.current)&&te.current.blur()};function Ot(G,U){if(G===-1)return-1;let le=G;for(;;){if(U==="next"&&le===ce.length||U==="previous"&&le===-1)return-1;const ve=se?"data-item-index":"data-tag-index",ee=he.querySelector(`[${ve}="${le}"]`);if(!ee||!ee.hasAttribute("tabindex")||ee.disabled||ee.getAttribute("aria-disabled")==="true")le+=U==="next"?1:-1;else return le}}const kt=(G,U)=>{if(!R)return;ae===""&&We(G,"toggleInput");let le=ge;ge===-1?ae===""&&U==="previous"&&(le=ce.length-1):(le+=U==="next"?1:-1,le<0&&(le=0),le===ce.length&&(le=-1)),le=Ot(le,U),me(le),lt(le)},Rt=G=>{be.current=!0,Re(""),J&&J(G,"","clear"),dt(G,R?[]:null,"clear")},gn=G=>U=>{if(G.onKeyDown&&G.onKeyDown(U),!U.defaultMuiPrevented&&(ge!==-1&&!["ArrowLeft","ArrowRight"].includes(U.key)&&(me(-1),lt(-1)),U.which!==229))switch(U.key){case"Home":Ye&&A&&(U.preventDefault(),pe({diff:"start",direction:"next",reason:"keyboard",event:U}));break;case"End":Ye&&A&&(U.preventDefault(),pe({diff:"end",direction:"previous",reason:"keyboard",event:U}));break;case"PageUp":U.preventDefault(),pe({diff:-Pi,direction:"previous",reason:"keyboard",event:U}),Ie(U);break;case"PageDown":U.preventDefault(),pe({diff:Pi,direction:"next",reason:"keyboard",event:U}),Ie(U);break;case"ArrowDown":U.preventDefault(),pe({diff:1,direction:"next",reason:"keyboard",event:U}),Ie(U);break;case"ArrowUp":U.preventDefault(),pe({diff:-1,direction:"previous",reason:"keyboard",event:U}),Ie(U);break;case"ArrowLeft":!R&&se?lt(0):kt(U,"previous");break;case"ArrowRight":!R&&se?lt(-1):kt(U,"next");break;case"Enter":if(Le.current!==-1&&Ye){const le=fe[Le.current],ve=O?O(le):!1;if(U.preventDefault(),ve)return;tt(U,le,"selectOption"),o&&te.current.setSelectionRange(te.current.value.length,te.current.value.length)}else M&&ae!==""&&mt===!1&&(R&&U.preventDefault(),tt(U,ae,"createOption","freeSolo"));break;case"Escape":Ye?(U.preventDefault(),U.stopPropagation(),We(U,"escape")):d&&(ae!==""||R&&ce.length>0||se)&&(U.preventDefault(),U.stopPropagation(),Rt(U));break;case"Backspace":if(R&&!oe&&ae===""&&ce.length>0){const le=ge===-1?ce.length-1:ge,ve=ce.slice();ve.splice(le,1),dt(U,ve,"removeOption",{option:ce[le]})}!R&&se&&!oe&&(Y(null),lt(-1));break;case"Delete":if(R&&!oe&&ae===""&&ce.length>0&&ge!==-1){const le=ge,ve=ce.slice();ve.splice(le,1),dt(U,ve,"removeOption",{option:ce[le]})}!R&&se&&!oe&&(Y(null),lt(-1));break}},Ne=G=>{St(!0),re&&!be.current&&Ie(G)},ut=G=>{if(n(K)){te.current.focus();return}St(!1),Oe.current=!0,be.current=!1,l&&Le.current!==-1&&Ye?tt(G,fe[Le.current],"blur"):l&&M&&ae!==""?tt(G,ae,"blur","freeSolo"):u&&Ee(G,ce,"blur"),We(G,"blur")},Kt=G=>{const U=G.target.value;ae!==U&&(Re(U),Mt(!1),J&&J(G,U,"input")),U===""?!b&&!R&&dt(G,null,"clear"):Ie(G)},yn=G=>{const U=Number(G.currentTarget.getAttribute("data-option-index"));Le.current!==U&&Qe({event:G,index:U,reason:"mouse"})},ht=G=>{Qe({event:G,index:Number(G.currentTarget.getAttribute("data-option-index")),reason:"touch"}),Pe.current=!0},en=G=>{const U=Number(G.currentTarget.getAttribute("data-option-index"));tt(G,fe[U],"selectOption"),Pe.current=!1},xn=G=>U=>{const le=ce.slice();le.splice(G,1),dt(U,le,"removeOption",{option:ce[G]})},Qt=G=>{dt(G,null,"removeOption",{option:ce})},Ze=G=>{at?We(G,"toggleInput"):Ie(G)},Xe=G=>{G.currentTarget.contains(G.target)&&G.target.getAttribute("id")!==de&&G.preventDefault()},$t=G=>{G.currentTarget.contains(G.target)&&(te.current.focus(),ie&&Oe.current&&te.current.selectionEnd-te.current.selectionStart===0&&te.current.select(),Oe.current=!1)},tn=G=>{!v&&(ae===""||!at)&&Ze(G)};let Zt=M&&ae.length>0;Zt=Zt||(R?ce.length>0:ce!==null);let nn=fe;return P&&(nn=fe.reduce((G,U,le)=>{const ve=P(U);return G.length>0&&G[G.length-1].group===ve?G[G.length-1].options.push(U):G.push({key:le,index:le,group:ve,options:[U]}),G},[])),v&&Ve&&ut(),{getRootProps:(G={})=>({...G,onKeyDown:gn(G),onMouseDown:Xe,onClick:$t}),getInputLabelProps:()=>({id:`${de}-label`,htmlFor:de}),getInputProps:()=>({id:de,value:ae,onBlur:ut,onFocus:Ne,onChange:Kt,onMouseDown:tn,"aria-activedescendant":Ye?"":null,"aria-autocomplete":o?"both":"list","aria-controls":ze?`${de}-listbox`:void 0,"aria-expanded":ze,autoComplete:"off",ref:te,autoCapitalize:"none",spellCheck:"false",role:"combobox",disabled:v}),getClearProps:()=>({tabIndex:-1,type:"button",onClick:Rt}),getItemProps:({index:G=0}={})=>({...R&&{key:G},...se?{"data-item-index":G}:{"data-tag-index":G},tabIndex:-1,...!oe&&{onDelete:R?xn(G):Qt}}),getPopupIndicatorProps:()=>({tabIndex:-1,type:"button",onClick:Ze}),getTagProps:({index:G})=>({key:G,"data-tag-index":G,tabIndex:-1,...!oe&&{onDelete:xn(G)}}),getListboxProps:()=>({role:"listbox",id:`${de}-listbox`,"aria-labelledby":`${de}-label`,ref:Fe,onMouseDown:G=>{G.preventDefault()}}),getOptionProps:({index:G,option:U})=>{const le=(R?ce:[ce]).some(ee=>ee!=null&&V(U,ee)),ve=O?O(U):!1;return{key:E?.(U)??ue(U),tabIndex:-1,role:"option",id:`${de}-option-${G}`,onMouseMove:yn,onClick:en,onTouchStart:ht,"data-option-index":G,"aria-disabled":ve,"aria-selected":le}},id:de,inputValue:ae,value:ce,dirty:Zt,expanded:Ye&&he,popupOpen:Ye,focused:Ve||ge!==-1,anchorEl:he,setAnchorEl:we,focusedItem:ge,focusedTag:ge,groupedOptions:nn}}function _h(e){return c.generateUtilityClass("MuiListSubheader",e)}c.generateUtilityClasses("MuiListSubheader",["root","colorPrimary","colorInherit","gutters","inset","sticky"]);const Nh=e=>{const{classes:n,color:r,disableGutters:o,inset:i,disableSticky:l}=e,a={root:["root",r!=="default"&&`color${c.capitalize(r)}`,!o&&"gutters",i&&"inset",!l&&"sticky"]};return c.composeClasses(a,_h,n)},Ph=c.styled("li",{name:"MuiListSubheader",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,r.color!=="default"&&n[`color${c.capitalize(r.color)}`],!r.disableGutters&&n.gutters,r.inset&&n.inset,!r.disableSticky&&n.sticky]}})(c.memoTheme(({theme:e})=>({boxSizing:"border-box",lineHeight:"48px",listStyle:"none",color:(e.vars||e).palette.text.secondary,fontFamily:e.typography.fontFamily,fontWeight:e.typography.fontWeightMedium,fontSize:e.typography.pxToRem(14),variants:[{props:{color:"primary"},style:{color:(e.vars||e).palette.primary.main}},{props:{color:"inherit"},style:{color:"inherit"}},{props:({ownerState:n})=>!n.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:n})=>n.inset,style:{paddingLeft:72}},{props:({ownerState:n})=>!n.disableSticky,style:{position:"sticky",top:0,zIndex:1,backgroundColor:(e.vars||e).palette.background.paper}}]}))),Ys=Te.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiListSubheader"}),{className:i,color:l="default",component:a="li",disableGutters:u=!1,disableSticky:d=!1,inset:h=!1,...y}=o,b={...o,color:l,component:a,disableGutters:u,disableSticky:d,inset:h},x=Nh(b);return t.jsx(Ph,{as:a,className:c.clsx(x.root,i),ref:r,ownerState:b,...y})});Ys&&(Ys.muiSkipListHighlight=!0);const zh=c.createSvgIcon(t.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}));function Wh(e){return c.generateUtilityClass("MuiAutocomplete",e)}const Me=c.generateUtilityClasses("MuiAutocomplete",["root","expanded","fullWidth","focused","focusVisible","tag","tagSizeSmall","tagSizeMedium","hasPopupIcon","hasClearIcon","inputRoot","input","inputFocused","endAdornment","clearIndicator","popupIndicator","popupIndicatorOpen","popper","popperDisablePortal","paper","listbox","loading","noOptions","option","groupLabel","groupUl"]);var Wi,qi;const qh=e=>{const{classes:n,disablePortal:r,expanded:o,focused:i,fullWidth:l,hasClearIcon:a,hasPopupIcon:u,inputFocused:d,popupOpen:h,size:y}=e,b={root:["root",o&&"expanded",i&&"focused",l&&"fullWidth",a&&"hasClearIcon",u&&"hasPopupIcon"],inputRoot:["inputRoot"],input:["input",d&&"inputFocused"],tag:["tag",`tagSize${c.capitalize(y)}`],endAdornment:["endAdornment"],clearIndicator:["clearIndicator"],popupIndicator:["popupIndicator",h&&"popupIndicatorOpen"],popper:["popper",r&&"popperDisablePortal"],paper:["paper"],listbox:["listbox"],loading:["loading"],noOptions:["noOptions"],option:["option"],groupLabel:["groupLabel"],groupUl:["groupUl"]};return c.composeClasses(b,Wh,n)},Bh=c.styled("div",{name:"MuiAutocomplete",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e,{fullWidth:o,hasClearIcon:i,hasPopupIcon:l,inputFocused:a,size:u}=r;return[{[`& .${Me.tag}`]:n.tag},{[`& .${Me.tag}`]:n[`tagSize${c.capitalize(u)}`]},{[`& .${Me.inputRoot}`]:n.inputRoot},{[`& .${Me.input}`]:n.input},{[`& .${Me.input}`]:a&&n.inputFocused},n.root,o&&n.fullWidth,l&&n.hasPopupIcon,i&&n.hasClearIcon]}})({[`&.${Me.focused} .${Me.clearIndicator}`]:{visibility:"visible"},"@media (pointer: fine)":{[`&:hover .${Me.clearIndicator}`]:{visibility:"visible"}},[`& .${Me.tag}`]:{margin:3,maxWidth:"calc(100% - 6px)"},[`& .${Me.inputRoot}`]:{[`.${Me.hasPopupIcon}&, .${Me.hasClearIcon}&`]:{paddingRight:30},[`.${Me.hasPopupIcon}.${Me.hasClearIcon}&`]:{paddingRight:56},[`& .${Me.input}`]:{width:0,minWidth:30}},[`& .${c.inputClasses.root}`]:{paddingBottom:1,"& .MuiInput-input":{padding:"4px 4px 4px 0px"}},[`& .${c.inputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{[`& .${c.inputClasses.input}`]:{padding:"2px 4px 3px 0"}},[`& .${c.outlinedInputClasses.root}`]:{padding:9,[`.${Me.hasPopupIcon}&, .${Me.hasClearIcon}&`]:{paddingRight:39},[`.${Me.hasPopupIcon}.${Me.hasClearIcon}&`]:{paddingRight:65},[`& .${Me.input}`]:{padding:"7.5px 4px 7.5px 5px"},[`& .${Me.endAdornment}`]:{right:9}},[`& .${c.outlinedInputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{paddingTop:6,paddingBottom:6,paddingLeft:6,[`& .${Me.input}`]:{padding:"2.5px 4px 2.5px 8px"}},[`& .${c.filledInputClasses.root}`]:{paddingTop:19,paddingLeft:8,[`.${Me.hasPopupIcon}&, .${Me.hasClearIcon}&`]:{paddingRight:39},[`.${Me.hasPopupIcon}.${Me.hasClearIcon}&`]:{paddingRight:65},[`& .${c.filledInputClasses.input}`]:{padding:"7px 4px"},[`& .${Me.endAdornment}`]:{right:9}},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{paddingBottom:1,[`& .${c.filledInputClasses.input}`]:{padding:"2.5px 4px"}},[`& .${c.inputBaseClasses.hiddenLabel}`]:{paddingTop:8},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.hiddenLabel}`]:{paddingTop:0,paddingBottom:0,[`& .${Me.input}`]:{paddingTop:16,paddingBottom:17}},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.hiddenLabel}.${c.inputBaseClasses.sizeSmall}`]:{[`& .${Me.input}`]:{paddingTop:8,paddingBottom:9}},[`& .${Me.input}`]:{flexGrow:1,textOverflow:"ellipsis",opacity:0},variants:[{props:{fullWidth:!0},style:{width:"100%"}},{props:{size:"small"},style:{[`& .${Me.tag}`]:{margin:2,maxWidth:"calc(100% - 4px)"}}},{props:{inputFocused:!0},style:{[`& .${Me.input}`]:{opacity:1}}},{props:{multiple:!0},style:{[`& .${Me.inputRoot}`]:{flexWrap:"wrap"}}}]}),Vh=c.styled("div",{name:"MuiAutocomplete",slot:"EndAdornment"})({position:"absolute",right:0,top:"50%",transform:"translate(0, -50%)"}),Hh=c.styled(c.IconButton,{name:"MuiAutocomplete",slot:"ClearIndicator"})({marginRight:-2,padding:4,visibility:"hidden"}),Uh=c.styled(c.IconButton,{name:"MuiAutocomplete",slot:"PopupIndicator",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.popupIndicator,r.popupOpen&&n.popupIndicatorOpen]}})({padding:2,marginRight:-2,variants:[{props:{popupOpen:!0},style:{transform:"rotate(180deg)"}}]}),Gh=c.styled(c.Popper,{name:"MuiAutocomplete",slot:"Popper",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${Me.option}`]:n.option},n.popper,r.disablePortal&&n.popperDisablePortal]}})(c.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.modal,variants:[{props:{disablePortal:!0},style:{position:"absolute"}}]}))),Yh=c.styled(c.Paper,{name:"MuiAutocomplete",slot:"Paper"})(c.memoTheme(({theme:e})=>({...e.typography.body1,overflow:"auto"}))),Kh=c.styled("div",{name:"MuiAutocomplete",slot:"Loading"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Qh=c.styled("div",{name:"MuiAutocomplete",slot:"NoOptions"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Zh=c.styled("ul",{name:"MuiAutocomplete",slot:"Listbox"})(c.memoTheme(({theme:e})=>({listStyle:"none",margin:0,padding:"8px 0",maxHeight:"40vh",overflow:"auto",position:"relative",[`& .${Me.option}`]:{minHeight:48,display:"flex",overflow:"hidden",justifyContent:"flex-start",alignItems:"center",cursor:"pointer",paddingTop:6,boxSizing:"border-box",outline:"0",WebkitTapHighlightColor:"transparent",paddingBottom:6,paddingLeft:16,paddingRight:16,[e.breakpoints.up("sm")]:{minHeight:"auto"},[`&.${Me.focused}`]:{backgroundColor:(e.vars||e).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},'&[aria-disabled="true"]':{opacity:(e.vars||e).palette.action.disabledOpacity,pointerEvents:"none"},[`&.${Me.focusVisible}`]:{backgroundColor:(e.vars||e).palette.action.focus},'&[aria-selected="true"]':{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity),[`&.${Me.focused}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:(e.vars||e).palette.action.selected}},[`&.${Me.focusVisible}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.focusOpacity}`)}}}}))),Xh=c.styled(Ys,{name:"MuiAutocomplete",slot:"GroupLabel"})(c.memoTheme(({theme:e})=>({backgroundColor:(e.vars||e).palette.background.paper,top:-8}))),Jh=c.styled("ul",{name:"MuiAutocomplete",slot:"GroupUl"})({padding:0,[`& .${Me.option}`]:{paddingLeft:24}}),Ks=Te.forwardRef(function(n,r){const o=c.useDefaultProps({props:n,name:"MuiAutocomplete"}),{autoComplete:i=!1,autoHighlight:l=!1,autoSelect:a=!1,blurOnSelect:u=!1,ChipProps:d,className:h,clearIcon:y=Wi||(Wi=t.jsx(zh,{fontSize:"small"})),clearOnBlur:b=!o.freeSolo,clearOnEscape:x=!1,clearText:v="Clear",closeText:k="Close",componentsProps:C,defaultValue:S=o.multiple?[]:null,disableClearable:j=!1,disableCloseOnSelect:M=!1,disabled:O=!1,disabledItemsFocusable:E=!1,disableListWrap:$=!1,disablePortal:P=!1,filterOptions:A,filterSelectedOptions:B=!1,forcePopupIcon:D="auto",freeSolo:_=!1,fullWidth:V=!1,getLimitTagsText:R=Ae=>`+${Ae}`,getOptionDisabled:W,getOptionKey:Z,getOptionLabel:ne,isOptionEqualToValue:J,groupBy:H,handleHomeEndKeys:Q=!o.freeSolo,id:re,includeInputInList:z=!1,inputValue:oe,limitTags:se=-1,ListboxComponent:ie,ListboxProps:De,loading:de=!1,loadingText:ue="Loading…",multiple:be=!1,noOptionsText:Oe="No options",onChange:te,onClose:K,onHighlightChange:he,onInputChange:we,onOpen:ge,open:me,openOnFocus:ye=!1,openText:Le="Open",options:st,PaperComponent:ce,PopperComponent:Y,popupIcon:ae=qi||(qi=t.jsx(c.ArrowDropDownIcon,{})),readOnly:Re=!1,renderGroup:Ve,renderInput:St,renderOption:Ee,renderTags:at,renderValue:yt,selectOnFocus:xt=!o.freeSolo,size:Mt="medium",slots:mt={},slotProps:Ye={},value:fe,...Ke}=o,{getRootProps:ze,getInputProps:lt,getInputLabelProps:ct,getPopupIndicatorProps:Qe,getClearProps:pe,getItemProps:He,getListboxProps:vt,getOptionProps:Ce,value:Fe,dirty:Ie,expanded:We,id:dt,popupOpen:Pe,focused:tt,focusedItem:Ot,anchorEl:kt,setAnchorEl:Rt,inputValue:gn,groupedOptions:Ne}=Lh({...o,componentName:"Autocomplete"}),ut=!j&&!O&&Ie&&!Re,Kt=(!_||D===!0)&&D!==!1,{onMouseDown:yn}=lt(),{ref:ht,...en}=vt(),Qt=ne||(Ae=>Ae.label??Ae),Ze={...o,disablePortal:P,expanded:We,focused:tt,fullWidth:V,getOptionLabel:Qt,hasClearIcon:ut,hasPopupIcon:Kt,inputFocused:Ot===-1,popupOpen:Pe,size:Mt},Xe=qh(Ze),$t={slots:{paper:ce,popper:Y,...mt},slotProps:{chip:d,listbox:De,...C,...Ye}},[tn,Zt]=c.useSlot("listbox",{elementType:Zh,externalForwardedProps:$t,ownerState:Ze,className:Xe.listbox,additionalProps:en,ref:ht}),[nn,G]=c.useSlot("paper",{elementType:c.Paper,externalForwardedProps:$t,ownerState:Ze,className:Xe.paper}),[U,le]=c.useSlot("popper",{elementType:c.Popper,externalForwardedProps:$t,ownerState:Ze,className:Xe.popper,additionalProps:{disablePortal:P,style:{width:kt?kt.clientWidth:null},role:"presentation",anchorEl:kt,open:Pe}});let ve;const ee=Ae=>({className:Xe.tag,disabled:O,...He(Ae)});if(be?Fe.length>0&&(at?ve=at(Fe,ee,Ze):yt?ve=yt(Fe,ee,Ze):ve=Fe.map((Ae,zt)=>{const{key:gt,...qt}=ee({index:zt});return t.jsx(c.Chip,{label:Qt(Ae),size:Mt,...qt,...$t.slotProps.chip},gt)})):yt&&Fe!=null&&(ve=yt(Fe,ee,Ze)),se>-1&&Array.isArray(ve)){const Ae=ve.length-se;!tt&&Ae>0&&(ve=ve.splice(0,se),ve.push(t.jsx("span",{className:Xe.tag,children:R(Ae)},ve.length)))}const Ue=Ve||(Ae=>t.jsxs("li",{children:[t.jsx(Xh,{className:Xe.groupLabel,ownerState:Ze,component:"div",children:Ae.group}),t.jsx(Jh,{className:Xe.groupUl,ownerState:Ze,children:Ae.children})]},Ae.key)),vn=Ee||((Ae,zt)=>{const{key:gt,...qt}=Ae;return t.jsx("li",{...qt,children:Qt(zt)},gt)}),zn=(Ae,zt)=>{const gt=Ce({option:Ae,index:zt});return vn({...gt,className:Xe.option},Ae,{selected:gt["aria-selected"],index:zt,inputValue:gn},Ze)},Wn=$t.slotProps.clearIndicator,Dr=$t.slotProps.popupIndicator;return t.jsxs(Te.Fragment,{children:[t.jsx(Bh,{ref:r,className:c.clsx(Xe.root,h),ownerState:Ze,...ze(Ke),children:St({id:dt,disabled:O,fullWidth:!0,size:Mt==="small"?"small":void 0,InputLabelProps:ct(),InputProps:{ref:Rt,className:Xe.inputRoot,startAdornment:ve,onMouseDown:Ae=>{Ae.target===Ae.currentTarget&&yn(Ae)},...(ut||Kt)&&{endAdornment:t.jsxs(Vh,{className:Xe.endAdornment,ownerState:Ze,children:[ut?t.jsx(Hh,{...pe(),"aria-label":v,title:v,ownerState:Ze,...Wn,className:c.clsx(Xe.clearIndicator,Wn?.className),children:y}):null,Kt?t.jsx(Uh,{...Qe(),disabled:O,"aria-label":Pe?k:Le,title:Pe?k:Le,ownerState:Ze,...Dr,className:c.clsx(Xe.popupIndicator,Dr?.className),children:ae}):null]})}},inputProps:{className:Xe.input,disabled:O,readOnly:Re,...lt()}})}),kt?t.jsx(Gh,{as:U,...le,children:t.jsxs(Yh,{as:nn,...G,children:[de&&Ne.length===0?t.jsx(Kh,{className:Xe.loading,ownerState:Ze,children:ue}):null,Ne.length===0&&!_&&!de?t.jsx(Qh,{className:Xe.noOptions,ownerState:Ze,role:"presentation",onMouseDown:Ae=>{Ae.preventDefault()},children:Oe}):null,Ne.length>0?t.jsx(tn,{as:ie,...Zt,children:Ne.map((Ae,zt)=>H?Ue({key:Ae.key,group:Ae.group,children:Ae.options.map((gt,qt)=>zn(gt,Ae.index+qt))}):zn(Ae,zt))}):null]})}):null]})});c.dayjs.extend(c.utc);function js(e){switch(e){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 ef(e){return e==="DateMinMax"}function Ms(e){return e==="Between"}function tf({spec:e,values:n,selection:r,onChange:o,retrievalFn:i}){const l=()=>r?.matchType?r.matchType:e.defaultMatchType?e.defaultMatchType:e.filterType==="DateMinMax"?"Between":js(e.filterType)[0]||"Equals",[a,u]=T.useState(l()),[d,h]=T.useState(r?.value??""),[y,b]=T.useState(r?.value2??""),[x,v]=T.useState([]),[k,C]=T.useState(!1),[S,j]=T.useState(""),[M,O]=T.useState(!1),[E,$]=T.useState(!1),P=T.useRef(null),A=T.useRef(0),[B,D]=T.useState(!1);T.useEffect(()=>{if(e.filterType!=="Retrieval"||!i)return;const z=S.trim();if(z.length<=2){v([]),O(!1);return}return P.current&&clearTimeout(P.current),P.current=setTimeout(async()=>{A.current+=1;const oe=A.current;C(!0);try{const se=await i(z,e);oe===A.current&&v(se)}catch(se){oe===A.current&&(console.error("Retrieval failed",se),v([]))}finally{oe===A.current&&(C(!1),O(!0))}},500),()=>{P.current&&clearTimeout(P.current)}},[S,e,i]),T.useEffect(()=>{r===null?(h(""),b(""),u(e.defaultMatchType??(e.filterType==="DateMinMax"?"Between":js(e.filterType)[0]||"Equals"))):r&&(u(r.matchType),h(r.value??""),b(r.value2??""))},[r,e.filterType,e.defaultMatchType]);const _=js(e.filterType),V=ef(e.filterType),R=Ms(a),W=V&&n.length>=2&&n[0].value instanceof Date?c.dayjs.utc(n[0].value):void 0,Z=V&&n.length>=2&&n[1].value instanceof Date?c.dayjs.utc(n[1].value):void 0,ne=e.filterType==="MinMax"&&n.length>=2&&typeof n[0].value=="number"?n[0].value:void 0,J=e.filterType==="MinMax"&&n.length>=2&&typeof n[1].value=="number"?n[1].value:void 0;if(_.length===0)return null;const H=z=>{const oe=z.target.value;u(oe),Ms(oe)||b(""),d&&o({dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:oe,value:d,...Ms(oe)&&y&&{value2:y}})},Q=(z,oe)=>{h(z??""),oe!==void 0&&b(oe??"");const se=Array.isArray(z)&&z.length===0;o(!se&&z!==""&&z!==null&&z!==void 0?{dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:a,value:z,...R&&oe&&{value2:oe}}:null)},re=()=>{h(""),b(""),o(null)};return t.jsxs(Ge,{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:[t.jsxs(Ge,{sx:{fontWeight:600,color:e.required&&!r?"error.main":"text.primary"},children:[e.label??e.dimensionName,e.required&&t.jsx(Ge,{component:"span",sx:{color:r?"text.secondary":"error.main",fontWeight:400,fontSize:"0.7rem",ml:.5},children:"(required)"})]}),e.filterType!=="Boolean"&&!e.defaultMatchType&&_.length>1&&t.jsxs(c.FormControl,{size:"small",fullWidth:!0,children:[t.jsx(c.InputLabel,{children:"Match Type"}),t.jsx(c.Select,{value:a,label:"Match Type",onChange:H,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:_.map(z=>t.jsx(et,{value:z,children:z},z))})]}),e.filterType==="Star"&&a==="Equals"&&t.jsx(Ks,{multiple:!0,size:"small",options:n,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(d)?d.map(z=>n.find(oe=>oe.value===z)||z):d?[n.find(z=>z.value===d)||d]:[],onChange:(z,oe)=>{const se=oe.map(ie=>typeof ie=="string"?ie:ie&&typeof ie=="object"&&"value"in ie?ie.value:ie);Q(se)},noOptionsText:"No matches found",renderInput:z=>t.jsx(c.TextField,{...z,size:"small",label:"Values",placeholder:"Select values..."}),freeSolo:!e.values||e.values.length===0,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),e.filterType==="Star"&&a==="Contains"&&t.jsx(c.TextField,{size:"small",label:"Search Text",value:d,onChange:z=>h(z.target.value),onBlur:()=>Q(d),onKeyDown:z=>{z.key==="Enter"&&Q(d)},placeholder:"Enter text to search...",fullWidth:!0}),e.filterType==="Boolean"&&t.jsxs(c.FormControl,{size:"small",fullWidth:!0,children:[t.jsx(c.InputLabel,{children:"Value"}),t.jsxs(c.Select,{value:d===!0?"true":d===!1?"false":"",label:"Value",onChange:z=>{const oe=z.target.value;oe==="true"?Q(!0):oe==="false"?Q(!1):re()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[t.jsx(et,{value:"",children:t.jsx("em",{children:"Blank"})}),t.jsx(et,{value:"true",children:"True"}),t.jsx(et,{value:"false",children:"False"})]})]}),e.filterType==="Retrieval"&&a==="Semantic Search"&&t.jsx(Ks,{multiple:!0,size:"small",options:x,loading:k,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(d)?d.map(z=>x.find(se=>se.value===z)||{value:z}):d?[{value:d}]:[],onInputChange:(z,oe)=>{j(oe)},onChange:(z,oe)=>{const se=oe.map(ie=>typeof ie=="string"?ie:ie&&typeof ie=="object"&&"value"in ie?ie.value:ie);Q(se)},noOptionsText:S.trim().length<=2?"Type at least 3 characters to search":"No matches found",renderInput:z=>t.jsx(c.TextField,{...z,size:"small",label:"Search Values",placeholder:"Type to search...",onFocus:()=>$(!0),onBlur:()=>$(!1),helperText:E&&!k&&M&&x.length===0?"No matches found":void 0,InputProps:{...z.InputProps,endAdornment:t.jsxs(t.Fragment,{children:[k?t.jsx(c.CircularProgress,{color:"inherit",size:20}):null,z.InputProps.endAdornment]})}}),freeSolo:!0,filterOptions:z=>z,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),e.filterType==="MinMax"&&!R&&t.jsx(c.TextField,{size:"small",type:"number",label:"Value",value:d,onChange:z=>Q(parseFloat(z.target.value)||""),onFocus:()=>D(!0),onBlur:()=>D(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:ne,max:J},helperText:B&&ne!==void 0&&J!==void 0?`Valid range: [${ne} - ${J}]`:void 0}),e.filterType==="MinMax"&&R&&t.jsxs(Ge,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ge,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(c.TextField,{size:"small",type:"number",label:"From",value:d,onChange:z=>Q(parseFloat(z.target.value)||"",y),onFocus:()=>D(!0),onBlur:()=>D(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:ne,max:y||J}}),t.jsx(Ge,{children:"to"}),t.jsx(c.TextField,{size:"small",type:"number",label:"To",value:y,onChange:z=>Q(d,parseFloat(z.target.value)||""),onFocus:()=>D(!0),onBlur:()=>D(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:d||ne,max:J}})]}),B&&ne!==void 0&&J!==void 0&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",ne," - ",J,"]"]})]}),V&&!R&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsx(c.DatePicker,{label:"Date",value:d instanceof Date?c.dayjs.utc(d):null,onChange:z=>{z===null?Q(null):z.isValid()&&Q(z.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?void 0:W,maxDate:d instanceof Date?void 0:Z,referenceDate:a==="After"&&W?W:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>D(!0),onBlur:()=>D(!1),helperText:B&&W&&Z?`Valid range: [${W.format("YYYY-MM-DD")} - ${Z.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),V&&R&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsxs(Ge,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ge,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(Ge,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"From",value:d instanceof Date?c.dayjs.utc(d):null,onChange:z=>{z===null?Q(null,y):z.isValid()&&Q(z.utc().toDate(),y)},timezone:"UTC",minDate:d instanceof Date?void 0:W,maxDate:y instanceof Date?c.dayjs.utc(y):d instanceof Date?void 0:Z,referenceDate:W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>D(!0),onBlur:()=>D(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),t.jsx(Ge,{children:"to"}),t.jsx(Ge,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"To",value:y instanceof Date?c.dayjs.utc(y):null,onChange:z=>{z===null?Q(d,null):z.isValid()&&Q(d,z.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?c.dayjs.utc(d):y instanceof Date?void 0:W,maxDate:y instanceof Date?void 0:Z,referenceDate:d instanceof Date?c.dayjs.utc(d):W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>D(!0),onBlur:()=>D(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),B&&W&&Z&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",W.format("YYYY-MM-DD")," -"," ",Z.format("YYYY-MM-DD"),"]"]})]})})]})}function os(e,n){const{matchType:r,value:o,value2:i}=n;if(Array.isArray(o))return r!=="Equals"&&r!=="Semantic Search"||o.length===0?"":`(${o.map(a=>`${e} = ${c.formatMalloyValue(a)}`).join(" or ")})`;switch(r){case"Equals":case"Semantic Search":return`${e} = ${c.formatMalloyValue(o)}`;case"Contains":if(typeof o=="string"){const l=nd.StringFilterExpression.unparse({operator:"contains",values:[o]});return`${e} ~ ${c.malloyFilterLiteral(l)}`}return`${e} = ${c.formatMalloyValue(o)}`;case"After":case"Greater Than":return`${e} > ${c.formatMalloyValue(o)}`;case"Before":case"Less Than":return`${e} < ${c.formatMalloyValue(o)}`;case"Between":return i!==void 0?`${e} >= ${c.formatMalloyValue(o)} and ${e} <= ${c.formatMalloyValue(i)}`:`${e} >= ${c.formatMalloyValue(o)}`;default:return""}}function nf(e){const n=new Set,r=e.schema?.fields;if(!r)return n;for(const o of r)"kind"in o&&o.kind==="join"&&o.name&&n.add(o.name);return n}function rf(e){if(!e)return null;for(const n of e)if(n.startsWith("##(filters)")){const r=n.slice(11).trim();try{const o=JSON.parse(r);if(Array.isArray(o)){const i=[];for(const l of o)if(typeof l=="string"){const a=l.indexOf(".");a>0&&a<l.length-1&&i.push({source:l.substring(0,a),dimension:l.substring(a+1)})}if(i.length>0)return{filters:i}}}catch(o){console.error(`Failed to parse "${n}" annotation:`,o)}}return null}function il(e){if(e.startsWith("#(filter)")){const n=e.slice(9).trim();try{const r=JSON.parse(n);if(r.type)return r}catch(r){console.error(`Failed to parse "${e}" annotation:`,r)}}return null}function sf(e){const n=e.match(/^#\s*label\s*=\s*"([^"]+)"/);return n?n[1]:null}function of(e){const n=new Map;let r="";for(const o of e)if(o.type==="code"){if(!r&&o.text){const l=o.text.split(`
|
|
4
|
+
`).map(a=>a.trim()).find(a=>a.startsWith("import "))?.match(/['"]([^'"\n]+)['"]/);l&&(r=l[1])}if(o.newSources&&o.newSources.length>0)for(const i of o.newSources)try{const l=JSON.parse(i);l.name&&n.set(l.name,l)}catch(l){console.error("Failed to parse SourceInfo:",l)}}return{sourceInfoMap:n,modelPath:r}}function af(e,n,r){const o=[];for(const{source:i,dimension:l}of n){const a=e.get(i);if(!a){console.warn(`Source "${i}" not found in notebook sources`),o.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}const u=a.schema?.fields;if(!u){o.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}const d=u.find(b=>b.name===l);if(!d){console.warn(`Dimension "${l}" not found in source "${i}"`),o.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}let h="Star",y;if("annotations"in d&&d.annotations){for(const b of d.annotations)if(b.value){const x=il(b.value);x&&(h=x.type);const v=sf(b.value);v&&(y=v)}}o.push({source:i,model:r,dimensionName:l,filterType:h,label:y})}return o}function lf(e,n,r){return e.length===0?"":e.map(i=>{const{dimensionName:l,source:a}=i,d=a&&a!==r?`\`${a}\`.\`${l}\``:`\`${l}\``;return os(d,i)}).filter(i=>i.length>0).join(" and ")}function cf(e){const n=e.match(/run\s*:\s*(\w+)\s*->/);if(n)return n[1];const r=e.match(/^\s*(\w+)\s*->/m);return r?r[1]:null}function uf(e,n){return`${e.trimEnd()} + {where: ${n}}`}const df=c.createSvgIcon(t.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"})),al=e=>{if(!e)return"Explore semantic models, run queries, and build reports";const n=e.replace(/^#+\s+/gm,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/`([^`]+)`/g,"$1").trim(),o=n.split(/\n\s*\n/)[1]||n;if(o.length<=120)return o;const i=o.substring(0,120).split(" ");return i.pop(),i.join(" ")+"..."},ll=(e,n)=>{const r=(e.readme||void 0)?.split(`
|
|
5
5
|
`)??[];return r.length===0&&(r.push(`# ${e.name}`),r.push("")),(e.readme?.length??0)>0&&n?r.splice(2,1,n):n&&r.push(n),r.join(`
|
|
6
|
-
`)};function Bi(){const[e,n]=j.useState(!1),{apiClients:r}=q.useServer(),o=()=>{n(!0)},i=()=>{n(!1)},l=Nn({mutationFn(u){return r.environments.createEnvironment({name:u.name,readme:ol({name:u.name,readme:""},u.description)})},success:"Environment created",invalidates:[["environments"]],closeDialog:i,resource:"environment",action:"create"}),a=async u=>{u.preventDefault();const d=new FormData(u.currentTarget),h=d.get("name")?.toString(),y=d.get("description")?.toString();if(!h)throw new Error("Name is required");l.mutate({name:h,description:y})};return t.jsxs(j.Fragment,{children:[t.jsx(c.AddButton,{label:"Environment",onClick:o}),t.jsx(c.AppDialog,{open:e,onClose:i,title:"New environment",description:"An environment holds packages and the connections they query through.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:l.isPending,onClick:i,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"environment-form",variant:"contained",loading:l.isPending,children:"Create environment"})]}),children:t.jsx("form",{onSubmit:a,id:"environment-form",children:t.jsxs(ss,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(c.TextField,{id:"description",name:"description",label:"Description",placeholder:"Explore semantic models, run queries, and build reports",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}})]})})}),l.notice]})}function of({environment:e,onCloseDialog:n}){const[r,o]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{o(!0)},a=()=>{o(!1),n()},u=Nn({mutationFn:()=>i.environments.deleteEnvironment(e.name),success:"Environment deleted",invalidates:[["environments"]],closeDialog:a,resource:"environment",action:"delete"});return t.jsxs(j.Fragment,{children:[t.jsxs(p.MenuItem,{onClick:l,children:[t.jsx(p.ListItemIcon,{children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:r,onClose:a,title:"Delete environment",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:a,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>u.mutate(),loading:u.isPending,children:"Delete environment"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:e.name}),"? Its packages stop being served and this cannot be undone."]})}),u.notice]})}function af({environment:e,onCloseDialog:n}){const[r,o]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{o(!0)},a=()=>{o(!1),n()},u=Nn({mutationFn(h){return i.environments.updateEnvironment(e.name,{name:e.name,readme:ol({name:e.name,readme:e.readme},h.description)})},success:"Environment updated",invalidates:[["environments"]],closeDialog:a,resource:"environment",action:"update"}),d=h=>{h.preventDefault();const b=new FormData(h.currentTarget).get("description")?.toString();u.mutate({description:b})};return t.jsxs(j.Fragment,{children:[t.jsxs(p.MenuItem,{onClick:l,children:[t.jsx(p.ListItemIcon,{children:t.jsx(Pt.Edit,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:r,onClose:a,title:"Edit environment",description:"What this environment is, for the people who open it.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:u.isPending,onClick:a,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"environment-form",variant:"contained",loading:u.isPending,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:d,id:"environment-form",children:t.jsxs(ss,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:e.name,InputLabelProps:{shrink:!0}}),t.jsx(c.TextField,{id:"description",name:"description",label:"Description",type:"text",fullWidth:!0,size:"small",defaultValue:sl(e.readme),InputLabelProps:{shrink:!0}})]})})}),u.notice]})}const lf=[{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:Vt.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:Vt.mcpAgents},{title:"Surface",body:"Reports declared in Malloy, laid out as a grid or read top to bottom, and no-build HTML data apps, all shipped inside the package, plus this Console for browsing them.",href:Vt.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:Vt.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:Vt.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:Vt.connections}];function cf({href:e,children:n}){return t.jsx(p.Box,{component:"a",href:e,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary",textDecoration:"underline"},children:n})}function uf({onClickEnvironment:e}){const{apiClients:n,mutable:r}=q.useServer(),{data:o,isSuccess:i,isError:l,error:a}=c.useQueryWithApiError({queryKey:["environments"],queryFn:()=>n.environments.listEnvironments()});if(l)return t.jsx(c.ApiErrorDisplay,{error:a,context:"Environments List"});if(!i)return t.jsx(c.Loading,{text:"Loading environments..."});const u=o.data??[];return t.jsxs(p.Container,{maxWidth:"md",sx:{py:6},children:[t.jsxs(p.Box,{sx:{mb:5},children:[t.jsx(p.Typography,{variant:"h3",component:"h1",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Publisher"}),t.jsx(p.Typography,{variant:"body1",color:"text.secondary",sx:{mb:3},children:"The analytics engine for Malloy."}),t.jsx(p.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."})]}),t.jsx(p.Grid,{container:!0,spacing:4,sx:{mb:5},children:lf.map(d=>t.jsx(p.Grid,{size:{xs:12,sm:6},children:t.jsxs(p.Stack,{spacing:1,children:[t.jsx(p.Typography,{variant:"body2",component:"a",href:d.href,target:"_blank",rel:"noopener noreferrer",sx:{fontWeight:500,color:"text.primary",textDecoration:"none","&:hover":{textDecoration:"underline"}},children:d.title}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{lineHeight:1.6},children:d.body})]})},d.title))}),t.jsx(p.Divider,{sx:{my:4}}),u.length>0?t.jsx(Nt,{title:"Environments",count:u.length,description:"Published environments available on this server",...r?{action:t.jsx(Bi,{})}:{},children:t.jsx(p.Stack,{children:u.map(d=>t.jsx(df,{environment:d,...e?{onClickEnvironment:e}:{}},d.name))})}):t.jsxs(p.Box,{sx:{mb:4},children:[t.jsx(p.Typography,{variant:"h5",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Get started"}),t.jsx(p.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."}),r?t.jsx(Bi,{}):t.jsx(p.Button,{variant:"contained",color:"primary",href:Vt.publishing,target:"_blank",rel:"noopener noreferrer",children:"Learn how to create models"})]}),t.jsx(p.Divider,{sx:{my:4}}),t.jsxs(p.Typography,{variant:"body2",color:"text.secondary",sx:{maxWidth:720,lineHeight:1.6,mt:2},children:["Join the"," ",t.jsx(cf,{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 df({environment:e,onClickEnvironment:n}){const{mutable:r}=q.useServer(),[o,i]=j.useState(null),l=!!o,a=sl(e.readme),u=h=>{h.stopPropagation(),i(h.currentTarget)},d=()=>i(null);return t.jsx(rs,{icon:t.jsx(sf,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.environment,label:e.name??"",ariaLabel:e.name??"",...a?{description:a}:{},...e.name&&n?{onClick:h=>n(`/${e.name}/`,h)}:{},...r?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(p.IconButton,{size:"small",onClick:u,"aria-label":`Environment actions for ${e.name}`,children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(p.Menu,{anchorEl:o,open:l,onClose:d,onClick:h=>h.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[t.jsx(af,{environment:e,onCloseDialog:d}),t.jsx(of,{environment:e,onCloseDialog:d})]})]})}:{}})}var an={},jt={},tr={},ln={},Ms={},Vi;function hf(){return Vi||(Vi=1,Object.defineProperty(Ms,"__esModule",{value:!0})),Ms}var nr={},rr={},Hi;function mn(){if(Hi)return rr;Hi=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.CronField=void 0;let e=class il{#e=!1;#n=!1;#o=!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(r,o={rawValue:""}){if(!Array.isArray(r))throw new Error(`${this.constructor.name} Validation error, values is not an array`);if(!(r.length>0))throw new Error(`${this.constructor.name} Validation error, values contains no values`);this.options={...o,rawValue:o.rawValue??""},this.#s=r.sort(il.sorter),this.#o=this.options.wildcard!==void 0?this.options.wildcard:this.#r(),this.#e=this.options.rawValue.includes("L")||r.includes("L"),this.#n=this.options.rawValue.includes("?")||r.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.#o}get values(){return this.#s}static sorter(r,o){const i=typeof r=="number",l=typeof o=="number";return i&&l?r-o:!i&&!l?r.localeCompare(o):i?-1:1}static findNearestValueInList(r,o,i){if(i){for(let l=r.length-1;l>=0;l--)if(r[l]<o)return r[l];return null}for(let l=0;l<r.length;l++)if(r[l]>o)return r[l];return null}findNearestValue(r,o){return this.constructor.findNearestValueInList(this.values,r,o)}serialize(){return{wildcard:this.#o,values:this.#s}}validate(){let r;const o=this.chars.length>0?` or chars ${this.chars.join("")}`:"",i=d=>h=>new RegExp(`^\\d{0,2}${h}$`).test(d),l=d=>(r=d,typeof d=="number"?d>=this.min&&d<=this.max:this.chars.some(i(d)));if(!this.#s.every(l))throw new Error(`${this.constructor.name} Validation error, got value ${r} expected range ${this.min}-${this.max}${o}`);const u=this.#s.find((d,h)=>this.#s.indexOf(d)!==h);if(u)throw new Error(`${this.constructor.name} Validation error, duplicate values found: ${u}`)}#r(){return this.options.rawValue.length>0?["*","?"].includes(this.options.rawValue):Array.from({length:this.max-this.min+1},(r,o)=>o+this.min).every(r=>this.#s.includes(r))}};return rr.CronField=e,rr}var Ui;function ff(){if(Ui)return nr;Ui=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.CronDayOfMonth=void 0;const e=mn(),n=1,r=31,o=Object.freeze(["L"]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}static get validChars(){return/^[?,*\dLH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}};return nr.CronDayOfMonth=i,nr}var sr={},Gi;function mf(){if(Gi)return sr;Gi=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.CronDayOfWeek=void 0;const e=mn(),n=0,r=7,o=Object.freeze(["L"]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}static get validChars(){return/^[?,*\dLH#/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}get nthDay(){return this.options.nthDayOfWeek??0}};return sr.CronDayOfWeek=i,sr}var or={},Yi;function pf(){if(Yi)return or;Yi=1,Object.defineProperty(or,"__esModule",{value:!0}),or.CronHour=void 0;const e=mn(),n=0,r=23,o=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}};return or.CronHour=i,or}var ir={},Ki;function gf(){if(Ki)return ir;Ki=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.CronMinute=void 0;const e=mn(),n=0,r=59,o=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}};return ir.CronMinute=i,ir}var ar={},Es={},bt={},Qi;function yf(){if(Qi)return bt;Qi=1,Object.defineProperty(bt,"__esModule",{value:!0});class e extends Error{}class n extends e{constructor(s){super(`Invalid DateTime: ${s.toMessage()}`)}}class r extends e{constructor(s){super(`Invalid Interval: ${s.toMessage()}`)}}class o extends e{constructor(s){super(`Invalid Duration: ${s.toMessage()}`)}}class i extends e{}class l extends e{constructor(s){super(`Invalid unit ${s}`)}}class a extends e{}class u extends e{constructor(){super("Zone is an abstract class")}}const d="numeric",h="short",y="long",b={year:d,month:d,day:d},x={year:d,month:h,day:d},v={year:d,month:h,day:d,weekday:h},k={year:d,month:y,day:d},C={year:d,month:y,day:d,weekday:y},S={hour:d,minute:d},T={hour:d,minute:d,second:d},O={hour:d,minute:d,second:d,timeZoneName:h},M={hour:d,minute:d,second:d,timeZoneName:y},E={hour:d,minute:d,hourCycle:"h23"},R={hour:d,minute:d,second:d,hourCycle:"h23"},P={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:h},F={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:y},B={year:d,month:d,day:d,hour:d,minute:d},D={year:d,month:d,day:d,hour:d,minute:d,second:d},_={year:d,month:h,day:d,hour:d,minute:d},V={year:d,month:h,day:d,hour:d,minute:d,second:d},$={year:d,month:h,day:d,weekday:h,hour:d,minute:d},W={year:d,month:y,day:d,hour:d,minute:d,timeZoneName:h},Z={year:d,month:y,day:d,hour:d,minute:d,second:d,timeZoneName:h},ne={year:d,month:y,day:d,weekday:y,hour:d,minute:d,timeZoneName:y},J={year:d,month:y,day:d,weekday:y,hour:d,minute:d,second:d,timeZoneName:y};class H{get type(){throw new u}get name(){throw new u}get ianaName(){return this.name}get isUniversal(){throw new u}offsetName(s,f){throw new u}formatOffset(s,f){throw new u}offset(s){throw new u}equals(s){throw new u}get isValid(){throw new u}}let Q=null;class re extends H{static get instance(){return Q===null&&(Q=new re),Q}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(s,{format:f,locale:g}){return Fo(s,f,g)}formatOffset(s,f){return Vn(this.offset(s),f)}offset(s){return-new Date(s).getTimezoneOffset()}equals(s){return s.type==="system"}get isValid(){return!0}}const z=new Map;function oe(m){let s=z.get(m);return s===void 0&&(s=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:m,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),z.set(m,s)),s}const se={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function ie(m,s){const f=m.format(s).replace(/\u200E/g,""),g=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(f),[,w,I,A,L,N,X,xe]=g;return[A,w,I,L,N,X,xe]}function De(m,s){const f=m.formatToParts(s),g=[];for(let w=0;w<f.length;w++){const{type:I,value:A}=f[w],L=se[I];I==="era"?g[L]=A:ee(L)||(g[L]=parseInt(A,10))}return g}const de=new Map;class ue extends H{static create(s){let f=de.get(s);return f===void 0&&de.set(s,f=new ue(s)),f}static resetCache(){de.clear(),z.clear()}static isValidSpecifier(s){return this.isValidZone(s)}static isValidZone(s){if(!s)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:s}).format(),!0}catch{return!1}}constructor(s){super(),this.zoneName=s,this.valid=ue.isValidZone(s)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(s,{format:f,locale:g}){return Fo(s,f,g,this.name)}formatOffset(s,f){return Vn(this.offset(s),f)}offset(s){if(!this.valid)return NaN;const f=new Date(s);if(isNaN(f))return NaN;const g=oe(this.name);let[w,I,A,L,N,X,xe]=g.formatToParts?De(g,f):ie(g,f);L==="BC"&&(w=-Math.abs(w)+1);const Be=Fr({year:w,month:I,day:A,hour:N===24?0:N,minute:X,second:xe,millisecond:0});let Se=+f;const it=Se%1e3;return Se-=it>=0?it:1e3+it,(Be-Se)/(60*1e3)}equals(s){return s.type==="iana"&&s.name===this.name}get isValid(){return this.valid}}let be={};function Me(m,s={}){const f=JSON.stringify([m,s]);let g=be[f];return g||(g=new Intl.ListFormat(m,s),be[f]=g),g}const te=new Map;function K(m,s={}){const f=JSON.stringify([m,s]);let g=te.get(f);return g===void 0&&(g=new Intl.DateTimeFormat(m,s),te.set(f,g)),g}const he=new Map;function we(m,s={}){const f=JSON.stringify([m,s]);let g=he.get(f);return g===void 0&&(g=new Intl.NumberFormat(m,s),he.set(f,g)),g}const ge=new Map;function pe(m,s={}){const{base:f,...g}=s,w=JSON.stringify([m,g]);let I=ge.get(w);return I===void 0&&(I=new Intl.RelativeTimeFormat(m,s),ge.set(w,I)),I}let ye=null;function Le(){return ye||(ye=new Intl.DateTimeFormat().resolvedOptions().locale,ye)}const st=new Map;function ce(m){let s=st.get(m);return s===void 0&&(s=new Intl.DateTimeFormat(m).resolvedOptions(),st.set(m,s)),s}const Y=new Map;function ae(m){let s=Y.get(m);if(!s){const f=new Intl.Locale(m);s="getWeekInfo"in f?f.getWeekInfo():f.weekInfo,"minimalDays"in s||(s={...Ye,...s}),Y.set(m,s)}return s}function Fe(m){const s=m.indexOf("-x-");s!==-1&&(m=m.substring(0,s));const f=m.indexOf("-u-");if(f===-1)return[m];{let g,w;try{g=K(m).resolvedOptions(),w=m}catch{const N=m.substring(0,f);g=K(N).resolvedOptions(),w=N}const{numberingSystem:I,calendar:A}=g;return[w,I,A]}}function Ve(m,s,f){return(f||s)&&(m.includes("-u-")||(m+="-u"),f&&(m+=`-ca-${f}`),s&&(m+=`-nu-${s}`)),m}function St(m){const s=[];for(let f=1;f<=12;f++){const g=ke.utc(2009,f,1);s.push(m(g))}return s}function Ee(m){const s=[];for(let f=1;f<=7;f++){const g=ke.utc(2016,11,13+f);s.push(m(g))}return s}function at(m,s,f,g){const w=m.listingMode();return w==="error"?null:w==="en"?f(s):g(s)}function yt(m){return m.numberingSystem&&m.numberingSystem!=="latn"?!1:m.numberingSystem==="latn"||!m.locale||m.locale.startsWith("en")||ce(m.locale).numberingSystem==="latn"}class xt{constructor(s,f,g){this.padTo=g.padTo||0,this.floor=g.floor||!1;const{padTo:w,floor:I,...A}=g;if(!f||Object.keys(A).length>0){const L={useGrouping:!1,...g};g.padTo>0&&(L.minimumIntegerDigits=g.padTo),this.inf=we(s,L)}}format(s){if(this.inf){const f=this.floor?Math.floor(s):s;return this.inf.format(f)}else{const f=this.floor?Math.floor(s):fs(s,3);return ot(f,this.padTo)}}}class Ot{constructor(s,f,g){this.opts=g,this.originalZone=void 0;let w;if(this.opts.timeZone)this.dt=s;else if(s.zone.type==="fixed"){const A=-1*(s.offset/60),L=A>=0?`Etc/GMT+${A}`:`Etc/GMT${A}`;s.offset!==0&&ue.create(L).valid?(w=L,this.dt=s):(w="UTC",this.dt=s.offset===0?s:s.setZone("UTC").plus({minutes:s.offset}),this.originalZone=s.zone)}else s.zone.type==="system"?this.dt=s:s.zone.type==="iana"?(this.dt=s,w=s.zone.name):(w="UTC",this.dt=s.setZone("UTC").plus({minutes:s.offset}),this.originalZone=s.zone);const I={...this.opts};I.timeZone=I.timeZone||w,this.dtf=K(f,I)}format(){return this.originalZone?this.formatToParts().map(({value:s})=>s).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const s=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?s.map(f=>{if(f.type==="timeZoneName"){const g=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...f,value:g}}else return f}):s}resolvedOptions(){return this.dtf.resolvedOptions()}}class pt{constructor(s,f,g){this.opts={style:"long",...g},!f&&zn()&&(this.rtf=pe(s,g))}format(s,f){return this.rtf?this.rtf.format(s,f):$c(f,s,this.opts.numeric,this.opts.style!=="long")}formatToParts(s,f){return this.rtf?this.rtf.formatToParts(s,f):[]}}const Ye={firstDay:1,minimalDays:4,weekend:[6,7]};class fe{static fromOpts(s){return fe.create(s.locale,s.numberingSystem,s.outputCalendar,s.weekSettings,s.defaultToEN)}static create(s,f,g,w,I=!1){const A=s||Ne.defaultLocale,L=A||(I?"en-US":Le()),N=f||Ne.defaultNumberingSystem,X=g||Ne.defaultOutputCalendar,xe=qt(w)||Ne.defaultWeekSettings;return new fe(L,N,X,xe,A)}static resetCache(){ye=null,te.clear(),he.clear(),ge.clear(),st.clear(),Y.clear()}static fromObject({locale:s,numberingSystem:f,outputCalendar:g,weekSettings:w}={}){return fe.create(s,f,g,w)}constructor(s,f,g,w,I){const[A,L,N]=Fe(s);this.locale=A,this.numberingSystem=f||L||null,this.outputCalendar=g||N||null,this.weekSettings=w,this.intl=Ve(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=I,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=yt(this)),this.fastNumbersCached}listingMode(){const s=this.isEnglish(),f=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return s&&f?"en":"intl"}clone(s){return!s||Object.getOwnPropertyNames(s).length===0?this:fe.create(s.locale||this.specifiedLocale,s.numberingSystem||this.numberingSystem,s.outputCalendar||this.outputCalendar,qt(s.weekSettings)||this.weekSettings,s.defaultToEN||!1)}redefaultToEN(s={}){return this.clone({...s,defaultToEN:!0})}redefaultToSystem(s={}){return this.clone({...s,defaultToEN:!1})}months(s,f=!1){return at(this,s,Lo,()=>{const g=this.intl==="ja"||this.intl.startsWith("ja-");f&=!g;const w=f?{month:s,day:"numeric"}:{month:s},I=f?"format":"standalone";if(!this.monthsCache[I][s]){const A=g?L=>this.dtFormatter(L,w).format():L=>this.extract(L,w,"month");this.monthsCache[I][s]=St(A)}return this.monthsCache[I][s]})}weekdays(s,f=!1){return at(this,s,Po,()=>{const g=f?{weekday:s,year:"numeric",month:"long",day:"numeric"}:{weekday:s},w=f?"format":"standalone";return this.weekdaysCache[w][s]||(this.weekdaysCache[w][s]=Ee(I=>this.extract(I,g,"weekday"))),this.weekdaysCache[w][s]})}meridiems(){return at(this,void 0,()=>zo,()=>{if(!this.meridiemCache){const s={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[ke.utc(2016,11,13,9),ke.utc(2016,11,13,19)].map(f=>this.extract(f,s,"dayperiod"))}return this.meridiemCache})}eras(s){return at(this,s,Wo,()=>{const f={era:s};return this.eraCache[s]||(this.eraCache[s]=[ke.utc(-40,1,1),ke.utc(2017,1,1)].map(g=>this.extract(g,f,"era"))),this.eraCache[s]})}extract(s,f,g){const w=this.dtFormatter(s,f),I=w.formatToParts(),A=I.find(L=>L.type.toLowerCase()===g);return A?A.value:null}numberFormatter(s={}){return new xt(this.intl,s.forceSimple||this.fastNumbers,s)}dtFormatter(s,f={}){return new Ot(s,this.intl,f)}relFormatter(s={}){return new pt(this.intl,this.isEnglish(),s)}listFormatter(s={}){return Me(this.intl,s)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||ce(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Wn()?ae(this.locale):Ye}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(s){return this.locale===s.locale&&this.numberingSystem===s.numberingSystem&&this.outputCalendar===s.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let Ke=null;class ze extends H{static get utcInstance(){return Ke===null&&(Ke=new ze(0)),Ke}static instance(s){return s===0?ze.utcInstance:new ze(s)}static parseSpecifier(s){if(s){const f=s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(f)return new ze(Ar(f[1],f[2]))}return null}constructor(s){super(),this.fixed=s}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Vn(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Vn(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(s,f){return Vn(this.fixed,f)}get isUniversal(){return!0}offset(){return this.fixed}equals(s){return s.type==="fixed"&&s.fixed===this.fixed}get isValid(){return!0}}class lt extends H{constructor(s){super(),this.zoneName=s}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 ct(m,s){if(ee(m)||m===null)return s;if(m instanceof H)return m;if(Ct(m)){const f=m.toLowerCase();return f==="default"?s:f==="local"||f==="system"?re.instance:f==="utc"||f==="gmt"?ze.utcInstance:ze.parseSpecifier(f)||ue.create(m)}else return qe(m)?ze.instance(m):typeof m=="object"&&"offset"in m&&typeof m.offset=="function"?m:new lt(m)}const Qe={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},me={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]},He=Qe.hanidec.replace(/[\[|\]]/g,"").split("");function vt(m){let s=parseInt(m,10);if(isNaN(s)){s="";for(let f=0;f<m.length;f++){const g=m.charCodeAt(f);if(m[f].search(Qe.hanidec)!==-1)s+=He.indexOf(m[f]);else for(const w in me){const[I,A]=me[w];g>=I&&g<=A&&(s+=g-I)}}return parseInt(s,10)}else return s}const Ce=new Map;function Re(){Ce.clear()}function Ie({numberingSystem:m},s=""){const f=m||"latn";let g=Ce.get(f);g===void 0&&(g=new Map,Ce.set(f,g));let w=g.get(s);return w===void 0&&(w=new RegExp(`${Qe[f]}${s}`),g.set(s,w)),w}let We=()=>Date.now(),dt="system",Pe=null,tt=null,Mt=null,kt=60,Ft,gn=null;class Ne{static get now(){return We}static set now(s){We=s}static set defaultZone(s){dt=s}static get defaultZone(){return ct(dt,re.instance)}static get defaultLocale(){return Pe}static set defaultLocale(s){Pe=s}static get defaultNumberingSystem(){return tt}static set defaultNumberingSystem(s){tt=s}static get defaultOutputCalendar(){return Mt}static set defaultOutputCalendar(s){Mt=s}static get defaultWeekSettings(){return gn}static set defaultWeekSettings(s){gn=qt(s)}static get twoDigitCutoffYear(){return kt}static set twoDigitCutoffYear(s){kt=s%100}static get throwOnInvalid(){return Ft}static set throwOnInvalid(s){Ft=s}static resetCaches(){fe.resetCache(),ue.resetCache(),ke.resetCache(),Re()}}class ut{constructor(s,f){this.reason=s,this.explanation=f}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const Kt=[0,31,59,90,120,151,181,212,243,273,304,334],yn=[0,31,60,91,121,152,182,213,244,274,305,335];function ht(m,s){return new ut("unit out of range",`you specified ${s} (of type ${typeof s}) as a ${m}, which is invalid`)}function en(m,s,f){const g=new Date(Date.UTC(m,s-1,f));m<100&&m>=0&&g.setUTCFullYear(g.getUTCFullYear()-1900);const w=g.getUTCDay();return w===0?7:w}function xn(m,s,f){return f+(qn(m)?yn:Kt)[s-1]}function Qt(m,s){const f=qn(m)?yn:Kt,g=f.findIndex(I=>I<s),w=s-f[g];return{month:g+1,day:w}}function Ze(m,s){return(m-s+7)%7+1}function Xe(m,s=4,f=1){const{year:g,month:w,day:I}=m,A=xn(g,w,I),L=Ze(en(g,w,I),f);let N=Math.floor((A-L+14-s)/7),X;return N<1?(X=g-1,N=Bn(X,s,f)):N>Bn(g,s,f)?(X=g+1,N=1):X=g,{weekYear:X,weekNumber:N,weekday:L,...Lr(m)}}function At(m,s=4,f=1){const{weekYear:g,weekNumber:w,weekday:I}=m,A=Ze(en(g,1,s),f),L=bn(g);let N=w*7+I-A-7+s,X;N<1?(X=g-1,N+=bn(X)):N>L?(X=g+1,N-=bn(g)):X=g;const{month:xe,day:Te}=Qt(X,N);return{year:X,month:xe,day:Te,...Lr(m)}}function tn(m){const{year:s,month:f,day:g}=m,w=xn(s,f,g);return{year:s,ordinal:w,...Lr(m)}}function Zt(m){const{year:s,ordinal:f}=m,{month:g,day:w}=Qt(s,f);return{year:s,month:g,day:w,...Lr(m)}}function nn(m,s){if(!ee(m.localWeekday)||!ee(m.localWeekNumber)||!ee(m.localWeekYear)){if(!ee(m.weekday)||!ee(m.weekNumber)||!ee(m.weekYear))throw new i("Cannot mix locale-based week fields with ISO-based week fields");return ee(m.localWeekday)||(m.weekday=m.localWeekday),ee(m.localWeekNumber)||(m.weekNumber=m.localWeekNumber),ee(m.localWeekYear)||(m.weekYear=m.localWeekYear),delete m.localWeekday,delete m.localWeekNumber,delete m.localWeekYear,{minDaysInFirstWeek:s.getMinDaysInFirstWeek(),startOfWeek:s.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function G(m,s=4,f=1){const g=Ue(m.weekYear),w=Et(m.weekNumber,1,Bn(m.weekYear,s,f)),I=Et(m.weekday,1,7);return g?w?I?!1:ht("weekday",m.weekday):ht("week",m.weekNumber):ht("weekYear",m.weekYear)}function U(m){const s=Ue(m.year),f=Et(m.ordinal,1,bn(m.year));return s?f?!1:ht("ordinal",m.ordinal):ht("year",m.year)}function le(m){const s=Ue(m.year),f=Et(m.month,1,12),g=Et(m.day,1,$r(m.year,m.month));return s?f?g?!1:ht("day",m.day):ht("month",m.month):ht("year",m.year)}function ve(m){const{hour:s,minute:f,second:g,millisecond:w}=m,I=Et(s,0,23)||s===24&&f===0&&g===0&&w===0,A=Et(f,0,59),L=Et(g,0,59),N=Et(w,0,999);return I?A?L?N?!1:ht("millisecond",w):ht("second",g):ht("minute",f):ht("hour",s)}function ee(m){return typeof m>"u"}function qe(m){return typeof m=="number"}function Ue(m){return typeof m=="number"&&m%1===0}function Ct(m){return typeof m=="string"}function vn(m){return Object.prototype.toString.call(m)==="[object Date]"}function zn(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Wn(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function Dr(m){return Array.isArray(m)?m:[m]}function $e(m,s,f){if(m.length!==0)return m.reduce((g,w)=>{const I=[s(w),w];return g&&f(g[0],I[0])===g[0]?g:I},null)[1]}function zt(m,s){return s.reduce((f,g)=>(f[g]=m[g],f),{})}function gt(m,s){return Object.prototype.hasOwnProperty.call(m,s)}function qt(m){if(m==null)return null;if(typeof m!="object")throw new a("Week settings must be an object");if(!Et(m.firstDay,1,7)||!Et(m.minimalDays,1,7)||!Array.isArray(m.weekend)||m.weekend.some(s=>!Et(s,1,7)))throw new a("Invalid week settings");return{firstDay:m.firstDay,minimalDays:m.minimalDays,weekend:Array.from(m.weekend)}}function Et(m,s,f){return Ue(m)&&m>=s&&m<=f}function wc(m,s){return m-s*Math.floor(m/s)}function ot(m,s=2){const f=m<0;let g;return f?g="-"+(""+-m).padStart(s,"0"):g=(""+m).padStart(s,"0"),g}function Xt(m){if(!(ee(m)||m===null||m===""))return parseInt(m,10)}function rn(m){if(!(ee(m)||m===null||m===""))return parseFloat(m)}function hs(m){if(!(ee(m)||m===null||m==="")){const s=parseFloat("0."+m)*1e3;return Math.floor(s)}}function fs(m,s,f="round"){const g=10**s;switch(f){case"expand":return m>0?Math.ceil(m*g)/g:Math.floor(m*g)/g;case"trunc":return Math.trunc(m*g)/g;case"round":return Math.round(m*g)/g;case"floor":return Math.floor(m*g)/g;case"ceil":return Math.ceil(m*g)/g;default:throw new RangeError(`Value rounding ${f} is out of range`)}}function qn(m){return m%4===0&&(m%100!==0||m%400===0)}function bn(m){return qn(m)?366:365}function $r(m,s){const f=wc(s-1,12)+1,g=m+(s-f)/12;return f===2?qn(g)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][f-1]}function Fr(m){let s=Date.UTC(m.year,m.month-1,m.day,m.hour,m.minute,m.second,m.millisecond);return m.year<100&&m.year>=0&&(s=new Date(s),s.setUTCFullYear(m.year,m.month-1,m.day)),+s}function $o(m,s,f){return-Ze(en(m,1,s),f)+s-1}function Bn(m,s=4,f=1){const g=$o(m,s,f),w=$o(m+1,s,f);return(bn(m)-g+w)/7}function ms(m){return m>99?m:m>Ne.twoDigitCutoffYear?1900+m:2e3+m}function Fo(m,s,f,g=null){const w=new Date(m),I={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};g&&(I.timeZone=g);const A={timeZoneName:s,...I},L=new Intl.DateTimeFormat(f,A).formatToParts(w).find(N=>N.type.toLowerCase()==="timezonename");return L?L.value:null}function Ar(m,s){let f=parseInt(m,10);Number.isNaN(f)&&(f=0);const g=parseInt(s,10)||0,w=f<0||Object.is(f,-0)?-g:g;return f*60+w}function Ao(m){const s=Number(m);if(typeof m=="boolean"||m===""||!Number.isFinite(s))throw new a(`Invalid unit value ${m}`);return s}function Rr(m,s){const f={};for(const g in m)if(gt(m,g)){const w=m[g];if(w==null)continue;f[s(g)]=Ao(w)}return f}function Vn(m,s){const f=Math.trunc(Math.abs(m/60)),g=Math.trunc(Math.abs(m%60)),w=m>=0?"+":"-";switch(s){case"short":return`${w}${ot(f,2)}:${ot(g,2)}`;case"narrow":return`${w}${f}${g>0?`:${g}`:""}`;case"techie":return`${w}${ot(f,2)}${ot(g,2)}`;default:throw new RangeError(`Value format ${s} is out of range for property format`)}}function Lr(m){return zt(m,["hour","minute","second","millisecond"])}const Sc=["January","February","March","April","May","June","July","August","September","October","November","December"],Ro=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],kc=["J","F","M","A","M","J","J","A","S","O","N","D"];function Lo(m){switch(m){case"narrow":return[...kc];case"short":return[...Ro];case"long":return[...Sc];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 _o=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],No=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Cc=["M","T","W","T","F","S","S"];function Po(m){switch(m){case"narrow":return[...Cc];case"short":return[...No];case"long":return[..._o];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const zo=["AM","PM"],jc=["Before Christ","Anno Domini"],Tc=["BC","AD"],Oc=["B","A"];function Wo(m){switch(m){case"narrow":return[...Oc];case"short":return[...Tc];case"long":return[...jc];default:return null}}function Mc(m){return zo[m.hour<12?0:1]}function Ec(m,s){return Po(s)[m.weekday-1]}function Ic(m,s){return Lo(s)[m.month-1]}function Dc(m,s){return Wo(s)[m.year<0?0:1]}function $c(m,s,f="always",g=!1){const w={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."]},I=["hours","minutes","seconds"].indexOf(m)===-1;if(f==="auto"&&I){const Te=m==="days";switch(s){case 1:return Te?"tomorrow":`next ${w[m][0]}`;case-1:return Te?"yesterday":`last ${w[m][0]}`;case 0:return Te?"today":`this ${w[m][0]}`}}const A=Object.is(s,-0)||s<0,L=Math.abs(s),N=L===1,X=w[m],xe=g?N?X[1]:X[2]||X[1]:N?w[m][0]:m;return A?`${L} ${xe} ago`:`in ${L} ${xe}`}function qo(m,s){let f="";for(const g of m)g.literal?f+=g.val:f+=s(g.val);return f}const Fc={D:b,DD:x,DDD:k,DDDD:C,t:S,tt:T,ttt:O,tttt:M,T:E,TT:R,TTT:P,TTTT:F,f:B,ff:_,fff:W,ffff:ne,F:D,FF:V,FFF:Z,FFFF:J};class ft{static create(s,f={}){return new ft(s,f)}static parseFormat(s){let f=null,g="",w=!1;const I=[];for(let A=0;A<s.length;A++){const L=s.charAt(A);L==="'"?((g.length>0||w)&&I.push({literal:w||/^\s+$/.test(g),val:g===""?"'":g}),f=null,g="",w=!w):w||L===f?g+=L:(g.length>0&&I.push({literal:/^\s+$/.test(g),val:g}),g=L,f=L)}return g.length>0&&I.push({literal:w||/^\s+$/.test(g),val:g}),I}static macroTokenToFormatOpts(s){return Fc[s]}constructor(s,f){this.opts=f,this.loc=s,this.systemLoc=null}formatWithSystemDefault(s,f){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(s,{...this.opts,...f}).format()}dtFormatter(s,f={}){return this.loc.dtFormatter(s,{...this.opts,...f})}formatDateTime(s,f){return this.dtFormatter(s,f).format()}formatDateTimeParts(s,f){return this.dtFormatter(s,f).formatToParts()}formatInterval(s,f){return this.dtFormatter(s.start,f).dtf.formatRange(s.start.toJSDate(),s.end.toJSDate())}resolvedOptions(s,f){return this.dtFormatter(s,f).resolvedOptions()}num(s,f=0,g=void 0){if(this.opts.forceSimple)return ot(s,f);const w={...this.opts};return f>0&&(w.padTo=f),g&&(w.signDisplay=g),this.loc.numberFormatter(w).format(s)}formatDateTimeFromString(s,f){const g=this.loc.listingMode()==="en",w=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",I=(Se,it)=>this.loc.extract(s,Se,it),A=Se=>s.isOffsetFixed&&s.offset===0&&Se.allowZ?"Z":s.isValid?s.zone.formatOffset(s.ts,Se.format):"",L=()=>g?Mc(s):I({hour:"numeric",hourCycle:"h12"},"dayperiod"),N=(Se,it)=>g?Ic(s,Se):I(it?{month:Se}:{month:Se,day:"numeric"},"month"),X=(Se,it)=>g?Ec(s,Se):I(it?{weekday:Se}:{weekday:Se,month:"long",day:"numeric"},"weekday"),xe=Se=>{const it=ft.macroTokenToFormatOpts(Se);return it?this.formatWithSystemDefault(s,it):Se},Te=Se=>g?Dc(s,Se):I({era:Se},"era"),Be=Se=>{switch(Se){case"S":return this.num(s.millisecond);case"u":case"SSS":return this.num(s.millisecond,3);case"s":return this.num(s.second);case"ss":return this.num(s.second,2);case"uu":return this.num(Math.floor(s.millisecond/10),2);case"uuu":return this.num(Math.floor(s.millisecond/100));case"m":return this.num(s.minute);case"mm":return this.num(s.minute,2);case"h":return this.num(s.hour%12===0?12:s.hour%12);case"hh":return this.num(s.hour%12===0?12:s.hour%12,2);case"H":return this.num(s.hour);case"HH":return this.num(s.hour,2);case"Z":return A({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return A({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return A({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return s.zone.offsetName(s.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return s.zone.offsetName(s.ts,{format:"long",locale:this.loc.locale});case"z":return s.zoneName;case"a":return L();case"d":return w?I({day:"numeric"},"day"):this.num(s.day);case"dd":return w?I({day:"2-digit"},"day"):this.num(s.day,2);case"c":return this.num(s.weekday);case"ccc":return X("short",!0);case"cccc":return X("long",!0);case"ccccc":return X("narrow",!0);case"E":return this.num(s.weekday);case"EEE":return X("short",!1);case"EEEE":return X("long",!1);case"EEEEE":return X("narrow",!1);case"L":return w?I({month:"numeric",day:"numeric"},"month"):this.num(s.month);case"LL":return w?I({month:"2-digit",day:"numeric"},"month"):this.num(s.month,2);case"LLL":return N("short",!0);case"LLLL":return N("long",!0);case"LLLLL":return N("narrow",!0);case"M":return w?I({month:"numeric"},"month"):this.num(s.month);case"MM":return w?I({month:"2-digit"},"month"):this.num(s.month,2);case"MMM":return N("short",!1);case"MMMM":return N("long",!1);case"MMMMM":return N("narrow",!1);case"y":return w?I({year:"numeric"},"year"):this.num(s.year);case"yy":return w?I({year:"2-digit"},"year"):this.num(s.year.toString().slice(-2),2);case"yyyy":return w?I({year:"numeric"},"year"):this.num(s.year,4);case"yyyyyy":return w?I({year:"numeric"},"year"):this.num(s.year,6);case"G":return Te("short");case"GG":return Te("long");case"GGGGG":return Te("narrow");case"kk":return this.num(s.weekYear.toString().slice(-2),2);case"kkkk":return this.num(s.weekYear,4);case"W":return this.num(s.weekNumber);case"WW":return this.num(s.weekNumber,2);case"n":return this.num(s.localWeekNumber);case"nn":return this.num(s.localWeekNumber,2);case"ii":return this.num(s.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(s.localWeekYear,4);case"o":return this.num(s.ordinal);case"ooo":return this.num(s.ordinal,3);case"q":return this.num(s.quarter);case"qq":return this.num(s.quarter,2);case"X":return this.num(Math.floor(s.ts/1e3));case"x":return this.num(s.ts);default:return xe(Se)}};return qo(ft.parseFormat(f),Be)}formatDurationFromString(s,f){const g=this.opts.signMode==="negativeLargestOnly"?-1:1,w=xe=>{switch(xe[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}},I=(xe,Te)=>Be=>{const Se=w(Be);if(Se){const it=Te.isNegativeDuration&&Se!==Te.largestUnit?g:1;let Lt;return this.opts.signMode==="negativeLargestOnly"&&Se!==Te.largestUnit?Lt="never":this.opts.signMode==="all"?Lt="always":Lt="auto",this.num(xe.get(Se)*it,Be.length,Lt)}else return Be},A=ft.parseFormat(f),L=A.reduce((xe,{literal:Te,val:Be})=>Te?xe:xe.concat(Be),[]),N=s.shiftTo(...L.map(w).filter(xe=>xe)),X={isNegativeDuration:N<0,largestUnit:Object.keys(N.values)[0]};return qo(A,I(N,X))}}const Bo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function wn(...m){const s=m.reduce((f,g)=>f+g.source,"");return RegExp(`^${s}$`)}function Sn(...m){return s=>m.reduce(([f,g,w],I)=>{const[A,L,N]=I(s,w);return[{...f,...A},L||g,N]},[{},null,1]).slice(0,2)}function kn(m,...s){if(m==null)return[null,null];for(const[f,g]of s){const w=f.exec(m);if(w)return g(w)}return[null,null]}function Vo(...m){return(s,f)=>{const g={};let w;for(w=0;w<m.length;w++)g[m[w]]=Xt(s[f+w]);return[g,null,f+w]}}const Ho=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Ac=`(?:${Ho.source}?(?:\\[(${Bo.source})\\])?)?`,ps=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Uo=RegExp(`${ps.source}${Ac}`),gs=RegExp(`(?:[Tt]${Uo.source})?`),Rc=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Lc=/(\d{4})-?W(\d\d)(?:-?(\d))?/,_c=/(\d{4})-?(\d{3})/,Nc=Vo("weekYear","weekNumber","weekDay"),Pc=Vo("year","ordinal"),zc=/(\d{4})-(\d\d)-(\d\d)/,Go=RegExp(`${ps.source} ?(?:${Ho.source}|(${Bo.source}))?`),Wc=RegExp(`(?: ${Go.source})?`);function Cn(m,s,f){const g=m[s];return ee(g)?f:Xt(g)}function qc(m,s){return[{year:Cn(m,s),month:Cn(m,s+1,1),day:Cn(m,s+2,1)},null,s+3]}function jn(m,s){return[{hours:Cn(m,s,0),minutes:Cn(m,s+1,0),seconds:Cn(m,s+2,0),milliseconds:hs(m[s+3])},null,s+4]}function Hn(m,s){const f=!m[s]&&!m[s+1],g=Ar(m[s+1],m[s+2]),w=f?null:ze.instance(g);return[{},w,s+3]}function Un(m,s){const f=m[s]?ue.create(m[s]):null;return[{},f,s+1]}const Bc=RegExp(`^T?${ps.source}$`),Vc=/^-?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 Hc(m){const[s,f,g,w,I,A,L,N,X]=m,xe=s[0]==="-",Te=N&&N[0]==="-",Be=(Se,it=!1)=>Se!==void 0&&(it||Se&&xe)?-Se:Se;return[{years:Be(rn(f)),months:Be(rn(g)),weeks:Be(rn(w)),days:Be(rn(I)),hours:Be(rn(A)),minutes:Be(rn(L)),seconds:Be(rn(N),N==="-0"),milliseconds:Be(hs(X),Te)}]}const Uc={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function ys(m,s,f,g,w,I,A){const L={year:s.length===2?ms(Xt(s)):Xt(s),month:Ro.indexOf(f)+1,day:Xt(g),hour:Xt(w),minute:Xt(I)};return A&&(L.second=Xt(A)),m&&(L.weekday=m.length>3?_o.indexOf(m)+1:No.indexOf(m)+1),L}const Gc=/^(?:(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 Yc(m){const[,s,f,g,w,I,A,L,N,X,xe,Te]=m,Be=ys(s,w,g,f,I,A,L);let Se;return N?Se=Uc[N]:X?Se=0:Se=Ar(xe,Te),[Be,new ze(Se)]}function Kc(m){return m.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Qc=/^(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$/,Zc=/^(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$/,Xc=/^(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 Yo(m){const[,s,f,g,w,I,A,L]=m;return[ys(s,w,g,f,I,A,L),ze.utcInstance]}function Jc(m){const[,s,f,g,w,I,A,L]=m;return[ys(s,L,f,g,w,I,A),ze.utcInstance]}const eu=wn(Rc,gs),tu=wn(Lc,gs),nu=wn(_c,gs),ru=wn(Uo),Ko=Sn(qc,jn,Hn,Un),su=Sn(Nc,jn,Hn,Un),ou=Sn(Pc,jn,Hn,Un),iu=Sn(jn,Hn,Un);function au(m){return kn(m,[eu,Ko],[tu,su],[nu,ou],[ru,iu])}function lu(m){return kn(Kc(m),[Gc,Yc])}function cu(m){return kn(m,[Qc,Yo],[Zc,Yo],[Xc,Jc])}function uu(m){return kn(m,[Vc,Hc])}const du=Sn(jn);function hu(m){return kn(m,[Bc,du])}const fu=wn(zc,Wc),mu=wn(Go),pu=Sn(jn,Hn,Un);function gu(m){return kn(m,[fu,Ko],[mu,pu])}const Qo="Invalid Duration",Zo={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}},yu={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},...Zo},It=146097/400,Tn=146097/4800,xu={years:{quarters:4,months:12,weeks:It/7,days:It,hours:It*24,minutes:It*24*60,seconds:It*24*60*60,milliseconds:It*24*60*60*1e3},quarters:{months:3,weeks:It/28,days:It/4,hours:It*24/4,minutes:It*24*60/4,seconds:It*24*60*60/4,milliseconds:It*24*60*60*1e3/4},months:{weeks:Tn/7,days:Tn,hours:Tn*24,minutes:Tn*24*60,seconds:Tn*24*60*60,milliseconds:Tn*24*60*60*1e3},...Zo},sn=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],vu=sn.slice(0).reverse();function Bt(m,s,f=!1){const g={values:f?s.values:{...m.values,...s.values||{}},loc:m.loc.clone(s.loc),conversionAccuracy:s.conversionAccuracy||m.conversionAccuracy,matrix:s.matrix||m.matrix};return new Ae(g)}function Xo(m,s){var f;let g=(f=s.milliseconds)!=null?f:0;for(const w of vu.slice(1))s[w]&&(g+=s[w]*m[w].milliseconds);return g}function Jo(m,s){const f=Xo(m,s)<0?-1:1;sn.reduceRight((g,w)=>{if(ee(s[w]))return g;if(g){const I=s[g]*f,A=m[w][g],L=Math.floor(I/A);s[w]+=L*f,s[g]-=L*A*f}return w},null),sn.reduce((g,w)=>{if(ee(s[w]))return g;if(g){const I=s[g]%1;s[g]-=I,s[w]+=I*m[g][w]}return w},null)}function ei(m){const s={};for(const[f,g]of Object.entries(m))g!==0&&(s[f]=g);return s}class Ae{constructor(s){const f=s.conversionAccuracy==="longterm"||!1;let g=f?xu:yu;s.matrix&&(g=s.matrix),this.values=s.values,this.loc=s.loc||fe.create(),this.conversionAccuracy=f?"longterm":"casual",this.invalid=s.invalid||null,this.matrix=g,this.isLuxonDuration=!0}static fromMillis(s,f){return Ae.fromObject({milliseconds:s},f)}static fromObject(s,f={}){if(s==null||typeof s!="object")throw new a(`Duration.fromObject: argument expected to be an object, got ${s===null?"null":typeof s}`);return new Ae({values:Rr(s,Ae.normalizeUnit),loc:fe.fromObject(f),conversionAccuracy:f.conversionAccuracy,matrix:f.matrix})}static fromDurationLike(s){if(qe(s))return Ae.fromMillis(s);if(Ae.isDuration(s))return s;if(typeof s=="object")return Ae.fromObject(s);throw new a(`Unknown duration argument ${s} of type ${typeof s}`)}static fromISO(s,f){const[g]=uu(s);return g?Ae.fromObject(g,f):Ae.invalid("unparsable",`the input "${s}" can't be parsed as ISO 8601`)}static fromISOTime(s,f){const[g]=hu(s);return g?Ae.fromObject(g,f):Ae.invalid("unparsable",`the input "${s}" can't be parsed as ISO 8601`)}static invalid(s,f=null){if(!s)throw new a("need to specify a reason the Duration is invalid");const g=s instanceof ut?s:new ut(s,f);if(Ne.throwOnInvalid)throw new o(g);return new Ae({invalid:g})}static normalizeUnit(s){const f={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"}[s&&s.toLowerCase()];if(!f)throw new l(s);return f}static isDuration(s){return s&&s.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(s,f={}){const g={...f,floor:f.round!==!1&&f.floor!==!1};return this.isValid?ft.create(this.loc,g).formatDurationFromString(this,s):Qo}toHuman(s={}){if(!this.isValid)return Qo;const f=s.showZeros!==!1,g=sn.map(w=>{const I=this.values[w];return ee(I)||I===0&&!f?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...s,unit:w.slice(0,-1)}).format(I)}).filter(w=>w);return this.loc.listFormatter({type:"conjunction",style:s.listStyle||"narrow",...s}).format(g)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let s="P";return this.years!==0&&(s+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(s+=this.months+this.quarters*3+"M"),this.weeks!==0&&(s+=this.weeks+"W"),this.days!==0&&(s+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(s+="T"),this.hours!==0&&(s+=this.hours+"H"),this.minutes!==0&&(s+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(s+=fs(this.seconds+this.milliseconds/1e3,3)+"S"),s==="P"&&(s+="T0S"),s}toISOTime(s={}){if(!this.isValid)return null;const f=this.toMillis();return f<0||f>=864e5?null:(s={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...s,includeOffset:!1},ke.fromMillis(f,{zone:"UTC"}).toISOTime(s))}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?Xo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(s){if(!this.isValid)return this;const f=Ae.fromDurationLike(s),g={};for(const w of sn)(gt(f.values,w)||gt(this.values,w))&&(g[w]=f.get(w)+this.get(w));return Bt(this,{values:g},!0)}minus(s){if(!this.isValid)return this;const f=Ae.fromDurationLike(s);return this.plus(f.negate())}mapUnits(s){if(!this.isValid)return this;const f={};for(const g of Object.keys(this.values))f[g]=Ao(s(this.values[g],g));return Bt(this,{values:f},!0)}get(s){return this[Ae.normalizeUnit(s)]}set(s){if(!this.isValid)return this;const f={...this.values,...Rr(s,Ae.normalizeUnit)};return Bt(this,{values:f})}reconfigure({locale:s,numberingSystem:f,conversionAccuracy:g,matrix:w}={}){const A={loc:this.loc.clone({locale:s,numberingSystem:f}),matrix:w,conversionAccuracy:g};return Bt(this,A)}as(s){return this.isValid?this.shiftTo(s).get(s):NaN}normalize(){if(!this.isValid)return this;const s=this.toObject();return Jo(this.matrix,s),Bt(this,{values:s},!0)}rescale(){if(!this.isValid)return this;const s=ei(this.normalize().shiftToAll().toObject());return Bt(this,{values:s},!0)}shiftTo(...s){if(!this.isValid)return this;if(s.length===0)return this;s=s.map(A=>Ae.normalizeUnit(A));const f={},g={},w=this.toObject();let I;for(const A of sn)if(s.indexOf(A)>=0){I=A;let L=0;for(const X in g)L+=this.matrix[X][A]*g[X],g[X]=0;qe(w[A])&&(L+=w[A]);const N=Math.trunc(L);f[A]=N,g[A]=(L*1e3-N*1e3)/1e3}else qe(w[A])&&(g[A]=w[A]);for(const A in g)g[A]!==0&&(f[I]+=A===I?g[A]:g[A]/this.matrix[I][A]);return Jo(this.matrix,f),Bt(this,{values:f},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const s={};for(const f of Object.keys(this.values))s[f]=this.values[f]===0?0:-this.values[f];return Bt(this,{values:s},!0)}removeZeros(){if(!this.isValid)return this;const s=ei(this.values);return Bt(this,{values:s},!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(s){if(!this.isValid||!s.isValid||!this.loc.equals(s.loc))return!1;function f(g,w){return g===void 0||g===0?w===void 0||w===0:g===w}for(const g of sn)if(!f(this.values[g],s.values[g]))return!1;return!0}}const On="Invalid Interval";function bu(m,s){return!m||!m.isValid?Je.invalid("missing or invalid start"):!s||!s.isValid?Je.invalid("missing or invalid end"):s<m?Je.invalid("end before start",`The end of an interval must be after its start, but you had start=${m.toISO()} and end=${s.toISO()}`):null}class Je{constructor(s){this.s=s.start,this.e=s.end,this.invalid=s.invalid||null,this.isLuxonInterval=!0}static invalid(s,f=null){if(!s)throw new a("need to specify a reason the Interval is invalid");const g=s instanceof ut?s:new ut(s,f);if(Ne.throwOnInvalid)throw new r(g);return new Je({invalid:g})}static fromDateTimes(s,f){const g=Qn(s),w=Qn(f),I=bu(g,w);return I??new Je({start:g,end:w})}static after(s,f){const g=Ae.fromDurationLike(f),w=Qn(s);return Je.fromDateTimes(w,w.plus(g))}static before(s,f){const g=Ae.fromDurationLike(f),w=Qn(s);return Je.fromDateTimes(w.minus(g),w)}static fromISO(s,f){const[g,w]=(s||"").split("/",2);if(g&&w){let I,A;try{I=ke.fromISO(g,f),A=I.isValid}catch{A=!1}let L,N;try{L=ke.fromISO(w,f),N=L.isValid}catch{N=!1}if(A&&N)return Je.fromDateTimes(I,L);if(A){const X=Ae.fromISO(w,f);if(X.isValid)return Je.after(I,X)}else if(N){const X=Ae.fromISO(g,f);if(X.isValid)return Je.before(L,X)}}return Je.invalid("unparsable",`the input "${s}" can't be parsed as ISO 8601`)}static isInterval(s){return s&&s.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(s="milliseconds"){return this.isValid?this.toDuration(s).get(s):NaN}count(s="milliseconds",f){if(!this.isValid)return NaN;const g=this.start.startOf(s,f);let w;return f!=null&&f.useLocaleWeeks?w=this.end.reconfigure({locale:g.locale}):w=this.end,w=w.startOf(s,f),Math.floor(w.diff(g,s).get(s))+(w.valueOf()!==this.end.valueOf())}hasSame(s){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,s):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(s){return this.isValid?this.s>s:!1}isBefore(s){return this.isValid?this.e<=s:!1}contains(s){return this.isValid?this.s<=s&&this.e>s:!1}set({start:s,end:f}={}){return this.isValid?Je.fromDateTimes(s||this.s,f||this.e):this}splitAt(...s){if(!this.isValid)return[];const f=s.map(Qn).filter(A=>this.contains(A)).sort((A,L)=>A.toMillis()-L.toMillis()),g=[];let{s:w}=this,I=0;for(;w<this.e;){const A=f[I]||this.e,L=+A>+this.e?this.e:A;g.push(Je.fromDateTimes(w,L)),w=L,I+=1}return g}splitBy(s){const f=Ae.fromDurationLike(s);if(!this.isValid||!f.isValid||f.as("milliseconds")===0)return[];let{s:g}=this,w=1,I;const A=[];for(;g<this.e;){const L=this.start.plus(f.mapUnits(N=>N*w));I=+L>+this.e?this.e:L,A.push(Je.fromDateTimes(g,I)),g=I,w+=1}return A}divideEqually(s){return this.isValid?this.splitBy(this.length()/s).slice(0,s):[]}overlaps(s){return this.e>s.s&&this.s<s.e}abutsStart(s){return this.isValid?+this.e==+s.s:!1}abutsEnd(s){return this.isValid?+s.e==+this.s:!1}engulfs(s){return this.isValid?this.s<=s.s&&this.e>=s.e:!1}equals(s){return!this.isValid||!s.isValid?!1:this.s.equals(s.s)&&this.e.equals(s.e)}intersection(s){if(!this.isValid)return this;const f=this.s>s.s?this.s:s.s,g=this.e<s.e?this.e:s.e;return f>=g?null:Je.fromDateTimes(f,g)}union(s){if(!this.isValid)return this;const f=this.s<s.s?this.s:s.s,g=this.e>s.e?this.e:s.e;return Je.fromDateTimes(f,g)}static merge(s){const[f,g]=s.sort((w,I)=>w.s-I.s).reduce(([w,I],A)=>I?I.overlaps(A)||I.abutsStart(A)?[w,I.union(A)]:[w.concat([I]),A]:[w,A],[[],null]);return g&&f.push(g),f}static xor(s){let f=null,g=0;const w=[],I=s.map(N=>[{time:N.s,type:"s"},{time:N.e,type:"e"}]),A=Array.prototype.concat(...I),L=A.sort((N,X)=>N.time-X.time);for(const N of L)g+=N.type==="s"?1:-1,g===1?f=N.time:(f&&+f!=+N.time&&w.push(Je.fromDateTimes(f,N.time)),f=null);return Je.merge(w)}difference(...s){return Je.xor([this].concat(s)).map(f=>this.intersection(f)).filter(f=>f&&!f.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:On}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(s=b,f={}){return this.isValid?ft.create(this.s.loc.clone(f),s).formatInterval(this):On}toISO(s){return this.isValid?`${this.s.toISO(s)}/${this.e.toISO(s)}`:On}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:On}toISOTime(s){return this.isValid?`${this.s.toISOTime(s)}/${this.e.toISOTime(s)}`:On}toFormat(s,{separator:f=" – "}={}){return this.isValid?`${this.s.toFormat(s)}${f}${this.e.toFormat(s)}`:On}toDuration(s,f){return this.isValid?this.e.diff(this.s,s,f):Ae.invalid(this.invalidReason)}mapEndpoints(s){return Je.fromDateTimes(s(this.s),s(this.e))}}class Gn{static hasDST(s=Ne.defaultZone){const f=ke.now().setZone(s).set({month:12});return!s.isUniversal&&f.offset!==f.set({month:6}).offset}static isValidIANAZone(s){return ue.isValidZone(s)}static normalizeZone(s){return ct(s,Ne.defaultZone)}static getStartOfWeek({locale:s=null,locObj:f=null}={}){return(f||fe.create(s)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:s=null,locObj:f=null}={}){return(f||fe.create(s)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:s=null,locObj:f=null}={}){return(f||fe.create(s)).getWeekendDays().slice()}static months(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null,outputCalendar:I="gregory"}={}){return(w||fe.create(f,g,I)).months(s)}static monthsFormat(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null,outputCalendar:I="gregory"}={}){return(w||fe.create(f,g,I)).months(s,!0)}static weekdays(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null}={}){return(w||fe.create(f,g,null)).weekdays(s)}static weekdaysFormat(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null}={}){return(w||fe.create(f,g,null)).weekdays(s,!0)}static meridiems({locale:s=null}={}){return fe.create(s).meridiems()}static eras(s="short",{locale:f=null}={}){return fe.create(f,null,"gregory").eras(s)}static features(){return{relative:zn(),localeWeek:Wn()}}}function ti(m,s){const f=w=>w.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),g=f(s)-f(m);return Math.floor(Ae.fromMillis(g).as("days"))}function wu(m,s,f){const g=[["years",(N,X)=>X.year-N.year],["quarters",(N,X)=>X.quarter-N.quarter+(X.year-N.year)*4],["months",(N,X)=>X.month-N.month+(X.year-N.year)*12],["weeks",(N,X)=>{const xe=ti(N,X);return(xe-xe%7)/7}],["days",ti]],w={},I=m;let A,L;for(const[N,X]of g)f.indexOf(N)>=0&&(A=N,w[N]=X(m,s),L=I.plus(w),L>s?(w[N]--,m=I.plus(w),m>s&&(L=m,w[N]--,m=I.plus(w))):m=L);return[m,w,L,A]}function Su(m,s,f,g){let[w,I,A,L]=wu(m,s,f);const N=s-w,X=f.filter(Te=>["hours","minutes","seconds","milliseconds"].indexOf(Te)>=0);X.length===0&&(A<s&&(A=w.plus({[L]:1})),A!==w&&(I[L]=(I[L]||0)+N/(A-w)));const xe=Ae.fromObject(I,g);return X.length>0?Ae.fromMillis(N,g).shiftTo(...X).plus(xe):xe}const ku="missing Intl.DateTimeFormat.formatToParts support";function _e(m,s=f=>f){return{regex:m,deser:([f])=>s(vt(f))}}const ni="[ ]",ri=new RegExp(ni,"g");function Cu(m){return m.replace(/\./g,"\\.?").replace(ri,ni)}function si(m){return m.replace(/\./g,"").replace(ri," ").toLowerCase()}function Rt(m,s){return m===null?null:{regex:RegExp(m.map(Cu).join("|")),deser:([f])=>m.findIndex(g=>si(f)===si(g))+s}}function oi(m,s){return{regex:m,deser:([,f,g])=>Ar(f,g),groups:s}}function _r(m){return{regex:m,deser:([s])=>s}}function ju(m){return m.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Tu(m,s){const f=Ie(s),g=Ie(s,"{2}"),w=Ie(s,"{3}"),I=Ie(s,"{4}"),A=Ie(s,"{6}"),L=Ie(s,"{1,2}"),N=Ie(s,"{1,3}"),X=Ie(s,"{1,6}"),xe=Ie(s,"{1,9}"),Te=Ie(s,"{2,4}"),Be=Ie(s,"{4,6}"),Se=Wt=>({regex:RegExp(ju(Wt.val)),deser:([En])=>En,literal:!0}),Lt=(Wt=>{if(m.literal)return Se(Wt);switch(Wt.val){case"G":return Rt(s.eras("short"),0);case"GG":return Rt(s.eras("long"),0);case"y":return _e(X);case"yy":return _e(Te,ms);case"yyyy":return _e(I);case"yyyyy":return _e(Be);case"yyyyyy":return _e(A);case"M":return _e(L);case"MM":return _e(g);case"MMM":return Rt(s.months("short",!0),1);case"MMMM":return Rt(s.months("long",!0),1);case"L":return _e(L);case"LL":return _e(g);case"LLL":return Rt(s.months("short",!1),1);case"LLLL":return Rt(s.months("long",!1),1);case"d":return _e(L);case"dd":return _e(g);case"o":return _e(N);case"ooo":return _e(w);case"HH":return _e(g);case"H":return _e(L);case"hh":return _e(g);case"h":return _e(L);case"mm":return _e(g);case"m":return _e(L);case"q":return _e(L);case"qq":return _e(g);case"s":return _e(L);case"ss":return _e(g);case"S":return _e(N);case"SSS":return _e(w);case"u":return _r(xe);case"uu":return _r(L);case"uuu":return _e(f);case"a":return Rt(s.meridiems(),0);case"kkkk":return _e(I);case"kk":return _e(Te,ms);case"W":return _e(L);case"WW":return _e(g);case"E":case"c":return _e(f);case"EEE":return Rt(s.weekdays("short",!1),1);case"EEEE":return Rt(s.weekdays("long",!1),1);case"ccc":return Rt(s.weekdays("short",!0),1);case"cccc":return Rt(s.weekdays("long",!0),1);case"Z":case"ZZ":return oi(new RegExp(`([+-]${L.source})(?::(${g.source}))?`),2);case"ZZZ":return oi(new RegExp(`([+-]${L.source})(${g.source})?`),2);case"z":return _r(/[a-z_+-/]{1,256}?/i);case" ":return _r(/[^\S\n\r]/);default:return Se(Wt)}})(m)||{invalidReason:ku};return Lt.token=m,Lt}const Ou={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 Mu(m,s,f){const{type:g,value:w}=m;if(g==="literal"){const N=/^\s+$/.test(w);return{literal:!N,val:N?" ":w}}const I=s[g];let A=g;g==="hour"&&(s.hour12!=null?A=s.hour12?"hour12":"hour24":s.hourCycle!=null?s.hourCycle==="h11"||s.hourCycle==="h12"?A="hour12":A="hour24":A=f.hour12?"hour12":"hour24");let L=Ou[A];if(typeof L=="object"&&(L=L[I]),L)return{literal:!1,val:L}}function Eu(m){return[`^${m.map(f=>f.regex).reduce((f,g)=>`${f}(${g.source})`,"")}$`,m]}function Iu(m,s,f){const g=m.match(s);if(g){const w={};let I=1;for(const A in f)if(gt(f,A)){const L=f[A],N=L.groups?L.groups+1:1;!L.literal&&L.token&&(w[L.token.val[0]]=L.deser(g.slice(I,I+N))),I+=N}return[g,w]}else return[g,{}]}function Du(m){const s=I=>{switch(I){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 f=null,g;return ee(m.z)||(f=ue.create(m.z)),ee(m.Z)||(f||(f=new ze(m.Z)),g=m.Z),ee(m.q)||(m.M=(m.q-1)*3+1),ee(m.h)||(m.h<12&&m.a===1?m.h+=12:m.h===12&&m.a===0&&(m.h=0)),m.G===0&&m.y&&(m.y=-m.y),ee(m.u)||(m.S=hs(m.u)),[Object.keys(m).reduce((I,A)=>{const L=s(A);return L&&(I[L]=m[A]),I},{}),f,g]}let xs=null;function $u(){return xs||(xs=ke.fromMillis(1555555555555)),xs}function Fu(m,s){if(m.literal)return m;const f=ft.macroTokenToFormatOpts(m.val),g=ci(f,s);return g==null||g.includes(void 0)?m:g}function ii(m,s){return Array.prototype.concat(...m.map(f=>Fu(f,s)))}class ai{constructor(s,f){if(this.locale=s,this.format=f,this.tokens=ii(ft.parseFormat(f),s),this.units=this.tokens.map(g=>Tu(g,s)),this.disqualifyingUnit=this.units.find(g=>g.invalidReason),!this.disqualifyingUnit){const[g,w]=Eu(this.units);this.regex=RegExp(g,"i"),this.handlers=w}}explainFromTokens(s){if(this.isValid){const[f,g]=Iu(s,this.regex,this.handlers),[w,I,A]=g?Du(g):[null,null,void 0];if(gt(g,"a")&>(g,"H"))throw new i("Can't include meridiem when specifying 24-hour format");return{input:s,tokens:this.tokens,regex:this.regex,rawMatches:f,matches:g,result:w,zone:I,specificOffset:A}}else return{input:s,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function li(m,s,f){return new ai(m,f).explainFromTokens(s)}function Au(m,s,f){const{result:g,zone:w,specificOffset:I,invalidReason:A}=li(m,s,f);return[g,w,I,A]}function ci(m,s){if(!m)return null;const g=ft.create(s,m).dtFormatter($u()),w=g.formatToParts(),I=g.resolvedOptions();return w.map(A=>Mu(A,m,I))}const vs="Invalid DateTime",ui=864e13;function Yn(m){return new ut("unsupported zone",`the zone "${m.name}" is not supported`)}function bs(m){return m.weekData===null&&(m.weekData=Xe(m.c)),m.weekData}function ws(m){return m.localWeekData===null&&(m.localWeekData=Xe(m.c,m.loc.getMinDaysInFirstWeek(),m.loc.getStartOfWeek())),m.localWeekData}function on(m,s){const f={ts:m.ts,zone:m.zone,c:m.c,o:m.o,loc:m.loc,invalid:m.invalid};return new ke({...f,...s,old:f})}function di(m,s,f){let g=m-s*60*1e3;const w=f.offset(g);if(s===w)return[g,s];g-=(w-s)*60*1e3;const I=f.offset(g);return w===I?[g,w]:[m-Math.min(w,I)*60*1e3,Math.max(w,I)]}function Nr(m,s){m+=s*60*1e3;const f=new Date(m);return{year:f.getUTCFullYear(),month:f.getUTCMonth()+1,day:f.getUTCDate(),hour:f.getUTCHours(),minute:f.getUTCMinutes(),second:f.getUTCSeconds(),millisecond:f.getUTCMilliseconds()}}function Pr(m,s,f){return di(Fr(m),s,f)}function hi(m,s){const f=m.o,g=m.c.year+Math.trunc(s.years),w=m.c.month+Math.trunc(s.months)+Math.trunc(s.quarters)*3,I={...m.c,year:g,month:w,day:Math.min(m.c.day,$r(g,w))+Math.trunc(s.days)+Math.trunc(s.weeks)*7},A=Ae.fromObject({years:s.years-Math.trunc(s.years),quarters:s.quarters-Math.trunc(s.quarters),months:s.months-Math.trunc(s.months),weeks:s.weeks-Math.trunc(s.weeks),days:s.days-Math.trunc(s.days),hours:s.hours,minutes:s.minutes,seconds:s.seconds,milliseconds:s.milliseconds}).as("milliseconds"),L=Fr(I);let[N,X]=di(L,f,m.zone);return A!==0&&(N+=A,X=m.zone.offset(N)),{ts:N,o:X}}function Mn(m,s,f,g,w,I){const{setZone:A,zone:L}=f;if(m&&Object.keys(m).length!==0||s){const N=s||L,X=ke.fromObject(m,{...f,zone:N,specificOffset:I});return A?X:X.setZone(L)}else return ke.invalid(new ut("unparsable",`the input "${w}" can't be parsed as ${g}`))}function zr(m,s,f=!0){return m.isValid?ft.create(fe.create("en-US"),{allowZ:f,forceSimple:!0}).formatDateTimeFromString(m,s):null}function Ss(m,s,f){const g=m.c.year>9999||m.c.year<0;let w="";if(g&&m.c.year>=0&&(w+="+"),w+=ot(m.c.year,g?6:4),f==="year")return w;if(s){if(w+="-",w+=ot(m.c.month),f==="month")return w;w+="-"}else if(w+=ot(m.c.month),f==="month")return w;return w+=ot(m.c.day),w}function fi(m,s,f,g,w,I,A){let L=!f||m.c.millisecond!==0||m.c.second!==0,N="";switch(A){case"day":case"month":case"year":break;default:if(N+=ot(m.c.hour),A==="hour")break;if(s){if(N+=":",N+=ot(m.c.minute),A==="minute")break;L&&(N+=":",N+=ot(m.c.second))}else{if(N+=ot(m.c.minute),A==="minute")break;L&&(N+=ot(m.c.second))}if(A==="second")break;L&&(!g||m.c.millisecond!==0)&&(N+=".",N+=ot(m.c.millisecond,3))}return w&&(m.isOffsetFixed&&m.offset===0&&!I?N+="Z":m.o<0?(N+="-",N+=ot(Math.trunc(-m.o/60)),N+=":",N+=ot(Math.trunc(-m.o%60))):(N+="+",N+=ot(Math.trunc(m.o/60)),N+=":",N+=ot(Math.trunc(m.o%60)))),I&&(N+="["+m.zone.ianaName+"]"),N}const mi={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Ru={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Lu={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Wr=["year","month","day","hour","minute","second","millisecond"],_u=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Nu=["year","ordinal","hour","minute","second","millisecond"];function qr(m){const s={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"}[m.toLowerCase()];if(!s)throw new l(m);return s}function pi(m){switch(m.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return qr(m)}}function Pu(m){if(Kn===void 0&&(Kn=Ne.now()),m.type!=="iana")return m.offset(Kn);const s=m.name;let f=ks.get(s);return f===void 0&&(f=m.offset(Kn),ks.set(s,f)),f}function gi(m,s){const f=ct(s.zone,Ne.defaultZone);if(!f.isValid)return ke.invalid(Yn(f));const g=fe.fromObject(s);let w,I;if(ee(m.year))w=Ne.now();else{for(const N of Wr)ee(m[N])&&(m[N]=mi[N]);const A=le(m)||ve(m);if(A)return ke.invalid(A);const L=Pu(f);[w,I]=Pr(m,L,f)}return new ke({ts:w,zone:f,loc:g,o:I})}function yi(m,s,f){const g=ee(f.round)?!0:f.round,w=ee(f.rounding)?"trunc":f.rounding,I=(L,N)=>(L=fs(L,g||f.calendary?0:2,f.calendary?"round":w),s.loc.clone(f).relFormatter(f).format(L,N)),A=L=>f.calendary?s.hasSame(m,L)?0:s.startOf(L).diff(m.startOf(L),L).get(L):s.diff(m,L).get(L);if(f.unit)return I(A(f.unit),f.unit);for(const L of f.units){const N=A(L);if(Math.abs(N)>=1)return I(N,L)}return I(m>s?-0:0,f.units[f.units.length-1])}function xi(m){let s={},f;return m.length>0&&typeof m[m.length-1]=="object"?(s=m[m.length-1],f=Array.from(m).slice(0,m.length-1)):f=Array.from(m),[s,f]}let Kn;const ks=new Map;class ke{constructor(s){const f=s.zone||Ne.defaultZone;let g=s.invalid||(Number.isNaN(s.ts)?new ut("invalid input"):null)||(f.isValid?null:Yn(f));this.ts=ee(s.ts)?Ne.now():s.ts;let w=null,I=null;if(!g)if(s.old&&s.old.ts===this.ts&&s.old.zone.equals(f))[w,I]=[s.old.c,s.old.o];else{const L=qe(s.o)&&!s.old?s.o:f.offset(this.ts);w=Nr(this.ts,L),g=Number.isNaN(w.year)?new ut("invalid input"):null,w=g?null:w,I=g?null:L}this._zone=f,this.loc=s.loc||fe.create(),this.invalid=g,this.weekData=null,this.localWeekData=null,this.c=w,this.o=I,this.isLuxonDateTime=!0}static now(){return new ke({})}static local(){const[s,f]=xi(arguments),[g,w,I,A,L,N,X]=f;return gi({year:g,month:w,day:I,hour:A,minute:L,second:N,millisecond:X},s)}static utc(){const[s,f]=xi(arguments),[g,w,I,A,L,N,X]=f;return s.zone=ze.utcInstance,gi({year:g,month:w,day:I,hour:A,minute:L,second:N,millisecond:X},s)}static fromJSDate(s,f={}){const g=vn(s)?s.valueOf():NaN;if(Number.isNaN(g))return ke.invalid("invalid input");const w=ct(f.zone,Ne.defaultZone);return w.isValid?new ke({ts:g,zone:w,loc:fe.fromObject(f)}):ke.invalid(Yn(w))}static fromMillis(s,f={}){if(qe(s))return s<-ui||s>ui?ke.invalid("Timestamp out of range"):new ke({ts:s,zone:ct(f.zone,Ne.defaultZone),loc:fe.fromObject(f)});throw new a(`fromMillis requires a numerical input, but received a ${typeof s} with value ${s}`)}static fromSeconds(s,f={}){if(qe(s))return new ke({ts:s*1e3,zone:ct(f.zone,Ne.defaultZone),loc:fe.fromObject(f)});throw new a("fromSeconds requires a numerical input")}static fromObject(s,f={}){s=s||{};const g=ct(f.zone,Ne.defaultZone);if(!g.isValid)return ke.invalid(Yn(g));const w=fe.fromObject(f),I=Rr(s,pi),{minDaysInFirstWeek:A,startOfWeek:L}=nn(I,w),N=Ne.now(),X=ee(f.specificOffset)?g.offset(N):f.specificOffset,xe=!ee(I.ordinal),Te=!ee(I.year),Be=!ee(I.month)||!ee(I.day),Se=Te||Be,it=I.weekYear||I.weekNumber;if((Se||xe)&&it)throw new i("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(Be&&xe)throw new i("Can't mix ordinal dates with month/day");const Lt=it||I.weekday&&!Se;let Wt,En,Zn=Nr(N,X);Lt?(Wt=_u,En=Ru,Zn=Xe(Zn,A,L)):xe?(Wt=Nu,En=Lu,Zn=tn(Zn)):(Wt=Wr,En=mi);let vi=!1;for(const Jn of Wt){const Hu=I[Jn];ee(Hu)?vi?I[Jn]=En[Jn]:I[Jn]=Zn[Jn]:vi=!0}const Wu=Lt?G(I,A,L):xe?U(I):le(I),bi=Wu||ve(I);if(bi)return ke.invalid(bi);const qu=Lt?At(I,A,L):xe?Zt(I):I,[Bu,Vu]=Pr(qu,X,g),Xn=new ke({ts:Bu,zone:g,o:Vu,loc:w});return I.weekday&&Se&&s.weekday!==Xn.weekday?ke.invalid("mismatched weekday",`you can't specify both a weekday of ${I.weekday} and a date of ${Xn.toISO()}`):Xn.isValid?Xn:ke.invalid(Xn.invalid)}static fromISO(s,f={}){const[g,w]=au(s);return Mn(g,w,f,"ISO 8601",s)}static fromRFC2822(s,f={}){const[g,w]=lu(s);return Mn(g,w,f,"RFC 2822",s)}static fromHTTP(s,f={}){const[g,w]=cu(s);return Mn(g,w,f,"HTTP",f)}static fromFormat(s,f,g={}){if(ee(s)||ee(f))throw new a("fromFormat requires an input string and a format");const{locale:w=null,numberingSystem:I=null}=g,A=fe.fromOpts({locale:w,numberingSystem:I,defaultToEN:!0}),[L,N,X,xe]=Au(A,s,f);return xe?ke.invalid(xe):Mn(L,N,g,`format ${f}`,s,X)}static fromString(s,f,g={}){return ke.fromFormat(s,f,g)}static fromSQL(s,f={}){const[g,w]=gu(s);return Mn(g,w,f,"SQL",s)}static invalid(s,f=null){if(!s)throw new a("need to specify a reason the DateTime is invalid");const g=s instanceof ut?s:new ut(s,f);if(Ne.throwOnInvalid)throw new n(g);return new ke({invalid:g})}static isDateTime(s){return s&&s.isLuxonDateTime||!1}static parseFormatForOpts(s,f={}){const g=ci(s,fe.fromObject(f));return g?g.map(w=>w?w.val:null).join(""):null}static expandFormat(s,f={}){return ii(ft.parseFormat(s),fe.fromObject(f)).map(w=>w.val).join("")}static resetCache(){Kn=void 0,ks.clear()}get(s){return this[s]}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?bs(this).weekYear:NaN}get weekNumber(){return this.isValid?bs(this).weekNumber:NaN}get weekday(){return this.isValid?bs(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?ws(this).weekday:NaN}get localWeekNumber(){return this.isValid?ws(this).weekNumber:NaN}get localWeekYear(){return this.isValid?ws(this).weekYear:NaN}get ordinal(){return this.isValid?tn(this.c).ordinal:NaN}get monthShort(){return this.isValid?Gn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Gn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Gn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Gn.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 s=864e5,f=6e4,g=Fr(this.c),w=this.zone.offset(g-s),I=this.zone.offset(g+s),A=this.zone.offset(g-w*f),L=this.zone.offset(g-I*f);if(A===L)return[this];const N=g-A*f,X=g-L*f,xe=Nr(N,A),Te=Nr(X,L);return xe.hour===Te.hour&&xe.minute===Te.minute&&xe.second===Te.second&&xe.millisecond===Te.millisecond?[on(this,{ts:N}),on(this,{ts:X})]:[this]}get isInLeapYear(){return qn(this.year)}get daysInMonth(){return $r(this.year,this.month)}get daysInYear(){return this.isValid?bn(this.year):NaN}get weeksInWeekYear(){return this.isValid?Bn(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Bn(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(s={}){const{locale:f,numberingSystem:g,calendar:w}=ft.create(this.loc.clone(s),s).resolvedOptions(this);return{locale:f,numberingSystem:g,outputCalendar:w}}toUTC(s=0,f={}){return this.setZone(ze.instance(s),f)}toLocal(){return this.setZone(Ne.defaultZone)}setZone(s,{keepLocalTime:f=!1,keepCalendarTime:g=!1}={}){if(s=ct(s,Ne.defaultZone),s.equals(this.zone))return this;if(s.isValid){let w=this.ts;if(f||g){const I=s.offset(this.ts),A=this.toObject();[w]=Pr(A,I,s)}return on(this,{ts:w,zone:s})}else return ke.invalid(Yn(s))}reconfigure({locale:s,numberingSystem:f,outputCalendar:g}={}){const w=this.loc.clone({locale:s,numberingSystem:f,outputCalendar:g});return on(this,{loc:w})}setLocale(s){return this.reconfigure({locale:s})}set(s){if(!this.isValid)return this;const f=Rr(s,pi),{minDaysInFirstWeek:g,startOfWeek:w}=nn(f,this.loc),I=!ee(f.weekYear)||!ee(f.weekNumber)||!ee(f.weekday),A=!ee(f.ordinal),L=!ee(f.year),N=!ee(f.month)||!ee(f.day),X=L||N,xe=f.weekYear||f.weekNumber;if((X||A)&&xe)throw new i("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(N&&A)throw new i("Can't mix ordinal dates with month/day");let Te;I?Te=At({...Xe(this.c,g,w),...f},g,w):ee(f.ordinal)?(Te={...this.toObject(),...f},ee(f.day)&&(Te.day=Math.min($r(Te.year,Te.month),Te.day))):Te=Zt({...tn(this.c),...f});const[Be,Se]=Pr(Te,this.o,this.zone);return on(this,{ts:Be,o:Se})}plus(s){if(!this.isValid)return this;const f=Ae.fromDurationLike(s);return on(this,hi(this,f))}minus(s){if(!this.isValid)return this;const f=Ae.fromDurationLike(s).negate();return on(this,hi(this,f))}startOf(s,{useLocaleWeeks:f=!1}={}){if(!this.isValid)return this;const g={},w=Ae.normalizeUnit(s);switch(w){case"years":g.month=1;case"quarters":case"months":g.day=1;case"weeks":case"days":g.hour=0;case"hours":g.minute=0;case"minutes":g.second=0;case"seconds":g.millisecond=0;break}if(w==="weeks")if(f){const I=this.loc.getStartOfWeek(),{weekday:A}=this;A<I&&(g.weekNumber=this.weekNumber-1),g.weekday=I}else g.weekday=1;if(w==="quarters"){const I=Math.ceil(this.month/3);g.month=(I-1)*3+1}return this.set(g)}endOf(s,f){return this.isValid?this.plus({[s]:1}).startOf(s,f).minus(1):this}toFormat(s,f={}){return this.isValid?ft.create(this.loc.redefaultToEN(f)).formatDateTimeFromString(this,s):vs}toLocaleString(s=b,f={}){return this.isValid?ft.create(this.loc.clone(f),s).formatDateTime(this):vs}toLocaleParts(s={}){return this.isValid?ft.create(this.loc.clone(s),s).formatDateTimeParts(this):[]}toISO({format:s="extended",suppressSeconds:f=!1,suppressMilliseconds:g=!1,includeOffset:w=!0,extendedZone:I=!1,precision:A="milliseconds"}={}){if(!this.isValid)return null;A=qr(A);const L=s==="extended";let N=Ss(this,L,A);return Wr.indexOf(A)>=3&&(N+="T"),N+=fi(this,L,f,g,w,I,A),N}toISODate({format:s="extended",precision:f="day"}={}){return this.isValid?Ss(this,s==="extended",qr(f)):null}toISOWeekDate(){return zr(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:s=!1,suppressSeconds:f=!1,includeOffset:g=!0,includePrefix:w=!1,extendedZone:I=!1,format:A="extended",precision:L="milliseconds"}={}){return this.isValid?(L=qr(L),(w&&Wr.indexOf(L)>=3?"T":"")+fi(this,A==="extended",f,s,g,I,L)):null}toRFC2822(){return zr(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return zr(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Ss(this,!0):null}toSQLTime({includeOffset:s=!0,includeZone:f=!1,includeOffsetSpace:g=!0}={}){let w="HH:mm:ss.SSS";return(f||s)&&(g&&(w+=" "),f?w+="z":s&&(w+="ZZ")),zr(this,w,!0)}toSQL(s={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(s)}`:null}toString(){return this.isValid?this.toISO():vs}[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(s={}){if(!this.isValid)return{};const f={...this.c};return s.includeConfig&&(f.outputCalendar=this.outputCalendar,f.numberingSystem=this.loc.numberingSystem,f.locale=this.loc.locale),f}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(s,f="milliseconds",g={}){if(!this.isValid||!s.isValid)return Ae.invalid("created by diffing an invalid DateTime");const w={locale:this.locale,numberingSystem:this.numberingSystem,...g},I=Dr(f).map(Ae.normalizeUnit),A=s.valueOf()>this.valueOf(),L=A?this:s,N=A?s:this,X=Su(L,N,I,w);return A?X.negate():X}diffNow(s="milliseconds",f={}){return this.diff(ke.now(),s,f)}until(s){return this.isValid?Je.fromDateTimes(this,s):this}hasSame(s,f,g){if(!this.isValid)return!1;const w=s.valueOf(),I=this.setZone(s.zone,{keepLocalTime:!0});return I.startOf(f,g)<=w&&w<=I.endOf(f,g)}equals(s){return this.isValid&&s.isValid&&this.valueOf()===s.valueOf()&&this.zone.equals(s.zone)&&this.loc.equals(s.loc)}toRelative(s={}){if(!this.isValid)return null;const f=s.base||ke.fromObject({},{zone:this.zone}),g=s.padding?this<f?-s.padding:s.padding:0;let w=["years","months","days","hours","minutes","seconds"],I=s.unit;return Array.isArray(s.unit)&&(w=s.unit,I=void 0),yi(f,this.plus(g),{...s,numeric:"always",units:w,unit:I})}toRelativeCalendar(s={}){return this.isValid?yi(s.base||ke.fromObject({},{zone:this.zone}),this,{...s,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...s){if(!s.every(ke.isDateTime))throw new a("min requires all arguments be DateTimes");return $e(s,f=>f.valueOf(),Math.min)}static max(...s){if(!s.every(ke.isDateTime))throw new a("max requires all arguments be DateTimes");return $e(s,f=>f.valueOf(),Math.max)}static fromFormatExplain(s,f,g={}){const{locale:w=null,numberingSystem:I=null}=g,A=fe.fromOpts({locale:w,numberingSystem:I,defaultToEN:!0});return li(A,s,f)}static fromStringExplain(s,f,g={}){return ke.fromFormatExplain(s,f,g)}static buildFormatParser(s,f={}){const{locale:g=null,numberingSystem:w=null}=f,I=fe.fromOpts({locale:g,numberingSystem:w,defaultToEN:!0});return new ai(I,s)}static fromFormatParser(s,f,g={}){if(ee(s)||ee(f))throw new a("fromFormatParser requires an input string and a format parser");const{locale:w=null,numberingSystem:I=null}=g,A=fe.fromOpts({locale:w,numberingSystem:I,defaultToEN:!0});if(!A.equals(f.locale))throw new a(`fromFormatParser called with a locale of ${A}, but the format parser was created for ${f.locale}`);const{result:L,zone:N,specificOffset:X,invalidReason:xe}=f.explainFromTokens(s);return xe?ke.invalid(xe):Mn(L,N,g,`format ${f.format}`,s,X)}static get DATE_SHORT(){return b}static get DATE_MED(){return x}static get DATE_MED_WITH_WEEKDAY(){return v}static get DATE_FULL(){return k}static get DATE_HUGE(){return C}static get TIME_SIMPLE(){return S}static get TIME_WITH_SECONDS(){return T}static get TIME_WITH_SHORT_OFFSET(){return O}static get TIME_WITH_LONG_OFFSET(){return M}static get TIME_24_SIMPLE(){return E}static get TIME_24_WITH_SECONDS(){return R}static get TIME_24_WITH_SHORT_OFFSET(){return P}static get TIME_24_WITH_LONG_OFFSET(){return F}static get DATETIME_SHORT(){return B}static get DATETIME_SHORT_WITH_SECONDS(){return D}static get DATETIME_MED(){return _}static get DATETIME_MED_WITH_SECONDS(){return V}static get DATETIME_MED_WITH_WEEKDAY(){return $}static get DATETIME_FULL(){return W}static get DATETIME_FULL_WITH_SECONDS(){return Z}static get DATETIME_HUGE(){return ne}static get DATETIME_HUGE_WITH_SECONDS(){return J}}function Qn(m){if(ke.isDateTime(m))return m;if(m&&m.valueOf&&qe(m.valueOf()))return ke.fromJSDate(m);if(m&&typeof m=="object")return ke.fromObject(m);throw new a(`Unknown datetime argument: ${m}, of type ${typeof m}`)}const zu="3.7.2";return bt.DateTime=ke,bt.Duration=Ae,bt.FixedOffsetZone=ze,bt.IANAZone=ue,bt.Info=Gn,bt.Interval=Je,bt.InvalidZone=lt,bt.Settings=Ne,bt.SystemZone=re,bt.VERSION=zu,bt.Zone=H,bt}var Zi;function lo(){return Zi||(Zi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CronDate=e.DAYS_IN_MONTH=e.DateMathOp=e.TimeUnit=void 0;const n=yf();var r;(function(l){l.Second="Second",l.Minute="Minute",l.Hour="Hour",l.Day="Day",l.Month="Month",l.Year="Year"})(r||(e.TimeUnit=r={}));var o;(function(l){l.Add="Add",l.Subtract="Subtract"})(o||(e.DateMathOp=o={})),e.DAYS_IN_MONTH=Object.freeze([31,29,31,30,31,30,31,31,30,31,30,31]);class i{#e;#n=null;#o=null;constructor(a,u){const d={zone:u};if(a?a instanceof i?(this.#e=a.#e,this.#n=a.#n,this.#o=a.#o):a instanceof Date?this.#e=n.DateTime.fromJSDate(a,d):typeof a=="number"?this.#e=n.DateTime.fromMillis(a,d):(this.#e=n.DateTime.fromISO(a,d),this.#e.isValid||(this.#e=n.DateTime.fromRFC2822(a,d)),this.#e.isValid||(this.#e=n.DateTime.fromSQL(a,d)),this.#e.isValid||(this.#e=n.DateTime.fromFormat(a,"EEE, d MMM yyyy HH:mm:ss",d))):this.#e=n.DateTime.local(),!this.#e.isValid)throw new Error(`CronDate: unhandled timestamp: ${a}`);u&&u!==this.#e.zoneName&&(this.#e=this.#e.setZone(u))}static#s(a){return a%4===0&&a%100!==0||a%400===0}get dstStart(){return this.#n}set dstStart(a){this.#n=a}get dstEnd(){return this.#o}set dstEnd(a){this.#o=a}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(a){switch(a){case r.Year:return this.addYear();case r.Month:return this.addMonth();case r.Day:return this.addDay();case r.Hour:return this.addHour();case r.Minute:return this.addMinute();case r.Second:return this.addSecond()}}subtractUnit(a){switch(a){case r.Year:return this.subtractYear();case r.Month:return this.subtractMonth();case r.Day:return this.subtractDay();case r.Hour:return this.subtractHour();case r.Minute:return this.subtractMinute();case r.Second:return this.subtractSecond()}}invokeDateOperation(a,u){if(a===o.Add){this.addUnit(u);return}if(a===o.Subtract){this.subtractUnit(u);return}throw new Error(`Invalid verb: ${a}`)}getDate(){return this.#e.day}getFullYear(){return this.#e.year}getDay(){const a=this.#e.weekday;return a===7?0:a}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 a=this.#r().weekday;return a===7?0:a}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(a){this.#e=this.#e.set({day:a})}setFullYear(a){this.#e=this.#e.set({year:a})}setDay(a){this.#e=this.#e.set({weekday:a})}setMonth(a){this.#e=this.#e.set({month:a+1})}setHours(a){this.#e=this.#e.set({hour:a})}setMinutes(a){this.#e=this.#e.set({minute:a})}setSeconds(a){this.#e=this.#e.set({second:a})}setMilliseconds(a){this.#e=this.#e.set({millisecond:a})}toString(){return this.toDate().toString()}toDate(){return this.#e.toJSDate()}isLastDayOfMonth(){const{day:a,month:u}=this.#e;if(u===2){const d=i.#s(this.#e.year);return a===e.DAYS_IN_MONTH[u-1]-(d?0:1)}return a===e.DAYS_IN_MONTH[u-1]}isLastWeekdayOfMonth(){const{day:a,month:u}=this.#e;let d;return u===2?d=e.DAYS_IN_MONTH[u-1]-(i.#s(this.#e.year)?0:1):d=e.DAYS_IN_MONTH[u-1],a>d-7}applyDateOperation(a,u,d){if(u===r.Month||u===r.Day){this.invokeDateOperation(a,u);return}const h=this.getHours();this.invokeDateOperation(a,u);const y=this.getHours(),b=y-h;b===2?d!==24&&(this.dstStart=h+1):b===0&&this.getMinutes()===0&&this.getSeconds()===0&&d!==24&&(this.dstEnd=y)}#r(){return this.#e.toUTC()}}e.CronDate=i,e.default=i})(Es)),Es}var Xi;function xf(){if(Xi)return ar;Xi=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.CronMonth=void 0;const e=lo(),n=mn(),r=1,o=12,i=Object.freeze([]);let l=class extends n.CronField{static get min(){return r}static get max(){return o}static get chars(){return i}static get daysInMonth(){return e.DAYS_IN_MONTH}constructor(u,d){super(u,d),this.validate()}get values(){return super.values}};return ar.CronMonth=l,ar}var lr={},Ji;function vf(){if(Ji)return lr;Ji=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.CronSecond=void 0;const e=mn(),n=0,r=59,o=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}};return lr.CronSecond=i,lr}var ea;function co(){return ea||(ea=1,(function(e){var n=ln&&ln.__createBinding||(Object.create?(function(o,i,l,a){a===void 0&&(a=l);var u=Object.getOwnPropertyDescriptor(i,l);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[l]}}),Object.defineProperty(o,a,u)}):(function(o,i,l,a){a===void 0&&(a=l),o[a]=i[l]})),r=ln&&ln.__exportStar||function(o,i){for(var l in o)l!=="default"&&!Object.prototype.hasOwnProperty.call(i,l)&&n(i,o,l)};Object.defineProperty(e,"__esModule",{value:!0}),r(hf(),e),r(ff(),e),r(mf(),e),r(mn(),e),r(pf(),e),r(gf(),e),r(xf(),e),r(vf(),e)})(ln)),ln}var ta;function al(){if(ta)return tr;ta=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.CronFieldCollection=void 0;const e=co();let n=class gr{#e;#n;#o;#s;#r;#t;static from(o,i){return new gr({second:this.resolveField(e.CronSecond,o.second,i.second),minute:this.resolveField(e.CronMinute,o.minute,i.minute),hour:this.resolveField(e.CronHour,o.hour,i.hour),dayOfMonth:this.resolveField(e.CronDayOfMonth,o.dayOfMonth,i.dayOfMonth),month:this.resolveField(e.CronMonth,o.month,i.month),dayOfWeek:this.resolveField(e.CronDayOfWeek,o.dayOfWeek,i.dayOfWeek)})}static resolveField(o,i,l){return l?l instanceof e.CronField?l:new o(l):i}constructor({second:o,minute:i,hour:l,dayOfMonth:a,month:u,dayOfWeek:d}){if(!o)throw new Error("Validation error, Field second is missing");if(!i)throw new Error("Validation error, Field minute is missing");if(!l)throw new Error("Validation error, Field hour is missing");if(!a)throw new Error("Validation error, Field dayOfMonth is missing");if(!u)throw new Error("Validation error, Field month is missing");if(!d)throw new Error("Validation error, Field dayOfWeek is missing");if(u.values.length===1&&!a.hasLastChar&&d.isWildcard&&!(parseInt(a.values[0],10)<=e.CronMonth.daysInMonth[u.values[0]-1]))throw new Error("Invalid explicit day of month definition");this.#e=o,this.#n=i,this.#o=l,this.#r=u,this.#t=d,this.#s=a}get second(){return this.#e}get minute(){return this.#n}get hour(){return this.#o}get dayOfMonth(){return this.#s}get month(){return this.#r}get dayOfWeek(){return this.#t}static compactField(o){if(o.length===0)return[];const i=[];let l;return o.forEach((a,u,d)=>{if(l===void 0){l={start:a,count:1};return}const h=d[u-1]||l.start,y=d[u+1];if(a==="L"||a==="W"){i.push(l),i.push({start:a,count:1}),l=void 0;return}if(l.step===void 0&&y!==void 0){const b=a-h,x=y-a;if(b<=x){l={...l,count:2,end:a,step:b};return}l.step=1}a-(l.end??0)===l.step?(l.count++,l.end=a):(l.count===1?i.push({start:l.start,count:1}):l.count===2?(i.push({start:l.start,count:1}),i.push({start:l.end??h,count:1})):i.push(l),l={start:a,count:1})}),l&&i.push(l),i}static#c(o,i,l){const a=i.step;return a?a===1&&i.start===o.min&&i.end&&i.end>=l?o.hasQuestionMarkChar?"?":"*":a!==1&&i.start===o.min&&i.end&&i.end>=l-a+1?`*/${a}`:null:null}static#l(o,i){const l=o.step;if(l===1)return`${o.start}-${o.end}`;const a=o.start===0?o.count-1:o.count;if(!l)throw new Error("Unexpected range step");if(!o.end)throw new Error("Unexpected range end");if(l*a>o.end){const u=(h,y)=>{if(typeof o.start!="number")throw new Error("Unexpected range start");return y%l===0?o.start+y:null};if(typeof o.start!="number")throw new Error("Unexpected range start");const d={length:o.end-o.start+1};return Array.from(d,u).filter(h=>h!==null).join(",")}return o.end===i-l+1?`${o.start}/${l}`:`${o.start}-${o.end}/${l}`}stringifyField(o){let i=o.max,l=o.values;if(o instanceof e.CronDayOfWeek){i=6;const u=this.#t.values;l=u[u.length-1]===7?u.slice(0,-1):u}o instanceof e.CronDayOfMonth&&(i=this.#r.values.length===1?e.CronMonth.daysInMonth[this.#r.values[0]-1]:o.max);const a=gr.compactField(l);if(a.length===1){const u=gr.#c(o,a[0],i);if(u)return u}return a.map(u=>{const d=u.count===1?u.start.toString():gr.#l(u,i);return o instanceof e.CronDayOfWeek&&o.nthDay>0?`${d}#${o.nthDay}`:d}).join(",")}stringify(o=!1){const i=[];return o&&i.push(this.stringifyField(this.#e)),i.push(this.stringifyField(this.#n),this.stringifyField(this.#o),this.stringifyField(this.#s),this.stringifyField(this.#r),this.stringifyField(this.#t)),i.join(" ")}serialize(){return{second:this.#e.serialize(),minute:this.#n.serialize(),hour:this.#o.serialize(),dayOfMonth:this.#s.serialize(),month:this.#r.serialize(),dayOfWeek:this.#t.serialize()}}};return tr.CronFieldCollection=n,tr}var Is={},na;function ll(){return na||(na=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CronExpression=e.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE=e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE=void 0;const n=lo();e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE="Out of the time span range",e.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE="Invalid expression, loop limit exceeded";const r=1e4;class o{#e;#n;#o;#s;#r;#t;#c=null;#l=!1;constructor(l,a){this.#e=a,this.#n=a.tz,this.#s=a.startDate?new n.CronDate(a.startDate,this.#n):null,this.#r=a.endDate?new n.CronDate(a.endDate,this.#n):null;let u=a.currentDate??a.startDate;if(u){const d=new n.CronDate(u,this.#n);this.#s&&d.getTime()<this.#s.getTime()?u=this.#s:this.#r&&d.getTime()>this.#r.getTime()&&(u=this.#r)}this.#o=new n.CronDate(u,this.#n),this.#t=l}get fields(){return this.#t}static fieldsToExpression(l,a){return new o(l,a||{})}static#i(l,a){return a.some(u=>u===l)}#a(l,a){return l[a?l.length-1:0]}#d(l){const a=`${l.getFullYear()}-${l.getMonth()+1}-${l.getDate()}`;if(this.#c===a)return this.#l;const u=new n.CronDate(l);u.setStartOfDay();const d=new n.CronDate(l);return d.setEndOfDay(),this.#c=a,this.#l=u.getUTCOffset()!==d.getUTCOffset(),this.#l}#h(l,a,u){const d=this.#t.second.values,h=l.getSeconds(),y=this.#t.second.findNearestValue(h,u);if(y!==null){l.setSeconds(y);return}l.applyDateOperation(a,n.TimeUnit.Minute,this.#t.hour.values.length),l.setSeconds(this.#a(d,u))}#m(l,a,u){const d=this.#t.minute.values,h=this.#t.second.values,y=l.getMinutes(),b=this.#t.minute.findNearestValue(y,u);if(b!==null){l.setMinutes(b),l.setSeconds(this.#a(h,u));return}l.applyDateOperation(a,n.TimeUnit.Hour,this.#t.hour.values.length),l.setMinutes(this.#a(d,u)),l.setSeconds(this.#a(h,u))}static#p(l,a){const u=a.isLastWeekdayOfMonth();return l.some(d=>{const h=parseInt(d.toString().charAt(0),10)%7;if(Number.isNaN(h))throw new Error(`Invalid last weekday of the month expression: ${d}`);return a.getDay()===h&&u})}next(){return this.#u()}prev(){return this.#u(!0)}hasNext(){const l=this.#o;try{return this.#u(),!0}catch{return!1}finally{this.#o=l}}hasPrev(){const l=this.#o;try{return this.#u(!0),!0}catch{return!1}finally{this.#o=l}}take(l){const a=[];if(l>=0)for(let u=0;u<l;u++)try{a.push(this.next())}catch{return a}else for(let u=0;u>l;u--)try{a.push(this.prev())}catch{return a}return a}reset(l){this.#o=new n.CronDate(l||this.#e.currentDate,this.#n)}stringify(l=!1){return this.#t.stringify(l)}includesDate(l){const{second:a,minute:u,hour:d,month:h}=this.#t,y=new n.CronDate(l,this.#n);return!(!a.values.includes(y.getSeconds())||!u.values.includes(y.getMinutes())||!d.values.includes(y.getHours())||!h.values.includes(y.getMonth()+1)||!this.#f(y)||this.#t.dayOfWeek.nthDay>0&&Math.ceil(y.getDate()/7)!==this.#t.dayOfWeek.nthDay)}toString(){return this.#e.expression||this.stringify(!0)}#f(l){const a=this.#t.dayOfMonth.isWildcard,u=!a,d=this.#t.dayOfWeek.isWildcard,h=!d,y=o.#i(l.getDate(),this.#t.dayOfMonth.values)||this.#t.dayOfMonth.hasLastChar&&l.isLastDayOfMonth(),b=o.#i(l.getDay(),this.#t.dayOfWeek.values)||this.#t.dayOfWeek.hasLastChar&&o.#p(this.#t.dayOfWeek.values,l);return!!(u&&h&&(y||b)||y&&!h||a&&!d&&b)}#g(l,a,u){const d=this.#t.hour.values,h=d,y=l.getHours(),b=o.#i(y,d),x=l.dstEnd===y;if(l.dstStart!==null&&l.dstStart===y-1&&o.#i(l.dstStart,d))return!0;if(x&&!u)return l.dstEnd=null,l.applyDateOperation(n.DateMathOp.Add,n.TimeUnit.Hour,h.length),!1;if(b)return!0;l.dstStart=null;const v=this.#t.hour.findNearestValue(y,u);if(v===null)return l.applyDateOperation(a,n.TimeUnit.Day,h.length),!1;if(this.#d(l)){const k=u?y-v:v-y;for(let C=0;C<k&&(l.applyDateOperation(a,n.TimeUnit.Hour,h.length),!(!u&&l.getHours()>=v||u&&l.getHours()<=v));C++);}else l.setHours(v);return l.setMinutes(this.#a(this.#t.minute.values,u)),l.setSeconds(this.#a(this.#t.second.values,u)),!1}#y(l){if(!this.#s&&!this.#r)return;const a=l.getTime();if(this.#s&&a<this.#s.getTime())throw new Error(e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE);if(this.#r&&a>this.#r.getTime())throw new Error(e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE)}#u(l=!1){const a=l?n.DateMathOp.Subtract:n.DateMathOp.Add,u=new n.CronDate(this.#o),d=u.getTime();let h=0;for(;++h<r;){if(this.#y(u),!this.#f(u)){u.applyDateOperation(a,n.TimeUnit.Day,this.#t.hour.values.length);continue}if(!(this.#t.dayOfWeek.nthDay<=0||Math.ceil(u.getDate()/7)===this.#t.dayOfWeek.nthDay)){u.applyDateOperation(a,n.TimeUnit.Day,this.#t.hour.values.length);continue}if(!o.#i(u.getMonth()+1,this.#t.month.values)){u.applyDateOperation(a,n.TimeUnit.Month,this.#t.hour.values.length);continue}if(this.#g(u,a,l)){if(!o.#i(u.getMinutes(),this.#t.minute.values)){this.#m(u,a,l);continue}if(!o.#i(u.getSeconds(),this.#t.second.values)){this.#h(u,a,l);continue}if(d===u.getTime()){(a==="Add"||u.getMilliseconds()===0)&&u.applyDateOperation(a,n.TimeUnit.Second,this.#t.hour.values.length);continue}break}}if(h>r)throw new Error(e.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE);return u.getMilliseconds()!==0&&u.setMilliseconds(0),this.#o=u,u}[Symbol.iterator](){return{next:()=>{try{return{value:this.#u(),done:!1}}catch{return{value:void 0,done:!0}}}}}}e.CronExpression=o,e.default=o})(Is)),Is}var Br={},ra;function bf(){if(ra)return Br;ra=1,Object.defineProperty(Br,"__esModule",{value:!0}),Br.seededRandom=r;function e(o){let i=2166136261;for(let l=0;l<o.length;l++)i^=o.charCodeAt(l),i=Math.imul(i,16777619);return()=>i>>>0}function n(o){return()=>{let i=o+=1831565813;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}function r(o){const i=o?e(o)():Math.floor(Math.random()*1e10);return n(i)}return Br}var sa;function Qs(){if(sa)return jt;sa=1,Object.defineProperty(jt,"__esModule",{value:!0}),jt.CronExpressionParser=jt.DayOfWeek=jt.Months=jt.CronUnit=jt.PredefinedExpressions=void 0;const e=al(),n=ll(),r=bf(),o=co();var i;(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"})(i||(jt.PredefinedExpressions=i={}));var l;(function(h){h.Second="Second",h.Minute="Minute",h.Hour="Hour",h.DayOfMonth="DayOfMonth",h.Month="Month",h.DayOfWeek="DayOfWeek"})(l||(jt.CronUnit=l={}));var a;(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"})(a||(jt.Months=a={}));var u;(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"})(u||(jt.DayOfWeek=u={}));let d=class Tt{static parse(y,b={}){const{strict:x=!1,hashSeed:v}=b,k=(0,r.seededRandom)(v);y=i[y]||y;const C=Tt.#e(y,x);if(!(C.dayOfMonth==="*"||C.dayOfWeek==="*"||!x))throw new Error("Cannot use both dayOfMonth and dayOfWeek together in strict mode!");const S=Tt.#n(l.Second,C.second,o.CronSecond.constraints,k),T=Tt.#n(l.Minute,C.minute,o.CronMinute.constraints,k),O=Tt.#n(l.Hour,C.hour,o.CronHour.constraints,k),M=Tt.#n(l.Month,C.month,o.CronMonth.constraints,k),E=Tt.#n(l.DayOfMonth,C.dayOfMonth,o.CronDayOfMonth.constraints,k),{dayOfWeek:R,nthDayOfWeek:P}=Tt.#d(C.dayOfWeek),F=Tt.#n(l.DayOfWeek,R,o.CronDayOfWeek.constraints,k),B=new e.CronFieldCollection({second:new o.CronSecond(S,{rawValue:C.second}),minute:new o.CronMinute(T,{rawValue:C.minute}),hour:new o.CronHour(O,{rawValue:C.hour}),dayOfMonth:new o.CronDayOfMonth(E,{rawValue:C.dayOfMonth}),month:new o.CronMonth(M,{rawValue:C.month}),dayOfWeek:new o.CronDayOfWeek(F,{rawValue:C.dayOfWeek,nthDayOfWeek:P})});return new n.CronExpression(B,{...b,expression:y})}static#e(y,b){if(b&&!y.length)throw new Error("Invalid cron expression");y=y||"0 * * * * *";const x=y.trim().split(/\s+/);if(b&&x.length<6)throw new Error("Invalid cron expression, expected 6 fields");if(x.length>6)throw new Error("Invalid cron expression, too many fields");const v=["*","*","*","*","*","0"];x.length<v.length&&x.unshift(...v.slice(x.length));const[k,C,S,T,O,M]=x;return{second:k,minute:C,hour:S,dayOfMonth:T,month:O,dayOfWeek:M}}static#n(y,b,x,v){if((y===l.Month||y===l.DayOfWeek)&&(b=b.replace(/[a-z]{3}/gi,k=>{k=k.toLowerCase();const C=a[k]||u[k];if(C===void 0)throw new Error(`Validation error, cannot resolve alias "${k}"`);return C.toString()})),!x.validChars.test(b))throw new Error(`Invalid characters, got value: ${b}`);return b=this.#o(b,x),b=this.#s(b,x,v),this.#r(y,b,x)}static#o(y,b){return y.replace(/[*?]/g,b.min+"-"+b.max)}static#s(y,b,x){const v=x();return y.replace(/H(?:\((\d+)-(\d+)\))?(?:\/(\d+))?/g,(k,C,S,T)=>{if(C&&S&&T){const O=parseInt(C,10),M=parseInt(S,10),E=parseInt(T,10);if(O>M)throw new Error(`Invalid range: ${O}-${M}, min > max`);if(E<=0)throw new Error(`Invalid step: ${E}, must be positive`);const R=Math.max(O,b.min),P=Math.floor(v*E),F=[];for(let B=Math.floor(R/E)*E+P;B<=M;B+=E)B>=R&&F.push(B);return F.join(",")}else if(C&&S){const O=parseInt(C,10),M=parseInt(S,10);if(O>M)throw new Error(`Invalid range: ${O}-${M}, min > max`);return String(Math.floor(v*(M-O+1))+O)}else if(T){const O=parseInt(T,10);if(O<=0)throw new Error(`Invalid step: ${O}, must be positive`);const M=Math.floor(v*O),E=[];for(let R=Math.floor(b.min/O)*O+M;R<=b.max;R+=O)R>=b.min&&E.push(R);return E.join(",")}else return String(Math.floor(v*(b.max-b.min+1)+b.min))})}static#r(y,b,x){const v=[];function k(S,T){if(Array.isArray(S))v.push(...S);else if(Tt.#h(T,S))v.push(S);else{const O=parseInt(S.toString(),10);if(!(O>=T.min&&O<=T.max))throw new Error(`Constraint error, got value ${S} expected range ${T.min}-${T.max}`);v.push(y===l.DayOfWeek?O%7:S)}}return b.split(",").forEach(S=>{if(!(S.length>0))throw new Error("Invalid list value format");k(Tt.#t(y,S,x),x)}),v}static#t(y,b,x){const v=b.split("/");if(v.length>2)throw new Error(`Invalid repeat: ${b}`);return v.length===2?(v[0].includes("-")||(v[0]=`${v[0]}-${x.max}`),Tt.#a(y,v[0],parseInt(v[1],10),x)):Tt.#a(y,b,1,x)}static#c(y,b,x){if(!(!isNaN(y)&&!isNaN(b)&&y>=x.min&&b<=x.max))throw new Error(`Constraint error, got range ${y}-${b} expected range ${x.min}-${x.max}`);if(y>b)throw new Error(`Invalid range: ${y}-${b}, min(${y}) > max(${b})`)}static#l(y){if(!(!isNaN(y)&&y>0))throw new Error(`Constraint error, cannot repeat at every ${y} time.`)}static#i(y,b,x,v){const k=[];y===l.DayOfWeek&&x%7===0&&k.push(0);for(let C=b;C<=x;C+=v)k.indexOf(C)===-1&&k.push(C);return k}static#a(y,b,x,v){const k=b.split("-");if(k.length<=1)return isNaN(+b)?b:+b;const[C,S]=k.map(T=>parseInt(T,10));return this.#c(C,S,v),this.#l(x),this.#i(y,C,S,x)}static#d(y){const b=y.split("#");if(b.length<=1)return{dayOfWeek:b[0]};const x=+b[b.length-1],v=y.match(/([,-/])/);if(v!==null)throw new Error(`Constraint error, invalid dayOfWeek \`#\` and \`${v?.[0]}\` special characters are incompatible`);if(!(b.length<=2&&!isNaN(x)&&x>=1&&x<=5))throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)");return{dayOfWeek:b[0],nthDayOfWeek:x}}static#h(y,b){return y.chars.some(x=>b.toString().includes(x))}};return jt.CronExpressionParser=d,jt}var _t={};const wf={},Sf=Object.freeze(Object.defineProperty({__proto__:null,default:wf},Symbol.toStringTag,{value:"Module"})),oa=c.getAugmentedNamespace(Sf);var ia;function kf(){if(ia)return _t;ia=1;var e=_t&&_t.__createBinding||(Object.create?(function(l,a,u,d){d===void 0&&(d=u);var h=Object.getOwnPropertyDescriptor(a,u);(!h||("get"in h?!a.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return a[u]}}),Object.defineProperty(l,d,h)}):(function(l,a,u,d){d===void 0&&(d=u),l[d]=a[u]})),n=_t&&_t.__setModuleDefault||(Object.create?(function(l,a){Object.defineProperty(l,"default",{enumerable:!0,value:a})}):function(l,a){l.default=a}),r=_t&&_t.__importStar||(function(){var l=function(a){return l=Object.getOwnPropertyNames||function(u){var d=[];for(var h in u)Object.prototype.hasOwnProperty.call(u,h)&&(d[d.length]=h);return d},l(a)};return function(a){if(a&&a.__esModule)return a;var u={};if(a!=null)for(var d=l(a),h=0;h<d.length;h++)d[h]!=="default"&&e(u,a,d[h]);return n(u,a),u}})();Object.defineProperty(_t,"__esModule",{value:!0}),_t.CronFileParser=void 0;const o=Qs();let i=class Yr{static async parseFile(a){const{readFile:u}=await Promise.resolve().then(()=>r(oa)),d=await u(a,"utf8");return Yr.#e(d)}static parseFileSync(a){const{readFileSync:u}=oa,d=u(a,"utf8");return Yr.#e(d)}static#e(a){const u=a.split(`
|
|
7
|
-
`),d={variables:{},expressions:[],errors:{}};for(const h of u){const y=h.trim();if(y.length===0||y.startsWith("#"))continue;const b=y.match(/^(.*)=(.*)$/);if(b){const[,x,v]=b;d.variables[x]=v.replace(/["']/g,"");continue}try{const x=Yr.#n(y);d.expressions.push(x.interval)}catch(x){d.errors[y]=x}}return d}static#n(a){const u=a.split(" ");return{interval:o.CronExpressionParser.parse(u.slice(0,5).join(" ")),command:u.slice(5,u.length)}}};return _t.CronFileParser=i,_t}var aa;function Cf(){return aa||(aa=1,(function(e){var n=an&&an.__createBinding||(Object.create?(function(h,y,b,x){x===void 0&&(x=b);var v=Object.getOwnPropertyDescriptor(y,b);(!v||("get"in v?!y.__esModule:v.writable||v.configurable))&&(v={enumerable:!0,get:function(){return y[b]}}),Object.defineProperty(h,x,v)}):(function(h,y,b,x){x===void 0&&(x=b),h[x]=y[b]})),r=an&&an.__exportStar||function(h,y){for(var b in h)b!=="default"&&!Object.prototype.hasOwnProperty.call(y,b)&&n(y,h,b)};Object.defineProperty(e,"__esModule",{value:!0}),e.CronFileParser=e.CronExpressionParser=e.CronExpression=e.CronFieldCollection=e.CronDate=void 0;const o=Qs();var i=lo();Object.defineProperty(e,"CronDate",{enumerable:!0,get:function(){return i.CronDate}});var l=al();Object.defineProperty(e,"CronFieldCollection",{enumerable:!0,get:function(){return l.CronFieldCollection}});var a=ll();Object.defineProperty(e,"CronExpression",{enumerable:!0,get:function(){return a.CronExpression}});var u=Qs();Object.defineProperty(e,"CronExpressionParser",{enumerable:!0,get:function(){return u.CronExpressionParser}});var d=kf();Object.defineProperty(e,"CronFileParser",{enumerable:!0,get:function(){return d.CronFileParser}}),r(co(),e),e.default=o.CronExpressionParser})(an)),an}var jf=Cf(),Ds={exports:{}},la;function Tf(){return la||(la=1,(function(e,n){(function(o,i){e.exports=i()})(globalThis,()=>(()=>{var r={949:((a,u,d)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.CronParser=void 0;var h=d(515),y=(function(){function b(x,v,k){v===void 0&&(v=!0),k===void 0&&(k=!1),this.expression=x,this.dayOfWeekStartIndexZero=v,this.monthStartIndexZero=k}return b.prototype.parse=function(){var x,v,k=(x=this.expression)!==null&&x!==void 0?x:"";if(k==="@reboot")return v=["@reboot","","","","","",""],v;if(k.startsWith("@")){var C=this.parseSpecial(this.expression);v=this.extractParts(C)}else v=this.extractParts(this.expression);return this.normalize(v),this.validate(v),v},b.prototype.parseSpecial=function(x){var v={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *","@reboot":"@reboot"},k=v[x];if(!k)throw new Error("Unknown special expression.");return k},b.prototype.extractParts=function(x){if(!this.expression)throw new Error("cron expression is empty");for(var v=x.trim().split(/[ ]+/),k=0;k<v.length;k++)if(v[k].includes(",")){var C=v[k].split(",").map(function(T){return T.trim()}).filter(function(T){return T!==""}).map(function(T){return isNaN(Number(T))?T:Number(T)}).filter(function(T){return T!==null&&T!==""});C.length===0&&C.push("*"),C.sort(function(T,O){return T!==null&&O!==null?T-O:0}),v[k]=C.map(function(T){return T!==null?T.toString():""}).join(",")}if(v.length<5)throw new Error("Expression has only ".concat(v.length," part").concat(v.length==1?"":"s",". At least 5 parts are required."));if(v.length==5)v.unshift(""),v.push("");else if(v.length==6){var S=/\d{4}$/.test(v[5])||v[4]=="?"||v[2]=="?";S?v.unshift(""):v.push("")}else if(v.length>7)throw new Error("Expression has ".concat(v.length," parts; too many!"));return v},b.prototype.normalize=function(x){var v=this;if(x[3]=x[3].replace("?","*"),x[5]=x[5].replace("?","*"),x[2]=x[2].replace("?","*"),x[0].indexOf("0/")==0&&(x[0]=x[0].replace("0/","*/")),x[1].indexOf("0/")==0&&(x[1]=x[1].replace("0/","*/")),x[2].indexOf("0/")==0&&(x[2]=x[2].replace("0/","*/")),x[3].indexOf("1/")==0&&(x[3]=x[3].replace("1/","*/")),x[4].indexOf("1/")==0&&(x[4]=x[4].replace("1/","*/")),x[6].indexOf("1/")==0&&(x[6]=x[6].replace("1/","*/")),x[5]=x[5].replace(/(^\d)|([^#/\s]\d)/g,function(R){var P=R.replace(/\D/,""),F=P;return v.dayOfWeekStartIndexZero?P=="7"&&(F="0"):F=(parseInt(P)-1).toString(),R.replace(P,F)}),x[5]=="L"&&(x[5]="6"),x[3]=="?"&&(x[3]="*"),x[3].indexOf("W")>-1&&(x[3].indexOf(",")>-1||x[3].indexOf("-")>-1))throw new Error("The 'W' character can be specified only when the day-of-month is a single day, not a range or list of days.");var k={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};for(var C in k)x[5]=x[5].replace(new RegExp(C,"gi"),k[C].toString());x[4]=x[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function(R){var P=R.replace(/\D/,""),F=P;return v.monthStartIndexZero&&(F=(parseInt(P)+1).toString()),R.replace(P,F)});var S={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12};for(var T in S)x[4]=x[4].replace(new RegExp(T,"gi"),S[T].toString());x[0]=="0"&&(x[0]=""),!/\*|\-|\,|\//.test(x[2])&&(/\*|\//.test(x[1])||/\*|\//.test(x[0]))&&(x[2]+="-".concat(x[2]));for(var O=0;O<x.length;O++)if(x[O].indexOf(",")!=-1&&(x[O]=x[O].split(",").filter(function(R){return R!==""}).join(",")||"*"),x[O]=="*/1"&&(x[O]="*"),x[O].indexOf("/")>-1&&!/^\*|\-|\,/.test(x[O])){var M=null;switch(O){case 4:M="12";break;case 5:M="6";break;case 6:M="9999";break;default:M=null;break}if(M!==null){var E=x[O].split("/");x[O]="".concat(E[0],"-").concat(M,"/").concat(E[1])}}},b.prototype.validate=function(x){var v="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(x[0],v),this.validateOnlyExpectedCharactersFound(x[1],v),this.validateOnlyExpectedCharactersFound(x[2],v),this.validateOnlyExpectedCharactersFound(x[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(x[4],v),this.validateOnlyExpectedCharactersFound(x[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(x[6],v),this.validateAnyRanges(x)},b.prototype.validateAnyRanges=function(x){h.default.secondRange(x[0]),h.default.minuteRange(x[1]),h.default.hourRange(x[2]),h.default.dayOfMonthRange(x[3]),h.default.monthRange(x[4],this.monthStartIndexZero),h.default.dayOfWeekRange(x[5],this.dayOfWeekStartIndexZero)},b.prototype.validateOnlyExpectedCharactersFound=function(x,v){var k=x.match(new RegExp("[^".concat(v,"]+"),"gi"));if(k&&k.length)throw new Error("Expression contains invalid values: '".concat(k.toString(),"'"))},b})();u.CronParser=y}),333:((a,u,d)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.ExpressionDescriptor=void 0;var h=d(823),y=d(949),b=(function(){function x(v,k){if(this.expression=v,this.options=k,this.expressionParts=new Array(5),!this.options.locale&&x.defaultLocale&&(this.options.locale=x.defaultLocale),!x.locales[this.options.locale]){var C=Object.keys(x.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(C,"'.")),this.options.locale=C}this.i18n=x.locales[this.options.locale],k.use24HourTimeFormat===void 0&&(k.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault())}return x.toString=function(v,k){var C=k===void 0?{}:k,S=C.throwExceptionOnParseError,T=S===void 0?!0:S,O=C.verbose,M=O===void 0?!1:O,E=C.dayOfWeekStartIndexZero,R=E===void 0?!0:E,P=C.monthStartIndexZero,F=P===void 0?!1:P,B=C.use24HourTimeFormat,D=C.locale,_=D===void 0?null:D,V={throwExceptionOnParseError:T,verbose:M,dayOfWeekStartIndexZero:R,monthStartIndexZero:F,use24HourTimeFormat:B,locale:_};V.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var $=new x(v,V);return $.getFullDescription()},x.initialize=function(v,k){k===void 0&&(k="en"),x.specialCharacters=["/","-",",","*"],x.defaultLocale=k,v.load(x.locales)},x.prototype.getFullDescription=function(){var v,k,C="";try{var S=new y.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=S.parse(),this.expressionParts[0]==="@reboot")return((k=(v=this.i18n).atReboot)===null||k===void 0?void 0:k.call(v))||"Run once, at startup";var T=this.getTimeOfDayDescription(),O=this.getDayOfMonthDescription(),M=this.getMonthDescription(),E=this.getDayOfWeekDescription(),R=this.getYearDescription();C+=T+O+E+M+R,C=this.transformVerbosity(C,!!this.options.verbose),C=C.charAt(0).toLocaleUpperCase()+C.substr(1)}catch(P){if(!this.options.throwExceptionOnParseError)C=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw"".concat(P)}return C},x.prototype.getTimeOfDayDescription=function(){var v=this.expressionParts[0],k=this.expressionParts[1],C=this.expressionParts[2],S="";if(!h.StringUtilities.containsAny(k,x.specialCharacters)&&!h.StringUtilities.containsAny(C,x.specialCharacters)&&!h.StringUtilities.containsAny(v,x.specialCharacters))S+=this.i18n.atSpace()+this.formatTime(C,k,v);else if(!v&&k.indexOf("-")>-1&&!(k.indexOf(",")>-1)&&!(k.indexOf("/")>-1)&&!h.StringUtilities.containsAny(C,x.specialCharacters)){var T=k.split("-");S+=h.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(C,T[0],""),this.formatTime(C,T[1],""))}else if(!v&&C.indexOf(",")>-1&&C.indexOf("-")==-1&&C.indexOf("/")==-1&&!h.StringUtilities.containsAny(k,x.specialCharacters)){var O=C.split(",");S+=this.i18n.at();for(var M=0;M<O.length;M++)S+=" ",S+=this.formatTime(O[M],k,""),M<O.length-2&&(S+=","),M==O.length-2&&(S+=this.i18n.spaceAnd())}else{var E=this.getSecondsDescription(),R=this.getMinutesDescription(),P=this.getHoursDescription();if(S+=E,S&&R&&(S+=", "),S+=R,R===P)return S;S&&P&&(S+=", "),S+=P}return S},x.prototype.getSecondsDescription=function(){var v=this,k=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(C){return C},function(C){return h.StringUtilities.format(v.i18n.everyX0Seconds(C),C)},function(C){return v.i18n.secondsX0ThroughX1PastTheMinute()},function(C){return C=="0"?"":parseInt(C)<20?v.i18n.atX0SecondsPastTheMinute(C):v.i18n.atX0SecondsPastTheMinuteGt20()||v.i18n.atX0SecondsPastTheMinute(C)});return k},x.prototype.getMinutesDescription=function(){var v=this,k=this.expressionParts[0],C=this.expressionParts[2],S=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(T){return T},function(T){return h.StringUtilities.format(v.i18n.everyX0Minutes(T),T)},function(T){return v.i18n.minutesX0ThroughX1PastTheHour()},function(T){try{return T=="0"&&C.indexOf("/")==-1&&k==""?v.i18n.everyHour():parseInt(T)<20?v.i18n.atX0MinutesPastTheHour(T):v.i18n.atX0MinutesPastTheHourGt20()||v.i18n.atX0MinutesPastTheHour(T)}catch{return v.i18n.atX0MinutesPastTheHour(T)}});return S},x.prototype.getHoursDescription=function(){var v=this,k=this.expressionParts[2],C=0,S=[];k.split("/")[0].split(",").forEach(function(M){var E=M.split("-");E.length===2&&S.push({value:E[1],index:C+1}),C+=E.length});var T=0,O=this.getSegmentDescription(k,this.i18n.everyHour(),function(M){var E=S.find(function(P){return P.value===M&&P.index===T}),R=E&&v.expressionParts[1]!=="0";return T++,R?v.formatTime(M,"59",""):v.formatTime(M,"0","")},function(M){return h.StringUtilities.format(v.i18n.everyX0Hours(M),M)},function(M){return v.i18n.betweenX0AndX1()},function(M){return v.i18n.atX0()});return O},x.prototype.getDayOfWeekDescription=function(){var v=this,k=this.i18n.daysOfTheWeek(),C=null;return this.expressionParts[5]=="*"?C="":C=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(S,T){var O=S;S.indexOf("#")>-1?O=S.substring(0,S.indexOf("#")):S.indexOf("L")>-1&&(O=O.replace("L",""));var M=parseInt(O),E=v.i18n.daysOfTheWeekInCase?v.i18n.daysOfTheWeekInCase(T)[M]:k[M];if(S.indexOf("#")>-1){var R=null,P=S.substring(S.indexOf("#")+1),F=S.substring(0,S.indexOf("#"));switch(P){case"1":R=v.i18n.first(F);break;case"2":R=v.i18n.second(F);break;case"3":R=v.i18n.third(F);break;case"4":R=v.i18n.fourth(F);break;case"5":R=v.i18n.fifth(F);break}E=R+" "+E}return E},function(S){return parseInt(S)==1?"":h.StringUtilities.format(v.i18n.commaEveryX0DaysOfTheWeek(S),S)},function(S){var T=S.substring(0,S.indexOf("-")),O=v.expressionParts[3]!="*";return O?v.i18n.commaAndX0ThroughX1(T):v.i18n.commaX0ThroughX1(T)},function(S){var T=null;if(S.indexOf("#")>-1){var O=S.substring(S.indexOf("#")+1),M=S.substring(0,S.indexOf("#"));T=v.i18n.commaOnThe(O,M).trim()+v.i18n.spaceX0OfTheMonth()}else if(S.indexOf("L")>-1)T=v.i18n.commaOnTheLastX0OfTheMonth(S.replace("L",""));else{var E=v.expressionParts[3]!="*";T=E?v.i18n.commaAndOnX0():v.i18n.commaOnlyOnX0(S)}return T}),C},x.prototype.getMonthDescription=function(){var v=this,k=this.i18n.monthsOfTheYear(),C=this.getSegmentDescription(this.expressionParts[4],"",function(S,T){return T&&v.i18n.monthsOfTheYearInCase?v.i18n.monthsOfTheYearInCase(T)[parseInt(S)-1]:k[parseInt(S)-1]},function(S){return parseInt(S)==1?"":h.StringUtilities.format(v.i18n.commaEveryX0Months(S),S)},function(S){return v.i18n.commaMonthX0ThroughMonthX1()||v.i18n.commaX0ThroughX1()},function(S){return v.i18n.commaOnlyInMonthX0?v.i18n.commaOnlyInMonthX0():v.i18n.commaOnlyInX0()});return C},x.prototype.getDayOfMonthDescription=function(){var v=this,k=null,C=this.expressionParts[3];switch(C){case"L":k=this.i18n.commaOnTheLastDayOfTheMonth();break;case"WL":case"LW":k=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var S=C.match(/(\d{1,2}W)|(W\d{1,2})/);if(S){var T=parseInt(S[0].replace("W","")),O=T==1?this.i18n.firstWeekday():h.StringUtilities.format(this.i18n.weekdayNearestDayX0(),T.toString());k=h.StringUtilities.format(this.i18n.commaOnTheX0OfTheMonth(),O);break}else{var M=C.match(/L-(\d{1,2})/);if(M){var E=M[1];k=h.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(E),E);break}else{if(C=="*"&&this.expressionParts[5]!="*")return"";k=this.getSegmentDescription(C,this.i18n.commaEveryDay(),function(R){return R=="L"?v.i18n.lastDay():v.i18n.dayX0?h.StringUtilities.format(v.i18n.dayX0(),R):R},function(R){return R=="1"?v.i18n.commaEveryDay():v.i18n.commaEveryX0Days(R)},function(R){return v.i18n.commaBetweenDayX0AndX1OfTheMonth(R)},function(R){return v.i18n.commaOnDayX0OfTheMonth(R)})}break}}return k},x.prototype.getYearDescription=function(){var v=this,k=this.getSegmentDescription(this.expressionParts[6],"",function(C){return/^\d+$/.test(C)?new Date(parseInt(C),1).getFullYear().toString():C},function(C){return h.StringUtilities.format(v.i18n.commaEveryX0Years(C),C)},function(C){return v.i18n.commaYearX0ThroughYearX1()||v.i18n.commaX0ThroughX1()},function(C){return v.i18n.commaOnlyInYearX0?v.i18n.commaOnlyInYearX0():v.i18n.commaOnlyInX0()});return k},x.prototype.getSegmentDescription=function(v,k,C,S,T,O){var M=null,E=v.indexOf("/")>-1,R=v.indexOf("-")>-1,P=v.indexOf(",")>-1;if(!v)M="";else if(v==="*")M=k;else if(!E&&!R&&!P)M=h.StringUtilities.format(O(v),C(v));else if(P){for(var F=v.split(","),B="",D=0;D<F.length;D++)if(D>0&&F.length>2&&(B+=",",D<F.length-1&&(B+=" ")),D>0&&F.length>1&&(D==F.length-1||F.length==2)&&(B+="".concat(this.i18n.spaceAnd()," ")),F[D].indexOf("/")>-1||F[D].indexOf("-")>-1){var _=F[D].indexOf("-")>-1&&F[D].indexOf("/")==-1,V=this.getSegmentDescription(F[D],k,C,S,_?this.i18n.commaX0ThroughX1:T,O);_&&(V=V.replace(", ","")),B+=V}else E?B+=this.getSegmentDescription(F[D],k,C,S,T,O):B+=C(F[D]);E?M=B:M=h.StringUtilities.format(O(v),B)}else if(E){var F=v.split("/");if(M=h.StringUtilities.format(S(F[1]),F[1]),F[0].indexOf("-")>-1){var $=this.generateRangeSegmentDescription(F[0],T,C);$.indexOf(", ")!=0&&(M+=", "),M+=$}else if(F[0].indexOf("*")==-1){var W=h.StringUtilities.format(O(F[0]),C(F[0]));W=W.replace(", ",""),M+=h.StringUtilities.format(this.i18n.commaStartingX0(),W)}}else R&&(M=this.generateRangeSegmentDescription(v,T,C));return M},x.prototype.generateRangeSegmentDescription=function(v,k,C){var S="",T=v.split("-"),O=C(T[0],1),M=C(T[1],2),E=k(v);return S+=h.StringUtilities.format(E,O,M),S},x.prototype.formatTime=function(v,k,C){var S=0,T=0,O=parseInt(v)+S,M=parseInt(k)+T;M>=60?(M-=60,O+=1):M<0&&(M+=60,O-=1),O>=24?O=O-24:O<0&&(O=24+O);var E="",R=!1;this.options.use24HourTimeFormat||(R=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),E=R?"".concat(this.getPeriod(O)," "):" ".concat(this.getPeriod(O)),O>12&&(O-=12),O===0&&(O=12));var P="";return C&&(P=":".concat(("00"+C).substring(C.length))),"".concat(R?E:"").concat(("00"+O.toString()).substring(O.toString().length),":").concat(("00"+M.toString()).substring(M.toString().length)).concat(P).concat(R?"":E)},x.prototype.transformVerbosity=function(v,k){if(!k&&(v=v.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),v=v.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),v=v.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),v=v.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var C=0,S=Object.entries(this.i18n.conciseVerbosityReplacements());C<S.length;C++){var T=S[C],O=T[0],M=T[1];v=v.replace(new RegExp(O,"g"),M)}return v},x.prototype.getPeriod=function(v){return v>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},x.locales={},x})();u.ExpressionDescriptor=b}),747:((a,u,d)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.enLocaleLoader=void 0;var h=d(486),y=(function(){function b(){}return b.prototype.load=function(x){x.en=new h.en},b})();u.enLocaleLoader=y}),486:((a,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.en=void 0;var d=(function(){function h(){}return h.prototype.atX0SecondsPastTheMinuteGt20=function(){return null},h.prototype.atX0MinutesPastTheHourGt20=function(){return null},h.prototype.commaMonthX0ThroughMonthX1=function(){return null},h.prototype.commaYearX0ThroughYearX1=function(){return null},h.prototype.use24HourTimeFormatByDefault=function(){return!1},h.prototype.anErrorOccuredWhenGeneratingTheExpressionD=function(){return"An error occurred when generating the expression description. Check the cron expression syntax."},h.prototype.everyMinute=function(){return"every minute"},h.prototype.everyHour=function(){return"every hour"},h.prototype.atSpace=function(){return"At "},h.prototype.everyMinuteBetweenX0AndX1=function(){return"Every minute between %s and %s"},h.prototype.at=function(){return"At"},h.prototype.spaceAnd=function(){return" and"},h.prototype.everySecond=function(){return"every second"},h.prototype.everyX0Seconds=function(){return"every %s seconds"},h.prototype.secondsX0ThroughX1PastTheMinute=function(){return"seconds %s through %s past the minute"},h.prototype.atX0SecondsPastTheMinute=function(){return"at %s seconds past the minute"},h.prototype.everyX0Minutes=function(){return"every %s minutes"},h.prototype.minutesX0ThroughX1PastTheHour=function(){return"minutes %s through %s past the hour"},h.prototype.atX0MinutesPastTheHour=function(){return"at %s minutes past the hour"},h.prototype.everyX0Hours=function(){return"every %s hours"},h.prototype.betweenX0AndX1=function(){return"between %s and %s"},h.prototype.atX0=function(){return"at %s"},h.prototype.commaEveryDay=function(){return", every day"},h.prototype.commaEveryX0DaysOfTheWeek=function(){return", every %s days of the week"},h.prototype.commaX0ThroughX1=function(){return", %s through %s"},h.prototype.commaAndX0ThroughX1=function(){return", %s through %s"},h.prototype.first=function(){return"first"},h.prototype.second=function(){return"second"},h.prototype.third=function(){return"third"},h.prototype.fourth=function(){return"fourth"},h.prototype.fifth=function(){return"fifth"},h.prototype.commaOnThe=function(){return", on the "},h.prototype.spaceX0OfTheMonth=function(){return" %s of the month"},h.prototype.lastDay=function(){return"the last day"},h.prototype.commaOnTheLastX0OfTheMonth=function(){return", on the last %s of the month"},h.prototype.commaOnlyOnX0=function(){return", only on %s"},h.prototype.commaAndOnX0=function(){return", and on %s"},h.prototype.commaEveryX0Months=function(){return", every %s months"},h.prototype.commaOnlyInX0=function(){return", only in %s"},h.prototype.commaOnTheLastDayOfTheMonth=function(){return", on the last day of the month"},h.prototype.commaOnTheLastWeekdayOfTheMonth=function(){return", on the last weekday of the month"},h.prototype.commaDaysBeforeTheLastDayOfTheMonth=function(){return", %s days before the last day of the month"},h.prototype.firstWeekday=function(){return"first weekday"},h.prototype.weekdayNearestDayX0=function(){return"weekday nearest day %s"},h.prototype.commaOnTheX0OfTheMonth=function(){return", on the %s of the month"},h.prototype.commaEveryX0Days=function(){return", every %s days"},h.prototype.commaBetweenDayX0AndX1OfTheMonth=function(){return", between day %s and %s of the month"},h.prototype.commaOnDayX0OfTheMonth=function(){return", on day %s of the month"},h.prototype.commaEveryHour=function(){return", every hour"},h.prototype.commaEveryX0Years=function(){return", every %s years"},h.prototype.commaStartingX0=function(){return", starting %s"},h.prototype.daysOfTheWeek=function(){return["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},h.prototype.monthsOfTheYear=function(){return["January","February","March","April","May","June","July","August","September","October","November","December"]},h.prototype.atReboot=function(){return"Run once, at startup"},h})();u.en=d}),515:((a,u)=>{Object.defineProperty(u,"__esModule",{value:!0});function d(y,b){if(!y)throw new Error(b)}var h=(function(){function y(){}return y.secondRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);d(k>=0&&k<=59,"seconds part must be >= 0 and <= 59")}},y.minuteRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);d(k>=0&&k<=59,"minutes part must be >= 0 and <= 59")}},y.hourRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);d(k>=0&&k<=23,"hours part must be >= 0 and <= 23")}},y.dayOfMonthRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);d(k>=1&&k<=31,"DOM part must be >= 1 and <= 31")}},y.monthRange=function(b,x){for(var v=b.split(","),k=0;k<v.length;k++)if(!isNaN(parseInt(v[k],10))){var C=parseInt(v[k],10);d(C>=1&&C<=12,x?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12")}},y.dayOfWeekRange=function(b,x){for(var v=b.split(","),k=0;k<v.length;k++)if(!isNaN(parseInt(v[k],10))){var C=parseInt(v[k],10);d(C>=0&&C<=6,x?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7")}},y})();u.default=h}),823:((a,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.StringUtilities=void 0;var d=(function(){function h(){}return h.format=function(y){for(var b=[],x=1;x<arguments.length;x++)b[x-1]=arguments[x];return y.replace(/%s/g,function(v){return b.shift()})},h.containsAny=function(y,b){return b.some(function(x){return y.indexOf(x)>-1})},h})();u.StringUtilities=d})},o={};function i(a){var u=o[a];if(u!==void 0)return u.exports;var d=o[a]={exports:{}};return r[a](d,d.exports,i),d.exports}var l={};return(()=>{var a=l;Object.defineProperty(a,"__esModule",{value:!0}),a.toString=void 0;var u=i(333),d=i(747);u.ExpressionDescriptor.initialize(new d.enLocaleLoader),a.default=u.ExpressionDescriptor;var h=u.ExpressionDescriptor.toString;a.toString=h})(),l})())})(Ds)),Ds.exports}var Of=Tf();const Mf=c.getDefaultExportFromCjs(Of),Ef=new Set(["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC","SUN","MON","TUE","WED","THU","FRI","SAT"]);function If(e){for(const n of e.trim().split(/\s+/)){if(/[#?]/.test(n))return!1;for(const r of n.split(/[,\-/]/))if(!(r===""||r==="*")&&/[A-Za-z]/.test(r)&&!Ef.has(r.toUpperCase()))return!1}return!0}function uo(e){const n=(e??"").trim();if(n.split(/\s+/).filter(Boolean).length!==5)return{valid:!1,description:"",nextRun:null,error:"Expected a 5-field UNIX cron: minute hour day-of-month month day-of-week."};if(!If(n))return{valid:!1,description:"",nextRun:null,error:"Unsupported cron syntax: L, W, #, and ? extensions are not allowed (plain 5-field UNIX cron only)."};try{const r=Mf.toString(n,{use24HourTimeFormat:!0,verbose:!1}),o=jf.CronExpressionParser.parse(n,{tz:"UTC"}).next().toDate();return{valid:!0,description:r,nextRun:o}}catch(r){return{valid:!1,description:"",nextRun:null,error:r instanceof Error?r.message:"Invalid cron expression."}}}function cl(e){return e?e.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",timeZone:"UTC",hour12:!1})+" UTC":"—"}function Df({onSubmit:e,isSubmitting:n,disabled:r,disabledReason:o}){const[i,l]=j.useState(!1),[a,u]=j.useState(!1),d=()=>l(!1),h=async()=>{try{await e({forceRefresh:a}),l(!1)}catch{}},y=t.jsx("span",{children:t.jsx(c.AddButton,{label:"Materialization",onClick:()=>l(!0),disabled:r})});return t.jsxs(t.Fragment,{children:[r&&o?t.jsx(p.Tooltip,{title:o,children:y}):y,t.jsx(c.AppDialog,{open:i,onClose:d,title:"New materialization",description:"Compile the package, build a table for every persist source, and load them so queries serve from the tables.",actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{onClick:d,children:"Cancel"}),t.jsx(p.Button,{variant:"contained",loading:n,onClick:h,children:"Materialize"})]}),children:t.jsx(p.FormGroup,{children:t.jsx(p.FormControlLabel,{control:t.jsx(p.Switch,{checked:a,onChange:b=>u(b.target.checked)}),label:"Force refresh (rebuild even if unchanged)"})})})]})}function Kr({children:e}){return t.jsx(p.Typography,{variant:"caption",component:"h6",sx:{display:"block",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600,color:"text.secondary",mb:1},children:e})}function es(e){return e===q.MaterializationStatus.Pending||e===q.MaterializationStatus.ManifestRowsReady}function $f(e){return e===q.MaterializationStatus.ManifestFileReady||e===q.MaterializationStatus.Failed||e===q.MaterializationStatus.Cancelled}function Ff(e){switch(e){case q.MaterializationStatus.ManifestFileReady:return"Done";case q.MaterializationStatus.Failed:return"Failed";case q.MaterializationStatus.Cancelled:return"Cancelled";case q.MaterializationStatus.Pending:case q.MaterializationStatus.ManifestRowsReady:return"Pending";default:return"Unknown"}}function Af(e){switch(e){case q.MaterializationStatus.ManifestRowsReady:return"info";case q.MaterializationStatus.ManifestFileReady:return"success";case q.MaterializationStatus.Failed:return"error";case q.MaterializationStatus.Cancelled:return"warning";case q.MaterializationStatus.Pending:default:return"default"}}function ul(e){return e.status===q.MaterializationStatus.ManifestFileReady&&is(e).autoLoad==="failed"}function dl(e){return ul(e)?"Built, not served":Ff(e.status)}function Zs(e){return ul(e)?"warning":Af(e.status)}function Rf(e){const n=Object.values(is(e).refusedSources??{}).map(o=>({name:o.name,message:o.message})),r=Object.values(e.manifest?.failures??{}).filter(o=>o.refused).map(o=>({name:o.sourceName??o.sourceEntityId,message:o.reason}));return[...n,...r].sort((o,i)=>o.name.localeCompare(i.name))}function hl(e,n){const r=[`${e.sourcesBuilt??0} built`,`${e.sourcesReused??0} reused`];return e.sourcesRefused&&r.push(`${e.sourcesRefused} refused`),r.join(n)}function is(e){return e.metadata??{}}function fl(e){return e.trigger==="scheduler"||e.trigger==="SCHEDULER"}function Lf(e){return fl(e)?"Scheduled":"Manual"}function ml(e,n){if(!e)return"-";const r=new Date(e).getTime(),o=n?new Date(n).getTime():Date.now(),i=Math.max(0,o-r);if(i<1e3)return`${i}ms`;const l=Math.round(i/1e3);if(l<60)return`${l}s`;const a=Math.floor(l/60),u=l%60;if(a<60)return`${a}m ${u}s`;const d=Math.floor(a/60),h=a%60;return`${d}h ${h}m`}function Xs(e){if(!e)return"—";const n=new Date(e);return Number.isNaN(n.getTime())?"—":n.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function _f(e){if(!e)return"-";const n=new Date(e).getTime(),r=Math.round((Date.now()-n)/1e3);if(r<60)return"just now";const o=Math.floor(r/60);if(o<60)return`${o}m ago`;const i=Math.floor(o/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function Nf({entries:e,builtAt:n}){const r=Object.entries(e??{});return t.jsxs(p.Box,{children:[t.jsxs(p.Stack,{direction:"row",alignItems:"baseline",justifyContent:"space-between",children:[t.jsx(Kr,{children:"Build manifest"}),n&&t.jsxs(p.Typography,{variant:"caption",color:"text.secondary",children:["Built ",Xs(n)]})]}),r.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:"No materialized tables yet."}):t.jsxs(p.Table,{size:"small",children:[t.jsx(p.TableHead,{children:t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:"Source"}),t.jsx(p.TableCell,{children:"Table name"}),t.jsx(p.TableCell,{children:"Connection"}),t.jsx(p.TableCell,{children:"Realization"}),t.jsx(p.TableCell,{align:"right",children:"Rows"})]})}),t.jsx(p.TableBody,{children:r.map(([o,i])=>t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:i.sourceName??o}),t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:i.physicalTableName??"-"}),t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:i.connectionName??"-"}),t.jsx(p.TableCell,{children:i.realization??"-"}),t.jsx(p.TableCell,{align:"right",children:i.rowCount??"-"})]},o))})]})]})}function pl({meta:e}){const n=fl(e);return t.jsx(p.Tooltip,{title:n?"Fired by the materialization schedule":"Triggered manually",children:t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:Lf(e)})})}function Pf({materialization:e,buildPlan:n,onClose:r}){const o=e?is(e):{},i=e?Rf(e):[],l=n.status==="ready"?Object.values(n.plan?.sources??{}):[];return t.jsx(p.Dialog,{open:e!==null,onClose:r,maxWidth:"md",fullWidth:!0,"aria-labelledby":"materialization-detail-title",children:e&&t.jsxs(t.Fragment,{children:[t.jsxs(p.DialogTitle,{sx:{pr:6,pb:1.5},id:"materialization-detail-title",children:[t.jsxs(p.Stack,{direction:"row",alignItems:"center",spacing:1,sx:{mb:.75},children:[t.jsx(p.Chip,{size:"small",label:dl(e),color:Zs(e),variant:es(e.status)?"filled":"outlined"}),t.jsx(pl,{meta:o})]}),t.jsx(p.Typography,{variant:"subtitle1",sx:{fontWeight:600},children:e.packageName??"Materialization"}),t.jsx(p.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:q.MONO_FONT_FAMILY,wordBreak:"break-all"},children:e.id}),t.jsx(p.IconButton,{"aria-label":"close",onClick:r,sx:{position:"absolute",right:8,top:8},children:t.jsx(c.CloseIcon,{fontSize:"small"})})]}),t.jsxs(p.DialogContent,{dividers:!0,children:[t.jsxs(p.Box,{sx:{bgcolor:"action.hover",borderRadius:2,p:2,mb:3,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:2},children:[t.jsx(cr,{label:"Started",value:Xs(e.startedAt??e.createdAt)}),t.jsx(cr,{label:"Completed",value:Xs(e.completedAt)}),t.jsx(cr,{label:"Duration",value:ml(e.startedAt,e.completedAt)}),t.jsx(cr,{label:"Sources",value:hl(o," · ")}),t.jsx(cr,{label:"Force refresh",value:o.forceRefresh?"Yes":"No"})]}),e.error&&t.jsxs(p.Box,{sx:{borderRadius:2,p:2,mb:3,border:"1px solid",borderColor:"error.main"},children:[t.jsx(Kr,{children:t.jsx(p.Box,{component:"span",sx:{color:"error.main"},children:"Error"})}),t.jsx(p.Typography,{variant:"body2",sx:{fontFamily:q.MONO_FONT_FAMILY,whiteSpace:"pre-wrap"},children:e.error})]}),i.length>0&&t.jsxs(p.Box,{sx:{borderRadius:2,p:2,mb:3,border:"1px solid",borderColor:"warning.main"},children:[t.jsx(Kr,{children:t.jsx(p.Box,{component:"span",sx:{color:"warning.main"},children:"Refused sources"})}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1},children:"Not built, because materializing them would be unsafe. They serve live until the model changes."}),i.map(a=>t.jsxs(p.Box,{sx:{mt:1},children:[t.jsx(p.Typography,{variant:"body2",sx:{fontFamily:q.MONO_FONT_FAMILY},children:a.name}),t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{whiteSpace:"pre-wrap"},children:a.message})]},a.name))]}),t.jsxs(p.Box,{sx:{mb:3},children:[t.jsx(Kr,{children:"Build plan"}),n.status==="loading"?t.jsx(c.Loading,{text:c.LOADING_COPY.loading,size:16,centered:!1}):n.status==="unavailable"?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:"The build plan is unavailable."}):l.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:"This package has no persist sources."}):t.jsxs(p.Table,{size:"small",children:[t.jsx(p.TableHead,{children:t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:"Source"}),t.jsx(p.TableCell,{children:"Connection"}),t.jsx(p.TableCell,{children:"Dialect"}),t.jsx(p.TableCell,{align:"right",children:"Columns"}),t.jsx(p.TableCell,{children:"Source Entity ID"})]})}),t.jsx(p.TableBody,{children:l.map(a=>t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:a.name}),t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:a.connectionName}),t.jsx(p.TableCell,{children:a.dialect??"-"}),t.jsx(p.TableCell,{align:"right",children:a.columns?.length??0}),t.jsx(p.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"0.75rem",wordBreak:"break-all",maxWidth:220},children:a.sourceEntityId})]},a.sourceID))})]})]}),t.jsx(Nf,{entries:e.manifest?.entries,builtAt:e.manifest?.builtAt})]})]})})}function cr({label:e,value:n}){return t.jsxs(p.Box,{children:[t.jsx(p.Typography,{variant:"caption",color:"text.secondary",display:"block",children:e}),t.jsx(p.Typography,{variant:"body2",children:n})]})}const zf=c.createSvgIcon(t.jsx("path",{d:"M6 6h12v12H6z"}));function Wf({materialization:e,onCloseDialog:n,isMutating:r,onDelete:o}){const[i,l]=j.useState(!1),a=()=>l(!0),u=()=>{l(!1),n()};return t.jsxs(j.Fragment,{children:[t.jsxs(et,{"aria-label":`Delete materialization ${e?.id??""}`.trim(),onClick:d=>{d.stopPropagation(),a()},sx:{color:"error.main"},children:[t.jsx(io,{sx:{color:"inherit"},children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(ao,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:i,onClose:u,title:"Delete materialization",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:u,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>o(),loading:r,children:"Delete run"})]}),children:t.jsx(c.Typography,{variant:"body2",children:"Delete this run's record? This cannot be undone. The tables it built stay in place: drop any you no longer need through their connection."})})]})}function qf({materializations:e,mutable:n,isMutating:r,onStop:o,onDelete:i,onViewDetails:l}){return e.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{py:1,fontStyle:"italic"},children:"No materializations yet."}):t.jsxs(p.Table,{size:"small",sx:{"& td, & th":{borderColor:"divider"},"& td:first-of-type, & th:first-of-type":{pl:0},"& td:last-of-type, & th:last-of-type":{pr:0},"& th":{color:"text.secondary",fontWeight:600}},children:[t.jsx(p.TableHead,{children:t.jsxs(p.TableRow,{children:[t.jsx(p.TableCell,{children:"Status"}),t.jsx(p.TableCell,{children:"Trigger"}),t.jsx(p.TableCell,{children:"Started"}),t.jsx(p.TableCell,{children:"Duration"}),t.jsx(p.TableCell,{children:"Sources"}),t.jsx(p.TableCell,{align:"right",children:"Actions"})]})}),t.jsx(p.TableBody,{children:e.map(a=>t.jsx(Bf,{materialization:a,mutable:n,isMutating:r,onStop:o,onDelete:i,onViewDetails:l},a.id))})]})}function Bf({materialization:e,mutable:n,isMutating:r,onStop:o,onDelete:i,onViewDetails:l}){const[a,u]=j.useState(null),d=!!a,h=()=>u(null),y=is(e),b=y.sourcesBuilt!==void 0||y.sourcesReused!==void 0?hl(y,", "):"-",x=es(e.status),v=$f(e.status),k=e.error??void 0,C=n&&(x||v);return t.jsxs(p.TableRow,{hover:!0,sx:{cursor:"pointer","&:focus-visible":{outline:"2px solid",outlineColor:"primary.main",outlineOffset:"-2px"}},onClick:()=>l(e),onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),l(e))},role:"button",tabIndex:0,"aria-label":`View materialization ${e.id??""} details`.trim(),children:[t.jsx(p.TableCell,{children:t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",gap:.5},children:[t.jsx(p.Typography,{variant:"body2",sx:{fontWeight:500,color:Zs(e)==="default"?"text.primary":`${Zs(e)}.main`},children:dl(e)}),k&&t.jsx(p.Tooltip,{title:k,children:t.jsx(c.InfoOutlinedIcon,{fontSize:"small",color:"error"})})]})}),t.jsx(p.TableCell,{children:t.jsx(pl,{meta:y})}),t.jsx(p.TableCell,{children:_f(e.startedAt??e.createdAt)}),t.jsx(p.TableCell,{children:ml(e.startedAt,e.completedAt)}),t.jsx(p.TableCell,{children:b}),t.jsx(p.TableCell,{align:"right",onClick:S=>S.stopPropagation(),children:C&&t.jsxs(t.Fragment,{children:[t.jsx(p.IconButton,{size:"small","aria-label":`Materialization actions for ${e.id??""}`.trim(),onClick:S=>u(S.currentTarget),children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(p.Menu,{anchorEl:a,open:d,onClose:h,anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n&&x&&t.jsxs(p.MenuItem,{"aria-label":`Stop materialization ${e.id??""}`.trim(),disabled:r,onClick:()=>{h(),o(e)},children:[t.jsx(p.ListItemIcon,{children:t.jsx(zf,{fontSize:"small"})}),t.jsx(p.ListItemText,{children:"Stop"})]}),n&&v&&t.jsx(Wf,{materialization:e,isMutating:r,onCloseDialog:h,onDelete:()=>i(e)})]})]})})]})}const Vf=c.createSvgIcon(t.jsx("path",{d:"m11.99 18.54-7.37-5.73L3 14.07l9 7 9-7-1.63-1.27zM12 16l7.36-5.73L21 9l-9-7-9 7 1.63 1.27zm0-11.47L17.74 9 12 13.47 6.26 9z"})),Hf={package:"Materialized artifacts are shared across versions",version:"Materialized artifacts are per published version"};function Uf({scope:e,disabled:n,disabledReason:r,isSubmitting:o,onChange:i}){const[l,a]=j.useState(null),u=async d=>{a(null),d!==e&&await i(d).catch(()=>{})};return t.jsxs(t.Fragment,{children:[t.jsx(c.SecondaryButton,{label:"Scope",icon:t.jsx(Vf,{}),onClick:d=>a(d.currentTarget),disabled:n||o,...r?{disabledReason:r}:{},ariaHasPopup:"menu",ariaLabel:`Scope: ${e}`}),t.jsx(p.Menu,{anchorEl:l,open:!!l,onClose:()=>a(null),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:["package","version"].map(d=>t.jsxs(p.MenuItem,{selected:d===e,onClick:()=>void u(d),children:[t.jsx(p.ListItemIcon,{sx:{minWidth:32},children:d===e&&t.jsx(c.CheckIcon,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:d,secondary:Hf[d]})]},d))})]})}const Gf=c.createSvgIcon([t.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8"},"0"),t.jsx("path",{d:"M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z"},"1")]),ca="0 6 * * *";function Yf({currentSchedule:e,isSubmitting:n,disabled:r,disabledReason:o,onSubmit:i}){const[l,a]=j.useState(!1),[u,d]=j.useState(e??ca),h=()=>{d(e??ca),a(!0)},y=()=>a(!1),b=uo(u),x=async v=>{try{await i(v),a(!1)}catch{}};return t.jsxs(t.Fragment,{children:[t.jsx(c.SecondaryButton,{label:"Schedule",icon:t.jsx(Gf,{}),onClick:h,disabled:r,...o?{disabledReason:o}:{},ariaHasPopup:"dialog",ariaLabel:e?"Edit schedule":"Set schedule"}),t.jsxs(c.AppDialog,{open:l,onClose:y,title:e?"Edit schedule":"Set schedule",description:"The publisher rebuilds this package's materializations on this cadence: a 5-field UNIX cron, in UTC. In a hosted deployment the change takes effect on your next publish.",actions:t.jsxs(t.Fragment,{children:[e&&t.jsx(p.Button,{color:"error",loading:n,onClick:()=>x(null),sx:{mr:"auto"},children:"Clear schedule"}),t.jsx(p.Button,{onClick:y,children:"Cancel"}),t.jsx(p.Button,{variant:"contained",loading:n,disabled:!b.valid,onClick:()=>x(u.trim()),children:"Save schedule"})]}),children:[t.jsx(p.TextField,{autoFocus:!0,fullWidth:!0,size:"small",label:"Cron expression",value:u,onChange:v=>d(v.target.value),error:u.trim()!==""&&!b.valid,helperText:b.valid?`${b.description} · next run ${cl(b.nextRun)}`:b.error,slotProps:{htmlInput:{style:{fontFamily:q.MONO_FONT_FAMILY}}}}),t.jsxs(p.Alert,{severity:"info",children:["A schedule runs only on version-scoped packages, so saving one sets ",t.jsx("code",{children:"scope: version"})," for this package."]})]})]})}const Kf=3e3;function gl({resourceUri:e,versioned:n=!1}){const{apiClients:r,mutable:o}=q.useServer(),i=mt.useQueryClient(),{environmentName:l,packageName:a,versionId:u}=c.parseResourceUri(e),[d,h]=j.useState(""),[y,b]=j.useState(null);if(!a)throw new Error("Materializations requires a package in the resource URI");const x=c.useQueryWithApiError({queryKey:["materializations",l,a,u],queryFn:()=>r.materializations.listMaterializations(l,a,void 0,void 0,u),refetchInterval:H=>(H.state.data?.data??[]).some(z=>es(z.status))?Kf:!1}),v=c.useQueryWithApiError({queryKey:["package",l,a,u],queryFn:()=>r.packages.getPackage(l,a,u)}),k=c.useQueryWithApiError({queryKey:["package-build-plan",l,a,u],queryFn:async({signal:H})=>{try{return{inline:!1,plan:(await r.packages.getPackageBuildPlan(l,a,u,{signal:H})).data}}catch(Q){if(Q?.response?.status===404)return{inline:!0,plan:null};throw Q}},enabled:y!==null}),C=()=>i.invalidateQueries({queryKey:["materializations",l,a]}),S=c.useMutationWithApiError({mutationFn:Ht("materialization","create",H=>r.materializations.createMaterialization(l,a,{forceRefresh:H.forceRefresh,...u!==void 0?{versionId:u}:{}})),onSuccess(){h("Materialization requested"),C()},onError(H){h(H.message),C()}}),T=c.useMutationWithApiError({mutationFn:Ht("materialization","update",H=>r.materializations.materializationAction(l,a,H.id,q.MaterializationActionActionEnum.Stop,u)),onSuccess(){h("Materialization stopped"),C()},onError(H){h(H.message)}}),O=c.useMutationWithApiError({mutationFn:Ht("materialization","delete",H=>r.materializations.deleteMaterialization(l,a,H.id,u)),onSuccess(){h("Materialization deleted"),C()},onError(H){h(H.message)}}),M=v.data?.data,E=c.useMutationWithApiError({mutationFn:Ht("schedule","update",H=>r.packages.updatePackage(l,a,{name:a,description:M?.description,...H?{scope:q.PackageScopeEnum.Version}:{},materialization:{schedule:H}})),onSuccess(H,Q){h(Q?"Schedule updated":"Schedule cleared"),i.invalidateQueries({queryKey:["package",l,a]})},onError(H){h(H.message)}}),R=c.useMutationWithApiError({mutationFn:Ht("scope","update",H=>r.packages.updatePackage(l,a,{name:a,description:M?.description,scope:H})),onSuccess(){h("Scope updated"),i.invalidateQueries({queryKey:["package",l,a]})},onError(H){h(H.message)}}),P=x.data?.data??[],F=P.find(H=>H.id===y)??null,B=P.some(H=>es(H.status)),D=S.isPending||T.isPending||O.isPending,_=k.isError?{status:"unavailable"}:k.isSuccess?k.data.inline?v.isSuccess?{status:"ready",plan:M?.buildPlan??null}:v.isError?{status:"unavailable"}:{status:"loading"}:{status:"ready",plan:k.data.plan}:{status:"loading"},V=M?.materialization?.schedule??null,$=M?.scope===q.PackageScopeEnum.Version?"version":"package",W=!!M?.manifestLocation,Z=!!M?.materialization?.freshness,ne=V?uo(V):null,J=W?"Control-plane managed: refresh is driven by the control plane, not the built-in scheduler.":[ne?ne.valid?`${ne.description} (${V}), next run ${cl(ne.nextRun)}`:`Unrecognized cron expression (${V})`:Z?"Refreshed by a freshness policy; a cron schedule does not apply":"On demand only, no schedule set",`scope: ${$}`].join(" · ");return t.jsxs(t.Fragment,{children:[t.jsxs(Nt,{title:"Materializations",count:x.isSuccess?P.length:void 0,action:o&&t.jsxs(p.Stack,{direction:"row",spacing:1,alignItems:"center",children:[!W&&!n&&t.jsx(Uf,{scope:$,disabled:!!V,disabledReason:"A schedule requires version scope. Clear the schedule to change it.",isSubmitting:R.isPending,onChange:H=>R.mutateAsync(H==="version"?q.PackageScopeEnum.Version:q.PackageScopeEnum.Package)}),!W&&!n&&t.jsx(Yf,{currentSchedule:V,isSubmitting:E.isPending,disabled:Z,disabledReason:"This package declares a freshness policy; a schedule and freshness are mutually exclusive.",onSubmit:H=>E.mutateAsync(H)}),t.jsx(Df,{onSubmit:H=>S.mutateAsync(H),isSubmitting:S.isPending,disabled:B,disabledReason:"A materialization is already pending or running for this package."})]}),children:[v.isSuccess&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:J}),x.isError&&t.jsx(c.ApiErrorDisplay,{error:x.error,context:`${l} > ${a} > Materializations`}),!x.isSuccess&&!x.isError&&t.jsx(c.Loading,{text:"Loading materializations..."}),x.isSuccess&&t.jsx(qf,{materializations:P,mutable:o,isMutating:D,onStop:H=>T.mutate(H),onDelete:H=>O.mutate(H),onViewDetails:H=>b(H.id??null)})]}),t.jsx(Pf,{materialization:F,buildPlan:_,onClose:()=>b(null)}),t.jsx(p.Snackbar,{open:d!=="",autoHideDuration:6e3,onClose:()=>h(""),message:d})]})}const ho=c.createSvgIcon(t.jsx("path",{d:"M17 7h-4v2h4c1.65 0 3 1.35 3 3s-1.35 3-3 3h-4v2h4c2.76 0 5-2.24 5-5s-2.24-5-5-5m-6 8H7c-1.65 0-3-1.35-3-3s1.35-3 3-3h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4zm-3-4h8v2H8z"}));function Ln(e){return yl(e).join(`
|
|
8
|
-
`).trim()||void 0}function
|
|
9
|
-
`).trim()||void 0}function fo(e){if(!e)return[];const n=[];for(const r of e){const o=r.value?.trim();if(!o||o.startsWith('#"')||o.startsWith("#(doc)"))continue;const i=o.replace(/^#+@?\s*/,"").trim();i&&!i.startsWith("(")&&n.push(i)}return n}function
|
|
10
|
-
`)}function
|
|
6
|
+
`)};function Bi(){const[e,n]=T.useState(!1),{apiClients:r}=q.useServer(),o=()=>{n(!0)},i=()=>{n(!1)},l=Nn({mutationFn(u){return r.environments.createEnvironment({name:u.name,readme:ll({name:u.name,readme:""},u.description)})},success:"Environment created",invalidates:[["environments"]],closeDialog:i,resource:"environment",action:"create"}),a=async u=>{u.preventDefault();const d=new FormData(u.currentTarget),h=d.get("name")?.toString(),y=d.get("description")?.toString();if(!h)throw new Error("Name is required");l.mutate({name:h,description:y})};return t.jsxs(T.Fragment,{children:[t.jsx(c.AddButton,{label:"Environment",onClick:o}),t.jsx(c.AppDialog,{open:e,onClose:i,title:"New environment",description:"An environment holds packages and the connections they query through.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:l.isPending,onClick:i,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"environment-form",variant:"contained",loading:l.isPending,children:"Create environment"})]}),children:t.jsx("form",{onSubmit:a,id:"environment-form",children:t.jsxs(ss,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(c.TextField,{id:"description",name:"description",label:"Description",placeholder:"Explore semantic models, run queries, and build reports",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}})]})})}),l.notice]})}function hf({environment:e,onCloseDialog:n}){const[r,o]=T.useState(!1),{apiClients:i}=q.useServer(),l=()=>{o(!0)},a=()=>{o(!1),n()},u=Nn({mutationFn:()=>i.environments.deleteEnvironment(e.name),success:"Environment deleted",invalidates:[["environments"]],closeDialog:a,resource:"environment",action:"delete"});return t.jsxs(T.Fragment,{children:[t.jsxs(m.MenuItem,{onClick:l,children:[t.jsx(m.ListItemIcon,{children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(m.ListItemText,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:r,onClose:a,title:"Delete environment",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:a,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>u.mutate(),loading:u.isPending,children:"Delete environment"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:e.name}),"? Its packages stop being served and this cannot be undone."]})}),u.notice]})}function ff({environment:e,onCloseDialog:n}){const[r,o]=T.useState(!1),{apiClients:i}=q.useServer(),l=()=>{o(!0)},a=()=>{o(!1),n()},u=Nn({mutationFn(h){return i.environments.updateEnvironment(e.name,{name:e.name,readme:ll({name:e.name,readme:e.readme},h.description)})},success:"Environment updated",invalidates:[["environments"]],closeDialog:a,resource:"environment",action:"update"}),d=h=>{h.preventDefault();const b=new FormData(h.currentTarget).get("description")?.toString();u.mutate({description:b})};return t.jsxs(T.Fragment,{children:[t.jsxs(m.MenuItem,{onClick:l,children:[t.jsx(m.ListItemIcon,{children:t.jsx(Pt.Edit,{fontSize:"small"})}),t.jsx(m.ListItemText,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:r,onClose:a,title:"Edit environment",description:"What this environment is, for the people who open it.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:u.isPending,onClick:a,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"environment-form",variant:"contained",loading:u.isPending,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:d,id:"environment-form",children:t.jsxs(ss,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:e.name,InputLabelProps:{shrink:!0}}),t.jsx(c.TextField,{id:"description",name:"description",label:"Description",type:"text",fullWidth:!0,size:"small",defaultValue:al(e.readme),InputLabelProps:{shrink:!0}})]})})}),u.notice]})}const pf=[{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:Vt.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:Vt.mcpAgents},{title:"Surface",body:"Reports declared in Malloy, laid out as a grid or read top to bottom, and no-build HTML data apps, all shipped inside the package, plus this Console for browsing them.",href:Vt.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:Vt.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:Vt.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:Vt.connections}];function mf({href:e,children:n}){return t.jsx(m.Box,{component:"a",href:e,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary",textDecoration:"underline"},children:n})}function gf({onClickEnvironment:e}){const{apiClients:n,mutable:r}=q.useServer(),{data:o,isSuccess:i,isError:l,error:a}=c.useQueryWithApiError({queryKey:["environments"],queryFn:()=>n.environments.listEnvironments()});if(l)return t.jsx(c.ApiErrorDisplay,{error:a,context:"Environments List"});if(!i)return t.jsx(c.Loading,{text:"Loading environments..."});const u=o.data??[];return t.jsxs(m.Container,{maxWidth:"md",sx:{py:6},children:[t.jsxs(m.Box,{sx:{mb:5},children:[t.jsx(m.Typography,{variant:"h3",component:"h1",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Publisher"}),t.jsx(m.Typography,{variant:"body1",color:"text.secondary",sx:{mb:3},children:"The analytics engine for Malloy."}),t.jsx(m.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."})]}),t.jsx(m.Grid,{container:!0,spacing:4,sx:{mb:5},children:pf.map(d=>t.jsx(m.Grid,{size:{xs:12,sm:6},children:t.jsxs(m.Stack,{spacing:1,children:[t.jsx(m.Typography,{variant:"body2",component:"a",href:d.href,target:"_blank",rel:"noopener noreferrer",sx:{fontWeight:500,color:"text.primary",textDecoration:"none","&:hover":{textDecoration:"underline"}},children:d.title}),t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{lineHeight:1.6},children:d.body})]})},d.title))}),t.jsx(m.Divider,{sx:{my:4}}),u.length>0?t.jsx(Nt,{title:"Environments",count:u.length,description:"Published environments available on this server",...r?{action:t.jsx(Bi,{})}:{},children:t.jsx(m.Stack,{children:u.map(d=>t.jsx(yf,{environment:d,...e?{onClickEnvironment:e}:{}},d.name))})}):t.jsxs(m.Box,{sx:{mb:4},children:[t.jsx(m.Typography,{variant:"h5",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Get started"}),t.jsx(m.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."}),r?t.jsx(Bi,{}):t.jsx(m.Button,{variant:"contained",color:"primary",href:Vt.publishing,target:"_blank",rel:"noopener noreferrer",children:"Learn how to create models"})]}),t.jsx(m.Divider,{sx:{my:4}}),t.jsxs(m.Typography,{variant:"body2",color:"text.secondary",sx:{maxWidth:720,lineHeight:1.6,mt:2},children:["Join the"," ",t.jsx(mf,{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 yf({environment:e,onClickEnvironment:n}){const{mutable:r}=q.useServer(),[o,i]=T.useState(null),l=!!o,a=al(e.readme),u=h=>{h.stopPropagation(),i(h.currentTarget)},d=()=>i(null);return t.jsx(rs,{icon:t.jsx(df,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.environment,label:e.name??"",ariaLabel:e.name??"",...a?{description:a}:{},...e.name&&n?{onClick:h=>n(`/${e.name}/`,h)}:{},...r?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(m.IconButton,{size:"small",onClick:u,"aria-label":`Environment actions for ${e.name}`,children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(m.Menu,{anchorEl:o,open:l,onClose:d,onClick:h=>h.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[t.jsx(ff,{environment:e,onCloseDialog:d}),t.jsx(hf,{environment:e,onCloseDialog:d})]})]})}:{}})}var an={},Tt={},tr={},ln={},Os={},Vi;function xf(){return Vi||(Vi=1,Object.defineProperty(Os,"__esModule",{value:!0})),Os}var nr={},rr={},Hi;function pn(){if(Hi)return rr;Hi=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.CronField=void 0;let e=class cl{#e=!1;#n=!1;#o=!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(r,o={rawValue:""}){if(!Array.isArray(r))throw new Error(`${this.constructor.name} Validation error, values is not an array`);if(!(r.length>0))throw new Error(`${this.constructor.name} Validation error, values contains no values`);this.options={...o,rawValue:o.rawValue??""},this.#s=r.sort(cl.sorter),this.#o=this.options.wildcard!==void 0?this.options.wildcard:this.#r(),this.#e=this.options.rawValue.includes("L")||r.includes("L"),this.#n=this.options.rawValue.includes("?")||r.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.#o}get values(){return this.#s}static sorter(r,o){const i=typeof r=="number",l=typeof o=="number";return i&&l?r-o:!i&&!l?r.localeCompare(o):i?-1:1}static findNearestValueInList(r,o,i){if(i){for(let l=r.length-1;l>=0;l--)if(r[l]<o)return r[l];return null}for(let l=0;l<r.length;l++)if(r[l]>o)return r[l];return null}findNearestValue(r,o){return this.constructor.findNearestValueInList(this.values,r,o)}serialize(){return{wildcard:this.#o,values:this.#s}}validate(){let r;const o=this.chars.length>0?` or chars ${this.chars.join("")}`:"",i=d=>h=>new RegExp(`^\\d{0,2}${h}$`).test(d),l=d=>(r=d,typeof d=="number"?d>=this.min&&d<=this.max:this.chars.some(i(d)));if(!this.#s.every(l))throw new Error(`${this.constructor.name} Validation error, got value ${r} expected range ${this.min}-${this.max}${o}`);const u=this.#s.find((d,h)=>this.#s.indexOf(d)!==h);if(u)throw new Error(`${this.constructor.name} Validation error, duplicate values found: ${u}`)}#r(){return this.options.rawValue.length>0?["*","?"].includes(this.options.rawValue):Array.from({length:this.max-this.min+1},(r,o)=>o+this.min).every(r=>this.#s.includes(r))}};return rr.CronField=e,rr}var Ui;function vf(){if(Ui)return nr;Ui=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.CronDayOfMonth=void 0;const e=pn(),n=1,r=31,o=Object.freeze(["L"]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}static get validChars(){return/^[?,*\dLH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}};return nr.CronDayOfMonth=i,nr}var sr={},Gi;function bf(){if(Gi)return sr;Gi=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.CronDayOfWeek=void 0;const e=pn(),n=0,r=7,o=Object.freeze(["L"]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}static get validChars(){return/^[?,*\dLH#/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}get nthDay(){return this.options.nthDayOfWeek??0}};return sr.CronDayOfWeek=i,sr}var or={},Yi;function wf(){if(Yi)return or;Yi=1,Object.defineProperty(or,"__esModule",{value:!0}),or.CronHour=void 0;const e=pn(),n=0,r=23,o=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}};return or.CronHour=i,or}var ir={},Ki;function Sf(){if(Ki)return ir;Ki=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.CronMinute=void 0;const e=pn(),n=0,r=59,o=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}};return ir.CronMinute=i,ir}var ar={},Es={},bt={},Qi;function kf(){if(Qi)return bt;Qi=1,Object.defineProperty(bt,"__esModule",{value:!0});class e extends Error{}class n extends e{constructor(s){super(`Invalid DateTime: ${s.toMessage()}`)}}class r extends e{constructor(s){super(`Invalid Interval: ${s.toMessage()}`)}}class o extends e{constructor(s){super(`Invalid Duration: ${s.toMessage()}`)}}class i extends e{}class l extends e{constructor(s){super(`Invalid unit ${s}`)}}class a extends e{}class u extends e{constructor(){super("Zone is an abstract class")}}const d="numeric",h="short",y="long",b={year:d,month:d,day:d},x={year:d,month:h,day:d},v={year:d,month:h,day:d,weekday:h},k={year:d,month:y,day:d},C={year:d,month:y,day:d,weekday:y},S={hour:d,minute:d},j={hour:d,minute:d,second:d},M={hour:d,minute:d,second:d,timeZoneName:h},O={hour:d,minute:d,second:d,timeZoneName:y},E={hour:d,minute:d,hourCycle:"h23"},$={hour:d,minute:d,second:d,hourCycle:"h23"},P={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:h},A={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:y},B={year:d,month:d,day:d,hour:d,minute:d},D={year:d,month:d,day:d,hour:d,minute:d,second:d},_={year:d,month:h,day:d,hour:d,minute:d},V={year:d,month:h,day:d,hour:d,minute:d,second:d},R={year:d,month:h,day:d,weekday:h,hour:d,minute:d},W={year:d,month:y,day:d,hour:d,minute:d,timeZoneName:h},Z={year:d,month:y,day:d,hour:d,minute:d,second:d,timeZoneName:h},ne={year:d,month:y,day:d,weekday:y,hour:d,minute:d,timeZoneName:y},J={year:d,month:y,day:d,weekday:y,hour:d,minute:d,second:d,timeZoneName:y};class H{get type(){throw new u}get name(){throw new u}get ianaName(){return this.name}get isUniversal(){throw new u}offsetName(s,f){throw new u}formatOffset(s,f){throw new u}offset(s){throw new u}equals(s){throw new u}get isValid(){throw new u}}let Q=null;class re extends H{static get instance(){return Q===null&&(Q=new re),Q}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(s,{format:f,locale:g}){return Ro(s,f,g)}formatOffset(s,f){return Vn(this.offset(s),f)}offset(s){return-new Date(s).getTimezoneOffset()}equals(s){return s.type==="system"}get isValid(){return!0}}const z=new Map;function oe(p){let s=z.get(p);return s===void 0&&(s=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:p,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),z.set(p,s)),s}const se={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function ie(p,s){const f=p.format(s).replace(/\u200E/g,""),g=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(f),[,w,I,F,L,N,X,xe]=g;return[F,w,I,L,N,X,xe]}function De(p,s){const f=p.formatToParts(s),g=[];for(let w=0;w<f.length;w++){const{type:I,value:F}=f[w],L=se[I];I==="era"?g[L]=F:ee(L)||(g[L]=parseInt(F,10))}return g}const de=new Map;class ue extends H{static create(s){let f=de.get(s);return f===void 0&&de.set(s,f=new ue(s)),f}static resetCache(){de.clear(),z.clear()}static isValidSpecifier(s){return this.isValidZone(s)}static isValidZone(s){if(!s)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:s}).format(),!0}catch{return!1}}constructor(s){super(),this.zoneName=s,this.valid=ue.isValidZone(s)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(s,{format:f,locale:g}){return Ro(s,f,g,this.name)}formatOffset(s,f){return Vn(this.offset(s),f)}offset(s){if(!this.valid)return NaN;const f=new Date(s);if(isNaN(f))return NaN;const g=oe(this.name);let[w,I,F,L,N,X,xe]=g.formatToParts?De(g,f):ie(g,f);L==="BC"&&(w=-Math.abs(w)+1);const Be=Rr({year:w,month:I,day:F,hour:N===24?0:N,minute:X,second:xe,millisecond:0});let Se=+f;const it=Se%1e3;return Se-=it>=0?it:1e3+it,(Be-Se)/(60*1e3)}equals(s){return s.type==="iana"&&s.name===this.name}get isValid(){return this.valid}}let be={};function Oe(p,s={}){const f=JSON.stringify([p,s]);let g=be[f];return g||(g=new Intl.ListFormat(p,s),be[f]=g),g}const te=new Map;function K(p,s={}){const f=JSON.stringify([p,s]);let g=te.get(f);return g===void 0&&(g=new Intl.DateTimeFormat(p,s),te.set(f,g)),g}const he=new Map;function we(p,s={}){const f=JSON.stringify([p,s]);let g=he.get(f);return g===void 0&&(g=new Intl.NumberFormat(p,s),he.set(f,g)),g}const ge=new Map;function me(p,s={}){const{base:f,...g}=s,w=JSON.stringify([p,g]);let I=ge.get(w);return I===void 0&&(I=new Intl.RelativeTimeFormat(p,s),ge.set(w,I)),I}let ye=null;function Le(){return ye||(ye=new Intl.DateTimeFormat().resolvedOptions().locale,ye)}const st=new Map;function ce(p){let s=st.get(p);return s===void 0&&(s=new Intl.DateTimeFormat(p).resolvedOptions(),st.set(p,s)),s}const Y=new Map;function ae(p){let s=Y.get(p);if(!s){const f=new Intl.Locale(p);s="getWeekInfo"in f?f.getWeekInfo():f.weekInfo,"minimalDays"in s||(s={...Ye,...s}),Y.set(p,s)}return s}function Re(p){const s=p.indexOf("-x-");s!==-1&&(p=p.substring(0,s));const f=p.indexOf("-u-");if(f===-1)return[p];{let g,w;try{g=K(p).resolvedOptions(),w=p}catch{const N=p.substring(0,f);g=K(N).resolvedOptions(),w=N}const{numberingSystem:I,calendar:F}=g;return[w,I,F]}}function Ve(p,s,f){return(f||s)&&(p.includes("-u-")||(p+="-u"),f&&(p+=`-ca-${f}`),s&&(p+=`-nu-${s}`)),p}function St(p){const s=[];for(let f=1;f<=12;f++){const g=ke.utc(2009,f,1);s.push(p(g))}return s}function Ee(p){const s=[];for(let f=1;f<=7;f++){const g=ke.utc(2016,11,13+f);s.push(p(g))}return s}function at(p,s,f,g){const w=p.listingMode();return w==="error"?null:w==="en"?f(s):g(s)}function yt(p){return p.numberingSystem&&p.numberingSystem!=="latn"?!1:p.numberingSystem==="latn"||!p.locale||p.locale.startsWith("en")||ce(p.locale).numberingSystem==="latn"}class xt{constructor(s,f,g){this.padTo=g.padTo||0,this.floor=g.floor||!1;const{padTo:w,floor:I,...F}=g;if(!f||Object.keys(F).length>0){const L={useGrouping:!1,...g};g.padTo>0&&(L.minimumIntegerDigits=g.padTo),this.inf=we(s,L)}}format(s){if(this.inf){const f=this.floor?Math.floor(s):s;return this.inf.format(f)}else{const f=this.floor?Math.floor(s):fs(s,3);return ot(f,this.padTo)}}}class Mt{constructor(s,f,g){this.opts=g,this.originalZone=void 0;let w;if(this.opts.timeZone)this.dt=s;else if(s.zone.type==="fixed"){const F=-1*(s.offset/60),L=F>=0?`Etc/GMT+${F}`:`Etc/GMT${F}`;s.offset!==0&&ue.create(L).valid?(w=L,this.dt=s):(w="UTC",this.dt=s.offset===0?s:s.setZone("UTC").plus({minutes:s.offset}),this.originalZone=s.zone)}else s.zone.type==="system"?this.dt=s:s.zone.type==="iana"?(this.dt=s,w=s.zone.name):(w="UTC",this.dt=s.setZone("UTC").plus({minutes:s.offset}),this.originalZone=s.zone);const I={...this.opts};I.timeZone=I.timeZone||w,this.dtf=K(f,I)}format(){return this.originalZone?this.formatToParts().map(({value:s})=>s).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const s=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?s.map(f=>{if(f.type==="timeZoneName"){const g=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...f,value:g}}else return f}):s}resolvedOptions(){return this.dtf.resolvedOptions()}}class mt{constructor(s,f,g){this.opts={style:"long",...g},!f&&zn()&&(this.rtf=me(s,g))}format(s,f){return this.rtf?this.rtf.format(s,f):Fc(f,s,this.opts.numeric,this.opts.style!=="long")}formatToParts(s,f){return this.rtf?this.rtf.formatToParts(s,f):[]}}const Ye={firstDay:1,minimalDays:4,weekend:[6,7]};class fe{static fromOpts(s){return fe.create(s.locale,s.numberingSystem,s.outputCalendar,s.weekSettings,s.defaultToEN)}static create(s,f,g,w,I=!1){const F=s||Ne.defaultLocale,L=F||(I?"en-US":Le()),N=f||Ne.defaultNumberingSystem,X=g||Ne.defaultOutputCalendar,xe=qt(w)||Ne.defaultWeekSettings;return new fe(L,N,X,xe,F)}static resetCache(){ye=null,te.clear(),he.clear(),ge.clear(),st.clear(),Y.clear()}static fromObject({locale:s,numberingSystem:f,outputCalendar:g,weekSettings:w}={}){return fe.create(s,f,g,w)}constructor(s,f,g,w,I){const[F,L,N]=Re(s);this.locale=F,this.numberingSystem=f||L||null,this.outputCalendar=g||N||null,this.weekSettings=w,this.intl=Ve(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=I,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=yt(this)),this.fastNumbersCached}listingMode(){const s=this.isEnglish(),f=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return s&&f?"en":"intl"}clone(s){return!s||Object.getOwnPropertyNames(s).length===0?this:fe.create(s.locale||this.specifiedLocale,s.numberingSystem||this.numberingSystem,s.outputCalendar||this.outputCalendar,qt(s.weekSettings)||this.weekSettings,s.defaultToEN||!1)}redefaultToEN(s={}){return this.clone({...s,defaultToEN:!0})}redefaultToSystem(s={}){return this.clone({...s,defaultToEN:!1})}months(s,f=!1){return at(this,s,Lo,()=>{const g=this.intl==="ja"||this.intl.startsWith("ja-");f&=!g;const w=f?{month:s,day:"numeric"}:{month:s},I=f?"format":"standalone";if(!this.monthsCache[I][s]){const F=g?L=>this.dtFormatter(L,w).format():L=>this.extract(L,w,"month");this.monthsCache[I][s]=St(F)}return this.monthsCache[I][s]})}weekdays(s,f=!1){return at(this,s,Po,()=>{const g=f?{weekday:s,year:"numeric",month:"long",day:"numeric"}:{weekday:s},w=f?"format":"standalone";return this.weekdaysCache[w][s]||(this.weekdaysCache[w][s]=Ee(I=>this.extract(I,g,"weekday"))),this.weekdaysCache[w][s]})}meridiems(){return at(this,void 0,()=>zo,()=>{if(!this.meridiemCache){const s={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[ke.utc(2016,11,13,9),ke.utc(2016,11,13,19)].map(f=>this.extract(f,s,"dayperiod"))}return this.meridiemCache})}eras(s){return at(this,s,Wo,()=>{const f={era:s};return this.eraCache[s]||(this.eraCache[s]=[ke.utc(-40,1,1),ke.utc(2017,1,1)].map(g=>this.extract(g,f,"era"))),this.eraCache[s]})}extract(s,f,g){const w=this.dtFormatter(s,f),I=w.formatToParts(),F=I.find(L=>L.type.toLowerCase()===g);return F?F.value:null}numberFormatter(s={}){return new xt(this.intl,s.forceSimple||this.fastNumbers,s)}dtFormatter(s,f={}){return new Mt(s,this.intl,f)}relFormatter(s={}){return new mt(this.intl,this.isEnglish(),s)}listFormatter(s={}){return Oe(this.intl,s)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||ce(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Wn()?ae(this.locale):Ye}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(s){return this.locale===s.locale&&this.numberingSystem===s.numberingSystem&&this.outputCalendar===s.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let Ke=null;class ze extends H{static get utcInstance(){return Ke===null&&(Ke=new ze(0)),Ke}static instance(s){return s===0?ze.utcInstance:new ze(s)}static parseSpecifier(s){if(s){const f=s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(f)return new ze($r(f[1],f[2]))}return null}constructor(s){super(),this.fixed=s}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Vn(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Vn(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(s,f){return Vn(this.fixed,f)}get isUniversal(){return!0}offset(){return this.fixed}equals(s){return s.type==="fixed"&&s.fixed===this.fixed}get isValid(){return!0}}class lt extends H{constructor(s){super(),this.zoneName=s}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 ct(p,s){if(ee(p)||p===null)return s;if(p instanceof H)return p;if(Ct(p)){const f=p.toLowerCase();return f==="default"?s:f==="local"||f==="system"?re.instance:f==="utc"||f==="gmt"?ze.utcInstance:ze.parseSpecifier(f)||ue.create(p)}else return qe(p)?ze.instance(p):typeof p=="object"&&"offset"in p&&typeof p.offset=="function"?p:new lt(p)}const Qe={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},pe={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]},He=Qe.hanidec.replace(/[\[|\]]/g,"").split("");function vt(p){let s=parseInt(p,10);if(isNaN(s)){s="";for(let f=0;f<p.length;f++){const g=p.charCodeAt(f);if(p[f].search(Qe.hanidec)!==-1)s+=He.indexOf(p[f]);else for(const w in pe){const[I,F]=pe[w];g>=I&&g<=F&&(s+=g-I)}}return parseInt(s,10)}else return s}const Ce=new Map;function Fe(){Ce.clear()}function Ie({numberingSystem:p},s=""){const f=p||"latn";let g=Ce.get(f);g===void 0&&(g=new Map,Ce.set(f,g));let w=g.get(s);return w===void 0&&(w=new RegExp(`${Qe[f]}${s}`),g.set(s,w)),w}let We=()=>Date.now(),dt="system",Pe=null,tt=null,Ot=null,kt=60,Rt,gn=null;class Ne{static get now(){return We}static set now(s){We=s}static set defaultZone(s){dt=s}static get defaultZone(){return ct(dt,re.instance)}static get defaultLocale(){return Pe}static set defaultLocale(s){Pe=s}static get defaultNumberingSystem(){return tt}static set defaultNumberingSystem(s){tt=s}static get defaultOutputCalendar(){return Ot}static set defaultOutputCalendar(s){Ot=s}static get defaultWeekSettings(){return gn}static set defaultWeekSettings(s){gn=qt(s)}static get twoDigitCutoffYear(){return kt}static set twoDigitCutoffYear(s){kt=s%100}static get throwOnInvalid(){return Rt}static set throwOnInvalid(s){Rt=s}static resetCaches(){fe.resetCache(),ue.resetCache(),ke.resetCache(),Fe()}}class ut{constructor(s,f){this.reason=s,this.explanation=f}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const Kt=[0,31,59,90,120,151,181,212,243,273,304,334],yn=[0,31,60,91,121,152,182,213,244,274,305,335];function ht(p,s){return new ut("unit out of range",`you specified ${s} (of type ${typeof s}) as a ${p}, which is invalid`)}function en(p,s,f){const g=new Date(Date.UTC(p,s-1,f));p<100&&p>=0&&g.setUTCFullYear(g.getUTCFullYear()-1900);const w=g.getUTCDay();return w===0?7:w}function xn(p,s,f){return f+(qn(p)?yn:Kt)[s-1]}function Qt(p,s){const f=qn(p)?yn:Kt,g=f.findIndex(I=>I<s),w=s-f[g];return{month:g+1,day:w}}function Ze(p,s){return(p-s+7)%7+1}function Xe(p,s=4,f=1){const{year:g,month:w,day:I}=p,F=xn(g,w,I),L=Ze(en(g,w,I),f);let N=Math.floor((F-L+14-s)/7),X;return N<1?(X=g-1,N=Bn(X,s,f)):N>Bn(g,s,f)?(X=g+1,N=1):X=g,{weekYear:X,weekNumber:N,weekday:L,...Lr(p)}}function $t(p,s=4,f=1){const{weekYear:g,weekNumber:w,weekday:I}=p,F=Ze(en(g,1,s),f),L=bn(g);let N=w*7+I-F-7+s,X;N<1?(X=g-1,N+=bn(X)):N>L?(X=g+1,N-=bn(g)):X=g;const{month:xe,day:je}=Qt(X,N);return{year:X,month:xe,day:je,...Lr(p)}}function tn(p){const{year:s,month:f,day:g}=p,w=xn(s,f,g);return{year:s,ordinal:w,...Lr(p)}}function Zt(p){const{year:s,ordinal:f}=p,{month:g,day:w}=Qt(s,f);return{year:s,month:g,day:w,...Lr(p)}}function nn(p,s){if(!ee(p.localWeekday)||!ee(p.localWeekNumber)||!ee(p.localWeekYear)){if(!ee(p.weekday)||!ee(p.weekNumber)||!ee(p.weekYear))throw new i("Cannot mix locale-based week fields with ISO-based week fields");return ee(p.localWeekday)||(p.weekday=p.localWeekday),ee(p.localWeekNumber)||(p.weekNumber=p.localWeekNumber),ee(p.localWeekYear)||(p.weekYear=p.localWeekYear),delete p.localWeekday,delete p.localWeekNumber,delete p.localWeekYear,{minDaysInFirstWeek:s.getMinDaysInFirstWeek(),startOfWeek:s.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function G(p,s=4,f=1){const g=Ue(p.weekYear),w=Et(p.weekNumber,1,Bn(p.weekYear,s,f)),I=Et(p.weekday,1,7);return g?w?I?!1:ht("weekday",p.weekday):ht("week",p.weekNumber):ht("weekYear",p.weekYear)}function U(p){const s=Ue(p.year),f=Et(p.ordinal,1,bn(p.year));return s?f?!1:ht("ordinal",p.ordinal):ht("year",p.year)}function le(p){const s=Ue(p.year),f=Et(p.month,1,12),g=Et(p.day,1,Ar(p.year,p.month));return s?f?g?!1:ht("day",p.day):ht("month",p.month):ht("year",p.year)}function ve(p){const{hour:s,minute:f,second:g,millisecond:w}=p,I=Et(s,0,23)||s===24&&f===0&&g===0&&w===0,F=Et(f,0,59),L=Et(g,0,59),N=Et(w,0,999);return I?F?L?N?!1:ht("millisecond",w):ht("second",g):ht("minute",f):ht("hour",s)}function ee(p){return typeof p>"u"}function qe(p){return typeof p=="number"}function Ue(p){return typeof p=="number"&&p%1===0}function Ct(p){return typeof p=="string"}function vn(p){return Object.prototype.toString.call(p)==="[object Date]"}function zn(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Wn(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function Dr(p){return Array.isArray(p)?p:[p]}function Ae(p,s,f){if(p.length!==0)return p.reduce((g,w)=>{const I=[s(w),w];return g&&f(g[0],I[0])===g[0]?g:I},null)[1]}function zt(p,s){return s.reduce((f,g)=>(f[g]=p[g],f),{})}function gt(p,s){return Object.prototype.hasOwnProperty.call(p,s)}function qt(p){if(p==null)return null;if(typeof p!="object")throw new a("Week settings must be an object");if(!Et(p.firstDay,1,7)||!Et(p.minimalDays,1,7)||!Array.isArray(p.weekend)||p.weekend.some(s=>!Et(s,1,7)))throw new a("Invalid week settings");return{firstDay:p.firstDay,minimalDays:p.minimalDays,weekend:Array.from(p.weekend)}}function Et(p,s,f){return Ue(p)&&p>=s&&p<=f}function Cc(p,s){return p-s*Math.floor(p/s)}function ot(p,s=2){const f=p<0;let g;return f?g="-"+(""+-p).padStart(s,"0"):g=(""+p).padStart(s,"0"),g}function Xt(p){if(!(ee(p)||p===null||p===""))return parseInt(p,10)}function rn(p){if(!(ee(p)||p===null||p===""))return parseFloat(p)}function hs(p){if(!(ee(p)||p===null||p==="")){const s=parseFloat("0."+p)*1e3;return Math.floor(s)}}function fs(p,s,f="round"){const g=10**s;switch(f){case"expand":return p>0?Math.ceil(p*g)/g:Math.floor(p*g)/g;case"trunc":return Math.trunc(p*g)/g;case"round":return Math.round(p*g)/g;case"floor":return Math.floor(p*g)/g;case"ceil":return Math.ceil(p*g)/g;default:throw new RangeError(`Value rounding ${f} is out of range`)}}function qn(p){return p%4===0&&(p%100!==0||p%400===0)}function bn(p){return qn(p)?366:365}function Ar(p,s){const f=Cc(s-1,12)+1,g=p+(s-f)/12;return f===2?qn(g)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][f-1]}function Rr(p){let s=Date.UTC(p.year,p.month-1,p.day,p.hour,p.minute,p.second,p.millisecond);return p.year<100&&p.year>=0&&(s=new Date(s),s.setUTCFullYear(p.year,p.month-1,p.day)),+s}function Ao(p,s,f){return-Ze(en(p,1,s),f)+s-1}function Bn(p,s=4,f=1){const g=Ao(p,s,f),w=Ao(p+1,s,f);return(bn(p)-g+w)/7}function ps(p){return p>99?p:p>Ne.twoDigitCutoffYear?1900+p:2e3+p}function Ro(p,s,f,g=null){const w=new Date(p),I={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};g&&(I.timeZone=g);const F={timeZoneName:s,...I},L=new Intl.DateTimeFormat(f,F).formatToParts(w).find(N=>N.type.toLowerCase()==="timezonename");return L?L.value:null}function $r(p,s){let f=parseInt(p,10);Number.isNaN(f)&&(f=0);const g=parseInt(s,10)||0,w=f<0||Object.is(f,-0)?-g:g;return f*60+w}function $o(p){const s=Number(p);if(typeof p=="boolean"||p===""||!Number.isFinite(s))throw new a(`Invalid unit value ${p}`);return s}function Fr(p,s){const f={};for(const g in p)if(gt(p,g)){const w=p[g];if(w==null)continue;f[s(g)]=$o(w)}return f}function Vn(p,s){const f=Math.trunc(Math.abs(p/60)),g=Math.trunc(Math.abs(p%60)),w=p>=0?"+":"-";switch(s){case"short":return`${w}${ot(f,2)}:${ot(g,2)}`;case"narrow":return`${w}${f}${g>0?`:${g}`:""}`;case"techie":return`${w}${ot(f,2)}${ot(g,2)}`;default:throw new RangeError(`Value format ${s} is out of range for property format`)}}function Lr(p){return zt(p,["hour","minute","second","millisecond"])}const Tc=["January","February","March","April","May","June","July","August","September","October","November","December"],Fo=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],jc=["J","F","M","A","M","J","J","A","S","O","N","D"];function Lo(p){switch(p){case"narrow":return[...jc];case"short":return[...Fo];case"long":return[...Tc];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 _o=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],No=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],Mc=["M","T","W","T","F","S","S"];function Po(p){switch(p){case"narrow":return[...Mc];case"short":return[...No];case"long":return[..._o];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const zo=["AM","PM"],Oc=["Before Christ","Anno Domini"],Ec=["BC","AD"],Ic=["B","A"];function Wo(p){switch(p){case"narrow":return[...Ic];case"short":return[...Ec];case"long":return[...Oc];default:return null}}function Dc(p){return zo[p.hour<12?0:1]}function Ac(p,s){return Po(s)[p.weekday-1]}function Rc(p,s){return Lo(s)[p.month-1]}function $c(p,s){return Wo(s)[p.year<0?0:1]}function Fc(p,s,f="always",g=!1){const w={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."]},I=["hours","minutes","seconds"].indexOf(p)===-1;if(f==="auto"&&I){const je=p==="days";switch(s){case 1:return je?"tomorrow":`next ${w[p][0]}`;case-1:return je?"yesterday":`last ${w[p][0]}`;case 0:return je?"today":`this ${w[p][0]}`}}const F=Object.is(s,-0)||s<0,L=Math.abs(s),N=L===1,X=w[p],xe=g?N?X[1]:X[2]||X[1]:N?w[p][0]:p;return F?`${L} ${xe} ago`:`in ${L} ${xe}`}function qo(p,s){let f="";for(const g of p)g.literal?f+=g.val:f+=s(g.val);return f}const Lc={D:b,DD:x,DDD:k,DDDD:C,t:S,tt:j,ttt:M,tttt:O,T:E,TT:$,TTT:P,TTTT:A,f:B,ff:_,fff:W,ffff:ne,F:D,FF:V,FFF:Z,FFFF:J};class ft{static create(s,f={}){return new ft(s,f)}static parseFormat(s){let f=null,g="",w=!1;const I=[];for(let F=0;F<s.length;F++){const L=s.charAt(F);L==="'"?((g.length>0||w)&&I.push({literal:w||/^\s+$/.test(g),val:g===""?"'":g}),f=null,g="",w=!w):w||L===f?g+=L:(g.length>0&&I.push({literal:/^\s+$/.test(g),val:g}),g=L,f=L)}return g.length>0&&I.push({literal:w||/^\s+$/.test(g),val:g}),I}static macroTokenToFormatOpts(s){return Lc[s]}constructor(s,f){this.opts=f,this.loc=s,this.systemLoc=null}formatWithSystemDefault(s,f){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(s,{...this.opts,...f}).format()}dtFormatter(s,f={}){return this.loc.dtFormatter(s,{...this.opts,...f})}formatDateTime(s,f){return this.dtFormatter(s,f).format()}formatDateTimeParts(s,f){return this.dtFormatter(s,f).formatToParts()}formatInterval(s,f){return this.dtFormatter(s.start,f).dtf.formatRange(s.start.toJSDate(),s.end.toJSDate())}resolvedOptions(s,f){return this.dtFormatter(s,f).resolvedOptions()}num(s,f=0,g=void 0){if(this.opts.forceSimple)return ot(s,f);const w={...this.opts};return f>0&&(w.padTo=f),g&&(w.signDisplay=g),this.loc.numberFormatter(w).format(s)}formatDateTimeFromString(s,f){const g=this.loc.listingMode()==="en",w=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",I=(Se,it)=>this.loc.extract(s,Se,it),F=Se=>s.isOffsetFixed&&s.offset===0&&Se.allowZ?"Z":s.isValid?s.zone.formatOffset(s.ts,Se.format):"",L=()=>g?Dc(s):I({hour:"numeric",hourCycle:"h12"},"dayperiod"),N=(Se,it)=>g?Rc(s,Se):I(it?{month:Se}:{month:Se,day:"numeric"},"month"),X=(Se,it)=>g?Ac(s,Se):I(it?{weekday:Se}:{weekday:Se,month:"long",day:"numeric"},"weekday"),xe=Se=>{const it=ft.macroTokenToFormatOpts(Se);return it?this.formatWithSystemDefault(s,it):Se},je=Se=>g?$c(s,Se):I({era:Se},"era"),Be=Se=>{switch(Se){case"S":return this.num(s.millisecond);case"u":case"SSS":return this.num(s.millisecond,3);case"s":return this.num(s.second);case"ss":return this.num(s.second,2);case"uu":return this.num(Math.floor(s.millisecond/10),2);case"uuu":return this.num(Math.floor(s.millisecond/100));case"m":return this.num(s.minute);case"mm":return this.num(s.minute,2);case"h":return this.num(s.hour%12===0?12:s.hour%12);case"hh":return this.num(s.hour%12===0?12:s.hour%12,2);case"H":return this.num(s.hour);case"HH":return this.num(s.hour,2);case"Z":return F({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return F({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return F({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return s.zone.offsetName(s.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return s.zone.offsetName(s.ts,{format:"long",locale:this.loc.locale});case"z":return s.zoneName;case"a":return L();case"d":return w?I({day:"numeric"},"day"):this.num(s.day);case"dd":return w?I({day:"2-digit"},"day"):this.num(s.day,2);case"c":return this.num(s.weekday);case"ccc":return X("short",!0);case"cccc":return X("long",!0);case"ccccc":return X("narrow",!0);case"E":return this.num(s.weekday);case"EEE":return X("short",!1);case"EEEE":return X("long",!1);case"EEEEE":return X("narrow",!1);case"L":return w?I({month:"numeric",day:"numeric"},"month"):this.num(s.month);case"LL":return w?I({month:"2-digit",day:"numeric"},"month"):this.num(s.month,2);case"LLL":return N("short",!0);case"LLLL":return N("long",!0);case"LLLLL":return N("narrow",!0);case"M":return w?I({month:"numeric"},"month"):this.num(s.month);case"MM":return w?I({month:"2-digit"},"month"):this.num(s.month,2);case"MMM":return N("short",!1);case"MMMM":return N("long",!1);case"MMMMM":return N("narrow",!1);case"y":return w?I({year:"numeric"},"year"):this.num(s.year);case"yy":return w?I({year:"2-digit"},"year"):this.num(s.year.toString().slice(-2),2);case"yyyy":return w?I({year:"numeric"},"year"):this.num(s.year,4);case"yyyyyy":return w?I({year:"numeric"},"year"):this.num(s.year,6);case"G":return je("short");case"GG":return je("long");case"GGGGG":return je("narrow");case"kk":return this.num(s.weekYear.toString().slice(-2),2);case"kkkk":return this.num(s.weekYear,4);case"W":return this.num(s.weekNumber);case"WW":return this.num(s.weekNumber,2);case"n":return this.num(s.localWeekNumber);case"nn":return this.num(s.localWeekNumber,2);case"ii":return this.num(s.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(s.localWeekYear,4);case"o":return this.num(s.ordinal);case"ooo":return this.num(s.ordinal,3);case"q":return this.num(s.quarter);case"qq":return this.num(s.quarter,2);case"X":return this.num(Math.floor(s.ts/1e3));case"x":return this.num(s.ts);default:return xe(Se)}};return qo(ft.parseFormat(f),Be)}formatDurationFromString(s,f){const g=this.opts.signMode==="negativeLargestOnly"?-1:1,w=xe=>{switch(xe[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}},I=(xe,je)=>Be=>{const Se=w(Be);if(Se){const it=je.isNegativeDuration&&Se!==je.largestUnit?g:1;let Lt;return this.opts.signMode==="negativeLargestOnly"&&Se!==je.largestUnit?Lt="never":this.opts.signMode==="all"?Lt="always":Lt="auto",this.num(xe.get(Se)*it,Be.length,Lt)}else return Be},F=ft.parseFormat(f),L=F.reduce((xe,{literal:je,val:Be})=>je?xe:xe.concat(Be),[]),N=s.shiftTo(...L.map(w).filter(xe=>xe)),X={isNegativeDuration:N<0,largestUnit:Object.keys(N.values)[0]};return qo(F,I(N,X))}}const Bo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function wn(...p){const s=p.reduce((f,g)=>f+g.source,"");return RegExp(`^${s}$`)}function Sn(...p){return s=>p.reduce(([f,g,w],I)=>{const[F,L,N]=I(s,w);return[{...f,...F},L||g,N]},[{},null,1]).slice(0,2)}function kn(p,...s){if(p==null)return[null,null];for(const[f,g]of s){const w=f.exec(p);if(w)return g(w)}return[null,null]}function Vo(...p){return(s,f)=>{const g={};let w;for(w=0;w<p.length;w++)g[p[w]]=Xt(s[f+w]);return[g,null,f+w]}}const Ho=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,_c=`(?:${Ho.source}?(?:\\[(${Bo.source})\\])?)?`,ms=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Uo=RegExp(`${ms.source}${_c}`),gs=RegExp(`(?:[Tt]${Uo.source})?`),Nc=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Pc=/(\d{4})-?W(\d\d)(?:-?(\d))?/,zc=/(\d{4})-?(\d{3})/,Wc=Vo("weekYear","weekNumber","weekDay"),qc=Vo("year","ordinal"),Bc=/(\d{4})-(\d\d)-(\d\d)/,Go=RegExp(`${ms.source} ?(?:${Ho.source}|(${Bo.source}))?`),Vc=RegExp(`(?: ${Go.source})?`);function Cn(p,s,f){const g=p[s];return ee(g)?f:Xt(g)}function Hc(p,s){return[{year:Cn(p,s),month:Cn(p,s+1,1),day:Cn(p,s+2,1)},null,s+3]}function Tn(p,s){return[{hours:Cn(p,s,0),minutes:Cn(p,s+1,0),seconds:Cn(p,s+2,0),milliseconds:hs(p[s+3])},null,s+4]}function Hn(p,s){const f=!p[s]&&!p[s+1],g=$r(p[s+1],p[s+2]),w=f?null:ze.instance(g);return[{},w,s+3]}function Un(p,s){const f=p[s]?ue.create(p[s]):null;return[{},f,s+1]}const Uc=RegExp(`^T?${ms.source}$`),Gc=/^-?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 Yc(p){const[s,f,g,w,I,F,L,N,X]=p,xe=s[0]==="-",je=N&&N[0]==="-",Be=(Se,it=!1)=>Se!==void 0&&(it||Se&&xe)?-Se:Se;return[{years:Be(rn(f)),months:Be(rn(g)),weeks:Be(rn(w)),days:Be(rn(I)),hours:Be(rn(F)),minutes:Be(rn(L)),seconds:Be(rn(N),N==="-0"),milliseconds:Be(hs(X),je)}]}const Kc={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function ys(p,s,f,g,w,I,F){const L={year:s.length===2?ps(Xt(s)):Xt(s),month:Fo.indexOf(f)+1,day:Xt(g),hour:Xt(w),minute:Xt(I)};return F&&(L.second=Xt(F)),p&&(L.weekday=p.length>3?_o.indexOf(p)+1:No.indexOf(p)+1),L}const Qc=/^(?:(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 Zc(p){const[,s,f,g,w,I,F,L,N,X,xe,je]=p,Be=ys(s,w,g,f,I,F,L);let Se;return N?Se=Kc[N]:X?Se=0:Se=$r(xe,je),[Be,new ze(Se)]}function Xc(p){return p.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Jc=/^(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$/,eu=/^(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$/,tu=/^(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 Yo(p){const[,s,f,g,w,I,F,L]=p;return[ys(s,w,g,f,I,F,L),ze.utcInstance]}function nu(p){const[,s,f,g,w,I,F,L]=p;return[ys(s,L,f,g,w,I,F),ze.utcInstance]}const ru=wn(Nc,gs),su=wn(Pc,gs),ou=wn(zc,gs),iu=wn(Uo),Ko=Sn(Hc,Tn,Hn,Un),au=Sn(Wc,Tn,Hn,Un),lu=Sn(qc,Tn,Hn,Un),cu=Sn(Tn,Hn,Un);function uu(p){return kn(p,[ru,Ko],[su,au],[ou,lu],[iu,cu])}function du(p){return kn(Xc(p),[Qc,Zc])}function hu(p){return kn(p,[Jc,Yo],[eu,Yo],[tu,nu])}function fu(p){return kn(p,[Gc,Yc])}const pu=Sn(Tn);function mu(p){return kn(p,[Uc,pu])}const gu=wn(Bc,Vc),yu=wn(Go),xu=Sn(Tn,Hn,Un);function vu(p){return kn(p,[gu,Ko],[yu,xu])}const Qo="Invalid Duration",Zo={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}},bu={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},...Zo},It=146097/400,jn=146097/4800,wu={years:{quarters:4,months:12,weeks:It/7,days:It,hours:It*24,minutes:It*24*60,seconds:It*24*60*60,milliseconds:It*24*60*60*1e3},quarters:{months:3,weeks:It/28,days:It/4,hours:It*24/4,minutes:It*24*60/4,seconds:It*24*60*60/4,milliseconds:It*24*60*60*1e3/4},months:{weeks:jn/7,days:jn,hours:jn*24,minutes:jn*24*60,seconds:jn*24*60*60,milliseconds:jn*24*60*60*1e3},...Zo},sn=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],Su=sn.slice(0).reverse();function Bt(p,s,f=!1){const g={values:f?s.values:{...p.values,...s.values||{}},loc:p.loc.clone(s.loc),conversionAccuracy:s.conversionAccuracy||p.conversionAccuracy,matrix:s.matrix||p.matrix};return new $e(g)}function Xo(p,s){var f;let g=(f=s.milliseconds)!=null?f:0;for(const w of Su.slice(1))s[w]&&(g+=s[w]*p[w].milliseconds);return g}function Jo(p,s){const f=Xo(p,s)<0?-1:1;sn.reduceRight((g,w)=>{if(ee(s[w]))return g;if(g){const I=s[g]*f,F=p[w][g],L=Math.floor(I/F);s[w]+=L*f,s[g]-=L*F*f}return w},null),sn.reduce((g,w)=>{if(ee(s[w]))return g;if(g){const I=s[g]%1;s[g]-=I,s[w]+=I*p[g][w]}return w},null)}function ei(p){const s={};for(const[f,g]of Object.entries(p))g!==0&&(s[f]=g);return s}class $e{constructor(s){const f=s.conversionAccuracy==="longterm"||!1;let g=f?wu:bu;s.matrix&&(g=s.matrix),this.values=s.values,this.loc=s.loc||fe.create(),this.conversionAccuracy=f?"longterm":"casual",this.invalid=s.invalid||null,this.matrix=g,this.isLuxonDuration=!0}static fromMillis(s,f){return $e.fromObject({milliseconds:s},f)}static fromObject(s,f={}){if(s==null||typeof s!="object")throw new a(`Duration.fromObject: argument expected to be an object, got ${s===null?"null":typeof s}`);return new $e({values:Fr(s,$e.normalizeUnit),loc:fe.fromObject(f),conversionAccuracy:f.conversionAccuracy,matrix:f.matrix})}static fromDurationLike(s){if(qe(s))return $e.fromMillis(s);if($e.isDuration(s))return s;if(typeof s=="object")return $e.fromObject(s);throw new a(`Unknown duration argument ${s} of type ${typeof s}`)}static fromISO(s,f){const[g]=fu(s);return g?$e.fromObject(g,f):$e.invalid("unparsable",`the input "${s}" can't be parsed as ISO 8601`)}static fromISOTime(s,f){const[g]=mu(s);return g?$e.fromObject(g,f):$e.invalid("unparsable",`the input "${s}" can't be parsed as ISO 8601`)}static invalid(s,f=null){if(!s)throw new a("need to specify a reason the Duration is invalid");const g=s instanceof ut?s:new ut(s,f);if(Ne.throwOnInvalid)throw new o(g);return new $e({invalid:g})}static normalizeUnit(s){const f={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"}[s&&s.toLowerCase()];if(!f)throw new l(s);return f}static isDuration(s){return s&&s.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(s,f={}){const g={...f,floor:f.round!==!1&&f.floor!==!1};return this.isValid?ft.create(this.loc,g).formatDurationFromString(this,s):Qo}toHuman(s={}){if(!this.isValid)return Qo;const f=s.showZeros!==!1,g=sn.map(w=>{const I=this.values[w];return ee(I)||I===0&&!f?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...s,unit:w.slice(0,-1)}).format(I)}).filter(w=>w);return this.loc.listFormatter({type:"conjunction",style:s.listStyle||"narrow",...s}).format(g)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let s="P";return this.years!==0&&(s+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(s+=this.months+this.quarters*3+"M"),this.weeks!==0&&(s+=this.weeks+"W"),this.days!==0&&(s+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(s+="T"),this.hours!==0&&(s+=this.hours+"H"),this.minutes!==0&&(s+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(s+=fs(this.seconds+this.milliseconds/1e3,3)+"S"),s==="P"&&(s+="T0S"),s}toISOTime(s={}){if(!this.isValid)return null;const f=this.toMillis();return f<0||f>=864e5?null:(s={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...s,includeOffset:!1},ke.fromMillis(f,{zone:"UTC"}).toISOTime(s))}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?Xo(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(s){if(!this.isValid)return this;const f=$e.fromDurationLike(s),g={};for(const w of sn)(gt(f.values,w)||gt(this.values,w))&&(g[w]=f.get(w)+this.get(w));return Bt(this,{values:g},!0)}minus(s){if(!this.isValid)return this;const f=$e.fromDurationLike(s);return this.plus(f.negate())}mapUnits(s){if(!this.isValid)return this;const f={};for(const g of Object.keys(this.values))f[g]=$o(s(this.values[g],g));return Bt(this,{values:f},!0)}get(s){return this[$e.normalizeUnit(s)]}set(s){if(!this.isValid)return this;const f={...this.values,...Fr(s,$e.normalizeUnit)};return Bt(this,{values:f})}reconfigure({locale:s,numberingSystem:f,conversionAccuracy:g,matrix:w}={}){const F={loc:this.loc.clone({locale:s,numberingSystem:f}),matrix:w,conversionAccuracy:g};return Bt(this,F)}as(s){return this.isValid?this.shiftTo(s).get(s):NaN}normalize(){if(!this.isValid)return this;const s=this.toObject();return Jo(this.matrix,s),Bt(this,{values:s},!0)}rescale(){if(!this.isValid)return this;const s=ei(this.normalize().shiftToAll().toObject());return Bt(this,{values:s},!0)}shiftTo(...s){if(!this.isValid)return this;if(s.length===0)return this;s=s.map(F=>$e.normalizeUnit(F));const f={},g={},w=this.toObject();let I;for(const F of sn)if(s.indexOf(F)>=0){I=F;let L=0;for(const X in g)L+=this.matrix[X][F]*g[X],g[X]=0;qe(w[F])&&(L+=w[F]);const N=Math.trunc(L);f[F]=N,g[F]=(L*1e3-N*1e3)/1e3}else qe(w[F])&&(g[F]=w[F]);for(const F in g)g[F]!==0&&(f[I]+=F===I?g[F]:g[F]/this.matrix[I][F]);return Jo(this.matrix,f),Bt(this,{values:f},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const s={};for(const f of Object.keys(this.values))s[f]=this.values[f]===0?0:-this.values[f];return Bt(this,{values:s},!0)}removeZeros(){if(!this.isValid)return this;const s=ei(this.values);return Bt(this,{values:s},!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(s){if(!this.isValid||!s.isValid||!this.loc.equals(s.loc))return!1;function f(g,w){return g===void 0||g===0?w===void 0||w===0:g===w}for(const g of sn)if(!f(this.values[g],s.values[g]))return!1;return!0}}const Mn="Invalid Interval";function ku(p,s){return!p||!p.isValid?Je.invalid("missing or invalid start"):!s||!s.isValid?Je.invalid("missing or invalid end"):s<p?Je.invalid("end before start",`The end of an interval must be after its start, but you had start=${p.toISO()} and end=${s.toISO()}`):null}class Je{constructor(s){this.s=s.start,this.e=s.end,this.invalid=s.invalid||null,this.isLuxonInterval=!0}static invalid(s,f=null){if(!s)throw new a("need to specify a reason the Interval is invalid");const g=s instanceof ut?s:new ut(s,f);if(Ne.throwOnInvalid)throw new r(g);return new Je({invalid:g})}static fromDateTimes(s,f){const g=Qn(s),w=Qn(f),I=ku(g,w);return I??new Je({start:g,end:w})}static after(s,f){const g=$e.fromDurationLike(f),w=Qn(s);return Je.fromDateTimes(w,w.plus(g))}static before(s,f){const g=$e.fromDurationLike(f),w=Qn(s);return Je.fromDateTimes(w.minus(g),w)}static fromISO(s,f){const[g,w]=(s||"").split("/",2);if(g&&w){let I,F;try{I=ke.fromISO(g,f),F=I.isValid}catch{F=!1}let L,N;try{L=ke.fromISO(w,f),N=L.isValid}catch{N=!1}if(F&&N)return Je.fromDateTimes(I,L);if(F){const X=$e.fromISO(w,f);if(X.isValid)return Je.after(I,X)}else if(N){const X=$e.fromISO(g,f);if(X.isValid)return Je.before(L,X)}}return Je.invalid("unparsable",`the input "${s}" can't be parsed as ISO 8601`)}static isInterval(s){return s&&s.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(s="milliseconds"){return this.isValid?this.toDuration(s).get(s):NaN}count(s="milliseconds",f){if(!this.isValid)return NaN;const g=this.start.startOf(s,f);let w;return f!=null&&f.useLocaleWeeks?w=this.end.reconfigure({locale:g.locale}):w=this.end,w=w.startOf(s,f),Math.floor(w.diff(g,s).get(s))+(w.valueOf()!==this.end.valueOf())}hasSame(s){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,s):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(s){return this.isValid?this.s>s:!1}isBefore(s){return this.isValid?this.e<=s:!1}contains(s){return this.isValid?this.s<=s&&this.e>s:!1}set({start:s,end:f}={}){return this.isValid?Je.fromDateTimes(s||this.s,f||this.e):this}splitAt(...s){if(!this.isValid)return[];const f=s.map(Qn).filter(F=>this.contains(F)).sort((F,L)=>F.toMillis()-L.toMillis()),g=[];let{s:w}=this,I=0;for(;w<this.e;){const F=f[I]||this.e,L=+F>+this.e?this.e:F;g.push(Je.fromDateTimes(w,L)),w=L,I+=1}return g}splitBy(s){const f=$e.fromDurationLike(s);if(!this.isValid||!f.isValid||f.as("milliseconds")===0)return[];let{s:g}=this,w=1,I;const F=[];for(;g<this.e;){const L=this.start.plus(f.mapUnits(N=>N*w));I=+L>+this.e?this.e:L,F.push(Je.fromDateTimes(g,I)),g=I,w+=1}return F}divideEqually(s){return this.isValid?this.splitBy(this.length()/s).slice(0,s):[]}overlaps(s){return this.e>s.s&&this.s<s.e}abutsStart(s){return this.isValid?+this.e==+s.s:!1}abutsEnd(s){return this.isValid?+s.e==+this.s:!1}engulfs(s){return this.isValid?this.s<=s.s&&this.e>=s.e:!1}equals(s){return!this.isValid||!s.isValid?!1:this.s.equals(s.s)&&this.e.equals(s.e)}intersection(s){if(!this.isValid)return this;const f=this.s>s.s?this.s:s.s,g=this.e<s.e?this.e:s.e;return f>=g?null:Je.fromDateTimes(f,g)}union(s){if(!this.isValid)return this;const f=this.s<s.s?this.s:s.s,g=this.e>s.e?this.e:s.e;return Je.fromDateTimes(f,g)}static merge(s){const[f,g]=s.sort((w,I)=>w.s-I.s).reduce(([w,I],F)=>I?I.overlaps(F)||I.abutsStart(F)?[w,I.union(F)]:[w.concat([I]),F]:[w,F],[[],null]);return g&&f.push(g),f}static xor(s){let f=null,g=0;const w=[],I=s.map(N=>[{time:N.s,type:"s"},{time:N.e,type:"e"}]),F=Array.prototype.concat(...I),L=F.sort((N,X)=>N.time-X.time);for(const N of L)g+=N.type==="s"?1:-1,g===1?f=N.time:(f&&+f!=+N.time&&w.push(Je.fromDateTimes(f,N.time)),f=null);return Je.merge(w)}difference(...s){return Je.xor([this].concat(s)).map(f=>this.intersection(f)).filter(f=>f&&!f.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:Mn}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(s=b,f={}){return this.isValid?ft.create(this.s.loc.clone(f),s).formatInterval(this):Mn}toISO(s){return this.isValid?`${this.s.toISO(s)}/${this.e.toISO(s)}`:Mn}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Mn}toISOTime(s){return this.isValid?`${this.s.toISOTime(s)}/${this.e.toISOTime(s)}`:Mn}toFormat(s,{separator:f=" – "}={}){return this.isValid?`${this.s.toFormat(s)}${f}${this.e.toFormat(s)}`:Mn}toDuration(s,f){return this.isValid?this.e.diff(this.s,s,f):$e.invalid(this.invalidReason)}mapEndpoints(s){return Je.fromDateTimes(s(this.s),s(this.e))}}class Gn{static hasDST(s=Ne.defaultZone){const f=ke.now().setZone(s).set({month:12});return!s.isUniversal&&f.offset!==f.set({month:6}).offset}static isValidIANAZone(s){return ue.isValidZone(s)}static normalizeZone(s){return ct(s,Ne.defaultZone)}static getStartOfWeek({locale:s=null,locObj:f=null}={}){return(f||fe.create(s)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:s=null,locObj:f=null}={}){return(f||fe.create(s)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:s=null,locObj:f=null}={}){return(f||fe.create(s)).getWeekendDays().slice()}static months(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null,outputCalendar:I="gregory"}={}){return(w||fe.create(f,g,I)).months(s)}static monthsFormat(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null,outputCalendar:I="gregory"}={}){return(w||fe.create(f,g,I)).months(s,!0)}static weekdays(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null}={}){return(w||fe.create(f,g,null)).weekdays(s)}static weekdaysFormat(s="long",{locale:f=null,numberingSystem:g=null,locObj:w=null}={}){return(w||fe.create(f,g,null)).weekdays(s,!0)}static meridiems({locale:s=null}={}){return fe.create(s).meridiems()}static eras(s="short",{locale:f=null}={}){return fe.create(f,null,"gregory").eras(s)}static features(){return{relative:zn(),localeWeek:Wn()}}}function ti(p,s){const f=w=>w.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),g=f(s)-f(p);return Math.floor($e.fromMillis(g).as("days"))}function Cu(p,s,f){const g=[["years",(N,X)=>X.year-N.year],["quarters",(N,X)=>X.quarter-N.quarter+(X.year-N.year)*4],["months",(N,X)=>X.month-N.month+(X.year-N.year)*12],["weeks",(N,X)=>{const xe=ti(N,X);return(xe-xe%7)/7}],["days",ti]],w={},I=p;let F,L;for(const[N,X]of g)f.indexOf(N)>=0&&(F=N,w[N]=X(p,s),L=I.plus(w),L>s?(w[N]--,p=I.plus(w),p>s&&(L=p,w[N]--,p=I.plus(w))):p=L);return[p,w,L,F]}function Tu(p,s,f,g){let[w,I,F,L]=Cu(p,s,f);const N=s-w,X=f.filter(je=>["hours","minutes","seconds","milliseconds"].indexOf(je)>=0);X.length===0&&(F<s&&(F=w.plus({[L]:1})),F!==w&&(I[L]=(I[L]||0)+N/(F-w)));const xe=$e.fromObject(I,g);return X.length>0?$e.fromMillis(N,g).shiftTo(...X).plus(xe):xe}const ju="missing Intl.DateTimeFormat.formatToParts support";function _e(p,s=f=>f){return{regex:p,deser:([f])=>s(vt(f))}}const ni="[ ]",ri=new RegExp(ni,"g");function Mu(p){return p.replace(/\./g,"\\.?").replace(ri,ni)}function si(p){return p.replace(/\./g,"").replace(ri," ").toLowerCase()}function Ft(p,s){return p===null?null:{regex:RegExp(p.map(Mu).join("|")),deser:([f])=>p.findIndex(g=>si(f)===si(g))+s}}function oi(p,s){return{regex:p,deser:([,f,g])=>$r(f,g),groups:s}}function _r(p){return{regex:p,deser:([s])=>s}}function Ou(p){return p.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Eu(p,s){const f=Ie(s),g=Ie(s,"{2}"),w=Ie(s,"{3}"),I=Ie(s,"{4}"),F=Ie(s,"{6}"),L=Ie(s,"{1,2}"),N=Ie(s,"{1,3}"),X=Ie(s,"{1,6}"),xe=Ie(s,"{1,9}"),je=Ie(s,"{2,4}"),Be=Ie(s,"{4,6}"),Se=Wt=>({regex:RegExp(Ou(Wt.val)),deser:([En])=>En,literal:!0}),Lt=(Wt=>{if(p.literal)return Se(Wt);switch(Wt.val){case"G":return Ft(s.eras("short"),0);case"GG":return Ft(s.eras("long"),0);case"y":return _e(X);case"yy":return _e(je,ps);case"yyyy":return _e(I);case"yyyyy":return _e(Be);case"yyyyyy":return _e(F);case"M":return _e(L);case"MM":return _e(g);case"MMM":return Ft(s.months("short",!0),1);case"MMMM":return Ft(s.months("long",!0),1);case"L":return _e(L);case"LL":return _e(g);case"LLL":return Ft(s.months("short",!1),1);case"LLLL":return Ft(s.months("long",!1),1);case"d":return _e(L);case"dd":return _e(g);case"o":return _e(N);case"ooo":return _e(w);case"HH":return _e(g);case"H":return _e(L);case"hh":return _e(g);case"h":return _e(L);case"mm":return _e(g);case"m":return _e(L);case"q":return _e(L);case"qq":return _e(g);case"s":return _e(L);case"ss":return _e(g);case"S":return _e(N);case"SSS":return _e(w);case"u":return _r(xe);case"uu":return _r(L);case"uuu":return _e(f);case"a":return Ft(s.meridiems(),0);case"kkkk":return _e(I);case"kk":return _e(je,ps);case"W":return _e(L);case"WW":return _e(g);case"E":case"c":return _e(f);case"EEE":return Ft(s.weekdays("short",!1),1);case"EEEE":return Ft(s.weekdays("long",!1),1);case"ccc":return Ft(s.weekdays("short",!0),1);case"cccc":return Ft(s.weekdays("long",!0),1);case"Z":case"ZZ":return oi(new RegExp(`([+-]${L.source})(?::(${g.source}))?`),2);case"ZZZ":return oi(new RegExp(`([+-]${L.source})(${g.source})?`),2);case"z":return _r(/[a-z_+-/]{1,256}?/i);case" ":return _r(/[^\S\n\r]/);default:return Se(Wt)}})(p)||{invalidReason:ju};return Lt.token=p,Lt}const Iu={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 Du(p,s,f){const{type:g,value:w}=p;if(g==="literal"){const N=/^\s+$/.test(w);return{literal:!N,val:N?" ":w}}const I=s[g];let F=g;g==="hour"&&(s.hour12!=null?F=s.hour12?"hour12":"hour24":s.hourCycle!=null?s.hourCycle==="h11"||s.hourCycle==="h12"?F="hour12":F="hour24":F=f.hour12?"hour12":"hour24");let L=Iu[F];if(typeof L=="object"&&(L=L[I]),L)return{literal:!1,val:L}}function Au(p){return[`^${p.map(f=>f.regex).reduce((f,g)=>`${f}(${g.source})`,"")}$`,p]}function Ru(p,s,f){const g=p.match(s);if(g){const w={};let I=1;for(const F in f)if(gt(f,F)){const L=f[F],N=L.groups?L.groups+1:1;!L.literal&&L.token&&(w[L.token.val[0]]=L.deser(g.slice(I,I+N))),I+=N}return[g,w]}else return[g,{}]}function $u(p){const s=I=>{switch(I){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 f=null,g;return ee(p.z)||(f=ue.create(p.z)),ee(p.Z)||(f||(f=new ze(p.Z)),g=p.Z),ee(p.q)||(p.M=(p.q-1)*3+1),ee(p.h)||(p.h<12&&p.a===1?p.h+=12:p.h===12&&p.a===0&&(p.h=0)),p.G===0&&p.y&&(p.y=-p.y),ee(p.u)||(p.S=hs(p.u)),[Object.keys(p).reduce((I,F)=>{const L=s(F);return L&&(I[L]=p[F]),I},{}),f,g]}let xs=null;function Fu(){return xs||(xs=ke.fromMillis(1555555555555)),xs}function Lu(p,s){if(p.literal)return p;const f=ft.macroTokenToFormatOpts(p.val),g=ci(f,s);return g==null||g.includes(void 0)?p:g}function ii(p,s){return Array.prototype.concat(...p.map(f=>Lu(f,s)))}class ai{constructor(s,f){if(this.locale=s,this.format=f,this.tokens=ii(ft.parseFormat(f),s),this.units=this.tokens.map(g=>Eu(g,s)),this.disqualifyingUnit=this.units.find(g=>g.invalidReason),!this.disqualifyingUnit){const[g,w]=Au(this.units);this.regex=RegExp(g,"i"),this.handlers=w}}explainFromTokens(s){if(this.isValid){const[f,g]=Ru(s,this.regex,this.handlers),[w,I,F]=g?$u(g):[null,null,void 0];if(gt(g,"a")&>(g,"H"))throw new i("Can't include meridiem when specifying 24-hour format");return{input:s,tokens:this.tokens,regex:this.regex,rawMatches:f,matches:g,result:w,zone:I,specificOffset:F}}else return{input:s,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function li(p,s,f){return new ai(p,f).explainFromTokens(s)}function _u(p,s,f){const{result:g,zone:w,specificOffset:I,invalidReason:F}=li(p,s,f);return[g,w,I,F]}function ci(p,s){if(!p)return null;const g=ft.create(s,p).dtFormatter(Fu()),w=g.formatToParts(),I=g.resolvedOptions();return w.map(F=>Du(F,p,I))}const vs="Invalid DateTime",ui=864e13;function Yn(p){return new ut("unsupported zone",`the zone "${p.name}" is not supported`)}function bs(p){return p.weekData===null&&(p.weekData=Xe(p.c)),p.weekData}function ws(p){return p.localWeekData===null&&(p.localWeekData=Xe(p.c,p.loc.getMinDaysInFirstWeek(),p.loc.getStartOfWeek())),p.localWeekData}function on(p,s){const f={ts:p.ts,zone:p.zone,c:p.c,o:p.o,loc:p.loc,invalid:p.invalid};return new ke({...f,...s,old:f})}function di(p,s,f){let g=p-s*60*1e3;const w=f.offset(g);if(s===w)return[g,s];g-=(w-s)*60*1e3;const I=f.offset(g);return w===I?[g,w]:[p-Math.min(w,I)*60*1e3,Math.max(w,I)]}function Nr(p,s){p+=s*60*1e3;const f=new Date(p);return{year:f.getUTCFullYear(),month:f.getUTCMonth()+1,day:f.getUTCDate(),hour:f.getUTCHours(),minute:f.getUTCMinutes(),second:f.getUTCSeconds(),millisecond:f.getUTCMilliseconds()}}function Pr(p,s,f){return di(Rr(p),s,f)}function hi(p,s){const f=p.o,g=p.c.year+Math.trunc(s.years),w=p.c.month+Math.trunc(s.months)+Math.trunc(s.quarters)*3,I={...p.c,year:g,month:w,day:Math.min(p.c.day,Ar(g,w))+Math.trunc(s.days)+Math.trunc(s.weeks)*7},F=$e.fromObject({years:s.years-Math.trunc(s.years),quarters:s.quarters-Math.trunc(s.quarters),months:s.months-Math.trunc(s.months),weeks:s.weeks-Math.trunc(s.weeks),days:s.days-Math.trunc(s.days),hours:s.hours,minutes:s.minutes,seconds:s.seconds,milliseconds:s.milliseconds}).as("milliseconds"),L=Rr(I);let[N,X]=di(L,f,p.zone);return F!==0&&(N+=F,X=p.zone.offset(N)),{ts:N,o:X}}function On(p,s,f,g,w,I){const{setZone:F,zone:L}=f;if(p&&Object.keys(p).length!==0||s){const N=s||L,X=ke.fromObject(p,{...f,zone:N,specificOffset:I});return F?X:X.setZone(L)}else return ke.invalid(new ut("unparsable",`the input "${w}" can't be parsed as ${g}`))}function zr(p,s,f=!0){return p.isValid?ft.create(fe.create("en-US"),{allowZ:f,forceSimple:!0}).formatDateTimeFromString(p,s):null}function Ss(p,s,f){const g=p.c.year>9999||p.c.year<0;let w="";if(g&&p.c.year>=0&&(w+="+"),w+=ot(p.c.year,g?6:4),f==="year")return w;if(s){if(w+="-",w+=ot(p.c.month),f==="month")return w;w+="-"}else if(w+=ot(p.c.month),f==="month")return w;return w+=ot(p.c.day),w}function fi(p,s,f,g,w,I,F){let L=!f||p.c.millisecond!==0||p.c.second!==0,N="";switch(F){case"day":case"month":case"year":break;default:if(N+=ot(p.c.hour),F==="hour")break;if(s){if(N+=":",N+=ot(p.c.minute),F==="minute")break;L&&(N+=":",N+=ot(p.c.second))}else{if(N+=ot(p.c.minute),F==="minute")break;L&&(N+=ot(p.c.second))}if(F==="second")break;L&&(!g||p.c.millisecond!==0)&&(N+=".",N+=ot(p.c.millisecond,3))}return w&&(p.isOffsetFixed&&p.offset===0&&!I?N+="Z":p.o<0?(N+="-",N+=ot(Math.trunc(-p.o/60)),N+=":",N+=ot(Math.trunc(-p.o%60))):(N+="+",N+=ot(Math.trunc(p.o/60)),N+=":",N+=ot(Math.trunc(p.o%60)))),I&&(N+="["+p.zone.ianaName+"]"),N}const pi={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Nu={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Pu={ordinal:1,hour:0,minute:0,second:0,millisecond:0},Wr=["year","month","day","hour","minute","second","millisecond"],zu=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],Wu=["year","ordinal","hour","minute","second","millisecond"];function qr(p){const s={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"}[p.toLowerCase()];if(!s)throw new l(p);return s}function mi(p){switch(p.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return qr(p)}}function qu(p){if(Kn===void 0&&(Kn=Ne.now()),p.type!=="iana")return p.offset(Kn);const s=p.name;let f=ks.get(s);return f===void 0&&(f=p.offset(Kn),ks.set(s,f)),f}function gi(p,s){const f=ct(s.zone,Ne.defaultZone);if(!f.isValid)return ke.invalid(Yn(f));const g=fe.fromObject(s);let w,I;if(ee(p.year))w=Ne.now();else{for(const N of Wr)ee(p[N])&&(p[N]=pi[N]);const F=le(p)||ve(p);if(F)return ke.invalid(F);const L=qu(f);[w,I]=Pr(p,L,f)}return new ke({ts:w,zone:f,loc:g,o:I})}function yi(p,s,f){const g=ee(f.round)?!0:f.round,w=ee(f.rounding)?"trunc":f.rounding,I=(L,N)=>(L=fs(L,g||f.calendary?0:2,f.calendary?"round":w),s.loc.clone(f).relFormatter(f).format(L,N)),F=L=>f.calendary?s.hasSame(p,L)?0:s.startOf(L).diff(p.startOf(L),L).get(L):s.diff(p,L).get(L);if(f.unit)return I(F(f.unit),f.unit);for(const L of f.units){const N=F(L);if(Math.abs(N)>=1)return I(N,L)}return I(p>s?-0:0,f.units[f.units.length-1])}function xi(p){let s={},f;return p.length>0&&typeof p[p.length-1]=="object"?(s=p[p.length-1],f=Array.from(p).slice(0,p.length-1)):f=Array.from(p),[s,f]}let Kn;const ks=new Map;class ke{constructor(s){const f=s.zone||Ne.defaultZone;let g=s.invalid||(Number.isNaN(s.ts)?new ut("invalid input"):null)||(f.isValid?null:Yn(f));this.ts=ee(s.ts)?Ne.now():s.ts;let w=null,I=null;if(!g)if(s.old&&s.old.ts===this.ts&&s.old.zone.equals(f))[w,I]=[s.old.c,s.old.o];else{const L=qe(s.o)&&!s.old?s.o:f.offset(this.ts);w=Nr(this.ts,L),g=Number.isNaN(w.year)?new ut("invalid input"):null,w=g?null:w,I=g?null:L}this._zone=f,this.loc=s.loc||fe.create(),this.invalid=g,this.weekData=null,this.localWeekData=null,this.c=w,this.o=I,this.isLuxonDateTime=!0}static now(){return new ke({})}static local(){const[s,f]=xi(arguments),[g,w,I,F,L,N,X]=f;return gi({year:g,month:w,day:I,hour:F,minute:L,second:N,millisecond:X},s)}static utc(){const[s,f]=xi(arguments),[g,w,I,F,L,N,X]=f;return s.zone=ze.utcInstance,gi({year:g,month:w,day:I,hour:F,minute:L,second:N,millisecond:X},s)}static fromJSDate(s,f={}){const g=vn(s)?s.valueOf():NaN;if(Number.isNaN(g))return ke.invalid("invalid input");const w=ct(f.zone,Ne.defaultZone);return w.isValid?new ke({ts:g,zone:w,loc:fe.fromObject(f)}):ke.invalid(Yn(w))}static fromMillis(s,f={}){if(qe(s))return s<-ui||s>ui?ke.invalid("Timestamp out of range"):new ke({ts:s,zone:ct(f.zone,Ne.defaultZone),loc:fe.fromObject(f)});throw new a(`fromMillis requires a numerical input, but received a ${typeof s} with value ${s}`)}static fromSeconds(s,f={}){if(qe(s))return new ke({ts:s*1e3,zone:ct(f.zone,Ne.defaultZone),loc:fe.fromObject(f)});throw new a("fromSeconds requires a numerical input")}static fromObject(s,f={}){s=s||{};const g=ct(f.zone,Ne.defaultZone);if(!g.isValid)return ke.invalid(Yn(g));const w=fe.fromObject(f),I=Fr(s,mi),{minDaysInFirstWeek:F,startOfWeek:L}=nn(I,w),N=Ne.now(),X=ee(f.specificOffset)?g.offset(N):f.specificOffset,xe=!ee(I.ordinal),je=!ee(I.year),Be=!ee(I.month)||!ee(I.day),Se=je||Be,it=I.weekYear||I.weekNumber;if((Se||xe)&&it)throw new i("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(Be&&xe)throw new i("Can't mix ordinal dates with month/day");const Lt=it||I.weekday&&!Se;let Wt,En,Zn=Nr(N,X);Lt?(Wt=zu,En=Nu,Zn=Xe(Zn,F,L)):xe?(Wt=Wu,En=Pu,Zn=tn(Zn)):(Wt=Wr,En=pi);let vi=!1;for(const Jn of Wt){const Yu=I[Jn];ee(Yu)?vi?I[Jn]=En[Jn]:I[Jn]=Zn[Jn]:vi=!0}const Vu=Lt?G(I,F,L):xe?U(I):le(I),bi=Vu||ve(I);if(bi)return ke.invalid(bi);const Hu=Lt?$t(I,F,L):xe?Zt(I):I,[Uu,Gu]=Pr(Hu,X,g),Xn=new ke({ts:Uu,zone:g,o:Gu,loc:w});return I.weekday&&Se&&s.weekday!==Xn.weekday?ke.invalid("mismatched weekday",`you can't specify both a weekday of ${I.weekday} and a date of ${Xn.toISO()}`):Xn.isValid?Xn:ke.invalid(Xn.invalid)}static fromISO(s,f={}){const[g,w]=uu(s);return On(g,w,f,"ISO 8601",s)}static fromRFC2822(s,f={}){const[g,w]=du(s);return On(g,w,f,"RFC 2822",s)}static fromHTTP(s,f={}){const[g,w]=hu(s);return On(g,w,f,"HTTP",f)}static fromFormat(s,f,g={}){if(ee(s)||ee(f))throw new a("fromFormat requires an input string and a format");const{locale:w=null,numberingSystem:I=null}=g,F=fe.fromOpts({locale:w,numberingSystem:I,defaultToEN:!0}),[L,N,X,xe]=_u(F,s,f);return xe?ke.invalid(xe):On(L,N,g,`format ${f}`,s,X)}static fromString(s,f,g={}){return ke.fromFormat(s,f,g)}static fromSQL(s,f={}){const[g,w]=vu(s);return On(g,w,f,"SQL",s)}static invalid(s,f=null){if(!s)throw new a("need to specify a reason the DateTime is invalid");const g=s instanceof ut?s:new ut(s,f);if(Ne.throwOnInvalid)throw new n(g);return new ke({invalid:g})}static isDateTime(s){return s&&s.isLuxonDateTime||!1}static parseFormatForOpts(s,f={}){const g=ci(s,fe.fromObject(f));return g?g.map(w=>w?w.val:null).join(""):null}static expandFormat(s,f={}){return ii(ft.parseFormat(s),fe.fromObject(f)).map(w=>w.val).join("")}static resetCache(){Kn=void 0,ks.clear()}get(s){return this[s]}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?bs(this).weekYear:NaN}get weekNumber(){return this.isValid?bs(this).weekNumber:NaN}get weekday(){return this.isValid?bs(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?ws(this).weekday:NaN}get localWeekNumber(){return this.isValid?ws(this).weekNumber:NaN}get localWeekYear(){return this.isValid?ws(this).weekYear:NaN}get ordinal(){return this.isValid?tn(this.c).ordinal:NaN}get monthShort(){return this.isValid?Gn.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?Gn.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?Gn.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?Gn.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 s=864e5,f=6e4,g=Rr(this.c),w=this.zone.offset(g-s),I=this.zone.offset(g+s),F=this.zone.offset(g-w*f),L=this.zone.offset(g-I*f);if(F===L)return[this];const N=g-F*f,X=g-L*f,xe=Nr(N,F),je=Nr(X,L);return xe.hour===je.hour&&xe.minute===je.minute&&xe.second===je.second&&xe.millisecond===je.millisecond?[on(this,{ts:N}),on(this,{ts:X})]:[this]}get isInLeapYear(){return qn(this.year)}get daysInMonth(){return Ar(this.year,this.month)}get daysInYear(){return this.isValid?bn(this.year):NaN}get weeksInWeekYear(){return this.isValid?Bn(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?Bn(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(s={}){const{locale:f,numberingSystem:g,calendar:w}=ft.create(this.loc.clone(s),s).resolvedOptions(this);return{locale:f,numberingSystem:g,outputCalendar:w}}toUTC(s=0,f={}){return this.setZone(ze.instance(s),f)}toLocal(){return this.setZone(Ne.defaultZone)}setZone(s,{keepLocalTime:f=!1,keepCalendarTime:g=!1}={}){if(s=ct(s,Ne.defaultZone),s.equals(this.zone))return this;if(s.isValid){let w=this.ts;if(f||g){const I=s.offset(this.ts),F=this.toObject();[w]=Pr(F,I,s)}return on(this,{ts:w,zone:s})}else return ke.invalid(Yn(s))}reconfigure({locale:s,numberingSystem:f,outputCalendar:g}={}){const w=this.loc.clone({locale:s,numberingSystem:f,outputCalendar:g});return on(this,{loc:w})}setLocale(s){return this.reconfigure({locale:s})}set(s){if(!this.isValid)return this;const f=Fr(s,mi),{minDaysInFirstWeek:g,startOfWeek:w}=nn(f,this.loc),I=!ee(f.weekYear)||!ee(f.weekNumber)||!ee(f.weekday),F=!ee(f.ordinal),L=!ee(f.year),N=!ee(f.month)||!ee(f.day),X=L||N,xe=f.weekYear||f.weekNumber;if((X||F)&&xe)throw new i("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(N&&F)throw new i("Can't mix ordinal dates with month/day");let je;I?je=$t({...Xe(this.c,g,w),...f},g,w):ee(f.ordinal)?(je={...this.toObject(),...f},ee(f.day)&&(je.day=Math.min(Ar(je.year,je.month),je.day))):je=Zt({...tn(this.c),...f});const[Be,Se]=Pr(je,this.o,this.zone);return on(this,{ts:Be,o:Se})}plus(s){if(!this.isValid)return this;const f=$e.fromDurationLike(s);return on(this,hi(this,f))}minus(s){if(!this.isValid)return this;const f=$e.fromDurationLike(s).negate();return on(this,hi(this,f))}startOf(s,{useLocaleWeeks:f=!1}={}){if(!this.isValid)return this;const g={},w=$e.normalizeUnit(s);switch(w){case"years":g.month=1;case"quarters":case"months":g.day=1;case"weeks":case"days":g.hour=0;case"hours":g.minute=0;case"minutes":g.second=0;case"seconds":g.millisecond=0;break}if(w==="weeks")if(f){const I=this.loc.getStartOfWeek(),{weekday:F}=this;F<I&&(g.weekNumber=this.weekNumber-1),g.weekday=I}else g.weekday=1;if(w==="quarters"){const I=Math.ceil(this.month/3);g.month=(I-1)*3+1}return this.set(g)}endOf(s,f){return this.isValid?this.plus({[s]:1}).startOf(s,f).minus(1):this}toFormat(s,f={}){return this.isValid?ft.create(this.loc.redefaultToEN(f)).formatDateTimeFromString(this,s):vs}toLocaleString(s=b,f={}){return this.isValid?ft.create(this.loc.clone(f),s).formatDateTime(this):vs}toLocaleParts(s={}){return this.isValid?ft.create(this.loc.clone(s),s).formatDateTimeParts(this):[]}toISO({format:s="extended",suppressSeconds:f=!1,suppressMilliseconds:g=!1,includeOffset:w=!0,extendedZone:I=!1,precision:F="milliseconds"}={}){if(!this.isValid)return null;F=qr(F);const L=s==="extended";let N=Ss(this,L,F);return Wr.indexOf(F)>=3&&(N+="T"),N+=fi(this,L,f,g,w,I,F),N}toISODate({format:s="extended",precision:f="day"}={}){return this.isValid?Ss(this,s==="extended",qr(f)):null}toISOWeekDate(){return zr(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:s=!1,suppressSeconds:f=!1,includeOffset:g=!0,includePrefix:w=!1,extendedZone:I=!1,format:F="extended",precision:L="milliseconds"}={}){return this.isValid?(L=qr(L),(w&&Wr.indexOf(L)>=3?"T":"")+fi(this,F==="extended",f,s,g,I,L)):null}toRFC2822(){return zr(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return zr(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Ss(this,!0):null}toSQLTime({includeOffset:s=!0,includeZone:f=!1,includeOffsetSpace:g=!0}={}){let w="HH:mm:ss.SSS";return(f||s)&&(g&&(w+=" "),f?w+="z":s&&(w+="ZZ")),zr(this,w,!0)}toSQL(s={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(s)}`:null}toString(){return this.isValid?this.toISO():vs}[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(s={}){if(!this.isValid)return{};const f={...this.c};return s.includeConfig&&(f.outputCalendar=this.outputCalendar,f.numberingSystem=this.loc.numberingSystem,f.locale=this.loc.locale),f}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(s,f="milliseconds",g={}){if(!this.isValid||!s.isValid)return $e.invalid("created by diffing an invalid DateTime");const w={locale:this.locale,numberingSystem:this.numberingSystem,...g},I=Dr(f).map($e.normalizeUnit),F=s.valueOf()>this.valueOf(),L=F?this:s,N=F?s:this,X=Tu(L,N,I,w);return F?X.negate():X}diffNow(s="milliseconds",f={}){return this.diff(ke.now(),s,f)}until(s){return this.isValid?Je.fromDateTimes(this,s):this}hasSame(s,f,g){if(!this.isValid)return!1;const w=s.valueOf(),I=this.setZone(s.zone,{keepLocalTime:!0});return I.startOf(f,g)<=w&&w<=I.endOf(f,g)}equals(s){return this.isValid&&s.isValid&&this.valueOf()===s.valueOf()&&this.zone.equals(s.zone)&&this.loc.equals(s.loc)}toRelative(s={}){if(!this.isValid)return null;const f=s.base||ke.fromObject({},{zone:this.zone}),g=s.padding?this<f?-s.padding:s.padding:0;let w=["years","months","days","hours","minutes","seconds"],I=s.unit;return Array.isArray(s.unit)&&(w=s.unit,I=void 0),yi(f,this.plus(g),{...s,numeric:"always",units:w,unit:I})}toRelativeCalendar(s={}){return this.isValid?yi(s.base||ke.fromObject({},{zone:this.zone}),this,{...s,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...s){if(!s.every(ke.isDateTime))throw new a("min requires all arguments be DateTimes");return Ae(s,f=>f.valueOf(),Math.min)}static max(...s){if(!s.every(ke.isDateTime))throw new a("max requires all arguments be DateTimes");return Ae(s,f=>f.valueOf(),Math.max)}static fromFormatExplain(s,f,g={}){const{locale:w=null,numberingSystem:I=null}=g,F=fe.fromOpts({locale:w,numberingSystem:I,defaultToEN:!0});return li(F,s,f)}static fromStringExplain(s,f,g={}){return ke.fromFormatExplain(s,f,g)}static buildFormatParser(s,f={}){const{locale:g=null,numberingSystem:w=null}=f,I=fe.fromOpts({locale:g,numberingSystem:w,defaultToEN:!0});return new ai(I,s)}static fromFormatParser(s,f,g={}){if(ee(s)||ee(f))throw new a("fromFormatParser requires an input string and a format parser");const{locale:w=null,numberingSystem:I=null}=g,F=fe.fromOpts({locale:w,numberingSystem:I,defaultToEN:!0});if(!F.equals(f.locale))throw new a(`fromFormatParser called with a locale of ${F}, but the format parser was created for ${f.locale}`);const{result:L,zone:N,specificOffset:X,invalidReason:xe}=f.explainFromTokens(s);return xe?ke.invalid(xe):On(L,N,g,`format ${f.format}`,s,X)}static get DATE_SHORT(){return b}static get DATE_MED(){return x}static get DATE_MED_WITH_WEEKDAY(){return v}static get DATE_FULL(){return k}static get DATE_HUGE(){return C}static get TIME_SIMPLE(){return S}static get TIME_WITH_SECONDS(){return j}static get TIME_WITH_SHORT_OFFSET(){return M}static get TIME_WITH_LONG_OFFSET(){return O}static get TIME_24_SIMPLE(){return E}static get TIME_24_WITH_SECONDS(){return $}static get TIME_24_WITH_SHORT_OFFSET(){return P}static get TIME_24_WITH_LONG_OFFSET(){return A}static get DATETIME_SHORT(){return B}static get DATETIME_SHORT_WITH_SECONDS(){return D}static get DATETIME_MED(){return _}static get DATETIME_MED_WITH_SECONDS(){return V}static get DATETIME_MED_WITH_WEEKDAY(){return R}static get DATETIME_FULL(){return W}static get DATETIME_FULL_WITH_SECONDS(){return Z}static get DATETIME_HUGE(){return ne}static get DATETIME_HUGE_WITH_SECONDS(){return J}}function Qn(p){if(ke.isDateTime(p))return p;if(p&&p.valueOf&&qe(p.valueOf()))return ke.fromJSDate(p);if(p&&typeof p=="object")return ke.fromObject(p);throw new a(`Unknown datetime argument: ${p}, of type ${typeof p}`)}const Bu="3.7.2";return bt.DateTime=ke,bt.Duration=$e,bt.FixedOffsetZone=ze,bt.IANAZone=ue,bt.Info=Gn,bt.Interval=Je,bt.InvalidZone=lt,bt.Settings=Ne,bt.SystemZone=re,bt.VERSION=Bu,bt.Zone=H,bt}var Zi;function lo(){return Zi||(Zi=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CronDate=e.DAYS_IN_MONTH=e.DateMathOp=e.TimeUnit=void 0;const n=kf();var r;(function(l){l.Second="Second",l.Minute="Minute",l.Hour="Hour",l.Day="Day",l.Month="Month",l.Year="Year"})(r||(e.TimeUnit=r={}));var o;(function(l){l.Add="Add",l.Subtract="Subtract"})(o||(e.DateMathOp=o={})),e.DAYS_IN_MONTH=Object.freeze([31,29,31,30,31,30,31,31,30,31,30,31]);class i{#e;#n=null;#o=null;constructor(a,u){const d={zone:u};if(a?a instanceof i?(this.#e=a.#e,this.#n=a.#n,this.#o=a.#o):a instanceof Date?this.#e=n.DateTime.fromJSDate(a,d):typeof a=="number"?this.#e=n.DateTime.fromMillis(a,d):(this.#e=n.DateTime.fromISO(a,d),this.#e.isValid||(this.#e=n.DateTime.fromRFC2822(a,d)),this.#e.isValid||(this.#e=n.DateTime.fromSQL(a,d)),this.#e.isValid||(this.#e=n.DateTime.fromFormat(a,"EEE, d MMM yyyy HH:mm:ss",d))):this.#e=n.DateTime.local(),!this.#e.isValid)throw new Error(`CronDate: unhandled timestamp: ${a}`);u&&u!==this.#e.zoneName&&(this.#e=this.#e.setZone(u))}static#s(a){return a%4===0&&a%100!==0||a%400===0}get dstStart(){return this.#n}set dstStart(a){this.#n=a}get dstEnd(){return this.#o}set dstEnd(a){this.#o=a}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(a){switch(a){case r.Year:return this.addYear();case r.Month:return this.addMonth();case r.Day:return this.addDay();case r.Hour:return this.addHour();case r.Minute:return this.addMinute();case r.Second:return this.addSecond()}}subtractUnit(a){switch(a){case r.Year:return this.subtractYear();case r.Month:return this.subtractMonth();case r.Day:return this.subtractDay();case r.Hour:return this.subtractHour();case r.Minute:return this.subtractMinute();case r.Second:return this.subtractSecond()}}invokeDateOperation(a,u){if(a===o.Add){this.addUnit(u);return}if(a===o.Subtract){this.subtractUnit(u);return}throw new Error(`Invalid verb: ${a}`)}getDate(){return this.#e.day}getFullYear(){return this.#e.year}getDay(){const a=this.#e.weekday;return a===7?0:a}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 a=this.#r().weekday;return a===7?0:a}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(a){this.#e=this.#e.set({day:a})}setFullYear(a){this.#e=this.#e.set({year:a})}setDay(a){this.#e=this.#e.set({weekday:a})}setMonth(a){this.#e=this.#e.set({month:a+1})}setHours(a){this.#e=this.#e.set({hour:a})}setMinutes(a){this.#e=this.#e.set({minute:a})}setSeconds(a){this.#e=this.#e.set({second:a})}setMilliseconds(a){this.#e=this.#e.set({millisecond:a})}toString(){return this.toDate().toString()}toDate(){return this.#e.toJSDate()}isLastDayOfMonth(){const{day:a,month:u}=this.#e;if(u===2){const d=i.#s(this.#e.year);return a===e.DAYS_IN_MONTH[u-1]-(d?0:1)}return a===e.DAYS_IN_MONTH[u-1]}isLastWeekdayOfMonth(){const{day:a,month:u}=this.#e;let d;return u===2?d=e.DAYS_IN_MONTH[u-1]-(i.#s(this.#e.year)?0:1):d=e.DAYS_IN_MONTH[u-1],a>d-7}applyDateOperation(a,u,d){if(u===r.Month||u===r.Day){this.invokeDateOperation(a,u);return}const h=this.getHours();this.invokeDateOperation(a,u);const y=this.getHours(),b=y-h;b===2?d!==24&&(this.dstStart=h+1):b===0&&this.getMinutes()===0&&this.getSeconds()===0&&d!==24&&(this.dstEnd=y)}#r(){return this.#e.toUTC()}}e.CronDate=i,e.default=i})(Es)),Es}var Xi;function Cf(){if(Xi)return ar;Xi=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.CronMonth=void 0;const e=lo(),n=pn(),r=1,o=12,i=Object.freeze([]);let l=class extends n.CronField{static get min(){return r}static get max(){return o}static get chars(){return i}static get daysInMonth(){return e.DAYS_IN_MONTH}constructor(u,d){super(u,d),this.validate()}get values(){return super.values}};return ar.CronMonth=l,ar}var lr={},Ji;function Tf(){if(Ji)return lr;Ji=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.CronSecond=void 0;const e=pn(),n=0,r=59,o=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return o}constructor(a,u){super(a,u),this.validate()}get values(){return super.values}};return lr.CronSecond=i,lr}var ea;function co(){return ea||(ea=1,(function(e){var n=ln&&ln.__createBinding||(Object.create?(function(o,i,l,a){a===void 0&&(a=l);var u=Object.getOwnPropertyDescriptor(i,l);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[l]}}),Object.defineProperty(o,a,u)}):(function(o,i,l,a){a===void 0&&(a=l),o[a]=i[l]})),r=ln&&ln.__exportStar||function(o,i){for(var l in o)l!=="default"&&!Object.prototype.hasOwnProperty.call(i,l)&&n(i,o,l)};Object.defineProperty(e,"__esModule",{value:!0}),r(xf(),e),r(vf(),e),r(bf(),e),r(pn(),e),r(wf(),e),r(Sf(),e),r(Cf(),e),r(Tf(),e)})(ln)),ln}var ta;function ul(){if(ta)return tr;ta=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.CronFieldCollection=void 0;const e=co();let n=class gr{#e;#n;#o;#s;#r;#t;static from(o,i){return new gr({second:this.resolveField(e.CronSecond,o.second,i.second),minute:this.resolveField(e.CronMinute,o.minute,i.minute),hour:this.resolveField(e.CronHour,o.hour,i.hour),dayOfMonth:this.resolveField(e.CronDayOfMonth,o.dayOfMonth,i.dayOfMonth),month:this.resolveField(e.CronMonth,o.month,i.month),dayOfWeek:this.resolveField(e.CronDayOfWeek,o.dayOfWeek,i.dayOfWeek)})}static resolveField(o,i,l){return l?l instanceof e.CronField?l:new o(l):i}constructor({second:o,minute:i,hour:l,dayOfMonth:a,month:u,dayOfWeek:d}){if(!o)throw new Error("Validation error, Field second is missing");if(!i)throw new Error("Validation error, Field minute is missing");if(!l)throw new Error("Validation error, Field hour is missing");if(!a)throw new Error("Validation error, Field dayOfMonth is missing");if(!u)throw new Error("Validation error, Field month is missing");if(!d)throw new Error("Validation error, Field dayOfWeek is missing");if(u.values.length===1&&!a.hasLastChar&&d.isWildcard&&!(parseInt(a.values[0],10)<=e.CronMonth.daysInMonth[u.values[0]-1]))throw new Error("Invalid explicit day of month definition");this.#e=o,this.#n=i,this.#o=l,this.#r=u,this.#t=d,this.#s=a}get second(){return this.#e}get minute(){return this.#n}get hour(){return this.#o}get dayOfMonth(){return this.#s}get month(){return this.#r}get dayOfWeek(){return this.#t}static compactField(o){if(o.length===0)return[];const i=[];let l;return o.forEach((a,u,d)=>{if(l===void 0){l={start:a,count:1};return}const h=d[u-1]||l.start,y=d[u+1];if(a==="L"||a==="W"){i.push(l),i.push({start:a,count:1}),l=void 0;return}if(l.step===void 0&&y!==void 0){const b=a-h,x=y-a;if(b<=x){l={...l,count:2,end:a,step:b};return}l.step=1}a-(l.end??0)===l.step?(l.count++,l.end=a):(l.count===1?i.push({start:l.start,count:1}):l.count===2?(i.push({start:l.start,count:1}),i.push({start:l.end??h,count:1})):i.push(l),l={start:a,count:1})}),l&&i.push(l),i}static#c(o,i,l){const a=i.step;return a?a===1&&i.start===o.min&&i.end&&i.end>=l?o.hasQuestionMarkChar?"?":"*":a!==1&&i.start===o.min&&i.end&&i.end>=l-a+1?`*/${a}`:null:null}static#l(o,i){const l=o.step;if(l===1)return`${o.start}-${o.end}`;const a=o.start===0?o.count-1:o.count;if(!l)throw new Error("Unexpected range step");if(!o.end)throw new Error("Unexpected range end");if(l*a>o.end){const u=(h,y)=>{if(typeof o.start!="number")throw new Error("Unexpected range start");return y%l===0?o.start+y:null};if(typeof o.start!="number")throw new Error("Unexpected range start");const d={length:o.end-o.start+1};return Array.from(d,u).filter(h=>h!==null).join(",")}return o.end===i-l+1?`${o.start}/${l}`:`${o.start}-${o.end}/${l}`}stringifyField(o){let i=o.max,l=o.values;if(o instanceof e.CronDayOfWeek){i=6;const u=this.#t.values;l=u[u.length-1]===7?u.slice(0,-1):u}o instanceof e.CronDayOfMonth&&(i=this.#r.values.length===1?e.CronMonth.daysInMonth[this.#r.values[0]-1]:o.max);const a=gr.compactField(l);if(a.length===1){const u=gr.#c(o,a[0],i);if(u)return u}return a.map(u=>{const d=u.count===1?u.start.toString():gr.#l(u,i);return o instanceof e.CronDayOfWeek&&o.nthDay>0?`${d}#${o.nthDay}`:d}).join(",")}stringify(o=!1){const i=[];return o&&i.push(this.stringifyField(this.#e)),i.push(this.stringifyField(this.#n),this.stringifyField(this.#o),this.stringifyField(this.#s),this.stringifyField(this.#r),this.stringifyField(this.#t)),i.join(" ")}serialize(){return{second:this.#e.serialize(),minute:this.#n.serialize(),hour:this.#o.serialize(),dayOfMonth:this.#s.serialize(),month:this.#r.serialize(),dayOfWeek:this.#t.serialize()}}};return tr.CronFieldCollection=n,tr}var Is={},na;function dl(){return na||(na=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CronExpression=e.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE=e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE=void 0;const n=lo();e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE="Out of the time span range",e.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE="Invalid expression, loop limit exceeded";const r=1e4;class o{#e;#n;#o;#s;#r;#t;#c=null;#l=!1;constructor(l,a){this.#e=a,this.#n=a.tz,this.#s=a.startDate?new n.CronDate(a.startDate,this.#n):null,this.#r=a.endDate?new n.CronDate(a.endDate,this.#n):null;let u=a.currentDate??a.startDate;if(u){const d=new n.CronDate(u,this.#n);this.#s&&d.getTime()<this.#s.getTime()?u=this.#s:this.#r&&d.getTime()>this.#r.getTime()&&(u=this.#r)}this.#o=new n.CronDate(u,this.#n),this.#t=l}get fields(){return this.#t}static fieldsToExpression(l,a){return new o(l,a||{})}static#i(l,a){return a.some(u=>u===l)}#a(l,a){return l[a?l.length-1:0]}#d(l){const a=`${l.getFullYear()}-${l.getMonth()+1}-${l.getDate()}`;if(this.#c===a)return this.#l;const u=new n.CronDate(l);u.setStartOfDay();const d=new n.CronDate(l);return d.setEndOfDay(),this.#c=a,this.#l=u.getUTCOffset()!==d.getUTCOffset(),this.#l}#h(l,a,u){const d=this.#t.second.values,h=l.getSeconds(),y=this.#t.second.findNearestValue(h,u);if(y!==null){l.setSeconds(y);return}l.applyDateOperation(a,n.TimeUnit.Minute,this.#t.hour.values.length),l.setSeconds(this.#a(d,u))}#p(l,a,u){const d=this.#t.minute.values,h=this.#t.second.values,y=l.getMinutes(),b=this.#t.minute.findNearestValue(y,u);if(b!==null){l.setMinutes(b),l.setSeconds(this.#a(h,u));return}l.applyDateOperation(a,n.TimeUnit.Hour,this.#t.hour.values.length),l.setMinutes(this.#a(d,u)),l.setSeconds(this.#a(h,u))}static#m(l,a){const u=a.isLastWeekdayOfMonth();return l.some(d=>{const h=parseInt(d.toString().charAt(0),10)%7;if(Number.isNaN(h))throw new Error(`Invalid last weekday of the month expression: ${d}`);return a.getDay()===h&&u})}next(){return this.#u()}prev(){return this.#u(!0)}hasNext(){const l=this.#o;try{return this.#u(),!0}catch{return!1}finally{this.#o=l}}hasPrev(){const l=this.#o;try{return this.#u(!0),!0}catch{return!1}finally{this.#o=l}}take(l){const a=[];if(l>=0)for(let u=0;u<l;u++)try{a.push(this.next())}catch{return a}else for(let u=0;u>l;u--)try{a.push(this.prev())}catch{return a}return a}reset(l){this.#o=new n.CronDate(l||this.#e.currentDate,this.#n)}stringify(l=!1){return this.#t.stringify(l)}includesDate(l){const{second:a,minute:u,hour:d,month:h}=this.#t,y=new n.CronDate(l,this.#n);return!(!a.values.includes(y.getSeconds())||!u.values.includes(y.getMinutes())||!d.values.includes(y.getHours())||!h.values.includes(y.getMonth()+1)||!this.#f(y)||this.#t.dayOfWeek.nthDay>0&&Math.ceil(y.getDate()/7)!==this.#t.dayOfWeek.nthDay)}toString(){return this.#e.expression||this.stringify(!0)}#f(l){const a=this.#t.dayOfMonth.isWildcard,u=!a,d=this.#t.dayOfWeek.isWildcard,h=!d,y=o.#i(l.getDate(),this.#t.dayOfMonth.values)||this.#t.dayOfMonth.hasLastChar&&l.isLastDayOfMonth(),b=o.#i(l.getDay(),this.#t.dayOfWeek.values)||this.#t.dayOfWeek.hasLastChar&&o.#m(this.#t.dayOfWeek.values,l);return!!(u&&h&&(y||b)||y&&!h||a&&!d&&b)}#g(l,a,u){const d=this.#t.hour.values,h=d,y=l.getHours(),b=o.#i(y,d),x=l.dstEnd===y;if(l.dstStart!==null&&l.dstStart===y-1&&o.#i(l.dstStart,d))return!0;if(x&&!u)return l.dstEnd=null,l.applyDateOperation(n.DateMathOp.Add,n.TimeUnit.Hour,h.length),!1;if(b)return!0;l.dstStart=null;const v=this.#t.hour.findNearestValue(y,u);if(v===null)return l.applyDateOperation(a,n.TimeUnit.Day,h.length),!1;if(this.#d(l)){const k=u?y-v:v-y;for(let C=0;C<k&&(l.applyDateOperation(a,n.TimeUnit.Hour,h.length),!(!u&&l.getHours()>=v||u&&l.getHours()<=v));C++);}else l.setHours(v);return l.setMinutes(this.#a(this.#t.minute.values,u)),l.setSeconds(this.#a(this.#t.second.values,u)),!1}#y(l){if(!this.#s&&!this.#r)return;const a=l.getTime();if(this.#s&&a<this.#s.getTime())throw new Error(e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE);if(this.#r&&a>this.#r.getTime())throw new Error(e.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE)}#u(l=!1){const a=l?n.DateMathOp.Subtract:n.DateMathOp.Add,u=new n.CronDate(this.#o),d=u.getTime();let h=0;for(;++h<r;){if(this.#y(u),!this.#f(u)){u.applyDateOperation(a,n.TimeUnit.Day,this.#t.hour.values.length);continue}if(!(this.#t.dayOfWeek.nthDay<=0||Math.ceil(u.getDate()/7)===this.#t.dayOfWeek.nthDay)){u.applyDateOperation(a,n.TimeUnit.Day,this.#t.hour.values.length);continue}if(!o.#i(u.getMonth()+1,this.#t.month.values)){u.applyDateOperation(a,n.TimeUnit.Month,this.#t.hour.values.length);continue}if(this.#g(u,a,l)){if(!o.#i(u.getMinutes(),this.#t.minute.values)){this.#p(u,a,l);continue}if(!o.#i(u.getSeconds(),this.#t.second.values)){this.#h(u,a,l);continue}if(d===u.getTime()){(a==="Add"||u.getMilliseconds()===0)&&u.applyDateOperation(a,n.TimeUnit.Second,this.#t.hour.values.length);continue}break}}if(h>r)throw new Error(e.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE);return u.getMilliseconds()!==0&&u.setMilliseconds(0),this.#o=u,u}[Symbol.iterator](){return{next:()=>{try{return{value:this.#u(),done:!1}}catch{return{value:void 0,done:!0}}}}}}e.CronExpression=o,e.default=o})(Is)),Is}var Br={},ra;function jf(){if(ra)return Br;ra=1,Object.defineProperty(Br,"__esModule",{value:!0}),Br.seededRandom=r;function e(o){let i=2166136261;for(let l=0;l<o.length;l++)i^=o.charCodeAt(l),i=Math.imul(i,16777619);return()=>i>>>0}function n(o){return()=>{let i=o+=1831565813;return i=Math.imul(i^i>>>15,i|1),i^=i+Math.imul(i^i>>>7,i|61),((i^i>>>14)>>>0)/4294967296}}function r(o){const i=o?e(o)():Math.floor(Math.random()*1e10);return n(i)}return Br}var sa;function Qs(){if(sa)return Tt;sa=1,Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.CronExpressionParser=Tt.DayOfWeek=Tt.Months=Tt.CronUnit=Tt.PredefinedExpressions=void 0;const e=ul(),n=dl(),r=jf(),o=co();var i;(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"})(i||(Tt.PredefinedExpressions=i={}));var l;(function(h){h.Second="Second",h.Minute="Minute",h.Hour="Hour",h.DayOfMonth="DayOfMonth",h.Month="Month",h.DayOfWeek="DayOfWeek"})(l||(Tt.CronUnit=l={}));var a;(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"})(a||(Tt.Months=a={}));var u;(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"})(u||(Tt.DayOfWeek=u={}));let d=class jt{static parse(y,b={}){const{strict:x=!1,hashSeed:v}=b,k=(0,r.seededRandom)(v);y=i[y]||y;const C=jt.#e(y,x);if(!(C.dayOfMonth==="*"||C.dayOfWeek==="*"||!x))throw new Error("Cannot use both dayOfMonth and dayOfWeek together in strict mode!");const S=jt.#n(l.Second,C.second,o.CronSecond.constraints,k),j=jt.#n(l.Minute,C.minute,o.CronMinute.constraints,k),M=jt.#n(l.Hour,C.hour,o.CronHour.constraints,k),O=jt.#n(l.Month,C.month,o.CronMonth.constraints,k),E=jt.#n(l.DayOfMonth,C.dayOfMonth,o.CronDayOfMonth.constraints,k),{dayOfWeek:$,nthDayOfWeek:P}=jt.#d(C.dayOfWeek),A=jt.#n(l.DayOfWeek,$,o.CronDayOfWeek.constraints,k),B=new e.CronFieldCollection({second:new o.CronSecond(S,{rawValue:C.second}),minute:new o.CronMinute(j,{rawValue:C.minute}),hour:new o.CronHour(M,{rawValue:C.hour}),dayOfMonth:new o.CronDayOfMonth(E,{rawValue:C.dayOfMonth}),month:new o.CronMonth(O,{rawValue:C.month}),dayOfWeek:new o.CronDayOfWeek(A,{rawValue:C.dayOfWeek,nthDayOfWeek:P})});return new n.CronExpression(B,{...b,expression:y})}static#e(y,b){if(b&&!y.length)throw new Error("Invalid cron expression");y=y||"0 * * * * *";const x=y.trim().split(/\s+/);if(b&&x.length<6)throw new Error("Invalid cron expression, expected 6 fields");if(x.length>6)throw new Error("Invalid cron expression, too many fields");const v=["*","*","*","*","*","0"];x.length<v.length&&x.unshift(...v.slice(x.length));const[k,C,S,j,M,O]=x;return{second:k,minute:C,hour:S,dayOfMonth:j,month:M,dayOfWeek:O}}static#n(y,b,x,v){if((y===l.Month||y===l.DayOfWeek)&&(b=b.replace(/[a-z]{3}/gi,k=>{k=k.toLowerCase();const C=a[k]||u[k];if(C===void 0)throw new Error(`Validation error, cannot resolve alias "${k}"`);return C.toString()})),!x.validChars.test(b))throw new Error(`Invalid characters, got value: ${b}`);return b=this.#o(b,x),b=this.#s(b,x,v),this.#r(y,b,x)}static#o(y,b){return y.replace(/[*?]/g,b.min+"-"+b.max)}static#s(y,b,x){const v=x();return y.replace(/H(?:\((\d+)-(\d+)\))?(?:\/(\d+))?/g,(k,C,S,j)=>{if(C&&S&&j){const M=parseInt(C,10),O=parseInt(S,10),E=parseInt(j,10);if(M>O)throw new Error(`Invalid range: ${M}-${O}, min > max`);if(E<=0)throw new Error(`Invalid step: ${E}, must be positive`);const $=Math.max(M,b.min),P=Math.floor(v*E),A=[];for(let B=Math.floor($/E)*E+P;B<=O;B+=E)B>=$&&A.push(B);return A.join(",")}else if(C&&S){const M=parseInt(C,10),O=parseInt(S,10);if(M>O)throw new Error(`Invalid range: ${M}-${O}, min > max`);return String(Math.floor(v*(O-M+1))+M)}else if(j){const M=parseInt(j,10);if(M<=0)throw new Error(`Invalid step: ${M}, must be positive`);const O=Math.floor(v*M),E=[];for(let $=Math.floor(b.min/M)*M+O;$<=b.max;$+=M)$>=b.min&&E.push($);return E.join(",")}else return String(Math.floor(v*(b.max-b.min+1)+b.min))})}static#r(y,b,x){const v=[];function k(S,j){if(Array.isArray(S))v.push(...S);else if(jt.#h(j,S))v.push(S);else{const M=parseInt(S.toString(),10);if(!(M>=j.min&&M<=j.max))throw new Error(`Constraint error, got value ${S} expected range ${j.min}-${j.max}`);v.push(y===l.DayOfWeek?M%7:S)}}return b.split(",").forEach(S=>{if(!(S.length>0))throw new Error("Invalid list value format");k(jt.#t(y,S,x),x)}),v}static#t(y,b,x){const v=b.split("/");if(v.length>2)throw new Error(`Invalid repeat: ${b}`);return v.length===2?(v[0].includes("-")||(v[0]=`${v[0]}-${x.max}`),jt.#a(y,v[0],parseInt(v[1],10),x)):jt.#a(y,b,1,x)}static#c(y,b,x){if(!(!isNaN(y)&&!isNaN(b)&&y>=x.min&&b<=x.max))throw new Error(`Constraint error, got range ${y}-${b} expected range ${x.min}-${x.max}`);if(y>b)throw new Error(`Invalid range: ${y}-${b}, min(${y}) > max(${b})`)}static#l(y){if(!(!isNaN(y)&&y>0))throw new Error(`Constraint error, cannot repeat at every ${y} time.`)}static#i(y,b,x,v){const k=[];y===l.DayOfWeek&&x%7===0&&k.push(0);for(let C=b;C<=x;C+=v)k.indexOf(C)===-1&&k.push(C);return k}static#a(y,b,x,v){const k=b.split("-");if(k.length<=1)return isNaN(+b)?b:+b;const[C,S]=k.map(j=>parseInt(j,10));return this.#c(C,S,v),this.#l(x),this.#i(y,C,S,x)}static#d(y){const b=y.split("#");if(b.length<=1)return{dayOfWeek:b[0]};const x=+b[b.length-1],v=y.match(/([,-/])/);if(v!==null)throw new Error(`Constraint error, invalid dayOfWeek \`#\` and \`${v?.[0]}\` special characters are incompatible`);if(!(b.length<=2&&!isNaN(x)&&x>=1&&x<=5))throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)");return{dayOfWeek:b[0],nthDayOfWeek:x}}static#h(y,b){return y.chars.some(x=>b.toString().includes(x))}};return Tt.CronExpressionParser=d,Tt}var _t={};const Mf={},Of=Object.freeze(Object.defineProperty({__proto__:null,default:Mf},Symbol.toStringTag,{value:"Module"})),oa=c.getAugmentedNamespace(Of);var ia;function Ef(){if(ia)return _t;ia=1;var e=_t&&_t.__createBinding||(Object.create?(function(l,a,u,d){d===void 0&&(d=u);var h=Object.getOwnPropertyDescriptor(a,u);(!h||("get"in h?!a.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return a[u]}}),Object.defineProperty(l,d,h)}):(function(l,a,u,d){d===void 0&&(d=u),l[d]=a[u]})),n=_t&&_t.__setModuleDefault||(Object.create?(function(l,a){Object.defineProperty(l,"default",{enumerable:!0,value:a})}):function(l,a){l.default=a}),r=_t&&_t.__importStar||(function(){var l=function(a){return l=Object.getOwnPropertyNames||function(u){var d=[];for(var h in u)Object.prototype.hasOwnProperty.call(u,h)&&(d[d.length]=h);return d},l(a)};return function(a){if(a&&a.__esModule)return a;var u={};if(a!=null)for(var d=l(a),h=0;h<d.length;h++)d[h]!=="default"&&e(u,a,d[h]);return n(u,a),u}})();Object.defineProperty(_t,"__esModule",{value:!0}),_t.CronFileParser=void 0;const o=Qs();let i=class Yr{static async parseFile(a){const{readFile:u}=await Promise.resolve().then(()=>r(oa)),d=await u(a,"utf8");return Yr.#e(d)}static parseFileSync(a){const{readFileSync:u}=oa,d=u(a,"utf8");return Yr.#e(d)}static#e(a){const u=a.split(`
|
|
7
|
+
`),d={variables:{},expressions:[],errors:{}};for(const h of u){const y=h.trim();if(y.length===0||y.startsWith("#"))continue;const b=y.match(/^(.*)=(.*)$/);if(b){const[,x,v]=b;d.variables[x]=v.replace(/["']/g,"");continue}try{const x=Yr.#n(y);d.expressions.push(x.interval)}catch(x){d.errors[y]=x}}return d}static#n(a){const u=a.split(" ");return{interval:o.CronExpressionParser.parse(u.slice(0,5).join(" ")),command:u.slice(5,u.length)}}};return _t.CronFileParser=i,_t}var aa;function If(){return aa||(aa=1,(function(e){var n=an&&an.__createBinding||(Object.create?(function(h,y,b,x){x===void 0&&(x=b);var v=Object.getOwnPropertyDescriptor(y,b);(!v||("get"in v?!y.__esModule:v.writable||v.configurable))&&(v={enumerable:!0,get:function(){return y[b]}}),Object.defineProperty(h,x,v)}):(function(h,y,b,x){x===void 0&&(x=b),h[x]=y[b]})),r=an&&an.__exportStar||function(h,y){for(var b in h)b!=="default"&&!Object.prototype.hasOwnProperty.call(y,b)&&n(y,h,b)};Object.defineProperty(e,"__esModule",{value:!0}),e.CronFileParser=e.CronExpressionParser=e.CronExpression=e.CronFieldCollection=e.CronDate=void 0;const o=Qs();var i=lo();Object.defineProperty(e,"CronDate",{enumerable:!0,get:function(){return i.CronDate}});var l=ul();Object.defineProperty(e,"CronFieldCollection",{enumerable:!0,get:function(){return l.CronFieldCollection}});var a=dl();Object.defineProperty(e,"CronExpression",{enumerable:!0,get:function(){return a.CronExpression}});var u=Qs();Object.defineProperty(e,"CronExpressionParser",{enumerable:!0,get:function(){return u.CronExpressionParser}});var d=Ef();Object.defineProperty(e,"CronFileParser",{enumerable:!0,get:function(){return d.CronFileParser}}),r(co(),e),e.default=o.CronExpressionParser})(an)),an}var Df=If(),Ds={exports:{}},la;function Af(){return la||(la=1,(function(e,n){(function(o,i){e.exports=i()})(globalThis,()=>(()=>{var r={949:((a,u,d)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.CronParser=void 0;var h=d(515),y=(function(){function b(x,v,k){v===void 0&&(v=!0),k===void 0&&(k=!1),this.expression=x,this.dayOfWeekStartIndexZero=v,this.monthStartIndexZero=k}return b.prototype.parse=function(){var x,v,k=(x=this.expression)!==null&&x!==void 0?x:"";if(k==="@reboot")return v=["@reboot","","","","","",""],v;if(k.startsWith("@")){var C=this.parseSpecial(this.expression);v=this.extractParts(C)}else v=this.extractParts(this.expression);return this.normalize(v),this.validate(v),v},b.prototype.parseSpecial=function(x){var v={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@midnight":"0 0 * * *","@hourly":"0 * * * *","@reboot":"@reboot"},k=v[x];if(!k)throw new Error("Unknown special expression.");return k},b.prototype.extractParts=function(x){if(!this.expression)throw new Error("cron expression is empty");for(var v=x.trim().split(/[ ]+/),k=0;k<v.length;k++)if(v[k].includes(",")){var C=v[k].split(",").map(function(j){return j.trim()}).filter(function(j){return j!==""}).map(function(j){return isNaN(Number(j))?j:Number(j)}).filter(function(j){return j!==null&&j!==""});C.length===0&&C.push("*"),C.sort(function(j,M){return j!==null&&M!==null?j-M:0}),v[k]=C.map(function(j){return j!==null?j.toString():""}).join(",")}if(v.length<5)throw new Error("Expression has only ".concat(v.length," part").concat(v.length==1?"":"s",". At least 5 parts are required."));if(v.length==5)v.unshift(""),v.push("");else if(v.length==6){var S=/\d{4}$/.test(v[5])||v[4]=="?"||v[2]=="?";S?v.unshift(""):v.push("")}else if(v.length>7)throw new Error("Expression has ".concat(v.length," parts; too many!"));return v},b.prototype.normalize=function(x){var v=this;if(x[3]=x[3].replace("?","*"),x[5]=x[5].replace("?","*"),x[2]=x[2].replace("?","*"),x[0].indexOf("0/")==0&&(x[0]=x[0].replace("0/","*/")),x[1].indexOf("0/")==0&&(x[1]=x[1].replace("0/","*/")),x[2].indexOf("0/")==0&&(x[2]=x[2].replace("0/","*/")),x[3].indexOf("1/")==0&&(x[3]=x[3].replace("1/","*/")),x[4].indexOf("1/")==0&&(x[4]=x[4].replace("1/","*/")),x[6].indexOf("1/")==0&&(x[6]=x[6].replace("1/","*/")),x[5]=x[5].replace(/(^\d)|([^#/\s]\d)/g,function($){var P=$.replace(/\D/,""),A=P;return v.dayOfWeekStartIndexZero?P=="7"&&(A="0"):A=(parseInt(P)-1).toString(),$.replace(P,A)}),x[5]=="L"&&(x[5]="6"),x[3]=="?"&&(x[3]="*"),x[3].indexOf("W")>-1&&(x[3].indexOf(",")>-1||x[3].indexOf("-")>-1))throw new Error("The 'W' character can be specified only when the day-of-month is a single day, not a range or list of days.");var k={SUN:0,MON:1,TUE:2,WED:3,THU:4,FRI:5,SAT:6};for(var C in k)x[5]=x[5].replace(new RegExp(C,"gi"),k[C].toString());x[4]=x[4].replace(/(^\d{1,2})|([^#/\s]\d{1,2})/g,function($){var P=$.replace(/\D/,""),A=P;return v.monthStartIndexZero&&(A=(parseInt(P)+1).toString()),$.replace(P,A)});var S={JAN:1,FEB:2,MAR:3,APR:4,MAY:5,JUN:6,JUL:7,AUG:8,SEP:9,OCT:10,NOV:11,DEC:12};for(var j in S)x[4]=x[4].replace(new RegExp(j,"gi"),S[j].toString());x[0]=="0"&&(x[0]=""),!/\*|\-|\,|\//.test(x[2])&&(/\*|\//.test(x[1])||/\*|\//.test(x[0]))&&(x[2]+="-".concat(x[2]));for(var M=0;M<x.length;M++)if(x[M].indexOf(",")!=-1&&(x[M]=x[M].split(",").filter(function($){return $!==""}).join(",")||"*"),x[M]=="*/1"&&(x[M]="*"),x[M].indexOf("/")>-1&&!/^\*|\-|\,/.test(x[M])){var O=null;switch(M){case 4:O="12";break;case 5:O="6";break;case 6:O="9999";break;default:O=null;break}if(O!==null){var E=x[M].split("/");x[M]="".concat(E[0],"-").concat(O,"/").concat(E[1])}}},b.prototype.validate=function(x){var v="0-9,\\-*/";this.validateOnlyExpectedCharactersFound(x[0],v),this.validateOnlyExpectedCharactersFound(x[1],v),this.validateOnlyExpectedCharactersFound(x[2],v),this.validateOnlyExpectedCharactersFound(x[3],"0-9,\\-*/LW"),this.validateOnlyExpectedCharactersFound(x[4],v),this.validateOnlyExpectedCharactersFound(x[5],"0-9,\\-*/L#"),this.validateOnlyExpectedCharactersFound(x[6],v),this.validateAnyRanges(x)},b.prototype.validateAnyRanges=function(x){h.default.secondRange(x[0]),h.default.minuteRange(x[1]),h.default.hourRange(x[2]),h.default.dayOfMonthRange(x[3]),h.default.monthRange(x[4],this.monthStartIndexZero),h.default.dayOfWeekRange(x[5],this.dayOfWeekStartIndexZero)},b.prototype.validateOnlyExpectedCharactersFound=function(x,v){var k=x.match(new RegExp("[^".concat(v,"]+"),"gi"));if(k&&k.length)throw new Error("Expression contains invalid values: '".concat(k.toString(),"'"))},b})();u.CronParser=y}),333:((a,u,d)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.ExpressionDescriptor=void 0;var h=d(823),y=d(949),b=(function(){function x(v,k){if(this.expression=v,this.options=k,this.expressionParts=new Array(5),!this.options.locale&&x.defaultLocale&&(this.options.locale=x.defaultLocale),!x.locales[this.options.locale]){var C=Object.keys(x.locales)[0];console.warn("Locale '".concat(this.options.locale,"' could not be found; falling back to '").concat(C,"'.")),this.options.locale=C}this.i18n=x.locales[this.options.locale],k.use24HourTimeFormat===void 0&&(k.use24HourTimeFormat=this.i18n.use24HourTimeFormatByDefault())}return x.toString=function(v,k){var C=k===void 0?{}:k,S=C.throwExceptionOnParseError,j=S===void 0?!0:S,M=C.verbose,O=M===void 0?!1:M,E=C.dayOfWeekStartIndexZero,$=E===void 0?!0:E,P=C.monthStartIndexZero,A=P===void 0?!1:P,B=C.use24HourTimeFormat,D=C.locale,_=D===void 0?null:D,V={throwExceptionOnParseError:j,verbose:O,dayOfWeekStartIndexZero:$,monthStartIndexZero:A,use24HourTimeFormat:B,locale:_};V.tzOffset&&console.warn("'tzOffset' option has been deprecated and is no longer supported.");var R=new x(v,V);return R.getFullDescription()},x.initialize=function(v,k){k===void 0&&(k="en"),x.specialCharacters=["/","-",",","*"],x.defaultLocale=k,v.load(x.locales)},x.prototype.getFullDescription=function(){var v,k,C="";try{var S=new y.CronParser(this.expression,this.options.dayOfWeekStartIndexZero,this.options.monthStartIndexZero);if(this.expressionParts=S.parse(),this.expressionParts[0]==="@reboot")return((k=(v=this.i18n).atReboot)===null||k===void 0?void 0:k.call(v))||"Run once, at startup";var j=this.getTimeOfDayDescription(),M=this.getDayOfMonthDescription(),O=this.getMonthDescription(),E=this.getDayOfWeekDescription(),$=this.getYearDescription();C+=j+M+E+O+$,C=this.transformVerbosity(C,!!this.options.verbose),C=C.charAt(0).toLocaleUpperCase()+C.substr(1)}catch(P){if(!this.options.throwExceptionOnParseError)C=this.i18n.anErrorOccuredWhenGeneratingTheExpressionD();else throw"".concat(P)}return C},x.prototype.getTimeOfDayDescription=function(){var v=this.expressionParts[0],k=this.expressionParts[1],C=this.expressionParts[2],S="";if(!h.StringUtilities.containsAny(k,x.specialCharacters)&&!h.StringUtilities.containsAny(C,x.specialCharacters)&&!h.StringUtilities.containsAny(v,x.specialCharacters))S+=this.i18n.atSpace()+this.formatTime(C,k,v);else if(!v&&k.indexOf("-")>-1&&!(k.indexOf(",")>-1)&&!(k.indexOf("/")>-1)&&!h.StringUtilities.containsAny(C,x.specialCharacters)){var j=k.split("-");S+=h.StringUtilities.format(this.i18n.everyMinuteBetweenX0AndX1(),this.formatTime(C,j[0],""),this.formatTime(C,j[1],""))}else if(!v&&C.indexOf(",")>-1&&C.indexOf("-")==-1&&C.indexOf("/")==-1&&!h.StringUtilities.containsAny(k,x.specialCharacters)){var M=C.split(",");S+=this.i18n.at();for(var O=0;O<M.length;O++)S+=" ",S+=this.formatTime(M[O],k,""),O<M.length-2&&(S+=","),O==M.length-2&&(S+=this.i18n.spaceAnd())}else{var E=this.getSecondsDescription(),$=this.getMinutesDescription(),P=this.getHoursDescription();if(S+=E,S&&$&&(S+=", "),S+=$,$===P)return S;S&&P&&(S+=", "),S+=P}return S},x.prototype.getSecondsDescription=function(){var v=this,k=this.getSegmentDescription(this.expressionParts[0],this.i18n.everySecond(),function(C){return C},function(C){return h.StringUtilities.format(v.i18n.everyX0Seconds(C),C)},function(C){return v.i18n.secondsX0ThroughX1PastTheMinute()},function(C){return C=="0"?"":parseInt(C)<20?v.i18n.atX0SecondsPastTheMinute(C):v.i18n.atX0SecondsPastTheMinuteGt20()||v.i18n.atX0SecondsPastTheMinute(C)});return k},x.prototype.getMinutesDescription=function(){var v=this,k=this.expressionParts[0],C=this.expressionParts[2],S=this.getSegmentDescription(this.expressionParts[1],this.i18n.everyMinute(),function(j){return j},function(j){return h.StringUtilities.format(v.i18n.everyX0Minutes(j),j)},function(j){return v.i18n.minutesX0ThroughX1PastTheHour()},function(j){try{return j=="0"&&C.indexOf("/")==-1&&k==""?v.i18n.everyHour():parseInt(j)<20?v.i18n.atX0MinutesPastTheHour(j):v.i18n.atX0MinutesPastTheHourGt20()||v.i18n.atX0MinutesPastTheHour(j)}catch{return v.i18n.atX0MinutesPastTheHour(j)}});return S},x.prototype.getHoursDescription=function(){var v=this,k=this.expressionParts[2],C=0,S=[];k.split("/")[0].split(",").forEach(function(O){var E=O.split("-");E.length===2&&S.push({value:E[1],index:C+1}),C+=E.length});var j=0,M=this.getSegmentDescription(k,this.i18n.everyHour(),function(O){var E=S.find(function(P){return P.value===O&&P.index===j}),$=E&&v.expressionParts[1]!=="0";return j++,$?v.formatTime(O,"59",""):v.formatTime(O,"0","")},function(O){return h.StringUtilities.format(v.i18n.everyX0Hours(O),O)},function(O){return v.i18n.betweenX0AndX1()},function(O){return v.i18n.atX0()});return M},x.prototype.getDayOfWeekDescription=function(){var v=this,k=this.i18n.daysOfTheWeek(),C=null;return this.expressionParts[5]=="*"?C="":C=this.getSegmentDescription(this.expressionParts[5],this.i18n.commaEveryDay(),function(S,j){var M=S;S.indexOf("#")>-1?M=S.substring(0,S.indexOf("#")):S.indexOf("L")>-1&&(M=M.replace("L",""));var O=parseInt(M),E=v.i18n.daysOfTheWeekInCase?v.i18n.daysOfTheWeekInCase(j)[O]:k[O];if(S.indexOf("#")>-1){var $=null,P=S.substring(S.indexOf("#")+1),A=S.substring(0,S.indexOf("#"));switch(P){case"1":$=v.i18n.first(A);break;case"2":$=v.i18n.second(A);break;case"3":$=v.i18n.third(A);break;case"4":$=v.i18n.fourth(A);break;case"5":$=v.i18n.fifth(A);break}E=$+" "+E}return E},function(S){return parseInt(S)==1?"":h.StringUtilities.format(v.i18n.commaEveryX0DaysOfTheWeek(S),S)},function(S){var j=S.substring(0,S.indexOf("-")),M=v.expressionParts[3]!="*";return M?v.i18n.commaAndX0ThroughX1(j):v.i18n.commaX0ThroughX1(j)},function(S){var j=null;if(S.indexOf("#")>-1){var M=S.substring(S.indexOf("#")+1),O=S.substring(0,S.indexOf("#"));j=v.i18n.commaOnThe(M,O).trim()+v.i18n.spaceX0OfTheMonth()}else if(S.indexOf("L")>-1)j=v.i18n.commaOnTheLastX0OfTheMonth(S.replace("L",""));else{var E=v.expressionParts[3]!="*";j=E?v.i18n.commaAndOnX0():v.i18n.commaOnlyOnX0(S)}return j}),C},x.prototype.getMonthDescription=function(){var v=this,k=this.i18n.monthsOfTheYear(),C=this.getSegmentDescription(this.expressionParts[4],"",function(S,j){return j&&v.i18n.monthsOfTheYearInCase?v.i18n.monthsOfTheYearInCase(j)[parseInt(S)-1]:k[parseInt(S)-1]},function(S){return parseInt(S)==1?"":h.StringUtilities.format(v.i18n.commaEveryX0Months(S),S)},function(S){return v.i18n.commaMonthX0ThroughMonthX1()||v.i18n.commaX0ThroughX1()},function(S){return v.i18n.commaOnlyInMonthX0?v.i18n.commaOnlyInMonthX0():v.i18n.commaOnlyInX0()});return C},x.prototype.getDayOfMonthDescription=function(){var v=this,k=null,C=this.expressionParts[3];switch(C){case"L":k=this.i18n.commaOnTheLastDayOfTheMonth();break;case"WL":case"LW":k=this.i18n.commaOnTheLastWeekdayOfTheMonth();break;default:var S=C.match(/(\d{1,2}W)|(W\d{1,2})/);if(S){var j=parseInt(S[0].replace("W","")),M=j==1?this.i18n.firstWeekday():h.StringUtilities.format(this.i18n.weekdayNearestDayX0(),j.toString());k=h.StringUtilities.format(this.i18n.commaOnTheX0OfTheMonth(),M);break}else{var O=C.match(/L-(\d{1,2})/);if(O){var E=O[1];k=h.StringUtilities.format(this.i18n.commaDaysBeforeTheLastDayOfTheMonth(E),E);break}else{if(C=="*"&&this.expressionParts[5]!="*")return"";k=this.getSegmentDescription(C,this.i18n.commaEveryDay(),function($){return $=="L"?v.i18n.lastDay():v.i18n.dayX0?h.StringUtilities.format(v.i18n.dayX0(),$):$},function($){return $=="1"?v.i18n.commaEveryDay():v.i18n.commaEveryX0Days($)},function($){return v.i18n.commaBetweenDayX0AndX1OfTheMonth($)},function($){return v.i18n.commaOnDayX0OfTheMonth($)})}break}}return k},x.prototype.getYearDescription=function(){var v=this,k=this.getSegmentDescription(this.expressionParts[6],"",function(C){return/^\d+$/.test(C)?new Date(parseInt(C),1).getFullYear().toString():C},function(C){return h.StringUtilities.format(v.i18n.commaEveryX0Years(C),C)},function(C){return v.i18n.commaYearX0ThroughYearX1()||v.i18n.commaX0ThroughX1()},function(C){return v.i18n.commaOnlyInYearX0?v.i18n.commaOnlyInYearX0():v.i18n.commaOnlyInX0()});return k},x.prototype.getSegmentDescription=function(v,k,C,S,j,M){var O=null,E=v.indexOf("/")>-1,$=v.indexOf("-")>-1,P=v.indexOf(",")>-1;if(!v)O="";else if(v==="*")O=k;else if(!E&&!$&&!P)O=h.StringUtilities.format(M(v),C(v));else if(P){for(var A=v.split(","),B="",D=0;D<A.length;D++)if(D>0&&A.length>2&&(B+=",",D<A.length-1&&(B+=" ")),D>0&&A.length>1&&(D==A.length-1||A.length==2)&&(B+="".concat(this.i18n.spaceAnd()," ")),A[D].indexOf("/")>-1||A[D].indexOf("-")>-1){var _=A[D].indexOf("-")>-1&&A[D].indexOf("/")==-1,V=this.getSegmentDescription(A[D],k,C,S,_?this.i18n.commaX0ThroughX1:j,M);_&&(V=V.replace(", ","")),B+=V}else E?B+=this.getSegmentDescription(A[D],k,C,S,j,M):B+=C(A[D]);E?O=B:O=h.StringUtilities.format(M(v),B)}else if(E){var A=v.split("/");if(O=h.StringUtilities.format(S(A[1]),A[1]),A[0].indexOf("-")>-1){var R=this.generateRangeSegmentDescription(A[0],j,C);R.indexOf(", ")!=0&&(O+=", "),O+=R}else if(A[0].indexOf("*")==-1){var W=h.StringUtilities.format(M(A[0]),C(A[0]));W=W.replace(", ",""),O+=h.StringUtilities.format(this.i18n.commaStartingX0(),W)}}else $&&(O=this.generateRangeSegmentDescription(v,j,C));return O},x.prototype.generateRangeSegmentDescription=function(v,k,C){var S="",j=v.split("-"),M=C(j[0],1),O=C(j[1],2),E=k(v);return S+=h.StringUtilities.format(E,M,O),S},x.prototype.formatTime=function(v,k,C){var S=0,j=0,M=parseInt(v)+S,O=parseInt(k)+j;O>=60?(O-=60,M+=1):O<0&&(O+=60,M-=1),M>=24?M=M-24:M<0&&(M=24+M);var E="",$=!1;this.options.use24HourTimeFormat||($=!!(this.i18n.setPeriodBeforeTime&&this.i18n.setPeriodBeforeTime()),E=$?"".concat(this.getPeriod(M)," "):" ".concat(this.getPeriod(M)),M>12&&(M-=12),M===0&&(M=12));var P="";return C&&(P=":".concat(("00"+C).substring(C.length))),"".concat($?E:"").concat(("00"+M.toString()).substring(M.toString().length),":").concat(("00"+O.toString()).substring(O.toString().length)).concat(P).concat($?"":E)},x.prototype.transformVerbosity=function(v,k){if(!k&&(v=v.replace(new RegExp(", ".concat(this.i18n.everyMinute()),"g"),""),v=v.replace(new RegExp(", ".concat(this.i18n.everyHour()),"g"),""),v=v.replace(new RegExp(this.i18n.commaEveryDay(),"g"),""),v=v.replace(/\, ?$/,""),this.i18n.conciseVerbosityReplacements))for(var C=0,S=Object.entries(this.i18n.conciseVerbosityReplacements());C<S.length;C++){var j=S[C],M=j[0],O=j[1];v=v.replace(new RegExp(M,"g"),O)}return v},x.prototype.getPeriod=function(v){return v>=12?this.i18n.pm&&this.i18n.pm()||"PM":this.i18n.am&&this.i18n.am()||"AM"},x.locales={},x})();u.ExpressionDescriptor=b}),747:((a,u,d)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.enLocaleLoader=void 0;var h=d(486),y=(function(){function b(){}return b.prototype.load=function(x){x.en=new h.en},b})();u.enLocaleLoader=y}),486:((a,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.en=void 0;var d=(function(){function h(){}return h.prototype.atX0SecondsPastTheMinuteGt20=function(){return null},h.prototype.atX0MinutesPastTheHourGt20=function(){return null},h.prototype.commaMonthX0ThroughMonthX1=function(){return null},h.prototype.commaYearX0ThroughYearX1=function(){return null},h.prototype.use24HourTimeFormatByDefault=function(){return!1},h.prototype.anErrorOccuredWhenGeneratingTheExpressionD=function(){return"An error occurred when generating the expression description. Check the cron expression syntax."},h.prototype.everyMinute=function(){return"every minute"},h.prototype.everyHour=function(){return"every hour"},h.prototype.atSpace=function(){return"At "},h.prototype.everyMinuteBetweenX0AndX1=function(){return"Every minute between %s and %s"},h.prototype.at=function(){return"At"},h.prototype.spaceAnd=function(){return" and"},h.prototype.everySecond=function(){return"every second"},h.prototype.everyX0Seconds=function(){return"every %s seconds"},h.prototype.secondsX0ThroughX1PastTheMinute=function(){return"seconds %s through %s past the minute"},h.prototype.atX0SecondsPastTheMinute=function(){return"at %s seconds past the minute"},h.prototype.everyX0Minutes=function(){return"every %s minutes"},h.prototype.minutesX0ThroughX1PastTheHour=function(){return"minutes %s through %s past the hour"},h.prototype.atX0MinutesPastTheHour=function(){return"at %s minutes past the hour"},h.prototype.everyX0Hours=function(){return"every %s hours"},h.prototype.betweenX0AndX1=function(){return"between %s and %s"},h.prototype.atX0=function(){return"at %s"},h.prototype.commaEveryDay=function(){return", every day"},h.prototype.commaEveryX0DaysOfTheWeek=function(){return", every %s days of the week"},h.prototype.commaX0ThroughX1=function(){return", %s through %s"},h.prototype.commaAndX0ThroughX1=function(){return", %s through %s"},h.prototype.first=function(){return"first"},h.prototype.second=function(){return"second"},h.prototype.third=function(){return"third"},h.prototype.fourth=function(){return"fourth"},h.prototype.fifth=function(){return"fifth"},h.prototype.commaOnThe=function(){return", on the "},h.prototype.spaceX0OfTheMonth=function(){return" %s of the month"},h.prototype.lastDay=function(){return"the last day"},h.prototype.commaOnTheLastX0OfTheMonth=function(){return", on the last %s of the month"},h.prototype.commaOnlyOnX0=function(){return", only on %s"},h.prototype.commaAndOnX0=function(){return", and on %s"},h.prototype.commaEveryX0Months=function(){return", every %s months"},h.prototype.commaOnlyInX0=function(){return", only in %s"},h.prototype.commaOnTheLastDayOfTheMonth=function(){return", on the last day of the month"},h.prototype.commaOnTheLastWeekdayOfTheMonth=function(){return", on the last weekday of the month"},h.prototype.commaDaysBeforeTheLastDayOfTheMonth=function(){return", %s days before the last day of the month"},h.prototype.firstWeekday=function(){return"first weekday"},h.prototype.weekdayNearestDayX0=function(){return"weekday nearest day %s"},h.prototype.commaOnTheX0OfTheMonth=function(){return", on the %s of the month"},h.prototype.commaEveryX0Days=function(){return", every %s days"},h.prototype.commaBetweenDayX0AndX1OfTheMonth=function(){return", between day %s and %s of the month"},h.prototype.commaOnDayX0OfTheMonth=function(){return", on day %s of the month"},h.prototype.commaEveryHour=function(){return", every hour"},h.prototype.commaEveryX0Years=function(){return", every %s years"},h.prototype.commaStartingX0=function(){return", starting %s"},h.prototype.daysOfTheWeek=function(){return["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},h.prototype.monthsOfTheYear=function(){return["January","February","March","April","May","June","July","August","September","October","November","December"]},h.prototype.atReboot=function(){return"Run once, at startup"},h})();u.en=d}),515:((a,u)=>{Object.defineProperty(u,"__esModule",{value:!0});function d(y,b){if(!y)throw new Error(b)}var h=(function(){function y(){}return y.secondRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);d(k>=0&&k<=59,"seconds part must be >= 0 and <= 59")}},y.minuteRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);d(k>=0&&k<=59,"minutes part must be >= 0 and <= 59")}},y.hourRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);d(k>=0&&k<=23,"hours part must be >= 0 and <= 23")}},y.dayOfMonthRange=function(b){for(var x=b.split(","),v=0;v<x.length;v++)if(!isNaN(parseInt(x[v],10))){var k=parseInt(x[v],10);d(k>=1&&k<=31,"DOM part must be >= 1 and <= 31")}},y.monthRange=function(b,x){for(var v=b.split(","),k=0;k<v.length;k++)if(!isNaN(parseInt(v[k],10))){var C=parseInt(v[k],10);d(C>=1&&C<=12,x?"month part must be >= 0 and <= 11":"month part must be >= 1 and <= 12")}},y.dayOfWeekRange=function(b,x){for(var v=b.split(","),k=0;k<v.length;k++)if(!isNaN(parseInt(v[k],10))){var C=parseInt(v[k],10);d(C>=0&&C<=6,x?"DOW part must be >= 0 and <= 6":"DOW part must be >= 1 and <= 7")}},y})();u.default=h}),823:((a,u)=>{Object.defineProperty(u,"__esModule",{value:!0}),u.StringUtilities=void 0;var d=(function(){function h(){}return h.format=function(y){for(var b=[],x=1;x<arguments.length;x++)b[x-1]=arguments[x];return y.replace(/%s/g,function(v){return b.shift()})},h.containsAny=function(y,b){return b.some(function(x){return y.indexOf(x)>-1})},h})();u.StringUtilities=d})},o={};function i(a){var u=o[a];if(u!==void 0)return u.exports;var d=o[a]={exports:{}};return r[a](d,d.exports,i),d.exports}var l={};return(()=>{var a=l;Object.defineProperty(a,"__esModule",{value:!0}),a.toString=void 0;var u=i(333),d=i(747);u.ExpressionDescriptor.initialize(new d.enLocaleLoader),a.default=u.ExpressionDescriptor;var h=u.ExpressionDescriptor.toString;a.toString=h})(),l})())})(Ds)),Ds.exports}var Rf=Af();const $f=c.getDefaultExportFromCjs(Rf),Ff=new Set(["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC","SUN","MON","TUE","WED","THU","FRI","SAT"]);function Lf(e){for(const n of e.trim().split(/\s+/)){if(/[#?]/.test(n))return!1;for(const r of n.split(/[,\-/]/))if(!(r===""||r==="*")&&/[A-Za-z]/.test(r)&&!Ff.has(r.toUpperCase()))return!1}return!0}function uo(e){const n=(e??"").trim();if(n.split(/\s+/).filter(Boolean).length!==5)return{valid:!1,description:"",nextRun:null,error:"Expected a 5-field UNIX cron: minute hour day-of-month month day-of-week."};if(!Lf(n))return{valid:!1,description:"",nextRun:null,error:"Unsupported cron syntax: L, W, #, and ? extensions are not allowed (plain 5-field UNIX cron only)."};try{const r=$f.toString(n,{use24HourTimeFormat:!0,verbose:!1}),o=Df.CronExpressionParser.parse(n,{tz:"UTC"}).next().toDate();return{valid:!0,description:r,nextRun:o}}catch(r){return{valid:!1,description:"",nextRun:null,error:r instanceof Error?r.message:"Invalid cron expression."}}}function hl(e){return e?e.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",timeZone:"UTC",hour12:!1})+" UTC":"—"}function _f({onSubmit:e,isSubmitting:n,disabled:r,disabledReason:o}){const[i,l]=T.useState(!1),[a,u]=T.useState(!1),d=()=>l(!1),h=async()=>{try{await e({forceRefresh:a}),l(!1)}catch{}},y=t.jsx("span",{children:t.jsx(c.AddButton,{label:"Materialization",onClick:()=>l(!0),disabled:r})});return t.jsxs(t.Fragment,{children:[r&&o?t.jsx(m.Tooltip,{title:o,children:y}):y,t.jsx(c.AppDialog,{open:i,onClose:d,title:"New materialization",description:"Compile the package, build a table for every persist source, and load them so queries serve from the tables.",actions:t.jsxs(t.Fragment,{children:[t.jsx(m.Button,{onClick:d,children:"Cancel"}),t.jsx(m.Button,{variant:"contained",loading:n,onClick:h,children:"Materialize"})]}),children:t.jsx(m.FormGroup,{children:t.jsx(m.FormControlLabel,{control:t.jsx(m.Switch,{checked:a,onChange:b=>u(b.target.checked)}),label:"Force refresh (rebuild even if unchanged)"})})})]})}function Kr({children:e}){return t.jsx(m.Typography,{variant:"caption",component:"h6",sx:{display:"block",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600,color:"text.secondary",mb:1},children:e})}function es(e){return e===q.MaterializationStatus.Pending||e===q.MaterializationStatus.ManifestRowsReady}function Nf(e){return e===q.MaterializationStatus.ManifestFileReady||e===q.MaterializationStatus.Failed||e===q.MaterializationStatus.Cancelled}function Pf(e){switch(e){case q.MaterializationStatus.ManifestFileReady:return"Done";case q.MaterializationStatus.Failed:return"Failed";case q.MaterializationStatus.Cancelled:return"Cancelled";case q.MaterializationStatus.Pending:case q.MaterializationStatus.ManifestRowsReady:return"Pending";default:return"Unknown"}}function zf(e){switch(e){case q.MaterializationStatus.ManifestRowsReady:return"info";case q.MaterializationStatus.ManifestFileReady:return"success";case q.MaterializationStatus.Failed:return"error";case q.MaterializationStatus.Cancelled:return"warning";case q.MaterializationStatus.Pending:default:return"default"}}function fl(e){return e.status===q.MaterializationStatus.ManifestFileReady&&is(e).autoLoad==="failed"}function pl(e){return fl(e)?"Built, not served":Pf(e.status)}function Zs(e){return fl(e)?"warning":zf(e.status)}function Wf(e){const n=Object.values(is(e).refusedSources??{}).map(o=>({name:o.name,message:o.message})),r=Object.values(e.manifest?.failures??{}).filter(o=>o.refused).map(o=>({name:o.sourceName??o.sourceEntityId,message:o.reason}));return[...n,...r].sort((o,i)=>o.name.localeCompare(i.name))}function ml(e,n){const r=[`${e.sourcesBuilt??0} built`,`${e.sourcesReused??0} reused`];return e.sourcesRefused&&r.push(`${e.sourcesRefused} refused`),r.join(n)}function is(e){return e.metadata??{}}function gl(e){return e.trigger==="scheduler"||e.trigger==="SCHEDULER"}function qf(e){return gl(e)?"Scheduled":"Manual"}function yl(e,n){if(!e)return"-";const r=new Date(e).getTime(),o=n?new Date(n).getTime():Date.now(),i=Math.max(0,o-r);if(i<1e3)return`${i}ms`;const l=Math.round(i/1e3);if(l<60)return`${l}s`;const a=Math.floor(l/60),u=l%60;if(a<60)return`${a}m ${u}s`;const d=Math.floor(a/60),h=a%60;return`${d}h ${h}m`}function Xs(e){if(!e)return"—";const n=new Date(e);return Number.isNaN(n.getTime())?"—":n.toLocaleString(void 0,{year:"numeric",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})}function Bf(e){if(!e)return"-";const n=new Date(e).getTime(),r=Math.round((Date.now()-n)/1e3);if(r<60)return"just now";const o=Math.floor(r/60);if(o<60)return`${o}m ago`;const i=Math.floor(o/60);return i<24?`${i}h ago`:`${Math.floor(i/24)}d ago`}function Vf({entries:e,builtAt:n}){const r=Object.entries(e??{});return t.jsxs(m.Box,{children:[t.jsxs(m.Stack,{direction:"row",alignItems:"baseline",justifyContent:"space-between",children:[t.jsx(Kr,{children:"Build manifest"}),n&&t.jsxs(m.Typography,{variant:"caption",color:"text.secondary",children:["Built ",Xs(n)]})]}),r.length===0?t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:"No materialized tables yet."}):t.jsxs(m.Table,{size:"small",children:[t.jsx(m.TableHead,{children:t.jsxs(m.TableRow,{children:[t.jsx(m.TableCell,{children:"Source"}),t.jsx(m.TableCell,{children:"Table name"}),t.jsx(m.TableCell,{children:"Connection"}),t.jsx(m.TableCell,{children:"Realization"}),t.jsx(m.TableCell,{align:"right",children:"Rows"})]})}),t.jsx(m.TableBody,{children:r.map(([o,i])=>t.jsxs(m.TableRow,{children:[t.jsx(m.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:i.sourceName??o}),t.jsx(m.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:i.physicalTableName??"-"}),t.jsx(m.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:i.connectionName??"-"}),t.jsx(m.TableCell,{children:i.realization??"-"}),t.jsx(m.TableCell,{align:"right",children:i.rowCount??"-"})]},o))})]})]})}function xl({meta:e}){const n=gl(e);return t.jsx(m.Tooltip,{title:n?"Fired by the materialization schedule":"Triggered manually",children:t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:qf(e)})})}function Hf({materialization:e,buildPlan:n,onClose:r}){const o=e?is(e):{},i=e?Wf(e):[],l=n.status==="ready"?Object.values(n.plan?.sources??{}):[];return t.jsx(m.Dialog,{open:e!==null,onClose:r,maxWidth:"md",fullWidth:!0,"aria-labelledby":"materialization-detail-title",children:e&&t.jsxs(t.Fragment,{children:[t.jsxs(m.DialogTitle,{sx:{pr:6,pb:1.5},id:"materialization-detail-title",children:[t.jsxs(m.Stack,{direction:"row",alignItems:"center",spacing:1,sx:{mb:.75},children:[t.jsx(m.Chip,{size:"small",label:pl(e),color:Zs(e),variant:es(e.status)?"filled":"outlined"}),t.jsx(xl,{meta:o})]}),t.jsx(m.Typography,{variant:"subtitle1",sx:{fontWeight:600},children:e.packageName??"Materialization"}),t.jsx(m.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:q.MONO_FONT_FAMILY,wordBreak:"break-all"},children:e.id}),t.jsx(m.IconButton,{"aria-label":"close",onClick:r,sx:{position:"absolute",right:8,top:8},children:t.jsx(c.CloseIcon,{fontSize:"small"})})]}),t.jsxs(m.DialogContent,{dividers:!0,children:[t.jsxs(m.Box,{sx:{bgcolor:"action.hover",borderRadius:2,p:2,mb:3,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(140px, 1fr))",gap:2},children:[t.jsx(cr,{label:"Started",value:Xs(e.startedAt??e.createdAt)}),t.jsx(cr,{label:"Completed",value:Xs(e.completedAt)}),t.jsx(cr,{label:"Duration",value:yl(e.startedAt,e.completedAt)}),t.jsx(cr,{label:"Sources",value:ml(o," · ")}),t.jsx(cr,{label:"Force refresh",value:o.forceRefresh?"Yes":"No"})]}),e.error&&t.jsxs(m.Box,{sx:{borderRadius:2,p:2,mb:3,border:"1px solid",borderColor:"error.main"},children:[t.jsx(Kr,{children:t.jsx(m.Box,{component:"span",sx:{color:"error.main"},children:"Error"})}),t.jsx(m.Typography,{variant:"body2",sx:{fontFamily:q.MONO_FONT_FAMILY,whiteSpace:"pre-wrap"},children:e.error})]}),i.length>0&&t.jsxs(m.Box,{sx:{borderRadius:2,p:2,mb:3,border:"1px solid",borderColor:"warning.main"},children:[t.jsx(Kr,{children:t.jsx(m.Box,{component:"span",sx:{color:"warning.main"},children:"Refused sources"})}),t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1},children:"Not built, because materializing them would be unsafe. They serve live until the model changes."}),i.map(a=>t.jsxs(m.Box,{sx:{mt:1},children:[t.jsx(m.Typography,{variant:"body2",sx:{fontFamily:q.MONO_FONT_FAMILY},children:a.name}),t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{whiteSpace:"pre-wrap"},children:a.message})]},a.name))]}),t.jsxs(m.Box,{sx:{mb:3},children:[t.jsx(Kr,{children:"Build plan"}),n.status==="loading"?t.jsx(c.Loading,{text:c.LOADING_COPY.loading,size:16,centered:!1}):n.status==="unavailable"?t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:"The build plan is unavailable."}):l.length===0?t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:"This package has no persist sources."}):t.jsxs(m.Table,{size:"small",children:[t.jsx(m.TableHead,{children:t.jsxs(m.TableRow,{children:[t.jsx(m.TableCell,{children:"Source"}),t.jsx(m.TableCell,{children:"Connection"}),t.jsx(m.TableCell,{children:"Dialect"}),t.jsx(m.TableCell,{align:"right",children:"Columns"}),t.jsx(m.TableCell,{children:"Source Entity ID"})]})}),t.jsx(m.TableBody,{children:l.map(a=>t.jsxs(m.TableRow,{children:[t.jsx(m.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:a.name}),t.jsx(m.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY},children:a.connectionName}),t.jsx(m.TableCell,{children:a.dialect??"-"}),t.jsx(m.TableCell,{align:"right",children:a.columns?.length??0}),t.jsx(m.TableCell,{sx:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"0.75rem",wordBreak:"break-all",maxWidth:220},children:a.sourceEntityId})]},a.sourceID))})]})]}),t.jsx(Vf,{entries:e.manifest?.entries,builtAt:e.manifest?.builtAt})]})]})})}function cr({label:e,value:n}){return t.jsxs(m.Box,{children:[t.jsx(m.Typography,{variant:"caption",color:"text.secondary",display:"block",children:e}),t.jsx(m.Typography,{variant:"body2",children:n})]})}const Uf=c.createSvgIcon(t.jsx("path",{d:"M6 6h12v12H6z"}));function Gf({materialization:e,onCloseDialog:n,isMutating:r,onDelete:o}){const[i,l]=T.useState(!1),a=()=>l(!0),u=()=>{l(!1),n()};return t.jsxs(T.Fragment,{children:[t.jsxs(et,{"aria-label":`Delete materialization ${e?.id??""}`.trim(),onClick:d=>{d.stopPropagation(),a()},sx:{color:"error.main"},children:[t.jsx(io,{sx:{color:"inherit"},children:t.jsx(Pt.Delete,{fontSize:"small"})}),t.jsx(ao,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:i,onClose:u,title:"Delete materialization",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:u,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>o(),loading:r,children:"Delete run"})]}),children:t.jsx(c.Typography,{variant:"body2",children:"Delete this run's record? This cannot be undone. The tables it built stay in place: drop any you no longer need through their connection."})})]})}function Yf({materializations:e,mutable:n,isMutating:r,onStop:o,onDelete:i,onViewDetails:l}){return e.length===0?t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{py:1,fontStyle:"italic"},children:"No materializations yet."}):t.jsxs(m.Table,{size:"small",sx:{"& td, & th":{borderColor:"divider"},"& td:first-of-type, & th:first-of-type":{pl:0},"& td:last-of-type, & th:last-of-type":{pr:0},"& th":{color:"text.secondary",fontWeight:600}},children:[t.jsx(m.TableHead,{children:t.jsxs(m.TableRow,{children:[t.jsx(m.TableCell,{children:"Status"}),t.jsx(m.TableCell,{children:"Trigger"}),t.jsx(m.TableCell,{children:"Started"}),t.jsx(m.TableCell,{children:"Duration"}),t.jsx(m.TableCell,{children:"Sources"}),t.jsx(m.TableCell,{align:"right",children:"Actions"})]})}),t.jsx(m.TableBody,{children:e.map(a=>t.jsx(Kf,{materialization:a,mutable:n,isMutating:r,onStop:o,onDelete:i,onViewDetails:l},a.id))})]})}function Kf({materialization:e,mutable:n,isMutating:r,onStop:o,onDelete:i,onViewDetails:l}){const[a,u]=T.useState(null),d=!!a,h=()=>u(null),y=is(e),b=y.sourcesBuilt!==void 0||y.sourcesReused!==void 0?ml(y,", "):"-",x=es(e.status),v=Nf(e.status),k=e.error??void 0,C=n&&(x||v);return t.jsxs(m.TableRow,{hover:!0,sx:{cursor:"pointer","&:focus-visible":{outline:"2px solid",outlineColor:"primary.main",outlineOffset:"-2px"}},onClick:()=>l(e),onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),l(e))},role:"button",tabIndex:0,"aria-label":`View materialization ${e.id??""} details`.trim(),children:[t.jsx(m.TableCell,{children:t.jsxs(m.Box,{sx:{display:"flex",alignItems:"center",gap:.5},children:[t.jsx(m.Typography,{variant:"body2",sx:{fontWeight:500,color:Zs(e)==="default"?"text.primary":`${Zs(e)}.main`},children:pl(e)}),k&&t.jsx(m.Tooltip,{title:k,children:t.jsx(c.InfoOutlinedIcon,{fontSize:"small",color:"error"})})]})}),t.jsx(m.TableCell,{children:t.jsx(xl,{meta:y})}),t.jsx(m.TableCell,{children:Bf(e.startedAt??e.createdAt)}),t.jsx(m.TableCell,{children:yl(e.startedAt,e.completedAt)}),t.jsx(m.TableCell,{children:b}),t.jsx(m.TableCell,{align:"right",onClick:S=>S.stopPropagation(),children:C&&t.jsxs(t.Fragment,{children:[t.jsx(m.IconButton,{size:"small","aria-label":`Materialization actions for ${e.id??""}`.trim(),onClick:S=>u(S.currentTarget),children:t.jsx(Pt.MoreVert,{fontSize:"small"})}),t.jsxs(m.Menu,{anchorEl:a,open:d,onClose:h,anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n&&x&&t.jsxs(m.MenuItem,{"aria-label":`Stop materialization ${e.id??""}`.trim(),disabled:r,onClick:()=>{h(),o(e)},children:[t.jsx(m.ListItemIcon,{children:t.jsx(Uf,{fontSize:"small"})}),t.jsx(m.ListItemText,{children:"Stop"})]}),n&&v&&t.jsx(Gf,{materialization:e,isMutating:r,onCloseDialog:h,onDelete:()=>i(e)})]})]})})]})}const Qf=c.createSvgIcon(t.jsx("path",{d:"m11.99 18.54-7.37-5.73L3 14.07l9 7 9-7-1.63-1.27zM12 16l7.36-5.73L21 9l-9-7-9 7 1.63 1.27zm0-11.47L17.74 9 12 13.47 6.26 9z"})),Zf={package:"Materialized artifacts are shared across versions",version:"Materialized artifacts are per published version"};function Xf({scope:e,disabled:n,disabledReason:r,isSubmitting:o,onChange:i}){const[l,a]=T.useState(null),u=async d=>{a(null),d!==e&&await i(d).catch(()=>{})};return t.jsxs(t.Fragment,{children:[t.jsx(c.SecondaryButton,{label:"Scope",icon:t.jsx(Qf,{}),onClick:d=>a(d.currentTarget),disabled:n||o,...r?{disabledReason:r}:{},ariaHasPopup:"menu",ariaLabel:`Scope: ${e}`}),t.jsx(m.Menu,{anchorEl:l,open:!!l,onClose:()=>a(null),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:["package","version"].map(d=>t.jsxs(m.MenuItem,{selected:d===e,onClick:()=>void u(d),children:[t.jsx(m.ListItemIcon,{sx:{minWidth:32},children:d===e&&t.jsx(c.CheckIcon,{fontSize:"small"})}),t.jsx(m.ListItemText,{primary:d,secondary:Zf[d]})]},d))})]})}const Jf=c.createSvgIcon([t.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8"},"0"),t.jsx("path",{d:"M12.5 7H11v6l5.25 3.15.75-1.23-4.5-2.67z"},"1")]),ca="0 6 * * *";function ep({currentSchedule:e,isSubmitting:n,disabled:r,disabledReason:o,onSubmit:i}){const[l,a]=T.useState(!1),[u,d]=T.useState(e??ca),h=()=>{d(e??ca),a(!0)},y=()=>a(!1),b=uo(u),x=async v=>{try{await i(v),a(!1)}catch{}};return t.jsxs(t.Fragment,{children:[t.jsx(c.SecondaryButton,{label:"Schedule",icon:t.jsx(Jf,{}),onClick:h,disabled:r,...o?{disabledReason:o}:{},ariaHasPopup:"dialog",ariaLabel:e?"Edit schedule":"Set schedule"}),t.jsxs(c.AppDialog,{open:l,onClose:y,title:e?"Edit schedule":"Set schedule",description:"The publisher rebuilds this package's materializations on this cadence: a 5-field UNIX cron, in UTC. In a hosted deployment the change takes effect on your next publish.",actions:t.jsxs(t.Fragment,{children:[e&&t.jsx(m.Button,{color:"error",loading:n,onClick:()=>x(null),sx:{mr:"auto"},children:"Clear schedule"}),t.jsx(m.Button,{onClick:y,children:"Cancel"}),t.jsx(m.Button,{variant:"contained",loading:n,disabled:!b.valid,onClick:()=>x(u.trim()),children:"Save schedule"})]}),children:[t.jsx(m.TextField,{autoFocus:!0,fullWidth:!0,size:"small",label:"Cron expression",value:u,onChange:v=>d(v.target.value),error:u.trim()!==""&&!b.valid,helperText:b.valid?`${b.description} · next run ${hl(b.nextRun)}`:b.error,slotProps:{htmlInput:{style:{fontFamily:q.MONO_FONT_FAMILY}}}}),t.jsxs(m.Alert,{severity:"info",children:["A schedule runs only on version-scoped packages, so saving one sets ",t.jsx("code",{children:"scope: version"})," for this package."]})]})]})}const tp=3e3;function vl({resourceUri:e,versioned:n=!1}){const{apiClients:r,mutable:o}=q.useServer(),i=pt.useQueryClient(),{environmentName:l,packageName:a,versionId:u}=c.parseResourceUri(e),[d,h]=T.useState(""),[y,b]=T.useState(null);if(!a)throw new Error("Materializations requires a package in the resource URI");const x=c.useQueryWithApiError({queryKey:["materializations",l,a,u],queryFn:()=>r.materializations.listMaterializations(l,a,void 0,void 0,u),refetchInterval:H=>(H.state.data?.data??[]).some(z=>es(z.status))?tp:!1}),v=c.useQueryWithApiError({queryKey:["package",l,a,u],queryFn:()=>r.packages.getPackage(l,a,u)}),k=c.useQueryWithApiError({queryKey:["package-build-plan",l,a,u],queryFn:async({signal:H})=>{try{return{inline:!1,plan:(await r.packages.getPackageBuildPlan(l,a,u,{signal:H})).data}}catch(Q){if(Q?.response?.status===404)return{inline:!0,plan:null};throw Q}},enabled:y!==null}),C=()=>i.invalidateQueries({queryKey:["materializations",l,a]}),S=c.useMutationWithApiError({mutationFn:Ht("materialization","create",H=>r.materializations.createMaterialization(l,a,{forceRefresh:H.forceRefresh,...u!==void 0?{versionId:u}:{}})),onSuccess(){h("Materialization requested"),C()},onError(H){h(H.message),C()}}),j=c.useMutationWithApiError({mutationFn:Ht("materialization","update",H=>r.materializations.materializationAction(l,a,H.id,q.MaterializationActionActionEnum.Stop,u)),onSuccess(){h("Materialization stopped"),C()},onError(H){h(H.message)}}),M=c.useMutationWithApiError({mutationFn:Ht("materialization","delete",H=>r.materializations.deleteMaterialization(l,a,H.id,u)),onSuccess(){h("Materialization deleted"),C()},onError(H){h(H.message)}}),O=v.data?.data,E=c.useMutationWithApiError({mutationFn:Ht("schedule","update",H=>r.packages.updatePackage(l,a,{name:a,description:O?.description,...H?{scope:q.PackageScopeEnum.Version}:{},materialization:{schedule:H}})),onSuccess(H,Q){h(Q?"Schedule updated":"Schedule cleared"),i.invalidateQueries({queryKey:["package",l,a]})},onError(H){h(H.message)}}),$=c.useMutationWithApiError({mutationFn:Ht("scope","update",H=>r.packages.updatePackage(l,a,{name:a,description:O?.description,scope:H})),onSuccess(){h("Scope updated"),i.invalidateQueries({queryKey:["package",l,a]})},onError(H){h(H.message)}}),P=x.data?.data??[],A=P.find(H=>H.id===y)??null,B=P.some(H=>es(H.status)),D=S.isPending||j.isPending||M.isPending,_=k.isError?{status:"unavailable"}:k.isSuccess?k.data.inline?v.isSuccess?{status:"ready",plan:O?.buildPlan??null}:v.isError?{status:"unavailable"}:{status:"loading"}:{status:"ready",plan:k.data.plan}:{status:"loading"},V=O?.materialization?.schedule??null,R=O?.scope===q.PackageScopeEnum.Version?"version":"package",W=!!O?.manifestLocation,Z=!!O?.materialization?.freshness,ne=V?uo(V):null,J=W?"Control-plane managed: refresh is driven by the control plane, not the built-in scheduler.":[ne?ne.valid?`${ne.description} (${V}), next run ${hl(ne.nextRun)}`:`Unrecognized cron expression (${V})`:Z?"Refreshed by a freshness policy; a cron schedule does not apply":"On demand only, no schedule set",`scope: ${R}`].join(" · ");return t.jsxs(t.Fragment,{children:[t.jsxs(Nt,{title:"Materializations",count:x.isSuccess?P.length:void 0,action:o&&t.jsxs(m.Stack,{direction:"row",spacing:1,alignItems:"center",children:[!W&&!n&&t.jsx(Xf,{scope:R,disabled:!!V,disabledReason:"A schedule requires version scope. Clear the schedule to change it.",isSubmitting:$.isPending,onChange:H=>$.mutateAsync(H==="version"?q.PackageScopeEnum.Version:q.PackageScopeEnum.Package)}),!W&&!n&&t.jsx(ep,{currentSchedule:V,isSubmitting:E.isPending,disabled:Z,disabledReason:"This package declares a freshness policy; a schedule and freshness are mutually exclusive.",onSubmit:H=>E.mutateAsync(H)}),t.jsx(_f,{onSubmit:H=>S.mutateAsync(H),isSubmitting:S.isPending,disabled:B,disabledReason:"A materialization is already pending or running for this package."})]}),children:[v.isSuccess&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:J}),x.isError&&t.jsx(c.ApiErrorDisplay,{error:x.error,context:`${l} > ${a} > Materializations`}),!x.isSuccess&&!x.isError&&t.jsx(c.Loading,{text:"Loading materializations..."}),x.isSuccess&&t.jsx(Yf,{materializations:P,mutable:o,isMutating:D,onStop:H=>j.mutate(H),onDelete:H=>M.mutate(H),onViewDetails:H=>b(H.id??null)})]}),t.jsx(Hf,{materialization:A,buildPlan:_,onClose:()=>b(null)}),t.jsx(m.Snackbar,{open:d!=="",autoHideDuration:6e3,onClose:()=>h(""),message:d})]})}const ho=c.createSvgIcon(t.jsx("path",{d:"M17 7h-4v2h4c1.65 0 3 1.35 3 3s-1.35 3-3 3h-4v2h4c2.76 0 5-2.24 5-5s-2.24-5-5-5m-6 8H7c-1.65 0-3-1.35-3-3s1.35-3 3-3h4V7H7c-2.76 0-5 2.24-5 5s2.24 5 5 5h4zm-3-4h8v2H8z"}));function Ln(e){return bl(e).join(`
|
|
8
|
+
`).trim()||void 0}function bl(e){if(!e)return[];const n=[];for(const r of e){const o=r.value?.trim();if(o){if(o.startsWith('#"'))n.push(o.slice(2).trim());else if(o.startsWith("#(doc)")){let i=o.slice(6).trim();i.length>=2&&i.startsWith('"')&&i.endsWith('"')&&(i=i.slice(1,-1)),n.push(i)}}}return n.filter(r=>r.trim()!=="")}function ua(e){const n=(e??[]).map(r=>({...r,value:r.value?.trim()??""})).filter(r=>r.value.startsWith('##"')||r.value.startsWith("##(doc)")).map(r=>({...r,value:r.value.slice(1)}));return Ln(n)}function np(e,n){const r=e.docParts??[],o=n?.docParts??[];return(o.length>0&&o.length<r.length&&o.every((a,u)=>a===r[u])?r.slice(o.length):r).join(`
|
|
9
|
+
`).trim()||void 0}function fo(e){if(!e)return[];const n=[];for(const r of e){const o=r.value?.trim();if(!o||o.startsWith('#"')||o.startsWith("#(doc)"))continue;const i=o.replace(/^#+@?\s*/,"").trim();i&&!i.startsWith("(")&&n.push(i)}return n}function rp(e){const n=new Set;for(const r of e){const{tag:o,log:i}=td.parseAnnotation([`# ${r}`]);if(i.length>0){const l=/^[A-Za-z_][\w.]*/.exec(r.trim())?.[0];l&&!/^\s*[\w.]+\s*=/.test(r)&&n.add(l);continue}for(const[l,a]of o.entries())a.deleted||(a.eq===void 0?n.add(l):l==="viz"&&typeof a.eq=="string"&&n.add(a.eq))}return[...n]}function sp(e){return wl(e,"persist")}function op(e){return wl(e,"preaggregate")}function wl(e,n){const r=new RegExp(`^#@?\\s*${n}\\b`);return(e??[]).some(o=>r.test(o.value?.trim()??""))}function po(e){const n=lp(e);if(!e||!n)return n;switch(e.kind){case"number_type":return e.subtype?`${n} · ${e.subtype}`:n;case"date_type":case"timestamp_type":case"timestamptz_type":return e.timeframe?`${n} · ${e.timeframe}`:n;case"sql_native_type":return e.sql_type?`sql native · ${e.sql_type}`:"sql native";case"array_type":return`array<${po(e.element_type)??"unknown"}>`;case"record_type":{const r=e.fields.length;return`record · ${r} ${r===1?"field":"fields"}`}default:return n}}function ip(e){if(e?.kind==="record_type")return e.fields.map(n=>`${n.name} ${po(n.type)??""}`.trim()).join(`
|
|
10
|
+
`)}function ap(e){const n=(e??[]).filter(r=>/^#@/.test(r.value?.trim()??""));return fo((e??[]).filter(r=>!n.includes(r)))}function lp(e){return e?.kind?.replace(/_type$/,"")}const un=T.forwardRef(function(n,r){return t.jsx(m.Typography,{ref:r,variant:"body2",...n,sx:{color:"text.secondary",...n.sx}})}),Cr=T.forwardRef(function(n,r){return t.jsx(m.Typography,{ref:r,variant:"caption",...n,sx:{color:"text.secondary",...n.sx}})});function xr({message:e,secondary:n,actions:r}){return t.jsxs(m.Box,{"data-testid":"empty-row",sx:{display:"flex",alignItems:"center",gap:2,flexWrap:"wrap",p:2,border:"1px dashed",borderColor:"divider",borderRadius:2},children:[t.jsxs(m.Box,{sx:{flex:1,minWidth:200},children:[t.jsx(un,{children:e}),n&&t.jsx(un,{sx:{color:"text.secondary",mt:.5},children:n})]}),r&&t.jsx(m.Box,{sx:{display:"flex",gap:1,flexShrink:0,alignItems:"center"},children:r})]})}const Sl="--model-viewer-mono",Dt=`var(${Sl}, ${q.MONO_FONT_FAMILY})`,kl="inherit",wt={micro:"0.6875rem",caption:"0.75rem",small:"0.8125rem",body:"0.875rem",bodyLarge:"1rem"},Js={strong:500},Vr=e=>({tint:`color-mix(in srgb, ${e} 12%, transparent)`,onTint:e}),nt={text:{secondary:"text.secondary",tertiary:"text.disabled"},background:{muted:"action.hover",strong:"action.selected"},accent:{sage:Vr(q.PALETTE.lime)},warning:Vr(q.PALETTE.amber),error:Vr(q.PALETTE.red),info:Vr(q.PALETTE.blue)},as=nt.text.tertiary,cp={positive:{bg:nt.accent.sage.tint,fg:nt.accent.sage.onTint},neutral:{bg:nt.background.strong,fg:nt.text.secondary},warning:{bg:nt.warning.tint,fg:nt.warning.onTint},negative:{bg:nt.error.tint,fg:nt.error.onTint},info:{bg:nt.info.tint,fg:nt.info.onTint},quiet:{bg:nt.background.muted,fg:nt.text.secondary}},At=T.forwardRef(function({tone:n="neutral",voice:r="state",size:o="inline",busy:i=!1,children:l,sx:a,...u},d){const{bg:h,fg:y}=cp[n],b=wt.micro;return t.jsxs(Ge,{ref:d,component:"span","data-pill-tone":n,"data-pill-placement":o,...u,sx:[{display:"inline-flex",alignItems:"center",gap:i?"4px":0,padding:"2px 8px",borderRadius:"999px",bgcolor:h,color:y,flexShrink:0,whiteSpace:"nowrap",...r==="token"?{fontFamily:Dt,fontSize:b}:{fontFamily:kl,fontSize:b,fontWeight:Js.strong}},...Array.isArray(a)?a:[a]],children:[i&&t.jsx(c.CircularProgress,{size:9,thickness:5,sx:{color:"info.main",flexShrink:0},"aria-hidden":!0}),l]})}),up={width:"100%",maxWidth:"1200px",mx:"auto"},eo=3,Tr=1.5,Pn={display:"flex",flexDirection:"column",minWidth:0,minHeight:0,border:"1px solid",borderColor:"divider",borderRadius:2,bgcolor:"background.paper",overflow:"hidden",cursor:"default"},dp={...Pn,border:"none",borderRadius:0,bgcolor:"transparent",overflow:"visible"};function Ut({label:e,value:n,mono:r}){return t.jsxs(t.Fragment,{children:[t.jsx(m.Box,{component:"span",sx:{color:as,fontSize:wt.caption},children:e}),t.jsx(m.Box,{component:"span",sx:{fontFamily:r?Dt:void 0,wordBreak:"break-all"},children:n})]})}function hp(e){const n=e.map(r=>r.name).join(", ");return`Reads the ${e.length===1?"given":"givens"} ${n}, set in the Givens section above`}function Cl({givens:e}){return e.length===0?null:t.jsx(m.Tooltip,{title:hp(e),children:t.jsx(At,{voice:"token",tone:"quiet",sx:{alignSelf:"center",flexShrink:0},children:"given"})})}function fp(e){const n=c.renderGivenDefault(e.type,e.default);return n===void 0?"none — a value is required":n===""?"(empty)":n}function mo({givens:e,framed:n=!0}){return e.length===0?null:t.jsx(m.Box,{"data-testid":"model-viewer-given-card",sx:{...n?Pn:{},p:Tr,display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:"16px",rowGap:"6px",alignItems:"baseline",fontFamily:kl,fontSize:wt.small,color:"text.primary"},children:e.map(r=>t.jsxs(m.Box,{sx:{display:"contents"},children:[t.jsx(Ut,{label:"Given",value:r.name,mono:!0}),r.label&&t.jsx(Ut,{label:"Label",value:r.label}),t.jsx(Ut,{label:"Type",value:r.type,mono:!0}),t.jsx(Ut,{label:"Default",value:fp(r)}),r.description&&t.jsx(Ut,{label:"Description",value:r.description})]},r.name))})}const Tl=T.createContext({});function ls(){return T.useContext(Tl)}function pp(e,n,r=new Set){const o=n?.givens;if(!Array.isArray(o))return[];const i=[];for(const l of o){if(!l||typeof l!="object")continue;const a=l;if(typeof a.name!="string"||!a.name||typeof a.type!="string"||!a.type||r.has(a.name))continue;const u=Array.isArray(a.annotations)?a.annotations.filter(d=>typeof d=="string"):void 0;i.push({name:a.name,type:a.type,modelFile:e,...u&&{annotations:u},...typeof a.default=="string"&&{default:a.default},...a.required===!0&&{required:!0},...typeof a.label=="string"&&a.label&&{label:a.label},...typeof a.description=="string"&&a.description&&{description:a.description},...(a.control==="select"||a.control==="multiselect")&&{control:a.control},...typeof a.rangeMin=="number"&&{rangeMin:a.rangeMin},...typeof a.rangeMax=="number"&&{rangeMax:a.rangeMax},...a.suggest&&typeof a.suggest=="object"&&{suggest:a.suggest}})}return i}function mp(e){return new Map(e.map(n=>[n.name,n.type]))}function gp(e,n){const r=new Map(Array.from(e).filter(([l,a])=>n.has(l)&&!(a===""&&n.get(l)==="string"))),o=c.givensToRequest(r,n),i=Object.entries(o).sort(([l],[a])=>l<a?-1:l>a?1:0);return i.length>0?Object.fromEntries(i):void 0}function go(e){return e&&Object.keys(e).length>0?JSON.stringify(e):""}function yp(e){if(!e)return[];const n=[];for(const r of e){const o=r.value?.trim();if(!o||!o.startsWith("#(filter)"))continue;const i=vp(o.slice(9).trim());i&&n.push(i)}return n}const xp=new Set(["equal","in","like","greater_than","less_than"]);function vp(e){let n,r,o,i=!1,l=!1;for(const a of bp(e)){if(a==="implicit"){i=!0;continue}if(a==="required"){l=!0;continue}const u=a.indexOf("=");if(u<=0)continue;const d=a.slice(0,u).trim();let h=a.slice(u+1).trim();h.length>=2&&h.startsWith('"')&&h.endsWith('"')&&(h=h.slice(1,-1)),d==="name"?n=h:d==="dimension"?r=h:d==="type"&&xp.has(h)&&(o=h)}return!r||!o?null:{name:n??r,dimension:r,type:o,implicit:i,required:l}}function bp(e){const n=[];let r="",o=!1;for(const i of e){if(i==='"'){o=!o,r+=i;continue}if(!o&&/\s/.test(i)){r&&n.push(r),r="";continue}r+=i}return r&&n.push(r),n}const wp=/^#\(index(_values)?\b/;function Sp(e){return!("annotations"in e)||!e.annotations?!1:e.annotations.some(n=>wp.test(n.value?.trim()??""))}function kp(e){const n=new Map;for(const r of e){const o=yp(r.annotations).filter(i=>i.required&&!i.implicit).map(i=>i.name);o.length>0&&n.set(r.name,o)}return n}function Cp(e){return new Set(e.map(n=>n.name))}function jl(e){const n=new Map;for(const r of e){if(!r.source)continue;let o=n.get(r.source);o||(o=new Map,n.set(r.source,o)),o.set(r.name,r)}return n}function Ir(e){let n="",r=0;const o=(i,l)=>{n+=e.slice(i,l).replace(/[^\n]/g," "),r=l};for(;r<e.length;){const i=e[r],l=e.slice(r,r+2);if(l==="//"||l==="--"){const a=e.indexOf(`
|
|
11
11
|
`,r);o(r,a===-1?e.length:a)}else if(l==="/*"){const a=e.indexOf("*/",r+2);o(r,a===-1?e.length:a+2)}else if(e.startsWith('"""',r)){const a=e.indexOf('"""',r+3),u=a===-1?e.length:a;n+='"""',r+=3,o(r,u),a!==-1&&(n+='"""',r+=3)}else if(i==="'"||i==='"'){n+=i;let a=r+1;for(;a<e.length&&e[a]!==i&&e[a]!==`
|
|
12
12
|
`;)a+=e[a]==="\\"&&e[a+1]!==`
|
|
13
13
|
`?2:1;o(r+1,Math.min(a,e.length)),e[r]===i&&(n+=i,r+=1)}else if(i==="`"){let a=r+1;for(;a<e.length&&e[a]!=="`"&&e[a]!==`
|
|
14
|
-
`;)a+=e[a]==="\\"?2:1;const u=Math.min(a+1,e.length);n+=e.slice(r,u),r=u}else n+=i,r+=1}return n}function
|
|
14
|
+
`;)a+=e[a]==="\\"?2:1;const u=Math.min(a+1,e.length);n+=e.slice(r,u),r=u}else n+=i,r+=1}return n}function mn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function dn(e,n){if(!e||n.length===0)return[];const r=Ir(e);return n.filter(o=>new RegExp(`\\$${mn(o.name)}(?![A-Za-z0-9_])`).test(r))}function Tp(e,n){if(!e)return new Set;const r=Ir(e);return new Set(n.filter(o=>new RegExp(`(?<![A-Za-z0-9_$.])\`?${mn(o.name)}\`?\\s*::`).test(r)).map(o=>o.name))}function jp(e,n,r,o){if(!e)return{givens:[...n],unknown:new Set(n.map(b=>b.name))};const i=Ir(e),l=new Set(dn(e,n).map(b=>b.name)),a=new Set(l),u=new Set,d=b=>{a.add(b),l.has(b)||u.add(b)};for(const[b,x]of r??[])if(new RegExp(`(?<![A-Za-z0-9_$.])\`?${mn(b)}\`?(?![A-Za-z0-9_])`).test(i)){for(const k of x)a.add(k.name);for(const k of o?.get(b)??[])d(k)}const h=/^\s*query\s*:\s*`?[A-Za-z_]\w*`?\s+is\s+/.exec(i),y=h?to(i.slice(h[0].length)):void 0;if(y===void 0||y!==null&&!r?.has(y))for(const b of n)d(b.name);return{givens:n.filter(b=>a.has(b.name)),unknown:u}}function Mp(e,n,r){if(r.length===0)return{givens:[],unknown:new Set};const o=Ml(e,n,r);return o?o.unresolved?{givens:[...r],unknown:new Set(r.filter(i=>!o.readHere.has(i.name)).map(i=>i.name))}:{givens:r.filter(i=>o.readHere.has(i.name)||!o.readByAnySource.has(i.name)),unknown:new Set}:{givens:[...r],unknown:new Set(r.map(i=>i.name))}}function Op(e,n,r,o){const i=new Map,l=Ml(e,n,r);if(!l)return i;const a=new Set;for(const u of l.reached)if(!(u!==n&&!o.has(u)))for(const d of dn(l.blocks.get(u),r))a.add(d.name);for(const u of l.reached)if(!(u===n||o.has(u)))for(const d of dn(l.blocks.get(u),r))a.has(d.name)||i.set(d.name,[...i.get(d.name)??[],u]);return i}function Ml(e,n,r){if(!e||r.length===0)return;const o=Ip(Ir(e));if(!o.has(n))return;const i=new Set;for(const h of o.values())for(const y of dn(h,r))i.add(y.name);const l=new Set;let a=!1;const u=h=>{if(l.has(h))return;l.add(h);const y=o.get(h);if(!y)return;const b=Dp(y,h,o);b.unresolved&&(a=!0);for(const x of b.sources)u(x)};u(n);const d=new Set;for(const h of l)for(const y of dn(o.get(h),r))d.add(y.name);return{blocks:o,reached:l,readHere:d,readByAnySource:i,unresolved:a}}const Ep=/^(?:source|query|run|given|import)\b|^#/;function Ip(e){const n=new Map;let r,o=0;const i=()=>{r&&n.set(r.name,r.lines.join(`
|
|
15
15
|
`)),r=void 0};for(const l of e.split(`
|
|
16
|
-
`)){const a=o===0?/^source\s*:\s*`?([A-Za-z_]\w*)`?\s+is\b/.exec(l):null;a?(i(),r={name:a[1],lines:[l]}):o===0&&km.test(l)?i():r&&r.lines.push(l);for(const u of l)u==="{"?o+=1:u==="}"&&(o=Math.max(0,o-1))}return i(),n}function jm(e,n,r){const o=[];let i=!1;const l=d=>{d===null||d===n||(d!==void 0&&r.has(d)?o.push(d):i=!0)},a=new RegExp(`source\\s*:\\s*\`?${pn(n)}\`?\\s+is\\s+`).exec(e);a&&l(to(e.slice(a.index+a[0].length)));const u=/join_\w+\s*:\s*`?([A-Za-z_]\w*)`?(\s+is\s+)?/g;for(let d=u.exec(e);d;d=u.exec(e))l(d[2]?to(e.slice(d.index+d[0].length)):d[1]);return{sources:o,unresolved:i}}function to(e){const n=/^`?([A-Za-z_]\w*)`?/.exec(e);if(!n)return;const r=e.slice(n[0].length).trimStart();if(r.startsWith("."))return null;if(!r.startsWith("("))return n[1]}const Tr={"&:focus-visible":{outline:"2px solid",outlineColor:"primary.main",outlineOffset:"-2px"}},jl=j.createContext(void 0);function yo({layer:e,title:n,children:r,testId:o}){const i=j.useContext(jl);if(!i||!e||!i.layers.includes(e))return t.jsx(p.Tooltip,{title:n,children:t.jsx(p.Box,{component:"span",tabIndex:0,role:"img","aria-label":n,"data-testid":o,sx:{display:"inline-flex",borderRadius:1,...Tr},children:r})});const l=i.openLayer===e;return t.jsx(p.Tooltip,{title:n,children:t.jsx(p.Box,{component:"button",type:"button",onClick:()=>i.toggle(e),"aria-expanded":l,"aria-controls":i.cardId,"aria-label":`${n} ${l?"Hide":"Show"} details.`,"data-testid":o,"data-header-chip":e,sx:{appearance:"none",border:"none",background:"none",font:"inherit",p:0,cursor:"pointer",display:"inline-flex",alignItems:"center",borderRadius:1,"& [data-pill-tone]":{transition:"filter 120ms ease",...l?{filter:"brightness(0.9)"}:{}},"&:hover [data-pill-tone]":{filter:l?"brightness(0.9)":"brightness(0.94)"},...Tr},children:r})})}function Tm(e){try{const{data:n}=JSON.parse(e);return n?.kind==="array_cell"?n.array_value.length:n?.kind==="record_cell"?1:0}catch{return}}const Om={authorize:[],accessFilter:[]};function da(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"&&n.trim()!==""):[]}function Mm(e){const n=new Map,r=e?.sources;if(!Array.isArray(r))return n;for(const o of r){if(!o||typeof o!="object")continue;const i=o;if(typeof i.name!="string"||!i.name)continue;const l=da(i.authorize),a=da(i.accessFilter);l.length===0&&a.length===0||n.set(i.name,{authorize:l,accessFilter:a})}return n}function Qr(e,n){return n&&e?.get(n)||Om}function Yt(e){return!!e&&e.authorize.some(n=>n.trim()!=="true")}function Jt(e){return!!e&&e.accessFilter.length>0}const ha=/^\(?\s*(?:'([^']*)'|"([^"]*)")\s+in\s+\$GROUPS\s*\)?$/;function Em(e){const n=e.trim();if(n==="false")return"no one";const r=ha.exec(n);if(r)return`members of ${r[1]??r[2]}`;for(const o of["or","and"]){const i=n.split(new RegExp(`\\s+${o}\\s+`));if(i.length<2)continue;const l=i.map(a=>ha.exec(a.trim()));if(l.every(a=>a)){const a=l.map(u=>u[1]??u[2]);return o==="or"?`members of ${a.slice(0,-1).join(", ")} or ${a[a.length-1]}`:`members of all of ${a.join(", ")}`}}}function Tl(e){const n=e.authorize.filter(o=>o.trim()!=="true").map(o=>Em(o)??"readers its access rule admits");return Array.from(new Set(n)).join(", and ")}const Ol="Only some readers can query this source",Ml="Each reader sees only the rows they're allowed to see";function Im(e,n){return e?Yt(n)?`You can't access ${e}. It is restricted to ${Tl(n)}; ask an administrator of this package for access.`:`You can't access ${e}. Ask an administrator of this package for access.`:"You don't have access to run this. Ask an administrator of this package for access."}function Dm(e,n){if(!(!Jt(e)||n===void 0))return Tm(n)===0?"Filtered to your rows: this source shows each reader only the rows they're allowed to see.":void 0}function El(e){return Yt(e)||Jt(e)}function $m(e,n){return`This join doesn't apply the ${Yt(n)&&Jt(n)?"access rule and row filter":Yt(n)?"access rule":"row filter"} on ${e}: its rows are read under this source's rules.`}function Fm({access:e}){return t.jsxs(t.Fragment,{children:[Yt(e)&&t.jsx(fa,{label:"Restricted",meaning:Ol}),Jt(e)&&t.jsx(fa,{label:"Row filtered",meaning:Ml})]})}function fa({label:e,meaning:n}){return t.jsx(yo,{layer:"access",title:`${e}: ${n}`,testId:`source-access-chip-${e==="Restricted"?"restricted":"row-filtered"}`,children:t.jsx($t,{tone:"neutral",size:"header",children:e})})}function Il({access:e}){return t.jsxs(t.Fragment,{children:[Yt(e)&&t.jsx(p.Tooltip,{title:`Restricted: ${Ol}`,children:t.jsx($t,{voice:"token",tone:"neutral",sx:{alignSelf:"center"},children:"Restricted"})}),Jt(e)&&t.jsx(p.Tooltip,{title:`Row filtered: ${Ml}`,children:t.jsx($t,{voice:"token",tone:"neutral",sx:{alignSelf:"center"},children:"Row filtered"})})]})}function Am(e){return[Yt(e)&&"restricted",Jt(e)&&"row filtered"].filter(Boolean).map(n=>`, ${n}`).join("")}function Rm({access:e,showRules:n}){const r=Yt(e),o=Jt(e);return!r&&!o?null:t.jsxs(p.Box,{"data-testid":"source-access-facts",sx:{display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:"16px",rowGap:"6px",alignItems:"baseline"},children:[r&&t.jsx(Ut,{label:"Restricted to",value:Tl(e)}),r&&n&&e.authorize.filter(i=>i.trim()!=="true").map((i,l)=>t.jsx(Ut,{label:"Access rule",value:i,mono:!0},`a${l}`)),o&&t.jsx(Ut,{label:"Rows",value:"Rows are filtered for each reader"}),o&&n&&e.accessFilter.map((i,l)=>t.jsx(Ut,{label:"Row filter",value:i,mono:!0},`f${l}`))]})}const ma="Private",Lm="index.malloy doesn't export this file, so only people who can edit the package see it.";function pa(){return t.jsx(yo,{title:`${ma}: ${Lm}`,testId:"model-viewer-off-surface",children:t.jsx($t,{tone:"warning",size:"header",children:ma})})}const ga="Public",_m="index.malloy exports this source, so everyone who can read the package can query it.";function Nm(){return t.jsx(yo,{title:`${ga}: ${_m}`,testId:"model-viewer-public-surface",children:t.jsx($t,{tone:"positive",size:"header",children:ga})})}function Pm(e){const n=j.useRef(e);return e!==void 0&&(n.current=e),n.current}function $s({title:e,titleAdornments:n,kindLabel:r,meta:o,doc:i,provenance:l,actions:a,status:u,headingLevel:d="h1",modelDoc:h,access:y,showRules:b=!1,isSource:x=!0,offSurface:v,publicSurface:k=!1}){const C=Yt(y)||Jt(y),S=C?["access"]:[],[T,O]=j.useState(void 0),M=T!==void 0&&S.includes(T)?T:void 0,E=Pm(M),R=j.useId(),P={openLayer:M,layers:S,toggle:_=>O(V=>V===_?void 0:_),cardId:R},F=C||v||k||!!u,B=q.usePublisherTheme().theme.ui.type.pageTitle,D=typeof B.fontSize=="number"?`${B.fontSize}px`:B.fontSize;return t.jsxs(p.Box,{children:[t.jsxs(p.Box,{"data-testid":"model-viewer-source-heading",sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:1.5,pt:eo,pb:.5},children:[t.jsx(p.Box,{component:d,sx:{m:0,fontSize:d==="h1"?D:`calc(${D} * 0.8)`,fontWeight:B.fontWeight??600,lineHeight:1.25,color:"text.primary",fontFamily:Dt,minWidth:0,overflowWrap:"anywhere"},children:e}),n,a&&t.jsx(p.Box,{sx:{ml:"auto",display:"flex",alignItems:"center",gap:1},children:a})]}),!x&&v&&t.jsx(p.Box,{sx:{display:"flex",alignItems:"center",pt:.5,pb:1},children:t.jsx(pa,{})}),x&&F&&t.jsx(jl.Provider,{value:P,children:t.jsxs(p.Box,{"data-testid":"model-viewer-status-row",sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:1.5,pt:.5,pb:1},children:[t.jsx(Fm,{access:y}),v&&t.jsx(pa,{}),k&&t.jsx(Nm,{}),u]})}),h&&t.jsx(ya,{doc:h,label:"model description",testId:"model-viewer-model-doc"},`model:${h}`),i&&t.jsx(ya,{doc:i},i),(r!==void 0||o!==void 0||l)&&t.jsxs(p.Box,{"data-testid":"model-viewer-source-meta",sx:{display:"flex",alignItems:"center",gap:.75,minWidth:0,pb:2,fontSize:wt.body,color:"text.secondary",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[r!==void 0&&t.jsx(p.Box,{component:"span","data-testid":"model-viewer-source-kind",children:r}),r!==void 0&&(o!==void 0||l)&&t.jsx(p.Box,{component:"span","aria-hidden":!0,children:"·"}),o!==void 0&&t.jsx(p.Box,{component:"span",children:o}),o!==void 0&&l&&t.jsx(p.Box,{component:"span","aria-hidden":!0,children:"·"}),l&&t.jsx(p.Box,{component:"span",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:l})]}),t.jsx(p.Collapse,{in:M!==void 0,timeout:"auto",unmountOnExit:!0,children:t.jsx(p.Box,{id:R,"data-testid":"model-viewer-source-detail","data-layer":E??void 0,sx:{...Pn,p:jr,mb:2},children:E==="access"&&y&&t.jsx(Rm,{access:y,showRules:b})})})]})}const zm=2;function ya({doc:e,label:n="description",testId:r="model-viewer-source-doc"}){const[o,i]=j.useState(!1),[l,a]=j.useState(!1),u=j.useRef(null);return j.useEffect(()=>{const d=u.current;if(!d||o)return;const h=()=>a(d.scrollHeight>d.clientHeight+1);if(h(),typeof ResizeObserver>"u")return;const y=new ResizeObserver(h);return y.observe(d),()=>y.disconnect()},[o,e]),t.jsxs(p.Box,{"data-testid":r,sx:{pb:.5},children:[t.jsx(p.Box,{ref:u,sx:{fontSize:wt.body,lineHeight:1.5,color:"text.secondary",whiteSpace:"pre-line",...o?{}:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:zm,overflow:"hidden"}},children:Dl(e)}),(l||o)&&t.jsx(p.Box,{component:"button",type:"button",onClick:()=>i(!o),"aria-expanded":o,"aria-label":o?`Show less of the ${n}`:`Show the full ${n}`,sx:{all:"unset",cursor:"pointer",fontSize:wt.small,color:"text.secondary",textDecoration:"underline","&:hover":{color:"text.primary"},"&:focus-visible":{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}},children:o?"Less":"More"})]})}function Dl(e){return e.split(/(`[^`\n]+`)/g).map((n,r)=>/^`[^`]+`$/.test(n)?t.jsx(p.Box,{component:"code",sx:{fontFamily:Dt,fontSize:"0.92em",color:"text.primary"},children:n.slice(1,-1)},r):n)}function cs(e){const n=e?.response?.status;return typeof n=="number"?n:void 0}function Wm(e){const n=cs(e);return n===403||n===404}function qm(e,n){if(!e?.modelPath||!e.sourceName)return{kind:"unknown"};const r=n.get(e.modelPath);return r?r.has(e.sourceName)?{kind:"link"}:{kind:"join-only"}:{kind:"unknown"}}const xo=j.createContext([]),ts="text.primary",ur=e=>({main:e,tint:`color-mix(in srgb, ${e} 12%, transparent)`,onTint:e}),Fn={steel:ur(q.PALETTE.cyan),sage:ur(q.PALETTE.lime),brown:ur(q.PALETTE.slate),olive:ur(q.PALETTE.violet),amber:ur(q.PALETTE.amber)};function xa(e){return e==="measure"?Fn.sage:e==="calculate"?Fn.amber:e==="view"?Fn.olive:Fn.steel}const va=["steel","brown","olive","sage"];function Bm(e){return va[e%va.length]}const $l={small:13,caption:12},Vm={fontFamily:Dt,fontSize:$l.small,fontWeight:500,color:ts},Fl={fontSize:$l.caption,color:"text.secondary"};function _n({label:e,count:n,level:r="h2",testId:o,action:i,children:l}){return n===0?null:r==="h3"?t.jsxs(p.Box,{component:"section","aria-label":e,"data-testid":o,sx:{mb:2},children:[t.jsx(p.Box,{component:"h3",sx:{m:0,mb:1,fontSize:wt.bodyLarge,fontWeight:Js.strong,color:ts},children:e}),l]}):t.jsxs(p.Box,{component:"section","aria-label":e,"data-testid":o,sx:{mb:3},children:[t.jsxs(p.Box,{sx:{mb:2},children:[t.jsx(p.Box,{component:"h2",sx:{m:0,fontSize:"1.25rem",fontWeight:Js.strong,color:ts},children:e}),i&&t.jsx(p.Box,{sx:{...Fl,mt:.25,display:"flex",alignItems:"center"},children:i})]}),l]})}function vr(e,n){return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} ${n} ${e.at(-1)}`}function ba(e,n){return`${e.label??e.name}: ${c.describeGivenValue(e,n)}`}const Hr=e=>e.label??e.name;function Al(e,n,r=void 0,o=void 0,i=!1,l="source"){const a=e??[],u=M=>r?.[M.name]!==void 0,d=M=>o?.has(M.name)===!0,h=a.filter(M=>!u(M)&&M.default===void 0),y=n??[],b=y.length===0&&h.length>0&&h.every(M=>d(M)),x=i&&b?h:[];if(x.length===0&&(h.length>0||y.length>0)){const M=h.length>0?`a value for ${h.length===1?"the given":"the givens"} ${h.map(Hr).join(", ")}`:"",E=y.length>0?`${y.length===1?"the required filter":"the required filters"} ${y.join(", ")}`:"",R=h.filter(d),P=R.length===0?"":R.length===h.length?` This page can't tell whether this ${l} reads ${h.length===1?"it":"them"}.`:` This page can't tell whether this ${l} reads ${vr(R.map(Hr),"or")}.`;let F;return E===""?F=`This needs ${M}. Set ${h.length===1?"it":"them"} in the Givens section above.${P}`:M===""?F=`This needs ${E}, which this page can't set; open the source in a dashboard or notebook.`:F=`This needs ${M} (set ${h.length===1?"it":"them"} in the Givens section above) and ${E}, which this page can't set; open the source in a dashboard or notebook.${P}`,{kind:"blocked",reason:F,canRunAnyway:b}}const v=M=>M.length>0?`${M.length===1?"the default":"the defaults"} ${M.map(E=>ba(E)).join(", ")}`:"",k=[];x.length>0&&k.push(`Ran without a value for ${x.length===1?"the given":"the givens"} ${vr(x.map(Hr),"and")}, which this page can't tell this ${l} reads.`);const C=a.filter(M=>!x.includes(M)),S=C.filter(M=>!d(M)),T=v(S.filter(M=>!u(M)));T!==""&&k.push(`Ran with ${T}.`);const O=C.filter(d);if(O.length>0){const M=[O.filter(u).map(E=>ba(E,r?.[E.name])).join(", "),v(O.filter(E=>!u(E)))].filter(E=>E!=="").join(" and ");k.push(O.length===C.length?`This page can't tell which givens this ${l} reads. Where it reads one, it ran with ${M}.`:`This page can't tell whether this ${l} reads ${vr(O.map(Hr),"or")}. Where it does, it ran with ${M}.`)}return k.length>0?{kind:"noted",note:k.join(" ")}:{kind:"ok"}}const Hm=400;function Um({givens:e,unknown:n,inheritedFrom:r,values:o,onChange:i,onReset:l,environmentName:a,packageName:u,modelPath:d,versionId:h,declaredTypes:y}){const b=j.useMemo(()=>[...e],[e]),x=j.useMemo(()=>{const F=e.filter(B=>n?.has(B.name));if(F.length!==0)return F.length===e.length?"This page can't tell which of these givens this source reads, so a value set here may not apply to it.":`This page can't tell whether this source reads ${vr(F.map(B=>B.label??B.name),"or")}, so a value set for ${F.length===1?"it":"them"} may not apply.`},[e,n]),[v,k]=j.useState(()=>new Set),C=j.useCallback(F=>k(B=>B.has(F)?B:new Set([...B,F])),[]),S=c.useSettled(o,Hm),T=j.useMemo(()=>({values:S,declaredTypes:y}),[S,y]),{options:O,isLoading:M,failed:E,truncated:R,search:P}=c.useSuggestOptions(a,u,d,b,h,T,void 0,v,!0);return t.jsxs(_n,{label:"Givens",count:e.length,testId:"model-givens-section",children:[t.jsx(p.Box,{sx:{"& .MuiPaper-root":{borderColor:"divider"}},children:t.jsx(c.GivensPanel,{layout:"bar",givens:b,values:o,onChange:i,onReset:l,options:O,optionsLoading:M,optionsFailed:E,optionsTruncated:R,optionSearch:P,onControlOpen:C})}),x&&t.jsx(un,{"data-testid":"model-givens-unknown",sx:{mt:1},children:x}),r&&r.size>0&&t.jsx(un,{"data-testid":"model-givens-inherited",sx:{mt:1},children:[...r].map(([F,B])=>B.length===1?`${F} is inherited from ${B[0]}, which this model doesn't export.`:`${F} is inherited from ${B.slice(0,-1).join(", ")} and ${B.at(-1)}, none of which this model exports.`).join(" ")})]})}const Gm="A source is a queryable entry point into the model — pick one to browse its dimensions, measures, views and joins.";function Ym(e,n=!1){return e===0?"No sources":`${e} ${n?"public ":""}source${e===1?"":"s"}`}const Km=c.createSvgIcon(t.jsx("path",{d:"M21 11h-1.5v-.5h-2v3h2V13H21v1c0 .55-.45 1-1 1h-3c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1zM8 10v5H6.5v-1.5h-2V15H3v-5c0-.55.45-1 1-1h3c.55 0 1 .45 1 1m-1.5.5h-2V12h2zm7 1.5c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1h-4V9h4c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1M11 10.5v.75h2v-.75zm2 2.25h-2v.75h2z"})),Qm=c.createSvgIcon(t.jsx("path",{d:"M6 6v2h8.59L5 17.59 6.41 19 16 9.41V18h2V6z"})),Zm=c.createSvgIcon(t.jsx("path",{d:"M4 9h4v11H4zm12 4h4v7h-4zm-6-9h4v16h-4z"})),Xm=c.createSvgIcon([t.jsx("path",{d:"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 16H5V5h14z"},"0"),t.jsx("path",{d:"M6.25 7.72h5v1.5h-5zM13 15.75h5v1.5h-5zm0-2.5h5v1.5h-5zM8 18h1.5v-2h2v-1.5h-2v-2H8v2H6V16h2zm6.09-7.05 1.41-1.41 1.41 1.41 1.06-1.06-1.41-1.42 1.41-1.41L16.91 6 15.5 7.41 14.09 6l-1.06 1.06 1.41 1.41-1.41 1.42z"},"1")]),Rl=c.createSvgIcon(t.jsx("path",{d:"M20 3h-1V1h-2v2H7V1H5v2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 18H4V10h16zm0-13H4V5h16z"})),Jm=c.createSvgIcon(t.jsx("path",{d:"M17 20.41 18.41 19 15 15.59 13.59 17zM7.5 8H11v5.59L5.59 19 7 20.41l6-6V8h3.5L12 3.5z"})),ep=c.createSvgIcon(t.jsx("path",{d:"M9.4 16.6 4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0 4.6-4.6-4.6-4.6L16 6l6 6-6 6z"})),tp=c.createSvgIcon(t.jsx("path",{d:"M15 4v2h3v12h-3v2h5V4zM4 20h5v-2H6V6h3V4H4z"})),np=c.createSvgIcon(t.jsx("path",{d:"M4 7v2c0 .55-.45 1-1 1H2v4h1c.55 0 1 .45 1 1v2c0 1.65 1.35 3 3 3h3v-2H7c-.55 0-1-.45-1-1v-2c0-1.3-.84-2.42-2-2.83v-.34C5.16 11.42 6 10.3 6 9V7c0-.55.45-1 1-1h3V4H7C5.35 4 4 5.35 4 7m17 3c-.55 0-1-.45-1-1V7c0-1.65-1.35-3-3-3h-3v2h3c.55 0 1 .45 1 1v2c0 1.3.84 2.42 2 2.83v.34c-1.16.41-2 1.52-2 2.83v2c0 .55-.45 1-1 1h-3v2h3c1.65 0 3-1.35 3-3v-2c0-.55.45-1 1-1h1v-4z"})),rp=c.createSvgIcon(t.jsx("path",{d:"m12 8-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z"})),sp=c.createSvgIcon(t.jsx("path",{d:"M4 10.5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5m0-6c-.83 0-1.5.67-1.5 1.5S3.17 7.5 4 7.5 5.5 6.83 5.5 6 4.83 4.5 4 4.5m0 12c-.83 0-1.5.68-1.5 1.5s.68 1.5 1.5 1.5 1.5-.68 1.5-1.5-.67-1.5-1.5-1.5M7 19h14v-2H7zm0-6h14v-2H7zm0-8v2h14V5z"})),Ll=c.createSvgIcon(t.jsx("path",{d:"M7.41 8.59 12 13.17l4.59-4.58L18 10l-6 6-6-6z"})),op=c.createSvgIcon(t.jsx("path",{d:"M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2M9 6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9zm9 14H6V10h12zm-6-3c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2"})),ip=c.createSvgIcon(t.jsx("path",{d:"m20.5 10 .5-2h-4l1-4h-2l-1 4h-4l1-4h-2L9 8H5l-.5 2h4l-1 4h-4L3 16h4l-1 4h2l1-4h4l-1 4h2l1-4h4l.5-2h-4l1-4zm-7 4h-4l1-4h4z"})),_l=c.createSvgIcon(t.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8m.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"})),ap=c.createSvgIcon([t.jsx("path",{d:"m21.41 11.41-8.83-8.83c-.37-.37-.88-.58-1.41-.58H4c-1.1 0-2 .9-2 2v7.17c0 .53.21 1.04.59 1.41l8.83 8.83c.78.78 2.05.78 2.83 0l7.17-7.17c.78-.78.78-2.04-.01-2.83M12.83 20 4 11.17V4h7.17L20 12.83z"},"0"),t.jsx("circle",{cx:"6.5",cy:"6.5",r:"1.5"},"1")]),Nl=c.createSvgIcon(t.jsx("path",{d:"M17 6H7c-3.31 0-6 2.69-6 6s2.69 6 6 6h10c3.31 0 6-2.69 6-6s-2.69-6-6-6m0 10H7c-2.21 0-4-1.79-4-4s1.79-4 4-4h10c2.21 0 4 1.79 4 4s-1.79 4-4 4m0-7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3"})),lp=c.createSvgIcon(t.jsx("path",{d:"M3 17v2h6v-2zM3 5v2h10V5zm10 16v-2h8v-2h-8v-2h-2v6zM7 9v2H3v2h4v2h2V9zm14 4v-2H11v2zm-6-4h2V7h4V5h-4V3h-2z"})),Pl=c.createSvgIcon(t.jsx("path",{d:"M3 5v14h18V5zm5.33 12H5V7h3.33zm5.34 0h-3.33V7h3.33zM19 17h-3.33V7H19z"})),cp=c.createSvgIcon(t.jsx("path",{d:"M12 5.99 19.53 19H4.47zM12 2 1 21h22zm1 14h-2v2h2zm0-6h-2v4h2z"}));function rt(e,n){const r=({size:o,...i})=>t.jsx(e,{...i,sx:{fontSize:o}});return r.displayName=n,r}const up=rt(Km,"IconText"),wa=rt(Qm,"IconOpen"),zl=rt(Zm,"IconResult"),dp=rt(Xm,"IconCalculation"),hp=rt(Rl,"IconDate"),fp=rt(Jm,"IconJoin"),mp=rt(ep,"IconCode"),pp=rt(tp,"IconList"),gp=rt(np,"IconRecord"),yp=rt(rp,"IconCollapse"),xp=rt(c.ExpandMoreIcon,"IconExpand"),vp=rt(sp,"IconFields"),bp=rt(Ll,"IconDropdown"),wp=rt(op,"IconLock"),Wl=rt(ip,"IconNumber"),Sp=rt(_l,"IconTimestamp"),kp=rt(ap,"IconValues"),Cp=rt(Nl,"IconBoolean"),jp=rt(lp,"IconGivens"),ql=rt(Pl,"IconColumn");rt(cp,"IconWarning");const Or=j.createContext(void 0);function vo(){const[e,n]=j.useState(!1),r=j.useContext(Or),[o,i]=j.useState(r?.n);return r&&r.n!==o&&(i(r.n),n(r.open)),[e,n]}function Tp({allOpen:e,onToggle:n,noun:r,disabledReason:o}){const i=e?t.jsx(yp,{size:16,"aria-hidden":!0}):t.jsx(xp,{size:16,"aria-hidden":!0});return t.jsx(p.Tooltip,{title:o??"",children:t.jsx("span",{children:t.jsxs(p.ButtonBase,{disabled:!!o,onClick:n,"aria-label":o??`${e?"Collapse":"Expand"} all ${r[1]}`,sx:{font:"inherit",color:"text.secondary",gap:.25,borderRadius:1,"&:hover":{color:"text.primary",textDecoration:"underline"},...Tr,"&.Mui-disabled":{opacity:.5}},children:[i,e?"Collapse all":"Expand all"]})})})}function ns({noun:e,disabledReason:n}){const[r,o]=j.useState(void 0),i=r?.open??!1;return{command:r,action:t.jsx(Tp,{allOpen:i,onToggle:()=>o({open:!i,n:(r?.n??0)+1}),noun:e,disabledReason:n})}}let Fs;function Op(e,n){if(Fs?.text===n)return Fs.parsed;const r=n.replace(/\r\n/g,`
|
|
16
|
+
`)){const a=o===0?/^source\s*:\s*`?([A-Za-z_]\w*)`?\s+is\b/.exec(l):null;a?(i(),r={name:a[1],lines:[l]}):o===0&&Ep.test(l)?i():r&&r.lines.push(l);for(const u of l)u==="{"?o+=1:u==="}"&&(o=Math.max(0,o-1))}return i(),n}function Dp(e,n,r){const o=[];let i=!1;const l=d=>{d===null||d===n||(d!==void 0&&r.has(d)?o.push(d):i=!0)},a=new RegExp(`source\\s*:\\s*\`?${mn(n)}\`?\\s+is\\s+`).exec(e);a&&l(to(e.slice(a.index+a[0].length)));const u=/join_\w+\s*:\s*`?([A-Za-z_]\w*)`?(\s+is\s+)?/g;for(let d=u.exec(e);d;d=u.exec(e))l(d[2]?to(e.slice(d.index+d[0].length)):d[1]);return{sources:o,unresolved:i}}function to(e){const n=/^`?([A-Za-z_]\w*)`?/.exec(e);if(!n)return;const r=e.slice(n[0].length).trimStart();if(r.startsWith("."))return null;if(!r.startsWith("("))return n[1]}const jr={"&:focus-visible":{outline:"2px solid",outlineColor:"primary.main",outlineOffset:"-2px"}},Ol=T.createContext(void 0);function yo({layer:e,title:n,children:r,testId:o}){const i=T.useContext(Ol);if(!i||!e||!i.layers.includes(e))return t.jsx(m.Tooltip,{title:n,children:t.jsx(m.Box,{component:"span",tabIndex:0,role:"img","aria-label":n,"data-testid":o,sx:{display:"inline-flex",borderRadius:1,...jr},children:r})});const l=i.openLayer===e;return t.jsx(m.Tooltip,{title:n,children:t.jsx(m.Box,{component:"button",type:"button",onClick:()=>i.toggle(e),"aria-expanded":l,"aria-controls":i.cardId,"aria-label":`${n} ${l?"Hide":"Show"} details.`,"data-testid":o,"data-header-chip":e,sx:{appearance:"none",border:"none",background:"none",font:"inherit",p:0,cursor:"pointer",display:"inline-flex",alignItems:"center",borderRadius:1,"& [data-pill-tone]":{transition:"filter 120ms ease",...l?{filter:"brightness(0.9)"}:{}},"&:hover [data-pill-tone]":{filter:l?"brightness(0.9)":"brightness(0.94)"},...jr},children:r})})}function Ap(e){try{const{data:n}=JSON.parse(e);return n?.kind==="array_cell"?n.array_value.length:n?.kind==="record_cell"?1:0}catch{return}}const Rp={authorize:[],accessFilter:[]};function da(e){return Array.isArray(e)?e.filter(n=>typeof n=="string"&&n.trim()!==""):[]}function $p(e){const n=new Map,r=e?.sources;if(!Array.isArray(r))return n;for(const o of r){if(!o||typeof o!="object")continue;const i=o;if(typeof i.name!="string"||!i.name)continue;const l=da(i.authorize),a=da(i.accessFilter);l.length===0&&a.length===0||n.set(i.name,{authorize:l,accessFilter:a})}return n}function Qr(e,n){return n&&e?.get(n)||Rp}function Yt(e){return!!e&&e.authorize.some(n=>n.trim()!=="true")}function Jt(e){return!!e&&e.accessFilter.length>0}const ha=/^\(?\s*(?:'([^']*)'|"([^"]*)")\s+in\s+\$GROUPS\s*\)?$/;function Fp(e){const n=e.trim();if(n==="false")return"no one";const r=ha.exec(n);if(r)return`members of ${r[1]??r[2]}`;for(const o of["or","and"]){const i=n.split(new RegExp(`\\s+${o}\\s+`));if(i.length<2)continue;const l=i.map(a=>ha.exec(a.trim()));if(l.every(a=>a)){const a=l.map(u=>u[1]??u[2]);return o==="or"?`members of ${a.slice(0,-1).join(", ")} or ${a[a.length-1]}`:`members of all of ${a.join(", ")}`}}}function El(e){const n=e.authorize.filter(o=>o.trim()!=="true").map(o=>Fp(o)??"readers its access rule admits");return Array.from(new Set(n)).join(", and ")}const Il="Only some readers can query this source",Dl="Each reader sees only the rows they're allowed to see";function Lp(e,n){return e?Yt(n)?`You can't access ${e}. It is restricted to ${El(n)}; ask an administrator of this package for access.`:`You can't access ${e}. Ask an administrator of this package for access.`:"You don't have access to run this. Ask an administrator of this package for access."}function _p(e,n){if(!(!Jt(e)||n===void 0))return Ap(n)===0?"Filtered to your rows: this source shows each reader only the rows they're allowed to see.":void 0}function Al(e){return Yt(e)||Jt(e)}function Np(e,n){return`This join doesn't apply the ${Yt(n)&&Jt(n)?"access rule and row filter":Yt(n)?"access rule":"row filter"} on ${e}: its rows are read under this source's rules.`}function Pp({access:e}){return t.jsxs(t.Fragment,{children:[Yt(e)&&t.jsx(fa,{label:"Restricted",meaning:Il}),Jt(e)&&t.jsx(fa,{label:"Row filtered",meaning:Dl})]})}function fa({label:e,meaning:n}){return t.jsx(yo,{layer:"access",title:`${e}: ${n}`,testId:`source-access-chip-${e==="Restricted"?"restricted":"row-filtered"}`,children:t.jsx(At,{tone:"neutral",size:"header",children:e})})}function Rl({access:e}){return t.jsxs(t.Fragment,{children:[Yt(e)&&t.jsx(m.Tooltip,{title:`Restricted: ${Il}`,children:t.jsx(At,{voice:"token",tone:"neutral",sx:{alignSelf:"center"},children:"Restricted"})}),Jt(e)&&t.jsx(m.Tooltip,{title:`Row filtered: ${Dl}`,children:t.jsx(At,{voice:"token",tone:"neutral",sx:{alignSelf:"center"},children:"Row filtered"})})]})}function zp(e){return[Yt(e)&&"restricted",Jt(e)&&"row filtered"].filter(Boolean).map(n=>`, ${n}`).join("")}function Wp({access:e,showRules:n}){const r=Yt(e),o=Jt(e);return!r&&!o?null:t.jsxs(m.Box,{"data-testid":"source-access-facts",sx:{display:"grid",gridTemplateColumns:"max-content 1fr",columnGap:"16px",rowGap:"6px",alignItems:"baseline"},children:[r&&t.jsx(Ut,{label:"Restricted to",value:El(e)}),r&&n&&e.authorize.filter(i=>i.trim()!=="true").map((i,l)=>t.jsx(Ut,{label:"Access rule",value:i,mono:!0},`a${l}`)),o&&t.jsx(Ut,{label:"Rows",value:"Rows are filtered for each reader"}),o&&n&&e.accessFilter.map((i,l)=>t.jsx(Ut,{label:"Row filter",value:i,mono:!0},`f${l}`))]})}const pa="Private",qp="index.malloy doesn't export this file, so only people who can edit the package see it.";function ma(){return t.jsx(yo,{title:`${pa}: ${qp}`,testId:"model-viewer-off-surface",children:t.jsx(At,{tone:"warning",size:"header",children:pa})})}const ga="Public",Bp="index.malloy exports this source, so everyone who can read the package can query it.";function Vp(){return t.jsx(yo,{title:`${ga}: ${Bp}`,testId:"model-viewer-public-surface",children:t.jsx(At,{tone:"positive",size:"header",children:ga})})}function Hp(e){const n=T.useRef(e);return e!==void 0&&(n.current=e),n.current}function As({title:e,titleAdornments:n,kindLabel:r,meta:o,doc:i,provenance:l,actions:a,status:u,headingLevel:d="h1",modelDoc:h,access:y,showRules:b=!1,isSource:x=!0,offSurface:v,publicSurface:k=!1}){const C=Yt(y)||Jt(y),S=C?["access"]:[],[j,M]=T.useState(void 0),O=j!==void 0&&S.includes(j)?j:void 0,E=Hp(O),$=T.useId(),P={openLayer:O,layers:S,toggle:_=>M(V=>V===_?void 0:_),cardId:$},A=C||v||k||!!u,B=q.usePublisherTheme().theme.ui.type.pageTitle,D=typeof B.fontSize=="number"?`${B.fontSize}px`:B.fontSize;return t.jsxs(m.Box,{children:[t.jsxs(m.Box,{"data-testid":"model-viewer-source-heading",sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:1.5,pt:eo,pb:.5},children:[t.jsx(m.Box,{component:d,sx:{m:0,fontSize:d==="h1"?D:`calc(${D} * 0.8)`,fontWeight:B.fontWeight??600,lineHeight:1.25,color:"text.primary",fontFamily:Dt,minWidth:0,overflowWrap:"anywhere"},children:e}),n,a&&t.jsx(m.Box,{sx:{ml:"auto",display:"flex",alignItems:"center",gap:1},children:a})]}),!x&&v&&t.jsx(m.Box,{sx:{display:"flex",alignItems:"center",pt:.5,pb:1},children:t.jsx(ma,{})}),x&&A&&t.jsx(Ol.Provider,{value:P,children:t.jsxs(m.Box,{"data-testid":"model-viewer-status-row",sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:1.5,pt:.5,pb:1},children:[t.jsx(Pp,{access:y}),v&&t.jsx(ma,{}),k&&t.jsx(Vp,{}),u]})}),h&&t.jsx(ya,{doc:h,label:"model description",testId:"model-viewer-model-doc"},`model:${h}`),i&&t.jsx(ya,{doc:i},i),(r!==void 0||o!==void 0||l)&&t.jsxs(m.Box,{"data-testid":"model-viewer-source-meta",sx:{display:"flex",alignItems:"center",gap:.75,minWidth:0,pb:2,fontSize:wt.body,color:"text.secondary",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:[r!==void 0&&t.jsx(m.Box,{component:"span","data-testid":"model-viewer-source-kind",children:r}),r!==void 0&&(o!==void 0||l)&&t.jsx(m.Box,{component:"span","aria-hidden":!0,children:"·"}),o!==void 0&&t.jsx(m.Box,{component:"span",children:o}),o!==void 0&&l&&t.jsx(m.Box,{component:"span","aria-hidden":!0,children:"·"}),l&&t.jsx(m.Box,{component:"span",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:l})]}),t.jsx(m.Collapse,{in:O!==void 0,timeout:"auto",unmountOnExit:!0,children:t.jsx(m.Box,{id:$,"data-testid":"model-viewer-source-detail","data-layer":E??void 0,sx:{...Pn,p:Tr,mb:2},children:E==="access"&&y&&t.jsx(Wp,{access:y,showRules:b})})})]})}const Up=2;function ya({doc:e,label:n="description",testId:r="model-viewer-source-doc"}){const[o,i]=T.useState(!1),[l,a]=T.useState(!1),u=T.useRef(null);return T.useEffect(()=>{const d=u.current;if(!d||o)return;const h=()=>a(d.scrollHeight>d.clientHeight+1);if(h(),typeof ResizeObserver>"u")return;const y=new ResizeObserver(h);return y.observe(d),()=>y.disconnect()},[o,e]),t.jsxs(m.Box,{"data-testid":r,sx:{pb:.5},children:[t.jsx(m.Box,{ref:u,sx:{fontSize:wt.body,lineHeight:1.5,color:"text.secondary",whiteSpace:"pre-line",...o?{}:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:Up,overflow:"hidden"}},children:$l(e)}),(l||o)&&t.jsx(m.Box,{component:"button",type:"button",onClick:()=>i(!o),"aria-expanded":o,"aria-label":o?`Show less of the ${n}`:`Show the full ${n}`,sx:{all:"unset",cursor:"pointer",fontSize:wt.small,color:"text.secondary",textDecoration:"underline","&:hover":{color:"text.primary"},"&:focus-visible":{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}},children:o?"Less":"More"})]})}function $l(e){return e.split(/(`[^`\n]+`)/g).map((n,r)=>/^`[^`]+`$/.test(n)?t.jsx(m.Box,{component:"code",sx:{fontFamily:Dt,fontSize:"0.92em",color:"text.primary"},children:n.slice(1,-1)},r):n)}function cs(e){const n=e?.response?.status;return typeof n=="number"?n:void 0}function Gp(e){const n=cs(e);return n===403||n===404}function Yp(e,n){if(!e?.modelPath||!e.sourceName)return{kind:"unknown"};const r=n.get(e.modelPath);return r?r.has(e.sourceName)?{kind:"link"}:{kind:"join-only"}:{kind:"unknown"}}const xo=T.createContext([]),ts="text.primary",ur=e=>({main:e,tint:`color-mix(in srgb, ${e} 12%, transparent)`,onTint:e}),Rn={steel:ur(q.PALETTE.cyan),sage:ur(q.PALETTE.lime),brown:ur(q.PALETTE.slate),olive:ur(q.PALETTE.violet),amber:ur(q.PALETTE.amber)};function xa(e){return e==="measure"?Rn.sage:e==="calculate"?Rn.amber:e==="view"?Rn.olive:Rn.steel}const va=["steel","brown","olive","sage"];function Kp(e){return va[e%va.length]}const Fl={small:13,caption:12},Qp={fontFamily:Dt,fontSize:Fl.small,fontWeight:500,color:ts},Ll={fontSize:Fl.caption,color:"text.secondary"};function _n({label:e,count:n,level:r="h2",testId:o,action:i,children:l}){return n===0?null:r==="h3"?t.jsxs(m.Box,{component:"section","aria-label":e,"data-testid":o,sx:{mb:2},children:[t.jsx(m.Box,{component:"h3",sx:{m:0,mb:1,fontSize:wt.bodyLarge,fontWeight:Js.strong,color:ts},children:e}),l]}):t.jsxs(m.Box,{component:"section","aria-label":e,"data-testid":o,sx:{mb:3},children:[t.jsxs(m.Box,{sx:{mb:2},children:[t.jsx(m.Box,{component:"h2",sx:{m:0,fontSize:"1.25rem",fontWeight:Js.strong,color:ts},children:e}),i&&t.jsx(m.Box,{sx:{...Ll,mt:.25,display:"flex",alignItems:"center"},children:i})]}),l]})}function vr(e,n){return e.length<=1?e.join(""):`${e.slice(0,-1).join(", ")} ${n} ${e.at(-1)}`}function ba(e,n){return`${e.label??e.name}: ${c.describeGivenValue(e,n)}`}const Hr=e=>e.label??e.name;function _l(e,n,r=void 0,o=void 0,i=!1,l="source"){const a=e??[],u=O=>r?.[O.name]!==void 0,d=O=>o?.has(O.name)===!0,h=a.filter(O=>!u(O)&&O.default===void 0),y=n??[],b=y.length===0&&h.length>0&&h.every(O=>d(O)),x=i&&b?h:[];if(x.length===0&&(h.length>0||y.length>0)){const O=h.length>0?`a value for ${h.length===1?"the given":"the givens"} ${h.map(Hr).join(", ")}`:"",E=y.length>0?`${y.length===1?"the required filter":"the required filters"} ${y.join(", ")}`:"",$=h.filter(d),P=$.length===0?"":$.length===h.length?` This page can't tell whether this ${l} reads ${h.length===1?"it":"them"}.`:` This page can't tell whether this ${l} reads ${vr($.map(Hr),"or")}.`;let A;return E===""?A=`This needs ${O}. Set ${h.length===1?"it":"them"} in the Givens section above.${P}`:O===""?A=`This needs ${E}, which this page can't set; open the source in a dashboard or notebook.`:A=`This needs ${O} (set ${h.length===1?"it":"them"} in the Givens section above) and ${E}, which this page can't set; open the source in a dashboard or notebook.${P}`,{kind:"blocked",reason:A,canRunAnyway:b}}const v=O=>O.length>0?`${O.length===1?"the default":"the defaults"} ${O.map(E=>ba(E)).join(", ")}`:"",k=[];x.length>0&&k.push(`Ran without a value for ${x.length===1?"the given":"the givens"} ${vr(x.map(Hr),"and")}, which this page can't tell this ${l} reads.`);const C=a.filter(O=>!x.includes(O)),S=C.filter(O=>!d(O)),j=v(S.filter(O=>!u(O)));j!==""&&k.push(`Ran with ${j}.`);const M=C.filter(d);if(M.length>0){const O=[M.filter(u).map(E=>ba(E,r?.[E.name])).join(", "),v(M.filter(E=>!u(E)))].filter(E=>E!=="").join(" and ");k.push(M.length===C.length?`This page can't tell which givens this ${l} reads. Where it reads one, it ran with ${O}.`:`This page can't tell whether this ${l} reads ${vr(M.map(Hr),"or")}. Where it does, it ran with ${O}.`)}return k.length>0?{kind:"noted",note:k.join(" ")}:{kind:"ok"}}const Zp=400;function Xp({givens:e,unknown:n,inheritedFrom:r,values:o,onChange:i,onReset:l,environmentName:a,packageName:u,modelPath:d,versionId:h,declaredTypes:y}){const b=T.useMemo(()=>[...e],[e]),x=T.useMemo(()=>{const A=e.filter(B=>n?.has(B.name));if(A.length!==0)return A.length===e.length?"This page can't tell which of these givens this source reads, so a value set here may not apply to it.":`This page can't tell whether this source reads ${vr(A.map(B=>B.label??B.name),"or")}, so a value set for ${A.length===1?"it":"them"} may not apply.`},[e,n]),[v,k]=T.useState(()=>new Set),C=T.useCallback(A=>k(B=>B.has(A)?B:new Set([...B,A])),[]),S=c.useSettled(o,Zp),j=T.useMemo(()=>({values:S,declaredTypes:y}),[S,y]),{options:M,isLoading:O,failed:E,truncated:$,search:P}=c.useSuggestOptions(a,u,d,b,h,j,void 0,v,!0);return t.jsxs(_n,{label:"Givens",count:e.length,testId:"model-givens-section",children:[t.jsx(m.Box,{sx:{"& .MuiPaper-root":{borderColor:"divider"}},children:t.jsx(c.GivensPanel,{layout:"bar",givens:b,values:o,onChange:i,onReset:l,options:M,optionsLoading:O,optionsFailed:E,optionsTruncated:$,optionSearch:P,onControlOpen:C})}),x&&t.jsx(un,{"data-testid":"model-givens-unknown",sx:{mt:1},children:x}),r&&r.size>0&&t.jsx(un,{"data-testid":"model-givens-inherited",sx:{mt:1},children:[...r].map(([A,B])=>B.length===1?`${A} is inherited from ${B[0]}, which this model doesn't export.`:`${A} is inherited from ${B.slice(0,-1).join(", ")} and ${B.at(-1)}, none of which this model exports.`).join(" ")})]})}const Jp="A source is a queryable entry point into the model — pick one to browse its dimensions, measures, views and joins.";function em(e,n=!1){return e===0?"No sources":`${e} ${n?"public ":""}source${e===1?"":"s"}`}const tm=c.createSvgIcon(t.jsx("path",{d:"M21 11h-1.5v-.5h-2v3h2V13H21v1c0 .55-.45 1-1 1h-3c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1zM8 10v5H6.5v-1.5h-2V15H3v-5c0-.55.45-1 1-1h3c.55 0 1 .45 1 1m-1.5.5h-2V12h2zm7 1.5c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1h-4V9h4c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1M11 10.5v.75h2v-.75zm2 2.25h-2v.75h2z"})),nm=c.createSvgIcon(t.jsx("path",{d:"M6 6v2h8.59L5 17.59 6.41 19 16 9.41V18h2V6z"})),rm=c.createSvgIcon(t.jsx("path",{d:"M4 9h4v11H4zm12 4h4v7h-4zm-6-9h4v16h-4z"})),sm=c.createSvgIcon([t.jsx("path",{d:"M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 16H5V5h14z"},"0"),t.jsx("path",{d:"M6.25 7.72h5v1.5h-5zM13 15.75h5v1.5h-5zm0-2.5h5v1.5h-5zM8 18h1.5v-2h2v-1.5h-2v-2H8v2H6V16h2zm6.09-7.05 1.41-1.41 1.41 1.41 1.06-1.06-1.41-1.42 1.41-1.41L16.91 6 15.5 7.41 14.09 6l-1.06 1.06 1.41 1.41-1.41 1.42z"},"1")]),Nl=c.createSvgIcon(t.jsx("path",{d:"M20 3h-1V1h-2v2H7V1H5v2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m0 18H4V10h16zm0-13H4V5h16z"})),om=c.createSvgIcon(t.jsx("path",{d:"M17 20.41 18.41 19 15 15.59 13.59 17zM7.5 8H11v5.59L5.59 19 7 20.41l6-6V8h3.5L12 3.5z"})),im=c.createSvgIcon(t.jsx("path",{d:"M9.4 16.6 4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0 4.6-4.6-4.6-4.6L16 6l6 6-6 6z"})),am=c.createSvgIcon(t.jsx("path",{d:"M15 4v2h3v12h-3v2h5V4zM4 20h5v-2H6V6h3V4H4z"})),lm=c.createSvgIcon(t.jsx("path",{d:"M4 7v2c0 .55-.45 1-1 1H2v4h1c.55 0 1 .45 1 1v2c0 1.65 1.35 3 3 3h3v-2H7c-.55 0-1-.45-1-1v-2c0-1.3-.84-2.42-2-2.83v-.34C5.16 11.42 6 10.3 6 9V7c0-.55.45-1 1-1h3V4H7C5.35 4 4 5.35 4 7m17 3c-.55 0-1-.45-1-1V7c0-1.65-1.35-3-3-3h-3v2h3c.55 0 1 .45 1 1v2c0 1.3.84 2.42 2 2.83v.34c-1.16.41-2 1.52-2 2.83v2c0 .55-.45 1-1 1h-3v2h3c1.65 0 3-1.35 3-3v-2c0-.55.45-1 1-1h1v-4z"})),cm=c.createSvgIcon(t.jsx("path",{d:"m12 8-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z"})),um=c.createSvgIcon(t.jsx("path",{d:"M4 10.5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5m0-6c-.83 0-1.5.67-1.5 1.5S3.17 7.5 4 7.5 5.5 6.83 5.5 6 4.83 4.5 4 4.5m0 12c-.83 0-1.5.68-1.5 1.5s.68 1.5 1.5 1.5 1.5-.68 1.5-1.5-.67-1.5-1.5-1.5M7 19h14v-2H7zm0-6h14v-2H7zm0-8v2h14V5z"})),Pl=c.createSvgIcon(t.jsx("path",{d:"M7.41 8.59 12 13.17l4.59-4.58L18 10l-6 6-6-6z"})),dm=c.createSvgIcon(t.jsx("path",{d:"M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2M9 6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9zm9 14H6V10h12zm-6-3c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2"})),hm=c.createSvgIcon(t.jsx("path",{d:"m20.5 10 .5-2h-4l1-4h-2l-1 4h-4l1-4h-2L9 8H5l-.5 2h4l-1 4h-4L3 16h4l-1 4h2l1-4h4l-1 4h2l1-4h4l.5-2h-4l1-4zm-7 4h-4l1-4h4z"})),zl=c.createSvgIcon(t.jsx("path",{d:"M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2M12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8m.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z"})),fm=c.createSvgIcon([t.jsx("path",{d:"m21.41 11.41-8.83-8.83c-.37-.37-.88-.58-1.41-.58H4c-1.1 0-2 .9-2 2v7.17c0 .53.21 1.04.59 1.41l8.83 8.83c.78.78 2.05.78 2.83 0l7.17-7.17c.78-.78.78-2.04-.01-2.83M12.83 20 4 11.17V4h7.17L20 12.83z"},"0"),t.jsx("circle",{cx:"6.5",cy:"6.5",r:"1.5"},"1")]),Wl=c.createSvgIcon(t.jsx("path",{d:"M17 6H7c-3.31 0-6 2.69-6 6s2.69 6 6 6h10c3.31 0 6-2.69 6-6s-2.69-6-6-6m0 10H7c-2.21 0-4-1.79-4-4s1.79-4 4-4h10c2.21 0 4 1.79 4 4s-1.79 4-4 4m0-7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3"})),pm=c.createSvgIcon(t.jsx("path",{d:"M3 17v2h6v-2zM3 5v2h10V5zm10 16v-2h8v-2h-8v-2h-2v6zM7 9v2H3v2h4v2h2V9zm14 4v-2H11v2zm-6-4h2V7h4V5h-4V3h-2z"})),ql=c.createSvgIcon(t.jsx("path",{d:"M3 5v14h18V5zm5.33 12H5V7h3.33zm5.34 0h-3.33V7h3.33zM19 17h-3.33V7H19z"})),mm=c.createSvgIcon(t.jsx("path",{d:"M12 5.99 19.53 19H4.47zM12 2 1 21h22zm1 14h-2v2h2zm0-6h-2v4h2z"}));function rt(e,n){const r=({size:o,...i})=>t.jsx(e,{...i,sx:{fontSize:o}});return r.displayName=n,r}const gm=rt(tm,"IconText"),wa=rt(nm,"IconOpen"),Bl=rt(rm,"IconResult"),ym=rt(sm,"IconCalculation"),xm=rt(Nl,"IconDate"),vm=rt(om,"IconJoin"),bm=rt(im,"IconCode"),wm=rt(am,"IconList"),Sm=rt(lm,"IconRecord"),km=rt(cm,"IconCollapse"),Cm=rt(c.ExpandMoreIcon,"IconExpand"),Tm=rt(um,"IconFields"),jm=rt(Pl,"IconDropdown"),Mm=rt(dm,"IconLock"),Vl=rt(hm,"IconNumber"),Om=rt(zl,"IconTimestamp"),Em=rt(fm,"IconValues"),Im=rt(Wl,"IconBoolean"),Dm=rt(pm,"IconGivens"),Hl=rt(ql,"IconColumn");rt(mm,"IconWarning");const Mr=T.createContext(void 0);function vo(){const[e,n]=T.useState(!1),r=T.useContext(Mr),[o,i]=T.useState(r?.n);return r&&r.n!==o&&(i(r.n),n(r.open)),[e,n]}function Am({allOpen:e,onToggle:n,noun:r,disabledReason:o}){const i=e?t.jsx(km,{size:16,"aria-hidden":!0}):t.jsx(Cm,{size:16,"aria-hidden":!0});return t.jsx(m.Tooltip,{title:o??"",children:t.jsx("span",{children:t.jsxs(m.ButtonBase,{disabled:!!o,onClick:n,"aria-label":o??`${e?"Collapse":"Expand"} all ${r[1]}`,sx:{font:"inherit",color:"text.secondary",gap:.25,borderRadius:1,"&:hover":{color:"text.primary",textDecoration:"underline"},...jr,"&.Mui-disabled":{opacity:.5}},children:[i,e?"Collapse all":"Expand all"]})})})}function ns({noun:e,disabledReason:n}){const[r,o]=T.useState(void 0),i=r?.open??!1;return{command:r,action:t.jsx(Am,{allOpen:i,onToggle:()=>o({open:!i,n:(r?.n??0)+1}),noun:e,disabledReason:n})}}let Rs;function Rm(e,n){if(Rs?.text===n)return Rs.parsed;const r=n.replace(/\r\n/g,`
|
|
17
17
|
`);let o;try{o={lines:r.split(`
|
|
18
|
-
`),symbols:e.Malloy.parse({source:r}).symbols}}catch{o=void 0}return
|
|
19
|
-
`)}let
|
|
18
|
+
`),symbols:e.Malloy.parse({source:r}).symbols}}catch{o=void 0}return Rs={text:n,parsed:o},o}function us(e,n){const{start:r,end:o}=n;return r.line===o.line?(e[r.line]??"").slice(r.character,o.character):[(e[r.line]??"").slice(r.character),...e.slice(r.line+1,o.line),(e[o.line]??"").slice(0,o.character)].join(`
|
|
19
|
+
`)}let Ul,Ur;function $m(){return Ur??=import("@malloydata/malloy").then(e=>{const n="Malloy"in e?e:e.default;return Ul=n,n}),Ur.catch(()=>{Ur=void 0}),Ur}function Gl(e,n=!0){const[r,o]=T.useState(Ul),[i,l]=T.useState(!1),a=!!e&&n;return T.useEffect(()=>{if(!a||r)return;let d=!0;return $m().then(h=>d&&o(h),()=>d&&l(!0)),()=>{d=!1}},[a,r]),{parsed:T.useMemo(()=>a&&r&&e?Rm(r,e):void 0,[a,r,e]),pending:a&&!r&&!i}}function Fm(e,n){if(!e)return;const r=e.symbols.filter(o=>o.type==="query"&&o.name.replace(/^`(.*)`$/,"$1")===n);if(r.length===1)return`query: ${us(e.lines,r[0].range).trimEnd()}`}function Yl(e){const n=e.replace(/^\n+/,"").split(`
|
|
20
20
|
`),r=[];let o=0;for(;o<n.length;){const i=n[o].trim();if(!i.startsWith("#"))break;!i.startsWith('#"')&&!i.startsWith("#(doc)")&&r.push(n[o]),o+=1}return[...r,...n.slice(o)].join(`
|
|
21
|
-
`).trim()}function
|
|
21
|
+
`).trim()}function Lm(e,n){const r=Yl(n),o=mn(e),i=new RegExp(`^(?:(?:dimension|measure|view)\\s*:\\s*)?${o}\\s+is\\s+`),l=r.replace(i,"");if(l===r||!(l.startsWith("{")&&l.endsWith("}")))return r;const u=l.slice(1,-1).replace(/^\n/,"").replace(/\s+$/,"").split(`
|
|
22
22
|
`),d=u.filter(b=>b.trim()).map(b=>b.match(/^[ \t]*/)[0].length),h=d.length?Math.min(...d):0;return u.map(b=>b.slice(h)).join(`
|
|
23
|
-
`).trim()||r}function
|
|
23
|
+
`).trim()||r}function _m(e,n){const r=Yl(n),o=r.split(`
|
|
24
24
|
`),i=o.findIndex(u=>!u.trim().startsWith("#"));if(i<0)return r;const l=o[i];if(/^\s*view\s*:/.test(l))return Sa(o,i).join(`
|
|
25
|
-
`);const a=
|
|
26
|
-
`)):r}function Sa(e,n){const r=e.slice(n+1).filter(i=>i.trim()!=="");if(r.length===0)return e;const o=Math.min(...r.map(i=>i.length-i.trimStart().length));return o===0?e:e.map((i,l)=>l<=n?i:i.slice(Math.min(o,i.length-i.trimStart().length)))}function bo(e){return e.kind==="dimension"&&e.indexed===!0}function wo(e){return!!e&&(e.loading||!!e.code||!!e.inheritedFrom||!!e.error)}function
|
|
27
|
-
`)||e.scrollWidth>e.clientWidth}const Ap={dimension:ql,measure:Wl,calculate:dp,view:zl,join:fp};function Rp(e){switch(e){case"dimension":case"measure":case"calculate":case"view":return xa(e).main;case"column":return xa("dimension").main;case"join":return Fn.brown.main}}function Lp(e){const n=e?.trim().toLowerCase()??"";if(!n)return;if(n.startsWith("array"))return pp;if(n.startsWith("record")||/\bfields?\b/.test(n))return gp;switch(n.split(/[\s·<]/)[0]){case"string":return up;case"number":return Wl;case"date":return hp;case"timestamp":case"timestamptz":return Sp;case"boolean":return Cp;default:return}}const _p=16;function So({kind:e,dataType:n}){const r=e==="dimension"||e==="measure"||e==="calculate"||e==="column"?Lp(n):void 0;return t.jsx(p.Box,{component:"span","aria-hidden":!0,"data-row-glyph":e,sx:{display:"inline-flex",alignSelf:"center",flexShrink:0,color:Rp(e)},children:j.createElement(r??Ap[e==="column"?"dimension":e],{size:_p})})}function ko(e,n){return(n?e.givensBySource?.get(n):void 0)??e.givens}function Ul(e,n){if(!e.givenValues||!n)return e;const r=new Set(n.map(i=>i.name)),o=Object.entries(e.givenValues).filter(([i])=>r.has(i));return{...e,givenValues:o.length>0?Object.fromEntries(o):void 0}}function Np({run:e,modelPath:n,query:r,enabled:o}){const{server:i,apiClients:l}=q.useServer(),a=mt.useQuery({...Gl({server:i,apiClients:l,run:e,modelPath:n,query:r}),enabled:o,refetchOnWindowFocus:!1,refetchOnReconnect:!1});return{result:a.data?.data.result,isSuccess:a.isSuccess,isLoading:a.isLoading,isFetching:a.isFetching,isError:a.isError,error:a.error,refetch:a.refetch}}function Co(e,n,r,o){return["model-viewer-run",e,n.projectName,n.packageName,r,n.versionId??"",o,go(n.givenValues),...n.includeHiddenFilesAndSources?["off-surface"]:[]]}function Gl({server:e,apiClients:n,run:r,modelPath:o,query:i}){const l=go(r.givenValues)===""?void 0:r.givenValues;return{queryKey:Co(e,r,o,i),queryFn:async({signal:a})=>{const u=performance.now(),d=()=>Math.round(performance.now()-u);try{const h=await n.models.executeQueryModel(r.projectName,r.packageName,o,{query:i,versionId:r.versionId,...l&&{givens:l},...r.queryMetadata&&{queryMetadata:{...r.queryMetadata}}},r.includeHiddenFilesAndSources?!0:void 0,void 0,{signal:a});return r.onQueryRun?.({outcome:"success",durationMs:d()}),h}catch(h){throw a?.aborted||r.onQueryRun?.({outcome:"error",durationMs:d()}),h}},staleTime:1/0,retry:!1}}const As=12,Pp=5*6e4;function zp(e){const n=cs(e);return n===void 0?!1:n>=400&&n<500&&n!==401&&n!==408&&n!==429}function Wp(e){if(!e)return[];const{data:n}=JSON.parse(e);return n?.kind!=="array_cell"?[]:n.array_value.flatMap(r=>{if(r.kind!=="record_cell")return[];const o=r.record_value[0];if(!o)return[];switch(o.kind){case"string_cell":return[o.string_value];case"number_cell":return[String(o.number_value)];case"boolean_cell":return[String(o.boolean_value)];case"date_cell":return[o.date_value];case"timestamp_cell":return[o.timestamp_value];default:return[]}})}function qp({run:e,modelPath:n,sourceName:r,field:o,fetchSamples:i,generation:l}){const{server:a,apiClients:u}=q.useServer(),d=o?.kind==="dimension"&&o.indexed===!0,h=ko(e,r),y=d&&!i?Al(h,e.requiredFiltersBySource?.get(r),e.givenValues):void 0,b=y?.kind==="blocked"?y.reason:void 0,x=d&&!b?o.name:void 0,v=mt.useQuery({...Gl({server:a,apiClients:u,run:Ul(e,h),modelPath:n,query:c.sampleValuesQuery(r,x??"",As)}),enabled:!!x&&!i,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),k=mt.useQuery({queryKey:["model-viewer-samples",a,e.projectName,e.packageName,e.versionId??"",n,r,x,l??"host"],enabled:!!x&&!!i,staleTime:Pp,retry:!1,refetchOnWindowFocus:!1,queryFn:async({signal:T})=>{try{const O=await i({modelPath:n,sourceName:r,fieldName:x,limit:As,signal:T}),M=Array.isArray(O)?{values:O}:O;return{...M,values:M.values.slice(0,As)}}catch(O){if(zp(O))return{values:[]};throw O}}}),C=i?k:v,S=i?k.data:v.data&&{values:Wp(v.data.data.result)};return{samples:S?.values??[],total:S?.total,unavailable:b??S?.unavailable,loading:!!x&&C.isPending,failed:C.isError}}function Bp({children:e}){return t.jsx(p.Box,{component:"span",sx:{fontFamily:Dt,fontSize:wt.caption,color:"text.primary",bgcolor:nt.background.muted,border:"1px solid",borderColor:"divider",borderRadius:1,padding:"2px 8px"},children:e})}function Vp({run:e,fetchSamples:n,modelPath:r,sourceName:o,field:i,generation:l}){const{samples:a,total:u,unavailable:d,loading:h,failed:y}=qp({run:e,fetchSamples:n,modelPath:r,sourceName:o,field:i,generation:l});return t.jsxs(p.Box,{"data-testid":"model-viewer-values",sx:{fontSize:wt.small},children:[t.jsx(p.Box,{component:"div",sx:{color:as,fontSize:wt.caption,mb:"6px"},children:u!=null?`The most common of ${u.toLocaleString()} ${u===1?"value":"values"}`:"The most common values"}),h?t.jsx(p.CircularProgress,{size:12,sx:{color:"text.secondary"}}):d?t.jsx(p.Box,{component:"span","data-testid":"model-viewer-values-unavailable",sx:{color:"text.secondary"},children:d}):y?t.jsx(p.Box,{component:"span",sx:{fontStyle:"italic",color:"text.secondary"},children:"Sample values couldn't be loaded."}):a.length===0?t.jsx(p.Box,{component:"span",sx:{fontStyle:"italic",color:"text.secondary"},children:"No values found."}):t.jsx(p.Box,{sx:{display:"flex",flexWrap:"wrap",gap:"6px"},children:a.map(b=>t.jsx(Bp,{children:b},b))})]})}const Rs={scopeName:"source.malloy",patterns:[{include:"#malloy-language"}],repository:{"malloy-language":{patterns:[{include:"#sql-string"},{include:"#comments"},{include:"#tags"},{include:"#strings"},{include:"#numbers"},{include:"#keywords"},{include:"#properties"},{include:"#functions"},{include:"#datetimes"},{include:"#identifiers-quoted"},{include:"#types"},{include:"#constants"},{include:"#timeframes"},{include:"#identifiers-unquoted"}]},"malloy-matched":{begin:"{",end:"}",patterns:[{include:"#malloy-matched"},{include:"#malloy-language"}]},"malloy-in-sql":{begin:"%{",name:"source.malloy-in-sql",end:"}%?",patterns:[{include:"#malloy-matched"},{include:"#malloy-language"}]},"sql-string":{patterns:[{begin:'(\\b[A-Za-z_][A-Za-z_0-9]*)(\\s*\\.\\s*)(sql)(\\s*\\(\\s*)(""")',end:'"""',beginCaptures:{1:{name:"variable.other"},3:{name:"keyword.control.sql"},5:{name:"punctuation.sql-block.open"}},endCaptures:{0:{name:"punctuation.sql-block.close"}},name:"source.sql",patterns:[{include:"#malloy-in-sql"},{include:"source.sql"}]}]},functions:{patterns:[{match:"(?i)\\b(count)(\\s*\\()(distinct)",captures:{1:{name:"entity.name.function"},3:{name:"entity.name.function.modifier"}}},{match:"(?i)\\b(AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE|UNGROUPED)(\\s*\\()",captures:{1:{name:"entity.name.function"}}},{match:"(?i)\\b([a-zA-Z_][a-zA-Z_0-9]*)(\\s*\\()",captures:{1:{name:"entity.name.function"}}},{match:"(?i)\\b([a-zA-Z_][a-zA-Z_0-9]*)(!)(timestamp|number|string|boolean|date)?(\\s*\\()",captures:{1:{name:"entity.name.function"},3:{name:"entity.name.type"}}}]},datetimes:{patterns:[{match:"(?i)@[0-9]{4}-[0-9]{2}-[0-9]{2}[ T][0-9]{2}:[0-9]{2}((:[0-9]{2})(([\\.,][0-9]+)(\\[[A-Za-z_/]+\\])?)?)?",name:"constant.numeric.timestamp"},{match:"(?i)@[0-9]{4}(-Q[1-4]|-[0-9]{2}(-[0-9]{2}(-WK)?)?)?",name:"constant.numeric.date"}]},"identifiers-quoted":{patterns:[{match:"`[^`]*`",name:"variable.other.quoted"}]},"identifiers-unquoted":{patterns:[{match:"(?i)\\b[A-Za-z_][A-Za-z_0-9]*\\b",name:"variable.other"}]},timeframes:{patterns:[{match:"(?i)\\b((year|quarter|month|week|day|hour|minute|second)s?)\\b",name:"keyword.other.timeframe"},{match:"(?i)\\b(day_of_year|day_of_month)\\b",name:"keyword.other.timeframe"}]},comments:{patterns:[{begin:"/\\*",end:"\\*/",beginCaptures:{0:{name:"punctuation.definition.comment.begin"}},endCaptures:{0:{name:"punctuation.definition.comment.end"}},name:"comment.block"},{begin:"//",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-slash"},{begin:"--",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-hyphen"}]},tags:{patterns:[{match:"##\\n",name:"string.quoted",captures:{0:{name:"string.quoted"}}},{begin:'#"',end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-slash"},{match:"#\\n",name:"string.quoted",captures:{0:{name:"string.quoted"}}},{begin:"#\\s",end:"\\n",beginCaptures:{0:{name:"support.type.property-name.json"}},name:"comment.line.double-slash",patterns:[{include:"#tag-values"}]},{begin:"##\\s",end:"\\n",beginCaptures:{0:{name:"support.type.property-name.json"}},name:"comment.line.double-slash",patterns:[{include:"#tag-values"}]},{begin:"#",end:"\\n",beginCaptures:{0:{name:"string.quoted"}},name:"string.quoted"}],repository:{"tag-values":{name:"support.type.property-name.json",match:'(-)?((?:[^\\s=#]+)|(?:"[^#]+"))(?:\\s*(=)\\s*((?:[^\\s=#]+)|(?:"[^#]+")))?',captures:{1:{name:"keyword.control.negate"},2:{name:"support.type.property-name.json"},3:{name:"keyword.operator.comparison.ts"},4:{name:"string.quoted"}}}}},strings:{patterns:[{begin:"'",end:"'",beginCaptures:{0:{name:"punctuation.definition.string.begin"}},endCaptures:{0:{name:"punctuation.definition.string.end"}},name:"string.quoted.single",patterns:[{include:"#escapes"}]},{begin:'"',end:'"',beginCaptures:{0:{name:"punctuation.definition.string.begin"}},endCaptures:{0:{name:"punctuation.definition.string.end"}},name:"string.quoted.double",patterns:[{include:"#escapes"}]},{begin:'"""',end:'"""',beginCaptures:{0:{name:"punctuation.definition.string.begin"}},endCaptures:{0:{name:"punctuation.definition.string.end"}},name:"string.quoted.triple"},{begin:"(?i)[r|/]'",end:"'",name:"string.regexp",patterns:[{include:"#regex-escapes"}]}],repository:{escapes:{name:"constant.character.escape",match:"\\\\(u[A-Fa-f0-9]{4}|.)",captures:{0:{name:"constant.character.escape"}}},"regex-escapes":{name:"constant.character.escape",match:"\\\\.",captures:{0:{name:"constant.character.escape"}}}}},numbers:{match:"(?i)(\\b((0|[1-9][0-9]*)(E[+-]?[0-9]+|\\.[0-9]*)?)|\\.[0-9]+)",name:"constant.numeric"},constants:{patterns:[{match:"(?i)\\bnull\\b",name:"constant.language.null"},{match:"(?i)\\btrue\\b",name:"constant.language.true"},{match:"(?i)\\bfalse\\b",name:"constant.language.false"}]},types:{patterns:[{match:"(?i)\\bstring\\b",name:"entity.name.type.string"},{match:"(?i)\\bnumber\\b",name:"entity.name.type.number"},{match:"(?i)\\bdate\\b",name:"entity.name.type.date"},{match:"(?i)\\btimestamp\\b",name:"entity.name.type.timestamp"},{match:"(?i)\\bboolean\\b",name:"entity.name.type.boolean"}]},properties:{patterns:[{match:"(?i)\\baccept\\b",name:"keyword.control.accept"},{match:"(?i)\\bselect\\b",name:"keyword.control.select"},{match:"(?i)\\bconnection\\b",name:"keyword.control.connection"},{match:"(?i)\\brun\\b",name:"keyword.control.run"},{match:"(?i)\\bextend\\b",name:"keyword.control.extend"},{match:"(?i)\\brefine\\b",name:"keyword.control.refine"},{match:"(?i)\\baggregate\\b",name:"keyword.control.aggregate"},{match:"(?i)\\bsample\\b",name:"keyword.control.sample"},{match:"(?i)\\bcalculate\\b",name:"keyword.control.calculate"},{match:"(?i)\\btimezone\\b",name:"keyword.control.timezone"},{match:"(?i)\\bdimension\\b",name:"keyword.control.dimension"},{match:"(?i)\\bexcept\\b",name:"keyword.control.except"},{match:"(?i)\\bsource\\b",name:"keyword.control.source"},{match:"(?i)\\bgroup_by\\b",name:"keyword.control.group_by"},{match:"(?i)\\bhaving\\b",name:"keyword.control.having"},{match:"(?i)\\bindex\\b",name:"keyword.control.index"},{match:"(?i)\\bjoin_one\\b",name:"keyword.control.join_one"},{match:"(?i)\\bwith\\b",name:"keyword.control.with"},{match:"(?i)\\bjoin_many\\b",name:"keyword.control.join_many"},{match:"(?i)\\bjoin_cross\\b",name:"keyword.control.join_cross"},{match:"(?i)\\blimit\\b",name:"keyword.control.limit"},{match:"(?i)\\bmeasure\\b",name:"keyword.control.measure"},{match:"(?i)\\bnest\\b",name:"keyword.control.nest"},{match:"(?i)\\border_by\\b",name:"keyword.control.order_by"},{match:"(?i)\\bpartition_by\\b",name:"keyword.control.partition_by"},{match:"(?i)\\bprimary_key\\b",name:"keyword.control.primary_key"},{match:"(?i)\\bproject\\b",name:"keyword.control.project"},{match:"(?i)\\bquery\\b",name:"keyword.control.query"},{match:"(?i)\\brename\\b",name:"keyword.control.rename"},{match:"(?i)\\btop\\b",name:"keyword.control.top"},{match:"(?i)\\bview\\b",name:"keyword.control.view"},{match:"(?i)\\bwhere\\b",name:"keyword.control.where"},{match:"(?i)\\bdeclare\\b",name:"keyword.control.declare"}]},keywords:{patterns:[{match:"(?i)\\bis\\b",name:"keyword.control.is"},{match:"(?i)\\bon\\b",name:"keyword.control.on"},{match:"(?i)\\bnot\\b",name:"keyword.other.not"},{match:"(?i)\\bor\\b",name:"keyword.other.or"},{match:"(?i)\\bdesc\\b",name:"keyword.control.desc"},{match:"(?i)\\bby\\b",name:"keyword.control.by"},{match:"(?i)\\band\\b",name:"keyword.other.and"},{match:"(?i)\\basc\\b",name:"keyword.control.asc"},{match:"(?i)\\bfor\\b",name:"keyword.other.for"},{match:"(?i)\\belse\\b",name:"keyword.other.else"},{match:"(?i)\\bto\\b",name:"keyword.other.to"},{match:"(?i)\\bwhen\\b",name:"keyword.other.when"},{match:"(?i)\\bpick\\b",name:"keyword.other.pick"},{match:"(?i)\\bimport\\b",name:"keyword.control.import"}]}}},Hp={...Rs,patterns:[...Rs.patterns,{include:"#docvar"}],repository:{...Rs.repository,docvar:{patterns:[{match:"\\<\\<[^(\\>\\>)]*\\>\\>",beginCaptures:{0:{name:"punctuation.definition.comment.begin"}},endCaptures:{0:{name:"punctuation.definition.comment.end"}},name:"markup.italic.markdown"}]}}},Up={name:"Malloy SQL",scopeName:"source.malloy-sql",patterns:[{include:"#malloysql-sql"}],repository:{"malloysql-sql":{beginCaptures:{0:{name:"entity.other.attribute.malloy-sql"},1:{name:"entity.other.attribute.malloy-sql"},3:{name:"comment.line.double-slash"}},name:"meta.embedded.block.malloysql.sql",patterns:[{include:"#comments"},{begin:"%{",end:"}%",beginCaptures:{0:{name:"punctuation.definition.malloy-sql"}},endCaptures:{0:{name:"punctuation.definition.malloy-sql"}},name:"meta.embedded.block.malloy",patterns:[{include:"source.malloy"}]},{include:"source.sql"}]},comments:{patterns:[{begin:"/\\*",end:"\\*/",beginCaptures:{0:{name:"punctuation.definition.comment.begin"}},endCaptures:{0:{name:"punctuation.definition.comment.end"}},name:"comment.block"},{begin:"//",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-slash"},{begin:"--",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-hyphen"}]}}},Gp="github-light",Yp="github-dark";let Ls;function Kp(){return Ls||(Ls=(async()=>{const[{createHighlighterCore:e},{createOnigurumaEngine:n},{default:r},{default:o},{default:i},{default:l},{default:a}]=await Promise.all([Promise.resolve().then(()=>require("./core-8NVBCLZh.cjs.js")),Promise.resolve().then(()=>require("./engine-oniguruma-BkproSVE.cjs.js")),Promise.resolve().then(()=>require("./sql-BqWZrLHB.cjs.js")),Promise.resolve().then(()=>require("./json-y-J1j5EW.cjs.js")),Promise.resolve().then(()=>require("./typescript-BqvpT6pB.cjs.js")),Promise.resolve().then(()=>require("./github-light-BFTOhCbz.cjs.js")),Promise.resolve().then(()=>require("./github-dark-BKL9xNgN.cjs.js"))]);return e({engine:n(Promise.resolve().then(()=>require("./wasm-Dw4u1m6u.cjs.js"))),themes:[l,a],langs:[r,o,i,{name:"malloy",scopeName:"source.malloy",embeddedLangs:["sql"],...Hp},{name:"malloysql",scopeName:"source.malloy-sql",embeddedLangs:["sql"],...Up}]})})()),Ls}async function jo(e,n,r="light"){return(await Kp()).codeToHtml(e,{lang:n,theme:r==="dark"?Yp:Gp})}function Mr({code:e,testId:n,framed:r=!0}){const{mode:o}=q.usePublisherTheme(),[i,l]=j.useState(void 0);return j.useEffect(()=>{let a=!0;return jo(e,"malloy",o).then(u=>a&&l(u)).catch(()=>a&&l(void 0)),()=>{a=!1}},[e,o]),t.jsx(p.Box,{"data-testid":n,sx:{fontFamily:Dt,fontSize:"0.75rem",overflowX:"auto","& pre":{m:0,background:"transparent !important"},...r&&{border:"1px solid",borderColor:"divider",borderRadius:1,px:1.5,py:1,bgcolor:"background.default"}},children:i?t.jsx("div",{dangerouslySetInnerHTML:{__html:i}}):t.jsx(p.Box,{component:"pre",sx:{whiteSpace:"pre"},children:e})})}function ds({message:e,onRetry:n,severity:r="error"}){return t.jsx(p.Alert,{severity:r,action:n&&t.jsx(p.Button,{color:"inherit",size:"small",onClick:n,children:"Retry"}),children:e})}function Yl(e){const n=e?.response?.data?.message;return typeof n=="string"&&n?n:void 0}function Kl(e,n){const r=Yl(n);return r?`${e}: ${r}`:`${e}.`}function Qp(e){const n=cs(e);return!(n===400||n===401||n===403||n===404||n===422)}function Zp({query:e,error:n,onRetry:r,testId:o,forbiddenMessage:i}){const l=i!==void 0&&cs(n)===403;return t.jsxs(p.Box,{"data-testid":o,sx:{display:"flex",flexDirection:"column",gap:1},children:[e&&t.jsx(Mr,{code:e,testId:"query-failure-code"}),t.jsx(ds,{message:l?i:Kl("Query failed",n),onRetry:r&&Qp(n)?r:void 0})]})}const ka=j.forwardRef(function(n,r){return t.jsx(p.Button,{ref:r,variant:"contained",size:"small",disableElevation:!0,...n,sx:{textTransform:"none",...n.sx}})}),Xp=j.forwardRef(function(n,r){return t.jsx(p.Button,{ref:r,variant:"outlined",size:"small",color:"inherit",...n,sx:{textTransform:"none",borderRadius:999,borderColor:"divider",color:"text.secondary",...n.sx}})}),yr=10,Jp="clamp(340px, 40%, 520px)";function eg({field:e,run:n,modelPath:r,sourceName:o,fieldCode:i,joined:l=!1}){const[a,u]=vo(),{fetchSamples:d,samplesGeneration:h,renderFieldStatus:y,renderFieldAction:b,renderFieldDetail:x}=ls(),v={modelPath:r,sourceName:o,field:e,joined:l},k=y?.(v),C=b?.(v),S=e.doc?void 0:i?.columnDoc,T=e.doc??S,O=wo(i),M=j.useContext(xo),E=j.useMemo(()=>dn(i?.code,M),[i?.code,M]),R=bo(e)&&!l&&!!n,P=[...O?["code"]:[],...R?["values"]:[],...E.length>0?["givens"]:[]],F=$=>P.includes($),B=e.kind==="measure"?"measure":e.kind==="calculate"?"calculate":"dimension",D=P.length>0?t.jsxs(p.Box,{"data-testid":"model-viewer-field-card",sx:{...Pn,"& > * + *":{borderTop:1,borderColor:"divider"}},children:[F("code")&&(i?.loading?t.jsx(p.Box,{sx:{p:jr,display:"flex"},children:t.jsx(p.CircularProgress,{size:12,sx:{color:"text.secondary"}})}):i?.code?t.jsx(Mr,{testId:"model-viewer-definition",code:Ip(e.name,i.code),framed:!1}):i?.inheritedFrom?t.jsx(Mr,{testId:"model-viewer-definition",code:`${i.inheritedFrom.fromTable?"// A column of the table this source reads, as it is":"// Passed through from the query this source is built on"}
|
|
28
|
-
${i.inheritedFrom.code}`,framed:!1}):t.jsx(
|
|
29
|
-
`)[0]]}),h&&t.jsx(
|
|
30
|
-
`)}},[e.tags]),
|
|
25
|
+
`);const a=mn(e);return new RegExp(`^\\s*${a}\\s+is\\b`).test(l)?(o[i]=l.replace(/^(\s*)/,"$1view: "),Sa(o,i).join(`
|
|
26
|
+
`)):r}function Sa(e,n){const r=e.slice(n+1).filter(i=>i.trim()!=="");if(r.length===0)return e;const o=Math.min(...r.map(i=>i.length-i.trimStart().length));return o===0?e:e.map((i,l)=>l<=n?i:i.slice(Math.min(o,i.length-i.trimStart().length)))}function bo(e){return e.kind==="dimension"&&e.indexed===!0}function wo(e){return!!e&&(e.loading||!!e.code||!!e.inheritedFrom||!!e.error)}function Nm(e,n){const r=[],o=[];for(const i of e){const l=n(i);(!!l&&!l.loading&&(!!l.code||!!l.error)||bo(i)?r:o).push(i)}return o.length===0||r.length===0?e:[...r,...o]}function Pm(e,n){return n.includes(`
|
|
27
|
+
`)||e.scrollWidth>e.clientWidth}const zm={dimension:Hl,measure:Vl,calculate:ym,view:Bl,join:vm};function Wm(e){switch(e){case"dimension":case"measure":case"calculate":case"view":return xa(e).main;case"column":return xa("dimension").main;case"join":return Rn.brown.main}}function qm(e){const n=e?.trim().toLowerCase()??"";if(!n)return;if(n.startsWith("array"))return wm;if(n.startsWith("record")||/\bfields?\b/.test(n))return Sm;switch(n.split(/[\s·<]/)[0]){case"string":return gm;case"number":return Vl;case"date":return xm;case"timestamp":case"timestamptz":return Om;case"boolean":return Im;default:return}}const Bm=16;function So({kind:e,dataType:n}){const r=e==="dimension"||e==="measure"||e==="calculate"||e==="column"?qm(n):void 0;return t.jsx(m.Box,{component:"span","aria-hidden":!0,"data-row-glyph":e,sx:{display:"inline-flex",alignSelf:"center",flexShrink:0,color:Wm(e)},children:T.createElement(r??zm[e==="column"?"dimension":e],{size:Bm})})}function ko(e,n){return(n?e.givensBySource?.get(n):void 0)??e.givens}function Kl(e,n){if(!e.givenValues||!n)return e;const r=new Set(n.map(i=>i.name)),o=Object.entries(e.givenValues).filter(([i])=>r.has(i));return{...e,givenValues:o.length>0?Object.fromEntries(o):void 0}}function Vm({run:e,modelPath:n,query:r,enabled:o}){const{server:i,apiClients:l}=q.useServer(),a=pt.useQuery({...Ql({server:i,apiClients:l,run:e,modelPath:n,query:r}),enabled:o,refetchOnWindowFocus:!1,refetchOnReconnect:!1});return{result:a.data?.data.result,isSuccess:a.isSuccess,isLoading:a.isLoading,isFetching:a.isFetching,isError:a.isError,error:a.error,refetch:a.refetch}}function Co(e,n,r,o){return["model-viewer-run",e,n.projectName,n.packageName,r,n.versionId??"",o,go(n.givenValues),...n.includeHiddenFilesAndSources?["off-surface"]:[]]}function Ql({server:e,apiClients:n,run:r,modelPath:o,query:i}){const l=go(r.givenValues)===""?void 0:r.givenValues;return{queryKey:Co(e,r,o,i),queryFn:async({signal:a})=>{const u=performance.now(),d=()=>Math.round(performance.now()-u);try{const h=await n.models.executeQueryModel(r.projectName,r.packageName,o,{query:i,versionId:r.versionId,...l&&{givens:l},...r.queryMetadata&&{queryMetadata:{...r.queryMetadata}}},r.includeHiddenFilesAndSources?!0:void 0,void 0,{signal:a});return r.onQueryRun?.({outcome:"success",durationMs:d()}),h}catch(h){throw a?.aborted||r.onQueryRun?.({outcome:"error",durationMs:d()}),h}},staleTime:1/0,retry:!1}}const $s=12,Hm=5*6e4;function Um(e){const n=cs(e);return n===void 0?!1:n>=400&&n<500&&n!==401&&n!==408&&n!==429}function Gm(e){if(!e)return[];const{data:n}=JSON.parse(e);return n?.kind!=="array_cell"?[]:n.array_value.flatMap(r=>{if(r.kind!=="record_cell")return[];const o=r.record_value[0];if(!o)return[];switch(o.kind){case"string_cell":return[o.string_value];case"number_cell":return[String(o.number_value)];case"boolean_cell":return[String(o.boolean_value)];case"date_cell":return[o.date_value];case"timestamp_cell":return[o.timestamp_value];default:return[]}})}function Ym({run:e,modelPath:n,sourceName:r,field:o,fetchSamples:i,generation:l}){const{server:a,apiClients:u}=q.useServer(),d=o?.kind==="dimension"&&o.indexed===!0,h=ko(e,r),y=d&&!i?_l(h,e.requiredFiltersBySource?.get(r),e.givenValues):void 0,b=y?.kind==="blocked"?y.reason:void 0,x=d&&!b?o.name:void 0,v=pt.useQuery({...Ql({server:a,apiClients:u,run:Kl(e,h),modelPath:n,query:c.sampleValuesQuery(r,x??"",$s)}),enabled:!!x&&!i,refetchOnWindowFocus:!1,refetchOnReconnect:!1}),k=pt.useQuery({queryKey:["model-viewer-samples",a,e.projectName,e.packageName,e.versionId??"",n,r,x,l??"host"],enabled:!!x&&!!i,staleTime:Hm,retry:!1,refetchOnWindowFocus:!1,queryFn:async({signal:j})=>{try{const M=await i({modelPath:n,sourceName:r,fieldName:x,limit:$s,signal:j}),O=Array.isArray(M)?{values:M}:M;return{...O,values:O.values.slice(0,$s)}}catch(M){if(Um(M))return{values:[]};throw M}}}),C=i?k:v,S=i?k.data:v.data&&{values:Gm(v.data.data.result)};return{samples:S?.values??[],total:S?.total,unavailable:b??S?.unavailable,loading:!!x&&C.isPending,failed:C.isError}}function Km({children:e}){return t.jsx(m.Box,{component:"span",sx:{fontFamily:Dt,fontSize:wt.caption,color:"text.primary",bgcolor:nt.background.muted,border:"1px solid",borderColor:"divider",borderRadius:1,padding:"2px 8px"},children:e})}function Qm({run:e,fetchSamples:n,modelPath:r,sourceName:o,field:i,generation:l}){const{samples:a,total:u,unavailable:d,loading:h,failed:y}=Ym({run:e,fetchSamples:n,modelPath:r,sourceName:o,field:i,generation:l});return t.jsxs(m.Box,{"data-testid":"model-viewer-values",sx:{fontSize:wt.small},children:[t.jsx(m.Box,{component:"div",sx:{color:as,fontSize:wt.caption,mb:"6px"},children:u!=null?`The most common of ${u.toLocaleString()} ${u===1?"value":"values"}`:"The most common values"}),h?t.jsx(m.CircularProgress,{size:12,sx:{color:"text.secondary"}}):d?t.jsx(m.Box,{component:"span","data-testid":"model-viewer-values-unavailable",sx:{color:"text.secondary"},children:d}):y?t.jsx(m.Box,{component:"span",sx:{fontStyle:"italic",color:"text.secondary"},children:"Sample values couldn't be loaded."}):a.length===0?t.jsx(m.Box,{component:"span",sx:{fontStyle:"italic",color:"text.secondary"},children:"No values found."}):t.jsx(m.Box,{sx:{display:"flex",flexWrap:"wrap",gap:"6px"},children:a.map(b=>t.jsx(Km,{children:b},b))})]})}const Fs={scopeName:"source.malloy",patterns:[{include:"#malloy-language"}],repository:{"malloy-language":{patterns:[{include:"#sql-string"},{include:"#comments"},{include:"#tags"},{include:"#strings"},{include:"#numbers"},{include:"#keywords"},{include:"#properties"},{include:"#functions"},{include:"#datetimes"},{include:"#identifiers-quoted"},{include:"#types"},{include:"#constants"},{include:"#timeframes"},{include:"#identifiers-unquoted"}]},"malloy-matched":{begin:"{",end:"}",patterns:[{include:"#malloy-matched"},{include:"#malloy-language"}]},"malloy-in-sql":{begin:"%{",name:"source.malloy-in-sql",end:"}%?",patterns:[{include:"#malloy-matched"},{include:"#malloy-language"}]},"sql-string":{patterns:[{begin:'(\\b[A-Za-z_][A-Za-z_0-9]*)(\\s*\\.\\s*)(sql)(\\s*\\(\\s*)(""")',end:'"""',beginCaptures:{1:{name:"variable.other"},3:{name:"keyword.control.sql"},5:{name:"punctuation.sql-block.open"}},endCaptures:{0:{name:"punctuation.sql-block.close"}},name:"source.sql",patterns:[{include:"#malloy-in-sql"},{include:"source.sql"}]}]},functions:{patterns:[{match:"(?i)\\b(count)(\\s*\\()(distinct)",captures:{1:{name:"entity.name.function"},3:{name:"entity.name.function.modifier"}}},{match:"(?i)\\b(AVG|COUNT|FIRST|FORMAT|LAST|LCASE|LEN|MAX|MID|MIN|MOD|NOW|ROUND|SUM|UCASE|UNGROUPED)(\\s*\\()",captures:{1:{name:"entity.name.function"}}},{match:"(?i)\\b([a-zA-Z_][a-zA-Z_0-9]*)(\\s*\\()",captures:{1:{name:"entity.name.function"}}},{match:"(?i)\\b([a-zA-Z_][a-zA-Z_0-9]*)(!)(timestamp|number|string|boolean|date)?(\\s*\\()",captures:{1:{name:"entity.name.function"},3:{name:"entity.name.type"}}}]},datetimes:{patterns:[{match:"(?i)@[0-9]{4}-[0-9]{2}-[0-9]{2}[ T][0-9]{2}:[0-9]{2}((:[0-9]{2})(([\\.,][0-9]+)(\\[[A-Za-z_/]+\\])?)?)?",name:"constant.numeric.timestamp"},{match:"(?i)@[0-9]{4}(-Q[1-4]|-[0-9]{2}(-[0-9]{2}(-WK)?)?)?",name:"constant.numeric.date"}]},"identifiers-quoted":{patterns:[{match:"`[^`]*`",name:"variable.other.quoted"}]},"identifiers-unquoted":{patterns:[{match:"(?i)\\b[A-Za-z_][A-Za-z_0-9]*\\b",name:"variable.other"}]},timeframes:{patterns:[{match:"(?i)\\b((year|quarter|month|week|day|hour|minute|second)s?)\\b",name:"keyword.other.timeframe"},{match:"(?i)\\b(day_of_year|day_of_month)\\b",name:"keyword.other.timeframe"}]},comments:{patterns:[{begin:"/\\*",end:"\\*/",beginCaptures:{0:{name:"punctuation.definition.comment.begin"}},endCaptures:{0:{name:"punctuation.definition.comment.end"}},name:"comment.block"},{begin:"//",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-slash"},{begin:"--",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-hyphen"}]},tags:{patterns:[{match:"##\\n",name:"string.quoted",captures:{0:{name:"string.quoted"}}},{begin:'#"',end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-slash"},{match:"#\\n",name:"string.quoted",captures:{0:{name:"string.quoted"}}},{begin:"#\\s",end:"\\n",beginCaptures:{0:{name:"support.type.property-name.json"}},name:"comment.line.double-slash",patterns:[{include:"#tag-values"}]},{begin:"##\\s",end:"\\n",beginCaptures:{0:{name:"support.type.property-name.json"}},name:"comment.line.double-slash",patterns:[{include:"#tag-values"}]},{begin:"#",end:"\\n",beginCaptures:{0:{name:"string.quoted"}},name:"string.quoted"}],repository:{"tag-values":{name:"support.type.property-name.json",match:'(-)?((?:[^\\s=#]+)|(?:"[^#]+"))(?:\\s*(=)\\s*((?:[^\\s=#]+)|(?:"[^#]+")))?',captures:{1:{name:"keyword.control.negate"},2:{name:"support.type.property-name.json"},3:{name:"keyword.operator.comparison.ts"},4:{name:"string.quoted"}}}}},strings:{patterns:[{begin:"'",end:"'",beginCaptures:{0:{name:"punctuation.definition.string.begin"}},endCaptures:{0:{name:"punctuation.definition.string.end"}},name:"string.quoted.single",patterns:[{include:"#escapes"}]},{begin:'"',end:'"',beginCaptures:{0:{name:"punctuation.definition.string.begin"}},endCaptures:{0:{name:"punctuation.definition.string.end"}},name:"string.quoted.double",patterns:[{include:"#escapes"}]},{begin:'"""',end:'"""',beginCaptures:{0:{name:"punctuation.definition.string.begin"}},endCaptures:{0:{name:"punctuation.definition.string.end"}},name:"string.quoted.triple"},{begin:"(?i)[r|/]'",end:"'",name:"string.regexp",patterns:[{include:"#regex-escapes"}]}],repository:{escapes:{name:"constant.character.escape",match:"\\\\(u[A-Fa-f0-9]{4}|.)",captures:{0:{name:"constant.character.escape"}}},"regex-escapes":{name:"constant.character.escape",match:"\\\\.",captures:{0:{name:"constant.character.escape"}}}}},numbers:{match:"(?i)(\\b((0|[1-9][0-9]*)(E[+-]?[0-9]+|\\.[0-9]*)?)|\\.[0-9]+)",name:"constant.numeric"},constants:{patterns:[{match:"(?i)\\bnull\\b",name:"constant.language.null"},{match:"(?i)\\btrue\\b",name:"constant.language.true"},{match:"(?i)\\bfalse\\b",name:"constant.language.false"}]},types:{patterns:[{match:"(?i)\\bstring\\b",name:"entity.name.type.string"},{match:"(?i)\\bnumber\\b",name:"entity.name.type.number"},{match:"(?i)\\bdate\\b",name:"entity.name.type.date"},{match:"(?i)\\btimestamp\\b",name:"entity.name.type.timestamp"},{match:"(?i)\\bboolean\\b",name:"entity.name.type.boolean"}]},properties:{patterns:[{match:"(?i)\\baccept\\b",name:"keyword.control.accept"},{match:"(?i)\\bselect\\b",name:"keyword.control.select"},{match:"(?i)\\bconnection\\b",name:"keyword.control.connection"},{match:"(?i)\\brun\\b",name:"keyword.control.run"},{match:"(?i)\\bextend\\b",name:"keyword.control.extend"},{match:"(?i)\\brefine\\b",name:"keyword.control.refine"},{match:"(?i)\\baggregate\\b",name:"keyword.control.aggregate"},{match:"(?i)\\bsample\\b",name:"keyword.control.sample"},{match:"(?i)\\bcalculate\\b",name:"keyword.control.calculate"},{match:"(?i)\\btimezone\\b",name:"keyword.control.timezone"},{match:"(?i)\\bdimension\\b",name:"keyword.control.dimension"},{match:"(?i)\\bexcept\\b",name:"keyword.control.except"},{match:"(?i)\\bsource\\b",name:"keyword.control.source"},{match:"(?i)\\bgroup_by\\b",name:"keyword.control.group_by"},{match:"(?i)\\bhaving\\b",name:"keyword.control.having"},{match:"(?i)\\bindex\\b",name:"keyword.control.index"},{match:"(?i)\\bjoin_one\\b",name:"keyword.control.join_one"},{match:"(?i)\\bwith\\b",name:"keyword.control.with"},{match:"(?i)\\bjoin_many\\b",name:"keyword.control.join_many"},{match:"(?i)\\bjoin_cross\\b",name:"keyword.control.join_cross"},{match:"(?i)\\blimit\\b",name:"keyword.control.limit"},{match:"(?i)\\bmeasure\\b",name:"keyword.control.measure"},{match:"(?i)\\bnest\\b",name:"keyword.control.nest"},{match:"(?i)\\border_by\\b",name:"keyword.control.order_by"},{match:"(?i)\\bpartition_by\\b",name:"keyword.control.partition_by"},{match:"(?i)\\bprimary_key\\b",name:"keyword.control.primary_key"},{match:"(?i)\\bproject\\b",name:"keyword.control.project"},{match:"(?i)\\bquery\\b",name:"keyword.control.query"},{match:"(?i)\\brename\\b",name:"keyword.control.rename"},{match:"(?i)\\btop\\b",name:"keyword.control.top"},{match:"(?i)\\bview\\b",name:"keyword.control.view"},{match:"(?i)\\bwhere\\b",name:"keyword.control.where"},{match:"(?i)\\bdeclare\\b",name:"keyword.control.declare"}]},keywords:{patterns:[{match:"(?i)\\bis\\b",name:"keyword.control.is"},{match:"(?i)\\bon\\b",name:"keyword.control.on"},{match:"(?i)\\bnot\\b",name:"keyword.other.not"},{match:"(?i)\\bor\\b",name:"keyword.other.or"},{match:"(?i)\\bdesc\\b",name:"keyword.control.desc"},{match:"(?i)\\bby\\b",name:"keyword.control.by"},{match:"(?i)\\band\\b",name:"keyword.other.and"},{match:"(?i)\\basc\\b",name:"keyword.control.asc"},{match:"(?i)\\bfor\\b",name:"keyword.other.for"},{match:"(?i)\\belse\\b",name:"keyword.other.else"},{match:"(?i)\\bto\\b",name:"keyword.other.to"},{match:"(?i)\\bwhen\\b",name:"keyword.other.when"},{match:"(?i)\\bpick\\b",name:"keyword.other.pick"},{match:"(?i)\\bimport\\b",name:"keyword.control.import"}]}}},Zm={...Fs,patterns:[...Fs.patterns,{include:"#docvar"}],repository:{...Fs.repository,docvar:{patterns:[{match:"\\<\\<[^(\\>\\>)]*\\>\\>",beginCaptures:{0:{name:"punctuation.definition.comment.begin"}},endCaptures:{0:{name:"punctuation.definition.comment.end"}},name:"markup.italic.markdown"}]}}},Xm={name:"Malloy SQL",scopeName:"source.malloy-sql",patterns:[{include:"#malloysql-sql"}],repository:{"malloysql-sql":{beginCaptures:{0:{name:"entity.other.attribute.malloy-sql"},1:{name:"entity.other.attribute.malloy-sql"},3:{name:"comment.line.double-slash"}},name:"meta.embedded.block.malloysql.sql",patterns:[{include:"#comments"},{begin:"%{",end:"}%",beginCaptures:{0:{name:"punctuation.definition.malloy-sql"}},endCaptures:{0:{name:"punctuation.definition.malloy-sql"}},name:"meta.embedded.block.malloy",patterns:[{include:"source.malloy"}]},{include:"source.sql"}]},comments:{patterns:[{begin:"/\\*",end:"\\*/",beginCaptures:{0:{name:"punctuation.definition.comment.begin"}},endCaptures:{0:{name:"punctuation.definition.comment.end"}},name:"comment.block"},{begin:"//",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-slash"},{begin:"--",end:"\\n",beginCaptures:{0:{name:"punctuation.definition.comment"}},name:"comment.line.double-hyphen"}]}}},Jm="github-light",eg="github-dark";let Ls;function tg(){return Ls||(Ls=(async()=>{const[{createHighlighterCore:e},{createOnigurumaEngine:n},{default:r},{default:o},{default:i},{default:l},{default:a}]=await Promise.all([Promise.resolve().then(()=>require("./core-8NVBCLZh.cjs.js")),Promise.resolve().then(()=>require("./engine-oniguruma-BkproSVE.cjs.js")),Promise.resolve().then(()=>require("./sql-BqWZrLHB.cjs.js")),Promise.resolve().then(()=>require("./json-y-J1j5EW.cjs.js")),Promise.resolve().then(()=>require("./typescript-BqvpT6pB.cjs.js")),Promise.resolve().then(()=>require("./github-light-BFTOhCbz.cjs.js")),Promise.resolve().then(()=>require("./github-dark-BKL9xNgN.cjs.js"))]);return e({engine:n(Promise.resolve().then(()=>require("./wasm-Dw4u1m6u.cjs.js"))),themes:[l,a],langs:[r,o,i,{name:"malloy",scopeName:"source.malloy",embeddedLangs:["sql"],...Zm},{name:"malloysql",scopeName:"source.malloy-sql",embeddedLangs:["sql"],...Xm}]})})()),Ls}async function To(e,n,r="light"){return(await tg()).codeToHtml(e,{lang:n,theme:r==="dark"?eg:Jm})}function Or({code:e,testId:n,framed:r=!0}){const{mode:o}=q.usePublisherTheme(),[i,l]=T.useState(void 0);return T.useEffect(()=>{let a=!0;return To(e,"malloy",o).then(u=>a&&l(u)).catch(()=>a&&l(void 0)),()=>{a=!1}},[e,o]),t.jsx(m.Box,{"data-testid":n,sx:{fontFamily:Dt,fontSize:"0.75rem",overflowX:"auto","& pre":{m:0,background:"transparent !important"},...r&&{border:"1px solid",borderColor:"divider",borderRadius:1,px:1.5,py:1,bgcolor:"background.default"}},children:i?t.jsx("div",{dangerouslySetInnerHTML:{__html:i}}):t.jsx(m.Box,{component:"pre",sx:{whiteSpace:"pre"},children:e})})}function ds({message:e,onRetry:n,severity:r="error"}){return t.jsx(m.Alert,{severity:r,action:n&&t.jsx(m.Button,{color:"inherit",size:"small",onClick:n,children:"Retry"}),children:e})}function Zl(e){const n=e?.response?.data?.message;return typeof n=="string"&&n?n:void 0}function Xl(e,n){const r=Zl(n);return r?`${e}: ${r}`:`${e}.`}function ng(e){const n=cs(e);return!(n===400||n===401||n===403||n===404||n===422)}function rg({query:e,error:n,onRetry:r,testId:o,forbiddenMessage:i}){const l=i!==void 0&&cs(n)===403;return t.jsxs(m.Box,{"data-testid":o,sx:{display:"flex",flexDirection:"column",gap:1},children:[e&&t.jsx(Or,{code:e,testId:"query-failure-code"}),t.jsx(ds,{message:l?i:Xl("Query failed",n),onRetry:r&&ng(n)?r:void 0})]})}const ka=T.forwardRef(function(n,r){return t.jsx(m.Button,{ref:r,variant:"contained",size:"small",disableElevation:!0,...n,sx:{textTransform:"none",...n.sx}})}),sg=T.forwardRef(function(n,r){return t.jsx(m.Button,{ref:r,variant:"outlined",size:"small",color:"inherit",...n,sx:{textTransform:"none",borderRadius:999,borderColor:"divider",color:"text.secondary",...n.sx}})}),yr=10,og="clamp(340px, 40%, 520px)";function ig({field:e,run:n,modelPath:r,sourceName:o,fieldCode:i,joined:l=!1}){const[a,u]=vo(),{fetchSamples:d,samplesGeneration:h,renderFieldStatus:y,renderFieldAction:b,renderFieldDetail:x}=ls(),v={modelPath:r,sourceName:o,field:e,joined:l},k=y?.(v),C=b?.(v),S=e.doc?void 0:i?.columnDoc,j=e.doc??S,M=wo(i),O=T.useContext(xo),E=T.useMemo(()=>dn(i?.code,O),[i?.code,O]),$=bo(e)&&!l&&!!n,P=[...M?["code"]:[],...$?["values"]:[],...E.length>0?["givens"]:[]],A=R=>P.includes(R),B=e.kind==="measure"?"measure":e.kind==="calculate"?"calculate":"dimension",D=P.length>0?t.jsxs(m.Box,{"data-testid":"model-viewer-field-card",sx:{...Pn,"& > * + *":{borderTop:1,borderColor:"divider"}},children:[A("code")&&(i?.loading?t.jsx(m.Box,{sx:{p:Tr,display:"flex"},children:t.jsx(m.CircularProgress,{size:12,sx:{color:"text.secondary"}})}):i?.code?t.jsx(Or,{testId:"model-viewer-definition",code:Lm(e.name,i.code),framed:!1}):i?.inheritedFrom?t.jsx(Or,{testId:"model-viewer-definition",code:`${i.inheritedFrom.fromTable?"// A column of the table this source reads, as it is":"// Passed through from the query this source is built on"}
|
|
28
|
+
${i.inheritedFrom.code}`,framed:!1}):t.jsx(m.Box,{sx:{p:1},children:t.jsx(ds,{message:"Couldn't load this model's code right now."})})),A("values")&&n&&t.jsx(m.Box,{sx:{p:Tr},children:t.jsx(Qm,{run:n,fetchSamples:d,generation:h,modelPath:r,sourceName:o,field:e})}),A("givens")&&t.jsx(mo,{givens:E,framed:!1})]}):void 0,_=x?x(v,D):D,V=_!=null&&_!==!1;return t.jsxs(m.Box,{"data-testid":"model-viewer-field-row","data-name":e.name,sx:a&&V?{pb:1.25}:void 0,children:[t.jsx(jo,{glyph:t.jsx(So,{kind:B,dataType:e.dataType}),name:e.name,typeLabel:e.dataType,typeTip:e.typeTip,typeAsChip:!0,stackPills:!0,doc:j,generatedDoc:!!S,open:a,expandable:V,onToggle:()=>u(R=>!R),descriptors:t.jsx(Cl,{givens:E}),pills:k,action:C}),V&&t.jsx(m.Collapse,{in:a,timeout:"auto",unmountOnExit:!0,children:t.jsx(m.Box,{"data-testid":"model-viewer-field-detail",sx:{mx:`${yr}px`,mt:"2px",display:"flex",flexDirection:"column",gap:1.5},children:_})})]})}function jo({glyph:e,name:n,typeLabel:r,typeAsChip:o=!1,stackPills:i=!1,typeTip:l,descriptors:a,pills:u,action:d,trailing:h,doc:y,generatedDoc:b=!1,open:x,expandable:v,onToggle:k}){const C=T.useId(),S=j=>{if(!v||j.target.closest("[data-row-action]"))return;const M=j.target.closest("button, a, [role='button']");M&&!M.hasAttribute("data-field-toggle")||k()};return t.jsxs(m.Box,{onClick:S,sx:{display:"flex",alignItems:x?"flex-start":"center",borderRadius:1.5,transition:"background 0.1s",cursor:v?"pointer":"default",...v?{"&:hover":{bgcolor:nt.background.muted},"&:hover [data-pill-tone='quiet']":{bgcolor:nt.background.strong}}:{}},children:[t.jsxs(m.Box,{sx:{display:"flex",flexDirection:i?"column":"row",alignItems:i?"stretch":"center",minWidth:0,flexShrink:0,width:{md:og},overflow:{md:"hidden"}},children:[t.jsxs(m.Box,{component:v?"button":"div",type:v?"button":void 0,"aria-expanded":v?x:void 0,"aria-describedby":i?C:void 0,"data-field-toggle":v?"":void 0,sx:{appearance:"none",border:"none",background:"none",font:"inherit",color:"inherit",textAlign:"left",minWidth:0,px:`${yr}px`,py:"6px",borderRadius:1.5,...jr,display:"flex",alignItems:"baseline",gap:"8px",flexWrap:i?"nowrap":"wrap",rowGap:"4px",cursor:v?"pointer":"default"},children:[e,t.jsxs(m.Box,{component:"span",sx:{display:"contents","& > *":{flexShrink:0},...i?{"& > *:first-of-type":{flexShrink:1,minWidth:0}}:{}},children:[t.jsx(m.Box,{component:"span",title:n,sx:{...Qp,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:n}),r&&(o?t.jsx(m.Tooltip,{title:l?t.jsx(m.Box,{sx:{whiteSpace:"pre-line"},children:l}):"",children:t.jsx(At,{voice:"token",tone:"quiet",sx:{alignSelf:"center"},children:r})}):t.jsx(m.Box,{component:"span",sx:Ll,children:r})),a]}),!i&&u]}),i?t.jsxs(m.Box,{id:C,sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:"8px",px:`${yr}px`,pb:"6px",mt:"-2px","&:empty":{display:"none"}},children:[u,d&&t.jsx(m.Box,{component:"span","data-row-action":"",sx:{display:"inline-flex"},children:d})]}):d&&t.jsx(m.Box,{component:"span","data-row-action":"",sx:{display:"inline-flex"},children:d})]}),y&&t.jsxs(m.Box,{component:"span","data-testid":"model-viewer-field-doc",onMouseEnter:j=>{const M=j.currentTarget;M.title=!x&&Pm(M,y)?y:""},sx:{flex:1,minWidth:0,ml:1,pr:`${yr}px`,py:x?"6px":0,fontSize:wt.small,color:as,...x?{whiteSpace:"pre-line"}:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"}},children:[b&&t.jsx(At,{voice:"state",tone:"quiet","data-testid":"model-viewer-field-doc-generated",sx:{mr:.75,verticalAlign:"baseline"},children:"Generated"}),x?y:y.split(`
|
|
29
|
+
`)[0]]}),h&&t.jsx(m.Box,{sx:{ml:"auto",flexShrink:0,pl:1,pr:`${yr}px`,display:"inline-flex",alignItems:"center",height:32},children:h})]})}const ag=480;function lg({run:e,modelPath:n,query:r,sourceName:o,givens:i,givensUnknown:l,mode:a="result",renderCode:u,onShownChange:d}){const h=go(e.givenValues),[y,b]=T.useState(a==="result"?h:null);a==="result"&&y===null&&b(h);const x=y!==null&&y!==h,v=o?e.requiredFiltersBySource?.get(o):void 0,[k,C]=T.useState(null),S=k===h,j=T.useMemo(()=>_l(i??ko(e,o),v,e.givenValues,i?l:o?e.unknownGivensBySource?.get(o):void 0,S,i?"query":"source"),[e,o,i,l,v,S]),{result:M,isSuccess:O,isError:E,error:$,refetch:P}=Vm({run:e,modelPath:n,query:r,enabled:y===h&&j.kind!=="blocked"});y!==null&&y!==h&&M!==void 0&&b(h);const A=Qr(e.accessBySource,o),B=Lp(o,A),D=()=>x?b(h):void P(),[_,V]=T.useState(null);M!==void 0&&(_?.givensKey!==h||_.result!==M)&&V({result:M,givensKey:h});const R=j.kind==="blocked"?void 0:M!==void 0?{result:M,givensKey:h}:x&&_?{result:_.result,givensKey:_.givensKey}:void 0,W=R?.result,Z=T.useMemo(()=>_p(A,W),[A,W]),ne=R?.givensKey??"";T.useEffect(()=>{if(d){if(W===void 0)return d(void 0);d({result:W,givensKey:ne})}},[d,W,ne]);const J=a==="result"&&j.kind!=="blocked";return T.useEffect(()=>{J&&c.warmMalloyRenderer()},[J]),t.jsx(m.Box,{"data-testid":"model-viewer-run-result","data-mode":a,children:a==="code"?u?.():j.kind==="blocked"?t.jsxs(m.Box,{sx:{display:"flex",alignItems:"center",gap:1.5,flexWrap:"wrap"},children:[t.jsx(un,{"data-testid":"model-viewer-run-blocked",children:j.reason}),j.canRunAnyway&&t.jsx(ka,{size:"small",onClick:()=>{C(h),b(h)},children:"Run anyway"})]}):E&&!x?t.jsx(rg,{query:r,error:$,onRetry:()=>void P(),forbiddenMessage:B}):O&&!M&&!x?t.jsx(xr,{message:"The query returned no result."}):t.jsxs(m.Box,{"data-testid":"model-viewer-result-card",sx:{...Pn,p:Tr,overflowX:"auto"},children:[x&&t.jsxs(m.Box,{"data-testid":"model-viewer-run-stale",sx:{display:"flex",alignItems:"center",gap:1.5,flexWrap:"wrap",mb:1},children:[t.jsx(un,{children:"The given values changed since this ran."}),t.jsx(ka,{size:"small",onClick:D,"aria-label":"Run with these values",children:"Run"})]}),j.kind==="noted"&&W&&!x&&t.jsx(Cr,{"data-testid":"model-viewer-run-defaults",component:"div",sx:{mb:1},children:j.note}),!(x&&!W)&&(W===void 0?t.jsx(c.Loading,{text:c.LOADING_COPY.running}):t.jsx(c.ResultContainer,{result:W,maxHeight:ag,maxResultSize:e.maxResultSize})),Z&&t.jsx(Cr,{"data-testid":"model-viewer-run-filtered",component:"div",sx:{mt:1},children:Z})]})})}function cg(e){return{p:"3px",borderRadius:1,color:e?"text.primary":"text.secondary",bgcolor:e?nt.background.strong:"transparent","&:hover":{bgcolor:e?nt.background.strong:nt.background.muted,color:"text.primary"},"&.Mui-disabled":{color:"text.disabled"}}}function ug({value:e,options:n,onChange:r,"aria-label":o}){return t.jsx(m.Box,{role:"group","aria-label":o,sx:{display:"inline-flex",gap:"2px"},children:n.map(i=>{const l=i.value===e,a=i.disabled===!0;return t.jsx(m.Tooltip,{title:a?i.disabledReason??i.label:i.label,children:t.jsx("span",{style:{display:"inline-flex"},children:t.jsx(m.IconButton,{size:"small",role:"button","aria-pressed":l,"aria-label":a?i.disabledReason??i.label:i.label,disabled:a,onClick:()=>r(i.value),sx:cg(l),children:i.icon})})},i.value)})})}const dg=["result","givens","fields","code","values","access"],hg={result:{icon:t.jsx(Bl,{size:14}),label:"Result"},fields:{icon:t.jsx(Tm,{size:14}),label:"Fields"},code:{icon:t.jsx(bm,{size:14}),label:"Code"},values:{icon:t.jsx(Em,{size:14}),label:"Values"},givens:{icon:t.jsx(Dm,{size:14}),label:"Givens"},access:{icon:t.jsx(Mm,{size:14}),label:"Access"}};function Jl(e,n){const r=dg.filter(a=>e.includes(a)),[o,i]=T.useState(void 0),l=o!==void 0&&r.includes(o)?o:n!==void 0&&r.includes(n)?n:r[0];return{layers:r,layer:l,setLayer:i}}function ec({layers:e,value:n,onChange:r,"aria-label":o,disabledReasons:i}){return e.length<2||n===void 0?null:t.jsx(ug,{"aria-label":o,value:n,onChange:r,options:e.map(l=>{const a=i?.[l];return{value:l,...hg[l],...a?{disabled:!0,disabledReason:a}:{}}})})}function tc({field:e,modelPath:n,sourceName:r,fieldCode:o,run:i,runQuery:l,runGivens:a,runGivensUnknown:u}){const d=l??c.viewRunQuery(r,e.name),h=a??(i&&ko(i,r)),y=T.useMemo(()=>i&&Kl(i,h),[i,h]),b=l?"query":"view",[x,v]=vo(),[k,C]=T.useState(void 0),S=wo(o),j=T.useContext(xo),{renderRunActions:M}=ls(),{server:O}=q.useServer(),E=T.useMemo(()=>dn(o?.code,j),[o?.code,j]),{chartNames:$,tagsInFull:P}=T.useMemo(()=>{const W=e.tags??[],Z=rp(W),ne=Z.length>0?Z:W;return{chartNames:ne,tagsInFull:W.join(" ")===ne.join(" ")?void 0:W.map(J=>`# ${J}`).join(`
|
|
30
|
+
`)}},[e.tags]),A=["result","code",...E.length>0?["givens"]:[]],{layers:B,layer:D,setLayer:_}=Jl(A,i?"result":"code"),V=D??"code",R=()=>V==="givens"?t.jsx(mo,{givens:E}):o?.loading?t.jsx(m.CircularProgress,{size:12,sx:{color:"text.secondary"}}):o?.code?t.jsx(Or,{testId:"model-viewer-definition",code:l?o.code:_m(e.name,o.code)}):o?.error?t.jsx(ds,{message:"Couldn't load this model's code right now."}):t.jsx(xr,{message:`No Malloy code to show for this ${b}.`});return t.jsxs(m.Box,{"data-testid":"model-viewer-view-row","data-name":e.name,sx:x?{pb:1.5}:void 0,children:[t.jsx(jo,{glyph:t.jsx(So,{kind:"view"}),name:e.name,doc:e.doc,open:x,expandable:!0,onToggle:()=>v(W=>!W),trailing:x&&t.jsxs(m.Box,{sx:{display:"flex",alignItems:"center",gap:"2px"},children:[t.jsx(ec,{"aria-label":`Show for ${e.name}`,layers:B,value:V,onChange:_,disabledReasons:{result:i?void 0:`This ${b} can't be run here`,code:S?void 0:`No Malloy code to show for this ${b}`}}),y&&M?.({kind:l?"query":"view",modelPath:n,sourceName:l?"":r,name:e.name,query:d,givens:y.givenValues,queryKey:Co(O,y,n,d),shown:k})]}),descriptors:t.jsxs(t.Fragment,{children:[$.map(W=>{const Z=t.jsx(At,{voice:"token",tone:"quiet",sx:{alignSelf:"center"},children:W},W);return P?t.jsx(m.Tooltip,{title:P,slotProps:{tooltip:{sx:{whiteSpace:"pre-line",fontFamily:Dt}}},children:Z},W):Z}),t.jsx(Cl,{givens:E})]})}),t.jsx(m.Collapse,{in:x,timeout:"auto",mountOnEnter:!0,children:t.jsx(m.Box,{"data-testid":"model-viewer-view-card",sx:{mx:"10px",mt:1,minWidth:0},children:t.jsx(m.Box,{sx:{minWidth:0,overflowX:"auto"},children:y?t.jsx(lg,{run:y,modelPath:n,query:d,sourceName:r||void 0,givens:a,givensUnknown:u,mode:V==="result"?"result":"code",renderCode:R,onShownChange:C}):R()})})})]})}function fg({queries:e,sourceText:n,modelPath:r,run:o}){const{parsed:i,pending:l}=Gl(n,e.length>0),a=T.useMemo(()=>e.map(d=>{const h=Fm(i,d.name),y=d.sourceName||!o?.givens||l?void 0:jp(h,o.givens,o.givensBySource,o.unknownGivensBySource);return{query:d,field:{name:d.name,kind:"view",doc:d.doc,tags:d.tags},code:{code:h,loading:l},runGivens:y?.givens,runGivensUnknown:y?.unknown}}),[e,i,l,o?.givens,o?.givensBySource,o?.unknownGivensBySource]),u=ns({noun:["query","queries"]});return t.jsx(_n,{label:"Queries",count:e.length,testId:"model-viewer-queries",action:u.action,children:t.jsx(Mr.Provider,{value:u.command,children:a.map(({query:d,field:h,code:y,runGivens:b,runGivensUnknown:x})=>t.jsx(tc,{field:h,modelPath:r,sourceName:d.sourceName??"",fieldCode:y,run:o,runQuery:c.namedQueryRunQuery(d.name),runGivens:b,runGivensUnknown:x},d.name))})})}function nc(e){const{entities:n,loading:r,error:o,columnDescriptions:i,declarations:l,declarationsLoading:a}=e;return u=>{const d=n?.get(u.name),h=l?.get(u.name);if(!d&&!r&&h&&h.kind===u.kind)return{code:h.code,loading:!1,error:!1,inherited:!1};if(!d&&!r&&!o&&a)return{loading:!0,error:!1,inherited:!1};const y=d?.fieldType==="column";return{code:y?void 0:d?.code??void 0,inheritedFrom:y&&d?.code?{code:d.code,fromTable:!!d.table||d.code!==u.name}:void 0,loading:!o&&r,error:o,inherited:y,columnDoc:y?i?.get(u.name):void 0}}}const Ca=200;function br({label:e,noun:n,items:r,run:o,modelPath:i,sourceName:l,getFieldCode:a,level:u}){const{showField:d}=ls(),h=T.useMemo(()=>d?r.filter(M=>d({modelPath:i,sourceName:l,field:M,joined:u==="h3"})):r,[r,d,i,l,u]),[y,b]=T.useState(!1),x=h.some(M=>bo(M)&&u!=="h3"||wo(a?.(M))),{command:v,action:k}=ns({noun:n,disabledReason:x?void 0:`None of these ${n[1]} has anything to show`}),C=u!=="h3"?k:void 0,S=T.useMemo(()=>a?Nm(h,a):h,[h,a]),j=y||S.length<=Ca?S:S.slice(0,Ca);return t.jsx(_n,{label:e,count:h.length,level:u,action:C,children:t.jsx(Mr.Provider,{value:v,children:t.jsxs(m.Box,{sx:{display:"flex",flexDirection:"column",gap:"3px"},children:[j.map(M=>t.jsx(ig,{field:M,run:o,modelPath:i,sourceName:l,fieldCode:a?.(M),joined:u==="h3"},M.name)),j.length<S.length&&t.jsxs(m.Button,{size:"small",onClick:()=>b(!0),sx:{alignSelf:"flex-start",textTransform:"none"},children:["Show all ",S.length.toLocaleString()," ",n[1]]})]})})})}function pg(e,n){const r=new Map;if(!e||!n)return r;const o=new Map;for(const l of e.symbols)l.type==="explore"&&o.set(Mo(l.name),l);const i=new Set;for(let l=n;l&&!i.has(l);){i.add(l);const a=o.get(l);if(!a)break;for(const[u,d]of gg(e.lines,a))r.has(u)||r.set(u,d);l=Cg(us(e.lines,a.range))}return r}const Ta=/^\s*(view|measure|dimension)\s*:\s*$/,mg=/^`?([A-Za-z_]\w*)`?\s+is\b/;function gg(e,n){const r=new Map;let o,i=n.range.start;for(const a of n.children){const u=us(e,{start:i,end:a.range.start});o=wg(u)??o,i=a.range.end;const d=yg(a,o);if(!d)continue;const h=xg(e,a,d);if(!h)continue;const y=Mo(a.name);r.set(y,r.has(y)?null:h)}const l=new Map;for(const[a,u]of r)u&&l.set(a,u);return l}function yg(e,n){if(e.type==="query")return n==="view"?"view":void 0;if(e.type==="field"&&(n==="dimension"||n==="measure"))return n}function xg(e,n,r){const o=us(e,n.range).split(`
|
|
31
31
|
`),i=[];for(;o.length>1&&/^\s*(#|\/\/|--|$)/.test(o[0]);){const u=o.shift().trim();u.startsWith("#")&&i.push(u)}o[0]=o[0].trimStart();const l=o.join(`
|
|
32
|
-
`).trimEnd(),a=
|
|
33
|
-
`)}}function
|
|
34
|
-
`,r),l=i===-1?e.length:i;n+=" ".repeat(l-r),r=l-1}else n+=o}return n}function yg(e,n){const r=e[n];for(let o=n+1;o<e.length;o++)if(e[o]==="\\")o++;else if(e[o]===r)return o;return e.length}function xg(e){return/^`?[A-Za-z_]\w*`?\s+is\s+`?([A-Za-z_]\w*)`?\s*(?:extend\b|$)/.exec(e)?.[1]}function Oo(e){return e.replace(/^`(.*)`$/,"$1")}const vg=["fields","code"],Ta={display:"inline-flex",alignItems:"center",color:"text.secondary",borderRadius:1,padding:"2px",flexShrink:0,"&:hover":{color:ts}};function bg({join:e,run:n,modelPath:r,sourceName:o,link:i,entitiesByName:l,entitiesLoading:a,entitiesError:u,code:d,target:h,showRules:y=!1}){const[b,x]=vo(),{layers:v,layer:k,setLayer:C}=Ql(vg),S=j.useMemo(()=>l?Jl({entities:l,loading:!!a,error:!!u}):void 0,[l,a,u]),T=e.dimensions.length+e.measures.length,O=t.jsxs(p.Box,{sx:{display:"inline-flex",alignItems:"center",gap:1},children:[b&&t.jsx(Zl,{"aria-label":`Show for ${e.name}`,layers:v,value:k,onChange:C,disabledReasons:{code:d?void 0:"No Malloy code to show for this join"}}),i?.kind==="link"&&i.href&&t.jsx(p.Link,{href:i.href,"aria-label":`Open ${e.name}`,title:`Open ${e.name}`,sx:Ta,children:t.jsx(wa,{size:14})}),i?.kind==="link"&&!i.href&&i.onOpen&&t.jsx(p.Link,{component:"button",type:"button",onClick:i.onOpen,"aria-label":`Open ${e.name}`,title:`Open ${e.name}`,sx:Ta,children:t.jsx(wa,{size:14})}),i?.kind==="join-only"&&t.jsx(p.Box,{component:"span",sx:{fontSize:wt.micro,fontStyle:"italic",color:"text.secondary",flexShrink:0},children:"only accessible via join"})]});return t.jsxs(p.Box,{"data-testid":"model-viewer-join-row","data-name":e.name,sx:b?{pb:1.25}:void 0,children:[t.jsx(To,{glyph:t.jsx(So,{kind:"join"}),name:e.name,typeLabel:`${T} ${T===1?"field":"fields"}`,stackPills:!0,descriptors:t.jsxs($t,{tone:"quiet",voice:"token",sx:{alignSelf:"center",flexShrink:0},children:["join_",e.relationship]}),doc:e.doc,open:b,expandable:!0,onToggle:()=>x(M=>!M),trailing:O,pills:h&&t.jsx(Il,{access:h.access})}),t.jsx(p.Collapse,{in:b,timeout:"auto",unmountOnExit:!0,children:t.jsx(p.Box,{sx:{mx:"10px",mt:"2px"},children:k==="code"&&d?t.jsx(Mr,{testId:"model-viewer-join-code",code:d}):t.jsxs(p.Box,{"data-testid":"model-viewer-join-fields",sx:{...Pn,bgcolor:"transparent",p:1.5,pb:0},children:[h&&y&&t.jsx(Cr,{component:"div","data-testid":"model-viewer-join-gate-warning",sx:{mb:1},children:$m(h.sourceName,h.access)}),t.jsx(br,{label:"Measures",noun:["measure","measures"],level:"h3",items:e.measures,run:n,modelPath:r,sourceName:o,getFieldCode:S}),t.jsx(br,{label:"Dimensions",noun:["dimension","dimensions"],level:"h3",items:e.dimensions,run:n,modelPath:r,sourceName:o,getFieldCode:S})]})})})]})}function wg({source:e,modelPath:n,entitiesByName:r,entitiesLoading:o,entitiesError:i,modelText:l,joinLinks:a,joinEntities:u,joinCodes:d,joinAccess:h,showRules:y=!1,columnDescriptions:b,run:x,queries:v,givens:k}){const C={run:x,modelPath:n,sourceName:e.name},{showField:S}=ls(),T=j.useMemo(()=>S?e.views.filter(D=>S({modelPath:n,sourceName:e.name,field:D,joined:!1})):e.views,[S,e,n]),O=ns({noun:["view","views"]}),M=ns({noun:["join","joins"]}),E=j.useMemo(()=>!o&&[...e.views,...e.measures,...e.calculations,...e.dimensions].some(D=>!r?.get(D.name)),[o,r,e]),{parsed:R,pending:P}=Vl(l,E),F=j.useMemo(()=>lg(R,e.name),[R,e.name]),B=j.useMemo(()=>Jl({entities:r,loading:!!o,error:!!i,columnDescriptions:b,declarations:F,declarationsLoading:P}),[r,o,i,b,F,P]);return t.jsxs(p.Box,{sx:{paddingBottom:"24px"},children:[k,t.jsx(_n,{label:"Views",count:T.length,action:O.action,children:t.jsx(Or.Provider,{value:O.command,children:T.map(D=>t.jsx(Xl,{field:D,modelPath:n,sourceName:e.name,fieldCode:B(D),run:x},D.name))})}),v,t.jsx(br,{label:"Measures",noun:["measure","measures"],items:e.measures,getFieldCode:B,...C}),t.jsx(br,{label:"Calculations",noun:["calculation","calculations"],items:e.calculations,getFieldCode:B,...C}),t.jsx(br,{label:"Dimensions",noun:["dimension","dimensions"],items:e.dimensions,getFieldCode:B,...C}),t.jsx(_n,{label:"Joins",count:e.joins.length,action:M.action,children:t.jsx(Or.Provider,{value:M.command,children:e.joins.map(D=>t.jsx(bg,{join:D,run:x,modelPath:n,sourceName:e.name,link:a?.get(D.name),entitiesByName:u?.get(D.name),code:d?.get(D.name),target:h?.get(D.name),showRules:y,entitiesLoading:o,entitiesError:i},D.name))})})]})}function no(e){return{name:e.name,kind:e.kind,dataType:mo(e.type),typeTip:em(e.type),tags:tm(e.annotations),doc:Ln(e.annotations),indexed:e.kind==="dimension"?gm(e):void 0,preaggregate:e.kind==="measure"?Jf(e.annotations):void 0}}function Sg(e){const n=[],r=[];for(const o of e.schema?.fields??[]){if(o.kind!=="dimension"&&o.kind!=="measure")continue;const i={...no(o),indexed:!1,preaggregate:!1};o.kind==="dimension"?n.push(i):r.push(i)}return{name:e.name,relationship:e.relationship,doc:Ln(e.annotations),dimensions:n,measures:r}}function kg(e,n){const r={name:e.name,doc:Ln(e.annotations),docParts:yl(e.annotations),accent:Bm(n),persist:Xf(e.annotations),dimensions:[],measures:[],calculations:[],views:[],joins:[]};for(const o of e.schema?.fields??[])switch(o.kind){case"dimension":case"measure":r[o.kind==="dimension"?"dimensions":"measures"].push(no(o));break;case"calculate":r.calculations.push(no(o));break;case"view":r.views.push({name:o.name,kind:"view",doc:Ln(o.annotations),tags:fo(o.annotations)});break;case"join":r.joins.push(Sg(o));break}return r}function Cg(e){const n=[];for(const r of e??[]){if(!r.name)continue;const o=(r.annotations??[]).map(i=>({value:i}));n.push({name:r.name,sourceName:r.sourceName||void 0,doc:Ln(o),tags:fo(o)})}return n}function ec(e){return e.dimensions.length+e.measures.length+e.calculations.length+e.views.length}function jg(e,n){if(e.length===0)return null;const r=h=>h.toLowerCase().replace(/[-_]/g,""),o=n?r((n.split("/").pop()??n).replace(/\.malloy$/,"")):void 0,i=new Map(e.map(h=>[h.name,new Set(h.views.map(y=>y.name))])),l=h=>e.some(y=>{if(y.name===h.name||y.views.length===0)return!1;const b=i.get(h.name);return y.views.length<h.views.length&&[...i.get(y.name)].every(x=>b.has(x))}),a=e.filter(h=>!l(h)),u=a.length>0?a:e;let d=u[0];for(const h of u.slice(1)){if(h.views.length!==d.views.length){h.views.length>d.views.length&&(d=h);continue}o&&r(h.name)===o&&r(d.name)!==o&&(d=h)}return d}function Tg(e,n,r){if(!e||!n)return;const i=new RegExp("source:\\s*`?"+pn(n)+"`?\\s+is\\s+`?([A-Za-z_]\\w*)`?\\s*(?:->|extend\\b)").exec(e);if(!i)return;const l=i[1];return r.has(l)?l:void 0}function _s(e,n){return`${e} ${e===1?n:`${n}s`}`}function Og(e){const n=ec(e),r=[_s(e.views.length,"view"),_s(n,"field")];return e.joins.length>0&&r.push(_s(e.joins.length,"join")),r.join(" · ")}function Mg(e,n,r){if(r){const u=r.exportOrder,d=u.length>0&&e.some(h=>u.includes(h.name));return{sources:Dg(e,h=>h.name,u),curated:!0,exportOrdered:d}}const o=e.map((u,d)=>({source:u,index:d})).filter(({source:u})=>u.name!==n?.name).sort((u,d)=>d.source.views.length-u.source.views.length||u.index-d.index).map(({source:u})=>u),i=n?[n,...o]:o,l=n?.views.length??0,a=n&&l>0&&e.every(u=>u.views.length<=l)?n.name:void 0;return{sources:i,curated:!1,exportOrdered:!1,mostViews:a}}function Eg(e){return/^`.*`$/.test(e)?e.slice(1,-1):e}function Ig(e){if(!e)return[];const n=Ir(e),r=[];for(const o of n.matchAll(/(?:^|[\s;])export\s*\{([^}]*)\}/gi))for(const i of o[1].split(",")){const l=Eg(i.trim());l&&!r.includes(l)&&r.push(l)}return r}function Dg(e,n,r){if(r.length===0)return[...e];const o=i=>{const l=r.indexOf(n(i));return l===-1?r.length:l};return e.map((i,l)=>({item:i,index:l})).sort((i,l)=>o(i.item)-o(l.item)||i.index-l.index).map(({item:i})=>i)}function $g(e,n){const r=e?.trim();if(r)return{text:r,generated:!1};const o=n?.trim();return o?{text:o,generated:!0}:void 0}const Fg="This package's curated sources, in the order its index.malloy exports them.",Ag="This package's public sources.";function Rg(e){return e.mostViews?", most views":""}function Lg({anchorEl:e,onClose:n,sources:r,currentName:o,onPickSource:i,curated:l=!1,exportOrdered:a=!1}){const u=!!e;return t.jsxs(p.Popover,{open:u,anchorEl:e,onClose:n,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},slotProps:{paper:{sx:{width:460,maxWidth:"calc(100vw - 32px)",maxHeight:"min(70vh, 560px)",display:"flex",flexDirection:"column",borderRadius:"10px"},"data-testid":"model-sources-dropdown"}},children:[t.jsxs(p.Box,{sx:{px:2,pt:1.5,pb:1,borderBottom:1,borderColor:"divider"},children:[t.jsx(p.Typography,{variant:"subtitle2",component:"h2",sx:{m:0},children:"Sources"}),t.jsx(Cr,{component:"p",sx:{m:0},children:l?a?Fg:Ag:Gm})]}),t.jsx(p.Box,{sx:{overflowY:"auto",py:.5},children:r.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{py:4,textAlign:"center"},children:"This model defines no sources."}):r.map(d=>{const h=d.name===o;return t.jsxs(p.ButtonBase,{"data-item-name":d.name,"aria-label":`Open source ${d.name}${Rg(d)}${Am(d.access)}`,"aria-current":h||void 0,onClick:()=>{n(),i(d.name)},sx:{display:"flex",width:"100%",alignItems:"flex-start",justifyContent:"flex-start",textAlign:"left",gap:1.25,px:2,py:1,bgcolor:h?nt.background.muted:void 0,"&:hover":{bgcolor:h?nt.background.strong:nt.background.muted},...Tr},children:[t.jsx(p.Box,{component:"span","aria-hidden":!0,sx:{color:Fn.steel.main,display:"inline-flex",pt:"2px"},children:t.jsx(ql,{size:16})}),t.jsxs(p.Box,{component:"span",sx:{minWidth:0,flex:1},children:[t.jsxs(p.Box,{component:"span",sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:1},children:[t.jsx(p.Box,{component:"span",sx:{fontFamily:Dt,fontSize:wt.body,fontWeight:500,color:"text.primary"},children:d.name}),d.mostViews&&t.jsx($t,{tone:"quiet",sx:{alignSelf:"center"},children:_g}),El(d.access)&&t.jsx(Il,{access:d.access}),d.status]}),(d.description||d.descriptionPending)&&t.jsxs(p.Box,{component:"span",sx:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",mt:.25,fontSize:wt.small,color:"text.secondary",minHeight:d.description?void 0:"1.4em"},children:[d.description?.generated&&t.jsx($t,{tone:"quiet","data-testid":"model-sources-summary-generated",sx:{mr:.75,verticalAlign:"baseline"},children:"Generated"}),d.description&&Dl(d.description.text)]}),t.jsx(Cr,{"data-testid":"model-sources-row-meta",sx:{display:"block",mt:.25},children:d.meta})]})]},`source:${d.name}`)})})]})}const _g="Most views";function Ng({sources:e,currentName:n,countLabel:r,onPickSource:o,curated:i=!1,exportOrdered:l=!1,onWarm:a}){const[u,d]=j.useState(null);return t.jsxs(t.Fragment,{children:[t.jsx(Xp,{size:"small",variant:"outlined",onClick:h=>{a?.(),d(h.currentTarget)},endIcon:t.jsx(bp,{size:20}),"aria-label":`${r}. Showing ${n}, one of the ${r} in this model`,"aria-haspopup":"dialog","aria-expanded":!!u,onPointerEnter:a,onFocus:a,sx:{ml:1,transition:"none"},children:r}),t.jsx(Lg,{anchorEl:u,onClose:()=>d(null),sources:e,currentName:n,onPickSource:o,curated:i,exportOrdered:l})]})}const Pg=[],zg=[],Wg=[],qg=new Map;function Bg(e){const n=e.modelDef;if(typeof n!="string")return!1;try{const r=JSON.parse(n);return Array.isArray(r.imports)&&r.imports.length>0}catch{return!1}}function Vg(e,n){if(typeof e=="string")try{const o=ua(JSON.parse(e).annotations);if(o)return o}catch{}if(!n)return;const r=n.split(`
|
|
35
|
-
`).filter(o=>/^##(\(doc\)|")/.test(o.trim())).map(o=>({value:o}));return ua(r)}async function
|
|
36
|
-
`);jo(M,"typescript",O).then(E=>{a(E)})}},[n,O]),t.jsxs(p.Box,{children:[l&&t.jsx(p.Box,{sx:{marginBottom:"16px"},children:t.jsx(p.Typography,{fontSize:"12px",sx:{fontSize:"12px","& .line":{textWrap:"wrap"}},children:t.jsx("div",{className:"content",dangerouslySetInnerHTML:{__html:l}})})}),t.jsxs(p.Box,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"},children:[t.jsx(p.Typography,{variant:"body2",sx:{fontSize:"15px",fontWeight:600,color:"text.primary",px:2,py:1,bgcolor:"action.hover",borderRadius:1.5,border:1,borderColor:"divider"},children:e}),t.jsx(c.FloatingIconButton,{"aria-label":"Expand results",onClick:()=>d(!0),children:t.jsx(c.SearchIcon,{})})]}),t.jsxs(q.CleanMetricCard,{sx:{position:"relative"},children:[o&&!h&&t.jsxs(p.Box,{sx:{padding:"40px 20px",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:"Click Run to execute the query"}),t.jsx(p.Button,{variant:"contained",startIcon:t.jsx(Zg,{}),onClick:()=>y(!0),children:"Run Query"})]}),C&&t.jsx(c.ResultPanel,{state:S,context:e,maxHeight:c.MODEL_CELL_MAX_HEIGHT,maxResultSize:i})]}),t.jsx(rc,{open:u,onClose:()=>d(!1),result:T?.data?.result||"",renderLogs:T?.data?.renderLogs,title:`Query: ${e}`})]})}function Jg(e){return e!=null}function ey(e,n){const r=[],o=[];for(const l of e){if(l.name===void 0||Jg(n.get(l.name)))continue;if(l.default==null){r.push(l.name);continue}const a=c.renderGivenDefault(l.type??"string",l.default);a&&o.push(`${l.name} = ${a}`)}const i={missing:r};return o.length>0&&(i.defaultsNote=o.length===1?`Ran with the default ${o[0]}`:`Ran with defaults ${o.join(", ")}`),i}function ty(e){return e.length===1?`This source may need a value for the given ${e[0]}. Set it in the parameters above.`:`This source may need values for the givens ${e.join(", ")}. Set them in the parameters above.`}function sc({sourceAndPaths:e,selectedSourceIndex:n,existingQuery:r,onQueryChange:o,onSourceChange:i,resourceUri:l,givens:a,gate:u}){return j.useEffect(()=>{i&&i(n)},[n,i]),t.jsx(q.StyledCardMedia,{children:t.jsxs(wr.Stack,{spacing:2,component:"section",children:[t.jsx(ry,{sourceAndPath:e[n],existingQuery:r,onChange:d=>{o&&o(d)},resourceUri:l,givens:a,gate:u}),t.jsx(wr.Box,{height:"5px"})]})})}function Ns(){return{query:void 0,malloyQuery:void 0,malloyResult:void 0}}function ny({sourceAndPath:e,onChange:n,existingQuery:r,explorerComponents:o,QueryBuilder:i,resourceUri:l,givens:a,gate:u}){const[d,h]=j.useState(r||Ns()),[y,b]=j.useState(void 0);j.useEffect(()=>{r&&h(r)},[r]);const[x,v]=j.useState([]),{MalloyExplorerProvider:k,QueryPanel:C,ResizableCollapsiblePanel:S,ResultPanel:T,SourcePanel:O}=o;j.useEffect(()=>{n&&n(d)},[n,d]);const{environmentName:M,packageName:E,versionId:R}=c.parseResourceUri(l),{apiClients:P}=q.useServer(),F=j.useRef(void 0),B=c.useMutationWithApiError({mutationFn:()=>{F.current=u,b({executionState:"running",query:d?.malloyQuery,queryResolutionStartMillis:Date.now(),onCancel:()=>{B.reset(),b(void 0)},response:{}});const $=typeof d?.malloyQuery=="string"?d.malloyQuery:new i.ASTQuery({source:e.sourceInfo,query:d?.malloyQuery}).toMalloy();return h({...d,query:$}),P.models.executeQueryModel(M,E,e.modelPath,{query:$,sourceName:void 0,queryName:void 0,versionId:R,...a&&Object.keys(a).length>0?{givens:a}:{}})},onSuccess:$=>{if($){const W=JSON.parse($.data.result);h({...d,malloyResult:W});const Z=F.current;b(ne=>ne?{...ne,executionState:"finished",response:{result:W,...Z?.defaultsNote?{messages:[{severity:"INFO",title:Z.defaultsNote}]}:{}}}:void 0)}},onError:$=>{console.error("Query execution error:",$);const W=$?.data?.message??$?.message??"The query could not be run.",Z=[{severity:"ERROR",title:W}],ne=F.current?.missing??[];($?.status===403||/Access denied for source/i.test(W))&&ne.length>0&&Z.push({severity:"WARN",title:ty(ne)}),b(H=>H?{...H,executionState:"finished",response:{messages:Z}}:void 0)}}),[D,_]=j.useState(e.sourceInfo.name);j.useEffect(()=>{D!==e.sourceInfo.name&&(_(e.sourceInfo.name),h(Ns()),b(void 0))},[e,D]);const V=j.useCallback($=>{h({...d,malloyQuery:$,malloyResult:void 0})},[d]);return D!==e.sourceInfo.name?t.jsx("div",{children:"Loading..."}):t.jsx(q.StyledExplorerContent,{sx:{border:"1px solid #e0e0e0",borderRadius:"8px",overflow:"hidden"},children:t.jsx(k,{source:e.sourceInfo,query:d?.malloyQuery,topValues:[],onFocusedNestViewPathChange:v,focusedNestViewPath:x,onQueryChange:V,children:t.jsxs("div",{style:{display:"flex",height:"100%",overflowY:"auto"},children:[t.jsx(S,{isInitiallyExpanded:!0,initialWidth:180,minWidth:180,icon:"database",title:e.sourceInfo.name,children:t.jsx(O,{onRefresh:()=>h(Ns())})}),t.jsx(S,{isInitiallyExpanded:!0,initialWidth:280,minWidth:280,icon:"filterSliders",title:"Query",children:t.jsx(C,{runQuery:()=>{console.log(`running query with: ${d?.malloyQuery}`);try{B.mutate()}catch($){console.error("Error running query:",$)}}})}),t.jsx(T,{source:e.sourceInfo,draftQuery:d?.malloyQuery,setDraftQuery:$=>h({...d,malloyQuery:$}),submittedQuery:y,options:{showRawQuery:!0}})]})})},e.sourceInfo.name)}function ry(e){const[n,r]=j.useState(null),[o,i]=j.useState(null),[l,a]=j.useState(!0);return j.useEffect(()=>{let u=!0;return Promise.all([import("@malloydata/malloy-explorer"),c.loadQueryBuilder()]).then(([d,h])=>{u&&(r(d),i(h),a(!1))}).catch(d=>{console.error("Failed to load Malloy components:",d),u&&a(!1)}),()=>{u=!1}},[]),l||!n||!o?t.jsx(q.StyledExplorerPage,{children:t.jsx(q.StyledExplorerContent,{children:t.jsx(wr.Box,{sx:{alignItems:"center",justifyContent:"center",height:"200px",color:"text.secondary"},children:"Loading explorer..."})})}):t.jsx(ny,{...e,explorerComponents:n,QueryBuilder:o,resourceUri:e.resourceUri})}function Mo(e,n=!0){const{modelPath:r,environmentName:o,packageName:i,versionId:l}=c.parseResourceUri(e),{apiClients:a}=q.useServer();return c.useQueryWithApiError({queryKey:["package",o,i,r,l],queryFn:async()=>(await a.models.getModel(o,i,r,l)).data,enabled:n})}function Eo({data:e,onChange:n,existingQuery:r,initialSelectedSourceIndex:o=0,onSourceChange:i,resourceUri:l,givens:a,onGivensChange:u,startingGivens:d}){const[h,y]=j.useState(o);j.useEffect(()=>{y(o)},[o]);const{data:b,isError:x,isLoading:v,error:k}=Mo(l,!e),{environmentName:C,packageName:S,modelPath:T,versionId:O}=c.parseResourceUri(l),M=e||b,E=j.useMemo(()=>M?.givens??[],[M]),R=c.useDocumentControls({specs:E,loaded:!!M,params:a,onGivensChange:u,startingValues:d,documentKey:l,autorun:!0,environmentName:C??"",packageName:S??"",modelPath:T,versionId:O,documentName:T}),P=j.useMemo(()=>c.givensToRequest(R.applied,R.declaredTypes),[R.applied,R.declaredTypes]),F=j.useMemo(()=>ey(E,R.applied),[E,R.applied]);if(v&&!e)return t.jsx(c.Loading,{text:"Fetching Model..."});if(x&&!e)return console.log("error",k),t.jsx(c.ApiErrorDisplay,{error:k,context:`ModelExplorer > ${T}`});if(!M)return t.jsx(c.Loading,{text:c.LOADING_COPY.loading});const B=(M?.sourceInfos||[]).map((_,V)=>{try{return JSON.parse(_)?.name||`Source ${V+1}`}catch{return`Source ${V+1}`}}),D=B[h]||"";return t.jsxs(q.StyledCard,{variant:"outlined",children:[t.jsx(q.StyledCardContent,{children:t.jsx(p.Stack,{sx:{flexDirection:"row"},children:t.jsx(Ks,{size:"small",id:"size-small-standard",disablePortal:!0,options:B,value:D,onChange:(_,V)=>{if(!V)return;const $=B.indexOf(V);$>=0&&(y($),i?.($))},renderInput:_=>t.jsx(c.TextField,{..._}),style:{width:350,marginTop:"3px",marginLeft:"6px",marginBottom:"8px"}})})}),t.jsx(c.GivensPanel,{...R.panel}),t.jsx(q.StyledCardMedia,{children:t.jsxs(p.Stack,{spacing:2,component:"section",children:[Array.isArray(M.sourceInfos)&&M.sourceInfos.length>0&&t.jsx(sc,{sourceAndPaths:M.sourceInfos.map(_=>({sourceInfo:JSON.parse(_),modelPath:T})),selectedSourceIndex:h,existingQuery:r,onQueryChange:n,resourceUri:l,givens:P,gate:F}),t.jsx(p.Box,{height:"5px"})]})})]})}function Io({open:e,onClose:n,resourceUri:r,data:o,title:i="Data Sources",hasValidImport:l=!0,existingQuery:a,initialSelectedSourceIndex:u,onChange:d,onSourceChange:h,givens:y,onGivensChange:b,startingGivens:x}){return t.jsxs(p.Dialog,{open:e,onClose:n,fullScreen:!0,children:[t.jsxs(p.DialogTitle,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i,t.jsx(p.IconButton,{onClick:n,sx:{color:"text.secondary"},children:t.jsx(c.CloseIcon,{})})]}),t.jsx(p.DialogContent,{children:l?t.jsx(Eo,{resourceUri:r,data:o,existingQuery:a,initialSelectedSourceIndex:u,onChange:d,onSourceChange:h,givens:y,onGivensChange:b,startingGivens:x}):t.jsx("div",{children:"No valid import statement found in cell"})})]})}function sy({onChange:e,resourceUri:n,runOnDemand:r=!1,maxResultSize:o=0,givens:i,onGivensChange:l}){const{modelPath:a}=c.parseResourceUri(n),{data:u,isError:d,isLoading:h,error:y}=Mo(n),[b,x]=j.useState(!1),[v,k]=j.useState(),[C,S]=j.useState(0),[T,O]=j.useState(""),[M,E]=j.useState({}),R=i??M,P=l??($=>E($)),F=u?.modelDef,B=j.useMemo(()=>{if(!F)return!1;try{const $=JSON.parse(F);return Array.isArray($.imports)&&$.imports.length>0}catch{return!1}},[F]);if(h)return t.jsx(c.Loading,{text:"Fetching Model..."});if(d)return console.log("error",y),t.jsx(c.ApiErrorDisplay,{error:y,context:`Model > ${a}`});const D=$=>{k($),e&&e($)},_=$=>{S($)},V=()=>{const $=window.location.href;navigator.clipboard.writeText($).then(()=>O("URL copied to clipboard!")).catch(()=>O("Failed to copy URL"))};return t.jsxs(t.Fragment,{children:[t.jsxs(p.Box,{sx:{position:"relative",maxWidth:"1200px",margin:"0 auto",paddingTop:"24px"},children:[Array.isArray(u?.sourceInfos)&&u.sourceInfos.length>0&&t.jsxs(p.Stack,{spacing:2,component:"section",children:[t.jsxs(p.Box,{sx:{padding:"0 0 16px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsx(p.Typography,{variant:"h1",sx:{fontSize:"28px",fontWeight:"600",color:"#1a1a1a",marginBottom:"8px",marginTop:"0",paddingLeft:"0"},children:"Sources"}),t.jsx(p.Tooltip,{title:"Copy link",children:t.jsx(p.IconButton,{size:"small","aria-label":"Copy link",onClick:V,sx:{color:"text.secondary"},children:t.jsx(ho,{fontSize:"small"})})})]}),t.jsx(Eo,{data:u,onChange:D,onSourceChange:_,existingQuery:v,initialSelectedSourceIndex:C,resourceUri:n,givens:R,onGivensChange:P}),t.jsx(c.FloatingIconButton,{"aria-label":"Expand results",sx:{position:"absolute",top:"90px",right:"4px",zIndex:2},onClick:()=>x(!0),children:t.jsx(c.SearchIcon,{})})]}),u?.queries?.length>0&&t.jsxs(p.Stack,{spacing:2,component:"section",sx:{marginTop:"24px"},children:[t.jsx(p.Box,{sx:{padding:"0 0 16px 0"},children:t.jsx(p.Typography,{variant:"h2",sx:{fontSize:"24px",fontWeight:"600",color:"#1a1a1a",marginBottom:"0",marginTop:"8px",paddingLeft:"0"},children:"Named Queries"})}),u.queries.map($=>t.jsx(Xg,{queryName:$.name,annotations:$.annotations,resourceUri:n,runOnDemand:r,maxResultSize:o},$.name))]}),(!Array.isArray(u?.sourceInfos)||u.sourceInfos.length===0)&&!(u?.queries&&u.queries.length>0)&&t.jsxs(p.Box,{sx:{textAlign:"center",py:6},children:[t.jsx(p.Typography,{variant:"body1",sx:{color:"text.secondary",marginBottom:"8px"},children:"This model exposes no sources or queries."}),B&&t.jsxs(p.Typography,{variant:"body2",color:"text.secondary",children:["It imports other files but re-exports nothing. Add"," ",t.jsxs("code",{children:["export ","{ source_name }"]})," to surface imported sources here."]})]}),t.jsx(Io,{open:b,onClose:()=>x(!1),resourceUri:n,data:u,title:`Model: ${a.split("/").pop()}`,existingQuery:v,initialSelectedSourceIndex:C,onChange:D,onSourceChange:_,givens:R,onGivensChange:P})]}),t.jsx(p.Snackbar,{open:T!=="",autoHideDuration:6e3,onClose:()=>O(""),message:T})]})}function oy(){const[e,n]=j.useState(""),r=()=>{navigator.clipboard.writeText(window.location.href).then(()=>n("URL copied to clipboard!")).catch(()=>n("Failed to copy URL"))};return t.jsxs(t.Fragment,{children:[t.jsx(p.Tooltip,{title:"Copy link",children:t.jsx(p.IconButton,{size:"small","aria-label":"Copy link",onClick:r,sx:{color:"text.secondary"},children:t.jsx(ho,{fontSize:"small"})})}),t.jsx(p.Snackbar,{open:e!=="",autoHideDuration:6e3,onClose:()=>n(""),message:e})]})}function iy(e){const{modelPage:n,isLoadingStatus:r}=q.useServer();if(r)return t.jsx(c.Loading,{text:"Fetching Model..."});if(n!=="viewer")return t.jsx(sy,{...e});const{onChange:o,runOnDemand:i,headerActions:l,...a}=e;return t.jsx(nc,{...a,headerActions:l??t.jsx(oy,{})})}const ay={"persist-source-refused":"persist-not-built","preaggregate-not-built":"rollup-not-built","preaggregate-join-one-key-repeated":"rollup-join-one-key-repeated","stored-native-schema-missing":"database-native-type-missing"};function ly(e){const n=(o,i)=>`${o}\0${i.subject??""}\0${i.message??""}`,r=new Set(e.map(o=>n(o.code,o)));return e.filter(o=>{const i=o.code!==void 0?ay[o.code]:void 0;return i===void 0||!r.has(n(i,o))})}function cy({warnings:e}){const[n,r]=j.useState(!1),o=ly(e??[]),i=o.filter(a=>a.severity==="error"),l=o.filter(a=>a.severity!=="error");return i.length===0&&l.length===0?null:t.jsxs(p.Stack,{sx:{gap:1,mb:4},children:[i.length>0&&t.jsxs(p.Alert,{severity:"warning",children:[t.jsx(p.AlertTitle,{children:i.length===1?"1 problem in this package":`${i.length} problems in this package`}),t.jsx(Ma,{findings:i})]}),l.length>0&&t.jsxs(p.Box,{children:[t.jsxs(p.Button,{size:"small","aria-expanded":n,onClick:()=>r(a=>!a),sx:{px:.5,color:"text.secondary"},children:[n?"Hide":"Show"," ",l.length," ",l.length===1?"note":"notes"]}),n&&t.jsx(p.Box,{sx:{pl:.5,pt:.5},children:t.jsx(Ma,{findings:l})})]})]})}function Ma({findings:e}){return t.jsx(p.Stack,{component:"ul",sx:{m:0,p:0,listStyle:"none",gap:.75},children:e.map((n,r)=>t.jsxs(p.Typography,{component:"li",variant:"body2",children:[n.model&&t.jsx(p.Box,{component:"span",sx:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"0.85em",mr:1},children:n.model}),n.message]},`${n.model??""}:${n.code??""}:${r}`))})}function oc(e){return j.useMemo(()=>{if(!e?.sources?.length)return[];const n=new Map;for(const r of e.sources)if(r.givens?.length)for(const o of r.givens)o.name&&!n.has(o.name)&&n.set(o.name,o);return Array.from(n.values())},[e])}function uy(e){return e.type==="code"}function dy(e){return(e.text??"").split(`
|
|
32
|
+
`).trimEnd(),a=mg.exec(l);if(!(!a||a[1]!==Mo(n.name)))return{kind:r,code:[...vg(e,n.range.start),...i,l].join(`
|
|
33
|
+
`)}}function vg(e,n){const r=(e[n.line]??"").slice(0,n.character),o=r.trim()==="";if(!o&&!Ta.test(r))return[];const i=a=>{const u=[];let d=a;for(;d>=0&&e[d].trim().startsWith("#");)u.unshift(e[d--].trim());return{out:u,next:d}},l=i(n.line-1);return o&&l.next>=0&&Ta.test(e[l.next])?[...i(l.next-1).out,...l.out]:l.out}const bg=/(?<![\w:])([A-Za-z_]\w*)\s*:(?!:)/g;function wg(e){let n;for(const r of Sg(e).matchAll(bg))n=r[1];return n}function Sg(e){let n="";for(let r=0;r<e.length;r++){const o=e[r];if(e.startsWith('"""',r)){const i=e.indexOf('"""',r+3),l=i===-1?e.length:i+3;n+=" ".repeat(l-r),r=l-1}else if(o==='"'||o==="'"||o==="`"){const i=kg(e,r);n+=" ".repeat(i-r+1),r=i}else if(o==="#"||o==="/"&&e[r+1]==="/"||o==="-"&&e[r+1]==="-"){const i=e.indexOf(`
|
|
34
|
+
`,r),l=i===-1?e.length:i;n+=" ".repeat(l-r),r=l-1}else n+=o}return n}function kg(e,n){const r=e[n];for(let o=n+1;o<e.length;o++)if(e[o]==="\\")o++;else if(e[o]===r)return o;return e.length}function Cg(e){return/^`?[A-Za-z_]\w*`?\s+is\s+`?([A-Za-z_]\w*)`?\s*(?:extend\b|$)/.exec(e)?.[1]}function Mo(e){return e.replace(/^`(.*)`$/,"$1")}const Tg=["fields","code"],ja={display:"inline-flex",alignItems:"center",color:"text.secondary",borderRadius:1,padding:"2px",flexShrink:0,"&:hover":{color:ts}};function jg({join:e,run:n,modelPath:r,sourceName:o,link:i,entitiesByName:l,entitiesLoading:a,entitiesError:u,code:d,target:h,showRules:y=!1}){const[b,x]=vo(),{layers:v,layer:k,setLayer:C}=Jl(Tg),S=T.useMemo(()=>l?nc({entities:l,loading:!!a,error:!!u}):void 0,[l,a,u]),j=e.dimensions.length+e.measures.length,M=t.jsxs(m.Box,{sx:{display:"inline-flex",alignItems:"center",gap:1},children:[b&&t.jsx(ec,{"aria-label":`Show for ${e.name}`,layers:v,value:k,onChange:C,disabledReasons:{code:d?void 0:"No Malloy code to show for this join"}}),i?.kind==="link"&&i.href&&t.jsx(m.Link,{href:i.href,"aria-label":`Open ${e.name}`,title:`Open ${e.name}`,sx:ja,children:t.jsx(wa,{size:14})}),i?.kind==="link"&&!i.href&&i.onOpen&&t.jsx(m.Link,{component:"button",type:"button",onClick:i.onOpen,"aria-label":`Open ${e.name}`,title:`Open ${e.name}`,sx:ja,children:t.jsx(wa,{size:14})}),i?.kind==="join-only"&&t.jsx(m.Box,{component:"span",sx:{fontSize:wt.micro,fontStyle:"italic",color:"text.secondary",flexShrink:0},children:"only accessible via join"})]});return t.jsxs(m.Box,{"data-testid":"model-viewer-join-row","data-name":e.name,sx:b?{pb:1.25}:void 0,children:[t.jsx(jo,{glyph:t.jsx(So,{kind:"join"}),name:e.name,typeLabel:`${j} ${j===1?"field":"fields"}`,stackPills:!0,descriptors:t.jsxs(At,{tone:"quiet",voice:"token",sx:{alignSelf:"center",flexShrink:0},children:["join_",e.relationship]}),doc:e.doc,open:b,expandable:!0,onToggle:()=>x(O=>!O),trailing:M,pills:h&&t.jsx(Rl,{access:h.access})}),t.jsx(m.Collapse,{in:b,timeout:"auto",unmountOnExit:!0,children:t.jsx(m.Box,{sx:{mx:"10px",mt:"2px"},children:k==="code"&&d?t.jsx(Or,{testId:"model-viewer-join-code",code:d}):t.jsxs(m.Box,{"data-testid":"model-viewer-join-fields",sx:{...Pn,bgcolor:"transparent",p:1.5,pb:0},children:[h&&y&&t.jsx(Cr,{component:"div","data-testid":"model-viewer-join-gate-warning",sx:{mb:1},children:Np(h.sourceName,h.access)}),t.jsx(br,{label:"Measures",noun:["measure","measures"],level:"h3",items:e.measures,run:n,modelPath:r,sourceName:o,getFieldCode:S}),t.jsx(br,{label:"Dimensions",noun:["dimension","dimensions"],level:"h3",items:e.dimensions,run:n,modelPath:r,sourceName:o,getFieldCode:S})]})})})]})}function Mg({source:e,modelPath:n,entitiesByName:r,entitiesLoading:o,entitiesError:i,modelText:l,joinLinks:a,joinEntities:u,joinCodes:d,joinAccess:h,showRules:y=!1,columnDescriptions:b,run:x,queries:v,givens:k}){const C={run:x,modelPath:n,sourceName:e.name},{showField:S}=ls(),j=T.useMemo(()=>S?e.views.filter(D=>S({modelPath:n,sourceName:e.name,field:D,joined:!1})):e.views,[S,e,n]),M=ns({noun:["view","views"]}),O=ns({noun:["join","joins"]}),E=T.useMemo(()=>!o&&[...e.views,...e.measures,...e.calculations,...e.dimensions].some(D=>!r?.get(D.name)),[o,r,e]),{parsed:$,pending:P}=Gl(l,E),A=T.useMemo(()=>pg($,e.name),[$,e.name]),B=T.useMemo(()=>nc({entities:r,loading:!!o,error:!!i,columnDescriptions:b,declarations:A,declarationsLoading:P}),[r,o,i,b,A,P]);return t.jsxs(m.Box,{sx:{paddingBottom:"24px"},children:[k,t.jsx(_n,{label:"Views",count:j.length,action:M.action,children:t.jsx(Mr.Provider,{value:M.command,children:j.map(D=>t.jsx(tc,{field:D,modelPath:n,sourceName:e.name,fieldCode:B(D),run:x},D.name))})}),v,t.jsx(br,{label:"Measures",noun:["measure","measures"],items:e.measures,getFieldCode:B,...C}),t.jsx(br,{label:"Calculations",noun:["calculation","calculations"],items:e.calculations,getFieldCode:B,...C}),t.jsx(br,{label:"Dimensions",noun:["dimension","dimensions"],items:e.dimensions,getFieldCode:B,...C}),t.jsx(_n,{label:"Joins",count:e.joins.length,action:O.action,children:t.jsx(Mr.Provider,{value:O.command,children:e.joins.map(D=>t.jsx(jg,{join:D,run:x,modelPath:n,sourceName:e.name,link:a?.get(D.name),entitiesByName:u?.get(D.name),code:d?.get(D.name),target:h?.get(D.name),showRules:y,entitiesLoading:o,entitiesError:i},D.name))})})]})}function no(e){return{name:e.name,kind:e.kind,dataType:po(e.type),typeTip:ip(e.type),tags:ap(e.annotations),doc:Ln(e.annotations),indexed:e.kind==="dimension"?Sp(e):void 0,preaggregate:e.kind==="measure"?op(e.annotations):void 0}}function Og(e){const n=[],r=[];for(const o of e.schema?.fields??[]){if(o.kind!=="dimension"&&o.kind!=="measure")continue;const i={...no(o),indexed:!1,preaggregate:!1};o.kind==="dimension"?n.push(i):r.push(i)}return{name:e.name,relationship:e.relationship,doc:Ln(e.annotations),dimensions:n,measures:r}}function Eg(e,n){const r={name:e.name,doc:Ln(e.annotations),docParts:bl(e.annotations),accent:Kp(n),persist:sp(e.annotations),dimensions:[],measures:[],calculations:[],views:[],joins:[]};for(const o of e.schema?.fields??[])switch(o.kind){case"dimension":case"measure":r[o.kind==="dimension"?"dimensions":"measures"].push(no(o));break;case"calculate":r.calculations.push(no(o));break;case"view":r.views.push({name:o.name,kind:"view",doc:Ln(o.annotations),tags:fo(o.annotations)});break;case"join":r.joins.push(Og(o));break}return r}function Ig(e){const n=[];for(const r of e??[]){if(!r.name)continue;const o=(r.annotations??[]).map(i=>({value:i}));n.push({name:r.name,sourceName:r.sourceName||void 0,doc:Ln(o),tags:fo(o)})}return n}function rc(e){return e.dimensions.length+e.measures.length+e.calculations.length+e.views.length}function Dg(e,n){if(e.length===0)return null;const r=h=>h.toLowerCase().replace(/[-_]/g,""),o=n?r((n.split("/").pop()??n).replace(/\.malloy$/,"")):void 0,i=new Map(e.map(h=>[h.name,new Set(h.views.map(y=>y.name))])),l=h=>e.some(y=>{if(y.name===h.name||y.views.length===0)return!1;const b=i.get(h.name);return y.views.length<h.views.length&&[...i.get(y.name)].every(x=>b.has(x))}),a=e.filter(h=>!l(h)),u=a.length>0?a:e;let d=u[0];for(const h of u.slice(1)){if(h.views.length!==d.views.length){h.views.length>d.views.length&&(d=h);continue}o&&r(h.name)===o&&r(d.name)!==o&&(d=h)}return d}function Ag(e,n,r){if(!e||!n)return;const i=new RegExp("source:\\s*`?"+mn(n)+"`?\\s+is\\s+`?([A-Za-z_]\\w*)`?\\s*(?:->|extend\\b)").exec(e);if(!i)return;const l=i[1];return r.has(l)?l:void 0}function _s(e,n){return`${e} ${e===1?n:`${n}s`}`}function Rg(e){const n=rc(e),r=[_s(e.views.length,"view"),_s(n,"field")];return e.joins.length>0&&r.push(_s(e.joins.length,"join")),r.join(" · ")}function $g(e,n,r){if(r){const u=r.exportOrder,d=u.length>0&&e.some(h=>u.includes(h.name));return{sources:_g(e,h=>h.name,u),curated:!0,exportOrdered:d}}const o=e.map((u,d)=>({source:u,index:d})).filter(({source:u})=>u.name!==n?.name).sort((u,d)=>d.source.views.length-u.source.views.length||u.index-d.index).map(({source:u})=>u),i=n?[n,...o]:o,l=n?.views.length??0,a=n&&l>0&&e.every(u=>u.views.length<=l)?n.name:void 0;return{sources:i,curated:!1,exportOrdered:!1,mostViews:a}}function Fg(e){return/^`.*`$/.test(e)?e.slice(1,-1):e}function Lg(e){if(!e)return[];const n=Ir(e),r=[];for(const o of n.matchAll(/(?:^|[\s;])export\s*\{([^}]*)\}/gi))for(const i of o[1].split(",")){const l=Fg(i.trim());l&&!r.includes(l)&&r.push(l)}return r}function _g(e,n,r){if(r.length===0)return[...e];const o=i=>{const l=r.indexOf(n(i));return l===-1?r.length:l};return e.map((i,l)=>({item:i,index:l})).sort((i,l)=>o(i.item)-o(l.item)||i.index-l.index).map(({item:i})=>i)}function Ng(e,n){const r=e?.trim();if(r)return{text:r,generated:!1};const o=n?.trim();return o?{text:o,generated:!0}:void 0}const Pg="This package's curated sources, in the order its index.malloy exports them.",zg="This package's public sources.";function Wg(e){return e.mostViews?", most views":""}function qg({anchorEl:e,onClose:n,sources:r,currentName:o,onPickSource:i,curated:l=!1,exportOrdered:a=!1}){const u=!!e;return t.jsxs(m.Popover,{open:u,anchorEl:e,onClose:n,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},slotProps:{paper:{sx:{width:460,maxWidth:"calc(100vw - 32px)",maxHeight:"min(70vh, 560px)",display:"flex",flexDirection:"column",borderRadius:"10px"},"data-testid":"model-sources-dropdown"}},children:[t.jsxs(m.Box,{sx:{px:2,pt:1.5,pb:1,borderBottom:1,borderColor:"divider"},children:[t.jsx(m.Typography,{variant:"subtitle2",component:"h2",sx:{m:0},children:"Sources"}),t.jsx(Cr,{component:"p",sx:{m:0},children:l?a?Pg:zg:Jp})]}),t.jsx(m.Box,{sx:{overflowY:"auto",py:.5},children:r.length===0?t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{py:4,textAlign:"center"},children:"This model defines no sources."}):r.map(d=>{const h=d.name===o;return t.jsxs(m.ButtonBase,{"data-item-name":d.name,"aria-label":`Open source ${d.name}${Wg(d)}${zp(d.access)}`,"aria-current":h||void 0,onClick:()=>{n(),i(d.name)},sx:{display:"flex",width:"100%",alignItems:"flex-start",justifyContent:"flex-start",textAlign:"left",gap:1.25,px:2,py:1,bgcolor:h?nt.background.muted:void 0,"&:hover":{bgcolor:h?nt.background.strong:nt.background.muted},...jr},children:[t.jsx(m.Box,{component:"span","aria-hidden":!0,sx:{color:Rn.steel.main,display:"inline-flex",pt:"2px"},children:t.jsx(Hl,{size:16})}),t.jsxs(m.Box,{component:"span",sx:{minWidth:0,flex:1},children:[t.jsxs(m.Box,{component:"span",sx:{display:"flex",alignItems:"center",flexWrap:"wrap",gap:1},children:[t.jsx(m.Box,{component:"span",sx:{fontFamily:Dt,fontSize:wt.body,fontWeight:500,color:"text.primary"},children:d.name}),d.mostViews&&t.jsx(At,{tone:"quiet",sx:{alignSelf:"center"},children:Bg}),Al(d.access)&&t.jsx(Rl,{access:d.access}),d.status]}),(d.description||d.descriptionPending)&&t.jsxs(m.Box,{component:"span",sx:{display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:2,overflow:"hidden",mt:.25,fontSize:wt.small,color:"text.secondary",minHeight:d.description?void 0:"1.4em"},children:[d.description?.generated&&t.jsx(At,{tone:"quiet","data-testid":"model-sources-summary-generated",sx:{mr:.75,verticalAlign:"baseline"},children:"Generated"}),d.description&&$l(d.description.text)]}),t.jsx(Cr,{"data-testid":"model-sources-row-meta",sx:{display:"block",mt:.25},children:d.meta})]})]},`source:${d.name}`)})})]})}const Bg="Most views";function Vg({sources:e,currentName:n,countLabel:r,onPickSource:o,curated:i=!1,exportOrdered:l=!1,onWarm:a}){const[u,d]=T.useState(null);return t.jsxs(t.Fragment,{children:[t.jsx(sg,{size:"small",variant:"outlined",onClick:h=>{a?.(),d(h.currentTarget)},endIcon:t.jsx(jm,{size:20}),"aria-label":`${r}. Showing ${n}, one of the ${r} in this model`,"aria-haspopup":"dialog","aria-expanded":!!u,onPointerEnter:a,onFocus:a,sx:{ml:1,transition:"none"},children:r}),t.jsx(qg,{anchorEl:u,onClose:()=>d(null),sources:e,currentName:n,onPickSource:o,curated:i,exportOrdered:l})]})}const Hg=[],Ug=[],Gg=[],Yg=new Map;function Kg(e){const n=e.modelDef;if(typeof n!="string")return!1;try{const r=JSON.parse(n);return Array.isArray(r.imports)&&r.imports.length>0}catch{return!1}}function Qg(e,n){if(typeof e=="string")try{const o=ua(JSON.parse(e).annotations);if(o)return o}catch{}if(!n)return;const r=n.split(`
|
|
35
|
+
`).filter(o=>/^##(\(doc\)|")/.test(o.trim())).map(o=>({value:o}));return ua(r)}async function Zg(e,n,r,o,i,l){const a=await e.models.getModel(n,r,o,i,l),u=Xg(a.data);return{sourceInfos:(a.data.sourceInfos??[]).map(d=>JSON.parse(d)),queries:a.data.queries??[],sourceText:u,givens:pp(o,a.data),access:$p(a.data),modelDoc:Qg(a.data.modelInfo,u),hasImports:Kg(a.data)}}function Xg(e){const n=e.sourceText;return typeof n=="string"?n:void 0}function sc(e,n,r,o,i=!1){return["model-viewer-sources",e,n,r,o??"",...i?["off-surface"]:[]]}function Jg(e,n,r,o,i,l=!1){return{queryKey:sc(n,r,o,i,l),queryFn:()=>Zg(e,n,r,o,i,l),...i&&i!=="latest"?{staleTime:1/0}:{}}}function ey(e,n,r,o,i=!0,l=!1){const{apiClients:a}=q.useServer(),u=pt.useQuery({...Jg(a,e,n,r,o,l),enabled:i&&!!(e&&n&&r)});return{sources:u.data?.sourceInfos??Hg,queries:u.data?.queries??Ug,sourceText:u.data?.sourceText,givens:u.data?.givens??Gg,access:u.data?.access??Yg,modelDoc:u.data?.modelDoc,hasImports:u.data?.hasImports??!1,isLoading:u.isLoading,isError:u.isError,error:u.error,refetch:u.refetch}}const ty=new Map;function Ma(e){return(e.split("/").pop()??e).replace(/\.malloy$/,"")}function ny(e,n){const r=Tp(e,n),o=n.filter(l=>!r.has(l.name)),i="Nothing on this page reads them.";return o.length===0?`Declared here for the models that import this file. ${i}`:o.length===n.length?`Imported from another file, for the models that import this one. ${i}`:`For the models that import this file. ${vr(o.map(l=>l.name),"and")} ${o.length===1?"comes":"come"} from a file this one imports; the rest are declared here. ${i}`}function oc({resourceUri:e,sourceName:n,onSourceChange:r,initialSourceName:o,includeHiddenFilesAndSources:i=!1,hostGivenNames:l,givens:a,onGivensChange:u,showAccessRules:d=!1,headingLevel:h="h1",headerActions:y,renderSourceStatus:b,entities:x,entitiesLoading:v=!1,entitiesError:k=!1,columnDescriptions:C,joinHref:S,queryMetadata:j,onQueryRun:M,maxResultSize:O,extensions:E}){const{environmentName:$,packageName:P,modelPath:A="",versionId:B}=c.parseResourceUri(e),D=q.usePublisherTheme().theme.ui.font.mono,{sources:_,queries:V,sourceText:R,givens:W,access:Z,modelDoc:ne,hasImports:J,isLoading:H,isError:Q,error:re,refetch:z}=ey($,P,A,B,!0,i),oe=T.useMemo(()=>new Set(l??[]),[l]),se=T.useMemo(()=>W.filter(Ce=>!oe.has(Ce.name)),[W,oe]),ie=T.useMemo(()=>_.map(Eg),[_]),De=T.useMemo(()=>Ig(V),[V]),de=T.useMemo(()=>Cp(ie),[ie]),ue=T.useMemo(()=>kp(_),[_]),be=T.useMemo(()=>mp(se),[se]),Oe=JSON.stringify(a??null),te=T.useMemo(()=>a&&Object.fromEntries(Object.entries(a).filter(([Ce])=>be.has(Ce))),[Oe,be]),K=!H&&!Q,he=T.useCallback(Ce=>u?.(Ce,Array.from(be.keys())),[u,be]),we=c.useGivensState({declaredTypes:be,params:te,onParamsChange:K&&u?he:void 0,documentKey:`${$}/${P}@${B??""}/${A}`,autorun:!0}),ge=T.useMemo(()=>gp(we.applied,be),[we.applied,be]),{givensBySource:me,unknownGivensBySource:ye}=T.useMemo(()=>{const Ce=new Map,Fe=new Map;for(const Ie of ie){const We=Mp(R,Ie.name,se);Ce.set(Ie.name,We.givens),We.unknown.size>0&&Fe.set(Ie.name,We.unknown)}return{givensBySource:Ce,unknownGivensBySource:Fe}},[ie,R,se]),Le=T.useMemo(()=>({projectName:$,packageName:P,versionId:B,givens:se,givensBySource:me,unknownGivensBySource:ye,requiredFiltersBySource:ue,givenValues:ge,accessBySource:Z,includeHiddenFilesAndSources:i,queryMetadata:j,onQueryRun:M,maxResultSize:O}),[$,P,B,se,me,ye,ue,ge,Z,i,j,M,O]),[st,ce]=T.useState(o),Y=n!==void 0,ae=Y?n:st,Re=T.useCallback(Ce=>{Y||ce(Ce),r?.(Ce)},[Y,r]),Ve=T.useMemo(()=>Dg(ie,A),[ie,A]),Ee=ie.find(Ce=>Ce.name===ae)??(Y?void 0:Ve),at=T.useMemo(()=>Ee?me.get(Ee.name)??se:se,[Ee,me,se]),yt=T.useMemo(()=>Ee?Op(R,Ee.name,se,de):new Map,[Ee,R,se,de]),xt=T.useMemo(()=>Ag(R,Ee?.name,de),[R,Ee?.name,de]),Mt=T.useMemo(()=>Ee?np(Ee,ie.find(Ce=>Ce.name===xt)):void 0,[Ee,ie,xt]),mt=T.useMemo(()=>x?jl(x):ty,[x]),Ye=Ee?mt.get(Ee.name):void 0,{joinLinks:fe,joinEntities:Ke,joinCodes:ze,joinAccessRules:lt}=T.useMemo(()=>{const Ce=new Map,Fe=new Map,Ie=new Map,We=new Map,dt=new Map([[A,new Set(de)]]);for(const Pe of Ye?.values()??[]){if(Pe.fieldType!=="join")continue;Pe.code&&Ie.set(Pe.name,Pe.code);const tt=Pe.joinTarget;if(tt)if(tt.modelPath===A){const Ot=mt.get(tt.sourceName);Ot&&Fe.set(Pe.name,Ot);const kt=Qr(Z,tt.sourceName);Al(kt)&&We.set(Pe.name,{sourceName:tt.sourceName,access:kt});const Rt=Yp(tt,dt);Ce.set(Pe.name,Rt.kind==="link"?{...Rt,onOpen:()=>Re(tt.sourceName)}:Rt)}else{const Ot=S?.(tt);Ot&&Ce.set(Pe.name,{kind:"link",href:Ot})}}return{joinLinks:Ce,joinEntities:Fe,joinCodes:Ie,joinAccessRules:We}},[Ye,mt,A,de,Z,Re,S]),ct=A==="index.malloy"&&!i,Qe=T.useMemo(()=>$g(ie,Ve,ct?{exportOrder:Lg(R)}:void 0),[ie,Ve,ct,R]),pe=E?.describePickerSource,He=T.useMemo(()=>Qe.sources.map(Ce=>{const Fe=pe?.({modelPath:A,sourceName:Ce.name});return{name:Ce.name,description:Ng(Ce.doc,Fe?.summary),descriptionPending:!Ce.doc?.trim()&&!Fe?.summary&&!!Fe?.summaryPending,meta:Rg(Ce),mostViews:Qe.mostViews===Ce.name,access:Qr(Z,Ce.name),status:Fe?.status}}),[Qe,Z,pe,A]),vt=(()=>{if(H)return t.jsx(c.Loading,{text:"Fetching Model..."});if(Q)return Gp(re)?t.jsx(m.Box,{sx:{pt:eo},children:t.jsx(xr,{message:Zl(re)??`${P}/${A} doesn't exist, or you don't have access to it.`})}):t.jsx(ds,{message:Xl("Failed to load model",re),onRetry:()=>void z()});const Ce=De.length>0&&t.jsx(fg,{queries:De,sourceText:R,modelPath:A,run:Le});if(ie.length===0)return De.length===0?t.jsxs(t.Fragment,{children:[t.jsx(As,{headingLevel:h,title:Ma(A),meta:se.length>0?`${se.length} ${se.length===1?"given":"givens"}`:void 0,actions:y,isSource:!1,offSurface:i}),t.jsx(xr,{message:"This model defines no sources or queries.",secondary:J&&t.jsxs(t.Fragment,{children:["It imports other files but re-exports nothing. Add"," ",t.jsxs("code",{children:["export ","{ source_name }"]})," to surface imported sources here."]})}),t.jsxs(_n,{label:"Givens",count:se.length,testId:"model-viewer-declared-givens",children:[t.jsx(un,{"data-testid":"model-viewer-declared-givens-where",sx:{mb:1},children:ny(R,se)}),t.jsx(mo,{givens:se})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(As,{headingLevel:h,title:Ma(A),meta:`${De.length} ${De.length===1?"query":"queries"}`,actions:y,isSource:!1,offSurface:i}),Ce]});if(!Ee)return t.jsx(m.Box,{sx:{pt:eo},children:t.jsx(xr,{message:`This model has no source named ${ae}.`,secondary:t.jsxs(m.Box,{component:"span","data-testid":"model-viewer-source-links",children:["Sources in this model: ",ie.map((Pe,tt)=>t.jsxs("span",{children:[tt>0&&", ",t.jsx(m.Link,{component:"button",type:"button",onClick:()=>Re(Pe.name),sx:{fontFamily:Dt,verticalAlign:"baseline"},children:Pe.name})]},Pe.name))]})})});const Fe=rc(Ee),Ie=xt?void 0:[...Ye?.values()??[]].find(Pe=>Pe.table)?.table,We=xt?t.jsxs(t.Fragment,{children:["from ",t.jsx(m.Link,{component:"button",type:"button",onClick:()=>Re(xt),sx:{fontFamily:Dt,color:as,textDecorationColor:"inherit",verticalAlign:"baseline"},children:xt})]}):Ie?t.jsxs(t.Fragment,{children:["reads ",t.jsx(m.Box,{component:"span","data-testid":"model-viewer-source-table",sx:{fontFamily:Dt},children:[Ie.connectionName,Ie.catalogName,Ie.schemaName,Ie.tableName].filter(Boolean).join(".")})]}):void 0,dt=E?.renderSourceDetail?.({modelPath:A,sourceName:Ee.name});return t.jsxs(t.Fragment,{children:[t.jsx(As,{headingLevel:h,title:Ee.name,titleAdornments:ie.length>1&&t.jsx(Vg,{sources:He,currentName:Ee.name,countLabel:em(He.length,Qe.curated),onPickSource:Re,curated:Qe.curated,exportOrdered:Qe.exportOrdered}),actions:y,status:b?.(Ee.name),kindLabel:"Source",meta:`${Fe} ${Fe===1?"field":"fields"}`,doc:Mt,modelDoc:ne,access:Qr(Z,Ee.name),showRules:d,offSurface:i,publicSurface:ct,provenance:We}),dt&&t.jsx(m.Box,{"data-testid":"model-viewer-source-detail",sx:{mt:1.5},children:dt}),t.jsx(xo.Provider,{value:se,children:t.jsx(Mg,{source:Ee,modelPath:A,entitiesByName:Ye,entitiesLoading:v,entitiesError:k,columnDescriptions:C?.get(Ee.name),modelText:R,joinLinks:fe,joinAccess:lt,showRules:d,joinEntities:Ke,joinCodes:ze,run:Le,queries:Ce,givens:t.jsx(Xp,{givens:at,unknown:Ee?ye.get(Ee.name):void 0,inheritedFrom:yt,values:we.draft,onChange:we.setGiven,onReset:we.reset,environmentName:$,packageName:P,modelPath:A,versionId:B,declaredTypes:be})},Ee.name)})]})})();return t.jsx(Tl.Provider,{value:E??{},children:t.jsx(m.Box,{"data-testid":"model-viewer",sx:{...up,pb:2,[Sl]:D},children:t.jsx(m.Box,{sx:dp,children:vt})})})}const ry=c.createSvgIcon(t.jsx("path",{d:"M8 5v14l11-7z"}));function ic({open:e,onClose:n,result:r,title:o="Results",renderLogs:i,drill:l}){return t.jsx(c.AppDialog,{open:e,onClose:n,title:o,maxWidth:!1,showClose:!0,children:t.jsx(m.Box,{sx:{height:"70vh",overflow:"auto"},children:t.jsx(c.ResultContainer,{result:r,maxHeight:c.RESULTS_DIALOG_MAX_HEIGHT,maxResultSize:1e6,renderLogs:i,drill:l})})})}function sy({queryName:e,annotations:n,resourceUri:r,runOnDemand:o=!1,maxResultSize:i=0}){const[l,a]=T.useState(),[u,d]=T.useState(!1),[h,y]=T.useState(!1),{packageName:b,environmentName:x,versionId:v,modelPath:k}=c.parseResourceUri(r),C=!o||h,S=c.useQueryResult({environmentName:x,packageName:b,modelPath:k,versionId:v,queryName:e},{enabled:C}),j=S.data,{mode:M}=q.usePublisherTheme();return T.useEffect(()=>{if(n&&n.length>0){const O=n.map(E=>`// ${E}`).join(`
|
|
36
|
+
`);To(O,"typescript",M).then(E=>{a(E)})}},[n,M]),t.jsxs(m.Box,{children:[l&&t.jsx(m.Box,{sx:{marginBottom:"16px"},children:t.jsx(m.Typography,{fontSize:"12px",sx:{fontSize:"12px","& .line":{textWrap:"wrap"}},children:t.jsx("div",{className:"content",dangerouslySetInnerHTML:{__html:l}})})}),t.jsxs(m.Box,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"8px"},children:[t.jsx(m.Typography,{variant:"body2",sx:{fontSize:"15px",fontWeight:600,color:"text.primary",px:2,py:1,bgcolor:"action.hover",borderRadius:1.5,border:1,borderColor:"divider"},children:e}),t.jsx(c.FloatingIconButton,{"aria-label":"Expand results",onClick:()=>d(!0),children:t.jsx(c.SearchIcon,{})})]}),t.jsxs(q.CleanMetricCard,{sx:{position:"relative"},children:[o&&!h&&t.jsxs(m.Box,{sx:{padding:"40px 20px",textAlign:"center",display:"flex",flexDirection:"column",alignItems:"center",gap:"16px"},children:[t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:"Click Run to execute the query"}),t.jsx(m.Button,{variant:"contained",startIcon:t.jsx(ry,{}),onClick:()=>y(!0),children:"Run Query"})]}),C&&t.jsx(c.ResultPanel,{state:S,context:e,maxHeight:c.MODEL_CELL_MAX_HEIGHT,maxResultSize:i})]}),t.jsx(ic,{open:u,onClose:()=>d(!1),result:j?.data?.result||"",renderLogs:j?.data?.renderLogs,title:`Query: ${e}`})]})}function oy(e){return e!=null}function iy(e,n){const r=[],o=[];for(const l of e){if(l.name===void 0||oy(n.get(l.name)))continue;if(l.default==null){r.push(l.name);continue}const a=c.renderGivenDefault(l.type??"string",l.default);a&&o.push(`${l.name} = ${a}`)}const i={missing:r};return o.length>0&&(i.defaultsNote=o.length===1?`Ran with the default ${o[0]}`:`Ran with defaults ${o.join(", ")}`),i}function ay(e){return e.length===1?`This source may need a value for the given ${e[0]}. Set it in the parameters above.`:`This source may need values for the givens ${e.join(", ")}. Set them in the parameters above.`}function ac({sourceAndPaths:e,selectedSourceIndex:n,existingQuery:r,onQueryChange:o,onSourceChange:i,resourceUri:l,givens:a,gate:u}){return T.useEffect(()=>{i&&i(n)},[n,i]),t.jsx(q.StyledCardMedia,{children:t.jsxs(wr.Stack,{spacing:2,component:"section",children:[t.jsx(cy,{sourceAndPath:e[n],existingQuery:r,onChange:d=>{o&&o(d)},resourceUri:l,givens:a,gate:u}),t.jsx(wr.Box,{height:"5px"})]})})}function Ns(){return{query:void 0,malloyQuery:void 0,malloyResult:void 0}}function ly({sourceAndPath:e,onChange:n,existingQuery:r,explorerComponents:o,QueryBuilder:i,resourceUri:l,givens:a,gate:u}){const[d,h]=T.useState(r||Ns()),[y,b]=T.useState(void 0);T.useEffect(()=>{r&&h(r)},[r]);const[x,v]=T.useState([]),{MalloyExplorerProvider:k,QueryPanel:C,ResizableCollapsiblePanel:S,ResultPanel:j,SourcePanel:M}=o;T.useEffect(()=>{n&&n(d)},[n,d]);const{environmentName:O,packageName:E,versionId:$}=c.parseResourceUri(l),{apiClients:P}=q.useServer(),A=T.useRef(void 0),B=c.useMutationWithApiError({mutationFn:()=>{A.current=u,b({executionState:"running",query:d?.malloyQuery,queryResolutionStartMillis:Date.now(),onCancel:()=>{B.reset(),b(void 0)},response:{}});const R=typeof d?.malloyQuery=="string"?d.malloyQuery:new i.ASTQuery({source:e.sourceInfo,query:d?.malloyQuery}).toMalloy();return h({...d,query:R}),P.models.executeQueryModel(O,E,e.modelPath,{query:R,sourceName:void 0,queryName:void 0,versionId:$,...a&&Object.keys(a).length>0?{givens:a}:{}})},onSuccess:R=>{if(R){const W=JSON.parse(R.data.result);h({...d,malloyResult:W});const Z=A.current;b(ne=>ne?{...ne,executionState:"finished",response:{result:W,...Z?.defaultsNote?{messages:[{severity:"INFO",title:Z.defaultsNote}]}:{}}}:void 0)}},onError:R=>{console.error("Query execution error:",R);const W=R?.data?.message??R?.message??"The query could not be run.",Z=[{severity:"ERROR",title:W}],ne=A.current?.missing??[];(R?.status===403||/Access denied for source/i.test(W))&&ne.length>0&&Z.push({severity:"WARN",title:ay(ne)}),b(H=>H?{...H,executionState:"finished",response:{messages:Z}}:void 0)}}),[D,_]=T.useState(e.sourceInfo.name);T.useEffect(()=>{D!==e.sourceInfo.name&&(_(e.sourceInfo.name),h(Ns()),b(void 0))},[e,D]);const V=T.useCallback(R=>{h({...d,malloyQuery:R,malloyResult:void 0})},[d]);return D!==e.sourceInfo.name?t.jsx("div",{children:"Loading..."}):t.jsx(q.StyledExplorerContent,{sx:{border:"1px solid #e0e0e0",borderRadius:"8px",overflow:"hidden"},children:t.jsx(k,{source:e.sourceInfo,query:d?.malloyQuery,topValues:[],onFocusedNestViewPathChange:v,focusedNestViewPath:x,onQueryChange:V,children:t.jsxs("div",{style:{display:"flex",height:"100%",overflowY:"auto"},children:[t.jsx(S,{isInitiallyExpanded:!0,initialWidth:180,minWidth:180,icon:"database",title:e.sourceInfo.name,children:t.jsx(M,{onRefresh:()=>h(Ns())})}),t.jsx(S,{isInitiallyExpanded:!0,initialWidth:280,minWidth:280,icon:"filterSliders",title:"Query",children:t.jsx(C,{runQuery:()=>{console.log(`running query with: ${d?.malloyQuery}`);try{B.mutate()}catch(R){console.error("Error running query:",R)}}})}),t.jsx(j,{source:e.sourceInfo,draftQuery:d?.malloyQuery,setDraftQuery:R=>h({...d,malloyQuery:R}),submittedQuery:y,options:{showRawQuery:!0}})]})})},e.sourceInfo.name)}function cy(e){const[n,r]=T.useState(null),[o,i]=T.useState(null),[l,a]=T.useState(!0);return T.useEffect(()=>{let u=!0;return Promise.all([import("@malloydata/malloy-explorer"),c.loadQueryBuilder()]).then(([d,h])=>{u&&(r(d),i(h),a(!1))}).catch(d=>{console.error("Failed to load Malloy components:",d),u&&a(!1)}),()=>{u=!1}},[]),l||!n||!o?t.jsx(q.StyledExplorerPage,{children:t.jsx(q.StyledExplorerContent,{children:t.jsx(wr.Box,{sx:{alignItems:"center",justifyContent:"center",height:"200px",color:"text.secondary"},children:"Loading explorer..."})})}):t.jsx(ly,{...e,explorerComponents:n,QueryBuilder:o,resourceUri:e.resourceUri})}function Oo(e,n=!0){const{modelPath:r,environmentName:o,packageName:i,versionId:l}=c.parseResourceUri(e),{apiClients:a}=q.useServer();return c.useQueryWithApiError({queryKey:["package",o,i,r,l],queryFn:async()=>(await a.models.getModel(o,i,r,l)).data,enabled:n})}function Eo({data:e,onChange:n,existingQuery:r,initialSelectedSourceIndex:o=0,onSourceChange:i,resourceUri:l,givens:a,onGivensChange:u,startingGivens:d}){const[h,y]=T.useState(o);T.useEffect(()=>{y(o)},[o]);const{data:b,isError:x,isLoading:v,error:k}=Oo(l,!e),{environmentName:C,packageName:S,modelPath:j,versionId:M}=c.parseResourceUri(l),O=e||b,E=T.useMemo(()=>O?.givens??[],[O]),$=c.useDocumentControls({specs:E,loaded:!!O,params:a,onGivensChange:u,startingValues:d,documentKey:l,autorun:!0,environmentName:C??"",packageName:S??"",modelPath:j,versionId:M,documentName:j}),P=T.useMemo(()=>c.givensToRequest($.applied,$.declaredTypes),[$.applied,$.declaredTypes]),A=T.useMemo(()=>iy(E,$.applied),[E,$.applied]);if(v&&!e)return t.jsx(c.Loading,{text:"Fetching Model..."});if(x&&!e)return console.log("error",k),t.jsx(c.ApiErrorDisplay,{error:k,context:`ModelExplorer > ${j}`});if(!O)return t.jsx(c.Loading,{text:c.LOADING_COPY.loading});const B=(O?.sourceInfos||[]).map((_,V)=>{try{return JSON.parse(_)?.name||`Source ${V+1}`}catch{return`Source ${V+1}`}}),D=B[h]||"";return t.jsxs(q.StyledCard,{variant:"outlined",children:[t.jsx(q.StyledCardContent,{children:t.jsx(m.Stack,{sx:{flexDirection:"row"},children:t.jsx(Ks,{size:"small",id:"size-small-standard",disablePortal:!0,options:B,value:D,onChange:(_,V)=>{if(!V)return;const R=B.indexOf(V);R>=0&&(y(R),i?.(R))},renderInput:_=>t.jsx(c.TextField,{..._}),style:{width:350,marginTop:"3px",marginLeft:"6px",marginBottom:"8px"}})})}),t.jsx(c.GivensPanel,{...$.panel}),t.jsx(q.StyledCardMedia,{children:t.jsxs(m.Stack,{spacing:2,component:"section",children:[Array.isArray(O.sourceInfos)&&O.sourceInfos.length>0&&t.jsx(ac,{sourceAndPaths:O.sourceInfos.map(_=>({sourceInfo:JSON.parse(_),modelPath:j})),selectedSourceIndex:h,existingQuery:r,onQueryChange:n,resourceUri:l,givens:P,gate:A}),t.jsx(m.Box,{height:"5px"})]})})]})}function Io({open:e,onClose:n,resourceUri:r,data:o,title:i="Data Sources",hasValidImport:l=!0,existingQuery:a,initialSelectedSourceIndex:u,onChange:d,onSourceChange:h,givens:y,onGivensChange:b,startingGivens:x}){return t.jsxs(m.Dialog,{open:e,onClose:n,fullScreen:!0,children:[t.jsxs(m.DialogTitle,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[i,t.jsx(m.IconButton,{onClick:n,sx:{color:"text.secondary"},children:t.jsx(c.CloseIcon,{})})]}),t.jsx(m.DialogContent,{children:l?t.jsx(Eo,{resourceUri:r,data:o,existingQuery:a,initialSelectedSourceIndex:u,onChange:d,onSourceChange:h,givens:y,onGivensChange:b,startingGivens:x}):t.jsx("div",{children:"No valid import statement found in cell"})})]})}function uy({onChange:e,resourceUri:n,runOnDemand:r=!1,maxResultSize:o=0,givens:i,onGivensChange:l}){const{modelPath:a}=c.parseResourceUri(n),{data:u,isError:d,isLoading:h,error:y}=Oo(n),[b,x]=T.useState(!1),[v,k]=T.useState(),[C,S]=T.useState(0),[j,M]=T.useState(""),[O,E]=T.useState({}),$=i??O,P=l??(R=>E(R)),A=u?.modelDef,B=T.useMemo(()=>{if(!A)return!1;try{const R=JSON.parse(A);return Array.isArray(R.imports)&&R.imports.length>0}catch{return!1}},[A]);if(h)return t.jsx(c.Loading,{text:"Fetching Model..."});if(d)return console.log("error",y),t.jsx(c.ApiErrorDisplay,{error:y,context:`Model > ${a}`});const D=R=>{k(R),e&&e(R)},_=R=>{S(R)},V=()=>{const R=window.location.href;navigator.clipboard.writeText(R).then(()=>M("URL copied to clipboard!")).catch(()=>M("Failed to copy URL"))};return t.jsxs(t.Fragment,{children:[t.jsxs(m.Box,{sx:{position:"relative",maxWidth:"1200px",margin:"0 auto",paddingTop:"24px"},children:[Array.isArray(u?.sourceInfos)&&u.sourceInfos.length>0&&t.jsxs(m.Stack,{spacing:2,component:"section",children:[t.jsxs(m.Box,{sx:{padding:"0 0 16px 0",display:"flex",alignItems:"center",justifyContent:"space-between"},children:[t.jsx(m.Typography,{variant:"h1",sx:{fontSize:"28px",fontWeight:"600",color:"#1a1a1a",marginBottom:"8px",marginTop:"0",paddingLeft:"0"},children:"Sources"}),t.jsx(m.Tooltip,{title:"Copy link",children:t.jsx(m.IconButton,{size:"small","aria-label":"Copy link",onClick:V,sx:{color:"text.secondary"},children:t.jsx(ho,{fontSize:"small"})})})]}),t.jsx(Eo,{data:u,onChange:D,onSourceChange:_,existingQuery:v,initialSelectedSourceIndex:C,resourceUri:n,givens:$,onGivensChange:P}),t.jsx(c.FloatingIconButton,{"aria-label":"Expand results",sx:{position:"absolute",top:"90px",right:"4px",zIndex:2},onClick:()=>x(!0),children:t.jsx(c.SearchIcon,{})})]}),u?.queries?.length>0&&t.jsxs(m.Stack,{spacing:2,component:"section",sx:{marginTop:"24px"},children:[t.jsx(m.Box,{sx:{padding:"0 0 16px 0"},children:t.jsx(m.Typography,{variant:"h2",sx:{fontSize:"24px",fontWeight:"600",color:"#1a1a1a",marginBottom:"0",marginTop:"8px",paddingLeft:"0"},children:"Named Queries"})}),u.queries.map(R=>t.jsx(sy,{queryName:R.name,annotations:R.annotations,resourceUri:n,runOnDemand:r,maxResultSize:o},R.name))]}),(!Array.isArray(u?.sourceInfos)||u.sourceInfos.length===0)&&!(u?.queries&&u.queries.length>0)&&t.jsxs(m.Box,{sx:{textAlign:"center",py:6},children:[t.jsx(m.Typography,{variant:"body1",sx:{color:"text.secondary",marginBottom:"8px"},children:"This model exposes no sources or queries."}),B&&t.jsxs(m.Typography,{variant:"body2",color:"text.secondary",children:["It imports other files but re-exports nothing. Add"," ",t.jsxs("code",{children:["export ","{ source_name }"]})," to surface imported sources here."]})]}),t.jsx(Io,{open:b,onClose:()=>x(!1),resourceUri:n,data:u,title:`Model: ${a.split("/").pop()}`,existingQuery:v,initialSelectedSourceIndex:C,onChange:D,onSourceChange:_,givens:$,onGivensChange:P})]}),t.jsx(m.Snackbar,{open:j!=="",autoHideDuration:6e3,onClose:()=>M(""),message:j})]})}function dy(){const[e,n]=T.useState(""),r=()=>{navigator.clipboard.writeText(window.location.href).then(()=>n("URL copied to clipboard!")).catch(()=>n("Failed to copy URL"))};return t.jsxs(t.Fragment,{children:[t.jsx(m.Tooltip,{title:"Copy link",children:t.jsx(m.IconButton,{size:"small","aria-label":"Copy link",onClick:r,sx:{color:"text.secondary"},children:t.jsx(ho,{fontSize:"small"})})}),t.jsx(m.Snackbar,{open:e!=="",autoHideDuration:6e3,onClose:()=>n(""),message:e})]})}function hy(e){const{modelPage:n,isLoadingStatus:r}=q.useServer();if(r)return t.jsx(c.Loading,{text:"Fetching Model..."});if(n!=="viewer")return t.jsx(uy,{...e});const{onChange:o,runOnDemand:i,headerActions:l,...a}=e;return t.jsx(oc,{...a,headerActions:l??t.jsx(dy,{})})}const fy={"persist-source-refused":"persist-not-built","preaggregate-not-built":"rollup-not-built","preaggregate-join-one-key-repeated":"rollup-join-one-key-repeated","stored-native-schema-missing":"database-native-type-missing"};function py(e){const n=(o,i)=>`${o}\0${i.subject??""}\0${i.message??""}`,r=new Set(e.map(o=>n(o.code,o)));return e.filter(o=>{const i=o.code!==void 0?fy[o.code]:void 0;return i===void 0||!r.has(n(i,o))})}function my({warnings:e}){const[n,r]=T.useState(!1),o=py(e??[]),i=o.filter(a=>a.severity==="error"),l=o.filter(a=>a.severity!=="error");return i.length===0&&l.length===0?null:t.jsxs(m.Stack,{sx:{gap:1,mb:4},children:[i.length>0&&t.jsxs(m.Alert,{severity:"warning",children:[t.jsx(m.AlertTitle,{children:i.length===1?"1 problem in this package":`${i.length} problems in this package`}),t.jsx(Oa,{findings:i})]}),l.length>0&&t.jsxs(m.Box,{children:[t.jsxs(m.Button,{size:"small","aria-expanded":n,onClick:()=>r(a=>!a),sx:{px:.5,color:"text.secondary"},children:[n?"Hide":"Show"," ",l.length," ",l.length===1?"note":"notes"]}),n&&t.jsx(m.Box,{sx:{pl:.5,pt:.5},children:t.jsx(Oa,{findings:l})})]})]})}function Oa({findings:e}){return t.jsx(m.Stack,{component:"ul",sx:{m:0,p:0,listStyle:"none",gap:.75},children:e.map((n,r)=>t.jsxs(m.Typography,{component:"li",variant:"body2",children:[n.model&&t.jsx(m.Box,{component:"span",sx:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"0.85em",mr:1},children:n.model}),n.message]},`${n.model??""}:${n.code??""}:${r}`))})}function lc(e){return T.useMemo(()=>{if(!e?.sources?.length)return[];const n=new Map;for(const r of e.sources)if(r.givens?.length)for(const o of r.givens)o.name&&!n.has(o.name)&&n.set(o.name,o);return Array.from(n.values())},[e])}function gy(e){return e.type==="code"}function yy(e){return(e.text??"").split(`
|
|
37
37
|
`).filter(n=>!n.trimStart().startsWith("##")).join(`
|
|
38
|
-
`)}const hy=c.createSvgIcon(t.jsx("path",{d:"M9.4 16.6 4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0 4.6-4.6-4.6-4.6L16 6l6 6-6 6z"}));function fy({cell:e,resourceUri:n,showCopyLink:r,maxResultSize:o,isExecuting:i,pendingRerun:l,onNavigate:a,onDrillSelf:u,canDrillSelf:d,onDrillNavigate:h,givens:y,givenSpecs:b}){const[x,v]=j.useState(!1),[k,C]=j.useState(!1),[S,T]=j.useState(),[O,M]=j.useState(!1),{modelPage:E,isLoadingStatus:R}=q.useServer(),P=!R&&E!=="viewer",[F,B]=j.useState(""),{environmentName:D,packageName:_,modelPath:V}=c.parseResourceUri(n),$={environmentName:D,packageName:_,sourcePath:V,onNavigate:a},{drill:W,drillMenu:Z}=oo({onNavigate:h,onSelf:u,canSelf:d}),ne=/import\s*\{([^}]+)\}\s*from\s*['"`][^'"`]+['"`]/,J=/import\s*(?:\{[^}]*\}\s*from\s*)?['"`]([^'"`]+)['"`]/,H=!!e.text&&(ne.test(e.text)||J.test(e.text)),Q=()=>{if(!e.newSources||e.newSources.length===0)return 0;let ie=[],De="";if(e.text){const de=e.text.match(ne);de&&(ie=de[1].split(",").map(be=>be.trim()));const ue=e.text.match(J);ue&&(De=ue[1].trim())}for(let de=0;de<e.newSources.length;de++)try{const ue=JSON.parse(e.newSources[de]);if(ie.length>0&&ie.includes(ue.name)||De&&De===ue.path)return de}catch{continue}return 0},re=j.useMemo(()=>e.newSources&&e.newSources.length>0?{sourceInfos:e.newSources,resource:n,givens:b}:void 0,[e.newSources,n,b]),{mode:z}=q.usePublisherTheme();j.useEffect(()=>{e.type==="code"&&jo(dy(e),"malloy",z).then(ie=>{T(ie)})},[e,z]);const oe=()=>{const ie=window.location.href;navigator.clipboard.writeText(ie).then(()=>B("URL copied to clipboard!")).catch(()=>B("Failed to copy URL"))},se=t.jsx(c.AppDialog,{open:x,onClose:()=>v(!1),title:"Malloy code",maxWidth:"lg",showClose:!0,children:t.jsx(p.Box,{sx:ie=>({border:`1px solid ${ie.palette.divider}`,borderRadius:"8px",padding:"16px",fontFamily:q.MONO_FONT_FAMILY,fontSize:"14px",lineHeight:"1.5",overflow:"auto",maxHeight:"70vh",backgroundColor:ie.palette.background.paper,color:ie.palette.text.primary}),children:t.jsx("pre",{className:"code-display",style:{margin:0},dangerouslySetInnerHTML:{__html:S}})})});return e.type==="markdown"&&t.jsx(p.Box,{children:t.jsxs(c.TextTileFrame,{children:[r?t.jsxs(p.Stack,{direction:"row",alignItems:"flex-start",justifyContent:"space-between",children:[t.jsx(c.Prose,{variant:"document",links:$,children:e.text}),t.jsx(p.Tooltip,{title:"Copy link",children:t.jsx(p.IconButton,{"aria-label":"Copy link",onClick:oe,sx:{color:"text.secondary",mt:"18px"},children:t.jsx(ho,{sx:{fontSize:"24px"}})})})]}):t.jsx(c.Prose,{variant:"document",links:$,children:e.text}),t.jsx(p.Snackbar,{open:F!=="",autoHideDuration:6e3,onClose:()=>B(""),message:F})]})})||e.type==="code"&&t.jsxs(p.Box,{children:[e.newSources&&e.newSources.length>0&&t.jsx(p.Stack,{sx:{flexDirection:"column",gap:"8px",marginBottom:"2px"},children:t.jsx(q.CleanMetricCard,{sx:{position:"relative",padding:"0"},children:t.jsxs(p.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingLeft:"24px",paddingRight:"8px"},children:[S&&t.jsx("span",{dangerouslySetInnerHTML:{__html:S},style:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"14px",flex:1,marginRight:"8px"}}),H&&P&&t.jsx(c.FloatingIconButton,{"aria-label":"Data sources",sx:{flexShrink:0},onClick:()=>M(!0),children:t.jsx(c.SearchIcon,{})})]})})}),t.jsx(Io,{open:O&&P,onClose:()=>M(!1),title:"Data Sources",hasValidImport:H,resourceUri:n,data:re,initialSelectedSourceIndex:Q(),startingGivens:y}),se,t.jsx(rc,{open:k,onClose:()=>C(!1),result:e.result||"",title:"Results",drill:W}),i&&!e.result&&!e.error&&!H&&!(e.newSources&&e.newSources.length>0)&&t.jsx(c.TileCard,{children:t.jsx(p.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:200},children:t.jsx(p.CircularProgress,{size:32})})}),!e.result&&e.error&&t.jsx(c.ErrorDetailAlert,{summary:"This cell could not be run.",detail:e.error}),e.result&&l&&t.jsx(p.LinearProgress,{"aria-label":"Re-run pending",sx:{mb:1,height:2,borderRadius:1}}),e.result&&t.jsxs(c.TileCard,{children:[t.jsx(c.TileHeading,{title:"",action:t.jsxs(p.Stack,{direction:"row",sx:{gap:.5,mt:"-4px"},children:[t.jsx(c.FloatingIconButton,{"aria-label":"Malloy code",onClick:ie=>{ie.stopPropagation(),v(!0)},children:t.jsx(hy,{})}),t.jsx(c.FloatingIconButton,{"aria-label":"Expand results",onClick:()=>C(!0),children:t.jsx(c.SearchIcon,{})})]})}),t.jsx(c.ResultContainer,{result:e.result,maxHeight:c.NOTEBOOK_CELL_MAX_HEIGHT,maxResultSize:o,drill:W}),Z]})]})}function my({ready:e,lastRunKey:n,pendingKey:r,runKey:o,documentKey:i}){if(!e)return{cancelPending:r!==void 0,dispatch:"none"};const l=r!==void 0&&r!==o;if(n===o)return{cancelPending:l,dispatch:"none"};if(r===o)return{cancelPending:l,dispatch:"none"};const a=n===null||!n.startsWith(`${i}|`);return{cancelPending:l,dispatch:a?"now":"settle"}}const py=4;function gy(e){const n=e?.response?.data?.message;return typeof n=="string"&&n!==""?n:e instanceof Error&&e.message!==""?e.message:"The server did not say why."}function yy({resourceUri:e,maxResultSize:n=0,givens:r,onGivensChange:o,onNavigate:i,onDrillNavigate:l,actions:a,notebook:u,runCell:d}){const{environmentName:h,packageName:y,versionId:b,modelPath:x}=c.parseResourceUri(e),[v,k]=j.useState([]),[C,S]=j.useState(!1),[T,O]=j.useState(!1),M=j.useRef(void 0),[E,R]=j.useState(null),P=oc(u),F=u.autorun!==!1,B=c.useReportEvents(),D=c.useDocumentControls({specs:P,loaded:!0,startingValues:u.startingGivens,params:r,onGivensChange:o,documentKey:e,autorun:F,environmentName:h,packageName:y,modelPath:x,versionId:b,documentName:x}),{applied:_,declaredTypes:V,canSelf:$,onSelf:W}=D,Z=j.useCallback(ue=>{const be=c.givensToRequest(ue,V);return Object.keys(be).length>0?JSON.stringify(be):void 0},[V]),ne=j.useMemo(()=>c.givensToParams(_,V),[_,V]),J=j.useRef(0),H=j.useRef(null),Q=j.useRef(null),re=j.useRef(void 0);j.useEffect(()=>()=>{H.current?.abort(),Q.current=null,clearTimeout(re.current?.timer),re.current=void 0},[]);const z=j.useCallback(async(ue=new Map)=>{if(!u.notebookCells)return;const be=++J.current;H.current?.abort();const Me=new AbortController;H.current=Me,k(u.notebookCells.map(te=>({...te}))),S(!0),R(null);try{const te=[];for(let he=0;he<u.notebookCells.length;he++){const we=u.notebookCells[he];if(!uy(we))continue;const ge=he,pe=async()=>{try{const ye=await d({cell:we,givens:ue,declaredTypes:V,signal:Me.signal});if(J.current!==be)return;const Le=ye.result;k(st=>{const ce=[...st];return ce[ge]||(ce[ge]={...we}),ce[ge]={...ce[ge],result:Le},ce})}catch(ye){if(Me.signal.aborted||J.current!==be)return;B.emit({type:"report.query_failed",tile:ge,category:c.failureCategory(ye)}),B.listening||console.error(`Error executing cell ${ge}:`,ye);const Le=gy(ye);k(st=>{const ce=[...st];return ce[ge]||(ce[ge]={...we}),ce[ge]={...ce[ge],error:Le},ce})}};te.push(pe)}const K=[];for(const he of te){const we=he().then(()=>{K.splice(K.indexOf(we),1)});K.push(we),K.length>=py&&await Promise.race(K)}await Promise.all(K)}catch(te){if(Me.signal.aborted||J.current!==be)return;B.emit({type:"report.query_failed",category:c.failureCategory(te)}),B.listening||console.error("Error executing notebook cells:",te),R(te)}finally{J.current===be&&(S(!1),H.current=null)}},[u,V,d,B]),oe=j.useRef(0),se=j.useRef(void 0);se.current!==u&&(se.current=u,oe.current+=1);const ie=oe.current;j.useEffect(()=>{const ue=`${e}|${ie}`,be=`${ue}|${Z(_)??""}`;M.current!==void 0&&M.current!==ue&&(H.current?.abort(),H.current=null),M.current=ue;const Me=my({ready:!!u.notebookCells,lastRunKey:Q.current,pendingKey:re.current?.key,runKey:be,documentKey:ue});if(Me.cancelPending&&(clearTimeout(re.current?.timer),re.current=void 0,O(!1)),Me.dispatch==="none")return;const te=()=>{re.current=void 0,O(!1),Q.current=be,z(_)};if(Me.dispatch==="now"){te();return}O(!0),re.current={key:be,timer:setTimeout(te,c.GIVEN_SETTLE_MS)}},[u,ie,e,_,Z,z]);const De=v.length>0?v:u.notebookCells||[],de=0;return t.jsxs(c.ReportPage,{layout:"linear",header:a?t.jsx(p.Stack,{direction:"row",sx:{justifyContent:"flex-end"},children:a}):null,controls:D.panel.givens.length>0?t.jsx(c.StickyControls,{children:t.jsx(c.GivensPanel,{...D.panel,layout:"bar"})}):void 0,children:[De.map((ue,be)=>t.jsx(fy,{cell:ue,showCopyLink:be===de,resourceUri:e,maxResultSize:n,isExecuting:C,givens:ne,givenSpecs:P,pendingRerun:T,onNavigate:i,onDrillNavigate:l,onDrillSelf:P.length>0?W:void 0,canDrillSelf:$},be)),E&&t.jsx(c.ApiErrorDisplay,{error:{message:E.message,status:500,name:"ExecutionError"},context:"Notebook Execution"})]})}function xy({environmentName:e,packageName:n,versionId:r,path:o,notebook:i,...l}){const{apiClients:a,server:u}=q.useServer(),d=j.useCallback(async({cell:h,givens:y,declaredTypes:b,signal:x})=>{const v=h.runQuery;if(v===void 0)return{};x.throwIfAborted();const k=c.givensToRequest(y,b),C={environmentName:e,packageName:n,versionId:r,modelPath:o,query:v,givens:Object.keys(k).length>0?k:void 0},S=[...c.queryResultKey(C),u],T=()=>q.globalQueryClient.fetchQuery({queryKey:S,queryFn:({signal:M})=>c.requestQueryResult(a,C,M),...q.CHART_RESULT_QUERY_OPTIONS}),O=()=>void q.globalQueryClient.cancelQueries({queryKey:S,exact:!0});x.addEventListener("abort",O,{once:!0});try{let M;try{M=await T()}catch(E){if(!mt.isCancelledError(E)||x.aborted)throw E;M=await T()}return{result:M.data.result}}finally{x.removeEventListener("abort",O)}},[a,u,e,n,o,r]);return t.jsx(yy,{...l,resourceUri:c.encodeResourceUri({environmentName:e,packageName:n,modelPath:o,versionId:r}),notebook:i,runCell:d})}function ic({resourceUri:e,path:n,givens:r,onGivensChange:o,onNavigate:i,onLinkNavigate:l,height:a,maxResultSize:u,onEvent:d,chrome:h,manifestStaleTime:y,actions:b,rowsActions:x}){const v=c.parseResourceUri(e),{apiClients:k}=q.useServer(),C=v.environmentName??"",S=v.packageName??"",T=v.versionId,O=!!v.environmentName&&!!v.packageName,{data:M,isSuccess:E,isError:R,error:P}=c.useQueryWithApiError({...c.reportQueryOptions(k,{environmentName:C,packageName:S,path:n,versionId:T},y),enabled:O&&n!==""}),F=M?.layout,B=c.useReportEmitter({path:n,layout:F},d),D=`${e}|${n}`,_=j.useRef(void 0),V=j.useRef({key:D,at:c.now()});V.current.key!==D&&(V.current={key:D,at:c.now()}),j.useEffect(()=>{_.current!==D&&(O?R?(_.current=D,B.emit({type:"report.load_failed",surface:"view",category:c.failureCategory(P)})):E&&M&&(_.current=D,B.emit({type:"report.opened",surface:"view",from:"package",tiles:M.tiles?.length??M.notebook?.notebookCells?.filter(ne=>ne.type==="code"&&ne.runQuery!==void 0).length??0,durationMs:c.now()-V.current.at})):(_.current=D,B.emit({type:"report.load_failed",surface:"view",category:"invalid"})))},[D,O,R,P,E,M,B]);const $=j.useCallback((ne,J)=>{const H=i?.(ne,J);H&&B.emit({type:"report.drill",to:"report",outcome:H})},[i,B]),W=i?$:void 0;if(!O)return t.jsxs(p.Alert,{severity:"error",children:["A report resource URI must name an environment and a package. Received: ",e]});if(R)return t.jsx(c.ApiErrorDisplay,{context:`${C} > ${S} > ${n}`,error:P});if(!E||!M)return t.jsx(c.Loading,{text:c.LOADING_COPY.opening("report")});const Z=M.notebook?.format==="malloynb"?t.jsx(xy,{environmentName:C,packageName:S,versionId:T,path:n,notebook:M.notebook,givens:r,onGivensChange:o,onNavigate:l,onDrillNavigate:W,maxResultSize:u,...b!==void 0?{actions:b}:{}}):t.jsx(Ga,{manifest:M,environmentName:C,packageName:S,versionId:T,documentName:n,givens:r,onGivensChange:o,onNavigate:W,...l?{onLinkNavigate:l}:{},height:a,maxResultSize:u,chrome:h,...b!==void 0?{actions:b}:{},...x!==void 0?{rowsActions:x}:{}});return t.jsx(c.ReportEventsContext.Provider,{value:B,children:Z})}function ac({open:e,layout:n,kind:r,allowLayoutChange:o,allowKindChange:i,environmentName:l,packageName:a,versionId:u,models:d,modelsLoading:h=!1,modelsError:y,onRetryModels:b,target:x,savedAs:v,onClose:k,onCreated:C,onEvent:S}){const T=n??(r?c.layoutOfKind(r):"linear"),O=o??i??!0,[M,E]=j.useState(T),[R,P]=j.useState(void 0),[F,B]=j.useState(""),[D,_]=j.useState(""),[V,$]=j.useState(""),W=j.useRef(null),[Z,ne]=j.useState(""),[J,H]=j.useState(!1),[Q,re]=j.useState(!1),[z,oe]=j.useState(!1),[se,ie]=j.useState(void 0),De=y!=null,{choices:de,isLoading:ue,isSuccess:be,failed:Me,retry:te,canRetry:K}=c.useDocumentChoices({environmentName:l,packageName:a,...u!==void 0?{versionId:u}:{},models:d,enabled:e&&d.length>0}),he=j.useMemo(()=>de.get(F)??[],[de,F]),we=j.useMemo(()=>new Map([...de.entries()].flatMap(([me,He])=>He.map(vt=>[Ps(me,vt.source,vt.view),{model:me,source:vt.source,view:vt.view}]))),[de]),ge=j.useMemo(()=>{const me=de.size>1;return[...de.entries()].flatMap(([He,vt])=>{const Ce=new Map;for(const Re of vt)Ce.set(Re.source,[...Ce.get(Re.source)??[],Re]);return[...Ce.entries()].map(([Re,Ie])=>({key:`${He}::${Re}`,label:Re,ariaLabel:`${Re} in ${He}`,...me||Ie[0]?.sourceDescription?{detail:[me?He:void 0,Ie[0]?.sourceDescription].filter(Boolean).join(" · ")}:{},entries:Ie.map(We=>({key:Ps(He,We.source,We.view),name:We.view,title:We.description??c.readableName(We.view),...We.chart?{chart:We.chart}:{}}))}))})},[de]),pe=me=>{const He=we.get(me);He&&(B(He.model),_(`${He.source}::${He.view}`))},ye=he.find(me=>`${me.source}::${me.view}`===D),Le=ye?Ps(F,ye.source,ye.view):void 0,st=vy(ye,250);j.useEffect(()=>{e&&E(T)},[e,T]),j.useEffect(()=>{if(!e)return;const me=[...de.keys()];F===""&&me.length>0&&B(me[0])},[e,de,F]),j.useEffect(()=>{!e||he.length===0||D!==""||_(`${he[0].source}::${he[0].view}`)},[e,he,D]),j.useEffect(()=>{!e||J||ye===void 0||ne(c.readableName(ye.view))},[e,J,ye]),j.useEffect(()=>{e||(B(""),_(""),$(""),ne(""),H(!1),P(void 0),re(!1),ie(void 0))},[e]);const ce=j.useMemo(()=>{if(Z.trim()!=="")for(let me=1;me<=c.MAX_SLUG_ATTEMPTS;me++){const He=c.reportPathForTitle(Z,me);if(!x.existing?.includes(He))return He}},[Z,x]),Y=R?.trim(),ae=Y===void 0||Y===""?void 0:Y.endsWith(".malloy")?Y:`${Y}.malloy`,Fe=ae??ce,Ve=ae===void 0?void 0:c.reportPathProblem(ae)??(x.existing?.includes(ae)?`${ae} already exists; choose another location.`:void 0),Ee=(ye===void 0?void 0:c.newDocumentProblem({title:Z,modelPath:F,source:ye.source,view:ye.view}))??(Z.trim()!==""&&Fe===void 0?"No free file name for this title; choose another.":void 0),at=Ee!==void 0&&(Q||Z.trim()!==""),yt=h||ue,{theme:xt}=q.usePublisherTheme(),Ot=xt.ui,pt=c.edgeColor(xt.cardBorder),Ye=de.size===0&&(De||Me.length>0),fe=yt?"Loading the model":Ye?"Couldn't read the model to start from":de.size===0?"Nothing in the model to start from yet":ye===void 0?"Pick what to start from":void 0,Ke="report",ze=z?`Creating ${Ke}…`:`Create ${Ke}`,lt=D!==""&&ye===void 0&&he.length>0,ct=async()=>{if(!(fe!==void 0||ye===void 0||z)){if(Ee!==void 0||Ve!==void 0){re(!0);return}oe(!0),ie(void 0);try{const me=await c.createDocument({layout:M,...ae!==void 0?{path:ae}:{},document:{title:Z,modelPath:F,source:ye.source,view:ye.view},target:x,...S?{onEvent:S}:{}});C(me)}catch(me){const He=me.response?.data?.message;ie(He??(me instanceof Error?me.message:String(me)))}finally{oe(!1)}}},Qe=me=>t.jsx(p.Button,{color:"inherit",size:"small",onClick:me,children:"Retry"});return t.jsx(c.AppDialog,{className:`${c.reportClasses.dialog} ${c.reportClasses.newReportDialog}`,maxWidth:"md",initialFocus:W,open:e,onClose:z?()=>{}:k,title:`New ${Ke}`,description:"A report is a Malloy file in the package that lays out text and queries. Pick what its first query shows; the rest is the builder.",actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{onClick:k,disabled:z,children:"Cancel"}),t.jsx(p.Tooltip,{title:z?"":fe??"",children:t.jsx("span",{children:t.jsx(p.Button,{variant:"contained",disabled:z||fe!==void 0,"aria-label":!z&&fe!==void 0?`${ze}: ${fe}`:ze,onClick:()=>void ct(),children:ze})})})]}),children:t.jsxs(p.Stack,{sx:{gap:1.5},children:[De?t.jsx(p.Alert,{severity:"error",action:b&&so.canRetryRequest(y)?Qe(b):void 0,children:"Couldn't read this package's models, so no view is listed to start from."}):d.length===0?!h&&t.jsxs(p.Alert,{severity:"info",children:["This package has no models yet. Add a .malloy file that declares a source with a view, then create a ",Ke," from it."]}):Me.length>0?t.jsxs(p.Alert,{severity:"warning",action:K?Qe(te):void 0,children:["Couldn't read ",Me.join(", "),", so nothing from"," ",Me.length===1?"it":"them"," is listed."]}):be&&de.size===0&&t.jsxs(p.Alert,{severity:"info",children:["A ",Ke," starts from a view of a source, and no model in this package declares one yet. Add a view to a source in a model file and this list fills in."]}),t.jsxs(p.Box,{sx:{mx:-3,mb:-1,borderTop:`1px solid ${pt}`,borderBottom:`1px solid ${pt}`,display:"grid",gridTemplateColumns:{xs:"1fr",md:"320px minmax(0, 1fr)"},height:{md:500}},children:[t.jsx(p.Box,{sx:{display:"flex",flexDirection:"column",minHeight:0,borderRight:{md:`1px solid ${pt}`},maxHeight:{xs:280,md:"none"}},children:t.jsx(c.ViewPicker,{groups:ge,query:V,onQuery:$,picked:Le,onPick:pe,onTake:me=>{pe(me)},searchRef:W,disabled:z,empty:t.jsx(p.Typography,{variant:"body2",sx:{color:"text.secondary",p:2},children:yt?"Reading the package's models…":"Nothing to start from."})})}),t.jsxs(p.Box,{sx:me=>({p:2.5,display:"flex",flexDirection:"column",gap:2,minHeight:0,overflowY:"auto",bgcolor:`color-mix(in srgb, ${me.palette.text.primary} 3%, ${me.palette.background.paper})`}),children:[O&&t.jsxs(p.Box,{children:[t.jsx(Ea,{children:"Layout"}),t.jsx(p.Box,{role:"radiogroup","aria-label":"Layout",sx:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:1},children:["linear","grid"].map(me=>t.jsx(Sy,{layout:me,checked:M===me,disabled:z,onPick:()=>E(me)},me))}),t.jsx(p.Typography,{variant:"caption",component:"p",sx:{color:"text.secondary",mt:.75},children:"Switch it any time in the builder."})]}),t.jsxs(p.Box,{children:[t.jsx(Ea,{children:"First query"}),t.jsx(p.Box,{role:"region","aria-label":"Preview",sx:me=>({height:200,display:"flex",position:"relative",overflow:"hidden",borderRadius:Ot.radius.tile,border:`1px solid ${pt}`,bgcolor:me.palette.background.paper,"&::after":{content:'""',position:"absolute",left:0,right:0,bottom:0,height:40,pointerEvents:"none",background:`linear-gradient(to bottom, transparent, ${me.palette.background.paper})`}}),children:ye&&st?t.jsx(p.Box,{sx:{flex:1,minWidth:0,px:2,pt:1.5},children:t.jsx(c.DashboardTile,{environmentName:l,packageName:a,...u!==void 0?{versionId:u}:{},modelPath:F,tile:`${st.source} -> ${st.view}`,label:Z.trim()||c.readableName(st.view),borderless:!0,givens:by,declaredTypes:wy,height:180})}):t.jsx(p.Typography,{variant:"body2",sx:{color:"text.secondary",m:"auto"},children:lt?"What you picked is no longer in this model; pick something else.":"Pick what to start from."})}),t.jsx(p.Typography,{variant:"caption",component:"p",sx:{color:"text.secondary",mt:.75},children:"More are added in the builder."})]}),t.jsx(p.TextField,{size:"small",label:"Title",value:Z,disabled:z,onChange:me=>{H(!0),ne(me.target.value)},InputLabelProps:{shrink:!0},inputProps:{"aria-label":"Report title"},error:at,helperText:at?Ee:x.route==="package"?"Names the file too, unless you type a location.":v??`Saved as a new ${Ke} in the host's store, and opened in the builder.`}),t.jsx(p.TextField,{size:"small",label:"Location",value:R??ce??"",placeholder:"report.malloy",disabled:z,onChange:me=>P(me.target.value),InputLabelProps:{shrink:!0},inputProps:{"aria-label":"Location"},error:Ve!==void 0,helperText:Ve??(Fe?`Written as ${Fe} in the package, and opened in the builder.`:"A path in the package; the package root by default.")}),se&&t.jsx(p.Alert,{severity:"error",children:se})]})]})]})})}function vy(e,n){const[r,o]=j.useState(void 0);return j.useEffect(()=>{const i=window.setTimeout(()=>o(e),n);return()=>window.clearTimeout(i)},[e,n]),r}const Ps=(e,n,r)=>`${e}::${n}::${r}`,by=new Map,wy=new Map;function Ea({children:e}){const n=q.usePublisherTheme().theme.ui;return t.jsx(p.Typography,{component:"div",sx:{...n.type.label,color:"text.secondary",mb:.75},children:e})}function Sy({layout:e,checked:n,disabled:r,onPick:o}){const{theme:i}=q.usePublisherTheme(),l=i.ui,a=c.edgeColor(i.cardBorder),u=n?i.accent:"currentColor";return t.jsxs(p.ButtonBase,{role:"radio","aria-checked":n,"aria-label":e==="linear"?"Linear":"Grid",disabled:r,onClick:o,sx:d=>({justifyContent:"flex-start",gap:1.25,px:1.25,py:1,borderRadius:l.radius.tile,border:`1px solid ${n?i.accent:a}`,boxShadow:n?`0 0 0 1px ${i.accent}`:"none",bgcolor:n?`color-mix(in srgb, ${i.accent} 6%, ${d.palette.background.paper})`:d.palette.background.paper,color:d.palette.text.secondary,textAlign:"left"}),children:[t.jsx("svg",{width:"34",height:"26",viewBox:"0 0 34 26","aria-hidden":!0,children:e==="linear"?t.jsxs("g",{fill:"none",stroke:u,strokeWidth:"1.5",children:[t.jsx("rect",{x:"3",y:"2",width:"28",height:"7",rx:"1.5"}),t.jsx("rect",{x:"3",y:"12",width:"28",height:"5",rx:"1.5"}),t.jsx("path",{d:"M5 21.5h20",strokeLinecap:"round"})]}):t.jsxs("g",{fill:"none",stroke:u,strokeWidth:"1.5",children:[t.jsx("rect",{x:"2",y:"2",width:"14",height:"10",rx:"1.5"}),t.jsx("rect",{x:"18",y:"2",width:"14",height:"10",rx:"1.5"}),t.jsx("rect",{x:"2",y:"14",width:"30",height:"10",rx:"1.5"})]})}),t.jsxs(p.Box,{children:[t.jsx(p.Box,{sx:{...l.type.control,fontWeight:n?l.type.label.fontWeight:500,color:n?i.accent:"text.primary"},children:e==="linear"?"Linear":"Grid"}),t.jsx(p.Box,{sx:{...l.type.caption,color:"text.secondary"},children:e==="linear"?"Read top to bottom":"Tiles side by side"})]})]})}const ky=c.createSvgIcon(t.jsx("path",{d:"M21 11h-1.5v-.5h-2v3h2V13H21v1c0 .55-.45 1-1 1h-3c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1zM8 10v5H6.5v-1.5h-2V15H3v-5c0-.55.45-1 1-1h3c.55 0 1 .45 1 1m-1.5.5h-2V12h2zm7 1.5c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1h-4V9h4c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1M11 10.5v.75h2v-.75zm2 2.25h-2v.75h2z"})),Cy=c.createSvgIcon(t.jsx("path",{d:"M15 4v2h3v12h-3v2h5V4zM4 20h5v-2H6V6h3V4H4z"})),jy=c.createSvgIcon(t.jsx("path",{d:"M4 7v2c0 .55-.45 1-1 1H2v4h1c.55 0 1 .45 1 1v2c0 1.65 1.35 3 3 3h3v-2H7c-.55 0-1-.45-1-1v-2c0-1.3-.84-2.42-2-2.83v-.34C5.16 11.42 6 10.3 6 9V7c0-.55.45-1 1-1h3V4H7C5.35 4 4 5.35 4 7m17 3c-.55 0-1-.45-1-1V7c0-1.65-1.35-3-3-3h-3v2h3c.55 0 1 .45 1 1v2c0 1.3.84 2.42 2 2.83v.34c-1.16.41-2 1.52-2 2.83v2c0 .55-.45 1-1 1h-3v2h3c1.65 0 3-1.35 3-3v-2c0-.55.45-1 1-1h1v-4z"})),Ty=c.createSvgIcon(t.jsx("path",{d:"M20 10V8h-4V4h-2v4h-4V4H8v4H4v2h4v4H4v2h4v4h2v-4h4v4h2v-4h4v-2h-4v-4zm-6 4h-4v-4h4z"})),lc={dashboard:q.PALETTE.blue,report:q.PALETTE.violet,model:q.PALETTE.cyan,dataApp:q.PALETTE.pink,data:q.PALETTE.lime,materialization:q.PALETTE.amber,agent:q.PALETTE.red};function cc({type:e,size:n=18,sx:r,...o}){return t.jsx(c.SvgIcon,{...o,viewBox:"0 0 24 24",sx:{width:n,height:n,fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",...r},children:Oy[e]()})}const Oy={report:My,model:Ey,data:Iy,materialization:Dy,dataApp:Ay,dashboard:$y,agent:Fy};function My(){return t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M14 3 H6 a2 2 0 0 0 -2 2 v14 a2 2 0 0 0 2 2 h12 a2 2 0 0 0 2 -2 V9 z"}),t.jsx("path",{d:"M14 3 v4 a2 2 0 0 0 2 2 h4"}),t.jsx("path",{d:"M8 17 v-3"}),t.jsx("path",{d:"M12 17 v-6"}),t.jsx("path",{d:"M16 17 v-4"})]})}function Ey(){return t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M12 3 L4 7 v10 l8 4 l8 -4 V7 z"}),t.jsx("path",{d:"M4 7 l8 4 l8 -4"}),t.jsx("path",{d:"M12 11 v10"})]})}function Iy(){return t.jsxs(t.Fragment,{children:[t.jsx("rect",{x:"3.5",y:"3.5",width:"17",height:"17",rx:"2"}),t.jsx("path",{d:"M3.5 9.5 H20.5"}),t.jsx("path",{d:"M9.5 3.5 V20.5"})]})}function Dy(){return t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M12 3 L21 7.5 L12 12 L3 7.5 Z"}),t.jsx("path",{d:"M3 12 L12 16.5 L21 12"}),t.jsx("path",{d:"M3 16.5 L12 21 L21 16.5"})]})}function $y(){return t.jsxs(t.Fragment,{children:[t.jsx("rect",{x:"3.5",y:"3.5",width:"17",height:"17",rx:"2"}),t.jsx("path",{d:"M3.5 9.5 H20.5"}),t.jsx("path",{d:"M12 9.5 V20.5"}),t.jsx("path",{d:"M12 15 H20.5"})]})}function Fy(){return t.jsxs(t.Fragment,{children:[t.jsx("circle",{cx:"12",cy:"8",r:"3.5"}),t.jsx("path",{d:"M5 20 a7 7 0 0 1 14 0"})]})}function Ay(){return t.jsxs(t.Fragment,{children:[t.jsx("rect",{x:"3.5",y:"4.5",width:"17",height:"15",rx:"2"}),t.jsx("path",{d:"M3.5 9.5 H20.5"}),t.jsx("path",{d:"M7 13.5 H17"}),t.jsx("path",{d:"M7 16.5 H13"})]})}function uc(e){return e>=1e9?`${(e/1e9).toFixed(1)} B rows`:e>=1e6?`${(e/1e6).toFixed(1)} M rows`:e>=1e3?`${(e/1e3).toFixed(1)} K rows`:`${e} rows`}const Ry=12;function Ly(e){const n=e?.trim().toLowerCase()??"";if(n.startsWith("array")||n.endsWith("[]"))return Cy;if(n.startsWith("record")||n.startsWith("struct"))return jy;switch(n.split(/[\s(<]/)[0]){case"string":return ky;case"number":return Ty;case"date":return Rl;case"timestamp":case"timestamptz":return _l;case"boolean":return Nl;default:return Pl}}function _y({column:e}){const n=Ly(e.type);return t.jsxs(p.Box,{component:"li",sx:r=>({display:"flex",alignItems:"center",gap:1.25,px:1,py:.625,borderRadius:1,transition:"background-color 0.1s","&:hover":{backgroundColor:r.palette.mode==="dark"?"rgba(255, 255, 255, 0.06)":r.palette.grey[100]}}),children:[t.jsx(n,{"aria-hidden":!0,sx:{fontSize:18,color:"primary.main",flexShrink:0}}),t.jsxs(p.Box,{sx:{display:"flex",alignItems:"baseline",gap:1,minWidth:0,flex:1},children:[t.jsx(p.Typography,{component:"span",sx:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"0.8125rem",fontWeight:500,color:"text.primary",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),e.type&&t.jsx(p.Typography,{component:"span",variant:"caption",color:"text.secondary",sx:{flexShrink:0,maxWidth:"50%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.type})]})]})}function Ny({database:e,onClose:n}){const r=e!==null,[o,i]=j.useState(e);e!==null&&e!==o&&i(e);const[l,a]=j.useState(""),[u,d]=j.useState(o?.path);u!==o?.path&&(d(o?.path),a(""));const h=j.useId(),y=o?.path??"",b=y.split("/").pop()||y,x=y.slice(0,Math.max(0,y.length-b.length-1)),v=o?.info?.rowCount,k=[x,v===void 0?null:uc(v)].filter(Boolean).join(" · "),C=j.useMemo(()=>o?.info?.columns??[],[o]),S=l.trim().toLowerCase(),T=j.useMemo(()=>S?C.filter(O=>O.name?.toLowerCase().includes(S)||O.type?.toLowerCase().includes(S)):C,[C,S]);return t.jsxs(c.AppDialog,{open:r,onClose:n,showClose:!0,title:t.jsxs(p.Stack,{direction:"row",alignItems:"center",spacing:1.5,sx:{minWidth:0},children:[t.jsx(p.Box,{"aria-hidden":!0,sx:{width:32,height:32,borderRadius:1,bgcolor:lc.data,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t.jsx(cc,{type:"data",size:18})}),t.jsxs(p.Box,{sx:{minWidth:0},children:[t.jsx(p.Typography,{component:"span",noWrap:!0,title:y,sx:{display:"block",fontFamily:q.MONO_FONT_FAMILY,fontSize:"1rem",fontWeight:600,letterSpacing:0,lineHeight:1.4},children:b||"Columns"}),k&&t.jsx(p.Typography,{component:"span",variant:"caption",color:"text.secondary",noWrap:!0,sx:{display:"block",lineHeight:1.4},children:k})]})]}),children:[o?.error&&t.jsx(p.Alert,{severity:"error",variant:"outlined",children:o.error}),o&&!o.error&&t.jsxs(p.Box,{component:"section","aria-labelledby":h,sx:{display:"flex",flexDirection:"column",border:"1px solid",borderColor:"divider",borderRadius:2,bgcolor:"background.paper",overflow:"hidden",mb:2},children:[t.jsxs(p.Stack,{direction:"row",alignItems:"center",spacing:1,sx:{px:1.5,py:1,minHeight:44,borderBottom:"1px solid",borderColor:"divider"},children:[t.jsxs(p.Typography,{id:h,component:"h3",sx:{fontSize:"0.875rem",fontWeight:600},children:["Columns",t.jsxs(p.Typography,{component:"span",variant:"caption",color:"text.secondary",sx:{ml:.75,fontVariantNumeric:"tabular-nums"},children:["· ",S?`${T.length} of `:"",C.length]})]}),C.length>Ry&&t.jsx(p.InputBase,{value:l,onChange:O=>a(O.target.value),placeholder:"Filter columns",inputProps:{"aria-label":"Filter columns"},startAdornment:t.jsx(p.InputAdornment,{position:"start",children:t.jsx(c.SearchIcon,{sx:{fontSize:16,color:"text.secondary"}})}),sx:{ml:"auto !important",width:200,fontSize:"0.8125rem",px:1,py:.25,border:"1px solid",borderColor:"divider",borderRadius:1.5,"&.Mui-focused":{borderColor:"primary.main"}}})]}),t.jsx(p.Box,{sx:{overflowY:"auto",maxHeight:420,px:.75,py:.75},children:T.length===0?t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic",px:1,py:1},children:S?"No columns match":"No columns"}):t.jsx(p.Box,{component:"ul","aria-labelledby":h,sx:{listStyle:"none",m:0,p:0},children:T.map((O,M)=>t.jsx(_y,{column:O},`${O.name}-${M}`))})})]})]})}const Do=(e,n,r)=>["packageVersions",e,n,r];async function dc(e,n,r){try{return(await e.versions.listPackageVersions(n,r)).data}catch(o){const i=o?.response?.status;if(i===404||i===501)return[];throw o}}function hc(e,n,r={}){const{apiClients:o,server:i}=q.useServer(),l=(r.enabled??!0)&&e!==""&&n!=="",a=mt.useQuery({queryKey:Do(e,n,i),queryFn:()=>dc(o,e,n),enabled:l,staleTime:3e4,retry:!1}),{refetch:u}=a,d=j.useCallback(()=>void u(),[u]),h=a.data??[];return{versions:h,latest:h.find(y=>y.latest)?.id,isPending:l&&a.isPending,isError:l&&a.isError,refetch:d}}function Py(e,n){const{apiClients:r,server:o}=q.useServer(),i=mt.useQueryClient();return j.useCallback(()=>i.fetchQuery({queryKey:Do(e,n,o),queryFn:()=>dc(r,e,n),staleTime:0,retry:!1}),[i,r,o,e,n])}function fc(e,n){const r=mt.useQueryClient();return j.useCallback(()=>r.invalidateQueries({predicate:o=>o.queryKey[1]===e&&o.queryKey[2]===n}),[r,e,n])}const zy=c.createSvgIcon(t.jsx("path",{d:"m20.54 5.23-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27M6.24 5h11.52l.81.97H5.44zM5 19V8h14v11zm8.45-9h-2.9v3H8l4 4 4-4h-2.55z"})),Wy=c.createSvgIcon(t.jsx("path",{d:"M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2"})),qy=c.createSvgIcon(t.jsx("path",{d:"M14 4v5c0 1.12.37 2.16 1 3H9c.65-.86 1-1.9 1-3V4zm3-2H7c-.55 0-1 .45-1 1s.45 1 1 1h1v5c0 1.66-1.34 3-3 3v2h5.97v7l1 1 1-1v-7H19v-2c-1.66 0-3-1.34-3-3V4h1c.55 0 1-.45 1-1s-.45-1-1-1"})),By=c.createSvgIcon(t.jsx("path",{d:"m20.54 5.23-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27M6.24 5h11.52l.83 1H5.42zM5 19V8h14v11zm3-5h2.55v3h2.9v-3H16l-4-4z"})),dr=e=>{const n=e?.response?.data?.message;return typeof n=="string"&&n!==""?n:e instanceof Error?e.message:"Unknown error"},Vy=e=>{const n=new Date(e);return Number.isNaN(n.getTime())?"":n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})},An=e=>e.archiveStatus==="archive",zs="Tables built for this version alone (under scope: version) are dropped.";function Ia(e,n){const r=!An(e)&&n.filter(i=>!An(i)).length<=1,o=n.length<=1;return{archive:e.latest?"The latest version can't be archived":r?"The last version in service can't be archived":void 0,delete:o?void 0:e.latest?"Pin another version as latest first":r?"The last version in service; delete the archived versions first":void 0}}function mc({environmentName:e,packageName:n,versions:r,selectedVersionId:o,onSelectVersion:i,onReplaceVersion:l,onPackageDeleted:a,canManage:u}){const{apiClients:d}=q.useServer(),h=mt.useQueryClient(),y=fc(e,n),b=Py(e,n),[x,v]=j.useState(null),[k,C]=j.useState(null),[S,T]=j.useState(null),[O,M]=j.useState(null),[E,R]=j.useState(null),[P,F]=j.useState(null),B=j.useRef(null),D=j.useRef(null),_=j.useRef(null),V=j.useRef(new Map),$=r.find(K=>K.latest)?.id,W=o??$,Z=()=>Promise.all([y(),h.invalidateQueries({queryKey:["packages",e]})]),ne=async(K,he)=>{const we=he??await b().catch(()=>{});if(we===void 0)return;const ge=we.find(ye=>ye.latest)?.id,pe=ge??we.find(ye=>ye.id!==K&&!An(ye))?.id;pe!==void 0&&(l?l(pe===ge?void 0:pe):i(pe))},J=mt.useMutation({mutationFn:K=>d.versions.setPackageLatestVersion(e,n,{version:K}),onSuccess:async()=>{T(null),await Z()},onError:()=>void Z()}),H=mt.useMutation({mutationFn:({id:K,archiveStatus:he})=>d.versions.updatePackageVersion(e,n,K,{archiveStatus:he}),onSuccess:async(K,{id:he,archiveStatus:we})=>{M(null),we==="archive"&&he===W&&await ne(he),await Z()},onError:(K,{id:he,archiveStatus:we})=>{we==="unarchive"&&F(`Couldn't unarchive v${he}: ${dr(K)}`),Z()}}),Q=H.isPending?H.variables?.id:void 0,re=mt.useMutation({mutationFn:({id:K})=>d.versions.deletePackageVersion(e,n,K),onSuccess:async(K,{id:he,read:we})=>{R(null);const pe=await b().catch(()=>{})??we.filter(ye=>ye.id!==he);if(pe.length===0){await h.invalidateQueries({queryKey:["packages",e]}),a?.();return}he===W&&await ne(he,pe),await Z()},onError:()=>void Z()}),z=()=>C(null),oe=k?Ia(k.version,r):{},se=k!==null&&!An(k.version)&&k.version.latest&&oe.archive!==void 0&&oe.delete!==void 0,ie=E!==null&&E.versions===void 0,De=E?.versions!==void 0&&E.versions.length<=1,de=E?.versions!==void 0?Ia(E.version,E.versions).delete:void 0,ue=async K=>{z(),v(null),re.reset(),R({version:K});const he=pe=>R(ye=>ye!==null&&ye.version.id===K.id&&ye.versions===void 0?pe:ye);let we;try{we=await b()}catch(pe){he(null),F(`Couldn't check v${K.id} before deleting it: ${dr(pe)}`);return}const ge=we.find(pe=>pe.id===K.id);if(ge===void 0){he(null),F(`v${K.id} is no longer a version of ${n}.`),Z();return}he({version:ge,versions:we})},be=(K,he)=>{!u||Q===K.id||C({version:K,anchor:V.current.get(K.id)??he})},Me=(K,he)=>{const we=K.key==="ArrowRight"||K.key==="ContextMenu"||K.key==="F10"&&K.shiftKey;!u||!we||(K.preventDefault(),K.stopPropagation(),be(he,K.currentTarget))},te=k&&t.jsxs(p.MenuItem,{disabled:oe.delete!==void 0,onClick:()=>void ue(k.version),children:[t.jsx(p.ListItemIcon,{children:t.jsx(c.DeleteOutlineIcon,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:"Delete version",secondary:oe.delete})]},"delete");return t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{size:"small",variant:"outlined",endIcon:t.jsx(Ll,{}),"aria-label":W?`Version v${W}, change version`:"Select a version","aria-haspopup":"menu",onClick:K=>v(K.currentTarget),sx:{borderRadius:999,textTransform:"none",fontWeight:500,px:1.5,minWidth:0,whiteSpace:"nowrap"},children:W?`v${W}`:"Select a version"}),t.jsx(p.Menu,{anchorEl:x,open:x!==null,onClose:()=>v(null),slotProps:{paper:{sx:{minWidth:320,maxWidth:400,mt:1,borderRadius:3}},list:{"aria-label":`Versions of ${n}`,disabledItemsFocusable:!0}},children:r.map(K=>{const he=K.id===W,we=An(K),ge=[we?"Archived":void 0,Vy(K.createdAt),K.gitCommitSha?K.gitCommitSha.slice(0,7):void 0].filter(Boolean).join(" · ");return t.jsxs(p.MenuItem,{"aria-current":he?"true":void 0,"aria-disabled":we&&!u?"true":void 0,"aria-haspopup":u?"menu":void 0,"data-testid":"version-row",onKeyDown:pe=>Me(pe,K),onClick:pe=>{if(we){be(K,pe.currentTarget);return}he||(v(null),i(K.id,pe))},sx:pe=>({gap:1,borderLeft:"3px solid",borderLeftColor:he?pe.palette.primary.main:"transparent",backgroundColor:he?p.alpha(pe.palette.primary.main,.04):void 0,cursor:he||we&&!u?"default":"pointer"}),children:[t.jsx(p.ListItemText,{primary:K.id,secondary:ge,sx:{opacity:we?.6:1},slotProps:{primary:{sx:{fontWeight:he?600:400}}}}),K.latest&&t.jsx(p.Chip,{size:"small",label:"Latest",color:"info",variant:"outlined",sx:{height:20,fontSize:11,fontWeight:600}}),u&&t.jsx(p.Tooltip,{title:Q===K.id?"Updating this version…":"",children:t.jsx("span",{children:t.jsx(p.IconButton,{ref:pe=>{pe?V.current.set(K.id,pe):V.current.delete(K.id)},size:"small","aria-label":`More actions for version ${K.id}`,"aria-haspopup":"menu",disabled:Q===K.id,onClick:pe=>{pe.stopPropagation(),C({version:K,anchor:pe.currentTarget})},children:t.jsx(Wy,{fontSize:"small"})})})})]},K.id)})}),t.jsx(p.Menu,{anchorEl:k?.anchor??null,open:k!==null,onClose:z,slotProps:{list:{"aria-label":k?`Actions for version ${k.version.id}`:void 0,disabledItemsFocusable:!0,autoFocus:se}},children:k&&An(k.version)?[t.jsxs(p.MenuItem,{onClick:()=>{const{id:K}=k.version;z(),H.mutate({id:K,archiveStatus:"unarchive"})},children:[t.jsx(p.ListItemIcon,{children:t.jsx(By,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:"Unarchive"})]},"unarchive"),t.jsx(p.Divider,{},"divider"),te]:k&&[t.jsxs(p.MenuItem,{disabled:k.version.latest,onClick:()=>{T(k.version),J.reset(),z(),v(null)},children:[t.jsx(p.ListItemIcon,{children:t.jsx(qy,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:"Pin as latest",secondary:k.version.latest?"Already the latest version":void 0})]},"pin-latest"),t.jsxs(p.MenuItem,{disabled:oe.archive!==void 0,onClick:()=>{M(k.version),H.reset(),z(),v(null)},children:[t.jsx(p.ListItemIcon,{children:t.jsx(zy,{fontSize:"small"})}),t.jsx(p.ListItemText,{primary:"Archive",secondary:oe.archive})]},"archive"),t.jsx(p.Divider,{},"divider"),te]}),t.jsx(c.AppDialog,{open:S!==null,onClose:()=>{J.isPending||T(null)},title:S?`Pin v${S.id} as latest`:"",description:S?`Requests that name no version will be served from v${S.id}.`:void 0,initialFocus:B,actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{ref:B,disabled:J.isPending,onClick:()=>T(null),children:"Cancel"}),t.jsx(p.Button,{variant:"contained",loading:J.isPending,onClick:()=>S&&J.mutate(S.id),children:"Pin as latest"})]}),children:t.jsxs(p.Stack,{spacing:1.5,children:[$&&S&&$!==S.id&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:`The latest version is v${$} now. Links and requests that name a version keep answering as before.`}),J.isError&&S&&t.jsx(p.Alert,{severity:"error",role:"alert",children:`Couldn't pin v${S.id} as latest: ${dr(J.error)}`})]})}),t.jsx(c.AppDialog,{open:O!==null,onClose:()=>{H.isPending||M(null)},title:O?`Archive v${O.id}`:"",description:O?`v${O.id} stops being served and is unloaded. Its files stay, so it can be unarchived.`:void 0,initialFocus:D,actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{ref:D,disabled:H.isPending,onClick:()=>M(null),children:"Cancel"}),t.jsx(p.Button,{variant:"contained",loading:H.isPending,onClick:()=>O&&H.mutate({id:O.id,archiveStatus:"archive"}),children:"Archive"})]}),children:t.jsxs(p.Stack,{spacing:1.5,children:[t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:`${zs} Its scheduled builds stop, and once unarchived it serves live until it is built again.`}),H.isError&&O&&t.jsx(p.Alert,{severity:"error",role:"alert",children:`Couldn't archive v${O.id}: ${dr(H.error)}`})]})}),t.jsx(c.AppDialog,{open:E!==null,onClose:()=>{re.isPending||R(null)},title:E?`Delete v${E.version.id}`:"",initialFocus:_,actions:t.jsxs(t.Fragment,{children:[t.jsx(p.Button,{ref:_,disabled:re.isPending,onClick:()=>R(null),children:"Cancel"}),t.jsx(p.Button,{variant:"contained",color:"error",loading:re.isPending,disabled:ie||de!==void 0,onClick:()=>E?.versions&&re.mutate({id:E.version.id,read:E.versions}),children:De?"Delete package":"Delete version"})]}),children:t.jsxs(p.Stack,{spacing:1.5,children:[ie&&E&&t.jsx(p.Typography,{variant:"body2",children:`Checking ${n}'s versions before deleting v${E.version.id}…`}),E&&!ie&&t.jsx(p.Typography,{variant:"body2",children:De?`v${E.version.id} is the only version of ${n}, so deleting it deletes the package. ${zs} This cannot be undone.`:`v${E.version.id} stops being served and its files are removed. ${zs} Links that name it stop working, and this cannot be undone.`}),de!==void 0&&E&&t.jsx(p.Alert,{severity:"warning",role:"alert",children:`v${E.version.id} can't be deleted now: ${de}.`}),re.isError&&E&&t.jsx(p.Alert,{severity:"error",role:"alert",children:`Couldn't delete v${E.version.id}: ${dr(re.error)}`})]})}),t.jsx(p.Snackbar,{open:P!==null,autoHideDuration:8e3,onClose:()=>F(null),anchorOrigin:{vertical:"bottom",horizontal:"center"},children:t.jsx(p.Box,{children:t.jsx(p.Alert,{severity:"error",variant:"filled",onClose:()=>F(null),children:P})})})]})}const Hy="README.malloynb",Uy=e=>!!e&&!e.includes("/")&&c.documentSlug(e)?.toLowerCase()==="readme";function Gy({onClickPackageFile:e,onOpenDocument:n,resourceUri:r,onEvent:o,onSelectVersion:i,onReplaceVersion:l}){const{apiClients:a,server:u,mutable:d}=q.useServer(),h=mt.useQueryClient(),y=e??(Y=>{window.location.href=Y}),{environmentName:b,packageName:x,versionId:v}=c.parseResourceUri(r),k=hc(b,x),{versions:C}=k,S=C.length>0,T=!S&&!k.isPending&&!k.isError,O=i??((Y,ae)=>y(`/${encodeURIComponent(b)}/${encodeURIComponent(x)}/${encodeURIComponent(Y)}`,ae)),M=n??((Y,ae)=>{const Fe=Y.mode==="edit"?c.reportEditRoute(b,x,Y.path):c.reportRoute(b,x,Y.path);ae?y(Fe,ae):y(Fe)}),[E,R]=j.useState(null),[P,F]=j.useState(!1),B=Fa(),D=c.useOptionalDocumentStorage()?.documentStorage,[_,V]=j.useState([]),[$,W]=j.useState({state:D?"pending":"ready"}),Z=j.useCallback(async()=>{if(!D)return;let Y;try{Y=await D.listWorkspaces(!1)}catch{W({state:"failed"});return}W({state:"ready",chosen:c.chooseWorkspace(Y)});const ae=[],Fe=c.draftKey(b,x,"");for(const Ve of Y.filter(St=>St.writeable))for(const St of await D.listDocuments(Ve))St.path.startsWith(Fe)&&ae.push({locator:St,where:Ve.description});V(ae)},[D,b,x]);j.useEffect(()=>{Z()},[Z]);const ne=Y=>Y.path.slice(c.draftKey(b,x,"").length),J=c.useQueryWithApiError({queryKey:["package",b,x,v],queryFn:()=>a.packages.getPackage(b,x,v,!1)}),H=c.useQueryWithApiError({queryKey:["package-agents",b,x,v],queryFn:()=>a.agents.listAgents(b,x,v)}),Q=c.useReportListing(b,x,v),re=c.useQueryWithApiError({queryKey:["models",b,x,v],queryFn:()=>a.models.listModels(b,x,v)}),z=c.useQueryWithApiError({queryKey:["databases",b,x,v],queryFn:()=>a.databases.listDatabases(b,x,v)}),se=c.useQueryWithApiError({queryKey:["data-apps",b,x,v],queryFn:async()=>{try{return await a.dataApps.listDataApps(b,x,v)}catch(Y){const ae=Y?.response?.status;if(ae===404||ae===void 0)return{data:[]};throw Y}}}).data?.data??[],ie=Q.reports.filter(Y=>!!Y.path),De=Ky(ie),de=new Set(ie.map(Y=>Y.path).filter(Y=>Y!==void 0)),ue=(re.data?.data??[]).slice().filter(Y=>!de.has(Y.path)).sort((Y,ae)=>Y.path.localeCompare(ae.path)),be=(z.data?.data??[]).slice().sort((Y,ae)=>Y.path.localeCompare(ae.path)),Me=$.state==="ready"?c.createRoute({authoritative:$.chosen?.authoritative===!0,mutable:d&&T,canStore:$.chosen?.writeable===!0,...v===void 0?{}:{versionId:v}}):void 0,te=Q.settled&&(re.isSuccess||re.isError),K=Me!==void 0&&te,he=K&&!B,we=j.useMemo(()=>{if(!K)return;const Y=[...Q.reports.flatMap(ae=>ae.path?[ae.path]:[]),...(re.data?.data??[]).flatMap(ae=>ae.path?[ae.path]:[])];if(Me==="storage"&&D&&$.state==="ready")return $.chosen?{route:Me,storage:D,workspace:$.chosen,environmentName:b,packageName:x,existing:Y}:void 0;if(Me==="package")return{route:Me,existing:Y,write:async(ae,Fe)=>{await a.models.updateModelSource(b,x,ae,{source:Fe})}}},[K,Me,D,$,b,x,a,Q.reports,re.data]),ge=J.data?.data?.description??"",pe=H.data?.data??[],ye=(ie.find(Y=>Y.path===Hy)??ie.find(Y=>Uy(Y.path)))?.path,Le=!Q.settled,st=S?t.jsx(mc,{environmentName:b,packageName:x,versions:C,...v!==void 0?{selectedVersionId:v}:{},onSelectVersion:O,...l?{onReplaceVersion:l}:{},onPackageDeleted:()=>y(`/${encodeURIComponent(b)}`),canManage:d}):null,ce=t.jsxs(p.Stack,{direction:"row",alignItems:"center",spacing:1.5,sx:{mb:.5},children:[t.jsx(p.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em"},children:x}),st]});if(J.isError){const Y=t.jsx(c.ApiErrorDisplay,{error:J.error,context:`${b} > ${x}`});return st?t.jsxs(p.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsx(p.Box,{sx:{mb:4},children:ce}),Y]}):Y}return t.jsxs(p.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsxs(p.Box,{sx:{mb:4},children:[ce,ge&&t.jsx(p.Typography,{variant:"body2",color:"text.secondary",children:ge})]}),t.jsx(cy,{warnings:J.data?.data?.warnings}),k.isError&&t.jsx(p.Box,{sx:{mb:4},children:t.jsx(p.Alert,{severity:"warning",action:t.jsx(p.Button,{color:"inherit",size:"small",onClick:k.refetch,children:"Retry"}),children:"Could not read this package's versions, so nothing that changes it is offered until they load."})}),Le&&t.jsx(c.Loading,{text:"Loading package..."}),we&&t.jsx(ac,{open:P,layout:"linear",environmentName:b,packageName:x,...v!==void 0?{versionId:v}:{},models:ue.map(Y=>Y.path).filter(Y=>typeof Y=="string"&&Y.endsWith(".malloy")&&!de.has(Y)),modelsLoading:re.isPending,...re.isError?{modelsError:re.error}:{},onRetryModels:()=>void re.refetch(),target:we,...o?{onEvent:o}:{},onClose:()=>F(!1),onCreated:Y=>{F(!1),c.invalidateReportQueries(h),h.invalidateQueries({queryKey:["models"]}),M({path:Y.path,layout:Y.layout,slug:Y.slug,mode:"edit"})}}),!Le&&t.jsxs(t.Fragment,{children:[Q.isError&&t.jsx(p.Box,{sx:{mb:4},children:t.jsx(p.Alert,{severity:"warning",action:t.jsx(p.Button,{color:"inherit",size:"small",onClick:()=>void Q.refetch(),children:"Retry"}),children:"Could not list this package's reports, so any it has are missing from this page."})}),(De.length>0||K)&&t.jsxs(Nt,{title:"Reports",count:De.length,...he?{action:t.jsx(c.AddButton,{label:"Report",onClick:()=>F(!0)})}:{},children:[De.length===0&&t.jsx(Ws,{label:"No reports yet",...he?{action:{label:"Add report",onClick:()=>F(!0)}}:{}}),De.map(Y=>t.jsx(Dn,{type:Y.layout==="grid"?"dashboard":"report",label:Y.label,rightLabel:Y.layout,...Y.secondary===void 0?{}:{description:Y.secondary},onClick:ae=>Y.path.endsWith(".malloynb")?y(`/${b}/${x}/${Y.path}`,ae):M({path:Y.path,layout:Y.layout,slug:Y.slug,mode:"view"},ae)},Y.path))]}),T&&_.length>0&&t.jsx(Nt,{title:"Drafts",count:_.length,children:_.map(({locator:Y,where:ae})=>t.jsx(Dn,{type:Y.type==="grid"?"dashboard":"report",label:ne(Y),rightLabel:ae,onClick:Fe=>M({path:ne(Y),layout:Y.type,slug:c.documentSlug(ne(Y))??"",mode:"edit"},Fe),trailingAction:t.jsx(p.Tooltip,{title:"Delete this draft",children:t.jsx(p.IconButton,{size:"small","aria-label":`Delete draft ${ne(Y)}`,onClick:Fe=>{Fe.stopPropagation(),D?.deleteDocument(Y).then(Z)},children:t.jsx(c.DeleteOutlineIcon,{fontSize:"small"})})})},`${Y.workspace}:${Y.path}`))}),se.length>0&&t.jsx(Nt,{title:"Apps",count:se.length,children:se.map(Y=>{const ae=!!Y.title&&Y.title!==Y.path,Fe=`${Ka(u)}${Y.resource}`;return t.jsx(Dn,{type:"dataApp",label:ae?Y.title:Y.path,rightLabel:ae?Y.path:void 0,onClick:Ve=>{e?e(`/${b}/${x}/data-apps/${Y.path}`,Ve):Ve&&(Ve.metaKey||Ve.ctrlKey)?window.open(Fe,"_blank"):window.location.href=Fe},trailingAction:t.jsx(p.Tooltip,{title:"Open standalone in new tab",children:t.jsx(p.IconButton,{size:"small",href:Fe,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",onClick:Ve=>Ve.stopPropagation(),sx:{color:"text.secondary"},children:t.jsx(Ya,{fontSize:"small"})})})},Y.path)})}),t.jsxs(Nt,{title:"Models",count:ue.length,children:[ue.map(Y=>t.jsx(Dn,{type:"model",label:Y.path,onClick:ae=>y(`/${b}/${x}/${Y.path}`,ae)},Y.path)),ue.length===0&&t.jsx(Ws,{label:"No models"})]}),pe.length>0&&t.jsx(Nt,{title:"Agents",count:pe.length,description:"Declared in publisher.json. Name one in an agent session to work as it. Schedules are listed only; nothing runs them yet.",children:pe.map(Y=>t.jsx(Yy,{agent:Y},Y.name))}),t.jsxs(Nt,{title:"Data",count:be.length,children:[be.map(Y=>t.jsx(Dn,{type:"data",label:Y.path,rightLabel:Y.info?uc(Y.info.rowCount):"Unreadable",onClick:()=>R(Y)},Y.path)),be.length===0&&t.jsx(Ws,{label:"No data files"})]}),t.jsx(gl,{resourceUri:r,versioned:!T}),ye&&t.jsx(p.Box,{sx:{mt:6},children:t.jsx(ic,{resourceUri:c.encodeResourceUri({environmentName:b,packageName:x,versionId:v}),path:ye,onLinkNavigate:y})})]}),t.jsx(Ny,{database:E,onClose:()=>R(null)})]})}function Dn({type:e,label:n,description:r,rightLabel:o,onClick:i,trailingAction:l}){return t.jsx(rs,{icon:t.jsx(cc,{type:e}),tint:lc[e],label:n,mono:!0,...r===void 0?{}:{description:r},...o===void 0?{}:{rightLabel:o},...i===void 0?{}:{onClick:i},...l===void 0?{}:{trailingAction:l}})}function Yy({agent:e}){return t.jsxs(t.Fragment,{children:[t.jsx(Dn,{type:"agent",label:e.name??"",...e.description?{description:e.description}:{},...e.model&&e.model!=="inherit"?{rightLabel:e.model}:{}}),(e.schedules??[]).map(n=>{const r=uo(n.cron??"");return t.jsxs(p.Typography,{variant:"caption",color:"text.secondary",sx:{display:"block",ml:6,mb:.5},children:[r.valid?r.description:n.cron," (UTC), task"," ",n.task,". Not run yet."]},`${n.cron}|${n.task}`)})]})}function Ky(e){const n=e.map(o=>({path:o.path??"",layout:c.listedLayout(o),slug:c.documentSlug(o.path)??o.path??"",title:o.title})),r=new Map;for(const o of n)r.set(o.slug,(r.get(o.slug)??0)+1);return n.map(({title:o,...i})=>{const l=!!o&&o!==i.slug&&o!==i.path,a=(r.get(i.slug)??0)>1,u=l?o:i.path.endsWith(".malloynb")?i.path:i.slug;return{...i,label:u,secondary:u!==i.path&&(l||a||i.path.includes("/"))?i.path:void 0}}).sort((o,i)=>o.label.localeCompare(i.label)||o.path.localeCompare(i.path))}function Ws({label:e,action:n}){return t.jsxs(p.Stack,{direction:"row",sx:{alignItems:"center",gap:1,py:1},children:[t.jsx(p.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:e}),n&&t.jsx(p.Button,{size:"small",onClick:n.onClick,children:n.label})]})}const Da=/^publisher:document:(dashboard|notebook):(.+)$/;function Qy(e,n){const r=[];for(let o=0;o<e.length;o++){const i=e.key(o);i!==null&&Da.test(i)&&r.push(i)}for(const o of r){const[,i,l]=Da.exec(o),a=e.getItem(o);a!==null&&n(l,c.layoutOfKind(i),a)&&e.removeItem(o)}}const qs={name:"Local",description:"Stored in this browser only",writeable:!0},ro="publisher:report:",cn=e=>`${ro}${e}`;function hr(e){const n=localStorage.getItem(e);if(n!==null)try{const r=JSON.parse(n);if(typeof r.content=="string"&&(r.type==="grid"||r.type==="linear"))return{type:r.type,content:r.content}}catch{}}const Bs=(e,n)=>localStorage.setItem(cn(e),JSON.stringify(n));class Zy{migrated=!1;migrate(){this.migrated||(this.migrated=!0,Qy(localStorage,(n,r,o)=>hr(cn(n))!==void 0?!1:(Bs(n,{type:r,content:o}),!0)))}async listWorkspaces(n){return[qs]}async listDocuments(n,r){if(n.name!==qs.name)return[];this.migrate();const o=[];for(let i=0;i<localStorage.length;i++){const l=localStorage.key(i);if(l===null||!l.startsWith(ro))continue;const a=hr(l);a&&(r===void 0||a.type===r)&&o.push({workspace:qs.name,type:a.type,path:l.slice(ro.length)})}return o}async getDocument(n){this.migrate();const r=hr(cn(n.path));if(r===void 0)throw Vs(n);return r.content}async getDocumentType(n){this.migrate();const r=hr(cn(n.path));if(r===void 0)throw Vs(n);return r.type}async saveDocument(n,r){this.migrate(),Bs(n.path,{type:n.type,content:r})}async deleteDocument(n){if(this.migrate(),hr(cn(n.path))===void 0)throw Vs(n);localStorage.removeItem(cn(n.path))}async moveDocument(n,r){const o=await this.getDocument(n);Bs(r.path,{type:r.type,content:o}),r.path!==n.path&&localStorage.removeItem(cn(n.path))}}function Vs(e){return new c.DocumentNotFoundError(`No report at ${e.workspace}/${e.path}`)}async function Xy(e,n,r,o){const i=c.chooseWorkspace(await e.listWorkspaces(!1));if(!i)return;const l=c.draftKey(n,r,o);if(e.getDocumentType)try{return await e.getDocumentType({workspace:i.name,path:l})}catch(a){if(c.isDocumentNotFound(a))return;throw a}return(await e.listDocuments(i)).find(a=>a.path===l)?.type}function Jy(e,n,r,o=!0){const i=c.useOptionalDocumentStorage()?.documentStorage,l=o&&i!==void 0,[a,u]=j.useState(),d=c.draftKey(e,n,r);return j.useEffect(()=>{if(!l||!i)return;let h=!1;return Xy(i,e,n,r).catch(()=>{}).then(y=>{h||u({key:d,layout:y})}),()=>{h=!0}},[l,i,e,n,r,d]),l?a?.key===d?{layout:a.layout,settled:!0}:{layout:void 0,settled:!1}:{layout:void 0,settled:!0}}function pc(e){const{environmentName:n,packageName:r}=c.parseResourceUri(e.resourceUri);if(!n||!r)throw new Error("Environment and Package name must be provided for query embedding.");return JSON.stringify({...e})}function ex({embeddedQueryResult:e}){const{query:n,sourceName:r,queryName:o,resourceUri:i,height:l}=JSON.parse(e),{modelPath:a}=c.parseResourceUri(i);if(!a||!n&&(!o||!r)||typeof a!="string")throw new Error("Invalid embedded query result: "+e);return t.jsx(gc,{query:n,sourceName:r,queryName:o,resourceUri:i,height:l})}function gc({query:e,sourceName:n,queryName:r,resourceUri:o,height:i=400}){const{modelPath:l,environmentName:a,packageName:u,versionId:d}=c.parseResourceUri(o);if(!a||!u)throw new Error("No environment or package name provided. A resource URI must be provided.");const h=c.useQueryResult({environmentName:a,packageName:u,modelPath:l,versionId:d,query:e,sourceName:n,queryName:r});return t.jsx(c.ResultPanel,{state:h,context:`${a} > ${u} > ${l}`,maxHeight:i})}function yc(e,n,r="grid"){const o=n.filter(l=>!!l.path).filter(l=>c.documentSlug(l.path)===e),i=o.filter(l=>c.listedLayout(l)===r);return i.length===1?{found:c.locatedReport(i[0])}:o.length===1?{found:c.locatedReport(o[0])}:o.length===0?{missing:!0}:{ambiguous:o.map(l=>l.path).sort()}}const tx=/^(dashboards|notebooks)\/([^/]+)$/;function nx(e){const n=tx.exec(e);if(n)return{name:n[2],prefer:n[1]==="dashboards"?"grid":"linear"}}const rx=(e,n,r,o)=>`/${e}/${n}/${r}s/${encodeURIComponent(o)}`;function sx({kind:e,slug:n,reports:r}){const o=yc(n,r,c.layoutOfKind(e));return"found"in o?o.found:void 0}function ox(e,n){return`${e}:${n}`}function hn(e){return ox(e.source,e.filterName??e.dimensionName)}function ix(e){const n=new Map;for(const r of e){const o=`${r.source}|${r.model}`,i=n.get(o)||[];i.push(r),n.set(o,i)}return n}function ax(e,n,r,o){const i=n.filter(h=>(h.filterType==="Star"||h.filterType==="MinMax"||h.filterType==="DateMinMax")&&!h.values);if(i.length===0)return"";const a=[...new Set(i.map(h=>h.dimensionName))].map(h=>`\`${h}\``).join(", "),u=o?.filter(h=>h.source===e)||[],d=u.length>0?u.map(h=>os(`\`${h.dimensionName}\``,h)).filter(h=>h.length>0).join(" and "):"";return`
|
|
38
|
+
`)}const xy=c.createSvgIcon(t.jsx("path",{d:"M9.4 16.6 4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0 4.6-4.6-4.6-4.6L16 6l6 6-6 6z"}));function vy({cell:e,resourceUri:n,showCopyLink:r,maxResultSize:o,isExecuting:i,pendingRerun:l,onNavigate:a,onDrillSelf:u,canDrillSelf:d,onDrillNavigate:h,givens:y,givenSpecs:b}){const[x,v]=T.useState(!1),[k,C]=T.useState(!1),[S,j]=T.useState(),[M,O]=T.useState(!1),{modelPage:E,isLoadingStatus:$}=q.useServer(),P=!$&&E!=="viewer",[A,B]=T.useState(""),{environmentName:D,packageName:_,modelPath:V}=c.parseResourceUri(n),R={environmentName:D,packageName:_,sourcePath:V,onNavigate:a},{drill:W,drillMenu:Z}=oo({onNavigate:h,onSelf:u,canSelf:d}),ne=/import\s*\{([^}]+)\}\s*from\s*['"`][^'"`]+['"`]/,J=/import\s*(?:\{[^}]*\}\s*from\s*)?['"`]([^'"`]+)['"`]/,H=!!e.text&&(ne.test(e.text)||J.test(e.text)),Q=()=>{if(!e.newSources||e.newSources.length===0)return 0;let ie=[],De="";if(e.text){const de=e.text.match(ne);de&&(ie=de[1].split(",").map(be=>be.trim()));const ue=e.text.match(J);ue&&(De=ue[1].trim())}for(let de=0;de<e.newSources.length;de++)try{const ue=JSON.parse(e.newSources[de]);if(ie.length>0&&ie.includes(ue.name)||De&&De===ue.path)return de}catch{continue}return 0},re=T.useMemo(()=>e.newSources&&e.newSources.length>0?{sourceInfos:e.newSources,resource:n,givens:b}:void 0,[e.newSources,n,b]),{mode:z}=q.usePublisherTheme();T.useEffect(()=>{e.type==="code"&&To(yy(e),"malloy",z).then(ie=>{j(ie)})},[e,z]);const oe=()=>{const ie=window.location.href;navigator.clipboard.writeText(ie).then(()=>B("URL copied to clipboard!")).catch(()=>B("Failed to copy URL"))},se=t.jsx(c.AppDialog,{open:x,onClose:()=>v(!1),title:"Malloy code",maxWidth:"lg",showClose:!0,children:t.jsx(m.Box,{sx:ie=>({border:`1px solid ${ie.palette.divider}`,borderRadius:"8px",padding:"16px",fontFamily:q.MONO_FONT_FAMILY,fontSize:"14px",lineHeight:"1.5",overflow:"auto",maxHeight:"70vh",backgroundColor:ie.palette.background.paper,color:ie.palette.text.primary}),children:t.jsx("pre",{className:"code-display",style:{margin:0},dangerouslySetInnerHTML:{__html:S}})})});return e.type==="markdown"&&t.jsx(m.Box,{children:t.jsxs(c.TextTileFrame,{children:[r?t.jsxs(m.Stack,{direction:"row",alignItems:"flex-start",justifyContent:"space-between",children:[t.jsx(c.Prose,{variant:"document",links:R,children:e.text}),t.jsx(m.Tooltip,{title:"Copy link",children:t.jsx(m.IconButton,{"aria-label":"Copy link",onClick:oe,sx:{color:"text.secondary",mt:"18px"},children:t.jsx(ho,{sx:{fontSize:"24px"}})})})]}):t.jsx(c.Prose,{variant:"document",links:R,children:e.text}),t.jsx(m.Snackbar,{open:A!=="",autoHideDuration:6e3,onClose:()=>B(""),message:A})]})})||e.type==="code"&&t.jsxs(m.Box,{children:[e.newSources&&e.newSources.length>0&&t.jsx(m.Stack,{sx:{flexDirection:"column",gap:"8px",marginBottom:"2px"},children:t.jsx(q.CleanMetricCard,{sx:{position:"relative",padding:"0"},children:t.jsxs(m.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",paddingLeft:"24px",paddingRight:"8px"},children:[S&&t.jsx("span",{dangerouslySetInnerHTML:{__html:S},style:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"14px",flex:1,marginRight:"8px"}}),H&&P&&t.jsx(c.FloatingIconButton,{"aria-label":"Data sources",sx:{flexShrink:0},onClick:()=>O(!0),children:t.jsx(c.SearchIcon,{})})]})})}),t.jsx(Io,{open:M&&P,onClose:()=>O(!1),title:"Data Sources",hasValidImport:H,resourceUri:n,data:re,initialSelectedSourceIndex:Q(),startingGivens:y}),se,t.jsx(ic,{open:k,onClose:()=>C(!1),result:e.result||"",title:"Results",drill:W}),i&&!e.result&&!e.error&&!H&&!(e.newSources&&e.newSources.length>0)&&t.jsx(c.TileCard,{children:t.jsx(m.Box,{sx:{display:"flex",justifyContent:"center",alignItems:"center",minHeight:200},children:t.jsx(m.CircularProgress,{size:32})})}),!e.result&&e.error&&t.jsx(c.ErrorDetailAlert,{summary:"This cell could not be run.",detail:e.error}),e.result&&l&&t.jsx(m.LinearProgress,{"aria-label":"Re-run pending",sx:{mb:1,height:2,borderRadius:1}}),e.result&&t.jsxs(c.TileCard,{children:[t.jsx(c.TileHeading,{title:"",action:t.jsxs(m.Stack,{direction:"row",sx:{gap:.5,mt:"-4px"},children:[t.jsx(c.FloatingIconButton,{"aria-label":"Malloy code",onClick:ie=>{ie.stopPropagation(),v(!0)},children:t.jsx(xy,{})}),t.jsx(c.FloatingIconButton,{"aria-label":"Expand results",onClick:()=>C(!0),children:t.jsx(c.SearchIcon,{})})]})}),t.jsx(c.ResultContainer,{result:e.result,maxHeight:c.NOTEBOOK_CELL_MAX_HEIGHT,maxResultSize:o,drill:W}),Z]})]})}function by({ready:e,lastRunKey:n,pendingKey:r,runKey:o,documentKey:i}){if(!e)return{cancelPending:r!==void 0,dispatch:"none"};const l=r!==void 0&&r!==o;if(n===o)return{cancelPending:l,dispatch:"none"};if(r===o)return{cancelPending:l,dispatch:"none"};const a=n===null||!n.startsWith(`${i}|`);return{cancelPending:l,dispatch:a?"now":"settle"}}const wy=4;function Sy(e){const n=e?.response?.data?.message;return typeof n=="string"&&n!==""?n:e instanceof Error&&e.message!==""?e.message:"The server did not say why."}function ky({resourceUri:e,maxResultSize:n=0,givens:r,onGivensChange:o,onNavigate:i,onDrillNavigate:l,actions:a,notebook:u,runCell:d}){const{environmentName:h,packageName:y,versionId:b,modelPath:x}=c.parseResourceUri(e),[v,k]=T.useState([]),[C,S]=T.useState(!1),[j,M]=T.useState(!1),O=T.useRef(void 0),[E,$]=T.useState(null),P=lc(u),A=u.autorun!==!1,B=c.useReportEvents(),D=c.useDocumentControls({specs:P,loaded:!0,startingValues:u.startingGivens,params:r,onGivensChange:o,documentKey:e,autorun:A,environmentName:h,packageName:y,modelPath:x,versionId:b,documentName:x}),{applied:_,declaredTypes:V,canSelf:R,onSelf:W}=D,Z=T.useCallback(ue=>{const be=c.givensToRequest(ue,V);return Object.keys(be).length>0?JSON.stringify(be):void 0},[V]),ne=T.useMemo(()=>c.givensToParams(_,V),[_,V]),J=T.useRef(0),H=T.useRef(null),Q=T.useRef(null),re=T.useRef(void 0);T.useEffect(()=>()=>{H.current?.abort(),Q.current=null,clearTimeout(re.current?.timer),re.current=void 0},[]);const z=T.useCallback(async(ue=new Map)=>{if(!u.notebookCells)return;const be=++J.current;H.current?.abort();const Oe=new AbortController;H.current=Oe,k(u.notebookCells.map(te=>({...te}))),S(!0),$(null);try{const te=[];for(let he=0;he<u.notebookCells.length;he++){const we=u.notebookCells[he];if(!gy(we))continue;const ge=he,me=async()=>{try{const ye=await d({cell:we,givens:ue,declaredTypes:V,signal:Oe.signal});if(J.current!==be)return;const Le=ye.result;k(st=>{const ce=[...st];return ce[ge]||(ce[ge]={...we}),ce[ge]={...ce[ge],result:Le},ce})}catch(ye){if(Oe.signal.aborted||J.current!==be)return;B.emit({type:"report.query_failed",tile:ge,category:c.failureCategory(ye)}),B.listening||console.error(`Error executing cell ${ge}:`,ye);const Le=Sy(ye);k(st=>{const ce=[...st];return ce[ge]||(ce[ge]={...we}),ce[ge]={...ce[ge],error:Le},ce})}};te.push(me)}const K=[];for(const he of te){const we=he().then(()=>{K.splice(K.indexOf(we),1)});K.push(we),K.length>=wy&&await Promise.race(K)}await Promise.all(K)}catch(te){if(Oe.signal.aborted||J.current!==be)return;B.emit({type:"report.query_failed",category:c.failureCategory(te)}),B.listening||console.error("Error executing notebook cells:",te),$(te)}finally{J.current===be&&(S(!1),H.current=null)}},[u,V,d,B]),oe=T.useRef(0),se=T.useRef(void 0);se.current!==u&&(se.current=u,oe.current+=1);const ie=oe.current;T.useEffect(()=>{const ue=`${e}|${ie}`,be=`${ue}|${Z(_)??""}`;O.current!==void 0&&O.current!==ue&&(H.current?.abort(),H.current=null),O.current=ue;const Oe=by({ready:!!u.notebookCells,lastRunKey:Q.current,pendingKey:re.current?.key,runKey:be,documentKey:ue});if(Oe.cancelPending&&(clearTimeout(re.current?.timer),re.current=void 0,M(!1)),Oe.dispatch==="none")return;const te=()=>{re.current=void 0,M(!1),Q.current=be,z(_)};if(Oe.dispatch==="now"){te();return}M(!0),re.current={key:be,timer:setTimeout(te,c.GIVEN_SETTLE_MS)}},[u,ie,e,_,Z,z]);const De=v.length>0?v:u.notebookCells||[],de=0;return t.jsxs(c.ReportPage,{layout:"linear",header:a?t.jsx(m.Stack,{direction:"row",sx:{justifyContent:"flex-end"},children:a}):null,controls:D.panel.givens.length>0?t.jsx(c.StickyControls,{children:t.jsx(c.GivensPanel,{...D.panel,layout:"bar"})}):void 0,children:[De.map((ue,be)=>t.jsx(vy,{cell:ue,showCopyLink:be===de,resourceUri:e,maxResultSize:n,isExecuting:C,givens:ne,givenSpecs:P,pendingRerun:j,onNavigate:i,onDrillNavigate:l,onDrillSelf:P.length>0?W:void 0,canDrillSelf:R},be)),E&&t.jsx(c.ApiErrorDisplay,{error:{message:E.message,status:500,name:"ExecutionError"},context:"Notebook Execution"})]})}function Cy({environmentName:e,packageName:n,versionId:r,path:o,notebook:i,...l}){const{apiClients:a,server:u}=q.useServer(),d=T.useCallback(async({cell:h,givens:y,declaredTypes:b,signal:x})=>{const v=h.runQuery;if(v===void 0)return{};x.throwIfAborted();const k=c.givensToRequest(y,b),C={environmentName:e,packageName:n,versionId:r,modelPath:o,query:v,givens:Object.keys(k).length>0?k:void 0},S=[...c.queryResultKey(C),u],j=()=>q.globalQueryClient.fetchQuery({queryKey:S,queryFn:({signal:O})=>c.requestQueryResult(a,C,O),...q.CHART_RESULT_QUERY_OPTIONS}),M=()=>void q.globalQueryClient.cancelQueries({queryKey:S,exact:!0});x.addEventListener("abort",M,{once:!0});try{let O;try{O=await j()}catch(E){if(!pt.isCancelledError(E)||x.aborted)throw E;O=await j()}return{result:O.data.result}}finally{x.removeEventListener("abort",M)}},[a,u,e,n,o,r]);return t.jsx(ky,{...l,resourceUri:c.encodeResourceUri({environmentName:e,packageName:n,modelPath:o,versionId:r}),notebook:i,runCell:d})}function cc({resourceUri:e,path:n,givens:r,onGivensChange:o,onNavigate:i,onLinkNavigate:l,height:a,maxResultSize:u,onEvent:d,chrome:h,manifestStaleTime:y,actions:b,rowsActions:x}){const v=c.parseResourceUri(e),{apiClients:k}=q.useServer(),C=v.environmentName??"",S=v.packageName??"",j=v.versionId,M=!!v.environmentName&&!!v.packageName,{data:O,isSuccess:E,isError:$,error:P}=c.useQueryWithApiError({...c.reportQueryOptions(k,{environmentName:C,packageName:S,path:n,versionId:j},y),enabled:M&&n!==""}),A=O?.layout,B=c.useReportEmitter({path:n,layout:A},d),D=`${e}|${n}`,_=T.useRef(void 0),V=T.useRef({key:D,at:c.now()});V.current.key!==D&&(V.current={key:D,at:c.now()}),T.useEffect(()=>{_.current!==D&&(M?$?(_.current=D,B.emit({type:"report.load_failed",surface:"view",category:c.failureCategory(P)})):E&&O&&(_.current=D,B.emit({type:"report.opened",surface:"view",from:"package",tiles:O.tiles?.length??O.notebook?.notebookCells?.filter(ne=>ne.type==="code"&&ne.runQuery!==void 0).length??0,durationMs:c.now()-V.current.at})):(_.current=D,B.emit({type:"report.load_failed",surface:"view",category:"invalid"})))},[D,M,$,P,E,O,B]);const R=T.useCallback((ne,J)=>{const H=i?.(ne,J);H&&B.emit({type:"report.drill",to:"report",outcome:H})},[i,B]),W=i?R:void 0;if(!M)return t.jsxs(m.Alert,{severity:"error",children:["A report resource URI must name an environment and a package. Received: ",e]});if($)return t.jsx(c.ApiErrorDisplay,{context:`${C} > ${S} > ${n}`,error:P});if(!E||!O)return t.jsx(c.Loading,{text:c.LOADING_COPY.opening("report")});const Z=O.notebook?.format==="malloynb"?t.jsx(Cy,{environmentName:C,packageName:S,versionId:j,path:n,notebook:O.notebook,givens:r,onGivensChange:o,onNavigate:l,onDrillNavigate:W,maxResultSize:u,...b!==void 0?{actions:b}:{}}):t.jsx(Ga,{manifest:O,environmentName:C,packageName:S,versionId:j,documentName:n,givens:r,onGivensChange:o,onNavigate:W,...l?{onLinkNavigate:l}:{},height:a,maxResultSize:u,chrome:h,...b!==void 0?{actions:b}:{},...x!==void 0?{rowsActions:x}:{}});return t.jsx(c.ReportEventsContext.Provider,{value:B,children:Z})}function uc({open:e,layout:n,kind:r,allowLayoutChange:o,allowKindChange:i,environmentName:l,packageName:a,versionId:u,models:d,modelsLoading:h=!1,modelsError:y,onRetryModels:b,target:x,savedAs:v,onClose:k,onCreated:C,onEvent:S}){const j=n??(r?c.layoutOfKind(r):"linear"),M=o??i??!0,[O,E]=T.useState(j),[$,P]=T.useState(void 0),[A,B]=T.useState(""),[D,_]=T.useState(""),[V,R]=T.useState(""),W=T.useRef(null),[Z,ne]=T.useState(""),[J,H]=T.useState(!1),[Q,re]=T.useState(!1),[z,oe]=T.useState(!1),[se,ie]=T.useState(void 0),De=y!=null,{choices:de,isLoading:ue,isSuccess:be,failed:Oe,retry:te,canRetry:K}=c.useDocumentChoices({environmentName:l,packageName:a,...u!==void 0?{versionId:u}:{},models:d,enabled:e&&d.length>0}),he=T.useMemo(()=>de.get(A)??[],[de,A]),we=T.useMemo(()=>new Map([...de.entries()].flatMap(([pe,He])=>He.map(vt=>[Ps(pe,vt.source,vt.view),{model:pe,source:vt.source,view:vt.view}]))),[de]),ge=T.useMemo(()=>{const pe=de.size>1;return[...de.entries()].flatMap(([He,vt])=>{const Ce=new Map;for(const Fe of vt)Ce.set(Fe.source,[...Ce.get(Fe.source)??[],Fe]);return[...Ce.entries()].map(([Fe,Ie])=>({key:`${He}::${Fe}`,label:Fe,ariaLabel:`${Fe} in ${He}`,...pe||Ie[0]?.sourceDescription?{detail:[pe?He:void 0,Ie[0]?.sourceDescription].filter(Boolean).join(" · ")}:{},entries:Ie.map(We=>({key:Ps(He,We.source,We.view),name:We.view,title:We.description??c.readableName(We.view),...We.chart?{chart:We.chart}:{}}))}))})},[de]),me=pe=>{const He=we.get(pe);He&&(B(He.model),_(`${He.source}::${He.view}`))},ye=he.find(pe=>`${pe.source}::${pe.view}`===D),Le=ye?Ps(A,ye.source,ye.view):void 0,st=Ty(ye,250);T.useEffect(()=>{e&&E(j)},[e,j]),T.useEffect(()=>{if(!e)return;const pe=[...de.keys()];A===""&&pe.length>0&&B(pe[0])},[e,de,A]),T.useEffect(()=>{!e||he.length===0||D!==""||_(`${he[0].source}::${he[0].view}`)},[e,he,D]),T.useEffect(()=>{!e||J||ye===void 0||ne(c.readableName(ye.view))},[e,J,ye]),T.useEffect(()=>{e||(B(""),_(""),R(""),ne(""),H(!1),P(void 0),re(!1),ie(void 0))},[e]);const ce=T.useMemo(()=>{if(Z.trim()!=="")for(let pe=1;pe<=c.MAX_SLUG_ATTEMPTS;pe++){const He=c.reportPathForTitle(Z,pe);if(!x.existing?.includes(He))return He}},[Z,x]),Y=$?.trim(),ae=Y===void 0||Y===""?void 0:Y.endsWith(".malloy")?Y:`${Y}.malloy`,Re=ae??ce,Ve=ae===void 0?void 0:c.reportPathProblem(ae)??(x.existing?.includes(ae)?`${ae} already exists; choose another location.`:void 0),Ee=(ye===void 0?void 0:c.newDocumentProblem({title:Z,modelPath:A,source:ye.source,view:ye.view}))??(Z.trim()!==""&&Re===void 0?"No free file name for this title; choose another.":void 0),at=Ee!==void 0&&(Q||Z.trim()!==""),yt=h||ue,{theme:xt}=q.usePublisherTheme(),Mt=xt.ui,mt=c.edgeColor(xt.cardBorder),Ye=de.size===0&&(De||Oe.length>0),fe=yt?"Loading the model":Ye?"Couldn't read the model to start from":de.size===0?"Nothing in the model to start from yet":ye===void 0?"Pick what to start from":void 0,Ke="report",ze=z?`Creating ${Ke}…`:`Create ${Ke}`,lt=D!==""&&ye===void 0&&he.length>0,ct=async()=>{if(!(fe!==void 0||ye===void 0||z)){if(Ee!==void 0||Ve!==void 0){re(!0);return}oe(!0),ie(void 0);try{const pe=await c.createDocument({layout:O,...ae!==void 0?{path:ae}:{},document:{title:Z,modelPath:A,source:ye.source,view:ye.view},target:x,...S?{onEvent:S}:{}});C(pe)}catch(pe){const He=pe.response?.data?.message;ie(He??(pe instanceof Error?pe.message:String(pe)))}finally{oe(!1)}}},Qe=pe=>t.jsx(m.Button,{color:"inherit",size:"small",onClick:pe,children:"Retry"});return t.jsx(c.AppDialog,{className:`${c.reportClasses.dialog} ${c.reportClasses.newReportDialog}`,maxWidth:"md",initialFocus:W,open:e,onClose:z?()=>{}:k,title:`New ${Ke}`,description:"A report is a Malloy file in the package that lays out text and queries. Pick what its first query shows; the rest is the builder.",actions:t.jsxs(t.Fragment,{children:[t.jsx(m.Button,{onClick:k,disabled:z,children:"Cancel"}),t.jsx(m.Tooltip,{title:z?"":fe??"",children:t.jsx("span",{children:t.jsx(m.Button,{variant:"contained",disabled:z||fe!==void 0,"aria-label":!z&&fe!==void 0?`${ze}: ${fe}`:ze,onClick:()=>void ct(),children:ze})})})]}),children:t.jsxs(m.Stack,{sx:{gap:1.5},children:[De?t.jsx(m.Alert,{severity:"error",action:b&&so.canRetryRequest(y)?Qe(b):void 0,children:"Couldn't read this package's models, so no view is listed to start from."}):d.length===0?!h&&t.jsxs(m.Alert,{severity:"info",children:["This package has no models yet. Add a .malloy file that declares a source with a view, then create a ",Ke," from it."]}):Oe.length>0?t.jsxs(m.Alert,{severity:"warning",action:K?Qe(te):void 0,children:["Couldn't read ",Oe.join(", "),", so nothing from"," ",Oe.length===1?"it":"them"," is listed."]}):be&&de.size===0&&t.jsxs(m.Alert,{severity:"info",children:["A ",Ke," starts from a view of a source, and no model in this package declares one yet. Add a view to a source in a model file and this list fills in."]}),t.jsxs(m.Box,{sx:{mx:-3,mb:-1,borderTop:`1px solid ${mt}`,borderBottom:`1px solid ${mt}`,display:"grid",gridTemplateColumns:{xs:"1fr",md:"320px minmax(0, 1fr)"},height:{md:500}},children:[t.jsx(m.Box,{sx:{display:"flex",flexDirection:"column",minHeight:0,borderRight:{md:`1px solid ${mt}`},maxHeight:{xs:280,md:"none"}},children:t.jsx(c.ViewPicker,{groups:ge,query:V,onQuery:R,picked:Le,onPick:me,onTake:pe=>{me(pe)},searchRef:W,disabled:z,empty:t.jsx(m.Typography,{variant:"body2",sx:{color:"text.secondary",p:2},children:yt?"Reading the package's models…":"Nothing to start from."})})}),t.jsxs(m.Box,{sx:pe=>({p:2.5,display:"flex",flexDirection:"column",gap:2,minHeight:0,overflowY:"auto",bgcolor:`color-mix(in srgb, ${pe.palette.text.primary} 3%, ${pe.palette.background.paper})`}),children:[M&&t.jsxs(m.Box,{children:[t.jsx(Ea,{children:"Layout"}),t.jsx(m.Box,{role:"radiogroup","aria-label":"Layout",sx:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:1},children:["linear","grid"].map(pe=>t.jsx(Oy,{layout:pe,checked:O===pe,disabled:z,onPick:()=>E(pe)},pe))}),t.jsx(m.Typography,{variant:"caption",component:"p",sx:{color:"text.secondary",mt:.75},children:"Switch it any time in the builder."})]}),t.jsxs(m.Box,{children:[t.jsx(Ea,{children:"First query"}),t.jsx(m.Box,{role:"region","aria-label":"Preview",sx:pe=>({height:200,display:"flex",position:"relative",overflow:"hidden",borderRadius:Mt.radius.tile,border:`1px solid ${mt}`,bgcolor:pe.palette.background.paper,"&::after":{content:'""',position:"absolute",left:0,right:0,bottom:0,height:40,pointerEvents:"none",background:`linear-gradient(to bottom, transparent, ${pe.palette.background.paper})`}}),children:ye&&st?t.jsx(m.Box,{sx:{flex:1,minWidth:0,px:2,pt:1.5},children:t.jsx(c.DashboardTile,{environmentName:l,packageName:a,...u!==void 0?{versionId:u}:{},modelPath:A,tile:`${st.source} -> ${st.view}`,label:Z.trim()||c.readableName(st.view),borderless:!0,givens:jy,declaredTypes:My,height:180})}):t.jsx(m.Typography,{variant:"body2",sx:{color:"text.secondary",m:"auto"},children:lt?"What you picked is no longer in this model; pick something else.":"Pick what to start from."})}),t.jsx(m.Typography,{variant:"caption",component:"p",sx:{color:"text.secondary",mt:.75},children:"More are added in the builder."})]}),t.jsx(m.TextField,{size:"small",label:"Title",value:Z,disabled:z,onChange:pe=>{H(!0),ne(pe.target.value)},InputLabelProps:{shrink:!0},inputProps:{"aria-label":"Report title"},error:at,helperText:at?Ee:x.route==="package"?"Names the file too, unless you type a location.":v??`Saved as a new ${Ke} in the host's store, and opened in the builder.`}),t.jsx(m.TextField,{size:"small",label:"Location",value:$??ce??"",placeholder:"report.malloy",disabled:z,onChange:pe=>P(pe.target.value),InputLabelProps:{shrink:!0},inputProps:{"aria-label":"Location"},error:Ve!==void 0,helperText:Ve??(Re?`Written as ${Re} in the package, and opened in the builder.`:"A path in the package; the package root by default.")}),se&&t.jsx(m.Alert,{severity:"error",children:se})]})]})]})})}function Ty(e,n){const[r,o]=T.useState(void 0);return T.useEffect(()=>{const i=window.setTimeout(()=>o(e),n);return()=>window.clearTimeout(i)},[e,n]),r}const Ps=(e,n,r)=>`${e}::${n}::${r}`,jy=new Map,My=new Map;function Ea({children:e}){const n=q.usePublisherTheme().theme.ui;return t.jsx(m.Typography,{component:"div",sx:{...n.type.label,color:"text.secondary",mb:.75},children:e})}function Oy({layout:e,checked:n,disabled:r,onPick:o}){const{theme:i}=q.usePublisherTheme(),l=i.ui,a=c.edgeColor(i.cardBorder),u=n?i.accent:"currentColor";return t.jsxs(m.ButtonBase,{role:"radio","aria-checked":n,"aria-label":e==="linear"?"Linear":"Grid",disabled:r,onClick:o,sx:d=>({justifyContent:"flex-start",gap:1.25,px:1.25,py:1,borderRadius:l.radius.tile,border:`1px solid ${n?i.accent:a}`,boxShadow:n?`0 0 0 1px ${i.accent}`:"none",bgcolor:n?`color-mix(in srgb, ${i.accent} 6%, ${d.palette.background.paper})`:d.palette.background.paper,color:d.palette.text.secondary,textAlign:"left"}),children:[t.jsx("svg",{width:"34",height:"26",viewBox:"0 0 34 26","aria-hidden":!0,children:e==="linear"?t.jsxs("g",{fill:"none",stroke:u,strokeWidth:"1.5",children:[t.jsx("rect",{x:"3",y:"2",width:"28",height:"7",rx:"1.5"}),t.jsx("rect",{x:"3",y:"12",width:"28",height:"5",rx:"1.5"}),t.jsx("path",{d:"M5 21.5h20",strokeLinecap:"round"})]}):t.jsxs("g",{fill:"none",stroke:u,strokeWidth:"1.5",children:[t.jsx("rect",{x:"2",y:"2",width:"14",height:"10",rx:"1.5"}),t.jsx("rect",{x:"18",y:"2",width:"14",height:"10",rx:"1.5"}),t.jsx("rect",{x:"2",y:"14",width:"30",height:"10",rx:"1.5"})]})}),t.jsxs(m.Box,{children:[t.jsx(m.Box,{sx:{...l.type.control,fontWeight:n?l.type.label.fontWeight:500,color:n?i.accent:"text.primary"},children:e==="linear"?"Linear":"Grid"}),t.jsx(m.Box,{sx:{...l.type.caption,color:"text.secondary"},children:e==="linear"?"Read top to bottom":"Tiles side by side"})]})]})}const Ey=c.createSvgIcon(t.jsx("path",{d:"M21 11h-1.5v-.5h-2v3h2V13H21v1c0 .55-.45 1-1 1h-3c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1zM8 10v5H6.5v-1.5h-2V15H3v-5c0-.55.45-1 1-1h3c.55 0 1 .45 1 1m-1.5.5h-2V12h2zm7 1.5c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1h-4V9h4c.55 0 1 .45 1 1v1c0 .55-.45 1-1 1M11 10.5v.75h2v-.75zm2 2.25h-2v.75h2z"})),Iy=c.createSvgIcon(t.jsx("path",{d:"M15 4v2h3v12h-3v2h5V4zM4 20h5v-2H6V6h3V4H4z"})),Dy=c.createSvgIcon(t.jsx("path",{d:"M4 7v2c0 .55-.45 1-1 1H2v4h1c.55 0 1 .45 1 1v2c0 1.65 1.35 3 3 3h3v-2H7c-.55 0-1-.45-1-1v-2c0-1.3-.84-2.42-2-2.83v-.34C5.16 11.42 6 10.3 6 9V7c0-.55.45-1 1-1h3V4H7C5.35 4 4 5.35 4 7m17 3c-.55 0-1-.45-1-1V7c0-1.65-1.35-3-3-3h-3v2h3c.55 0 1 .45 1 1v2c0 1.3.84 2.42 2 2.83v.34c-1.16.41-2 1.52-2 2.83v2c0 .55-.45 1-1 1h-3v2h3c1.65 0 3-1.35 3-3v-2c0-.55.45-1 1-1h1v-4z"})),Ay=c.createSvgIcon(t.jsx("path",{d:"M20 10V8h-4V4h-2v4h-4V4H8v4H4v2h4v4H4v2h4v4h2v-4h4v4h2v-4h4v-2h-4v-4zm-6 4h-4v-4h4z"})),dc={dashboard:q.PALETTE.blue,report:q.PALETTE.violet,model:q.PALETTE.cyan,dataApp:q.PALETTE.pink,data:q.PALETTE.lime,materialization:q.PALETTE.amber,agent:q.PALETTE.red};function hc({type:e,size:n=18,sx:r,...o}){return t.jsx(c.SvgIcon,{...o,viewBox:"0 0 24 24",sx:{width:n,height:n,fill:"none",stroke:"currentColor",strokeWidth:1.5,strokeLinecap:"round",strokeLinejoin:"round",...r},children:Ry[e]()})}const Ry={report:$y,model:Fy,data:Ly,materialization:_y,dataApp:zy,dashboard:Ny,agent:Py};function $y(){return t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M14 3 H6 a2 2 0 0 0 -2 2 v14 a2 2 0 0 0 2 2 h12 a2 2 0 0 0 2 -2 V9 z"}),t.jsx("path",{d:"M14 3 v4 a2 2 0 0 0 2 2 h4"}),t.jsx("path",{d:"M8 17 v-3"}),t.jsx("path",{d:"M12 17 v-6"}),t.jsx("path",{d:"M16 17 v-4"})]})}function Fy(){return t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M12 3 L4 7 v10 l8 4 l8 -4 V7 z"}),t.jsx("path",{d:"M4 7 l8 4 l8 -4"}),t.jsx("path",{d:"M12 11 v10"})]})}function Ly(){return t.jsxs(t.Fragment,{children:[t.jsx("rect",{x:"3.5",y:"3.5",width:"17",height:"17",rx:"2"}),t.jsx("path",{d:"M3.5 9.5 H20.5"}),t.jsx("path",{d:"M9.5 3.5 V20.5"})]})}function _y(){return t.jsxs(t.Fragment,{children:[t.jsx("path",{d:"M12 3 L21 7.5 L12 12 L3 7.5 Z"}),t.jsx("path",{d:"M3 12 L12 16.5 L21 12"}),t.jsx("path",{d:"M3 16.5 L12 21 L21 16.5"})]})}function Ny(){return t.jsxs(t.Fragment,{children:[t.jsx("rect",{x:"3.5",y:"3.5",width:"17",height:"17",rx:"2"}),t.jsx("path",{d:"M3.5 9.5 H20.5"}),t.jsx("path",{d:"M12 9.5 V20.5"}),t.jsx("path",{d:"M12 15 H20.5"})]})}function Py(){return t.jsxs(t.Fragment,{children:[t.jsx("circle",{cx:"12",cy:"8",r:"3.5"}),t.jsx("path",{d:"M5 20 a7 7 0 0 1 14 0"})]})}function zy(){return t.jsxs(t.Fragment,{children:[t.jsx("rect",{x:"3.5",y:"4.5",width:"17",height:"15",rx:"2"}),t.jsx("path",{d:"M3.5 9.5 H20.5"}),t.jsx("path",{d:"M7 13.5 H17"}),t.jsx("path",{d:"M7 16.5 H13"})]})}function fc(e){return e>=1e9?`${(e/1e9).toFixed(1)} B rows`:e>=1e6?`${(e/1e6).toFixed(1)} M rows`:e>=1e3?`${(e/1e3).toFixed(1)} K rows`:`${e} rows`}const Wy=12;function qy(e){const n=e?.trim().toLowerCase()??"";if(n.startsWith("array")||n.endsWith("[]"))return Iy;if(n.startsWith("record")||n.startsWith("struct"))return Dy;switch(n.split(/[\s(<]/)[0]){case"string":return Ey;case"number":return Ay;case"date":return Nl;case"timestamp":case"timestamptz":return zl;case"boolean":return Wl;default:return ql}}function By({column:e}){const n=qy(e.type);return t.jsxs(m.Box,{component:"li",sx:r=>({display:"flex",alignItems:"center",gap:1.25,px:1,py:.625,borderRadius:1,transition:"background-color 0.1s","&:hover":{backgroundColor:r.palette.mode==="dark"?"rgba(255, 255, 255, 0.06)":r.palette.grey[100]}}),children:[t.jsx(n,{"aria-hidden":!0,sx:{fontSize:18,color:"primary.main",flexShrink:0}}),t.jsxs(m.Box,{sx:{display:"flex",alignItems:"baseline",gap:1,minWidth:0,flex:1},children:[t.jsx(m.Typography,{component:"span",sx:{fontFamily:q.MONO_FONT_FAMILY,fontSize:"0.8125rem",fontWeight:500,color:"text.primary",minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.name}),e.type&&t.jsx(m.Typography,{component:"span",variant:"caption",color:"text.secondary",sx:{flexShrink:0,maxWidth:"50%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.type})]})]})}function Vy({database:e,onClose:n}){const r=e!==null,[o,i]=T.useState(e);e!==null&&e!==o&&i(e);const[l,a]=T.useState(""),[u,d]=T.useState(o?.path);u!==o?.path&&(d(o?.path),a(""));const h=T.useId(),y=o?.path??"",b=y.split("/").pop()||y,x=y.slice(0,Math.max(0,y.length-b.length-1)),v=o?.info?.rowCount,k=[x,v===void 0?null:fc(v)].filter(Boolean).join(" · "),C=T.useMemo(()=>o?.info?.columns??[],[o]),S=l.trim().toLowerCase(),j=T.useMemo(()=>S?C.filter(M=>M.name?.toLowerCase().includes(S)||M.type?.toLowerCase().includes(S)):C,[C,S]);return t.jsxs(c.AppDialog,{open:r,onClose:n,showClose:!0,title:t.jsxs(m.Stack,{direction:"row",alignItems:"center",spacing:1.5,sx:{minWidth:0},children:[t.jsx(m.Box,{"aria-hidden":!0,sx:{width:32,height:32,borderRadius:1,bgcolor:dc.data,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t.jsx(hc,{type:"data",size:18})}),t.jsxs(m.Box,{sx:{minWidth:0},children:[t.jsx(m.Typography,{component:"span",noWrap:!0,title:y,sx:{display:"block",fontFamily:q.MONO_FONT_FAMILY,fontSize:"1rem",fontWeight:600,letterSpacing:0,lineHeight:1.4},children:b||"Columns"}),k&&t.jsx(m.Typography,{component:"span",variant:"caption",color:"text.secondary",noWrap:!0,sx:{display:"block",lineHeight:1.4},children:k})]})]}),children:[o?.error&&t.jsx(m.Alert,{severity:"error",variant:"outlined",children:o.error}),o&&!o.error&&t.jsxs(m.Box,{component:"section","aria-labelledby":h,sx:{display:"flex",flexDirection:"column",border:"1px solid",borderColor:"divider",borderRadius:2,bgcolor:"background.paper",overflow:"hidden",mb:2},children:[t.jsxs(m.Stack,{direction:"row",alignItems:"center",spacing:1,sx:{px:1.5,py:1,minHeight:44,borderBottom:"1px solid",borderColor:"divider"},children:[t.jsxs(m.Typography,{id:h,component:"h3",sx:{fontSize:"0.875rem",fontWeight:600},children:["Columns",t.jsxs(m.Typography,{component:"span",variant:"caption",color:"text.secondary",sx:{ml:.75,fontVariantNumeric:"tabular-nums"},children:["· ",S?`${j.length} of `:"",C.length]})]}),C.length>Wy&&t.jsx(m.InputBase,{value:l,onChange:M=>a(M.target.value),placeholder:"Filter columns",inputProps:{"aria-label":"Filter columns"},startAdornment:t.jsx(m.InputAdornment,{position:"start",children:t.jsx(c.SearchIcon,{sx:{fontSize:16,color:"text.secondary"}})}),sx:{ml:"auto !important",width:200,fontSize:"0.8125rem",px:1,py:.25,border:"1px solid",borderColor:"divider",borderRadius:1.5,"&.Mui-focused":{borderColor:"primary.main"}}})]}),t.jsx(m.Box,{sx:{overflowY:"auto",maxHeight:420,px:.75,py:.75},children:j.length===0?t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic",px:1,py:1},children:S?"No columns match":"No columns"}):t.jsx(m.Box,{component:"ul","aria-labelledby":h,sx:{listStyle:"none",m:0,p:0},children:j.map((M,O)=>t.jsx(By,{column:M},`${M.name}-${O}`))})})]})]})}const Do=(e,n,r)=>["packageVersions",e,n,r];async function pc(e,n,r){try{return(await e.versions.listPackageVersions(n,r)).data}catch(o){const i=o?.response?.status;if(i===404||i===501)return[];throw o}}function mc(e,n,r={}){const{apiClients:o,server:i}=q.useServer(),l=(r.enabled??!0)&&e!==""&&n!=="",a=pt.useQuery({queryKey:Do(e,n,i),queryFn:()=>pc(o,e,n),enabled:l,staleTime:3e4,retry:!1}),{refetch:u}=a,d=T.useCallback(()=>void u(),[u]),h=a.data??[];return{versions:h,latest:h.find(y=>y.latest)?.id,isPending:l&&a.isPending,isError:l&&a.isError,refetch:d}}function Hy(e,n){const{apiClients:r,server:o}=q.useServer(),i=pt.useQueryClient();return T.useCallback(()=>i.fetchQuery({queryKey:Do(e,n,o),queryFn:()=>pc(r,e,n),staleTime:0,retry:!1}),[i,r,o,e,n])}function gc(e,n){const r=pt.useQueryClient();return T.useCallback(()=>r.invalidateQueries({predicate:o=>o.queryKey[1]===e&&o.queryKey[2]===n}),[r,e,n])}const Uy=c.createSvgIcon(t.jsx("path",{d:"m20.54 5.23-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27M6.24 5h11.52l.81.97H5.44zM5 19V8h14v11zm8.45-9h-2.9v3H8l4 4 4-4h-2.55z"})),Gy=c.createSvgIcon(t.jsx("path",{d:"M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2m-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2"})),Yy=c.createSvgIcon(t.jsx("path",{d:"M14 4v5c0 1.12.37 2.16 1 3H9c.65-.86 1-1.9 1-3V4zm3-2H7c-.55 0-1 .45-1 1s.45 1 1 1h1v5c0 1.66-1.34 3-3 3v2h5.97v7l1 1 1-1v-7H19v-2c-1.66 0-3-1.34-3-3V4h1c.55 0 1-.45 1-1s-.45-1-1-1"})),Ky=c.createSvgIcon(t.jsx("path",{d:"m20.54 5.23-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27M6.24 5h11.52l.83 1H5.42zM5 19V8h14v11zm3-5h2.55v3h2.9v-3H16l-4-4z"})),dr=e=>{const n=e?.response?.data?.message;return typeof n=="string"&&n!==""?n:e instanceof Error?e.message:"Unknown error"},Qy=e=>{const n=new Date(e);return Number.isNaN(n.getTime())?"":n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})},$n=e=>e.archiveStatus==="archive",zs="Tables built for this version alone (under scope: version) are dropped.";function Ia(e,n){const r=!$n(e)&&n.filter(i=>!$n(i)).length<=1,o=n.length<=1;return{archive:e.latest?"The latest version can't be archived":r?"The last version in service can't be archived":void 0,delete:o?void 0:e.latest?"Pin another version as latest first":r?"The last version in service; delete the archived versions first":void 0}}function yc({environmentName:e,packageName:n,versions:r,selectedVersionId:o,onSelectVersion:i,onReplaceVersion:l,onPackageDeleted:a,canManage:u}){const{apiClients:d}=q.useServer(),h=pt.useQueryClient(),y=gc(e,n),b=Hy(e,n),[x,v]=T.useState(null),[k,C]=T.useState(null),[S,j]=T.useState(null),[M,O]=T.useState(null),[E,$]=T.useState(null),[P,A]=T.useState(null),B=T.useRef(null),D=T.useRef(null),_=T.useRef(null),V=T.useRef(new Map),R=r.find(K=>K.latest)?.id,W=o??R,Z=()=>Promise.all([y(),h.invalidateQueries({queryKey:["packages",e]})]),ne=async(K,he)=>{const we=he??await b().catch(()=>{});if(we===void 0)return;const ge=we.find(ye=>ye.latest)?.id,me=ge??we.find(ye=>ye.id!==K&&!$n(ye))?.id;me!==void 0&&(l?l(me===ge?void 0:me):i(me))},J=pt.useMutation({mutationFn:K=>d.versions.setPackageLatestVersion(e,n,{version:K}),onSuccess:async()=>{j(null),await Z()},onError:()=>void Z()}),H=pt.useMutation({mutationFn:({id:K,archiveStatus:he})=>d.versions.updatePackageVersion(e,n,K,{archiveStatus:he}),onSuccess:async(K,{id:he,archiveStatus:we})=>{O(null),we==="archive"&&he===W&&await ne(he),await Z()},onError:(K,{id:he,archiveStatus:we})=>{we==="unarchive"&&A(`Couldn't unarchive v${he}: ${dr(K)}`),Z()}}),Q=H.isPending?H.variables?.id:void 0,re=pt.useMutation({mutationFn:({id:K})=>d.versions.deletePackageVersion(e,n,K),onSuccess:async(K,{id:he,read:we})=>{$(null);const me=await b().catch(()=>{})??we.filter(ye=>ye.id!==he);if(me.length===0){await h.invalidateQueries({queryKey:["packages",e]}),a?.();return}he===W&&await ne(he,me),await Z()},onError:()=>void Z()}),z=()=>C(null),oe=k?Ia(k.version,r):{},se=k!==null&&!$n(k.version)&&k.version.latest&&oe.archive!==void 0&&oe.delete!==void 0,ie=E!==null&&E.versions===void 0,De=E?.versions!==void 0&&E.versions.length<=1,de=E?.versions!==void 0?Ia(E.version,E.versions).delete:void 0,ue=async K=>{z(),v(null),re.reset(),$({version:K});const he=me=>$(ye=>ye!==null&&ye.version.id===K.id&&ye.versions===void 0?me:ye);let we;try{we=await b()}catch(me){he(null),A(`Couldn't check v${K.id} before deleting it: ${dr(me)}`);return}const ge=we.find(me=>me.id===K.id);if(ge===void 0){he(null),A(`v${K.id} is no longer a version of ${n}.`),Z();return}he({version:ge,versions:we})},be=(K,he)=>{!u||Q===K.id||C({version:K,anchor:V.current.get(K.id)??he})},Oe=(K,he)=>{const we=K.key==="ArrowRight"||K.key==="ContextMenu"||K.key==="F10"&&K.shiftKey;!u||!we||(K.preventDefault(),K.stopPropagation(),be(he,K.currentTarget))},te=k&&t.jsxs(m.MenuItem,{disabled:oe.delete!==void 0,onClick:()=>void ue(k.version),children:[t.jsx(m.ListItemIcon,{children:t.jsx(c.DeleteOutlineIcon,{fontSize:"small"})}),t.jsx(m.ListItemText,{primary:"Delete version",secondary:oe.delete})]},"delete");return t.jsxs(t.Fragment,{children:[t.jsx(m.Button,{size:"small",variant:"outlined",endIcon:t.jsx(Pl,{}),"aria-label":W?`Version v${W}, change version`:"Select a version","aria-haspopup":"menu",onClick:K=>v(K.currentTarget),sx:{borderRadius:999,textTransform:"none",fontWeight:500,px:1.5,minWidth:0,whiteSpace:"nowrap"},children:W?`v${W}`:"Select a version"}),t.jsx(m.Menu,{anchorEl:x,open:x!==null,onClose:()=>v(null),slotProps:{paper:{sx:{minWidth:320,maxWidth:400,mt:1,borderRadius:3}},list:{"aria-label":`Versions of ${n}`,disabledItemsFocusable:!0}},children:r.map(K=>{const he=K.id===W,we=$n(K),ge=[we?"Archived":void 0,Qy(K.createdAt),K.gitCommitSha?K.gitCommitSha.slice(0,7):void 0].filter(Boolean).join(" · ");return t.jsxs(m.MenuItem,{"aria-current":he?"true":void 0,"aria-disabled":we&&!u?"true":void 0,"aria-haspopup":u?"menu":void 0,"data-testid":"version-row",onKeyDown:me=>Oe(me,K),onClick:me=>{if(we){be(K,me.currentTarget);return}he||(v(null),i(K.id,me))},sx:me=>({gap:1,borderLeft:"3px solid",borderLeftColor:he?me.palette.primary.main:"transparent",backgroundColor:he?m.alpha(me.palette.primary.main,.04):void 0,cursor:he||we&&!u?"default":"pointer"}),children:[t.jsx(m.ListItemText,{primary:K.id,secondary:ge,sx:{opacity:we?.6:1},slotProps:{primary:{sx:{fontWeight:he?600:400}}}}),K.latest&&t.jsx(m.Chip,{size:"small",label:"Latest",color:"info",variant:"outlined",sx:{height:20,fontSize:11,fontWeight:600}}),u&&t.jsx(m.Tooltip,{title:Q===K.id?"Updating this version…":"",children:t.jsx("span",{children:t.jsx(m.IconButton,{ref:me=>{me?V.current.set(K.id,me):V.current.delete(K.id)},size:"small","aria-label":`More actions for version ${K.id}`,"aria-haspopup":"menu",disabled:Q===K.id,onClick:me=>{me.stopPropagation(),C({version:K,anchor:me.currentTarget})},children:t.jsx(Gy,{fontSize:"small"})})})})]},K.id)})}),t.jsx(m.Menu,{anchorEl:k?.anchor??null,open:k!==null,onClose:z,slotProps:{list:{"aria-label":k?`Actions for version ${k.version.id}`:void 0,disabledItemsFocusable:!0,autoFocus:se}},children:k&&$n(k.version)?[t.jsxs(m.MenuItem,{onClick:()=>{const{id:K}=k.version;z(),H.mutate({id:K,archiveStatus:"unarchive"})},children:[t.jsx(m.ListItemIcon,{children:t.jsx(Ky,{fontSize:"small"})}),t.jsx(m.ListItemText,{primary:"Unarchive"})]},"unarchive"),t.jsx(m.Divider,{},"divider"),te]:k&&[t.jsxs(m.MenuItem,{disabled:k.version.latest,onClick:()=>{j(k.version),J.reset(),z(),v(null)},children:[t.jsx(m.ListItemIcon,{children:t.jsx(Yy,{fontSize:"small"})}),t.jsx(m.ListItemText,{primary:"Pin as latest",secondary:k.version.latest?"Already the latest version":void 0})]},"pin-latest"),t.jsxs(m.MenuItem,{disabled:oe.archive!==void 0,onClick:()=>{O(k.version),H.reset(),z(),v(null)},children:[t.jsx(m.ListItemIcon,{children:t.jsx(Uy,{fontSize:"small"})}),t.jsx(m.ListItemText,{primary:"Archive",secondary:oe.archive})]},"archive"),t.jsx(m.Divider,{},"divider"),te]}),t.jsx(c.AppDialog,{open:S!==null,onClose:()=>{J.isPending||j(null)},title:S?`Pin v${S.id} as latest`:"",description:S?`Requests that name no version will be served from v${S.id}.`:void 0,initialFocus:B,actions:t.jsxs(t.Fragment,{children:[t.jsx(m.Button,{ref:B,disabled:J.isPending,onClick:()=>j(null),children:"Cancel"}),t.jsx(m.Button,{variant:"contained",loading:J.isPending,onClick:()=>S&&J.mutate(S.id),children:"Pin as latest"})]}),children:t.jsxs(m.Stack,{spacing:1.5,children:[R&&S&&R!==S.id&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:`The latest version is v${R} now. Links and requests that name a version keep answering as before.`}),J.isError&&S&&t.jsx(m.Alert,{severity:"error",role:"alert",children:`Couldn't pin v${S.id} as latest: ${dr(J.error)}`})]})}),t.jsx(c.AppDialog,{open:M!==null,onClose:()=>{H.isPending||O(null)},title:M?`Archive v${M.id}`:"",description:M?`v${M.id} stops being served and is unloaded. Its files stay, so it can be unarchived.`:void 0,initialFocus:D,actions:t.jsxs(t.Fragment,{children:[t.jsx(m.Button,{ref:D,disabled:H.isPending,onClick:()=>O(null),children:"Cancel"}),t.jsx(m.Button,{variant:"contained",loading:H.isPending,onClick:()=>M&&H.mutate({id:M.id,archiveStatus:"archive"}),children:"Archive"})]}),children:t.jsxs(m.Stack,{spacing:1.5,children:[t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:`${zs} Its scheduled builds stop, and once unarchived it serves live until it is built again.`}),H.isError&&M&&t.jsx(m.Alert,{severity:"error",role:"alert",children:`Couldn't archive v${M.id}: ${dr(H.error)}`})]})}),t.jsx(c.AppDialog,{open:E!==null,onClose:()=>{re.isPending||$(null)},title:E?`Delete v${E.version.id}`:"",initialFocus:_,actions:t.jsxs(t.Fragment,{children:[t.jsx(m.Button,{ref:_,disabled:re.isPending,onClick:()=>$(null),children:"Cancel"}),t.jsx(m.Button,{variant:"contained",color:"error",loading:re.isPending,disabled:ie||de!==void 0,onClick:()=>E?.versions&&re.mutate({id:E.version.id,read:E.versions}),children:De?"Delete package":"Delete version"})]}),children:t.jsxs(m.Stack,{spacing:1.5,children:[ie&&E&&t.jsx(m.Typography,{variant:"body2",children:`Checking ${n}'s versions before deleting v${E.version.id}…`}),E&&!ie&&t.jsx(m.Typography,{variant:"body2",children:De?`v${E.version.id} is the only version of ${n}, so deleting it deletes the package. ${zs} This cannot be undone.`:`v${E.version.id} stops being served and its files are removed. ${zs} Links that name it stop working, and this cannot be undone.`}),de!==void 0&&E&&t.jsx(m.Alert,{severity:"warning",role:"alert",children:`v${E.version.id} can't be deleted now: ${de}.`}),re.isError&&E&&t.jsx(m.Alert,{severity:"error",role:"alert",children:`Couldn't delete v${E.version.id}: ${dr(re.error)}`})]})}),t.jsx(m.Snackbar,{open:P!==null,autoHideDuration:8e3,onClose:()=>A(null),anchorOrigin:{vertical:"bottom",horizontal:"center"},children:t.jsx(m.Box,{children:t.jsx(m.Alert,{severity:"error",variant:"filled",onClose:()=>A(null),children:P})})})]})}const Zy="README.malloynb",Xy=e=>!!e&&!e.includes("/")&&c.documentSlug(e)?.toLowerCase()==="readme";function Jy({onClickPackageFile:e,onOpenDocument:n,resourceUri:r,onEvent:o,onSelectVersion:i,onReplaceVersion:l}){const{apiClients:a,server:u,mutable:d}=q.useServer(),h=pt.useQueryClient(),y=e??(Y=>{window.location.href=Y}),{environmentName:b,packageName:x,versionId:v}=c.parseResourceUri(r),k=mc(b,x),{versions:C}=k,S=C.length>0,j=!S&&!k.isPending&&!k.isError,M=i??((Y,ae)=>y(`/${encodeURIComponent(b)}/${encodeURIComponent(x)}/${encodeURIComponent(Y)}`,ae)),O=n??((Y,ae)=>{const Re=Y.mode==="edit"?c.reportEditRoute(b,x,Y.path):c.reportRoute(b,x,Y.path);ae?y(Re,ae):y(Re)}),[E,$]=T.useState(null),[P,A]=T.useState(!1),B=Ra(),D=c.useOptionalDocumentStorage()?.documentStorage,[_,V]=T.useState([]),[R,W]=T.useState({state:D?"pending":"ready"}),Z=T.useCallback(async()=>{if(!D)return;let Y;try{Y=await D.listWorkspaces(!1)}catch{W({state:"failed"});return}W({state:"ready",chosen:c.chooseWorkspace(Y)});const ae=[],Re=c.draftKey(b,x,"");for(const Ve of Y.filter(St=>St.writeable))for(const St of await D.listDocuments(Ve))St.path.startsWith(Re)&&ae.push({locator:St,where:Ve.description});V(ae)},[D,b,x]);T.useEffect(()=>{Z()},[Z]);const ne=Y=>Y.path.slice(c.draftKey(b,x,"").length),J=c.useQueryWithApiError({queryKey:["package",b,x,v],queryFn:()=>a.packages.getPackage(b,x,v,!1)}),H=c.useQueryWithApiError({queryKey:["package-agents",b,x,v],queryFn:()=>a.agents.listAgents(b,x,v)}),Q=c.useReportListing(b,x,v),re=c.useQueryWithApiError({queryKey:["models",b,x,v],queryFn:()=>a.models.listModels(b,x,v)}),z=c.useQueryWithApiError({queryKey:["databases",b,x,v],queryFn:()=>a.databases.listDatabases(b,x,v)}),se=c.useQueryWithApiError({queryKey:["data-apps",b,x,v],queryFn:async()=>{try{return await a.dataApps.listDataApps(b,x,v)}catch(Y){const ae=Y?.response?.status;if(ae===404||ae===void 0)return{data:[]};throw Y}}}).data?.data??[],ie=Q.reports.filter(Y=>!!Y.path),De=tx(ie),de=new Set(ie.map(Y=>Y.path).filter(Y=>Y!==void 0)),ue=(re.data?.data??[]).slice().filter(Y=>!de.has(Y.path)).sort((Y,ae)=>Y.path.localeCompare(ae.path)),be=(z.data?.data??[]).slice().sort((Y,ae)=>Y.path.localeCompare(ae.path)),Oe=R.state==="ready"?c.createRoute({authoritative:R.chosen?.authoritative===!0,mutable:d&&j,canStore:R.chosen?.writeable===!0,...v===void 0?{}:{versionId:v}}):void 0,te=Q.settled&&(re.isSuccess||re.isError),K=Oe!==void 0&&te,he=K&&!B,we=T.useMemo(()=>{if(!K)return;const Y=[...Q.reports.flatMap(ae=>ae.path?[ae.path]:[]),...(re.data?.data??[]).flatMap(ae=>ae.path?[ae.path]:[])];if(Oe==="storage"&&D&&R.state==="ready")return R.chosen?{route:Oe,storage:D,workspace:R.chosen,environmentName:b,packageName:x,existing:Y}:void 0;if(Oe==="package")return{route:Oe,existing:Y,write:async(ae,Re)=>{await a.models.updateModelSource(b,x,ae,{source:Re})}}},[K,Oe,D,R,b,x,a,Q.reports,re.data]),ge=J.data?.data?.description??"",me=H.data?.data??[],ye=(ie.find(Y=>Y.path===Zy)??ie.find(Y=>Xy(Y.path)))?.path,Le=!Q.settled,st=S?t.jsx(yc,{environmentName:b,packageName:x,versions:C,...v!==void 0?{selectedVersionId:v}:{},onSelectVersion:M,...l?{onReplaceVersion:l}:{},onPackageDeleted:()=>y(`/${encodeURIComponent(b)}`),canManage:d}):null,ce=t.jsxs(m.Stack,{direction:"row",alignItems:"center",spacing:1.5,sx:{mb:.5},children:[t.jsx(m.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em"},children:x}),st]});if(J.isError){const Y=t.jsx(c.ApiErrorDisplay,{error:J.error,context:`${b} > ${x}`});return st?t.jsxs(m.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsx(m.Box,{sx:{mb:4},children:ce}),Y]}):Y}return t.jsxs(m.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsxs(m.Box,{sx:{mb:4},children:[ce,ge&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:ge})]}),t.jsx(my,{warnings:J.data?.data?.warnings}),k.isError&&t.jsx(m.Box,{sx:{mb:4},children:t.jsx(m.Alert,{severity:"warning",action:t.jsx(m.Button,{color:"inherit",size:"small",onClick:k.refetch,children:"Retry"}),children:"Could not read this package's versions, so nothing that changes it is offered until they load."})}),Le&&t.jsx(c.Loading,{text:"Loading package..."}),we&&t.jsx(uc,{open:P,layout:"linear",environmentName:b,packageName:x,...v!==void 0?{versionId:v}:{},models:ue.map(Y=>Y.path).filter(Y=>typeof Y=="string"&&Y.endsWith(".malloy")&&!de.has(Y)),modelsLoading:re.isPending,...re.isError?{modelsError:re.error}:{},onRetryModels:()=>void re.refetch(),target:we,...o?{onEvent:o}:{},onClose:()=>A(!1),onCreated:Y=>{A(!1),c.invalidateReportQueries(h),h.invalidateQueries({queryKey:["models"]}),O({path:Y.path,layout:Y.layout,slug:Y.slug,mode:"edit"})}}),!Le&&t.jsxs(t.Fragment,{children:[Q.isError&&t.jsx(m.Box,{sx:{mb:4},children:t.jsx(m.Alert,{severity:"warning",action:t.jsx(m.Button,{color:"inherit",size:"small",onClick:()=>void Q.refetch(),children:"Retry"}),children:"Could not list this package's reports, so any it has are missing from this page."})}),(De.length>0||K)&&t.jsxs(Nt,{title:"Reports",count:De.length,...he?{action:t.jsx(c.AddButton,{label:"Report",onClick:()=>A(!0)})}:{},children:[De.length===0&&t.jsx(Ws,{label:"No reports yet",...he?{action:{label:"Add report",onClick:()=>A(!0)}}:{}}),De.map(Y=>t.jsx(Dn,{type:Y.layout==="grid"?"dashboard":"report",label:Y.label,rightLabel:Y.layout,...Y.secondary===void 0?{}:{description:Y.secondary},onClick:ae=>Y.path.endsWith(".malloynb")?y(`/${b}/${x}/${Y.path}`,ae):O({path:Y.path,layout:Y.layout,slug:Y.slug,mode:"view"},ae)},Y.path))]}),j&&_.length>0&&t.jsx(Nt,{title:"Drafts",count:_.length,children:_.map(({locator:Y,where:ae})=>t.jsx(Dn,{type:Y.type==="grid"?"dashboard":"report",label:ne(Y),rightLabel:ae,onClick:Re=>O({path:ne(Y),layout:Y.type,slug:c.documentSlug(ne(Y))??"",mode:"edit"},Re),trailingAction:t.jsx(m.Tooltip,{title:"Delete this draft",children:t.jsx(m.IconButton,{size:"small","aria-label":`Delete draft ${ne(Y)}`,onClick:Re=>{Re.stopPropagation(),D?.deleteDocument(Y).then(Z)},children:t.jsx(c.DeleteOutlineIcon,{fontSize:"small"})})})},`${Y.workspace}:${Y.path}`))}),se.length>0&&t.jsx(Nt,{title:"Apps",count:se.length,children:se.map(Y=>{const ae=!!Y.title&&Y.title!==Y.path,Re=`${Xa(u)}${Y.resource}`;return t.jsx(Dn,{type:"dataApp",label:ae?Y.title:Y.path,rightLabel:ae?Y.path:void 0,onClick:Ve=>{e?e(`/${b}/${x}/data-apps/${Y.path}`,Ve):Ve&&(Ve.metaKey||Ve.ctrlKey)?window.open(Re,"_blank"):window.location.href=Re},trailingAction:t.jsx(m.Tooltip,{title:"Open standalone in new tab",children:t.jsx(m.IconButton,{size:"small",href:Re,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",onClick:Ve=>Ve.stopPropagation(),sx:{color:"text.secondary"},children:t.jsx(Ya,{fontSize:"small"})})})},Y.path)})}),t.jsxs(Nt,{title:"Models",count:ue.length,children:[ue.map(Y=>t.jsx(Dn,{type:"model",label:Y.path,onClick:ae=>y(`/${b}/${x}/${Y.path}`,ae)},Y.path)),ue.length===0&&t.jsx(Ws,{label:"No models"})]}),me.length>0&&t.jsx(Nt,{title:"Agents",count:me.length,description:"Declared in publisher.json. Name one in an agent session to work as it. Schedules are listed only; nothing runs them yet.",children:me.map(Y=>t.jsx(ex,{agent:Y},Y.name))}),t.jsxs(Nt,{title:"Data",count:be.length,children:[be.map(Y=>t.jsx(Dn,{type:"data",label:Y.path,rightLabel:Y.info?fc(Y.info.rowCount):"Unreadable",onClick:()=>$(Y)},Y.path)),be.length===0&&t.jsx(Ws,{label:"No data files"})]}),t.jsx(vl,{resourceUri:r,versioned:!j}),ye&&t.jsx(m.Box,{sx:{mt:6},children:t.jsx(cc,{resourceUri:c.encodeResourceUri({environmentName:b,packageName:x,versionId:v}),path:ye,onLinkNavigate:y})})]}),t.jsx(Vy,{database:E,onClose:()=>$(null)})]})}function Dn({type:e,label:n,description:r,rightLabel:o,onClick:i,trailingAction:l}){return t.jsx(rs,{icon:t.jsx(hc,{type:e}),tint:dc[e],label:n,mono:!0,...r===void 0?{}:{description:r},...o===void 0?{}:{rightLabel:o},...i===void 0?{}:{onClick:i},...l===void 0?{}:{trailingAction:l}})}function ex({agent:e}){return t.jsxs(t.Fragment,{children:[t.jsx(Dn,{type:"agent",label:e.name??"",...e.description?{description:e.description}:{},...e.model&&e.model!=="inherit"?{rightLabel:e.model}:{}}),(e.schedules??[]).map(n=>{const r=uo(n.cron??"");return t.jsxs(m.Typography,{variant:"caption",color:"text.secondary",sx:{display:"block",ml:6,mb:.5},children:[r.valid?r.description:n.cron," (UTC), task"," ",n.task,". Not run yet."]},`${n.cron}|${n.task}`)})]})}function tx(e){const n=e.map(o=>({path:o.path??"",layout:c.listedLayout(o),slug:c.documentSlug(o.path)??o.path??"",title:o.title})),r=new Map;for(const o of n)r.set(o.slug,(r.get(o.slug)??0)+1);return n.map(({title:o,...i})=>{const l=!!o&&o!==i.slug&&o!==i.path,a=(r.get(i.slug)??0)>1,u=l?o:i.path.endsWith(".malloynb")?i.path:i.slug;return{...i,label:u,secondary:u!==i.path&&(l||a||i.path.includes("/"))?i.path:void 0}}).sort((o,i)=>o.label.localeCompare(i.label)||o.path.localeCompare(i.path))}function Ws({label:e,action:n}){return t.jsxs(m.Stack,{direction:"row",sx:{alignItems:"center",gap:1,py:1},children:[t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{fontStyle:"italic"},children:e}),n&&t.jsx(m.Button,{size:"small",onClick:n.onClick,children:n.label})]})}const Da=/^publisher:document:(dashboard|notebook):(.+)$/;function nx(e,n){const r=[];for(let o=0;o<e.length;o++){const i=e.key(o);i!==null&&Da.test(i)&&r.push(i)}for(const o of r){const[,i,l]=Da.exec(o),a=e.getItem(o);a!==null&&n(l,c.layoutOfKind(i),a)&&e.removeItem(o)}}const qs={name:"Local",description:"Stored in this browser only",writeable:!0},ro="publisher:report:",cn=e=>`${ro}${e}`;function hr(e){const n=localStorage.getItem(e);if(n!==null)try{const r=JSON.parse(n);if(typeof r.content=="string"&&(r.type==="grid"||r.type==="linear"))return{type:r.type,content:r.content}}catch{}}const Bs=(e,n)=>localStorage.setItem(cn(e),JSON.stringify(n));class rx{migrated=!1;migrate(){this.migrated||(this.migrated=!0,nx(localStorage,(n,r,o)=>hr(cn(n))!==void 0?!1:(Bs(n,{type:r,content:o}),!0)))}async listWorkspaces(n){return[qs]}async listDocuments(n,r){if(n.name!==qs.name)return[];this.migrate();const o=[];for(let i=0;i<localStorage.length;i++){const l=localStorage.key(i);if(l===null||!l.startsWith(ro))continue;const a=hr(l);a&&(r===void 0||a.type===r)&&o.push({workspace:qs.name,type:a.type,path:l.slice(ro.length)})}return o}async getDocument(n){this.migrate();const r=hr(cn(n.path));if(r===void 0)throw Vs(n);return r.content}async getDocumentType(n){this.migrate();const r=hr(cn(n.path));if(r===void 0)throw Vs(n);return r.type}async saveDocument(n,r){this.migrate(),Bs(n.path,{type:n.type,content:r})}async deleteDocument(n){if(this.migrate(),hr(cn(n.path))===void 0)throw Vs(n);localStorage.removeItem(cn(n.path))}async moveDocument(n,r){const o=await this.getDocument(n);Bs(r.path,{type:r.type,content:o}),r.path!==n.path&&localStorage.removeItem(cn(n.path))}}function Vs(e){return new c.DocumentNotFoundError(`No report at ${e.workspace}/${e.path}`)}async function sx(e,n,r,o){const i=c.chooseWorkspace(await e.listWorkspaces(!1));if(!i)return;const l=c.draftKey(n,r,o);if(e.getDocumentType)try{return await e.getDocumentType({workspace:i.name,path:l})}catch(a){if(c.isDocumentNotFound(a))return;throw a}return(await e.listDocuments(i)).find(a=>a.path===l)?.type}function ox(e,n,r,o=!0){const i=c.useOptionalDocumentStorage()?.documentStorage,l=o&&i!==void 0,[a,u]=T.useState(),d=c.draftKey(e,n,r);return T.useEffect(()=>{if(!l||!i)return;let h=!1;return sx(i,e,n,r).catch(()=>{}).then(y=>{h||u({key:d,layout:y})}),()=>{h=!0}},[l,i,e,n,r,d]),l?a?.key===d?{layout:a.layout,settled:!0}:{layout:void 0,settled:!1}:{layout:void 0,settled:!0}}function xc(e){const{environmentName:n,packageName:r}=c.parseResourceUri(e.resourceUri);if(!n||!r)throw new Error("Environment and Package name must be provided for query embedding.");return JSON.stringify({...e})}function ix({embeddedQueryResult:e}){const{query:n,sourceName:r,queryName:o,resourceUri:i,height:l}=JSON.parse(e),{modelPath:a}=c.parseResourceUri(i);if(!a||!n&&(!o||!r)||typeof a!="string")throw new Error("Invalid embedded query result: "+e);return t.jsx(vc,{query:n,sourceName:r,queryName:o,resourceUri:i,height:l})}function vc({query:e,sourceName:n,queryName:r,resourceUri:o,height:i=400}){const{modelPath:l,environmentName:a,packageName:u,versionId:d}=c.parseResourceUri(o);if(!a||!u)throw new Error("No environment or package name provided. A resource URI must be provided.");const h=c.useQueryResult({environmentName:a,packageName:u,modelPath:l,versionId:d,query:e,sourceName:n,queryName:r});return t.jsx(c.ResultPanel,{state:h,context:`${a} > ${u} > ${l}`,maxHeight:i})}function bc(e,n,r="grid"){const o=n.filter(l=>!!l.path).filter(l=>c.documentSlug(l.path)===e),i=o.filter(l=>c.listedLayout(l)===r);return i.length===1?{found:c.locatedReport(i[0])}:o.length===1?{found:c.locatedReport(o[0])}:o.length===0?{missing:!0}:{ambiguous:o.map(l=>l.path).sort()}}const ax=/^(dashboards|notebooks)\/([^/]+)$/;function lx(e){const n=ax.exec(e);if(n)return{name:n[2],prefer:n[1]==="dashboards"?"grid":"linear"}}const cx=(e,n,r,o)=>`/${e}/${n}/${r}s/${encodeURIComponent(o)}`;function ux({kind:e,slug:n,reports:r}){const o=bc(n,r,c.layoutOfKind(e));return"found"in o?o.found:void 0}function dx(e,n){return`${e}:${n}`}function hn(e){return dx(e.source,e.filterName??e.dimensionName)}function hx(e){const n=new Map;for(const r of e){const o=`${r.source}|${r.model}`,i=n.get(o)||[];i.push(r),n.set(o,i)}return n}function fx(e,n,r,o){const i=n.filter(h=>(h.filterType==="Star"||h.filterType==="MinMax"||h.filterType==="DateMinMax")&&!h.values);if(i.length===0)return"";const a=[...new Set(i.map(h=>h.dimensionName))].map(h=>`\`${h}\``).join(", "),u=o?.filter(h=>h.source===e)||[],d=u.length>0?u.map(h=>os(`\`${h.dimensionName}\``,h)).filter(h=>h.length>0).join(" and "):"";return`
|
|
39
39
|
run: ${e} -> {
|
|
40
40
|
${d?`where: ${d}`:""}
|
|
41
41
|
index: ${a}
|
|
@@ -45,7 +45,7 @@ ${i.inheritedFrom.code}`,framed:!1}):t.jsx(p.Box,{sx:{p:1},children:t.jsx(ds,{me
|
|
|
45
45
|
|
|
46
46
|
limit: ${r}
|
|
47
47
|
}
|
|
48
|
-
`}function
|
|
48
|
+
`}function px(e,n){const r=new Map;for(const y of n){const b=hn(y);r.set(b,[])}const o=JSON.parse(e),i=o.schema.fields,l=new Map;i.forEach((y,b)=>{l.set(y.name,b)});const a=y=>{if(!y)return null;switch(y.kind){case"string_cell":return y.string_value??null;case"number_cell":return y.number_value??null;case"boolean_cell":return y.boolean_value??null;case"null_cell":return null;default:return console.log("Unknown cell kind: "+y.kind),null}},d=(o.data?.array_value||[]).map(y=>{const b={};return y.kind==="record_cell"&&y.record_value&&y.record_value.forEach((x,v)=>{const k=i[v]?.name;if(k){const C=a(x);k==="fieldName"&&typeof C=="string"?b.fieldName=C:k==="fieldPath"&&typeof C=="string"?b.fieldPath=C:k==="fieldType"&&typeof C=="string"?b.fieldType=C:k==="fieldValue"&&typeof C=="string"?b.fieldValue=C:k==="weight"&&typeof C=="number"&&(b.weight=C)}}),b}),h=d.length===0||d.every(y=>!y.fieldName);for(const y of n){if(y.filterType==="NONE"||y.filterType==="Retrieval")continue;const b=d.filter(v=>{const k=v.fieldName||"",C=v.fieldPath||"";if(k===y.dimensionName||C===y.dimensionName||k.toLowerCase()===y.dimensionName.toLowerCase()||C.toLowerCase()===y.dimensionName.toLowerCase())return!0;const S=C.split(".").pop()||"";return S===y.dimensionName||S.toLowerCase()===y.dimensionName.toLowerCase()});if(b.length===0)continue;const x=hn(y);if(y.filterType==="Star"){const v=b.filter(k=>k.fieldType==="string").map(k=>({value:k.fieldValue??"",count:k.weight})).sort((k,C)=>(C.count??0)-(k.count??0));r.set(x,v)}else if(y.filterType==="MinMax"){console.log("MinMax dimensionEntries: "+JSON.stringify(b,null,2)),console.log("All MinMax dimension entries fieldTypes:",b.map(k=>k.fieldType));const v=b.find(k=>k.fieldType==="number");if(console.log("numericEntry: "+JSON.stringify(v,null,2)),v?.fieldValue){const k=v.fieldValue,C=k.split(" to ");if(console.log("rangeParts: "+C),C.length===2){const S=[{value:parseFloat(C[0])},{value:parseFloat(C[1])}];r.set(x,S)}else console.warn(`Could not parse numeric range for ${y.dimensionName}: ${k}`)}else console.warn(`No numeric entry found for ${y.dimensionName}. Available entries:`,b)}else if(y.filterType==="DateMinMax"){const v=b.find(k=>k.fieldType==="date"||k.fieldType==="timestamp"||k.fieldType==="string");if(console.log("dateEntry: "+JSON.stringify(v,null,2)),console.log("All date dimension entries fieldTypes:",b.map(k=>k.fieldType)),v?.fieldValue){const k=v.fieldValue,C=k.split(" to ");if(console.log("date rangeParts: "+C),C.length===2){const S=[{value:new Date(C[0].trim())},{value:new Date(C[1].trim())}];r.set(x,S)}else console.warn(`Could not parse date range for ${y.dimensionName}: ${k}`)}else console.warn(`No date entry found for ${y.dimensionName}. Available entries:`,b)}}return{values:r,noRowsMatchedFilter:h}}function wc(e){const{environment:n,package:r,dimensionSpecs:o,versionId:i,enabled:l=!0,indexLimit:a=1e4,activeFilters:u=[]}=e,d=T.useMemo(()=>hx(o),[o]),h=T.useMemo(()=>{const C=[];for(const[S,j]of d){const[M,O]=S.split("|"),E=fx(M,j,a,u);E?C.push({key:S,source:M,model:O,query:E,specs:j}):console.log("No query for source: ",M,"model: ",O)}return C},[d,a,u]),y=T.useMemo(()=>l&&h.length>0&&o.some(C=>C.filterType==="Star"||C.filterType==="MinMax"||C.filterType==="DateMinMax"),[l,h,o]),{apiClients:b}=q.useServer(),x=c.useQueryWithApiError({queryKey:["dimensionalFilter",n,r,o,i,u],queryFn:async({signal:C})=>{if(!y){const O=new Map;for(const E of o){const $=hn(E);O.set($,[])}return{values:O,noRowsMatchedFilter:!1}}const S=await Promise.all(h.map(async O=>{const E=await b.models.executeQueryModel(n,r,O.model,{query:O.query,versionId:i,bypassFilters:!0},void 0,void 0,{signal:C});return{config:O,result:px(E.data.result,O.specs)}})),j=new Map;let M=!1;for(const{result:O}of S){for(const[E,$]of O.values)j.set(E,$);O.noRowsMatchedFilter&&(M=!0)}return{values:j,noRowsMatchedFilter:M}},enabled:y,staleTime:300*1e3,placeholderData:C=>C}),v=x.data?.values;return{data:T.useMemo(()=>{const C=new Map;for(const S of o){const j=hn(S);S.values?C.set(j,S.values.map(M=>({value:M}))):C.set(j,[])}if(v)for(const[S,j]of v)j.length>0&&C.set(S,j);return C},[o,v]),noRowsMatchedFilter:x.data?.noRowsMatchedFilter??!1,isLoading:y?x.isPending:!1,isError:y?x.isError:!1,error:y?x.error:null,refetch:x.refetch}}function mx(e){return os(`\`${e.dimensionName}\``,e)}function Sc(e){const{dimensionSpecs:n}=e,[r,o]=T.useState(()=>{const h=new Map;return n.forEach(y=>{const b=hn(y);h.set(b,{spec:y,selection:null})}),h});T.useEffect(()=>{o(h=>{const y=new Map;return n.forEach(b=>{const x=hn(b),v=h.get(x);y.set(x,{spec:b,selection:v?.selection??null})}),y})},[n]);const i=T.useCallback((h,y)=>{o(b=>{const x=new Map(b),v=x.get(h);return v&&x.set(h,{...v,selection:y}),x})},[]),l=T.useCallback(h=>{i(h,null)},[i]),a=T.useCallback(()=>{o(h=>{const y=new Map(h);return y.forEach((b,x)=>{y.set(x,{...b,selection:null})}),y})},[]),u=T.useCallback(()=>{const h=[];return r.forEach(y=>{y.selection&&h.push(y.selection)}),h},[r]),d=T.useCallback(()=>{const h=u();if(h.length===0)return"";const y=h.map(b=>mx(b)).filter(b=>b.length>0);return y.length===0?"":`where ${y.join(" and ")}`},[u]);return{filterStates:r,updateFilter:i,clearFilter:l,clearAllFilters:a,getActiveFilters:u,generateWhereClause:d}}function gx(e){return os(`\`${e.dimensionName}\``,e)}function yx(e){if(e.length===0)return"";const n=e.map(r=>gx(r)).filter(r=>r.length>0);return n.length===0?"":n.join(" and ")}function xx(e,n,r,o=1e3){const i=yx(n),a=r&&r.length>0?`group_by: ${r.map(u=>`\`${u}\``).join(", ")}`:"select: *";return i?`
|
|
49
49
|
run: ${e} -> {
|
|
50
50
|
where: ${i}
|
|
51
51
|
${a}
|
|
@@ -56,4 +56,4 @@ ${i.inheritedFrom.code}`,framed:!1}):t.jsx(p.Box,{sx:{p:1},children:t.jsx(ds,{me
|
|
|
56
56
|
${a}
|
|
57
57
|
limit: ${o}
|
|
58
58
|
}
|
|
59
|
-
`}function
|
|
59
|
+
`}function kc(e){const{environment:n,package:r,model:o,source:i,filterSelections:l,fields:a,limit:u=1e3,versionId:d}=e,[h,y]=T.useState(null),b=T.useMemo(()=>xx(i,l,a,u),[i,l,a,u]),x=T.useMemo(()=>c.encodeResourceUri({environmentName:n,packageName:r,modelPath:o,versionId:d}),[n,r,o,d]),v=l.length>0,k=T.useCallback(()=>{if(!v){y(null);return}const C=xc({resourceUri:x,query:b});y(C)},[v,x,b]);return{embeddedQueryResult:h,queryString:b,resourceUri:x,executeQuery:k,canExecute:v}}function vx(e,n=5e3){const r=e.dimensionSpecs[0]?.source??"",o=e.dimensionSpecs[0]?.model??"",{filterStates:i,updateFilter:l,clearAllFilters:a,getActiveFilters:u}=Sc({dimensionSpecs:e.dimensionSpecs}),d=T.useMemo(()=>u(),[i,u]),{data:h,noRowsMatchedFilter:y,isLoading:b,isError:x,error:v,refetch:k}=wc({environment:e.environment,package:e.package,indexLimit:e.indexLimit,dimensionSpecs:e.dimensionSpecs,versionId:e.versionId,activeFilters:d}),C=b&&!h,{embeddedQueryResult:S,queryString:j,executeQuery:M,canExecute:O}=kc({environment:e.environment,package:e.package,model:o,source:r,filterSelections:d,limit:n,fields:e.selectFields,versionId:e.versionId});return{filterStates:i,updateFilter:l,clearAllFilters:a,activeFilters:d,data:h,noRowsMatchedFilter:y,isLoading:b,isInitialLoading:C,isError:x,error:v,refetch:k,embeddedQueryResult:S,queryString:j,executeQuery:M,canExecute:O}}function bx({modelPath:e,query:n,sourceName:r,queryName:o,enabled:i=!0,resourceUri:l}){const{environmentName:a,packageName:u,versionId:d}=c.parseResourceUri(l),{apiClients:h}=q.useServer(),{data:y,isSuccess:b,isError:x,error:v,isLoading:k}=c.useQueryWithApiError({queryKey:["rawQueryData",a,u,e,d,n,r,o],queryFn:({signal:S})=>h.models.executeQueryModel(a,u,e,{query:n,sourceName:r,queryName:o,versionId:d},void 0,void 0,{signal:S}),enabled:i});return{data:b&&y?.data?.result?(()=>{try{return JSON.parse(y.data.result).data?.array_value||[]}catch(S){return console.error("Failed to parse query result:",S),[]}})():[],isSuccess:b,isError:x,error:v,isLoading:k}}exports.AddButton=c.AddButton;exports.ApiErrorDisplay=c.ApiErrorDisplay;exports.AppDialog=c.AppDialog;exports.DRILL_SELF=c.DRILL_SELF;exports.DashboardTile=c.DashboardTile;exports.DocumentNotFoundError=c.DocumentNotFoundError;exports.DocumentStorageProvider=c.DocumentStorageProvider;exports.GivenInput=c.GivenInput;exports.GivensPanel=c.GivensPanel;exports.INITIAL_RENDER_HEIGHT=c.INITIAL_RENDER_HEIGHT;exports.LOADING_COPY=c.LOADING_COPY;exports.Loading=c.Loading;exports.MODEL_CELL_MAX_HEIGHT=c.MODEL_CELL_MAX_HEIGHT;exports.MOTION_FAST=c.MOTION_FAST;exports.NOTEBOOK_CELL_MAX_HEIGHT=c.NOTEBOOK_CELL_MAX_HEIGHT;exports.Prose=c.Prose;exports.REPORT_EDIT_PARAM=c.REPORT_EDIT_PARAM;exports.RESTRICTED_NOTICE=c.RESTRICTED_NOTICE;exports.RESULTS_DIALOG_MAX_HEIGHT=c.RESULTS_DIALOG_MAX_HEIGHT;exports.ResultContainer=c.ResultContainer;exports.ResultPanel=c.ResultPanel;exports.STICKY_CONTROLS_Z=c.STICKY_CONTROLS_Z;exports.STICKY_TOP_VAR=c.STICKY_TOP_VAR;exports.SecondaryButton=c.SecondaryButton;exports.TILE_MAX_HEIGHT=c.TILE_MAX_HEIGHT;exports.TILE_MIN_HEIGHT=c.TILE_MIN_HEIGHT;exports.TileCard=c.TileCard;exports.TileFilterTag=c.TileFilterTag;exports.TileHeading=c.TileHeading;exports.UNCAPPED_CONTAINER_HEIGHT=c.UNCAPPED_CONTAINER_HEIGHT;exports.UnsavedChangesDialog=c.UnsavedChangesDialog;exports.buildTableCssVars=c.buildTableCssVars;exports.clearReportDraft=c.clearReportDraft;exports.contentNodeDepth=c.contentNodeDepth;exports.dangerTextColor=c.dangerTextColor;exports.documentPreamble=c.documentPreamble;exports.documentSlug=c.documentSlug;exports.draftStorageAvailable=c.draftStorageAvailable;exports.drillDestinations=c.drillDestinations;exports.drillValueToFilter=c.drillValueToFilter;exports.encodeDrillValue=c.encodeDrillValue;exports.encodeResourceUri=c.encodeResourceUri;exports.humanizeSlug=c.humanizeSlug;exports.initialResultHeight=c.initialResultHeight;exports.isDocumentNotFound=c.isDocumentNotFound;exports.isDrillTargetPath=c.isDrillTargetPath;exports.localGivenSpec=c.localGivenSpec;exports.locateReport=c.locateReport;exports.malloyIdentifier=c.malloyIdentifier;exports.malloyLiteral=c.malloyLiteral;exports.measureContentHeight=c.measureContentHeight;exports.parseResourceUri=c.parseResourceUri;exports.queryResultKey=c.queryResultKey;exports.reducedMotionSx=c.reducedMotionSx;exports.remeasuresAfterReady=c.remeasuresAfterReady;exports.reportClasses=c.reportClasses;exports.reportDraftKey=c.reportDraftKey;exports.reportEditRoute=c.reportEditRoute;exports.reportRoute=c.reportRoute;exports.reportRoutePath=c.reportRoutePath;exports.resolveDrill=c.resolveDrill;exports.resolveDrillTarget=c.resolveDrillTarget;exports.resolveResultHeight=c.resolveResultHeight;exports.resultSizing=c.resultSizing;exports.scrollBehavior=c.scrollBehavior;exports.tileIgnoredFilterLabels=c.tileIgnoredFilterLabels;exports.useCompiledDocument=c.useCompiledDocument;exports.useDocumentControls=c.useDocumentControls;exports.useDocumentLocation=c.useDocumentLocation;exports.useDocumentStorage=c.useDocumentStorage;exports.useDrillSelf=c.useDrillSelf;exports.useGivensState=c.useGivensState;exports.useOptionalDocumentStorage=c.useOptionalDocumentStorage;exports.useQueryResult=c.useQueryResult;exports.useReportListing=c.useReportListing;exports.useSuggestOptions=c.useSuggestOptions;exports.visibleWithoutHoverSx=c.visibleWithoutHoverSx;exports.withPreamble=c.withPreamble;exports.DEFAULT_THEME=q.DEFAULT_THEME;exports.DEFAULT_UI=q.DEFAULT_UI;exports.MONO_FONT_FAMILY=q.MONO_FONT_FAMILY;exports.PALETTE=q.PALETTE;exports.SURFACE_TINT=q.SURFACE_TINT;exports.ServerProvider=q.ServerProvider;exports.ThemeProvider=q.ThemeProvider;exports.accentFor=q.accentFor;exports.contrastRatio=q.contrastRatio;exports.mergeUi=q.mergeUi;exports.resolveMode=q.resolveMode;exports.resolveTheme=q.resolveTheme;exports.usePublisherTheme=q.usePublisherTheme;exports.useServer=q.useServer;exports.canRetryRequest=so.canRetryRequest;exports.DRILL_CELL_CLASS=fn.DRILL_CELL_CLASS;exports.RenderedResult=fn.RenderedResult;exports.buildMalloyExplicitTheme=fn.buildMalloyExplicitTheme;exports.buildVegaThemeOverride=fn.buildVegaThemeOverride;exports.drillableFieldNames=fn.drillableFieldNames;exports.markDrillableCells=fn.markDrillableCells;exports.readChartAnnotations=fn.readChartAnnotations;exports.BackLink=od;exports.BrowserDocumentStorage=rx;exports.ConnectionExplorer=sl;exports.DOC_LINKS=Vt;exports.DashboardView=Ga;exports.DataAppViewer=_d;exports.DimensionFilter=tf;exports.DownloadRowsCsv=Ha;exports.EmbeddedQueryResult=ix;exports.Environment=Dh;exports.Home=gf;exports.Materializations=vl;exports.Model=hy;exports.ModelExplorer=Eo;exports.ModelExplorerDialog=Io;exports.ModelViewer=oc;exports.NarrowEditGate=id;exports.NewDocumentDialog=uc;exports.PUBLISHER_COLOR_SCHEME_APPLIED_MESSAGE_TYPE=Za;exports.PUBLISHER_COLOR_SCHEME_MESSAGE_TYPE=Ka;exports.PUBLISHER_COLOR_SCHEME_REQUEST_MESSAGE_TYPE=Qa;exports.Package=Jy;exports.Packages=ol;exports.QueryResult=vc;exports.Report=cc;exports.SourcesExplorer=ac;exports.VersionSwitch=yc;exports.createEmbeddedQueryResult=xc;exports.documentRoute=cx;exports.extractDimensionSpecs=af;exports.extractSourceFromQuery=cf;exports.generateFilterClause=lf;exports.getDimensionKey=hn;exports.getJoinedSources=nf;exports.groupEntitiesBySource=jl;exports.injectWhereClause=uf;exports.isNarrowScreen=$a;exports.legacyAliasOf=lx;exports.locateDocument=ux;exports.locateReportByName=bc;exports.modelQueryKey=sc;exports.packageFileUrl=Ja;exports.packageVersionsQueryKey=Do;exports.parseAllSourceInfos=of;exports.parseDimensionFilterAnnotation=il;exports.parseNotebookFilterAnnotation=rf;exports.runQueryKey=Co;exports.setConsoleEventHandler=Xd;exports.useDimensionFilters=Sc;exports.useDimensionFiltersFromSpec=vx;exports.useDimensionFiltersQuery=kc;exports.useDimensionalFilterRangeData=wc;exports.useDraftLayout=ox;exports.useDrill=oo;exports.useGivenUrlParams=md;exports.useInvalidatePackage=gc;exports.useModelData=Oo;exports.useModelGivens=lc;exports.useNarrowScreen=Ra;exports.usePackageVersions=mc;exports.useRawQueryData=bx;exports.useRouterClickHandler=ad;
|