@malloy-publisher/sdk 0.12.3 → 0.12.5

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.
@@ -251,6 +251,10 @@ export interface BigqueryConnection {
251
251
  * Query timeout in milliseconds
252
252
  */
253
253
  'queryTimeoutMilliseconds'?: string;
254
+ /**
255
+ * Copy table and column descriptions from BigQuery onto the schema as `#(dbmeta)` annotations.
256
+ */
257
+ 'dbmeta'?: boolean;
254
258
  }
255
259
  export interface BuildGraph {
256
260
  'connectionName': string;
@@ -2576,7 +2580,7 @@ export interface PackageWarningsInner {
2576
2580
  */
2577
2581
  'message'?: string;
2578
2582
  /**
2579
- * A stable identifier for the finding\'s family, for a client that acts on it rather than only showing it; absent for a family that has none yet. `deprecated-malloynb-notebook`: a `.malloynb` notebook, the deprecated cell format (one per file, `model` naming it). `deprecated-filter-annotation`: a source declaring deprecated `#(filter)` annotations (one per declaring source, `model` naming its file and `subject` the source). `report-name-ambiguous`: two or more grid reports share a basename, so the deprecated `GET …/dashboards/{name}` route answers 409 for it (one per name, `subject` naming it and the message every path; `warn`). `classification-coverage`: a published source with a dimension or measure that carries no `#(classification)` while some field in the package does (one per source, `model` naming its file and `subject` the source; `warn`; see docs/classification.md). `classification-malformed`: a `#(classification)` annotation that names no single class (one per field, `subject` the source; `warn`). `entities-…` (`entities-not-a-dimension`, `entities-parameterized-source`, `entities-multiple-required-filters`, `entities-sharing-not-allowed-on-dimension`, `entities-schedule-not-allowed-on-dimension`, `entities-required-filter-missing-dimension`, `entities-required-filter-non-public-dimension`): an `#(index)` or required `#(filter)` an index cannot honor, left out of `GET …/entities` (`model` its file; `warn`). The per-file report findings (`notebook-…`, `report-…`) and the report curation findings (`report-on-surface`, `index-is-not-a-report`). The message wording may change; the code does not.
2583
+ * A stable identifier for the finding\'s family, for a client that acts on it rather than only showing it; absent for a family that has none yet. `deprecated-malloynb-notebook`: a `.malloynb` notebook, the deprecated cell format (one per file, `model` naming it). `deprecated-filter-annotation`: a source declaring deprecated `#(filter)` annotations (one per declaring source, `model` naming its file and `subject` the source). `report-name-ambiguous`: two or more grid reports share a basename, so the deprecated `GET …/dashboards/{name}` route answers 409 for it (one per name, `subject` naming it and the message every path; `warn`). `classification-coverage`: a published source with a dimension or measure that carries no `#(classification)` while some field in the package does (one per source, `model` naming its file and `subject` the source; `warn`; see docs/classification.md). `classification-malformed`: a `#(classification)` annotation that names no single class (one per field, `subject` the source; `warn`). `classification-downgrade`: a field that declares a lower class than the fields its expression reads, which Publisher cannot tell from a real de-identification, so a review has to (one per field, `subject` the source; `warn`; a plain copy under `#(carries)` refuses the load instead). `join-bypass`: an author join from a published source to one with a stricter gate, which the join does not carry (one per join, or one for a walk cut short at the join bound; always a `warn`, never a load refusal; see docs/authorize.md). `entities-…` (`entities-not-a-dimension`, `entities-parameterized-source`, `entities-multiple-required-filters`, `entities-sharing-not-allowed-on-dimension`, `entities-schedule-not-allowed-on-dimension`, `entities-required-filter-missing-dimension`, `entities-required-filter-non-public-dimension`): an `#(index)` or required `#(filter)` an index cannot honor, left out of `GET …/entities` (`model` its file; `warn`). The per-file report findings (`notebook-…`, `report-…`) and the report curation findings (`report-on-surface`, `index-is-not-a-report`). The message wording may change; the code does not.
2580
2584
  */
2581
2585
  'code'?: string;
2582
2586
  /**
package/dist/index.cjs.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";var Gu=Object.create;var Ci=Object.defineProperty;var Yu=Object.getOwnPropertyDescriptor;var Ku=Object.getOwnPropertyNames;var Qu=Object.getPrototypeOf,Zu=Object.prototype.hasOwnProperty;var Xu=(e,n,r,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of Ku(n))!Zu.call(e,i)&&i!==r&&Ci(e,i,{get:()=>n[i],enumerable:!(s=Yu(n,i))||s.enumerable});return e};var ji=(e,n,r)=>(r=e!=null?Gu(Qu(e)):{},Xu(n||!e||!e.__esModule?Ci(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"),j=require("react"),c=require("./useCompiledDocument--Z7vKZL5.cjs.js"),q=require("./ServerProvider-CqL6xzta.cjs.js"),yt=require("@tanstack/react-query"),Sr=require("@mui/system"),_t=require("@mui/icons-material"),Ju=require("@malloydata/malloy-tag"),io=require("./text-entry-BJwltZiy.cjs.js"),fn=require("./RenderedResult-C2arX5Zz.cjs.js"),ed=require("@malloydata/malloy-filter"),Yr=require("react-router-dom");function td(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}return n.default=e,Object.freeze(n)}const we=td(j),nd=c.createSvgIcon(t.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function rd({label:e,href:n,onClick:r}){const s=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:s,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(nd,{sx:{fontSize:18}}),"Back to ",e]})}const Aa="(max-width:599.95px)";function La(){return m.useMediaQuery(Aa,{noSsr:!0})}function Na(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Aa).matches}function sd({children:e}){const[n]=j.useState(Na),[r,s]=j.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:()=>s(!0),children:"Edit anyway"})]})}function od(){const e=Yr.useNavigate();return(n,r)=>{if(!r||!r.metaKey&&!r.ctrlKey&&!r.shiftKey&&r.button!==1){e(n);return}const s=new URL(n,window.location.href).href;(r.metaKey||r.ctrlKey||r.button===1||r.shiftKey)&&window.open(s,"_blank")}}function Pa(e,n){return e.flatMap(({filter:r})=>{if(r.kind!=="literal_equality"||r.expression.kind!=="field_reference")return[];const s=id(r.value,n);return s===void 0?[]:[{field:r.expression.name,label:s,expression:r.expression}]})}function _a(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=za(e.date_value);return r&&`@${r[0]}-${r[1]}-${r[2]}`}case"timestamp_literal":{const r=qa(e.timestamp_value,n);return r&&`@${r[0]}-${r[1]}-${r[2]} ${r[3]}:${r[4]}:${r[5]}${Wa(e.timestamp_value)}`}default:return}}function id(e,n){switch(e.kind){case"string_literal":return e.string_value;case"null_literal":return"null";case"date_literal":{const r=za(e.date_value);return r&&Ti([...r,"00","00","00"],e.granularity??"day")}case"timestamp_literal":{const r=qa(e.timestamp_value,n);return r&&Ti(r,e.granularity??"second")+(e.granularity===void 0?Wa(e.timestamp_value):"")}default:return _a(e)}}function za(e){const n=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);return n?[n[1],n[2],n[3]]:void 0}function Wa(e){const n=/:\d{2}\.(\d+)/.exec(e)?.[1]?.replace(/0+$/,"");return n?`.${n}`:""}function qa(e,n){const r=new Date(e);if(Number.isNaN(r.getTime()))return;let s;try{s=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=>s.find(a=>a.type===l)?.value??"";return[i("year").padStart(4,"0"),i("month"),i("day"),i("hour"),i("minute"),i("second")]}function Ti([e,n,r,s,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} ${s}`;case"minute":return`${e}-${n}-${r} ${s}:${i}`;default:return`${e}-${n}-${r} ${s}:${i}:${l}`}}const ad="drill_metadata_corrected",Xr=e=>e,An=e=>{try{return e?.()}catch{return}},Ba=e=>An(e.isBasic?.bind(e))===!0&&An(e.wasDimension?.bind(e))===!0,ld=e=>[e.isString,e.isNumber,e.isBoolean,e.isTime].some(n=>An(n?.bind(e))===!0);function Jr(e){const n=e.metadataTag?.text("drill_expression","code");return n===void 0||n.trim()===""?void 0:n}function Va(e){const n=[];for(let r=e.parent;r;r=r.parent)n.push(r);return n}function Ha(e){const n=Va(e),s=(n[n.length-1]??e).metadataTag,i=s?.text("source","name");if(!i||!s?.array||s.array("source","parameters")!==void 0||s.has?.(ad)!==!0)return;const l=[];for(const d of[...n].reverse())if(An(d.isArray?.bind(d))===!0){if(d.metadataTag?.has?.("drillable")!==!0)return;for(const u of d.metadataTag?.array?.("drill_filters")??[]){const h=u.text("code");if(!h)return;l.push(h)}}const a=s?.text("query_name");return{source:i,filters:l,...a&&!a.startsWith("__")?{queryName:a}:{}}}function Er(e){const n=new Set;for(const r of Va(e))for(const s of r.fields??[])Ba(s)&&n.add(s);return[...n]}function Ua(e){const n=new Set(Er(e).filter(r=>An(r.isTime?.bind(r))===!0).map(r=>An(r.getEffectiveQueryTimezone?.bind(r))));return n.size>1?null:[...n][0]}function Mi(e){return!Ba(e)||Jr(e)===void 0||Ha(e)===void 0||Ua(e)===null?!1:Er(e).every(n=>Jr(n)!==void 0&&n.drillStableExpression!==void 0&&ld(n))}function cd(e,n){const r=Er(e),s=[],i=new Set;for(const l of n){if(l.kind==="drill")continue;const{filter:a}=l;if(a.kind!=="literal_equality")return;const d=JSON.stringify(a.expression),u=r.find(g=>JSON.stringify(g.drillStableExpression)===d),h=u&&Jr(u);if(u===void 0||h===void 0)return;s.push({code:h,value:a.value}),i.add(u)}return r.every(l=>i.has(l))&&s.length>0?s:void 0}const ud=360;function Gs(e){return e?e.getLabel?.()??e.tag?.text("label")??Xr(e).metadataTag?.text("label")??e.name:""}function dd(e,n){const r=e.drillClauses?Pa(e.drillClauses,e.timezone):[];if(r.length===0)return`${Gs(n)}: ${e.label}`;const s=Er(Xr(n));return r.map(i=>{const l=JSON.stringify(i.expression),a=s.find(d=>JSON.stringify(d.drillStableExpression)===l);return`${a?Gs(a):i.field}: ${i.label}`}).join(", ")}function ao({onNavigate:e,onSelf:n,destinationTitle:r,canSelf:s,onRows:i}){const[l,a]=j.useState(null),d=j.useCallback((S,T)=>S.filter(M=>M===c.DRILL_SELF?n!==void 0&&(s?.(T)??!0):e!==void 0),[e,n,s]),u=j.useCallback((S,T,M)=>{if(T===c.DRILL_SELF){n?.(S.given,S.rawValue);return}e?.({path:T,dashboard:T,givens:{[S.given]:S.value}},M)},[e,n]),h=j.useCallback(S=>{if(!i||S.noRows||S.isHeader||!S.field)return;const T=Xr(S.field);if(!Mi(T))return;const M=Ha(T);if(M===void 0)return;const O=S.drillClauses;let I;if(O!==void 0){const _=cd(T,O);if(_===void 0)return;I={dimensions:_}}else{const _=Jr(T);if(_===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;I={code:_}}const R=Ua(T)??void 0;return{field:S.field.name,rawValue:S.value,label:c.drillValueLabel(S.value),target:M,...I,...S.context===void 0?{}:{context:S.context},...O===void 0?{}:{drillClauses:O},...R===void 0?{}:{timezone:R}}},[i]),g=j.useCallback(S=>{const T=c.resolveDrill(S),M=h(S),O=T?Array.from(new Set(d(T.to,T.given))).sort((_,$)=>+($===c.DRILL_SELF)-+(_===c.DRILL_SELF)):[],I=`${Gs(S.field)}: ${T?.label??c.drillValueLabel(S.value)}`,R=O.map(_=>({key:`to:${_}`,label:_===c.DRILL_SELF?`Filter to ${I}`:`Open ${r?.(_)??c.humanizeSlug(_.split("/").pop()??_)} (${I})`,run:()=>{T&&u(T,_,S.event)}}));M&&S.field&&R.push({key:"rows",label:`Show rows (${dd(M,S.field)})`,run:()=>i?.(M)}),R.length!==0&&a({items:R,top:S.event?.clientY??0,left:S.event?.clientX??0})},[u,d,i,h,r]),b=j.useCallback(S=>d(c.drillDestinations(S),c.drillGivenName(S)).length>0,[d]),x=j.useCallback(S=>i!==void 0&&Mi(Xr(S)),[i]),v=j.useMemo(()=>({onClick:g,canDrill:S=>b(S)||x(S)}),[g,b,x]),C=j.useCallback((S,T)=>({canDrill:M=>b(M)||T&&x(M),onClick:M=>g({...M,...S===void 0?{}:{context:S},...T?{}:{noRows:!0}})}),[g,b,x]),k=j.useCallback(()=>a(null),[]);return{drill:v,bindingFor:C,drillMenu:t.jsx(m.Menu,{open:l!==null,onClose:k,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:()=>{k(),S.run()},sx:{maxWidth:ud},children:t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.label})},S.key))})}}const hd=e=>{const n=we.useRef({});return we.useEffect(()=>{n.current=e}),n.current};function fd(){const[e]=Yr.useSearchParams(),n=Yr.useNavigate(),r=Yr.useLocation(),s=j.useMemo(()=>Object.fromEntries(e.entries()),[e]),i=j.useRef(new Set),l=j.useRef(null),a=j.useCallback(h=>{const g=l.current,b=new URLSearchParams(g?.key===r.key?g.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]),d=j.useCallback((h,g)=>{const b=new Set([...g,...i.current]);i.current=new Set([...i.current,...Object.keys(h),...g]),a(x=>{for(const v of b)Object.prototype.hasOwnProperty.call(h,v)||x.delete(v);for(const[v,C]of Object.entries(h))x.set(v,C)})},[a]),u=j.useCallback((h,g)=>a(b=>{g===void 0?b.delete(h):b.set(h,g)}),[a]);return{params:s,onGivensChange:d,setParam:u}}const pd=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 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 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 Ga(e){const n=e.data;return n?.kind!=="array_cell"?[]:n.array_value.flatMap(r=>r.kind==="record_cell"?[r.record_value]:[])}function gd(e){const n=e.schema.fields;return`\uFEFF${[n.map(s=>pr(fr(s.name))).join(","),...Ga(e).map(s=>n.map((i,l)=>md(s[l])).join(","))].join(`\r
2
2
  `)}\r
3
- `}function yd(e,n){return[e,"rows",...n].join("_").replace(/[^A-Za-z0-9._-]+/g,"_").replace(/_+/g,"_").replace(/^[_.]+|[_.]+$/g,"").slice(0,120)||"rows"}function xd(e,n,r){return r==="server_default"&&n!==void 0&&e>=n?n:void 0}const Oi="Download the rows behind this value as CSV, up to the server's row limit",vd=4e4;function bd(e,n){const r=URL.createObjectURL(new Blob([e],{type:"text/csv;charset=utf-8"})),s=document.createElement("a");s.href=r,s.download=n,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),vd)}function wd(e){const r=e?.response?.data?.message;return typeof r=="string"&&r!==""?r:e instanceof Error&&e.message!==""?e.message:"The request failed."}function Ya({query:e,preamble:n,environmentName:r,packageName:s,modelPath:i,versionId:l,givens:a,fileName:d}){const{apiClients:u}=q.useServer(),[h,g]=j.useState(!1),[b,x]=j.useState(Oi),[v,C]=j.useState(void 0),k=j.useRef(void 0);j.useEffect(()=>()=>k.current?.abort(),[]);const S=async()=>{k.current?.abort();const T=new AbortController;k.current=T,g(!0),C(void 0);try{const M=await u.models.executeQueryModel(r,s,i,{query:n===void 0?e:c.withPreamble(n,e),givens:a,versionId:l},void 0,{signal:T.signal});if(T.signal.aborted)return;const O=M.data,I=JSON.parse(O.result??"{}"),R=xd(Ga(I).length,O.queryRowLimit,O.queryRowLimitSource);x(R===void 0?Oi:`First ${R} rows: the server's row limit, so there may be more`),bd(gd(I),R===void 0?`${d}.csv`:`${d}_first_${R}_rows_server_limit.csv`)}catch(M){if(T.signal.aborted)return;C(`Download failed: ${wd(M)}`)}finally{k.current===T&&(k.current=void 0,g(!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(pd,{fontSize:"small"}),onClick:()=>void S(),disabled:h,children:"Download CSV"})})})]})}const Ka=200;function Sd(e){const{target:n}=e;if(n!==void 0&&!(e.dimensions===void 0&&e.code===void 0))return{...e,target:n}}function Ii(e,n=Ka){const r=Cd(e);if(r===void 0)return;const s=[...e.target.filters,...r].join(", "),i=e.timezone?`timezone: '${c.escapeMalloyString(e.timezone)}'; `:"",l=n===null?"":`; limit: ${n}`,a=kd(e.target.source);if(a!==void 0)return`run: ${a} -> { ${i}where: ${s}; select: *${l} }`}function kd(e){return io.isBareName(e)?e:e.includes("`")?void 0:`\`${e}\``}function js(e){return/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(e)?e:`(${e})`}function Cd(e){if(e.dimensions){const r=[];for(const{code:s,value:i}of e.dimensions){if(i.kind==="null_literal"){r.push(`${js(s)} is null`);continue}const l=_a(i,e.timezone);if(l===void 0)return;r.push(`${js(s)} = ${l}`)}return r}const n=c.malloyLiteral(e.rawValue);return e.code!==void 0&&n?[`${js(e.code)} = ${n}`]:void 0}const jd="This value cannot be written as a filter, so its rows cannot be fetched.";function Ei(e){const n=e.drillClauses?Pa(e.drillClauses,e.timezone):[];return n.length>0?n:[{field:e.field,label:e.label}]}function Td({request:e,environmentName:n,packageName:r,versionId:s,modelPath:i,preamble:l,givens:a,onClose:d,onDone:u,actions:h}){const{theme:g}=q.usePublisherTheme(),b=e?Ii(e):void 0,x=e?Ii(e,null):void 0,v=e&&x!==void 0?{query:x,...l===void 0?{}:{preamble:l},environmentName:n,packageName:r,modelPath:i,...s===void 0?{}:{versionId:s},givens:a,fileName:yd(e.target.source,Ei(e).map(C=>C.label))}:void 0;return t.jsxs(m.Dialog,{open:e!==void 0,onClose:d,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"," ",Ei(e).map((C,k)=>t.jsxs(j.Fragment,{children:[k>0&&" and ",t.jsx(m.Box,{component:"code",sx:{fontSize:"0.9em"},children:C.field})," ","is ",C.label]},k))]}):"Rows",t.jsx(m.Typography,{component:"div",variant:"caption",sx:{color:g.tileTitle,mt:.25},children:e?`The first ${Ka} 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(Ya,{...v})),t.jsx(m.IconButton,{onClick:d,"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:jd}),b!==void 0&&t.jsx(Md,{query:l===void 0?b:c.withPreamble(l,b),environmentName:n,packageName:r,...s===void 0?{}:{versionId:s},modelPath:i,givens:a,...u?{onDone:u}:{}})]}),t.jsxs(m.DialogActions,{sx:{px:3,py:1.5},children:[b!==void 0&&t.jsx(m.Typography,{variant:"caption",sx:{mr:"auto",color:g.tileTitle,fontFamily:g.ui.font.mono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:b,children:b}),t.jsx(m.Button,{onClick:d,children:"Close"})]})]})}function Md({query:e,environmentName:n,packageName:r,versionId:s,modelPath:i,givens:l,onDone:a}){const d=c.useQueryResult({environmentName:n,packageName:r,modelPath:i,...s===void 0?{}:{versionId:s},query:e,givens:l}),{isSuccess:u,isError:h}=d,g=j.useRef(void 0);return j.useEffect(()=>{g.current=c.now()},[e]),j.useEffect(()=>{g.current===void 0||!u&&!h||(a?.(u,c.now()-g.current),g.current=void 0)},[u,h,a]),t.jsx(m.Box,{sx:{p:1},children:t.jsx(c.ResultPanel,{state:d,context:e})})}function ss({manifest:e,environmentName:n,packageName:r,versionId:s,documentName:i,givens:l,onGivensChange:a,onNavigate:d,height:u,maxResultSize:h,controlsLayout:g="bar",preamble:b,runModelPath:x,hiddenGivens:v,literalReads:C,onLinkNavigate:k,actions:S,rowsActions:T}){const M=j.useMemo(()=>k?{environmentName:n,packageName:r,sourcePath:e.path??i,onNavigate:k}:void 0,[n,r,e.path,i,k]),O=j.useMemo(()=>(e.givens??[]).filter(ae=>!(b!==void 0&&ae.secure===!0)&&!(ae.name!==void 0&&v?.includes(ae.name))),[e,v,b]),I=j.useMemo(()=>l===void 0?void 0:Object.fromEntries(Object.entries(l).filter(([,ae])=>typeof ae=="string")),[l]),R=c.useDocumentControls({specs:O,loaded:!0,startingValues:e.startingGivens,params:I,onGivensChange:a,documentKey:`${n}/${r}/${s??""}/${i}`,autorun:e.autorun!==!1,environmentName:n,packageName:r,modelPath:x??e.path,versionId:s,documentName:i,...b!==void 0?{preamble:b}:{},...l?{hostGivens:l}:{}}),{applied:_,declaredTypes:$,canSelf:B,onSelf:F}=R,N=c.useReportEvents(),H=j.useMemo(()=>{const ae=new Set((e.tiles??[]).flatMap(Z=>Z.givenNames??[]));return Object.fromEntries(Object.entries(l??{}).filter(([Z])=>ae.has(Z)&&!$.has(Z)))},[e,l,$]),[D,W]=j.useState(void 0),K=j.useCallback(ae=>{const Z=Sd(ae);Z!==void 0&&W(Z)},[]),J=j.useMemo(()=>c.withHostGivens(c.givensToRequest(_,$),H),[_,$,H]),{reports:X}=c.useReportListing(n,r,s,d!==void 0),G=j.useCallback(ae=>{const Z=c.resolveDrillTarget(ae,X);if(Z.kind!=="path")return;const ce=Z.report.path;return X.find(be=>be.path===ce)?.title||void 0},[X]),{bindingFor:Q,drillMenu:ie}=ao({onNavigate:d,onSelf:F,canSelf:B,onRows:K,destinationTitle:G}),z=j.useCallback((ae,Z)=>Q(ae,Z!==!0),[Q]),{columns:re,layout:se,tileMaxHeight:ne,tableMaxHeight:Me}=c.layoutRules(e.layout,e.dashboardColumns),oe=j.useMemo(()=>c.missingRequiredGivens(O,_,l),[O,_,l]);if(e.error)return t.jsx(c.ReportPage,{layout:se,header:t.jsx(Di,{manifest:e,links:M,actions:S}),children:t.jsx(m.Alert,{severity:"error",children:e.error})});const ue=x??e.path,De=e.tiles??[],Ne=c.isPlaced(De);return t.jsxs(c.ReportPage,{layout:se,header:t.jsx(Di,{manifest:e,links:M,actions:S}),controls:O.length>0?t.jsx(c.StickyControls,{children:t.jsx(c.GivensPanel,{...R.panel,layout:g})}):void 0,children:[oe.length>0&&t.jsx(m.Alert,{severity:"info",children:c.requiredPrompt(oe)}),ue===void 0?t.jsx(m.Alert,{severity:"error",children:"This dashboard has no model path, so there is nothing to run."}):De.length>0?t.jsx(c.DashboardGrid,{tiles:De,columns:re,minTilePx:c.MIN_TILE_PX,rowGapPx:c.GRID_GAP_PX,keyOf:(ae,Z)=>`${Z}:${ae.kind==="text"?`text:${ae.name}`:ae.query}`,renderTile:(ae,Z)=>ae.kind==="text"||ae.query===void 0?t.jsx(m.Box,{sx:ae.rowspan!==void 0||Ne?{minHeight:0,overflow:"auto"}:void 0,children:t.jsx(Od,{markdown:ae.markdown??"",links:M})}):t.jsx(c.DashboardTile,{index:Z,environmentName:n,packageName:r,versionId:s,modelPath:ue,tile:ae.query,label:ae.label,subtitle:ae.subtitle,borderless:ae.borderless,givens:_,hostGivens:H,declaredTypes:$,givenNames:ae.givenNames,height:ae.rowspan!==void 0||Ne?c.tileHeightPx(ae.rowspan??c.PLACED_DEFAULT_ROWSPAN.query):se==="grid"?u??ne:ne,tableMaxHeight:Me,fixedHeight:ae.rowspan!==void 0||Ne,maxResultSize:h,drill:z(ae.query,ae.restricted),ignoredFilters:c.tileIgnoredFilterLabels(ae.givenNames&&(ae.query&&C?.[ae.query]?[...ae.givenNames,...C[ae.query]]:ae.givenNames),O),...b!==void 0?{preamble:b,restricted:ae.restricted}:{},...(()=>{const ce=c.waitingOn(oe,ae.givenNames);return ce.length>0?{waitingFor:c.waitingText(ce)}:{}})()})}):t.jsx(m.Alert,{severity:"warning",children:"This dashboard names neither a query nor any tiles."}),ie,ue!==void 0&&t.jsx(Td,{request:D,environmentName:n,packageName:r,...s===void 0?{}:{versionId:s},modelPath:ue,...b===void 0?{}:{preamble:b},givens:J,...T===void 0?{}:{actions:T},onClose:()=>W(void 0),onDone:(ae,Z)=>{D&&N.emit({type:"report.rows_shown",source:D.target.source,view:D.target.queryName??"",field:D.field,ok:ae,durationMs:Z})}})]})}function Od({markdown:e,links:n}){return t.jsx(c.TextTileFrame,{children:t.jsx(c.Prose,{variant:"document",links:n,children:e})})}function Di({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 Qa=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"})),Id="publisher:resize";function Ed(e){return typeof e=="object"&&e!==null&&e.type===Id&&typeof e.height=="number"}function Za(e){return e.replace(/\/api\/v0\/?$/,"")}function Xa({server:e,environmentName:n,packageName:r,path:s,versionId:i}){const l=s.startsWith("public/")?s.slice(7):s,a=`${Za(e)}/environments/${encodeURIComponent(n)}/packages/${encodeURIComponent(r)}/`+l;return i===void 0?a:`${a}${a.includes("?")?"&":"?"}versionId=${encodeURIComponent(i)}`}function Dd(e){try{const{environmentName:n,packageName:r,modelPath:s,versionId:i}=c.parseResourceUri(e);return!n||!r||!s?null:{environmentName:n,packageName:r,dataAppPath:s,versionId:i}}catch{return null}}function Fd({resourceUri:e}){const{server:n,apiClients:r}=q.useServer(),s=Dd(e),i=s?.environmentName??"",l=s?.packageName??"",a=s?.dataAppPath??"",d=s?.versionId,u=j.useMemo(()=>Xa({server:n,environmentName:i,packageName:l,path:a,...d!==void 0?{versionId:d}:{}}),[n,i,l,a,d]),g=c.useQueryWithApiError({queryKey:["data-apps",i,l,d],queryFn:()=>r.dataApps.listDataApps(i,l,d),enabled:!!s}).data?.data?.find(S=>S.path===a),b=g?.title??a,x=g?.fit==="viewport",v=j.useRef(null),[C,k]=j.useState(120);return j.useEffect(()=>{if(x)return;function S(T){Ed(T.data)&&T.source===v.current?.contentWindow&&T.data.height>0&&k(Math.ceil(T.data.height))}return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[x]),s?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:u,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:t.jsx(Qa,{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:u,title:b,sandbox:"allow-scripts allow-same-origin allow-forms",style:{display:"block",width:"100%",height:x?"100%":C,border:0}})})]}):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 Pt({title:e,count:n,description:r,action:s,children:i}){const l=j.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,")"]})]}),s]}),r&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:r}),t.jsx(m.Box,{children:i})]})}function $d({resourceUri:e}){const{environmentName:n}=c.parseResourceUri(e),{apiClients:r}=q.useServer(),[s,i]=j.useState(!1),l=90,{data:a,isSuccess:d,isError:u,error:h}=c.useQueryWithApiError({queryKey:["about",n],queryFn:()=>r.environments.getEnvironment(n,!1)}),g=a?.data?.readme||"",b=g.split(/\s+/),x=b.length>l,v=b.slice(0,l).join(" ");return t.jsxs(t.Fragment,{children:[!d&&!u&&t.jsx(c.Loading,{text:"Fetching About..."}),d&&g&&t.jsxs(Pt,{title:"Readme",children:[t.jsx(c.Prose,{variant:"caption",children:s||!x?g:v}),x&&t.jsx(m.Box,{sx:{mt:1},children:t.jsx(c.SecondaryButton,{label:s?"Read less":"Read more",onClick:()=>i(!s)})})]}),u&&t.jsx(c.ApiErrorDisplay,{error:h,context:`${n} > About`})]})}function Rd(e={}){const{autoHideDuration:n=null,disableWindowBlurListener:r=!1,onClose:s,open:i,resumeHideDuration:l}=e,a=c.useTimeout();we.useEffect(()=>{if(!i)return;function T(M){M.defaultPrevented||M.key==="Escape"&&s?.(M,"escapeKeyDown")}return document.addEventListener("keydown",T),()=>{document.removeEventListener("keydown",T)}},[i,s]);const d=c.useEventCallback((T,M)=>{s?.(T,M)}),u=c.useEventCallback(T=>{!s||T==null||a.start(T,()=>{d(null,"timeout")})});we.useEffect(()=>(i&&u(n),a.clear),[i,n,u,a]);const h=T=>{s?.(T,"clickaway")},g=a.clear,b=we.useCallback(()=>{n!=null&&u(l??n*.5)},[n,l,u]),x=T=>M=>{const O=T.onBlur;O?.(M),b()},v=T=>M=>{const O=T.onFocus;O?.(M),g()},C=T=>M=>{const O=T.onMouseEnter;O?.(M),g()},k=T=>M=>{const O=T.onMouseLeave;O?.(M),b()};return we.useEffect(()=>{if(!r&&i)return window.addEventListener("focus",b),window.addEventListener("blur",g),()=>{window.removeEventListener("focus",b),window.removeEventListener("blur",g)}},[r,i,b,g]),{getRootProps:(T={})=>{const M={...c.extractEventHandlers(e),...c.extractEventHandlers(T)};return{role:"presentation",...T,...M,onBlur:x(M),onFocus:v(M),onMouseEnter:C(M),onMouseLeave:k(M)}},onClickAway:h}}function Fi(e){return e.substring(2).toLowerCase()}function Ad(e,n){return n.documentElement.clientWidth<e.clientX||n.documentElement.clientHeight<e.clientY}function Ld(e){const{children:n,disableReactTree:r=!1,mouseEvent:s="onClick",onClickAway:i,touchEvent:l="onTouchEnd"}=e,a=we.useRef(!1),d=we.useRef(null),u=we.useRef(!1),h=we.useRef(!1);we.useEffect(()=>(setTimeout(()=>{u.current=!0},0),()=>{u.current=!1}),[]);const g=c.useForkRef(c.getReactElementRef(n),d),b=c.useEventCallback(C=>{const k=h.current;h.current=!1;const S=c.ownerDocument(d.current);if(!u.current||!d.current||"clientX"in C&&Ad(C,S))return;if(a.current){a.current=!1;return}let T;C.composedPath?T=C.composedPath().includes(d.current):T=!S.documentElement.contains(C.target)||d.current.contains(C.target),!T&&(r||!k)&&i(C)}),x=C=>k=>{h.current=!0;const S=n.props[C];S&&S(k)},v={ref:g};return l!==!1&&(v[l]=x(l)),we.useEffect(()=>{if(l!==!1){const C=Fi(l),k=c.ownerDocument(d.current),S=()=>{a.current=!0};return k.addEventListener(C,b),k.addEventListener("touchmove",S),()=>{k.removeEventListener(C,b),k.removeEventListener("touchmove",S)}}},[b,l]),s!==!1&&(v[s]=x(s)),we.useEffect(()=>{if(s!==!1){const C=Fi(s),k=c.ownerDocument(d.current);return k.addEventListener(C,b),()=>{k.removeEventListener(C,b)}}},[b,s]),we.cloneElement(n,v)}function Nd(e){return c.generateUtilityClass("MuiSnackbarContent",e)}c.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const Pd=e=>{const{classes:n}=e,r={root:["root"],action:["action"],message:["message"]};return c.composeClasses(r,Nd,n)},_d=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}}})),zd=c.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),Wd=c.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),qd=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiSnackbarContent"}),{action:i,className:l,message:a,role:d="alert",...u}=s,h=s,g=Pd(h);return t.jsxs(_d,{role:d,elevation:6,className:c.clsx(g.root,l),ownerState:h,ref:r,...u,children:[t.jsx(zd,{className:g.message,ownerState:h,children:a}),i?t.jsx(Wd,{className:g.action,ownerState:h,children:i}):null]})});function Bd(e){return c.generateUtilityClass("MuiSnackbar",e)}c.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const Vd=e=>{const{classes:n,anchorOrigin:r}=e,s={root:["root",`anchorOrigin${c.capitalize(r.vertical)}${c.capitalize(r.horizontal)}`]};return c.composeClasses(s,Bd,n)},Hd=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%)"}}}]}))),Ud=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiSnackbar"}),i=c.useTheme(),l={enter:i.transitions.duration.enteringScreen,exit:i.transitions.duration.leavingScreen},{action:a,anchorOrigin:{vertical:d,horizontal:u}={vertical:"bottom",horizontal:"left"},autoHideDuration:h=null,children:g,className:b,ClickAwayListenerProps:x,ContentProps:v,disableWindowBlurListener:C=!1,message:k,onBlur:S,onClose:T,onFocus:M,onMouseEnter:O,onMouseLeave:I,open:R,resumeHideDuration:_,slots:$={},slotProps:B={},TransitionComponent:F,transitionDuration:N=l,TransitionProps:{onEnter:H,onExited:D,...W}={},...K}=s,J={...s,anchorOrigin:{vertical:d,horizontal:u},autoHideDuration:h,disableWindowBlurListener:C,TransitionComponent:F,transitionDuration:N},X=Vd(J),{getRootProps:G,onClickAway:Q}=Rd({...J}),[ie,z]=we.useState(!0),re=ge=>{z(!0),D&&D(ge)},se=(ge,he)=>{z(!1),H&&H(ge,he)},ne={slots:{transition:F,...$},slotProps:{content:v,clickAwayListener:x,transition:W,...B}},[Me,oe]=c.useSlot("root",{ref:r,className:[X.root,b],elementType:Hd,getSlotProps:G,externalForwardedProps:{...ne,...K},ownerState:J}),[ue,{ownerState:De,...Ne}]=c.useSlot("clickAwayListener",{elementType:Ld,externalForwardedProps:ne,getSlotProps:ge=>({onClickAway:(...he)=>{const ye=he[0];ge.onClickAway?.(...he),!ye?.defaultMuiPrevented&&Q(...he)}}),ownerState:J}),[ae,Z]=c.useSlot("content",{elementType:qd,shouldForwardComponentProp:!0,externalForwardedProps:ne,additionalProps:{message:k,action:a},ownerState:J}),[ce,be]=c.useSlot("transition",{elementType:c.Grow,externalForwardedProps:ne,getSlotProps:ge=>({onEnter:(...he)=>{ge.onEnter?.(...he),se(...he)},onExited:(...he)=>{ge.onExited?.(...he),re(...he)}}),additionalProps:{appear:!0,in:R,timeout:N,direction:d==="top"?"down":"up"},ownerState:J});return!R&&ie?null:t.jsx(ue,{...Ne,...$.clickAwayListener&&{ownerState:De},children:t.jsx(Me,{...oe,children:t.jsx(ce,{...be,children:g||t.jsx(ae,{...Z})})})})});let Ys;function Gd(e){Ys=e}function $i(e){if(Ys)try{Ys(e)}catch{}}function Ht(e,n,r){return(async s=>{const i=Date.now();try{const l=await r(s);return $i({type:"console.mutation",resource:e,action:n,ok:!0,durationMs:Date.now()-i}),l}catch(l){throw $i({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 Pn({mutationFn:e,success:n,invalidates:r,closeDialog:s,resource:i,action:l}){const a=yt.useQueryClient(),[d,u]=j.useState(""),h=c.useMutationWithApiError({mutationFn:Ht(i,l,e),onSuccess(){s();for(const g of r)a.invalidateQueries({queryKey:g});u(n)},onError(g){u(g instanceof Error?g.message:"An unknown error occurred")}});return{mutate:h.mutate,isPending:h.isPending,notice:t.jsx(Ud,{open:d!=="",autoHideDuration:6e3,onClose:()=>u(""),message:d})}}const Ja="https://docs.malloydata.dev/documentation",Ts=`${Ja}/user_guides/publishing`,En="https://github.com/malloydata/publisher/blob/main/docs",Vt={docsHome:`${Ja}/`,publishing:`${Ts}/publishing`,explorer:`${Ts}/explorer`,mcpAgents:`${Ts}/mcp_agents`,surfaces:`${En}/choosing-a-surface.md`,dashboards:`${En}/dashboards.md`,dataApps:`${En}/html-data-apps.md`,givens:`${En}/givens.md`,materialization:`${En}/materialization.md`,connections:`${En}/connections.md`};function Yd({resourceUri:e}){const[n,r]=j.useState(!1),{apiClients:s}=q.useServer(),{environmentName:i}=c.parseResourceUri(e),l=Pn({mutationFn(d){return s.packages.createPackage(i,{name:d.name,description:d.description,location:d.location})},success:"Package created",invalidates:[["packages",i]],closeDialog:()=>r(!1),resource:"package",action:"create"}),a=d=>{d.preventDefault();const u=new FormData(d.currentTarget),h=u.get("name")?.toString(),g=u.get("description")?.toString(),b=u.get("location")?.toString();l.mutate({name:h,description:g,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 Kd=c.createSvgIcon(t.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function os({icon:e,tint:n,label:r,mono:s,description:i,rightLabel:l,trailingAction:a,onClick:d,ariaLabel:u}){const h=!!d,g=b=>{d&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),d(b))};return t.jsxs(m.Box,{onClick:d,onKeyDown:h?g:void 0,role:h?"button":void 0,tabIndex:h?0:void 0,"aria-label":u,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:{...s?{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 el=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"})),Qd=c.generateUtilityClasses("MuiBox",["root"]),Zd=c.createTheme(),Ye=Sr.createBox({themeId:c.THEME_ID,defaultTheme:Zd,defaultClassName:Qd.root,generateClassName:c.ClassNameGenerator.generate}),is=Sr.createStack({createStyledComponent:c.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:e=>c.useDefaultProps({props:e,name:"MuiStack"})}),Ri=c.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function Xd(e){return c.generateUtilityClass("MuiListItemIcon",e)}const Ai=c.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),Jd=e=>{const{alignItems:n,classes:r}=e,s={root:["root",n==="flex-start"&&"alignItemsFlexStart"]};return c.composeClasses(s,Xd,r)},eh=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}}]}))),lo=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiListItemIcon"}),{className:i,...l}=s,a=we.useContext(c.ListContext),d={...s,alignItems:a.alignItems},u=Jd(d);return t.jsx(eh,{className:c.clsx(u.root,i),ownerState:d,ref:r,...l})});function th(e){return c.generateUtilityClass("MuiListItemText",e)}const Fn=c.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),nh=e=>{const{classes:n,inset:r,primary:s,secondary:i,dense:l}=e,a={root:["root",r&&"inset",l&&"dense",s&&i&&"multiline"],primary:["primary"],secondary:["secondary"]};return c.composeClasses(a,th,n)},rh=c.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${Fn.primary}`]:n.primary},{[`& .${Fn.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(& .${Fn.primary})`]:{display:"block"},[`.${c.typographyClasses.root}:where(& .${Fn.secondary})`]:{display:"block"},variants:[{props:({ownerState:e})=>e.primary&&e.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:e})=>e.inset,style:{paddingLeft:56}}]}),co=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiListItemText"}),{children:i,className:l,disableTypography:a=!1,inset:d=!1,primary:u,primaryTypographyProps:h,secondary:g,secondaryTypographyProps:b,slots:x={},slotProps:v={},...C}=s,{dense:k}=we.useContext(c.ListContext);let S=u??i,T=g;const M={...s,disableTypography:a,inset:d,primary:!!S,secondary:!!T,dense:k},O=nh(M),I={slots:x,slotProps:{primary:h,secondary:b,...v}},[R,_]=c.useSlot("root",{className:c.clsx(O.root,l),elementType:rh,externalForwardedProps:{...I,...C},ownerState:M,ref:r}),[$,B]=c.useSlot("primary",{className:O.primary,elementType:c.Typography,externalForwardedProps:I,ownerState:M}),[F,N]=c.useSlot("secondary",{className:O.secondary,elementType:c.Typography,externalForwardedProps:I,ownerState:M});return S!=null&&S.type!==c.Typography&&!a&&(S=t.jsx($,{variant:k?"body2":"body1",component:B?.variant?void 0:"span",...B,children:S})),T!=null&&T.type!==c.Typography&&!a&&(T=t.jsx(F,{variant:"body2",color:"textSecondary",...N,children:T})),t.jsxs(R,{..._,children:[S,T]})});function sh(e){return c.generateUtilityClass("MuiMenuItem",e)}const er=c.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),oh=(e,n)=>{const{ownerState:r}=e;return[n.root,r.dense&&n.dense,r.divider&&n.divider,!r.disableGutters&&n.gutters]},ih=e=>{const{disabled:n,dense:r,divider:s,disableGutters:i,selected:l,classes:a}=e,d={root:["root",r&&"dense",n&&"disabled",!i&&"gutters",s&&"divider",l&&"selected"]},u=c.composeClasses(d,sh,a);return{...a,...u}},ah=c.styled(c.ButtonBase,{shouldForwardProp:e=>c.rootShouldForwardProp(e)||e==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:oh})(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},[`& + .${Ri.root}`]:{marginTop:e.spacing(1),marginBottom:e.spacing(1)},[`& + .${Ri.inset}`]:{marginLeft:52},[`& .${Fn.root}`]:{marginTop:0,marginBottom:0},[`& .${Fn.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"}}}]}))),tt=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiMenuItem"}),{autoFocus:i=!1,component:l="li",dense:a=!1,divider:d=!1,disableGutters:u=!1,focusVisibleClassName:h,role:g="menuitem",tabIndex:b,className:x,...v}=s,C=we.useContext(c.ListContext),k=we.useMemo(()=>({dense:a||C.dense||!1,disableGutters:u}),[C.dense,a,u]),S=we.useRef(null);c.useEnhancedEffect(()=>{i&&S.current&&S.current.focus()},[i]);const T={...s,dense:k.dense,divider:d,disableGutters:u},M=ih(s),O=c.useForkRef(S,r);let I;return s.disabled||(I=b!==void 0?b:-1),t.jsx(c.ListContext.Provider,{value:k,children:t.jsx(ah,{ref:O,role:g,tabIndex:I,component:l,focusVisibleClassName:c.clsx(M.focusVisible,h),className:c.clsx(M.root,x),...v,ownerState:T,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}],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"},lh={sqlserver:{port:"integer",encrypt:"boolean",trustServerCertificate:"boolean"}},ch={sqlserver:["hostNameInCertificate","instanceName"]};function tl(e,n){const r=lh[e],s=ch[e];if(!r&&!s)return n;const i={...n};for(const l of s??[])i[l]===""&&delete i[l];for(const[l,a]of Object.entries(r??{})){const d=n[l];if(d!==void 0){if(d===""){delete i[l];continue}if(a==="integer"){const u=Number(d);Number.isInteger(u)&&(i[l]=u)}else(d==="true"||d==="false")&&(i[l]=d==="true")}}return i}const nl=Object.values(q.ConnectionTypeEnum).filter(e=>e!==q.ConnectionTypeEnum.Publisher),Ks={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},kr=[{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"}}],Cr=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],uh=[{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 es(e){return e==="postgres"||e==="bigquery"||e==="snowflake"?Gt[e]||[]:e==="s3"?kr:e==="gcs"?Cr:e==="azure"?uh:[]}function dh({onSubmit:e,isSubmitting:n}){const[r,s]=j.useState(!1),[i,l]=j.useState("postgres"),[a,d]=j.useState([]),[u,h]=j.useState("postgres"),[g,b]=j.useState("s3"),[x,v]=j.useState("config"),C=()=>{s(!0)},k=()=>{s(!1),d([]),l("postgres"),h("postgres"),b("s3"),v("config")},S=async I=>{I.preventDefault();const R=new FormData(I.currentTarget),_=R.get("name")?.toString(),$=R.get("type")?.toString(),B=Gt[$];if(!_)throw new Error("Name is required");if(!$)throw new Error("Type is required");let F;if($==="ducklake"){const N={};if(u==="postgres"){const W=Gt.postgres,K={};if(W.forEach(J=>{const X=R.get(`ducklake_pg_${J.name}`)?.toString();X&&(K[J.name]=X)}),Object.keys(K).length===0)throw new Error("DuckLake requires catalog connection");N.postgresConnection=K}const H=R.get("ducklake_bucketUrl")?.toString();if(!H)throw new Error("DuckLake requires a bucket URL");const D={bucketUrl:H};if(g==="s3"){const W={};if(kr.forEach(K=>{const J=R.get(`ducklake_s3_${K.name}`)?.toString();J&&(W[K.name]=J)}),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&&(D.s3Connection=W)}else if(g==="gcs"){const W={};if(Cr.forEach(K=>{const J=R.get(`ducklake_gcs_${K.name}`)?.toString();J&&(W[K.name]=J)}),!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&&(D.gcsConnection=W)}F={name:_,type:$,ducklakeConnection:{catalog:N,storage:D}}}else if($==="duckdb"){if(a.length===0)throw new Error("DuckDB connection must have at least one attached database");const N=a.map((H,D)=>{const W=H.dbType,K=R.get(`attachedDb_${D}_name`)?.toString();if(!K)throw new Error(`Attached database at index ${D} must have a name`);const J={name:K,type:W},X=es(W);if(X&&X.length>0){const G={};if(X.forEach(ie=>{const z=R.get(`attachedDb_${D}_${ie.name}`)?.toString();z&&(G[ie.name]=z)}),W==="s3"){if(G.provider==="credential_chain")delete G.accessKeyId,delete G.secretAccessKey,delete G.sessionToken;else if(delete G.chain,!G.accessKeyId||!G.secretAccessKey)throw new Error(`Attached database "${K}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const Q=Ks[W];Q&&(J[Q]=G)}return J});F={name:_,type:$,duckdbConnection:{attachedDatabases:N}}}else{const N={};if(B.forEach(H=>{const D=R.get(H.name)?.toString();D&&(N[H.name]=D)}),$==="postgres"){if(!!!N.connectionString?.trim()){const D=["host","port","databaseName","userName","password"];for(const W of D)if(!N[W])throw new Error(`${B.find(K=>K.name===W)?.label||W} is required`)}}else if($==="bigquery"){if(!N.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if($==="snowflake"){if(!N.account)throw new Error("Account is required");if(!N.username)throw new Error("Username is required");if(!N.warehouse)throw new Error("Warehouse is required");if(!N.password&&!N.privateKey)throw new Error("Either password or private key is required")}else if($==="trino"){if(!N.server)throw new Error("Server is required");if(!N.user)throw new Error("User is required");if(N.server.trim().startsWith("https://")&&!N.password&&!N.peakaKey)throw new Error("Password is required for HTTPS connections (or use Peaka Key)")}else if($==="mysql"){const H=["host","port","database","user","password"];for(const D of H)if(!N[D])throw new Error(`${B.find(W=>W.name===D)?.label||D} is required`)}else if($==="sqlserver"){const H=["server","database","user","password"];if(!N.instanceName&&!N.port)throw new Error("Port is required unless an instance name is given");for(const D of H)if(!N[D])throw new Error(`${B.find(W=>W.name===D)?.label||D} is required`)}else if($==="motherduck"){if(!N.accessToken)throw new Error("Access Token is required")}else if($==="databricks"){if(!N.host)throw new Error("Host is required");if(!N.path)throw new Error("HTTP Path is required");const H=N.oauthClientId&&N.oauthClientSecret;if(!N.token&&!H)throw new Error("Either Access Token or OAuth Client ID + Secret is required")}F={name:_,type:$,[mr[$]]:tl($,N)}}await e(F),k()},T=()=>{d([...a,{name:"",dbType:"postgres"}])},M=I=>{d(a.filter((R,_)=>_!==I))},O=(I,R)=>{const _=[...a];_[I]={..._[I],dbType:R},d(_)};return t.jsxs(j.Fragment,{children:[t.jsx(c.AddButton,{label:"Connection",onClick:C}),t.jsx(c.AppDialog,{open:r,onClose:k,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:k,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(is,{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:I=>l(I.target.value),children:nl.map(I=>t.jsx(tt,{value:I,children:I},I))}),i==="ducklake"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{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:u,select:!0,onChange:I=>h(I.target.value),children:t.jsx(tt,{value:"postgres",children:"PostgreSQL"})}),u==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(I=>t.jsx(c.TextField,{id:`ducklake_pg_${I.name}`,name:`ducklake_pg_${I.name}`,label:I.label,type:I.type,fullWidth:!0,size:"small"},`pg_${I.name}`))})]}),t.jsxs(Ye,{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:g,select:!0,onChange:I=>b(I.target.value),children:[t.jsx(tt,{value:"s3",children:"S3"}),t.jsx(tt,{value:"gcs",children:"GCS"})]}),t.jsx(c.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:g==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small"}),g==="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"}),kr.filter(I=>I.visibleWhen?x===I.visibleWhen.value:!0).map(I=>t.jsx(c.TextField,{id:`ducklake_s3_${I.name}`,name:`ducklake_s3_${I.name}`,label:I.label,type:I.selectOptions?void 0:I.type,fullWidth:!0,size:"small",required:I.required,select:!!I.selectOptions,defaultValue:I.selectOptions?x:void 0,onChange:I.name==="provider"?R=>v(R.target.value):void 0,placeholder:I.name==="region"?"us-east-1":void 0,children:I.selectOptions?.map(R=>t.jsx(tt,{value:R.value,children:R.label},R.value))},`s3_${I.name}`))]}),g==="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"}),Cr.map(I=>t.jsx(c.TextField,{id:`ducklake_gcs_${I.name}`,name:`ducklake_gcs_${I.name}`,label:I.label,type:I.type,fullWidth:!0,size:"small",required:I.required},`gcs_${I.name}`))]})]})]}):i==="duckdb"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{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((I,R)=>{const _=es(I.dbType);return t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ye,{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:()=>M(R),size:"small",color:"error",children:t.jsx(el,{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:I.name}),t.jsx(c.TextField,{id:`attachedDb_${R}_type`,name:`attachedDb_${R}_type`,label:"Database Type",fullWidth:!0,size:"small",value:I.dbType,select:!0,onChange:$=>O(R,$.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map($=>t.jsx(tt,{value:$,children:$},$))}),_.filter($=>$.visibleWhen?(I[$.visibleWhen.field]||_.find(F=>F.name===$.visibleWhen?.field)?.selectOptions?.[0]?.value)===$.visibleWhen.value:!0).map($=>t.jsx(c.TextField,{id:`attachedDb_${R}_${$.name}`,name:`attachedDb_${R}_${$.name}`,label:$.label,type:$.selectOptions?void 0:$.type,fullWidth:!0,size:"small",required:$.required,select:!!$.selectOptions,defaultValue:$.selectOptions?.[0]?.value,onChange:$.selectOptions?B=>{const F=[...a];F[R]={...F[R],[$.name]:B.target.value},d(F)}:void 0,children:$.selectOptions?.map(B=>t.jsx(tt,{value:B.value,children:B.label},B.value))},$.name))]},R)})]}):Gt[i].map(I=>t.jsx(c.TextField,{id:I.name,name:I.name,label:I.label,type:I.type,fullWidth:!0,size:"small",required:I.required,select:!!I.selectOptions,defaultValue:I.selectOptions?I.selectOptions[0]?.value:void 0,children:I.selectOptions?.map(R=>t.jsx(tt,{value:R.value,children:R.label},R.value))},I.name))]})})})]})}function hh({connection:e,onCloseDialog:n,isMutating:r,onDelete:s}){const[i,l]=j.useState(!1),a=()=>{l(!0)},d=()=>{l(!1),n()};return t.jsxs(j.Fragment,{children:[t.jsxs(tt,{"aria-label":`Delete connection ${e?.name??""}`.trim(),onClick:u=>{u.stopPropagation(),a()},sx:{color:"error.main"},children:[t.jsx(lo,{sx:{color:"inherit"},children:t.jsx(_t.Delete,{fontSize:"small"})}),t.jsx(co,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:i,onClose:d,title:"Delete connection",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:d,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>s(),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 Li=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function Ni(e){const n=e.duckdbConnection?.attachedDatabases;return!n||n.length===0?[]:n.map(r=>({name:r.name||"",dbType:r.type||"postgres"}))}function Pi(e){const n=e.ducklakeConnection;return n&&n.storage?.gcsConnection?"gcs":"s3"}function fh({connection:e,onSubmit:n,isSubmitting:r,onCloseDialog:s}){const[i,l]=j.useState(!1),[a,d]=j.useState(e.type),u=j.useMemo(()=>new Set(e.withheldFields??[]),[e.withheldFields]),[h,g]=j.useState(()=>Ni(e)),[b,x]=j.useState("postgres"),[v,C]=j.useState(()=>Pi(e)),[k,S]=j.useState(()=>e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),T=()=>{g(Ni(e)),d(e.type),S(e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),x("postgres"),C(Pi(e)),l(!0)},M=()=>{l(!1),s?.()},O=async F=>{F.preventDefault();const N=new FormData(F.currentTarget),H=N.get("name")?.toString(),D=N.get("type")?.toString(),W=Gt[D];if(!H)throw new Error("Name is required");if(!D)throw new Error("Type is required");let K;if(D==="ducklake"){const J={};if(b==="postgres"){const Q=Gt.postgres,ie={};if(Q.forEach(z=>{const re=N.get(`ducklake_pg_${z.name}`)?.toString();re&&(ie[z.name]=re)}),Object.keys(ie).length===0)throw new Error("DuckLake requires catalog connection");J.postgresConnection=ie}const X=N.get("ducklake_bucketUrl")?.toString();if(!X)throw new Error("DuckLake requires a bucket URL");const G={bucketUrl:X};if(v==="s3"){const Q={};kr.forEach(z=>{const re=N.get(`ducklake_s3_${z.name}`)?.toString();re&&(Q[z.name]=re)});const ie=e.ducklakeConnection?.storage?.s3Connection;if(ie&&(!Q.provider&&ie.provider&&(Q.provider=ie.provider),!Q.chain&&ie.chain&&(Q.chain=ie.chain),!Q.accessKeyId&&ie.accessKeyId&&(Q.accessKeyId=ie.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&&(G.s3Connection=Q)}else if(v==="gcs"){const Q={};Cr.forEach(z=>{const re=N.get(`ducklake_gcs_${z.name}`)?.toString();re&&(Q[z.name]=re)});const ie=e.ducklakeConnection?.storage?.gcsConnection;if(ie&&!Q.keyId&&ie.keyId&&(Q.keyId=ie.keyId),!Q.keyId)throw new Error("GCS Key ID is required");Object.keys(Q).length>0&&(G.gcsConnection=Q)}K={name:H,type:D,ducklakeConnection:{catalog:J,storage:G}}}else if(D==="duckdb"){if(h.length===0)throw new Error("DuckDB connection must have at least one attached database");const J=h.map((X,G)=>{const Q=X.dbType,ie=N.get(`attachedDb_${G}_name`)?.toString();if(!ie)throw new Error(`Attached database at index ${G} must have a name`);const z={name:ie,type:Q},re=es(Q);if(re&&re.length>0){const se={};if(re.forEach(Me=>{const oe=N.get(`attachedDb_${G}_${Me.name}`)?.toString();oe&&(se[Me.name]=oe)}),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 "${ie}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const ne=Ks[Q];ne&&(z[ne]=se)}return z});K={name:H,type:D,duckdbConnection:{attachedDatabases:J}}}else{const J=e[mr[D]]||{},X={};if(W.forEach(G=>{const Q=N.get(G.name)?.toString(),ie=J[G.name];Q?X[G.name]=Q:Li.has(G.name)||(Q!==void 0?X[G.name]=Q:ie&&(X[G.name]=ie))}),D==="postgres"){const G=["host","port","databaseName","userName"],Q=u.has("postgresConnection.connectionString");if(!(!!X.connectionString?.trim()||Q)){const z=G;for(const re of z)if(!X[re])throw new Error(`${W.find(se=>se.name===re)?.label||re} is required`)}}else if(D==="snowflake"){if(!X.account)throw new Error("Account is required");if(!X.username)throw new Error("Username is required");if(!X.warehouse)throw new Error("Warehouse is required")}else if(D==="trino"){if(!X.server)throw new Error("Server is required");if(!X.user)throw new Error("User is required")}else if(D==="mysql"){const G=["host","port","database","user"];for(const Q of G)if(!X[Q])throw new Error(`${W.find(ie=>ie.name===Q)?.label||Q} is required`)}else if(D==="sqlserver"){const G=["server","database","user"];if(!X.instanceName&&!X.port)throw new Error("Port is required unless an instance name is given");for(const Q of G)if(!X[Q])throw new Error(`${W.find(ie=>ie.name===Q)?.label||Q} is required`)}else if(D==="databricks"){if(!X.host)throw new Error("Host is required");if(!X.path)throw new Error("HTTP Path is required")}K={name:H,type:D,[mr[D]]:tl(D,X)}}await n(K),M()},I=()=>{g([...h,{name:"",dbType:"postgres"}])},R=F=>{g(h.filter((N,H)=>H!==F))},_=(F,N)=>{const H=[...h];H[F]={...H[F],dbType:N},g(H)},$=(F,N)=>{const H=e.duckdbConnection?.attachedDatabases;if(!H||!H[F])return"";const D=H[F],W=Ks[D.type||""];return W&&D[W]?D[W][N]??"":""},B=F=>{const N=e.ducklakeConnection;if(!N)return"";if(F.startsWith("pg_")){const H=F.replace("pg_","");return N.catalog?.postgresConnection?.[H]??""}if(F==="bucketUrl")return N.storage?.bucketUrl??"";if(F.startsWith("s3_")){const H=F.replace("s3_","");return N.storage?.s3Connection?.[H]??""}if(F.startsWith("gcs_")){const H=F.replace("gcs_","");return N.storage?.gcsConnection?.[H]??""}return""};return t.jsxs(j.Fragment,{children:[t.jsxs(tt,{"aria-label":`Edit connection ${e?.name??""}`.trim(),onClick:F=>{F.preventDefault(),F.stopPropagation(),T()},children:[t.jsx(lo,{children:t.jsx(_t.Edit,{fontSize:"small"})}),t.jsx(co,{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(is,{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:F=>d(F.target.value),children:nl.map(F=>t.jsx(tt,{value:F,children:F},F))}),a==="ducklake"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{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:F=>x(F.target.value),children:t.jsx(tt,{value:"postgres",children:"PostgreSQL"})}),b==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(F=>t.jsx(c.TextField,{id:`ducklake_pg_${F.name}`,name:`ducklake_pg_${F.name}`,label:F.label,type:F.type,fullWidth:!0,size:"small",defaultValue:B(`pg_${F.name}`)},`pg_${F.name}`))})]}),t.jsxs(Ye,{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:F=>C(F.target.value),children:[t.jsx(tt,{value:"s3",children:"S3"}),t.jsx(tt,{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"}),kr.filter(F=>F.visibleWhen?k===F.visibleWhen.value:!0).map(F=>t.jsx(c.TextField,{id:`ducklake_s3_${F.name}`,name:`ducklake_s3_${F.name}`,label:F.label,type:F.selectOptions?void 0:F.type,fullWidth:!0,size:"small",required:F.required&&F.name!=="secretAccessKey",select:!!F.selectOptions,defaultValue:F.selectOptions?k:B(`s3_${F.name}`),onChange:F.name==="provider"?N=>S(N.target.value):void 0,placeholder:F.name==="region"?"us-east-1":F.name==="secretAccessKey"&&u.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:F.selectOptions?.map(N=>t.jsx(tt,{value:N.value,children:N.label},N.value))},`s3_${F.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"}),Cr.map(F=>t.jsx(c.TextField,{id:`ducklake_gcs_${F.name}`,name:`ducklake_gcs_${F.name}`,label:F.label,type:F.type,fullWidth:!0,size:"small",required:F.required&&F.name!=="secret",defaultValue:B(`gcs_${F.name}`),placeholder:F.name==="secret"&&u.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${F.name}`))]})]})]}):a==="duckdb"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{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:I,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((F,N)=>{const H=es(F.dbType);return t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ye,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(c.Typography,{variant:"subtitle2",children:["Database ",N+1]}),t.jsx(c.IconButton,{"aria-label":`Remove attached database ${N+1}`,onClick:()=>R(N),size:"small",color:"error",children:t.jsx(el,{fontSize:"small"})})]}),t.jsx(c.TextField,{required:!0,id:`attachedDb_${N}_name`,name:`attachedDb_${N}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:F.name}),t.jsx(c.TextField,{id:`attachedDb_${N}_type`,name:`attachedDb_${N}_type`,label:"Database Type",fullWidth:!0,size:"small",value:F.dbType,select:!0,onChange:D=>_(N,D.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map(D=>t.jsx(tt,{value:D,children:D},D))}),H.filter(D=>D.visibleWhen?(F[D.visibleWhen.field]||$(N,D.visibleWhen.field)||H.find(K=>K.name===D.visibleWhen?.field)?.selectOptions?.[0]?.value)===D.visibleWhen.value:!0).map(D=>t.jsx(c.TextField,{id:`attachedDb_${N}_${D.name}`,name:`attachedDb_${N}_${D.name}`,label:D.label,type:D.selectOptions?void 0:D.type,fullWidth:!0,size:"small",required:D.required,select:!!D.selectOptions,defaultValue:$(N,D.name)||D.selectOptions?.[0]?.value,onChange:D.selectOptions?W=>{const K=[...h];K[N]={...K[N],[D.name]:W.target.value},g(K)}:void 0,children:D.selectOptions?.map(W=>t.jsx(tt,{value:W.value,children:W.label},W.value))},D.name))]},N)})]}):Gt[a].map(F=>{const N=e?.[mr[a]??""]?.[F.name??""]??"",H=F.type==="password"||Li.has(F.name),D=u.has(`${mr[a]??""}.${F.name}`),W=F.selectOptions?N===""||N===void 0?F.selectOptions[0]?.value:String(N):void 0;return t.jsx(c.TextField,{id:F.name,name:F.name,label:F.label,type:F.type,fullWidth:!0,size:"small",required:F.required&&!H&&!N,select:!!F.selectOptions,defaultValue:F.selectOptions?W:N,placeholder:D?"Leave empty to keep existing":void 0,helperText:H?D?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0,children:F.selectOptions?.map(K=>t.jsx(tt,{value:K.value,children:K.label},K.value))},F.name)})]})})})]})}function _i(e,n){return!e||e.type!=="duckdb"?!1:(e.duckdbConnection?.attachedDatabases||[]).some(s=>s.type==="azure"&&s.name===n)}function ph(e){return e.startsWith("gs://")||e.startsWith("s3://")||e.startsWith("https://")||e.startsWith("abfss://")||e.startsWith("az://")}function rl({connectionName:e,resourceUri:n,schema:r,connection:s}){const{apiClients:i}=q.useServer(),{environmentName:l}=c.parseResourceUri(n),[a,d]=j.useState(null),[u,h]=j.useState(r||null),[g,b]=j.useState(!1),{data:x,isError:v,isLoading:C,error:k}=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:g,onChange:T=>b(T.target.checked)}),label:"Hidden Schemas"})]}),t.jsx(m.Divider,{sx:{mt:"2px"}}),t.jsxs(m.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[C&&t.jsx(c.Loading,{text:"Loading schemas..."}),v&&t.jsx(c.ApiErrorDisplay,{error:k,context:`${l} > ${e} > Schemas`}),!C&&!v&&S.length===0&&t.jsx(m.Typography,{variant:"body2",children:"No Schemas"}),!C&&!v&&S.length>0&&t.jsx(m.List,{dense:!0,disablePadding:!0,children:S.map(T=>{const M=T.name;if(T.isHidden&&!g)return null;const I=u===M;return t.jsx(m.ListItemButton,{selected:I,onClick:()=>{h(M),d(null)},children:t.jsx(m.ListItemText,{primary:M})},M)})})]})]})}),t.jsx(m.Grid,{size:{xs:12,md:r?6:4},children:u&&t.jsx(m.Paper,{sx:{p:1,m:0},children:t.jsx(yh,{connectionName:e,schemaName:u,onTableSelect:T=>{d(T)},resourceUri:n,connection:s})})}),t.jsx(m.Grid,{size:{xs:12,md:r?6:4},children:u&&a&&t.jsx(mh,{environmentName:l,connectionName:e,schemaName:u,tableResource:a})})]})}function mh({environmentName:e,connectionName:n,schemaName:r,tableResource:s}){const{apiClients:i}=q.useServer(),{data:l,isLoading:a,isError:d,error:u}=c.useQueryWithApiError({queryKey:["connectionTableDetail",e,n,r,s],queryFn:()=>i.connections.getTable(e,n,r,s),enabled:!!r&&!!s}),h={resource:l?.data?.resource??s,columns:l?.data?.columns??[]};return t.jsxs(m.Paper,{sx:{p:1,m:0},children:[d&&t.jsx(c.ApiErrorDisplay,{error:u,context:`${e} > ${n} > ${r} > ${s}`}),!d&&t.jsx(gh,{table:h,loading:a})]})}function gh({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,s)=>r.name.localeCompare(s.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 yh({connectionName:e,schemaName:n,onTableSelect:r,resourceUri:s,connection:i}){const{environmentName:l}=c.parseResourceUri(s),{apiClients:a}=q.useServer(),[d,u]=j.useState(""),{data:h,isSuccess:g,isError:b,error:x,isLoading:v}=c.useQueryWithApiError({queryKey:["tablesInSchema",l,e,n],queryFn:()=>a.connections.listTables(l,e,n)}),C=_i(i,n),k=T=>C?T:T.split(".").pop()||T,S=g&&h?.data?h.data.filter(T=>k(T.resource).toLowerCase().includes(d.toLowerCase())).sort((T,M)=>k(T.resource).localeCompare(k(M.resource))):[];return t.jsxs(t.Fragment,{children:[t.jsx(m.Typography,{variant:"overline",fontWeight:"bold",children:ph(n)||_i(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:d,onChange:T=>u(T.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}`}),g&&S.length===0&&t.jsx(m.Typography,{variant:"body2",children:"No Tables"}),g&&h?.data&&h.data.length>0&&t.jsx(m.List,{dense:!0,disablePadding:!0,children:S.map(T=>{let M=k(T.resource);return!C&&T.resource.includes("://")&&(M=T.resource.split("/").pop()||T.resource),t.jsx(m.ListItemButton,{onClick:()=>r(T.resource),children:t.jsx(m.ListItemText,{primary:M,secondary:T.columns.length>0?`${T.columns.length} columns`:void 0})},T.resource)})})]})]})}const xh={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 vh(e){return e?xh[e]??e:""}function bh({resourceUri:e}){const{apiClients:n,mutable:r}=q.useServer(),s=yt.useQueryClient(),{environmentName:i}=c.parseResourceUri(e),[l,a]=j.useState(""),[d,u]=j.useState(null),h=c.encodeResourceUri({environmentName:i,connectionName:d}),{data:g,isSuccess:b,isError:x,error:v}=c.useQueryWithApiError({queryKey:["connections",i],queryFn:()=>n.connections.listConnections(i)}),C=c.useMutationWithApiError({mutationFn:Ht("connection","create",O=>n.environments.updateEnvironment(i,{name:i,connections:[...g.data,O]})),onSuccess(){a("Connection added successfully"),s.invalidateQueries({queryKey:["connections",i]})},onError(O){a(O.message)}}),k=c.useMutationWithApiError({mutationFn:Ht("connection","update",O=>n.environments.updateEnvironment(i,{name:i,connections:g.data.map(I=>I.name===O.name?O:I)})),onSuccess(O,I){a(`Connection ${I.name} updated successfully`),s.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,I){a(`Connection ${I.name} deleted successfully`),s.invalidateQueries({queryKey:["connections",i]})},onError(O){a(O.message)}}),T=b?[...g.data].sort((O,I)=>(O.name??"").localeCompare(I.name??"")):[],M=C.isPending||k.isPending||S.isPending;return t.jsxs(Pt,{title:"Connections",...b?{count:T.length}:{},description:"Database connections available to packages in this environment",...r&&b?{action:t.jsx(dh,{onSubmit:O=>C.mutateAsync(O),isSubmitting:C.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&&T.length===0&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),b&&T.length>0&&t.jsx(m.Stack,{children:T.map(O=>t.jsx(wh,{connection:O,mutable:r,isMutating:M,onOpenExplorer:()=>u(O.name??null),onEdit:I=>k.mutateAsync(I),onDelete:I=>S.mutateAsync(I)},O.name))}),t.jsx(m.Snackbar,{open:l!=="",autoHideDuration:6e3,onClose:()=>a(""),message:l}),t.jsx(c.AppDialog,{open:d!==null,onClose:()=>u(null),maxWidth:"lg",title:`Connection explorer: ${d??""}`,showClose:!0,children:d&&t.jsx(rl,{resourceUri:h,connectionName:d,connection:g?.data?.find(O=>O.name===d)})})]})}function wh({connection:e,mutable:n,isMutating:r,onOpenExplorer:s,onEdit:i,onDelete:l}){const[a,d]=j.useState(null),u=!!a,h=b=>{b.stopPropagation(),d(b.currentTarget)},g=()=>d(null);return t.jsx(os,{icon:t.jsx(Kd,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.connection,label:e.name??"",ariaLabel:e.name??"",description:vh(e.type),onClick:s,...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(_t.MoreVert,{fontSize:"small"})}),t.jsxs(m.Menu,{anchorEl:a,open:u,onClose:g,onClick:b=>b.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[t.jsx(fh,{connection:e,onSubmit:i,isSubmitting:r,onCloseDialog:g}),t.jsx(hh,{connection:e,onCloseDialog:g,isMutating:r,onDelete:()=>l(e)})]})]})}:{}})}const Sh=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 kh({resourceUri:e,onCloseDialog:n}){const[r,s]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{s(!0)},a=()=>{s(!1),n()},{environmentName:d,packageName:u}=c.parseResourceUri(e),h=Pn({mutationFn:()=>i.packages.deletePackage(d,u),success:"Package deleted",invalidates:[["packages",d]],closeDialog:a,resource:"package",action:"delete"});return t.jsxs(j.Fragment,{children:[t.jsxs(m.MenuItem,{onClick:l,children:[t.jsx(m.ListItemIcon,{children:t.jsx(_t.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:u}),"? The package stops being served and this cannot be undone."]})}),h.notice]})}function Ch({package:e,resourceUri:n,onCloseDialog:r}){const[s,i]=j.useState(!1),{apiClients:l}=q.useServer(),a=()=>{i(!0)},d=()=>{i(!1),r()},{packageName:u,environmentName:h}=c.parseResourceUri(n),g=Pn({mutationFn(x){return l.packages.updatePackage(h,u,{name:u,description:x.description})},success:"Package updated",invalidates:[["packages",h]],closeDialog:d,resource:"package",action:"update"}),b=x=>{x.preventDefault();const C=new FormData(x.currentTarget).get("description")?.toString();g.mutate({description:C})};return t.jsxs(j.Fragment,{children:[t.jsxs(m.MenuItem,{onClick:a,children:[t.jsx(m.ListItemIcon,{children:t.jsx(_t.Edit,{fontSize:"small"})}),t.jsx(m.ListItemText,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:s,onClose:d,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:g.isPending,onClick:d,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"package-form",variant:"contained",loading:g.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}})]})})}),g.notice]})}function sl({onSelectPackage:e,resourceUri:n}){const{apiClients:r}=q.useServer(),{environmentName:s}=c.parseResourceUri(n),{data:i,isSuccess:l,isError:a,error:d}=c.useQueryWithApiError({queryKey:["packages",s],queryFn:()=>r.packages.listPackages(s)});if(a)return t.jsx(c.ApiErrorDisplay,{error:d,context:`${s} > Packages`});if(!l)return t.jsx(c.Loading,{text:"Fetching Packages..."});const u=[...i.data].sort((h,g)=>h.name.localeCompare(g.name));return t.jsx(m.Stack,{children:u.map(h=>{const g=c.encodeResourceUri({environmentName:s,packageName:h.name});return t.jsx(jh,{pkg:h,packageResourceUri:g,onSelectPackage:e},h.name)})})}function jh({pkg:e,packageResourceUri:n,onSelectPackage:r}){const{mutable:s}=q.useServer(),i=e.versionId!==void 0||e.latestVersion!==void 0,[l,a]=j.useState(null),d=!!l,u=g=>{g.stopPropagation(),a(g.currentTarget)},h=()=>a(null);return t.jsx(os,{icon:t.jsx(Sh,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.package,label:e.name,ariaLabel:e.name,...e.description?{description:e.description}:{},onClick:g=>r(e.name,g),...s?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(m.IconButton,{size:"small",onClick:u,"aria-label":`Package actions for ${e.name}`,children:t.jsx(_t.MoreVert,{fontSize:"small"})}),t.jsxs(m.Menu,{anchorEl:l,open:d,onClose:h,onClick:g=>g.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[!i&&t.jsx(Ch,{package:e,resourceUri:n,onCloseDialog:h}),t.jsx(kh,{resourceUri:n,onCloseDialog:h})]})]})}:{}})}function Th({onSelectPackage:e,resourceUri:n}){const{apiClients:r,mutable:s}=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(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(Pt,{title:"Packages",...l.isSuccess?{count:l.data.data.length}:{},description:"Published packages available for use in this environment",...s?{action:t.jsx(Yd,{resourceUri:n})}:{},children:t.jsx(sl,{onSelectPackage:e,resourceUri:n})}),t.jsx(bh,{resourceUri:n}),t.jsx($d,{resourceUri:n})]})}function zi({array1:e,array2:n,parser:r=s=>s}){return e&&n&&e.length===n.length&&e.every((s,i)=>r(s)===r(n[i]))}function Wi(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}function Mh(e={}){const{ignoreAccents:n=!0,ignoreCase:r=!0,limit:s,matchFrom:i="any",stringify:l,trim:a=!1}=e;return(d,{inputValue:u,getOptionLabel:h})=>{let g=a?u.trim():u;r&&(g=g.toLowerCase()),n&&(g=Wi(g));const b=g?d.filter(x=>{let v=(l||h)(x);return r&&(v=v.toLowerCase()),n&&(v=Wi(v)),i==="start"?v.startsWith(g):v.includes(g)}):d;return typeof s=="number"?b.slice(0,s):b}}const Oh=Mh(),qi=5,Ih=e=>e.current!==null&&e.current.parentElement?.contains(document.activeElement),Eh=[];function Bi(e,n,r,s){if(n||e==null||s)return"";const i=r(e);return typeof i=="string"?i:""}function Dh(e){const{unstable_isActiveElementInListbox:n=Ih,unstable_classNamePrefix:r="Mui",autoComplete:s=!1,autoHighlight:i=!1,autoSelect:l=!1,blurOnSelect:a=!1,clearOnBlur:d=!e.freeSolo,clearOnEscape:u=!1,componentName:h="useAutocomplete",defaultValue:g=e.multiple?Eh:null,disableClearable:b=!1,disableCloseOnSelect:x=!1,disabled:v,disabledItemsFocusable:C=!1,disableListWrap:k=!1,filterOptions:S=Oh,filterSelectedOptions:T=!1,freeSolo:M=!1,getOptionDisabled:O,getOptionKey:I,getOptionLabel:R=U=>U.label??U,groupBy:_,handleHomeEndKeys:$=!e.freeSolo,id:B,includeInputInList:F=!1,inputValue:N,isOptionEqualToValue:H=(U,V)=>U===V,multiple:D=!1,onChange:W,onClose:K,onHighlightChange:J,onInputChange:X,onOpen:G,open:Q,openOnFocus:ie=!1,options:z,readOnly:re=!1,renderValue:se,selectOnFocus:ne=!e.freeSolo,value:Me}=e,oe=c.useId(B);let ue=R;ue=U=>{const V=R(U);return typeof V!="string"?String(V):V};const De=we.useRef(!1),Ne=we.useRef(!0),ae=we.useRef(null),Z=we.useRef(null),[ce,be]=we.useState(null),[ge,he]=we.useState(-1),ye=i?0:-1,Fe=we.useRef(ye),ze=we.useRef(Bi(g??Me,D,ue)).current,[me,Y]=c.useControlled({controlled:Me,default:g,name:h}),[le,Oe]=c.useControlled({controlled:N,default:ze,name:h,state:"inputValue"}),[Re,at]=we.useState(!1),Ie=we.useCallback((U,V,de)=>{if(!(D?me.length<V.length:V!==null)&&!d)return;const te=Bi(V,D,ue,se);le!==te&&(Oe(te),X&&X(U,te,de))},[ue,le,D,X,Oe,d,me,se]),[lt,xt]=c.useControlled({controlled:Q,default:!1,name:h,state:"open"}),[vt,Mt]=we.useState(!0),mt=!D&&me!=null&&le===ue(me),Ke=lt&&!re,fe=Ke?S(z.filter(U=>!(T&&(D?me:[me]).some(V=>V!==null&&H(U,V)))),{inputValue:mt&&vt?"":le,getOptionLabel:ue}):[],Qe=hd({filteredOptions:fe,value:me,inputValue:le});we.useEffect(()=>{const U=me!==Qe.value;Re&&!U||M&&!U||Ie(null,me,"reset")},[me,Ie,Re,Qe.value,M]);const qe=lt&&fe.length>0&&!re,ct=c.useEventCallback(U=>{if(U===-1)ae.current.focus();else{const V=se?"data-item-index":"data-tag-index";ce.querySelector(`[${V}="${U}"]`).focus()}});we.useEffect(()=>{D&&ge>me.length-1&&(he(-1),ct(-1))},[me,D,ge,ct]);function ut(U,V){if(!Z.current||U<0||U>=fe.length)return-1;let de=U;for(;;){const ve=Z.current.querySelector(`[data-option-index="${de}"]`),te=C?!1:!ve||ve.disabled||ve.getAttribute("aria-disabled")==="true";if(ve&&ve.hasAttribute("tabindex")&&!te)return de;if(V==="next"?de=(de+1)%fe.length:de=(de-1+fe.length)%fe.length,de===U)return-1}}const Ze=c.useEventCallback(({event:U,index:V,reason:de})=>{if(Fe.current=V,V===-1?ae.current.removeAttribute("aria-activedescendant"):ae.current.setAttribute("aria-activedescendant",`${oe}-option-${V}`),J&&["mouse","keyboard","touch"].includes(de)&&J(U,V===-1?null:fe[V],de),!Z.current)return;const ve=Z.current.querySelector(`[role="option"].${r}-focused`);ve&&(ve.classList.remove(`${r}-focused`),ve.classList.remove(`${r}-focusVisible`));let te=Z.current;if(Z.current.getAttribute("role")!=="listbox"&&(te=Z.current.parentElement.querySelector('[role="listbox"]')),!te)return;if(V===-1){te.scrollTop=0;return}const Ve=Z.current.querySelector(`[data-option-index="${V}"]`);if(Ve&&(Ve.classList.add(`${r}-focused`),de==="keyboard"&&Ve.classList.add(`${r}-focusVisible`),te.scrollHeight>te.clientHeight&&de!=="mouse"&&de!=="touch")){const Ge=Ve,Ct=te.clientHeight+te.scrollTop,vn=Ge.offsetTop+Ge.offsetHeight;vn>Ct?te.scrollTop=vn-te.clientHeight:Ge.offsetTop-Ge.offsetHeight*(_?1.3:0)<te.scrollTop&&(te.scrollTop=Ge.offsetTop-Ge.offsetHeight*(_?1.3:0))}}),pe=c.useEventCallback(({event:U,diff:V,direction:de="next",reason:ve})=>{if(!Ke)return;const Ve=ut((()=>{const Ge=fe.length-1;if(V==="reset")return ye;if(V==="start")return 0;if(V==="end")return Ge;const Ct=Fe.current+V;return Ct<0?Ct===-1&&F?-1:k&&Fe.current!==-1||Math.abs(V)>1?0:Ge:Ct>Ge?Ct===Ge+1&&F?-1:k||Math.abs(V)>1?Ge:0:Ct})(),de);if(Ze({index:Ve,reason:ve,event:U}),s&&V!=="reset")if(Ve===-1)ae.current.value=le;else{const Ge=ue(fe[Ve]);ae.current.value=Ge,Ge.toLowerCase().indexOf(le.toLowerCase())===0&&le.length>0&&ae.current.setSelectionRange(le.length,Ge.length)}}),Ue=!zi({array1:Qe.filteredOptions,array2:fe,parser:ue}),bt=()=>{const U=(V,de)=>{const ve=V?ue(V):"",te=de?ue(de):"";return ve===te};if(Fe.current!==-1&&!zi({array1:Qe.filteredOptions,array2:fe,parser:ue})&&Qe.inputValue===le&&(D?me.length===Qe.value.length&&Qe.value.every((V,de)=>ue(me[de])===ue(V)):U(Qe.value,me))){const V=Qe.filteredOptions[Fe.current];if(V)return fe.findIndex(de=>ue(de)===ue(V))}return-1},Ce=we.useCallback(()=>{if(!Ke)return;const U=bt();if(U!==-1){Fe.current=U;return}const V=D?me[0]:me;if(fe.length===0||V==null){pe({diff:"reset"});return}if(Z.current){if(V!=null){const de=fe[Fe.current];if(D&&de&&me.findIndex(te=>H(de,te))!==-1)return;const ve=fe.findIndex(te=>H(te,V));ve===-1?pe({diff:"reset"}):Ze({index:ve});return}if(Fe.current>=fe.length-1){Ze({index:fe.length-1});return}Ze({index:Fe.current})}},[fe.length,D?!1:me,T,pe,Ze,Ke,le,D]),Le=c.useEventCallback(U=>{c.setRef(Z,U),U&&Ce()});we.useEffect(()=>{Ue&&Ce()},[Ce,Ue]);const Ee=U=>{lt||(xt(!0),Mt(!0),G&&G(U))},Be=(U,V)=>{lt&&(xt(!1),K&&K(U,V))},ht=(U,V,de,ve)=>{if(D){if(me.length===V.length&&me.every((te,Ve)=>te===V[Ve]))return}else if(me===V)return;W&&W(U,V,de,ve),Y(V)},We=we.useRef(!1),nt=(U,V,de="selectOption",ve="options")=>{let te=de,Ve=V;if(D){Ve=Array.isArray(me)?me.slice():[];const Ge=Ve.findIndex(Ct=>H(V,Ct));Ge===-1?Ve.push(V):ve!=="freeSolo"&&(Ve.splice(Ge,1),te="removeOption")}Ie(U,Ve,te),ht(U,Ve,te,{option:V}),!x&&(!U||!U.ctrlKey&&!U.metaKey)&&Be(U,te),(a===!0||a==="touch"&&We.current||a==="mouse"&&!We.current)&&ae.current.blur()};function Ot(U,V){if(U===-1)return-1;let de=U;for(;;){if(V==="next"&&de===me.length||V==="previous"&&de===-1)return-1;const ve=se?"data-item-index":"data-tag-index",te=ce.querySelector(`[${ve}="${de}"]`);if(!te||!te.hasAttribute("tabindex")||te.disabled||te.getAttribute("aria-disabled")==="true")de+=V==="next"?1:-1;else return de}}const kt=(U,V)=>{if(!D)return;le===""&&Be(U,"toggleInput");let de=ge;ge===-1?le===""&&V==="previous"&&(de=me.length-1):(de+=V==="next"?1:-1,de<0&&(de=0),de===me.length&&(de=-1)),de=Ot(de,V),he(de),ct(de)},$t=U=>{De.current=!0,Oe(""),X&&X(U,"","clear"),ht(U,D?[]:null,"clear")},gn=U=>V=>{if(U.onKeyDown&&U.onKeyDown(V),!V.defaultMuiPrevented&&(ge!==-1&&!["ArrowLeft","ArrowRight"].includes(V.key)&&(he(-1),ct(-1)),V.which!==229))switch(V.key){case"Home":Ke&&$&&(V.preventDefault(),pe({diff:"start",direction:"next",reason:"keyboard",event:V}));break;case"End":Ke&&$&&(V.preventDefault(),pe({diff:"end",direction:"previous",reason:"keyboard",event:V}));break;case"PageUp":V.preventDefault(),pe({diff:-qi,direction:"previous",reason:"keyboard",event:V}),Ee(V);break;case"PageDown":V.preventDefault(),pe({diff:qi,direction:"next",reason:"keyboard",event:V}),Ee(V);break;case"ArrowDown":V.preventDefault(),pe({diff:1,direction:"next",reason:"keyboard",event:V}),Ee(V);break;case"ArrowUp":V.preventDefault(),pe({diff:-1,direction:"previous",reason:"keyboard",event:V}),Ee(V);break;case"ArrowLeft":!D&&se?ct(0):kt(V,"previous");break;case"ArrowRight":!D&&se?ct(-1):kt(V,"next");break;case"Enter":if(Fe.current!==-1&&Ke){const de=fe[Fe.current],ve=O?O(de):!1;if(V.preventDefault(),ve)return;nt(V,de,"selectOption"),s&&ae.current.setSelectionRange(ae.current.value.length,ae.current.value.length)}else M&&le!==""&&mt===!1&&(D&&V.preventDefault(),nt(V,le,"createOption","freeSolo"));break;case"Escape":Ke?(V.preventDefault(),V.stopPropagation(),Be(V,"escape")):u&&(le!==""||D&&me.length>0||se)&&(V.preventDefault(),V.stopPropagation(),$t(V));break;case"Backspace":if(D&&!re&&le===""&&me.length>0){const de=ge===-1?me.length-1:ge,ve=me.slice();ve.splice(de,1),ht(V,ve,"removeOption",{option:me[de]})}!D&&se&&!re&&(Y(null),ct(-1));break;case"Delete":if(D&&!re&&le===""&&me.length>0&&ge!==-1){const de=ge,ve=me.slice();ve.splice(de,1),ht(V,ve,"removeOption",{option:me[de]})}!D&&se&&!re&&(Y(null),ct(-1));break}},_e=U=>{at(!0),ie&&!De.current&&Ee(U)},dt=U=>{if(n(Z)){ae.current.focus();return}at(!1),Ne.current=!0,De.current=!1,l&&Fe.current!==-1&&Ke?nt(U,fe[Fe.current],"blur"):l&&M&&le!==""?nt(U,le,"blur","freeSolo"):d&&Ie(U,me,"blur"),Be(U,"blur")},Kt=U=>{const V=U.target.value;le!==V&&(Oe(V),Mt(!1),X&&X(U,V,"input")),V===""?!b&&!D&&ht(U,null,"clear"):Ee(U)},yn=U=>{const V=Number(U.currentTarget.getAttribute("data-option-index"));Fe.current!==V&&Ze({event:U,index:V,reason:"mouse"})},ft=U=>{Ze({event:U,index:Number(U.currentTarget.getAttribute("data-option-index")),reason:"touch"}),We.current=!0},en=U=>{const V=Number(U.currentTarget.getAttribute("data-option-index"));nt(U,fe[V],"selectOption"),We.current=!1},xn=U=>V=>{const de=me.slice();de.splice(U,1),ht(V,de,"removeOption",{option:me[U]})},Qt=U=>{ht(U,null,"removeOption",{option:me})},Xe=U=>{lt?Be(U,"toggleInput"):Ee(U)},Je=U=>{U.currentTarget.contains(U.target)&&U.target.getAttribute("id")!==oe&&U.preventDefault()},Rt=U=>{U.currentTarget.contains(U.target)&&(ae.current.focus(),ne&&Ne.current&&ae.current.selectionEnd-ae.current.selectionStart===0&&ae.current.select(),Ne.current=!1)},tn=U=>{!v&&(le===""||!lt)&&Xe(U)};let Zt=M&&le.length>0;Zt=Zt||(D?me.length>0:me!==null);let nn=fe;return _&&(nn=fe.reduce((U,V,de)=>{const ve=_(V);return U.length>0&&U[U.length-1].group===ve?U[U.length-1].options.push(V):U.push({key:de,index:de,group:ve,options:[V]}),U},[])),v&&Re&&dt(),{getRootProps:(U={})=>({...U,onKeyDown:gn(U),onMouseDown:Je,onClick:Rt}),getInputLabelProps:()=>({id:`${oe}-label`,htmlFor:oe}),getInputProps:()=>({id:oe,value:le,onBlur:dt,onFocus:_e,onChange:Kt,onMouseDown:tn,"aria-activedescendant":Ke?"":null,"aria-autocomplete":s?"both":"list","aria-controls":qe?`${oe}-listbox`:void 0,"aria-expanded":qe,autoComplete:"off",ref:ae,autoCapitalize:"none",spellCheck:"false",role:"combobox",disabled:v}),getClearProps:()=>({tabIndex:-1,type:"button",onClick:$t}),getItemProps:({index:U=0}={})=>({...D&&{key:U},...se?{"data-item-index":U}:{"data-tag-index":U},tabIndex:-1,...!re&&{onDelete:D?xn(U):Qt}}),getPopupIndicatorProps:()=>({tabIndex:-1,type:"button",onClick:Xe}),getTagProps:({index:U})=>({key:U,"data-tag-index":U,tabIndex:-1,...!re&&{onDelete:xn(U)}}),getListboxProps:()=>({role:"listbox",id:`${oe}-listbox`,"aria-labelledby":`${oe}-label`,ref:Le,onMouseDown:U=>{U.preventDefault()}}),getOptionProps:({index:U,option:V})=>{const de=(D?me:[me]).some(te=>te!=null&&H(V,te)),ve=O?O(V):!1;return{key:I?.(V)??ue(V),tabIndex:-1,role:"option",id:`${oe}-option-${U}`,onMouseMove:yn,onClick:en,onTouchStart:ft,"data-option-index":U,"aria-disabled":ve,"aria-selected":de}},id:oe,inputValue:le,value:me,dirty:Zt,expanded:Ke&&ce,popupOpen:Ke,focused:Re||ge!==-1,anchorEl:ce,setAnchorEl:be,focusedItem:ge,focusedTag:ge,groupedOptions:nn}}function Fh(e){return c.generateUtilityClass("MuiListSubheader",e)}c.generateUtilityClasses("MuiListSubheader",["root","colorPrimary","colorInherit","gutters","inset","sticky"]);const $h=e=>{const{classes:n,color:r,disableGutters:s,inset:i,disableSticky:l}=e,a={root:["root",r!=="default"&&`color${c.capitalize(r)}`,!s&&"gutters",i&&"inset",!l&&"sticky"]};return c.composeClasses(a,Fh,n)},Rh=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}}]}))),Qs=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiListSubheader"}),{className:i,color:l="default",component:a="li",disableGutters:d=!1,disableSticky:u=!1,inset:h=!1,...g}=s,b={...s,color:l,component:a,disableGutters:d,disableSticky:u,inset:h},x=$h(b);return t.jsx(Rh,{as:a,className:c.clsx(x.root,i),ref:r,ownerState:b,...g})});Qs&&(Qs.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 Lh(e){return c.generateUtilityClass("MuiAutocomplete",e)}const Te=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 Vi,Hi;const Nh=e=>{const{classes:n,disablePortal:r,expanded:s,focused:i,fullWidth:l,hasClearIcon:a,hasPopupIcon:d,inputFocused:u,popupOpen:h,size:g}=e,b={root:["root",s&&"expanded",i&&"focused",l&&"fullWidth",a&&"hasClearIcon",d&&"hasPopupIcon"],inputRoot:["inputRoot"],input:["input",u&&"inputFocused"],tag:["tag",`tagSize${c.capitalize(g)}`],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,Lh,n)},Ph=c.styled("div",{name:"MuiAutocomplete",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e,{fullWidth:s,hasClearIcon:i,hasPopupIcon:l,inputFocused:a,size:d}=r;return[{[`& .${Te.tag}`]:n.tag},{[`& .${Te.tag}`]:n[`tagSize${c.capitalize(d)}`]},{[`& .${Te.inputRoot}`]:n.inputRoot},{[`& .${Te.input}`]:n.input},{[`& .${Te.input}`]:a&&n.inputFocused},n.root,s&&n.fullWidth,l&&n.hasPopupIcon,i&&n.hasClearIcon]}})({[`&.${Te.focused} .${Te.clearIndicator}`]:{visibility:"visible"},"@media (pointer: fine)":{[`&:hover .${Te.clearIndicator}`]:{visibility:"visible"}},[`& .${Te.tag}`]:{margin:3,maxWidth:"calc(100% - 6px)"},[`& .${Te.inputRoot}`]:{[`.${Te.hasPopupIcon}&, .${Te.hasClearIcon}&`]:{paddingRight:30},[`.${Te.hasPopupIcon}.${Te.hasClearIcon}&`]:{paddingRight:56},[`& .${Te.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,[`.${Te.hasPopupIcon}&, .${Te.hasClearIcon}&`]:{paddingRight:39},[`.${Te.hasPopupIcon}.${Te.hasClearIcon}&`]:{paddingRight:65},[`& .${Te.input}`]:{padding:"7.5px 4px 7.5px 5px"},[`& .${Te.endAdornment}`]:{right:9}},[`& .${c.outlinedInputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{paddingTop:6,paddingBottom:6,paddingLeft:6,[`& .${Te.input}`]:{padding:"2.5px 4px 2.5px 8px"}},[`& .${c.filledInputClasses.root}`]:{paddingTop:19,paddingLeft:8,[`.${Te.hasPopupIcon}&, .${Te.hasClearIcon}&`]:{paddingRight:39},[`.${Te.hasPopupIcon}.${Te.hasClearIcon}&`]:{paddingRight:65},[`& .${c.filledInputClasses.input}`]:{padding:"7px 4px"},[`& .${Te.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,[`& .${Te.input}`]:{paddingTop:16,paddingBottom:17}},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.hiddenLabel}.${c.inputBaseClasses.sizeSmall}`]:{[`& .${Te.input}`]:{paddingTop:8,paddingBottom:9}},[`& .${Te.input}`]:{flexGrow:1,textOverflow:"ellipsis",opacity:0},variants:[{props:{fullWidth:!0},style:{width:"100%"}},{props:{size:"small"},style:{[`& .${Te.tag}`]:{margin:2,maxWidth:"calc(100% - 4px)"}}},{props:{inputFocused:!0},style:{[`& .${Te.input}`]:{opacity:1}}},{props:{multiple:!0},style:{[`& .${Te.inputRoot}`]:{flexWrap:"wrap"}}}]}),_h=c.styled("div",{name:"MuiAutocomplete",slot:"EndAdornment"})({position:"absolute",right:0,top:"50%",transform:"translate(0, -50%)"}),zh=c.styled(c.IconButton,{name:"MuiAutocomplete",slot:"ClearIndicator"})({marginRight:-2,padding:4,visibility:"hidden"}),Wh=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)"}}]}),qh=c.styled(c.Popper,{name:"MuiAutocomplete",slot:"Popper",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${Te.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"}}]}))),Bh=c.styled(c.Paper,{name:"MuiAutocomplete",slot:"Paper"})(c.memoTheme(({theme:e})=>({...e.typography.body1,overflow:"auto"}))),Vh=c.styled("div",{name:"MuiAutocomplete",slot:"Loading"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Hh=c.styled("div",{name:"MuiAutocomplete",slot:"NoOptions"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Uh=c.styled("ul",{name:"MuiAutocomplete",slot:"Listbox"})(c.memoTheme(({theme:e})=>({listStyle:"none",margin:0,padding:"8px 0",maxHeight:"40vh",overflow:"auto",position:"relative",[`& .${Te.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"},[`&.${Te.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"},[`&.${Te.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),[`&.${Te.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}},[`&.${Te.focusVisible}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.focusOpacity}`)}}}}))),Gh=c.styled(Qs,{name:"MuiAutocomplete",slot:"GroupLabel"})(c.memoTheme(({theme:e})=>({backgroundColor:(e.vars||e).palette.background.paper,top:-8}))),Yh=c.styled("ul",{name:"MuiAutocomplete",slot:"GroupUl"})({padding:0,[`& .${Te.option}`]:{paddingLeft:24}}),Zs=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiAutocomplete"}),{autoComplete:i=!1,autoHighlight:l=!1,autoSelect:a=!1,blurOnSelect:d=!1,ChipProps:u,className:h,clearIcon:g=Vi||(Vi=t.jsx(Ah,{fontSize:"small"})),clearOnBlur:b=!s.freeSolo,clearOnEscape:x=!1,clearText:v="Clear",closeText:C="Close",componentsProps:k,defaultValue:S=s.multiple?[]:null,disableClearable:T=!1,disableCloseOnSelect:M=!1,disabled:O=!1,disabledItemsFocusable:I=!1,disableListWrap:R=!1,disablePortal:_=!1,filterOptions:$,filterSelectedOptions:B=!1,forcePopupIcon:F="auto",freeSolo:N=!1,fullWidth:H=!1,getLimitTagsText:D=$e=>`+${$e}`,getOptionDisabled:W,getOptionKey:K,getOptionLabel:J,isOptionEqualToValue:X,groupBy:G,handleHomeEndKeys:Q=!s.freeSolo,id:ie,includeInputInList:z=!1,inputValue:re,limitTags:se=-1,ListboxComponent:ne,ListboxProps:Me,loading:oe=!1,loadingText:ue="Loading…",multiple:De=!1,noOptionsText:Ne="No options",onChange:ae,onClose:Z,onHighlightChange:ce,onInputChange:be,onOpen:ge,open:he,openOnFocus:ye=!1,openText:Fe="Open",options:ze,PaperComponent:me,PopperComponent:Y,popupIcon:le=Hi||(Hi=t.jsx(c.ArrowDropDownIcon,{})),readOnly:Oe=!1,renderGroup:Re,renderInput:at,renderOption:Ie,renderTags:lt,renderValue:xt,selectOnFocus:vt=!s.freeSolo,size:Mt="medium",slots:mt={},slotProps:Ke={},value:fe,...Qe}=s,{getRootProps:qe,getInputProps:ct,getInputLabelProps:ut,getPopupIndicatorProps:Ze,getClearProps:pe,getItemProps:Ue,getListboxProps:bt,getOptionProps:Ce,value:Le,dirty:Ee,expanded:Be,id:ht,popupOpen:We,focused:nt,focusedItem:Ot,anchorEl:kt,setAnchorEl:$t,inputValue:gn,groupedOptions:_e}=Dh({...s,componentName:"Autocomplete"}),dt=!T&&!O&&Ee&&!Oe,Kt=(!N||F===!0)&&F!==!1,{onMouseDown:yn}=ct(),{ref:ft,...en}=bt(),Qt=J||($e=>$e.label??$e),Xe={...s,disablePortal:_,expanded:Be,focused:nt,fullWidth:H,getOptionLabel:Qt,hasClearIcon:dt,hasPopupIcon:Kt,inputFocused:Ot===-1,popupOpen:We,size:Mt},Je=Nh(Xe),Rt={slots:{paper:me,popper:Y,...mt},slotProps:{chip:u,listbox:Me,...k,...Ke}},[tn,Zt]=c.useSlot("listbox",{elementType:Uh,externalForwardedProps:Rt,ownerState:Xe,className:Je.listbox,additionalProps:en,ref:ft}),[nn,U]=c.useSlot("paper",{elementType:c.Paper,externalForwardedProps:Rt,ownerState:Xe,className:Je.paper}),[V,de]=c.useSlot("popper",{elementType:c.Popper,externalForwardedProps:Rt,ownerState:Xe,className:Je.popper,additionalProps:{disablePortal:_,style:{width:kt?kt.clientWidth:null},role:"presentation",anchorEl:kt,open:We}});let ve;const te=$e=>({className:Je.tag,disabled:O,...Ue($e)});if(De?Le.length>0&&(lt?ve=lt(Le,te,Xe):xt?ve=xt(Le,te,Xe):ve=Le.map(($e,zt)=>{const{key:gt,...qt}=te({index:zt});return t.jsx(c.Chip,{label:Qt($e),size:Mt,...qt,...Rt.slotProps.chip},gt)})):xt&&Le!=null&&(ve=xt(Le,te,Xe)),se>-1&&Array.isArray(ve)){const $e=ve.length-se;!nt&&$e>0&&(ve=ve.splice(0,se),ve.push(t.jsx("span",{className:Je.tag,children:D($e)},ve.length)))}const Ge=Re||($e=>t.jsxs("li",{children:[t.jsx(Gh,{className:Je.groupLabel,ownerState:Xe,component:"div",children:$e.group}),t.jsx(Yh,{className:Je.groupUl,ownerState:Xe,children:$e.children})]},$e.key)),vn=Ie||(($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:Je.option},$e,{selected:gt["aria-selected"],index:zt,inputValue:gn},Xe)},Wn=Rt.slotProps.clearIndicator,Fr=Rt.slotProps.popupIndicator;return t.jsxs(we.Fragment,{children:[t.jsx(Ph,{ref:r,className:c.clsx(Je.root,h),ownerState:Xe,...qe(Qe),children:at({id:ht,disabled:O,fullWidth:!0,size:Mt==="small"?"small":void 0,InputLabelProps:ut(),InputProps:{ref:$t,className:Je.inputRoot,startAdornment:ve,onMouseDown:$e=>{$e.target===$e.currentTarget&&yn($e)},...(dt||Kt)&&{endAdornment:t.jsxs(_h,{className:Je.endAdornment,ownerState:Xe,children:[dt?t.jsx(zh,{...pe(),"aria-label":v,title:v,ownerState:Xe,...Wn,className:c.clsx(Je.clearIndicator,Wn?.className),children:g}):null,Kt?t.jsx(Wh,{...Ze(),disabled:O,"aria-label":We?C:Fe,title:We?C:Fe,ownerState:Xe,...Fr,className:c.clsx(Je.popupIndicator,Fr?.className),children:le}):null]})}},inputProps:{className:Je.input,disabled:O,readOnly:Oe,...ct()}})}),kt?t.jsx(qh,{as:V,...de,children:t.jsxs(Bh,{as:nn,...U,children:[oe&&_e.length===0?t.jsx(Vh,{className:Je.loading,ownerState:Xe,children:ue}):null,_e.length===0&&!N&&!oe?t.jsx(Hh,{className:Je.noOptions,ownerState:Xe,role:"presentation",onMouseDown:$e=>{$e.preventDefault()},children:Ne}):null,_e.length>0?t.jsx(tn,{as:ne,...Zt,children:_e.map(($e,zt)=>G?Ge({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 Ms(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 Kh(e){return e==="DateMinMax"}function Os(e){return e==="Between"}function Qh({spec:e,values:n,selection:r,onChange:s,retrievalFn:i}){const l=()=>r?.matchType?r.matchType:e.defaultMatchType?e.defaultMatchType:e.filterType==="DateMinMax"?"Between":Ms(e.filterType)[0]||"Equals",[a,d]=j.useState(l()),[u,h]=j.useState(r?.value??""),[g,b]=j.useState(r?.value2??""),[x,v]=j.useState([]),[C,k]=j.useState(!1),[S,T]=j.useState(""),[M,O]=j.useState(!1),[I,R]=j.useState(!1),_=j.useRef(null),$=j.useRef(0),[B,F]=j.useState(!1);j.useEffect(()=>{if(e.filterType!=="Retrieval"||!i)return;const z=S.trim();if(z.length<=2){v([]),O(!1);return}return _.current&&clearTimeout(_.current),_.current=setTimeout(async()=>{$.current+=1;const re=$.current;k(!0);try{const se=await i(z,e);re===$.current&&v(se)}catch(se){re===$.current&&(console.error("Retrieval failed",se),v([]))}finally{re===$.current&&(k(!1),O(!0))}},500),()=>{_.current&&clearTimeout(_.current)}},[S,e,i]),j.useEffect(()=>{r===null?(h(""),b(""),d(e.defaultMatchType??(e.filterType==="DateMinMax"?"Between":Ms(e.filterType)[0]||"Equals"))):r&&(d(r.matchType),h(r.value??""),b(r.value2??""))},[r,e.filterType,e.defaultMatchType]);const N=Ms(e.filterType),H=Kh(e.filterType),D=Os(a),W=H&&n.length>=2&&n[0].value instanceof Date?c.dayjs.utc(n[0].value):void 0,K=H&&n.length>=2&&n[1].value instanceof Date?c.dayjs.utc(n[1].value):void 0,J=e.filterType==="MinMax"&&n.length>=2&&typeof n[0].value=="number"?n[0].value:void 0,X=e.filterType==="MinMax"&&n.length>=2&&typeof n[1].value=="number"?n[1].value:void 0;if(N.length===0)return null;const G=z=>{const re=z.target.value;d(re),Os(re)||b(""),u&&s({dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:re,value:u,...Os(re)&&g&&{value2:g}})},Q=(z,re)=>{h(z??""),re!==void 0&&b(re??"");const se=Array.isArray(z)&&z.length===0;s(!se&&z!==""&&z!==null&&z!==void 0?{dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:a,value:z,...D&&re&&{value2:re}}:null)},ie=()=>{h(""),b(""),s(null)};return t.jsxs(Ye,{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(Ye,{sx:{fontWeight:600,color:e.required&&!r?"error.main":"text.primary"},children:[e.label??e.dimensionName,e.required&&t.jsx(Ye,{component:"span",sx:{color:r?"text.secondary":"error.main",fontWeight:400,fontSize:"0.7rem",ml:.5},children:"(required)"})]}),e.filterType!=="Boolean"&&!e.defaultMatchType&&N.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:G,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:N.map(z=>t.jsx(tt,{value:z,children:z},z))})]}),e.filterType==="Star"&&a==="Equals"&&t.jsx(Zs,{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(u)?u.map(z=>n.find(re=>re.value===z)||z):u?[n.find(z=>z.value===u)||u]:[],onChange:(z,re)=>{const se=re.map(ne=>typeof ne=="string"?ne:ne&&typeof ne=="object"&&"value"in ne?ne.value:ne);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:u,onChange:z=>h(z.target.value),onBlur:()=>Q(u),onKeyDown:z=>{z.key==="Enter"&&Q(u)},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:u===!0?"true":u===!1?"false":"",label:"Value",onChange:z=>{const re=z.target.value;re==="true"?Q(!0):re==="false"?Q(!1):ie()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[t.jsx(tt,{value:"",children:t.jsx("em",{children:"Blank"})}),t.jsx(tt,{value:"true",children:"True"}),t.jsx(tt,{value:"false",children:"False"})]})]}),e.filterType==="Retrieval"&&a==="Semantic Search"&&t.jsx(Zs,{multiple:!0,size:"small",options:x,loading:C,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(u)?u.map(z=>x.find(se=>se.value===z)||{value:z}):u?[{value:u}]:[],onInputChange:(z,re)=>{T(re)},onChange:(z,re)=>{const se=re.map(ne=>typeof ne=="string"?ne:ne&&typeof ne=="object"&&"value"in ne?ne.value:ne);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:I&&!C&&M&&x.length===0?"No matches found":void 0,InputProps:{...z.InputProps,endAdornment:t.jsxs(t.Fragment,{children:[C?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"&&!D&&t.jsx(c.TextField,{size:"small",type:"number",label:"Value",value:u,onChange:z=>Q(parseFloat(z.target.value)||""),onFocus:()=>F(!0),onBlur:()=>F(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:J,max:X},helperText:B&&J!==void 0&&X!==void 0?`Valid range: [${J} - ${X}]`:void 0}),e.filterType==="MinMax"&&D&&t.jsxs(Ye,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ye,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(c.TextField,{size:"small",type:"number",label:"From",value:u,onChange:z=>Q(parseFloat(z.target.value)||"",g),onFocus:()=>F(!0),onBlur:()=>F(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:J,max:g||X}}),t.jsx(Ye,{children:"to"}),t.jsx(c.TextField,{size:"small",type:"number",label:"To",value:g,onChange:z=>Q(u,parseFloat(z.target.value)||""),onFocus:()=>F(!0),onBlur:()=>F(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:u||J,max:X}})]}),B&&J!==void 0&&X!==void 0&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",J," - ",X,"]"]})]}),H&&!D&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsx(c.DatePicker,{label:"Date",value:u instanceof Date?c.dayjs.utc(u):null,onChange:z=>{z===null?Q(null):z.isValid()&&Q(z.utc().toDate())},timezone:"UTC",minDate:u instanceof Date?void 0:W,maxDate:u instanceof Date?void 0:K,referenceDate:a==="After"&&W?W:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>F(!0),onBlur:()=>F(!1),helperText:B&&W&&K?`Valid range: [${W.format("YYYY-MM-DD")} - ${K.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),H&&D&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsxs(Ye,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ye,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(Ye,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"From",value:u instanceof Date?c.dayjs.utc(u):null,onChange:z=>{z===null?Q(null,g):z.isValid()&&Q(z.utc().toDate(),g)},timezone:"UTC",minDate:u instanceof Date?void 0:W,maxDate:g instanceof Date?c.dayjs.utc(g):u instanceof Date?void 0:K,referenceDate:W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>F(!0),onBlur:()=>F(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),t.jsx(Ye,{children:"to"}),t.jsx(Ye,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"To",value:g instanceof Date?c.dayjs.utc(g):null,onChange:z=>{z===null?Q(u,null):z.isValid()&&Q(u,z.utc().toDate())},timezone:"UTC",minDate:u instanceof Date?c.dayjs.utc(u):g instanceof Date?void 0:W,maxDate:g instanceof Date?void 0:K,referenceDate:u instanceof Date?c.dayjs.utc(u):W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>F(!0),onBlur:()=>F(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),B&&W&&K&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",W.format("YYYY-MM-DD")," -"," ",K.format("YYYY-MM-DD"),"]"]})]})})]})}function as(e,n){const{matchType:r,value:s,value2:i}=n;if(Array.isArray(s))return r!=="Equals"&&r!=="Semantic Search"||s.length===0?"":`(${s.map(a=>`${e} = ${c.formatMalloyValue(a)}`).join(" or ")})`;switch(r){case"Equals":case"Semantic Search":return`${e} = ${c.formatMalloyValue(s)}`;case"Contains":if(typeof s=="string"){const l=ed.StringFilterExpression.unparse({operator:"contains",values:[s]});return`${e} ~ ${c.malloyFilterLiteral(l)}`}return`${e} = ${c.formatMalloyValue(s)}`;case"After":case"Greater Than":return`${e} > ${c.formatMalloyValue(s)}`;case"Before":case"Less Than":return`${e} < ${c.formatMalloyValue(s)}`;case"Between":return i!==void 0?`${e} >= ${c.formatMalloyValue(s)} and ${e} <= ${c.formatMalloyValue(i)}`:`${e} >= ${c.formatMalloyValue(s)}`;default:return""}}function Zh(e){const n=new Set,r=e.schema?.fields;if(!r)return n;for(const s of r)"kind"in s&&s.kind==="join"&&s.name&&n.add(s.name);return n}function Xh(e){if(!e)return null;for(const n of e)if(n.startsWith("##(filters)")){const r=n.slice(11).trim();try{const s=JSON.parse(r);if(Array.isArray(s)){const i=[];for(const l of s)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(s){console.error(`Failed to parse "${n}" annotation:`,s)}}return null}function ol(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 Jh(e){const n=e.match(/^#\s*label\s*=\s*"([^"]+)"/);return n?n[1]:null}function ef(e){const n=new Map;let r="";for(const s of e)if(s.type==="code"){if(!r&&s.text){const l=s.text.split(`
3
+ `}function yd(e,n){return[e,"rows",...n].join("_").replace(/[^A-Za-z0-9._-]+/g,"_").replace(/_+/g,"_").replace(/^[_.]+|[_.]+$/g,"").slice(0,120)||"rows"}function xd(e,n,r){return r==="server_default"&&n!==void 0&&e>=n?n:void 0}const Oi="Download the rows behind this value as CSV, up to the server's row limit",vd=4e4;function bd(e,n){const r=URL.createObjectURL(new Blob([e],{type:"text/csv;charset=utf-8"})),s=document.createElement("a");s.href=r,s.download=n,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),vd)}function wd(e){const r=e?.response?.data?.message;return typeof r=="string"&&r!==""?r:e instanceof Error&&e.message!==""?e.message:"The request failed."}function Ya({query:e,preamble:n,environmentName:r,packageName:s,modelPath:i,versionId:l,givens:a,fileName:d}){const{apiClients:u}=q.useServer(),[h,g]=j.useState(!1),[b,x]=j.useState(Oi),[v,C]=j.useState(void 0),k=j.useRef(void 0);j.useEffect(()=>()=>k.current?.abort(),[]);const S=async()=>{k.current?.abort();const T=new AbortController;k.current=T,g(!0),C(void 0);try{const M=await u.models.executeQueryModel(r,s,i,{query:n===void 0?e:c.withPreamble(n,e),givens:a,versionId:l},void 0,{signal:T.signal});if(T.signal.aborted)return;const O=M.data,I=JSON.parse(O.result??"{}"),R=xd(Ga(I).length,O.queryRowLimit,O.queryRowLimitSource);x(R===void 0?Oi:`First ${R} rows: the server's row limit, so there may be more`),bd(gd(I),R===void 0?`${d}.csv`:`${d}_first_${R}_rows_server_limit.csv`)}catch(M){if(T.signal.aborted)return;C(`Download failed: ${wd(M)}`)}finally{k.current===T&&(k.current=void 0,g(!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(pd,{fontSize:"small"}),onClick:()=>void S(),disabled:h,children:"Download CSV"})})})]})}const Ka=200;function Sd(e){const{target:n}=e;if(n!==void 0&&!(e.dimensions===void 0&&e.code===void 0))return{...e,target:n}}function Ii(e,n=Ka){const r=Cd(e);if(r===void 0)return;const s=[...e.target.filters,...r].join(", "),i=e.timezone?`timezone: '${c.escapeMalloyString(e.timezone)}'; `:"",l=n===null?"":`; limit: ${n}`,a=kd(e.target.source);if(a!==void 0)return`run: ${a} -> { ${i}where: ${s}; select: *${l} }`}function kd(e){return io.isBareName(e)?e:e.includes("`")?void 0:`\`${e}\``}function js(e){return/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(e)?e:`(${e})`}function Cd(e){if(e.dimensions){const r=[];for(const{code:s,value:i}of e.dimensions){if(i.kind==="null_literal"){r.push(`${js(s)} is null`);continue}const l=_a(i,e.timezone);if(l===void 0)return;r.push(`${js(s)} = ${l}`)}return r}const n=c.malloyLiteral(e.rawValue);return e.code!==void 0&&n?[`${js(e.code)} = ${n}`]:void 0}const jd="This value cannot be written as a filter, so its rows cannot be fetched.";function Ei(e){const n=e.drillClauses?Pa(e.drillClauses,e.timezone):[];return n.length>0?n:[{field:e.field,label:e.label}]}function Td({request:e,environmentName:n,packageName:r,versionId:s,modelPath:i,preamble:l,givens:a,onClose:d,onDone:u,actions:h}){const{theme:g}=q.usePublisherTheme(),b=e?Ii(e):void 0,x=e?Ii(e,null):void 0,v=e&&x!==void 0?{query:x,...l===void 0?{}:{preamble:l},environmentName:n,packageName:r,modelPath:i,...s===void 0?{}:{versionId:s},givens:a,fileName:yd(e.target.source,Ei(e).map(C=>C.label))}:void 0;return t.jsxs(m.Dialog,{open:e!==void 0,onClose:d,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"," ",Ei(e).map((C,k)=>t.jsxs(j.Fragment,{children:[k>0&&" and ",t.jsx(m.Box,{component:"code",sx:{fontSize:"0.9em"},children:C.field})," ","is ",C.label]},k))]}):"Rows",t.jsx(m.Typography,{component:"div",variant:"caption",sx:{color:g.tileTitle,mt:.25},children:e?`The first ${Ka} 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(Ya,{...v})),t.jsx(m.IconButton,{onClick:d,"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:jd}),b!==void 0&&t.jsx(Md,{query:l===void 0?b:c.withPreamble(l,b),environmentName:n,packageName:r,...s===void 0?{}:{versionId:s},modelPath:i,givens:a,...u?{onDone:u}:{}})]}),t.jsxs(m.DialogActions,{sx:{px:3,py:1.5},children:[b!==void 0&&t.jsx(m.Typography,{variant:"caption",sx:{mr:"auto",color:g.tileTitle,fontFamily:g.ui.font.mono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:b,children:b}),t.jsx(m.Button,{onClick:d,children:"Close"})]})]})}function Md({query:e,environmentName:n,packageName:r,versionId:s,modelPath:i,givens:l,onDone:a}){const d=c.useQueryResult({environmentName:n,packageName:r,modelPath:i,...s===void 0?{}:{versionId:s},query:e,givens:l}),{isSuccess:u,isError:h}=d,g=j.useRef(void 0);return j.useEffect(()=>{g.current=c.now()},[e]),j.useEffect(()=>{g.current===void 0||!u&&!h||(a?.(u,c.now()-g.current),g.current=void 0)},[u,h,a]),t.jsx(m.Box,{sx:{p:1},children:t.jsx(c.ResultPanel,{state:d,context:e})})}function ss({manifest:e,environmentName:n,packageName:r,versionId:s,documentName:i,givens:l,onGivensChange:a,onNavigate:d,height:u,maxResultSize:h,controlsLayout:g="bar",preamble:b,runModelPath:x,hiddenGivens:v,literalReads:C,onLinkNavigate:k,actions:S,rowsActions:T}){const M=j.useMemo(()=>k?{environmentName:n,packageName:r,sourcePath:e.path??i,onNavigate:k}:void 0,[n,r,e.path,i,k]),O=j.useMemo(()=>(e.givens??[]).filter(ae=>!(b!==void 0&&ae.secure===!0)&&!(ae.name!==void 0&&v?.includes(ae.name))),[e,v,b]),I=j.useMemo(()=>l===void 0?void 0:Object.fromEntries(Object.entries(l).filter(([,ae])=>typeof ae=="string")),[l]),R=c.useDocumentControls({specs:O,loaded:!0,startingValues:e.startingGivens,params:I,onGivensChange:a,documentKey:`${n}/${r}/${s??""}/${i}`,autorun:e.autorun!==!1,environmentName:n,packageName:r,modelPath:x??e.path,versionId:s,documentName:i,...b!==void 0?{preamble:b}:{},...l?{hostGivens:l}:{}}),{applied:_,declaredTypes:$,canSelf:B,onSelf:F}=R,N=c.useReportEvents(),H=j.useMemo(()=>{const ae=new Set((e.tiles??[]).flatMap(Z=>Z.givenNames??[]));return Object.fromEntries(Object.entries(l??{}).filter(([Z])=>ae.has(Z)&&!$.has(Z)))},[e,l,$]),[D,W]=j.useState(void 0),K=j.useCallback(ae=>{const Z=Sd(ae);Z!==void 0&&W(Z)},[]),J=j.useMemo(()=>c.withHostGivens(c.givensToRequest(_,$),H),[_,$,H]),{reports:X}=c.useReportListing(n,r,s,d!==void 0),G=j.useCallback(ae=>{const Z=c.resolveDrillTarget(ae,X);if(Z.kind!=="path")return;const ce=Z.report.path;return X.find(be=>be.path===ce)?.title||void 0},[X]),{bindingFor:Q,drillMenu:ie}=ao({onNavigate:d,onSelf:F,canSelf:B,onRows:K,destinationTitle:G}),z=j.useCallback((ae,Z)=>Q(ae,Z!==!0),[Q]),{columns:re,layout:se,tileMaxHeight:ne,tableMaxHeight:Me}=c.layoutRules(e.layout,e.dashboardColumns),oe=j.useMemo(()=>c.missingRequiredGivens(O,_,l),[O,_,l]);if(e.error)return t.jsx(c.ReportPage,{layout:se,header:t.jsx(Di,{manifest:e,links:M,actions:S}),children:t.jsx(m.Alert,{severity:"error",children:e.error})});const ue=x??e.path,De=e.tiles??[],Ne=c.isPlaced(De);return t.jsxs(c.ReportPage,{layout:se,header:t.jsx(Di,{manifest:e,links:M,actions:S}),controls:O.length>0?t.jsx(c.StickyControls,{children:t.jsx(c.GivensPanel,{...R.panel,layout:g})}):void 0,children:[oe.length>0&&t.jsx(m.Alert,{severity:"info",children:c.requiredPrompt(oe)}),ue===void 0?t.jsx(m.Alert,{severity:"error",children:"This dashboard has no model path, so there is nothing to run."}):De.length>0?t.jsx(c.DashboardGrid,{tiles:De,columns:re,minTilePx:c.MIN_TILE_PX,rowGapPx:c.GRID_GAP_PX,keyOf:(ae,Z)=>`${Z}:${ae.kind==="text"?`text:${ae.name}`:ae.query}`,renderTile:(ae,Z)=>ae.kind==="text"||ae.query===void 0?t.jsx(m.Box,{sx:ae.rowspan!==void 0||Ne?{minHeight:0,overflow:"auto"}:void 0,children:t.jsx(Od,{markdown:ae.markdown??"",links:M})}):t.jsx(c.DashboardTile,{index:Z,environmentName:n,packageName:r,versionId:s,modelPath:ue,tile:ae.query,label:ae.label,subtitle:ae.subtitle,borderless:ae.borderless,givens:_,hostGivens:H,declaredTypes:$,givenNames:ae.givenNames,height:ae.rowspan!==void 0||Ne?c.tileHeightPx(ae.rowspan??c.PLACED_DEFAULT_ROWSPAN.query):se==="grid"?u??ne:ne,tableMaxHeight:Me,fixedHeight:ae.rowspan!==void 0||Ne,maxResultSize:h,drill:z(ae.query,ae.restricted),ignoredFilters:c.tileIgnoredFilterLabels(ae.givenNames&&(ae.query&&C?.[ae.query]?[...ae.givenNames,...C[ae.query]]:ae.givenNames),O),...b!==void 0?{preamble:b,restricted:ae.restricted}:{},...(()=>{const ce=c.waitingOn(oe,ae.givenNames);return ce.length>0?{waitingFor:c.waitingText(ce)}:{}})()})}):t.jsx(m.Alert,{severity:"warning",children:"This dashboard names neither a query nor any tiles."}),ie,ue!==void 0&&t.jsx(Td,{request:D,environmentName:n,packageName:r,...s===void 0?{}:{versionId:s},modelPath:ue,...b===void 0?{}:{preamble:b},givens:J,...T===void 0?{}:{actions:T},onClose:()=>W(void 0),onDone:(ae,Z)=>{D&&N.emit({type:"report.rows_shown",source:D.target.source,view:D.target.queryName??"",field:D.field,ok:ae,durationMs:Z})}})]})}function Od({markdown:e,links:n}){return t.jsx(c.TextTileFrame,{children:t.jsx(c.Prose,{variant:"document",links:n,children:e})})}function Di({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 Qa=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"})),Id="publisher:resize";function Ed(e){return typeof e=="object"&&e!==null&&e.type===Id&&typeof e.height=="number"}function Za(e){return e.replace(/\/api\/v0\/?$/,"")}function Xa({server:e,environmentName:n,packageName:r,path:s,versionId:i}){const l=s.startsWith("public/")?s.slice(7):s,a=`${Za(e)}/environments/${encodeURIComponent(n)}/packages/${encodeURIComponent(r)}/`+l;return i===void 0?a:`${a}${a.includes("?")?"&":"?"}versionId=${encodeURIComponent(i)}`}function Dd(e){try{const{environmentName:n,packageName:r,modelPath:s,versionId:i}=c.parseResourceUri(e);return!n||!r||!s?null:{environmentName:n,packageName:r,dataAppPath:s,versionId:i}}catch{return null}}function Fd({resourceUri:e}){const{server:n,apiClients:r}=q.useServer(),s=Dd(e),i=s?.environmentName??"",l=s?.packageName??"",a=s?.dataAppPath??"",d=s?.versionId,u=j.useMemo(()=>Xa({server:n,environmentName:i,packageName:l,path:a,...d!==void 0?{versionId:d}:{}}),[n,i,l,a,d]),g=c.useQueryWithApiError({queryKey:["data-apps",i,l,d],queryFn:()=>r.dataApps.listDataApps(i,l,d),enabled:!!s}).data?.data?.find(S=>S.path===a),b=g?.title??a,x=g?.fit==="viewport",v=j.useRef(null),[C,k]=j.useState(120);return j.useEffect(()=>{if(x)return;function S(T){Ed(T.data)&&T.source===v.current?.contentWindow&&T.data.height>0&&k(Math.ceil(T.data.height))}return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[x]),s?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:u,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:t.jsx(Qa,{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:u,title:b,sandbox:"allow-scripts allow-same-origin allow-forms",style:{display:"block",width:"100%",height:x?"100%":C,border:0}})})]}):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 Pt({title:e,count:n,description:r,action:s,children:i}){const l=j.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,")"]})]}),s]}),r&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:r}),t.jsx(m.Box,{children:i})]})}function $d({resourceUri:e}){const{environmentName:n}=c.parseResourceUri(e),{apiClients:r}=q.useServer(),[s,i]=j.useState(!1),l=90,{data:a,isSuccess:d,isError:u,error:h}=c.useQueryWithApiError({queryKey:["about",n],queryFn:()=>r.environments.getEnvironment(n,!1)}),g=a?.data?.readme||"",b=g.split(/\s+/),x=b.length>l,v=b.slice(0,l).join(" ");return t.jsxs(t.Fragment,{children:[!d&&!u&&t.jsx(c.Loading,{text:"Fetching About..."}),d&&g&&t.jsxs(Pt,{title:"Readme",children:[t.jsx(c.Prose,{variant:"caption",children:s||!x?g:v}),x&&t.jsx(m.Box,{sx:{mt:1},children:t.jsx(c.SecondaryButton,{label:s?"Read less":"Read more",onClick:()=>i(!s)})})]}),u&&t.jsx(c.ApiErrorDisplay,{error:h,context:`${n} > About`})]})}function Rd(e={}){const{autoHideDuration:n=null,disableWindowBlurListener:r=!1,onClose:s,open:i,resumeHideDuration:l}=e,a=c.useTimeout();we.useEffect(()=>{if(!i)return;function T(M){M.defaultPrevented||M.key==="Escape"&&s?.(M,"escapeKeyDown")}return document.addEventListener("keydown",T),()=>{document.removeEventListener("keydown",T)}},[i,s]);const d=c.useEventCallback((T,M)=>{s?.(T,M)}),u=c.useEventCallback(T=>{!s||T==null||a.start(T,()=>{d(null,"timeout")})});we.useEffect(()=>(i&&u(n),a.clear),[i,n,u,a]);const h=T=>{s?.(T,"clickaway")},g=a.clear,b=we.useCallback(()=>{n!=null&&u(l??n*.5)},[n,l,u]),x=T=>M=>{const O=T.onBlur;O?.(M),b()},v=T=>M=>{const O=T.onFocus;O?.(M),g()},C=T=>M=>{const O=T.onMouseEnter;O?.(M),g()},k=T=>M=>{const O=T.onMouseLeave;O?.(M),b()};return we.useEffect(()=>{if(!r&&i)return window.addEventListener("focus",b),window.addEventListener("blur",g),()=>{window.removeEventListener("focus",b),window.removeEventListener("blur",g)}},[r,i,b,g]),{getRootProps:(T={})=>{const M={...c.extractEventHandlers(e),...c.extractEventHandlers(T)};return{role:"presentation",...T,...M,onBlur:x(M),onFocus:v(M),onMouseEnter:C(M),onMouseLeave:k(M)}},onClickAway:h}}function Fi(e){return e.substring(2).toLowerCase()}function Ad(e,n){return n.documentElement.clientWidth<e.clientX||n.documentElement.clientHeight<e.clientY}function Ld(e){const{children:n,disableReactTree:r=!1,mouseEvent:s="onClick",onClickAway:i,touchEvent:l="onTouchEnd"}=e,a=we.useRef(!1),d=we.useRef(null),u=we.useRef(!1),h=we.useRef(!1);we.useEffect(()=>(setTimeout(()=>{u.current=!0},0),()=>{u.current=!1}),[]);const g=c.useForkRef(c.getReactElementRef(n),d),b=c.useEventCallback(C=>{const k=h.current;h.current=!1;const S=c.ownerDocument(d.current);if(!u.current||!d.current||"clientX"in C&&Ad(C,S))return;if(a.current){a.current=!1;return}let T;C.composedPath?T=C.composedPath().includes(d.current):T=!S.documentElement.contains(C.target)||d.current.contains(C.target),!T&&(r||!k)&&i(C)}),x=C=>k=>{h.current=!0;const S=n.props[C];S&&S(k)},v={ref:g};return l!==!1&&(v[l]=x(l)),we.useEffect(()=>{if(l!==!1){const C=Fi(l),k=c.ownerDocument(d.current),S=()=>{a.current=!0};return k.addEventListener(C,b),k.addEventListener("touchmove",S),()=>{k.removeEventListener(C,b),k.removeEventListener("touchmove",S)}}},[b,l]),s!==!1&&(v[s]=x(s)),we.useEffect(()=>{if(s!==!1){const C=Fi(s),k=c.ownerDocument(d.current);return k.addEventListener(C,b),()=>{k.removeEventListener(C,b)}}},[b,s]),we.cloneElement(n,v)}function Nd(e){return c.generateUtilityClass("MuiSnackbarContent",e)}c.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const Pd=e=>{const{classes:n}=e,r={root:["root"],action:["action"],message:["message"]};return c.composeClasses(r,Nd,n)},_d=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}}})),zd=c.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),Wd=c.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),qd=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiSnackbarContent"}),{action:i,className:l,message:a,role:d="alert",...u}=s,h=s,g=Pd(h);return t.jsxs(_d,{role:d,elevation:6,className:c.clsx(g.root,l),ownerState:h,ref:r,...u,children:[t.jsx(zd,{className:g.message,ownerState:h,children:a}),i?t.jsx(Wd,{className:g.action,ownerState:h,children:i}):null]})});function Bd(e){return c.generateUtilityClass("MuiSnackbar",e)}c.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const Vd=e=>{const{classes:n,anchorOrigin:r}=e,s={root:["root",`anchorOrigin${c.capitalize(r.vertical)}${c.capitalize(r.horizontal)}`]};return c.composeClasses(s,Bd,n)},Hd=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%)"}}}]}))),Ud=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiSnackbar"}),i=c.useTheme(),l={enter:i.transitions.duration.enteringScreen,exit:i.transitions.duration.leavingScreen},{action:a,anchorOrigin:{vertical:d,horizontal:u}={vertical:"bottom",horizontal:"left"},autoHideDuration:h=null,children:g,className:b,ClickAwayListenerProps:x,ContentProps:v,disableWindowBlurListener:C=!1,message:k,onBlur:S,onClose:T,onFocus:M,onMouseEnter:O,onMouseLeave:I,open:R,resumeHideDuration:_,slots:$={},slotProps:B={},TransitionComponent:F,transitionDuration:N=l,TransitionProps:{onEnter:H,onExited:D,...W}={},...K}=s,J={...s,anchorOrigin:{vertical:d,horizontal:u},autoHideDuration:h,disableWindowBlurListener:C,TransitionComponent:F,transitionDuration:N},X=Vd(J),{getRootProps:G,onClickAway:Q}=Rd({...J}),[ie,z]=we.useState(!0),re=ge=>{z(!0),D&&D(ge)},se=(ge,he)=>{z(!1),H&&H(ge,he)},ne={slots:{transition:F,...$},slotProps:{content:v,clickAwayListener:x,transition:W,...B}},[Me,oe]=c.useSlot("root",{ref:r,className:[X.root,b],elementType:Hd,getSlotProps:G,externalForwardedProps:{...ne,...K},ownerState:J}),[ue,{ownerState:De,...Ne}]=c.useSlot("clickAwayListener",{elementType:Ld,externalForwardedProps:ne,getSlotProps:ge=>({onClickAway:(...he)=>{const ye=he[0];ge.onClickAway?.(...he),!ye?.defaultMuiPrevented&&Q(...he)}}),ownerState:J}),[ae,Z]=c.useSlot("content",{elementType:qd,shouldForwardComponentProp:!0,externalForwardedProps:ne,additionalProps:{message:k,action:a},ownerState:J}),[ce,be]=c.useSlot("transition",{elementType:c.Grow,externalForwardedProps:ne,getSlotProps:ge=>({onEnter:(...he)=>{ge.onEnter?.(...he),se(...he)},onExited:(...he)=>{ge.onExited?.(...he),re(...he)}}),additionalProps:{appear:!0,in:R,timeout:N,direction:d==="top"?"down":"up"},ownerState:J});return!R&&ie?null:t.jsx(ue,{...Ne,...$.clickAwayListener&&{ownerState:De},children:t.jsx(Me,{...oe,children:t.jsx(ce,{...be,children:g||t.jsx(ae,{...Z})})})})});let Ys;function Gd(e){Ys=e}function $i(e){if(Ys)try{Ys(e)}catch{}}function Ht(e,n,r){return(async s=>{const i=Date.now();try{const l=await r(s);return $i({type:"console.mutation",resource:e,action:n,ok:!0,durationMs:Date.now()-i}),l}catch(l){throw $i({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 Pn({mutationFn:e,success:n,invalidates:r,closeDialog:s,resource:i,action:l}){const a=yt.useQueryClient(),[d,u]=j.useState(""),h=c.useMutationWithApiError({mutationFn:Ht(i,l,e),onSuccess(){s();for(const g of r)a.invalidateQueries({queryKey:g});u(n)},onError(g){u(g instanceof Error?g.message:"An unknown error occurred")}});return{mutate:h.mutate,isPending:h.isPending,notice:t.jsx(Ud,{open:d!=="",autoHideDuration:6e3,onClose:()=>u(""),message:d})}}const Ja="https://docs.malloydata.dev/documentation",Ts=`${Ja}/user_guides/publishing`,En="https://github.com/malloydata/publisher/blob/main/docs",Vt={docsHome:`${Ja}/`,publishing:`${Ts}/publishing`,explorer:`${Ts}/explorer`,mcpAgents:`${Ts}/mcp_agents`,surfaces:`${En}/choosing-a-surface.md`,dashboards:`${En}/dashboards.md`,dataApps:`${En}/html-data-apps.md`,givens:`${En}/givens.md`,materialization:`${En}/materialization.md`,connections:`${En}/connections.md`};function Yd({resourceUri:e}){const[n,r]=j.useState(!1),{apiClients:s}=q.useServer(),{environmentName:i}=c.parseResourceUri(e),l=Pn({mutationFn(d){return s.packages.createPackage(i,{name:d.name,description:d.description,location:d.location})},success:"Package created",invalidates:[["packages",i]],closeDialog:()=>r(!1),resource:"package",action:"create"}),a=d=>{d.preventDefault();const u=new FormData(d.currentTarget),h=u.get("name")?.toString(),g=u.get("description")?.toString(),b=u.get("location")?.toString();l.mutate({name:h,description:g,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 Kd=c.createSvgIcon(t.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function os({icon:e,tint:n,label:r,mono:s,description:i,rightLabel:l,trailingAction:a,onClick:d,ariaLabel:u}){const h=!!d,g=b=>{d&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),d(b))};return t.jsxs(m.Box,{onClick:d,onKeyDown:h?g:void 0,role:h?"button":void 0,tabIndex:h?0:void 0,"aria-label":u,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:{...s?{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 el=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"})),Qd=c.generateUtilityClasses("MuiBox",["root"]),Zd=c.createTheme(),Ye=Sr.createBox({themeId:c.THEME_ID,defaultTheme:Zd,defaultClassName:Qd.root,generateClassName:c.ClassNameGenerator.generate}),is=Sr.createStack({createStyledComponent:c.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:e=>c.useDefaultProps({props:e,name:"MuiStack"})}),Ri=c.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function Xd(e){return c.generateUtilityClass("MuiListItemIcon",e)}const Ai=c.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),Jd=e=>{const{alignItems:n,classes:r}=e,s={root:["root",n==="flex-start"&&"alignItemsFlexStart"]};return c.composeClasses(s,Xd,r)},eh=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}}]}))),lo=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiListItemIcon"}),{className:i,...l}=s,a=we.useContext(c.ListContext),d={...s,alignItems:a.alignItems},u=Jd(d);return t.jsx(eh,{className:c.clsx(u.root,i),ownerState:d,ref:r,...l})});function th(e){return c.generateUtilityClass("MuiListItemText",e)}const Fn=c.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),nh=e=>{const{classes:n,inset:r,primary:s,secondary:i,dense:l}=e,a={root:["root",r&&"inset",l&&"dense",s&&i&&"multiline"],primary:["primary"],secondary:["secondary"]};return c.composeClasses(a,th,n)},rh=c.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${Fn.primary}`]:n.primary},{[`& .${Fn.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(& .${Fn.primary})`]:{display:"block"},[`.${c.typographyClasses.root}:where(& .${Fn.secondary})`]:{display:"block"},variants:[{props:({ownerState:e})=>e.primary&&e.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:e})=>e.inset,style:{paddingLeft:56}}]}),co=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiListItemText"}),{children:i,className:l,disableTypography:a=!1,inset:d=!1,primary:u,primaryTypographyProps:h,secondary:g,secondaryTypographyProps:b,slots:x={},slotProps:v={},...C}=s,{dense:k}=we.useContext(c.ListContext);let S=u??i,T=g;const M={...s,disableTypography:a,inset:d,primary:!!S,secondary:!!T,dense:k},O=nh(M),I={slots:x,slotProps:{primary:h,secondary:b,...v}},[R,_]=c.useSlot("root",{className:c.clsx(O.root,l),elementType:rh,externalForwardedProps:{...I,...C},ownerState:M,ref:r}),[$,B]=c.useSlot("primary",{className:O.primary,elementType:c.Typography,externalForwardedProps:I,ownerState:M}),[F,N]=c.useSlot("secondary",{className:O.secondary,elementType:c.Typography,externalForwardedProps:I,ownerState:M});return S!=null&&S.type!==c.Typography&&!a&&(S=t.jsx($,{variant:k?"body2":"body1",component:B?.variant?void 0:"span",...B,children:S})),T!=null&&T.type!==c.Typography&&!a&&(T=t.jsx(F,{variant:"body2",color:"textSecondary",...N,children:T})),t.jsxs(R,{..._,children:[S,T]})});function sh(e){return c.generateUtilityClass("MuiMenuItem",e)}const er=c.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),oh=(e,n)=>{const{ownerState:r}=e;return[n.root,r.dense&&n.dense,r.divider&&n.divider,!r.disableGutters&&n.gutters]},ih=e=>{const{disabled:n,dense:r,divider:s,disableGutters:i,selected:l,classes:a}=e,d={root:["root",r&&"dense",n&&"disabled",!i&&"gutters",s&&"divider",l&&"selected"]},u=c.composeClasses(d,sh,a);return{...a,...u}},ah=c.styled(c.ButtonBase,{shouldForwardProp:e=>c.rootShouldForwardProp(e)||e==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:oh})(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},[`& + .${Ri.root}`]:{marginTop:e.spacing(1),marginBottom:e.spacing(1)},[`& + .${Ri.inset}`]:{marginLeft:52},[`& .${Fn.root}`]:{marginTop:0,marginBottom:0},[`& .${Fn.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"}}}]}))),tt=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiMenuItem"}),{autoFocus:i=!1,component:l="li",dense:a=!1,divider:d=!1,disableGutters:u=!1,focusVisibleClassName:h,role:g="menuitem",tabIndex:b,className:x,...v}=s,C=we.useContext(c.ListContext),k=we.useMemo(()=>({dense:a||C.dense||!1,disableGutters:u}),[C.dense,a,u]),S=we.useRef(null);c.useEnhancedEffect(()=>{i&&S.current&&S.current.focus()},[i]);const T={...s,dense:k.dense,divider:d,disableGutters:u},M=ih(s),O=c.useForkRef(S,r);let I;return s.disabled||(I=b!==void 0?b:-1),t.jsx(c.ListContext.Provider,{value:k,children:t.jsx(ah,{ref:O,role:g,tabIndex:I,component:l,focusVisibleClassName:c.clsx(M.focusVisible,h),className:c.clsx(M.root,x),...v,ownerState:T,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"},lh={bigquery:{dbmeta:"boolean"},sqlserver:{port:"integer",encrypt:"boolean",trustServerCertificate:"boolean"}},ch={sqlserver:["hostNameInCertificate","instanceName"]};function tl(e,n){const r=lh[e],s=ch[e];if(!r&&!s)return n;const i={...n};for(const l of s??[])i[l]===""&&delete i[l];for(const[l,a]of Object.entries(r??{})){const d=n[l];if(d!==void 0){if(d===""){delete i[l];continue}if(a==="integer"){const u=Number(d);Number.isInteger(u)&&(i[l]=u)}else(d==="true"||d==="false")&&(i[l]=d==="true")}}return i}const nl=Object.values(q.ConnectionTypeEnum).filter(e=>e!==q.ConnectionTypeEnum.Publisher),Ks={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},kr=[{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"}}],Cr=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],uh=[{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 es(e){return e==="postgres"||e==="bigquery"||e==="snowflake"?Gt[e]||[]:e==="s3"?kr:e==="gcs"?Cr:e==="azure"?uh:[]}function dh({onSubmit:e,isSubmitting:n}){const[r,s]=j.useState(!1),[i,l]=j.useState("postgres"),[a,d]=j.useState([]),[u,h]=j.useState("postgres"),[g,b]=j.useState("s3"),[x,v]=j.useState("config"),C=()=>{s(!0)},k=()=>{s(!1),d([]),l("postgres"),h("postgres"),b("s3"),v("config")},S=async I=>{I.preventDefault();const R=new FormData(I.currentTarget),_=R.get("name")?.toString(),$=R.get("type")?.toString(),B=Gt[$];if(!_)throw new Error("Name is required");if(!$)throw new Error("Type is required");let F;if($==="ducklake"){const N={};if(u==="postgres"){const W=Gt.postgres,K={};if(W.forEach(J=>{const X=R.get(`ducklake_pg_${J.name}`)?.toString();X&&(K[J.name]=X)}),Object.keys(K).length===0)throw new Error("DuckLake requires catalog connection");N.postgresConnection=K}const H=R.get("ducklake_bucketUrl")?.toString();if(!H)throw new Error("DuckLake requires a bucket URL");const D={bucketUrl:H};if(g==="s3"){const W={};if(kr.forEach(K=>{const J=R.get(`ducklake_s3_${K.name}`)?.toString();J&&(W[K.name]=J)}),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&&(D.s3Connection=W)}else if(g==="gcs"){const W={};if(Cr.forEach(K=>{const J=R.get(`ducklake_gcs_${K.name}`)?.toString();J&&(W[K.name]=J)}),!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&&(D.gcsConnection=W)}F={name:_,type:$,ducklakeConnection:{catalog:N,storage:D}}}else if($==="duckdb"){if(a.length===0)throw new Error("DuckDB connection must have at least one attached database");const N=a.map((H,D)=>{const W=H.dbType,K=R.get(`attachedDb_${D}_name`)?.toString();if(!K)throw new Error(`Attached database at index ${D} must have a name`);const J={name:K,type:W},X=es(W);if(X&&X.length>0){const G={};if(X.forEach(ie=>{const z=R.get(`attachedDb_${D}_${ie.name}`)?.toString();z&&(G[ie.name]=z)}),W==="s3"){if(G.provider==="credential_chain")delete G.accessKeyId,delete G.secretAccessKey,delete G.sessionToken;else if(delete G.chain,!G.accessKeyId||!G.secretAccessKey)throw new Error(`Attached database "${K}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const Q=Ks[W];Q&&(J[Q]=G)}return J});F={name:_,type:$,duckdbConnection:{attachedDatabases:N}}}else{const N={};if(B.forEach(H=>{const D=R.get(H.name)?.toString();D&&(N[H.name]=D)}),$==="postgres"){if(!!!N.connectionString?.trim()){const D=["host","port","databaseName","userName","password"];for(const W of D)if(!N[W])throw new Error(`${B.find(K=>K.name===W)?.label||W} is required`)}}else if($==="bigquery"){if(!N.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if($==="snowflake"){if(!N.account)throw new Error("Account is required");if(!N.username)throw new Error("Username is required");if(!N.warehouse)throw new Error("Warehouse is required");if(!N.password&&!N.privateKey)throw new Error("Either password or private key is required")}else if($==="trino"){if(!N.server)throw new Error("Server is required");if(!N.user)throw new Error("User is required");if(N.server.trim().startsWith("https://")&&!N.password&&!N.peakaKey)throw new Error("Password is required for HTTPS connections (or use Peaka Key)")}else if($==="mysql"){const H=["host","port","database","user","password"];for(const D of H)if(!N[D])throw new Error(`${B.find(W=>W.name===D)?.label||D} is required`)}else if($==="sqlserver"){const H=["server","database","user","password"];if(!N.instanceName&&!N.port)throw new Error("Port is required unless an instance name is given");for(const D of H)if(!N[D])throw new Error(`${B.find(W=>W.name===D)?.label||D} is required`)}else if($==="motherduck"){if(!N.accessToken)throw new Error("Access Token is required")}else if($==="databricks"){if(!N.host)throw new Error("Host is required");if(!N.path)throw new Error("HTTP Path is required");const H=N.oauthClientId&&N.oauthClientSecret;if(!N.token&&!H)throw new Error("Either Access Token or OAuth Client ID + Secret is required")}F={name:_,type:$,[mr[$]]:tl($,N)}}await e(F),k()},T=()=>{d([...a,{name:"",dbType:"postgres"}])},M=I=>{d(a.filter((R,_)=>_!==I))},O=(I,R)=>{const _=[...a];_[I]={..._[I],dbType:R},d(_)};return t.jsxs(j.Fragment,{children:[t.jsx(c.AddButton,{label:"Connection",onClick:C}),t.jsx(c.AppDialog,{open:r,onClose:k,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:k,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(is,{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:I=>l(I.target.value),children:nl.map(I=>t.jsx(tt,{value:I,children:I},I))}),i==="ducklake"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{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:u,select:!0,onChange:I=>h(I.target.value),children:t.jsx(tt,{value:"postgres",children:"PostgreSQL"})}),u==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(I=>t.jsx(c.TextField,{id:`ducklake_pg_${I.name}`,name:`ducklake_pg_${I.name}`,label:I.label,type:I.type,fullWidth:!0,size:"small"},`pg_${I.name}`))})]}),t.jsxs(Ye,{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:g,select:!0,onChange:I=>b(I.target.value),children:[t.jsx(tt,{value:"s3",children:"S3"}),t.jsx(tt,{value:"gcs",children:"GCS"})]}),t.jsx(c.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:g==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small"}),g==="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"}),kr.filter(I=>I.visibleWhen?x===I.visibleWhen.value:!0).map(I=>t.jsx(c.TextField,{id:`ducklake_s3_${I.name}`,name:`ducklake_s3_${I.name}`,label:I.label,type:I.selectOptions?void 0:I.type,fullWidth:!0,size:"small",required:I.required,select:!!I.selectOptions,defaultValue:I.selectOptions?x:void 0,onChange:I.name==="provider"?R=>v(R.target.value):void 0,placeholder:I.name==="region"?"us-east-1":void 0,children:I.selectOptions?.map(R=>t.jsx(tt,{value:R.value,children:R.label},R.value))},`s3_${I.name}`))]}),g==="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"}),Cr.map(I=>t.jsx(c.TextField,{id:`ducklake_gcs_${I.name}`,name:`ducklake_gcs_${I.name}`,label:I.label,type:I.type,fullWidth:!0,size:"small",required:I.required},`gcs_${I.name}`))]})]})]}):i==="duckdb"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{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((I,R)=>{const _=es(I.dbType);return t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ye,{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:()=>M(R),size:"small",color:"error",children:t.jsx(el,{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:I.name}),t.jsx(c.TextField,{id:`attachedDb_${R}_type`,name:`attachedDb_${R}_type`,label:"Database Type",fullWidth:!0,size:"small",value:I.dbType,select:!0,onChange:$=>O(R,$.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map($=>t.jsx(tt,{value:$,children:$},$))}),_.filter($=>$.visibleWhen?(I[$.visibleWhen.field]||_.find(F=>F.name===$.visibleWhen?.field)?.selectOptions?.[0]?.value)===$.visibleWhen.value:!0).map($=>t.jsx(c.TextField,{id:`attachedDb_${R}_${$.name}`,name:`attachedDb_${R}_${$.name}`,label:$.label,type:$.selectOptions?void 0:$.type,fullWidth:!0,size:"small",required:$.required,select:!!$.selectOptions,defaultValue:$.selectOptions?.[0]?.value,onChange:$.selectOptions?B=>{const F=[...a];F[R]={...F[R],[$.name]:B.target.value},d(F)}:void 0,children:$.selectOptions?.map(B=>t.jsx(tt,{value:B.value,children:B.label},B.value))},$.name))]},R)})]}):Gt[i].map(I=>t.jsx(c.TextField,{id:I.name,name:I.name,label:I.label,type:I.type,fullWidth:!0,size:"small",required:I.required,select:!!I.selectOptions,defaultValue:I.selectOptions?I.selectOptions[0]?.value:void 0,children:I.selectOptions?.map(R=>t.jsx(tt,{value:R.value,children:R.label},R.value))},I.name))]})})})]})}function hh({connection:e,onCloseDialog:n,isMutating:r,onDelete:s}){const[i,l]=j.useState(!1),a=()=>{l(!0)},d=()=>{l(!1),n()};return t.jsxs(j.Fragment,{children:[t.jsxs(tt,{"aria-label":`Delete connection ${e?.name??""}`.trim(),onClick:u=>{u.stopPropagation(),a()},sx:{color:"error.main"},children:[t.jsx(lo,{sx:{color:"inherit"},children:t.jsx(_t.Delete,{fontSize:"small"})}),t.jsx(co,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:i,onClose:d,title:"Delete connection",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:d,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>s(),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 Li=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function Ni(e){const n=e.duckdbConnection?.attachedDatabases;return!n||n.length===0?[]:n.map(r=>({name:r.name||"",dbType:r.type||"postgres"}))}function Pi(e){const n=e.ducklakeConnection;return n&&n.storage?.gcsConnection?"gcs":"s3"}function fh({connection:e,onSubmit:n,isSubmitting:r,onCloseDialog:s}){const[i,l]=j.useState(!1),[a,d]=j.useState(e.type),u=j.useMemo(()=>new Set(e.withheldFields??[]),[e.withheldFields]),[h,g]=j.useState(()=>Ni(e)),[b,x]=j.useState("postgres"),[v,C]=j.useState(()=>Pi(e)),[k,S]=j.useState(()=>e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),T=()=>{g(Ni(e)),d(e.type),S(e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),x("postgres"),C(Pi(e)),l(!0)},M=()=>{l(!1),s?.()},O=async F=>{F.preventDefault();const N=new FormData(F.currentTarget),H=N.get("name")?.toString(),D=N.get("type")?.toString(),W=Gt[D];if(!H)throw new Error("Name is required");if(!D)throw new Error("Type is required");let K;if(D==="ducklake"){const J={};if(b==="postgres"){const Q=Gt.postgres,ie={};if(Q.forEach(z=>{const re=N.get(`ducklake_pg_${z.name}`)?.toString();re&&(ie[z.name]=re)}),Object.keys(ie).length===0)throw new Error("DuckLake requires catalog connection");J.postgresConnection=ie}const X=N.get("ducklake_bucketUrl")?.toString();if(!X)throw new Error("DuckLake requires a bucket URL");const G={bucketUrl:X};if(v==="s3"){const Q={};kr.forEach(z=>{const re=N.get(`ducklake_s3_${z.name}`)?.toString();re&&(Q[z.name]=re)});const ie=e.ducklakeConnection?.storage?.s3Connection;if(ie&&(!Q.provider&&ie.provider&&(Q.provider=ie.provider),!Q.chain&&ie.chain&&(Q.chain=ie.chain),!Q.accessKeyId&&ie.accessKeyId&&(Q.accessKeyId=ie.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&&(G.s3Connection=Q)}else if(v==="gcs"){const Q={};Cr.forEach(z=>{const re=N.get(`ducklake_gcs_${z.name}`)?.toString();re&&(Q[z.name]=re)});const ie=e.ducklakeConnection?.storage?.gcsConnection;if(ie&&!Q.keyId&&ie.keyId&&(Q.keyId=ie.keyId),!Q.keyId)throw new Error("GCS Key ID is required");Object.keys(Q).length>0&&(G.gcsConnection=Q)}K={name:H,type:D,ducklakeConnection:{catalog:J,storage:G}}}else if(D==="duckdb"){if(h.length===0)throw new Error("DuckDB connection must have at least one attached database");const J=h.map((X,G)=>{const Q=X.dbType,ie=N.get(`attachedDb_${G}_name`)?.toString();if(!ie)throw new Error(`Attached database at index ${G} must have a name`);const z={name:ie,type:Q},re=es(Q);if(re&&re.length>0){const se={};if(re.forEach(Me=>{const oe=N.get(`attachedDb_${G}_${Me.name}`)?.toString();oe&&(se[Me.name]=oe)}),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 "${ie}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const ne=Ks[Q];ne&&(z[ne]=se)}return z});K={name:H,type:D,duckdbConnection:{attachedDatabases:J}}}else{const J=e[mr[D]]||{},X={};if(W.forEach(G=>{const Q=N.get(G.name)?.toString(),ie=J[G.name];Q?X[G.name]=Q:Li.has(G.name)||(Q!==void 0?X[G.name]=Q:ie&&(X[G.name]=ie))}),D==="postgres"){const G=["host","port","databaseName","userName"],Q=u.has("postgresConnection.connectionString");if(!(!!X.connectionString?.trim()||Q)){const z=G;for(const re of z)if(!X[re])throw new Error(`${W.find(se=>se.name===re)?.label||re} is required`)}}else if(D==="snowflake"){if(!X.account)throw new Error("Account is required");if(!X.username)throw new Error("Username is required");if(!X.warehouse)throw new Error("Warehouse is required")}else if(D==="trino"){if(!X.server)throw new Error("Server is required");if(!X.user)throw new Error("User is required")}else if(D==="mysql"){const G=["host","port","database","user"];for(const Q of G)if(!X[Q])throw new Error(`${W.find(ie=>ie.name===Q)?.label||Q} is required`)}else if(D==="sqlserver"){const G=["server","database","user"];if(!X.instanceName&&!X.port)throw new Error("Port is required unless an instance name is given");for(const Q of G)if(!X[Q])throw new Error(`${W.find(ie=>ie.name===Q)?.label||Q} is required`)}else if(D==="databricks"){if(!X.host)throw new Error("Host is required");if(!X.path)throw new Error("HTTP Path is required")}K={name:H,type:D,[mr[D]]:tl(D,X)}}await n(K),M()},I=()=>{g([...h,{name:"",dbType:"postgres"}])},R=F=>{g(h.filter((N,H)=>H!==F))},_=(F,N)=>{const H=[...h];H[F]={...H[F],dbType:N},g(H)},$=(F,N)=>{const H=e.duckdbConnection?.attachedDatabases;if(!H||!H[F])return"";const D=H[F],W=Ks[D.type||""];return W&&D[W]?D[W][N]??"":""},B=F=>{const N=e.ducklakeConnection;if(!N)return"";if(F.startsWith("pg_")){const H=F.replace("pg_","");return N.catalog?.postgresConnection?.[H]??""}if(F==="bucketUrl")return N.storage?.bucketUrl??"";if(F.startsWith("s3_")){const H=F.replace("s3_","");return N.storage?.s3Connection?.[H]??""}if(F.startsWith("gcs_")){const H=F.replace("gcs_","");return N.storage?.gcsConnection?.[H]??""}return""};return t.jsxs(j.Fragment,{children:[t.jsxs(tt,{"aria-label":`Edit connection ${e?.name??""}`.trim(),onClick:F=>{F.preventDefault(),F.stopPropagation(),T()},children:[t.jsx(lo,{children:t.jsx(_t.Edit,{fontSize:"small"})}),t.jsx(co,{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(is,{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:F=>d(F.target.value),children:nl.map(F=>t.jsx(tt,{value:F,children:F},F))}),a==="ducklake"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{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:F=>x(F.target.value),children:t.jsx(tt,{value:"postgres",children:"PostgreSQL"})}),b==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(F=>t.jsx(c.TextField,{id:`ducklake_pg_${F.name}`,name:`ducklake_pg_${F.name}`,label:F.label,type:F.type,fullWidth:!0,size:"small",defaultValue:B(`pg_${F.name}`)},`pg_${F.name}`))})]}),t.jsxs(Ye,{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:F=>C(F.target.value),children:[t.jsx(tt,{value:"s3",children:"S3"}),t.jsx(tt,{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"}),kr.filter(F=>F.visibleWhen?k===F.visibleWhen.value:!0).map(F=>t.jsx(c.TextField,{id:`ducklake_s3_${F.name}`,name:`ducklake_s3_${F.name}`,label:F.label,type:F.selectOptions?void 0:F.type,fullWidth:!0,size:"small",required:F.required&&F.name!=="secretAccessKey",select:!!F.selectOptions,defaultValue:F.selectOptions?k:B(`s3_${F.name}`),onChange:F.name==="provider"?N=>S(N.target.value):void 0,placeholder:F.name==="region"?"us-east-1":F.name==="secretAccessKey"&&u.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:F.selectOptions?.map(N=>t.jsx(tt,{value:N.value,children:N.label},N.value))},`s3_${F.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"}),Cr.map(F=>t.jsx(c.TextField,{id:`ducklake_gcs_${F.name}`,name:`ducklake_gcs_${F.name}`,label:F.label,type:F.type,fullWidth:!0,size:"small",required:F.required&&F.name!=="secret",defaultValue:B(`gcs_${F.name}`),placeholder:F.name==="secret"&&u.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${F.name}`))]})]})]}):a==="duckdb"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{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:I,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((F,N)=>{const H=es(F.dbType);return t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ye,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(c.Typography,{variant:"subtitle2",children:["Database ",N+1]}),t.jsx(c.IconButton,{"aria-label":`Remove attached database ${N+1}`,onClick:()=>R(N),size:"small",color:"error",children:t.jsx(el,{fontSize:"small"})})]}),t.jsx(c.TextField,{required:!0,id:`attachedDb_${N}_name`,name:`attachedDb_${N}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:F.name}),t.jsx(c.TextField,{id:`attachedDb_${N}_type`,name:`attachedDb_${N}_type`,label:"Database Type",fullWidth:!0,size:"small",value:F.dbType,select:!0,onChange:D=>_(N,D.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map(D=>t.jsx(tt,{value:D,children:D},D))}),H.filter(D=>D.visibleWhen?(F[D.visibleWhen.field]||$(N,D.visibleWhen.field)||H.find(K=>K.name===D.visibleWhen?.field)?.selectOptions?.[0]?.value)===D.visibleWhen.value:!0).map(D=>t.jsx(c.TextField,{id:`attachedDb_${N}_${D.name}`,name:`attachedDb_${N}_${D.name}`,label:D.label,type:D.selectOptions?void 0:D.type,fullWidth:!0,size:"small",required:D.required,select:!!D.selectOptions,defaultValue:$(N,D.name)||D.selectOptions?.[0]?.value,onChange:D.selectOptions?W=>{const K=[...h];K[N]={...K[N],[D.name]:W.target.value},g(K)}:void 0,children:D.selectOptions?.map(W=>t.jsx(tt,{value:W.value,children:W.label},W.value))},D.name))]},N)})]}):Gt[a].map(F=>{const N=e?.[mr[a]??""]?.[F.name??""]??"",H=F.type==="password"||Li.has(F.name),D=u.has(`${mr[a]??""}.${F.name}`),W=F.selectOptions?N===""||N===void 0?F.selectOptions[0]?.value:String(N):void 0;return t.jsx(c.TextField,{id:F.name,name:F.name,label:F.label,type:F.type,fullWidth:!0,size:"small",required:F.required&&!H&&!N,select:!!F.selectOptions,defaultValue:F.selectOptions?W:N,placeholder:D?"Leave empty to keep existing":void 0,helperText:H?D?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0,children:F.selectOptions?.map(K=>t.jsx(tt,{value:K.value,children:K.label},K.value))},F.name)})]})})})]})}function _i(e,n){return!e||e.type!=="duckdb"?!1:(e.duckdbConnection?.attachedDatabases||[]).some(s=>s.type==="azure"&&s.name===n)}function ph(e){return e.startsWith("gs://")||e.startsWith("s3://")||e.startsWith("https://")||e.startsWith("abfss://")||e.startsWith("az://")}function rl({connectionName:e,resourceUri:n,schema:r,connection:s}){const{apiClients:i}=q.useServer(),{environmentName:l}=c.parseResourceUri(n),[a,d]=j.useState(null),[u,h]=j.useState(r||null),[g,b]=j.useState(!1),{data:x,isError:v,isLoading:C,error:k}=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:g,onChange:T=>b(T.target.checked)}),label:"Hidden Schemas"})]}),t.jsx(m.Divider,{sx:{mt:"2px"}}),t.jsxs(m.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[C&&t.jsx(c.Loading,{text:"Loading schemas..."}),v&&t.jsx(c.ApiErrorDisplay,{error:k,context:`${l} > ${e} > Schemas`}),!C&&!v&&S.length===0&&t.jsx(m.Typography,{variant:"body2",children:"No Schemas"}),!C&&!v&&S.length>0&&t.jsx(m.List,{dense:!0,disablePadding:!0,children:S.map(T=>{const M=T.name;if(T.isHidden&&!g)return null;const I=u===M;return t.jsx(m.ListItemButton,{selected:I,onClick:()=>{h(M),d(null)},children:t.jsx(m.ListItemText,{primary:M})},M)})})]})]})}),t.jsx(m.Grid,{size:{xs:12,md:r?6:4},children:u&&t.jsx(m.Paper,{sx:{p:1,m:0},children:t.jsx(yh,{connectionName:e,schemaName:u,onTableSelect:T=>{d(T)},resourceUri:n,connection:s})})}),t.jsx(m.Grid,{size:{xs:12,md:r?6:4},children:u&&a&&t.jsx(mh,{environmentName:l,connectionName:e,schemaName:u,tableResource:a})})]})}function mh({environmentName:e,connectionName:n,schemaName:r,tableResource:s}){const{apiClients:i}=q.useServer(),{data:l,isLoading:a,isError:d,error:u}=c.useQueryWithApiError({queryKey:["connectionTableDetail",e,n,r,s],queryFn:()=>i.connections.getTable(e,n,r,s),enabled:!!r&&!!s}),h={resource:l?.data?.resource??s,columns:l?.data?.columns??[]};return t.jsxs(m.Paper,{sx:{p:1,m:0},children:[d&&t.jsx(c.ApiErrorDisplay,{error:u,context:`${e} > ${n} > ${r} > ${s}`}),!d&&t.jsx(gh,{table:h,loading:a})]})}function gh({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,s)=>r.name.localeCompare(s.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 yh({connectionName:e,schemaName:n,onTableSelect:r,resourceUri:s,connection:i}){const{environmentName:l}=c.parseResourceUri(s),{apiClients:a}=q.useServer(),[d,u]=j.useState(""),{data:h,isSuccess:g,isError:b,error:x,isLoading:v}=c.useQueryWithApiError({queryKey:["tablesInSchema",l,e,n],queryFn:()=>a.connections.listTables(l,e,n)}),C=_i(i,n),k=T=>C?T:T.split(".").pop()||T,S=g&&h?.data?h.data.filter(T=>k(T.resource).toLowerCase().includes(d.toLowerCase())).sort((T,M)=>k(T.resource).localeCompare(k(M.resource))):[];return t.jsxs(t.Fragment,{children:[t.jsx(m.Typography,{variant:"overline",fontWeight:"bold",children:ph(n)||_i(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:d,onChange:T=>u(T.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}`}),g&&S.length===0&&t.jsx(m.Typography,{variant:"body2",children:"No Tables"}),g&&h?.data&&h.data.length>0&&t.jsx(m.List,{dense:!0,disablePadding:!0,children:S.map(T=>{let M=k(T.resource);return!C&&T.resource.includes("://")&&(M=T.resource.split("/").pop()||T.resource),t.jsx(m.ListItemButton,{onClick:()=>r(T.resource),children:t.jsx(m.ListItemText,{primary:M,secondary:T.columns.length>0?`${T.columns.length} columns`:void 0})},T.resource)})})]})]})}const xh={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 vh(e){return e?xh[e]??e:""}function bh({resourceUri:e}){const{apiClients:n,mutable:r}=q.useServer(),s=yt.useQueryClient(),{environmentName:i}=c.parseResourceUri(e),[l,a]=j.useState(""),[d,u]=j.useState(null),h=c.encodeResourceUri({environmentName:i,connectionName:d}),{data:g,isSuccess:b,isError:x,error:v}=c.useQueryWithApiError({queryKey:["connections",i],queryFn:()=>n.connections.listConnections(i)}),C=c.useMutationWithApiError({mutationFn:Ht("connection","create",O=>n.environments.updateEnvironment(i,{name:i,connections:[...g.data,O]})),onSuccess(){a("Connection added successfully"),s.invalidateQueries({queryKey:["connections",i]})},onError(O){a(O.message)}}),k=c.useMutationWithApiError({mutationFn:Ht("connection","update",O=>n.environments.updateEnvironment(i,{name:i,connections:g.data.map(I=>I.name===O.name?O:I)})),onSuccess(O,I){a(`Connection ${I.name} updated successfully`),s.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,I){a(`Connection ${I.name} deleted successfully`),s.invalidateQueries({queryKey:["connections",i]})},onError(O){a(O.message)}}),T=b?[...g.data].sort((O,I)=>(O.name??"").localeCompare(I.name??"")):[],M=C.isPending||k.isPending||S.isPending;return t.jsxs(Pt,{title:"Connections",...b?{count:T.length}:{},description:"Database connections available to packages in this environment",...r&&b?{action:t.jsx(dh,{onSubmit:O=>C.mutateAsync(O),isSubmitting:C.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&&T.length===0&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),b&&T.length>0&&t.jsx(m.Stack,{children:T.map(O=>t.jsx(wh,{connection:O,mutable:r,isMutating:M,onOpenExplorer:()=>u(O.name??null),onEdit:I=>k.mutateAsync(I),onDelete:I=>S.mutateAsync(I)},O.name))}),t.jsx(m.Snackbar,{open:l!=="",autoHideDuration:6e3,onClose:()=>a(""),message:l}),t.jsx(c.AppDialog,{open:d!==null,onClose:()=>u(null),maxWidth:"lg",title:`Connection explorer: ${d??""}`,showClose:!0,children:d&&t.jsx(rl,{resourceUri:h,connectionName:d,connection:g?.data?.find(O=>O.name===d)})})]})}function wh({connection:e,mutable:n,isMutating:r,onOpenExplorer:s,onEdit:i,onDelete:l}){const[a,d]=j.useState(null),u=!!a,h=b=>{b.stopPropagation(),d(b.currentTarget)},g=()=>d(null);return t.jsx(os,{icon:t.jsx(Kd,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.connection,label:e.name??"",ariaLabel:e.name??"",description:vh(e.type),onClick:s,...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(_t.MoreVert,{fontSize:"small"})}),t.jsxs(m.Menu,{anchorEl:a,open:u,onClose:g,onClick:b=>b.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[t.jsx(fh,{connection:e,onSubmit:i,isSubmitting:r,onCloseDialog:g}),t.jsx(hh,{connection:e,onCloseDialog:g,isMutating:r,onDelete:()=>l(e)})]})]})}:{}})}const Sh=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 kh({resourceUri:e,onCloseDialog:n}){const[r,s]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{s(!0)},a=()=>{s(!1),n()},{environmentName:d,packageName:u}=c.parseResourceUri(e),h=Pn({mutationFn:()=>i.packages.deletePackage(d,u),success:"Package deleted",invalidates:[["packages",d]],closeDialog:a,resource:"package",action:"delete"});return t.jsxs(j.Fragment,{children:[t.jsxs(m.MenuItem,{onClick:l,children:[t.jsx(m.ListItemIcon,{children:t.jsx(_t.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:u}),"? The package stops being served and this cannot be undone."]})}),h.notice]})}function Ch({package:e,resourceUri:n,onCloseDialog:r}){const[s,i]=j.useState(!1),{apiClients:l}=q.useServer(),a=()=>{i(!0)},d=()=>{i(!1),r()},{packageName:u,environmentName:h}=c.parseResourceUri(n),g=Pn({mutationFn(x){return l.packages.updatePackage(h,u,{name:u,description:x.description})},success:"Package updated",invalidates:[["packages",h]],closeDialog:d,resource:"package",action:"update"}),b=x=>{x.preventDefault();const C=new FormData(x.currentTarget).get("description")?.toString();g.mutate({description:C})};return t.jsxs(j.Fragment,{children:[t.jsxs(m.MenuItem,{onClick:a,children:[t.jsx(m.ListItemIcon,{children:t.jsx(_t.Edit,{fontSize:"small"})}),t.jsx(m.ListItemText,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:s,onClose:d,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:g.isPending,onClick:d,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"package-form",variant:"contained",loading:g.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}})]})})}),g.notice]})}function sl({onSelectPackage:e,resourceUri:n}){const{apiClients:r}=q.useServer(),{environmentName:s}=c.parseResourceUri(n),{data:i,isSuccess:l,isError:a,error:d}=c.useQueryWithApiError({queryKey:["packages",s],queryFn:()=>r.packages.listPackages(s)});if(a)return t.jsx(c.ApiErrorDisplay,{error:d,context:`${s} > Packages`});if(!l)return t.jsx(c.Loading,{text:"Fetching Packages..."});const u=[...i.data].sort((h,g)=>h.name.localeCompare(g.name));return t.jsx(m.Stack,{children:u.map(h=>{const g=c.encodeResourceUri({environmentName:s,packageName:h.name});return t.jsx(jh,{pkg:h,packageResourceUri:g,onSelectPackage:e},h.name)})})}function jh({pkg:e,packageResourceUri:n,onSelectPackage:r}){const{mutable:s}=q.useServer(),i=e.versionId!==void 0||e.latestVersion!==void 0,[l,a]=j.useState(null),d=!!l,u=g=>{g.stopPropagation(),a(g.currentTarget)},h=()=>a(null);return t.jsx(os,{icon:t.jsx(Sh,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.package,label:e.name,ariaLabel:e.name,...e.description?{description:e.description}:{},onClick:g=>r(e.name,g),...s?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(m.IconButton,{size:"small",onClick:u,"aria-label":`Package actions for ${e.name}`,children:t.jsx(_t.MoreVert,{fontSize:"small"})}),t.jsxs(m.Menu,{anchorEl:l,open:d,onClose:h,onClick:g=>g.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[!i&&t.jsx(Ch,{package:e,resourceUri:n,onCloseDialog:h}),t.jsx(kh,{resourceUri:n,onCloseDialog:h})]})]})}:{}})}function Th({onSelectPackage:e,resourceUri:n}){const{apiClients:r,mutable:s}=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(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(Pt,{title:"Packages",...l.isSuccess?{count:l.data.data.length}:{},description:"Published packages available for use in this environment",...s?{action:t.jsx(Yd,{resourceUri:n})}:{},children:t.jsx(sl,{onSelectPackage:e,resourceUri:n})}),t.jsx(bh,{resourceUri:n}),t.jsx($d,{resourceUri:n})]})}function zi({array1:e,array2:n,parser:r=s=>s}){return e&&n&&e.length===n.length&&e.every((s,i)=>r(s)===r(n[i]))}function Wi(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}function Mh(e={}){const{ignoreAccents:n=!0,ignoreCase:r=!0,limit:s,matchFrom:i="any",stringify:l,trim:a=!1}=e;return(d,{inputValue:u,getOptionLabel:h})=>{let g=a?u.trim():u;r&&(g=g.toLowerCase()),n&&(g=Wi(g));const b=g?d.filter(x=>{let v=(l||h)(x);return r&&(v=v.toLowerCase()),n&&(v=Wi(v)),i==="start"?v.startsWith(g):v.includes(g)}):d;return typeof s=="number"?b.slice(0,s):b}}const Oh=Mh(),qi=5,Ih=e=>e.current!==null&&e.current.parentElement?.contains(document.activeElement),Eh=[];function Bi(e,n,r,s){if(n||e==null||s)return"";const i=r(e);return typeof i=="string"?i:""}function Dh(e){const{unstable_isActiveElementInListbox:n=Ih,unstable_classNamePrefix:r="Mui",autoComplete:s=!1,autoHighlight:i=!1,autoSelect:l=!1,blurOnSelect:a=!1,clearOnBlur:d=!e.freeSolo,clearOnEscape:u=!1,componentName:h="useAutocomplete",defaultValue:g=e.multiple?Eh:null,disableClearable:b=!1,disableCloseOnSelect:x=!1,disabled:v,disabledItemsFocusable:C=!1,disableListWrap:k=!1,filterOptions:S=Oh,filterSelectedOptions:T=!1,freeSolo:M=!1,getOptionDisabled:O,getOptionKey:I,getOptionLabel:R=U=>U.label??U,groupBy:_,handleHomeEndKeys:$=!e.freeSolo,id:B,includeInputInList:F=!1,inputValue:N,isOptionEqualToValue:H=(U,V)=>U===V,multiple:D=!1,onChange:W,onClose:K,onHighlightChange:J,onInputChange:X,onOpen:G,open:Q,openOnFocus:ie=!1,options:z,readOnly:re=!1,renderValue:se,selectOnFocus:ne=!e.freeSolo,value:Me}=e,oe=c.useId(B);let ue=R;ue=U=>{const V=R(U);return typeof V!="string"?String(V):V};const De=we.useRef(!1),Ne=we.useRef(!0),ae=we.useRef(null),Z=we.useRef(null),[ce,be]=we.useState(null),[ge,he]=we.useState(-1),ye=i?0:-1,Fe=we.useRef(ye),ze=we.useRef(Bi(g??Me,D,ue)).current,[me,Y]=c.useControlled({controlled:Me,default:g,name:h}),[le,Oe]=c.useControlled({controlled:N,default:ze,name:h,state:"inputValue"}),[Re,at]=we.useState(!1),Ie=we.useCallback((U,V,de)=>{if(!(D?me.length<V.length:V!==null)&&!d)return;const te=Bi(V,D,ue,se);le!==te&&(Oe(te),X&&X(U,te,de))},[ue,le,D,X,Oe,d,me,se]),[lt,xt]=c.useControlled({controlled:Q,default:!1,name:h,state:"open"}),[vt,Mt]=we.useState(!0),mt=!D&&me!=null&&le===ue(me),Ke=lt&&!re,fe=Ke?S(z.filter(U=>!(T&&(D?me:[me]).some(V=>V!==null&&H(U,V)))),{inputValue:mt&&vt?"":le,getOptionLabel:ue}):[],Qe=hd({filteredOptions:fe,value:me,inputValue:le});we.useEffect(()=>{const U=me!==Qe.value;Re&&!U||M&&!U||Ie(null,me,"reset")},[me,Ie,Re,Qe.value,M]);const qe=lt&&fe.length>0&&!re,ct=c.useEventCallback(U=>{if(U===-1)ae.current.focus();else{const V=se?"data-item-index":"data-tag-index";ce.querySelector(`[${V}="${U}"]`).focus()}});we.useEffect(()=>{D&&ge>me.length-1&&(he(-1),ct(-1))},[me,D,ge,ct]);function ut(U,V){if(!Z.current||U<0||U>=fe.length)return-1;let de=U;for(;;){const ve=Z.current.querySelector(`[data-option-index="${de}"]`),te=C?!1:!ve||ve.disabled||ve.getAttribute("aria-disabled")==="true";if(ve&&ve.hasAttribute("tabindex")&&!te)return de;if(V==="next"?de=(de+1)%fe.length:de=(de-1+fe.length)%fe.length,de===U)return-1}}const Ze=c.useEventCallback(({event:U,index:V,reason:de})=>{if(Fe.current=V,V===-1?ae.current.removeAttribute("aria-activedescendant"):ae.current.setAttribute("aria-activedescendant",`${oe}-option-${V}`),J&&["mouse","keyboard","touch"].includes(de)&&J(U,V===-1?null:fe[V],de),!Z.current)return;const ve=Z.current.querySelector(`[role="option"].${r}-focused`);ve&&(ve.classList.remove(`${r}-focused`),ve.classList.remove(`${r}-focusVisible`));let te=Z.current;if(Z.current.getAttribute("role")!=="listbox"&&(te=Z.current.parentElement.querySelector('[role="listbox"]')),!te)return;if(V===-1){te.scrollTop=0;return}const Ve=Z.current.querySelector(`[data-option-index="${V}"]`);if(Ve&&(Ve.classList.add(`${r}-focused`),de==="keyboard"&&Ve.classList.add(`${r}-focusVisible`),te.scrollHeight>te.clientHeight&&de!=="mouse"&&de!=="touch")){const Ge=Ve,Ct=te.clientHeight+te.scrollTop,vn=Ge.offsetTop+Ge.offsetHeight;vn>Ct?te.scrollTop=vn-te.clientHeight:Ge.offsetTop-Ge.offsetHeight*(_?1.3:0)<te.scrollTop&&(te.scrollTop=Ge.offsetTop-Ge.offsetHeight*(_?1.3:0))}}),pe=c.useEventCallback(({event:U,diff:V,direction:de="next",reason:ve})=>{if(!Ke)return;const Ve=ut((()=>{const Ge=fe.length-1;if(V==="reset")return ye;if(V==="start")return 0;if(V==="end")return Ge;const Ct=Fe.current+V;return Ct<0?Ct===-1&&F?-1:k&&Fe.current!==-1||Math.abs(V)>1?0:Ge:Ct>Ge?Ct===Ge+1&&F?-1:k||Math.abs(V)>1?Ge:0:Ct})(),de);if(Ze({index:Ve,reason:ve,event:U}),s&&V!=="reset")if(Ve===-1)ae.current.value=le;else{const Ge=ue(fe[Ve]);ae.current.value=Ge,Ge.toLowerCase().indexOf(le.toLowerCase())===0&&le.length>0&&ae.current.setSelectionRange(le.length,Ge.length)}}),Ue=!zi({array1:Qe.filteredOptions,array2:fe,parser:ue}),bt=()=>{const U=(V,de)=>{const ve=V?ue(V):"",te=de?ue(de):"";return ve===te};if(Fe.current!==-1&&!zi({array1:Qe.filteredOptions,array2:fe,parser:ue})&&Qe.inputValue===le&&(D?me.length===Qe.value.length&&Qe.value.every((V,de)=>ue(me[de])===ue(V)):U(Qe.value,me))){const V=Qe.filteredOptions[Fe.current];if(V)return fe.findIndex(de=>ue(de)===ue(V))}return-1},Ce=we.useCallback(()=>{if(!Ke)return;const U=bt();if(U!==-1){Fe.current=U;return}const V=D?me[0]:me;if(fe.length===0||V==null){pe({diff:"reset"});return}if(Z.current){if(V!=null){const de=fe[Fe.current];if(D&&de&&me.findIndex(te=>H(de,te))!==-1)return;const ve=fe.findIndex(te=>H(te,V));ve===-1?pe({diff:"reset"}):Ze({index:ve});return}if(Fe.current>=fe.length-1){Ze({index:fe.length-1});return}Ze({index:Fe.current})}},[fe.length,D?!1:me,T,pe,Ze,Ke,le,D]),Le=c.useEventCallback(U=>{c.setRef(Z,U),U&&Ce()});we.useEffect(()=>{Ue&&Ce()},[Ce,Ue]);const Ee=U=>{lt||(xt(!0),Mt(!0),G&&G(U))},Be=(U,V)=>{lt&&(xt(!1),K&&K(U,V))},ht=(U,V,de,ve)=>{if(D){if(me.length===V.length&&me.every((te,Ve)=>te===V[Ve]))return}else if(me===V)return;W&&W(U,V,de,ve),Y(V)},We=we.useRef(!1),nt=(U,V,de="selectOption",ve="options")=>{let te=de,Ve=V;if(D){Ve=Array.isArray(me)?me.slice():[];const Ge=Ve.findIndex(Ct=>H(V,Ct));Ge===-1?Ve.push(V):ve!=="freeSolo"&&(Ve.splice(Ge,1),te="removeOption")}Ie(U,Ve,te),ht(U,Ve,te,{option:V}),!x&&(!U||!U.ctrlKey&&!U.metaKey)&&Be(U,te),(a===!0||a==="touch"&&We.current||a==="mouse"&&!We.current)&&ae.current.blur()};function Ot(U,V){if(U===-1)return-1;let de=U;for(;;){if(V==="next"&&de===me.length||V==="previous"&&de===-1)return-1;const ve=se?"data-item-index":"data-tag-index",te=ce.querySelector(`[${ve}="${de}"]`);if(!te||!te.hasAttribute("tabindex")||te.disabled||te.getAttribute("aria-disabled")==="true")de+=V==="next"?1:-1;else return de}}const kt=(U,V)=>{if(!D)return;le===""&&Be(U,"toggleInput");let de=ge;ge===-1?le===""&&V==="previous"&&(de=me.length-1):(de+=V==="next"?1:-1,de<0&&(de=0),de===me.length&&(de=-1)),de=Ot(de,V),he(de),ct(de)},$t=U=>{De.current=!0,Oe(""),X&&X(U,"","clear"),ht(U,D?[]:null,"clear")},gn=U=>V=>{if(U.onKeyDown&&U.onKeyDown(V),!V.defaultMuiPrevented&&(ge!==-1&&!["ArrowLeft","ArrowRight"].includes(V.key)&&(he(-1),ct(-1)),V.which!==229))switch(V.key){case"Home":Ke&&$&&(V.preventDefault(),pe({diff:"start",direction:"next",reason:"keyboard",event:V}));break;case"End":Ke&&$&&(V.preventDefault(),pe({diff:"end",direction:"previous",reason:"keyboard",event:V}));break;case"PageUp":V.preventDefault(),pe({diff:-qi,direction:"previous",reason:"keyboard",event:V}),Ee(V);break;case"PageDown":V.preventDefault(),pe({diff:qi,direction:"next",reason:"keyboard",event:V}),Ee(V);break;case"ArrowDown":V.preventDefault(),pe({diff:1,direction:"next",reason:"keyboard",event:V}),Ee(V);break;case"ArrowUp":V.preventDefault(),pe({diff:-1,direction:"previous",reason:"keyboard",event:V}),Ee(V);break;case"ArrowLeft":!D&&se?ct(0):kt(V,"previous");break;case"ArrowRight":!D&&se?ct(-1):kt(V,"next");break;case"Enter":if(Fe.current!==-1&&Ke){const de=fe[Fe.current],ve=O?O(de):!1;if(V.preventDefault(),ve)return;nt(V,de,"selectOption"),s&&ae.current.setSelectionRange(ae.current.value.length,ae.current.value.length)}else M&&le!==""&&mt===!1&&(D&&V.preventDefault(),nt(V,le,"createOption","freeSolo"));break;case"Escape":Ke?(V.preventDefault(),V.stopPropagation(),Be(V,"escape")):u&&(le!==""||D&&me.length>0||se)&&(V.preventDefault(),V.stopPropagation(),$t(V));break;case"Backspace":if(D&&!re&&le===""&&me.length>0){const de=ge===-1?me.length-1:ge,ve=me.slice();ve.splice(de,1),ht(V,ve,"removeOption",{option:me[de]})}!D&&se&&!re&&(Y(null),ct(-1));break;case"Delete":if(D&&!re&&le===""&&me.length>0&&ge!==-1){const de=ge,ve=me.slice();ve.splice(de,1),ht(V,ve,"removeOption",{option:me[de]})}!D&&se&&!re&&(Y(null),ct(-1));break}},_e=U=>{at(!0),ie&&!De.current&&Ee(U)},dt=U=>{if(n(Z)){ae.current.focus();return}at(!1),Ne.current=!0,De.current=!1,l&&Fe.current!==-1&&Ke?nt(U,fe[Fe.current],"blur"):l&&M&&le!==""?nt(U,le,"blur","freeSolo"):d&&Ie(U,me,"blur"),Be(U,"blur")},Kt=U=>{const V=U.target.value;le!==V&&(Oe(V),Mt(!1),X&&X(U,V,"input")),V===""?!b&&!D&&ht(U,null,"clear"):Ee(U)},yn=U=>{const V=Number(U.currentTarget.getAttribute("data-option-index"));Fe.current!==V&&Ze({event:U,index:V,reason:"mouse"})},ft=U=>{Ze({event:U,index:Number(U.currentTarget.getAttribute("data-option-index")),reason:"touch"}),We.current=!0},en=U=>{const V=Number(U.currentTarget.getAttribute("data-option-index"));nt(U,fe[V],"selectOption"),We.current=!1},xn=U=>V=>{const de=me.slice();de.splice(U,1),ht(V,de,"removeOption",{option:me[U]})},Qt=U=>{ht(U,null,"removeOption",{option:me})},Xe=U=>{lt?Be(U,"toggleInput"):Ee(U)},Je=U=>{U.currentTarget.contains(U.target)&&U.target.getAttribute("id")!==oe&&U.preventDefault()},Rt=U=>{U.currentTarget.contains(U.target)&&(ae.current.focus(),ne&&Ne.current&&ae.current.selectionEnd-ae.current.selectionStart===0&&ae.current.select(),Ne.current=!1)},tn=U=>{!v&&(le===""||!lt)&&Xe(U)};let Zt=M&&le.length>0;Zt=Zt||(D?me.length>0:me!==null);let nn=fe;return _&&(nn=fe.reduce((U,V,de)=>{const ve=_(V);return U.length>0&&U[U.length-1].group===ve?U[U.length-1].options.push(V):U.push({key:de,index:de,group:ve,options:[V]}),U},[])),v&&Re&&dt(),{getRootProps:(U={})=>({...U,onKeyDown:gn(U),onMouseDown:Je,onClick:Rt}),getInputLabelProps:()=>({id:`${oe}-label`,htmlFor:oe}),getInputProps:()=>({id:oe,value:le,onBlur:dt,onFocus:_e,onChange:Kt,onMouseDown:tn,"aria-activedescendant":Ke?"":null,"aria-autocomplete":s?"both":"list","aria-controls":qe?`${oe}-listbox`:void 0,"aria-expanded":qe,autoComplete:"off",ref:ae,autoCapitalize:"none",spellCheck:"false",role:"combobox",disabled:v}),getClearProps:()=>({tabIndex:-1,type:"button",onClick:$t}),getItemProps:({index:U=0}={})=>({...D&&{key:U},...se?{"data-item-index":U}:{"data-tag-index":U},tabIndex:-1,...!re&&{onDelete:D?xn(U):Qt}}),getPopupIndicatorProps:()=>({tabIndex:-1,type:"button",onClick:Xe}),getTagProps:({index:U})=>({key:U,"data-tag-index":U,tabIndex:-1,...!re&&{onDelete:xn(U)}}),getListboxProps:()=>({role:"listbox",id:`${oe}-listbox`,"aria-labelledby":`${oe}-label`,ref:Le,onMouseDown:U=>{U.preventDefault()}}),getOptionProps:({index:U,option:V})=>{const de=(D?me:[me]).some(te=>te!=null&&H(V,te)),ve=O?O(V):!1;return{key:I?.(V)??ue(V),tabIndex:-1,role:"option",id:`${oe}-option-${U}`,onMouseMove:yn,onClick:en,onTouchStart:ft,"data-option-index":U,"aria-disabled":ve,"aria-selected":de}},id:oe,inputValue:le,value:me,dirty:Zt,expanded:Ke&&ce,popupOpen:Ke,focused:Re||ge!==-1,anchorEl:ce,setAnchorEl:be,focusedItem:ge,focusedTag:ge,groupedOptions:nn}}function Fh(e){return c.generateUtilityClass("MuiListSubheader",e)}c.generateUtilityClasses("MuiListSubheader",["root","colorPrimary","colorInherit","gutters","inset","sticky"]);const $h=e=>{const{classes:n,color:r,disableGutters:s,inset:i,disableSticky:l}=e,a={root:["root",r!=="default"&&`color${c.capitalize(r)}`,!s&&"gutters",i&&"inset",!l&&"sticky"]};return c.composeClasses(a,Fh,n)},Rh=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}}]}))),Qs=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiListSubheader"}),{className:i,color:l="default",component:a="li",disableGutters:d=!1,disableSticky:u=!1,inset:h=!1,...g}=s,b={...s,color:l,component:a,disableGutters:d,disableSticky:u,inset:h},x=$h(b);return t.jsx(Rh,{as:a,className:c.clsx(x.root,i),ref:r,ownerState:b,...g})});Qs&&(Qs.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 Lh(e){return c.generateUtilityClass("MuiAutocomplete",e)}const Te=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 Vi,Hi;const Nh=e=>{const{classes:n,disablePortal:r,expanded:s,focused:i,fullWidth:l,hasClearIcon:a,hasPopupIcon:d,inputFocused:u,popupOpen:h,size:g}=e,b={root:["root",s&&"expanded",i&&"focused",l&&"fullWidth",a&&"hasClearIcon",d&&"hasPopupIcon"],inputRoot:["inputRoot"],input:["input",u&&"inputFocused"],tag:["tag",`tagSize${c.capitalize(g)}`],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,Lh,n)},Ph=c.styled("div",{name:"MuiAutocomplete",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e,{fullWidth:s,hasClearIcon:i,hasPopupIcon:l,inputFocused:a,size:d}=r;return[{[`& .${Te.tag}`]:n.tag},{[`& .${Te.tag}`]:n[`tagSize${c.capitalize(d)}`]},{[`& .${Te.inputRoot}`]:n.inputRoot},{[`& .${Te.input}`]:n.input},{[`& .${Te.input}`]:a&&n.inputFocused},n.root,s&&n.fullWidth,l&&n.hasPopupIcon,i&&n.hasClearIcon]}})({[`&.${Te.focused} .${Te.clearIndicator}`]:{visibility:"visible"},"@media (pointer: fine)":{[`&:hover .${Te.clearIndicator}`]:{visibility:"visible"}},[`& .${Te.tag}`]:{margin:3,maxWidth:"calc(100% - 6px)"},[`& .${Te.inputRoot}`]:{[`.${Te.hasPopupIcon}&, .${Te.hasClearIcon}&`]:{paddingRight:30},[`.${Te.hasPopupIcon}.${Te.hasClearIcon}&`]:{paddingRight:56},[`& .${Te.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,[`.${Te.hasPopupIcon}&, .${Te.hasClearIcon}&`]:{paddingRight:39},[`.${Te.hasPopupIcon}.${Te.hasClearIcon}&`]:{paddingRight:65},[`& .${Te.input}`]:{padding:"7.5px 4px 7.5px 5px"},[`& .${Te.endAdornment}`]:{right:9}},[`& .${c.outlinedInputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{paddingTop:6,paddingBottom:6,paddingLeft:6,[`& .${Te.input}`]:{padding:"2.5px 4px 2.5px 8px"}},[`& .${c.filledInputClasses.root}`]:{paddingTop:19,paddingLeft:8,[`.${Te.hasPopupIcon}&, .${Te.hasClearIcon}&`]:{paddingRight:39},[`.${Te.hasPopupIcon}.${Te.hasClearIcon}&`]:{paddingRight:65},[`& .${c.filledInputClasses.input}`]:{padding:"7px 4px"},[`& .${Te.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,[`& .${Te.input}`]:{paddingTop:16,paddingBottom:17}},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.hiddenLabel}.${c.inputBaseClasses.sizeSmall}`]:{[`& .${Te.input}`]:{paddingTop:8,paddingBottom:9}},[`& .${Te.input}`]:{flexGrow:1,textOverflow:"ellipsis",opacity:0},variants:[{props:{fullWidth:!0},style:{width:"100%"}},{props:{size:"small"},style:{[`& .${Te.tag}`]:{margin:2,maxWidth:"calc(100% - 4px)"}}},{props:{inputFocused:!0},style:{[`& .${Te.input}`]:{opacity:1}}},{props:{multiple:!0},style:{[`& .${Te.inputRoot}`]:{flexWrap:"wrap"}}}]}),_h=c.styled("div",{name:"MuiAutocomplete",slot:"EndAdornment"})({position:"absolute",right:0,top:"50%",transform:"translate(0, -50%)"}),zh=c.styled(c.IconButton,{name:"MuiAutocomplete",slot:"ClearIndicator"})({marginRight:-2,padding:4,visibility:"hidden"}),Wh=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)"}}]}),qh=c.styled(c.Popper,{name:"MuiAutocomplete",slot:"Popper",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${Te.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"}}]}))),Bh=c.styled(c.Paper,{name:"MuiAutocomplete",slot:"Paper"})(c.memoTheme(({theme:e})=>({...e.typography.body1,overflow:"auto"}))),Vh=c.styled("div",{name:"MuiAutocomplete",slot:"Loading"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Hh=c.styled("div",{name:"MuiAutocomplete",slot:"NoOptions"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Uh=c.styled("ul",{name:"MuiAutocomplete",slot:"Listbox"})(c.memoTheme(({theme:e})=>({listStyle:"none",margin:0,padding:"8px 0",maxHeight:"40vh",overflow:"auto",position:"relative",[`& .${Te.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"},[`&.${Te.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"},[`&.${Te.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),[`&.${Te.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}},[`&.${Te.focusVisible}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.focusOpacity}`)}}}}))),Gh=c.styled(Qs,{name:"MuiAutocomplete",slot:"GroupLabel"})(c.memoTheme(({theme:e})=>({backgroundColor:(e.vars||e).palette.background.paper,top:-8}))),Yh=c.styled("ul",{name:"MuiAutocomplete",slot:"GroupUl"})({padding:0,[`& .${Te.option}`]:{paddingLeft:24}}),Zs=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiAutocomplete"}),{autoComplete:i=!1,autoHighlight:l=!1,autoSelect:a=!1,blurOnSelect:d=!1,ChipProps:u,className:h,clearIcon:g=Vi||(Vi=t.jsx(Ah,{fontSize:"small"})),clearOnBlur:b=!s.freeSolo,clearOnEscape:x=!1,clearText:v="Clear",closeText:C="Close",componentsProps:k,defaultValue:S=s.multiple?[]:null,disableClearable:T=!1,disableCloseOnSelect:M=!1,disabled:O=!1,disabledItemsFocusable:I=!1,disableListWrap:R=!1,disablePortal:_=!1,filterOptions:$,filterSelectedOptions:B=!1,forcePopupIcon:F="auto",freeSolo:N=!1,fullWidth:H=!1,getLimitTagsText:D=$e=>`+${$e}`,getOptionDisabled:W,getOptionKey:K,getOptionLabel:J,isOptionEqualToValue:X,groupBy:G,handleHomeEndKeys:Q=!s.freeSolo,id:ie,includeInputInList:z=!1,inputValue:re,limitTags:se=-1,ListboxComponent:ne,ListboxProps:Me,loading:oe=!1,loadingText:ue="Loading…",multiple:De=!1,noOptionsText:Ne="No options",onChange:ae,onClose:Z,onHighlightChange:ce,onInputChange:be,onOpen:ge,open:he,openOnFocus:ye=!1,openText:Fe="Open",options:ze,PaperComponent:me,PopperComponent:Y,popupIcon:le=Hi||(Hi=t.jsx(c.ArrowDropDownIcon,{})),readOnly:Oe=!1,renderGroup:Re,renderInput:at,renderOption:Ie,renderTags:lt,renderValue:xt,selectOnFocus:vt=!s.freeSolo,size:Mt="medium",slots:mt={},slotProps:Ke={},value:fe,...Qe}=s,{getRootProps:qe,getInputProps:ct,getInputLabelProps:ut,getPopupIndicatorProps:Ze,getClearProps:pe,getItemProps:Ue,getListboxProps:bt,getOptionProps:Ce,value:Le,dirty:Ee,expanded:Be,id:ht,popupOpen:We,focused:nt,focusedItem:Ot,anchorEl:kt,setAnchorEl:$t,inputValue:gn,groupedOptions:_e}=Dh({...s,componentName:"Autocomplete"}),dt=!T&&!O&&Ee&&!Oe,Kt=(!N||F===!0)&&F!==!1,{onMouseDown:yn}=ct(),{ref:ft,...en}=bt(),Qt=J||($e=>$e.label??$e),Xe={...s,disablePortal:_,expanded:Be,focused:nt,fullWidth:H,getOptionLabel:Qt,hasClearIcon:dt,hasPopupIcon:Kt,inputFocused:Ot===-1,popupOpen:We,size:Mt},Je=Nh(Xe),Rt={slots:{paper:me,popper:Y,...mt},slotProps:{chip:u,listbox:Me,...k,...Ke}},[tn,Zt]=c.useSlot("listbox",{elementType:Uh,externalForwardedProps:Rt,ownerState:Xe,className:Je.listbox,additionalProps:en,ref:ft}),[nn,U]=c.useSlot("paper",{elementType:c.Paper,externalForwardedProps:Rt,ownerState:Xe,className:Je.paper}),[V,de]=c.useSlot("popper",{elementType:c.Popper,externalForwardedProps:Rt,ownerState:Xe,className:Je.popper,additionalProps:{disablePortal:_,style:{width:kt?kt.clientWidth:null},role:"presentation",anchorEl:kt,open:We}});let ve;const te=$e=>({className:Je.tag,disabled:O,...Ue($e)});if(De?Le.length>0&&(lt?ve=lt(Le,te,Xe):xt?ve=xt(Le,te,Xe):ve=Le.map(($e,zt)=>{const{key:gt,...qt}=te({index:zt});return t.jsx(c.Chip,{label:Qt($e),size:Mt,...qt,...Rt.slotProps.chip},gt)})):xt&&Le!=null&&(ve=xt(Le,te,Xe)),se>-1&&Array.isArray(ve)){const $e=ve.length-se;!nt&&$e>0&&(ve=ve.splice(0,se),ve.push(t.jsx("span",{className:Je.tag,children:D($e)},ve.length)))}const Ge=Re||($e=>t.jsxs("li",{children:[t.jsx(Gh,{className:Je.groupLabel,ownerState:Xe,component:"div",children:$e.group}),t.jsx(Yh,{className:Je.groupUl,ownerState:Xe,children:$e.children})]},$e.key)),vn=Ie||(($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:Je.option},$e,{selected:gt["aria-selected"],index:zt,inputValue:gn},Xe)},Wn=Rt.slotProps.clearIndicator,Fr=Rt.slotProps.popupIndicator;return t.jsxs(we.Fragment,{children:[t.jsx(Ph,{ref:r,className:c.clsx(Je.root,h),ownerState:Xe,...qe(Qe),children:at({id:ht,disabled:O,fullWidth:!0,size:Mt==="small"?"small":void 0,InputLabelProps:ut(),InputProps:{ref:$t,className:Je.inputRoot,startAdornment:ve,onMouseDown:$e=>{$e.target===$e.currentTarget&&yn($e)},...(dt||Kt)&&{endAdornment:t.jsxs(_h,{className:Je.endAdornment,ownerState:Xe,children:[dt?t.jsx(zh,{...pe(),"aria-label":v,title:v,ownerState:Xe,...Wn,className:c.clsx(Je.clearIndicator,Wn?.className),children:g}):null,Kt?t.jsx(Wh,{...Ze(),disabled:O,"aria-label":We?C:Fe,title:We?C:Fe,ownerState:Xe,...Fr,className:c.clsx(Je.popupIndicator,Fr?.className),children:le}):null]})}},inputProps:{className:Je.input,disabled:O,readOnly:Oe,...ct()}})}),kt?t.jsx(qh,{as:V,...de,children:t.jsxs(Bh,{as:nn,...U,children:[oe&&_e.length===0?t.jsx(Vh,{className:Je.loading,ownerState:Xe,children:ue}):null,_e.length===0&&!N&&!oe?t.jsx(Hh,{className:Je.noOptions,ownerState:Xe,role:"presentation",onMouseDown:$e=>{$e.preventDefault()},children:Ne}):null,_e.length>0?t.jsx(tn,{as:ne,...Zt,children:_e.map(($e,zt)=>G?Ge({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 Ms(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 Kh(e){return e==="DateMinMax"}function Os(e){return e==="Between"}function Qh({spec:e,values:n,selection:r,onChange:s,retrievalFn:i}){const l=()=>r?.matchType?r.matchType:e.defaultMatchType?e.defaultMatchType:e.filterType==="DateMinMax"?"Between":Ms(e.filterType)[0]||"Equals",[a,d]=j.useState(l()),[u,h]=j.useState(r?.value??""),[g,b]=j.useState(r?.value2??""),[x,v]=j.useState([]),[C,k]=j.useState(!1),[S,T]=j.useState(""),[M,O]=j.useState(!1),[I,R]=j.useState(!1),_=j.useRef(null),$=j.useRef(0),[B,F]=j.useState(!1);j.useEffect(()=>{if(e.filterType!=="Retrieval"||!i)return;const z=S.trim();if(z.length<=2){v([]),O(!1);return}return _.current&&clearTimeout(_.current),_.current=setTimeout(async()=>{$.current+=1;const re=$.current;k(!0);try{const se=await i(z,e);re===$.current&&v(se)}catch(se){re===$.current&&(console.error("Retrieval failed",se),v([]))}finally{re===$.current&&(k(!1),O(!0))}},500),()=>{_.current&&clearTimeout(_.current)}},[S,e,i]),j.useEffect(()=>{r===null?(h(""),b(""),d(e.defaultMatchType??(e.filterType==="DateMinMax"?"Between":Ms(e.filterType)[0]||"Equals"))):r&&(d(r.matchType),h(r.value??""),b(r.value2??""))},[r,e.filterType,e.defaultMatchType]);const N=Ms(e.filterType),H=Kh(e.filterType),D=Os(a),W=H&&n.length>=2&&n[0].value instanceof Date?c.dayjs.utc(n[0].value):void 0,K=H&&n.length>=2&&n[1].value instanceof Date?c.dayjs.utc(n[1].value):void 0,J=e.filterType==="MinMax"&&n.length>=2&&typeof n[0].value=="number"?n[0].value:void 0,X=e.filterType==="MinMax"&&n.length>=2&&typeof n[1].value=="number"?n[1].value:void 0;if(N.length===0)return null;const G=z=>{const re=z.target.value;d(re),Os(re)||b(""),u&&s({dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:re,value:u,...Os(re)&&g&&{value2:g}})},Q=(z,re)=>{h(z??""),re!==void 0&&b(re??"");const se=Array.isArray(z)&&z.length===0;s(!se&&z!==""&&z!==null&&z!==void 0?{dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:a,value:z,...D&&re&&{value2:re}}:null)},ie=()=>{h(""),b(""),s(null)};return t.jsxs(Ye,{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(Ye,{sx:{fontWeight:600,color:e.required&&!r?"error.main":"text.primary"},children:[e.label??e.dimensionName,e.required&&t.jsx(Ye,{component:"span",sx:{color:r?"text.secondary":"error.main",fontWeight:400,fontSize:"0.7rem",ml:.5},children:"(required)"})]}),e.filterType!=="Boolean"&&!e.defaultMatchType&&N.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:G,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:N.map(z=>t.jsx(tt,{value:z,children:z},z))})]}),e.filterType==="Star"&&a==="Equals"&&t.jsx(Zs,{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(u)?u.map(z=>n.find(re=>re.value===z)||z):u?[n.find(z=>z.value===u)||u]:[],onChange:(z,re)=>{const se=re.map(ne=>typeof ne=="string"?ne:ne&&typeof ne=="object"&&"value"in ne?ne.value:ne);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:u,onChange:z=>h(z.target.value),onBlur:()=>Q(u),onKeyDown:z=>{z.key==="Enter"&&Q(u)},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:u===!0?"true":u===!1?"false":"",label:"Value",onChange:z=>{const re=z.target.value;re==="true"?Q(!0):re==="false"?Q(!1):ie()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[t.jsx(tt,{value:"",children:t.jsx("em",{children:"Blank"})}),t.jsx(tt,{value:"true",children:"True"}),t.jsx(tt,{value:"false",children:"False"})]})]}),e.filterType==="Retrieval"&&a==="Semantic Search"&&t.jsx(Zs,{multiple:!0,size:"small",options:x,loading:C,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(u)?u.map(z=>x.find(se=>se.value===z)||{value:z}):u?[{value:u}]:[],onInputChange:(z,re)=>{T(re)},onChange:(z,re)=>{const se=re.map(ne=>typeof ne=="string"?ne:ne&&typeof ne=="object"&&"value"in ne?ne.value:ne);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:I&&!C&&M&&x.length===0?"No matches found":void 0,InputProps:{...z.InputProps,endAdornment:t.jsxs(t.Fragment,{children:[C?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"&&!D&&t.jsx(c.TextField,{size:"small",type:"number",label:"Value",value:u,onChange:z=>Q(parseFloat(z.target.value)||""),onFocus:()=>F(!0),onBlur:()=>F(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:J,max:X},helperText:B&&J!==void 0&&X!==void 0?`Valid range: [${J} - ${X}]`:void 0}),e.filterType==="MinMax"&&D&&t.jsxs(Ye,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ye,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(c.TextField,{size:"small",type:"number",label:"From",value:u,onChange:z=>Q(parseFloat(z.target.value)||"",g),onFocus:()=>F(!0),onBlur:()=>F(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:J,max:g||X}}),t.jsx(Ye,{children:"to"}),t.jsx(c.TextField,{size:"small",type:"number",label:"To",value:g,onChange:z=>Q(u,parseFloat(z.target.value)||""),onFocus:()=>F(!0),onBlur:()=>F(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:u||J,max:X}})]}),B&&J!==void 0&&X!==void 0&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",J," - ",X,"]"]})]}),H&&!D&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsx(c.DatePicker,{label:"Date",value:u instanceof Date?c.dayjs.utc(u):null,onChange:z=>{z===null?Q(null):z.isValid()&&Q(z.utc().toDate())},timezone:"UTC",minDate:u instanceof Date?void 0:W,maxDate:u instanceof Date?void 0:K,referenceDate:a==="After"&&W?W:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>F(!0),onBlur:()=>F(!1),helperText:B&&W&&K?`Valid range: [${W.format("YYYY-MM-DD")} - ${K.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),H&&D&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsxs(Ye,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ye,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(Ye,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"From",value:u instanceof Date?c.dayjs.utc(u):null,onChange:z=>{z===null?Q(null,g):z.isValid()&&Q(z.utc().toDate(),g)},timezone:"UTC",minDate:u instanceof Date?void 0:W,maxDate:g instanceof Date?c.dayjs.utc(g):u instanceof Date?void 0:K,referenceDate:W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>F(!0),onBlur:()=>F(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),t.jsx(Ye,{children:"to"}),t.jsx(Ye,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"To",value:g instanceof Date?c.dayjs.utc(g):null,onChange:z=>{z===null?Q(u,null):z.isValid()&&Q(u,z.utc().toDate())},timezone:"UTC",minDate:u instanceof Date?c.dayjs.utc(u):g instanceof Date?void 0:W,maxDate:g instanceof Date?void 0:K,referenceDate:u instanceof Date?c.dayjs.utc(u):W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>F(!0),onBlur:()=>F(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),B&&W&&K&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",W.format("YYYY-MM-DD")," -"," ",K.format("YYYY-MM-DD"),"]"]})]})})]})}function as(e,n){const{matchType:r,value:s,value2:i}=n;if(Array.isArray(s))return r!=="Equals"&&r!=="Semantic Search"||s.length===0?"":`(${s.map(a=>`${e} = ${c.formatMalloyValue(a)}`).join(" or ")})`;switch(r){case"Equals":case"Semantic Search":return`${e} = ${c.formatMalloyValue(s)}`;case"Contains":if(typeof s=="string"){const l=ed.StringFilterExpression.unparse({operator:"contains",values:[s]});return`${e} ~ ${c.malloyFilterLiteral(l)}`}return`${e} = ${c.formatMalloyValue(s)}`;case"After":case"Greater Than":return`${e} > ${c.formatMalloyValue(s)}`;case"Before":case"Less Than":return`${e} < ${c.formatMalloyValue(s)}`;case"Between":return i!==void 0?`${e} >= ${c.formatMalloyValue(s)} and ${e} <= ${c.formatMalloyValue(i)}`:`${e} >= ${c.formatMalloyValue(s)}`;default:return""}}function Zh(e){const n=new Set,r=e.schema?.fields;if(!r)return n;for(const s of r)"kind"in s&&s.kind==="join"&&s.name&&n.add(s.name);return n}function Xh(e){if(!e)return null;for(const n of e)if(n.startsWith("##(filters)")){const r=n.slice(11).trim();try{const s=JSON.parse(r);if(Array.isArray(s)){const i=[];for(const l of s)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(s){console.error(`Failed to parse "${n}" annotation:`,s)}}return null}function ol(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 Jh(e){const n=e.match(/^#\s*label\s*=\s*"([^"]+)"/);return n?n[1]:null}function ef(e){const n=new Map;let r="";for(const s of e)if(s.type==="code"){if(!r&&s.text){const l=s.text.split(`
4
4
  `).map(a=>a.trim()).find(a=>a.startsWith("import "))?.match(/['"]([^'"\n]+)['"]/);l&&(r=l[1])}if(s.newSources&&s.newSources.length>0)for(const i of s.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 tf(e,n,r){const s=[];for(const{source:i,dimension:l}of n){const a=e.get(i);if(!a){console.warn(`Source "${i}" not found in notebook sources`),s.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}const d=a.schema?.fields;if(!d){s.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}const u=d.find(b=>b.name===l);if(!u){console.warn(`Dimension "${l}" not found in source "${i}"`),s.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}let h="Star",g;if("annotations"in u&&u.annotations){for(const b of u.annotations)if(b.value){const x=ol(b.value);x&&(h=x.type);const v=Jh(b.value);v&&(g=v)}}s.push({source:i,model:r,dimensionName:l,filterType:h,label:g})}return s}function nf(e,n,r){return e.length===0?"":e.map(i=>{const{dimensionName:l,source:a}=i,u=a&&a!==r?`\`${a}\`.\`${l}\``:`\`${l}\``;return as(u,i)}).filter(i=>i.length>0).join(" and ")}function rf(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 sf(e,n){return`${e.trimEnd()} + {where: ${n}}`}const of=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"})),il=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(),s=n.split(/\n\s*\n/)[1]||n;if(s.length<=120)return s;const i=s.substring(0,120).split(" ");return i.pop(),i.join(" ")+"..."},al=(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
6
  `)};function Ui(){const[e,n]=j.useState(!1),{apiClients:r}=q.useServer(),s=()=>{n(!0)},i=()=>{n(!1)},l=Pn({mutationFn(d){return r.environments.createEnvironment({name:d.name,readme:al({name:d.name,readme:""},d.description)})},success:"Environment created",invalidates:[["environments"]],closeDialog:i,resource:"environment",action:"create"}),a=async d=>{d.preventDefault();const u=new FormData(d.currentTarget),h=u.get("name")?.toString(),g=u.get("description")?.toString();if(!h)throw new Error("Name is required");l.mutate({name:h,description:g})};return t.jsxs(j.Fragment,{children:[t.jsx(c.AddButton,{label:"Environment",onClick:s}),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(is,{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 af({environment:e,onCloseDialog:n}){const[r,s]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{s(!0)},a=()=>{s(!1),n()},d=Pn({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(m.MenuItem,{onClick:l,children:[t.jsx(m.ListItemIcon,{children:t.jsx(_t.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:()=>d.mutate(),loading:d.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."]})}),d.notice]})}function lf({environment:e,onCloseDialog:n}){const[r,s]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{s(!0)},a=()=>{s(!1),n()},d=Pn({mutationFn(h){return i.environments.updateEnvironment(e.name,{name:e.name,readme:al({name:e.name,readme:e.readme},h.description)})},success:"Environment updated",invalidates:[["environments"]],closeDialog:a,resource:"environment",action:"update"}),u=h=>{h.preventDefault();const b=new FormData(h.currentTarget).get("description")?.toString();d.mutate({description:b})};return t.jsxs(j.Fragment,{children:[t.jsxs(m.MenuItem,{onClick:l,children:[t.jsx(m.ListItemIcon,{children:t.jsx(_t.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:d.isPending,onClick:a,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"environment-form",variant:"contained",loading:d.isPending,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:u,id:"environment-form",children:t.jsxs(is,{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:il(e.readme),InputLabelProps:{shrink:!0}})]})})}),d.notice]})}const cf=[{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 uf({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 df({onClickEnvironment:e}){const{apiClients:n,mutable:r}=q.useServer(),{data:s,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 d=s.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:cf.map(u=>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:u.href,target:"_blank",rel:"noopener noreferrer",sx:{fontWeight:500,color:"text.primary",textDecoration:"none","&:hover":{textDecoration:"underline"}},children:u.title}),t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{lineHeight:1.6},children:u.body})]})},u.title))}),t.jsx(m.Divider,{sx:{my:4}}),d.length>0?t.jsx(Pt,{title:"Environments",count:d.length,description:"Published environments available on this server",...r?{action:t.jsx(Ui,{})}:{},children:t.jsx(m.Stack,{children:d.map(u=>t.jsx(hf,{environment:u,...e?{onClickEnvironment:e}:{}},u.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(Ui,{}):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(uf,{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 hf({environment:e,onClickEnvironment:n}){const{mutable:r}=q.useServer(),[s,i]=j.useState(null),l=!!s,a=il(e.readme),d=h=>{h.stopPropagation(),i(h.currentTarget)},u=()=>i(null);return t.jsx(os,{icon:t.jsx(of,{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:d,"aria-label":`Environment actions for ${e.name}`,children:t.jsx(_t.MoreVert,{fontSize:"small"})}),t.jsxs(m.Menu,{anchorEl:s,open:l,onClose:u,onClick:h=>h.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[t.jsx(lf,{environment:e,onCloseDialog:u}),t.jsx(af,{environment:e,onCloseDialog:u})]})]})}:{}})}var an={},jt={},tr={},ln={},Is={},Gi;function ff(){return Gi||(Gi=1,Object.defineProperty(Is,"__esModule",{value:!0})),Is}var nr={},rr={},Yi;function pn(){if(Yi)return rr;Yi=1,Object.defineProperty(rr,"__esModule",{value:!0}),rr.CronField=void 0;let e=class ll{#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,s={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={...s,rawValue:s.rawValue??""},this.#s=r.sort(ll.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,s){const i=typeof r=="number",l=typeof s=="number";return i&&l?r-s:!i&&!l?r.localeCompare(s):i?-1:1}static findNearestValueInList(r,s,i){if(i){for(let l=r.length-1;l>=0;l--)if(r[l]<s)return r[l];return null}for(let l=0;l<r.length;l++)if(r[l]>s)return r[l];return null}findNearestValue(r,s){return this.constructor.findNearestValueInList(this.values,r,s)}serialize(){return{wildcard:this.#o,values:this.#s}}validate(){let r;const s=this.chars.length>0?` or chars ${this.chars.join("")}`:"",i=u=>h=>new RegExp(`^\\d{0,2}${h}$`).test(u),l=u=>(r=u,typeof u=="number"?u>=this.min&&u<=this.max:this.chars.some(i(u)));if(!this.#s.every(l))throw new Error(`${this.constructor.name} Validation error, got value ${r} expected range ${this.min}-${this.max}${s}`);const d=this.#s.find((u,h)=>this.#s.indexOf(u)!==h);if(d)throw new Error(`${this.constructor.name} Validation error, duplicate values found: ${d}`)}#r(){return this.options.rawValue.length>0?["*","?"].includes(this.options.rawValue):Array.from({length:this.max-this.min+1},(r,s)=>s+this.min).every(r=>this.#s.includes(r))}};return rr.CronField=e,rr}var Ki;function pf(){if(Ki)return nr;Ki=1,Object.defineProperty(nr,"__esModule",{value:!0}),nr.CronDayOfMonth=void 0;const e=pn(),n=1,r=31,s=Object.freeze(["L"]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return s}static get validChars(){return/^[?,*\dLH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(a,d){super(a,d),this.validate()}get values(){return super.values}};return nr.CronDayOfMonth=i,nr}var sr={},Qi;function mf(){if(Qi)return sr;Qi=1,Object.defineProperty(sr,"__esModule",{value:!0}),sr.CronDayOfWeek=void 0;const e=pn(),n=0,r=7,s=Object.freeze(["L"]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return s}static get validChars(){return/^[?,*\dLH#/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(a,d){super(a,d),this.validate()}get values(){return super.values}get nthDay(){return this.options.nthDayOfWeek??0}};return sr.CronDayOfWeek=i,sr}var or={},Zi;function gf(){if(Zi)return or;Zi=1,Object.defineProperty(or,"__esModule",{value:!0}),or.CronHour=void 0;const e=pn(),n=0,r=23,s=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return s}constructor(a,d){super(a,d),this.validate()}get values(){return super.values}};return or.CronHour=i,or}var ir={},Xi;function yf(){if(Xi)return ir;Xi=1,Object.defineProperty(ir,"__esModule",{value:!0}),ir.CronMinute=void 0;const e=pn(),n=0,r=59,s=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return s}constructor(a,d){super(a,d),this.validate()}get values(){return super.values}};return ir.CronMinute=i,ir}var ar={},Es={},wt={},Ji;function xf(){if(Ji)return wt;Ji=1,Object.defineProperty(wt,"__esModule",{value:!0});class e extends Error{}class n extends e{constructor(o){super(`Invalid DateTime: ${o.toMessage()}`)}}class r extends e{constructor(o){super(`Invalid Interval: ${o.toMessage()}`)}}class s extends e{constructor(o){super(`Invalid Duration: ${o.toMessage()}`)}}class i extends e{}class l extends e{constructor(o){super(`Invalid unit ${o}`)}}class a extends e{}class d extends e{constructor(){super("Zone is an abstract class")}}const u="numeric",h="short",g="long",b={year:u,month:u,day:u},x={year:u,month:h,day:u},v={year:u,month:h,day:u,weekday:h},C={year:u,month:g,day:u},k={year:u,month:g,day:u,weekday:g},S={hour:u,minute:u},T={hour:u,minute:u,second:u},M={hour:u,minute:u,second:u,timeZoneName:h},O={hour:u,minute:u,second:u,timeZoneName:g},I={hour:u,minute:u,hourCycle:"h23"},R={hour:u,minute:u,second:u,hourCycle:"h23"},_={hour:u,minute:u,second:u,hourCycle:"h23",timeZoneName:h},$={hour:u,minute:u,second:u,hourCycle:"h23",timeZoneName:g},B={year:u,month:u,day:u,hour:u,minute:u},F={year:u,month:u,day:u,hour:u,minute:u,second:u},N={year:u,month:h,day:u,hour:u,minute:u},H={year:u,month:h,day:u,hour:u,minute:u,second:u},D={year:u,month:h,day:u,weekday:h,hour:u,minute:u},W={year:u,month:g,day:u,hour:u,minute:u,timeZoneName:h},K={year:u,month:g,day:u,hour:u,minute:u,second:u,timeZoneName:h},J={year:u,month:g,day:u,weekday:g,hour:u,minute:u,timeZoneName:g},X={year:u,month:g,day:u,weekday:g,hour:u,minute:u,second:u,timeZoneName:g};class G{get type(){throw new d}get name(){throw new d}get ianaName(){return this.name}get isUniversal(){throw new d}offsetName(o,f){throw new d}formatOffset(o,f){throw new d}offset(o){throw new d}equals(o){throw new d}get isValid(){throw new d}}let Q=null;class ie extends G{static get instance(){return Q===null&&(Q=new ie),Q}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(o,{format:f,locale:y}){return Lo(o,f,y)}formatOffset(o,f){return Vn(this.offset(o),f)}offset(o){return-new Date(o).getTimezoneOffset()}equals(o){return o.type==="system"}get isValid(){return!0}}const z=new Map;function re(p){let o=z.get(p);return o===void 0&&(o=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,o)),o}const se={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function ne(p,o){const f=p.format(o).replace(/\u200E/g,""),y=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(f),[,w,E,A,L,P,ee,xe]=y;return[A,w,E,L,P,ee,xe]}function Me(p,o){const f=p.formatToParts(o),y=[];for(let w=0;w<f.length;w++){const{type:E,value:A}=f[w],L=se[E];E==="era"?y[L]=A:te(L)||(y[L]=parseInt(A,10))}return y}const oe=new Map;class ue extends G{static create(o){let f=oe.get(o);return f===void 0&&oe.set(o,f=new ue(o)),f}static resetCache(){oe.clear(),z.clear()}static isValidSpecifier(o){return this.isValidZone(o)}static isValidZone(o){if(!o)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:o}).format(),!0}catch{return!1}}constructor(o){super(),this.zoneName=o,this.valid=ue.isValidZone(o)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(o,{format:f,locale:y}){return Lo(o,f,y,this.name)}formatOffset(o,f){return Vn(this.offset(o),f)}offset(o){if(!this.valid)return NaN;const f=new Date(o);if(isNaN(f))return NaN;const y=re(this.name);let[w,E,A,L,P,ee,xe]=y.formatToParts?Me(y,f):ne(y,f);L==="BC"&&(w=-Math.abs(w)+1);const He=Rr({year:w,month:E,day:A,hour:P===24?0:P,minute:ee,second:xe,millisecond:0});let Se=+f;const it=Se%1e3;return Se-=it>=0?it:1e3+it,(He-Se)/(60*1e3)}equals(o){return o.type==="iana"&&o.name===this.name}get isValid(){return this.valid}}let De={};function Ne(p,o={}){const f=JSON.stringify([p,o]);let y=De[f];return y||(y=new Intl.ListFormat(p,o),De[f]=y),y}const ae=new Map;function Z(p,o={}){const f=JSON.stringify([p,o]);let y=ae.get(f);return y===void 0&&(y=new Intl.DateTimeFormat(p,o),ae.set(f,y)),y}const ce=new Map;function be(p,o={}){const f=JSON.stringify([p,o]);let y=ce.get(f);return y===void 0&&(y=new Intl.NumberFormat(p,o),ce.set(f,y)),y}const ge=new Map;function he(p,o={}){const{base:f,...y}=o,w=JSON.stringify([p,y]);let E=ge.get(w);return E===void 0&&(E=new Intl.RelativeTimeFormat(p,o),ge.set(w,E)),E}let ye=null;function Fe(){return ye||(ye=new Intl.DateTimeFormat().resolvedOptions().locale,ye)}const ze=new Map;function me(p){let o=ze.get(p);return o===void 0&&(o=new Intl.DateTimeFormat(p).resolvedOptions(),ze.set(p,o)),o}const Y=new Map;function le(p){let o=Y.get(p);if(!o){const f=new Intl.Locale(p);o="getWeekInfo"in f?f.getWeekInfo():f.weekInfo,"minimalDays"in o||(o={...Ke,...o}),Y.set(p,o)}return o}function Oe(p){const o=p.indexOf("-x-");o!==-1&&(p=p.substring(0,o));const f=p.indexOf("-u-");if(f===-1)return[p];{let y,w;try{y=Z(p).resolvedOptions(),w=p}catch{const P=p.substring(0,f);y=Z(P).resolvedOptions(),w=P}const{numberingSystem:E,calendar:A}=y;return[w,E,A]}}function Re(p,o,f){return(f||o)&&(p.includes("-u-")||(p+="-u"),f&&(p+=`-ca-${f}`),o&&(p+=`-nu-${o}`)),p}function at(p){const o=[];for(let f=1;f<=12;f++){const y=ke.utc(2009,f,1);o.push(p(y))}return o}function Ie(p){const o=[];for(let f=1;f<=7;f++){const y=ke.utc(2016,11,13+f);o.push(p(y))}return o}function lt(p,o,f,y){const w=p.listingMode();return w==="error"?null:w==="en"?f(o):y(o)}function xt(p){return p.numberingSystem&&p.numberingSystem!=="latn"?!1:p.numberingSystem==="latn"||!p.locale||p.locale.startsWith("en")||me(p.locale).numberingSystem==="latn"}class vt{constructor(o,f,y){this.padTo=y.padTo||0,this.floor=y.floor||!1;const{padTo:w,floor:E,...A}=y;if(!f||Object.keys(A).length>0){const L={useGrouping:!1,...y};y.padTo>0&&(L.minimumIntegerDigits=y.padTo),this.inf=be(o,L)}}format(o){if(this.inf){const f=this.floor?Math.floor(o):o;return this.inf.format(f)}else{const f=this.floor?Math.floor(o):ps(o,3);return ot(f,this.padTo)}}}class Mt{constructor(o,f,y){this.opts=y,this.originalZone=void 0;let w;if(this.opts.timeZone)this.dt=o;else if(o.zone.type==="fixed"){const A=-1*(o.offset/60),L=A>=0?`Etc/GMT+${A}`:`Etc/GMT${A}`;o.offset!==0&&ue.create(L).valid?(w=L,this.dt=o):(w="UTC",this.dt=o.offset===0?o:o.setZone("UTC").plus({minutes:o.offset}),this.originalZone=o.zone)}else o.zone.type==="system"?this.dt=o:o.zone.type==="iana"?(this.dt=o,w=o.zone.name):(w="UTC",this.dt=o.setZone("UTC").plus({minutes:o.offset}),this.originalZone=o.zone);const E={...this.opts};E.timeZone=E.timeZone||w,this.dtf=Z(f,E)}format(){return this.originalZone?this.formatToParts().map(({value:o})=>o).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const o=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?o.map(f=>{if(f.type==="timeZoneName"){const y=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...f,value:y}}else return f}):o}resolvedOptions(){return this.dtf.resolvedOptions()}}class mt{constructor(o,f,y){this.opts={style:"long",...y},!f&&zn()&&(this.rtf=he(o,y))}format(o,f){return this.rtf?this.rtf.format(o,f):$c(f,o,this.opts.numeric,this.opts.style!=="long")}formatToParts(o,f){return this.rtf?this.rtf.formatToParts(o,f):[]}}const Ke={firstDay:1,minimalDays:4,weekend:[6,7]};class fe{static fromOpts(o){return fe.create(o.locale,o.numberingSystem,o.outputCalendar,o.weekSettings,o.defaultToEN)}static create(o,f,y,w,E=!1){const A=o||_e.defaultLocale,L=A||(E?"en-US":Fe()),P=f||_e.defaultNumberingSystem,ee=y||_e.defaultOutputCalendar,xe=qt(w)||_e.defaultWeekSettings;return new fe(L,P,ee,xe,A)}static resetCache(){ye=null,ae.clear(),ce.clear(),ge.clear(),ze.clear(),Y.clear()}static fromObject({locale:o,numberingSystem:f,outputCalendar:y,weekSettings:w}={}){return fe.create(o,f,y,w)}constructor(o,f,y,w,E){const[A,L,P]=Oe(o);this.locale=A,this.numberingSystem=f||L||null,this.outputCalendar=y||P||null,this.weekSettings=w,this.intl=Re(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=E,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=xt(this)),this.fastNumbersCached}listingMode(){const o=this.isEnglish(),f=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return o&&f?"en":"intl"}clone(o){return!o||Object.getOwnPropertyNames(o).length===0?this:fe.create(o.locale||this.specifiedLocale,o.numberingSystem||this.numberingSystem,o.outputCalendar||this.outputCalendar,qt(o.weekSettings)||this.weekSettings,o.defaultToEN||!1)}redefaultToEN(o={}){return this.clone({...o,defaultToEN:!0})}redefaultToSystem(o={}){return this.clone({...o,defaultToEN:!1})}months(o,f=!1){return lt(this,o,_o,()=>{const y=this.intl==="ja"||this.intl.startsWith("ja-");f&=!y;const w=f?{month:o,day:"numeric"}:{month:o},E=f?"format":"standalone";if(!this.monthsCache[E][o]){const A=y?L=>this.dtFormatter(L,w).format():L=>this.extract(L,w,"month");this.monthsCache[E][o]=at(A)}return this.monthsCache[E][o]})}weekdays(o,f=!1){return lt(this,o,qo,()=>{const y=f?{weekday:o,year:"numeric",month:"long",day:"numeric"}:{weekday:o},w=f?"format":"standalone";return this.weekdaysCache[w][o]||(this.weekdaysCache[w][o]=Ie(E=>this.extract(E,y,"weekday"))),this.weekdaysCache[w][o]})}meridiems(){return lt(this,void 0,()=>Bo,()=>{if(!this.meridiemCache){const o={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[ke.utc(2016,11,13,9),ke.utc(2016,11,13,19)].map(f=>this.extract(f,o,"dayperiod"))}return this.meridiemCache})}eras(o){return lt(this,o,Vo,()=>{const f={era:o};return this.eraCache[o]||(this.eraCache[o]=[ke.utc(-40,1,1),ke.utc(2017,1,1)].map(y=>this.extract(y,f,"era"))),this.eraCache[o]})}extract(o,f,y){const w=this.dtFormatter(o,f),E=w.formatToParts(),A=E.find(L=>L.type.toLowerCase()===y);return A?A.value:null}numberFormatter(o={}){return new vt(this.intl,o.forceSimple||this.fastNumbers,o)}dtFormatter(o,f={}){return new Mt(o,this.intl,f)}relFormatter(o={}){return new mt(this.intl,this.isEnglish(),o)}listFormatter(o={}){return Ne(this.intl,o)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||me(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Wn()?le(this.locale):Ke}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(o){return this.locale===o.locale&&this.numberingSystem===o.numberingSystem&&this.outputCalendar===o.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let Qe=null;class qe extends G{static get utcInstance(){return Qe===null&&(Qe=new qe(0)),Qe}static instance(o){return o===0?qe.utcInstance:new qe(o)}static parseSpecifier(o){if(o){const f=o.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(f)return new qe(Ar(f[1],f[2]))}return null}constructor(o){super(),this.fixed=o}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(o,f){return Vn(this.fixed,f)}get isUniversal(){return!0}offset(){return this.fixed}equals(o){return o.type==="fixed"&&o.fixed===this.fixed}get isValid(){return!0}}class ct extends G{constructor(o){super(),this.zoneName=o}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 ut(p,o){if(te(p)||p===null)return o;if(p instanceof G)return p;if(Ct(p)){const f=p.toLowerCase();return f==="default"?o:f==="local"||f==="system"?ie.instance:f==="utc"||f==="gmt"?qe.utcInstance:qe.parseSpecifier(f)||ue.create(p)}else return Ve(p)?qe.instance(p):typeof p=="object"&&"offset"in p&&typeof p.offset=="function"?p:new ct(p)}const Ze={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]},Ue=Ze.hanidec.replace(/[\[|\]]/g,"").split("");function bt(p){let o=parseInt(p,10);if(isNaN(o)){o="";for(let f=0;f<p.length;f++){const y=p.charCodeAt(f);if(p[f].search(Ze.hanidec)!==-1)o+=Ue.indexOf(p[f]);else for(const w in pe){const[E,A]=pe[w];y>=E&&y<=A&&(o+=y-E)}}return parseInt(o,10)}else return o}const Ce=new Map;function Le(){Ce.clear()}function Ee({numberingSystem:p},o=""){const f=p||"latn";let y=Ce.get(f);y===void 0&&(y=new Map,Ce.set(f,y));let w=y.get(o);return w===void 0&&(w=new RegExp(`${Ze[f]}${o}`),y.set(o,w)),w}let Be=()=>Date.now(),ht="system",We=null,nt=null,Ot=null,kt=60,$t,gn=null;class _e{static get now(){return Be}static set now(o){Be=o}static set defaultZone(o){ht=o}static get defaultZone(){return ut(ht,ie.instance)}static get defaultLocale(){return We}static set defaultLocale(o){We=o}static get defaultNumberingSystem(){return nt}static set defaultNumberingSystem(o){nt=o}static get defaultOutputCalendar(){return Ot}static set defaultOutputCalendar(o){Ot=o}static get defaultWeekSettings(){return gn}static set defaultWeekSettings(o){gn=qt(o)}static get twoDigitCutoffYear(){return kt}static set twoDigitCutoffYear(o){kt=o%100}static get throwOnInvalid(){return $t}static set throwOnInvalid(o){$t=o}static resetCaches(){fe.resetCache(),ue.resetCache(),ke.resetCache(),Le()}}class dt{constructor(o,f){this.reason=o,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 ft(p,o){return new dt("unit out of range",`you specified ${o} (of type ${typeof o}) as a ${p}, which is invalid`)}function en(p,o,f){const y=new Date(Date.UTC(p,o-1,f));p<100&&p>=0&&y.setUTCFullYear(y.getUTCFullYear()-1900);const w=y.getUTCDay();return w===0?7:w}function xn(p,o,f){return f+(qn(p)?yn:Kt)[o-1]}function Qt(p,o){const f=qn(p)?yn:Kt,y=f.findIndex(E=>E<o),w=o-f[y];return{month:y+1,day:w}}function Xe(p,o){return(p-o+7)%7+1}function Je(p,o=4,f=1){const{year:y,month:w,day:E}=p,A=xn(y,w,E),L=Xe(en(y,w,E),f);let P=Math.floor((A-L+14-o)/7),ee;return P<1?(ee=y-1,P=Bn(ee,o,f)):P>Bn(y,o,f)?(ee=y+1,P=1):ee=y,{weekYear:ee,weekNumber:P,weekday:L,...Nr(p)}}function Rt(p,o=4,f=1){const{weekYear:y,weekNumber:w,weekday:E}=p,A=Xe(en(y,1,o),f),L=bn(y);let P=w*7+E-A-7+o,ee;P<1?(ee=y-1,P+=bn(ee)):P>L?(ee=y+1,P-=bn(y)):ee=y;const{month:xe,day:je}=Qt(ee,P);return{year:ee,month:xe,day:je,...Nr(p)}}function tn(p){const{year:o,month:f,day:y}=p,w=xn(o,f,y);return{year:o,ordinal:w,...Nr(p)}}function Zt(p){const{year:o,ordinal:f}=p,{month:y,day:w}=Qt(o,f);return{year:o,month:y,day:w,...Nr(p)}}function nn(p,o){if(!te(p.localWeekday)||!te(p.localWeekNumber)||!te(p.localWeekYear)){if(!te(p.weekday)||!te(p.weekNumber)||!te(p.weekYear))throw new i("Cannot mix locale-based week fields with ISO-based week fields");return te(p.localWeekday)||(p.weekday=p.localWeekday),te(p.localWeekNumber)||(p.weekNumber=p.localWeekNumber),te(p.localWeekYear)||(p.weekYear=p.localWeekYear),delete p.localWeekday,delete p.localWeekNumber,delete p.localWeekYear,{minDaysInFirstWeek:o.getMinDaysInFirstWeek(),startOfWeek:o.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function U(p,o=4,f=1){const y=Ge(p.weekYear),w=It(p.weekNumber,1,Bn(p.weekYear,o,f)),E=It(p.weekday,1,7);return y?w?E?!1:ft("weekday",p.weekday):ft("week",p.weekNumber):ft("weekYear",p.weekYear)}function V(p){const o=Ge(p.year),f=It(p.ordinal,1,bn(p.year));return o?f?!1:ft("ordinal",p.ordinal):ft("year",p.year)}function de(p){const o=Ge(p.year),f=It(p.month,1,12),y=It(p.day,1,$r(p.year,p.month));return o?f?y?!1:ft("day",p.day):ft("month",p.month):ft("year",p.year)}function ve(p){const{hour:o,minute:f,second:y,millisecond:w}=p,E=It(o,0,23)||o===24&&f===0&&y===0&&w===0,A=It(f,0,59),L=It(y,0,59),P=It(w,0,999);return E?A?L?P?!1:ft("millisecond",w):ft("second",y):ft("minute",f):ft("hour",o)}function te(p){return typeof p>"u"}function Ve(p){return typeof p=="number"}function Ge(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 Fr(p){return Array.isArray(p)?p:[p]}function $e(p,o,f){if(p.length!==0)return p.reduce((y,w)=>{const E=[o(w),w];return y&&f(y[0],E[0])===y[0]?y:E},null)[1]}function zt(p,o){return o.reduce((f,y)=>(f[y]=p[y],f),{})}function gt(p,o){return Object.prototype.hasOwnProperty.call(p,o)}function qt(p){if(p==null)return null;if(typeof p!="object")throw new a("Week settings must be an object");if(!It(p.firstDay,1,7)||!It(p.minimalDays,1,7)||!Array.isArray(p.weekend)||p.weekend.some(o=>!It(o,1,7)))throw new a("Invalid week settings");return{firstDay:p.firstDay,minimalDays:p.minimalDays,weekend:Array.from(p.weekend)}}function It(p,o,f){return Ge(p)&&p>=o&&p<=f}function Sc(p,o){return p-o*Math.floor(p/o)}function ot(p,o=2){const f=p<0;let y;return f?y="-"+(""+-p).padStart(o,"0"):y=(""+p).padStart(o,"0"),y}function Xt(p){if(!(te(p)||p===null||p===""))return parseInt(p,10)}function rn(p){if(!(te(p)||p===null||p===""))return parseFloat(p)}function fs(p){if(!(te(p)||p===null||p==="")){const o=parseFloat("0."+p)*1e3;return Math.floor(o)}}function ps(p,o,f="round"){const y=10**o;switch(f){case"expand":return p>0?Math.ceil(p*y)/y:Math.floor(p*y)/y;case"trunc":return Math.trunc(p*y)/y;case"round":return Math.round(p*y)/y;case"floor":return Math.floor(p*y)/y;case"ceil":return Math.ceil(p*y)/y;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 $r(p,o){const f=Sc(o-1,12)+1,y=p+(o-f)/12;return f===2?qn(y)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][f-1]}function Rr(p){let o=Date.UTC(p.year,p.month-1,p.day,p.hour,p.minute,p.second,p.millisecond);return p.year<100&&p.year>=0&&(o=new Date(o),o.setUTCFullYear(p.year,p.month-1,p.day)),+o}function Ao(p,o,f){return-Xe(en(p,1,o),f)+o-1}function Bn(p,o=4,f=1){const y=Ao(p,o,f),w=Ao(p+1,o,f);return(bn(p)-y+w)/7}function ms(p){return p>99?p:p>_e.twoDigitCutoffYear?1900+p:2e3+p}function Lo(p,o,f,y=null){const w=new Date(p),E={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};y&&(E.timeZone=y);const A={timeZoneName:o,...E},L=new Intl.DateTimeFormat(f,A).formatToParts(w).find(P=>P.type.toLowerCase()==="timezonename");return L?L.value:null}function Ar(p,o){let f=parseInt(p,10);Number.isNaN(f)&&(f=0);const y=parseInt(o,10)||0,w=f<0||Object.is(f,-0)?-y:y;return f*60+w}function No(p){const o=Number(p);if(typeof p=="boolean"||p===""||!Number.isFinite(o))throw new a(`Invalid unit value ${p}`);return o}function Lr(p,o){const f={};for(const y in p)if(gt(p,y)){const w=p[y];if(w==null)continue;f[o(y)]=No(w)}return f}function Vn(p,o){const f=Math.trunc(Math.abs(p/60)),y=Math.trunc(Math.abs(p%60)),w=p>=0?"+":"-";switch(o){case"short":return`${w}${ot(f,2)}:${ot(y,2)}`;case"narrow":return`${w}${f}${y>0?`:${y}`:""}`;case"techie":return`${w}${ot(f,2)}${ot(y,2)}`;default:throw new RangeError(`Value format ${o} is out of range for property format`)}}function Nr(p){return zt(p,["hour","minute","second","millisecond"])}const kc=["January","February","March","April","May","June","July","August","September","October","November","December"],Po=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],Cc=["J","F","M","A","M","J","J","A","S","O","N","D"];function _o(p){switch(p){case"narrow":return[...Cc];case"short":return[...Po];case"long":return[...kc];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 zo=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Wo=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],jc=["M","T","W","T","F","S","S"];function qo(p){switch(p){case"narrow":return[...jc];case"short":return[...Wo];case"long":return[...zo];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const Bo=["AM","PM"],Tc=["Before Christ","Anno Domini"],Mc=["BC","AD"],Oc=["B","A"];function Vo(p){switch(p){case"narrow":return[...Oc];case"short":return[...Mc];case"long":return[...Tc];default:return null}}function Ic(p){return Bo[p.hour<12?0:1]}function Ec(p,o){return qo(o)[p.weekday-1]}function Dc(p,o){return _o(o)[p.month-1]}function Fc(p,o){return Vo(o)[p.year<0?0:1]}function $c(p,o,f="always",y=!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."]},E=["hours","minutes","seconds"].indexOf(p)===-1;if(f==="auto"&&E){const je=p==="days";switch(o){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 A=Object.is(o,-0)||o<0,L=Math.abs(o),P=L===1,ee=w[p],xe=y?P?ee[1]:ee[2]||ee[1]:P?w[p][0]:p;return A?`${L} ${xe} ago`:`in ${L} ${xe}`}function Ho(p,o){let f="";for(const y of p)y.literal?f+=y.val:f+=o(y.val);return f}const Rc={D:b,DD:x,DDD:C,DDDD:k,t:S,tt:T,ttt:M,tttt:O,T:I,TT:R,TTT:_,TTTT:$,f:B,ff:N,fff:W,ffff:J,F,FF:H,FFF:K,FFFF:X};class pt{static create(o,f={}){return new pt(o,f)}static parseFormat(o){let f=null,y="",w=!1;const E=[];for(let A=0;A<o.length;A++){const L=o.charAt(A);L==="'"?((y.length>0||w)&&E.push({literal:w||/^\s+$/.test(y),val:y===""?"'":y}),f=null,y="",w=!w):w||L===f?y+=L:(y.length>0&&E.push({literal:/^\s+$/.test(y),val:y}),y=L,f=L)}return y.length>0&&E.push({literal:w||/^\s+$/.test(y),val:y}),E}static macroTokenToFormatOpts(o){return Rc[o]}constructor(o,f){this.opts=f,this.loc=o,this.systemLoc=null}formatWithSystemDefault(o,f){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(o,{...this.opts,...f}).format()}dtFormatter(o,f={}){return this.loc.dtFormatter(o,{...this.opts,...f})}formatDateTime(o,f){return this.dtFormatter(o,f).format()}formatDateTimeParts(o,f){return this.dtFormatter(o,f).formatToParts()}formatInterval(o,f){return this.dtFormatter(o.start,f).dtf.formatRange(o.start.toJSDate(),o.end.toJSDate())}resolvedOptions(o,f){return this.dtFormatter(o,f).resolvedOptions()}num(o,f=0,y=void 0){if(this.opts.forceSimple)return ot(o,f);const w={...this.opts};return f>0&&(w.padTo=f),y&&(w.signDisplay=y),this.loc.numberFormatter(w).format(o)}formatDateTimeFromString(o,f){const y=this.loc.listingMode()==="en",w=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",E=(Se,it)=>this.loc.extract(o,Se,it),A=Se=>o.isOffsetFixed&&o.offset===0&&Se.allowZ?"Z":o.isValid?o.zone.formatOffset(o.ts,Se.format):"",L=()=>y?Ic(o):E({hour:"numeric",hourCycle:"h12"},"dayperiod"),P=(Se,it)=>y?Dc(o,Se):E(it?{month:Se}:{month:Se,day:"numeric"},"month"),ee=(Se,it)=>y?Ec(o,Se):E(it?{weekday:Se}:{weekday:Se,month:"long",day:"numeric"},"weekday"),xe=Se=>{const it=pt.macroTokenToFormatOpts(Se);return it?this.formatWithSystemDefault(o,it):Se},je=Se=>y?Fc(o,Se):E({era:Se},"era"),He=Se=>{switch(Se){case"S":return this.num(o.millisecond);case"u":case"SSS":return this.num(o.millisecond,3);case"s":return this.num(o.second);case"ss":return this.num(o.second,2);case"uu":return this.num(Math.floor(o.millisecond/10),2);case"uuu":return this.num(Math.floor(o.millisecond/100));case"m":return this.num(o.minute);case"mm":return this.num(o.minute,2);case"h":return this.num(o.hour%12===0?12:o.hour%12);case"hh":return this.num(o.hour%12===0?12:o.hour%12,2);case"H":return this.num(o.hour);case"HH":return this.num(o.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 o.zone.offsetName(o.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return o.zone.offsetName(o.ts,{format:"long",locale:this.loc.locale});case"z":return o.zoneName;case"a":return L();case"d":return w?E({day:"numeric"},"day"):this.num(o.day);case"dd":return w?E({day:"2-digit"},"day"):this.num(o.day,2);case"c":return this.num(o.weekday);case"ccc":return ee("short",!0);case"cccc":return ee("long",!0);case"ccccc":return ee("narrow",!0);case"E":return this.num(o.weekday);case"EEE":return ee("short",!1);case"EEEE":return ee("long",!1);case"EEEEE":return ee("narrow",!1);case"L":return w?E({month:"numeric",day:"numeric"},"month"):this.num(o.month);case"LL":return w?E({month:"2-digit",day:"numeric"},"month"):this.num(o.month,2);case"LLL":return P("short",!0);case"LLLL":return P("long",!0);case"LLLLL":return P("narrow",!0);case"M":return w?E({month:"numeric"},"month"):this.num(o.month);case"MM":return w?E({month:"2-digit"},"month"):this.num(o.month,2);case"MMM":return P("short",!1);case"MMMM":return P("long",!1);case"MMMMM":return P("narrow",!1);case"y":return w?E({year:"numeric"},"year"):this.num(o.year);case"yy":return w?E({year:"2-digit"},"year"):this.num(o.year.toString().slice(-2),2);case"yyyy":return w?E({year:"numeric"},"year"):this.num(o.year,4);case"yyyyyy":return w?E({year:"numeric"},"year"):this.num(o.year,6);case"G":return je("short");case"GG":return je("long");case"GGGGG":return je("narrow");case"kk":return this.num(o.weekYear.toString().slice(-2),2);case"kkkk":return this.num(o.weekYear,4);case"W":return this.num(o.weekNumber);case"WW":return this.num(o.weekNumber,2);case"n":return this.num(o.localWeekNumber);case"nn":return this.num(o.localWeekNumber,2);case"ii":return this.num(o.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(o.localWeekYear,4);case"o":return this.num(o.ordinal);case"ooo":return this.num(o.ordinal,3);case"q":return this.num(o.quarter);case"qq":return this.num(o.quarter,2);case"X":return this.num(Math.floor(o.ts/1e3));case"x":return this.num(o.ts);default:return xe(Se)}};return Ho(pt.parseFormat(f),He)}formatDurationFromString(o,f){const y=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}},E=(xe,je)=>He=>{const Se=w(He);if(Se){const it=je.isNegativeDuration&&Se!==je.largestUnit?y: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,He.length,Lt)}else return He},A=pt.parseFormat(f),L=A.reduce((xe,{literal:je,val:He})=>je?xe:xe.concat(He),[]),P=o.shiftTo(...L.map(w).filter(xe=>xe)),ee={isNegativeDuration:P<0,largestUnit:Object.keys(P.values)[0]};return Ho(A,E(P,ee))}}const Uo=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function wn(...p){const o=p.reduce((f,y)=>f+y.source,"");return RegExp(`^${o}$`)}function Sn(...p){return o=>p.reduce(([f,y,w],E)=>{const[A,L,P]=E(o,w);return[{...f,...A},L||y,P]},[{},null,1]).slice(0,2)}function kn(p,...o){if(p==null)return[null,null];for(const[f,y]of o){const w=f.exec(p);if(w)return y(w)}return[null,null]}function Go(...p){return(o,f)=>{const y={};let w;for(w=0;w<p.length;w++)y[p[w]]=Xt(o[f+w]);return[y,null,f+w]}}const Yo=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,Ac=`(?:${Yo.source}?(?:\\[(${Uo.source})\\])?)?`,gs=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,Ko=RegExp(`${gs.source}${Ac}`),ys=RegExp(`(?:[Tt]${Ko.source})?`),Lc=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,Nc=/(\d{4})-?W(\d\d)(?:-?(\d))?/,Pc=/(\d{4})-?(\d{3})/,_c=Go("weekYear","weekNumber","weekDay"),zc=Go("year","ordinal"),Wc=/(\d{4})-(\d\d)-(\d\d)/,Qo=RegExp(`${gs.source} ?(?:${Yo.source}|(${Uo.source}))?`),qc=RegExp(`(?: ${Qo.source})?`);function Cn(p,o,f){const y=p[o];return te(y)?f:Xt(y)}function Bc(p,o){return[{year:Cn(p,o),month:Cn(p,o+1,1),day:Cn(p,o+2,1)},null,o+3]}function jn(p,o){return[{hours:Cn(p,o,0),minutes:Cn(p,o+1,0),seconds:Cn(p,o+2,0),milliseconds:fs(p[o+3])},null,o+4]}function Hn(p,o){const f=!p[o]&&!p[o+1],y=Ar(p[o+1],p[o+2]),w=f?null:qe.instance(y);return[{},w,o+3]}function Un(p,o){const f=p[o]?ue.create(p[o]):null;return[{},f,o+1]}const Vc=RegExp(`^T?${gs.source}$`),Hc=/^-?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 Uc(p){const[o,f,y,w,E,A,L,P,ee]=p,xe=o[0]==="-",je=P&&P[0]==="-",He=(Se,it=!1)=>Se!==void 0&&(it||Se&&xe)?-Se:Se;return[{years:He(rn(f)),months:He(rn(y)),weeks:He(rn(w)),days:He(rn(E)),hours:He(rn(A)),minutes:He(rn(L)),seconds:He(rn(P),P==="-0"),milliseconds:He(fs(ee),je)}]}const Gc={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function xs(p,o,f,y,w,E,A){const L={year:o.length===2?ms(Xt(o)):Xt(o),month:Po.indexOf(f)+1,day:Xt(y),hour:Xt(w),minute:Xt(E)};return A&&(L.second=Xt(A)),p&&(L.weekday=p.length>3?zo.indexOf(p)+1:Wo.indexOf(p)+1),L}const Yc=/^(?:(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 Kc(p){const[,o,f,y,w,E,A,L,P,ee,xe,je]=p,He=xs(o,w,y,f,E,A,L);let Se;return P?Se=Gc[P]:ee?Se=0:Se=Ar(xe,je),[He,new qe(Se)]}function Qc(p){return p.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Zc=/^(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$/,Xc=/^(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$/,Jc=/^(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 Zo(p){const[,o,f,y,w,E,A,L]=p;return[xs(o,w,y,f,E,A,L),qe.utcInstance]}function eu(p){const[,o,f,y,w,E,A,L]=p;return[xs(o,L,f,y,w,E,A),qe.utcInstance]}const tu=wn(Lc,ys),nu=wn(Nc,ys),ru=wn(Pc,ys),su=wn(Ko),Xo=Sn(Bc,jn,Hn,Un),ou=Sn(_c,jn,Hn,Un),iu=Sn(zc,jn,Hn,Un),au=Sn(jn,Hn,Un);function lu(p){return kn(p,[tu,Xo],[nu,ou],[ru,iu],[su,au])}function cu(p){return kn(Qc(p),[Yc,Kc])}function uu(p){return kn(p,[Zc,Zo],[Xc,Zo],[Jc,eu])}function du(p){return kn(p,[Hc,Uc])}const hu=Sn(jn);function fu(p){return kn(p,[Vc,hu])}const pu=wn(Wc,qc),mu=wn(Qo),gu=Sn(jn,Hn,Un);function yu(p){return kn(p,[pu,Xo],[mu,gu])}const Jo="Invalid Duration",ei={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}},xu={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},...ei},Et=146097/400,Tn=146097/4800,vu={years:{quarters:4,months:12,weeks:Et/7,days:Et,hours:Et*24,minutes:Et*24*60,seconds:Et*24*60*60,milliseconds:Et*24*60*60*1e3},quarters:{months:3,weeks:Et/28,days:Et/4,hours:Et*24/4,minutes:Et*24*60/4,seconds:Et*24*60*60/4,milliseconds:Et*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},...ei},sn=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],bu=sn.slice(0).reverse();function Bt(p,o,f=!1){const y={values:f?o.values:{...p.values,...o.values||{}},loc:p.loc.clone(o.loc),conversionAccuracy:o.conversionAccuracy||p.conversionAccuracy,matrix:o.matrix||p.matrix};return new Ae(y)}function ti(p,o){var f;let y=(f=o.milliseconds)!=null?f:0;for(const w of bu.slice(1))o[w]&&(y+=o[w]*p[w].milliseconds);return y}function ni(p,o){const f=ti(p,o)<0?-1:1;sn.reduceRight((y,w)=>{if(te(o[w]))return y;if(y){const E=o[y]*f,A=p[w][y],L=Math.floor(E/A);o[w]+=L*f,o[y]-=L*A*f}return w},null),sn.reduce((y,w)=>{if(te(o[w]))return y;if(y){const E=o[y]%1;o[y]-=E,o[w]+=E*p[y][w]}return w},null)}function ri(p){const o={};for(const[f,y]of Object.entries(p))y!==0&&(o[f]=y);return o}class Ae{constructor(o){const f=o.conversionAccuracy==="longterm"||!1;let y=f?vu:xu;o.matrix&&(y=o.matrix),this.values=o.values,this.loc=o.loc||fe.create(),this.conversionAccuracy=f?"longterm":"casual",this.invalid=o.invalid||null,this.matrix=y,this.isLuxonDuration=!0}static fromMillis(o,f){return Ae.fromObject({milliseconds:o},f)}static fromObject(o,f={}){if(o==null||typeof o!="object")throw new a(`Duration.fromObject: argument expected to be an object, got ${o===null?"null":typeof o}`);return new Ae({values:Lr(o,Ae.normalizeUnit),loc:fe.fromObject(f),conversionAccuracy:f.conversionAccuracy,matrix:f.matrix})}static fromDurationLike(o){if(Ve(o))return Ae.fromMillis(o);if(Ae.isDuration(o))return o;if(typeof o=="object")return Ae.fromObject(o);throw new a(`Unknown duration argument ${o} of type ${typeof o}`)}static fromISO(o,f){const[y]=du(o);return y?Ae.fromObject(y,f):Ae.invalid("unparsable",`the input "${o}" can't be parsed as ISO 8601`)}static fromISOTime(o,f){const[y]=fu(o);return y?Ae.fromObject(y,f):Ae.invalid("unparsable",`the input "${o}" can't be parsed as ISO 8601`)}static invalid(o,f=null){if(!o)throw new a("need to specify a reason the Duration is invalid");const y=o instanceof dt?o:new dt(o,f);if(_e.throwOnInvalid)throw new s(y);return new Ae({invalid:y})}static normalizeUnit(o){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"}[o&&o.toLowerCase()];if(!f)throw new l(o);return f}static isDuration(o){return o&&o.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(o,f={}){const y={...f,floor:f.round!==!1&&f.floor!==!1};return this.isValid?pt.create(this.loc,y).formatDurationFromString(this,o):Jo}toHuman(o={}){if(!this.isValid)return Jo;const f=o.showZeros!==!1,y=sn.map(w=>{const E=this.values[w];return te(E)||E===0&&!f?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...o,unit:w.slice(0,-1)}).format(E)}).filter(w=>w);return this.loc.listFormatter({type:"conjunction",style:o.listStyle||"narrow",...o}).format(y)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let o="P";return this.years!==0&&(o+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(o+=this.months+this.quarters*3+"M"),this.weeks!==0&&(o+=this.weeks+"W"),this.days!==0&&(o+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(o+="T"),this.hours!==0&&(o+=this.hours+"H"),this.minutes!==0&&(o+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(o+=ps(this.seconds+this.milliseconds/1e3,3)+"S"),o==="P"&&(o+="T0S"),o}toISOTime(o={}){if(!this.isValid)return null;const f=this.toMillis();return f<0||f>=864e5?null:(o={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...o,includeOffset:!1},ke.fromMillis(f,{zone:"UTC"}).toISOTime(o))}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?ti(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(o){if(!this.isValid)return this;const f=Ae.fromDurationLike(o),y={};for(const w of sn)(gt(f.values,w)||gt(this.values,w))&&(y[w]=f.get(w)+this.get(w));return Bt(this,{values:y},!0)}minus(o){if(!this.isValid)return this;const f=Ae.fromDurationLike(o);return this.plus(f.negate())}mapUnits(o){if(!this.isValid)return this;const f={};for(const y of Object.keys(this.values))f[y]=No(o(this.values[y],y));return Bt(this,{values:f},!0)}get(o){return this[Ae.normalizeUnit(o)]}set(o){if(!this.isValid)return this;const f={...this.values,...Lr(o,Ae.normalizeUnit)};return Bt(this,{values:f})}reconfigure({locale:o,numberingSystem:f,conversionAccuracy:y,matrix:w}={}){const A={loc:this.loc.clone({locale:o,numberingSystem:f}),matrix:w,conversionAccuracy:y};return Bt(this,A)}as(o){return this.isValid?this.shiftTo(o).get(o):NaN}normalize(){if(!this.isValid)return this;const o=this.toObject();return ni(this.matrix,o),Bt(this,{values:o},!0)}rescale(){if(!this.isValid)return this;const o=ri(this.normalize().shiftToAll().toObject());return Bt(this,{values:o},!0)}shiftTo(...o){if(!this.isValid)return this;if(o.length===0)return this;o=o.map(A=>Ae.normalizeUnit(A));const f={},y={},w=this.toObject();let E;for(const A of sn)if(o.indexOf(A)>=0){E=A;let L=0;for(const ee in y)L+=this.matrix[ee][A]*y[ee],y[ee]=0;Ve(w[A])&&(L+=w[A]);const P=Math.trunc(L);f[A]=P,y[A]=(L*1e3-P*1e3)/1e3}else Ve(w[A])&&(y[A]=w[A]);for(const A in y)y[A]!==0&&(f[E]+=A===E?y[A]:y[A]/this.matrix[E][A]);return ni(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 o={};for(const f of Object.keys(this.values))o[f]=this.values[f]===0?0:-this.values[f];return Bt(this,{values:o},!0)}removeZeros(){if(!this.isValid)return this;const o=ri(this.values);return Bt(this,{values:o},!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(o){if(!this.isValid||!o.isValid||!this.loc.equals(o.loc))return!1;function f(y,w){return y===void 0||y===0?w===void 0||w===0:y===w}for(const y of sn)if(!f(this.values[y],o.values[y]))return!1;return!0}}const Mn="Invalid Interval";function wu(p,o){return!p||!p.isValid?et.invalid("missing or invalid start"):!o||!o.isValid?et.invalid("missing or invalid end"):o<p?et.invalid("end before start",`The end of an interval must be after its start, but you had start=${p.toISO()} and end=${o.toISO()}`):null}class et{constructor(o){this.s=o.start,this.e=o.end,this.invalid=o.invalid||null,this.isLuxonInterval=!0}static invalid(o,f=null){if(!o)throw new a("need to specify a reason the Interval is invalid");const y=o instanceof dt?o:new dt(o,f);if(_e.throwOnInvalid)throw new r(y);return new et({invalid:y})}static fromDateTimes(o,f){const y=Qn(o),w=Qn(f),E=wu(y,w);return E??new et({start:y,end:w})}static after(o,f){const y=Ae.fromDurationLike(f),w=Qn(o);return et.fromDateTimes(w,w.plus(y))}static before(o,f){const y=Ae.fromDurationLike(f),w=Qn(o);return et.fromDateTimes(w.minus(y),w)}static fromISO(o,f){const[y,w]=(o||"").split("/",2);if(y&&w){let E,A;try{E=ke.fromISO(y,f),A=E.isValid}catch{A=!1}let L,P;try{L=ke.fromISO(w,f),P=L.isValid}catch{P=!1}if(A&&P)return et.fromDateTimes(E,L);if(A){const ee=Ae.fromISO(w,f);if(ee.isValid)return et.after(E,ee)}else if(P){const ee=Ae.fromISO(y,f);if(ee.isValid)return et.before(L,ee)}}return et.invalid("unparsable",`the input "${o}" can't be parsed as ISO 8601`)}static isInterval(o){return o&&o.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(o="milliseconds"){return this.isValid?this.toDuration(o).get(o):NaN}count(o="milliseconds",f){if(!this.isValid)return NaN;const y=this.start.startOf(o,f);let w;return f!=null&&f.useLocaleWeeks?w=this.end.reconfigure({locale:y.locale}):w=this.end,w=w.startOf(o,f),Math.floor(w.diff(y,o).get(o))+(w.valueOf()!==this.end.valueOf())}hasSame(o){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,o):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(o){return this.isValid?this.s>o:!1}isBefore(o){return this.isValid?this.e<=o:!1}contains(o){return this.isValid?this.s<=o&&this.e>o:!1}set({start:o,end:f}={}){return this.isValid?et.fromDateTimes(o||this.s,f||this.e):this}splitAt(...o){if(!this.isValid)return[];const f=o.map(Qn).filter(A=>this.contains(A)).sort((A,L)=>A.toMillis()-L.toMillis()),y=[];let{s:w}=this,E=0;for(;w<this.e;){const A=f[E]||this.e,L=+A>+this.e?this.e:A;y.push(et.fromDateTimes(w,L)),w=L,E+=1}return y}splitBy(o){const f=Ae.fromDurationLike(o);if(!this.isValid||!f.isValid||f.as("milliseconds")===0)return[];let{s:y}=this,w=1,E;const A=[];for(;y<this.e;){const L=this.start.plus(f.mapUnits(P=>P*w));E=+L>+this.e?this.e:L,A.push(et.fromDateTimes(y,E)),y=E,w+=1}return A}divideEqually(o){return this.isValid?this.splitBy(this.length()/o).slice(0,o):[]}overlaps(o){return this.e>o.s&&this.s<o.e}abutsStart(o){return this.isValid?+this.e==+o.s:!1}abutsEnd(o){return this.isValid?+o.e==+this.s:!1}engulfs(o){return this.isValid?this.s<=o.s&&this.e>=o.e:!1}equals(o){return!this.isValid||!o.isValid?!1:this.s.equals(o.s)&&this.e.equals(o.e)}intersection(o){if(!this.isValid)return this;const f=this.s>o.s?this.s:o.s,y=this.e<o.e?this.e:o.e;return f>=y?null:et.fromDateTimes(f,y)}union(o){if(!this.isValid)return this;const f=this.s<o.s?this.s:o.s,y=this.e>o.e?this.e:o.e;return et.fromDateTimes(f,y)}static merge(o){const[f,y]=o.sort((w,E)=>w.s-E.s).reduce(([w,E],A)=>E?E.overlaps(A)||E.abutsStart(A)?[w,E.union(A)]:[w.concat([E]),A]:[w,A],[[],null]);return y&&f.push(y),f}static xor(o){let f=null,y=0;const w=[],E=o.map(P=>[{time:P.s,type:"s"},{time:P.e,type:"e"}]),A=Array.prototype.concat(...E),L=A.sort((P,ee)=>P.time-ee.time);for(const P of L)y+=P.type==="s"?1:-1,y===1?f=P.time:(f&&+f!=+P.time&&w.push(et.fromDateTimes(f,P.time)),f=null);return et.merge(w)}difference(...o){return et.xor([this].concat(o)).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(o=b,f={}){return this.isValid?pt.create(this.s.loc.clone(f),o).formatInterval(this):Mn}toISO(o){return this.isValid?`${this.s.toISO(o)}/${this.e.toISO(o)}`:Mn}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:Mn}toISOTime(o){return this.isValid?`${this.s.toISOTime(o)}/${this.e.toISOTime(o)}`:Mn}toFormat(o,{separator:f=" – "}={}){return this.isValid?`${this.s.toFormat(o)}${f}${this.e.toFormat(o)}`:Mn}toDuration(o,f){return this.isValid?this.e.diff(this.s,o,f):Ae.invalid(this.invalidReason)}mapEndpoints(o){return et.fromDateTimes(o(this.s),o(this.e))}}class Gn{static hasDST(o=_e.defaultZone){const f=ke.now().setZone(o).set({month:12});return!o.isUniversal&&f.offset!==f.set({month:6}).offset}static isValidIANAZone(o){return ue.isValidZone(o)}static normalizeZone(o){return ut(o,_e.defaultZone)}static getStartOfWeek({locale:o=null,locObj:f=null}={}){return(f||fe.create(o)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:o=null,locObj:f=null}={}){return(f||fe.create(o)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:o=null,locObj:f=null}={}){return(f||fe.create(o)).getWeekendDays().slice()}static months(o="long",{locale:f=null,numberingSystem:y=null,locObj:w=null,outputCalendar:E="gregory"}={}){return(w||fe.create(f,y,E)).months(o)}static monthsFormat(o="long",{locale:f=null,numberingSystem:y=null,locObj:w=null,outputCalendar:E="gregory"}={}){return(w||fe.create(f,y,E)).months(o,!0)}static weekdays(o="long",{locale:f=null,numberingSystem:y=null,locObj:w=null}={}){return(w||fe.create(f,y,null)).weekdays(o)}static weekdaysFormat(o="long",{locale:f=null,numberingSystem:y=null,locObj:w=null}={}){return(w||fe.create(f,y,null)).weekdays(o,!0)}static meridiems({locale:o=null}={}){return fe.create(o).meridiems()}static eras(o="short",{locale:f=null}={}){return fe.create(f,null,"gregory").eras(o)}static features(){return{relative:zn(),localeWeek:Wn()}}}function si(p,o){const f=w=>w.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),y=f(o)-f(p);return Math.floor(Ae.fromMillis(y).as("days"))}function Su(p,o,f){const y=[["years",(P,ee)=>ee.year-P.year],["quarters",(P,ee)=>ee.quarter-P.quarter+(ee.year-P.year)*4],["months",(P,ee)=>ee.month-P.month+(ee.year-P.year)*12],["weeks",(P,ee)=>{const xe=si(P,ee);return(xe-xe%7)/7}],["days",si]],w={},E=p;let A,L;for(const[P,ee]of y)f.indexOf(P)>=0&&(A=P,w[P]=ee(p,o),L=E.plus(w),L>o?(w[P]--,p=E.plus(w),p>o&&(L=p,w[P]--,p=E.plus(w))):p=L);return[p,w,L,A]}function ku(p,o,f,y){let[w,E,A,L]=Su(p,o,f);const P=o-w,ee=f.filter(je=>["hours","minutes","seconds","milliseconds"].indexOf(je)>=0);ee.length===0&&(A<o&&(A=w.plus({[L]:1})),A!==w&&(E[L]=(E[L]||0)+P/(A-w)));const xe=Ae.fromObject(E,y);return ee.length>0?Ae.fromMillis(P,y).shiftTo(...ee).plus(xe):xe}const Cu="missing Intl.DateTimeFormat.formatToParts support";function Pe(p,o=f=>f){return{regex:p,deser:([f])=>o(bt(f))}}const oi="[  ]",ii=new RegExp(oi,"g");function ju(p){return p.replace(/\./g,"\\.?").replace(ii,oi)}function ai(p){return p.replace(/\./g,"").replace(ii," ").toLowerCase()}function At(p,o){return p===null?null:{regex:RegExp(p.map(ju).join("|")),deser:([f])=>p.findIndex(y=>ai(f)===ai(y))+o}}function li(p,o){return{regex:p,deser:([,f,y])=>Ar(f,y),groups:o}}function Pr(p){return{regex:p,deser:([o])=>o}}function Tu(p){return p.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function Mu(p,o){const f=Ee(o),y=Ee(o,"{2}"),w=Ee(o,"{3}"),E=Ee(o,"{4}"),A=Ee(o,"{6}"),L=Ee(o,"{1,2}"),P=Ee(o,"{1,3}"),ee=Ee(o,"{1,6}"),xe=Ee(o,"{1,9}"),je=Ee(o,"{2,4}"),He=Ee(o,"{4,6}"),Se=Wt=>({regex:RegExp(Tu(Wt.val)),deser:([In])=>In,literal:!0}),Lt=(Wt=>{if(p.literal)return Se(Wt);switch(Wt.val){case"G":return At(o.eras("short"),0);case"GG":return At(o.eras("long"),0);case"y":return Pe(ee);case"yy":return Pe(je,ms);case"yyyy":return Pe(E);case"yyyyy":return Pe(He);case"yyyyyy":return Pe(A);case"M":return Pe(L);case"MM":return Pe(y);case"MMM":return At(o.months("short",!0),1);case"MMMM":return At(o.months("long",!0),1);case"L":return Pe(L);case"LL":return Pe(y);case"LLL":return At(o.months("short",!1),1);case"LLLL":return At(o.months("long",!1),1);case"d":return Pe(L);case"dd":return Pe(y);case"o":return Pe(P);case"ooo":return Pe(w);case"HH":return Pe(y);case"H":return Pe(L);case"hh":return Pe(y);case"h":return Pe(L);case"mm":return Pe(y);case"m":return Pe(L);case"q":return Pe(L);case"qq":return Pe(y);case"s":return Pe(L);case"ss":return Pe(y);case"S":return Pe(P);case"SSS":return Pe(w);case"u":return Pr(xe);case"uu":return Pr(L);case"uuu":return Pe(f);case"a":return At(o.meridiems(),0);case"kkkk":return Pe(E);case"kk":return Pe(je,ms);case"W":return Pe(L);case"WW":return Pe(y);case"E":case"c":return Pe(f);case"EEE":return At(o.weekdays("short",!1),1);case"EEEE":return At(o.weekdays("long",!1),1);case"ccc":return At(o.weekdays("short",!0),1);case"cccc":return At(o.weekdays("long",!0),1);case"Z":case"ZZ":return li(new RegExp(`([+-]${L.source})(?::(${y.source}))?`),2);case"ZZZ":return li(new RegExp(`([+-]${L.source})(${y.source})?`),2);case"z":return Pr(/[a-z_+-/]{1,256}?/i);case" ":return Pr(/[^\S\n\r]/);default:return Se(Wt)}})(p)||{invalidReason:Cu};return Lt.token=p,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 Iu(p,o,f){const{type:y,value:w}=p;if(y==="literal"){const P=/^\s+$/.test(w);return{literal:!P,val:P?" ":w}}const E=o[y];let A=y;y==="hour"&&(o.hour12!=null?A=o.hour12?"hour12":"hour24":o.hourCycle!=null?o.hourCycle==="h11"||o.hourCycle==="h12"?A="hour12":A="hour24":A=f.hour12?"hour12":"hour24");let L=Ou[A];if(typeof L=="object"&&(L=L[E]),L)return{literal:!1,val:L}}function Eu(p){return[`^${p.map(f=>f.regex).reduce((f,y)=>`${f}(${y.source})`,"")}$`,p]}function Du(p,o,f){const y=p.match(o);if(y){const w={};let E=1;for(const A in f)if(gt(f,A)){const L=f[A],P=L.groups?L.groups+1:1;!L.literal&&L.token&&(w[L.token.val[0]]=L.deser(y.slice(E,E+P))),E+=P}return[y,w]}else return[y,{}]}function Fu(p){const o=E=>{switch(E){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,y;return te(p.z)||(f=ue.create(p.z)),te(p.Z)||(f||(f=new qe(p.Z)),y=p.Z),te(p.q)||(p.M=(p.q-1)*3+1),te(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),te(p.u)||(p.S=fs(p.u)),[Object.keys(p).reduce((E,A)=>{const L=o(A);return L&&(E[L]=p[A]),E},{}),f,y]}let vs=null;function $u(){return vs||(vs=ke.fromMillis(1555555555555)),vs}function Ru(p,o){if(p.literal)return p;const f=pt.macroTokenToFormatOpts(p.val),y=hi(f,o);return y==null||y.includes(void 0)?p:y}function ci(p,o){return Array.prototype.concat(...p.map(f=>Ru(f,o)))}class ui{constructor(o,f){if(this.locale=o,this.format=f,this.tokens=ci(pt.parseFormat(f),o),this.units=this.tokens.map(y=>Mu(y,o)),this.disqualifyingUnit=this.units.find(y=>y.invalidReason),!this.disqualifyingUnit){const[y,w]=Eu(this.units);this.regex=RegExp(y,"i"),this.handlers=w}}explainFromTokens(o){if(this.isValid){const[f,y]=Du(o,this.regex,this.handlers),[w,E,A]=y?Fu(y):[null,null,void 0];if(gt(y,"a")&&gt(y,"H"))throw new i("Can't include meridiem when specifying 24-hour format");return{input:o,tokens:this.tokens,regex:this.regex,rawMatches:f,matches:y,result:w,zone:E,specificOffset:A}}else return{input:o,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function di(p,o,f){return new ui(p,f).explainFromTokens(o)}function Au(p,o,f){const{result:y,zone:w,specificOffset:E,invalidReason:A}=di(p,o,f);return[y,w,E,A]}function hi(p,o){if(!p)return null;const y=pt.create(o,p).dtFormatter($u()),w=y.formatToParts(),E=y.resolvedOptions();return w.map(A=>Iu(A,p,E))}const bs="Invalid DateTime",fi=864e13;function Yn(p){return new dt("unsupported zone",`the zone "${p.name}" is not supported`)}function ws(p){return p.weekData===null&&(p.weekData=Je(p.c)),p.weekData}function Ss(p){return p.localWeekData===null&&(p.localWeekData=Je(p.c,p.loc.getMinDaysInFirstWeek(),p.loc.getStartOfWeek())),p.localWeekData}function on(p,o){const f={ts:p.ts,zone:p.zone,c:p.c,o:p.o,loc:p.loc,invalid:p.invalid};return new ke({...f,...o,old:f})}function pi(p,o,f){let y=p-o*60*1e3;const w=f.offset(y);if(o===w)return[y,o];y-=(w-o)*60*1e3;const E=f.offset(y);return w===E?[y,w]:[p-Math.min(w,E)*60*1e3,Math.max(w,E)]}function _r(p,o){p+=o*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 zr(p,o,f){return pi(Rr(p),o,f)}function mi(p,o){const f=p.o,y=p.c.year+Math.trunc(o.years),w=p.c.month+Math.trunc(o.months)+Math.trunc(o.quarters)*3,E={...p.c,year:y,month:w,day:Math.min(p.c.day,$r(y,w))+Math.trunc(o.days)+Math.trunc(o.weeks)*7},A=Ae.fromObject({years:o.years-Math.trunc(o.years),quarters:o.quarters-Math.trunc(o.quarters),months:o.months-Math.trunc(o.months),weeks:o.weeks-Math.trunc(o.weeks),days:o.days-Math.trunc(o.days),hours:o.hours,minutes:o.minutes,seconds:o.seconds,milliseconds:o.milliseconds}).as("milliseconds"),L=Rr(E);let[P,ee]=pi(L,f,p.zone);return A!==0&&(P+=A,ee=p.zone.offset(P)),{ts:P,o:ee}}function On(p,o,f,y,w,E){const{setZone:A,zone:L}=f;if(p&&Object.keys(p).length!==0||o){const P=o||L,ee=ke.fromObject(p,{...f,zone:P,specificOffset:E});return A?ee:ee.setZone(L)}else return ke.invalid(new dt("unparsable",`the input "${w}" can't be parsed as ${y}`))}function Wr(p,o,f=!0){return p.isValid?pt.create(fe.create("en-US"),{allowZ:f,forceSimple:!0}).formatDateTimeFromString(p,o):null}function ks(p,o,f){const y=p.c.year>9999||p.c.year<0;let w="";if(y&&p.c.year>=0&&(w+="+"),w+=ot(p.c.year,y?6:4),f==="year")return w;if(o){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 gi(p,o,f,y,w,E,A){let L=!f||p.c.millisecond!==0||p.c.second!==0,P="";switch(A){case"day":case"month":case"year":break;default:if(P+=ot(p.c.hour),A==="hour")break;if(o){if(P+=":",P+=ot(p.c.minute),A==="minute")break;L&&(P+=":",P+=ot(p.c.second))}else{if(P+=ot(p.c.minute),A==="minute")break;L&&(P+=ot(p.c.second))}if(A==="second")break;L&&(!y||p.c.millisecond!==0)&&(P+=".",P+=ot(p.c.millisecond,3))}return w&&(p.isOffsetFixed&&p.offset===0&&!E?P+="Z":p.o<0?(P+="-",P+=ot(Math.trunc(-p.o/60)),P+=":",P+=ot(Math.trunc(-p.o%60))):(P+="+",P+=ot(Math.trunc(p.o/60)),P+=":",P+=ot(Math.trunc(p.o%60)))),E&&(P+="["+p.zone.ianaName+"]"),P}const yi={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},Lu={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},Nu={ordinal:1,hour:0,minute:0,second:0,millisecond:0},qr=["year","month","day","hour","minute","second","millisecond"],Pu=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],_u=["year","ordinal","hour","minute","second","millisecond"];function Br(p){const o={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(!o)throw new l(p);return o}function xi(p){switch(p.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return Br(p)}}function zu(p){if(Kn===void 0&&(Kn=_e.now()),p.type!=="iana")return p.offset(Kn);const o=p.name;let f=Cs.get(o);return f===void 0&&(f=p.offset(Kn),Cs.set(o,f)),f}function vi(p,o){const f=ut(o.zone,_e.defaultZone);if(!f.isValid)return ke.invalid(Yn(f));const y=fe.fromObject(o);let w,E;if(te(p.year))w=_e.now();else{for(const P of qr)te(p[P])&&(p[P]=yi[P]);const A=de(p)||ve(p);if(A)return ke.invalid(A);const L=zu(f);[w,E]=zr(p,L,f)}return new ke({ts:w,zone:f,loc:y,o:E})}function bi(p,o,f){const y=te(f.round)?!0:f.round,w=te(f.rounding)?"trunc":f.rounding,E=(L,P)=>(L=ps(L,y||f.calendary?0:2,f.calendary?"round":w),o.loc.clone(f).relFormatter(f).format(L,P)),A=L=>f.calendary?o.hasSame(p,L)?0:o.startOf(L).diff(p.startOf(L),L).get(L):o.diff(p,L).get(L);if(f.unit)return E(A(f.unit),f.unit);for(const L of f.units){const P=A(L);if(Math.abs(P)>=1)return E(P,L)}return E(p>o?-0:0,f.units[f.units.length-1])}function wi(p){let o={},f;return p.length>0&&typeof p[p.length-1]=="object"?(o=p[p.length-1],f=Array.from(p).slice(0,p.length-1)):f=Array.from(p),[o,f]}let Kn;const Cs=new Map;class ke{constructor(o){const f=o.zone||_e.defaultZone;let y=o.invalid||(Number.isNaN(o.ts)?new dt("invalid input"):null)||(f.isValid?null:Yn(f));this.ts=te(o.ts)?_e.now():o.ts;let w=null,E=null;if(!y)if(o.old&&o.old.ts===this.ts&&o.old.zone.equals(f))[w,E]=[o.old.c,o.old.o];else{const L=Ve(o.o)&&!o.old?o.o:f.offset(this.ts);w=_r(this.ts,L),y=Number.isNaN(w.year)?new dt("invalid input"):null,w=y?null:w,E=y?null:L}this._zone=f,this.loc=o.loc||fe.create(),this.invalid=y,this.weekData=null,this.localWeekData=null,this.c=w,this.o=E,this.isLuxonDateTime=!0}static now(){return new ke({})}static local(){const[o,f]=wi(arguments),[y,w,E,A,L,P,ee]=f;return vi({year:y,month:w,day:E,hour:A,minute:L,second:P,millisecond:ee},o)}static utc(){const[o,f]=wi(arguments),[y,w,E,A,L,P,ee]=f;return o.zone=qe.utcInstance,vi({year:y,month:w,day:E,hour:A,minute:L,second:P,millisecond:ee},o)}static fromJSDate(o,f={}){const y=vn(o)?o.valueOf():NaN;if(Number.isNaN(y))return ke.invalid("invalid input");const w=ut(f.zone,_e.defaultZone);return w.isValid?new ke({ts:y,zone:w,loc:fe.fromObject(f)}):ke.invalid(Yn(w))}static fromMillis(o,f={}){if(Ve(o))return o<-fi||o>fi?ke.invalid("Timestamp out of range"):new ke({ts:o,zone:ut(f.zone,_e.defaultZone),loc:fe.fromObject(f)});throw new a(`fromMillis requires a numerical input, but received a ${typeof o} with value ${o}`)}static fromSeconds(o,f={}){if(Ve(o))return new ke({ts:o*1e3,zone:ut(f.zone,_e.defaultZone),loc:fe.fromObject(f)});throw new a("fromSeconds requires a numerical input")}static fromObject(o,f={}){o=o||{};const y=ut(f.zone,_e.defaultZone);if(!y.isValid)return ke.invalid(Yn(y));const w=fe.fromObject(f),E=Lr(o,xi),{minDaysInFirstWeek:A,startOfWeek:L}=nn(E,w),P=_e.now(),ee=te(f.specificOffset)?y.offset(P):f.specificOffset,xe=!te(E.ordinal),je=!te(E.year),He=!te(E.month)||!te(E.day),Se=je||He,it=E.weekYear||E.weekNumber;if((Se||xe)&&it)throw new i("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(He&&xe)throw new i("Can't mix ordinal dates with month/day");const Lt=it||E.weekday&&!Se;let Wt,In,Zn=_r(P,ee);Lt?(Wt=Pu,In=Lu,Zn=Je(Zn,A,L)):xe?(Wt=_u,In=Nu,Zn=tn(Zn)):(Wt=qr,In=yi);let Si=!1;for(const Jn of Wt){const Uu=E[Jn];te(Uu)?Si?E[Jn]=In[Jn]:E[Jn]=Zn[Jn]:Si=!0}const qu=Lt?U(E,A,L):xe?V(E):de(E),ki=qu||ve(E);if(ki)return ke.invalid(ki);const Bu=Lt?Rt(E,A,L):xe?Zt(E):E,[Vu,Hu]=zr(Bu,ee,y),Xn=new ke({ts:Vu,zone:y,o:Hu,loc:w});return E.weekday&&Se&&o.weekday!==Xn.weekday?ke.invalid("mismatched weekday",`you can't specify both a weekday of ${E.weekday} and a date of ${Xn.toISO()}`):Xn.isValid?Xn:ke.invalid(Xn.invalid)}static fromISO(o,f={}){const[y,w]=lu(o);return On(y,w,f,"ISO 8601",o)}static fromRFC2822(o,f={}){const[y,w]=cu(o);return On(y,w,f,"RFC 2822",o)}static fromHTTP(o,f={}){const[y,w]=uu(o);return On(y,w,f,"HTTP",f)}static fromFormat(o,f,y={}){if(te(o)||te(f))throw new a("fromFormat requires an input string and a format");const{locale:w=null,numberingSystem:E=null}=y,A=fe.fromOpts({locale:w,numberingSystem:E,defaultToEN:!0}),[L,P,ee,xe]=Au(A,o,f);return xe?ke.invalid(xe):On(L,P,y,`format ${f}`,o,ee)}static fromString(o,f,y={}){return ke.fromFormat(o,f,y)}static fromSQL(o,f={}){const[y,w]=yu(o);return On(y,w,f,"SQL",o)}static invalid(o,f=null){if(!o)throw new a("need to specify a reason the DateTime is invalid");const y=o instanceof dt?o:new dt(o,f);if(_e.throwOnInvalid)throw new n(y);return new ke({invalid:y})}static isDateTime(o){return o&&o.isLuxonDateTime||!1}static parseFormatForOpts(o,f={}){const y=hi(o,fe.fromObject(f));return y?y.map(w=>w?w.val:null).join(""):null}static expandFormat(o,f={}){return ci(pt.parseFormat(o),fe.fromObject(f)).map(w=>w.val).join("")}static resetCache(){Kn=void 0,Cs.clear()}get(o){return this[o]}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?ws(this).weekYear:NaN}get weekNumber(){return this.isValid?ws(this).weekNumber:NaN}get weekday(){return this.isValid?ws(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?Ss(this).weekday:NaN}get localWeekNumber(){return this.isValid?Ss(this).weekNumber:NaN}get localWeekYear(){return this.isValid?Ss(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 o=864e5,f=6e4,y=Rr(this.c),w=this.zone.offset(y-o),E=this.zone.offset(y+o),A=this.zone.offset(y-w*f),L=this.zone.offset(y-E*f);if(A===L)return[this];const P=y-A*f,ee=y-L*f,xe=_r(P,A),je=_r(ee,L);return xe.hour===je.hour&&xe.minute===je.minute&&xe.second===je.second&&xe.millisecond===je.millisecond?[on(this,{ts:P}),on(this,{ts:ee})]:[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(o={}){const{locale:f,numberingSystem:y,calendar:w}=pt.create(this.loc.clone(o),o).resolvedOptions(this);return{locale:f,numberingSystem:y,outputCalendar:w}}toUTC(o=0,f={}){return this.setZone(qe.instance(o),f)}toLocal(){return this.setZone(_e.defaultZone)}setZone(o,{keepLocalTime:f=!1,keepCalendarTime:y=!1}={}){if(o=ut(o,_e.defaultZone),o.equals(this.zone))return this;if(o.isValid){let w=this.ts;if(f||y){const E=o.offset(this.ts),A=this.toObject();[w]=zr(A,E,o)}return on(this,{ts:w,zone:o})}else return ke.invalid(Yn(o))}reconfigure({locale:o,numberingSystem:f,outputCalendar:y}={}){const w=this.loc.clone({locale:o,numberingSystem:f,outputCalendar:y});return on(this,{loc:w})}setLocale(o){return this.reconfigure({locale:o})}set(o){if(!this.isValid)return this;const f=Lr(o,xi),{minDaysInFirstWeek:y,startOfWeek:w}=nn(f,this.loc),E=!te(f.weekYear)||!te(f.weekNumber)||!te(f.weekday),A=!te(f.ordinal),L=!te(f.year),P=!te(f.month)||!te(f.day),ee=L||P,xe=f.weekYear||f.weekNumber;if((ee||A)&&xe)throw new i("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(P&&A)throw new i("Can't mix ordinal dates with month/day");let je;E?je=Rt({...Je(this.c,y,w),...f},y,w):te(f.ordinal)?(je={...this.toObject(),...f},te(f.day)&&(je.day=Math.min($r(je.year,je.month),je.day))):je=Zt({...tn(this.c),...f});const[He,Se]=zr(je,this.o,this.zone);return on(this,{ts:He,o:Se})}plus(o){if(!this.isValid)return this;const f=Ae.fromDurationLike(o);return on(this,mi(this,f))}minus(o){if(!this.isValid)return this;const f=Ae.fromDurationLike(o).negate();return on(this,mi(this,f))}startOf(o,{useLocaleWeeks:f=!1}={}){if(!this.isValid)return this;const y={},w=Ae.normalizeUnit(o);switch(w){case"years":y.month=1;case"quarters":case"months":y.day=1;case"weeks":case"days":y.hour=0;case"hours":y.minute=0;case"minutes":y.second=0;case"seconds":y.millisecond=0;break}if(w==="weeks")if(f){const E=this.loc.getStartOfWeek(),{weekday:A}=this;A<E&&(y.weekNumber=this.weekNumber-1),y.weekday=E}else y.weekday=1;if(w==="quarters"){const E=Math.ceil(this.month/3);y.month=(E-1)*3+1}return this.set(y)}endOf(o,f){return this.isValid?this.plus({[o]:1}).startOf(o,f).minus(1):this}toFormat(o,f={}){return this.isValid?pt.create(this.loc.redefaultToEN(f)).formatDateTimeFromString(this,o):bs}toLocaleString(o=b,f={}){return this.isValid?pt.create(this.loc.clone(f),o).formatDateTime(this):bs}toLocaleParts(o={}){return this.isValid?pt.create(this.loc.clone(o),o).formatDateTimeParts(this):[]}toISO({format:o="extended",suppressSeconds:f=!1,suppressMilliseconds:y=!1,includeOffset:w=!0,extendedZone:E=!1,precision:A="milliseconds"}={}){if(!this.isValid)return null;A=Br(A);const L=o==="extended";let P=ks(this,L,A);return qr.indexOf(A)>=3&&(P+="T"),P+=gi(this,L,f,y,w,E,A),P}toISODate({format:o="extended",precision:f="day"}={}){return this.isValid?ks(this,o==="extended",Br(f)):null}toISOWeekDate(){return Wr(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:o=!1,suppressSeconds:f=!1,includeOffset:y=!0,includePrefix:w=!1,extendedZone:E=!1,format:A="extended",precision:L="milliseconds"}={}){return this.isValid?(L=Br(L),(w&&qr.indexOf(L)>=3?"T":"")+gi(this,A==="extended",f,o,y,E,L)):null}toRFC2822(){return Wr(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return Wr(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?ks(this,!0):null}toSQLTime({includeOffset:o=!0,includeZone:f=!1,includeOffsetSpace:y=!0}={}){let w="HH:mm:ss.SSS";return(f||o)&&(y&&(w+=" "),f?w+="z":o&&(w+="ZZ")),Wr(this,w,!0)}toSQL(o={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(o)}`:null}toString(){return this.isValid?this.toISO():bs}[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(o={}){if(!this.isValid)return{};const f={...this.c};return o.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(o,f="milliseconds",y={}){if(!this.isValid||!o.isValid)return Ae.invalid("created by diffing an invalid DateTime");const w={locale:this.locale,numberingSystem:this.numberingSystem,...y},E=Fr(f).map(Ae.normalizeUnit),A=o.valueOf()>this.valueOf(),L=A?this:o,P=A?o:this,ee=ku(L,P,E,w);return A?ee.negate():ee}diffNow(o="milliseconds",f={}){return this.diff(ke.now(),o,f)}until(o){return this.isValid?et.fromDateTimes(this,o):this}hasSame(o,f,y){if(!this.isValid)return!1;const w=o.valueOf(),E=this.setZone(o.zone,{keepLocalTime:!0});return E.startOf(f,y)<=w&&w<=E.endOf(f,y)}equals(o){return this.isValid&&o.isValid&&this.valueOf()===o.valueOf()&&this.zone.equals(o.zone)&&this.loc.equals(o.loc)}toRelative(o={}){if(!this.isValid)return null;const f=o.base||ke.fromObject({},{zone:this.zone}),y=o.padding?this<f?-o.padding:o.padding:0;let w=["years","months","days","hours","minutes","seconds"],E=o.unit;return Array.isArray(o.unit)&&(w=o.unit,E=void 0),bi(f,this.plus(y),{...o,numeric:"always",units:w,unit:E})}toRelativeCalendar(o={}){return this.isValid?bi(o.base||ke.fromObject({},{zone:this.zone}),this,{...o,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...o){if(!o.every(ke.isDateTime))throw new a("min requires all arguments be DateTimes");return $e(o,f=>f.valueOf(),Math.min)}static max(...o){if(!o.every(ke.isDateTime))throw new a("max requires all arguments be DateTimes");return $e(o,f=>f.valueOf(),Math.max)}static fromFormatExplain(o,f,y={}){const{locale:w=null,numberingSystem:E=null}=y,A=fe.fromOpts({locale:w,numberingSystem:E,defaultToEN:!0});return di(A,o,f)}static fromStringExplain(o,f,y={}){return ke.fromFormatExplain(o,f,y)}static buildFormatParser(o,f={}){const{locale:y=null,numberingSystem:w=null}=f,E=fe.fromOpts({locale:y,numberingSystem:w,defaultToEN:!0});return new ui(E,o)}static fromFormatParser(o,f,y={}){if(te(o)||te(f))throw new a("fromFormatParser requires an input string and a format parser");const{locale:w=null,numberingSystem:E=null}=y,A=fe.fromOpts({locale:w,numberingSystem:E,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:P,specificOffset:ee,invalidReason:xe}=f.explainFromTokens(o);return xe?ke.invalid(xe):On(L,P,y,`format ${f.format}`,o,ee)}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 C}static get DATE_HUGE(){return k}static get TIME_SIMPLE(){return S}static get TIME_WITH_SECONDS(){return T}static get TIME_WITH_SHORT_OFFSET(){return M}static get TIME_WITH_LONG_OFFSET(){return O}static get TIME_24_SIMPLE(){return I}static get TIME_24_WITH_SECONDS(){return R}static get TIME_24_WITH_SHORT_OFFSET(){return _}static get TIME_24_WITH_LONG_OFFSET(){return $}static get DATETIME_SHORT(){return B}static get DATETIME_SHORT_WITH_SECONDS(){return F}static get DATETIME_MED(){return N}static get DATETIME_MED_WITH_SECONDS(){return H}static get DATETIME_MED_WITH_WEEKDAY(){return D}static get DATETIME_FULL(){return W}static get DATETIME_FULL_WITH_SECONDS(){return K}static get DATETIME_HUGE(){return J}static get DATETIME_HUGE_WITH_SECONDS(){return X}}function Qn(p){if(ke.isDateTime(p))return p;if(p&&p.valueOf&&Ve(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 Wu="3.7.2";return wt.DateTime=ke,wt.Duration=Ae,wt.FixedOffsetZone=qe,wt.IANAZone=ue,wt.Info=Gn,wt.Interval=et,wt.InvalidZone=ct,wt.Settings=_e,wt.SystemZone=ie,wt.VERSION=Wu,wt.Zone=G,wt}var ea;function uo(){return ea||(ea=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CronDate=e.DAYS_IN_MONTH=e.DateMathOp=e.TimeUnit=void 0;const n=xf();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 s;(function(l){l.Add="Add",l.Subtract="Subtract"})(s||(e.DateMathOp=s={})),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,d){const u={zone:d};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,u):typeof a=="number"?this.#e=n.DateTime.fromMillis(a,u):(this.#e=n.DateTime.fromISO(a,u),this.#e.isValid||(this.#e=n.DateTime.fromRFC2822(a,u)),this.#e.isValid||(this.#e=n.DateTime.fromSQL(a,u)),this.#e.isValid||(this.#e=n.DateTime.fromFormat(a,"EEE, d MMM yyyy HH:mm:ss",u))):this.#e=n.DateTime.local(),!this.#e.isValid)throw new Error(`CronDate: unhandled timestamp: ${a}`);d&&d!==this.#e.zoneName&&(this.#e=this.#e.setZone(d))}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,d){if(a===s.Add){this.addUnit(d);return}if(a===s.Subtract){this.subtractUnit(d);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:d}=this.#e;if(d===2){const u=i.#s(this.#e.year);return a===e.DAYS_IN_MONTH[d-1]-(u?0:1)}return a===e.DAYS_IN_MONTH[d-1]}isLastWeekdayOfMonth(){const{day:a,month:d}=this.#e;let u;return d===2?u=e.DAYS_IN_MONTH[d-1]-(i.#s(this.#e.year)?0:1):u=e.DAYS_IN_MONTH[d-1],a>u-7}applyDateOperation(a,d,u){if(d===r.Month||d===r.Day){this.invokeDateOperation(a,d);return}const h=this.getHours();this.invokeDateOperation(a,d);const g=this.getHours(),b=g-h;b===2?u!==24&&(this.dstStart=h+1):b===0&&this.getMinutes()===0&&this.getSeconds()===0&&u!==24&&(this.dstEnd=g)}#r(){return this.#e.toUTC()}}e.CronDate=i,e.default=i})(Es)),Es}var ta;function vf(){if(ta)return ar;ta=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.CronMonth=void 0;const e=uo(),n=pn(),r=1,s=12,i=Object.freeze([]);let l=class extends n.CronField{static get min(){return r}static get max(){return s}static get chars(){return i}static get daysInMonth(){return e.DAYS_IN_MONTH}constructor(d,u){super(d,u),this.validate()}get values(){return super.values}};return ar.CronMonth=l,ar}var lr={},na;function bf(){if(na)return lr;na=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.CronSecond=void 0;const e=pn(),n=0,r=59,s=Object.freeze([]);let i=class extends e.CronField{static get min(){return n}static get max(){return r}static get chars(){return s}constructor(a,d){super(a,d),this.validate()}get values(){return super.values}};return lr.CronSecond=i,lr}var ra;function ho(){return ra||(ra=1,(function(e){var n=ln&&ln.__createBinding||(Object.create?(function(s,i,l,a){a===void 0&&(a=l);var d=Object.getOwnPropertyDescriptor(i,l);(!d||("get"in d?!i.__esModule:d.writable||d.configurable))&&(d={enumerable:!0,get:function(){return i[l]}}),Object.defineProperty(s,a,d)}):(function(s,i,l,a){a===void 0&&(a=l),s[a]=i[l]})),r=ln&&ln.__exportStar||function(s,i){for(var l in s)l!=="default"&&!Object.prototype.hasOwnProperty.call(i,l)&&n(i,s,l)};Object.defineProperty(e,"__esModule",{value:!0}),r(ff(),e),r(pf(),e),r(mf(),e),r(pn(),e),r(gf(),e),r(yf(),e),r(vf(),e),r(bf(),e)})(ln)),ln}var sa;function cl(){if(sa)return tr;sa=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.CronFieldCollection=void 0;const e=ho();let n=class gr{#e;#n;#o;#s;#r;#t;static from(s,i){return new gr({second:this.resolveField(e.CronSecond,s.second,i.second),minute:this.resolveField(e.CronMinute,s.minute,i.minute),hour:this.resolveField(e.CronHour,s.hour,i.hour),dayOfMonth:this.resolveField(e.CronDayOfMonth,s.dayOfMonth,i.dayOfMonth),month:this.resolveField(e.CronMonth,s.month,i.month),dayOfWeek:this.resolveField(e.CronDayOfWeek,s.dayOfWeek,i.dayOfWeek)})}static resolveField(s,i,l){return l?l instanceof e.CronField?l:new s(l):i}constructor({second:s,minute:i,hour:l,dayOfMonth:a,month:d,dayOfWeek:u}){if(!s)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(!d)throw new Error("Validation error, Field month is missing");if(!u)throw new Error("Validation error, Field dayOfWeek is missing");if(d.values.length===1&&!a.hasLastChar&&u.isWildcard&&!(parseInt(a.values[0],10)<=e.CronMonth.daysInMonth[d.values[0]-1]))throw new Error("Invalid explicit day of month definition");this.#e=s,this.#n=i,this.#o=l,this.#r=d,this.#t=u,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(s){if(s.length===0)return[];const i=[];let l;return s.forEach((a,d,u)=>{if(l===void 0){l={start:a,count:1};return}const h=u[d-1]||l.start,g=u[d+1];if(a==="L"||a==="W"){i.push(l),i.push({start:a,count:1}),l=void 0;return}if(l.step===void 0&&g!==void 0){const b=a-h,x=g-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(s,i,l){const a=i.step;return a?a===1&&i.start===s.min&&i.end&&i.end>=l?s.hasQuestionMarkChar?"?":"*":a!==1&&i.start===s.min&&i.end&&i.end>=l-a+1?`*/${a}`:null:null}static#l(s,i){const l=s.step;if(l===1)return`${s.start}-${s.end}`;const a=s.start===0?s.count-1:s.count;if(!l)throw new Error("Unexpected range step");if(!s.end)throw new Error("Unexpected range end");if(l*a>s.end){const d=(h,g)=>{if(typeof s.start!="number")throw new Error("Unexpected range start");return g%l===0?s.start+g:null};if(typeof s.start!="number")throw new Error("Unexpected range start");const u={length:s.end-s.start+1};return Array.from(u,d).filter(h=>h!==null).join(",")}return s.end===i-l+1?`${s.start}/${l}`:`${s.start}-${s.end}/${l}`}stringifyField(s){let i=s.max,l=s.values;if(s instanceof e.CronDayOfWeek){i=6;const d=this.#t.values;l=d[d.length-1]===7?d.slice(0,-1):d}s instanceof e.CronDayOfMonth&&(i=this.#r.values.length===1?e.CronMonth.daysInMonth[this.#r.values[0]-1]:s.max);const a=gr.compactField(l);if(a.length===1){const d=gr.#c(s,a[0],i);if(d)return d}return a.map(d=>{const u=d.count===1?d.start.toString():gr.#l(d,i);return s instanceof e.CronDayOfWeek&&s.nthDay>0?`${u}#${s.nthDay}`:u}).join(",")}stringify(s=!1){const i=[];return s&&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 Ds={},oa;function ul(){return oa||(oa=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=uo();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 s{#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 d=a.currentDate??a.startDate;if(d){const u=new n.CronDate(d,this.#n);this.#s&&u.getTime()<this.#s.getTime()?d=this.#s:this.#r&&u.getTime()>this.#r.getTime()&&(d=this.#r)}this.#o=new n.CronDate(d,this.#n),this.#t=l}get fields(){return this.#t}static fieldsToExpression(l,a){return new s(l,a||{})}static#i(l,a){return a.some(d=>d===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 d=new n.CronDate(l);d.setStartOfDay();const u=new n.CronDate(l);return u.setEndOfDay(),this.#c=a,this.#l=d.getUTCOffset()!==u.getUTCOffset(),this.#l}#h(l,a,d){const u=this.#t.second.values,h=l.getSeconds(),g=this.#t.second.findNearestValue(h,d);if(g!==null){l.setSeconds(g);return}l.applyDateOperation(a,n.TimeUnit.Minute,this.#t.hour.values.length),l.setSeconds(this.#a(u,d))}#p(l,a,d){const u=this.#t.minute.values,h=this.#t.second.values,g=l.getMinutes(),b=this.#t.minute.findNearestValue(g,d);if(b!==null){l.setMinutes(b),l.setSeconds(this.#a(h,d));return}l.applyDateOperation(a,n.TimeUnit.Hour,this.#t.hour.values.length),l.setMinutes(this.#a(u,d)),l.setSeconds(this.#a(h,d))}static#m(l,a){const d=a.isLastWeekdayOfMonth();return l.some(u=>{const h=parseInt(u.toString().charAt(0),10)%7;if(Number.isNaN(h))throw new Error(`Invalid last weekday of the month expression: ${u}`);return a.getDay()===h&&d})}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 d=0;d<l;d++)try{a.push(this.next())}catch{return a}else for(let d=0;d>l;d--)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:d,hour:u,month:h}=this.#t,g=new n.CronDate(l,this.#n);return!(!a.values.includes(g.getSeconds())||!d.values.includes(g.getMinutes())||!u.values.includes(g.getHours())||!h.values.includes(g.getMonth()+1)||!this.#f(g)||this.#t.dayOfWeek.nthDay>0&&Math.ceil(g.getDate()/7)!==this.#t.dayOfWeek.nthDay)}toString(){return this.#e.expression||this.stringify(!0)}#f(l){const a=this.#t.dayOfMonth.isWildcard,d=!a,u=this.#t.dayOfWeek.isWildcard,h=!u,g=s.#i(l.getDate(),this.#t.dayOfMonth.values)||this.#t.dayOfMonth.hasLastChar&&l.isLastDayOfMonth(),b=s.#i(l.getDay(),this.#t.dayOfWeek.values)||this.#t.dayOfWeek.hasLastChar&&s.#m(this.#t.dayOfWeek.values,l);return!!(d&&h&&(g||b)||g&&!h||a&&!u&&b)}#g(l,a,d){const u=this.#t.hour.values,h=u,g=l.getHours(),b=s.#i(g,u),x=l.dstEnd===g;if(l.dstStart!==null&&l.dstStart===g-1&&s.#i(l.dstStart,u))return!0;if(x&&!d)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(g,d);if(v===null)return l.applyDateOperation(a,n.TimeUnit.Day,h.length),!1;if(this.#d(l)){const C=d?g-v:v-g;for(let k=0;k<C&&(l.applyDateOperation(a,n.TimeUnit.Hour,h.length),!(!d&&l.getHours()>=v||d&&l.getHours()<=v));k++);}else l.setHours(v);return l.setMinutes(this.#a(this.#t.minute.values,d)),l.setSeconds(this.#a(this.#t.second.values,d)),!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,d=new n.CronDate(this.#o),u=d.getTime();let h=0;for(;++h<r;){if(this.#y(d),!this.#f(d)){d.applyDateOperation(a,n.TimeUnit.Day,this.#t.hour.values.length);continue}if(!(this.#t.dayOfWeek.nthDay<=0||Math.ceil(d.getDate()/7)===this.#t.dayOfWeek.nthDay)){d.applyDateOperation(a,n.TimeUnit.Day,this.#t.hour.values.length);continue}if(!s.#i(d.getMonth()+1,this.#t.month.values)){d.applyDateOperation(a,n.TimeUnit.Month,this.#t.hour.values.length);continue}if(this.#g(d,a,l)){if(!s.#i(d.getMinutes(),this.#t.minute.values)){this.#p(d,a,l);continue}if(!s.#i(d.getSeconds(),this.#t.second.values)){this.#h(d,a,l);continue}if(u===d.getTime()){(a==="Add"||d.getMilliseconds()===0)&&d.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 d.getMilliseconds()!==0&&d.setMilliseconds(0),this.#o=d,d}[Symbol.iterator](){return{next:()=>{try{return{value:this.#u(),done:!1}}catch{return{value:void 0,done:!0}}}}}}e.CronExpression=s,e.default=s})(Ds)),Ds}var Vr={},ia;function wf(){if(ia)return Vr;ia=1,Object.defineProperty(Vr,"__esModule",{value:!0}),Vr.seededRandom=r;function e(s){let i=2166136261;for(let l=0;l<s.length;l++)i^=s.charCodeAt(l),i=Math.imul(i,16777619);return()=>i>>>0}function n(s){return()=>{let i=s+=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(s){const i=s?e(s)():Math.floor(Math.random()*1e10);return n(i)}return Vr}var aa;function Xs(){if(aa)return jt;aa=1,Object.defineProperty(jt,"__esModule",{value:!0}),jt.CronExpressionParser=jt.DayOfWeek=jt.Months=jt.CronUnit=jt.PredefinedExpressions=void 0;const e=cl(),n=ul(),r=wf(),s=ho();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 d;(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"})(d||(jt.DayOfWeek=d={}));let u=class Tt{static parse(g,b={}){const{strict:x=!1,hashSeed:v}=b,C=(0,r.seededRandom)(v);g=i[g]||g;const k=Tt.#e(g,x);if(!(k.dayOfMonth==="*"||k.dayOfWeek==="*"||!x))throw new Error("Cannot use both dayOfMonth and dayOfWeek together in strict mode!");const S=Tt.#n(l.Second,k.second,s.CronSecond.constraints,C),T=Tt.#n(l.Minute,k.minute,s.CronMinute.constraints,C),M=Tt.#n(l.Hour,k.hour,s.CronHour.constraints,C),O=Tt.#n(l.Month,k.month,s.CronMonth.constraints,C),I=Tt.#n(l.DayOfMonth,k.dayOfMonth,s.CronDayOfMonth.constraints,C),{dayOfWeek:R,nthDayOfWeek:_}=Tt.#d(k.dayOfWeek),$=Tt.#n(l.DayOfWeek,R,s.CronDayOfWeek.constraints,C),B=new e.CronFieldCollection({second:new s.CronSecond(S,{rawValue:k.second}),minute:new s.CronMinute(T,{rawValue:k.minute}),hour:new s.CronHour(M,{rawValue:k.hour}),dayOfMonth:new s.CronDayOfMonth(I,{rawValue:k.dayOfMonth}),month:new s.CronMonth(O,{rawValue:k.month}),dayOfWeek:new s.CronDayOfWeek($,{rawValue:k.dayOfWeek,nthDayOfWeek:_})});return new n.CronExpression(B,{...b,expression:g})}static#e(g,b){if(b&&!g.length)throw new Error("Invalid cron expression");g=g||"0 * * * * *";const x=g.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[C,k,S,T,M,O]=x;return{second:C,minute:k,hour:S,dayOfMonth:T,month:M,dayOfWeek:O}}static#n(g,b,x,v){if((g===l.Month||g===l.DayOfWeek)&&(b=b.replace(/[a-z]{3}/gi,C=>{C=C.toLowerCase();const k=a[C]||d[C];if(k===void 0)throw new Error(`Validation error, cannot resolve alias "${C}"`);return k.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(g,b,x)}static#o(g,b){return g.replace(/[*?]/g,b.min+"-"+b.max)}static#s(g,b,x){const v=x();return g.replace(/H(?:\((\d+)-(\d+)\))?(?:\/(\d+))?/g,(C,k,S,T)=>{if(k&&S&&T){const M=parseInt(k,10),O=parseInt(S,10),I=parseInt(T,10);if(M>O)throw new Error(`Invalid range: ${M}-${O}, min > max`);if(I<=0)throw new Error(`Invalid step: ${I}, must be positive`);const R=Math.max(M,b.min),_=Math.floor(v*I),$=[];for(let B=Math.floor(R/I)*I+_;B<=O;B+=I)B>=R&&$.push(B);return $.join(",")}else if(k&&S){const M=parseInt(k,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(T){const M=parseInt(T,10);if(M<=0)throw new Error(`Invalid step: ${M}, must be positive`);const O=Math.floor(v*M),I=[];for(let R=Math.floor(b.min/M)*M+O;R<=b.max;R+=M)R>=b.min&&I.push(R);return I.join(",")}else return String(Math.floor(v*(b.max-b.min+1)+b.min))})}static#r(g,b,x){const v=[];function C(S,T){if(Array.isArray(S))v.push(...S);else if(Tt.#h(T,S))v.push(S);else{const M=parseInt(S.toString(),10);if(!(M>=T.min&&M<=T.max))throw new Error(`Constraint error, got value ${S} expected range ${T.min}-${T.max}`);v.push(g===l.DayOfWeek?M%7:S)}}return b.split(",").forEach(S=>{if(!(S.length>0))throw new Error("Invalid list value format");C(Tt.#t(g,S,x),x)}),v}static#t(g,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(g,v[0],parseInt(v[1],10),x)):Tt.#a(g,b,1,x)}static#c(g,b,x){if(!(!isNaN(g)&&!isNaN(b)&&g>=x.min&&b<=x.max))throw new Error(`Constraint error, got range ${g}-${b} expected range ${x.min}-${x.max}`);if(g>b)throw new Error(`Invalid range: ${g}-${b}, min(${g}) > max(${b})`)}static#l(g){if(!(!isNaN(g)&&g>0))throw new Error(`Constraint error, cannot repeat at every ${g} time.`)}static#i(g,b,x,v){const C=[];g===l.DayOfWeek&&x%7===0&&C.push(0);for(let k=b;k<=x;k+=v)C.indexOf(k)===-1&&C.push(k);return C}static#a(g,b,x,v){const C=b.split("-");if(C.length<=1)return isNaN(+b)?b:+b;const[k,S]=C.map(T=>parseInt(T,10));return this.#c(k,S,v),this.#l(x),this.#i(g,k,S,x)}static#d(g){const b=g.split("#");if(b.length<=1)return{dayOfWeek:b[0]};const x=+b[b.length-1],v=g.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(g,b){return g.chars.some(x=>b.toString().includes(x))}};return jt.CronExpressionParser=u,jt}var Nt={};const Sf={},kf=Object.freeze(Object.defineProperty({__proto__:null,default:Sf},Symbol.toStringTag,{value:"Module"})),la=c.getAugmentedNamespace(kf);var ca;function Cf(){if(ca)return Nt;ca=1;var e=Nt&&Nt.__createBinding||(Object.create?(function(l,a,d,u){u===void 0&&(u=d);var h=Object.getOwnPropertyDescriptor(a,d);(!h||("get"in h?!a.__esModule:h.writable||h.configurable))&&(h={enumerable:!0,get:function(){return a[d]}}),Object.defineProperty(l,u,h)}):(function(l,a,d,u){u===void 0&&(u=d),l[u]=a[d]})),n=Nt&&Nt.__setModuleDefault||(Object.create?(function(l,a){Object.defineProperty(l,"default",{enumerable:!0,value:a})}):function(l,a){l.default=a}),r=Nt&&Nt.__importStar||(function(){var l=function(a){return l=Object.getOwnPropertyNames||function(d){var u=[];for(var h in d)Object.prototype.hasOwnProperty.call(d,h)&&(u[u.length]=h);return u},l(a)};return function(a){if(a&&a.__esModule)return a;var d={};if(a!=null)for(var u=l(a),h=0;h<u.length;h++)u[h]!=="default"&&e(d,a,u[h]);return n(d,a),d}})();Object.defineProperty(Nt,"__esModule",{value:!0}),Nt.CronFileParser=void 0;const s=Xs();let i=class Kr{static async parseFile(a){const{readFile:d}=await Promise.resolve().then(()=>r(la)),u=await d(a,"utf8");return Kr.#e(u)}static parseFileSync(a){const{readFileSync:d}=la,u=d(a,"utf8");return Kr.#e(u)}static#e(a){const d=a.split(`
package/dist/index.es.js CHANGED
@@ -2514,6 +2514,16 @@ const Xr = dn("MuiMenuItem", ["root", "focusVisible", "dense", "disabled", "divi
2514
2514
  name: "queryTimeoutMilliseconds",
2515
2515
  type: "text",
2516
2516
  required: !1
2517
+ },
2518
+ {
2519
+ label: "Database Metadata",
2520
+ name: "dbmeta",
2521
+ type: "text",
2522
+ required: !1,
2523
+ selectOptions: [
2524
+ { label: "No", value: "false" },
2525
+ { label: "Yes", value: "true" }
2526
+ ]
2517
2527
  }
2518
2528
  ],
2519
2529
  snowflake: [
@@ -2819,6 +2829,9 @@ const Xr = dn("MuiMenuItem", ["root", "focusVisible", "dense", "disabled", "divi
2819
2829
  ducklake: "ducklakeConnection",
2820
2830
  publisher: "publisherConnection"
2821
2831
  }, Jp = {
2832
+ bigquery: {
2833
+ dbmeta: "boolean"
2834
+ },
2822
2835
  sqlserver: {
2823
2836
  port: "integer",
2824
2837
  encrypt: "boolean",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@malloy-publisher/sdk",
3
3
  "description": "Malloy Publisher SDK",
4
- "version": "0.12.3",
4
+ "version": "0.12.5",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs.js",
7
7
  "module": "dist/index.es.js",
@@ -25,6 +25,15 @@ describe("typedConnectionConfig", () => {
25
25
  });
26
26
  });
27
27
 
28
+ it("sends BigQuery dbmeta as a boolean", () => {
29
+ expect(
30
+ typedConnectionConfig("bigquery", {
31
+ defaultProjectId: "data-project",
32
+ dbmeta: "true",
33
+ }),
34
+ ).toEqual({ defaultProjectId: "data-project", dbmeta: true });
35
+ });
36
+
28
37
  it("leaves out a blank optional name rather than storing an empty one", () => {
29
38
  // The edit form submits "" for an untouched optional field; stored, the
30
39
  // connector would read a defined instanceName and drop the port.
@@ -117,6 +117,16 @@ export const connectionFieldsByType: Record<
117
117
  type: "text",
118
118
  required: false,
119
119
  },
120
+ {
121
+ label: "Database Metadata",
122
+ name: "dbmeta",
123
+ type: "text",
124
+ required: false,
125
+ selectOptions: [
126
+ { label: "No", value: "false" },
127
+ { label: "Yes", value: "true" },
128
+ ],
129
+ },
120
130
  ],
121
131
  snowflake: [
122
132
  {
@@ -411,6 +421,9 @@ export const attributesFieldName: Record<ConnectionTypeEnum, string> = {
411
421
  const TYPED_FIELDS: Partial<
412
422
  Record<ConnectionTypeEnum, Record<string, "integer" | "boolean">>
413
423
  > = {
424
+ bigquery: {
425
+ dbmeta: "boolean",
426
+ },
414
427
  sqlserver: {
415
428
  port: "integer",
416
429
  encrypt: "boolean",