@malloy-publisher/sdk 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Rl=Object.create;var go=Object.defineProperty;var Pl=Object.getOwnPropertyDescriptor;var Ll=Object.getOwnPropertyNames;var _l=Object.getPrototypeOf,zl=Object.prototype.hasOwnProperty;var Wl=(e,r,i,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let d of Ll(r))!zl.call(e,d)&&d!==i&&go(e,d,{get:()=>r[d],enumerable:!(o=Pl(r,d))||o.enumerable});return e};var ql=(e,r,i)=>(i=e!=null?Rl(_l(e)):{},Wl(r||!e||!e.__esModule?go(i,"default",{value:e,enumerable:!0}):i,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),g=require("@mui/material"),O=require("react"),s=require("./useCompiledDocument-QgySwHGA.cjs.js"),U=require("./ServerProvider-CFHqDHFO.cjs.js"),Ot=require("@tanstack/react-query"),nr=require("@mui/system"),Dt=require("@mui/icons-material"),ps=require("./text-entry-BJwltZiy.cjs.js"),tn=require("./RenderedResult-C2r3Zkwl.cjs.js"),vr=require("react-router-dom");function Vl(e){const r=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const i in e)if(i!=="default"){const o=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(r,i,o.get?o:{enumerable:!0,get:()=>e[i]})}}return r.default=e,Object.freeze(r)}const be=Vl(O),Hl=s.createSvgIcon(t.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function Bl({label:e,href:r,onClick:i}){const o=d=>{const a=d.metaKey||d.ctrlKey||d.shiftKey||d.altKey||d.button!==0;r!==void 0&&a||(d.preventDefault(),i(d))};return t.jsxs(g.Link,{...r===void 0?{component:"button",type:"button"}:{href:r},onClick:o,underline:"none","aria-label":`Back to ${e}`,sx:{display:"inline-flex",alignItems:"center",gap:.5,cursor:"pointer",color:"text.secondary",fontSize:"0.875rem",mb:2,border:0,p:0,background:"none",font:"inherit","&:hover":{color:"primary.main"}},children:[t.jsx(Hl,{sx:{fontSize:18}}),"Back to ",e]})}const li="(max-width:599.95px)";function ci(){return g.useMediaQuery(li,{noSsr:!0})}function ui(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(li).matches}function Ul({children:e}){const[r]=O.useState(ui),[i,o]=O.useState(!1);return!r||i?t.jsx(t.Fragment,{children:e}):t.jsxs(g.Stack,{sx:{alignItems:"flex-start",gap:1.5,py:3},children:[t.jsx(g.Typography,{variant:"h6",children:"Editing works best on a larger screen"}),t.jsx(g.Typography,{variant:"body2",color:"text.secondary",children:"The editor is built for a wider window. You can still try it here."}),t.jsx(g.Button,{variant:"outlined",onClick:()=>o(!0),children:"Edit anyway"})]})}function Gl(){const e=vr.useNavigate();return(r,i)=>{if(!i||!i.metaKey&&!i.ctrlKey&&!i.shiftKey&&i.button!==1){e(r);return}const o=new URL(r,window.location.href).href;(i.metaKey||i.ctrlKey||i.button===1||i.shiftKey)&&window.open(o,"_blank")}}function di(e,r){return e.flatMap(({filter:i})=>{if(i.kind!=="literal_equality"||i.expression.kind!=="field_reference")return[];const o=Yl(i.value,r);return o===void 0?[]:[{field:i.expression.name,label:o,expression:i.expression}]})}function hi(e,r){switch(e.kind){case"string_literal":return`'${s.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 i=fi(e.date_value);return i&&`@${i[0]}-${i[1]}-${i[2]}`}case"timestamp_literal":{const i=mi(e.timestamp_value,r);return i&&`@${i[0]}-${i[1]}-${i[2]} ${i[3]}:${i[4]}:${i[5]}${pi(e.timestamp_value)}`}default:return}}function Yl(e,r){switch(e.kind){case"string_literal":return e.string_value;case"null_literal":return"null";case"date_literal":{const i=fi(e.date_value);return i&&yo([...i,"00","00","00"],e.granularity??"day")}case"timestamp_literal":{const i=mi(e.timestamp_value,r);return i&&yo(i,e.granularity??"second")+(e.granularity===void 0?pi(e.timestamp_value):"")}default:return hi(e)}}function fi(e){const r=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);return r?[r[1],r[2],r[3]]:void 0}function pi(e){const r=/:\d{2}\.(\d+)/.exec(e)?.[1]?.replace(/0+$/,"");return r?`.${r}`:""}function mi(e,r){const i=new Date(e);if(Number.isNaN(i.getTime()))return;let o;try{o=new Intl.DateTimeFormat("en-US",{timeZone:r??"UTC",hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(i)}catch{return}const d=a=>o.find(c=>c.type===a)?.value??"";return[d("year").padStart(4,"0"),d("month"),d("day"),d("hour"),d("minute"),d("second")]}function yo([e,r,i,o,d,a],c){switch(c){case"year":return e;case"quarter":return`${e}-Q${Math.floor((Number(r)-1)/3)+1}`;case"month":return`${e}-${r}`;case"week":case"day":return`${e}-${r}-${i}`;case"hour":return`${e}-${r}-${i} ${o}`;case"minute":return`${e}-${r}-${i} ${o}:${d}`;default:return`${e}-${r}-${i} ${o}:${d}:${a}`}}const Kl="drill_metadata_corrected",wr=e=>e,Cn=e=>{try{return e?.()}catch{return}},gi=e=>Cn(e.isBasic?.bind(e))===!0&&Cn(e.wasDimension?.bind(e))===!0,Zl=e=>[e.isString,e.isNumber,e.isBoolean,e.isTime].some(r=>Cn(r?.bind(e))===!0);function Cr(e){const r=e.metadataTag?.text("drill_expression","code");return r===void 0||r.trim()===""?void 0:r}function yi(e){const r=[];for(let i=e.parent;i;i=i.parent)r.push(i);return r}function xi(e){const r=yi(e),o=(r[r.length-1]??e).metadataTag,d=o?.text("source","name");if(!d||!o?.array||o.array("source","parameters")!==void 0||o.has?.(Kl)!==!0)return;const a=[];for(const f of[...r].reverse())if(Cn(f.isArray?.bind(f))===!0){if(f.metadataTag?.has?.("drillable")!==!0)return;for(const h of f.metadataTag?.array?.("drill_filters")??[]){const p=h.text("code");if(!p)return;a.push(p)}}const c=o?.text("query_name");return{source:d,filters:a,...c&&!c.startsWith("__")?{queryName:c}:{}}}function or(e){const r=new Set;for(const i of yi(e))for(const o of i.fields??[])gi(o)&&r.add(o);return[...r]}function vi(e){const r=new Set(or(e).filter(i=>Cn(i.isTime?.bind(i))===!0).map(i=>Cn(i.getEffectiveQueryTimezone?.bind(i))));return r.size>1?null:[...r][0]}function xo(e){return!gi(e)||Cr(e)===void 0||xi(e)===void 0||vi(e)===null?!1:or(e).every(r=>Cr(r)!==void 0&&r.drillStableExpression!==void 0&&Zl(r))}function Ql(e,r){const i=or(e),o=[],d=new Set;for(const a of r){if(a.kind==="drill")continue;const{filter:c}=a;if(c.kind!=="literal_equality")return;const f=JSON.stringify(c.expression),h=i.find(x=>JSON.stringify(x.drillStableExpression)===f),p=h&&Cr(h);if(h===void 0||p===void 0)return;o.push({code:p,value:c.value}),d.add(h)}return i.every(a=>d.has(a))&&o.length>0?o:void 0}const Xl=360;function os(e){return e?e.getLabel?.()??e.tag?.text("label")??wr(e).metadataTag?.text("label")??e.name:""}function Jl(e,r){const i=e.drillClauses?di(e.drillClauses,e.timezone):[];if(i.length===0)return`${os(r)}: ${e.label}`;const o=or(wr(r));return i.map(d=>{const a=JSON.stringify(d.expression),c=o.find(f=>JSON.stringify(f.drillStableExpression)===a);return`${c?os(c):d.field}: ${d.label}`}).join(", ")}function ms({onNavigate:e,onSelf:r,destinationTitle:i,canSelf:o,onRows:d}){const[a,c]=O.useState(null),f=O.useCallback((k,T)=>k.filter(j=>j===s.DRILL_SELF?r!==void 0&&(o?.(T)??!0):e!==void 0),[e,r,o]),h=O.useCallback((k,T,j)=>{if(T===s.DRILL_SELF){r?.(k.given,k.rawValue);return}e?.({path:T,dashboard:T,givens:{[k.given]:k.value}},j)},[e,r]),p=O.useCallback(k=>{if(!d||k.noRows||k.isHeader||!k.field)return;const T=wr(k.field);if(!xo(T))return;const j=xi(T);if(j===void 0)return;const E=k.drillClauses;let D;if(E!==void 0){const q=Ql(T,E);if(q===void 0)return;D={dimensions:q}}else{const q=Cr(T);if(q===void 0||or(T).length!==1||s.drillValueToFilter(k.value)===void 0||typeof k.value=="number"&&Number.isInteger(k.value)&&!Number.isSafeInteger(k.value))return;D={code:q}}const N=vi(T)??void 0;return{field:k.field.name,rawValue:k.value,label:s.drillValueLabel(k.value),target:j,...D,...k.context===void 0?{}:{context:k.context},...E===void 0?{}:{drillClauses:E},...N===void 0?{}:{timezone:N}}},[d]),x=O.useCallback(k=>{const T=s.resolveDrill(k),j=p(k),E=T?Array.from(new Set(f(T.to,T.given))).sort((q,P)=>+(P===s.DRILL_SELF)-+(q===s.DRILL_SELF)):[],D=`${os(k.field)}: ${T?.label??s.drillValueLabel(k.value)}`,N=E.map(q=>({key:`to:${q}`,label:q===s.DRILL_SELF?`Filter to ${D}`:`Open ${i?.(q)??s.humanizeSlug(q.split("/").pop()??q)} (${D})`,run:()=>{T&&h(T,q,k.event)}}));j&&k.field&&N.push({key:"rows",label:`Show rows (${Jl(j,k.field)})`,run:()=>d?.(j)}),N.length!==0&&c({items:N,top:k.event?.clientY??0,left:k.event?.clientX??0})},[h,f,d,p,i]),b=O.useCallback(k=>f(s.drillDestinations(k),s.drillGivenName(k)).length>0,[f]),v=O.useCallback(k=>d!==void 0&&xo(wr(k)),[d]),y=O.useMemo(()=>({onClick:x,canDrill:k=>b(k)||v(k)}),[x,b,v]),w=O.useCallback((k,T)=>({canDrill:j=>b(j)||T&&v(j),onClick:j=>x({...j,...k===void 0?{}:{context:k},...T?{}:{noRows:!0}})}),[x,b,v]),C=O.useCallback(()=>c(null),[]);return{drill:y,bindingFor:w,drillMenu:t.jsx(g.Menu,{open:a!==null,onClose:C,anchorReference:"anchorPosition",anchorPosition:{top:a?.top??0,left:a?.left??0},children:(a?.items??[]).map(k=>t.jsx(g.MenuItem,{title:k.label,"aria-label":k.label,onClick:()=>{C(),k.run()},sx:{maxWidth:Xl},children:t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k.label})},k.key))})}}const ec=e=>{const r=be.useRef({});return be.useEffect(()=>{r.current=e}),r.current};function tc(){const[e]=vr.useSearchParams(),r=vr.useNavigate(),i=vr.useLocation(),o=O.useMemo(()=>Object.fromEntries(e.entries()),[e]),d=O.useRef(new Set),a=O.useCallback((c,f)=>{const h=new Set([...f,...d.current]);d.current=new Set([...d.current,...Object.keys(c),...f]);const p=new URLSearchParams(i.search);for(const x of h)Object.prototype.hasOwnProperty.call(c,x)||p.delete(x);for(const[x,b]of Object.entries(c))p.set(x,b);r({search:p.toString(),hash:i.hash},{replace:!0})},[r,i]);return{params:o,onGivensChange:a}}const nc=s.createSvgIcon(t.jsx("path",{d:"M5 20h14v-2H5zM19 9h-4V3H9v6H5l7 7z"}));function Qn(e){return/^[=+\-@\t\r]/.test(e)?`'${e}`:e}function Xn(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function rc(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 Xn(Qn(e.string_value));case"json_cell":return Xn(Qn(e.json_value));case"sql_native_cell":return Xn(Qn(e.sql_native_value));default:return Xn(Qn(JSON.stringify(e)))}}function bi(e){const r=e.data;return r?.kind!=="array_cell"?[]:r.array_value.flatMap(i=>i.kind==="record_cell"?[i.record_value]:[])}function sc(e){const r=e.schema.fields;return`\uFEFF${[r.map(o=>Xn(Qn(o.name))).join(","),...bi(e).map(o=>r.map((d,a)=>rc(o[a])).join(","))].join(`\r
1
+ "use strict";var Rl=Object.create;var go=Object.defineProperty;var Pl=Object.getOwnPropertyDescriptor;var Ll=Object.getOwnPropertyNames;var _l=Object.getPrototypeOf,zl=Object.prototype.hasOwnProperty;var Wl=(e,r,i,o)=>{if(r&&typeof r=="object"||typeof r=="function")for(let d of Ll(r))!zl.call(e,d)&&d!==i&&go(e,d,{get:()=>r[d],enumerable:!(o=Pl(r,d))||o.enumerable});return e};var ql=(e,r,i)=>(i=e!=null?Rl(_l(e)):{},Wl(r||!e||!e.__esModule?go(i,"default",{value:e,enumerable:!0}):i,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),g=require("@mui/material"),O=require("react"),s=require("./useCompiledDocument-D7X_K6YU.cjs.js"),U=require("./ServerProvider-BHfg1Ed6.cjs.js"),Ot=require("@tanstack/react-query"),nr=require("@mui/system"),Dt=require("@mui/icons-material"),ps=require("./text-entry-BJwltZiy.cjs.js"),tn=require("./RenderedResult-SgDlxzs9.cjs.js"),vr=require("react-router-dom");function Vl(e){const r=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const i in e)if(i!=="default"){const o=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(r,i,o.get?o:{enumerable:!0,get:()=>e[i]})}}return r.default=e,Object.freeze(r)}const be=Vl(O),Hl=s.createSvgIcon(t.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function Bl({label:e,href:r,onClick:i}){const o=d=>{const a=d.metaKey||d.ctrlKey||d.shiftKey||d.altKey||d.button!==0;r!==void 0&&a||(d.preventDefault(),i(d))};return t.jsxs(g.Link,{...r===void 0?{component:"button",type:"button"}:{href:r},onClick:o,underline:"none","aria-label":`Back to ${e}`,sx:{display:"inline-flex",alignItems:"center",gap:.5,cursor:"pointer",color:"text.secondary",fontSize:"0.875rem",mb:2,border:0,p:0,background:"none",font:"inherit","&:hover":{color:"primary.main"}},children:[t.jsx(Hl,{sx:{fontSize:18}}),"Back to ",e]})}const li="(max-width:599.95px)";function ci(){return g.useMediaQuery(li,{noSsr:!0})}function ui(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(li).matches}function Ul({children:e}){const[r]=O.useState(ui),[i,o]=O.useState(!1);return!r||i?t.jsx(t.Fragment,{children:e}):t.jsxs(g.Stack,{sx:{alignItems:"flex-start",gap:1.5,py:3},children:[t.jsx(g.Typography,{variant:"h6",children:"Editing works best on a larger screen"}),t.jsx(g.Typography,{variant:"body2",color:"text.secondary",children:"The editor is built for a wider window. You can still try it here."}),t.jsx(g.Button,{variant:"outlined",onClick:()=>o(!0),children:"Edit anyway"})]})}function Gl(){const e=vr.useNavigate();return(r,i)=>{if(!i||!i.metaKey&&!i.ctrlKey&&!i.shiftKey&&i.button!==1){e(r);return}const o=new URL(r,window.location.href).href;(i.metaKey||i.ctrlKey||i.button===1||i.shiftKey)&&window.open(o,"_blank")}}function di(e,r){return e.flatMap(({filter:i})=>{if(i.kind!=="literal_equality"||i.expression.kind!=="field_reference")return[];const o=Yl(i.value,r);return o===void 0?[]:[{field:i.expression.name,label:o,expression:i.expression}]})}function hi(e,r){switch(e.kind){case"string_literal":return`'${s.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 i=fi(e.date_value);return i&&`@${i[0]}-${i[1]}-${i[2]}`}case"timestamp_literal":{const i=mi(e.timestamp_value,r);return i&&`@${i[0]}-${i[1]}-${i[2]} ${i[3]}:${i[4]}:${i[5]}${pi(e.timestamp_value)}`}default:return}}function Yl(e,r){switch(e.kind){case"string_literal":return e.string_value;case"null_literal":return"null";case"date_literal":{const i=fi(e.date_value);return i&&yo([...i,"00","00","00"],e.granularity??"day")}case"timestamp_literal":{const i=mi(e.timestamp_value,r);return i&&yo(i,e.granularity??"second")+(e.granularity===void 0?pi(e.timestamp_value):"")}default:return hi(e)}}function fi(e){const r=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);return r?[r[1],r[2],r[3]]:void 0}function pi(e){const r=/:\d{2}\.(\d+)/.exec(e)?.[1]?.replace(/0+$/,"");return r?`.${r}`:""}function mi(e,r){const i=new Date(e);if(Number.isNaN(i.getTime()))return;let o;try{o=new Intl.DateTimeFormat("en-US",{timeZone:r??"UTC",hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(i)}catch{return}const d=a=>o.find(c=>c.type===a)?.value??"";return[d("year").padStart(4,"0"),d("month"),d("day"),d("hour"),d("minute"),d("second")]}function yo([e,r,i,o,d,a],c){switch(c){case"year":return e;case"quarter":return`${e}-Q${Math.floor((Number(r)-1)/3)+1}`;case"month":return`${e}-${r}`;case"week":case"day":return`${e}-${r}-${i}`;case"hour":return`${e}-${r}-${i} ${o}`;case"minute":return`${e}-${r}-${i} ${o}:${d}`;default:return`${e}-${r}-${i} ${o}:${d}:${a}`}}const Kl="drill_metadata_corrected",wr=e=>e,Cn=e=>{try{return e?.()}catch{return}},gi=e=>Cn(e.isBasic?.bind(e))===!0&&Cn(e.wasDimension?.bind(e))===!0,Zl=e=>[e.isString,e.isNumber,e.isBoolean,e.isTime].some(r=>Cn(r?.bind(e))===!0);function Cr(e){const r=e.metadataTag?.text("drill_expression","code");return r===void 0||r.trim()===""?void 0:r}function yi(e){const r=[];for(let i=e.parent;i;i=i.parent)r.push(i);return r}function xi(e){const r=yi(e),o=(r[r.length-1]??e).metadataTag,d=o?.text("source","name");if(!d||!o?.array||o.array("source","parameters")!==void 0||o.has?.(Kl)!==!0)return;const a=[];for(const f of[...r].reverse())if(Cn(f.isArray?.bind(f))===!0){if(f.metadataTag?.has?.("drillable")!==!0)return;for(const h of f.metadataTag?.array?.("drill_filters")??[]){const p=h.text("code");if(!p)return;a.push(p)}}const c=o?.text("query_name");return{source:d,filters:a,...c&&!c.startsWith("__")?{queryName:c}:{}}}function or(e){const r=new Set;for(const i of yi(e))for(const o of i.fields??[])gi(o)&&r.add(o);return[...r]}function vi(e){const r=new Set(or(e).filter(i=>Cn(i.isTime?.bind(i))===!0).map(i=>Cn(i.getEffectiveQueryTimezone?.bind(i))));return r.size>1?null:[...r][0]}function xo(e){return!gi(e)||Cr(e)===void 0||xi(e)===void 0||vi(e)===null?!1:or(e).every(r=>Cr(r)!==void 0&&r.drillStableExpression!==void 0&&Zl(r))}function Ql(e,r){const i=or(e),o=[],d=new Set;for(const a of r){if(a.kind==="drill")continue;const{filter:c}=a;if(c.kind!=="literal_equality")return;const f=JSON.stringify(c.expression),h=i.find(x=>JSON.stringify(x.drillStableExpression)===f),p=h&&Cr(h);if(h===void 0||p===void 0)return;o.push({code:p,value:c.value}),d.add(h)}return i.every(a=>d.has(a))&&o.length>0?o:void 0}const Xl=360;function os(e){return e?e.getLabel?.()??e.tag?.text("label")??wr(e).metadataTag?.text("label")??e.name:""}function Jl(e,r){const i=e.drillClauses?di(e.drillClauses,e.timezone):[];if(i.length===0)return`${os(r)}: ${e.label}`;const o=or(wr(r));return i.map(d=>{const a=JSON.stringify(d.expression),c=o.find(f=>JSON.stringify(f.drillStableExpression)===a);return`${c?os(c):d.field}: ${d.label}`}).join(", ")}function ms({onNavigate:e,onSelf:r,destinationTitle:i,canSelf:o,onRows:d}){const[a,c]=O.useState(null),f=O.useCallback((k,T)=>k.filter(j=>j===s.DRILL_SELF?r!==void 0&&(o?.(T)??!0):e!==void 0),[e,r,o]),h=O.useCallback((k,T,j)=>{if(T===s.DRILL_SELF){r?.(k.given,k.rawValue);return}e?.({path:T,dashboard:T,givens:{[k.given]:k.value}},j)},[e,r]),p=O.useCallback(k=>{if(!d||k.noRows||k.isHeader||!k.field)return;const T=wr(k.field);if(!xo(T))return;const j=xi(T);if(j===void 0)return;const E=k.drillClauses;let D;if(E!==void 0){const q=Ql(T,E);if(q===void 0)return;D={dimensions:q}}else{const q=Cr(T);if(q===void 0||or(T).length!==1||s.drillValueToFilter(k.value)===void 0||typeof k.value=="number"&&Number.isInteger(k.value)&&!Number.isSafeInteger(k.value))return;D={code:q}}const N=vi(T)??void 0;return{field:k.field.name,rawValue:k.value,label:s.drillValueLabel(k.value),target:j,...D,...k.context===void 0?{}:{context:k.context},...E===void 0?{}:{drillClauses:E},...N===void 0?{}:{timezone:N}}},[d]),x=O.useCallback(k=>{const T=s.resolveDrill(k),j=p(k),E=T?Array.from(new Set(f(T.to,T.given))).sort((q,P)=>+(P===s.DRILL_SELF)-+(q===s.DRILL_SELF)):[],D=`${os(k.field)}: ${T?.label??s.drillValueLabel(k.value)}`,N=E.map(q=>({key:`to:${q}`,label:q===s.DRILL_SELF?`Filter to ${D}`:`Open ${i?.(q)??s.humanizeSlug(q.split("/").pop()??q)} (${D})`,run:()=>{T&&h(T,q,k.event)}}));j&&k.field&&N.push({key:"rows",label:`Show rows (${Jl(j,k.field)})`,run:()=>d?.(j)}),N.length!==0&&c({items:N,top:k.event?.clientY??0,left:k.event?.clientX??0})},[h,f,d,p,i]),b=O.useCallback(k=>f(s.drillDestinations(k),s.drillGivenName(k)).length>0,[f]),v=O.useCallback(k=>d!==void 0&&xo(wr(k)),[d]),y=O.useMemo(()=>({onClick:x,canDrill:k=>b(k)||v(k)}),[x,b,v]),w=O.useCallback((k,T)=>({canDrill:j=>b(j)||T&&v(j),onClick:j=>x({...j,...k===void 0?{}:{context:k},...T?{}:{noRows:!0}})}),[x,b,v]),C=O.useCallback(()=>c(null),[]);return{drill:y,bindingFor:w,drillMenu:t.jsx(g.Menu,{open:a!==null,onClose:C,anchorReference:"anchorPosition",anchorPosition:{top:a?.top??0,left:a?.left??0},children:(a?.items??[]).map(k=>t.jsx(g.MenuItem,{title:k.label,"aria-label":k.label,onClick:()=>{C(),k.run()},sx:{maxWidth:Xl},children:t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k.label})},k.key))})}}const ec=e=>{const r=be.useRef({});return be.useEffect(()=>{r.current=e}),r.current};function tc(){const[e]=vr.useSearchParams(),r=vr.useNavigate(),i=vr.useLocation(),o=O.useMemo(()=>Object.fromEntries(e.entries()),[e]),d=O.useRef(new Set),a=O.useCallback((c,f)=>{const h=new Set([...f,...d.current]);d.current=new Set([...d.current,...Object.keys(c),...f]);const p=new URLSearchParams(i.search);for(const x of h)Object.prototype.hasOwnProperty.call(c,x)||p.delete(x);for(const[x,b]of Object.entries(c))p.set(x,b);r({search:p.toString(),hash:i.hash},{replace:!0})},[r,i]);return{params:o,onGivensChange:a}}const nc=s.createSvgIcon(t.jsx("path",{d:"M5 20h14v-2H5zM19 9h-4V3H9v6H5l7 7z"}));function Qn(e){return/^[=+\-@\t\r]/.test(e)?`'${e}`:e}function Xn(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function rc(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 Xn(Qn(e.string_value));case"json_cell":return Xn(Qn(e.json_value));case"sql_native_cell":return Xn(Qn(e.sql_native_value));default:return Xn(Qn(JSON.stringify(e)))}}function bi(e){const r=e.data;return r?.kind!=="array_cell"?[]:r.array_value.flatMap(i=>i.kind==="record_cell"?[i.record_value]:[])}function sc(e){const r=e.schema.fields;return`\uFEFF${[r.map(o=>Xn(Qn(o.name))).join(","),...bi(e).map(o=>r.map((d,a)=>rc(o[a])).join(","))].join(`\r
2
2
  `)}\r
3
3
  `}function oc(e,r){return[e,"rows",...r].join("_").replace(/[^A-Za-z0-9._-]+/g,"_").replace(/_+/g,"_").replace(/^[_.]+|[_.]+$/g,"").slice(0,120)||"rows"}function ic(e,r,i){return i==="server_default"&&r!==void 0&&e>=r?r:void 0}const vo="Download the rows behind this value as CSV, up to the server's row limit",ac=4e4;function lc(e,r){const i=URL.createObjectURL(new Blob([e],{type:"text/csv;charset=utf-8"})),o=document.createElement("a");o.href=i,o.download=r,document.body.appendChild(o),o.click(),o.remove(),setTimeout(()=>URL.revokeObjectURL(i),ac)}function cc(e){const i=e?.response?.data?.message;return typeof i=="string"&&i!==""?i:e instanceof Error&&e.message!==""?e.message:"The request failed."}function Si({query:e,preamble:r,environmentName:i,packageName:o,modelPath:d,versionId:a,givens:c,fileName:f}){const{apiClients:h}=U.useServer(),[p,x]=O.useState(!1),[b,v]=O.useState(vo),[y,w]=O.useState(void 0),C=O.useRef(void 0);O.useEffect(()=>()=>C.current?.abort(),[]);const k=async()=>{C.current?.abort();const T=new AbortController;C.current=T,x(!0),w(void 0);try{const j=await h.models.executeQueryModel(i,o,d,{query:r===void 0?e:s.withPreamble(r,e),givens:c,versionId:a},void 0,{signal:T.signal});if(T.signal.aborted)return;const E=j.data,D=JSON.parse(E.result??"{}"),N=ic(bi(D).length,E.queryRowLimit,E.queryRowLimitSource);v(N===void 0?vo:`First ${N} rows: the server's row limit, so there may be more`),lc(sc(D),N===void 0?`${f}.csv`:`${f}_first_${N}_rows_server_limit.csv`)}catch(j){if(T.signal.aborted)return;w(`Download failed: ${cc(j)}`)}finally{C.current===T&&(C.current=void 0,x(!1))}};return t.jsxs(g.Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[y&&t.jsx(g.Typography,{role:"alert",variant:"caption",color:"error",sx:{maxWidth:320},children:y}),t.jsx(g.Tooltip,{title:b,children:t.jsx("span",{children:t.jsx(g.Button,{size:"small",startIcon:t.jsx(nc,{fontSize:"small"}),onClick:()=>void k(),disabled:p,children:"Download CSV"})})})]})}const wi=200;function uc(e){const{target:r}=e;if(r!==void 0&&!(e.dimensions===void 0&&e.code===void 0))return{...e,target:r}}function bo(e,r=wi){const i=hc(e);if(i===void 0)return;const o=[...e.target.filters,...i].join(", "),d=e.timezone?`timezone: '${s.escapeMalloyString(e.timezone)}'; `:"",a=r===null?"":`; limit: ${r}`,c=dc(e.target.source);if(c!==void 0)return`run: ${c} -> { ${d}where: ${o}; select: *${a} }`}function dc(e){return ps.isBareName(e)?e:e.includes("`")?void 0:`\`${e}\``}function Wr(e){return/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(e)?e:`(${e})`}function hc(e){if(e.dimensions){const i=[];for(const{code:o,value:d}of e.dimensions){if(d.kind==="null_literal"){i.push(`${Wr(o)} is null`);continue}const a=hi(d,e.timezone);if(a===void 0)return;i.push(`${Wr(o)} = ${a}`)}return i}const r=s.malloyLiteral(e.rawValue);return e.code!==void 0&&r?[`${Wr(e.code)} = ${r}`]:void 0}const fc="This value cannot be written as a filter, so its rows cannot be fetched.";function So(e){const r=e.drillClauses?di(e.drillClauses,e.timezone):[];return r.length>0?r:[{field:e.field,label:e.label}]}function pc({request:e,environmentName:r,packageName:i,versionId:o,modelPath:d,preamble:a,givens:c,onClose:f,onDone:h,actions:p}){const{theme:x}=U.usePublisherTheme(),b=e?bo(e):void 0,v=e?bo(e,null):void 0,y=e&&v!==void 0?{query:v,...a===void 0?{}:{preamble:a},environmentName:r,packageName:i,modelPath:d,...o===void 0?{}:{versionId:o},givens:c,fileName:oc(e.target.source,So(e).map(w=>w.label))}:void 0;return t.jsxs(g.Dialog,{open:e!==void 0,onClose:f,maxWidth:"lg",fullWidth:!0,children:[t.jsxs(g.DialogTitle,{sx:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",pb:.5},children:[t.jsxs(g.Box,{children:[e?t.jsxs(t.Fragment,{children:["Rows where"," ",So(e).map((w,C)=>t.jsxs(O.Fragment,{children:[C>0&&" and ",t.jsx(g.Box,{component:"code",sx:{fontSize:"0.9em"},children:w.field})," ","is ",w.label]},C))]}):"Rows",t.jsx(g.Typography,{component:"div",variant:"caption",sx:{color:x.tileTitle,mt:.25},children:e?`The first ${wi} rows of ${e.target.source} behind this value, with the tile's own filters and the controls applied.`:""})]}),t.jsxs(g.Box,{sx:{display:"flex",alignItems:"center",gap:1,ml:1},children:[y&&(p?p(y):t.jsx(Si,{...y})),t.jsx(g.IconButton,{onClick:f,"aria-label":"Close",size:"small",sx:{color:"text.secondary"},children:t.jsx(s.CloseIcon,{fontSize:"small"})})]})]}),t.jsxs(g.DialogContent,{dividers:!0,sx:{p:0,minHeight:240},children:[b===void 0&&e&&t.jsx(g.Typography,{variant:"body2",sx:{p:2},children:fc}),b!==void 0&&t.jsx(mc,{query:a===void 0?b:s.withPreamble(a,b),environmentName:r,packageName:i,...o===void 0?{}:{versionId:o},modelPath:d,givens:c,...h?{onDone:h}:{}})]}),t.jsxs(g.DialogActions,{sx:{px:3,py:1.5},children:[b!==void 0&&t.jsx(g.Typography,{variant:"caption",sx:{mr:"auto",color:x.tileTitle,fontFamily:x.ui.font.mono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:b,children:b}),t.jsx(g.Button,{onClick:f,children:"Close"})]})]})}function mc({query:e,environmentName:r,packageName:i,versionId:o,modelPath:d,givens:a,onDone:c}){const f=s.useQueryResult({environmentName:r,packageName:i,modelPath:d,...o===void 0?{}:{versionId:o},query:e,givens:a}),{isSuccess:h,isError:p}=f,x=O.useRef(void 0);return O.useEffect(()=>{x.current=s.now()},[e]),O.useEffect(()=>{x.current===void 0||!h&&!p||(c?.(h,s.now()-x.current),x.current=void 0)},[h,p,c]),t.jsx(g.Box,{sx:{p:1},children:t.jsx(s.ResultPanel,{state:f,context:e})})}function jr({manifest:e,environmentName:r,packageName:i,versionId:o,documentName:d,givens:a,onGivensChange:c,onNavigate:f,height:h,maxResultSize:p,controlsLayout:x="bar",preamble:b,runModelPath:v,hiddenGivens:y,literalReads:w,onLinkNavigate:C,actions:k,rowsActions:T}){const j=O.useMemo(()=>C?{environmentName:r,packageName:i,sourcePath:e.path??d,onNavigate:C}:void 0,[r,i,e.path,d,C]),E=O.useMemo(()=>(e.givens??[]).filter(re=>!(b!==void 0&&re.secure===!0)&&!(re.name!==void 0&&y?.includes(re.name))),[e,y,b]),D=O.useMemo(()=>a===void 0?void 0:Object.fromEntries(Object.entries(a).filter(([,re])=>typeof re=="string")),[a]),N=s.useDocumentControls({specs:E,loaded:!0,startingValues:e.startingGivens,params:D,onGivensChange:c,documentKey:`${r}/${i}/${o??""}/${d}`,autorun:e.autorun!==!1,environmentName:r,packageName:i,modelPath:v??e.path,versionId:o,documentName:d,...b!==void 0?{preamble:b}:{},...a?{hostGivens:a}:{}}),{applied:q,declaredTypes:P,canSelf:ee,onSelf:$}=N,L=s.useReportEvents(),G=O.useMemo(()=>{const re=new Set((e.tiles??[]).flatMap(Y=>Y.givenNames??[]));return Object.fromEntries(Object.entries(a??{}).filter(([Y])=>re.has(Y)&&!P.has(Y)))},[e,a,P]),[I,B]=O.useState(void 0),Z=O.useCallback(re=>{const Y=uc(re);Y!==void 0&&B(Y)},[]),H=O.useMemo(()=>s.withHostGivens(s.givensToRequest(q,P),G),[q,P,G]),{reports:X}=s.useReportListing(r,i,o,f!==void 0),ne=O.useCallback(re=>{const Y=s.resolveDrillTarget(re,X);if(Y.kind!=="path")return;const ie=Y.report.path;return X.find(Ce=>Ce.path===ie)?.title||void 0},[X]),{bindingFor:K,drillMenu:le}=ms({onNavigate:f,onSelf:$,canSelf:ee,onRows:Z,destinationTitle:ne}),z=O.useCallback((re,Y)=>K(re,Y!==!0),[K]),{columns:te,layout:se,tileMaxHeight:ce,tableMaxHeight:Ie}=s.layoutRules(e.layout,e.dashboardColumns),ae=O.useMemo(()=>s.missingRequiredGivens(E,q,a),[E,q,a]);if(e.error)return t.jsx(s.ReportPage,{layout:se,header:t.jsx(wo,{manifest:e,links:j,actions:k}),children:t.jsx(g.Alert,{severity:"error",children:e.error})});const de=v??e.path,$e=e.tiles??[],qe=s.isPlaced($e);return t.jsxs(s.ReportPage,{layout:se,header:t.jsx(wo,{manifest:e,links:j,actions:k}),controls:E.length>0?t.jsx(s.StickyControls,{children:t.jsx(s.GivensPanel,{...N.panel,layout:x})}):void 0,children:[ae.length>0&&t.jsx(g.Alert,{severity:"info",children:s.requiredPrompt(ae)}),de===void 0?t.jsx(g.Alert,{severity:"error",children:"This dashboard has no model path, so there is nothing to run."}):$e.length>0?t.jsx(s.DashboardGrid,{tiles:$e,columns:te,minTilePx:s.MIN_TILE_PX,rowGapPx:s.GRID_GAP_PX,keyOf:(re,Y)=>`${Y}:${re.kind==="text"?`text:${re.name}`:re.query}`,renderTile:(re,Y)=>re.kind==="text"||re.query===void 0?t.jsx(g.Box,{sx:re.rowspan!==void 0||qe?{minHeight:0,overflow:"auto"}:void 0,children:t.jsx(gc,{markdown:re.markdown??"",links:j})}):t.jsx(s.DashboardTile,{index:Y,environmentName:r,packageName:i,versionId:o,modelPath:de,tile:re.query,label:re.label,subtitle:re.subtitle,borderless:re.borderless,givens:q,hostGivens:G,declaredTypes:P,givenNames:re.givenNames,height:re.rowspan!==void 0||qe?s.tileHeightPx(re.rowspan??s.PLACED_DEFAULT_ROWSPAN.query):se==="grid"?h??ce:ce,tableMaxHeight:Ie,fixedHeight:re.rowspan!==void 0||qe,maxResultSize:p,drill:z(re.query,re.restricted),ignoredFilters:s.tileIgnoredFilterLabels(re.givenNames&&(re.query&&w?.[re.query]?[...re.givenNames,...w[re.query]]:re.givenNames),E),...b!==void 0?{preamble:b,restricted:re.restricted}:{},...(()=>{const ie=s.waitingOn(ae,re.givenNames);return ie.length>0?{waitingFor:s.waitingText(ie)}:{}})()})}):t.jsx(g.Alert,{severity:"warning",children:"This dashboard names neither a query nor any tiles."}),le,de!==void 0&&t.jsx(pc,{request:I,environmentName:r,packageName:i,...o===void 0?{}:{versionId:o},modelPath:de,...b===void 0?{}:{preamble:b},givens:H,...T===void 0?{}:{actions:T},onClose:()=>B(void 0),onDone:(re,Y)=>{I&&L.emit({type:"report.rows_shown",source:I.target.source,view:I.target.queryName??"",field:I.field,ok:re,durationMs:Y})}})]})}function gc({markdown:e,links:r}){return t.jsx(s.TextTileFrame,{children:t.jsx(s.Prose,{variant:"document",links:r,children:e})})}function wo({manifest:e,links:r,actions:i}){return t.jsx(s.ReportHeader,{title:e.title??e.name,actions:i,description:e.description?t.jsx(s.TextTileFrame,{children:t.jsx(s.Prose,{variant:"document",links:r,children:e.description})}):void 0})}const Ci=s.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"})),yc="publisher:resize";function xc(e){return typeof e=="object"&&e!==null&&e.type===yc&&typeof e.height=="number"}function ki(e){return e.replace(/\/api\/v0\/?$/,"")}function Ti({server:e,environmentName:r,packageName:i,path:o,versionId:d}){const a=o.startsWith("public/")?o.slice(7):o,c=`${ki(e)}/environments/${encodeURIComponent(r)}/packages/${encodeURIComponent(i)}/`+a;return d===void 0?c:`${c}${c.includes("?")?"&":"?"}versionId=${encodeURIComponent(d)}`}function vc(e){try{const{environmentName:r,packageName:i,modelPath:o,versionId:d}=s.parseResourceUri(e);return!r||!i||!o?null:{environmentName:r,packageName:i,dataAppPath:o,versionId:d}}catch{return null}}function bc({resourceUri:e}){const{server:r,apiClients:i}=U.useServer(),o=vc(e),d=o?.environmentName??"",a=o?.packageName??"",c=o?.dataAppPath??"",f=o?.versionId,h=O.useMemo(()=>Ti({server:r,environmentName:d,packageName:a,path:c,...f!==void 0?{versionId:f}:{}}),[r,d,a,c,f]),x=s.useQueryWithApiError({queryKey:["data-apps",d,a,f],queryFn:()=>i.dataApps.listDataApps(d,a,f),enabled:!!o}).data?.data?.find(k=>k.path===c),b=x?.title??c,v=x?.fit==="viewport",y=O.useRef(null),[w,C]=O.useState(120);return O.useEffect(()=>{if(v)return;function k(T){xc(T.data)&&T.source===y.current?.contentWindow&&T.data.height>0&&C(Math.ceil(T.data.height))}return window.addEventListener("message",k),()=>window.removeEventListener("message",k)},[v]),o?t.jsxs(g.Box,{sx:{p:3,...v?{height:"100%",display:"flex",flexDirection:"column"}:{maxWidth:1600,mx:"auto"}},children:[t.jsxs(g.Stack,{direction:"row",alignItems:"baseline",spacing:1,sx:{mb:1,flexShrink:0},children:[t.jsx(g.Typography,{variant:"h6",sx:{fontWeight:"fontWeightMedium",letterSpacing:"-0.025em"},children:b}),t.jsx(g.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:U.MONO_FONT_FAMILY},children:c}),t.jsx(g.Box,{sx:{flex:1}}),t.jsx(g.Tooltip,{title:"Open standalone in new tab",children:t.jsx(g.IconButton,{size:"small",href:h,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:t.jsx(Ci,{fontSize:"small"})})})]}),t.jsx(g.Box,{sx:{border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden",backgroundColor:"background.paper",...v?{flex:1,minHeight:0}:{}},children:t.jsx("iframe",{ref:y,src:h,title:b,sandbox:"allow-scripts allow-same-origin allow-forms",style:{display:"block",width:"100%",height:v?"100%":w,border:0}})})]}):t.jsxs(g.Box,{sx:{p:3,maxWidth:1600,mx:"auto"},children:[t.jsx(g.Typography,{variant:"h6",sx:{fontWeight:"fontWeightMedium"},children:"Can't open data app"}),t.jsxs(g.Typography,{variant:"body2",color:"text.secondary",sx:{mt:1},children:["This data app link is missing an environment, package, or path:",t.jsx(g.Box,{component:"span",sx:{fontFamily:U.MONO_FONT_FAMILY,ml:1},children:e})]})]})}function Mt({title:e,count:r,description:i,action:o,children:d}){const a=O.useId();return t.jsxs(g.Box,{component:"section","aria-labelledby":a,sx:{mb:4},children:[t.jsxs(g.Stack,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:i?0:1,minHeight:40},children:[t.jsxs(g.Stack,{direction:"row",alignItems:"baseline",spacing:1,children:[t.jsx(g.Typography,{id:a,variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em",lineHeight:1.2},children:e}),r!==void 0&&t.jsxs(g.Typography,{variant:"caption",color:"text.secondary",children:["(",r,")"]})]}),o]}),i&&t.jsx(g.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:i}),t.jsx(g.Box,{children:d})]})}function Sc({resourceUri:e}){const{environmentName:r}=s.parseResourceUri(e),{apiClients:i}=U.useServer(),[o,d]=O.useState(!1),a=90,{data:c,isSuccess:f,isError:h,error:p}=s.useQueryWithApiError({queryKey:["about",r],queryFn:()=>i.environments.getEnvironment(r,!1)}),x=c?.data?.readme||"",b=x.split(/\s+/),v=b.length>a,y=b.slice(0,a).join(" ");return t.jsxs(t.Fragment,{children:[!f&&!h&&t.jsx(s.Loading,{text:"Fetching About..."}),f&&x&&t.jsxs(Mt,{title:"Readme",children:[t.jsx(s.Prose,{variant:"caption",children:o||!v?x:y}),v&&t.jsx(g.Box,{sx:{mt:1},children:t.jsx(s.SecondaryButton,{label:o?"Read less":"Read more",onClick:()=>d(!o)})})]}),h&&t.jsx(s.ApiErrorDisplay,{error:p,context:`${r} > About`})]})}function wc(e={}){const{autoHideDuration:r=null,disableWindowBlurListener:i=!1,onClose:o,open:d,resumeHideDuration:a}=e,c=s.useTimeout();be.useEffect(()=>{if(!d)return;function T(j){j.defaultPrevented||j.key==="Escape"&&o?.(j,"escapeKeyDown")}return document.addEventListener("keydown",T),()=>{document.removeEventListener("keydown",T)}},[d,o]);const f=s.useEventCallback((T,j)=>{o?.(T,j)}),h=s.useEventCallback(T=>{!o||T==null||c.start(T,()=>{f(null,"timeout")})});be.useEffect(()=>(d&&h(r),c.clear),[d,r,h,c]);const p=T=>{o?.(T,"clickaway")},x=c.clear,b=be.useCallback(()=>{r!=null&&h(a??r*.5)},[r,a,h]),v=T=>j=>{const E=T.onBlur;E?.(j),b()},y=T=>j=>{const E=T.onFocus;E?.(j),x()},w=T=>j=>{const E=T.onMouseEnter;E?.(j),x()},C=T=>j=>{const E=T.onMouseLeave;E?.(j),b()};return be.useEffect(()=>{if(!i&&d)return window.addEventListener("focus",b),window.addEventListener("blur",x),()=>{window.removeEventListener("focus",b),window.removeEventListener("blur",x)}},[i,d,b,x]),{getRootProps:(T={})=>{const j={...s.extractEventHandlers(e),...s.extractEventHandlers(T)};return{role:"presentation",...T,...j,onBlur:v(j),onFocus:y(j),onMouseEnter:w(j),onMouseLeave:C(j)}},onClickAway:p}}function Co(e){return e.substring(2).toLowerCase()}function Cc(e,r){return r.documentElement.clientWidth<e.clientX||r.documentElement.clientHeight<e.clientY}function kc(e){const{children:r,disableReactTree:i=!1,mouseEvent:o="onClick",onClickAway:d,touchEvent:a="onTouchEnd"}=e,c=be.useRef(!1),f=be.useRef(null),h=be.useRef(!1),p=be.useRef(!1);be.useEffect(()=>(setTimeout(()=>{h.current=!0},0),()=>{h.current=!1}),[]);const x=s.useForkRef(s.getReactElementRef(r),f),b=s.useEventCallback(w=>{const C=p.current;p.current=!1;const k=s.ownerDocument(f.current);if(!h.current||!f.current||"clientX"in w&&Cc(w,k))return;if(c.current){c.current=!1;return}let T;w.composedPath?T=w.composedPath().includes(f.current):T=!k.documentElement.contains(w.target)||f.current.contains(w.target),!T&&(i||!C)&&d(w)}),v=w=>C=>{p.current=!0;const k=r.props[w];k&&k(C)},y={ref:x};return a!==!1&&(y[a]=v(a)),be.useEffect(()=>{if(a!==!1){const w=Co(a),C=s.ownerDocument(f.current),k=()=>{c.current=!0};return C.addEventListener(w,b),C.addEventListener("touchmove",k),()=>{C.removeEventListener(w,b),C.removeEventListener("touchmove",k)}}},[b,a]),o!==!1&&(y[o]=v(o)),be.useEffect(()=>{if(o!==!1){const w=Co(o),C=s.ownerDocument(f.current);return C.addEventListener(w,b),()=>{C.removeEventListener(w,b)}}},[b,o]),be.cloneElement(r,y)}function Tc(e){return s.generateUtilityClass("MuiSnackbarContent",e)}s.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const jc=e=>{const{classes:r}=e,i={root:["root"],action:["action"],message:["message"]};return s.composeClasses(i,Tc,r)},Mc=s.styled(s.Paper,{name:"MuiSnackbarContent",slot:"Root"})(s.memoTheme(({theme:e})=>{const r=e.palette.mode==="light"?.8:.98;return{...e.typography.body2,color:e.vars?e.vars.palette.SnackbarContent.color:e.palette.getContrastText(s.emphasize(e.palette.background.default,r)),backgroundColor:e.vars?e.vars.palette.SnackbarContent.bg:s.emphasize(e.palette.background.default,r),display:"flex",alignItems:"center",flexWrap:"wrap",padding:"6px 16px",flexGrow:1,[e.breakpoints.up("sm")]:{flexGrow:"initial",minWidth:288}}})),Oc=s.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),Dc=s.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),Ec=be.forwardRef(function(r,i){const o=s.useDefaultProps({props:r,name:"MuiSnackbarContent"}),{action:d,className:a,message:c,role:f="alert",...h}=o,p=o,x=jc(p);return t.jsxs(Mc,{role:f,elevation:6,className:s.clsx(x.root,a),ownerState:p,ref:i,...h,children:[t.jsx(Oc,{className:x.message,ownerState:p,children:c}),d?t.jsx(Dc,{className:x.action,ownerState:p,children:d}):null]})});function Ic(e){return s.generateUtilityClass("MuiSnackbar",e)}s.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const $c=e=>{const{classes:r,anchorOrigin:i}=e,o={root:["root",`anchorOrigin${s.capitalize(i.vertical)}${s.capitalize(i.horizontal)}`]};return s.composeClasses(o,Ic,r)},Fc=s.styled("div",{name:"MuiSnackbar",slot:"Root",overridesResolver:(e,r)=>{const{ownerState:i}=e;return[r.root,r[`anchorOrigin${s.capitalize(i.anchorOrigin.vertical)}${s.capitalize(i.anchorOrigin.horizontal)}`]]}})(s.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.snackbar,position:"fixed",display:"flex",left:8,right:8,justifyContent:"center",alignItems:"center",variants:[{props:({ownerState:r})=>r.anchorOrigin.vertical==="top",style:{top:8,[e.breakpoints.up("sm")]:{top:24}}},{props:({ownerState:r})=>r.anchorOrigin.vertical!=="top",style:{bottom:8,[e.breakpoints.up("sm")]:{bottom:24}}},{props:({ownerState:r})=>r.anchorOrigin.horizontal==="left",style:{justifyContent:"flex-start",[e.breakpoints.up("sm")]:{left:24,right:"auto"}}},{props:({ownerState:r})=>r.anchorOrigin.horizontal==="right",style:{justifyContent:"flex-end",[e.breakpoints.up("sm")]:{right:24,left:"auto"}}},{props:({ownerState:r})=>r.anchorOrigin.horizontal==="center",style:{[e.breakpoints.up("sm")]:{left:"50%",right:"auto",transform:"translateX(-50%)"}}}]}))),Ac=be.forwardRef(function(r,i){const o=s.useDefaultProps({props:r,name:"MuiSnackbar"}),d=s.useTheme(),a={enter:d.transitions.duration.enteringScreen,exit:d.transitions.duration.leavingScreen},{action:c,anchorOrigin:{vertical:f,horizontal:h}={vertical:"bottom",horizontal:"left"},autoHideDuration:p=null,children:x,className:b,ClickAwayListenerProps:v,ContentProps:y,disableWindowBlurListener:w=!1,message:C,onBlur:k,onClose:T,onFocus:j,onMouseEnter:E,onMouseLeave:D,open:N,resumeHideDuration:q,slots:P={},slotProps:ee={},TransitionComponent:$,transitionDuration:L=a,TransitionProps:{onEnter:G,onExited:I,...B}={},...Z}=o,H={...o,anchorOrigin:{vertical:f,horizontal:h},autoHideDuration:p,disableWindowBlurListener:w,TransitionComponent:$,transitionDuration:L},X=$c(H),{getRootProps:ne,onClickAway:K}=wc({...H}),[le,z]=be.useState(!0),te=ge=>{z(!0),I&&I(ge)},se=(ge,he)=>{z(!1),G&&G(ge,he)},ce={slots:{transition:$,...P},slotProps:{content:y,clickAwayListener:v,transition:B,...ee}},[Ie,ae]=s.useSlot("root",{ref:i,className:[X.root,b],elementType:Fc,getSlotProps:ne,externalForwardedProps:{...ce,...Z},ownerState:H}),[de,{ownerState:$e,...qe}]=s.useSlot("clickAwayListener",{elementType:kc,externalForwardedProps:ce,getSlotProps:ge=>({onClickAway:(...he)=>{const ve=he[0];ge.onClickAway?.(...he),!ve?.defaultMuiPrevented&&K(...he)}}),ownerState:H}),[re,Y]=s.useSlot("content",{elementType:Ec,shouldForwardComponentProp:!0,externalForwardedProps:ce,additionalProps:{message:C,action:c},ownerState:H}),[ie,Ce]=s.useSlot("transition",{elementType:s.Grow,externalForwardedProps:ce,getSlotProps:ge=>({onEnter:(...he)=>{ge.onEnter?.(...he),se(...he)},onExited:(...he)=>{ge.onExited?.(...he),te(...he)}}),additionalProps:{appear:!0,in:N,timeout:L,direction:f==="top"?"down":"up"},ownerState:H});return!N&&le?null:t.jsx(de,{...qe,...P.clickAwayListener&&{ownerState:$e},children:t.jsx(Ie,{...ae,children:t.jsx(ie,{...Ce,children:x||t.jsx(re,{...Y})})})})});let is;function Nc(e){is=e}function ko(e){if(is)try{is(e)}catch{}}function Pt(e,r,i){return(async o=>{const d=Date.now();try{const a=await i(o);return ko({type:"console.mutation",resource:e,action:r,ok:!0,durationMs:Date.now()-d}),a}catch(a){throw ko({type:"console.mutation",resource:e,action:r,ok:!1,durationMs:Date.now()-d,reason:a instanceof Error?a.message:"An unknown error occurred"}),a}})}function kn({mutationFn:e,success:r,invalidates:i,closeDialog:o,resource:d,action:a}){const c=Ot.useQueryClient(),[f,h]=O.useState(""),p=s.useMutationWithApiError({mutationFn:Pt(d,a,e),onSuccess(){o();for(const x of i)c.invalidateQueries({queryKey:x});h(r)},onError(x){h(x instanceof Error?x.message:"An unknown error occurred")}});return{mutate:p.mutate,isPending:p.isPending,notice:t.jsx(Ac,{open:f!=="",autoHideDuration:6e3,onClose:()=>h(""),message:f})}}const ji="https://docs.malloydata.dev/documentation",qr=`${ji}/user_guides/publishing`,vn="https://github.com/malloydata/publisher/blob/main/docs",Rt={docsHome:`${ji}/`,publishing:`${qr}/publishing`,explorer:`${qr}/explorer`,mcpAgents:`${qr}/mcp_agents`,surfaces:`${vn}/choosing-a-surface.md`,dashboards:`${vn}/dashboards.md`,dataApps:`${vn}/html-data-apps.md`,givens:`${vn}/givens.md`,materialization:`${vn}/materialization.md`,connections:`${vn}/connections.md`};function Rc({resourceUri:e}){const[r,i]=O.useState(!1),{apiClients:o}=U.useServer(),{environmentName:d}=s.parseResourceUri(e),a=kn({mutationFn(f){return o.packages.createPackage(d,{name:f.name,description:f.description,location:f.location})},success:"Package created",invalidates:[["packages",d]],closeDialog:()=>i(!1),resource:"package",action:"create"}),c=f=>{f.preventDefault();const h=new FormData(f.currentTarget),p=h.get("name")?.toString(),x=h.get("description")?.toString(),b=h.get("location")?.toString();a.mutate({name:p,description:x,location:b})};return t.jsxs(t.Fragment,{children:[t.jsx(s.AddButton,{label:"Package",onClick:()=>i(!0)}),t.jsx(s.AppDialog,{open:r,onClose:()=>i(!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(g.Box,{component:"a",href:Rt.publishing,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary"},children:"package format"}),"."]}),actions:t.jsxs(t.Fragment,{children:[t.jsx(g.Button,{disabled:a.isPending,onClick:()=>i(!1),children:"Cancel"}),t.jsx(g.Button,{type:"submit",form:"package-form",variant:"contained",loading:a.isPending,children:"Create package"})]}),children:t.jsx("form",{onSubmit:c,id:"package-form",children:t.jsxs(g.Stack,{sx:{gap:2},children:[t.jsx(g.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(g.TextField,{id:"description",name:"description",label:"Description",multiline:!0,rows:3,fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(g.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}})]})})}),a.notice]})}const Pc=s.createSvgIcon(t.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function Mr({icon:e,tint:r,label:i,mono:o,description:d,rightLabel:a,trailingAction:c,onClick:f,ariaLabel:h}){const p=!!f,x=b=>{f&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),f(b))};return t.jsxs(g.Box,{onClick:f,onKeyDown:p?x:void 0,role:p?"button":void 0,tabIndex:p?0:void 0,"aria-label":h,sx:b=>({display:"flex",alignItems:"center",gap:1.5,py:1,px:1,mx:-1,cursor:p?"pointer":"default",borderRadius:1.5,transition:"background-color 0.1s","&:hover":p?{backgroundColor:b.palette.mode==="dark"?"rgba(255, 255, 255, 0.08)":"grey.100"}:void 0,"&:focus-visible":p?{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}:void 0}),children:[t.jsx(g.Box,{sx:{width:32,height:32,borderRadius:1,bgcolor:r,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:e}),t.jsxs(g.Box,{sx:{flex:1,minWidth:0,display:"flex",alignItems:"baseline",gap:1.5},children:[t.jsx(g.Typography,{variant:"body2",sx:{...o?{fontFamily:U.MONO_FONT_FAMILY}:{},flexShrink:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i}),d&&t.jsx(g.Typography,{variant:"body2",color:"text.secondary",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:d})]}),a&&t.jsx(g.Typography,{variant:"caption",color:"text.secondary",sx:{flexShrink:0},children:a}),c&&t.jsx(g.Box,{sx:{flexShrink:0,display:"flex",alignItems:"center"},children:c})]})}const Mi=s.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"})),Lc=s.generateUtilityClasses("MuiBox",["root"]),_c=s.createTheme(),We=nr.createBox({themeId:s.THEME_ID,defaultTheme:_c,defaultClassName:Lc.root,generateClassName:s.ClassNameGenerator.generate}),Or=nr.createStack({createStyledComponent:s.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:e=>s.useDefaultProps({props:e,name:"MuiStack"})}),To=s.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function zc(e){return s.generateUtilityClass("MuiListItemIcon",e)}const jo=s.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),Wc=e=>{const{alignItems:r,classes:i}=e,o={root:["root",r==="flex-start"&&"alignItemsFlexStart"]};return s.composeClasses(o,zc,i)},qc=s.styled("div",{name:"MuiListItemIcon",slot:"Root",overridesResolver:(e,r)=>{const{ownerState:i}=e;return[r.root,i.alignItems==="flex-start"&&r.alignItemsFlexStart]}})(s.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}}]}))),gs=be.forwardRef(function(r,i){const o=s.useDefaultProps({props:r,name:"MuiListItemIcon"}),{className:d,...a}=o,c=be.useContext(s.ListContext),f={...o,alignItems:c.alignItems},h=Wc(f);return t.jsx(qc,{className:s.clsx(h.root,d),ownerState:f,ref:i,...a})});function Vc(e){return s.generateUtilityClass("MuiListItemText",e)}const Sn=s.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),Hc=e=>{const{classes:r,inset:i,primary:o,secondary:d,dense:a}=e,c={root:["root",i&&"inset",a&&"dense",o&&d&&"multiline"],primary:["primary"],secondary:["secondary"]};return s.composeClasses(c,Vc,r)},Bc=s.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(e,r)=>{const{ownerState:i}=e;return[{[`& .${Sn.primary}`]:r.primary},{[`& .${Sn.secondary}`]:r.secondary},r.root,i.inset&&r.inset,i.primary&&i.secondary&&r.multiline,i.dense&&r.dense]}})({flex:"1 1 auto",minWidth:0,marginTop:4,marginBottom:4,[`.${s.typographyClasses.root}:where(& .${Sn.primary})`]:{display:"block"},[`.${s.typographyClasses.root}:where(& .${Sn.secondary})`]:{display:"block"},variants:[{props:({ownerState:e})=>e.primary&&e.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:e})=>e.inset,style:{paddingLeft:56}}]}),ys=be.forwardRef(function(r,i){const o=s.useDefaultProps({props:r,name:"MuiListItemText"}),{children:d,className:a,disableTypography:c=!1,inset:f=!1,primary:h,primaryTypographyProps:p,secondary:x,secondaryTypographyProps:b,slots:v={},slotProps:y={},...w}=o,{dense:C}=be.useContext(s.ListContext);let k=h??d,T=x;const j={...o,disableTypography:c,inset:f,primary:!!k,secondary:!!T,dense:C},E=Hc(j),D={slots:v,slotProps:{primary:p,secondary:b,...y}},[N,q]=s.useSlot("root",{className:s.clsx(E.root,a),elementType:Bc,externalForwardedProps:{...D,...w},ownerState:j,ref:i}),[P,ee]=s.useSlot("primary",{className:E.primary,elementType:s.Typography,externalForwardedProps:D,ownerState:j}),[$,L]=s.useSlot("secondary",{className:E.secondary,elementType:s.Typography,externalForwardedProps:D,ownerState:j});return k!=null&&k.type!==s.Typography&&!c&&(k=t.jsx(P,{variant:C?"body2":"body1",component:ee?.variant?void 0:"span",...ee,children:k})),T!=null&&T.type!==s.Typography&&!c&&(T=t.jsx($,{variant:"body2",color:"textSecondary",...L,children:T})),t.jsxs(N,{...q,children:[k,T]})});function Uc(e){return s.generateUtilityClass("MuiMenuItem",e)}const _n=s.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),Gc=(e,r)=>{const{ownerState:i}=e;return[r.root,i.dense&&r.dense,i.divider&&r.divider,!i.disableGutters&&r.gutters]},Yc=e=>{const{disabled:r,dense:i,divider:o,disableGutters:d,selected:a,classes:c}=e,f={root:["root",i&&"dense",r&&"disabled",!d&&"gutters",o&&"divider",a&&"selected"]},h=s.composeClasses(f,Uc,c);return{...c,...h}},Kc=s.styled(s.ButtonBase,{shouldForwardProp:e=>s.rootShouldForwardProp(e)||e==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:Gc})(s.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"}},[`&.${_n.selected}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity),[`&.${_n.focusVisible}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.focusOpacity}`)}},[`&.${_n.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)}},[`&.${_n.focusVisible}`]:{backgroundColor:(e.vars||e).palette.action.focus},[`&.${_n.disabled}`]:{opacity:(e.vars||e).palette.action.disabledOpacity},[`& + .${To.root}`]:{marginTop:e.spacing(1),marginBottom:e.spacing(1)},[`& + .${To.inset}`]:{marginLeft:52},[`& .${Sn.root}`]:{marginTop:0,marginBottom:0},[`& .${Sn.inset}`]:{paddingLeft:36},[`& .${jo.root}`]:{minWidth:36},variants:[{props:({ownerState:r})=>!r.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:r})=>r.divider,style:{borderBottom:`1px solid ${(e.vars||e).palette.divider}`,backgroundClip:"padding-box"}},{props:({ownerState:r})=>!r.dense,style:{[e.breakpoints.up("sm")]:{minHeight:"auto"}}},{props:({ownerState:r})=>r.dense,style:{minHeight:32,paddingTop:4,paddingBottom:4,...e.typography.body2,[`& .${jo.root} svg`]:{fontSize:"1.25rem"}}}]}))),Ge=be.forwardRef(function(r,i){const o=s.useDefaultProps({props:r,name:"MuiMenuItem"}),{autoFocus:d=!1,component:a="li",dense:c=!1,divider:f=!1,disableGutters:h=!1,focusVisibleClassName:p,role:x="menuitem",tabIndex:b,className:v,...y}=o,w=be.useContext(s.ListContext),C=be.useMemo(()=>({dense:c||w.dense||!1,disableGutters:h}),[w.dense,c,h]),k=be.useRef(null);s.useEnhancedEffect(()=>{d&&k.current&&k.current.focus()},[d]);const T={...o,dense:C.dense,divider:f,disableGutters:h},j=Yc(o),E=s.useForkRef(k,i);let D;return o.disabled||(D=b!==void 0?b:-1),t.jsx(s.ListContext.Provider,{value:C,children:t.jsx(Kc,{ref:E,role:x,tabIndex:D,component:a,focusVisibleClassName:s.clsx(j.focusVisible,p),className:s.clsx(j.root,v),...y,ownerState:T,classes:j})})}),Lt={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:[]},Jn={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",trino:"trinoConnection",databricks:"databricksConnection",mysql:"mysqlConnection",sqlserver:"sqlserverConnection",duckdb:"duckdbConnection",motherduck:"motherduckConnection",ducklake:"ducklakeConnection",publisher:"publisherConnection"},Zc={sqlserver:{port:"integer",encrypt:"boolean",trustServerCertificate:"boolean"}},Qc={sqlserver:["hostNameInCertificate","instanceName"]};function Oi(e,r){const i=Zc[e],o=Qc[e];if(!i&&!o)return r;const d={...r};for(const a of o??[])d[a]===""&&delete d[a];for(const[a,c]of Object.entries(i??{})){const f=r[a];if(f!==void 0){if(f===""){delete d[a];continue}if(c==="integer"){const h=Number(f);Number.isInteger(h)&&(d[a]=h)}else(f==="true"||f==="false")&&(d[a]=f==="true")}}return d}const Di=Object.values(U.ConnectionTypeEnum).filter(e=>e!==U.ConnectionTypeEnum.Publisher),as={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},rr=[{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"}}],sr=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],Xc=[{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 kr(e){return e==="postgres"||e==="bigquery"||e==="snowflake"?Lt[e]||[]:e==="s3"?rr:e==="gcs"?sr:e==="azure"?Xc:[]}function Jc({onSubmit:e,isSubmitting:r}){const[i,o]=O.useState(!1),[d,a]=O.useState("postgres"),[c,f]=O.useState([]),[h,p]=O.useState("postgres"),[x,b]=O.useState("s3"),[v,y]=O.useState("config"),w=()=>{o(!0)},C=()=>{o(!1),f([]),a("postgres"),p("postgres"),b("s3"),y("config")},k=async D=>{D.preventDefault();const N=new FormData(D.currentTarget),q=N.get("name")?.toString(),P=N.get("type")?.toString(),ee=Lt[P];if(!q)throw new Error("Name is required");if(!P)throw new Error("Type is required");let $;if(P==="ducklake"){const L={};if(h==="postgres"){const B=Lt.postgres,Z={};if(B.forEach(H=>{const X=N.get(`ducklake_pg_${H.name}`)?.toString();X&&(Z[H.name]=X)}),Object.keys(Z).length===0)throw new Error("DuckLake requires catalog connection");L.postgresConnection=Z}const G=N.get("ducklake_bucketUrl")?.toString();if(!G)throw new Error("DuckLake requires a bucket URL");const I={bucketUrl:G};if(x==="s3"){const B={};if(rr.forEach(Z=>{const H=N.get(`ducklake_s3_${Z.name}`)?.toString();H&&(B[Z.name]=H)}),B.provider==="credential_chain")delete B.accessKeyId,delete B.secretAccessKey,delete B.sessionToken;else{if(delete B.chain,!B.accessKeyId)throw new Error("S3 Access Key ID is required");if(!B.secretAccessKey)throw new Error("S3 Secret Access Key is required")}Object.keys(B).length>0&&(I.s3Connection=B)}else if(x==="gcs"){const B={};if(sr.forEach(Z=>{const H=N.get(`ducklake_gcs_${Z.name}`)?.toString();H&&(B[Z.name]=H)}),!B.keyId)throw new Error("GCS Key ID is required");if(!B.secret)throw new Error("GCS Secret is required");Object.keys(B).length>0&&(I.gcsConnection=B)}$={name:q,type:P,ducklakeConnection:{catalog:L,storage:I}}}else if(P==="duckdb"){if(c.length===0)throw new Error("DuckDB connection must have at least one attached database");const L=c.map((G,I)=>{const B=G.dbType,Z=N.get(`attachedDb_${I}_name`)?.toString();if(!Z)throw new Error(`Attached database at index ${I} must have a name`);const H={name:Z,type:B},X=kr(B);if(X&&X.length>0){const ne={};if(X.forEach(le=>{const z=N.get(`attachedDb_${I}_${le.name}`)?.toString();z&&(ne[le.name]=z)}),B==="s3"){if(ne.provider==="credential_chain")delete ne.accessKeyId,delete ne.secretAccessKey,delete ne.sessionToken;else if(delete ne.chain,!ne.accessKeyId||!ne.secretAccessKey)throw new Error(`Attached database "${Z}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const K=as[B];K&&(H[K]=ne)}return H});$={name:q,type:P,duckdbConnection:{attachedDatabases:L}}}else{const L={};if(ee.forEach(G=>{const I=N.get(G.name)?.toString();I&&(L[G.name]=I)}),P==="postgres"){if(!!!L.connectionString?.trim()){const I=["host","port","databaseName","userName","password"];for(const B of I)if(!L[B])throw new Error(`${ee.find(Z=>Z.name===B)?.label||B} is required`)}}else if(P==="bigquery"){if(!L.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if(P==="snowflake"){if(!L.account)throw new Error("Account is required");if(!L.username)throw new Error("Username is required");if(!L.warehouse)throw new Error("Warehouse is required");if(!L.password&&!L.privateKey)throw new Error("Either password or private key is required")}else if(P==="trino"){if(!L.server)throw new Error("Server is required");if(!L.user)throw new Error("User is required");if(L.server.trim().startsWith("https://")&&!L.password&&!L.peakaKey)throw new Error("Password is required for HTTPS connections (or use Peaka Key)")}else if(P==="mysql"){const G=["host","port","database","user","password"];for(const I of G)if(!L[I])throw new Error(`${ee.find(B=>B.name===I)?.label||I} is required`)}else if(P==="sqlserver"){const G=["server","database","user","password"];if(!L.instanceName&&!L.port)throw new Error("Port is required unless an instance name is given");for(const I of G)if(!L[I])throw new Error(`${ee.find(B=>B.name===I)?.label||I} is required`)}else if(P==="motherduck"){if(!L.accessToken)throw new Error("Access Token is required")}else if(P==="databricks"){if(!L.host)throw new Error("Host is required");if(!L.path)throw new Error("HTTP Path is required");const G=L.oauthClientId&&L.oauthClientSecret;if(!L.token&&!G)throw new Error("Either Access Token or OAuth Client ID + Secret is required")}$={name:q,type:P,[Jn[P]]:Oi(P,L)}}await e($),C()},T=()=>{f([...c,{name:"",dbType:"postgres"}])},j=D=>{f(c.filter((N,q)=>q!==D))},E=(D,N)=>{const q=[...c];q[D]={...q[D],dbType:N},f(q)};return t.jsxs(O.Fragment,{children:[t.jsx(s.AddButton,{label:"Connection",onClick:w}),t.jsx(s.AppDialog,{open:i,onClose:C,title:"New connection",description:"Add a connection so packages in this environment can query your database with Malloy.",actions:t.jsxs(t.Fragment,{children:[t.jsx(s.Button,{disabled:r,onClick:C,children:"Cancel"}),t.jsx(s.Button,{type:"submit",form:"connection-form",variant:"contained",loading:r,children:"Create connection"})]}),children:t.jsx("form",{onSubmit:k,id:"connection-form",children:t.jsxs(Or,{sx:{gap:2},children:[t.jsx(s.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small"}),t.jsx(s.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:d,select:!0,onChange:D=>a(D.target.value),children:Di.map(D=>t.jsx(Ge,{value:D,children:D},D))}),d==="ducklake"?t.jsxs(We,{sx:{mt:2},children:[t.jsxs(We,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(s.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),t.jsx(s.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:h,select:!0,onChange:D=>p(D.target.value),children:t.jsx(Ge,{value:"postgres",children:"PostgreSQL"})}),h==="postgres"&&t.jsx(t.Fragment,{children:Lt.postgres.map(D=>t.jsx(s.TextField,{id:`ducklake_pg_${D.name}`,name:`ducklake_pg_${D.name}`,label:D.label,type:D.type,fullWidth:!0,size:"small"},`pg_${D.name}`))})]}),t.jsxs(We,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(s.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),t.jsxs(s.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:x,select:!0,onChange:D=>b(D.target.value),children:[t.jsx(Ge,{value:"s3",children:"S3"}),t.jsx(Ge,{value:"gcs",children:"GCS"})]}),t.jsx(s.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:x==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small"}),x==="s3"&&t.jsxs(t.Fragment,{children:[t.jsx(s.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),rr.filter(D=>D.visibleWhen?v===D.visibleWhen.value:!0).map(D=>t.jsx(s.TextField,{id:`ducklake_s3_${D.name}`,name:`ducklake_s3_${D.name}`,label:D.label,type:D.selectOptions?void 0:D.type,fullWidth:!0,size:"small",required:D.required,select:!!D.selectOptions,defaultValue:D.selectOptions?v:void 0,onChange:D.name==="provider"?N=>y(N.target.value):void 0,placeholder:D.name==="region"?"us-east-1":void 0,children:D.selectOptions?.map(N=>t.jsx(Ge,{value:N.value,children:N.label},N.value))},`s3_${D.name}`))]}),x==="gcs"&&t.jsxs(t.Fragment,{children:[t.jsx(s.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),sr.map(D=>t.jsx(s.TextField,{id:`ducklake_gcs_${D.name}`,name:`ducklake_gcs_${D.name}`,label:D.label,type:D.type,fullWidth:!0,size:"small",required:D.required},`gcs_${D.name}`))]})]})]}):d==="duckdb"?t.jsxs(We,{sx:{mt:2},children:[t.jsxs(We,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsx(s.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),t.jsx(s.SecondaryButton,{label:"Database",icon:t.jsx(s.AddIcon,{}),onClick:T,ariaLabel:"Add database"})]}),c.length===0&&t.jsx(s.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),c.map((D,N)=>{const q=kr(D.dbType);return t.jsxs(We,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(We,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(s.Typography,{variant:"subtitle2",children:["Database ",N+1]}),t.jsx(s.IconButton,{onClick:()=>j(N),size:"small",color:"error",children:t.jsx(Mi,{fontSize:"small"})})]}),t.jsx(s.TextField,{required:!0,id:`attachedDb_${N}_name`,name:`attachedDb_${N}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:D.name}),t.jsx(s.TextField,{id:`attachedDb_${N}_type`,name:`attachedDb_${N}_type`,label:"Database Type",fullWidth:!0,size:"small",value:D.dbType,select:!0,onChange:P=>E(N,P.target.value),children:Object.values(U.AttachedDatabaseTypeEnum).map(P=>t.jsx(Ge,{value:P,children:P},P))}),q.filter(P=>P.visibleWhen?(D[P.visibleWhen.field]||q.find($=>$.name===P.visibleWhen?.field)?.selectOptions?.[0]?.value)===P.visibleWhen.value:!0).map(P=>t.jsx(s.TextField,{id:`attachedDb_${N}_${P.name}`,name:`attachedDb_${N}_${P.name}`,label:P.label,type:P.selectOptions?void 0:P.type,fullWidth:!0,size:"small",required:P.required,select:!!P.selectOptions,defaultValue:P.selectOptions?.[0]?.value,onChange:P.selectOptions?ee=>{const $=[...c];$[N]={...$[N],[P.name]:ee.target.value},f($)}:void 0,children:P.selectOptions?.map(ee=>t.jsx(Ge,{value:ee.value,children:ee.label},ee.value))},P.name))]},N)})]}):Lt[d].map(D=>t.jsx(s.TextField,{id:D.name,name:D.name,label:D.label,type:D.type,fullWidth:!0,size:"small",required:D.required,select:!!D.selectOptions,defaultValue:D.selectOptions?D.selectOptions[0]?.value:void 0,children:D.selectOptions?.map(N=>t.jsx(Ge,{value:N.value,children:N.label},N.value))},D.name))]})})})]})}function eu({connection:e,onCloseDialog:r,isMutating:i,onDelete:o}){const[d,a]=O.useState(!1),c=()=>{a(!0)},f=()=>{a(!1),r()};return t.jsxs(O.Fragment,{children:[t.jsxs(Ge,{"aria-label":`Delete connection ${e?.name??""}`.trim(),onClick:h=>{h.stopPropagation(),c()},sx:{color:"error.main"},children:[t.jsx(gs,{sx:{color:"inherit"},children:t.jsx(Dt.Delete,{fontSize:"small"})}),t.jsx(ys,{children:"Delete"})]}),t.jsx(s.AppDialog,{open:d,onClose:f,title:"Delete connection",actions:t.jsxs(t.Fragment,{children:[t.jsx(s.Button,{onClick:f,children:"Cancel"}),t.jsx(s.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>o(),loading:i,children:"Delete connection"})]}),children:t.jsxs(s.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:e.name}),"? Packages that query through it stop working, and this cannot be undone."]})})]})}const Mo=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function Oo(e){const r=e.duckdbConnection?.attachedDatabases;return!r||r.length===0?[]:r.map(i=>({name:i.name||"",dbType:i.type||"postgres"}))}function Do(e){const r=e.ducklakeConnection;return r&&r.storage?.gcsConnection?"gcs":"s3"}function tu({connection:e,onSubmit:r,isSubmitting:i,onCloseDialog:o}){const[d,a]=O.useState(!1),[c,f]=O.useState(e.type),h=O.useMemo(()=>new Set(e.withheldFields??[]),[e.withheldFields]),[p,x]=O.useState(()=>Oo(e)),[b,v]=O.useState("postgres"),[y,w]=O.useState(()=>Do(e)),[C,k]=O.useState(()=>e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),T=()=>{x(Oo(e)),f(e.type),k(e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),v("postgres"),w(Do(e)),a(!0)},j=()=>{a(!1),o?.()},E=async $=>{$.preventDefault();const L=new FormData($.currentTarget),G=L.get("name")?.toString(),I=L.get("type")?.toString(),B=Lt[I];if(!G)throw new Error("Name is required");if(!I)throw new Error("Type is required");let Z;if(I==="ducklake"){const H={};if(b==="postgres"){const K=Lt.postgres,le={};if(K.forEach(z=>{const te=L.get(`ducklake_pg_${z.name}`)?.toString();te&&(le[z.name]=te)}),Object.keys(le).length===0)throw new Error("DuckLake requires catalog connection");H.postgresConnection=le}const X=L.get("ducklake_bucketUrl")?.toString();if(!X)throw new Error("DuckLake requires a bucket URL");const ne={bucketUrl:X};if(y==="s3"){const K={};rr.forEach(z=>{const te=L.get(`ducklake_s3_${z.name}`)?.toString();te&&(K[z.name]=te)});const le=e.ducklakeConnection?.storage?.s3Connection;if(le&&(!K.provider&&le.provider&&(K.provider=le.provider),!K.chain&&le.chain&&(K.chain=le.chain),!K.accessKeyId&&le.accessKeyId&&(K.accessKeyId=le.accessKeyId)),K.provider==="credential_chain")delete K.accessKeyId,delete K.secretAccessKey,delete K.sessionToken;else if(delete K.chain,!K.accessKeyId)throw new Error("S3 Access Key ID is required");Object.keys(K).length>0&&(ne.s3Connection=K)}else if(y==="gcs"){const K={};sr.forEach(z=>{const te=L.get(`ducklake_gcs_${z.name}`)?.toString();te&&(K[z.name]=te)});const le=e.ducklakeConnection?.storage?.gcsConnection;if(le&&!K.keyId&&le.keyId&&(K.keyId=le.keyId),!K.keyId)throw new Error("GCS Key ID is required");Object.keys(K).length>0&&(ne.gcsConnection=K)}Z={name:G,type:I,ducklakeConnection:{catalog:H,storage:ne}}}else if(I==="duckdb"){if(p.length===0)throw new Error("DuckDB connection must have at least one attached database");const H=p.map((X,ne)=>{const K=X.dbType,le=L.get(`attachedDb_${ne}_name`)?.toString();if(!le)throw new Error(`Attached database at index ${ne} must have a name`);const z={name:le,type:K},te=kr(K);if(te&&te.length>0){const se={};if(te.forEach(Ie=>{const ae=L.get(`attachedDb_${ne}_${Ie.name}`)?.toString();ae&&(se[Ie.name]=ae)}),K==="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 "${le}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const ce=as[K];ce&&(z[ce]=se)}return z});Z={name:G,type:I,duckdbConnection:{attachedDatabases:H}}}else{const H=e[Jn[I]]||{},X={};if(B.forEach(ne=>{const K=L.get(ne.name)?.toString(),le=H[ne.name];K?X[ne.name]=K:Mo.has(ne.name)||(K!==void 0?X[ne.name]=K:le&&(X[ne.name]=le))}),I==="postgres"){const ne=["host","port","databaseName","userName"],K=h.has("postgresConnection.connectionString");if(!(!!X.connectionString?.trim()||K)){const z=ne;for(const te of z)if(!X[te])throw new Error(`${B.find(se=>se.name===te)?.label||te} is required`)}}else if(I==="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(I==="trino"){if(!X.server)throw new Error("Server is required");if(!X.user)throw new Error("User is required")}else if(I==="mysql"){const ne=["host","port","database","user"];for(const K of ne)if(!X[K])throw new Error(`${B.find(le=>le.name===K)?.label||K} is required`)}else if(I==="sqlserver"){const ne=["server","database","user"];if(!X.instanceName&&!X.port)throw new Error("Port is required unless an instance name is given");for(const K of ne)if(!X[K])throw new Error(`${B.find(le=>le.name===K)?.label||K} is required`)}else if(I==="databricks"){if(!X.host)throw new Error("Host is required");if(!X.path)throw new Error("HTTP Path is required")}Z={name:G,type:I,[Jn[I]]:Oi(I,X)}}await r(Z),j()},D=()=>{x([...p,{name:"",dbType:"postgres"}])},N=$=>{x(p.filter((L,G)=>G!==$))},q=($,L)=>{const G=[...p];G[$]={...G[$],dbType:L},x(G)},P=($,L)=>{const G=e.duckdbConnection?.attachedDatabases;if(!G||!G[$])return"";const I=G[$],B=as[I.type||""];return B&&I[B]?I[B][L]??"":""},ee=$=>{const L=e.ducklakeConnection;if(!L)return"";if($.startsWith("pg_")){const G=$.replace("pg_","");return L.catalog?.postgresConnection?.[G]??""}if($==="bucketUrl")return L.storage?.bucketUrl??"";if($.startsWith("s3_")){const G=$.replace("s3_","");return L.storage?.s3Connection?.[G]??""}if($.startsWith("gcs_")){const G=$.replace("gcs_","");return L.storage?.gcsConnection?.[G]??""}return""};return t.jsxs(O.Fragment,{children:[t.jsxs(Ge,{"aria-label":`Edit connection ${e?.name??""}`.trim(),onClick:$=>{$.preventDefault(),$.stopPropagation(),T()},children:[t.jsx(gs,{children:t.jsx(Dt.Edit,{fontSize:"small"})}),t.jsx(ys,{children:"Edit"})]}),t.jsx(s.AppDialog,{open:d,onClose:j,title:"Edit connection",description:"Change how packages in this environment reach your database.",actions:t.jsxs(t.Fragment,{children:[t.jsx(s.Button,{disabled:i,onClick:j,children:"Cancel"}),t.jsx(s.Button,{type:"submit",form:"connection-form",variant:"contained",loading:i,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:E,id:"connection-form",children:t.jsxs(Or,{sx:{gap:2},children:[t.jsx(s.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",defaultValue:e.name}),t.jsx(s.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:c,select:!0,onChange:$=>f($.target.value),children:Di.map($=>t.jsx(Ge,{value:$,children:$},$))}),c==="ducklake"?t.jsxs(We,{sx:{mt:2},children:[t.jsxs(We,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(s.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),t.jsx(s.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:b,select:!0,onChange:$=>v($.target.value),children:t.jsx(Ge,{value:"postgres",children:"PostgreSQL"})}),b==="postgres"&&t.jsx(t.Fragment,{children:Lt.postgres.map($=>t.jsx(s.TextField,{id:`ducklake_pg_${$.name}`,name:`ducklake_pg_${$.name}`,label:$.label,type:$.type,fullWidth:!0,size:"small",defaultValue:ee(`pg_${$.name}`)},`pg_${$.name}`))})]}),t.jsxs(We,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(s.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),t.jsxs(s.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:y,select:!0,onChange:$=>w($.target.value),children:[t.jsx(Ge,{value:"s3",children:"S3"}),t.jsx(Ge,{value:"gcs",children:"GCS"})]}),t.jsx(s.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:y==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small",defaultValue:ee("bucketUrl")}),y==="s3"&&t.jsxs(t.Fragment,{children:[t.jsx(s.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),rr.filter($=>$.visibleWhen?C===$.visibleWhen.value:!0).map($=>t.jsx(s.TextField,{id:`ducklake_s3_${$.name}`,name:`ducklake_s3_${$.name}`,label:$.label,type:$.selectOptions?void 0:$.type,fullWidth:!0,size:"small",required:$.required&&$.name!=="secretAccessKey",select:!!$.selectOptions,defaultValue:$.selectOptions?C:ee(`s3_${$.name}`),onChange:$.name==="provider"?L=>k(L.target.value):void 0,placeholder:$.name==="region"?"us-east-1":$.name==="secretAccessKey"&&h.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:$.selectOptions?.map(L=>t.jsx(Ge,{value:L.value,children:L.label},L.value))},`s3_${$.name}`))]}),y==="gcs"&&t.jsxs(t.Fragment,{children:[t.jsx(s.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),sr.map($=>t.jsx(s.TextField,{id:`ducklake_gcs_${$.name}`,name:`ducklake_gcs_${$.name}`,label:$.label,type:$.type,fullWidth:!0,size:"small",required:$.required&&$.name!=="secret",defaultValue:ee(`gcs_${$.name}`),placeholder:$.name==="secret"&&h.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${$.name}`))]})]})]}):c==="duckdb"?t.jsxs(We,{sx:{mt:2},children:[t.jsxs(We,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsx(s.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),t.jsx(s.SecondaryButton,{label:"Database",icon:t.jsx(s.AddIcon,{}),onClick:D,ariaLabel:"Add database"})]}),p.length===0&&t.jsx(s.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),p.map(($,L)=>{const G=kr($.dbType);return t.jsxs(We,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(We,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(s.Typography,{variant:"subtitle2",children:["Database ",L+1]}),t.jsx(s.IconButton,{"aria-label":`Remove attached database ${L+1}`,onClick:()=>N(L),size:"small",color:"error",children:t.jsx(Mi,{fontSize:"small"})})]}),t.jsx(s.TextField,{required:!0,id:`attachedDb_${L}_name`,name:`attachedDb_${L}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:$.name}),t.jsx(s.TextField,{id:`attachedDb_${L}_type`,name:`attachedDb_${L}_type`,label:"Database Type",fullWidth:!0,size:"small",value:$.dbType,select:!0,onChange:I=>q(L,I.target.value),children:Object.values(U.AttachedDatabaseTypeEnum).map(I=>t.jsx(Ge,{value:I,children:I},I))}),G.filter(I=>I.visibleWhen?($[I.visibleWhen.field]||P(L,I.visibleWhen.field)||G.find(Z=>Z.name===I.visibleWhen?.field)?.selectOptions?.[0]?.value)===I.visibleWhen.value:!0).map(I=>t.jsx(s.TextField,{id:`attachedDb_${L}_${I.name}`,name:`attachedDb_${L}_${I.name}`,label:I.label,type:I.selectOptions?void 0:I.type,fullWidth:!0,size:"small",required:I.required,select:!!I.selectOptions,defaultValue:P(L,I.name)||I.selectOptions?.[0]?.value,onChange:I.selectOptions?B=>{const Z=[...p];Z[L]={...Z[L],[I.name]:B.target.value},x(Z)}:void 0,children:I.selectOptions?.map(B=>t.jsx(Ge,{value:B.value,children:B.label},B.value))},I.name))]},L)})]}):Lt[c].map($=>{const L=e?.[Jn[c]??""]?.[$.name??""]??"",G=$.type==="password"||Mo.has($.name),I=h.has(`${Jn[c]??""}.${$.name}`),B=$.selectOptions?L===""||L===void 0?$.selectOptions[0]?.value:String(L):void 0;return t.jsx(s.TextField,{id:$.name,name:$.name,label:$.label,type:$.type,fullWidth:!0,size:"small",required:$.required&&!G&&!L,select:!!$.selectOptions,defaultValue:$.selectOptions?B:L,placeholder:I?"Leave empty to keep existing":void 0,helperText:G?I?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0,children:$.selectOptions?.map(Z=>t.jsx(Ge,{value:Z.value,children:Z.label},Z.value))},$.name)})]})})})]})}function Eo(e,r){return!e||e.type!=="duckdb"?!1:(e.duckdbConnection?.attachedDatabases||[]).some(o=>o.type==="azure"&&o.name===r)}function nu(e){return e.startsWith("gs://")||e.startsWith("s3://")||e.startsWith("https://")||e.startsWith("abfss://")||e.startsWith("az://")}function Ei({connectionName:e,resourceUri:r,schema:i,connection:o}){const{apiClients:d}=U.useServer(),{environmentName:a}=s.parseResourceUri(r),[c,f]=O.useState(null),[h,p]=O.useState(i||null),[x,b]=O.useState(!1),{data:v,isError:y,isLoading:w,error:C}=s.useQueryWithApiError({queryKey:["schemas",a,e],queryFn:()=>d.connections.listSchemas(a,e)}),k=v?.data||[];return t.jsxs(g.Grid,{container:!0,spacing:1,children:[!i&&t.jsx(g.Grid,{size:{xs:12,md:4},children:t.jsxs(g.Paper,{sx:{p:1,m:0},children:[t.jsxs(g.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:0},children:[t.jsx(g.Typography,{variant:"overline",fontWeight:"bold",children:"Table Paths"}),t.jsx(g.FormControlLabel,{control:t.jsx(g.Switch,{checked:x,onChange:T=>b(T.target.checked)}),label:"Hidden Schemas"})]}),t.jsx(g.Divider,{sx:{mt:"2px"}}),t.jsxs(g.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[w&&t.jsx(s.Loading,{text:"Loading schemas..."}),y&&t.jsx(s.ApiErrorDisplay,{error:C,context:`${a} > ${e} > Schemas`}),!w&&!y&&k.length===0&&t.jsx(g.Typography,{variant:"body2",children:"No Schemas"}),!w&&!y&&k.length>0&&t.jsx(g.List,{dense:!0,disablePadding:!0,children:k.map(T=>{const j=T.name;if(T.isHidden&&!x)return null;const D=h===j;return t.jsx(g.ListItemButton,{selected:D,onClick:()=>{p(j),f(null)},children:t.jsx(g.ListItemText,{primary:j})},j)})})]})]})}),t.jsx(g.Grid,{size:{xs:12,md:i?6:4},children:h&&t.jsx(g.Paper,{sx:{p:1,m:0},children:t.jsx(ou,{connectionName:e,schemaName:h,onTableSelect:T=>{f(T)},resourceUri:r,connection:o})})}),t.jsx(g.Grid,{size:{xs:12,md:i?6:4},children:h&&c&&t.jsx(ru,{environmentName:a,connectionName:e,schemaName:h,tableResource:c})})]})}function ru({environmentName:e,connectionName:r,schemaName:i,tableResource:o}){const{apiClients:d}=U.useServer(),{data:a,isLoading:c,isError:f,error:h}=s.useQueryWithApiError({queryKey:["connectionTableDetail",e,r,i,o],queryFn:()=>d.connections.getTable(e,r,i,o),enabled:!!i&&!!o}),p={resource:a?.data?.resource??o,columns:a?.data?.columns??[]};return t.jsxs(g.Paper,{sx:{p:1,m:0},children:[f&&t.jsx(s.ApiErrorDisplay,{error:h,context:`${e} > ${r} > ${i} > ${o}`}),!f&&t.jsx(su,{table:p,loading:c})]})}function su({table:e,loading:r}){return r?t.jsx(s.Loading,{text:"Loading columns..."}):t.jsxs(t.Fragment,{children:[t.jsxs(g.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(g.Divider,{}),t.jsx(g.Box,{sx:{mt:"10px",maxHeight:"600px",overflowY:"auto"},children:t.jsx(g.TableContainer,{children:t.jsxs(g.Table,{size:"small",sx:{"& .MuiTableCell-root":{padding:"10px"}},children:[t.jsx(g.TableHead,{children:t.jsxs(g.TableRow,{children:[t.jsx(g.TableCell,{children:"NAME"}),t.jsx(g.TableCell,{children:"TYPE"})]})}),t.jsx(g.TableBody,{children:e.columns?.sort((i,o)=>i.name.localeCompare(o.name))?.map(i=>t.jsxs(g.TableRow,{children:[t.jsx(g.TableCell,{children:i.name}),t.jsx(g.TableCell,{children:i.type})]},i.name))})]})})})]})}function ou({connectionName:e,schemaName:r,onTableSelect:i,resourceUri:o,connection:d}){const{environmentName:a}=s.parseResourceUri(o),{apiClients:c}=U.useServer(),[f,h]=O.useState(""),{data:p,isSuccess:x,isError:b,error:v,isLoading:y}=s.useQueryWithApiError({queryKey:["tablesInSchema",a,e,r],queryFn:()=>c.connections.listTables(a,e,r)}),w=Eo(d,r),C=T=>w?T:T.split(".").pop()||T,k=x&&p?.data?p.data.filter(T=>C(T.resource).toLowerCase().includes(f.toLowerCase())).sort((T,j)=>C(T.resource).localeCompare(C(j.resource))):[];return t.jsxs(t.Fragment,{children:[t.jsx(g.Typography,{variant:"overline",fontWeight:"bold",children:nu(r)||Eo(d,r)?`Files in ${r}`:`Tables in ${r}`}),t.jsx(g.Divider,{}),t.jsx(g.Box,{sx:{mt:1,mb:1},children:t.jsx(g.TextField,{size:"small",fullWidth:!0,placeholder:"Search tables...",value:f,onChange:T=>h(T.target.value),variant:"outlined"})}),t.jsx(g.Divider,{}),t.jsxs(g.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[y&&t.jsx(s.Loading,{text:"Fetching Tables..."}),b&&t.jsx(s.ApiErrorDisplay,{error:v,context:`${a} > ${e} > ${r}`}),x&&k.length===0&&t.jsx(g.Typography,{variant:"body2",children:"No Tables"}),x&&p?.data&&p.data.length>0&&t.jsx(g.List,{dense:!0,disablePadding:!0,children:k.map(T=>{let j=C(T.resource);return!w&&T.resource.includes("://")&&(j=T.resource.split("/").pop()||T.resource),t.jsx(g.ListItemButton,{onClick:()=>i(T.resource),children:t.jsx(g.ListItemText,{primary:j,secondary:T.columns.length>0?`${T.columns.length} columns`:void 0})},T.resource)})})]})]})}const iu={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 au(e){return e?iu[e]??e:""}function lu({resourceUri:e}){const{apiClients:r,mutable:i}=U.useServer(),o=Ot.useQueryClient(),{environmentName:d}=s.parseResourceUri(e),[a,c]=O.useState(""),[f,h]=O.useState(null),p=s.encodeResourceUri({environmentName:d,connectionName:f}),{data:x,isSuccess:b,isError:v,error:y}=s.useQueryWithApiError({queryKey:["connections",d],queryFn:()=>r.connections.listConnections(d)}),w=s.useMutationWithApiError({mutationFn:Pt("connection","create",E=>r.environments.updateEnvironment(d,{name:d,connections:[...x.data,E]})),onSuccess(){c("Connection added successfully"),o.invalidateQueries({queryKey:["connections",d]})},onError(E){c(E.message)}}),C=s.useMutationWithApiError({mutationFn:Pt("connection","update",E=>r.environments.updateEnvironment(d,{name:d,connections:x.data.map(D=>D.name===E.name?E:D)})),onSuccess(E,D){c(`Connection ${D.name} updated successfully`),o.invalidateQueries({queryKey:["connections",d]})},onError(E){c(E.message)}}),k=s.useMutationWithApiError({mutationFn:Pt("connection","delete",E=>{if(!E.name)throw new Error("Cannot delete a connection with no name");return r.connections.deleteConnection(d,E.name)}),onSuccess(E,D){c(`Connection ${D.name} deleted successfully`),o.invalidateQueries({queryKey:["connections",d]})},onError(E){c(E.message)}}),T=b?[...x.data].sort((E,D)=>(E.name??"").localeCompare(D.name??"")):[],j=w.isPending||C.isPending||k.isPending;return t.jsxs(Mt,{title:"Connections",...b?{count:T.length}:{},description:"Database connections available to packages in this environment",...i&&b?{action:t.jsx(Jc,{onSubmit:E=>w.mutateAsync(E),isSubmitting:w.isPending})}:{},children:[!b&&!v&&t.jsx(g.Typography,{variant:"body2",color:"text.secondary",children:"Fetching Connections..."}),v&&t.jsx(s.ApiErrorDisplay,{error:y,context:`${d} > Connections`}),b&&T.length===0&&t.jsx(g.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),b&&T.length>0&&t.jsx(g.Stack,{children:T.map(E=>t.jsx(cu,{connection:E,mutable:i,isMutating:j,onOpenExplorer:()=>h(E.name??null),onEdit:D=>C.mutateAsync(D),onDelete:D=>k.mutateAsync(D)},E.name))}),t.jsx(g.Snackbar,{open:a!=="",autoHideDuration:6e3,onClose:()=>c(""),message:a}),t.jsx(s.AppDialog,{open:f!==null,onClose:()=>h(null),maxWidth:"lg",title:`Connection explorer: ${f??""}`,showClose:!0,children:f&&t.jsx(Ei,{resourceUri:p,connectionName:f,connection:x?.data?.find(E=>E.name===f)})})]})}function cu({connection:e,mutable:r,isMutating:i,onOpenExplorer:o,onEdit:d,onDelete:a}){const[c,f]=O.useState(null),h=!!c,p=b=>{b.stopPropagation(),f(b.currentTarget)},x=()=>f(null);return t.jsx(Mr,{icon:t.jsx(Pc,{sx:{fontSize:18}}),tint:U.SURFACE_TINT.connection,label:e.name??"",ariaLabel:e.name??"",description:au(e.type),onClick:o,...r?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(g.IconButton,{size:"small",onClick:p,"aria-label":`Connection actions for ${e.name??""}`.trim(),children:t.jsx(Dt.MoreVert,{fontSize:"small"})}),t.jsxs(g.Menu,{anchorEl:c,open:h,onClose:x,onClick:b=>b.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[t.jsx(tu,{connection:e,onSubmit:d,isSubmitting:i,onCloseDialog:x}),t.jsx(eu,{connection:e,onCloseDialog:x,isMutating:i,onDelete:()=>a(e)})]})]})}:{}})}const uu=s.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 du({resourceUri:e,onCloseDialog:r}){const[i,o]=O.useState(!1),{apiClients:d}=U.useServer(),a=()=>{o(!0)},c=()=>{o(!1),r()},{environmentName:f,packageName:h}=s.parseResourceUri(e),p=kn({mutationFn:()=>d.packages.deletePackage(f,h),success:"Package deleted",invalidates:[["packages",f]],closeDialog:c,resource:"package",action:"delete"});return t.jsxs(O.Fragment,{children:[t.jsxs(g.MenuItem,{onClick:a,children:[t.jsx(g.ListItemIcon,{children:t.jsx(Dt.Delete,{fontSize:"small"})}),t.jsx(g.ListItemText,{children:"Delete"})]}),t.jsx(s.AppDialog,{open:i,onClose:c,title:"Delete package",actions:t.jsxs(t.Fragment,{children:[t.jsx(s.Button,{onClick:c,children:"Cancel"}),t.jsx(s.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>p.mutate(),loading:p.isPending,children:"Delete package"})]}),children:t.jsxs(s.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:h}),"? The package stops being served and this cannot be undone."]})}),p.notice]})}function hu({package:e,resourceUri:r,onCloseDialog:i}){const[o,d]=O.useState(!1),{apiClients:a}=U.useServer(),c=()=>{d(!0)},f=()=>{d(!1),i()},{packageName:h,environmentName:p}=s.parseResourceUri(r),x=kn({mutationFn(v){return a.packages.updatePackage(p,h,{name:h,description:v.description})},success:"Package updated",invalidates:[["packages",p]],closeDialog:f,resource:"package",action:"update"}),b=v=>{v.preventDefault();const w=new FormData(v.currentTarget).get("description")?.toString();x.mutate({description:w})};return t.jsxs(O.Fragment,{children:[t.jsxs(g.MenuItem,{onClick:c,children:[t.jsx(g.ListItemIcon,{children:t.jsx(Dt.Edit,{fontSize:"small"})}),t.jsx(g.ListItemText,{children:"Edit"})]}),t.jsx(s.AppDialog,{open:o,onClose:f,title:"Edit package",description:`What ${e.name} is, for the people who open it.`,actions:t.jsxs(t.Fragment,{children:[t.jsx(s.Button,{disabled:x.isPending,onClick:f,children:"Cancel"}),t.jsx(s.Button,{type:"submit",form:"package-form",variant:"contained",loading:x.isPending,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:b,id:"package-form",children:t.jsxs(g.Stack,{sx:{gap:2},children:[t.jsx(s.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(s.TextField,{id:"description",name:"description",label:"Description",multiline:!0,fullWidth:!0,rows:4,size:"small",defaultValue:e.description,InputLabelProps:{shrink:!0}})]})})}),x.notice]})}function Ii({onSelectPackage:e,resourceUri:r}){const{apiClients:i}=U.useServer(),{environmentName:o}=s.parseResourceUri(r),{data:d,isSuccess:a,isError:c,error:f}=s.useQueryWithApiError({queryKey:["packages",o],queryFn:()=>i.packages.listPackages(o)});if(c)return t.jsx(s.ApiErrorDisplay,{error:f,context:`${o} > Packages`});if(!a)return t.jsx(s.Loading,{text:"Fetching Packages..."});const h=[...d.data].sort((p,x)=>p.name.localeCompare(x.name));return t.jsx(g.Stack,{children:h.map(p=>{const x=s.encodeResourceUri({environmentName:o,packageName:p.name});return t.jsx(fu,{pkg:p,packageResourceUri:x,onSelectPackage:e},p.name)})})}function fu({pkg:e,packageResourceUri:r,onSelectPackage:i}){const{mutable:o}=U.useServer(),d=e.versionId!==void 0||e.latestVersion!==void 0,[a,c]=O.useState(null),f=!!a,h=x=>{x.stopPropagation(),c(x.currentTarget)},p=()=>c(null);return t.jsx(Mr,{icon:t.jsx(uu,{sx:{fontSize:18}}),tint:U.SURFACE_TINT.package,label:e.name,ariaLabel:e.name,...e.description?{description:e.description}:{},onClick:x=>i(e.name,x),...o?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(g.IconButton,{size:"small",onClick:h,"aria-label":`Package actions for ${e.name}`,children:t.jsx(Dt.MoreVert,{fontSize:"small"})}),t.jsxs(g.Menu,{anchorEl:a,open:f,onClose:p,onClick:x=>x.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[!d&&t.jsx(hu,{package:e,resourceUri:r,onCloseDialog:p}),t.jsx(du,{resourceUri:r,onCloseDialog:p})]})]})}:{}})}function pu({onSelectPackage:e,resourceUri:r}){const{apiClients:i,mutable:o}=U.useServer(),{environmentName:d}=s.parseResourceUri(r),a=s.useQueryWithApiError({queryKey:["packages",d],queryFn:()=>i.packages.listPackages(d)});return O.useEffect(()=>{window.scrollTo({top:0,behavior:"auto"})},[]),t.jsxs(g.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsxs(g.Box,{sx:{mb:4},children:[t.jsx(g.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em",mb:.5},children:d}),t.jsx(g.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(Mt,{title:"Packages",...a.isSuccess?{count:a.data.data.length}:{},description:"Published packages available for use in this environment",...o?{action:t.jsx(Rc,{resourceUri:r})}:{},children:t.jsx(Ii,{onSelectPackage:e,resourceUri:r})}),t.jsx(lu,{resourceUri:r}),t.jsx(Sc,{resourceUri:r})]})}function Io({array1:e,array2:r,parser:i=o=>o}){return e&&r&&e.length===r.length&&e.every((o,d)=>i(o)===i(r[d]))}function $o(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}function mu(e={}){const{ignoreAccents:r=!0,ignoreCase:i=!0,limit:o,matchFrom:d="any",stringify:a,trim:c=!1}=e;return(f,{inputValue:h,getOptionLabel:p})=>{let x=c?h.trim():h;i&&(x=x.toLowerCase()),r&&(x=$o(x));const b=x?f.filter(v=>{let y=(a||p)(v);return i&&(y=y.toLowerCase()),r&&(y=$o(y)),d==="start"?y.startsWith(x):y.includes(x)}):f;return typeof o=="number"?b.slice(0,o):b}}const gu=mu(),Fo=5,yu=e=>e.current!==null&&e.current.parentElement?.contains(document.activeElement),xu=[];function Ao(e,r,i,o){if(r||e==null||o)return"";const d=i(e);return typeof d=="string"?d:""}function vu(e){const{unstable_isActiveElementInListbox:r=yu,unstable_classNamePrefix:i="Mui",autoComplete:o=!1,autoHighlight:d=!1,autoSelect:a=!1,blurOnSelect:c=!1,clearOnBlur:f=!e.freeSolo,clearOnEscape:h=!1,componentName:p="useAutocomplete",defaultValue:x=e.multiple?xu:null,disableClearable:b=!1,disableCloseOnSelect:v=!1,disabled:y,disabledItemsFocusable:w=!1,disableListWrap:C=!1,filterOptions:k=gu,filterSelectedOptions:T=!1,freeSolo:j=!1,getOptionDisabled:E,getOptionKey:D,getOptionLabel:N=V=>V.label??V,groupBy:q,handleHomeEndKeys:P=!e.freeSolo,id:ee,includeInputInList:$=!1,inputValue:L,isOptionEqualToValue:G=(V,W)=>V===W,multiple:I=!1,onChange:B,onClose:Z,onHighlightChange:H,onInputChange:X,onOpen:ne,open:K,openOnFocus:le=!1,options:z,readOnly:te=!1,renderValue:se,selectOnFocus:ce=!e.freeSolo,value:Ie}=e,ae=s.useId(ee);let de=N;de=V=>{const W=N(V);return typeof W!="string"?String(W):W};const $e=be.useRef(!1),qe=be.useRef(!0),re=be.useRef(null),Y=be.useRef(null),[ie,Ce]=be.useState(null),[ge,he]=be.useState(-1),ve=d?0:-1,Oe=be.useRef(ve),Re=be.useRef(Ao(x??Ie,I,de)).current,[_,me]=s.useControlled({controlled:Ie,default:x,name:p}),[pe,Fe]=s.useControlled({controlled:L,default:Re,name:p,state:"inputValue"}),[Le,ct]=be.useState(!1),pt=be.useCallback((V,W,oe)=>{if(!(I?_.length<W.length:W!==null)&&!f)return;const J=Ao(W,I,de,se);pe!==J&&(Fe(J),X&&X(V,J,oe))},[de,pe,I,X,Fe,f,_,se]),[tt,mt]=s.useControlled({controlled:K,default:!1,name:p,state:"open"}),[Vt,Et]=be.useState(!0),St=!I&&_!=null&&pe===de(_),Qe=tt&&!te,ue=Qe?k(z.filter(V=>!(T&&(I?_:[_]).some(W=>W!==null&&G(V,W)))),{inputValue:St&&Vt?"":pe,getOptionLabel:de}):[],Ye=ec({filteredOptions:ue,value:_,inputValue:pe});be.useEffect(()=>{const V=_!==Ye.value;Le&&!V||j&&!V||pt(null,_,"reset")},[_,pt,Le,Ye.value,j]);const _e=tt&&ue.length>0&&!te,nt=s.useEventCallback(V=>{if(V===-1)re.current.focus();else{const W=se?"data-item-index":"data-tag-index";ie.querySelector(`[${W}="${V}"]`).focus()}});be.useEffect(()=>{I&&ge>_.length-1&&(he(-1),nt(-1))},[_,I,ge,nt]);function at(V,W){if(!Y.current||V<0||V>=ue.length)return-1;let oe=V;for(;;){const xe=Y.current.querySelector(`[data-option-index="${oe}"]`),J=w?!1:!xe||xe.disabled||xe.getAttribute("aria-disabled")==="true";if(xe&&xe.hasAttribute("tabindex")&&!J)return oe;if(W==="next"?oe=(oe+1)%ue.length:oe=(oe-1+ue.length)%ue.length,oe===V)return-1}}const rt=s.useEventCallback(({event:V,index:W,reason:oe})=>{if(Oe.current=W,W===-1?re.current.removeAttribute("aria-activedescendant"):re.current.setAttribute("aria-activedescendant",`${ae}-option-${W}`),H&&["mouse","keyboard","touch"].includes(oe)&&H(V,W===-1?null:ue[W],oe),!Y.current)return;const xe=Y.current.querySelector(`[role="option"].${i}-focused`);xe&&(xe.classList.remove(`${i}-focused`),xe.classList.remove(`${i}-focusVisible`));let J=Y.current;if(Y.current.getAttribute("role")!=="listbox"&&(J=Y.current.parentElement.querySelector('[role="listbox"]')),!J)return;if(W===-1){J.scrollTop=0;return}const Ae=Y.current.querySelector(`[data-option-index="${W}"]`);if(Ae&&(Ae.classList.add(`${i}-focused`),oe==="keyboard"&&Ae.classList.add(`${i}-focusVisible`),J.scrollHeight>J.clientHeight&&oe!=="mouse"&&oe!=="touch")){const Pe=Ae,dt=J.clientHeight+J.scrollTop,ln=Pe.offsetTop+Pe.offsetHeight;ln>dt?J.scrollTop=ln-J.clientHeight:Pe.offsetTop-Pe.offsetHeight*(q?1.3:0)<J.scrollTop&&(J.scrollTop=Pe.offsetTop-Pe.offsetHeight*(q?1.3:0))}}),fe=s.useEventCallback(({event:V,diff:W,direction:oe="next",reason:xe})=>{if(!Qe)return;const Ae=at((()=>{const Pe=ue.length-1;if(W==="reset")return ve;if(W==="start")return 0;if(W==="end")return Pe;const dt=Oe.current+W;return dt<0?dt===-1&&$?-1:C&&Oe.current!==-1||Math.abs(W)>1?0:Pe:dt>Pe?dt===Pe+1&&$?-1:C||Math.abs(W)>1?Pe:0:dt})(),oe);if(rt({index:Ae,reason:xe,event:V}),o&&W!=="reset")if(Ae===-1)re.current.value=pe;else{const Pe=de(ue[Ae]);re.current.value=Pe,Pe.toLowerCase().indexOf(pe.toLowerCase())===0&&pe.length>0&&re.current.setSelectionRange(pe.length,Pe.length)}}),Ve=!Io({array1:Ye.filteredOptions,array2:ue,parser:de}),gt=()=>{const V=(W,oe)=>{const xe=W?de(W):"",J=oe?de(oe):"";return xe===J};if(Oe.current!==-1&&!Io({array1:Ye.filteredOptions,array2:ue,parser:de})&&Ye.inputValue===pe&&(I?_.length===Ye.value.length&&Ye.value.every((W,oe)=>de(_[oe])===de(W)):V(Ye.value,_))){const W=Ye.filteredOptions[Oe.current];if(W)return ue.findIndex(oe=>de(oe)===de(W))}return-1},ut=be.useCallback(()=>{if(!Qe)return;const V=gt();if(V!==-1){Oe.current=V;return}const W=I?_[0]:_;if(ue.length===0||W==null){fe({diff:"reset"});return}if(Y.current){if(W!=null){const oe=ue[Oe.current];if(I&&oe&&_.findIndex(J=>G(oe,J))!==-1)return;const xe=ue.findIndex(J=>G(J,W));xe===-1?fe({diff:"reset"}):rt({index:xe});return}if(Oe.current>=ue.length-1){rt({index:ue.length-1});return}rt({index:Oe.current})}},[ue.length,I?!1:_,T,fe,rt,Qe,pe,I]),Xe=s.useEventCallback(V=>{s.setRef(Y,V),V&&ut()});be.useEffect(()=>{Ve&&ut()},[ut,Ve]);const ze=V=>{tt||(mt(!0),Et(!0),ne&&ne(V))},Je=(V,W)=>{tt&&(mt(!1),Z&&Z(V,W))},yt=(V,W,oe,xe)=>{if(I){if(_.length===W.length&&_.every((J,Ae)=>J===W[Ae]))return}else if(_===W)return;B&&B(V,W,oe,xe),me(W)},xt=be.useRef(!1),wt=(V,W,oe="selectOption",xe="options")=>{let J=oe,Ae=W;if(I){Ae=Array.isArray(_)?_.slice():[];const Pe=Ae.findIndex(dt=>G(W,dt));Pe===-1?Ae.push(W):xe!=="freeSolo"&&(Ae.splice(Pe,1),J="removeOption")}pt(V,Ae,J),yt(V,Ae,J,{option:W}),!v&&(!V||!V.ctrlKey&&!V.metaKey)&&Je(V,J),(c===!0||c==="touch"&&xt.current||c==="mouse"&&!xt.current)&&re.current.blur()};function rn(V,W){if(V===-1)return-1;let oe=V;for(;;){if(W==="next"&&oe===_.length||W==="previous"&&oe===-1)return-1;const xe=se?"data-item-index":"data-tag-index",J=ie.querySelector(`[${xe}="${oe}"]`);if(!J||!J.hasAttribute("tabindex")||J.disabled||J.getAttribute("aria-disabled")==="true")oe+=W==="next"?1:-1;else return oe}}const It=(V,W)=>{if(!I)return;pe===""&&Je(V,"toggleInput");let oe=ge;ge===-1?pe===""&&W==="previous"&&(oe=_.length-1):(oe+=W==="next"?1:-1,oe<0&&(oe=0),oe===_.length&&(oe=-1)),oe=rn(oe,W),he(oe),nt(oe)},Ht=V=>{$e.current=!0,Fe(""),X&&X(V,"","clear"),yt(V,I?[]:null,"clear")},sn=V=>W=>{if(V.onKeyDown&&V.onKeyDown(W),!W.defaultMuiPrevented&&(ge!==-1&&!["ArrowLeft","ArrowRight"].includes(W.key)&&(he(-1),nt(-1)),W.which!==229))switch(W.key){case"Home":Qe&&P&&(W.preventDefault(),fe({diff:"start",direction:"next",reason:"keyboard",event:W}));break;case"End":Qe&&P&&(W.preventDefault(),fe({diff:"end",direction:"previous",reason:"keyboard",event:W}));break;case"PageUp":W.preventDefault(),fe({diff:-Fo,direction:"previous",reason:"keyboard",event:W}),ze(W);break;case"PageDown":W.preventDefault(),fe({diff:Fo,direction:"next",reason:"keyboard",event:W}),ze(W);break;case"ArrowDown":W.preventDefault(),fe({diff:1,direction:"next",reason:"keyboard",event:W}),ze(W);break;case"ArrowUp":W.preventDefault(),fe({diff:-1,direction:"previous",reason:"keyboard",event:W}),ze(W);break;case"ArrowLeft":!I&&se?nt(0):It(W,"previous");break;case"ArrowRight":!I&&se?nt(-1):It(W,"next");break;case"Enter":if(Oe.current!==-1&&Qe){const oe=ue[Oe.current],xe=E?E(oe):!1;if(W.preventDefault(),xe)return;wt(W,oe,"selectOption"),o&&re.current.setSelectionRange(re.current.value.length,re.current.value.length)}else j&&pe!==""&&St===!1&&(I&&W.preventDefault(),wt(W,pe,"createOption","freeSolo"));break;case"Escape":Qe?(W.preventDefault(),W.stopPropagation(),Je(W,"escape")):h&&(pe!==""||I&&_.length>0||se)&&(W.preventDefault(),W.stopPropagation(),Ht(W));break;case"Backspace":if(I&&!te&&pe===""&&_.length>0){const oe=ge===-1?_.length-1:ge,xe=_.slice();xe.splice(oe,1),yt(W,xe,"removeOption",{option:_[oe]})}!I&&se&&!te&&(me(null),nt(-1));break;case"Delete":if(I&&!te&&pe===""&&_.length>0&&ge!==-1){const oe=ge,xe=_.slice();xe.splice(oe,1),yt(W,xe,"removeOption",{option:_[oe]})}!I&&se&&!te&&(me(null),nt(-1));break}},Ee=V=>{ct(!0),le&&!$e.current&&ze(V)},et=V=>{if(r(Y)){re.current.focus();return}ct(!1),qe.current=!0,$e.current=!1,a&&Oe.current!==-1&&Qe?wt(V,ue[Oe.current],"blur"):a&&j&&pe!==""?wt(V,pe,"blur","freeSolo"):f&&pt(V,_,"blur"),Je(V,"blur")},_t=V=>{const W=V.target.value;pe!==W&&(Fe(W),Et(!1),X&&X(V,W,"input")),W===""?!b&&!I&&yt(V,null,"clear"):ze(V)},on=V=>{const W=Number(V.currentTarget.getAttribute("data-option-index"));Oe.current!==W&&rt({event:V,index:W,reason:"mouse"})},st=V=>{rt({event:V,index:Number(V.currentTarget.getAttribute("data-option-index")),reason:"touch"}),xt.current=!0},Bt=V=>{const W=Number(V.currentTarget.getAttribute("data-option-index"));wt(V,ue[W],"selectOption"),xt.current=!1},an=V=>W=>{const oe=_.slice();oe.splice(V,1),yt(W,oe,"removeOption",{option:_[V]})},zt=V=>{yt(V,null,"removeOption",{option:_})},He=V=>{tt?Je(V,"toggleInput"):ze(V)},Be=V=>{V.currentTarget.contains(V.target)&&V.target.getAttribute("id")!==ae&&V.preventDefault()},Ct=V=>{V.currentTarget.contains(V.target)&&(re.current.focus(),ce&&qe.current&&re.current.selectionEnd-re.current.selectionStart===0&&re.current.select(),qe.current=!1)},Ut=V=>{!y&&(pe===""||!tt)&&He(V)};let Wt=j&&pe.length>0;Wt=Wt||(I?_.length>0:_!==null);let Gt=ue;return q&&(Gt=ue.reduce((V,W,oe)=>{const xe=q(W);return V.length>0&&V[V.length-1].group===xe?V[V.length-1].options.push(W):V.push({key:oe,index:oe,group:xe,options:[W]}),V},[])),y&&Le&&et(),{getRootProps:(V={})=>({...V,onKeyDown:sn(V),onMouseDown:Be,onClick:Ct}),getInputLabelProps:()=>({id:`${ae}-label`,htmlFor:ae}),getInputProps:()=>({id:ae,value:pe,onBlur:et,onFocus:Ee,onChange:_t,onMouseDown:Ut,"aria-activedescendant":Qe?"":null,"aria-autocomplete":o?"both":"list","aria-controls":_e?`${ae}-listbox`:void 0,"aria-expanded":_e,autoComplete:"off",ref:re,autoCapitalize:"none",spellCheck:"false",role:"combobox",disabled:y}),getClearProps:()=>({tabIndex:-1,type:"button",onClick:Ht}),getItemProps:({index:V=0}={})=>({...I&&{key:V},...se?{"data-item-index":V}:{"data-tag-index":V},tabIndex:-1,...!te&&{onDelete:I?an(V):zt}}),getPopupIndicatorProps:()=>({tabIndex:-1,type:"button",onClick:He}),getTagProps:({index:V})=>({key:V,"data-tag-index":V,tabIndex:-1,...!te&&{onDelete:an(V)}}),getListboxProps:()=>({role:"listbox",id:`${ae}-listbox`,"aria-labelledby":`${ae}-label`,ref:Xe,onMouseDown:V=>{V.preventDefault()}}),getOptionProps:({index:V,option:W})=>{const oe=(I?_:[_]).some(J=>J!=null&&G(W,J)),xe=E?E(W):!1;return{key:D?.(W)??de(W),tabIndex:-1,role:"option",id:`${ae}-option-${V}`,onMouseMove:on,onClick:Bt,onTouchStart:st,"data-option-index":V,"aria-disabled":xe,"aria-selected":oe}},id:ae,inputValue:pe,value:_,dirty:Wt,expanded:Qe&&ie,popupOpen:Qe,focused:Le||ge!==-1,anchorEl:ie,setAnchorEl:Ce,focusedItem:ge,focusedTag:ge,groupedOptions:Gt}}function bu(e){return s.generateUtilityClass("MuiListSubheader",e)}s.generateUtilityClasses("MuiListSubheader",["root","colorPrimary","colorInherit","gutters","inset","sticky"]);const Su=e=>{const{classes:r,color:i,disableGutters:o,inset:d,disableSticky:a}=e,c={root:["root",i!=="default"&&`color${s.capitalize(i)}`,!o&&"gutters",d&&"inset",!a&&"sticky"]};return s.composeClasses(c,bu,r)},wu=s.styled("li",{name:"MuiListSubheader",slot:"Root",overridesResolver:(e,r)=>{const{ownerState:i}=e;return[r.root,i.color!=="default"&&r[`color${s.capitalize(i.color)}`],!i.disableGutters&&r.gutters,i.inset&&r.inset,!i.disableSticky&&r.sticky]}})(s.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:r})=>!r.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:r})=>r.inset,style:{paddingLeft:72}},{props:({ownerState:r})=>!r.disableSticky,style:{position:"sticky",top:0,zIndex:1,backgroundColor:(e.vars||e).palette.background.paper}}]}))),ls=be.forwardRef(function(r,i){const o=s.useDefaultProps({props:r,name:"MuiListSubheader"}),{className:d,color:a="default",component:c="li",disableGutters:f=!1,disableSticky:h=!1,inset:p=!1,...x}=o,b={...o,color:a,component:c,disableGutters:f,disableSticky:h,inset:p},v=Su(b);return t.jsx(wu,{as:c,className:s.clsx(v.root,d),ref:i,ownerState:b,...x})});ls&&(ls.muiSkipListHighlight=!0);const Cu=s.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 ku(e){return s.generateUtilityClass("MuiAutocomplete",e)}const Te=s.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 No,Ro;const Tu=e=>{const{classes:r,disablePortal:i,expanded:o,focused:d,fullWidth:a,hasClearIcon:c,hasPopupIcon:f,inputFocused:h,popupOpen:p,size:x}=e,b={root:["root",o&&"expanded",d&&"focused",a&&"fullWidth",c&&"hasClearIcon",f&&"hasPopupIcon"],inputRoot:["inputRoot"],input:["input",h&&"inputFocused"],tag:["tag",`tagSize${s.capitalize(x)}`],endAdornment:["endAdornment"],clearIndicator:["clearIndicator"],popupIndicator:["popupIndicator",p&&"popupIndicatorOpen"],popper:["popper",i&&"popperDisablePortal"],paper:["paper"],listbox:["listbox"],loading:["loading"],noOptions:["noOptions"],option:["option"],groupLabel:["groupLabel"],groupUl:["groupUl"]};return s.composeClasses(b,ku,r)},ju=s.styled("div",{name:"MuiAutocomplete",slot:"Root",overridesResolver:(e,r)=>{const{ownerState:i}=e,{fullWidth:o,hasClearIcon:d,hasPopupIcon:a,inputFocused:c,size:f}=i;return[{[`& .${Te.tag}`]:r.tag},{[`& .${Te.tag}`]:r[`tagSize${s.capitalize(f)}`]},{[`& .${Te.inputRoot}`]:r.inputRoot},{[`& .${Te.input}`]:r.input},{[`& .${Te.input}`]:c&&r.inputFocused},r.root,o&&r.fullWidth,a&&r.hasPopupIcon,d&&r.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}},[`& .${s.inputClasses.root}`]:{paddingBottom:1,"& .MuiInput-input":{padding:"4px 4px 4px 0px"}},[`& .${s.inputClasses.root}.${s.inputBaseClasses.sizeSmall}`]:{[`& .${s.inputClasses.input}`]:{padding:"2px 4px 3px 0"}},[`& .${s.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}},[`& .${s.outlinedInputClasses.root}.${s.inputBaseClasses.sizeSmall}`]:{paddingTop:6,paddingBottom:6,paddingLeft:6,[`& .${Te.input}`]:{padding:"2.5px 4px 2.5px 8px"}},[`& .${s.filledInputClasses.root}`]:{paddingTop:19,paddingLeft:8,[`.${Te.hasPopupIcon}&, .${Te.hasClearIcon}&`]:{paddingRight:39},[`.${Te.hasPopupIcon}.${Te.hasClearIcon}&`]:{paddingRight:65},[`& .${s.filledInputClasses.input}`]:{padding:"7px 4px"},[`& .${Te.endAdornment}`]:{right:9}},[`& .${s.filledInputClasses.root}.${s.inputBaseClasses.sizeSmall}`]:{paddingBottom:1,[`& .${s.filledInputClasses.input}`]:{padding:"2.5px 4px"}},[`& .${s.inputBaseClasses.hiddenLabel}`]:{paddingTop:8},[`& .${s.filledInputClasses.root}.${s.inputBaseClasses.hiddenLabel}`]:{paddingTop:0,paddingBottom:0,[`& .${Te.input}`]:{paddingTop:16,paddingBottom:17}},[`& .${s.filledInputClasses.root}.${s.inputBaseClasses.hiddenLabel}.${s.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"}}}]}),Mu=s.styled("div",{name:"MuiAutocomplete",slot:"EndAdornment"})({position:"absolute",right:0,top:"50%",transform:"translate(0, -50%)"}),Ou=s.styled(s.IconButton,{name:"MuiAutocomplete",slot:"ClearIndicator"})({marginRight:-2,padding:4,visibility:"hidden"}),Du=s.styled(s.IconButton,{name:"MuiAutocomplete",slot:"PopupIndicator",overridesResolver:(e,r)=>{const{ownerState:i}=e;return[r.popupIndicator,i.popupOpen&&r.popupIndicatorOpen]}})({padding:2,marginRight:-2,variants:[{props:{popupOpen:!0},style:{transform:"rotate(180deg)"}}]}),Eu=s.styled(s.Popper,{name:"MuiAutocomplete",slot:"Popper",overridesResolver:(e,r)=>{const{ownerState:i}=e;return[{[`& .${Te.option}`]:r.option},r.popper,i.disablePortal&&r.popperDisablePortal]}})(s.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.modal,variants:[{props:{disablePortal:!0},style:{position:"absolute"}}]}))),Iu=s.styled(s.Paper,{name:"MuiAutocomplete",slot:"Paper"})(s.memoTheme(({theme:e})=>({...e.typography.body1,overflow:"auto"}))),$u=s.styled("div",{name:"MuiAutocomplete",slot:"Loading"})(s.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Fu=s.styled("div",{name:"MuiAutocomplete",slot:"NoOptions"})(s.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Au=s.styled("ul",{name:"MuiAutocomplete",slot:"Listbox"})(s.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}`)}}}}))),Nu=s.styled(ls,{name:"MuiAutocomplete",slot:"GroupLabel"})(s.memoTheme(({theme:e})=>({backgroundColor:(e.vars||e).palette.background.paper,top:-8}))),Ru=s.styled("ul",{name:"MuiAutocomplete",slot:"GroupUl"})({padding:0,[`& .${Te.option}`]:{paddingLeft:24}}),cs=be.forwardRef(function(r,i){const o=s.useDefaultProps({props:r,name:"MuiAutocomplete"}),{autoComplete:d=!1,autoHighlight:a=!1,autoSelect:c=!1,blurOnSelect:f=!1,ChipProps:h,className:p,clearIcon:x=No||(No=t.jsx(Cu,{fontSize:"small"})),clearOnBlur:b=!o.freeSolo,clearOnEscape:v=!1,clearText:y="Clear",closeText:w="Close",componentsProps:C,defaultValue:k=o.multiple?[]:null,disableClearable:T=!1,disableCloseOnSelect:j=!1,disabled:E=!1,disabledItemsFocusable:D=!1,disableListWrap:N=!1,disablePortal:q=!1,filterOptions:P,filterSelectedOptions:ee=!1,forcePopupIcon:$="auto",freeSolo:L=!1,fullWidth:G=!1,getLimitTagsText:I=je=>`+${je}`,getOptionDisabled:B,getOptionKey:Z,getOptionLabel:H,isOptionEqualToValue:X,groupBy:ne,handleHomeEndKeys:K=!o.freeSolo,id:le,includeInputInList:z=!1,inputValue:te,limitTags:se=-1,ListboxComponent:ce,ListboxProps:Ie,loading:ae=!1,loadingText:de="Loading…",multiple:$e=!1,noOptionsText:qe="No options",onChange:re,onClose:Y,onHighlightChange:ie,onInputChange:Ce,onOpen:ge,open:he,openOnFocus:ve=!1,openText:Oe="Open",options:Re,PaperComponent:_,PopperComponent:me,popupIcon:pe=Ro||(Ro=t.jsx(s.ArrowDropDownIcon,{})),readOnly:Fe=!1,renderGroup:Le,renderInput:ct,renderOption:pt,renderTags:tt,renderValue:mt,selectOnFocus:Vt=!o.freeSolo,size:Et="medium",slots:St={},slotProps:Qe={},value:ue,...Ye}=o,{getRootProps:_e,getInputProps:nt,getInputLabelProps:at,getPopupIndicatorProps:rt,getClearProps:fe,getItemProps:Ve,getListboxProps:gt,getOptionProps:ut,value:Xe,dirty:ze,expanded:Je,id:yt,popupOpen:xt,focused:wt,focusedItem:rn,anchorEl:It,setAnchorEl:Ht,inputValue:sn,groupedOptions:Ee}=vu({...o,componentName:"Autocomplete"}),et=!T&&!E&&ze&&!Fe,_t=(!L||$===!0)&&$!==!1,{onMouseDown:on}=nt(),{ref:st,...Bt}=gt(),zt=H||(je=>je.label??je),He={...o,disablePortal:q,expanded:Je,focused:wt,fullWidth:G,getOptionLabel:zt,hasClearIcon:et,hasPopupIcon:_t,inputFocused:rn===-1,popupOpen:xt,size:Et},Be=Tu(He),Ct={slots:{paper:_,popper:me,...St},slotProps:{chip:h,listbox:Ie,...C,...Qe}},[Ut,Wt]=s.useSlot("listbox",{elementType:Au,externalForwardedProps:Ct,ownerState:He,className:Be.listbox,additionalProps:Bt,ref:st}),[Gt,V]=s.useSlot("paper",{elementType:s.Paper,externalForwardedProps:Ct,ownerState:He,className:Be.paper}),[W,oe]=s.useSlot("popper",{elementType:s.Popper,externalForwardedProps:Ct,ownerState:He,className:Be.popper,additionalProps:{disablePortal:q,style:{width:It?It.clientWidth:null},role:"presentation",anchorEl:It,open:xt}});let xe;const J=je=>({className:Be.tag,disabled:E,...Ve(je)});if($e?Xe.length>0&&(tt?xe=tt(Xe,J,He):mt?xe=mt(Xe,J,He):xe=Xe.map((je,$t)=>{const{key:it,...At}=J({index:$t});return t.jsx(s.Chip,{label:zt(je),size:Et,...At,...Ct.slotProps.chip},it)})):mt&&Xe!=null&&(xe=mt(Xe,J,He)),se>-1&&Array.isArray(xe)){const je=xe.length-se;!wt&&je>0&&(xe=xe.splice(0,se),xe.push(t.jsx("span",{className:Be.tag,children:I(je)},xe.length)))}const Pe=Le||(je=>t.jsxs("li",{children:[t.jsx(Nu,{className:Be.groupLabel,ownerState:He,component:"div",children:je.group}),t.jsx(Ru,{className:Be.groupUl,ownerState:He,children:je.children})]},je.key)),ln=pt||((je,$t)=>{const{key:it,...At}=je;return t.jsx("li",{...At,children:zt($t)},it)}),Tn=(je,$t)=>{const it=ut({option:je,index:$t});return ln({...it,className:Be.option},je,{selected:it["aria-selected"],index:$t,inputValue:sn},He)},jn=Ct.slotProps.clearIndicator,ir=Ct.slotProps.popupIndicator;return t.jsxs(be.Fragment,{children:[t.jsx(ju,{ref:i,className:s.clsx(Be.root,p),ownerState:He,..._e(Ye),children:ct({id:yt,disabled:E,fullWidth:!0,size:Et==="small"?"small":void 0,InputLabelProps:at(),InputProps:{ref:Ht,className:Be.inputRoot,startAdornment:xe,onMouseDown:je=>{je.target===je.currentTarget&&on(je)},...(et||_t)&&{endAdornment:t.jsxs(Mu,{className:Be.endAdornment,ownerState:He,children:[et?t.jsx(Ou,{...fe(),"aria-label":y,title:y,ownerState:He,...jn,className:s.clsx(Be.clearIndicator,jn?.className),children:x}):null,_t?t.jsx(Du,{...rt(),disabled:E,"aria-label":xt?w:Oe,title:xt?w:Oe,ownerState:He,...ir,className:s.clsx(Be.popupIndicator,ir?.className),children:pe}):null]})}},inputProps:{className:Be.input,disabled:E,readOnly:Fe,...nt()}})}),It?t.jsx(Eu,{as:W,...oe,children:t.jsxs(Iu,{as:Gt,...V,children:[ae&&Ee.length===0?t.jsx($u,{className:Be.loading,ownerState:He,children:de}):null,Ee.length===0&&!L&&!ae?t.jsx(Fu,{className:Be.noOptions,ownerState:He,role:"presentation",onMouseDown:je=>{je.preventDefault()},children:qe}):null,Ee.length>0?t.jsx(Ut,{as:ce,...Wt,children:Ee.map((je,$t)=>ne?Pe({key:je.key,group:je.group,children:je.options.map((it,At)=>Tn(it,je.index+At))}):Tn(je,$t))}):null]})}):null]})});s.dayjs.extend(s.utc);function Vr(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 Pu(e){return e==="DateMinMax"}function Hr(e){return e==="Between"}function Lu({spec:e,values:r,selection:i,onChange:o,retrievalFn:d}){const a=()=>i?.matchType?i.matchType:e.defaultMatchType?e.defaultMatchType:e.filterType==="DateMinMax"?"Between":Vr(e.filterType)[0]||"Equals",[c,f]=O.useState(a()),[h,p]=O.useState(i?.value??""),[x,b]=O.useState(i?.value2??""),[v,y]=O.useState([]),[w,C]=O.useState(!1),[k,T]=O.useState(""),[j,E]=O.useState(!1),[D,N]=O.useState(!1),q=O.useRef(null),P=O.useRef(0),[ee,$]=O.useState(!1);O.useEffect(()=>{if(e.filterType!=="Retrieval"||!d)return;const z=k.trim();if(z.length<=2){y([]),E(!1);return}return q.current&&clearTimeout(q.current),q.current=setTimeout(async()=>{P.current+=1;const te=P.current;C(!0);try{const se=await d(z,e);te===P.current&&y(se)}catch(se){te===P.current&&(console.error("Retrieval failed",se),y([]))}finally{te===P.current&&(C(!1),E(!0))}},500),()=>{q.current&&clearTimeout(q.current)}},[k,e,d]),O.useEffect(()=>{i===null?(p(""),b(""),f(e.defaultMatchType??(e.filterType==="DateMinMax"?"Between":Vr(e.filterType)[0]||"Equals"))):i&&(f(i.matchType),p(i.value??""),b(i.value2??""))},[i,e.filterType,e.defaultMatchType]);const L=Vr(e.filterType),G=Pu(e.filterType),I=Hr(c),B=G&&r.length>=2&&r[0].value instanceof Date?s.dayjs.utc(r[0].value):void 0,Z=G&&r.length>=2&&r[1].value instanceof Date?s.dayjs.utc(r[1].value):void 0,H=e.filterType==="MinMax"&&r.length>=2&&typeof r[0].value=="number"?r[0].value:void 0,X=e.filterType==="MinMax"&&r.length>=2&&typeof r[1].value=="number"?r[1].value:void 0;if(L.length===0)return null;const ne=z=>{const te=z.target.value;f(te),Hr(te)||b(""),h&&o({dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:te,value:h,...Hr(te)&&x&&{value2:x}})},K=(z,te)=>{p(z??""),te!==void 0&&b(te??"");const se=Array.isArray(z)&&z.length===0;o(!se&&z!==""&&z!==null&&z!==void 0?{dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:c,value:z,...I&&te&&{value2:te}}:null)},le=()=>{p(""),b(""),o(null)};return t.jsxs(We,{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(We,{sx:{fontWeight:600,color:e.required&&!i?"error.main":"text.primary"},children:[e.label??e.dimensionName,e.required&&t.jsx(We,{component:"span",sx:{color:i?"text.secondary":"error.main",fontWeight:400,fontSize:"0.7rem",ml:.5},children:"(required)"})]}),e.filterType!=="Boolean"&&!e.defaultMatchType&&L.length>1&&t.jsxs(s.FormControl,{size:"small",fullWidth:!0,children:[t.jsx(s.InputLabel,{children:"Match Type"}),t.jsx(s.Select,{value:c,label:"Match Type",onChange:ne,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:L.map(z=>t.jsx(Ge,{value:z,children:z},z))})]}),e.filterType==="Star"&&c==="Equals"&&t.jsx(cs,{multiple:!0,size:"small",options:r,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(h)?h.map(z=>r.find(te=>te.value===z)||z):h?[r.find(z=>z.value===h)||h]:[],onChange:(z,te)=>{const se=te.map(ce=>typeof ce=="string"?ce:ce&&typeof ce=="object"&&"value"in ce?ce.value:ce);K(se)},noOptionsText:"No matches found",renderInput:z=>t.jsx(s.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"&&c==="Contains"&&t.jsx(s.TextField,{size:"small",label:"Search Text",value:h,onChange:z=>p(z.target.value),onBlur:()=>K(h),onKeyDown:z=>{z.key==="Enter"&&K(h)},placeholder:"Enter text to search...",fullWidth:!0}),e.filterType==="Boolean"&&t.jsxs(s.FormControl,{size:"small",fullWidth:!0,children:[t.jsx(s.InputLabel,{children:"Value"}),t.jsxs(s.Select,{value:h===!0?"true":h===!1?"false":"",label:"Value",onChange:z=>{const te=z.target.value;te==="true"?K(!0):te==="false"?K(!1):le()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[t.jsx(Ge,{value:"",children:t.jsx("em",{children:"Blank"})}),t.jsx(Ge,{value:"true",children:"True"}),t.jsx(Ge,{value:"false",children:"False"})]})]}),e.filterType==="Retrieval"&&c==="Semantic Search"&&t.jsx(cs,{multiple:!0,size:"small",options:v,loading:w,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(h)?h.map(z=>v.find(se=>se.value===z)||{value:z}):h?[{value:h}]:[],onInputChange:(z,te)=>{T(te)},onChange:(z,te)=>{const se=te.map(ce=>typeof ce=="string"?ce:ce&&typeof ce=="object"&&"value"in ce?ce.value:ce);K(se)},noOptionsText:k.trim().length<=2?"Type at least 3 characters to search":"No matches found",renderInput:z=>t.jsx(s.TextField,{...z,size:"small",label:"Search Values",placeholder:"Type to search...",onFocus:()=>N(!0),onBlur:()=>N(!1),helperText:D&&!w&&j&&v.length===0?"No matches found":void 0,InputProps:{...z.InputProps,endAdornment:t.jsxs(t.Fragment,{children:[w?t.jsx(s.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"&&!I&&t.jsx(s.TextField,{size:"small",type:"number",label:"Value",value:h,onChange:z=>K(parseFloat(z.target.value)||""),onFocus:()=>$(!0),onBlur:()=>$(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:H,max:X},helperText:ee&&H!==void 0&&X!==void 0?`Valid range: [${H} - ${X}]`:void 0}),e.filterType==="MinMax"&&I&&t.jsxs(We,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(We,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(s.TextField,{size:"small",type:"number",label:"From",value:h,onChange:z=>K(parseFloat(z.target.value)||"",x),onFocus:()=>$(!0),onBlur:()=>$(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:H,max:x||X}}),t.jsx(We,{children:"to"}),t.jsx(s.TextField,{size:"small",type:"number",label:"To",value:x,onChange:z=>K(h,parseFloat(z.target.value)||""),onFocus:()=>$(!0),onBlur:()=>$(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:h||H,max:X}})]}),ee&&H!==void 0&&X!==void 0&&t.jsxs(s.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",H," - ",X,"]"]})]}),G&&!I&&t.jsx(s.LocalizationProvider,{dateAdapter:s.AdapterDayjs,children:t.jsx(s.DatePicker,{label:"Date",value:h instanceof Date?s.dayjs.utc(h):null,onChange:z=>{z===null?K(null):z.isValid()&&K(z.utc().toDate())},timezone:"UTC",minDate:h instanceof Date?void 0:B,maxDate:h instanceof Date?void 0:Z,referenceDate:c==="After"&&B?B:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>$(!0),onBlur:()=>$(!1),helperText:ee&&B&&Z?`Valid range: [${B.format("YYYY-MM-DD")} - ${Z.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),G&&I&&t.jsx(s.LocalizationProvider,{dateAdapter:s.AdapterDayjs,children:t.jsxs(We,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(We,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(We,{sx:{flex:1,minWidth:0},children:t.jsx(s.DatePicker,{label:"From",value:h instanceof Date?s.dayjs.utc(h):null,onChange:z=>{z===null?K(null,x):z.isValid()&&K(z.utc().toDate(),x)},timezone:"UTC",minDate:h instanceof Date?void 0:B,maxDate:x instanceof Date?s.dayjs.utc(x):h instanceof Date?void 0:Z,referenceDate:B,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>$(!0),onBlur:()=>$(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),t.jsx(We,{children:"to"}),t.jsx(We,{sx:{flex:1,minWidth:0},children:t.jsx(s.DatePicker,{label:"To",value:x instanceof Date?s.dayjs.utc(x):null,onChange:z=>{z===null?K(h,null):z.isValid()&&K(h,z.utc().toDate())},timezone:"UTC",minDate:h instanceof Date?s.dayjs.utc(h):x instanceof Date?void 0:B,maxDate:x instanceof Date?void 0:Z,referenceDate:h instanceof Date?s.dayjs.utc(h):B,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>$(!0),onBlur:()=>$(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),ee&&B&&Z&&t.jsxs(s.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",B.format("YYYY-MM-DD")," -"," ",Z.format("YYYY-MM-DD"),"]"]})]})})]})}function _u(e){const r=new Set,i=e.schema?.fields;if(!i)return r;for(const o of i)"kind"in o&&o.kind==="join"&&o.name&&r.add(o.name);return r}function zu(e){if(!e)return null;for(const r of e)if(r.startsWith("##(filters)")){const i=r.slice(11).trim();try{const o=JSON.parse(i);if(Array.isArray(o)){const d=[];for(const a of o)if(typeof a=="string"){const c=a.indexOf(".");c>0&&c<a.length-1&&d.push({source:a.substring(0,c),dimension:a.substring(c+1)})}if(d.length>0)return{filters:d}}}catch(o){console.error(`Failed to parse "${r}" annotation:`,o)}}return null}function $i(e){if(e.startsWith("#(filter)")){const r=e.slice(9).trim();try{const i=JSON.parse(r);if(i.type)return i}catch(i){console.error(`Failed to parse "${e}" annotation:`,i)}}return null}function Wu(e){const r=e.match(/^#\s*label\s*=\s*"([^"]+)"/);return r?r[1]:null}function qu(e){const r=new Map;let i="";for(const o of e)if(o.type==="code"){if(!i&&o.text){const a=o.text.split(`
4
4
  `).map(c=>c.trim()).find(c=>c.startsWith("import "))?.match(/['"]([^'"\n]+)['"]/);a&&(i=a[1])}if(o.newSources&&o.newSources.length>0)for(const d of o.newSources)try{const a=JSON.parse(d);a.name&&r.set(a.name,a)}catch(a){console.error("Failed to parse SourceInfo:",a)}}return{sourceInfoMap:r,modelPath:i}}function Vu(e,r,i){const o=[];for(const{source:d,dimension:a}of r){const c=e.get(d);if(!c){console.warn(`Source "${d}" not found in notebook sources`),o.push({source:d,model:i,dimensionName:a,filterType:"Star"});continue}const f=c.schema?.fields;if(!f){o.push({source:d,model:i,dimensionName:a,filterType:"Star"});continue}const h=f.find(b=>b.name===a);if(!h){console.warn(`Dimension "${a}" not found in source "${d}"`),o.push({source:d,model:i,dimensionName:a,filterType:"Star"});continue}let p="Star",x;if("annotations"in h&&h.annotations){for(const b of h.annotations)if(b.value){const v=$i(b.value);v&&(p=v.type);const y=Wu(b.value);y&&(x=y)}}o.push({source:d,model:i,dimensionName:a,filterType:p,label:x})}return o}function Hu(e,r,i){return e.length===0?"":e.map(d=>{const{dimensionName:a,source:c,matchType:f,value:h,value2:p}=d,b=c&&c!==i?`\`${c}\`.\`${a}\``:`\`${a}\``,v=h instanceof Date,y=(w,C=!1)=>w==null?"null":C&&w instanceof Date?`@${w.getFullYear()}-${String(w.getMonth()+1).padStart(2,"0")}-${String(w.getDate()).padStart(2,"0")}`:typeof w=="string"?`'${s.escapeMalloyString(w)}'`:typeof w=="boolean"?w?"true":"false":String(w);switch(f){case"Equals":case"Semantic Search":return Array.isArray(h)&&h.length>0?`(${h.map(C=>`${b} = ${y(C,v)}`).join(" or ")})`:`${b} = ${y(h,v)}`;case"Contains":return typeof h=="string"?`${b} ~ f'%${s.escapeMalloyString(h)}%'`:`${b} = ${y(h)}`;case"After":case"Greater Than":return`${b} > ${y(h,v)}`;case"Before":case"Less Than":return`${b} < ${y(h,v)}`;case"Between":return p!==void 0?`${b} >= ${y(h,v)} and ${b} <= ${y(p,v)}`:`${b} >= ${y(h,v)}`;default:return""}}).filter(d=>d.length>0).join(" and ")}function Bu(e){const r=e.match(/run\s*:\s*(\w+)\s*->/);if(r)return r[1];const i=e.match(/^\s*(\w+)\s*->/m);return i?i[1]:null}function Uu(e,r){return`${e.trimEnd()} + {where: ${r}}`}const Gu=s.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"})),Fi=e=>{if(!e)return"Explore semantic models, run queries, and build reports";const r=e.replace(/^#+\s+/gm,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/`([^`]+)`/g,"$1").trim(),o=r.split(/\n\s*\n/)[1]||r;if(o.length<=120)return o;const d=o.substring(0,120).split(" ");return d.pop(),d.join(" ")+"..."},Ai=(e,r)=>{const i=(e.readme||void 0)?.split(`
package/dist/index.es.js CHANGED
@@ -2,15 +2,15 @@ import { jsx as r, jsxs as C, Fragment as xe } from "react/jsx-runtime";
2
2
  import { Link as Vu, useMediaQuery as Hu, Stack as Le, Typography as re, Button as Ze, Menu as Mn, MenuItem as Yt, Box as te, Tooltip as sn, Dialog as _i, DialogTitle as qi, IconButton as Vt, DialogContent as zi, DialogActions as Uu, Alert as ct, TextField as Un, Grid as hr, Paper as Oi, FormControlLabel as Js, Switch as el, Divider as Dn, List as tl, ListItemButton as nl, ListItemText as Wt, TableContainer as Bu, Table as No, TableHead as Po, TableRow as En, TableCell as Ee, TableBody as Ao, Snackbar as ro, ListItemIcon as fn, Container as To, FormGroup as ju, Chip as rl, AlertTitle as Gu, ButtonBase as Ku, InputBase as Zu, InputAdornment as Yu, alpha as Xu, CircularProgress as Qu, LinearProgress as Ju } from "@mui/material";
3
3
  import * as we from "react";
4
4
  import Me, { useState as X, useCallback as Ke, useMemo as Be, useRef as mt, useEffect as ut, Fragment as ed, useId as ol } from "react";
5
- import { n as _e, bk as Bn, bl as Ar, bm as td, bn as Ga, bo as nd, bp as rd, bq as od, br as id, bs as il, bt as Wi, bu as Vi, al as Qr, bv as Hi, aw as ad, aG as Ui, bw as al, bx as sd, by as Fo, aF as sl, bz as ld, ar as cd, aH as ud, au as Mi, J as dd, aN as hd, ac as fd, G as md, bA as pd, aJ as ll, aL as gd, aM as yd, aK as vd, a4 as bd, P as wd, ag as cl, aO as Bi, ae as ul, a1 as Ro, $ as pr, aB as dt, bB as We, aI as At, S as oo, b6 as Et, bC as xd, bD as Hn, bE as Ka, bF as dl, bG as kd, bH as ri, bI as mn, bJ as Qt, bK as pn, bL as Xt, bM as gn, bN as tt, bO as ji, bP as Ft, bQ as Za, bR as Sd, bS as Pt, bT as Cd, bU as It, bV as hn, bW as io, t as pt, bX as Td, bY as Od, bZ as Md, b_ as Oo, b$ as Ye, c0 as Ya, c1 as Dd, c2 as hl, c3 as Gi, c4 as De, A as fl, c5 as Lo, c6 as xt, c7 as _o, c8 as Ed, c9 as ko, ca as Id, cb as $d, cc as ml, cd as Nd, ce as cr, cf as _n, cg as Xa, ch as oi, ci as bn, cj as Qa, ck as Ja, cl as es, cm as Pd, cn as ts, co as ns, cp as ii, cq as Ad, cr as Fd, cs as Rd, ct as pl, cu as Ld, cv as rs, cw as _d, cx as qd, C as zd, cy as gl, cz as Wd, cA as Jr, cB as eo, cC as Vd, cD as Hd, cE as Ud, cF as qo, aC as Bd, cG as yl, aV as Di, cH as vl, bj as jd, v as ai, b9 as Gd, bg as Kd, cI as Zd, bd as Yd, p as bl, r as os, V as Xd, a$ as Ki, ba as Qd, cJ as Jd, B as wl, b2 as xl, aQ as kl, bb as eh, aY as th, b1 as zo, cK as nh, cL as rh, cM as Mo, cN as Sl, cO as oh, aS as ih, aa as is, cP as ah, ab as sh, cQ as lh, cR as ch, cS as uh, cT as as, cU as Re } from "./useCompiledDocument-Bc0HuUtz.es.js";
6
- import { cV as Zy, cW as Yy, cX as Xy, o as Qy, cY as Jy, cZ as ev, c_ as tv, c$ as nv, d0 as rv, d1 as ov, d2 as iv, d3 as av, U as sv, d as lv, b7 as cv, g as uv, z as dv, aE as hv, d4 as fv, d5 as mv, d6 as pv, d7 as gv, av as yv, d8 as vv, m as bv, d9 as wv, K as xv, e as kv, b4 as Sv, da as Cv, db as Tv, b as Ov, ak as Mv, aD as Dv, dc as Ev, dd as Iv, de as $v, df as Nv, dg as Pv, dh as Av } from "./useCompiledDocument-Bc0HuUtz.es.js";
7
- import { bi as Ae, bh as vr, bn as wt, m as ss, d as Cl, bo as Zi, a2 as Dt, ap as wo, a1 as dh, bp as Tl, bq as Ol, br as hh, bs as Ml, bt as fh, bu as mh, bv as qn } from "./ServerProvider-DdGjhDhY.es.js";
8
- import { bw as Rv, bm as Lv, aV as _v, bx as qv, by as zv, bz as Wv, bA as Vv, bB as Hv, bk as Uv } from "./ServerProvider-DdGjhDhY.es.js";
5
+ import { n as _e, bk as Bn, bl as Ar, bm as td, bn as Ga, bo as nd, bp as rd, bq as od, br as id, bs as il, bt as Wi, bu as Vi, al as Qr, bv as Hi, aw as ad, aG as Ui, bw as al, bx as sd, by as Fo, aF as sl, bz as ld, ar as cd, aH as ud, au as Mi, J as dd, aN as hd, ac as fd, G as md, bA as pd, aJ as ll, aL as gd, aM as yd, aK as vd, a4 as bd, P as wd, ag as cl, aO as Bi, ae as ul, a1 as Ro, $ as pr, aB as dt, bB as We, aI as At, S as oo, b6 as Et, bC as xd, bD as Hn, bE as Ka, bF as dl, bG as kd, bH as ri, bI as mn, bJ as Qt, bK as pn, bL as Xt, bM as gn, bN as tt, bO as ji, bP as Ft, bQ as Za, bR as Sd, bS as Pt, bT as Cd, bU as It, bV as hn, bW as io, t as pt, bX as Td, bY as Od, bZ as Md, b_ as Oo, b$ as Ye, c0 as Ya, c1 as Dd, c2 as hl, c3 as Gi, c4 as De, A as fl, c5 as Lo, c6 as xt, c7 as _o, c8 as Ed, c9 as ko, ca as Id, cb as $d, cc as ml, cd as Nd, ce as cr, cf as _n, cg as Xa, ch as oi, ci as bn, cj as Qa, ck as Ja, cl as es, cm as Pd, cn as ts, co as ns, cp as ii, cq as Ad, cr as Fd, cs as Rd, ct as pl, cu as Ld, cv as rs, cw as _d, cx as qd, C as zd, cy as gl, cz as Wd, cA as Jr, cB as eo, cC as Vd, cD as Hd, cE as Ud, cF as qo, aC as Bd, cG as yl, aV as Di, cH as vl, bj as jd, v as ai, b9 as Gd, bg as Kd, cI as Zd, bd as Yd, p as bl, r as os, V as Xd, a$ as Ki, ba as Qd, cJ as Jd, B as wl, b2 as xl, aQ as kl, bb as eh, aY as th, b1 as zo, cK as nh, cL as rh, cM as Mo, cN as Sl, cO as oh, aS as ih, aa as is, cP as ah, ab as sh, cQ as lh, cR as ch, cS as uh, cT as as, cU as Re } from "./useCompiledDocument-CXMPtJkJ.es.js";
6
+ import { cV as Zy, cW as Yy, cX as Xy, o as Qy, cY as Jy, cZ as ev, c_ as tv, c$ as nv, d0 as rv, d1 as ov, d2 as iv, d3 as av, U as sv, d as lv, b7 as cv, g as uv, z as dv, aE as hv, d4 as fv, d5 as mv, d6 as pv, d7 as gv, av as yv, d8 as vv, m as bv, d9 as wv, K as xv, e as kv, b4 as Sv, da as Cv, db as Tv, b as Ov, ak as Mv, aD as Dv, dc as Ev, dd as Iv, de as $v, df as Nv, dg as Pv, dh as Av } from "./useCompiledDocument-CXMPtJkJ.es.js";
7
+ import { bi as Ae, bh as vr, bn as wt, m as ss, d as Cl, bo as Zi, a2 as Dt, ap as wo, a1 as dh, bp as Tl, bq as Ol, br as hh, bs as Ml, bt as fh, bu as mh, bv as qn } from "./ServerProvider-DBw-thY0.es.js";
8
+ import { bw as Rv, bm as Lv, aV as _v, bx as qv, by as zv, bz as Wv, bA as Vv, bB as Hv, bk as Uv } from "./ServerProvider-DBw-thY0.es.js";
9
9
  import { useQueryClient as jn, useQuery as ph, useMutation as si } from "@tanstack/react-query";
10
10
  import { createBox as gh, createStack as yh, Stack as vh, Box as Dl } from "@mui/system";
11
11
  import { Delete as Wo, Edit as Yi, MoreVert as Vo } from "@mui/icons-material";
12
12
  import { i as bh, n as wh } from "./text-entry-YKJZbRPo.es.js";
13
- import { D as jv, R as Gv, b as Kv, a as Zv, d as Yv, m as Xv, r as Qv } from "./RenderedResult-r3dg2xOJ.es.js";
13
+ import { D as jv, R as Gv, b as Kv, a as Zv, d as Yv, m as Xv, r as Qv } from "./RenderedResult-D8bCgThO.es.js";
14
14
  import { useNavigate as El, useSearchParams as xh, useLocation as kh } from "react-router-dom";
15
15
  const Sh = _e(/* @__PURE__ */ r("path", {
16
16
  d: "M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"
@@ -1,6 +1,6 @@
1
1
  import { jsx as S, jsxs as re, Fragment as Bt } from "react/jsx-runtime";
2
2
  import { Box as be, Dialog as Td, DialogTitle as Rd, IconButton as Xn, DialogContent as Id, Typography as Ge, Stack as wt, DialogActions as $d, Button as st, Tooltip as wn, TextField as Vn, InputAdornment as zl, Alert as Ed, Autocomplete as Od, CircularProgress as _l, FormControl as Gi, Slider as Ad, FormHelperText as qi, FormControlLabel as Fd, Checkbox as Ld, Paper as ei, MenuItem as An, ButtonBase as Wl, Popover as Nd, LinearProgress as Bd } from "@mui/material";
3
- import { bh as Ke, bm as Qn, bn as Vd, bi as Zn, bg as Hl, bC as zd } from "./ServerProvider-DdGjhDhY.es.js";
3
+ import { bh as Ke, bm as Qn, bn as Vd, bi as Zn, bg as Hl, bC as zd } from "./ServerProvider-DBw-thY0.es.js";
4
4
  import * as x from "react";
5
5
  import xt, { useState as Oe, useEffect as He, useRef as Ye, useId as Ul, useMemo as Ve, useCallback as et, createContext as Ao, useContext as Jn, isValidElement as lo, cloneElement as co, Children as _d, Suspense as Wd, lazy as Hd } from "react";
6
6
  import { useQueries as Yl, QueryClientContext as Ud, useQuery as Yd, useMutation as jd, keepPreviousData as Gd } from "@tanstack/react-query";
@@ -23414,7 +23414,7 @@ function lk(e) {
23414
23414
  `)
23415
23415
  };
23416
23416
  }
23417
- const ck = Hd(() => import("./RenderedResult-r3dg2xOJ.es.js").then((e) => e.c));
23417
+ const ck = Hd(() => import("./RenderedResult-D8bCgThO.es.js").then((e) => e.c));
23418
23418
  function uk({
23419
23419
  result: e,
23420
23420
  maxHeight: t,